diff --git a/Documents/Pack/V1.0/Source/Classes/x-saherelm.base.class.mq5 b/Documents/Pack/V1.0/Source/Classes/x-saherelm.base.class.mq5 deleted file mode 100644 index 8425c50e..00000000 --- a/Documents/Pack/V1.0/Source/Classes/x-saherelm.base.class.mq5 +++ /dev/null @@ -1,79 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Class Library -// -------------------------------------- -// Name: XBaseClass -// Description: provides all based classes for use ... -// -// -// Maintainer: -// ------------ -// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) -// -////////////////////////////////////////////////////// -// -// Global Properties ... -#property library -#property copyright "Copyright 2023, SaherElm IT Center" -#property link "https://www.saherelm.ir" -#property version "1.00" -#property strict - -// -#include "../Libraries/x-saherelm.common.lib.mq5" - -// -// XBase Class ... -class XSCBase -{ - // - // Public ... -public: - // - // Protected ... - - // - // Represent Basic Unique Tag ... - virtual string GetTag(); - - // - // Retrieve Class Token ... - virtual string GetToken(); - -protected: - // - // Private ... -private: -}; - -// -template -string GenerateSpecifiedCommonSummary( - T &mItem, - string separator = "\n", - bool includeScores = true, - bool setLabel = false // -) -{ - // - string result = NULL; - - // - result = - // - (!setLabel - ? "" - : "Commons:" + separator) + - "---------------" + separator + - "Symbol: " + mItem.symbol + separator + - "Period: " + ToString(mItem.period) + separator + - "Time: " + ToString(mItem.time) + separator + - "" - // - ; - - // - return result; -} - -// diff --git a/Documents/Pack/V1.0/Source/Classes/x-saherelm.x121.setup.class.mq5 b/Documents/Pack/V1.0/Source/Classes/x-saherelm.x121.setup.class.mq5 deleted file mode 100644 index b704aa34..00000000 --- a/Documents/Pack/V1.0/Source/Classes/x-saherelm.x121.setup.class.mq5 +++ /dev/null @@ -1,4155 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Class Library -// ---------------------------------------------- -// Name: XSCX121Setup -// Description: provides implementation of X121 -// Setup ... -// -// -// 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 "../Libraries/x-saherelm.xtrade.lib.mq5" -#include "../Classes/x-saherelm.xalert.class.mq5" - -// -#include "../Helpers/x-saherelm.xmc.helper.mq5" -#include "../Helpers/x-saherelm.xpv.helper.mq5" -#include "../Helpers/x-saherelm.xtd.helper.mq5" -#include "../Helpers/x-saherelm.xhk.helper.mq5" -#include "../Helpers/x-saherelm.xsln.helper.mq5" -#include "../Helpers/x-saherelm.xstr.helper.mq5" -#include "../Helpers/x-saherelm.xche.helper.mq5" -#include "../Helpers/x-saherelm.xich.helper.mq5" -#include "../Helpers/x-saherelm.xmrb.helper.mq5" -#include "../Helpers/x-saherelm.xosc.helper.mq5" -#include "../Helpers/x-saherelm.xvlm.helper.mq5" -#include "../Helpers/x-saherelm.xhtd.helper.mq5" -#include "../Helpers/x-saherelm.xatsl.helper.mq5" -#include "../Helpers/x-saherelm.xdmnt.helper.mq5" -#include "../Helpers/x-saherelm.xasct.helper.mq5" -#include "../Helpers/x-saherelm.xsslc.helper.mq5" -#include "../Helpers/x-saherelm.xhull.helper.mq5" -#include "../Helpers/x-saherelm.xadxtd.helper.mq5" - -// -// Definitions ... - -// -enum ENUM_X121_SIGNAL_PROVIDER -{ - // - PROVIDER_UNKNOWN = 0, - PROVIDER_XMC = 1, - PROVIDER_XSARD = 2, - PROVIDER_XADXTD = 3, - PROVIDER_XSTR = 4, - PROVIDER_XCHE = 5, - PROVIDER_XTD = 6, - PROVIDER_XSI = 7, - PROVIDER_XCI = 8, - PROVIDER_XMCD = 9, - PROVIDER_XICH = 10, - PROVIDER_XHK = 11, - PROVIDER_XSMHK = 12, - PROVIDER_XMRB = 13, - PROVIDER_XSSLC = 14, - PROVIDER_XHULL = 15, - PROVIDER_XASCT = 16, - PROVIDER_XVLM = 17, - PROVIDER_XPVF = 18, - PROVIDER_XPVSAR = 19, - PROVIDER_XHTSRD = 20, - PROVIDER_XATSL = 21, - PROVIDER_XHTD = 22, - PROVIDER_XSLN = 23 -}; - -// -string ToString(ENUM_X121_SIGNAL_PROVIDER value) -{ - // - string result = NULL; - - // - string vStr = EnumToString(value); - if (!IsValid(vStr)) - { - return result; - } - - // - string parts[]; - int partsCount = SplitContent( - parts, - vStr, - "_" - // - ); - if (partsCount <= 0) - { - return result; - } - - // - bool hasLastPart = GetLastItem( - result, - parts - // - ); - if (!hasLastPart) - { - return result; - } - - // - return result; -} - -// -ENUM_X121_SIGNAL_PROVIDER FromString(string value) -{ - // - ENUM_X121_SIGNAL_PROVIDER result = PROVIDER_UNKNOWN; - - // - if (!IsValid(value)) - { - return result; - } - - // - if (Contains(value, (EnumToString(PROVIDER_XMC)))) - { - result = PROVIDER_XMC; - } - else if (Contains(value, (EnumToString(PROVIDER_XSARD)))) - { - result = PROVIDER_XSARD; - } - else if (Contains(value, (EnumToString(PROVIDER_XADXTD)))) - { - result = PROVIDER_XADXTD; - } - else if (Contains(value, (EnumToString(PROVIDER_XSTR)))) - { - result = PROVIDER_XSTR; - } - else if (Contains(value, (EnumToString(PROVIDER_XCHE)))) - { - result = PROVIDER_XCHE; - } - else if (Contains(value, (EnumToString(PROVIDER_XTD)))) - { - result = PROVIDER_XTD; - } - else if (Contains(value, (EnumToString(PROVIDER_XSI)))) - { - result = PROVIDER_XSI; - } - else if (Contains(value, (EnumToString(PROVIDER_XCI)))) - { - result = PROVIDER_XCI; - } - else if (Contains(value, (EnumToString(PROVIDER_XMCD)))) - { - result = PROVIDER_XMCD; - } - else if (Contains(value, (EnumToString(PROVIDER_XICH)))) - { - result = PROVIDER_XICH; - } - else if (Contains(value, (EnumToString(PROVIDER_XHK)))) - { - result = PROVIDER_XHK; - } - else if (Contains(value, (EnumToString(PROVIDER_XSMHK)))) - { - result = PROVIDER_XSMHK; - } - else if (Contains(value, (EnumToString(PROVIDER_XMRB)))) - { - result = PROVIDER_XMRB; - } - else if (Contains(value, (EnumToString(PROVIDER_XSSLC)))) - { - result = PROVIDER_XSSLC; - } - else if (Contains(value, (EnumToString(PROVIDER_XHULL)))) - { - result = PROVIDER_XHULL; - } - else if (Contains(value, (EnumToString(PROVIDER_XASCT)))) - { - result = PROVIDER_XASCT; - } - else if (Contains(value, (EnumToString(PROVIDER_XVLM)))) - { - result = PROVIDER_XVLM; - } - else if (Contains(value, (EnumToString(PROVIDER_XPVF)))) - { - result = PROVIDER_XPVF; - } - else if (Contains(value, (EnumToString(PROVIDER_XPVSAR)))) - { - result = PROVIDER_XPVSAR; - } - else if (Contains(value, (EnumToString(PROVIDER_XHTSRD)))) - { - result = PROVIDER_XHTSRD; - } - - // - return result; -} - -// -// Inputs ... -struct X121SetupInputs -{ - // - // Commons ... - string symbol; // Symbol - ENUM_TIMEFRAMES period; // Time Frame - - // - // Helpers Inputs ... - XMCInputs mcInputs; // XMC Inputs - XPVInputs pvInputs; // XPV Inputs - XTDInputs tdInputs; // XTD Inputs - XHKInputs hkInputs; // XHK Inputs - XHTDInputs htdInputs; // XHTD Inputs - XCHEInputs cheInputs; // XCHE Inputs - XICHInputs ichInputs; // XICH Inputs - XSTRInputs strInputs; // XSTR Inputs - XMRBInputs mrbInputs; // XMRB Inputs - XOSCInputs oscInputs; // XOSC Inputs - XVLMInputs vlmInputs; // XVLM Inputs - XSLNInputs slnInputs; // XSLN Inputs - XATSLInputs atslInputs; // XATSL Inputs - XDMNTInputs dmntInputs; // XDMNT Inputs - XASCTInputs asctInputs; // XASCT Inputs - XSSLCInputs sslcInputs; // XSSLC Inputs - XHULLInputs hullInputs; // XHULL Inputs - XADXTDInputs adxtdInputs; // XADXTD Inputs - - // - // Constructor ... - void X121SetupInputs() - { - Clean(); - } - - // - bool Init() - { - // - Default(); - - // - bool result = IsValid(); - - // - return result; - } - bool Init( - string _symbol, // Symbol - ENUM_TIMEFRAMES _period, // Time Frame - XMCInputs &_mcInputs, // XMC Inputs - XPVInputs &_pvInputs, // XPV Inputs - XTDInputs &_tdInputs, // XTD Inputs - XHKInputs &_hkInputs, // XHK Inputs - XHTDInputs &_htdInputs, // XHTD Inputs - XCHEInputs &_cheInputs, // XCHE Inputs - XICHInputs &_ichInputs, // XICH Inputs - XSTRInputs &_strInputs, // XSTR Inputs - XMRBInputs &_mrbInputs, // XMRB Inputs - XOSCInputs &_oscInputs, // XOSC Inputs - XVLMInputs &_vlmInputs, // XVLM Inputs - XSLNInputs &_slnInputs, // XSLN Inputs - XATSLInputs &_atslInputs, // XATSL Inputs - XDMNTInputs &_dmntInputs, // XDMNT Inputs - XASCTInputs &_asctInputs, // XASCT Inputs - XSSLCInputs &_sslcInputs, // XSSLC Inputs - XHULLInputs &_hullInputs, // XHULL Inputs - XADXTDInputs &_adxtdInputs // XADXTD Inputs - ) - { - // - this.symbol = _symbol; - this.period = _period; - - // - // Helpers Inputs ... - this.mcInputs = _mcInputs; - this.pvInputs = _pvInputs; - this.tdInputs = _tdInputs; - this.hkInputs = _hkInputs; - this.htdInputs = _htdInputs; - this.cheInputs = _cheInputs; - this.ichInputs = _ichInputs; - this.strInputs = _strInputs; - this.mrbInputs = _mrbInputs; - this.oscInputs = _oscInputs; - this.vlmInputs = _vlmInputs; - this.atslInputs = _atslInputs; - this.dmntInputs = _dmntInputs; - this.asctInputs = _asctInputs; - this.sslcInputs = _sslcInputs; - this.hullInputs = _hullInputs; - this.adxtdInputs = _adxtdInputs; - - // - bool result = IsValid(); - - // - return result; - } - - // - // Tools ... - - // - // Cleanup ... - void Clean() - { - // - symbol = NULL; - period = NULL; - - // - mcInputs.Clean(); - pvInputs.Clean(); - tdInputs.Clean(); - hkInputs.Clean(); - cheInputs.Clean(); - ichInputs.Clean(); - strInputs.Clean(); - mrbInputs.Clean(); - oscInputs.Clean(); - vlmInputs.Clean(); - slnInputs.Clean(); - htdInputs.Clean(); - asctInputs.Clean(); - sslcInputs.Clean(); - hullInputs.Clean(); - atslInputs.Clean(); - dmntInputs.Clean(); - adxtdInputs.Clean(); - } - - // - // Default ... - void Default() - { - // - mcInputs.Default(); - pvInputs.Default(); - tdInputs.Default(); - hkInputs.Default(); - cheInputs.Default(); - ichInputs.Default(); - strInputs.Default(); - mrbInputs.Default(); - oscInputs.Default(); - vlmInputs.Default(); - slnInputs.Default(); - htdInputs.Default(); - asctInputs.Default(); - sslcInputs.Default(); - hullInputs.Default(); - atslInputs.Default(); - dmntInputs.Default(); - adxtdInputs.Default(); - } - - // - // Validate ... - bool IsValid() - { - // - bool result = false; - - // - result = - // - IsValid(symbol) && - IsValid(period) - // - ; - if (!result) - { - return result; - } - - // - result = tdInputs.IsValid(); - if (!result) - { - return result; - } - - // - result = slnInputs.IsValid(); - if (!result) - { - return result; - } - - // - result = pvInputs.IsValid(); - if (!result) - { - return result; - } - - // - result = hkInputs.IsValid(); - if (!result) - { - return result; - } - - // - result = cheInputs.IsValid(); - if (!result) - { - return result; - } - - // - result = ichInputs.IsValid(); - if (!result) - { - return result; - } - - // - result = strInputs.IsValid(); - if (!result) - { - return result; - } - - // - result = mrbInputs.IsValid(); - if (!result) - { - return result; - } - - // - result = oscInputs.IsValid(); - if (!result) - { - return result; - } - - // - result = vlmInputs.IsValid(); - if (!result) - { - return result; - } - - // - result = mcInputs.IsValid(); - if (!result) - { - return result; - } - - // - result = asctInputs.IsValid(); - if (!result) - { - return result; - } - - // - result = sslcInputs.IsValid(); - if (!result) - { - return result; - } - - // - result = hullInputs.IsValid(); - if (!result) - { - return result; - } - - // - result = adxtdInputs.IsValid(); - if (!result) - { - return result; - } - - // - result = htdInputs.IsValid(); - if (!result) - { - return result; - } - - // - result = atslInputs.IsValid(); - if (!result) - { - return result; - } - - // - result = dmntInputs.IsValid(); - if (!result) - { - return result; - } - - // - return result; - } -}; - -// -// Conditions ... -struct X121SetupConditions -{ - // - // Common ... - string symbol; - ENUM_TIMEFRAMES period; - datetime time; - - // - // Conditions ... - XMCConditions mcConditions; - XPVConditions pvConditions; - XTDConditions tdConditions; - XHKConditions hkConditions; - XCHEConditions cheConditions; - XICHConditions ichConditions; - XSTRConditions strConditions; - XMRBConditions mrbConditions; - XVLMConditions vlmConditions; - XHTDConditions htdConditions; - XSLNConditions slnConditions; - XATSLConditions atslConditions; - XASCTConditions asctConditions; - XSSLCConditions sslcConditions; - XHULLConditions hullConditions; - XDMNTConditions dmntConditions; - XADXTDConditions adxtdConditions; - - // - // Oscillators ... - double cci[]; - double rsi[]; - double macd[]; - double macdSignal[]; - - // - // Tools ... - - // - // Cleanup ... - void Clean() - { - // - time = NULL; - symbol = NULL; - period = NULL; - - // - Clean(cci); - Clean(rsi); - Clean(macd); - Clean(macdSignal); - - // - mcConditions.Clean(); - tdConditions.Clean(); - hkConditions.Clean(); - cheConditions.Clean(); - ichConditions.Clean(); - strConditions.Clean(); - mrbConditions.Clean(); - vlmConditions.Clean(); - slnConditions.Clean(); - htdConditions.Clean(); - atslConditions.Clean(); - asctConditions.Clean(); - sslcConditions.Clean(); - hullConditions.Clean(); - dmntConditions.Clean(); - adxtdConditions.Clean(); - } - - // - void GenerateScore( - double &bullishScore, - double &bearishScore // - ) - { - // - bullishScore = 0; - bearishScore = 0; - - // - double tempBullishScore = 0; - double tempBearishScore = 0; - - // - mcConditions.GenerateScore( - tempBullishScore, - tempBearishScore // - ); - bullishScore += tempBullishScore; - bearishScore += tempBearishScore; - - // - pvConditions.GenerateScore( - tempBullishScore, - tempBearishScore // - ); - bullishScore += tempBullishScore; - bearishScore += tempBearishScore; - - // - slnConditions.GenerateScore( - tempBullishScore, - tempBearishScore // - ); - bullishScore += tempBullishScore; - bearishScore += tempBearishScore; - - // - adxtdConditions.GenerateScore( - tempBullishScore, - tempBearishScore // - ); - bullishScore += tempBullishScore; - bearishScore += tempBearishScore; - - // - strConditions.GenerateScore( - tempBullishScore, - tempBearishScore // - ); - bullishScore += tempBullishScore; - bearishScore += tempBearishScore; - - // - cheConditions.GenerateScore( - tempBullishScore, - tempBearishScore // - ); - bullishScore += tempBullishScore; - bearishScore += tempBearishScore; - - // - asctConditions.GenerateScore( - tempBullishScore, - tempBearishScore // - ); - bullishScore += tempBullishScore; - bearishScore += tempBearishScore; - - // - tdConditions.GenerateScore( - tempBullishScore, - tempBearishScore // - ); - bullishScore += tempBullishScore; - bearishScore += tempBearishScore; - - // - ichConditions.GenerateScore( - tempBullishScore, - tempBearishScore // - ); - bullishScore += tempBullishScore; - bearishScore += tempBearishScore; - - // - hkConditions.GenerateScore( - tempBullishScore, - tempBearishScore // - ); - bullishScore += tempBullishScore; - bearishScore += tempBearishScore; - - // - mrbConditions.GenerateScore( - tempBullishScore, - tempBearishScore // - ); - bullishScore += tempBullishScore; - bearishScore += tempBearishScore; - - // - vlmConditions.GenerateScore( - tempBullishScore, - tempBearishScore // - ); - bullishScore += tempBullishScore; - bearishScore += tempBearishScore; - - // - sslcConditions.GenerateScore( - tempBullishScore, - tempBearishScore // - ); - bullishScore += tempBullishScore; - bearishScore += tempBearishScore; - - // - hullConditions.GenerateScore( - tempBullishScore, - tempBearishScore // - ); - bullishScore += tempBullishScore; - bearishScore += tempBearishScore; - - // - htdConditions.GenerateScore( - tempBullishScore, - tempBearishScore // - ); - bullishScore += tempBullishScore; - bearishScore += tempBearishScore; - - // - atslConditions.GenerateScore( - tempBullishScore, - tempBearishScore // - ); - bullishScore += tempBullishScore; - bearishScore += tempBearishScore; - - // - dmntConditions.GenerateScore( - tempBullishScore, - tempBearishScore // - ); - bullishScore += tempBullishScore; - bearishScore += tempBearishScore; - - // - } - - // - 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 pvSummary = pvConditions.GenerateSummary(false, true, false, ignoreFalseConditions); - string mcSummary = mcConditions.GenerateSummary(false, true, false, ignoreFalseConditions); - string tdSummary = tdConditions.GenerateSummary(false, true, false, ignoreFalseConditions); - string hkSummary = hkConditions.GenerateSummary(false, true, false, ignoreFalseConditions); - string strSummary = strConditions.GenerateSummary(false, true, false, ignoreFalseConditions); - string cheSummary = cheConditions.GenerateSummary(false, true, false, ignoreFalseConditions); - string ichSummary = ichConditions.GenerateSummary(false, true, false, ignoreFalseConditions); - string mrbSummary = mrbConditions.GenerateSummary(false, true, false, ignoreFalseConditions); - string vlmSummary = vlmConditions.GenerateSummary(false, true, false, ignoreFalseConditions); - string slnSummary = slnConditions.GenerateSummary(false, true, false, ignoreFalseConditions); - string htdSummary = htdConditions.GenerateSummary(false, true, false, ignoreFalseConditions); - string atsSummary = atslConditions.GenerateSummary(false, true, false, ignoreFalseConditions); - string asctSummary = asctConditions.GenerateSummary(false, true, false, ignoreFalseConditions); - string sslcSummary = sslcConditions.GenerateSummary(false, true, false, ignoreFalseConditions); - string hullSummary = hullConditions.GenerateSummary(false, true, false, ignoreFalseConditions); - string dmntSummary = dmntConditions.GenerateSummary(false, true, false, ignoreFalseConditions); - string adxtdSummary = adxtdConditions.GenerateSummary(false, true, false, ignoreFalseConditions); - - // - string conditionsStr = - // - pvSummary + separator + - mcSummary + separator + - tdSummary + separator + - hkSummary + separator + - ichSummary + separator + - mrbSummary + separator + - vlmSummary + separator + - slnSummary + separator + - strSummary + separator + - cheSummary + separator + - asctSummary + separator + - sslcSummary + separator + - hullSummary + separator + - adxtdSummary + separator + - htdSummary + separator + - atsSummary + separator + - dmntSummary + separator + - "" - // - ; - - // - result = - // - "[" + GetTag() + "]" + separator + - (onlyConditions - ? "" - : commonStr) + - (!includeScores - ? "" - : scoresStr) + - " " + separator + - (onlyCommons - ? "" - : conditionsStr) + - "" - // - ; - - // - return result; - } - - // - // Add Combine Conditions ... - - // - bool IsTrendBullish() - { - // - bool result = false; - - // - result = - // - (strConditions.isTrendSwitchedToBullish && - slnConditions.isBullish && - htdConditions.isBullish && - atslConditions.isBullish && - cheConditions.isStrongBullish) - // - || - // - (slnConditions.isSwitchedToBullish && - strConditions.isTrendBullish && - htdConditions.isBullish && - atslConditions.isBullish && - cheConditions.isStrongBullish) - // - || - // - (htdConditions.isSwitchedToBullish && - strConditions.isTrendBullish && - slnConditions.isBullish && - atslConditions.isBullish && - cheConditions.isStrongBullish) - // - || - // - (atslConditions.isSwitchedToBullish && - strConditions.isTrendBullish && - htdConditions.isBullish && - slnConditions.isBullish && - cheConditions.isStrongBullish) - // - || - // - (cheConditions.isStrongSwitchedToBullish && - strConditions.isTrendBullish && - htdConditions.isBullish && - slnConditions.isBullish && - atslConditions.isBullish) - // - ; - - // - return result; - } - - // - bool IsTrendBearish() - { - // - bool result = false; - - // - result = - // - (strConditions.isTrendSwitchedToBearish && - slnConditions.isBearish && - htdConditions.isBearish && - atslConditions.isBearish && - cheConditions.isStrongBearish) - // - || - // - (slnConditions.isSwitchedToBearish && - strConditions.isTrendBearish && - htdConditions.isBearish && - atslConditions.isBearish && - cheConditions.isStrongBearish) - // - || - // - (htdConditions.isSwitchedToBearish && - strConditions.isTrendBearish && - slnConditions.isBearish && - atslConditions.isBearish && - cheConditions.isStrongBearish) - // - || - // - (atslConditions.isSwitchedToBearish && - strConditions.isTrendBearish && - htdConditions.isBearish && - slnConditions.isBearish && - cheConditions.isStrongBearish) - // - || - // - (cheConditions.isStrongSwitchedToBearish && - strConditions.isTrendBearish && - htdConditions.isBearish && - slnConditions.isBearish && - atslConditions.isBearish) - // - ; - - // - return result; - } - - // - string GetTag() - { - return "X121Setup"; - } -}; - -// -// Condition Parser ... -struct X121SignalGenerator -{ - // - string version; - - // - // Constructor ... - void X121SignalGenerator() - { - } - - // - // Retrieve OSC Based Long Verifications ... - bool IsOSCLongVerified( - X121SetupConditions &conditions // Conditions - ) - { - // - bool result = false; - - // - int zIndex = 0; - int cIndex = zIndex + 1; - int pIndex = cIndex + 1; - - // - result = - // - // CCI ... - conditions.cci[cIndex] < 96 && - conditions.cci[cIndex] > conditions.cci[pIndex] - // - && - // - // RSI ... - conditions.rsi[cIndex] < 70 && - conditions.rsi[cIndex] > conditions.rsi[pIndex] - // - && - // - // MACD ... - conditions.macd[cIndex] > 0 && - conditions.macdSignal[cIndex] > 0 && - conditions.macd[cIndex] > conditions.macdSignal[cIndex] - // - ; - - // - return result; - } - - // - // Retrieve OSC Based Short Verifications ... - bool IsOSCShortVerified( - X121SetupConditions &conditions // Conditions - ) - { - // - bool result = false; - - // - int zIndex = 0; - int cIndex = zIndex + 1; - int pIndex = cIndex + 1; - - // - result = - // - // CCI ... - conditions.cci[cIndex] > -96 && - conditions.cci[cIndex] < conditions.cci[pIndex] - // - && - // - // RSI ... - conditions.rsi[cIndex] > 30 && - conditions.rsi[cIndex] < conditions.rsi[pIndex] - // - && - // - // MACD ... - conditions.macd[cIndex] < 0 && - conditions.macdSignal[cIndex] < 0 && - conditions.macd[cIndex] < conditions.macdSignal[cIndex] - // - ; - - // - return result; - } - - // - // Check Market Conditions for Long Signals ... - bool HasLongConditions( - X121SetupConditions &conditions, // Conditions - int &pusher, // Pushers - string &provider, // Provider - double &tp, // Provided TP - double &sl // Provided SL - ) - { - // - bool result = false; - - // - tp = 0; - sl = 0; - pusher = 0; - - // - bool isOSCShortVerified = IsOSCShortVerified(conditions); - - // - int zIndex = 0; - int cIndex = zIndex + 1; - int pIndex = cIndex + 1; - - // - double bullishScore = 0; - double bearishScore = 0; - conditions.GenerateScore( - bullishScore, - bearishScore // - ); - - // - // XMC ... - bool long1 = - // - // Starting Conditions ... - conditions.mcConditions.isSwitchedToBullish && - // - // Verifications ... - conditions.mcConditions.isSARBullish && - conditions.adxtdConditions.isStrong && - conditions.adxtdConditions.isBullish && - conditions.strConditions.isTrendBullish && - conditions.cheConditions.isStrongBullish && - conditions.tdConditions.isBullish && - conditions.hkConditions.isHKBullish && - conditions.hkConditions.isSMHKBullish && - conditions.mrbConditions.isFastOverSlow && - conditions.sslcConditions.isBullish && - conditions.hullConditions.isBullish && - conditions.vlmConditions.isVolumeBullish && - conditions.atslConditions.isBullish && - conditions.htdConditions.isBullish && - conditions.slnConditions.isBullish - // - ; - if (long1) - { - // - pusher++; - provider = ToString(PROVIDER_XMC); - } - - // - // XSARD ... - bool long2 = - // - // Starting Conditions ... - conditions.mcConditions.isSARSwitchedToBullish && - // - // Verifications ... - conditions.mcConditions.isBullish && - conditions.adxtdConditions.isStrong && - conditions.adxtdConditions.isBullish && - conditions.strConditions.isTrendBullish && - conditions.cheConditions.isStrongBullish && - conditions.tdConditions.isBullish && - conditions.hkConditions.isHKBullish && - conditions.hkConditions.isSMHKBullish && - conditions.mrbConditions.isFastOverSlow && - conditions.sslcConditions.isBullish && - conditions.hullConditions.isBullish && - conditions.vlmConditions.isVolumeBullish && - conditions.atslConditions.isBullish && - conditions.htdConditions.isBullish && - conditions.slnConditions.isBullish - // - ; - if (long2) - { - // - pusher++; - provider = ToString(PROVIDER_XSARD); - } - - // - // XADXTD ... - bool long3 = - // - // Starting Conditions ... - conditions.adxtdConditions.isStrongSwitchedToBullish && - // - // Verifications ... - conditions.mcConditions.isBullish && - conditions.mcConditions.isSARBullish && - conditions.strConditions.isTrendBullish && - conditions.cheConditions.isStrongBullish && - conditions.tdConditions.isBullish && - conditions.hkConditions.isHKBullish && - conditions.hkConditions.isSMHKBullish && - conditions.mrbConditions.isFastOverSlow && - conditions.sslcConditions.isBullish && - conditions.hullConditions.isBullish && - conditions.vlmConditions.isVolumeBullish && - conditions.atslConditions.isBullish && - conditions.htdConditions.isBullish && - conditions.slnConditions.isBullish - // - ; - if (long3) - { - // - pusher++; - provider = ToString(PROVIDER_XADXTD); - } - - // - // XSTR ... - bool long4 = - // - // Starting Conditions ... - conditions.strConditions.isTrendSwitchedToBullish && - // - // Verifications ... - conditions.mcConditions.isBullish && - conditions.mcConditions.isSARBullish && - conditions.adxtdConditions.isStrong && - conditions.adxtdConditions.isBullish && - conditions.cheConditions.isStrongBullish && - conditions.tdConditions.isBullish && - conditions.hkConditions.isHKBullish && - conditions.hkConditions.isSMHKBullish && - conditions.mrbConditions.isFastOverSlow && - conditions.sslcConditions.isBullish && - conditions.hullConditions.isBullish && - conditions.vlmConditions.isVolumeBullish && - conditions.atslConditions.isBullish && - conditions.htdConditions.isBullish && - conditions.slnConditions.isBullish - // - ; - if (long4) - { - // - pusher++; - provider = ToString(PROVIDER_XSTR); - } - - // - // XCHE ... - bool long5 = - // - // Starting Conditions ... - conditions.cheConditions.isStrongSwitchedToBullish && - // - // Verifications ... - conditions.mcConditions.isBullish && - conditions.mcConditions.isSARBullish && - conditions.adxtdConditions.isStrong && - conditions.adxtdConditions.isBullish && - conditions.strConditions.isTrendBullish && - conditions.tdConditions.isBullish && - conditions.hkConditions.isHKBullish && - conditions.hkConditions.isSMHKBullish && - conditions.mrbConditions.isFastOverSlow && - conditions.sslcConditions.isBullish && - conditions.hullConditions.isBullish && - conditions.vlmConditions.isVolumeBullish && - conditions.atslConditions.isBullish && - conditions.htdConditions.isBullish && - conditions.slnConditions.isBullish && - conditions.atslConditions.isBullish && - conditions.htdConditions.isBullish && - conditions.slnConditions.isBullish - // - ; - if (long5) - { - // - pusher++; - provider = ToString(PROVIDER_XCHE); - } - - // - // XTD ... - bool long6 = - // - // Starting Conditions ... - conditions.tdConditions.isSwitchedToBullish && - // - // Verifications ... - conditions.mcConditions.isBullish && - conditions.mcConditions.isSARBullish && - conditions.adxtdConditions.isStrong && - conditions.adxtdConditions.isBullish && - conditions.strConditions.isTrendBullish && - conditions.cheConditions.isStrongBullish && - conditions.hkConditions.isHKBullish && - conditions.hkConditions.isSMHKBullish && - conditions.mrbConditions.isFastOverSlow && - conditions.sslcConditions.isBullish && - conditions.hullConditions.isBullish && - conditions.vlmConditions.isVolumeBullish && - conditions.atslConditions.isBullish && - conditions.htdConditions.isBullish && - conditions.slnConditions.isBullish - // - ; - if (long6) - { - // - pusher++; - provider = ToString(PROVIDER_XTD); - } - - // - // XSI ... - bool long7 = - // - // Starting Conditions ... - conditions.rsi[cIndex] > 30 && - conditions.rsi[pIndex] <= 30 && - // - // Verifications ... - conditions.tdConditions.isBullish && - conditions.mcConditions.isBullish && - conditions.mcConditions.isSARBullish && - conditions.adxtdConditions.isStrong && - conditions.adxtdConditions.isBullish && - conditions.strConditions.isTrendBullish && - conditions.cheConditions.isStrongBullish && - conditions.hkConditions.isHKBullish && - conditions.hkConditions.isSMHKBullish && - conditions.mrbConditions.isFastOverSlow && - conditions.sslcConditions.isBullish && - conditions.hullConditions.isBullish && - conditions.vlmConditions.isVolumeBullish && - conditions.atslConditions.isBullish && - conditions.htdConditions.isBullish && - conditions.slnConditions.isBullish - // - ; - if (long7) - { - // - pusher++; - provider = ToString(PROVIDER_XSI); - } - - // - // XCI ... - bool long8 = - // - // Starting Conditions ... - conditions.cci[cIndex] > -100 && - conditions.cci[pIndex] <= -100 && - // - // Verifications ... - conditions.tdConditions.isBullish && - conditions.mcConditions.isBullish && - conditions.mcConditions.isSARBullish && - conditions.adxtdConditions.isStrong && - conditions.adxtdConditions.isBullish && - conditions.strConditions.isTrendBullish && - conditions.cheConditions.isStrongBullish && - conditions.hkConditions.isHKBullish && - conditions.hkConditions.isSMHKBullish && - conditions.mrbConditions.isFastOverSlow && - conditions.sslcConditions.isBullish && - conditions.hullConditions.isBullish && - conditions.vlmConditions.isVolumeBullish && - conditions.atslConditions.isBullish && - conditions.htdConditions.isBullish && - conditions.slnConditions.isBullish - // - ; - if (long8) - { - // - pusher++; - provider = ToString(PROVIDER_XCI); - } - - // - // XMCD ... - bool long9 = - // - // Starting Conditions ... - conditions.macd[cIndex] > 0 && - conditions.macd[cIndex] > conditions.macdSignal[cIndex] && - // - // Verifications ... - conditions.tdConditions.isBullish && - conditions.mcConditions.isBullish && - conditions.mcConditions.isSARBullish && - conditions.adxtdConditions.isStrong && - conditions.adxtdConditions.isBullish && - conditions.strConditions.isTrendBullish && - conditions.cheConditions.isStrongBullish && - conditions.hkConditions.isHKBullish && - conditions.hkConditions.isSMHKBullish && - conditions.mrbConditions.isFastOverSlow && - conditions.sslcConditions.isBullish && - conditions.hullConditions.isBullish && - conditions.vlmConditions.isVolumeBullish && - conditions.atslConditions.isBullish && - conditions.htdConditions.isBullish && - conditions.slnConditions.isBullish - // - ; - if (long9) - { - // - pusher++; - provider = ToString(PROVIDER_XMCD); - } - - // - // XICH ... - bool long10 = - // - // Starting Conditions ... - conditions.ichConditions.HasLongConditions() && - // - // Verifications ... - conditions.tdConditions.isBullish && - conditions.mcConditions.isBullish && - conditions.mcConditions.isSARBullish && - conditions.adxtdConditions.isStrong && - conditions.adxtdConditions.isBullish && - conditions.strConditions.isTrendBullish && - conditions.cheConditions.isStrongBullish && - conditions.hkConditions.isHKBullish && - conditions.hkConditions.isSMHKBullish && - conditions.mrbConditions.isFastOverSlow && - conditions.sslcConditions.isBullish && - conditions.hullConditions.isBullish && - conditions.vlmConditions.isVolumeBullish && - conditions.atslConditions.isBullish && - conditions.htdConditions.isBullish && - conditions.slnConditions.isBullish - // - ; - if (long10) - { - // - pusher++; - provider = ToString(PROVIDER_XICH); - } - - // - // XHK ... - bool long11 = - // - // Starting Conditions ... - conditions.hkConditions.isHKSwitchedToBullish && - // - // Verifications ... - conditions.tdConditions.isBullish && - conditions.mcConditions.isBullish && - conditions.mcConditions.isSARBullish && - conditions.adxtdConditions.isStrong && - conditions.adxtdConditions.isBullish && - conditions.strConditions.isTrendBullish && - conditions.cheConditions.isStrongBullish && - conditions.hkConditions.isSMHKBullish && - conditions.mrbConditions.isFastOverSlow && - conditions.sslcConditions.isBullish && - conditions.hullConditions.isBullish && - conditions.vlmConditions.isVolumeBullish && - conditions.atslConditions.isBullish && - conditions.htdConditions.isBullish && - conditions.slnConditions.isBullish - // - ; - if (long11) - { - // - pusher++; - provider = ToString(PROVIDER_XHK); - } - - // - // XSMHK ... - bool long12 = - // - // Starting Conditions ... - conditions.hkConditions.isSMHKSwitchedToBullish && - // - // Verifications ... - conditions.tdConditions.isBullish && - conditions.mcConditions.isBullish && - conditions.mcConditions.isSARBullish && - conditions.adxtdConditions.isStrong && - conditions.adxtdConditions.isBullish && - conditions.strConditions.isTrendBullish && - conditions.cheConditions.isStrongBullish && - conditions.hkConditions.isHKBullish && - conditions.mrbConditions.isFastOverSlow && - conditions.sslcConditions.isBullish && - conditions.hullConditions.isBullish && - conditions.vlmConditions.isVolumeBullish && - conditions.atslConditions.isBullish && - conditions.htdConditions.isBullish && - conditions.slnConditions.isBullish - // - ; - if (long12) - { - // - pusher++; - provider = ToString(PROVIDER_XSMHK); - } - - // - // XMRB ... - bool long13 = - // - // Starting Conditions ... - conditions.mrbConditions.isFastCrossedOverSlow && - // - // Verifications ... - conditions.tdConditions.isBullish && - conditions.mcConditions.isBullish && - conditions.mcConditions.isSARBullish && - conditions.adxtdConditions.isStrong && - conditions.adxtdConditions.isBullish && - conditions.strConditions.isTrendBullish && - conditions.cheConditions.isStrongBullish && - conditions.hkConditions.isHKBullish && - conditions.hkConditions.isSMHKBullish && - conditions.sslcConditions.isBullish && - conditions.hullConditions.isBullish && - conditions.vlmConditions.isVolumeBullish && - conditions.atslConditions.isBullish && - conditions.htdConditions.isBullish && - conditions.slnConditions.isBullish - // - ; - if (long13) - { - // - pusher++; - provider = ToString(PROVIDER_XMRB); - } - - // - // XSSLC ... - bool long14 = - // - // Starting Conditions ... - conditions.sslcConditions.isSwitchedToBullish && - // - // Verifications ... - conditions.tdConditions.isBullish && - conditions.mcConditions.isBullish && - conditions.mcConditions.isSARBullish && - conditions.adxtdConditions.isStrong && - conditions.adxtdConditions.isBullish && - conditions.strConditions.isTrendBullish && - conditions.cheConditions.isStrongBullish && - conditions.hkConditions.isHKBullish && - conditions.hkConditions.isSMHKBullish && - conditions.mrbConditions.isFastOverSlow && - conditions.hullConditions.isBullish && - conditions.vlmConditions.isVolumeBullish && - conditions.atslConditions.isBullish && - conditions.htdConditions.isBullish && - conditions.slnConditions.isBullish - // - ; - if (long14) - { - // - pusher++; - provider = ToString(PROVIDER_XSSLC); - } - - // - // XHULL ... - bool long15 = - // - // Starting Conditions ... - conditions.hullConditions.isSwitchedToBullish && - // - // Verifications ... - conditions.tdConditions.isBullish && - conditions.mcConditions.isBullish && - conditions.mcConditions.isSARBullish && - conditions.adxtdConditions.isStrong && - conditions.adxtdConditions.isBullish && - conditions.strConditions.isTrendBullish && - conditions.cheConditions.isStrongBullish && - conditions.hkConditions.isHKBullish && - conditions.hkConditions.isSMHKBullish && - conditions.mrbConditions.isFastOverSlow && - conditions.sslcConditions.isBullish && - conditions.vlmConditions.isVolumeBullish && - conditions.atslConditions.isBullish && - conditions.htdConditions.isBullish && - conditions.slnConditions.isBullish - // - ; - if (long15) - { - // - pusher++; - provider = ToString(PROVIDER_XHULL); - } - - // - // XASCT ... - bool long16 = - // - // Starting Conditions ... - conditions.asctConditions.isLongSignal && - // - // Verifications ... - conditions.tdConditions.isBullish && - conditions.mcConditions.isBullish && - conditions.mcConditions.isSARBullish && - conditions.adxtdConditions.isStrong && - conditions.adxtdConditions.isBullish && - conditions.strConditions.isTrendBullish && - conditions.cheConditions.isStrongBullish && - conditions.hkConditions.isHKBullish && - conditions.hkConditions.isSMHKBullish && - conditions.mrbConditions.isFastOverSlow && - conditions.hullConditions.isBullish && - conditions.sslcConditions.isBullish && - conditions.vlmConditions.isVolumeBullish && - conditions.atslConditions.isBullish && - conditions.htdConditions.isBullish && - conditions.slnConditions.isBullish - // - ; - if (long16) - { - // - pusher++; - provider = ToString(PROVIDER_XASCT); - } - - // - // XVLM ... - bool long17 = - // - // Starting Conditions ... - conditions.vlmConditions.isVolumeChangedToBullish && - // - // Verifications ... - conditions.tdConditions.isBullish && - conditions.mcConditions.isBullish && - conditions.mcConditions.isSARBullish && - conditions.adxtdConditions.isStrong && - conditions.adxtdConditions.isBullish && - conditions.strConditions.isTrendBullish && - conditions.cheConditions.isStrongBullish && - conditions.hkConditions.isHKBullish && - conditions.hkConditions.isSMHKBullish && - conditions.mrbConditions.isFastOverSlow && - conditions.hullConditions.isBullish && - conditions.sslcConditions.isBullish && - conditions.atslConditions.isBullish && - conditions.htdConditions.isBullish && - conditions.slnConditions.isBullish - // - ; - if (long17) - { - // - pusher++; - provider = ToString(PROVIDER_XVLM); - } - - // - // XPVF ... - bool long18 = - // - // Starting Conditions ... - conditions.pvConditions.isFiboIncreased && - // - // Verifications ... - conditions.tdConditions.isBullish && - conditions.mcConditions.isBullish && - conditions.mcConditions.isSARBullish && - conditions.adxtdConditions.isStrong && - conditions.adxtdConditions.isBullish && - conditions.strConditions.isTrendBullish && - conditions.cheConditions.isStrongBullish && - conditions.hkConditions.isHKBullish && - conditions.hkConditions.isSMHKBullish && - conditions.mrbConditions.isFastOverSlow && - conditions.hullConditions.isBullish && - conditions.sslcConditions.isBullish && - conditions.vlmConditions.isVolumeBullish && - conditions.atslConditions.isBullish && - conditions.htdConditions.isBullish && - conditions.slnConditions.isBullish - // - ; - if (long18) - { - // - pusher++; - provider = ToString(PROVIDER_XPVF); - } - - // - // XPVSAR ... - bool long19 = - // - // Starting Conditions ... - conditions.mcConditions.isSARSwitchedToBullish && - conditions.pvConditions.vales[zIndex] == conditions.mcConditions.psar[zIndex] && - conditions.strConditions.isTrendBullish && - conditions.cheConditions.isStrongBullish && - conditions.atslConditions.isBullish && - conditions.htdConditions.isBullish && - conditions.slnConditions.isBullish - // - ; - if (long19) - { - // - pusher += 2; - provider = ToString(PROVIDER_XPVSAR); - } - - // - // XHTSRD ... - bool long20 = - // - // Starting Conditions ... - conditions.IsTrendBullish() && - conditions.dmntConditions.isBullish && - // - // Verifications ... - conditions.tdConditions.isBullish && - conditions.adxtdConditions.isStrong && - conditions.adxtdConditions.isBullish && - conditions.vlmConditions.isVolumeBullish && - conditions.atslConditions.isBullish && - conditions.htdConditions.isBullish && - conditions.slnConditions.isBullish - // - ; - if (long20) - { - // - pusher++; - provider = ToString(PROVIDER_XHTSRD); - } - - // - // XATSL ... - bool long21 = - // - // Starting Conditions ... - conditions.atslConditions.isSwitchedToBullish && - // - // Verifications ... - conditions.tdConditions.isBullish && - conditions.mcConditions.isBullish && - conditions.mcConditions.isSARBullish && - conditions.adxtdConditions.isStrong && - conditions.adxtdConditions.isBullish && - conditions.strConditions.isTrendBullish && - conditions.cheConditions.isStrongBullish && - conditions.hkConditions.isHKBullish && - conditions.hkConditions.isSMHKBullish && - conditions.mrbConditions.isFastOverSlow && - conditions.hullConditions.isBullish && - conditions.sslcConditions.isBullish && - conditions.vlmConditions.isVolumeBullish && - conditions.htdConditions.isBullish && - conditions.slnConditions.isBullish - // - ; - if (long21) - { - // - pusher++; - provider = ToString(PROVIDER_XATSL); - } - - // - // XHTD ... - bool long22 = - // - // Starting Conditions ... - conditions.htdConditions.isSwitchedToBullish && - // - // Verifications ... - conditions.tdConditions.isBullish && - conditions.mcConditions.isBullish && - conditions.mcConditions.isSARBullish && - conditions.adxtdConditions.isStrong && - conditions.adxtdConditions.isBullish && - conditions.strConditions.isTrendBullish && - conditions.cheConditions.isStrongBullish && - conditions.hkConditions.isHKBullish && - conditions.hkConditions.isSMHKBullish && - conditions.mrbConditions.isFastOverSlow && - conditions.hullConditions.isBullish && - conditions.sslcConditions.isBullish && - conditions.vlmConditions.isVolumeBullish && - conditions.atslConditions.isBullish && - conditions.slnConditions.isBullish - // - ; - if (long22) - { - // - pusher++; - provider = ToString(PROVIDER_XHTD); - } - - // - // XSLN ... - bool long23 = - // - // Starting Conditions ... - conditions.slnConditions.isSwitchedToBullish && - // - // Verifications ... - conditions.tdConditions.isBullish && - conditions.mcConditions.isBullish && - conditions.mcConditions.isSARBullish && - conditions.adxtdConditions.isStrong && - conditions.adxtdConditions.isBullish && - conditions.strConditions.isTrendBullish && - conditions.cheConditions.isStrongBullish && - conditions.hkConditions.isHKBullish && - conditions.hkConditions.isSMHKBullish && - conditions.mrbConditions.isFastOverSlow && - conditions.hullConditions.isBullish && - conditions.sslcConditions.isBullish && - conditions.vlmConditions.isVolumeBullish && - conditions.atslConditions.isBullish && - conditions.htdConditions.isBullish - // - ; - if (long23) - { - // - pusher++; - provider = ToString(PROVIDER_XSLN); - } - - // - result = - // - pusher >= 1 && - ( - // - long1 - // - || - // - long2 - // - || - // - long3 - // - || - // - long4 - // - || - // - long5 - // - || - // - long6 - // - || - // - long7 - // - || - // - long8 - // - || - // - long9 - // - || - // - long10 - // - || - // - long11 - // - || - // - long12 - // - || - // - long13 - // - || - // - long14 - // - || - // - long15 - // - || - // - long16 - // - || - // - long17 - // - || - // - long18 - // - || - // - long19 - // - || - // - long20 - // - || - // - long21 - // - || - // - long22 - // - || - // - long23 - // - ) - // - ; - - // - return result; - } - - // - // Check Market Conditions for Short Signals ... - bool HasShortConditions( - X121SetupConditions &conditions, // Conditions - int &pusher, // Pushers - string &provider, // Provider - double &tp, // Provided TP - double &sl // Provided SL - ) - { - // - bool result = false; - - // - tp = 0; - sl = 0; - pusher = 0; - - // - bool isOSCLongVerified = IsOSCLongVerified(conditions); - - // - int zIndex = 0; - int cIndex = zIndex + 1; - int pIndex = cIndex + 1; - - // - double bullishScore = 0; - double bearishScore = 0; - conditions.GenerateScore( - bullishScore, - bearishScore // - ); - - // - // XMC ... - bool short1 = - // - // Starting Conditions ... - conditions.mcConditions.isSwitchedToBearish && - // - // Verifications ... - conditions.mcConditions.isSARBearish && - conditions.adxtdConditions.isStrong && - conditions.adxtdConditions.isBearish && - conditions.strConditions.isTrendBearish && - conditions.cheConditions.isStrongBearish && - conditions.tdConditions.isBearish && - conditions.hkConditions.isHKBearish && - conditions.hkConditions.isSMHKBearish && - conditions.mrbConditions.isFastUnderSlow && - conditions.sslcConditions.isBearish && - conditions.hullConditions.isBearish && - conditions.vlmConditions.isVolumeBearish && - conditions.atslConditions.isBearish && - conditions.htdConditions.isBearish && - conditions.slnConditions.isBearish - // - ; - if (short1) - { - // - pusher++; - provider = ToString(PROVIDER_XMC); - } - - // - // XSARD ... - bool short2 = - // - // Starting Conditions ... - conditions.mcConditions.isSARSwitchedToBearish && - // - // Verifications ... - conditions.mcConditions.isBearish && - conditions.adxtdConditions.isStrong && - conditions.adxtdConditions.isBearish && - conditions.strConditions.isTrendBearish && - conditions.cheConditions.isStrongBearish && - conditions.tdConditions.isBearish && - conditions.hkConditions.isHKBearish && - conditions.hkConditions.isSMHKBearish && - conditions.mrbConditions.isFastUnderSlow && - conditions.sslcConditions.isBearish && - conditions.hullConditions.isBearish && - conditions.vlmConditions.isVolumeBearish && - conditions.atslConditions.isBearish && - conditions.htdConditions.isBearish && - conditions.slnConditions.isBearish - // - ; - if (short2) - { - // - pusher++; - provider = ToString(PROVIDER_XSARD); - } - - // - // XADXTD ... - bool short3 = - // - // Starting Conditions ... - conditions.adxtdConditions.isStrongSwitchedToBearish && - // - // Verifications ... - conditions.mcConditions.isBearish && - conditions.mcConditions.isSARBearish && - conditions.strConditions.isTrendBearish && - conditions.cheConditions.isStrongBearish && - conditions.tdConditions.isBearish && - conditions.hkConditions.isHKBearish && - conditions.hkConditions.isSMHKBearish && - conditions.mrbConditions.isFastUnderSlow && - conditions.sslcConditions.isBearish && - conditions.hullConditions.isBearish && - conditions.vlmConditions.isVolumeBearish && - conditions.atslConditions.isBearish && - conditions.htdConditions.isBearish && - conditions.slnConditions.isBearish - // - ; - if (short3) - { - // - pusher++; - provider = ToString(PROVIDER_XADXTD); - } - - // - // XSTR ... - bool short4 = - // - // Starting Conditions ... - conditions.strConditions.isTrendSwitchedToBearish && - // - // Verifications ... - conditions.mcConditions.isBearish && - conditions.mcConditions.isSARBearish && - conditions.adxtdConditions.isStrong && - conditions.adxtdConditions.isBearish && - conditions.cheConditions.isStrongBearish && - conditions.tdConditions.isBearish && - conditions.hkConditions.isHKBearish && - conditions.hkConditions.isSMHKBearish && - conditions.mrbConditions.isFastUnderSlow && - conditions.sslcConditions.isBearish && - conditions.hullConditions.isBearish && - conditions.vlmConditions.isVolumeBearish && - conditions.atslConditions.isBearish && - conditions.htdConditions.isBearish && - conditions.slnConditions.isBearish - // - ; - if (short4) - { - // - pusher++; - provider = ToString(PROVIDER_XSTR); - } - - // - // XCHE ... - bool short5 = - // - // Starting Conditions ... - conditions.cheConditions.isStrongSwitchedToBearish && - // - // Verifications ... - conditions.mcConditions.isBearish && - conditions.mcConditions.isSARBearish && - conditions.adxtdConditions.isStrong && - conditions.adxtdConditions.isBearish && - conditions.strConditions.isTrendBearish && - conditions.tdConditions.isBearish && - conditions.hkConditions.isHKBearish && - conditions.hkConditions.isSMHKBearish && - conditions.mrbConditions.isFastUnderSlow && - conditions.sslcConditions.isBearish && - conditions.hullConditions.isBearish && - conditions.vlmConditions.isVolumeBearish && - conditions.atslConditions.isBearish && - conditions.htdConditions.isBearish && - conditions.slnConditions.isBearish - // - ; - if (short5) - { - // - pusher++; - provider = ToString(PROVIDER_XCHE); - } - - // - // XTD ... - bool short6 = - // - // Starting Conditions ... - conditions.tdConditions.isSwitchedToBearish && - // - // Verifications ... - conditions.mcConditions.isBearish && - conditions.mcConditions.isSARBearish && - conditions.adxtdConditions.isStrong && - conditions.adxtdConditions.isBearish && - conditions.strConditions.isTrendBearish && - conditions.cheConditions.isStrongBearish && - conditions.hkConditions.isHKBearish && - conditions.hkConditions.isSMHKBearish && - conditions.mrbConditions.isFastUnderSlow && - conditions.sslcConditions.isBearish && - conditions.hullConditions.isBearish && - conditions.vlmConditions.isVolumeBearish && - conditions.atslConditions.isBearish && - conditions.htdConditions.isBearish && - conditions.slnConditions.isBearish - // - ; - if (short6) - { - // - pusher++; - provider = ToString(PROVIDER_XTD); - } - - // - // XSI ... - bool short7 = - // - // Starting Conditions ... - conditions.rsi[cIndex] < 70 && - conditions.rsi[pIndex] >= 70 && - // - // Verifications ... - conditions.tdConditions.isBearish && - conditions.mcConditions.isBearish && - conditions.mcConditions.isSARBearish && - conditions.adxtdConditions.isStrong && - conditions.adxtdConditions.isBearish && - conditions.strConditions.isTrendBearish && - conditions.cheConditions.isStrongBearish && - conditions.hkConditions.isHKBearish && - conditions.hkConditions.isSMHKBearish && - conditions.mrbConditions.isFastUnderSlow && - conditions.sslcConditions.isBearish && - conditions.hullConditions.isBearish && - conditions.vlmConditions.isVolumeBearish && - conditions.atslConditions.isBearish && - conditions.htdConditions.isBearish && - conditions.slnConditions.isBearish - // - ; - if (short7) - { - // - pusher++; - provider = ToString(PROVIDER_XSI); - } - - // - // XCI ... - bool short8 = - // - // Starting Conditions ... - conditions.cci[cIndex] < 100 && - conditions.cci[pIndex] >= 100 && - // - // Verifications ... - conditions.tdConditions.isBearish && - conditions.mcConditions.isBearish && - conditions.mcConditions.isSARBearish && - conditions.adxtdConditions.isStrong && - conditions.adxtdConditions.isBearish && - conditions.strConditions.isTrendBearish && - conditions.cheConditions.isStrongBearish && - conditions.hkConditions.isHKBearish && - conditions.hkConditions.isSMHKBearish && - conditions.mrbConditions.isFastUnderSlow && - conditions.sslcConditions.isBearish && - conditions.hullConditions.isBearish && - conditions.vlmConditions.isVolumeBearish && - conditions.atslConditions.isBearish && - conditions.htdConditions.isBearish && - conditions.slnConditions.isBearish - // - ; - if (short8) - { - // - pusher++; - provider = ToString(PROVIDER_XCI); - } - - // - // XMCD ... - bool short9 = - // - // Starting Conditions ... - conditions.macd[cIndex] < 0 && - conditions.macd[cIndex] < conditions.macdSignal[cIndex] && - // - // Verifications ... - conditions.tdConditions.isBearish && - conditions.mcConditions.isBearish && - conditions.mcConditions.isSARBearish && - conditions.adxtdConditions.isStrong && - conditions.adxtdConditions.isBearish && - conditions.strConditions.isTrendBearish && - conditions.cheConditions.isStrongBearish && - conditions.hkConditions.isHKBearish && - conditions.hkConditions.isSMHKBearish && - conditions.mrbConditions.isFastUnderSlow && - conditions.sslcConditions.isBearish && - conditions.hullConditions.isBearish && - conditions.vlmConditions.isVolumeBearish && - conditions.atslConditions.isBearish && - conditions.htdConditions.isBearish && - conditions.slnConditions.isBearish - // - ; - if (short9) - { - // - pusher++; - provider = ToString(PROVIDER_XMCD); - } - - // - // XICH ... - bool short10 = - // - // Starting Conditions ... - conditions.ichConditions.HasShortConditions() && - // - // Verifications ... - conditions.tdConditions.isBearish && - conditions.mcConditions.isBearish && - conditions.mcConditions.isSARBearish && - conditions.adxtdConditions.isStrong && - conditions.adxtdConditions.isBearish && - conditions.strConditions.isTrendBearish && - conditions.cheConditions.isStrongBearish && - conditions.hkConditions.isHKBearish && - conditions.hkConditions.isSMHKBearish && - conditions.mrbConditions.isFastUnderSlow && - conditions.sslcConditions.isBearish && - conditions.hullConditions.isBearish && - conditions.vlmConditions.isVolumeBearish && - conditions.atslConditions.isBearish && - conditions.htdConditions.isBearish && - conditions.slnConditions.isBearish - // - ; - if (short10) - { - // - pusher++; - provider = ToString(PROVIDER_XICH); - } - - // - // XHK ... - bool short11 = - // - // Starting Conditions ... - conditions.hkConditions.isHKSwitchedToBearish && - // - // Verifications ... - conditions.tdConditions.isBearish && - conditions.mcConditions.isBearish && - conditions.mcConditions.isSARBearish && - conditions.adxtdConditions.isStrong && - conditions.adxtdConditions.isBearish && - conditions.strConditions.isTrendBearish && - conditions.cheConditions.isStrongBearish && - conditions.hkConditions.isSMHKBearish && - conditions.mrbConditions.isFastUnderSlow && - conditions.sslcConditions.isBearish && - conditions.hullConditions.isBearish && - conditions.vlmConditions.isVolumeBearish && - conditions.atslConditions.isBearish && - conditions.htdConditions.isBearish && - conditions.slnConditions.isBearish - // - ; - if (short11) - { - // - pusher++; - provider = ToString(PROVIDER_XHK); - } - - // - // XSMHK ... - bool short12 = - // - // Starting Conditions ... - conditions.hkConditions.isSMHKSwitchedToBearish && - // - // Verifications ... - conditions.tdConditions.isBearish && - conditions.mcConditions.isBearish && - conditions.mcConditions.isSARBearish && - conditions.adxtdConditions.isStrong && - conditions.adxtdConditions.isBearish && - conditions.strConditions.isTrendBearish && - conditions.cheConditions.isStrongBearish && - conditions.hkConditions.isHKBearish && - conditions.mrbConditions.isFastUnderSlow && - conditions.sslcConditions.isBearish && - conditions.hullConditions.isBearish && - conditions.vlmConditions.isVolumeBearish && - conditions.atslConditions.isBearish && - conditions.htdConditions.isBearish && - conditions.slnConditions.isBearish - // - ; - if (short12) - { - // - pusher++; - provider = ToString(PROVIDER_XSMHK); - } - - // - // XMRB ... - bool short13 = - // - // Starting Conditions ... - conditions.mrbConditions.isFastCrossedUnderSlow && - // - // Verifications ... - conditions.tdConditions.isBearish && - conditions.mcConditions.isBearish && - conditions.mcConditions.isSARBearish && - conditions.adxtdConditions.isStrong && - conditions.adxtdConditions.isBearish && - conditions.strConditions.isTrendBearish && - conditions.cheConditions.isStrongBearish && - conditions.hkConditions.isHKBearish && - conditions.hkConditions.isSMHKBearish && - conditions.sslcConditions.isBearish && - conditions.hullConditions.isBearish && - conditions.vlmConditions.isVolumeBearish && - conditions.atslConditions.isBearish && - conditions.htdConditions.isBearish && - conditions.slnConditions.isBearish - // - ; - if (short13) - { - // - pusher++; - provider = ToString(PROVIDER_XMRB); - } - - // - // XSSLC ... - bool short14 = - // - // Starting Conditions ... - conditions.sslcConditions.isSwitchedToBearish && - // - // Verifications ... - conditions.tdConditions.isBearish && - conditions.mcConditions.isBearish && - conditions.mcConditions.isSARBearish && - conditions.adxtdConditions.isStrong && - conditions.adxtdConditions.isBearish && - conditions.strConditions.isTrendBearish && - conditions.cheConditions.isStrongBearish && - conditions.hkConditions.isHKBearish && - conditions.hkConditions.isSMHKBearish && - conditions.mrbConditions.isFastUnderSlow && - conditions.hullConditions.isBearish && - conditions.vlmConditions.isVolumeBearish && - conditions.atslConditions.isBearish && - conditions.htdConditions.isBearish && - conditions.slnConditions.isBearish - // - ; - if (short14) - { - // - pusher++; - provider = ToString(PROVIDER_XSSLC); - } - - // - // XHULL ... - bool short15 = - // - // Starting Conditions ... - conditions.hullConditions.isSwitchedToBearish && - // - // Verifications ... - conditions.tdConditions.isBearish && - conditions.mcConditions.isBearish && - conditions.mcConditions.isSARBearish && - conditions.adxtdConditions.isStrong && - conditions.adxtdConditions.isBearish && - conditions.strConditions.isTrendBearish && - conditions.cheConditions.isStrongBearish && - conditions.hkConditions.isHKBearish && - conditions.hkConditions.isSMHKBearish && - conditions.mrbConditions.isFastUnderSlow && - conditions.sslcConditions.isBearish && - conditions.vlmConditions.isVolumeBearish && - conditions.atslConditions.isBearish && - conditions.htdConditions.isBearish && - conditions.slnConditions.isBearish - // - ; - if (short15) - { - // - pusher++; - provider = ToString(PROVIDER_XHULL); - } - - // - // XASCT ... - bool short16 = - // - // Starting Conditions ... - conditions.asctConditions.isShortSignal && - // - // Verifications ... - conditions.tdConditions.isBearish && - conditions.mcConditions.isBearish && - conditions.mcConditions.isSARBearish && - conditions.adxtdConditions.isStrong && - conditions.adxtdConditions.isBearish && - conditions.strConditions.isTrendBearish && - conditions.cheConditions.isStrongBearish && - conditions.hkConditions.isHKBearish && - conditions.hkConditions.isSMHKBearish && - conditions.mrbConditions.isFastUnderSlow && - conditions.hullConditions.isBearish && - conditions.sslcConditions.isBearish && - conditions.vlmConditions.isVolumeBearish && - conditions.atslConditions.isBearish && - conditions.htdConditions.isBearish && - conditions.slnConditions.isBearish - // - ; - if (short16) - { - // - pusher++; - provider = ToString(PROVIDER_XASCT); - } - - // - // XVLM ... - bool short17 = - // - // Starting Conditions ... - conditions.vlmConditions.isVolumeChangedToBearish && - // - // Verifications ... - conditions.tdConditions.isBearish && - conditions.mcConditions.isBearish && - conditions.mcConditions.isSARBearish && - conditions.adxtdConditions.isStrong && - conditions.adxtdConditions.isBearish && - conditions.strConditions.isTrendBearish && - conditions.cheConditions.isStrongBearish && - conditions.hkConditions.isHKBearish && - conditions.hkConditions.isSMHKBearish && - conditions.mrbConditions.isFastUnderSlow && - conditions.hullConditions.isBearish && - conditions.sslcConditions.isBearish && - conditions.atslConditions.isBearish && - conditions.htdConditions.isBearish && - conditions.slnConditions.isBearish - // - ; - if (short17) - { - // - pusher++; - provider = ToString(PROVIDER_XVLM); - } - - // - // XPVF ... - bool short18 = - // - // Starting Conditions ... - conditions.pvConditions.isFiboDecreased && - // - // Verifications ... - conditions.tdConditions.isBearish && - conditions.mcConditions.isBearish && - conditions.mcConditions.isSARBearish && - conditions.adxtdConditions.isStrong && - conditions.adxtdConditions.isBearish && - conditions.strConditions.isTrendBearish && - conditions.cheConditions.isStrongBearish && - conditions.hkConditions.isHKBearish && - conditions.hkConditions.isSMHKBearish && - conditions.mrbConditions.isFastUnderSlow && - conditions.hullConditions.isBearish && - conditions.sslcConditions.isBearish && - conditions.vlmConditions.isVolumeBearish && - conditions.atslConditions.isBearish && - conditions.htdConditions.isBearish && - conditions.slnConditions.isBearish - // - ; - if (short18) - { - // - pusher++; - provider = ToString(PROVIDER_XPVF); - } - - // - // XPVSAR ... - bool short19 = - // - // Starting Conditions ... - conditions.mcConditions.isSARSwitchedToBearish && - conditions.pvConditions.peaks[zIndex] == conditions.mcConditions.psar[zIndex] && - conditions.strConditions.isTrendBearish && - conditions.cheConditions.isStrongBearish && - conditions.atslConditions.isBearish && - conditions.htdConditions.isBearish && - conditions.slnConditions.isBearish - // - ; - if (short19) - { - // - pusher += 2; - provider = ToString(PROVIDER_XPVSAR); - } - - // - // XHTSRD ... - bool short20 = - // - // Starting Conditions ... - conditions.IsTrendBearish() && - conditions.dmntConditions.isBearish && - // - // Verifications ... - conditions.tdConditions.isBearish && - conditions.adxtdConditions.isStrong && - conditions.adxtdConditions.isBearish && - conditions.vlmConditions.isVolumeBearish && - conditions.atslConditions.isBearish && - conditions.htdConditions.isBearish && - conditions.slnConditions.isBearish - // - ; - if (short20) - { - // - pusher++; - provider = ToString(PROVIDER_XHTSRD); - } - - // - // XATSL ... - bool short21 = - // - // Starting Conditions ... - conditions.atslConditions.isSwitchedToBearish && - // - // Verifications ... - conditions.mcConditions.isSARBearish && - conditions.adxtdConditions.isStrong && - conditions.adxtdConditions.isBearish && - conditions.strConditions.isTrendBearish && - conditions.cheConditions.isStrongBearish && - conditions.tdConditions.isBearish && - conditions.hkConditions.isHKBearish && - conditions.hkConditions.isSMHKBearish && - conditions.mrbConditions.isFastUnderSlow && - conditions.sslcConditions.isBearish && - conditions.hullConditions.isBearish && - conditions.vlmConditions.isVolumeBearish && - conditions.mcConditions.isBearish && - conditions.htdConditions.isBearish && - conditions.slnConditions.isBearish - // - ; - if (short21) - { - // - pusher++; - provider = ToString(PROVIDER_XATSL); - } - - // - // XHTD ... - bool short22 = - // - // Starting Conditions ... - conditions.htdConditions.isSwitchedToBearish && - // - // Verifications ... - conditions.mcConditions.isSARBearish && - conditions.adxtdConditions.isStrong && - conditions.adxtdConditions.isBearish && - conditions.strConditions.isTrendBearish && - conditions.cheConditions.isStrongBearish && - conditions.tdConditions.isBearish && - conditions.hkConditions.isHKBearish && - conditions.hkConditions.isSMHKBearish && - conditions.mrbConditions.isFastUnderSlow && - conditions.sslcConditions.isBearish && - conditions.hullConditions.isBearish && - conditions.vlmConditions.isVolumeBearish && - conditions.mcConditions.isBearish && - conditions.atslConditions.isBearish && - conditions.atslConditions.isBearish && - conditions.slnConditions.isBearish - // - ; - if (short22) - { - // - pusher++; - provider = ToString(PROVIDER_XHTD); - } - - // - // XSLN ... - bool short23 = - // - // Starting Conditions ... - conditions.slnConditions.isSwitchedToBearish && - // - // Verifications ... - conditions.mcConditions.isSARBearish && - conditions.adxtdConditions.isStrong && - conditions.adxtdConditions.isBearish && - conditions.strConditions.isTrendBearish && - conditions.cheConditions.isStrongBearish && - conditions.tdConditions.isBearish && - conditions.hkConditions.isHKBearish && - conditions.hkConditions.isSMHKBearish && - conditions.mrbConditions.isFastUnderSlow && - conditions.sslcConditions.isBearish && - conditions.hullConditions.isBearish && - conditions.vlmConditions.isVolumeBearish && - conditions.mcConditions.isBearish && - conditions.atslConditions.isBearish && - conditions.atslConditions.isBearish && - conditions.htdConditions.isBearish - // - ; - if (short23) - { - // - pusher++; - provider = ToString(PROVIDER_XSLN); - } - - // - result = - // - pusher >= 1 && - ( - // - short1 - // - || - // - short2 - // - || - // - short3 - // - || - // - short4 - // - || - // - short5 - // - || - // - short6 - // - || - // - short7 - // - || - // - short8 - // - || - // - short9 - // - || - // - short10 - // - || - // - short11 - // - || - // - short12 - // - || - // - short13 - // - || - // - short14 - // - || - // - short15 - // - || - // - short16 - // - || - // - short17 - // - || - // - short18 - // - || - // - short19 - // - || - // - short20 - // - || - // - short21 - // - || - // - short22 - // - || - // - short23 - // - ) - // - ; - - // - return result; - } - - // - // Retrieve Long Verifications ... - bool HasLongVerifications( - X121SetupConditions &conditions[] // Conditions Collection - ) - { - // - bool result = false; - - // - int count = ArraySize(conditions); - result = IsValidSize(count); - if (!result) - { - return result; - } - - // - // Loop through Conditions to Get Verifications ... - for (int i = count - 1; i >= 0; i--) - { - // - X121SetupConditions iConditions = conditions[i]; - - // - result = IsConditionsValidForLong(iConditions); - if (result) - { - break; - } - } - - // - return result; - } - - // - // Count Number of Long Validations ... - int CountLongValidations( - X121SetupConditions &conditions // Conditions - ) - { - // - int result = 0; - - // - // XTD ... - bool isTDPassed = - // - conditions.tdConditions.isBullish || - conditions.tdConditions.isSwitchedToBullish - // - ; - if (isTDPassed) - { - result++; - } - - // - // XHK ... - bool isHKPassed = - // - (conditions.hkConditions.isHKBullish || - conditions.hkConditions.isHKSwitchedToBullish) - // - || - // - (conditions.hkConditions.isSMHKBullish || - conditions.hkConditions.isSMHKSwitchedToBullish) - // - ; - if (isHKPassed) - { - result++; - } - - // - // XCHE ... - bool isCHEPassed = - // - conditions.cheConditions.isBullish || - conditions.cheConditions.isStrongBullish || - conditions.cheConditions.isSwitchedToBullish || - conditions.cheConditions.isStrongSwitchedToBullish - // - ; - if (isCHEPassed) - { - result++; - } - - // - // XICH ... - bool isICHPassed = - // - (conditions.ichConditions.isTenkanSenOverKijunSen || - conditions.ichConditions.isTenkanSenCrossedOverKijunSen) - // - && - // - (conditions.ichConditions.isSenkouSpanAOverB || - conditions.ichConditions.isSenkouSpanAOverLast || - conditions.ichConditions.isSenkouSpanACrossedOverB || - conditions.ichConditions.isSenkouSpanACrossedOverLast) - // - && - // - (conditions.ichConditions.isFutureSenkouSpanAOverB || - conditions.ichConditions.isFutureSenkouSpanAOverLast || - conditions.ichConditions.isFutureSenkouSpanACrossedOverB || - conditions.ichConditions.isFutureSenkouSpanACrossedOverLast) - // - ; - if (isICHPassed) - { - result++; - } - - // - // XSTR ... - bool isSTRPassed = - // - conditions.strConditions.isTrendBullish || - conditions.strConditions.isTrendSwitchedToBullish - // - ; - if (isSTRPassed) - { - result++; - } - - // - // XMRB ... - bool isMRBPassed = - // - conditions.mrbConditions.isFastOverSlow || - conditions.mrbConditions.isFastCrossedOverSlow - // - ; - if (isMRBPassed) - { - result++; - } - - // - // XVLM ... - bool isVLMPassed = - // - conditions.vlmConditions.isVolumeBullish || - conditions.vlmConditions.isVolumeOverLast || - conditions.vlmConditions.isVolumeChangedToBullish - // - ; - if (isVLMPassed) - { - result++; - } - - // - // XSSLC ... - bool isSSLCPassed = - // - conditions.sslcConditions.isBullish || - conditions.sslcConditions.isSwitchedToBullish - // - ; - if (isSSLCPassed) - { - result++; - } - - // - // XHULL ... - bool isHULLPassed = - // - conditions.hullConditions.isBullish || - conditions.hullConditions.isUpBullish || - conditions.hullConditions.isDownBullish || - conditions.hullConditions.isSwitchedToBullish - // - ; - if (isHULLPassed) - { - result++; - } - - // - // XADX ... - bool isADXTDPassed = - // - conditions.adxtdConditions.isBullish || - conditions.adxtdConditions.isSwitchedToBullish || - conditions.adxtdConditions.isStrongSwitchedToBullish - // - ; - if (isADXTDPassed) - { - result++; - } - - // - // XMC ... - bool isMATDPassed = - // - ((conditions.mcConditions.isBullish || - conditions.mcConditions.isSwitchedToBullish) - // - || - // - ((conditions.mcConditions.isFastOverVerifier || - conditions.mcConditions.isFastCrossedOverVerifier) - // - && - // - (conditions.mcConditions.isSlowOverVerifier || - conditions.mcConditions.isSlowCrossedOverVerifier))) - // - || - // - (conditions.mcConditions.isSARBullish || - conditions.mcConditions.isSARSwitchedToBullish) - // - ; - if (isMATDPassed) - { - result++; - } - - // - return result; - } - - // - bool IsConditionsValidForLong( - X121SetupConditions &conditions, // Conditions - int verifications = 2 // Number of Verifications - ) - { - // - bool result = false; - - // - int signs = CountLongValidations(conditions); - - // - result = - // - verifications <= 0 - ? signs > 0 - : signs >= verifications - // - ; - - // - return result; - } - - // - // Retrieve Short Verifications ... - bool HasShortVerifications( - X121SetupConditions &conditions[] // Conditions Collection - ) - { - // - bool result = false; - - // - int count = ArraySize(conditions); - result = IsValidSize(count); - if (!result) - { - return result; - } - - // - // Loop through Conditions to Get Verifications ... - for (int i = count - 1; i >= 0; i--) - { - // - X121SetupConditions iConditions = conditions[i]; - - // - result = IsConditionsValidForShort(iConditions); - if (result) - { - break; - } - } - - // - return result; - } - - // - int CountShortValidations( - X121SetupConditions &conditions // Conditions - ) - { - // - int result = 0; - - // - // XTD ... - bool isTDPassed = - // - conditions.tdConditions.isBearish || - conditions.tdConditions.isSwitchedToBearish - // - ; - if (isTDPassed) - { - result++; - } - - // - // XHK ... - bool isHKPassed = - // - (conditions.hkConditions.isHKBearish || - conditions.hkConditions.isHKSwitchedToBearish) - // - || - // - (conditions.hkConditions.isSMHKBearish || - conditions.hkConditions.isSMHKSwitchedToBearish) - // - ; - if (isHKPassed) - { - result++; - } - - // - // XCHE ... - bool isCHEPassed = - // - conditions.cheConditions.isBearish || - conditions.cheConditions.isStrongBearish || - conditions.cheConditions.isSwitchedToBearish || - conditions.cheConditions.isStrongSwitchedToBearish - // - ; - if (isCHEPassed) - { - result++; - } - - // - // XICH ... - bool isICHPassed = - // - (conditions.ichConditions.isTenkanSenUnderKijunSen || - conditions.ichConditions.isTenkanSenCrossedUnderKijunSen) - // - && - // - (conditions.ichConditions.isSenkouSpanAUnderB || - conditions.ichConditions.isSenkouSpanAUnderLast || - conditions.ichConditions.isSenkouSpanACrossedUnderB || - conditions.ichConditions.isSenkouSpanACrossedUnderLast) - // - && - // - (conditions.ichConditions.isFutureSenkouSpanAUnderB || - conditions.ichConditions.isFutureSenkouSpanAUnderLast || - conditions.ichConditions.isFutureSenkouSpanACrossedUnderB || - conditions.ichConditions.isFutureSenkouSpanACrossedUnderLast) - // - ; - if (isICHPassed) - { - result++; - } - - // - // XSTR ... - bool isSTRPassed = - // - conditions.strConditions.isTrendBearish || - conditions.strConditions.isTrendSwitchedToBearish - // - ; - if (isSTRPassed) - { - result++; - } - - // - // XMRB ... - bool isMRBPassed = - // - conditions.mrbConditions.isFastUnderSlow || - conditions.mrbConditions.isFastCrossedUnderSlow - // - ; - if (isMRBPassed) - { - result++; - } - - // - // XVLM ... - bool isVLMPassed = - // - conditions.vlmConditions.isVolumeBearish || - conditions.vlmConditions.isVolumeUnderLast || - conditions.vlmConditions.isVolumeChangedToBearish - // - ; - if (isVLMPassed) - { - result++; - } - - // - // XSSLC ... - bool isSSLCPassed = - // - conditions.sslcConditions.isBearish || - conditions.sslcConditions.isSwitchedToBearish - // - ; - if (isSSLCPassed) - { - result++; - } - - // - // XHULL ... - bool isHULLPassed = - // - conditions.hullConditions.isBearish || - conditions.hullConditions.isUpBearish || - conditions.hullConditions.isDownBearish || - conditions.hullConditions.isSwitchedToBearish - // - ; - if (isHULLPassed) - { - result++; - } - - // - // XADX ... - bool isADXTDPassed = - // - conditions.adxtdConditions.isBearish || - conditions.adxtdConditions.isSwitchedToBearish || - conditions.adxtdConditions.isStrongSwitchedToBearish - // - ; - if (isADXTDPassed) - { - result++; - } - - // - // XMC ... - bool isMATDPassed = - // - ((conditions.mcConditions.isBearish || - conditions.mcConditions.isSwitchedToBearish) - // - || - // - ((conditions.mcConditions.isFastUnderVerifier || - conditions.mcConditions.isFastCrossedUnderVerifier) - // - && - // - (conditions.mcConditions.isSlowUnderVerifier || - conditions.mcConditions.isSlowCrossedUnderVerifier))) - // - || - // - (conditions.mcConditions.isSARBearish || - conditions.mcConditions.isSARSwitchedToBearish) - // - ; - if (isMATDPassed) - { - result++; - } - - // - return result; - } - - // - bool IsConditionsValidForShort( - X121SetupConditions &conditions, // Conditions - int verifications = 2 // Number of Verifications - ) - { - // - bool result = false; - - // - int signs = CountShortValidations(conditions); - - // - result = - // - verifications <= 0 - ? signs > 0 - : signs >= verifications - // - ; - - // - return result; - } - - // - // Filter Long Conditions ... - bool FilterLongConditions( - X121SetupConditions &conditions, // Conditions - int pusher, // Pushers - string provider // Provider - ) - { - // - bool result = false; - - // - // TODO Filter ... - result = true; // provider == ToString(PROVIDER_XHTSRD); - - // - return result; - } - - // - // Filter Short Conditions ... - bool FilterShortConditions( - X121SetupConditions &conditions, // Conditions - int pusher, // Pushers - string provider // Provider - ) - { - // - bool result = false; - - // - // TODO Filter ... - result = true; // provider == ToString(PROVIDER_XHTSRD); - - // - return result; - } - - // - // Check Conditions for Generating Possible Signals ... - bool HasSignal( - X121SetupConditions &conditions, // Conditions - XSignal &signal, // Signal if Exists - int &pusher, // Pushers - string &provider, // Signal Provider Name - double &tp, // Provided TP - double &sl, // Provided SL - bool _useSupport, // Generate Support Signals - bool _allowLong, // Allow Long Signals - bool _allowShort, // Allow Short Signals - double _volume = 0.01, // Volume - double _slPoint = 0, // SL Point - bool _ignoreSL = false, // Ignore Calculated SL - double _tpPoint = 30, // TP Point - bool _ignoreTP = false // Ignore Calculated TP - ) - { - // - bool result = false; - - // - signal.Clean(); - - // - result = _allowLong || _allowShort; - if (!result) - { - return result; - } - - // - bool hasLong = false; - bool hasShort = false; - - // - if (_allowLong) - { - // - hasLong = - HasLongConditions( - conditions, - pusher, - provider, - tp, - sl // - ); - - // - if (hasLong) - { - // - hasLong = FilterLongConditions( - conditions, - pusher, - provider // - ); - } - } - - // - if (_allowShort && !hasLong) - { - // - hasShort = - HasShortConditions( - conditions, - pusher, - provider, - tp, - sl // - ); - - // - if (hasShort) - { - // - hasShort = FilterShortConditions( - conditions, - pusher, - provider // - ); - } - } - - // - result = hasLong || hasShort; - if (!result) - { - return result; - } - - // - string mProvider = - IsValid(provider) - ? provider - : GetTag(); - - // - // Prepare Signals ... - ENUM_POSITION_TYPE mType = - hasLong - ? POSITION_TYPE_BUY - : POSITION_TYPE_SELL; - - // - double mEntry = GetEntry( - conditions.symbol, - mType // - ); - - // - double mSL = 0; - double mTP = 0; - double mPointValue = - GetPoints(conditions.symbol); - result = CalculateTPSLByPoint( - mSL, - mTP, - mType, - mEntry, - mPointValue, - 1, - _slPoint, - _tpPoint // - ); - if (!result) - { - return result; - } - - // - result = signal.Prepare( - conditions.symbol, - mProvider, - conditions.period, - mType, - X_ORDER_MODE_MARKET, - mEntry, - _volume, - _ignoreSL - ? 0 - : mSL, - _ignoreTP - ? 0 - : mTP // - ); - if (!result) - { - return result; - } - - // - return result; - } - - // - string GetTag() - { - return "X121"; - } -}; - -// -// Class ... -class XSCX121Setup : public XSCBaseAlert -{ - // - // Public ... -public: - // - // Props ... - XSCXMCHelper *mcHelper; - XSCXPVHelper *pvHelper; - XSCXTDHelper *tdHelper; - XSCXHKHelper *hkHelper; - XSCXCHEHelper *cheHelper; - XSCXICHHelper *ichHelper; - XSCXSTRHelper *strHelper; - XSCXMRBHelper *mrbHelper; - XSCXOSCHelper *oscHelper; - XSCXVLMHelper *vlmHelper; - XSCXSLNHelper *slnHelper; - XSCXHTDHelper *hdtHelper; - XSCXASCTHelper *asctHelper; - XSCXSSLCHelper *sslcHelper; - XSCXHULLHelper *hullHelper; - XSCXATSLHelper *atslHelper; - XSCXDMNTHelper *dmntHelper; - XSCXADXTDHelper *adxtdHelper; - - // - // Constructor(s) ... - void XSCX121Setup() {} - - // - // Deconstructor ... - void ~XSCX121Setup() - { - // - delete mcHelper; - delete pvHelper; - delete tdHelper; - delete hkHelper; - delete cheHelper; - delete ichHelper; - delete strHelper; - delete mrbHelper; - delete oscHelper; - delete vlmHelper; - delete hdtHelper; - delete asctHelper; - delete sslcHelper; - delete hullHelper; - delete atslHelper; - delete dmntHelper; - delete adxtdHelper; - } - - // - // Getter(s) / Setter(s) ... - - // - string GetSymbol() - { - return inputs.symbol; - } - - // - ENUM_TIMEFRAMES GetPeriod() - { - return inputs.period; - } - - // - // Tools ... - - // - bool Init( - X121SetupInputs &_inputs // Configurations - ) - { - // - bool result = false; - - // - result = _inputs.IsValid(); - if (!result) - { - return result; - } - - // - inputs = _inputs; - - // - // Initialize Helpers ... - - // - // XPV ... - pvHelper = new XSCXPVHelper(); - result = pvHelper.Init( - inputs.symbol, - inputs.period, - inputs.pvInputs // - ); - if (!result) - { - return result; - } - - // - // XSLN ... - slnHelper = new XSCXSLNHelper(); - result = slnHelper.Init( - inputs.symbol, - inputs.period, - inputs.slnInputs // - ); - if (!result) - { - return result; - } - - // - // XTD ... - tdHelper = new XSCXTDHelper(); - result = tdHelper.Init( - inputs.symbol, - inputs.period, - inputs.tdInputs // - ); - if (!result) - { - return result; - } - - // - // XHTD ... - hdtHelper = new XSCXHTDHelper(); - result = hdtHelper.Init( - inputs.symbol, - inputs.period, - inputs.htdInputs // - ); - if (!result) - { - return result; - } - - // - // XATSL ... - atslHelper = new XSCXATSLHelper(); - result = atslHelper.Init( - inputs.symbol, - inputs.period, - inputs.atslInputs // - ); - if (!result) - { - return result; - } - - // - // XDMNT ... - dmntHelper = new XSCXDMNTHelper(); - result = dmntHelper.Init( - inputs.symbol, - inputs.period, - inputs.dmntInputs // - ); - if (!result) - { - return result; - } - - // - // XHK ... - hkHelper = new XSCXHKHelper(); - result = hkHelper.Init( - inputs.symbol, - inputs.period, - inputs.hkInputs // - ); - if (!result) - { - return result; - } - - // - // XCHE ... - cheHelper = new XSCXCHEHelper(); - result = cheHelper.Init( - inputs.symbol, - inputs.period, - inputs.cheInputs // - ); - if (!result) - { - return result; - } - - // - // XICH ... - ichHelper = new XSCXICHHelper(); - result = ichHelper.Init( - inputs.symbol, - inputs.period, - inputs.ichInputs // - ); - if (!result) - { - return result; - } - - // - // XSTR ... - strHelper = new XSCXSTRHelper(); - result = strHelper.Init( - inputs.symbol, - inputs.period, - inputs.strInputs // - ); - if (!result) - { - return result; - } - - // - // XMRB ... - mrbHelper = new XSCXMRBHelper(); - result = mrbHelper.Init( - inputs.symbol, - inputs.period, - inputs.mrbInputs // - ); - if (!result) - { - return result; - } - - // - // XOSC ... - oscHelper = new XSCXOSCHelper(); - result = oscHelper.Init( - inputs.symbol, - inputs.period, - inputs.oscInputs // - ); - if (!result) - { - return result; - } - - // - // XVLM ... - vlmHelper = new XSCXVLMHelper(); - result = vlmHelper.Init( - inputs.symbol, - inputs.period, - inputs.vlmInputs // - ); - if (!result) - { - return result; - } - - // - // XMC ... - mcHelper = new XSCXMCHelper(); - result = mcHelper.Init( - inputs.symbol, - inputs.period, - inputs.mcInputs // - ); - if (!result) - { - return result; - } - - // - // XASCT ... - asctHelper = new XSCXASCTHelper(); - result = asctHelper.Init( - inputs.symbol, - inputs.period, - inputs.asctInputs // - ); - if (!result) - { - return result; - } - - // - // XSSLC ... - sslcHelper = new XSCXSSLCHelper(); - result = sslcHelper.Init( - inputs.symbol, - inputs.period, - inputs.sslcInputs // - ); - if (!result) - { - return result; - } - - // - // XHULL ... - hullHelper = new XSCXHULLHelper(); - result = hullHelper.Init( - inputs.symbol, - inputs.period, - inputs.hullInputs // - ); - if (!result) - { - return result; - } - - // - // XADXTD ... - adxtdHelper = new XSCXADXTDHelper(); - result = adxtdHelper.Init( - inputs.symbol, - inputs.period, - inputs.adxtdInputs // - ); - if (!result) - { - return result; - } - - // - return result; - } - - // - X121SetupInputs GetInputs() - { - return inputs; - } - - // - bool SetInputs( - X121SetupInputs &_inputs // Configurations - ) - { - return Init(_inputs); - } - - // - bool GetConditions( - X121SetupConditions &conditions, // - int barIndex = 0, // - int loopback = 5 // - ) - { - // - bool result = true; - - // - conditions.Clean(); - - // - conditions.symbol = GetSymbol(); - conditions.period = GetPeriod(); - conditions.time = TimeCurrent(); - - // - result = hdtHelper.GetConditions( - conditions.htdConditions, - barIndex, - loopback // - ); - if (!result) - { - return result; - } - - // - result = slnHelper.GetConditions( - conditions.slnConditions, - barIndex, - loopback // - ); - if (!result) - { - return result; - } - - // - result = atslHelper.GetConditions( - conditions.atslConditions, - barIndex, - loopback // - ); - if (!result) - { - return result; - } - - // - result = dmntHelper.GetConditions( - conditions.dmntConditions, - barIndex, - loopback // - ); - if (!result) - { - return result; - } - - // - result = pvHelper.GetConditions( - conditions.pvConditions, - barIndex, - loopback // - ); - if (!result) - { - return result; - } - - // - result = tdHelper.GetConditions( - conditions.tdConditions, - barIndex, - loopback // - ); - if (!result) - { - return result; - } - - // - result = hkHelper.GetConditions( - conditions.hkConditions, - barIndex, - loopback // - ); - if (!result) - { - return result; - } - - // - result = cheHelper.GetConditions( - conditions.cheConditions, - barIndex, - loopback // - ); - if (!result) - { - return result; - } - - // - result = ichHelper.GetConditions( - conditions.ichConditions, - barIndex, - loopback // - ); - if (!result) - { - return result; - } - - // - result = strHelper.GetConditions( - conditions.strConditions, - barIndex, - loopback // - ); - if (!result) - { - return result; - } - - // - result = mrbHelper.GetConditions( - conditions.mrbConditions, - barIndex, - loopback // - ); - if (!result) - { - return result; - } - - // - result = mcHelper.GetConditions( - conditions.mcConditions, - barIndex, - loopback // - ); - if (!result) - { - return result; - } - - // - result = asctHelper.GetConditions( - conditions.asctConditions, - barIndex, - loopback // - ); - if (!result) - { - return result; - } - - // - result = vlmHelper.GetConditions( - conditions.vlmConditions, - barIndex, - loopback // - ); - if (!result) - { - return result; - } - - // - result = sslcHelper.GetConditions( - conditions.sslcConditions, - barIndex, - loopback // - ); - if (!result) - { - return result; - } - - // - result = hullHelper.GetConditions( - conditions.hullConditions, - barIndex, - loopback // - ); - if (!result) - { - return result; - } - - // - result = adxtdHelper.GetConditions( - conditions.adxtdConditions, - barIndex, - loopback // - ); - if (!result) - { - return result; - } - - // - oscHelper.CopyCCI( - barIndex, - loopback, - conditions.cci // - ); - oscHelper.CopyRSI( - barIndex, - loopback, - conditions.rsi // - ); - oscHelper.CopyMACD( - barIndex, - loopback, - conditions.macd // - ); - oscHelper.CopyMACDSignal( - barIndex, - loopback, - conditions.macdSignal // - ); - - // - return result; - } - - // - // Protected ... -protected: - // - // Private ... -private: - // - // Props ... - X121SetupInputs inputs; // Setup Configurations ... -}; - -// -// Tools ... - -// -int FindSignalConditionsIndex( - XSignal &signal, - X121SetupConditions &conditions[] // -) -{ - // - int result = -1; - - // - // Check Signal is Valid ... - if (!signal.IsValid()) - { - return result; - } - - // - // Check Conditions Count ... - int conditionsCount = ArraySize(conditions); - if (!IsValidSize(conditionsCount)) - { - return result; - } - - // - for (int i = 0; i < conditionsCount; i++) - { - // - X121SetupConditions iConditions = conditions[i]; - - // - if (signal.symbol == iConditions.symbol && - signal.period == iConditions.period) - { - // - result = i; - break; - } - } - - // - return result; -} - -// \ No newline at end of file diff --git a/Documents/Pack/V1.0/Source/Classes/x-saherelm.x121.setup.cycle.class.mq5 b/Documents/Pack/V1.0/Source/Classes/x-saherelm.x121.setup.cycle.class.mq5 deleted file mode 100644 index 6fdd5700..00000000 --- a/Documents/Pack/V1.0/Source/Classes/x-saherelm.x121.setup.cycle.class.mq5 +++ /dev/null @@ -1,828 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Class Library -// ---------------------------------------------- -// Name: XSCX121SetupCycle -// Description: provides implementation of X121 -// Setup on Specified Market Cycle ... -// -// -// 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 -#include "../Classes/x-saherelm.x121.setup.class.mq5" - -// -// Definitions ... - -// -// Inputs ... -struct X121SetupCycleInputs -{ - // - // Props ... - - // - XMarketCycle cycle; // Market Cycle - - // - X121SetupInputs inputs; // Inputs - - // - XSCX121Setup *setup; // Setup - - // - // Constructor ... - void X121SetupCycleInputs() - { - } - - // - // Initialization ... - bool Init( - X121SetupInputs &_inputs, // Configurations - ENUM_TIMEFRAMES _hostPeriod, // Host Period - ENUM_X_MARKET_CYCLES _cycle, // Init Cycle - ENUM_X_PERIOD_METHOD _method, // Period Selection Method - ENUM_TIMEFRAMES _period, // Provided Period - string _prefix = "" // Prefix - ) - { - // - bool result = false; - - // - // Validate Inputs ... - result = - // - IsValid(_inputs.symbol) - // - ; - if (!result) - { - return result; - } - - // - // Init Cycle ... - result = cycle.Init( - inputs.symbol, - _hostPeriod, - _cycle, - _method, - _period, - _prefix // - ); - if (!result) - { - return result; - } - - // - cycle.Update(0); - - // - _inputs.period = cycle.period; - - // - result = _inputs.IsValid(); - if (!result) - { - return result; - } - - // - this.inputs = _inputs; - - // - setup = new XSCX121Setup(); - result = setup.Init( - inputs // - ); - - // - return result; - } - - // - // Tools ... - - // - string GetSymbol() - { - return inputs.symbol; - } - - // - ENUM_TIMEFRAMES GetPeriod() - { - return inputs.period; - } - - // - bool CanProcessBar() - { - return cycle.barTracker.CanProcessBar(); - } - - // - void WaitsUntilNextBar() - { - cycle.barTracker.Waits(); - } - - // - bool GetConditions( - X121SetupConditions &conditions, // - int barIndex = 0, // - int loopback = 5 // - ) - { - // - bool result = false; - - // - result = cycle.Update( - barIndex // - ); - - // - result = setup.GetConditions( - conditions, - barIndex, - loopback // - ); - - // - return result; - } -}; - -// -// Class ... -class XSCX121SetupCycles : public XSCBaseAlert -{ - // - // Public ... -public: - // - // Props ... - X121SignalGenerator signalGenerator; - - // - X121SetupCycleInputs cCycle; // Current (Host) Cycle - X121SetupCycleInputs sCycle; // Short Cycle - X121SetupCycleInputs mCycle; // Medium Cycle - X121SetupCycleInputs lCycle; // Long Cycle - X121SetupCycleInputs hCycle; // Hind Cycle - - // - // Constructor(s) ... - void XSCX121SetupCycles() {} - - // - // Deconstructor ... - void ~XSCX121SetupCycles() {} - - // - // Initialized ... - bool Init( - X121SetupInputs &_inputs, // Configurations - string _symbol, // Trading Symbol - ENUM_TIMEFRAMES _hostPeriod, // Host Period - ENUM_X_PERIOD_METHOD _sMethod = X_PERIOD_AUTO, // Short Period Selection Method - ENUM_TIMEFRAMES _sPeriod = NULL, // Short Provided Period - ENUM_X_PERIOD_METHOD _mMethod = X_PERIOD_AUTO, // Medium Period Selection Method - ENUM_TIMEFRAMES _mPeriod = NULL, // Medium Provided Period - ENUM_X_PERIOD_METHOD _lMethod = X_PERIOD_AUTO, // Long Period Selection Method - ENUM_TIMEFRAMES _lPeriod = NULL, // Long Provided Period - ENUM_X_PERIOD_METHOD _hMethod = X_PERIOD_AUTO, // Hind Period Selection Method - ENUM_TIMEFRAMES _hPeriod = NULL // Hind Provided Period - ) - { - // - bool result = false; - - // - // Check Validation of Symbol and Period ... - result = - // - IsValid(_symbol) && - IsValid(_hostPeriod) - // - ; - if (!result) - { - return result; - } - - // - // Initialize Market Cycles ... - - // - // Current ... - _inputs.symbol = _symbol; - result = cCycle.Init( - _inputs, - _hostPeriod, - X_MARKET_CYCLE_SHORT, - X_PERIOD_MANUALLY, - _hostPeriod, - "CURR" // - ); - if (!result) - { - return result; - } - - // - result = cBarTracker.Init( - _inputs.symbol, - _hostPeriod // - ); - if (!result) - { - return result; - } - - // - // Short ... - result = sCycle.Init( - _inputs, - _hostPeriod, - X_MARKET_CYCLE_SHORT, - _sMethod, - _sPeriod // - ); - if (!result) - { - return result; - } - - // - result = sBarTracker.Init( - _inputs.symbol, - sCycle.cycle.period // - ); - if (!result) - { - return result; - } - - // - // Medium ... - result = mCycle.Init( - _inputs, - _hostPeriod, - X_MARKET_CYCLE_MEDIUM, - _mMethod, - _mPeriod // - ); - if (!result) - { - return result; - } - - // - result = mBarTracker.Init( - _inputs.symbol, - mCycle.cycle.period // - ); - if (!result) - { - return result; - } - - // - // Long ... - result = lCycle.Init( - _inputs, - _hostPeriod, - X_MARKET_CYCLE_LONG, - _lMethod, - _lPeriod // - ); - if (!result) - { - return result; - } - - // - result = lBarTracker.Init( - _inputs.symbol, - lCycle.cycle.period // - ); - if (!result) - { - return result; - } - - // - // Hind ... - result = hCycle.Init( - _inputs, - _hostPeriod, - X_MARKET_CYCLE_HIND, - _hMethod, - _hPeriod // - ); - if (!result) - { - return result; - } - - // - result = hBarTracker.Init( - _inputs.symbol, - hCycle.cycle.period // - ); - if (!result) - { - return result; - } - - // - _inputs.period = cCycle.GetPeriod(); - - // - this.inputs = _inputs; - result = inputs.IsValid(); - - // - return result; - } - - // - // Getter(s) / Setter(s) ... - - // - X121SetupInputs GetInputs() - { - return this.inputs; - } - - // - bool SetInputs( - X121SetupInputs &_inputs // Cycles Configurations - ) - { - // - bool result = Init( - _inputs, - _inputs.symbol, - _inputs.period // - ); - - // - return result; - } - - // - string GetSymbol() - { - return cCycle.GetSymbol(); - } - - // - ENUM_TIMEFRAMES GetPeriod() - { - return cCycle.GetPeriod(); - } - - // - bool ForceState() - { - return forceState; - } - - // - void ForceState(bool value) - { - forceState = value; - } - - // - bool CanProcessBar( - ENUM_X_MARKET_CYCLES cycle = X_MARKET_CYCLE_UNKNOWN // - ) - { - // - bool result = false; - - // - switch (cycle) - { - // - case X_MARKET_CYCLE_SHORT: - // - result = sBarTracker.CanProcessBar(); - break; - - // - case X_MARKET_CYCLE_MEDIUM: - // - result = mBarTracker.CanProcessBar(); - break; - - // - case X_MARKET_CYCLE_LONG: - // - result = lBarTracker.CanProcessBar(); - break; - - // - case X_MARKET_CYCLE_HIND: - // - result = hBarTracker.CanProcessBar(); - break; - - // - default: - case X_MARKET_CYCLE_UNKNOWN: - // - result = cBarTracker.CanProcessBar(); - break; - } - - // - return result; - } - - // - datetime GetNextSignalTime( - ENUM_X_MARKET_CYCLES cycle = X_MARKET_CYCLE_UNKNOWN // - ) - { - // - datetime result = NULL; - - // - switch (cycle) - { - // - case X_MARKET_CYCLE_SHORT: - result = sNextValidSignal; - break; - - // - case X_MARKET_CYCLE_MEDIUM: - result = mNextValidSignal; - break; - - // - case X_MARKET_CYCLE_LONG: - result = lNextValidSignal; - break; - - // - case X_MARKET_CYCLE_HIND: - result = hNextValidSignal; - break; - - // - default: - case X_MARKET_CYCLE_UNKNOWN: - result = cNextValidSignal; - break; - } - - // - return result; - } - - // - void WaitsUntilNextBar( - ENUM_X_MARKET_CYCLES cycle = X_MARKET_CYCLE_UNKNOWN // - ) - { - // - switch (cycle) - { - // - case X_MARKET_CYCLE_SHORT: - // - FillNextBarTime( - sNextValidSignal, - sBarTracker // - ); - sBarTracker.Waits(); - break; - - // - case X_MARKET_CYCLE_MEDIUM: - // - FillNextBarTime( - mNextValidSignal, - mBarTracker // - ); - mBarTracker.Waits(); - break; - - // - case X_MARKET_CYCLE_LONG: - // - FillNextBarTime( - lNextValidSignal, - lBarTracker // - ); - lBarTracker.Waits(); - break; - - // - case X_MARKET_CYCLE_HIND: - // - FillNextBarTime( - hNextValidSignal, - hBarTracker // - ); - hBarTracker.Waits(); - break; - - // - default: - case X_MARKET_CYCLE_UNKNOWN: - // - FillNextBarTime( - cNextValidSignal, - cBarTracker // - ); - cBarTracker.Waits(); - break; - } - } - - // - bool GetConditions( - X121SetupConditions &conditions, // - ENUM_X_MARKET_CYCLES cycle = X_MARKET_CYCLE_UNKNOWN, // - int barIndex = 0, // - int loopback = 5 // - ) - { - // - bool result = false; - - // - switch (cycle) - { - // - case X_MARKET_CYCLE_SHORT: - // - result = sCycle.GetConditions( - conditions, - barIndex, - loopback // - ); - break; - - // - case X_MARKET_CYCLE_MEDIUM: - // - result = mCycle.GetConditions( - conditions, - barIndex, - loopback // - ); - break; - - // - case X_MARKET_CYCLE_LONG: - // - result = lCycle.GetConditions( - conditions, - barIndex, - loopback // - ); - break; - - // - case X_MARKET_CYCLE_HIND: - // - result = hCycle.GetConditions( - conditions, - barIndex, - loopback // - ); - break; - - // - default: - case X_MARKET_CYCLE_UNKNOWN: - // - result = cCycle.GetConditions( - conditions, - barIndex, - loopback // - ); - break; - } - - // - return result; - } - - // - XSCZones *GetZones( - ENUM_X_MARKET_CYCLES cycle = X_MARKET_CYCLE_UNKNOWN, // - int barIndex = 0, // - int numberOfZones = 10 // - ) - { - // - XSCZonesInput zInputs; - zInputs.numberOfZones = numberOfZones; - - // - int length = 0; - ENUM_TIMEFRAMES zPeriod = NULL; - switch (cycle) - { - // - case X_MARKET_CYCLE_SHORT: - // - zPeriod = sCycle.GetPeriod(); - break; - - // - case X_MARKET_CYCLE_MEDIUM: - // - zPeriod = mCycle.GetPeriod(); - break; - - // - case X_MARKET_CYCLE_LONG: - // - zPeriod = lCycle.GetPeriod(); - break; - - // - case X_MARKET_CYCLE_HIND: - // - zPeriod = hCycle.GetPeriod(); - break; - - // - default: - case X_MARKET_CYCLE_UNKNOWN: - // - zPeriod = cCycle.GetPeriod(); - break; - } - - // - ENUM_TIMEFRAMES cPeriod = GetPeriod(); - length = (PeriodSeconds(zPeriod) / PeriodSeconds(cPeriod)) + 1; - - // - zInputs.length = length; - XSCZones *result = new XSCZones( - GetSymbol(), - cPeriod // - ); - if (!result.Init(zInputs)) - { - return NULL; - } - - // - return result; - } - - // - bool ProcessMarket( - XSignal &signal, - X121SetupConditions &conditions, - int &pushers, - string &provider, - double &tp, - double &sl, - ENUM_X_MARKET_CYCLES cycle = X_MARKET_CYCLE_UNKNOWN, - bool allowSupports = false, // Allow Support Signal Generating ... - bool allowLong = false, - bool allowShort = false, - double volume = 0.01, - double slPoint = 100, - bool ignoreSL = false, - double tpPoint = 100, - bool ignoreTP = false, - int barIndex = 0, - int loopback = 5 // - ) - { - // - bool result = false; - - // - result = CanProcessBar( - cycle // - ); - if (!result) - { - return result; - } - - // - result = GetConditions( - conditions, - cycle, // Current Market ... - barIndex, // Bar Index ... - loopback // Loop Back ... - ); - if (!result) - { - return result; - } - - // - // Parse Conditions for Signal ... - result = signalGenerator.HasSignal( - conditions, - signal, - pushers, - provider, - tp, - sl, - allowSupports, - allowLong, - allowShort, - volume, - slPoint, - ignoreSL, - tpPoint, - ignoreTP // - ); - - // - if (result) - { - // - WaitsUntilNextBar( - cycle // - ); - } - - // - return result; - } - - // - // Protected ... -protected: - // - // Private ... -private: - // - // Props ... - - // - X121SetupInputs inputs; // Cycles Configurations - - // - bool forceState; // Force State - - // - // Bar Trackers ... - XBarTracker cBarTracker; - XBarTracker sBarTracker; - XBarTracker mBarTracker; - XBarTracker lBarTracker; - XBarTracker hBarTracker; - - // - datetime cNextValidSignal; - datetime sNextValidSignal; - datetime mNextValidSignal; - datetime lNextValidSignal; - datetime hNextValidSignal; - - // - void FillNextBarTime( - datetime &next, - XBarTracker &tracker // - ) - { - // - next = iTime( - tracker.symbol, - tracker.period, - 0) + - PeriodSeconds(tracker.period); - } -}; - -// \ No newline at end of file diff --git a/Documents/Pack/V1.0/Source/Classes/x-saherelm.x121.setup.xea.mq5 b/Documents/Pack/V1.0/Source/Classes/x-saherelm.x121.setup.xea.mq5 deleted file mode 100644 index d4fd1711..00000000 --- a/Documents/Pack/V1.0/Source/Classes/x-saherelm.x121.setup.xea.mq5 +++ /dev/null @@ -1,4948 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Class Library -// ---------------------------------------------- -// Name: XSCX121SetupCycle -// Description: provides implementation of X121 -// Setup on Specified Market Cycle ... -// -// -// 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.x121.setup.cycle.class.mq5" -#include "../Classes/x-saherelm.xea.class.mq5" - -// -// Definitions ... - -// -// Model all Trades Data as this Structure ... -struct XTradeInfo { - // - int pushers; // Signal Pushers - datetime time; // Issue Time (Open Position) - string symbol; // Trading Symbol - double entry; // Entry Price - double volume; // Volume - string provider; // Signaller - ENUM_TIMEFRAMES period; // Trading Timeframe - ENUM_X_POSITION_TYPES type; // Position Type - - // - ulong ticket; // Position Ticket - double profit; // Profit on Close - double commission; // Commission - double swap; // Swap - string message; // Close Reason - datetime endTime; // End Time - - // - X121SetupConditions cConditions; // Generated Current Conditions - X121SetupConditions sConditions; // Generated Short Conditions - X121SetupConditions mConditions; // Generated Medium Conditions - X121SetupConditions lConditions; // Generated Long Conditions - X121SetupConditions hConditions; // Generated Hind Conditions - - // - // Constructor ... - void XTradeInfo() { - Clean(); - } - - // - // Tools ... - - // - // Cleanup ... - void Clean() { - // - time = NULL; - type = NULL; - symbol = NULL; - period = NULL; - endTime = NULL; - message = NULL; - provider = NULL; - - // - swap = 0; - entry = 0; - ticket = 0; - profit = 0; - volume = 0; - pushers = 0; - commission = 0; - - // - cConditions.Clean(); - sConditions.Clean(); - mConditions.Clean(); - lConditions.Clean(); - hConditions.Clean(); - - // - ResetGrid(); - ResetSupport(); - ResetRecovery(); - } - - // - bool Fill( - const XSignal &_signal, - int _pushers, - bool _allowGrid, - bool _allowRecover, - bool _allowSupport, - X121SetupConditions &_cConditions, - X121SetupConditions &_sConditions, - X121SetupConditions &_mConditions, - X121SetupConditions &_lConditions, - X121SetupConditions &_hConditions // - ) { - // - bool result = false; - - // - result = - // - IsValid(_signal.symbol) && - IsValid(_signal.period) && - IsValid(_signal.provider) - // - ; - - // - if(!result) { - return result; - } - - // - pushers = _pushers; - time = _signal.time; - entry = _signal.entry; - symbol = _signal.symbol; - period = _signal.period; - volume = _signal.volume; - provider = _signal.provider; - type = ToPositionType(_signal.type); - - // - cConditions = _cConditions; - sConditions = _sConditions; - mConditions = _mConditions; - lConditions = _lConditions; - hConditions = _hConditions; - - // - allowGrid = _allowGrid; - allowRecover = _allowRecover; - allowSupport = _allowSupport; - - // - return result; - } - - // - bool IsOwn( - ulong _ticket // - ) { - // - bool result = false; - - // - result = _ticket == ticket; - - // - return result; - } - - // - bool IsOwn( - string _symbol, - string _provider, - ENUM_TIMEFRAMES _period // - ) { - // - bool result = false; - - // - result = - // - IsValid(_symbol) && - IsValid(_provider) && - IsValid(_period) && - // - symbol == _symbol && - provider == _provider && - period == _period - // - ; - - // - return result; - } - - // - // Data Collector ... - - // - bool IsValid() { - // - bool result = false; - - // - result = - // - ticket > 0 && - IsValid(time) && - IsValid(symbol) && - IsValid(period) - // - ; - - // - return result; - } - - // - int GetAge() { - // - int result = -1; - - // - if(!IsValid(symbol) || - !IsValid(time) || - !IsValid(endTime) || - !IsValid(period)) { - return result; - } - - // - int startIndex = iBarShift( - symbol, - period, - time, - false // - ); - - // - int endIndex = iBarShift( - symbol, - period, - endTime, - false // - ); - - // - result = MathAbs(startIndex - endIndex); - - // - return result; - } - - // - string GetFileName() { - // - string result = NULL; - - // - if(!IsValid()) { - return result; - } - - // - result = - // - symbol + "\\" + - ToString(type) + "\\" + - (profit >= 0 ? "Profit" : "Loss") + - "\\" + - provider + "_" + - ToString(ticket) + "_" + - ToString(period) + "_" + - ToFormatString(time) - // - ; - - // - return result; - } - - // - string GetSignalFileName() { - // - string result = NULL; - - // - result = - // - symbol + "\\" + - ToString(type) + "\\" + - provider + "_" + - ToFormatString(time) - // - ; - - // - return result; - } - - // - string ToString( - bool onlySignals = false // - ) { - // - string result = NULL; - - // - string cConditionsStr = cConditions - .GenerateSummary( - false, // Only Commons ... - true, // Only Conditions ... - false, // Include Score ... - false // Include False Conditions ... - ); - string sConditionsStr = sConditions - .GenerateSummary( - false, // Only Commons ... - true, // Only Conditions ... - false, // Include Score ... - false // Include False Conditions ... - ); - string mConditionsStr = mConditions - .GenerateSummary( - false, // Only Commons ... - true, // Only Conditions ... - false, // Include Score ... - false // Include False Conditions ... - ); - string lConditionsStr = lConditions - .GenerateSummary( - false, // Only Commons ... - true, // Only Conditions ... - false, // Include Score ... - false // Include False Conditions ... - ); - string hConditionsStr = hConditions - .GenerateSummary( - false, // Only Commons ... - true, // Only Conditions ... - false, // Include Score ... - false // Include False Conditions ... - ); - - // - int age = GetAge(); - - // - result = - // - (onlySignals ? "" : ToString("Ticket", ticket)) + - ToString("Symbol", symbol) + - ToString("Period", period) + - ToString("Entry", entry) + - ToString("Provider", provider) + - ToString("Type", ToString(type)) + - ToString("Time", time) + - ToString("Pushers", pushers) + - (onlySignals ? "" : "-------------" + "\n" + ToString("Volume", volume) + ToString("Profit", profit) + ToString("Commission", commission) + ToString("Swap", swap) + ToString("End Time", endTime) + ToString("Age", age) + ToString("Message", message)) + - "-------------" + "\n" + - "Conditions" + "\n" + - "-------------" + "\n" + - "-------------" + "\n" + - "CURRENT [" + ToString(cConditions.period) + "]" + "\n" + - "-------------" + "\n" + - cConditionsStr + "\n" + - "-------------" + "\n" + - "SHORT [" + ToString(sConditions.period) + "]" + "\n" + - "-------------" + "\n" + - sConditionsStr + "\n" + - "-------------" + "\n" + - "MEDIUM [" + ToString(mConditions.period) + "]" + "\n" + - "-------------" + "\n" + - mConditionsStr + "\n" + - "-------------" + "\n" + - "LONG [" + ToString(lConditions.period) + "]" + "\n" + - "-------------" + "\n" + - lConditionsStr + "\n" + - "-------------" + "\n" + - "HIND [" + ToString(hConditions.period) + "]" + "\n" + - "-------------" + "\n" + - hConditionsStr + "\n" + - // - "" - // - ; - - // - return result; - } - - // - // These are Some Helpers for Trading Controls and do not relate to Main - // purpose of Trade Handler ... - - // - // Supporting ... - - // - bool allowSupport; // Allow Support - - // - void ResetSupport() { - allowSupport = false; - } - - // - // Retrieve Support Signal ... - bool HasSupport( - XSignal &support // - ) { - // - bool result = false; - - // - return result; - } - - // - // Grid System Calculations ... - - // - int gLevel; // Number of Grids - bool allowGrid; // Allow Grid - double gEntry; // Represents Next Grid Signal's Entry - double gVolume; // Represent Next Grid Signal's Volume - - // - void ResetGrid() { - // - gEntry = 0; - gLevel = 0; - gVolume = 0; - - // - allowGrid = false; - } - - // - void SetGrid( - double nextEntry, - double nextVolume // - ) { - // - gEntry = nextEntry; - gVolume = nextVolume; - } - - // - // Prepare Data For Next Grid ... - void PrepareNextGrid( - double distance, - double volumeMultiplier // - ) { - // - bool isValid = - // - IsValid() && - entry > 0 && - volume > 0 && - distance > 0 && - volumeMultiplier > 0 - // - ; - bool isLong = IsLong(type); - - // - double distancePrice = PointToPrice( - distance, - symbol // - ); - - // - double selectedEntry = - gEntry <= 0 ? entry : gEntry; - double selectedVolume = - gVolume <= 0 ? volume : gVolume; - - // - double nextEntry = - isLong ? selectedEntry - distancePrice : selectedEntry + distancePrice; - double nextVolume = selectedVolume * volumeMultiplier; - - // - SetGrid( - nextEntry, - nextVolume // - ); - } - - // - // Check if a Grid Signal Exists Prepared and - // Provide it ... - bool HasGrid( - XSignal &signal, // Result Signal - double distance, - double volumeMultiplier // - ) { - // - bool result = false; - - // - signal.Clean(); - - // - result = IsValid() && - distance > 0 && - volumeMultiplier > 0; - if(!result) { - return result; - } - - // - bool isLong = IsLong(type); - - // - ENUM_POSITION_TYPE gType = - isLong ? POSITION_TYPE_BUY : POSITION_TYPE_SELL; - - // - double cEntry = GetEntry( - symbol, - gType // - ); - - // - result = - isLong ? cEntry <= gEntry : cEntry >= gEntry; - if(!result) { - return result; - } - - // - result = signal.Prepare( - symbol, - provider, - period, - gType, - X_ORDER_MODE_MARKET, - cEntry, - gVolume, - 0, // SL ... - 0 // TP ... - ); - - // - if(result) { - // - // set Support Token ... - string comment = GenerateSupportTag(ticket); - signal.comment = comment; - - // - PrepareNextGrid( - distance, - volumeMultiplier // - ); - - // - gLevel++; - } - - // - return result; - } - - // - // Recovery Zone System ... - - // - bool allowRecover; // Allow Recover - ENUM_POSITION_TYPE rLastRecoveryType; // Last Executed Recovery Signal's Type - double rLongEntry; // Represent Next Recovery Long Signal's Entry - double rShortEntry; // Represent Next Recovery Short Signal's Entry - double rVolume; // Represent Next Recovery Signal's Volume - double rZoneUpper; // Zone Recovery Upper Bound - double rZoneLower; // Zone Recovery Lower Bound - int rLevel; // Number of Recoveries - - // - void ResetRecovery() { - // - rLevel = 0; - rVolume = 0; - rLongEntry = 0; - rZoneUpper = 0; - rZoneLower = 0; - rShortEntry = 0; - - // - allowRecover = false; - } - - // - void SetRecovery( - double nextLongEntry, - double nextShortEntry, - double zoneUpper, - double zoneLower, - double nextVolume // - ) { - // - rVolume = nextVolume; - rZoneUpper = zoneUpper; - rZoneLower = zoneLower; - rLongEntry = nextLongEntry; - rShortEntry = nextShortEntry; - } - - // - void PrepareNextRecovery( - double distance, // Define Target Based On Zones - double volumeMultiplier, // Volume Multiplier - ENUM_POSITION_TYPE lastType // Last Type - ) { - // - bool isValid = - // - IsValid() && - entry > 0 && - volume > 0 && - distance > 0 && - volumeMultiplier > 0 - // - ; - - // - bool isLong = IsLong(lastType); - - // - double distancePrice = PointToPrice( - distance, - symbol // - ); - - // - double selectedEntry = - isLong ? rLongEntry <= 0 ? entry : rLongEntry : rShortEntry <= 0 ? entry : - rShortEntry; - double selectedVolume = - rVolume <= 0 ? volume : rVolume; - - // - double nextLongEntry = - isLong ? selectedEntry : selectedEntry + distancePrice; - double nextShortEntry = - isLong ? selectedEntry - distancePrice : selectedEntry; - - // - double nextVolume = selectedVolume * volumeMultiplier; - // rLevel % 2 == 1 - // ? volume - // : volume * volumeMultiplier; - - // - double zoneUpper = - rZoneUpper > 0 ? rZoneUpper : isLong ? entry + distancePrice : - entry + (distancePrice * 2); - double zoneLower = - rZoneLower > 0 ? rZoneLower : isLong ? entry + (distancePrice * 2) : - entry - distancePrice; - - // - SetRecovery( - nextLongEntry, - nextShortEntry, - zoneUpper, - zoneLower, - nextVolume // - ); - - // - rLastRecoveryType = lastType; - } - - // - // Check if a Recovery Signal Exists Prepared and - // Provide it ... - bool HasRecovery( - XSignal &signal, // Result Signal ... - double distance, - double volumeMultiplier // - ) { - // - bool result = false; - - // - signal.Clean(); - - // - result = - // - IsValid() && - entry > 0 && - volume > 0 && - distance > 0 && - volumeMultiplier > 0 - // - ; - if(!result) { - return result; - } - - // - double distancePrice = PointToPrice( - distance, - symbol // - ); - - // - bool isLong = IsLong(type); - bool isLastLong = IsLong(rLastRecoveryType); - - // - // Check For Long Recovery ... - double cLongEntry = GetEntry( - symbol, - POSITION_TYPE_BUY // - ); - bool hasLongRecovery = - !isLastLong && - rLongEntry > 0 && cLongEntry >= rLongEntry; - - // - // Check For Short Recovery ... - double cShortEntry = GetEntry( - symbol, - POSITION_TYPE_SELL // - ); - bool hasShortRecovery = - isLastLong && - rShortEntry > 0 && - cShortEntry <= rShortEntry; - - // - result = hasLongRecovery || hasShortRecovery; - if(!result) { - return result; - } - - // - ENUM_POSITION_TYPE rType = - hasLongRecovery ? POSITION_TYPE_BUY : POSITION_TYPE_SELL; - - // - double rEntry = - hasLongRecovery ? cLongEntry : cShortEntry; - - // - double rTP = - hasLongRecovery ? rZoneUpper : rZoneLower; - - // - double rSL = - hasLongRecovery ? rZoneLower : rZoneUpper; - - // - result = signal.Prepare( - symbol, - provider, - period, - rType, - X_ORDER_MODE_MARKET, - rEntry, - rVolume, - 0, // rSL, // SL ... - 0 // rTP // TP ... - ); - if(result) { - // - // set Support Token ... - string comment = GenerateSupportTag(ticket); - signal.comment = comment; - - // - rLevel++; - - // - PrepareNextRecovery( - distance, - volumeMultiplier, - rType // - ); - } - - // - return result; - } -}; - -// -// a Class For Read and Write Trade Info Data in Files ... -class XTradeInfoCollector { - // - // Public ... - public: - // - // Props ... - - // - // Constructor(s) ... - void XTradeInfoCollector( - string _path = NULL // Base Path - ) { - // - mAccount = new XSCAccount(); - - // - if(IsValid(_path)) { - mPath = _path; - } else { - mPath = "XTradeInfo" + "\\" + mAccount.GetCompany(); - } - } - - // - // Deconstructor ... - void ~XTradeInfoCollector() {} - - // - bool IsExists(XTradeInfo &item) { - // - bool result = false; - - // - int mHandler = GetFileHandlerForRead(item); - result = mHandler != INVALID_HANDLE; - FileClose(mHandler); - - // - return result; - } - - // - bool Save(XTradeInfo &item) { - // - bool result = false; - - // - // Check info is Valid ... - result = item.IsValid(); - if(!result) { - return result; - } - - // - string content = item.ToString(); - result = IsValid(content); - if(!result) { - return result; - } - - // - int mHandler = GetFileHandlerForWrite(item); - result = mHandler != INVALID_HANDLE; - if(!result) { - return result; - } - - // - FileWrite(mHandler, content); - FileFlush(mHandler); - FileClose(mHandler); - - // - return result; - } - - // - bool SaveSignal(XTradeInfo &item) { - // - bool result = false; - - // - string content = item.ToString(); - result = IsValid(content); - if(!result) { - return result; - } - - // - int mHandler = GetSignalFileHandlerForWrite(item); - 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 Path ... - - // - XSCAccount *mAccount; - - // - string GetFilePath(XTradeInfo &item) { - // - string fileName = item.GetFileName(); - - // - return GetFilePath(fileName); - } - string GetFilePath(string fileName) { - // - string result = ""; - - // - result = - // - mPath + "\\" + "Trades" + "\\" + fileName + ".x121.log" - // - ; - - // - return result; - } - - // - string GetSignalFilePath(XTradeInfo &item) { - // - string fileName = item.GetSignalFileName(); - - // - return GetSignalFilePath(fileName); - } - string GetSignalFilePath(string fileName) { - // - string result = ""; - - // - result = - // - mPath + "\\" + "Signals" + "\\" + fileName + ".x121.log" - // - ; - - // - return result; - } - - // - int GetFileHandlerForRead(XTradeInfo &item) { - // - int result = INVALID_HANDLE; - - // - string filePath = GetFilePath(item); - if(!IsValid(filePath)) { - return result; - } - - // - result = FileOpen( - filePath, - FILE_READ | FILE_TXT // - ); - - // - return result; - } - int GetFileHandlerForWrite(XTradeInfo &item) { - // - int result = INVALID_HANDLE; - - // - string filePath = GetFilePath(item); - if(!IsValid(filePath)) { - return result; - } - - // - result = FileOpen( - filePath, - FILE_READ | FILE_WRITE | FILE_TXT // - ); - - // - return result; - } - - // - int GetSignalFileHandlerForRead(XTradeInfo &item) { - // - int result = INVALID_HANDLE; - - // - string filePath = GetSignalFilePath(item); - if(!IsValid(filePath)) { - return result; - } - - // - result = FileOpen( - filePath, - FILE_READ | FILE_TXT // - ); - - // - return result; - } - int GetSignalFileHandlerForWrite(XTradeInfo &item) { - // - int result = INVALID_HANDLE; - - // - string filePath = GetSignalFilePath(item); - if(!IsValid(filePath)) { - return result; - } - - // - result = FileOpen( - filePath, - FILE_READ | FILE_WRITE | FILE_TXT // - ); - - // - return result; - } -}; - -// -// a Class for Holding all required data for Specified Trade -// such as: -// - Signal; -// - Position; -// - Conditions; -// - Scores; -// - etc ... -class XTradeHandler { - // - public: - // - // Props ... - - // - // Constructor ... - void XTradeHandler( - XSCTrade *trade // an Instance of Trader Class - ) { - // - Clean(data); - SetSave(false); - mTrader = trade; - collector = new XTradeInfoCollector(); - } - - // - // Getter(s) / Setter(s) ... - - // - // Others ... - - // - bool GetSave() { - return mSave; - } - - // - void SetSave(bool value) { - mSave = value; - } - - // - bool GetSaveSignalsOnly() { - return mSaveSignalsOnly; - } - - // - void SetSaveSignalsOnly(bool value) { - mSaveSignalsOnly = value; - } - - // - // Hedging ... - - // - double MinProfitPerTrade() { - return mMinProfitPerTrade; - } - - // - void MinProfitPerTrade(double value) { - // - if(value < 0) { - value = 0; - } - - // - mMinProfitPerTrade = value; - } - - // - double MinProfitPerVolumeFactor() { - return mMinProfitPerVolumeFactor; - } - - // - void MinProfitPerVolumeFactor(double value) { - // - if(value < 0) { - value = 0; - } - - // - if(value > 0 && value < 0.01) { - value = 0.01; - } - - // - mMinProfitPerVolumeFactor = value; - } - - // - // Trailling Stop ... - - // - bool AllowTrailStop() { - return mAllowTrailStop; - } - - // - void AllowTrailStop(bool value) { - mAllowTrailStop = value; - } - - // - bool DisableTrailingWhenOpposit() { - return mDisableTrailingWhenOpposit; - } - - // - void DisableTrailingWhenOpposit(bool value) { - mDisableTrailingWhenOpposit = value; - } - - // - double NextTrailPoint() { - return mNextTrailPoint; - } - - // - void NextTrailPoint(double value) { - // - if(value < 0) { - value = 0; - } - - // - mNextTrailPoint = value; - } - - // - double FirstTrailPoint() { - return mFirstTrailPoint; - } - - // - void FirstTrailPoint(double value) { - // - if(value < 0) { - value = 0; - } - - // - mFirstTrailPoint = value; - } - - // - double NextTrailDistance() { - return mNextTrailDistance; - } - - // - void NextTrailDistance(double value) { - // - if(value < 0) { - value = 0; - } - - // - mNextTrailDistance = value; - } - - // - double FirstTrailDistance() { - return mFirstTrailDistance; - } - - // - void FirstTrailDistance(double value) { - // - if(value < 0) { - value = 0; - } - - // - mFirstTrailDistance = value; - } - - // - bool EnableTrailling() { - // - bool result = false; - - // - result = - // - AllowTrailStop() && - NextTrailPoint() > 0 && - FirstTrailPoint() > 0 && - NextTrailDistance() > 0 && - FirstTrailDistance() > 0 - // - ; - - // - return result; - } - - // - // Supporting ... - - // - bool AllowSupport() { - return mAllowSupport; - } - - // - void AllowSupport(bool value) { - mAllowSupport = value; - } - - // - bool SupportOnlyForces() { - return mSupportOnlyForces; - } - - // - void SupportOnlyForces(bool value) { - mSupportOnlyForces = value; - } - - // - double SupportDistance() { - return mSupportDistance; - } - - // - void SupportDistance(double value) { - // - if(value < 0) { - value = 0; - } - - // - mSupportDistance = value; - } - - // - int MaxNumberOfSupports() { - return mMaxNumberOfSupports; - } - - // - void MaxNumberOfSupports(int value) { - // - if(value < 0) { - value = 0; - } - - // - mMaxNumberOfSupports = value; - } - - // - double SupportVolumeMultiplier() { - return mSupportVolumeMultiplier; - } - - // - void SupportVolumeMultiplier(double value) { - // - if(value < 1) { - value = 1; - } - - // - mSupportVolumeMultiplier = value; - } - - // - double MaxAllowedSupportVolume() { - return mMaxAllowedSupportVolume; - } - - // - void MaxAllowedSupportVolume(double value) { - // - if(value < 0.01) { - value = 0.01; - } - - // - mMaxAllowedSupportVolume = value; - } - - // - bool EnableSupport() { - // - bool result = false; - - // - result = - // - AllowSupport() && - SupportDistance() > 0 && - MaxNumberOfSupports() >= 0 && - SupportVolumeMultiplier() > 0 - // - ; - - // - return result; - } - - // - // Grid ... - - // - bool AllowGrid() { - return mAllowGrid; - } - - // - void AllowGrid(bool value) { - mAllowGrid = value; - } - - // - bool GridOnlyForces() { - return mGridOnlyForces; - } - - // - void GridOnlyForces(bool value) { - mGridOnlyForces = value; - } - - // - int MaxNumberOfGrids() { - return mMaxNumberOfGrids; - } - - // - void MaxNumberOfGrids(int value) { - // - if(value < 0) { - value = 0; - } - - // - mMaxNumberOfGrids = value; - } - - // - double GridDistance() { - return mGridDistance; - } - - // - void GridDistance(double value) { - // - if(value < 0) { - value = 0; - } - - // - mGridDistance = value; - } - - // - double GridVolumeMultiplier() { - return mGridVolumeMultiplier; - } - - // - void GridVolumeMultiplier(double value) { - // - if(value < 1) { - value = 1; - } - - // - mGridVolumeMultiplier = value; - } - - // - double MaxAllowedGridVolume() { - return mMaxAllowedGridVolume; - } - - // - void MaxAllowedGridVolume(double value) { - // - if(value < 0.01) { - value = 0.01; - } - - // - mMaxAllowedGridVolume = value; - } - - // - // Check Grid Properties to Validate it's Enable or not ... - bool EnableGrid() { - // - bool result = false; - - // - result = - // - AllowGrid() && - GridDistance() > 0 && - MaxNumberOfGrids() >= 0 && - GridVolumeMultiplier() > 0 - // - ; - - // - return result; - } - - // - // Recovery System ... - - // - bool AllowRecovery() { - return mAllowRecovery; - } - - // - void AllowRecovery(bool value) { - mAllowRecovery = value; - } - - // - bool RecoverOnlyForces() { - return mRecoverOnlyForces; - } - - // - void RecoverOnlyForces(bool value) { - mRecoverOnlyForces = value; - } - - // - int MaxNumberOfRecoveries() { - return mMaxNumberOfRecoveries; - } - - // - void MaxNumberOfRecoveries(int value) { - // - if(value < 0) { - value = 0; - } - - // - mMaxNumberOfRecoveries = value; - } - - // - double RecoveryDistance() { - return mRecoveryDistance; - } - - // - void RecoveryDistance(double value) { - // - if(value < 0) { - value = 0; - } - - // - mRecoveryDistance = value; - } - - // - double RecoveryVolumeMultiplier() { - return mRecoveryVolumeMultiplier; - } - - // - void RecoveryVolumeMultiplier(double value) { - // - if(value < 1) { - value = 1; - } - - // - mRecoveryVolumeMultiplier = value; - } - - // - double MaxAllowedRecoveryVolume() { - return mMaxAllowedRecoveryVolume; - } - - // - void MaxAllowedRecoveryVolume(double value) { - // - if(value < 0.01) { - value = 0.01; - } - - // - mMaxAllowedRecoveryVolume = value; - } - - // - // Check Recovery Properties to Validate it's Enable or not ... - bool EnableRecovery() { - // - bool result = false; - - // - result = - // - AllowRecovery() && - RecoveryDistance() > 0 && - MaxNumberOfRecoveries() >= 0 && - RecoveryVolumeMultiplier() > 0 - // - ; - - // - return result; - } - - // - // Tools ... - - // - int Count() { - return ArraySize(data); - } - - // - int FindIndex(ulong ticket) { - // - int result = -1; - - // - int count = Count(); - if(!IsValidSize(count)) { - return result; - } - - // - for(int i = 0; i < count; i++) { - // - XTradeInfo iInfo = data[i]; - - // - bool isOwn = iInfo.IsOwn( - ticket // - ); - if(isOwn) { - // - result = i; - break; - } - } - - // - return result; - } - - // - int FindIndex(XSignal &signal) { - // - int result = -1; - - // - int count = Count(); - if(!IsValidSize(count)) { - return result; - } - - // - for(int i = 0; i < count; i++) { - // - XTradeInfo iInfo = data[i]; - - // - bool isOWN = - // - iInfo.time == signal.time && - iInfo.symbol == signal.symbol && - iInfo.volume == signal.volume && - iInfo.period == signal.period && - iInfo.provider == signal.provider && - iInfo.type == ToPositionType(signal.type) - // - ; - - // - if(isOWN) { - // - result = i; - break; - } - } - - // - return result; - } - - // - void Add( - XSignal &signal, - int pushers, - bool allowGrid, - bool allowRecover, - bool allowSupport, - X121SetupConditions &cConditions, - X121SetupConditions &sConditions, - X121SetupConditions &mConditions, - X121SetupConditions &lConditions, - X121SetupConditions &hConditions // - ) { - // - XTradeInfo info; - bool isFilled = info.Fill( - signal, - pushers, - allowGrid, - allowRecover, - allowSupport, - cConditions, - sConditions, - mConditions, - lConditions, - hConditions // - ); - if(!isFilled) { - return; - } - - // - AddRef( - info, - data // - ); - - // - if(GetSaveSignalsOnly()) { - collector.SaveSignal(info); - } - } - - // - void Remove(XSignal &signal) { - // - int infoIDX = FindIndex(signal); - if(!IsValidIndex(infoIDX)) { - return; - } - - // - ArrayRemove( - data, - infoIDX, - 1 // - ); - } - - // - void Update(XSignal &signal) { - // - if(!signal.IsValid() || !signal.IsExecuted()) { - return; - } - - // - int infoIDX = FindIndex(signal); - if(!IsValidIndex(infoIDX)) { - return; - } - - // - data[infoIDX].ticket = signal.positionId; - - // - // Find Orders for Accessing Commission ... - XDeal deals[]; - int dealsCount = mTrader.GetDeals( - deals, - signal.symbol, - signal.provider, - signal.period, - NULL, - DEAL_ENTRY_IN // Position Open Deal ... - ); - if(!IsValidSize(dealsCount)) { - return; - } - - // - for(int i = 0; i < dealsCount; i++) { - // - XDeal iDeal = deals[i]; - - // - if(iDeal.positionId == signal.positionId) { - data[infoIDX].commission = iDeal.commission; - } - } - - // - // Check if Grid System Enable or Not ... - if(EnableGrid()) { - // - // Here we Prepare Handler Structure for - // Next Grid Position ... - data[infoIDX].PrepareNextGrid( - GridDistance(), - GridVolumeMultiplier() // - ); - } - - // - // Check if Recovery System Enable or Not ... - if(EnableRecovery()) { - // - data[infoIDX].PrepareNextRecovery( - GridDistance(), - GridVolumeMultiplier(), - signal.type // - ); - } - } - - // - void Update(XDeal &deal) { - // - if(!deal.IsValid()) { - return; - } - - // - int infoIDX = FindIndex(deal.positionId); - if(!IsValidIndex(infoIDX)) { - return; - } - - // - data[infoIDX].swap = deal.swap; - data[infoIDX].endTime = deal.time; - data[infoIDX].profit = deal.profit; - - // - string message = deal.reason == DEAL_REASON_TP ? "TP" : "SL"; - data[infoIDX].message = message; - - // - Finish(infoIDX); - } - - // - void Update(XPosition &position) { - // - if(!position.IsValid()) { - return; - } - - // - int infoIDX = FindIndex(position.ticket); - if(!IsValidIndex(infoIDX)) { - return; - } - - // - data[infoIDX].swap = position.swap; - data[infoIDX].endTime = TimeCurrent(); - data[infoIDX].profit = position.profit; - data[infoIDX].message = position.comment; - - // - Finish(infoIDX); - } - - // - // Sync ... - void Sync() { - // - int count = Count(); - if(!IsValidSize(count)) { - return; - } - - // - int mustRemoved[]; - for(int i = 0; i < count; i++) { - // - XTradeInfo iInfo = data[i]; - - // - if(iInfo.ticket > 0 && !mTrader.IsOpen(iInfo.ticket)) { - // - AddSpecific( - i, - mustRemoved // - ); - } - } - - // - int mustRemovedCount = ArraySize(mustRemoved); - if(!IsValidSize(mustRemovedCount)) { - return; - } - - // - for(int i = 0; i < mustRemovedCount; i++) { - // - ArrayRemove( - data, - i, - 1 // - ); - } - } - - // - // Protection Handlers ... - - // - // Handle Do All Protecting ... - int DoProtect( - XSignal &signals[], // if PRotecting Generate Some Support Signals, Holds them here - XSCX121SetupCycles *&setups[] // Number of Setups - ) { - // - int result = 0; - - // - // Calling Protection Algorithms ... - - // - // Trailling ... - if(EnableTrailling()) { - int traillings = HandleTrailling(); - } - - // - if(AllowSupport()) { - // - XSignal supports[]; - int supportsCount = RequestForSupport( - supports, - setups // - ); - - // - if(IsValidSize(supportsCount)) { - // - Copy( - supports, - signals, - false // - ); - } - } - - // - // Grid ... - if(EnableGrid()) { - // - XSignal grids[]; - int gridsCount = RequestForGrid(grids); - if(IsValidSize(gridsCount)) { - // - Copy( - grids, - signals, - false // - ); - } - } - - // - // Recovery ... - if(EnableRecovery()) { - // - XSignal recoveries[]; - int recoveriesCount = RequestForRecovery(recoveries); - if(IsValidSize(recoveriesCount)) { - // - Copy( - recoveries, - signals, - false // - ); - } - } - - // - result = ArraySize(signals); - - // - return result; - } - - // - int GetBreakoutsSignals(XSignal &signals[]) { - // - int result = 0; - - // - Clean(signals); - - // - int count = Count(); - if(!IsValidSize(count)) { - return result; - } - - // - for(int i = 0; i < count; i++) { - // - double iEntry = data[i].entry; - string iSymbol = data[i].symbol; - ENUM_TIMEFRAMES iPeriod = data[i].period; - ENUM_X_POSITION_TYPES iType = data[i].type; - - // - bool isLong = IsLong(iType); - ENUM_POSITION_TYPE iPType = isLong ? POSITION_TYPE_BUY : POSITION_TYPE_SELL; - - // - double cEntry = GetEntry( - iSymbol, - iPType // - ); - - // - XOHCL cBar; - bool isInited = cBar.Init( - iSymbol, - iPeriod, - 1 // - ); - if(!isInited) { - continue; - } - - // - bool isBullish = cBar.IsBullish(); - bool isBreakUp = cBar.IsBreakUp(iEntry); - - // - bool isBearish = cBar.IsBearish(); - bool isBreakDown = cBar.IsBreakDown(iEntry); - - // - bool isBreaked = - isLong ? isBullish && isBreakUp && cEntry > iEntry : isBearish && isBreakDown && cEntry < iEntry; - - // - if(isBreaked) { - // - // Update Date of TradeInfo ... - data[i].entry = cEntry; - data[i].time = TimeCurrent(); - - // - // Generate Signal ... - XSignal iSignal; - bool isPrepared = iSignal.Prepare( - data[i].symbol, - data[i].provider, - data[i].period, - iPType, - X_ORDER_MODE_MARKET, - data[i].entry, - data[i].volume, - 0, - 0 // - ); - - // - // Add Signal to Result ... - if(isPrepared) { - // - AddRef( - iSignal, - signals // - ); - } - } - - // // - // double hotLevels[]; - - // // - // AddSpecific( - // 0.25, - // hotLevels // - // ); - - // // - // AddSpecific( - // 0.20, - // hotLevels // - // ); - - // // - // AddSpecific( - // 0.12, - // hotLevels // - // ); - - // // - // XSCZonesInput zonesInput; - // zonesInput.length = 71; - // zonesInput.numberOfZones = 10; - // XSCZones *zones = new XSCZones( - // iSymbol, - // _Period // - // ); - - // // - // zonesInput.AddLevelColor( - // hotLevels[0], - // clrRed // - // ); - // zonesInput.AddLevelColor( - // hotLevels[1], - // clrOrange // - // ); - // zonesInput.AddLevelColor( - // hotLevels[2], - // clrLightCoral // - // ); - // bool canUseZones = zones.Init(zonesInput); - - // // - // XSCCFInput cfInputs; - // cfInputs.Default(); - // XSCCF *cf = new XSCCF( - // iSymbol, - // _Period // - // ); - // bool canUseCF = cf.Init(cfInputs); - - // // - // XSCTrendInput tInputs; - // tInputs.Default(); - // XSCTrend *trend = new XSCTrend( - // iSymbol, - // _Period // - // ); - // bool canUseTrend = trend.Init(tInputs); - - // if (canUseCF && canUseTrend && canUseZones) - // { - // // - // // cf.Draw(); - // trend.Draw(); - // // zones.Draw(); - // Print("Use CF ..."); - // // cf.Remove(); - // // trend.Remove(); - // // zones.Remove(); - // } - } - - // - result = ArraySize(signals); - - // - return result; - } - - // - // Protected ... - protected: - // - // Props ... - XSCTrade *mTrader; - XTradeInfo data[]; - XTradeInfoCollector *collector; - - // - bool mSave; // Save Results ... - bool mSaveSignalsOnly; // Save Only Signals and COnditions - - // - // Hedging ... - double mMinProfitPerTrade; // Minimum Required Profit for Hedging - double mMinProfitPerVolumeFactor; // Minimum Required Profit for Hedging Per Volume - - // - // Trailling ... - bool mAllowTrailStop; // Enable Trailling Stop Losses - bool mDisableTrailingWhenOpposit; // Disable Trailling When has Opposite In Drawdown - double mNextTrailPoint; // Next Trailling Step - double mFirstTrailPoint; // First Stop Trail - double mFirstTrailDistance; // Start Trailling Distance - double mNextTrailDistance; // Next Trailling Distance - - // - // Supporting ... - bool mAllowSupport; // Allow Support Signals - bool mSupportOnlyForces; // Support Only Force Signals - double mSupportDistance; // Supporting Distance - int mMaxNumberOfSupports; // Max Number of Support Signals - double mSupportVolumeMultiplier; // Support Signals Volume Multiplier - double mMaxAllowedSupportVolume; // Max Allowed Support Signals Volume - - // - // Grid ... - bool mAllowGrid; // Allow Grid Signals - bool mGridOnlyForces; // Grid Only Force Signals - int mMaxNumberOfGrids; // Max Number of Grid Signals - double mGridDistance; // Grid Distance - double mGridVolumeMultiplier; // Grid Volume Multiplier - double mMaxAllowedGridVolume; // Max Allowed Grid Signals Volume - - // - // Recovery ... - bool mAllowRecovery; // Allow Recovery Signals - bool mRecoverOnlyForces; // Recover Only Force Signals - int mMaxNumberOfRecoveries; // Max Number of Recovery Signals - double mRecoveryDistance; // Recovery Distance - double mRecoveryVolumeMultiplier; // Recovery Volume Multiplier - double mMaxAllowedRecoveryVolume; // Max Allowed Recovery Signals Volume - - // - // Tools ... - - // - void Finish(int index) { - // - XTradeInfo info = data[index]; - if(!info.IsValid()) { - return; - } - - // - ArrayRemove( - data, - index, - 1 // - ); - - // - if(GetSave()) { - collector.Save(info); - } - } - - // - // Protection Methods ... - - // - int HandleTrailling() { - // - int result = 0; - - // - // Check Trailling is Enabled or not ... - if(!EnableTrailling()) { - return result; - } - - // - // Do Synch Before Start Trailing ... - Sync(); - - // - // Since Trailing Done based On In Profit Positions ... - // First we Check if ... - XPosition positions[]; - XPosition inDPositions[]; - XPosition inPPositions[]; - int positionsCount = mTrader.GetPositions(positions); - if(!IsValidSize(positionsCount)) { - return result; - } - - // - int inDPositionsCount = ExtractInDrawdownPositions( - positions, - inDPositions // - ); - int inPPositionsCount = ExtractInProfitPositions( - positions, - inPPositions // - ); - if(!IsValidSize(inPPositionsCount)) { - return result; - } - - // - for(int i = 0; i < inPPositionsCount; i++) { - // - XPosition iPosition = inPPositions[i]; - - // - // ignore Support Positions ... - bool isSupport = IsSupport(iPosition.comment); - if(isSupport) { - continue; - } - - // - // Only Trail Positions which they Hasnt any Support ... - bool hasSupport = mTrader.HasSupport(iPosition.ticket); - result = !hasSupport; - if(!result) { - return result; - } - - // - // Find Positin Info Index ... - int idx = FindIndex(iPosition.ticket); - if(!IsValidIndex(idx)) { - continue; - } - - // - bool isLong = IsLong(iPosition.type); - - // - // Here we Select Price for SL Trailling ... - double usedPrice = 0; - if(iPosition.sl != 0) { - // - if(isLong) { - // - if(iPosition.sl < iPosition.entry) { - usedPrice = iPosition.entry; - } else { - usedPrice = iPosition.sl; - } - } else { - // - if(iPosition.sl > iPosition.entry) { - usedPrice = iPosition.entry; - } else { - usedPrice = iPosition.sl; - } - } - } else { - usedPrice = iPosition.entry; - } - - // - double nextTrailPoint = NextTrailPoint(); - double firstTrailPoint = FirstTrailPoint(); - double nextTrailDistance = NextTrailDistance(); - double firstTrailDistance = FirstTrailDistance(); - - // - bool isFirstTrail = usedPrice == iPosition.entry; - - // - double usedTrailDiff = - isFirstTrail ? MathMax(firstTrailPoint, firstTrailDistance) : MathMax(nextTrailPoint, nextTrailDistance); - - // - double iExit = GetExit( - iPosition.symbol, - iPosition.type // - ); - double iPriceDistance = MathAbs(usedPrice - iExit); - double iPriceDistanceInPoint = PriceToPoint( - iPriceDistance, - iPosition.symbol // - ); - - // - bool canTrail = iPriceDistanceInPoint >= usedTrailDiff; - if(!canTrail) { - continue; - } - - // - // Check Opposit Side Position ... - // if Exists, dont Trail ... - if(DisableTrailingWhenOpposit() && IsValidSize(inDPositionsCount)) { - // - bool canTrail = true; - ENUM_POSITION_TYPE oppositType = GetOpposit(iPosition.type); - for(int j = 0; j < inDPositionsCount; j++) { - // - XPosition inDPosition = inDPositions[j]; - - // - bool isOpposit = - inDPosition.symbol == iPosition.symbol && - inDPosition.type == oppositType; - if(isOpposit) { - // - canTrail = false; - break; - } - } - - // - if(!canTrail) { - continue; - } - } - - // - usedTrailDiff = - isFirstTrail ? MathMin(firstTrailPoint, firstTrailDistance) : MathMin(nextTrailPoint, nextTrailDistance); - double usedTrailDiffPrice = PointToPrice( - usedTrailDiff, - iPosition.symbol // - ); - - // - double sl = - isLong ? usedPrice + usedTrailDiffPrice : usedPrice - usedTrailDiffPrice; - string comment = PrepareSLTrailTag(iPosition.comment); - - // - bool isModified = mTrader.Modify( - iPosition.ticket, - sl, - iPosition.tp, - comment // - ); - if(isModified) { - result++; - } - } - - // - return result; - } - - // - int RequestForSupport( - XSignal &signals[], - XSCX121SetupCycles *&setups[] // - ) { - // - int result = 0; - - // - Clean(signals); - - // - if(!AllowSupport()) { - return result; - } - - // - Sync(); - - // - int count = Count(); - if(!IsValidSize(count)) { - return result; - } - - // - for(int i = 0; i < count; i++) { - // - XSignal iSupport; - double iPivot = -1; - int iPivotIDX = -1; - bool hasSupport = data[i].HasSupport( - iSupport // - ); - if(hasSupport) { - // - AddRef( - iSupport, - signals // - ); - } - } - - // - result = ArraySize(signals); - - // - // TODO: Complete this Later ... - return result; - - // - // Validate Setups Count ... - // int setupsCount = ArraySize(setups); - // if (!IsValidSize(setupsCount)) - // { - // return result; - // } - - // // - // // Implement Supporting Mechanism ... - - // // - // // Extracting In Drawdown Positions ... - // XPosition positions[]; - // int positionsCount = mTrader.GetInDrawdownPositions( - // positions // - // ); - // if (!IsValidSize(positionsCount)) - // { - // return result; - // } - - // // - // double supportDistance = SupportDistance(); - // int maxNUmberOfSupports = MaxNumberOfSupports(); - // double maxAllowedVolume = MaxAllowedSupportVolume(); - // double volumeMultiplier = SupportVolumeMultiplier(); - - // // - // X121SignalGenerator signalGenerator; - - // // - // for (int i = 0; i < positionsCount; i++) - // { - // // - // XPosition iPosition = positions[i]; - - // // - // // Check Position is not Support Position ... - // bool isSupport = IsSupport(iPosition.comment); - // if (isSupport) - // { - // continue; - // } - - // // - // // Find Related Setp ... - // int idx = FindSetupIndex( - // iPosition.symbol, - // setups // - // ); - // if (!IsValidIndex(idx)) - // { - // continue; - // } - - // // - // int index = FindIndex(iPosition.ticket); - // if (!IsValidIndex(index)) - // { - // continue; - // } - - // // - // // Check Position must atleast 20 Point in drawdown ... - - // // - // double onePointPrice = PointToPrice( - // 1, - // iPosition.symbol // - // ); - - // // - // double iExitPrice = GetExit( - // iPosition.symbol, - // iPosition.type // - // ); - - // // - // double priceDiff = MathAbs(iPosition.entry - iExitPrice); - // double priceDiffPoints = priceDiff / onePointPrice; - - // // - // bool isFarEnough = priceDiffPoints >= (supportDistance / 2); - // if (!isFarEnough) - // { - // continue; - // } - - // // - // // Check Support COunts and etc ... - // // implementing supporting mechanis ... - - // // - // } - - // // - // result = ArraySize(signals); - - // - return result; - } - - // - int RequestForGrid(XSignal &signals[]) { - // - int result = 0; - - // - Clean(signals); - - // - if(!EnableGrid()) { - return result; - } - - // - int maxAllowed = MaxNumberOfGrids(); - double maxAllowedVolume = MaxAllowedGridVolume(); - - // - int count = Count(); - if(!IsValidSize(count)) { - return result; - } - - // - for(int i = 0; i < count; i++) { - // - // Check Count ... - bool isMaxPassed = - maxAllowed <= 0 ? true : data[i].gLevel < maxAllowed; - if(!isMaxPassed) { - continue; - } - - // - XSignal iSignal; - bool hasGrid = data[i].HasGrid( - iSignal, - GridDistance(), - GridVolumeMultiplier() // - ); - - // - if(hasGrid) { - // - // Check Max Volume ... - iSignal.volume = - maxAllowedVolume <= 0 ? iSignal.volume : MathMin(iSignal.volume, maxAllowedVolume); - - // - AddRef( - iSignal, - signals // - ); - } - } - - // - result = ArraySize(signals); - - // - return result; - } - - // - int RequestForRecovery(XSignal &signals[]) { - // - int result = 0; - - // - Clean(signals); - - // - if(!EnableRecovery()) { - return result; - } - - // - int maxAllowed = MaxNumberOfRecoveries(); - double maxAllowedVolume = MaxAllowedRecoveryVolume(); - - // - int count = Count(); - if(!IsValidSize(count)) { - return result; - } - - // - for(int i = 0; i < count; i++) { - // - // Check Count ... - bool isMaxPassed = - maxAllowed <= 0 ? true : data[i].rLevel < maxAllowed; - if(!isMaxPassed) { - continue; - } - - // - XSignal iSignal; - bool hasRecovery = data[i].HasRecovery( - iSignal, - RecoveryDistance(), - RecoveryVolumeMultiplier() // - ); - - // - if(hasRecovery) { - // - // Check Max Volume ... - iSignal.volume = - maxAllowedVolume <= 0 ? iSignal.volume : MathMin(iSignal.volume, maxAllowedVolume); - - // - AddRef( - iSignal, - signals // - ); - } - } - - // - result = ArraySize(signals); - - // - return result; - } - - // - int FindSetupIndex( - string symbol, - XSCX121SetupCycles *&setups[] // - ) { - // - int result = 0; - - // - if(!IsValid(symbol)) { - return result; - } - - // - for(int i = 0; i < ArraySize(setups); i++) { - // - if(setups[i].GetSymbol() == symbol) { - // - result = i; - break; - } - } - - // - return result; - } - - // - void AddHotLevelsToZones( - XSCZones *zones // - ) { - // - zones.AddLevelColor( - 0.25, - clrRed // - ); - zones.AddLevelColor( - 0.20, - clrOrange // - ); - zones.AddLevelColor( - 0.15, - clrYellow // - ); - } -}; - -// -// Class ... -class XSCX121SetupEA : public XSCBaseEA { - // - // Public ... - public: - // - // Props ... - X121SignalGenerator signalGenerator; - - // - // Constructors ... - XSCX121SetupEA( - // - // XTrade Class Requirements ... - int slippage, // Specify Slippage - ulong magicNumber, // Specify Magic Number - // - // XSCTrade Event Handlers ... - TOnSignal onSignal = NULL, // On Signal Recieved Event Handler - TOnModify onModifyPosition = NULL, // On Modify Position Event Handler - TOnStopLoss onStopLossTriggered = NULL, // On StopLoass Triggered Event Handler - TOnTakeProfit onTakeProfitTriggered = NULL, // On TakeProfit Triggered Event Handler - TOnForceClose onForceClosePosition = NULL, // On Force Close Position Event Handler - TOnPartialClose onPartialClosePosition = NULL, // On Partial Close Position Event Handler - TOnDealsChanged onDealsChangedHandler = NULL, // On Deals Changed Event Handler - TOnOrdersChanged onOrdersChangedHandler = NULL, // On Orders Changed Event Handler - TOnPositionsChanged onPositionsChangedHandler = NULL, // On Positions Changed Event Handler - TOnTradeStateChanged onTradeStateChangedHandler = NULL // On Trade State Changed Event Handler - ) : XSCBaseEA(slippage, - magicNumber, - onSignal, - onModifyPosition, - onStopLossTriggered, - onTakeProfitTriggered, - onForceClosePosition, - onPartialClosePosition, - onDealsChangedHandler, - onOrdersChangedHandler, - onPositionsChangedHandler, - onTradeStateChangedHandler // - ) { - // - mTradeHandler = new XTradeHandler(mTrader); - - // - // Implement Default Configs ... - DefaultConfigs(); - } - - // - // Deconstructor ... - ~XSCX121SetupEA() { - // - delete mTradeHandler; - - // - Clean(mSetups); - } - - // - bool AddSetup(XSCX121SetupCycles *setup) { - // - bool result = false; - - // - result = setup != NULL; - if(!result) { - return result; - } - - // - Add( - setup, - mSetups // - ); - - // - return result; - } - - // - // Getter(s) / Setter(s) ... - - // - /// Signals ... - - // - bool AllowLong() { - return mAllowLong; - } - - // - void AllowLong(bool value) { - mAllowLong = value; - } - - // - bool AllowShort() { - return mAllowShort; - } - - // - void AllowShort(bool value) { - mAllowShort = value; - } - - // - int DelayBetweenTwoSignal() { - return mDelayBetweenTwoSignal; - } - - // - void DelayBetweenTwoSignal(int value) { - // - if(value < 0) { - value = 0; - } - - // - mDelayBetweenTwoSignal = value; - } - - // - int ReuiredSignalVerifications() { - return mReuiredSignalVerifications; - } - - // - void ReuiredSignalVerifications(int value) { - // - if(value < 1) { - value = 1; - } - - // - mReuiredSignalVerifications = value; - } - - // - bool GetVerificationFromOtherTimeFrames() { - return mGetVerificationFromOtherTimeFrames; - } - - // - void GetVerificationFromOtherTimeFrames(bool value) { - mGetVerificationFromOtherTimeFrames = value; - } - - // - bool ExecuteSignalsOnBreakout() { - return mExecuteSignalsOnBreakout; - } - - // - void ExecuteSignalsOnBreakout(bool value) { - mExecuteSignalsOnBreakout = value; - } - - // - // Risk Management ... - - // - double Volume() { - return mVolume; - } - - // - void Volume(double value) { - // - if(value < 0.01) { - value = 0.01; - } - - // - mVolume = value; - } - - // - double TPPoint() { - return mTPPoint; - } - - // - void TPPoint(double value) { - // - if(value < 0) { - value = 0; - } - - // - mTPPoint = value; - } - - // - double SLPoint() { - return mSLPoint; - } - - // - void SLPoint(double value) { - // - if(value < 0) { - value = 0; - } - - // - mSLPoint = value; - } - - // - int MaxAllowedTrades() { - return mMaxAllowedTrades; - } - - // - void MaxAllowedTrades(int value) { - // - if(value < 0) { - value = 0; - } - - // - mMaxAllowedTrades = value; - // mTrader.SetMaxAllowedPositions(value); - } - - // - bool UseMaxAllowedPerDirection() { - return mUseMaxAllowedPerDirection; - } - - // - void UseMaxAllowedPerDirection(bool value) { - mUseMaxAllowedPerDirection = value; - } - - // - bool IgnoreTP() { - return mIgnoreTP; - } - - // - void IgnoreTP(bool value) { - mIgnoreTP = value; - } - - // - bool IgnoreSL() { - return mIgnoreSL; - } - - // - void IgnoreSL(bool value) { - mIgnoreSL = value; - } - - // - bool IncreaseNextSignalsVolume() { - return mIncreaseNextSignalsVolume; - } - - // - void IncreaseNextSignalsVolume(bool value) { - mIncreaseNextSignalsVolume = value; - } - - // - double IncreaseNextSignalsVolumeMultiplier() { - return mIncreaseNextSignalsVolumeMultiplier; - } - - // - void IncreaseNextSignalsVolumeMultiplier(double value) { - // - if(value <= 0) { - value = 0; - } - - // - mIncreaseNextSignalsVolumeMultiplier = value; - } - - // - bool AcceptNextDirectionalSignalsWhenFirstInProfit() { - return mAcceptNextDirectionalSignalsWhenFirstInProfit; - } - - // - void AcceptNextDirectionalSignalsWhenFirstInProfit(bool value) { - mAcceptNextDirectionalSignalsWhenFirstInProfit = value; - } - - // - // Signalling ... - - // - int StartSignallingHoure() { - return mStartSignallingHoure; - } - - // - void StartSignallingHoure(int value) { - // - if(value < -1) { - value = -1; - } - - // - mStartSignallingHoure = value; - } - - // - int EndSignallingHoure() { - return mEndSignallingHoure; - } - - // - void EndSignallingHoure(int value) { - // - if(value < -1) { - value = -1; - } - - // - mEndSignallingHoure = value; - } - - // - int CloseOnSpecificTime() { - return mCloseOnSpecificTime; - } - - // - void CloseOnSpecificTime(int value) { - // - if(value < -1) { - value = -1; - } - - // - mCloseOnSpecificTime = value; - } - - // - bool CloseOnOpposit() { - return mCloseOnOpposit; - } - - // - void CloseOnOpposit(bool value) { - mCloseOnOpposit = value; - } - - // - // Trailling ... - - // - bool AllowTrailStop() { - return mTradeHandler.AllowTrailStop(); - } - - // - void AllowTrailStop(bool value) { - mTradeHandler.AllowTrailStop(value); - } - - // - bool DisableTrailingWhenOpposit() { - return mTradeHandler.DisableTrailingWhenOpposit(); - } - - // - void DisableTrailingWhenOpposit(bool value) { - mTradeHandler.DisableTrailingWhenOpposit(value); - } - - // - double NextTrailPoint() { - return mTradeHandler.NextTrailPoint(); - } - - // - void NextTrailPoint(double value) { - mTradeHandler.NextTrailPoint(value); - } - - // - double FirstTrailPoint() { - return mTradeHandler.FirstTrailPoint(); - } - - // - void FirstTrailPoint(double value) { - mTradeHandler.FirstTrailPoint(value); - } - - // - double NextTrailDistance() { - return mTradeHandler.NextTrailDistance(); - } - - // - void NextTrailDistance(double value) { - mTradeHandler.NextTrailDistance(value); - } - - // - double FirstTrailDistance() { - return mTradeHandler.FirstTrailDistance(); - } - - // - void FirstTrailDistance(double value) { - mTradeHandler.FirstTrailDistance(value); - } - - // - // Supporting ... - - // - bool AllowSupport() { - return mTradeHandler.AllowSupport(); - } - - // - void AllowSupport(bool value) { - mTradeHandler.AllowSupport(value); - } - - // - bool SupportOnlyForces() { - return mTradeHandler.SupportOnlyForces(); - } - - // - void SupportOnlyForces(bool value) { - mTradeHandler.SupportOnlyForces(value); - } - - // - bool EnableSupport() { - return mTradeHandler.EnableSupport(); - } - - // - double SupportDistance() { - return mTradeHandler.SupportDistance(); - } - - // - void SupportDistance(double value) { - mTradeHandler.SupportDistance(value); - } - - // - int MaxNumberOfSupports() { - return mTradeHandler.MaxNumberOfSupports(); - } - - // - void MaxNumberOfSupports(int value) { - mTradeHandler.MaxNumberOfSupports(value); - } - - // - double SupportVolumeMultiplier() { - return mTradeHandler.SupportVolumeMultiplier(); - } - - // - void SupportVolumeMultiplier(double value) { - mTradeHandler.SupportVolumeMultiplier(value); - } - - // - double MaxAllowedSupportVolume() { - return mTradeHandler.MaxAllowedSupportVolume(); - } - - // - void MaxAllowedSupportVolume(double value) { - mTradeHandler.MaxAllowedSupportVolume(value); - } - - // - // Grid ... - - // - bool AllowGrid() { - return mTradeHandler.AllowGrid(); - } - - // - void AllowGrid(bool value) { - mTradeHandler.AllowGrid(value); - } - - // - bool GridOnlyForces() { - return mTradeHandler.GridOnlyForces(); - } - - // - void GridOnlyForces(bool value) { - mTradeHandler.GridOnlyForces(value); - } - - // - bool EnableGrid() { - return mTradeHandler.EnableGrid(); - } - - // - int MaxNumberOfGrids() { - return mTradeHandler.MaxNumberOfGrids(); - } - - // - void MaxNumberOfGrids(int value) { - mTradeHandler.MaxNumberOfGrids(value); - } - - // - double GridDistance() { - return mTradeHandler.GridDistance(); - } - - // - void GridDistance(double value) { - mTradeHandler.GridDistance(value); - } - - // - double GridVolumeMultiplier() { - return mTradeHandler.GridVolumeMultiplier(); - } - - // - void GridVolumeMultiplier(double value) { - mTradeHandler.GridVolumeMultiplier(value); - } - - // - double MaxAllowedGridVolume() { - return mTradeHandler.MaxAllowedGridVolume(); - } - - // - void MaxAllowedGridVolume(double value) { - mTradeHandler.MaxAllowedGridVolume(value); - } - - // - // Recovery System ... - - // - bool AllowRecovery() { - return mTradeHandler.AllowRecovery(); - } - - // - void AllowRecovery(bool value) { - mTradeHandler.AllowRecovery(value); - } - - // - bool RecoverOnlyForces() { - return mTradeHandler.RecoverOnlyForces(); - } - - // - void RecoverOnlyForces(bool value) { - mTradeHandler.RecoverOnlyForces(value); - } - - // - bool EnableRecovery() { - return mTradeHandler.EnableRecovery(); - } - - // - int MaxNumberOfRecoveries() { - return mTradeHandler.MaxNumberOfRecoveries(); - } - - // - void MaxNumberOfRecoveries(int value) { - mTradeHandler.MaxNumberOfRecoveries(value); - } - - // - double RecoveryDistance() { - return mTradeHandler.RecoveryDistance(); - } - - // - void RecoveryDistance(double value) { - mTradeHandler.RecoveryDistance(value); - } - - // - double RecoveryVolumeMultiplier() { - return mTradeHandler.RecoveryVolumeMultiplier(); - } - - // - void RecoveryVolumeMultiplier(double value) { - mTradeHandler.RecoveryVolumeMultiplier(value); - } - - // - double MaxAllowedRecoveryVolume() { - return mTradeHandler.MaxAllowedRecoveryVolume(); - } - - // - void MaxAllowedRecoveryVolume(double value) { - mTradeHandler.MaxAllowedRecoveryVolume(value); - } - - // - // Others ... - - // - bool SaveResults() { - return mTradeHandler.GetSave(); - } - - // - void SaveResults(bool value) { - mTradeHandler.SetSave(value); - } - - // - bool SaveSignalsOnly() { - return mTradeHandler.GetSaveSignalsOnly(); - } - - // - void SaveSignalsOnly(bool value) { - mTradeHandler.SetSaveSignalsOnly(value); - } - - // - double MinFreeMargingForOpenTrades() { - return mMinFreeMargingForOpenTrades; - } - - // - void MinFreeMargingForOpenTrades(double value) { - // - if(value < 0) { - value = 0; - } - - // - mMinFreeMargingForOpenTrades = value; - } - - // - // Hedging ... - - // - double MinProfitPerTrade() { - return mTradeHandler.MinProfitPerTrade(); - } - - // - void MinProfitPerTrade(double value) { - // - MinRequiredProfitPerTrade(value); - mTradeHandler.MinProfitPerTrade(value); - } - - // - double MinProfitPerVolumeFactor() { - return mTradeHandler.MinProfitPerVolumeFactor(); - } - - // - void MinProfitPerVolumeFactor(double value) { - // - MinRequiredProfitPerVolumeFactor(value); - mTradeHandler.MinProfitPerVolumeFactor(value); - } - - // - // Overrides ... - - // - // Customize Token ... - string GetToken() override { - return GetSpecificToken(this); - } - - // - string GetTag() override { - return this.GetToken(); - } - - // - // Tools ... - - // - // Check Provider for any Guards ... - bool CheckForGuard(XGuard &guards[]) override { - // - bool result = false; - - // - return result; - } - - // - // Request Provider to Collect all - // Potentially Signals and then - // filters theme here and passed them - // for Executing ... - int RequestForSignal( - XSignal &signals[] // Holds Signals ... - ) override { - // - bool result = 0; - - // - Clean(signals); - - // - if(!IsEnable()) { - return result; - } - - // - // IMPLEMENT ... - int count = CountSetups(); - result = IsValidSize(count); - if(!result) { - return result; - } - - // - // Current ... - double cTP = 0; - double cSL = 0; - XSignal cSignal; - int cPusher = 0; - bool cHasSignal = false; - string cProvider = NULL; - X121SetupConditions cConditions; - - // - // Short ... - double sTP = 0; - double sSL = 0; - XSignal sSignal; - int sPusher = 0; - bool sHasSignal = false; - string sProvider = NULL; - X121SetupConditions sConditions; - - // - // Medium ... - double mTP = 0; - double mSL = 0; - XSignal mSignal; - int mPusher = 0; - bool mHasSignal = false; - string mProvider = NULL; - X121SetupConditions mConditions; - - // - // Long ... - double lTP = 0; - double lSL = 0; - XSignal lSignal; - int lPusher = 0; - bool lHasSignal = false; - string lProvider = NULL; - X121SetupConditions lConditions; - - // - // Hind ... - double hTP = 0; - double hSL = 0; - XSignal hSignal; - int hPusher = 0; - bool hHasSignal = false; - string hProvider = NULL; - X121SetupConditions hConditions; - - // - bool canSupport = - // - EnableSupport() && - !SupportOnlyForces() - // - ; - bool canGrid = - // - EnableGrid() && - !GridOnlyForces() - // - ; - bool canRecover = - // - EnableRecovery() && - !RecoverOnlyForces() - // - ; - - // - double volume = Volume(); - double slPoint = SLPoint(); - double tpPoint = TPPoint(); - bool ignoreSL = IgnoreSL(); - bool ignoreTP = IgnoreTP(); - bool allowLong = AllowLong(); - bool allowShort = AllowShort(); - - // - bool useCMarket = true; - bool useSMarket = true; - bool useMMarket = true; - bool useLMarket = true; - bool useHMarket = true; - - // - for(int i = 0; i < count; i++) { - // - // Current Market ... - - // - cPusher = 0; - cSignal.Clean(); - cProvider = NULL; - cHasSignal = false; - cConditions.Clean(); - - // - cHasSignal = !useCMarket ? false : mSetups[i].ProcessMarket(cSignal, cConditions, cPusher, cProvider, cTP, cSL, X_MARKET_CYCLE_UNKNOWN, canSupport, allowLong, allowShort, volume, slPoint, ignoreSL, tpPoint, ignoreTP, 0, - 5 // - ); - - // - // Short Market ... - - // - sPusher = 0; - sSignal.Clean(); - sProvider = NULL; - sHasSignal = false; - sConditions.Clean(); - - // - sHasSignal = !useSMarket ? false : mSetups[i].ProcessMarket(sSignal, sConditions, sPusher, sProvider, sTP, sSL, X_MARKET_CYCLE_SHORT, canSupport, allowLong, allowShort, volume, slPoint, ignoreSL, tpPoint, ignoreTP, 0, - 5 // - ); - - // - // Medium Market ... - - // - mPusher = 0; - mSignal.Clean(); - mProvider = NULL; - mHasSignal = false; - mConditions.Clean(); - - // - mHasSignal = !useMMarket ? false : mSetups[i].ProcessMarket(mSignal, mConditions, mPusher, mProvider, mTP, mSL, X_MARKET_CYCLE_MEDIUM, canSupport, allowLong, allowShort, volume, slPoint, ignoreSL, tpPoint, ignoreTP, 0, - 5 // - ); - - // - // Long Market ... - - // - lPusher = 0; - lSignal.Clean(); - lProvider = NULL; - lHasSignal = false; - lConditions.Clean(); - - // - lHasSignal = !useLMarket ? false : mSetups[i].ProcessMarket(lSignal, lConditions, lPusher, lProvider, lTP, lSL, X_MARKET_CYCLE_LONG, canSupport, allowLong, allowShort, volume, slPoint, ignoreSL, tpPoint, ignoreTP, 0, - 5 // - ); - - // - // Hind Market ... - - // - hPusher = 0; - hSignal.Clean(); - hProvider = NULL; - hHasSignal = false; - hConditions.Clean(); - - // - hHasSignal = !useHMarket ? false : mSetups[i].ProcessMarket(hSignal, hConditions, hPusher, hProvider, hTP, hSL, X_MARKET_CYCLE_HIND, canSupport, allowLong, allowShort, volume, slPoint, ignoreSL, tpPoint, ignoreTP, 0, - 5 // - ); - - // - // Parse Signals and Add them for Executing ... - - // - // Check if there is a Signal or Not ... - bool hasSignal = cHasSignal || sHasSignal || mHasSignal || lHasSignal || hHasSignal; - if(hasSignal) { - // - XSignal signal; - X121SetupConditions otherConditions[]; - - // - if(cHasSignal) { - // - signal = cSignal; - - // - AddRef( - sConditions, - otherConditions // - ); - AddRef( - mConditions, - otherConditions // - ); - // AddRef( - // lConditions, - // otherConditions // - // ); - // AddRef( - // hConditions, - // otherConditions // - // ); - } - - // - if(sHasSignal) { - // - signal = sSignal; - - // - AddRef( - cConditions, - otherConditions // - ); - AddRef( - mConditions, - otherConditions // - ); - // AddRef( - // lConditions, - // otherConditions // - // ); - // AddRef( - // hConditions, - // otherConditions // - // ); - } - - // - if(mHasSignal) { - // - signal = mSignal; - - // - AddRef( - sConditions, - otherConditions // - ); - AddRef( - lConditions, - otherConditions // - ); - } - - // - if(lHasSignal) { - // - signal = lSignal; - - // - // AddRef( - // cConditions, - // otherConditions // - // ); - AddRef( - mConditions, - otherConditions // - ); - AddRef( - hConditions, - otherConditions // - ); - } - - // - if(hHasSignal) { - // - signal = hSignal; - - // - AddRef( - cConditions, - otherConditions // - ); - AddRef( - sConditions, - otherConditions // - ); - AddRef( - mConditions, - otherConditions // - ); - AddRef( - lConditions, - otherConditions // - ); - AddRef( - hConditions, - otherConditions // - ); - } - - // - int pushers = cPusher + sPusher + mPusher + lPusher + hPusher; - - // - bool isLong = IsLong(signal.type); - - // - // Validate Signal ... - bool isValid = - // - // Handle Pusher Validations ... - (mReuiredSignalVerifications <= 0 ? true : pushers >= mReuiredSignalVerifications) - // - && - // - // Handle Other Conditions Validations ... - (!mGetVerificationFromOtherTimeFrames ? true : isLong ? signalGenerator.HasLongVerifications(otherConditions) : - signalGenerator.HasShortVerifications(otherConditions)) - // - ; - - // - // bool forceState = mSetups[i].ForceState(); - bool forceState = mForce; - - // - if(!forceState) { - // - // Add Signal to Execution Result ... - AddRef( - signal, - signals // - ); - - // - // Add new Signal Info ... - mTradeHandler.Add( - signal, - pushers, - canGrid, - canRecover, - canSupport, - cConditions, - sConditions, - mConditions, - lConditions, - hConditions // - ); - } else { - // - // Clear Other Conditions ... - Clean(otherConditions); - - // - // Fill All Conditions to Other Conditions ... - AddRef( - cConditions, - otherConditions // - ); - AddRef( - sConditions, - otherConditions // - ); - AddRef( - mConditions, - otherConditions // - ); - AddRef( - lConditions, - otherConditions // - ); - AddRef( - hConditions, - otherConditions // - ); - - // - // If Recieved Any Unverified Signal - // we Passed it to EQM Manager ... - EQMHandleInvalidSignal( - signal, - pushers, - isValid, - otherConditions // - ); - } - } - } - - // - result = ArraySize(signals); - - // - return result; - } - - // - // Here we Manage Signals for Executing ... - // - Check Policies based on their Signaller ... - // - Check Same Time Open Positions ... - // - Check Signal Age for new Trade ... - // and etc ... - int HandleSignalManagement(XSignal &signals[]) override { - // - int result = 0; - - // - int signalsCount = ArraySize(signals); - if(!IsValidSize(signalsCount)) { - return result; - } - - // - XSignal tmpSignals[]; - XSignal eSignals[]; // Must Executed - Copy( - signals, - tmpSignals // - ); - - // - Clean(signals); - - // - int maxAllowed = MaxAllowedTrades(); - bool perDirection = UseMaxAllowedPerDirection(); - - // - for(int i = 0; i < signalsCount; i++) { - // - XSignal iSignal = tmpSignals[i]; - - // - bool isSignalValid = false; - - // - isSignalValid = IsSignalDelayPassed(iSignal); - if(!isSignalValid) { - continue; - } - - // - // Handle Close All Positions when Opposit Signal Recieved ... - if(mCloseOnOpposit) { - // - // Select Signal Opposit Positions ... - ENUM_X_POSITION_TYPES iOpposit = GetOppositPositionType(iSignal.type); - - // - XPosition iPositions[]; - int iPositionsCount = mTrader.GetPositions( - iPositions, - iSignal.symbol, - NULL, // All Providers ... - NULL, // All Periods ... - iOpposit // Opposit Positions ... - ); - - // - if(IsValidSize(iPositionsCount)) { - // - string comment = "Close due Opposit ..."; - - // - int closeds = Close( - iPositions, - comment // - ); - if(IsValidSize(closeds)) { - // - string message = XEQMSupportToken + " Closed " + ToString(iPositionsCount) + " due Opposit Signal ..."; - - // - Alert(message); - } - } - } - - // - // TODO: Remove this ... - // isSignalValid = !AllowSupport() - // ? true - // : IsValidSize(ArraySize(iSignal.supports)); - // if (!isSignalValid) - // { - // continue; - // } - - // - // Filter Signals Based On Max Allowed ... - if(maxAllowed > 0) { - // - // Here we Get Opposite Signals of Same Symbol Valid ... - ENUM_X_POSITION_TYPES iType = - perDirection ? ToPositionType(iSignal.type) : X_POSITION_TYPE_ALL; - XPosition iSymbolsPositions[]; - int iSymbolsPositionsCount = mTrader.GetPositions( - iSymbolsPositions, - iSignal.symbol, - NULL, // Provider - NULL, // Period - iType, // Type - true // - ); - - // - int iSupportsCount = 0; - if(IsValidSize(iSymbolsPositionsCount)) { - // - // Filter Support Positions ... - XPosition iSupports[]; - iSupportsCount = ExtractSupports( - iSymbolsPositions, - iSupports // - ); - } - - // - isSignalValid = - iSupportsCount <= 0 ? iSymbolsPositionsCount < maxAllowed : iSymbolsPositionsCount - iSupportsCount < maxAllowed; - if(!isSignalValid) { - continue; - } - } else { - isSignalValid = true; - } - - // - // Only Accept Next Same Type when Previous in Profit ... - bool isSameTypeExists = false; - if(isSignalValid) { - // - ENUM_X_POSITION_TYPES iType = - ToPositionType(iSignal.type); - XPosition iSymbolsPositions[]; - int iSymbolsPositionsCount = mTrader.GetPositions( - iSymbolsPositions, - iSignal.symbol, - NULL, // Provider - NULL, // Period - iType, // Type - true // - ); - - // - int iSupportsCount = 0; - if(IsValidSize(iSymbolsPositionsCount)) { - // - // Filter Support Positions ... - XPosition iSupports[]; - iSupportsCount = ExtractSupports( - iSymbolsPositions, - iSupports // - ); - - // - // Filter Support Positions ... - if(IsValidSize(iSupportsCount)) { - // - XPosition tmpPositions[]; - Copy( - iSymbolsPositions, - tmpPositions // - ); - - // - Clean(iSymbolsPositions); - - // - for(int i = 0; i < iSymbolsPositionsCount; i++) { - // - XPosition iPosition = tmpPositions[i]; - - // - bool isSupport = IsSupport(iPosition.comment); - if(isSupport) { - continue; - } - - // - AddRef( - iPosition, - iSymbolsPositions // - ); - } - - // - iSymbolsPositionsCount = ArraySize(iSymbolsPositions); - } - } - - // - bool acceptNewOnlyWhenLastInProfit = AcceptNextDirectionalSignalsWhenFirstInProfit(); - isSameTypeExists = IsValidSize(iSymbolsPositionsCount); - if(isSameTypeExists && acceptNewOnlyWhenLastInProfit) { - // - XPosition youngest; - int youngestAge = GetYoungest( - youngest, - iSymbolsPositions // - ); - - // - isSignalValid = youngest.profit > 0.1; - } - - // - if(!isSignalValid) { - continue; - } - } - - // - // Multiply Signal Volume ... - if(isSignalValid) { - // - XPosition iSymbolsPositions[]; - int iSymbolsPositionsCount = mTrader.GetPositions( - iSymbolsPositions, - iSignal.symbol, - NULL, // Provider - NULL, // Period - NULL, // Type - true // - ); - - // - int iSupportsCount = 0; - if(IsValidSize(iSymbolsPositionsCount)) { - // - // Filter Support Positions ... - XPosition iSupports[]; - iSupportsCount = ExtractSupports( - iSymbolsPositions, - iSupports // - ); - } - - // - int multiplier = - iSupportsCount <= 0 ? iSymbolsPositionsCount : iSymbolsPositionsCount - iSupportsCount; - if(multiplier <= 0) { - multiplier = 1; - } else { - multiplier++; - } - - // - bool canIncreaseVolume = IncreaseNextSignalsVolume(); - if(canIncreaseVolume) { - // - double volumeMultiplier = IncreaseNextSignalsVolumeMultiplier(); - iSignal.volume = iSignal.volume * (multiplier * volumeMultiplier); - } - } - - // - // Handle Signal ... - if(isSignalValid) { - // - AddRef( - iSignal, - eSignals // - ); - } - } - - // - result = ArraySize(eSignals); - - // - // Cutom Signal Execution ... - if(IsValidSize(result)) { - // - Copy( - eSignals, - signals // - ); - - // - HandleSignals(signals); - } - - // - return result; - } - - // - // Handle State Management .... - // here we can manage current state ... - // - Check for Long Positions for each Signaller to Close ... - // - Handle Hedging Signaller's Positions if it's enabled ... - // - Force Closing Position when Specified Time reached ... - // - Check Start and End time or Trading Dates ... - // - handle Trailing or Risk free Signals based on several conditions ... - // and etc ... - bool HandleStateManagement(XSignal &signals[]) override { - // - bool result = false; - - // - // Do all State Management here ... - - // - // Check if there are open Positions - // and their doesn't have TP and SL and - // Youngest Age of Positions longest as enough - // Make State of Signalling to Force State for Recieving - // Signal and Clear their Tp and SL for allowing hedges ... - EQMHandleForceState(); - - // - DoHedge(); - - // - // Handle Close All Positions on Specific Time ... - DoEQMCloseOnSpecificTime(); - - // - // Do EQM Protection if Provided ... - DoEQMProtect(); - - // - // if Returns true, Signal Execution failed ... - return result; - } - - // - // Signal Info ... - - // - void OnSignalExecuted(const XSignal &signal) override { - // - // Signal Info Manager ... - XSignal tSignal = signal; - bool isSupport = IsSupport(signal.comment); - if(!isSupport) { - mTradeHandler.Update(tSignal); - } - - // - mTradeHandler.Sync(); - } - - // - void OnSignalExecutionFailed( - const XSignal &signal, - const ENUM_X_SIGNAL_EXECUTION_RESULT reason // - ) override { - // - // Signal Info Manager ... - XSignal tSignal = signal; - mTradeHandler.Remove(tSignal); - mTradeHandler.Sync(); - } - - // - void OnPositionClosed( - const XPosition &position, - const string comment // - ) override { - // - // When a Position Closed Manually ... - // Signal Info Manager ... - XPosition tPosition = position; - bool isSupport = ExtractSupportedTicket(position.comment) > 0; - bool isEQMSupport = ExtractEQMSupportedTicket(position.comment) > 0; - tPosition.comment = comment; - if(!isSupport && !isEQMSupport) { - mTradeHandler.Update(tPosition); - } - - // - mTradeHandler.Sync(); - } - - // - void OnStopLossTriggered(const XDeal &deal) override { - // - // When a Position's Stop Loss Triggered ... - // Signal Info Manager ... - XDeal tDeal = deal; - mTradeHandler.Update(tDeal); - mTradeHandler.Sync(); - } - - // - void OnTakeProfitTriggered(const XDeal &deal) override { - // - // When a Position's Take Profit Triggered ... - // Signal Info Manager ... - XDeal tDeal = deal; - mTradeHandler.Update(tDeal); - mTradeHandler.Sync(); - } - - // - // Protected ... - protected: - // - // Tools ... - - // - // Check Signalling Enable or not ... - bool IsEnable() { - // - bool result = false; - - // - // Check Signal Type is Enabled or not ... - bool isTypePassed = mAllowLong || mAllowShort; - - // - // Check Signalling Time ... - MqlDateTime cTime; - bool isTimeRecieved = TimeCurrent(cTime); - - // - int endHour = EndSignallingHoure(); - int startHour = StartSignallingHoure(); - - // - bool isStartHourPassed = - startHour <= -1 ? true : cTime.hour >= startHour; - bool isEndHourPassed = - endHour <= -1 ? true : cTime.hour < endHour; - bool isTimePassed = isTimeRecieved && isStartHourPassed && isEndHourPassed; - - // - result = isTypePassed && isTimePassed; - - // - return result; - } - - // - bool CanCloseOnTime() { - // - bool result = false; - - // - result = mCloseOnSpecificTime >= 0 && mCloseOnSpecificTime <= 23; - if(!result) { - return result; - } - - // - MqlDateTime timeStruct; - result = TimeCurrent(timeStruct); - if(!result) { - return result; - } - - // - result = timeStruct.hour == mCloseOnSpecificTime; - - // - return result; - } - - // - // Custom Signal Execution ... - void HandleSignals(XSignal &signals[]) { - // - int signalsCount = ArraySize(signals); - if(!IsValidSize(signals)) { - return; - } - - // - bool isMarginPassed = IsMarginPassed(); - bool isDrawdownPassed = IsDrawdownPassed(); - if(!isDrawdownPassed) { - // - string message = "Desn't Have Good State For Execute Signals ..."; - - // - Alert(message); - - // - mForce = true; - - // - EQMHandleForceSignals(signals); - return; - } else { - mForce = false; - } - - // - bool executeOnBreakouts = ExecuteSignalsOnBreakout(); - if(executeOnBreakouts) { - // - XSignal bSignals[]; - int bSignalsCount = mTradeHandler.GetBreakoutsSignals(bSignals); - if(IsValidSize(bSignalsCount)) { - // - ENUM_X_SIGNAL_EXECUTION_RESULT states[]; - int executedSignalsCount = ExecuteSignals( - signals, - states, - false // - ); - } - } else { - // - ENUM_X_SIGNAL_EXECUTION_RESULT states[]; - int executedSignalsCount = ExecuteSignals( - signals, - states, - false // - ); - } - } - - // - // Check Delay Between Two Signals ... - bool IsSignalDelayPassed( - XSignal &signal // - ) { - // - bool result = false; - - // - // Check Signal Validation ... - result = signal.IsValid(); - if(!result) { - return result; - } - - // - // Check Delay Signals Allowed ... - int delay = DelayBetweenTwoSignal(); - result = delay <= 0; - if(result) { - return result; - } - - // - // Retrieve Positions ... - // Based On Provider and Symbol and TimeFrame ... - XPosition positions[]; - int positionsCount = mTrader.GetPositions( - positions, - signal.symbol, - NULL, // signal.provider, - NULL, // signal.period, - ToPositionType(signal.type), - true // Filter By Magic ... - ); - result = !IsValidSize(positionsCount); - if(result) { - return result; - } - - // - XPosition youngest; - int youngestAge = GetYoungest( - youngest, - positions // - ); - result = youngestAge >= delay; - - // - return result; - } - - // - bool IsMarginPassed() { - // - double freeMargin = mTrader.mAccount.GetFreeMargin(); - double minFreeMargingForHandleForce = MinFreeMargingForOpenTrades(); - - // - bool result = minFreeMargingForHandleForce <= 0 ? true : freeMargin >= minFreeMargingForHandleForce; - - // - return result; - } - - // - bool IsDrawdownPassed() { - // - bool result = false; - - // - double maxAllowedDrawdownPercent = 5; // MaxAllowedDrawdownPercent(); - double drawdownPercent = GetDrawdownPercent(); - - // - result = maxAllowedDrawdownPercent <= 0 ? true : drawdownPercent <= maxAllowedDrawdownPercent; - - // - return result; - } - - // - // EQM Functions ... - - // - // Force Close All Positions Due EQM Hedge ... - bool DoEQMForceClose() { - // - bool result = false; - - // - XPosition positions[]; - int positionsCount = mTrader.GetPositions(positions); - result = IsValidSize(positionsCount); - if(!result) { - return result; - } - - // - double profit = SpecifiedCalculatePositionsProfit( - positions // - ); - - // - string comment = XEQMSupportToken + " Hedge ..."; - int closed = Close( - positions, - comment // - ); - - // - result = IsValidSize(closed); - if(result) { - // - mTradeHandler.Sync(); - EQMClearAllForceStates(); - } - - // - // Handle Sleeping ... - int restingTime = RestingAfterHedge(); - if(result && IsValidSize(restingTime)) { - Sleeping(restingTime); - } - - // - return result; - } - - // - // Do All Protecting Mechanism ... - void DoEQMProtect() { - // - XSignal supports[]; - int supportsCount = mTradeHandler.DoProtect( - supports, - mSetups // - ); - - // - if(IsValidSize(supportsCount)) { - EQMExecuteSignals(supports); - } - } - - // - // Handle Close Trades on Specific Time ... - void DoEQMCloseOnSpecificTime() { - // - bool canClose = CanCloseOnTime(); - if(!canClose) { - return; - } - - // - XPosition positions[]; - int positionsCount = mTrader.GetPositions(positions); - if(!IsValidSize(positionsCount)) { - return; - } - - // - string comment = XEQMSupportToken + " Close On Specific Time ..."; - - // - int closed = Close( - positions, - comment // - ); - if(IsValidSize(closed)) { - // - string message = XEQMSupportToken + " Closed " + ToString(closed) + " Positions on Specified Time ..."; - - // - Alert(message); - } - } - - // - // Handle any Invalid Signals ... - // this Signals passed From Request For Signal Function ... - // these need to add to Trade Handler .... - void EQMHandleInvalidSignal( - XSignal &signal, // Invalid Signal - int pushers, // Pushers - bool isValid, // IsValid Signal ... - X121SetupConditions &conditions[] // All Time Frames Conditions - ) { - // - int setupIDX = FindSetupIndex(signal.symbol); - if(!IsValidIndex(setupIDX)) { - return; - } - - // - // bool isForce = mSetups[setupIDX].ForceState(); - if(!mForce) { - return; - } - - // - // TODO: Implement this later ... - return; - - // - XSignal signals[]; - - // - if(isValid) { - // - bool canSupport = - // - EnableSupport() && - SupportOnlyForces() - // - ; - bool canGrid = - // - EnableGrid() && - GridOnlyForces() - // - ; - bool canRecover = - // - EnableRecovery() && - RecoverOnlyForces() - // - ; - - // - AddRef( - signal, - signals // - ); - - // - // Add new Signal Info ... - mTradeHandler.Add( - signal, - pushers, - canGrid, - canRecover, - canSupport, - conditions[0], - conditions[1], - conditions[2], - conditions[3], - conditions[4] // - ); - } - - // - if(ArraySize(signals) > 0) { - EQMExecuteSignals(signals); - } - } - - // - // When Margin not passed and Happens an Invalid Signal - // HandleSignals Functions passed Signals to this Method ... - // these Signals Added to Trade Handler Before ... - void EQMHandleForceSignals( - XSignal &signals[] // - ) { - // - if(!mForce) { - return; - } - - // - int count = ArraySize(signals); - if(!IsValidSize(count)) { - return; - } - - // - // TODO: - // Implement what we want ... - } - - // - void EQMHandleForceState() { - // - if(!mForce) { - return; - } - - // - // Exit From Force State ... - - // - // One: Based On Positions Count ... - XPosition positions[]; - int positionsCount = mTrader.GetPositions(positions); - if(!IsValidSize(positionsCount)) { - // - mForce = false; - return; - } - - // - // Two: Based On Free Margin ... - bool isMarginPassed = IsMarginPassed(); - bool isDrawdownPassed = IsDrawdownPassed(); - if(isDrawdownPassed) { - // - mForce = false; - return; - } - - // - // Additional Works on Force States ... - // TODO: Complete this ... - } - - // - // Execute Signals which Provided through - // EQM Protecting Senarios and must be Executed withouth - // any Policies ... - void EQMExecuteSignals( - XSignal &signals[] // - ) { - // - int signalsCount = ArraySize(signals); - if(!IsValidSize(signals)) { - return; - } - - // - // - // Execute Supports ... - ENUM_X_SIGNAL_EXECUTION_RESULT states[]; - int executed = ExecuteSignals( - signals, - states, - false // Ignore Policies ... - ); - if(executed != signalsCount) { - // - // TODO: Dow What We Want ... - // Print("Error On Executing Support Signal ..."); - } - - // - // Remove Supported Signals TP and SL and leave them for Handling using HEDGE Mechanism ... - if(IsValidSize(executed)) { - // - for(int i = 0; i < signalsCount; i++) { - // - ENUM_X_SIGNAL_EXECUTION_RESULT iState = states[i]; - if(iState != X_SIGNAL_EXECUTION_SUCCEED) { - continue; - } - - // - XSignal iSignal = signals[i]; - if(!iSignal.IsValid() || !iSignal.IsExecuted()) { - continue; - } - - // - ulong iParentTicket = ExtractParentTicket(iSignal.comment); - if(iParentTicket <= 0) { - continue; - } - - // - XPosition iParent; - bool hasParent = mTrader.GetPosition( - iParentTicket, - iParent // - ); - if(!hasParent) { - continue; - } - - // - // Check Parent Has TP or SL ... - if(iParent.tp == 0 && iParent.sl == 0) { - continue; - } - - // - // Remove TP and SL of Supported Positions ... - string comment = "EQM Remove TPSL ..."; - bool isModified = Modify( - iParentTicket, - 0, - 0, - comment // - ); - if(isModified) { - // - // TODO: - // do What we want ... - } - } - } - } - - // - // Clear All Force States of Setups ... - void EQMClearAllForceStates() { - // - int setupsCount = CountSetups(); - if(!IsValidSize(setupsCount)) { - return; - } - - // - for(int i = 0; i < setupsCount; i++) { - mSetups[i].ForceState(false); - } - } - - // - // Private ... - private: - // - // Props ... - - // - // Signals ... - bool mAllowLong; // Allow Long - bool mAllowShort; // Allow Short - int mReuiredSignalVerifications; // Required Verifications for Validate Signals - bool mExecuteSignalsOnBreakout; // Execute Signals On Breakouts - bool mGetVerificationFromOtherTimeFrames; // Get Verifications from Other Time Frames - - // - // Risk Management ... - double mVolume; // Volume - double mTPPoint; // TP Point - double mSLPoint; // SL Point - bool mIgnoreTP; // Ignore Calculated TP - bool mIgnoreSL; // Ignore Calculated SL - int mMaxAllowedTrades; // Max Alloed Positions - bool mUseMaxAllowedPerDirection; // Use Max Allowed Positions Per Direction - bool mIncreaseNextSignalsVolume; // Increase Next Signals Volume - double mIncreaseNextSignalsVolumeMultiplier; // Increase Next Signals Volume Multiplier - bool mAcceptNextDirectionalSignalsWhenFirstInProfit; // Accept Same Symbol/Type Signal when Last in Profit - - // - // Signalling ... - bool mCloseOnOpposit; // Close all Positions on Opposit - int mEndSignallingHoure; // End Signalling at Specific Time - int mCloseOnSpecificTime; // Close All Trades in Specific Time - int mStartSignallingHoure; // Start Signalling at Specific Time - - // - // Force State: - // we can do many things in force state: - // - Prepare Force Hedging; - // - Receive Signals with minimal Verifications; - // - Increase Volume Size of in Profit Positions; - // - etc ... - bool mForce; // Determine in Force State or not - int mDelayBetweenTwoSignal; // Delay between two same signal - double mMinFreeMargingForOpenTrades; // Min Free Margin for Open Trades - - // - XSCX121SetupCycles *mSetups[]; // Number of Setups - XTradeHandler *mTradeHandler; // Handle all Event which related to Signals and Positions - - // - // Apply Default Configurations ... - void DefaultConfigs() { - // - // Signals ... - AllowLong(false); - AllowShort(false); - ReuiredSignalVerifications(0); - GetVerificationFromOtherTimeFrames(false); - - // - // Risk Management ... - TPPoint(0); - SLPoint(0); - Volume(0.01); - IgnoreTP(false); - IgnoreSL(false); - MaxAllowedTrades(0); - UseMaxAllowedPerDirection(false); - IncreaseNextSignalsVolume(false); - IncreaseNextSignalsVolumeMultiplier(1); - AcceptNextDirectionalSignalsWhenFirstInProfit(false); - - // - // Signalling ... - CloseOnOpposit(false); - EndSignallingHoure(-1); - CloseOnSpecificTime(-1); - StartSignallingHoure(-1); - - // - // Trailling ... - AllowTrailStop(false); - NextTrailPoint(0); - FirstTrailPoint(0); - NextTrailDistance(0); - FirstTrailDistance(0); - - // - // Supporting ... - AllowSupport(false); - MaxNumberOfSupports(0); - SupportOnlyForces(false); - SupportVolumeMultiplier(0.01); - MaxAllowedSupportVolume(0.08); - - // - // Grid ... - GridDistance(0); - AllowGrid(false); - MaxNumberOfGrids(0); - GridOnlyForces(false); - GridVolumeMultiplier(0.01); - MaxAllowedGridVolume(0.08); - - // - // Recovery ... - RecoveryDistance(0); - AllowRecovery(false); - MaxNumberOfRecoveries(0); - RecoverOnlyForces(false); - RecoveryVolumeMultiplier(0.01); - MaxAllowedRecoveryVolume(0.08); - - // - SaveResults(false); - SaveSignalsOnly(true); - } - - // - // Tools ... - int CountSetups() { - return ArraySize(mSetups); - } - - // - // Find Setup Index by Symbol and Period ... - int FindSetupIndex( - string symbol, - ENUM_TIMEFRAMES period // - ) { - // - int result = -1; - - // - int count = CountSetups(); - if(!IsValidSize(count)) { - return result; - } - - // - for(int i = 0; i < count; i++) { - // - XSCX121SetupCycles *iSetup = mSetups[i]; - - // - X121SetupInputs iInputs = iSetup.GetInputs(); - - // - if(iInputs.symbol == symbol && iInputs.period == period) { - // - result = i; - break; - } - } - - // - return result; - } - - // - // Find Setup Index by Providing Symbol ... - int FindSetupIndex( - string symbol // - ) { - // - int result = -1; - - // - int count = CountSetups(); - if(!IsValidSize(count)) { - return result; - } - - // - for(int i = 0; i < count; i++) { - // - XSCX121SetupCycles *iSetup = mSetups[i]; - - // - X121SetupInputs iInputs = iSetup.GetInputs(); - - // - if(iInputs.symbol == symbol) { - // - result = i; - break; - } - } - - // - return result; - } - - // -}; - -// diff --git a/Documents/Pack/V1.0/Source/Classes/x-saherelm.xaccount.class.mq5 b/Documents/Pack/V1.0/Source/Classes/x-saherelm.xaccount.class.mq5 deleted file mode 100644 index 66169f54..00000000 --- a/Documents/Pack/V1.0/Source/Classes/x-saherelm.xaccount.class.mq5 +++ /dev/null @@ -1,398 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Class Library -// ---------------------------------------------- -// Name: XSCAccount -// Description: provides all Account 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 - -// -// START Definitions ... -// - -// -// END Definitions ... -// - -// -// START Import and Inclused requirements ... -// - -// -// Includes ... -#include -#include "../Classes/x-saherelm.base.class.mq5" - -// -// END Import and Inclused requirements ... -// - -// -// START Overrides ... -// - -// -// END Overrides ... -// - -// -// a Class for Manage Account ... -class XSCAccount : public XSCBase -{ - // - // Public ... -public: - // - // Constructor ... - void XSCAccount() - { - // - mAccountInfo = new CAccountInfo(); - } - - // - // Deconstructor ... - void ~XSCAccount() - { - } - - // - // START Provided Functions ... - // - - // - // User Account ... - long GetUserAccount() - { - return mAccountInfo.Login(); - } - - // - // Account Leverage ... - long GetLeverage() - { - return mAccountInfo.Leverage(); - } - - // - // Get Trade Expert State ... - bool CanExpertTrade() - { - return mAccountInfo.TradeExpert(); - } - - // - // User Account Trade Mopde (ENUM_ACCOUNT_TRADE_MODE) ... - // -------------------------- - // ACCOUNT_TRADE_MODE_DEMO - // ACCOUNT_TRADE_MODE_CONTEST - // ACCOUNT_TRADE_MODE_REAL - ENUM_ACCOUNT_TRADE_MODE GetTradeMode() - { - return mAccountInfo.TradeMode(); - } - - // - // Get Account Balance ... - double GetBalance() - { - return mAccountInfo.Balance(); - } - - // - // Get the amount of give Credit ... - double GetCredit() - { - return mAccountInfo.Credit(); - } - - // - // Get the amount of current Profit on account ... - double GetProfit() - { - return mAccountInfo.Profit(); - } - - // - // Get the amount of current Equity on account ... - double GetEquity() - { - return mAccountInfo.Equity(); - } - - // - // Get the amount of reserved Margin ... - double GetMargin() - { - return mAccountInfo.Margin(); - } - - // - // Get the amount of free Margin ... - double GetFreeMargin() - { - return mAccountInfo.FreeMargin(); - } - - // - // Get the Level of Margin ... - double GetMarginLevel() - { - return mAccountInfo.MarginLevel(); - } - - // - // Get the Level Of Margin for a Deposit ... - double GetMarginCall() - { - return mAccountInfo.MarginCall(); - } - - // - // Get the Level of Margin for Stop out ... - double GetMarginStopOut() - { - return mAccountInfo.MarginStopOut(); - } - - // - // Get the Client Name ... - string GetName() - { - return mAccountInfo.Name(); - } - - // - // Get the Trade Server Name ... - string GetServerName() - { - return mAccountInfo.Server(); - } - - // - // Get deposit Currency Name ... - string GetCurrency() - { - return mAccountInfo.Currency(); - } - - // - // Get the Company Name that serves an Account ... - string GetCompany() - { - return mAccountInfo.Company(); - } - - // - // Calculate Profits for the current account based on passed parameters ... - double CalculateTradeProfit( - const string symbol, // trading symbol - ENUM_ORDER_TYPE type, // order type - double volume, // volume - double entry, // open price - double exit // close price - ) - { - // - double result = mAccountInfo.OrderProfitCheck( - symbol, - type, - volume, - entry, - exit); - - // - return result; - } - - // - // Calculate amount of margin which required for trade operation ... - double CalculateMarging( - const string symbol, // trading symbol - ENUM_ORDER_TYPE type, // order type - double volume, // volume - double entry // open price - ) - { - // - double result = mAccountInfo.MarginCheck( - symbol, - type, - volume, - entry); - - // - return result; - } - - // - // Calculate amount of free margin left after trade operation ... - double CalculateFreeMarging( - const string symbol, // trading symbol - ENUM_ORDER_TYPE type, // order type - double volume, // volume - double entry // open price - ) - { - // - double result = mAccountInfo.FreeMarginCheck( - symbol, - type, - volume, - entry); - - // - return result; - } - - // - // Calculate the Maximum possible volume of trade operation ... - double CalculateMaxVolume( - const string symbol, // trading symbol - ENUM_ORDER_TYPE type, // order type - double entry, // open price - double percent = 100 // percent of available margin - ) - { - // - double result = mAccountInfo.MaxLotCheck( - symbol, - type, - entry, - percent); - - // - return result; - } - - // - // Calculate Point Value for Given Symbol based on Account ... - double GetPointValue( - string symbol // trading symbol - ) - { - // - double result = 0; - - // - double tickSize = SymbolInfoDouble(symbol, SYMBOL_TRADE_TICK_SIZE); - double tickValue = SymbolInfoDouble(symbol, SYMBOL_TRADE_TICK_VALUE); - double point = SymbolInfoDouble(symbol, SYMBOL_POINT); - - // - double ticksPerPoint = tickSize / point; - - // - result = tickValue / ticksPerPoint; - - // - return result; - } - - // - // Calculate Risk Amount based on account Currency by Providing: - // Points and Volume ... - double CalculateRiskAmount( - string symbol, // trading symbol - double points, // amount of Risk Points - double volume // position Volume - ) - { - // - double result = 0; - - // - double pointValue = GetPointValue(symbol); - - // - result = pointValue * volume * points; - - // - return result; - } - - // - // Calculate Risk Points based on account Currency by Providing: - // Volume and Amount ... - double CalculateRiskPoints( - string symbol, // trading symbol - double volume, // position Volume - double amount // amount of Risk based on Account Currency - ) - { - // - double result = 0; - - // - double pointValue = GetPointValue(symbol); - - // - result = amount / (pointValue * volume); - - // - return result; - } - - // - // Calculate Volume based on account Currency by Providing: - // Amount and Risk Points ... - double CalculateVolume( - string symbol, // trading symbol - double amount, // amount of Risk based on Account Currency - double points // amount of Risk Points - ) - { - // - double result = 0; - - // - points = - points <= 0 - ? 10 - : points; - - // - double pointValue = GetPointValue(symbol); - - // - result = amount / (pointValue * points); - - // - return result; - } - - // - // END Provided Functions ... - // - - // - // Protected ... -protected: - // - // Private ... -private: - // - // Account Info ... - CAccountInfo mAccountInfo; -}; - -// -// START Usefull Functions ... -// - -// -// END Usefull Functions ... -// diff --git a/Documents/Pack/V1.0/Source/Classes/x-saherelm.xalert.class.mq5 b/Documents/Pack/V1.0/Source/Classes/x-saherelm.xalert.class.mq5 deleted file mode 100644 index 7f15e326..00000000 --- a/Documents/Pack/V1.0/Source/Classes/x-saherelm.xalert.class.mq5 +++ /dev/null @@ -1,1575 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Class Library -// ---------------------------------------------- -// Name: XSCAlert -// Description: provides all Alerts requirements ... -// -// -// Maintainer: -// ------------ -// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) -// -////////////////////////////////////////////////////// -// -// Global Properties ... -#property library -#property copyright "Copyright 2023, SaherElm IT Center" -#property link "https://www.saherelm.ir" -#property version "1.00" -#property strict - -// -// Imports ... -#include "../Classes/x-saherelm.base.class.mq5" - -// -// Class Definition ... - -class XSCAlert : public XSCBase -{ - // - // Public ... -public: - // - // Props ... - - // - // Constructor ... - XSCAlert( - string prefix = "X-Alert", // Alerts Prefixe - bool enableAlerts = true, // Enable Alerts - bool logAlerts = true, // Log Alerts - bool terminalAlerts = false, // Terminal Alerts - bool mailAlerts = false, // Mail Alerts - bool pushAlerts = false // Push Alerts - ) - { - // - mPrefix = prefix; - mLogAlerts = logAlerts; - mMailAlerts = mailAlerts; - mPushAlerts = pushAlerts; - mEnableAlerts = enableAlerts; - mTerminalAlerts = terminalAlerts; - - // - // Normalize Prefix if Not Provided ... - if (!IsValid(mPrefix)) - { - mPrefix = GetTag(); - } - } - - // - // Deconstructor ... - ~XSCAlert() {} - - // - // Override ... - string GetTag() override - { - return GetSpecificToken(this); - } - - // - // Properties Getter(s) / Setter(s) ... - - // - string GetPrefix() - { - return mPrefix; - } - - // - void SetPrefix(string value) - { - mPrefix = value; - } - - // - bool GetLogAlerts() - { - return mLogAlerts; - } - - // - void SetLogAlerts(bool value) - { - mLogAlerts = value; - } - - // - bool GetEnableAlerts() - { - return mEnableAlerts; - } - - // - void SetEnableAlerts(bool value) - { - mEnableAlerts = value; - } - - // - bool GetPushAlerts() - { - return mPushAlerts; - } - - // - void SetPushAlerts(bool value) - { - mPushAlerts = value; - } - - // - bool GetMailAlerts() - { - return mMailAlerts; - } - - // - void SetMailAlerts(bool value) - { - mMailAlerts = value; - } - - // - bool GetTerminalAlerts() - { - return mTerminalAlerts; - } - - // - void SetTerminalAlerts(bool value) - { - mTerminalAlerts = value; - } - - // - // Tools Funtions ... - - // - // Alerts ... - - // - // Logging an Alert ... - void LogAlert(string message) - { - // - // Validate Args ... - if (!CanLogAlert()) - { - return; - } - - // - Log(message); - } - - // - // Terminal Alert ... - void TerminalAlert(string message) - { - // - // Validate Args ... - if (!CanTerminalAlert()) - { - return; - } - - // - // Prepare Message ... - message = PrepareMessage(message); - - // Send Terminal Alert ... - Alert(message); - } - - // - // Mail Alert ... - void MailAlert(string message) - { - // - // Validate Args ... - if (!CanMailAlert()) - { - return; - } - - // - // Send Mail Alert ... - SendMail(GetPrefix(), message); - } - - // - // Send Push Notification ... - void PushAlert(string message) - { - // - // Validate Args ... - if (!CanPushAlert()) - { - return; - } - - // - // Prepare Message ... - message = PrepareMessage(message); - - // - // Send Push Notification Alert ... - SendNotification(message); - } - - // - // Send an Alert by Handling all Different Specified - // type's of Alert's if they are Enabled ... - void Alert(string message) - { - // - // Handle Log, if Enabled ... - LogAlert(message); - - // - // Handle Mail if Enabled ... - MailAlert(message); - - // - // Handle Push if Enabled ... - PushAlert(message); - - // - // Handle Terminal if Enabled ... - TerminalAlert(message); - } - - // - // Logs ... - - // - // Log a Message ... - void Log(string message) - { - // - if (!CanLog()) - { - return; - } - - // - Print(GetPrefix(), " > ", message); - } - void Log(string tag, string message) - { - // - if (!CanLog()) - { - return; - } - - // - Print(GetPrefix(), "_", tag, " > ", message); - } - void LogEmpty() - { - // - if (!CanLog()) - { - return; - } - - // - Print(" "); - } - - // - // Log Specific Array ... - template - void LogArray( - T &array[], // Array to Log - string label = NULL // Array Label - ) - { - // - if (!CanLog()) - { - return; - } - - // - Print(GetPrefix(), ">", (IsValid(label) ? label : "")); - ArrayPrint(array); - } - - // - // Error ... - - // - // Log an Error ... - void LogError( - int error = -1 // Specific Error, if it's equal to -1, use Last Error ... - ) - { - // - if (!CanLog()) - { - return; - } - - // - if (error <= -1) - { - error = GetLastError(); - } - - // - string errorMsg = GetErrorDescription(error); - - // - Log("Error: " + errorMsg); - } - - // - // Retrieve Specified Error Code Description ... - string GetErrorDescription(int err_code) - { - // - string result = ""; - - // - switch (err_code) - { - // - //--- Constant Description - - // - case ERR_SUCCESS: - result = "The operation completed successfully"; - break; - - // - case ERR_INTERNAL_ERROR: - result = "Unexpected internal error"; - break; - - // - case ERR_WRONG_INTERNAL_PARAMETER: - result = "Wrong parameter in the inner call of the client terminal function"; - break; - - // - case ERR_INVALID_PARAMETER: - result = "Wrong parameter when calling the system function"; - break; - - // - case ERR_NOT_ENOUGH_MEMORY: - result = "Not enough memory to perform the system function"; - break; - - // - case ERR_STRUCT_WITHOBJECTS_ORCLASS: - result = "The structure contains objects of strings and/or dynamic arrays and/or structure of such objects and/or classes"; - break; - - // - case ERR_INVALID_ARRAY: - result = "Array of a wrong type, wrong size, or a damaged object of a dynamic array"; - break; - - // - case ERR_ARRAY_RESIZE_ERROR: - result = "Not enough memory for the relocation of an array, or an attempt to change the size of a static array"; - break; - - // - case ERR_STRING_RESIZE_ERROR: - result = "Not enough memory for the relocation of string"; - break; - - // - case ERR_NOTINITIALIZED_STRING: - result = "Not initialized string"; - break; - - // - case ERR_INVALID_DATETIME: - result = "Invalid date and/or time"; - break; - - // - case ERR_ARRAY_BAD_SIZE: - result = "Requested array size exceeds 2 GB"; - break; - - // - case ERR_INVALID_POINTER: - result = "Wrong pointer"; - break; - - // - case ERR_INVALID_POINTER_TYPE: - result = "Wrong type of pointer"; - break; - - // - case ERR_FUNCTION_NOT_ALLOWED: - result = "System function is not allowed to call"; - break; - - // - //--- Charts - - // - case ERR_CHART_WRONG_ID: - result = "Wrong chart ID"; - break; - - // - case ERR_CHART_NO_REPLY: - result = "Chart does not respond"; - break; - - // - case ERR_CHART_NOT_FOUND: - result = "Chart not found"; - break; - - // - case ERR_CHART_NO_EXPERT: - result = "No Expert Advisor in the chart that could handle the event"; - break; - - // - case ERR_CHART_CANNOT_OPEN: - result = "Chart opening error"; - break; - - // - case ERR_CHART_CANNOT_CHANGE: - result = "Failed to change chart symbol and period"; - break; - - // - case ERR_CHART_CANNOT_CREATE_TIMER: - result = "Failed to create timer"; - break; - - // - case ERR_CHART_WRONG_PROPERTY: - result = "Wrong chart property ID"; - break; - - // - case ERR_CHART_SCREENSHOT_FAILED: - result = "Error creating screenshots"; - break; - - // - case ERR_CHART_NAVIGATE_FAILED: - result = "Error navigating through chart"; - break; - - // - case ERR_CHART_TEMPLATE_FAILED: - result = "Error applying template"; - break; - - // - case ERR_CHART_WINDOW_NOT_FOUND: - result = "Subwindow containing the indicator was not found"; - break; - - // - case ERR_CHART_INDICATOR_CANNOT_ADD: - result = "Error adding an indicator to chart"; - break; - - // - case ERR_CHART_INDICATOR_CANNOT_DEL: - result = "Error deleting an indicator from the chart"; - break; - - // - case ERR_CHART_INDICATOR_NOT_FOUND: - result = "Indicator not found on the specified chart"; - break; - - // - //--- Graphical Objects - case ERR_OBJECT_ERROR: - result = "Error working with a graphical object"; - break; - - // - case ERR_OBJECT_NOT_FOUND: - result = "Graphical object was not found"; - break; - - // - case ERR_OBJECT_WRONG_PROPERTY: - result = "Wrong ID of a graphical object property"; - break; - - // - case ERR_OBJECT_GETDATE_FAILED: - result = "Unable to get date corresponding to the value"; - break; - - // - case ERR_OBJECT_GETVALUE_FAILED: - result = "Unable to get value corresponding to the date"; - break; - - // - //--- MarketInfo - - // - case ERR_MARKET_UNKNOWN_SYMBOL: - result = "Unknown symbol"; - break; - - // - case ERR_MARKET_NOT_SELECTED: - result = "Symbol is not selected in MarketWatch"; - break; - - // - case ERR_MARKET_WRONG_PROPERTY: - result = "Wrong identifier of a symbol property"; - break; - - // - case ERR_MARKET_LASTTIME_UNKNOWN: - result = "Time of the last tick is not known (no ticks)"; - break; - - // - case ERR_MARKET_SELECT_ERROR: - result = "Error adding or deleting a symbol in MarketWatch"; - break; - - // - //--- History Access - - // - case ERR_HISTORY_NOT_FOUND: - result = "Requested history not found"; - break; - - // - case ERR_HISTORY_WRONG_PROPERTY: - result = "Wrong ID of the history property"; - break; - - // - //--- Global_Variables - - // - case ERR_GLOBALVARIABLE_NOT_FOUND: - result = "Global variable of the client terminal is not found"; - break; - - // - case ERR_GLOBALVARIABLE_EXISTS: - result = "Global variable of the client terminal with the same name already exists"; - break; - - // - case ERR_MAIL_SEND_FAILED: - result = "Email sending failed"; - break; - - // - case ERR_PLAY_SOUND_FAILED: - result = "Sound playing failed"; - break; - - // - case ERR_MQL5_WRONG_PROPERTY: - result = "Wrong identifier of the program property"; - break; - - // - case ERR_TERMINAL_WRONG_PROPERTY: - result = "Wrong identifier of the terminal property"; - break; - - // - case ERR_FTP_SEND_FAILED: - result = "File sending via ftp failed"; - break; - - // - case ERR_NOTIFICATION_SEND_FAILED: - result = "Error in sending notification"; - break; - - // - //--- Custom Indicator Buffers - - // - case ERR_BUFFERS_NO_MEMORY: - result = "Not enough memory for the distribution of indicator buffers"; - break; - - // - case ERR_BUFFERS_WRONG_INDEX: - result = "Wrong indicator buffer index"; - break; - - // - //--- Custom Indicator Properties - - // - case ERR_CUSTOM_WRONG_PROPERTY: - result = "Wrong ID of the custom indicator property"; - break; - - // - //--- Account - - // - case ERR_ACCOUNT_WRONG_PROPERTY: - result = "Wrong account property ID"; - break; - - // - case ERR_TRADE_WRONG_PROPERTY: - result = "Wrong trade property ID"; - break; - - // - case ERR_TRADE_DISABLED: - result = "Trading by Expert Advisors prohibited"; - break; - - // - case ERR_TRADE_POSITION_NOT_FOUND: - result = "Position not found"; - break; - - // - case ERR_TRADE_ORDER_NOT_FOUND: - result = "Order not found"; - break; - - // - case ERR_TRADE_DEAL_NOT_FOUND: - result = "Deal not found"; - break; - - // - case ERR_TRADE_SEND_FAILED: - result = "Trade request sending failed"; - break; - - // - //--- Indicators - - // - case ERR_INDICATOR_UNKNOWN_SYMBOL: - result = "Unknown symbol"; - break; - - // - case ERR_INDICATOR_CANNOT_CREATE: - result = "Indicator cannot be created"; - break; - - // - case ERR_INDICATOR_NO_MEMORY: - result = "Not enough memory to add the indicator"; - break; - - // - case ERR_INDICATOR_CANNOT_APPLY: - result = "The indicator cannot be applied to another indicator"; - break; - - // - case ERR_INDICATOR_CANNOT_ADD: - result = "Error applying an indicator to chart"; - break; - - // - case ERR_INDICATOR_DATA_NOT_FOUND: - result = "Requested data not found"; - break; - - // - case ERR_INDICATOR_WRONG_HANDLE: - result = "Wrong indicator handle"; - break; - - // - case ERR_INDICATOR_WRONG_PARAMETERS: - result = "Wrong number of parameters when creating an indicator"; - break; - - // - case ERR_INDICATOR_PARAMETERS_MISSING: - result = "No parameters when creating an indicator"; - break; - - // - case ERR_INDICATOR_CUSTOM_NAME: - result = "The first parameter in the array must be the name of the custom indicator"; - break; - - // - case ERR_INDICATOR_PARAMETER_TYPE: - result = "Invalid parameter type in the array when creating an indicator"; - break; - - // - case ERR_INDICATOR_WRONG_INDEX: - result = "Wrong index of the requested indicator buffer"; - break; - - // - //--- Depth of Market - - // - case ERR_BOOKS_CANNOT_ADD: - result = "Depth Of Market can not be added"; - break; - - // - case ERR_BOOKS_CANNOT_DELETE: - result = "Depth Of Market can not be removed"; - break; - - // - case ERR_BOOKS_CANNOT_GET: - result = "The data from Depth Of Market can not be obtained"; - break; - - // - case ERR_BOOKS_CANNOT_SUBSCRIBE: - result = "Error in subscribing to receive new data from Depth Of Market"; - break; - - // - //--- File Operations - - // - case ERR_TOO_MANY_FILES: - result = "More than 64 files cannot be opened at the same time"; - break; - - // - case ERR_WRONG_FILENAME: - result = "Invalid file name"; - break; - - // - case ERR_TOO_LONG_FILENAME: - result = "Too long file name"; - break; - - // - case ERR_CANNOT_OPEN_FILE: - result = "File opening error"; - break; - - // - case ERR_FILE_CACHEBUFFER_ERROR: - result = "Not enough memory for cache to read"; - break; - - // - case ERR_CANNOT_DELETE_FILE: - result = "File deleting error"; - break; - - // - case ERR_INVALID_FILEHANDLE: - result = "A file with this handle was closed, or was not opening at all"; - break; - - // - case ERR_WRONG_FILEHANDLE: - result = "Wrong file handle"; - break; - - // - case ERR_FILE_NOTTOWRITE: - result = "The file must be opened for writing"; - break; - - // - case ERR_FILE_NOTTOREAD: - result = "The file must be opened for reading"; - break; - - // - case ERR_FILE_NOTBIN: - result = "The file must be opened as a binary one"; - break; - - // - case ERR_FILE_NOTTXT: - result = "The file must be opened as a text"; - break; - - // - case ERR_FILE_NOTTXTORCSV: - result = "The file must be opened as a text or CSV"; - break; - - // - case ERR_FILE_NOTCSV: - result = "The file must be opened as CSV"; - break; - - // - case ERR_FILE_READERROR: - result = "File reading error"; - break; - - // - case ERR_FILE_BINSTRINGSIZE: - result = "String size must be specified, because the file is opened as binary"; - break; - - // - case ERR_INCOMPATIBLE_FILE: - result = "A text file must be for string arrays, for other arrays - binary"; - break; - - // - case ERR_FILE_IS_DIRECTORY: - result = "This is not a file, this is a directory"; - break; - - // - case ERR_FILE_NOT_EXIST: - result = "File does not exist"; - break; - - // - case ERR_FILE_CANNOT_REWRITE: - result = "File can not be rewritten"; - break; - - // - case ERR_WRONG_DIRECTORYNAME: - result = "Wrong directory name"; - break; - - // - case ERR_DIRECTORY_NOT_EXIST: - result = "Directory does not exist"; - break; - - // - case ERR_FILE_ISNOT_DIRECTORY: - result = "This is a file, not a directory"; - break; - - // - case ERR_CANNOT_DELETE_DIRECTORY: - result = "The directory cannot be removed"; - break; - - // - case ERR_CANNOT_CLEAN_DIRECTORY: - result = "Failed to clear the directory (probably one or more files are blocked and removal operation failed)"; - break; - - // - case ERR_FILE_WRITEERROR: - result = "Failed to write a resource to a file"; - break; - - // - //--- String Casting - - // - case ERR_NO_STRING_DATE: - result = "No date in the string"; - break; - - // - case ERR_WRONG_STRING_DATE: - result = "Wrong date in the string"; - break; - - // - case ERR_WRONG_STRING_TIME: - result = "Wrong time in the string"; - break; - - // - case ERR_STRING_TIME_ERROR: - result = "Error converting string to date"; - break; - - // - case ERR_STRING_OUT_OF_MEMORY: - result = "Not enough memory for the string"; - break; - - // - case ERR_STRING_SMALL_LEN: - result = "The string length is less than expected"; - break; - - // - case ERR_STRING_TOO_BIGNUMBER: - result = "Too large number, more than ULONG_MAX"; - break; - - // - case ERR_WRONG_FORMATSTRING: - result = "Invalid format string"; - break; - - // - case ERR_TOO_MANY_FORMATTERS: - result = "Amount of format specifiers more than the parameters"; - break; - - // - case ERR_TOO_MANY_PARAMETERS: - result = "Amount of parameters more than the format specifiers"; - break; - - // - case ERR_WRONG_STRING_PARAMETER: - result = "Damaged parameter of string type"; - break; - - // - case ERR_STRINGPOS_OUTOFRANGE: - result = "Position outside the string"; - break; - - // - case ERR_STRING_ZEROADDED: - result = "0 added to the string end, a useless operation"; - break; - - // - case ERR_STRING_UNKNOWNTYPE: - result = "Unknown data type when converting to a string"; - break; - - // - case ERR_WRONG_STRING_OBJECT: - result = "Damaged string object"; - break; - - // - //--- Operations with Arrays - - // - case ERR_INCOMPATIBLE_ARRAYS: - result = "Copying incompatible arrays. String array can be copied only to a string array, and a numeric array - in numeric array only"; - break; - - // - case ERR_SMALL_ASSERIES_ARRAY: - result = "The receiving array is declared as AS_SERIES, and it is of insufficient size"; - break; - - // - case ERR_SMALL_ARRAY: - result = "Too small array, the starting position is outside the array"; - break; - - // - case ERR_ZEROSIZE_ARRAY: - result = "An array of zero length"; - break; - - // - case ERR_NUMBER_ARRAYS_ONLY: - result = "Must be a numeric array"; - break; - - // - case ERR_ONEDIM_ARRAYS_ONLY: - result = "Must be a one-dimensional array"; - break; - - // - case ERR_SERIES_ARRAY: - result = "Timeseries cannot be used"; - break; - - // - case ERR_DOUBLE_ARRAY_ONLY: - result = "Must be an array of type double"; - break; - - // - case ERR_FLOAT_ARRAY_ONLY: - result = "Must be an array of type float"; - break; - - // - case ERR_LONG_ARRAY_ONLY: - result = "Must be an array of type long"; - break; - - // - case ERR_INT_ARRAY_ONLY: - result = "Must be an array of type int"; - break; - - // - case ERR_SHORT_ARRAY_ONLY: - result = "Must be an array of type short"; - break; - - // - case ERR_CHAR_ARRAY_ONLY: - result = "Must be an array of type char"; - break; - - // - //--- Operations with OpenCL - - // - case ERR_OPENCL_NOT_SUPPORTED: - result = "OpenCL functions are not supported on this computer"; - break; - - // - case ERR_OPENCL_INTERNAL: - result = "Internal error occurred when running OpenCL"; - break; - - // - case ERR_OPENCL_INVALID_HANDLE: - result = "Invalid OpenCL handle"; - break; - - // - case ERR_OPENCL_CONTEXT_CREATE: - result = "Error creating the OpenCL context"; - break; - - // - case ERR_OPENCL_QUEUE_CREATE: - result = "Failed to create a run queue in OpenCL"; - break; - - // - case ERR_OPENCL_PROGRAM_CREATE: - result = "Error occurred when compiling an OpenCL program"; - break; - - // - case ERR_OPENCL_TOO_LONG_KERNEL_NAME: - result = "Too long kernel name (OpenCL kernel)"; - break; - - // - case ERR_OPENCL_KERNEL_CREATE: - result = "Error creating an OpenCL kernel"; - break; - - // - case ERR_OPENCL_SET_KERNEL_PARAMETER: - result = "Error occurred when setting parameters for the OpenCL kernel"; - break; - - // - case ERR_OPENCL_EXECUTE: - result = "OpenCL program runtime error"; - break; - - // - case ERR_OPENCL_WRONG_BUFFER_SIZE: - result = "Invalid size of the OpenCL buffer"; - break; - - // - case ERR_OPENCL_WRONG_BUFFER_OFFSET: - result = "Invalid offset in the OpenCL buffer"; - break; - - // - case ERR_OPENCL_BUFFER_CREATE: - result = "Failed to create and OpenCL buffer"; - break; - - // - //--- User-Defined Errors - default: - result = "UNKNOWN Erro ..."; - break; - } - - // - return result; - } - - // - // Retrieve Specified Error Code Description ... - string GetTradeServerReturnCodeDescription(int return_code) - { - // - string result = ""; - - // - switch (return_code) - { - // - case TRADE_RETCODE_REQUOTE: - result = "Requote"; - break; - - // - case TRADE_RETCODE_REJECT: - result = "Request rejected"; - break; - - // - case TRADE_RETCODE_CANCEL: - result = "Request canceled by trader"; - break; - - // - case TRADE_RETCODE_PLACED: - result = "Order placed"; - break; - - // - case TRADE_RETCODE_DONE: - result = "Request completed"; - break; - - // - case TRADE_RETCODE_DONE_PARTIAL: - result = "Only part of the request was completed"; - break; - - // - case TRADE_RETCODE_ERROR: - result = "Request processing error"; - break; - - // - case TRADE_RETCODE_TIMEOUT: - result = "Request canceled by timeout"; - break; - - // - case TRADE_RETCODE_INVALID: - result = "Invalid request"; - break; - - // - case TRADE_RETCODE_INVALID_VOLUME: - result = "Invalid volume in the request"; - break; - - // - case TRADE_RETCODE_INVALID_PRICE: - result = "Invalid price in the request"; - break; - - // - case TRADE_RETCODE_INVALID_STOPS: - result = "Invalid stops in the request"; - break; - - // - case TRADE_RETCODE_TRADE_DISABLED: - result = "Trade is disabled"; - break; - - // - case TRADE_RETCODE_MARKET_CLOSED: - result = "Market is closed"; - break; - - // - case TRADE_RETCODE_NO_MONEY: - result = "There is not enough money to complete the request"; - break; - - // - case TRADE_RETCODE_PRICE_CHANGED: - result = "Prices changed"; - break; - - // - case TRADE_RETCODE_PRICE_OFF: - result = "There are no quotes to process the request"; - break; - - // - case TRADE_RETCODE_INVALID_EXPIRATION: - result = "Invalid order expiration date in the request"; - break; - - // - case TRADE_RETCODE_ORDER_CHANGED: - result = "Order state changed"; - break; - - // - case TRADE_RETCODE_TOO_MANY_REQUESTS: - result = "Too frequent requests"; - break; - - // - case TRADE_RETCODE_NO_CHANGES: - result = "No changes in request"; - break; - - // - case TRADE_RETCODE_SERVER_DISABLES_AT: - result = "Autotrading disabled by server"; - break; - - // - case TRADE_RETCODE_CLIENT_DISABLES_AT: - result = "Autotrading disabled by client terminal"; - break; - - // - case TRADE_RETCODE_LOCKED: - result = "Request locked for processing"; - break; - - // - case TRADE_RETCODE_FROZEN: - result = "Order or position frozen"; - break; - - // - case TRADE_RETCODE_INVALID_FILL: - result = "Invalid order filling type"; - break; - - // - case TRADE_RETCODE_CONNECTION: - result = "No connection with the trade server"; - break; - - // - case TRADE_RETCODE_ONLY_REAL: - result = "Operation is allowed only for live accounts"; - break; - - // - case TRADE_RETCODE_LIMIT_ORDERS: - result = "The number of pending orders has reached the limit"; - break; - - // - case TRADE_RETCODE_LIMIT_VOLUME: - result = "The volume of orders and positions for the symbol has reached the limit"; - break; - - // - default: - result = "Invalid return code of the trade server"; - break; - } - - // - return result; - } - - // - // Protected ... -protected: - // - // Private ... - - // - bool CanLog() - { - return mLogAlerts; - } - - // - bool CanLogAlert() - { - // - bool result = GetEnableAlerts() && GetLogAlerts(); - - // - return result; - } - - // - bool CanTerminalAlert() - { - // - bool result = GetEnableAlerts() && GetTerminalAlerts(); - - // - return result; - } - - // - bool CanMailAlert() - { - // - bool result = GetEnableAlerts() && GetMailAlerts(); - - // - return result; - } - - // - bool CanPushAlert() - { - // - bool result = GetEnableAlerts() && GetPushAlerts(); - - // - return result; - } - -private: - // - // Props ... - string mPrefix; // Alerts Prefixe - bool mEnableAlerts; // Enable Alerts - bool mLogAlerts; // Log Alerts - bool mTerminalAlerts; // Terminal Alerts - bool mMailAlerts; // Mail Alerts - bool mPushAlerts; // Push Alerts - - // - // Tools ... - - // - // Clear Escape String and - // Attach Alert Prefix to Message ... - string PrepareMessage(string message) - { - // - StringReplace(message, "\n", " | "); - - // - StringConcatenate(message, GetPrefix(), " > ", message); - - // - return message; - } -}; - -// -// a Base Class by Support Alert ... -class XSCBaseAlert : public XSCBase -{ - // - // Public ... -public: - // - // Props ... - - // - // Constructor(s) ... - void XSCBaseAlert() - { - // - // Instance Alert ... - mAlert = new XSCAlert(); - } - - // - // Deconstructors ... - void ~XSCBaseAlert() - { - // - delete mAlert; - } - - // - // Alert Handler Functions ... - - // - // Alert Functions Getter(s) / Setters(s) ... - - // - string GetAlertPrefix() - { - return mAlert.GetPrefix(); - } - - // - void SetAlertPrefix(string value) - { - mAlert.SetPrefix(value); - } - - // - bool GetAlertLogAlerts() - { - return mAlert.GetLogAlerts(); - } - - // - void SetAlertLogAlerts(bool value) - { - mAlert.SetLogAlerts(value); - } - - // - bool GetAlertEnableAlerts() - { - return mAlert.GetEnableAlerts(); - } - - // - void SetAlertEnableAlerts(bool value) - { - mAlert.SetEnableAlerts(value); - } - - // - bool GetAlertPushAlerts() - { - return mAlert.GetPushAlerts(); - } - - // - void SetAlertPushAlerts(bool value) - { - mAlert.SetPushAlerts(value); - } - - // - bool GetAlertMailAlerts() - { - return mAlert.GetMailAlerts(); - } - - // - void SetAlertMailAlerts(bool value) - { - mAlert.SetMailAlerts(value); - } - - // - bool GetAlertTerminalAlerts() - { - return mAlert.GetTerminalAlerts(); - } - - // - void SetAlertTerminalAlerts(bool value) - { - mAlert.SetTerminalAlerts(value); - } - - // - // Alert Actions ... - - // - // Logging an Alert ... - void LogAlert(string message) - { - mAlert.LogAlert(message); - } - - // - // Terminal Alert ... - void TerminalAlert(string message) - { - mAlert.TerminalAlert(message); - } - - // - // Mail Alert ... - void MailAlert(string message) - { - mAlert.MailAlert(message); - } - - // - // Send Push Notification ... - void PushAlert(string message) - { - mAlert.PushAlert(message); - } - - // - // Send an Alert by Handling all Different Specified - // type's of Alert's if they are Enabled ... - void Alert(string message) - { - mAlert.Alert(message); - } - - // - // Logs ... - - // - // Log a Message ... - void Log(string message) - { - mAlert.Log(message); - } - void Log(string tag, string message) - { - mAlert.Log(tag, message); - } - void LogEmpty() - { - mAlert.LogEmpty(); - } - - // - // Log Specific Array ... - template - void LogArray( - T &array[], // Array to Log - string label = NULL // Array Label - ) - { - mAlert.LogArray(array, label); - } - - // - // Error ... - - // - // Log an Error ... - void LogError( - int error = -1 // Specific Error, if it's equal to -1, use Last Error ... - ) - { - mAlert.LogError(error); - } - - // - // Retrieve Specified Error Code Description ... - string GetErrorDescription(int err_code) - { - return mAlert.GetErrorDescription(err_code); - } - - // - // Retrieve Specified Error Code Description ... - string GetTradeServerReturnCodeDescription(int return_code) - { - return mAlert.GetTradeServerReturnCodeDescription(return_code); - } - - // - // Protected ... -protected: - // - // Alert ... - XSCAlert *mAlert; - - // - // Private ... -private: -}; - -// \ No newline at end of file diff --git a/Documents/Pack/V1.0/Source/Classes/x-saherelm.xea.class.mq5 b/Documents/Pack/V1.0/Source/Classes/x-saherelm.xea.class.mq5 deleted file mode 100644 index 919d3673..00000000 --- a/Documents/Pack/V1.0/Source/Classes/x-saherelm.xea.class.mq5 +++ /dev/null @@ -1,1776 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Class Library -// ---------------------------------------------- -// Name: XSCBaseEA -// Description: provides all Base EA 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.xalert.class.mq5" -#include "../Classes/x-saherelm.xtrade.class.mq5" - -// -// Define On Signal Event Handler Type ... -typedef void (*TOnSignal)(XSignal &signal); - -// -// Class Definition ... - -class XSCBaseEA : public XSCBaseAlert -{ - // - // Public ... -public: - // - // Props ... - - // - // Trade Class Instance ... - XSCTrade *mTrader; - - // - // Constructor ... - XSCBaseEA( - // - // XTrade Class Requirements ... - int slippage, // Specify Slippage - ulong magicNumber, // Specify Magic Number - // - // Event Handlers ... - TOnSignal onSignal = NULL, // On Signal Recieved Event Handler - TOnModify onModifyPosition = NULL, // On Modify Position Event Handler - TOnStopLoss onStopLossTriggered = NULL, // On StopLoass Triggered Event Handler - TOnTakeProfit onTakeProfitTriggered = NULL, // On TakeProfit Triggered Event Handler - TOnForceClose onForceClosePosition = NULL, // On Force Close Position Event Handler - TOnPartialClose onPartialClosePosition = NULL, // On Partial Close Position Event Handler - TOnDealsChanged onDealsChangedHandler = NULL, // On Deals Changed Event Handler - TOnOrdersChanged onOrdersChangedHandler = NULL, // On Orders Changed Event Handler - TOnPositionsChanged onPositionsChangedHandler = NULL, // On Positions Changed Event Handler - TOnTradeStateChanged onTradeStateChangedHandler = NULL // On Trade State Changed Event Handler - ) - { - // - // Instance XSCTrade Class ... - mTrader = new XSCTrade( - slippage, - magicNumber // - ); - - // - mIsInTestMode = IsRunningOnTestMode(); - mStaticBalanceForCalculateDrawdown = 0; // Ignore ... - - // - // Set Event Handlers ... - mOnSignal = onSignal; - mOnModifyPosition = onModifyPosition; - mOnStopLossTriggered = onStopLossTriggered; - mOnForceClosePosition = onForceClosePosition; - mOnTakeProfitTriggered = onTakeProfitTriggered; - mOnDealsChangedHandler = onDealsChangedHandler; - mOnPartialClosePosition = onPartialClosePosition; - mOnOrdersChangedHandler = onOrdersChangedHandler; - mOnPositionsChangedHandler = onPositionsChangedHandler; - mOnTradeStateChangedHandler = onTradeStateChangedHandler; - - // - if (mOnSignal != NULL) - { - AddOnSignalEventHandler(mOnSignal); - } - - // - if (mOnModifyPosition != NULL) - { - mTrader.AddOnModifyPositionEventHandler(mOnModifyPosition); - } - - // - if (mOnForceClosePosition != NULL) - { - mTrader.AddOnForceClosePositionEventHandler(mOnForceClosePosition); - } - - // - if (mOnPartialClosePosition != NULL) - { - mTrader.AddOnPartialClosePositionEventHandler(mOnPartialClosePosition); - } - - // - if (mOnStopLossTriggered != NULL) - { - mTrader.AddOnStopLossEventHandler(mOnStopLossTriggered); - } - - // - if (mOnTakeProfitTriggered != NULL) - { - mTrader.AddOnTakeProfitEventHandler(mOnTakeProfitTriggered); - } - - // - if (mOnDealsChangedHandler != NULL) - { - mTrader.AddOnDealsChangedEventHandler(mOnDealsChangedHandler); - } - - // - if (mOnOrdersChangedHandler != NULL) - { - mTrader.AddOnOrdersChangedEventHandler(mOnOrdersChangedHandler); - } - - // - if (mOnPositionsChangedHandler != NULL) - { - mTrader.AddOnPositionsChangedEventHandler(mOnPositionsChangedHandler); - } - - // - if (mOnTradeStateChangedHandler != NULL) - { - mTrader.AddOnTradeStateChangedEventHandler(mOnTradeStateChangedHandler); - } - } - - // - // Deconstractor ... - ~XSCBaseEA() - { - // - delete mTrader; - } - - // - // Properties Getter(s) / Setter(s) ... - - // - // Retrieve Slippage ... - int GetSlippage() - { - return mTrader.GetSlippage(); - } - - // - // Retrieve Magic Number ... - ulong GetMagicNumber() - { - return mTrader.GetMagicNumber(); - } - - // - double GetDrawdownPercent() - { - // - CalculateMaxDrawdown(); - return mDrawdownPercent; - } - - // - void AddOnSignalEventHandler(TOnSignal handler) - { - // - Add( - handler, - mOnSignalEventHandlers // - ); - } - - // - double MinRequiredProfitPerTrade() - { - return mMinRequiredProfitPerTrade; - } - - // - void MinRequiredProfitPerTrade(double value) - { - // - if (value < 0) - { - value = 0; - } - - // - mMinRequiredProfitPerTrade = value; - } - - // - double MinRequiredProfitPerVolumeFactor() - { - return mMinRequiredProfitPerVolumeFactor; - } - - // - void MinRequiredProfitPerVolumeFactor(double value) - { - // - if (value < 0) - { - value = 0; - } - - // - if (value > 0 && value < 0.01) - { - value = 0.01; - } - - // - mMinRequiredProfitPerVolumeFactor = value; - } - - // - int RestingAfterHedge() - { - return mRestingAfterHedge; - } - - // - void RestingAfterHedge(int value) - { - // - if (value < 0) - { - value = 0; - } - - // - mRestingAfterHedge = value; - } - - // - // Overrides ... - - // - // Customize Token ... - virtual string GetToken() - { - return GetSpecificToken(this); - } - - // - virtual string GetTag() - { - return this.GetToken(); - } - - // - // Virtual Functions ... - - // - // Handle Chart Events ... - virtual void OnChartEvent( - const int id, // event ID - const long &lparam, // long type event parameter - const double &dparam, // double type event parameter - const string &sparam // string type event parameter - ) - { - } - - // - // OnTick Handler ... - virtual void OnTick() - { - // - CalculateMaxDrawdown(); - - // - // Draw ... - Draw(); - - // - // Check Trade Events ... - OnTrade(); - - // - SyncSupports(); - - // - // First Check For Any Guard Actions ... - // then Handle Guards if Provided ... - XGuard guards[]; - bool hasGuard = CheckForGuard(guards); - if (hasGuard) - { - DoGuards(guards); - } - - // - XSignal signals[]; - - // - // Second Check for Position Management or Equity Management - // Actions like Supports or etc ... - bool isIgnored = HandleStateManagement(signals); - if (isIgnored) - { - return; - } - - // - // Check Sleeping State ... - bool isSlept = IsSlept(); - if (isSlept) - { - return; - } - - // - // Second Check For Signals ... - // then Execute Signals if Provided ... - int signalsCount = RequestForSignal(signals); - if (signalsCount <= 0) - { - return; - } - - // - // Execute Signals ... - HandleSignalsExecution(signals); - } - - // - // These are Some Event Handler ... - - // - // Calls whenever a signal Executed ... - virtual void OnSignalExecuted(const XSignal &signal) {} - - // - // Cals whenever a Signal Execution Failed ... - virtual void OnSignalExecutionFailed( - const XSignal &signal, - const ENUM_X_SIGNAL_EXECUTION_RESULT reason // - ) - { - } - - // - // Calls when a Position Modified ... - virtual void OnPositionModified( - const XPosition &position, - const string comment // - ) - { - } - - // - // Calls when a Position Closed ... - virtual void OnPositionClosed( - const XPosition &position, - const string comment // - ) - { - } - - // - // Calls when a Position Partially Closed ... - virtual void OnPositionPartialyClosed( - const XPosition &position, - const string comment // - ) - { - } - - // - // Handle StopLoss Event ... - virtual void OnStopLossTriggered(const XDeal &deal) {} - - // - // Handle TakeProfit Event ... - virtual void OnTakeProfitTriggered(const XDeal &deal) {} - - // - // Handle Deals Changed Event ... - virtual void OnDealsChangedHandler(int count) {} - - // - // Handle Order Changed Event ... - virtual void OnOrdersChangedHandler(int count) {} - - // - // Handle Position Changed Event ... - virtual void OnPositionsChangedHandler(int count) {} - - // - // Handle Trade State Changed ... - virtual void OnTradeStateChangedHandler(const XOnTradeHandlerState &state) {} - - // - // Handle On Trade ... - virtual void OnTrade() - { - // - XOnTradeHandlerState state = mTrader.HandleOnTrade(); - - // - if ( - !state.hasNewDeal && - !state.hasNewOrder && - !state.hasNewPosition && - !state.hasNewHistoryOrder) - { - return; - } - - // - // STATE ... - - // - // Notfy Trade State Changed Event ... - OnTradeStateChangedHandler(state); - - // - // DEALS ... - if (state.hasNewDeal) - { - // - // Notfy Deals Changed Event ... - OnDealsChangedHandler(state.newDeals); - - // - // Retrieve Last Deal ... - XDeal deals[]; - mTrader.GetDeals(deals); - int dealsCount = ArraySize(deals); - if (dealsCount > 0) - { - // - XDeal lastDeal = deals[0]; - - // - if (lastDeal.reason == DEAL_REASON_TP) - { - OnTakeProfitTriggered(lastDeal); - } - else if (lastDeal.reason == DEAL_REASON_SL) - { - OnStopLossTriggered(lastDeal); - } - } - } - - // - // ORDERS ... - if (state.hasNewOrder || state.hasNewHistoryOrder) - { - // - // Notfy Orders Changed Event ... - OnOrdersChangedHandler(state.newOrders + state.newHistoryOrders); - } - - // - // POSITIONS ... - if (state.hasNewPosition) - { - // - // Notfy Positions Changed Event ... - OnPositionsChangedHandler(state.newPositions); - } - } - - // - // Retrieve Dept Of Market ... - virtual void OnBookEvent(const string &symbol) - { - // - // TODO: Implement this ... - } - - // - // Draw On Chart if anything is required ... - virtual void Draw() {} - - // - // Check For any Guard Actions ... - virtual bool CheckForGuard(XGuard &guards[]) - { - return false; - } - - // - // When a Guard Notified to Do Support Signal ... - // this Method Calls For Retrieve Support Signal ... - // if it's Provided, Execute it ... - virtual bool RequestForSupport( - XSignal &support, // Holds Support Signal, if Provided - string provider, // Positions Provided by Specific Provider - string symbol, // Trading Symbol - ENUM_X_POSITION_TYPES type, // Trading Type - ENUM_TIMEFRAMES period // Specified Time Frame - ) - { - return false; - } - - // - // Handle Position(s)/ Order(s) or EQM Supporting Action ... - // if returns true, prevent for process Tick ... - virtual bool HandleStateManagement(XSignal &signals[]) - { - return false; - } - - // - // Regulary Filtered Signals passed to this - // and here we can do Additional Signal Filtering - // for Signal Management such as (Providers and etc) ... - virtual int HandleSignalManagement(XSignal &signals[]) - { - // - int result = ArraySize(signals); - - // - return result; - } - - // - // Here we Have to Check Market based - // on our Strategy for Trading ... - // and if a Good Entry founded ... - // model it as an XSignal struct and passed it to result ... - virtual int RequestForSignal( - XSignal &signals[] // Holds Signals ... - ) - { - return 0; - } - - // - // Execute Provided Signals ... - virtual void HandleSignalsExecution(XSignal &signals[]) - { - // - int signalsCount = ArraySize(signals); - if (signalsCount <= 0) - { - return; - } - - // - int managedSignalsCount = HandleSignalManagement(signals); - if (managedSignalsCount <= 0) - { - return; - } - - // - // Notify Signal Event Handlers for Reciving New Signal ... - for (int i = 0; i < managedSignalsCount; i++) - { - NotifyOnSignalEventHandlers(signals[i]); - } - - // - // Try to Execute Signals ... - ENUM_X_SIGNAL_EXECUTION_RESULT reasons[]; - int executedSignalsCount = ExecuteSignals( - signals, - reasons // - ); - } - - // - // Tools ... - - // - // Calculate Max Drawdown and it's Percent ... - double CalculateMaxDrawdown() - { - // - int positionsCount = PositionsTotal(); - if (IsValidSize(positionsCount)) - { - double mEquity = mTrader.mAccount.GetEquity(); - if (mEquity > mMaxDrawdown) - { - mMaxDrawdown = mEquity; - } - - // - mDrawdownPercent = (mMaxDrawdown - mEquity) / (mStaticBalanceForCalculateDrawdown > 0 ? mStaticBalanceForCalculateDrawdown : mMaxDrawdown) * 100; - mDrawdownPercent = NormalizeDouble(mDrawdownPercent, 3); - } - else - { - // - mMaxDrawdown = 0.0; - mDrawdownPercent = 0.0; - } - - // - return mDrawdownPercent; - } - - // - // Protected ... -protected: - // - // Props ... - - // - // Check in Test Mode or not ... - bool mIsInTestMode; - - // - // Save Max Drawdown ... - double mMaxDrawdown; - double mDrawdownPercent; - double mStaticBalanceForCalculateDrawdown; - - // - - // - // Tools ... - - // - // Since we need to Calls Some Event Handlers on - // - Signal Execution; - // - Modified; - // - Closed; - // - Partial Closed; - // events ... - // we have to implement thouse Methods here and use them ... - - // - // Execute Stand alone Signal ... - bool ExecuteSignal( - XSignal &signal, // Signal - ENUM_X_SIGNAL_EXECUTION_RESULT &state, // Result - bool checkPolicies = true, // Check Account Policies - ENUM_ORDER_TYPE_TIME lifetime = ORDER_TIME_GTC, // Order LifeTime - datetime expiration = NULL // order expiration time - ) - { - // - bool result = false; - - // - result = mTrader.ExecuteSignal( - signal, - state, - lifetime, - expiration, - checkPolicies // - ); - if (result) - { - // - OnSignalExecuted(signal); - - // - string message = "Signal Executed (" + ToString(signal.positionId) + ") Successfully ..."; - - // - Alert(message); - } - else - { - // - OnSignalExecutionFailed(signal, state); - - // // - // string message = "Signal Execution Failed: " + ToString(state) + " ..."; - - // // - // Alert(message); - } - - // - return result; - } - - // - // Execute a Collection of Signals ... - int ExecuteSignals( - XSignal &signals[], // Collection of Signal for Execution - ENUM_X_SIGNAL_EXECUTION_RESULT &states[], // Signal Execution Result - bool checkPolicies = true, // Check Account Policies - ENUM_ORDER_TYPE_TIME lifetime = ORDER_TIME_GTC, // Order LifeTime - datetime expiration = NULL // order expiration time - ) - { - // - int result = 0; - - // - int signalsCount = ArraySize(signals); - if (!IsValidSize(signalsCount)) - { - return result; - } - - // - Clean(states); - ArrayResize(states, signalsCount, X_SIGNAL_EXECUTION_UNKNOWN); - - // - for (int i = 0; i < signalsCount; i++) - { - // - bool isExecuted = ExecuteSignal( - signals[i], - states[i], - checkPolicies, - lifetime, - expiration // - ); - if (isExecuted) - { - result++; - } - } - - // - return result; - } - - // - // Modify ... - bool Modify( - ulong ticket, // position ticket - double sl = 0, // stop loss price - double tp = 0, // take profit - string comment = NULL // comment - ) - { - // - bool result = false; - - // - result = mTrader.Modify( - ticket, - sl, - tp, - comment // - ); - - // - if (result) - { - // - XPosition position; - result = mTrader.GetPosition( - ticket, - position // - ); - if (result) - { - // - OnPositionModified( - position, - comment // - ); - - // - string message = "Position " + ToString(ticket) + " Modified Successfully ..."; - - // - Alert(message); - } - } - - // - return result; - } - - // - // Close ... - bool Close( - ulong ticket, - string comment // - ) - { - // - bool result = false; - - // - XPosition position; - result = mTrader.GetPosition( - ticket, - position // - ); - - // - result = mTrader.Close( - ticket, - comment // - ); - - // - if (result) - { - // - OnPositionClosed( - position, - comment // - ); - - // - string message = "Position " + ToString(ticket) + " Closed Successfully ..."; - - // - Alert(message); - } - - // - return result; - } - - // - // Close ... - int Close( - XPosition &positions[], - string comment // - ) - { - // - int result = 0; - - // - int count = ArraySize(positions); - if (!IsValidSize(count)) - { - return result; - } - - // - for (int i = 0; i < count; i++) - { - // - bool isClosed = Close( - positions[i].ticket, - comment // - ); - - // - if (isClosed) - { - result++; - } - } - - // - return result; - } - - // - // Partial Close ... - bool PartialClose( - ulong ticket, - double volume, - string comment // - ) - { - // - bool result = false; - - // - XPosition position; - result = mTrader.GetPosition( - ticket, - position // - ); - if (!result) - { - return result; - } - - // - result = mTrader.ClosePartial( - ticket, - volume, - comment // - ); - - // - if (result) - { - // - OnPositionPartialyClosed( - position, - comment // - ); - - // - string message = "Position " + ToString(ticket) + " Successfully Closed Parital ..."; - - // - Alert(message); - } - - // - return result; - } - - // - // Partial Close ... - int PartialClose( - XPosition &positions[], - double volume, - string comment // - ) - { - // - int result = 0; - - // - int count = ArraySize(positions); - if (!IsValidSize(count)) - { - return result; - } - - // - for (int i = 0; i < count; i++) - { - // - bool isClosed = PartialClose( - positions[i].ticket, - volume, - comment // - ); - - // - if (isClosed) - { - result++; - } - } - - // - return result; - } - - // - int CancelOrders() - { - // - int result = 0; - - // - XOrder supports[]; - int supportsCount = mTrader.GetOrders( - supports, - NULL, // All Symbols ... - XEQMSupportToken, // Only EQM Supports ... - NULL, // All Periods ... - X_POSITION_TYPE_ALL, // All Order Types ... - ORDER_STATE_PLACED, // Untriggered Orders ... - true // Filter by Magic ... - ); - if (!IsValidSize(supportsCount)) - { - return result; - } - - // - result = mTrader.CancelOrders( - supports // - ); - - // - return result; - } - - // - // Search Positions and Remove - // non Exists Positions Support Orders ... - void SyncSupports() - { - // - XOrder orders[]; - int ordersCount = mTrader.GetOrders( - orders, - NULL, // All Symbols ... - NULL, // All Providers ... - NULL, // All Periods ... - X_POSITION_TYPE_ALL, // All Types ... - ORDER_STATE_PLACED, // Placed Untriggered Orders ... - true // Filter by Magic ... - ); - if (!IsValidSize(ordersCount)) - { - return; - } - - // - XPosition positions[]; - int positionsCount = mTrader.GetPositions( - positions // - ); - if (!IsValidSize(positions)) - { - // - mTrader.CancelOrders(orders); - return; - } - - // - XOrder mustCancel[]; - for (int i = 0; i < ordersCount; i++) - { - // - XOrder iOrder = orders[i]; - - // - // Check Order is Support or not ... - ulong iParentTicket = ExtractSupportedTicket(iOrder.comment); - if (iParentTicket <= 0) - { - continue; - } - - // - // We Sure it is support Order ... - XPosition parent; - bool isParentExists = mTrader.GetPosition( - iParentTicket, - parent // - ); - if (!isParentExists) - { - // - AddRef( - iOrder, - mustCancel // - ); - } - } - - // - int mustCancelCount = ArraySize(mustCancel); - if (!IsValidSize(mustCancelCount)) - { - return; - } - - // - mTrader.CancelOrders(mustCancel); - } - - // - // Hedging ... - - // - // Check Required Properties Setted for Hedge or not ... - bool AllowHedge() - { - // - bool result = false; - - // - result = - // - mMinRequiredProfitPerTrade > 0 && - mMinRequiredProfitPerVolumeFactor > 0 - // - ; - - // - return result; - } - - // - // Check Hedge Conditions is Happens or not ... - // if true doing Hedge ... - bool DoHedge() - { - // - bool result = false; - - // - result = AllowHedge(); - if (!result) - { - return result; - } - - // - XPosition positions[]; - int positionsCount = mTrader.GetPositions(positions); - result = positionsCount > 1; - if (!result) - { - return result; - } - - // - // Check At Least One Support Positions Open For Hedging ... - // XPosition supports[]; - // int supportsCount = ExtractSupports( - // positions, - // supports // - // ); - // result = IsValidSize(supportsCount); - // if (!result) - // { - // return result; - // } - - // - double profits = SpecifiedCalculatePositionsProfit(positions); - double requiredProfit = SpecifiedCalculateRequiredProfitForHedge( - positions, - mMinRequiredProfitPerTrade, - mMinRequiredProfitPerVolumeFactor // - ); - - // - result = profits >= requiredProfit; - if (!result) - { - return result; - } - - // - string comment = XEQMSupportToken + " Hedge ..."; - - // - int closed = Close( - positions, - comment // - ); - result = IsValidSize(closed); - if (!result) - { - return result; - } - - // - SyncSupports(); - - // - string message = XEQMSupportToken + " Hedge: " + ToString(profits) + " ..."; - - // - Alert(message); - - // - if (mRestingAfterHedge > 0) - { - Sleeping(mRestingAfterHedge); - } - - // - return result; - } - - // - // Signal Event Listeners ... - - // - void NotifyOnSignalEventHandlers(XSignal &signal) - { - // - int listenersCount = ArraySize(mOnSignalEventHandlers); - if (listenersCount <= 0) - { - return; - } - - // - for (int i = 0; i < listenersCount; i++) - { - // - TOnSignal iListener = mOnSignalEventHandlers[i]; - - // - iListener(signal); - } - } - - // - // 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_X_POSITION_TYPES type, // Trading Type - ENUM_TIMEFRAMES period, // Specified Time Frame - double minProfitForHedging = 1, // Specified Profit for Hedge - double minProfitForHedgingVolumeFactor = 0.01 // Specified Volume Factor for Hedge - ) - { - // - XPosition positions[]; - int positionsCount = mTrader - .GetPositions( - positions, - symbol, - provider, - period, - type - // - ); - if (positionsCount <= 1) - { - return; - } - - // - double profit = SpecifiedCalculatePositionsProfit(positions); - double requiredProfit = SpecifiedCalculateRequiredProfitForHedge( - positions, - minProfitForHedging, - minProfitForHedgingVolumeFactor // - ); - - // - 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); - - // - Alert(message); - } - } - - // - // Close Max In Profit Trade Guard Action ... - void HandleGuardCloseInProfitAction( - string provider, // Positions Provided by Specific Provider - string symbol, // Trading Symbol - ENUM_X_POSITION_TYPES 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 ..."; - - // - Alert(message); - } - - // - // Close Max In Drawdown Trade Guard Action ... - void HandleGuardCloseInDrawdownAction( - string provider, // Positions Provided by Specific Provider - string symbol, // Trading Symbol - ENUM_X_POSITION_TYPES 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 ..."; - - // - Alert(message); - } - - // - // Force Close Specified Set Of Position ... - void HandleGuardForceCloseAction( - string provider, // Positions Provided by Specific Provider - string symbol, // Trading Symbol - ENUM_X_POSITION_TYPES 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)) - { - Alert(comment); - } - } - - // - // Trailing Specified Set Of Positions Stop Losses ... - void HandleGuardTrailingStopAction( - string provider, // Positions Provided by Specific Provider - string symbol, // Trading Symbol - ENUM_X_POSITION_TYPES 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 ..."; - - // - Alert(message); - } - } - - // - // Add Support Signal for Specified Positions ... - void HandleGuardAddSupportPositionAction( - string provider, // Positions Provided by Specific Provider - string symbol, // Trading Symbol - ENUM_X_POSITION_TYPES 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 = 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)) - { - Alert(comment); - } - } - - // - // Cancel all Placed Orders ... - void HandleGuardCancelPendingOrdersAction( - string provider, // Positions Provided by Specific Provider - string symbol, // Trading Symbol - ENUM_X_POSITION_TYPES type, // Trading Type - ENUM_TIMEFRAMES period // Specified Time Frame - ) - { - // - XOrder orders[]; - int ordersCount = mTrader.GetOrders( - orders, - symbol, - provider, - period, - 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 ..."; - - // - Alert(message); - } - } - - // - // Sleeping Context ... - - // - // Sleeping Mode ... - int mSleepingDuration; - datetime mSleepingStartAt; - bool Sleeping(int seconds = -1) - { - // - bool result = false; - - // - mSleepingDuration = - seconds > 0 - ? seconds - : mRestingAfterHedge > 0 - ? mRestingAfterHedge - : 0; - result = mSleepingDuration > 0; - if (!result) - { - // - ResetSleeping(); - return result; - } - - // - // Check Doesnt Sleep Before ... - result = mSleepingStartAt == NULL; - if (!result) - { - // - ResetSleeping(); - return result; - } - - // - datetime cTime = TimeCurrent(); - mSleepingStartAt = cTime; - - // - return result; - } - bool IsSlept() - { - // - bool result = false; - - // - result = mSleepingDuration > 0 && - mSleepingStartAt != NULL; - if (!result) - { - // - ResetSleeping(); - return result; - } - - // - datetime cTime = TimeCurrent(); - result = (int)cTime < (int)mSleepingStartAt + mSleepingDuration; - if (!result) - { - ResetSleeping(); - } - - // - return result; - } - void ResetSleeping() - { - // - mSleepingDuration = 0; - mSleepingStartAt = NULL; - } - - // - // Private ... -private: - // - // Props ... - - // - int mRestingAfterHedge; // Resting Bars After Hedge - double mMinRequiredProfitPerTrade; // Minimum Required Profit for Hedging - double mMinRequiredProfitPerVolumeFactor; // Minimum Required Profit for Hedging Per Velume - - // - // Signal Event Listeners ... - TOnSignal mOnSignalEventHandlers[]; - - // - // Event Handlers ... - TOnSignal mOnSignal; - TOnModify mOnModifyPosition; - TOnStopLoss mOnStopLossTriggered; - TOnTakeProfit mOnTakeProfitTriggered; - TOnForceClose mOnForceClosePosition; - TOnDealsChanged mOnDealsChangedHandler; - TOnPartialClose mOnPartialClosePosition; - TOnOrdersChanged mOnOrdersChangedHandler; - TOnPositionsChanged mOnPositionsChangedHandler; - TOnTradeStateChanged mOnTradeStateChangedHandler; -}; - -// \ No newline at end of file diff --git a/Documents/Pack/V1.0/Source/Classes/x-saherelm.xhelper.class.mq5 b/Documents/Pack/V1.0/Source/Classes/x-saherelm.xhelper.class.mq5 deleted file mode 100644 index 966eb8d9..00000000 --- a/Documents/Pack/V1.0/Source/Classes/x-saherelm.xhelper.class.mq5 +++ /dev/null @@ -1,148 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Class Library -// ---------------------------------------------- -// Name: XSCBaseHelper -// Description: provides all Base 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 - -// -// Includes ... -#include "../Classes/x-saherelm.base.class.mq5" - -// -// Definitions ... - -// -// a Class for Handle base requirements ... -// for indicators ... -class XSCBaseHelper : public XSCBase -{ - // - // Public ... -public: - // - // Constructor ... - void XSCBaseHelper( - string symbol, // Trading Symbol - ENUM_TIMEFRAMES period // Trading Time Frame - ) - { - // - mSymbol = symbol; - mPeriod = period; - } - - // - // Deconstructor ... - void ~XSCBaseHelper() - { - // - IndicatorRelease(mHandler); - } - - // - // Setter(s) / Getter(s) ... - - // - // Symbol ... - string GetSymbol() - { - return mSymbol; - } - - // - // Period ... - ENUM_TIMEFRAMES GetPeriod() - { - return mPeriod; - } - - // - // Retrieve Bars ... - int CountBars() - { - // - int result = - Bars( - mSymbol, - mPeriod - // - ); - - // - return result; - } - - // - // Retrieve Indicator Calculated Bars ... - int CountCalculatedBars() - { - return BarsCalculated(mHandler); - } - - // - // Generate Tag ... - virtual string GetTag() - { - // - string result = NULL; - - // - result = - // - GetToken() + - "[" + - GetSymbol() + "|" + - ToString(GetPeriod()) + - "]" - // - ; - - // - return result; - } - - // - // Functions ... - - // - // Protected ... -protected: - // - // Props ... - - // - // Symbol ... - string mSymbol; - - // - // Period ... - ENUM_TIMEFRAMES mPeriod; - - // - // Indicator Handler ... - int mHandler; - - // - // Private ... -private: - // -}; - -// -// Tools .... \ No newline at end of file diff --git a/Documents/Pack/V1.0/Source/Classes/x-saherelm.xhttp.class.mq5 b/Documents/Pack/V1.0/Source/Classes/x-saherelm.xhttp.class.mq5 deleted file mode 100644 index 82adadb6..00000000 --- a/Documents/Pack/V1.0/Source/Classes/x-saherelm.xhttp.class.mq5 +++ /dev/null @@ -1,373 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Class Library -// ---------------------------------------------- -// Name: XSCHttp -// Description: provides all HTTP 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 - -// -// Definitions ... - -// -enum X_HTTP_METHOD -{ - X_HTTP_GET, - X_HTTP_POST -}; - -// -// Imports ... - -// -// Includes ... -#include "../Classes/x-saherelm.base.class.mq5" -#include "../Libraries/x-saherelm.common.lib.mq5" - -// -// a Class for Manage Account ... -class XSCHttp : public XSCBase -{ - // - // Public ... -public: - // - // Constructor ... - void XSCHttp() - { - XSCHttp("", 10000); - } - void XSCHttp( - string path, // Base Folder to Store Data - int timeout // base timeout for Requests - ) - { - // - Path(path); - Timeout(timeout); - } - - // - // Deconstructor ... - void ~XSCHttp() - { - } - - // - // Properties Getter(s) / Setter(s) ... - - // - // Path ... - void Path(string value) - { - // - mPath = value; - - // - if (!IsValid(mPath)) - { - mPath = GetTag(); - } - } - - string Path() - { - return mPath; - } - - // - // Timeout ... - void Timeout(int value) - { - mTimeout = value; - } - - // - int Timeout() - { - return mTimeout; - } - - // - // Error ... - int Error() - { - return mError; - } - - // - // Response ... - string Response() - { - return mResponse; - } - - // - // Overrides ... - string GetTag() override - { - return GetSpecificToken(this); - } - - // - // Tools ... - - // - // Send Global Request ... - int SendRequest( - X_HTTP_METHOD method, // Httm Request Method - const string url, // Server Address - const string headers, // Headers providing - const char &payload[], // the Data which needs to Send - char &response[], // Response of request - string responseHeaders, // Response Headers - int timeout = 500 // Timeout for response default is 500 - ) - { - // - int result = -1; - - // - string strMethod = ToString(method); - if (StringLen(strMethod) == 0) - { - return result; - } - - // - // Reset State ... - ResetState(); - - // - result = WebRequest( - strMethod, - url, - headers, - timeout, - payload, - response, - responseHeaders); - - // - if (result < 0) - { - mError = GetLastError(); - } - else - { - mResponse = CharArrayToString(response); - } - - // - return result; - } - - // - // Get Request ... - int GetRequest( - const string url, // Server Address - const string headers, // Headers providing - const char &payload[], // the Data which needs to Send - char &response[], // Response of request - string responseHeaders, // Response Headers - int timeout = 500 // Timeout for response default is 500 - ) - { - // - int result = SendRequest( - X_HTTP_GET, - url, - headers, - payload, - response, - responseHeaders, - timeout); - - // - return result; - } - - // - // Post Request ... - int PostRequest( - const string url, // Server Address - const string headers, // Headers providing - const char &payload[], // the Data which needs to Send - char &response[], // Response of request - string responseHeaders, // Response Headers - int timeout = 500 // Timeout for response default is 500 - ) - { - // - int result = SendRequest( - X_HTTP_POST, - url, - headers, - payload, - response, - responseHeaders, - timeout); - - // - return result; - } - - // - // Handle Download Specific URL Content to Specific Path and File Name ... - bool Download( - string url, // the URL address which going to download - string fileName // Specify Destination file name to Store Response - ) - { - // - bool result = false; - - // - string filePath = GetFilePath(fileName); - string cookie = NULL; - string referer = NULL; - int timeout = Timeout(); - - // - char payload[]; - string headers; - char response[]; - string responseHeaders; - - // - // Send Request ... - int requestResult = GetRequest( - url, - headers, - payload, - response, - responseHeaders, - timeout); - - // - // Define File Handler ... - int mFileHandler = FileOpen( - filePath, - FILE_WRITE | FILE_BIN); - if (mFileHandler == INVALID_HANDLE) - { - // - mError = GetLastError(); - return result; - } - - // - // Write Response to File ... - uint writed = FileWriteArray( - mFileHandler, - response, - 0, - ArraySize(response)); - FileFlush(mFileHandler); - FileClose(mFileHandler); - - // - result = writed > 0; - - // - return result; - } - - // - // END Provided Functions ... - // - - // - // Protected ... -protected: - // - // Destintion Folder Path ... - string mPath; - - // - // WEB Request Timeout Value ... - int mTimeout; - - // - // WEB Request's Response ... - string mResponse; - - // - // Error Value ... - int mError; - - // - // Private ... -private: - // - // Reset Errors State ... - void ResetState() - { - // - // Reset Errors ... - mError = -1; - mResponse = ""; - ResetLastError(); - } - - // - // Generate Full File Path ... - string GetFilePath(string fileName) - { - // - string result = ""; - - // - result = - // - Path() + "\\" + fileName - // - ; - - // - return result; - } -}; - -// -// Tools ... - -// -// Convert enum to String ... -string ToString(X_HTTP_METHOD method) -{ - // - string result = ""; - - // - switch (method) - { - // - case X_HTTP_GET: - result = "GET"; - break; - - // - case X_HTTP_POST: - result = "POST"; - break; - } - - // - return result; -} - -// \ No newline at end of file diff --git a/Documents/Pack/V1.0/Source/Classes/x-saherelm.xmd5.class.mq5 b/Documents/Pack/V1.0/Source/Classes/x-saherelm.xmd5.class.mq5 deleted file mode 100644 index 3311aa5a..00000000 --- a/Documents/Pack/V1.0/Source/Classes/x-saherelm.xmd5.class.mq5 +++ /dev/null @@ -1,441 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Class Library -// ---------------------------------------------- -// Name: XSCMD5 -// Description: Provides MD5 Hashing 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 - -// -// START Definitions ... -// - -// -static uchar _md5_PADDING[64] = - { - 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; - -// -#define _md5_F(x, y, z) (((x) & (y)) | ((~x) & (z))) -#define _md5_G(x, y, z) (((x) & (z)) | ((y) & (~z))) -#define _md5_H(x, y, z) ((x) ^ (y) ^ (z)) -#define _md5_I(x, y, z) ((y) ^ ((x) | (~z))) -#define _md5_ROTATE_LEFT(x, n) (((x) << (n)) | ((x) >> (32 - (n)))) - -// -#define _md5_FF(a, b, c, d, x, s, ac) \ - { \ - (a) += _md5_F((b), (c), (d)) + (x) + (uint)(ac); \ - (a) = _md5_ROTATE_LEFT((a), (s)); \ - (a) += (b); \ - } - -// -#define _md5_GG(a, b, c, d, x, s, ac) \ - { \ - (a) += _md5_G((b), (c), (d)) + (x) + (uint)(ac); \ - (a) = _md5_ROTATE_LEFT((a), (s)); \ - (a) += (b); \ - } - -// -#define _md5_HH(a, b, c, d, x, s, ac) \ - { \ - (a) += _md5_H((b), (c), (d)) + (x) + (uint)(ac); \ - (a) = _md5_ROTATE_LEFT((a), (s)); \ - (a) += (b); \ - } - -// -#define _md5_II(a, b, c, d, x, s, ac) \ - { \ - (a) += _md5_I((b), (c), (d)) + (x) + (uint)(ac); \ - (a) = _md5_ROTATE_LEFT((a), (s)); \ - (a) += (b); \ - } - -// -#define _md5_INIT_STATE_0 0x67452301 -#define _md5_INIT_STATE_1 0xefcdab89 -#define _md5_INIT_STATE_2 0x98badcfe -#define _md5_INIT_STATE_3 0x10325476 - -// -#define _md5_S11 7 -#define _md5_S12 12 -#define _md5_S13 17 -#define _md5_S14 22 - -// -#define _md5_S21 5 -#define _md5_S22 9 -#define _md5_S23 14 -#define _md5_S24 20 - -// -#define _md5_S31 4 -#define _md5_S32 11 -#define _md5_S33 16 -#define _md5_S34 23 - -// -#define _md5_S41 6 -#define _md5_S42 10 -#define _md5_S43 15 -#define _md5_S44 21 - -// -// END Definitions ... -// - -// -// XCMD5 a library for Hashing ... -class XSCMD5 -{ - // - // Public Provides ... -public: - // - // Protected Provides ... - - // - // Constructor ... - XSCMD5(void) {} - - // - // Deconstructor ... - ~XSCMD5(void) {} - - // - // Hash Specified Char Array ... - string Hash( - uchar &mSource[], // Specify Char Array to Hash - int mLength = 0 // Specify Length of Char Array which required to hash - ) - { - // - string result = ""; - - // - int sourceCount = ArraySize(mSource); - - // - // Validate Args ... - if ( - sourceCount <= 0 || - (sourceCount > 0 && mLength > sourceCount)) - { - return result; - } - - // - // Normalize Args ... - if (mLength == 0) - { - mLength = sourceCount; - } - - // - // Init MD5 ... - MD5Init(); - - // - // Update Buffer ... - MD5Update(mSource, mLength); - - // - // Calculate Result ... - result = MD5Final(); - - // - return result; - } - - // - // Hash Specified String ... - string Hash( - string mSource // Specified String - ) - { - // - string result = ""; - - // - // Converts String to Char Array ... - uchar bytes[]; - StringToCharArray( - mSource, - bytes, - 0, - StringLen(mSource)); - - // - result = Hash( - bytes, - ArraySize(bytes)); - - // - return result; - } - -protected: - // - // Private Provides ... -private: - // - uint m_lMD5[4]; - uint m_nCount[2]; - uchar m_lpszBuffer[64]; - - // - // Convert Byte to DWord ... - void ByteToDWord(int &out[], uint &in[], uint len) - { - // - uint i = 0; - uint j = 0; - - // - for (; j < len; i++, j += 4) - { - out[i] = (int)in[j] | (int)in[j + 1] << 8 | (int)in[j + 2] << 16 | (int)in[j + 3] << 24; - } - } - - // - // Convert DWord to Byte ... - void DWordToByte(uchar &out[], int &in[], uint len) - { - // - uint i = 0; - uint j = 0; - - // - for (; j < len; i++, j += 4) - { - // - out[j] = (uchar)(in[i] & 0xff); - out[j + 1] = (uchar)((in[i] >> 8) & 0xff); - out[j + 2] = (uchar)((in[i] >> 16) & 0xff); - out[j + 3] = (uchar)((in[i] >> 24) & 0xff); - } - } - - // - // Init MD5 Array ... - void MD5Init() - { - // - ArrayInitialize(m_lpszBuffer, 64); - - // - m_nCount[0] = m_nCount[1] = 0; - m_lMD5[0] = _md5_INIT_STATE_0; - m_lMD5[1] = _md5_INIT_STATE_1; - m_lMD5[2] = _md5_INIT_STATE_2; - m_lMD5[3] = _md5_INIT_STATE_3; - } - - // - // Update MD5 ... - void MD5Update(uchar &inBuf[], uint inLen) - { - // - int i, ii; - int mdi; - - // - uint in[16]; - int i0 = 0; - - // - mdi = (int)((m_nCount[0] >> 3) & 0x3F); - - // - if ((m_nCount[0] + ((uint)inLen << 3)) < m_nCount[0]) - { - m_nCount[1]++; - } - - // - m_nCount[0] += ((uint)inLen << 3); - m_nCount[1] += ((uint)inLen >> 29); - - // - while ((inLen--) > 0) - { - // - m_lpszBuffer[mdi++] = inBuf[i0++]; - if (mdi == 0x40) - { - // - for (i = 0, ii = 0; i < 16; i++, ii += 4) - { - in[i] = (((uint)m_lpszBuffer[ii + 3]) << 24) | (((uint)m_lpszBuffer[ii + 2]) << 16) | (((uint)m_lpszBuffer[ii + 1]) << 8) | ((uint)m_lpszBuffer[ii]); - } - - // - Transform(m_lMD5, in); - - // - mdi = 0; - } - } - } - - // - // Finalize an MD5 Expression ... - string MD5Final() - { - // - uchar bits[8]; - int nIndex; - uint nPadLen; - const int nMD5Size = 16; - uchar lpszMD5[16]; - string temp; - string out = ""; - int i; - - // - DWordToByte(bits, m_nCount, 8); - nIndex = (int)((m_nCount[0] >> 3) & 0x3f); - nPadLen = (nIndex < 56) ? (56 - nIndex) : (120 - nIndex); - MD5Update(_md5_PADDING, nPadLen); - MD5Update(bits, 8); - DWordToByte(lpszMD5, m_lMD5, nMD5Size); - - // - for (i = 0; i < nMD5Size; i++) - { - // - if (lpszMD5[i] == 0) - { - temp = "00"; - } - else if (lpszMD5[i] <= 15) - { - temp = StringFormat("0%x", lpszMD5[i]); - } - else - { - temp = StringFormat("%x", lpszMD5[i]); - } - - // - out += temp; - } - - // - lpszMD5[0] = '\0'; - - // - return (out); - } - - // - // Transform Buffers ... - void Transform(uint &buf[], uint &in[]) - { - // - uint a = buf[0], b = buf[1], c = buf[2], d = buf[3]; - - // - _md5_FF(a, b, c, d, in[0], _md5_S11, 0xD76AA478); - _md5_FF(d, a, b, c, in[1], _md5_S12, 0xE8C7B756); - _md5_FF(c, d, a, b, in[2], _md5_S13, 0x242070DB); - _md5_FF(b, c, d, a, in[3], _md5_S14, 0xC1BDCEEE); - _md5_FF(a, b, c, d, in[4], _md5_S11, 0xF57C0FAF); - _md5_FF(d, a, b, c, in[5], _md5_S12, 0x4787C62A); - _md5_FF(c, d, a, b, in[6], _md5_S13, 0xA8304613); - _md5_FF(b, c, d, a, in[7], _md5_S14, 0xFD469501); - _md5_FF(a, b, c, d, in[8], _md5_S11, 0x698098D8); - _md5_FF(d, a, b, c, in[9], _md5_S12, 0x8B44F7AF); - _md5_FF(c, d, a, b, in[10], _md5_S13, 0xFFFF5BB1); - _md5_FF(b, c, d, a, in[11], _md5_S14, 0x895CD7BE); - _md5_FF(a, b, c, d, in[12], _md5_S11, 0x6B901122); - _md5_FF(d, a, b, c, in[13], _md5_S12, 0xFD987193); - _md5_FF(c, d, a, b, in[14], _md5_S13, 0xA679438E); - _md5_FF(b, c, d, a, in[15], _md5_S14, 0x49B40821); - - // - _md5_GG(a, b, c, d, in[1], _md5_S21, 0xF61E2562); - _md5_GG(d, a, b, c, in[6], _md5_S22, 0xC040B340); - _md5_GG(c, d, a, b, in[11], _md5_S23, 0x265E5A51); - _md5_GG(b, c, d, a, in[0], _md5_S24, 0xE9B6C7AA); - _md5_GG(a, b, c, d, in[5], _md5_S21, 0xD62F105D); - _md5_GG(d, a, b, c, in[10], _md5_S22, 0x02441453); - _md5_GG(c, d, a, b, in[15], _md5_S23, 0xD8A1E681); - _md5_GG(b, c, d, a, in[4], _md5_S24, 0xE7D3FBC8); - _md5_GG(a, b, c, d, in[9], _md5_S21, 0x21E1CDE6); - _md5_GG(d, a, b, c, in[14], _md5_S22, 0xC33707D6); - _md5_GG(c, d, a, b, in[3], _md5_S23, 0xF4D50D87); - _md5_GG(b, c, d, a, in[8], _md5_S24, 0x455A14ED); - _md5_GG(a, b, c, d, in[13], _md5_S21, 0xA9E3E905); - _md5_GG(d, a, b, c, in[2], _md5_S22, 0xFCEFA3F8); - _md5_GG(c, d, a, b, in[7], _md5_S23, 0x676F02D9); - _md5_GG(b, c, d, a, in[12], _md5_S24, 0x8D2A4C8A); - - // - _md5_HH(a, b, c, d, in[5], _md5_S31, 0xFFFA3942); - _md5_HH(d, a, b, c, in[8], _md5_S32, 0x8771F681); - _md5_HH(c, d, a, b, in[11], _md5_S33, 0x6D9D6122); - _md5_HH(b, c, d, a, in[14], _md5_S34, 0xFDE5380C); - _md5_HH(a, b, c, d, in[1], _md5_S31, 0xA4BEEA44); - _md5_HH(d, a, b, c, in[4], _md5_S32, 0x4BDECFA9); - _md5_HH(c, d, a, b, in[7], _md5_S33, 0xF6BB4B60); - _md5_HH(b, c, d, a, in[10], _md5_S34, 0xBEBFBC70); - _md5_HH(a, b, c, d, in[13], _md5_S31, 0x289B7EC6); - _md5_HH(d, a, b, c, in[0], _md5_S32, 0xEAA127FA); - _md5_HH(c, d, a, b, in[3], _md5_S33, 0xD4EF3085); - _md5_HH(b, c, d, a, in[6], _md5_S34, 0x04881D05); - _md5_HH(a, b, c, d, in[9], _md5_S31, 0xD9D4D039); - _md5_HH(d, a, b, c, in[12], _md5_S32, 0xE6DB99E5); - _md5_HH(c, d, a, b, in[15], _md5_S33, 0x1FA27CF8); - _md5_HH(b, c, d, a, in[2], _md5_S34, 0xC4AC5665); - - // - _md5_II(a, b, c, d, in[0], _md5_S41, 0xF4292244); - _md5_II(d, a, b, c, in[7], _md5_S42, 0x432AFF97); - _md5_II(c, d, a, b, in[14], _md5_S43, 0xAB9423A7); - _md5_II(b, c, d, a, in[5], _md5_S44, 0xFC93A039); - _md5_II(a, b, c, d, in[12], _md5_S41, 0x655B59C3); - _md5_II(d, a, b, c, in[3], _md5_S42, 0x8F0CCC92); - _md5_II(c, d, a, b, in[10], _md5_S43, 0xFFEFF47D); - _md5_II(b, c, d, a, in[1], _md5_S44, 0x85845DD1); - _md5_II(a, b, c, d, in[8], _md5_S41, 0x6FA87E4F); - _md5_II(d, a, b, c, in[15], _md5_S42, 0xFE2CE6E0); - _md5_II(c, d, a, b, in[6], _md5_S43, 0xA3014314); - _md5_II(b, c, d, a, in[13], _md5_S44, 0x4E0811A1); - _md5_II(a, b, c, d, in[4], _md5_S41, 0xF7537E82); - _md5_II(d, a, b, c, in[11], _md5_S42, 0xBD3AF235); - _md5_II(c, d, a, b, in[2], _md5_S43, 0x2AD7D2BB); - _md5_II(b, c, d, a, in[9], _md5_S44, 0xEB86D391); - - // - buf[0] += a; - buf[1] += b; - buf[2] += c; - buf[3] += d; - } -}; diff --git a/Documents/Pack/V1.0/Source/Classes/x-saherelm.xrange.class.mq5 b/Documents/Pack/V1.0/Source/Classes/x-saherelm.xrange.class.mq5 deleted file mode 100644 index 0fedb424..00000000 --- a/Documents/Pack/V1.0/Source/Classes/x-saherelm.xrange.class.mq5 +++ /dev/null @@ -1,54 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Class Library -// ---------------------------------------------- -// Name: XSCRange -// Description: provides all Range requirements ... -// -// -// Maintainer: -// ------------ -// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) -// -////////////////////////////////////////////////////// -// -// Global Properties ... -#property library -#property copyright "Copyright 2023, SaherElm IT Center" -#property link "https://www.saherelm.ir" -#property version "1.00" -#property strict - -// -// Imports ... -#include "../Classes/x-saherelm.base.class.mq5" -#include "../Libraries/x-saherelm.draw.lib.mq5" - -// -// Definitions ... - -// -enum ENUM_XSCRANGE_CALCULATION_MODE { - // - XSCRANGE_CALCULATE_MANUALLY = 0, - XSCRANGE_CALCULATE_DAILY = 1, - XSCRANGE_CALCULATE_HALFDAY = 2, - XSCRANGE_CALCULATE_4H = 3, -}; - -// -struct XSCRangeInput -{ - // - // Props ... - - // - datetime startTime; // Range Start Time - datetime endTime; // Range End Time - - // - int lifetime; // Range Live Time (Secconds) - - // - -}; \ No newline at end of file diff --git a/Documents/Pack/V1.0/Source/Classes/x-saherelm.xsccf.class.mq5 b/Documents/Pack/V1.0/Source/Classes/x-saherelm.xsccf.class.mq5 deleted file mode 100644 index 2e5d55c6..00000000 --- a/Documents/Pack/V1.0/Source/Classes/x-saherelm.xsccf.class.mq5 +++ /dev/null @@ -1,736 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Class Library -// ---------------------------------------------- -// Name: XSCRange -// Description: provides all Range requirements ... -// -// -// Maintainer: -// ------------ -// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) -// -////////////////////////////////////////////////////// -// -// Global Properties ... -#property library -#property copyright "Copyright 2023, SaherElm IT Center" -#property link "https://www.saherelm.ir" -#property version "1.00" -#property strict - -// -// Imports ... -#include "../Classes/x-saherelm.base.class.mq5" -#include "../Libraries/x-saherelm.draw.lib.mq5" - -// -// Definitions ... - -// -struct XSCCFInput -{ - // - // Props ... - - // - int length; // Minimum of Same Bars - - // - color clrUpper; // Upper Color ... - color clrLower; // Lower Color ... - - // - // Constructor ... - void XSCCFInput() - { - Clean(); - } - - // - // Tools ... - - // - // Cleanup ... - void Clean() - { - // - length = 0; - - // - clrUpper = CLR_NONE; - clrLower = CLR_NONE; - } - - // - // Defualt Configs ... - void Default() - { - // - length = 4; - - // - clrLower = clrAqua; - clrUpper = clrMagenta; - } - - // - // Validate ... - bool IsValid() - { - // - bool result = false; - - // - result = - // - length >= 2 - // - ; - - // - return result; - } -}; - -// -// Class ... - -class XSCCF : public XSCBase -{ - // - // Public ... -public: - // - // Props ... - - // - // Constructor ... - void XSCCF( - string symbol, - ENUM_TIMEFRAMES period // - ) : XSCBase() - { - // - mSymbol = symbol; - mPeriod = period; - } - - // - // Deconstructor ... - void ~XSCCF() {} - - // - // Initialize ... - bool Init(XSCCFInput &inputs) - { - // - bool result = false; - - // - result = inputs.IsValid(); - if (!result) - { - return result; - } - - // - mInputs = inputs; - - // - // Find Bullish Bar ... - result = FindBullishBar(0); - if (!result) - { - return result; - } - - // - // Find Bearish Bar ... - result = FindBearishBar(0); - if (!result) - { - return result; - } - - // - return result; - } - - // - // Getter(s) / Setter(s) ... - - // - string GetSymbol() - { - return mSymbol; - } - - // - ENUM_TIMEFRAMES GetPeriod() - { - return mPeriod; - } - - // - XSCCFInput GetInputs() - { - return mInputs; - } - - // - bool SetInputs(XSCCFInput &inputs) - { - return Init(inputs); - } - - // - XOHCL GetBullishBar() - { - return bullishBar; - } - - // - XOHCL GetBearishBar() - { - return bearishBar; - } - - // - // Overrides ... - string GetTag() override - { - return "XCF"; - } - - // - // Tools ... - - // - // Validate ... - bool IsValid() - { - // - bool result = false; - - // - result = - // - bullishBar.IsValid() && - bearishBar.IsValid() - // - ; - - // - return result; - } - - // - // Retrieve Title Prefix ... - string GetIdentifier() - { - // - string result = NULL; - - // - if (!IsValid()) - { - return result; - } - - // - result = GetTag() + "_" + - mSymbol + "_" + - ToString(mPeriod) + "_" + - ToFormatString(bullishBar.time) + "_"; - - // - return result; - } - - // - // Remove Draws ... - bool Remove( - long chartId = 0, - int subWindow = 0 // - ) - { - // - bool result = false; - - // - result = IsValid(); - if (!result) - { - return result; - } - - // - string prefix = GetIdentifier(); - result = IsSpecifiedValid(prefix); - if (!result) - { - return result; - } - - // - RemoveDraws( - prefix, - chartId, - subWindow // - ); - - // - return result; - } - - // - bool Draw( - long chartId = 0, - string prefix = NULL, - int subWindow = 0, - string upperPrefix = "Upper", - string lowerPrefix = "Lower" // - ) - { - // - bool result = false; - - // - result = IsValid(); - if (!result) - { - return result; - } - - // - result = DrawBullishBar( - chartId, - prefix, - subWindow, - upperPrefix, - lowerPrefix // - ); - if (!result) - { - return result; - } - - // - result = DrawBearishBar( - chartId, - prefix, - subWindow, - upperPrefix, - lowerPrefix // - ); - if (!result) - { - return result; - } - - // - return result; - } - - // - // Protected ... -protected: - // - // Tools ... - - // - bool FindBullishBar( - int barIndex // - ) - { - // - bool result = false; - - // - int next = barIndex + 1; - - // - int totalBars = iBars( - mSymbol, - mPeriod // - ); - result = barIndex >= 0 && barIndex + 1 + mInputs.length < totalBars; - if (!result) - { - return result; - } - - // - bool isNextValid = next >= 0 && next + 1 + mInputs.length < totalBars; - - // - int bullBarIndex = barIndex + 1; - int start = bullBarIndex + 1; - int end = start + mInputs.length; - - // - XOHCL startBar; - result = startBar.Init( - mSymbol, - mPeriod, - bullBarIndex // - ); - if (!result) - { - return result; - } - - // - result = startBar.IsBullish(); - if (!result) - { - if (isNextValid) - { - return FindBullishBar(next); - } - else - { - return result; - } - } - - // - // Loop Back to Find Bearish Bars ... - for (int i = start; i < end; i++) - { - // - XOHCL iBar; - result = iBar.Init( - mSymbol, - mPeriod, - i // - ); - if (!result || !iBar.IsBearish()) - { - // - if (isNextValid) - { - return FindBullishBar(next); - } - else - { - return result; - } - - // - break; - } - } - - // - if (result) - { - bullishBar = startBar; - } - - // - return result; - } - - // - bool FindBearishBar( - int barIndex // - ) - { - // - bool result = false; - - // - int next = barIndex + 1; - - // - int totalBars = iBars( - mSymbol, - mPeriod // - ); - result = barIndex >= 0 && barIndex + 1 + mInputs.length < totalBars; - if (!result) - { - return result; - } - - // - bool isNextValid = next >= 0 && next + 1 + mInputs.length < totalBars; - - // - int bearBarIndex = barIndex + 1; - int start = bearBarIndex + 1; - int end = start + mInputs.length; - - // - XOHCL startBar; - result = startBar.Init( - mSymbol, - mPeriod, - bearBarIndex // - ); - if (!result) - { - return result; - } - - // - result = startBar.IsBearish(); - if (!result) - { - if (isNextValid) - { - return FindBearishBar(next); - } - else - { - return result; - } - } - - // - // Loop Back to Find Bearish Bars ... - for (int i = start; i < end; i++) - { - // - XOHCL iBar; - result = iBar.Init( - mSymbol, - mPeriod, - i // - ); - if (!result || !iBar.IsBullish()) - { - // - if (isNextValid) - { - return FindBearishBar(next); - } - else - { - return result; - } - - // - break; - } - } - - // - if (result) - { - bearishBar = startBar; - } - - // - return result; - } - - // - bool DrawBullishBar( - long chartId = 0, - string prefix = NULL, - int subWindow = 0, - string upperPrefix = "Upper", - string lowerPrefix = "Lower" // - ) - { - // - bool result = false; - - // - result = bullishBar.IsValid(); - if (!result) - { - return result; - } - - // - if (!IsSpecifiedValid(upperPrefix)) - { - upperPrefix = "High"; - } - - // - if (!IsSpecifiedValid(lowerPrefix)) - { - lowerPrefix = "Low"; - } - - // - datetime cTime = TimeCurrent(); - - // - string identifier = GetIdentifier(); - - // - // High Line ... - string bullishHighLineName = - (IsSpecifiedValid(prefix) - ? prefix + "_" - : "") + - identifier + "_" + - "BULL_" + - upperPrefix; - - // - result = DrawTrendLine( - chartId, - bullishHighLineName, - subWindow, - bullishBar.time, - bullishBar.high, - cTime, - bullishBar.high, - mInputs.clrUpper, - STYLE_SOLID, - 2, - false, - false, - true // Ray Right ... - ); - - // - // Low Line ... - string bullishLowLineName = - (IsSpecifiedValid(prefix) - ? prefix + "_" - : "") + - identifier + "_" + - "BULL_" + - lowerPrefix; - - // - result = DrawTrendLine( - chartId, - bullishLowLineName, - subWindow, - bullishBar.time, - bullishBar.low, - cTime, - bullishBar.low, - mInputs.clrLower, - STYLE_SOLID, - 2, - false, - false, - true // Ray Right ... - ); - - // - return result; - } - - // - bool DrawBearishBar( - long chartId = 0, - string prefix = NULL, - int subWindow = 0, - string upperPrefix = "Upper", - string lowerPrefix = "Lower" // - ) - { - // - bool result = false; - - // - result = bearishBar.IsValid(); - if (!result) - { - return result; - } - - // - if (!IsSpecifiedValid(upperPrefix)) - { - upperPrefix = "High"; - } - - // - if (!IsSpecifiedValid(lowerPrefix)) - { - lowerPrefix = "Low"; - } - - // - datetime cTime = TimeCurrent(); - - // - string identifier = GetIdentifier(); - - // - // High Line ... - string bearishHighLineName = - (IsSpecifiedValid(prefix) - ? prefix + "_" - : "") + - identifier + "_" + - "BEAR_" + - upperPrefix; - - // - result = DrawTrendLine( - chartId, - bearishHighLineName, - subWindow, - bearishBar.time, - bearishBar.high, - cTime, - bearishBar.high, - mInputs.clrUpper, - STYLE_SOLID, - 2, - false, - false, - true // Ray Right ... - ); - - // - // Low Line ... - string bearishLowLineName = - (IsSpecifiedValid(prefix) - ? prefix + "_" - : "") + - identifier + "_" + - "BEAR_" + - lowerPrefix; - - // - result = DrawTrendLine( - chartId, - bearishLowLineName, - subWindow, - bearishBar.time, - bearishBar.low, - cTime, - bearishBar.low, - mInputs.clrLower, - STYLE_SOLID, - 2, - false, - false, - true // Ray Right ... - ); - - // - return result; - } - - // - // Private ... -private: - // - // Props ... - string mSymbol; // Trading Symbol ... - ENUM_TIMEFRAMES mPeriod; // Trading Period ... - - // - XOHCL bearishBar; // Bearish Order Block Bar - XOHCL bullishBar; // Bullish Order Block Bar - - // - XSCCFInput mInputs; // Configs ... -}; - -// \ No newline at end of file diff --git a/Documents/Pack/V1.0/Source/Classes/x-saherelm.xscsupres.class.mq5 b/Documents/Pack/V1.0/Source/Classes/x-saherelm.xscsupres.class.mq5 deleted file mode 100644 index e5dda43f..00000000 --- a/Documents/Pack/V1.0/Source/Classes/x-saherelm.xscsupres.class.mq5 +++ /dev/null @@ -1,330 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Class Library -// ---------------------------------------------- -// Name: XSCSupRes -// Description: provides all Support and Resistances requirements ... -// -// -// Maintainer: -// ------------ -// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) -// -////////////////////////////////////////////////////// -// -// Global Properties ... -#property library -#property copyright "Copyright 2023, SaherElm IT Center" -#property link "https://www.saherelm.ir" -#property version "1.00" -#property strict - -// -// Imports ... -#include "../Classes/x-saherelm.base.class.mq5" -#include "../Helpers/x-saherelm.xpv.helper.mq5" -#include "../Libraries/x-saherelm.draw.lib.mq5" - -// -// Definitions ... -struct XSCSupResInput -{ - // - // Props ... - - // - int numberOfSupports; // Number of Required Supports - int numberOfResistances; // Number of Required Resistances - - // - int pivotsVerifications; // Pivots Verifications - - // - double distance; // Distance between Pivots - - // - double price; // Price for Support and Resistance Finding - - // - color clrSupport; - color clrResistance; - - // - // Constructor ... - void XSCSupResInput() - { - Clean(); - } - - // - // Tools ... - - // - // Cleanup ... - void Clean() - { - // - numberOfSupports = 0; - numberOfResistances = 0; - - // - price = 0; - distance = 0; - pivotsVerifications = 0; - - // - clrSupport = CLR_NONE; - clrResistance = CLR_NONE; - } - - // - // Defualt Configs ... - void Default() - { - // - numberOfSupports = 5; - numberOfResistances = 5; - - // - price = 0; - distance = 10; - pivotsVerifications = 35; - - // - clrSupport = clrAqua; - clrResistance = clrMagenta; - } - - // - // Validate ... - bool IsValid() - { - // - bool result = false; - - // - result = - // - price > 0 && - distance >= 0 && - numberOfSupports > 0 && - numberOfResistances > 0 && - pivotsVerifications > 2 - // - ; - - // - return result; - } -}; - -// -// Class ... - -// -class XSCSupRes : public XSCBase -{ - // - // Public ... -public: - // - // Props ... - - // - // Constructor ... - void XSCSupRes( - string symbol, - ENUM_TIMEFRAMES period // - ) : XSCBase() - { - // - mSymbol = symbol; - mPeriod = period; - } - - // - // Deconstructor ... - void ~XSCSupRes() {} - - // - // Initializer ... - bool Init(XSCSupResInput &inputs) - { - // - bool result = false; - - // - result = inputs.IsValid(); - if (!result) - { - return result; - } - - // - mInputs = inputs; - - // - // Find Pivots ... - result = FindPivots(); - if (!result) - { - return result; - } - - // - return result; - } - - // - // Getter(s) / Setter(s) ... - - // - string GetSymbol() - { - return mSymbol; - } - - // - ENUM_TIMEFRAMES GetPeriod() - { - return mPeriod; - } - - // - XSCSupResInput GetInputs() - { - return mInputs; - } - - // - bool SetInputs(XSCSupResInput &inputs) - { - return Init(inputs); - } - - // - // Overrides ... - - // - string GetTag() override - { - return "XSupRes"; - } - - // - // Tools ... - - // - // Validate ... - bool IsValid() - { - // - bool result = false; - - // - result = - // - false - // - ; - - // - return result; - } - - // - // Retrieve Title Prefix ... - string GetIdentifier() - { - // - string result = NULL; - - // - if (!IsValid()) - { - return result; - } - - // - result = GetTag() + "_" + - mSymbol + "_" + - ToString(mPeriod) + "_"; - - // - return result; - } - - // - // Protected ... -protected: - // - // Tools ... - - // - // Private ... -private: - // - // Props ... - - // - string mSymbol; // Trading Symbol ... - ENUM_TIMEFRAMES mPeriod; // Trading Period ... - - // - XSCSupResInput mInputs; // Configs ... - - // - double mSupports[]; - double mResistances[]; - - // - // Tools ... - - // - bool FindPivots(int barIndex = 0) - { - // - bool result = false; - - // - int totalBars = iBars( - mSymbol, - mPeriod // - ); - - // - result = barIndex >= 0 && barIndex < totalBars - mInputs.pivotsVerifications; - if (!result) { - return result; - } - - // - int next = barIndex + 1; - bool canNext = next >= 0 && next < totalBars - mInputs.pivotsVerifications; - - // - XSCXPVHelper helper = new XSCXPVHelper(); - XPVInputs pvInputs; - pvInputs.Default(); - result = helper.Init( - mSymbol, - mPeriod, - pvInputs // - ); - if (!result) - { - return result; - } - - // - // TODO: Complete this ... - - // - // Check States ... - - // - return result; - } -}; - -// \ No newline at end of file diff --git a/Documents/Pack/V1.0/Source/Classes/x-saherelm.xsctrend.class.mq5 b/Documents/Pack/V1.0/Source/Classes/x-saherelm.xsctrend.class.mq5 deleted file mode 100644 index 9b2e096e..00000000 --- a/Documents/Pack/V1.0/Source/Classes/x-saherelm.xsctrend.class.mq5 +++ /dev/null @@ -1,746 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Class Library -// ---------------------------------------------- -// Name: XSCTrend -// Description: provides all Trend requirements ... -// -// -// Maintainer: -// ------------ -// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) -// -////////////////////////////////////////////////////// -// -// Global Properties ... -#property library -#property copyright "Copyright 2023, SaherElm IT Center" -#property link "https://www.saherelm.ir" -#property version "1.00" -#property strict - -// -// Imports ... -#include "../Classes/x-saherelm.base.class.mq5" -#include "../Libraries/x-saherelm.draw.lib.mq5" - -// -// All Required Inputs ... -struct XSCTrendInput -{ - // - int numberOfShoulders; // Number of Shoulders - - // - color clrUpper; // Upper Colors - color clrLower; // Lower Colors - color clrHighs; // Highs Colors - color clrLows; // Lows Colors - - // - // Constructor ... - void XSCTrendInput() - { - Clean(); - } - - // - // Tools ... - - // - // Cleanup ... - void Clean() - { - // - numberOfShoulders = 0; - - // - clrUpper = CLR_NONE; - clrLower = CLR_NONE; - clrHighs = CLR_NONE; - clrLows = CLR_NONE; - } - - // - // Defualt Configs ... - void Default() - { - // - numberOfShoulders = 7; - - // - clrUpper = clrRed; - clrLower = clrGreen; - - // - clrHighs = clrAqua; - clrLows = clrMagenta; - } - - // - // Validate ... - bool IsValid() - { - // - bool result = false; - - // - result = - // - numberOfShoulders >= 2 - // - ; - - // - return result; - } -}; - -// -// Class Definitions ... -class XSCTrend : public XSCBase -{ - // - // Public ... -public: - // - // Props ... - - // - // Constructor ... - void XSCTrend( - string symbol, - ENUM_TIMEFRAMES period // - ) : XSCBase() - { - // - mSymbol = symbol; - mPeriod = period; - } - - // - // Deconstructor ... - void ~XSCTrend() - { - Remove(); - } - - // - // Initialize ... - bool Init(XSCTrendInput &inputs) - { - // - bool result = false; - - // - result = inputs.IsValid(); - if (!result) - { - return result; - } - - // - mInputs = inputs; - - // - result = zBar.Init( - mSymbol, - mPeriod, - 0 // - ); - - // - int firstSwingLowIndex = FindSwing( - zBar.symbol, - zBar.period, - X_SWING_LOW, - mInputs.numberOfShoulders, - zBar.Index() + 1 // - ); - result = firstSwingLowBar.Init( - zBar.symbol, - zBar.period, - firstSwingLowIndex // - ); - if (!result) - { - return result; - } - - // - int secondSwingLowIndex = FindSwing( - zBar.symbol, - zBar.period, - X_SWING_LOW, - mInputs.numberOfShoulders, - firstSwingLowIndex + 1 // - ); - - // - result = secondSwingLowBar.Init( - zBar.symbol, - zBar.period, - secondSwingLowIndex // - ); - if (!result) - { - return result; - } - - // - int firstSwingHighIndex = FindSwing( - zBar.symbol, - zBar.period, - X_SWING_HIGH, - mInputs.numberOfShoulders, - zBar.Index() + 1 // - ); - result = firstSwingHighBar.Init( - zBar.symbol, - zBar.period, - firstSwingHighIndex // - ); - if (!result) - { - return result; - } - - // - int secondSwingHighIndex = FindSwing( - zBar.symbol, - zBar.period, - X_SWING_HIGH, - mInputs.numberOfShoulders, - firstSwingHighIndex + 1 // - ); - result = secondSwingHighBar.Init( - zBar.symbol, - zBar.period, - secondSwingHighIndex // - ); - if (!result) - { - return result; - } - - // - return result; - } - - // - // Getter(s) / Setter(s) ... - - // - string GetSymbol() - { - return mSymbol; - } - - // - ENUM_TIMEFRAMES GetPeriod() - { - return mPeriod; - } - - // - XSCTrendInput GetInputs() - { - return mInputs; - } - - // - bool SetInputs(XSCTrendInput &inputs) - { - return Init(inputs); - } - - // - XOHCL GetBar() - { - return zBar; - } - - // - XOHCL GetFirstSwingLowBar() - { - return firstSwingLowBar; - } - - // - XOHCL GetSecondSwingLowBar() - { - return secondSwingLowBar; - } - - // - XOHCL GetFirstSwingHighBar() - { - return firstSwingHighBar; - } - - // - XOHCL GetSecondSwingHighBar() - { - return secondSwingHighBar; - } - - // - // Overrides ... - - // - string GetTag() override - { - return "XTREND"; - } - - // - // Tools ... - - // - // Validate ... - bool IsValid() - { - // - bool result = false; - - // - result = - // - zBar.IsValid() && - firstSwingLowBar.IsValid() && - secondSwingLowBar.IsValid() && - firstSwingHighBar.IsValid() && - secondSwingHighBar.IsValid() - // - ; - - // - return result; - } - - // - // Retrieve Title Prefix ... - string GetIdentifier() - { - // - string result = NULL; - - // - if (!IsValid()) - { - return result; - } - - // - result = GetTag() + "_" + - mSymbol + "_" + - ToString(mPeriod) + "_" + - ToFormatString(zBar.time); - - // - return result; - } - - // - // Retrieve Chart Line Values ... - - // - // Get Lows Line Price at Specific Time ... - double GetLows(datetime time = NULL) - { - // - double result = 0; - - // - result = GetObjectPrice( - lowsName, - time // - ); - - // - return result; - } - - // - // Get Highs Line Price at Specific Time ... - double GetHighs(datetime time = NULL) - { - // - double result = 0; - - // - result = GetObjectPrice( - highsName, - time // - ); - - // - return result; - } - - // - // Get Support Line Price at Specific Time ... - double GetSupport(datetime time = NULL) - { - // - double result = 0; - - // - result = GetObjectPrice( - supportName, - time // - ); - - // - return result; - } - - // - // Get Resistance Line Price at Specific Time ... - double GetResistance(datetime time = NULL) - { - // - double result = 0; - - // - result = GetObjectPrice( - resistanceName, - time // - ); - - // - return result; - } - - // - // Remove Draws ... - bool Remove( - long chartId = 0, - int subWindow = 0 // - ) - { - // - bool result = false; - - // - result = IsValid(); - if (!result) - { - return result; - } - - // - string prefix = GetIdentifier(); - result = IsSpecifiedValid(prefix); - if (!result) - { - return result; - } - - // - RemoveDraws( - prefix, - chartId, - subWindow // - ); - - // - return result; - } - - // - // Draw Trend Object on Chart ... - bool Draw( - long chartId = 0, - string prefix = NULL, - int subWindow = 0, - string upperPrefix = "Upper", - string lowerPrefix = "Lower", - string highsPrefix = "Highs", - string lowsPrefix = "Lows" // - ) - { - // - bool result = false; - - // - result = IsValid(); - if (!result) - { - return result; - } - - // - // Normalize Prefixes ... - - // - if (!IsSpecifiedValid(upperPrefix)) - { - upperPrefix = "Upper"; - } - - // - if (!IsSpecifiedValid(lowerPrefix)) - { - lowerPrefix = "Lower"; - } - - // - if (!IsSpecifiedValid(highsPrefix)) - { - highsPrefix = "Highs"; - } - - // - if (!IsSpecifiedValid(lowsPrefix)) - { - lowsPrefix = "Lows"; - } - - // - string identifier = GetIdentifier(); - result = IsSpecifiedValid(identifier); - if (!result) - { - return result; - } - - // - double support = secondSwingLowBar.low; - datetime supportTime = - secondSwingLowBar.time > secondSwingHighBar.time - ? secondSwingHighBar.time - : secondSwingLowBar.time; - supportName = - // - identifier + - (IsSpecifiedValid(prefix) - ? "_" + prefix + "_" - : "") + - "_" + lowerPrefix + "_" + - "" - // - ; - - // - double resistance = secondSwingHighBar.high; - datetime resistanceTime = - secondSwingLowBar.time > secondSwingHighBar.time - ? secondSwingHighBar.time - : secondSwingLowBar.time; - resistanceName = - // - identifier + - (IsSpecifiedValid(prefix) - ? "_" + prefix + "_" - : "") + - "_" + upperPrefix + "_" + - "" - // - ; - - // - double newLow = firstSwingLowBar.low; - datetime newLowTime = firstSwingLowBar.time; - - // - double oldLow = secondSwingLowBar.low; - datetime oldLowTime = secondSwingLowBar.time; - lowsName = - // - identifier + - (IsSpecifiedValid(prefix) - ? "_" + prefix + "_" - : "") + - "_" + lowsPrefix + "_" + - "" - // - ; - - // - double newHigh = firstSwingHighBar.high; - datetime newHighTime = firstSwingHighBar.time; - - // - double oldHigh = secondSwingHighBar.high; - datetime oldHighTime = secondSwingHighBar.time; - highsName = - // - identifier + - (IsSpecifiedValid(prefix) - ? "_" + prefix + "_" - : "") + - "_" + highsPrefix + "_" + - "" - // - ; - - // - // Draw Support ... - result = DrawTrendLine( - chartId, - supportName, - subWindow, - supportTime, - support, - newLowTime, - support, - mInputs.clrLower, - STYLE_SOLID, - 2, - false, - false, - true // Ray Right ... - ); - if (!result) - { - return result; - } - - // - // Draw Resistance ... - result = DrawTrendLine( - chartId, - resistanceName, - subWindow, - resistanceTime, - resistance, - newHighTime, - resistance, - mInputs.clrUpper, - STYLE_SOLID, - 2, - false, - false, - true // Ray Right ... - ); - if (!result) - { - return result; - } - - // - // Draw Highs ... - result = DrawTrendLine( - chartId, - highsName, - subWindow, - oldHighTime, - oldHigh, - newHighTime, - newHigh, - mInputs.clrHighs, - STYLE_SOLID, - 2, - false, - false, - true // Ray Right ... - ); - if (!result) - { - return result; - } - - // - // Draw Lows ... - result = DrawTrendLine( - chartId, - lowsName, - subWindow, - oldLowTime, - oldLow, - newLowTime, - newLow, - mInputs.clrLows, - STYLE_SOLID, - 2, - false, - false, - true // Ray Right ... - ); - if (!result) - { - return result; - } - - // - return result; - } - - // - // Protected ... -protected: - // - // Tools ... - - // - double GetObjectPrice( - string objName, - datetime objTime, - long chartId = 0, - int subWindow = 0 // - ) - { - // - double result = 0; - - // - if (!IsValid()) - { - return result; - } - - // - if (!IsSpecifiedValid(objName)) - { - return result; - } - - // - objTime = NormalizeTime(objTime); - - // - string objectName = FindObjectName( - objName, - chartId, - subWindow // - ); - - // - result = ObjectGetValueByTime( - chartId, - objectName, - objTime // - ); - - // - return result; - } - - // - // Private ... -private: - // - // Props ... - string mSymbol; // Trading Symbol ... - ENUM_TIMEFRAMES mPeriod; // Trading Period ... - - // - XSCTrendInput mInputs; // Configs ... - - // - XOHCL zBar; - XOHCL firstSwingLowBar; - XOHCL secondSwingLowBar; - XOHCL firstSwingHighBar; - XOHCL secondSwingHighBar; - - // - // Object Names ... - string lowsName; - string highsName; - string supportName; - string resistanceName; -}; - -// \ No newline at end of file diff --git a/Documents/Pack/V1.0/Source/Classes/x-saherelm.xsczone.class.mq5 b/Documents/Pack/V1.0/Source/Classes/x-saherelm.xsczone.class.mq5 deleted file mode 100644 index a6421c48..00000000 --- a/Documents/Pack/V1.0/Source/Classes/x-saherelm.xsczone.class.mq5 +++ /dev/null @@ -1,805 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Class Library -// ---------------------------------------------- -// Name: XSCZone -// Description: provides all Zone 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 -#include -#include "../Classes/x-saherelm.base.class.mq5" -#include "../Libraries/x-saherelm.draw.lib.mq5" -#include - -// -// Definitions ... -#define defZoneBGColor CLR_NONE // clrLightGray -#define defZoneLBLColor clrWhite - -// -// All Required Inputs ... -struct XSCZonesInput -{ - // - int length; // Calculation Length - int numberOfZones; // Number of Zones - - // - double levels[]; // Levels Percentage - color colors[]; // level Colors - - // - // Constructor ... - void XSCZonesInput() - { - Clean(); - } - - // - // Tools ... - - // - // Cleanup ... - void Clean() - { - // - length = 0; - numberOfZones = 0; - - // - Clean(levels); - Clean(colors); - } - - // - // Validate ... - bool IsValid() - { - // - bool result = false; - - // - result = - // - length >= 5 && - numberOfZones >= 2 - // - ; - - // - return result; - } - - // - // Add Specified Level/Color ... - void AddLevelColor( - double level, - color clr // - ) - { - // - Add( - level, - levels); - - // - Add( - clr, - colors // - ); - } - - // - // Retrieve Sort Indexed Levels Color ... - void RetrieveSortedLevels( - double &_levels[], - color &_colors[] // - ) - { - // - Clean(_levels); - Clean(_colors); - - // - int levelsCount = ArraySize(levels); - int colorsCount = ArraySize(colors); - - // - bool hasChild = IsValidSize(levelsCount) && - IsValidSize(colorsCount); - if (!hasChild) - { - return; - } - - // - // Create Temp Levels ... - double tmpLevels[]; - Copy( - levels, - tmpLevels // - ); - ArraySort(tmpLevels); - ArrayReverse(tmpLevels); - - // - // Size of Looping ... - int minSize = MathMin(levelsCount, colorsCount); - - // - for (int i = 0; i < minSize; i++) - { - // - double iLevel = tmpLevels[i]; - - // - int iLevelIDX = FindIndex( - iLevel, - levels // - ); - if (!IsValidIndex(iLevelIDX)) - { - continue; - } - - // - Add( - levels[iLevelIDX], - _levels // - ); - - // - Add( - colors[iLevelIDX], - _colors // - ); - } - } -}; - -// -// Class ... - -// -// Specific Zone ... -class XSCZone : public CObject -{ - // - // Public ... -public: - // - // Props ... - double high; - double low; - int ticks; - double percent; - - // - // Compare Two Zone With Each Other ... - virtual int Compare( - const CObject *node, - const int mode = 0 // - ) const - { - // - const XSCZone *other = (XSCZone *)node; - - // - return other.ticks - ticks; - } - - // - // Create Object ... - - // - // Protected ... -protected: - // - // Private ... -private: -}; - -// -// Zones ... - -// -class XSCZones : public XSCBase -{ - // - // Public ... -public: - // - // Constructor(s) ... - void XSCZones( - string symbol, - ENUM_TIMEFRAMES period // - ) : XSCBase() - { - // - this.mSymbol = symbol; - this.mPeriod = period; - } - - // - void ~XSCZones() - { - // - mZones.Clear(); - mChartObjects.Clear(); - } - - // - // Initialize Zones by Providing required - // Input Variables ... - bool Init( - XSCZonesInput &inputs // Inputs ... - ) - { - // - bool result = false; - - // - // Validate Inputs ... - result = inputs.IsValid(); - if (!result) - { - return result; - } - - // - // Set Inputs ... - mInputs = inputs; - - // - // Do Calculatins ... - Calculate(); - - // - return result; - } - - // - XSCZonesInput GetInputs() - { - return mInputs; - } - - // - bool SetInputs(XSCZonesInput &inputs) - { - return Init(inputs); - } - - // - // Overrides ... - - // - string GetTag() override - { - return "XZONE"; - } - - // - // Retrieve Title Prefix ... - string GetIdentifier() - { - // - string result = NULL; - - // - if (!IsValid()) - { - return result; - } - - // - result = GetTag() + "_" + - mSymbol + "_" + - ToString(mPeriod) + - ToFormatString(mStartTime) + "_" + - ToFormatString(mEndTime); - - // - return result; - } - - // - bool IsValid() - { - // - bool result = false; - - // - result = - // - mZones.Total() > 0 - // - ; - - // - return result; - } - - // - // Add Specified Level/Color ... - void AddLevelColor( - double level, - color clr // - ) - { - // - mInputs.AddLevelColor( - level, - clr // - ); - } - - // - void Calculate() - { - // - // Prevent Double Calculating ... - int bars = iBars( - mSymbol, - mPeriod // - ); - if (mCalculatedBars == bars) - { - return; - } - - // - mCalculatedBars = bars; - - // - // Calculate Start and End Time ... - - // - mStartTime = iTime( - mSymbol, - mPeriod, - mInputs.length + 1 // - ); - - // - mEndTime = iTime( - mSymbol, - mPeriod, - 0 // - ); - - // - // Retrieve Ticks between Times ... - Clean(mTicks); - CopyTicksRange( - mSymbol, - mTicks, - COPY_TICKS_ALL, - mStartTime * 1000, - mEndTime * 1000 // - ); - - // - // Retrieve Highs ... - Clean(mHighs); - CopyHigh( - mSymbol, - mPeriod, - mStartTime, - mEndTime, - mHighs // - ); - - // - // Find Highest Value in Range ... - int highIDX = ArrayMaximum(mHighs); - mRangeHigh = mHighs[highIDX]; - - // - // Retrieve Lows ... - Clean(mLows); - CopyLow( - mSymbol, - mPeriod, - mStartTime, - mEndTime, - mLows // - ); - - // - // Find Lowest Value in Range ... - int lowIDX = ArrayMinimum(mLows); - mRangeLow = mLows[lowIDX]; - - // - datetime mTimes[]; - CopyTime( - mSymbol, - mPeriod, - mStartTime, - mEndTime, - mTimes // - ); - mRangeHighTime = mTimes[highIDX]; - mRangeLowTime = mTimes[lowIDX]; - - // - double mRangeSize = GetRange(); - - // - // Prepare Zones Array ... - mZones.Clear(); - - // - // Create Zones ... - for (int i = 0; i < mInputs.numberOfZones; i++) - { - // - // Instance a New Zone ... - XSCZone *iZone = new XSCZone(); - - // - // Calculate Each Zones High / Low based on Range ... - double iH = mRangeHigh - mRangeSize * i / mInputs.numberOfZones; - double iL = mRangeHigh - mRangeSize * (i + 1) / mInputs.numberOfZones; - - // - // Set Zone High Low Properties ... - iZone.low = iL; - iZone.high = iH; - - // - // Add Zone to Zone Array Objects ... - mZones.Add(iZone); - } - - // - // Calculate Each Zone Ticks ... - int mTicksCount = CountTicks(); - for (int i = 0; i < mTicksCount; i++) - { - // - // Retrieve i Index Tick Object ... - MqlTick iTick = mTicks[i]; - - // - // Loop Through Zones ... - for (int j = 0; j < mZones.Total(); j++) - { - // - // Retrieve j Index Zone Object ... - XSCZone *jZone = mZones.At(j); - - // - bool isInRange = IsTickInZoneRange( - iTick, - jZone // - ); - if (isInRange) - { - // - jZone.ticks++; - break; - } - } - } - - // - // Calculating Zone Percents ... - for (int i = 0; i < mZones.Total(); i++) - { - // - XSCZone *iZone = mZones.At(i); - - // - double percent = CalculateZoneTickPercent(iZone); - iZone.percent = percent; - } - - // - mZones.Sort(); - } - - // - int CountZones() - { - return mZones.Total(); - } - - // - XSCZone *GetZone(int index) - { - return mZones.At(index); - } - - // - double CalculateZoneTickPercent( - XSCZone *zone, - int normalizationDigits = 2 // - ) - { - // - double result = 0; - - // - if (normalizationDigits < 2 || normalizationDigits > 5) - { - normalizationDigits = 2; - } - - // - int ticksCount = CountTicks(); - if (ticksCount <= 0) - { - return result; - } - - // - result = (double)zone.ticks / ticksCount * 100; - result = NormalizeDouble(result, normalizationDigits); - - // - return result; - } - - // - bool Draw( - long chartId = 0, - string prefix = "XSCZone", - int subWindow = 0, - bool redraw = false // - ) - { - // - bool result = false; - - // - if (redraw) - { - mChartObjects.Clear(); - } - - // - if (StringLen(prefix) <= 0) - { - prefix = "XSCZone"; - } - - // - int zonesCount = mZones.Total(); - result = IsValidSize(zonesCount); - if (!result) - { - return result; - } - - // - mZones.Sort(); - - // - int ticksCount = CountTicks(); - result = IsValidSize(ticksCount); - if (!result) - { - return result; - } - - // - double levels[]; - color colors[]; - mInputs.RetrieveSortedLevels( - levels, - colors // - ); - int levelsCount = ArraySize(levels); - int colorsCount = ArraySize(colors); - bool canSetLevels = IsValidSize(levelsCount) && - IsValidSize(colorsCount) && - levelsCount == colorsCount; - - // - // Loop Through Zones ... - for (int i = 0; i < zonesCount; i++) - { - // - XSCZone *iZone = mZones.At(i); - - // - // Generate Chart Object Names ... - string iRectName = prefix + ToString(i); - string iLabelName = iRectName + "_lbl"; - - // - // Creating Rectangles ... - CChartObjectRectangle *iRect = new CChartObjectRectangle(); - result = iRect.Create( - chartId, - iRectName, - subWindow, - mStartTime, - iZone.high, - mEndTime, - iZone.low // - ); - if (!result) - { - break; - } - - // - // Set Default Rectangle Color ... - // iRect.Color(defZoneBGColor); - iRect.Fill(true); - - // - // Create Label ... - CChartObjectLabel *iLabel = new CChartObjectLabel(); - result = iLabel.Create( - chartId, - iLabelName, - subWindow, - mStartTime, - iZone.high // - ); - if (!result) - { - break; - } - - // - iLabel.Color(defZoneLBLColor); - - // - iLabel.Description(ToString(iZone.percent) + "%"); - - // - // Set Levels and Colors if Provided ... - if (canSetLevels) - { - // - color iRectColor = defZoneBGColor; - for (int z = 0; z < levelsCount; z++) - { - // - double zLevel = levels[z]; - color zColor = colors[z]; - - // - if (iZone.ticks >= ticksCount * zLevel) - { - // - iRectColor = zColor; - break; - } - } - - // - iRect.Color(iRectColor); - } - - // - mChartObjects.Add(iRect); - mChartObjects.Add(iLabel); - } - - // - return result; - } - - // - bool Remove( - long chartId = 0, - string prefix = "XSCZone", - int subWindow = 0, - bool redraw = false // - ) - { - // - bool result = false; - - // - mChartObjects.Clear(); - - // - result = - // - true - // - ; - - // - return result; - } - - // - // Protected ... -protected: - // - // Props ... - - // - datetime mStartTime; - datetime mEndTime; - - // - MqlTick mTicks[]; - double mHighs[]; - double mLows[]; - double mRangeHigh; - datetime mRangeHighTime; - double mRangeLow; - datetime mRangeLowTime; - - // - CArrayObj mZones; - CArrayObj mChartObjects; - - // - // Tools ... - - // - int CountTicks() - { - return ArraySize(mTicks); - } - - // - double GetRange() - { - return mRangeHigh - mRangeLow; - } - - // - // Check a Tick is in a Zone rage or not ... - bool IsTickInZoneRange( - MqlTick &tick, // Tick For Checking - XSCZone *zone // Zone For Checking - ) - { - // - bool result = false; - - // - result = - // - tick.bid >= zone.low && - tick.bid <= zone.high - // - ; - - // - return result; - } - - // - // Private ... -private: - // - // Props ... - - // - string mSymbol; // Analyzing Symbol - ENUM_TIMEFRAMES mPeriod; // Analyzing Period - - // - XSCZonesInput mInputs; // Configurations - - // - int mCalculatedBars; // Calculated Bars ... -}; \ No newline at end of file diff --git a/Documents/Pack/V1.0/Source/Classes/x-saherelm.xtrade.class.mq5 b/Documents/Pack/V1.0/Source/Classes/x-saherelm.xtrade.class.mq5 deleted file mode 100644 index 9e5933f3..00000000 --- a/Documents/Pack/V1.0/Source/Classes/x-saherelm.xtrade.class.mq5 +++ /dev/null @@ -1,3761 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Class Library -// ---------------------------------------------- -// Name: XSCTrade -// Description: provides all Trade requirements ... -// -// -// Maintainer: -// ------------ -// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) -// -////////////////////////////////////////////////////// -// -// Global Properties ... -#property library -#property copyright "Copyright 2023, SaherElm IT Center" -#property link "https://www.saherelm.ir" -#property version "1.00" -#property strict - -// -// Imports ... -#include "../Classes/x-saherelm.base.class.mq5" -#include "../Libraries/x-saherelm.xtrade.lib.mq5" -#include "../Classes/x-saherelm.xaccount.class.mq5" - -// -// Definitions ... - -// -// Overrides ... - -// -// XCTrade Base Class ... -class XSCTradeBase : public CTrade -{ -public: - // - // Modify Specific Position, by Specific Comment ... - bool PositionModify( - const string symbol, // Symbol - const double sl, // Stop Loss - const double tp, // Take Profit - const string comment = "" // Comment For Modify - ) - { - // - // check stopped - if (IsStopped(__FUNCTION__)) - { - return (false); - } - - // - // check position existence - if (!SelectPosition(symbol)) - { - return (false); - } - - // - // clean - ClearStructures(); - - // - // setting request - m_request.action = TRADE_ACTION_SLTP; - m_request.symbol = symbol; - m_request.magic = m_magic; - m_request.sl = sl; - m_request.tp = tp; - m_request.position = PositionGetInteger(POSITION_TICKET); - - // - // Specified Comment ... - if (StringLen(comment) > 0) - { - m_request.comment = comment; - } - - // - // action and return the result - return (OrderSend(m_request, m_result)); - } - bool PositionModify( - const ulong ticket, // Position Ticket - const double sl, // Stop Loss - const double tp, // Take Profit - const string comment = "" // Comment For Modify - ) - { - // - // check stopped - if (IsStopped(__FUNCTION__)) - { - return (false); - } - - // - // check position existence - if (!PositionSelectByTicket(ticket)) - { - return (false); - } - - // - // clean - ClearStructures(); - - // - // setting request - m_request.action = TRADE_ACTION_SLTP; - m_request.position = ticket; - m_request.symbol = PositionGetString(POSITION_SYMBOL); - m_request.magic = m_magic; - m_request.sl = sl; - m_request.tp = tp; - - // - // Specified Comment ... - if (StringLen(comment) > 0) - { - m_request.comment = comment; - } - - // - // action and return the result - return (OrderSend(m_request, m_result)); - } - - // - // Close Specific Position, by Specific Comment ... - bool PositionClose( - const string symbol, // Symbol - const ulong deviation, // Deviation - const string comment = "" // Comment For Close - ) - { - // - bool partial_close = false; - int retry_count = 10; - uint retcode = TRADE_RETCODE_REJECT; - - // - // check stopped - if (IsStopped(__FUNCTION__)) - { - return (false); - } - - // - // clean - ClearStructures(); - - // - // check filling - if (!FillingCheck(symbol)) - { - return (false); - } - - // - do - { - // - // check - if (SelectPosition(symbol)) - { - // - if ((ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY) - { - // - // prepare request for close BUY position - m_request.type = ORDER_TYPE_SELL; - m_request.price = SymbolInfoDouble(symbol, SYMBOL_BID); - } - else - { - // - // prepare request for close SELL position - m_request.type = ORDER_TYPE_BUY; - m_request.price = SymbolInfoDouble(symbol, SYMBOL_ASK); - } - } - else - { - // - // position not found - m_result.retcode = retcode; - return (false); - } - - // - // setting request - m_request.action = TRADE_ACTION_DEAL; - m_request.symbol = symbol; - m_request.volume = PositionGetDouble(POSITION_VOLUME); - m_request.magic = m_magic; - m_request.deviation = (deviation == ULONG_MAX) ? m_deviation : deviation; - m_request.position = PositionGetInteger(POSITION_TICKET); - - // - // Specify Comment ... - m_request.comment = comment; - - // - // check volume - double max_volume = SymbolInfoDouble(symbol, SYMBOL_VOLUME_MAX); - if (m_request.volume > max_volume) - { - // - m_request.volume = max_volume; - partial_close = true; - } - else - { - partial_close = false; - } - - // - // hedging? just send order - if (IsHedging()) - { - return (OrderSend(m_request, m_result)); - } - - // - // order send - if (!OrderSend(m_request, m_result)) - { - // - if (--retry_count != 0) - { - continue; - } - - // - if (retcode == TRADE_RETCODE_DONE_PARTIAL) - { - m_result.retcode = retcode; - } - - // - return (false); - } - - // - //--- WARNING. If position volume exceeds the maximum volume allowed for deal, - //--- and when the asynchronous trade mode is on, for safety reasons, position is closed not completely, - //--- but partially. It is decreased by the maximum volume allowed for deal. - if (m_async_mode) - { - break; - } - - // - retcode = TRADE_RETCODE_DONE_PARTIAL; - if (partial_close) - { - Sleep(1000); - } - } while (partial_close); - - // - // succeed - return (true); - } - bool PositionClose( - const ulong ticket, // Position Ticket - const ulong deviation, // Deviation - const string comment = "" // Comment For Close - ) - { - // - // check stopped - if (IsStopped(__FUNCTION__)) - { - return (false); - } - - // - // check position existence - if (!PositionSelectByTicket(ticket)) - { - return (false); - } - - // - string symbol = PositionGetString(POSITION_SYMBOL); - - // - // clean - ClearStructures(); - - // - // check filling - if (!FillingCheck(symbol)) - { - return (false); - } - - // - // check - if ((ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY) - { - // - // prepare request for close BUY position - m_request.type = ORDER_TYPE_SELL; - m_request.price = SymbolInfoDouble(symbol, SYMBOL_BID); - } - else - { - // - // prepare request for close SELL position - m_request.type = ORDER_TYPE_BUY; - m_request.price = SymbolInfoDouble(symbol, SYMBOL_ASK); - } - - // - // setting request - m_request.action = TRADE_ACTION_DEAL; - m_request.position = ticket; - m_request.symbol = symbol; - m_request.volume = PositionGetDouble(POSITION_VOLUME); - m_request.magic = m_magic; - m_request.deviation = (deviation == ULONG_MAX) ? m_deviation : deviation; - - // - // Specify Comment ... - m_request.comment = comment; - - // - // close position - return (OrderSend(m_request, m_result)); - } - - // - // Partial Close Specific Position, by Specific Comment ... - bool PositionClosePartial( - const string symbol, // Symbol - const double volume, // Partial Closing Volume - const ulong deviation, // Deviation - const string comment = "" // Comment For Close - ) - { - // - uint retcode = TRADE_RETCODE_REJECT; - - // - // check stopped - if (IsStopped(__FUNCTION__)) - { - return (false); - } - - // - // for hedging mode only - if (!IsHedging()) - { - return (false); - } - - // - // clean - ClearStructures(); - - // - // check filling - if (!FillingCheck(symbol)) - { - return (false); - } - - // - // check - if (SelectPosition(symbol)) - { - // - if ((ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY) - { - // - // prepare request for close BUY position - m_request.type = ORDER_TYPE_SELL; - m_request.price = SymbolInfoDouble(symbol, SYMBOL_BID); - } - else - { - // - // prepare request for close SELL position - m_request.type = ORDER_TYPE_BUY; - m_request.price = SymbolInfoDouble(symbol, SYMBOL_ASK); - } - } - else - { - // - // position not found - m_result.retcode = retcode; - return (false); - } - - // - // check volume - double position_volume = PositionGetDouble(POSITION_VOLUME); - if (position_volume > volume) - { - position_volume = volume; - } - - // - // setting request - m_request.action = TRADE_ACTION_DEAL; - m_request.symbol = symbol; - m_request.volume = position_volume; - m_request.magic = m_magic; - m_request.deviation = (deviation == ULONG_MAX) ? m_deviation : deviation; - m_request.position = PositionGetInteger(POSITION_TICKET); - - // - // Specifieng Comment ... - m_request.comment = comment; - - // - // hedging? just send order - return (OrderSend(m_request, m_result)); - } - bool PositionClosePartial( - const ulong ticket, // Position Ticket - const double volume, // Partial Closing Volume - const ulong deviation, // Deviation - const string comment = "" // Comment For Close - ) - { - // - // check stopped - if (IsStopped(__FUNCTION__)) - { - return (false); - } - - // - // for hedging mode only - if (!IsHedging()) - { - return (false); - } - - // - // check position existence - if (!PositionSelectByTicket(ticket)) - { - return (false); - } - - // - string symbol = PositionGetString(POSITION_SYMBOL); - - // - // clean - ClearStructures(); - - // - // check filling - if (!FillingCheck(symbol)) - { - return (false); - } - - // - // check - if ((ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY) - { - // - // prepare request for close BUY position - m_request.type = ORDER_TYPE_SELL; - m_request.price = SymbolInfoDouble(symbol, SYMBOL_BID); - } - else - { - // - // prepare request for close SELL position - m_request.type = ORDER_TYPE_BUY; - m_request.price = SymbolInfoDouble(symbol, SYMBOL_ASK); - } - - // - // check volume - double position_volume = PositionGetDouble(POSITION_VOLUME); - if (position_volume > volume) - { - position_volume = volume; - } - - // - // setting request - m_request.action = TRADE_ACTION_DEAL; - m_request.position = ticket; - m_request.symbol = symbol; - m_request.volume = position_volume; - m_request.magic = m_magic; - m_request.deviation = (deviation == ULONG_MAX) ? m_deviation : deviation; - - // - // Specifieng Comment ... - m_request.comment = comment; - - // - // close position - return (OrderSend(m_request, m_result)); - } -}; - -// -// Implementation ... - -// -// a Class For Manage Trades and Handle Trading Actions ... -class XSCTrade : public XSCBase -{ - // - // Public ... -public: - // - // Props ... - XSCAccount *mAccount; // Account Info Provider - - // - // Constructors ... - void XSCTrade( - int slippage, // Specify Slippage - ulong magicNumber, // Specify Magic Number - double maxAllowedSpread = 0, // Max Allowed Spred for Opening Trades - int maxAllowedPositions = 0, // Max Allowed Positions - double maxAllowedDrawdownFactor = 0 // Max Allowed Drawdown Factor - ) - { - // - // Setting Props ... - mSlippage = slippage; - mMagicNumber = magicNumber; - - // - mMaxAllowedSpread = maxAllowedSpread; - mMaxAllowedPositions = maxAllowedPositions; - mMaxAllowedDrawdownFactor = maxAllowedDrawdownFactor; - - // - mAccount = new XSCAccount(); - - // - // Instance Base Trader Class ... - mTrader = new XSCTradeBase(); - - // - // Configuring Base Trader Class ... - mTrader.SetAsyncMode(false); - mTrader.SetDeviationInPoints(mSlippage); - mTrader.SetExpertMagicNumber(mMagicNumber); - - // - // Setting Log Level ... - mTrader.LogLevel(LOG_LEVEL_ERRORS); - - // - // OnTrade Context ... - - // - mDaysForRead = 1; - mScanStarted = false; - - // - // Reset On Trade Counter ... - ResetOnTradeContext(); - - // - // Init On Trade Context ... - InitOnTradeContext(); - } - - // - // Deconstructor ... - ~XSCTrade() - { - // - // Remove Pointer ... - delete mTrader; - delete mAccount; - } - - // - // Props ... - - // - // Retrieve Slippage ... - int GetSlippage() - { - return mSlippage; - } - - // - // Retrieve Magic Number ... - ulong GetMagicNumber() - { - return mMagicNumber; - } - - // - double GetMaxAllowedSpread() - { - return mMaxAllowedSpread; - } - - // - int GetMaxAllowedPositions() - { - return mMaxAllowedPositions; - } - - // - void SetMaxAllowedPositions(int value) - { - // - if (value < 0) - { - value = 0; - } - - // - mMaxAllowedPositions = value; - } - - // - double GetMaxAllowedDrawdownFactor() - { - return mMaxAllowedDrawdownFactor; - } - - // - // Add Event Listeners ... - - // - void AddOnModifyPositionEventHandler(TOnModify handler) - { - // - Add( - handler, - mOnModifyEventHandlers - // - ); - } - - // - void AddOnForceClosePositionEventHandler(TOnForceClose handler) - { - // - Add( - handler, - mOnForceCloseEventHandlers - // - ); - } - - // - void AddOnPartialClosePositionEventHandler(TOnPartialClose handler) - { - // - Add( - handler, - mOnPartialCloseEventHandlers - // - ); - } - - // - // Add New Deals Changed Event Handler ... - void AddOnTradeStateChangedEventHandler(TOnTradeStateChanged handler) - { - // - Add( - handler, - mTradeStateChangedEventHandlers - // - ); - } - - // - // Add New Deals Changed Event Handler ... - void AddOnDealsChangedEventHandler(TOnDealsChanged handler) - { - // - Add( - handler, - mDealsChangedEventHandlers - // - ); - } - - // - // Add New Orders Changed Event Handler ... - void AddOnOrdersChangedEventHandler(TOnOrdersChanged handler) - { - // - Add( - handler, - mOrdersChangedEventHandlers - // - ); - } - - // - // Add New Positions Changed Event Handler ... - void AddOnPositionsChangedEventHandler(TOnPositionsChanged handler) - { - // - Add( - handler, - mPositionsChangedEventHandlers - // - ); - } - - // - // Add New Stop Loss Event Handler ... - void AddOnStopLossEventHandler(TOnStopLoss handler) - { - // - Add( - handler, - mStopLossEventHandlers - // - ); - } - - // - // Add New Stop Loss Event Handler ... - void AddOnTakeProfitEventHandler(TOnTakeProfit handler) - { - // - Add( - handler, - mTakeProfitEventHandlers - // - ); - } - - // - // Functions ... - - // - // Handlers ... - - // - // Process On Trade Requirement ... - // this Only Used when we Have to Proccess OnTrade Event in EA(s) ... - void HandleOnTradeEvent( - XOnTradeHandlerState &result // Hold's Result - ) - { - // - result.Clean(); - - // - if (mScanStarted) - { - // - ProcessOnTradeContext(result); - } - else - { - // - // Init Trade Context ... - InitOnTradeContext(); - - // - return; - } - - // - // Here we Can Check the Start ... - bool isValid = - // - result.IsValid() && - // - !result.hasNewDeal && - !result.hasNewOrder && - !result.hasNewPosition && - !result.hasNewHistoryOrder - // - ; - if (!isValid) - { - return; - } - - // - // State ... - - // - // Notfy Trade State Changed Event ... - NotifyTradeStateChangeEvent(result); - - // - // Deals ... - if (result.hasNewDeal) - { - // - // Notfy Deals Changed Event ... - NotifyDealsChangeEvent(result.newDeals); - - // - // Retrieve Last Deal ... - XDeal deals[]; - int dealsCount = GetDeals(deals); - if (dealsCount > 0) - { - // - XDeal lastDeal = deals[0]; - - // - if (lastDeal.reason == DEAL_REASON_TP) - { - NotifyTakeProfitEvent(lastDeal); - } - else if (lastDeal.reason == DEAL_REASON_SL) - { - NotifyStopLossEvent(lastDeal); - } - } - } - - // - // Orders ... - if (result.hasNewOrder || result.hasNewHistoryOrder) - { - // - // Notfy Orders Changed Event ... - NotifyOrdersChangeEvent(result.newOrders + result.newHistoryOrders); - } - - // - // Positions ... - if (result.hasNewPosition) - { - // - // Notfy Positions Changed Event ... - NotifyPositionsChangeEvent(result.newPositions); - } - } - - // - // This Must be Called Every time OnTrade Event Happening ... - // this Used for Implementing Custom Senarios ... - XOnTradeHandlerState HandleOnTrade() - { - // - // Handle OnTrade Event ... - XOnTradeHandlerState state; - HandleOnTradeEvent(state); - if ( - !state.hasNewDeal && - !state.hasNewOrder && - !state.hasNewPosition && - !state.hasNewHistoryOrder) - { - return state; - } - - // - // State ... - - // - // Notfy Trade State Changed Event ... - NotifyTradeStateChangeEvent(state); - - // - // DEALS ... - if (state.hasNewDeal) - { - // - // Notfy Deals Changed Event ... - NotifyDealsChangeEvent(state.newDeals); - - // - // Retrieve Last Deal ... - XDeal deals[]; - GetDeals(deals); - int dealsCount = ArraySize(deals); - if (dealsCount > 0) - { - // - XDeal lastDeal = deals[0]; - - // - if (lastDeal.reason == DEAL_REASON_TP) - { - NotifyTakeProfitEvent(lastDeal); - } - else if (lastDeal.reason == DEAL_REASON_SL) - { - NotifyStopLossEvent(lastDeal); - } - } - } - - // - // ORDERS ... - if (state.hasNewOrder || state.hasNewHistoryOrder) - { - // - // Notfy Orders Changed Event ... - NotifyOrdersChangeEvent(state.newOrders + state.newHistoryOrders); - } - - // - // POSITIONS ... - if (state.hasNewPosition) - { - // - // Notfy Positions Changed Event ... - NotifyPositionsChangeEvent(state.newPositions); - } - - // - return state; - } - - // - // Trade Actions ... - - // - // Main ... - - // - // Policies ... - - // - // Check Acocunt Balance is Allow new Trades or not ... - bool CheckEquityForTrade() - { - // - bool result = false; - - // - if (mMaxAllowedDrawdownFactor <= 0) - { - // - result = true; - return result; - } - - // - double equity = mAccount.GetEquity(); - double balance = mAccount.GetBalance(); - - // - double selectedBalance = MathMax(equity, balance) - MathMin(equity, balance); - - // - double maxAllowedBalanceDrawDown = GetMaxAllowedEquity(); - - // - result = equity > balance || - (equity <= balance && - selectedBalance <= maxAllowedBalanceDrawDown); - - // - return result; - } - - // - // Check Max Allowed Positions Policy for Trade ... - bool CheckPositionsForTrade() - { - // - bool result = false; - - // - if (mMaxAllowedPositions <= 0) - { - // - result = true; - return result; - } - - // - XPosition positions[]; - int positionsCount = GetPositions(positions); - if (positionsCount <= 0) - { - // - result = true; - return result; - } - - // - result = positionsCount < mMaxAllowedPositions; - - // - return result; - } - - // - // Check Spread is Ok for Executing Specific Signal ... - bool CheckSpreadForSignalExecution(XSignal &mSignal) - { - // - bool result = false; - - // - bool isSpreadCheckEnable = mMaxAllowedSpread > 0; - if (!isSpreadCheckEnable) - { - result = true; - } - else - { - // - // Retrieve Signal Spread ... - double spread = mSignal.GetSpread(); - result = spread <= mMaxAllowedSpread; - } - - // - return result; - } - - // - // Check Account Policy ... - bool CheckAccountPolicy( - XSignal &mSignal, // For Executing Signal - ENUM_X_SIGNAL_EXECUTION_RESULT &state // State Holder - ) - { - // - bool result = false; - - // - // Check Positions For Trade ... - result = CheckPositionsForTrade(); - if (!result) - { - // - state = X_SIGNAL_EXECUTION_FAILED_MAX_REACHED; - return result; - } - - // - // Check Equity For Trade ... - result = CheckEquityForTrade(); - if (!result) - { - // - state = X_SIGNAL_EXECUTION_FAILED_NO_EQUITY; - return result; - } - - // - // Check Spread for Trade ... - result = CheckSpreadForSignalExecution(mSignal); - if (!result) - { - // - state = X_SIGNAL_EXECUTION_FAILED_SPREAD; - return result; - } - - // - return result; - } - - // - // Execute a Signal ... - bool ExecuteSignal( - XSignal &mSignal, // Signal - ENUM_X_SIGNAL_EXECUTION_RESULT &state, // Result - ENUM_ORDER_TYPE_TIME lifetime = ORDER_TIME_GTC, // Order LifeTime - datetime expiration = NULL, // order expiration time - bool checkPolicies = true // Check Account Policies - ) - { - // - bool result = false; - state = X_SIGNAL_EXECUTION_UNKNOWN; - - // - double currentEntry = GetEntry( - mSignal.symbol, - mSignal.type - // - ); - bool isLong = IsLong(mSignal.type); - - // - if (!mSignal.IsValid()) - { - // - state = X_SIGNAL_EXECUTION_FAILED_INVALID_PARAMS; - return result; - } - - // - // Prepare Signal Comment ... - string mSComment = mSignal.GenerateComment(); - mSignal.comment += mSComment; - - // - // Handle Market Execution ... - if (mSignal.mode == X_ORDER_MODE_MARKET) - { - // - // Do Apply Policies here ... - bool hasPolicy = !checkPolicies - ? true - : CheckAccountPolicy(mSignal, state); - if (!hasPolicy) - { - result = false; - } - else - { - // - if (isLong) - { - // - result = Buy( - mSignal.symbol, - mSignal.period, - mSignal.volume, - mSignal.entry, - mSignal.sl, - mSignal.tp, - mSignal.comment - // - ); - } - else - { - // - result = Sell( - mSignal.symbol, - mSignal.period, - mSignal.volume, - mSignal.entry, - mSignal.sl, - mSignal.tp, - mSignal.comment - // - ); - } - } - } - // - // Handle Stop Execution ... - else if (mSignal.mode == X_ORDER_MODE_STOP) - { - - // - // Check Conditions ... - - // - // Check Price ... - result = isLong - ? mSignal.entry > currentEntry - : mSignal.entry < currentEntry; - if (!result) - { - // - state = X_SIGNAL_EXECUTION_FAILED_PRICE_ERROR; - return result; - } - - // - // Execute Order ... - if (isLong) - { - // - result = BuyStop( - mSignal.symbol, - mSignal.period, - mSignal.volume, - mSignal.entry, - mSignal.sl, - mSignal.tp, - lifetime, - expiration, - mSignal.comment - // - ); - } - else - { - // - result = SellStop( - mSignal.symbol, - mSignal.period, - mSignal.volume, - mSignal.entry, - mSignal.sl, - mSignal.tp, - lifetime, - expiration, - mSignal.comment - // - ); - } - } - // - // Handle Limit Execution ... - else if (mSignal.mode == X_ORDER_MODE_LIMIT) - { - // - // Check Conditions ... - - // - // Check Price ... - result = isLong - ? mSignal.entry < currentEntry - : mSignal.entry > currentEntry; - if (!result) - { - // - state = X_SIGNAL_EXECUTION_FAILED_PRICE_ERROR; - return result; - } - - // - // Execute Order ... - if (isLong) - { - // - result = BuyLimit( - mSignal.symbol, - mSignal.period, - mSignal.volume, - mSignal.entry, - mSignal.sl, - mSignal.tp, - lifetime, - expiration, - mSignal.comment - // - ); - } - else - { - // - result = SellLimit( - mSignal.symbol, - mSignal.period, - mSignal.volume, - mSignal.entry, - mSignal.sl, - mSignal.tp, - lifetime, - expiration, - mSignal.comment - // - ); - } - } - - // - // Handle Ticket ... - if (result) - { - // - state = X_SIGNAL_EXECUTION_SUCCEED; - - // - ulong ticket; - if (mSignal.mode == X_ORDER_MODE_MARKET) - { - ticket = GetLastOpenPositionTicket(); - } - else - { - ticket = GetLastPlacedOrderTicket(); - } - - // - mSignal.positionId = ticket; - - // - // Handle Store XPositionInfo ... - if (mSignal.mode == X_ORDER_MODE_MARKET) - { - // - // TODO: Implement this ... - } - - // - // 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; - } - } - - // - return result; - } - - // - // Execute a Collection Of Signals ... - int ExecuteSignals( - XSignal &signals[], // Collection of Signal for Execution - ENUM_X_SIGNAL_EXECUTION_RESULT &states[], // Signal Execution Result - ENUM_ORDER_TYPE_TIME lifetime = ORDER_TIME_GTC, // Order LifeTime - datetime expiration = NULL, // order expiration time - bool checkPolicies = true // Check Account Policies - ) - { - // - int result = 0; - - // - Clean(states); - - // - int signalsCount = ArraySize(signals); - if (signalsCount <= 0) - { - return result; - } - - // - ArrayResize(states, signalsCount); - ArrayInitialize(states, X_SIGNAL_EXECUTION_UNKNOWN); - for (int i = 0; i < signalsCount; i++) - { - // - bool isExecuted = ExecuteSignal( - signals[i], - states[i], - lifetime, - expiration, - checkPolicies - // - ); - - // - if (isExecuted) - { - result++; - } - } - - // - return result; - } - - // - int ExecuteSpecifiedSignals( - XSignal &signals[], // Collection of Signal for Execution - XSignal ¬Executeds[], // Not Executed Signal - ENUM_X_SIGNAL_EXECUTION_RESULT &states[], // Signal Execution Result - ENUM_ORDER_TYPE_TIME lifetime = ORDER_TIME_GTC, // Order LifeTime - datetime expiration = NULL, // order expiration time - bool checkPolicies = true // Check Account Policies - ) - { - // - int result = 0; - - // - Clean(states); - Clean(notExecuteds); - - // - int signalsCount = ArraySize(signals); - if (signalsCount <= 0) - { - return result; - } - - // - ArrayResize(states, signalsCount); - ArrayInitialize(states, X_SIGNAL_EXECUTION_UNKNOWN); - for (int i = 0; i < signalsCount; i++) - { - // - bool isExecuted = ExecuteSignal( - signals[i], - states[i], - lifetime, - expiration - // - ); - - // - if (isExecuted) - { - result++; - } - else - { - // - AddRef( - signals[i], - notExecuteds // - ); - } - } - - // - return result; - } - - // - // Regular Trade Actions ... - - // - // Buy ... - - // - // Force Open a Buy/Long Position ... - bool Buy( - string symbol, // Specified Symbol - ENUM_TIMEFRAMES period, // Specified Trade's Period - double volume, // position volume - double price, // execution price - double sl = 0, // stop loss price - double tp = 0, // take profit price - string comment = NULL // comment - ) - { - // - bool result = false; - - // - ENUM_TIMEFRAMES mPeriod = ExtractPeriod(comment); - if (!IsValid(comment) || - !IsValid(mPeriod)) - { - // - string mPeriodStr = GeneratePeriodTag(period); - - // - comment += mPeriodStr; - } - - // - result = mTrader.Buy( - volume, - symbol, - price, - sl, - tp, - comment - // - ); - - // - return result; - } - - // - // Send BUY LIMIT order ... - bool BuyLimit( - string symbol, // Specified Symbol - ENUM_TIMEFRAMES period, // Specified Trade's Period - double volume, // order volume - double price, // order price - double sl = 0.0, // stop loss price - double tp = 0.0, // take profit price - ENUM_ORDER_TYPE_TIME typeTime = ORDER_TIME_GTC, // order lifetime - datetime expiration = 0, // order expiration time - string comment = NULL // comment - ) - { - // - bool result = false; - - // - ENUM_TIMEFRAMES mPeriod = ExtractPeriod(comment); - if (!IsValid(comment) || - !IsValid(mPeriod)) - { - // - string mPeriodStr = GeneratePeriodTag(period); - - // - comment += mPeriodStr; - } - - // - result = mTrader.BuyLimit( - volume, - price, - symbol, - sl, - tp, - typeTime, - expiration, - comment - // - ); - - // - return result; - } - - // - // Send BUY STOP order ... - bool BuyStop( - string symbol, // Specified Symbol - ENUM_TIMEFRAMES period, // Specified Trade's Period - double volume, // order volume - double price, // order price - double sl = 0.0, // stop loss price - double tp = 0.0, // take profit price - ENUM_ORDER_TYPE_TIME typeTime = ORDER_TIME_GTC, // order lifetime - datetime expiration = 0, // order expiration time - string comment = NULL // comment - ) - { - // - bool result = false; - - // - ENUM_TIMEFRAMES mPeriod = ExtractPeriod(comment); - if (!IsValid(comment) || - !IsValid(mPeriod)) - { - // - string mPeriodStr = GeneratePeriodTag(period); - - // - comment += mPeriodStr; - } - - // - result = mTrader.BuyStop( - volume, - price, - symbol, - sl, - tp, - typeTime, - expiration, - comment - // - ); - - // - return result; - } - - // - // Sell ... - - // - // Force Open a Sell/Short Position ... - bool Sell( - string symbol, // Specified Symbol - ENUM_TIMEFRAMES period, // Specified Trade's Period - double volume, // position volume - double price, // execution price - double sl = 0, // stop loss price - double tp = 0, // take profit price - string comment = NULL // comment - ) - { - // - bool result = false; - - // - ENUM_TIMEFRAMES mPeriod = ExtractPeriod(comment); - if (!IsValid(comment) || - !IsValid(mPeriod)) - { - // - string mPeriodStr = GeneratePeriodTag(period); - - // - comment += mPeriodStr; - } - - // - result = mTrader.Sell( - volume, - symbol, - price, - sl, - tp, - comment - // - ); - - // - return result; - } - - // - // Send SELL LIMIT order ... - bool SellLimit( - string symbol, // Specified Symbol - ENUM_TIMEFRAMES period, // Specified Trade's Period - double volume, // order volume - double price, // order price - double sl = 0.0, // stop loss price - double tp = 0.0, // take profit price - ENUM_ORDER_TYPE_TIME typeTime = ORDER_TIME_GTC, // order lifetime - datetime expiration = 0, // order expiration time - string comment = NULL // comment - ) - { - // - bool result = false; - - // - ENUM_TIMEFRAMES mPeriod = ExtractPeriod(comment); - if (!IsValid(comment) || - !IsValid(mPeriod)) - { - // - string mPeriodStr = GeneratePeriodTag(period); - - // - comment += mPeriodStr; - } - - // - result = mTrader.SellLimit( - volume, - price, - symbol, - sl, - tp, - typeTime, - expiration, - comment - // - ); - - // - return result; - } - - // - // Send SELL STOP order ... - bool SellStop( - string symbol, // Specified Symbol - ENUM_TIMEFRAMES period, // Specified Trade's Period - double volume, // order volume - double price, // order price - double sl = 0.0, // stop loss price - double tp = 0.0, // take profit price - ENUM_ORDER_TYPE_TIME typeTime = ORDER_TIME_GTC, // order lifetime - datetime expiration = 0, // order expiration time - string comment = NULL // comment - ) - { - // - bool result = false; - - // - ENUM_TIMEFRAMES mPeriod = ExtractPeriod(comment); - if (!IsValid(comment) || - !IsValid(mPeriod)) - { - // - string mPeriodStr = GeneratePeriodTag(period); - - // - comment += mPeriodStr; - } - - // - result = mTrader.SellStop( - volume, - price, - symbol, - sl, - tp, - typeTime, - expiration, - comment - // - ); - - // - return result; - } - - // - // Check a Position is Exists Open or not ... - bool IsOpen( - ulong ticket // Specified Position Ticket - ) - { - // - bool result = false; - - // - result = mPositionInfo - .SelectByTicket(ticket); - - // - return result; - } - - // - // Modify Position ... - bool Modify( - const ulong ticket, // position ticket - double sl = 0, // stop loss price - double tp = 0, // take profit - string comment = NULL // comment - ) - { - // - bool result = false; - - // - // Validate Args ... - XPosition position; - result = - GetPosition( - ticket, - position // - ) && - (tp >= 0 || sl >= 0); - if (!result) - { - return result; - } - - // - // Use Position Comment when there isn't new One ... - if (!IsValid(comment) == 0) - { - // - // if there isn't provided Comment - // Use Position Comment for default ... - comment = "Modify " + GetPositionComment(ticket); - } - - // - result = mTrader.PositionModify( - ticket, - sl, - tp, - comment - // - ); - if (result) - { - // - NotifyModifyEvent( - ticket, - position.profit, - comment // - ); - } - - // - return result; - } - - // - // Close Position By Ticket ... - bool Close( - ulong ticket, // Position Ticket - string comment = NULL // Close Position By Specific Comment - ) - { - // - bool result = false; - - // - // Check Position Open ... - XPosition position; - result = GetPosition( - ticket, - position // - ); - if (!result) - { - return result; - } - - // - // Use Default Position Comment if it's Not Provided ... - if (!IsValid(comment)) - { - comment = "Close " + GetPositionComment(ticket); - } - - // - // Close Position By Specific Comment ... - result = mTrader.PositionClose( - ticket, - mSlippage, - comment - // - ); - if (result) - { - // - NotifyForceCloseEvent( - ticket, - position, - comment // - ); - } - - // - return result; - } - - // - // Close Specified Positions ... - int Close( - string comment = NULL, // Close Position By Specific Comment - string symbol = NULL, // Trading Symbol - string provider = NULL, // Signal Provider - ENUM_TIMEFRAMES period = NULL, // Trading Period - ENUM_X_POSITION_TYPES type = NULL, // Long (Buy) or Short (Sell) - bool filterByMagic = true // Get Only Self Open Positions - ) - { - // - int result = 0; - - // - XPosition positions[]; - int positionsCount = GetPositions( - positions, - symbol, - provider, - period, - type, - filterByMagic); - if (positionsCount <= 0) - { - return result; - } - - // - for (int i = 0; i < positionsCount; i++) - { - // - XPosition iPosition = positions[i]; - - // - bool isClosed = Close( - iPosition.ticket, - comment - // - ); - if (isClosed) - { - result++; - } - } - - // - return result; - } - - // - // Close a Collection of Positions ... - int Close( - XPosition &positions[], // Collection of Positions - string comment // Close Comment - ) - { - // - int result = 0; - - // - int positionsCount = ArraySize(positions); - if (positionsCount <= 0) - { - return result; - } - - // - for (int i = 0; i < positionsCount; i++) - { - // - XPosition iPosition = positions[i]; - - // - bool isClosed = Close( - iPosition.ticket, - comment - // - ); - if (isClosed) - { - result++; - } - } - - // - return result; - } - - // - // Close Partial By Ticket ... - bool ClosePartial( - ulong ticket, // Position Ticket - double volume, // Volume Size for Partial Closing - string comment = NULL // Close Position By Specific Comment - ) - { - // - bool result = false; - - // - XPosition position; - result = GetPosition( - ticket, - position // - ); - if (!result) - { - return result; - } - - // - // Use Default Partial Close Comment ... - if (!IsValid(comment)) - { - // - comment += "PClose " + GetPositionComment(ticket); - } - - // - result = mTrader.PositionClosePartial( - ticket, - volume, - mSlippage, - comment - // - ); - if (result) - { - // - NotifyPartialCloseEvent( - ticket, - position.profit, - comment // - ); - } - - // - return result; - } - - // - // Cancel Specific Order ... - bool CancelOrder(ulong ticket) - { - return mTrader - .OrderDelete(ticket); - } - - // - // Cancel Specific Orders ... - int CancelOrders( - XOrder &orders[] // Specified Orders ... - ) - { - // - int result = 0; - - // - int ordersCount = ArraySize(orders); - if (ordersCount <= 0) - { - return result; - } - - // - for (int i = 0; i < ordersCount; i++) - { - // - XOrder iOrder = orders[i]; - - // - bool isDeleted = mTrader - .OrderDelete(iOrder.ticket); - if (isDeleted && !result) - { - result++; - } - } - - // - return result; - } - - // - // Extractors ... - - // - // Positions ... - - // - // Calculate Positions Profit ... - double Profit( - string symbol = NULL, // Trading Symbol - string provider = NULL, // Signal Provider - ENUM_TIMEFRAMES period = NULL, // Trading Period - ENUM_X_POSITION_TYPES type = NULL, // Long (Buy) or Short (Sell) - bool filterByMagic = true // Get Only Self Open Positions - ) - { - // - double result = 0; - - // - // Retrieve Positions ... - XPosition positions[]; - int positionsCount = GetPositions( - positions, - symbol, - provider, - period, - type, - filterByMagic - // - ); - if (positionsCount <= 0) - { - return result; - } - - // - for (int i = 0; i < positionsCount; i++) - { - result += positions[i].profit; - } - - // - return result; - } - - // - // Retrieve Specific Position by Index ... - bool GetPosition( - int index, // Specified Index - XPosition &result // Hold's Result - ) - { - // - return result - .ByIndex(index); - } - - // - // Retrieve Specific Position by Ticket ... - bool GetPosition( - ulong ticket, // Specified Ticket - XPosition &result // Hold's Result - ) - { - // - return result - .ByTicket(ticket); - } - - // - // Retrieve Positions ... - int GetPositions( - XPosition &result[], // Hold's Result - string symbol = NULL, // Trading Symbol - string provider = NULL, // Signal Provider - ENUM_TIMEFRAMES period = NULL, // Trading Period - ENUM_X_POSITION_TYPES type = NULL, // Long (Buy) or Short (Sell) - bool filterByMagic = true, // Get Only Self Open Positions - bool forceClean = true // Clean Result Array - ) - { - // - int mResult = 0; - - // - int before = ArraySize(result); - - // - if (forceClean) - { - Clean(result); - } - - // - // Count Positions ... - int itemsCount = PositionsTotal(); - if (itemsCount <= 0) - { - return mResult; - } - - // - // Loop Through all Positions ... - for (int i = itemsCount - 1; i >= 0; i--) - { - // - XPosition iItem; - bool isLoaded = iItem.ByIndex(i); - if (!isLoaded) - { - continue; - } - - // - // Now we have to Check Given Filters ... - bool isFiltersPassed = - iItem.IsFiltersPassed( - symbol, - provider, - period, - type, - mMagicNumber, - filterByMagic - // - ); - if (!isFiltersPassed) - { - continue; - } - - // - // Add Filtered Item into Result ... - AddRef( - iItem, - result - // - ); - } - - // - int after = ArraySize(result); - - // - mResult = after - before; - - // - return mResult; - } - - // - void GetPositions( - XPosition &longs[], // Hold's Longs Result - XPosition &shorts[], // Hold's Shorts Result - string symbol = NULL, // Trading Symbol - string provider = NULL, // Signal Provider - ENUM_TIMEFRAMES period = NULL, // Trading Period - bool filterByMagic = true, // Get Only Self Open Positions - bool forceClean = true // Clean Result Array - ) - { - // - // Retrieve Long Positions ... - GetPositions( - longs, - symbol, - provider, - period, - X_POSITION_TYPE_LONG, - filterByMagic, - forceClean // - ); - - // - // Retrieve Short Positions ... - GetPositions( - shorts, - symbol, - provider, - period, - X_POSITION_TYPE_SHORT, - filterByMagic, - forceClean // - ); - } - - // - // Select In Profit Positions ... - int GetInProfitPositions( - XPosition &result[], // Hold's Result - string symbol = NULL, // Trading Symbol - string provider = NULL, // Signal Provider - ENUM_TIMEFRAMES period = NULL, // Trading Period - ENUM_X_POSITION_TYPES type = NULL, // Long (Buy) or Short (Sell) - ENUM_X_POSITION_SELECT_METHODS method = NULL, // Selection Method - bool filterByMagic = true, // Get Only Self Open Positions - bool forceClean = true // Clean Result Array - ) - { - // - int mResult = 0; - - // - int before = ArraySize(result); - - // - if (forceClean) - { - Clean(result); - } - - // - XPosition positions[]; - int positionsCount = GetPositions( - positions, - symbol, - provider, - period, - type, - filterByMagic, - forceClean); - if (positionsCount <= 0) - { - return mResult; - } - - // - XPosition min; - XPosition max; - - // - for (int i = 0; i < positionsCount; i++) - { - // - XPosition iPosition = positions[i]; - - // - if (iPosition.profit <= 0) - { - continue; - } - - // - // Calculate Min and Max ... - - // - // Min ... - if (!min.IsValid() || min.profit <= 0 || min.profit > iPosition.profit) - { - min = iPosition; - } - - // - // Max ... - if (!max.IsValid() || max.profit <= 0 || max.profit < iPosition.profit) - { - max = iPosition; - } - - // - bool isSelectionMethodFilterPassed = - // - (method == NULL || - method == X_POSITION_SELECT_ALL) - ? true - : false; - // - ; - if (!isSelectionMethodFilterPassed) - { - continue; - } - - // - AddRef( - iPosition, - result - // - ); - } - - // - if (min.IsValid() && - (method == X_POSITION_SELECT_MIN || - method == X_POSITION_SELECT_BOTH)) - { - // - AddRef( - min, - result - // - ); - } - - // - if (max.IsValid() && - (method == X_POSITION_SELECT_MAX || - method == X_POSITION_SELECT_BOTH)) - { - // - AddRef( - max, - result - // - ); - } - - // - int after = ArraySize(result); - - // - mResult = after - before; - - // - return mResult; - } - - // - // Select In Drawdown Positions ... - int GetInDrawdownPositions( - XPosition &result[], // Hold's Result - string symbol = NULL, // Trading Symbol - string provider = NULL, // Signal Provider - ENUM_TIMEFRAMES period = NULL, // Trading Period - ENUM_X_POSITION_TYPES type = NULL, // Long (Buy) or Short (Sell) - ENUM_X_POSITION_SELECT_METHODS method = NULL, // Selection Method - bool filterByMagic = true, // Get Only Self Open Positions - bool forceClean = true // Clean Result Array - ) - { - // - int mResult = 0; - - // - int before = ArraySize(result); - - // - if (forceClean) - { - Clean(result); - } - - // - XPosition positions[]; - int positionsCount = GetPositions( - positions, - symbol, - provider, - period, - type, - filterByMagic, - forceClean); - if (positionsCount <= 0) - { - return mResult; - } - - // - XPosition min; - XPosition max; - - // - for (int i = 0; i < positionsCount; i++) - { - // - XPosition iPosition = positions[i]; - - // - if (iPosition.profit >= 0) - { - continue; - } - - // - // Calculate Min and Max ... - - // - // Min ... - if (!min.IsValid() || min.profit <= 0 || min.profit > iPosition.profit) - { - min = iPosition; - } - - // - // Max ... - if (!max.IsValid() || max.profit <= 0 || max.profit < iPosition.profit) - { - max = iPosition; - } - - // - bool isSelectionMethodFilterPassed = - // - (method == NULL || - method == X_POSITION_SELECT_ALL) - ? true - : false; - // - ; - if (!isSelectionMethodFilterPassed) - { - continue; - } - - // - AddRef( - iPosition, - result - // - ); - } - - // - if (min.IsValid() && - (method == X_POSITION_SELECT_MIN || - method == X_POSITION_SELECT_BOTH)) - { - // - AddRef( - min, - result - // - ); - } - - // - if (max.IsValid() && - (method == X_POSITION_SELECT_MAX || - method == X_POSITION_SELECT_BOTH)) - { - // - AddRef( - max, - result - // - ); - } - - // - int after = ArraySize(result); - - // - mResult = after - before; - - // - return mResult; - } - - // - // Orders ... - - // - // Retrieve Specific Order by Index ... - bool GetOrder( - int index, // Specified Index - XOrder &result // Hold's Result - ) - { - // - return result - .ByIndex(index); - } - - // - // Retrieve Specific Positions Orders ... - int GetOrders( - ulong ticket, // Positions Ticket - XOrder &result[], // Hold's Result - bool forceClean = true // Clean Result Array - ) - { - // - int mResult = 0; - - // - // Select History by Specified Ticket ... - bool isHistorySelected = HistorySelectByPosition(ticket); - if (!isHistorySelected) - { - return mResult; - } - - // - int ordersCount = HistoryOrdersTotal(); - if (ordersCount <= 0) - { - return mResult; - } - - // - int before = ArraySize(result); - - // - if (forceClean) - { - Clean(result); - } - - // - for (int i = 0; i < ordersCount; i++) - { - // - XOrder iOrder; - bool isLoaded = iOrder.HistoryByIndex(i); - if (!isLoaded) - { - continue; - } - - // - bool isTicketFilterPassed = - // - iOrder.ticket = ticket - // - ; - if (!isTicketFilterPassed) - { - continue; - } - - // - AddRef( - iOrder, - result - // - ); - } - - // - int after = ArraySize(result); - - // - mResult = after - before; - - // - return mResult; - } - - // - // Retrieve All Orders ... - int GetOrders( - XOrder &result[], // Hold's Result - string symbol = NULL, // Trading Symbol - string provider = NULL, // Signal Provider - ENUM_TIMEFRAMES period = NULL, // Trading Period - ENUM_X_POSITION_TYPES type = NULL, // Long (Buy) or Short (Sell) - ENUM_ORDER_STATE state = NULL, // Order State - bool filterByMagic = true, // Get Only Self Open Positions - bool forceClean = true // Clean Result Array - ) - { - // - int mResult = 0; - - // - int before = ArraySize(result); - - // - if (forceClean) - { - Clean(result); - } - - // - // Count Positions ... - int itemsCount = OrdersTotal(); - if (itemsCount <= 0) - { - return mResult; - } - - // - // Loop Through all Positions ... - for (int i = itemsCount - 1; i >= 0; i--) - { - // - XOrder iItem; - bool isLoaded = iItem.ByIndex(i); - if (!isLoaded) - { - continue; - } - - // - // Now we have to Check Given Filters ... - bool isFiltersPassed = - iItem.IsFiltersPassed( - symbol, - provider, - period, - type, - state, - mMagicNumber, - filterByMagic - // - ); - if (!isFiltersPassed) - { - continue; - } - - // - // Add Filtered Item into Result ... - AddRef( - iItem, - result - // - ); - } - - // - int after = ArraySize(result); - - // - mResult = after - before; - - // - return mResult; - } - - // - // Retrieve Historical Orders ... - int GetOrders( - XOrder &result[], // Hold's Result - string symbol = NULL, // Trading Symbol - string provider = NULL, // Signal Provider - ENUM_TIMEFRAMES period = NULL, // Trading Period - ENUM_X_POSITION_TYPES type = NULL, // Long (Buy) or Short (Sell) - ENUM_ORDER_STATE state = NULL, // Order State - datetime startDate = NULL, // Specify Start Date - datetime endDate = NULL, // Specify End Date - bool filterByMagic = true, // Get Only Self Open Positions - bool forceClean = true // Clean Result Array - ) - { - // - int mResult = 0; - - // - endDate = NormalizeTime(endDate); - - // - if (!IsValid(startDate)) - { - startDate = endDate - PeriodSeconds(PERIOD_D1); - } - - // - bool isHistorySelected = HistorySelect( - startDate, - endDate); - if (!isHistorySelected) - { - return mResult; - } - - // - int before = ArraySize(result); - - // - if (forceClean) - { - Clean(result); - } - - // - // Count Positions ... - int itemsCount = OrdersTotal(); - if (itemsCount <= 0) - { - return mResult; - } - - // - // Loop Through all Positions ... - for (int i = itemsCount - 1; i >= 0; i--) - { - // - XOrder iItem; - bool isLoaded = iItem.HistoryByIndex(i); - if (!isLoaded) - { - continue; - } - - // - // Now we have to Check Given Filters ... - bool isFiltersPassed = - iItem.IsFiltersPassed( - symbol, - provider, - period, - type, - state, - mMagicNumber, - filterByMagic - // - ); - if (!isFiltersPassed) - { - continue; - } - - // - // Add Filtered Item into Result ... - AddRef( - iItem, - result - // - ); - } - - // - int after = ArraySize(result); - - // - mResult = after - before; - - // - return mResult; - } - - // - // Deals ... - - // - // Retrieve Specific Deal by Index ... - bool GetDeal( - int index, // Specified Index - XDeal &result // Hold's Result - ) - { - // - return result - .ByIndex(index); - } - - // - bool GetLastDeal( - XDeal &result // Hold's Result - ) - { - // - bool mResult = false; - - // - mResult = HistorySelect(0, TimeCurrent()); - if (!mResult) - { - return mResult; - } - - // - int lastDealIndex = HistoryDealsTotal() - 1; - - // - mResult = GetDeal( - lastDealIndex, - result // - ); - - // - return mResult; - } - - // - // Retrieve Specified Deal's History ... - int GetDealsHistory( - XDeal &deal, // Specified Deal - XOrder &history[], // Deals History - bool forceClean = true // Clean Result Array - ) - { - // - int result = 0; - - // - if (!deal.IsValid()) - { - return result; - } - - // - result = GetOrders( - deal.positionId, - history, - forceClean); - - // - return result; - } - - // - // Retrieve All Deals ... - int GetDeals( - XDeal &result[], // Hold's Result - string symbol = NULL, // Trading Symbol - string provider = NULL, // Signal Provider - ENUM_TIMEFRAMES period = NULL, // Trading Period - ENUM_DEAL_TYPE type = NULL, // Deal Type - ENUM_DEAL_ENTRY entry = NULL, // Deal Entry - ENUM_DEAL_REASON reason = NULL, // Deal Reason - datetime startDate = NULL, // Specify Start Date - datetime endDate = NULL, // Specify End Date - bool filterByMagic = true, // Get Only Self Open Positions - bool forceClean = true // Clean Result Array - ) - { - // - int mResult = 0; - - // - endDate = NormalizeTime(endDate); - - // - if (!IsValid(startDate)) - { - startDate = endDate - PeriodSeconds(PERIOD_D1); - } - - // - bool isHistorySelected = HistorySelect( - startDate, - endDate); - if (!isHistorySelected) - { - return mResult; - } - - // - int before = ArraySize(result); - - // - if (forceClean) - { - Clean(result); - } - - // - // Count Positions ... - int itemsCount = HistoryDealsTotal(); - if (itemsCount <= 0) - { - return mResult; - } - - // - // Loop Through all Positions ... - for (int i = itemsCount - 1; i >= 0; i--) - { - // - XDeal iItem; - bool isLoaded = iItem.ByIndex(i); - if (!isLoaded) - { - continue; - } - - // - // Now we have to Check Given Filters ... - bool isFiltersPassed = - iItem.IsFiltersPassed( - symbol, - provider, - period, - type, - entry, - reason, - mMagicNumber, - filterByMagic - // - ); - if (!isFiltersPassed) - { - continue; - } - - // - // Add Filtered Item into Result ... - AddRef( - iItem, - result - // - ); - } - - // - int after = ArraySize(result); - - // - mResult = after - before; - - // - return mResult; - } - - // - // Support Functions ... - - // - // Check a Position has Support or not ... - bool HasSupport( - ulong ticket, - bool forceOpen = true // - ) - { - // - bool result = false; - - // - result = ticket > 0; - if (!result) - { - return result; - } - - // - if (forceOpen) - { - // - result = IsOpen(ticket); - if (!result) - { - return result; - } - } - - // - XPosition positions[]; - int positionsCount = GetPositions(positions); - result = IsValidSize(positionsCount); - if (!result) - { - return result; - } - - // - // Extract Support Positions ... - XPosition supports[]; - int supportsCount = ExtractSupports( - positions, - supports // - ); - result = IsValidSize(supportsCount); - if (!result) - { - return result; - } - - // - // Loop Through Supports ... - for (int i = 0; i < supportsCount; i++) - { - // - XPosition iSupport = supports[i]; - - // - ulong supportedTicket = ExtractSupportedTicket(iSupport.comment); - ulong eqmSupportedTicket = ExtractEQMSupportedTicket(iSupport.comment); - - // - result = - // - (supportedTicket > 0 && ticket == supportedTicket) - // - || - // - (eqmSupportedTicket > 0 && ticket == eqmSupportedTicket) - // - ; - if (result) - { - break; - } - } - - // - return result; - } - - // - // Retrieve Specific Position's Supports ... - int GetSupports( - ulong ticket, - XPosition &dest[], // Result ... - bool forceOpen = true // - ) - { - // - int result = 0; - - // - Clean(dest); - - // - bool hasSupport = HasSupport( - ticket, - forceOpen // - ); - if (!hasSupport) - { - return result; - } - - // - XPosition positions[]; - int positionsCount = GetPositions(positions); - if (!IsValidSize(positionsCount)) - { - return result; - } - - // - // Extract Support Positions ... - XPosition supports[]; - int supportsCount = ExtractSupports( - positions, - supports // - ); - if (!IsValidSize(supportsCount)) - { - return result; - } - - // - // Loop Through Supports ... - for (int i = 0; i < supportsCount; i++) - { - // - XPosition iSupport = supports[i]; - - // - ulong supportedTicket = ExtractSupportedTicket(iSupport.comment); - ulong eqmSupportedTicket = ExtractEQMSupportedTicket(iSupport.comment); - - // - bool isOwn = - // - (supportedTicket > 0 && ticket == supportedTicket) - // - || - // - (eqmSupportedTicket > 0 && ticket == eqmSupportedTicket) - // - ; - if (isOwn) - { - // - AddRef( - iSupport, - dest // - ); - } - } - - // - result = ArraySize(dest); - - // - return result; - } - - // - // Retrieve Specific Position's Supports ... - int GetSupports( - ulong ticket, - XOrder &dest[], // Result ... - bool forceOpen = true // - ) - { - // - int result = 0; - - // - Clean(dest); - - // - bool hasSupport = HasSupport( - ticket, - forceOpen // - ); - if (!hasSupport) - { - return result; - } - - // - XOrder orders[]; - int ordersCount = GetOrders( - orders, - NULL, // All Symbols ... - NULL, // All Providers ... - NULL, // All Periods ... - X_POSITION_TYPE_ALL, // All Types ... - ORDER_STATE_PLACED, // Untriggere Orders ... - true // - ); - if (!IsValidSize(ordersCount)) - { - return result; - } - - // - // Extract Support Positions ... - XOrder supports[]; - int supportsCount = ExtractSupports( - orders, - supports // - ); - if (!IsValidSize(supportsCount)) - { - return result; - } - - // - // Loop Through Supports ... - for (int i = 0; i < supportsCount; i++) - { - // - XOrder iSupport = supports[i]; - - // - ulong supportedTicket = ExtractSupportedTicket(iSupport.comment); - ulong eqmSupportedTicket = ExtractEQMSupportedTicket(iSupport.comment); - - // - bool isOwn = - // - (supportedTicket > 0 && ticket == supportedTicket) - // - || - // - (eqmSupportedTicket > 0 && ticket == eqmSupportedTicket) - // - ; - if (isOwn) - { - // - AddRef( - iSupport, - dest // - ); - } - } - - // - result = ArraySize(dest); - - // - return result; - } - - // - // Tools ... - - // - // Retrieve Last Open Position Ticket ... - ulong GetLastOpenPositionTicket() - { - // - ulong result = 0; - - int positionsCount = PositionsTotal(); - if (positionsCount <= 0) - { - return result; - } - - // - result = PositionGetTicket(PositionsTotal() - 1); - - // - return result; - } - - // - // Retrieve Last Placed Order Ticket ... - ulong GetLastPlacedOrderTicket() - { - // - ulong result = 0; - - int ordersCount = OrdersTotal(); - if (ordersCount <= 0) - { - return result; - } - - // - if (mOrderInfo.SelectByIndex(ordersCount - 1)) - { - result = mOrderInfo.Ticket(); - } - - // - return result; - } - - // - // Protected ... -protected: - // - // Props ... - - // - // Event Listener Notifiers ... - - // - // State ... - void NotifyTradeStateChangeEvent(const XOnTradeHandlerState &state) - { - // - int count = ArraySize(mTradeStateChangedEventHandlers); - if (count <= 0) - { - return; - } - - // - for (int i = 0; i < count; i++) - { - // - TOnTradeStateChanged iHandler = mTradeStateChangedEventHandlers[i]; - iHandler(state); - } - } - - // - // Deals ... - void NotifyDealsChangeEvent(int changes) - { - // - int count = ArraySize(mDealsChangedEventHandlers); - if (count <= 0) - { - return; - } - - // - for (int i = 0; i < count; i++) - { - // - TOnDealsChanged iHandler = mDealsChangedEventHandlers[i]; - iHandler(changes); - } - } - - // - // Orders ... - void NotifyOrdersChangeEvent(int changes) - { - // - int count = ArraySize(mOrdersChangedEventHandlers); - if (count <= 0) - { - return; - } - - // - for (int i = 0; i < count; i++) - { - // - TOnOrdersChanged iHandler = mOrdersChangedEventHandlers[i]; - iHandler(changes); - } - } - - // - // Positions ... - void NotifyPositionsChangeEvent(int changes) - { - // - int count = ArraySize(mPositionsChangedEventHandlers); - if (count <= 0) - { - return; - } - - // - for (int i = 0; i < count; i++) - { - // - TOnPositionsChanged iHandler = mPositionsChangedEventHandlers[i]; - iHandler(changes); - } - } - - // - // StopLoss ... - void NotifyStopLossEvent(const XDeal &deal) - { - // - int count = ArraySize(mStopLossEventHandlers); - if (count <= 0) - { - return; - } - - // - for (int i = 0; i < count; i++) - { - // - TOnStopLoss iHandler = mStopLossEventHandlers[i]; - iHandler(deal); - } - } - - // - // Take Profit ... - void NotifyTakeProfitEvent(const XDeal &deal) - { - // - int count = ArraySize(mTakeProfitEventHandlers); - if (count <= 0) - { - return; - } - - // - for (int i = 0; i < count; i++) - { - // - TOnTakeProfit iHandler = mTakeProfitEventHandlers[i]; - iHandler(deal); - } - } - - // - void NotifyModifyEvent( - ulong ticket, - double profit, - string comment // - ) - { - // - int count = ArraySize(mOnModifyEventHandlers); - if (count <= 0) - { - return; - } - - // - for (int i = 0; i < count; i++) - { - // - TOnModify iHandler = mOnModifyEventHandlers[i]; - iHandler( - ticket, - profit, - comment // - ); - } - } - - // - void NotifyForceCloseEvent( - ulong ticket, - XPosition &position, - string comment // - ) - { - // - int count = ArraySize(mOnForceCloseEventHandlers); - if (count <= 0) - { - return; - } - - // - for (int i = 0; i < count; i++) - { - // - TOnForceClose iHandler = mOnForceCloseEventHandlers[i]; - iHandler( - ticket, - position, - comment // - ); - } - } - - // - void NotifyPartialCloseEvent( - ulong ticket, - double profit, - string comment // - ) - { - // - int count = ArraySize(mOnPartialCloseEventHandlers); - if (count <= 0) - { - return; - } - - // - for (int i = 0; i < count; i++) - { - // - TOnModify iHandler = mOnPartialCloseEventHandlers[i]; - iHandler( - ticket, - profit, - comment // - ); - } - } - - // - // Tools ... - - // - // Retrieve Specified Position Comment ... - string GetPositionComment(ulong ticket) - { - // - string result = NULL; - - // - if (!IsOpen(ticket)) - { - return result; - } - - // - XPosition position; - bool isLoaded = position.ByTicket(ticket); - if (!isLoaded) - { - return result; - } - - // - result = position.comment; - - // - return result; - } - - // - ENUM_TIMEFRAMES GetDealPeriod(XDeal &deal) - { - // - ENUM_TIMEFRAMES result = NULL; - - // - XOrder orders[]; - int ordersCount = GetDealsHistory( - deal, - orders); - if (!ordersCount) - { - return result; - } - - // - for (int i = 0; i < ordersCount; i++) - { - // - XOrder iOrder = orders[i]; - - // - if (IsValid(iOrder.comment)) - { - // - ENUM_TIMEFRAMES iPeriod = ExtractPeriod(iOrder.comment); - if (IsValid(iPeriod)) - { - result = iPeriod; - break; - } - } - } - - // - return result; - } - - // - double GetMaxAllowedEquity() - { - // - double equity = mAccount.GetEquity(); - double balance = mAccount.GetBalance(); - - // - double balanceForFactor = MathAbs(equity - balance); - if (balanceForFactor <= 0) - { - balanceForFactor = balance; - } - else - { - balanceForFactor = equity; - } - - // - double result = balanceForFactor * mMaxAllowedDrawdownFactor; - - // - return result; - } - - // - // Private ... -private: - // - // Props ... - - // - int mSlippage; // Slippage ... - ulong mMagicNumber; // Magic Number (Unique Identifier) ... - - // - double mMaxAllowedSpread; // Max Allowed Spred for Opening Trades - int mMaxAllowedPositions; // Max Allowed Same Positions - double mMaxAllowedDrawdownFactor; // Max Allowed Drawdown Factor - - // - XSCTradeBase *mTrader; // Base CTrade Manipulated Instance ... - - // - CDealInfo mDealInfo; // Deals Info ... - COrderInfo mOrderInfo; // Order Info ... - CPositionInfo mPositionInfo; // Positions Info - CHistoryOrderInfo mHistoryOrderInfo; // History Orders Info ... - - // - // Position Info Collector ... - - // - // Tools ... - - // - // OnTrade Event Handlers Section ... - - // - // Props ... - - // - int mDaysForRead; // Reading Dates for Trade History Checker ... - datetime mEndDate; // End Date for Trade history Checking ... - datetime mStartDate; // Start Date for Trade history Checking ... ... - int mOrdersCount; // Number of Active orders ... - int mPositionsCount; // Number of Open positions ... - int mDealsCount; // Number of Deals in the Trade History Checking ... - int mHistoryOrdersCount; // Number of Orders in the Trade History Checking ... - bool mScanStarted; // a Flag of counter relevance ... - - // - // Event Listeners ... - - // - // Deals Changed Event Handlers ... - TOnDealsChanged mDealsChangedEventHandlers[]; - - // - // Orders Changed Event Handlers ... - TOnOrdersChanged mOrdersChangedEventHandlers[]; - - // - // Positions Changed Event Handlers ... - TOnPositionsChanged mPositionsChangedEventHandlers[]; - - // - // Trade State Changed Event Handlers ... - TOnTradeStateChanged mTradeStateChangedEventHandlers[]; - - // - TOnModify mOnModifyEventHandlers[]; - TOnForceClose mOnForceCloseEventHandlers[]; - TOnPartialClose mOnPartialCloseEventHandlers[]; - - // - // TPSL ... - TOnStopLoss mStopLossEventHandlers[]; - TOnTakeProfit mTakeProfitEventHandlers[]; - - // - // Reset On Trade Scanner Context ... - void ResetOnTradeContext() - { - // - mEndDate = TimeCurrent(); - mStartDate = mEndDate - (mDaysForRead * PeriodSeconds(PERIOD_D1)); - } - - // - // Initial Context Of Trade Scanner ... - void InitOnTradeContext() - { - // - ResetLastError(); - - // - mOrdersCount = OrdersTotal(); - mPositionsCount = PositionsTotal(); - - // - // load history ... - bool selected = HistorySelect(mStartDate, mEndDate); - if (!selected) - { - return; - } - - // - // get the current value ... - mDealsCount = HistoryDealsTotal(); - mHistoryOrdersCount = HistoryOrdersTotal(); - - // - mScanStarted = true; - } - - // - // Check Statrt Date In Trade History ... - void CheckStartDateInTradeHistory() - { - // - // initial interval, if we were to start working right now .. - datetime currStart = TimeCurrent() - (mDaysForRead * PeriodSeconds(PERIOD_D1)); - - // - // make sure that the start limit of the trade history has not gone - // more than 1 day over the intended date ... - if (currStart - mStartDate > PeriodSeconds(PERIOD_D1)) - { - // - // correct the start date of history to be loaded in the cache ... - mStartDate = currStart; - - // - // now reload the trade history for the updated interval ... - HistorySelect(mStartDate, mEndDate); - - // - // correct the deal and order counters in history for further comparison - mHistoryOrdersCount = HistoryOrdersTotal(); - mDealsCount = HistoryDealsTotal(); - } - } - - // - // Process On Trade Context ... - void ProcessOnTradeContext( - XOnTradeHandlerState &result // Hold's Result - ) - { - // - mEndDate = TimeCurrent(); - - // - ResetLastError(); - - // - // download trading history from the specified interval to the program cache ... - bool selected = HistorySelect(mStartDate, mEndDate); - if (!selected) - { - return; - } - - // - // get the current values ... - int currOrders = OrdersTotal(); - int currPositions = PositionsTotal(); - int currDeals = HistoryDealsTotal(); - int currHistoryOrders = HistoryOrdersTotal(); - - // - // Orders ... - // check if the number of active orders has been changed ... - if (currOrders != mOrdersCount) - { - // - // number of active orders has been changed ... - result.hasNewOrder = true; - result.newOrders = currOrders - mOrdersCount; - - // - // update the value ... - mOrdersCount = currOrders; - } - - // - // Positions ... - // changes in the number of open positions ... - if (currPositions != mPositionsCount) - { - // - // number of open positions has been changed ... - result.hasNewPosition = true; - result.newPositions = currPositions - mPositionsCount; - - // - // update the value ... - mPositionsCount = currPositions; - } - - // - // Deals ... - // changes in the number of deals in the trade history cache ... - if (currDeals != mDealsCount) - { - // - // number of deals in the trade history cache has been changed ... - result.hasNewDeal = true; - result.newDeals = currDeals - mDealsCount; - - // - // update the value ... - mDealsCount = currDeals; - } - - // - // History Orders ... - // changes in the number of history orders in the trade history cache ... - if (currHistoryOrders != mHistoryOrdersCount) - { - // - // number of history orders in the trade history cache has been changed ... - result.hasNewHistoryOrder = true; - result.newHistoryOrders = currHistoryOrders - mHistoryOrdersCount; - - // - // update the value ... - mHistoryOrdersCount = currHistoryOrders; - } - - // - // checking if it is necessary to change the limits of the trade history to be requested in cache ... - CheckStartDateInTradeHistory(); - } -}; - -// \ No newline at end of file diff --git a/Documents/Pack/V1.0/Source/Experts/x-saherelm.x121.ea.mq5 b/Documents/Pack/V1.0/Source/Experts/x-saherelm.x121.ea.mq5 deleted file mode 100644 index 074bdf85..00000000 --- a/Documents/Pack/V1.0/Source/Experts/x-saherelm.x121.ea.mq5 +++ /dev/null @@ -1,652 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center X121EA MQL5 Expert Advisor -// ------------------------------------------------- -// Name: X121EA -// Description: an Exper Advisor which used RSI and MA -// to Analyse Market ... -// -// Maintainer: -// ------------ -// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) -// -//////////////////////////////////////////////////////x -// -// Global Properties ... -#property copyright "Copyright 2023, SaherElm IT Center" -#property link "https://saherelm.ir" -#property version "1.00" -#property description "SaherElm X121EA" -#property strict - -// -// Imports ... -#include "../Helpers/x-saherelm.xct.helper.mq5" -#include "../Helpers/x-saherelm.xcc.helper.mq5" -#include "../Classes/x-saherelm.x121.setup.xea.mq5" - -// -#define ShortName "X121EA" - -// -// Inputs ... - -// -// Common ... -input group "Common"; -input long x121EAMagicNumber = 78692110; // Magic Number -input int x121EASlippage = 10; // Slippgae - -// -// Symbols ... -input group "Symbol(s)"; -input string x121EASymbols = "EURUSDb,USDCHFb,EURCHFb,USDJPYb,EURJPYb,GBPUSDb"; // Symbols -input bool x121EAUseAllSymbols = false; // Use All Available Symbols -input bool x121EAUseAllWatchListSymbols = false; // Use All Watch List Symbols - -// -// Signals ... -input group "Signals"; -input bool x121EAAllowLong = true; // Allow Long Trades -input bool x121EAAllowShort = true; // Allow Short Trades -input int x121EAStartSignallingHoure = 3; // Start Signalling at Specific Time -input int x121EAEndSignallingHoure = 22; // End Signalling at Specific Time -input int x121EACloseOnSpecificTime = -1; // Close All Trades in Specific Time -input int x121EADelayBetweenTwoSignal = 10; // Delay Between two Same Signals -input int x121EAReuiredSignalVerifications = 4; // Required Verifications for Signals -input bool x121EAExecuteSignalsOnBreakout = false; // Execute Signals On Breakouts -input bool x121EAGetVerificationFromOtherTimeFrames = true; // Get Verifications from Other Time Frames - -// -// Risk Management ... -input group "Risk Management"; -input double x121EAVolume = 0.01; // Static Volume -input double x121EATPPoint = 1000; // TP Point -input double x121EASLPoint = 1000; // SL Point -input bool x121EAIgnoreSL = false; // Ignore Calculated SL -input bool x121EAIgnoreTP = false; // Ignore Calculated TP -input bool x121EACloseOnOpposit = false; // Close all Positions on Opposit -input int x121EAMaxAllowedTrades = 2; // Max Allowed Positions Per Symbol -input bool x121EAUseMaxAllowedPerDirection = true; // Use Max Allowed Positions Per Direction -input int x121EAMinFreeMargingForOpenTrades = 900; // Min Margin For Opening Trades -input bool x121EAIncreaseNextSignalsVolume = true; // Increase Next Signals Volume -input double x121EAIncreaseNextSignalsVolumeMultiplier = 1; // Increase Next Signals Volume Multiplier -input bool x121EAAcceptNextDirectionalSignalsWhenFirstInProfit = true; // Accept Same Symbol/Type Signal when Last in Profit - -// -input group "Trailling"; -input bool x121EAAllowTrailStop = true; // Enable Trailling Stop Losses -input bool x121EADisableTrailingWhenOpposit = true; // Disable Trailling When has Opposite In Drawdown -input double x121EAFirstTrailDistance = 100; // Start Trailling Distance -input double x121EAFirstTrailPoint = 60; // First Stop Trail -input double x121EANextTrailDistance = 50; // Next Trailling Distance -input double x121EANextTrailPoint = 25; // Next Trailling Step - -// -input group "Supporting"; -input bool x121EAAllowSupport = false; // Allow Support Signals -input bool x121EASupportOnlyForces = false; // Support Only Force Signals -double x121EASupportDistance = 0; // Supporting Distance -input int x121EAMaxNumberOfSupports = 0; // Max Number of Support Signals -input double x121EASupportVolumeMultiplier = 0; // Support Signals Volume Multiplier -input double x121EAMaxAllowedSupportVolume = 0; // Max Allowed Support Signals Volume - -// -input group "Grid"; -input bool x121EAAllowGrid = false; // Allow Grid Signals -input bool x121EAGridOnlyForces = false; // Grid Only Force Signals -input int x121EAMaxNumberOfGrids = 0; // Max Number of Grid Signals -input double x121EAGridDistance = 0; // Grid Distance -input double x121EAGridVolumeMultiplier = 0; // Grid Volume Multiplier -input double x121EAMaxAllowedGridVolume = 0; // Max Allowed Grid Signals Volume - -// -input group "Recovery"; -input bool x121EAAllowRecovery = false; // Allow Recovery Signals -input bool x121EARecoverOnlyForces = false; // Recover Only Force Signals -input int x121EAMaxNumberOfRecoveries = 0; // Max Number of Recovery Signals -input double x121EARecoveryDistance = 0; // Recovery Distance -input double x121EARecoveryVolumeMultiplier = 0; // Recovery Volume Multiplier -input double x121EAMaxAllowedRecoveryVolume = 0; // Max Allowed Recovery Signals Volume - -// -input group "Hedging"; -input int x121EARestingAfterHedge = 1000; // Resting Seconds After Hedge -input double x121EAMinRequiredProfitPerTrade = 0.3; // Minimum Required Profit for Hedging -input double x121EAMinRequiredProfitPerVolumeFactor = 0.01; // Minimum Required Profit for Hedging Per Volume - -// -// Alert ... -input group "Alerts"; -input bool x121EAEnableAlerts = true; // Enable Alerts -input bool x121EALogAlerts = true; // Log Alerts -input bool x121EAMailAlerts = false; // Mail Alerts -input bool x121EAPushAlerts = false; // Push Alerts -input bool x121EATerminalAlerts = false; // Terminal Alerts - -// -// Definitions ... - -// -// Local Variables ... - -// -string x121EAUsedSymbols[]; -XSCX121SetupEA *x121EA; - -// -XSCXCTHelper *x121EACTHelper; -XSCXCCHelper *x121EACCHelper; - -// -// Event Handlers ... - -// -// Initialization ... -int OnInit() -{ - // - drawPrefix = ShortName; - - // - if (!InitialEA()) - { - return INIT_PARAMETERS_INCORRECT; - } - - // - // 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 - - // - // De Initialize XSampleEA Providers ... - delete x121EA; - - // - delete x121EACTHelper; - delete x121EACCHelper; -} - -// -// On Tick Handler ... -void OnTick() -{ - // - x121EA.OnTick(); - - // - X121ReportState(); -} - -// -// Custom Functions ... - -// -bool InitialEA() -{ - // - bool result = false; - - // - // Bar Timer ... - XCTInputs ctInputs; - ctInputs.Default(); - x121EACTHelper = new XSCXCTHelper(); - result = x121EACTHelper.Init( - _Symbol, - _Period, - ctInputs // - ); - if (!result) - { - return result; - } - - // - // Bar Styles ... - XCCInputs ccInputs; - ccInputs.Default(); - x121EACCHelper = new XSCXCCHelper(); - result = x121EACCHelper.Init( - _Symbol, - _Period, - ccInputs // - ); - if (!result) - { - return result; - } - - // - // TesterHideIndicators(true); - - // - string inputSymbols[]; - int inputSymbolsCount = SplitContent( - inputSymbols, - x121EASymbols // - ); - - // - string allSymbols[]; - int allSymbolsCount = GetAllSymbols( - allSymbols // - ); - - // - string watchListSymbols[]; - int watchListSymbolsCount = GetAllSymbols( - watchListSymbols, - true // - ); - - // - Clean(x121EAUsedSymbols); - if (x121EAUseAllSymbols) - { - // - Copy( - allSymbols, - x121EAUsedSymbols // - ); - } - else if (x121EAUseAllWatchListSymbols) - { - // - Copy( - watchListSymbols, - x121EAUsedSymbols // - ); - } - else if (IsValidSize(inputSymbolsCount)) - { - // - Copy( - inputSymbols, - x121EAUsedSymbols // - ); - } - else - { - // - Add( - _Symbol, - x121EAUsedSymbols // - ); - } - int symbolsCount = ArraySize(x121EAUsedSymbols); - result = IsValidSize(symbolsCount); - if (!result) - { - return result; - } - - // - x121EA = new XSCX121SetupEA( - x121EASlippage, - x121EAMagicNumber // - ); - - // - // Configure EA Class Instance ... - - // - // Signals ... - x121EA.AllowLong(x121EAAllowLong); - x121EA.AllowShort(x121EAAllowShort); - x121EA.DelayBetweenTwoSignal(x121EADelayBetweenTwoSignal); - x121EA.ExecuteSignalsOnBreakout(x121EAExecuteSignalsOnBreakout); - x121EA.ReuiredSignalVerifications(x121EAReuiredSignalVerifications); - x121EA.GetVerificationFromOtherTimeFrames(x121EAGetVerificationFromOtherTimeFrames); - - // - // Risk Management ... - x121EA.Volume(x121EAVolume); - x121EA.TPPoint(x121EATPPoint); - x121EA.SLPoint(x121EASLPoint); - x121EA.IgnoreSL(x121EAIgnoreSL); - x121EA.IgnoreTP(x121EAIgnoreTP); - x121EA.MaxAllowedTrades(x121EAMaxAllowedTrades); - x121EA.IncreaseNextSignalsVolume(x121EAIncreaseNextSignalsVolume); - x121EA.UseMaxAllowedPerDirection(x121EAUseMaxAllowedPerDirection); - x121EA.MinFreeMargingForOpenTrades(x121EAMinFreeMargingForOpenTrades); - x121EA.IncreaseNextSignalsVolumeMultiplier(x121EAIncreaseNextSignalsVolumeMultiplier); - x121EA.AcceptNextDirectionalSignalsWhenFirstInProfit(x121EAAcceptNextDirectionalSignalsWhenFirstInProfit); - - // - // Protection ... - - // - // Signalling ... - x121EA.CloseOnOpposit(x121EACloseOnOpposit); - x121EA.EndSignallingHoure(x121EAEndSignallingHoure); - x121EA.CloseOnSpecificTime(x121EACloseOnSpecificTime); - x121EA.StartSignallingHoure(x121EAStartSignallingHoure); - - // - // Trailling ... - x121EA.AllowTrailStop(x121EAAllowTrailStop); - x121EA.NextTrailPoint(x121EANextTrailPoint); - x121EA.FirstTrailPoint(x121EAFirstTrailPoint); - x121EA.NextTrailDistance(x121EANextTrailDistance); - x121EA.FirstTrailDistance(x121EAFirstTrailDistance); - x121EA.DisableTrailingWhenOpposit(x121EADisableTrailingWhenOpposit); - - // - // Supporting ... - x121EA.AllowSupport(x121EAAllowSupport); - x121EA.SupportOnlyForces(x121EASupportOnlyForces); - x121EA.SupportDistance(x121EASupportDistance); - x121EA.MaxNumberOfSupports(x121EAMaxNumberOfSupports); - x121EA.SupportVolumeMultiplier(x121EASupportVolumeMultiplier); - x121EA.MaxAllowedSupportVolume(x121EAMaxAllowedSupportVolume); - - // - // Grid ... - x121EA.AllowGrid(x121EAAllowGrid); - x121EA.GridOnlyForces(x121EAGridOnlyForces); - x121EA.GridDistance(x121EAGridDistance); - x121EA.MaxNumberOfGrids(x121EAMaxNumberOfGrids); - x121EA.GridVolumeMultiplier(x121EAGridVolumeMultiplier); - x121EA.MaxAllowedGridVolume(x121EAMaxAllowedGridVolume); - - // - // Recovery ... - x121EA.AllowRecovery(x121EAAllowRecovery); - x121EA.RecoverOnlyForces(x121EARecoverOnlyForces); - x121EA.RecoveryDistance(x121EARecoveryDistance); - x121EA.MaxNumberOfRecoveries(x121EAMaxNumberOfRecoveries); - x121EA.RecoveryVolumeMultiplier(x121EARecoveryVolumeMultiplier); - x121EA.MaxAllowedRecoveryVolume(x121EAMaxAllowedRecoveryVolume); - - // - // Hedging ... - x121EA.RestingAfterHedge(x121EARestingAfterHedge); - x121EA.MinProfitPerTrade(x121EAMinRequiredProfitPerTrade); - x121EA.MinProfitPerVolumeFactor(x121EAMinRequiredProfitPerVolumeFactor); - - // - // Alert ... - x121EA.SetAlertPrefix(ShortName); - x121EA.SetAlertEnableAlerts(x121EAEnableAlerts); - x121EA.SetAlertLogAlerts(x121EALogAlerts); - x121EA.SetAlertMailAlerts(x121EAMailAlerts); - x121EA.SetAlertPushAlerts(x121EAPushAlerts); - x121EA.SetAlertTerminalAlerts(x121EATerminalAlerts); - - // - // Configure Indicators ... - X121SetupInputs setupInputsDefault; - setupInputsDefault.Default(); - X121PreConfigureStyles(setupInputsDefault); - - // - // Prepare Providers and Add them into mX121EA class ... - for (int i = 0; i < symbolsCount; i++) - { - // - // Requirements ... - string iSymbol = x121EAUsedSymbols[i]; - ENUM_TIMEFRAMES iHostPeriod = _Period; - - // - XSCX121SetupCycles *iSetupCycle; - iSetupCycle = new XSCX121SetupCycles(); - result = iSetupCycle.Init( - setupInputsDefault, - iSymbol, - iHostPeriod // - ); - if (!result) - { - break; - } - - // - result = x121EA.AddSetup(iSetupCycle); - if (!result) - { - break; - } - } - - // - return result; -} - -// -void X121PreConfigureStyles(X121SetupInputs &inputs) -{ - // - // XHTD ... - inputs.htdInputs.show = false; - - // - // XATSL ... - inputs.atslInputs.show = false; - - // - // XSLN ... - inputs.slnInputs.show = false; - - // - // XDMNT ... - inputs.dmntInputs.showBull = false; - inputs.dmntInputs.showBear = false; - - // - // XSTR ... - inputs.strInputs.showTrends = false; - inputs.strInputs.fillTrends = false; - - // - // XPV ... - inputs.pvInputs.showPeaksAndVales = false; - inputs.pvInputs.showLevels = false; - inputs.pvInputs.showConsolidations = false; - inputs.pvInputs.showFibo1Levels = false; - inputs.pvInputs.showFibo2Levels = false; - inputs.pvInputs.showFibo3Levels = false; - inputs.pvInputs.showFibo4Levels = false; - inputs.pvInputs.showFibo5Levels = false; - - // - // XMC ... - inputs.mcInputs.showSar = false; - inputs.mcInputs.showFastMa = false; - inputs.mcInputs.showSlowMa = false; - inputs.mcInputs.showVerifierMa = false; - - // - // XHK ... - inputs.hkInputs.drawHikenAshi = false; - inputs.hkInputs.drawSmoothedHikenAshi = false; - - // - // XCHE ... - inputs.cheInputs.showLongExit1Line = false; - inputs.cheInputs.showShortExit1Line = false; - inputs.cheInputs.showLongExit2Line = false; - inputs.cheInputs.showShortExit2Line = false; - - // - // XICH ... - inputs.ichInputs.showTenkanSen = false; - inputs.ichInputs.showKijunSen = false; - inputs.ichInputs.showKijunSenPlus = false; - inputs.ichInputs.showKijunSenNegative = false; - inputs.ichInputs.showChikouSpan = false; - inputs.ichInputs.showSenkouSpanA = false; - inputs.ichInputs.showSenkouSpanB = false; - inputs.ichInputs.showKumo = false; - - // - // XMRB ... - inputs.mrbInputs.showFastMa = false; - inputs.mrbInputs.showSlowMa = false; - inputs.mrbInputs.showRibbon = false; - - // - // XASCT ... - inputs.asctInputs.showLongs = false; - inputs.asctInputs.showShorts = false; - - // - // XSSLC ... - inputs.sslcInputs.showUp = false; - inputs.sslcInputs.showDown = false; - - // - // XHULL ... - inputs.hullInputs.showUpZone = false; - inputs.hullInputs.showDownZone = false; -} - -// -void X121ReportState() -{ - // - string comment = NULL; - - // - comment = - ShortName + "\n" + - "------------" + "\n" + - "Trading Symbols: " + ToString(ArraySize(x121EAUsedSymbols)) + "\n" + "\n"; - - // - // Detect What we Want to Show as Comment ... - // bool isInForceState = x121EA.ForceState(); - double bullishScore = 0; // x121EA.GetBullishScore(); - double bearishScore = 0; // x121EA.GetBearishScore(); - double drawDownPercent = x121EA.GetDrawdownPercent(); - - // - comment += - // - (bullishScore > 0 || bearishScore > 0 - ? "Scores:" + "\n" + - "------------" + "\n" + - "Bullish: " + ToString(bullishScore) + "\n" + - "Bearish: " + ToString(bearishScore) + "\n" + - "------------" + "\n" - : "") + - "Drawdown: " + ToString(drawDownPercent) + "%" + "\n" + - // "------------" + "\n" + - // "Force State: " + ToString(isInForceState) + "\n" + - // - "" - // - ; - - // - XPosition positions[]; - int positionsCount = x121EA.mTrader.GetPositions( - positions // - ); - if (IsValidSize(positionsCount)) - { - // - int longs = 0; - double longVolumes = 0; - double longProfits = 0; - - // - int shorts = 0; - double shortVolumes = 0; - double shortProfits = 0; - - // - // Retrieve Required Informations of Positions ... - CountPositions( - positions, - longs, - longProfits, - longVolumes, - shorts, - shortProfits, - shortVolumes // - ); - - // - comment += - // - "------------" + "\n" + - "Positions: " + "\n" + - "------------" + "\n" + - (longs <= 0 - ? "" - : "\n" + "Longs:" + "\n" + - "------------" + "\n" + - "Count: " + ToString(longs) + "\n" + - "Profits: " + ToString(longProfits) + "\n" + - "" - // - ) + - // - (shorts <= 0 - ? "" - : "\n" + "Shorts:" + "\n" + - "------------" + "\n" + - "Count: " + ToString(shorts) + "\n" + - "Profits: " + ToString(shortProfits) + "\n" + - "" - // - ) + - // - "" - // - ; - } - - // - if (positionsCount > 1 && x121EAMinRequiredProfitPerTrade > 0 && x121EAMinRequiredProfitPerVolumeFactor > 0) - { - // - double profit = SpecifiedCalculatePositionsProfit( - positions // - ); - double requiredProfitForHedge = SpecifiedCalculateRequiredProfitForHedge( - positions, - x121EAMinRequiredProfitPerTrade, - x121EAMinRequiredProfitPerVolumeFactor // - ); - - // - comment += - // - "\n" + "Hedging: " + "\n" + - "------------" + "\n" + - "Profits: " + ToString(profit) + "\n" + - "RequiredProft: " + ToString(requiredProfitForHedge) + "\n" + - // - "" - // - ; - } - - // - if (IsValid(comment)) - { - Comment(comment); - } -} - -// diff --git a/Documents/Pack/V1.0/Source/Helpers/x-saherelm.xadxtd.helper.mq5 b/Documents/Pack/V1.0/Source/Helpers/x-saherelm.xadxtd.helper.mq5 deleted file mode 100644 index 206b20ed..00000000 --- a/Documents/Pack/V1.0/Source/Helpers/x-saherelm.xadxtd.helper.mq5 +++ /dev/null @@ -1,704 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Class Library -// ---------------------------------------------- -// Name: XADXTD -// Description: provides Indicator implementation -// 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.xhelper.class.mq5" - -// -// Indicator Buffers ... -enum ENUM_XADXTD_BUFFERS -{ - XADXTD_STRENGTH_LINE = 0, // Strenght Buffer ... - XADXTD_BULL_LINE = 1, // Bull Buffer ... - XADXTD_BEAR_LINE = 2, // Bear Buffer ... -}; - -// -// XADXTD Indicator Inputs ... -struct XADXTDInputs -{ - // - // Props ... - int length; // Length - - // - // Constructor ... - XADXTDInputs() - { - Clean(); - } - - // - // Tools ... - - // - // Cleanup ... - void Clean() - { - length = 0; - } - - // - // Default ... - void Default() - { - length = 21; - } - - // - // Validate ... - bool IsValid() - { - // - bool result = false; - - // - result = - // - length > 0 - // - ; - - // - return result; - } - - // - // Retrieve Max Length ... - int Max() - { - // - int result = 0; - - // - int values[1] = { - length // - }; - - // - result = GetMax(values); - - // - return result; - } -}; - -// -// Define Conditions ... -struct XADXTDConditions -{ - // - // Common ... - string symbol; - ENUM_TIMEFRAMES period; - datetime time; - - // - // Buffers ... - double strength[]; - double bullp[]; - double bearp[]; - - // - // Conditions ... - - // - bool isStrong; - bool isBullish; - bool isBearish; - bool isSwitchedToBullish; - bool isSwitchedToBearish; - bool isStrongSwitchedToBullish; - bool isStrongSwitchedToBearish; - - // - void Clean() - { - // - Clean(strength); - Clean(bullp); - Clean(bearp); - - // - ArraySetAsSeries(strength, true); - ArraySetAsSeries(bullp, true); - ArraySetAsSeries(bearp, true); - - // - isStrong = false; - isBullish = false; - isBearish = false; - isSwitchedToBullish = false; - isSwitchedToBearish = false; - isStrongSwitchedToBullish = false; - isStrongSwitchedToBearish = false; - } - - // - void GenerateScore( - double &bullishScore, - double &bearishScore // - ) - { - // - bullishScore = 0; - bearishScore = 0; - - // - if (isBullish) - { - // - bullishScore++; - if (isStrong) - { - bullishScore++; - } - } - if (isBearish) - { - bearishScore++; - if (isStrong) - { - bearishScore++; - } - } - if (isSwitchedToBullish) - { - bullishScore++; - if (isStrong) - { - bullishScore++; - } - } - if (isSwitchedToBearish) - { - bearishScore++; - if (isStrong) - { - bearishScore++; - } - } - if (isStrongSwitchedToBullish) - { - bullishScore++; - } - if (isStrongSwitchedToBearish) - { - bearishScore++; - } - } - - // - 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 = - // - ToString("isStrong", isStrong, ignoreFalseConditions, separator) + - ToString("isBullish", isBullish, ignoreFalseConditions, separator) + - ToString("isBearish", isBearish, ignoreFalseConditions, separator) + - ToString("isSwitchedToBullish", isSwitchedToBullish, ignoreFalseConditions, separator) + - ToString("isSwitchedToBearish", isSwitchedToBearish, ignoreFalseConditions, separator) + - ToString("isStrongSwitchedToBullish", isStrongSwitchedToBullish, ignoreFalseConditions, separator) + - ToString("isStrongSwitchedToBearish", isStrongSwitchedToBearish, ignoreFalseConditions, separator) + - "" - // - ; - - // - result = - // - "[" + GetTag() + "]" + separator + - (onlyConditions - ? "" - : commonStr) + - (!includeScores - ? "" - : scoresStr) + - " " + separator + - (onlyCommons - ? "" - : conditionsStr) + - "" - // - ; - - // - return result; - } - - // - string GetTag() - { - return "XADXTD"; - } -}; - -// -// Class ... -class XSCXADXTDHelper : public XSCBaseHelper -{ - // - // Public ... -public: - // - // Props ... - - // - // Constructors ... - XSCXADXTDHelper() : XSCBaseHelper(_Symbol, _Period) - { - } - - // - // Deconstructor ... - ~XSCXADXTDHelper() {} - - // - // Tools ... - bool Init( - string symbol, // Trading Symbol - ENUM_TIMEFRAMES period, // Trading Period - XADXTDInputs &inputs // Inputs - ) - { - // - bool result = false; - - // - mSymbol = symbol; - mPeriod = period; - - // - result = inputs.IsValid(); - if (!result) - { - return result; - } - - // - mInputs = inputs; - - // - ArraySetAsSeries(bullpBuffer, true); - ArraySetAsSeries(bearpBuffer, true); - ArraySetAsSeries(strengthBuffer, true); - - // - mHandler = iCustom( - mSymbol, - mPeriod, - "x-saherelm.xadxtd", - // - // Inputs ... - mInputs.length // Length - // - ); - result = mHandler != INVALID_HANDLE; - if (!result) - { - return result; - } - - // - return result; - } - - // - // Inputs ... - - // - XADXTDInputs GetInputs() - { - return mInputs; - } - - // - bool SetInputs( - XADXTDInputs &inputs // Configs - ) - { - // - return Init( - mSymbol, - mPeriod, - inputs - // - ); - } - - // - // Buffers ... - - // - // Strength ... - - // - double GetStrength( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - int count = ArraySize(strengthBuffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return strengthBuffer[barIndex]; - } - - // - // Copy Required Items ... - int CopyStrength( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - strengthBuffer, - buffer, - forceClean - // - ); - } - - // - // BullP ... - - // - double GetBullP( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - int count = ArraySize(bullpBuffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return bullpBuffer[barIndex]; - } - - // - // Copy Required Items ... - int CopyBullP( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - bullpBuffer, - buffer, - forceClean - // - ); - } - - // - // BearP ... - - // - double GetBearP( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - int count = ArraySize(bearpBuffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return bearpBuffer[barIndex]; - } - - // - // Copy Required Items ... - int CopyBearP( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - bearpBuffer, - buffer, - forceClean - // - ); - } - - // - bool GetConditions( - XADXTDConditions &conditions, // - int barIndex = 0, // - int loopback = 3 // - ) - { - // - bool result = true; - - // - if (loopback < 3) - { - loopback = 3; - } - - // - conditions.Clean(); - - // - conditions.symbol = mSymbol; - conditions.period = mPeriod; - conditions.time = TimeCurrent(); - - // - int zIndex = barIndex; - int cIndex = zIndex + 1; - int pIndex = cIndex + 1; - int ppIndex = pIndex + 1; - - // - // Buffers ... - - // - CopyStrength( - zIndex, - loopback, - conditions.strength // - ); - - // - CopyBullP( - zIndex, - loopback, - conditions.bullp // - ); - - // - CopyBearP( - zIndex, - loopback, - conditions.bearp // - ); - - // - // Calculate Conditions ... - - // - bool isStrong = conditions.strength[cIndex] >= 20; - - // - bool isBullish = conditions.bullp[cIndex] > conditions.bearp[cIndex]; - bool isBearish = conditions.bearp[cIndex] > conditions.bullp[cIndex]; - - // - bool isBullishPrev = conditions.bullp[pIndex] > conditions.bearp[pIndex]; - bool isBearishPrev = conditions.bearp[pIndex] > conditions.bullp[pIndex]; - - // - bool isSwitchedToBullish = isBullish && - !isBullishPrev; - bool isSwitchedToBearish = isBearish && - !isBearishPrev; - - // - bool isStrongSwitchedToBullish = isStrong && - isSwitchedToBullish; - bool isStrongSwitchedToBearish = isStrong && - isSwitchedToBearish; - - // - conditions.isStrong = isStrong; - conditions.isBullish = isBullish; - conditions.isBearish = isBearish; - conditions.isSwitchedToBullish = isSwitchedToBullish; - conditions.isSwitchedToBearish = isSwitchedToBearish; - conditions.isStrongSwitchedToBullish = isStrongSwitchedToBullish; - conditions.isStrongSwitchedToBearish = isStrongSwitchedToBearish; - - // - return result; - } - - // - // Protected ... -protected: - // - // Private ... -private: - // - // Props ... - XADXTDInputs mInputs; // Inputs ... - - // - // Buffers ... - double bullpBuffer[]; - double bearpBuffer[]; - double strengthBuffer[]; - - // - // Tools ... - - // - // Calculate Values Until Now ... - void Calculate() - { - // - int totalBars = CountBars(); - if (totalBars > 1000) { - totalBars = 1000; - } - - // - // Strength Buffer ... - CopyBuffer( - mHandler, - XADXTD_STRENGTH_LINE, - 0, - totalBars, - strengthBuffer - // - ); - - // - // BullP Buffer ... - CopyBuffer( - mHandler, - XADXTD_BULL_LINE, - 0, - totalBars, - bullpBuffer - // - ); - - // - // BearP Buffer ... - CopyBuffer( - mHandler, - XADXTD_BEAR_LINE, - 0, - totalBars, - bearpBuffer - // - ); - } -}; - -// \ No newline at end of file diff --git a/Documents/Pack/V1.0/Source/Helpers/x-saherelm.xama.helper.mq5 b/Documents/Pack/V1.0/Source/Helpers/x-saherelm.xama.helper.mq5 deleted file mode 100644 index a394f6cd..00000000 --- a/Documents/Pack/V1.0/Source/Helpers/x-saherelm.xama.helper.mq5 +++ /dev/null @@ -1,320 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Helper Class Library -// ---------------------------------------------- -// Name: XSCXAMAHelper -// 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.xhelper.class.mq5" - -// -// Definitions ... - -// -enum ENUM_XAMA_BUFFERS -{ - XAMA_MAIN_LINE = 0 -}; - -// -// Input Models ... -struct XAMAInputs -{ - // - // Props ... - // - // Market ... - int length; // Period - int fastEMA; // Fast EMA Period - int slowEMA; // Slow EMA Period - int maShift; // Shift - ENUM_APPLIED_PRICE appliedTo; // Applied To - // - // Presentation ... - bool showLine; // Show Line - - // - // Constructor(s) ... - XAMAInputs() - { - // - Clean(); - } - - // - // Tools ... - - // - // Clean ... - void Clean() - { - // - length = 0; - fastEMA = 0; - slowEMA = 0; - maShift = 0; - showLine = false; - appliedTo = PRICE_CLOSE; - } - - // - // Default ... - void Default() - { - // - length = 18; - fastEMA = 2; - slowEMA = 30; - maShift = 0; - showLine = true; - appliedTo = PRICE_CLOSE; - } - - // - // Validate ... - bool IsValid() - { - // - bool result = false; - - // - result = - // - length > 0 && - fastEMA > 0 && - slowEMA > 0 && - slowEMA > fastEMA - // - ; - - // - return result; - } - - // - // Retrieve MAx Length ... - int Max() - { - // - int result = 0; - - // - result = MathMax(length, length); - - // - return result; - } -}; - -// -// Class ... -class XSCXAMAHelper : public XSCBaseHelper -{ - // - // Public ... -public: - // - // Props ... - - // - // Constructors ... - XSCXAMAHelper() : XSCBaseHelper(_Symbol, _Period) - { - } - - // - // Deconstructor ... - ~XSCXAMAHelper() {} - - // - // Tools ... - bool Init( - string symbol, // Trading Symbol - ENUM_TIMEFRAMES period, // Trading Period - XAMAInputs &inputs // Inputs - ) - { - // - bool result = false; - - // - mSymbol = symbol; - mPeriod = period; - - // - result = inputs.IsValid(); - if (!result) - { - return result; - } - - // - mInputs = inputs; - - // - ArraySetAsSeries(mainBuffer, true); - mHandler = iCustom( - mSymbol, - mPeriod, - "x-saherelm.xama", - // - // Inputs ... - // - // Market ... - "", - mInputs.length, // Period - mInputs.fastEMA, // Fast EMA Period - mInputs.slowEMA, // Slow EMA Period - mInputs.maShift, // Shift - mInputs.appliedTo, // Applied To - // - // Presentation ... - "", - mInputs.showLine // Show Line - // - ); - result = mHandler != INVALID_HANDLE; - if (!result) - { - return result; - } - - // - return result; - } - - // - // Inputs ... - - // - XAMAInputs GetInputs() - { - return mInputs; - } - - // - bool SetInputs( - XAMAInputs &inputs // Configs - ) - { - // - return Init( - mSymbol, - mPeriod, - inputs - // - ); - } - - // - // Buffers ... - - // - double GetMain( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - int count = ArraySize(mainBuffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return mainBuffer[barIndex]; - } - - // - // Copy Required Items ... - int CopyMain( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - mainBuffer, - buffer, - forceClean - // - ); - } - - // - // Protected ... -protected: - // - // Private ... -private: - // - // Props ... - XAMAInputs mInputs; // Inputs ... - - // - // Buffers ... - double mainBuffer[]; - - // - // Tools ... - - // - // Calculate Values Until Now ... - void Calculate() - { - // - int totalBars = CountBars(); - if (totalBars > 1000) { - totalBars = 1000; - } - - // - // Main Buffer ... - CopyBuffer( - mHandler, - XAMA_MAIN_LINE, - 0, - totalBars, - mainBuffer - // - ); - } -}; - -// -// Tools ... \ No newline at end of file diff --git a/Documents/Pack/V1.0/Source/Helpers/x-saherelm.xasct.helper.mq5 b/Documents/Pack/V1.0/Source/Helpers/x-saherelm.xasct.helper.mq5 deleted file mode 100644 index 1352885c..00000000 --- a/Documents/Pack/V1.0/Source/Helpers/x-saherelm.xasct.helper.mq5 +++ /dev/null @@ -1,578 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Helper Class Library -// ---------------------------------------------- -// Name: XSCXASCTHelper -// 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.xhelper.class.mq5" - -// -// Definitions ... - -// -enum ENUM_XASCT_BUFFERS -{ - XASCT_LONG_LINE = 0, - XASCT_SHORT_LINE = 1 -}; - -// -// Input Models ... -struct XASCTInputs -{ - // - // Props ... - // - // Market ... - int risk; // Risk - // - // Presentation ... - bool showLongs; // Show Long Arrows - bool showShorts; // Show Short Arrows - uchar longArrowCode; // Long Arrow - uchar shortArrowCode; // Short Arrow - - // - // Constructor(s) ... - XASCTInputs() - { - // - Clean(); - } - - // - // Tools ... - - // - // Clean ... - void Clean() - { - // - risk = 0; - - // - showLongs = false; - showShorts = false; - longArrowCode = 0; - shortArrowCode = 0; - } - - // - // Default ... - void Default() - { - // - risk = 4; - - // - showLongs = true; - showShorts = true; - longArrowCode = 233; - shortArrowCode = 234; - } - - // - // Validate ... - bool IsValid() - { - // - bool result = false; - - // - result = - // - risk >= 1 - // - ; - - // - return result; - } - - // - // Retrieve MAx Length ... - int Max() - { - // - int result = 0; - - // - result = int(MathMax(3 + risk * 2, 4) + 1); - - // - return result; - } -}; - -// -// Define Conditions ... -struct XASCTConditions -{ - // - // Common ... - string symbol; - ENUM_TIMEFRAMES period; - datetime time; - - // - // Buffers ... - double longSignal[]; - double shortSignal[]; - - // - // Conditions ... - - // - bool isLongSignal; - bool isShortSignal; - - // - void Clean() - { - // - Clean(longSignal); - Clean(shortSignal); - - // - ArraySetAsSeries(longSignal, true); - ArraySetAsSeries(shortSignal, true); - - // - isLongSignal = false; - isShortSignal = false; - } - - // - void GenerateScore( - double &bullishScore, - double &bearishScore // - ) - { - // - bullishScore = 0; - bearishScore = 0; - - // - if (isLongSignal) - { - bullishScore++; - } - - // - if (isShortSignal) - { - bearishScore++; - } - } - - // - 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 = - // - ToString("isLongSignal", isLongSignal, ignoreFalseConditions, separator) + - ToString("isShortSignal", isShortSignal, ignoreFalseConditions, separator) + - "" - // - ; - - // - result = - // - "[" + GetTag() + "]" + separator + - (onlyConditions - ? "" - : commonStr) + - (!includeScores - ? "" - : scoresStr) + - " " + separator + - (onlyCommons - ? "" - : conditionsStr) + - "" - // - ; - - // - return result; - } - - // - string GetTag() - { - return "XASCT"; - } -}; - -// -// Class ... -class XSCXASCTHelper : public XSCBaseHelper -{ - // - // Public ... -public: - // - // Props ... - - // - // Constructors ... - XSCXASCTHelper() : XSCBaseHelper(_Symbol, _Period) - { - } - - // - // Deconstructor ... - ~XSCXASCTHelper() {} - - // - // Tools ... - bool Init( - string symbol, // Trading Symbol - ENUM_TIMEFRAMES period, // Trading Period - XASCTInputs &inputs // Inputs - ) - { - // - bool result = false; - - // - mSymbol = symbol; - mPeriod = period; - - // - result = inputs.IsValid(); - if (!result) - { - return result; - } - - // - mInputs = inputs; - - // - ArraySetAsSeries(longsBuffer, true); - ArraySetAsSeries(shortsBuffer, true); - mHandler = iCustom( - mSymbol, - mPeriod, - "x-saherelm.xasct", - // - // Inputs ... - // - // Market ... - "", - mInputs.risk, // Risk - // - // Presentation ... - "", - mInputs.showLongs, // Show Long Arrows - mInputs.showShorts, // Show Short Arrows - mInputs.longArrowCode, // Long Arrow - mInputs.shortArrowCode // Short Arrow - // - ); - result = mHandler != INVALID_HANDLE; - if (!result) - { - return result; - } - - // - return result; - } - - // - // Inputs ... - - // - XASCTInputs GetInputs() - { - return mInputs; - } - - // - bool SetInputs( - XASCTInputs &inputs // Configs - ) - { - // - return Init( - mSymbol, - mPeriod, - inputs - // - ); - } - - // - // Buffers ... - - // - double GetLong( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - int count = ArraySize(longsBuffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return longsBuffer[barIndex]; - } - - // - // Copy Required Items ... - int CopyLong( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - longsBuffer, - buffer, - forceClean - // - ); - } - - // - double GetShort( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - int count = ArraySize(shortsBuffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return shortsBuffer[barIndex]; - } - - // - // Copy Required Items ... - int CopyShort( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - shortsBuffer, - buffer, - forceClean - // - ); - } - - // - bool GetConditions( - XASCTConditions &conditions, // - int barIndex = 0, // - int loopback = 3 // - ) - { - // - bool result = true; - - // - if (loopback < 3) - { - loopback = 3; - } - - // - conditions.Clean(); - - // - conditions.symbol = mSymbol; - conditions.period = mPeriod; - conditions.time = TimeCurrent(); - - // - int zIndex = barIndex; - int cIndex = zIndex + 1; - int pIndex = cIndex + 1; - int ppIndex = pIndex + 1; - - // - // Buffers ... - - // - CopyLong( - zIndex, - loopback, - conditions.longSignal // - ); - CopyShort( - zIndex, - loopback, - conditions.shortSignal // - ); - - // - // Conditions ... - - // - bool isLongSignal = NotEmptyZero(conditions.longSignal[cIndex]); - bool isShortSignal = NotEmptyZero(conditions.shortSignal[cIndex]); - - // - conditions.isLongSignal = isLongSignal; - conditions.isShortSignal = isShortSignal; - - // - return result; - } - - // - // Protected ... -protected: - // - // Private ... -private: - // - // Props ... - XASCTInputs mInputs; // Inputs ... - - // - // Buffers ... - double longsBuffer[]; - double shortsBuffer[]; - - // - // Tools ... - - // - // Calculate Values Until Now ... - void Calculate() - { - // - int totalBars = CountBars(); - if (totalBars > 1000) { - totalBars = 1000; - } - - // - // Longs Buffer ... - CopyBuffer( - mHandler, - XASCT_LONG_LINE, - 0, - totalBars, - longsBuffer - // - ); - - // - // Shorts Buffer ... - CopyBuffer( - mHandler, - XASCT_SHORT_LINE, - 0, - totalBars, - shortsBuffer - // - ); - } -}; - -// -// Tools ... \ No newline at end of file diff --git a/Documents/Pack/V1.0/Source/Helpers/x-saherelm.xatsl.helper.mq5 b/Documents/Pack/V1.0/Source/Helpers/x-saherelm.xatsl.helper.mq5 deleted file mode 100644 index 606b2646..00000000 --- a/Documents/Pack/V1.0/Source/Helpers/x-saherelm.xatsl.helper.mq5 +++ /dev/null @@ -1,552 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Helper Class Library -// ---------------------------------------------- -// Name: XSCXATSLHelper -// 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.xhelper.class.mq5" - -// -// Definitions ... - -// -enum ENUM_XATSL_BUFFERS -{ - XATSL_MAIN_LINE = 0, -}; - -// -// Input Models ... -struct XATSLInputs -{ - // - // Props ... - - // - // Market ... - int length; // Length - double coeff; // Coefficient - - // - // Presentation ... - bool show; // Show - - // - // Constructor(s) ... - XATSLInputs() - { - // - Clean(); - } - - // - // Tools ... - - // - // Clean ... - void Clean() - { - // - length = 0; - coeff = 0; - - // - show = false; - } - - // - // Default ... - void Default() - { - // - length = 14; - coeff = 2.0; - - // - show = true; - } - - // - // Validate ... - bool IsValid() - { - // - bool result = false; - - // - result = - // - length >= 2 && - coeff > 0 - // - ; - - // - return result; - } - - // - // Retrieve MAx Length ... - int Max() - { - // - int result = 0; - - // - result = MathMax(result, length); - - // - return result; - } -}; - -// -// Define Conditions ... -struct XATSLConditions -{ - // - // Common ... - string symbol; - ENUM_TIMEFRAMES period; - datetime time; - - // - // Buffers ... - double atsl[]; - - // - // Conditions ... - - // - bool isBullish; - bool isBearish; - - // - bool isSwitchedToBullish; - bool isSwitchedToBearish; - - // - void Clean() - { - // - Clean(atsl); - - // - ArraySetAsSeries(atsl, true); - - // - isBullish = false; - isBearish = false; - isSwitchedToBullish = false; - isSwitchedToBearish = false; - } - - // - void GenerateScore( - double &bullishScore, - double &bearishScore // - ) - { - // - bullishScore = 0; - bearishScore = 0; - - // - if (isBullish) - { - bullishScore++; - } - if (isSwitchedToBullish) - { - bullishScore++; - } - - if (isBearish) - { - bearishScore++; - } - if (isSwitchedToBearish) - { - bearishScore++; - } - } - - // - 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 = - // - ToString("isBullish", isBullish, ignoreFalseConditions, separator) + - ToString("isBearish", isBearish, ignoreFalseConditions, separator) + - ToString("isSwitchedToBullish", isSwitchedToBullish, ignoreFalseConditions, separator) + - ToString("isSwitchedToBearish", isSwitchedToBearish, ignoreFalseConditions, separator) + - "" - // - ; - - // - result = - // - "[" + GetTag() + "]" + separator + - (onlyConditions - ? "" - : commonStr) + - (!includeScores - ? "" - : scoresStr) + - " " + separator + - (onlyCommons - ? "" - : conditionsStr) + - "" - // - ; - - // - return result; - } - - // - string GetTag() - { - return "XATSL"; - } -}; - -// -// Class ... -class XSCXATSLHelper : public XSCBaseHelper -{ - // - // Public ... -public: - // - // Props ... - - // - // Constructors ... - XSCXATSLHelper() : XSCBaseHelper(_Symbol, _Period) - { - } - - // - // Deconstructor ... - ~XSCXATSLHelper() {} - - // - // Tools ... - bool Init( - string symbol, // Trading Symbol - ENUM_TIMEFRAMES period, // Trading Period - XATSLInputs &inputs // Inputs - ) - { - // - bool result = false; - - // - mSymbol = symbol; - mPeriod = period; - - // - result = inputs.IsValid(); - if (!result) - { - return result; - } - - // - mInputs = inputs; - - // - ArraySetAsSeries(atslBuffer, true); - mHandler = iCustom( - mSymbol, - mPeriod, - "x-saherelm.xatsl", - // - // Inputs ... - // - // Market ... - "", - mInputs.length, - mInputs.coeff, - // - // Presentation ... - "", - mInputs.show - // - ); - result = mHandler != INVALID_HANDLE; - if (!result) - { - return result; - } - - // - return result; - } - - // - // Inputs ... - - // - XATSLInputs GetInputs() - { - return mInputs; - } - - // - bool SetInputs( - XATSLInputs &inputs // Configs - ) - { - // - return Init( - mSymbol, - mPeriod, - inputs - // - ); - } - - // - // Buffers ... - - // - double GetATSL( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - int count = ArraySize(atslBuffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return atslBuffer[barIndex]; - } - - // - // Copy Required Items ... - int CopyATSL( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - atslBuffer, - buffer, - forceClean - // - ); - } - - // - bool GetConditions( - XATSLConditions &conditions, // - int barIndex = 0, // - int loopback = 3 // - ) - { - // - bool result = true; - - // - if (loopback < 3) - { - loopback = 3; - } - - // - conditions.Clean(); - - // - conditions.symbol = mSymbol; - conditions.period = mPeriod; - conditions.time = TimeCurrent(); - - // - int zIndex = barIndex; - int cIndex = zIndex + 1; - int pIndex = cIndex + 1; - int ppIndex = pIndex + 1; - - // - // Buffers ... - - // - CopyATSL( - zIndex, - loopback, - conditions.atsl // - ); - - // - // Conditions ... - - // - XOHCL cBar; - result = cBar.Init( - mSymbol, - mPeriod, - cIndex // - ); - if (!result) - { - return result; - } - - // - XOHCL pBar; - result = pBar.Init( - mSymbol, - mPeriod, - pIndex // - ); - if (!result) - { - return result; - } - - // - bool isBullish = conditions.atsl[cIndex] < cBar.close; - bool isBullishPrev = conditions.atsl[pIndex] < pBar.close; - - // - bool isBearish = conditions.atsl[cIndex] > cBar.close; - bool isBearishPrev = conditions.atsl[pIndex] > pBar.close; - - // - bool isSwitchedToBullish = isBullish && - !isBullishPrev; - bool isSwitchedToBearish = isBearish && - !isBearishPrev; - - // - conditions.isBullish = isBullish; - conditions.isBearish = isBearish; - conditions.isSwitchedToBullish = isSwitchedToBullish; - conditions.isSwitchedToBearish = isSwitchedToBearish; - - // - return result; - } - - // - // Protected ... -protected: - // - // Private ... -private: - // - // Props ... - XATSLInputs mInputs; // Inputs ... - - // - // Buffers ... - double atslBuffer[]; - - // - // Tools ... - - // - // Calculate Values Until Now ... - void Calculate() - { - // - int totalBars = CountBars(); - if (totalBars > 1000) - { - totalBars = 1000; - } - - // - // Longs Buffer ... - CopyBuffer( - mHandler, - XATSL_MAIN_LINE, - 0, - totalBars, - atslBuffer - // - ); - } -}; - -// \ No newline at end of file diff --git a/Documents/Pack/V1.0/Source/Helpers/x-saherelm.xcc.helper.mq5 b/Documents/Pack/V1.0/Source/Helpers/x-saherelm.xcc.helper.mq5 deleted file mode 100644 index 98bec867..00000000 --- a/Documents/Pack/V1.0/Source/Helpers/x-saherelm.xcc.helper.mq5 +++ /dev/null @@ -1,245 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Helper Class Library -// ---------------------------------------------- -// Name: XSCXCCHelper -// 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.xhelper.class.mq5" - -// -// Definitions ... - -// -// Input Models ... -struct XCCInputs -{ - // - // Props ... - - // - // Chart Style ... - ENUM_CHART_MODE mode; // Mode - color upColor; // Up Color - color downColor; // Down Color - color lineColor; // Line mode and Doji candlestick Color - color bearishColor; // Bullish Color - color bullishColor; // Bearish Color - color volumesColor; // Volumes Color - - // - // Presentation ... - bool showCandles; // Show Candles - - // - // Constructor(s) ... - XCCInputs() - { - // - Clean(); - } - - // - // Tools ... - - // - // Clean ... - void Clean() - { - // - mode = CHART_CANDLES; - - // - upColor = CLR_NONE; - downColor = CLR_NONE; - lineColor = CLR_NONE; - bearishColor = CLR_NONE; - bullishColor = CLR_NONE; - volumesColor = CLR_NONE; - - // - showCandles = false; - } - - // - // Default ... - void Default() - { - // - mode = CHART_CANDLES; - - // - upColor = clrLime; - downColor = clrRed; - lineColor = clrLime; - bearishColor = clrRed; - bullishColor = clrLime; - volumesColor = clrGreen; - // - showCandles = true; - } - - // - // Validate ... - bool IsValid() - { - // - bool result = false; - - // - result = - // - true - // - ; - - // - return result; - } - - // - // Retrieve MAx Length ... - int Max() - { - // - int result = 0; - - // - result = MathMax(0, 0); - - // - return result; - } -}; - -// -// Class ... -class XSCXCCHelper : public XSCBaseHelper -{ - // - // Public ... -public: - // - // Props ... - - // - // Constructors ... - XSCXCCHelper() : XSCBaseHelper(_Symbol, _Period) - { - } - - // - // Deconstructor ... - ~XSCXCCHelper() {} - - // - // Tools ... - bool Init( - string symbol, // Trading Symbol - ENUM_TIMEFRAMES period, // Trading Period - XCCInputs &inputs // Inputs - ) - { - // - bool result = false; - - // - mSymbol = symbol; - mPeriod = period; - - // - result = inputs.IsValid(); - if (!result) - { - return result; - } - - // - mInputs = inputs; - - // - mHandler = iCustom( - mSymbol, - mPeriod, - "x-saherelm.xcc", - // - // Inputs ... - // - // Chart Style ... - "", - mInputs.mode, // Mode - mInputs.upColor, // Up Color - mInputs.downColor, // Down Color - mInputs.lineColor, // Line mode and Doji candlestick Color - mInputs.bearishColor, // Bullish Color - mInputs.bullishColor, // Bearish Color - mInputs.volumesColor, // Volumes Color - // - // Presentation ... - "", - mInputs.showCandles // Show Candles - // - ); - result = mHandler != INVALID_HANDLE; - if (!result) - { - return result; - } - - // - return result; - } - - // - // Inputs ... - - // - XCCInputs GetInputs() - { - return mInputs; - } - - // - bool SetInputs( - XCCInputs &inputs // Configs - ) - { - // - return Init( - mSymbol, - mPeriod, - inputs - // - ); - } - - // - // Protected ... -protected: - // - // Private ... -private: - // - // Props ... - XCCInputs mInputs; // Inputs ... -}; - -// -// Tools ... \ No newline at end of file diff --git a/Documents/Pack/V1.0/Source/Helpers/x-saherelm.xche.helper.mq5 b/Documents/Pack/V1.0/Source/Helpers/x-saherelm.xche.helper.mq5 deleted file mode 100644 index a3ac938a..00000000 --- a/Documents/Pack/V1.0/Source/Helpers/x-saherelm.xche.helper.mq5 +++ /dev/null @@ -1,805 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Helper Class Library -// ---------------------------------------------- -// Name: XSCXCHEHelper -// 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 - -// -#include "../Classes/x-saherelm.xhelper.class.mq5" - -// -// Definitions ... - -// -enum ENUM_XCHE_BUFFERS -{ - X_CHE_LONG_EXIT_1_LINE = 0, - X_CHE_SHORT_EXIT_1_LINE = 1, - X_CHE_LONG_EXIT_2_LINE = 2, - X_CHE_SHORT_EXIT_2_LINE = 3, -}; - -// -// Input Models ... -struct XCHEInputs -{ - // - // Props ... - - // - // Market ... - int length; // Length - int loopback; // Loopback - double multiplier1; // 1st Multiplier - double multiplier2; // 2nd Multiplier - - // - // Calculation ... - ENUM_APPLIED_PRICE upAppliedTo; // Up Zone Applied To - ENUM_APPLIED_PRICE downAppliedTo; // Down Zone Applied To - - // - // Presentation ... - bool showLongExit1Line; // Show 1st Long Exit - bool showShortExit1Line; // Show 1st Short Exit - bool showLongExit2Line; // Show 2st Long Exit - bool showShortExit2Line; // Show 2st Short Exit - - // - // Constructor(s) ... - XCHEInputs() - { - // - Clean(); - } - - // - // Tools ... - - // - // Clean ... - void Clean() - { - // - length = 0; - loopback = 0; - multiplier1 = 0; - multiplier2 = 0; - - // - upAppliedTo = PRICE_HIGH; - downAppliedTo = PRICE_LOW; - - // - showLongExit1Line = false; - showShortExit1Line = false; - showLongExit2Line = false; - showShortExit2Line = false; - } - - // - // Default ... - void Default() - { - // - length = 35; - loopback = 26; - multiplier1 = 3.0; - multiplier2 = 3.5; - - // - upAppliedTo = PRICE_HIGH; - downAppliedTo = PRICE_LOW; - - // - showLongExit1Line = true; - showShortExit1Line = true; - showLongExit2Line = true; - showShortExit2Line = true; - } - - // - // Validate ... - bool IsValid() - { - // - bool result = false; - - // - result = - // - length > 0 && - loopback < length && - multiplier1 > 0 && - multiplier2 > multiplier1 - // - ; - - // - return result; - } - - // - // Retrieve MAx Length ... - int Max() - { - // - int result = 0; - - // - result = MathMax(length, loopback); - - // - return result; - } -}; - -// -// Define Conditions ... -struct XCHEConditions -{ - // - // Common ... - string symbol; - ENUM_TIMEFRAMES period; - datetime time; - - // - // Buffers ... - double long1[]; - double long2[]; - double short1[]; - double short2[]; - - // - // Conditions ... - - // - bool isBullish; - bool isBearish; - bool isStrongBullish; - bool isStrongBearish; - bool isSwitchedToBullish; - bool isSwitchedToBearish; - bool isStrongSwitchedToBullish; - bool isStrongSwitchedToBearish; - - // - void Clean() - { - // - Clean(long1); - Clean(long2); - Clean(short1); - Clean(short2); - - // - ArraySetAsSeries(long1, true); - ArraySetAsSeries(long2, true); - ArraySetAsSeries(short1, true); - ArraySetAsSeries(short2, true); - - // - isBullish = false; - isBearish = false; - isStrongBullish = false; - isStrongBearish = false; - isSwitchedToBullish = false; - isSwitchedToBearish = false; - isStrongSwitchedToBullish = false; - isStrongSwitchedToBearish = false; - } - - // - void GenerateScore( - double &bullishScore, - double &bearishScore // - ) - { - // - bullishScore = 0; - bearishScore = 0; - - // - if (isBullish) - { - bullishScore++; - } - if (isStrongBullish) - { - bullishScore++; - } - if (isSwitchedToBullish) - { - bullishScore++; - } - if (isStrongSwitchedToBullish) - { - bullishScore++; - } - - // - if (isBearish) - { - bearishScore++; - } - if (isStrongBearish) - { - bearishScore++; - } - if (isSwitchedToBearish) - { - bearishScore++; - } - if (isStrongSwitchedToBearish) - { - bearishScore++; - } - } - - // - 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 = - // - ToString("isBullish", isBullish, ignoreFalseConditions, separator) + - ToString("isBearish", isBearish, ignoreFalseConditions, separator) + - ToString("isStrongBullish", isStrongBullish, ignoreFalseConditions, separator) + - ToString("isStrongBearish", isStrongBearish, ignoreFalseConditions, separator) + - ToString("isSwitchedToBullish", isSwitchedToBullish, ignoreFalseConditions, separator) + - ToString("isSwitchedToBearish", isSwitchedToBearish, ignoreFalseConditions, separator) + - ToString("isStrongSwitchedToBullish", isStrongSwitchedToBullish, ignoreFalseConditions, separator) + - ToString("isStrongSwitchedToBearish", isStrongSwitchedToBearish, ignoreFalseConditions, separator) + - "" - // - ; - - // - result = - // - "[" + GetTag() + "]" + separator + - (onlyConditions - ? "" - : commonStr) + - (!includeScores - ? "" - : scoresStr) + - " " + separator + - (onlyCommons - ? "" - : conditionsStr) + - "" - // - ; - - // - return result; - } - - // - string GetTag() - { - return "XCHE"; - } -}; - -// -// Class ... -class XSCXCHEHelper : public XSCBaseHelper -{ - // - // Public ... -public: - // - // Props ... - - // - // Constructors ... - XSCXCHEHelper() : XSCBaseHelper(_Symbol, _Period) - { - } - - // - // Deconstructor ... - ~XSCXCHEHelper() {} - - // - // Tools ... - bool Init( - string symbol, // Trading Symbol - ENUM_TIMEFRAMES period, // Trading Period - XCHEInputs &inputs // Inputs - ) - { - // - bool result = false; - - // - mSymbol = symbol; - mPeriod = period; - - // - result = inputs.IsValid(); - if (!result) - { - return result; - } - - // - mInputs = inputs; - - // - ArraySetAsSeries(longExit1Buffer, true); - ArraySetAsSeries(longExit2Buffer, true); - ArraySetAsSeries(shortExit1Buffer, true); - ArraySetAsSeries(shortExit2Buffer, true); - - // - mHandler = iCustom( - mSymbol, - mPeriod, - "x-saherelm.xche", - // - // Inputs ... - // - // Market ... - "", - mInputs.length, - mInputs.loopback, - mInputs.multiplier1, - mInputs.multiplier2, - // - // Calculations ... - "", - mInputs.upAppliedTo, - mInputs.downAppliedTo, - // - // Presentation ... - "", - mInputs.showLongExit1Line, // Show 1st Long Exit, - mInputs.showShortExit1Line, // Show 1st Short Exit, - mInputs.showLongExit2Line, // Show 2st Long Exit, - mInputs.showShortExit2Line // Show 2st Short Exit - // - ); - result = mHandler != INVALID_HANDLE; - if (!result) - { - return result; - } - - // - return result; - } - - // - // Inputs ... - - // - XCHEInputs GetInputs() - { - return mInputs; - } - - // - bool SetInputs( - XCHEInputs &inputs // Configs - ) - { - // - return Init( - mSymbol, - mPeriod, - inputs); - } - - // - // Buffers ... - - // - double GetLongExit1( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - return longExit1Buffer[barIndex]; - } - - // - // Copy Required Long Exits 1 ... - int CopyLongExit1( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - longExit1Buffer, - buffer, - forceClean - // - ); - } - - // - double GetLongExit2( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - return longExit2Buffer[barIndex]; - } - - // - // Copy Required Long Exits 2 ... - int CopyLongExit2( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - longExit2Buffer, - buffer, - forceClean - // - ); - } - - // - double GetShortExit1( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - return shortExit1Buffer[barIndex]; - } - - // - // Copy Required Short Exits 1 ... - int CopyShortExit1( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - shortExit1Buffer, - buffer, - forceClean - // - ); - } - - // - double GetShortExit2( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - return shortExit2Buffer[barIndex]; - } - - // - // Copy Required Short Exits 2 ... - int CopyShortExit2( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - shortExit2Buffer, - buffer, - forceClean - // - ); - } - - // - bool GetConditions( - XCHEConditions &conditions, // - int barIndex = 0, // - int loopback = 3 // - ) - { - // - bool result = true; - - // - if (loopback < 3) - { - loopback = 3; - } - - // - conditions.Clean(); - - // - conditions.symbol = mSymbol; - conditions.period = mPeriod; - conditions.time = TimeCurrent(); - - // - int zIndex = barIndex; - int cIndex = zIndex + 1; - int pIndex = cIndex + 1; - int ppIndex = pIndex + 1; - - // - // Buffers ... - - // - CopyLongExit1( - zIndex, - loopback, - conditions.long1 // - ); - CopyLongExit2( - zIndex, - loopback, - conditions.long2 // - ); - CopyShortExit1( - zIndex, - loopback, - conditions.short1 // - ); - CopyShortExit2( - zIndex, - loopback, - conditions.short2 // - ); - - // - // Conditions ... - - // - bool isBullish = NotEmptyZero(conditions.long1[cIndex]); - bool isBearish = NotEmptyZero(conditions.short1[cIndex]); - - // - bool isBullishPrev = NotEmptyZero(conditions.long1[pIndex]); - bool isBearishPrev = NotEmptyZero(conditions.short1[pIndex]); - - // - bool isStrongBullish = isBullish && - NotEmptyZero(conditions.long2[cIndex]); - bool isStrongBearish = isBearish && - NotEmptyZero(conditions.short2[cIndex]); - - // - bool isStrongBullishPrev = isBullishPrev && - NotEmptyZero(conditions.long2[pIndex]); - bool isStrongBearishPrev = isBearishPrev && - NotEmptyZero(conditions.short2[pIndex]); - - // - bool isSwitchedToBullish = isBullish && - !isBullishPrev; - bool isSwitchedToBearish = isBearish && - !isBearishPrev; - - // - bool isStrongSwitchedToBullish = isStrongBullish && - !isStrongBullishPrev; - bool isStrongSwitchedToBearish = isStrongBearish && - !isStrongBearishPrev; - - // - conditions.isBullish = isBullish; - conditions.isBearish = isBearish; - conditions.isStrongBullish = isStrongBullish; - conditions.isStrongBearish = isStrongBearish; - conditions.isSwitchedToBullish = isSwitchedToBullish; - conditions.isSwitchedToBearish = isSwitchedToBearish; - conditions.isStrongSwitchedToBullish = isStrongSwitchedToBullish; - conditions.isStrongSwitchedToBearish = isStrongSwitchedToBearish; - - // - return result; - } - - // - // Protected ... -protected: - // - // Private ... -private: - // - // Props ... - XCHEInputs mInputs; // Inputs ... - - // - // Buffers ... - // - double longExit1Buffer[]; - double longExit2Buffer[]; - double shortExit1Buffer[]; - double shortExit2Buffer[]; - - // - // Tools ... - - // - // Calculate Values Until Now ... - void Calculate() - { - // - int totalBars = CountBars(); - if (totalBars > 1000) { - totalBars = 1000; - } - - // - // Long Exit 1 ... - CopyBuffer( - mHandler, - X_CHE_LONG_EXIT_1_LINE, - 0, - totalBars, - longExit1Buffer - // - ); - - // - // Long Exit 2 ... - CopyBuffer( - mHandler, - X_CHE_LONG_EXIT_2_LINE, - 0, - totalBars, - longExit2Buffer - // - ); - - // - // Short Exit 1 ... - CopyBuffer( - mHandler, - X_CHE_SHORT_EXIT_1_LINE, - 0, - totalBars, - shortExit1Buffer - // - ); - - // - // Short Exit 2 ... - CopyBuffer( - mHandler, - X_CHE_SHORT_EXIT_2_LINE, - 0, - totalBars, - shortExit2Buffer - // - ); - } -}; - -// -// Tools ... diff --git a/Documents/Pack/V1.0/Source/Helpers/x-saherelm.xct.helper.mq5 b/Documents/Pack/V1.0/Source/Helpers/x-saherelm.xct.helper.mq5 deleted file mode 100644 index 315857a4..00000000 --- a/Documents/Pack/V1.0/Source/Helpers/x-saherelm.xct.helper.mq5 +++ /dev/null @@ -1,220 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Helper Class Library -// ---------------------------------------------- -// Name: XSCXCTHelper -// 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.xhelper.class.mq5" - -// -// Definitions ... - -// -// Input Models ... -struct XCTInputs -{ - // - // Props ... - - // - color clr; // Text Color - ENUM_BASE_CORNER corner; // Text Position - - // - // Presentation ... - bool showCandleTime; // Show Candle Time - - // - // Constructor(s) ... - XCTInputs() - { - // - Clean(); - } - - // - // Tools ... - - // - // Clean ... - void Clean() - { - // - clr = CLR_NONE; - corner = CORNER_RIGHT_LOWER; - - // - // Presentation ... - showCandleTime = false; - } - - // - // Default ... - void Default() - { - // - clr = clrYellow; - corner = CORNER_RIGHT_LOWER; - - // - // Presentation ... - showCandleTime = true; - } - - // - // Validate ... - bool IsValid() - { - // - bool result = false; - - // - result = - // - true - // - ; - - // - return result; - } - - // - // Retrieve MAx Length ... - int Max() - { - // - int result = 0; - - // - result = MathMax(0, 0); - - // - return result; - } -}; - -// -// Class ... -class XSCXCTHelper : public XSCBaseHelper -{ - // - // Public ... -public: - // - // Props ... - - // - // Constructors ... - XSCXCTHelper() : XSCBaseHelper(_Symbol, _Period) - { - } - - // - // Deconstructor ... - ~XSCXCTHelper() {} - - // - // Tools ... - bool Init( - string symbol, // Trading Symbol - ENUM_TIMEFRAMES period, // Trading Period - XCTInputs &inputs // Inputs - ) - { - // - bool result = false; - - // - mSymbol = symbol; - mPeriod = period; - - // - result = inputs.IsValid(); - if (!result) - { - return result; - } - - // - mInputs = inputs; - - // - mHandler = iCustom( - mSymbol, - mPeriod, - "x-saherelm.xct", - // - // Inputs ... - mInputs.clr, // Text Color - mInputs.corner, // Text Position - // - // Presentation ... - "", - mInputs.showCandleTime // Show Candle Time - // - ); - result = mHandler != INVALID_HANDLE; - if (!result) - { - return result; - } - - // - return result; - } - - // - // Inputs ... - - // - XCTInputs GetInputs() - { - return mInputs; - } - - // - bool SetInputs( - XCTInputs &inputs // Configs - ) - { - // - return Init( - mSymbol, - mPeriod, - inputs - // - ); - } - - // - // Protected ... -protected: - // - // Private ... -private: - // - // Props ... - XCTInputs mInputs; // Inputs ... -}; - -// -// Tools ... \ No newline at end of file diff --git a/Documents/Pack/V1.0/Source/Helpers/x-saherelm.xdmnt.helper.mq5 b/Documents/Pack/V1.0/Source/Helpers/x-saherelm.xdmnt.helper.mq5 deleted file mode 100644 index 4718fb1e..00000000 --- a/Documents/Pack/V1.0/Source/Helpers/x-saherelm.xdmnt.helper.mq5 +++ /dev/null @@ -1,568 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Helper Class Library -// ---------------------------------------------- -// Name: XSCXDMNTHelper -// 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.xhelper.class.mq5" - -// -// Definitions ... - -// -enum ENUM_XDMNT_BUFFERS -{ - XDMNT_BULL_LINE = 0, - XDMNT_BEAR_LINE = 1, -}; - -// -// Input Models ... -struct XDMNTInputs -{ - // - // Props ... - - // - // Presentation ... - bool showBull; // Show Bull - bool showBear; // Show Bear - - // - // Constructor(s) ... - XDMNTInputs() - { - // - Clean(); - } - - // - // Tools ... - - // - // Clean ... - void Clean() - { - // - showBull = false; - showBear = false; - } - - // - // Default ... - void Default() - { - // - showBull = true; - showBear = true; - } - - // - // Validate ... - bool IsValid() - { - // - bool result = false; - - // - result = - // - true - // - ; - - // - return result; - } - - // - // Retrieve MAx Length ... - int Max() - { - // - int result = 0; - - // - result = 0; - - // - return result; - } -}; - -// -// Define Conditions ... -struct XDMNTConditions -{ - // - // Common ... - string symbol; - ENUM_TIMEFRAMES period; - datetime time; - - // - // Buffers ... - double bull[]; - double bear[]; - - // - // Conditions ... - - // - bool isBullish; - bool isBearish; - - // - void Clean() - { - // - Clean(bull); - Clean(bear); - - // - ArraySetAsSeries(bull, true); - ArraySetAsSeries(bear, true); - - // - isBullish = false; - isBearish = false; - } - - // - void GenerateScore( - double &bullishScore, - double &bearishScore // - ) - { - // - bullishScore = 0; - bearishScore = 0; - - // - if (isBullish) - { - bullishScore++; - } - - // - if (isBearish) - { - bearishScore++; - } - } - - // - 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 = - // - ToString("isBullish", isBullish, ignoreFalseConditions, separator) + - ToString("isBearish", isBearish, ignoreFalseConditions, separator) + - "" - // - ; - - // - result = - // - "[" + GetTag() + "]" + separator + - (onlyConditions - ? "" - : commonStr) + - (!includeScores - ? "" - : scoresStr) + - " " + separator + - (onlyCommons - ? "" - : conditionsStr) + - "" - // - ; - - // - return result; - } - - // - string GetTag() - { - return "XDMNT"; - } -}; - -// -// Class ... -class XSCXDMNTHelper : public XSCBaseHelper -{ - // - // Public ... -public: - // - // Props ... - - // - // Constructors ... - XSCXDMNTHelper() : XSCBaseHelper(_Symbol, _Period) - { - } - - // - // Deconstructor ... - ~XSCXDMNTHelper() {} - - // - // Tools ... - bool Init( - string symbol, // Trading Symbol - ENUM_TIMEFRAMES period, // Trading Period - XDMNTInputs &inputs // Inputs - ) - { - // - bool result = false; - - // - mSymbol = symbol; - mPeriod = period; - - // - result = inputs.IsValid(); - if (!result) - { - return result; - } - - // - mInputs = inputs; - - // - ArraySetAsSeries(bullBuffer, true); - ArraySetAsSeries(bearBuffer, true); - mHandler = iCustom( - mSymbol, - mPeriod, - "x-saherelm.xdmnt", - // - // Inputs ... - // - // Presentation ... - "", - mInputs.showBull, - mInputs.showBear - // - ); - result = mHandler != INVALID_HANDLE; - if (!result) - { - return result; - } - - // - return result; - } - - // - // Inputs ... - - // - XDMNTInputs GetInputs() - { - return mInputs; - } - - // - bool SetInputs( - XDMNTInputs &inputs // Configs - ) - { - // - return Init( - mSymbol, - mPeriod, - inputs - // - ); - } - - // - // Buffers ... - - // - // Bull ... - - // - double GetBull( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - int count = ArraySize(bullBuffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return bullBuffer[barIndex]; - } - - // - // Copy Required Items ... - int CopyBull( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - bullBuffer, - buffer, - forceClean - // - ); - } - - // - // Bear ... - - // - double GetBear( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - int count = ArraySize(bearBuffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return bearBuffer[barIndex]; - } - - // - // Copy Required Items ... - int CopyBear( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - bearBuffer, - buffer, - forceClean - // - ); - } - - // - bool GetConditions( - XDMNTConditions &conditions, // - int barIndex = 0, // - int loopback = 3 // - ) - { - // - bool result = true; - - // - if (loopback < 3) - { - loopback = 3; - } - - // - conditions.Clean(); - - // - conditions.symbol = mSymbol; - conditions.period = mPeriod; - conditions.time = TimeCurrent(); - - // - int zIndex = barIndex; - int cIndex = zIndex + 1; - int pIndex = cIndex + 1; - int ppIndex = pIndex + 1; - - // - // Buffers ... - - // - CopyBull( - zIndex, - loopback, - conditions.bull // - ); - - // - CopyBear( - zIndex, - loopback, - conditions.bear // - ); - - // - // Conditions ... - - // - bool isBullish = conditions.bull[cIndex] != 0; - - // - bool isBearish = conditions.bear[cIndex] != 0; - - // - conditions.isBullish = isBullish; - conditions.isBearish = isBearish; - - // - return result; - } - - // - // Protected ... -protected: - // - // Private ... -private: - // - // Props ... - XDMNTInputs mInputs; // Inputs ... - - // - // Buffers ... - double bullBuffer[]; - double bearBuffer[]; - - // - // Tools ... - - // - // Calculate Values Until Now ... - void Calculate() - { - // - int totalBars = CountBars(); - if (totalBars > 1000) - { - totalBars = 1000; - } - - // - // Bull Buffer ... - CopyBuffer( - mHandler, - XDMNT_BULL_LINE, - 0, - totalBars, - bullBuffer - // - ); - - // - // Bear Buffer ... - CopyBuffer( - mHandler, - XDMNT_BEAR_LINE, - 0, - totalBars, - bearBuffer - // - ); - } -}; - -// \ No newline at end of file diff --git a/Documents/Pack/V1.0/Source/Helpers/x-saherelm.xdon.helper.mq5 b/Documents/Pack/V1.0/Source/Helpers/x-saherelm.xdon.helper.mq5 deleted file mode 100644 index c7ec287a..00000000 --- a/Documents/Pack/V1.0/Source/Helpers/x-saherelm.xdon.helper.mq5 +++ /dev/null @@ -1,1078 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Helper Class Library -// ---------------------------------------------- -// Name: XSCXDONHelper -// 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.xhelper.class.mq5" - -// -// Definitions ... - -// -enum ENUM_XDON_BUFFERS -{ - // - // Open ... - XDON_UPPER_O_LINE = 0, - XDON_LOWER_O_LINE = 1, - // - // Close ... - XDON_UPPER_C_LINE = 2, - XDON_LOWER_C_LINE = 3, - // - // High ... - XDON_UPPER_H_LINE = 4, - XDON_LOWER_H_LINE = 5, - // - // Low ... - XDON_UPPER_L_LINE = 6, - XDON_LOWER_L_LINE = 7, -}; - -// -// Input Models ... -struct XDONInputs -{ - // - // Props ... - - // - // Market ... - int length; // Market Length - double offset; // Offset - - // - // Presentation ... - bool showOpen; // Show Open - bool showHigh; // Show High - bool showClose; // Show Close - bool showLow; // Show Low - - // - // Constructor(s) ... - XDONInputs() - { - // - Clean(); - } - - // - // Tools ... - - // - // Clean ... - void Clean() - { - // - // Market ... - length = 0; - offset = 0; - - // - // Presentation ... - showOpen = false; - showHigh = false; - showClose = false; - showLow = false; - } - - // - // Default ... - void Default() - { - // - // Market ... - length = 52; - offset = 0; - - // - // Presentation ... - showOpen = true; - showHigh = true; - showClose = true; - showLow = true; - } - - // - // Validate ... - bool IsValid() - { - // - bool result = false; - - // - result = - // - length >= 5 && - offset >= 0 - // - ; - - // - return result; - } - - // - // Retrieve MAx Length ... - int Max() - { - // - int result = 0; - - // - result = MathMax(0, length); - - // - return result; - } -}; - -// -// Class ... -class XSCXDONHelper : public XSCBaseHelper -{ - // - // Public ... -public: - // - // Props ... - - // - // Constructors ... - XSCXDONHelper() : XSCBaseHelper(_Symbol, _Period) - { - } - - // - // Deconstructor ... - ~XSCXDONHelper() {} - - // - // Tools ... - bool Init( - string symbol, // Trading Symbol - ENUM_TIMEFRAMES period, // Trading Period - XDONInputs &inputs // Inputs - ) - { - // - bool result = false; - - // - mSymbol = symbol; - mPeriod = period; - - // - result = inputs.IsValid(); - if (!result) - { - return result; - } - - // - mInputs = inputs; - - // - ArraySetAsSeries(upperOBuffer, true); - ArraySetAsSeries(lowerOBuffer, true); - ArraySetAsSeries(upperCBuffer, true); - ArraySetAsSeries(lowerCBuffer, true); - ArraySetAsSeries(upperHBuffer, true); - ArraySetAsSeries(lowerHBuffer, true); - ArraySetAsSeries(upperLBuffer, true); - ArraySetAsSeries(lowerLBuffer, true); - - // - mHandler = iCustom( - mSymbol, - mPeriod, - "x-saherelm.xdon", - // - // Inputs ... - // - // Market ... - "", - mInputs.length, // Market Length - mInputs.offset, // Offset - // - // Presentation ... - "", - mInputs.showOpen, // Show Open - mInputs.showHigh, // Show High - mInputs.showClose, // Show Close - mInputs.showLow // Show Low - // - ); - result = mHandler != INVALID_HANDLE; - if (!result) - { - return result; - } - - // - return result; - } - - // - // Inputs ... - - // - XDONInputs GetInputs() - { - return mInputs; - } - - // - bool SetInputs( - XDONInputs &inputs // Configs - ) - { - // - return Init( - mSymbol, - mPeriod, - inputs - // - ); - } - - // - // Buffers ... - - // - // Open ... - - // - // Upper ... - - // - double GetUpperO( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - int count = ArraySize(upperOBuffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return upperOBuffer[barIndex]; - } - - // - // Copy Required Items ... - int CopyUpperO( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - upperOBuffer, - buffer, - forceClean - // - ); - } - - // - bool IsSameUpperO( - int barIndex, // Start Bar Index - int verifier = 71 // Number of Verifiers - ) - { - // - // Update Calculations ... - Calculate(); - - // - return IsSame( - upperOBuffer, - verifier, - barIndex // - ); - } - - // - // Lower ... - - // - double GetLowerO( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - int count = ArraySize(lowerOBuffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return lowerOBuffer[barIndex]; - } - - // - // Copy Required Items ... - int CopyLowerO( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - lowerOBuffer, - buffer, - forceClean - // - ); - } - - // - bool IsSameLowerO( - int barIndex, // Start Bar Index - int verifier = 71 // Number of Verifiers - ) - { - // - // Update Calculations ... - Calculate(); - - // - return IsSame( - lowerOBuffer, - verifier, - barIndex // - ); - } - - // - // Close ... - - // - // Upper ... - - // - double GetUpperC( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - int count = ArraySize(upperCBuffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return upperCBuffer[barIndex]; - } - - // - // Copy Required Items ... - int CopyUpperC( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - upperCBuffer, - buffer, - forceClean - // - ); - } - - // - bool IsSameUpperC( - int barIndex, // Start Bar Index - int verifier = 71 // Number of Verifiers - ) - { - // - // Update Calculations ... - Calculate(); - - // - return IsSame( - upperCBuffer, - verifier, - barIndex // - ); - } - - // - // Lower ... - - // - double GetLowerC( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - int count = ArraySize(lowerCBuffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return lowerCBuffer[barIndex]; - } - - // - // Copy Required Items ... - int CopyLowerC( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - lowerCBuffer, - buffer, - forceClean - // - ); - } - - // - bool IsSameLowerC( - int barIndex, // Start Bar Index - int verifier = 71 // Number of Verifiers - ) - { - // - // Update Calculations ... - Calculate(); - - // - return IsSame( - lowerCBuffer, - verifier, - barIndex // - ); - } - - // - // High ... - - // - // Upper ... - - // - double GetUpperH( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - int count = ArraySize(upperHBuffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return upperHBuffer[barIndex]; - } - - // - // Copy Required Items ... - int CopyUpperH( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - upperHBuffer, - buffer, - forceClean - // - ); - } - - // - bool IsSameUpperH( - int barIndex, // Start Bar Index - int verifier = 71 // Number of Verifiers - ) - { - // - // Update Calculations ... - Calculate(); - - // - return IsSame( - upperHBuffer, - verifier, - barIndex // - ); - } - - // - // Lower ... - - // - double GetLowerH( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - int count = ArraySize(lowerHBuffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return lowerHBuffer[barIndex]; - } - - // - // Copy Required Items ... - int CopyLowerH( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - lowerHBuffer, - buffer, - forceClean - // - ); - } - - // - bool IsSameLowerH( - int barIndex, // Start Bar Index - int verifier = 71 // Number of Verifiers - ) - { - // - // Update Calculations ... - Calculate(); - - // - return IsSame( - lowerHBuffer, - verifier, - barIndex // - ); - } - - // - // Low ... - - // - // Upper ... - - // - double GetUpperL( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - int count = ArraySize(upperLBuffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return upperLBuffer[barIndex]; - } - - // - // Copy Required Items ... - int CopyUpperL( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - upperLBuffer, - buffer, - forceClean - // - ); - } - - // - bool IsSameUpperL( - int barIndex, // Start Bar Index - int verifier = 71 // Number of Verifiers - ) - { - // - // Update Calculations ... - Calculate(); - - // - return IsSame( - upperLBuffer, - verifier, - barIndex // - ); - } - - // - // Lower ... - - // - double GetLowerL( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - int count = ArraySize(lowerLBuffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return lowerLBuffer[barIndex]; - } - - // - // Copy Required Items ... - int CopyLowerL( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - lowerLBuffer, - buffer, - forceClean - // - ); - } - - // - bool IsSameLowerL( - int barIndex, // Start Bar Index - int verifier = 71 // Number of Verifiers - ) - { - // - // Update Calculations ... - Calculate(); - - // - return IsSame( - lowerLBuffer, - verifier, - barIndex // - ); - } - - // - void GetUppers( - double &result[], - int barIndex = 0 // - ) - { - // - Clean(result); - - // - double uo = GetUpperO(barIndex); - double uc = GetUpperC(barIndex); - double uh = GetUpperH(barIndex); - double ul = GetUpperL(barIndex); - - // - Add(uo, result); - Add(uc, result); - Add(uh, result); - Add(ul, result); - } - double GetMinUpper( - int barIndex = 0 // - ) - { - // - double values[]; - GetUppers(values); - - // - double result = GetMin(values); - - // - return result; - } - double GetMaxUpper( - int barIndex = 0 // - ) - { - // - double values[]; - GetUppers(values); - - // - double result = GetMax(values); - - // - return result; - } - - // - void GetLowers( - double &result[], - int barIndex = 0 // - ) - { - // - Clean(result); - - // - double lo = GetLowerO(barIndex); - double lc = GetLowerC(barIndex); - double lh = GetLowerH(barIndex); - double ll = GetLowerL(barIndex); - - // - Add(lo, result); - Add(lc, result); - Add(lh, result); - Add(ll, result); - } - double GetMinLower( - int barIndex = 0 // - ) - { - // - double values[]; - GetLowers(values); - - // - double result = GetMin(values); - - // - return result; - } - double GetMaxLower( - int barIndex = 0 // - ) - { - // - double values[]; - GetLowers(values); - - // - double result = GetMin(values); - - // - return result; - } - - // - // Protected ... -protected: - // - // Private ... -private: - // - // Props ... - XDONInputs mInputs; // Inputs ... - - // - // Buffers ... - double upperOBuffer[]; - double lowerOBuffer[]; - double upperCBuffer[]; - double lowerCBuffer[]; - double upperHBuffer[]; - double lowerHBuffer[]; - double upperLBuffer[]; - double lowerLBuffer[]; - - // - // Tools ... - - // - // Calculate Values Until Now ... - void Calculate() - { - // - int totalBars = CountBars(); - if (totalBars > 1000) { - totalBars = 1000; - } - - // - // Open ... - - // - // Upper Buffer ... - CopyBuffer( - mHandler, - XDON_UPPER_O_LINE, - 0, - totalBars, - upperOBuffer - // - ); - - // - // Lower Buffer ... - CopyBuffer( - mHandler, - XDON_LOWER_O_LINE, - 0, - totalBars, - lowerOBuffer - // - ); - - // - // Close ... - - // - // Upper Buffer ... - CopyBuffer( - mHandler, - XDON_UPPER_C_LINE, - 0, - totalBars, - upperCBuffer - // - ); - - // - // Lower Buffer ... - CopyBuffer( - mHandler, - XDON_LOWER_C_LINE, - 0, - totalBars, - lowerCBuffer - // - ); - - // - // High ... - - // - // Upper Buffer ... - CopyBuffer( - mHandler, - XDON_UPPER_H_LINE, - 0, - totalBars, - upperHBuffer - // - ); - - // - // Lower Buffer ... - CopyBuffer( - mHandler, - XDON_LOWER_H_LINE, - 0, - totalBars, - lowerHBuffer - // - ); - - // - // Low ... - - // - // Upper Buffer ... - CopyBuffer( - mHandler, - XDON_UPPER_L_LINE, - 0, - totalBars, - upperLBuffer - // - ); - - // - // Lower Buffer ... - CopyBuffer( - mHandler, - XDON_LOWER_L_LINE, - 0, - totalBars, - lowerLBuffer - // - ); - } -}; - -// -// Tools ... \ No newline at end of file diff --git a/Documents/Pack/V1.0/Source/Helpers/x-saherelm.xhk.helper.mq5 b/Documents/Pack/V1.0/Source/Helpers/x-saherelm.xhk.helper.mq5 deleted file mode 100644 index 29445c8b..00000000 --- a/Documents/Pack/V1.0/Source/Helpers/x-saherelm.xhk.helper.mq5 +++ /dev/null @@ -1,1296 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Helper Class Library -// ---------------------------------------------- -// Name: XSCXHKHelper -// 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.xhelper.class.mq5" - -// -// Definitions ... - -// -enum ENUM_XHK_BUFFERS -{ - // - // Hiken Ashi ... - XHK_OPEN_LINE = 0, - XHK_HIGHLINE = 1, - XHK_LOW_LINE = 2, - XHK_CLOSE_LINE = 3, - // - // Smoothed Hiken Ashi ... - XHK_SM_OPEN_LINE = 5, - XHK_SM_HIGHLINE = 6, - XHK_SM_LOW_LINE = 7, - XHK_SM_CLOSE_LINE = 8, -}; - -// -// Input Models ... -struct XHKInputs -{ - // - // Props ... - - // - // Market ... - int smoothingLength; // Smoothing Length - // - // Presentation ... - bool drawHikenAshi; // Draw Hiken Ashi - bool drawSmoothedHikenAshi; // Draw Smoothed Hiken Ashi - - // - // Constructor(s) ... - XHKInputs() - { - // - Clean(); - } - - // - // Tools ... - - // - // Clean ... - void Clean() - { - // - // Market ... - smoothingLength = 0; - // - // Presentation ... - drawHikenAshi = false; - drawSmoothedHikenAshi = false; - } - - // - // Default ... - void Default() - { - // - // Market ... - smoothingLength = 17; - // - // Presentation ... - drawHikenAshi = true; - drawSmoothedHikenAshi = true; - } - - // - // Validate ... - bool IsValid() - { - // - bool result = false; - - // - result = - // - smoothingLength > 2 - // - ; - - // - return result; - } - - // - // Retrieve MAx Length ... - int Max() - { - // - int result = 0; - - // - result = MathMax(0, smoothingLength); - - // - return result; - } -}; - -// -// Define Conditions ... -struct XHKConditions -{ - // - // Common ... - string symbol; - ENUM_TIMEFRAMES period; - datetime time; - - // - // Buffers ... - XOHCL hkBar[]; - XOHCL smHKBar[]; - - // - // Conditions ... - - // - bool isHKBullish; - bool isHKBearish; - bool isHKSwitchedToBullish; - bool isHKSwitchedToBearish; - - // - bool isSMHKBullish; - bool isSMHKBearish; - bool isSMHKSwitchedToBullish; - bool isSMHKSwitchedToBearish; - - // - void Clean() - { - // - Clean(hkBar); - Clean(smHKBar); - - // - ArraySetAsSeries(hkBar, true); - ArraySetAsSeries(smHKBar, true); - - // - isHKBullish = false; - isHKBearish = false; - isHKSwitchedToBullish = false; - isHKSwitchedToBearish = false; - - // - isSMHKBullish = false; - isSMHKBearish = false; - isSMHKSwitchedToBullish = false; - isSMHKSwitchedToBearish = false; - } - - // - void GenerateScore( - double &bullishScore, - double &bearishScore // - ) - { - // - bullishScore = 0; - bearishScore = 0; - - // - if (isHKBullish) - { - bullishScore++; - } - if (isHKSwitchedToBullish) - { - bullishScore++; - } - - // - if (isHKBearish) - { - bearishScore++; - } - if (isHKSwitchedToBearish) - { - bearishScore++; - } - - // - if (isSMHKBullish) - { - bullishScore++; - } - if (isSMHKSwitchedToBullish) - { - bullishScore++; - } - - // - if (isSMHKBearish) - { - bearishScore++; - } - if (isSMHKSwitchedToBearish) - { - bearishScore++; - } - } - - // - 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 = - // - ToString("isHKBullish", isHKBullish, ignoreFalseConditions, separator) + - ToString("isHKSwitchedToBullish", isHKSwitchedToBullish, ignoreFalseConditions, separator) + - ToString("isHKBearish", isHKBearish, ignoreFalseConditions, separator) + - ToString("isHKSwitchedToBearish", isHKSwitchedToBearish, ignoreFalseConditions, separator) + - // - ToString("isSMHKBullish", isSMHKBullish, ignoreFalseConditions, separator) + - ToString("isSMHKSwitchedToBullish", isSMHKSwitchedToBullish, ignoreFalseConditions, separator) + - ToString("isSMHKBearish", isSMHKBearish, ignoreFalseConditions, separator) + - ToString("isSMHKSwitchedToBearish", isSMHKSwitchedToBearish, ignoreFalseConditions, separator) + - "" - // - ; - - // - result = - // - "[" + GetTag() + "]" + separator + - (onlyConditions - ? "" - : commonStr) + - (!includeScores - ? "" - : scoresStr) + - " " + separator + - (onlyCommons - ? "" - : conditionsStr) + - "" - // - ; - - // - return result; - } - - // - string GetTag() - { - return "XHK"; - } -}; - -// -// Class ... -class XSCXHKHelper : public XSCBaseHelper -{ - // - // Public ... -public: - // - // Props ... - - // - // Constructors ... - XSCXHKHelper() : XSCBaseHelper(_Symbol, _Period) - { - } - - // - // Deconstructor ... - ~XSCXHKHelper() {} - - // - // Tools ... - bool Init( - string symbol, // Trading Symbol - ENUM_TIMEFRAMES period, // Trading Period - XHKInputs &inputs // Inputs - ) - { - // - bool result = false; - - // - mSymbol = symbol; - mPeriod = period; - - // - result = inputs.IsValid(); - if (!result) - { - return result; - } - - // - mInputs = inputs; - - // - ArraySetAsSeries(openBuffer, true); - ArraySetAsSeries(highBuffer, true); - ArraySetAsSeries(lowBuffer, true); - ArraySetAsSeries(closeBuffer, true); - ArraySetAsSeries(smOpenBuffer, true); - ArraySetAsSeries(smHighBuffer, true); - ArraySetAsSeries(smLowBuffer, true); - ArraySetAsSeries(smCloseBuffer, true); - - // - mHandler = iCustom( - mSymbol, - mPeriod, - "x-saherelm.xhk", - // - // Inputs ... - // - // Market ... - "", - mInputs.smoothingLength, // Smoothing Length - // - // Presentation ... - "", - mInputs.drawHikenAshi, // Draw Hiken Ashi - mInputs.drawSmoothedHikenAshi // Draw Smoothed Hiken Ashi - // - ); - result = mHandler != INVALID_HANDLE; - if (!result) - { - return result; - } - - // - return result; - } - - // - // Inputs ... - - // - XHKInputs GetInputs() - { - return mInputs; - } - - // - bool SetInputs( - XHKInputs &inputs // Configs - ) - { - // - return Init( - mSymbol, - mPeriod, - inputs - // - ); - } - - // - // Buffers ... - - // - double GetOpen( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - int count = ArraySize(openBuffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return openBuffer[barIndex]; - } - - // - // Copy Required Items ... - int CopyOpen( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - openBuffer, - buffer, - forceClean - // - ); - } - - // - double GetHigh( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - int count = ArraySize(highBuffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return highBuffer[barIndex]; - } - - // - // Copy Required Items ... - int CopyHigh( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - highBuffer, - buffer, - forceClean - // - ); - } - - // - double GetLow( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - int count = ArraySize(lowBuffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return lowBuffer[barIndex]; - } - - // - // Copy Required Items ... - int CopyLow( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - lowBuffer, - buffer, - forceClean - // - ); - } - - // - double GetClose( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - int count = ArraySize(closeBuffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return closeBuffer[barIndex]; - } - - // - // Copy Required Items ... - int CopyClose( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - closeBuffer, - buffer, - forceClean - // - ); - } - - // - // Smoothed ... - - // - double GetSMOpen( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - int count = ArraySize(smOpenBuffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return smOpenBuffer[barIndex]; - } - - // - // Copy Required Items ... - int CopySMOpen( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - smOpenBuffer, - buffer, - forceClean - // - ); - } - - // - double GetSMHigh( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - int count = ArraySize(smHighBuffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return smHighBuffer[barIndex]; - } - - // - // Copy Required Items ... - int CopySMHigh( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - smHighBuffer, - buffer, - forceClean - // - ); - } - - // - double GetSMLow( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - int count = ArraySize(smLowBuffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return smLowBuffer[barIndex]; - } - - // - // Copy Required Items ... - int CopySMLow( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - smLowBuffer, - buffer, - forceClean - // - ); - } - - // - double GetSMClose( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - int count = ArraySize(smCloseBuffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return smCloseBuffer[barIndex]; - } - - // - // Copy Required Items ... - int CopySMClose( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - smCloseBuffer, - buffer, - forceClean - // - ); - } - - // - // XOHCL ... - - // - // Retrieve Hiken Ashi Info as XOHCL model ... - bool AsOHCL( - XOHCL &bar, // Holds Result - int barIndex // Bar Index - ) - { - // - bool result = false; - - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - int count = ArraySize(openBuffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - double open = GetOpen(barIndex); - double high = GetHigh(barIndex); - double close = GetClose(barIndex); - double low = GetLow(barIndex); - - // - result = bar.Init( - mSymbol, - mPeriod, - open, - high, - close, - low, - barIndex - // - ); - - // - return result; - } - - // - // Copy Required Items ... - int CopyAsOHCL( - int start, // Start - int count, // Number of Items for read - XOHCL &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - int result = 0; - - // - // Update Calculations ... - Calculate(); - - // - if (forceClean) - { - Clean(buffer); - } - - // - int before = ArraySize(buffer); - - // - if (start < 0) - { - start = 0; - } - - // - if (start >= ArraySize(openBuffer)) - { - start = ArraySize(openBuffer) - 1; - } - - // - bool asSeriesBuffer = ArrayGetAsSeries(buffer); - ArraySetAsSeries(buffer, true); - - // - for (int i = start; i < start + count; i++) - { - // - XOHCL iBar; - bool isInit = AsOHCL(iBar, i); - - // - if (isInit) - { - // - AddRef( - iBar, - buffer - // - ); - } - } - - // - ArraySetAsSeries(buffer, asSeriesBuffer); - - // - int after = ArraySize(buffer); - - // - result = after - before; - - // - return result; - } - - // - // Retrieve Smoothed Hiken Ashi Info as XOHCL model ... - bool SMAsOHCL( - XOHCL &bar, // Holds Result - int barIndex // Bar Index - ) - { - // - bool result = false; - - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - int count = ArraySize(openBuffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - double open = GetSMOpen(barIndex); - double high = GetSMHigh(barIndex); - double close = GetSMClose(barIndex); - double low = GetSMLow(barIndex); - - // - result = bar.Init( - mSymbol, - mPeriod, - open, - high, - close, - low, - barIndex - // - ); - - // - return result; - } - - // - // Copy Required Items ... - int CopySMAsOHCL( - int start, // Start - int count, // Number of Items for read - XOHCL &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - int result = 0; - - // - // Update Calculations ... - Calculate(); - - // - if (forceClean) - { - Clean(buffer); - } - - // - int before = ArraySize(buffer); - - // - if (start < 0) - { - start = 0; - } - - // - if (start >= ArraySize(openBuffer)) - { - start = ArraySize(openBuffer) - 1; - } - - // - bool asSeriesBuffer = ArrayGetAsSeries(buffer); - ArraySetAsSeries(buffer, true); - - // - for (int i = start; i < start + count; i++) - { - // - XOHCL iBar; - bool isInit = SMAsOHCL(iBar, i); - - // - if (isInit) - { - // - AddRef( - iBar, - buffer - // - ); - } - } - - // - ArraySetAsSeries(buffer, asSeriesBuffer); - - // - int after = ArraySize(buffer); - - // - result = after - before; - - // - return result; - } - - // - bool GetConditions( - XHKConditions &conditions, // - int barIndex = 0, // - int loopback = 3 // - ) - { - // - bool result = true; - - // - if (loopback < 3) - { - loopback = 3; - } - - // - conditions.Clean(); - - // - conditions.symbol = mSymbol; - conditions.period = mPeriod; - conditions.time = TimeCurrent(); - - // - int zIndex = barIndex; - int cIndex = zIndex + 1; - int pIndex = cIndex + 1; - int ppIndex = pIndex + 1; - - // - CopyAsOHCL( - zIndex, - loopback, - conditions.hkBar // - ); - CopySMAsOHCL( - zIndex, - loopback, - conditions.smHKBar // - ); - - // - // Calculate Conditions ... - - // - bool isHKBullish = conditions.hkBar[cIndex].IsBullish(); - bool isHKBullishPrev = conditions.hkBar[pIndex].IsBullish(); - - // - bool isHKSwitchedToBullish = isHKBullish && - !isHKBullishPrev; - - // - bool isHKBearish = conditions.hkBar[cIndex].IsBearish(); - bool isHKBearishPrev = conditions.hkBar[pIndex].IsBearish(); - - // - bool isHKSwitchedToBearish = isHKBearish && - !isHKBearishPrev; - - // - bool isSMHKBullish = conditions.smHKBar[cIndex].IsBullish(); - bool isSMHKBullishPrev = conditions.smHKBar[pIndex].IsBullish(); - - // - bool isSMHKSwitchedToBullish = isSMHKBullish && - !isSMHKBullishPrev; - - // - bool isSMHKBearish = conditions.smHKBar[cIndex].IsBearish(); - bool isSMHKBearishPrev = conditions.smHKBar[pIndex].IsBearish(); - - // - bool isSMHKSwitchedToBearish = isSMHKBearish && - !isSMHKBearishPrev; - - // - conditions.isHKBullish = isHKBullish; - conditions.isHKSwitchedToBullish = isHKSwitchedToBullish; - conditions.isHKBearish = isHKBearish; - conditions.isHKSwitchedToBearish = isHKSwitchedToBearish; - conditions.isSMHKBullish = isSMHKBullish; - conditions.isSMHKSwitchedToBullish = isSMHKSwitchedToBullish; - conditions.isSMHKBearish = isSMHKBearish; - conditions.isSMHKSwitchedToBearish = isSMHKSwitchedToBearish; - - // - return result; - } - - // - // Protected ... -protected: - // - // Private ... -private: - // - // Props ... - XHKInputs mInputs; // Inputs ... - - // - // Buffers ... - double openBuffer[]; - double highBuffer[]; - double lowBuffer[]; - double closeBuffer[]; - double smOpenBuffer[]; - double smHighBuffer[]; - double smLowBuffer[]; - double smCloseBuffer[]; - - // - // Tools ... - - // - // Calculate Values Until Now ... - void Calculate() - { - // - int totalBars = CountBars(); - if (totalBars > 1000) { - totalBars = 1000; - } - - // - // Open Buffer ... - CopyBuffer( - mHandler, - XHK_OPEN_LINE, - 0, - totalBars, - openBuffer - // - ); - - // - // High Buffer ... - CopyBuffer( - mHandler, - XHK_HIGHLINE, - 0, - totalBars, - highBuffer - // - ); - - // - // Low Buffer ... - CopyBuffer( - mHandler, - XHK_LOW_LINE, - 0, - totalBars, - lowBuffer - // - ); - - // - // Close Buffer ... - CopyBuffer( - mHandler, - XHK_CLOSE_LINE, - 0, - totalBars, - closeBuffer - // - ); - - // - // Smoothed ... - - // - // Open Buffer ... - CopyBuffer( - mHandler, - XHK_SM_OPEN_LINE, - 0, - totalBars, - smOpenBuffer - // - ); - - // - // High Buffer ... - CopyBuffer( - mHandler, - XHK_SM_HIGHLINE, - 0, - totalBars, - smHighBuffer - // - ); - - // - // Low Buffer ... - CopyBuffer( - mHandler, - XHK_SM_LOW_LINE, - 0, - totalBars, - smLowBuffer - // - ); - - // - // Close Buffer ... - CopyBuffer( - mHandler, - XHK_SM_CLOSE_LINE, - 0, - totalBars, - smCloseBuffer - // - ); - } -}; - -// -// Tools ... \ No newline at end of file diff --git a/Documents/Pack/V1.0/Source/Helpers/x-saherelm.xhtd.helper.mq5 b/Documents/Pack/V1.0/Source/Helpers/x-saherelm.xhtd.helper.mq5 deleted file mode 100644 index 8f7f4727..00000000 --- a/Documents/Pack/V1.0/Source/Helpers/x-saherelm.xhtd.helper.mq5 +++ /dev/null @@ -1,560 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Helper Class Library -// ---------------------------------------------- -// Name: XSCXHTDHelper -// 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.xhelper.class.mq5" - -// -// Definitions ... - -// -enum ENUM_XHTD_BUFFERS -{ - XHTD_MAIN_LINE = 0, -}; - -// -// Input Models ... -struct XHTDInputs -{ - // - // Props ... - - // - // Market ... - int length; // Length - ENUM_APPLIED_PRICE appliedTo; // Applied To - double multiplier; // Multiplier - - // - // Presentation ... - bool show; // Show - - // - // Constructor(s) ... - XHTDInputs() - { - // - Clean(); - } - - // - // Tools ... - - // - // Clean ... - void Clean() - { - // - length = 0; - multiplier = 0; - - // - appliedTo = PRICE_CLOSE; - - // - show = false; - } - - // - // Default ... - void Default() - { - // - length = 14; - multiplier = 0.66; - - // - appliedTo = PRICE_CLOSE; - - // - show = true; - } - - // - // Validate ... - bool IsValid() - { - // - bool result = false; - - // - result = - // - length >= 2 && - multiplier > 0 - // - ; - - // - return result; - } - - // - // Retrieve MAx Length ... - int Max() - { - // - int result = 0; - - // - result = MathMax(result, length); - - // - return result; - } -}; - -// -// Define Conditions ... -struct XHTDConditions -{ - // - // Common ... - string symbol; - ENUM_TIMEFRAMES period; - datetime time; - - // - // Buffers ... - double htd[]; - - // - // Conditions ... - - // - bool isBullish; - bool isBearish; - - // - bool isSwitchedToBullish; - bool isSwitchedToBearish; - - // - void Clean() - { - // - Clean(htd); - - // - ArraySetAsSeries(htd, true); - - // - isBullish = false; - isBearish = false; - isSwitchedToBullish = false; - isSwitchedToBearish = false; - } - - // - void GenerateScore( - double &bullishScore, - double &bearishScore // - ) - { - // - bullishScore = 0; - bearishScore = 0; - - // - if (isBullish) - { - bullishScore++; - } - if (isSwitchedToBullish) - { - bullishScore++; - } - - if (isBearish) - { - bearishScore++; - } - if (isSwitchedToBearish) - { - bearishScore++; - } - } - - // - 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 = - // - ToString("isBullish", isBullish, ignoreFalseConditions, separator) + - ToString("isBearish", isBearish, ignoreFalseConditions, separator) + - ToString("isSwitchedToBullish", isSwitchedToBullish, ignoreFalseConditions, separator) + - ToString("isSwitchedToBearish", isSwitchedToBearish, ignoreFalseConditions, separator) + - "" - // - ; - - // - result = - // - "[" + GetTag() + "]" + separator + - (onlyConditions - ? "" - : commonStr) + - (!includeScores - ? "" - : scoresStr) + - " " + separator + - (onlyCommons - ? "" - : conditionsStr) + - "" - // - ; - - // - return result; - } - - // - string GetTag() - { - return "XHTD"; - } -}; - -// -// Class ... -class XSCXHTDHelper : public XSCBaseHelper -{ - // - // Public ... -public: - // - // Props ... - - // - // Constructors ... - XSCXHTDHelper() : XSCBaseHelper(_Symbol, _Period) - { - } - - // - // Deconstructor ... - ~XSCXHTDHelper() {} - - // - // Tools ... - bool Init( - string symbol, // Trading Symbol - ENUM_TIMEFRAMES period, // Trading Period - XHTDInputs &inputs // Inputs - ) - { - // - bool result = false; - - // - mSymbol = symbol; - mPeriod = period; - - // - result = inputs.IsValid(); - if (!result) - { - return result; - } - - // - mInputs = inputs; - - // - ArraySetAsSeries(htdBuffer, true); - mHandler = iCustom( - mSymbol, - mPeriod, - "x-saherelm.xhtd", - // - // Inputs ... - // - // Market ... - "", - mInputs.length, - mInputs.appliedTo, - mInputs.multiplier, - // - // Presentation ... - "", - mInputs.show - // - ); - result = mHandler != INVALID_HANDLE; - if (!result) - { - return result; - } - - // - return result; - } - - // - // Inputs ... - - // - XHTDInputs GetInputs() - { - return mInputs; - } - - // - bool SetInputs( - XHTDInputs &inputs // Configs - ) - { - // - return Init( - mSymbol, - mPeriod, - inputs - // - ); - } - - // - // Buffers ... - - // - double GetHTD( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - int count = ArraySize(htdBuffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return htdBuffer[barIndex]; - } - - // - // Copy Required Items ... - int CopyHTD( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - htdBuffer, - buffer, - forceClean - // - ); - } - - // - bool GetConditions( - XHTDConditions &conditions, // - int barIndex = 0, // - int loopback = 3 // - ) - { - // - bool result = true; - - // - if (loopback < 3) - { - loopback = 3; - } - - // - conditions.Clean(); - - // - conditions.symbol = mSymbol; - conditions.period = mPeriod; - conditions.time = TimeCurrent(); - - // - int zIndex = barIndex; - int cIndex = zIndex + 1; - int pIndex = cIndex + 1; - int ppIndex = pIndex + 1; - - // - // Buffers ... - - // - CopyHTD( - zIndex, - loopback, - conditions.htd // - ); - - // - // Conditions ... - - // - XOHCL cBar; - result = cBar.Init( - mSymbol, - mPeriod, - cIndex // - ); - if (!result) - { - return result; - } - - // - XOHCL pBar; - result = pBar.Init( - mSymbol, - mPeriod, - pIndex // - ); - if (!result) - { - return result; - } - - // - bool isBullish = conditions.htd[cIndex] < cBar.close; - bool isBullishPrev = conditions.htd[pIndex] < pBar.close; - - // - bool isBearish = conditions.htd[cIndex] > cBar.close; - bool isBearishPrev = conditions.htd[pIndex] > pBar.close; - - // - bool isSwitchedToBullish = isBullish && - !isBullishPrev; - bool isSwitchedToBearish = isBearish && - !isBearishPrev; - - // - conditions.isBullish = isBullish; - conditions.isBearish = isBearish; - conditions.isSwitchedToBullish = isSwitchedToBullish; - conditions.isSwitchedToBearish = isSwitchedToBearish; - - // - return result; - } - - // - // Protected ... -protected: - // - // Private ... -private: - // - // Props ... - XHTDInputs mInputs; // Inputs ... - - // - // Buffers ... - double htdBuffer[]; - - // - // Tools ... - - // - // Calculate Values Until Now ... - void Calculate() - { - // - int totalBars = CountBars(); - if (totalBars > 1000) - { - totalBars = 1000; - } - - // - // Longs Buffer ... - CopyBuffer( - mHandler, - XHTD_MAIN_LINE, - 0, - totalBars, - htdBuffer - // - ); - } -}; - -// \ No newline at end of file diff --git a/Documents/Pack/V1.0/Source/Helpers/x-saherelm.xhull.helper.mq5 b/Documents/Pack/V1.0/Source/Helpers/x-saherelm.xhull.helper.mq5 deleted file mode 100644 index 741e23d2..00000000 --- a/Documents/Pack/V1.0/Source/Helpers/x-saherelm.xhull.helper.mq5 +++ /dev/null @@ -1,674 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Helper Class Library -// ---------------------------------------------- -// Name: XSCXHULLHelper -// 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.xhelper.class.mq5" - -// -// Definitions ... - -// -enum ENUM_XHULLC_BUFFERS -{ - XHULLC_UP_LINE = 0, - XHULLC_DOWN_LINE = 2, -}; - -// -// Input Models ... -struct XHULLInputs -{ - // - // Props ... - // - // Market ... - int length; // Length - double divisor; // Divisor (Speed) - - // - // Calculation ... - ENUM_APPLIED_PRICE upAppliedTo; // Up Zone Applied to - ENUM_APPLIED_PRICE downAppliedTo; // Down Zone Applied to - - // - // Presentation ... - bool showUpZone; // Show Up Zone - bool showDownZone; // Show Down Zone - - // - // Constructor(s) ... - XHULLInputs() - { - // - Clean(); - } - - // - // Tools ... - - // - // Clean ... - void Clean() - { - // - // Market ... - length = 0; - divisor = 0; - - // - // Calculation ... - upAppliedTo = PRICE_HIGH; - downAppliedTo = PRICE_LOW; - - // - // Presentation ... - showUpZone = false; - showDownZone = false; - } - - // - // Default ... - void Default() - { - // - // Market ... - length = 72; - divisor = 2.0; - - // - // Calculation ... - upAppliedTo = PRICE_HIGH; - downAppliedTo = PRICE_LOW; - - // - // Presentation ... - showUpZone = true; - showDownZone = true; - } - - // - // Validate ... - bool IsValid() - { - // - bool result = false; - - // - result = - // - length >= 9 && - divisor >= 0.5 - // - ; - - // - return result; - } - - // - // Retrieve MAx Length ... - int Max() - { - // - int result = 0; - - // - result = MathMax(0, length); - - // - return result; - } -}; - -// -// Define Conditions ... -struct XHULLConditions -{ - // - // Common ... - string symbol; - ENUM_TIMEFRAMES period; - datetime time; - - // - // Buffers ... - double up[]; - double down[]; - - // - // Conditions ... - - // - bool isBullish; - bool isBearish; - bool isUpBullish; - bool isUpBearish; - bool isDownBullish; - bool isDownBearish; - bool isSwitchedToBullish; - bool isSwitchedToBearish; - - // - void Clean() - { - // - Clean(up); - Clean(down); - - // - ArraySetAsSeries(up, true); - ArraySetAsSeries(down, true); - - // - isBullish = false; - isBearish = false; - isUpBullish = false; - isUpBearish = false; - isDownBullish = false; - isDownBearish = false; - isSwitchedToBullish = false; - isSwitchedToBearish = false; - } - - // - void GenerateScore( - double &bullishScore, - double &bearishScore // - ) - { - // - bullishScore = 0; - bearishScore = 0; - - // - if (isBullish) - { - bullishScore++; - } - if (isUpBullish) - { - bullishScore++; - } - if (isDownBullish) - { - bullishScore++; - } - if (isSwitchedToBullish) - { - bullishScore++; - } - - // - if (isBearish) - { - bearishScore++; - } - if (isUpBearish) - { - bearishScore++; - } - if (isDownBearish) - { - bearishScore++; - } - if (isSwitchedToBearish) - { - bearishScore++; - } - } - - // - 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 = - // - ToString("isBullish", isBullish, ignoreFalseConditions, separator) + - ToString("isBearish", isBearish, ignoreFalseConditions, separator) + - ToString("isUpBullish", isUpBullish, ignoreFalseConditions, separator) + - ToString("isUpBearish", isUpBearish, ignoreFalseConditions, separator) + - ToString("isDownBullish", isDownBullish, ignoreFalseConditions, separator) + - ToString("isDownBearish", isDownBearish, ignoreFalseConditions, separator) + - ToString("isSwitchedToBullish", isSwitchedToBullish, ignoreFalseConditions, separator) + - ToString("isSwitchedToBearish", isSwitchedToBearish, ignoreFalseConditions, separator) + - "" - // - ; - - // - result = - // - "[" + GetTag() + "]" + separator + - (onlyConditions - ? "" - : commonStr) + - (!includeScores - ? "" - : scoresStr) + - " " + separator + - (onlyCommons - ? "" - : conditionsStr) + - "" - // - ; - - // - return result; - } - - // - string GetTag() - { - return "XHULL"; - } -}; - -// -// Class ... -class XSCXHULLHelper : public XSCBaseHelper -{ - // - // Public ... -public: - // - // Props ... - - // - // Constructors ... - XSCXHULLHelper() : XSCBaseHelper(_Symbol, _Period) - { - } - - // - // Deconstructor ... - ~XSCXHULLHelper() {} - - // - // Tools ... - bool Init( - string symbol, // Trading Symbol - ENUM_TIMEFRAMES period, // Trading Period - XHULLInputs &inputs // Inputs - ) - { - // - bool result = false; - - // - mSymbol = symbol; - mPeriod = period; - - // - result = inputs.IsValid(); - if (!result) - { - return result; - } - - // - mInputs = inputs; - - // - // ArraySetAsSeries(mainBuffer, true); - mHandler = iCustom( - mSymbol, - mPeriod, - "x-saherelm.xhull", - // - // Inputs ... - // - // Market ... - "", - mInputs.length, // Length - mInputs.divisor, // Divisor (Speed) - // - // Calculation ... - "", - mInputs.upAppliedTo, // Up Zone Applied to - mInputs.downAppliedTo, // Down Zone Applied to - // - // Presentation ... - "", - mInputs.showUpZone, // Show Up Zone - mInputs.showDownZone // Show Down Zone - // - ); - result = mHandler != INVALID_HANDLE; - if (!result) - { - return result; - } - - // - return result; - } - - // - // Inputs ... - - // - XHULLInputs GetInputs() - { - return mInputs; - } - - // - bool SetInputs( - XHULLInputs &inputs // Configs - ) - { - // - return Init( - mSymbol, - mPeriod, - inputs - // - ); - } - - // - // Buffers ... - - // - double GetUp( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - int count = ArraySize(upBuffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return upBuffer[barIndex]; - } - - // - // Copy Required Items ... - int CopyUp( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - upBuffer, - buffer, - forceClean - // - ); - } - - // - double GetDown( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - int count = ArraySize(downBuffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return downBuffer[barIndex]; - } - - // - // Copy Required Items ... - int CopyDown( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - downBuffer, - buffer, - forceClean - // - ); - } - - // - bool GetConditions( - XHULLConditions &conditions, // - int barIndex = 0, // - int loopback = 4 // - ) - { - // - bool result = true; - - // - if (loopback < 4) - { - loopback = 4; - } - - // - conditions.Clean(); - - // - conditions.symbol = mSymbol; - conditions.period = mPeriod; - conditions.time = TimeCurrent(); - - // - int zIndex = barIndex; - int cIndex = zIndex + 1; - int pIndex = cIndex + 1; - int ppIndex = pIndex + 1; - - // - CopyUp( - zIndex, - loopback, - conditions.up // - ); - CopyDown( - zIndex, - loopback, - conditions.down // - ); - - // - // Calculate Conditions ... - - // - bool isUpBullish = conditions.up[cIndex] > conditions.up[pIndex]; - bool isUpBearish = conditions.up[cIndex] < conditions.up[pIndex]; - - // - bool isUpBullishPrev = conditions.up[pIndex] > conditions.up[ppIndex]; - bool isUpBearishPrev = conditions.up[pIndex] < conditions.up[ppIndex]; - - // - bool isDownBullish = conditions.down[cIndex] > conditions.down[pIndex]; - bool isDownBearish = conditions.down[cIndex] < conditions.down[pIndex]; - - // - bool isDownBullishPrev = conditions.down[pIndex] > conditions.down[ppIndex]; - bool isDownBearishPrev = conditions.down[pIndex] < conditions.down[ppIndex]; - - // - bool isBullish = isUpBullish && - isDownBullish; - bool isBearish = isUpBearish && - isDownBearish; - - // - bool isBullishPrev = isUpBullishPrev && - isDownBullishPrev; - bool isBearishPrev = isUpBearishPrev && - isDownBearishPrev; - - // - bool isSwitchedToBullish = isBullish && - !isBullishPrev; - bool isSwitchedToBearish = isBearish && - !isBearishPrev; - - // - conditions.isBullish = isBullish; - conditions.isBearish = isBearish; - conditions.isUpBullish = isUpBullish; - conditions.isUpBearish = isUpBearish; - conditions.isDownBullish = isDownBullish; - conditions.isDownBearish = isDownBearish; - conditions.isSwitchedToBullish = isSwitchedToBullish; - conditions.isSwitchedToBearish = isSwitchedToBearish; - - // - return result; - } - - // - // Protected ... -protected: - // - // Private ... -private: - // - // Props ... - XHULLInputs mInputs; // Inputs ... - - // - // Buffers ... - double upBuffer[]; - double downBuffer[]; - - // - // Tools ... - - // - // Calculate Values Until Now ... - void Calculate() - { - // - int totalBars = CountBars(); - if (totalBars > 1000) { - totalBars = 1000; - } - - // - // Up Buffer ... - CopyBuffer( - mHandler, - XHULLC_UP_LINE, - 0, - totalBars, - upBuffer - // - ); - - // - // Down Buffer ... - CopyBuffer( - mHandler, - XHULLC_DOWN_LINE, - 0, - totalBars, - downBuffer - // - ); - } -}; - -// -// Tools ... \ No newline at end of file diff --git a/Documents/Pack/V1.0/Source/Helpers/x-saherelm.xich.helper.mq5 b/Documents/Pack/V1.0/Source/Helpers/x-saherelm.xich.helper.mq5 deleted file mode 100644 index 30e060e4..00000000 --- a/Documents/Pack/V1.0/Source/Helpers/x-saherelm.xich.helper.mq5 +++ /dev/null @@ -1,1565 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Helper Class Library -// ---------------------------------------------- -// Name: XSCXICHHelper -// 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 - -// -#include "../Classes/x-saherelm.xhelper.class.mq5" - -// -// Definitions ... -// -// Ichimoku Lines Calculator Mode ... -enum ENUM_XICH_CALCULATION_MODE -{ - // - X_XICH_HH_LL_MODE = 1, // Highest High and Lowest Low - X_XICH_HO_LC_MODE = 2, // Highest Open and Lowest Close -}; - -// -enum ENUM_XICH_BUFFERS -{ - X_ICH_TEANKANSEN_LINE = 0, - X_ICH_KIJUNSEN_LINE = 1, - X_ICH_CHIKOUSPAN_LINE = 4, - X_ICH_SENKOUSPANA_LINE = 5, - X_ICH_SENKOUSPANB_LINE = 6, -}; - -// -// Input Models ... -struct XICHInputs -{ - // - // Props ... - - // - // Market ... - // - // Tenkan Sen ... - int tenkanSenLength; // Length - ENUM_XICH_CALCULATION_MODE tenkanSenMode; // Calculation Mode - - // - // Kijun Sen ... - int kijunSenLength; // Length - ENUM_XICH_CALCULATION_MODE kijunSenMode; // Calculation Mode - - // - // Senkou Span B ... - int senkouSpanBLength; // Length - ENUM_XICH_CALCULATION_MODE senkouSpanBMode; // Calculation Mode - - // - // Chikou Span ... - ENUM_APPLIED_PRICE chikuoSpanAppliedTo; // Price Type - - // - // Presentation ... - bool showTenkanSen; // Show Tenkan Sen - bool showKijunSen; // Show Kijun Sen - bool showKijunSenPlus; // Show Kijun Sen + - bool showKijunSenNegative; // Show Kijun Sen - - bool showChikouSpan; // Show Chikou Span - bool showSenkouSpanA; // Show Senkou Span A - bool showSenkouSpanB; // Show Senkou Span B - bool showKumo; // Show Kumo - bool shiftKumo; // Shift Kumo to Future - - // - // Constructor(s) ... - XICHInputs() - { - // - Clean(); - } - - // - // Tools ... - - // - // Clean ... - void Clean() - { - // - kijunSenLength = 0; - tenkanSenLength = 0; - senkouSpanBLength = 0; - - // - kijunSenMode = X_XICH_HH_LL_MODE; - tenkanSenMode = X_XICH_HH_LL_MODE; - senkouSpanBMode = X_XICH_HH_LL_MODE; - - // - chikuoSpanAppliedTo = PRICE_CLOSE; - - // - showTenkanSen = false; - showKijunSen = false; - showKijunSenPlus = false; - showKijunSenNegative = false; - showChikouSpan = false; - showSenkouSpanA = false; - showSenkouSpanB = false; - showKumo = false; - shiftKumo = true; - } - - // - // Default ... - void Default() - { - // - kijunSenLength = 26; - tenkanSenLength = 9; - senkouSpanBLength = 52; - - // - kijunSenMode = X_XICH_HH_LL_MODE; - tenkanSenMode = X_XICH_HH_LL_MODE; - senkouSpanBMode = X_XICH_HH_LL_MODE; - - // - chikuoSpanAppliedTo = PRICE_CLOSE; - - // - showTenkanSen = true; - showKijunSen = true; - showKijunSenPlus = false; - showKijunSenNegative = false; - showChikouSpan = true; - showSenkouSpanA = true; - showSenkouSpanB = true; - showKumo = true; - shiftKumo = true; - } - - // - // Validate ... - bool IsValid() - { - // - bool result = false; - - // - result = - // - tenkanSenLength > 2 && - kijunSenLength > tenkanSenLength && - senkouSpanBLength > kijunSenLength - // - ; - - // - return result; - } - - // - // Retrieve MAx Length ... - int Max() - { - // - int result = 0; - - // - result = MathMax(result, tenkanSenLength); - result = MathMax(result, kijunSenLength); - result = MathMax(result, senkouSpanBLength); - - // - return result; - } -}; - -// -// Define Conditions ... -struct XICHConditions -{ - // - // Common ... - string symbol; - ENUM_TIMEFRAMES period; - datetime time; - - // - // Buffers ... - double tenkanSen[]; - double kijunSen[]; - double chikouSpan[]; - double senkouSpanA[]; - double senkouSpanB[]; - double futureSenkouSpanA[]; - double futureSenkouSpanB[]; - - // - // Conditions ... - - // - bool isClosedOverKijunSen; - bool isClosedUnderKijunSen; - bool isTenkanSenOverKijunSen; - bool isTenkanSenUnderKijunSen; - bool isTenkanSenCrossedOverKijunSen; - bool isTenkanSenCrossedUnderKijunSen; - - // - bool isSenkouSpanAOverB; - bool isSenkouSpanAUnderB; - bool isSenkouSpanAOverLast; - bool isSenkouSpanAUnderLast; - bool isFutureSenkouSpanAOverB; - bool isFutureSenkouSpanAUnderB; - bool isFutureSenkouSpanAOverLast; - bool isFutureSenkouSpanAUnderLast; - - // - bool isSenkouSpanACrossedOverB; - bool isSenkouSpanACrossedUnderB; - bool isSenkouSpanACrossedOverLast; - bool isSenkouSpanACrossedUnderLast; - bool isFutureSenkouSpanACrossedOverB; - bool isFutureSenkouSpanACrossedUnderB; - bool isFutureSenkouSpanACrossedOverLast; - bool isFutureSenkouSpanACrossedUnderLast; - - // - void Clean() - { - // - Clean(tenkanSen); - Clean(kijunSen); - Clean(chikouSpan); - Clean(senkouSpanA); - Clean(senkouSpanB); - Clean(futureSenkouSpanA); - Clean(futureSenkouSpanB); - - // - ArraySetAsSeries(tenkanSen, true); - ArraySetAsSeries(kijunSen, true); - ArraySetAsSeries(chikouSpan, true); - ArraySetAsSeries(senkouSpanA, true); - ArraySetAsSeries(senkouSpanB, true); - ArraySetAsSeries(futureSenkouSpanA, true); - ArraySetAsSeries(futureSenkouSpanB, true); - - // - isClosedOverKijunSen = false; - isClosedUnderKijunSen = false; - isTenkanSenOverKijunSen = false; - isTenkanSenUnderKijunSen = false; - isTenkanSenCrossedOverKijunSen = false; - isTenkanSenCrossedUnderKijunSen = false; - - // - isSenkouSpanAOverB = false; - isSenkouSpanAUnderB = false; - isSenkouSpanAOverLast = false; - isSenkouSpanAUnderLast = false; - isFutureSenkouSpanAOverB = false; - isFutureSenkouSpanAUnderB = false; - isFutureSenkouSpanAOverLast = false; - isFutureSenkouSpanAUnderLast = false; - - // - isSenkouSpanACrossedOverB = false; - isSenkouSpanACrossedUnderB = false; - isSenkouSpanACrossedOverLast = false; - isSenkouSpanACrossedUnderLast = false; - isFutureSenkouSpanACrossedOverB = false; - isFutureSenkouSpanACrossedUnderB = false; - isFutureSenkouSpanACrossedOverLast = false; - isFutureSenkouSpanACrossedUnderLast = false; - } - - // - void GenerateScore( - double &bullishScore, - double &bearishScore // - ) - { - // - bullishScore = 0; - bearishScore = 0; - - // - if (isClosedOverKijunSen) - { - bullishScore++; - } - if (isTenkanSenOverKijunSen) - { - bullishScore++; - } - if (isTenkanSenCrossedOverKijunSen) - { - bullishScore++; - } - if (isSenkouSpanAOverB) - { - bullishScore++; - } - if (isSenkouSpanAOverLast) - { - bullishScore++; - } - if (isFutureSenkouSpanAOverB) - { - bullishScore++; - } - if (isFutureSenkouSpanAOverLast) - { - bullishScore++; - } - if (isSenkouSpanACrossedOverB) - { - bullishScore++; - } - if (isSenkouSpanACrossedOverLast) - { - bullishScore++; - } - if (isFutureSenkouSpanACrossedOverB) - { - bullishScore++; - } - if (isFutureSenkouSpanACrossedOverLast) - { - bullishScore++; - } - - // - if (isClosedUnderKijunSen) - { - bearishScore++; - } - if (isTenkanSenUnderKijunSen) - { - bearishScore++; - } - if (isTenkanSenCrossedUnderKijunSen) - { - bearishScore++; - } - if (isSenkouSpanAUnderB) - { - bearishScore++; - } - if (isSenkouSpanAUnderLast) - { - bearishScore++; - } - if (isFutureSenkouSpanAUnderB) - { - bearishScore++; - } - if (isFutureSenkouSpanAUnderLast) - { - bearishScore++; - } - if (isSenkouSpanACrossedUnderB) - { - bearishScore++; - } - if (isSenkouSpanACrossedUnderLast) - { - bearishScore++; - } - if (isFutureSenkouSpanACrossedUnderB) - { - bearishScore++; - } - if (isFutureSenkouSpanACrossedUnderLast) - { - bearishScore++; - } - } - - // - 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 = - // - ToString("isClosedOverKijunSen", isClosedOverKijunSen, ignoreFalseConditions, separator) + - ToString("isClosedUnderKijunSen", isClosedUnderKijunSen, ignoreFalseConditions, separator) + - ToString("isTenkanSenOverKijunSen", isTenkanSenOverKijunSen, ignoreFalseConditions, separator) + - ToString("isTenkanSenUnderKijunSen", isTenkanSenUnderKijunSen, ignoreFalseConditions, separator) + - ToString("isTenkanSenCrossedOverKijunSen", isTenkanSenCrossedOverKijunSen, ignoreFalseConditions, separator) + - ToString("isTenkanSenCrossedUnderKijunSen", isTenkanSenCrossedUnderKijunSen, ignoreFalseConditions, separator) + - // - ToString("isSenkouSpanAOverB", isSenkouSpanAOverB, ignoreFalseConditions, separator) + - ToString("isSenkouSpanAUnderB", isSenkouSpanAUnderB, ignoreFalseConditions, separator) + - ToString("isSenkouSpanAOverLast", isSenkouSpanAOverLast, ignoreFalseConditions, separator) + - ToString("isSenkouSpanAUnderLast", isSenkouSpanAUnderLast, ignoreFalseConditions, separator) + - ToString("isFutureSenkouSpanAOverB", isFutureSenkouSpanAOverB, ignoreFalseConditions, separator) + - ToString("isFutureSenkouSpanAUnderB", isFutureSenkouSpanAUnderB, ignoreFalseConditions, separator) + - ToString("isFutureSenkouSpanAOverLast", isFutureSenkouSpanAOverLast, ignoreFalseConditions, separator) + - ToString("isFutureSenkouSpanAUnderLast", isFutureSenkouSpanAUnderLast, ignoreFalseConditions, separator) + - // - ToString("isSenkouSpanACrossedOverB", isSenkouSpanACrossedOverB, ignoreFalseConditions, separator) + - ToString("isSenkouSpanACrossedUnderB", isSenkouSpanACrossedUnderB, ignoreFalseConditions, separator) + - ToString("isSenkouSpanACrossedOverLast", isSenkouSpanACrossedOverLast, ignoreFalseConditions, separator) + - ToString("isSenkouSpanACrossedUnderLast", isSenkouSpanACrossedUnderLast, ignoreFalseConditions, separator) + - ToString("isFutureSenkouSpanACrossedOverB", isFutureSenkouSpanACrossedOverB, ignoreFalseConditions, separator) + - ToString("isFutureSenkouSpanACrossedUnderB", isFutureSenkouSpanACrossedUnderB, ignoreFalseConditions, separator) + - ToString("isFutureSenkouSpanACrossedOverLast", isFutureSenkouSpanACrossedOverLast, ignoreFalseConditions, separator) + - ToString("isFutureSenkouSpanACrossedUnderLast", isFutureSenkouSpanACrossedUnderLast, ignoreFalseConditions, separator) + - "" - // - ; - - // - result = - // - "[" + GetTag() + "]" + separator + - (onlyConditions - ? "" - : commonStr) + - (!includeScores - ? "" - : scoresStr) + - " " + separator + - (onlyCommons - ? "" - : conditionsStr) + - "" - // - ; - - // - return result; - } - - // - string GetTag() - { - return "XICH"; - } - - // - bool HasLongConditions() - { - // - bool result; - - // - int zIndex = 0; - int cIndex = zIndex + 1; - int pIndex = cIndex + 1; - - // - XOHCL cBar; - result = cBar.Init( - symbol, - period, - cIndex // - ); - if (!result) - { - return result; - } - - // - XOHCL pBar; - result = pBar.Init( - symbol, - period, - pIndex // - ); - if (!result) - { - return result; - } - - // - bool isCloseOverSenkouSpanA = cBar.close > senkouSpanA[cIndex]; - - // - bool isBaseBullish = isCloseOverSenkouSpanA && - isSenkouSpanAOverB && - isSenkouSpanAOverLast; - - // - bool isKijunSenOverSenkouSpanA = kijunSen[cIndex] > senkouSpanA[cIndex]; - - // - bool isCloseOverTenkanSen = cBar.close > tenkanSen[cIndex]; - - // - bool isPriceCloseCrossedUpTenkanSen = pBar.close <= tenkanSen[pIndex] && - cBar.close > tenkanSen[cIndex]; - - // - double cKumoUpper = MathMax(senkouSpanA[cIndex], senkouSpanB[cIndex]); - double pKumoUpper = MathMax(senkouSpanA[pIndex], senkouSpanB[pIndex]); - - // - double cKumoLower = MathMin(senkouSpanA[cIndex], senkouSpanB[cIndex]); - double pKumoLower = MathMin(senkouSpanA[pIndex], senkouSpanB[pIndex]); - - // - bool isTenkanSenOverKumo = tenkanSen[cIndex] > cKumoUpper; - bool isTenkanSenOverKumoPrev = tenkanSen[pIndex] > pKumoUpper; - - // - bool isTenkanSenUnderKumo = tenkanSen[cIndex] < cKumoLower; - bool isTenkanSenUnderKumoPrev = tenkanSen[pIndex] < pKumoLower; - - // - bool isTenkanSenCrossedOverKumo = isTenkanSenOverKumo && - !isTenkanSenOverKumoPrev; - - // - bool isTenkanSenCrossedUnderKumo = isTenkanSenUnderKumo && - !isTenkanSenUnderKumoPrev; - - // - bool condition1 = - isBaseBullish && - isCloseOverTenkanSen && - isKijunSenOverSenkouSpanA && - isTenkanSenCrossedOverKijunSen; - - // - bool condition2 = - isBaseBullish && - isCloseOverTenkanSen && - isKijunSenOverSenkouSpanA && - isTenkanSenOverKijunSen && - isSenkouSpanACrossedOverB; - - // - bool condition3 = - isBaseBullish && - isKijunSenOverSenkouSpanA && - isPriceCloseCrossedUpTenkanSen && - isTenkanSenOverKijunSen; - - // - bool condition4 = - isCloseOverTenkanSen && - isTenkanSenCrossedOverKumo && - isTenkanSenOverKijunSen && - isFutureSenkouSpanAOverB && - isFutureSenkouSpanAOverLast; - - // - result = - // - condition1 - // - || - // - condition2 - // - || - // - condition3 - // - || - // - condition4 - // - ; - - // - return result; - } - - // - bool HasShortConditions() - { - // - bool result = false; - - // - int zIndex = 0; - int cIndex = zIndex + 1; - int pIndex = cIndex + 1; - - // - XOHCL cBar; - result = cBar.Init( - symbol, - period, - cIndex // - ); - if (!result) - { - return result; - } - - // - XOHCL pBar; - result = pBar.Init( - symbol, - period, - pIndex // - ); - if (!result) - { - return result; - } - - // - bool isCloseUnderSenkouSpanB = cBar.close < senkouSpanB[cIndex]; - - // - bool isBaseBearish = isCloseUnderSenkouSpanB && - isSenkouSpanAUnderB && - isSenkouSpanAUnderLast; - - // - bool isKijunSenUnderSenkouSpanB = kijunSen[cIndex] < senkouSpanB[cIndex]; - - // - bool isCloseUnderTenkanSen = cBar.close < tenkanSen[cIndex]; - - // - bool isPriceCloseCrossedDownTenkanSen = pBar.close >= tenkanSen[pIndex] && - cBar.close < tenkanSen[cIndex]; - - // - double cKumoUpper = MathMax(senkouSpanA[cIndex], senkouSpanB[cIndex]); - double pKumoUpper = MathMax(senkouSpanA[pIndex], senkouSpanB[pIndex]); - - // - double cKumoLower = MathMin(senkouSpanA[cIndex], senkouSpanB[cIndex]); - double pKumoLower = MathMin(senkouSpanA[pIndex], senkouSpanB[pIndex]); - - // - bool isTenkanSenOverKumo = tenkanSen[cIndex] > cKumoUpper; - bool isTenkanSenOverKumoPrev = tenkanSen[pIndex] > pKumoUpper; - - // - bool isTenkanSenUnderKumo = tenkanSen[cIndex] < cKumoLower; - bool isTenkanSenUnderKumoPrev = tenkanSen[pIndex] < pKumoLower; - - // - bool isTenkanSenCrossedOverKumo = isTenkanSenOverKumo && - !isTenkanSenOverKumoPrev; - - // - bool isTenkanSenCrossedUnderKumo = isTenkanSenUnderKumo && - !isTenkanSenUnderKumoPrev; - - // - bool condition1 = - isBaseBearish && - isCloseUnderTenkanSen && - isKijunSenUnderSenkouSpanB && - isTenkanSenCrossedUnderKijunSen; - - // - bool condition2 = - isBaseBearish && - isCloseUnderTenkanSen && - isKijunSenUnderSenkouSpanB && - isTenkanSenUnderKijunSen && - isSenkouSpanACrossedUnderB; - - // - bool condition3 = - isBaseBearish && - isKijunSenUnderSenkouSpanB && - isPriceCloseCrossedDownTenkanSen && - isTenkanSenUnderKijunSen; - - // - bool condition4 = - isCloseUnderTenkanSen && - isTenkanSenCrossedUnderKumo && - isTenkanSenUnderKijunSen && - isFutureSenkouSpanAUnderB && - isFutureSenkouSpanAUnderLast; - - // - result = - // - condition1 - - || - // - condition2 - // - || - // - condition3 - // - || - // - condition4 - // - ; - - // - return result; - } -}; - -// -// Class ... -class XSCXICHHelper : public XSCBaseHelper -{ - // - // Public ... -public: - // - // Props ... - - // - // Constructors ... - XSCXICHHelper() : XSCBaseHelper(_Symbol, _Period) - { - } - - // - // Deconstructor ... - ~XSCXICHHelper() {} - - // - // Tools ... - bool Init( - string symbol, // Trading Symbol - ENUM_TIMEFRAMES period, // Trading Period - XICHInputs &inputs // Inputs - ) - { - // - bool result = false; - - // - mSymbol = symbol; - mPeriod = period; - - // - result = inputs.IsValid(); - if (!result) - { - return result; - } - - // - mInputs = inputs; - - // - ArraySetAsSeries(tenkanSenBuffer, true); - ArraySetAsSeries(kijunSenBuffer, true); - ArraySetAsSeries(chikouSpanBuffer, true); - ArraySetAsSeries(senkouSpanABuffer, true); - ArraySetAsSeries(senkouSpanBBuffer, true); - ArraySetAsSeries(futureSenkouSpanABuffer, true); - ArraySetAsSeries(futureSenkouSpanBBuffer, true); - - // - mHandler = iCustom( - mSymbol, - mPeriod, - "x-saherelm.xich", - // - // Inputs ... - // - // TenkanSen ... - "", - mInputs.tenkanSenLength, - mInputs.tenkanSenMode, - // - // KijunSen ... - "", - mInputs.kijunSenLength, - mInputs.kijunSenMode, - // - // SenkouSpan B ... - "", - mInputs.senkouSpanBLength, - mInputs.senkouSpanBMode, - // - // ChikouSpan ... - "", - mInputs.chikuoSpanAppliedTo, - // - // Presentation ... - "", - mInputs.showTenkanSen, // Show Tenkan Sen - mInputs.showKijunSen, // Show Kijun Sen - mInputs.showKijunSenPlus, // Show Kijun Sen + - mInputs.showKijunSenNegative, // Show Kijun Sen - - mInputs.showChikouSpan, // Show Chikou Span - mInputs.showSenkouSpanA, // Show Senkou Span A - mInputs.showSenkouSpanB, // Show Senkou Span B - mInputs.showKumo, // Show Kumo - mInputs.shiftKumo // Shift Kumo to Future - // - ); - result = mHandler != INVALID_HANDLE; - if (!result) - { - return result; - } - - // - return result; - } - - // - // Inputs ... - - // - XICHInputs GetInputs() - { - return mInputs; - } - - // - bool SetInputs( - XICHInputs &inputs // Configs - ) - { - // - return Init( - mSymbol, - mPeriod, - inputs); - } - - // - // Buffers ... - - // - // TenkanSen ... - - // - double GetTenkanSen( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - return tenkanSenBuffer[barIndex]; - } - - // - // Copy Required Items ... - int CopyTenkanSen( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - tenkanSenBuffer, - buffer, - forceClean - // - ); - } - - // - bool IsSameTenkanSen( - int barIndex, // Start Bar Index - int verifier = 71 // Number of Verifiers - ) - { - // - // Update Calculations ... - Calculate(); - - // - return IsSame( - tenkanSenBuffer, - verifier, - barIndex // - ); - } - - // - // KijunSen ... - - // - double GetKijunSen( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - return kijunSenBuffer[barIndex]; - } - - // - // Copy Required Items ... - int CopyKijunSen( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - kijunSenBuffer, - buffer, - forceClean - // - ); - } - - // - bool IsSameKijunSen( - int barIndex, // Start Bar Index - int verifier = 71 // Number of Verifiers - ) - { - // - // Update Calculations ... - Calculate(); - - // - return IsSame( - kijunSenBuffer, - verifier, - barIndex // - ); - } - - // - // ChikouSpan ... - - // - double GetChikouSpan( - int barIndex // Bar Index - ) - { - // - barIndex -= mInputs.kijunSenLength; - - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - if (barIndex > ArraySize(chikouSpanBuffer)) - { - barIndex = ArraySize(chikouSpanBuffer) - 1; - } - - // - Calculate(); - - // - return chikouSpanBuffer[barIndex]; - } - - // - // Copy Required Items ... - int CopyChikouSpan( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start - mInputs.kijunSenLength, - count, - chikouSpanBuffer, - buffer, - forceClean - // - ); - } - - // - // SenkouSpanA ... - - // - double GetSenkouSpanA( - int barIndex // Bar Index - ) - { - // - Calculate(); - - // - return senkouSpanABuffer[barIndex]; - } - - // - // Copy Required Items ... - int CopySenkouSpanA( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - senkouSpanABuffer, - buffer, - forceClean - // - ); - } - - // - bool IsSameSenkouSpanA( - int barIndex, // Start Bar Index - int verifier = 71 // Number of Verifiers - ) - { - // - // Update Calculations ... - Calculate(); - - // - return IsSame( - senkouSpanABuffer, - verifier, - barIndex // - ); - } - - // - // SenkouSpanB ... - - // - double GetSenkouSpanB( - int barIndex // Bar Index - ) - { - // - Calculate(); - - // - return senkouSpanBBuffer[barIndex + mInputs.kijunSenLength]; - } - - // - // Copy Required Items ... - int CopySenkouSpanB( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - senkouSpanBBuffer, - buffer, - forceClean - // - ); - } - - // - bool IsSameSenkouSpanB( - int barIndex, // Start Bar Index - int verifier = 71 // Number of Verifiers - ) - { - // - // Update Calculations ... - Calculate(); - - // - return IsSame( - senkouSpanBBuffer, - verifier, - barIndex // - ); - } - - // - // Future SenkouSpanA ... - - // - double GetFutureSenkouSpanA( - int barIndex // Bar Index - ) - { - // - barIndex -= mInputs.kijunSenLength; - - // - Calculate(); - - // - return senkouSpanABuffer[barIndex]; - } - - // - // Copy Required Items ... - int CopyFutureSenkouSpanA( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start - mInputs.kijunSenLength, - count, - futureSenkouSpanABuffer, - buffer, - forceClean - // - ); - } - - // - // Future SenkouSpanB ... - - // - double GetFutureSenkouSpanB( - int barIndex // Bar Index - ) - { - // - barIndex -= mInputs.kijunSenLength; - - // - Calculate(); - - // - return senkouSpanBBuffer[barIndex]; - } - - // - // Copy Required Items ... - int CopyFutureSenkouSpanB( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start - mInputs.kijunSenLength, - count, - futureSenkouSpanBBuffer, - buffer, - forceClean - // - ); - } - - // - bool GetConditions( - XICHConditions &conditions, // - int barIndex = 0, // - int loopback = 4 // - ) - { - // - bool result = true; - - // - if (loopback < 4) - { - loopback = 4; - } - - // - conditions.Clean(); - - // - conditions.symbol = mSymbol; - conditions.period = mPeriod; - conditions.time = TimeCurrent(); - - // - int zIndex = barIndex; - int cIndex = zIndex + 1; - int pIndex = cIndex + 1; - int ppIndex = pIndex + 1; - - // - CopyTenkanSen( - zIndex, - loopback, - conditions.tenkanSen // - ); - CopyKijunSen( - zIndex, - loopback, - conditions.kijunSen // - ); - CopyChikouSpan( - zIndex, - loopback, - conditions.chikouSpan // - ); - CopySenkouSpanA( - zIndex, - loopback, - conditions.senkouSpanA // - ); - CopySenkouSpanB( - zIndex, - loopback, - conditions.senkouSpanB // - ); - CopyFutureSenkouSpanA( - zIndex, - loopback, - conditions.futureSenkouSpanA // - ); - CopyFutureSenkouSpanB( - zIndex, - loopback, - conditions.futureSenkouSpanB // - ); - - // - // Calculate Conditions ... - - // - XOHCL cBar; - result = cBar.Init( - _Symbol, - _Period, - cIndex // - ); - if (!result) - { - return result; - } - - // - bool isClosedOverKijunSen = cBar.close > conditions.kijunSen[cIndex]; - bool isClosedUnderKijunSen = cBar.close < conditions.kijunSen[cIndex]; - - // - bool isTenkanSenOverKijunSen = conditions.tenkanSen[cIndex] > conditions.kijunSen[cIndex]; - bool isTenkanSenUnderKijunSen = conditions.tenkanSen[cIndex] < conditions.kijunSen[cIndex]; - - // - bool isTenkanSenOverKijunSenPrev = conditions.tenkanSen[pIndex] > conditions.kijunSen[pIndex]; - bool isTenkanSenUnderKijunSenPrev = conditions.tenkanSen[pIndex] < conditions.kijunSen[pIndex]; - - // - bool isTenkanSenCrossedOverKijunSen = isTenkanSenOverKijunSen && - !isTenkanSenOverKijunSenPrev; - bool isTenkanSenCrossedUnderKijunSen = isTenkanSenUnderKijunSen && - !isTenkanSenUnderKijunSenPrev; - - // - bool isSenkouSpanAOverB = conditions.senkouSpanA[cIndex] > conditions.senkouSpanB[cIndex]; - bool isSenkouSpanAUnderB = conditions.senkouSpanA[cIndex] < conditions.senkouSpanB[cIndex]; - - // - bool isSenkouSpanAOverBPrev = conditions.senkouSpanA[pIndex] > conditions.senkouSpanB[pIndex]; - bool isSenkouSpanAUnderBPrev = conditions.senkouSpanA[pIndex] < conditions.senkouSpanB[pIndex]; - - // - bool isSenkouSpanAOverLast = conditions.senkouSpanA[cIndex] > conditions.senkouSpanA[pIndex]; - bool isSenkouSpanAUnderLast = conditions.senkouSpanA[cIndex] < conditions.senkouSpanA[pIndex]; - - // - bool isSenkouSpanAOverLastPrev = conditions.senkouSpanA[pIndex] > conditions.senkouSpanA[ppIndex]; - bool isSenkouSpanAUnderLastPrev = conditions.senkouSpanA[pIndex] < conditions.senkouSpanA[ppIndex]; - - // - bool isFutureSenkouSpanAOverB = conditions.futureSenkouSpanA[cIndex] > conditions.futureSenkouSpanB[cIndex]; - bool isFutureSenkouSpanAUnderB = conditions.futureSenkouSpanA[cIndex] < conditions.futureSenkouSpanB[cIndex]; - - // - bool isFutureSenkouSpanAOverBPrev = conditions.futureSenkouSpanA[pIndex] > conditions.futureSenkouSpanB[pIndex]; - bool isFutureSenkouSpanAUnderBPrev = conditions.futureSenkouSpanA[pIndex] < conditions.futureSenkouSpanB[pIndex]; - - // - bool isFutureSenkouSpanAOverLast = conditions.futureSenkouSpanA[cIndex] > conditions.futureSenkouSpanA[pIndex]; - bool isFutureSenkouSpanAUnderLast = conditions.futureSenkouSpanA[cIndex] < conditions.futureSenkouSpanA[pIndex]; - - // - bool isFutureSenkouSpanAOverLastPrev = conditions.futureSenkouSpanA[pIndex] > conditions.futureSenkouSpanA[ppIndex]; - bool isFutureSenkouSpanAUnderLastPrev = conditions.futureSenkouSpanA[pIndex] < conditions.futureSenkouSpanA[ppIndex]; - - // - bool isSenkouSpanACrossedOverB = isSenkouSpanAOverB && - !isSenkouSpanAOverBPrev; - bool isSenkouSpanACrossedUnderB = isSenkouSpanAUnderB && - !isSenkouSpanAUnderBPrev; - - // - bool isSenkouSpanACrossedOverLast = isSenkouSpanAOverLast & - !isSenkouSpanAOverLastPrev; - bool isSenkouSpanACrossedUnderLast = isSenkouSpanAUnderLast && - !isSenkouSpanAUnderLastPrev; - - // - bool isFutureSenkouSpanACrossedOverB = isFutureSenkouSpanAOverB && - !isFutureSenkouSpanAOverBPrev; - bool isFutureSenkouSpanACrossedUnderB = isFutureSenkouSpanAUnderB && - !isFutureSenkouSpanAUnderBPrev; - - // - bool isFutureSenkouSpanACrossedOverLast = isFutureSenkouSpanAOverLast && - !isFutureSenkouSpanAOverLastPrev; - bool isFutureSenkouSpanACrossedUnderLast = isFutureSenkouSpanAUnderLast && - !isFutureSenkouSpanAUnderLastPrev; - - // - conditions.isClosedOverKijunSen = isClosedOverKijunSen; - conditions.isClosedUnderKijunSen = isClosedUnderKijunSen; - conditions.isTenkanSenOverKijunSen = isTenkanSenOverKijunSen; - conditions.isTenkanSenUnderKijunSen = isTenkanSenUnderKijunSen; - conditions.isTenkanSenCrossedOverKijunSen = isTenkanSenCrossedOverKijunSen; - conditions.isTenkanSenCrossedUnderKijunSen = isTenkanSenCrossedUnderKijunSen; - conditions.isSenkouSpanAOverB = isSenkouSpanAOverB; - conditions.isSenkouSpanAUnderB = isSenkouSpanAUnderB; - conditions.isSenkouSpanAOverLast = isSenkouSpanAOverLast; - conditions.isSenkouSpanAUnderLast = isSenkouSpanAUnderLast; - conditions.isFutureSenkouSpanAOverB = isFutureSenkouSpanAOverB; - conditions.isFutureSenkouSpanAUnderB = isFutureSenkouSpanAUnderB; - conditions.isFutureSenkouSpanAOverLast = isFutureSenkouSpanAOverLast; - conditions.isFutureSenkouSpanAUnderLast = isFutureSenkouSpanAUnderLast; - conditions.isSenkouSpanACrossedOverB = isSenkouSpanACrossedOverB; - conditions.isSenkouSpanACrossedUnderB = isSenkouSpanACrossedUnderB; - conditions.isSenkouSpanACrossedOverLast = isSenkouSpanACrossedOverLast; - conditions.isSenkouSpanACrossedUnderLast = isSenkouSpanACrossedUnderLast; - conditions.isFutureSenkouSpanACrossedOverB = isFutureSenkouSpanACrossedOverB; - conditions.isFutureSenkouSpanACrossedUnderB = isFutureSenkouSpanACrossedUnderB; - conditions.isFutureSenkouSpanACrossedOverLast = isFutureSenkouSpanACrossedOverLast; - conditions.isFutureSenkouSpanACrossedUnderLast = isFutureSenkouSpanACrossedUnderLast; - - // - return result; - } - - // - // Protected ... -protected: - // - // Private ... -private: - // - // Props ... - XICHInputs mInputs; // Inputs ... - - // - // Buffers ... - double tenkanSenBuffer[]; - double kijunSenBuffer[]; - double chikouSpanBuffer[]; - double senkouSpanABuffer[]; - double senkouSpanBBuffer[]; - double futureSenkouSpanABuffer[]; - double futureSenkouSpanBBuffer[]; - - // - // Tools ... - - // - // Calculate Values Until Now ... - void Calculate() - { - // - int totalBars = CountBars(); - if (totalBars > 1000) { - totalBars = 1000; - } - - // - // TenkanSen ... - CopyBuffer( - mHandler, - X_ICH_TEANKANSEN_LINE, - 0, - totalBars, - tenkanSenBuffer - // - ); - - // - // KijunSen ... - CopyBuffer( - mHandler, - X_ICH_KIJUNSEN_LINE, - 0, - totalBars, - kijunSenBuffer - // - ); - - // - // ChikouSpan ... - CopyBuffer( - mHandler, - X_ICH_CHIKOUSPAN_LINE, - 0, - totalBars, - chikouSpanBuffer - // - ); - - // - // SenkouSpan A ... - CopyBuffer( - mHandler, - X_ICH_SENKOUSPANA_LINE, - 0, - totalBars, - senkouSpanABuffer - // - ); - - // - // SenkouSpan B ... - CopyBuffer( - mHandler, - X_ICH_SENKOUSPANB_LINE, - 0, - totalBars, - senkouSpanBBuffer - // - ); - - // - // SenkouSpan A ... - CopyBuffer( - mHandler, - X_ICH_SENKOUSPANA_LINE, - 0 - mInputs.kijunSenLength, - totalBars, - futureSenkouSpanABuffer - // - ); - - // - // SenkouSpan B ... - CopyBuffer( - mHandler, - X_ICH_SENKOUSPANB_LINE, - 0 - mInputs.kijunSenLength, - totalBars, - futureSenkouSpanBBuffer - // - ); - } -}; - -// -// Tools ... diff --git a/Documents/Pack/V1.0/Source/Helpers/x-saherelm.xmc.helper.mq5 b/Documents/Pack/V1.0/Source/Helpers/x-saherelm.xmc.helper.mq5 deleted file mode 100644 index b2dcdf50..00000000 --- a/Documents/Pack/V1.0/Source/Helpers/x-saherelm.xmc.helper.mq5 +++ /dev/null @@ -1,1111 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Helper Class Library -// ---------------------------------------------- -// Name: XSCXMCHelper -// 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 - -// -#include "../Classes/x-saherelm.xhelper.class.mq5" - -// -// Definitions ... - -// -enum ENUM_XMC_BUFFERS -{ - XMC_FAST_LINE = 0, - XMC_SLOW_LINE = 1, - XMC_VERIFIER_LINE = 2, - XMC_SAR_LINE = 3, -}; - -// -// Input Models ... -struct XMCInputs -{ - // - // Props ... - - // - // Market ... - - // - // Fast ... - int fastLength; // Length - int fastShift; // Shift - ENUM_MA_METHOD fastMethod; // Method - ENUM_APPLIED_PRICE fastAppliedTo; // Applied To - - // - // Slow ... - int slowLength; // Length - int slowShift; // Shift - ENUM_MA_METHOD slowMethod; // Method - ENUM_APPLIED_PRICE slowAppliedTo; // Applied To - - // - // Verifier ... - int verifierLength; // Length - int verifierShift; // Shift - ENUM_MA_METHOD verifierMethod; // Method - ENUM_APPLIED_PRICE verifierAppliedTo; // Applied To - - // - double step; // Sar Step - double maximum; // Sar Maximum - - // - // Presentation ... - bool showFastMa; // Show Fast - bool showSlowMa; // Show Slow - bool showVerifierMa; // Show Verifier - bool showSar; // Show Sar - - // - // Constructor(s) ... - XMCInputs() - { - // - Clean(); - } - - // - // Tools ... - - // - // Clean ... - void Clean() - { - // - fastLength = 0; - fastShift = 0; - fastMethod = 0; - fastAppliedTo = PRICE_CLOSE; - - // - slowLength = 0; - slowShift = 0; - slowMethod = 0; - slowAppliedTo = PRICE_CLOSE; - - // - verifierLength = 0; - verifierShift = 0; - verifierMethod = 0; - verifierAppliedTo = PRICE_CLOSE; - - // - step = 0; - maximum = 0; - - // - showSar = false; - showFastMa = false; - showSlowMa = false; - showVerifierMa = false; - } - - // - // Default ... - void Default() - { - // - fastLength = 21; - fastShift = 0; - fastMethod = MODE_EMA; - fastAppliedTo = PRICE_CLOSE; - - // - slowLength = 50; - slowShift = 0; - slowMethod = MODE_EMA; - slowAppliedTo = PRICE_CLOSE; - - // - verifierLength = 200; - verifierShift = 0; - verifierMethod = MODE_EMA; - verifierAppliedTo = PRICE_CLOSE; - - // - step = 0.02; - maximum = 0.2; - - // - showSar = true; - showFastMa = true; - showSlowMa = true; - showVerifierMa = true; - } - - // - // Validate ... - bool IsValid() - { - // - bool result = false; - - // - result = - // - fastLength > 1 && - slowLength > fastLength && - verifierLength > slowLength && - // - step > 0 && - maximum > step - // - ; - - // - return result; - } - - // - // Retrieve MAx Length ... - int Max() - { - // - int result = 0; - - // - result = MathMax(fastLength, slowLength); - result = MathMax(result, verifierLength); - - // - return result; - } -}; - -// -// Define Conditions ... -struct XMCConditions -{ - // - // Common ... - string symbol; - ENUM_TIMEFRAMES period; - datetime time; - - // - // Buffers ... - double fast[]; - double slow[]; - double verifier[]; - - // - double psar[]; - - // - // Conditions ... - - // - // Trend ... - bool isBullish; - bool isBearish; - bool isSwitchedToBullish; - bool isSwitchedToBearish; - - // - // Fast Slow ... - bool isFastOverSlow; - bool isFastUnderSlow; - bool isFastCrossedOverSlow; - bool isFastCrossedUnderSlow; - - // - // Fast Verifier ... - bool isFastOverVerifier; - bool isFastUnderVerifier; - bool isFastCrossedOverVerifier; - bool isFastCrossedUnderVerifier; - - // - // Slow Verifier ... - bool isSlowOverVerifier; - bool isSlowUnderVerifier; - bool isSlowCrossedOverVerifier; - bool isSlowCrossedUnderVerifier; - - // - bool isSARBullish; - bool isSARBearish; - bool isSARSwitchedToBullish; - bool isSARSwitchedToBearish; - - // - void Clean() - { - // - Clean(fast); - Clean(slow); - Clean(verifier); - - // - ArraySetAsSeries(fast, true); - ArraySetAsSeries(slow, true); - ArraySetAsSeries(verifier, true); - - // - // Trend ... - isBullish = false; - isBearish = false; - isSwitchedToBullish = false; - isSwitchedToBearish = false; - - // - // Fast Slow ... - isFastOverSlow = false; - isFastUnderSlow = false; - isFastCrossedOverSlow = false; - isFastCrossedUnderSlow = false; - - // - // Fast Verifier ... - isFastOverVerifier = false; - isFastUnderVerifier = false; - isFastCrossedOverVerifier = false; - isFastCrossedUnderVerifier = false; - - // - // Slow Verifier ... - isSlowOverVerifier = false; - isSlowUnderVerifier = false; - isSlowCrossedOverVerifier = false; - isSlowCrossedUnderVerifier = false; - - // - isSARBullish = false; - isSARBearish = false; - isSARSwitchedToBullish = false; - isSARSwitchedToBearish = false; - } - - // - void GenerateScore( - double &bullishScore, - double &bearishScore // - ) - { - // - bullishScore = 0; - bearishScore = 0; - - // - // Trend ... - - // - if (isBullish) - { - bullishScore++; - } - if (isSwitchedToBullish) - { - bullishScore++; - } - - // - if (isBearish) - { - bearishScore++; - } - if (isSwitchedToBearish) - { - bearishScore++; - } - - // - // Fast Slow ... - - // - if (isFastOverSlow) - { - bullishScore++; - } - if (isFastCrossedOverSlow) - { - bullishScore++; - } - - // - if (isFastUnderSlow) - { - bearishScore++; - } - if (isFastCrossedUnderSlow) - { - bearishScore++; - } - - // - // Fast Verifier ... - - // - if (isFastOverVerifier) - { - bullishScore++; - } - if (isFastCrossedOverVerifier) - { - bullishScore++; - } - - // - if (isFastUnderVerifier) - { - bearishScore++; - } - if (isFastCrossedUnderVerifier) - { - bearishScore++; - } - - // - // Slow Verifier ... - - // - if (isSlowOverVerifier) - { - bullishScore++; - } - if (isSlowCrossedOverVerifier) - { - bullishScore++; - } - - // - if (isSlowUnderVerifier) - { - bearishScore++; - } - if (isSlowCrossedUnderVerifier) - { - bearishScore++; - } - - // - if (isSARBullish) - { - bullishScore++; - } - if (isSARSwitchedToBullish) - { - bullishScore++; - } - - // - if (isSARBearish) - { - bearishScore++; - } - if (isSARSwitchedToBearish) - { - bearishScore++; - } - } - - // - 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 = - // - // Trend ... - ToString("isBullish", isBullish, ignoreFalseConditions, separator) + - ToString("isBearish", isBearish, ignoreFalseConditions, separator) + - ToString("isSwitchedToBullish", isSwitchedToBullish, ignoreFalseConditions, separator) + - ToString("isSwitchedToBearish", isSwitchedToBearish, ignoreFalseConditions, separator) + - // - // Fast Slow ... - ToString("isFastOverSlow", isFastOverSlow, ignoreFalseConditions, separator) + - ToString("isFastUnderSlow", isFastUnderSlow, ignoreFalseConditions, separator) + - ToString("isFastCrossedOverSlow", isFastCrossedOverSlow, ignoreFalseConditions, separator) + - ToString("isFastCrossedUnderSlow", isFastCrossedUnderSlow, ignoreFalseConditions, separator) + - // - // Fast Verifier ... - ToString("isFastOverVerifier", isFastOverVerifier, ignoreFalseConditions, separator) + - ToString("isFastUnderVerifier", isFastUnderVerifier, ignoreFalseConditions, separator) + - ToString("isFastCrossedOverVerifier", isFastCrossedOverVerifier, ignoreFalseConditions, separator) + - ToString("isFastCrossedUnderVerifier", isFastCrossedUnderVerifier, ignoreFalseConditions, separator) + - // - // Slow Verifier ... - ToString("isSlowOverVerifier", isSlowOverVerifier, ignoreFalseConditions, separator) + - ToString("isSlowUnderVerifier", isSlowUnderVerifier, ignoreFalseConditions, separator) + - ToString("isSlowCrossedOverVerifier", isSlowCrossedOverVerifier, ignoreFalseConditions, separator) + - ToString("isSlowCrossedUnderVerifier", isSlowCrossedUnderVerifier, ignoreFalseConditions, separator) + - // - // Psar ... - ToString("isSARBullish", isSARBullish, ignoreFalseConditions, separator) + - ToString("isSARBearish", isSARBearish, ignoreFalseConditions, separator) + - ToString("isSARSwitchedToBullish", isSARSwitchedToBullish, ignoreFalseConditions, separator) + - ToString("isSARSwitchedToBearish", isSARSwitchedToBearish, ignoreFalseConditions, separator) + - // - "" - // - ; - - // - result = - // - "[" + GetTag() + "]" + separator + - (onlyConditions - ? "" - : commonStr) + - (!includeScores - ? "" - : scoresStr) + - " " + separator + - (onlyCommons - ? "" - : conditionsStr) + - "" - // - ; - - // - return result; - } - - // - string GetTag() - { - return "XMATD"; - } -}; - -// -// Class ... -class XSCXMCHelper : public XSCBaseHelper -{ - // - // Public ... -public: - // - // Props ... - - // - // Constructors ... - XSCXMCHelper() : XSCBaseHelper(_Symbol, _Period) - { - } - - // - // Deconstructor ... - ~XSCXMCHelper() {} - - // - // Tools ... - bool Init( - string symbol, // Trading Symbol - ENUM_TIMEFRAMES period, // Trading Period - XMCInputs &inputs // Inputs - ) - { - // - bool result = false; - - // - mSymbol = symbol; - mPeriod = period; - - // - result = inputs.IsValid(); - if (!result) - { - return result; - } - - // - mInputs = inputs; - - // - ArraySetAsSeries(fastBuffer, true); - ArraySetAsSeries(slowBuffer, true); - ArraySetAsSeries(verifierBuffer, true); - mHandler = iCustom( - mSymbol, - mPeriod, - "x-saherelm.xmc", - // - // Inputs ... - // - // Fast ... - "", - mInputs.fastLength, - mInputs.fastShift, - mInputs.fastMethod, - mInputs.fastAppliedTo, - // - // Slow ... - "", - mInputs.slowLength, - mInputs.slowShift, - mInputs.slowMethod, - mInputs.slowAppliedTo, - // - // Verifier ... - "", - mInputs.verifierLength, - mInputs.verifierShift, - mInputs.verifierMethod, - mInputs.verifierAppliedTo, - // - // Psar ... - "", - mInputs.step, - mInputs.maximum, - // - // Presentation ... - "", - mInputs.showSar, // Show Sar ... - mInputs.showFastMa, // Show Fast - mInputs.showSlowMa, // Show Slow - mInputs.showVerifierMa // Show Verifier - // - ); - result = mHandler != INVALID_HANDLE; - if (!result) - { - return result; - } - - // - return result; - } - - // - // Inputs ... - - // - XMCInputs GetInputs() - { - return mInputs; - } - - // - bool SetInputs( - XMCInputs &inputs // Configs - ) - { - // - return Init( - mSymbol, - mPeriod, - inputs); - } - - // - // Buffers ... - - // - // Fast ... - - // - double GetFast( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - return fastBuffer[barIndex]; - } - - // - // Copy Required Buffer ... - int CopyFast( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - fastBuffer, - buffer, - forceClean - // - ); - } - - // - // Slow ... - - // - double GetSlow( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - return slowBuffer[barIndex]; - } - - // - // Copy Required Buffer ... - int CopySlow( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - slowBuffer, - buffer, - forceClean - // - ); - } - - // - // Verifier ... - - // - double GetVerifier( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - return verifierBuffer[barIndex]; - } - - // - // Copy Required Buffer ... - int CopyVerifier( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - verifierBuffer, - buffer, - forceClean - // - ); - } - - // - // Sar ... - - // - double GetSar( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - return sarBuffer[barIndex]; - } - - // - // Copy Required Buffer ... - int CopySar( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - sarBuffer, - buffer, - forceClean - // - ); - } - - // - bool GetConditions( - XMCConditions &conditions, // - int barIndex = 0, // - int loopback = 3 // - ) - { - // - bool result = true; - - // - if (loopback < 3) - { - loopback = 3; - } - - // - conditions.Clean(); - - // - conditions.symbol = mSymbol; - conditions.period = mPeriod; - conditions.time = TimeCurrent(); - - // - int zIndex = barIndex; - int cIndex = zIndex + 1; - int pIndex = cIndex + 1; - int ppIndex = pIndex + 1; - - // - CopyFast( - zIndex, - loopback, - conditions.fast // - ); - - // - CopySlow( - zIndex, - loopback, - conditions.slow // - ); - - // - CopyVerifier( - zIndex, - loopback, - conditions.verifier // - ); - - // - CopySar( - zIndex, - loopback, - conditions.psar // - ); - - // - // Calculate Conditions ... - - // - // Trend ... - - // - bool isBullish = conditions.fast[cIndex] > conditions.slow[cIndex] && - conditions.slow[cIndex] > conditions.verifier[cIndex]; - bool isBearish = conditions.fast[cIndex] < conditions.slow[cIndex] && - conditions.slow[cIndex] < conditions.verifier[cIndex]; - - // - bool isBullishPrev = conditions.fast[pIndex] > conditions.slow[pIndex] && - conditions.slow[pIndex] > conditions.verifier[pIndex]; - bool isBearishPrev = conditions.fast[pIndex] < conditions.slow[pIndex] && - conditions.slow[pIndex] < conditions.verifier[pIndex]; - - // - bool isSwitchedToBullish = isBullish && - !isBullishPrev; - bool isSwitchedToBearish = isBearish && - !isBearishPrev; - - // - // Set Conditions to Structure ... - conditions.isBullish = isBullish; - conditions.isBearish = isBearish; - conditions.isSwitchedToBullish = isSwitchedToBullish; - conditions.isSwitchedToBearish = isSwitchedToBearish; - - // - // Fast Slow ... - - // - bool isFastOverSlow = conditions.fast[cIndex] > conditions.slow[cIndex]; - bool isFastUnderSlow = conditions.fast[cIndex] < conditions.slow[cIndex]; - - // - bool isFastOverSlowPrev = conditions.fast[pIndex] > conditions.slow[pIndex]; - bool isFastUnderSlowPrev = conditions.fast[pIndex] < conditions.slow[pIndex]; - - // - bool isFastCrossedOverSlow = isFastOverSlow && - !isFastOverSlowPrev; - bool isFastCrossedUnderSlow = isFastUnderSlow && - !isFastUnderSlowPrev; - - // - conditions.isFastOverSlow = isFastOverSlow; - conditions.isFastUnderSlow = isFastUnderSlow; - conditions.isFastCrossedOverSlow = isFastCrossedOverSlow; - conditions.isFastCrossedUnderSlow = isFastCrossedUnderSlow; - - // - // Fast Verifier ... - - // - bool isFastOverVerifier = conditions.fast[cIndex] > conditions.verifier[cIndex]; - bool isFastUnderVerifier = conditions.fast[cIndex] < conditions.verifier[cIndex]; - - // - bool isFastOverVerifierPrev = conditions.fast[pIndex] > conditions.verifier[pIndex]; - bool isFastUnderVerifierPrev = conditions.fast[pIndex] < conditions.verifier[pIndex]; - - // - bool isFastCrossedOverVerifier = isFastOverVerifier && - !isFastOverVerifierPrev; - bool isFastCrossedUnderVerifier = isFastUnderVerifier && - !isFastUnderVerifierPrev; - - // - conditions.isFastOverVerifier = isFastOverVerifier; - conditions.isFastUnderVerifier = isFastUnderVerifier; - conditions.isFastCrossedOverVerifier = isFastCrossedOverVerifier; - conditions.isFastCrossedUnderVerifier = isFastCrossedUnderVerifier; - - // - // Slow Verifier ... - - // - bool isSlowOverVerifier = conditions.slow[cIndex] > conditions.verifier[cIndex]; - bool isSlowUnderVerifier = conditions.slow[cIndex] < conditions.verifier[cIndex]; - - // - bool isSlowOverVerifierPrev = conditions.slow[pIndex] > conditions.verifier[pIndex]; - bool isSlowUnderVerifierPrev = conditions.slow[pIndex] < conditions.verifier[pIndex]; - - // - bool isSlowCrossedOverVerifier = isSlowOverVerifier && - !isSlowOverVerifierPrev; - bool isSlowCrossedUnderVerifier = isSlowUnderVerifier && - !isSlowUnderVerifierPrev; - - // - conditions.isSlowOverVerifier = isSlowOverVerifier; - conditions.isSlowUnderVerifier = isSlowUnderVerifier; - conditions.isSlowCrossedOverVerifier = isSlowCrossedOverVerifier; - conditions.isSlowCrossedUnderVerifier = isSlowCrossedUnderVerifier; - - // - XOHCL cBar; - cBar.Init( - mSymbol, - mPeriod, - cIndex // - ); - - // - XOHCL pBar; - pBar.Init( - mSymbol, - mPeriod, - pIndex // - ); - - // - bool isSARBullish = conditions.psar[cIndex] < cBar.low; - bool isSARBearish = conditions.psar[cIndex] > cBar.high; - - // - bool isSARBullishPrev = conditions.psar[pIndex] < pBar.low; - bool isSARBearishPrev = conditions.psar[pIndex] > pBar.high; - - // - bool isSARSwitchedToBullish = isSARBullish && - !isSARBullishPrev; - bool isSARSwitchedToBearish = isSARBearish && - !isSARBearishPrev; - - // - conditions.isSARBullish = isSARBullish; - conditions.isSARBearish = isSARBearish; - conditions.isSARSwitchedToBullish = isSARSwitchedToBullish; - conditions.isSARSwitchedToBearish = isSARSwitchedToBearish; - - // - return result; - } - - // - // Protected ... -protected: - // - // Private ... -private: - // - // Props ... - XMCInputs mInputs; // Inputs ... - - // - // Buffers ... - // - double sarBuffer[]; - double fastBuffer[]; - double slowBuffer[]; - double verifierBuffer[]; - - // - // Tools ... - - // - // Calculate Values Until Now ... - void Calculate() - { - // - int totalBars = CountBars(); - if (totalBars > 1000) { - totalBars = 1000; - } - - // - // Sar ... - CopyBuffer( - mHandler, - XMC_SAR_LINE, - 0, - totalBars, - sarBuffer - // - ); - - // - // Fast ... - CopyBuffer( - mHandler, - XMC_FAST_LINE, - 0, - totalBars, - fastBuffer - // - ); - - // - // Slow ... - CopyBuffer( - mHandler, - XMC_SLOW_LINE, - 0, - totalBars, - slowBuffer - // - ); - - // - // Verifier ... - CopyBuffer( - mHandler, - XMC_VERIFIER_LINE, - 0, - totalBars, - verifierBuffer - // - ); - } -}; - -// -// Tools ... diff --git a/Documents/Pack/V1.0/Source/Helpers/x-saherelm.xmrb.helper.mq5 b/Documents/Pack/V1.0/Source/Helpers/x-saherelm.xmrb.helper.mq5 deleted file mode 100644 index 2e421600..00000000 --- a/Documents/Pack/V1.0/Source/Helpers/x-saherelm.xmrb.helper.mq5 +++ /dev/null @@ -1,1636 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Helper Class Library -// ---------------------------------------------- -// Name: XSCXMRBHelper -// 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.xhelper.class.mq5" - -// -// Definitions ... - -// -enum ENUM_XMRB_BUFFERS -{ - // - // Ribbon ... - XMRB_FAST_LINE = 0, - XMRB_SLOW_LINE = 1, - // - // Ribbon 1 ... - XMRB_R1_FAST_LINE = 2, - XMRB_R1_SLOW_LINE = 3, - // - // Ribbon 2 ... - XMRB_R2_FAST_LINE = 4, - XMRB_R2_SLOW_LINE = 5, - // - // Ribbon 3 ... - XMRB_R3_FAST_LINE = 6, - XMRB_R3_SLOW_LINE = 7, - // - // Ribbon 4 ... - XMRB_R4_FAST_LINE = 8, - XMRB_R4_SLOW_LINE = 9, - // - // Ribbon 5 ... - XMRB_R5_FAST_LINE = 10, - XMRB_R5_SLOW_LINE = 11, - // - // Ribbon 5 ... - XMRB_R6_FAST_LINE = 12, - XMRB_R6_SLOW_LINE = 13, -}; - -// -// Input Models ... -struct XMRBInputs -{ - // - // Props ... - - // - // Ribbon 1 ... - int fast1Length; // Fast - int slow1Length; // Slow - ENUM_APPLIED_PRICE r1AppliedTo; // AppliedTo - - // - // Ribbon 2 ... - int fast2Length; // Fast - int slow2Length; // Slow - ENUM_APPLIED_PRICE r2AppliedTo; // AppliedTo - - // - // Ribbon 3 ... - int fast3Length; // Fast - int slow3Length; // Slow - ENUM_APPLIED_PRICE r3AppliedTo; // AppliedTo - - // - // Ribbon 4 ... - int fast4Length; // Fast - int slow4Length; // Slow - ENUM_APPLIED_PRICE r4AppliedTo; // AppliedTo - - // - // Ribbon 5 ... - int fast5Length; // Fast - int slow5Length; // Slow - ENUM_APPLIED_PRICE r5AppliedTo; // AppliedTo - - // - // Ribbon 6 ... - int fast6Length; // Fast - int slow6Length; // Slow - ENUM_APPLIED_PRICE r6AppliedTo; // AppliedTo - - // - // Calculation ... - ENUM_MA_METHOD ribbonMode; // Mode - - // - // Presentation ... - bool showFastMa; // Show Fast - bool showSlowMa; // Show Slow - bool showRibbon; // Show Ribbon - - // - // Constructor(s) ... - XMRBInputs() - { - // - Clean(); - } - - // - // Tools ... - - // - // Clean ... - void Clean() - { - // - // Ribbon 1 ... - fast1Length = 0; // Fast - slow1Length = 0; // Slow - r1AppliedTo = PRICE_HIGH; // AppliedTo - - // - // Ribbon 2 ... - fast2Length = 0; // Fast - slow2Length = 0; // Slow - r2AppliedTo = PRICE_OPEN; // AppliedTo - - // - // Ribbon 3 ... - fast3Length = 0; // Fast - slow3Length = 0; // Slow - r3AppliedTo = PRICE_CLOSE; // AppliedTo - - // - // Ribbon 4 ... - fast4Length = 0; // Fast - slow4Length = 0; // Slow - r4AppliedTo = PRICE_MEDIAN; // AppliedTo - - // - // Ribbon 5 ... - fast5Length = 0; // Fast - slow5Length = 0; // Slow - r5AppliedTo = PRICE_TYPICAL; // AppliedTo - - // - // Ribbon 6 ... - fast6Length = 0; // Fast - slow6Length = 0; // Slow - r6AppliedTo = PRICE_LOW; // AppliedTo - - // - // Calculation ... - ribbonMode = MODE_EMA; // Mode - - // - // Presentation ... - showFastMa = false; // Show Fast - showSlowMa = false; // Show Slow - showRibbon = false; // Show Ribbon - } - - // - // Default ... - void Default() - { - // - // Ribbon 1 ... - fast1Length = 50; // Fast - slow1Length = 100; // Slow - r1AppliedTo = PRICE_HIGH; // AppliedTo - - // - // Ribbon 2 ... - fast2Length = 50; // Fast - slow2Length = 100; // Slow - r2AppliedTo = PRICE_OPEN; // AppliedTo - - // - // Ribbon 3 ... - fast3Length = 50; // Fast - slow3Length = 100; // Slow - r3AppliedTo = PRICE_CLOSE; // AppliedTo - - // - // Ribbon 4 ... - fast4Length = 50; // Fast - slow4Length = 100; // Slow - r4AppliedTo = PRICE_MEDIAN; // AppliedTo - - // - // Ribbon 5 ... - fast5Length = 50; // Fast - slow5Length = 100; // Slow - r5AppliedTo = PRICE_TYPICAL; // AppliedTo - - // - // Ribbon 6 ... - fast6Length = 50; // Fast - slow6Length = 100; // Slow - r6AppliedTo = PRICE_LOW; // AppliedTo - - // - // Calculation ... - ribbonMode = MODE_EMA; // Mode - - // - // Presentation ... - showFastMa = true; // Show Fast - showSlowMa = true; // Show Slow - showRibbon = false; // Show Ribbon - } - - // - // Validate ... - bool IsValid() - { - // - bool result = false; - - // - result = - // - (fast1Length > 2 && - fast2Length > 2 && - fast3Length > 2 && - fast4Length > 2 && - fast5Length > 2 && - fast6Length > 2 && - slow1Length > fast1Length && - slow2Length > fast2Length && - slow3Length > fast3Length && - slow4Length > fast4Length && - slow5Length > fast5Length && - slow6Length > fast6Length - // - ) - // - ; - - // - return result; - } - - // - // Retrieve MAx Length ... - int Max() - { - // - int result = 0; - - // - result = MathMax(fast1Length, fast2Length); - result = MathMax(result, fast3Length); - result = MathMax(result, fast4Length); - result = MathMax(result, fast5Length); - result = MathMax(result, fast6Length); - - // - result = MathMax(result, slow1Length); - result = MathMax(result, slow2Length); - result = MathMax(result, slow3Length); - result = MathMax(result, slow4Length); - result = MathMax(result, slow5Length); - result = MathMax(result, slow6Length); - - // - return result; - } -}; - -// -// Define Conditions ... -struct XMRBConditions -{ - // - // Common ... - string symbol; - ENUM_TIMEFRAMES period; - datetime time; - - // - // Buffers ... - - // - double fast[]; - double slow[]; - - // - // Conditions ... - - // - bool isFastOverSlow; - bool isFastUnderSlow; - bool isFastCrossedOverSlow; - bool isFastCrossedUnderSlow; - - // - void Clean() - { - // - Clean(fast); - Clean(slow); - - // - ArraySetAsSeries(fast, true); - ArraySetAsSeries(slow, true); - - // - isFastOverSlow = false; - isFastUnderSlow = false; - isFastCrossedOverSlow = false; - isFastCrossedUnderSlow = false; - } - - // - void GenerateScore( - double &bullishScore, - double &bearishScore // - ) - { - // - bullishScore = 0; - bearishScore = 0; - - // - if (isFastOverSlow) - { - bullishScore++; - } - if (isFastCrossedOverSlow) - { - bullishScore++; - } - - // - if (isFastUnderSlow) - { - bearishScore++; - } - if (isFastCrossedUnderSlow) - { - bearishScore++; - } - } - - // - 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 = - // - ToString("isFastOverSlow", isFastOverSlow, ignoreFalseConditions, separator) + - ToString("isFastUnderSlow", isFastUnderSlow, ignoreFalseConditions, separator) + - ToString("isFastCrossedOverSlow", isFastCrossedOverSlow, ignoreFalseConditions, separator) + - ToString("isFastCrossedUnderSlow", isFastCrossedUnderSlow, ignoreFalseConditions, separator) + - "" - // - ; - - // - result = - // - "[" + GetTag() + "]" + separator + - (onlyConditions - ? "" - : commonStr) + - (!includeScores - ? "" - : scoresStr) + - " " + separator + - (onlyCommons - ? "" - : conditionsStr) + - "" - // - ; - - // - return result; - } - - // - string GetTag() - { - return "XMRB"; - } -}; - -// -// Class ... -class XSCXMRBHelper : public XSCBaseHelper -{ - // - // Public ... -public: - // - // Props ... - - // - // Constructors ... - XSCXMRBHelper() : XSCBaseHelper(_Symbol, _Period) - { - } - - // - // Deconstructor ... - ~XSCXMRBHelper() {} - - // - // Tools ... - bool Init( - string symbol, // Trading Symbol - ENUM_TIMEFRAMES period, // Trading Period - XMRBInputs &inputs // Inputs - ) - { - // - bool result = false; - - // - mSymbol = symbol; - mPeriod = period; - - // - result = inputs.IsValid(); - if (!result) - { - return result; - } - - // - mInputs = inputs; - - // - ArraySetAsSeries(fastBuffer, true); - ArraySetAsSeries(slowBuffer, true); - ArraySetAsSeries(r1FastBuffer, true); - ArraySetAsSeries(r1SlowBuffer, true); - ArraySetAsSeries(r2FastBuffer, true); - ArraySetAsSeries(r2SlowBuffer, true); - ArraySetAsSeries(r3FastBuffer, true); - ArraySetAsSeries(r3SlowBuffer, true); - ArraySetAsSeries(r4FastBuffer, true); - ArraySetAsSeries(r4SlowBuffer, true); - ArraySetAsSeries(r5FastBuffer, true); - ArraySetAsSeries(r5SlowBuffer, true); - ArraySetAsSeries(r6FastBuffer, true); - ArraySetAsSeries(r6SlowBuffer, true); - - // - mHandler = iCustom( - mSymbol, - mPeriod, - "x-saherelm.xmrb", - // - // Inputs ... - // - // Ribbon 1 ... - "", - mInputs.fast1Length, // Fast - mInputs.slow1Length, // Slow - mInputs.r1AppliedTo, // AppliedTo - // - // Ribbon 2 ... - "", - mInputs.fast2Length, // Fast - mInputs.slow2Length, // Slow - mInputs.r2AppliedTo, // AppliedTo - // - // Ribbon 3 ... - "", - mInputs.fast3Length, // Fast - mInputs.slow3Length, // Slow - mInputs.r3AppliedTo, // AppliedTo - // - // Ribbon 4 ... - "", - mInputs.fast4Length, // Fast - mInputs.slow4Length, // Slow - mInputs.r4AppliedTo, // AppliedTo - // - // Ribbon 5 ... - "", - mInputs.fast5Length, // Fast - mInputs.slow5Length, // Slow - mInputs.r5AppliedTo, // AppliedTo - // - // Ribbon 6 ... - "", - mInputs.fast6Length, // Fast - mInputs.slow6Length, // Slow - mInputs.r6AppliedTo, // AppliedTo - // - // Calculation ... - "", - mInputs.ribbonMode, // Mode - // - // Presentation ... - "", - mInputs.showFastMa, // Show Fast - mInputs.showSlowMa, // Show Slow - mInputs.showRibbon // Show Ribbon - // - ); - result = mHandler != INVALID_HANDLE; - if (!result) - { - return result; - } - - // - return result; - } - - // - // Inputs ... - - // - XMRBInputs GetInputs() - { - return mInputs; - } - - // - bool SetInputs( - XMRBInputs &inputs // Configs - ) - { - // - return Init( - mSymbol, - mPeriod, - inputs - // - ); - } - - // - // Buffers ... - - // - // Fast ... - - // - double GetFast( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - int count = ArraySize(fastBuffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return fastBuffer[barIndex]; - } - - // - // Copy Required Items ... - int CopyFast( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - fastBuffer, - buffer, - forceClean - // - ); - } - - // - // Slow ... - - // - double GetSlow( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - int count = ArraySize(slowBuffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return slowBuffer[barIndex]; - } - - // - // Copy Required Items ... - int CopySlow( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - slowBuffer, - buffer, - forceClean - // - ); - } - - // - // Ribbon 1 ... - - // - // Fast ... - - // - double GetR1Fast( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - int count = ArraySize(r1FastBuffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return r1FastBuffer[barIndex]; - } - - // - // Copy Required Items ... - int CopyR1Fast( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - r1FastBuffer, - buffer, - forceClean - // - ); - } - - // - // Slow ... - - // - double GetR1Slow( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - int count = ArraySize(r1SlowBuffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return r1SlowBuffer[barIndex]; - } - - // - // Copy Required Items ... - int CopyR1Slow( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - r1SlowBuffer, - buffer, - forceClean - // - ); - } - - // - // Ribbon 2 ... - - // - // Fast ... - - // - double GetR2Fast( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - int count = ArraySize(r2FastBuffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return r2FastBuffer[barIndex]; - } - - // - // Copy Required Items ... - int CopyR2Fast( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - r2FastBuffer, - buffer, - forceClean - // - ); - } - - // - // Slow ... - - // - double GetR2Slow( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - int count = ArraySize(r2SlowBuffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return r2SlowBuffer[barIndex]; - } - - // - // Copy Required Items ... - int CopyR2Slow( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - r2SlowBuffer, - buffer, - forceClean - // - ); - } - - // - // Ribbon 3 ... - - // - // Fast ... - - // - double GetR3Fast( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - int count = ArraySize(r3FastBuffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return r3FastBuffer[barIndex]; - } - - // - // Copy Required Items ... - int CopyR3Fast( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - r3FastBuffer, - buffer, - forceClean - // - ); - } - - // - // Slow ... - - // - double GetR3Slow( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - int count = ArraySize(r3SlowBuffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return r3SlowBuffer[barIndex]; - } - - // - // Copy Required Items ... - int CopyR3Slow( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - r3SlowBuffer, - buffer, - forceClean - // - ); - } - - // - // Ribbon 4 ... - - // - // Fast ... - - // - double GetR4Fast( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - int count = ArraySize(r4FastBuffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return r4FastBuffer[barIndex]; - } - - // - // Copy Required Items ... - int CopyR4Fast( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - r4FastBuffer, - buffer, - forceClean - // - ); - } - - // - // Slow ... - - // - double GetR4Slow( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - int count = ArraySize(r4SlowBuffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return r4SlowBuffer[barIndex]; - } - - // - // Copy Required Items ... - int CopyR4Slow( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - r4SlowBuffer, - buffer, - forceClean - // - ); - } - - // - // Ribbon 5 ... - - // - // Fast ... - - // - double GetR5Fast( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - int count = ArraySize(r5FastBuffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return r5FastBuffer[barIndex]; - } - - // - // Copy Required Items ... - int CopyR5Fast( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - r5FastBuffer, - buffer, - forceClean - // - ); - } - - // - // Slow ... - - // - double GetR5Slow( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - int count = ArraySize(r5SlowBuffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return r5SlowBuffer[barIndex]; - } - - // - // Copy Required Items ... - int CopyR5Slow( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - r5SlowBuffer, - buffer, - forceClean - // - ); - } - - // - // Ribbon 6 ... - - // - // Fast ... - - // - double GetR6Fast( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - int count = ArraySize(r6FastBuffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return r6FastBuffer[barIndex]; - } - - // - // Copy Required Items ... - int CopyR6Fast( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - r6FastBuffer, - buffer, - forceClean - // - ); - } - - // - // Slow ... - - // - double GetR6Slow( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - int count = ArraySize(r6SlowBuffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return r6SlowBuffer[barIndex]; - } - - // - // Copy Required Items ... - int CopyR6Slow( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - r6SlowBuffer, - buffer, - forceClean - // - ); - } - - // - bool GetConditions( - XMRBConditions &conditions, // - int barIndex = 0, // - int loopback = 3 // - ) - { - // - bool result = true; - - // - if (loopback < 3) - { - loopback = 3; - } - - // - conditions.Clean(); - - // - conditions.symbol = mSymbol; - conditions.period = mPeriod; - conditions.time = TimeCurrent(); - - // - int zIndex = barIndex; - int cIndex = zIndex + 1; - int pIndex = cIndex + 1; - int ppIndex = pIndex + 1; - - // - CopyFast( - zIndex, - loopback, - conditions.fast // - ); - CopySlow( - zIndex, - loopback, - conditions.slow // - ); - - // - // Calculate Conditions ... - - // - bool isFastOverSlow = conditions.fast[cIndex] > conditions.slow[cIndex]; - bool isFastUnderSlow = conditions.fast[cIndex] < conditions.slow[cIndex]; - - // - bool isFastOverSlowPrev = conditions.fast[pIndex] > conditions.slow[pIndex]; - bool isFastUnderSlowPrev = conditions.fast[pIndex] < conditions.slow[pIndex]; - - // - bool isFastCrossedOverSlow = isFastOverSlow && - !isFastOverSlowPrev; - bool isFastCrossedUnderSlow = isFastUnderSlow && - !isFastUnderSlowPrev; - - // - conditions.isFastOverSlow = isFastOverSlow; - conditions.isFastUnderSlow = isFastUnderSlow; - conditions.isFastCrossedOverSlow = isFastCrossedOverSlow; - conditions.isFastCrossedUnderSlow = isFastCrossedUnderSlow; - // - return result; - } - - // - // Protected ... -protected: - // - // Private ... -private: - // - // Props ... - XMRBInputs mInputs; // Inputs ... - - // - // Buffers ... - double fastBuffer[]; - double slowBuffer[]; - double r1FastBuffer[]; - double r1SlowBuffer[]; - double r2FastBuffer[]; - double r2SlowBuffer[]; - double r3FastBuffer[]; - double r3SlowBuffer[]; - double r4FastBuffer[]; - double r4SlowBuffer[]; - double r5FastBuffer[]; - double r5SlowBuffer[]; - double r6FastBuffer[]; - double r6SlowBuffer[]; - - // - // Tools ... - - // - // Calculate Values Until Now ... - void Calculate() - { - // - int totalBars = CountBars(); - if (totalBars > 1000) - { - totalBars = 1000; - } - - // - // Fast Buffer ... - CopyBuffer( - mHandler, - XMRB_FAST_LINE, - 0, - totalBars, - fastBuffer - // - ); - - // - // Slow Buffer ... - CopyBuffer( - mHandler, - XMRB_SLOW_LINE, - 0, - totalBars, - slowBuffer - // - ); - - // - // Ribbon 1 ... - - // - // Fast Buffer ... - CopyBuffer( - mHandler, - XMRB_R1_FAST_LINE, - 0, - totalBars, - r1FastBuffer - // - ); - - // - // Slow Buffer ... - CopyBuffer( - mHandler, - XMRB_R1_SLOW_LINE, - 0, - totalBars, - r1SlowBuffer - // - ); - - // - // Ribbon 2 ... - - // - // Fast Buffer ... - CopyBuffer( - mHandler, - XMRB_R2_FAST_LINE, - 0, - totalBars, - r2FastBuffer - // - ); - - // - // Slow Buffer ... - CopyBuffer( - mHandler, - XMRB_R2_SLOW_LINE, - 0, - totalBars, - r2SlowBuffer - // - ); - - // - // Ribbon 3 ... - - // - // Fast Buffer ... - CopyBuffer( - mHandler, - XMRB_R3_FAST_LINE, - 0, - totalBars, - r3FastBuffer - // - ); - - // - // Slow Buffer ... - CopyBuffer( - mHandler, - XMRB_R3_SLOW_LINE, - 0, - totalBars, - r3SlowBuffer - // - ); - - // - // Ribbon 4 ... - - // - // Fast Buffer ... - CopyBuffer( - mHandler, - XMRB_R4_FAST_LINE, - 0, - totalBars, - r4FastBuffer - // - ); - - // - // Slow Buffer ... - CopyBuffer( - mHandler, - XMRB_R4_SLOW_LINE, - 0, - totalBars, - r4SlowBuffer - // - ); - - // - // Ribbon 5 ... - - // - // Fast Buffer ... - CopyBuffer( - mHandler, - XMRB_R5_FAST_LINE, - 0, - totalBars, - r5FastBuffer - // - ); - - // - // Slow Buffer ... - CopyBuffer( - mHandler, - XMRB_R5_SLOW_LINE, - 0, - totalBars, - r5SlowBuffer - // - ); - - // - // Ribbon 6 ... - - // - // Fast Buffer ... - CopyBuffer( - mHandler, - XMRB_R6_FAST_LINE, - 0, - totalBars, - r6FastBuffer - // - ); - - // - // Slow Buffer ... - CopyBuffer( - mHandler, - XMRB_R6_SLOW_LINE, - 0, - totalBars, - r6SlowBuffer - // - ); - } -}; - -// -// Tools ... \ No newline at end of file diff --git a/Documents/Pack/V1.0/Source/Helpers/x-saherelm.xosc.helper.mq5 b/Documents/Pack/V1.0/Source/Helpers/x-saherelm.xosc.helper.mq5 deleted file mode 100644 index 8de18fd1..00000000 --- a/Documents/Pack/V1.0/Source/Helpers/x-saherelm.xosc.helper.mq5 +++ /dev/null @@ -1,1323 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Helper Class Library -// ---------------------------------------------- -// Name: XSCXOSCHelper -// 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 - -// -#include "../Classes/x-saherelm.xhelper.class.mq5" - -// -// Definitions ... - -// -enum ENUM_XOSC_BUFFERS -{ - X_OSC_ATR_LINE = 0, - X_OSC_RVI_MAIN_LINE = 1, - X_OSC_RVI_SIGNAL_LINE = 2, - X_OSC_BULL_POWER_LINE = 3, - X_OSC_BEAR_POWER_LINE = 4, - X_OSC_VOLUME_LINE = 5, - X_OSC_RSI_LINE = 6, - X_OSC_CCI_LINE = 7, - X_OSC_MOMENTUM_LINE = 8, - X_OSC_SAR_LINE = 9, - X_OSC_MACD_MAIN_LINE = 10, - X_OSC_MACD_SIGNAL_LINE = 11, - X_OSC_STOCH_MAIN_LINE = 12, - X_OSC_STOCH_SIGNAL_LINE = 13, - X_OSC_STDDEV_LINE = 14, -}; - -// -// Input Models ... -struct XOSCInputs -{ - // - // Props ... - - // - // ATR ... - int atrLength; // Length - - // - // RVI ... - int rviLength; // Length - - // - // BULLPOWER ... - int bullpLength; // Length - - // - // BEARPOWER ... - int bearpLength; // Length - - // - // VOLUME ... - ENUM_APPLIED_VOLUME volumeAppliedTo; // Applied To - - // - // RSI ... - int rsiLength; // Length - ENUM_APPLIED_PRICE rsiAppliedTo; // Applied To - - // - // CCI ... - int cciLength; // Length - ENUM_APPLIED_PRICE cciAppliedTo; // Applied To - - // - // STDDEV ... - int stddevLength; // Length - int stddevShift; // Shift - ENUM_MA_METHOD stddevMethod; // Mode - ENUM_APPLIED_PRICE stddevAppliedTo; // AppliedTo - - // - // MOMENTUM ... - int momentumLength; // Length - ENUM_APPLIED_PRICE momentumAppliedTo; // Applied To - - // - // SAR ... - double sarStep; // Step - double sarMaximum; // Maximum - - // - // MACD ... - int macdFastLength; // Fast Length - int macdSlowLength; // Slow Length - int macdSignaLength; // Signal Length - ENUM_APPLIED_PRICE macdAppliedTo; // Applied To - - // - // STOCHASTIC ... - // The buffer numbers: 0 - MAIN_LINE, 1 - SIGNAL_LINE. - int stochKLength; // K Length - int stochDLength; // D Length - int stochSlowing; // Slowing - ENUM_MA_METHOD stochMaMethod; // Ma Method - ENUM_STO_PRICE stochMode; // Calculation Mode - - // - // Constructor(s) ... - XOSCInputs() - { - // - Clean(); - } - - // - // Tools ... - - // - // Clean ... - void Clean() - { - // - atrLength = 0; // Length - rviLength = 0; // Length - bullpLength = 0; // Length - bearpLength = 0; // Length - volumeAppliedTo = VOLUME_TICK; // Applied To - rsiLength = 0; // Length - rsiAppliedTo = PRICE_CLOSE; // Applied To - cciLength = 0; // Length - cciAppliedTo = PRICE_TYPICAL; // Applied To - stddevLength = 0; // Length - stddevShift = 0; // Shift - stddevMethod = MODE_SMA; // Mode - stddevAppliedTo = PRICE_CLOSE; // AppliedTo - momentumLength = 0; // Length - momentumAppliedTo = PRICE_CLOSE; // Applied To - sarStep = 0; // Step - sarMaximum = 0; // Maximum - macdFastLength = 0; // Fast Length - macdSlowLength = 0; // Slow Length - macdSignaLength = 0; // Signal Length - macdAppliedTo = PRICE_CLOSE; // Applied To - stochKLength = 0; // K Length - stochDLength = 0; // D Length - stochSlowing = 0; // Slowing - stochMaMethod = MODE_SMA; // Ma Method - stochMode = STO_LOWHIGH; // Calculation Mode - } - - // - // Default ... - void Default() - { - // - atrLength = 14; // Length - rviLength = 10; // Length - bullpLength = 13; // Length - bearpLength = 13; // Length - volumeAppliedTo = VOLUME_TICK; // Applied To - rsiLength = 14; // Length - rsiAppliedTo = PRICE_CLOSE; // Applied To - cciLength = 14; // Length - cciAppliedTo = PRICE_TYPICAL; // Applied To - stddevLength = 20; // Length - stddevShift = 0; // Shift - stddevMethod = MODE_SMA; // Mode - stddevAppliedTo = PRICE_CLOSE; // AppliedTo - momentumLength = 14; // Length - momentumAppliedTo = PRICE_CLOSE; // Applied To - sarStep = 0.02; // Step - sarMaximum = 0.2; // Maximum - macdFastLength = 12; // Fast Length - macdSlowLength = 26; // Slow Length - macdSignaLength = 9; // Signal Length - macdAppliedTo = PRICE_CLOSE; // Applied To - stochKLength = 5; // K Length - stochDLength = 3; // D Length - stochSlowing = 3; // Slowing - stochMaMethod = MODE_SMA; // Ma Method - stochMode = STO_LOWHIGH; // Calculation Mode - } - - // - // Validate ... - bool IsValid() - { - // - bool result = false; - - // - result = - // - atrLength >= 2 && - rviLength >= 2 && - bullpLength >= 2 && - bearpLength >= 2 && - rsiLength >= 2 && - cciLength >= 2 && - momentumLength >= 2 && - sarStep > 0 && - sarStep < sarMaximum && - macdFastLength >= 2 && - macdSlowLength > macdFastLength && - macdSignaLength >= 2 && - stochKLength >= 2 && - stochDLength >= 2 && - stochSlowing >= 2 && - stddevLength >= 2 && - stddevShift >= 0 - // - ; - - // - return result; - } - - // - // Retrieve MAx Length ... - int Max() - { - // - int result = 0; - - // - result = MathMax(atrLength, rviLength); - result = MathMax(result, bullpLength); - result = MathMax(result, bearpLength); - result = MathMax(result, rsiLength); - result = MathMax(result, cciLength); - result = MathMax(result, momentumLength); - result = MathMax(result, macdFastLength); - result = MathMax(result, macdSlowLength); - result = MathMax(result, macdSignaLength); - result = MathMax(result, stochKLength); - result = MathMax(result, stochDLength); - result = MathMax(result, stochSlowing); - result = MathMax(result, stddevLength); - - // - return result; - } -}; - -// -// Class ... -class XSCXOSCHelper : public XSCBaseHelper -{ - // - // Public ... -public: - // - // Props ... - - // - // Constructors ... - XSCXOSCHelper() : XSCBaseHelper(_Symbol, _Period) - { - } - - // - // Deconstructor ... - ~XSCXOSCHelper() {} - - // - // Tools ... - bool Init( - string symbol, // Trading Symbol - ENUM_TIMEFRAMES period, // Trading Period - XOSCInputs &inputs // Inputs - ) - { - // - bool result = false; - - // - mSymbol = symbol; - mPeriod = period; - - // - result = inputs.IsValid(); - if (!result) - { - return result; - } - - // - mInputs = inputs; - - // - ArraySetAsSeries(atrBuffer, true); - ArraySetAsSeries(rviMainBuffer, true); - ArraySetAsSeries(rviSignalBuffer, true); - ArraySetAsSeries(bullPBuffer, true); - ArraySetAsSeries(bearPBuffer, true); - ArraySetAsSeries(volumeBuffer, true); - ArraySetAsSeries(rsiBuffer, true); - ArraySetAsSeries(cciBuffer, true); - ArraySetAsSeries(momentumBuffer, true); - ArraySetAsSeries(sarBuffer, true); - ArraySetAsSeries(macdMainBuffer, true); - ArraySetAsSeries(macdSignalBuffer, true); - ArraySetAsSeries(stochMainBuffer, true); - ArraySetAsSeries(stochSignalBuffer, true); - ArraySetAsSeries(stddevBuffer, true); - - // - mHandler = iCustom( - mSymbol, - mPeriod, - "x-saherelm.xosc", - // - // Inputs ... - // - // ATR ... - "", - mInputs.atrLength, - // - // RVI ... - "", - mInputs.rviLength, - // - // Bulls Power ... - "", - mInputs.bullpLength, - // - // Bears Power ... - "", - mInputs.bearpLength, - // - // Voluem ... - "", - mInputs.volumeAppliedTo, - // - // RSI ... - "", - mInputs.rsiLength, - mInputs.rsiAppliedTo, - // - // CCI ... - "", - mInputs.cciLength, - mInputs.cciAppliedTo, - // - // STDDev ... - "", - mInputs.stddevLength, - mInputs.stddevShift, - mInputs.stddevMethod, - mInputs.stddevAppliedTo, - // - // Momentum ... - "", - mInputs.momentumLength, - mInputs.momentumAppliedTo, - // - // SAR ... - "", - mInputs.sarStep, - mInputs.sarMaximum, - // - // MACD ... - "", - mInputs.macdFastLength, - mInputs.macdSlowLength, - mInputs.macdSignaLength, - mInputs.macdAppliedTo, - // - // Stochastic ... - "", - mInputs.stochKLength, - mInputs.stochDLength, - mInputs.stochSlowing, - mInputs.stochMaMethod, - mInputs.stochMode - // - ); - result = mHandler != INVALID_HANDLE; - if (!result) - { - return result; - } - - // - return result; - } - - // - // Inputs ... - - // - XOSCInputs GetInputs() - { - return mInputs; - } - - // - bool SetInputs( - XOSCInputs &inputs // Configs - ) - { - // - return Init( - mSymbol, - mPeriod, - inputs); - } - - // - // Buffers ... - - // - // ATR ... - - // - double GetATR( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - return atrBuffer[barIndex]; - } - - // - // Copy Required Buffer ... - int CopyATR( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - atrBuffer, - buffer, - forceClean - // - ); - } - - // - // RVI ... - - // - double GetRVI( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - return rviMainBuffer[barIndex]; - } - - // - // Copy Required Buffer ... - int CopyRVI( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - rviMainBuffer, - buffer, - forceClean - // - ); - } - - // - double GetRVISignal( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - return rviSignalBuffer[barIndex]; - } - - // - // Copy Required Buffer ... - int CopyRVISignal( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - rviSignalBuffer, - buffer, - forceClean - // - ); - } - - // - // BULLP ... - - // - double GetBullPower( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - return bullPBuffer[barIndex]; - } - - // - // Copy Required Buffer ... - int CopyBullPower( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - bullPBuffer, - buffer, - forceClean - // - ); - } - - // - // BEARP ... - - // - double GetBearPower( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - return bearPBuffer[barIndex]; - } - - // - // Copy Required Buffer ... - int CopyBearPower( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - bearPBuffer, - buffer, - forceClean - // - ); - } - - // - // VOLUME ... - - // - double GetVolume( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - return volumeBuffer[barIndex]; - } - - // - // Copy Required Buffer ... - int CopyVolume( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - volumeBuffer, - buffer, - forceClean - // - ); - } - - // - // RSI ... - - // - double GetRSI( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - return rsiBuffer[barIndex]; - } - - // - // Copy Required Buffer ... - int CopyRSI( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - rsiBuffer, - buffer, - forceClean - // - ); - } - - // - // CCI ... - - // - double GetCCI( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - return cciBuffer[barIndex]; - } - - // - // Copy Required Buffer ... - int CopyCCI( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - cciBuffer, - buffer, - forceClean - // - ); - } - - // - // MOMENTUM ... - - // - double GetMomentum( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - return momentumBuffer[barIndex]; - } - - // - // Copy Required Buffer ... - int CopyMomentum( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - momentumBuffer, - buffer, - forceClean - // - ); - } - - // - // SAR ... - - // - double GetSAR( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - return sarBuffer[barIndex]; - } - - // - // Copy Required Buffer ... - int CopySAR( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - sarBuffer, - buffer, - forceClean - // - ); - } - - // - // STDDEV ... - - // - double GetSTDDEV( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - return stddevBuffer[barIndex]; - } - - // - // Copy Required Buffer ... - int CopySTDDEV( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - stddevBuffer, - buffer, - forceClean - // - ); - } - - // - // MACD ... - - // - double GetMACD( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - return macdMainBuffer[barIndex]; - } - - // - // Copy Required Buffer ... - int CopyMACD( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - macdMainBuffer, - buffer, - forceClean - // - ); - } - - // - double GetMACDSignal( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - return macdSignalBuffer[barIndex]; - } - - // - // Copy Required Buffer ... - int CopyMACDSignal( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - macdSignalBuffer, - buffer, - forceClean - // - ); - } - - // - // STOCH ... - - // - double GetSTOCH( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - return stochMainBuffer[barIndex]; - } - - // - // Copy Required Buffer ... - int CopySTOCH( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - stochMainBuffer, - buffer, - forceClean - // - ); - } - - // - double GetSTOCHSignal( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - return stochSignalBuffer[barIndex]; - } - - // - // Copy Required Buffer ... - int CopySTOCHSignal( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - stochSignalBuffer, - buffer, - forceClean - // - ); - } - - // - // Protected ... -protected: - // - // Private ... -private: - // - // Props ... - XOSCInputs mInputs; // Inputs ... - - // - // Buffers ... - double atrBuffer[]; - double rviMainBuffer[]; - double rviSignalBuffer[]; - double bullPBuffer[]; - double bearPBuffer[]; - double volumeBuffer[]; - double rsiBuffer[]; - double cciBuffer[]; - double momentumBuffer[]; - double sarBuffer[]; - double macdMainBuffer[]; - double macdSignalBuffer[]; - double stochMainBuffer[]; - double stochSignalBuffer[]; - double stddevBuffer[]; - - // - // Tools ... - - // - // Calculate Values Until Now ... - void Calculate() - { - // - int totalBars = CountBars(); - if (totalBars > 1000) { - totalBars = 1000; - } - - // - // ATR ... - CopyBuffer( - mHandler, - X_OSC_ATR_LINE, - 0, - totalBars, - atrBuffer - // - ); - - // - // BULLP ... - CopyBuffer( - mHandler, - X_OSC_BULL_POWER_LINE, - 0, - totalBars, - bullPBuffer - // - ); - - // - // BEARP ... - CopyBuffer( - mHandler, - X_OSC_BEAR_POWER_LINE, - 0, - totalBars, - bearPBuffer - // - ); - - // - // VOLUME ... - CopyBuffer( - mHandler, - X_OSC_VOLUME_LINE, - 0, - totalBars, - volumeBuffer - // - ); - - // - // RSI ... - CopyBuffer( - mHandler, - X_OSC_RSI_LINE, - 0, - totalBars, - rsiBuffer - // - ); - - // - // CCI ... - CopyBuffer( - mHandler, - X_OSC_CCI_LINE, - 0, - totalBars, - cciBuffer - // - ); - - // - // MOMENTUM ... - CopyBuffer( - mHandler, - X_OSC_MOMENTUM_LINE, - 0, - totalBars, - momentumBuffer - // - ); - - // - // SAR ... - CopyBuffer( - mHandler, - X_OSC_SAR_LINE, - 0, - totalBars, - sarBuffer - // - ); - - // - // STDDEV ... - CopyBuffer( - mHandler, - X_OSC_STDDEV_LINE, - 0, - totalBars, - stddevBuffer - // - ); - - // - // RVI ... - - // - // RVI Main ... - CopyBuffer( - mHandler, - X_OSC_RVI_MAIN_LINE, - 0, - totalBars, - rviMainBuffer - // - ); - - // - // RVI Signal ... - CopyBuffer( - mHandler, - X_OSC_RVI_SIGNAL_LINE, - 0, - totalBars, - rviSignalBuffer - // - ); - - // - // MACD ... - - // - // MACD Main ... - CopyBuffer( - mHandler, - X_OSC_MACD_MAIN_LINE, - 0, - totalBars, - macdMainBuffer - // - ); - - // - // MACD Signal ... - CopyBuffer( - mHandler, - X_OSC_MACD_SIGNAL_LINE, - 0, - totalBars, - macdSignalBuffer - // - ); - - // - // STOCH ... - - // - // STOCH Main ... - CopyBuffer( - mHandler, - X_OSC_STOCH_MAIN_LINE, - 0, - totalBars, - stochMainBuffer - // - ); - - // - // STOCH Signal ... - CopyBuffer( - mHandler, - X_OSC_STOCH_SIGNAL_LINE, - 0, - totalBars, - stochSignalBuffer - // - ); - } -}; - -// -// Tools ... diff --git a/Documents/Pack/V1.0/Source/Helpers/x-saherelm.xpv.helper.mq5 b/Documents/Pack/V1.0/Source/Helpers/x-saherelm.xpv.helper.mq5 deleted file mode 100644 index 9df5fdb3..00000000 --- a/Documents/Pack/V1.0/Source/Helpers/x-saherelm.xpv.helper.mq5 +++ /dev/null @@ -1,3033 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Helper Class Library -// ---------------------------------------------- -// Name: XSCXPVHelper -// 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.xhelper.class.mq5" - -// -// Definitions ... - -// -enum ENUM_XPV_BUFFERS -{ - // - // Peaks and Vales ... - XPV_PEAKS_LINE = 0, - XPV_VALES_LINE = 1, - // - // Support and Resistances ... - XPV_RESISTANCE_LINE = 2, - XPV_SUPPORT_LINE = 4, - // - // Fibonacci ... - XPV_FIB_1_LINE = 6, - XPV_FIB_2_LINE = 8, - XPV_FIB_3_LINE = 10, - XPV_FIB_4_LINE = 12, - XPV_FIB_5_LINE = 14, - // - // Short ... - XPV_SC_HH_LINE = 16, - XPV_SC_LL_LINE = 18, - // - // Medium ... - XPV_MC_HH_LINE = 20, - XPV_MC_LL_LINE = 22, - // - // Long ... - XPV_LC_HH_LINE = 24, - XPV_LC_LL_LINE = 26, - // - // Hind ... - XPV_HC_HH_LINE = 28, - XPV_HC_LL_LINE = 30, -}; - -// -// Input Models ... -struct XPVInputs -{ - // - // Props ... - - // - // Makret Cycles ... - - // - // Short ... - ENUM_X_PERIOD_METHOD scMethod; // How to Find Period - ENUM_TIMEFRAMES scPeriod; // Time Period - - // - // Medium ... - ENUM_X_PERIOD_METHOD mcMethod; // How to Find Period - ENUM_TIMEFRAMES mcPeriod; // Time Period - - // - // Long ... - ENUM_X_PERIOD_METHOD lcMethod; // How to Find Period - ENUM_TIMEFRAMES lcPeriod; // Time Period - - // - // Hind ... - ENUM_X_PERIOD_METHOD hcMethod; // How to Find Period - ENUM_TIMEFRAMES hcPeriod; // Time Period - - // - // Fibonacci ... - double fiboLevel1; // Fibio 1st Level - double fiboLevel2; // Fibio 2st Level - double fiboLevel3; // Fibio 3rd Level - double fiboLevel4; // Fibio 4th Level - double fiboLevel5; // Fibio 5th Level - - // - // Boundary Detection Modes ... - ENUM_SERIESMODE hhMode; // Highest High Calculation Method - ENUM_SERIESMODE llMode; // Lowest Low Calculation Method - - // - // Presentation ... - bool showPeaksAndVales; // Show Peaks and Vales - bool showLevels; // Show Levels - bool showConsolidations; // Show Consolidations - bool showFibo1Levels; // Show Fibo 1st Level - bool showFibo2Levels; // Show Fibo 2nd Level - bool showFibo3Levels; // Show Fibo 3rd Level - bool showFibo4Levels; // Show Fibo 4th Level - bool showFibo5Levels; // Show Fibo 5th Level - - // - // Constructor(s) ... - XPVInputs() - { - // - Clean(); - } - - // - // Tools ... - - // - // Clean ... - void Clean() - { - // - // Makret Cycles ... - - // - // Short ... - scMethod = X_PERIOD_NOTHING; - scPeriod = NULL; - - // - // Medium ... - mcMethod = X_PERIOD_NOTHING; - mcPeriod = NULL; - - // - // Long ... - lcMethod = X_PERIOD_NOTHING; - lcPeriod = NULL; - - // - // Hind ... - hcMethod = X_PERIOD_NOTHING; - hcPeriod = NULL; - - // - // Fibonacci ... - fiboLevel1 = 0; - fiboLevel2 = 0; - fiboLevel3 = 0; - fiboLevel4 = 0; - fiboLevel5 = 0; - - // - // Boundary Detection Modes ... - hhMode = MODE_HIGH; - llMode = MODE_LOW; - - // - // Presentation ... - showPeaksAndVales = false; - showLevels = false; - showConsolidations = false; - showFibo1Levels = false; - showFibo2Levels = false; - showFibo3Levels = false; - showFibo4Levels = false; - showFibo5Levels = false; - } - - // - // Default ... - void Default() - { - // - // Makret Cycles ... - - // - // Short ... - scMethod = X_PERIOD_AUTO; - scPeriod = NULL; - - // - // Medium ... - mcMethod = X_PERIOD_AUTO; - mcPeriod = NULL; - - // - // Long ... - lcMethod = X_PERIOD_AUTO; - lcPeriod = NULL; - - // - // Hind ... - hcMethod = X_PERIOD_AUTO; - hcPeriod = NULL; - - // - // Fibonacci ... - fiboLevel1 = 0.236; - fiboLevel2 = 0.382; - fiboLevel3 = 0.5; - fiboLevel4 = 0.618; - fiboLevel5 = 0.764; - - // - // Boundary Detection Modes ... - hhMode = MODE_HIGH; - llMode = MODE_LOW; - - // - // Presentation ... - showPeaksAndVales = true; - showLevels = false; - showConsolidations = false; - showFibo1Levels = true; - showFibo2Levels = true; - showFibo3Levels = true; - showFibo4Levels = true; - showFibo5Levels = true; - } - - // - // Validate ... - bool IsValid() - { - // - bool result = false; - - // - result = - // - IsValid(scMethod, scPeriod) && - IsValid(mcMethod, mcPeriod) && - IsValid(lcMethod, lcPeriod) && - IsValid(hcMethod, hcPeriod) - // - ; - - // - return result; - } - - // - // Retrieve MAx Length ... - int Max() - { - // - int result = 0; - - // - result = MathMax(result, 0); - - // - return result; - } -}; - -// -// Conditions ... -struct XPVConditions -{ - // - // Common ... - string symbol; - ENUM_TIMEFRAMES period; - datetime time; - - // - // Buffers ... - double peaks[]; - double vales[]; - double resistances[]; - double supports[]; - double fib1s[]; - double fib2s[]; - double fib3s[]; - double fib4s[]; - double fib5s[]; - double sCHHs[]; - double sCLLs[]; - double mCHHs[]; - double mCLLs[]; - double lCHHs[]; - double lCLLs[]; - double hCHHs[]; - double hCLLs[]; - - // - // Conditions ... - - // - bool isNewPeak; - bool isNewPeakOverLast; - bool isNewPeakUnderLast; - - // - bool isNewVale; - bool isNewValeOverLast; - bool isNewValeUnderLast; - - // - bool isFiboIncreased; - bool isFiboDecreased; - bool isFiboSectionChanged; - - // - // SC ... - - // - bool isSCBullish; - bool isSCHHBullish; - bool isSCLLBullish; - bool isSCSwitchedToBullish; - bool isSCHHSwitchedToBullish; - bool isSCLLSwitchedToBullish; - - // - bool isSCBearish; - bool isSCHHBearish; - bool isSCLLBearish; - bool isSCSwitchedToBearish; - bool isSCHHSwitchedToBearish; - bool isSCLLSwitchedToBeraish; - - // - // MC ... - - // - bool isMCBullish; - bool isMCHHBullish; - bool isMCLLBullish; - bool isMCSwitchedToBullish; - bool isMCHHSwitchedToBullish; - bool isMCLLSwitchedToBullish; - - // - bool isMCBearish; - bool isMCHHBearish; - bool isMCLLBearish; - bool isMCSwitchedToBearish; - bool isMCHHSwitchedToBearish; - bool isMCLLSwitchedToBeraish; - - // - // LC ... - - // - bool isLCBullish; - bool isLCHHBullish; - bool isLCLLBullish; - bool isLCSwitchedToBullish; - bool isLCHHSwitchedToBullish; - bool isLCLLSwitchedToBullish; - // - bool isLCBearish; - bool isLCHHBearish; - bool isLCLLBearish; - bool isLCSwitchedToBearish; - bool isLCHHSwitchedToBearish; - bool isLCLLSwitchedToBeraish; - - // - // HC ... - - // - bool isHCBullish; - bool isHCHHBullish; - bool isHCLLBullish; - bool isHCSwitchedToBullish; - bool isHCHHSwitchedToBullish; - bool isHCLLSwitchedToBullish; - - // - bool isHCBearish; - bool isHCHHBearish; - bool isHCLLBearish; - bool isHCSwitchedToBearish; - bool isHCHHSwitchedToBearish; - bool isHCLLSwitchedToBeraish; - - // - void Clean() - { - // - Clean(peaks); - Clean(vales); - Clean(resistances); - Clean(supports); - Clean(fib1s); - Clean(fib2s); - Clean(fib3s); - Clean(fib4s); - Clean(fib5s); - Clean(sCHHs); - Clean(sCLLs); - Clean(mCHHs); - Clean(mCLLs); - Clean(lCHHs); - Clean(lCLLs); - Clean(hCHHs); - Clean(hCLLs); - - // - ArraySetAsSeries(peaks, true); - ArraySetAsSeries(vales, true); - ArraySetAsSeries(resistances, true); - ArraySetAsSeries(supports, true); - ArraySetAsSeries(fib1s, true); - ArraySetAsSeries(fib2s, true); - ArraySetAsSeries(fib3s, true); - ArraySetAsSeries(fib4s, true); - ArraySetAsSeries(fib5s, true); - ArraySetAsSeries(sCHHs, true); - ArraySetAsSeries(sCLLs, true); - ArraySetAsSeries(mCHHs, true); - ArraySetAsSeries(mCLLs, true); - ArraySetAsSeries(lCHHs, true); - ArraySetAsSeries(lCLLs, true); - ArraySetAsSeries(hCHHs, true); - ArraySetAsSeries(hCLLs, true); - - // - isNewPeak = false; - isNewPeakOverLast = false; - isNewPeakUnderLast = false; - isNewVale = false; - isNewValeOverLast = false; - isNewValeUnderLast = false; - isFiboIncreased = false; - isFiboDecreased = false; - isFiboSectionChanged = false; - isSCBullish = false; - isSCHHBullish = false; - isSCLLBullish = false; - isSCSwitchedToBullish = false; - isSCHHSwitchedToBullish = false; - isSCLLSwitchedToBullish = false; - isSCBearish = false; - isSCHHBearish = false; - isSCLLBearish = false; - isSCSwitchedToBearish = false; - isSCHHSwitchedToBearish = false; - isSCLLSwitchedToBeraish = false; - isMCBullish = false; - isMCHHBullish = false; - isMCLLBullish = false; - isMCSwitchedToBullish = false; - isMCHHSwitchedToBullish = false; - isMCLLSwitchedToBullish = false; - isMCBearish = false; - isMCHHBearish = false; - isMCLLBearish = false; - isMCSwitchedToBearish = false; - isMCHHSwitchedToBearish = false; - isMCLLSwitchedToBeraish = false; - isLCBullish = false; - isLCHHBullish = false; - isLCLLBullish = false; - isLCSwitchedToBullish = false; - isLCHHSwitchedToBullish = false; - isLCLLSwitchedToBullish = false; - isLCBearish = false; - isLCHHBearish = false; - isLCLLBearish = false; - isLCSwitchedToBearish = false; - isLCHHSwitchedToBearish = false; - isLCLLSwitchedToBeraish = false; - isHCBullish = false; - isHCHHBullish = false; - isHCLLBullish = false; - isHCSwitchedToBullish = false; - isHCHHSwitchedToBullish = false; - isHCLLSwitchedToBullish = false; - isHCBearish = false; - isHCHHBearish = false; - isHCLLBearish = false; - isHCSwitchedToBearish = false; - isHCHHSwitchedToBearish = false; - isHCLLSwitchedToBeraish = false; - } - - // - void GenerateScore( - double &bullishScore, - double &bearishScore // - ) - { - // - bullishScore = 0; - bearishScore = 0; - - // - if (isNewPeak) - { - } - if (isNewPeakOverLast) - { - } - if (isNewPeakUnderLast) - { - } - - // - if (isNewVale) - { - } - if (isNewValeOverLast) - { - } - if (isNewValeUnderLast) - { - } - - // - if (isFiboIncreased) - { - } - if (isFiboDecreased) - { - } - if (isFiboSectionChanged) - { - } - - // - if (isSCBullish) - { - bullishScore++; - } - if (isSCHHBullish) - { - bullishScore++; - } - if (isSCLLBullish) - { - bullishScore++; - } - if (isSCSwitchedToBullish) - { - bullishScore++; - } - if (isSCHHSwitchedToBullish) - { - bullishScore++; - } - if (isSCLLSwitchedToBullish) - { - bullishScore++; - } - - // - if (isSCBearish) - { - bearishScore++; - } - if (isSCHHBearish) - { - bearishScore++; - } - if (isSCLLBearish) - { - bearishScore++; - } - if (isSCSwitchedToBearish) - { - bearishScore++; - } - if (isSCHHSwitchedToBearish) - { - bearishScore++; - } - if (isSCLLSwitchedToBeraish) - { - bearishScore++; - } - - // - if (isMCBullish) - { - bullishScore++; - } - if (isMCHHBullish) - { - bullishScore++; - } - if (isMCLLBullish) - { - bullishScore++; - } - if (isMCSwitchedToBullish) - { - bullishScore++; - } - if (isMCHHSwitchedToBullish) - { - bullishScore++; - } - if (isMCLLSwitchedToBullish) - { - bullishScore++; - } - - // - if (isMCBearish) - { - bearishScore++; - } - if (isMCHHBearish) - { - bearishScore++; - } - if (isMCLLBearish) - { - bearishScore++; - } - if (isMCSwitchedToBearish) - { - bearishScore++; - } - if (isMCHHSwitchedToBearish) - { - bearishScore++; - } - if (isMCLLSwitchedToBeraish) - { - bearishScore++; - } - - // - if (isLCBullish) - { - bullishScore++; - } - if (isLCHHBullish) - { - bullishScore++; - } - if (isLCLLBullish) - { - bullishScore++; - } - if (isLCSwitchedToBullish) - { - bullishScore++; - } - if (isLCHHSwitchedToBullish) - { - bullishScore++; - } - if (isLCLLSwitchedToBullish) - { - bullishScore++; - } - - // - if (isLCBearish) - { - bearishScore++; - } - if (isLCHHBearish) - { - bearishScore++; - } - if (isLCLLBearish) - { - bearishScore++; - } - if (isLCSwitchedToBearish) - { - bearishScore++; - } - if (isLCHHSwitchedToBearish) - { - bearishScore++; - } - if (isLCLLSwitchedToBeraish) - { - bearishScore++; - } - - if (isHCBullish) - { - bullishScore++; - } - if (isHCHHBullish) - { - bullishScore++; - } - if (isHCLLBullish) - { - bullishScore++; - } - if (isHCSwitchedToBullish) - { - bullishScore++; - } - if (isHCHHSwitchedToBullish) - { - bullishScore++; - } - if (isHCLLSwitchedToBullish) - { - bullishScore++; - } - - // - if (isHCBearish) - { - bearishScore++; - } - if (isHCHHBearish) - { - bearishScore++; - } - if (isHCLLBearish) - { - bearishScore++; - } - if (isHCSwitchedToBearish) - { - bearishScore++; - } - if (isHCHHSwitchedToBearish) - { - bearishScore++; - } - if (isHCLLSwitchedToBeraish) - { - bearishScore++; - } - } - - // - 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 = - // - ToString("isNewPeak", isNewPeak, ignoreFalseConditions, separator) + - ToString("isNewPeakOverLast", isNewPeakOverLast, ignoreFalseConditions, separator) + - ToString("isNewPeakUnderLast", isNewPeakUnderLast, ignoreFalseConditions, separator) + - ToString("isNewVale", isNewVale, ignoreFalseConditions, separator) + - ToString("isNewValeOverLast", isNewValeOverLast, ignoreFalseConditions, separator) + - ToString("isNewValeUnderLast", isNewValeUnderLast, ignoreFalseConditions, separator) + - ToString("isFiboIncreased", isFiboIncreased, ignoreFalseConditions, separator) + - ToString("isFiboDecreased", isFiboDecreased, ignoreFalseConditions, separator) + - ToString("isFiboSectionChanged", isFiboSectionChanged, ignoreFalseConditions, separator) + - ToString("isSCBullish", isSCBullish, ignoreFalseConditions, separator) + - ToString("isSCHHBullish", isSCHHBullish, ignoreFalseConditions, separator) + - ToString("isSCLLBullish", isSCLLBullish, ignoreFalseConditions, separator) + - ToString("isSCSwitchedToBullish", isSCSwitchedToBullish, ignoreFalseConditions, separator) + - ToString("isSCHHSwitchedToBullish", isSCHHSwitchedToBullish, ignoreFalseConditions, separator) + - ToString("isSCLLSwitchedToBullish", isSCLLSwitchedToBullish, ignoreFalseConditions, separator) + - ToString("isSCBearish", isSCBearish, ignoreFalseConditions, separator) + - ToString("isSCHHBearish", isSCHHBearish, ignoreFalseConditions, separator) + - ToString("isSCLLBearish", isSCLLBearish, ignoreFalseConditions, separator) + - ToString("isSCSwitchedToBearish", isSCSwitchedToBearish, ignoreFalseConditions, separator) + - ToString("isSCHHSwitchedToBearish", isSCHHSwitchedToBearish, ignoreFalseConditions, separator) + - ToString("isSCLLSwitchedToBeraish", isSCLLSwitchedToBeraish, ignoreFalseConditions, separator) + - ToString("isMCBullish", isMCBullish, ignoreFalseConditions, separator) + - ToString("isMCHHBullish", isMCHHBullish, ignoreFalseConditions, separator) + - ToString("isMCLLBullish", isMCLLBullish, ignoreFalseConditions, separator) + - ToString("isMCSwitchedToBullish", isMCSwitchedToBullish, ignoreFalseConditions, separator) + - ToString("isMCHHSwitchedToBullish", isMCHHSwitchedToBullish, ignoreFalseConditions, separator) + - ToString("isMCLLSwitchedToBullish", isMCLLSwitchedToBullish, ignoreFalseConditions, separator) + - ToString("isMCBearish", isMCBearish, ignoreFalseConditions, separator) + - ToString("isMCHHBearish", isMCHHBearish, ignoreFalseConditions, separator) + - ToString("isMCLLBearish", isMCLLBearish, ignoreFalseConditions, separator) + - ToString("isMCSwitchedToBearish", isMCSwitchedToBearish, ignoreFalseConditions, separator) + - ToString("isMCHHSwitchedToBearish", isMCHHSwitchedToBearish, ignoreFalseConditions, separator) + - ToString("isMCLLSwitchedToBeraish", isMCLLSwitchedToBeraish, ignoreFalseConditions, separator) + - ToString("isLCBullish", isLCBullish, ignoreFalseConditions, separator) + - ToString("isLCHHBullish", isLCHHBullish, ignoreFalseConditions, separator) + - ToString("isLCLLBullish", isLCLLBullish, ignoreFalseConditions, separator) + - ToString("isLCSwitchedToBullish", isLCSwitchedToBullish, ignoreFalseConditions, separator) + - ToString("isLCHHSwitchedToBullish", isLCHHSwitchedToBullish, ignoreFalseConditions, separator) + - ToString("isLCLLSwitchedToBullish", isLCLLSwitchedToBullish, ignoreFalseConditions, separator) + - ToString("isLCBearish", isLCBearish, ignoreFalseConditions, separator) + - ToString("isLCHHBearish", isLCHHBearish, ignoreFalseConditions, separator) + - ToString("isLCLLBearish", isLCLLBearish, ignoreFalseConditions, separator) + - ToString("isLCSwitchedToBearish", isLCSwitchedToBearish, ignoreFalseConditions, separator) + - ToString("isLCHHSwitchedToBearish", isLCHHSwitchedToBearish, ignoreFalseConditions, separator) + - ToString("isLCLLSwitchedToBeraish", isLCLLSwitchedToBeraish, ignoreFalseConditions, separator) + - ToString("isHCBullish", isHCBullish, ignoreFalseConditions, separator) + - ToString("isHCHHBullish", isHCHHBullish, ignoreFalseConditions, separator) + - ToString("isHCLLBullish", isHCLLBullish, ignoreFalseConditions, separator) + - ToString("isHCSwitchedToBullish", isHCSwitchedToBullish, ignoreFalseConditions, separator) + - ToString("isHCHHSwitchedToBullish", isHCHHSwitchedToBullish, ignoreFalseConditions, separator) + - ToString("isHCLLSwitchedToBullish", isHCLLSwitchedToBullish, ignoreFalseConditions, separator) + - ToString("isHCBearish", isHCBearish, ignoreFalseConditions, separator) + - ToString("isHCHHBearish", isHCHHBearish, ignoreFalseConditions, separator) + - ToString("isHCLLBearish", isHCLLBearish, ignoreFalseConditions, separator) + - ToString("isHCSwitchedToBearish", isHCSwitchedToBearish, ignoreFalseConditions, separator) + - ToString("isHCHHSwitchedToBearish", isHCHHSwitchedToBearish, ignoreFalseConditions, separator) + - ToString("isHCLLSwitchedToBeraish", isHCLLSwitchedToBeraish, ignoreFalseConditions, separator) + - "" - // - ; - - // - result = - // - "[" + GetTag() + "]" + separator + - (onlyConditions - ? "" - : commonStr) + - (!includeScores - ? "" - : scoresStr) + - " " + separator + - (onlyCommons - ? "" - : conditionsStr) + - "" - // - ; - - // - return result; - } - - // - string GetTag() - { - return "XPV"; - } -}; - -// -// Class ... -class XSCXPVHelper : public XSCBaseHelper -{ - // - // Public ... -public: - // - // Props ... - - // - // Constructors ... - XSCXPVHelper() : XSCBaseHelper(_Symbol, _Period) - { - } - - // - // Deconstructor ... - ~XSCXPVHelper() {} - - // - // Tools ... - bool Init( - string symbol, // Trading Symbol - ENUM_TIMEFRAMES period, // Trading Period - XPVInputs &inputs // Inputs - ) - { - // - bool result = false; - - // - mSymbol = symbol; - mPeriod = period; - - // - result = inputs.IsValid(); - if (!result) - { - return result; - } - - // - mInputs = inputs; - - // - ArraySetAsSeries(peaksBuffer, true); - ArraySetAsSeries(valesBuffer, true); - ArraySetAsSeries(resistanceBuffer, true); - ArraySetAsSeries(supportBuffer, true); - ArraySetAsSeries(fib1Buffer, true); - ArraySetAsSeries(fib2Buffer, true); - ArraySetAsSeries(fib3Buffer, true); - ArraySetAsSeries(fib4Buffer, true); - ArraySetAsSeries(fib5Buffer, true); - ArraySetAsSeries(scHHBuffer, true); - ArraySetAsSeries(scLLBuffer, true); - ArraySetAsSeries(mcHHBuffer, true); - ArraySetAsSeries(mcLLBuffer, true); - ArraySetAsSeries(lcHHBuffer, true); - ArraySetAsSeries(lcLLBuffer, true); - ArraySetAsSeries(hcHHBuffer, true); - ArraySetAsSeries(hcLLBuffer, true); - - // - mHandler = iCustom( - mSymbol, - mPeriod, - "x-saherelm.xpv", - // - // Inputs ... - // - // Makret Cycles ... - "", - // - // Short ... - "", - mInputs.scMethod, // How to Find Period - mInputs.scPeriod, // Time Period - // - // Medium ... - "", - mInputs.mcMethod, // How to Find Period - mInputs.mcPeriod, // Time Period - // - // Long ... - "", - mInputs.lcMethod, // How to Find Period - mInputs.lcPeriod, // Time Period - // - // Hind ... - "", - mInputs.hcMethod, // How to Find Period - mInputs.hcPeriod, // Time Period - // - // Fibonacci ... - "", - mInputs.fiboLevel1, // Fibio 1st Level - mInputs.fiboLevel2, // Fibio 2st Level - mInputs.fiboLevel3, // Fibio 3rd Level - mInputs.fiboLevel4, // Fibio 4th Level - mInputs.fiboLevel5, // Fibio 5th Level - // - // Boundary Detection Modes ... - "", - mInputs.hhMode, // Highest High Calculation Method - mInputs.llMode, // Lowest Low Calculation Method - // - // Presentation ... - "", - mInputs.showPeaksAndVales, // Show Peaks and Vales - mInputs.showLevels, // Show Levels - mInputs.showConsolidations, // Show Consolidations - mInputs.showFibo1Levels, // Show Fibo 1st Level - mInputs.showFibo2Levels, // Show Fibo 2nd Level - mInputs.showFibo3Levels, // Show Fibo 3rd Level - mInputs.showFibo4Levels, // Show Fibo 4th Level - mInputs.showFibo5Levels // Show Fibo 5th Level - // - ); - result = mHandler != INVALID_HANDLE; - if (!result) - { - return result; - } - - // - return result; - } - - // - // Inputs ... - - // - XPVInputs GetInputs() - { - return mInputs; - } - - // - bool SetInputs( - XPVInputs &inputs // Configs - ) - { - // - return Init( - mSymbol, - mPeriod, - inputs - // - ); - } - - // - // Buffers ... - - // - // Peaks ... - - // - double GetPeak( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - int count = ArraySize(peaksBuffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return peaksBuffer[barIndex]; - } - - // - // Copy Required Items ... - int CopyPeak( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - peaksBuffer, - buffer, - forceClean - // - ); - } - - // - bool IsSamePeak( - int barIndex, // Start Bar Index - int verifier = 71 // Number of Verifiers - ) - { - // - // Update Calculations ... - Calculate(); - - // - return IsSame( - peaksBuffer, - verifier, - barIndex // - ); - } - - // - // Vales ... - - // - double GetVale( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - int count = ArraySize(valesBuffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return valesBuffer[barIndex]; - } - - // - // Copy Required Items ... - int CopyVale( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - valesBuffer, - buffer, - forceClean - // - ); - } - - // - bool IsSameVale( - int barIndex, // Start Bar Index - int verifier = 71 // Number of Verifiers - ) - { - // - // Update Calculations ... - Calculate(); - - // - return IsSame( - valesBuffer, - verifier, - barIndex // - ); - } - - // - // Resistance ... - - // - double GetResistance( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - int count = ArraySize(resistanceBuffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return resistanceBuffer[barIndex]; - } - - // - // Copy Required Items ... - int CopyResistance( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - resistanceBuffer, - buffer, - forceClean - // - ); - } - - // - // Support ... - - // - double GetSupport( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - int count = ArraySize(supportBuffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return supportBuffer[barIndex]; - } - - // - // Copy Required Items ... - int CopySupport( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - supportBuffer, - buffer, - forceClean - // - ); - } - - // - // Fibonacci ... - - // - // Level 1 ... - - // - double GetFib1( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - int count = ArraySize(fib1Buffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return fib1Buffer[barIndex]; - } - - // - // Copy Required Items ... - int CopyFib1( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - fib1Buffer, - buffer, - forceClean - // - ); - } - - // - bool IsSameFib1( - int barIndex, // Start Bar Index - int verifier = 71 // Number of Verifiers - ) - { - // - // Update Calculations ... - Calculate(); - - // - return IsSame( - fib1Buffer, - verifier, - barIndex // - ); - } - - // - // Level 2 ... - - // - double GetFib2( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - int count = ArraySize(fib2Buffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return fib2Buffer[barIndex]; - } - - // - // Copy Required Items ... - int CopyFib2( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - fib2Buffer, - buffer, - forceClean - // - ); - } - - // - bool IsSameFib2( - int barIndex, // Start Bar Index - int verifier = 71 // Number of Verifiers - ) - { - // - // Update Calculations ... - Calculate(); - - // - return IsSame( - fib2Buffer, - verifier, - barIndex // - ); - } - - // - // Level 3 ... - - // - double GetFib3( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - int count = ArraySize(fib3Buffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return fib3Buffer[barIndex]; - } - - // - // Copy Required Items ... - int CopyFib3( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - fib3Buffer, - buffer, - forceClean - // - ); - } - - // - bool IsSameFib3( - int barIndex, // Start Bar Index - int verifier = 71 // Number of Verifiers - ) - { - // - // Update Calculations ... - Calculate(); - - // - return IsSame( - fib3Buffer, - verifier, - barIndex // - ); - } - - // - // Level 4 ... - - // - double GetFib4( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - int count = ArraySize(fib4Buffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return fib4Buffer[barIndex]; - } - - // - // Copy Required Items ... - int CopyFib4( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - fib4Buffer, - buffer, - forceClean - // - ); - } - - // - bool IsSameFib4( - int barIndex, // Start Bar Index - int verifier = 71 // Number of Verifiers - ) - { - // - // Update Calculations ... - Calculate(); - - // - return IsSame( - fib4Buffer, - verifier, - barIndex // - ); - } - - // - // Level 5 ... - - // - double GetFib5( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - int count = ArraySize(fib5Buffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return fib5Buffer[barIndex]; - } - - // - // Copy Required Items ... - int CopyFib5( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - fib5Buffer, - buffer, - forceClean - // - ); - } - - // - bool IsSameFib5( - int barIndex, // Start Bar Index - int verifier = 71 // Number of Verifiers - ) - { - // - // Update Calculations ... - Calculate(); - - // - return IsSame( - fib5Buffer, - verifier, - barIndex // - ); - } - - // - // Cycles ... - - // - // Short ... - - // - // HH ... - - // - double GetSCHH( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - int count = ArraySize(scHHBuffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return scHHBuffer[barIndex]; - } - - // - // Copy Required Items ... - int CopySCHH( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - scHHBuffer, - buffer, - forceClean - // - ); - } - - // - bool IsSameSCHH( - int barIndex, // Start Bar Index - int verifier = 71 // Number of Verifiers - ) - { - // - // Update Calculations ... - Calculate(); - - // - return IsSame( - scHHBuffer, - verifier, - barIndex // - ); - } - - // - // LL ... - - // - double GetSCLL( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - int count = ArraySize(scLLBuffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return scLLBuffer[barIndex]; - } - - // - // Copy Required Items ... - int CopySCLL( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - scLLBuffer, - buffer, - forceClean - // - ); - } - - // - bool IsSameSCLL( - int barIndex, // Start Bar Index - int verifier = 71 // Number of Verifiers - ) - { - // - // Update Calculations ... - Calculate(); - - // - return IsSame( - scLLBuffer, - verifier, - barIndex // - ); - } - - // - // Medium ... - - // - // HH ... - - // - double GetMCHH( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - int count = ArraySize(mcHHBuffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return mcHHBuffer[barIndex]; - } - - // - // Copy Required Items ... - int CopyMCHH( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - mcHHBuffer, - buffer, - forceClean - // - ); - } - - // - bool IsSameMCHH( - int barIndex, // Start Bar Index - int verifier = 71 // Number of Verifiers - ) - { - // - // Update Calculations ... - Calculate(); - - // - return IsSame( - mcHHBuffer, - verifier, - barIndex // - ); - } - - // - // LL ... - - // - double GetMCLL( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - int count = ArraySize(mcLLBuffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return mcLLBuffer[barIndex]; - } - - // - // Copy Required Items ... - int CopyMCLL( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - mcLLBuffer, - buffer, - forceClean - // - ); - } - - // - bool IsSameMCLL( - int barIndex, // Start Bar Index - int verifier = 71 // Number of Verifiers - ) - { - // - // Update Calculations ... - Calculate(); - - // - return IsSame( - mcLLBuffer, - verifier, - barIndex // - ); - } - - // - // Long ... - - // - // HH ... - - // - double GetLCHH( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - int count = ArraySize(lcHHBuffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return lcHHBuffer[barIndex]; - } - - // - // Copy Required Items ... - int CopyLCHH( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - lcHHBuffer, - buffer, - forceClean - // - ); - } - - // - bool IsSameLCHH( - int barIndex, // Start Bar Index - int verifier = 71 // Number of Verifiers - ) - { - // - // Update Calculations ... - Calculate(); - - // - return IsSame( - lcHHBuffer, - verifier, - barIndex // - ); - } - - // - // LL ... - - // - double GetLCLL( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - int count = ArraySize(lcLLBuffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return lcLLBuffer[barIndex]; - } - - // - // Copy Required Items ... - int CopyLCLL( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - lcLLBuffer, - buffer, - forceClean - // - ); - } - - // - bool IsSameLCLL( - int barIndex, // Start Bar Index - int verifier = 71 // Number of Verifiers - ) - { - // - // Update Calculations ... - Calculate(); - - // - return IsSame( - lcLLBuffer, - verifier, - barIndex // - ); - } - - // - // Hind ... - - // - // HH ... - - // - double GetHCHH( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - int count = ArraySize(hcHHBuffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return hcHHBuffer[barIndex]; - } - - // - // Copy Required Items ... - int CopyHCHH( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - hcHHBuffer, - buffer, - forceClean - // - ); - } - - // - bool IsSameHCHH( - int barIndex, // Start Bar Index - int verifier = 71 // Number of Verifiers - ) - { - // - // Update Calculations ... - Calculate(); - - // - return IsSame( - hcHHBuffer, - verifier, - barIndex // - ); - } - - // - // LL ... - - // - double GetHCLL( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - int count = ArraySize(hcLLBuffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return hcLLBuffer[barIndex]; - } - - // - // Copy Required Items ... - int CopyHCLL( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - hcLLBuffer, - buffer, - forceClean - // - ); - } - - // - bool IsSameHCLL( - int barIndex, // Start Bar Index - int verifier = 71 // Number of Verifiers - ) - { - // - // Update Calculations ... - Calculate(); - - // - return IsSame( - hcLLBuffer, - verifier, - barIndex // - ); - } - - // - bool GetConditions( - XPVConditions &conditions, // - int barIndex = 0, // - int loopback = 3 // - ) - { - // - bool result = true; - - // - if (loopback < 3) - { - loopback = 3; - } - - // - conditions.Clean(); - - // - conditions.symbol = mSymbol; - conditions.period = mPeriod; - conditions.time = TimeCurrent(); - - // - int zIndex = barIndex; - int cIndex = zIndex + 1; - int pIndex = cIndex + 1; - int ppIndex = pIndex + 1; - - // - // Buffers ... - - // - CopyPeak( - zIndex, - loopback, - conditions.peaks // - ); - - // - CopyVale( - zIndex, - loopback, - conditions.vales // - ); - - // - CopySupport( - zIndex, - loopback, - conditions.supports // - ); - - // - CopyResistance( - zIndex, - loopback, - conditions.resistances // - ); - - // - CopyFib1( - zIndex, - loopback, - conditions.fib1s // - ); - - // - CopyFib2( - zIndex, - loopback, - conditions.fib2s // - ); - - // - CopyFib3( - zIndex, - loopback, - conditions.fib3s // - ); - - // - CopyFib4( - zIndex, - loopback, - conditions.fib4s // - ); - - // - CopyFib5( - zIndex, - loopback, - conditions.fib5s // - ); - - // - CopySCHH( - zIndex, - loopback, - conditions.sCHHs // - ); - - // - CopySCLL( - zIndex, - loopback, - conditions.sCLLs // - ); - - // - CopyMCHH( - zIndex, - loopback, - conditions.mCHHs // - ); - - // - CopyMCLL( - zIndex, - loopback, - conditions.mCLLs // - ); - - // - CopyLCHH( - zIndex, - loopback, - conditions.lCHHs // - ); - - // - CopyLCLL( - zIndex, - loopback, - conditions.lCLLs // - ); - - // - CopyHCHH( - zIndex, - loopback, - conditions.hCHHs // - ); - - // - CopyHCLL( - zIndex, - loopback, - conditions.hCLLs // - ); - - // - // Conditions ... - - // - bool isNewPeak = conditions.peaks[cIndex] != conditions.peaks[pIndex]; - bool isNewPeakOverLast = isNewPeak && - conditions.peaks[cIndex] > conditions.peaks[pIndex]; - bool isNewPeakUnderLast = isNewPeak && - conditions.peaks[cIndex] < conditions.peaks[pIndex]; - - // - bool isNewVale = conditions.vales[cIndex] != conditions.vales[pIndex]; - bool isNewValeOverLast = isNewVale && - conditions.vales[cIndex] > conditions.vales[pIndex]; - bool isNewValeUnderLast = isNewVale && - conditions.vales[cIndex] < conditions.vales[pIndex]; - - // - bool isFiboIncreased = - // - conditions.fib1s[cIndex] > conditions.fib1s[pIndex] && - conditions.fib2s[cIndex] > conditions.fib2s[pIndex] && - conditions.fib3s[cIndex] > conditions.fib3s[pIndex] && - conditions.fib4s[cIndex] > conditions.fib4s[pIndex] && - conditions.fib5s[cIndex] > conditions.fib5s[pIndex] - // - ; - bool isFiboDecreased = - // - conditions.fib1s[cIndex] < conditions.fib1s[pIndex] && - conditions.fib2s[cIndex] < conditions.fib2s[pIndex] && - conditions.fib3s[cIndex] < conditions.fib3s[pIndex] && - conditions.fib4s[cIndex] < conditions.fib4s[pIndex] && - conditions.fib5s[cIndex] < conditions.fib5s[pIndex] - // - ; - bool isFiboSectionChanged = - // - (isFiboDecreased && - isNewPeakUnderLast) - // - || - // - (isFiboIncreased && - isNewValeOverLast) - // - ; - - // - // SC ... - - // - bool isSCHHBullish = conditions.sCHHs[cIndex] > conditions.sCHHs[pIndex]; - bool isSCLLBullish = conditions.sCLLs[cIndex] > conditions.sCLLs[pIndex]; - - // - bool isSCHHBullishPrev = conditions.sCHHs[pIndex] > conditions.sCHHs[ppIndex]; - bool isSCLLBullishPrev = conditions.sCLLs[pIndex] > conditions.sCLLs[ppIndex]; - - // - bool isSCBullish = isSCHHBullish && - isSCLLBullish; - - // - bool isSCBullishPrev = isSCHHBullishPrev && - isSCLLBullishPrev; - - // - bool isSCHHSwitchedToBullish = isSCHHBullish && - !isSCHHBullishPrev; - bool isSCLLSwitchedToBullish = isSCLLBullish && - !isSCLLBullishPrev; - - // - bool isSCHHBearish = conditions.sCHHs[cIndex] < conditions.sCHHs[pIndex]; - bool isSCLLBearish = conditions.sCLLs[cIndex] < conditions.sCLLs[pIndex]; - - // - bool isSCHHBearishPrev = conditions.sCHHs[pIndex] < conditions.sCHHs[ppIndex]; - bool isSCLLBearishPrev = conditions.sCLLs[pIndex] < conditions.sCLLs[ppIndex]; - - // - bool isSCBearish = isSCHHBearish && - isSCLLBearish; - - // - bool isSCBearishPrev = isSCHHBearishPrev && - isSCLLBearishPrev; - - // - bool isSCHHSwitchedToBearish = isSCHHBearish && - !isSCHHBearishPrev; - bool isSCLLSwitchedToBeraish = isSCLLBearish && - !isSCLLBearishPrev; - - // - bool isSCSwitchedToBullish = - // - (isSCHHSwitchedToBullish && - !isSCLLBearish) - // - || - // - (isSCLLSwitchedToBullish && - !isSCHHBearish) - // - ; - - // - bool isSCSwitchedToBearish = - // - (isSCHHSwitchedToBearish && - !isSCLLBullish) - // - || - // - (isSCLLSwitchedToBeraish && - !isSCHHBullish) - // - ; - - // - // MC ... - - // - bool isMCHHBullish = conditions.mCHHs[cIndex] > conditions.mCHHs[pIndex]; - bool isMCLLBullish = conditions.mCLLs[cIndex] > conditions.mCLLs[pIndex]; - - // - bool isMCHHBullishPrev = conditions.mCHHs[pIndex] > conditions.mCHHs[ppIndex]; - bool isMCLLBullishPrev = conditions.mCLLs[pIndex] > conditions.mCLLs[ppIndex]; - - // - bool isMCBullish = isMCHHBullish && - isMCLLBullish; - - // - bool isMCBullishPrev = isMCHHBullishPrev && - isMCLLBullishPrev; - - // - bool isMCHHSwitchedToBullish = isMCHHBullish && - !isMCHHBullishPrev; - bool isMCLLSwitchedToBullish = isMCLLBullish && - !isMCLLBullishPrev; - - // - bool isMCHHBearish = conditions.mCHHs[cIndex] < conditions.mCHHs[pIndex]; - bool isMCLLBearish = conditions.mCLLs[cIndex] < conditions.mCLLs[pIndex]; - - // - bool isMCHHBearishPrev = conditions.mCHHs[pIndex] < conditions.mCHHs[ppIndex]; - bool isMCLLBearishPrev = conditions.mCLLs[pIndex] < conditions.mCLLs[ppIndex]; - - // - bool isMCBearish = isMCHHBearish && - isMCLLBearish; - - // - bool isMCBearishPrev = isMCHHBearishPrev && - isMCLLBearishPrev; - - // - bool isMCHHSwitchedToBearish = isMCHHBearish && - !isMCHHBearishPrev; - bool isMCLLSwitchedToBeraish = isMCLLBearish && - !isMCLLBearishPrev; - - // - bool isMCSwitchedToBullish = - // - (isMCHHSwitchedToBullish && - !isMCLLBearish) - // - || - // - (isMCLLSwitchedToBullish && - !isMCHHBearish) - // - ; - - // - bool isMCSwitchedToBearish = - // - (isMCHHSwitchedToBearish && - !isMCLLBullish) - // - || - // - (isMCLLSwitchedToBeraish && - !isMCHHBullish) - // - ; - - // - // LC ... - - // - bool isLCHHBullish = conditions.lCHHs[cIndex] > conditions.lCHHs[pIndex]; - bool isLCLLBullish = conditions.lCLLs[cIndex] > conditions.lCLLs[pIndex]; - - // - bool isLCHHBullishPrev = conditions.lCHHs[pIndex] > conditions.lCHHs[ppIndex]; - bool isLCLLBullishPrev = conditions.lCLLs[pIndex] > conditions.lCLLs[ppIndex]; - - // - bool isLCBullish = isLCHHBullish && - isLCLLBullish; - - // - bool isLCBullishPrev = isLCHHBullishPrev && - isLCLLBullishPrev; - - // - bool isLCHHSwitchedToBullish = isLCHHBullish && - !isLCHHBullishPrev; - bool isLCLLSwitchedToBullish = isLCLLBullish && - !isLCLLBullishPrev; - - // - bool isLCHHBearish = conditions.lCHHs[cIndex] < conditions.lCHHs[pIndex]; - bool isLCLLBearish = conditions.lCLLs[cIndex] < conditions.lCLLs[pIndex]; - - // - bool isLCHHBearishPrev = conditions.lCHHs[pIndex] < conditions.lCHHs[ppIndex]; - bool isLCLLBearishPrev = conditions.lCLLs[pIndex] < conditions.lCLLs[ppIndex]; - - // - bool isLCBearish = isLCHHBearish && - isLCLLBearish; - - // - bool isLCBearishPrev = isLCHHBearishPrev && - isLCLLBearishPrev; - - // - bool isLCHHSwitchedToBearish = isLCHHBearish && - !isLCHHBearishPrev; - bool isLCLLSwitchedToBeraish = isLCLLBearish && - !isLCLLBearishPrev; - - // - bool isLCSwitchedToBullish = - // - (isLCHHSwitchedToBullish && - !isLCLLBearish) - // - || - // - (isLCLLSwitchedToBullish && - !isLCHHBearish) - // - ; - - // - bool isLCSwitchedToBearish = - // - (isLCHHSwitchedToBearish && - !isLCLLBullish) - // - || - // - (isLCLLSwitchedToBeraish && - !isLCHHBullish) - // - ; - - // - // HC ... - - // - bool isHCHHBullish = conditions.hCHHs[cIndex] > conditions.hCHHs[pIndex]; - bool isHCLLBullish = conditions.hCLLs[cIndex] > conditions.hCLLs[pIndex]; - - // - bool isHCHHBullishPrev = conditions.hCHHs[pIndex] > conditions.hCHHs[ppIndex]; - bool isHCLLBullishPrev = conditions.hCLLs[pIndex] > conditions.hCLLs[ppIndex]; - - // - bool isHCBullish = isHCHHBullish && - isHCLLBullish; - - // - bool isHCBullishPrev = isHCHHBullishPrev && - isHCLLBullishPrev; - - // - bool isHCHHSwitchedToBullish = isHCHHBullish && - !isHCHHBullishPrev; - bool isHCLLSwitchedToBullish = isHCLLBullish && - !isHCLLBullishPrev; - - // - bool isHCHHBearish = conditions.hCHHs[cIndex] < conditions.hCHHs[pIndex]; - bool isHCLLBearish = conditions.hCLLs[cIndex] < conditions.hCLLs[pIndex]; - - // - bool isHCHHBearishPrev = conditions.hCHHs[pIndex] < conditions.hCHHs[ppIndex]; - bool isHCLLBearishPrev = conditions.hCLLs[pIndex] < conditions.hCLLs[ppIndex]; - - // - bool isHCBearish = isHCHHBearish && - isHCLLBearish; - - // - bool isHCBearishPrev = isHCHHBearishPrev && - isHCLLBearishPrev; - - // - bool isHCHHSwitchedToBearish = isHCHHBearish && - !isHCHHBearishPrev; - bool isHCLLSwitchedToBeraish = isHCLLBearish && - !isHCLLBearishPrev; - - // - bool isHCSwitchedToBullish = - // - (isHCHHSwitchedToBullish && - !isHCLLBearish) - // - || - // - (isHCLLSwitchedToBullish && - !isHCHHBearish) - // - ; - - // - bool isHCSwitchedToBearish = - // - (isHCHHSwitchedToBearish && - !isHCLLBullish) - // - || - // - (isHCLLSwitchedToBeraish && - !isHCHHBullish) - // - ; - - // - conditions.isNewPeak = isNewPeak; - conditions.isNewPeakOverLast = isNewPeakOverLast; - conditions.isNewPeakUnderLast = isNewPeakUnderLast; - conditions.isNewVale = isNewVale; - conditions.isNewValeOverLast = isNewValeOverLast; - conditions.isNewValeUnderLast = isNewValeUnderLast; - conditions.isFiboIncreased = isFiboIncreased; - conditions.isFiboDecreased = isFiboDecreased; - conditions.isFiboSectionChanged = isFiboSectionChanged; - conditions.isSCBullish = isSCBullish; - conditions.isSCHHBullish = isSCHHBullish; - conditions.isSCLLBullish = isSCLLBullish; - conditions.isSCSwitchedToBullish = isSCSwitchedToBullish; - conditions.isSCHHSwitchedToBullish = isSCHHSwitchedToBullish; - conditions.isSCLLSwitchedToBullish = isSCLLSwitchedToBullish; - conditions.isSCBearish = isSCBearish; - conditions.isSCHHBearish = isSCHHBearish; - conditions.isSCLLBearish = isSCLLBearish; - conditions.isSCSwitchedToBearish = isSCSwitchedToBearish; - conditions.isSCHHSwitchedToBearish = isSCHHSwitchedToBearish; - conditions.isSCLLSwitchedToBeraish = isSCLLSwitchedToBeraish; - conditions.isMCBullish = isMCBullish; - conditions.isMCHHBullish = isMCHHBullish; - conditions.isMCLLBullish = isMCLLBullish; - conditions.isMCSwitchedToBullish = isMCSwitchedToBullish; - conditions.isMCHHSwitchedToBullish = isMCHHSwitchedToBullish; - conditions.isMCLLSwitchedToBullish = isMCLLSwitchedToBullish; - conditions.isMCBearish = isMCBearish; - conditions.isMCHHBearish = isMCHHBearish; - conditions.isMCLLBearish = isMCLLBearish; - conditions.isMCSwitchedToBearish = isMCSwitchedToBearish; - conditions.isMCHHSwitchedToBearish = isMCHHSwitchedToBearish; - conditions.isMCLLSwitchedToBeraish = isMCLLSwitchedToBeraish; - conditions.isLCBullish = isLCBullish; - conditions.isLCHHBullish = isLCHHBullish; - conditions.isLCLLBullish = isLCLLBullish; - conditions.isLCSwitchedToBullish = isLCSwitchedToBullish; - conditions.isLCHHSwitchedToBullish = isLCHHSwitchedToBullish; - conditions.isLCLLSwitchedToBullish = isLCLLSwitchedToBullish; - conditions.isLCBearish = isLCBearish; - conditions.isLCHHBearish = isLCHHBearish; - conditions.isLCLLBearish = isLCLLBearish; - conditions.isLCSwitchedToBearish = isLCSwitchedToBearish; - conditions.isLCHHSwitchedToBearish = isLCHHSwitchedToBearish; - conditions.isLCLLSwitchedToBeraish = isLCLLSwitchedToBeraish; - conditions.isHCBullish = isHCBullish; - conditions.isHCHHBullish = isHCHHBullish; - conditions.isHCLLBullish = isHCLLBullish; - conditions.isHCSwitchedToBullish = isHCSwitchedToBullish; - conditions.isHCHHSwitchedToBullish = isHCHHSwitchedToBullish; - conditions.isHCLLSwitchedToBullish = isHCLLSwitchedToBullish; - conditions.isHCBearish = isHCBearish; - conditions.isHCHHBearish = isHCHHBearish; - conditions.isHCLLBearish = isHCLLBearish; - conditions.isHCSwitchedToBearish = isHCSwitchedToBearish; - conditions.isHCHHSwitchedToBearish = isHCHHSwitchedToBearish; - conditions.isHCLLSwitchedToBeraish = isHCLLSwitchedToBeraish; - // - return result; - } - - // - // Protected ... -protected: - // - // Private ... -private: - // - // Props ... - XPVInputs mInputs; // Inputs ... - - // - // Buffers ... - double peaksBuffer[]; - double valesBuffer[]; - double resistanceBuffer[]; - double supportBuffer[]; - double fib1Buffer[]; - double fib2Buffer[]; - double fib3Buffer[]; - double fib4Buffer[]; - double fib5Buffer[]; - double scHHBuffer[]; - double scLLBuffer[]; - double mcHHBuffer[]; - double mcLLBuffer[]; - double lcHHBuffer[]; - double lcLLBuffer[]; - double hcHHBuffer[]; - double hcLLBuffer[]; - - // - // Tools ... - - // - // Calculate Values Until Now ... - void Calculate() - { - // - int totalBars = CountBars(); - if (totalBars > 1000) { - totalBars = 1000; - } - - // - // Peaks and Vales ... - - // - // Peaks Buffer ... - CopyBuffer( - mHandler, - XPV_PEAKS_LINE, - 0, - totalBars, - peaksBuffer - // - ); - - // - // Vales Buffer ... - CopyBuffer( - mHandler, - XPV_VALES_LINE, - 0, - totalBars, - valesBuffer - // - ); - - // - // Support and Resistances ... - - // - // Resistances Buffer ... - CopyBuffer( - mHandler, - XPV_RESISTANCE_LINE, - 0, - totalBars, - resistanceBuffer - // - ); - - // - // Supports Buffer ... - CopyBuffer( - mHandler, - XPV_SUPPORT_LINE, - 0, - totalBars, - supportBuffer - // - ); - - // - // Fibonacci ... - - // - // Level 1 Buffer ... - CopyBuffer( - mHandler, - XPV_FIB_1_LINE, - 0, - totalBars, - fib1Buffer - // - ); - - // - // Level 2 Buffer ... - CopyBuffer( - mHandler, - XPV_FIB_2_LINE, - 0, - totalBars, - fib2Buffer - // - ); - - // - // Level 3 Buffer ... - CopyBuffer( - mHandler, - XPV_FIB_3_LINE, - 0, - totalBars, - fib3Buffer - // - ); - - // - // Level 4 Buffer ... - CopyBuffer( - mHandler, - XPV_FIB_4_LINE, - 0, - totalBars, - fib4Buffer - // - ); - - // - // Level 5 Buffer ... - CopyBuffer( - mHandler, - XPV_FIB_5_LINE, - 0, - totalBars, - fib5Buffer - // - ); - - // - // Cycles ... - - // - // Short ... - - // - // HH ... - CopyBuffer( - mHandler, - XPV_SC_HH_LINE, - 0, - totalBars, - scHHBuffer - // - ); - - // - // LL ... - CopyBuffer( - mHandler, - XPV_SC_LL_LINE, - 0, - totalBars, - scLLBuffer - // - ); - - // - // Medium ... - - // - // HH ... - CopyBuffer( - mHandler, - XPV_MC_HH_LINE, - 0, - totalBars, - mcHHBuffer - // - ); - - // - // LL ... - CopyBuffer( - mHandler, - XPV_MC_LL_LINE, - 0, - totalBars, - mcLLBuffer - // - ); - - // - // Long ... - - // - // HH ... - CopyBuffer( - mHandler, - XPV_LC_HH_LINE, - 0, - totalBars, - lcHHBuffer - // - ); - - // - // LL ... - CopyBuffer( - mHandler, - XPV_LC_LL_LINE, - 0, - totalBars, - lcLLBuffer - // - ); - - // - // Hind ... - - // - // HH ... - CopyBuffer( - mHandler, - XPV_HC_HH_LINE, - 0, - totalBars, - hcHHBuffer - // - ); - - // - // LL ... - CopyBuffer( - mHandler, - XPV_HC_LL_LINE, - 0, - totalBars, - hcLLBuffer - // - ); - } -}; - -// -// Tools ... \ No newline at end of file diff --git a/Documents/Pack/V1.0/Source/Helpers/x-saherelm.xsln.helper.mq5 b/Documents/Pack/V1.0/Source/Helpers/x-saherelm.xsln.helper.mq5 deleted file mode 100644 index 7df7e9ab..00000000 --- a/Documents/Pack/V1.0/Source/Helpers/x-saherelm.xsln.helper.mq5 +++ /dev/null @@ -1,638 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Helper Class Library -// ---------------------------------------------- -// Name: XSCXSLNHelper -// 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.xhelper.class.mq5" - -// -// Definitions ... - -// -enum ENUM_XSLN_STATE -{ - XSLN_STATE_BULLISH = 1, - XSLN_STATE_BEARISH = -1, -}; - -// -enum ENUM_XSLN_BUFFERS -{ - XSLN_MAIN_LINE = 0, - XSLN_STATE_LINE = 2, -}; - -// -// Input Models ... -struct XSLNInputs -{ - // - // Props ... - - // - // Presentation ... - bool show; // Show - - // - // Constructor(s) ... - XSLNInputs() - { - // - Clean(); - } - - // - // Tools ... - - // - // Clean ... - void Clean() - { - // - show = false; - } - - // - // Default ... - void Default() - { - // - show = true; - } - - // - // Validate ... - bool IsValid() - { - // - bool result = false; - - // - result = - // - true - // - ; - - // - return result; - } - - // - // Retrieve MAx Length ... - int Max() - { - // - int result = 0; - - // - result = 0; - - // - return result; - } -}; - -// -// Define Conditions ... -struct XSLNConditions -{ - // - // Common ... - string symbol; - ENUM_TIMEFRAMES period; - datetime time; - - // - // Buffers ... - double sln[]; - double state[]; - - // - // Conditions ... - - // - bool isBullish; - bool isBearish; - - // - bool isSwitchedToBullish; - bool isSwitchedToBearish; - - // - void Clean() - { - // - Clean(sln); - Clean(state); - - // - ArraySetAsSeries(sln, true); - ArraySetAsSeries(state, true); - - // - isBullish = false; - isBearish = false; - isSwitchedToBullish = false; - isSwitchedToBearish = false; - } - - // - void GenerateScore( - double &bullishScore, - double &bearishScore // - ) - { - // - bullishScore = 0; - bearishScore = 0; - - // - if (isBullish) - { - bullishScore++; - } - if (isSwitchedToBullish) - { - bullishScore++; - } - - if (isBearish) - { - bearishScore++; - } - if (isSwitchedToBearish) - { - bearishScore++; - } - } - - // - 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 = - // - ToString("isBullish", isBullish, ignoreFalseConditions, separator) + - ToString("isBearish", isBearish, ignoreFalseConditions, separator) + - ToString("isSwitchedToBullish", isSwitchedToBullish, ignoreFalseConditions, separator) + - ToString("isSwitchedToBearish", isSwitchedToBearish, ignoreFalseConditions, separator) + - "" - // - ; - - // - result = - // - "[" + GetTag() + "]" + separator + - (onlyConditions - ? "" - : commonStr) + - (!includeScores - ? "" - : scoresStr) + - " " + separator + - (onlyCommons - ? "" - : conditionsStr) + - "" - // - ; - - // - return result; - } - - // - string GetTag() - { - return "XSLN"; - } -}; - -// -// Class ... -class XSCXSLNHelper : public XSCBaseHelper -{ - // - // Public ... -public: - // - // Props ... - - // - // Constructors ... - XSCXSLNHelper() : XSCBaseHelper(_Symbol, _Period) - { - } - - // - // Deconstructor ... - ~XSCXSLNHelper() {} - - // - // Tools ... - bool Init( - string symbol, // Trading Symbol - ENUM_TIMEFRAMES period, // Trading Period - XSLNInputs &inputs // Inputs - ) - { - // - bool result = false; - - // - mSymbol = symbol; - mPeriod = period; - - // - result = inputs.IsValid(); - if (!result) - { - return result; - } - - // - mInputs = inputs; - - // - ArraySetAsSeries(slnBuffer, true); - ArraySetAsSeries(stateBuffer, true); - mHandler = iCustom( - mSymbol, - mPeriod, - "x-saherelm.xsln", - // - // Inputs ... - // - // Presentation ... - "", - mInputs.show - // - ); - result = mHandler != INVALID_HANDLE; - if (!result) - { - return result; - } - - // - return result; - } - - // - // Inputs ... - - // - XSLNInputs GetInputs() - { - return mInputs; - } - - // - bool SetInputs( - XSLNInputs &inputs // Configs - ) - { - // - return Init( - mSymbol, - mPeriod, - inputs - // - ); - } - - // - // Buffers ... - - // - double GetSLN( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - int count = ArraySize(slnBuffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return slnBuffer[barIndex]; - } - - // - // Copy Required Items ... - int CopySLN( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - slnBuffer, - buffer, - forceClean - // - ); - } - - // - double GetState( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - int count = ArraySize(stateBuffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return stateBuffer[barIndex]; - } - - // - // Copy Required Items ... - int CopyState( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - stateBuffer, - buffer, - forceClean - // - ); - } - - // - ENUM_XSLN_STATE ToState(double value) - { - return (ENUM_XSLN_STATE)value; - } - - // - bool IsBullish(double state) - { - // - bool result = false; - - // - result = state == 1 || state == -1; - if (!result) - { - return result; - } - - // - ENUM_XSLN_STATE eState = ToState(state); - result = eState == XSLN_STATE_BULLISH; - - // - return result; - } - - // - bool IsBearish(double state) - { - // - bool result = false; - - // - result = state == 1 || state == -1; - if (!result) - { - return result; - } - - // - ENUM_XSLN_STATE eState = ToState(state); - result = eState == XSLN_STATE_BEARISH; - - // - return result; - } - - // - bool GetConditions( - XSLNConditions &conditions, // - int barIndex = 0, // - int loopback = 3 // - ) - { - // - bool result = true; - - // - if (loopback < 3) - { - loopback = 3; - } - - // - conditions.Clean(); - - // - conditions.symbol = mSymbol; - conditions.period = mPeriod; - conditions.time = TimeCurrent(); - - // - int zIndex = barIndex; - int cIndex = zIndex + 1; - int pIndex = cIndex + 1; - int ppIndex = pIndex + 1; - - // - // Buffers ... - - // - CopySLN( - zIndex, - loopback, - conditions.sln // - ); - - // - CopyState( - zIndex, - loopback, - conditions.state // - ); - - // - // Conditions ... - - // - bool isBullish = IsBullish(conditions.state[cIndex]); - bool isBullishPrev = IsBullish(conditions.state[pIndex]); - - // - bool isBearish = IsBearish(conditions.state[cIndex]); - bool isBearishPrev = IsBearish(conditions.state[pIndex]); - - // - bool isSwitchedToBullish = isBullish && - !isBullishPrev; - bool isSwitchedToBearish = isBearish && - !isBearishPrev; - - // - conditions.isBullish = isBullish; - conditions.isBearish = isBearish; - conditions.isSwitchedToBullish = isSwitchedToBullish; - conditions.isSwitchedToBearish = isSwitchedToBearish; - - // - return result; - } - - // - // Protected ... -protected: - // - // Private ... -private: - // - // Props ... - XSLNInputs mInputs; // Inputs ... - - // - // Buffers ... - double slnBuffer[]; - double stateBuffer[]; - - // - // Tools ... - - // - // Calculate Values Until Now ... - void Calculate() - { - // - int totalBars = CountBars(); - if (totalBars > 1000) - { - totalBars = 1000; - } - - // - // Longs Buffer ... - CopyBuffer( - mHandler, - XSLN_MAIN_LINE, - 0, - totalBars, - slnBuffer - // - ); - - // - // Longs Buffer ... - CopyBuffer( - mHandler, - XSLN_STATE_LINE, - 0, - totalBars, - stateBuffer - // - ); - } -}; - -// \ No newline at end of file diff --git a/Documents/Pack/V1.0/Source/Helpers/x-saherelm.xsslc.helper.mq5 b/Documents/Pack/V1.0/Source/Helpers/x-saherelm.xsslc.helper.mq5 deleted file mode 100644 index d9b7049c..00000000 --- a/Documents/Pack/V1.0/Source/Helpers/x-saherelm.xsslc.helper.mq5 +++ /dev/null @@ -1,631 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Helper Class Library -// ---------------------------------------------- -// Name: XSCXSSLCHelper -// 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.xhelper.class.mq5" - -// -// Definitions ... - -// -enum ENUM_XSSLC_BUFFERS -{ - XSSLC_UP_LINE = 0, - XSSLC_DOWN_LINE = 1, -}; - -// -// Input Models ... -struct XSSLCInputs -{ - // - // Props ... - - // - // Market ... - int length; // Length - - // - // Calculation ... - ENUM_MA_METHOD method; // Method - ENUM_APPLIED_PRICE upAppliedTo; // Up Applied To - ENUM_APPLIED_PRICE downAppliedTo; // Down Applied To - - // - // Presentation ... - bool showUp; // Show Up - bool showDown; // Show Down - - // - // Constructor(s) ... - XSSLCInputs() - { - // - Clean(); - } - - // - // Tools ... - - // - // Clean ... - void Clean() - { - // - // Market ... - length = 0; - - // - // Calculation ... - method = MODE_SMA; - upAppliedTo = PRICE_HIGH; - downAppliedTo = PRICE_LOW; - - // - // Presentation ... - showUp = false; - showDown = false; - } - - // - // Default ... - void Default() - { - // - // Market ... - length = 36; - - // - // Calculation ... - method = MODE_SMA; - upAppliedTo = PRICE_HIGH; - downAppliedTo = PRICE_LOW; - - // - // Presentation ... - showUp = true; - showDown = true; - } - - // - // Validate ... - bool IsValid() - { - // - bool result = false; - - // - result = - // - length > 2 - // - ; - - // - return result; - } - - // - // Retrieve MAx Length ... - int Max() - { - // - int result = 0; - - // - result = MathMax(0, 0); - - // - return result; - } -}; - -// -// Define Conditions ... -struct XSSLCConditions -{ - // - // Common ... - string symbol; - ENUM_TIMEFRAMES period; - datetime time; - - // - // Buffers ... - double up[]; - double down[]; - - // - // Conditions ... - - // - bool isBullish; - bool isBearish; - bool isSwitchedToBullish; - bool isSwitchedToBearish; - - // - void Clean() - { - // - Clean(up); - Clean(down); - - // - ArraySetAsSeries(up, true); - ArraySetAsSeries(down, true); - - // - isBullish = false; - isBearish = false; - isSwitchedToBullish = false; - isSwitchedToBearish = false; - } - - // - void GenerateScore( - double &bullishScore, - double &bearishScore // - ) - { - // - bullishScore = 0; - bearishScore = 0; - - // - if (isBullish) - { - bullishScore++; - } - if (isSwitchedToBullish) - { - bullishScore++; - } - - // - if (isBearish) - { - bearishScore++; - } - if (isSwitchedToBearish) - { - bearishScore++; - } - } - - // - 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 = - // - ToString("isBullish", isBullish, ignoreFalseConditions, separator) + - ToString("isBearish", isBearish, ignoreFalseConditions, separator) + - ToString("isSwitchedToBullish", isSwitchedToBullish, ignoreFalseConditions, separator) + - ToString("isSwitchedToBearish", isSwitchedToBearish, ignoreFalseConditions, separator) + - "" - // - ; - - // - result = - // - "[" + GetTag() + "]" + separator + - (onlyConditions - ? "" - : commonStr) + - (!includeScores - ? "" - : scoresStr) + - " " + separator + - (onlyCommons - ? "" - : conditionsStr) + - "" - // - ; - - // - return result; - } - - // - string GetTag() - { - return "XSSLC"; - } -}; - -// -// Class ... -class XSCXSSLCHelper : public XSCBaseHelper -{ - // - // Public ... -public: - // - // Props ... - - // - // Constructors ... - XSCXSSLCHelper() : XSCBaseHelper(_Symbol, _Period) - { - } - - // - // Deconstructor ... - ~XSCXSSLCHelper() {} - - // - // Tools ... - bool Init( - string symbol, // Trading Symbol - ENUM_TIMEFRAMES period, // Trading Period - XSSLCInputs &inputs // Inputs - ) - { - // - bool result = false; - - // - mSymbol = symbol; - mPeriod = period; - - // - result = inputs.IsValid(); - if (!result) - { - return result; - } - - // - mInputs = inputs; - - // - ArraySetAsSeries(upBuffer, true); - ArraySetAsSeries(downBuffer, true); - - // - mHandler = iCustom( - mSymbol, - mPeriod, - "x-saherelm.xsslc", - // - // Inputs ... - // - // Market ... - "", - mInputs.length, // Length - // - // Calculation ... - "", - mInputs.method, // Method - mInputs.upAppliedTo, // Up Applied To - mInputs.downAppliedTo, // Down Applied To - // - // Presentation ... - "", - mInputs.showUp, // Show Up - mInputs.showDown // Show Down - // - ); - result = mHandler != INVALID_HANDLE; - if (!result) - { - return result; - } - - // - return result; - } - - // - // Inputs ... - - // - XSSLCInputs GetInputs() - { - return mInputs; - } - - // - bool SetInputs( - XSSLCInputs &inputs // Configs - ) - { - // - return Init( - mSymbol, - mPeriod, - inputs - // - ); - } - - // - // Buffers ... - - // - // Up ... - - // - double GetUp( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - int count = ArraySize(upBuffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return upBuffer[barIndex]; - } - - // - // Copy Required Items ... - int CopyUp( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - upBuffer, - buffer, - forceClean - // - ); - } - - // - // Down ... - - // - double GetDown( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - int count = ArraySize(downBuffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return downBuffer[barIndex]; - } - - // - // Copy Required Items ... - int CopyDown( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - downBuffer, - buffer, - forceClean - // - ); - } - - // - bool GetConditions( - XSSLCConditions &conditions, // - int barIndex = 0, // - int loopback = 3 // - ) - { - // - bool result = true; - - // - if (loopback < 3) - { - loopback = 3; - } - - // - conditions.Clean(); - - // - conditions.symbol = mSymbol; - conditions.period = mPeriod; - conditions.time = TimeCurrent(); - - // - int zIndex = barIndex; - int cIndex = zIndex + 1; - int pIndex = cIndex + 1; - int ppIndex = pIndex + 1; - - // - CopyUp( - zIndex, - loopback, - conditions.up // - ); - CopyDown( - zIndex, - loopback, - conditions.down // - ); - - // - // Calculate Conditions ... - - // - bool isBullish = conditions.up[cIndex] > conditions.down[cIndex]; - bool isBearish = conditions.up[cIndex] < conditions.down[cIndex]; - - // - bool isBullishPrev = conditions.up[pIndex] > conditions.down[pIndex]; - bool isBearishPrev = conditions.up[pIndex] < conditions.down[pIndex]; - - // - bool isSwitchedToBullish = isBullish && - !isBullishPrev; - bool isSwitchedToBearish = isBearish && - !isBearishPrev; - - // - conditions.isBullish = isBullish; - conditions.isBearish = isBearish; - conditions.isSwitchedToBullish = isSwitchedToBullish; - conditions.isSwitchedToBearish = isSwitchedToBearish; - - // - return result; - } - - // - // Protected ... -protected: - // - // Private ... -private: - // - // Props ... - XSSLCInputs mInputs; // Inputs ... - - // - // Buffers ... - double upBuffer[]; - double downBuffer[]; - - // - // Tools ... - - // - // Calculate Values Until Now ... - void Calculate() - { - // - int totalBars = CountBars(); - if (totalBars > 1000) { - totalBars = 1000; - } - - // - // Up ... - CopyBuffer( - mHandler, - XSSLC_UP_LINE, - 0, - totalBars, - upBuffer - // - ); - - // - // Down ... - CopyBuffer( - mHandler, - XSSLC_DOWN_LINE, - 0, - totalBars, - downBuffer - // - ); - } -}; - -// -// Tools ... \ No newline at end of file diff --git a/Documents/Pack/V1.0/Source/Helpers/x-saherelm.xstr.helper.mq5 b/Documents/Pack/V1.0/Source/Helpers/x-saherelm.xstr.helper.mq5 deleted file mode 100644 index 61d9867f..00000000 --- a/Documents/Pack/V1.0/Source/Helpers/x-saherelm.xstr.helper.mq5 +++ /dev/null @@ -1,643 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Helper Class Library -// ---------------------------------------------- -// Name: XSCXSTRHelper -// 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 - -// -#include "../Classes/x-saherelm.xhelper.class.mq5" - -// -// Definitions ... - -// -enum ENUM_XSTR_BUFFERS -{ - X_STR_TREND_LINE = 0, - X_STR_STATE_LINE = 5, -}; - -// -enum ENUM_XSTR_TREND_STATES -{ - X_STR_BULLISH = 1, // Bullish - X_STR_BEARISH = -1, // Bearish -}; - -// -// Input Models ... -struct XSTRInputs -{ - // - // Props ... - - // - // Market ... - int length; // Length - double multiplier; // Multiplier - ENUM_APPLIED_PRICE appliedTo; // Applied To - - // - // Presentation ... - bool showTrends; // Show Trends - bool fillTrends; // Fill Trends - - // - // Constructor(s) ... - XSTRInputs() - { - // - Clean(); - } - - // - // Tools ... - - // - // Clean ... - void Clean() - { - // - length = 0; - multiplier = 0; - appliedTo = PRICE_CLOSE; - // - showTrends = false; - fillTrends = false; - } - - // - // Default ... - void Default() - { - // - length = 14; - multiplier = 3.5; - appliedTo = PRICE_MEDIAN; - // - showTrends = true; - fillTrends = false; - } - - // - // Validate ... - bool IsValid() - { - // - bool result = false; - - // - result = - // - length > 0 && - multiplier > 0 - // - ; - - // - return result; - } - - // - // Retrieve MAx Length ... - int Max() - { - // - int result = 0; - - // - result = length; - - // - return result; - } -}; - -// -// Define Conditions ... -struct XSTRConditions -{ - // - // Common ... - string symbol; - ENUM_TIMEFRAMES period; - datetime time; - - // - // Buffers ... - double trend[]; - double state[]; - - // - // Conditions ... - - // - bool isTrendBullish; - bool isTrendBearish; - bool isTrendSwitchedToBullish; - bool isTrendSwitchedToBearish; - - // - void Clean() - { - // - Clean(trend); - Clean(state); - - // - ArraySetAsSeries(trend, true); - ArraySetAsSeries(state, true); - - // - isTrendBullish = false; - isTrendBearish = false; - isTrendSwitchedToBullish = false; - isTrendSwitchedToBearish = false; - } - - // - void GenerateScore( - double &bullishScore, - double &bearishScore // - ) - { - // - bullishScore = 0; - bearishScore = 0; - - // - if (isTrendBullish) - { - bullishScore++; - } - if (isTrendSwitchedToBullish) - { - bullishScore++; - } - - // - if (isTrendBearish) - { - bearishScore++; - } - if (isTrendSwitchedToBearish) - { - bearishScore++; - } - } - - // - 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 = - // - ToString("isTrendBullish", isTrendBullish, ignoreFalseConditions, separator) + - ToString("isTrendBearish", isTrendBearish, ignoreFalseConditions, separator) + - ToString("isTrendSwitchedToBullish", isTrendSwitchedToBullish, ignoreFalseConditions, separator) + - ToString("isTrendSwitchedToBearish", isTrendSwitchedToBearish, ignoreFalseConditions, separator) + - "" - // - ; - - // - result = - // - "[" + GetTag() + "]" + separator + - (onlyConditions - ? "" - : commonStr) + - (!includeScores - ? "" - : scoresStr) + - " " + separator + - (onlyCommons - ? "" - : conditionsStr) + - "" - // - ; - - // - return result; - } - - // - string GetTag() - { - return "XSTR"; - } -}; - -// -// Class ... -class XSCXSTRHelper : public XSCBaseHelper -{ - // - // Public ... -public: - // - // Props ... - - // - // Constructors ... - XSCXSTRHelper() : XSCBaseHelper(_Symbol, _Period) - { - } - - // - // Deconstructor ... - ~XSCXSTRHelper() {} - - // - // Tools ... - bool Init( - string symbol, // Trading Symbol - ENUM_TIMEFRAMES period, // Trading Period - XSTRInputs &inputs // Inputs - ) - { - // - bool result = false; - - // - mSymbol = symbol; - mPeriod = period; - - // - result = inputs.IsValid(); - if (!result) - { - return result; - } - - // - mInputs = inputs; - - // - ArraySetAsSeries(trendBuffer, true); - ArraySetAsSeries(stateBuffer, true); - - // - mHandler = iCustom( - mSymbol, - mPeriod, - "x-saherelm.xstr", - // - // Inputs ... - // - // ATR ... - "", - mInputs.length, // Length - mInputs.multiplier, // Multiplier - mInputs.appliedTo, // Applied To - // - // Presentation ... - "", - mInputs.showTrends, // Show Trends - mInputs.fillTrends // Fill Trends - // - ); - result = mHandler != INVALID_HANDLE; - if (!result) - { - return result; - } - - // - return result; - } - - // - // Inputs ... - - // - XSTRInputs GetInputs() - { - return mInputs; - } - - // - bool SetInputs( - XSTRInputs &inputs // Configs - ) - { - // - return Init( - mSymbol, - mPeriod, - inputs); - } - - // - // Buffers ... - - // - // Trend ... - - // - double GetTrend( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - return trendBuffer[barIndex]; - } - - // - // Copy Required Buffer ... - int CopyTrend( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - trendBuffer, - buffer, - forceClean - // - ); - } - - // - // State ... - - // - ENUM_XSTR_TREND_STATES GetState( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - return (ENUM_XSTR_TREND_STATES)((int)stateBuffer[barIndex]); - } - - // - // Copy Required Buffer ... - int CopyState( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - stateBuffer, - buffer, - forceClean - // - ); - } - - // - // Tools ... - - // - ENUM_XSTR_TREND_STATES ToState(double state) - { - return (ENUM_XSTR_TREND_STATES)((int)state); - } - - // - bool IsBullish(double state) - { - // - bool result = false; - - // - result = - // - ToState(state) == X_STR_BULLISH; - // - ; - - // - return result; - } - - // - bool IsBearish(double state) - { - // - bool result = false; - - // - result = - // - ToState(state) == X_STR_BEARISH; - // - ; - - // - return result; - } - - // - bool GetConditions( - XSTRConditions &conditions, // - int barIndex = 0, // - int loopback = 3 // - ) - { - // - bool result = true; - - // - if (loopback < 3) - { - loopback = 3; - } - - // - conditions.Clean(); - - // - conditions.symbol = mSymbol; - conditions.period = mPeriod; - conditions.time = TimeCurrent(); - - // - int zIndex = barIndex; - int cIndex = zIndex + 1; - int pIndex = cIndex + 1; - int ppIndex = pIndex + 1; - - // - CopyTrend( - zIndex, - loopback, - conditions.trend // - ); - CopyState( - zIndex, - loopback, - conditions.state // - ); - - // - // Calculate Conditions ... - - // - bool isTrendBullish = IsBullish(conditions.state[cIndex]); - bool isTrendBearish = IsBearish(conditions.state[cIndex]); - - // - bool isTrendBullishPrev = IsBullish(conditions.state[pIndex]); - bool isTrendBearishPrev = IsBearish(conditions.state[pIndex]); - - // - bool isTrendSwitchedToBullish = isTrendBullish && - !isTrendBullishPrev; - bool isTrendSwitchedToBearish = isTrendBearish && - !isTrendBearishPrev; - - // - conditions.isTrendBullish = isTrendBullish; - conditions.isTrendBearish = isTrendBearish; - conditions.isTrendSwitchedToBullish = isTrendSwitchedToBullish; - conditions.isTrendSwitchedToBearish = isTrendSwitchedToBearish; - - // - return result; - } - - // - // Protected ... -protected: - // - // Private ... -private: - // - // Props ... - XSTRInputs mInputs; // Inputs ... - - // - // Buffers ... - double trendBuffer[]; - double stateBuffer[]; - - // - // Tools ... - - // - // Calculate Values Until Now ... - void Calculate() - { - // - int totalBars = CountBars(); - if (totalBars > 1000) { - totalBars = 1000; - } - - // - // Trend ... - CopyBuffer( - mHandler, - X_STR_TREND_LINE, - 0, - totalBars, - trendBuffer - // - ); - - // - // State ... - CopyBuffer( - mHandler, - X_STR_STATE_LINE, - 0, - totalBars, - stateBuffer - // - ); - } -}; - -// -// Tools ... diff --git a/Documents/Pack/V1.0/Source/Helpers/x-saherelm.xtd.helper.mq5 b/Documents/Pack/V1.0/Source/Helpers/x-saherelm.xtd.helper.mq5 deleted file mode 100644 index 4a4aacf6..00000000 --- a/Documents/Pack/V1.0/Source/Helpers/x-saherelm.xtd.helper.mq5 +++ /dev/null @@ -1,681 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Helper Class Library -// ---------------------------------------------- -// Name: XSCXTDHelper -// 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.xhelper.class.mq5" - -// -// Definitions ... - -// -enum ENUM_XTD_BUFFERS -{ - XTD_BULLISH_LINE = 0, - XTD_BEARISH_LINE = 1, - XTD_SIGNAL_LINE = 2, -}; - -// -// Input Models ... -struct XTDInputs -{ - // - // Props ... - // - int length; // Market Length - bool drawCrosses; // Draw Cross Arrows - - // - // Bullish ... - uchar bullishArrowCode; // Cross Over Arrow Code - color bullishArrowColor; // Cross Over Arrow Color - - // - // Bearish ... - uchar bearishArrowCode; // Cross Under Arrow Code - color bearishArrowColor; // Cross Under Arrow Color - - // - // Constructor(s) ... - XTDInputs() - { - // - Clean(); - } - - // - // Tools ... - - // - // Clean ... - void Clean() - { - // - length = 0; - drawCrosses = false; - - // - // Bullish ... - bullishArrowCode = 228; - bullishArrowColor = CLR_NONE; - - // - // Bearish ... - bearishArrowCode = 230; - bearishArrowColor = CLR_NONE; - } - - // - // Default ... - void Default() - { - // - length = 14; - drawCrosses = false; - - // - // Bullish ... - bullishArrowCode = 228; - bullishArrowColor = CLR_NONE; - - // - // Bearish ... - bearishArrowCode = 230; - bearishArrowColor = CLR_NONE; - } - - // - // Validate ... - bool IsValid() - { - // - bool result = false; - - // - result = - // - length >= 2 - // - ; - - // - return result; - } - - // - // Retrieve MAx Length ... - int Max() - { - // - int result = 0; - - // - result = MathMax(result, length); - - // - return result; - } -}; - -// -// Define Conditions ... -struct XTDConditions -{ - // - // Common ... - string symbol; - ENUM_TIMEFRAMES period; - datetime time; - - // - // Buffers ... - double bullish[]; - double bearish[]; - - // - // Conditions ... - - // - bool isBullish; - bool isBearish; - bool isSwitchedToBullish; - bool isSwitchedToBearish; - - // - void Clean() - { - // - Clean(bullish); - Clean(bearish); - - // - ArraySetAsSeries(bullish, true); - ArraySetAsSeries(bearish, true); - - // - isBullish = false; - isBearish = false; - isSwitchedToBullish = false; - isSwitchedToBearish = false; - } - - // - void GenerateScore( - double &bullishScore, - double &bearishScore // - ) - { - // - bullishScore = 0; - bearishScore = 0; - - // - if (isBullish) - { - bullishScore++; - } - if (isSwitchedToBullish) - { - bullishScore++; - } - - // - if (isBearish) - { - bearishScore++; - } - if (isSwitchedToBearish) - { - bearishScore++; - } - } - - // - 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 = - // - ToString("isBullish", isBullish, ignoreFalseConditions, separator) + - ToString("isBearish", isBearish, ignoreFalseConditions, separator) + - ToString("isSwitchedToBullish", isSwitchedToBullish, ignoreFalseConditions, separator) + - ToString("isSwitchedToBearish", isSwitchedToBearish, ignoreFalseConditions, separator) + - "" - // - ; - - // - result = - // - "[" + GetTag() + "]" + separator + - (onlyConditions - ? "" - : commonStr) + - (!includeScores - ? "" - : scoresStr) + - " " + separator + - (onlyCommons - ? "" - : conditionsStr) + - "" - // - ; - - // - return result; - } - - // - string GetTag() - { - return "XTD"; - } -}; - -// -// Class ... -class XSCXTDHelper : public XSCBaseHelper -{ - // - // Public ... -public: - // - // Props ... - - // - // Constructors ... - XSCXTDHelper() : XSCBaseHelper(_Symbol, _Period) - { - } - - // - // Deconstructor ... - ~XSCXTDHelper() {} - - // - // Tools ... - bool Init( - string symbol, // Trading Symbol - ENUM_TIMEFRAMES period, // Trading Period - XTDInputs &inputs // Inputs - ) - { - // - bool result = false; - - // - mSymbol = symbol; - mPeriod = period; - - // - result = inputs.IsValid(); - if (!result) - { - return result; - } - - // - mInputs = inputs; - - // - ArraySetAsSeries(bullishBuffer, true); - ArraySetAsSeries(bearishBuffer, true); - ArraySetAsSeries(signalBuffer, true); - - // - mHandler = iCustom( - mSymbol, - mPeriod, - "x-saherelm.xtd", - // - // Inputs ... - // - mInputs.length, // Market Length - mInputs.drawCrosses, // Draw Cross Arrows - // - // Bullish ... - mInputs.bullishArrowCode, // Cross Over Arrow Code - mInputs.bullishArrowColor, // Cross Over Arrow Color - // - // Bearish ... - mInputs.bearishArrowCode, // Cross Under Arrow Code - mInputs.bearishArrowColor // Cross Under Arrow Color - // - ); - result = mHandler != INVALID_HANDLE; - if (!result) - { - return result; - } - - // - return result; - } - - // - // Inputs ... - - // - XTDInputs GetInputs() - { - return mInputs; - } - - // - bool SetInputs( - XTDInputs &inputs // Configs - ) - { - // - return Init( - mSymbol, - mPeriod, - inputs - // - ); - } - - // - // Buffers ... - - // - double GetBullish( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - int count = ArraySize(bullishBuffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return bullishBuffer[barIndex]; - } - - // - // Copy Required Items ... - int CopyBullish( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - bullishBuffer, - buffer, - forceClean - // - ); - } - - // - double GetBearish( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - int count = ArraySize(bearishBuffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return bearishBuffer[barIndex]; - } - - // - // Copy Required Items ... - int CopyBearish( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - bearishBuffer, - buffer, - forceClean - // - ); - } - - // - double GetSignal( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - int count = ArraySize(signalBuffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return signalBuffer[barIndex]; - } - - // - // Copy Required Items ... - int CopySignal( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - signalBuffer, - buffer, - forceClean - // - ); - } - - // - bool GetConditions( - XTDConditions &conditions, // - int barIndex = 0, // - int loopback = 3 // - ) - { - // - bool result = true; - - // - if (loopback < 3) - { - loopback = 3; - } - - // - conditions.Clean(); - - // - conditions.symbol = mSymbol; - conditions.period = mPeriod; - conditions.time = TimeCurrent(); - - // - int zIndex = barIndex; - int cIndex = zIndex + 1; - int pIndex = cIndex + 1; - int ppIndex = pIndex + 1; - - // - CopyBullish( - zIndex, - loopback, - conditions.bullish // - ); - CopyBearish( - zIndex, - loopback, - conditions.bearish // - ); - - // - // Calculate Conditions ... - - // - bool isBullish = conditions.bullish[cIndex] > conditions.bearish[cIndex]; - bool isBearish = conditions.bullish[cIndex] < conditions.bearish[cIndex]; - - // - bool isBullishPrev = conditions.bullish[pIndex] > conditions.bearish[pIndex]; - bool isBearishPrev = conditions.bullish[pIndex] < conditions.bearish[pIndex]; - - // - bool isSwitchedToBullish = isBullish && - !isBullishPrev; - bool isSwitchedToBearish = isBearish && - !isBearishPrev; - - // - conditions.isBullish = isBullish; - conditions.isBearish = isBearish; - conditions.isSwitchedToBullish = isSwitchedToBullish; - conditions.isSwitchedToBearish = isSwitchedToBearish; - - // - return result; - } - - // - // Protected ... -protected: - // - // Private ... -private: - // - // Props ... - XTDInputs mInputs; // Inputs ... - - // - // Buffers ... - double bullishBuffer[]; - double bearishBuffer[]; - double signalBuffer[]; - - // - // Tools ... - - // - // Calculate Values Until Now ... - void Calculate() - { - // - int totalBars = CountBars(); - if (totalBars > 1000) { - totalBars = 1000; - } - - // - // Bullish ... - CopyBuffer( - mHandler, - XTD_BULLISH_LINE, - 0, - totalBars, - bullishBuffer - // - ); - - // - // Bearish ... - CopyBuffer( - mHandler, - XTD_BEARISH_LINE, - 0, - totalBars, - bearishBuffer - // - ); - - // - // Signal ... - CopyBuffer( - mHandler, - XTD_SIGNAL_LINE, - 0, - totalBars, - signalBuffer - // - ); - } -}; - -// -// Tools ... \ No newline at end of file diff --git a/Documents/Pack/V1.0/Source/Helpers/x-saherelm.xtm.helper.mq5 b/Documents/Pack/V1.0/Source/Helpers/x-saherelm.xtm.helper.mq5 deleted file mode 100644 index b8e1c7c4..00000000 --- a/Documents/Pack/V1.0/Source/Helpers/x-saherelm.xtm.helper.mq5 +++ /dev/null @@ -1,313 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Helper Class Library -// ---------------------------------------------- -// Name: XSCXTMHelper -// 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.xhelper.class.mq5" - -// -// Definitions ... - -// -enum ENUM_XTM_BUFFERS -{ - XTM_MAIN_LINE = 0 -}; - -// -// Input Models ... -struct XTMInputs -{ - // - // Props ... - // - // Market ... - int maPeriod; // Period - int maShift; // Shift - ENUM_MA_METHOD maMethod; // Method - ENUM_APPLIED_PRICE maAppliedTo; // Applied To - // - // Presentation ... - bool showLine; // Show Line - - // - // Constructor(s) ... - XTMInputs() - { - // - Clean(); - } - - // - // Tools ... - - // - // Clean ... - void Clean() - { - // - maShift = 0; - maPeriod = 0; - showLine = false; - maMethod = MODE_SMA; - maAppliedTo = PRICE_CLOSE; - } - - // - // Default ... - void Default() - { - // - maShift = 0; - maPeriod = 14; - showLine = true; - maMethod = MODE_SMA; - maAppliedTo = PRICE_CLOSE; - } - - // - // Validate ... - bool IsValid() - { - // - bool result = false; - - // - result = - // - maPeriod >= 2 - // - ; - - // - return result; - } - - // - // Retrieve MAx Length ... - int Max() - { - // - int result = 0; - - // - result = MathMax(result, maPeriod); - - // - return result; - } -}; - -// -// Class ... -class XSCXTMHelper : public XSCBaseHelper -{ - // - // Public ... -public: - // - // Props ... - - // - // Constructors ... - XSCXTMHelper() : XSCBaseHelper(_Symbol, _Period) - { - } - - // - // Deconstructor ... - ~XSCXTMHelper() {} - - // - // Tools ... - bool Init( - string symbol, // Trading Symbol - ENUM_TIMEFRAMES period, // Trading Period - XTMInputs &inputs // Inputs - ) - { - // - bool result = false; - - // - mSymbol = symbol; - mPeriod = period; - - // - result = inputs.IsValid(); - if (!result) - { - return result; - } - - // - mInputs = inputs; - - // - ArraySetAsSeries(mainBuffer, true); - mHandler = iCustom( - mSymbol, - mPeriod, - "x-saherelm.xtm", - // - // Inputs ... - // - // Market ... - "", - mInputs.maPeriod, // Period - mInputs.maShift, // Shift - mInputs.maMethod, // Method - mInputs.maAppliedTo, // Applied To - // - // Presentation ... - "", - mInputs.showLine // Show Line - // - ); - result = mHandler != INVALID_HANDLE; - if (!result) - { - return result; - } - - // - return result; - } - - // - // Inputs ... - - // - XTMInputs GetInputs() - { - return mInputs; - } - - // - bool SetInputs( - XTMInputs &inputs // Configs - ) - { - // - return Init( - mSymbol, - mPeriod, - inputs - // - ); - } - - // - // Buffers ... - - // - double GetMain( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - int count = ArraySize(mainBuffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return mainBuffer[barIndex]; - } - - // - // Copy Required Items ... - int CopyMain( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - mainBuffer, - buffer, - forceClean - // - ); - } - - // - // Protected ... -protected: - // - // Private ... -private: - // - // Props ... - XTMInputs mInputs; // Inputs ... - - // - // Buffers ... - double mainBuffer[]; - - // - // Tools ... - - // - // Calculate Values Until Now ... - void Calculate() - { - // - int totalBars = CountBars(); - if (totalBars > 1000) { - totalBars = 1000; - } - - // - // Main Buffer ... - CopyBuffer( - mHandler, - XTM_MAIN_LINE, - 0, - totalBars, - mainBuffer - // - ); - } -}; - -// -// Tools ... \ No newline at end of file diff --git a/Documents/Pack/V1.0/Source/Helpers/x-saherelm.xvlm.helper.mq5 b/Documents/Pack/V1.0/Source/Helpers/x-saherelm.xvlm.helper.mq5 deleted file mode 100644 index 2b9db8ec..00000000 --- a/Documents/Pack/V1.0/Source/Helpers/x-saherelm.xvlm.helper.mq5 +++ /dev/null @@ -1,553 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Helper Class Library -// ---------------------------------------------- -// Name: XSCXVLMHelper -// 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 - -// -#include "../Classes/x-saherelm.xhelper.class.mq5" - -// -// Definitions ... - -// -enum ENUM_XVLM_BUFFERS -{ - XVLM_VOLUME_LINE = 0 -}; - -// -// Input Models ... -struct XVLMInputs -{ - // - // Props ... - - // - int length; // Length - - // - // Constructor(s) ... - XVLMInputs() - { - Clean(); - } - - // - // Tools ... - - // - // Clean ... - void Clean() - { - length = 0; - } - - // - // Default ... - void Default() - { - length = 14; - } - - // - // Validate ... - bool IsValid() - { - // - bool result = false; - - // - result = - // - length > 1 - // - ; - - // - return result; - } - - // - // Retrieve MAx Length ... - int Max() - { - // - int result = 0; - - // - result = length; - - // - return result; - } -}; - -// -// Define Conditions ... -struct XVLMConditions -{ - // - // Common ... - string symbol; - ENUM_TIMEFRAMES period; - datetime time; - - // - // Buffers ... - double volume[]; - - // - // Conditions ... - - // - bool isVolumeBullish; - bool isVolumeBearish; - bool isVolumeOverLast; - bool isVolumeUnderLast; - bool isVolumeChangedToBullish; - bool isVolumeChangedToBearish; - - // - void Clean() - { - // - Clean(volume); - - // - ArraySetAsSeries(volume, true); - - // - isVolumeBullish = false; - isVolumeBearish = false; - isVolumeOverLast = false; - isVolumeUnderLast = false; - isVolumeChangedToBullish = false; - isVolumeChangedToBearish = false; - } - - // - void GenerateScore( - double &bullishScore, - double &bearishScore // - ) - { - // - bullishScore = 0; - bearishScore = 0; - - // - if (isVolumeBullish) - { - bullishScore++; - } - if (isVolumeOverLast) - { - bullishScore++; - } - if (isVolumeChangedToBullish) - { - bullishScore++; - } - - // - if (isVolumeBearish) - { - bearishScore++; - } - if (isVolumeUnderLast) - { - bearishScore++; - } - if (isVolumeChangedToBearish) - { - bearishScore++; - } - } - - // - 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 = - // - ToString("isVolumeBullish", isVolumeBullish, ignoreFalseConditions, separator) + - ToString("isVolumeBearish", isVolumeBearish, ignoreFalseConditions, separator) + - ToString("isVolumeOverLast", isVolumeOverLast, ignoreFalseConditions, separator) + - ToString("isVolumeUnderLast", isVolumeUnderLast, ignoreFalseConditions, separator) + - ToString("isVolumeChangedToBullish", isVolumeChangedToBullish, ignoreFalseConditions, separator) + - ToString("isVolumeChangedToBearish", isVolumeChangedToBearish, ignoreFalseConditions, separator) + - "" - // - ; - - // - result = - // - "[" + GetTag() + "]" + separator + - (onlyConditions - ? "" - : commonStr) + - (!includeScores - ? "" - : scoresStr) + - " " + separator + - (onlyCommons - ? "" - : conditionsStr) + - "" - // - ; - - // - return result; - } - - // - string GetTag() - { - return "XVLM"; - } -}; - -// -// Class ... -class XSCXVLMHelper : public XSCBaseHelper -{ - // - // Public ... -public: - // - // Props ... - - // - // Constructors ... - XSCXVLMHelper() : XSCBaseHelper(_Symbol, _Period) - { - } - - // - // Deconstructor ... - ~XSCXVLMHelper() {} - - // - // Tools ... - bool Init( - string symbol, // Trading Symbol - ENUM_TIMEFRAMES period, // Trading Period - XVLMInputs &inputs // Inputs - ) - { - // - bool result = false; - - // - mSymbol = symbol; - mPeriod = period; - - // - result = inputs.IsValid(); - if (!result) - { - return result; - } - - // - mInputs = inputs; - - // - ArraySetAsSeries(volumeBuffer, true); - - // - mHandler = iCustom( - mSymbol, - mPeriod, - "x-saherelm.xvlm", - // - // Inputs ... - mInputs.length // Length - ); - result = mHandler != INVALID_HANDLE; - if (!result) - { - return result; - } - - // - return result; - } - - // - // Inputs ... - - // - XVLMInputs GetInputs() - { - return mInputs; - } - - // - bool SetInputs( - XVLMInputs &inputs // Configs - ) - { - // - return Init( - mSymbol, - mPeriod, - inputs); - } - - // - // Buffers ... - - // - // Volume ... - - // - double GetVolume( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - return volumeBuffer[barIndex]; - } - - // - // Copy Required Buffer ... - int CopyVolume( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - volumeBuffer, - buffer, - forceClean - // - ); - } - - // - // Tools ... - - // - bool IsBullish(double volume) - { - // - bool result = false; - - // - result = - // - volume > 0; - // - ; - - // - return result; - } - - // - bool IsBearish(double volume) - { - // - bool result = false; - - // - result = - // - volume < 0 - // - ; - - // - return result; - } - - // - bool GetConditions( - XVLMConditions &conditions, // - int barIndex = 0, // - int loopback = 4 // - ) - { - // - bool result = true; - - // - if (loopback < 4) - { - loopback = 4; - } - - // - conditions.Clean(); - - // - conditions.symbol = mSymbol; - conditions.period = mPeriod; - conditions.time = TimeCurrent(); - - // - int zIndex = barIndex; - int cIndex = zIndex + 1; - int pIndex = cIndex + 1; - int ppIndex = pIndex + 1; - - // - CopyVolume( - zIndex, - loopback, - conditions.volume // - ); - - // - // Calculate Conditions ... - - // - bool isVolumeBullish = conditions.volume[cIndex] > 0; - bool isVolumeBullishPrev = conditions.volume[pIndex] > 0; - - // - bool isVolumeBearish = conditions.volume[cIndex] < 0; - bool isVolumeBearishPrev = conditions.volume[pIndex] < 0; - - // - bool isVolumeOverLast = conditions.volume[cIndex] > conditions.volume[pIndex]; - bool isVolumeOverLastPrev = conditions.volume[pIndex] > conditions.volume[ppIndex]; - - // - bool isVolumeUnderLast = conditions.volume[cIndex] < conditions.volume[pIndex]; - bool isVolumeUnderLastPrev = conditions.volume[pIndex] < conditions.volume[ppIndex]; - - // - bool isVolumeChangedToBullish = isVolumeBullish && - !isVolumeBullishPrev; - bool isVolumeChangedToBearish = isVolumeBearish && - !isVolumeBearishPrev; - - // - conditions.isVolumeBullish = isVolumeBullish; - conditions.isVolumeBearish = isVolumeBearish; - conditions.isVolumeOverLast = isVolumeOverLast; - conditions.isVolumeUnderLast = isVolumeUnderLast; - conditions.isVolumeChangedToBullish = isVolumeChangedToBullish; - conditions.isVolumeChangedToBearish = isVolumeChangedToBearish; - - // - return result; - } - - // - // Protected ... -protected: - // - // Private ... -private: - // - // Props ... - XVLMInputs mInputs; // Inputs ... - - // - // Buffers ... - double volumeBuffer[]; - - // - // Tools ... - - // - // Calculate Values Until Now ... - void Calculate() - { - // - int totalBars = CountBars(); - if (totalBars > 1000) { - totalBars = 1000; - } - - // - // Trend ... - CopyBuffer( - mHandler, - XVLM_VOLUME_LINE, - 0, - totalBars, - volumeBuffer - // - ); - } -}; - -// -// Tools ... diff --git a/Documents/Pack/V1.0/Source/Helpers/x-saherelm.xzg.helper.mq5 b/Documents/Pack/V1.0/Source/Helpers/x-saherelm.xzg.helper.mq5 deleted file mode 100644 index a68318d8..00000000 --- a/Documents/Pack/V1.0/Source/Helpers/x-saherelm.xzg.helper.mq5 +++ /dev/null @@ -1,530 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Helper Class Library -// ---------------------------------------------- -// Name: XSCXZGHelper -// 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.xhelper.class.mq5" - -// -// Definitions ... - -// -// How to Calculate Up and Down Price ... -enum ENUM_X_ZG_PRICE_MODE -{ - // - X_ZG_PRICE_HIGH_LOW_MODE = 1, - X_ZG_PRICE_OPEN_CLOSE_MODE = 2, -}; - -// -enum ENUM_XZG_BUFFERS -{ - // - XZG_MAIN_LINE = 0, - XZG_PEAKSANDVALES_LINE = 2, - XZG_HIGHS_LINE = 4, - XZG_LOWS_LINE = 5, -}; - -// -// Input Models ... -struct XZGInputs -{ - // - // Props ... - - // - // Market ... - int depth; // Depth - int deviation; // Deviation - int backStep; // Back Step - ENUM_X_ZG_PRICE_MODE mode; // Mode - // - // Presentation ... - bool showZigZag; // Show ZigZag - bool showPeaksAndVales; // Show Peaks and Vales - - // - // Constructor(s) ... - XZGInputs() - { - // - Clean(); - } - - // - // Tools ... - - // - // Clean ... - void Clean() - { - // - // Market ... - depth = 0; - deviation = 0; - backStep = 0; - mode = X_ZG_PRICE_HIGH_LOW_MODE; - // - // Presentation ... - showZigZag = false; - showPeaksAndVales = false; - } - - // - // Default ... - void Default() - { - // - // Market ... - depth = 12; - deviation = 5; - backStep = 3; - mode = X_ZG_PRICE_HIGH_LOW_MODE; - // - // Presentation ... - showZigZag = true; - showPeaksAndVales = true; - } - - // - // Validate ... - bool IsValid() - { - // - bool result = false; - - // - result = - // - depth > 0 && - deviation > 0 && - backStep > 0 - // - ; - - // - return result; - } - - // - // Retrieve MAx Length ... - int Max() - { - // - int result = 0; - - // - result = MathMax(backStep, depth); - - // - return result; - } -}; - -// -// Class ... -class XSCXZGHelper : public XSCBaseHelper -{ - // - // Public ... -public: - // - // Props ... - - // - // Constructors ... - XSCXZGHelper() : XSCBaseHelper(_Symbol, _Period) - { - } - - // - // Deconstructor ... - ~XSCXZGHelper() {} - - // - // Tools ... - bool Init( - string symbol, // Trading Symbol - ENUM_TIMEFRAMES period, // Trading Period - XZGInputs &inputs // Inputs - ) - { - // - bool result = false; - - // - mSymbol = symbol; - mPeriod = period; - - // - result = inputs.IsValid(); - if (!result) - { - return result; - } - - // - mInputs = inputs; - - // - ArraySetAsSeries(mainBuffer, true); - ArraySetAsSeries(PeaksAndValesBuffer, true); - ArraySetAsSeries(highsBuffer, true); - ArraySetAsSeries(lowsBuffer, true); - - // - mHandler = iCustom( - mSymbol, - mPeriod, - "x-saherelm.xzg", - // - // Inputs ... - // - // Market ... - "", - mInputs.depth, // Depth - mInputs.deviation, // Deviation - mInputs.backStep, // Back Step - mInputs.mode, // Mode - // - // Presentation ... - "", - mInputs.showZigZag, // Show ZigZag - mInputs.showPeaksAndVales // Show Peaks and Vales - // - ); - result = mHandler != INVALID_HANDLE; - if (!result) - { - return result; - } - - // - return result; - } - - // - // Inputs ... - - // - XZGInputs GetInputs() - { - return mInputs; - } - - // - bool SetInputs( - XZGInputs &inputs // Configs - ) - { - // - return Init( - mSymbol, - mPeriod, - inputs - // - ); - } - - // - // Buffers ... - - // - double GetMain( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - int count = ArraySize(mainBuffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return mainBuffer[barIndex]; - } - - // - // Copy Required Items ... - int CopyMain( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - mainBuffer, - buffer, - forceClean - // - ); - } - - // - double GetPeaksAndVales( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - int count = ArraySize(PeaksAndValesBuffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return PeaksAndValesBuffer[barIndex]; - } - - // - // Copy Required Items ... - int CopyPeaksAndVales( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - PeaksAndValesBuffer, - buffer, - forceClean - // - ); - } - - // - double GetHigh( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - int count = ArraySize(highsBuffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return highsBuffer[barIndex]; - } - - // - // Copy Required Items ... - int CopyHigh( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - highsBuffer, - buffer, - forceClean - // - ); - } - - // - double GetLow( - int barIndex // Bar Index - ) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - Calculate(); - - // - int count = ArraySize(lowsBuffer); - if (barIndex >= count) - { - barIndex = count - 1; - } - - // - return lowsBuffer[barIndex]; - } - - // - // Copy Required Items ... - int CopyLow( - int start, // Start - int count, // Number of Items for read - double &buffer[], // Dest Buffer - bool forceClean = true // Force To Clean buffer - ) - { - // - // Update Calculations ... - Calculate(); - - // - // Copy Items ... - return Copy( - start, - count, - lowsBuffer, - buffer, - forceClean - // - ); - } - - // - // Protected ... -protected: - // - // Private ... -private: - // - // Props ... - XZGInputs mInputs; // Inputs ... - - // - // Buffers ... - double mainBuffer[]; - double PeaksAndValesBuffer[]; - double highsBuffer[]; - double lowsBuffer[]; - - // - // Tools ... - - // - // Calculate Values Until Now ... - void Calculate() - { - // - int totalBars = CountBars(); - if (totalBars > 1000) { - totalBars = 1000; - } - - // - // Main Buffer ... - CopyBuffer( - mHandler, - XZG_MAIN_LINE, - 0, - totalBars, - mainBuffer - // - ); - - // - // Peaks and Vales Buffer ... - CopyBuffer( - mHandler, - XZG_PEAKSANDVALES_LINE, - 0, - totalBars, - PeaksAndValesBuffer - // - ); - - // - // Highs Buffer ... - CopyBuffer( - mHandler, - XZG_HIGHS_LINE, - 0, - totalBars, - highsBuffer - // - ); - - // - // Lows Buffer ... - CopyBuffer( - mHandler, - XZG_LOWS_LINE, - 0, - totalBars, - lowsBuffer - // - ); - } -}; - -// -// Tools ... \ No newline at end of file diff --git a/Documents/Pack/V1.0/Source/Indicators/x-saherelm.xadxtd.mq5 b/Documents/Pack/V1.0/Source/Indicators/x-saherelm.xadxtd.mq5 deleted file mode 100644 index 0812561f..00000000 --- a/Documents/Pack/V1.0/Source/Indicators/x-saherelm.xadxtd.mq5 +++ /dev/null @@ -1,223 +0,0 @@ -/////////////////////////////////////////////////////// -// SaherElm IT Center MQL5 Indicator -// ------------------------------------------- -// Name: XADXTD -// Description: ADX TD Channel ... -// -// 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 XADXTD Indicator" -#property strict - -// -#define ShortName "XADXTD" - -// -// Imports ... -#include "../Libraries/x-saherelm.common.lib.mq5" - -// -// Inputs ... -input int length = 21; // Length - -// -// BUFFERS ... - -// -#property indicator_chart_window - -// -#property indicator_buffers 3 -#property indicator_plots 0 - -// -#define strengthBufferIndex 0 -double strengthBuffer[]; - -// -#define bullpBufferIndex 1 -double bullpBuffer[]; - -// -#define bearpBufferIndex 2 -double bearpBuffer[]; - -// -int maxLength = 0; -int mHandler = INVALID_HANDLE; - -// -// Event Handlers ... - -// -// Initialization ... -int OnInit() -{ - // - // Validate Inputs ... - if (!ValidateInputs()) - { - return INIT_PARAMETERS_INCORRECT; - } - - // - // because in some cases we may have more than one input for - // calculation and we must prevent any calculation - // untill we pass the biggest input length, here we get max Input length - // and then wait until pass it ... - maxLength = ExtractMaxLengthOfInputs(); - - // - // Define Index Buffers ... - DefineBuffers(); - - // - // Set Indicator ShortName ... - SetIndicatorName(); - - // - mHandler = iADX( - _Symbol, - _Period, - length // - ); - if (mHandler == INVALID_HANDLE) - { - 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 - - // - IndicatorRelease(mHandler); -} - -// -// Calculating what we want ... -int OnCalculate( - const int rates_total, // Total Bars on Chart ... - const int prev_calculated, // Total Calculated Bars on Charts ... - const datetime &time[], // History of Open Time ... - const double &open[], // History of Open Price ... - const double &high[], // History of High Price ... - const double &low[], // History of Low Price ... - const double &close[], // History of Close Price ... - const long &tick_volume[], // History of Tick Volumes on Bar ... - const long &volume[], // History of Trade Volumes ... - const int &spread[] // History of Spread Price ... -) -{ - // - // this counts Available Bars ... - int limit; - - // - // Check Calculated Bars ... - int adxCalculatedBars = BarsCalculated(mHandler); - if (adxCalculatedBars < maxLength) - { - return prev_calculated; - } - - // - limit = (prev_calculated > rates_total || prev_calculated <= 0) ? rates_total : (rates_total - prev_calculated) + 1; - - // - // Buffers Copy ... - int copiedADXStrength = CopyBuffer(mHandler, MAIN_LINE, 0, limit, strengthBuffer); - int copiedADXBullp = CopyBuffer(mHandler, PLUSDI_LINE, 0, limit, bullpBuffer); - int copiedADXBearP = CopyBuffer(mHandler, MINUSDI_LINE, 0, limit, bearpBuffer); - if (copiedADXBullp <= 0 || - copiedADXBearP <= 0 || - copiedADXStrength <= 0) - { - return prev_calculated; - } - - // - return rates_total; -} - -// -// Functions ... - -// -// Validate Input Args for Initialization ... -bool ValidateInputs() -{ - // - bool result = - // - (length > 0) - // - ; - - // - return result; -} - -// -// Retrieve all Exists Input Max Length ... -// use for Start Of Drawing ... -int ExtractMaxLengthOfInputs() -{ - // - int result = 0; - - // - result = MathMax(result, length); - - // - return result; -} - -// -// Set Indicator Short Name and also we can define Buffers Labels ... -void SetIndicatorName() -{ - IndicatorSetString(INDICATOR_SHORTNAME, ShortName); -} - -// -// Define Indexes and Styles ... -void DefineBuffers() -{ - // - ArraySetAsSeries(strengthBuffer, true); - SetIndexBuffer(strengthBufferIndex, strengthBuffer, INDICATOR_CALCULATIONS); - - // - ArraySetAsSeries(bullpBuffer, true); - SetIndexBuffer(bullpBufferIndex, bullpBuffer, INDICATOR_CALCULATIONS); - - // - ArraySetAsSeries(bearpBuffer, true); - SetIndexBuffer(bearpBufferIndex, bearpBuffer, INDICATOR_CALCULATIONS); -} \ No newline at end of file diff --git a/Documents/Pack/V1.0/Source/Indicators/x-saherelm.xama.mq5 b/Documents/Pack/V1.0/Source/Indicators/x-saherelm.xama.mq5 deleted file mode 100644 index 714a25d7..00000000 --- a/Documents/Pack/V1.0/Source/Indicators/x-saherelm.xama.mq5 +++ /dev/null @@ -1,348 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 XAMA Indicator -// --------------------------------------------- -// Name: XAMA -// Description: Trend Magic Indicator ... -// -// -// Maintainer: -// ------------ -// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) -// -////////////////////////////////////////////////////// -// -// Global Properties ... -#property copyright "Copyright 2023, SaherElm IT Center" -#property link "https://saherelm.ir" -#property version "1.00" -#property description "SaherElm XAMA Indicator" -#property strict - -// -// Constants ... - -#define ShortName "XAMA" - -// -// Indicator States ... -enum ENUM_X_XAMA_STATES -{ - X_XAMA_BULLISH = 1, - X_XAMA_BEARISH = -1, - X_XAMA_NEUTURAL = 0, -}; - -// -// Inputs ... - -// -// Market ... -input group "Market"; -input int length = 18; // Period -input int fastEMA = 2; // Fast EMA Period -input int slowEMA = 30; // Slow EMA Period -input int maShift = 0; // Shift -input ENUM_APPLIED_PRICE appliedTo = PRICE_CLOSE; // Applied To - -// -// Presentation ... -input group "Presentation"; -input bool showLine = true; // Show Line - -// -// Includes Common Library ... -#include "../Libraries/x-saherelm.common.lib.mq5" - -// -// START Buffers ... -// -#property indicator_chart_window - -// -#property indicator_buffers 3 -#property indicator_plots 1 - -// -// maBuffer ... -#define maBufferIndex 0 -#define maColorBufferIndex 1 -#define stateBufferIndex 2 - -double maBuffer[]; -double maColorBuffer[]; -double stateBuffer[]; - -#property indicator_label1 "XAMA" -#property indicator_type1 DRAW_COLOR_LINE -#property indicator_color1 clrLime, clrGray, clrRed, CLR_NONE -#property indicator_style1 STYLE_SOLID -#property indicator_width1 1 -// -// END Buffers ... -// - -// -// START Global Definitions: Variables, Properties and etc ... -// -int maHandler = INVALID_HANDLE; -// -// END Global Definitions: Variables, Properties and etc ... -// - -// -// START Event Handlers ... -// -// -// Initialization ... -int OnInit() -{ - // - // Validate Inputs ... - if (!ValidateInputs()) - { - return INIT_PARAMETERS_INCORRECT; - } - - // - // Initializing MA Handler ... - maHandler = iAMA( - _Symbol, - _Period, - length, - fastEMA, - slowEMA, - maShift, - appliedTo); - if (maHandler == INVALID_HANDLE) - { - // - return INIT_FAILED; - } - - // - // Define Index Buffers ... - DefineBuffers(); - - // - // Set Indicator ShortName ... - SetIndicatorName(); - - // - // Init Succeed ... - return INIT_SUCCEEDED; -} - -// -// DeInitialization ... -void OnDeinit(const int reason) -{ - // - // REASON_PROGRAM 0 The EA has stopped working calling the ExpertRemove() function - // REASON_REMOVE 1 Program removed from a chart - // REASON_RECOMPILE 2 Program recompiled - // REASON_CHARTCHANGE 3 A symbol or a chart period is changed - // REASON_CHARTCLOSE 4 Chart closed - // REASON_PARAMETERS 5 Inputs changed by a user - // REASON_ACCOUNT 6 Another account has been activated or reconnection to the trade server has occurred due to changes in the account settings - // REASON_TEMPLATE 7 Another chart template applied - // REASON_INITFAILED 8 The OnInit() handler returned a non-zero value - // REASON_CLOSE 9 Terminal closed - - // - // Here we can handle De Initialization Reasons ... - IndicatorRelease(maHandler); -} - -// -// Calculations ... -// -// Calculating what we want ... -int OnCalculate( - // - // total Candles on chart ... - const int rates_total, - // - // total calculated Candles on charts ... - const int prev_calculated, - // - // history of Candles Open Time ... - const datetime &time[], - // - // history of Candles Open Price ... - const double &open[], - // - // history of Candles High Price ... - const double &high[], - // - // history of Candles Low Price ... - const double &low[], - // - // history of Candles Close Price ... - const double &close[], - // - // history of Tick Volumes on Candle ... - const long &tick_volume[], - // - // history of Trade Volumes ... - const long &volume[], - // - // history of Candles Spread Price ... - const int &spread[]) -{ - // - // Prepare Buffers ... - ArraySetAsSeries(time, true); - ArraySetAsSeries(open, true); - ArraySetAsSeries(high, true); - ArraySetAsSeries(low, true); - ArraySetAsSeries(close, true); - ArraySetAsSeries(tick_volume, true); - ArraySetAsSeries(volume, true); - ArraySetAsSeries(spread, true); - - // - // this counts Available Bars ... - int limit; - - // - // because in some cases we may have more than one input for - // calculation and we must prevent any calculation - // untill we pass the biggest input length, here we get max Input length - // and then wait until pass it ... - int maxLength = MathMax(fastEMA, slowEMA); - maxLength = MathMax(maxLength, length); - - // - // Check Calculated Bars ... - int maCalculatedBars = BarsCalculated(maHandler); - if (maCalculatedBars < maxLength) - { - return prev_calculated; - } - - // - limit = (prev_calculated > rates_total || prev_calculated <= 0) ? rates_total : (rates_total - prev_calculated) + 1; - - // - // Buffers Copy ... - int copiedMas = CopyBuffer(maHandler, 0, 0, limit, maBuffer); - if (copiedMas <= 0) - { - return prev_calculated; - } - - // - // Main Loop ... - for (int i = limit - 1; i >= 0 && !IsStopped(); i--) - { - // - // Do Buffers Calculation ... - CalculateBuffers(i); - } - - // - return rates_total; -} -// -// END Event Handlers ... -// - -// -// START Functions ... -// -// -// Validate Input Args for Initialization ... -bool ValidateInputs() -{ - // - bool result = false; - - // - // Validate Args ... - if (length >= 2) - { - result = true; - } - - // - return result; -} - -// -// Define Indexes and Styles ... -void DefineBuffers() -{ - // - string maBufferLabel = "XAMA " + "(" + (string)length + ")"; - - // - // Ma Buffer ... - ArraySetAsSeries(maBuffer, true); - SetIndexBuffer(maBufferIndex, maBuffer, INDICATOR_DATA); - PlotIndexSetString(maBufferIndex, PLOT_LABEL, maBufferLabel); - - // - // Ma Color Buffer ... - ArraySetAsSeries(maColorBuffer, true); - SetIndexBuffer(maColorBufferIndex, maColorBuffer, INDICATOR_COLOR_INDEX); - - // - // State Buffer ... - ArraySetAsSeries(stateBuffer, true); - SetIndexBuffer(stateBufferIndex, stateBuffer, INDICATOR_CALCULATIONS); -} - -// -// Set Indicator Short Name and also we can define Buffers Labels ... -void SetIndicatorName() -{ - // - string indicatorShortName = ""; - StringConcatenate(indicatorShortName, ShortName, " ", "(", length, ")"); - - // - IndicatorSetString(INDICATOR_SHORTNAME, indicatorShortName); -} - -// -// Calculate Buffers ... -void CalculateBuffers(int bar_index) -{ - // - // Requirements ... - XOHCL candle; - candle.Init( - _Symbol, - _Period, - bar_index); - - // - double maValue = maBuffer[bar_index]; - - // - double lineColorIndex = - maValue < candle.low ? 0 : maValue > candle.high ? 2 - : 1; - - // - // Define State Value ... - // lineColorIndex == 0 => Bullish => 1; - // lineColorIndex == 1 => Neutural => 0; - // lineColorIndex == 2 => Bearish => -1; - double stateValue = - lineColorIndex == 0 ? X_XAMA_BULLISH : lineColorIndex == 2 ? X_XAMA_BEARISH - : X_XAMA_NEUTURAL; - - // - // Set Ma Buffer Color Index ... - maColorBuffer[bar_index] = showLine ? lineColorIndex : 3; - - // - // Set State Buffer Value ... - stateBuffer[bar_index] = stateValue; -} - -// -// END Functions ... -// diff --git a/Documents/Pack/V1.0/Source/Indicators/x-saherelm.xasct.mq5 b/Documents/Pack/V1.0/Source/Indicators/x-saherelm.xasct.mq5 deleted file mode 100644 index 9e8e1f3c..00000000 --- a/Documents/Pack/V1.0/Source/Indicators/x-saherelm.xasct.mq5 +++ /dev/null @@ -1,442 +0,0 @@ -/////////////////////////////////////////////////////// -// SaherElm IT Center MQL5 Indicator -// ------------------------------------------- -// Name: XASCT -// Description: XASCTrend Detector ... -// -// 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 XASCT Indicator" -#property strict - -// -#define ShortName "XASCT" - -// -// Inputs ... - -// -input group "Market"; -input int risk = 4; // Risk - -// -input group "Presentation"; -input bool showLongs = true; // Show Long Arrows -input bool showShorts = true; // Show Short Arrows -input uchar longArrowCode = 233; // Long Arrow -input uchar shortArrowCode = 234; // Short Arrow - -// -// Buffers ... - -// -#property indicator_chart_window - -// -#property indicator_buffers 2 -#property indicator_plots 2 - -// -#define longBufferIndex 0 -double longBuffer[]; - -// -#property indicator_label1 "XASCT Long" -#property indicator_type1 DRAW_ARROW -#property indicator_color1 clrAqua -#property indicator_width1 3 - -// -#define shortBufferIndex 1 -double shortBuffer[]; - -// -#property indicator_label2 "XASCT Short" -#property indicator_type2 DRAW_ARROW -#property indicator_color2 clrMagenta -#property indicator_width2 3 - -// -// Variables ... -int maxLength = 0; -int wPRHandlers[3]; -int x1, x2 = 0; -int value10, value11 = 0; - -// -// EVENT Handlers ... - -// -// Initialization ... -int OnInit() -{ - // - // Validate Inputs ... - if (!ValidateInputs()) - { - return INIT_PARAMETERS_INCORRECT; - } - - // - maxLength = ExtractMaxLengthOfInputs(); - - // - x1 = 67 + risk; - x2 = 33 - risk; - value10 = 2; - value11 = value10; - - // - wPRHandlers[0] = iWPR(_Symbol, _Period, 3); - if (wPRHandlers[0] == INVALID_HANDLE) - { - return INIT_FAILED; - } - - // - wPRHandlers[1] = iWPR(_Symbol, _Period, 4); - if (wPRHandlers[1] == INVALID_HANDLE) - { - return INIT_FAILED; - } - - // - wPRHandlers[2] = iWPR(_Symbol, _Period, 3 + risk * 2); - if (wPRHandlers[2] == INVALID_HANDLE) - { - return INIT_FAILED; - } - - // - // Define Index Buffers ... - DefineBuffers(); - - // - // Set Indicator ShortName ... - SetIndicatorName(); - - // - // Init Succeed ... - return INIT_SUCCEEDED; -} - -// -// DeInitialization ... -void OnDeinit(const int reason) -{ - // - // REASON_PROGRAM 0 The EA has stopped working calling the ExpertRemove() function - // REASON_REMOVE 1 Program removed from a chart - // REASON_RECOMPILE 2 Program recompiled - // REASON_CHARTCHANGE 3 A symbol or a chart period is changed - // REASON_CHARTCLOSE 4 Chart closed - // REASON_PARAMETERS 5 Inputs changed by a user - // REASON_ACCOUNT 6 Another account has been activated or reconnection to the trade server has occurred due to changes in the account settings - // REASON_TEMPLATE 7 Another chart template applied - // REASON_INITFAILED 8 The OnInit() handler returned a non-zero value - // REASON_CLOSE 9 Terminal closed -} - -// -// Calculating what we want ... -int OnCalculate( - const int rates_total, // Total Bars on Chart ... - const int prev_calculated, // Total Calculated Bars on Charts ... - const datetime &time[], // History of Open Time ... - const double &open[], // History of Open Price ... - const double &high[], // History of High Price ... - const double &low[], // History of Low Price ... - const double &close[], // History of Close Price ... - const long &tick_volume[], // History of Tick Volumes on Bar ... - const long &volume[], // History of Trade Volumes ... - const int &spread[] // History of Spread Price ... -) -{ - // - // Validate Calculated Bars ... - bool isPassedRequiredCalculatedBars = - // - BarsCalculated(wPRHandlers[0]) == rates_total && - BarsCalculated(wPRHandlers[1]) == rates_total && - BarsCalculated(wPRHandlers[2]) == rates_total - // - ; - if (!isPassedRequiredCalculatedBars) - { - return 0; - } - - // - // Declare Some Local Variables for Use ... - int limit, bar, count, iii; - double value2, value3, vel = 0, wprs[]; - double trueCount, range, avgRange, mrO1, mrO2; - - // - // checking for the first start of the indicator calculation ... - if (prev_calculated > rates_total || prev_calculated <= 0) - { - limit = rates_total - maxLength; - } - // - // starting index for calculation of all bars - else - { - limit = rates_total - prev_calculated; - } - - // - ArraySetAsSeries(wprs, true); - ArraySetAsSeries(open, true); - ArraySetAsSeries(high, true); - ArraySetAsSeries(low, true); - ArraySetAsSeries(close, true); - - // - // Main Loop ... - for (bar = limit; bar >= 0 && !IsStopped(); bar--) - { - // - range = 0.0; - avgRange = 0.0; - for (count = bar; count <= bar + 9; count++) - { - avgRange = avgRange + MathAbs(high[count] - low[count]); - } - - // - count = bar; - trueCount = 0; - range = avgRange / 10; - - // - while (count < bar + 9 && trueCount < 1) - { - // - if (MathAbs(open[count] - close[count + 1]) >= range * 2.0) - { - trueCount++; - } - - // - count++; - } - - // - if (trueCount >= 1) - { - mrO1 = count; - } - else - { - mrO1 = -1; - } - - // - count = bar; - trueCount = 0; - - // - while (count < bar + 6 && trueCount < 1) - { - // - if (MathAbs(close[count + 3] - close[count]) >= range * 4.6) - { - trueCount++; - } - - // - count++; - } - - // - if (trueCount >= 1) - { - mrO2 = count; - } - else - { - mrO2 = -1; - } - - // - if (mrO1 > -1) - { - value11 = 0; - } - else - { - value11 = value10; - } - if (mrO2 > -1) - { - value11 = 1; - } - else - { - value11 = value10; - } - - // - if (CopyBuffer(wPRHandlers[value11], 0, bar, 1, wprs) <= 0) - { - return 0; - } - - // - value2 = 100 - MathAbs(wprs[0]); - - // - longBuffer[bar] = 0; - shortBuffer[bar] = 0; - - // - value3 = 0; - - // - if (value2 < x2) - { - // - iii = 1; - while (bar + iii < rates_total) - { - // - if (CopyBuffer(wPRHandlers[value11], 0, bar + iii, 1, wprs) <= 0) - { - return 0; - } - - // - vel = 100 - MathAbs(wprs[0]); - if (vel >= x2 && vel <= x1) - { - iii++; - } - else - { - break; - } - } - - // - if (vel > x1) - { - value3 = high[bar] + range * 0.5; - shortBuffer[bar] = value3; - } - } - - // - if (value2 > x1) - { - // - iii = 1; - while (bar + iii < rates_total) - { - // - if (CopyBuffer(wPRHandlers[value11], 0, bar + iii, 1, wprs) <= 0) - { - return 0; - } - - // - vel = 100 - MathAbs(wprs[0]); - if (vel >= x2 && vel <= x1) - { - iii++; - } - else - { - break; - } - } - - // - if (vel < x2) - { - value3 = low[bar] - range * 0.5; - longBuffer[bar] = value3; - } - } - } - - // - return rates_total; -} - -// -// CUSTOM Functions ... - -// -// Validate Input Args for Initialization ... -bool ValidateInputs() -{ - // - bool result = true; - - // - result = - risk >= 1; - - // - return result; -} - -// -// Retrieve all Exists Input Max Length ... -// use for Start Of Drawing ... -int ExtractMaxLengthOfInputs() -{ - // - int result = 0; - - // - result = int(MathMax(3 + risk * 2, 4) + 1); - - // - return result; -} - -// -// Set Indicator Short Name and also we can define Buffers Labels ... -void SetIndicatorName() -{ - // - IndicatorSetInteger(INDICATOR_DIGITS, _Digits); - IndicatorSetString(INDICATOR_SHORTNAME, ShortName); -} - -// -// Define Indexes and Styles ... -void DefineBuffers() -{ - // - // Longs Buffer ... - ENUM_DRAW_TYPE longsDrawType = showLongs ? DRAW_ARROW : DRAW_NONE; - ArraySetAsSeries(longBuffer, true); - SetIndexBuffer(longBufferIndex, longBuffer, INDICATOR_DATA); - PlotIndexSetDouble(longBufferIndex, PLOT_EMPTY_VALUE, 0); - PlotIndexSetInteger(longBufferIndex, PLOT_DRAW_BEGIN, maxLength); - PlotIndexSetInteger(longBufferIndex, PLOT_SHOW_DATA, showLongs); - PlotIndexSetInteger(longBufferIndex, PLOT_DRAW_TYPE, longsDrawType); - PlotIndexSetInteger(longBufferIndex, PLOT_ARROW, longArrowCode); - - // - // Short Buffer ... - ENUM_DRAW_TYPE shortsDrawType = showShorts ? DRAW_ARROW : DRAW_NONE; - ArraySetAsSeries(shortBuffer, true); - SetIndexBuffer(shortBufferIndex, shortBuffer, INDICATOR_DATA); - PlotIndexSetDouble(shortBufferIndex, PLOT_EMPTY_VALUE, 0); - PlotIndexSetInteger(shortBufferIndex, PLOT_DRAW_BEGIN, maxLength); - PlotIndexSetInteger(shortBufferIndex, PLOT_SHOW_DATA, showShorts); - PlotIndexSetInteger(shortBufferIndex, PLOT_DRAW_TYPE, shortsDrawType); - PlotIndexSetInteger(shortBufferIndex, PLOT_ARROW, shortArrowCode); -} \ No newline at end of file diff --git a/Documents/Pack/V1.0/Source/Indicators/x-saherelm.xatsl.mq5 b/Documents/Pack/V1.0/Source/Indicators/x-saherelm.xatsl.mq5 deleted file mode 100644 index 7e30a974..00000000 --- a/Documents/Pack/V1.0/Source/Indicators/x-saherelm.xatsl.mq5 +++ /dev/null @@ -1,333 +0,0 @@ -/////////////////////////////////////////////////////// -// SaherElm IT Center MQL5 Indicator -// ------------------------------------------- -// Name: XATSL -// Description: ATR SL ... -// -// 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 XATSL Indicator" -#property strict - -// -#define ShortName "XATSL" - -// -// Imports ... -#include "../Libraries/x-saherelm.common.lib.mq5" - -// -// Inputs ... - -// -input group "Market"; -input int length = 14; // Length -input double coeff = 2.0; // Coefficient - -// -input group "Presentation"; -input bool show = true; // Show - -// -// Buffers ... - -// -#property indicator_chart_window - -// -#property indicator_buffers 7 -#property indicator_plots 2 - -// -#define mainBufferIndex 0 -double mainBuffer[]; - -// -#define mainBufferColorIndex 1 -double mainBufferColor[]; - -// -#define hideColorIDX 0 -#define bullColorIDX 1 -#define bearColorIDX 2 - -// -#property indicator_label1 "XATSL" -#property indicator_type1 DRAW_COLOR_LINE -#property indicator_color1 CLR_NONE, clrGreen, clrDarkRed -#property indicator_style1 STYLE_DOT -#property indicator_width1 1 - -// -#define hlBufferIndex 2 -double hlBuffer[]; - -// -#define wmaBufferIndex 3 -double wmaBuffer[]; - -// -#define tmpBufferIndex 4 -double tmpBuffer[]; - -// -#define diffBufferIndex 5 -double diffBuffer[]; - -// -// Variables ... -int maPeriod; -double k; - -// -// Event Handlers ... - -// -// Initialization ... -int OnInit() -{ - // - // Validate Inputs ... - if (!ValidateInputs()) - { - return INIT_PARAMETERS_INCORRECT; - } - - // - maPeriod = int(length < 1 ? 1 : length); - double n1 = 2.0 * double(maPeriod - 1); - k = 2.0 / (n1 + 1); - - // - // Define Index Buffers ... - DefineBuffers(); - - // - // Set Indicator ShortName ... - SetIndicatorName(); - - // - // Init Succeed ... - return INIT_SUCCEEDED; -} - -// -// DeInitialization ... -void OnDeinit(const int reason) -{ - // - // REASON_PROGRAM 0 The EA has stopped working calling the ExpertRemove() function - // REASON_REMOVE 1 Program removed from a chart - // REASON_RECOMPILE 2 Program recompiled - // REASON_CHARTCHANGE 3 A symbol or a chart period is changed - // REASON_CHARTCLOSE 4 Chart closed - // REASON_PARAMETERS 5 Inputs changed by a user - // REASON_ACCOUNT 6 Another account has been activated or reconnection to the trade server has occurred due to changes in the account settings - // REASON_TEMPLATE 7 Another chart template applied - // REASON_INITFAILED 8 The OnInit() handler returned a non-zero value - // REASON_CLOSE 9 Terminal closed -} - -// -// Calculating what we want ... -int OnCalculate( - const int rates_total, // Total Bars on Chart ... - const int prev_calculated, // Total Calculated Bars on Charts ... - const datetime &time[], // History of Open Time ... - const double &open[], // History of Open Price ... - const double &high[], // History of High Price ... - const double &low[], // History of Low Price ... - const double &close[], // History of Close Price ... - const long &tick_volume[], // History of Tick Volumes on Bar ... - const long &volume[], // History of Trade Volumes ... - const int &spread[] // History of Spread Price ... -) -{ - // - ArraySetAsSeries(high, true); - ArraySetAsSeries(low, true); - ArraySetAsSeries(close, true); - - // - if (rates_total < maPeriod) - { - return 0; - } - - // - int limit = rates_total - prev_calculated; - if (limit > 1) - { - // - limit = rates_total - 2; - - // - ArrayInitialize(mainBuffer, EMPTY_VALUE); - ArrayInitialize(hlBuffer, 0); - ArrayInitialize(diffBuffer, 0); - ArrayInitialize(wmaBuffer, 0); - ArrayInitialize(tmpBuffer, 0); - } - - // - for (int i = limit; i >= 0 && !IsStopped(); i--) - { - // - hlBuffer[i] = high[i] - low[i]; - - // - double href = 0; - double lref = 0; - - // - double sma = MAOnArray(hlBuffer, 0, maPeriod, 0, MODE_SMA, i); - double hiLo = fmin(hlBuffer[i], sma); - - // - href = (low[i] <= high[i + 1] ? high[i] - close[i + 1] : (hlBuffer[i] - close[i + 1] + high[i + 1]) / 2); - lref = (high[i] >= low[i + 1] ? close[i + 1] - low[i] : (close[i + 1] - low[i + 1] + hlBuffer[i]) / 2); - - // - diffBuffer[i] = fmax(hiLo, fmax(href, lref)); - } - - // - for (int i = limit; i >= 0 && !IsStopped(); i--) - { - // - if (i == rates_total - 2) - { - wmaBuffer[i] = MAOnArray(diffBuffer, 0, maPeriod, 0, MODE_EMA, i); - } - else - { - wmaBuffer[i] = (diffBuffer[i] - wmaBuffer[i + 1]) * k + wmaBuffer[i + 1]; - } - } - - // - for (int i = limit; i >= 0 && !IsStopped(); i--) - { - // - double loss = wmaBuffer[i] * coeff; - if (close[i] > tmpBuffer[i + 1] && close[i + 1] > tmpBuffer[i + 1]) - { - // - tmpBuffer[i] = fmax(tmpBuffer[i + 1], close[i] - loss); - - // - mainBuffer[i] = tmpBuffer[i]; - } - else - { - // - if (close[i] < tmpBuffer[i + 1] && close[i + 1] < tmpBuffer[i + 1]) - { - // - tmpBuffer[i] = fmin(tmpBuffer[i + 1], close[i] + loss); - - // - mainBuffer[i] = tmpBuffer[i]; - } - else - { - // - if (close[i] > tmpBuffer[i + 1]) - { - // - tmpBuffer[i] = close[i] - loss; - - // - mainBuffer[i] = tmpBuffer[i]; - } - else - { - // - tmpBuffer[i] = close[i] + loss; - - // - mainBuffer[i] = tmpBuffer[i]; - } - } - } - - // - // Define Color Buffer ... - double clrValue = !show - ? hideColorIDX - : mainBuffer[i] > close[i] - ? bearColorIDX - : bullColorIDX; - mainBufferColor[i] = clrValue; - } - - // - return rates_total; -} - -// -// Custom Functions ... - -// -// Validate Input Args for Initialization ... -bool ValidateInputs() -{ - // - bool result = false; - - // - result = length >= 2 && - coeff > 0; - - // - return result; -} - -// -// Set Indicator Short Name and also we can define Buffers Labels ... -void SetIndicatorName() -{ - IndicatorSetString(INDICATOR_SHORTNAME, ShortName); -} - -// -// Define Indexes and Styles ... -void DefineBuffers() -{ - // - // Main ... - ENUM_DRAW_TYPE mainDrawType = show ? DRAW_COLOR_LINE : DRAW_NONE; - - ArraySetAsSeries(mainBuffer, true); - ArraySetAsSeries(mainBufferColor, true); - PlotIndexSetInteger(mainBufferIndex, PLOT_SHOW_DATA, true); - SetIndexBuffer(mainBufferIndex, mainBuffer, INDICATOR_DATA); - PlotIndexSetInteger(mainBufferIndex, PLOT_DRAW_TYPE, mainDrawType); - SetIndexBuffer(mainBufferColorIndex, mainBufferColor, INDICATOR_COLOR_INDEX); - - // - ArraySetAsSeries(hlBuffer, true); - SetIndexBuffer(hlBufferIndex, hlBuffer, INDICATOR_CALCULATIONS); - - // - ArraySetAsSeries(wmaBuffer, true); - SetIndexBuffer(wmaBufferIndex, wmaBuffer, INDICATOR_CALCULATIONS); - - // - ArraySetAsSeries(tmpBuffer, true); - SetIndexBuffer(tmpBufferIndex, tmpBuffer, INDICATOR_CALCULATIONS); - - // - ArraySetAsSeries(diffBuffer, true); - SetIndexBuffer(diffBufferIndex, diffBuffer, INDICATOR_CALCULATIONS); -} - -// \ No newline at end of file diff --git a/Documents/Pack/V1.0/Source/Indicators/x-saherelm.xcc.mq5 b/Documents/Pack/V1.0/Source/Indicators/x-saherelm.xcc.mq5 deleted file mode 100644 index 2e11f1c3..00000000 --- a/Documents/Pack/V1.0/Source/Indicators/x-saherelm.xcc.mq5 +++ /dev/null @@ -1,458 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Candle Styles -// --------------------------------------------------- -// Name: XCC -// Description: Candle Styles ... -// -// -// 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 XCC Indicator" -#property strict - -// -// START Constants ... -// - -// -// Indicator Short Name ... -#define ShortName "XCC" - -// -// Holds an SnapShot of Charts Configuration ... -struct XChartStyle -{ - // - // chart's ID ... - long chartId; - // - // chart's mode ... - ENUM_CHART_MODE mode; - // - // show bid line ... - bool showBidLine; - // - // show ask line ... - bool showAskLine; - // - // show grids on chart ... - bool showGrid; - // - // show volumes ... - bool showVolumes; - // - // Displaying trade levels in the chart (levels of open positions, Stop Loss, Take Profit and pending orders) ... - bool showTradeLevels; - // - // chart autoscroll ... - bool autoScroll; - // - // chart quick navigation state ... - bool quickNavigation; - // - // chart's foreground color ... - color foreGroundColor; - // - // chart's background color ... - color backGroundColor; - // - // Up Color ... - color upColor; - // - // Down Color ... - color downColor; - // - // Bullish color ... - color bullishColor; - // - // Bearish color ... - color bearishColor; - // - // grid color ... - color gridColor; - // - // bid line color ... - color bidLineColor; - // - // ask line color ... - color askLineColor; - // - // line mode and doji candlestick color ... - color lineColor; - // - // Color of stop order levels (Stop Loss and Take Profit) ... - color stopColor; - // - // volumes color ... - color volumesColor; -}; - -// -// END Constants ... -// - -// -// START Inputs ... -// - -// -input group "Chart Style"; -input ENUM_CHART_MODE mode = CHART_CANDLES; // Mode -input color upColor = clrLime; // Up Color -input color downColor = clrRed; // Down Color -input color lineColor = clrLime; // Line mode and Doji candlestick Color -input color bearishColor = clrRed; // Bullish Color -input color bullishColor = clrLime; // Bearish Color -input color volumesColor = clrGreen; // Volumes Color - -// -input group "Presentation"; -input bool showCandles = true; // Show Candles - -// -// END Inputs ... -// - -// -// START Includes and Imports ... -// - -// -// Includes Draw Library ... -#include "../Libraries/x-saherelm.draw.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 0 -#property indicator_plots 0 - -// -// END Buffers ... -// - -// -// START Global Definitions: Variables, Properties and etc ... -// - -// -int maxLength; - -// -XChartStyle chartStyle; -XChartStyle clearStyle; - -// -// END Global Definitions: Variables, Properties and etc ... -// - -// -// START Event Handlers ... -// - -// -// Initialization ... -int OnInit() -{ - // - // Validate Inputs ... - if (!ValidateInputs()) - { - return INIT_PARAMETERS_INCORRECT; - } - - // - drawPrefix = 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(); - - // - // Define Index Buffers ... - DefineBuffers(); - - // - // Set Indicator ShortName ... - SetIndicatorName(); - - // - // Apply Chart Style ... - ApplyCustomChartStyle(); - - // - // 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 -} - -// -// 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; - - // - limit = (prev_calculated > rates_total || prev_calculated <= 0) ? rates_total : (rates_total - prev_calculated) + 1; - - // - // Main Loop ... - for (int i = limit - 1; i >= 0 && !IsStopped(); i--) - { - CalculateBuffers(i); - } - - // - return rates_total; -} - -// -// END Event Handlers ... -// - -// -// START Functions ... -// - -// -// Validate Input Args for Initialization ... -bool ValidateInputs() -{ - // - bool result = true; - - // - return result; -} - -// -// Retrieve all Exists Input Max Length ... -// use for Start Of Drawing ... -int ExtractMaxLengthOfInputs() -{ - // - int result = 0; - - // - return result; -} - -// -// Define Indexes and Styles ... -void DefineBuffers() -{ -} - -// -// Set Indicator Short Name and also we can define Buffers Labels ... -void SetIndicatorName() -{ - IndicatorSetString(INDICATOR_SHORTNAME, ShortName); -} - -// -// Calculate Buffers ... -void CalculateBuffers( - int bar_index // Selected Bar Index -) -{ -} - -// -// Apply Custom Chart Style ... -void ApplyCustomChartStyle() -{ - // - // Read Current Chart Config and Store it ... - ReadChartStyle(); - - // - // After Reading Current Chart Style ... - // we have to Save Configs and Change Styles ... - clearStyle = chartStyle; - - // - clearStyle.upColor = CLR_NONE; - clearStyle.downColor = CLR_NONE; - clearStyle.lineColor = CLR_NONE; - clearStyle.bullishColor = CLR_NONE; - clearStyle.bearishColor = CLR_NONE; - - // - // Decide to Show or not Candles based on User Input ... - if (showCandles) - { - SetChartStyle(chartStyle); - } - else - { - SetChartStyle(clearStyle); - } -} - -// -// Read Previous Chart Style ... -void ReadChartStyle() -{ - // - // Retrieve Current Chart ID ... - long chartId = ChartID(); - chartStyle.chartId = chartId; - - // - // Retrieve Chart Mode ... - chartStyle.mode = (ENUM_CHART_MODE)ChartGetInteger(chartId, CHART_MODE); - - // - chartStyle.showBidLine = (bool)ChartGetInteger(chartId, CHART_SHOW_BID_LINE); - chartStyle.showAskLine = (bool)ChartGetInteger(chartId, CHART_SHOW_ASK_LINE); - chartStyle.showGrid = (bool)ChartGetInteger(chartId, CHART_SHOW_GRID); - chartStyle.showVolumes = (bool)ChartGetInteger(chartId, CHART_SHOW_VOLUMES); - chartStyle.showTradeLevels = (bool)ChartGetInteger(chartId, CHART_SHOW_TRADE_LEVELS); - chartStyle.autoScroll = (bool)ChartGetInteger(chartId, CHART_AUTOSCROLL); - chartStyle.quickNavigation = (bool)ChartGetInteger(chartId, CHART_QUICK_NAVIGATION); - - // - chartStyle.foreGroundColor = (color)ChartGetInteger(chartId, CHART_COLOR_FOREGROUND); - chartStyle.backGroundColor = (color)ChartGetInteger(chartId, CHART_COLOR_BACKGROUND); - chartStyle.upColor = (color)ChartGetInteger(chartId, CHART_COLOR_CHART_UP); - chartStyle.downColor = (color)ChartGetInteger(chartId, CHART_COLOR_CHART_DOWN); - chartStyle.bullishColor = (color)ChartGetInteger(chartId, CHART_COLOR_CANDLE_BULL); - chartStyle.bearishColor = (color)ChartGetInteger(chartId, CHART_COLOR_CANDLE_BEAR); - chartStyle.gridColor = (color)ChartGetInteger(chartId, CHART_COLOR_GRID); - chartStyle.bidLineColor = (color)ChartGetInteger(chartId, CHART_COLOR_BID); - chartStyle.askLineColor = (color)ChartGetInteger(chartId, CHART_COLOR_ASK); - chartStyle.stopColor = (color)ChartGetInteger(chartId, CHART_COLOR_STOP_LEVEL); - chartStyle.lineColor = (color)ChartGetInteger(chartId, CHART_COLOR_CHART_LINE); - chartStyle.volumesColor = (color)ChartGetInteger(chartId, CHART_COLOR_VOLUME); - - // - chartStyle.mode = mode; - chartStyle.upColor = upColor; - chartStyle.downColor = downColor; - chartStyle.lineColor = lineColor; - chartStyle.bearishColor = bearishColor; - chartStyle.bullishColor = bullishColor; - chartStyle.volumesColor = volumesColor; -} - -// -// Set Chart Style ... -void SetChartStyle( - XChartStyle &mChartStyle // Chart Style to Apply -) -{ - // - ApplyChartStyle( - mChartStyle.chartId, - mChartStyle.mode, - mChartStyle.showBidLine, - mChartStyle.showAskLine, - mChartStyle.showGrid, - mChartStyle.showVolumes, - mChartStyle.showTradeLevels, - mChartStyle.autoScroll, - mChartStyle.quickNavigation, - mChartStyle.foreGroundColor, - mChartStyle.backGroundColor, - mChartStyle.upColor, - mChartStyle.downColor, - mChartStyle.bullishColor, - mChartStyle.bearishColor, - mChartStyle.gridColor, - mChartStyle.bidLineColor, - mChartStyle.askLineColor, - mChartStyle.lineColor, - mChartStyle.stopColor, - mChartStyle.volumesColor); -} - -// -// END Functions ... -// diff --git a/Documents/Pack/V1.0/Source/Indicators/x-saherelm.xche.mq5 b/Documents/Pack/V1.0/Source/Indicators/x-saherelm.xche.mq5 deleted file mode 100644 index f47d3639..00000000 --- a/Documents/Pack/V1.0/Source/Indicators/x-saherelm.xche.mq5 +++ /dev/null @@ -1,631 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Indicator -// --------------------------------------------- -// Name: XCHE -// Description: Chandelier Exit Indicator ... -// -// -// Maintainer: -// ------------ -// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) -// -////////////////////////////////////////////////////// -// -// Global Properties ... -#property copyright "Copyright 2023, SaherElm IT Center" -#property link "https://saherelm.ir" -#property version "1.00" -#property description "SaherElm XCHE Indicator" -#property strict - -// -// START Constants ... -// - -// -#define ShortName "XCHE" - -// -// END Constants ... -// - -// -// START Inputs ... -// - -// -input group "Market"; -input int length = 35; // Length -input int loopback = 26; // Loopback -input double multiplier1 = 3.0; // 1st Multiplier -input double multiplier2 = 3.5; // 2nd Multiplier - -// -input group "Calculation"; -input ENUM_APPLIED_PRICE upAppliedTo = PRICE_HIGH; // Up Zone Applied to -input ENUM_APPLIED_PRICE downAppliedTo = PRICE_LOW; // Down Zone Applied to - -// -input group "Presentation"; -input bool showLongExit1Line = true; // Show 1st Long Exit -input bool showShortExit1Line = true; // Show 1st Short Exit -input bool showLongExit2Line = true; // Show 2st Long Exit -input bool showShortExit2Line = true; // Show 2st Short Exit - -// -// END Inputs ... -// - -// -// START Includes and Imports ... -// - -// -// Includes Common Library ... -#include "../Libraries/x-saherelm.common.lib.mq5" - -// -// END Includes and Imports ... -// - -// -// START Buffers ... -// - -// -#property indicator_chart_window - -// -#property indicator_buffers 8 -#property indicator_plots 8 - -// -// Long Exit 1 ... -#define longExit1BufferIndex 0 -double longExit1Buffer[]; - -// -#property indicator_label1 "XCHE LE 1" -#property indicator_type1 DRAW_LINE -#property indicator_color1 clrLime -#property indicator_style1 STYLE_DOT - -// -// Short Exit 1 ... -#define shortExit1BufferIndex 1 -double shortExit1Buffer[]; - -// -#property indicator_label2 "XCHE SE 1" -#property indicator_type2 DRAW_LINE -#property indicator_style2 STYLE_DOT -#property indicator_color2 clrRed - -// -// Long Exit 2 ... -#define longExit2BufferIndex 2 -double longExit2Buffer[]; - -// -#property indicator_label3 "XCHE LE 2" -#property indicator_type3 DRAW_LINE -#property indicator_style2 STYLE_DOT -#property indicator_color3 clrAqua - -// -// Short Exit 2 ... -#define shortExit2BufferIndex 3 -double shortExit2Buffer[]; - -// -#property indicator_label4 "XCHE SE 2" -#property indicator_type4 DRAW_LINE -#property indicator_style2 STYLE_DOT -#property indicator_color4 clrMagenta - -// -// START Arrows ... - -// -// Long Exit 1 Start ... -#define longExit1StartBufferIndex 4 -double longExit1StartBuffer[]; - -// -#property indicator_label5 "XCHE LES 1" -#property indicator_type5 DRAW_ARROW -#property indicator_color5 clrLime - -// -// Short Exit 1 Start ... -#define shortExit1StartBufferIndex 5 -double shortExit1StartBuffer[]; - -// -#property indicator_label6 "XCHE SES 1" -#property indicator_type6 DRAW_ARROW -#property indicator_color6 clrRed - -// -// Long Exit 2 Start ... -#define longExit2StartBufferIndex 6 -double longExit2StartBuffer[]; - -// -#property indicator_label7 "XCHE LES 2" -#property indicator_type7 DRAW_ARROW -#property indicator_color7 clrAqua - -// -// Short Exit 2 Start ... -#define shortExit2StartBufferIndex 7 -double shortExit2StartBuffer[]; - -// -#property indicator_label8 "XCHE SES 2" -#property indicator_type8 DRAW_ARROW -#property indicator_color8 clrMagenta - -// -// END Buffers ... -// - -// -// START Global Definitions: Variables, Properties and etc ... -// - -// -int maxLength; - -// -// Working Array ... -double work[][6]; -#define hi1Idx 0 -#define lo1Idx 1 -#define hi2Idx 2 -#define lo2Idx 3 -#define trend1Idx 4 -#define trend2Idx 5 - -// -// END Global Definitions: Variables, Properties and etc ... -// - -// -// START Event Handlers ... -// - -// -// Initialization ... -int OnInit() -{ - // - // Validate Inputs ... - if (!ValidateInputs()) - { - return INIT_PARAMETERS_INCORRECT; - } - - // - // because in some cases we may have more than one input for - // calculation and we must prevent any calculation - // untill we pass the biggest input length, here we get max Input length - // and then wait until pass it ... - maxLength = ExtractMaxLengthOfInputs(); - - // - // Define Index Buffers ... - DefineBuffers(); - - // - // Set Indicator ShortName ... - SetIndicatorName(); - - // - // Init Succeed ... - return INIT_SUCCEEDED; -} - -// -// DeInitialization ... -void OnDeinit(const int reason) -{ - // - // REASON_PROGRAM 0 The EA has stopped working calling the ExpertRemove() function - // REASON_REMOVE 1 Program removed from a chart - // REASON_RECOMPILE 2 Program recompiled - // REASON_CHARTCHANGE 3 A symbol or a chart mPeriod 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 -} - -// -// 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[]) -{ - // - if (Bars(_Symbol, _Period) < rates_total) - { - return (prev_calculated); - } - - // - if (ArrayRange(work, 0) != rates_total) - { - ArrayResize(work, rates_total); - } - - // - // this counts Available Bars ... - int limit; - - // - limit = prev_calculated - 1; - if (limit < 0) - { - limit = 0; - } - - // - // Main Loop ... - for (int i = limit; i < rates_total && !IsStopped(); i++) - { - CalculateBuffers( - i, - prev_calculated, - rates_total, - // - open, - high, - low, - close); - } - - // - return rates_total; -} -// -// END Event Handlers ... -// - -// -// START Functions ... -// - -// -// Validate Input Args for Initialization ... -bool ValidateInputs() -{ - // - bool result = true; - - // - result = - length >= 9 && - loopback >= 0; - - // - return result; -} - -// -// Retrieve all Exists Input Max Length ... -// use for Start Of Drawing ... -int ExtractMaxLengthOfInputs() -{ - // - int result = 0; - - // - result = MathMax(length, loopback); - - // - return result; -} - -// -// Set Indicator Short Name and also we can define Buffers Labels ... -void SetIndicatorName() -{ - IndicatorSetString(INDICATOR_SHORTNAME, ShortName); -} - -// -// Define Indexes and Styles ... -void DefineBuffers() -{ - // - uint arrowCode = 159; - - // - // LEVEL 1 ... - - // - // Long Exit 1 ... - - // - // Draw Type ... - ENUM_DRAW_TYPE longExit1DrawType = showLongExit1Line ? DRAW_LINE : DRAW_NONE; - ENUM_DRAW_TYPE longExit1StartDrawType = showLongExit1Line ? DRAW_ARROW : DRAW_NONE; - - // - // Buffer ... - SetIndexBuffer(longExit1BufferIndex, longExit1Buffer, INDICATOR_DATA); - PlotIndexSetInteger(longExit1BufferIndex, PLOT_SHOW_DATA, showLongExit1Line); - PlotIndexSetInteger(longExit1BufferIndex, PLOT_DRAW_TYPE, longExit1DrawType); - - // - // Start Buffer ... - SetIndexBuffer(longExit1StartBufferIndex, longExit1StartBuffer, INDICATOR_DATA); - PlotIndexSetInteger(longExit1StartBufferIndex, PLOT_ARROW, arrowCode); - PlotIndexSetInteger(longExit1StartBufferIndex, PLOT_SHOW_DATA, false); - PlotIndexSetInteger(longExit1StartBufferIndex, PLOT_DRAW_TYPE, longExit1StartDrawType); - - // - // Short Exit 1 ... - - // - // Draw Type ... - ENUM_DRAW_TYPE shortExit1DrawType = showShortExit1Line ? DRAW_LINE : DRAW_NONE; - ENUM_DRAW_TYPE shortExit1StartDrawType = showShortExit1Line ? DRAW_ARROW : DRAW_NONE; - - // - // Buffer ... - SetIndexBuffer(shortExit1BufferIndex, shortExit1Buffer, INDICATOR_DATA); - PlotIndexSetInteger(shortExit1BufferIndex, PLOT_SHOW_DATA, showShortExit1Line); - PlotIndexSetInteger(shortExit1BufferIndex, PLOT_DRAW_TYPE, shortExit1DrawType); - - // - // Start Buffer ... - SetIndexBuffer(shortExit1StartBufferIndex, shortExit1StartBuffer, INDICATOR_DATA); - PlotIndexSetInteger(shortExit1StartBufferIndex, PLOT_ARROW, arrowCode); - PlotIndexSetInteger(shortExit1StartBufferIndex, PLOT_SHOW_DATA, false); - PlotIndexSetInteger(shortExit1StartBufferIndex, PLOT_DRAW_TYPE, shortExit1StartDrawType); - - // - // LEVEL 2 ... - - // - // Long Exit 2 ... - - // - // Draw Type ... - ENUM_DRAW_TYPE longExit2DrawType = showLongExit2Line ? DRAW_LINE : DRAW_NONE; - ENUM_DRAW_TYPE longExit2StartDrawType = showLongExit2Line ? DRAW_ARROW : DRAW_NONE; - - // - // Buffer ... - SetIndexBuffer(longExit2BufferIndex, longExit2Buffer, INDICATOR_DATA); - PlotIndexSetInteger(longExit2BufferIndex, PLOT_SHOW_DATA, showLongExit2Line); - PlotIndexSetInteger(longExit2BufferIndex, PLOT_DRAW_TYPE, longExit2DrawType); - - // - // Start Buffer ... - SetIndexBuffer(longExit2StartBufferIndex, longExit2StartBuffer, INDICATOR_DATA); - PlotIndexSetInteger(longExit2StartBufferIndex, PLOT_ARROW, arrowCode); - PlotIndexSetInteger(longExit2StartBufferIndex, PLOT_SHOW_DATA, false); - PlotIndexSetInteger(longExit2StartBufferIndex, PLOT_DRAW_TYPE, longExit2StartDrawType); - - // - // Short Exit 2 ... - - // - // Draw Type ... - ENUM_DRAW_TYPE shortExit2DrawType = showShortExit2Line ? DRAW_LINE : DRAW_NONE; - ENUM_DRAW_TYPE shortExit2StartDrawType = showShortExit2Line ? DRAW_ARROW : DRAW_NONE; - - // - // Buffer ... - SetIndexBuffer(shortExit2BufferIndex, shortExit2Buffer, INDICATOR_DATA); - PlotIndexSetInteger(shortExit2BufferIndex, PLOT_SHOW_DATA, showShortExit2Line); - PlotIndexSetInteger(shortExit2BufferIndex, PLOT_DRAW_TYPE, shortExit2DrawType); - - // - // Start Buffer ... - SetIndexBuffer(shortExit2StartBufferIndex, shortExit2StartBuffer, INDICATOR_DATA); - PlotIndexSetInteger(shortExit2StartBufferIndex, PLOT_ARROW, arrowCode); - PlotIndexSetInteger(shortExit2StartBufferIndex, PLOT_SHOW_DATA, false); - PlotIndexSetInteger(shortExit2StartBufferIndex, PLOT_DRAW_TYPE, shortExit2StartDrawType); -} - -// -// Calculate Buffers ... -void CalculateBuffers( - int bar_index, // Selected Bar Index - int prevCalculated, // Previous Calculated - int ratesTotal, // Total Rates - const double &open[], // Rates Open ... - const double &high[], // Rates High ... - const double &low[], // Rates Low ... - const double &close[] // Rates Close ... -) -{ - // - // Cleanup Buffers ... - longExit1Buffer[bar_index] = longExit1StartBuffer[bar_index] = shortExit1Buffer[bar_index] = shortExit1StartBuffer[bar_index] = EMPTY_VALUE; - longExit2Buffer[bar_index] = longExit2StartBuffer[bar_index] = shortExit2Buffer[bar_index] = shortExit2StartBuffer[bar_index] = EMPTY_VALUE; - - // - int start = MathMax(bar_index - loopback, 0); - - // - // Calculate ATR Value ... - double atrValue = 0; - for (int k = 1; k <= length && (bar_index - k - 1) >= 0; k++) - { - // - atrValue += MathMax(high[bar_index - k], close[MathMax(bar_index - k - 1, 0)]) - - MathMin(low[bar_index - k], close[MathMax(bar_index - k - 1, 0)]); - } - atrValue /= (double)length; - - // - // Retrieve Highest High and Lowest Lows ... - double loopbackMax = high[ArrayMaximum(high, start, loopback)]; - double loopbackMin = low[ArrayMinimum(low, start, loopback)]; - - // - // Fill Multi Dimesional Working Array ... - work[bar_index][hi1Idx] = loopbackMax - multiplier1 * atrValue; - work[bar_index][lo1Idx] = loopbackMin + multiplier1 * atrValue; - work[bar_index][hi2Idx] = loopbackMax - multiplier2 * atrValue; - work[bar_index][lo2Idx] = loopbackMin + multiplier2 * atrValue; - work[bar_index][trend1Idx] = (bar_index > 0) ? work[bar_index - 1][trend1Idx] : 0; - work[bar_index][trend2Idx] = (bar_index > 0) ? work[bar_index - 1][trend2Idx] : 0; - - // - if (bar_index > 0) - { - // - // Calculate Trends ... - if (close[bar_index] > work[bar_index - 1][lo1Idx]) - { - work[bar_index][trend1Idx] = 1; - } - - // - if (close[bar_index] < work[bar_index - 1][hi1Idx]) - { - work[bar_index][trend1Idx] = -1; - } - - // - if (close[bar_index] > work[bar_index - 1][lo2Idx]) - { - work[bar_index][trend2Idx] = 1; - } - - // - if (close[bar_index] < work[bar_index - 1][hi2Idx]) - { - work[bar_index][trend2Idx] = -1; - } - - // - // Calculate Exit Values ... - - // - // Exit 1 ... - - // - // Long ... - if (multiplier1 > 0 && work[bar_index][trend1Idx] == 1) - { - // - if (work[bar_index][hi1Idx] < work[bar_index - 1][hi1Idx]) - { - work[bar_index][hi1Idx] = work[bar_index - 1][hi1Idx]; - } - - // - longExit1Buffer[bar_index] = work[bar_index][hi1Idx]; - - // - if (longExit1Buffer[bar_index - 1] == EMPTY_VALUE) - { - longExit1StartBuffer[bar_index] = longExit1Buffer[bar_index]; - } - } - - // - // Short ... - if (multiplier1 > 0 && work[bar_index][trend1Idx] == -1) - { - // - if (work[bar_index][lo1Idx] > work[bar_index - 1][lo1Idx]) - { - work[bar_index][lo1Idx] = work[bar_index - 1][lo1Idx]; - } - - // - shortExit1Buffer[bar_index] = work[bar_index][lo1Idx]; - - // - if (shortExit1Buffer[bar_index - 1] == EMPTY_VALUE) - { - shortExit1StartBuffer[bar_index] = shortExit1Buffer[bar_index]; - } - } - - // - // Exit 2 ... - - // - // Long ... - if (multiplier2 > 0 && work[bar_index][trend2Idx] == 1) - { - if (work[bar_index][hi2Idx] < work[bar_index - 1][hi2Idx]) - { - work[bar_index][hi2Idx] = work[bar_index - 1][hi2Idx]; - } - - // - longExit2Buffer[bar_index] = work[bar_index][hi2Idx]; - - // - if (longExit2Buffer[bar_index - 1] == EMPTY_VALUE) - { - longExit2StartBuffer[bar_index] = longExit2Buffer[bar_index]; - } - } - - // - // Short ... - if (multiplier2 > 0 && work[bar_index][trend2Idx] == -1) - { - // - if (work[bar_index][lo2Idx] > work[bar_index - 1][lo2Idx]) - { - work[bar_index][lo2Idx] = work[bar_index - 1][lo2Idx]; - } - - // - shortExit2Buffer[bar_index] = work[bar_index][lo2Idx]; - - // - if (shortExit2Buffer[bar_index - 1] == EMPTY_VALUE) - { - shortExit2StartBuffer[bar_index] = shortExit2Buffer[bar_index]; - } - } - } -} - -// -// END Functions ... -// diff --git a/Documents/Pack/V1.0/Source/Indicators/x-saherelm.xct.mq5 b/Documents/Pack/V1.0/Source/Indicators/x-saherelm.xct.mq5 deleted file mode 100644 index 25b3b073..00000000 --- a/Documents/Pack/V1.0/Source/Indicators/x-saherelm.xct.mq5 +++ /dev/null @@ -1,261 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Indicator -// --------------------------------------------- -// Name: XCT -// Description: Trend Magic Indicator ... -// -// -// Maintainer: -// ------------ -// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) -// -////////////////////////////////////////////////////// -// -// Global Properties ... -#property copyright "Copyright 2023, SaherElm IT Center" -#property link "https://saherelm.ir" -#property version "1.00" -#property description "SaherElm XCT Indicator" -#property strict - -// -// START Constants ... -// - -// -#define ShortName "XCT" -#include "../Libraries/x-saherelm.common.lib.mq5" - -// -// END Constants ... -// - -// -// START Inputs ... -// - -// -input color clr = clrYellow; // Text Color -input ENUM_BASE_CORNER corner = CORNER_RIGHT_LOWER; // Text Position - -// -input group "Presentation"; -input bool showCandleTime = true; // Show Candle Time - -// -// END Inputs ... -// - -// -// START Buffers ... -// - -// -#property indicator_chart_window - -// -#property indicator_buffers 0 -#property indicator_plots 0 - -// -// END Buffers ... -// - -// -// START Global Definitions: Variables, Properties and etc ... -// - -// -// END Global Definitions: Variables, Properties and etc ... -// - -// -// START Event Handlers ... -// - -// -// Initialization ... -int OnInit() -{ - // - // Validate Inputs ... - if (showCandleTime) - { - CreateIndicatorObject(); - } - else - { - ObjectDelete(0, ShortName); - } - - // - // 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 - - // - ulong chID = FindChartID( - _Symbol, - _Period - // - ); - - // - // Delete Object ... - ObjectDelete(chID, ShortName); - - // - Comment(""); -} - -// -// Calculating what we want ... -int OnCalculate( - const int rates_total, // Total Bars on Chart ... - const int prev_calculated, // Total Calculated Bars on Charts ... - const datetime &time[], // History of Open Time ... - const double &open[], // History of Open Price ... - const double &high[], // History of High Price ... - const double &low[], // History of Low Price ... - const double &close[], // History of Close Price ... - const long &tick_volume[], // History of Tick Volumes on Bar ... - const long &volume[], // History of Trade Volumes ... - const int &spread[] // History of Spread Price ... -) -{ - // - ArraySetAsSeries(time, true); - - // - if (!showCandleTime) - { - return rates_total; - } - - // - ulong chID = FindChartID( - _Symbol, - _Period - // - ); - - // - XBarRemainsTime barRemains; - barRemains.Init( - _Symbol, - _Period - // - ); - - // - string msg = barRemains - .ToString( - "", - "", - "", - "", - "", - ":", - true - // - ); - - // - long mSpread = SymbolInfoInteger(Symbol(), SYMBOL_SPREAD); - - // - string _sp = ""; - if (mSpread < 10) - _sp = ".."; - else if (mSpread < 100) - _sp = "."; - - // - string objText = "Spread: " + IntegerToString(mSpread) + _sp + " Next Bar in: " + msg; - - // - ObjectSetInteger(chID, ShortName, OBJPROP_COLOR, clr); - ObjectSetString(chID, ShortName, OBJPROP_TEXT, objText); - ObjectSetInteger(chID, ShortName, OBJPROP_FONTSIZE, 10); - ObjectSetString(chID, ShortName, OBJPROP_FONT, "Courier"); - - // - return rates_total; -} - -// -// END Event Handlers ... -// - -// -// START Functions ... -// - -// -// Set Indicator Short Name and also we can define Buffers Labels ... -void SetIndicatorName() -{ - IndicatorSetString(INDICATOR_SHORTNAME, ShortName); -} - -// -void CreateIndicatorObject() -{ - // - if (!showCandleTime) - { - return; - } - - // - ObjectCreate(0, ShortName, OBJ_LABEL, 0, 0, 0); - ObjectSetInteger(0, ShortName, OBJPROP_CORNER, corner); - ObjectSetInteger(0, ShortName, OBJPROP_XDISTANCE, 10); - ObjectSetInteger(0, ShortName, OBJPROP_YDISTANCE, 2); - - // - ENUM_ANCHOR_POINT Anchor = ANCHOR_LEFT_UPPER; - switch (corner) - { - case CORNER_LEFT_UPPER: - Anchor = ANCHOR_LEFT_UPPER; - break; - case CORNER_RIGHT_UPPER: - Anchor = ANCHOR_RIGHT_UPPER; - break; - case CORNER_LEFT_LOWER: - Anchor = ANCHOR_LEFT_LOWER; - break; - case CORNER_RIGHT_LOWER: - Anchor = ANCHOR_RIGHT_LOWER; - break; - } - - // - ObjectSetInteger(0, ShortName, OBJPROP_ANCHOR, Anchor); -} - -// -// END Functions ... -// diff --git a/Documents/Pack/V1.0/Source/Indicators/x-saherelm.xdmnt.mq5 b/Documents/Pack/V1.0/Source/Indicators/x-saherelm.xdmnt.mq5 deleted file mode 100644 index cd4c6278..00000000 --- a/Documents/Pack/V1.0/Source/Indicators/x-saherelm.xdmnt.mq5 +++ /dev/null @@ -1,222 +0,0 @@ -/////////////////////////////////////////////////////// -// SaherElm IT Center MQL5 Indicator -// ------------------------------------------- -// Name: XDMNT -// Description: Dominant ... -// -// 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 XDMNT Indicator" -#property strict - -// -#define ShortName "XDMNT" - -// -// Imports ... -#include "../Libraries/x-saherelm.common.lib.mq5" - -// -// Inputs ... - -// -input group "Presentation"; -input bool showBull = true; // Show Bull -input bool showBear = true; // Show Bear - -// -// Buffers ... - -// -#property indicator_chart_window - -// -#property indicator_buffers 2 -#property indicator_plots 2 - -// -#define bullBufferIndex 0 -double bullBuffer[]; - -// -#property indicator_label1 "XDMNT Bull" -#property indicator_type1 DRAW_ARROW -#property indicator_color1 clrAqua -#property indicator_width1 2 - -// -#define bearBufferIndex 1 -double bearBuffer[]; - -// -#property indicator_label2 "XDMNT Bear" -#property indicator_type2 DRAW_ARROW -#property indicator_color2 clrMagenta -#property indicator_width2 2 - -// -// Event Handlers ... - -// -// Initialization ... -int OnInit() -{ - // - // Validate Inputs ... - if (!ValidateInputs()) - { - return INIT_PARAMETERS_INCORRECT; - } - - // - // Define Index Buffers ... - DefineBuffers(); - - // - // Set Indicator ShortName ... - SetIndicatorName(); - - // - // Init Succeed ... - return INIT_SUCCEEDED; -} - -// -// DeInitialization ... -void OnDeinit(const int reason) -{ - // - // REASON_PROGRAM 0 The EA has stopped working calling the ExpertRemove() function - // REASON_REMOVE 1 Program removed from a chart - // REASON_RECOMPILE 2 Program recompiled - // REASON_CHARTCHANGE 3 A symbol or a chart period is changed - // REASON_CHARTCLOSE 4 Chart closed - // REASON_PARAMETERS 5 Inputs changed by a user - // REASON_ACCOUNT 6 Another account has been activated or reconnection to the trade server has occurred due to changes in the account settings - // REASON_TEMPLATE 7 Another chart template applied - // REASON_INITFAILED 8 The OnInit() handler returned a non-zero value - // REASON_CLOSE 9 Terminal closed -} - -// -// Calculating what we want ... -int OnCalculate( - const int rates_total, // Total Bars on Chart ... - const int prev_calculated, // Total Calculated Bars on Charts ... - const datetime &time[], // History of Open Time ... - const double &open[], // History of Open Price ... - const double &high[], // History of High Price ... - const double &low[], // History of Low Price ... - const double &close[], // History of Close Price ... - const long &tick_volume[], // History of Tick Volumes on Bar ... - const long &volume[], // History of Trade Volumes ... - const int &spread[] // History of Spread Price ... -) -{ - // - ArraySetAsSeries(open, true); - ArraySetAsSeries(high, true); - ArraySetAsSeries(low, true); - ArraySetAsSeries(close, true); - ArraySetAsSeries(time, true); - - // - for (int i = 1; i < rates_total - 2; i++) - { - // - // Bullish ... - if (open[i] < close[i] && open[i + 1] < close[i + 1] && open[i] >= close[i + 1] && low[i] < close[i + 1] && high[i + 1] > open[i]) - { - // - bullBuffer[i] = low[i + 1]; - } - else - { - // - bullBuffer[i] = 0; - } - - // - // Bearish ... - if (open[i] > close[i] && open[i + 1] > close[i + 1] && open[i] <= close[i + 1] && high[i] > close[i + 1] && low[i + 1] < open[i]) - { - // - bearBuffer[i] = high[i + 1]; - } - else - { - // - bearBuffer[i] = 0; - } - } - - // - return rates_total; -} - -// -// Custom Functions ... - -// -// Validate Input Args for Initialization ... -bool ValidateInputs() -{ - // - bool result = false; - - // - result = true; - - // - return result; -} - -// -// Set Indicator Short Name and also we can define Buffers Labels ... -void SetIndicatorName() -{ - IndicatorSetString(INDICATOR_SHORTNAME, ShortName); -} - -// -// Define Indexes and Styles ... -void DefineBuffers() -{ - // - // Bull ... - ENUM_DRAW_TYPE bullDrawType = showBull ? DRAW_ARROW : DRAW_NONE; - - // - ArraySetAsSeries(bullBuffer, true); - PlotIndexSetInteger(bullBufferIndex, PLOT_ARROW, 225); - PlotIndexSetDouble(bullBufferIndex, PLOT_EMPTY_VALUE, 0); - SetIndexBuffer(bullBufferIndex, bullBuffer, INDICATOR_DATA); - - // - PlotIndexSetInteger(bullBufferIndex, PLOT_SHOW_DATA, showBull); - PlotIndexSetInteger(bullBufferIndex, PLOT_DRAW_TYPE, bullDrawType); - - // - // Bear ... - ENUM_DRAW_TYPE bearDrawType = showBear ? DRAW_ARROW : DRAW_NONE; - - // - ArraySetAsSeries(bearBuffer, true); - PlotIndexSetInteger(bearBufferIndex, PLOT_ARROW, 225); - PlotIndexSetDouble(bearBufferIndex, PLOT_EMPTY_VALUE, 0); - SetIndexBuffer(bearBufferIndex, bearBuffer, INDICATOR_DATA); - - // - PlotIndexSetInteger(bearBufferIndex, PLOT_SHOW_DATA, showBull); - PlotIndexSetInteger(bearBufferIndex, PLOT_DRAW_TYPE, bearDrawType); -} - -// \ No newline at end of file diff --git a/Documents/Pack/V1.0/Source/Indicators/x-saherelm.xdon.mq5 b/Documents/Pack/V1.0/Source/Indicators/x-saherelm.xdon.mq5 deleted file mode 100644 index c96e2bf7..00000000 --- a/Documents/Pack/V1.0/Source/Indicators/x-saherelm.xdon.mq5 +++ /dev/null @@ -1,366 +0,0 @@ -/////////////////////////////////////////////////////// -// SaherElm IT Center MQL5 Indicator -// ------------------------------------------- -// Name: XDON -// Description: DONCHAIN Channel ... -// -// 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 XDON Indicator" -#property strict - -// -#define ShortName "XDON" - -// -// INPUT ... - -// -input group "Market"; -input int length = 52; // Market Length -input double offset = 0; // Offset - -// -input group "Presentation"; -input bool showOpen = true; // Show Open -input bool showHigh = true; // Show High -input bool showClose = true; // Show Close -input bool showLow = true; // Show Low - -// -// BUFFERS ... - -// -#property indicator_chart_window - -// -#property indicator_buffers 8 -#property indicator_plots 8 - -// -#define upperOBufferIndex 0 -double upperOBuffer[]; - -// -#property indicator_label1 "XDON OU" -#property indicator_type1 DRAW_LINE -#property indicator_color1 clrCornflowerBlue -#property indicator_width1 2 - -// -#define lowerOBufferIndex 1 -double lowerOBuffer[]; - -// -#property indicator_label2 "XDON OL" -#property indicator_type2 DRAW_LINE -#property indicator_color2 clrCornflowerBlue -#property indicator_width2 2 - -// -#define upperCBufferIndex 2 -double upperCBuffer[]; - -// -#property indicator_label3 "XDON CU" -#property indicator_type3 DRAW_LINE -#property indicator_color3 clrCoral -#property indicator_width3 2 - -// -#define lowerCBufferIndex 3 -double lowerCBuffer[]; - -// -#property indicator_label4 "XDON CL" -#property indicator_type4 DRAW_LINE -#property indicator_color4 clrCoral -#property indicator_width4 2 - -// -#define upperHBufferIndex 4 -double upperHBuffer[]; - -// -#property indicator_label5 "XDON HU" -#property indicator_type5 DRAW_LINE -#property indicator_color5 clrAquamarine -#property indicator_width5 2 - -// -#define lowerHBufferIndex 5 -double lowerHBuffer[]; - -// -#property indicator_label6 "XDON HL" -#property indicator_type6 DRAW_LINE -#property indicator_color6 clrAquamarine -#property indicator_width6 2 - -// -#define upperLBufferIndex 6 -double upperLBuffer[]; - -// -#property indicator_label7 "XDON LU" -#property indicator_type7 DRAW_LINE -#property indicator_color7 clrDarkOrchid -#property indicator_width7 2 - -// -#define lowerLBufferIndex 7 -double lowerLBuffer[]; - -// -#property indicator_label8 "XDON LL" -#property indicator_type8 DRAW_LINE -#property indicator_color8 clrDarkOrchid -#property indicator_width8 2 - -// -// EVENT Handlers ... - -// -// Initialization ... -int OnInit() -{ - // - // Validate Inputs ... - if (!ValidateInputs()) - { - return INIT_PARAMETERS_INCORRECT; - } - - // - // Define Index Buffers ... - DefineBuffers(); - - // - // Set Indicator ShortName ... - SetIndicatorName(); - - // - // Init Succeed ... - return INIT_SUCCEEDED; -} - -// -// DeInitialization ... -void OnDeinit(const int reason) -{ - // - // REASON_PROGRAM 0 The EA has stopped working calling the ExpertRemove() function - // REASON_REMOVE 1 Program removed from a chart - // REASON_RECOMPILE 2 Program recompiled - // REASON_CHARTCHANGE 3 A symbol or a chart period is changed - // REASON_CHARTCLOSE 4 Chart closed - // REASON_PARAMETERS 5 Inputs changed by a user - // REASON_ACCOUNT 6 Another account has been activated or reconnection to the trade server has occurred due to changes in the account settings - // REASON_TEMPLATE 7 Another chart template applied - // REASON_INITFAILED 8 The OnInit() handler returned a non-zero value - // REASON_CLOSE 9 Terminal closed -} - -// -// Calculating what we want ... -int OnCalculate( - const int rates_total, // Total Bars on Chart ... - const int prev_calculated, // Total Calculated Bars on Charts ... - const datetime &time[], // History of Open Time ... - const double &open[], // History of Open Price ... - const double &high[], // History of High Price ... - const double &low[], // History of Low Price ... - const double &close[], // History of Close Price ... - const long &tick_volume[], // History of Tick Volumes on Bar ... - const long &volume[], // History of Trade Volumes ... - const int &spread[] // History of Spread Price ... -) -{ - // - if (rates_total < length - 1) - { - return prev_calculated; - } - - // - int start = prev_calculated == 0 - ? length - : prev_calculated - 1; - - // - // Main Loop ... - for (int barIndex = start; barIndex < rates_total; barIndex++) - { - // - // OPEN ... - - // - double upperOValue = open[ArrayMaximum(open, barIndex - length + 1, length)]; - double lowerOValue = open[ArrayMinimum(open, barIndex - length + 1, length)]; - - // - double oDelta = MathAbs(upperOValue - lowerOValue); - double oOffsetValue = oDelta * (offset) * 0.01; - - // - upperOBuffer[barIndex] = upperOValue - oOffsetValue; - lowerOBuffer[barIndex] = lowerOValue + oOffsetValue; - - // - // CLOSE ... - - // - double upperCValue = close[ArrayMaximum(close, barIndex - length + 1, length)]; - double lowerCValue = close[ArrayMinimum(close, barIndex - length + 1, length)]; - - // - double cDelta = MathAbs(upperCValue - lowerCValue); - double cOffsetValue = cDelta * (offset) * 0.01; - - // - upperCBuffer[barIndex] = upperCValue - cOffsetValue; - lowerCBuffer[barIndex] = lowerCValue + cOffsetValue; - - // - // HIGH ... - - // - double upperHValue = high[ArrayMaximum(high, barIndex - length + 1, length)]; - double lowerHValue = high[ArrayMinimum(high, barIndex - length + 1, length)]; - - // - double hDelta = MathAbs(upperHValue - lowerHValue); - double hOffsetValue = hDelta * (offset) * 0.01; - - // - upperHBuffer[barIndex] = upperHValue - hOffsetValue; - lowerHBuffer[barIndex] = lowerHValue + hOffsetValue; - - // - // LOW ... - - // - double upperLValue = low[ArrayMaximum(low, barIndex - length + 1, length)]; - double lowerLValue = low[ArrayMinimum(low, barIndex - length + 1, length)]; - - // - double lDelta = MathAbs(upperLValue - lowerLValue); - double lOffsetValue = lDelta * (offset) * 0.01; - - // - upperLBuffer[barIndex] = upperLValue - lOffsetValue; - lowerLBuffer[barIndex] = lowerLValue + lOffsetValue; - } - - // - return rates_total; -} - -// -// CUSTOM Functions ... - -// -// Validate Input Args for Initialization ... -bool ValidateInputs() -{ - // - bool result = false; - - // - result = length >= 7; - - // - return result; -} - -// -// Define Indexes and Styles ... -void DefineBuffers() -{ - // - // Open ... - ENUM_DRAW_TYPE openDrawType = showOpen ? DRAW_LINE : DRAW_NONE; - - // - // UPPER ... - SetIndexBuffer(upperOBufferIndex, upperOBuffer, INDICATOR_DATA); - PlotIndexSetInteger(upperOBufferIndex, PLOT_SHOW_DATA, showOpen); - PlotIndexSetDouble(upperOBufferIndex, PLOT_EMPTY_VALUE, EMPTY_VALUE); - PlotIndexSetInteger(upperOBufferIndex, PLOT_DRAW_TYPE, openDrawType); - - // - // LOWER ... - SetIndexBuffer(lowerOBufferIndex, lowerOBuffer, INDICATOR_DATA); - PlotIndexSetInteger(lowerOBufferIndex, PLOT_SHOW_DATA, showOpen); - PlotIndexSetDouble(lowerOBufferIndex, PLOT_EMPTY_VALUE, EMPTY_VALUE); - PlotIndexSetInteger(lowerOBufferIndex, PLOT_DRAW_TYPE, openDrawType); - - // - // Close ... - ENUM_DRAW_TYPE closeDrawType = showClose ? DRAW_LINE : DRAW_NONE; - - // - // UPPER ... - SetIndexBuffer(upperCBufferIndex, upperCBuffer, INDICATOR_DATA); - PlotIndexSetInteger(upperCBufferIndex, PLOT_SHOW_DATA, showClose); - PlotIndexSetDouble(upperCBufferIndex, PLOT_EMPTY_VALUE, EMPTY_VALUE); - PlotIndexSetInteger(upperCBufferIndex, PLOT_DRAW_TYPE, closeDrawType); - - // - // LOWER ... - SetIndexBuffer(lowerCBufferIndex, lowerCBuffer, INDICATOR_DATA); - PlotIndexSetInteger(lowerCBufferIndex, PLOT_SHOW_DATA, showClose); - PlotIndexSetDouble(lowerCBufferIndex, PLOT_EMPTY_VALUE, EMPTY_VALUE); - PlotIndexSetInteger(lowerCBufferIndex, PLOT_DRAW_TYPE, closeDrawType); - - // - // High ... - ENUM_DRAW_TYPE highDrawType = showHigh ? DRAW_LINE : DRAW_NONE; - - // - // UPPER ... - SetIndexBuffer(upperHBufferIndex, upperHBuffer, INDICATOR_DATA); - PlotIndexSetInteger(upperHBufferIndex, PLOT_SHOW_DATA, showHigh); - PlotIndexSetDouble(upperHBufferIndex, PLOT_EMPTY_VALUE, EMPTY_VALUE); - PlotIndexSetInteger(upperHBufferIndex, PLOT_DRAW_TYPE, highDrawType); - - // - // LOWER ... - SetIndexBuffer(lowerHBufferIndex, lowerHBuffer, INDICATOR_DATA); - PlotIndexSetInteger(lowerHBufferIndex, PLOT_SHOW_DATA, showHigh); - PlotIndexSetDouble(lowerHBufferIndex, PLOT_EMPTY_VALUE, EMPTY_VALUE); - PlotIndexSetInteger(lowerHBufferIndex, PLOT_DRAW_TYPE, highDrawType); - - // - // Low ... - ENUM_DRAW_TYPE lowDrawType = showLow ? DRAW_LINE : DRAW_NONE; - - // - // UPPER ... - SetIndexBuffer(upperLBufferIndex, upperLBuffer, INDICATOR_DATA); - PlotIndexSetInteger(upperLBufferIndex, PLOT_SHOW_DATA, showLow); - PlotIndexSetDouble(upperLBufferIndex, PLOT_EMPTY_VALUE, EMPTY_VALUE); - PlotIndexSetInteger(upperLBufferIndex, PLOT_DRAW_TYPE, lowDrawType); - - // - // LOWER ... - SetIndexBuffer(lowerLBufferIndex, lowerLBuffer, INDICATOR_DATA); - PlotIndexSetInteger(lowerLBufferIndex, PLOT_SHOW_DATA, showLow); - PlotIndexSetDouble(lowerLBufferIndex, PLOT_EMPTY_VALUE, EMPTY_VALUE); - PlotIndexSetInteger(lowerLBufferIndex, PLOT_DRAW_TYPE, lowDrawType); -} - -// -// Set Indicator Short Name and also we can define Buffers Labels ... -void SetIndicatorName() -{ - IndicatorSetString(INDICATOR_SHORTNAME, ShortName); -} diff --git a/Documents/Pack/V1.0/Source/Indicators/x-saherelm.xhk.mq5 b/Documents/Pack/V1.0/Source/Indicators/x-saherelm.xhk.mq5 deleted file mode 100644 index 37cf4b55..00000000 --- a/Documents/Pack/V1.0/Source/Indicators/x-saherelm.xhk.mq5 +++ /dev/null @@ -1,479 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Indicator -// -------------------------------------------- -// Name: XHK -// Description: Hiken Ashi ... -// 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 XHK Indicator" -#property strict - -// -// Constants ... - -// -// Indicator Short Name ... -#define ShortName "XHK" - -// -// Imports ... -#include -#include "../Libraries/x-saherelm.common.lib.mq5" - -// -// Inputs ... - -// -input group "Market"; -input int smoothingLength = 17; // Smoothing Length -// -input group "Presentation"; -input bool drawHikenAshi = true; // Draw Hiken Ashi -input bool drawSmoothedHikenAshi = true; // Draw Smoothed Hiken Ashi - -// -// Buffers ... - -// -#property indicator_chart_window - -// -#property indicator_buffers 10 -#property indicator_plots 10 - -// -// Buffers ... - -// -// Open ... -#define openBufferIndex 0 -double openBuffer[]; - -// -// High ... -#define highBufferIndex 1 -double highBuffer[]; - -// -// Low ... -#define lowBufferIndex 2 -double lowBuffer[]; - -// -// Close ... -#define closeBufferIndex 3 -double closeBuffer[]; - -// -// Candle Color ... -#define candleColorBufferIndex 4 -double candleColorBuffer[]; - -// -#define candlesBufferIndex 0 - -// -#property indicator_label1 "XHK Open;XHK High;XHK Low;XHK Close" -#property indicator_type1 DRAW_COLOR_CANDLES -#property indicator_color1 CLR_NONE, clrAqua, clrMagenta - -// -// SM Open ... -#define openSMBufferIndex 5 -double openSMBuffer[]; - -// -// SM High ... -#define highSMBufferIndex 6 -double highSMBuffer[]; - -// -// SM Low ... -#define lowSMBufferIndex 7 -double lowSMBuffer[]; - -// -// SM Close ... -#define closeSMBufferIndex 8 -double closeSMBuffer[]; - -// -// SM Candle Color ... -#define candleColorSMBufferIndex 9 -double candleColorSMBuffer[]; - -// -#define candlesSMBufferIndex 1 - -// -#property indicator_label2 "XSMHK Open;XSMHK High;XSMHK Low;XSMHK Close" -#property indicator_type2 DRAW_COLOR_CANDLES -#property indicator_color2 CLR_NONE, clrDarkGreen, clrDarkRed - -// -// Variables, Properties and etc ... - -// -int maxLength; - -// -double mHideColorIDX = 0; - -// -// Event Handlers ... - -// -// Initialization ... -int OnInit() -{ - // - // Validate Inputs ... - if (!ValidateInputs()) - { - return INIT_PARAMETERS_INCORRECT; - } - - // - // because in some cases we may have more than one input for - // calculation and we must prevent any calculation - // untill we pass the biggest input length, here we get max Input length - // and then wait until pass it ... - maxLength = ExtractMaxLengthOfInputs(); - - // - // Define Index Buffers ... - DefineBuffers(); - - // - // Set Indicator ShortName ... - SetIndicatorName(); - - // - // Init Succeed ... - return INIT_SUCCEEDED; -} - -// -// DeInitialization ... -void OnDeinit(const int reason) -{ - // - // REASON_PROGRAM 0 The EA has stopped working calling the ExpertRemove() function - // REASON_REMOVE 1 Program removed from a chart - // REASON_RECOMPILE 2 Program recompiled - // REASON_CHARTCHANGE 3 A symbol or a chart period is changed - // REASON_CHARTCLOSE 4 Chart closed - // REASON_PARAMETERS 5 Inputs changed by a user - // REASON_ACCOUNT 6 Another account has been activated or reconnection to the trade server has occurred due to changes in the account settings - // REASON_TEMPLATE 7 Another chart template applied - // REASON_INITFAILED 8 The OnInit() handler returned a non-zero value - // REASON_CLOSE 9 Terminal closed -} - -// -// Calculating what we want ... -int OnCalculate( - const int rates_total, // Total Bars on Chart ... - const int prev_calculated, // Total Calculated Bars on Charts ... - const datetime &time[], // History of Open Time ... - const double &open[], // History of Open Price ... - const double &high[], // History of High Price ... - const double &low[], // History of Low Price ... - const double &close[], // History of Close Price ... - const long &tick_volume[], // History of Tick Volumes on Bar ... - const long &volume[], // History of Trade Volumes ... - const int &spread[] // History of Spread Price ... -) -{ - // - // 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; - - // - limit = (prev_calculated > rates_total || prev_calculated <= 0) ? rates_total : (rates_total - prev_calculated) + 1; - - // - // Main Loop ... - for (int i = limit - 1; i >= 0 && !IsStopped(); i--) - { - CalculateBuffers(i, prev_calculated, rates_total, open, high, close, low); - } - - // - CalculateSM(rates_total, prev_calculated); - - // - return rates_total; -} - -// -// Functions ... - -// -// Validate Input Args for Initialization ... -bool ValidateInputs() -{ - // - bool result = true; - - // - return result; -} - -// -// Retrieve all Exists Input Max Length ... -// use for Start Of Drawing ... -int ExtractMaxLengthOfInputs() -{ - // - int result = 0; - - // - return result; -} - -// -// Define Indexes and Styles ... -void DefineBuffers() -{ - // - // Candles Color ... - ArraySetAsSeries(candleColorBuffer, true); - SetIndexBuffer(candleColorBufferIndex, candleColorBuffer, INDICATOR_COLOR_INDEX); - - // - // Set EMPTY_VALUE on Candles Buffer ... - PlotIndexSetDouble(candlesBufferIndex, PLOT_EMPTY_VALUE, 0.0); - - // - PlotIndexSetInteger(candlesBufferIndex, PLOT_SHOW_DATA, false); - PlotIndexSetInteger(candleColorBufferIndex, PLOT_SHOW_DATA, false); - - // - // Open ... - ArraySetAsSeries(openBuffer, true); - PlotIndexSetInteger(openBufferIndex, PLOT_SHOW_DATA, false); - SetIndexBuffer(openBufferIndex, openBuffer, INDICATOR_DATA); - - // - // High ... - ArraySetAsSeries(highBuffer, true); - SetIndexBuffer(highBufferIndex, highBuffer, INDICATOR_DATA); - PlotIndexSetInteger(highBufferIndex, PLOT_SHOW_DATA, false); - - // - // Close ... - ArraySetAsSeries(closeBuffer, true); - SetIndexBuffer(closeBufferIndex, closeBuffer, INDICATOR_DATA); - PlotIndexSetInteger(closeBufferIndex, PLOT_SHOW_DATA, false); - - // - // Low ... - ArraySetAsSeries(lowBuffer, true); - SetIndexBuffer(lowBufferIndex, lowBuffer, INDICATOR_DATA); - PlotIndexSetInteger(lowBufferIndex, PLOT_SHOW_DATA, false); - - // - // Candles Color ... - ArraySetAsSeries(candleColorSMBuffer, true); - SetIndexBuffer(candleColorSMBufferIndex, candleColorSMBuffer, INDICATOR_COLOR_INDEX); - - // - // Set EMPTY_VALUE on Candles Buffer ... - PlotIndexSetDouble(candlesSMBufferIndex, PLOT_EMPTY_VALUE, 0.0); - - // - PlotIndexSetInteger(candlesSMBufferIndex, PLOT_SHOW_DATA, false); - PlotIndexSetInteger(candleColorSMBufferIndex, PLOT_SHOW_DATA, false); - - // - // Open ... - ArraySetAsSeries(openSMBuffer, true); - PlotIndexSetInteger(openSMBufferIndex, PLOT_SHOW_DATA, false); - SetIndexBuffer(openSMBufferIndex, openSMBuffer, INDICATOR_DATA); - - // - // High ... - ArraySetAsSeries(highSMBuffer, true); - SetIndexBuffer(highSMBufferIndex, highSMBuffer, INDICATOR_DATA); - PlotIndexSetInteger(highSMBufferIndex, PLOT_SHOW_DATA, false); - - // - // Close ... - ArraySetAsSeries(closeSMBuffer, true); - SetIndexBuffer(closeSMBufferIndex, closeSMBuffer, INDICATOR_DATA); - PlotIndexSetInteger(closeSMBufferIndex, PLOT_SHOW_DATA, false); - - // - // Low ... - ArraySetAsSeries(lowSMBuffer, true); - SetIndexBuffer(lowSMBufferIndex, lowSMBuffer, INDICATOR_DATA); - PlotIndexSetInteger(lowSMBufferIndex, PLOT_SHOW_DATA, false); -} - -// -// Set Indicator Short Name and also we can define Buffers Labels ... -void SetIndicatorName() -{ - IndicatorSetString(INDICATOR_SHORTNAME, ShortName); -} - -// -// Calculate Buffers ... -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[] // -) -{ - // - double mPrevHKOpenValue; - double mPrevHKCloseValue; - - // - if (ArraySize(open) <= bar_index + 1) - { - // - mPrevHKOpenValue = 0; - mPrevHKCloseValue = 0; - } - else - { - // - mPrevHKOpenValue = openBuffer[bar_index + 1]; - mPrevHKCloseValue = closeBuffer[bar_index + 1]; - } - - // - double mHKOpenValue = (mPrevHKOpenValue + mPrevHKCloseValue) / 2; - double mHKCloseValue = (open[bar_index] + high[bar_index] + close[bar_index] + low[bar_index]) / 4; - double mHKHighValue = MathMax(high[bar_index], MathMax(mHKOpenValue, mHKCloseValue)); - double mHKLowValue = MathMin(low[bar_index], MathMin(mHKOpenValue, mHKCloseValue)); - - // - openBuffer[bar_index] = mHKOpenValue; - highBuffer[bar_index] = mHKHighValue; - lowBuffer[bar_index] = mHKLowValue; - closeBuffer[bar_index] = mHKCloseValue; - - // - bool isBearish = - // - openBuffer[bar_index] > closeBuffer[bar_index] - // - ; - - // - candleColorBuffer[bar_index] = !drawHikenAshi - ? mHideColorIDX - : isBearish - ? 2 - : 1; -} - -// -// Calculate Smoothed HikenAshi ... -void CalculateSM( - int ratesTotal, // Total Bars - int prevCalculated // Calculated Bars -) -{ - // - // Open ... - int calculatedSMHKOpens = ExponentialMAOnBuffer( - ratesTotal, - prevCalculated, - 0, - smoothingLength, - openBuffer, - openSMBuffer); - - // - // High ... - int calculatedSMHKHighs = ExponentialMAOnBuffer( - ratesTotal, - prevCalculated, - 0, - smoothingLength, - highBuffer, - highSMBuffer); - - // - // Low ... - int calculatedSMHKLows = ExponentialMAOnBuffer( - ratesTotal, - prevCalculated, - 0, - smoothingLength, - lowBuffer, - lowSMBuffer); - - // - // Close ... - int calculatedSMHKCloses = ExponentialMAOnBuffer( - ratesTotal, - prevCalculated, - 0, - smoothingLength, - closeBuffer, - closeSMBuffer); - - // - // Find Calculated Items for Colors ... - int mNumberOfItems = MathMin(calculatedSMHKOpens, calculatedSMHKHighs); - mNumberOfItems = MathMin(mNumberOfItems, calculatedSMHKLows); - mNumberOfItems = MathMin(mNumberOfItems, calculatedSMHKCloses); - - // - // Create a Loop for Color of Candles ... - for (int i = 0; i < mNumberOfItems; i++) - { - // - bool isBearish = - // - openSMBuffer[i] > closeSMBuffer[i] - // - ; - - // - if (drawSmoothedHikenAshi) - { - // - candleColorSMBuffer[i] = isBearish - ? 2 - : 1; - } - else - { - // - candleColorSMBuffer[i] = mHideColorIDX; - } - } -} diff --git a/Documents/Pack/V1.0/Source/Indicators/x-saherelm.xhtd.mq5 b/Documents/Pack/V1.0/Source/Indicators/x-saherelm.xhtd.mq5 deleted file mode 100644 index 873d9030..00000000 --- a/Documents/Pack/V1.0/Source/Indicators/x-saherelm.xhtd.mq5 +++ /dev/null @@ -1,368 +0,0 @@ -/////////////////////////////////////////////////////// -// SaherElm IT Center MQL5 Indicator -// ------------------------------------------- -// Name: XHTD -// Description: HULL Trend Detector ... -// -// 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 XHTD Indicator" -#property strict - -// -#define ShortName "XHTD" - -// -// Imports ... -#include "../Libraries/x-saherelm.common.lib.mq5" - -// -// Inputs ... - -// -input group "Market"; -input int length = 14; // Length -input ENUM_APPLIED_PRICE appliedTo = PRICE_CLOSE; // Applied To -input double multiplier = 0.66; // Multiplier - -// -input group "Presentation"; -input bool show = true; // Show - -// -// Buffers ... - -// -#property indicator_chart_window - -// -#property indicator_buffers 2 -#property indicator_plots 2 - -// -#define mainBufferIndex 0 -double mainBuffer[]; - -// -#define mainBufferColorIndex 1 -double mainBufferColor[]; - -// -#define hideColorIDX 0 -#define bullColorIDX 1 -#define bearColorIDX 2 - -// -#property indicator_label1 "XHTD" -#property indicator_type1 DRAW_COLOR_LINE -#property indicator_color1 CLR_NONE, clrGreen, clrDarkRed -#property indicator_style1 STYLE_DOT -#property indicator_width1 1 - -// -#define upBufferIndex 2 -double upBuffer[]; - -// -#define downBufferIndex 3 -double downBuffer[]; - -// -#define directionBufferIndex 4 -double directionBuffer[]; - -// -// Event Handlers ... - -// -// Initialization ... -int OnInit() -{ - // - // Validate Inputs ... - if (!ValidateInputs()) - { - return INIT_PARAMETERS_INCORRECT; - } - - // - // Define Index Buffers ... - DefineBuffers(); - - // - // Set Indicator ShortName ... - SetIndicatorName(); - - // - // Init Succeed ... - return INIT_SUCCEEDED; -} - -// -// DeInitialization ... -void OnDeinit(const int reason) -{ - // - // REASON_PROGRAM 0 The EA has stopped working calling the ExpertRemove() function - // REASON_REMOVE 1 Program removed from a chart - // REASON_RECOMPILE 2 Program recompiled - // REASON_CHARTCHANGE 3 A symbol or a chart period is changed - // REASON_CHARTCLOSE 4 Chart closed - // REASON_PARAMETERS 5 Inputs changed by a user - // REASON_ACCOUNT 6 Another account has been activated or reconnection to the trade server has occurred due to changes in the account settings - // REASON_TEMPLATE 7 Another chart template applied - // REASON_INITFAILED 8 The OnInit() handler returned a non-zero value - // REASON_CLOSE 9 Terminal closed -} - -// -// Calculating what we want ... -int OnCalculate( - const int rates_total, // Total Bars on Chart ... - const int prev_calculated, // Total Calculated Bars on Charts ... - const datetime &time[], // History of Open Time ... - const double &open[], // History of Open Price ... - const double &high[], // History of High Price ... - const double &low[], // History of Low Price ... - const double &close[], // History of Close Price ... - const long &tick_volume[], // History of Tick Volumes on Bar ... - const long &volume[], // History of Trade Volumes ... - const int &spread[] // History of Spread Price ... -) -{ - // - if (ArraySize(directionBuffer) != rates_total) - { - // - ArrayResize(upBuffer, rates_total); - ArrayResize(downBuffer, rates_total); - ArrayResize(directionBuffer, rates_total); - } - - // - for (int i = (int)MathMax(prev_calculated - 1, 1); i < rates_total; i++) - { - // - double atr = 0; - for (int k = 0; k < length && (i - k - 1) >= 0; k++) - { - atr += MathMax(high[i - k], close[i - k - 1]) - MathMin(low[i - k], close[i - k - 1]); - } - - // - atr /= length; - - // - double cprice = close[i]; - double appliedPrice = getPrice( - appliedTo, - open, - close, - high, - low, - i, - rates_total // - ); - double mprice = iHull( - appliedPrice, - length, - i, - rates_total // - ); - - // - upBuffer[i] = mprice + multiplier * atr; - downBuffer[i] = mprice - multiplier * atr; - - // - mainBufferColor[i] = mainBufferColor[i - 1]; - directionBuffer[i] = directionBuffer[i - 1]; - - // - if (cprice > upBuffer[i - 1]) - { - directionBuffer[i] = 1; - } - - // - if (cprice < downBuffer[i - 1]) - { - directionBuffer[i] = -1; - } - - // - if (directionBuffer[i] > 0) - { - // - downBuffer[i] = MathMax(downBuffer[i], downBuffer[i - 1]); - - // - mainBuffer[i] = downBuffer[i]; - } - else - { - // - upBuffer[i] = MathMin(upBuffer[i], upBuffer[i - 1]); - - // - mainBuffer[i] = upBuffer[i]; - } - - // - if (directionBuffer[i] == 1) - { - mainBufferColor[i] = bullColorIDX; - } - - // - if (directionBuffer[i] == -1) - { - mainBufferColor[i] = bearColorIDX; - } - } - - // - return rates_total; -} - -// -// Custom Functions ... - -// -// Validate Input Args for Initialization ... -bool ValidateInputs() -{ - // - bool result = false; - - // - result = length >= 2 && - multiplier > 0; - - // - return result; -} - -// -// Set Indicator Short Name and also we can define Buffers Labels ... -void SetIndicatorName() -{ - IndicatorSetString(INDICATOR_SHORTNAME, ShortName); -} - -// -// Define Indexes and Styles ... -void DefineBuffers() -{ - // - // Main ... - ENUM_DRAW_TYPE mainDrawType = show ? DRAW_COLOR_LINE : DRAW_NONE; - - // - PlotIndexSetInteger(mainBufferIndex, PLOT_SHOW_DATA, true); - SetIndexBuffer(mainBufferIndex, mainBuffer, INDICATOR_DATA); - PlotIndexSetInteger(mainBufferIndex, PLOT_DRAW_TYPE, mainDrawType); - SetIndexBuffer(mainBufferColorIndex, mainBufferColor, INDICATOR_COLOR_INDEX); - - // - SetIndexBuffer(upBufferIndex, upBuffer, INDICATOR_CALCULATIONS); - - // - SetIndexBuffer(downBufferIndex, downBuffer, INDICATOR_CALCULATIONS); - - // - SetIndexBuffer(directionBufferIndex, directionBuffer, INDICATOR_CALCULATIONS); -} - -// -// Hull Handler ... -double workHull[][2]; -double iHull( - double price, - double period, - int r, - int bars, - int instanceNo = 0 // -) -{ - // - if (ArrayRange(workHull, 0) != bars) - { - ArrayResize(workHull, bars); - } - - // - int HmaPeriod = (int)MathMax(period, 2); - int HalfPeriod = (int)MathFloor(HmaPeriod / 2); - int HullPeriod = (int)MathFloor(MathSqrt(HmaPeriod)); - double hma, hmw, weight; - instanceNo *= 2; - - // - workHull[r][instanceNo] = price; - - // - hmw = HalfPeriod; - hma = hmw * price; - for (int k = 1; k < HalfPeriod && (r - k) >= 0; k++) - { - // - weight = HalfPeriod - k; - hmw += weight; - hma += weight * workHull[r - k][instanceNo]; - } - workHull[r][instanceNo + 1] = 2.0 * hma / hmw; - - // - hmw = HmaPeriod; - hma = hmw * price; - for (int k = 1; k < period && (r - k) >= 0; k++) - { - // - weight = HmaPeriod - k; - hmw += weight; - hma += weight * workHull[r - k][instanceNo]; - } - workHull[r][instanceNo + 1] -= hma / hmw; - - // - hmw = HullPeriod; - hma = hmw * workHull[r][instanceNo + 1]; - for (int k = 1; k < HullPeriod && (r - k) >= 0; k++) - { - // - weight = HullPeriod - k; - hmw += weight; - hma += weight * workHull[r - k][1 + instanceNo]; - } - - // - return (hma / hmw); -} - -// -double getPrice(ENUM_APPLIED_PRICE price, const double& open[], const double& close[], const double& high[], const double& low[], int i, int bars) -{ - switch (price) - { - case PRICE_CLOSE: return(close[i]); - case PRICE_OPEN: return(open[i]); - case PRICE_HIGH: return(high[i]); - case PRICE_LOW: return(low[i]); - case PRICE_MEDIAN: return((high[i]+low[i])/2.0); - case PRICE_TYPICAL: return((high[i]+low[i]+close[i])/3.0); - case PRICE_WEIGHTED: return((high[i]+low[i]+close[i]+close[i])/4.0); - //case PRICE_AVERAGE: return((high[i]+low[i]+close[i]+open[i])/4.0); - } - return(0); -} - -// \ No newline at end of file diff --git a/Documents/Pack/V1.0/Source/Indicators/x-saherelm.xhull.mq5 b/Documents/Pack/V1.0/Source/Indicators/x-saherelm.xhull.mq5 deleted file mode 100644 index ffc17928..00000000 --- a/Documents/Pack/V1.0/Source/Indicators/x-saherelm.xhull.mq5 +++ /dev/null @@ -1,583 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Indicator -// --------------------------------------------- -// Name: XHULL -// Description: Hull Trend Indicator ... -// -// -// Maintainer: -// ------------ -// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) -// -////////////////////////////////////////////////////// -// -// Global Properties ... -#property copyright "Copyright 2023, SaherElm IT Center" -#property link "https://saherelm.ir" -#property version "1.00" -#property description "SaherElm XHULL Indicator" -#property strict - -// -// START Constants ... -// - -// -#define ShortName "XHULL" - -// -struct XHullData -{ - // - double value; - double value3; - - // - double wsum1; - double wsum2; - double wsum3; - - // - double lsum1; - double lsum2; - double lsum3; -}; - -// -// END Constants ... -// - -// -// START Includes and Imports ... -// - -// -// Includes Common Library ... -#include "../Libraries/x-saherelm.common.lib.mq5" - -// -// END Includes and Imports ... -// - -// -// START XSCHULL Class Definition ... -// - -// -// a Class For Hull Calculations ... -class XSCHull -{ - // -public: - // - // Constructor ... - XSCHull() : mFullPeriod(1), mHalfPeriod(1), mSqrtPeriod(1), mArraySize(-1) - { - // - // These are a way above to assign Private variables at Construct time ... - } - - // - // Deconstructor ... - ~XSCHull() - { - ArrayFree(mData); - } - - // - // Initial Hull ... - bool Init( - int mPeriod, - double mDivisor) - { - // - bool result = false; - - // - mFullPeriod = (int)(mPeriod > 1 ? mPeriod : 1); - mHalfPeriod = (int)(mFullPeriod > 1 ? mFullPeriod / (mDivisor > 1 ? mDivisor : 1) : 1); - mSqrtPeriod = (int)MathSqrt(mFullPeriod); - - // - mArraySize = -1; - mWeight1 = mWeight2 = mWeight3 = 1; - - // - result = true; - - // - return result; - } - - // - // CalCulate Specific Value ... - double Calculate( - double value, - int i, - int bars) - { - // - double result = 0; - - // - if (mArraySize < bars) - { - // - mArraySize = ArrayResize(mData, bars + 500); - if (mArraySize < bars) - return result; - } - - // - mData[i].value = value; - if (i > mFullPeriod) - { - // - mData[i].wsum1 = mData[i - 1].wsum1 + value * mHalfPeriod - mData[i - 1].lsum1; - mData[i].lsum1 = mData[i - 1].lsum1 + value - mData[i - mHalfPeriod].value; - mData[i].wsum2 = mData[i - 1].wsum2 + value * mFullPeriod - mData[i - 1].lsum2; - mData[i].lsum2 = mData[i - 1].lsum2 + value - mData[i - mFullPeriod].value; - } - else - { - // - mData[i].wsum1 = mData[i].wsum2 = - mData[i].lsum1 = mData[i].lsum2 = mWeight1 = mWeight2 = 0; - for (int k = 0, w1 = mHalfPeriod, w2 = mFullPeriod; w2 > 0 && i >= k; k++, w1--, w2--) - { - // - if (w1 > 0) - { - // - mData[i].wsum1 += mData[i - k].value * w1; - mData[i].lsum1 += mData[i - k].value; - mWeight1 += w1; - } - - // - mData[i].wsum2 += mData[i - k].value * w2; - mData[i].lsum2 += mData[i - k].value; - mWeight2 += w2; - } - } - - // - mData[i].value3 = 2.0 * mData[i].wsum1 / mWeight1 - mData[i].wsum2 / mWeight2; - - // - if (i > mSqrtPeriod) - { - // - mData[i].wsum3 = mData[i - 1].wsum3 + mData[i].value3 * mSqrtPeriod - mData[i - 1].lsum3; - mData[i].lsum3 = mData[i - 1].lsum3 + mData[i].value3 - mData[i - mSqrtPeriod].value3; - } - else - { - // - mData[i].wsum3 = - mData[i].lsum3 = mWeight3 = 0; - - // - for (int k = 0, w3 = mSqrtPeriod; w3 > 0 && i >= k; k++, w3--) - { - // - mData[i].wsum3 += mData[i - k].value3 * w3; - mData[i].lsum3 += mData[i - k].value3; - mWeight3 += w3; - } - } - - // - result = mData[i].wsum3 / mWeight3; - - // - return result; - } - - // - // Protected ... -protected: - // - // Private ... -private: - // - int mFullPeriod; - int mHalfPeriod; - int mSqrtPeriod; - int mArraySize; - double mWeight1; - double mWeight2; - double mWeight3; - - // - XHullData mData[]; -}; - -// -// END XSCHULL Class Definition ... -// - -// -// START Inputs ... -// - -// -input group "Market"; -input int length = 72; // Length -input double divisor = 2.0; // Divisor (Speed) - -// -input group "Calculation"; -input ENUM_APPLIED_PRICE upAppliedTo = PRICE_HIGH; // Up Zone Applied to -input ENUM_APPLIED_PRICE downAppliedTo = PRICE_LOW; // Down Zone Applied to - -// -input group "Presentation"; -input bool showUpZone = true; // Show Up Zone -input bool showDownZone = true; // Show Down Zone - -// -// END Inputs ... -// - -// -// START Buffers ... -// - -// -#property indicator_chart_window - -// -#property indicator_buffers 4 -#property indicator_plots 4 - -// -// UP Zone ... - -// -#define upZoneBufferIndex 0 -#define upZoneColorBufferIndex 1 - -// -double upZoneBuffer[]; -double upZoneColorBuffer[]; - -// -#property indicator_label1 "XHULL Up" -#property indicator_type1 DRAW_COLOR_LINE -#property indicator_color1 clrLightGray, clrAqua, clrMagenta -#property indicator_width1 1 - -// -// DOWN Zone ... - -// -#define downZoneBufferIndex 2 -#define downZoneColorBufferIndex 3 - -// -double downZoneBuffer[]; -double downZoneColorBuffer[]; - -// -#property indicator_label2 "XHULL Down" -#property indicator_type2 DRAW_COLOR_LINE -#property indicator_color2 clrLightGray, clrAqua, clrMagenta -#property indicator_width2 1 - -// -// END Buffers ... -// - -// -// START Global Definitions: Variables, Properties and etc ... -// - -// -int maxLength; - -// -XSCHull *mUpZHull; -XSCHull *mDownZHull; - -// -// END Global Definitions: Variables, Properties and etc ... -// - -// -// START Event Handlers ... -// -// -// Initialization ... -int OnInit() -{ - // - // Validate Inputs ... - if (!ValidateInputs()) - { - return INIT_PARAMETERS_INCORRECT; - } - - // - // because in some cases we may have more than one input for - // calculation and we must prevent any calculation - // untill we pass the biggest input length, here we get max Input length - // and then wait until pass it ... - maxLength = ExtractMaxLengthOfInputs(); - - // - // Define Index Buffers ... - DefineBuffers(); - - // - // Set Indicator ShortName ... - SetIndicatorName(); - - // - // Make an Instance of Hull Class ... - - // - mUpZHull = new XSCHull(); - mUpZHull.Init( - length, - divisor); - - // - mDownZHull = new XSCHull(); - mDownZHull.Init( - length, - divisor); - - // - // 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 mPeriod is changed - // REASON_CHARTCLOSE 4 Chart closed - // REASON_PARAMETERS 5 Inputs changed by a user - // REASON_ACCOUNT 6 Another account has been activated or reconnection to the trade server has occurred due to changes in the account settings - // REASON_TEMPLATE 7 Another chart template applied - // REASON_INITFAILED 8 The OnInit() handler returned a non-zero value - // REASON_CLOSE 9 Terminal closed - - // - delete mUpZHull; - delete mDownZHull; -} - -// -// Calculating what we want ... -int OnCalculate( - const int rates_total, // Total Bars on Chart ... - const int prev_calculated, // Total Calculated Bars on Charts ... - const datetime &time[], // History of Open Time ... - const double &open[], // History of Open Price ... - const double &high[], // History of High Price ... - const double &low[], // History of Low Price ... - const double &close[], // History of Close Price ... - const long &tick_volume[], // History of Tick Volumes on Bar ... - const long &volume[], // History of Trade Volumes ... - const int &spread[] // History of Spread Price ... -) -{ - // - // this counts Available Bars ... - int limit; - - // - limit = prev_calculated - 1; - if (limit < 0) - { - limit = 0; - } - - // - // Main Loop ... - for (int i = limit; i < rates_total && !IsStopped(); i++) - { - // - double upPrice = getPrice( - upAppliedTo, - open, high, low, close, i); - - // - double downPrice = getPrice( - downAppliedTo, - open, high, low, close, i); - - // - CalculateBuffers( - i, - rates_total, - upPrice, - downPrice); - } - - // - return rates_total; -} -// -// END Event Handlers ... -// - -// -// START Functions ... -// - -// -// Validate Input Args for Initialization ... -bool ValidateInputs() -{ - // - bool result = true; - - // - result = - length >= 9 && - divisor >= 0.5; - - // - return result; -} - -// -// Retrieve all Exists Input Max Length ... -// use for Start Of Drawing ... -int ExtractMaxLengthOfInputs() -{ - // - int result = 0; - - // - result = length; - - // - return result; -} - -// -// Set Indicator Short Name and also we can define Buffers Labels ... -void SetIndicatorName() -{ - // - IndicatorSetString(INDICATOR_SHORTNAME, ShortName); -} - -// -// Define Indexes and Styles ... -void DefineBuffers() -{ - // - // UP Zone ... - - // - // Draw Type ... - ENUM_DRAW_TYPE upZoneDrawType = showUpZone ? DRAW_COLOR_LINE : DRAW_NONE; - - // - // Buffer ... - SetIndexBuffer(upZoneBufferIndex, upZoneBuffer, INDICATOR_DATA); - PlotIndexSetInteger(upZoneBufferIndex, PLOT_SHOW_DATA, showUpZone); - PlotIndexSetInteger(upZoneBufferIndex, PLOT_DRAW_TYPE, upZoneDrawType); - - // - // Color Buffer ... - SetIndexBuffer(upZoneColorBufferIndex, upZoneColorBuffer, INDICATOR_COLOR_INDEX); - - // - // DOWN Zone ... - - // - // Draw Type ... - ENUM_DRAW_TYPE downZoneDrawType = showDownZone ? DRAW_COLOR_LINE : DRAW_NONE; - - // - // Buffer ... - SetIndexBuffer(downZoneBufferIndex, downZoneBuffer, INDICATOR_DATA); - PlotIndexSetInteger(downZoneBufferIndex - 1, PLOT_SHOW_DATA, showDownZone); - PlotIndexSetInteger(downZoneBufferIndex - 1, PLOT_DRAW_TYPE, downZoneDrawType); - - // - // Color Buffer ... - SetIndexBuffer(downZoneColorBufferIndex, downZoneColorBuffer, INDICATOR_COLOR_INDEX); -} - -// -// Calculate Buffers ... -void CalculateBuffers( - int bar_index, // Selected Bar Index - int ratesTotal, // Total Rates - double upPrice, // Up Price ... - double downPrice // Down Price ... -) -{ - // - double upValue = mUpZHull.Calculate( - upPrice, - bar_index, - ratesTotal); - upZoneBuffer[bar_index] = upValue; - double upColorIDX = (bar_index > 0) - ? (upZoneBuffer[bar_index] > upZoneBuffer[bar_index - 1]) - ? 1 - : (upZoneBuffer[bar_index] < upZoneBuffer[bar_index - 1]) - ? 2 - : upZoneColorBuffer[bar_index - 1] - : 0; - upZoneColorBuffer[bar_index] = upColorIDX; - - // - double downValue = mDownZHull.Calculate( - downPrice, - bar_index, - ratesTotal); - downZoneBuffer[bar_index] = downValue; - double downColorIDX = (bar_index > 0) - ? (downZoneBuffer[bar_index] > downZoneBuffer[bar_index - 1]) - ? 1 - : (downZoneBuffer[bar_index] < downZoneBuffer[bar_index - 1]) - ? 2 - : downZoneColorBuffer[bar_index - 1] - : 0; - downZoneColorBuffer[bar_index] = downColorIDX; -} - -// -// END Functions ... -// - -// -// TEMPLATE Function ... - -template -double getPrice(ENUM_APPLIED_PRICE tprice, T &open[], T &high[], T &low[], T &close[], int i) -{ - switch (tprice) - { - case PRICE_CLOSE: - return (close[i]); - case PRICE_OPEN: - return (open[i]); - case PRICE_HIGH: - return (high[i]); - case PRICE_LOW: - return (low[i]); - case PRICE_MEDIAN: - return ((high[i] + low[i]) / 2.0); - case PRICE_TYPICAL: - return ((high[i] + low[i] + close[i]) / 3.0); - case PRICE_WEIGHTED: - return ((high[i] + low[i] + close[i] + close[i]) / 4.0); - } - return (0); -} diff --git a/Documents/Pack/V1.0/Source/Indicators/x-saherelm.xich.mq5 b/Documents/Pack/V1.0/Source/Indicators/x-saherelm.xich.mq5 deleted file mode 100644 index 00bf6fbb..00000000 --- a/Documents/Pack/V1.0/Source/Indicators/x-saherelm.xich.mq5 +++ /dev/null @@ -1,846 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Indicator -// ------------------------------------------------- -// Name: XICH -// Description: Ichimoku Kinko Hyo ... -// -// -// 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 XICH Indicator" -#property strict - -// -// START Constants ... -// - -// -// Indicator Short Name ... -#define ShortName "XICH" - -// -// Ichimoku Golden Numbers ... -enum ENUM_X_ICHIMOKU_GOLDEN_NUMBERS -{ - X_ICH_BASE = 9, - X_ICH_GOLDEN = 17, - X_ICH_CYCLE = 26, - X_ICH_PERIOD = 35, - X_ICH_STAR = 45, - X_ICH_MED = 52, - X_ICH_LONG = 63, - X_ICH_FULL = 72 -}; - -// -// Ichimoku Lines Calculator Mode ... -enum ENUM_X_ICHIMOKU_CALCULATION_MODE -{ - // - X_XICH_HH_LL_MODE = 1, // Highest High and Lowest Low - X_XICH_HO_LC_MODE = 2, // Highest Open and Lowest Close -}; - -// -// END Constants ... -// - -// -// START Inputs ... -// - -// -// ICHIMOKU Kinko Hyo ... - -// -// TENKANSEN ... -input group "Tenkan Sen"; -input int tenkanSenLength = 9; // Length -input ENUM_X_ICHIMOKU_CALCULATION_MODE tenkanSenMode = X_XICH_HH_LL_MODE; // Calculation Mode - -// -// KIJUNSEN ... -input group "Kijun Sen"; -input int kijunSenLength = 26; // Length -input ENUM_X_ICHIMOKU_CALCULATION_MODE kijunSenMode = X_XICH_HH_LL_MODE; // Calculation Mode - -// -// SENKOUSPANB ... -input group "Senkou Span B"; -input int senkouSpanBLength = 52; // Length -input ENUM_X_ICHIMOKU_CALCULATION_MODE senkouSpanBMode = X_XICH_HH_LL_MODE; // Calculation Mode - -// -// CHIKOUSPAN ... -input group "Chikou Span"; -input ENUM_APPLIED_PRICE chikuoSpanAppliedTo = PRICE_CLOSE; // Price Type - -// -input group "Presentation"; -input bool showTenkanSen = true; // Show Tenkan Sen -input bool showKijunSen = true; // Show Kijun Sen -input bool showKijunSenPlus = false; // Show Kijun Sen + -input bool showKijunSenNegative = false; // Show Kijun Sen - -input bool showChikouSpan = true; // Show Chikou Span -input bool showSenkouSpanA = true; // Show Senkou Span A -input bool showSenkouSpanB = true; // Show Senkou Span B -input bool showKumo = true; // Show Kumo -input bool shiftKumo = true; // Shift Kumo to Future - -// -// END Inputs ... -// - -// -// START Includes and Imports ... -// - -// -// Includes Common Library ... -#include "../Libraries/x-saherelm.common.lib.mq5" - -// -// END Includes and Imports ... -// - -// -// START Buffers ... -// -#property indicator_chart_window - -// -#property indicator_buffers 15 -#property indicator_plots 8 - -// -// PLOTTED Buffers ... - -// -// ICHIMOKU ... - -// -// TENKANSEN ... - -// -#define tenkanSenBufferIndex 0 -double tenkanSenBuffer[]; - -// -#property indicator_label1 "XICH TK" -#property indicator_type1 DRAW_LINE -#property indicator_color1 clrBrown -#property indicator_style1 STYLE_SOLID -#property indicator_width1 1 - -// -// KIJUNSEN ... - -// -#define kijunSenBufferIndex 1 -double kijunSenBuffer[]; - -// -#property indicator_label2 "XICH KJ" -#property indicator_type2 DRAW_LINE -#property indicator_color2 clrDodgerBlue -#property indicator_style2 STYLE_SOLID -#property indicator_width2 1 - -// -#define kijunSenPlusBufferIndex 2 -double kijunSenPlusBuffer[]; - -// -#property indicator_label3 "XICH KJ+" -#property indicator_type3 DRAW_LINE -#property indicator_color3 clrMediumTurquoise -#property indicator_style3 STYLE_DOT -#property indicator_width3 1 - -// -#define kijunSenNegativeBufferIndex 3 -double kijunSenNegativeBuffer[]; - -// -#property indicator_label4 "XICH KJ-" -#property indicator_type4 DRAW_LINE -#property indicator_color4 clrDarkSeaGreen -#property indicator_style4 STYLE_DOT -#property indicator_width4 1 - -// -// CHIKOUSPAN ... - -// -#define chikouSpanBufferIndex 4 -double chikouSpanBuffer[]; - -// -#property indicator_label5 "XICH CS" -#property indicator_type5 DRAW_LINE -#property indicator_color5 clrDarkGreen -#property indicator_style5 STYLE_SOLID -#property indicator_width5 1 - -// -#define senkouABufferIndex 5 -double senkouABuffer[]; - -// -#property indicator_label6 "XICH SSA" -#property indicator_type6 DRAW_LINE -#property indicator_color6 clrLightGray -#property indicator_style6 STYLE_DASHDOTDOT -#property indicator_width6 1 - -// -#define senkouBBufferIndex 6 -double senkouBBuffer[]; - -// -#property indicator_label7 "XICH SSB" -#property indicator_type7 DRAW_LINE -#property indicator_color7 clrLightGray -#property indicator_style7 STYLE_DASHDOTDOT -#property indicator_width7 1 - -// -// KUMO ... - -// -// SENKOUSPANA ... - -// -#define senkouSpanABufferIndex 7 -double senkouSpanABuffer[]; - -// -// SENKOUSPANB ... - -// -#define senkouSpanBBufferIndex 8 -double senkouSpanBBuffer[]; - -// -// KUMOCLOUD ... - -// -#define kumoBufferIndex 7 - -// -#property indicator_label8 "XICH Kumo" -#property indicator_type8 DRAW_FILLING -#property indicator_color8 clrAqua, clrMagenta -#property indicator_style8 STYLE_SOLID -#property indicator_width8 1 - -// -// DATA Buffers ... - -// -#define dTenkanBufferIndex 9 -double dTenkanBuffer[]; - -// -#define dKijunBufferIndex 10 -double dKijunBuffer[]; - -// -#define dChikouBufferIndex 11 -double dChikouBuffer[]; - -// -#define dSSABufferIndex 12 -double dSSABuffer[]; - -// -#define dSSBBufferIndex 13 -double dSSBBuffer[]; - -// -// END Buffers ... -// - -// -// START Global Definitions: Variables, Properties and etc ... -// - -// -int maxLength; -int mHandler; - -// -ENUM_SERIESMODE mTenkanSenTopMode = NULL; -ENUM_SERIESMODE mTenkanSenBottomMode = NULL; - -// -ENUM_SERIESMODE mKijunSenTopMode = NULL; -ENUM_SERIESMODE mKijunSenBottomMode = NULL; - -// -ENUM_SERIESMODE mSenkouSpanBTopMode = NULL; -ENUM_SERIESMODE mSenkouSpanBBottomMode = NULL; - -// -// END Global Definitions: Variables, Properties and etc ... -// - -// -// START Event Handlers ... -// - -// -// Initialization ... -int OnInit() -{ - // - // Validate Inputs ... - if (!ValidateInputs()) - { - return INIT_PARAMETERS_INCORRECT; - } - - // - // because in some cases we may have more than one input for - // calculation and we must prevent any calculation - // untill we pass the biggest input length, here we get max Input length - // and then wait until pass it ... - maxLength = ExtractMaxLengthOfInputs(); - - // - // Define Index Buffers ... - DefineBuffers(); - - // - // Init Handler ... - mHandler = iIchimoku( - _Symbol, - _Period, - tenkanSenLength, - kijunSenLength, - senkouSpanBLength); - if (mHandler == INVALID_HANDLE) - { - 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 - - // - IndicatorRelease(mHandler); -} - -// -// 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 ichCalculatedBars = BarsCalculated(mHandler); - if (ichCalculatedBars < maxLength) - { - return prev_calculated; - } - - // - limit = (prev_calculated > rates_total || prev_calculated <= 0) ? rates_total : (rates_total - prev_calculated) + 1; - - // - // Buffers Copy ... - int copiedTenkans = CopyBuffer(mHandler, TENKANSEN_LINE, 0, limit, dTenkanBuffer); - int copiedKijuns = CopyBuffer(mHandler, KIJUNSEN_LINE, 0, limit, dKijunBuffer); - int copiedChikous = CopyBuffer(mHandler, CHIKOUSPAN_LINE, 0, limit, dChikouBuffer); - int copiedSSAs = CopyBuffer(mHandler, SENKOUSPANA_LINE, 0, limit, dSSABuffer); - int copiedSSBs = CopyBuffer(mHandler, SENKOUSPANB_LINE, 0, limit, dSSBBuffer); - if ( - copiedSSAs < 0 || - copiedSSBs < 0 || - copiedKijuns < 0 || - copiedTenkans < 0 || - copiedChikous < 0) - { - return prev_calculated; - } - - // - // Main Loop ... - for (int i = limit - 1; i >= 0 && !IsStopped(); i--) - { - CalculateBuffers(i); - } - - // - return rates_total; -} - -// -// END Event Handlers ... -// - -// -// START Functions ... -// - -// -// Validate Input Args for Initialization ... -bool ValidateInputs() -{ - // - bool result = - // - (tenkanSenLength > 2 && - kijunSenLength > tenkanSenLength && - senkouSpanBLength > kijunSenLength) - // - ; - - // - return result; -} - -// -// Retrieve all Exists Input Max Length ... -// use for Start Of Drawing ... -int ExtractMaxLengthOfInputs() -{ - // - int result = 0; - - // - // Ichimoku ... - result = MathMax(result, tenkanSenLength); - result = MathMax(result, kijunSenLength); - result = MathMax(result, senkouSpanBLength); - - // - return result; -} - -// -// Define Indexes and Styles ... -void DefineBuffers() -{ - // - // ICHIMOKU ... - - // - // TENKANSEN ... - - // - ENUM_DRAW_TYPE tenkanSenDrawType = showTenkanSen ? DRAW_LINE : DRAW_NONE; - - // - ArraySetAsSeries(tenkanSenBuffer, true); - SetIndexBuffer(tenkanSenBufferIndex, tenkanSenBuffer, INDICATOR_DATA); - PlotIndexSetInteger(tenkanSenBufferIndex, PLOT_DRAW_BEGIN, maxLength); - PlotIndexSetInteger(tenkanSenBufferIndex, PLOT_SHOW_DATA, showTenkanSen); - PlotIndexSetInteger(tenkanSenBufferIndex, PLOT_DRAW_TYPE, tenkanSenDrawType); - - // - // KIJUNSEN ... - - // - ENUM_DRAW_TYPE kijunSenDrawType = showKijunSen ? DRAW_LINE : DRAW_NONE; - - // - ArraySetAsSeries(kijunSenBuffer, true); - SetIndexBuffer(kijunSenBufferIndex, kijunSenBuffer, INDICATOR_DATA); - PlotIndexSetInteger(kijunSenBufferIndex, PLOT_DRAW_BEGIN, maxLength); - PlotIndexSetInteger(kijunSenBufferIndex, PLOT_SHOW_DATA, showKijunSen); - PlotIndexSetInteger(kijunSenBufferIndex, PLOT_DRAW_TYPE, kijunSenDrawType); - - // - // KIJUNSEN Plus ... - - // - ENUM_DRAW_TYPE kijunSenPlusDrawType = showKijunSenPlus ? DRAW_LINE : DRAW_NONE; - - // - ArraySetAsSeries(kijunSenPlusBuffer, true); - SetIndexBuffer(kijunSenPlusBufferIndex, kijunSenPlusBuffer, INDICATOR_DATA); - PlotIndexSetInteger(kijunSenPlusBufferIndex, PLOT_DRAW_BEGIN, maxLength); - PlotIndexSetInteger(kijunSenPlusBufferIndex, PLOT_SHIFT, kijunSenLength); - PlotIndexSetInteger(kijunSenPlusBufferIndex, PLOT_SHOW_DATA, false); - PlotIndexSetInteger(kijunSenPlusBufferIndex, PLOT_DRAW_TYPE, kijunSenPlusDrawType); - - // - // KIJUNSEN Negative ... - - // - ENUM_DRAW_TYPE kijunSenNegativeDrawType = showKijunSenNegative ? DRAW_LINE : DRAW_NONE; - - // - ArraySetAsSeries(kijunSenNegativeBuffer, true); - SetIndexBuffer(kijunSenNegativeBufferIndex, kijunSenNegativeBuffer, INDICATOR_DATA); - PlotIndexSetInteger(kijunSenNegativeBufferIndex, PLOT_DRAW_BEGIN, maxLength); - PlotIndexSetInteger(kijunSenNegativeBufferIndex, PLOT_SHIFT, -kijunSenLength); - PlotIndexSetInteger(kijunSenNegativeBufferIndex, PLOT_SHOW_DATA, false); - PlotIndexSetInteger(kijunSenNegativeBufferIndex, PLOT_DRAW_TYPE, kijunSenNegativeDrawType); - - // - // CHIKOUSPAN ... - - // - ENUM_DRAW_TYPE chikouSpanDrawType = showChikouSpan ? DRAW_LINE : DRAW_NONE; - - // - ArraySetAsSeries(chikouSpanBuffer, true); - SetIndexBuffer(chikouSpanBufferIndex, chikouSpanBuffer, INDICATOR_DATA); - PlotIndexSetInteger(chikouSpanBufferIndex, PLOT_DRAW_BEGIN, maxLength); - PlotIndexSetInteger(chikouSpanBufferIndex, PLOT_SHIFT, -kijunSenLength); - PlotIndexSetInteger(chikouSpanBufferIndex, PLOT_SHOW_DATA, showChikouSpan); - PlotIndexSetInteger(chikouSpanBufferIndex, PLOT_DRAW_TYPE, chikouSpanDrawType); - - // - // SENKOUSPAN A and B ... - int shiftSize = shiftKumo ? kijunSenLength : 0; - - // - // SENKOUSPANA ... - ENUM_DRAW_TYPE senkouSpanADrawType = showSenkouSpanA ? DRAW_LINE : DRAW_NONE; - ArraySetAsSeries(senkouABuffer, true); - SetIndexBuffer(senkouABufferIndex, senkouABuffer, INDICATOR_DATA); - PlotIndexSetInteger(senkouABufferIndex, PLOT_SHIFT, shiftSize); - PlotIndexSetInteger(senkouABufferIndex, PLOT_SHOW_DATA, showSenkouSpanA); - PlotIndexSetInteger(senkouABufferIndex, PLOT_DRAW_TYPE, senkouSpanADrawType); - - // - // SENKOUSPANB ... - ENUM_DRAW_TYPE senkouSpanBDrawType = showSenkouSpanB ? DRAW_LINE : DRAW_NONE; - ArraySetAsSeries(senkouBBuffer, true); - SetIndexBuffer(senkouBBufferIndex, senkouBBuffer, INDICATOR_DATA); - PlotIndexSetInteger(senkouBBufferIndex, PLOT_SHIFT, shiftSize); - PlotIndexSetInteger(senkouBBufferIndex, PLOT_SHOW_DATA, showSenkouSpanB); - PlotIndexSetInteger(senkouBBufferIndex, PLOT_DRAW_TYPE, senkouSpanBDrawType); - - // - // KUMO ... - - // - // SENKOUSPANA ... - ArraySetAsSeries(senkouSpanABuffer, true); - SetIndexBuffer(senkouSpanABufferIndex, senkouSpanABuffer, INDICATOR_DATA); - PlotIndexSetInteger(senkouSpanABufferIndex, PLOT_DRAW_BEGIN, maxLength); - - // - // SENKOUSPANB ... - ArraySetAsSeries(senkouSpanBBuffer, true); - SetIndexBuffer(senkouSpanBBufferIndex, senkouSpanBBuffer, INDICATOR_DATA); - PlotIndexSetInteger(senkouSpanBBufferIndex, PLOT_DRAW_BEGIN, maxLength); - - // - // KUMO ... - - // - ENUM_DRAW_TYPE kumoDrawType = showKumo ? DRAW_FILLING : DRAW_NONE; - - // - PlotIndexSetInteger(kumoBufferIndex, PLOT_SHIFT, shiftSize); - PlotIndexSetInteger(kumoBufferIndex, PLOT_SHOW_DATA, false); - PlotIndexSetInteger(kumoBufferIndex, PLOT_DRAW_TYPE, kumoDrawType); - - // - // DATA Buffers ... - - // - // D Tenkan ... - ArraySetAsSeries(dTenkanBuffer, true); - SetIndexBuffer(dTenkanBufferIndex, dTenkanBuffer, INDICATOR_CALCULATIONS); - - // - // D Kijun ... - ArraySetAsSeries(dKijunBuffer, true); - SetIndexBuffer(dKijunBufferIndex, dKijunBuffer, INDICATOR_CALCULATIONS); - - // - // D Chikou ... - ArraySetAsSeries(dChikouBuffer, true); - SetIndexBuffer(dChikouBufferIndex, dChikouBuffer, INDICATOR_CALCULATIONS); - - // - // D SSA ... - ArraySetAsSeries(dSSABuffer, true); - SetIndexBuffer(dSSABufferIndex, dSSABuffer, INDICATOR_CALCULATIONS); - - // - // D SSB ... - ArraySetAsSeries(dSSBBuffer, true); - SetIndexBuffer(dSSBBufferIndex, dSSBBuffer, INDICATOR_CALCULATIONS); -} - -// -// Set Indicator Short Name and also we can define Buffers Labels ... -void SetIndicatorName() -{ - IndicatorSetString(INDICATOR_SHORTNAME, ShortName); -} - -// -// Calculate Buffers ... -void CalculateBuffers( - int bar_index // Selected Bar Index -) -{ - // - // ICHIMOKU ... - - // - double topValue; - double bottomValue; - - // - // TENKANSEN ... - - // - // Extract Tenkan Sen Top/Bottom Calculation Mode based on User Input ... - if (mTenkanSenTopMode == NULL || mTenkanSenBottomMode == NULL) - { - // - switch (tenkanSenMode) - { - // - case X_XICH_HH_LL_MODE: - // - mTenkanSenTopMode = MODE_HIGH; - mTenkanSenBottomMode = MODE_LOW; - break; - - // - case X_XICH_HO_LC_MODE: - // - mTenkanSenTopMode = MODE_OPEN; - mTenkanSenBottomMode = MODE_CLOSE; - break; - } - } - - // - XOHCL bar; - bar.Init( - _Symbol, - _Period, - bar_index - // - ); - - // - // Calculate Top ... - topValue = bar - .FindHighest( - tenkanSenLength, - mTenkanSenTopMode - // - ); - - // - // Calculate Bottom ... - bottomValue = bar - .FindLowest( - tenkanSenLength, - mTenkanSenBottomMode - // - ); - - // - double tenkanSenValue = (topValue + bottomValue) / 2; - tenkanSenBuffer[bar_index] = tenkanSenValue; - - // - // KIJUNSEN ... - - // - // Extract Kijun Sen Top/Bottom Calculation Mode based on User Input ... - if (mKijunSenTopMode == NULL || mKijunSenBottomMode == NULL) - { - // - switch (kijunSenMode) - { - // - case X_XICH_HH_LL_MODE: - // - mKijunSenTopMode = MODE_HIGH; - mKijunSenBottomMode = MODE_LOW; - break; - - // - case X_XICH_HO_LC_MODE: - // - mKijunSenTopMode = MODE_OPEN; - mKijunSenBottomMode = MODE_CLOSE; - break; - } - } - - // - // Calculate Top ... - topValue = bar - .FindHighest( - kijunSenLength, - mKijunSenTopMode - // - ); - - // - // Calculate Bottom ... - bottomValue = bar - .FindLowest( - kijunSenLength, - mKijunSenBottomMode - // - ); - - // - double kijunSenValue = (topValue + bottomValue) / 2; - kijunSenBuffer[bar_index] = kijunSenValue; - - // - kijunSenPlusBuffer[bar_index] = kijunSenValue; - kijunSenNegativeBuffer[bar_index] = kijunSenValue; - - // - // CHIKOUSPAN ... - double chikouSpanValue = bar - .GetPrice(chikuoSpanAppliedTo); - - // - chikouSpanBuffer[bar_index] = chikouSpanValue; - - // - // KUMO ... - - // - // SENKOUSPANA ... - double senkouSpanAValue = (tenkanSenValue + kijunSenValue) / 2; - senkouABuffer[bar_index] = senkouSpanAValue; - senkouSpanABuffer[bar_index] = senkouSpanAValue; - - // - // SENKOUSPANB ... - - // - // Extract Senkou Span B Top/Bottom Calculation Mode based on User Input ... - if (mSenkouSpanBTopMode == NULL || mSenkouSpanBBottomMode == NULL) - { - // - switch (senkouSpanBMode) - { - // - case X_XICH_HH_LL_MODE: - // - mSenkouSpanBTopMode = MODE_HIGH; - mSenkouSpanBBottomMode = MODE_LOW; - break; - - // - case X_XICH_HO_LC_MODE: - // - mSenkouSpanBTopMode = MODE_OPEN; - mSenkouSpanBBottomMode = MODE_CLOSE; - break; - } - } - - // - // Calculate Top ... - topValue = bar - .FindHighest( - senkouSpanBLength, - mSenkouSpanBTopMode - // - ); - - // - // Calculate Bottom ... - bottomValue = bar - .FindLowest( - senkouSpanBLength, - mSenkouSpanBBottomMode - // - ); - - // - double senkouSpanBValue = (topValue + bottomValue) / 2; - senkouBBuffer[bar_index] = senkouSpanBValue; - senkouSpanBBuffer[bar_index] = senkouSpanBValue; -} - -// -// END Functions ... -// diff --git a/Documents/Pack/V1.0/Source/Indicators/x-saherelm.xmc.mq5 b/Documents/Pack/V1.0/Source/Indicators/x-saherelm.xmc.mq5 deleted file mode 100644 index bd40a26b..00000000 --- a/Documents/Pack/V1.0/Source/Indicators/x-saherelm.xmc.mq5 +++ /dev/null @@ -1,483 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 XMC MA Cross Indicator -// --------------------------------------------------- -// Name: XMC -// Description: Moving Average Crosses -// 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 XMC Indicator" -#property strict - -// -// START Constants ... -// - -// -// Indicator Short Name ... -#define ShortName "XMC" - -// -// END Constants ... -// - -// -// START Inputs ... -// - -// -input group "Fast"; -input int fastMaLength = 21; // Length -input int fastMaShift = 0; // Shift -input ENUM_MA_METHOD fastMaMethod = MODE_EMA; // Method -input ENUM_APPLIED_PRICE fastMaAppliedTo = PRICE_CLOSE; // Applied To - -// -input group "Slow"; -input int slowMaLength = 50; // Length -input int slowMaShift = 0; // Shift -input ENUM_MA_METHOD slowMaMethod = MODE_EMA; // Method -input ENUM_APPLIED_PRICE slowMaAppliedTo = PRICE_CLOSE; // Applied To - -// -input group "Verifier"; -input int verifierMaLength = 200; // Length -input int verifierMaShift = 0; // Shift -input ENUM_MA_METHOD verifierMaMethod = MODE_EMA; // Method -input ENUM_APPLIED_PRICE verifierMaAppliedTo = PRICE_CLOSE; // Applied To - -// -input group "PSar"; -input double sarStep = 0.02; // Step -input double sarMaximum = 0.2; // Maximum - -// -input group "Presentation"; -input bool showSar = true; // Show Sar -input bool showFastMa = true; // Show Fast -input bool showSlowMa = true; // Show Slow -input bool showVerifierMa = true; // Show Verifier - -// -// END Inputs ... -// - -// -// START Includes and Imports ... -// - -// -// Includes Common Library ... -#include "../Libraries/x-saherelm.common.lib.mq5" - -// -// END Includes and Imports ... -// - -// -// START Buffers ... -// -#property indicator_chart_window - -// -#property indicator_buffers 4 -#property indicator_plots 4 - -// -// PLOTTED Buffers ... - -// -// MA ... - -// -// FAST ... -#define fastMaBufferIndex 0 -double fastMaBuffer[]; - -// -#property indicator_label1 "XMC MA F" -#property indicator_type1 DRAW_LINE -#property indicator_color1 clrYellow -#property indicator_style1 STYLE_SOLID -#property indicator_width1 1 - -// -// SLOW ... -#define slowMaBufferIndex 1 -double slowMaBuffer[]; - -// -#property indicator_label2 "XMC MA S" -#property indicator_type2 DRAW_LINE -#property indicator_color2 clrDarkOrange -#property indicator_style2 STYLE_SOLID -#property indicator_width2 1 - -// -// VERIFIER ... -#define verifierMaBufferIndex 2 -double verifierMaBuffer[]; - -// -#property indicator_label3 "XMC MA V" -#property indicator_type3 DRAW_LINE -#property indicator_color3 clrDarkBlue -#property indicator_style3 STYLE_SOLID -#property indicator_width3 2 - -// -// SAR ... -#define sarBufferIndex 3 -double sarBuffer[]; - -// -#property indicator_label4 "XMC SAR" -#property indicator_type4 DRAW_ARROW -#property indicator_color4 clrDarkGreen -#property indicator_width4 2 - -// -// END Buffers ... -// - -// -// START Global Definitions: Variables, Properties and etc ... -// - -// -int maxLength; - -// -int sarHandler = INVALID_HANDLE; -int fastMaHandler = INVALID_HANDLE; -int slowMaHandler = INVALID_HANDLE; -int verifierMaHandler = INVALID_HANDLE; - -// -// END Global Definitions: Variables, Properties and etc ... -// - -// -// START Event Handlers ... -// - -// -// Initialization ... -int OnInit() -{ - // - // Validate Inputs ... - if (!ValidateInputs()) - { - return INIT_PARAMETERS_INCORRECT; - } - - // - // because in some cases we may have more than one input for - // calculation and we must prevent any calculation - // untill we pass the biggest input length, here we get max Input length - // and then wait until pass it ... - maxLength = ExtractMaxLengthOfInputs(); - - // - // Define Index Buffers ... - DefineBuffers(); - - // - // Set Indicator ShortName ... - SetIndicatorName(); - - // - // SAR Initializer ... - sarHandler = iSAR( - _Symbol, - _Period, - sarStep, - sarMaximum // - ); - if (sarHandler == INVALID_HANDLE) - { - return INIT_FAILED; - } - - // - // MA Initialization ... - - // - // FAST ... - fastMaHandler = iMA( - _Symbol, - _Period, - fastMaLength, - fastMaShift, - fastMaMethod, - fastMaAppliedTo); - if (fastMaHandler == INVALID_HANDLE) - { - return INIT_FAILED; - } - - // - // SLOW ... - slowMaHandler = iMA( - _Symbol, - _Period, - slowMaLength, - slowMaShift, - slowMaMethod, - slowMaAppliedTo); - if (slowMaHandler == INVALID_HANDLE) - { - return INIT_FAILED; - } - - // - // VERIFIER ... - verifierMaHandler = iMA( - _Symbol, - _Period, - verifierMaLength, - verifierMaShift, - verifierMaMethod, - verifierMaAppliedTo); - if (verifierMaHandler == INVALID_HANDLE) - { - return INIT_FAILED; - } - - // - // Init Succeed ... - return INIT_SUCCEEDED; -} - -// -// DeInitialization ... -void OnDeinit(const int reason) -{ - // - // REASON_PROGRAM 0 The EA has stopped working calling the ExpertRemove() function - // REASON_REMOVE 1 Program removed from a chart - // REASON_RECOMPILE 2 Program recompiled - // REASON_CHARTCHANGE 3 A symbol or a chart period is changed - // REASON_CHARTCLOSE 4 Chart closed - // REASON_PARAMETERS 5 Inputs changed by a user - // REASON_ACCOUNT 6 Another account has been activated or reconnection to the trade server has occurred due to changes in the account settings - // REASON_TEMPLATE 7 Another chart template applied - // REASON_INITFAILED 8 The OnInit() handler returned a non-zero value - // REASON_CLOSE 9 Terminal closed - - // - // Here we can handle De Initialization Reasons ... - IndicatorRelease(sarHandler); - IndicatorRelease(fastMaHandler); - IndicatorRelease(slowMaHandler); - IndicatorRelease(verifierMaHandler); -} - -// -// Calculations ... -// -// Calculating what we want ... -int OnCalculate( - const int rates_total, // Total Bars on Chart ... - const int prev_calculated, // Total Calculated Bars on Charts ... - const datetime &time[], // History of Open Time ... - const double &open[], // History of Open Price ... - const double &high[], // History of High Price ... - const double &low[], // History of Low Price ... - const double &close[], // History of Close Price ... - const long &tick_volume[], // History of Tick Volumes on Bar ... - const long &volume[], // History of Trade Volumes ... - const int &spread[] // History of Spread Price ... -) -{ - // - // 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 fastMaCalculatedBars = BarsCalculated(fastMaHandler); - int slowMaCalculatedBars = BarsCalculated(slowMaHandler); - int verifierMaCalculatedBars = BarsCalculated(verifierMaHandler); - if (sarCalculatedBars < maxLength || - fastMaCalculatedBars < maxLength || - slowMaCalculatedBars < maxLength || - verifierMaCalculatedBars < 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 copiedFastMas = CopyBuffer(fastMaHandler, 0, 0, limit, fastMaBuffer); - int copiedSlowMas = CopyBuffer(slowMaHandler, 0, 0, limit, slowMaBuffer); - int copiedVerifierMas = CopyBuffer(verifierMaHandler, 0, 0, limit, verifierMaBuffer); - if (copiedSars <= 0 || - copiedFastMas <= 0 || - copiedSlowMas <= 0 || - copiedVerifierMas <= 0) - { - return prev_calculated; - } - - // - // Main Loop ... - for (int i = limit - 1; i >= 0 && !IsStopped(); i--) - { - CalculateBuffers(i); - } - - // - return rates_total; -} - -// -// END Event Handlers ... -// - -// -// START Functions ... -// - -// -// Validate Input Args for Initialization ... -bool ValidateInputs() -{ - // - bool result = - // - // Validate Ma ... - (fastMaLength > 2 && - slowMaLength > fastMaLength && - verifierMaLength > slowMaLength) - // - && - // - (sarStep > 0 && - sarMaximum > sarStep) - // - ; - - // - return result; -} - -// -// Retrieve all Exists Input Max Length ... -// use for Start Of Drawing ... -int ExtractMaxLengthOfInputs() -{ - // - int result = 0; - - // - // Ma ... - result = MathMax(result, fastMaLength); - result = MathMax(result, slowMaLength); - result = MathMax(result, verifierMaLength); - - // - return result; -} - -// -// Define Indexes and Styles ... -void DefineBuffers() -{ - // - // SAR ... - ENUM_DRAW_TYPE sarDrawType = showSar ? DRAW_ARROW : DRAW_NONE; - - // - // PEAKS ... - ArraySetAsSeries(sarBuffer, true); - SetIndexBuffer(sarBufferIndex, sarBuffer, INDICATOR_DATA); - PlotIndexSetInteger(sarBufferIndex, PLOT_ARROW, 225); - PlotIndexSetDouble(sarBufferIndex, PLOT_EMPTY_VALUE, 0); - - // - PlotIndexSetInteger(sarBufferIndex, PLOT_SHOW_DATA, showSar); - PlotIndexSetInteger(sarBufferIndex, PLOT_DRAW_TYPE, sarDrawType); - - // - // MA ... - - // - // FAST ... - ENUM_DRAW_TYPE fastMaDrawType = showFastMa ? DRAW_LINE : DRAW_NONE; - ArraySetAsSeries(fastMaBuffer, true); - SetIndexBuffer(fastMaBufferIndex, fastMaBuffer, INDICATOR_DATA); - PlotIndexSetInteger(fastMaBufferIndex, PLOT_DRAW_BEGIN, maxLength); - PlotIndexSetInteger(fastMaBufferIndex, PLOT_SHOW_DATA, showFastMa); - PlotIndexSetInteger(fastMaBufferIndex, PLOT_DRAW_TYPE, fastMaDrawType); - - // - // SLOW ... - ENUM_DRAW_TYPE slowMaDrawType = showSlowMa ? DRAW_LINE : DRAW_NONE; - ArraySetAsSeries(slowMaBuffer, true); - SetIndexBuffer(slowMaBufferIndex, slowMaBuffer, INDICATOR_DATA); - PlotIndexSetInteger(slowMaBufferIndex, PLOT_DRAW_BEGIN, maxLength); - PlotIndexSetInteger(slowMaBufferIndex, PLOT_SHOW_DATA, showSlowMa); - PlotIndexSetInteger(slowMaBufferIndex, PLOT_DRAW_TYPE, slowMaDrawType); - - // - // VERIFIER ... - ENUM_DRAW_TYPE verifierMaDrawType = showVerifierMa ? DRAW_LINE : DRAW_NONE; - ArraySetAsSeries(verifierMaBuffer, true); - SetIndexBuffer(verifierMaBufferIndex, verifierMaBuffer, INDICATOR_DATA); - PlotIndexSetInteger(verifierMaBufferIndex, PLOT_DRAW_BEGIN, maxLength); - PlotIndexSetInteger(verifierMaBufferIndex, PLOT_SHOW_DATA, showVerifierMa); - PlotIndexSetInteger(verifierMaBufferIndex, PLOT_DRAW_TYPE, verifierMaDrawType); -} - -// -// 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 -) -{ -} - -// -// END Functions ... -// diff --git a/Documents/Pack/V1.0/Source/Indicators/x-saherelm.xmrb.mq5 b/Documents/Pack/V1.0/Source/Indicators/x-saherelm.xmrb.mq5 deleted file mode 100644 index 5ff1d82a..00000000 --- a/Documents/Pack/V1.0/Source/Indicators/x-saherelm.xmrb.mq5 +++ /dev/null @@ -1,855 +0,0 @@ -////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Indicator -// -------------------------------------- -// Name: XMRB -// Description: Moving Average Ribbon -// -// -// 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 XMRB Indicator" -#property strict - -// -// START Constants ... -// - -// -// Indicator Short Name ... -#define ShortName "XMRB" - -// -// END Constants ... -// - -// -// START Inputs ... -// - -// -input group "Ribbon 1"; -input int fast1Length = 20; // Fast -input int slow1Length = 50; // Slow -input ENUM_APPLIED_PRICE r1AppliedTo = PRICE_HIGH; // Applied To - -// -input group "Ribbon 2"; -input int fast2Length = 20; // Fast -input int slow2Length = 50; // Slow -input ENUM_APPLIED_PRICE r2AppliedTo = PRICE_OPEN; // Applied To - -// -input group "Ribbon 3"; -input int fast3Length = 20; // Fast -input int slow3Length = 50; // Slow -input ENUM_APPLIED_PRICE r3AppliedTo = PRICE_CLOSE; // Applied To - -// -input group "Ribbon 4"; -input int fast4Length = 20; // Fast -input int slow4Length = 50; // Slow -input ENUM_APPLIED_PRICE r4AppliedTo = PRICE_MEDIAN; // Applied To - -// -input group "Ribbon 5"; -input int fast5Length = 20; // Fast -input int slow5Length = 50; // Slow -input ENUM_APPLIED_PRICE r5AppliedTo = PRICE_TYPICAL; // Applied To - -// -input group "Ribbon 6"; -input int fast6Length = 20; // Fast -input int slow6Length = 50; // Slow -input ENUM_APPLIED_PRICE r6AppliedTo = PRICE_LOW; // Applied To - -// -input group "Calculation"; -input ENUM_MA_METHOD ribbonMode = MODE_EMA; // Mode - -// -input group "Presentation"; -input bool showFastMa = true; // Show Fast -input bool showSlowMa = true; // Show Slow -input bool showRibbon = false; // Show Ribbon - -// -// END Inputs ... -// - -// -// START Includes and Imports ... -// - -// -// Includes Common Library ... -#include "../Libraries/x-saherelm.common.lib.mq5" - -// -// END Includes and Imports ... -// - -// -// START Buffers ... -// -#property indicator_chart_window - -// -#property indicator_buffers 14 -#property indicator_plots 14 - -// -// PLOTTED Buffers ... - -// -// MA ... - -// -// FAST ... -#define fastMaBufferIndex 0 -double fastMaBuffer[]; - -// -#property indicator_label1 "XMRB F" -#property indicator_type1 DRAW_LINE -#property indicator_color1 clrLime -#property indicator_style1 STYLE_SOLID -#property indicator_width1 1 - -// -// SLOW ... -#define slowMaBufferIndex 1 -double slowMaBuffer[]; - -// -#property indicator_label2 "XMRB S" -#property indicator_type2 DRAW_LINE -#property indicator_color2 clrRed -#property indicator_style2 STYLE_SOLID -#property indicator_width2 1 - -// -// DATA Buffers ... - -// -// FAST ... - -// -#define fast1BufferIndex 2 -double fast1Buffer[]; - -// -#property indicator_label3 "XMRB 1 F" -#property indicator_type3 DRAW_LINE -#property indicator_color3 clrAquamarine -#property indicator_style3 STYLE_DOT -#property indicator_width3 1 - -// -#define fast2BufferIndex 3 -double fast2Buffer[]; - -// -#property indicator_label4 "XMRB 2 F" -#property indicator_type4 DRAW_LINE -#property indicator_color4 clrAquamarine -#property indicator_style4 STYLE_DOT -#property indicator_width4 1 - -// -#define fast3BufferIndex 4 -double fast3Buffer[]; - -// -#property indicator_label5 "XMRB 3 F" -#property indicator_type5 DRAW_LINE -#property indicator_color5 clrAquamarine -#property indicator_style5 STYLE_DOT -#property indicator_width5 1 - -// -#define fast4BufferIndex 5 -double fast4Buffer[]; - -// -#property indicator_label6 "XMRB 4 F" -#property indicator_type6 DRAW_LINE -#property indicator_color6 clrAquamarine -#property indicator_style6 STYLE_DOT -#property indicator_width6 1 - -// -#define fast5BufferIndex 6 -double fast5Buffer[]; - -// -#property indicator_label7 "XMRB 5 F" -#property indicator_type7 DRAW_LINE -#property indicator_color7 clrAquamarine -#property indicator_style7 STYLE_DOT -#property indicator_width7 1 - -// -#define fast6BufferIndex 7 -double fast6Buffer[]; - -// -#property indicator_label8 "XMRB 6 F" -#property indicator_type8 DRAW_LINE -#property indicator_color8 clrAquamarine -#property indicator_style8 STYLE_DOT -#property indicator_width8 1 - -// -// SLOW ... - -// -#define slow1BufferIndex 8 -double slow1Buffer[]; - -// -#property indicator_label9 "XMRB 1 S" -#property indicator_type9 DRAW_LINE -#property indicator_color9 clrPlum -#property indicator_style9 STYLE_DOT -#property indicator_width9 1 - -// -#define slow2BufferIndex 9 -double slow2Buffer[]; - -// -#property indicator_label10 "XMRB 2 S" -#property indicator_type10 DRAW_LINE -#property indicator_color10 clrPlum -#property indicator_style10 STYLE_DOT -#property indicator_width10 1 - -// -#define slow3BufferIndex 10 -double slow3Buffer[]; - -// -#property indicator_label11 "XMRB 3 S" -#property indicator_type11 DRAW_LINE -#property indicator_color11 clrPlum -#property indicator_style11 STYLE_DOT -#property indicator_width11 1 - -// -#define slow4BufferIndex 11 -double slow4Buffer[]; - -// -#property indicator_label12 "XMRB 4 S" -#property indicator_type12 DRAW_LINE -#property indicator_color12 clrPlum -#property indicator_style12 STYLE_DOT -#property indicator_width12 1 - -// -#define slow5BufferIndex 12 -double slow5Buffer[]; - -// -#property indicator_label13 "XMRB 5 S" -#property indicator_type13 DRAW_LINE -#property indicator_color13 clrPlum -#property indicator_style13 STYLE_DOT -#property indicator_width13 1 - -// -#define slow6BufferIndex 13 -double slow6Buffer[]; - -// -#property indicator_label14 "XMRB 6 S" -#property indicator_type14 DRAW_LINE -#property indicator_color14 clrPlum -#property indicator_style14 STYLE_DOT -#property indicator_width14 1 - -// -// END Buffers ... -// - -// -// START Global Definitions: Variables, Properties and etc ... -// - -// -int maxLength; - -// -int fast1MaHandler = INVALID_HANDLE; -int fast2MaHandler = INVALID_HANDLE; -int fast3MaHandler = INVALID_HANDLE; -int fast4MaHandler = INVALID_HANDLE; -int fast5MaHandler = INVALID_HANDLE; -int fast6MaHandler = INVALID_HANDLE; - -// -int slow1MaHandler = INVALID_HANDLE; -int slow2MaHandler = INVALID_HANDLE; -int slow3MaHandler = INVALID_HANDLE; -int slow4MaHandler = INVALID_HANDLE; -int slow5MaHandler = INVALID_HANDLE; -int slow6MaHandler = INVALID_HANDLE; - -// -// END Global Definitions: Variables, Properties and etc ... -// - -// -// START Event Handlers ... -// - -// -// Initialization ... -int OnInit() -{ - // - // Validate Inputs ... - if (!ValidateInputs()) - { - return INIT_PARAMETERS_INCORRECT; - } - - // - // because in some cases we may have more than one input for - // calculation and we must prevent any calculation - // untill we pass the biggest input length, here we get max Input length - // and then wait until pass it ... - maxLength = ExtractMaxLengthOfInputs(); - - // - // Define Index Buffers ... - DefineBuffers(); - - // - // Set Indicator ShortName ... - SetIndicatorName(); - - // - // Initialize MAs ... - if (!InitializeMas()) - { - return INIT_PARAMETERS_INCORRECT; - } - - // - // 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(fast1MaHandler); - IndicatorRelease(fast2MaHandler); - IndicatorRelease(fast3MaHandler); - IndicatorRelease(fast4MaHandler); - IndicatorRelease(fast5MaHandler); - IndicatorRelease(fast6MaHandler); - - // - IndicatorRelease(slow1MaHandler); - IndicatorRelease(slow2MaHandler); - IndicatorRelease(slow3MaHandler); - IndicatorRelease(slow4MaHandler); - IndicatorRelease(slow5MaHandler); - IndicatorRelease(slow6MaHandler); -} - -// -// Calculating what we want ... -int OnCalculate( - const int rates_total, // Total Bars on Chart ... - const int prev_calculated, // Total Calculated Bars on Charts ... - const datetime &time[], // History of Open Time ... - const double &open[], // History of Open Price ... - const double &high[], // History of High Price ... - const double &low[], // History of Low Price ... - const double &close[], // History of Close Price ... - const long &tick_volume[], // History of Tick Volumes on Bar ... - const long &volume[], // History of Trade Volumes ... - const int &spread[] // History of Spread Price ... -) -{ - // - // 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 fast1MaCalculatedBars = BarsCalculated(fast1MaHandler); - int fast2MaCalculatedBars = BarsCalculated(fast2MaHandler); - int fast3MaCalculatedBars = BarsCalculated(fast3MaHandler); - int fast4MaCalculatedBars = BarsCalculated(fast4MaHandler); - int fast5MaCalculatedBars = BarsCalculated(fast5MaHandler); - int fast6MaCalculatedBars = BarsCalculated(fast6MaHandler); - // - int slow1MaCalculatedBars = BarsCalculated(slow1MaHandler); - int slow2MaCalculatedBars = BarsCalculated(slow2MaHandler); - int slow3MaCalculatedBars = BarsCalculated(slow3MaHandler); - int slow4MaCalculatedBars = BarsCalculated(slow4MaHandler); - int slow5MaCalculatedBars = BarsCalculated(slow5MaHandler); - int slow6MaCalculatedBars = BarsCalculated(slow6MaHandler); - if ( - fast1MaCalculatedBars < maxLength || - fast2MaCalculatedBars < maxLength || - fast3MaCalculatedBars < maxLength || - fast4MaCalculatedBars < maxLength || - fast5MaCalculatedBars < maxLength || - fast6MaCalculatedBars < maxLength || - slow1MaCalculatedBars < maxLength || - slow2MaCalculatedBars < maxLength || - slow3MaCalculatedBars < maxLength || - slow4MaCalculatedBars < maxLength || - slow5MaCalculatedBars < maxLength || - slow6MaCalculatedBars < maxLength // - ) - { - return prev_calculated; - } - - // - limit = (prev_calculated > rates_total || prev_calculated <= 0) ? rates_total : (rates_total - prev_calculated) + 1; - - // - // Buffers Copy ... - // - int copiedFast1Mas = CopyBuffer(fast1MaHandler, 0, 0, limit, fast1Buffer); - int copiedFast2Mas = CopyBuffer(fast2MaHandler, 0, 0, limit, fast2Buffer); - int copiedFast3Mas = CopyBuffer(fast3MaHandler, 0, 0, limit, fast3Buffer); - int copiedFast4Mas = CopyBuffer(fast4MaHandler, 0, 0, limit, fast4Buffer); - int copiedFast5Mas = CopyBuffer(fast5MaHandler, 0, 0, limit, fast5Buffer); - int copiedFast6Mas = CopyBuffer(fast6MaHandler, 0, 0, limit, fast6Buffer); - // - int copiedSlow1Mas = CopyBuffer(slow1MaHandler, 0, 0, limit, slow1Buffer); - int copiedSlow2Mas = CopyBuffer(slow2MaHandler, 0, 0, limit, slow2Buffer); - int copiedSlow3Mas = CopyBuffer(slow3MaHandler, 0, 0, limit, slow3Buffer); - int copiedSlow4Mas = CopyBuffer(slow4MaHandler, 0, 0, limit, slow4Buffer); - int copiedSlow5Mas = CopyBuffer(slow5MaHandler, 0, 0, limit, slow5Buffer); - int copiedSlow6Mas = CopyBuffer(slow6MaHandler, 0, 0, limit, slow6Buffer); - if ( - copiedFast1Mas <= 0 || - copiedFast2Mas <= 0 || - copiedFast3Mas <= 0 || - copiedFast4Mas <= 0 || - copiedFast5Mas <= 0 || - copiedFast6Mas <= 0 || - copiedSlow1Mas <= 0 || - copiedSlow2Mas <= 0 || - copiedSlow3Mas <= 0 || - copiedSlow4Mas <= 0 || - copiedSlow5Mas <= 0 || - copiedSlow6Mas <= 0 // - ) - { - return prev_calculated; - } - - // - // Main Loop ... - for (int i = limit - 1; i >= 0 && !IsStopped(); i--) - { - CalculateBuffers(i); - } - - // - return rates_total; -} - -// -// END Event Handlers ... -// - -// -// START Functions ... -// - -// -// Validate Input Args for Initialization ... -bool ValidateInputs() -{ - // - bool result = - // - (fast1Length > 2 && - fast2Length > 2 && - fast3Length > 2 && - fast4Length > 2 && - fast5Length > 2 && - fast6Length > 2 && - slow1Length > fast1Length && - slow2Length > fast2Length && - slow3Length > fast3Length && - slow4Length > fast4Length && - slow5Length > fast5Length && - slow6Length > fast6Length - // - ) - // - ; - - // - return result; -} - -// -// Retrieve all Exists Input Max Length ... -// use for Start Of Drawing ... -int ExtractMaxLengthOfInputs() -{ - // - int result = 0; - - // - // Ma ... - - // - result = MathMax(fast1Length, fast2Length); - result = MathMax(result, fast3Length); - result = MathMax(result, fast4Length); - result = MathMax(result, fast5Length); - result = MathMax(result, fast6Length); - - // - result = MathMax(result, slow1Length); - result = MathMax(result, slow2Length); - result = MathMax(result, slow3Length); - result = MathMax(result, slow4Length); - result = MathMax(result, slow5Length); - result = MathMax(result, slow6Length); - - // - return result; -} - -// -// Initialize Ma Handlers ... -bool InitializeMas() -{ - // - bool result = false; - - // - fast1MaHandler = iMA( - _Symbol, - _Period, - fast1Length, - 0, - ribbonMode, - r1AppliedTo); - fast2MaHandler = iMA( - _Symbol, - _Period, - fast2Length, - 0, - ribbonMode, - r2AppliedTo); - fast3MaHandler = iMA( - _Symbol, - _Period, - fast3Length, - 0, - ribbonMode, - r3AppliedTo); - fast4MaHandler = iMA( - _Symbol, - _Period, - fast4Length, - 0, - ribbonMode, - r4AppliedTo); - fast5MaHandler = iMA( - _Symbol, - _Period, - fast5Length, - 0, - ribbonMode, - r5AppliedTo); - fast6MaHandler = iMA( - _Symbol, - _Period, - fast6Length, - 0, - ribbonMode, - r6AppliedTo); - - // - slow1MaHandler = iMA( - _Symbol, - _Period, - slow1Length, - 0, - ribbonMode, - r1AppliedTo); - slow2MaHandler = iMA( - _Symbol, - _Period, - slow2Length, - 0, - ribbonMode, - r2AppliedTo); - slow3MaHandler = iMA( - _Symbol, - _Period, - slow3Length, - 0, - ribbonMode, - r3AppliedTo); - slow4MaHandler = iMA( - _Symbol, - _Period, - slow4Length, - 0, - ribbonMode, - r4AppliedTo); - slow5MaHandler = iMA( - _Symbol, - _Period, - slow5Length, - 0, - ribbonMode, - r5AppliedTo); - slow6MaHandler = iMA( - _Symbol, - _Period, - slow6Length, - 0, - ribbonMode, - r6AppliedTo); - - // - result = - fast1MaHandler != INVALID_HANDLE && - fast2MaHandler != INVALID_HANDLE && - fast3MaHandler != INVALID_HANDLE && - fast4MaHandler != INVALID_HANDLE && - fast5MaHandler != INVALID_HANDLE && - fast6MaHandler != INVALID_HANDLE && - slow1MaHandler != INVALID_HANDLE && - slow2MaHandler != INVALID_HANDLE && - slow3MaHandler != INVALID_HANDLE && - slow4MaHandler != INVALID_HANDLE && - slow5MaHandler != INVALID_HANDLE && - slow6MaHandler != INVALID_HANDLE; - - // - return result; -} - -// -// Define Indexes and Styles ... -void DefineBuffers() -{ - // - // FAST ... - ENUM_DRAW_TYPE fastDrawType = showFastMa ? DRAW_LINE : DRAW_NONE; - - ArraySetAsSeries(fastMaBuffer, true); - SetIndexBuffer(fastMaBufferIndex, fastMaBuffer, INDICATOR_DATA); - PlotIndexSetInteger(fastMaBufferIndex, PLOT_SHOW_DATA, showFastMa); - PlotIndexSetInteger(fastMaBufferIndex, PLOT_DRAW_BEGIN, maxLength); - PlotIndexSetInteger(fastMaBufferIndex, PLOT_DRAW_TYPE, fastDrawType); - - // - // SLOW ... - ENUM_DRAW_TYPE slowDrawType = showSlowMa ? DRAW_LINE : DRAW_NONE; - - ArraySetAsSeries(slowMaBuffer, true); - SetIndexBuffer(slowMaBufferIndex, slowMaBuffer, INDICATOR_DATA); - PlotIndexSetInteger(slowMaBufferIndex, PLOT_SHOW_DATA, showSlowMa); - PlotIndexSetInteger(slowMaBufferIndex, PLOT_DRAW_BEGIN, maxLength); - PlotIndexSetInteger(slowMaBufferIndex, PLOT_DRAW_TYPE, slowDrawType); - - // - // DATA ... - ENUM_DRAW_TYPE ribbonDrawType = showRibbon ? DRAW_LINE : DRAW_NONE; - - // - ArraySetAsSeries(fast1Buffer, true); - SetIndexBuffer(fast1BufferIndex, fast1Buffer, INDICATOR_DATA); - PlotIndexSetInteger(fast1BufferIndex, PLOT_SHOW_DATA, showRibbon); - PlotIndexSetInteger(fast1BufferIndex, PLOT_DRAW_BEGIN, maxLength); - PlotIndexSetInteger(fast1BufferIndex, PLOT_DRAW_TYPE, ribbonDrawType); - - // - ArraySetAsSeries(fast2Buffer, true); - SetIndexBuffer(fast2BufferIndex, fast2Buffer, INDICATOR_DATA); - PlotIndexSetInteger(fast2BufferIndex, PLOT_SHOW_DATA, showRibbon); - PlotIndexSetInteger(fast2BufferIndex, PLOT_DRAW_BEGIN, maxLength); - PlotIndexSetInteger(fast2BufferIndex, PLOT_DRAW_TYPE, ribbonDrawType); - - // - ArraySetAsSeries(fast3Buffer, true); - SetIndexBuffer(fast3BufferIndex, fast3Buffer, INDICATOR_DATA); - PlotIndexSetInteger(fast3BufferIndex, PLOT_SHOW_DATA, showRibbon); - PlotIndexSetInteger(fast3BufferIndex, PLOT_DRAW_BEGIN, maxLength); - PlotIndexSetInteger(fast3BufferIndex, PLOT_DRAW_TYPE, ribbonDrawType); - - // - ArraySetAsSeries(fast4Buffer, true); - SetIndexBuffer(fast4BufferIndex, fast4Buffer, INDICATOR_DATA); - PlotIndexSetInteger(fast4BufferIndex, PLOT_SHOW_DATA, showRibbon); - PlotIndexSetInteger(fast4BufferIndex, PLOT_DRAW_BEGIN, maxLength); - PlotIndexSetInteger(fast4BufferIndex, PLOT_DRAW_TYPE, ribbonDrawType); - - // - ArraySetAsSeries(fast5Buffer, true); - SetIndexBuffer(fast5BufferIndex, fast5Buffer, INDICATOR_DATA); - PlotIndexSetInteger(fast5BufferIndex, PLOT_SHOW_DATA, showRibbon); - PlotIndexSetInteger(fast5BufferIndex, PLOT_DRAW_BEGIN, maxLength); - PlotIndexSetInteger(fast5BufferIndex, PLOT_DRAW_TYPE, ribbonDrawType); - - // - ArraySetAsSeries(fast6Buffer, true); - SetIndexBuffer(fast6BufferIndex, fast6Buffer, INDICATOR_DATA); - PlotIndexSetInteger(fast6BufferIndex, PLOT_SHOW_DATA, showRibbon); - PlotIndexSetInteger(fast6BufferIndex, PLOT_DRAW_BEGIN, maxLength); - PlotIndexSetInteger(fast6BufferIndex, PLOT_DRAW_TYPE, ribbonDrawType); - - // - ArraySetAsSeries(slow1Buffer, true); - SetIndexBuffer(slow1BufferIndex, slow1Buffer, INDICATOR_DATA); - PlotIndexSetInteger(slow1BufferIndex, PLOT_SHOW_DATA, showRibbon); - PlotIndexSetInteger(slow1BufferIndex, PLOT_DRAW_BEGIN, maxLength); - PlotIndexSetInteger(slow1BufferIndex, PLOT_DRAW_TYPE, ribbonDrawType); - - // - ArraySetAsSeries(slow2Buffer, true); - SetIndexBuffer(slow2BufferIndex, slow2Buffer, INDICATOR_DATA); - PlotIndexSetInteger(slow2BufferIndex, PLOT_SHOW_DATA, showRibbon); - PlotIndexSetInteger(slow2BufferIndex, PLOT_DRAW_BEGIN, maxLength); - PlotIndexSetInteger(slow2BufferIndex, PLOT_DRAW_TYPE, ribbonDrawType); - - // - ArraySetAsSeries(slow3Buffer, true); - SetIndexBuffer(slow3BufferIndex, slow3Buffer, INDICATOR_DATA); - PlotIndexSetInteger(slow3BufferIndex, PLOT_SHOW_DATA, showRibbon); - PlotIndexSetInteger(slow3BufferIndex, PLOT_DRAW_BEGIN, maxLength); - PlotIndexSetInteger(slow3BufferIndex, PLOT_DRAW_TYPE, ribbonDrawType); - - // - ArraySetAsSeries(slow4Buffer, true); - SetIndexBuffer(slow4BufferIndex, slow4Buffer, INDICATOR_DATA); - PlotIndexSetInteger(slow4BufferIndex, PLOT_SHOW_DATA, showRibbon); - PlotIndexSetInteger(slow4BufferIndex, PLOT_DRAW_BEGIN, maxLength); - PlotIndexSetInteger(slow4BufferIndex, PLOT_DRAW_TYPE, ribbonDrawType); - - // - ArraySetAsSeries(slow5Buffer, true); - SetIndexBuffer(slow5BufferIndex, slow5Buffer, INDICATOR_DATA); - PlotIndexSetInteger(slow5BufferIndex, PLOT_SHOW_DATA, showRibbon); - PlotIndexSetInteger(slow5BufferIndex, PLOT_DRAW_BEGIN, maxLength); - PlotIndexSetInteger(slow5BufferIndex, PLOT_DRAW_TYPE, ribbonDrawType); - - // - ArraySetAsSeries(slow6Buffer, true); - SetIndexBuffer(slow6BufferIndex, slow6Buffer, INDICATOR_DATA); - PlotIndexSetInteger(slow6BufferIndex, PLOT_SHOW_DATA, showRibbon); - PlotIndexSetInteger(slow6BufferIndex, PLOT_DRAW_BEGIN, maxLength); - PlotIndexSetInteger(slow6BufferIndex, PLOT_DRAW_TYPE, ribbonDrawType); -} - -// -// Set Indicator Short Name and also we can define Buffers Labels ... -void SetIndicatorName() -{ - IndicatorSetString(INDICATOR_SHORTNAME, ShortName); -} - -// -// Calculate Buffers ... -void CalculateBuffers( - int bar_index // Selected Bar Index -) -{ - // - // Retireve Values ... - - // - double fast1Value = fast1Buffer[bar_index]; - double fast2Value = fast2Buffer[bar_index]; - double fast3Value = fast3Buffer[bar_index]; - double fast4Value = fast4Buffer[bar_index]; - double fast5Value = fast5Buffer[bar_index]; - double fast6Value = fast6Buffer[bar_index]; - - // - double fasts[] = { - fast1Value, - fast2Value, - fast3Value, - fast4Value, - fast5Value, - fast6Value}; - - // - double slow1Value = slow1Buffer[bar_index]; - double slow2Value = slow2Buffer[bar_index]; - double slow3Value = slow3Buffer[bar_index]; - double slow4Value = slow4Buffer[bar_index]; - double slow5Value = slow5Buffer[bar_index]; - double slow6Value = slow6Buffer[bar_index]; - - // - double slows[] = { - slow1Value, - slow2Value, - slow3Value, - slow4Value, - slow5Value, - slow6Value}; - - // - double fastValue = GetAverage(fasts); - fastMaBuffer[bar_index] = fastValue; - - // - double slowValue = GetAverage(slows); - slowMaBuffer[bar_index] = slowValue; -} - -// -// END Functions ... -// diff --git a/Documents/Pack/V1.0/Source/Indicators/x-saherelm.xosc.mq5 b/Documents/Pack/V1.0/Source/Indicators/x-saherelm.xosc.mq5 deleted file mode 100644 index ecf3a27b..00000000 --- a/Documents/Pack/V1.0/Source/Indicators/x-saherelm.xosc.mq5 +++ /dev/null @@ -1,721 +0,0 @@ -////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Indicator -// --------------------------------------------- -// Name: XOSC -// Description: provides some oscillator values -// as empty Indicator ... -// -// -// Maintainer: -// ------------ -// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) -// -////////////////////////////////////////////////////// -// -// Global Properties ... -#property copyright "Copyright 2023, SaherElm IT Center" -#property link "https://saherelm.ir" -#property version "1.00" -#property description "SaherElm X121_XAMA Indicator" -#property strict - -// -// START Constants ... -// - -#define ShortName "XOSC" - -// -// END Constants ... -// - -// -// START Inputs ... -// - -// -// ATR ... -input group "ATR"; -input int atrLength = 14; // Length - -// -// RVI ... -// The buffer numbers are the following: 0 - MAIN_LINE, 1 - SIGNAL_LINE. -input group "RVI"; -input int rviLength = 10; // Length - -// -// BULLPOWER ... -input group "Bulls Power"; -input int bullpLength = 13; // Length - -// -// BEARPOWER ... -input group "Bears Power"; -input int bearpLength = 13; // Length - -// -// VOLUME ... -input group "Volumes"; -input ENUM_APPLIED_VOLUME volumeAppliedTo = VOLUME_TICK; // Applied To - -// -// RSI ... -input group "RSI"; -input int rsiLength = 14; // Length -input ENUM_APPLIED_PRICE rsiAppliedTo = PRICE_CLOSE; // Applied To - -// -// CCI ... -input group "CCI"; -input int cciLength = 14; // Length -input ENUM_APPLIED_PRICE cciAppliedTo = PRICE_TYPICAL; // Applied To - -// -// STDDEV ... -input group "Standard Deviation"; -input int stddevLength = 20; // Length -input int stddevShift = 0; // Shift -input ENUM_MA_METHOD stddevMethod = MODE_SMA; // Mode -input ENUM_APPLIED_PRICE stddevAppliedTo = PRICE_CLOSE; // AppliedTo - -// -// MOMENTUM ... -input group "Momentum"; -input int momentumLength = 14; // Length -input ENUM_APPLIED_PRICE momentumAppliedTo = PRICE_CLOSE; // Applied To - -// -// SAR ... -input group "SAR"; -input double sarStep = 0.02; // Step -input double sarMaximum = 0.2; // Maximum - -// -// MACD ... -// The buffer numbers are the following: 0 - MAIN_LINE, 1 - SIGNAL_LINE. -input group "MACD"; -input int macdFastLength = 12; // Fast Length -input int macdSlowLength = 26; // Slow Length -input int macdSignaLength = 9; // Signal Length -input ENUM_APPLIED_PRICE macdAppliedTo = PRICE_CLOSE; // Applied To - -// -// STOCHASTIC ... -// The buffer numbers: 0 - MAIN_LINE, 1 - SIGNAL_LINE. -input group "Stochastic"; -input int stochKLength = 5; // K Length -input int stochDLength = 3; // D Length -input int stochSlowing = 3; // Slowing -input ENUM_MA_METHOD stochMaMethod = MODE_SMA; // Ma Method -input ENUM_STO_PRICE stochMode = STO_LOWHIGH; // Calculation Mode - -// -// END Inputs ... -// - -// -// Includes Common Library ... -#include "../Libraries/x-saherelm.common.lib.mq5" - -// -// START Buffers ... -// - -// -#property indicator_chart_window - -// -#property indicator_buffers 15 -#property indicator_plots 0 - -// -// ATR ... -#define atrBufferIndex 0 -double atrBuffer[]; - -// -// RVI ... -#define rviMainBufferIndex 1 -#define rviSignalBufferIndex 2 -double rviMainBuffer[]; -double rviSignalBuffer[]; - -// -// BULLPOWER ... -#define bullPBufferIndex 3 -double bullPBuffer[]; - -// -// BEARPOWER ... -#define bearPBufferIndex 4 -double bearPBuffer[]; - -// -// VOLUME ... -#define volumeBufferIndex 5 -double volumeBuffer[]; - -// -// RSI ... -#define rsiBufferIndex 6 -double rsiBuffer[]; - -// -// CCI ... -#define cciBufferIndex 7 -double cciBuffer[]; - -// -// MOMENTUM ... -#define momentumBufferIndex 8 -double momentumBuffer[]; - -// -// SAR ... -#define sarBufferIndex 9 -double sarBuffer[]; - -// -// MACD ... -#define macdMainBufferIndex 10 -#define macdSignalBufferIndex 11 -double macdMainBuffer[]; -double macdSignalBuffer[]; - -// -// STOCHASTIC ... -#define stochMainBufferIndex 12 -#define stochSignalBufferIndex 13 -double stochMainBuffer[]; -double stochSignalBuffer[]; - -// -// STANDARDDEVIATION ... -#define stddevBufferIndex 14 -double stddevBuffer[]; - -// -// END Buffers ... -// - -// -// START Global Definitions: Variables, Properties and etc ... -// - -// -int maxLength; - -// -int atrHandler = INVALID_HANDLE; -int rviHandler = INVALID_HANDLE; -int bullPHandler = INVALID_HANDLE; -int bearPHandler = INVALID_HANDLE; -int volumeHandler = INVALID_HANDLE; -int rsiHandler = INVALID_HANDLE; -int cciHandler = INVALID_HANDLE; -int momentumHandler = INVALID_HANDLE; -int sarHandler = INVALID_HANDLE; -int macdHandler = INVALID_HANDLE; -int stochHandler = INVALID_HANDLE; -int stddevHandler = INVALID_HANDLE; - -// -// END Global Definitions: Variables, Properties and etc ... -// - -// -// START Event Handlers ... -// - -// -// Initialization ... -int OnInit() -{ - // - // Validate Inputs ... - if (!ValidateInputs()) - { - return INIT_PARAMETERS_INCORRECT; - } - - // - // because in some cases we may have more than one input for - // calculation and we must prevent any calculation - // untill we pass the biggest input length, here we get max Input length - // and then wait until pass it ... - maxLength = ExtractMaxLengthOfInputs(); - - // - // Initializing Handlers ... - - // - // ATR ... - atrHandler = iATR( - _Symbol, - _Period, - atrLength); - - // - // RVI ... - rviHandler = iRVI( - _Symbol, - _Period, - rviLength); - - // - // BULLSPOWER ... - bullPHandler = iBullsPower( - _Symbol, - _Period, - bullpLength); - - // - // BEARSPOWER ... - bearPHandler = iBearsPower( - _Symbol, - _Period, - bullpLength); - - // - // VOLUMES ... - volumeHandler = iVolumes( - _Symbol, - _Period, - volumeAppliedTo); - - // - // RSI ... - rsiHandler = iRSI( - _Symbol, - _Period, - rsiLength, - rsiAppliedTo); - - // - // CCI ... - cciHandler = iCCI( - _Symbol, - _Period, - cciLength, - cciAppliedTo); - - // - // MOMENTUM ... - momentumHandler = iMomentum( - _Symbol, - _Period, - momentumLength, - momentumAppliedTo); - - // - // SAR ... - sarHandler = iSAR( - _Symbol, - _Period, - sarStep, - sarMaximum); - - // - // MACD ... - macdHandler = iMACD( - _Symbol, - _Period, - macdFastLength, - macdSlowLength, - macdSignaLength, - macdAppliedTo); - - // - // STOCHASTIC ... - stochHandler = iStochastic( - _Symbol, - _Period, - stochKLength, - stochDLength, - stochSlowing, - stochMaMethod, - stochMode); - - // - // STANDARDDEVIATION ... - stddevHandler = iStdDev( - _Symbol, - _Period, - stddevLength, - stddevShift, - stddevMethod, - stddevAppliedTo); - - // - bool isAllHandlersInit = - // - atrHandler != INVALID_HANDLE && - rviHandler != INVALID_HANDLE && - bullPHandler != INVALID_HANDLE && - bearPHandler != INVALID_HANDLE && - volumeHandler != INVALID_HANDLE && - rsiHandler != INVALID_HANDLE && - cciHandler != INVALID_HANDLE && - momentumHandler != INVALID_HANDLE && - sarHandler != INVALID_HANDLE && - macdHandler != INVALID_HANDLE && - stochHandler != INVALID_HANDLE && - stddevHandler != INVALID_HANDLE - // - ; - if (!isAllHandlersInit) - { - return INIT_FAILED; - } - - // - // Define Index Buffers ... - DefineBuffers(); - - // - // Set Indicator ShortName ... - SetIndicatorName(); - - // - // Init Succeed ... - return INIT_SUCCEEDED; -} - -// -// DeInitialization ... -void OnDeinit(const int reason) -{ - // - // REASON_PROGRAM 0 The EA has stopped working calling the ExpertRemove() function - // REASON_REMOVE 1 Program removed from a chart - // REASON_RECOMPILE 2 Program recompiled - // REASON_CHARTCHANGE 3 A symbol or a chart period is changed - // REASON_CHARTCLOSE 4 Chart closed - // REASON_PARAMETERS 5 Inputs changed by a user - // REASON_ACCOUNT 6 Another account has been activated or reconnection to the trade server has occurred due to changes in the account settings - // REASON_TEMPLATE 7 Another chart template applied - // REASON_INITFAILED 8 The OnInit() handler returned a non-zero value - // REASON_CLOSE 9 Terminal closed - - // - // Here we can handle De Initialization Reasons ... - IndicatorRelease(atrHandler); - IndicatorRelease(rviHandler); - IndicatorRelease(bullPHandler); - IndicatorRelease(bearPHandler); - IndicatorRelease(volumeHandler); - IndicatorRelease(rsiHandler); - IndicatorRelease(cciHandler); - IndicatorRelease(momentumHandler); - IndicatorRelease(sarHandler); - IndicatorRelease(macdHandler); - IndicatorRelease(stochHandler); - IndicatorRelease(stddevHandler); -} - -// -// 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 atrCalculatedBars = BarsCalculated(atrHandler); - int rviCalculatedBars = BarsCalculated(rviHandler); - int bullPCalculatedBars = BarsCalculated(bullPHandler); - int bearPCalculatedBars = BarsCalculated(bearPHandler); - int volumeCalculatedBars = BarsCalculated(volumeHandler); - int rsiCalculatedBars = BarsCalculated(rsiHandler); - int cciCalculatedBars = BarsCalculated(cciHandler); - int momentumCalculatedBars = BarsCalculated(momentumHandler); - int sarCalculatedBars = BarsCalculated(sarHandler); - int macdCalculatedBars = BarsCalculated(macdHandler); - int stochCalculatedBars = BarsCalculated(stochHandler); - int stddevCalculatedBars = BarsCalculated(stddevHandler); - - // - bool isCalculatedBarsPassed = - // - atrCalculatedBars >= maxLength && - rviCalculatedBars >= maxLength && - bullPCalculatedBars >= maxLength && - bearPCalculatedBars >= maxLength && - volumeCalculatedBars >= maxLength && - rsiCalculatedBars >= maxLength && - cciCalculatedBars >= maxLength && - momentumCalculatedBars >= maxLength && - sarCalculatedBars >= maxLength && - macdCalculatedBars >= maxLength && - stochCalculatedBars >= maxLength && - stddevCalculatedBars >= maxLength - // - ; - if (!isCalculatedBarsPassed) - { - return prev_calculated; - } - - // - limit = (prev_calculated > rates_total || prev_calculated <= 0) ? rates_total : (rates_total - prev_calculated) + 1; - - // - // Buffers Copy ... - int atrCopiedItems = CopyBuffer(atrHandler, 0, 0, limit, atrBuffer); - int rviMainCopiedItems = CopyBuffer(rviHandler, MAIN_LINE, 0, limit, rviMainBuffer); - int rviSignalCopiedItems = CopyBuffer(rviHandler, SIGNAL_LINE, 0, limit, rviSignalBuffer); - int bullPCopiedItems = CopyBuffer(bullPHandler, 0, 0, limit, bullPBuffer); - int bearPCopiedItems = CopyBuffer(bearPHandler, 0, 0, limit, bearPBuffer); - int volumeCopiedItems = CopyBuffer(volumeHandler, 0, 0, limit, volumeBuffer); - int rsiCopiedItems = CopyBuffer(rsiHandler, 0, 0, limit, rsiBuffer); - int cciCopiedItems = CopyBuffer(cciHandler, 0, 0, limit, cciBuffer); - int momentumCopiedItems = CopyBuffer(momentumHandler, 0, 0, limit, momentumBuffer); - int sarCopiedItems = CopyBuffer(sarHandler, 0, 0, limit, sarBuffer); - int macdMainCopiedItems = CopyBuffer(macdHandler, MAIN_LINE, 0, limit, macdMainBuffer); - int macdSignalCopiedItems = CopyBuffer(macdHandler, SIGNAL_LINE, 0, limit, macdSignalBuffer); - int stochMainCopiedItems = CopyBuffer(stochHandler, MAIN_LINE, 0, limit, stochMainBuffer); - int stocSignalhCopiedItems = CopyBuffer(stochHandler, SIGNAL_LINE, 0, limit, stochSignalBuffer); - int stddevCopiedItems = CopyBuffer(stddevHandler, 0, 0, limit, stddevBuffer); - - // - bool isCopiedBarsPassed = - // - atrCopiedItems > 0 && - rviMainCopiedItems > 0 && - rviSignalCopiedItems > 0 && - bullPCopiedItems > 0 && - bearPCopiedItems > 0 && - volumeCopiedItems > 0 && - rsiCopiedItems > 0 && - cciCopiedItems > 0 && - momentumCopiedItems > 0 && - sarCopiedItems > 0 && - macdMainCopiedItems > 0 && - macdSignalCopiedItems > 0 && - stochMainCopiedItems > 0 && - stocSignalhCopiedItems > 0 && - stddevCopiedItems > 0 - // - ; - if (!isCopiedBarsPassed) - { - return prev_calculated; - } - - // - // Main Loop ... - for (int i = limit - 1; i >= 0 && !IsStopped(); i--) - { - // - // Do Buffers Calculation ... - // HERE We Do Not anything ... - } - - // - return rates_total; -} - -// -// END Event Handlers ... -// - -// -// START Functions ... -// - -// -// Validate Input Args for Initialization ... -bool ValidateInputs() -{ - // - bool result = false; - - // - // Validate Args ... - result = - // - atrLength >= 2 && - rviLength >= 2 && - bullpLength >= 2 && - bearpLength >= 2 && - rsiLength >= 2 && - cciLength >= 2 && - momentumLength >= 2 && - sarStep > 0 && - sarStep < sarMaximum && - macdFastLength >= 2 && - macdSlowLength > macdFastLength && - macdSignaLength >= 2 && - stochKLength >= 2 && - stochDLength >= 2 && - stochSlowing >= 2 && - stddevLength >= 2 && - stddevShift >= 0 - // - ; - - // - return result; -} - -// -// Retrieve all Exists Input Max Length ... -// use for Start Of Drawing ... -int ExtractMaxLengthOfInputs() -{ - // - int result = 0; - - // - result = MathMax(atrLength, rviLength); - result = MathMax(result, bullpLength); - result = MathMax(result, bearpLength); - result = MathMax(result, rsiLength); - result = MathMax(result, cciLength); - result = MathMax(result, momentumLength); - result = MathMax(result, macdFastLength); - result = MathMax(result, macdSlowLength); - result = MathMax(result, macdSignaLength); - result = MathMax(result, stochKLength); - result = MathMax(result, stochDLength); - result = MathMax(result, stochSlowing); - result = MathMax(result, stddevLength); - - // - return result; -} - -// -// Set Indicator Short Name and also we can define Buffers Labels ... -void SetIndicatorName() -{ - IndicatorSetString(INDICATOR_SHORTNAME, ShortName); -} - -// -// Define Indexes and Styles ... -void DefineBuffers() -{ - // - // DATA Buffers ... - - // - // ATR ... - ArraySetAsSeries(atrBuffer, true); - SetIndexBuffer(atrBufferIndex, atrBuffer, INDICATOR_CALCULATIONS); - - // - // RVI ... - - // - // Main ... - ArraySetAsSeries(rviMainBuffer, true); - SetIndexBuffer(rviMainBufferIndex, rviMainBuffer, INDICATOR_CALCULATIONS); - - // - // Signal ... - ArraySetAsSeries(rviSignalBuffer, true); - SetIndexBuffer(rviSignalBufferIndex, rviSignalBuffer, INDICATOR_CALCULATIONS); - - // - // BULLPOWER ... - ArraySetAsSeries(bullPBuffer, true); - SetIndexBuffer(bullPBufferIndex, bullPBuffer, INDICATOR_CALCULATIONS); - - // - // BEARPOWER ... - ArraySetAsSeries(bearPBuffer, true); - SetIndexBuffer(bearPBufferIndex, bearPBuffer, INDICATOR_CALCULATIONS); - - // - // VOLUME ... - ArraySetAsSeries(volumeBuffer, true); - SetIndexBuffer(volumeBufferIndex, volumeBuffer, INDICATOR_CALCULATIONS); - - // - // RSI ... - ArraySetAsSeries(rsiBuffer, true); - SetIndexBuffer(rsiBufferIndex, rsiBuffer, INDICATOR_CALCULATIONS); - - // - // CCI ... - ArraySetAsSeries(cciBuffer, true); - SetIndexBuffer(cciBufferIndex, cciBuffer, INDICATOR_CALCULATIONS); - - // - // MOMENTUM ... - ArraySetAsSeries(momentumBuffer, true); - SetIndexBuffer(momentumBufferIndex, momentumBuffer, INDICATOR_CALCULATIONS); - - // - // SAR ... - ArraySetAsSeries(sarBuffer, true); - SetIndexBuffer(sarBufferIndex, sarBuffer, INDICATOR_CALCULATIONS); - - // - // STANDARDDEVIATION ... - ArraySetAsSeries(stddevBuffer, true); - SetIndexBuffer(stddevBufferIndex, stddevBuffer, INDICATOR_CALCULATIONS); - - // - // MACD ... - - // - // Main ... - ArraySetAsSeries(macdMainBuffer, true); - SetIndexBuffer(macdMainBufferIndex, macdMainBuffer, INDICATOR_CALCULATIONS); - - // - // Signal ... - ArraySetAsSeries(macdSignalBuffer, true); - SetIndexBuffer(macdSignalBufferIndex, macdSignalBuffer, INDICATOR_CALCULATIONS); -} - -// -// END Functions ... -// diff --git a/Documents/Pack/V1.0/Source/Indicators/x-saherelm.xpv.mq5 b/Documents/Pack/V1.0/Source/Indicators/x-saherelm.xpv.mq5 deleted file mode 100644 index 038dfbfc..00000000 --- a/Documents/Pack/V1.0/Source/Indicators/x-saherelm.xpv.mq5 +++ /dev/null @@ -1,1292 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Indicator -// ------------------------------------------------- -// Name: XPV -// Description: Peaks and Vales ... -// -// -// 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 XPV Indicator" -#property strict - -// -// Definitions ... - -// -#define ShortName "XPV" - -// -// Includes Common Library ... -#include "../Libraries/x-saherelm.common.lib.mq5" - -// -// Inputs ... - -// -input group "Makret Cycles"; - -// -input group "Short"; -input ENUM_X_PERIOD_METHOD scMethod = X_PERIOD_AUTO; // How to Find Period -input ENUM_TIMEFRAMES scPeriod = NULL; // Time Period -// input int scLength = 0; // Length - -// -input group "Medium"; -input ENUM_X_PERIOD_METHOD mcMethod = X_PERIOD_AUTO; // How to Find Period -input ENUM_TIMEFRAMES mcPeriod = NULL; // Time Period -// input int mcLength = 0; // Length - -// -input group "Long"; -input ENUM_X_PERIOD_METHOD lcMethod = X_PERIOD_AUTO; // How to Find Period -input ENUM_TIMEFRAMES lcPeriod = NULL; // Time Period -// input int lcLength = 0; // Length - -// -input group "Hind"; -input ENUM_X_PERIOD_METHOD hcMethod = X_PERIOD_AUTO; // How to Find Period -input ENUM_TIMEFRAMES hcPeriod = NULL; // Time Period -// input int hcLength = 0; // Length - -// -input group "Fibonacci"; -input double fiboLevel1 = 0.236; // Fibio 1st Level -input double fiboLevel2 = 0.382; // Fibio 2st Level -input double fiboLevel3 = 0.5; // Fibio 3rd Level -input double fiboLevel4 = 0.618; // Fibio 4th Level -input double fiboLevel5 = 0.764; // Fibio 5th Level - -// -input group "Boundary Detection Modes"; -input ENUM_SERIESMODE hhMode = MODE_HIGH; // Highest High Calculation Method -input ENUM_SERIESMODE llMode = MODE_LOW; // Lowest Low Calculation Method - -// -input group "Presentation"; -input bool showPeaksAndVales = true; // Show Peaks and Vales -input bool showLevels = false; // Show Levels -input bool showConsolidations = false; // Show Consolidations -input bool showFibo1Levels = false; // Show Fibo 1st Level -input bool showFibo2Levels = false; // Show Fibo 2nd Level -input bool showFibo3Levels = false; // Show Fibo 3rd Level -input bool showFibo4Levels = false; // Show Fibo 4th Level -input bool showFibo5Levels = false; // Show Fibo 5th Level - -// -// Buffers ... - -// -#property indicator_chart_window - -// -#property indicator_buffers 32 -#property indicator_plots 32 - -// -// PEAKS ... - -// -#define peaksBufferIndex 0 -double peaksBuffer[]; - -// -#property indicator_label1 "XPV PEAKS" -#property indicator_type1 DRAW_ARROW -#property indicator_color1 clrAqua -#property indicator_width1 1 - -// -// VALES ... - -// -#define valesBufferIndex 1 -double valesBuffer[]; - -// -#property indicator_label2 "XPV VALES" -#property indicator_type2 DRAW_ARROW -#property indicator_color2 clrMagenta -#property indicator_width2 1 - -// -#define rBufferIndex 2 -double rBuffer[]; - -// -#define rColorBufferIndex 3 -double rColorBuffer[]; - -// -#property indicator_label3 "XPV R" -#property indicator_type3 DRAW_COLOR_LINE -#property indicator_color3 CLR_NONE, clrAqua -#property indicator_style3 STYLE_DOT -#property indicator_width3 1 - -// -#define sBufferIndex 4 -#define sBufferPlotIndex 3 -double sBuffer[]; - -// -#define sColorBufferIndex 5 -double sColorBuffer[]; - -// -#property indicator_label4 "XPV S" -#property indicator_type4 DRAW_COLOR_LINE -#property indicator_color4 CLR_NONE, clrMagenta -#property indicator_style4 STYLE_DOT -#property indicator_width4 1 - -// -// FIBBO Level 1 ... - -// -#define fl1BufferIndex 6 -#define fl1BufferPlotIndex 4 -double fl1Buffer[]; - -// -#define fl1ColorBufferIndex 7 -double fl1ColorBuffer[]; - -// -#property indicator_label5 "XPV FL1" -#property indicator_type5 DRAW_COLOR_LINE -#property indicator_color5 CLR_NONE, clrGold -#property indicator_style5 STYLE_DASHDOTDOT -#property indicator_width5 1 - -// -// FIBBO Level 2 ... - -// -#define fl2BufferIndex 8 -#define fl2BufferPlotIndex 5 -double fl2Buffer[]; - -// -#define fl2ColorBufferIndex 9 -double fl2ColorBuffer[]; - -// -#property indicator_label6 "XPV FL2" -#property indicator_type6 DRAW_COLOR_LINE -#property indicator_color6 CLR_NONE, clrGold -#property indicator_style6 STYLE_DASHDOTDOT -#property indicator_width6 1 - -// -// FIBBO Level 3 ... - -// -#define fl3BufferIndex 10 -#define fl3BufferPlotIndex 6 -double fl3Buffer[]; - -// -#define fl3ColorBufferIndex 11 -double fl3ColorBuffer[]; - -// -#property indicator_label7 "XPV FL3" -#property indicator_type7 DRAW_COLOR_LINE -#property indicator_color7 CLR_NONE, clrGold -#property indicator_style7 STYLE_DASHDOTDOT -#property indicator_width7 1 - -// -// FIBBO Level 4 ... - -// -#define fl4BufferIndex 12 -#define fl4BufferPlotIndex 7 -double fl4Buffer[]; - -// -#define fl4ColorBufferIndex 13 -double fl4ColorBuffer[]; - -// -#property indicator_label8 "XPV FL4" -#property indicator_type8 DRAW_COLOR_LINE -#property indicator_color8 CLR_NONE, clrGold -#property indicator_style8 STYLE_DASHDOTDOT -#property indicator_width8 1 - -// -// FIBBO Level 5 ... - -// -#define fl5BufferIndex 14 -#define fl5BufferPlotIndex 8 -double fl5Buffer[]; - -// -#define fl5ColorBufferIndex 15 -double fl5ColorBuffer[]; - -// -#property indicator_label9 "XPV FL5" -#property indicator_type9 DRAW_COLOR_LINE -#property indicator_color9 CLR_NONE, clrGold -#property indicator_style9 STYLE_DASHDOTDOT -#property indicator_width9 1 - -// -// LEVELS ... - -// -#define scHHBufferIndex 16 -#define scHHBufferPlotIndex 9 -double scHHBuffer[]; - -// -#define scHHColorBufferIndex 17 -double scHHColorBuffer[]; - -// -#property indicator_label10 "XPV SHH" -#property indicator_type10 DRAW_COLOR_LINE -#property indicator_color10 CLR_NONE, clrLightGray, clrAqua, clrMagenta -#property indicator_style10 STYLE_DOT -#property indicator_width10 1 - -#define scLLBufferIndex 18 -#define scLLBufferPlotIndex 10 -double scLLBuffer[]; - -// -#define scLLColorBufferIndex 19 -double scLLColorBuffer[]; - -// -#property indicator_label11 "XPV SLL" -#property indicator_type11 DRAW_COLOR_LINE -#property indicator_color11 CLR_NONE, clrLightGray, clrAqua, clrMagenta -#property indicator_style11 STYLE_DOT -#property indicator_width11 1 - -// -#define mcHHBufferIndex 20 -#define mcHHBufferPlotIndex 11 -double mcHHBuffer[]; - -// -#define mcHHColorBufferIndex 21 -double mcHHColorBuffer[]; - -// -#property indicator_label12 "XPV MHH" -#property indicator_type12 DRAW_COLOR_LINE -#property indicator_color12 CLR_NONE, clrLightGray, clrAqua, clrMagenta -#property indicator_style12 STYLE_DOT -#property indicator_width12 1 - -// -#define mcLLBufferIndex 22 -#define mcLLBufferPlotIndex 12 -double mcLLBuffer[]; - -// -#define mcLLColorBufferIndex 23 -double mcLLColorBuffer[]; - -// -#property indicator_label13 "XPV MLL" -#property indicator_type13 DRAW_COLOR_LINE -#property indicator_color13 CLR_NONE, clrLightGray, clrAqua, clrMagenta -#property indicator_style13 STYLE_DOT -#property indicator_width13 1 - -// -#define lcHHBufferIndex 24 -#define lcHHBufferPlotIndex 13 -double lcHHBuffer[]; - -// -#define lcHHColorBufferIndex 25 -double lcHHColorBuffer[]; - -// -#property indicator_label14 "XPV LHH" -#property indicator_type14 DRAW_COLOR_LINE -#property indicator_color14 CLR_NONE, clrLightGray, clrAqua, clrMagenta -#property indicator_style14 STYLE_DOT -#property indicator_width14 1 - -// -#define lcLLBufferIndex 26 -#define lcLLBufferPlotIndex 14 -double lcLLBuffer[]; - -// -#define lcLLColorBufferIndex 27 -double lcLLColorBuffer[]; - -// -#property indicator_label15 "XPV LLL" -#property indicator_type15 DRAW_COLOR_LINE -#property indicator_color15 CLR_NONE, clrLightGray, clrAqua, clrMagenta -#property indicator_style15 STYLE_DOT -#property indicator_width15 1 - -// -#define hcHHBufferIndex 28 -#define hcHHBufferPlotIndex 15 -double hcHHBuffer[]; - -// -#define hcHHColorBufferIndex 29 -double hcHHColorBuffer[]; - -// -#property indicator_label16 "XPV HHH" -#property indicator_type16 DRAW_COLOR_LINE -#property indicator_color16 CLR_NONE, clrLightGray, clrAqua, clrMagenta -#property indicator_style16 STYLE_DOT -#property indicator_width16 1 - -// -#define hcLLBufferIndex 30 -#define hcLLBufferPlotIndex 16 -double hcLLBuffer[]; - -// -#define hcLLColorBufferIndex 31 -double hcLLColorBuffer[]; - -// -#property indicator_label17 "XPV HLL" -#property indicator_type17 DRAW_COLOR_LINE -#property indicator_color17 CLR_NONE, clrLightGray, clrAqua, clrMagenta -#property indicator_style17 STYLE_DOT -#property indicator_width17 1 - -// -// Variables, Properties and etc ... - -// -int maxLength; - -// -double mHideColorIDX = 0; - -// -// XMarketCycle sc; -int mSCLength = 0; -double mLastSCHH = 0; -double mLastSCLL = 0; -ENUM_TIMEFRAMES mSCPeriod = NULL; - -// -// XMarketCycle mc; -int mMCLength = 0; -double mLastMCHH = 0; -double mLastMCLL = 0; -ENUM_TIMEFRAMES mMCPeriod = NULL; - -// -// XMarketCycle lc; -int mLCLength = 0; -double mLastLCHH = 0; -double mLastLCLL = 0; -ENUM_TIMEFRAMES mLCPeriod = NULL; - -// -// XMarketCycle hc; -int mHCLength = 0; -double mLastHCHH = 0; -double mLastHCLL = 0; -ENUM_TIMEFRAMES mHCPeriod = NULL; - -// -double lastPeak = 0; -double lastVale = 0; - -// -// Event Handlers ... - -// -// Initialization ... -int OnInit() -{ - // - // Validate Inputs ... - if (!ValidateInputs()) - { - return INIT_PARAMETERS_INCORRECT; - } - - // - if (!InitMarketCycles()) - { - return INIT_PARAMETERS_INCORRECT; - } - - // - // because in some cases we may have more than one input for - // calculation and we must prevent any calculation - // untill we pass the biggest input length, here we get max Input length - // and then wait until pass it ... - maxLength = ExtractMaxLengthOfInputs(); - - // - // Define Index Buffers ... - DefineBuffers(); - - // - // Set Indicator ShortName ... - SetIndicatorName(); - - // - // Init Succeed ... - return INIT_SUCCEEDED; -} - -// -// DeInitialization ... -void OnDeinit(const int reason) -{ - // - // REASON_PROGRAM 0 The EA has stopped working calling the ExpertRemove() function - // REASON_REMOVE 1 Program removed from a chart - // REASON_RECOMPILE 2 Program recompiled - // REASON_CHARTCHANGE 3 A symbol or a chart period is changed - // REASON_CHARTCLOSE 4 Chart closed - // REASON_PARAMETERS 5 Inputs changed by a user - // REASON_ACCOUNT 6 Another account has been activated or reconnection to the trade server has occurred due to changes in the account settings - // REASON_TEMPLATE 7 Another chart template applied - // REASON_INITFAILED 8 The OnInit() handler returned a non-zero value - // REASON_CLOSE 9 Terminal closed -} - -// -// Calculating what we want ... -int OnCalculate( - const int rates_total, // Total Bars on Chart ... - const int prev_calculated, // Total Calculated Bars on Charts ... - const datetime &time[], // History of Open Time ... - const double &open[], // History of Open Price ... - const double &high[], // History of High Price ... - const double &low[], // History of Low Price ... - const double &close[], // History of Close Price ... - const long &tick_volume[], // History of Tick Volumes on Bar ... - const long &volume[], // History of Trade Volumes ... - const int &spread[] // History of Spread Price ... - // -) -{ - // - // 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; - - // - limit = (prev_calculated > rates_total || prev_calculated <= 0) ? rates_total : (rates_total - prev_calculated) + 1; - - // - // Main Loop ... - for (int i = limit - 1; i >= 0 && !IsStopped(); i--) - { - CalculateBuffers(i); - } - - // - return rates_total; -} - -// -// Functions ... - -// -// Validate Input Args for Initialization ... -bool ValidateInputs() -{ - // - bool result = - // - (IsValid(scMethod, scPeriod) && - IsValid(mcMethod, mcPeriod) && - IsValid(lcMethod, lcPeriod) && - IsValid(hcMethod, hcPeriod)) - // - ; - - // - return result; -} - -// -// Retrieve all Exists Input Max Length ... -// use for Start Of Drawing ... -int ExtractMaxLengthOfInputs() -{ - // - int result = 0; - - // - result = MathMax(mSCLength, mMCLength); - result = MathMax(result, mLCLength); - result = MathMax(result, mHCLength); - - // - return result; -} - -// -// Define Indexes and Styles ... -void DefineBuffers() -{ - // - // PEAKS and VALES ... - ENUM_DRAW_TYPE pvDrawType = showPeaksAndVales ? DRAW_ARROW : DRAW_NONE; - - // - // PEAKS ... - ArraySetAsSeries(peaksBuffer, true); - SetIndexBuffer(peaksBufferIndex, peaksBuffer, INDICATOR_DATA); - PlotIndexSetInteger(peaksBufferIndex, PLOT_ARROW, 225); - PlotIndexSetDouble(peaksBufferIndex, PLOT_EMPTY_VALUE, 0); - - // - PlotIndexSetInteger(peaksBufferIndex, PLOT_SHOW_DATA, showPeaksAndVales); - PlotIndexSetInteger(peaksBufferIndex, PLOT_DRAW_TYPE, pvDrawType); - - // - // VALES ... - ArraySetAsSeries(valesBuffer, true); - SetIndexBuffer(valesBufferIndex, valesBuffer, INDICATOR_DATA); - PlotIndexSetInteger(valesBufferIndex, PLOT_ARROW, 225); - PlotIndexSetDouble(valesBufferIndex, PLOT_EMPTY_VALUE, 0); - - // - PlotIndexSetInteger(valesBufferIndex, PLOT_SHOW_DATA, showPeaksAndVales); - PlotIndexSetInteger(valesBufferIndex, PLOT_DRAW_TYPE, pvDrawType); - - // - // SUPPORT and RESISTANCE ... - // - - // - // RESISTANCE ... - ArraySetAsSeries(rBuffer, true); - SetIndexBuffer(rBufferIndex, rBuffer, INDICATOR_DATA); - PlotIndexSetInteger(rBufferIndex, PLOT_SHOW_DATA, false); - PlotIndexSetInteger(rBufferIndex, PLOT_DRAW_BEGIN, maxLength); - - // - // RESISTANCE Color ... - ArraySetAsSeries(rColorBuffer, true); - SetIndexBuffer(rColorBufferIndex, rColorBuffer, INDICATOR_COLOR_INDEX); - - // - // SUPPORT ... - ArraySetAsSeries(sBuffer, true); - SetIndexBuffer(sBufferIndex, sBuffer, INDICATOR_DATA); - PlotIndexSetInteger(sBufferPlotIndex, PLOT_DRAW_BEGIN, maxLength); - PlotIndexSetInteger(sBufferPlotIndex, PLOT_SHOW_DATA, false); - - // - // SUPPORT Color ... - ArraySetAsSeries(sColorBuffer, true); - SetIndexBuffer(sColorBufferIndex, sColorBuffer, INDICATOR_COLOR_INDEX); - - // - // FIBBO Levels ... - - // - // LEVEL 1 ... - - // - // Buffer ... - ArraySetAsSeries(fl1Buffer, true); - SetIndexBuffer(fl1BufferIndex, fl1Buffer, INDICATOR_DATA); - PlotIndexSetInteger(fl1BufferPlotIndex, PLOT_DRAW_BEGIN, maxLength); - PlotIndexSetInteger(fl1BufferPlotIndex, PLOT_SHOW_DATA, showFibo1Levels); - - // - // Color ... - ArraySetAsSeries(fl1ColorBuffer, true); - SetIndexBuffer(fl1ColorBufferIndex, fl1ColorBuffer, INDICATOR_COLOR_INDEX); - - // - // LEVEL 2 ... - - // - // Buffer ... - ArraySetAsSeries(fl2Buffer, true); - SetIndexBuffer(fl2BufferIndex, fl2Buffer, INDICATOR_DATA); - PlotIndexSetInteger(fl2BufferPlotIndex, PLOT_DRAW_BEGIN, maxLength); - PlotIndexSetInteger(fl2BufferPlotIndex, PLOT_SHOW_DATA, showFibo2Levels); - - // - // Color ... - ArraySetAsSeries(fl2ColorBuffer, true); - SetIndexBuffer(fl2ColorBufferIndex, fl2ColorBuffer, INDICATOR_COLOR_INDEX); - - // - // LEVEL 3 ... - - // - // Buffer ... - ArraySetAsSeries(fl3Buffer, true); - SetIndexBuffer(fl3BufferIndex, fl3Buffer, INDICATOR_DATA); - PlotIndexSetInteger(fl3BufferPlotIndex, PLOT_DRAW_BEGIN, maxLength); - PlotIndexSetInteger(fl3BufferPlotIndex, PLOT_SHOW_DATA, showFibo3Levels); - - // - // Color ... - ArraySetAsSeries(fl3ColorBuffer, true); - SetIndexBuffer(fl3ColorBufferIndex, fl3ColorBuffer, INDICATOR_COLOR_INDEX); - - // - // LEVEL 4 ... - - // - // Buffer ... - ArraySetAsSeries(fl4Buffer, true); - SetIndexBuffer(fl4BufferIndex, fl4Buffer, INDICATOR_DATA); - PlotIndexSetInteger(fl4BufferPlotIndex, PLOT_DRAW_BEGIN, maxLength); - PlotIndexSetInteger(fl4BufferPlotIndex, PLOT_SHOW_DATA, showFibo4Levels); - - // - // Color ... - ArraySetAsSeries(fl4ColorBuffer, true); - SetIndexBuffer(fl4ColorBufferIndex, fl4ColorBuffer, INDICATOR_COLOR_INDEX); - - // - // LEVEL 5 ... - - // - // Buffer ... - ArraySetAsSeries(fl5Buffer, true); - SetIndexBuffer(fl5BufferIndex, fl5Buffer, INDICATOR_DATA); - PlotIndexSetInteger(fl5BufferPlotIndex, PLOT_DRAW_BEGIN, maxLength); - PlotIndexSetInteger(fl5BufferPlotIndex, PLOT_SHOW_DATA, showFibo5Levels); - - // - // Color ... - ArraySetAsSeries(fl5ColorBuffer, true); - SetIndexBuffer(fl5ColorBufferIndex, fl5ColorBuffer, INDICATOR_COLOR_INDEX); - - // - // SHORT Buffers ... - - // - // HIGH ... - ArraySetAsSeries(scHHBuffer, true); - SetIndexBuffer(scHHBufferIndex, scHHBuffer, INDICATOR_DATA); - - // - PlotIndexSetInteger(scHHBufferPlotIndex, PLOT_DRAW_BEGIN, maxLength); - PlotIndexSetInteger(scHHBufferPlotIndex, PLOT_SHOW_DATA, showLevels); - - // - ArraySetAsSeries(scHHColorBuffer, true); - SetIndexBuffer(scHHColorBufferIndex, scHHColorBuffer, INDICATOR_COLOR_INDEX); - - // - // LOW ... - ArraySetAsSeries(scLLBuffer, true); - SetIndexBuffer(scLLBufferIndex, scLLBuffer, INDICATOR_DATA); - - // - PlotIndexSetInteger(scLLBufferPlotIndex, PLOT_DRAW_BEGIN, maxLength); - PlotIndexSetInteger(scLLBufferPlotIndex, PLOT_SHOW_DATA, showLevels); - - // - ArraySetAsSeries(scLLColorBuffer, true); - SetIndexBuffer(scLLColorBufferIndex, scLLColorBuffer, INDICATOR_COLOR_INDEX); - - // - // MEDIUM Buffer ... - - // - // HIGH ... - ArraySetAsSeries(mcHHBuffer, true); - SetIndexBuffer(mcHHBufferIndex, mcHHBuffer, INDICATOR_DATA); - - // - PlotIndexSetInteger(mcHHBufferPlotIndex, PLOT_DRAW_BEGIN, maxLength); - PlotIndexSetInteger(mcHHBufferPlotIndex, PLOT_SHOW_DATA, showLevels); - - // - ArraySetAsSeries(mcHHColorBuffer, true); - SetIndexBuffer(mcHHColorBufferIndex, mcHHColorBuffer, INDICATOR_COLOR_INDEX); - - // - // LOW ... - ArraySetAsSeries(mcLLBuffer, true); - SetIndexBuffer(mcLLBufferIndex, mcLLBuffer, INDICATOR_DATA); - - // - PlotIndexSetInteger(mcLLBufferPlotIndex, PLOT_DRAW_BEGIN, maxLength); - PlotIndexSetInteger(mcLLBufferPlotIndex, PLOT_SHOW_DATA, showLevels); - - // - ArraySetAsSeries(mcLLColorBuffer, true); - SetIndexBuffer(mcLLColorBufferIndex, mcLLColorBuffer, INDICATOR_COLOR_INDEX); - - // - // LONG Buffer ... - - // - // HIGH ... - ArraySetAsSeries(lcHHBuffer, true); - SetIndexBuffer(lcHHBufferIndex, lcHHBuffer, INDICATOR_DATA); - - // - PlotIndexSetInteger(lcHHBufferPlotIndex, PLOT_DRAW_BEGIN, maxLength); - PlotIndexSetInteger(lcHHBufferPlotIndex, PLOT_SHOW_DATA, showLevels); - - // - ArraySetAsSeries(lcHHColorBuffer, true); - SetIndexBuffer(lcHHColorBufferIndex, lcHHColorBuffer, INDICATOR_COLOR_INDEX); - - // - // LOW ... - ArraySetAsSeries(lcLLBuffer, true); - SetIndexBuffer(lcLLBufferIndex, lcLLBuffer, INDICATOR_DATA); - - // - PlotIndexSetInteger(lcLLBufferPlotIndex, PLOT_DRAW_BEGIN, maxLength); - PlotIndexSetInteger(lcLLBufferPlotIndex, PLOT_SHOW_DATA, showLevels); - - // - ArraySetAsSeries(lcLLColorBuffer, true); - SetIndexBuffer(lcLLColorBufferIndex, lcLLColorBuffer, INDICATOR_COLOR_INDEX); - - // - // HIND Buffer ... - - // - // HIGH ... - ArraySetAsSeries(hcHHBuffer, true); - SetIndexBuffer(hcHHBufferIndex, hcHHBuffer, INDICATOR_DATA); - - // - PlotIndexSetInteger(hcHHBufferPlotIndex, PLOT_DRAW_BEGIN, maxLength); - PlotIndexSetInteger(hcHHBufferPlotIndex, PLOT_SHOW_DATA, showLevels); - - // - ArraySetAsSeries(hcHHColorBuffer, true); - SetIndexBuffer(hcHHColorBufferIndex, hcHHColorBuffer, INDICATOR_COLOR_INDEX); - - // - // LOW ... - ArraySetAsSeries(hcLLBuffer, true); - SetIndexBuffer(hcLLBufferIndex, hcLLBuffer, INDICATOR_DATA); - - // - PlotIndexSetInteger(hcLLBufferPlotIndex, PLOT_DRAW_BEGIN, maxLength); - PlotIndexSetInteger(hcLLBufferPlotIndex, PLOT_SHOW_DATA, showLevels); - - // - ArraySetAsSeries(hcLLColorBuffer, true); - SetIndexBuffer(hcLLColorBufferIndex, hcLLColorBuffer, INDICATOR_COLOR_INDEX); -} - -// -// Set Indicator Short Name and also we can define Buffers Labels ... -void SetIndicatorName() -{ - IndicatorSetString(INDICATOR_SHORTNAME, ShortName); -} - -// -// Calculate Buffers ... -void CalculateBuffers( - int bar_index // Selected Bar Index -) -{ - // - // Calculate Cycles ... - CalculateCycles(bar_index); - - // - // Calculate Peaks and Vales ... - CalculatePeaksAndVales(bar_index); - - // - // Calculate Fibonnaci ... - CalculateFibonacci(bar_index); -} - -// -// Custom ... - -// -// Initial Market Cycles ... -bool InitMarketCycles() -{ - // - bool result = false; - - // - int cPeriodSeconds = PeriodSeconds(_Period); - - // - // Find Cycle Period ... - if (scMethod == X_PERIOD_AUTO) - { - // - // Select Period ... - mSCPeriod = GetCyclePeriod( - X_MARKET_CYCLE_SHORT, - _Period // - ); - } - else - { - mSCPeriod = scPeriod; - } - - // - if (IsValid(mSCPeriod)) - { - mSCLength = PeriodSeconds(mSCPeriod) / cPeriodSeconds; - } - - // - // Find Cycle Period ... - if (mcMethod == X_PERIOD_AUTO) - { - // - // Select Period ... - mMCPeriod = GetCyclePeriod( - X_MARKET_CYCLE_MEDIUM, - _Period // - ); - } - else - { - mMCPeriod = mcPeriod; - } - - // - if (IsValid(mMCPeriod)) - { - mMCLength = PeriodSeconds(mMCPeriod) / cPeriodSeconds; - } - - // - // Find Cycle Period ... - if (lcMethod == X_PERIOD_AUTO) - { - // - // Select Period ... - mLCPeriod = GetCyclePeriod( - X_MARKET_CYCLE_LONG, - _Period // - ); - } - else - { - mLCPeriod = lcPeriod; - } - - // - if (IsValid(mLCPeriod)) - { - mLCLength = PeriodSeconds(mLCPeriod) / cPeriodSeconds; - } - - // - // Find Cycle Period ... - if (hcMethod == X_PERIOD_AUTO) - { - // - // Select Period ... - mHCPeriod = GetCyclePeriod( - X_MARKET_CYCLE_HIND, - _Period // - ); - } - else - { - mHCPeriod = hcPeriod; - } - - // - if (IsValid(mHCPeriod)) - { - mHCLength = PeriodSeconds(mHCPeriod) / cPeriodSeconds; - } - - // - result = mSCLength > 0 && - mMCLength > mSCLength && - mLCLength > mMCLength && - mHCLength > mLCLength; - - // - return result; -} - -// -// Calculate Specified Cycles HH and LL ... -void CalculateCycle( - int barIndex, - ENUM_X_MARKET_CYCLES cycle, - double &lastHH, - double &hhBuffer[], - double &hhColorBuffer[], - double &lastLL, - double &llBuffer[], - double &llColorBuffer[] // -) -{ - // - XOHCL bar; - bar.Init( - _Symbol, - _Period, - barIndex - // - ); - - // - 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; - } - - // - double hhValue = bar.FindHighest( - mLength, - hhMode - // - ); - hhBuffer[barIndex] = hhValue; - - // - double hhColorIDX = - !showLevels - ? mHideColorIDX - : (hhValue == lastHH) - ? !showConsolidations - ? mHideColorIDX - : 1 - : hhValue > lastHH - ? 2 - : hhValue < lastHH - ? 3 - : mHideColorIDX; - hhColorBuffer[barIndex] = hhColorIDX; - - // - lastHH = hhValue; - - // - double llValue = bar.FindLowest( - mLength, - llMode - // - ); - llBuffer[barIndex] = llValue; - - // - double llColorIDX = - !showLevels - ? mHideColorIDX - : (llValue == lastLL) - ? !showConsolidations - ? mHideColorIDX - : 1 - : llValue > lastLL - ? 2 - : llValue < lastLL - ? 3 - : mHideColorIDX; - llColorBuffer[barIndex] = llColorIDX; - - // - lastLL = llValue; -} - -// -// Calculate Cycles Up and Down Boundaries ... -void CalculateCycles( - int barIndex // Bar Index -) -{ - // - // Short ... - CalculateCycle( - barIndex, - X_MARKET_CYCLE_SHORT, - // - mLastSCHH, - scHHBuffer, - scHHColorBuffer, - // - mLastSCLL, - scLLBuffer, - scLLColorBuffer - // - ); - - // - // Medium ... - CalculateCycle( - barIndex, - X_MARKET_CYCLE_MEDIUM, - // - mLastMCHH, - mcHHBuffer, - mcHHColorBuffer, - // - mLastMCLL, - mcLLBuffer, - mcLLColorBuffer - // - ); - - // - // Long ... - CalculateCycle( - barIndex, - X_MARKET_CYCLE_LONG, - // - mLastLCHH, - lcHHBuffer, - lcHHColorBuffer, - // - mLastLCLL, - lcLLBuffer, - lcLLColorBuffer - // - ); - - // - // Hind ... - CalculateCycle( - barIndex, - X_MARKET_CYCLE_HIND, - // - mLastHCHH, - hcHHBuffer, - hcHHColorBuffer, - // - mLastHCLL, - hcLLBuffer, - hcLLColorBuffer - // - ); -} - -// -// Calculate Peaks and Values ... -void CalculatePeaksAndVales( - int barIndex // Bar Index -) -{ - // - // Retrieve Requirements ... - - // - // Short ... - double scHHValue = scHHBuffer[barIndex]; - double scLLValue = scLLBuffer[barIndex]; - - // - // Medium ... - double mcHHValue = mcHHBuffer[barIndex]; - double mcLLValue = mcLLBuffer[barIndex]; - - // - // Long ... - double lcHHValue = lcHHBuffer[barIndex]; - double lcLLValue = lcLLBuffer[barIndex]; - - // - // Hind ... - double hcHHValue = hcHHBuffer[barIndex]; - double hcLLValue = hcLLBuffer[barIndex]; - - // - double rColorIDX = mHideColorIDX; - double sColorIDX = mHideColorIDX; - - // - // RESISTANCE ... - double rValue = (scHHValue + mcHHValue + lcHHValue + hcHHValue) / 4; - - // - // PEAKS ... - bool isPeak = rValue == hcHHValue && - hcHHValue == lcHHValue && - lcHHValue == mcHHValue && - mcHHValue == scHHValue; - - // - if (isPeak && lastPeak != rValue) - { - // - rColorIDX = 1; - lastPeak = rValue; - } - - // - // SUPPORT ... - double sValue = (scLLValue + mcLLValue + lcLLValue + hcLLValue) / 4; - - // - // VALES ... - bool isVale = sValue == hcLLValue && - hcLLValue == lcLLValue && - lcLLValue == mcLLValue && - mcLLValue == scLLValue; - - // - if (isVale && lastVale != sValue) - { - // - sColorIDX = 1; - - // - lastVale = sValue; - } - - // - rBuffer[barIndex] = rValue; - sBuffer[barIndex] = sValue; - peaksBuffer[barIndex] = lastPeak; - valesBuffer[barIndex] = lastVale; - - // - if (showPeaksAndVales) - { - // - rColorBuffer[barIndex] = rColorIDX; - sColorBuffer[barIndex] = sColorIDX; - } - else - { - // - rColorBuffer[barIndex] = mHideColorIDX; - sColorBuffer[barIndex] = mHideColorIDX; - } -} - -// -// Calculate Fibonacci Level 1 ... -void CalculateFibonacci( - int barIndex // Bar Index -) -{ - // - // Select Requirements ... - double upPrice = peaksBuffer[barIndex]; - double downPrice = valesBuffer[barIndex]; - - // - // Level 1 ... - double fibLevel1Value = GetFibonacciLevel( - upPrice, - downPrice, - fiboLevel1, - 1); - // - // Level 2 ... - double fibLevel2Value = GetFibonacciLevel( - upPrice, - downPrice, - fiboLevel2, - 1); - - // - // Level 3 ... - double fibLevel3Value = GetFibonacciLevel( - upPrice, - downPrice, - fiboLevel3, - 1); - - // - // Level 4 ... - double fibLevel4Value = GetFibonacciLevel( - upPrice, - downPrice, - fiboLevel4, - 1); - - // - // Level 5 ... - double fibLevel5Value = GetFibonacciLevel( - upPrice, - downPrice, - fiboLevel5, - 1); - - // - fl1Buffer[barIndex] = fibLevel1Value; - fl2Buffer[barIndex] = fibLevel2Value; - fl3Buffer[barIndex] = fibLevel3Value; - fl4Buffer[barIndex] = fibLevel4Value; - fl5Buffer[barIndex] = fibLevel5Value; - - // - double fl1ColorIdx = showFibo1Levels ? 1 : mHideColorIDX; - double fl2ColorIdx = showFibo2Levels ? 1 : mHideColorIDX; - double fl3ColorIdx = showFibo3Levels ? 1 : mHideColorIDX; - double fl4ColorIdx = showFibo4Levels ? 1 : mHideColorIDX; - double fl5ColorIdx = showFibo5Levels ? 1 : mHideColorIDX; - - // - fl1ColorBuffer[barIndex] = fl1ColorIdx; - fl2ColorBuffer[barIndex] = fl2ColorIdx; - fl3ColorBuffer[barIndex] = fl3ColorIdx; - fl4ColorBuffer[barIndex] = fl4ColorIdx; - fl5ColorBuffer[barIndex] = fl5ColorIdx; -} - -// \ No newline at end of file diff --git a/Documents/Pack/V1.0/Source/Indicators/x-saherelm.xsln.mq5 b/Documents/Pack/V1.0/Source/Indicators/x-saherelm.xsln.mq5 deleted file mode 100644 index ca38f492..00000000 --- a/Documents/Pack/V1.0/Source/Indicators/x-saherelm.xsln.mq5 +++ /dev/null @@ -1,279 +0,0 @@ -/////////////////////////////////////////////////////// -// SaherElm IT Center MQL5 Indicator -// ------------------------------------------- -// Name: XSLN -// Description: HULL Trend Detector ... -// -// 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 XSLN Indicator" -#property strict - -// -#define ShortName "XSLN" - -// -// Imports ... -#include "../Libraries/x-saherelm.common.lib.mq5" - -// -// Inputs ... - -// -input group "Presentation"; -input bool show = true; // Show - -// -// Buffers ... - -// -#property indicator_chart_window - -// -#property indicator_buffers 3 -#property indicator_plots 2 - -// -#define mainBufferIndex 0 -double mainBuffer[]; - -// -#define mainBufferColorIndex 1 -double mainBufferColor[]; - -// -#define stateBufferIndex 2 -double stateBuffer[]; - -// -#define hideColorIDX 0 -#define bullColorIDX 1 -#define bearColorIDX 2 - -// -#property indicator_label1 "XSLN" -#property indicator_type1 DRAW_COLOR_LINE -#property indicator_color1 CLR_NONE, clrGreen, clrDarkRed -#property indicator_style1 STYLE_DOT -#property indicator_width1 1 - -// -// Variables ... - -// -double work[][5]; -#define hHi 0 -#define hLo 1 -#define lHi 2 -#define lLo 3 -#define trend 4 - -// -// Event Handlers ... - -// -// Initialization ... -int OnInit() -{ - // - // Validate Inputs ... - if (!ValidateInputs()) - { - return INIT_PARAMETERS_INCORRECT; - } - - // - // Define Index Buffers ... - DefineBuffers(); - - // - // Set Indicator ShortName ... - SetIndicatorName(); - - // - // Init Succeed ... - return INIT_SUCCEEDED; -} - -// -// DeInitialization ... -void OnDeinit(const int reason) -{ - // - // REASON_PROGRAM 0 The EA has stopped working calling the ExpertRemove() function - // REASON_REMOVE 1 Program removed from a chart - // REASON_RECOMPILE 2 Program recompiled - // REASON_CHARTCHANGE 3 A symbol or a chart period is changed - // REASON_CHARTCLOSE 4 Chart closed - // REASON_PARAMETERS 5 Inputs changed by a user - // REASON_ACCOUNT 6 Another account has been activated or reconnection to the trade server has occurred due to changes in the account settings - // REASON_TEMPLATE 7 Another chart template applied - // REASON_INITFAILED 8 The OnInit() handler returned a non-zero value - // REASON_CLOSE 9 Terminal closed -} - -// -// Calculating what we want ... -int OnCalculate( - const int rates_total, // Total Bars on Chart ... - const int prev_calculated, // Total Calculated Bars on Charts ... - const datetime &time[], // History of Open Time ... - const double &open[], // History of Open Price ... - const double &high[], // History of High Price ... - const double &low[], // History of Low Price ... - const double &close[], // History of Close Price ... - const long &tick_volume[], // History of Tick Volumes on Bar ... - const long &volume[], // History of Trade Volumes ... - const int &spread[] // History of Spread Price ... -) -{ - // - if (ArrayRange(work, 0) != rates_total) - { - // - ArrayResize(work, rates_total); - ArrayResize(stateBuffer, rates_total); - } - - // - for (int i = (int)MathMax(prev_calculated - 1, 0); i < rates_total; i++) - { - // - if (i == 0) - { - // - work[i][hHi] = high[i]; - work[i][hLo] = low[i]; - work[i][lHi] = high[i]; - work[i][lLo] = low[i]; - work[i][trend] = -1; - stateBuffer[i] = -1; - continue; - } - - // - work[i][trend] = work[i - 1][trend]; - work[i][hHi] = work[i - 1][hHi]; - work[i][hLo] = work[i - 1][hLo]; - work[i][lHi] = work[i - 1][lHi]; - work[i][lLo] = work[i - 1][lLo]; - - // - if (work[i - 1][trend] == 1) - { - // - work[i][hHi] = MathMax(work[i - 1][hHi], high[i]); - work[i][hLo] = MathMax(work[i - 1][hLo], low[i]); - - // - if (high[i] < work[i][hLo]) - { - // - work[i][trend] = -1; - work[i][lHi] = high[i]; - work[i][lLo] = low[i]; - } - } - - // - if (work[i - 1][trend] == -1) - { - // - work[i][lHi] = MathMin(work[i - 1][lHi], high[i]); - work[i][lLo] = MathMin(work[i - 1][lLo], low[i]); - - // - if (low[i] > work[i][lHi]) - { - // - work[i][trend] = 1; - work[i][hHi] = high[i]; - work[i][hLo] = low[i]; - } - } - - // - if (work[i][trend] == 1) - { - mainBuffer[i] = work[i][hLo]; - } - else - { - mainBuffer[i] = work[i][lHi]; - } - - // - stateBuffer[i] = stateBuffer[i - 1]; - mainBufferColor[i] = mainBufferColor[i - 1]; - - // - if (work[i][trend] == 1) - { - // - stateBuffer[i] = 1; - mainBufferColor[i] = bullColorIDX; - } - - // - if (work[i][trend] == -1) - { - // - stateBuffer[i] = -1; - mainBufferColor[i] = bearColorIDX; - } - } - - // - return rates_total; -} - -// -// Custom Functions ... - -// -// Validate Input Args for Initialization ... -bool ValidateInputs() -{ - // - bool result = false; - - // - result = true; - - // - return result; -} - -// -// Set Indicator Short Name and also we can define Buffers Labels ... -void SetIndicatorName() -{ - IndicatorSetString(INDICATOR_SHORTNAME, ShortName); -} - -// -// Define Indexes and Styles ... -void DefineBuffers() -{ - // - // Main ... - ENUM_DRAW_TYPE mainDrawType = show ? DRAW_COLOR_LINE : DRAW_NONE; - - PlotIndexSetInteger(mainBufferIndex, PLOT_SHOW_DATA, true); - SetIndexBuffer(mainBufferIndex, mainBuffer, INDICATOR_DATA); - PlotIndexSetInteger(mainBufferIndex, PLOT_DRAW_TYPE, mainDrawType); - SetIndexBuffer(mainBufferColorIndex, mainBufferColor, INDICATOR_COLOR_INDEX); - - // - SetIndexBuffer(stateBufferIndex, stateBuffer, INDICATOR_CALCULATIONS); -} - -// \ No newline at end of file diff --git a/Documents/Pack/V1.0/Source/Indicators/x-saherelm.xsslc.mq5 b/Documents/Pack/V1.0/Source/Indicators/x-saherelm.xsslc.mq5 deleted file mode 100644 index 620cb249..00000000 --- a/Documents/Pack/V1.0/Source/Indicators/x-saherelm.xsslc.mq5 +++ /dev/null @@ -1,440 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Indicator -// ---------------------------------------------------- -// Name: XSSLC -// Description: SSL Channel Indicator -// -// -// Maintainer: -// ------------ -// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) -// -////////////////////////////////////////////////////// -// -// Global Properties ... -#property copyright "Copyright 2023, SaherElm IT Center" -#property link "https://saherelm.ir" -#property version "1.00" -#property description "SaherElm XSSLC Indicator" -#property strict - -// -// START Constants ... -// - -// -// Indicator Short Name ... -#define ShortName "XSSLC" - -// -// END Constants ... -// - -// -// START Inputs ... -// - -// -input group "Market"; -input int length = 36; // Length - -// -input group "Calculation"; -input ENUM_MA_METHOD method = MODE_SMA; // Method -input ENUM_APPLIED_PRICE upAppliedTo = PRICE_HIGH; // Up Applied To -input ENUM_APPLIED_PRICE downAppliedTo = PRICE_LOW; // Down Applied To - -// -input group "Presentation"; -input bool showUp = true; // Show Up -input bool showDown = true; // Show Down - -// -// END Inputs ... -// - -// -// START Includes and Imports ... -// - -// -// Includes Common Library ... -#include "../Libraries/x-saherelm.common.lib.mq5" - -// -// END Includes and Imports ... -// - -// -// START Buffers ... -// -#property indicator_chart_window - -// -#property indicator_buffers 5 -#property indicator_plots 2 - -// -// PLOTTED Buffers ... - -// -#define upBufferIndex 0 -double upBuffer[]; - -// -#property indicator_label1 "XSSLC Up" -#property indicator_type1 DRAW_LINE -#property indicator_color1 clrLime -#property indicator_style1 STYLE_SOLID -#property indicator_width1 1 - -// -#define downBufferIndex 1 -double downBuffer[]; - -// -#property indicator_label2 "XSSLC Down" -#property indicator_type2 DRAW_LINE -#property indicator_color2 clrRed -#property indicator_style2 STYLE_SOLID -#property indicator_width2 1 - -// -// DATA Buffers ... - -// -#define upMaBufferIndex 2 -double upMaBuffer[]; - -// -#define downMaBufferIndex 3 -double downMaBuffer[]; - -// -#define kpiBufferIndex 4 -double kpiBuffer[]; - -// -// END Buffers ... -// - -// -// START Global Definitions: Variables, Properties and etc ... -// - -// -int maxLength; - -// -int upHandler = INVALID_HANDLE; -int downHandler = INVALID_HANDLE; - -// -// END Global Definitions: Variables, Properties and etc ... -// - -// -// START Event Handlers ... -// - -// -// Initialization ... -int OnInit() -{ - // - // Validate Inputs ... - if (!ValidateInputs()) - { - return INIT_PARAMETERS_INCORRECT; - } - - // - // because in some cases we may have more than one input for - // calculation and we must prevent any calculation - // untill we pass the biggest input length, here we get max Input length - // and then wait until pass it ... - maxLength = ExtractMaxLengthOfInputs(); - - // - // Define Index Buffers ... - DefineBuffers(); - - // - // Set Indicator ShortName ... - SetIndicatorName(); - - // - // Initialize Requierd Handlers ... - upHandler = iMA( - _Symbol, - _Period, - length, - 0, - method, - upAppliedTo); - downHandler = iMA( - _Symbol, - _Period, - length, - 0, - method, - downAppliedTo); - if (upHandler == INVALID_HANDLE || downHandler == INVALID_HANDLE) - { - // - string msg = "Error in Initilizing Indicator ..."; - Print(msg); - - // - 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 - - // - // Release Indicators ... - IndicatorRelease(upHandler); - IndicatorRelease(downHandler); -} - -// -// 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 upCalculatedBars = BarsCalculated(upHandler); - int downCalculatedBars = BarsCalculated(downHandler); - if (upCalculatedBars < maxLength || - downCalculatedBars < maxLength) - { - return prev_calculated; - } - - // - limit = (prev_calculated > rates_total || prev_calculated <= 0) ? rates_total : (rates_total - prev_calculated) + 1; - - // - // Buffers Copy ... - int copiedUps = CopyBuffer(upHandler, 0, 0, limit, upMaBuffer); - int copiedDowns = CopyBuffer(downHandler, 0, 0, limit, downMaBuffer); - if (copiedUps <= 0 || - copiedDowns <= 0) - { - return prev_calculated; - } - - // - // Main Loop ... - for (int i = limit - 1; i >= 0 && !IsStopped(); i--) - { - CalculateBuffers(i, limit, rates_total, prev_calculated, close); - } - - // - return rates_total; -} - -// -// END Event Handlers ... -// - -// -// START Functions ... -// - -// -// Validate Input Args for Initialization ... -bool ValidateInputs() -{ - // - bool result = - // - (length > 2) - // - ; - - // - return result; -} - -// -// Retrieve all Exists Input Max Length ... -// use for Start Of Drawing ... -int ExtractMaxLengthOfInputs() -{ - // - int result = 0; - - // - result = MathMax(result, length); - - // - return result; -} - -// -// Define Indexes and Styles ... -void DefineBuffers() -{ - // - // UP ... - - // - ENUM_DRAW_TYPE upDrawType = showUp ? DRAW_LINE : DRAW_NONE; - - ArraySetAsSeries(upBuffer, true); - SetIndexBuffer(upBufferIndex, upBuffer, INDICATOR_DATA); - PlotIndexSetInteger(upBufferIndex, PLOT_SHOW_DATA, showUp); - PlotIndexSetInteger(upBufferIndex, PLOT_DRAW_BEGIN, maxLength); - PlotIndexSetInteger(upBufferIndex, PLOT_DRAW_TYPE, upDrawType); - - // - // DOWN ... - - // - ENUM_DRAW_TYPE downDrawType = showDown ? DRAW_LINE : DRAW_NONE; - - ArraySetAsSeries(downBuffer, true); - SetIndexBuffer(downBufferIndex, downBuffer, INDICATOR_DATA); - PlotIndexSetInteger(downBufferIndex, PLOT_SHOW_DATA, showDown); - PlotIndexSetInteger(downBufferIndex, PLOT_DRAW_BEGIN, maxLength); - PlotIndexSetInteger(downBufferIndex, PLOT_DRAW_TYPE, downDrawType); - - // - // DATA Buffers ... - - // - // UP MA ... - ArraySetAsSeries(upMaBuffer, true); - SetIndexBuffer(upMaBufferIndex, upMaBuffer, INDICATOR_CALCULATIONS); - - // - // DOWN MA ... - ArraySetAsSeries(downMaBuffer, true); - SetIndexBuffer(downMaBufferIndex, downMaBuffer, INDICATOR_CALCULATIONS); - - // - // KPI ... - ArraySetAsSeries(kpiBuffer, true); - SetIndexBuffer(kpiBufferIndex, kpiBuffer, INDICATOR_CALCULATIONS); -} - -// -// Set Indicator Short Name and also we can define Buffers Labels ... -void SetIndicatorName() -{ - IndicatorSetString(INDICATOR_SHORTNAME, ShortName); -} - -// -// Calculate Buffers ... -void CalculateBuffers( - int bar_index, // Selected Bar Index - int limit, - int ratesTotal, - int prevCalculated, - const double &close[]) -{ - // - double upMaValue = upMaBuffer[bar_index]; - double downMaValue = downMaBuffer[bar_index]; - - // - double closeValue = close[bar_index]; - - // - double kpiValue; - if (closeValue > upMaValue) - { - kpiValue = 1; - } - else if (closeValue < downMaValue) - { - kpiValue = -1; - } - else - { - kpiValue = kpiBuffer[bar_index + 1]; - } - - // - kpiBuffer[bar_index] = kpiValue; - - // - double upValue = kpiValue < 0 ? downMaValue : upMaValue; - upBuffer[bar_index] = upValue; - - // - double downValue = kpiValue < 0 ? upMaValue : downMaValue; - downBuffer[bar_index] = downValue; -} - -// -// END Functions ... -// diff --git a/Documents/Pack/V1.0/Source/Indicators/x-saherelm.xstr.mq5 b/Documents/Pack/V1.0/Source/Indicators/x-saherelm.xstr.mq5 deleted file mode 100644 index 90e6eeb9..00000000 --- a/Documents/Pack/V1.0/Source/Indicators/x-saherelm.xstr.mq5 +++ /dev/null @@ -1,580 +0,0 @@ -////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Indicator -// --------------------------------------------- -// Name: XSTR -// Description: Super Trend Indicator ... -// -// -// Maintainer: -// ------------ -// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) -// -////////////////////////////////////////////////////// -// -// Global Properties ... -#property copyright "Copyright 2023, SaherElm IT Center" -#property link "https://saherelm.ir" -#property version "1.00" -#property description "SaherElm X121_XAMA Indicator" -#property strict - -// -// START Constants ... -// - -#define ShortName "XSTR" - -// -// END Constants ... -// - -// -// START Inputs ... -// - -// -// Market ... -input group "ATR"; -input int atrLength = 14; // Length -input double atrMultiplier = 3.0; // Multiplier -input ENUM_APPLIED_PRICE atrAppliedTo = PRICE_MEDIAN; // Applied To - -// -// Presentation ... -input group "Presentation"; -input bool showTrends = true; // Show Trends -input bool fillTrends = true; // Fill Trends - -// -// END Inputs ... -// - -// -// Includes Common Library ... -#include "../Libraries/x-saherelm.common.lib.mq5" - -// -// START Buffers ... -// - -// -#property indicator_chart_window - -// -#property indicator_buffers 9 -#property indicator_plots 2 - -// -#define fillUpBufferIndex 0 -double fillUpBuffer[]; - -#define fillDownBufferIndex 1 -double fillDownBuffer[]; - -// -#define fillingPlotBufferIndex 0 - -// -#property indicator_label1 "XSTR Filling" -#property indicator_type1 DRAW_FILLING -#property indicator_color1 clrBisque, clrPaleGreen - -// -#define mainBufferIndex 2 -#define mainPlotBufferIndex 1 -double mainBuffer[]; - -// -#define mainColorBufferIndex 3 -double mainColorBuffer[]; - -// -#property indicator_label2 "XSTR" -#property indicator_type2 DRAW_COLOR_LINE -#property indicator_color2 CLR_NONE, clrGreen, clrDarkRed -#property indicator_style2 STYLE_DOT - -// -// DATA Buffers ... - -// -#define atrBufferIndex 4 -double atrBuffer[]; - -// -#define trendBufferIndex 5 -double trendBuffer[]; - -// -#define upBufferIndex 6 -double upBuffer[]; - -// -#define downBufferIndex 7 -double downBuffer[]; - -// -#define priceBufferIndex 8 -double priceBuffer[]; - -// -// END Buffers ... -// - -// -// START Global Definitions: Variables, Properties and etc ... -// - -// -int maxLength; - -// -int atrHandler = INVALID_HANDLE; - -// -int changeOfTrend; -int startBearishTrend; -int startBullishTrend; - -// -// END Global Definitions: Variables, Properties and etc ... -// - -// -// START Event Handlers ... -// - -// -// Initialization ... -int OnInit() -{ - // - // Validate Inputs ... - if (!ValidateInputs()) - { - return INIT_PARAMETERS_INCORRECT; - } - - // - // because in some cases we may have more than one input for - // calculation and we must prevent any calculation - // untill we pass the biggest input length, here we get max Input length - // and then wait until pass it ... - maxLength = ExtractMaxLengthOfInputs(); - - // - atrHandler = iATR( - _Symbol, - _Period, - atrLength); - if (atrHandler == INVALID_HANDLE) - { - return INIT_FAILED; - } - - // - // Define Index Buffers ... - DefineBuffers(); - - // - // Set Indicator ShortName ... - SetIndicatorName(); - - // - // Init Succeed ... - return INIT_SUCCEEDED; -} - -// -// DeInitialization ... -void OnDeinit(const int reason) -{ - // - // REASON_PROGRAM 0 The EA has stopped working calling the ExpertRemove() function - // REASON_REMOVE 1 Program removed from a chart - // REASON_RECOMPILE 2 Program recompiled - // REASON_CHARTCHANGE 3 A symbol or a chart period is changed - // REASON_CHARTCLOSE 4 Chart closed - // REASON_PARAMETERS 5 Inputs changed by a user - // REASON_ACCOUNT 6 Another account has been activated or reconnection to the trade server has occurred due to changes in the account settings - // REASON_TEMPLATE 7 Another chart template applied - // REASON_INITFAILED 8 The OnInit() handler returned a non-zero value - // REASON_CLOSE 9 Terminal closed - - // - // Here we can handle De Initialization Reasons ... - IndicatorRelease(atrHandler); -} - -// -// 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[]) -{ - // - int numOfRequiredAtrs; - if (prev_calculated > rates_total || prev_calculated < 0) - { - numOfRequiredAtrs = rates_total; - } - else - { - // - numOfRequiredAtrs = rates_total - prev_calculated; - if (prev_calculated > 0) - { - numOfRequiredAtrs++; - } - } - - // - // Checking for stop ... - if (IsStopped()) - { - return 0; - } - - // - // Check Number of items Copy or not ... - int copiedATRs = CopyBuffer(atrHandler, 0, 0, numOfRequiredAtrs, atrBuffer); - if (copiedATRs <= 0) - { - return 0; - } - - // - int limit; - - // - // checking for the limit start of calculation of an indicator ... - if (prev_calculated > rates_total || prev_calculated <= 0) - { - // - // starting index for calculation of all bars ... - limit = maxLength; - } - else - { - // - // starting number for calculation of new bars - limit = prev_calculated - 1; - } - - // - // Main Loop ... - for (int i = limit; i < rates_total && !IsStopped(); i++) - { - // - // Calculated Price ... - double price = getPrice( - atrAppliedTo, - open, - high, - low, - close, - i); - // price = (high[i] + low[i]) / 2; - priceBuffer[i] = price; - - // - double atr = atrBuffer[i]; - - // - // Up ... - upBuffer[i] = price + (atrMultiplier * atr); - - // - // Down ... - downBuffer[i] = price - (atrMultiplier * atr); - - // - if (close[i] > upBuffer[i - 1]) - { - // - trendBuffer[i] = 1; - if (trendBuffer[i - 1] == -1) - { - changeOfTrend = 1; - } - } - else if (close[i] < downBuffer[i - 1]) - { - // - trendBuffer[i] = -1; - if (trendBuffer[i - 1] == 1) - { - changeOfTrend = 1; - } - } - else if (trendBuffer[i - 1] == 1) - { - // - trendBuffer[i] = 1; - changeOfTrend = 0; - } - else if (trendBuffer[i - 1] == -1) - { - // - trendBuffer[i] = -1; - changeOfTrend = 0; - } - - // - // Down Trend Starting ... - if (trendBuffer[i] < 0 && trendBuffer[i - 1] > 0) - { - startBearishTrend = 1; - } - else - { - startBearishTrend = 0; - } - - // - // Up Trend Starting ... - if (trendBuffer[i] > 0 && trendBuffer[i - 1] < 0) - { - startBullishTrend = 1; - } - else - { - startBullishTrend = 0; - } - - // - if (trendBuffer[i] > 0 && downBuffer[i] < downBuffer[i - 1]) - { - downBuffer[i] = downBuffer[i - 1]; - } - - // - if (trendBuffer[i] < 0 && upBuffer[i] > upBuffer[i - 1]) - { - upBuffer[i] = upBuffer[i - 1]; - } - - // - if (startBearishTrend == 1) - { - upBuffer[i] = priceBuffer[i] + (atrMultiplier * atr); - } - - // - if (startBullishTrend == 1) - { - downBuffer[i] = priceBuffer[i] - (atrMultiplier * atr); - } - - // - // Draw the indicator ... - - // - double colorIDX = 0; - mainColorBuffer[i] = colorIDX; - - // - if (trendBuffer[i] == 1) - { - // - mainBuffer[i] = downBuffer[i]; - if (changeOfTrend == 1) - { - mainBuffer[i - 1] = mainBuffer[i - 2]; - changeOfTrend = 0; - } - - // - colorIDX = 1; - } - else if (trendBuffer[i] == -1) - { - // - mainBuffer[i] = upBuffer[i]; - if (changeOfTrend == 1) - { - // - mainBuffer[i - 1] = mainBuffer[i - 2]; - changeOfTrend = 0; - } - - // - colorIDX = 2; - } - - // - if (showTrends) - { - mainColorBuffer[i] = colorIDX; - } - - // - // Filling ... - if (fillTrends) - { - // - fillUpBuffer[i] = mainBuffer[i]; - fillDownBuffer[i] = close[i]; - } - else - { - // - fillUpBuffer[i] = EMPTY_VALUE; - fillDownBuffer[i] = EMPTY_VALUE; - } - } - - // - return rates_total; -} - -// -// END Event Handlers ... -// - -// -// START Functions ... -// - -// -// Validate Input Args for Initialization ... -bool ValidateInputs() -{ - // - bool result = false; - - // - // Validate Args ... - result = - // - atrLength >= 2 - // - ; - - // - return result; -} - -// -// Retrieve all Exists Input Max Length ... -// use for Start Of Drawing ... -int ExtractMaxLengthOfInputs() -{ - // - int result = 0; - - // - result = atrLength; - - // - return result; -} - -// -// Set Indicator Short Name and also we can define Buffers Labels ... -void SetIndicatorName() -{ - IndicatorSetString(INDICATOR_SHORTNAME, ShortName); -} - -// -// Define Indexes and Styles ... -void DefineBuffers() -{ - // - // PLOT Buffers ... - - // - // FILLINGS ... - SetIndexBuffer(fillUpBufferIndex, fillUpBuffer, INDICATOR_DATA); - SetIndexBuffer(fillDownBufferIndex, fillDownBuffer, INDICATOR_DATA); - PlotIndexSetInteger(fillingPlotBufferIndex, PLOT_SHOW_DATA, false); - - // - // MAIN ... - SetIndexBuffer(mainBufferIndex, mainBuffer, INDICATOR_DATA); - PlotIndexSetInteger(mainPlotBufferIndex, PLOT_SHOW_DATA, showTrends); - SetIndexBuffer(mainColorBufferIndex, mainColorBuffer, INDICATOR_COLOR_INDEX); - - // - // DATA Buffers ... - - // - // ATR ... - SetIndexBuffer(atrBufferIndex, atrBuffer, INDICATOR_CALCULATIONS); - - // - // TREND ... - SetIndexBuffer(trendBufferIndex, trendBuffer, INDICATOR_CALCULATIONS); - - // - // UP ... - SetIndexBuffer(upBufferIndex, upBuffer, INDICATOR_CALCULATIONS); - - // - // DOWN ... - SetIndexBuffer(downBufferIndex, downBuffer, INDICATOR_CALCULATIONS); - - // - // PRICE ... - SetIndexBuffer(priceBufferIndex, priceBuffer, INDICATOR_CALCULATIONS); -} - -// -// END Functions ... -// - -// -// TEMPLATE Function ... - -template -double getPrice(ENUM_APPLIED_PRICE tprice, T &open[], T &high[], T &low[], T &close[], int i) -{ - switch (tprice) - { - case PRICE_CLOSE: - return (close[i]); - case PRICE_OPEN: - return (open[i]); - case PRICE_HIGH: - return (high[i]); - case PRICE_LOW: - return (low[i]); - case PRICE_MEDIAN: - return ((high[i] + low[i]) / 2.0); - case PRICE_TYPICAL: - return ((high[i] + low[i] + close[i]) / 3.0); - case PRICE_WEIGHTED: - return ((high[i] + low[i] + close[i] + close[i]) / 4.0); - } - return (0); -} diff --git a/Documents/Pack/V1.0/Source/Indicators/x-saherelm.xtd.mq5 b/Documents/Pack/V1.0/Source/Indicators/x-saherelm.xtd.mq5 deleted file mode 100644 index ca796955..00000000 --- a/Documents/Pack/V1.0/Source/Indicators/x-saherelm.xtd.mq5 +++ /dev/null @@ -1,457 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Trend Detector Oscillator -// -------------------------------------------------- -// Name: XTD -// Description: trend detecting in both sides ... -// -// -// Maintainer: -// ------------ -// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) -// -////////////////////////////////////////////////////// -// -// Global Properties ... -#property copyright "Copyright 2023, SaherElm IT Center" -#property link "https://saherelm.ir" -#property version "1.00" -#property description "SaherElm XTD Oscillator" -#property strict - -// -// START Constants ... -// -#define ShortName "XTD" - -// -// XTD Oscillator States ... -enum ENUM_X_XTD_STATES -{ - X_XTD_BULLISH_CROSSED_OVER_BEARISH = 2, - X_XTD_BULLISH_OVER_BEARISH = 1, - X_XTD_NEUTURAL = 0, - X_XTD_BULLISH_UNDER_BEARISH = -1, - X_XTD_BULLISH_CROSSED_UNDER_BEARISH = -2 -}; -// -// END Constants ... -// - -// -// START Inputs ... -// -input int length = 14; // Market Length -input bool drawCrosses = true; // Draw Cross Arrows - -// -// Bullish ... -input uchar bullishArrowCode = 228; // Cross Over Arrow Code -input color bullishArrowColor = clrAqua; // Cross Over Arrow Color - -// -// Bearish ... -input uchar bearishArrowCode = 230; // Cross Under Arrow Code -input color bearishArrowColor = clrMagenta; // Cross Under Arrow Color -// -// END Inputs ... -// - -// -// Includes Common Library ... -#include "../Libraries/x-saherelm.common.lib.mq5"; - -// -// Includes Draw Library ... -#include "../Libraries/x-saherelm.draw.lib.mq5"; - -// -// START Buffers ... -// -// #property indicator_separate_window -#property indicator_chart_window - -// -#property indicator_buffers 3 -// #property indicator_plots 3 -#property indicator_plots 0 - -// -#define bullishBufferIndex 0 -#define bearishBufferIndex 1 -#define signalBufferIndex 2 - -// -double bullishBuffer[]; -double bearishBuffer[]; -double signalBuffer[]; - -// -// #property indicator_label1 "XBullPower" -// #property indicator_type1 DRAW_LINE -// #property indicator_color1 clrLime -// #property indicator_style1 STYLE_SOLID -// #property indicator_width1 1 - -// -// #property indicator_label2 "XBearPower" -// #property indicator_type2 DRAW_LINE -// #property indicator_color2 clrRed -// #property indicator_style2 STYLE_SOLID -// #property indicator_width2 1 - -// -// #property indicator_label3 "XSignal" -// #property indicator_type3 DRAW_LINE -// #property indicator_color3 clrGold -// #property indicator_style3 STYLE_DOT -// #property indicator_width3 1 -// -// END Buffers ... -// - -// -// START Global Definitions: Variables, Properties and etc ... -// -// -int xtdBullishCandleCount = 0; -int xtdBearishCandleCount = 0; -// -// END Global Definitions: Variables, Properties and etc ... -// - -// -// START Event Handlers ... -// -// -// Initialization ... -int OnInit() -{ - // - // Validate Inputs ... - if (!ValidateInputs()) - { - return INIT_PARAMETERS_INCORRECT; - } - - // - drawPrefix = ShortName; - - // - // Define Index Buffers ... - DefineBuffers(); - - // - // Set Indicator ShortName ... - SetIndicatorName(); - - // - // Init Succeed ... - return INIT_SUCCEEDED; -} - -// -// DeInitialization ... -void OnDeinit(const int reason) -{ - // - // REASON_PROGRAM 0 The EA has stopped working calling the ExpertRemove() function - // REASON_REMOVE 1 Program removed from a chart - // REASON_RECOMPILE 2 Program recompiled - // REASON_CHARTCHANGE 3 A symbol or a chart period is changed - // REASON_CHARTCLOSE 4 Chart closed - // REASON_PARAMETERS 5 Inputs changed by a user - // REASON_ACCOUNT 6 Another account has been activated or reconnection to the trade server has occurred due to changes in the account settings - // REASON_TEMPLATE 7 Another chart template applied - // REASON_INITFAILED 8 The OnInit() handler returned a non-zero value - // REASON_CLOSE 9 Terminal closed - - // - // Here we can handle De Initialization Reasons ... -} - -// -// Calculations ... -// -// Calculating what we want ... -int OnCalculate( - // - // total Candles on chart ... - const int rates_total, - // - // total calculated Candles on charts ... - const int prev_calculated, - // - // history of Candles Open Time ... - const datetime &time[], - // - // history of Candles Open Price ... - const double &open[], - // - // history of Candles High Price ... - const double &high[], - // - // history of Candles Low Price ... - const double &low[], - // - // history of Candles Close Price ... - const double &close[], - // - // history of Tick Volumes on Candle ... - const long &tick_volume[], - // - // history of Trade Volumes ... - const long &volume[], - // - // history of Candles Spread Price ... - const int &spread[]) -{ - // - // Prepare Buffers ... - ArraySetAsSeries(time, true); - ArraySetAsSeries(open, true); - ArraySetAsSeries(high, true); - ArraySetAsSeries(low, true); - ArraySetAsSeries(close, true); - ArraySetAsSeries(tick_volume, true); - ArraySetAsSeries(volume, true); - ArraySetAsSeries(spread, true); - - // - // this counts Available Bars ... - int limit; - - // - // because in some cases we may have more than one input for - // calculation and we must prevent any calculation - // untill we pass the biggest input length, here we get max Input length - // and then wait until pass it ... - int maxLength = MathMax(0, length); - - // - limit = prev_calculated < maxLength ? rates_total - (maxLength + 1) : rates_total - prev_calculated; - - // - // Main Loop ... - for (int i = limit; i >= 0 && !IsStopped(); i--) - { - // - CalculateBuffers(i, close); - } - - // - return rates_total; -} -// -// END Event Handlers ... -// - -// -// START Functions ... -// -// -// Validate Input Args for Initialization ... -bool ValidateInputs() -{ - // - bool result = false; - - // - // Validate Args ... - if (length >= 5) - { - result = true; - } - - // - return result; -} - -// -// Define Indexes and Styles ... -void DefineBuffers() -{ - // - // Bullish Buffer ... - string bullishBufferLabel = ShortName + "BullPow " + "(" + (string)length + ")"; - ArraySetAsSeries(bullishBuffer, true); - SetIndexBuffer(bullishBufferIndex, bullishBuffer, INDICATOR_CALCULATIONS); - // SetIndexBuffer(bullishBufferIndex, bullishBuffer, INDICATOR_DATA); - // PlotIndexSetInteger(bullishBufferIndex, PLOT_DRAW_BEGIN, length); - // PlotIndexSetString(bullishBufferIndex, PLOT_LABEL, bullishBufferLabel); - - // - // Bearish Buffer ... - string bearishBufferLabel = ShortName + "BearPow " + "(" + (string)length + ")"; - ArraySetAsSeries(bearishBuffer, true); - SetIndexBuffer(bearishBufferIndex, bearishBuffer, INDICATOR_CALCULATIONS); - // SetIndexBuffer(bearishBufferIndex, bearishBuffer, INDICATOR_DATA); - // PlotIndexSetInteger(bearishBufferIndex, PLOT_DRAW_BEGIN, length); - // PlotIndexSetString(bearishBufferIndex, PLOT_LABEL, bearishBufferLabel); - - // - // Signal Buffer ... - string signalBufferLabel = ShortName + "Signal " + "(" + (string)length + ")"; - ArraySetAsSeries(signalBuffer, true); - SetIndexBuffer(signalBufferIndex, signalBuffer, INDICATOR_CALCULATIONS); - // SetIndexBuffer(signalBufferIndex, signalBuffer, INDICATOR_DATA); - // PlotIndexSetInteger(signalBufferIndex, PLOT_DRAW_BEGIN, length); - // PlotIndexSetString(signalBufferIndex, PLOT_LABEL, signalBufferLabel); -} - -// -// Set Indicator Short Name and also we can define Buffers Labels ... -void SetIndicatorName() -{ - // - string indicatorShortName = ""; - StringConcatenate(indicatorShortName, ShortName, " ", "( ", length, " )"); - - // - IndicatorSetString(INDICATOR_SHORTNAME, indicatorShortName); -} - -// -// Calculate Buffers ... -void CalculateBuffers( - int bar_index, - const double &close[]) -{ - // - // Reset Global Counters ... - xtdBullishCandleCount = 0; - xtdBearishCandleCount = 0; - - // - // Loop through Closes ... - for (int i = bar_index; i <= bar_index + length; i++) - { - for (int j = i + 1; j <= bar_index + length; j++) - { - // - if (close[i] > close[j]) - { - xtdBullishCandleCount++; - } - - // - if (close[i] < close[j]) - { - xtdBearishCandleCount++; - } - } - } - - // - // Bullish Power Buffer ... - bullishBuffer[bar_index] = MathAbs(xtdBullishCandleCount); - - // - // Bearish Power Buffer ... - bearishBuffer[bar_index] = MathAbs(xtdBearishCandleCount); - - // - // Signal Buffer ... - signalBuffer[bar_index] = bullishBuffer[bar_index] - bearishBuffer[bar_index]; - - // - // Check and Draw Crosses if it's Specified ... - if (drawCrosses) - { - DrawCrosses(bar_index); - } -} - -// -// -double GetState( - int bar_index // Specified Bar Index -) -{ - // - // Check Cross Points ... - // bullishCrossedOverBearish = 2; - // bullishOverBearish = 1; - // bullishCrossedUnderBearish = -2; - // bullishUnderBearish = -1; - // OtherWise = 0; - bool isBullishCrossedOverBearish = IsCrossedOver( - bullishBuffer, - bearishBuffer, - bar_index); - bool isBullishCrossedUnderBearish = IsCrossedUnder( - bullishBuffer, - bearishBuffer, - bar_index); - bool isBullishOverBearish = IsOver( - bullishBuffer, - bearishBuffer, - bar_index); - bool isBullishUnderBearish = IsUnder( - bullishBuffer, - bearishBuffer, - bar_index); - - // - double result = X_XTD_NEUTURAL; - if (isBullishCrossedOverBearish) - { - result = X_XTD_BULLISH_CROSSED_OVER_BEARISH; - } - else if (isBullishCrossedUnderBearish) - { - result = X_XTD_BULLISH_CROSSED_UNDER_BEARISH; - } - else if (isBullishOverBearish) - { - result = X_XTD_BULLISH_OVER_BEARISH; - } - else if (isBullishUnderBearish) - { - result = X_XTD_BULLISH_UNDER_BEARISH; - } - else - { - result = X_XTD_NEUTURAL; - } - - // - return result; -} - -// -// Draw Crosses ... -void DrawCrosses( - int bar_index // the bars which required to draw cross arrow on it ... -) -{ - // - double stateValue = GetState(bar_index); - - // - bool isOver = stateValue == 2; - double low = iLow(_Symbol, _Period, bar_index); - double high = iHigh(_Symbol, _Period, bar_index); - - // - double price = isOver ? low : high; - datetime time = iTime(_Symbol, _Period, bar_index); - ENUM_ARROW_ANCHOR anchor = isOver ? ANCHOR_TOP : ANCHOR_BOTTOM; - uchar arrowCode = isOver ? bullishArrowCode : bearishArrowCode; - color arrowColor = isOver ? bullishArrowColor : bearishArrowColor; - string crossName = "Trend " + (isOver ? "Up" : "Down") + "_" + (string)time + "_" + (string)price; - - // - DrawArrow( - 0, - crossName, - 0, - time, - price, - arrowCode, - anchor, - arrowColor); -} -// -// END Functions ... -// diff --git a/Documents/Pack/V1.0/Source/Indicators/x-saherelm.xtd.osc.mq5 b/Documents/Pack/V1.0/Source/Indicators/x-saherelm.xtd.osc.mq5 deleted file mode 100644 index 4f40f3c8..00000000 --- a/Documents/Pack/V1.0/Source/Indicators/x-saherelm.xtd.osc.mq5 +++ /dev/null @@ -1,457 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Trend Detector Oscillator -// -------------------------------------------------- -// Name: XTD -// Description: trend detecting in both sides ... -// -// -// Maintainer: -// ------------ -// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) -// -////////////////////////////////////////////////////// -// -// Global Properties ... -#property copyright "Copyright 2023, SaherElm IT Center" -#property link "https://saherelm.ir" -#property version "1.00" -#property description "SaherElm XTD Oscillator" -#property strict - -// -// START Constants ... -// -#define ShortName "XTD" - -// -// XTD Oscillator States ... -enum ENUM_X_XTD_STATES -{ - X_XTD_BULLISH_CROSSED_OVER_BEARISH = 2, - X_XTD_BULLISH_OVER_BEARISH = 1, - X_XTD_NEUTURAL = 0, - X_XTD_BULLISH_UNDER_BEARISH = -1, - X_XTD_BULLISH_CROSSED_UNDER_BEARISH = -2 -}; -// -// END Constants ... -// - -// -// START Inputs ... -// -input int length = 14; // Market Length -input bool drawCrosses = true; // Draw Cross Arrows - -// -// Bullish ... -input uchar bullishArrowCode = 228; // Cross Over Arrow Code -input color bullishArrowColor = clrAqua; // Cross Over Arrow Color - -// -// Bearish ... -input uchar bearishArrowCode = 230; // Cross Under Arrow Code -input color bearishArrowColor = clrMagenta; // Cross Under Arrow Color -// -// END Inputs ... -// - -// -// Includes Common Library ... -#include "../Libraries/x-saherelm.common.lib.mq5"; - -// -// Includes Draw Library ... -#include "../Libraries/x-saherelm.draw.lib.mq5"; - -// -// START Buffers ... -// -#property indicator_separate_window -// #property indicator_chart_window - -// -#property indicator_buffers 3 -#property indicator_plots 2 -// #property indicator_plots 0 - -// -#define bullishBufferIndex 0 -#define bearishBufferIndex 1 -#define signalBufferIndex 2 - -// -double bullishBuffer[]; -double bearishBuffer[]; -double signalBuffer[]; - -// -#property indicator_label1 "XBullPower" -#property indicator_type1 DRAW_LINE -#property indicator_color1 clrLime -#property indicator_style1 STYLE_SOLID -#property indicator_width1 1 - -// -#property indicator_label2 "XBearPower" -#property indicator_type2 DRAW_LINE -#property indicator_color2 clrRed -#property indicator_style2 STYLE_SOLID -#property indicator_width2 1 - -// -// #property indicator_label3 "XSignal" -// #property indicator_type3 DRAW_LINE -// #property indicator_color3 clrGold -// #property indicator_style3 STYLE_DOT -// #property indicator_width3 1 -// -// END Buffers ... -// - -// -// START Global Definitions: Variables, Properties and etc ... -// -// -int xtdBullishCandleCount = 0; -int xtdBearishCandleCount = 0; -// -// END Global Definitions: Variables, Properties and etc ... -// - -// -// START Event Handlers ... -// -// -// Initialization ... -int OnInit() -{ - // - // Validate Inputs ... - if (!ValidateInputs()) - { - return INIT_PARAMETERS_INCORRECT; - } - - // - drawPrefix = ShortName; - - // - // Define Index Buffers ... - DefineBuffers(); - - // - // Set Indicator ShortName ... - SetIndicatorName(); - - // - // Init Succeed ... - return INIT_SUCCEEDED; -} - -// -// DeInitialization ... -void OnDeinit(const int reason) -{ - // - // REASON_PROGRAM 0 The EA has stopped working calling the ExpertRemove() function - // REASON_REMOVE 1 Program removed from a chart - // REASON_RECOMPILE 2 Program recompiled - // REASON_CHARTCHANGE 3 A symbol or a chart period is changed - // REASON_CHARTCLOSE 4 Chart closed - // REASON_PARAMETERS 5 Inputs changed by a user - // REASON_ACCOUNT 6 Another account has been activated or reconnection to the trade server has occurred due to changes in the account settings - // REASON_TEMPLATE 7 Another chart template applied - // REASON_INITFAILED 8 The OnInit() handler returned a non-zero value - // REASON_CLOSE 9 Terminal closed - - // - // Here we can handle De Initialization Reasons ... -} - -// -// Calculations ... -// -// Calculating what we want ... -int OnCalculate( - // - // total Candles on chart ... - const int rates_total, - // - // total calculated Candles on charts ... - const int prev_calculated, - // - // history of Candles Open Time ... - const datetime &time[], - // - // history of Candles Open Price ... - const double &open[], - // - // history of Candles High Price ... - const double &high[], - // - // history of Candles Low Price ... - const double &low[], - // - // history of Candles Close Price ... - const double &close[], - // - // history of Tick Volumes on Candle ... - const long &tick_volume[], - // - // history of Trade Volumes ... - const long &volume[], - // - // history of Candles Spread Price ... - const int &spread[]) -{ - // - // Prepare Buffers ... - ArraySetAsSeries(time, true); - ArraySetAsSeries(open, true); - ArraySetAsSeries(high, true); - ArraySetAsSeries(low, true); - ArraySetAsSeries(close, true); - ArraySetAsSeries(tick_volume, true); - ArraySetAsSeries(volume, true); - ArraySetAsSeries(spread, true); - - // - // this counts Available Bars ... - int limit; - - // - // because in some cases we may have more than one input for - // calculation and we must prevent any calculation - // untill we pass the biggest input length, here we get max Input length - // and then wait until pass it ... - int maxLength = MathMax(0, length); - - // - limit = prev_calculated < maxLength ? rates_total - (maxLength + 1) : rates_total - prev_calculated; - - // - // Main Loop ... - for (int i = limit; i >= 0 && !IsStopped(); i--) - { - // - CalculateBuffers(i, close); - } - - // - return rates_total; -} -// -// END Event Handlers ... -// - -// -// START Functions ... -// -// -// Validate Input Args for Initialization ... -bool ValidateInputs() -{ - // - bool result = false; - - // - // Validate Args ... - if (length >= 5) - { - result = true; - } - - // - return result; -} - -// -// Define Indexes and Styles ... -void DefineBuffers() -{ - // - // Bullish Buffer ... - string bullishBufferLabel = ShortName + "BullPow " + "(" + (string)length + ")"; - ArraySetAsSeries(bullishBuffer, true); - // SetIndexBuffer(bullishBufferIndex, bullishBuffer, INDICATOR_CALCULATIONS); - SetIndexBuffer(bullishBufferIndex, bullishBuffer, INDICATOR_DATA); - PlotIndexSetInteger(bullishBufferIndex, PLOT_DRAW_BEGIN, length); - PlotIndexSetString(bullishBufferIndex, PLOT_LABEL, bullishBufferLabel); - - // - // Bearish Buffer ... - string bearishBufferLabel = ShortName + "BearPow " + "(" + (string)length + ")"; - ArraySetAsSeries(bearishBuffer, true); - // SetIndexBuffer(bearishBufferIndex, bearishBuffer, INDICATOR_CALCULATIONS); - SetIndexBuffer(bearishBufferIndex, bearishBuffer, INDICATOR_DATA); - PlotIndexSetInteger(bearishBufferIndex, PLOT_DRAW_BEGIN, length); - PlotIndexSetString(bearishBufferIndex, PLOT_LABEL, bearishBufferLabel); - - // - // Signal Buffer ... - string signalBufferLabel = ShortName + "Signal " + "(" + (string)length + ")"; - ArraySetAsSeries(signalBuffer, true); - SetIndexBuffer(signalBufferIndex, signalBuffer, INDICATOR_CALCULATIONS); - // SetIndexBuffer(signalBufferIndex, signalBuffer, INDICATOR_DATA); - // PlotIndexSetInteger(signalBufferIndex, PLOT_DRAW_BEGIN, length); - // PlotIndexSetString(signalBufferIndex, PLOT_LABEL, signalBufferLabel); -} - -// -// Set Indicator Short Name and also we can define Buffers Labels ... -void SetIndicatorName() -{ - // - string indicatorShortName = ""; - StringConcatenate(indicatorShortName, ShortName, " ", "( ", length, " )"); - - // - IndicatorSetString(INDICATOR_SHORTNAME, indicatorShortName); -} - -// -// Calculate Buffers ... -void CalculateBuffers( - int bar_index, - const double &close[]) -{ - // - // Reset Global Counters ... - xtdBullishCandleCount = 0; - xtdBearishCandleCount = 0; - - // - // Loop through Closes ... - for (int i = bar_index; i <= bar_index + length; i++) - { - for (int j = i + 1; j <= bar_index + length; j++) - { - // - if (close[i] > close[j]) - { - xtdBullishCandleCount++; - } - - // - if (close[i] < close[j]) - { - xtdBearishCandleCount++; - } - } - } - - // - // Bullish Power Buffer ... - bullishBuffer[bar_index] = MathAbs(xtdBullishCandleCount); - - // - // Bearish Power Buffer ... - bearishBuffer[bar_index] = MathAbs(xtdBearishCandleCount); - - // - // Signal Buffer ... - signalBuffer[bar_index] = bullishBuffer[bar_index] - bearishBuffer[bar_index]; - - // - // Check and Draw Crosses if it's Specified ... - if (drawCrosses) - { - DrawCrosses(bar_index); - } -} - -// -// -double GetState( - int bar_index // Specified Bar Index -) -{ - // - // Check Cross Points ... - // bullishCrossedOverBearish = 2; - // bullishOverBearish = 1; - // bullishCrossedUnderBearish = -2; - // bullishUnderBearish = -1; - // OtherWise = 0; - bool isBullishCrossedOverBearish = IsCrossedOver( - bullishBuffer, - bearishBuffer, - bar_index); - bool isBullishCrossedUnderBearish = IsCrossedUnder( - bullishBuffer, - bearishBuffer, - bar_index); - bool isBullishOverBearish = IsOver( - bullishBuffer, - bearishBuffer, - bar_index); - bool isBullishUnderBearish = IsUnder( - bullishBuffer, - bearishBuffer, - bar_index); - - // - double result = X_XTD_NEUTURAL; - if (isBullishCrossedOverBearish) - { - result = X_XTD_BULLISH_CROSSED_OVER_BEARISH; - } - else if (isBullishCrossedUnderBearish) - { - result = X_XTD_BULLISH_CROSSED_UNDER_BEARISH; - } - else if (isBullishOverBearish) - { - result = X_XTD_BULLISH_OVER_BEARISH; - } - else if (isBullishUnderBearish) - { - result = X_XTD_BULLISH_UNDER_BEARISH; - } - else - { - result = X_XTD_NEUTURAL; - } - - // - return result; -} - -// -// Draw Crosses ... -void DrawCrosses( - int bar_index // the bars which required to draw cross arrow on it ... -) -{ - // - double stateValue = GetState(bar_index); - - // - bool isOver = stateValue == 2; - double low = iLow(_Symbol, _Period, bar_index); - double high = iHigh(_Symbol, _Period, bar_index); - - // - double price = isOver ? low : high; - datetime time = iTime(_Symbol, _Period, bar_index); - ENUM_ARROW_ANCHOR anchor = isOver ? ANCHOR_TOP : ANCHOR_BOTTOM; - uchar arrowCode = isOver ? bullishArrowCode : bearishArrowCode; - color arrowColor = isOver ? bullishArrowColor : bearishArrowColor; - string crossName = "Trend " + (isOver ? "Up" : "Down") + "_" + (string)time + "_" + (string)price; - - // - DrawArrow( - 0, - crossName, - 0, - time, - price, - arrowCode, - anchor, - arrowColor); -} -// -// END Functions ... -// diff --git a/Documents/Pack/V1.0/Source/Indicators/x-saherelm.xtm.mq5 b/Documents/Pack/V1.0/Source/Indicators/x-saherelm.xtm.mq5 deleted file mode 100644 index 2ee52d1b..00000000 --- a/Documents/Pack/V1.0/Source/Indicators/x-saherelm.xtm.mq5 +++ /dev/null @@ -1,351 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Candle Indicator -// --------------------------------------------- -// Name: XTM -// Description: Trend Magic Indicator ... -// -// -// Maintainer: -// ------------ -// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) -// -////////////////////////////////////////////////////// -// -// Global Properties ... -#property copyright "Copyright 2023, SaherElm IT Center" -#property link "https://saherelm.ir" -#property version "1.00" -#property description "SaherElm XTM Indicator" -#property strict - -// -// START Constants ... -// -#define ShortName "XTM" - -// -// XTM Indicator States ... -enum ENUM_X_XTM_STATES -{ - X_XTM_BULLISH = 1, - X_XTM_BEARISH = -1, - X_XTM_NEUTURAL = 0, -}; -// -// END Constants ... -// - -// -// START Inputs ... -// - -// -input group "Market"; -input int maPeriod = 14; // Period -input int maShift = 0; // Shift -input ENUM_MA_METHOD maMethod = MODE_SMA; // Method -input ENUM_APPLIED_PRICE maAppliedTo = PRICE_CLOSE; // Applied To - -// -input group "Presentation"; -input bool showLine = true; // Show Line - -// -// END Inputs ... -// - -// -// Includes Common Library ... -#include "../Libraries/x-saherelm.common.lib.mq5" - -// -// START Buffers ... -// -#property indicator_chart_window - -// -#property indicator_buffers 3 -#property indicator_plots 1 - -// -// maBuffer ... -#define maBufferIndex 0 -#define maColorBufferIndex 1 -#define stateBufferIndex 2 - -double maBuffer[]; -double maColorBuffer[]; -double stateBuffer[]; - -#property indicator_label1 "XTM" -#property indicator_type1 DRAW_COLOR_LINE -#property indicator_color1 clrLime, clrGray, clrRed, CLR_NONE -#property indicator_style1 STYLE_SOLID -#property indicator_width1 1 -// -// END Buffers ... -// - -// -// START Global Definitions: Variables, Properties and etc ... -// -int maHandler = INVALID_HANDLE; -// -// END Global Definitions: Variables, Properties and etc ... -// - -// -// START Event Handlers ... -// -// -// Initialization ... -int OnInit() -{ - // - // Validate Inputs ... - if (!ValidateInputs()) - { - return INIT_PARAMETERS_INCORRECT; - } - - // - // Initializing MA Handler ... - maHandler = iMA( - _Symbol, - _Period, - maPeriod, - maShift, - maMethod, - maAppliedTo); - if (maHandler == INVALID_HANDLE) - { - return INIT_FAILED; - } - - // - // Define Index Buffers ... - DefineBuffers(); - - // - // Set Indicator ShortName ... - SetIndicatorName(); - - // - // Init Succeed ... - return INIT_SUCCEEDED; -} - -// -// DeInitialization ... -void OnDeinit(const int reason) -{ - // - // REASON_PROGRAM 0 The EA has stopped working calling the ExpertRemove() function - // REASON_REMOVE 1 Program removed from a chart - // REASON_RECOMPILE 2 Program recompiled - // REASON_CHARTCHANGE 3 A symbol or a chart period is changed - // REASON_CHARTCLOSE 4 Chart closed - // REASON_PARAMETERS 5 Inputs changed by a user - // REASON_ACCOUNT 6 Another account has been activated or reconnection to the trade server has occurred due to changes in the account settings - // REASON_TEMPLATE 7 Another chart template applied - // REASON_INITFAILED 8 The OnInit() handler returned a non-zero value - // REASON_CLOSE 9 Terminal closed - - // - // Here we can handle De Initialization Reasons ... -} - -// -// Calculations ... -// -// Calculating what we want ... -int OnCalculate( - // - // total Candles on chart ... - const int rates_total, - // - // total calculated Candles on charts ... - const int prev_calculated, - // - // history of Candles Open Time ... - const datetime &time[], - // - // history of Candles Open Price ... - const double &open[], - // - // history of Candles High Price ... - const double &high[], - // - // history of Candles Low Price ... - const double &low[], - // - // history of Candles Close Price ... - const double &close[], - // - // history of Tick Volumes on Candle ... - const long &tick_volume[], - // - // history of Trade Volumes ... - const long &volume[], - // - // history of Candles Spread Price ... - const int &spread[]) -{ - // - // Prepare Buffers ... - ArraySetAsSeries(time, true); - ArraySetAsSeries(open, true); - ArraySetAsSeries(high, true); - ArraySetAsSeries(low, true); - ArraySetAsSeries(close, true); - ArraySetAsSeries(tick_volume, true); - ArraySetAsSeries(volume, true); - ArraySetAsSeries(spread, true); - - // - // this counts Available Bars ... - int limit; - - // - // because in some cases we may have more than one input for - // calculation and we must prevent any calculation - // untill we pass the biggest input length, here we get max Input length - // and then wait until pass it ... - int maxLength = MathMax(0, maPeriod); - - // - // Check Calculated Bars ... - int maCalculatedBars = BarsCalculated(maHandler); - if (maCalculatedBars < maxLength) - { - return prev_calculated; - } - - // - limit = (prev_calculated > rates_total || prev_calculated <= 0) ? rates_total : (rates_total - prev_calculated) + 1; - - // - // Buffers Copy ... - int copiedMas = CopyBuffer(maHandler, 0, 0, limit, maBuffer); - if (copiedMas <= 0) - { - return prev_calculated; - } - - // - // Main Loop ... - for (int i = limit - 1; i >= 0 && !IsStopped(); i--) - { - // - // Do Buffers Calculation ... - CalculateBuffers(i); - } - - // - return rates_total; -} -// -// END Event Handlers ... -// - -// -// START Functions ... -// -// -// Validate Input Args for Initialization ... -bool ValidateInputs() -{ - // - bool result = false; - - // - // Validate Args ... - if (maPeriod >= 2) - { - result = true; - } - - // - return result; -} - -// -// Define Indexes and Styles ... -void DefineBuffers() -{ - // - string maBufferLabel = "XTM " + "(" + (string)maPeriod + ")"; - - // - // Ma Buffer ... - ArraySetAsSeries(maBuffer, true); - SetIndexBuffer(maBufferIndex, maBuffer, INDICATOR_DATA); - PlotIndexSetString(maBufferIndex, PLOT_LABEL, maBufferLabel); - - // - // Ma Color Buffer ... - ArraySetAsSeries(maColorBuffer, true); - SetIndexBuffer(maColorBufferIndex, maColorBuffer, INDICATOR_COLOR_INDEX); - - // - // State Buffer ... - ArraySetAsSeries(stateBuffer, true); - SetIndexBuffer(stateBufferIndex, stateBuffer, INDICATOR_CALCULATIONS); -} - -// -// Set Indicator Short Name and also we can define Buffers Labels ... -void SetIndicatorName() -{ - // - string indicatorShortName = ""; - StringConcatenate(indicatorShortName, ShortName, " ", "(", maPeriod, ")"); - - // - IndicatorSetString(INDICATOR_SHORTNAME, indicatorShortName); -} - -// -// Calculate Buffers ... -void CalculateBuffers(int bar_index) -{ - // - // Requirements ... - XOHCL candle; - candle.Init( - _Symbol, - _Period, - bar_index - // - ); - - // - double maValue = maBuffer[bar_index]; - - // - double lineColorIndex = - maValue < candle.low ? 0 : maValue > candle.high ? 2 - : 1; - - // - // Define State Value ... - // lineColorIndex == 0 => Bullish => 1; - // lineColorIndex == 1 => Neutural => 0; - // lineColorIndex == 2 => Bearish => -1; - double stateValue = - lineColorIndex == 0 ? X_XTM_BULLISH : lineColorIndex == 2 ? X_XTM_BEARISH - : X_XTM_NEUTURAL; - - // - // Set Ma Buffer Color Index ... - maColorBuffer[bar_index] = showLine ? lineColorIndex : 3; - - // - // Set State Buffer Value ... - stateBuffer[bar_index] = stateValue; -} - -// -// END Functions ... -// diff --git a/Documents/Pack/V1.0/Source/Indicators/x-saherelm.xvlm.mq5 b/Documents/Pack/V1.0/Source/Indicators/x-saherelm.xvlm.mq5 deleted file mode 100644 index 7aa93a91..00000000 --- a/Documents/Pack/V1.0/Source/Indicators/x-saherelm.xvlm.mq5 +++ /dev/null @@ -1,231 +0,0 @@ -////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Indicator -// --------------------------------------------- -// Name: XVLM -// Description: Volume Trend Indicator ... -// -// -// Maintainer: -// ------------ -// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) -// -////////////////////////////////////////////////////// -// -// Global Properties ... -#property copyright "Copyright 2023, SaherElm IT Center" -#property link "https://saherelm.ir" -#property version "1.00" -#property description "SaherElm XVLM Indicator" -#property strict - -// -// Imports ... -#include - -// -// Definitions ... - -// -#define ShortName "XVLM" - -// -// Inputs ... - -// -input int length = 14; // Length - -// -// Buffers ... - -// -#property indicator_chart_window - -// -#property indicator_buffers 2 -#property indicator_plots 0 - -/// -#define volumeBufferIndex 0 -double volumeBuffer[]; - -// -#define volumeColorBufferIndex 1 -double volumeColorBuffer[]; - -// -#property indicator_label1 "XVLM" -#property indicator_type1 DRAW_COLOR_HISTOGRAM -#property indicator_color1 clrLime, clrRed - -// -#define bullishColorIndex 0 -#define bearishColorIndex 1 - -// -// Variables ... - -// -int maxLength; - -// -double volumes[]; -double distances[]; - -// -// Event Handlers ... - -// -// Initialization ... -int OnInit() -{ - // - // Validate Inputs ... - if (!ValidateInputs()) - { - return INIT_PARAMETERS_INCORRECT; - } - - // - // because in some cases we may have more than one input for - // calculation and we must prevent any calculation - // untill we pass the biggest input length, here we get max Input length - // and then wait until pass it ... - maxLength = ExtractMaxLengthOfInputs(); - - // - ArrayResize(volumes, maxLength, 0); - ArrayResize(distances, maxLength, 0); - - // - // Define Index Buffers ... - DefineBuffers(); - - // - // Set Indicator ShortName ... - SetIndicatorName(); - - // - // Init Succeed ... - return INIT_SUCCEEDED; -} - -// -// DeInitialization ... -void OnDeinit(const int reason) -{ - // - // REASON_PROGRAM 0 The EA has stopped working calling the ExpertRemove() function - // REASON_REMOVE 1 Program removed from a chart - // REASON_RECOMPILE 2 Program recompiled - // REASON_CHARTCHANGE 3 A symbol or a chart period is changed - // REASON_CHARTCLOSE 4 Chart closed - // REASON_PARAMETERS 5 Inputs changed by a user - // REASON_ACCOUNT 6 Another account has been activated or reconnection to the trade server has occurred due to changes in the account settings - // REASON_TEMPLATE 7 Another chart template applied - // REASON_INITFAILED 8 The OnInit() handler returned a non-zero value - // REASON_CLOSE 9 Terminal closed - - // - // Here we can handle De Initialization Reasons ... -} - -// -// Calculating what we want ... -int OnCalculate( - const int rates_total, // Total Bars on Chart ... - const int prev_calculated, // Total Calculated Bars on Charts ... - const datetime &time[], // History of Open Time ... - const double &open[], // History of Open Price ... - const double &high[], // History of High Price ... - const double &low[], // History of Low Price ... - const double &close[], // History of Close Price ... - const long &tick_volume[], // History of Tick Volumes on Bar ... - const long &volume[], // History of Trade Volumes ... - const int &spread[] // History of Spread Price ... -) -{ - // - static int i = maxLength * 2; - for (i; i < rates_total; i++) - { - // - for (int x = 0; x < length; x++) - { - // - volumes[x] = (double)tick_volume[i - x]; - distances[x] = - (close[i - x] > open[i - x]) - ? high[i - x] - low[i - x] - : low[i - x] - high[i - x]; - } - - // - double iValue = MathMean(volumes) * MathMean(distances); - - // - volumeBuffer[i] = iValue; - volumeColorBuffer[i] = iValue > 0 - ? bullishColorIndex - : bearishColorIndex; - } - - // - i = rates_total - 1; - - // - return rates_total; -} - -// -// Custom Functions ... - -// -// Validate Input Args for Initialization ... -bool ValidateInputs() -{ - // - bool result = false; - - // - // Validate Args ... - result = - // - length >= 2 - // - ; - - // - return result; -} - -// -// Retrieve all Exists Input Max Length ... -// use for Start Of Drawing ... -int ExtractMaxLengthOfInputs() -{ - // - int result = 0; - - // - result = length; - - // - return result; -} - -// -// Set Indicator Short Name and also we can define Buffers Labels ... -void SetIndicatorName() -{ - IndicatorSetString(INDICATOR_SHORTNAME, ShortName); -} - -// -// Define Indexes and Styles ... -void DefineBuffers() -{ - // - SetIndexBuffer(volumeBufferIndex, volumeBuffer, INDICATOR_CALCULATIONS); - SetIndexBuffer(volumeColorBufferIndex, volumeColorBuffer, INDICATOR_CALCULATIONS); -} \ No newline at end of file diff --git a/Documents/Pack/V1.0/Source/Indicators/x-saherelm.xvlm.osc.mq5 b/Documents/Pack/V1.0/Source/Indicators/x-saherelm.xvlm.osc.mq5 deleted file mode 100644 index 98f5bdb2..00000000 --- a/Documents/Pack/V1.0/Source/Indicators/x-saherelm.xvlm.osc.mq5 +++ /dev/null @@ -1,231 +0,0 @@ -////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Indicator -// --------------------------------------------- -// Name: XVLM -// Description: Volume Trend Indicator ... -// -// -// Maintainer: -// ------------ -// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) -// -////////////////////////////////////////////////////// -// -// Global Properties ... -#property copyright "Copyright 2023, SaherElm IT Center" -#property link "https://saherelm.ir" -#property version "1.00" -#property description "SaherElm XVLM Indicator" -#property strict - -// -// Imports ... -#include - -// -// Definitions ... - -// -#define ShortName "XVLM" - -// -// Inputs ... - -// -input int length = 14; // Length - -// -// Buffers ... - -// -#property indicator_separate_window - -// -#property indicator_buffers 2 -#property indicator_plots 2 - -/// -#define volumeBufferIndex 0 -double volumeBuffer[]; - -// -#define volumeColorBufferIndex 1 -double volumeColorBuffer[]; - -// -#property indicator_label1 "XVLM" -#property indicator_type1 DRAW_COLOR_HISTOGRAM -#property indicator_color1 clrLime, clrRed - -// -#define bullishColorIndex 0 -#define bearishColorIndex 1 - -// -// Variables ... - -// -int maxLength; - -// -double volumes[]; -double distances[]; - -// -// Event Handlers ... - -// -// Initialization ... -int OnInit() -{ - // - // Validate Inputs ... - if (!ValidateInputs()) - { - return INIT_PARAMETERS_INCORRECT; - } - - // - // because in some cases we may have more than one input for - // calculation and we must prevent any calculation - // untill we pass the biggest input length, here we get max Input length - // and then wait until pass it ... - maxLength = ExtractMaxLengthOfInputs(); - - // - ArrayResize(volumes, maxLength, 0); - ArrayResize(distances, maxLength, 0); - - // - // Define Index Buffers ... - DefineBuffers(); - - // - // Set Indicator ShortName ... - SetIndicatorName(); - - // - // Init Succeed ... - return INIT_SUCCEEDED; -} - -// -// DeInitialization ... -void OnDeinit(const int reason) -{ - // - // REASON_PROGRAM 0 The EA has stopped working calling the ExpertRemove() function - // REASON_REMOVE 1 Program removed from a chart - // REASON_RECOMPILE 2 Program recompiled - // REASON_CHARTCHANGE 3 A symbol or a chart period is changed - // REASON_CHARTCLOSE 4 Chart closed - // REASON_PARAMETERS 5 Inputs changed by a user - // REASON_ACCOUNT 6 Another account has been activated or reconnection to the trade server has occurred due to changes in the account settings - // REASON_TEMPLATE 7 Another chart template applied - // REASON_INITFAILED 8 The OnInit() handler returned a non-zero value - // REASON_CLOSE 9 Terminal closed - - // - // Here we can handle De Initialization Reasons ... -} - -// -// Calculating what we want ... -int OnCalculate( - const int rates_total, // Total Bars on Chart ... - const int prev_calculated, // Total Calculated Bars on Charts ... - const datetime &time[], // History of Open Time ... - const double &open[], // History of Open Price ... - const double &high[], // History of High Price ... - const double &low[], // History of Low Price ... - const double &close[], // History of Close Price ... - const long &tick_volume[], // History of Tick Volumes on Bar ... - const long &volume[], // History of Trade Volumes ... - const int &spread[] // History of Spread Price ... -) -{ - // - static int i = maxLength * 2; - for (i; i < rates_total; i++) - { - // - for (int x = 0; x < length; x++) - { - // - volumes[x] = (double)tick_volume[i - x]; - distances[x] = - (close[i - x] > open[i - x]) - ? high[i - x] - low[i - x] - : low[i - x] - high[i - x]; - } - - // - double iValue = MathMean(volumes) * MathMean(distances); - - // - volumeBuffer[i] = iValue; - volumeColorBuffer[i] = iValue > 0 - ? bullishColorIndex - : bearishColorIndex; - } - - // - i = rates_total - 1; - - // - return rates_total; -} - -// -// Custom Functions ... - -// -// Validate Input Args for Initialization ... -bool ValidateInputs() -{ - // - bool result = false; - - // - // Validate Args ... - result = - // - length >= 2 - // - ; - - // - return result; -} - -// -// Retrieve all Exists Input Max Length ... -// use for Start Of Drawing ... -int ExtractMaxLengthOfInputs() -{ - // - int result = 0; - - // - result = length; - - // - return result; -} - -// -// Set Indicator Short Name and also we can define Buffers Labels ... -void SetIndicatorName() -{ - IndicatorSetString(INDICATOR_SHORTNAME, ShortName); -} - -// -// Define Indexes and Styles ... -void DefineBuffers() -{ - // - SetIndexBuffer(volumeBufferIndex, volumeBuffer, INDICATOR_DATA); - SetIndexBuffer(volumeColorBufferIndex, volumeColorBuffer, INDICATOR_COLOR_INDEX); -} \ No newline at end of file diff --git a/Documents/Pack/V1.0/Source/Indicators/x-saherelm.xzg.mq5 b/Documents/Pack/V1.0/Source/Indicators/x-saherelm.xzg.mq5 deleted file mode 100644 index 0abb3684..00000000 --- a/Documents/Pack/V1.0/Source/Indicators/x-saherelm.xzg.mq5 +++ /dev/null @@ -1,750 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Indicator -// --------------------------------------------- -// Name: XZG -// Description: Zogzag Implementation ... -// -// -// Maintainer: -// ------------ -// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) -// -////////////////////////////////////////////////////// -// -// Global Properties ... -#property copyright "Copyright 2023, SaherElm IT Center" -#property link "https://saherelm.ir" -#property version "1.00" -#property description "SaherElm XZG Indicator" -#property strict - -// -#define ShortName "XZG" - -// -// DEFINITIONS ... -enum ENUM_X_ZG_SEARCH_MODE -{ - X_ZG_SEARCH_EXTREMUM = 0, // searching for the first extremum - X_ZG_SEARCH_PEAK = 1, // searching for the next ZigZag peak - X_ZG_SEARCH_VALE = -1 // searching for the next ZigZag vale -}; - -// -// How to Calculate Up and Down Price ... -enum ENUM_X_ZG_PRICE_MODE -{ - // - X_ZG_PRICE_HIGH_LOW_MODE = 1, - X_ZG_PRICE_OPEN_CLOSE_MODE = 2, -}; - -// -// INPUT ... - -// -input group "Market"; -input int depth = 12; // Depth -input int deviation = 5; // Deviation -input int backStep = 3; // Back Step -input ENUM_X_ZG_PRICE_MODE mode = X_ZG_PRICE_HIGH_LOW_MODE; // Mode - -// -input group "Presentation"; -input bool showZigZag = true; // Show ZigZag -input bool showPeaksAndVales = true; // Show Peaks and Vales - -// -// BUFFERS ... - -// -#property indicator_chart_window - -// -#property indicator_buffers 6 -#property indicator_plots 4 - -// -// ZigZag ... - -// -#define mainBufferIndex 0 -#define mainBufferPlotIndex 0 -double mainBuffer[]; - -#define mainColorBufferIndex 1 -double mainColorBuffer[]; - -// -#property indicator_label1 "XZG Main" -#property indicator_type1 DRAW_COLOR_SECTION -#property indicator_color1 CLR_NONE, clrRoyalBlue, clrSaddleBrown -#property indicator_width1 2 - -// -// Highs ... - -// -// ZigZag Pointer or Line Indicator ... -#define arrowBufferIndex 2 -#define arrowBufferPlotIndex 1 -double arrowBuffer[]; - -// -#define arrowColorBufferIndex 3 -double arrowColorBuffer[]; - -// -#property indicator_label2 "XZG PV" -#property indicator_type2 DRAW_COLOR_ARROW -#property indicator_color2 CLR_NONE, clrAqua, clrMagenta -#property indicator_width2 1 - -// -#define highsBufferIndex 4 -double highsBuffer[]; - -// -// Lows ... - -// -#define lowsBufferIndex 5 -double lowsBuffer[]; - -// -// VARIABLES ... - -// -int mRecalc = 3; // Number of last extremes for recalculation - -// -// EVENT Handlers ... - -// -// Initialization ... -int OnInit() -{ - // - // Validate Inputs ... - if (!ValidateInputs()) - { - return INIT_PARAMETERS_INCORRECT; - } - - // - // logTag = ShortName; - - // - // Define Index Buffers ... - DefineBuffers(); - - // - // Set Indicator ShortName ... - SetIndicatorName(); - - // - // Init Succeed ... - return INIT_SUCCEEDED; -} - -// -// DeInitialization ... -void OnDeinit(const int reason) -{ - // - // REASON_PROGRAM 0 The EA has stopped working calling the ExpertRemove() function - // REASON_REMOVE 1 Program removed from a chart - // REASON_RECOMPILE 2 Program recompiled - // REASON_CHARTCHANGE 3 A symbol or a chart period is changed - // REASON_CHARTCLOSE 4 Chart closed - // REASON_PARAMETERS 5 Inputs changed by a user - // REASON_ACCOUNT 6 Another account has been activated or reconnection to the trade server has occurred due to changes in the account settings - // REASON_TEMPLATE 7 Another chart template applied - // REASON_INITFAILED 8 The OnInit() handler returned a non-zero value - // REASON_CLOSE 9 Terminal closed -} - -// -// Calculating what we want ... -int OnCalculate( - const int rates_total, // Total Bars on Chart ... - const int prev_calculated, // Total Calculated Bars on Charts ... - const datetime &time[], // History of Open Time ... - const double &open[], // History of Open Price ... - const double &high[], // History of High Price ... - const double &low[], // History of Low Price ... - const double &close[], // History of Close Price ... - const long &tick_volume[], // History of Tick Volumes on Bar ... - const long &volume[], // History of Trade Volumes ... - const int &spread[] // History of Spread Price ... -) -{ - // - double mZGHigh[]; - double mZGLow[]; - if (mode == X_ZG_PRICE_OPEN_CLOSE_MODE) - { - // - ArrayCopy( - mZGHigh, - open - // - ); - - // - ArrayCopy( - mZGLow, - close - // - ); - } - else - { - // - ArrayCopy( - mZGHigh, - high - // - ); - - // - ArrayCopy( - mZGLow, - low - // - ); - } - - // - int zigZagResult = CalcukateZigZag( - prev_calculated, - rates_total, - mZGHigh, - mZGLow - // - ); - - // - if (zigZagResult != rates_total) - { - return zigZagResult; - } - - // - return rates_total; -} - -// -// CUSTOM Functions ... - -// -// Validate Input Args for Initialization ... -bool ValidateInputs() -{ - // - bool result = false; - - // - result = - // - depth > 0 && - deviation > 0 && - backStep > 0 - // - ; - - // - return result; -} - -// -// Define Indexes and Styles ... -void DefineBuffers() -{ - // - // Main ... - - // - SetIndexBuffer(mainBufferIndex, mainBuffer, INDICATOR_DATA); - SetIndexBuffer(mainColorBufferIndex, mainColorBuffer, INDICATOR_COLOR_INDEX); - - // - PlotIndexSetInteger(mainBufferPlotIndex, PLOT_SHOW_DATA, showZigZag); - PlotIndexSetInteger(mainBufferPlotIndex, PLOT_DRAW_BEGIN, 0); - PlotIndexSetDouble(mainBufferPlotIndex, PLOT_EMPTY_VALUE, 0); - - // - // Arrow ... - - // - SetIndexBuffer(arrowBufferIndex, arrowBuffer, INDICATOR_DATA); - - // - PlotIndexSetInteger(arrowBufferPlotIndex, PLOT_SHOW_DATA, showPeaksAndVales); - PlotIndexSetInteger(arrowBufferPlotIndex, PLOT_DRAW_BEGIN, 0); - PlotIndexSetInteger(arrowBufferPlotIndex, PLOT_ARROW, 159); - PlotIndexSetInteger(arrowBufferPlotIndex, PLOT_ARROW_SHIFT, 0); - PlotIndexSetDouble(arrowBufferPlotIndex, PLOT_EMPTY_VALUE, 0); - - // - // Arrow Color ... - SetIndexBuffer(arrowColorBufferIndex, arrowColorBuffer, INDICATOR_COLOR_INDEX); - - // - // Highs ... - SetIndexBuffer(highsBufferIndex, highsBuffer, INDICATOR_CALCULATIONS); - - // - // Lows ... - SetIndexBuffer(lowsBufferIndex, lowsBuffer, INDICATOR_CALCULATIONS); -} - -// -// Set Indicator Short Name and also we can define Buffers Labels ... -void SetIndicatorName() -{ - IndicatorSetString(INDICATOR_SHORTNAME, ShortName); -} - -// -// Calculating Zig Zag ... -int CalcukateZigZag( - const int prev_calculated, - const int rates_total, - double &high[], - double &low[] - // -) -{ - // - if (rates_total < 100) - { - return 0; - } - - // - // Define Variables ... - int i = 0; - - // - int start = 0; - int extreme_counter = 0; - int extreme_search = X_ZG_SEARCH_EXTREMUM; - int shift = 0; - int back = 0; - int last_high_pos = 0; - int last_low_pos = 0; - - // - double val = 0; - double res = 0; - double curlow = 0; - double curhigh = 0; - double last_high = 0; - double last_low = 0; - - // - double colorIDX = 0; - double lastZigZagValue = 0; - - // - // Initializing ... - if (prev_calculated == 0) - { - // - ArrayInitialize(mainBuffer, 0); - ArrayInitialize(highsBuffer, 0); - ArrayInitialize(lowsBuffer, 0); - - // - start = depth; - } - - // - // Already Calculated Before ... - if (prev_calculated > 0) - { - // - i = rates_total - 1; - - // - // Searching for the third X_ZG_SEARCH_EXTREMUM from the last UnComplete Bar ... - while (extreme_counter < mRecalc && i > rates_total - 100) - { - // - res = mainBuffer[i]; - if (res != 0) - { - extreme_counter++; - } - - // - i--; - } - - // - i++; - start = i; - - // - // What type of X_ZG_SEARCH_EXTREMUM we Search for ... - if (lowsBuffer[i] != 0) - { - // - curlow = lowsBuffer[i]; - extreme_search = X_ZG_SEARCH_PEAK; - } - else - { - // - curhigh = highsBuffer[i]; - extreme_search = X_ZG_SEARCH_VALE; - } - - // - // Clear Values ... - for (i = start + 1; i < rates_total && !IsStopped(); i++) - { - // - mainBuffer[i] = 0; - lowsBuffer[i] = 0; - highsBuffer[i] = 0; - } - } - - // - // Search for High and Low Extremes ... - for (shift = start; shift < rates_total && !IsStopped(); shift++) - { - // - // Low ... - val = low[Lowest(low, depth, shift)]; - if (val == last_low) - { - val = 0; - } - else - { - // - last_low = val; - - // - if ((low[shift] - val) > deviation * _Point) - { - val = 0; - } - else - { - // - for (back = 1; back <= backStep; back++) - { - // - res = lowsBuffer[shift - back]; - if ((res != 0) && (res > val)) - { - lowsBuffer[shift - back] = 0; - } - } - } - } - - // - if (low[shift] == val) - { - lowsBuffer[shift] = val; - } - else - { - lowsBuffer[shift] = 0; - } - - // - // High ... - val = high[Highest(high, depth, shift)]; - if (val == last_high) - { - val = 0; - } - else - { - // - last_high = val; - - // - if ((val - high[shift]) > deviation * _Point) - { - val = 0; - } - else - { - // - for (back = 1; back <= backStep; back++) - { - // - res = highsBuffer[shift - back]; - if ((res != 0) && (res < val)) - { - highsBuffer[shift - back] = 0; - } - } - } - } - - // - if (high[shift] == val) - { - highsBuffer[shift] = val; - } - else - { - highsBuffer[shift] = 0; - } - } - - // - // Set Last Value ... - if (extreme_search == 0) // Undefined Values ... - { - // - last_low = 0; - last_high = 0; - } - else - { - // - last_low = curlow; - last_high = curhigh; - } - - // - // Final Selection of Extreme Points for ZigZag ... - for (shift = start; shift < rates_total && !IsStopped(); shift++) - { - // - res = 0; - - // - switch (extreme_search) - { - // - case X_ZG_SEARCH_EXTREMUM: - // - if (last_low == 0 && last_high == 0) - { - // - if (highsBuffer[shift] != 0) - { - // - last_high_pos = shift; - last_high = high[shift]; - - // - extreme_search = X_ZG_SEARCH_VALE; - - // - mainBuffer[shift] = last_high; - - // - res = 1; - } - - // - if (lowsBuffer[shift] != 0) - { - // - last_low_pos = shift; - last_low = low[shift]; - - // - extreme_search = X_ZG_SEARCH_PEAK; - - // - mainBuffer[shift] = last_low; - - // - res = 1; - } - } - break; - - // - case X_ZG_SEARCH_PEAK: - // - if (lowsBuffer[shift] != 0 && lowsBuffer[shift] < last_low && highsBuffer[shift] == 0) - { - // - mainBuffer[last_low_pos] = 0; - - // - last_low_pos = shift; - last_low = lowsBuffer[shift]; - - // - mainBuffer[shift] = last_low; - - // - res = 1; - } - - // - if (highsBuffer[shift] != 0 && lowsBuffer[shift] == 0) - { - // - last_high_pos = shift; - last_high = highsBuffer[shift]; - - // - mainBuffer[shift] = last_high; - - // - extreme_search = X_ZG_SEARCH_VALE; - - // - res = 1; - } - break; - - // - case X_ZG_SEARCH_VALE: - // - if (highsBuffer[shift] != 0 && highsBuffer[shift] > last_high && lowsBuffer[shift] == 0) - { - // - mainBuffer[last_high_pos] = 0; - - // - last_high_pos = shift; - last_high = highsBuffer[shift]; - - // - mainBuffer[shift] = last_high; - } - - // - if (lowsBuffer[shift] != 0 && highsBuffer[shift] == 0) - { - // - last_low_pos = shift; - last_low = lowsBuffer[shift]; - - // - mainBuffer[shift] = last_low; - - // - extreme_search = X_ZG_SEARCH_PEAK; - } - break; - } - - // - double iZigZagForColor = lastZigZagValue; - double iZigZag = mainBuffer[shift]; - if (iZigZag == 0 && lastZigZagValue != 0) - { - arrowBuffer[shift] = lastZigZagValue; - } - else if (iZigZag != 0) - { - // - lastZigZagValue = iZigZag; - arrowBuffer[shift] = lastZigZagValue; - } - - // - colorIDX = - lastZigZagValue > iZigZagForColor - ? 1 - : lastZigZagValue < iZigZagForColor - ? 2 - : colorIDX; - - // - mainColorBuffer[shift] = showZigZag ? colorIDX : 0; - arrowColorBuffer[shift] = showPeaksAndVales ? colorIDX : 0; - } - - // - return rates_total; -} - -// -// TOOLS ... - -// -// Search for the index of the highest bar ... -int Highest( - const double &mArray[], - const int mDepth, - const int mStart // -) -{ - // - int result = 0; - - // - if (mStart < 0) - { - return result; - } - - // - double max = mArray[mStart]; - result = mStart; - - // - // Start searching ... - for (int i = mStart - 1; i > mStart - mDepth && i >= 0; i--) - { - // - if (mArray[i] > max) - { - // - result = i; - max = mArray[i]; - } - } - - // - // Return index of the highest bar - return result; -} - -// -// Search for the index of the lowest bar ... -int Lowest( - const double &mArray[], - const int mDepth, - const int mStart // -) -{ - // - int result = 0; - - // - if (mStart < 0) - { - return result; - } - - // - double min = mArray[mStart]; - result = mStart; - - // - // Start searching ... - for (int i = mStart - 1; i > mStart - mDepth && i >= 0; i--) - { - // - if (mArray[i] < min) - { - // - result = i; - min = mArray[i]; - } - } - - // - // Return index of the lowest bar - return result; -} diff --git a/Documents/Pack/V1.0/Source/Libraries/x-saherelm.common.lib.mq5 b/Documents/Pack/V1.0/Source/Libraries/x-saherelm.common.lib.mq5 deleted file mode 100644 index f8d36ab3..00000000 --- a/Documents/Pack/V1.0/Source/Libraries/x-saherelm.common.lib.mq5 +++ /dev/null @@ -1,9064 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Common Library -// -------------------------------------- -// Name: XCommonLib -// Description: provide all commonly used functions ... -// -// -// Maintainer: -// ------------ -// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) -// -////////////////////////////////////////////////////// -// -// Global Properties ... -#property library -#property copyright "Copyright 2023, SaherElm IT Center" -#property link "https://www.saherelm.ir" -#property version "1.00" -#property strict - -// -// Imports ... -#include "../Classes/x-saherelm.xmd5.class.mq5" - -// -// Models ... - -// -// Specified Price Type ... -enum ENUM_X_PRICE -{ - X_PRICE_HIGH, - X_PRICE_OPEN, - X_PRICE_CLOSE, - X_PRICE_LOW -}; - -// -// Swing Types Enum ... -enum ENUM_X_SWING_TYPE -{ - X_NO_SWING = 0, - X_SWING_HIGH = 1, - X_SWING_LOW = -1, -}; - -// -ENUM_SERIESMODE ToSeriesMode(ENUM_X_SWING_TYPE value) -{ - // - ENUM_SERIESMODE result = MODE_HIGH; - - // - switch (value) - { - // - case X_SWING_HIGH: - result = MODE_HIGH; - break; - - // - case X_SWING_LOW: - result = MODE_LOW; - break; - } - - // - return result; -} - -// -// Find Swing Points ... -int FindSwing( - string mSymbol, // Trading Symbol ... - ENUM_TIMEFRAMES mPeriod, // Trading Period ... - ENUM_X_SWING_TYPE mMode, // Swing Based On Price mode ... - int mLength, // Loopback ... - int bar_index // BarIndex ... -) -{ - // - int result = -1; - - // - if (StringLen(mSymbol) == 0 || (mMode != X_SWING_HIGH && mMode != X_SWING_LOW)) - { - return result; - } - - // - int current = bar_index; - int founded = FindNextSwing( - mSymbol, - mPeriod, - mMode, - (mLength * 2) + 1, - current - mLength); - - // - while (founded != current) - { - // - current = FindNextSwing( - mSymbol, - mPeriod, - mMode, - mLength, - current + 1); - - // - founded = FindNextSwing( - mSymbol, - mPeriod, - mMode, - (mLength * 2) + 1, - current - mLength); - } - - // - result = current; - - // - return result; -} - -// -// Find Next Swing ... -int FindNextSwing( - string mSymbol, // Trading Symbol ... - ENUM_TIMEFRAMES mPeriod, // Trading Period ... - ENUM_X_SWING_TYPE mMode, // Swing Based On Price mode ... - int mLength, // Loopback ... - int bar_index // BarIndex ... -) -{ - // - int result = -1; - - // - if (bar_index < 0) - { - mLength += bar_index; - bar_index = 0; - } - - // - ENUM_SERIESMODE mSeriesMode = ToSeriesMode(mMode); - - // - result = mMode == X_SWING_HIGH - ? iHighest( - mSymbol, - mPeriod, - mSeriesMode, - mLength, - bar_index) - : iLowest( - mSymbol, - mPeriod, - mSeriesMode, - mLength, - bar_index); - - // - return result; -} - -// -// XPERIOD Calculation Method ... -enum ENUM_X_PERIOD_METHOD -{ - // - X_PERIOD_NOTHING, // Nothing - X_PERIOD_AUTO, // Auto Select - X_PERIOD_MANUALLY // Manually -}; - -// -// Available Market Cycles ... -enum ENUM_X_MARKET_CYCLES -{ - // - X_MARKET_CYCLE_UNKNOWN, // Unknown Cycle - X_MARKET_CYCLE_SHORT, // Short Cycle - X_MARKET_CYCLE_MEDIUM, // Medium Cycle - X_MARKET_CYCLE_LONG, // Long Cycle - X_MARKET_CYCLE_HIND, // Hind Cycle -}; - -// -// Structs ... - -// -// Model a Bar Remains Time ... -struct XBarRemainsTime -{ - // - int days; - int hours; - int minutes; - int seconds; - - // - // Constructor ... - XBarRemainsTime() - { - Clean(); - } - - // - // Always Calculate Current 0 Bar Timing ... - bool Init( - string mSymbol = NULL, // Trading Symbol - ENUM_TIMEFRAMES mPeriod = NULL // Trading Period - ) - { - // - bool result = false; - - // - mSymbol = NormalizeSymbol(mSymbol); - mPeriod = NormalizePeriod(mPeriod); - - // - int minuteSecoonds = 60; - int hourSeconds = minuteSecoonds * 60; - int daySeconds = 24 * hourSeconds; - - // - int periodSeconds = PeriodSeconds( - mPeriod); - datetime startTime = GetBarTime( - mSymbol, - mPeriod, - 0 - // - ); - - // - int secondsDiff = (int)startTime + periodSeconds - (int)TimeCurrent(); - - // - int mWorkingSecondsDiff = secondsDiff; - if (mWorkingSecondsDiff > daySeconds) - { - // - days = mWorkingSecondsDiff / daySeconds; - mWorkingSecondsDiff -= days * daySeconds; - } - if (mWorkingSecondsDiff > hourSeconds) - { - // - hours = mWorkingSecondsDiff / hourSeconds; - mWorkingSecondsDiff -= hours * hourSeconds; - } - if (mWorkingSecondsDiff > minuteSecoonds) - { - // - minutes = mWorkingSecondsDiff / minuteSecoonds; - mWorkingSecondsDiff -= minutes * minuteSecoonds; - } - seconds = mWorkingSecondsDiff; - - // - result = true; - - // - return result; - } - - // - // Tools ... - - // - // Cleanup ... - void Clean() - { - days = 0; - hours = 0; - minutes = 0; - seconds = 0; - } - - // - // To String Representation ... - string ToString( - string dayId = "d", - string hourId = "h", - string minuteId = "m", - string secondId = "s", - string idSeparator = ": ", - string separator = ", ", - bool ignoreZeroValues = true - // - ) - { - // - string result = ""; - - // - // Days ... - if (!ignoreZeroValues || days > 0) - { - result += dayId + idSeparator + (string)days + separator; - } - - // - // Hours ... - if (!ignoreZeroValues || hours > 0) - { - // - string strHour = ToString(hours); - if (StringLen(strHour) == 1) - { - strHour = "0" + strHour; - } - - // - result += hourId + idSeparator + strHour + separator; - } - - // - // Minutes ... - if (!ignoreZeroValues || minutes > 0) - { - // - string strMinute = ToString(minutes); - if (StringLen(strMinute) == 1) - { - strMinute = "0" + strMinute; - } - - // - result += minuteId + idSeparator + strMinute + separator; - } - - // - // Seconds ... - if (!ignoreZeroValues || seconds > 0) - { - // - string strSec = ToString(seconds); - if (StringLen(strSec) == 1) - { - strSec = "0" + strSec; - } - - // - result += secondId + idSeparator + strSec; - } - - // - return result; - } -}; - -// -// Describe an Specific Candle ... -struct XOHCL -{ - // - // Props ... - - // - double high; - double open; - double close; - double low; - - // - string symbol; - datetime time; - ENUM_TIMEFRAMES period; - - // - // Constructor ... - XOHCL() - { - Clean(); - } - - // - // Init a Bar ... - // Using Bar Index ... - bool Init( - string mSymbol = NULL, // Trading Symbol - ENUM_TIMEFRAMES mPeriod = NULL, // Trading Period - int barIndex = 0 // Bar Index - ) - { - // - mSymbol = NormalizeSymbol(mSymbol); - mPeriod = NormalizePeriod(mPeriod); - - // - symbol = mSymbol; - period = mPeriod; - - // - time = iTime( - mSymbol, - mPeriod, - barIndex - // - ); - - // - open = iOpen( - mSymbol, - mPeriod, - barIndex - // - ); - - // - close = iClose( - mSymbol, - mPeriod, - barIndex - // - ); - - // - high = iHigh( - mSymbol, - mPeriod, - barIndex); - - // - low = iLow( - mSymbol, - mPeriod, - barIndex - // - ); - - // - bool result = IsValid(); - - // - return result; - } - - // - // Init a Bar ... - // Using Bar Time ... - bool Init( - string mSymbol = NULL, // Trading Symbol - ENUM_TIMEFRAMES mPeriod = NULL, // Trading Period - datetime mTime = NULL // Bar Time - ) - { - // - mTime = NormalizeTime(mTime); - - // - int barIndex = iBarShift( - mSymbol, - mPeriod, - mTime, - false // - ); - - // - bool result = Init( - mSymbol, - mPeriod, - barIndex - // - ); - - // - return result; - } - - // - bool Init( - string mSymbol = NULL, // Trading Symbol - ENUM_TIMEFRAMES mPeriod = NULL, // Trading Period - double mOpen = 0, // Open - double mHigh = 0, // High - double mClose = 0, // Close - double mLow = 0, // Low - int barIndex = 0 // Bar Index - ) - { - // - mSymbol = NormalizeSymbol(mSymbol); - mPeriod = NormalizePeriod(mPeriod); - - // - symbol = mSymbol; - period = mPeriod; - - // - time = iTime( - mSymbol, - mPeriod, - barIndex - // - ); - - // - open = mOpen; - high = mHigh; - close = mClose; - low = mLow; - - // - return IsValid(); - } - - // - bool Init( - string mSymbol = NULL, // Trading Symbol - ENUM_TIMEFRAMES mPeriod = NULL, // Trading Period - double mOpen = 0, // Open - double mHigh = 0, // High - double mClose = 0, // Close - double mLow = 0, // Low - datetime mTime = NULL // Bar Time - ) - { - // - mSymbol = NormalizeSymbol(mSymbol); - mPeriod = NormalizePeriod(mPeriod); - - // - symbol = mSymbol; - period = mPeriod; - - // - int barIndex = iBarShift( - symbol, - period, - mTime); - - // - time = iTime( - mSymbol, - mPeriod, - barIndex - // - ); - - // - open = mOpen; - high = mHigh; - close = mClose; - low = mLow; - - // - return IsValid(); - } - - // - // Tools ... - - // - void Clean() - { - // - high = 0; - open = 0; - close = 0; - low = 0; - - // - time = NULL; - symbol = NULL; - period = NULL; - } - - // - // Validate Bar ... - bool IsValid() - { - // - bool result = false; - - // - result = - // - high > 0 && - open > 0 && - close > 0 && - low > 0 - // - ; - - // - return result; - } - - // - // Calculate X_PRICE Specified Type ... - double GetPrice(ENUM_X_PRICE mPType) - { - // - double result = 0; - - // - if (!IsValid()) - { - return result; - } - - // - switch (mPType) - { - // - case X_PRICE_OPEN: - result = open; - break; - // - case X_PRICE_HIGH: - result = high; - break; - // - case X_PRICE_CLOSE: - result = close; - break; - // - case X_PRICE_LOW: - result = low; - break; - } - - // - return result; - } - - // - // Retrieve Price base On Series Mode ... - double GetPrice(ENUM_SERIESMODE mMode) - { - // - ENUM_X_PRICE mXMode = ToPrice(mMode); - - // - return GetPrice(mXMode); - } - - // - // Calculate Applied Price ... - double GetPrice( - ENUM_APPLIED_PRICE mAppliedTo // Select Application Method - ) - { - // - double result = 0; - - // - // Calculate Applied Price ... - switch (mAppliedTo) - { - // - case PRICE_CLOSE: - result = close; - break; - - // - case PRICE_OPEN: - result = open; - break; - - // - case PRICE_HIGH: - result = high; - break; - - // - case PRICE_LOW: - result = low; - break; - - // - case PRICE_MEDIAN: - result = (high + low) / 2; - break; - - // - case PRICE_TYPICAL: - result = (high + low + close) / 3; - break; - - // - case PRICE_WEIGHTED: - result = (high + low + close + close) / 4; - break; - } - - // - return result; - } - - // - // Calculate Bar Mid Line ... - double GetMid() - { - // - double result = 0; - - // - if (!IsValid()) - { - return result; - } - - // - result = (high + low) / 2; - - // - return result; - } - - // - // Calculate up Price ... - double GetUp() - { - // - double result = 0; - - // - if (!IsValid()) - { - return result; - } - - // - result = MathMax(open, close); - - // - return result; - } - - // - // Calculate Down Price ... - double GetDown() - { - // - double result = 0; - - // - if (!IsValid()) - { - return result; - } - - // - result = MathMin(open, close); - - // - return result; - } - - // - // Calculate Bar Body ... - double GetBody() - { - // - double result = 0; - - // - if (!IsValid()) - { - return result; - } - - // - result = GetUp() - GetDown(); - - // - return result; - } - - // - // Calculate Bar Range ... - double GetRange() - { - // - double result = 0; - - // - if (!IsValid()) - { - return result; - } - - // - result = high - low; - - // - return result; - } - - // - // Calculate Bar Shadows ... - double GetShadows() - { - // - double result = 0; - - // - if (!IsValid()) - { - return result; - } - - // - result = GetRange() - GetBody(); - - // - return result; - } - - // - // Calculate Bar High Shadow ... - double GetHighShadow() - { - // - double result = 0; - - // - if (!IsValid()) - { - return result; - } - - // - result = - // - high - GetUp() - // - ; - - // - return result; - } - - // - // Calculate Bar Low Shadow ... - double GetLowShadow() - { - // - double result = 0; - - // - if (!IsValid()) - { - return result; - } - - // - result = - // - GetDown() - low; - // - ; - - // - return result; - } - - // - // Check Bar is Bullish ... - bool IsBullish() - { - // - bool result = false; - - // - if (!IsValid()) - { - return result; - } - - // - result = open < close; - - // - return result; - } - - // - // Check Bar is Bearish ... - bool IsBearish() - { - // - bool result = false; - - // - if (!IsValid()) - { - return result; - } - - // - result = open > close; - - // - return result; - } - - // - // Find Next Bar Time ... - datetime NextAt() - { - // - datetime result = NULL; - - // - if (!IsValid()) - { - return result; - } - - // - int prSeconds = PeriodSeconds(period); - - // - result = time + prSeconds; - - // - return result; - } - - // - // Find Prev Bar Time ... - datetime BeforeOn() - { - // - datetime result = NULL; - - // - if (!IsValid()) - { - return result; - } - - // - int prSeconds = PeriodSeconds(period); - - // - result = time - prSeconds; - - // - return result; - } - - // - // Find Current Bar Index on Chart ... - int Index() - { - // - int result = -1; - - // - if (!IsValid()) - { - return result; - } - - // - result = iBarShift( - symbol, - period, - time - // - ); - - // - return result; - } - - // - bool GetPreviousBar(XOHCL &bar) - { - // - bool result = false; - - // - result = IsValid(); - if (!result) - { - return result; - } - - // - int idx = Index(); - - // - result = bar.Init( - this.symbol, - this.period, - idx + 1 // - ); - - // - return result; - } - - // - // Check Bar has Strong Body or Not ... - bool HasStrongBody() - { - // - bool result = false; - - // - if (!IsValid()) - { - return result; - } - - // - double body = GetBody(); - double shadow = GetShadows(); - - // - result = body > shadow * 1.5; - - // - return result; - } - - // - // Bar Must Open Below Prce - // and Close Above it ... - bool IsBreakUp( - double price // a Price to Check Breake - ) - { - // - bool result = false; - - // - result = HasStrongBody(); - if (!result || price <= 0) - { - return result; - } - - // - // Select required Prices ... - - // - result = - // - close > price && - open < price; - - // - return result; - } - - // - // Bar Must Open Above Prce - // and Close Below it ... - bool IsBreakDown( - double price // a Price to Check Breake - ) - { - // - bool result = false; - - // - result = HasStrongBody(); - if (!result || price <= 0) - { - return result; - } - - // - // Select required Prices ... - - // - result = - // - open > price && - close < price; - - // - return result; - } - - // - bool IsBreakOut( - double price, // a Price to Check Breake - bool useHighLow = true // if true using High and Low price for Breakeouts, if not use Open Close - ) - { - // - bool result = false; - - // - result = HasStrongBody(); - if (!result || price <= 0) - { - return result; - } - - // - // Select required Prices ... - - // - double selectedUp = - useHighLow - ? high - : GetUp(); - double selectedDown = - useHighLow - ? low - : GetDown(); - - // - result = - // - selectedUp > price && - selectedDown < price; - - // - return result; - } - - // - // Check a Support Line Rejected or not ... - bool IsSupportRejected( - double price // Support Price - ) - { - // - bool result = false; - - // - // this is zBar ... - // so we are try to Recieve CBar ... - XOHCL cBar; - result = this.GetPreviousBar(cBar); - if (!result) - { - return result; - } - - // - // Now we are going to Recieve PBar ... - XOHCL pBar; - result = cBar.GetPreviousBar(pBar); - if (!result) - { - return result; - } - - // - // We Have this (0) Bar, cBar (1) and pBar (2) ... - - // - // pBar Down Shadow must break Price Line ... - // cBar and zBar Close must be Above Price Line ... - // also zBar Open must be Above Price Line ... - result = - // - pBar.high > price && - pBar.low < price && - cBar.close > price && - this.close > price && - this.open > price - // - ; - - // - return result; - } - - // - // Check a Support Line Breaked or not ... - bool IsSupportBreaked( - double price // Support Price - ) - { - // - bool result = false; - - // - // this is zBar ... - // so we are try to Recieve CBar ... - XOHCL cBar; - result = this.GetPreviousBar(cBar); - if (!result) - { - return result; - } - - // - // Now we are going to Recieve PBar ... - XOHCL pBar; - result = cBar.GetPreviousBar(pBar); - if (!result) - { - return result; - } - - // - // We Have this (0) Bar, cBar (1) and pBar (2) ... - - // - // pBar Down Shadow must break Price Line ... - // cBar and zBar Close must be Below Price Line ... - // also zBar Open must be Below Price Line ... - result = - // - pBar.high > price && - pBar.low < price && - cBar.close < price && - this.close < price && - this.open < price - // - ; - - // - return result; - } - - // - // Check a Resistance Line Rejected or not ... - bool IsResistanceRejected( - double price // Resistance Price - ) - { - // - bool result = false; - - // - // this is zBar ... - // so we are try to Recieve CBar ... - XOHCL cBar; - result = this.GetPreviousBar(cBar); - if (!result) - { - return result; - } - - // - // Now we are going to Recieve PBar ... - XOHCL pBar; - result = cBar.GetPreviousBar(pBar); - if (!result) - { - return result; - } - - // - // We Have this (0) Bar, cBar (1) and pBar (2) ... - - // - // pBar Up Shadow must break Price Line ... - // cBar and zBar Close must be Under Price Line ... - // also zBar Open must be Under Price Line ... - result = - // - pBar.high > price && - pBar.low < price && - cBar.close < price && - this.close < price && - this.open < price - // - ; - - // - return result; - } - - // - // Check a Resistance Line Breaked or not ... - bool IsResistanceBreaked( - double price // Support Price - ) - { - // - bool result = false; - - // - // this is zBar ... - // so we are try to Recieve CBar ... - XOHCL cBar; - result = this.GetPreviousBar(cBar); - if (!result) - { - return result; - } - - // - // Now we are going to Recieve PBar ... - XOHCL pBar; - result = cBar.GetPreviousBar(pBar); - if (!result) - { - return result; - } - - // - // We Have this (0) Bar, cBar (1) and pBar (2) ... - - // - // pBar Up Shadow must break Price Line ... - // cBar and zBar Close must be Over Price Line ... - // also zBar Open must be Pver Price Line ... - result = - // - pBar.low < price && - pBar.high > price && - cBar.close > price && - this.close > price && - this.open > price - // - ; - - // - return result; - } - - // - // Check Bar is Inside Previus Bar ... - bool IsInsideBar( - double threshold = 5 // Points Distance between Up and Down - ) - { - // - bool result = false; - - // - if (threshold < 0) - { - threshold = 0; - } - - // - XOHCL pBar; - result = GetPreviousBar(pBar); - if (!result) - { - return result; - } - - // - double offset = PointToPrice(threshold, this.symbol); - - // - result = - // - pBar.high > this.high && - pBar.low < this.low && - MathAbs(pBar.low - this.low) > offset && - MathAbs(pBar.high - this.high) > offset - // - ; - - // - return result; - } - - // - // Check Bar has Strongest Body in a Range ... - bool HasStrongestBody( - int mLoopback = 3 // loopback candles to compare it ... - ) - { - // - bool result = false; - - // - result = IsValid(); - if (!result) - { - return result; - } - - // - double body = GetBody(); - XOHCL prev = this; - for (int i = 0; i < mLoopback; i++) - { - // - bool isValid = prev.GetPreviousBar(prev); - if (!isValid) - { - // - result = false; - break; - } - - // - result = - // - result && - body > prev.GetBody() - // - ; - if (!result) - { - break; - } - } - - // - return result; - } - - // - // Check Bar has Weakest Body in a Range ... - bool HasWeakestBody( - int mLoopback = 3 // loopback candles to compare it ... - ) - { - // - bool result = false; - - // - result = IsValid(); - if (!result) - { - return result; - } - - // - double body = GetBody(); - XOHCL prev = this; - for (int i = 0; i < mLoopback; i++) - { - // - bool isValid = prev.GetPreviousBar(prev); - if (!isValid) - { - // - result = false; - break; - } - - // - result = - // - result && - body < prev.GetBody() - // - ; - if (!result) - { - break; - } - } - - // - return result; - } - - // - // Determines Swings based On this Bar ... - // Calculates Based on atleast 3 Bars Prev ... - ENUM_X_SWING_TYPE GetSwingType() - { - // - ENUM_X_SWING_TYPE result = X_NO_SWING; - - // - // Find Current Index of Bar ... - int barIndex = Index(); - if (barIndex <= -1) - { - return result; - } - - // - // First we have to Retrieve atleast 3 Bars before this bar ... - XOHCL bars[]; - int barsCount = GetBars( - bars, - symbol, - period, - barIndex + 1, - 3 - // - ); - if (barsCount < 3) - { - return result; - } - - // - // Check Swing Start Candle has Strong Body ... - bool isStrongBodyCandle = bars[2].HasStrongBody(); - if (!isStrongBodyCandle) - { - return result; - } - - // - // Check Swing Low Conditions ... - bool isSwingLowOrderBlock = - bars[2].low < bars[1].low && - bars[1].low < bars[0].low && - bars[2].low < bars[0].low; - if (isSwingLowOrderBlock) - { - result = X_SWING_LOW; - } - - // - // Check Swing High Conditions ... - bool isSwingHighOrderBlock = - bars[2].high > bars[1].high && - bars[1].high > bars[0].high && - bars[2].high > bars[0].high; - if (isSwingHighOrderBlock) - { - result = X_SWING_HIGH; - } - - // - return result; - } - - // - // Find Lowest Bar Index ... - int FindHighestIndex( - int mLength, // Loopback ... - ENUM_SERIESMODE mMode // Calculation mode - ) - { - // - int result = -1; - - // - if (!IsValid()) - { - return result; - } - - // - if (mLength < 2) - { - mLength = 2; - } - - // - result = iHighest( - symbol, - period, - mMode, - mLength, - Index()); - - // - return result; - } - - // - // Find Lowest ... - double FindHighest( - int mLength, // Loopback ... - ENUM_SERIESMODE mMode // Calculation mode - ) - { - // - double result = 0; - - // - if (!IsValid()) - { - return result; - } - - // - int idx = FindHighestIndex( - mLength, - mMode); - if (idx <= -1) - { - return result; - } - - // - XOHCL iH; - result = iH.Init( - symbol, - period, - idx - // - ); - if (!result) - { - return result; - } - - // - result = iH.GetPrice(mMode); - - // - return result; - } - - // - // Find Lowest Bar Index ... - int FindLowestIndex( - int mLength, // Loopback ... - ENUM_SERIESMODE mMode // Calculation mode - ) - { - // - int result = -1; - - // - if (!IsValid()) - { - return result; - } - - // - if (mLength < 2) - { - mLength = 2; - } - - // - result = iLowest( - symbol, - period, - mMode, - mLength, - Index()); - - // - return result; - } - - // - // Find Lowest ... - double FindLowest( - int mLength, // Loopback ... - ENUM_SERIESMODE mMode // Calculation mode - ) - { - // - double result = 0; - - // - if (!IsValid()) - { - return result; - } - - // - int idx = FindLowestIndex( - mLength, - mMode); - if (idx <= -1) - { - return result; - } - - // - XOHCL iL; - result = iL.Init( - symbol, - period, - idx - // - ); - if (!result) - { - return result; - } - - // - result = iL.GetPrice(mMode); - - // - return result; - } - - // - // Candlestic Tools ... - - // - bool IsDoji() - { - // - bool result = false; - - // - // Validate Content and Ignore 0 Bar - // since it is not Completed ... - result = IsValid() && Index() > 0; - if (!result) - { - return result; - } - - // - result = open == close; - - // - return result; - } - - // - // Convert to String Representation ... - string ToString() - { - // - string result = ""; - - // - result = GetTypeName(this) + - "(O(" + ToString(open) + "),H(" + ToString(high) + "),C(" + ToString(close) + "),L(" + ToString(low) + "))"; - - // - return result; - } -}; - -// -struct XPivot -{ - // - double pivot; // Pivot Price ... - int breaks; // Number of Breaks ... - int rejects; // Number of Rejects ... - - // - void XPivot() - { - Clean(); - } - - // - // Tools ... - - // - // Cleanup ... - void Clean() - { - // - pivot = 0; - breaks = 0; - rejects = 0; - } - - // - // Validate ... - bool IsValid() - { - // - bool result = false; - - // - result = pivot > 0; - - // - return result; - } -}; - -// -struct XPivotTracker -{ - // - XPivot pivots[]; - - // - // Constructor ... - void XPivotTracker() - { - Clean(); - } - - // - // Tools ... - - // - // Cleanup ... - void Clean() - { - // - Clean(pivots); - } - - // - int Count() - { - return ArraySize(pivots); - } - - // - double Get(int index) - { - // - double result = 0; - - // - NormalizeIndex(index, pivots); - - // - XPivot iPivot = pivots[index]; - - // - result = iPivot.pivot; - - // - return result; - } - - // - XPivot GetPivot(int index) - { - // - XPivot result; - - // - NormalizeIndex(index, pivots); - - // - result = pivots[index]; - - // - return result; - } - - // - bool Add(double mPivot) - { - // - bool result = false; - - // - result = mPivot > 0 && !Has(mPivot); - if (!result) - { - return result; - } - - // - XPivot pivot; - pivot.pivot = mPivot; - - // - AddRef( - pivot, - pivots // - ); - - // - result = true; - - // - return result; - } - - // - int Adds(double &mPivots[]) - { - // - int result = 0; - - // - int pivotsCount = ArraySize(mPivots); - if (!IsValidSize(pivotsCount)) - { - return result; - } - - // - for (int i = 0; i < pivotsCount; i++) - { - // - double iPivot = mPivots[i]; - - // - bool isAdded = Add(iPivot); - if (isAdded) - { - result++; - } - } - - // - return result; - } - - // - int FindIndex(double mPivot) - { - // - int result = -1; - - // - if (mPivot <= 0) - { - return result; - } - - // - int count = Count(); - if (!IsValidSize(count)) - { - return result; - } - - // - for (int i = 0; i < count; i++) - { - // - XPivot iPivot = pivots[i]; - - // - if (iPivot.pivot == mPivot) - { - // - result = i; - break; - } - } - - // - return result; - } - - // - double Has(double mPivot) - { - // - bool result = false; - - // - int pivotIDX = FindIndex(mPivot); - result = pivotIDX >= 0; - - // - return result; - } - - // - int Reject(double mPivot) - { - // - int result = 0; - - // - int pivotIDX = FindIndex(mPivot); - if (pivotIDX < 0) - { - return result; - } - - // - pivots[pivotIDX].rejects++; - - // - result = pivots[pivotIDX].rejects; - - // - return result; - } - - // - int Break(double mPivot) - { - // - int result = 0; - - // - int pivotIDX = FindIndex(mPivot); - if (pivotIDX < 0) - { - return result; - } - - // - pivots[pivotIDX].breaks++; - - // - result = pivots[pivotIDX].breaks; - - // - return result; - } - - // - bool Remove(double mPivot) - { - // - bool result = false; - - // - int pivotIDX = FindIndex(mPivot); - result = pivotIDX >= 0; - if (!result) - { - return result; - } - - // - result = ArrayRemove( - pivots, - pivotIDX, - 1 // - ); - - // - return result; - } - - // - bool HasChild() - { - // - bool result = false; - - // - int count = Count(); - result = IsValidSize(count); - - // - return result; - } -}; - -// -// Model Support and Resistance -// for Specific Bar ... -struct XOHCLSupRes -{ - // - // Props ... - - // - /// Resistances ... - double res[]; - - // - // Supports ... - double sup[]; - - // - // Constructor ... - XOHCLSupRes() - { - Clean(); - } - - // - // Init ... - bool Init( - double price, // Price ... - const double &pivots[], // Provided Pivot Points ... - int count = 3, // Number of Requireds ... - double step = 0 // Distance between each item with it's Last Side ... - ) - { - // - bool result = false; - - // - Clean(); - - // - if (price <= 0) - { - return result; - } - - // - int pivotsCount = ArraySize(pivots); - if (pivotsCount <= 0) - { - return result; - } - - // - if (count <= 0 || - count > pivotsCount - 1) - { - return result; - } - - // - double lastR = 0; - double tmpR[]; - - // - double lastS = 0; - double tmpS[]; - - // - // Extract Supports ... - // which prices is under low of candle ... - // - // Extract Resistance ... - // which prices is over high of candle ... - for (int i = 0; i < pivotsCount; i++) - { - // - double iFlat = pivots[i]; - - // - if (iFlat > price) - { - // - bool canAdd = - step <= 0 - ? true - : lastR == 0 || MathAbs(iFlat - lastR) >= step; - if (canAdd) - { - // - Add( - iFlat, - tmpR); - - // - lastR = iFlat; - } - } - else if (iFlat < price) - { - // - bool canAdd = - step <= 0 - ? true - : lastS == 0 || MathAbs(iFlat - lastS) >= step; - if (canAdd) - { - // - Add( - iFlat, - tmpS); - - // - lastS = iFlat; - } - } - } - - // - // Sorting Founded Resistance and Supports ... - - // - // Since Resistance Levels must be Increasing ... - ArraySort(tmpR); - - // - // Since Support Levels must be Decreasing ... - ArraySort(tmpS); - ArrayReverse(tmpS); - - // - // Fill Resistance ... - int tmpRCount = ArraySize(tmpR); - if (tmpRCount > 0) - { - // - if (tmpRCount < count) - { - // - ArrayCopy( - res, - tmpR); - } - else - { - // - ArrayCopy( - res, - tmpR, - 0, - 0, - count); - } - } - - // - // Fill Supports ... - int tmpSCount = ArraySize(tmpS); - if (tmpSCount > 0) - { - // - if (tmpSCount < count) - { - // - ArrayCopy( - sup, - tmpS); - } - else - { - // - ArrayCopy( - sup, - tmpS, - 0, - 0, - count); - } - } - - // - result = IsValid(); - - // - return result; - } - - // - // Tools ... - - // - // Cleanup ... - void Clean() - { - // - Clean(sup); - Clean(res); - } - - // - // Validate ... - bool IsValid() - { - // - bool result = false; - - // - result = - // - CountSupports() > 0 || - CountResistances() > 0 - // - ; - - // - return result; - } - - // - int CountSupports() - { - return ArraySize(sup); - } - - // - int CountResistances() - { - return ArraySize(res); - } -}; - -// -// Tracking Times ... -struct XTimeTracker -{ - // - // Props ... - int xMonth; - int xDayOfWeek; - int xForWeekDay; - int xDay; - int xHour; - - // - // Constructor ... - XTimeTracker() - { - Clean(); - } - - // - // Tools ... - - // - void Clean() - { - // - xDay = -1; - xHour = -1; - xMonth = -1; - xDayOfWeek = -1; - xForWeekDay = -1; - } - - // - // Detecting New Houre ... - bool IsNewHour() - { - // - bool result = false; - - // - // Retrieve Current Time as Struct ... - MqlDateTime timeStruct = GetCurrentTime(); - - // - // Check Houre ... - result = timeStruct.hour != xHour; - if (result) - { - xHour = timeStruct.hour; - } - - // - return result; - } - - // - // Detecting New Day ... - bool IsNewDay() - { - // - bool result = false; - - // - // Retrieve Current Time as Struct ... - MqlDateTime timeStruct = GetCurrentTime(); - - // - // Check Houre ... - result = timeStruct.day_of_year != xDay; - if (result) - { - xDay = timeStruct.day_of_year; - } - - // - return result; - } - - // - // Detecting New Week ... - bool IsNewWeek() - { - // - bool result = false; - - // - // Retrieve Current Time as Struct ... - MqlDateTime timeStruct = GetCurrentTime(); - - // - // Check Week ... - // Since Week Starts From Monday in Forex World ... - // we Calculate Start of Week by 1-Monday ... - result = - xDayOfWeek == -1 && - xForWeekDay == -1 - ? true - : timeStruct.day_of_week == 1 && - timeStruct.day_of_year > xForWeekDay; - - // - xForWeekDay = timeStruct.day_of_year; - xDayOfWeek = timeStruct.day_of_week; - - // - return result; - } - - // - // Detecting End Of Week ... - bool IsWeekEnd() - { - // - bool result = false; - - // - // Retrieve Current Time as Struct ... - MqlDateTime timeStruct = GetCurrentTime(); - - // - // Check WeekEnd ... - // Since Week Starts From Monday in Forex World ... - // we Calculate End of Week by 5-Friday ... - result = - xDayOfWeek != -1 && - timeStruct.day_of_week == 5 && - timeStruct.hour == 23 && - timeStruct.min == 59 && - timeStruct.sec == 59; - - // - return result; - } - - // - // Detecting New Month ... - bool IsNewMonth() - { - // - bool result = false; - - // - // Retrieve Current Time as Struct ... - MqlDateTime timeStruct = GetCurrentTime(); - - // - // Check Houre ... - result = timeStruct.mon != xMonth; - if (result) - { - xMonth = timeStruct.mon; - } - - // - return result; - } -}; - -// -// Tracking Bars on Specified Environment ... -struct XBarTracker -{ - // - string symbol; // Tracking Symbol - ENUM_TIMEFRAMES period; // Tracking Time Frame - - // - int lastTrackedBar; // Last Tracked Bar ... - - // - bool waitsUntilNext; // Waits Until Next Bar ... - - // - // Constructor ... - XBarTracker() - { - Clean(); - } - - // - // Initializer ... - bool Init( - string mSymbol = NULL, // Trading Symbol - ENUM_TIMEFRAMES mPeriod = NULL // Trading Period - ) - { - // - bool result = false; - - // - mSymbol = NormalizeSymbol(mSymbol); - mPeriod = NormalizePeriod(mPeriod); - - // - this.symbol = mSymbol; - this.period = mPeriod; - - // - this.lastTrackedBar = 0; - - // - result = true; - - // - return result; - } - - // - // Retrieve all Bars ... - int CountBars() - { - // - return Bars( - symbol, - period - // - ); - } - - // - // Check if it's New Bar ... - bool IsNewBar() - { - // - bool result = false; - - // - int currentBars = CountBars(); - - // - result = currentBars > lastTrackedBar; - if (result) - { - lastTrackedBar = currentBars; - } - - // - return result; - } - - // - bool CanProcessBar() - { - // - bool isInTestMode = IsRunningOnTestMode(); - - // - bool isNewBar = IsNewBar(); - - // - bool result = - isInTestMode - ? isNewBar - : !waitsUntilNext - ? true - : isNewBar; - if (result && waitsUntilNext) - { - waitsUntilNext = false; - } - - // - return result; - } - - // - void Waits() - { - this.waitsUntilNext = true; - } - - // - // Tools ... - void Clean() - { - // - symbol = NormalizeSymbol(NULL); - period = NormalizePeriod(NULL); - } - - // - bool GetBar( - XOHCL &bar, - int index = 0 // - ) - { - // - bool result = false; - - // - result = bar.Init( - symbol, - period, - index // - ); - - // - return result; - } - - // - bool GetBar( - XOHCL &bar, - datetime time = NULL // - ) - { - // - bool result = false; - - // - NormalizeTime(time); - - // - int barIndex = iBarShift( - symbol, - period, - time, - false // - ); - - // - result = barIndex >= 0; - if (!result) - { - return result; - } - - // - result = bar.Init( - symbol, - period, - barIndex // - ); - - // - return result; - } - - // - int Index(datetime time = NULL) - { - // - int result = 0; - - // - NormalizeTime(time); - - // - result = iBarShift( - symbol, - period, - time, - false // - ); - - // - return result; - } -}; - -// -// Track Value Changes ... -template -struct XValueTracker -{ - // - // Definitions ... - - // - // Model a Value Change ... - struct XValueChange - { - // - // Props ... - datetime at; // Change Time - T from; // Before Change Value - T to; // After Change Value - - // - // Constructor ... - XValueChange() - { - Clean(); - } - - // - // Cleanup ... - void Clean() - { - // - at = NULL; - from = NULL; - to = NULL; - } - - // - // Validate ... - bool IsValid() - { - // - bool result = false; - - // - result = IsValid(at); - if (!result) - { - return result; - } - - // - result = NotEmpty(from) && - NotEmpty(to); - - // - return result; - } - }; - - // - // Props ... - XValueChange changes[]; // Hold Changes - - // - // Constructor ... - XValueTracker() - { - Clean(); - } - - // - // Track a Change Happens Or Not ... - bool Track( - const T &source[] // Data Source for Track Changes - ) - { - // - bool result = false; - - // - if (ArraySize(source) <= 1) - { - return result; - } - - // - datetime time = TimeCurrent(); - - // - double from = source[1]; - double to = source[0]; - - // - result = to != from; - if (result) - { - return result; - } - - // - XValueChange lastChange; - bool hasLastChange = - GetLastItem( - lastChange, - changes - // - ); - result = - !hasLastChange - ? true - : lastChange.at < time && - lastChange.to != to && - lastChange.from != from; - if (!result) - { - return result; - } - - // - lastChange.Clean(); - - // - lastChange.to = to; - lastChange.at = time; - lastChange.from = from; - - // - AddRef( - lastChange, - changes - // - ); - - // - return result; - } - - // - // Tools ... - - // - // Cleanup ... - void Clean() - { - Clean(changes); - } -}; - -// -// Model a Market Cycle ... -struct XMarketCycle -{ - // - // Props ... - - // - string prefix; // Prefix Trag ... - - // - string symbol; // Market Symbol ... - - // - ENUM_TIMEFRAMES period; // Period of Cycle ... - ENUM_X_PERIOD_METHOD method; // Period Selection Method ... - ENUM_X_MARKET_CYCLES cycle; // Cycles of MArket ... - - // - int length; // Number Of Candles per Current Time Frame ... - ENUM_TIMEFRAMES hostPeriod; // Current Time Frame ... - - // - datetime lastStart; // Last Candle Bar Time ... - - // - XBarTracker barTracker; // Bar Tracker ... - XBarRemainsTime remains; // Current Bar Remains Model ... - - // - // Constructor ... - XMarketCycle() - { - Clean(); - } - - // - // Init Cycle ... - bool Init( - string mSymbol, // Trading Symbol - ENUM_TIMEFRAMES mHostPeriod, // Host Period - ENUM_X_MARKET_CYCLES mCycle, // Init Cycle - string mPrefix = "" // Prefix - ) - { - // - bool result = false; - - // - mSymbol = NormalizeSymbol(mSymbol); - mHostPeriod = NormalizePeriod(mHostPeriod); - - // - result = IsValid(mCycle); - if (!result) - { - return result; - } - - // - this.cycle = mCycle; - - // - // Set Automatically Prefix ... - if (StringLen(mPrefix) == 0) - { - this.prefix = ToString(cycle); - } - - // - result = IsValid( - method, - period // - ); - if (!result) - { - return result; - } - - // - this.symbol = mSymbol; - this.hostPeriod = mHostPeriod; - - // - // Find Cycle Period ... - if (method == X_PERIOD_AUTO) - { - // - // Select Period ... - this.period = GetCyclePeriod( - this.cycle, - this.hostPeriod); - } - - // - // Set Prefix if Provided ... - if (StringLen(mPrefix) > 0) - { - this.prefix = mPrefix; - } - - // - // Calculate Required Info ... - - // - // Length ... - this.length = PeriodSeconds(this.period) / PeriodSeconds(this.hostPeriod); - - // - // Update Additional Data ... - result = this.Update(0); - - // - return result; - } - - // - bool Init( - string mSymbol, // Trading Symbol - ENUM_TIMEFRAMES mHostPeriod, // Host Period - ENUM_X_MARKET_CYCLES mCycle, // Init Cycle - ENUM_X_PERIOD_METHOD mMethod, // Period Selection Method - ENUM_TIMEFRAMES mPeriod, // Provided Period - string mPrefix = "" // Prefix - ) - { - // - this.period = mPeriod; - this.method = mMethod; - - // - return Init( - mSymbol, - mHostPeriod, - mCycle, - mPrefix - // - ); - } - - // - // Tools ... - - // - // Cleanup ... - void Clean() - { - // - length = 0; - lastStart = 0; - - // - cycle = NULL; - prefix = NULL; - symbol = NULL; - period = NULL; - method = NULL; - hostPeriod = NULL; - - // - remains.Clean(); - barTracker.Clean(); - } - - // - // Check Structure Valid ... - bool IsValid() - { - // - bool result = false; - - // - result = IsValid( - method, - period); - if (!result) - { - return result; - } - - // - result = - // - length > 0 && - symbol != NULL && - period != NULL && - method != NULL && - hostPeriod != NULL && - method != X_PERIOD_NOTHING - // - ; - - // - return result; - } - - // - // Update Market Cycle Additional Info ... - bool Update(int hostBarIndex) - { - // - bool result = false; - - // - result = this.IsValid(); - if (!result) - { - return result; - } - - // - // Init Remains ... - result = remains.Init( - this.symbol, - this.period); - if (!result) - { - return result; - } - - // - // Init Bar Tracker ... - result = barTracker.Init( - this.symbol, - this.period); - if (!result) - { - return result; - } - - // - return result; - } - - // - // Count Bars ... - int CountBars() - { - // - int result = 0; - - // - if (!IsValid()) - { - return result; - } - - // - result = barTracker.CountBars(); - - // - return result; - } - - // - // Check New Bar ... - bool IsNewBar() - { - // - bool result = false; - - // - if (!IsValid()) - { - return result; - } - - // - result = barTracker.IsNewBar(); - - // - return result; - } - - // - // Retrieve Current Bar Index based on Host Period bar Index ... - int GetBarIndex(int barIndex) - { - // - int result = 0; - - // - if (!IsValid()) - { - return result; - } - - // - if (barIndex < 0) - { - return result; - } - - // - int totalBars = CountBars(); - if (barIndex >= totalBars) - { - // - result = totalBars - 1; - return result; - } - - // - datetime hostBarTime = iTime( - this.symbol, - this.hostPeriod, - barIndex - // - ); - - // - result = iBarShift( - this.symbol, - this.period, - hostBarTime - // - ); - - // - return result; - } - - // - // Retrieve Current Cycles Specific Bar ... - XOHCL GetBar(int barIndex) - { - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - int totalBars = CountBars(); - if (barIndex >= totalBars) - { - barIndex = totalBars - 1; - } - - // - XOHCL result; - result.Init( - this.symbol, - this.period, - barIndex - // - ); - - // - return result; - } - - // - // Extract Specific Range of Bars ... - // using Start Bar Index ... - int GetBars( - XOHCL &result[], // Hold Result - int from = 0, // Start Bar Index - int count = 1, // Number of Bars - bool forceClean = true // Clean Result Array - ) - { - // - int mResult = 0; - - // - if (from < 0) - { - from = 0; - } - - // - int total = Bars( - symbol, - period); - if (from > total - 2) - { - from = total - 2; - } - - // - if (count < 0) - { - count = 1; - } - - // - int start = from; - int end = start + count; - if (end > total - 1) - { - end = total - 1; - } - - // - if (forceClean) - { - Clean(result); - } - - // - int beforeSize = ArraySize(result); - - // - for (int i = start; i < end; i++) - { - // - XOHCL iBar; - bool isValid = iBar.Init( - symbol, - period, - i - // - ); - - // - if (isValid) - { - // - AddRef( - iBar, - result - // - ); - } - } - - // - int afterSize = ArraySize(result); - - // - mResult = afterSize - beforeSize; - - // - return mResult; - } - - // - // Extract Specific Range of Bars ... - // using Start Bar Time ... - int GetBars( - XOHCL &result[], // Hold Result - datetime from = NULL, // Start Bar Time - int count = 1, // Number of Bars - bool forceClean = true // Clean Result Array - ) - { - // - from = NormalizeTime(from); - - // - int barIndex = iBarShift( - symbol, - period, - from, - false - // - ); - - // - return GetBars( - result, - symbol, - period, - barIndex, - count, - forceClean - // - ); - } - - // - // Retrieve Bar Time ... - datetime GetBarTime(int barIndex) - { - // - datetime result = NULL; - - // - if (!IsValid()) - { - return result; - } - - // - if (barIndex < 0) - { - barIndex = 0; - } - - // - int totalBars = CountBars(); - if (barIndex >= totalBars) - { - barIndex = totalBars - 1; - } - - // - result = iTime( - this.symbol, - this.period, - barIndex - // - ); - - // - return result; - } - - // - // Find Chart ID ... - ulong GetChartID() - { - // - ulong result = 0; - - // - long firstChart = ChartFirst(); - result = firstChart; - - // - while (result >= 0) - { - // - string chSymbol = ChartSymbol(result); - ENUM_TIMEFRAMES chPeriod = ChartPeriod(result); - - // - bool isOwnChart = - // - symbol == chSymbol && - period == chPeriod - // - ; - if (isOwnChart) - { - break; - } - - // - result = ChartNext(result); - if (result < 0) - { - break; - } - } - - // - return result; - } - - // - // Create and String Representation for Unique Taging ... - string ToString() - { - // - string result = ""; - - // - if (!IsValid()) - { - return result; - } - - // - result = - GetTypeName(this) + "(" + - "PRFX(" + this.prefix + ")" + - "SMBL(" + this.symbol + ")" + - "CYC(" + ToString(this.cycle) + ")" + - "PRD(" + ToString(this.period) + ")" + - "PRDHST(" + ToString(this.hostPeriod) + ")" + - "MTH(" + EnumToString(this.method) + ")" + - ")"; - - // - return result; - } - - // - // Here we Produce a Summary brief of - // state of Cycle ... - string GenerateSummary() - { - // - string result = ""; - - // - bool hasPrefix = - StringLen(this.prefix) > 0 && - this.prefix != ToString(this.cycle); - result += (hasPrefix ? this.prefix + "[" : "") + - ToString(this.cycle) + - (hasPrefix ? "]" : "") + "\n"; - - // - result += " - PR: " + ToString(this.period) + "\n"; - - // - XOHCL cBar = GetBar(0); - - // - result += " - State: " + (cBar.IsBullish() ? "Bullish" : cBar.IsBearish() ? "Bearish" - : "Neutural"); - - // - return result; - } -}; - -// -// Linear Regression ... - -// -struct XLinearRegressionWorkStruct -{ - // - struct sDataStruct - { - // - double value; - double sumY; - double sumXY; - }; - - // - sDataStruct data[]; - - // - int dataSize; - int period; - double sumX; - double sumXX; - double divisor; - - // - // Constructor ... - XLinearRegressionWorkStruct() : dataSize(-1), period(-1) {} -}; - -// -struct XLinearRegression -{ - // - XLinearRegressionWorkStruct m_work; - - // - // Calculate Linear Regression ... - double Calculate( - double value, - int period, - double &_slope, - double &_intercept, - int r, - int bars // - ) - { - // - if (m_work.dataSize <= bars) - { - m_work.dataSize = ArrayResize(m_work.data, bars + 500, 2000); - } - - // - if (period < 1) - { - period = 1; - } - - // - if (m_work.period != (int)period) - { - // - m_work.period = (int)period; - m_work.sumX = m_work.period * (m_work.period - 1.0) / 2.0; - m_work.sumXX = m_work.period * (m_work.period - 1.0) * (2.0 * m_work.period - 1.0) / 6.0; - m_work.divisor = m_work.sumX * m_work.sumX - m_work.period * m_work.sumXX; - - // - if (m_work.divisor) - { - m_work.divisor = 1.0 / m_work.divisor; - } - } - - // - m_work.data[r].value = value; - - // - if (r >= m_work.period) - { - // - m_work.data[r].sumY = m_work.data[r - 1].sumY + value - m_work.data[r - m_work.period].value; - m_work.data[r].sumXY = m_work.data[r - 1].sumXY + m_work.data[r].sumY - m_work.data[r - m_work.period].value * (m_work.period - 1.0) - value; - } - else - { - // - m_work.data[r].sumY = value; - m_work.data[r].sumXY = 0; - - // - for (int k = 1; k < m_work.period && r >= k; k++) - { - // - m_work.data[r].sumY += m_work.data[r - k].value; - m_work.data[r].sumXY += k * m_work.data[r - k].value; - } - } - - // - _slope = (m_work.period * m_work.data[r].sumXY - m_work.sumX * m_work.data[r].sumY) * m_work.divisor; - _intercept = (m_work.data[r].sumY - _slope * m_work.sumX) / (double)m_work.period; - - // - double result = (_intercept + _slope * (m_work.period - 1.0)); - - // - return result; - } - - // -}; - -// -// Styling Buffers ... - -// -struct XBufferPlotStyle -{ - // - int width; // Width - color clr; // Color - uchar arrow; // Arrow Code - ENUM_DRAW_TYPE type; // Type - ENUM_LINE_STYLE style; // Style - - // - // Constructor ... - XBufferPlotStyle() - { - Default(); - } - - // - // Tools ... - - // - // Default ... - void Default() - { - // - width = 1; - arrow = 0; - clr = CLR_NONE; - type = DRAW_NONE; - style = STYLE_SOLID; - } -}; - -// -// Register a Buffer as Indexed Buffer ... -void SetIndexBuffer( - int &index, // the Index refrence for Buffer - double &buffer[], // Buffer to Set - XBufferPlotStyle &style, // Style to Apply to Buffer - double &colorBuffer[], // Color Buffer - string label = NULL, // Buffer Label - bool showData = true, // Show Data on Data Window - double empty = -1, // Set 0 or EMPTY_VALUE used for setting Empty Value - int drawBegin = -1 // if Set More Than -1 applied -) -{ - // - // Set Buffer Index ... - SetIndexBuffer(index, buffer, INDICATOR_DATA); - - // - // Show Date ... - PlotIndexSetInteger(index, PLOT_SHOW_DATA, showData); - - // - // Set Buffer Label ... - if (IsValid(label)) - { - PlotIndexSetString(index, PLOT_LABEL, label); - } - - // - if (empty == 0 || empty == EMPTY_VALUE) - { - PlotIndexSetDouble(index, PLOT_EMPTY_VALUE, empty); - } - - // - if (drawBegin > -1) - { - PlotIndexSetInteger(index, PLOT_DRAW_BEGIN, drawBegin); - } - - // - if (style.type == DRAW_ARROW) - { - PlotIndexSetInteger(index, PLOT_ARROW, style.arrow); - } - - // - PlotIndexSetInteger(index, PLOT_LINE_STYLE, style.style); - PlotIndexSetInteger(index, PLOT_LINE_WIDTH, style.width); - - // - string drawTypeStr = EnumToString(style.type); - bool hasColorBuffer = Contains("COLOR", drawTypeStr); - - // - if (!hasColorBuffer) - { - PlotIndexSetInteger(index, PLOT_LINE_COLOR, style.clr); - } - else - { - // - // Since Color Buffers must add as next Index of it's own Buffer - // here before applied Color Buffer increase index ... - index++; - - // - SetIndexBuffer(index, colorBuffer, INDICATOR_COLOR_INDEX); - } - - // - // Increase Index for Next Buffer ... - index++; -} - -// -void SetIndexCandleBuffers( - int &index, // the Index refrence for Buffer - string openLabel, // Open Label - double &open[], // Open Buffer - string highLabel, // High Label - double &high[], // High Buffer - string lowLabel, // Low Label - double &low[], // Low Buffer - string closeLabel, // Close Label - double &close[], // Close Buffer - bool showData = true, // Show Data on Data Window - double empty = -1, // Set 0 or EMPTY_VALUE used for setting Empty Value - int drawBegin = -1 // if Set More Than -1 applied -) -{ - // - bool hasLabel = - // - IsValid(openLabel) && - IsValid(highLabel) && - IsValid(lowLabel) && - IsValid(closeLabel) - // - ; - - // - string label = - !hasLabel - ? NULL - : openLabel + ";" + highLabel + ";" + lowLabel + ";" + closeLabel; - - // - // Set Buffer Index ... - SetIndexBuffer(index, open, INDICATOR_DATA); - - // - // Set Draw Candles Type ... - PlotIndexSetInteger(index, PLOT_LINE_STYLE, DRAW_CANDLES); - - // - // Show Date ... - PlotIndexSetInteger(index, PLOT_SHOW_DATA, showData); - - // - // Set Buffer Label ... - if (IsValid(label)) - { - PlotIndexSetString(index, PLOT_LABEL, label); - } - - // - if (empty == 0 || empty == EMPTY_VALUE) - { - PlotIndexSetDouble(index, PLOT_EMPTY_VALUE, empty); - } - - // - if (drawBegin > -1) - { - PlotIndexSetInteger(index, PLOT_DRAW_BEGIN, drawBegin); - } - - // - index++; - - // - // Set Buffer Index ... - SetIndexBuffer(index, high, INDICATOR_DATA); - index++; - - // - // Set Buffer Index ... - SetIndexBuffer(index, low, INDICATOR_DATA); - index++; - - // - // Set Buffer Index ... - SetIndexBuffer(index, close, INDICATOR_DATA); - index++; -} - -// -void SetIndexCandleBuffers( - int &index, // the Index refrence for Buffer - string openLabel, // Open Label - double &open[], // Open Buffer - string highLabel, // High Label - double &high[], // High Buffer - string lowLabel, // Low Label - double &low[], // Low Buffer - string closeLabel, // Close Label - double &close[], // Close Buffer - double &colorBuffer[], // Candle Color Buffer - bool showData = true, // Show Data on Data Window - double empty = -1, // Set 0 or EMPTY_VALUE used for setting Empty Value - int drawBegin = -1 // if Set More Than -1 applied -) -{ - // - SetIndexCandleBuffers( - index, - openLabel, - open, - highLabel, - high, - lowLabel, - low, - closeLabel, - close, - showData, - empty, - drawBegin // - ); - - // - int mFirstIndex = index - 4; - - // - // Set Draw Candles Type ... - PlotIndexSetInteger(mFirstIndex, PLOT_LINE_STYLE, DRAW_COLOR_CANDLES); - - // - // Set Color Buffer ... - SetIndexBuffer(index, colorBuffer, INDICATOR_COLOR_INDEX); - - // - index++; -} - -// -// Functions ... - -// -// Validators ... - -// -// Validate an String has length and not NULL ... -bool IsValid(string value) -{ - // - bool result = false; - - // - result = - // - value != NULL && - StringLen(value) > 0 - // - ; - - // - return result; -} -bool IsSpecifiedValid(string value) -{ - return IsValid(value); -} - -// -// Validate a Date ... -bool IsValid(datetime value) -{ - // - bool result = false; - - // - result = NotEmpty(value) && value != NULL; - - // - return result; -} -bool IsSpecifiedValid(datetime value) -{ - return IsValid(value); -} - -// -// Validate a Period Param ... -bool IsValid(ENUM_TIMEFRAMES value) -{ - // - bool result = false; - - // - result = - // - value != NULL - // - ; - - // - return result; -} -bool IsSpecifiedValid(ENUM_TIMEFRAMES value) -{ - // - return IsValid(value); -} - -// -// Validate Specified Cycle ... -bool IsValid(ENUM_X_MARKET_CYCLES value) -{ - // - bool result = false; - - // - result = - // - value != NULL && - value != X_MARKET_CYCLE_UNKNOWN - // - ; - - // - return result; -} - -// -// Validate Specific Period Mode ... -bool IsValid( - ENUM_X_PERIOD_METHOD mMethod, // Period Select Method - ENUM_TIMEFRAMES mPeriod // Selected Period -) -{ - // - bool result = false; - - // - result = - // - mMethod == X_PERIOD_NOTHING - ? false - : mMethod == X_PERIOD_MANUALLY - ? mPeriod != NULL - : mMethod == X_PERIOD_AUTO - ? true - : false - // - ; - - // - return result; -} - -// -bool IsSpecifiedValid( - ENUM_X_PERIOD_METHOD mMethod, // Period Select Method - ENUM_TIMEFRAMES mPeriod // Selected Period -) -{ - return IsValid(mMethod, - mPeriod // - ); -} - -// -// Validate Swing Mode ... -bool IsValid(ENUM_X_SWING_TYPE value) -{ - // - bool result = false; - - // - result = - // - value == X_SWING_HIGH || - value == X_SWING_LOW - // - ; - - // - return result; -} - -// -// As IS ... - -// -// Determine a Position type is Long or not ... -bool IsLong(ENUM_POSITION_TYPE type) -{ - // - bool result = type == POSITION_TYPE_BUY; - - // - return result; -} -bool IsLong(ENUM_ORDER_TYPE type) -{ - // - bool result = type == ORDER_TYPE_BUY; - - // - return result; -} - -// -// Determine a Position type is Short or not ... -bool IsShort(ENUM_POSITION_TYPE type) -{ - // - bool result = type == POSITION_TYPE_SELL; - - // - return result; -} -bool IsShort(ENUM_ORDER_TYPE type) -{ - // - bool result = type == ORDER_TYPE_SELL; - - // - return result; -} - -// -// Retrieve Opposit Direction Type ... -ENUM_POSITION_TYPE GetOpposit(ENUM_POSITION_TYPE type) -{ - // - ENUM_POSITION_TYPE result = NULL; - - // - bool isLong = IsLong(type); - result = isLong - ? POSITION_TYPE_SELL - : POSITION_TYPE_BUY; - - // - return result; -} -ENUM_ORDER_TYPE GetOpposit(ENUM_ORDER_TYPE type) -{ - // - ENUM_ORDER_TYPE result = NULL; - - // - bool isLong = IsLong(type); - result = isLong - ? ORDER_TYPE_SELL - : ORDER_TYPE_BUY; - - // - return result; -} - -// -string ToString(ENUM_POSITION_TYPE value) -{ - // - string result = NULL; - - // - result = - // - IsLong(value) - ? "Long" - : "Short" - // - ; - - // - return result; -} -string ToString(ENUM_ORDER_TYPE value) -{ - // - string result = NULL; - - // - result = - // - IsLong(value) - ? "Long" - : "Short" - // - ; - - // - return result; -} - -// -// Check Expert Running in Testing Mode or not ... -bool IsRunningOnTestMode() -{ - // - bool result = false; - - // - // check programm mode ... - result = MQL5InfoInteger(MQL5_TESTING); - - // - return result; -} - -// -// Find Chart ID ... -long FindChartID( - string mSymbol = NULL, // Trading Symbol - ENUM_TIMEFRAMES mPeriod = NULL // Trading Period -) -{ - // - long result = ChartFirst(); - long first = result; - - // - while (result > 0) - { - // - string chSymbol = ChartSymbol(result); - ENUM_TIMEFRAMES chPeriod = ChartPeriod(result); - - // - bool isOwn = - // - chSymbol == mSymbol && - chPeriod == mPeriod - // - ; - if (isOwn) - { - break; - } - - // - result = ChartNext(result); - } - - // - return result; -} - -// -// Normalizers ... - -// -// Check a Symbol provided or not ... -// if not use Default ... -string NormalizeSymbol(string value) -{ - // - string result = value; - - // - if (!IsValid(result)) - { - result = _Symbol; - } - - // - return result; -} - -// -// Check a Datetime provided or not ... -// if not use Current ... -datetime NormalizeTime(datetime value) -{ - // - datetime result = value; - - // - if (!IsValid(result)) - { - result = TimeCurrent(); - } - - // - return result; -} - -// -// Check a Period provided or not ... -// if not use Default ... -ENUM_TIMEFRAMES NormalizePeriod(ENUM_TIMEFRAMES value) -{ - // - ENUM_TIMEFRAMES result = value; - - // - if (!IsValid(value)) - { - result = _Period; - } - - // - return result; -} - -// -// Normalize Cycle ... -ENUM_X_MARKET_CYCLES NormalizeCycle(ENUM_X_MARKET_CYCLES value) -{ - // - ENUM_X_MARKET_CYCLES result = value; - - // - if (!IsValid(result)) - { - result = X_MARKET_CYCLE_SHORT; - } - - // - return value; -} - -// -// Validate a Buffer Size for Looping or etc ... -bool IsValidSize(int size) -{ - // - bool result = size > 0; - - // - return result; -} - -template -bool IsValidSize(T &buffer[]) -{ - // - bool result = false; - - // - result = - // - IsValidSize(ArraySize(buffer)) - // - ; - - // - return result; -} - -// -// Check a Given Index is Valid or not ... -bool IsValidIndex(int index) -{ - return index >= 0; -} - -// -// Normalize Index Based On Specified Buffer ... -template -void NormalizeIndex( - int &index, - T &buffer[] // -) -{ - // - int bufferSize = ArraySize(buffer); - - // - if (bufferSize <= 0) - { - index = 0; - } - - // - if (index <= 0) - { - index = 0; - } - - // - if (index > bufferSize - 1) - { - index = bufferSize - 1; - } -} - -// -// Normalize Start and Count based on Specified Buffer ... -template -void NormalizeCount( - int &start, - int &count, - T &buffer[] // -) -{ - // - // Validate Buffer Size ... - int bufferSize = ArraySize(buffer); - if (!IsValidSize(bufferSize)) - { - return; - } - - // - // Normalization Start ... - NormalizeIndex( - start, - buffer // - ); - - // - if (count < start) - { - count = (start - count); - } - - // - // Normalization Count ... - - // - if (count < 0) - { - count = start; - } - - // - if (count > bufferSize) - { - count = bufferSize; - } -} - -// -// Normalize a give Volume ... -double NormalizeVolume( - double mVolume, // desired volume to normalize - string mSymbol = NULL, // Trading Symbol - int mLength = 2 // Length of Digits -) -{ - // - double result = mVolume; - - // - mSymbol = NormalizeSymbol(mSymbol); - - // - // Normalize Digits ... - int digits = GetDigits(mSymbol); - - // - mLength = - mLength == 0 || mLength > digits - ? digits - : MathMin(mLength, digits); - - // - // Normalize Volume ... - result = NormalizeDouble(result, mLength); - - // - double maxAvailableVolume = SymbolInfoDouble(mSymbol, SYMBOL_VOLUME_MAX); - double minAvailableVolume = SymbolInfoDouble(mSymbol, SYMBOL_VOLUME_MIN); - - // - // Validate Result ... - if (result > maxAvailableVolume) - { - result = maxAvailableVolume; - } - else if (result < minAvailableVolume) - { - result = minAvailableVolume; - } - - // - return result; -} - -// -// Normallize Price ... -double NormalizePrice( - double mPrice, // desired Price for normalization - string mSymbol = NULL // Trading Symbol -) -{ - // - double result = 0; - - // - mSymbol = NormalizeSymbol(mSymbol); - - // - double tickSize = 0; - result = SymbolInfoDouble(mSymbol, SYMBOL_TRADE_TICK_SIZE, tickSize); - - // - int digits = GetDigits(mSymbol); - result = NormalizeDouble(MathRound(mPrice / tickSize) * tickSize, digits); - - // - return result; -} - -// -// Prices ... - -// -// Retrieve Ask Price ... -double GetAsk( - string mSymbol = NULL // Trading Symbol -) -{ - // - mSymbol = NormalizeSymbol(mSymbol); - - // - double result = SymbolInfoDouble(mSymbol, SYMBOL_ASK); - - // - return result; -} - -// -// Retrieve Bid Price ... -double GetBid( - string mSymbol = NULL // Trading Symbol -) -{ - // - mSymbol = NormalizeSymbol(mSymbol); - - // - double result = SymbolInfoDouble(mSymbol, SYMBOL_BID); - - // - return result; -} - -// -// Retrieve Spread Price ... -double GetSpread( - string mSymbol = NULL // Trading Symbol -) -{ - // - mSymbol = NormalizeSymbol(mSymbol); - - // - double ask = GetAsk(mSymbol); - double bid = GetBid(mSymbol); - - // - double result = MathAbs(ask - bid); - - // - return result; -} - -// -// Retrieve Point Value ... -double GetPoints( - string mSymbol = NULL // Trading Symbol -) -{ - // - mSymbol = NormalizeSymbol(mSymbol); - - // - double result = SymbolInfoDouble(mSymbol, SYMBOL_POINT); - - // - return result; -} - -// -// Retrieve Point Digits ... -int GetDigits( - string mSymbol = NULL // Trading Symbol -) -{ - // - mSymbol = NormalizeSymbol(mSymbol); - - // - int result = (int)SymbolInfoInteger(mSymbol, SYMBOL_DIGITS); - - // - return result; -} - -// -// Retrieve Entry Price ... -double GetEntry( - string mSymbol = NULL, // Trading Symbol - ENUM_POSITION_TYPE type = POSITION_TYPE_BUY // Get entry price for Which direction trade ... -) -{ - // - double result = 0; - - // - mSymbol = NormalizeSymbol(mSymbol); - - // - result = - IsLong(type) - ? GetAsk(mSymbol) - : GetBid(mSymbol); - result = NormalizePrice(result, mSymbol); - - // - return result; -} - -// -// Retrieve Exit Price ... -double GetExit( - string mSymbol = NULL, // Trading Symbol - ENUM_POSITION_TYPE type = POSITION_TYPE_BUY // Get entry price for Which direction trade ... -) -{ - // - double result = 0; - - // - mSymbol = NormalizeSymbol(mSymbol); - - // - result = - IsLong(type) - ? GetBid(mSymbol) - : GetAsk(mSymbol); - result = NormalizePrice(result, mSymbol); - - // - return result; -} - -// -// Get 1 Pip in Price Value ... -double GetPipPrice( - string mSymbol = NULL // Trading Symbol -) -{ - // - mSymbol = NormalizeSymbol(mSymbol); - - // - double symbolPoint = GetPoints(mSymbol); - int symbolDigits = GetDigits(mSymbol); - - // - double result = symbolPoint; - if (symbolDigits == 3 || symbolDigits == 5) - { - result *= 10; - } - - // - return result; -} - -// -// Converts Pips To Price ... -double PipsToPrice( - double mPips, // pips amount - string mSymbol = NULL // Trading Symbol -) -{ - // - mSymbol = NormalizeSymbol(mSymbol); - - // - int digits = GetDigits(mSymbol); - double pipValue = GetPipPrice(mSymbol); - double result = mPips * pipValue; - - // - result = NormalizePrice(result, mSymbol); - - // - return result; -} - -// -// Converts Price to Pips ... -double PriceToPips( - double mPrice, // the price amount which required to calculate - string mSymbol = NULL // Trading Symbol -) -{ - // - mSymbol = NormalizeSymbol(mSymbol); - mPrice = NormalizePrice(mPrice, mSymbol); - - // - int digits = GetDigits(mSymbol); - double pipPrice = GetPipPrice(mSymbol); - - // - double result = mPrice / pipPrice; - - // - result = NormalizeDouble(result, digits); - - // - return result; -} - -// -// Convert Price to Point ... -double PriceToPoint( - double price, // the price amount which required to calculate - string mSymbol = NULL // Trading Symbol -) -{ - // - double result = 0; - - // - mSymbol = NormalizeSymbol(mSymbol); - price = NormalizePrice(price, mSymbol); - - // - double point = GetPoints(mSymbol); - result = price / point; - - // - return result; -} - -// -// Converts Point to Price ... -double PointToPrice( - double points, // Points Amount - string mSymbol = NULL // Trading Symbol -) -{ - // - double result = 0; - - // - mSymbol = NormalizeSymbol(mSymbol); - - // - double point = GetPoints(mSymbol); - result = points * point; - - // - result = NormalizePrice(result, mSymbol); - - // - return result; -} - -// -// Converts Series Mode to XPRICE ... -ENUM_X_PRICE ToPrice( - ENUM_SERIESMODE mMode // Specified Series Mode ... -) -{ - // - ENUM_X_PRICE result = X_PRICE_CLOSE; - - // - switch (mMode) - { - // - // High ... - case MODE_HIGH: - result = X_PRICE_HIGH; - break; - - // - // Open ... - case MODE_OPEN: - result = X_PRICE_OPEN; - break; - - // - // Low ... - case MODE_LOW: - result = X_PRICE_LOW; - break; - - // - // Close ... - // Default ... - case MODE_CLOSE: - default: - result = X_PRICE_CLOSE; - break; - } - - // - return result; -} - -// -// Retrieve Applied Price ... -template -double GetAppliedPrice( - ENUM_APPLIED_PRICE tprice, // Type of Price Selection - T &open[], // Open Prices - T &high[], // High Preices - T &low[], // Low Prices - T &close[], // Close Prices - int i // Bar Index -) -{ - switch (tprice) - { - case PRICE_CLOSE: - return (close[i]); - case PRICE_OPEN: - return (open[i]); - case PRICE_HIGH: - return (high[i]); - case PRICE_LOW: - return (low[i]); - case PRICE_MEDIAN: - return ((high[i] + low[i]) / 2.0); - case PRICE_TYPICAL: - return ((high[i] + low[i] + close[i]) / 3.0); - case PRICE_WEIGHTED: - return ((high[i] + low[i] + close[i] + close[i]) / 4.0); - } - return (0); -} - -// -double iGetPrice( - int tprice, - double open, - double high, - const double low, - const double close // -) -{ - // - switch (tprice) - { - case PRICE_CLOSE: - return (close); - case PRICE_OPEN: - return (open); - case PRICE_HIGH: - return (high); - case PRICE_LOW: - return (low); - case PRICE_MEDIAN: - return ((high + low) / 2.0); - case PRICE_TYPICAL: - return ((high + low + close) / 3.0); - case PRICE_WEIGHTED: - return ((high + low + close + close) / 4.0); - } - - // - return (0); -} - -// -// Calculate TP/SL for Specified Type of Positions ... -void CalculateTPSL( - double &mSL, // Hold SL - double &mTP, // Hold TP - ENUM_POSITION_TYPE mType, // Position Type Long (Buy) / Short (Sell) - double mEntry, // Entry Price - double mR2R = 1, // Provided Risk To Reward Ratio - double slPrice = 0, // Provided SL Price - double tpPrice = 0, // Provided TP Price - double priceToRisk = 0, // If Entry equal to Provided SL Price Risk Point - double priceToReward = 0 // If Entry equal to Provided TP Price Reward Point -) -{ - // - // if Both TP and SL Provided, ignore R2R and Calculate direct ... - // if SL provided, Calculate TP based on Provided R2R ... - // if TP provided, Calculate SL based on Provided R2R ... - // default R2R is set to 1 ... - - // - mSL = 0; - mTP = 0; - - // - bool isLong = IsLong(mType); - - // - // Set Default R2R ... - if (mR2R < 1) - { - mR2R = 1; - } - - // - if (mEntry <= 0 || - (tpPrice <= 0 && slPrice <= 0)) - { - return; - } - - // - double risk = 0; - double reward = 0; - - // - bool canCalculateBasedOnSL = slPrice > 0 && - (isLong - ? slPrice <= mEntry - : slPrice >= mEntry); - - // - bool canCalculateBasedOnTP = tpPrice > 0 && - (isLong - ? tpPrice >= mEntry - : tpPrice <= mEntry); - - // - if (canCalculateBasedOnSL && !canCalculateBasedOnTP) - { - // - risk = MathAbs(mEntry - slPrice); - if (risk == 0) - { - risk = priceToRisk; - } - reward = risk * mR2R; - } - else if (!canCalculateBasedOnSL && canCalculateBasedOnTP) - { - // - reward = MathAbs(mEntry - tpPrice); - if (reward == 0) - { - reward = priceToReward; - } - risk = reward / mR2R; - } - else if (!canCalculateBasedOnSL && !canCalculateBasedOnTP) - { - // - bool canSetTPPrice = isLong - ? tpPrice > mEntry - : tpPrice < mEntry; - if (canSetTPPrice) - { - mTP = tpPrice; - } - - // - bool canSetSLPrice = isLong - ? slPrice < mEntry - : slPrice > mEntry; - if (canSetSLPrice) - { - mSL = slPrice; - } - - // - return; - } - else if (canCalculateBasedOnSL && canCalculateBasedOnTP) - { - // - bool canSetTPPrice = isLong - ? tpPrice > mEntry - : tpPrice < mEntry; - if (canSetTPPrice) - { - mTP = tpPrice; - } - - // - bool canSetSLPrice = isLong - ? slPrice < mEntry - : slPrice > mEntry; - if (canSetSLPrice) - { - mSL = slPrice; - } - - // - return; - } - - // - mTP = isLong - ? mEntry + reward - : mEntry - reward; - - // - mSL = isLong - ? mEntry - risk - : mEntry + risk; -} - -// -bool CalculateTPSLByPoint( - double &mSL, // Hold SL - double &mTP, // Hold TP - ENUM_POSITION_TYPE mType, // Position Type Long (Buy) / Short (Sell) - double mEntry, // Entry Price - double mPointValue, // Point Value - double mR2R = 1, // Provided Risk To Reward Ratio - double slPoint = 0, // Provided SL Point - double tpPoint = 0 // Provided TP Point -) -{ - // - bool result = false; - - // - mSL = 0; - mTP = 0; - - // - bool isLong = IsLong(mType); - - // - // Set Default R2R ... - if (mR2R < 1) - { - mR2R = 1; - } - - // - if (mEntry <= 0 || - mPointValue <= 0 || - (slPoint <= 0 && tpPoint <= 0)) - { - return result; - } - - // - double risk = 0; - double reward = 0; - - // - bool canCalculateBasedOnSL = slPoint > 0; - - // - bool canCalculateBasedOnTP = tpPoint > 0; - - // - if (!canCalculateBasedOnSL && !canCalculateBasedOnTP) - { - return result; - } - - // - if (canCalculateBasedOnSL && canCalculateBasedOnTP) - { - // - reward = tpPoint * mPointValue; - risk = slPoint * mPointValue; - } - else if (!canCalculateBasedOnSL && canCalculateBasedOnTP) - { - // - reward = tpPoint * mPointValue; - risk = reward / mR2R; - } - else if (canCalculateBasedOnSL && !canCalculateBasedOnTP) - { - // - risk = slPoint * mPointValue; - reward = risk * mR2R; - } - - // - result = risk > 0 && reward > 0; - if (!result) - { - return result; - } - - // - mTP = isLong - ? mEntry + reward - : mEntry - reward; - - // - mSL = isLong - ? mEntry - risk - : mEntry + risk; - - // - return result; -} - -// -bool GetTick( - string mSymbol, - MqlTick &tick // -) -{ - return SymbolInfoTick(mSymbol, tick); -} - -// -// Symbols ... - -// -// Retrieve Available Symbols ... -int GetAllSymbols( - string &symbols[], // Hold Result - bool onlyInWatchList = false, // Specified Retrieve only Symbols which in Watch List - bool forceClean = true // Force To Clean Result Array -) -{ - // - int result = 0; - - // - if (forceClean) - { - Clean(symbols); - } - - // - int beforeSize = ArraySize(symbols); - - // - int symbolsCount = SymbolsTotal(onlyInWatchList); - if (symbolsCount <= 0) - { - return result; - } - - // - for (int i = 0; i < symbolsCount; i++) - { - // - string iSymbol = SymbolName( - i, - onlyInWatchList - // - ); - if (!IsValid(iSymbol)) - { - continue; - } - - // - Add( - iSymbol, - symbols - // - ); - } - - // - int afterSize = ArraySize(symbols); - - // - result = afterSize - beforeSize; - - // - return result; -} - -// -// This is a Global Way to Filter Symbols -// you can pass Specific string as Query or a List String for Filtering ... -int FilterSymbols( - string query, // Which Query to Search Symbol - string &symbols[], // Hold Result - bool onlyInWatchList = false, // Specified Retrieve only Symbols which in Watch List - bool forceClean = true, // Force To Clean Result Array - bool ignoreCase = true, // Ignore Case - string querySeparator = "," // If Provided means query is a COllection of Queries and need to be Splitted -) -{ - // - int result = 0; - - // - if (forceClean) - { - Clean(symbols); - } - - // - if (!IsValid(query)) - { - return result; - } - - // - // Check Query is an String array or not ... - string mQueries[]; - int queriesCount = 0; - if (IsValid(querySeparator) && Contains(querySeparator, query, true)) - { - // - queriesCount = SplitContent( - mQueries, - query, - querySeparator - // - ); - } - - // - int beforeSize = ArraySize(symbols); - - // - string allSymbols[]; - int allSymbolsCount = GetAllSymbols( - allSymbols, - onlyInWatchList, - forceClean); - if (allSymbolsCount <= 0) - { - return result; - } - - // - // Loop Through all Symbols ... - for (int i = 0; i < allSymbolsCount; i++) - { - // - string iSymbol = allSymbols[i]; - - // - bool isFilterPassed = false; - if (queriesCount == 0) - { - // - isFilterPassed = Contains( - query, - iSymbol, - ignoreCase - // - ); - } - else if (queriesCount > 0) - { - // - isFilterPassed = Contains( - mQueries, - iSymbol, - ignoreCase - // - ); - } - - // - if (isFilterPassed) - { - // - Add( - iSymbol, - symbols - // - ); - } - } - - // - int afterSize = ArraySize(symbols); - - // - result = afterSize - beforeSize; - - // - return result; -} - -// -int FilterUSDSymbols( - string &symbols[], // Hold Result - bool onlyInWatchList = false, // Specified Retrieve only Symbols which in Watch List - bool forceClean = true, // Force To Clean Result Array - bool ignoreCase = true, // Ignore Case - string querySeparator = "," // If Provided means query is a COllection of Queries and need to be Splitted -) -{ - // - return FilterSymbols( - "USD", - symbols, - onlyInWatchList, - forceClean, - ignoreCase, - querySeparator - // - ); -} - -// -// Time / Date ... - -// -// Representation of Time Struct ... -// struct MqlDateTime -// { -// int year; // Year -// int mon; // Month -// int day; // Day -// int hour; // Hour -// int min; // Minutes -// int sec; // Seconds -// int day_of_week; // Day of week (0-Sunday, 1-Monday, ... ,6-Saturday) -// int day_of_year; // Day number of the year (January 1st is assigned the number value of zero) -// }; - -// -// Converts Time to Seconds ... -ulong TimeToSeconds( - datetime time // Specify time to Convert ... -) -{ - // - ulong result = (ulong)time; - - // - return result; -} -ulong TimeToSeconds( - MqlDateTime &time // Specify time to Convert ... -) -{ - // - datetime dTime = StructToTime(time); - - // - ulong result = TimeToSeconds(dTime); - - // - return result; -} - -// -// Converts Seconds To Time ... -datetime SecondsToTime( - ulong seconds // Specify Seconds to Convert ... -) -{ - // - datetime result = (datetime)seconds; - - // - return result; -} -MqlDateTime SecondsToStruct( - ulong seconds // Specify Seconds to Convert ... -) -{ - // - datetime dTime = SecondsToTime(seconds); - - // - MqlDateTime result = {}; - TimeToStruct( - dTime, - result); - - // - return result; -} - -// -// Converts Time to MilliSeconds ... -ulong TimeToMilliSeconds( - datetime time // Specify time to Convert ... -) -{ - // - ulong result = TimeToSeconds(time) * 1000; - - // - return result; -} -ulong TimeToMilliSeconds( - MqlDateTime &time // Specify time to Convert ... -) -{ - // - datetime dTime = StructToTime(time); - - // - ulong result = TimeToMilliSeconds(dTime); - - // - return result; -} - -// -// Converts MillisSeconds to Time ... -datetime MilliSecondsToTiem( - ulong milliSeconds // Specify MilliSeconds to Convert ... -) -{ - // - ulong seconds = milliSeconds / 1000; - - // - datetime result = SecondsToTime(seconds); - - // - return result; -} -MqlDateTime MilliSecondsToStruct( - ulong milliSeconds // Specify MilliSeconds to Convert ... -) -{ - // - datetime dTime = MilliSecondsToTiem(milliSeconds); - - // - MqlDateTime result = {}; - TimeToStruct( - dTime, - result); - - // - return result; -} - -// -// Retrieve DateTime Structure ... -MqlDateTime GetCurrentTime() -{ - // - MqlDateTime result = {}; - - // - TimeCurrent(result); - - // - return result; -} - -// -// Retrieve Current Time as Seconds ... -ulong GetCurrentTimeAsSeconds() -{ - // - datetime time = TimeCurrent(); - - // - ulong result = TimeToSeconds(time); - - // - return result; -} - -// -// Retrieve Current Time as MilliSeconds ... -ulong GetCurrentTimeAsMilliSeconds() -{ - // - datetime time = TimeCurrent(); - - // - ulong result = TimeToMilliSeconds(time); - - // - return result; -} - -// -// Converts a Date time to File Format ... -string ToFormatString( - datetime mTime, - string separator = "_" // -) -{ - // - string result = NULL; - - // - if (!IsValid(mTime)) - { - return result; - } - - // - MqlDateTime timeStruct; - bool isConverts = TimeToStruct( - mTime, - timeStruct // - ); - if (!isConverts) - { - return result; - } - - // - string year = ToString(timeStruct.year); - string month = ToString(timeStruct.mon); - string day = ToString(timeStruct.day); - string hour = ToString(timeStruct.hour); - string minute = ToString(timeStruct.min); - string second = ToString(timeStruct.sec); - - // - result = - // - // Year ... - year + separator + - // - // Month ... - (StringLen(month) == 1 - ? "0" + month - : month) + - separator + - // - // Day ... - (StringLen(day) == 1 - ? "0" + day - : day) + - separator + - // - // Hour ... - (StringLen(hour) == 1 - ? "0" + hour - : hour) + - separator + - // - // Minute ... - (StringLen(minute) == 1 - ? "0" + minute - : minute) + - separator + - // - // Seconds ... - (StringLen(second) == 1 - ? "0" + second - : second) + - separator + - // - "" - // - ; - - // - return result; -} - -// -// Bar Times ... - -// -// Retrieve Specified Bar Time ... -datetime GetBarTime( - string mSymbol = "", // Specify Symbol - ENUM_TIMEFRAMES mPeriod = NULL, // Specify TimeFrame - int barIndex = 0 // Specify Bar Index -) -{ - // - // Validate and Normalize Args ... - - // - mSymbol = NormalizeSymbol(mSymbol); - mPeriod = NormalizePeriod(mPeriod); - - // - // Retrieve Bar Time ... - datetime result = iTime( - mSymbol, - mPeriod, - barIndex); - - // - return result; -} - -// -// Retrieve Specified Bar Time ... -ulong GetBarTimeAsSeconds( - string mSymbol = "", // Specify Symbol - ENUM_TIMEFRAMES mPeriod = NULL, // Specify TimeFrame - int barIndex = 0 // Specify Bar Index -) -{ - // - // Retrieve Bar Time ... - datetime time = GetBarTime( - mSymbol, - mPeriod, - barIndex); - - // - ulong result = TimeToSeconds(time); - - // - return result; -} - -// -// Retrieve Specified Bar Time ... -ulong GetBarTimeAsMilliSeconds( - string mSymbol = "", // Specify Symbol - ENUM_TIMEFRAMES mPeriod = NULL, // Specify TimeFrame - int barIndex = 0 // Specify Bar Index -) -{ - // - // Retrieve Bar Time ... - datetime time = GetBarTime( - mSymbol, - mPeriod, - barIndex); - - // - ulong result = TimeToMilliSeconds(time); - - // - return result; -} - -// -// Retrieve a Bar Time Structure ... -MqlDateTime GetBarTimeStruct( - string mSymbol = "", // Specify Symbol - ENUM_TIMEFRAMES mPeriod = NULL, // Specify TimeFrame - int barIndex = 0 // Specify Bar Index -) -{ - // - MqlDateTime result = {}; - - // - // Retrieve Bar Time ... - datetime barTime = GetBarTime( - mSymbol, - mPeriod, - barIndex); - - // - // Convert to Structure ... - TimeToStruct(barTime, result); - - // - return result; -} - -// -// Other Tools ... - -// -template -bool IsSame( - T &buffer[], // Search Buffer - int count = 5, // Number of Searchs - int start = 0 // Start ... -) -{ - // - bool result = false; - - // - int bufferSize = ArraySize(buffer); - result = bufferSize > 0; - if (!result) - { - return result; - } - - // - // Validate Count ... - result = start + count < bufferSize; - if (!result) - { - return result; - } - - // - T iTem = buffer[start]; - for (int i = start; i < start + count; i++) - { - // - if (iTem != buffer[i]) - { - result = false; - break; - } - - // - if (!result) - { - result = true; - } - } - - // - return result; -} - -// -// Check first Cross Over second at index ... -bool IsCrossedOver( - const double &first[], // the buffer which check crossing over second buffer - const double &second[], // first buffer checks based on this buffer - const int index = 0 // check crosses in specific index -) -{ - // - bool result = false; - - // - // Validate Args ... - if (ArraySize(first) < index + 1 || ArraySize(second) < index + 1) - { - return result; - } - - // - result = first[index] > second[index] && - !(first[index + 1] > second[index + 1]); - - // - return result; -} - -// -// Check first is Over second at index ... -bool IsOver( - const double &first[], // the buffer which check over second buffer - const double &second[], // first buffer checks based on this buffer - const int index = 0 // check crosses in specific index -) -{ - // - bool result = false; - - // - // Validate Args ... - if (ArraySize(first) < index + 1 || ArraySize(second) < index + 1) - { - return result; - } - - // - result = first[index] > second[index] && - first[index + 1] > second[index + 1]; - - // - return result; -} - -// -// Check first Cross Under second at index ... -bool IsCrossedUnder( - const double &first[], // the buffer which check crossing under second buffer - const double &second[], // first buffer checks based on this buffer - const int index = 0 // check crosses in specific index -) -{ - // - bool result = false; - - // - // Validate Args ... - if (ArraySize(first) < index + 1 || ArraySize(second) < index + 1) - { - return result; - } - - // - result = first[index] < second[index] && - !(first[index + 1] < second[index + 1]); - - // - return result; -} - -// -// Check first is Under second at index ... -bool IsUnder( - const double &first[], // the buffer which check under second buffer - const double &second[], // first buffer checks based on this buffer - const int index = 0 // check crosses in specific index -) -{ - // - bool result = false; - - // - // Validate Args ... - if (ArraySize(first) < index + 1 || ArraySize(second) < index + 1) - { - return result; - } - - // - result = first[index] < second[index] && - first[index + 1] < second[index + 1]; - - // - return result; -} - -// -// Check if a Value Increasing in Loopback ... -bool IsIncreasing( - const int from, // Last Time Index - const int to, // Fisrs Tima Index - const double &buffer[] // the Buffer which required to search -) -{ - // - bool result = false; - - // - // Validate Args ... - if ( - from <= to || - ArraySize(buffer) < from + 1) - { - return result; - } - - // - // Loop through Items ... - double toValue = buffer[to]; - double fromValue = buffer[from]; - result = toValue > fromValue; - for (int i = to + 1; i <= from - 1; i++) - { - // - double iValue = buffer[i]; - bool isPassed = toValue >= iValue; - - // - bool isIIncreasing = IsIncreasing( - from, - i, - buffer); - - // - // Check Result ... - result = result && isPassed && isIIncreasing; - if (!result) - { - break; - } - } - - // - return result; -} - -// -// Check if a Value Decreasing in Loopback ... -bool IsDecreasing( - const int from, // Last Time Index - const int to, // Fisr Tima Index - const double &buffer[] // the Buffer which required to search -) -{ - // - bool result = false; - - // - // Validate Args ... - if ( - from <= to || - ArraySize(buffer) < from + 1) - { - return result; - } - - // - // Loop through Items ... - double toValue = buffer[to]; - double fromValue = buffer[from]; - result = toValue < fromValue; - for (int i = to + 1; i <= from - 1; i++) - { - // - double iValue = buffer[i]; - bool isPassed = toValue <= iValue; - - // - bool isIDecreasing = IsDecreasing( - from, - i, - buffer); - - // - // Check Result ... - result = result && isPassed && isIDecreasing; - if (!result) - { - break; - } - } - - // - return result; -} - -// -bool IsTrendingUp( - const double &buffer1[], // First Buffer - const double &buffer2[] // Seccend Buffer -) -{ - // - bool result = false; - - // - int buffer1Count = ArraySize(buffer1); - int buffer2Count = ArraySize(buffer2); - if (buffer1Count <= 0 || buffer2Count <= 0) - { - return result; - } - - // - int count = MathMin(buffer1Count, buffer2Count); - if (count <= 1) - { - return result; - } - - // - int upCounts = 0; - int downCounts = 0; - double value = MathAbs(buffer1[0] - buffer2[0]); - for (int i = 1; i < count; i++) - { - // - double iValue = MathAbs(buffer1[i] - buffer2[i]); - - // - if (value > iValue) - { - upCounts++; - } - - // - if (value < iValue) - { - downCounts++; - } - } - - // - result = upCounts > 1 && upCounts > downCounts; - - // - return result; -} - -// -bool IsTrendingDown( - const double &buffer1[], // First Buffer - const double &buffer2[] // Seccend Buffer -) -{ - // - bool result = false; - - // - int buffer1Count = ArraySize(buffer1); - int buffer2Count = ArraySize(buffer2); - if (buffer1Count <= 0 || buffer2Count <= 0) - { - return result; - } - - // - int count = MathMin(buffer1Count, buffer2Count); - if (count <= 1) - { - return result; - } - - // - int upCounts = 0; - int downCounts = 0; - double value = MathAbs(buffer1[0] - buffer2[0]); - for (int i = 1; i < count; i++) - { - // - double iValue = MathAbs(buffer1[i] - buffer2[i]); - - // - if (value > iValue) - { - upCounts++; - } - - // - if (value < iValue) - { - downCounts++; - } - } - - // - result = downCounts > 1 && downCounts > upCounts; - - // - return result; -} - -// -// Calculate Slope of Specified Buffer at Specified Index ... -double GetSlope( - const double &buffer[], // Buffer - int from, // In Past Index ... - int to // In Past Index ... -) -{ - // - double result = 0; - - // - if (from > ArraySize(buffer) || to > ArraySize(buffer)) - { - return result; - } - - // - double toValue = buffer[to]; - double fromValue = buffer[from]; - double deltaValue = toValue - fromValue; - double deltaTime = from - to; - - // - result = deltaValue / deltaTime; - - // - return result; -} - -// -// Calculate Fib Level ... -double GetFibonacciLevel( - double upPrice, // Upper Bound - double downPrice, // Downer Bound - double level, // Level Multiplier Factor - int direction // From Down to Up < 0, other wise Vice Versa - // -) -{ - // - double ling = upPrice - downPrice; - double pLevel = (ling / 100) * (level * 100); - - // - double result = direction > 0 ? upPrice - pLevel : downPrice + pLevel; - - // - return result; -} - -// -double MAOnArray( - double &array[], - int total, - int period, - int ma_shift, - int ma_method, - int shift // -) -{ - // - double result = 0; - - // - double buf[]; - double arr[]; - - // - if (total == 0) - { - total = ArraySize(array); - } - - // - if (total > 0 && total <= period) - { - return result; - } - - // - if (shift > total - period - ma_shift) - { - return result; - } - - // - // MA Method ... - switch (ma_method) - { - // - // Mode SMA ... - case MODE_SMA: - { - // - total = ArrayCopy(arr, array, 0, shift + ma_shift, period); - if (ArrayResize(buf, total) < 0) - { - return result; - } - - // - double sum = 0; - int i, pos = total - 1; - for (i = 1; i < period; i++, pos--) - { - sum += arr[pos]; - } - - // - while (pos >= 0) - { - // - sum += arr[pos]; - buf[pos] = sum / period; - sum -= arr[pos + period - 1]; - pos--; - } - - // - result = buf[0]; - return result; - } - - // - // Mode EMA ... - case MODE_EMA: - { - // - if (ArrayResize(buf, total) < 0) - { - return result; - } - - // - int pos = total - 2; - double pr = 2.0 / (period + 1); - - // - while (pos >= 0) - { - // - if (pos == total - 2) - { - buf[pos + 1] = array[pos + 1]; - } - - // - buf[pos] = array[pos] * pr + buf[pos + 1] * (1 - pr); - pos--; - } - - // - result = buf[shift + ma_shift]; - return result; - } - - // - // Mode SMMA ... - case MODE_SMMA: - { - // - if (ArrayResize(buf, total) < 0) - { - return result; - } - - // - int i, kk, pos; - double sum = 0; - pos = total - period; - - // - while (pos >= 0) - { - // - if (pos == total - period) - { - // - for (i = 0, kk = pos; i < period; i++, kk++) - { - // - sum += array[kk]; - buf[kk] = 0; - } - } - else - { - sum = buf[pos + 1] * (period - 1) + array[pos]; - } - - // - buf[pos] = sum / period; - pos--; - } - - // - result = buf[shift + ma_shift]; - return result; - } - - // - // Mode LWMA ... - case MODE_LWMA: - { - // - if (ArrayResize(buf, total) < 0) - { - return result; - } - - // - double price; - double sum = 0.0, lsum = 0.0; - int i, weight = 0, pos = total - 1; - - // - for (i = 1; i <= period; i++, pos--) - { - // - price = array[pos]; - sum += price * i; - lsum += price; - weight += i; - } - - // - pos++; - i = pos + period; - while (pos >= 0) - { - // - buf[pos] = sum / weight; - if (pos == 0) - { - break; - } - - // - i--; - pos--; - price = array[pos]; - sum = sum - lsum + price * period; - lsum -= array[i]; - lsum += price; - } - - // - result = buf[shift + ma_shift]; - return result; - } - - // - default: - return result; - } - - // - return result; -} - -// -// Method 1 -// Normalize between 1 and 0 ... -template -double GetNormalizedValueMethod1( - T &buffer[], // Array which required to Normalize - int mLength, // Length of Normalization - int mStart = 0, // start index - int digits = 5 // Normalization Digits -) -{ - // - double result = 0; - - // - if (digits <= 5) - { - digits = 5; - } - - // - int bufferSize = ArraySize(buffer); - if (!IsValidSize(bufferSize)) - { - return result; - } - - // - // Normalize Count ... - NormalizeCount( - mStart, - mLength, - buffer // - ); - - // - T max = 0; - T min = 0; - - // - if (bufferSize != mLength) - { - // - T tmp[]; - Copy( - mStart, - mLength, - buffer, - tmp // - ); - - // - max = GetMax(tmp); - min = GetMin(tmp); - } - - // - if (bufferSize == mLength) - { - // - max = GetMax(buffer); - min = GetMin(buffer); - } - - // - T iValue = buffer[mStart]; - - // - double minMaxDiff = (max - min); - if (minMaxDiff <= 0) - { - return result; - } - - // - result = (iValue - min) / minMaxDiff; - - // - result = NormalizeDouble(result, digits); - - // - return result; -} - -// -// Method 2 -// Normalize Between Specified Upper and Lower ... -template -double GetNormalizedValueMethod2( - T &buffer[], // Array which required to Normalize - int mLength, // Length of Normalization - int mUpper, // Specified Upper Value - int mLower, // Specified Lower Value - int mStart = 0, // start index - int digits = 5 // Normalization Digits -) -{ - // - double result = 0; - - // - if (digits <= 5) - { - digits = 5; - } - - // - int bufferSize = ArraySize(buffer); - if (!IsValidSize(bufferSize)) - { - return result; - } - - // - // Normalize Count ... - NormalizeCount( - mStart, - mLength, - buffer // - ); - - // - T max = 0; - T min = 0; - - // - if (bufferSize != mLength) - { - // - T tmp[]; - Copy( - mStart, - mLength, - buffer, - tmp // - ); - - // - max = GetMax(tmp); - min = GetMin(tmp); - } - - // - if (bufferSize == mLength) - { - // - max = GetMax(buffer); - min = GetMin(buffer); - } - - // - T iValue = buffer[mStart]; - - // - double minMaxDiff = (max - min); - double boundaryDiff = (mUpper - mLower); - if (minMaxDiff <= 0 || boundaryDiff <= 0) - { - return result; - } - - // - result = boundaryDiff / (minMaxDiff * (iValue - max) + max); - - // - result = NormalizeDouble(result, digits); - - // - return result; -} - -// -// Templates ... - -// -// Retrieve Specific Object Types Name ... -template -string GetTypeName(const T &t) -{ - return typename(T); -} - -// -template -string GetToken(T &item) -{ - // - string mType = GetTypeName(item); - - // - string result = mType; - - // - string parts[]; - int partsCount = SplitContent( - parts, - result, - " " - // - ); - if (partsCount <= 0) - { - // - result = mType; - return result; - } - - // - bool hasLastPart = GetLastItem( - result, - parts - // - ); - if (!hasLastPart) - { - // - result = mType; - return result; - } - - // - return result; -} - -// -// Same as Get Token for Use in Classes ... -template -string GetSpecificToken(T &item) -{ - // - string mType = GetTypeName(item); - - // - string result = mType; - - // - string parts[]; - int partsCount = SplitContent( - parts, - result, - " " - // - ); - if (partsCount <= 0) - { - // - result = mType; - return result; - } - - // - bool hasLastPart = GetLastItem( - result, - parts - // - ); - if (!hasLastPart) - { - // - result = mType; - return result; - } - - // - return result; -} - -// -// Generate Unique Tags ... -template -string GenerateTag(T &model) -{ - // - string result = ""; - - // - string tag = model.ToString(); - if (StringLen(tag) == 0) - { - return result; - } - - // - static XSCMD5 md5; - - // - result = md5.Hash(tag); - - // - return result; -} - -// -// Hash Specified Content ... -template -string ToMD5(T content) -{ - // - string result = ""; - - // - string strContent = ToString(content); - if (StringLen(strContent) == 0) - { - return result; - } - - // - static XSCMD5 md5; - - // - result = md5.Hash(strContent); - - // - return result; -} - -// -// Check a Value Not Empty ... -template -bool NotEmpty(T value) -{ - return value != EMPTY_VALUE; -} - -// -// Check a Value Not Empty and Zero ... -template -bool NotEmptyZero(T value) -{ - return value != EMPTY_VALUE && value != 0; -} - -// -// Add Specified Item to Array ... -template -int Add( - T item, // item want to add - T &buffer[] // Destination buffer -) -{ - // - int result = 0; - - // - ArrayResize( - buffer, - ArraySize(buffer) + 1); - - // - buffer[ArraySize(buffer) - 1] = item; - - // - result = ArraySize(buffer); - - // - return result; -} -template -int AddSpecific( - T item, // item want to add - T &buffer[] // Destination buffer -) -{ - // - return Add( - item, - buffer // - ); -} -template -int AddRef( - T &item, // item want to add - T &buffer[] // Destination buffer -) -{ - // - int result = 0; - - // - ArrayResize( - buffer, - ArraySize(buffer) + 1); - - // - buffer[ArraySize(buffer) - 1] = item; - - // - result = ArraySize(buffer); - - // - return result; -} - -// -// Remove Specified Item from an Array ... -template -bool Remove( - T item, - T &buffer[]) -{ - // - bool result = false; - - // - int itemIndex = FindIndex( - item, - buffer); - if (itemIndex < 0) - { - return result; - } - - // - result = ArrayRemove( - buffer, - itemIndex, - 1); - - // - return result; -} - -// -// Clean Specified Array ... -template -void Clean(T &buffer[]) -{ - // - ArrayFree(buffer); - ArrayResize(buffer, 0); -} -template -void SpecificClean(T &buffer[]) -{ - Clean(buffer); -} - -// -// Copy Whole Content of Source to Dest array ... -template -void Copy( - T &source[], // Source Buffer ... - T &dest[], // Dest Buffer ... - bool cleanDest = true // Force Clen Dest Buffer ... -) -{ - // - if (cleanDest) - { - Clean(dest); - } - - // - int sourceCount = ArraySize(source); - if (sourceCount <= 0) - { - return; - } - - // - for (int i = 0; i < sourceCount; i++) - { - // - T iSource = source[i]; - - // - AddRef( - iSource, - dest); - } -} - -// -// Copy Items from a Buffer ... -template -int Copy( - int start, // Start - int count, // Number of Items for read - T &source[], // Source Buffer - T &dest[], // Dest Buffer - bool forceClean = true, // Force To Clean buffer - bool forceStart = true // Force To Clean buffer -) -{ - // - int result = 0; - - // - if (forceClean) - { - Clean(dest); - } - - // - if (start < 0 && forceStart) - { - start = 0; - } - - // - if (start >= ArraySize(source)) - { - start = ArraySize(source) - 1; - } - - // - if (count == 0) - { - count = ArraySize(source) - 1 - start; - } - - // - if (start + count > ArraySize(source)) - { - return result; - } - - // - int beforeSize = ArraySize(dest); - - // - bool asSeriesDest = ArrayGetAsSeries(dest); - bool asSeriesSource = ArrayGetAsSeries(source); - - // - ArraySetAsSeries(dest, true); - ArraySetAsSeries(source, true); - - // - ArrayCopy( - dest, - source, - 0, - start, - count - // - ); - - // - int afterSize = ArraySize(dest); - - // - result = afterSize - beforeSize; - - // - ArraySetAsSeries(dest, asSeriesDest); - ArraySetAsSeries(source, asSeriesSource); - - // - return result; -} - -// -// Copy Items from a Buffer ... -template -int CopyRef( - int start, // Start - int count, // Number of Items for read - T &source[], // Source Buffer - T &dest[], // Dest Buffer - bool forceClean = true // Force To Clean buffer -) -{ - // - int result = 0; - - // - if (forceClean) - { - Clean(dest); - } - - // - if (start < 0) - { - start = 0; - } - - // - if (start >= ArraySize(source)) - { - start = ArraySize(source) - 1; - } - - // - int beforeSize = ArraySize(dest); - - // - bool asSeriesDest = ArrayGetAsSeries(dest); - bool asSeriesSource = ArrayGetAsSeries(source); - - // - ArraySetAsSeries(dest, true); - ArraySetAsSeries(source, true); - - // - for (int i = start; i < start + count; i++) - { - // - AddRef( - source[i], - dest - // - ); - } - - // - int afterSize = ArraySize(dest); - - // - result = afterSize - beforeSize; - - // - ArraySetAsSeries(dest, asSeriesDest); - ArraySetAsSeries(source, asSeriesSource); - - // - return result; -} - -// -// Retrive Last Item of Specified Buffer ... -template -bool GetLastItem( - T &item, // Holds Result - T &buffer[] // Specified Buffer -) -{ - // - bool result = false; - - // - int bufferSize = ArraySize(buffer); - if (bufferSize <= 0) - { - return result; - } - - // - item = buffer[bufferSize - 1]; - - // - result = true; - return result; -} - -// -// Search Array For Specific Item ... -template -int FindIndex( - T item, // What is Search ... - T &buffer[] // Search in ... -) -{ - // - int result = -1; - - // - int count = ArraySize(buffer); - if (count <= 0) - { - return result; - } - - // - for (int i = 0; i < count; i++) - { - // - T iT = buffer[i]; - - // - if (iT == item) - { - // - result = i; - break; - } - } - - // - return result; -} - -// -// Check an Array Contains Specified Value ... -template -bool Contains( - T item, // What is Search ... - T &buffer[] // Search in ... -) -{ - // - bool result = false; - - // - int idx = FindIndex( - item, - buffer); - result = idx > -1; - - // - return result; -} - -// -// Calculate a Buffer's Average ... -template -double GetAverage( - T &buffer[], // the Buffer which required to search - int start = 0, // Start Index - int count = 0 // Count for Search -) -{ - // - double result = 0; - - // - T tmp[]; - int tmpCount = Copy( - start, - count, - buffer, - tmp - // - ); - if (tmpCount <= 0) - { - return result; - } - - // - // Calculate Summary ... - for (int i = 0; i < tmpCount; i++) - { - result += buffer[i]; - } - - // - // Calculate Average ... - result = result / tmpCount; - - // - return result; -} - -// -// Get Max of Specific Loopback of a Buffer ... -template -T GetMax( - T &buffer[], // the Buffer which required to search - int start = 0, // Start Index - int count = 0 // Count for Search -) -{ - // - T result = 0; - - // - if (count <= 0) - { - count = ArraySize(buffer); - } - - // - T tmp[]; - int tmpCount = Copy( - start, - count, - buffer, - tmp - // - ); - if (tmpCount <= 0) - { - return result; - } - - // - // Loop Through LoopBack ... - for (int i = 0; i < tmpCount; i++) - { - // - T iValue = tmp[i]; - - // - result = - // - result == 0 || result < iValue - // - ? iValue - // - : result - // - ; - } - - // - return result; -} - -// -// Get Min of Specific Loopback of a Buffer ... -template -T GetMin( - T &buffer[], // the Buffer which required to search - int start = 0, // Start Index - int count = 0 // Count for Search -) -{ - // - T result = 0; - - // - if (count <= 0) - { - count = ArraySize(buffer); - } - - // - T tmp[]; - int tmpCount = Copy( - start, - count, - buffer, - tmp - // - ); - if (tmpCount <= 0) - { - return result; - } - - // - // Loop Through LoopBack ... - for (int i = 0; i < tmpCount; i++) - { - // - T iValue = tmp[i]; - - // - result = - // - result == 0 || result > iValue - // - ? iValue - // - : result - // - ; - } - - // - return result; -} - -// -// Find a Value less than Specified ... -template -T FindLesserThan( - T value, // Specified Value ... - const T &source[], // Source ... - bool isDescend = false // Find Biggest Lesser Value ... -) -{ - // - T result = -1; - - // - int itemsCount = ArraySize(source); - if (itemsCount <= 0) - { - return result; - } - - // - // Make a Copy of source ... - T tmp[]; - - // - ArrayResize( - tmp, - ArraySize(source)); - - // - ArrayCopy( - tmp, - source); - - // - // Sort Temp Buffer ... - ArraySort(tmp); - if (isDescend) - { - ArrayReverse(tmp); - } - - // - int tmpCount = ArraySize(tmp); - for (int i = 0; i < tmpCount; i++) - { - // - T iValue = tmp[i]; - - // - if (iValue < value) - { - // - result = iValue; - break; - } - } - - // - return result; -} - -// -// Find a Value less than Specified ... -template -T FindBiggerThan( - T value, // Specified Value ... - const T &source[], // Source ... - bool isDescend = false // Find Smallest Bigger Value ... -) -{ - // - T result = -1; - - // - int itemsCount = ArraySize(source); - if (itemsCount <= 0) - { - return result; - } - - // - // Make a Copy of source ... - T tmp[]; - - // - ArrayResize( - tmp, - ArraySize(source)); - - // - ArrayCopy( - tmp, - source); - - // - // Sort Temp Buffer ... - ArraySort(tmp); - if (!isDescend) - { - ArrayReverse(tmp); - } - - // - int tmpCount = ArraySize(tmp); - for (int i = 0; i < tmpCount; i++) - { - // - T iValue = tmp[i]; - - // - if (iValue > value) - { - // - result = iValue; - break; - } - } - - // - return result; -} - -// -// Find Same Values in Array ... -template -void FindSames( - T &result[], // Holds Result ... - T &source[], // Source ... - int verifications = 3 // Number of Consequence Repeat ... -) -{ - // - Clean(result); - - // - // TenkanSen Flats ... - int sourceCount = ArraySize(source); - if (sourceCount > verifications) - { - // - T mLast = 0; - int mVerified = 0; - for (int i = 0; i < sourceCount; i++) - { - // - T iVal = source[i]; - if (mLast == 0) - { - mLast = iVal; - } - else if (mLast == iVal) - { - mVerified++; - } - else - { - mLast = iVal; - mVerified = 0; - } - - // - if (iVal == mLast && mVerified >= verifications) - { - // - Add( - iVal, - result); - - // - mLast = 0; - mVerified = 0; - } - } - } -} - -// -// Add an Item to a Buffer if not Exists ... -void AddIfNotExists( - double value, - double &values[], - double smoothingPoint = 3) -{ - // - double smoothingValue = smoothingPoint * GetPoints(_Symbol); - - // - int valuesCount = ArraySize(values); - if (valuesCount <= 0) - { - // - Add(value, - values); - } - else - { - // - bool isExists = false; - for (int i = 0; i < valuesCount; i++) - { - // - double iVal = values[i]; - - // - double diff = MathAbs(iVal - value); - - // - if (iVal == value || diff < smoothingValue) - { - // - isExists = true; - break; - } - } - - // - if (!isExists) - { - // - Add(value, - values); - } - } -} - -// -// Add a Buffers Child to another Buffer -// if it's not Contains them ... -void AddsIfNotExists( - double &source[], - double &dest[], - double smoothingPoint = 3) -{ - // - double smoothingValue = smoothingPoint * GetPoints(_Symbol); - - // - int sourceCount = ArraySize(source); - if (sourceCount <= 0) - { - return; - } - - // - for (int i = 0; i < sourceCount; i++) - { - // - double iSource = source[i]; - - // - AddIfNotExists( - iSource, - dest, - smoothingPoint); - } -} - -// -// Bar XOHCL ... - -// -// Extract Specific Range of Bars ... -// using Start Bar Index ... -int GetBars( - XOHCL &result[], // Hold Result - string mSymbol = NULL, // Trading Symbol - ENUM_TIMEFRAMES mPeriod = NULL, // Trading Time Frame - int from = 0, // Start Bar Index - int count = 1, // Number of Bars - bool forceClean = true // Clean Result Array -) -{ - // - int mResult = 0; - - // - if (from < 0) - { - from = 0; - } - - // - mSymbol = NormalizeSymbol(mSymbol); - mPeriod = NormalizePeriod(mPeriod); - - // - int total = Bars( - mSymbol, - mPeriod); - if (from > total - 2) - { - from = total - 2; - } - - // - if (count < 0) - { - count = 1; - } - - // - int start = from; - int end = start + count; - if (end > total - 1) - { - end = total - 1; - } - - // - if (forceClean) - { - Clean(result); - } - - // - int beforeSize = ArraySize(result); - - // - for (int i = start; i < end; i++) - { - // - XOHCL iBar; - bool isValid = iBar.Init( - mSymbol, - mPeriod, - i - // - ); - - // - if (isValid) - { - // - AddRef( - iBar, - result - // - ); - } - } - - // - int afterSize = ArraySize(result); - - // - mResult = afterSize - beforeSize; - - // - return mResult; -} - -// -// Extract Specific Range of Bars ... -// using Start Bar Time ... -int GetBars( - XOHCL &result[], // Hold Result - string mSymbol = NULL, // Trading Symbol - ENUM_TIMEFRAMES mPeriod = NULL, // Trading Time Frame - datetime from = NULL, // Start Bar Time - int count = 1, // Number of Bars - bool forceClean = true // Clean Result Array -) -{ - // - mSymbol = NormalizeSymbol(mSymbol); - mPeriod = NormalizePeriod(mPeriod); - - // - from = NormalizeTime(from); - - // - int barIndex = iBarShift( - mSymbol, - mPeriod, - from, - false - // - ); - - // - return GetBars( - result, - mSymbol, - mPeriod, - barIndex, - count, - forceClean - // - ); -} - -// -// String ... - -// -// Search a Content Contains Specific String or not ... -bool Contains( - string mQuery, // Search String - string mContent, // Search Content - bool ignoreCase = true // Ignore Case -) -{ - // - bool result = false; - - // - // Validate Query ... - result = IsValid(mQuery); - if (!result) - { - return result; - } - - // - // Validate Content ... - result = IsValid(mContent); - if (!result) - { - return result; - } - - // - // Normalize Inputs ... - string query = mQuery; - string content = mContent; - if (ignoreCase) - { - // - StringToLower(query); - StringToLower(content); - } - - // - int queryIdx = StringFind( - content, - query); - - // - result = queryIdx >= 0; - - // - return result; -} - -// -bool Contains( - string &mQueries[], // Search Strings - string mContent, // Search Content - bool ignoreCase = true // Ignore Case -) -{ - // - bool result = false; - - // - // Validate Queries ... - int queriesCount = ArraySize(mQueries); - result = queriesCount > 0; - if (!result) - { - return result; - } - - // - // Validate Content ... - result = IsValid(mContent); - if (!result) - { - return result; - } - - // - int containsCount = 0; - for (int i = 0; i < queriesCount; i++) - { - // - bool isContains = Contains( - mQueries[i], - mContent, - ignoreCase); - - // - if (!isContains) - { - // - result = false; - break; - } - - // - containsCount++; - } - - // - result = containsCount == queriesCount; - - // - return result; -} - -// -// Convert From String ... -template -T FromString(string value) -{ - // - T result = NULL; - - // - if (!IsValid(value)) - { - return result; - } - - // - result = (T)value; - - // - return result; -} - -// -// Converts an item to String ... -template -string ToString(T value) -{ - return (string)value; -} - -// -// Used In Report or Summary Generators ... -string ToString( - string prefix, // Title - bool value, // Value - bool ignoreFalseConditions = true, // Ignore False Conditions - string lineSeparator = "\n", // Line Separator - string prefixSeparator = ":" // Title Separator -) -{ - // - string result = NULL; - - // - result = (value || !ignoreFalseConditions) - ? prefix + - prefixSeparator + " " + - ToString(value) + - lineSeparator - : ""; - - // - return result; -} - -// -template -string ToString( - string prefix, // Title - T value, // Value - string lineSeparator = "\n", // Line Separator - string prefixSeparator = ":" // Title Separator -) -{ - // - string result = NULL; - - // - result = prefix + - prefixSeparator + " " + - ToString(value) + - lineSeparator; - - // - return result; -} - -// -string SetLabel( - string mLabel, // Provided Label ... - string value, // Source Value ... - string separator = "\n", // Line Separator - bool addTopEmptyLine = true // Add Empty Line On top -) -{ - // - string result = value; - - // - if (StringLen(mLabel) <= 0) - { - return result; - } - - // - result = (StringLen(value) > 0) - ? (addTopEmptyLine ? separator : "") + - mLabel + - separator + - "-----------------------------" + - separator + - value - : value; - - // - return result; -} - -// -// Converts a Buffer to String Representation ... -template -string ToString( - const T &buffer[], // Specified Buffer - string separator = ",", // Specified Separator - bool addIndex = false, // Specified Add Items Indexes or Not - string indexLabel = "i:", // Specified Index Label - string indexSeparator = ">" // Specified Index Separator -) -{ - // - string result = ""; - - // - int bufferSize = ArraySize(buffer); - if (bufferSize <= 0) - { - return result; - } - - // - for (int i = 0; i < bufferSize; i++) - { - // - if (addIndex) - { - // - if (StringLen(indexLabel) > 0) - { - result += indexLabel + " "; - } - - // - result += (string)i + " "; - - // - if (StringLen(indexSeparator) > 0) - { - result += indexSeparator + " "; - } - } - - // - string iItemString = (string)buffer[i]; - - // - result += iItemString; - - // - if (i < bufferSize - 1) - { - result += separator; - } - } - - // - return result; -} - -// -// Converts String to boolean ... -bool ToBoolean(string value) -{ - // - bool result = false; - - // - if (StringLen(value) <= 0) - { - return result; - } - - // - StringToLower(value); - result = value == "true"; - - // - return result; -} - -// -// Split an String Representation of an Array ... -int SplitContent( - string &result[], // Hold Result ... - string content, // Source ... - string separator = ",", // Separator ... - bool forceCleanResult = true // Clean Result ... -) -{ - // - int mResult = 0; - - // - if (forceCleanResult) - { - Clean(result); - } - - // - int before = ArraySize(result); - - // - if (separator == NULL || StringLen(separator) == 0) - { - separator = ","; - } - - // - if (StringLen(content) == 0) - { - return mResult; - } - - // - StringSplit( - content, - StringGetCharacter( - separator, - 0), - result); - - // - int after = ArraySize(result); - - // - mResult = after - before; - - // - return mResult; -} - -// -// Extract Data from String ... -string ExtractString( - const string source, // Source String used for Extracting - const string startString = "(", // Expression Start String must be Unique - const string endString = ")" // Where to End Extraction, usually a Sign -) -{ - // - string result = ""; - - // - // Validate String ... - if ( - StringLen(source) == 0 || - StringLen(endString) == 0 || - StringLen(startString) == 0) - { - return result; - } - - // - // Find Start String Position ... - int sPos = StringFind( - source, - startString); - if (sPos < 0) - { - return result; - } - - // - // Find End String Position after Start String ... - int searchEndFromPos = sPos + StringLen(startString); - int ePos = StringFind( - source, - endString, - searchEndFromPos); - if (ePos < 0) - { - return result; - } - - // - // Extract Data from Source ... - int dLength = ePos - searchEndFromPos; - result = StringSubstr( - source, - searchEndFromPos, - dLength); - - // - return result; -} - -// -// Extract an Array of Contents ... -int ExtractStrings( - string &result[], // Hold Result - const string source, // Source String used for Extracting - const string startString = "(", // Expression Start String must be Unique - const string endString = ")" // Where to End Extraction, usually a Sign -) -{ - // - int mResult = 0; - - // - Clean(result); - - // - // Validate Args ... - int sourceLength = StringLen(source); - int startLength = StringLen(startString); - int endLength = StringLen(endString); - - // - int minRequiredLength = startLength + endLength; - - // - if ( - endLength <= 0 || - startLength <= 0 || - sourceLength <= 0 || - sourceLength < minRequiredLength) - { - return mResult; - } - - // - // Make a Copy of Source for Manipulating ... - string workStr = source; - - // - // Define a Loop ... - while (StringLen(workStr) > minRequiredLength) - { - // - // Find Item ... - string item = ExtractString( - workStr, - startString, - endString); - - // - // Breakout when couldn't find anymore item ... - int itemLength = StringLen(item); - if (itemLength <= 0) - { - break; - } - - // - // Prepare Item Source String for Replacing in Work String ... - string itemSource = startString + item + endString; - - // - // Add Item to Result Array ... - Add( - item, - result); - - // - // Replace Item Soure in Work String ... - StringReplace( - workStr, - itemSource, - ""); - } - - // - // Calculate Size of Array ... - mResult = ArraySize(result); - - // - return mResult; -} - -// -string ExtractSurrounded( - const string surrounded, // Surrounded Content - const string mToken, // Specified Token - const string startString = "(", // Expression Start String must be Unique - const string endString = ")" // Where to End Extraction, usually a Sign -) -{ - // - return ExtractString( - surrounded, - mToken + startString, - endString - // - ); -} - -// -int ParseIntSurrounded( - const string surrounded, // Surrounded Content - const string mToken, // Specified Token - const string startString = "(", // Expression Start String must be Unique - const string endString = ")" // Where to End Extraction, usually a Sign -) -{ - // - int result = NULL; - - // - string strContent = ExtractSurrounded( - surrounded, - mToken, - startString, - endString - // - ); - if (!IsValid(strContent)) - { - return result; - } - - // - result = (int)strContent; - - // - return result; -} -long ParseLongSurrounded( - const string surrounded, // Surrounded Content - const string mToken, // Specified Token - const string startString = "(", // Expression Start String must be Unique - const string endString = ")" // Where to End Extraction, usually a Sign -) -{ - // - long result = NULL; - - // - string strContent = ExtractSurrounded( - surrounded, - mToken, - startString, - endString - // - ); - if (!IsValid(strContent)) - { - return result; - } - - // - result = (long)strContent; - - // - return result; -} -string ParseStringSurrounded( - const string surrounded, // Surrounded Content - const string mToken, // Specified Token - const string startString = "(", // Expression Start String must be Unique - const string endString = ")" // Where to End Extraction, usually a Sign -) -{ - // - string result = NULL; - - // - string strContent = ExtractSurrounded( - surrounded, - mToken, - startString, - endString - // - ); - if (!IsValid(strContent)) - { - return result; - } - - // - result = (string)strContent; - - // - return result; -} -double ParseDoubleSurrounded( - const string surrounded, // Surrounded Content - const string mToken, // Specified Token - const string startString = "(", // Expression Start String must be Unique - const string endString = ")" // Where to End Extraction, usually a Sign -) -{ - // - double result = NULL; - - // - string strContent = ExtractSurrounded( - surrounded, - mToken, - startString, - endString - // - ); - if (!IsValid(strContent)) - { - return result; - } - - // - result = (double)strContent; - - // - return result; -} -datetime ParseTimeSurrounded( - const string surrounded, // Surrounded Content - const string mToken, // Specified Token - const string startString = "(", // Expression Start String must be Unique - const string endString = ")" // Where to End Extraction, usually a Sign -) -{ - // - datetime result = NULL; - - // - string strContent = ExtractSurrounded( - surrounded, - mToken, - startString, - endString - // - ); - if (!IsValid(strContent)) - { - return result; - } - - // - result = (datetime)strContent; - - // - return result; -} - -// -int ParseIntArraySurrounded( - int &result[], // Holds Result - const string surrounded, // Surrounded Content - const string mToken, // Specified Token - string separator = ",", // Separator ... - const string startString = "(", // Expression Start String must be Unique - const string endString = ")", // Where to End Extraction, usually a Sign - bool forceClean = true // Clean Result ... -) -{ - // - int count = 0; - - // - if (forceClean) - { - Clean(result); - } - - // - int before = ArraySize(result); - - // - string contentStr = ParseStringSurrounded(surrounded, mToken); - if (!IsValid(contentStr)) - { - return count; - } - - // - string tmps[]; - int tmpsCount = SplitContent( - tmps, - contentStr - // - ); - if (tmpsCount <= 0) - { - return count; - } - - // - for (int i = 0; i < tmpsCount; i++) - { - // - string iTMP = tmps[i]; - if (!IsValid(iTMP)) - { - continue; - } - - // - int iValue = (int)iTMP; - - // - Add( - iValue, - result - // - ); - } - - // - int after = ArraySize(result); - - // - count = after - before; - - // - return count; -} -int ParseLongArraySurrounded( - long &result[], // Holds Result - const string surrounded, // Surrounded Content - const string mToken, // Specified Token - string separator = ",", // Separator ... - const string startString = "(", // Expression Start String must be Unique - const string endString = ")", // Where to End Extraction, usually a Sign - bool forceClean = true // Clean Result ... -) -{ - // - int count = 0; - - // - if (forceClean) - { - Clean(result); - } - - // - int before = ArraySize(result); - - // - string contentStr = ParseStringSurrounded(surrounded, mToken); - if (!IsValid(contentStr)) - { - return count; - } - - // - string tmps[]; - int tmpsCount = SplitContent( - tmps, - contentStr - // - ); - if (tmpsCount <= 0) - { - return count; - } - - // - for (int i = 0; i < tmpsCount; i++) - { - // - string iTMP = tmps[i]; - if (!IsValid(iTMP)) - { - continue; - } - - // - long iValue = (long)iTMP; - - // - Add( - iValue, - result - // - ); - } - - // - int after = ArraySize(result); - - // - count = after - before; - - // - return count; -} -int ParseDoubleArraySurrounded( - double &result[], // Holds Result - const string surrounded, // Surrounded Content - const string mToken, // Specified Token - string separator = ",", // Separator ... - const string startString = "(", // Expression Start String must be Unique - const string endString = ")", // Where to End Extraction, usually a Sign - bool forceClean = true // Clean Result ... -) -{ - // - int count = 0; - - // - if (forceClean) - { - Clean(result); - } - - // - int before = ArraySize(result); - - // - string contentStr = ParseStringSurrounded(surrounded, mToken); - if (!IsValid(contentStr)) - { - return count; - } - - // - string tmps[]; - int tmpsCount = SplitContent( - tmps, - contentStr - // - ); - if (tmpsCount <= 0) - { - return count; - } - - // - for (int i = 0; i < tmpsCount; i++) - { - // - string iTMP = tmps[i]; - if (!IsValid(iTMP)) - { - continue; - } - - // - double iValue = (double)iTMP; - - // - Add( - iValue, - result - // - ); - } - - // - int after = ArraySize(result); - - // - count = after - before; - - // - return count; -} -int ParseTimeArraySurrounded( - datetime &result[], // Holds Result - const string surrounded, // Surrounded Content - const string mToken, // Specified Token - string separator = ",", // Separator ... - const string startString = "(", // Expression Start String must be Unique - const string endString = ")", // Where to End Extraction, usually a Sign - bool forceClean = true // Clean Result ... -) -{ - // - int count = 0; - - // - if (forceClean) - { - Clean(result); - } - - // - int before = ArraySize(result); - - // - string contentStr = ParseStringSurrounded(surrounded, mToken); - if (!IsValid(contentStr)) - { - return count; - } - - // - string tmps[]; - int tmpsCount = SplitContent( - tmps, - contentStr - // - ); - if (tmpsCount <= 0) - { - return count; - } - - // - for (int i = 0; i < tmpsCount; i++) - { - // - string iTMP = tmps[i]; - if (!IsValid(iTMP)) - { - continue; - } - - // - datetime iValue = (datetime)iTMP; - - // - Add( - iValue, - result - // - ); - } - - // - int after = ArraySize(result); - - // - count = after - before; - - // - return count; -} - -// -// Surround an String by Specific Token ... -template -string Surround( - string mToken, // an String which used to Tokenize - T &value, // a Value for Tokenize it - string startString = "(", // Token Start Content - string endString = ")" // Token End Content -) -{ - // - string result = NULL; - - // - string strValue = ToString(value); - if (!IsValid(strValue)) - { - return result; - } - - // - result = - // - (IsValid(mToken) - ? mToken - : "") + - // - startString + - strValue + - endString - // - ; - - // - return result; -} - -// -template -string SurroundArray( - string mToken, - T &value[], - string startString = "(", // Token Start Content - string endString = ")" // Token End Content -) -{ - // - string result = NULL; - - // - string valueStr = ToString(value); - if (!IsValid(valueStr)) - { - return result; - } - - // - result = Surround( - mToken, - valueStr, - startString, - endString - // - ); - - // - return result; -} - -// -// Periods / Cycles ... - -// -// Converts an String to TimeFrame ... -ENUM_TIMEFRAMES ToPeriod(string value) -{ - // - if (StringLen(value) == 0) - { - return _Period; - } - - // - StringTrimLeft(value); - StringTrimRight(value); - - // - ENUM_TIMEFRAMES result = _Period; - - // - if (value == "M1") - { - result = PERIOD_M1; - } - else if (value == "M2") - { - result = PERIOD_M2; - } - else if (value == "M3") - { - result = PERIOD_M3; - } - else if (value == "M4") - { - result = PERIOD_M4; - } - else if (value == "M5") - { - result = PERIOD_M5; - } - else if (value == "M6") - { - result = PERIOD_M6; - } - else if (value == "M10") - { - result = PERIOD_M10; - } - else if (value == "M12") - { - result = PERIOD_M12; - } - else if (value == "M15") - { - result = PERIOD_M15; - } - else if (value == "M20") - { - result = PERIOD_M20; - } - else if (value == "M30") - { - result = PERIOD_M30; - } - else if (value == "H1") - { - result = PERIOD_H1; - } - else if (value == "H2") - { - result = PERIOD_H2; - } - else if (value == "H3") - { - result = PERIOD_H3; - } - else if (value == "H4") - { - result = PERIOD_H4; - } - else if (value == "H6") - { - result = PERIOD_H6; - } - else if (value == "H8") - { - result = PERIOD_H8; - } - else if (value == "H12") - { - result = PERIOD_H12; - } - else if (value == "D1") - { - result = PERIOD_D1; - } - else if (value == "W1") - { - result = PERIOD_W1; - } - else if (value == "MN1") - { - result = PERIOD_MN1; - } - - // - return result; -} - -// -// Converts Period to String ... -string ToString(ENUM_TIMEFRAMES mPeriod) -{ - // - string result = ""; - - // - string mPStr = EnumToString(mPeriod); - - string mPStrParts[]; - int partsCount = StringSplit( - mPStr, - StringGetCharacter("_", 0), - mPStrParts); - if (partsCount <= 0) - { - return result; - } - - // - result = mPStrParts[1]; - - // - return result; -} - -// -// Retrieve All Available Period as an Array ...s -int GetAllAvailablePeriods( - ENUM_TIMEFRAMES &result[] // Holds Result ... -) -{ - // - Clean(result); - - // - Add( - PERIOD_M1, - result - // - ); - - // - Add( - PERIOD_M2, - result - // - ); - - // - Add( - PERIOD_M3, - result - // - ); - - // - Add( - PERIOD_M4, - result - // - ); - - // - Add( - PERIOD_M5, - result - // - ); - - // - Add( - PERIOD_M6, - result - // - ); - - // - Add( - PERIOD_M10, - result - // - ); - - // - Add( - PERIOD_M12, - result - // - ); - - // - Add( - PERIOD_M15, - result - // - ); - - // - Add( - PERIOD_M20, - result - // - ); - - // - Add( - PERIOD_M30, - result - // - ); - - // - Add( - PERIOD_H1, - result - // - ); - - // - Add( - PERIOD_H2, - result - // - ); - - // - Add( - PERIOD_H3, - result - // - ); - - // - Add( - PERIOD_H4, - result - // - ); - - // - Add( - PERIOD_H6, - result - // - ); - - // - Add( - PERIOD_H8, - result - // - ); - - // - Add( - PERIOD_H12, - result - // - ); - - // - Add( - PERIOD_D1, - result - // - ); - - // - Add( - PERIOD_W1, - result - // - ); - - // - Add( - PERIOD_MN1, - result - // - ); - - // - int mResult = ArraySize(result); - - // - return mResult; -} - -// -// Get Specific Time Frame Start Candle Time ... -datetime GetPeriodStartTime( - string mSymbol = NULL, // Specified Symbol ... - ENUM_TIMEFRAMES mPeriod = NULL, // Specified Period ... - datetime mTime = NULL // Specified Bar Time of Host Period ... -) -{ - // - // Normalize Arg ... - mTime = NormalizeTime(mTime); - mSymbol = NormalizeSymbol(mSymbol); - mPeriod = NormalizePeriod(mPeriod); - - // - int barIndex = iBarShift( - mSymbol, - mPeriod, - mTime, - false - // - ); - - // - datetime result = GetBarTime( - mSymbol, - mPeriod, - barIndex - // - ); - - // - return result; -} - -// -// Converts an String to it's related Market Cycle ... -ENUM_X_MARKET_CYCLES ToCycle(string value) -{ - // - ENUM_X_MARKET_CYCLES result = X_MARKET_CYCLE_UNKNOWN; - - // - ENUM_X_MARKET_CYCLES cycles[]; - int count = GetAllMarketCycles(cycles); - for (int i = 0; i < count; i++) - { - // - ENUM_X_MARKET_CYCLES iCycle = cycles[i]; - string iStr = ToString(iCycle); - - // - if (value == iStr) - { - // - result = iCycle; - break; - } - } - - // - return result; -} - -// -// Converts a Cycle to it's String Representation ... -string ToString(ENUM_X_MARKET_CYCLES cycle) -{ - // - string result = ""; - - // - string mPStr = EnumToString(cycle); - - string mPStrParts[]; - int partsCount = StringSplit( - mPStr, - StringGetCharacter("_", 0), - mPStrParts); - if (partsCount <= 0) - { - return result; - } - - // - result = mPStrParts[3]; - - // - return result; -} - -// -// Retrieve all Available Cycles ... -int GetAllMarketCycles(ENUM_X_MARKET_CYCLES &result[]) -{ - // - int mResult = 0; - - // - Clean(result); - - // - ENUM_X_MARKET_CYCLES tmp[] = { - X_MARKET_CYCLE_UNKNOWN, - X_MARKET_CYCLE_SHORT, - X_MARKET_CYCLE_MEDIUM, - X_MARKET_CYCLE_LONG, - X_MARKET_CYCLE_HIND}; - - // - Copy( - tmp, - result); - - // - Clean(tmp); - - // - mResult = ArraySize(result); - - // - return mResult; -} - -// -// Retrieve Nearest Period base on Given Period ... -ENUM_TIMEFRAMES GetNearestPeriod(ENUM_TIMEFRAMES mPeriod) -{ - // - ENUM_TIMEFRAMES result = _Period; - - // - mPeriod = NormalizePeriod(mPeriod); - - // - switch (mPeriod) - { - // - case PERIOD_M1: - case PERIOD_M2: - result = PERIOD_M4; - break; - - // - case PERIOD_M3: - case PERIOD_M4: - result = PERIOD_M6; - break; - - // - case PERIOD_M5: - case PERIOD_M6: - case PERIOD_M10: - case PERIOD_M12: - result = PERIOD_M15; - break; - - // - case PERIOD_M15: - case PERIOD_M20: - result = PERIOD_M30; - break; - - // - case PERIOD_H1: - case PERIOD_H2: - case PERIOD_H3: - result = PERIOD_H4; - break; - - // - case PERIOD_H6: - case PERIOD_H8: - result = PERIOD_H12; - break; - - // - case PERIOD_H12: - result = PERIOD_D1; - break; - - // - case PERIOD_D1: - result = PERIOD_W1; - break; - - // - default: - result = PERIOD_MN1; - break; - } - - // - return result; -} - -// -// Retrieve Mediest Period base on Given Period ... -ENUM_TIMEFRAMES GetMediestPeriod(ENUM_TIMEFRAMES mPeriod) -{ - // - ENUM_TIMEFRAMES result = _Period; - - // - mPeriod = NormalizePeriod(mPeriod); - - // - switch (mPeriod) - { - // - case PERIOD_M1: - case PERIOD_M2: - result = PERIOD_M15; - break; - - // - case PERIOD_M3: - case PERIOD_M4: - result = PERIOD_M30; - break; - - // - case PERIOD_M5: - case PERIOD_M6: - case PERIOD_M10: - case PERIOD_M12: - result = PERIOD_H1; - break; - - // - case PERIOD_M15: - case PERIOD_M20: - result = PERIOD_H2; - break; - - // - case PERIOD_H1: - case PERIOD_H2: - case PERIOD_H3: - result = PERIOD_H8; - break; - - // - case PERIOD_H6: - case PERIOD_H8: - result = PERIOD_D1; - break; - - // - case PERIOD_H12: - result = PERIOD_W1; - break; - - // - case PERIOD_D1: - result = PERIOD_MN1; - break; - - // - default: - result = PERIOD_MN1; - break; - } - - // - return result; -} - -// -// Retrieve Longest Period base on Given Period ... -ENUM_TIMEFRAMES GetLongestPeriod(ENUM_TIMEFRAMES mPeriod) -{ - // - ENUM_TIMEFRAMES result = _Period; - - // - mPeriod = NormalizePeriod(mPeriod); - - // - switch (mPeriod) - { - // - case PERIOD_M1: - case PERIOD_M2: - result = PERIOD_M30; - break; - - // - case PERIOD_M3: - case PERIOD_M4: - result = PERIOD_H1; - break; - - // - case PERIOD_M5: - case PERIOD_M6: - case PERIOD_M10: - case PERIOD_M12: - result = PERIOD_H2; - break; - - // - case PERIOD_M15: - case PERIOD_M20: - result = PERIOD_H4; - break; - - // - case PERIOD_H1: - case PERIOD_H2: - case PERIOD_H3: - result = PERIOD_H12; - break; - - // - case PERIOD_H6: - case PERIOD_H8: - result = PERIOD_W1; - break; - - // - case PERIOD_H12: - result = PERIOD_MN1; - break; - - // - case PERIOD_D1: - result = PERIOD_MN1; - break; - - // - default: - result = PERIOD_MN1; - break; - } - - // - return result; -} - -// -// Retrieve Hindmost Period base on Given Period ... -ENUM_TIMEFRAMES GetHindMostPeriod(ENUM_TIMEFRAMES mPeriod) -{ - // - ENUM_TIMEFRAMES result = _Period; - - // - mPeriod = NormalizePeriod(mPeriod); - - // - switch (mPeriod) - { - // - case PERIOD_M1: - case PERIOD_M2: - result = PERIOD_H1; - break; - - // - case PERIOD_M3: - case PERIOD_M4: - result = PERIOD_H2; - break; - - // - case PERIOD_M5: - case PERIOD_M6: - case PERIOD_M10: - case PERIOD_M12: - result = PERIOD_H4; - break; - - // - case PERIOD_M15: - case PERIOD_M20: - result = PERIOD_H8; - break; - - // - case PERIOD_H1: - case PERIOD_H2: - case PERIOD_H3: - result = PERIOD_D1; - break; - - // - case PERIOD_H6: - case PERIOD_H8: - result = PERIOD_MN1; - break; - - // - case PERIOD_H12: - result = PERIOD_MN1; - break; - - // - case PERIOD_D1: - result = PERIOD_MN1; - break; - - // - default: - result = PERIOD_MN1; - break; - } - - // - return result; -} - -// -// Retrieve Specified Cycles Period related to Host Period ... -ENUM_TIMEFRAMES GetCyclePeriod( - ENUM_X_MARKET_CYCLES mCycle = NULL, // Specified Cycle - ENUM_TIMEFRAMES mPeriod = NULL // Host Period -) -{ - // - ENUM_TIMEFRAMES result = NULL; - - // - mPeriod = NormalizePeriod(mPeriod); - mCycle = NormalizeCycle(mCycle); - - // - switch (mCycle) - { - // - // Short ... - case X_MARKET_CYCLE_SHORT: - result = GetNearestPeriod(mPeriod); - break; - - // - // Medium ... - case X_MARKET_CYCLE_MEDIUM: - result = GetMediestPeriod(mPeriod); - break; - - // - // Long ... - case X_MARKET_CYCLE_LONG: - result = GetLongestPeriod(mPeriod); - break; - - // - // Hind ... - case X_MARKET_CYCLE_HIND: - result = GetHindMostPeriod(mPeriod); - break; - } - - // - return result; -} \ No newline at end of file diff --git a/Documents/Pack/V1.0/Source/Libraries/x-saherelm.draw.lib.mq5 b/Documents/Pack/V1.0/Source/Libraries/x-saherelm.draw.lib.mq5 deleted file mode 100644 index cf58a7ac..00000000 --- a/Documents/Pack/V1.0/Source/Libraries/x-saherelm.draw.lib.mq5 +++ /dev/null @@ -1,2476 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Draw Library -// -------------------------------------- -// Name: XDraw -// Description: provides Draw abilities ... -// -// -// Maintainer: -// ------------ -// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) -// -////////////////////////////////////////////////////// -// -// Global Properties ... -#property library -#property copyright "Copyright 2023, SaherElm IT Center" -#property link "https://www.saherelm.ir" -#property version "1.00" -#property strict - -// -// Global Definitions: Variables, Properties and etc ... - -// -// Retrieve Chart Size in Pixel ... -struct XSize -{ - long width; - long height; - - // - int x; - int y; - int w; - int h; - - // - int wStep; - int hStep; -}; - -// -// Define a Draw Specifications ... -struct XDrawSpecifications -{ - // - // Props ... - - // - bool draw; // Draw or Not ... - - // - int width; // Draw Witdth ... - color clr; // Draw Color ... - ENUM_LINE_STYLE style; // Draw Style ... - - // - bool back; // in the background - bool fill; // fill object if supported - bool selection; // highlight to move - bool rayRight; // line's continuation to the right - bool hidden; // hidden in the object list - long zOrder; // priority for mouse click - - // - string label; // Label ... - color labelColor; // Label Color ... - double labelAngel; // Label Angle ... - string labelFont; // Label Font ... - int labelFontSize; // Label Font Size ... - ENUM_ANCHOR_POINT labelAnchor; // Label Anchor Point ... - - // - // Constructor ... - XDrawSpecifications() - { - Clean(); - } - - // - // Operator ... - void operator=(const XDrawSpecifications &value) - { - // - clr = value.clr; - draw = value.draw; - width = value.width; - style = value.style; - - // - back = value.back; - hidden = value.hidden; - zOrder = value.zOrder; - rayRight = value.rayRight; - selection = value.selection; - - // - fill = value.fill; - - // - label = value.label; - labelColor = value.labelColor; - labelAngel = value.labelAngel; - labelFont = value.labelFont; - labelFontSize = value.labelFontSize; - labelAnchor = value.labelAnchor; - } - - // - // Functions ... - - // - void Clean() - { - // - draw = false; - width = 1; - clr = CLR_NONE; - style = STYLE_SOLID; - - // - back = false; - hidden = false; - rayRight = false; - selection = false; - fill = false; - - // - zOrder = 0; - - // - label = ""; - labelColor = CLR_NONE; - labelAngel = 0; - labelFont = "Arial"; - labelFontSize = 20; - labelAnchor = ANCHOR_LEFT_UPPER; - } - - // - void Label( - string mLabel = "", // Label ... - color mLabelColor = CLR_NONE, // Label Color ... - string mLabelFont = "Arial", // Label Font ... - int mLabelFontSize = 20, // Label Font Size ... - ENUM_ANCHOR_POINT mLabelAnchor = ANCHOR_LEFT_UPPER, // Label Anchor Point ... - double mLabelAngel = 0 // Label Angle ... - ) - { - // - label = mLabel; - labelFont = mLabelFont; - labelColor = mLabelColor; - labelAngel = mLabelAngel; - labelAnchor = mLabelAnchor; - labelFontSize = mLabelFontSize; - } -}; - -// -// Candle Draw Specifications ... -struct XOHCLDrawSpecification -{ - // - // Props ... - XDrawSpecifications openStyle; - XDrawSpecifications highStyle; - XDrawSpecifications closeStyle; - XDrawSpecifications lowStyle; - - // - // Constructors ... - XOHCLDrawSpecification() - { - Clean(); - } - - // - // Operators ... - void operator=(const XOHCLDrawSpecification &value) - { - // - lowStyle = value.lowStyle; - openStyle = value.openStyle; - highStyle = value.highStyle; - closeStyle = value.closeStyle; - } - - // - // Functions ... - - // - void Clean() - { - // - lowStyle.Clean(); - openStyle.Clean(); - highStyle.Clean(); - closeStyle.Clean(); - } - - // - void Default() - { - // - // Open ... - openStyle.width = 1; - openStyle.draw = true; - openStyle.clr = clrLime; - openStyle.style = STYLE_SOLID; - openStyle.Label( - "O", - openStyle.clr); - - // - // High ... - highStyle.width = 1; - highStyle.draw = true; - highStyle.clr = clrAqua; - highStyle.style = STYLE_SOLID; - highStyle.Label( - "H", - highStyle.clr); - - // - // Close ... - closeStyle.width = 1; - closeStyle.draw = true; - closeStyle.clr = clrRed; - closeStyle.style = STYLE_SOLID; - closeStyle.Label( - "C", - closeStyle.clr); - - // - // Low ... - lowStyle.width = 1; - lowStyle.draw = true; - lowStyle.clr = clrMagenta; - lowStyle.style = STYLE_SOLID; - lowStyle.Label( - "L", - lowStyle.clr); - } - - // - void Width(int value) - { - // - lowStyle.width = value; - openStyle.width = value; - highStyle.width = value; - closeStyle.width = value; - } - - // - void Style(ENUM_LINE_STYLE value) - { - // - lowStyle.style = value; - openStyle.style = value; - highStyle.style = value; - closeStyle.style = value; - } - - // - void Color(color value) - { - // - lowStyle.clr = value; - openStyle.clr = value; - highStyle.clr = value; - closeStyle.clr = value; - } - - // - void RayRight(bool value) - { - // - lowStyle.rayRight = value; - openStyle.rayRight = value; - highStyle.rayRight = value; - closeStyle.rayRight = value; - } - - // - void Draw(bool value) - { - // - lowStyle.draw = value; - openStyle.draw = value; - highStyle.draw = value; - closeStyle.draw = value; - } - - // - void Back(bool value) - { - // - lowStyle.back = value; - openStyle.back = value; - highStyle.back = value; - closeStyle.back = value; - } - - // - void Fill(bool value) - { - // - lowStyle.fill = value; - openStyle.fill = value; - highStyle.fill = value; - closeStyle.fill = value; - } - - // - void Label(string value) - { - // - lowStyle.Label(value); - openStyle.Label(value); - highStyle.Label(value); - closeStyle.Label(value); - } - - // - void SetLabelPrefix(string value) - { - // - lowStyle.label = value + " " + lowStyle.label; - openStyle.label = value + " " + openStyle.label; - highStyle.label = value + " " + highStyle.label; - closeStyle.label = value + " " + closeStyle.label; - } -}; - -// -string drawPrefix = "X-OBJ"; - -// -// Common Draw Functions ... - -// -// remove drawn objects ... -void RemoveDraws( - string tag = NULL, - long chartId = -1, - int subWindow = -1 // -) -{ - // - // Normalize Args ... - // - if (tag == NULL) - { - tag = drawPrefix; - } - - // - if (chartId == -1) - { - chartId = 0; - } - - // - if (subWindow == -1) - { - subWindow = 0; - } - - // - for (int iObj = ObjectsTotal(chartId, subWindow) - 1; iObj >= 0; iObj--) - { - // - string on = ObjectName(chartId, iObj, subWindow); - if (StringFind(on, tag) >= 0) - { - ObjectDelete(chartId, on); - } - } - - // - // Redraw Chart ... - ChartRedraw(); -} - -// -bool RemoveDraw( - string name, - long chartId = -1, - int subWindow = -1 // -) -{ - // - bool result = false; - - // - if (chartId == -1) - { - chartId = 0; - } - - // - if (subWindow == -1) - { - subWindow = 0; - } - - // - string objName = ""; - for (int iObj = ObjectsTotal(chartId, subWindow) - 1; iObj >= 0; iObj--) - { - // - string on = ObjectName(chartId, iObj, subWindow); - if (StringFind(on, name) >= 0) - { - // - objName = on; - break; - } - } - - // - if (StringLen(objName) > 0) - { - result = ObjectDelete(chartId, objName); - } - - // - return result; -} - -// -// Deselect All Draws ... -void DeselectAllDraws() -{ - // - int objs = ObjectsTotal(ChartID(), 0); - for (int o = 0; o < objs; o++) - { - ObjectSetInteger(ChartID(), ObjectName(ChartID(), o, 0), OBJPROP_SELECTED, false); - } - - // - ChartRedraw(); -} - -// -// Check Object Exists ... -bool IsDrawExists( - string name, - long chartId = -1, - int subWindow = -1 // -) -{ - // - bool result = false; - - // - if (chartId == -1) - { - chartId = 0; - } - - // - if (subWindow == -1) - { - subWindow = 0; - } - - // - for (int iObj = ObjectsTotal(chartId, subWindow) - 1; iObj >= 0; iObj--) - { - // - string on = ObjectName(chartId, iObj, subWindow); - result = StringFind(on, name) >= 0; - if (result) - { - break; - } - } - - // - return result; -} - -// -// Find Specific Object Name ... -string FindObjectName( - string suggest, - long chartId = 0, - int subWindow = 0 // -) -{ - // - string result = NULL; - - // - int objectsCount = ObjectsTotal(chartId, subWindow); - if (objectsCount <= 0) { - return result; - } - - // - for (int i = objectsCount - 1; i >= 0; i--) { - // - string iObjectName = ObjectName(chartId, i, subWindow); - bool isExists = StringFind(iObjectName, suggest) >= 0; - if (isExists) { - // - result = iObjectName; - break; - } - } - - // - return result; -} - -// -// Regular Draws ... - -// -// Arrow Functions ... - -// -// Draw an Arrow Object on Chart ... -bool DrawArrow( - const long chartID = 0, // chart's ID - const string name = "Arrow", // arrow name - const int subWindow = 0, // subwindow index - datetime time = 0, // anchor point time - double price = 0, // anchor point price - const uchar arrowCode = 252, // arrow code - const ENUM_ARROW_ANCHOR anchor = ANCHOR_BOTTOM, // anchor point position - const color clr = clrAqua, // arrow color - const ENUM_LINE_STYLE style = STYLE_SOLID, // border line style - const int width = 3, // arrow size - const bool back = false, // in the background - const bool selection = false, // highlight to move - const bool hidden = false, // hidden in the object list - const long zOrder = 0 // Order Object ... -) -{ - // - bool result = false; - - // - // set anchor point coordinates if they are not set ... - ChangeArrowEmptyPoint(time, price); - - // - // reset the error value ... - ResetLastError(); - - // - // Normalize Name ... - string objName = drawPrefix + "_" + name; - - // - // create an arrow ... - result = ObjectCreate(chartID, objName, OBJ_ARROW, subWindow, time, price); - if (!result) - { - return result; - } - - // - // set the arrow code ... - ObjectSetInteger(chartID, objName, OBJPROP_ARROWCODE, arrowCode); - - // - // set anchor type ... - ObjectSetInteger(chartID, objName, OBJPROP_ANCHOR, anchor); - - // - // set the arrow color ... - ObjectSetInteger(chartID, objName, OBJPROP_COLOR, clr); - - // - // set the border line style ... - ObjectSetInteger(chartID, objName, OBJPROP_STYLE, style); - - // - // set the arrow's size ... - ObjectSetInteger(chartID, objName, OBJPROP_WIDTH, width); - - // - // display in the foreground false or background true ... - ObjectSetInteger(chartID, objName, OBJPROP_BACK, back); - - // - // enable true or disable false the mode of moving the arrow by mouse - // when creating a graphical object using ObjectCreate function, the object cannot be - // highlighted and moved by default. Inside this method, selection parameter - // is false by default, if you want making it possible to highlight and move the object - // change it to true ... - ObjectSetInteger(chartID, objName, OBJPROP_SELECTABLE, true); - ObjectSetInteger(chartID, objName, OBJPROP_SELECTED, selection); - - // - // hide true or display false graphical object name in the object list ... - ObjectSetInteger(chartID, objName, OBJPROP_HIDDEN, hidden); - - // - // set the priority for receiving the event of a mouse click in the chart ... - ObjectSetInteger(chartID, objName, OBJPROP_ZORDER, zOrder); - - // - // successful execution ... - return result; -} - -// -// Move the anchor point of Arrow ... -bool MoveArrow( - const long chartID = 0, // chart's ID - const string name = "Arrow", // object name - datetime time = 0, // anchor point time coordinate - double price = 0 // anchor point price coordinate -) -{ - // - bool result = false; - - // - // if point position is not set, move it to the current bar having Bid price ... - if (!time) - { - time = TimeCurrent(); - } - - // - if (!price) - { - price = SymbolInfoDouble(_Symbol, SYMBOL_BID); - } - - // - // move the anchor point ... - result = ObjectMove(chartID, name, 0, time, price); - - // - return result; -} - -// -// Delete an arrow ... -bool DeleteArrow( - const long chartID = 0, // chart's ID - const string name = "Arrow" // arrow name -) -{ - // - bool result = false; - - // - // delete an arrow ... - result = !ObjectDelete(chartID, name); - - // - return result; -} - -// -// Change the arrow code ... -bool ArrowCodeChange( - const long chartID = 0, // chart's ID - const string name = "Arrow", // object name - const uchar code = 252 // arrow code -) -{ - // - bool result = false; - - // - // change the arrow code ... - result = ObjectSetInteger(chartID, name, OBJPROP_ARROWCODE, code); - - // - return result; -} - -// -// Change anchor type ... -bool ArrowAnchorChange( - const long chartID = 0, // chart's ID - const string name = "Arrow", // object name - const ENUM_ARROW_ANCHOR anchor = ANCHOR_TOP // anchor type -) -{ - // - bool result = false; - - // - // change anchor type ... - result = !ObjectSetInteger(chartID, name, OBJPROP_ANCHOR, anchor); - - // - return result; -} - -// -// Check anchor point values and set default values -// for empty ones ... -void ChangeArrowEmptyPoint( - datetime &time, - double &price // -) -{ - // - // if the point's time is not set, it will be on the current bar ... - if (!time) - { - time = TimeCurrent(); - } - - // - // if the point's price is not set, it will have Bid value ... - if (!price) - { - price = SymbolInfoDouble(_Symbol, SYMBOL_BID); - } -} - -// -// Horizontal Line Functions ... - -// -// Create, Draw the horizontal line ... -bool DrawHorizontalLine( - const long chartID = 0, // chart's ID - const string name = "HLine", // line name - const int subWindow = 0, // subwindow index - double price = 0, // line price - const color clr = clrRed, // line color - const ENUM_LINE_STYLE style = STYLE_SOLID, // line style - const int width = 1, // line width - const bool back = false, // in the background - const bool selection = false, // highlight to move - const bool hidden = false, // hidden in the object list - const long zOrder = 0 // priority for mouse click -) -{ - // - bool result = false; - - // - // if the price is not set, set it at the current Bid price level ... - if (!price) - { - price = SymbolInfoDouble(Symbol(), SYMBOL_BID); - } - - // - // Normalize Name ... - string objName = drawPrefix + "_" + name; - - // - // create a horizontal line ... - result = ObjectCreate(chartID, objName, OBJ_HLINE, subWindow, 0, price); - if (!result) - { - return result; - } - - // - // set line color ... - ObjectSetInteger(chartID, objName, OBJPROP_COLOR, clr); - - // - // set line display style ... - ObjectSetInteger(chartID, objName, OBJPROP_STYLE, style); - - // - // set line width ... - ObjectSetInteger(chartID, objName, OBJPROP_WIDTH, width); - - // - // display in the foreground false or background true ... - ObjectSetInteger(chartID, objName, OBJPROP_BACK, back); - - // - // enable true or disable false the mode of moving the line by mouse - // when creating a graphical object using ObjectCreate function, the object cannot be - // highlighted and moved by default. Inside this method, selection parameter - // is true by default making it possible to highlight and move the object - ObjectSetInteger(chartID, objName, OBJPROP_SELECTABLE, selection); - ObjectSetInteger(chartID, objName, OBJPROP_SELECTED, selection); - - // - // hide true or display false graphical object name in the object list ... - ObjectSetInteger(chartID, objName, OBJPROP_HIDDEN, hidden); - - // - // set the priority for receiving the event of a mouse click in the chart ... - ObjectSetInteger(chartID, objName, OBJPROP_ZORDER, zOrder); - - // - // successful execution ... - return result; -} - -// -// Move horizontal line ... -bool MoveHorizontalLine( - const long chartID = 0, // chart's ID - const string name = "HLine", // line name - double price = 0 // line price -) -{ - // - bool result = false; - - // - // if the line price is not set, move it to the current Bid price level ... - if (!price) - { - price = SymbolInfoDouble(Symbol(), SYMBOL_BID); - } - - // - // move a horizontal line ... - result = ObjectMove(chartID, name, 0, 0, price); - - // - return result; -} - -// -// Delete a horizontal line ... -bool DeleteHorizontalLine( - const long chartID = 0, // chart's ID - const string name = "HLine" // line name -) -{ - // - bool result = false; - - // - // delete a horizontal line ... - result = ObjectDelete(chartID, name); - - // - return result; -} - -// -// Vertical Line Functions ... - -// -// Create the vertical line ... -bool DrawVerticalLine( - const long chartID = 0, // chart's ID - const string name = "VLine", // line name - const int subWindow = 0, // subwindow index - datetime time = 0, // line time - const color clr = clrRed, // line color - const ENUM_LINE_STYLE style = STYLE_SOLID, // line style - const int width = 1, // line width - const bool back = false, // in the background - const bool selection = false, // highlight to move - const bool hidden = false, // hidden in the object list - const long zOrder = 0 // priority for mouse click -) -{ - // - bool result = false; - - // - // if the line time is not set, draw it via the last bar ... - if (!time) - { - time = TimeCurrent(); - } - - // - // Normalize Name ... - string objName = drawPrefix + "_" + name; - - // - // create a vertical line ... - result = ObjectCreate(chartID, objName, OBJ_VLINE, subWindow, time, 0); - if (!result) - { - return result; - } - - // - // set line color ... - ObjectSetInteger(chartID, objName, OBJPROP_COLOR, clr); - - // - // set line display style ... - ObjectSetInteger(chartID, objName, OBJPROP_STYLE, style); - - // - // set line width ... - ObjectSetInteger(chartID, objName, OBJPROP_WIDTH, width); - - // - // display in the foreground false or background true ... - ObjectSetInteger(chartID, objName, OBJPROP_BACK, back); - - // - // enable true or disable false the mode of moving the line by mouse - // when creating a graphical object using ObjectCreate function, the object cannot be - // highlighted and moved by default. Inside this method, selection parameter - // is true by default making it possible to highlight and move the object ... - ObjectSetInteger(chartID, objName, OBJPROP_SELECTABLE, true); - ObjectSetInteger(chartID, objName, OBJPROP_SELECTED, selection); - - // - // hide true or display false graphical object name in the object list ... - ObjectSetInteger(chartID, objName, OBJPROP_HIDDEN, hidden); - - // - // set the priority for receiving the event of a mouse click in the chart - ObjectSetInteger(chartID, objName, OBJPROP_ZORDER, zOrder); - - // - // successful execution ... - return result; -} - -// -// Move the vertical line ... -bool MoveVerticalLine( - const long chartID = 0, // chart's ID - const string name = "VLine", // line name - datetime time = 0 // line time -) -{ - // - bool result = false; - - // - // if line time is not set, move the line to the last bar ... - if (!time) - { - time = TimeCurrent(); - } - - // - // move the vertical line ... - result = ObjectMove(chartID, name, 0, time, 0); - - // - return result; -} - -// -// Delete the vertical line ... -bool DeleteVerticalLine( - const long chartID = 0, // chart's ID - const string name = "VLine" // line name -) -{ - // - bool result = false; - - // - // delete the vertical line ... - result = ObjectDelete(chartID, name); - - // - return result; -} - -// -// Rectangle Functions ... - -// -// Create rectangle by the given coordinates ... -bool DrawRectangle( - const long chartID = 0, // chart's ID - const string name = "Rectangle", // rectangle name - const int subWindow = 0, // subwindow index - datetime time1 = 0, // first point time - double price1 = 0, // first point price - datetime time2 = 0, // second point time - double price2 = 0, // second point price - const color clr = clrRed, // rectangle color - const ENUM_LINE_STYLE style = STYLE_SOLID, // style of rectangle lines - const int width = 1, // width of rectangle lines - const bool fill = false, // filling rectangle with color - const bool back = false, // in the background - const bool selection = true, // highlight to move - const bool hidden = true, // hidden in the object list - const long zOrder = 0 // priority for mouse click -) -{ - // - bool result = false; - - // - // Set anchor points' coordinates if they are not set ... - ChangeRectangleEmptyPoints(time1, price1, time2, price2); - - // - // Create a rectangle by the given coordinates ... - result = ObjectCreate(chartID, name, OBJ_RECTANGLE, subWindow, time1, price1, time2, price2); - if (!result) - { - return result; - } - - // - // Set rectangle color ... - ObjectSetInteger(chartID, name, OBJPROP_COLOR, clr); - - // - // Set the style of rectangle lines - ObjectSetInteger(chartID, name, OBJPROP_STYLE, style); - - // - // Set width of the rectangle lines ... - ObjectSetInteger(chartID, name, OBJPROP_WIDTH, width); - - // - // Enable (true) or disable (false) the mode of filling the rectangle ... - ObjectSetInteger(chartID, name, OBJPROP_FILL, fill); - - // - // Display in the foreground (false) or background (true) ... - ObjectSetInteger(chartID, name, OBJPROP_BACK, back); - - // - // Enable (true) or disable (false) the mode of highlighting the rectangle for moving - // when creating a graphical object using ObjectCreate function, the object cannot be - // highlighted and moved by default. Inside this method, selection parameter - // is true by default making it possible to highlight and move the object - ObjectSetInteger(chartID, name, OBJPROP_SELECTABLE, selection); - - // - ObjectSetInteger(chartID, name, OBJPROP_SELECTED, selection); - - // - // Hide (true) or display (false) graphical object name in the object list ... - ObjectSetInteger(chartID, name, OBJPROP_HIDDEN, hidden); - - // - // Set the priority for receiving the event of a mouse click in the chart ... - ObjectSetInteger(chartID, name, OBJPROP_ZORDER, zOrder); - - // - // Successful execution - return result; -} - -// -// Move the rectangle anchor point ...s -bool RectanglePointChange( - const long chartID = 0, // chart's ID - const string name = "Rectangle", // rectangle name - const int pointIndex = 0, // anchor point index - datetime time = 0, // anchor point time coordinate - double price = 0 // anchor point price coordinate -) -{ - // - bool result = false; - - // - // if point position is not set, move it to the current bar having Bid price ... - if (!time) - { - time = TimeCurrent(); - } - - // - if (!price) - { - price = SymbolInfoDouble(Symbol(), SYMBOL_BID); - } - - // - // Move the anchor point ... - result = ObjectMove(chartID, name, pointIndex, time, price); - - // - return result; -} - -// -// Delete the rectangle ... -bool DeleteRectangle( - const long chartID = 0, // chart's ID - const string name = "Rectangle" // rectangle name -) -{ - // - bool result = false; - - // - result = ObjectDelete(chartID, name); - - // - return result; -} - -// -// Check the values of rectangle's anchor points and set default -// values for empty ones -void ChangeRectangleEmptyPoints( - datetime &time1, double &price1, - datetime &time2, double &price2 // -) -{ - // - // if the first point's time is not set, it will be on the current bar ... - if (!time1) - { - time1 = TimeCurrent(); - } - - // - // if the first point's price is not set, it will have Bid value ... - if (!price1) - { - price1 = SymbolInfoDouble(Symbol(), SYMBOL_BID); - } - - // - // if the second point's time is not set, it is located 9 bars left from the second one ... - if (!time2) - { - // - // array for receiving the open time of the last 10 bars ... - datetime temp[10]; - CopyTime(Symbol(), Period(), time1, 10, temp); - - // - // set the second point 9 bars left from the first one ... - time2 = temp[0]; - } - - // - // if the second point's price is not set, move it 300 points lower than the first one ... - if (!price2) - { - price2 = price1 - 300 * SymbolInfoDouble(Symbol(), SYMBOL_POINT); - } -} - -// -// RectangleLabel Functions ... - -// -// Create Rectangle Label Object ... -bool DrawRectangleLabel( - const long chartID = 0, // chart's ID - const string name = "RectLabel", // label name - const int subWindow = 0, // subwindow index - const int x = 0, // X coordinate - const int y = 0, // Y coordinate - const int width = 50, // width - const int height = 18, // height - const color bgColor = clrWhiteSmoke, // background color - const ENUM_BORDER_TYPE border = BORDER_SUNKEN, // border type - const ENUM_BASE_CORNER corner = CORNER_LEFT_UPPER, // chart corner for anchoring - const color clr = clrRed, // flat border color (Flat) - const ENUM_LINE_STYLE style = STYLE_SOLID, // flat border style - const int lineWidth = 1, // flat border width - const bool back = false, // in the background - const bool selection = false, // highlight to move - const bool hidden = false, // hidden in the object list - const long zOrder = 0 // priority for mouse click -) -{ - // - bool result = false; - - // - // Normalize Name ... - string objName = drawPrefix + "_" + name; - - // - // create a rectangle label - result = ObjectCreate(chartID, objName, OBJ_RECTANGLE_LABEL, subWindow, 0, 0); - if (!result) - { - return result; - } - - // - // set label coordinates ... - ObjectSetInteger(chartID, objName, OBJPROP_XDISTANCE, x); - ObjectSetInteger(chartID, objName, OBJPROP_YDISTANCE, y); - - // - // set label size ... - ObjectSetInteger(chartID, objName, OBJPROP_XSIZE, width); - ObjectSetInteger(chartID, objName, OBJPROP_YSIZE, height); - - // - // set background color ... - ObjectSetInteger(chartID, objName, OBJPROP_BGCOLOR, bgColor); - - // - // set border type ... - ObjectSetInteger(chartID, objName, OBJPROP_BORDER_TYPE, border); - - // - // set the chart's corner, relative to which point coordinates are defined ... - ObjectSetInteger(chartID, objName, OBJPROP_CORNER, corner); - - // - // set flat border color (in Flat mode) ... - ObjectSetInteger(chartID, objName, OBJPROP_COLOR, clr); - - // - // set flat border line style ... - ObjectSetInteger(chartID, objName, OBJPROP_STYLE, style); - - // - // set flat border width ... - ObjectSetInteger(chartID, objName, OBJPROP_WIDTH, lineWidth); - - // - // display in the foreground false or background true ... - ObjectSetInteger(chartID, objName, OBJPROP_BACK, back); - - // - // enable true or disable false the mode of moving the label by mouse ... - ObjectSetInteger(chartID, objName, OBJPROP_SELECTABLE, selection); - ObjectSetInteger(chartID, objName, OBJPROP_SELECTED, selection); - - // - // hide true or display false graphical object name in the object list ... - ObjectSetInteger(chartID, objName, OBJPROP_HIDDEN, hidden); - - // - // set the priority for receiving the event of a mouse click in the chart ... - ObjectSetInteger(chartID, objName, OBJPROP_ZORDER, zOrder); - - // - // successful execution ... - return result; -} - -// -// Move Rectangle Label .. -bool MoveRectangleLabel( - const long chartID = 0, // chart's ID - const string name = "RectLabel", // label name - const int x = 0, // X coordinate - const int y = 0 // Y coordinate -) -{ - // - bool result = false; - - // - // move the rectangle label ... - result = ObjectSetInteger(chartID, name, OBJPROP_XDISTANCE, x); - if (!result) - { - return result; - } - - // - result = ObjectSetInteger(chartID, name, OBJPROP_YDISTANCE, y); - - // - return result; -} - -// -// Delete the rectangle label ... -bool DeleteRectangleLabel( - const long chartID = 0, // chart's ID - const string name = "RectLabel" // label name -) -{ - // - bool result = false; - - // - // delete the label ... - result = ObjectDelete(chartID, name); - - // - return result; -} - -// -// Change Rectangle Label Size ... -bool ChangeSizeRectangleLabel( - const long chartID = 0, // chart's ID - const string name = "RectLabel", // label name - const int width = 50, // label width - const int height = 18 // label height -) -{ - // - bool result = false; - - // - // change label size ... - result = ObjectSetInteger(chartID, name, OBJPROP_XSIZE, width); - if (!result) - { - return result; - } - - // - result = ObjectSetInteger(chartID, name, OBJPROP_YSIZE, height); - - // - return result; -} - -// -// Change rectangle label border type ... -bool RectLabelChangeBorderType( - const long chartID = 0, // chart's ID - const string name = "RectLabel", // label name - const ENUM_BORDER_TYPE border = BORDER_SUNKEN // border type -) -{ - // - bool result = false; - - // - // change border type ... - result = ObjectSetInteger(chartID, name, OBJPROP_BORDER_TYPE, border); - - // - return result; -} - -// -// TrendLine Funcions ... - -// -// Create a trend line by the given coordinates ... -bool DrawTrendLine( - const long chartID = 0, // chart's ID - const string name = "TrendLine", // line name - const int subWindow = 0, // subwindow index - datetime time1 = 0, // first point time - double price1 = 0, // first point price - datetime time2 = 0, // second point time - double price2 = 0, // second point price - const color clr = clrYellow, // line color - const ENUM_LINE_STYLE style = STYLE_SOLID, // line style - const int width = 1, // line width - const bool back = false, // in the background - const bool selection = false, // highlight to move - const bool rayRight = false, // line's continuation to the right - const bool hidden = false, // hidden in the object list - const long zOrder = 0 // priority for mouse click -) -{ - // - bool result = false; - - // - // set anchor points' coordinates if they are not set ... - ChangeTrendLineEmptyPoints( - time1, - price1, - time2, - price2); - - // - // Normalize Name ... - string objName = drawPrefix + "_" + name; - - // - // create a trend line by the given coordinates ... - result = ObjectCreate(chartID, objName, OBJ_TREND, subWindow, time1, price1, time2, price2); - if (!result) - { - return result; - } - - // - // set line color ... - ObjectSetInteger(chartID, objName, OBJPROP_COLOR, clr); - - // - // set line display style ... - ObjectSetInteger(chartID, objName, OBJPROP_STYLE, style); - - // - // set line width ... - ObjectSetInteger(chartID, objName, OBJPROP_WIDTH, width); - - // - // display in the foreground false or background true ... - ObjectSetInteger(chartID, objName, OBJPROP_BACK, back); - - // - // enable true or disable false the mode of moving the line by mouse - // when creating a graphical object using ObjectCreate function, the object cannot be - // highlighted and moved by default. Inside this method, selection parameter - // is true by default making it possible to highlight and move the object ... - ObjectSetInteger(chartID, objName, OBJPROP_SELECTABLE, true); - ObjectSetInteger(chartID, objName, OBJPROP_SELECTED, selection); - - // - // enable true or disable false the mode of continuation of the line's display to the right ... - ObjectSetInteger(chartID, objName, OBJPROP_RAY_RIGHT, rayRight); - - // - // hide true or display false graphical object name in the object list ... - ObjectSetInteger(chartID, objName, OBJPROP_HIDDEN, hidden); - - // - // set the priority for receiving the event of a mouse click in the chart ... - ObjectSetInteger(chartID, objName, OBJPROP_ZORDER, zOrder); - - // - // successful execution ... - return result; -} - -// -// Move trend line anchor point ... | -bool ChangeTrendLinePoint( - const long chartID = 0, // chart's ID - const string name = "TrendLine", // line name - const int pointindex = 0, // anchor point index - datetime time = 0, // anchor point time coordinate - double price = 0 // anchor point price coordinate -) -{ - // - bool result = false; - - // - // if point position is not set, move it to the current bar having Bid price ... - if (!time) - { - time = TimeCurrent(); - } - - // - if (!price) - { - price = SymbolInfoDouble(Symbol(), SYMBOL_BID); - } - - // - // move trend line's anchor point ... - result = ObjectMove(chartID, name, pointindex, time, price); - - // - return result; -} - -// -// The function deletes the trend line from the chart ... -bool DeleteTrendLine( - const long chartID = 0, // chart's ID - const string name = "TrendLine" // line name -) -{ - // - bool result = false; - - // - // delete a trend line ... - result = ObjectDelete(chartID, name); - - // - return result; -} - -// -// Check the values of trend line's anchor points and set default ... -// values for empty ones ... -void ChangeTrendLineEmptyPoints( - datetime &time1, - double &price1, - datetime &time2, - double &price2 // -) -{ - // - // if the first point's time is not set, it will be on the current bar ... - if (!time1) - { - time1 = TimeCurrent(); - } - - // - // if the first point's price is not set, it will have Bid value ... - if (!price1) - { - price1 = SymbolInfoDouble(Symbol(), SYMBOL_BID); - } - - // - // if the second point's time is not set, it is located 9 bars left from the second one ... - if (!time2) - { - // - // array for receiving the open time of the last 10 bars ... - datetime temp[10]; - CopyTime(Symbol(), Period(), time1, 10, temp); - - // - // set the second point 9 bars left from the first one ... - time2 = temp[0]; - } - - // - // if the second point's price is not set, it is equal to the first point's one ... - if (!price2) - { - price2 = price1; - } -} - -// -// Text Functions ... - -// -// Create and Draw a Text Object ... -bool DrawText( - const long chartID = 0, // chart's ID - const string name = "Text", // object name - const int subWindow = 0, // subwindow index - datetime time = 0, // anchor point time - double price = 0, // anchor point price - const string text = "Text", // the text itself - const string font = "Arial", // font - const int fontSize = 10, // font size - const color clr = clrRed, // color - const double angle = 0.0, // text slope - const ENUM_ANCHOR_POINT anchor = ANCHOR_CENTER, // anchor type - const bool back = false, // in the background - const bool selection = false, // highlight to move - const bool hidden = true, // hidden in the object list - const long zOrder = 0 // priority for mouse click -) -{ - // - bool result = false; - - // - // set anchor point coordinates if they are not set ... - ChangeTextEmptyPoint(time, price); - - // - // Normalize Name ... - string objName = drawPrefix + "_" + name; - - // - // - // create Text object - result = ObjectCreate(chartID, objName, OBJ_TEXT, subWindow, time, price); - if (!result) - { - return result; - } - - // - // set the text ... - ObjectSetString(chartID, objName, OBJPROP_TEXT, text); - - // - // set text font ... - ObjectSetString(chartID, objName, OBJPROP_FONT, font); - - // - // set font size ... - ObjectSetInteger(chartID, objName, OBJPROP_FONTSIZE, fontSize); - - // - // set the slope angle of the text ... - ObjectSetDouble(chartID, objName, OBJPROP_ANGLE, angle); - - // - // set anchor type ... - ObjectSetInteger(chartID, objName, OBJPROP_ANCHOR, anchor); - - // - // set color ... - ObjectSetInteger(chartID, objName, OBJPROP_COLOR, clr); - - // - // display in the foreground false or background true ... - ObjectSetInteger(chartID, objName, OBJPROP_BACK, back); - - // - // enable true or disable false the mode of moving the object by mouse ... - ObjectSetInteger(chartID, objName, OBJPROP_SELECTABLE, true); - ObjectSetInteger(chartID, objName, OBJPROP_SELECTED, selection); - - // - // hide true or display false graphical object name in the object list ... - ObjectSetInteger(chartID, objName, OBJPROP_HIDDEN, hidden); - - // - // set the priority for receiving the event of a mouse click in the chart ... - ObjectSetInteger(chartID, objName, OBJPROP_ZORDER, zOrder); - - // - // successful execution ... - return result; -} - -// -// Move the anchor point ... -bool MoveText( - const long chartID = 0, // chart's ID - const string name = "Text", // object name - datetime time = 0, // anchor point time coordinate - double price = 0 // anchor point price coordinate -) -{ - // - bool result = false; - - // - // - // if point position is not set, move it to the current bar having Bid price - if (!time) - { - time = TimeCurrent(); - } - - // - if (!price) - { - price = SymbolInfoDouble(_Symbol, SYMBOL_BID); - } - - // - // move the anchor point ... - result = ObjectMove(chartID, name, 0, time, price); - - // - return result; -} - -// -// Change the object text ... -bool ChangeText( - const long chartID = 0, // chart's ID - const string name = "Text", // object name - const string text = "Text" // text -) -{ - // - bool result = false; - - // - // change object text ... - result = ObjectSetString(chartID, name, OBJPROP_TEXT, text); - - // - return result; -} - -// -// Delete Text object ... -bool DeleteText( - const long chartID = 0, // chart's ID - const string name = "Text" // object name -) -{ - // - bool result = false; - - // - // delete the object ... - result = ObjectDelete(chartID, name); - - // - return result; -} - -// -// Check anchor point values and set default values -// for empty ones ... -void ChangeTextEmptyPoint( - datetime &time, - double &price // -) -{ - // - // if the point's time is not set, it will be on the current bar ... - if (!time) - { - time = TimeCurrent(); - } - - // - // if the point's price is not set, it will have Bid value ... - if (!price) - { - price = SymbolInfoDouble(_Symbol, SYMBOL_BID); - } -} - -// -// Fibonacchi Functions ... - -// -// Create Fibonacci Retracement by the given coordinates ... -bool DrawFibonacci( - const long chartID = 0, // chart's ID - const string name = "Fibonacci", // object name - const int subWindow = 0, // subwindow index - datetime time1 = 0, // first point time - double price1 = 0, // first point price - datetime time2 = 0, // second point time - double price2 = 0, // second point price - const color clr = clrRed, // object color - const ENUM_LINE_STYLE style = STYLE_SOLID, // object line style - const int width = 1, // object line width - const bool back = false, // in the background - const bool selection = true, // highlight to move - const bool rayRight = false, // object's continuation to the right - const bool hidden = true, // hidden in the object list - const long zOrder = 0 // priority for mouse click -) -{ - // - bool result = false; - - // - // set anchor points' coordinates if they are not set ... - ChangeFibonacciEmptyPoints(time1, price1, time2, price2); - - // - // Normalize Name ... - string objName = drawPrefix + "_" + name; - - // - // Create Fibonacci Retracement by the given coordinates ... - result = ObjectCreate(chartID, objName, OBJ_FIBO, subWindow, time1, price1, time2, price2); - if (!result) - { - return result; - } - - // - // set color ... - ObjectSetInteger(chartID, objName, OBJPROP_COLOR, clr); - - // - // set line style ... - ObjectSetInteger(chartID, objName, OBJPROP_STYLE, style); - - // - // set line width ... - ObjectSetInteger(chartID, objName, OBJPROP_WIDTH, width); - - // - // display in the foreground false or background true ... - ObjectSetInteger(chartID, objName, OBJPROP_BACK, back); - - // - // enable true or disable false the mode of highlighting the channel for moving - // when creating a graphical object using ObjectCreate function, the object cannot be - // highlighted and moved by default. Inside this method, selection parameter - // is true by default making it possible to highlight and move the object ... - ObjectSetInteger(chartID, objName, OBJPROP_SELECTABLE, true); - ObjectSetInteger(chartID, objName, OBJPROP_SELECTED, selection); - - // - // enable true or disable false the mode of continuation of the object's display to the right ... - ObjectSetInteger(chartID, objName, OBJPROP_RAY_RIGHT, rayRight); - - // - // hide true or display false graphical object name in the object list ... - ObjectSetInteger(chartID, objName, OBJPROP_HIDDEN, hidden); - - // - // set the priority for receiving the event of a mouse click in the chart ... - ObjectSetInteger(chartID, objName, OBJPROP_ZORDER, zOrder); - - // - // successful execution ... - return result; -} - -// -// Create Fibonacci Retracement by the given coordinates ... -bool DrawCustomFibonacci( - // - int levels, // number of level lines - double &values[], // values of level lines - color &colors[], // color of level lines - ENUM_LINE_STYLE &styles[], // style of level lines - int &widths[], // width of level lines - string &descriptions[], // level Descriptions - // - const long chartID = 0, // chart's ID - const string name = "Fibonacci", // object name - const int subWindow = 0, // subwindow index - datetime time1 = 0, // first point time - double price1 = 0, // first point price - datetime time2 = 0, // second point time - double price2 = 0, // second point price - const color clr = clrAqua, // object color - const ENUM_LINE_STYLE style = STYLE_DOT, // object line style - const int width = 1, // object line width - const bool back = false, // in the background - const bool selection = true, // highlight to move - const bool rayRight = false, // object's continuation to the right - const bool hidden = true, // hidden in the object list - const long zOrder = 0 // priority for mouse click -) -{ - // - bool result = false; - - // - // set anchor points' coordinates if they are not set ... - ChangeFibonacciEmptyPoints(time1, price1, time2, price2); - - // - // Normalize Name ... - string objName = drawPrefix + "_" + name; - - // - // Create Fibonacci Retracement by the given coordinates ... - result = ObjectCreate(chartID, name, OBJ_FIBO, subWindow, time1, price1, time2, price2); - if (!result) - { - return result; - } - - // - // set color ... - ObjectSetInteger(chartID, objName, OBJPROP_COLOR, clr); - - // - // set line style ... - ObjectSetInteger(chartID, objName, OBJPROP_STYLE, style); - - // - // set line width ... - ObjectSetInteger(chartID, objName, OBJPROP_WIDTH, width); - - // - // display in the foreground false or background true ... - ObjectSetInteger(chartID, objName, OBJPROP_BACK, back); - - // - // enable true or disable false the mode of highlighting the channel for moving - // when creating a graphical object using ObjectCreate function, the object cannot be - // highlighted and moved by default. Inside this method, selection parameter - // is true by default making it possible to highlight and move the object ... - ObjectSetInteger(chartID, objName, OBJPROP_SELECTABLE, true); - ObjectSetInteger(chartID, objName, OBJPROP_SELECTED, selection); - - // - // enable true or disable false the mode of continuation of the object's display to the right ... - ObjectSetInteger(chartID, objName, OBJPROP_RAY_RIGHT, rayRight); - - // - // hide true or display false graphical object name in the object list ... - ObjectSetInteger(chartID, objName, OBJPROP_HIDDEN, hidden); - - // - // set the priority for receiving the event of a mouse click in the chart ... - ObjectSetInteger(chartID, objName, OBJPROP_ZORDER, zOrder); - - // - // Change Levels Of Fibonacci ... - result = FibonacciLevelsSet( - levels, - values, - colors, - styles, - widths, - descriptions, - chartID, - objName); - - // - // successful execution ... - return result; -} - -// -// Set number of levels and their parameters ... -bool FibonacciLevelsSet( - int levels, // number of level lines - double &values[], // values of level lines - color &colors[], // color of level lines - ENUM_LINE_STYLE &styles[], // style of level lines - int &widths[], // width of level lines - string &descriptions[], // level Descriptions - const long chartID = 0, // chart's ID - const string name = "Fibonacci" // object name -) -{ - // - bool result = false; - - // - // check array sizes ... - result = levels == ArraySize(colors) && - levels == ArraySize(styles) && - levels == ArraySize(widths) && - levels == ArraySize(widths); - if (!result) - { - return result; - } - - // - // set the number of levels ... - ObjectSetInteger(chartID, name, OBJPROP_LEVELS, levels); - - // - // set the properties of levels in the loop ... - for (int i = 0; i < levels; i++) - { - // - // level value ... - ObjectSetDouble(chartID, name, OBJPROP_LEVELVALUE, i, values[i]); - - // - // level color ... - ObjectSetInteger(chartID, name, OBJPROP_LEVELCOLOR, i, colors[i]); - - // - // level style ... - ObjectSetInteger(chartID, name, OBJPROP_LEVELSTYLE, i, styles[i]); - - // - // level width ... - ObjectSetInteger(chartID, name, OBJPROP_LEVELWIDTH, i, widths[i]); - - // - // level description ... - // ObjectSetString(chartID, name, OBJPROP_LEVELTEXT, i, DoubleToString(100 * values[i], 1)); - ObjectSetString(chartID, name, OBJPROP_LEVELTEXT, i, descriptions[i]); - } - - // - // successful execution ... - return result; -} - -// -// Move Fibonacci Retracement anchor point ... -bool FibonacciPointChange( - const long chartID = 0, // chart's ID - const string name = "Fibonacci", // object name - const int pointIndex = 0, // anchor point index - datetime time = 0, // anchor point time coordinate - double price = 0 // anchor point price coordinate -) -{ - // - bool result = false; - - // - // if point position is not set, move it to the current bar having Bid price ... - if (!time) - { - time = TimeCurrent(); - } - - // - if (!price) - { - price = SymbolInfoDouble(_Symbol, SYMBOL_BID); - } - - // - // move the anchor point ... - result = ObjectMove(chartID, name, pointIndex, time, price); - - // - return result; -} - -// -// Delete Fibonacci Retracement ... -bool DeleteFibonachi( - const long chartID = 0, // chart's ID - const string name = "Fibonacci" // object name -) -{ - // - bool result = false; - - // - // delete the object ... - result = ObjectDelete(chartID, name); - - // - return result; -} - -// -// Check the values of Fibonacci Retracement anchor points and set -// default values for empty ones ... -void ChangeFibonacciEmptyPoints( - datetime &time1, - double &price1, - datetime &time2, - double &price2 // -) -{ - // - // if the second point's time is not set, it will be on the current bar ... - if (!time2) - { - time2 = TimeCurrent(); - } - - // - // if the second point's price is not set, it will have Bid value ... - if (!price2) - { - price2 = SymbolInfoDouble(_Symbol, SYMBOL_BID); - } - - // - // if the first point's time is not set, it is located 9 bars left from the second one ... - if (!time1) - { - // - // array for receiving the open time of the last 10 bars ... - datetime temp[10]; - CopyTime(Symbol(), Period(), time2, 10, temp); - - // - // set the first point 9 bars left from the second one ... - time1 = temp[0]; - } - - // - // if the first point's price is not set, move it 200 points below the second one ... - if (!price1) - { - price1 = price2 - 200 * SymbolInfoDouble(_Symbol, SYMBOL_POINT); - } -} - -// -// Event Functions ... - -// -// Create an Event ... -bool EventCreate( - const long chartID = 0, // chart's ID - const string name = "Event", // object name - const int subWindow = 0, // subwindow index - const string text = "Content", // event text - datetime time = 0, // anchor point time - const color clr = clrRed, // color - const int width = 1, // point width when highlighted - const bool back = false, // in the background - const bool selection = false, // highlight to move - const bool hidden = true, // hidden in the object list - const long zOrder = 0 // priority for mouse click -) -{ - // - bool result = false; - - // - if (!time) - { - time = TimeCurrent(); - } - - // - result = ObjectCreate(chartID, name, OBJ_EVENT, subWindow, time, 0); - if (!result) - { - return result; - } - - // - // set event text - ObjectSetString(chartID, name, OBJPROP_TEXT, text); - - // - // set color - ObjectSetInteger(chartID, name, OBJPROP_COLOR, clr); - - // - // set anchor point width if the object is highlighted - ObjectSetInteger(chartID, name, OBJPROP_WIDTH, width); - - // - // display in the foreground false or background true - ObjectSetInteger(chartID, name, OBJPROP_BACK, back); - - // - // enable true or disable false the mode of moving event by mouse - ObjectSetInteger(chartID, name, OBJPROP_SELECTABLE, selection); - ObjectSetInteger(chartID, name, OBJPROP_SELECTED, selection); - - // - // hide true or display false graphical object name in the object list - ObjectSetInteger(chartID, name, OBJPROP_HIDDEN, hidden); - - // - // set the priority for receiving the event of a mouse click in the chart - ObjectSetInteger(chartID, name, OBJPROP_ZORDER, zOrder); - - // - // successful execution - return result; -} - -// -// Change Event object text -bool EventTextChange( - const long chartID = 0, // chart's ID - const string name = "Event", // event name - const string text = "Content" // text -) -{ - // - bool result = false; - - // - // change object text - result = ObjectSetString(chartID, name, OBJPROP_TEXT, text); - - // - return result; -} - -// -// Move Event object -bool EventMove( - const long chartID = 0, // chart's ID - const string name = "Event", // event name - datetime time = 0 // time -) -{ - // - bool result = false; - - // - // if time is not set, move event to the last bar - if (!time) - { - time = TimeCurrent(); - } - - // - // move the object - result = ObjectMove(chartID, name, 0, time, 0); - - // - return result; -} - -// -// Delete Event object -bool EventDelete( - const long chartID = 0, // chart's ID - const string name = "Event" // event name -) -{ - // - bool result = false; - - // - // delete the object - result = ObjectDelete(chartID, name); - - // - return result; -} - -// -// Button Functions ... - -// -// Create the button ... -bool ButtonCreate( - const long chartID = 0, // chart's ID - const string name = "Button", // button name - const int subWindow = 0, // subwindow index - const int x = 0, // X coordinate - const int y = 0, // Y coordinate - const int width = 50, // button width - const int height = 15, // button height - const ENUM_BASE_CORNER corner = CORNER_LEFT_UPPER, // chart corner for anchoring - const string text = "Button", // text - const string font = "Arial", // font - const int fontSize = 8, // font size - const color clr = clrBlack, // text color - const color bgColor = clrLightGray, // background color - const color borderColor = clrNONE, // border color - const bool state = false, // pressed/released - const bool back = false, // in the background - const bool selection = false, // highlight to move - const bool hidden = true, // hidden in the object list - const long zOrder = 0 // priority for mouse click -) -{ - // - bool result = false; - - // - // create the button - result = ObjectCreate(chartID, name, OBJ_BUTTON, subWindow, 0, 0); - if (!result) - { - return result; - } - - // - // set button coordinates - ObjectSetInteger(chartID, name, OBJPROP_XDISTANCE, x); - ObjectSetInteger(chartID, name, OBJPROP_YDISTANCE, y); - - // - // set button size - ObjectSetInteger(chartID, name, OBJPROP_XSIZE, width); - ObjectSetInteger(chartID, name, OBJPROP_YSIZE, height); - - // - // set the chart's corner, relative to which point coordinates are defined - ObjectSetInteger(chartID, name, OBJPROP_CORNER, corner); - - // - // set the text - ObjectSetString(chartID, name, OBJPROP_TEXT, text); - - // - // set text font - ObjectSetString(chartID, name, OBJPROP_FONT, font); - - // - // set font size - ObjectSetInteger(chartID, name, OBJPROP_FONTSIZE, fontSize); - - // - // set text color - ObjectSetInteger(chartID, name, OBJPROP_COLOR, clr); - - // - // set background color - ObjectSetInteger(chartID, name, OBJPROP_BGCOLOR, bgColor); - - // - // set border color - ObjectSetInteger(chartID, name, OBJPROP_BORDER_COLOR, borderColor); - - // - // display in the foreground false or background true - ObjectSetInteger(chartID, name, OBJPROP_BACK, back); - - // - // set button state - ObjectSetInteger(chartID, name, OBJPROP_STATE, state); - - // - // enable true or disable false the mode of moving the button by mouse - ObjectSetInteger(chartID, name, OBJPROP_SELECTABLE, selection); - ObjectSetInteger(chartID, name, OBJPROP_SELECTED, selection); - - // - // hide true or display false graphical object name in the object list - ObjectSetInteger(chartID, name, OBJPROP_HIDDEN, hidden); - - // - // set the priority for receiving the event of a mouse click in the chart - ObjectSetInteger(chartID, name, OBJPROP_ZORDER, zOrder); - - // - return result; -} - -// -// Move the button ... -bool ButtonMove( - const long chartID = 0, // chart's ID - const string name = "Button", // button name - const int x = 0, // X coordinate - const int y = 0 // Y coordinate -) -{ - // - bool result = false; - - // - // move the button - - // - result = ObjectSetInteger(chartID, name, OBJPROP_XDISTANCE, x); - if (!result) - { - return result; - } - - // - result = ObjectSetInteger(chartID, name, OBJPROP_YDISTANCE, y); - - // - return result; -} - -// -// Change button size ... -bool ButtonChangeSize( - const long chartID = 0, // chart's ID - const string name = "Button", // button name - const int width = 50, // button width - const int height = 18 // button height -) -{ - // - bool result = false; - - // - // change the button size - - // - result = ObjectSetInteger(chartID, name, OBJPROP_XSIZE, width); - if (!result) - { - return result; - } - - // - result = ObjectSetInteger(chartID, name, OBJPROP_YSIZE, height); - - // - return result; -} - -// -// Change corner of the chart for binding the button ... -bool ButtonChangeCorner( - const long chartID = 0, // chart's ID - const string name = "Button", // button name - const ENUM_BASE_CORNER corner = CORNER_LEFT_UPPER // chart corner for anchoring -) -{ - // - bool result = false; - - // - // change anchor corner - result = ObjectSetInteger(chartID, name, OBJPROP_CORNER, corner); - - // - return result; -} - -// -// Change button text ... -bool ButtonTextChange( - const long chartID = 0, // chart's ID - const string name = "Button", // button name - const string text = "Text" // text -) -{ - // - bool result = false; - - // - // change object text - result = ObjectSetString(chartID, name, OBJPROP_TEXT, text); - - // - return result; -} - -// -// Delete the button ... -bool ButtonDelete( - const long chartID = 0, // chart's ID - const string name = "Button" // button name -) -{ - // - bool result = false; - - // - // delete the button - result = ObjectDelete(chartID, name); - - // - return result; -} - -// -// Chart Style Drawers ... - -// -// Apply Styles On Chart ... -void ApplyChartStyle( - long mChartId = -1, // chart's ID - ENUM_CHART_MODE mMode = CHART_CANDLES, // chart's mMode - bool mShowBidLine = true, // show bid line - bool mShowAskLine = true, // show ask line - bool mShowGrid = false, // show grids on chart - bool mShowVolumes = false, // show volumes - bool mShowTradeLevels = true, // Displaying trade levels in the chart (levels of open positions, Stop Loss, Take Profit and pending orders) - bool mAutoScroll = true, // chart autoscroll - bool mQuickNavigation = true, // chart quick navigation state - color mForeGroundColor = clrWhite, // chart's foreground color - color mBackGroundColor = clrBlack, // chart's background color - color mUpColor = clrGreen, // Up Color - color mDownColor = clrRed, // Down Color - color mBullishColor = clrGreen, // Bullish color - color mBearishColor = clrRed, // Bearish color - color mGridColor = clrGray, // grid color - color mBidLineColor = clrGray, // bid line color - color mAskLineColor = clrRed, // ask line color - color mLineColor = clrLime, // line mMode and doji candlestick color - color mStopColor = clrGold, // Color of stop order levels (Stop Loss and Take Profit) - color mVolumesColor = clrGreen // volumes color -) -{ - // - // Validate Args ... - if (mChartId == -1) - { - mChartId = 0; - } - - // - ChartSetInteger(mChartId, CHART_MODE, mMode); - ChartSetInteger(mChartId, CHART_SHOW_BID_LINE, mShowBidLine); - ChartSetInteger(mChartId, CHART_SHOW_ASK_LINE, mShowAskLine); - ChartSetInteger(mChartId, CHART_SHOW_GRID, mShowGrid); - ChartSetInteger(mChartId, CHART_SHOW_VOLUMES, mShowVolumes); - ChartSetInteger(mChartId, CHART_SHOW_TRADE_LEVELS, mShowTradeLevels); - ChartSetInteger(mChartId, CHART_AUTOSCROLL, mAutoScroll); - ChartSetInteger(mChartId, CHART_QUICK_NAVIGATION, mQuickNavigation); - ChartSetInteger(mChartId, CHART_COLOR_FOREGROUND, mForeGroundColor); - ChartSetInteger(mChartId, CHART_COLOR_BACKGROUND, mBackGroundColor); - ChartSetInteger(mChartId, CHART_COLOR_CHART_UP, mUpColor); - ChartSetInteger(mChartId, CHART_COLOR_CHART_DOWN, mDownColor); - ChartSetInteger(mChartId, CHART_COLOR_CANDLE_BULL, mBullishColor); - ChartSetInteger(mChartId, CHART_COLOR_CANDLE_BEAR, mBearishColor); - ChartSetInteger(mChartId, CHART_COLOR_GRID, mGridColor); - ChartSetInteger(mChartId, CHART_COLOR_BID, mBidLineColor); - ChartSetInteger(mChartId, CHART_COLOR_ASK, mAskLineColor); - ChartSetInteger(mChartId, CHART_COLOR_STOP_LEVEL, mStopColor); - ChartSetInteger(mChartId, CHART_COLOR_CHART_LINE, mLineColor); - ChartSetInteger(mChartId, CHART_COLOR_VOLUME, mVolumesColor); -} - -// -// Tools ... - -// -// Retrieve Chart Size ... -bool GetChartSize( - XSize &result, // Holds Result ... - long chartID = 0 // Specified Chart ID ... -) -{ - // - bool mResult = false; - - // - mResult = ChartGetInteger(0, CHART_WIDTH_IN_PIXELS, 0, result.width); - if (!mResult) - { - return mResult; - } - - // - mResult = ChartGetInteger(0, CHART_HEIGHT_IN_PIXELS, 0, result.height); - - // - return mResult; -} diff --git a/Documents/Pack/V1.0/Source/Libraries/x-saherelm.xtrade.lib.mq5 b/Documents/Pack/V1.0/Source/Libraries/x-saherelm.xtrade.lib.mq5 deleted file mode 100644 index 557b2f7a..00000000 --- a/Documents/Pack/V1.0/Source/Libraries/x-saherelm.xtrade.lib.mq5 +++ /dev/null @@ -1,5284 +0,0 @@ -/////////////////////////////////////////////////////// -// -// SaherElm IT Center MQL5 Seriallize Library -// --------------------------------------- -// Name: XTradeLib -// Description: All models related to Trade ... -// -// -// 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 -#include "../Libraries/x-saherelm.draw.lib.mq5" -#include "../Classes/x-saherelm.xsccf.class.mq5" -#include "../Libraries/x-saherelm.common.lib.mq5" -#include "../Classes/x-saherelm.xsczone.class.mq5" -#include "../Classes/x-saherelm.xsctrend.class.mq5" - -// -// Definitions ... - -// -// a List of Used Tokens ... - -// -// Common ... -string XIDToken = "ID"; -string XTicketToken = "TK"; -string XModeToken = "MD"; -string XTypeToken = "TY"; -string XPeriodToken = "PR"; -string XProviderToken = "PRV"; -string XProfitToken = "PF"; - -// -string XTPToken = "TP"; -string XSLToken = "SL"; -string XTimeToken = "TM"; -string XEntryToken = "EN"; -string XVolumeToken = "VL"; -string XSymbolToken = "SMBL"; - -// -string XSupportToken = "SP"; -string XEQMSupportToken = "EQM"; -string XEQPToken = "EQP"; - -// -string XSLTrailToken = "SLT"; - -// -string XActionToken = "A"; - -// -string XDirectionalToken = "D"; -string XINDirectionalToken = "IND"; - -// -// Available Order Modes ... -enum ENUM_X_ORDER_MODES -{ - X_ORDER_MODE_NOTHING, // Nothing - X_ORDER_MODE_MARKET, // Market Order - X_ORDER_MODE_STOP, // Pending Stop Order - X_ORDER_MODE_LIMIT, // Pending Limit Order - X_ORDER_MODE_STOP_LIMIT, // Pending Stop Limit Order -}; - -// -string ToString(ENUM_X_ORDER_MODES value) -{ - // - string result = NULL; - - // - switch (value) - { - // - case X_ORDER_MODE_MARKET: - result = "Market"; - break; - - // - case X_ORDER_MODE_LIMIT: - result = "Limit"; - break; - - // - case X_ORDER_MODE_STOP: - result = "Stop"; - break; - - // - case X_ORDER_MODE_STOP_LIMIT: - result = "StopLimit"; - break; - } - - // - return result; -} - -// -// Select Positions Type ... -enum ENUM_X_POSITION_SELECT_METHODS -{ - X_POSITION_SELECT_NONE, // None - X_POSITION_SELECT_MAX, // Max - X_POSITION_SELECT_MIN, // Min - X_POSITION_SELECT_BOTH, // Min and Max - X_POSITION_SELECT_ALL, // All -}; - -// -// Signal Execution Result ... -// note that some of them must be handles in -// EA's ... -enum ENUM_X_SIGNAL_EXECUTION_RESULT -{ - // - X_SIGNAL_EXECUTION_UNKNOWN, // Unknown - X_SIGNAL_EXECUTION_SUCCEED, // Succed - X_SIGNAL_EXECUTION_FAILED_SPREAD, // Spread more than Max Allowed - X_SIGNAL_EXECUTION_FAILED_NO_EQUITY, // No Equity for Trade - X_SIGNAL_EXECUTION_FAILED_PRICE_ERROR, // Price Error - X_SIGNAL_EXECUTION_FAILED_MAX_REACHED, // Max Allowed Positions Reached - X_SIGNAL_EXECUTION_FAILED_INVALID_PARAMS, // Invalid Params -}; - -// -// Available Guard Action ... -enum ENUM_X_GUARD_ACTIONS -{ - X_GUARD_ACTION_NOTHING, // Nothing - X_GUARD_ACTION_HEDGE, // Hedge - X_GUARD_PARTIAL_CLOSE, // Partial Close - X_GUARD_ACTION_TRAIL_STOP, // Trail StopLoss - X_GUARD_ACTION_FORCE_CLOSE, // Force Close - X_GUARD_ACTION_ADD_SUPPORT_SIGNAL, // Add Support Signal - X_GUARD_ACTION_CANCEL_PENDING_ORDERS, // Cancel Pending Orders -}; - -// -enum ENUM_X_POSITION_TYPES -{ - X_POSITION_TYPE_NONE = 0, - X_POSITION_TYPE_ALL = 1, - X_POSITION_TYPE_LONG = 2, - X_POSITION_TYPE_SHORT = 3, -}; - -// -string ToString(ENUM_X_POSITION_TYPES value) -{ - // - string result = NULL; - - // - switch (value) - { - // - case X_POSITION_TYPE_ALL: - result = "All"; - break; - - // - case X_POSITION_TYPE_NONE: - result = "NONE"; - break; - - // - case X_POSITION_TYPE_SHORT: - result = "Short"; - break; - - // - case X_POSITION_TYPE_LONG: - result = "Long"; - break; - } - - // - return result; -} - -// -bool IsLong(ENUM_X_POSITION_TYPES value) -{ - return value == X_POSITION_TYPE_LONG; -} - -// -bool ToPositionType( - ENUM_POSITION_TYPE &dest, - ENUM_X_POSITION_TYPES source // -) -{ - // - bool result = false; - - // - result = source == X_POSITION_TYPE_LONG || - source == X_POSITION_TYPE_SHORT; - if (!result) - { - return result; - } - - // - dest = - source == X_POSITION_TYPE_LONG - ? POSITION_TYPE_BUY - : POSITION_TYPE_SELL; - - // - return result; -} - -// -ENUM_X_POSITION_TYPES ToPositionType(ENUM_POSITION_TYPE value) -{ - return IsLong(value) - ? X_POSITION_TYPE_LONG - : X_POSITION_TYPE_SHORT; -} - -// -ENUM_X_POSITION_TYPES GetOppositPositionType(ENUM_POSITION_TYPE type) -{ - // - ENUM_X_POSITION_TYPES result = X_POSITION_TYPE_NONE; - - // - bool isLong = IsLong(type); - bool isShort = IsShort(type); - - // - result = - // - isLong - ? X_POSITION_TYPE_SHORT - : isShort - ? X_POSITION_TYPE_LONG - : X_POSITION_TYPE_NONE - // - ; - - // - return result; -} - -// -// Structs ... - -// -// Model an Open Position ... -struct XPosition -{ - // - // Props ... - - // - // Magic Number ... - ulong magic; - - // - // Ticket ID ... - ulong ticket; - - // - // Tradinng Symbol ... - string symbol; - - // - // Trading Period ... - ENUM_TIMEFRAMES period; - - // - // Position Type ... - ENUM_POSITION_TYPE type; - - // - // Take Profit ... - double tp; - - // - // Stop Loss ... - double sl; - - // - // Position Current Profit ... - double profit; - - // - // Position Open Price ... - double entry; - - // - // Current Symbol Price ... - double price; - - // - // Position Swap ... - double swap; - - // - // Position Commission ... - double commission; - - // - // Volume ... - double volume; - - // - // Position Open Time ... - datetime openAt; - - // - // Sifnal Provider ... - string provider; - - // - // Position Comment ... - string comment; - - // - // Constructor ... - XPosition() - { - Clean(); - } - - // - // Initializers ... - - bool ByIndex(int index) - { - // - bool result = false; - - // - static CPositionInfo mPositionInfo; - - // - result = mPositionInfo.SelectByIndex(index); - if (!result) - { - return result; - } - - // - ulong mTicket = mPositionInfo.Ticket(); - - // - result = ByTicket(mTicket); - - // - return result; - } - - bool ByTicket(ulong mTicket) - { - // - bool result = false; - - // - static CPositionInfo mPositionInfo; - - // - result = mPositionInfo.SelectByTicket(mTicket); - if (!result) - { - return result; - } - - // - swap = mPositionInfo.Swap(); - magic = mPositionInfo.Magic(); - openAt = mPositionInfo.Time(); - sl = mPositionInfo.StopLoss(); - ticket = mPositionInfo.Ticket(); - symbol = mPositionInfo.Symbol(); - tp = mPositionInfo.TakeProfit(); - profit = mPositionInfo.Profit(); - volume = mPositionInfo.Volume(); - comment = mPositionInfo.Comment(); - entry = mPositionInfo.PriceOpen(); - type = mPositionInfo.PositionType(); - price = mPositionInfo.PriceCurrent(); - commission = mPositionInfo.Commission(); - - // - period = ExtractPeriod(comment); - provider = ExtractProvider(comment); - - // - return result; - } - - // - // Tools ... - - // - // Cleanup ... - void Clean() - { - magic = 0; - ticket = 0; - tp = 0; - sl = 0; - swap = 0; - entry = 0; - price = 0; - profit = 0; - volume = 0; - openAt = 0; - commission = 0; - - // - type = NULL; - period = NULL; - - // - symbol = NULL; - comment = NULL; - provider = NULL; - } - - // - // Validate ... - bool IsValid() - { - // - bool result = false; - - // - result = - // - IsValid(symbol) && - NotEmpty(ticket) - // - ; - - // - return result; - } - - // - // Retrieve Entry Price ... - double GetEntry() - { - // - double result = 0; - - // - if (!IsValid()) - { - return result; - } - - // - result = GetEntry( - symbol, - type - // - ); - - // - return result; - } - - // - // Retrieve Exit ... - double GetExit() - { - // - double result = 0; - - // - if (!IsValid()) - { - return result; - } - - // - result = GetExit( - symbol, - type - // - ); - - // - return result; - } - - // - // Get Spread by Point ... - double GetSpread() - { - // - double result = 0; - - // - if (!IsValid()) - { - return result; - } - - // - result = PriceToPoint(GetSpread(symbol)); - - // - return result; - } - - // - // Find Risk ... - double GetRisk() - { - // - double result = 0; - - // - if (!IsValid()) - { - return 0; - } - - // - result = MathAbs(entry - sl); - - // - return result; - } - - // - // Find Reward ... - double GetReward() - { - // - double result = 0; - - // - if (!IsValid()) - { - return result; - } - - // - result = MathAbs(tp - entry); - - // - return result; - } - - // - // Find Risk Reward Ratio ... - double GetRiskRewardRatio() - { - // - double result = 0; - - // - if (!IsValid()) - { - return result; - } - - // - result = GetReward() / GetRisk(); - - // - return result; - } - - // - // Calculate Age ... - int GetAge( - ENUM_TIMEFRAMES mPeriod // Calculate Age based on this period - ) - { - return GetAge(this, mPeriod); - } - - // - // Check this instance is Same os Given instance or not ... - bool IsSameAs( - const XPosition &value // instance for Compare - ) - { - // - bool result = false; - - // - result = - // - type == value.type && - magic == value.magic && - entry == value.entry && - ticket == value.ticket && - volume == value.volume && - symbol == value.symbol && - provider == value.provider - // - ; - - // - return result; - } - - // - // Find index in a Collection ... - int FindIndex( - const XPosition &values[] // Collection to Find - ) - { - // - return FindIndex( - this, - values - // - ); - } - - // - // Check Items Passed Specific Filters or not ... - bool IsFiltersPassed( - string mSymbol = NULL, // Trading Symbol - string mProvider = NULL, // Signal Provider - ENUM_TIMEFRAMES mPeriod = NULL, // Trading Timeframe - ENUM_X_POSITION_TYPES mType = NULL, // Long (Buy), Short (Sell) - ulong mMagic = NULL, // Magic Number - bool mFilterByMagic = true // Get Only Self Open Positions - ) - { - // - bool result = false; - - // - result = - // - // Magic Filter ... - IsMagicFilterPassed( - mMagic, - mFilterByMagic, - this - // - ) - // - && - // - // Symbol Filter ... - IsSymbolFilterPassed( - mSymbol, - this - // - ) - // - && - // - // Provider Filter ... - IsProviderFilterPassed( - mProvider, - this - // - ) - // - && - // - // Period Filter ... - IsPeriodFilterPassed( - mPeriod, - this - // - ) - // - && - // - // Type Filter ... - IsTypeFilterPassed( - mType, - this - // - ) - // - ; - - // - return result; - } -}; - -// -// Model a Signal ... -struct XSignal -{ - // - // Props ... - - // - ulong positionId; // if Executed this filled ... - - // - datetime time; // Issue Time ... - - // - double tp; // Take Profit ... - double sl; // Stop Loss ... - double entry; // Exntry or Execution Price ... - double volume; // Position Volume ... - - // - string symbol; // Trading Symbol ... - string comment; // Comment ... - string provider; // Signaller ... - - // - ENUM_TIMEFRAMES period; // Trading TimeFrame ... - ENUM_POSITION_TYPE type; // Long (Buy) or Short (Sell) ... - ENUM_X_ORDER_MODES mode; // Execution Mode ... - - // - XSignal supports[]; // a Collecion of Support Signals ... - - // - // Constructor ... - XSignal() - { - Clean(); - } - - // - 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 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 = GetOpposit(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 = GetOpposit(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; - } - - // - // Tools ... - - // - // Cleanup ... - void Clean() - { - // - entry = 0; - volume = 0; - positionId = 0; - - // - time = NULL; - type = NULL; - mode = NULL; - symbol = NULL; - period = NULL; - comment = NULL; - provider = NULL; - - // - Clean(supports); - } - - // - // Validate ... - bool IsValid() - { - // - bool result = false; - - // - result = - // - IsValid(period) && - IsValid(symbol) && - NotEmpty(volume) && - NotEmpty(entry) - // - ; - - // - if (!result) - { - return result; - } - - // - return result; - } - - // - // DO All Calculations and Normalizations ... - bool Normalize() - { - // - bool result = false; - - // - // Normalizations ... - symbol = NormalizeSymbol(symbol); - period = NormalizePeriod(period); - - // - time = NormalizeTime(time); - - // - sl = NormalizePrice(sl, symbol); - tp = NormalizePrice(tp, symbol); - entry = NormalizePrice(entry, symbol); - volume = NormalizeVolume(volume, symbol); - - // - result = IsValid(); - - // - return result; - } - - // - // Check Signal Executed or not ... - bool IsExecuted() - { - // - bool result = false; - - // - result = - // - IsValid() && - NotEmpty(positionId) - // - ; - - // - return result; - } - - // - // Generate Comment for Signal ... - string GenerateComment() - { - // - string result = NULL; - - // - if (!IsValid()) - { - return result; - } - - // - if (IsValid(provider)) - { - // - // Generate Provider Tag ... - result += GenerateProviderTag(provider); - } - - // - if (IsValid(period)) - { - // - // Generate Period Tag ... - result += GeneratePeriodTag(period); - } - - // - return result; - } - - // - int GetAge() - { - // - return GetAge( - this, - this.period // - ); - } - - // - // Retrieve Entry Price ... - double GetEntry() - { - // - double result = 0; - - // - if (!IsValid()) - { - return result; - } - - // - result = GetEntry( - symbol, - type - // - ); - - // - return result; - } - - // - // Retrieve Exit ... - double GetExit() - { - // - double result = 0; - - // - if (!IsValid()) - { - return result; - } - - // - result = GetExit( - symbol, - type - // - ); - - // - return result; - } - - // - // Get Spread by Point ... - double GetSpread() - { - // - double result = 0; - - // - if (!IsValid()) - { - return result; - } - - // - result = PriceToPoint(GetSpread(symbol)); - - // - return result; - } - - // - // Find Risk ... - double GetRisk() - { - // - double result = 0; - - // - if (!IsValid()) - { - return 0; - } - - // - result = MathAbs(entry - sl); - - // - return result; - } - - // - // Find Reward ... - double GetReward() - { - // - double result = 0; - - // - if (!IsValid()) - { - return result; - } - - // - result = MathAbs(tp - entry); - - // - return result; - } - - // - // Find Risk Reward Ratio ... - double GetRiskRewardRatio() - { - // - double result = 0; - - // - if (!IsValid()) - { - return result; - } - - // - result = GetReward() / GetRisk(); - - // - return result; - } - - // - // Draw Signal on Chart ... - bool Draw( - long chartID, - int subWindow = 0, - string prefix = NULL, - color entryColor = clrGold, - color bullishColor = clrSpringGreen, - color bearishColor = clrTomato // - ) - { - // - bool result = false; - - // - result = IsValid(); - if (!result) - { - return result; - } - - // - bool isLong = IsLong(this.type); - - // - prefix = - // - (!IsValid(prefix) ? "" : prefix) + - this.symbol + "_" + - ToString(this.period) + "_" + - this.provider - // - ; - - // - int age = this.GetAge(); - - // - // Retrieve Time ... - datetime time0 = iTime( - this.symbol, - this.period, - age // - ); - - // - // Retrieve 3 Time ... - datetime time3 = iTime( - this.symbol, - this.period, - age + 3 // - ); - - // - color posColor = isLong - ? bullishColor - : bearishColor; - color tpColor = bullishColor; - color slColor = bearishColor; - - // - ENUM_LINE_STYLE vLineStyle = STYLE_DOT; - ENUM_LINE_STYLE tpLineStyle = STYLE_SOLID; - ENUM_LINE_STYLE slLineStyle = STYLE_SOLID; - ENUM_LINE_STYLE entryLineStyle = STYLE_SOLID; - - // - int lineWidth = 2; - - // - // Vertical Line ... - string vlName = prefix + "_" + (string)time; - - // - result = DrawVerticalLine( - chartID, - vlName, - subWindow, - time0, - posColor, - vLineStyle, - lineWidth // - ); - if (!result) - { - return result; - } - - // - // TP ... - double profit = (MathAbs(this.tp - this.entry)) * this.volume; - string tpName = prefix + "_TP_" + (string)profit; - - // - result = DrawTrendLine( - chartID, - tpName, - subWindow, - time3, - this.tp, - time0, - this.tp, - tpColor, - tpLineStyle, - lineWidth // - ); - if (!result) - { - return result; - } - - // - // SL ... - double lost = (MathAbs(this.sl - this.entry)) * this.volume; - string slName = prefix + "_SL_" + (string)lost; - - // - result = DrawTrendLine( - chartID, - slName, - subWindow, - time3, - this.sl, - time0, - this.sl, - slColor, - slLineStyle, - lineWidth // - ); - if (!result) - { - return result; - } - - // - // ENTRY ... - string entryName = prefix + "_ENTRY_" + (string)lost; - - // - result = DrawTrendLine( - chartID, - entryName, - subWindow, - time3, - this.entry, - time, - this.entry, - entryColor, - entryLineStyle, - lineWidth // - ); - - // - return result; - } - - // - // Retrieve String Representation of Signal ... - string ToString() - { - // - string result = NULL; - - // - result = - // - ToString("Symbol", symbol) + - ToString("Period", period) + - ToString("Provider", provider) + - ToString("Type", type) + - ToString("Mode", mode) + - ToString("Volume", volume) + - ToString("Entry", entry) + - ToString("TP", tp) + - ToString("SL", sl) + - ToString("Time", time) + - ToString("Comment", comment) + - // - "" - // - ; - - // - return result; - } -}; - -// -// Model an Order ... -struct XOrder -{ - // - // Time of order placement ... - datetime setupAt; - - // - // Time of order expiration ... - datetime expiredAt; - - // - // Time of order execution or cancellation ... - datetime executedAt; - - // - // Order type ... - ENUM_ORDER_TYPE type; - - // - // Order state ... - ENUM_ORDER_STATE state; - - // - // Type of execution by remainder ... - ENUM_ORDER_TYPE_FILLING filling; - - // - // Order lifetime ... - ENUM_ORDER_TYPE_TIME lifetime; - - // - // Order ticket ... - ulong ticket; - - // - // Magic Number ... - long magic; - - // - // Position id, that is placed on order, - // when it is executed. Each executed order invokes a - // deal, that opens new or changes existing - // position. Id of that position is placed on - // executed order in this moment. - long positionId; - - // - // Initial volume on order placement ... - double initialVolume; - - // - // Unfilled volume ... - double currentVolume; - - // - // Price, specified in the order ... - double openPrice; - - // - // Current price by order symbol ... - double currentPrice; - - // - // Price of placing Limit order when StopLimit order is triggered ... - double stopLimitPrice; - - // - // Take Profit level ... - double tp; - - // - // Stop Loss level ... - double sl; - - // - // Trading Symbol ... - string symbol; - - // - // Signal Provider ... - string provider; - - // - // Order Comment ... - string comment; - - // - ENUM_TIMEFRAMES period; - - // - // Constructor ... - XOrder() - { - Clean(); - } - - // - // Initializers ... - bool ByIndex( - int index // Fill By Index ... - ) - { - // - bool result = false; - - // - int ordersCount = OrdersTotal(); - if (ordersCount <= 0) - { - return result; - } - - // - static COrderInfo mOrderInfo; - - // - result = mOrderInfo.SelectByIndex(index); - if (!result) - { - return result; - } - - // - // Reading Order Info ... - magic = mOrderInfo.Magic(); - sl = mOrderInfo.StopLoss(); - tp = mOrderInfo.TakeProfit(); - ticket = mOrderInfo.Ticket(); - openPrice = mOrderInfo.PriceOpen(); - positionId = mOrderInfo.PositionId(); - currentPrice = mOrderInfo.PriceCurrent(); - initialVolume = mOrderInfo.VolumeInitial(); - currentVolume = mOrderInfo.VolumeCurrent(); - stopLimitPrice = mOrderInfo.PriceStopLimit(); - - // - symbol = mOrderInfo.Symbol(); - comment = mOrderInfo.Comment(); - - // - state = mOrderInfo.State(); - type = mOrderInfo.OrderType(); - lifetime = mOrderInfo.TypeTime(); - filling = mOrderInfo.TypeFilling(); - - // - setupAt = mOrderInfo.TimeSetup(); - executedAt = mOrderInfo.TimeDone(); - expiredAt = mOrderInfo.TimeExpiration(); - - // - period = ExtractPeriod(comment); - provider = ExtractProvider(comment); - - // - result = IsValid(); - - // - return result; - } - - // - // Retrieve Specific History Order ... - bool HistoryByIndex( - int index // Fill By Index ... - ) - { - // - bool result = false; - - // - int ordersCount = HistoryOrdersTotal(); - if (ordersCount <= 0) - { - return result; - } - - // - static CHistoryOrderInfo mOrderInfo; - - // - result = mOrderInfo.SelectByIndex(index); - if (!result) - { - return result; - } - - // - // Reading Order Info ... - magic = mOrderInfo.Magic(); - sl = mOrderInfo.StopLoss(); - tp = mOrderInfo.TakeProfit(); - ticket = mOrderInfo.Ticket(); - openPrice = mOrderInfo.PriceOpen(); - positionId = mOrderInfo.PositionId(); - currentPrice = mOrderInfo.PriceCurrent(); - initialVolume = mOrderInfo.VolumeInitial(); - currentVolume = mOrderInfo.VolumeCurrent(); - stopLimitPrice = mOrderInfo.PriceStopLimit(); - - // - symbol = mOrderInfo.Symbol(); - comment = mOrderInfo.Comment(); - - // - state = mOrderInfo.State(); - type = mOrderInfo.OrderType(); - lifetime = mOrderInfo.TypeTime(); - filling = mOrderInfo.TypeFilling(); - - // - setupAt = mOrderInfo.TimeSetup(); - executedAt = mOrderInfo.TimeDone(); - expiredAt = mOrderInfo.TimeExpiration(); - - // - period = ExtractPeriod(comment); - provider = ExtractProvider(comment); - - // - result = IsValid(); - - // - return result; - } - - // - // Tools ... - - // - // Cleanup ... - void Clean() - { - // - tp = 0; - sl = 0; - magic = 0; - ticket = 0; - positionId = 0; - openPrice = 0; - currentPrice = 0; - initialVolume = 0; - currentVolume = 0; - stopLimitPrice = 0; - - // - setupAt = NULL; - expiredAt = NULL; - executedAt = NULL; - - // - symbol = NULL; - comment = NULL; - provider = NULL; - - // - type = NULL; - state = NULL; - period = NULL; - filling = NULL; - lifetime = NULL; - } - - // - // Validate ... - bool IsValid() - { - // - bool result = false; - - // - result = - // - IsValid(symbol) && - NotEmpty(ticket) && - NotEmpty(positionId) - // - ; - - // - return result; - } - - // - // Calculate Age ... - int GetAge( - ENUM_TIMEFRAMES mPeriod // Calculate Age based on this period - ) - { - return GetAge(this, mPeriod); - } - - // - // Check this instance is Same os Given instance or not ... - bool IsSameAs( - const XOrder &value // instance for Compare - ) - { - // - bool result = false; - - // - result = - // - type == value.type && - state == value.state && - magic == value.magic && - ticket == value.ticket && - symbol == value.symbol && - provider == value.provider && - positionId == value.positionId - // - ; - - // - return result; - } - - // - // Find index in a Collection ... - int FindIndex( - const XOrder &values[] // Collection to Find - ) - { - // - return FindIndex( - this, - values - // - ); - } - - // - // Check Items Passed Specific Filters or not ... - bool IsFiltersPassed( - string mSymbol = NULL, // Trading Symbol - string mProvider = NULL, // Signal Provider - ENUM_TIMEFRAMES mPeriod = NULL, // Trading Timeframe - ENUM_X_POSITION_TYPES mType = NULL, // Long (Buy), Short (Sell) - ENUM_ORDER_STATE mState = NULL, // Order State - ulong mMagic = NULL, // Magic Number - bool mFilterByMagic = true // Get Only Self Open Positions - ) - { - // - bool result = false; - - // - result = - // - // Magic Filter ... - IsMagicFilterPassed( - mMagic, - mFilterByMagic, - this - // - ) - // - && - // - // Symbol Filter ... - IsSymbolFilterPassed( - mSymbol, - this - // - ) - // - && - // - // Provider Filter ... - IsProviderFilterPassed( - mProvider, - this - // - ) - // - && - // - // Period Filter ... - IsPeriodFilterPassed( - mPeriod, - this - // - ) - // - && - // - // Type Filter ... - IsTypeFilterPassed( - mType, - this - // - ) - // - && - // - // State Filter ... - IsStateFilterPassed( - mState, - this - // - ) - // - ; - - // - return result; - } -}; - -// -// Model a Deal ... -struct XDeal -{ - // - // the ID of the Expert Advisor, that executed the deal ... - ulong magic; - - // - // the ID of position, in which the deal was involved ... - ulong positionId; - - // - // Ticket ... - ulong ticket; - - // - // the name of the deal symbol ... - string symbol; - - // - // order by which the deal is executed ... - ulong order; - - // - // the time of deal execution ... - datetime time; - - // - // Deal price ... - double price; - - // - // the financial result of the deal (in deposit currency) ... - double profit; - - // - // the amount of swap when position is closed ... - double swap; - - // - // the amount of commission of the deal ... - double commission; - - // - // the volume of deal ... - double volume; - - // - // the deal comment ... - string comment; - - // - string provider; - - // - ENUM_TIMEFRAMES period; - - // - // the deal type ... - // ------------------------------------------------------------------ - // DEAL_TYPE_BUY => Buy ... - // DEAL_TYPE_SELL => Sell ... - // DEAL_TYPE_BUY_CANCELED => Canceled buy deal ... - // There can be a situation when a previously executed buy deal is canceled. In this case, - // the type of the previously executed deal (DEAL_TYPE_BUY) is changed to DEAL_TYPE_BUY_CANCELED, - // and its profit/loss is zeroized. Previously obtained profit/loss is charged/withdrawn using a separated balance operation ... - // - // DEAL_TYPE_SELL_CANCELED => Canceled sell deal ... - // There can be a situation when a previously executed sell deal is canceled. In this case, - // the type of the previously executed deal (DEAL_TYPE_SELL) is changed to DEAL_TYPE_SELL_CANCELED, - // and its profit/loss is zeroized. Previously obtained profit/loss is charged/withdrawn using a separated balance operation - // - // DEAL_TYPE_BALANCE => Balance ... - // DEAL_TYPE_CREDIT => Credit ... - // DEAL_TYPE_CHARGE => Additional charge ... - // DEAL_TYPE_CORRECTION => Correction ... - // DEAL_TAX => Tax charges ... - // DEAL_TYPE_BONUS => Bonus ... - // DEAL_TYPE_INTEREST => Interest rate ... - // DEAL_DIVIDEND => Dividend operations... - // DEAL_DIVIDEND_FRANKED => Franked (non-taxable) dividend operations ... - // DEAL_TYPE_COMMISSION => Additional commission ... - // DEAL_TYPE_COMMISSION_DAILY => Daily commission ... - // DEAL_TYPE_COMMISSION_MONTHLY => Monthly commission ... - // DEAL_TYPE_COMMISSION_AGENT_DAILY => Daily agent commission ... - // DEAL_TYPE_COMMISSION_AGENT_MONTHLY => Monthly agent commission - ENUM_DEAL_TYPE type; - - // - // the deal direction ... - // ---------------------------------- - // DEAL_ENTRY_IN => Entry in ... - // DEAL_ENTRY_OUT => Entry out ... - // DEAL_ENTRY_INOUT => Reverse ... - // DEAL_ENTRY_OUT_BY => Close a position by an opposite one ... - ENUM_DEAL_ENTRY entry; - - // - // deal reson ... - // --------------------- - // DEAL_REASON_SL => The deal was executed as a result of Stop Loss activation ... - // DEAL_REASON_TP => The deal was executed as a result of Take Profit activation ... - // DEAL_REASON_SO => The deal was executed as a result of the Stop Out event ... - // DEAL_REASON_WEB => The deal was executed as a result of activation of an order placed from the web platform ... - // DEAL_REASON_SPLIT => The deal was executed after the split (price reduction) of an instrument, which had an open position during split announcement ... - // DEAL_REASON_CLIENT => The deal was executed as a result of activation of an order placed from a desktop terminal ... - // DEAL_REASON_MOBILE => The deal was executed as a result of activation of an order placed from a mobile application ... - // DEAL_REASON_EXPERT => The deal was executed as a result of activation of an order placed from an MQL5 program, i.e. an Expert Advisor or a script ... - // DEAL_REASON_VMARGIN => The deal was executed after charging the variation margin ... - // DEAL_REASON_ROLLOVER => The deal was executed due to a rollover ... - ENUM_DEAL_REASON reason; - - // - // Constructor ... - XDeal() - { - Clean(); - } - - // - // Initializers ... - bool ByIndex( - int index // Deal Index - ) - { - // - bool result = false; - - // - int dealsCount = HistoryDealsTotal(); - result = dealsCount > 0; - if (!result) - { - return result; - } - - // - static CDealInfo mDealInfo; - - // - result = mDealInfo.SelectByIndex(index); - if (!result) - { - // - return result; - } - - // - // Reading Order Info ... - swap = mDealInfo.Swap(); - magic = mDealInfo.Magic(); - order = mDealInfo.Order(); - ticket = mDealInfo.Ticket(); - time = mDealInfo.Time(); - price = mDealInfo.Price(); - symbol = mDealInfo.Symbol(); - profit = mDealInfo.Profit(); - volume = mDealInfo.Volume(); - comment = mDealInfo.Comment(); - positionId = mDealInfo.PositionId(); - entry = mDealInfo.Entry(); - commission = mDealInfo.Commission(); - type = mDealInfo.DealType(); - reason = (ENUM_DEAL_REASON)HistoryDealGetInteger( - ticket, - DEAL_REASON); - - // - period = ExtractPeriod(comment); - provider = ExtractProvider(comment); - - // - result = IsValid(); - - // - return result; - } - - // - // Tools ... - - // - // Cleanup ... - void Clean() - { - // - magic = 0; - positionId = 0; - ticket = 0; - order = 0; - time = 0; - price = 0; - profit = 0; - swap = 0; - commission = 0; - volume = 0; - - // - symbol = NULL; - comment = NULL; - provider = NULL; - - // - type = NULL; - entry = NULL; - period = NULL; - reason = NULL; - } - - // - // Validate ... - bool IsValid() - { - // - bool result = false; - - // - result = - // - IsValid(symbol) && - NotEmpty(ticket) && - NotEmpty(positionId) - // - ; - - // - return result; - } - - // - // Calculate Age ... - int GetAge( - ENUM_TIMEFRAMES mPeriod // Calculate Age based on this period - ) - { - return GetAge(this, mPeriod); - } - - // - // Check this instance is Same os Given instance or not ... - bool IsSameAs( - const XDeal &value // instance for Compare - ) - { - // - bool result = false; - - // - result = - // - type == value.type && - magic == value.magic && - entry == value.entry && - reason == value.reason && - ticket == value.ticket && - volume == value.volume && - symbol == value.symbol && - provider == value.provider && - positionId == value.positionId - // - ; - - // - return result; - } - - // - // Find index in a Collection ... - int FindIndex( - const XDeal &values[] // Collection to Find - ) - { - // - return FindIndex( - this, - values - // - ); - } - - // - // Check Items Passed Specific Filters or not ... - bool IsFiltersPassed( - string mSymbol = NULL, // Trading Symbol - string mProvider = NULL, // Signal Provider - ENUM_TIMEFRAMES mPeriod = NULL, // Trading Timeframe - ENUM_DEAL_TYPE mType = NULL, // Deal Type - ENUM_DEAL_ENTRY mEntry = NULL, // Deal Entry - ENUM_DEAL_REASON mReason = NULL, // Deal Reason - ulong mMagic = NULL, // Magic Number - bool mFilterByMagic = true // Get Only Self Open Positions - ) - { - // - bool result = false; - - // - result = - // - // Magic Filter ... - IsMagicFilterPassed( - mMagic, - mFilterByMagic, - this - // - ) - // - && - // - // Symbol Filter ... - IsSymbolFilterPassed( - mSymbol, - this - // - ) - // - && - // - // Provider Filter ... - IsProviderFilterPassed( - mProvider, - this - // - ) - // - && - // - // Period Filter ... - IsPeriodFilterPassed( - mPeriod, - this - // - ) - // - && - // - // Type Filter ... - IsTypeFilterPassed( - mType, - this - // - ) - // - && - // - // Entry Filter ... - IsEntryFilterPassed( - mEntry, - this - // - ) - // - && - // - // Reason Filter ... - IsReasonFilterPassed( - mReason, - this - // - ) - // - ; - - // - return result; - } -}; - -// -// Model OnTrade Event Handler Result on XCTrade Class ... -struct XOnTradeHandlerState -{ - // - bool hasNewDeal; - int newDeals; - - // - bool hasNewOrder; - int newOrders; - - // - bool hasNewPosition; - int newPositions; - - // - bool hasNewHistoryOrder; - int newHistoryOrders; - - // - // Constructor ... - XOnTradeHandlerState() - { - Clean(); - } - - // - // Tools ... - - // - // Cleanup ... - void Clean() - { - // - hasNewDeal = false; - hasNewOrder = false; - hasNewPosition = false; - hasNewHistoryOrder = false; - - // - newDeals = 0; - newOrders = 0; - newPositions = 0; - newHistoryOrders = 0; - } - - // - // Validate ... - bool IsValid() - { - // - bool result = false; - - // - result = - // - ( - // - hasNewDeal - ? newDeals > 0 - : true - // - ) - // - && - // - ( - // - hasNewOrder - ? newOrders > 0 - : true - // - ) - // - && - // - ( - // - hasNewPosition - ? newPositions > 0 - : true - // - ) - // - && - // - ( - // - hasNewHistoryOrder - ? newHistoryOrders > 0 - : true - // - ) - // - ; - - // - return result; - } -}; - -// -// Model Guard Info ... -struct XGuard -{ - // - string symbol; // Trading Symbol ... - string provider; // Signal Provider ... - ENUM_TIMEFRAMES period; // Trading Timeframe ... - ENUM_X_POSITION_TYPES type; // Position Type ... - ENUM_X_GUARD_ACTIONS action; // Which Action to Do ... - - // - double dblPayLoad; - string strPayload; - - // - // Constructor ... - XGuard() - { - Clean(); - } - - // - // Initialize ... - - // - // Global Initializer ... - bool Init( - string mSymbol, // Trading Symbol ... - ENUM_TIMEFRAMES mPeriod, // Trading Timeframe ... - ENUM_X_GUARD_ACTIONS mAction, // Which Action to Do ... - ENUM_X_POSITION_TYPES mType = NULL, // Position Type ... - string mProvider = NULL, // Signal Provider ... - double mDblPayLoad = NULL, - string mStrPayload = NULL // - ) - { - // - type = mType; - symbol = mSymbol; - period = mPeriod; - action = mAction; - provider = mProvider; - dblPayLoad = mDblPayLoad; - strPayload = mStrPayload; - - // - bool result = IsValid(); - - // - return result; - } - - // - // Tools ... - - // - // Cleanup ... - void Clean() - { - // - symbol = NULL; - provider = NULL; - period = NULL; - action = X_GUARD_ACTION_NOTHING; - - // - strPayload = NULL; - dblPayLoad = EMPTY_VALUE; - } - - // - // Validate ... - bool IsValid() - { - // - bool result = false; - - // - result = - // - action != X_GUARD_ACTION_NOTHING - // - ; - - // - return result; - } -}; - -// -// Model a Position with all of it's Supports ... -struct XPositionPack -{ - // - ulong ticket; // Main Position's Ticket - - // - XPosition position; // Main Position (if Exists) - - // - int supportOrdersCount; // Supported Orders (Untriggered) - int supportPositionsCount; // Supported Positions - - // - XOrder supportOrders[]; // Supported Orders (Untriggered) - XPosition supportPositions[]; // Supported Positions - - // - // Constructor ... - XPositionPack() - { - Clean(); - } - - // - // Tools ... - - // - // Cleanup ... - void Clean() - { - // - ticket = 0; - - // - position.Clean(); - - // - supportOrdersCount = 0; - supportPositionsCount = 0; - - // - Clean(supportOrders); - Clean(supportPositions); - } - - // - // Validate ... - bool IsValid() - { - // - bool result = false; - - // - result = - // - NotEmpty(ticket) && - ( - // - supportOrdersCount > 0 - ? ArraySize(supportOrders) == supportOrdersCount - : true - // - ) - // - && - // - ( - // - supportPositionsCount > 0 - ? ArraySize(supportPositions) == supportPositionsCount - : true - // - ) - // - ; - - // - return result; - } -}; - -// -// Check Position SL Trails Structure ... -struct XTrail -{ - // - ulong ticket; // Position Ticket ... - ENUM_POSITION_TYPE type; // Type ... - datetime time; // Trail Time ... - double before; // SL Value Before Trailing ... - double after; // SL Value After Trailing ... - int level; // Number of Trails SL ... - double profit; // Profit in SL Time ... - - // - // Constructor ... - XTrail() - { - Clean(); - } - - // - // Tools ... - - // - bool Init( - ulong mTicket, // Ticket - ENUM_POSITION_TYPE mType, // Type - double mProfit, // Profit - double mBefore, // Before - double mAfter // After - ) - { - // - Clean(); - - // - type = mType; - after = mAfter; - ticket = mTicket; - before = mBefore; - profit = mProfit; - - // - level++; - - // - time = TimeCurrent(); - - // - return IsValid(); - } - - // - bool Update( - double mSl, // new SL ... - double mProfit // Profit - ) - { - // - bool result = false; - - // - time = TimeCurrent(); - - // - double cAfter = after; - after = mSl; - before = cAfter; - profit = mProfit; - - // - level++; - - // - result = IsValid(); - - // - return result; - } - - // - string GenerateTag() - { - // - string result = NULL; - - // - string ticketLevelStr = ToString(ticket) + "," + ToString(level); - - // - result = Surround( - XSLTrailToken, - ticketLevelStr // - ); - - // - return result; - } - - // - // Cleanup ... - void Clean() - { - // - ticket = 0; - time = 0; - before = 0; - after = 0; - level = 0; - } - - // - // Validate ... - bool IsValid() - { - // - bool result = false; - - // - result = - // - ticket > 0 && - time > 0 && - level > 0 - // - ; - - // - return result; - } -}; - -// -struct XSymbolPositions -{ - // - string symbol; - - // - double profit; - double longsProfit; - double shortsProfit; - - // - double volume; - double longsVolume; - double shortsVolume; - - // - double requiredProfitForHedge; - - // - XPosition longs[]; - XPosition shorts[]; - XPosition positions[]; - - // - bool forceHedge; - - // - XSymbolPositions() - { - Clean(); - } - - // - bool Update( - double mMinProfitPerTrade, - double mMinProfitPerVolumeFactor // - ) - { - // - bool result = false; - - // - bool hasChild = HasChild(); - if (!hasChild) - { - return result; - } - - // - // Extract Types ... - ExtractPositions( - positions, - longs, - shorts // - ); - - // - int numOfLongs = 0; - int numOfShorts = 0; - CountPositions( - positions, - numOfLongs, - longsProfit, - longsVolume, - numOfShorts, - shortsProfit, - shortsVolume // - ); - - // - profit = longsProfit + shortsProfit; - volume = longsVolume + shortsVolume; - requiredProfitForHedge = SpecifiedCalculateRequiredProfitForHedge( - positions, - mMinProfitPerTrade, - mMinProfitPerVolumeFactor // - ); - - // - return result; - } - - // - // Tools ... - - // - // Cleanup ... - void Clean() - { - // - symbol = NULL; - forceHedge = false; - - // - profit = 0; - longsProfit = 0; - shortsProfit = 0; - - // - volume = 0; - longsVolume = 0; - shortsVolume = 0; - - // - requiredProfitForHedge = 0; - - // - Clean(longs); - Clean(shorts); - Clean(positions); - } - - // - // Validate ... - bool IsValid() - { - // - bool result = false; - - // - result = IsValid(symbol); - - // - return result; - } - - // - // Has Child ... - bool HasChild() - { - // - bool result = false; - - // - result = IsValid(); - if (!result) - { - return result; - } - - // - int count = Count(); - result = IsValidSize(count); - - // - return result; - } - - // - // Count ... - int Count() - { - return ArraySize(positions); - } - - // - int CountLongs() - { - return ArraySize(longs); - } - - // - int CountShorts() - { - return ArraySize(shorts); - } - - // - bool HasSupport() - { - // - bool result = false; - - // - result = HasChild(); - if (!result) - { - return result; - } - - // - result = HasLongSupport() || HasShortSupport(); - - // - return result; - } - - // - bool HasLongSupport() - { - // - bool result = false; - - // - int count = CountLongs(); - result = IsValidSize(count); - if (!result) - { - return result; - } - - // - for (int i = 0; i < count; i++) - { - // - XPosition iPosition = longs[i]; - result = IsSupport(iPosition.comment); - if (result) - { - break; - } - } - - // - return result; - } - - // - bool HasShortSupport() - { - // - bool result = false; - - // - int count = CountShorts(); - result = IsValidSize(count); - if (!result) - { - return result; - } - - // - for (int i = 0; i < count; i++) - { - // - XPosition iPosition = shorts[i]; - result = IsSupport(iPosition.comment); - if (result) - { - break; - } - } - - // - return result; - } - - // -}; - -// -bool IsContainsSymbol( - string symbol, - int &_index, - XSymbolPositions &_items[] // -) -{ - // - bool result = false; - - // - _index = -1; - - // - result = IsValid(symbol); - if (!result) - { - return result; - } - - // - int itemsCount = ArraySize(_items); - result = IsValidSize(itemsCount); - if (!result) - { - return result; - } - - // - for (int i = 0; i < itemsCount; i++) - { - // - result = _items[i].symbol == symbol; - if (result) - { - // - _index = i; - break; - } - } - - // - return result; -} - -// -// TypeDefs ... - -// -typedef void (*TOnDealsChanged)(int count); - -// -typedef void (*TOnOrdersChanged)(int count); - -// -typedef void (*TOnPositionsChanged)(int count); - -// -typedef void (*TOnStopLoss)(const XDeal &deal); -typedef void (*TOnTakeProfit)(const XDeal &deal); - -// -typedef void (*TOnTradeStateChanged)(const XOnTradeHandlerState &state); - -// -typedef void (*TOnForceClose)( - const ulong ticket, - const XPosition &position, - const string comment // -); - -// -typedef void (*TOnPartialClose)( - const ulong ticket, - const double profit, - const string comment // -); - -// -typedef void (*TOnModify)( - const ulong ticket, - const double profit, - const string comment // -); - -// -// Classes ... - -// -// Tools ... - -// -bool IsValid(ENUM_X_ORDER_MODES value) -{ - return value != X_ORDER_MODE_NOTHING; -} - -// -// Ages ... - -// -// Retrieve a Position Age ... -int GetAge( - XSignal &signal, // Selected Signal ... - ENUM_TIMEFRAMES period = NULL // Dest Time Frame ... -) -{ - // - int result = -1; - - // - if (period == NULL) - { - period = _Period; - } - - // - result = iBarShift( - signal.symbol, - period, - signal.time); - - // - return result; -} - -// -// Retrieve a Position Age ... -int GetAge( - XPosition &position, // Selected Position ... - ENUM_TIMEFRAMES period = NULL // Dest Time Frame ... -) -{ - // - int result = -1; - - // - if (period == NULL) - { - period = _Period; - } - - // - result = iBarShift( - position.symbol, - period, - position.openAt); - - // - return result; -} - -// -// Retrieve an Order Age ... -int GetAge( - XOrder &order, // Selected Order ... - ENUM_TIMEFRAMES period = NULL // Dest Time Frame ... -) -{ - // - int result = -1; - - // - if (period == NULL) - { - period = _Period; - } - - // - result = iBarShift( - order.symbol, - period, - order.setupAt); - - // - return result; -} - -// -// Retrieve a Deal Age ... -int GetAge( - XDeal &deal, // Selected Deal ... - ENUM_TIMEFRAMES period = NULL // Dest Time Frame ... -) -{ - // - int result = -1; - - // - if (period == NULL) - { - period = _Period; - } - - // - result = iBarShift( - deal.symbol, - period, - deal.time); - - // - return result; -} - -// -// Get Oldest Deal ... -int GetOldest( - XDeal &item, // Hold Result ... - XDeal &items[] // Source Array ... -) -{ - // - int result = -1; - - // - int itemsCount = ArraySize(items); - if (itemsCount <= 0) - { - return result; - } - - // - int tmpAge = 0; - XDeal tmpItem; - for (int i = 0; i < itemsCount; i++) - { - // - XDeal iItem = items[i]; - - // - int iAge = GetAge(iItem); - if (iAge > 0 && - (tmpAge == 0 || tmpAge < iAge)) - { - // - tmpAge = iAge; - tmpItem = iItem; - } - } - - // - if (tmpAge > 0) - { - // - result = tmpAge; - item = tmpItem; - } - - // - return result; -} - -// -// Get Youngest Deal ... -int GetYoungest( - XDeal &item, // Hold Result ... - XDeal &items[] // Source Array ... -) -{ - // - int result = -1; - - // - int itemsCount = ArraySize(items); - if (itemsCount <= 0) - { - return result; - } - - // - int tmpAge = 0; - XDeal tmpItem; - for (int i = 0; i < itemsCount; i++) - { - // - XDeal iItem = items[i]; - - // - int iAge = GetAge(iItem); - if (iAge > 0 && - (tmpAge == 0 || tmpAge > iAge)) - { - // - tmpAge = iAge; - tmpItem = iItem; - } - } - - // - if (tmpAge > 0) - { - // - result = tmpAge; - item = tmpItem; - } - - // - return result; -} - -// -// Get Oldest Order ... -int GetOldest( - XOrder &item, // Hold Result ... - XOrder &items[] // Source Array ... -) -{ - // - int result = -1; - - // - int itemsCount = ArraySize(items); - if (itemsCount <= 0) - { - return result; - } - - // - int tmpAge = 0; - XOrder tmpItem; - for (int i = 0; i < itemsCount; i++) - { - // - XOrder iItem = items[i]; - - // - int iAge = GetAge(iItem); - if (iAge > 0 && - (tmpAge == 0 || tmpAge < iAge)) - { - // - tmpAge = iAge; - tmpItem = iItem; - } - } - - // - if (tmpAge > 0) - { - // - result = tmpAge; - item = tmpItem; - } - - // - return result; -} - -// -// Get Youngest Order ... -int GetYoungest( - XOrder &item, // Hold Result ... - XOrder &items[] // Source Array ... -) -{ - // - int result = -1; - - // - int itemsCount = ArraySize(items); - if (itemsCount <= 0) - { - return result; - } - - // - int tmpAge = 0; - XOrder tmpItem; - for (int i = 0; i < itemsCount; i++) - { - // - XOrder iItem = items[i]; - - // - int iAge = GetAge(iItem); - if (iAge > 0 && - (tmpAge == 0 || tmpAge > iAge)) - { - // - tmpAge = iAge; - tmpItem = iItem; - } - } - - // - if (tmpAge > 0) - { - // - result = tmpAge; - item = tmpItem; - } - - // - return result; -} - -// -// Get Oldes Position ... -int GetOldest( - XPosition &item, // Hold Result ... - XPosition &items[] // Source Array ... -) -{ - // - int result = -1; - - // - int itemsCount = ArraySize(items); - if (itemsCount <= 0) - { - return result; - } - - // - int tmpAge = 0; - XPosition tmpItem; - for (int i = 0; i < itemsCount; i++) - { - // - XPosition iItem = items[i]; - - // - int iAge = GetAge(iItem); - if (iAge > 0 && - (tmpAge == 0 || tmpAge < iAge)) - { - // - tmpAge = iAge; - tmpItem = iItem; - } - } - - // - if (tmpAge > 0) - { - // - result = tmpAge; - item = tmpItem; - } - - // - return result; -} - -// -// Get Youngest Position ... -int GetYoungest( - XPosition &item, // Hold Result ... - XPosition &items[] // Source Array ... -) -{ - // - int result = -1; - - // - int itemsCount = ArraySize(items); - if (itemsCount <= 0) - { - return result; - } - - // - int tmpAge = 0; - XPosition tmpItem; - for (int i = 0; i < itemsCount; i++) - { - // - XPosition iItem = items[i]; - - // - int iAge = GetAge(iItem); - if (iAge > 0 && - (tmpAge == 0 || tmpAge > iAge)) - { - // - tmpAge = iAge; - tmpItem = iItem; - } - } - - // - if (tmpAge > 0) - { - // - result = tmpAge; - item = tmpItem; - } - - // - return result; -} - -// -int FindMaxProfitIndex( - XPosition &positions[] // Position Collection -) -{ - // - int result = -1; - - // - int positionsCount = ArraySize(positions); - if (!IsValidSize(positionsCount)) - { - return result; - } - - // - double max = 0; - for (int i = 0; i < positionsCount; i++) - { - // - XPosition iPosition = positions[i]; - if (iPosition.profit <= 0) - { - continue; - } - - // - if (max == 0 || - max < iPosition.profit) - { - // - result = i; - max = iPosition.profit; - } - } - - // - return result; -} - -// -int FindMinProfitIndex( - XPosition &positions[] // Position Collection -) -{ - // - int result = -1; - - // - int positionsCount = ArraySize(positions); - if (!IsValidSize(positionsCount)) - { - return result; - } - - // - double min = 0; - for (int i = 0; i < positionsCount; i++) - { - // - XPosition iPosition = positions[i]; - if (iPosition.profit <= 0) - { - continue; - } - - // - if (min == 0 || - min > iPosition.profit) - { - // - result = i; - min = iPosition.profit; - } - } - - // - return result; -} - -// -int ExtractInProfitPositions( - XPosition &positions[], // Position Collection - XPosition &inProfits[] // Result -) -{ - // - int result = 0; - - // - Clean(inProfits); - - // - int positionsCount = ArraySize(positions); - if (!IsValidSize(positionsCount)) - { - return result; - } - - // - for (int i = 0; i < positionsCount; i++) - { - // - XPosition iPosition = positions[i]; - - // - if (iPosition.profit > 0) - { - // - AddRef( - iPosition, - inProfits // - ); - } - } - - // - result = ArraySize(inProfits); - - // - return result; -} - -// -int FindMaxDrawdownIndex( - XPosition &positions[] // Position Collection -) -{ - // - int result = -1; - - // - int positionsCount = ArraySize(positions); - if (!IsValidSize(positionsCount)) - { - return result; - } - - // - double max = 0; - for (int i = 0; i < positionsCount; i++) - { - // - XPosition iPosition = positions[i]; - if (iPosition.profit >= 0) - { - continue; - } - - // - if (max == 0 || - MathAbs(max) < MathAbs(iPosition.profit)) - { - // - result = i; - max = iPosition.profit; - } - } - - // - return result; -} - -// -int FindMinDrawdownIndex( - XPosition &positions[] // Position Collection -) -{ - // - int result = -1; - - // - int positionsCount = ArraySize(positions); - if (!IsValidSize(positionsCount)) - { - return result; - } - - // - double min = 0; - for (int i = 0; i < positionsCount; i++) - { - // - XPosition iPosition = positions[i]; - if (iPosition.profit >= 0) - { - continue; - } - - // - if (min == 0 || - min > iPosition.profit) - { - // - result = i; - min = iPosition.profit; - } - } - - // - return result; -} - -// -int ExtractInDrawdownPositions( - XPosition &positions[], // Position Collection - XPosition &inDradowns[] // Result -) -{ - // - int result = 0; - - // - Clean(inDradowns); - - // - int positionsCount = ArraySize(positions); - if (!IsValidSize(positionsCount)) - { - return result; - } - - // - for (int i = 0; i < positionsCount; i++) - { - // - XPosition iPosition = positions[i]; - - // - if (iPosition.profit < 0) - { - // - AddRef( - iPosition, - inDradowns // - ); - } - } - - // - result = ArraySize(inDradowns); - - // - return result; -} - -// -// Check Filters ... - -// -// Magic Filter ... -template -bool IsMagicFilterPassed( - ulong magic, - bool filterByMagic, - T &item - // -) -{ - // - return !filterByMagic - ? true - : !NotEmpty(magic) - ? false - : magic == item.magic; -} - -// -// Symbol Filter ... -template -bool IsSymbolFilterPassed( - string symbol, - T &item - // -) -{ - // - return !IsValid(symbol) - ? true - : symbol == item.symbol; -} - -// -// Provider Filter ... -template -bool IsProviderFilterPassed( - string provider, - T &item - // -) -{ - // - return !IsValid(provider) - ? true - : provider == item.provider; -} - -// -// Period Filter ... -template -bool IsPeriodFilterPassed( - ENUM_TIMEFRAMES period, - T &item - // -) -{ - // - return !IsValid(period) - ? true - : period == item.period; -} - -// -// Type Filter ... -template -bool IsTypeFilterPassed( - ENUM_POSITION_TYPE type, - T &item - // -) -{ - // - bool result = type == item.type; - - // - return result; -} -template -bool IsTypeFilterPassed( - ENUM_X_POSITION_TYPES type, - T &item - // -) -{ - // - bool result = type == NULL || type == X_POSITION_TYPE_ALL - ? true - : ((type == X_POSITION_TYPE_LONG && ((int)item.type == (int)POSITION_TYPE_BUY || (int)item.type == (int)ORDER_TYPE_BUY)) || - (type == X_POSITION_TYPE_SHORT && ((int)item.type == (int)POSITION_TYPE_SELL || (int)item.type == (int)ORDER_TYPE_SELL))); - - // - return result; -} -template -bool IsTypeFilterPassed( - ENUM_ORDER_TYPE type, - T &item - // -) -{ - // - return type == NULL - ? true - : type == item.type; -} -template -bool IsTypeFilterPassed( - ENUM_DEAL_TYPE type, - T &item - // -) -{ - // - return type == NULL - ? true - : type == item.type; -} - -// -// Mode Filter ... -template -bool IsModeFilterPassed( - ENUM_X_ORDER_MODES mode, - T &item - // -) -{ - // - return mode == NULL - ? true - : mode == item.mode; -} - -// -// Entry Filter ... -template -bool IsEntryFilterPassed( - ENUM_DEAL_ENTRY entry, - T &item - // -) -{ - // - return entry == NULL - ? true - : entry == item.entry; -} - -// -// Reason Filter ... -template -bool IsReasonFilterPassed( - ENUM_DEAL_REASON reason, - T &item - // -) -{ - // - return reason == NULL - ? true - : reason == item.reason; -} - -// -// State Filter ... -template -bool IsStateFilterPassed( - ENUM_ORDER_STATE state, - T &item - // -) -{ - // - return state == NULL - ? true - : state == item.state; -} - -// - -// -// Find Specific Item Index inside a Collection ... -template -int FindIndex( - T &item, // Item to Find - const T &items[] // Items for Search -) -{ - // - int result = -1; - - // - // Check Item Validation ... - if (!item.IsValid()) - { - return result; - } - - // - int itemsCount = ArraySize(items); - if (itemsCount <= 0) - { - return result; - } - - // - for (int i = 0; i < itemsCount; i++) - { - // - T iItem = items[i]; - - // - // Validate Item ... - if (!iItem.IsValid()) - { - continue; - } - - // - bool isSame = item.IsSameAs(iItem); - if (isSame && result <= -1) - { - // - result = i; - break; - } - } - - // - return result; -} - -// -// -// Calculate Positions Profit Summary ... -double SpecifiedCalculatePositionsProfit( - XPosition &positions[] // Source -) -{ - // - double result = 0; - - // - int positionsCount = ArraySize(positions); - if (positionsCount <= 0) - { - return result; - } - - // - for (int i = 0; i < positionsCount; i++) - { - // - XPosition iPosition = positions[i]; - - // - result += iPosition.profit; - } - - // - return result; -} - -// -// Calculate Required Profit for Hedging ... -double SpecifiedCalculateRequiredProfitForHedge( - XPosition &positions[], // Source - double mMinProfitPerTrade, - double mMinProfitPerVolumeFactor // -) -{ - // - double result = 0; - - // - int positionsCount = ArraySize(positions); - if (positionsCount <= 0) - { - return result; - } - - // - bool isHedgingEnable = mMinProfitPerTrade > 0 && mMinProfitPerVolumeFactor > 0; - if (!isHedgingEnable) - { - return result; - } - - // - for (int i = 0; i < positionsCount; i++) - { - // - XPosition iPosition = positions[i]; - - // - if (mMinProfitPerTrade > 0 && mMinProfitPerVolumeFactor > 0) - { - // - result += - ((iPosition.volume / mMinProfitPerVolumeFactor) * - mMinProfitPerTrade) + - (-1 * iPosition.swap); - } - } - - // - return result; -} - -// -bool SpecifiedIsPositionsReadyForHedge( - XPosition &positions[], // Source - double mMinProfitPerTrade, - double mMinProfitPerVolumeFactor // -) -{ - // - double profit = SpecifiedCalculatePositionsProfit(positions); - double requiredProfit = SpecifiedCalculateRequiredProfitForHedge( - positions, - mMinProfitPerTrade, - mMinProfitPerVolumeFactor // - ); - - // - bool result = requiredProfit > 0 - ? profit >= requiredProfit - : profit > requiredProfit; - - // - return result; -} - -// -int FindCoverageDrawdownPosition( - XPosition &position, // In Drawdown Position - XPosition &inProfits[], // In Profit Positions - XPosition &coverage[], // Coverage Positons - double mMinProfitPerTrade, - double mMinProfitPerVolumeFactor // -) -{ - // - int result = 0; - - // - Clean(coverage); - - // - if (!position.IsValid() || position.profit >= 0) - { - return result; - } - - // - int inProfitsCount = ArraySize(inProfits); - if (!IsValidSize(inProfitsCount)) - { - return result; - } - - // - // Copy in Profits to TMP ... - XPosition tmp[]; - Copy( - inProfits, - tmp // - ); - - // - bool isCoverPassed = false; - while (!isCoverPassed || ArraySize(tmp) > 0) - { - // - XPosition max; - int idx = FindMaxProfitIndex(tmp); - if (idx >= 0) - { - // - if (tmp[idx].profit > 0) - { - AddRef( - tmp[idx], - coverage // - ); - - // - ArrayRemove( - tmp, - idx, - 1 // - ); - } - } - - // - // Check Cover Passed ... - XPosition tmpPositions[]; - Copy( - coverage, - tmpPositions // - ); - AddRef( - position, - tmpPositions // - ); - - // - double profits = SpecifiedCalculatePositionsProfit(tmpPositions); - double requiredProfit = SpecifiedCalculateRequiredProfitForHedge( - tmpPositions, - mMinProfitPerTrade, - mMinProfitPerVolumeFactor // - ); - isCoverPassed = profits >= requiredProfit; - if (isCoverPassed) - { - break; - } - - // - if (!isCoverPassed && ArraySize(tmp) == 0) - { - break; - } - } - - // - result = ArraySize(coverage); - - // - return result; -} - -// -// Extract a Collection of Positions SL ... -int ExtractSLs( - XPosition &positions[], - double &sls[] // -) -{ - // - int result = 0; - - // - Clean(sls); - - // - int positionsCount = ArraySize(positions); - if (!IsValidSize(positionsCount)) - { - return result; - } - - // - for (int i = 0; i < positionsCount; i++) - { - // - XPosition iPosition = positions[i]; - - // - if (iPosition.sl > 0) - { - // - Add( - iPosition.sl, - sls // - ); - } - } - - // - result = ArraySize(sls); - - // - return result; -} - -// -// Extract a Colletion of Positions TP ... -int ExtractTPs( - XPosition &positions[], - double &tps[] // -) -{ - // - int result = 0; - - // - Clean(tps); - - // - int positionsCount = ArraySize(positions); - if (!IsValidSize(positionsCount)) - { - return result; - } - - // - for (int i = 0; i < positionsCount; i++) - { - // - XPosition iPosition = positions[i]; - - // - if (iPosition.tp > 0) - { - // - Add( - iPosition.tp, - tps // - ); - } - } - - // - result = ArraySize(tps); - - // - return result; -} - -// -// Retrieve String Representation ... -string ToString(ENUM_X_SIGNAL_EXECUTION_RESULT value) -{ - // - string result = NULL; - - // - switch (value) - { - // - case X_SIGNAL_EXECUTION_UNKNOWN: - result = "Unknown"; - break; - - // - case X_SIGNAL_EXECUTION_SUCCEED: - result = "Succed"; - break; - - // - case X_SIGNAL_EXECUTION_FAILED_SPREAD: - result = "Spread more than Max Allowed"; - break; - - // - case X_SIGNAL_EXECUTION_FAILED_NO_EQUITY: - result = "No Equity for Trade"; - break; - - // - case X_SIGNAL_EXECUTION_FAILED_PRICE_ERROR: - result = "Price Error"; - break; - - // - case X_SIGNAL_EXECUTION_FAILED_MAX_REACHED: - result = "Max Allowed Positions Reached"; - break; - - // - case X_SIGNAL_EXECUTION_FAILED_INVALID_PARAMS: - result = "Invalid Params"; - break; - } - - // - return result; -} - -// -// Converts Position Type to Order Type ... -ENUM_ORDER_TYPE ToOrderType(ENUM_POSITION_TYPE value) -{ - // - bool isLong = IsLong(value); - - // - ENUM_ORDER_TYPE result = - isLong - ? ORDER_TYPE_BUY - : ORDER_TYPE_SELL; - - // - return result; -} -ENUM_ORDER_TYPE ToOrderType(ENUM_X_POSITION_TYPES value) -{ - // - ENUM_POSITION_TYPE mType = - value == X_POSITION_TYPE_SHORT - ? POSITION_TYPE_SELL - : POSITION_TYPE_BUY; - - // - bool isLong = IsLong(mType); - - // - ENUM_ORDER_TYPE result = - isLong - ? ORDER_TYPE_BUY - : ORDER_TYPE_SELL; - - // - return result; -} - -// -// Tagging ... - -// -// Generate Specified Tag for Using in Comments ... -string GeneratePeriodTag(ENUM_TIMEFRAMES period) -{ - // - string strPeriod = ToString(period); - return Surround( - XPeriodToken, - strPeriod - // - ); -} - -// -// Extract Period from a Tagged string ... -ENUM_TIMEFRAMES ExtractPeriod(string value) -{ - // - ENUM_TIMEFRAMES result = NULL; - - // - string pStr = ParseStringSurrounded( - value, - XPeriodToken - // - ); - if (!IsValid(pStr)) - { - return result; - } - - // - result = ToPeriod(pStr); - - // - return result; -} - -// Generate Specified Tag for Using in Comments ... -string GenerateProviderTag(string provider) -{ - // - return Surround( - XProviderToken, - provider - // - ); -} - -// -// Extract Provider from a Tagged string ... -string ExtractProvider(string value) -{ - // - return ParseStringSurrounded( - value, - XProviderToken - // - ); -} - -// -// Generate Support Comment Tag ... -string GenerateSupportTag(ulong ticket) -{ - // - return Surround( - XSupportToken, - ticket - // - ); -} - -// -// Extract Support Positions from a Tagged string ... -ulong ExtractSupportedTicket(string value) -{ - // - return ParseLongSurrounded( - value, - XSupportToken - // - ); -} - -// -// Extract Support ... -template -int ExtractSupports( - T &source[], - T &dest[] // Result ... -) -{ - // - int result = 0; - - // - Clean(dest); - - // - int sourceCount = ArraySize(source); - if (!IsValidSize(sourceCount)) - { - return result; - } - - // - for (int i = 0; i < sourceCount; i++) - { - // - T iSource = source[i]; - - // - ulong isSupport = ExtractSupportedTicket(iSource.comment) > 0; - ulong iEQMSupport = ExtractEQMSupportedTicket(iSource.comment) > 0; - if (isSupport || iEQMSupport) - { - // - AddRef( - iSource, - dest // - ); - } - } - - // - result = ArraySize(dest); - - // - return result; -} - -// -// Generate EQM Support Comment Tag ... -string GenerateEQMSupportTag(ulong ticket) -{ - // - return Surround( - XEQMSupportToken, - ticket - // - ); -} - -// -// Extract EQM Support Positions from a Tagged string ... -ulong ExtractEQMSupportedTicket(string value) -{ - // - return ParseLongSurrounded( - value, - XEQMSupportToken - // - ); -} - -// -bool IsSupport(string value) -{ - // - bool result = false; - - // - bool isSupport = ExtractSupportedTicket(value) > 0; - bool isEQMSupport = ExtractEQMSupportedTicket(value) > 0; - - // - result = - // - isSupport - // - || - // - isEQMSupport - // - ; - - // - return result; -} - -// -ulong ExtractParentTicket(string value) -{ - // - ulong result = 0; - - // - if (!IsSupport(value)) - { - return result; - } - - // - result = ExtractSupportedTicket(value); - if (result > 0) - { - return result; - } - - // - result = ExtractEQMSupportedTicket(value); - - // - return result; -} - -// -// SL Trails ... - -// -// Extract SL Trail Level ... -int ExtractSLTrailLevel(string comment) -{ - // - int result = 0; - - // - if (!IsValid(comment)) - { - return result; - } - - // - result = ParseIntSurrounded( - comment, - XSLTrailToken - // - ); - - // - return result; -} - -// -// Generate SL Trail Comment Tag ... -string GenerateSLTrailTag(int level) -{ - // - string result = NULL; - - // - if (level <= 0) - { - return result; - } - - // - result = Surround( - XSLTrailToken, - level - // - ); - - // - return result; -} - -// -// Prepare SL Trail Comment ... -string PrepareSLTrailTag( - const string comment // Original Position Comment ... -) -{ - // - string result = NULL; - - // - int level = 0; - result = comment; - - // - // Check Comment Contains SL Trailing or not ... - int lastTrailLevel = ExtractSLTrailLevel(comment); - if (lastTrailLevel <= 0) - { - level++; - } - else - { - // - level = lastTrailLevel + 1; - string lastLevelStr = GenerateSLTrailTag(lastTrailLevel); - StringReplace( - result, - lastLevelStr, - "" - // - ); - } - - // - // Generate level Comment ... - string levelStr = GenerateSLTrailTag(level); - result += levelStr; - - // - return result; -} - -// -// EQM Support Orders ... - -// -int GenerateEQMOrders( - XSignal &orders[], // Result - XPosition &position, // Supported Position - XOHCLSupRes &supRes, // Data Source - bool longs = true, - bool shorts = true // -) -{ - // - int result = 0; - - // - Clean(orders); - - // - if (!supRes.IsValid() || - !position.IsValid()) - { - return result; - } - - // - if (longs) - { - // - double longLevels[]; - - // - Copy( - supRes.res, - longLevels // - ); - - // - double minSup = GetMin( - supRes.sup // - ); - if (minSup > 0) - { - // - Add( - minSup, - longLevels // - ); - } - - // - ArraySort(longLevels); - - // - if (ArraySize(longLevels) > 2) - { - // - for (int i = 0; i < ArraySize(longLevels) - 2; i++) - { - // - double iSL = longLevels[i]; - double iEntry = longLevels[i + 1]; - double iTP = longLevels[i + 2]; - - // - XSignal iSignal; - bool isPrepared = iSignal.PrepareStopLong( - position.symbol, - XEQMSupportToken, - position.period, - iEntry, - position.volume, - iSL, - iTP // - ); - if (isPrepared) - { - // - string comment = GenerateSupportTag(position.ticket); - iSignal.comment = comment; - - // - AddRef( - iSignal, - orders // - ); - } - } - } - } - - // - if (shorts) - { - // - double shortLevels[]; - - // - Copy( - supRes.sup, - shortLevels // - ); - - // - double maxRes = GetMax( - supRes.res // - ); - if (maxRes > 0) - { - // - Add( - maxRes, - shortLevels // - ); - } - - // - ArraySort(shortLevels); - ArrayReverse(shortLevels); - - // - if (ArraySize(shortLevels) > 2) - { - // - for (int i = 0; i < ArraySize(shortLevels) - 2; i++) - { - // - double iSL = shortLevels[i]; - double iEntry = shortLevels[i + 1]; - double iTP = shortLevels[i + 2]; - - // - XSignal iSignal; - bool isPrepared = iSignal.PrepareStopShort( - position.symbol, - XEQMSupportToken, - position.period, - iEntry, - position.volume, - iSL, - iTP // - ); - if (isPrepared) - { - // - string comment = GenerateSupportTag(position.ticket); - iSignal.comment = comment; - - // - AddRef( - iSignal, - orders // - ); - } - } - } - } - - // - result = ArraySize(orders); - - // - return result; -} - -// -// Count Positions from a Collection ... -void CountPositions( - const XPosition &positions[], - int &longs, - double &longProfits, - double &longVolumes, // - // - int &shorts, - double &shortProfits, - double &shortVolumes // -) -{ - // - longs = 0; - longProfits = 0; - longVolumes = 0; - - // - shorts = 0; - shortProfits = 0; - shortVolumes = 0; - - // - int positionsCount = ArraySize(positions); - if (!IsValidSize(positionsCount)) - { - return; - } - - // - for (int i = 0; i < positionsCount; i++) - { - // - XPosition iPosition = positions[i]; - - // - bool isLong = IsLong(iPosition.type); - if (isLong) - { - // - longs++; - longProfits += iPosition.profit; - longVolumes += iPosition.volume; - } - else - { - // - shorts++; - shortProfits += iPosition.profit; - shortVolumes += iPosition.volume; - } - } -} - -// -// Extract Positions based On Type ... -void ExtractPositions( - XPosition &positions[], - XPosition &longs[], - XPosition &shorts[] // -) -{ - // - int count = ArraySize(positions); - if (!IsValidSize(count)) - { - return; - } - - // - Clean(longs); - Clean(shorts); - - // - for (int i = 0; i < count; i++) - { - // - XPosition iPosition = positions[i]; - - // - bool isLong = IsLong(iPosition.type); - if (isLong) - { - AddRef( - iPosition, - longs // - ); - } - else - { - AddRef( - iPosition, - shorts // - ); - } - } -} - -// -int FindSymbolIndex( - string mSymbol, - XSymbolPositions &mItems[] // -) -{ - // - int result = -1; - - // - if (!IsValid(mSymbol)) - { - return result; - } - - // - int count = ArraySize(mItems); - if (!IsValidSize(count)) - { - return result; - } - - // - for (int i = 0; i < count; i++) - { - // - XSymbolPositions iItem = mItems[i]; - - // - if (iItem.symbol == mSymbol) - { - // - result = i; - break; - } - } - - // - return result; -} - -// -int ExtractSymbolPositions( - XPosition &positions[], - XSymbolPositions &items[], // Holds Result - double mMinProfitPerTrade, - double mMinProfitPerVolumeFactor // -) -{ - // - int result = 0; - - // - int positionsCount = ArraySize(positions); - if (!IsValidSize(positionsCount)) - { - return result; - } - - // - Clean(items); - - // - for (int i = 0; i < positionsCount; i++) - { - // - XPosition iPosition = positions[i]; - - // - if (!iPosition.IsValid()) - { - continue; - } - - // - int itemIDX = FindSymbolIndex( - iPosition.symbol, - items // - ); - if (!IsValidIndex(itemIDX)) - { - // - // Add New One ... - XSymbolPositions item; - item.symbol = iPosition.symbol; - - // - AddRef( - item, - items // - ); - itemIDX = FindSymbolIndex(iPosition.symbol, items); - } - - // - AddRef( - iPosition, - items[itemIDX].positions // - ); - } - - // - result = ArraySize(items); - if (IsValidSize(result)) - { - // - for (int i = 0; i < result; i++) - { - // - items[i].Update( - mMinProfitPerTrade, - mMinProfitPerVolumeFactor // - ); - } - } - - // - return result; -} - -// -// Custom Drawings ... -bool DrawTrendState( - long chartId, - string _prefix, - XOHCL &_bar, - double &support, - double &resistance, - int shoulders = 10, - int subWindow = 0, - color resistanceColor = clrRed, - color supportColor = clrGreen, - color swingHighColor = clrAqua, - color swingLowColor = clrMagenta // -) -{ - // - bool result = false; - - // - result = - // - IsValid(_prefix) && - _bar.IsValid() - // - ; - if (!result) - { - return result; - } - - // - // Find Low Swings ... - - // - int firstSwingLowIndex = FindSwing( - _bar.symbol, - _bar.period, - X_SWING_LOW, - shoulders, - _bar.Index() + 1 // - ); - XOHCL firstSwingLowBar; - result = firstSwingLowBar.Init( - _bar.symbol, - _bar.period, - firstSwingLowIndex // - ); - if (!result) - { - return result; - } - - // - int secondSwingLowIndex = FindSwing( - _bar.symbol, - _bar.period, - X_SWING_LOW, - shoulders, - firstSwingLowIndex + 1 // - ); - XOHCL secondSwingLowBar; - result = secondSwingLowBar.Init( - _bar.symbol, - _bar.period, - secondSwingLowIndex // - ); - if (!result) - { - return result; - } - - // - support = secondSwingLowBar.low; - - // - string lowSwingTrendLineName = _prefix + "_Low_Swing_Trend"; - - // - result = DrawTrendLine( - chartId, - lowSwingTrendLineName, - subWindow, - secondSwingLowBar.time, - secondSwingLowBar.low, - firstSwingLowBar.time, - firstSwingLowBar.low, - swingLowColor, - STYLE_SOLID, - 2, - false, - false, - true // Ray Right ... - ); - if (!result) - { - return result; - } - - // - string lowSwingSupportLineName = _prefix + "_Low_Swing_Support"; - - // - result = DrawTrendLine( - chartId, - lowSwingSupportLineName, - subWindow, - secondSwingLowBar.time, - secondSwingLowBar.low, - firstSwingLowBar.time, - secondSwingLowBar.low, - supportColor, - STYLE_SOLID, - 2, - false, - false, - true // Ray Right ... - ); - if (!result) - { - return result; - } - - // - // Find High Swings ... - - // - int firstSwingHighIndex = FindSwing( - _bar.symbol, - _bar.period, - X_SWING_HIGH, - shoulders, - _bar.Index() + 1 // - ); - XOHCL firstSwingHighBar; - result = firstSwingHighBar.Init( - _bar.symbol, - _bar.period, - firstSwingHighIndex // - ); - if (!result) - { - return result; - } - - // - int secondSwingHighIndex = FindSwing( - _bar.symbol, - _bar.period, - X_SWING_HIGH, - shoulders, - firstSwingHighIndex + 1 // - ); - XOHCL secondSwingHighBar; - result = secondSwingHighBar.Init( - _bar.symbol, - _bar.period, - secondSwingHighIndex // - ); - if (!result) - { - return result; - } - - // - resistance = secondSwingHighBar.high; - - // - string highSwingTrendLineName = _prefix + "_High_Swing_Trend"; - - // - result = DrawTrendLine( - chartId, - highSwingTrendLineName, - subWindow, - secondSwingHighBar.time, - secondSwingHighBar.high, - firstSwingHighBar.time, - firstSwingHighBar.high, - swingHighColor, - STYLE_SOLID, - 2, - false, - false, - true // Ray Right ... - ); - if (!result) - { - return result; - } - - // - string highSwingResistanceLineName = _prefix + "_High_Swing_Resistance"; - - // - result = DrawTrendLine( - chartId, - highSwingResistanceLineName, - subWindow, - secondSwingHighBar.time, - secondSwingHighBar.high, - firstSwingHighBar.time, - secondSwingHighBar.high, - resistanceColor, - STYLE_SOLID, - 2, - false, - false, - true // Ray Right ... - ); - if (!result) - { - return result; - } - - // - return result; -} - -// \ No newline at end of file diff --git a/Experts/x-saherelm.x121.ea.mq5 b/Experts/x-saherelm.x121.ea.mq5 index 4a19e827..f6070db5 100644 --- a/Experts/x-saherelm.x121.ea.mq5 +++ b/Experts/x-saherelm.x121.ea.mq5 @@ -130,6 +130,9 @@ input bool x121EATerminalAlerts = false; // Terminal Alerts // // Local Variables ... +// +XTimeTracker x121EATimeTracker; + // string x121EAUsedSymbols[]; XSCX121SetupEA *x121EA; @@ -154,6 +157,10 @@ int OnInit() return INIT_PARAMETERS_INCORRECT; } + // + // Initializitation Succeed Message ... + x121EA.Alert("Initialized Successfully ..."); + // // Init Succeed ... return INIT_SUCCEEDED; @@ -182,12 +189,37 @@ void OnDeinit(const int reason) // delete x121EACTHelper; delete x121EACCHelper; + + // + // De Initialization Succeed ... + x121EA.Alert("De Initialized Successfully ..."); } // // On Tick Handler ... void OnTick() { + // + // Time Tracking ... + + // + if (x121EATimeTracker.IsNewHour()) + { + x121EA.Alert("New Hour ..."); + } + + // + if (x121EATimeTracker.IsNewDay()) + { + x121EA.Alert("New Day ..."); + } + + // + if (x121EATimeTracker.IsNewMonth()) + { + x121EA.Alert("New Mount ..."); + } + // x121EA.OnTick();