diff --git a/MQLTestWorkspace/X121/14030217/Classes/x-saherelm.http.class.ex5 b/MQLTestWorkspace/X121/14030217/Classes/x-saherelm.http.class.ex5 new file mode 100644 index 0000000..57d5c70 Binary files /dev/null and b/MQLTestWorkspace/X121/14030217/Classes/x-saherelm.http.class.ex5 differ diff --git a/MQLTestWorkspace/X121/14030217/Classes/x-saherelm.http.class.mq5 b/MQLTestWorkspace/X121/14030217/Classes/x-saherelm.http.class.mq5 new file mode 100644 index 0000000..e28342d --- /dev/null +++ b/MQLTestWorkspace/X121/14030217/Classes/x-saherelm.http.class.mq5 @@ -0,0 +1,385 @@ +/////////////////////////////////////////////////////// +// +// 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 + +// +// START Definitions ... +// + +// +enum X_HTTP_METHOD +{ + X_HTTP_GET, + X_HTTP_POST +}; + +// +// 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; +} + +// +// END Definitions ... +// + +// +// START Import and Inclused requirements ... +// + +// +// Includes ... +#include "../Libraries/x-saherelm.common.lib.mq5" + +// +// END Import and Inclused requirements ... +// + +// +// START Overrides ... +// + +// +// END Overrides ... +// + +// +// a Class for Manage Account ... +class XSCHttp +{ + // + // 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() + { + } + + // + // START Getter(s)/Setter(s) ... + // + + // + // Path ... + void Path(string value) + { + mPath = value; + } + + 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; + } + + // + // END Getter(s)/Setter(s) ... + // + + // + // START Provided Functions ... + // + + // + // 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; + } +}; + +// +// START Usefull Functions ... +// + +// +// END Usefull Functions ... +// diff --git a/MQLTestWorkspace/X121/14030217/Classes/x-saherelm.x121.provider.class.mq5 b/MQLTestWorkspace/X121/14030217/Classes/x-saherelm.x121.provider.class.mq5 new file mode 100644 index 0000000..2b83bb3 --- /dev/null +++ b/MQLTestWorkspace/X121/14030217/Classes/x-saherelm.x121.provider.class.mq5 @@ -0,0 +1,1851 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Class Library +// ---------------------------------------------- +// Name: XSCX121Provider +// Description: X121 Signal Provider ... +// +// +// 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 ... +// + +// +// START Import and Inclused requirements ... +// + +// +// Includes ... +#include "../Classes/x-saherelm.xprovider.class.mq5" +#include "../Helpers/x-saherelm.x121.xman.helper.class.mq5" + +// +// Library ... +#include "../Libraries/x-saherelm.seriallizer.lib.mq5" + +// +// END Import and Inclused requirements ... +// + +// +// Here we Have to Define an Input Structure Model +// for Provider Class to Handle Helpers Definitions ... +struct X121ProviderInputs +{ + // + // XMAN ... + XMANInputs xmanConfig; +}; + +// +// Model Market Sense based On Current Captured conditions ... +struct X121MarketConditions +{ + // + // Commonly Used Info ... + + // + // Symbol ... + string symbol; + + // + // Period ... + ENUM_TIMEFRAMES period; + + // + // Bar Time ... + datetime barTime; + + // + XCandleRemains barRemains; + + // + // Bar Index ... + int barIndex; + + // + // Check Current Market Condition has Signal or not ... + bool hasSignal; + + // + // If has any Signal, Models it's related info here ... + XSignal signal; + + // + // Support and Resistances ... + // if provides Signal ... + XOHCLSupRes supportResistances; + + // + // Change Price Steps ... + double momentumStep; + + // + XOHCL candles[]; + + // + // INDICATORS Market Sense ... + + // + // XMAN ... + XMANInfo xmanInfo; +}; + +// +#include "../Libraries/x-saherelm.x121.condition.parser.lib.mq5" + +// +// Notified a Signal was Appears ... +typedef void (*TOnSignalConditions)( + X121MarketConditions &info); + +// +// All Available Signal Types ... +enum ENUM_X121_SIGNAL_PROVIDERS +{ + NONE, // NONE ... + XTEST, // TEST ... + X786, // Hadi Khazaee Asl ... + X92, // Hadi Khazaee Asl ... +}; + +// +// END Definitions ... +// + +// +// START Overrides ... +// + +// +// END Overrides ... +// + +// +// a Base Class for All of our EA's ... +class XSCX121Provider : public XSCEABaseProvider +{ + // + // Public ... +public: + // + // Props ... + X121ProviderInputs providedConfig; + X121ProviderInputs currentConfig; + X121ProviderInputs cleanConfig; + + // + // Indicator Helper Classes Instance ... + + // + // XMAN ... + XSCXMANHelper *mXManHelper; + + // + // Pivot Points ... + + // + // Hull and SSL Pivot Points ... + double upZonePivots[]; + double downZonePivots[]; + + // + // Peaks and Vales Verifications Number ... + double peakPivots[]; + double valePivots[]; + + // + double cyclesHHPivots[]; + double cyclesLLPivots[]; + + // + double fibPivots[]; + + // + int pivotsSequentialCount; + + // + // Constructor ... + void XSCX121Provider( + string symbol, // Trading Symbol ... + ENUM_TIMEFRAMES period // Trading Time Frame ... + ) : XSCEABaseProvider(symbol, period) + { + // + mMinPivots = 200; + pivotsSequentialCount = 35; + + // + PrepareTag(); + } + + // + // Deconstructor ... + void ~XSCX121Provider() + { + // + // De construct Helpers ... + delete mXManHelper; + } + + // + virtual void PrepareTag() + { + mTag = "X121Provider((" + mSymbol + ")(" + ToString(mPeriod) + ")"; + } + + // + virtual bool Init() + { + // + bool result = false; + + // + // Instantiate all Indicators Helper Classes ... + + // + // XMAN ... + mXManHelper = new XSCXMANHelper( + mSymbol, + mPeriod); + result = mXManHelper.SetConfig(currentConfig.xmanConfig); + + // + return result; + } + + // + virtual int GetMaxLength() + { + // + int result = -1; + + // + result = MathMax(result, mXManHelper.GetMaxLength()); + + // + return result; + } + + // + virtual int GetCalculatedBars() + { + // + int result = -1; + + // + int mXManBars = mXManHelper.GetCalculatedBars(); + + // + int min = MathMin(1, mXManBars); + + // + int max = MathMax(1, mXManBars); + + // + result = min; + + // + return result; + } + + // + virtual void ProcessBuffers() + { + UpdatePivotPoints(); + } + + // + virtual bool ProcessTick(X121MarketConditions &conditions) + { + // + if (CanIgnoreTick()) + { + return false; + } + + // + return ProcessSignals(conditions); + } + + // + int GetMinPivots() + { + return mMinPivots; + } + + // + X121ProviderInputs GetConfig() + { + // + X121ProviderInputs result; + + // + result = currentConfig; + + // + return result; + } + + // + // Set Available Signallers ... + bool SetSignallers( + string &signallers[]) + { + // + bool result = false; + + // + result = ArraySize(signallers) > 0; + if (!result) + { + return result; + } + + // + Copy( + signallers, + mSignallers); + + // + return result; + } + + // + bool SetConfig(X121ProviderInputs &config) + { + // + bool result = false; + + // + PrepareConfig(config); + + // + result = Init(); + + // + return result; + } + + // + bool ResetDefaultConfig() + { + // + bool result = SetConfig(providedConfig); + + // + return result; + } + + // + bool ShowCleanConfig() + { + // + currentConfig = cleanConfig; + + // + bool result = Init(); + + // + return result; + } + + // + bool ShowDefaultConfig() + { + // + currentConfig = providedConfig; + + // + bool result = Init(); + + // + return result; + } + + // + bool IsAllowedSignaller( + ENUM_X121_SIGNAL_PROVIDERS provider // Signal Provider + ) + { + // + bool result = false; + + // + string providerStr = ToString(provider); + + // + result = Contains( + providerStr, + mSignallers); + + // + return result; + } + + // + // Generate Market Sense ... + X121MarketConditions GetMarketConditions( + int barIndex // Specified Bar Index + ) + { + // + X121MarketConditions result; + + // + // Fill Common Data ... + result.symbol = mSymbol; + result.period = mPeriod; + result.barIndex = barIndex; + + // + datetime barTime = GetCandleTime( + mSymbol, + mPeriod, + barIndex); + result.barTime = barTime; + + // + int remainedCandle = barIndex > 0 + ? barIndex - 1 + : barIndex; + GetCandleRemainsTime( + result.barRemains, + mSymbol, + mPeriod, + remainedCandle); + + // + // Attach Candles Info in XOHCL Model to Conditions ... + int mLoopBackBars = mXManHelper.Loopback(); + XOHCL candles[]; + GetCandles( + candles, + mSymbol, + mPeriod, + 0, + mLoopBackBars); + Copy( + candles, + result.candles); + Clean(candles); + + // + result.xmanInfo = mXManHelper.GetInfo(barIndex); + + // + return result; + } + + // + bool GuardCheck(XGuard &guards[]) + { + // + bool result = false; + + // + Clean(guards); + + // + // Implement Guards Check ... + X121MarketConditions mConditions = GetMarketConditions(1); + + // + // X786 ... + bool canCheckX786 = IsAllowedSignaller(X786); + if (canCheckX786) + { + // + } + + // + result = ArraySize(guards) > 0; + + // + return result; + } + + // + // Add Specific On SignalConditions Event Handler ... + int AddOnSignalConditionEventHandler(TOnSignalConditions handler) + { + // + ArrayResize( + mSignalConditionsEventHandlers, + ArraySize(mSignalConditionsEventHandlers) + 1); + + // + int result = ArraySize(mSignalConditionsEventHandlers) - 1; + mSignalConditionsEventHandlers[result] = handler; + + // + return result; + } + + // + // Remove All On Signal Event Handler ... + void ReoveOnSignalEventHandlers() + { + // + ArrayFree(mSignalConditionsEventHandlers); + } + + // + // Notify a Signal Found on all Event Listeners ... + void NotifyOnSignalConditionsEvent(X121MarketConditions &info) + { + // + int listenerCount = ArraySize(mSignalConditionsEventHandlers); + if (listenerCount <= 0) + { + return; + } + + // + // Loop Through Listeners ... + for (int i = 0; i < listenerCount; i++) + { + // + TOnSignalConditions listener = mSignalConditionsEventHandlers[i]; + + // + listener(info); + } + } + + // + // PIVOTS ... + + // + // Start Pivots Scanning on Instance Creation ... + void ProccessPivotPoints() + { + // + if (mStartPivotScan) + { + return; + } + + // + mStartPivotScan = true; + + // + int scanSize = iBars( + mSymbol, + mPeriod) - + 500; + + // + for (int i = 1; i < scanSize; i++) + { + // + UpdatePivotPoints(i); + + // + int pivotsCount = CountPivots(); + if (pivotsCount >= mMinPivots) + { + break; + } + } + } + + // + // Count Current Pivots ... + int CountPivots() + { + // + int pivotSizes[]; + + // + int upZoneCount = ArraySize(upZonePivots); + if (upZoneCount > 0) + { + // + Add( + upZoneCount, + pivotSizes); + } + + // + int downZoneCount = ArraySize(downZonePivots); + if (downZoneCount > 0) + { + // + Add( + downZoneCount, + pivotSizes); + } + + // + int peaksCount = ArraySize(peakPivots); + if (peaksCount > 0) + { + // + Add( + peaksCount, + pivotSizes); + } + + // + int valesCount = ArraySize(valePivots); + if (valesCount > 0) + { + // + Add( + valesCount, + pivotSizes); + } + + // + int fibsCount = ArraySize(fibPivots); + if (fibsCount > 0) + { + // + Add( + fibsCount, + pivotSizes); + } + + // + int cyclesHHsCount = ArraySize(cyclesHHPivots); + if (cyclesHHsCount > 0) + { + // + Add( + cyclesHHsCount, + pivotSizes); + } + + // + int cyclesLLsCount = ArraySize(cyclesLLPivots); + if (cyclesLLsCount > 0) + { + // + Add( + cyclesHHsCount, + pivotSizes); + } + + // + int result = ArraySize(pivotSizes) > 0 + ? pivotSizes[ArrayMaximum(pivotSizes)] + : 0; + + // + return result; + } + + // + // Generate Exists Support and Resistance based on Given Price ... + XOHCLSupRes GenerateSupportAndResistance( + double price, // Specified Price + int count = 10 // Number of Pivots in Each Side + ) + { + // + XOHCLSupRes result; + + // + UpdatePivotPoints(0); + + // + double pivots[]; + FillPivotPoints(pivots); + + // + // Generate Support and Resistances ... + result = ExtractSupportAndResistance( + price, + pivots, + count); + + // + return result; + } + + // + // Protected ... +protected: + // + // Private ... +private: + // + // CCandle Timer ... + int mCTimerHandler; + + // + // Signal Event Handlers ... + TOnSignalConditions mSignalConditionsEventHandlers[]; + + // + // Make Provided Config in Clean Style ... + void PrepareConfig(X121ProviderInputs &config) + { + // + cleanConfig = config; + + // + // XMAN ... + cleanConfig.xmanConfig.showCandleTimer = false; + cleanConfig.xmanConfig.showCandles = false; + cleanConfig.xmanConfig.showHKCandles = false; + cleanConfig.xmanConfig.showPeaksAndVales = false; + cleanConfig.xmanConfig.showTrends = false; + cleanConfig.xmanConfig.fillTrends = false; + cleanConfig.xmanConfig.showLevels = false; + cleanConfig.xmanConfig.showConsolidations = false; + cleanConfig.xmanConfig.showRibbons = false; + cleanConfig.xmanConfig.showHull = false; + cleanConfig.xmanConfig.showSSLChannel = false; + cleanConfig.xmanConfig.showFibo1Levels = false; + cleanConfig.xmanConfig.showFibo2Levels = false; + cleanConfig.xmanConfig.showFibo3Levels = false; + + // + providedConfig = config; + currentConfig = config; + } + + // + void Calculate(int barIndex) + { + // + mXManHelper.Calculate(barIndex); + } + + // + int mMinPivots; + bool mStartPivotScan; + double mLastMomentumStep; + + // + // Find Required Pivots for Support and Resistance ... + void UpdatePivotPoints( + int barIndex = 0 // Specified Candle ... + ) + { + // + Calculate(barIndex); + + // + // Detect Peask and Vales Pivots ... + + // + // Detect Hull Pivots ... + // find Hull Trend Changes ... + int idx = 0; + + // + // Retrieve XMan Info ... + // since it's the only one Indicator which provides Data here ... + XMANInfo info = mXManHelper.GetInfo(barIndex); + + // + // Define some Variable to count Verified Sequences ... + int fib1Verified = 0; + int fib2Verified = 0; + int fib3Verified = 0; + int peakVerified = 0; + int valeVerified = 0; + int scHHVerified = 0; + int scLLVerified = 0; + int mcHHVerified = 0; + int mcLLVerified = 0; + int lcHHVerified = 0; + int lcLLVerified = 0; + int hcHHVerified = 0; + int hcLLVerified = 0; + + // + // Here we have to select Points to verify their Sequential repeats ... + + // + // Slect Fibonacci Values ... + double selectedFib1 = info.fibLevel1s[idx]; + double selectedFib2 = info.fibLevel2s[idx]; + double selectedFib3 = info.fibLevel3s[idx]; + + // + // Select Peaks and Vales ... + double selectedPeak = info.peaks[idx]; + double selectedVale = info.vales[idx]; + + // + // Select Cycles Highest Highs ... + double selectedSCHH = info.sHHs[idx]; + double selectedMCHH = info.mHHs[idx]; + double selectedLCHH = info.lHHs[idx]; + double selectedHCHH = info.hHHs[idx]; + + // + // Select Cycles Lowest Lows ... + double selectedSCLL = info.sLLs[idx]; + double selectedMCLL = info.mLLs[idx]; + double selectedLCLL = info.lLLs[idx]; + double selectedHCLL = info.hLLs[idx]; + + // + // Now we Have to Loop Bars Until Fillup Required + // Pivots or END available Bars ... + int startIndex = idx; + int endIndex = pivotsSequentialCount + idx + 1; + for (int i = startIndex; i < endIndex; i++) + { + // + int idx = i - startIndex; + + // + // Now We Have to Compare each Selected Value with indexed value ... + + // + // Peaks ... + if (selectedPeak == info.peaks[i]) + { + peakVerified++; + } + else + { + peakVerified = 0; + } + + // + // Vales ... + if (selectedVale == info.vales[i]) + { + valeVerified++; + } + else + { + valeVerified = 0; + } + + // + // Fibo 1 ... + if (selectedFib1 == info.fibLevel1s[i]) + { + fib1Verified++; + } + else + { + fib1Verified = 0; + } + + // + // Fibo 2 ... + if (selectedFib2 == info.fibLevel2s[i]) + { + fib2Verified++; + } + else + { + fib2Verified = 0; + } + + // + // Fibo 3 ... + if (selectedFib3 == info.fibLevel3s[i]) + { + fib3Verified++; + } + else + { + fib3Verified = 0; + } + + // + // SCHH ... + if (selectedSCHH == info.sHHs[i]) + { + scHHVerified++; + } + else + { + scHHVerified = 0; + } + + // + // SCLL ... + if (selectedSCLL == info.sLLs[i]) + { + scLLVerified++; + } + else + { + scLLVerified = 0; + } + + // + // MCHH ... + if (selectedMCHH == info.mHHs[i]) + { + mcHHVerified++; + } + else + { + mcHHVerified = 0; + } + + // + // MCLL ... + if (selectedMCLL == info.mLLs[i]) + { + mcLLVerified++; + } + else + { + mcLLVerified = 0; + } + + // + // LCHH ... + if (selectedLCHH == info.lHHs[i]) + { + lcHHVerified++; + } + else + { + lcHHVerified = 0; + } + + // + // LCLL ... + if (selectedLCLL == info.lLLs[i]) + { + lcLLVerified++; + } + else + { + lcLLVerified = 0; + } + + // + // HCHH ... + if (selectedHCHH == info.hHHs[i]) + { + hcHHVerified++; + } + else + { + hcHHVerified = 0; + } + + // + // HCLL ... + if (selectedHCLL == info.hLLs[i]) + { + hcLLVerified++; + } + else + { + hcLLVerified = 0; + } + } + + // + // Now we Have to check Verifications of each + // Selected Values and if their Passed Sequential Count + // we add them as Pivot Points ... + + // + // Peaks ... + if (peakVerified >= pivotsSequentialCount) + { + // + AddIfNotExists( + selectedPeak, + peakPivots); + } + + // + // Vales ... + if (valeVerified >= pivotsSequentialCount) + { + // + AddIfNotExists( + selectedVale, + valePivots); + } + + // + // Fib 1 ... + if (fib1Verified >= pivotsSequentialCount) + { + // + AddIfNotExists( + selectedFib1, + fibPivots); + } + + // + // Fib 2 ... + if (fib2Verified >= pivotsSequentialCount) + { + // + AddIfNotExists( + selectedFib2, + fibPivots); + } + + // + // Fib 3 ... + if (fib3Verified >= pivotsSequentialCount) + { + // + AddIfNotExists( + selectedFib3, + fibPivots); + } + + // + // SCHH ... + if (scHHVerified >= pivotsSequentialCount) + { + // + AddIfNotExists( + selectedSCHH, + cyclesHHPivots); + } + + // + // SCLL ... + if (scLLVerified >= pivotsSequentialCount) + { + // + AddIfNotExists( + selectedSCLL, + cyclesLLPivots); + } + + // + // MCHH ... + if (mcHHVerified >= pivotsSequentialCount) + { + // + AddIfNotExists( + selectedMCHH, + cyclesHHPivots); + } + + // + // MCLL ... + if (mcLLVerified >= pivotsSequentialCount) + { + // + AddIfNotExists( + selectedMCLL, + cyclesLLPivots); + } + + // + // LCHH ... + if (lcHHVerified >= pivotsSequentialCount) + { + // + AddIfNotExists( + selectedLCHH, + cyclesHHPivots); + } + + // + // LCLL ... + if (lcLLVerified >= pivotsSequentialCount) + { + // + AddIfNotExists( + selectedLCLL, + cyclesLLPivots); + } + + // + // HCHH ... + if (hcHHVerified >= pivotsSequentialCount) + { + // + AddIfNotExists( + selectedHCHH, + cyclesHHPivots); + } + + // + // HCLL ... + if (hcLLVerified >= pivotsSequentialCount) + { + // + AddIfNotExists( + selectedHCLL, + cyclesLLPivots); + } + } + + // + // Fill Pivot Points ... + void FillPivotPoints( + double &result[]) + { + // + Clean(result); + + // + int pCount = CountPivots(); + if (pCount <= 0) + { + return; + } + + // + AddsIfNotExists( + upZonePivots, + result); + + // + AddsIfNotExists( + downZonePivots, + result); + + // + AddsIfNotExists( + peakPivots, + result); + + // + AddsIfNotExists( + valePivots, + result); + + // + AddsIfNotExists( + fibPivots, + result); + + // + AddsIfNotExists( + cyclesHHPivots, + result); + + // + AddsIfNotExists( + cyclesLLPivots, + result); + } + + // + // Available Signallers ... + string mSignallers[]; + + // + // Here we are Capture Conditions and Check Signals ... + // The Signals Must be Unique for each providers ... + bool ProcessSignals(X121MarketConditions &conditions) + { + // + X121MarketConditions mConditions = GetMarketConditions(1); + + // + // BUY ... + + // + Clean(mConditions.signal); + bool hasLongSignal = HasLongSignal(mConditions); + if (hasLongSignal) + { + // + NotifyOnSignalEvent( + mConditions.signal); + NotifyOnSignalConditionsEvent(mConditions); + mWaitUntilNewCandle = true; + + // + conditions = mConditions; + return true; + } + + // + // SELL ... + + // + Clean(mConditions.signal); + bool hasShortignal = HasShortSignal(mConditions); + if (hasShortignal) + { + // + NotifyOnSignalEvent( + mConditions.signal); + NotifyOnSignalConditionsEvent(mConditions); + mWaitUntilNewCandle = true; + + // + conditions = mConditions; + return true; + } + + // + return false; + } + + // + // Check has Long Signal on Each Strategies ... + bool HasLongSignal(X121MarketConditions &conditions) + { + // + bool result = false; + + // + // TODO: Remove ... + double xTPPoint = 30; + double xSLPoint = 20; + + // + // Retrieve Entry Price ... + double entry = GetEntry( + mSymbol, + POSITION_TYPE_BUY); + + // + // Retrieve Pivot Points ... + double pivots[]; + FillPivotPoints(pivots); + XOHCLSupRes supRes = ExtractSupportAndResistance( + entry, + pivots, + 15); + + // + // Cleaning Market Conditions Signal Structure ... + Clean(conditions.signal); + conditions.hasSignal = false; + + // + // X786 ... + bool x786HasSignal = false; + bool canCheckX786 = IsAllowedSignaller(X786); + if (canCheckX786) + { + // + x786HasSignal = + // + IsMarketBullish(conditions) && + IsBullishCandle(conditions.candles[1]) + // conditions.candles[0].low > conditions.candles[1].close + // + ; + + // + if (x786HasSignal) + { + // + Add( + ToString(X786), + conditions.signal.providers); + + // + double sl = conditions.xmanInfo.sLLs[0]; + + // + conditions.signal.r2r = 1; + conditions.signal.riskAmount = 0.01; + conditions.signal.mode = X_ORDER_MODE_MARKET; + conditions.signal.entry = entry; + conditions.signal.sl = sl; + conditions.signal.tp = 0; + + // + conditions.signal.calculateTP = true; + conditions.signal.useRiskAmountAsVolume = true; + + // // + // double supportFactor = ((MathAbs(entry - sl) / 2)); + // NormalizePrice( + // supportFactor, + // conditions.symbol); + + // // + // double supportVolume = 0.01; + + // // + // XSignal lSupport; + // Clean(lSupport); + + // // + // lSupport.r2r = 1; + // lSupport.sl = entry; + // lSupport.volume = supportVolume; + // lSupport.mode = X_ORDER_MODE_STOP; + // lSupport.type = POSITION_TYPE_SELL; + // lSupport.riskAmount = supportVolume; + // lSupport.symbol = conditions.symbol; + // lSupport.entry = entry - supportFactor; + // lSupport.tp = entry - (2 * supportFactor); + + // // + // Add( + // lSupport, + // conditions.signal.supports); + + // // + // // Check Support and Resistance ... + + // // + // Clean(lSupport); + + // // + // supportVolume = 0.01; + // supportFactor = ((MathAbs(entry - sl) / 2.3)); + + // // + // lSupport.r2r = 1; + // lSupport.sl = entry; + // lSupport.volume = supportVolume; + // lSupport.mode = X_ORDER_MODE_STOP; + // lSupport.type = POSITION_TYPE_SELL; + // lSupport.riskAmount = supportVolume; + // lSupport.symbol = conditions.symbol; + // lSupport.entry = entry - supportFactor; + // lSupport.tp = entry - (2 * supportFactor); + + // // + // Add( + // lSupport, + // conditions.signal.supports); + + // // + // // Check TP Calculate ... + + // // + // Clean(lSupport); + + // // + // supportVolume = 0.01; + // supportFactor = ((MathAbs(entry - sl) / 2.3)); + + // // + // lSupport.r2r = 1; + // lSupport.sl = entry; + // lSupport.volume = supportVolume; + // lSupport.mode = X_ORDER_MODE_STOP; + // lSupport.type = POSITION_TYPE_BUY; + // lSupport.riskAmount = supportVolume; + // lSupport.symbol = conditions.symbol; + // lSupport.entry = entry + supportFactor; + // lSupport.tp = entry + (2 * supportFactor); + + // // + // Add( + // lSupport, + // conditions.signal.supports); + } + } + + // + bool x92HasSignal = false; + bool canCheckX92 = IsAllowedSignaller(X92); + if (canCheckX92) + { + // + x92HasSignal = + // + false + // + ; + + // + if (x92HasSignal) + { + // + Add( + ToString(X92), + conditions.signal.providers); + + // + double sl = conditions.xmanInfo.mLLs[0]; + + // + conditions.signal.r2r = 1.5; + conditions.signal.riskAmount = 0.01; + conditions.signal.mode = X_ORDER_MODE_MARKET; + conditions.signal.entry = entry; + conditions.signal.sl = sl; + conditions.signal.tp = 0; + + // + conditions.signal.calculateTP = true; + conditions.signal.useRiskAmountAsVolume = true; + } + } + + // + result = + // + x786HasSignal + // + || + // + x92HasSignal + // + ; + + // + if (result) + { + // + conditions.supportResistances = supRes; + conditions.momentumStep = mLastMomentumStep; + + // + conditions.signal.symbol = mSymbol; + conditions.signal.period = mPeriod; + conditions.signal.type = POSITION_TYPE_BUY; + + // + conditions.hasSignal = true; + } + + // + return result; + } + + // + // Check has Short Signal on Each Strategies ... + bool HasShortSignal(X121MarketConditions &conditions) + { + // + bool result = false; + + // + // TODO: Remove this ... + double xTPPoint = 30; + double xSLPoint = 20; + + // + // Retrieve Entry Price ... + double entry = GetEntry( + mSymbol, + POSITION_TYPE_SELL); + + // + // Retrieve Pivot Points ... + double pivots[]; + FillPivotPoints(pivots); + XOHCLSupRes supRes = ExtractSupportAndResistance( + entry, + pivots, + 15); + + // + // Cleaning Market Conditions Signal Structure ... + Clean(conditions.signal); + conditions.hasSignal = false; + + // + // X786 ... + bool x786HasSignal = false; + bool canCheckX786 = IsAllowedSignaller(X786); + if (canCheckX786) + { + // + x786HasSignal = + // + false + // + ; + + // + if (x786HasSignal) + { + // + Add( + ToString(X786), + conditions.signal.providers); + + // + // double slPoint = xSLPoint; + // double slPrice = PointToPrice( + // conditions.symbol, + // slPoint); + // double sl = entry + slPrice; + + // // + // // TODO: Remove this to X121EA Class for Handling risk to reward and riskAmount and use risk amount as static volume + // // by access X121SignalProvider struture ... + // double tpPoint = xTPPoint; + // double tpPrice = PointToPrice( + // conditions.symbol, + // tpPoint); + // double tp = entry - tpPrice; + + // + double sl = conditions.xmanInfo.mHHs[0]; + + // + conditions.signal.r2r = 1.5; + conditions.signal.riskAmount = 0.01; + conditions.signal.mode = X_ORDER_MODE_MARKET; + conditions.signal.entry = entry; + conditions.signal.sl = sl; + conditions.signal.tp = 0; // tp; + + // + // conditions.signal.ignoreSL = false; + conditions.signal.calculateTP = true; + conditions.signal.useRiskAmountAsVolume = true; + } + } + + // + bool x92HasSignal = false; + bool canCheckX92 = IsAllowedSignaller(X92); + if (canCheckX92) + { + // + x92HasSignal = + // + false + // + // + ; + + // + if (x92HasSignal) + { + // + Add( + ToString(X92), + conditions.signal.providers); + + // + double sl = conditions.xmanInfo.mHHs[0]; + + // + conditions.signal.r2r = 1.5; + conditions.signal.riskAmount = 0.01; + conditions.signal.mode = X_ORDER_MODE_MARKET; + conditions.signal.entry = entry; + conditions.signal.sl = sl; + conditions.signal.tp = 0; + + // + conditions.signal.calculateTP = true; + conditions.signal.useRiskAmountAsVolume = true; + } + } + + // + result = + // + x786HasSignal + // + || + // + x92HasSignal + // + ; + + // + if (result) + { + // + conditions.supportResistances = supRes; + conditions.momentumStep = mLastMomentumStep; + + // + conditions.signal.symbol = mSymbol; + conditions.signal.period = mPeriod; + conditions.signal.type = POSITION_TYPE_SELL; + + // + conditions.hasSignal = true; + } + + // + return result; + } + + // + // SIGNALLER Tools ... + + // + double CalculateX786LognStop(const X121MarketConditions &conditions) + { + // + double result = 0; + + // + double val1 = conditions.xmanInfo.trends[0]; + double val2 = conditions.xmanInfo.sslcDowns[0]; + double val3 = conditions.xmanInfo.hullDowns[0]; + double val4 = conditions.xmanInfo.ribbon1s[0]; + double val5 = conditions.xmanInfo.ribbon2s[0]; + double val6 = conditions.xmanInfo.ribbon3s[0]; + double val7 = conditions.xmanInfo.ribbon4s[0]; + double val8 = conditions.xmanInfo.ribbon5s[0]; + double val9 = conditions.xmanInfo.ribbon6s[0]; + + // + double min = MathMin(val1, val2); + min = MathMin(min, val3); + min = MathMin(min, val4); + min = MathMin(min, val5); + min = MathMin(min, val6); + min = MathMin(min, val7); + min = MathMin(min, val8); + min = MathMin(min, val9); + + // + double max = MathMax(val1, val2); + max = MathMax(max, val3); + max = MathMax(max, val4); + max = MathMax(max, val5); + max = MathMax(max, val6); + max = MathMax(max, val7); + max = MathMax(max, val8); + max = MathMax(max, val9); + + // + return result; + } +}; + +// +// START Definitions ... +// + +// +// Model Signal Providers Definitions ... +struct X121SignalProvider +{ + // + // Provider use Which Symbol ... + string symbol; + + // + // Allowed Providers ... + string providers[]; + + // + // Provider use Which Time Frame ... + ENUM_TIMEFRAMES period; + + // + // Risk Amount Per Trades Related to Time Frames ... + // Percent of Available Balance ... + double riskAmount; + + // + // Use Provided Risk Amount as Static Volume ... + bool useRiskAmountAsStaticVolume; + + // + // Provider ... + XSCX121Provider *provider; +}; + +// +// END Definitions ... +// + +// +// START Usefull Functions ... +// + +// +// Add Specific Provider to List ... +void Add( + X121SignalProvider &item, // item want to add + X121SignalProvider &buffer[] // Destination buffer +) +{ + // + ArrayResize( + buffer, + ArraySize(buffer) + 1); + + // + buffer[ArraySize(buffer) - 1] = item; +} + +// +// Generate Identifier Tag ... +string GenerateTag(X121SignalProvider &descriptor) +{ + // + string result = ""; + + // + result = descriptor.symbol + "," + ToString(descriptor.period); + + // + return result; +} + +// +// Converts a Signal provider to String ... +string ToString(ENUM_X121_SIGNAL_PROVIDERS provider) +{ + return EnumToString(provider); +} + +// +// convert an String to Signal provider ... +ENUM_X121_SIGNAL_PROVIDERS ToProvider(string provider) +{ + // + ENUM_X121_SIGNAL_PROVIDERS result = NONE; + + // + if (ToString(NONE) == provider) + { + result = NONE; + } + else if (ToString(XTEST) == provider) + { + result = XTEST; + } + else if (ToString(X786) == provider) + { + result = X786; + } + else if (ToString(X92) == provider) + { + result = X92; + } + // else if (ToString(X110) == provider) + // { + // result = X110; + // } + // else if (ToString(X121) == provider) + // { + // result = X121; + // } + // else if (ToString(X128) == provider) + // { + // result = X128; + // } + + // + return result; +} + +// +// Extract Provider Type from Signal Commnet ... +ENUM_X121_SIGNAL_PROVIDERS ExtractPositionProvider(XPosition &position) +{ + // + ENUM_X121_SIGNAL_PROVIDERS result = NONE; + + // + string providerStr = + ExtractString( + position.comment, + XProviderToken + "(", + ")"); + if (StringLen(providerStr) <= 0) + { + return result; + } + + // + result = ToProvider(providerStr); + + // + return result; +} + +// +// List All Available Providers ... +void GetAllProviders( + ENUM_X121_SIGNAL_PROVIDERS &result[] // Hold Result ... +) +{ + // + Clean(result); + + // + // XTEST ... + ArrayResize( + result, + ArraySize(result) + 1); + result[ArraySize(result) - 1] = XTEST; + + // + // X786 ... + ArrayResize( + result, + ArraySize(result) + 1); + result[ArraySize(result) - 1] = X786; + + // + // X92 ... + ArrayResize( + result, + ArraySize(result) + 1); + result[ArraySize(result) - 1] = X92; + + // // + // // X110 ... + // ArrayResize( + // result, + // ArraySize(result) + 1); + // result[ArraySize(result) - 1] = X110; + + // // + // // X121 ... + // ArrayResize( + // result, + // ArraySize(result) + 1); + // result[ArraySize(result) - 1] = X121; + + // // + // // X128 ... + // ArrayResize( + // result, + // ArraySize(result) + 1); + // result[ArraySize(result) - 1] = X128; +} + +// +// Lis All Available Providers ... +void GetAllProviders( + string &result[] // Hold Result ... +) +{ + // + Clean(result); + + // + ENUM_X121_SIGNAL_PROVIDERS providers[]; + GetAllProviders(providers); + int providersCount = ArraySize(providers); + if (providersCount <= 0) + { + return; + } + + // + for (int i = 0; i < providersCount; i++) + { + // + ENUM_X121_SIGNAL_PROVIDERS iProvider = providers[i]; + + // + Add( + ToString(iProvider), + result); + } +} + +// +// END Usefull Functions ... +// diff --git a/MQLTestWorkspace/X121/14030217/Classes/x-saherelm.x121.xea.class.ex5 b/MQLTestWorkspace/X121/14030217/Classes/x-saherelm.x121.xea.class.ex5 new file mode 100644 index 0000000..dfd4246 Binary files /dev/null and b/MQLTestWorkspace/X121/14030217/Classes/x-saherelm.x121.xea.class.ex5 differ diff --git a/MQLTestWorkspace/X121/14030217/Classes/x-saherelm.x121.xea.class.mq5 b/MQLTestWorkspace/X121/14030217/Classes/x-saherelm.x121.xea.class.mq5 new file mode 100644 index 0000000..b5aed47 --- /dev/null +++ b/MQLTestWorkspace/X121/14030217/Classes/x-saherelm.x121.xea.class.mq5 @@ -0,0 +1,1711 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Class Library +// ---------------------------------------------- +// Name: XSCX121EA +// Description: an Expert Class which +// used 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 + +// +// START Import and Inclused requirements ... +// + +// +// Includes ... +#include "../Classes/x-saherelm.xea.class.mq5" +#include "../Libraries/x-saherelm.x121.draw.lib.mq5" +#include "../Classes/x-saherelm.x121.provider.class.mq5" + +// +// END Import and Inclused requirements ... +// + +// +// START Definitions ... +// + +// +// END Definitions ... +// + +// +// START Overrides ... +// + +// +// END Overrides ... +// + +// +// an Expert Advisor Class by X121Provider ... +class XSCX121EA : public XSCBaseEA +{ + // + // Public ... +public: + // + // Props ... + + // + // Constructor ... + void XSCX121EA( + string symbol, // Trading Symbol + ENUM_TIMEFRAMES period, // Trading Time Frame + ulong magic, // Magic Number + int slippage, // Slippgae + double minProfitPerTrade, // Min Profit Per Trade based On Volume Factor (Hedge) + double minProfitPerVolumeFactor, // Min Volume Factor for Calculating Profit (Hedge) + TOnStopLoss onStopLossTriggered = NULL, // On StopLoass Triggered Event Handler + TOnTakeProfit onTakeProfitTriggered = NULL, // On TakeProfit Triggered 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 + TOnSignalConditions onSignalConditions = NULL // On SignalConditions Event Handler + ) : XSCBaseEA(symbol, + period, + magic, + slippage, + onStopLossTriggered, + onTakeProfitTriggered, + onDealsChangedHandler, + onOrdersChangedHandler, + onPositionsChangedHandler, + onTradeStateChangedHandler) + { + // + mOnSignalConditions = onSignalConditions; + + // + mMinProfitPerTrade = minProfitPerTrade; + mMinProfitPerVolumeFactor = minProfitPerVolumeFactor; + } + + // + // DeConstructor ... + void ~XSCX121EA() + { + // + // Delete All Registered Providers ... + int providersCount = ArraySize(mProviders); + if (providersCount > 0) + { + // + for (int i = 0; i < providersCount; i++) + { + // + X121SignalProvider iProvider = mProviders[i]; + + // + delete iProvider.provider; + } + } + } + + // + // START Properties ... + // + + // + // Min Profit Per Trade ... + + // + bool MinProfitPerTrade(double value) + { + // + bool result = false; + + // + if (value <= 0) + { + return result; + } + + // + result = value > 0; + if (value == mMinProfitPerTrade) + { + return result; + } + + // + mMinProfitPerTrade = value; + + // + return result; + } + + // + double MinProfitPerTrade() + { + return mMinProfitPerTrade; + } + + // + // Min Profit Per Volume Factor ... + + // + bool MinProfitPerVolumeFactor(double value) + { + // + bool result = false; + + // + if (value <= 0) + { + return result; + } + + // + result = value > 0; + if (value == mMinProfitPerVolumeFactor) + { + return result; + } + + // + mMinProfitPerVolumeFactor = value; + + // + return result; + } + + // + double MinProfitPerVolumeFactor() + { + return mMinProfitPerVolumeFactor; + } + + // + // Add Provider ... + bool AddProvider( + X121SignalProvider &provider // Specific Provider ... + ) + { + // + bool result = false; + + // + // Validate Provider ... + if (provider.symbol == NULL || + provider.period == NULL || + provider.riskAmount <= 0 || + StringLen(provider.symbol) == 0 || + ArraySize(provider.providers) == 0) + { + return result; + } + + // + // Check Exists or not ... + int idx = GetProviderIndex( + provider.symbol, + provider.period); + if (idx >= 0) + { + return result; + } + + // + PrepareProviderConfig(); + + // + // Make Instance of X121Provider Class ... + provider.provider = new XSCX121Provider( + provider.symbol, + provider.period); + + // + // Attach Event Listener ... + if (mOnSignalConditions != NULL) + { + // + // Attach Event Handlers ... + provider.provider.AddOnSignalConditionEventHandler(mOnSignalConditions); + } + + // + // Set Signallers to Provider Class ... + result = provider.provider.SetSignallers(provider.providers); + if (!result) + { + return result; + } + + // + // Initialize Provider ... + result = provider.provider.SetConfig(mProviderConfig); + + // + // Add Prepared Provider to Providers ... + Add( + provider, + mProviders); + + // + return result; + } + + // + // Add Providers ... + int AddProviders( + X121SignalProvider &providers[] // Specific Providers ... + ) + { + // + int result = 0; + + // + int providersCount = ArraySize(providers); + if (providersCount <= 0) + { + return result; + } + + // + for (int i = 0; i < providersCount; i++) + { + // + X121SignalProvider iProvider = providers[i]; + + // + bool isAdded = AddProvider(iProvider); + if (isAdded) + { + result++; + } + } + + // + return result; + } + + // + // END Properties ... + // + + // + // START Overrides ... + // + + // + void OnPositionsChangedHandler(int count) + { + } + + // + // Handle TakeProfit Event ... + void OnTakeProfitTriggered(const XDeal &deal) + { + // + // Since we Use Hedge in Min Profit ... + // Some times a Position Modified and SL Trails ... + // this Position closed through sl Event ... + // here we Must Close positions's Pack Orders ... + + // + // So We Have to Get Positions Pack ... + XPositionPack dealPack; + bool hasPack = mTrader.GetDealPack( + deal, + dealPack); + if (hasPack) + { + HandleClosePack(dealPack); + } + } + + // + // Handle StopLoss Event ... + void OnStopLossTriggered(const XDeal &deal) + { + // + // Since we Use Hedge in Min Profit ... + // Some times a Position Modified and SL Trails ... + // this Position closed through sl Event ... + // here we Must Close positions's Pack Orders ... + + // + // So We Have to Get Positions Pack ... + XPositionPack dealPack; + bool hasPack = mTrader.GetDealPack( + deal, + dealPack); + if (hasPack) + { + HandleClosePack(dealPack); + } + } + + // + // END Overrides ... + // + + // + // START Inheritance Functions ... + // + + // + void PrepareTag() + { + mTag = "X121EA:" + mSymbol + "," + ToString(mPeriod) + (string)mMagic; + } + + // + // Check Providers Guard States ... + bool CheckGuard(XGuard &guards[]) + { + // + bool result = false; + + // + Clean(guards); + + // + // Positions Management ... + HandlePositionManagement(); + + // + int providersCount = ArraySize(mProviders); + if (providersCount <= 0) + { + return result; + } + + // + for (int i = 0; i < providersCount; i++) + { + // + X121SignalProvider iProvider = mProviders[i]; + + // + XGuard iGuards[]; + bool iHasGuard = iProvider.provider.GuardCheck(iGuards); + if (iHasGuard) + { + // + Copy( + iGuards, + guards, + false); + } + } + + // + // Here we Can Implement Custom Guards Senario ... + + // + // Do Management Equity ... + HandleEquityManagement(); + + // + result = ArraySize(guards) > 0; + + // + return result; + } + + // + // Check Providers for Signals ... + bool SignalCheck(XSignal &signals[]) + { + // + bool result = false; + + // + Clean(signals); + + // + // Since We may have Custom Supporting Senarios for Positions + // if there is no Equity or Positions Count Passed ... + // we Clear Account Policies Check here and do it after + // recieveing Signals ... + + // + // Check Providers Count ... + int providersCount = ArraySize(mProviders); + if (providersCount <= 0) + { + return result; + } + + // + // Loop through Providers to Recieve Market Sence based on each them ... + for (int i = 0; i < providersCount; i++) + { + // + // Get provider Descriptor Struct ... + X121SignalProvider iProvider = mProviders[i]; + + // + // Check Provider Pivot Point Ready ... + int iFoundedPivots = iProvider.provider.CountPivots(); + int iReuiredPivots = iProvider.provider.GetMinPivots(); + if (iFoundedPivots < iReuiredPivots) + { + // + // Start Retrieveing Pivot Points ... + iProvider.provider.ProccessPivotPoints(); + + // + // ignore Calculating Signals since Pivot Points recieved ... + continue; + } + + // + // Retrieve Market Consitions from Specified Provider ... + X121MarketConditions iConditions; + bool iHasSignal = iProvider.provider.ProcessTick(iConditions); + + // + // Check there is Signal or not ... + if (iHasSignal && iConditions.hasSignal) + { + // + // Check Signalling is Enabled by Signal type ... + bool isiSignalLong = IsLong(iConditions.signal.type); + if ((isiSignalLong && !mEnableLongs) || + (!isiSignalLong && !mEnableShorts)) + { + continue; + } + + // + // Here we Calculate Signals tp/sl volume and etc based on given + // configurations ... + PrepareConditionsSignal(iConditions); + + // + // Add Signal to Retrieved Signals Collection ... + Add( + iConditions.signal, + signals); + } + } + + // + // Here we proccess all Exists Registered Providers and get + // probably signals and add them signals Array ... + + // + // Check Signals Exists for Processing ... + result = ArraySize(signals) > 0; + + // + // IMPORTANT: + // Since we have to Implement our Signal Execution Senario + // Ignore this here for Default behaviour and implememt or Execution ... + if (result) + { + // + // Create an Array for Holding Allowed To Execute Signals ... + // this filled by given Signals from all providers ... + XSignal allowedSignals[]; + + // + // Check Account has required Equity for open Trades or not ... + bool hasEquity = CheckEquityForTrade(); + if (hasEquity) + { + // + // if Equity Exists ... + + // + // Check Positions Count ... + XPosition positions[]; + int positionsCount = GetPositions(positions); + + // + // Calculate Remained Positions based on configurations ... + int remainedPositionsCount = mMaxAllowedPositions - positionsCount; + + // + int incommingSignalsCount = ArraySize(signals); + + // + // Check incomming signals and remained Positions count ... + if (remainedPositionsCount >= incommingSignalsCount) + { + // + // Since we have necessary Equity for Trade ... + // and also remainedPositions count is bigger than incomming signals ... + // Accept all incomming Signals ... + Copy( + signals, + allowedSignals); + } + else + { + // + // since we have necessary Equity for trade ... + // but incomming Signals count is bigger than Max allowed positions at same time ... + // we have to select only remains count ... + for (int i = 0; i < remainedPositionsCount; i++) + { + // + XSignal iSignal = signals[i]; + + // + Add( + iSignal, + allowedSignals); + } + } + } + else + { + // + // there isn't enough Equity for Trade ... + // How to Select Signals when there is no Equity for Trade ... + + // + // TODO: we can Implement Equity Management here ... + + // + LogMessage("No Equity ..."); + } + + // + // Check Allowed Signals Count ... + int allowedSignalsCount = ArraySize(allowedSignals); + if (allowedSignalsCount > 0) + { + // + // Prepare Allowed Signals for Execution ... + PrepareSignals(allowedSignals); + + // + // Execute Signals oly when allowed ... + int executed = mTrader.ExecuteSignals(allowedSignals); + if (executed > 0) + { + // + // Draw Signal ... + // On Chart ... + DrawSignals( + allowedSignals, + true); + } + } + + // + // Prevent Default Base Signal Execution ... + + // + Clean(signals); + + // + return false; + } + + // + return result; + } + + // + // END Inheritance Functions ... + // + + // + // START Provided Actions ... + // + + // + // END Provided Actions ... + // + + // + // Protected ... +protected: + // + // Private ... +private: + // + // Props ... + X121SignalProvider mProviders[]; + X121ProviderInputs mProviderConfig; + TOnSignalConditions mOnSignalConditions; + + // + double mMinProfitPerTrade; + double mMinProfitPerVolumeFactor; + + // + // Actions ... + + // + // Pepare a Collection Of Signals ... + void PrepareSignals(XSignal &signals[]) + { + // + int signalsCount = ArraySize(signals); + if (signalsCount <= 0) + { + return; + } + + // + for (int i = 0; i < signalsCount; i++) + { + // + PrepareSignal(signals[i]); + } + } + + // + // POSITIONPACK ... + + // + // Check a Position Pack is Ready for Hedging ... + bool IsReadyForEQMHedge(XPositionPack &pack) + { + // + bool result = false; + + // + if (mMinProfitPerTrade <= 0 || + mMinProfitPerVolumeFactor <= 0) + { + return result; + } + + // + if (pack.supportPositionsCount <= 0) + { + return result; + } + + // + double profit = pack.position.profit; + double requiredProfit = + ((pack.position.volume / mMinProfitPerVolumeFactor) * + mMinProfitPerTrade) + + (-1 * pack.position.swap); + + // + for (int i = 0; i < pack.supportPositionsCount; i++) + { + // + XPosition iPosition = pack.supportPositions[i]; + + // + profit += iPosition.profit; + requiredProfit += + ((iPosition.volume / mMinProfitPerVolumeFactor) * + mMinProfitPerTrade) + + (-1 * iPosition.swap); + } + + // + result = profit >= requiredProfit; + + // + return result; + } + + // + // Close a Position Pack and Cancel All of it's Supports ... + bool HandleClosePack(XPositionPack &pack) + { + // + bool result = false; + + // + if (pack.ticket <= 0) + { + return result; + } + + // + XOrder orders[]; + XPosition positions[]; + + // + bool hasPos = pack.position.ticket > 0; + if (hasPos) + { + Add( + pack.position, + positions); + } + + // + bool hasSupportPos = pack.supportPositionsCount > 0; + if (hasSupportPos) + { + // + Copy( + pack.supportPositions, + positions, + false); + } + + // + bool hasSupportOrd = pack.supportOrdersCount > 0; + if (hasSupportOrd) + { + // + Copy( + pack.supportOrders, + orders); + } + + // + string comment = "EQM Close Pack"; + + // + int closed = mTrader.ClosePositions(positions, comment); + int canceled = mTrader.CancelOrders(orders); + + // + result = closed + canceled == ArraySize(orders) + ArraySize(positions); + if (result) + { + // + string message = "EQM Close Position(" + ToString(pack.ticket) + ")'s Pack ..."; + + // + LogMessage(message); + } + + // + return result; + } + + // + // POSITIONMANAGEMENT ... + // + + // + // Calculate Positions Profit Summary ... + double CalculatePositionsProfit( + 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 CalculateRequiredProfitForHedge( + 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.volume / mMinProfitPerVolumeFactor) * + mMinProfitPerTrade) + + (-1 * iPosition.swap); + } + + // + return result; + } + + // + // Manage Positions ... + void HandlePositionManagement() + { + // + // HandleHedgePositionPacks(); + + // + // HandleHedgePositions(); + + // + HandleCloseOrTrailStopMinProfitPositions(); + } + + // + void HandleHedgePositions() + { + // + bool isReady = IsPositionsReadyForEQMHedge(); + if (!isReady) + { + return; + } + + // + XPosition positions[]; + int positionsCount = GetPositions(positions); + + // + string comment = "EQM Hedge Positions ..."; + + // + int closed = mTrader.ClosePositions( + positions, + comment); + bool isClosed = closed == positionsCount; + if (isClosed) + { + // + LogMessage(comment); + } + } + + // + // Close a Position Pack Wen Reached to Specific Profit ... + void HandleHedgePositionPacks() + { + // + XPosition positions[]; + int positionsCount = GetPositions(positions); + if (positionsCount <= 0) + { + return; + } + + // + for (int i = 0; i < positionsCount; i++) + { + // + XPosition iPosition = positions[i]; + + // + XPositionPack iPack; + bool hasPack = mTrader.GetPositionPack( + iPosition.ticket, + iPosition.symbol, + iPosition.period, + iPack); + if (!hasPack) + { + continue; + } + + // + // Check Pack for Open Positions ... + bool isValidPack = iPack.supportPositionsCount > 0; + if (!isValidPack) + { + continue; + } + + // + // we sure a Position has Support and it's support open ... + bool isReady = IsReadyForEQMHedge(iPack); + if (!isReady) + { + continue; + } + + // + bool isClosed = HandleClosePack(iPack); + } + } + + // + // Try to Trail StopLoss or Close Posititons + // when reached Min Profit ... + void HandleCloseOrTrailStopMinProfitPositions() + { + // + // Retrieve In Profit Positions ... + XPosition positions[]; + int positionsCount = GetInProfitPositions(positions); + if (positionsCount <= 0) + { + return; + } + + // + for (int i = 0; i < positionsCount; i++) + { + // + XPosition iPosition = positions[i]; + + // + // Now we have to Calculate min Profit ... + double requiredProfit = + ((iPosition.volume / mMinProfitPerVolumeFactor) * + mMinProfitPerTrade) + + (-1 * iPosition.swap); + + // + // Now we Have to Check if Trailed Before or not ... + int trailLevel = ExtractSLTrailLevel(iPosition.comment); + if (trailLevel > 0) + { + requiredProfit *= (trailLevel + 1); + } + + // + // Check Can Trail or Close on Min Profit ... + bool conditionsPassed = iPosition.profit >= requiredProfit; + if (!conditionsPassed) + { + continue; + } + + // + // Now we have Sure iPosition is Ready for Trailing Stop or Close on Min Profit ... + bool isLong = IsLong(iPosition.type); + + // + // CASE A try to Trail Stop ... + double sl = 0; + double distance = 0; + if ((isLong && (iPosition.price > iPosition.entry && + iPosition.entry > iPosition.sl)) || + (!isLong && (iPosition.price < iPosition.entry && + iPosition.entry < iPosition.sl))) + { + // + // First Trail ... + + // + distance = isLong + ? iPosition.price - iPosition.entry + : iPosition.entry - iPosition.price; + + // + sl = iPosition.entry; + } + else if ((isLong && (iPosition.price > iPosition.sl && + iPosition.entry <= iPosition.sl)) || + (!isLong && (iPosition.price < iPosition.sl && + iPosition.entry >= iPosition.sl))) + { + // + // Trailed Before ... + + // + distance = isLong + ? iPosition.price - iPosition.entry + : iPosition.entry - iPosition.price; + + // + sl = isLong + ? iPosition.sl + distance + : iPosition.sl - distance; + } + + // + // Check Main Selected Position is Support of another Position or not ... + string params[]; + bool isSupport = ExtractSupportParams( + iPosition.comment, + params); + + // + bool isTrailed = false; + bool canTrail = !isSupport && sl > 0 && distance > 0; + if (canTrail) + { + // + string comment = PrepareSLTrailComment(iPosition.comment); + + // + isTrailed = mTrader.Modify( + iPosition.ticket, + sl, + iPosition.tp); + } + if (isTrailed) + { + // + string message = "EQM Trail Position(" + ToString(iPosition.ticket) + ")'s Stop Loss ..."; + + // + LogMessage(message); + + // + continue; + } + + // + // CASE B if not Trail, Close it in Min Profit ... + string comment = "EQM Close Min Profit ..."; + + // + // Check Position has Pack Or Not ... + // if has Pack must Close Pack ... + // if not, Close position itself ... + XPositionPack iPack; + bool hasPack = mTrader.GetPositionPack( + iPosition.ticket, + iPosition.symbol, + iPosition.period, + iPack); + if (hasPack) + { + // + HandleClosePack(iPack); + } + else + { + // + if (!isSupport) + { + // + bool isClosed = mTrader.Close( + iPosition.ticket, + comment); + if (isClosed) + { + // + string message = "EQM Close Position(" + ToString(iPosition.ticket) + ") In Min Profit: " + ToString(iPosition.profit); + + // + LogMessage(message); + } + } + } + } + } + + // + // Check Positions is Ready fro Hedging ... + bool IsPositionsReadyForEQMHedge() + { + // + bool result = false; + + // + if (mMinProfitPerTrade <= 0 || + mMinProfitPerVolumeFactor <= 0) + { + return result; + } + + // + double profit = 0; + double requiredProfit = 0; + + // + XPosition positions[]; + int positionsCount = GetPositions(positions); + if (positionsCount <= 1) + { + return result; + } + + // + profit = CalculatePositionsProfit(positions); + requiredProfit = CalculateRequiredProfitForHedge(positions); + + // + result = profit >= requiredProfit; + + // + return result; + } + + // + // EQUITYMANAGEMENT ... + // + + // + // All available Equity Actions Implemented here ... + void HandleEquityManagement() + { + // + // TODO: Complete this ... + } + + // + // Retrieve All EQM Placed Support Orders ... + int GetEQMOrders( + XOrder &orders[] // Hold Result + ) + { + // + int result = 0; + + // + XOrder allOrders[]; + int allOrdersCount = GetOrders(allOrders); + if (allOrdersCount <= 0) + { + return result; + } + + // + // Extract EQM Orders ... + result = GetEQMSupportOrders( + orders, + allOrders); + + // + return result; + } + + // + // Retrieve All EQM Support Positions ... + int GetEQMPositions( + XPosition &positions[] // Hold Result + ) + { + // + int result = 0; + + // + XPosition allPositions[]; + int allPositionsCount = GetPositions(allPositions); + if (allPositionsCount <= 0) + { + return result; + } + + // + // Extract EQM Positions ... + result = GetEQMSupportPositions( + positions, + allPositions); + + // + return result; + } + + // + // Cancel all EQM Placed Support Orders ... + bool CancelAllEQMOrders() + { + // + bool result = false; + + // + XOrder eqmOrders[]; + int eqmOrdersCount = GetEQMOrders(eqmOrders); + if (eqmOrdersCount <= 0) + { + return result; + } + + // + result = mTrader.CancelOrders(eqmOrders); + + // + return result; + } + + // + // Generate EQM Support Signals ... + int GenerateEQMSupports( + XSignal &supports[] // Holds Supports + ) + { + // + int result = 0; + + // + // Clean result Array ... + Clean(supports); + + // + // Since we Generate Support Signals based on Max In Drawdown Positions ... + // we hae to Find it and then find it's Related Provider ... + // then recieve Market Conditions based on it's Signaller's Provider ... + // then try to Generate Supports ... + XPosition inDrawdownPositions[]; + int inDrawdownPositionsCount = GetInDrawdownPositions( + inDrawdownPositions, + NULL, // All Symbols ... + NULL, // All TYpe Of Positions ... + NULL, // All Periods ... + NULL, // All Providers ... + X_POSITION_SELECT_MAX // we need Max InDrawdown ... + ); + if (inDrawdownPositionsCount <= 0) + { + return result; + } + + // + // Since We Select Max here ... + // and also check count ... + // just Recieve Max In DD Position ... + XPosition maxInDDPosition = inDrawdownPositions[0]; + + // + // Here we can Select Provider based on InDD Position ... + int providerIDX = GetProviderIndex( + maxInDDPosition.symbol, + maxInDDPosition.period); + + // + // Validate Index ... + if (providerIDX <= -1) + { + return result; + } + + // + // Retrieve Market Conditions Based on Specific Provider ... + X121MarketConditions conditions = mProviders[providerIDX] + .provider + .GetMarketConditions(0); + + // + // Here we have multiple Senarios for Supporting ... + + // + // Support Using Peaks and Vales ... + // in this Senario we Place Two Order on Peaks and Vales ... + + // + // Peaks ... + XSignal pSignal; + // TODO: Implwmwnr this ... + + // + // Vales ... + XSignal vSignal; + // TODO: Implwmwnr this ... + + // + result = ArraySize(supports); + + // + return result; + } + + // + // Count all open Positions Volume for supports ... + double GetEQMSupportVolume() + { + // + double result = 0; + + // + // Retrieve Positions ... + XPosition positions[]; + int positionsCount = GetPositions(positions); + if (positionsCount <= 0) + { + return result; + } + + // + // Retrieve EQM Positions and Check ... + // if it's count bigger than 0 means there are an Open + // EQM Support Position and we do not have to do anything ... + XPosition eqmPositions[]; + int eqmPositionsCount = GetEQMPositions(eqmPositions); + if (eqmPositionsCount > 0) + { + return result; + } + + // + for (int i = 0; i < positionsCount; i++) + { + // + XPosition iPosition = positions[i]; + + // + result += iPosition.volume; + } + + // + // Multiply Volume Summary ... + // TODO: Make it Configurable ... + result *= 1.5; + + // + return result; + } + + // + // Check Account is Ready for EQM Hedge or not ... + bool IsReadyForEQMHedge() + { + // + bool result = false; + + // + // Check required Inputs ... + if (mMinProfitPerTrade <= 0 || + mMinProfitPerVolumeFactor <= 0) + { + return result; + } + + // + // Check at least One EQM Support Position must be Open ... + XPosition eqmPositions[]; + int eqmPositionsCount = GetEQMPositions(eqmPositions); + if (eqmPositionsCount <= 0) + { + return result; + } + + // + // Get All Open Positions for Calculate Account Profit ... + XPosition positions[]; + int positionsCount = GetPositions( + positions); + if (positionsCount <= 0) + { + return result; + } + + // + // Define Factor Variables ... + double profit = 0; + double requiredProfit = 0; + + // + // Calculate Account Profit Factors ... + for (int i = 0; i < positionsCount; i++) + { + // + XPosition iPosition = positions[i]; + + // + profit += iPosition.profit; + requiredProfit += + ((iPosition.volume / mMinProfitPerVolumeFactor) * + mMinProfitPerTrade) + + (-1 * iPosition.swap); + } + + // + // Calculate the result ... + result = profit >= requiredProfit; + + // + return result; + } + + // + // PROVIDERS ... + // + + // + // Find Specific Provider Index by using give symbol and period ... + int GetProviderIndex( + string symbol, // Trading Symbol ... + ENUM_TIMEFRAMES period // Trading Time frame ... + ) + { + // + int result = -1; + + // + // Validate Args ... + if (period == NULL || + symbol == NULL || + StringLen(symbol) == 0) + { + return result; + } + + // + int providersCount = ArraySize(mProviders); + if (providersCount <= 0) + { + return result; + } + + // + for (int i = 0; i < providersCount; i++) + { + // + X121SignalProvider iProvider = mProviders[i]; + + // + if (iProvider.symbol == symbol && iProvider.period == period) + { + // + result = i; + break; + } + } + + // + return result; + } + + // + // Prepare Default Configurations for X121Provider Setup ... + void PrepareProviderConfig() + { + // + // Set Default X121 Provider Configurations ... + + // + // XMAN ... + + // + // Candle Timer ... + mProviderConfig.xmanConfig.candleTimerColor = clrGold; + mProviderConfig.xmanConfig.candleTimerCorner = CORNER_RIGHT_UPPER; + + // + // Chart Style ... + mProviderConfig.xmanConfig.upColor = clrLime; + mProviderConfig.xmanConfig.downColor = clrRed; + mProviderConfig.xmanConfig.lineColor = clrLime; + mProviderConfig.xmanConfig.bearishColor = clrRed; + mProviderConfig.xmanConfig.bullishColor = clrLime; + mProviderConfig.xmanConfig.volumesColor = clrGreen; + mProviderConfig.xmanConfig.chartMode = CHART_CANDLES; + + // + // Market Cycles ... + + // + // Level 1 ... + mProviderConfig.xmanConfig.l1Method = X_PERIOD_AUTO; + mProviderConfig.xmanConfig.l1Period = NULL; + + // + // Level 1 ... + mProviderConfig.xmanConfig.l2Method = X_PERIOD_AUTO; + mProviderConfig.xmanConfig.l2Period = NULL; + + // + // Level 1 ... + mProviderConfig.xmanConfig.l3Method = X_PERIOD_AUTO; + mProviderConfig.xmanConfig.l3Period = NULL; + + // + // Level 1 ... + mProviderConfig.xmanConfig.l4Method = X_PERIOD_AUTO; + mProviderConfig.xmanConfig.l4Period = NULL; + + // + // Fibonacci ... + mProviderConfig.xmanConfig.fiboLevel1 = 0.236; + mProviderConfig.xmanConfig.fiboLevel2 = 0.382; + mProviderConfig.xmanConfig.fiboLevel3 = 0.5; + mProviderConfig.xmanConfig.fiboLevel4 = 0.618; + mProviderConfig.xmanConfig.fiboLevel5 = 0.764; + + // + // Boundary Detection Modes ... + mProviderConfig.xmanConfig.hhMode = MODE_HIGH; + mProviderConfig.xmanConfig.llMode = MODE_LOW; + + // + // Trend Detection ... + mProviderConfig.xmanConfig.trendMultiplier = 3; + mProviderConfig.xmanConfig.trendPriceAppliedTo = PRICE_MEDIAN; + + // + // Ribbon Detection ... + mProviderConfig.xmanConfig.ribbonMode = X_MA_AMA; + + // + // Hull Trend Detection ... + mProviderConfig.xmanConfig.hullDivisor = 2.0; + mProviderConfig.xmanConfig.hullUpAppliedTo = PRICE_HIGH; + mProviderConfig.xmanConfig.hullDownAppliedTo = PRICE_LOW; + + // + // SSL Channel ... + mProviderConfig.xmanConfig.sslcMode = X_MA_SMA; + mProviderConfig.xmanConfig.sslcUpAppliedTo = PRICE_HIGH; + mProviderConfig.xmanConfig.sslcDownAppliedTo = PRICE_LOW; + + // + // Presentation ... + // NOTE: Since we Configure Presentation on PreDefine Section ... + // here we turn of all Presentations as Default ... + mProviderConfig.xmanConfig.showCandleTimer = false; + mProviderConfig.xmanConfig.showCandles = false; + mProviderConfig.xmanConfig.showHKCandles = false; + mProviderConfig.xmanConfig.showSMHKCandles = false; + mProviderConfig.xmanConfig.showPeaksAndVales = false; + mProviderConfig.xmanConfig.showTrends = false; + mProviderConfig.xmanConfig.fillTrends = false; + mProviderConfig.xmanConfig.showLevels = false; + mProviderConfig.xmanConfig.showConsolidations = false; + mProviderConfig.xmanConfig.showRibbons = false; + mProviderConfig.xmanConfig.showHull = false; + mProviderConfig.xmanConfig.showSSLChannel = false; + mProviderConfig.xmanConfig.showFibo1Levels = false; + mProviderConfig.xmanConfig.showFibo2Levels = false; + mProviderConfig.xmanConfig.showFibo3Levels = false; + mProviderConfig.xmanConfig.showFibo4Levels = false; + mProviderConfig.xmanConfig.showFibo5Levels = false; + + // + PreDefineProviderConfig(); + } + + // + // Config Representation of X121 Provider Setup ... + // for Specified Strategies ... + void PreDefineProviderConfig() + { + // + // Here we have to Name or Predefined Styles ... + bool x786Config = true; + + // + // by default we need to Show Candles and also Candle Timer ... + mProviderConfig.xmanConfig.showCandles = true; + mProviderConfig.xmanConfig.showCandleTimer = true; + + // + // now we act based on Predefined Variables ... + if (x786Config) + { + // + bool showHK = true; + bool showPVs = true; + bool showFibo = true; + bool showHull = false; + bool showSSLC = false; + bool showTrend = true; + bool showRibbon = false; + bool showPVLevels = false; + bool showPVLevelConsolidations = false; + + // + mProviderConfig.xmanConfig.showCandles = !showHK; + mProviderConfig.xmanConfig.showHKCandles = showHK; + mProviderConfig.xmanConfig.showSMHKCandles = showHK; + + // + mProviderConfig.xmanConfig.showHull = showHull; + mProviderConfig.xmanConfig.showTrends = showTrend; + mProviderConfig.xmanConfig.showRibbons = showRibbon; + mProviderConfig.xmanConfig.showSSLChannel = showSSLC; + + // + mProviderConfig.xmanConfig.showFibo1Levels = showFibo; + mProviderConfig.xmanConfig.showFibo2Levels = showFibo; + mProviderConfig.xmanConfig.showFibo3Levels = showFibo; + mProviderConfig.xmanConfig.showFibo4Levels = showFibo; + mProviderConfig.xmanConfig.showFibo5Levels = showFibo; + + // + mProviderConfig.xmanConfig.showPeaksAndVales = showPVs; + + // + mProviderConfig.xmanConfig.showLevels = showPVLevels; + mProviderConfig.xmanConfig.showConsolidations = showPVLevelConsolidations; + } + } + + // + // Prepare Signal ... + void PrepareConditionsSignal(X121MarketConditions &conditions) + { + // + if (!conditions.hasSignal) + { + return; + } + + // + bool isLong = IsLong(conditions.signal.type); + + // + // Check Calculate TP ... + if ( + conditions.signal.sl > 0 && + conditions.signal.r2r > 0 && + conditions.signal.entry > 0 && + conditions.signal.calculateTP) + { + // + double riskPrice = MathAbs(conditions.signal.entry - conditions.signal.sl); + double riskPoint = PriceToPoint( + conditions.signal.symbol, + riskPrice); + double rewardPoint = riskPoint * conditions.signal.r2r; + double rewardPrice = PointToPrice( + conditions.signal.symbol, + rewardPoint); + + // + double tp = + isLong + ? conditions.signal.entry + rewardPrice + : conditions.signal.entry - rewardPrice; + + // + conditions.signal.tp = tp; + } + + // + PrepareSignal(conditions.signal); + + // + conditions.signal.supportAndResistance = conditions.supportResistances; + } + + // + // TODO: Delete This ... + void DrawConditionsSignalOnChart(X121MarketConditions &conditions) + { + // + ulong mTicket = MathRand() * 100000; + + // + DrawSignal( + mTicket, + conditions.signal); + + // + DrawSupportResistance( + 0, + conditions.supportResistances, + conditions.signal.providers[0]); + } +}; + +// +// START Usefull Functions ... +// + +// +// END Usefull Functions ... +// diff --git a/MQLTestWorkspace/X121/14030217/Classes/x-saherelm.xaccount.class.ex5 b/MQLTestWorkspace/X121/14030217/Classes/x-saherelm.xaccount.class.ex5 new file mode 100644 index 0000000..ff66151 Binary files /dev/null and b/MQLTestWorkspace/X121/14030217/Classes/x-saherelm.xaccount.class.ex5 differ diff --git a/MQLTestWorkspace/X121/14030217/Classes/x-saherelm.xaccount.class.mq5 b/MQLTestWorkspace/X121/14030217/Classes/x-saherelm.xaccount.class.mq5 new file mode 100644 index 0000000..4425f0b --- /dev/null +++ b/MQLTestWorkspace/X121/14030217/Classes/x-saherelm.xaccount.class.mq5 @@ -0,0 +1,398 @@ +/////////////////////////////////////////////////////// +// +// 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 "../Libraries/x-saherelm.common.lib.mq5" + +// +// END Import and Inclused requirements ... +// + +// +// START Overrides ... +// + +// +// END Overrides ... +// + +// +// a Class for Manage Account ... +class XSCAccount +{ + // + // 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/MQLTestWorkspace/X121/14030217/Classes/x-saherelm.xea.class.ex5 b/MQLTestWorkspace/X121/14030217/Classes/x-saherelm.xea.class.ex5 new file mode 100644 index 0000000..3407d03 Binary files /dev/null and b/MQLTestWorkspace/X121/14030217/Classes/x-saherelm.xea.class.ex5 differ diff --git a/MQLTestWorkspace/X121/14030217/Classes/x-saherelm.xea.class.mq5 b/MQLTestWorkspace/X121/14030217/Classes/x-saherelm.xea.class.mq5 new file mode 100644 index 0000000..f8f1ea9 --- /dev/null +++ b/MQLTestWorkspace/X121/14030217/Classes/x-saherelm.xea.class.mq5 @@ -0,0 +1,1614 @@ +/////////////////////////////////////////////////////// +// +// 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 + +// +// START Definitions ... +// + +// +// END Definitions ... +// + +// +// START Import and Inclused requirements ... +// + +// +// Includes ... +#include "../Libraries/x-saherelm.alert.lib.mq5" +#include "../Libraries/x-saherelm.common.lib.mq5" +#include "../Classes/x-saherelm.xtrade.class.mq5" +#include "../Classes/x-saherelm.xaccount.class.mq5" +#include "../Classes/x-saherelm.xprovider.class.mq5" +#include "../Libraries/x-saherelm.seriallizer.lib.mq5" + +// +// END Import and Inclused requirements ... +// + +// +// START Overrides ... +// + +// +// END Overrides ... +// + +// +// a Class for Handle base requirements ... +// for indicators ... +class XSCBaseEA +{ + // + // Public ... +public: + // + // Props ... + XSCTrade *mTrader; + XSCAccount *mAccount; + + // + bool isNewHour; + bool isNewDay; + bool isNewWeek; + bool isNewMonth; + bool isNewCandle; + + // + bool isInTestMode; + + // + bool mWaitsUntilNewCandle; + + // + // Constructor ... + void XSCBaseEA( + string symbol, // Trading Symbol + ENUM_TIMEFRAMES period, // Trading Time Frame + ulong magic, // Magic Number + int slippage, // Slippgae + TOnStopLoss onStopLossTriggered = NULL, // On StopLoass Triggered Event Handler + TOnTakeProfit onTakeProfitTriggered = NULL, // On TakeProfit Triggered 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 + ) + { + // + mSymbol = symbol; + mPeriod = period; + + // + mMagic = magic; + mSlippage = slippage; + + // + mOnStopLossTriggered = onStopLossTriggered; + mOnTakeProfitTriggered = onTakeProfitTriggered; + mOnDealsChangedHandler = onDealsChangedHandler; + mOnOrdersChangedHandler = onOrdersChangedHandler; + mOnPositionsChangedHandler = onPositionsChangedHandler; + mOnTradeStateChangedHandler = onTradeStateChangedHandler; + + // + // Reset Timings ... + ResetTiming(); + + // + EnableLongs(true); + EnableShorts(true); + + // + MaxAllowedPositions(0); + MaxAllowedDrawDownFactor(0); + + // + InitRequirements(); + } + + // + // Deconstructor ... + void ~XSCBaseEA() + { + // + delete mTrader; + delete mAccount; + } + + // + // START Properties ... + // + + // + // Symbol ... + string GetSymbol() + { + return mSymbol; + } + + // + // Period ... + ENUM_TIMEFRAMES GetPeriod() + { + return mPeriod; + } + + // + // Tag ... + string GetTag() + { + return mTag; + } + + // + ulong GetMagic() + { + return mMagic; + } + + // + int GetSlippage() + { + return mSlippage; + } + + // + // Check Long Signalling State ... + bool EnableLongs() + { + return mEnableLongs; + } + + // + // Set Long Signalling State ... + void EnableLongs(bool enable) + { + // + if (enable == mEnableLongs) + { + return; + } + + // + mEnableLongs = enable; + } + + // + // Check Short Signalling State ... + bool EnableShorts() + { + return mEnableShorts; + } + + // + // Set Short Signalling State ... + void EnableShorts(bool enable) + { + // + if (enable == mEnableShorts) + { + return; + } + + // + mEnableShorts = enable; + } + + // + // Get Max Allowed Positions at Same Time ... + int MaxAllowedPositions() + { + return mMaxAllowedPositions; + } + + // + // Set Max Allowed Positions at Same Time ... + void MaxAllowedPositions(int value) + { + // + if (value < 0 || + value == mMaxAllowedPositions) + { + return; + } + + // + mMaxAllowedPositions = value; + } + + // + // Get Max Allowed DrawDown Factor ... + double MaxAllowedDrawDownFactor() + { + return mMaxAllowedDrawDownFactor; + } + + // + // Set Max Allowed Positions at Same Time ... + void MaxAllowedDrawDownFactor(double value) + { + // + if (value < 0 || + value == mMaxAllowedDrawDownFactor) + { + return; + } + + // + mMaxAllowedDrawDownFactor = value; + } + + // + // 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 balanceForFactor = MathAbs(equity - balance); + if (balanceForFactor <= 0) + { + balanceForFactor = balance; + } + else + { + balanceForFactor = equity; + } + + // + double maxAllowedBalanceDrawDown = balanceForFactor * mMaxAllowedDrawDownFactor; + + // + result = equity > balance || + (equity <= balance && + selectedBalance <= maxAllowedBalanceDrawDown); + + // + return result; + } + + // + // Check Max Allowed Positions Policy for Trade ... + bool ChecPositionsForTrade() + { + // + bool result = false; + + // + if (mMaxAllowedPositions <= 0) + { + // + result = true; + return result; + } + + // + int positionsCount = mTrader.CountPositions(); + if (positionsCount <= 0) + { + // + result = true; + return result; + } + + // + result = positionsCount <= mMaxAllowedPositions; + + // + return result; + } + + // + // Check Account Policies ... + bool CheckAccountPolicies() + { + // + bool result = false; + + // + // Check Equity for Trade ... + result = CheckEquityForTrade(); + if (!result) + { + // + string message = "not enough Equity for Trade ..."; + + // + LogMessage(message); + + // // + // // Handle Force Close Positions on Max Drawdown ... + // HandleGuardForceCloseAction( + // NULL, // All Providers ... + // NULL, // All Symbols ... + // NULL, // All Type of Positions ... + // NULL // All Periods ... + // ); + + // + return result; + } + + // + // Check Max Allowed Position for Trade ... + result = ChecPositionsForTrade(); + if (!result) + { + // + string message = "max allowed Positions reached ..."; + + // + LogMessage(message); + + // // + // HandleGuardCloseInProfitAction( + // NULL, // All Providers ... + // NULL, // All Symbols ... + // NULL, // All Type of Positions ... + // NULL, // All Periods ... + // X_POSITION_SELECT_MAX // Select Max Position ... + // ); + + // // + // HandleGuardCloseInDrawdownAction( + // NULL, // All Providers ... + // NULL, // All Symbols ... + // NULL, // All Type of Positions ... + // NULL, // All Periods ... + // X_POSITION_SELECT_MAX // Select Max Position ... + // ); + + // + return result; + } + + // + return result; + } + + // + // END Properties ... + // + + // + // START Provided Functions ... + // + + // + // Prepare Tag ... + virtual void PrepareTag() + { + mTag = "XEA" + mSymbol + "," + ToString(mPeriod) + (string)mMagic; + } + + // + // 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 + ) + { + } + + // + // Check any Registered Providers Signalling ... + virtual bool SignalCheck(XSignal &signals[]) + { + return false; + } + + // + // Check for any Custom Guard Actions Guard Actions ... + virtual bool CheckGuard(XGuard &guards[]) + { + return false; + } + + // + // NOTE: you have to call these Functions on Static Classes to Handle Works ... + + // + // 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) {} + + // + // Implemented Actions ... + + // + // OnTick Handler ... + void OnTick() + { + // + // First Check Guards .... + // Only when Open Positions Exists or Has Pending Order ... + XGuard guards[]; + bool hasGuard = CheckGuard(guards); + if (hasGuard) + { + DoGuards(guards); + } + + // + // Check Account Policies ... + bool isAccountPassed = CheckAccountPolicies(); + if (!isAccountPassed) + { + return; + } + + // + XSignal signals[]; + bool hasSignal = SignalCheck(signals); + if (hasSignal) + { + // + // Here we have to Check Signals and also it's State ... + XSignal enabledSignals[]; + int signalsCount = ArraySize(signals); + if (signalsCount <= 0) + { + return; + } + + // + // Filter Signals by their type and + // also Check EA Enable their type ... + for (int i = 0; i < signalsCount; i++) + { + // + XSignal iSignal = signals[i]; + bool isLong = IsLong(iSignal.type); + if ((isLong && mEnableLongs) || + (!isLong && mEnableShorts)) + { + // + PrepareSignal(iSignal); + + // + Add( + iSignal, + enabledSignals); + } + } + + // + int enabledSignalsCount = ArraySize(enabledSignals); + if (enabledSignalsCount <= 0) + { + return; + } + + // + // Check Trade Policies ... + + // + // Check Equity for Trade ... + bool canDoTrade = CheckEquityForTrade(); + if (!canDoTrade) + { + // + string message = "not enough Equity for Trade ..."; + + // + LogMessage(message); + return; + } + + // + // Check Max Allowed Position for Trade ... + canDoTrade = ChecPositionsForTrade(); + if (!canDoTrade) + { + // + string message = "max allowed Positions reached ..."; + + // + LogMessage(message); + + // + // Check How to Act with Signals if Max In Drawdown Reached ... + // TODO: Here we Have to Define Max In Draw Down Position type ... + return; + } + + // + mTrader.ExecuteSignals(enabledSignals); + } + } + + // + // Handle On Trade ... + 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 ... + void OnBookEvent(const string &symbol) + { + // + // TODO: Implement this ... + } + + // + // TOOLS ... + + // + // Prepare a Signal and Do Calculations ... + void PrepareSignal( + XSignal &signal // a Signal for Preparation ... + ) + { + // + // Calculate Volume ... + if (signal.useRiskAmountAsVolume && signal.riskAmount > 0) + { + signal.volume = signal.riskAmount; + } + else if ( + signal.sl > 0 && + signal.tp > 0 && + signal.volume == 0 && + signal.riskAmount > 0 && + !signal.useSupportAndResistance) + { + // + // Calculate Risk Point ... + double riskPoint = MathAbs(signal.entry - signal.sl); + riskPoint = PriceToPoint( + signal.symbol, + riskPoint); + + // + double volume = mAccount.CalculateVolume( + signal.symbol, + signal.riskAmount, + riskPoint); + + // + signal.volume = volume; + } + else if (signal.useSupportAndResistance) + { + // + // Calculate Everything using Supports and Resistances ... + // TODO: Implement Later ... + } + + // + if (signal.ignoreTP) + { + signal.tp = 0; + } + + // + if (signal.ignoreSL) + { + signal.sl = 0; + } + + // + // Normalize Signal ... + NormalizeSignal(signal); + } + + // + // Get All Open Trades ... + int GetPositions( + XPosition &result[], // Hold Result ... + string symbol = NULL, // Trading Symbol ... + ENUM_POSITION_TYPE type = NULL, // Trading Type ... + ENUM_TIMEFRAMES period = NULL, // Trading Period ... + string provider = NULL // Signal Provider ... + ) + { + // + int mResult = 0; + + // + Clean(result); + + // + bool hasSymbol = !(symbol == NULL || StringLen(symbol) == 0); + bool hasProvider = !(provider == NULL || StringLen(provider) == 0); + + // + int positionsCount = mTrader.CountPositions(); + if (positionsCount <= 0) + { + return mResult; + } + + // + XPosition positions[]; + mTrader.GetPositions( + positions, + symbol, + period); + positionsCount = ArraySize(positions); + if (positionsCount <= 0) + { + return mResult; + } + + // + if (!hasProvider && type == NULL) + { + // + Copy( + positions, + result); + + // + return ArraySize(result); + } + + // + if (type == NULL) + { + // + ArrayResize( + result, + ArraySize(positions)); + + // + for (int i = 0; i < positionsCount; i++) + { + // + Add( + positions[i], + result); + } + + // + return ArraySize(result); + } + + // + for (int i = 0; i < positionsCount; i++) + { + // + XPosition iPosition = positions[i]; + + // + string iProvider = ExtractProvider(iPosition.comment); + if (hasProvider && iProvider != provider) + { + continue; + } + + // + if (type == NULL || iPosition.type == type) + { + // + Add( + iPosition, + result); + } + } + + // + mResult = ArraySize(result); + + // + return mResult; + } + + // + // Get All In Profit Trades ... + int GetInProfitPositions( + XPosition &result[], // Hold Result ... + string symbol = NULL, // Trading Symbol ... + ENUM_POSITION_TYPE type = NULL, // Trading Type ... + ENUM_TIMEFRAMES period = NULL, // Trading Period ... + string provider = NULL, // Signal Provider ... + ENUM_X_POSITION_SELECT_METHODS method = NULL // Select Method ... + ) + { + // + int mResult = 0; + + // + Clean(result); + + // + if (method == NULL) + { + method = X_POSITION_SELECT_ALL; + } + + // + // Prevent Going Forwars Since selection type is NONE ... + if (method == X_POSITION_SELECT_NONE) + { + return mResult; + } + + // + bool isMinSelectable = method == X_POSITION_SELECT_MIN; + bool isMaxSelectable = method == X_POSITION_SELECT_MAX; + + // + XPosition positions[]; + GetPositions( + positions, + symbol, + type, + period, + provider); + int positionsCount = ArraySize(positions); + if (positionsCount <= 0) + { + return mResult; + } + + // + // Define Temp Position for Selecting Max Position ... + XPosition maxPos; + maxPos.profit = INVALID_HANDLE; + + // + // Define Temp Position for Selecting Min Position ... + XPosition minPos; + minPos.profit = INVALID_HANDLE; + + // + // Loop through available Positions for Selecting Positions ... + for (int i = 0; i < positionsCount; i++) + { + // + XPosition iPosition = positions[i]; + + // + // Check Profit State ... + if (iPosition.profit <= 0) + { + continue; + } + + // + // Check Selection State ... + if (isMinSelectable) + { + // + if (minPos.profit == INVALID_HANDLE || + minPos.profit > iPosition.profit) + { + minPos = iPosition; + } + + // + continue; + } + else if (isMaxSelectable) + { + // + if (maxPos.profit == INVALID_HANDLE || + maxPos.profit < iPosition.profit) + { + maxPos = iPosition; + } + + // + continue; + } + else + { + // + Add( + iPosition, + result); + } + } + + // + // Add Selected Position if Provided to Results ... + if (isMinSelectable) + { + // + Add( + minPos, + result); + } + else if (isMaxSelectable) + { + // + Add( + maxPos, + result); + } + + // + mResult = ArraySize(result); + + // + return mResult; + } + + // + // Get All In Drawdown Trades ... + int GetInDrawdownPositions( + XPosition &result[], // Hold Result ... + string symbol = NULL, // Trading Symbol ... + ENUM_POSITION_TYPE type = NULL, // Trading Type ... + ENUM_TIMEFRAMES period = NULL, // Trading Period ... + string provider = NULL, // Signal Provider ... + ENUM_X_POSITION_SELECT_METHODS method = NULL // Select Method ... + ) + { + // + int mResult = 0; + + // + Clean(result); + + // + if (method == NULL) + { + method = X_POSITION_SELECT_ALL; + } + + // + // Prevent Going Forwars Since selection type is NONE ... + if (method == X_POSITION_SELECT_NONE) + { + return mResult; + } + + // + bool isMinSelectable = method == X_POSITION_SELECT_MIN; + bool isMaxSelectable = method == X_POSITION_SELECT_MAX; + + // + XPosition positions[]; + GetPositions( + positions, + symbol, + type, + period, + provider); + int positionsCount = ArraySize(positions); + if (positionsCount <= 0) + { + return mResult; + } + + // + // Define Temp Position for Selecting Max Position ... + XPosition maxPos; + maxPos.profit = INVALID_HANDLE; + + // + // Define Temp Position for Selecting Min Position ... + XPosition minPos; + minPos.profit = INVALID_HANDLE; + + // + // Loop through available Positions for Selecting Positions ... + for (int i = 0; i < positionsCount; i++) + { + // + XPosition iPosition = positions[i]; + + // + // Check Profit State ... + if (iPosition.profit >= 0) + { + continue; + } + + // + // Check Selection State ... + if (isMinSelectable) + { + // + if (minPos.profit == INVALID_HANDLE || + minPos.profit < iPosition.profit) + { + minPos = iPosition; + } + + // + continue; + } + else if (isMaxSelectable) + { + // + if (maxPos.profit == INVALID_HANDLE || + maxPos.profit > iPosition.profit) + { + maxPos = iPosition; + } + + // + continue; + } + else + { + // + Add( + iPosition, + result); + } + } + + // + // Add Selected Position if Provided to Results ... + if (isMinSelectable) + { + // + Add( + minPos, + result); + } + else if (isMaxSelectable) + { + // + Add( + maxPos, + result); + } + + // + mResult = ArraySize(result); + + // + return mResult; + } + + // + // Retrieve Orders ... + int GetOrders( + XOrder &result[], // Hold Result ... + string symbol = NULL, // Trading Symbol ... + ENUM_ORDER_TYPE type = NULL, // Trading Type ... + ENUM_ORDER_STATE state = NULL, // Trading State ... + ENUM_TIMEFRAMES period = NULL, // Trading Period ... + string provider = NULL // Signal Provider ... + ) + { + // + int mResult = 0; + + // + Clean(result); + + // + XOrder orders[]; + mTrader.GetOrders( + orders, + symbol, + period, + state); + int ordersCount = ArraySize(orders); + if (ordersCount <= 0) + { + return mResult; + } + + // + if (type == NULL && + (provider == NULL || + StringLen(provider) == 0)) + { + // + Copy( + orders, + result); + + // + mResult = ArraySize(result); + + // + return mResult; + } + + // + for (int i = 0; i < ordersCount; i++) + { + // + XOrder iOrder = orders[i]; + + // + if (type != NULL && iOrder.type != type) + { + continue; + } + + // + if (provider != NULL && + StringLen(provider) > 0) + { + // + // Generate Order Provider ... + string iProvider = ExtractProvider(iOrder.comment); + if (iProvider != provider) + { + continue; + } + } + + // + Add( + iOrder, + result); + } + + // + mResult = ArraySize(result); + + // + return mResult; + } + + // + // GUARD Handlers ... + + // + // Parse Recievd Guards and Do them ... + void DoGuards(XGuard &guards[]) + { + // + int guardsCount = ArraySize(guards); + if (guardsCount <= 0) + { + return; + } + + // + for (int i = 0; i < guardsCount; i++) + { + // + XGuard iGuard = guards[i]; + + // + switch (iGuard.action) + { + // + // Hedge In Profit Specified Positions ... + case X_GUARD_ACTION_HEDGE: + HandleGuardHedgeAction( + iGuard.provider, + iGuard.symbol, + iGuard.type, + iGuard.period); + break; + + // + // Trail Stop Loss in Specified Positions ... + case X_GUARD_ACTION_TRAIL_STOP: + HandleGuardTrailingStopAction( + iGuard.provider, + iGuard.symbol, + iGuard.type, + iGuard.period, + iGuard.dblPayLoad); + break; + + // + // Force Close Specified Positions ... + case X_GUARD_ACTION_FORCE_CLOSE: + HandleGuardForceCloseAction( + iGuard.provider, + iGuard.symbol, + iGuard.type, + iGuard.period); + break; + + // + // Generate and Place Support Signals ... + case X_GUARD_ACTION_ADD_SUPPORT_SIGNAL: + HandleGuardAddSupportPositionAction( + iGuard.provider, + iGuard.symbol, + iGuard.type, + iGuard.period); + break; + + // + // Delete All Placed Pending Orders ... + case X_GUARD_ACTION_CANCEL_PENDING_ORDERS: + HandleGuardCancelPendingOrdersAction( + iGuard.provider, + iGuard.symbol, + iGuard.type, + iGuard.period); + break; + } + } + } + + // + // Close All Specified Provider's Positions in Profit Summary ... + void HandleGuardHedgeAction( + string provider, // Positions Provided by Specific Provider + string symbol, // Trading Symbol + ENUM_POSITION_TYPE type, // Trading Type + ENUM_TIMEFRAMES period, // Specified Time Frame + double minProfitForHedging = 1 // Specified Profit for Hedge + ) + { + // + // TODO: Implement this ... + } + + // + // Close Max In Profit Trade Guard Action ... + void HandleGuardCloseInProfitAction( + string provider, // Positions Provided by Specific Provider + string symbol, // Trading Symbol + ENUM_POSITION_TYPE type, // Trading Type + ENUM_TIMEFRAMES period, // Specified Time Frame + ENUM_X_POSITION_SELECT_METHODS method = NULL // Select Method + ) + { + // + XPosition positions[]; + GetInProfitPositions( + positions, + symbol, + type, + period, + provider, + method); + int positionsCount = ArraySize(positions); + if (positionsCount <= 0) + { + return; + } + + // + string comment = "Close InProfit ..."; + mTrader.ClosePositions( + positions, + comment); + + // + string message = "Guard Close (" + ToString(positionsCount) + ") Postion(s) In Profit ..."; + LogMessage(message); + } + + // + // Close Max In Drawdown Trade Guard Action ... + void HandleGuardCloseInDrawdownAction( + string provider, // Positions Provided by Specific Provider + string symbol, // Trading Symbol + ENUM_POSITION_TYPE type, // Trading Type + ENUM_TIMEFRAMES period, // Specified Time Frame + ENUM_X_POSITION_SELECT_METHODS method = NULL // Select Method + ) + { + // + XPosition positions[]; + GetInDrawdownPositions( + positions, + symbol, + type, + period, + provider, + method); + int positionsCount = ArraySize(positions); + if (positionsCount <= 0) + { + return; + } + + // + string comment = "Close InDrawdown ..."; + mTrader.ClosePositions( + positions, + comment); + + // + string message = "Guard Close (" + ToString(positionsCount) + ") Position(s) In Drawdown ..."; + LogMessage(message); + } + + // + // Force Close Specified Set Of Position ... + void HandleGuardForceCloseAction( + string provider, // Positions Provided by Specific Provider + string symbol, // Trading Symbol + ENUM_POSITION_TYPE type, // Trading Type + ENUM_TIMEFRAMES period, // Specified Time Frame + ulong ticket = 0 // Specific Ticket + ) + { + // + string comment = ""; + + // + // Close All Positions ... + if (ticket == 0) + { + // + XPosition positions[]; + GetPositions( + positions, + symbol, + type, + period, + provider); + if (ArraySize(positions) <= 0) + { + return; + } + + // + comment = provider + " Force Close Guard ..."; + + // + mTrader.ClosePositions( + positions, + comment); + } + // + // Close Specific Position ... + else + { + // + XPosition position; + bool hasPosition = mTrader.GetPosition( + position, + ticket); + + // + if (hasPosition) + { + // + comment = provider + "(" + ToString(ticket) + ")" + " Force Close Guard ..."; + + // + mTrader.Close( + ticket, + comment); + } + } + + // + if (StringLen(comment) > 0) + { + LogMessage(comment); + } + } + + // + // Trailing Specified Set Of Positions Stop Losses ... + void HandleGuardTrailingStopAction( + string provider, // Positions Provided by Specific Provider + string symbol, // Trading Symbol + ENUM_POSITION_TYPE type, // Trading Type + ENUM_TIMEFRAMES period, // Specified Time Frame + double sl // Desired SL Value ... + ) + { + // + if (sl <= 0) + { + return; + } + + // + NormalizePrice( + sl, + symbol); + + // + XPosition positions[]; + GetPositions( + positions, + symbol, + type, + period, + provider); + int positionsCount = ArraySize(positions); + if (positionsCount <= 0) + { + return; + } + + // + int modified = 0; + for (int i = 0; i < positionsCount; i++) + { + // + XPosition iPosition = positions[i]; + + // + string comment = PrepareSLTrailComment(iPosition.comment); + + // + bool isModified = mTrader.Modify( + iPosition.ticket, + sl, + iPosition.tp, + comment); + if (isModified) + { + modified++; + } + } + + // + if (modified > 0) + { + // + string msg = "(" + ToString(modified) + ") Position's Stop Trailed Successfully ..."; + + // + LogMessage(msg); + } + } + + // + // Add Support Signal for Specified Positions ... + void HandleGuardAddSupportPositionAction( + string provider, // Positions Provided by Specific Provider + string symbol, // Trading Symbol + ENUM_POSITION_TYPE type, // Trading Type + ENUM_TIMEFRAMES period // Specified Time Frame + ) + { + // + // TODO: Implement this ... + } + + // + // Cancel all Placed Orders ... + void HandleGuardCancelPendingOrdersAction( + string provider, // Positions Provided by Specific Provider + string symbol, // Trading Symbol + ENUM_POSITION_TYPE type, // Trading Type + ENUM_TIMEFRAMES period // Specified Time Frame + ) + { + // + // TODO: Implement this ... + } + + // + // END Provided Functions ... + // + + // + // Protected ... +protected: + // + string GetTagPrefix() + { + // + string result = "(" + mSymbol + ")(" + ToString(mPeriod) + ")"; + + // + return result; + } + + // + // Symbol ... + string mSymbol; + + // + // Period ... + ENUM_TIMEFRAMES mPeriod; + + // + // ExpertAdviser MAgic Number ... + ulong mMagic; + + // + // Slipppage ... + int mSlippage; + + // + // Tag Identifier ... + string mTag; + + // + bool mEnableLongs; + bool mEnableShorts; + + // + int mMaxAllowedPositions; + double mMaxAllowedDrawDownFactor; + + // + // Private ... +private: + // + // Define Requirements ... + + // + // XSCTrade Event Handlers ... + TOnStopLoss mOnStopLossTriggered; + TOnTakeProfit mOnTakeProfitTriggered; + TOnDealsChanged mOnDealsChangedHandler; + TOnOrdersChanged mOnOrdersChangedHandler; + TOnPositionsChanged mOnPositionsChangedHandler; + TOnTradeStateChanged mOnTradeStateChangedHandler; + + // + // Initi Requirements ... + void InitRequirements() + { + // + // Account Manager ... + mAccount = new XSCAccount(); + + // + // Trader ... + mTrader = new XSCTrade( + mSlippage, + mMagic); + + // + // Attach Event Handlers ... + + // + 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); + } + } +}; + +// +// START Usefull Functions ... +// + +// +// END Usefull Functions ... +// diff --git a/MQLTestWorkspace/X121/14030217/Classes/x-saherelm.xhelper.class.ex5 b/MQLTestWorkspace/X121/14030217/Classes/x-saherelm.xhelper.class.ex5 new file mode 100644 index 0000000..f2f0d42 Binary files /dev/null and b/MQLTestWorkspace/X121/14030217/Classes/x-saherelm.xhelper.class.ex5 differ diff --git a/MQLTestWorkspace/X121/14030217/Classes/x-saherelm.xhelper.class.mq5 b/MQLTestWorkspace/X121/14030217/Classes/x-saherelm.xhelper.class.mq5 new file mode 100644 index 0000000..d9cea8b --- /dev/null +++ b/MQLTestWorkspace/X121/14030217/Classes/x-saherelm.xhelper.class.mq5 @@ -0,0 +1,209 @@ +/////////////////////////////////////////////////////// +// +// 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 + +// +// START Definitions ... +// + +// +// END Definitions ... +// + +// +// START Import and Inclused requirements ... +// + +// +// Includes ... +#include "../Libraries/x-saherelm.common.lib.mq5" + +// +// END Import and Inclused requirements ... +// + +// +// START Overrides ... +// + +// +// END Overrides ... +// + +// +// a Class for Handle base requirements ... +// for indicators ... +class XSCBaseHelper +{ + // + // Public ... +public: + // + // Constructor ... + void XSCBaseHelper( + string symbol, // Trading Symbol + ENUM_TIMEFRAMES period // Trading Time Frame + ) + { + // + mSymbol = symbol; + mPeriod = period; + + // + LoopBack(52); + } + + // + // Deconstructor ... + void ~XSCBaseHelper() + { + IndicatorRelease(mHandler); + } + + // + // START Properties ... + // + + // + // Loopback Bars ... + void LoopBack(int value) + { + mLoopbackBars = value; + } + + int Loopback() + { + return mLoopbackBars; + } + + // + // Symbol ... + string GetSymbol() + { + return mSymbol; + } + + // + // Period ... + ENUM_TIMEFRAMES GetPeriod() + { + return mPeriod; + } + + // + // Tag ... + string GetTag() + { + return mTag; + } + + // + // Retrieve Bars ... + int GetBars() + { + // + int result = + Bars( + mSymbol, + mPeriod); + + // + return result; + } + + // + int GetCalculatedBars() + { + return BarsCalculated(mHandler); + } + + // + // END Properties ... + // + + // + // START Provided Functions ... + // + + // + // Prepare Tag ... + virtual void PrepareTag() {} + + // + // Reading Buffers based on Given Bar Index ... + virtual void Calculate( + int barIndex // Given Bar Index + ); + + // + // Retrieve MAx Required Length for Calculations ... + virtual int GetMaxLength(); + + // + // END Provided Functions ... + // + + // + // Protected ... +protected: + // + string GetTagPrefix() + { + // + string result = "(" + mSymbol + ")(" + ToString(mPeriod) + ")"; + + // + return result; + } + + // + // Symbol ... + string mSymbol; + + // + // Period ... + ENUM_TIMEFRAMES mPeriod; + + // + // Indicator Handler ... + int mHandler; + + // + // Number Of Items Read Per Tick ... + int mLoopbackBars; + + // + // Tag Identifier ... + string mTag; + + // + // Private ... +private: + // +}; + +// +// START Usefull Functions ... +// + +// +// END Usefull Functions ... +// diff --git a/MQLTestWorkspace/X121/14030217/Classes/x-saherelm.xnotifier.class.ex5 b/MQLTestWorkspace/X121/14030217/Classes/x-saherelm.xnotifier.class.ex5 new file mode 100644 index 0000000..6dbc041 Binary files /dev/null and b/MQLTestWorkspace/X121/14030217/Classes/x-saherelm.xnotifier.class.ex5 differ diff --git a/MQLTestWorkspace/X121/14030217/Classes/x-saherelm.xprovider.class.ex5 b/MQLTestWorkspace/X121/14030217/Classes/x-saherelm.xprovider.class.ex5 new file mode 100644 index 0000000..c295f28 Binary files /dev/null and b/MQLTestWorkspace/X121/14030217/Classes/x-saherelm.xprovider.class.ex5 differ diff --git a/MQLTestWorkspace/X121/14030217/Classes/x-saherelm.xprovider.class.mq5 b/MQLTestWorkspace/X121/14030217/Classes/x-saherelm.xprovider.class.mq5 new file mode 100644 index 0000000..e60bb27 --- /dev/null +++ b/MQLTestWorkspace/X121/14030217/Classes/x-saherelm.xprovider.class.mq5 @@ -0,0 +1,304 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Class Library +// ---------------------------------------------- +// Name: XSCEABaseProvider +// Description: provides base requirements for +// Specific Sgnal Provider ... +// +// +// 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 Import and Inclused requirements ... +// + +// +// Includes ... +#include "../Libraries/x-saherelm.log.lib.mq5" +#include "../Libraries/x-saherelm.draw.lib.mq5" +#include "../Libraries/x-saherelm.models.lib.mq5" +#include "../Libraries/x-saherelm.common.lib.mq5" + +// +// END Import and Inclused requirements ... +// + +// +// START Definitions ... +// + +// +// Notified a Signal was Appears ... +typedef void (*OnSignal)( + XSignal &signal); + +// +// Notified a Guard Appears ... +typedef void (*OnGuard)(XGuard &guard); + +// +// END Definitions ... +// + +// +// START Overrides ... +// + +// +// END Overrides ... +// + +// +// a Base Class for All of our EA's ... +class XSCEABaseProvider +{ + // + // Public ... +public: + // + // Constructor ... + void XSCEABaseProvider() + { + mSymbol = _Symbol; + mPeriod = _Period; + } + void XSCEABaseProvider( + string symbol, + ENUM_TIMEFRAMES period) + { + // + mSymbol = symbol; + mPeriod = period; + + // + mTag = mSymbol + "," + ToString(mPeriod); + + // + mIsInTestMode = IsRunningOnTestMode(); + } + + // + // Deconstructor ... + void ~XSCEABaseProvider() + { + } + + // + bool CanIgnoreTick() { + // + mIsNewCandle = IsNewCandle( + mSymbol, + mPeriod); + bool result = mIsInTestMode + ? !mIsNewCandle + : !mIsNewCandle && mWaitUntilNewCandle; + + // + return result; + } + + // + // Prepare State ... + void OnTick() + { + // + mIsNewCandle = IsNewCandle( + mSymbol, + mPeriod); + mCanIgnoreTick = mIsInTestMode + ? !mIsNewCandle + : !mIsNewCandle && mWaitUntilNewCandle; + + // + ProcessBuffers(); + + // + if (mCanIgnoreTick) + { + return; + } + + // + mWaitUntilNewCandle = false; + + // + ProcessTick(); + } + + // + virtual void PrepareTag(); + + // + // Initialize Indicators and Requirements ... + virtual bool Init(); + + // + virtual int GetMaxLength(); + + // + virtual int GetCalculatedBars(); + + // + // Handle Update Buffers ... + virtual void ProcessBuffers() + { + return; + } + + // + // Handle On Tick Event ... + virtual void ProcessTick() + { + return; + } + + // + // Check for Guards ... + virtual bool GuardCheck(XGuard &guards[]); + + // + // Add Specific On Signal Event Handler ... + int AddOnSignalEventHandler(OnSignal handler) + { + // + ArrayResize( + mSignalEventHandlers, + ArraySize(mSignalEventHandlers) + 1); + + // + int result = ArraySize(mSignalEventHandlers) - 1; + mSignalEventHandlers[result] = handler; + + // + return result; + } + + // + // Remove All On Signal Event Handler ... + void ReoveOnSignalEventHandlers() + { + // + ArrayFree(mSignalEventHandlers); + } + + // + // Notify a Signal Found on all Event Listeners ... + void NotifyOnSignalEvent(XSignal &info) + { + // + int listenerCount = ArraySize(mSignalEventHandlers); + if (listenerCount <= 0) + { + return; + } + + // + // Loop Through Listeners ... + for (int i = 0; i < listenerCount; i++) + { + // + OnSignal listener = mSignalEventHandlers[i]; + + // + listener(info); + } + } + + // + // Protected ... +protected: + // + string mSymbol; + + // + ENUM_TIMEFRAMES mPeriod; + + // + string mTag; + + // + bool mIsNewCandle; + bool mIsInTestMode; + bool mCanIgnoreTick; + bool mWaitUntilNewCandle; + + // + // Private ... +private: + // + // Signal Event Handlers ... + OnSignal mSignalEventHandlers[]; +}; + +// +// START Definitions ... +// + +// +// Model Signal Providers Definitions ... +struct XBaseSignalProvider +{ + // + // Provider use Which Symbol ... + string symbol; + + // + // Provider use Which Time Frame ... + ENUM_TIMEFRAMES period; + + // + // Risk Amount Per Trades Related to Time Frames ... + // Percent of Available Balance ... + double riskAmount; + + // + // Desired Magic Number ... + ulong magicNumber; +}; + +// +struct XLastSignal +{ + datetime at; + string provider; +}; + +// +// END Definitions ... +// + +// +// START Usefull Functions ... +// + +// +// Add Specific Provider to List ... +void Add( + XBaseSignalProvider &item, // item want to add + XBaseSignalProvider &buffer[] // Destination buffer +) +{ + // + ArrayResize( + buffer, + ArraySize(buffer) + 1); + + // + buffer[ArraySize(buffer) - 1] = item; +} + +// +// END Usefull Functions ... +// diff --git a/MQLTestWorkspace/X121/14030217/Classes/x-saherelm.xtrade.class.ex5 b/MQLTestWorkspace/X121/14030217/Classes/x-saherelm.xtrade.class.ex5 new file mode 100644 index 0000000..bc2ae55 Binary files /dev/null and b/MQLTestWorkspace/X121/14030217/Classes/x-saherelm.xtrade.class.ex5 differ diff --git a/MQLTestWorkspace/X121/14030217/Classes/x-saherelm.xtrade.class.mq5 b/MQLTestWorkspace/X121/14030217/Classes/x-saherelm.xtrade.class.mq5 new file mode 100644 index 0000000..24b7d54 --- /dev/null +++ b/MQLTestWorkspace/X121/14030217/Classes/x-saherelm.xtrade.class.mq5 @@ -0,0 +1,4538 @@ +/////////////////////////////////////////////////////// +// +// 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 + +// +// START Definitions ... +// + +// +// Model an Open Position ... +struct XPosition +{ + // + // 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; + + // + // Position Comment ... + string comment; +}; + +// +// 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 pocitionID; + + // + // 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 smybol; + + // + // Order Comment ... + string comment; + + // + ENUM_TIMEFRAMES period; +}; + +// +// 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; + + // + // 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; +}; + +// +// Model a Position with all of it's Supports ... +struct XPositionPack +{ + // + ulong ticket; + + // + XPosition position; + + // + int supportOrdersCount; + int supportPositionsCount; + + // + XOrder supportOrders[]; + XPosition supportPositions[]; +}; + +// +// 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; +}; + +// +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); + +// +// END Definitions ... +// + +// +// START Import and Inclused requirements ... +// + +// +// Includes ... +#include +#include "../Libraries/x-saherelm.log.lib.mq5" +#include "../Libraries/x-saherelm.common.lib.mq5" +#include "../Libraries/x-saherelm.seriallizer.lib.mq5" + +// +// END Import and Inclused requirements ... +// + +// +// START 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)); + } +}; + +// +// END Overrides ... +// + +// +// a Class for Manage Trades ... +class XSCTrade +{ + // + // Public ... +public: + // + // Constructor ... + void XSCTrade( + int slippage, // Specify Slippage + ulong magicNumber // Specify Magic Number + ) + { + // + mSlippage = slippage; + mMagicNumber = magicNumber; + + // + mPeriodPrefix = "PR"; + + // + mTrader = new XSCTradeBase(); + + // + mTrader.SetAsyncMode(false); + mTrader.SetDeviationInPoints(mSlippage); + mTrader.SetExpertMagicNumber(mMagicNumber); + + // + // Setting Log Level ... + mTrader.LogLevel(LOG_LEVEL_ERRORS); + + // + // Prepare Trade Event Materials ... + // + mDaysForRead = 1; + mScanStarted = false; + + // + // Reset On Trade Counter ... + ResetOnTradeContext(); + + // + // Init On Trade Context ... + InitOnTradeContext(); + } + + // + // Deconstructor ... + void ~XSCTrade() + { + } + + // + // START Event Processing ... + // + + // + // This Must be Called Every time OnTrade Event Happening ... + 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; + } + + // + // Process On Trade Requirement + void HandleOnTradeEvent( + XOnTradeHandlerState &result // Hold's Result + ) + { + // + if (mScanStarted) + { + ProcessOnTradeContext(result); + } + else + { + InitOnTradeContext(); + } + } + + // + // Event Emitters ... + + // + // STATE Changed ... + + // + // Clear Trade State Changed Event Handlers ... + void ClearOnTradeStateChangedEventHandlers() + { + // + ArrayFree(mTradeStateChangedEventHandlers); + + // + ArrayResize(mTradeStateChangedEventHandlers, 0); + } + + // + // Add New Deals Changed Event Handler ... + void AddOnTradeStateChangedEventHandler(TOnTradeStateChanged handler) + { + // + ArrayResize( + mTradeStateChangedEventHandlers, + ArraySize(mTradeStateChangedEventHandlers) + 1); + + // + mTradeStateChangedEventHandlers[ArraySize(mTradeStateChangedEventHandlers) - 1] = handler; + } + + // + // DEALS ... + + // + // Clear Deals Changed Event Handlers ... + void ClearOnDealsChangedEventHandlers() + { + // + ArrayFree(mDealsChangedEventHandlers); + + // + ArrayResize(mDealsChangedEventHandlers, 0); + } + + // + // Add New Deals Changed Event Handler ... + void AddOnDealsChangedEventHandler(TOnDealsChanged handler) + { + // + ArrayResize( + mDealsChangedEventHandlers, + ArraySize(mDealsChangedEventHandlers) + 1); + + // + mDealsChangedEventHandlers[ArraySize(mDealsChangedEventHandlers) - 1] = handler; + } + + // + // ORDERS ... + + // + // Clear Orders Changed Event Handlers ... + void ClearOnOrdersChangedEventHandlers() + { + // + ArrayFree(mOrdersChangedEventHandlers); + + // + ArrayResize(mOrdersChangedEventHandlers, 0); + } + + // + // Add New Orders Changed Event Handler ... + void AddOnOrdersChangedEventHandler(TOnOrdersChanged handler) + { + // + ArrayResize( + mOrdersChangedEventHandlers, + ArraySize(mOrdersChangedEventHandlers) + 1); + + // + mOrdersChangedEventHandlers[ArraySize(mOrdersChangedEventHandlers) - 1] = handler; + } + + // + // POSITIONS ... + + // + // Clear Positions Changed Event Handlers ... + void ClearOnPositionsChangedEventHandlers() + { + // + ArrayFree(mPositionsChangedEventHandlers); + + // + ArrayResize(mPositionsChangedEventHandlers, 0); + } + + // + // Add New Positions Changed Event Handler ... + void AddOnPositionsChangedEventHandler(TOnPositionsChanged handler) + { + // + ArrayResize( + mPositionsChangedEventHandlers, + ArraySize(mPositionsChangedEventHandlers) + 1); + + // + mPositionsChangedEventHandlers[ArraySize(mPositionsChangedEventHandlers) - 1] = handler; + } + + // + // TPSL ... + + // + // Clear Stop Loss Event Handlers ... + void ClearOnStopLossEventHandlers() + { + // + ArrayFree(mStopLossEventHandlers); + + // + ArrayResize(mStopLossEventHandlers, 0); + } + + // + // Add New Stop Loss Event Handler ... + void AddOnStopLossEventHandler(TOnStopLoss handler) + { + // + ArrayResize( + mStopLossEventHandlers, + ArraySize(mStopLossEventHandlers) + 1); + + // + mStopLossEventHandlers[ArraySize(mStopLossEventHandlers) - 1] = handler; + } + + // + // Clear Take Profit Event Handlers ... + void ClearOnTakeProfitEventHandlers() + { + // + ArrayFree(mTakeProfitEventHandlers); + + // + ArrayResize(mTakeProfitEventHandlers, 0); + } + + // + // Add New Stop Loss Event Handler ... + void AddOnTakeProfitEventHandler(TOnTakeProfit handler) + { + // + ArrayResize( + mTakeProfitEventHandlers, + ArraySize(mTakeProfitEventHandlers) + 1); + + // + mTakeProfitEventHandlers[ArraySize(mTakeProfitEventHandlers) - 1] = handler; + } + + // + // END Event Processing ... + // + + // + // START Provided Functions ... + // + + // + // Count Currently Open Positions ... + int CountPositions( + string symbol = "", // Specified Symbol + ENUM_POSITION_TYPE type = NULL // Specified Type + ) + { + // + int result = 0; + + // + int allPositions = 0; + int longPositions = 0; + int shortPositions = 0; + + // + int positionsCount = PositionsTotal(); + if (positionsCount <= 0) + { + return result; + } + + // + for (int i = 0; i < positionsCount; i++) + { + // + if (!mPositionInfo.SelectByIndex(i)) + { + continue; + } + + // + if (mPositionInfo.Magic() != mMagicNumber) + { + continue; + } + + // + string positionSymbol = mPositionInfo.Symbol(); + + // + ENUM_POSITION_TYPE positionType = mPositionInfo.PositionType(); + + // + if ( + type == NULL && + StringLen(symbol) <= 0) + { + // + allPositions++; + + // + continue; + } + else if ( + type != NULL && + StringLen(symbol) > 0) + { + // + if (type == positionType && + symbol == positionSymbol) + { + // + if (type == POSITION_TYPE_BUY) + { + longPositions++; + } + else + { + shortPositions++; + } + + // + continue; + } + } + else if (StringLen(symbol) > 0) + { + // + if (positionSymbol == symbol) + { + // + allPositions++; + + // + continue; + } + } + else if (type != NULL) + { + // + if (type == positionType) + { + // + if (type == POSITION_TYPE_BUY) + { + longPositions++; + } + else + { + shortPositions++; + } + + // + continue; + } + } + } + + // + // Specify Result ... + if ( + type == NULL && + StringLen(symbol) <= 0) + { + // + result = allPositions; + } + else if ( + type != NULL && + StringLen(symbol) > 0) + { + // + if (type == POSITION_TYPE_BUY) + { + result = longPositions; + } + else + { + result = shortPositions++; + } + } + else if (StringLen(symbol) > 0) + { + // + result = allPositions; + } + else if (type != NULL) + { + // + if (type == POSITION_TYPE_BUY) + { + result = longPositions; + } + else + { + result = shortPositions; + } + } + + // + return result; + } + + // + // Retrieve Max In Profit Position Ticket ... + ulong GetMaxInProfitPosition( + string symbol = "", // Specified Symbol + ENUM_POSITION_TYPE type = NULL // Specified Type + ) + { + // + ulong result = -1; + + // + double profit = 0; + + // + int positionsCount = PositionsTotal(); + if (positionsCount <= 0) + { + return result; + } + + // + for (int i = 0; i < positionsCount; i++) + { + // + if (!mPositionInfo.SelectByIndex(i)) + { + continue; + } + + // + if (mPositionInfo.Magic() != mMagicNumber) + { + continue; + } + + // + ulong positionTicket = mPositionInfo.Ticket(); + + // + string positionSymbol = mPositionInfo.Symbol(); + + // + double positionProfit = mPositionInfo.Profit(); + double positionAbsProfit = MathAbs(positionProfit); + if (positionProfit <= 0) + { + continue; + } + + // + ENUM_POSITION_TYPE positionType = mPositionInfo.PositionType(); + + // + if ( + type == NULL && + StringLen(symbol) <= 0) + { + // + if (profit < positionAbsProfit) + { + // + result = positionTicket; + profit = positionAbsProfit; + } + + // + continue; + } + else if ( + type != NULL && + StringLen(symbol) > 0) + { + // + if (type == positionType && + symbol == positionSymbol) + { + // + if (type == POSITION_TYPE_BUY) + { + // + if (profit < positionAbsProfit) + { + // + result = positionTicket; + profit = positionAbsProfit; + } + } + else + { + // + if (profit < positionAbsProfit) + { + // + result = positionTicket; + profit = positionAbsProfit; + } + } + + // + continue; + } + } + else if (StringLen(symbol) > 0) + { + // + if (positionSymbol == symbol) + { + // + if (profit < positionAbsProfit) + { + // + result = positionTicket; + profit = positionAbsProfit; + } + + // + continue; + } + } + else if (type != NULL) + { + // + if (type == positionType) + { + // + if (type == POSITION_TYPE_BUY) + { + // + if (profit < positionAbsProfit) + { + // + result = positionTicket; + profit = positionAbsProfit; + } + } + else + { + // + if (profit < positionAbsProfit) + { + // + result = positionTicket; + profit = positionAbsProfit; + } + } + + // + continue; + } + } + } + + // + return result; + } + + // + // Retrieve Max In DrawDown Position Ticket ... + ulong GetMaxInDrawDownPosition( + string symbol = "", // Specified Symbol + ENUM_POSITION_TYPE type = NULL // Specified Type + ) + { + // + ulong result = -1; + + // + double profit = 0; + + // + int positionsCount = PositionsTotal(); + if (positionsCount <= 0) + { + return result; + } + + // + for (int i = 0; i < positionsCount; i++) + { + // + if (!mPositionInfo.SelectByIndex(i)) + { + continue; + } + + // + if (mPositionInfo.Magic() != mMagicNumber) + { + continue; + } + + // + ulong positionTicket = mPositionInfo.Ticket(); + + // + string positionSymbol = mPositionInfo.Symbol(); + + // + double positionProfit = mPositionInfo.Profit(); + double positionAbsProfit = MathAbs(positionProfit); + if (positionProfit >= 0) + { + continue; + } + + // + ENUM_POSITION_TYPE positionType = mPositionInfo.PositionType(); + + // + if ( + type == NULL && + StringLen(symbol) <= 0) + { + // + if (profit < positionAbsProfit) + { + // + result = positionTicket; + profit = positionAbsProfit; + } + + // + continue; + } + else if ( + type != NULL && + StringLen(symbol) > 0) + { + // + if (type == positionType && + symbol == positionSymbol) + { + // + if (type == POSITION_TYPE_BUY) + { + // + if (profit < positionAbsProfit) + { + // + result = positionTicket; + profit = positionAbsProfit; + } + } + else + { + // + if (profit < positionAbsProfit) + { + // + result = positionTicket; + profit = positionAbsProfit; + } + } + + // + continue; + } + } + else if (StringLen(symbol) > 0) + { + // + if (positionSymbol == symbol) + { + // + if (profit < positionAbsProfit) + { + // + result = positionTicket; + profit = positionAbsProfit; + } + + // + continue; + } + } + else if (type != NULL) + { + // + if (type == positionType) + { + // + if (type == POSITION_TYPE_BUY) + { + // + if (profit < positionAbsProfit) + { + // + result = positionTicket; + profit = positionAbsProfit; + } + } + else + { + // + if (profit < positionAbsProfit) + { + // + result = positionTicket; + profit = positionAbsProfit; + } + } + + // + continue; + } + } + } + + // + return result; + } + + // + // Retrieve Specific Position's Profit ... + double GetPositionProfit( + const ulong ticket // Specified Position Ticket + ) + { + // + double result = 0; + + // + int positionsCount = PositionsTotal(); + if (positionsCount <= 0) + { + return result; + } + + // + for (int i = 0; i < positionsCount; i++) + { + // + if (!mPositionInfo.SelectByIndex(i)) + { + continue; + } + + // + if (mPositionInfo.Magic() != mMagicNumber) + { + continue; + } + + // + ulong positionTicket = mPositionInfo.Ticket(); + if (positionTicket != ticket) + { + continue; + } + + // + result = mPositionInfo.Profit(); + break; + } + + // + return result; + } + + // + // Retrieve Specific Position's OpenDate ... + datetime GetPositionOpenDate( + const ulong ticket // Specified Position Ticket + ) + { + // + datetime result = 0; + + // + int positionsCount = PositionsTotal(); + if (positionsCount <= 0) + { + return result; + } + + // + for (int i = 0; i < positionsCount; i++) + { + // + if (!mPositionInfo.SelectByIndex(i)) + { + continue; + } + + // + if (mPositionInfo.Magic() != mMagicNumber) + { + continue; + } + + // + ulong positionTicket = mPositionInfo.Ticket(); + if (positionTicket != ticket) + { + continue; + } + + // + result = mPositionInfo.Time(); + break; + } + + // + return result; + } + + // + // Retrieve Specific Position's Comment ... + string GetPositionComment( + const ulong ticket // Specified Position Ticket + ) + { + // + string result = ""; + + // + int positionsCount = PositionsTotal(); + if (positionsCount <= 0) + { + return result; + } + + // + for (int i = 0; i < positionsCount; i++) + { + // + if (!mPositionInfo.SelectByIndex(i)) + { + continue; + } + + // + if (mPositionInfo.Magic() != mMagicNumber) + { + continue; + } + + // + ulong positionTicket = mPositionInfo.Ticket(); + if (positionTicket != ticket) + { + continue; + } + + // + result = mPositionInfo.Comment(); + break; + } + + // + return result; + } + + // + // Retrieve All Open Positions Profit ... + double GetPositionsProfit( + string symbol = "", // Specified Symbol + ENUM_POSITION_TYPE type = NULL // Specified Type + ) + { + // + double result = 0; + + // + int positionsCount = PositionsTotal(); + if (positionsCount <= 0) + { + return result; + } + + // + for (int i = 0; i < positionsCount; i++) + { + // + if (!mPositionInfo.SelectByIndex(i)) + { + continue; + } + + // + if (mPositionInfo.Magic() != mMagicNumber) + { + continue; + } + + // + ulong positionTicket = mPositionInfo.Ticket(); + + // + string positionSymbol = mPositionInfo.Symbol(); + + // + double positionProfit = mPositionInfo.Profit(); + + // + ENUM_POSITION_TYPE positionType = mPositionInfo.PositionType(); + + // + if ( + type == NULL && + StringLen(symbol) <= 0) + { + // + result += positionProfit; + + // + continue; + } + else if ( + type != NULL && + StringLen(symbol) > 0) + { + // + if (type == positionType && + symbol == positionSymbol) + { + // + if (type == POSITION_TYPE_BUY) + { + result += positionProfit; + } + else + { + result += positionProfit; + } + + // + continue; + } + } + else if (StringLen(symbol) > 0) + { + // + if (positionSymbol == symbol) + { + result += positionProfit; + + // + continue; + } + } + else if (type != NULL) + { + // + if (type == positionType) + { + // + if (type == POSITION_TYPE_BUY) + { + result += positionProfit; + } + else + { + result += positionProfit; + } + + // + continue; + } + } + } + + // + return result; + } + + // + // Find Oldes Position ... + ulong GetOldestPosition( + string symbol = "", // Specified Symbol + ENUM_POSITION_TYPE type = NULL // Specified Type + ) + { + // + ulong result = 0; + + // + int age = 0; + + // + int positionsCount = PositionsTotal(); + if (positionsCount <= 0) + { + return result; + } + + // + for (int i = 0; i < positionsCount; i++) + { + // + if (!mPositionInfo.SelectByIndex(i)) + { + continue; + } + + // + if (mPositionInfo.Magic() != mMagicNumber) + { + continue; + } + + // + ulong positionTicket = mPositionInfo.Ticket(); + + // + string positionSymbol = mPositionInfo.Symbol(); + + // + double positionProfit = mPositionInfo.Profit(); + double positionAbsProfit = MathAbs(positionProfit); + if (positionProfit >= 0) + { + continue; + } + + // + ENUM_POSITION_TYPE positionType = mPositionInfo.PositionType(); + + // + string positionComment = mPositionInfo.Comment(); + ENUM_TIMEFRAMES positionPeriod = ExtractPositionPeriod(positionComment); + + // + // Calculate Position's Age ... + datetime positionOpenTime = mPositionInfo.Time(); + + // + // Retrieve Trade Open Bar Index based on Current Period ... + int positionOpenBarIndex = iBarShift( + positionSymbol, + positionPeriod, + positionOpenTime); + + // + // Calculate Trade Life ... + int positionAge = MathAbs(0 - positionOpenBarIndex); + + // + if ( + type == NULL && + StringLen(symbol) <= 0) + { + // + if (age < positionAge) + { + // + age = positionAge; + result = positionTicket; + } + + // + continue; + } + else if ( + type != NULL && + StringLen(symbol) > 0) + { + // + if (type == positionType && + symbol == positionSymbol) + { + // + if (type == POSITION_TYPE_BUY) + { + // + if (age < positionAge) + { + // + age = positionAge; + result = positionTicket; + } + } + else + { + // + if (age < positionAge) + { + // + age = positionAge; + result = positionTicket; + } + } + + // + continue; + } + } + else if (StringLen(symbol) > 0) + { + // + if (positionSymbol == symbol) + { + // + if (age < positionAge) + { + // + age = positionAge; + result = positionTicket; + } + + // + continue; + } + } + else if (type != NULL) + { + // + if (type == positionType) + { + // + if (type == POSITION_TYPE_BUY) + { + // + if (age < positionAge) + { + // + age = positionAge; + result = positionTicket; + } + } + else + { + // + if (age < positionAge) + { + // + age = positionAge; + result = positionTicket; + } + } + + // + continue; + } + } + } + + // + return result; + } + + // + // 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 = "" // comment + ) + { + // + bool result = false; + + // + string mPeriodStr = GeneratePositionPeriodComment(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 = "" // comment + ) + { + // + bool result = false; + + // + string mPeriodStr = GeneratePositionPeriodComment(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 = "" // comment + ) + { + // + bool result = false; + + // + string mPeriodStr = GeneratePositionPeriodComment(period); + + // + comment += mPeriodStr; + + // + result = mTrader.BuyStop( + volume, + price, + symbol, + sl, + tp, + typeTime, + expiration, + comment); + + // + return result; + } + + // + // 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 = "" // comment + ) + { + // + bool result = false; + + // + string mPeriodStr = GeneratePositionPeriodComment(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 = "" // comment + ) + { + // + bool result = false; + + // + string mPeriodStr = GeneratePositionPeriodComment(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 = "" // comment + ) + { + // + bool result = false; + + // + string mPeriodStr = GeneratePositionPeriodComment(period); + + // + comment += mPeriodStr; + + // + result = mTrader.SellStop( + volume, + price, + symbol, + sl, + tp, + typeTime, + expiration, + comment); + + // + return result; + } + + // + // Modify Position ... + bool Modify( + const ulong ticket, // position ticket + double sl = 0, // stop loss price + double tp = 0, // take profit + string comment = "" // comment + ) + { + // + bool result = false; + + // + // Validate Args ... + if (tp <= 0 && sl <= 0) + { + result = false; + return result; + } + + // + // Use Position Comment when there isn't new One ... + if (StringLen(comment) == 0) + { + comment = GetPositionComment(ticket); + } + + // + result = mTrader.PositionModify( + ticket, + sl, + tp, + comment); + + // + return result; + } + + // + // Close Position By Ticket ... + bool Close( + ulong ticket, // Position Ticket + string comment = "" // Close Position By Specific Comment + ) + { + // + bool result = false; + + // + // Try to Select Position ... + if (!mPositionInfo.SelectByTicket(ticket)) + { + return result; + } + + // + // Close Position By Specific Comment ... + result = mTrader.PositionClose( + ticket, + mSlippage, + comment); + + // + return result; + } + + // + // Close All Positions ... + void CloseAllPositions( + string comment = "" // Close Position By Specific Comment + ) + { + // + int positionsCount = PositionsTotal(); + if (positionsCount <= 0) + { + return; + } + + // + for (int i = 0; i < positionsCount; i++) + { + // + if (!mPositionInfo.SelectByIndex(i)) + { + continue; + } + + // + if (mPositionInfo.Magic() != mMagicNumber) + { + continue; + } + + // + ulong positionTicket = mPositionInfo.Ticket(); + Close( + positionTicket, + comment); + } + } + + // + // Close Partial By Ticket ... + bool ClosePartial( + ulong ticket, // Position Ticket + double volume, // Volume Size for Partial Closing + string comment = "" // Close Position By Specific Comment + ) + { + // + bool result = false; + + // + if (!mPositionInfo.SelectByTicket(ticket)) + { + return result; + } + + // + result = mTrader.PositionClosePartial( + ticket, + volume, + mSlippage, + comment); + + // + return result; + } + + // + // Find Position Open Bar Index ... + int GetPositionOpenBarIndex( + const ulong ticket // position ticket + ) + { + // + int result = -1; + + // + int positionsCount = PositionsTotal(); + if (positionsCount <= 0) + { + return result; + } + + // + for (int i = 0; i < positionsCount; i++) + { + // + if (!mPositionInfo.SelectByIndex(i)) + { + continue; + } + + // + if (mPositionInfo.Magic() != mMagicNumber) + { + continue; + } + + // + ulong positionTicket = mPositionInfo.Ticket(); + if (positionTicket != ticket) + { + continue; + } + + // + string symbol = mPositionInfo.Symbol(); + datetime openAt = mPositionInfo.Time(); + string comment = mPositionInfo.Comment(); + ENUM_TIMEFRAMES period = ExtractPositionPeriod(comment); + + // + result = iBarShift( + symbol, + period, + openAt); + } + + // + return result; + } + + // + bool GetPosition( + XPosition &position, // Holds result ... + ulong ticket // Required Position Ticket ... + ) + { + // + bool result = false; + + // + XPosition positions[]; + GetPositions(positions); + int positionsCount = ArraySize(positions); + if (positionsCount <= 0) + { + return result; + } + + // + for (int i = 0; i < positionsCount; i++) + { + // + XPosition iPosition = positions[i]; + + // + result = iPosition.ticket == ticket; + if (!result) + { + continue; + } + + // + position = iPosition; + break; + } + + // + return result; + } + + // + // Retrieve Positions as an Array ... + void GetPositions( + XPosition &result[] // Hold Result ... + ) + { + // + Clean(result); + + // + int positionsCount = PositionsTotal(); + if (positionsCount <= 0) + { + return; + } + + // + for (int i = 0; i < positionsCount; i++) + { + // + if (!mPositionInfo.SelectByIndex(i)) + { + continue; + } + + // + if (mPositionInfo.Magic() != mMagicNumber) + { + continue; + } + + // + ulong magic = mPositionInfo.Magic(); + ulong ticket = mPositionInfo.Ticket(); + string symbol = mPositionInfo.Symbol(); + datetime openAt = mPositionInfo.Time(); + double swap = mPositionInfo.Swap(); + double sl = mPositionInfo.StopLoss(); + double tp = mPositionInfo.TakeProfit(); + double profit = mPositionInfo.Profit(); + double volume = mPositionInfo.Volume(); + string comment = mPositionInfo.Comment(); + double entry = mPositionInfo.PriceOpen(); + double price = mPositionInfo.PriceCurrent(); + double commission = mPositionInfo.Commission(); + ENUM_POSITION_TYPE type = mPositionInfo.PositionType(); + ENUM_TIMEFRAMES period = ExtractPositionPeriod(comment); + + // + XPosition iPosition = {}; + + // + iPosition.tp = tp; + iPosition.sl = sl; + iPosition.swap = swap; + iPosition.type = type; + iPosition.magic = magic; + iPosition.entry = entry; + iPosition.price = price; + iPosition.ticket = ticket; + iPosition.symbol = symbol; + iPosition.period = period; + iPosition.volume = volume; + iPosition.openAt = openAt; + iPosition.profit = profit; + iPosition.comment = comment; + iPosition.commission = commission; + + // + Add( + iPosition, + result); + } + } + + // + void GetPositions( + XPosition &result[], // Hold Result ... + string symbol, // Trading Symbol ... + ENUM_TIMEFRAMES period // Trading Period ... + ) + { + // + Clean(result); + + // + bool hasPeriod = period != NULL; + bool hasSymbol = symbol != NULL && StringLen(symbol) > 0; + + // + int positionsCount = PositionsTotal(); + if (positionsCount <= 0) + { + return; + } + + // + XPosition allPositions[]; + GetPositions(allPositions); + + // + if (!hasPeriod && !hasSymbol) + { + // + Copy( + allPositions, + result); + + // + return; + } + + // + for (int i = 0; i < positionsCount; i++) + { + // + XPosition iPosition = allPositions[i]; + + // + if (hasSymbol && + symbol != iPosition.symbol) + { + continue; + } + + // + ENUM_TIMEFRAMES positionPeriod = ExtractPositionPeriod(iPosition.comment); + if (hasPeriod && + period != positionPeriod) + { + continue; + } + + // + Add( + iPosition, + result); + } + } + + // + // Execute a Signal ... + bool ExecuteSignal( + XSignal &signal, // Signal ... + string comment = "", // Position Comment ... + ENUM_ORDER_TYPE_TIME lifetime = ORDER_TIME_GTC, // Order LifeTime ... + datetime expiration = 0 // order expiration time + ) + { + // + bool result = false; + + // + double currentEntry = GetEntry( + signal.symbol, + signal.type); + bool isLong = IsLong(signal.type); + + // + ResetLastError(); + + // + if (signal.mode == X_ORDER_MODE_MARKET) + { + // + // Execute MArket Orders ... + if (isLong) + { + // + result = Buy( + signal.symbol, + signal.period, + signal.volume, + signal.entry, + signal.sl, + signal.tp, + comment); + } + else + { + // + result = Sell( + signal.symbol, + signal.period, + signal.volume, + signal.entry, + signal.sl, + signal.tp, + comment); + } + } + else if (signal.mode == X_ORDER_MODE_LIMIT) + { + // + // Execute Limit Orders ... + + // + // Check Conditions ... + + // + // Check Price ... + result = isLong + ? signal.entry < currentEntry + : signal.entry > currentEntry; + if (!result) + { + return result; + } + + // + // Check Expiration Date ... + result = (lifetime == ORDER_TIME_SPECIFIED || lifetime == ORDER_TIME_SPECIFIED_DAY) + ? expiration > 0 + : true; + if (!result) + { + return result; + } + + // + if (isLong) + { + // + result = BuyLimit( + signal.symbol, + signal.period, + signal.volume, + signal.entry, + signal.sl, + signal.tp, + lifetime, + expiration, + comment); + } + else + { + // + result = SellLimit( + signal.symbol, + signal.period, + signal.volume, + signal.entry, + signal.sl, + signal.tp, + lifetime, + expiration, + comment); + } + } + else if (signal.mode == X_ORDER_MODE_STOP) + { + // + // Execute Stop Orders ... + + // + // Check Conditions ... + + // + // Check Price ... + result = isLong + ? signal.entry > currentEntry + : signal.entry < currentEntry; + if (!result) + { + return result; + } + + // + // Check Expiration Date ... + result = (lifetime == ORDER_TIME_SPECIFIED || lifetime == ORDER_TIME_SPECIFIED_DAY) + ? expiration > 0 + : true; + if (!result) + { + return result; + } + + // + if (isLong) + { + // + result = BuyStop( + signal.symbol, + signal.period, + signal.volume, + signal.entry, + signal.sl, + signal.tp, + lifetime, + expiration, + comment); + } + else + { + // + result = SellStop( + signal.symbol, + signal.period, + signal.volume, + signal.entry, + signal.sl, + signal.tp, + lifetime, + expiration, + comment); + } + } + + // + if (!result) + { + LogMessage("Error: " + (string)GetLastError() + ", " + GetErrorDescription(GetLastError())); + } + else + { + // + // Retrieve Last Position Ticket ... + ulong ticket = GetLastOpenPositionTicket(); + + // + // Check Position have Support Signals or not ... + int supportsCount = ArraySize(signal.supports); + if (supportsCount > 0) + { + // + int executed = 0; + for (int i = 0; i < supportsCount; i++) + { + // + XSignal iSupport = signal.supports[i]; + + // + int supIndex = i + 1; + string iComment = GenerateSupportSignalComment( + ticket, + supIndex); + + // + bool isExecuted = ExecuteSignal( + iSupport, + iComment); + if (isExecuted) + { + executed++; + } + } + + // + result = executed == supportsCount; + } + } + + // + return result; + } + + // + // Execute a Collection of Signals ... + int ExecuteSignals( + const XSignal &signals[], // an Array of Signals ... + string comment = "", // Position Comment ... + ENUM_ORDER_TYPE_TIME lifetime = ORDER_TIME_GTC, // Order LifeTime ... + datetime expiration = 0 // order expiration time + ) + { + // + int result = 0; + + // + int signalsCount = ArraySize(signals); + if (signalsCount <= 0) + { + return result; + } + + // + for (int i = 0; i < signalsCount; i++) + { + // + XSignal iSignal = signals[i]; + + // + if (StringLen(comment) == 0) + { + comment = GenerateProvidersString(iSignal); + } + + // + bool isExecuted = ExecuteSignal( + iSignal, + comment, + lifetime, + expiration); + + // + if (isExecuted) + { + result++; + } + } + + // + return result; + } + + // + // Retrieve in Profit Positions ... + void GetInProfitPositions( + XPosition &result[] // Hold Result ... + ) + { + // + Clean(result); + + // + XPosition allPositions[]; + GetPositions(allPositions); + int positionsCount = ArraySize(allPositions); + if (positionsCount <= 0) + { + return; + } + + // + for (int i = 0; i < positionsCount; i++) + { + // + XPosition iPosition = allPositions[i]; + + // + if (iPosition.profit > 0) + { + Add( + iPosition, + result); + } + } + } + + // + // Retrieve in Drawdown Positions ... + void GetInDrawdownPositions( + XPosition &result[] // Hold Result ... + ) + { + // + Clean(result); + + // + XPosition allPositions[]; + GetPositions(allPositions); + int positionsCount = ArraySize(allPositions); + if (positionsCount <= 0) + { + return; + } + + // + for (int i = 0; i < positionsCount; i++) + { + // + XPosition iPosition = allPositions[i]; + + // + if (iPosition.profit < 0) + { + Add( + iPosition, + result); + } + } + } + + // + // Close a Collection Of Positions ... + int ClosePositions( + XPosition &positions[], // Positions to Close ... + string comment = "" // Specified 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; + } + + // + // Retrieve All Orders ... + void GetOrders( + XOrder &result[], // Holdes Result .... + string symbol, // Trading Symbol ... + ENUM_TIMEFRAMES period, // Trading TimeFrame ... + ENUM_ORDER_STATE state = NULL // Order State ... + ) + { + // + Clean(result); + + // + int ordersCount = OrdersTotal(); + if (ordersCount <= 0) + { + return; + } + + // + // Since Orders may be so more than positions ... + // start Orders Collectiong Loops reverse ... + for (int i = ordersCount - 1; i >= 0; i--) + { + // + if (!mOrderInfo.SelectByIndex(i)) + { + continue; + } + + // + if (mOrderInfo.Magic() != mMagicNumber) + { + continue; + } + + // + // Reading Order Info ... + long magic = mOrderInfo.Magic(); + double sl = mOrderInfo.StopLoss(); + ulong ticket = mOrderInfo.Ticket(); + double tp = mOrderInfo.TakeProfit(); + string oSymbol = mOrderInfo.Symbol(); + string comment = mOrderInfo.Comment(); + long pocitionID = mOrderInfo.PositionId(); + double openPrice = mOrderInfo.PriceOpen(); + datetime setupAt = mOrderInfo.TimeSetup(); + datetime executedAt = mOrderInfo.TimeDone(); + ENUM_ORDER_STATE oState = mOrderInfo.State(); + ENUM_ORDER_TYPE type = mOrderInfo.OrderType(); + double currentPrice = mOrderInfo.PriceCurrent(); + datetime expiredAt = mOrderInfo.TimeExpiration(); + double initialVolume = mOrderInfo.VolumeInitial(); + double currentVolume = mOrderInfo.VolumeCurrent(); + double stopLimitPrice = mOrderInfo.PriceStopLimit(); + ENUM_ORDER_TYPE_TIME lifetime = mOrderInfo.TypeTime(); + ENUM_ORDER_TYPE_FILLING filling = mOrderInfo.TypeFilling(); + + // + if (StringLen(symbol) > 0 && symbol != oSymbol) + { + continue; + } + + // + ENUM_TIMEFRAMES oPeriod = ExtractPositionPeriod(comment); + if (period != NULL && period != oPeriod) + { + continue; + } + + // + if (state != NULL && oState != state) + { + continue; + } + + // + // Now Create an instance of XOrder struct and fill it by + // retrieved data, and add it to results ... + XOrder iOrder = {}; + + // + iOrder.sl = sl; + iOrder.tp = tp; + iOrder.type = type; + iOrder.magic = magic; + iOrder.state = oState; + iOrder.ticket = ticket; + iOrder.smybol = oSymbol; + iOrder.period = oPeriod; + iOrder.setupAt = setupAt; + iOrder.comment = comment; + iOrder.filling = filling; + iOrder.lifetime = lifetime; + iOrder.expiredAt = expiredAt; + iOrder.openPrice = openPrice; + iOrder.pocitionID = pocitionID; + iOrder.executedAt = executedAt; + iOrder.currentPrice = currentPrice; + iOrder.initialVolume = initialVolume; + iOrder.currentVolume = currentVolume; + iOrder.stopLimitPrice = stopLimitPrice; + + // + Add( + iOrder, + result); + } + } + + // + int CountOrders() + { + return OrdersTotal(); + } + + // + // Cancel Specific Order ... + bool CancelOrder(ulong ticket) + { + return mTrader.OrderDelete(ticket); + } + + // + // Cancel Specific Orders ... + bool CancelOrders( + XOrder &orders[]) + { + // + bool result = false; + + // + 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 = isDeleted; + } + } + + // + return result; + } + + // + // Retrieve All Deals ... + void GetDeals(XDeal &result[]) + { + // + Clean(result); + + // + int dealsCount = HistoryDealsTotal(); + if (dealsCount <= 0) + { + return; + } + + // + for (int i = dealsCount - 1; i >= 0; i--) + { + // + if (!mDealInfo.SelectByIndex(i)) + { + continue; + } + + // + if (mDealInfo.Magic() != mMagicNumber) + { + continue; + } + + // + // Reading Order Info ... + double swap = mDealInfo.Swap(); + ulong magic = mDealInfo.Magic(); + ulong order = mDealInfo.Order(); + ulong ticket = mDealInfo.Ticket(); + datetime time = mDealInfo.Time(); + double price = mDealInfo.Price(); + string symbol = mDealInfo.Symbol(); + double profit = mDealInfo.Profit(); + double volume = mDealInfo.Volume(); + string comment = mDealInfo.Comment(); + ulong positionId = mDealInfo.PositionId(); + ENUM_DEAL_ENTRY entry = mDealInfo.Entry(); + double commission = mDealInfo.Commission(); + ENUM_DEAL_TYPE type = mDealInfo.DealType(); + ENUM_DEAL_REASON reason = (ENUM_DEAL_REASON)HistoryDealGetInteger( + ticket, + DEAL_REASON); + + // + XDeal iDeal = {}; + + // + iDeal.swap = swap; + iDeal.time = time; + iDeal.type = type; + iDeal.magic = magic; + iDeal.entry = entry; + iDeal.order = order; + iDeal.price = price; + iDeal.ticket = ticket; + iDeal.symbol = symbol; + iDeal.profit = profit; + iDeal.volume = volume; + iDeal.reason = reason; + iDeal.comment = comment; + iDeal.positionId = positionId; + iDeal.commission = commission; + + // + Add( + iDeal, + result); + } + } + + // + // Retrieve all History Orders of Specific Deal ... + int GetDealHistory( + const XDeal &deal, // Specified Deal + XOrder &history[] // Hold Result + ) + { + // + int result = 0; + + // + Clean(history); + + // + bool isHistorySelected = HistorySelectByPosition(deal.positionId); + if (!isHistorySelected) + { + return result; + } + + // + int ordersCount = HistoryOrdersTotal(); + if (ordersCount <= 0) + { + return result; + } + + // + for (int i = 0; i < ordersCount; i++) + { + // + if (!mHistoryOrderInfo.SelectByIndex(i)) + { + continue; + } + + // + ulong ticket = mHistoryOrderInfo.Ticket(); + + // + long positionId = mHistoryOrderInfo.PositionId(); + if (positionId != deal.positionId) + { + continue; + } + + // + // Reading Order Info ... + long magic = mHistoryOrderInfo.Magic(); + double sl = mHistoryOrderInfo.StopLoss(); + double tp = mHistoryOrderInfo.TakeProfit(); + string oSymbol = mHistoryOrderInfo.Symbol(); + string comment = mHistoryOrderInfo.Comment(); + double openPrice = mHistoryOrderInfo.PriceOpen(); + datetime setupAt = mHistoryOrderInfo.TimeSetup(); + datetime executedAt = mHistoryOrderInfo.TimeDone(); + ENUM_ORDER_STATE oState = mHistoryOrderInfo.State(); + ENUM_ORDER_TYPE type = mHistoryOrderInfo.OrderType(); + double currentPrice = mHistoryOrderInfo.PriceCurrent(); + datetime expiredAt = mHistoryOrderInfo.TimeExpiration(); + double initialVolume = mHistoryOrderInfo.VolumeInitial(); + double currentVolume = mHistoryOrderInfo.VolumeCurrent(); + double stopLimitPrice = mHistoryOrderInfo.PriceStopLimit(); + ENUM_ORDER_TYPE_TIME lifetime = mHistoryOrderInfo.TypeTime(); + ENUM_ORDER_TYPE_FILLING filling = mHistoryOrderInfo.TypeFilling(); + + // + ENUM_TIMEFRAMES oPeriod = ExtractPositionPeriod(comment); + + // + // Now Create an instance of XOrder struct and fill it by + // retrieved data, and add it to results ... + XOrder iOrder = {}; + + // + iOrder.sl = sl; + iOrder.tp = tp; + iOrder.type = type; + iOrder.magic = magic; + iOrder.state = oState; + iOrder.ticket = ticket; + iOrder.smybol = oSymbol; + iOrder.period = oPeriod; + iOrder.setupAt = setupAt; + iOrder.comment = comment; + iOrder.filling = filling; + iOrder.lifetime = lifetime; + iOrder.expiredAt = expiredAt; + iOrder.openPrice = openPrice; + iOrder.pocitionID = positionId; + iOrder.executedAt = executedAt; + iOrder.currentPrice = currentPrice; + iOrder.initialVolume = initialVolume; + iOrder.currentVolume = currentVolume; + iOrder.stopLimitPrice = stopLimitPrice; + + // + Add( + iOrder, + history); + } + + // + result = ArraySize(history); + + // + return result; + } + + // + // Find Deal Period ... + ENUM_TIMEFRAMES GetDealPeriod(const XDeal &deal) + { + // + ENUM_TIMEFRAMES result = NULL; + + // + XOrder history[]; + int historyCount = GetDealHistory( + deal, + history); + if (historyCount <= 0) + { + return result; + } + + // + for (int i = 0; i < historyCount; i++) + { + // + XOrder iOrder = history[i]; + + // + if (StringLen(iOrder.comment) == 0) + { + continue; + } + + // + string periodStr = ExtractPositionPeriodString(iOrder.comment); + if (StringLen(periodStr) > 0) + { + // + result = ToPeriod(periodStr); + break; + } + } + + // + return result; + } + + // + // Generate String Representation Of Position's Time Frame ... + string GeneratePositionPeriodComment(ENUM_TIMEFRAMES period) + { + // + string result = mPeriodPrefix + "(" + ToString(period) + ")"; + + // + return result; + } + + // + string ExtractPositionPeriodString(string comment) + { + // + string result = ""; + + // + if (StringLen(comment) <= 0) + { + return result; + } + + // + result = ExtractString( + comment, + mPeriodPrefix + "(", + ")"); + + // + return result; + } + + // + // Extract Position Time Frame From it's Comment ... + ENUM_TIMEFRAMES ExtractPositionPeriod(string comment) + { + // + ENUM_TIMEFRAMES result = NULL; + + // + string periodStr = ExtractPositionPeriodString(comment); + if (StringLen(periodStr) <= 0) + { + return result; + } + + // + result = ToPeriod(periodStr); + + // + return result; + } + + // + // 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; + } + + // + // SUPPORT Signals ... + + // + // Retrieve a Position if Exists + // by all of it's Supported Positon/Order (s) ... + bool GetPositionPack( + ulong ticket, // Sepcified Position's Ticket + XPositionPack &pack // Hold Result ... + ) + { + // + bool result = false; + + // + int positionsCount = CountPositions(); + int ordersCount = CountOrders(); + if (ordersCount <= 0 && positionsCount <= 0) + { + return result; + } + + // + XPosition position; + result = GetPosition( + position, + ticket); + if (!result) + { + return result; + } + + // + XOrder supportOrders[]; + XPosition supportPositions[]; + + // + XOrder orders[]; + GetOrders( + orders, + position.symbol, + position.period, + ORDER_STATE_PLACED); + ordersCount = ArraySize(orders); + + // + // Select Orders ... + if (ordersCount > 0) + { + // + for (int i = 0; i < ordersCount; i++) + { + // + XOrder iOrder = orders[i]; + + // + string params[]; + bool hasSupport = ExtractSupportParams( + iOrder.comment, + params); + if (hasSupport) + { + // + ulong parentTicket = ExtractParentTicket(iOrder.comment); + if (parentTicket == ticket) + { + // + Add( + iOrder, + supportOrders); + } + } + } + } + + // + XPosition positions[]; + GetPositions( + positions, + position.symbol, + position.period); + positionsCount = ArraySize(positions); + + // + // Select Positions ... + if (positionsCount > 0) + { + // + for (int i = 0; i < positionsCount; i++) + { + // + XPosition iPosition = positions[i]; + + // + string params[]; + bool hasSupport = ExtractSupportParams( + iPosition.comment, + params); + if (hasSupport) + { + // + ulong parentTicket = ExtractParentTicket(iPosition.comment); + if (parentTicket == ticket) + { + // + Add( + iPosition, + supportPositions); + } + } + } + } + + // + int supportOrdersCount = ArraySize(supportOrders); + int supportPositionsCount = ArraySize(supportPositions); + + // + pack.ticket = ticket; + pack.position = position; + + // + Copy(supportOrders, + pack.supportOrders); + Copy(supportPositions, + pack.supportPositions); + + // + pack.supportOrdersCount = supportOrdersCount; + pack.supportPositionsCount = supportPositionsCount; + + // + result = true; + + // + return result; + } + + // + // Extract specific Positions Pack ... + // in this senario there is no need to Position exists itself ... + bool GetPositionPack( + ulong ticket, // Specified Positions Ticket ... + string symbol, // Specified Position Symbol ... + ENUM_TIMEFRAMES period, // Specified Position Period ... + XPositionPack &pack // Hold Result ... + ) + { + // + bool result = false; + + // + // NOTE: We Have to Force Retrieve Position's pack event + // it's parent Position not Eists ... + pack.ticket = ticket; + pack.supportOrdersCount = 0; + Clean(pack.supportOrders); + pack.supportPositionsCount = 0; + Clean(pack.supportPositions); + + // + XPosition position; + bool hasPosition = GetPosition( + position, + ticket); + if (hasPosition) + { + pack.position = position; + } + + // + XOrder supportOrders[]; + XPosition supportPositions[]; + + // + XOrder orders[]; + GetOrders( + orders, + symbol, // Specified Symbol ... + period, // Specified Period + ORDER_STATE_PLACED // Just UnTriggered Orders ... + ); + int ordersCount = ArraySize(orders); + + // + // Select Orders ... + if (ordersCount > 0) + { + // + for (int i = 0; i < ordersCount; i++) + { + // + XOrder iOrder = orders[i]; + + // + string params[]; + bool hasSupport = ExtractSupportParams( + iOrder.comment, + params); + if (hasSupport) + { + // + ulong parentTicket = ExtractParentTicket(iOrder.comment); + if (parentTicket == ticket) + { + // + Add( + iOrder, + supportOrders); + } + } + } + } + + // + int supportOrdersCount = ArraySize(supportOrders); + if (supportOrdersCount > 0) + { + // + pack.supportOrdersCount = supportOrdersCount; + + // + Copy( + supportOrders, + pack.supportOrders); + } + + // + XPosition positions[]; + GetPositions( + positions, + symbol, // Specified Symbol ... + period // Specified Period ... + ); + int positionsCount = ArraySize(positions); + + // + // Select Positions ... + if (positionsCount > 0) + { + // + for (int i = 0; i < positionsCount; i++) + { + // + XPosition iPosition = positions[i]; + + // + string params[]; + bool hasSupport = ExtractSupportParams( + iPosition.comment, + params); + if (hasSupport) + { + // + ulong parentTicket = ExtractParentTicket(iPosition.comment); + if (parentTicket == ticket) + { + // + Add( + iPosition, + supportPositions); + } + } + } + } + + // + int supportPositionsCount = ArraySize(supportPositions); + if (supportPositionsCount > 0) + { + // + pack.supportPositionsCount = supportPositionsCount; + + // + Copy( + supportPositions, + pack.supportPositions); + } + + // + result = supportOrdersCount > 0 || supportPositionsCount > 0; + + // + return result; + } + + // + // Extract Specific Deals Position's Pack ... + // this used when a Position SL or TP triggered and we want to close + // all it's Supported Packs ... + bool GetDealPack( + const XDeal &deal, + XPositionPack &pack) + { + // + bool result = false; + + // + ulong ticket = deal.positionId; + ENUM_TIMEFRAMES dealPeriod = GetDealPeriod(deal); + string dealSymbol = deal.symbol; + + // + // So We Have to Get Positions Pack ... + result = GetPositionPack( + ticket, + dealSymbol, + dealPeriod, + pack); + + // + return result; + } + + // + // END Provided Functions ... + // + + // + // Protected ... +protected: + // + // Private ... + + // + // EVENTS Handlers 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); + } + } + + // + // TPSL ... + + // + 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); + } + } + + // + 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); + } + } + +private: + // + // using deviation, it must be in Point ... + int mSlippage; + + // + // using magic number ... + ulong mMagicNumber; + + // + // using CTrade instance ... + XSCTradeBase mTrader; + + // + // Deals Info ... + CDealInfo mDealInfo; + + // + // Order Info ... + COrderInfo mOrderInfo; + + // + // using PositionInfo instance ... + CPositionInfo mPositionInfo; + + // + // History Orders ... + CHistoryOrderInfo mHistoryOrderInfo; + + // + // ADDITIONAL Data ... + + // + string mPeriodPrefix; + + // + // START Trade Processing ... + // + + // + int mDaysForRead; + + // + // set the limits of the trade history on the global scope ... + + // + // // start date for trade history in cache ... + datetime mStartDate; + + // + // end date for trade history in cache ... + datetime mEndDate; + + // + // global OnTrade counters ... + + // + // number of active orders ... + int mOrdersCount; + + // + // number of open positions ... + int mPositionsCount; + + // + // number of deals in the trade history cache ... + int mDealsCount; + + // + // number of orders in the trade history cache ... + int mHistoryOrdersCount; + + // + // flag of counter relevance ... + bool mScanStarted; + + // + // 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(); + } + + // + // 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; + } + + // + // 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[]; + + // + // TPSL ... + TOnStopLoss mStopLossEventHandlers[]; + TOnTakeProfit mTakeProfitEventHandlers[]; + + // + // END Trade Processing ... + // +}; + +// +// START Usefull Functions ... +// + +// +// Add Specific XPosition to Specified Array ... +void Add( + XDeal &item, + XDeal &buffer[]) +{ + // + ArrayResize( + buffer, + ArraySize(buffer) + 1); + + // + buffer[ArraySize(buffer) - 1] = item; +} +void Add( + XOrder &item, + XOrder &buffer[]) +{ + // + ArrayResize( + buffer, + ArraySize(buffer) + 1); + + // + buffer[ArraySize(buffer) - 1] = item; +} +void Add( + XPosition &item, + XPosition &buffer[]) +{ + // + ArrayResize( + buffer, + ArraySize(buffer) + 1); + + // + buffer[ArraySize(buffer) - 1] = item; +} + +// +// Clear All Items Inside Array ... +void Clean(XDeal &buffer[]) +{ + // + ArrayFree(buffer); + ArrayResize(buffer, 0); +} +void Clean(XOrder &buffer[]) +{ + // + ArrayFree(buffer); + ArrayResize(buffer, 0); +} +void Clean(XPosition &buffer[]) +{ + // + ArrayFree(buffer); + ArrayResize(buffer, 0); +} + +// +// Generate Identifier Tag ... +string GenerateTag(XSignal &info) +{ + // + string result = ""; + + // + result = info.symbol + "," + ToString(info.period); + + // + return result; +} + +// +// Convert Position to Signal ... +XSignal ToSignalInfo( + XPosition &position) +{ + // + XSignal result; + + // + result.tp = position.tp; + result.sl = position.sl; + result.type = position.type; + result.entry = position.entry; + result.symbol = position.symbol; + result.period = position.period; + result.volume = position.volume; + + // + return result; +} + +// +// AGE Calculations ... +// + +// +// 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.smybol, + 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; +} + +// +// OLDEST Detection ... + +// +// Get Oldest Deal ... +int GetOldest( + XDeal &item, // Hold Result ... + XDeal &items[] // Source Array ... +) +{ + // + int result = 0; + + // + 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 = 0; + + // + 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 = 0; + + // + 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; +} + +// +// END Usefull Functions ... +// diff --git a/MQLTestWorkspace/X121/14030217/Documents/.gitkeep b/MQLTestWorkspace/X121/14030217/Documents/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/MQLTestWorkspace/X121/14030217/Documents/JsModules/x-color.tools.js b/MQLTestWorkspace/X121/14030217/Documents/JsModules/x-color.tools.js new file mode 100644 index 0000000..c3ac5f9 --- /dev/null +++ b/MQLTestWorkspace/X121/14030217/Documents/JsModules/x-color.tools.js @@ -0,0 +1,506 @@ +/** + * XColor Tools Module ... + * a module for handle colorify text contents in node js ... + * + * Maintainer + * + * Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) + */ + +// +//#region Module Imports ... +const XValueTools = require("./x-value.tools"); +//#endregion + +// +//#region Constants ... +/** + * these are available style which can applied to an string ... + */ +const AVAILABLE_STYLES = { + // + Bold: "\x1b[1m", + Dim: "\x1b[2m", + Underlined: "\x1b[4m", + Blink: "\x1b[5m", + ReverseFandB: "\x1b[7m", + Hidden: "\x1b[8m", + // + // Commonly used for reset all Styles ... + Reset: "\x1b[0m" +}; + +/** + * these are available foreground colors which can applied to an string ... + */ +const AVAILABLE_FOREGROUND_COLORS = { + Default: "\x1b[39m", + Black: "\x1b[30m", + Red: "\x1b[31m", + Green: "\x1b[32m", + Yellow: "\x1b[33m", + Blue: "\x1b[34m", + Magenta: "\x1b[35m", + Cyan: "\x1b[36m", + LightGray: "\x1b[37m", + DarkGray: "\x1b[90m", + LightRed: "\x1b[91m", + LightGreen: "\x1b[92m", + LightYellow: "\x1b[93m", + LightBlue: "\x1b[94m", + LightMagenta: "\x1b[95m", + LightCyan: "\x1b[96m", + White: "\x1b[97m", +}; + +/** + * these are available background colors which can applied to an string ... + */ +const AVAILABLE_BACKGROUND_COLORS = { + Default: "\x1b[49m", + Black: "\x1b[40m", + Red: "\x1b[41m", + Green: "\x1b[42m", + Yellow: "\x1b[43m", + Blue: "\x1b[44m", + Magenta: "\x1b[45m", + Cyan: "\x1b[46m", + LightGray: "\x1b[47m", + DarkGray: "\x1b[100m", + LightRed: "\x1b[101m", + LightGreen: "\x1b[102m", + LightYellow: "\x1b[103m", + LightBlue: "\x1b[104m", + LightMagenta: "\x1b[105m", + LightCyan: "\x1b[106m", + White: "\x1b[107m", +}; + +/** + * these are available style names, which exports from module and + * users can use them ... + */ +const STYLE_NAMES = { + Bold: "Bold", + Dim: "Dim", + Underlined: "Underlined", + Blink: "Blink", + ReverseFandB: "ReverseFandB", + Hidden: "Hidden", + Reset: "Reset", +}; + +/** + * these are available color names, which exports from module and + * users can use them ... + */ +const COLOR_NAMES = { + Default: "Default", + Black: "Black", + Red: "Red", + Green: "Green", + Yellow: "Yellow", + Blue: "Blue", + Magenta: "Magenta", + Cyan: "Cyan", + LightGray: "LightGray", + DarkGray: "DarkGray", + LightRed: "LightRed", + LightGreen: "LightGreen", + LightYellow: "LightYellow", + LightBlue: "LightBlue", + LightMagenta: "LightMagenta", + LightCyan: "LightCyan", + White: "White", +}; +//#endregion + +// +//#region Actions ... +/** + * apply specified style and color on a content ... + * + * @param {string} content specified content for styling ... + * @param {string} color specific color name for using to styling ... + * @param {string} style soecufic style name to use ... + * @param {boolean} toForeground apply specified color as foreground ... + * @param {boolean} toBackground apply specified color as background ... + * @returns {string} styled content ... + */ +function apply( + content, + color, + style, + toForeground = true, + toBackground = false +) { + // + let result = content; + + // + // Validate Arg ... + if (!XValueTools.isValidArg(content)) { + return result; + } + + // + // Detect and Validate Style and Apply it ... + let eStyle = AVAILABLE_STYLES[style]; + if (XValueTools.isValidArg(eStyle)) { + result = `${eStyle}${result}${AVAILABLE_STYLES.Reset}`; + } + + // + // Detect and Validate Foreground Color and Apply it ... + let eFColor = AVAILABLE_FOREGROUND_COLORS[color]; + if ( + !!toForeground + && XValueTools.isValidArg(eFColor) + ) { + result = `${eFColor}${result}${AVAILABLE_STYLES.Reset}`; + } + + // + // Detect and Validate Background Color and Apply it ... + let eBColor = AVAILABLE_BACKGROUND_COLORS[color]; + if ( + !!toBackground + && XValueTools.isValidArg(eBColor) + ) { + result = `${eBColor}${result}${AVAILABLE_STYLES.Reset}`; + } + +} + +/** + * apply specific style on a content ... + * + * @param {string} content specific content which going to styled ... + * @param {string} style a member of STYLE_NAMES which specified that which style going to applied to content ... + * @returns {string} styled content ... + */ +function applyStyle(content, style) { + // + // Validate Arg ... + if (!XValueTools.isValidArg(content)) { + return content; + } + + // + let eStyle = AVAILABLE_STYLES[style]; + if (eStyle === undefined) { + return content; + } + + // + return `${eStyle}${content}${AVAILABLE_STYLES.Reset}`; +} + +/** + * apply specific foreground color on a content ... + * + * @param {string} content specific content which going to colorified ... + * @param {string} color a member of COLOR_NAMES which specified that which color going to applied to content ... + * @returns {string} colorified content ... + */ +function applyForegroundColor(content, color) { + // + // Validate Arg ... + if (!XValueTools.isValidArg(content)) { + return content; + } + + // + let eColor = AVAILABLE_FOREGROUND_COLORS[color]; + if (eColor === undefined) { + return content; + } + + // + return `${eColor}${content}${AVAILABLE_STYLES.Reset}`; +} + +/** + * apply specific background color on a content ... + * + * @param {string} content specific content which going to colorified ... + * @param {string} color a member of COLOR_NAMES which specified that which color going to applied to content ... + * @returns {string} colorified content ... + */ +function applyBackgroundColor(content, color) { + // + // Validate Arg ... + if (!XValueTools.isValidArg(content)) { + return content; + } + + // + let eColor = AVAILABLE_BACKGROUND_COLORS[color]; + if (eColor === undefined) { + return content; + } + + // + return `${eColor}${content}${AVAILABLE_STYLES.Reset}`; +} + +/** + * generate style and color applier expression ... + * + * @param {string} color specific color name for using to styling ... + * @param {string} style soecufic style name to use ... + * @param {boolean} reset close applier string by reset styles ... + * @param {boolean} toForeground apply specified color as foreground ... + * @param {boolean} toBackground apply specified color as background ... + * @returns {string} style and color applier string ... + */ +function getApplier( + style = "", + color = "", + reset = false, + toForeground = true, + toBackground = false +) { + // + let result = ""; + + // + // Detect and Validate Style and Apply it ... + let eStyle = AVAILABLE_STYLES[style]; + if (XValueTools.isValidArg(eStyle)) { + result = `${eStyle}`; + } + + // + // Detect and Validate Foreground Color and Apply it ... + let eFColor = AVAILABLE_FOREGROUND_COLORS[color]; + if ( + !!toForeground + && XValueTools.isValidArg(eFColor) + ) { + result = `${eFColor}`; + } + + // + // Detect and Validate Background Color and Apply it ... + let eBColor = AVAILABLE_BACKGROUND_COLORS[color]; + if ( + !!toBackground + && XValueTools.isValidArg(eBColor) + ) { + result = `${eBColor}`; + } + + // + if ( + !!reset && + result.length > 0 + ) { + result = `${result}${AVAILABLE_STYLES.Reset}`; + } + + // + return result; +} + +/** + * generate style applier expression ... + * + * @param {string} style soecufic style name to use ... + * @param {boolean} reset close applier string by reset styles ... + * @returns {string} style applier string ... + */ +function getStyleApplier( + style = "", + reset = false +) { + // + let result = ""; + + // + // Detect and Validate Style and Apply it ... + let eStyle = AVAILABLE_STYLES[style]; + if (XValueTools.isValidArg(eStyle)) { + result = `${eStyle}`; + } + + // + if ( + !!reset && + result.length > 0 + ) { + result = `${result}${AVAILABLE_STYLES.Reset}`; + } + + // + return result; +} + +/** + * generate color applier expression ... + * + * @param {string} color specific color name for using to styling ... + * @param {boolean} reset close applier string by reset styles ... + * @param {boolean} toForeground apply specified color as foreground ... + * @param {boolean} toBackground apply specified color as background ... + * @returns {string} color applier string ... + */ +function getColorApplier( + color = "", + reset = false, + toForeground = true, + toBackground = false +) { + // + let result = ""; + + // + // Detect and Validate Foreground Color and Apply it ... + let eFColor = AVAILABLE_FOREGROUND_COLORS[color]; + if ( + !!toForeground + && XValueTools.isValidArg(eFColor) + ) { + result = `${eFColor}`; + } + + // + // Detect and Validate Background Color and Apply it ... + let eBColor = AVAILABLE_BACKGROUND_COLORS[color]; + if ( + !!toBackground + && XValueTools.isValidArg(eBColor) + ) { + result = `${eBColor}`; + } + + // + if ( + !!reset && + result.length > 0 + ) { + result = `${result}${AVAILABLE_STYLES.Reset}`; + } + + // + return result; +} + +/** + * colorified specific content ... + * + * @param {string} content specified content for styling ... + * @param {string} color specific color name for using to styling ... + * @param {boolean} toForeground apply specified color as foreground ... + * @param {boolean} toBackground apply specified color as background ... + * @returns {string} + */ +function colorifyContent( + content = "", + color = "", + toForeground = true, + toBackground = false +) { + // + let result = content; + + // + if (!XValueTools.isValidArg(content)) { + return result; + } + + // + // Finde Colors ... + + // + // Detect and Validate Foreground Color and Apply it ... + let eFColor = AVAILABLE_FOREGROUND_COLORS[color]; + if ( + !!toForeground + && XValueTools.isValidArg(eFColor) + ) { + result = `${eFColor}${result}`; + } + + // + // Detect and Validate Background Color and Apply it ... + let eBColor = AVAILABLE_BACKGROUND_COLORS[color]; + if ( + !!toBackground + && XValueTools.isValidArg(eBColor) + ) { + result = `${eBColor}${result}`; + } + + // + if ( + result.length > 0 + && ( + XValueTools.isValidArg(eFColor) || + XValueTools.isValidArg(eBColor) + ) + ) { + result = `${result}${AVAILABLE_STYLES.Reset}`; + } + + // + return result; +} + +/** + * apply style on specific content ... + * + * @param {string} content specified content for styling ... + * @param {string} style soecufic style name to use ... + * @returns {string} + */ +function stylifiyContent( + content = "", + style = "", +) { + // + let result = content; + + // + if (!XValueTools.isValidArg(content)) { + return result; + } + + // + // Detect and Validate Style and Apply it ... + let eStyle = AVAILABLE_STYLES[style]; + if (XValueTools.isValidArg(eStyle)) { + result = `${eStyle}${result}`; + } + + // + if ( + result.length > 0 + && XValueTools.isValidArg(eStyle) + ) { + result = `${result}${AVAILABLE_STYLES.Reset}`; + } + + // + return result; +} +//#endregion + +// +//#region Module Exports ... +module.exports = { + // + STYLE_NAMES, + COLOR_NAMES, + // + apply, + applyStyle, + getApplier, + getColorApplier, + getStyleApplier, + colorifyContent, + stylifiyContent, + applyForegroundColor, + applyBackgroundColor, +} +//#endregion \ No newline at end of file diff --git a/MQLTestWorkspace/X121/14030217/Documents/JsModules/x-file.tools.js b/MQLTestWorkspace/X121/14030217/Documents/JsModules/x-file.tools.js new file mode 100644 index 0000000..a1642a4 --- /dev/null +++ b/MQLTestWorkspace/X121/14030217/Documents/JsModules/x-file.tools.js @@ -0,0 +1,830 @@ +/** + * XFile Tools Module ... + * a module for handle all file/folder manipulating task in node js ... + * + * Maintainer + * + * Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) + */ + +// +//#region Module Imports ... +const fs = require('fs'); +const os = require('os'); +const Path = require('path'); +const http = require('http'); +const https = require('https'); +const XValueTools = require('./x-value.tools'); +//#endregion + +// +//#region Constants ... +/** + * current os path separators ... + */ +const PathSeparator = Path.sep; + +/** + * current directory ... + */ +const CurrentDir = __dirname; +//#endregion + +// +//#region Actions ... +// +//#region Global ... +/** + * retrieve a path status ... + * + * @param {string} path a path value to check ... + * @returns an stat object ... + */ +function getStatus(path = '') { + // + if (!XValueTools.isValidArg(path)) { + return undefined; + } + + // + return fs.statSync(path); +} + +/** + * retrieve user's Home path ... + * + * @returns {string} a path ... + */ +function getHomePath() { + return os.homedir(); +} +//#endregion + +// +//#region Path ... +/** + * retrieve the base name of specific address path ... + * + * @param {string} path address of file or folder ... + * @returns string ... + */ +function basename(path = '') { + // + if (!XValueTools.isValidArg(path)) { + return ''; + } + + // + const result = Path.basename(path); + return result; +} + +/** + * join several path segments together ... + * + * @param {...string} path path params ... + * @returns a joined paths ... + */ +function joinPath(...path) { + return Path.join(...path); +} + +/** + * resolve a relative path to absolute ... + * + * @param {string[]} path a path value to check ... + * @returns {string} + */ +function resolvePath(...path) { + return Path.resolve(...path); +} +//#endregion + +// +//#region File ... +/** + * determines a path destination is a file or not ... + * + * @param {string} path a path value to check ... + * @returns a boolean value ... + */ +function isFileExists(path = '') { + // + if (!XValueTools.isValidArg(path)) { + return false; + } + + // + try { + const stat = getStatus(path); + if (!stat) { + return false; + } + + // + return stat.isFile(); + } catch { + return false; + } +} + +/** + * remove a file ... + * + * @param {string} path a file path ... + * @returns {Promise} action done or not ... + */ +function removeFile(path = '') { + return new Promise((resolve) => { + // + if (!isFileExists(path)) { + resolve(false); + } + + // + fs.unlink(path, (err) => { + // + if (err) { + resolve(false); + return; + } + + // + resolve(true); + }); + }); +} + +/** + * copy a file to destination path ... + * + * @param {string} source source file path ... + * @param {string} dest dest folder path ... + * @returns {Promise} action done or not ... + */ +function copyFile( + source = '', + dest = '' +) { + return new Promise((resolve) => { + // + if ( + !isFileExists(source) || + !isDirectoryExists(dest) + ) { + resolve(false); + return; + } + + // + const destFilePath = Path.join(dest, Path.basename(source)); + fs.copyFile(source, destFilePath, (err) => { + // + if (err) { + resolve(false); + return; + } + + // + resolve(true); + }); + }); +} + +/** + * reading specified file content ... + * + * @param {string} path a file path ... + * @returns {Promise} file content ... + */ +function readFile(path = '') { + return new Promise((resolve) => { + // + if (!isFileExists(path)) { + resolve(''); + return; + } + + // + fs.readFile(path, 'utf8', (err, content) => { + // + if (err) { + resolve(undefined); + return; + } + + // + resolve(content); + }); + }); +} + +/** + * write content to a file ... + * + * @param {string} path a file path ... + * @param {string} content the content which going to write to the file ... + * @param {bool} overwrite determines file overwrite if exists ... + * @returns {Promise} action done or not ... + */ +function writeFile( + path = '', + content = '', + overwrite = true +) { + return new Promise((resolve) => { + // + if (isFileExists(path) && !overwrite) { + // + resolve(false); + return; + } + + // + // Normalize Content ... + content = XValueTools.isValidArg(content) ? + content : + ''; + + // + fs.writeFile(path, content, (err) => { + // + if (err) { + // + resolve(false); + return; + } + + // + resolve(true); + }); + }); +} + +/** + * create a file ... + * + * @param {string} path file path ... + * @param {string} fileName file name ... + * @returns {Promise} action done or not ... + */ +function createFile( + path = '', + fileName = '' +) { + return new Promise((resolve) => { + // + const filePath = Path.join(path, fileName); + if ( + isFileExists(filePath) || + !XValueTools.isValidArg(path) || + !XValueTools.isValidArg(fileName) + ) { + // + resolve(false); + return; + } + + // + fs.writeFile(filePath, '', (err) => { + // + if (err) { + // + resolve(false); + return; + } + + // + resolve(true); + }); + }); +} + +/** + * remove a file name extension ... + * + * @param {string} name + * @returns {string} name without extension ... + */ +function removeFileExtension(name = '') { + return name.substring(0, name.lastIndexOf('.')) || name; +} + +/** + * retrieve a file extension ... + * + * @param {string} path a path which locate a file ... + * @returns {string} + */ +function getFileExtension(path = '') { + // + let result = ""; + + // + // Validate Arg ... + if ( + !XValueTools.isValidArg(path) + || !isFileExists(path) + ) { + return result; + } + + // + // Retrieve just file name ... + const fileName = basename(path); + result = fileName.replace( + removeFileExtension(fileName), + "" + ); + + // + return result; +} + +/** + * retrieve all files list recursively from specific path ... + * + * @param {string} path a source folder path ... + * @param {string[]} extensions which file extensions need to be listed, live empty for all files ... + * @returns {Promise} + */ +async function getRecursiveFilesList( + path = "", + extensions = [] +) { + // + let result = []; + + // + // Validate Args ... + if ( + !XValueTools.isValidArg(path) + || !isDirectoryExists(path) + ) { + return result; + } + + // + const contents = await getDirectoryContents(path); + for(const item of contents) { + // + const itemPath = joinPath( + path, + item + ); + + // + const isItemFile = isFileExists(itemPath); + if (isItemFile) { + // + const itemFileExtension = getFileExtension(itemPath); + const isFileInSupportedExtensions = + extensions === undefined || extensions.length === 0 + ? true + : extensions.includes(itemFileExtension) + ; + if (isFileInSupportedExtensions) { + result.push(itemPath); + } + } else if (isDirectoryExists(itemPath)) { + // + const itemPathFiles = await getRecursiveFilesList(itemPath, extensions); + result.push(...itemPathFiles); + } + } + + // + return result; +} +//#endregion + +// +//#region Directory ... +/** + * create a directory ... + * + * @param {string} path destination path including dir name ... + * @param {boolean} recursive create directories recursively ... + * @returns action done or not ... + */ +function createDirectory( + path = '', + recursive = true +) { + // + let result = false; + + // + if ( + isDirectoryExists(path) || + !XValueTools.isValidArg(path) + ) { + return false; + } + + // + try { + // + fs.mkdirSync(path, { recursive: recursive }); + result = true; + return result; + } catch { + return false; + } +} + +/** + * remove a directory ... + * + * @param {string} path destination path including dir name ... + * @param {boolean} recursive removes directories recursively ... + * @returns {Promise} action done or not ... + */ +function removeDirectory( + path = '', + recursive = false +) { + return new Promise((resolve) => { + // + if (!isDirectoryExists(path)) { + resolve(false); + return; + } + + // + fs.rm(path, { + recursive + }, (err) => { + // + if (err) { + resolve(false); + return; + } + + // + resolve(true); + }); + }); +} + +/** + * determines a path destination is a directory or not ... + * + * @param {string} path a folder path ... + * @returns represent destnation path is Directory or not ... + */ +function isDirectoryExists(path = '') { + // + if (!XValueTools.isValidArg(path)) { + return false; + } + + // + try { + // + const isExists = fs.existsSync(path); + if (!isExists) { + return false; + } + + // + const stat = getStatus(path); + if (!stat) { + return false; + } + + // + const result = stat.isDirectory(); + return result; + } catch { + return false; + } +} + +/** + * retrieve a directory content ... + * + * @param {string} path a folder path ... + * @returns {Promise} a collection of folder files ... + */ +function getDirectoryContents(path = '') { + return new Promise((resolve) => { + // + if (!isDirectoryExists(path)) { + resolve([]); + return; + } + + // + fs.readdir(path, (err, content) => { + // + if (err) { + resolve([]); + return; + } + + // + resolve(content); + }); + }); +} + +/** + * retrieve a directory files ... + * + * @param {string} path a folder path ... + * @returns {Promise} a collection of folder files ... + */ +function getDirectoryFiles( + path = '', + containsHiddenFiles = false +) { + return new Promise((resolve) => { + // + if (!isDirectoryExists(path)) { + resolve([]); + return; + } + + // + fs.readdir(path, (err, content) => { + // + if (err) { + resolve([]); + return; + } + + // + if (!containsHiddenFiles) { + content = content.filter(c => !c.startsWith('.')); + } + + // + const result = []; + content + .forEach(c => { + // + const cPath = Path.join(path, c); + if (isFileExists(cPath)) { + result.push(c); + } + }); + + // + resolve(result); + }); + }); +} + +/** + * retrieve a directory folders ... + * + * @param {string} path a folder path ... + * @returns {Promise} a collection of folder names ... + */ +function getDirectoryFolders(path = '') { + return new Promise((resolve) => { + // + if (!isDirectoryExists(path)) { + resolve([]); + return; + } + + // + fs.readdir(path, (err, content) => { + // + if (err) { + resolve([]); + return; + } + + // + const result = []; + content.forEach(c => { + // + const cPath = Path.join(path, c); + if (isDirectoryExists(cPath)) { + result.push(c); + } + }); + + // + resolve(result); + }); + }); +} + +/** + * copy a folder with all of it's content to dest ... + * + * @param {string} source source folder path ... + * @param {string} dest dest folder path ... + * @returns {Promise} action done or not ... + */ +async function copyFolder( + source = '', + dest = '' +) { + // + if ( + !isDirectoryExists(source) || + !XValueTools.isValidArg(dest) || + !XValueTools.isValidArg(source) + ) { + return false; + } + + // + const folderName = Path.basename(source); + const destPath = Path.join(dest, folderName); + + // + // Create Dest Path folder if not exists ... + if (!isDirectoryExists(destPath)) { + // + let result = createDirectory(destPath, true); + if (!result) { + return false; + } + } + + // + // Files ... + const files = await getDirectoryFiles(source); + if (files && files.constructor === Array && files.length > 0) { + // + const filesPromises = files.map(file => copyFile(Path.join(source, file), destPath)); + const filesResult = (await Promise.all(filesPromises)).every(r => !!r); + if (!filesResult) { + return false; + } + } + + // + // Folders ... + const folders = await getDirectoryFolders(source); + if (folders && folders.constructor === Array && folders.length > 0) { + // + const folderPromises = folders.map(folder => copyFolder(Path.join(source, folder), destPath)); + const filesResult = (await Promise.all(folderPromises)).every(r => !!r); + if (!filesResult) { + return false; + } + } + + // + return true; +} +//#endregion + +// +//#region Downloader ... +/** + * download a file from specific url and store it ... + * + * @param {string} filepath the file name and path which required to put download file on it ... + * @param {string} url the web url for downloading ... + */ +function download(filepath, url) { + // + // Validate Args ... + if ( + !XValueTools.isValidArg(url) + || !XValueTools.isValidURL(url) + || !XValueTools.isValidArg(filepath) + ) { + return; + } + + // + var file = fs.createWriteStream(filepath); + + // + if (url.startsWith('https:')) { + https.get(url, function (response) { + response.pipe(file); + }); + } else if (url.startsWith('http:')) { + http.get(url, function (response) { + response.pipe(file); + }); + } +} +//#endregion + +// +//#region JSON ... +/** + * read and parse a JSON content from a file ... + * + * @param {string} path source file path ... + * @returns {any} + */ +function readJSON(path = "") { + // + // Validate Args ... + if (!isFileExists(path)) { + return undefined; + } + + // + let result = undefined; + try { + result = require(path); + } catch { + result = undefined; + } + + // + return result; +} + +/** + * write a JSON Object content into a file ... + * + * @param {string} path dest file path ... + * @param {any} content an object which required to write to file ... + * @returns {Promise} + */ +async function writeJSON( + path = "", + content = undefined +) { + // + let result = false; + + // + // Validate Args ... + if (!XValueTools.isValidArg(path)) { + return result; + } + + // + // Normallize Content ... + if (content === undefined) { + content = {}; + } + + // + const contentString = XValueTools.beautifyJSON(content); + + // + result = await writeFile( + path, + contentString, + true + ); + + // + return result; +} +//#endregion +//#endregion + +// +//#region Module Exports ... +module.exports = { + // + CurrentDir, + PathSeparator, + + // + getStatus, + getHomePath, + + // + basename, + joinPath, + resolvePath, + + // + download, + + // + readJSON, + writeJSON, + + // + copyFile, + readFile, + writeFile, + createFile, + removeFile, + isFileExists, + getFileExtension, + removeFileExtension, + getRecursiveFilesList, + + // + copyFolder, + createDirectory, + removeDirectory, + createDirectory, + removeDirectory, + isDirectoryExists, + isDirectoryExists, + getDirectoryFiles, + getDirectoryFolders, + getDirectoryContents, +} +//#endregion \ No newline at end of file diff --git a/MQLTestWorkspace/X121/14030217/Documents/JsModules/x-shell.tools.js b/MQLTestWorkspace/X121/14030217/Documents/JsModules/x-shell.tools.js new file mode 100644 index 0000000..0ee13de --- /dev/null +++ b/MQLTestWorkspace/X121/14030217/Documents/JsModules/x-shell.tools.js @@ -0,0 +1,219 @@ +/** + * XShell Tools Module ... + * a module for handling shell actions and retrieve OS Info in node js ... + * + * Maintainer + * + * Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) + */ + +// +//#region Imports ... +const os = require('os'); +const process = require('process'); +const { exec } = require("child_process"); +const XFileTools = require('./x-file.tools'); +//#endregion + +// +//#region Constants ... +// +const OS = { + Aix: 'aix', + Darwin: 'darwin', + FreeBSD: 'freebsd', + Linux: 'linux', + OpenBSD: 'openbsd', + SnOS: 'sunos', + Windows: 'win32' +}; + +// +const isWindows = process.platform === OS.Windows; +//#endregion + +// +//#region Actions ... +// +//#region Pure shell commands ... +/** + * execute a command using NodeJS on shell ... + * + * @param {string} cmd command to execute ... + * @param {string} cwd working directory ... + * + * @returns Promise instance ... + */ +function execute(cmd, cwd) { + return new Promise((resolve, reject) => { + // + if (!cmd || cmd.toString().length === 0 || (cwd && !XFileTools.isDirectoryExists(cwd))) { + reject('invalid args ...'); + return; + } + + // + exec(cmd, { cwd }, (err, result, stdError) => { + // + if (err) { + reject(err); + return; + } + + // + if (stdError) { + // + // reject(stdError); + // return; + } + + // + resolve(result); + }); + }); +}; + +/** + * determines a command exists on host or not ... + * + * @param {string} name specific command name ... + * + * @returns boolean Promise ... + */ +function checkCommandExists(name) { + return new Promise(resolve => { + // + if (!name) { + resolve(false); + return; + } + + // + const cmd = isWindows ? `${name} >nul 2>&1` : `type ${name} >/dev/null 2>&1`; + execute(cmd).then(result => { + resolve(true); + }) + .catch(err => { + resolve(false); + }); + }); +} +//#endregion + +// +//#region required commands state ... +/** + * check al required commands exists or not ... + * + * @returns + */ +async function isRequiredCommandsExists() { + // + let result = false; + + // + // const isTarExists = await isTarCommandExists(); + // const isCatExists = await isCatCommandExists(); + // const isGrepExists = await isGrepCommandExists(); + // const isSedExists = await isSedCommandExists(); + const isNpmExists = await isNpmCommandExists(); + const isNgExists = await isNgCommandExists(); + const isIonicExists = await isIonicCommandExists(); + const isCordovaExists = await isCordovaCommandExists(); + + // + result = isNpmExists + && isNgExists + && isIonicExists + && isCordovaExists + ; + + // + return result; +} + +/** + * retrieve required commands state object ... + * + * @returns + */ +async function getRequiredCommandsStates() { + // + const result = {}; + + // + // const isTarExists = await isTarCommandExists(); + // const isCatExists = await isCatCommandExists(); + // const isGrepExists = await isGrepCommandExists(); + // const isSedExists = await isSedCommandExists(); + const isNpmExists = await isNpmCommandExists(); + const isNgExists = await isNgCommandExists(); + const isIonicExists = await isIonicCommandExists(); + const isCordovaExists = await isCordovaCommandExists(); + + // + result['npm'] = isNpmExists; + result['ng'] = isNgExists; + result['ionic'] = isIonicExists; + result['cordova'] = isCordovaExists; + + // + return result; +} +//#endregion + +// +//#region Commonly used Command Checkers ... +/** + * determines npm command exists or not ... + * + * @returns + */ +function isNpmCommandExists() { + return checkCommandExists('npm'); +} + +/** + * determines ng command exists or not ... + * + * @returns + */ +function isNgCommandExists() { + return checkCommandExists('ng'); +} + +/** + * determines ionic command exists or not ... + * + * @returns + */ +function isIonicCommandExists() { + return checkCommandExists('ionic'); +} + +/** + * determines cordova command exists or not ... + * + * @returns + */ +function isCordovaCommandExists() { + return checkCommandExists('cordova'); +} +//#endregion +//#endregion + +// +//#region Module Exports ... +module.exports = { + // + execute, + checkCommandExists, + isRequiredCommandsExists, + getRequiredCommandsStates, + + // + isNgCommandExists, + isIonicCommandExists, + isCordovaCommandExists, +} +//#endregion \ No newline at end of file diff --git a/MQLTestWorkspace/X121/14030217/Documents/JsModules/x-type-detector.tools.js b/MQLTestWorkspace/X121/14030217/Documents/JsModules/x-type-detector.tools.js new file mode 100644 index 0000000..86ed3d8 --- /dev/null +++ b/MQLTestWorkspace/X121/14030217/Documents/JsModules/x-type-detector.tools.js @@ -0,0 +1,268 @@ +/** + * DataType Tools Module ... + * a module for manipulate and detect supported data types in node js ... + * + * Maintainer + * + * Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) + */ + +// +//#region Constants ... +/** + * all supported data types ... + */ +const DataTypes = { + Null: 'null', + Date: 'date', + Array: 'array', + Object: 'object', + String: 'string', + Number: 'number', + Unknown: 'unknown', + Boolean: 'boolean', + Function: 'function', + Undefined: 'undefined', +}; +//#endregion + +// +//#region Actions ... +/** + * detect type of a content ... + * + * @param {any} value the content which going to check ... + * @returns + */ +function getType(value) { + // + const type = typeof value; + + // + let result = DataTypes.Unknown; + let dateIdentifier = '[object Date]'; + let constructor = value && value.constructor ? + value.constructor.toString() : + ''; + + // + switch (type) { + // + case 'undefined': + result = DataTypes.Undefined; + break; + + // + case 'boolean': + result = DataTypes.Boolean; + break; + + // + case 'string': + result = DataTypes.String; + break; + + // + case 'number': + result = DataTypes.Number; + break; + + // + case 'function': + result = DataTypes.Function; + break; + + // + case 'object': + // + // Null ... + if (value === null) { + result = DataTypes.Null; + } else + // + // Array ... + if (Array.isArray(value)) { + result = DataTypes.Array; + } else + // + // Data ... + if ( + value instanceof Date || + isFunction(value.getMonth) || + constructor.includes(dateIdentifier) || + Object.prototype.toString.call(value) === dateIdentifier + ) { + result = DataTypes.Date; + } else + // + // Object ... + { + result = DataTypes.Object; + } + break; + + // + default: + result = DataTypes.Unknown; + break; + } + + // + return result; +} + +/** + * retrieve an object constructor ... + * + * @param {any} value the content which going to check ... + * @returns + */ +function getConstructor(value) { + // + const result = value && value.constructor ? + value.constructor.toString() : + ''; + + // + return result; +} + +/** + * retrieve an object prototype ... + * + * @param {any} value the content which going to check ... + * @returns + */ +function getPrototype(value) { + // + const result = value ? + Object.prototype.toString.call(value) : + ''; + + // + return result; +} + +/** + * check an object is null or not ... + * + * @param {any} value the content which going to check ... + * @returns + */ +function isNull(value) { + return getType(value) === DataTypes.Null; +} + +/** + * check an object is undefined or not ... + * + * @param {any} value the content which going to check ... + * @returns + */ +function isUndefined(value) { + return getType(value) === DataTypes.Undefined; +} + +/** + * check an object is null or undefined or not ... + * + * @param {any} value the content which going to check ... + * @returns + */ +function isNullOrUndefined(value) { + return isNull(value) || isUndefined(value); +} + +/** + * check an object is a date or not ... + * + * @param {any} value the content which going to check ... + * @returns + */ +function isDate(value) { + return getType(value) === DataTypes.Date; +} + +/** + * check an object is number or not ... + * + * @param {any} value the content which going to check ... + * @returns + */ +function isNumber(value) { + return getType(value) === DataTypes.Number; +} + +/** + * check an object is string or not ... + * + * @param {any} value the content which going to check ... + * @returns + */ +function isString(value) { + return getType(value) === DataTypes.String; +} + +/** + * check an object is boolean or not ... + * + * @param {any} value the content which going to check ... + * @returns + */ +function isBoolean(value) { + return getType(value) === DataTypes.Boolean; +} + +/** + * check an object is an Array or not ... + * + * @param {any} value the content which going to check ... + * @returns + */ +function isArray(value) { + return getType(value) === DataTypes.Array; +} + +/** + * check an object is and Object or not ... + * + * @param {any} value the content which going to check ... + * @returns + */ +function isObject(value) { + return getType(value) === DataTypes.Object; +} + +/** + * check an object is a Function or not ... + * + * @param {any} value the content which going to check ... + * @returns + */ +function isFunction(value) { + return getType(value) === DataTypes.Function; +} +//#endregion + +// +//#region Module Exports ... +module.exports = { + // + DataTypes, + + // + getType, + getConstructor, + getPrototype, + isNull, + isUndefined, + isNullOrUndefined, + isDate, + isNumber, + isString, + isBoolean, + isArray, + isObject, + isFunction, +} +//#endregion \ No newline at end of file diff --git a/MQLTestWorkspace/X121/14030217/Documents/JsModules/x-value.tools.js b/MQLTestWorkspace/X121/14030217/Documents/JsModules/x-value.tools.js new file mode 100644 index 0000000..81cfcc4 --- /dev/null +++ b/MQLTestWorkspace/X121/14030217/Documents/JsModules/x-value.tools.js @@ -0,0 +1,1528 @@ +/** + * Value Tools Module ... + * a module for Validate args and values ... + * + * Maintainer + * + * Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) + */ + +// +//#region Imports ... +const XTypeTools = require('./x-type-detector.tools'); +//#endregion + +// +//#region Actions ... +/** +* validate a value as an argument ... +* +* @param {string} value the value which going to validate ... +* @returns +*/ +function isValidArg(value) { + // + let result = false; + + // + result = value && + value.length > 0; + + // + return result; +} + +/** + * validate a collection of valuea as an arguments ... + * + * @param {string|string[]} values the value collection which going to checked ... + * @returns + */ +function isValidArgs(values) { + // + // Normalize Values ... + const normalValues = toNormalArray(values); + if (!hasChildArray(normalValues)) { + return false; + } + + // + let result = normalValues.every(nv => isValidArg(nv)); + return result; +} + +/** + * converts content to an array object ... + * + * @param {string|string[]} content the content which required to normalized ... + * @returns {string[]} array object ... + */ +function toNormalArray(content = '') { + // + // Validate Args ... + if (!isValidArg(content)) { + return []; + } + + // + const result = Array.isArray(content) ? + [...content] : + content.includes(',') && + content !== ',' ? + [...content.split(',')] : + [content]; + + // + return result; +} + +/** + * determines value is array and has atleast one child ... + * + * @param {any} value the value which going to checked ... + * @returns {boolean} result of checking ... + */ +function hasChildArray(value) { + // + let result = false; + result = value && + Array.isArray(value) && + value.length > 0; + + // + return result; +} + +/** + * check an string is ends with specified symbol ... + * + * @param {string} symbol specified search symbol ... + * @param {string} value specified search content ... + * @param {boolean} ignoreCase specified search case sensitive or not ... + * @returns + */ +function endsWidth( + symbol = '', + value = '', + ignoreCase = true +) { + // + if (!isValidArg(value)) { + return false; + } + + // + if (!isValidArg(symbol)) { + return true; + } + + // + // TODO: uncomment it if necessary ... + // symbol = symbol.trim(); + + // + let result = false; + const subtractedContent = value.substring(value.length - symbol.length); + result = !!ignoreCase ? + subtractedContent + .toLowerCase() === symbol + .toLowerCase() : + subtractedContent === symbol; + + // + return result; +} + +/** + * surround specified content by provided symbol ... + * + * @param {string} symbol surround string ... + * @param {string} content used content to surrounded by symbol ... + * @returns surrounded content ... + */ +function surroundBy( + symbol = '', + content = '' +) { + // + // Validate Args ... + if (!isValidArg(content)) { + content = ''; + } + + // + if (!isValidArg(symbol)) { + symbol = ''; + } + + // + if (isSurrounded(symbol, content)) { + return content; + } + + // + const result = `${symbol}${content}${symbol}`; + return result; +} + +/** + * convert a parsed sign to clear string ... + * + * @param {string} value a parsed content ... + * @returns clear parsed signs ... + */ +function toStringExpression(value) { + // + let result = ''; + result = value; + + // + if ( + !value || + !isValidArg(value) || + !isSurroundedString(value) + ) { + return result; + } + + // + const startSymbol = value.charAt(0); + const endSymbol = value.charAt(value.length - 1); + + // + if (startSymbol !== endSymbol) { + return result; + } + + // + if ( + startSymbol === "\"" || + startSymbol === "\'" + ) { + result = clearSurround(startSymbol, value); + } + + // + return result; +} + + + +/** + * find and cleare proposed candidates from specified content ... + * + * @param {string|string[]} candidates the proposed string(s) whic going to cleared from content ... + * @param {string} content the destination content which used to find and replace candidates on it ... + * @returns cleared content ... + */ +function clearContent( + candidates, + content +) { + // + // Validate Args ... + if ( + !candidates || + !isValidArg(content) + ) { + return ''; + } + + // + // Normalize candidates ... + const normalCandidates = toNormalArray(candidates) + .filter(c => isValidArg(c)); + if (!hasChildArray(normalCandidates)) { + return content; + } + + // + // define regexp for content ... + const regExpExpression = normalCandidates.join('|'); + const regExp = new RegExp( + regExpExpression, + 'gi' + ); + + // + let result = ''; + result = content.replace(regExp, ''); + + // + return result; +} + +/** + * clear surrounded symbol from content ... + * + * @param {string} symbol specified search symbol ... + * @param {string} content specified content to clear ... + * @returns + */ +function clearSurround( + symbol = '', + content = '' +) { + // + // Validate Args ... + if ( + !isValidArg(content) || + (isValidArg(symbol) && + symbol.length >= content.length - 1) + ) { + return ''; + } + + // + // Validate Surround ... + if (!isSurrounded(symbol, content)) { + return content; + } + + // + if (!isValidArg(symbol)) { + return content; + } + + // + let result = content.substring(symbol.length, content.length - symbol.length); + return result; +} + +/** + * clear object sign ... + * + * @param {string} content + * @returns cleared content ... + */ +function clearObjectSurround(content = '') { + // + // Validate Args ... + if ( + !isValidArg(content) || + !isSurroundedObject(content) + ) { + return content; + } + + // + const endIndex = content.length - ( + endsWidth('}', content) ? + 1 : + endsWidth('},', content) || + endsWidth('};', content) || + endsWidth('}\n', content) ? + 2 : + 0 + ); + + // + const result = content.substring(1, endIndex); + return result; +} + +/** + * clear array sign ... + * + * @param {string} content + * @returns cleared content ... + */ +function clearArraySurround(content = '') { + // + // Validate Args ... + if ( + !isValidArg(content) || + !isSurroundedArray(content) + ) { + return content; + } + + // + const endIndex = content.length - ( + endsWidth(']', content) ? + 1 : + endsWidth('],', content) || + endsWidth('];', content) || + endsWidth(']\n', content) ? + 2 : + 0 + ); + + // + const result = content.substring(1, endIndex); + return result; +} + +/** + * slice a content to individual parts ... + * + * @param {number|number[]} indexes which indexes used to slice ... + * @param {strng} content the content which going to sliced ... + * @returns sliced parts of content ... + */ +function sliceContent(indexes, content) { + // + // Validate Args ... + if ( + !isValidArg(indexes) || + !isValidArg(content) + ) { + return []; + } + + // + // Normalize indexes ... + const normalIndexes = toNormalArray(indexes) + .filter(index => index > -1 && index < content.length); + if (!hasChildArray(normalIndexes)) { + return []; + } + + // + let result = ['']; + result.pop(); + + // + let lastIndex = 0; + for (const index of normalIndexes) { + // + const part = content.substring(lastIndex, index); + if (isValidArg(part)) { + result.push(part.trim()); + } + + // + lastIndex = index + 1; + } + + // + // check remained parts ... + if (lastIndex < content.length) { + // + const part = content.substring(lastIndex); + if (isValidArg(part)) { + result.push(part.trim()); + } + } + + // + return result; +} + + + +/** + * check an string is starts and ends with specified symbol ... + * + * @param {string} symbol specified search symbol ... + * @param {string} content specified search content ... + * @param {boolean} ignoreCase specified search case sensitive or not ... + * @returns + */ +function isSurrounded( + symbol = '', + content = '', + ignoreCase = true +) { + // + // Validate Args ... + if (!isValidArg(content)) { + return false; + } + + // + if (!isValidArg(symbol)) { + return true; + } + + // + symbol = symbol.trim(); + + // + let result = false; + result = (!!ignoreCase ? + content + .toLowerCase() + .startsWith(symbol.toLowerCase()) : + content.startsWith(symbol) + ) && + endsWidth(symbol, content, ignoreCase); + + // + return result; +} + +/** + * determines a content is an string surrounded value or not ... + * + * @param {string} content a content which going to check ... + * @returns + */ +function isSurroundedString(content = '') { + // + // Validate Args ... + if (!isValidArg(content)) { + return false; + } + + // + let result = false; + result = ( + content.startsWith('\'') && + ( + endsWidth('\'', content) || + endsWidth('\',', content) || + endsWidth('\';', content) || + endsWidth('\'\n', content) + ) || + content.startsWith('\"') && + ( + endsWidth('\"', content) || + endsWidth('\",', content) || + endsWidth('\";', content) || + endsWidth('\"\n', content) + ) || + content.startsWith('`') && + ( + endsWidth('\`', content) || + endsWidth('\`,', content) || + endsWidth('\`;', content) || + endsWidth('\`\n', content) + ) + ); + return result; +} + +/** + * check a content is an array content or not ... + * + * @param {string} content + * @returns + */ +function isSurroundedArray(content = '') { + // + // Validate Args ... + if (!isValidArg(content)) { + return false; + } + + // + let result = false; + result = content.startsWith('[') && + ( + endsWidth(']', content) || + endsWidth('],', content) || + endsWidth('];', content) || + endsWidth(']\n', content) + ); + return result; +} + +/** + * check a content is an object content or not ... + * + * @param {string} content + * @returns + */ +function isSurroundedObject(content = '') { + // + // Validate Args ... + if (!isValidArg(content)) { + return false; + } + + // + let result = false; + result = content.startsWith('{') && + ( + endsWidth('}', content) || + endsWidth('},', content) || + endsWidth('};', content) || + endsWidth('}\n', content) + ); + return result; +} + +/** + * check an index model is contains inside anothers or not ... + * + * @param {{ start: number, end: number}} source the source index model to check ... + * @param {...{ start: number, end: number}} dest the collection of index models which going to check ... + * @returns + */ +function isIndexInside(source, ...dest) { + // + let result = false; + + // + // Validate Args ... + if (!source || !dest) { + return result; + } + + // + // Check idx is standard ... + if ( + !source || + !source.end || + !source.start || + source.start > source.end + ) { + return false; + } + + // + // Check types of destinations ... + for (let index of dest) { + // + // Check idx is standard ... + if ( + !index || + !index.end || + !index.start || + index.start > index.end + ) { + return false; + } + } + + // + if (dest.includes(source)) { + dest = dest.filter(d => d !== source); + } + + // + const insideContentIndex = dest.find(dIndex => { + // + const result = source.start >= dIndex.start && + source.start <= dIndex.end && + source.end >= dIndex.start && + source.end <= dIndex.end; + return result; + }); + + // + result = insideContentIndex; + return result; +} + +/** + * check a number exists in + * @param {number} idx the number which going to check ... + * @param {{ start: number, end: number}} index the index model + * @returns + */ +function isInsideIndex(idx = -1, index) { + // + let result = false; + + // + // Validate Args ... + if ( + !index || + !index.hasOwnProperty('end') || + !index.hasOwnProperty('start') + ) { + return result; + } + + // + result = idx > index.start && idx < index.end; + return result; +} + +/** + * determines an object is key/value and type ... + * + * @param {any} content the object which we are going to check ... + * @returns + */ +function isKeyValueType(content) { + // + const result = content && + content.hasOwnProperty('key') && + content.hasOwnProperty('type') && + content.hasOwnProperty('value'); + + // + return result; +} + + + +/** + * find all indexes of token(s) in content ... + * + * @param {string|string[]} tokens the tokens which require to search ... + * @param {string} content the content which using to search ... + * @returns {number[]} all occured indexes ... + */ +function findAllIndexes( + tokens, + content +) { + // + // Validate Args ... + if ( + !isValidArg(tokens) || + !isValidArg(content) + ) { + return []; + } + + // + // normalize tokens ... + const normalTokens = toNormalArray(tokens); + if (!hasChildArray(normalTokens)) { + return []; + } + + // + // Parse contents ... + let match; + const result = []; + const regExp = new RegExp( + normalTokens.join('|'), + 'g' + ); + while ((match = regExp.exec(content)) !== null) { + result.push(match.index); + } + if (!hasChildArray(result)) { + return []; + } + + // + return result; +} + +/** + * find nearest symbol in a content from specified index ... + * + * @param {string|string[]} candidates specifies which symbols to find ... + * @param {string} content te content for seasrch ... + * @param {number} startFromIndex the index of start position ... + * @returns + */ +function findNearest( + candidates, + content = '', + startFromIndex = 0 +) { + // + // Validate Args ... + if ( + !isValidArg(content) || + !isValidArg(candidates) || + !isValidArg(content.trim()) + ) { + return ''; + } + + // + // Normalize Content ... + content = content.trim(); + + // + // Normalize Starts From ... + startFromIndex = startFromIndex < 0 || startFromIndex > content.length - 1 ? 0 : startFromIndex; + + // + // Normalize Symbols ... + const normalCandidates = toNormalArray(candidates); + if (!hasChildArray(normalCandidates)) { + return ''; + } + + // + let nearestIndex = findNearestIndex( + normalCandidates, + content, + startFromIndex + ); + if (nearestIndex < 0) { + return ''; + } + + // + let result = content.substring( + nearestIndex, + nearestIndex + Math.max(...normalCandidates.map(nc => nc.length)) + ).trim(); + return result; +} + +/** + * search candidates in content and find nearest one and return it ... + * + * @param {string|string[]} candidates which candidates required to check ... + * @param {string} content the content which required to search candidates ... + * @param {number} startFromIndex the proposed index to start searching content from on ... + * @returns + */ +function findNearestIndex( + candidates = [''], + content = '', + startFromIndex = 0, + ignoreClosedItems = false +) { + // + // Validate Args ... + if ( + !isValidArg(content) || + !isValidArg(candidates) + ) { + return -1; + } + + // + // Mormalize startFromIndex value ... + startFromIndex = startFromIndex < 0 ? + 0 : + startFromIndex > content.length - 1 ? + content.length - 1 : + startFromIndex; + + // + // Normalize candidates ... + let normalCandidates = toNormalArray(candidates); + + // + if (!!ignoreClosedItems) { + normalCandidates = normalCandidates + .map(c => content.indexOf( + c, + startFromIndex + ) + ).map(c => +c) + .filter(c => +c > -1); + } else { + normalCandidates = findAllIndexesOutOfCloseds(normalCandidates, content) + .filter(c => c >= startFromIndex); + } + if (!hasChildArray(normalCandidates)) { + return -1; + } + + // + let result = -1; + result = Math.min(...normalCandidates); + + // + return result; +} + +/** + * find close index of specific sign in destination content ... + * + * @param {string} openSymbol open of area sign ... + * @param {string} closeSymbol close of area sign ... + * @param {string} content the destination content for parsing ... + * @param {number} startsFrom an start index of content for start parsing ... + * @returns + */ +function findCloseIndex( + openSymbol = '', + closeSymbol = '', + content = '', + startsFrom = -1 +) { + // + // Validate Args ... + if ( + startsFrom < 0 || + !isValidArg(content) || + !isValidArg(openSymbol) || + !isValidArg(closeSymbol) || + openSymbol === closeSymbol || + !content.includes(openSymbol) || + !content.includes(closeSymbol) || + startsFrom > content.length - 1 + ) { + return -1; + } + + // + let result = -1; + + // + let index = startsFrom; + const openSignStack = []; + while (index < content.length) { + // + const openCandidate = content.substring(index, index + openSymbol.length); + const closeCandidate = content.substring(index, index + closeSymbol.length); + + // + if (openCandidate === openSymbol) { + openSignStack.push(index); + } else if (closeCandidate === closeSymbol) { + // + if (openSignStack.length > 0) { + openSignStack.pop(); + } + + // + if (openSignStack.length === 0) { + result = index; + break; + } + } + + // + index++; + } + + // + return result; +} + +/** + * find closed contents of specific sign in destination content ... + * + * @param {string} openSymbol open of area sign ... + * @param {string} closeSymbol close of area sign ... + * @param {string} content the destination content for parsing ... + * @param {number} startsFrom an start index of content for start parsing ... + * @returns + */ +function findClosedContent( + openSymbol = '', + closeSymbol = '', + content = '', + startsFrom = 0, +) { + // + let result = [{ + start: -1, + end: -1, + content: '' + }]; + result.pop(); + + // + // Validate Args ... + if ( + !isValidArg(content) || + !isValidArg(openSymbol) || + !isValidArg(closeSymbol) || + !content.includes(openSymbol) || + !content.includes(closeSymbol) || + openSymbol.length >= content.length || + closeSymbol.length >= content.length + ) { + return result; + } + + // + // Normalize Start From ... + startsFrom = startsFrom < 0 || startsFrom >= content.length ? 0 : startsFrom; + + // + let canContinue = true; + while (!!canContinue) { + // + let openSymbolIndex = content.indexOf(openSymbol, startsFrom); + if (openSymbolIndex < 0) { + // + canContinue = false; + continue; + } + + // + let closeSymbolIndex = findCloseIndex( + openSymbol, + closeSymbol, + content, + openSymbolIndex + ); + if (closeSymbolIndex < 0) { + // + canContinue = false; + continue; + } + if (content.charAt(closeSymbolIndex) !== closeSymbol) { + closeSymbolIndex++; + } + + // + // Prevent ${} string interpolations ... + if ( + openSymbol === '{' && + openSymbolIndex - 1 >= 0 + ) { + // + const prevChar = content.charAt(openSymbolIndex - 1); + if (prevChar === '$') { + continue; + } + } + + // + const item = content + .substring(openSymbolIndex, closeSymbolIndex + 1) + .trim(); + startsFrom = closeSymbolIndex + 1; + result.push({ + start: openSymbolIndex, + end: closeSymbolIndex, + content: item + }); + } + + // + if (!hasChildArray(result)) { + return result; + } + + // + return result; +} + +/** + * extract a collection of closed contents exists in a content ... + * + * @param symbols a collection of open and close contents ... + * @param {string} content a content for searching inside it ... + * @returns a collection of closed content ... + */ +function findClosedContents( + symbols = [ + { + openSymbol: '', + closeSymbol: '' + } + ], + content = '' +) { + // + let result = [{ + start: -1, + end: -1, + content: '' + }]; + result.pop(); + + // + if ( + !isValidArg(content) || + !hasChildArray(symbols) + ) { + return []; + } + + // + symbols.forEach(symbol => { + // + const closedContent = findClosedContent( + symbol.openSymbol, + symbol.closeSymbol, + content + ); + + // + if (hasChildArray(closedContent)) { + result.push( + ...closedContent + ); + } + }); + + // + return result; +} + +/** + * find all string content closed items ... + * + * @param {string} content a content which going to search ... + * @returns a collection of index descriptors ... + */ +function findClosedStrings(content = '') { + // + // Validate Args ... + if (!isValidArg(content)) { + return []; + } + + // + // there are 3 types of strings ... + // ' " and ` + + // + const token1 = '\''; + const token1Stack = [0]; + token1Stack.pop(); + + // + const token2 = '"'; + const token2Stack = [0]; + token2Stack.pop(); + + // + const token3 = '`'; + const token3Stack = [0]; + token3Stack.pop(); + + // + const result = [ + { + start: -1, + end: -1, + content: '' + } + ]; + result.pop(); + + // + for (let i = 0; i < content.length; i++) { + // + const currentChart = content.charAt(i); + + // + //#region Token 1 ... + if (currentChart === token1) { + // + if (!hasChildArray(token1Stack)) { + token1Stack.push(i); + } else { + // + const start = token1Stack.pop(); + const end = i + 1; + const pContent = content.substring(start, end); + result.push({ + start, + end, + content: pContent + }); + } + } + //#endregion + + // + //#region Token 2 ... + if (currentChart === token2) { + // + if (!hasChildArray(token2Stack)) { + token2Stack.push(i); + } else { + // + const start = token2Stack.pop(); + const end = i + 1; + const pContent = content.substring(start, end); + result.push({ + start, + end, + content: pContent + }); + } + } + //#endregion + + // + //#region Token 3 ... + if (currentChart === token3) { + // + if (!hasChildArray(token3Stack)) { + token3Stack.push(i); + } else { + // + const start = token3Stack.pop(); + const end = i + 1; + const pContent = content.substring(start, end); + result.push({ + start, + end, + content: pContent + }); + } + } + //#endregion + } + + // + return result; +} + +/** + * find container indexes from within indexes ... + * + * @param {...{start: number, end: number}} index the collection of indexes to find beiggers inside ... + * @returns + */ +function findContainerIndexes(...index) { + // + let result = [ + { + start: -1, + end: -1, + content: '' + } + ]; + result.pop(); + + // + let concatedIndexes = []; + for (let idx of index) { + // + // Index Childs ... + for (let iix of idx) { + // + // Check idx is standard ... + if ( + !iix || + !iix.end || + !iix.start || + iix.start > iix.end + ) { + continue; + } + + // + // Check index inside another index ... + concatedIndexes.push(iix); + } + } + + // + if (!hasChildArray(concatedIndexes)) { + return result; + } + + // + for (let ccIdx of concatedIndexes) { + // + const isInside = isIndexInside(ccIdx, ...concatedIndexes); + if (isInside) { + continue; + } + + // + if (hasChildArray(result)) { + // + const isInsideResult = isIndexInside(ccIdx, ...result); + if (isInsideResult) { + continue; + } + } + + // + result.push(ccIdx); + } + + // + return result; +} + +/** + * find all tokens indexes inside a content which they are not inside closed items ... + * + * @param {string|string[]} tokens the tokens which require to search ... + * @param {string} content the content which using to search ... + * @returns + */ +function findAllIndexesOutOfCloseds1( + tokens, + content, +) { + // + // Validate Args ... + if (!isValidArg(content)) { + return []; + } + + // + // Extract token Indexes ... + const tokensIndexes = findAllIndexes(tokens, content); + if (!hasChildArray(tokensIndexes)) { + return []; + } + + // + // Extract Closed Objects Indexes ... + const closedArrays = findClosedContent('[', ']', content); + const closedObjects = findClosedContent('{', '}', content); + const closedStrings = findClosedStrings(content); + if ( + !hasChildArray(closedObjects) && + !hasChildArray(closedArrays) && + !hasChildArray(closedStrings) + ) { + return tokensIndexes; + } + + // + // find bigger sloded ... + let containerClosedItems = findContainerIndexes( + closedArrays, + closedObjects, + closedStrings + ).filter(i => !isSurroundedString(i.content)); + + // + let result = [-1]; + result.pop(); + + // + for (let tIdx of tokensIndexes) { + // + let canAdd = true; + for (let ccIndex of containerClosedItems) { + // + canAdd = isInsideIndex(tIdx, ccIndex); + if (canAdd) { + break; + } + } + + // + if (!canAdd) { + result.push(tIdx); + } + } + + // + return result; +} + +/** + * find all tokens indexes inside a content which they are not inside closed items ... + * + * @param {string|string[]} tokens the tokens which require to search ... + * @param {string} content the content which using to search ... + * @returns + */ +function findAllIndexesOutOfCloseds( + tokens, + content, +) { + // + // Define Result ... + let result = [-1]; + result.pop(); + + // + // Validate Args ... + if (!isValidArg(content)) { + return []; + } + + // + // Normalize Tokens ... + const normalizeTokens = toNormalArray(tokens); + if (!hasChildArray(normalizeTokens)) { + return result; + } + + // + // Extract Closed Objects Indexes ... + let openSymbols = [ + '{', + '[', + '\'', + '"', + '`' + ]; + let closeSymbols = [ + '}', + ']', + '\'', + '"', + '`' + ]; + let openStack = []; + let lastOpenSymbol = ''; + let lastClosedIndex = -1; + for (let i = 0; i < content.length; i++) { + // + const prevChar = content.charAt(i - 1) || ''; + const char = content.charAt(i); + const nextChar = content.charAt(i + 1) || ''; + + // + const isToken = normalizeTokens.includes(char); + const isOpenSymbol = openSymbols.includes(char); + const isCloseSymbol = closeSymbols.includes(char); + + // + if (isOpenSymbol && lastOpenSymbol !== char) { + openStack.push(i); + lastOpenSymbol = char === '\'' || char === '"' || char === '`' ? char : lastOpenSymbol; + } else if (isCloseSymbol) { + // + lastOpenSymbol = char === '\'' || char === '"' || char === '`' ? '' : lastOpenSymbol; + let lastPop = openStack.pop(); + if (openStack.length === 0) { + lastClosedIndex = lastPop; + } + } else if (isToken) { + if ( + i > lastClosedIndex && + openStack.length === 0 + ) { + result.push(i); + } + } + } + + // + return result; +} +//#endregion + +// +//#region Validator Actions ... +/** + * check specified value is Valid URL Address or not ... + * + * @param {string} value specified string which required to check + * @returns {boolean} + */ +function isValidURL(value = "") { + // + if (!isValidArg(value)) { + return false; + } + + const pattern = new RegExp( + '^([a-zA-Z]+:\\/\\/)?' + // protocol + '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|' + // domain name + '((\\d{1,3}\\.){3}\\d{1,3}))' + // OR IP (v4) address + '(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*' + // port and path + '(\\?[;&a-z\\d%_.~+=-]*)?' + // query string + '(\\#[-a-z\\d_]*)?$', // fragment locator + 'i' + ); + + // + const result = pattern.test(value); + return result; +} + +/** + * check specified value is Valid URL Address or not ... + * + * @param {string} value specified string which required to check + */ +function isValidEmail(value = "") { + // + if (!isValidArg(value)) { + return false; + } + + // + const pattern = /[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/gim; + + // + const result = pattern.test(value); + return result; +} +//#endregion + +// +//#region Normallizers ... +/** + * normallize an string ... + * + * @param {string} value specified value ... + * @returns {string} + */ +function toNormalString(value = "") { + // + if (!XTypeTools.isString(value)) { + value = ""; + } + + // + const result = value + .trim() + .toLowerCase(); + + // + return result; +} +//#endregion + +// +//#region Beautifiers ... +/** + * converts an object to string based on json and beautify result ... + * + * @param {any} object + * @returns {string} + */ +function beautifyJSON(object = undefined) { + // + // TODO: Complete this ... + let result = ""; + + // + // validate object ... + if (object === undefined) { + return result; + } + + // + // Convert result ... + result = JSON.stringify( + object, + null, + 4 + ); + + // + return result; +} +//#endregion + +// +//#region Module Exports ... +module.exports = { + // + endsWidth, + surroundBy, + isValidArg, + isValidArgs, + toNormalArray, + hasChildArray, + toStringExpression, + + // + sliceContent, + clearContent, + clearSurround, + clearArraySurround, + clearObjectSurround, + + // + isSurrounded, + isIndexInside, + isInsideIndex, + isKeyValueType, + isSurroundedArray, + isSurroundedString, + isSurroundedObject, + + // + findNearest, + findAllIndexes, + findCloseIndex, + findNearestIndex, + findClosedContent, + findClosedStrings, + findClosedContents, + findAllIndexesOutOfCloseds, + + // + // Validator Actions ... + isValidURL, + isValidEmail, + + // + // Normallizers ... + toNormalString, + + // + beautifyJSON, +} +//#endregion \ No newline at end of file diff --git a/MQLTestWorkspace/X121/14030217/Documents/Temp/multi.asset.configs.yml b/MQLTestWorkspace/X121/14030217/Documents/Temp/multi.asset.configs.yml new file mode 100644 index 0000000..79e0ba7 --- /dev/null +++ b/MQLTestWorkspace/X121/14030217/Documents/Temp/multi.asset.configs.yml @@ -0,0 +1 @@ +EURUSDb,GBPUSDb,USDJPYb,USDCHFb,XAUUSDb|M5,M15|0.01|X786|true \ No newline at end of file diff --git a/MQLTestWorkspace/X121/14030217/Experts/x-saherelm.xea.ex5 b/MQLTestWorkspace/X121/14030217/Experts/x-saherelm.xea.ex5 new file mode 100644 index 0000000..522991e Binary files /dev/null and b/MQLTestWorkspace/X121/14030217/Experts/x-saherelm.xea.ex5 differ diff --git a/MQLTestWorkspace/X121/14030217/Experts/x-saherelm.xea.mq5 b/MQLTestWorkspace/X121/14030217/Experts/x-saherelm.xea.mq5 new file mode 100644 index 0000000..68fe87e --- /dev/null +++ b/MQLTestWorkspace/X121/14030217/Experts/x-saherelm.xea.mq5 @@ -0,0 +1,366 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Expert Advisor +// ---------------------------------------- +// Name: X121EA +// Description: this is an expert controller +// advisors which provides a mechanism for use them ... +// +// NOTE: about provider instancing in multi asset state: +// you can provide configurations using this: +// +// EURUSDb,GBPUSDb,USDJPYb,USDCHFb,XAUUSDb|M5,M15|0.01|X786|true +// EURUSDb,GBPUSDb,USDJPYb,USDCHFb,XAUUSDb|M5,M15|0.01|X786|true +// +// or make the instance use this: +// +// XPV(EURUSDb|M15|0.01|X92|true)XPV(GBPUSDb|M5|0.02|X786|false) +// +// if leave Configuration string blank this will used default config +// and One asset mode enabled ... +// +// 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 X121EA" +#property strict + +// +// START Definitions ... +// + +// +#define ShortName "X121EA" + +// +// END Definitions ... +// + +// +// START Inputs ... +// + +// +// EA ... +input group "Common"; +input bool xEAEnable = true; // Enable EA +input int xEASlippage = 10; // Slippgae +input ulong xEAMagicNumber = 1604056; // Magic Number + +// +// Providers ... +input group "Providers"; +input string xEAProvidersConfiguration = ""; // Providers Configuration +input string xEADefaultSignalProviders = "X786"; // Default Allowed Signal Providers + +// +// Signals ... +input group "Signals"; +input bool xEAEnableLongs = true; // Enable Long Trades +input bool xEAEnableShorts = true; // Enable Short Trades + +// +// Risk Management ... +input group "Risk Management"; +input int xEAMaxOpenPositions = 15; // Max Allowed Open Trades +input double xEAMinRiskAmountPerTrade = 0.001; // Min Risk Amount Per Trade +input double xEAMaxAllowedDrawDownFactor = 0.01; // Max Allowed Drawdown Factor +input double xEAMinProfitPerTrade = 0.1; // Min Acceptable Profit Per Trade +input double xEAMinProfitPerVolumeFactor = 0.01; // Min Acceptable Profit Volume Factor Per Trade +input bool xEAUseRiskAmountAsStaticVolume = true; // Use Provided Risk Amount as Static Volume + +// +// Alerts ... +input group "Alerts"; +input bool xEAEnableAlerts = true; // Enable Events Alert +input bool xEAEnableHourlyAlerts = false; // Send Alert on each new Hour +input bool xEAEnableDailyAlerts = false; // Send Alert on each new Day +input bool xEAEnableWeeklyAlerts = false; // Send Alert on each new Week +input bool xEAEnableMonthlyAlerts = false; // Send Alert on each new Month + +// +// END Inputs ... +// + +// +// START Including Providers ... +// + +// +// Logger Library ... +#include "../Libraries/x-saherelm.log.lib.mq5" +#include "../Classes/x-saherelm.x121.xea.class.mq5" +#include "../Libraries/x-saherelm.seriallizer.lib.mq5" + +// +// END Including Providers ... +// + +// +// START Global Definitions: Variables, Properties and etc ... +// + +// +XSCX121EA *mX121EA; + +// +// END Global Definitions: Variables, Properties and etc ... +// + +// +// START Event Handlers ... +// + +// +// Initialization ... +int OnInit() +{ + // + logTag = ShortName; + drawPrefix = logTag; + alertPrefix = logTag; + + // + // Validate Inputs ... + if (!ValidateInputs()) + { + return INIT_PARAMETERS_INCORRECT; + } + + // + bool isInit = InitEAInstance(); + if (!isInit) + { + 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 + + // + // De Initialize XEA Providers ... + delete mX121EA; +} + +// +// On Tick Handler ... +void OnTick() +{ + // + // Prevent Going Forward if user Disable it ... + if (xEAEnable) + { + mX121EA.OnTick(); + } +} + +// +// Handle Trade Events ... +void OnTrade() +{ + mX121EA.OnTrade(); +} + +// +// Handle Signal Event ... +void OnSignalConditionsRecieved(X121MarketConditions &info) +{ +} + +// +// Handle StopLoss Event ... +void OnStopLossTriggered(const XDeal &deal) +{ +} + +// +// Handle TakeProfit Event ... +void OnTakeProfitTriggered(const XDeal &deal) +{ +} + +// +// Handle Deals Changed Event ... +void OnDealsChangedHandler(int count) +{ +} + +// +// Handle Order Changed Event ... +void OnOrdersChangedHandler(int count) +{ +} + +// +// Handle Position Changed Event ... +void OnPositionsChangedHandler(int count) +{ +} + +// +// Handle Trade State Changed ... +void OnTradeStateChangedHandler(const XOnTradeHandlerState &state) +{ +} + +// +// END Event Handlers ... +// + +// +// START Functions ... +// + +// +// Validate Input Args for Initialization ... +bool ValidateInputs() +{ + // + bool result = true; + + // + // Validate Args ... + result = + // + xEASlippage > 0 && + xEAMagicNumber > 0 && + xEAMinRiskAmountPerTrade > 0 && + StringLen(xEADefaultSignalProviders) > 0 + // + // TODO: add new validations here ... + // + ; + + // + // Validate Providers ... + if (result) + { + // + string providers[]; + SplitContent( + providers, + xEADefaultSignalProviders); + + // + int providersCount = ArraySize(providers); + if (providersCount <= 0) + { + // + result = false; + return result; + } + + // + string allProviders[]; + GetAllProviders(allProviders); + + // + bool hasError = false; + for (int i = 0; i < providersCount; i++) + { + // + string iProvider = providers[i]; + if (!Contains(iProvider, allProviders)) + { + // + hasError = true; + break; + } + } + + // + if (hasError) + { + // + result = false; + return result; + } + } + + // + // Logging State ... + string message = "Validation of (" + logTag + ") Inputs " + (result ? "Succeeded" : "Failed") + " ..."; + LogMessage(message); + + // + return result; +} + +// +// Initialize X121EA Class Instances ... +bool InitEAInstance() +{ + // + bool result = false; + + // + X121SignalProvider providers[]; + + // + // Try to Extract Configs ... + int configsCount = ExtractProviderConfigurations( + providers, + xEAProvidersConfiguration, + xEADefaultSignalProviders, + xEAMinRiskAmountPerTrade, + xEAUseRiskAmountAsStaticVolume); + + // + mX121EA = new XSCX121EA( + _Symbol, + _Period, + xEAMagicNumber, + xEASlippage, + xEAMinProfitPerTrade, + xEAMinProfitPerVolumeFactor, + OnStopLossTriggered, + OnTakeProfitTriggered, + OnDealsChangedHandler, + OnOrdersChangedHandler, + OnPositionsChangedHandler, + OnTradeStateChangedHandler, + OnSignalConditionsRecieved); + + // + mX121EA.EnableLongs(xEAEnableLongs); + mX121EA.EnableShorts(xEAEnableShorts); + mX121EA.MaxAllowedPositions(xEAMaxOpenPositions); + mX121EA.MaxAllowedDrawDownFactor(xEAMaxAllowedDrawDownFactor); + + // + // Attach Providers to EA Instance ... + int providersCount = ArraySize(providers); + int addedProviders = mX121EA.AddProviders(providers); + result = addedProviders == providersCount; + + // + return result; +} +// +// END Functions ... +// diff --git a/MQLTestWorkspace/X121/14030217/Helpers/x-saherelm.x121.xman.helper.class.ex5 b/MQLTestWorkspace/X121/14030217/Helpers/x-saherelm.x121.xman.helper.class.ex5 new file mode 100644 index 0000000..c92beba Binary files /dev/null and b/MQLTestWorkspace/X121/14030217/Helpers/x-saherelm.x121.xman.helper.class.ex5 differ diff --git a/MQLTestWorkspace/X121/14030217/Helpers/x-saherelm.x121.xman.helper.class.mq5 b/MQLTestWorkspace/X121/14030217/Helpers/x-saherelm.x121.xman.helper.class.mq5 new file mode 100644 index 0000000..3c1dcba --- /dev/null +++ b/MQLTestWorkspace/X121/14030217/Helpers/x-saherelm.x121.xman.helper.class.mq5 @@ -0,0 +1,1814 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Helper Class Library +// ---------------------------------------------- +// Name: XSCXMANHelper +// 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 + +// +// START Definitions ... +// + +// +#include "../Libraries/x-saherelm.xman.parser.lib.mq5" + +// +// All Extractable Buffers ... +enum ENUM_XMAN_BUFFERS +{ + // + // Peaks and Vales ... + XMAN_PEAKS_LINE = 0, // Peaks + XMAN_VALES_LINE = 1, // Vales + XMAN_PEAKS_STATE_LINE = 74, // New Peak + XMAN_VALES_STATE_LINE = 75, // New Vales + // + // Fibonacci Retracement ... + XMAN_FIB_L1_LINE = 6, // Fibo Level 1 + XMAN_FIB_L2_LINE = 8, // Fibo Level 2 + XMAN_FIB_L3_LINE = 10, // Fibo Level 3 + XMAN_FIB_L4_LINE = 12, // Fibo Level 3 + XMAN_FIB_L5_LINE = 14, // Fibo Level 3 + // + // Period Cycles ... + // + // Short Cycle ... + XMAN_SC_HH_LINE = 16, // High + XMAN_SC_LL_LINE = 18, // Low + XMAN_SC_HH_STATE_LINE = 76, // High State + XMAN_SC_LL_STATE_LINE = 77, // Low State + // + // Medium ... + XMAN_MC_HH_LINE = 20, // High + XMAN_MC_LL_LINE = 22, // Low + XMAN_MC_HH_STATE_LINE = 78, // High State + XMAN_MC_LL_STATE_LINE = 79, // Low State + // + // Long ... + XMAN_LC_HH_LINE = 24, // High + XMAN_LC_LL_LINE = 26, // Low + XMAN_LC_HH_STATE_LINE = 80, // High State + XMAN_LC_LL_STATE_LINE = 81, // Low State + // + // Hind ... + XMAN_HC_HH_LINE = 28, // High + XMAN_HC_LL_LINE = 30, // Low + XMAN_HC_HH_STATE_LINE = 82, // High State + XMAN_HC_LL_STATE_LINE = 83, // Low State + // + // XSTR ... + XMAN_TREND_LINE = 34, // Trend Value + XMAN_TREND_STATE_LINE = 84, // Trend Direction + // + // XMRB ... + // + // RIBBON 1 _ HIGH ... + XMAN_RB1_LINE = 36, // Value + XMAN_RB1_STATE_LINE = 85, // State + // + // RIBBON 2 _ OPEN ... + XMAN_RB2_LINE = 38, // Value + XMAN_RB2_STATE_LINE = 86, // State + // + // RIBBON 3 _ CLOSE ... + XMAN_RB3_LINE = 40, // Value + XMAN_RB3_STATE_LINE = 87, // State + // + // RIBBON 4 _ MEDIAN ... + XMAN_RB4_LINE = 42, // Value + XMAN_RB4_STATE_LINE = 88, // State + // + // RIBBON 5 _ TYPICAL ... + XMAN_RB5_LINE = 44, // Value + XMAN_RB5_STATE_LINE = 89, // State + // + // RIBBON 6 _ LOW ... + XMAN_RB6_LINE = 46, // Value + XMAN_RB6_STATE_LINE = 90, // State + // + // XSSLC ... + XMAN_SSLC_UP_LINE = 48, // Up + XMAN_SSLC_DOWN_LINE = 50, // Down + // + // XHULL ... + XMAN_HULL_UP_LINE = 52, // Up + XMAN_HULL_DOWN_LINE = 54, // Down + XMAN_HULL_UP_STATE_LINE = 91, // Up State + XMAN_HULL_DOWN_STATE_LINE = 92, // Down State + // + // XHK ... + XMAN_HK_OPEN_LINE = 56, // Open + XMAN_HK_HIGH_LINE = 57, // High + XMAN_HK_LOW_LINE = 58, // Low + XMAN_HK_CLOSE_LINE = 59, // Close + XMAN_HK_STATE_LINE = 93, // State + // + // XSMHK ... + XMAN_SMHK_OPEN_LINE = 61, // Open + XMAN_SMHK_HIGH_LINE = 62, // High + XMAN_SMHK_LOW_LINE = 63, // Low + XMAN_SMHK_CLOSE_LINE = 64, // Close +}; + +// +// Define States On XMAN ... +enum ENUM_XMAN_STATES +{ + XMAN_STATE_BULLISH = 2, + XMAN_STATE_STRONG_BULLISH = 8, + XMAN_STATE_BEARISH = 3, + XMAN_STATE_STRONG_BEARISH = 9, + XMAN_STATE_NEUTURAL = 1, + XMAN_STATE_STRONG_NEUTURAL = 7, +}; + +// +// Model all required info as a Model for Instancing Helper Class ... +struct XMANInputs +{ + // + // Candle Timer ... + color candleTimerColor; // Text Color + ENUM_BASE_CORNER candleTimerCorner; // Text Position + + // + // Chart Style ... + 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 + ENUM_CHART_MODE chartMode; // Chart Mode + + // + // Market Cycles ... + + // + // Level 1 ... + ENUM_X_PERIOD_METHOD l1Method; // How to Find Period + ENUM_TIMEFRAMES l1Period; // Time Period + + // + // Level 2 ... + ENUM_X_PERIOD_METHOD l2Method; // How to Find Period + ENUM_TIMEFRAMES l2Period; // Time Period + + // + // Level 3 ... + ENUM_X_PERIOD_METHOD l3Method; // How to Find Period + ENUM_TIMEFRAMES l3Period; // Time Period + + // + // Level 4 ... + ENUM_X_PERIOD_METHOD l4Method; // How to Find Period + ENUM_TIMEFRAMES l4Period; // 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 + + // + // Trend Detection + double trendMultiplier; // Multiplier + ENUM_APPLIED_PRICE trendPriceAppliedTo; // Applied To + + // + // Ribbon Detection ... + ENUM_X_MA_METHOD ribbonMode; // How to Calculate + + // + // Hull Trend Detection ... + double hullDivisor; // Divisor (Speed) + ENUM_APPLIED_PRICE hullUpAppliedTo; // Up Zone Applied to + ENUM_APPLIED_PRICE hullDownAppliedTo; // Down Zone Applied to + + // + // SSL Channel Detection ... + ENUM_X_MA_METHOD sslcMode; // How to Calculate + ENUM_APPLIED_PRICE sslcUpAppliedTo; // Up Applied To + ENUM_APPLIED_PRICE sslcDownAppliedTo; // Down Applied To + + // + // Presentation ... + bool showCandleTimer; // Show Candle Time + bool showCandles; // Show Candles + bool showHKCandles; // Draw Hiken Ashi Candle + bool showSMHKCandles; // Draw Smoothed Hiken Ashi Candle + bool showPeaksAndVales; // Show Peaks and Vales + bool showTrends; // Show Trends + bool fillTrends; // Fill Trends + bool showLevels; // Show Levels + bool showConsolidations; // Show Consolidations + bool showRibbons; // Show Ribbons + bool showHull; // Show Hull + bool showSSLChannel; // Show SSL Channel + 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 +}; + +// +// Model all Extractable Info as a Model for Market Analyzing ... +struct XMANInfo +{ + // + // COMMONS ... + + // + // Symbol ... + string symbol; + + // + // Period ... + ENUM_TIMEFRAMES period; + + // + // Bar Time ... + datetime barTime; + + // + // Bar Index ... + int barIndex; + + // + // SPECIALS ... + + // + // Buffers ... + + // + // Peaks and Vales ... + double peaks[]; + double peaksStates[]; + double vales[]; + double valesStates[]; + + // + // Fibonacci ... + double fibLevel1s[]; + double fibLevel2s[]; + double fibLevel3s[]; + double fibLevel4s[]; + double fibLevel5s[]; + + // + // Cycles ... + + // + // Short ... + double sHHs[]; + double sHHStates[]; + double sLLs[]; + double sLLStates[]; + + // + // Medium ... + double mHHs[]; + double mHHStates[]; + double mLLs[]; + double mLLStates[]; + + // + // Long ... + double lHHs[]; + double lHHStates[]; + double lLLs[]; + double lLLStates[]; + + // + // Hind ... + double hHHs[]; + double hHHStates[]; + double hLLs[]; + double hLLStates[]; + + // + // Trends ... + double trends[]; + double trendStates[]; + + // + // Ribbons ... + + // + // 1 _ High ... + double ribbon1s[]; + double ribbon1States[]; + + // + // 2 _ Open ... + double ribbon2s[]; + double ribbon2States[]; + + // + // 3 _ Close ... + double ribbon3s[]; + double ribbon3States[]; + + // + // 4 _ Median ... + double ribbon4s[]; + double ribbon4States[]; + + // + // 5 _ Typical ... + double ribbon5s[]; + double ribbon5States[]; + + // + // 6 _ Low ... + double ribbon6s[]; + double ribbon6States[]; + + // + // SSL Channel ... + double sslcUps[]; + double sslcDowns[]; + + // + // Hull Trend ... + double hullUps[]; + double hullUpStates[]; + double hullDowns[]; + double hullDownStates[]; + + // + // Hiken Ashi ... + double hkOpens[]; + double hkHighs[]; + double hkLows[]; + double hkCloses[]; + double hkStates[]; + + // + // Smoothed Hiken Ashi ... + double smhkOpens[]; + double smhkHighs[]; + double smhkLows[]; + double smhkCloses[]; +}; + +// +// END Definitions ... +// + +// +// START Import and Inclused requirements ... +// + +// +// Includes ... +#include "../Libraries/x-saherelm.common.lib.mq5" +#include "../Classes/x-saherelm.xhelper.class.mq5" + +// +// END Import and Inclused requirements ... +// + +// +// START Overrides ... +// + +// +// END Overrides ... +// + +// +class XSCXMANHelper : public XSCBaseHelper +{ + // + // Public ... +public: + // + // Props ... + + // + // Peaks and Vales ... + double peaksBuffer[]; + double peaksStateBuffer[]; + double valesBuffer[]; + double valesStateBuffer[]; + + // + // Fibonacci ... + double fibLevel1Buffer[]; + double fibLevel2Buffer[]; + double fibLevel3Buffer[]; + double fibLevel4Buffer[]; + double fibLevel5Buffer[]; + + // + // Cycles ... + + // + // Short ... + double sHHBuffer[]; + double sHHStateBuffer[]; + double sLLBuffer[]; + double sLLStateBuffer[]; + + // + // Medium ... + double mHHBuffer[]; + double mHHStateBuffer[]; + double mLLBuffer[]; + double mLLStateBuffer[]; + + // + // Long ... + double lHHBuffer[]; + double lHHStateBuffer[]; + double lLLBuffer[]; + double lLLStateBuffer[]; + + // + // Hind ... + double hHHBuffer[]; + double hHHStateBuffer[]; + double hLLBuffer[]; + double hLLStateBuffer[]; + + // + // Trends ... + double trendBuffer[]; + double trendStateBuffer[]; + + // + // Ribbons ... + + // + // 1 _ High ... + double ribbon1Buffer[]; + double ribbon1StateBuffer[]; + + // + // 2 _ Open ... + double ribbon2Buffer[]; + double ribbon2StateBuffer[]; + + // + // 3 _ Close ... + double ribbon3Buffer[]; + double ribbon3StateBuffer[]; + + // + // 4 _ Median ... + double ribbon4Buffer[]; + double ribbon4StateBuffer[]; + + // + // 5 _ Typical ... + double ribbon5Buffer[]; + double ribbon5StateBuffer[]; + + // + // 6 _ Low ... + double ribbon6Buffer[]; + double ribbon6StateBuffer[]; + + // + // SSL Channel ... + double sslUpBuffer[]; + double sslDownBuffer[]; + + // + // Hull Trend ... + double hullUpBuffer[]; + double hullUpStateBuffer[]; + double hullDownBuffer[]; + double hullDownStateBuffer[]; + + // + // Hiken Ashi ... + double hkOpenBuffer[]; + double hkHighBuffer[]; + double hkLowBuffer[]; + double hkCloseBuffer[]; + double hkStateBuffer[]; + + // + // Smoothed Hiken Ashi ... + double smhkOpenBuffer[]; + double smhkHighBuffer[]; + double smhkLowBuffer[]; + double smhkCloseBuffer[]; + + // + // Constructor ... + void XSCXMANHelper( + string symbol, // Trading Symbol + ENUM_TIMEFRAMES period // Trading Time Frame + ) : XSCBaseHelper(symbol, period) + { + PrepareTag(); + } + + // + // Deconstructor ... + void ~XSCXMANHelper() + { + } + + // + // START Properties ... + // + + // + // END Properties ... + // + + // + // START Provided Functions ... + // + + // + // Prepare Tag ... + virtual void PrepareTag() + { + mTag = "XMAN" + GetTagPrefix(); + } + + // + virtual int GetMaxLength() + { + // + int result = 1; + + // + result = 1; + + // + return result; + } + + // + // Initial Indicator Handler ... + bool Init() + { + // + bool result = false; + + // + // Validate Args ... + result = + // + // L1 ... + // Short Cycle ... + ( + // + mL1Method == X_PERIOD_AUTO + ? mL1Period == NULL + : mL1Period != NULL && mL1Method != X_PERIOD_NOTHING + // + ) + // + && + // + // L2 ... + // Medium Cycle ... + ( + // + mL2Method == X_PERIOD_AUTO + ? mL2Period == NULL + : mL2Period != NULL && mL2Method != X_PERIOD_NOTHING + // + ) + // + && + // + // L3 ... + // Long Cycle ... + ( + // + mL3Method == X_PERIOD_AUTO + ? mL3Period == NULL + : mL3Period != NULL && mL3Method != X_PERIOD_NOTHING + // + ) + // + && + // + // L4 ... + // Hind Cycle ... + ( + // + mL4Method == X_PERIOD_AUTO + ? mL4Period == NULL + : mL4Period != NULL && mL4Method != X_PERIOD_NOTHING + // + ) + // + && + // + // Validate Ribbon ... + ( + // + mRibbonMode != X_MA_NOTHING + // + ) + // + ; + if (!result) + { + return false; + } + + // + // Now we Have to Generate Proper Configs of Inputs ... + // to bypass into iCustom ... + + // + // Candle Timer ... + string ctConfig = GenerateCTimerConfig( + mCandleTimerColor, + mCandleTimerCorner); + + // + // Chart Style ... + string chStyleConfig = GenerateChartStyleConfig( + mUpColor, + mDownColor, + mLineColor, + mBearishColor, + mBullishColor, + mVolumesColor, + mChartMode); + + // + // Market Cycles ... + + // + // SHORT ... + string scConfig = GenerateSCConfig( + mL1Method, + mL1Period); + + // + // MEDIUM ... + string mcConfig = GenerateMCConfig( + mL2Method, + mL2Period); + + // + // LONG ... + string lcConfig = GenerateLCConfig( + mL3Method, + mL3Period); + + // + // HIND ... + string hcConfig = GenerateHCConfig( + mL4Method, + mL4Period); + + // + // Fibonacci ... + string fiboConfig = GenerateFibonacciConfig( + mFiboLevel1, + mFiboLevel2, + mFiboLevel3, + mFiboLevel4, + mFiboLevel5); + + // + // Boundary Detection ... + string bdConfig = GenerateBDConfig( + mHHMode, + mLLMode); + + // + // Trend Detection ... + string tdConfig = GenerateTDConfig( + mTrendMultiplier, + mTrendPriceAppliedTo); + + // + // Ribbon ... + string rbConfig = GenerateRBConfig( + mRibbonMode); + + // + // Hull Trend ... + string hullConfig = GenerateHullConfig( + mHullDivisor, + mHullUpAppliedTo, + mHullDownAppliedTo); + + // + // SSL Channel ... + string sslcConfig = GenerateSSLCConfig( + mSslcMode, + mSslcUpAppliedTo, + mSslcDownAppliedTo); + + // + // Presentations ... + + // + // STYLES ... + string stylesPRSConfig = GenerateStylePresentationConfig( + mShowCandleTimer, + mShowCandles, + mShowHKCandles, + mShowSMHKCandles); + + // + // PEAKSANDVALES ... + string pvPRSConfig = GeneratePVPresentationConfig( + mShowPeaksAndVales, + mShowLevels, + mShowConsolidations); + + // + // TREND ... + string trendPRSConfig = GenerateTrendPresentationConfig( + mShowTrends, + mFillTrends, + mShowRibbons, + mShowHull, + mShowSSLChannel); + + // + // FIBO ... + string fiboPRSConfig = GenerateFiboPresentationConfig( + mShowFibo1Levels, + mShowFibo2Levels, + mShowFibo3Levels, + mShowFibo4Levels, + mShowFibo5Levels); + + // + // Initialize Handler ... + mHandler = iCustom( + // + mSymbol, + mPeriod, + "x-saherelm.x121.xman", + // + // Inputs ... + // + // Candle Timer + "", + ctConfig, + // + // Chart Style + "", + chStyleConfig, + // + // Makret Cycles + "", + // + // Short + "", + scConfig, + // + // Medium + "", + mcConfig, + // + // Long + "", + lcConfig, + // + // Hind + "", + hcConfig, + // + // Fibonacci + "", + fiboConfig, + // + // Boundary Detection Modes + "", + bdConfig, + // + // Trend Detection + "", + tdConfig, + // + // Ribbon Detection + "", + rbConfig, + // + // Hull Trend Detection + "", + hullConfig, + // + // SSL Channel + "", + sslcConfig, + // + // Presentations + "", + // + // STYLES + stylesPRSConfig, + // + // PEAKSANDVALES + pvPRSConfig, + // + // TREND + trendPRSConfig, + // + // FIBO + fiboPRSConfig + // + ); + result = mHandler != INVALID_HANDLE; + + // + return result; + } + + // + // Retrieve Current Config ... + XMANInputs GetConfig() + { + // + XMANInputs result; + + // + result.candleTimerColor = mCandleTimerColor; + result.candleTimerCorner = mCandleTimerCorner; + result.upColor = mUpColor; + result.downColor = mDownColor; + result.lineColor = mLineColor; + result.bearishColor = mBearishColor; + result.bullishColor = mBullishColor; + result.volumesColor = mVolumesColor; + result.chartMode = mChartMode; + result.l1Method = mL1Method; + result.l1Period = mL1Period; + result.l2Method = mL2Method; + result.l2Period = mL2Period; + result.l3Method = mL3Method; + result.l3Period = mL3Period; + result.l4Method = mL4Method; + result.l4Period = mL4Period; + result.fiboLevel1 = mFiboLevel1; + result.fiboLevel2 = mFiboLevel2; + result.fiboLevel3 = mFiboLevel3; + result.fiboLevel4 = mFiboLevel4; + result.fiboLevel5 = mFiboLevel5; + result.hhMode = mHHMode; + result.llMode = mLLMode; + result.trendMultiplier = mTrendMultiplier; + result.trendPriceAppliedTo = mTrendPriceAppliedTo; + result.ribbonMode = mRibbonMode; + result.hullDivisor = mHullDivisor; + result.hullUpAppliedTo = mHullUpAppliedTo; + result.hullDownAppliedTo = mHullDownAppliedTo; + result.sslcMode = mSslcMode; + result.sslcUpAppliedTo = mSslcUpAppliedTo; + result.sslcDownAppliedTo = mSslcDownAppliedTo; + result.showCandleTimer = mShowCandleTimer; + result.showCandles = mShowCandles; + result.showHKCandles = mShowHKCandles; + result.showSMHKCandles = mShowSMHKCandles; + result.showPeaksAndVales = mShowPeaksAndVales; + result.showTrends = mShowTrends; + result.fillTrends = mFillTrends; + result.showLevels = mShowLevels; + result.showConsolidations = mShowConsolidations; + result.showRibbons = mShowRibbons; + result.showHull = mShowHull; + result.showSSLChannel = mShowSSLChannel; + result.showFibo1Levels = mShowFibo1Levels; + result.showFibo2Levels = mShowFibo2Levels; + result.showFibo3Levels = mShowFibo3Levels; + result.showFibo4Levels = mShowFibo4Levels; + result.showFibo5Levels = mShowFibo5Levels; + + // + return result; + } + + // + // Set Config ... + bool SetConfig(XMANInputs &config) + { + // + bool result = false; + + // + mCandleTimerColor = config.candleTimerColor; + mCandleTimerCorner = config.candleTimerCorner; + mUpColor = config.upColor; + mDownColor = config.downColor; + mLineColor = config.lineColor; + mBearishColor = config.bearishColor; + mBullishColor = config.bullishColor; + mVolumesColor = config.volumesColor; + mChartMode = config.chartMode; + mL1Method = config.l1Method; + mL1Period = config.l1Period; + mL2Method = config.l2Method; + mL2Period = config.l2Period; + mL3Method = config.l3Method; + mL3Period = config.l3Period; + mL4Method = config.l4Method; + mL4Period = config.l4Period; + mFiboLevel1 = config.fiboLevel1; + mFiboLevel2 = config.fiboLevel2; + mFiboLevel3 = config.fiboLevel3; + mFiboLevel4 = config.fiboLevel4; + mFiboLevel5 = config.fiboLevel5; + mHHMode = config.hhMode; + mLLMode = config.llMode; + mTrendMultiplier = config.trendMultiplier; + mTrendPriceAppliedTo = config.trendPriceAppliedTo; + mRibbonMode = config.ribbonMode; + mHullDivisor = config.hullDivisor; + mHullUpAppliedTo = config.hullUpAppliedTo; + mHullDownAppliedTo = config.hullDownAppliedTo; + mSslcMode = config.sslcMode; + mSslcUpAppliedTo = config.sslcUpAppliedTo; + mSslcDownAppliedTo = config.sslcDownAppliedTo; + mShowCandleTimer = config.showCandleTimer; + mShowCandles = config.showCandles; + mShowHKCandles = config.showHKCandles; + mShowSMHKCandles = config.showSMHKCandles; + mShowPeaksAndVales = config.showPeaksAndVales; + mShowTrends = config.showTrends; + mFillTrends = config.fillTrends; + mShowLevels = config.showLevels; + mShowConsolidations = config.showConsolidations; + mShowRibbons = config.showRibbons; + mShowHull = config.showHull; + mShowSSLChannel = config.showSSLChannel; + mShowFibo1Levels = config.showFibo1Levels; + mShowFibo2Levels = config.showFibo2Levels; + mShowFibo3Levels = config.showFibo3Levels; + mShowFibo4Levels = config.showFibo4Levels; + mShowFibo5Levels = config.showFibo5Levels; + + // + result = Init(); + + // + return result; + } + + // + // Reading Buffers based on Given Bar Index ... + virtual void Calculate( + int barIndex // Given Bar Index + ) + { + // + // Peaks ... + ArraySetAsSeries(peaksBuffer, true); + CopyBuffer( + mHandler, + XMAN_PEAKS_LINE, + barIndex, + mLoopbackBars, + peaksBuffer); + + // + // Peaks State ... + ArraySetAsSeries(peaksStateBuffer, true); + CopyBuffer( + mHandler, + XMAN_PEAKS_STATE_LINE, + barIndex, + mLoopbackBars, + peaksStateBuffer); + + // + // Vales ... + ArraySetAsSeries(valesBuffer, true); + CopyBuffer( + mHandler, + XMAN_VALES_LINE, + barIndex, + mLoopbackBars, + valesBuffer); + + // + // Vales State ... + ArraySetAsSeries(valesStateBuffer, true); + CopyBuffer( + mHandler, + XMAN_VALES_STATE_LINE, + barIndex, + mLoopbackBars, + valesStateBuffer); + + // + // Fibo 1 ... + ArraySetAsSeries(fibLevel1Buffer, true); + CopyBuffer( + mHandler, + XMAN_FIB_L1_LINE, + barIndex, + mLoopbackBars, + fibLevel1Buffer); + + // + // Fibo 2 ... + ArraySetAsSeries(fibLevel2Buffer, true); + CopyBuffer( + mHandler, + XMAN_FIB_L2_LINE, + barIndex, + mLoopbackBars, + fibLevel2Buffer); + + // + // Fibo 3 ... + ArraySetAsSeries(fibLevel3Buffer, true); + CopyBuffer( + mHandler, + XMAN_FIB_L3_LINE, + barIndex, + mLoopbackBars, + fibLevel3Buffer); + + // + // Fibo 4 ... + ArraySetAsSeries(fibLevel4Buffer, true); + CopyBuffer( + mHandler, + XMAN_FIB_L4_LINE, + barIndex, + mLoopbackBars, + fibLevel4Buffer); + + // + // Fibo 5 ... + ArraySetAsSeries(fibLevel5Buffer, true); + CopyBuffer( + mHandler, + XMAN_FIB_L5_LINE, + barIndex, + mLoopbackBars, + fibLevel5Buffer); + + // + // Cycles ... + + // + // Short ... + + // + // High ... + ArraySetAsSeries(sHHBuffer, true); + CopyBuffer( + mHandler, + XMAN_SC_HH_LINE, + barIndex, + mLoopbackBars, + sHHBuffer); + + // + // High State ... + ArraySetAsSeries(sHHStateBuffer, true); + CopyBuffer( + mHandler, + XMAN_SC_HH_STATE_LINE, + barIndex, + mLoopbackBars, + sHHStateBuffer); + + // + // High ... + ArraySetAsSeries(sLLBuffer, true); + CopyBuffer( + mHandler, + XMAN_SC_LL_LINE, + barIndex, + mLoopbackBars, + sLLBuffer); + + // + // High State ... + ArraySetAsSeries(sLLStateBuffer, true); + CopyBuffer( + mHandler, + XMAN_SC_LL_STATE_LINE, + barIndex, + mLoopbackBars, + sLLStateBuffer); + + // + // Medium ... + + // + // High ... + ArraySetAsSeries(mHHBuffer, true); + CopyBuffer( + mHandler, + XMAN_MC_HH_LINE, + barIndex, + mLoopbackBars, + mHHBuffer); + + // + // High State ... + ArraySetAsSeries(mHHStateBuffer, true); + CopyBuffer( + mHandler, + XMAN_MC_HH_STATE_LINE, + barIndex, + mLoopbackBars, + mHHStateBuffer); + + // + // High ... + ArraySetAsSeries(mLLBuffer, true); + CopyBuffer( + mHandler, + XMAN_MC_LL_LINE, + barIndex, + mLoopbackBars, + mLLBuffer); + + // + // High State ... + ArraySetAsSeries(mLLStateBuffer, true); + CopyBuffer( + mHandler, + XMAN_MC_LL_STATE_LINE, + barIndex, + mLoopbackBars, + mLLStateBuffer); + + // + // Long ... + + // + // High ... + ArraySetAsSeries(lHHBuffer, true); + CopyBuffer( + mHandler, + XMAN_LC_HH_LINE, + barIndex, + mLoopbackBars, + lHHBuffer); + + // + // High State ... + ArraySetAsSeries(lHHStateBuffer, true); + CopyBuffer( + mHandler, + XMAN_LC_HH_STATE_LINE, + barIndex, + mLoopbackBars, + lHHStateBuffer); + + // + // High ... + ArraySetAsSeries(lLLBuffer, true); + CopyBuffer( + mHandler, + XMAN_LC_LL_LINE, + barIndex, + mLoopbackBars, + lLLBuffer); + + // + // High State ... + ArraySetAsSeries(lLLStateBuffer, true); + CopyBuffer( + mHandler, + XMAN_LC_LL_STATE_LINE, + barIndex, + mLoopbackBars, + lLLStateBuffer); + + // + // Hind ... + + // + // High ... + ArraySetAsSeries(hHHBuffer, true); + CopyBuffer( + mHandler, + XMAN_HC_HH_LINE, + barIndex, + mLoopbackBars, + hHHBuffer); + + // + // High State ... + ArraySetAsSeries(hHHStateBuffer, true); + CopyBuffer( + mHandler, + XMAN_HC_HH_STATE_LINE, + barIndex, + mLoopbackBars, + hHHStateBuffer); + + // + // High ... + ArraySetAsSeries(hLLBuffer, true); + CopyBuffer( + mHandler, + XMAN_HC_LL_LINE, + barIndex, + mLoopbackBars, + hLLBuffer); + + // + // High State ... + ArraySetAsSeries(hLLStateBuffer, true); + CopyBuffer( + mHandler, + XMAN_HC_LL_STATE_LINE, + barIndex, + mLoopbackBars, + hLLStateBuffer); + + // + // Trend ... + + // + // Trend ... + ArraySetAsSeries(trendBuffer, true); + CopyBuffer( + mHandler, + XMAN_TREND_LINE, + barIndex, + mLoopbackBars, + trendBuffer); + + // + // Trend State ... + ArraySetAsSeries(trendStateBuffer, true); + CopyBuffer( + mHandler, + XMAN_TREND_STATE_LINE, + barIndex, + mLoopbackBars, + trendStateBuffer); + + // + // Ribbons ... + + // + // 1 ... + + // + // R1 ... + ArraySetAsSeries(ribbon1Buffer, true); + CopyBuffer( + mHandler, + XMAN_RB1_LINE, + barIndex, + mLoopbackBars, + ribbon1Buffer); + + // + // R1 State ... + ArraySetAsSeries(ribbon1StateBuffer, true); + CopyBuffer( + mHandler, + XMAN_RB1_STATE_LINE, + barIndex, + mLoopbackBars, + ribbon1StateBuffer); + + // + // 2 ... + + // + // R2 ... + ArraySetAsSeries(ribbon2Buffer, true); + CopyBuffer( + mHandler, + XMAN_RB2_LINE, + barIndex, + mLoopbackBars, + ribbon2Buffer); + + // + // R2 State ... + ArraySetAsSeries(ribbon2StateBuffer, true); + CopyBuffer( + mHandler, + XMAN_RB2_STATE_LINE, + barIndex, + mLoopbackBars, + ribbon2StateBuffer); + + // + // 3 ... + + // + // R3 ... + ArraySetAsSeries(ribbon3Buffer, true); + CopyBuffer( + mHandler, + XMAN_RB3_LINE, + barIndex, + mLoopbackBars, + ribbon3Buffer); + + // + // R3 State ... + ArraySetAsSeries(ribbon3StateBuffer, true); + CopyBuffer( + mHandler, + XMAN_RB3_STATE_LINE, + barIndex, + mLoopbackBars, + ribbon3StateBuffer); + + // + // 4 ... + + // + // R4 ... + ArraySetAsSeries(ribbon4Buffer, true); + CopyBuffer( + mHandler, + XMAN_RB4_LINE, + barIndex, + mLoopbackBars, + ribbon4Buffer); + + // + // R4 State ... + ArraySetAsSeries(ribbon4StateBuffer, true); + CopyBuffer( + mHandler, + XMAN_RB4_STATE_LINE, + barIndex, + mLoopbackBars, + ribbon4StateBuffer); + + // + // 5 ... + + // + // R5 ... + ArraySetAsSeries(ribbon5Buffer, true); + CopyBuffer( + mHandler, + XMAN_RB5_LINE, + barIndex, + mLoopbackBars, + ribbon5Buffer); + + // + // R5 State ... + ArraySetAsSeries(ribbon5StateBuffer, true); + CopyBuffer( + mHandler, + XMAN_RB5_STATE_LINE, + barIndex, + mLoopbackBars, + ribbon5StateBuffer); + + // + // 6 ... + + // + // R6 ... + ArraySetAsSeries(ribbon6Buffer, true); + CopyBuffer( + mHandler, + XMAN_RB6_LINE, + barIndex, + mLoopbackBars, + ribbon6Buffer); + + // + // R6 State ... + ArraySetAsSeries(ribbon6StateBuffer, true); + CopyBuffer( + mHandler, + XMAN_RB6_STATE_LINE, + barIndex, + mLoopbackBars, + ribbon6StateBuffer); + + // + // SSL Channel ... + + // + // UP ... + ArraySetAsSeries(sslUpBuffer, true); + CopyBuffer( + mHandler, + XMAN_SSLC_UP_LINE, + barIndex, + mLoopbackBars, + sslUpBuffer); + + // + // DOWN ... + ArraySetAsSeries(sslDownBuffer, true); + CopyBuffer( + mHandler, + XMAN_SSLC_DOWN_LINE, + barIndex, + mLoopbackBars, + sslDownBuffer); + + // + // HULL Trend ... + + // + // UP ... + ArraySetAsSeries(hullUpBuffer, true); + CopyBuffer( + mHandler, + XMAN_HULL_UP_LINE, + barIndex, + mLoopbackBars, + hullUpBuffer); + + // + // UP State ... + ArraySetAsSeries(hullUpStateBuffer, true); + CopyBuffer( + mHandler, + XMAN_HULL_UP_STATE_LINE, + barIndex, + mLoopbackBars, + hullUpStateBuffer); + + // + // DOWN ... + ArraySetAsSeries(hullDownBuffer, true); + CopyBuffer( + mHandler, + XMAN_HULL_DOWN_LINE, + barIndex, + mLoopbackBars, + hullDownBuffer); + + // + // DOWN State ... + ArraySetAsSeries(hullDownStateBuffer, true); + CopyBuffer( + mHandler, + XMAN_HULL_DOWN_STATE_LINE, + barIndex, + mLoopbackBars, + hullDownStateBuffer); + + // + // Hiken Ashi ... + + // + // Open ... + ArraySetAsSeries(hkOpenBuffer, true); + CopyBuffer( + mHandler, + XMAN_HK_OPEN_LINE, + barIndex, + mLoopbackBars, + hkOpenBuffer); + + // + // High ... + ArraySetAsSeries(hkHighBuffer, true); + CopyBuffer( + mHandler, + XMAN_HK_HIGH_LINE, + barIndex, + mLoopbackBars, + hkHighBuffer); + + // + // Low ... + ArraySetAsSeries(hkLowBuffer, true); + CopyBuffer( + mHandler, + XMAN_HK_LOW_LINE, + barIndex, + mLoopbackBars, + hkLowBuffer); + + // + // Close ... + ArraySetAsSeries(hkCloseBuffer, true); + CopyBuffer( + mHandler, + XMAN_HK_CLOSE_LINE, + barIndex, + mLoopbackBars, + hkCloseBuffer); + + // + // Close ... + ArraySetAsSeries(hkStateBuffer, true); + CopyBuffer( + mHandler, + XMAN_HK_STATE_LINE, + barIndex, + mLoopbackBars, + hkStateBuffer); + } + + // + // Retrieve Info at Specific Bar Index ... + XMANInfo GetInfo( + int barIndex // Given Bar Index + ) + { + // + XMANInfo result; + + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + // Do Calculations ... + Calculate(barIndex); + + // + // Generate Candle Time ... + datetime barTime = GetCandleTime( + mSymbol, + mPeriod, + barIndex); + + // + // Fill Result ... + result.symbol = mSymbol; + result.period = mPeriod; + result.barTime = barTime; + result.barIndex = barIndex; + + // + // Buffers ... + + // + Copy(peaksBuffer, + result.peaks); + Copy(peaksStateBuffer, + result.peaksStates); + Copy(valesBuffer, + result.vales); + Copy(valesStateBuffer, + result.valesStates); + + // + Copy(fibLevel1Buffer, + result.fibLevel1s); + Copy(fibLevel2Buffer, + result.fibLevel2s); + Copy(fibLevel3Buffer, + result.fibLevel3s); + Copy(fibLevel4Buffer, + result.fibLevel4s); + Copy(fibLevel5Buffer, + result.fibLevel5s); + + // + Copy(sHHBuffer, + result.sHHs); + Copy(sHHStateBuffer, + result.sHHStates); + Copy(sLLBuffer, + result.sLLs); + Copy(sLLStateBuffer, + result.sLLStates); + + // + Copy(mHHBuffer, + result.mHHs); + Copy(mHHStateBuffer, + result.mHHStates); + Copy(mLLBuffer, + result.mLLs); + Copy(mLLStateBuffer, + result.mLLStates); + + // + Copy(lHHBuffer, + result.lHHs); + Copy(lHHStateBuffer, + result.lHHStates); + Copy(lLLBuffer, + result.lLLs); + Copy(lLLStateBuffer, + result.lLLStates); + + // + Copy(hHHBuffer, + result.hHHs); + Copy(hHHStateBuffer, + result.hHHStates); + Copy(hLLBuffer, + result.hLLs); + Copy(hLLStateBuffer, + result.hLLStates); + + // + Copy(trendBuffer, + result.trends); + Copy(trendStateBuffer, + result.trendStates); + + // + Copy(ribbon1Buffer, + result.ribbon1s); + Copy(ribbon1StateBuffer, + result.ribbon1States); + + // + Copy(ribbon2Buffer, + result.ribbon2s); + Copy(ribbon2StateBuffer, + result.ribbon2States); + + // + Copy(ribbon3Buffer, + result.ribbon3s); + Copy(ribbon3StateBuffer, + result.ribbon3States); + + // + Copy(ribbon4Buffer, + result.ribbon4s); + Copy(ribbon4StateBuffer, + result.ribbon4States); + + // + Copy(ribbon5Buffer, + result.ribbon5s); + Copy(ribbon5StateBuffer, + result.ribbon5States); + + // + Copy(ribbon6Buffer, + result.ribbon6s); + Copy(ribbon6StateBuffer, + result.ribbon6States); + + // + Copy(sslUpBuffer, + result.sslcUps); + Copy(sslDownBuffer, + result.sslcDowns); + + // + Copy(hullUpBuffer, + result.hullUps); + Copy(hullUpStateBuffer, + result.hullUpStates); + Copy(hullDownBuffer, + result.hullDowns); + Copy(hullDownStateBuffer, + result.hullDownStates); + + // + Copy(hkOpenBuffer, + result.hkOpens); + Copy(hkHighBuffer, + result.hkHighs); + Copy(hkLowBuffer, + result.hkLows); + Copy(hkCloseBuffer, + result.hkCloses); + Copy(hkStateBuffer, + result.hkStates); + + // + return result; + } + + // + // Protcted ... +protected: + // + // Private ... +private: + // + // Inputs ... + + // + // Candle Timer ... + color mCandleTimerColor; // Text Color + ENUM_BASE_CORNER mCandleTimerCorner; // Text Position + + // + // Chart Style ... + color mUpColor; // Up Color + color mDownColor; // Down Color + color mLineColor; // Line mode and Doji candlestick Color + color mBearishColor; // Bullish Color + color mBullishColor; // Bearish Color + color mVolumesColor; // Volumes Color + ENUM_CHART_MODE mChartMode; // Chart Mode + + // + // Market Cycles ... + + // + // Level 1 ... + ENUM_X_PERIOD_METHOD mL1Method; // How to Find Period + ENUM_TIMEFRAMES mL1Period; // Time Period + + // + // Level 2 ... + ENUM_X_PERIOD_METHOD mL2Method; // How to Find Period + ENUM_TIMEFRAMES mL2Period; // Time Period + + // + // Level 3 ... + ENUM_X_PERIOD_METHOD mL3Method; // How to Find Period + ENUM_TIMEFRAMES mL3Period; // Time Period + + // + // Level 4 ... + ENUM_X_PERIOD_METHOD mL4Method; // How to Find Period + ENUM_TIMEFRAMES mL4Period; // Time Period + + // + // Fibonacci ... + double mFiboLevel1; // Fibio 1st Level + double mFiboLevel2; // Fibio 2st Level + double mFiboLevel3; // Fibio 3rd Level + double mFiboLevel4; // Fibio 4th Level + double mFiboLevel5; // Fibio 5th Level + + // + // Boundary Detection Modes ... + ENUM_SERIESMODE mHHMode; // Highest High Calculation Method + ENUM_SERIESMODE mLLMode; // Lowest Low Calculation Method + + // + // Trend Detection + double mTrendMultiplier; // Multiplier + ENUM_APPLIED_PRICE mTrendPriceAppliedTo; // Applied To + + // + // Ribbon Detection ... + ENUM_X_MA_METHOD mRibbonMode; // How to Calculate + + // + // Hull Trend Detection ... + double mHullDivisor; // Divisor (Speed) + ENUM_APPLIED_PRICE mHullUpAppliedTo; // Up Zone Applied to + ENUM_APPLIED_PRICE mHullDownAppliedTo; // Down Zone Applied to + + // + // SSL Channel Detection ... + ENUM_X_MA_METHOD mSslcMode; // How to Calculate + ENUM_APPLIED_PRICE mSslcUpAppliedTo; // Up Applied To + ENUM_APPLIED_PRICE mSslcDownAppliedTo; // Down Applied To + + // + // Presentation ... + bool mShowCandleTimer; // Show Candle Time + bool mShowCandles; // Show Candles + bool mShowHKCandles; // Draw Hiken Ashi Candle + bool mShowSMHKCandles; // Draw Smoothed Hiken Ashi Candle + bool mShowPeaksAndVales; // Show Peaks and Vales + bool mShowTrends; // Show Trends + bool mFillTrends; // Fill Trends + bool mShowLevels; // Show Levels + bool mShowConsolidations; // Show Consolidations + bool mShowRibbons; // Show Ribbons + bool mShowHull; // Show Hull + bool mShowSSLChannel; // Show SSL Channel + bool mShowFibo1Levels; // Show Fibo 1st Level + bool mShowFibo2Levels; // Show Fibo 2nd Level + bool mShowFibo3Levels; // Show Fibo 3rd Level + bool mShowFibo4Levels; // Show Fibo 4th Level + bool mShowFibo5Levels; // Show Fibo 5th Level +}; + +// +// START Usefull Functions ... +// + +// +// END Usefull Functions ... +// diff --git a/MQLTestWorkspace/X121/14030217/Indicators/x-saherelm.x121.xman.ex5 b/MQLTestWorkspace/X121/14030217/Indicators/x-saherelm.x121.xman.ex5 new file mode 100644 index 0000000..f7b0041 Binary files /dev/null and b/MQLTestWorkspace/X121/14030217/Indicators/x-saherelm.x121.xman.ex5 differ diff --git a/MQLTestWorkspace/X121/14030217/Indicators/x-saherelm.x121.xman.mq5 b/MQLTestWorkspace/X121/14030217/Indicators/x-saherelm.x121.xman.mq5 new file mode 100644 index 0000000..4a9b590 --- /dev/null +++ b/MQLTestWorkspace/X121/14030217/Indicators/x-saherelm.x121.xman.mq5 @@ -0,0 +1,4627 @@ +/////////////////////////////////////////////////////// +// SaherElm IT Center MQL5 Indicator +// ------------------------------------------- +// Name: X121_XMAN +// Description: Market Analyzer +// - Find Peaks and Vales +// - Find Trend +// - Find Market Direction +// - Detect Pivot Points and Swings +// +// Contains: +// ----------- +// - 4 Cycle of TimeFrames +// - Fibonacci Golden Zone +// - Trend Detection using True Range Averaging +// - Trend Detecting using Moving Averages Ribbon +// - Trend Detecting using SSL Channel +// - Trend Detecting using Hull 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 X121_XMAN Indicator" +#property strict + +// +// START Constants ... +// + +// +// Indicator Short Name ... +#define ShortName "X121_XMAN" + +// +struct XHullData +{ + // + double value; + double value3; + + // + double wsum1; + double wsum2; + double wsum3; + + // + double lsum1; + double lsum2; + double lsum3; +}; + +// +// 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; +}; + +// +struct XMRBColorInfo +{ + double clr; + double state; +}; + +// +// 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[]; +}; + +// +#include +#include "../Libraries/x-saherelm.xman.parser.lib.mq5" + +// +// END Constants ... +// + +// +// START Inputs ... +// + +// +input group "Candle Timer"; +input string cTimerConfig = "candleTimerColor(clrGold)candleTimerCorner(2)"; // Config + +// +input group "Chart Style"; +input string cStyleConfig = "upColor(clrLime) downColor(clrRed) lineColor(clrLime) bearishColor(clrRed) bullishColor(clrLime) volumesColor(clrGreen) chartMode(1)"; // Config + +// +input group "Makret Cycles"; +input group "Short"; +input string scConfig = "l1Method(1)l1Period(NULL)"; // Config +input group "Medium"; +input string mcConfig = "l2Method(1)l2Period(NULL)"; // Config +input group "Long"; +input string lcConfig = "l3Method(1)l3Period(NULL)"; // Config +input group "Hind"; +input string hcConfig = "l4Method(1)l4Period(NULL)"; // Config + +// +input group "Fibonacci"; +input string fibConfig = "fiboLevel1(0.236)fiboLevel2(0.382)fiboLevel3(0.5)fiboLevel4(0.618)fiboLevel5(0.764)"; // Config + +// +input group "Boundary Detection Modes"; +input string bdConfig = "hhMode(2)llMode(1)"; // Config + +// +input group "Trend Detection"; +input string tdConfig = "trendMultiplier(3)trendPriceAppliedTo(4)"; // Config + +// +input group "Ribbon Detection"; +input string rbConfig = "ribbonMode(5)"; // Config + +// +input group "Hull Trend Detection"; +input string hullConfig = "hullDivisor(2.0)hullUpAppliedTo(3)hullDownAppliedTo(4)"; // Config + +// +input group "SSL Channel"; +input string sslcConfig = "sslcMode(1)sslcUpAppliedTo(3)sslcDownAppliedTo(4)"; // Config + +// +input group "Presentation"; +input string stylePRSConfig = "showCandleTimer(true)showCandles(true)showHKCandles(false)showSMHKCandles(false)"; // Styles +input string pvPRSConfig = "showPeaksAndVales(true)showLevels(false)showConsolidations(false)"; // Peaks and Vales +input string trendPRSConfig = "showHull(false)showTrends(false)fillTrends(false)showRibbons(false)showSSLChannel(false)"; // Trend +input string fiboPRSConfig = "showFibo1Levels(false)showFibo2Levels(false)showFibo3Levels(false)showFibo4Levels(false)showFibo5Levels(false)"; // Fibonacci + +// +// END Inputs ... +// + +// +// START Configs ... +// + +// +// Candles Timer ... +color candleTimerColor = clrGold; // Text Color +ENUM_BASE_CORNER candleTimerCorner = CORNER_RIGHT_UPPER; // Text Position + +// +// Chart Style +color upColor = clrLime; // Up Color +color downColor = clrRed; // Down Color +color lineColor = clrLime; // Line mode and Doji candlestick Color +color bearishColor = clrRed; // Bullish Color +color bullishColor = clrLime; // Bearish Color +color volumesColor = clrGreen; // Volumes Color +ENUM_CHART_MODE chartMode = CHART_CANDLES; // Chart Mode + +// +// Makret Cycles + +// +// Level 1 ... +ENUM_X_PERIOD_METHOD l1Method = X_PERIOD_AUTO; // How to Find Period +ENUM_TIMEFRAMES l1Period = NULL; // Time Period + +// +// Level 2 ... +ENUM_X_PERIOD_METHOD l2Method = X_PERIOD_AUTO; // How to Find Period +ENUM_TIMEFRAMES l2Period = NULL; // Time Period + +// +// Level 3 ... +ENUM_X_PERIOD_METHOD l3Method = X_PERIOD_AUTO; // How to Find Period +ENUM_TIMEFRAMES l3Period = NULL; // Time Period + +// +// Level 4 ... +ENUM_X_PERIOD_METHOD l4Method = X_PERIOD_AUTO; // How to Find Period +ENUM_TIMEFRAMES l4Period = NULL; // Time Period + +// +// Fibonacci ... +double fiboLevel1 = 0.236; // Fibio 1st Level +double fiboLevel2 = 0.382; // Fibio 2st Level +double fiboLevel3 = 0.5; // Fibio 3rd Level +double fiboLevel4 = 0.618; // Fibio 4th Level +double fiboLevel5 = 0.764; // Fibio 5th Level + +// +// Boundary Detection Modes ... +ENUM_SERIESMODE hhMode = MODE_HIGH; // Highest High Calculation Method +ENUM_SERIESMODE llMode = MODE_LOW; // Lowest Low Calculation Method + +// +// Trend Detection ... +double trendMultiplier = 3; // Multiplier +ENUM_APPLIED_PRICE trendPriceAppliedTo = PRICE_MEDIAN; // Applied To + +// +// Ribbon Detection ... +ENUM_X_MA_METHOD ribbonMode = X_MA_AMA; // How to Calculate + +// +// Hull Trend Detection ... +double hullDivisor = 2.0; // Divisor (Speed) +ENUM_APPLIED_PRICE hullUpAppliedTo = PRICE_HIGH; // Up Zone Applied to +ENUM_APPLIED_PRICE hullDownAppliedTo = PRICE_LOW; // Down Zone Applied to + +// +// SSL Channel Detection ... +ENUM_X_MA_METHOD sslcMode = X_MA_SMA; // How to Calculate +ENUM_APPLIED_PRICE sslcUpAppliedTo = PRICE_HIGH; // Up Applied To +ENUM_APPLIED_PRICE sslcDownAppliedTo = PRICE_LOW; // Down Applied To + +// +// Presentation ... +bool showCandleTimer = true; // Show Candle Time +bool showCandles = true; // Show Candles +bool showHKCandles = false; // Draw Hiken Ashi Candle +bool showSMHKCandles = false; // Draw Smoothed Hiken Ashi Candle +bool showPeaksAndVales = true; // Show Peaks and Vales +bool showTrends = true; // Show Trends +bool fillTrends = false; // Fill Trends +bool showLevels = false; // Show Levels +bool showConsolidations = false; // Show Consolidations +bool showRibbons = false; // Show Ribbons +bool showHull = false; // Show Hull +bool showSSLChannel = false; // Show SSL Channel +bool showFibo1Levels = false; // Show Fibo 1st Level +bool showFibo2Levels = false; // Show Fibo 2nd Level +bool showFibo3Levels = false; // Show Fibo 3rd Level +bool showFibo4Levels = false; // Show Fibo 4th Level +bool showFibo5Levels = false; // Show Fibo 5th Level + +// +// END Configs ... +// + +// +// 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 94 +#property indicator_plots 50 + +// +// PEKSANDVALES ... + +// +// PEAKS ... + +// +#define peaksBufferIndex 0 +double peaksBuffer[]; + +// +#property indicator_label1 "X121_XMAN PEAKS" +#property indicator_type1 DRAW_ARROW +#property indicator_color1 clrAqua +#property indicator_width1 1 + +// +// VALES ... + +// +#define valesBufferIndex 1 +double valesBuffer[]; + +// +#property indicator_label2 "X121_XMAN 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 "X121_XMAN 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 "X121_XMAN 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 "X121_XMAN 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 "X121_XMAN 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 "X121_XMAN 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 "X121_XMAN 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 "X121_XMAN FL5" +#property indicator_type9 DRAW_COLOR_LINE +#property indicator_color9 CLR_NONE, clrGold +#property indicator_style9 STYLE_DASHDOTDOT +#property indicator_width9 1 + +// +// LEVELS ... + +// +#define sHHBufferIndex 16 +#define sHHBufferPlotIndex 9 +double sHHBuffer[]; + +// +#define sHHColorBufferIndex 17 +double sHHColorBuffer[]; + +// +#property indicator_label10 "X121_XMAN 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 sLLBufferIndex 18 +#define sLLBufferPlotIndex 10 +double sLLBuffer[]; + +// +#define sLLColorBufferIndex 19 +double sLLColorBuffer[]; + +// +#property indicator_label11 "X121_XMAN 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 mHHBufferIndex 20 +#define mHHBufferPlotIndex 11 +double mHHBuffer[]; + +// +#define mHHColorBufferIndex 21 +double mHHColorBuffer[]; + +// +#property indicator_label12 "X121_XMAN 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 mLLBufferIndex 22 +#define mLLBufferPlotIndex 12 +double mLLBuffer[]; + +// +#define mLLColorBufferIndex 23 +double mLLColorBuffer[]; + +// +#property indicator_label13 "X121_XMAN 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 lHHBufferIndex 24 +#define lHHBufferPlotIndex 13 +double lHHBuffer[]; + +// +#define lHHColorBufferIndex 25 +double lHHColorBuffer[]; + +// +#property indicator_label14 "X121_XMAN 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 lLLBufferIndex 26 +#define lLLBufferPlotIndex 14 +double lLLBuffer[]; + +// +#define lLLColorBufferIndex 27 +double lLLColorBuffer[]; + +// +#property indicator_label15 "X121_XMAN 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 hHHBufferIndex 28 +#define hHHBufferPlotIndex 15 +double hHHBuffer[]; + +// +#define hHHColorBufferIndex 29 +double hHHColorBuffer[]; + +// +#property indicator_label16 "X121_XMAN 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 hLLBufferIndex 30 +#define hLLBufferPlotIndex 16 +double hLLBuffer[]; + +// +#define hLLColorBufferIndex 31 +double hLLColorBuffer[]; + +// +#property indicator_label17 "X121_XMAN HLL" +#property indicator_type17 DRAW_COLOR_LINE +#property indicator_color17 CLR_NONE, clrLightGray, clrAqua, clrMagenta +#property indicator_style17 STYLE_DOT +#property indicator_width17 1 + +// +// XSTR Buffers ... + +// +#define fillUpBufferIndex 32 +double fillUpBuffer[]; + +#define fillDownBufferIndex 33 +double fillDownBuffer[]; + +// +#define fillingBufferPlotIndex 17 + +// +#property indicator_label18 "X121_XMAN TRND Filling" +#property indicator_type18 DRAW_FILLING +#property indicator_color18 clrBisque, clrPaleGreen + +// +#define trendBufferIndex 34 +#define trendBufferPlotIndex 18 +double trendBuffer[]; + +// +#define trendColorBufferIndex 35 +double trendColorBuffer[]; + +// +#property indicator_label19 "X121_XMAN TRND" +#property indicator_type19 DRAW_COLOR_LINE +#property indicator_color19 CLR_NONE, clrGreen, clrDarkRed +#property indicator_style19 STYLE_DOT +#property indicator_width19 1 + +// +// XMRB ... + +// +// RIBBON 1 ... +// High ... + +// +#define ribbon1BufferIndex 36 +#define ribbon1BufferPlotIndex 19 +double ribbon1Buffer[]; + +// +#define ribbon1ColorBufferIndex 37 +double ribbon1ColorBuffer[]; + +// +#property indicator_label20 "X121_XMAN RB 1" +#property indicator_type20 DRAW_COLOR_LINE +#property indicator_color20 CLR_NONE, clrGray, clrGreen, clrDarkRed +#property indicator_style20 STYLE_DASH +#property indicator_width20 1 + +// +// RIBBON 2 ... +// Open ... + +// +#define ribbon2BufferIndex 38 +#define ribbon2BufferPlotIndex 20 +double ribbon2Buffer[]; + +// +#define ribbon2ColorBufferIndex 39 +double ribbon2ColorBuffer[]; + +// +#property indicator_label21 "X121_XMAN RB 2" +#property indicator_type21 DRAW_COLOR_LINE +#property indicator_color21 CLR_NONE, clrGray, clrGreen, clrDarkRed +#property indicator_style21 STYLE_DASH +#property indicator_width21 1 + +// +// RIBBON 3 ... +// Close ... + +// +#define ribbon3BufferIndex 40 +#define ribbon3BufferPlotIndex 21 +double ribbon3Buffer[]; + +// +#define ribbon3ColorBufferIndex 41 +double ribbon3ColorBuffer[]; + +// +#property indicator_label22 "X121_XMAN RB 3" +#property indicator_type22 DRAW_COLOR_LINE +#property indicator_color22 CLR_NONE, clrGray, clrGreen, clrDarkRed +#property indicator_style22 STYLE_DASH +#property indicator_width22 1 + +// +// RIBBON 4 ... +// Median ... + +// +#define ribbon4BufferIndex 42 +#define ribbon4BufferPlotIndex 22 +double ribbon4Buffer[]; + +// +#define ribbon4ColorBufferIndex 43 +double ribbon4ColorBuffer[]; + +// +#property indicator_label23 "X121_XMAN RB 4" +#property indicator_type23 DRAW_COLOR_LINE +#property indicator_color23 CLR_NONE, clrGray, clrGreen, clrDarkRed +#property indicator_style23 STYLE_DASH +#property indicator_width23 1 + +// +// RIBBON 5 ... +// Typical ... + +// +#define ribbon5BufferIndex 44 +#define ribbon5BufferPlotIndex 23 +double ribbon5Buffer[]; + +// +#define ribbon5ColorBufferIndex 45 +double ribbon5ColorBuffer[]; + +// +#property indicator_label24 "X121_XMAN RB 5" +#property indicator_type24 DRAW_COLOR_LINE +#property indicator_color24 CLR_NONE, clrGray, clrGreen, clrDarkRed +#property indicator_style24 STYLE_DASH +#property indicator_width24 1 + +// +// RIBBON 6 ... +// Low ... + +// +#define ribbon6BufferIndex 46 +#define ribbon6BufferPlotIndex 24 +double ribbon6Buffer[]; + +// +#define ribbon6ColorBufferIndex 47 +double ribbon6ColorBuffer[]; + +// +#property indicator_label25 "X121_XMAN RB 6" +#property indicator_type25 DRAW_COLOR_LINE +#property indicator_color25 CLR_NONE, clrGray, clrGreen, clrDarkRed +#property indicator_style25 STYLE_DASH +#property indicator_width25 1 + +// +// XSSLC ... + +// +#define sslcUpBufferIndex 48 +#define sslcUpBufferPlotIndex 25 +double sslcUpBuffer[]; + +// +#define sslcUpColorBufferIndex 49 +double sslcUpColorBuffer[]; + +// +#property indicator_label26 "X121_XMAN SSLC Up" +#property indicator_type26 DRAW_COLOR_LINE +#property indicator_color26 CLR_NONE, clrLime +#property indicator_style26 STYLE_SOLID +#property indicator_width26 1 + +// +#define sslcDownBufferIndex 50 +#define sslcDownBufferPlotIndex 26 +double sslcDownBuffer[]; + +// +#define sslcDownColorBufferIndex 51 +double sslcDownColorBuffer[]; + +// +#property indicator_label27 "X121_XMAN SSLC Down" +#property indicator_type27 DRAW_COLOR_LINE +#property indicator_color27 CLR_NONE, clrRed +#property indicator_style27 STYLE_SOLID +#property indicator_width27 1 + +// +// XHULL ... + +// +// UP Zone ... + +// +#define hullUpZoneBufferIndex 52 +#define hullUpZoneBufferPlotIndex 27 +#define hullUpZoneColorBufferIndex 53 + +// +double hullUpZoneBuffer[]; +double hullUpZoneColorBuffer[]; + +// +#property indicator_label28 "X121_XMAN HULL Up" +#property indicator_type28 DRAW_COLOR_LINE +#property indicator_color28 CLR_NONE, clrGray, clrAqua, clrMagenta +#property indicator_width28 1 + +// +// DOWN Zone ... + +// +#define hullDownZoneBufferIndex 54 +#define hullDownZoneBufferPlotIndex 28 +#define hullDownZoneColorBufferIndex 55 + +// +double hullDownZoneBuffer[]; +double hullDownZoneColorBuffer[]; + +// +#property indicator_label29 "X121_XMAN HULL Down" +#property indicator_type29 DRAW_COLOR_LINE +#property indicator_color29 CLR_NONE, clrGray, clrAqua, clrMagenta +#property indicator_width29 1 + +// +// Open ... +#define hkOpenBufferIndex 56 +double hkOpenBuffer[]; + +// +// High ... +#define hkHighBufferIndex 57 +double hkHighBuffer[]; + +// +// Low ... +#define hkLowBufferIndex 58 +double hkLowBuffer[]; + +// +// Close ... +#define hkCloseBufferIndex 59 +double hkCloseBuffer[]; + +// +// Candle Color ... +#define hkCandleColorBufferIndex 60 +double hkCandleColorBuffer[]; + +// +#define hkCandlesBufferIndex 29 + +// +#property indicator_label30 "X121_XMAN HK Open;X121_XMAN HK High;X121_XMAN HK Low;X121_XMAN HK Close" +#property indicator_type30 DRAW_COLOR_CANDLES +#property indicator_color30 CLR_NONE, clrAqua, clrMagenta + +// +// Open ... +#define smhkOpenBufferIndex 61 +double smhkOpenBuffer[]; + +// +// High ... +#define smhkHighBufferIndex 62 +double smhkHighBuffer[]; + +// +// Low ... +#define smhkLowBufferIndex 63 +double smhkLowBuffer[]; + +// +// Close ... +#define smhkCloseBufferIndex 64 +double smhkCloseBuffer[]; + +// +// Candle Color ... +#define smhkCandleColorBufferIndex 65 +double smhkCandleColorBuffer[]; + +// +#define smhkCandlesBufferIndex 30 + +// +#property indicator_label31 "X121_XMAN SMHK Open;X121_XMAN SMHK High;X121_XMAN SMHK Low;X121_XMAN SMHK Close" +#property indicator_type31 DRAW_COLOR_CANDLES +#property indicator_color31 CLR_NONE, clrOliveDrab, clrSaddleBrown + +// +// DATA Buffers ... + +#define lastBufferIndex 65 + +// +// 66 +#define atrBufferIndex lastBufferIndex + 1 +double atrBuffer[]; + +// +// 67 +#define trendStateBufferIndex lastBufferIndex + 2 +double trendStateBuffer[]; + +// +// 68 +#define upBufferIndex lastBufferIndex + 3 +double upBuffer[]; + +// +// 69 +#define downBufferIndex lastBufferIndex + 4 +double downBuffer[]; + +// +// 70 +#define priceBufferIndex lastBufferIndex + 5 +double priceBuffer[]; + +// +// 71 +#define sslcUpMaBufferIndex lastBufferIndex + 6 +double sslcUpMaBuffer[]; + +// +// 72 +#define sslcDownMaBufferIndex lastBufferIndex + 7 +double sslcDownMaBuffer[]; + +// +// 73 +#define sslcKpiBufferIndex lastBufferIndex + 8 +double sslcKpiBuffer[]; + +// +// STATE Buffers ... + +// +// 74 +// When new Peaks Happens it's Valued otherwise EMPTY_VALUE ... +#define peaksStateBufferIndex lastBufferIndex + 9 +double peaksStateBuffer[]; + +// +// 75 +// When new Vales Happens it's Valued otherwise EMPTY_VALUE ... +#define valesStateBufferIndex lastBufferIndex + 10 +double valesStateBuffer[]; + +// +// SHORT Cycle ... + +// +// 76 +#define sHHStateBufferIndex lastBufferIndex + 11 +double sHHStateBuffer[]; + +// +// 77 +#define sLLStateBufferIndex lastBufferIndex + 12 +double sLLStateBuffer[]; + +// +// MEDIUM Cycle ... + +// +// 78 +#define mHHStateBufferIndex lastBufferIndex + 13 +double mHHStateBuffer[]; + +// +// 79 +#define mLLStateBufferIndex lastBufferIndex + 14 +double mLLStateBuffer[]; + +// +// LONG Cycle ... + +// +// 80 +#define lHHStateBufferIndex lastBufferIndex + 15 +double lHHStateBuffer[]; + +// +// 81 +#define lLLStateBufferIndex lastBufferIndex + 16 +double lLLStateBuffer[]; + +// +// HIND Cycle ... + +// +// 82 +#define hHHStateBufferIndex lastBufferIndex + 17 +double hHHStateBuffer[]; + +// +// 83 +#define hLLStateBufferIndex lastBufferIndex + 18 +double hLLStateBuffer[]; + +// +// XSTR ... +// 84 +#define strTrendStateBufferIndex lastBufferIndex + 19 +double strTrendStateBuffer[]; + +// +// XMRB ... + +// +// RIBBON 1 (High) ... +// 85 +#define rb1StateBufferIndex lastBufferIndex + 20 +double rb1StateBuffer[]; + +// +// RIBBON 2 (Open) ... +// 86 +#define rb2StateBufferIndex lastBufferIndex + 21 +double rb2StateBuffer[]; + +// +// RIBBON 3 (Close) ... +// 87 +#define rb3StateBufferIndex lastBufferIndex + 22 +double rb3StateBuffer[]; + +// +// RIBBON 4 (Median) ... +// 88 +#define rb4StateBufferIndex lastBufferIndex + 23 +double rb4StateBuffer[]; + +// +// RIBBON 5 (Typical) ... +// 89 +#define rb5StateBufferIndex lastBufferIndex + 24 +double rb5StateBuffer[]; + +// +// RIBBON 6 (Low) ... +// 90 +#define rb6StateBufferIndex lastBufferIndex + 25 +double rb6StateBuffer[]; + +// +// XHULL ... + +// +// 91 +#define hullUpStateBufferIndex lastBufferIndex + 26 +double hullUpStateBuffer[]; + +// +// 92 +#define hullDownStateBufferIndex lastBufferIndex + 27 +double hullDownStateBuffer[]; + +// +// XHK ... +// 93 +#define hkStateBufferIndex lastBufferIndex + 28 +double hkStateBuffer[]; + +// +// END Buffers ... +// + +// +// START Global Definitions: Variables, Properties and etc ... +// + +// +int maxLength; + +// +double lastPeak; +double lastVale; + +// +double mLastSHH = 0; +double mLastSLL = 0; + +// +double mLastMHH = 0; +double mLastMLL = 0; + +// +double mLastLHH = 0; +double mLastLLL = 0; + +// +double mLastHHH = 0; +double mLastHLL = 0; + +// +double mHideColorIDX = 0; + +// +int currentPeriodSecconds = 0; + +// +// CYCLE 1 ... +int mL1Candles; +int mL1PeriodSecconds = 0; +int mLastL1StartBarIndex = 0; +datetime mLastL1StartTime = NULL; +ENUM_TIMEFRAMES mL1Period = NULL; + +// +// CYCLE 2 ... +int mL2Candles; +int mL2PeriodSecconds = 0; +int mLastL2StartBarIndex = 0; +datetime mLastL2StartTime = NULL; +ENUM_TIMEFRAMES mL2Period = NULL; + +// +// CYCLE 3 ... +int mL3Candles; +int mL3PeriodSecconds = 0; +int mLastL3StartBarIndex = 0; +datetime mLastL3StartTime = NULL; +ENUM_TIMEFRAMES mL3Period = NULL; + +// +// CYCLE 4 ... +int mL4Candles; +int mL4PeriodSecconds = 0; +int mLastL4StartBarIndex = 0; +datetime mLastL4StartTime = NULL; +ENUM_TIMEFRAMES mL4Period = NULL; + +// +// XSTR ... + +// +int atrHandler = INVALID_HANDLE; + +// +int changeOfTrend; +int startBearishTrend; +int startBullishTrend; + +// +int mStrLength; + +// +// XMRB ... + +int mMRBLength; +int mMRBAMAFast = 2; +int mMRBAMASlow = 30; + +// +int rb1Handler = INVALID_HANDLE; +int rb2Handler = INVALID_HANDLE; +int rb3Handler = INVALID_HANDLE; +int rb4Handler = INVALID_HANDLE; +int rb5Handler = INVALID_HANDLE; +int rb6Handler = INVALID_HANDLE; + +// +// XSSLC ... + +// +int mSSLCLength; + +// +int sslcUpHandler = INVALID_HANDLE; +int sslcDownHandler = INVALID_HANDLE; + +// +// XHULL ... + +// +int mHULLLength; + +// +XSCHull *mUpZHull; +XSCHull *mDownZHull; + +// +double mLastHullUpValue; +double mLastHullUpColorValue = 1; +double mLastHullDownValue; +double mLastHullDownColorValue = 1; + +// +// XCC ... + +// +XChartStyle chartStyle; +XChartStyle clearStyle; + +// +int mHKSmoothingLength; + +// +// END Global Definitions: Variables, Properties and etc ... +// + +// +// START Event Handlers ... +// + +// +// Initialization ... +int OnInit() +{ + // + // Parse Configs ... + if (!ParseConfigs()) + { + return INIT_PARAMETERS_INCORRECT; + } + + // + // Validate Inputs ... + if (!ValidateInputs()) + { + return INIT_PARAMETERS_INCORRECT; + } + + // + InitCandleTimer(); + + // + // Initial Periods ... + InitialCycles(); + + // + 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(); + + // + // We Can Choose ATR Length based on Other Cycles ... + mStrLength = mL4Candles; + atrHandler = iATR( + _Symbol, + _Period, + mStrLength); + if (atrHandler == INVALID_HANDLE) + { + return INIT_FAILED; + } + + // + mMRBLength = mL4Candles; + if (!InitRibbons()) + { + return INIT_FAILED; + } + + // + mSSLCLength = mL4Candles; + if (!InitSSLChannel()) + { + return INIT_FAILED; + } + + // + mHULLLength = mL4Candles; + if (!InitHullTrend()) + { + return INIT_FAILED; + } + + // + mHKSmoothingLength = mL4Candles; + + // + // 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 + + // + // Here we can handle De Initialization Reasons ... + IndicatorRelease(atrHandler); + + // + // XMRB ... + IndicatorRelease(rb1Handler); + IndicatorRelease(rb2Handler); + IndicatorRelease(rb3Handler); + IndicatorRelease(rb4Handler); + IndicatorRelease(rb5Handler); + IndicatorRelease(rb6Handler); + + // + // XSSLC ... + IndicatorRelease(sslcUpHandler); + IndicatorRelease(sslcDownHandler); + + // + // XHULL ... + delete mUpZHull; + delete mDownZHull; + + // + ObjectDelete(0, ShortName); + + // + Comment(""); +} + +// +// 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[]) +{ + // + // Calculate Candle Remain Time ... + CalculateCandleTimer(); + + // + // 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 = GetAppliedPrice( + hullUpAppliedTo, + open, high, low, close, i); + + // + double downPrice = GetAppliedPrice( + hullDownAppliedTo, + open, high, low, close, i); + + // + CalculateHull(i, rates_total, upPrice, downPrice); + } + + // + bool isXSTRCalculated = CalculateXSTR( + rates_total, + prev_calculated, + open, + high, + low, + close); + if (!isXSTRCalculated) + { + return prev_calculated; + } + + // + // Prepare Buffers ... + ArraySetAsSeries(time, true); + ArraySetAsSeries(open, true); + ArraySetAsSeries(high, true); + ArraySetAsSeries(low, true); + ArraySetAsSeries(close, true); + ArraySetAsSeries(tick_volume, true); + ArraySetAsSeries(volume, true); + ArraySetAsSeries(spread, true); + + // + + // + // Checking Handlers Calculated Bars ... + + // + // XMRB ... + int rb1CalculatedBars = BarsCalculated(rb1Handler); + int rb2CalculatedBars = BarsCalculated(rb2Handler); + int rb3CalculatedBars = BarsCalculated(rb3Handler); + int rb4CalculatedBars = BarsCalculated(rb4Handler); + int rb5CalculatedBars = BarsCalculated(rb5Handler); + int rb6CalculatedBars = BarsCalculated(rb6Handler); + + // + // XSSLC ... + int sslcUpCalculatedBars = BarsCalculated(sslcUpHandler); + int sslcDownCalculatedBars = BarsCalculated(sslcDownHandler); + + // + bool isCalculatedBarsNotPassed = + // + // XMRB ... + rb1CalculatedBars < maxLength || + rb2CalculatedBars < maxLength || + rb3CalculatedBars < maxLength || + rb4CalculatedBars < maxLength || + rb5CalculatedBars < maxLength || + rb6CalculatedBars < maxLength || + // + // XSSLC ... + sslcUpCalculatedBars < maxLength || + sslcDownCalculatedBars < maxLength + // + ; + + // + if (isCalculatedBarsNotPassed) + { + return prev_calculated; + } + + // + limit = (prev_calculated > rates_total || prev_calculated <= 0) ? rates_total : (rates_total - prev_calculated) + 1; + + // + // Check Handlers Copied Bars ... + + // + // XMRB ... + int rb1CopiedBars = CopyBuffer(rb1Handler, 0, 0, limit, ribbon1Buffer); + int rb2CopiedBars = CopyBuffer(rb2Handler, 0, 0, limit, ribbon2Buffer); + int rb3CopiedBars = CopyBuffer(rb3Handler, 0, 0, limit, ribbon3Buffer); + int rb4CopiedBars = CopyBuffer(rb4Handler, 0, 0, limit, ribbon4Buffer); + int rb5CopiedBars = CopyBuffer(rb5Handler, 0, 0, limit, ribbon5Buffer); + int rb6CopiedBars = CopyBuffer(rb6Handler, 0, 0, limit, ribbon6Buffer); + + // + // XSSLC ... + int sslcUpCopiedBars = CopyBuffer(sslcUpHandler, 0, 0, limit, sslcUpMaBuffer); + int sslcDownCopiedBars = CopyBuffer(sslcDownHandler, 0, 0, limit, sslcDownMaBuffer); + + // + bool isCopiedBarsNotPassed = + // + // XMRB ... + rb1CopiedBars < 0 || + rb2CopiedBars < 0 || + rb3CopiedBars < 0 || + rb4CopiedBars < 0 || + rb5CopiedBars < 0 || + rb6CopiedBars < 0 || + // + // XSSLC ... + sslcUpCopiedBars < 0 || + sslcDownCopiedBars < 0 + // + ; + + // + if (isCopiedBarsNotPassed) + { + return prev_calculated; + } + + // + // Main Loop ... + for (int i = limit - 1; i >= 0 && !IsStopped(); i--) + { + // + CalculateBuffers(i); + + // + CalculateRibbonsColors(i, low, high); + + // + CalculateHikenAshi(i, prev_calculated, rates_total, open, high, close, low); + + // + CalculateSSLC(i, limit, rates_total, prev_calculated, close); + } + + // + CalculateSMHK(rates_total, prev_calculated); + + // + return rates_total; +} + +// +// END Event Handlers ... +// + +// +// START Functions ... +// + +// +// Parse Configs ... +bool ParseConfigs() +{ + // + bool result = false; + + // + // Since we Use Default Values ... + // Apply Changes Only When it's Provided ... + + // + bool hasCTConfig = StringLen(cTimerConfig) > 0; + if (hasCTConfig) + { + // + XCTimerConfig cfg = ParseCTimerConfig(cTimerConfig); + + // + candleTimerColor = cfg.candleTimerColor; + candleTimerCorner = cfg.candleTimerCorner; + } + + // + bool hasChartConfig = StringLen(cStyleConfig) > 0; + if (hasChartConfig) + { + // + XChartStyleConfig cfg = ParseChartStyleConfig(cStyleConfig); + + // + upColor = cfg.upColor; + downColor = cfg.downColor; + lineColor = cfg.lineColor; + bearishColor = cfg.bearishColor; + bullishColor = cfg.bullishColor; + volumesColor = cfg.volumesColor; + chartMode = cfg.chartMode; + } + + // + bool hasSCConfig = StringLen(scConfig) > 0; + if (hasSCConfig) + { + // + XSCConfig cfg = PrseSCConfig(scConfig); + + // + l1Method = cfg.l1Method; + l1Period = cfg.l1Period; + } + + // + bool hasMCConfig = StringLen(mcConfig) > 0; + if (hasMCConfig) + { + // + XMCConfig cfg = PrseMCConfig(mcConfig); + + // + l2Method = cfg.l2Method; + l2Period = cfg.l2Period; + } + + // + bool hasLCConfig = StringLen(lcConfig) > 0; + if (hasLCConfig) + { + // + XLCConfig cfg = PrseLCConfig(lcConfig); + + // + l3Method = cfg.l3Method; + l3Period = cfg.l3Period; + } + + // + bool hasHCConfig = StringLen(hcConfig) > 0; + if (hasHCConfig) + { + // + XHCConfig cfg = PrseHCConfig(hcConfig); + + // + l4Method = cfg.l4Method; + l4Period = cfg.l4Period; + } + + // + bool hasFibConfig = StringLen(fibConfig) > 0; + if (hasFibConfig) + { + // + XFiboConfig cfg = PrseFiboConfig(fibConfig); + + // + fiboLevel1 = cfg.fiboLevel1; + fiboLevel2 = cfg.fiboLevel2; + fiboLevel3 = cfg.fiboLevel3; + fiboLevel4 = cfg.fiboLevel4; + fiboLevel5 = cfg.fiboLevel5; + } + + // + bool hasBDConfig = StringLen(bdConfig) > 0; + if (hasBDConfig) + { + // + XBDConfig cfg = ParseBDConfig(bdConfig); + + // + hhMode = cfg.hhMode; + llMode = cfg.llMode; + } + + // + bool hasTDConfig = StringLen(tdConfig) > 0; + if (hasTDConfig) + { + // + XTDConfig cfg = ParseTDConfig(tdConfig); + + // + trendMultiplier = cfg.trendMultiplier; + trendPriceAppliedTo = cfg.trendPriceAppliedTo; + } + + // + bool hasRBConfig = StringLen(rbConfig) > 0; + if (hasRBConfig) + { + // + XRBConfig cfg = ParseRBConfig(rbConfig); + + // + ribbonMode = cfg.ribbonMode; + } + + // + bool hasHullConfig = StringLen(hullConfig) > 0; + if (hasHullConfig) + { + // + XHullConfig cfg = ParseHullConfig(hullConfig); + + // + hullDivisor = cfg.hullDivisor; + hullUpAppliedTo = cfg.hullUpAppliedTo; + hullDownAppliedTo = cfg.hullDownAppliedTo; + } + + // + bool hasSSLCConfig = StringLen(sslcConfig) > 0; + if (hasSSLCConfig) + { + // + XSSLCConfig cfg = ParseSSLCConfig(sslcConfig); + + // + sslcMode = cfg.sslcMode; + sslcUpAppliedTo = cfg.sslcUpAppliedTo; + sslcDownAppliedTo = cfg.sslcDownAppliedTo; + } + + // + bool hasStylePresentationConfig = StringLen(stylePRSConfig) > 0; + if (hasStylePresentationConfig) + { + // + XStylePresentationConfig cfg = ParseStylePresentationConfig(stylePRSConfig); + + // + showCandleTimer = cfg.showCandleTimer; + showCandles = cfg.showCandles; + showHKCandles = cfg.showHKCandles; + showSMHKCandles = cfg.showSMHKCandles; + } + + // + bool hasPVPresentationConfig = StringLen(pvPRSConfig) > 0; + if (hasPVPresentationConfig) + { + // + XPVPresentationConfig cfg = ParsePVPresentationConfig(pvPRSConfig); + + // + showPeaksAndVales = cfg.showPeaksAndVales; + showLevels = cfg.showLevels; + showConsolidations = cfg.showConsolidations; + } + + // + bool hasSTrendPresentationConfig = StringLen(trendPRSConfig) > 0; + if (hasSTrendPresentationConfig) + { + // + XTrendPresentationConfig cfg = ParseTrendPresentationConfig(trendPRSConfig); + + // + showHull = cfg.showHull; + showTrends = cfg.showTrends; + fillTrends = cfg.fillTrends; + showRibbons = cfg.showRibbons; + showSSLChannel = cfg.showSSLChannel; + } + + // + bool hasFiboPresentationConfig = StringLen(fiboPRSConfig) > 0; + if (hasFiboPresentationConfig) + { + // + XFiboPresentationConfig cfg = ParePresentationConfig(fiboPRSConfig); + + // + showFibo1Levels = cfg.showFibo1Levels; + showFibo2Levels = cfg.showFibo2Levels; + showFibo3Levels = cfg.showFibo3Levels; + showFibo4Levels = cfg.showFibo4Levels; + showFibo5Levels = cfg.showFibo5Levels; + } + + // + result = true; + + // + return result; +} + +// +// Validate Input Args for Initialization ... +bool ValidateInputs() +{ + // + bool result = true; + + // + // Validate User Inputs ... + result = + // + // L1 ... + // Short Cycle ... + ( + // + l1Method == X_PERIOD_AUTO + ? l1Period == NULL + : l1Period != NULL && l1Method != X_PERIOD_NOTHING + // + ) + // + && + // + // L2 ... + // Medium Cycle ... + ( + // + l2Method == X_PERIOD_AUTO + ? l2Period == NULL + : l2Period != NULL && l2Method != X_PERIOD_NOTHING + // + ) + // + && + // + // L3 ... + // Long Cycle ... + ( + // + l3Method == X_PERIOD_AUTO + ? l3Period == NULL + : l3Period != NULL && l3Method != X_PERIOD_NOTHING + // + ) + // + && + // + // L4 ... + // Hind Cycle ... + ( + // + l4Method == X_PERIOD_AUTO + ? l4Period == NULL + : l4Period != NULL && l4Method != X_PERIOD_NOTHING + // + ) + // + && + // + // Validate Ribbon ... + ( + // + ribbonMode != X_MA_NOTHING + // + ) + // + ; + + // + return result; +} + +// +// Retrieve all Exists Input Max Length ... +// use for Start Of Drawing ... +int ExtractMaxLengthOfInputs() +{ + // + int result = 1; + + // + result = MathMax(result, mL1Candles); + result = MathMax(result, mL2Candles); + result = MathMax(result, mL3Candles); + result = MathMax(result, mL4Candles); + + // + return result; +} + +// +// Init Candle Timer ... +void InitCandleTimer() +{ + // + // Validate Inputs ... + if (showCandleTimer) + { + CreateIndicatorObject(); + } + else + { + ObjectDelete(0, ShortName); + } +} + +// +// Initial Multi Time Frame Cycles Periods ... +void InitialCycles() +{ + // + // Calculate Current Period Secconds ... + currentPeriodSecconds = PeriodSeconds(_Period); + + // + // Nearest ... + // Calculate Cycle 1 Requirements ... + if (mL1Period == NULL) + { + // + if (l1Method == X_PERIOD_AUTO) + { + mL1Period = GetNearestTimeFrame(_Period); + } + else + { + mL1Period = l1Period; + } + + // + mL1PeriodSecconds = PeriodSeconds(mL1Period); + + // + mL1Candles = mL1PeriodSecconds / currentPeriodSecconds; + } + + // + // Mediest ... + // Calculate Cycle 2 Requirements ... + if (mL2Period == NULL) + { + // + if (l2Method == X_PERIOD_AUTO) + { + mL2Period = GetMediestTimeFrame(_Period); + } + else + { + mL2Period = l2Period; + } + + // + mL2PeriodSecconds = PeriodSeconds(mL2Period); + + // + mL2Candles = mL2PeriodSecconds / currentPeriodSecconds; + } + + // + // Farest ... + // Calculate Cycle 3 Requirements ... + if (mL3Period == NULL) + { + // + if (l3Method == X_PERIOD_AUTO) + { + mL3Period = GetFarestTimeFrame(_Period); + } + else + { + mL3Period = l3Period; + } + + // + mL3PeriodSecconds = PeriodSeconds(mL3Period); + + // + mL3Candles = mL3PeriodSecconds / currentPeriodSecconds; + } + + // + // HindMost ... + // Calculate Cycle 4 Requirements ... + if (mL4Period == NULL) + { + // + if (l4Method == X_PERIOD_AUTO) + { + mL4Period = GetHindmostTimeFrame(_Period); + } + else + { + mL4Period = l4Period; + } + + // + mL4PeriodSecconds = PeriodSeconds(mL4Period); + + // + mL4Candles = mL4PeriodSecconds / currentPeriodSecconds; + } + + // + string comment = GenerateCyclesRepresentation(); + Comment(comment); +} + +// +bool InitRibbons() +{ + // + bool result = false; + + // + if (mMRBLength <= 0) + { + return result; + } + + // + // RIBBON 1 ... + // High ... + result = InitMaHandler( + rb1Handler, + mMRBLength, + ribbonMode, + PRICE_HIGH); + if (!result) + { + return result; + } + + // + // RIBBON 2 ... + // Open ... + result = InitMaHandler( + rb2Handler, + mMRBLength, + ribbonMode, + PRICE_OPEN); + if (!result) + { + return result; + } + + // + // RIBBON 3 ... + // Close ... + result = InitMaHandler( + rb3Handler, + mMRBLength, + ribbonMode, + PRICE_CLOSE); + if (!result) + { + return result; + } + + // + // RIBBON 4 ... + // Median ... + result = InitMaHandler( + rb4Handler, + mMRBLength, + ribbonMode, + PRICE_MEDIAN); + if (!result) + { + return result; + } + + // + // RIBBON 5 ... + // Typical ... + result = InitMaHandler( + rb5Handler, + mMRBLength, + ribbonMode, + PRICE_TYPICAL); + if (!result) + { + return result; + } + + // + // RIBBON 6 ... + // Low ... + result = InitMaHandler( + rb6Handler, + mMRBLength, + ribbonMode, + PRICE_LOW); + + // + return result; +} + +// +bool InitSSLChannel() +{ + // + bool result = false; + + // + if (mSSLCLength <= 0) + { + return result; + } + + // + // SSLUP ... + result = InitMaHandler( + sslcUpHandler, + mSSLCLength, + sslcMode, + sslcUpAppliedTo); + if (!result) + { + return result; + } + + // + // SSLDOWN ... + result = InitMaHandler( + sslcDownHandler, + mSSLCLength, + sslcMode, + sslcDownAppliedTo); + + // + return result; +} + +// +bool InitHullTrend() +{ + // + bool result = false; + + // + if (mHULLLength <= 0) + { + return result; + } + + // + mUpZHull = new XSCHull(); + mUpZHull.Init( + mHULLLength, + hullDivisor); + + // + mDownZHull = new XSCHull(); + mDownZHull.Init( + mHULLLength, + hullDivisor); + + // + result = true; + + // + return result; +} + +// +// Define Indexes and Styles ... +void DefineBuffers() +{ + // + // RANGE ... + + // + // 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(sHHBuffer, true); + SetIndexBuffer(sHHBufferIndex, sHHBuffer, INDICATOR_DATA); + + // + PlotIndexSetInteger(sHHBufferPlotIndex, PLOT_DRAW_BEGIN, maxLength); + PlotIndexSetInteger(sHHBufferPlotIndex, PLOT_SHOW_DATA, showLevels); + + // + ArraySetAsSeries(sHHColorBuffer, true); + SetIndexBuffer(sHHColorBufferIndex, sHHColorBuffer, INDICATOR_COLOR_INDEX); + + // + // LOW ... + ArraySetAsSeries(sLLBuffer, true); + SetIndexBuffer(sLLBufferIndex, sLLBuffer, INDICATOR_DATA); + + // + PlotIndexSetInteger(sLLBufferPlotIndex, PLOT_DRAW_BEGIN, maxLength); + PlotIndexSetInteger(sLLBufferPlotIndex, PLOT_SHOW_DATA, showLevels); + + // + ArraySetAsSeries(sLLColorBuffer, true); + SetIndexBuffer(sLLColorBufferIndex, sLLColorBuffer, INDICATOR_COLOR_INDEX); + + // + // MEDIUM Buffer ... + + // + // HIGH ... + ArraySetAsSeries(mHHBuffer, true); + SetIndexBuffer(mHHBufferIndex, mHHBuffer, INDICATOR_DATA); + + // + PlotIndexSetInteger(mHHBufferPlotIndex, PLOT_DRAW_BEGIN, maxLength); + PlotIndexSetInteger(mHHBufferPlotIndex, PLOT_SHOW_DATA, showLevels); + + // + ArraySetAsSeries(mHHColorBuffer, true); + SetIndexBuffer(mHHColorBufferIndex, mHHColorBuffer, INDICATOR_COLOR_INDEX); + + // + // LOW ... + ArraySetAsSeries(mLLBuffer, true); + SetIndexBuffer(mLLBufferIndex, mLLBuffer, INDICATOR_DATA); + + // + PlotIndexSetInteger(mLLBufferPlotIndex, PLOT_DRAW_BEGIN, maxLength); + PlotIndexSetInteger(mLLBufferPlotIndex, PLOT_SHOW_DATA, showLevels); + + // + ArraySetAsSeries(mLLColorBuffer, true); + SetIndexBuffer(mLLColorBufferIndex, mLLColorBuffer, INDICATOR_COLOR_INDEX); + + // + // LONG Buffer ... + + // + // HIGH ... + ArraySetAsSeries(lHHBuffer, true); + SetIndexBuffer(lHHBufferIndex, lHHBuffer, INDICATOR_DATA); + + // + PlotIndexSetInteger(lHHBufferPlotIndex, PLOT_DRAW_BEGIN, maxLength); + PlotIndexSetInteger(lHHBufferPlotIndex, PLOT_SHOW_DATA, showLevels); + + // + ArraySetAsSeries(lHHColorBuffer, true); + SetIndexBuffer(lHHColorBufferIndex, lHHColorBuffer, INDICATOR_COLOR_INDEX); + + // + // LOW ... + ArraySetAsSeries(lLLBuffer, true); + SetIndexBuffer(lLLBufferIndex, lLLBuffer, INDICATOR_DATA); + + // + PlotIndexSetInteger(lLLBufferPlotIndex, PLOT_DRAW_BEGIN, maxLength); + PlotIndexSetInteger(lLLBufferPlotIndex, PLOT_SHOW_DATA, showLevels); + + // + ArraySetAsSeries(lLLColorBuffer, true); + SetIndexBuffer(lLLColorBufferIndex, lLLColorBuffer, INDICATOR_COLOR_INDEX); + + // + // HIND Buffer ... + + // + // HIGH ... + ArraySetAsSeries(hHHBuffer, true); + SetIndexBuffer(hHHBufferIndex, hHHBuffer, INDICATOR_DATA); + + // + PlotIndexSetInteger(hHHBufferPlotIndex, PLOT_DRAW_BEGIN, maxLength); + PlotIndexSetInteger(hHHBufferPlotIndex, PLOT_SHOW_DATA, showLevels); + + // + ArraySetAsSeries(hHHColorBuffer, true); + SetIndexBuffer(hHHColorBufferIndex, hHHColorBuffer, INDICATOR_COLOR_INDEX); + + // + // LOW ... + ArraySetAsSeries(hLLBuffer, true); + SetIndexBuffer(hLLBufferIndex, hLLBuffer, INDICATOR_DATA); + + // + PlotIndexSetInteger(hLLBufferPlotIndex, PLOT_DRAW_BEGIN, maxLength); + PlotIndexSetInteger(hLLBufferPlotIndex, PLOT_SHOW_DATA, showLevels); + + // + ArraySetAsSeries(hLLColorBuffer, true); + SetIndexBuffer(hLLColorBufferIndex, hLLColorBuffer, INDICATOR_COLOR_INDEX); + + // + // XSTR ... + + // + // FILLINGS ... + SetIndexBuffer(fillUpBufferIndex, fillUpBuffer, INDICATOR_DATA); + SetIndexBuffer(fillDownBufferIndex, fillDownBuffer, INDICATOR_DATA); + PlotIndexSetInteger(fillingBufferPlotIndex, PLOT_SHOW_DATA, false); + + // + // MAIN ... + SetIndexBuffer(trendBufferIndex, trendBuffer, INDICATOR_DATA); + PlotIndexSetInteger(trendBufferPlotIndex, PLOT_SHOW_DATA, showTrends); + SetIndexBuffer(trendColorBufferIndex, trendColorBuffer, INDICATOR_COLOR_INDEX); + + // + // RIBBON 1 ... + + // + ArraySetAsSeries(ribbon1Buffer, true); + SetIndexBuffer(ribbon1BufferIndex, ribbon1Buffer, INDICATOR_DATA); + + // + PlotIndexSetInteger(ribbon1BufferPlotIndex, PLOT_DRAW_BEGIN, maxLength); + PlotIndexSetInteger(ribbon1BufferPlotIndex, PLOT_SHOW_DATA, showRibbons); + + // + ArraySetAsSeries(ribbon1ColorBuffer, true); + SetIndexBuffer(ribbon1ColorBufferIndex, ribbon1ColorBuffer, INDICATOR_COLOR_INDEX); + + // + // RIBBON 2 ... + + // + ArraySetAsSeries(ribbon2Buffer, true); + SetIndexBuffer(ribbon2BufferIndex, ribbon2Buffer, INDICATOR_DATA); + + // + PlotIndexSetInteger(ribbon2BufferPlotIndex, PLOT_DRAW_BEGIN, maxLength); + PlotIndexSetInteger(ribbon2BufferPlotIndex, PLOT_SHOW_DATA, showRibbons); + + // + ArraySetAsSeries(ribbon2ColorBuffer, true); + SetIndexBuffer(ribbon2ColorBufferIndex, ribbon2ColorBuffer, INDICATOR_COLOR_INDEX); + + // + // RIBBON 3 ... + + // + ArraySetAsSeries(ribbon3Buffer, true); + SetIndexBuffer(ribbon3BufferIndex, ribbon3Buffer, INDICATOR_DATA); + + // + PlotIndexSetInteger(ribbon3BufferPlotIndex, PLOT_DRAW_BEGIN, maxLength); + PlotIndexSetInteger(ribbon3BufferPlotIndex, PLOT_SHOW_DATA, showRibbons); + + // + ArraySetAsSeries(ribbon3ColorBuffer, true); + SetIndexBuffer(ribbon3ColorBufferIndex, ribbon3ColorBuffer, INDICATOR_COLOR_INDEX); + + // + // RIBBON 4 ... + + // + ArraySetAsSeries(ribbon4Buffer, true); + SetIndexBuffer(ribbon4BufferIndex, ribbon4Buffer, INDICATOR_DATA); + + // + PlotIndexSetInteger(ribbon4BufferPlotIndex, PLOT_DRAW_BEGIN, maxLength); + PlotIndexSetInteger(ribbon4BufferPlotIndex, PLOT_SHOW_DATA, showRibbons); + + // + ArraySetAsSeries(ribbon4ColorBuffer, true); + SetIndexBuffer(ribbon4ColorBufferIndex, ribbon4ColorBuffer, INDICATOR_COLOR_INDEX); + + // + // RIBBON 5 ... + + // + ArraySetAsSeries(ribbon5Buffer, true); + SetIndexBuffer(ribbon5BufferIndex, ribbon5Buffer, INDICATOR_DATA); + + // + PlotIndexSetInteger(ribbon5BufferPlotIndex, PLOT_DRAW_BEGIN, maxLength); + PlotIndexSetInteger(ribbon5BufferPlotIndex, PLOT_SHOW_DATA, showRibbons); + + // + ArraySetAsSeries(ribbon5ColorBuffer, true); + SetIndexBuffer(ribbon5ColorBufferIndex, ribbon5ColorBuffer, INDICATOR_COLOR_INDEX); + + // + // RIBBON 6 ... + + // + ArraySetAsSeries(ribbon6Buffer, true); + SetIndexBuffer(ribbon6BufferIndex, ribbon6Buffer, INDICATOR_DATA); + + // + PlotIndexSetInteger(ribbon6BufferPlotIndex, PLOT_DRAW_BEGIN, maxLength); + PlotIndexSetInteger(ribbon6BufferPlotIndex, PLOT_SHOW_DATA, showRibbons); + + // + ArraySetAsSeries(ribbon6ColorBuffer, true); + SetIndexBuffer(ribbon6ColorBufferIndex, ribbon6ColorBuffer, INDICATOR_COLOR_INDEX); + + // + // XSSLC ... + + // + // UP ... + + // + ArraySetAsSeries(sslcUpBuffer, true); + SetIndexBuffer(sslcUpBufferIndex, sslcUpBuffer, INDICATOR_DATA); + + // + PlotIndexSetInteger(sslcUpBufferPlotIndex, PLOT_DRAW_BEGIN, maxLength); + PlotIndexSetInteger(sslcUpBufferPlotIndex, PLOT_SHOW_DATA, showSSLChannel); + + // + ArraySetAsSeries(sslcUpColorBuffer, true); + SetIndexBuffer(sslcUpColorBufferIndex, sslcUpColorBuffer, INDICATOR_COLOR_INDEX); + + // + // DOWN ... + + // + ArraySetAsSeries(sslcDownBuffer, true); + SetIndexBuffer(sslcDownBufferIndex, sslcDownBuffer, INDICATOR_DATA); + + // + PlotIndexSetInteger(sslcDownBufferPlotIndex, PLOT_DRAW_BEGIN, maxLength); + PlotIndexSetInteger(sslcDownBufferPlotIndex, PLOT_SHOW_DATA, showSSLChannel); + + // + ArraySetAsSeries(sslcDownColorBuffer, true); + SetIndexBuffer(sslcDownColorBufferIndex, sslcDownColorBuffer, INDICATOR_COLOR_INDEX); + + // + // XHULL ... + + // + // UP ... + + // + SetIndexBuffer(hullUpZoneBufferIndex, hullUpZoneBuffer, INDICATOR_DATA); + + // + PlotIndexSetInteger(hullUpZoneBufferPlotIndex, PLOT_DRAW_BEGIN, maxLength); + PlotIndexSetInteger(hullUpZoneBufferPlotIndex, PLOT_SHOW_DATA, showHull); + + // + SetIndexBuffer(hullUpZoneColorBufferIndex, hullUpZoneColorBuffer, INDICATOR_COLOR_INDEX); + + // + // DOWN ... + + // + SetIndexBuffer(hullDownZoneBufferIndex, hullDownZoneBuffer, INDICATOR_DATA); + + // + PlotIndexSetInteger(hullDownZoneBufferPlotIndex, PLOT_DRAW_BEGIN, maxLength); + PlotIndexSetInteger(hullDownZoneBufferPlotIndex, PLOT_SHOW_DATA, showHull); + + // + SetIndexBuffer(hullDownZoneColorBufferIndex, hullDownZoneColorBuffer, INDICATOR_COLOR_INDEX); + + // + // XHK ... + + // + // Candles Color ... + ArraySetAsSeries(hkCandleColorBuffer, true); + SetIndexBuffer(hkCandleColorBufferIndex, hkCandleColorBuffer, INDICATOR_COLOR_INDEX); + + // + // Set EMPTY_VALUE on Candles Buffer ... + PlotIndexSetDouble(hkCandlesBufferIndex, PLOT_EMPTY_VALUE, 0.0); + + // + PlotIndexSetInteger(hkCandlesBufferIndex, PLOT_SHOW_DATA, false); + PlotIndexSetInteger(hkCandleColorBufferIndex, PLOT_SHOW_DATA, false); + + // + // Open ... + ArraySetAsSeries(hkOpenBuffer, true); + PlotIndexSetInteger(hkOpenBufferIndex, PLOT_SHOW_DATA, false); + SetIndexBuffer(hkOpenBufferIndex, hkOpenBuffer, INDICATOR_DATA); + + // + // High ... + ArraySetAsSeries(hkHighBuffer, true); + SetIndexBuffer(hkHighBufferIndex, hkHighBuffer, INDICATOR_DATA); + PlotIndexSetInteger(hkHighBufferIndex, PLOT_SHOW_DATA, false); + + // + // Close ... + ArraySetAsSeries(hkCloseBuffer, true); + SetIndexBuffer(hkCloseBufferIndex, hkCloseBuffer, INDICATOR_DATA); + PlotIndexSetInteger(hkCloseBufferIndex, PLOT_SHOW_DATA, false); + + // + // Low ... + ArraySetAsSeries(hkLowBuffer, true); + SetIndexBuffer(hkLowBufferIndex, hkLowBuffer, INDICATOR_DATA); + PlotIndexSetInteger(hkLowBufferIndex, PLOT_SHOW_DATA, false); + + // + // XSMHK ... + + // + // Candles Color ... + ArraySetAsSeries(smhkCandleColorBuffer, true); + SetIndexBuffer(smhkCandleColorBufferIndex, smhkCandleColorBuffer, INDICATOR_COLOR_INDEX); + + // + // Set EMPTY_VALUE on Candles Buffer ... + PlotIndexSetDouble(smhkCandlesBufferIndex, PLOT_EMPTY_VALUE, 0.0); + + // + PlotIndexSetInteger(smhkCandlesBufferIndex, PLOT_SHOW_DATA, false); + PlotIndexSetInteger(smhkCandleColorBufferIndex, PLOT_SHOW_DATA, false); + + // + // Open ... + ArraySetAsSeries(smhkOpenBuffer, true); + PlotIndexSetInteger(smhkOpenBufferIndex, PLOT_SHOW_DATA, false); + SetIndexBuffer(smhkOpenBufferIndex, smhkOpenBuffer, INDICATOR_DATA); + + // + // High ... + ArraySetAsSeries(smhkHighBuffer, true); + SetIndexBuffer(smhkHighBufferIndex, smhkHighBuffer, INDICATOR_DATA); + PlotIndexSetInteger(smhkHighBufferIndex, PLOT_SHOW_DATA, false); + + // + // Close ... + ArraySetAsSeries(smhkCloseBuffer, true); + SetIndexBuffer(smhkCloseBufferIndex, smhkCloseBuffer, INDICATOR_DATA); + PlotIndexSetInteger(smhkCloseBufferIndex, PLOT_SHOW_DATA, false); + + // + // Low ... + ArraySetAsSeries(smhkLowBuffer, true); + SetIndexBuffer(smhkLowBufferIndex, smhkLowBuffer, INDICATOR_DATA); + PlotIndexSetInteger(smhkLowBufferIndex, PLOT_SHOW_DATA, false); + + // + // DATA Buffers ... + + // + // ATR ... + SetIndexBuffer(atrBufferIndex, atrBuffer, INDICATOR_CALCULATIONS); + + // + // TREND ... + SetIndexBuffer(trendStateBufferIndex, trendStateBuffer, INDICATOR_CALCULATIONS); + + // + // UP ... + SetIndexBuffer(upBufferIndex, upBuffer, INDICATOR_CALCULATIONS); + + // + // DOWN ... + SetIndexBuffer(downBufferIndex, downBuffer, INDICATOR_CALCULATIONS); + + // + // PRICE ... + SetIndexBuffer(priceBufferIndex, priceBuffer, INDICATOR_CALCULATIONS); + + // + // SSLCDOWNMA ... + ArraySetAsSeries(sslcUpMaBuffer, true); + SetIndexBuffer(sslcUpMaBufferIndex, sslcUpMaBuffer, INDICATOR_CALCULATIONS); + + // + // SSLCUPMA ... + ArraySetAsSeries(sslcDownMaBuffer, true); + SetIndexBuffer(sslcDownMaBufferIndex, sslcDownMaBuffer, INDICATOR_CALCULATIONS); + + // + // SSLCKPI ... + ArraySetAsSeries(sslcKpiBuffer, true); + SetIndexBuffer(sslcKpiBufferIndex, sslcKpiBuffer, INDICATOR_CALCULATIONS); + + // + // STATE Buffers ... + + // + // PEAKS ... + ArraySetAsSeries(peaksStateBuffer, true); + SetIndexBuffer(peaksStateBufferIndex, peaksStateBuffer, INDICATOR_CALCULATIONS); + + // + // VALES ... + ArraySetAsSeries(valesStateBuffer, true); + SetIndexBuffer(valesStateBufferIndex, valesStateBuffer, INDICATOR_CALCULATIONS); + + // + // CYCLES ... + + // + // SHORT ... + + // + ArraySetAsSeries(sHHStateBuffer, true); + SetIndexBuffer(sHHStateBufferIndex, sHHStateBuffer, INDICATOR_CALCULATIONS); + + // + ArraySetAsSeries(sLLStateBuffer, true); + SetIndexBuffer(sLLStateBufferIndex, sLLStateBuffer, INDICATOR_CALCULATIONS); + + // + // MEDIUM ... + + // + ArraySetAsSeries(mHHStateBuffer, true); + SetIndexBuffer(mHHStateBufferIndex, mHHStateBuffer, INDICATOR_CALCULATIONS); + + // + ArraySetAsSeries(mLLStateBuffer, true); + SetIndexBuffer(mLLStateBufferIndex, mLLStateBuffer, INDICATOR_CALCULATIONS); + + // + // LONG ... + + // + ArraySetAsSeries(lHHStateBuffer, true); + SetIndexBuffer(lHHStateBufferIndex, lHHStateBuffer, INDICATOR_CALCULATIONS); + + // + ArraySetAsSeries(lLLStateBuffer, true); + SetIndexBuffer(lLLStateBufferIndex, lLLStateBuffer, INDICATOR_CALCULATIONS); + + // + // HIND ... + + // + ArraySetAsSeries(hHHStateBuffer, true); + SetIndexBuffer(hHHStateBufferIndex, hHHStateBuffer, INDICATOR_CALCULATIONS); + + // + ArraySetAsSeries(hLLStateBuffer, true); + SetIndexBuffer(hLLStateBufferIndex, hLLStateBuffer, INDICATOR_CALCULATIONS); + + // + // XSTR ... + SetIndexBuffer(strTrendStateBufferIndex, strTrendStateBuffer, INDICATOR_CALCULATIONS); + + // + // XMBR ... + + // + // RIBBON 1 _ (High) ... + ArraySetAsSeries(rb1StateBuffer, true); + SetIndexBuffer(rb1StateBufferIndex, rb1StateBuffer, INDICATOR_CALCULATIONS); + + // + // RIBBON 2 _ (Open) ... + ArraySetAsSeries(rb2StateBuffer, true); + SetIndexBuffer(rb2StateBufferIndex, rb2StateBuffer, INDICATOR_CALCULATIONS); + + // + // RIBBON 3 _ (Close) ... + ArraySetAsSeries(rb3StateBuffer, true); + SetIndexBuffer(rb3StateBufferIndex, rb3StateBuffer, INDICATOR_CALCULATIONS); + + // + // RIBBON 4 _ (Median) ... + ArraySetAsSeries(rb4StateBuffer, true); + SetIndexBuffer(rb4StateBufferIndex, rb4StateBuffer, INDICATOR_CALCULATIONS); + + // + // RIBBON 5 _ (Typical) ... + ArraySetAsSeries(rb5StateBuffer, true); + SetIndexBuffer(rb5StateBufferIndex, rb5StateBuffer, INDICATOR_CALCULATIONS); + + // + // RIBBON 6 _ (Low) ... + ArraySetAsSeries(rb6StateBuffer, true); + SetIndexBuffer(rb6StateBufferIndex, rb6StateBuffer, INDICATOR_CALCULATIONS); + + // + // XHULL ... + + // + // UP Zone ... + SetIndexBuffer(hullUpStateBufferIndex, hullUpStateBuffer, INDICATOR_CALCULATIONS); + + // + // DOWN Zone ... + SetIndexBuffer(hullDownStateBufferIndex, hullDownStateBuffer, INDICATOR_CALCULATIONS); + + // + // XHK ... + + // + ArraySetAsSeries(hkStateBuffer, true); + SetIndexBuffer(hkStateBufferIndex, hkStateBuffer, 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 +) +{ + // + // Calculate ... + + // + // Calculate Short Cycle ... + CalculateShortCycle(bar_index); + + // + // Calculate Medium Cycle ... + CalculateMediumCycle(bar_index); + + // + // Calculate Long Cycle ... + CalculateLongCycle(bar_index); + + // + // Calculate Hind Cycle ... + CalculateHindCycle(bar_index); + + // + // Calculate Peaks and Vales ... + CalculatePeaksAndVales(bar_index); + + // + // Calculate Fibonnaci ... + CalculateFibonacci(bar_index); +} + +// +// START Calculation Parts ... +// + +// +// SHORT Cycle ... +void CalculateShortCycle( + int bar_index // Selected Bar Index +) +{ + // + ENUM_TIMEFRAMES mPeriod = mL1Period; + + // + double hhValue = GetCycleHHC( + bar_index, + mPeriod); + + // + double llValue = GetCycleLLC( + bar_index, + mPeriod); + + // + double lastHH = mLastSHH; + double lastLL = mLastSLL; + + // + double mHHState = EMPTY_VALUE; + double mhhColorIDX = mHideColorIDX; + if (showLevels) + { + // + if (hhValue == lastHH) + { + mhhColorIDX = showConsolidations ? 1 : mHideColorIDX; + } + else if (hhValue > lastHH) + { + mhhColorIDX = 2; + } + else if (hhValue < lastHH) + { + mhhColorIDX = 3; + } + + // + mHHState = mhhColorIDX; + } + else + { + mhhColorIDX = mHideColorIDX; + } + + // + double mLLState = EMPTY_VALUE; + double mllColorIDX = mHideColorIDX; + if (showLevels) + { + // + if (llValue == lastLL) + { + mllColorIDX = showConsolidations ? 1 : mHideColorIDX; + } + else if (llValue > lastLL) + { + mllColorIDX = 2; + } + else if (llValue < lastLL) + { + mllColorIDX = 3; + } + + // + mLLState = mllColorIDX; + } + else + { + mllColorIDX = mHideColorIDX; + } + + // + mLastSHH = hhValue; + mLastSLL = llValue; + + // + sHHBuffer[bar_index] = hhValue; + sLLBuffer[bar_index] = llValue; + sHHStateBuffer[bar_index] = mHHState; + sLLStateBuffer[bar_index] = mLLState; + sHHColorBuffer[bar_index] = mhhColorIDX; + sLLColorBuffer[bar_index] = mllColorIDX; +} + +// +// MEDIUM Cycle ... +void CalculateMediumCycle( + int bar_index // Selected Bar Index +) +{ + // + ENUM_TIMEFRAMES mPeriod = mL2Period; + + // + double hhValue = GetCycleHHC( + bar_index, + mPeriod); + + // + double llValue = GetCycleLLC( + bar_index, + mPeriod); + + // + double lastHH = mLastMHH; + double lastLL = mLastMLL; + + // + double mHHState = EMPTY_VALUE; + double mhhColorIDX = mHideColorIDX; + if (showLevels) + { + // + if (hhValue == lastHH) + { + mhhColorIDX = showConsolidations ? 1 : mHideColorIDX; + } + else if (hhValue > lastHH) + { + mhhColorIDX = 2; + } + else if (hhValue < lastHH) + { + mhhColorIDX = 3; + } + + // + mHHState = mhhColorIDX; + } + else + { + mhhColorIDX = mHideColorIDX; + } + + // + double mLLState = EMPTY_VALUE; + double mllColorIDX = mHideColorIDX; + if (showLevels) + { + // + if (llValue == lastLL) + { + mllColorIDX = showConsolidations ? 1 : mHideColorIDX; + } + else if (llValue > lastLL) + { + mllColorIDX = 2; + } + else if (llValue < lastLL) + { + mllColorIDX = 3; + } + + // + mLLState = mllColorIDX; + } + else + { + mllColorIDX = mHideColorIDX; + } + + // + mLastMHH = hhValue; + mLastMLL = llValue; + + // + mHHBuffer[bar_index] = hhValue; + mLLBuffer[bar_index] = llValue; + mHHStateBuffer[bar_index] = mHHState; + mLLStateBuffer[bar_index] = mLLState; + mHHColorBuffer[bar_index] = mhhColorIDX; + mLLColorBuffer[bar_index] = mllColorIDX; +} + +// +// LONG Cycle ... +void CalculateLongCycle( + int bar_index // Selected Bar Index +) +{ + // + ENUM_TIMEFRAMES mPeriod = mL3Period; + + // + double hhValue = GetCycleHHC( + bar_index, + mPeriod); + + // + double llValue = GetCycleLLC( + bar_index, + mPeriod); + + // + double lastHH = mLastLHH; + double lastLL = mLastLLL; + + // + double mHHState = EMPTY_VALUE; + double mhhColorIDX = mHideColorIDX; + if (showLevels) + { + // + if (hhValue == lastHH) + { + mhhColorIDX = showConsolidations ? 1 : mHideColorIDX; + } + else if (hhValue > lastHH) + { + mhhColorIDX = 2; + } + else if (hhValue < lastHH) + { + mhhColorIDX = 3; + } + + // + mHHState = mhhColorIDX; + } + else + { + mhhColorIDX = mHideColorIDX; + } + + // + double mLLState = EMPTY_VALUE; + double mllColorIDX = mHideColorIDX; + if (showLevels) + { + // + if (llValue == lastLL) + { + mllColorIDX = showConsolidations ? 1 : mHideColorIDX; + } + else if (llValue > lastLL) + { + mllColorIDX = 2; + } + else if (llValue < lastLL) + { + mllColorIDX = 3; + } + + // + mLLState = mllColorIDX; + } + else + { + mllColorIDX = mHideColorIDX; + } + + // + mLastLHH = hhValue; + mLastLLL = llValue; + + // + lHHBuffer[bar_index] = hhValue; + lLLBuffer[bar_index] = llValue; + lHHStateBuffer[bar_index] = mHHState; + lLLStateBuffer[bar_index] = mLLState; + lHHColorBuffer[bar_index] = mhhColorIDX; + lLLColorBuffer[bar_index] = mllColorIDX; +} + +// +// HIND Cycle ... +void CalculateHindCycle( + int bar_index // Selected Bar Index +) +{ + // + ENUM_TIMEFRAMES mPeriod = mL4Period; + + // + double hhValue = GetCycleHHC( + bar_index, + mPeriod); + + // + double llValue = GetCycleLLC( + bar_index, + mPeriod); + + // + double lastHH = mLastHHH; + double lastLL = mLastHLL; + + // + double mHHState = EMPTY_VALUE; + double mhhColorIDX = mHideColorIDX; + if (showLevels) + { + // + if (hhValue == lastHH) + { + mhhColorIDX = showConsolidations ? 1 : mHideColorIDX; + } + else if (hhValue > lastHH) + { + mhhColorIDX = 2; + } + else if (hhValue < lastHH) + { + mhhColorIDX = 3; + } + + // + mHHState = mhhColorIDX; + } + else + { + mhhColorIDX = mHideColorIDX; + } + + // + double mLLState = EMPTY_VALUE; + double mllColorIDX = mHideColorIDX; + if (showLevels) + { + // + if (llValue == lastLL) + { + mllColorIDX = showConsolidations ? 1 : mHideColorIDX; + } + else if (llValue > lastLL) + { + mllColorIDX = 2; + } + else if (llValue < lastLL) + { + mllColorIDX = 3; + } + + // + mLLState = mllColorIDX; + } + else + { + mllColorIDX = mHideColorIDX; + } + + // + mLastHHH = hhValue; + mLastHLL = llValue; + + // + hHHBuffer[bar_index] = hhValue; + hLLBuffer[bar_index] = llValue; + hHHStateBuffer[bar_index] = mHHState; + hLLStateBuffer[bar_index] = mLLState; + hHHColorBuffer[bar_index] = mhhColorIDX; + hLLColorBuffer[bar_index] = mllColorIDX; +} + +// +// Calculate Peaks and Values ... +void CalculatePeaksAndVales( + int bar_index // Bar Index +) +{ + // + // Retrieve Requirements ... + + // + // Short ... + double sHHValue = sHHBuffer[bar_index]; + double sLLValue = sLLBuffer[bar_index]; + + // + // Medium ... + double mHHValue = mHHBuffer[bar_index]; + double mLLValue = mLLBuffer[bar_index]; + + // + // Long ... + double lHHValue = lHHBuffer[bar_index]; + double lLLValue = lLLBuffer[bar_index]; + + // + // Hind ... + double hHHValue = hHHBuffer[bar_index]; + double hLLValue = hLLBuffer[bar_index]; + + // + double rColorIDX = mHideColorIDX; + double sColorIDX = mHideColorIDX; + + // + // RESISTANCE ... + double rValue = (sHHValue + mHHValue + lHHValue + hHHValue) / 4; + + // + // PEAKS ... + bool isPeak = rValue == hHHValue && + hHHValue == lHHValue && + lHHValue == mHHValue && + mHHValue == sHHValue; + + // + if (isPeak && lastPeak != rValue) + { + // + rColorIDX = 1; + lastPeak = rValue; + peaksStateBuffer[bar_index] = rColorIDX; + } + else + { + peaksStateBuffer[bar_index] = EMPTY_VALUE; + } + + // + // SUPPORT ... + double sValue = (sLLValue + mLLValue + lLLValue + hLLValue) / 4; + + // + // VALES ... + bool isVale = sValue == hLLValue && + hLLValue == lLLValue && + lLLValue == mLLValue && + mLLValue == sLLValue; + + // + if (isVale && lastVale != sValue) + { + // + sColorIDX = 1; + lastVale = sValue; + valesStateBuffer[bar_index] = sColorIDX; + } + else + { + valesStateBuffer[bar_index] = EMPTY_VALUE; + } + + // + rBuffer[bar_index] = rValue; + sBuffer[bar_index] = sValue; + peaksBuffer[bar_index] = lastPeak; + valesBuffer[bar_index] = lastVale; + + // + if (showPeaksAndVales) + { + // + rColorBuffer[bar_index] = rColorIDX; + sColorBuffer[bar_index] = sColorIDX; + } + else + { + // + rColorBuffer[bar_index] = mHideColorIDX; + sColorBuffer[bar_index] = mHideColorIDX; + } +} + +// +// Calculate Fibonacci Level 1 ... +void CalculateFibonacci( + int bar_index // Bar Index +) +{ + // + // Select Requirements ... + double upPrice = peaksBuffer[bar_index]; + double downPrice = valesBuffer[bar_index]; + + // + // 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[bar_index] = fibLevel1Value; + fl2Buffer[bar_index] = fibLevel2Value; + fl3Buffer[bar_index] = fibLevel3Value; + fl4Buffer[bar_index] = fibLevel4Value; + fl5Buffer[bar_index] = 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[bar_index] = fl1ColorIdx; + fl2ColorBuffer[bar_index] = fl2ColorIdx; + fl3ColorBuffer[bar_index] = fl3ColorIdx; + fl4ColorBuffer[bar_index] = fl4ColorIdx; + fl5ColorBuffer[bar_index] = fl5ColorIdx; +} + +// +// XSTR ... +bool CalculateXSTR( + const int rates_total, + const int prev_calculated, + const double &open[], + const double &high[], + const double &low[], + const double &close[] // +) +{ + // + bool result = false; + + // + 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 result; + } + + // + // Check Number of items Copy or not ... + int copiedATRs = CopyBuffer(atrHandler, 0, 0, numOfRequiredAtrs, atrBuffer); + if (copiedATRs <= 0) + { + return result; + } + + // + // + 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 = GetAppliedPrice( + trendPriceAppliedTo, + open, + high, + low, + close, + i); + // price = (high[i] + low[i]) / 2; + priceBuffer[i] = price; + + // + double atr = atrBuffer[i]; + + // + // Up ... + upBuffer[i] = price + (trendMultiplier * atr); + + // + // Down ... + downBuffer[i] = price - (trendMultiplier * atr); + + // + if (close[i] > upBuffer[i - 1]) + { + // + trendStateBuffer[i] = 1; + if (trendStateBuffer[i - 1] == -1) + { + changeOfTrend = 1; + } + } + else if (close[i] < downBuffer[i - 1]) + { + // + trendStateBuffer[i] = -1; + if (trendStateBuffer[i - 1] == 1) + { + changeOfTrend = 1; + } + } + else if (trendStateBuffer[i - 1] == 1) + { + // + trendStateBuffer[i] = 1; + changeOfTrend = 0; + } + else if (trendStateBuffer[i - 1] == -1) + { + // + trendStateBuffer[i] = -1; + changeOfTrend = 0; + } + + // + // Down Trend Starting ... + if (trendStateBuffer[i] < 0 && trendStateBuffer[i - 1] > 0) + { + startBearishTrend = 1; + } + else + { + startBearishTrend = 0; + } + + // + // Up Trend Starting ... + if (trendStateBuffer[i] > 0 && trendStateBuffer[i - 1] < 0) + { + startBullishTrend = 1; + } + else + { + startBullishTrend = 0; + } + + // + if (trendStateBuffer[i] > 0 && downBuffer[i] < downBuffer[i - 1]) + { + downBuffer[i] = downBuffer[i - 1]; + } + + // + if (trendStateBuffer[i] < 0 && upBuffer[i] > upBuffer[i - 1]) + { + upBuffer[i] = upBuffer[i - 1]; + } + + // + if (startBearishTrend == 1) + { + upBuffer[i] = priceBuffer[i] + (trendMultiplier * atr); + } + + // + if (startBullishTrend == 1) + { + downBuffer[i] = priceBuffer[i] - (trendMultiplier * atr); + } + + // + // Draw the indicator ... + + // + double colorIDX = 0; + double state = EMPTY_VALUE; + trendColorBuffer[i] = colorIDX; + + // + if (trendStateBuffer[i] == 1) + { + // + trendBuffer[i] = downBuffer[i]; + if (changeOfTrend == 1) + { + // + trendBuffer[i - 1] = trendBuffer[i - 2]; + changeOfTrend = 0; + + // + state = 2; + } + + // + colorIDX = 1; + } + else if (trendStateBuffer[i] == -1) + { + // + trendBuffer[i] = upBuffer[i]; + if (changeOfTrend == 1) + { + // + trendBuffer[i - 1] = trendBuffer[i - 2]; + changeOfTrend = 0; + + // + state = 3; + } + + // + colorIDX = 2; + } + + // + if (showTrends) + { + trendColorBuffer[i] = colorIDX; + } + strTrendStateBuffer[i] = state; + + // + // Filling ... + if (fillTrends) + { + // + fillUpBuffer[i] = trendBuffer[i]; + fillDownBuffer[i] = close[i]; + } + else + { + // + fillUpBuffer[i] = EMPTY_VALUE; + fillDownBuffer[i] = EMPTY_VALUE; + } + } + + // + result = true; + + // + return true; +} + +// +XMRBColorInfo GetRibbonColorIndex( + double value, + const double h, + const double l // +) +{ + // + XMRBColorInfo result; + + // + result.state = EMPTY_VALUE; + result.clr = mHideColorIDX; + + // + // Color Indexes ... + // 0 => HIDE + // 1 => NEUTURAL + // 2 => BULLISH + // 3 => BEARISH + + // + result.clr = 1; + + // + if (value < l && value < h) + { + result.clr = 2; + } + else if (value > h && value > l) + { + result.clr = 3; + } + else if (value < h && value > l) + { + result.clr = 1; + } + + // + result.state = result.clr; + + // + if (!showRibbons) + { + result.clr = mHideColorIDX; + } + + // + return result; +} + +// +// Calculate Ribbons Color ... +void CalculateRibbonsColors( + int bar_index, // Bar Index + const double &high[], + const double &low[] // +) +{ + // + double tmpVal; + XMRBColorInfo tmpColorIDX; + + // + double h = high[bar_index]; + double l = low[bar_index]; + + // + // RIBBON 1 ... + tmpVal = ribbon1Buffer[bar_index]; + tmpColorIDX = GetRibbonColorIndex( + tmpVal, + h, + l); + rb1StateBuffer[bar_index] = tmpColorIDX.state; + ribbon1ColorBuffer[bar_index] = tmpColorIDX.clr; + + // + // RIBBON 2 ... + tmpVal = ribbon2Buffer[bar_index]; + tmpColorIDX = GetRibbonColorIndex( + tmpVal, + h, + l); + rb2StateBuffer[bar_index] = tmpColorIDX.state; + ribbon2ColorBuffer[bar_index] = tmpColorIDX.clr; + + // + // RIBBON 3 ... + tmpVal = ribbon3Buffer[bar_index]; + tmpColorIDX = GetRibbonColorIndex( + tmpVal, + h, + l); + rb3StateBuffer[bar_index] = tmpColorIDX.state; + ribbon3ColorBuffer[bar_index] = tmpColorIDX.clr; + + // + // RIBBON 4 ... + tmpVal = ribbon4Buffer[bar_index]; + tmpColorIDX = GetRibbonColorIndex( + tmpVal, + h, + l); + rb4StateBuffer[bar_index] = tmpColorIDX.state; + ribbon4ColorBuffer[bar_index] = tmpColorIDX.clr; + + // + // RIBBON 5 ... + tmpVal = ribbon5Buffer[bar_index]; + tmpColorIDX = GetRibbonColorIndex( + tmpVal, + h, + l); + rb5StateBuffer[bar_index] = tmpColorIDX.state; + ribbon5ColorBuffer[bar_index] = tmpColorIDX.clr; + + // + // RIBBON 6 ... + tmpVal = ribbon6Buffer[bar_index]; + tmpColorIDX = GetRibbonColorIndex( + tmpVal, + h, + l); + rb6StateBuffer[bar_index] = tmpColorIDX.state; + ribbon6ColorBuffer[bar_index] = tmpColorIDX.clr; +} + +// +// Calculate SSL Channel ... +void CalculateSSLC( + int bar_index, // Selected Bar Index + int limit, + int ratesTotal, + int prevCalculated, + const double &close[]) +{ + // + double upMaValue = sslcUpMaBuffer[bar_index]; + double downMaValue = sslcDownMaBuffer[bar_index]; + + // + double closeValue = close[bar_index]; + + // + double kpiValue; + if (closeValue > upMaValue) + { + kpiValue = 1; + } + else if (closeValue < downMaValue) + { + kpiValue = -1; + } + else + { + kpiValue = sslcKpiBuffer[bar_index + 1]; + } + + // + sslcKpiBuffer[bar_index] = kpiValue; + + // + double upValue = kpiValue < 0 ? downMaValue : upMaValue; + sslcUpBuffer[bar_index] = upValue; + + // + double downValue = kpiValue < 0 ? upMaValue : downMaValue; + sslcDownBuffer[bar_index] = downValue; + + // + if (showSSLChannel) + { + // + sslcUpColorBuffer[bar_index] = 1; + sslcDownColorBuffer[bar_index] = 1; + } + else + { + // + sslcUpColorBuffer[bar_index] = mHideColorIDX; + sslcDownColorBuffer[bar_index] = mHideColorIDX; + } +} + +// +// Calculate XHULL ... +void CalculateHull( + 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); + hullUpZoneBuffer[bar_index] = upValue; + double upColorIDX = (bar_index > 0) + ? (hullUpZoneBuffer[bar_index] > hullUpZoneBuffer[bar_index - 1]) + ? 2 + : (hullUpZoneBuffer[bar_index] < hullUpZoneBuffer[bar_index - 1]) + ? 3 + : hullUpZoneColorBuffer[bar_index - 1] + : 1; + + // + double downValue = mDownZHull.Calculate( + downPrice, + bar_index, + ratesTotal); + hullDownZoneBuffer[bar_index] = downValue; + double downColorIDX = (bar_index > 0) + ? (hullDownZoneBuffer[bar_index] > hullDownZoneBuffer[bar_index - 1]) + ? 2 + : (hullDownZoneBuffer[bar_index] < hullDownZoneBuffer[bar_index - 1]) + ? 3 + : hullDownZoneColorBuffer[bar_index - 1] + : 1; + + // + hullUpStateBuffer[bar_index] = upColorIDX == 0 ? 1 : upColorIDX; + hullDownStateBuffer[bar_index] = downColorIDX == 0 ? 1 : downColorIDX; + if (showHull) + { + // + hullUpZoneColorBuffer[bar_index] = upColorIDX; + hullDownZoneColorBuffer[bar_index] = downColorIDX; + } + else + { + // + hullUpZoneColorBuffer[bar_index] = mHideColorIDX; + hullDownZoneColorBuffer[bar_index] = mHideColorIDX; + } +} + +// +// Calculate HikenAshi Buffers ... +void CalculateHikenAshi( + 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 = hkOpenBuffer[bar_index + 1]; + mPrevHKCloseValue = hkCloseBuffer[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)); + + // + hkOpenBuffer[bar_index] = mHKOpenValue; + hkHighBuffer[bar_index] = mHKHighValue; + hkLowBuffer[bar_index] = mHKLowValue; + hkCloseBuffer[bar_index] = mHKCloseValue; + + // + double candleColorValue = + mHKOpenValue < mHKCloseValue ? 1 : 2; + + // + hkStateBuffer[bar_index] = candleColorValue + 1; + hkCandleColorBuffer[bar_index] = showHKCandles ? candleColorValue : 0; +} + +// +// Calculate Candle Timer ... +void CalculateCandleTimer() +{ + // + if (!showCandleTimer) + { + return; + } + + // + XCandleRemains remainTime; + GetCandleRemainsTime( + remainTime, + _Symbol, + _Period, + 0); + + // + string msg = ToString( + remainTime, + "", + "", + "", + "", + "", + ":", + 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; + + // + ObjectSetString(0, ShortName, OBJPROP_TEXT, objText); + ObjectSetInteger(0, ShortName, OBJPROP_FONTSIZE, 10); + ObjectSetString(0, ShortName, OBJPROP_FONT, "Courier"); + ObjectSetInteger(0, ShortName, OBJPROP_COLOR, candleTimerColor); +} + +// +// Calculate Smoothed Hiken Ashi Candles ... +void CalculateSMHK( + int ratesTotal, // Total Bars + int prevCalculated // Calculated Bars +) +{ + // + // Open ... + int calculatedSMHKOpens = ExponentialMAOnBuffer( + ratesTotal, + prevCalculated, + 0, + mHKSmoothingLength, + hkOpenBuffer, + smhkOpenBuffer); + + // + // High ... + int calculatedSMHKHighs = ExponentialMAOnBuffer( + ratesTotal, + prevCalculated, + 0, + mHKSmoothingLength, + hkHighBuffer, + smhkHighBuffer); + + // + // Low ... + int calculatedSMHKLows = ExponentialMAOnBuffer( + ratesTotal, + prevCalculated, + 0, + mHKSmoothingLength, + hkLowBuffer, + smhkLowBuffer); + + // + // Close ... + int calculatedSMHKCloses = ExponentialMAOnBuffer( + ratesTotal, + prevCalculated, + 0, + mHKSmoothingLength, + hkCloseBuffer, + smhkCloseBuffer); + + // + // 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 = + // + smhkOpenBuffer[i] > smhkCloseBuffer[i] + // + ; + + // + if (showSMHKCandles) + { + // + smhkCandleColorBuffer[i] = isBearish + ? 2 + : 1; + } + else + { + // + smhkCandleColorBuffer[i] = mHideColorIDX; + } + } +} + +// +// END Calculation Parts ... +// + +// +// START Utilities ... +// + +// +// Create Candle Timer ... +void CreateIndicatorObject() +{ + // + if (!showCandleTimer) + { + return; + } + + // + ObjectCreate(0, ShortName, OBJ_LABEL, 0, 0, 0); + ObjectSetInteger(0, ShortName, OBJPROP_CORNER, candleTimerCorner); + ObjectSetInteger(0, ShortName, OBJPROP_XDISTANCE, 10); + ObjectSetInteger(0, ShortName, OBJPROP_YDISTANCE, 2); + + // + ENUM_ANCHOR_POINT Anchor = ANCHOR_LEFT_UPPER; + switch (candleTimerCorner) + { + 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); +} + +// +bool InitMaHandler( + int &handler, + int length, + ENUM_X_MA_METHOD mode, + ENUM_APPLIED_PRICE appliedTo) +{ + // + bool result = false; + + // + if (length <= 0) + { + return result; + } + + // + bool genericMethod = false; + ENUM_MA_METHOD method = NULL; + if (mode == X_MA_AMA) + { + // + handler = iAMA( + _Symbol, + _Period, + length, + mMRBAMAFast, + mMRBAMASlow, + 0, + appliedTo); + } + else if (mode == X_MA_EMA) + { + // + method = MODE_EMA; + genericMethod = true; + } + else if (mode == X_MA_LWMA) + { + // + method = MODE_LWMA; + genericMethod = true; + } + else if (mode == X_MA_SMA) + { + // + method = MODE_SMA; + genericMethod = true; + } + else if (mode == X_MA_SMMA) + { + // + method = MODE_SMMA; + genericMethod = true; + } + + // + if (genericMethod && handler == INVALID_HANDLE) + { + // + handler = iMA( + _Symbol, + _Period, + length, + 0, + method, + appliedTo); + } + + // + result = handler != INVALID_HANDLE; + + // + return result; +} + +// +// Retrieve Cycles Highest High ... +double GetCycleHH( + int bar_index, // Bar Index + ENUM_TIMEFRAMES period // Period +) +{ + // + datetime mCycleStartAt = GetPeriodStartTime( + _Symbol, + period); + + // + int mStartCycleBarIndex = iBarShift( + _Symbol, + _Period, + mCycleStartAt, + false); + + // + int mCycleCount = MathAbs(mStartCycleBarIndex - bar_index); + if (mCycleCount < 1) + { + mCycleCount = 1; + } + + // + // HIGH ... + int hhIndex = iHighest( + _Symbol, + _Period, + hhMode, + mCycleCount, + bar_index); + double result = GetAppliedPrice( + hhIndex, + hhMode); + + // + return result; +} + +// +// Retrieve Cycles Lowest Low ... +double GetCycleLL( + int bar_index, // Bar Index + ENUM_TIMEFRAMES period // Period +) +{ + // + datetime mCycleStartAt = GetPeriodStartTime( + _Symbol, + period); + + // + int mStartCycleBarIndex = iBarShift( + _Symbol, + _Period, + mCycleStartAt, + false); + + // + int mCycleCount = MathAbs(mStartCycleBarIndex - bar_index); + if (mCycleCount < 1) + { + mCycleCount = 1; + } + + // + // LOW ... + int llIndex = iLowest( + _Symbol, + _Period, + llMode, + mCycleCount, + bar_index); + double result = GetAppliedPrice( + llIndex, + llMode); + + // + return result; +} + +// +// Retrieve Cycles Highest High ... +double GetCycleHHC( + int bar_index, // Bar Index + ENUM_TIMEFRAMES period // Period +) +{ + // + int mCycleCount = 0; + if (period == mL1Period) + { + mCycleCount = mL1Candles; + } + else if (period == mL2Period) + { + mCycleCount = mL2Candles; + } + else if (period == mL3Period) + { + mCycleCount = mL3Candles; + } + else if (period == mL4Period) + { + mCycleCount = mL4Candles; + } + + // + // HIGH ... + int hhIndex = iHighest( + _Symbol, + _Period, + hhMode, + mCycleCount, + bar_index); + double result = GetAppliedPrice( + hhIndex, + hhMode); + + // + return result; +} + +// +// Retrieve Cycles Lowest Low ... +double GetCycleLLC( + int bar_index, // Bar Index + ENUM_TIMEFRAMES period // Period +) +{ + // + int mCycleCount = 0; + if (period == mL1Period) + { + mCycleCount = mL1Candles; + } + else if (period == mL2Period) + { + mCycleCount = mL2Candles; + } + else if (period == mL3Period) + { + mCycleCount = mL3Candles; + } + else if (period == mL4Period) + { + mCycleCount = mL4Candles; + } + + // + // LOW ... + int llIndex = iLowest( + _Symbol, + _Period, + llMode, + mCycleCount, + bar_index); + double result = GetAppliedPrice( + llIndex, + llMode); + + // + return result; +} + +// +string GenerateCyclesRepresentation() +{ + // + string result = ""; + + // + result += "C1: " + ToString(mL1Period) + "\n"; + result += "C2: " + ToString(mL2Period) + "\n"; + result += "C3: " + ToString(mL3Period) + "\n"; + result += "C4: " + ToString(mL4Period); + + // + return result; +} + +// +// 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 = chartMode; + 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 Utilities ... +// + +// +// END Functions ... +// diff --git a/MQLTestWorkspace/X121/14030217/Libraries/x-saherelm.alert.lib.ex5 b/MQLTestWorkspace/X121/14030217/Libraries/x-saherelm.alert.lib.ex5 new file mode 100644 index 0000000..28d6972 Binary files /dev/null and b/MQLTestWorkspace/X121/14030217/Libraries/x-saherelm.alert.lib.ex5 differ diff --git a/MQLTestWorkspace/X121/14030217/Libraries/x-saherelm.alert.lib.mq5 b/MQLTestWorkspace/X121/14030217/Libraries/x-saherelm.alert.lib.mq5 new file mode 100644 index 0000000..429d830 --- /dev/null +++ b/MQLTestWorkspace/X121/14030217/Libraries/x-saherelm.alert.lib.mq5 @@ -0,0 +1,187 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Alert Library +// -------------------------------------- +// Name: XAlert +// Description: provides Alerts 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 + +// +// START Inputs ... +// +input group "Alerts"; +input bool enableAlerts = true; // Enable Alerts +input bool logAlerts = true; // Log Alerts +input bool terminalAlerts = false; // Terminal Alerts +input bool mailAlerts = false; // Mail Alerts +input bool pushAlerts = false; // Push Alerts +// +// END Inputs ... +// + +// +#include "x-saherelm.log.lib.mq5" + +// +// START Global Definitions: Variables, Properties and etc ... +// +string alertPrefix = "X-Alert"; +// +// END Global Definitions: Variables, Properties and etc ... +// + +// +// START Provided Functions ... +// +// +// Initial Library if required ... +bool OnInInitAlertLibrary() +{ + return false; +} + +// +// DeInitial Library if required ... +void OnDeinitAlertLibrary() +{ +} + +// +// Attach Alert Prefix to Message ... +string PrepareAlertMessage(string message) +{ + // + StringReplace(message, "\n", " | "); + + // + StringConcatenate(message, alertPrefix, " > ", message); + + // + return message; +} + +// +// Logging an Alert ... +void LogAlert(string message) +{ + // + // Validate Args ... + if (!enableAlerts || !logAlerts) + { + return; + } + + // + LogMessage(alertPrefix, message); +} + +// +// Terminal Alert ... +void TerminalAlert(string message) +{ + // + // Validate Args ... + if (!enableAlerts || !terminalAlerts) + { + return; + } + + // + // Prepare Message ... + message = PrepareAlertMessage(message); + + // Send Terminal Alert ... + Alert(message); +} + +// +// Mail Alert ... +void MailAlert(string message) +{ + // + // Validate Args ... + if (!enableAlerts || !mailAlerts) + { + return; + } + + // + // Send Mail Alert ... + SendMail(alertPrefix, message); +} + +// +// Send Push Notification ... +void PushAlert(string message) +{ + // + // Validate Args ... + if (!enableAlerts || !pushAlerts) + { + return; + } + + // + // Prepare Message ... + message = PrepareAlertMessage(message); + + // + // Send Push Notification Alert ... + SendNotification(message); +} + +// +// Alert Sending ... +void SendAlert(string message) +{ + // + // Validate Args ... + if (!enableAlerts) + { + return; + } + + // + // Log ... + if (logAlerts) + { + LogAlert(message); + } + + // + // Terminal ... + if (terminalAlerts) + { + TerminalAlert(message); + } + + // + // Mail ... + if (mailAlerts) + { + MailAlert(message); + } + + // + // Push ... + if (pushAlerts) + { + PushAlert(message); + } +} +// +// END Provided Functions ... +// diff --git a/MQLTestWorkspace/X121/14030217/Libraries/x-saherelm.common.lib.ex5 b/MQLTestWorkspace/X121/14030217/Libraries/x-saherelm.common.lib.ex5 new file mode 100644 index 0000000..34b610c Binary files /dev/null and b/MQLTestWorkspace/X121/14030217/Libraries/x-saherelm.common.lib.ex5 differ diff --git a/MQLTestWorkspace/X121/14030217/Libraries/x-saherelm.common.lib.mq5 b/MQLTestWorkspace/X121/14030217/Libraries/x-saherelm.common.lib.mq5 new file mode 100644 index 0000000..aecc450 --- /dev/null +++ b/MQLTestWorkspace/X121/14030217/Libraries/x-saherelm.common.lib.mq5 @@ -0,0 +1,5095 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Common Library +// -------------------------------------- +// Name: XCommon +// 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 + +// +// START Inputs ... +// + +// +// END Inputs ... +// + +// +// Include Models Library ... +#include "x-saherelm.models.lib.mq5" + +// +// START Global Definitions: Variables, Properties and etc ... +// +// +// END Global Definitions: Variables, Properties and etc ... +// + +// +// START Provided Functions ... +// + +// +// Detect is new Candle or not ... +bool IsNewCandle() +{ + // + bool result = false; + + // + static int barsOnChart = 0; + int currentBarsOnChart = Bars(_Symbol, _Period); + result = currentBarsOnChart > barsOnChart; + if (!result) + { + return result; + } + + // + barsOnChart = currentBarsOnChart; + result = true; + + // + return result; +} +bool IsNewCandle( + string mSymbol, // Trading Symbol ... + ENUM_TIMEFRAMES mPeriod // Trading Time Frame ... +) +{ + // + bool result = false; + + // + static string mChartTags[]; + static int mChartBars[]; + + // + string chTag = mSymbol + "," + ToString(mPeriod); + + // + int currChTagIdx = -1; + int chCountedBars = 0; + int currentBars = Bars(mSymbol, mPeriod); + + // + if (ArraySize(mChartTags) > 0) + { + // + for (int i = 0; i < ArraySize(mChartTags); i++) + { + // + string iTag = mChartTags[i]; + if (iTag != chTag) + { + continue; + } + + // + currChTagIdx = i; + break; + } + + // + if (currChTagIdx > -1) + { + chCountedBars = mChartBars[currChTagIdx]; + } + } + + // + result = currentBars > chCountedBars; + if (result) + { + // + if (currChTagIdx > -1) + { + // + mChartTags[currChTagIdx] = chTag; + mChartBars[currChTagIdx] = currentBars; + } + else + { + // + Add(chTag, mChartTags); + Add(currentBars, mChartBars); + } + } + + // + return result; +} + +// +double XNZ(double check, double val = 0) +{ + if (check == EMPTY_VALUE || check == 0) + { + return val; + } + else + { + return check; + } +} + +// +// Retrive Ask Price ... +double GetAsk() +{ + return SymbolInfoDouble(_Symbol, SYMBOL_ASK); +} +double GetAsk( + string symbol // selected symbol for calculations +) +{ + // + double result = SymbolInfoDouble(symbol, SYMBOL_ASK); + + // + return result; +} + +// +// Retrieve Bid Price ... +double GetBid() +{ + return SymbolInfoDouble(_Symbol, SYMBOL_BID); +} +double GetBid( + string symbol // selected symbol for calculations +) +{ + // + double result = SymbolInfoDouble(symbol, SYMBOL_BID); + + // + return result; +} + +// +// Calculate and Retrieve Spread Price ... +double GetSpread() +{ + // + double ask = GetAsk(); + double bid = GetBid(); + double result = MathAbs(ask - bid); + + // + return result; +} +double GetSpread( + string symbol // selected symbol for calculations +) +{ + // + double ask = GetAsk(symbol); + double bid = GetBid(symbol); + double result = MathAbs(ask - bid); + + // + return result; +} + +// +// Get Points ... +double GetPoints() +{ + return _Point; +} +double GetPoints( + string symbol // selected symbol for calculations +) +{ + // + double result = SymbolInfoDouble(symbol, SYMBOL_POINT); + + // + return result; +} + +// +// Get Digits ... +int GetDigits() +{ + return _Digits; +} +int GetDigits( + string symbol // selected symbol for calculations +) +{ + // + int result = (int)SymbolInfoInteger(symbol, SYMBOL_DIGITS); + + // + return result; +} + +// +// Get Signal Entry ... +double GetEntry( + ENUM_POSITION_TYPE type // Get entry price for Which direction trade ... +) +{ + // + double result = 0; + + // + bool isLong = type == POSITION_TYPE_BUY; + result = isLong ? GetAsk() : GetBid(); + result = NormalizePrice(result); + + // + return result; +} +double GetEntry( + string symbol, // Specified Symbol + ENUM_POSITION_TYPE type // Get entry price for Which direction trade ... +) +{ + // + double result = 0; + + // + bool isLong = type == POSITION_TYPE_BUY; + result = isLong ? GetAsk(symbol) : GetBid(symbol); + result = NormalizePrice(result, symbol); + + // + return result; +} + +// +// Get Signal Exit ... +double GetExit( + ENUM_POSITION_TYPE type // Get entry price for Which direction trade ... +) +{ + // + double result = 0; + + // + bool isLong = type == POSITION_TYPE_BUY; + result = isLong ? GetBid() : GetAsk(); + result = NormalizePrice(result); + + // + return result; +} +double GetExit( + string symbol, // Specified Symbol + ENUM_POSITION_TYPE type // Get entry price for Which direction trade ... +) +{ + // + double result = 0; + + // + bool isLong = type == POSITION_TYPE_BUY; + result = isLong ? GetBid(symbol) : GetAsk(symbol); + result = NormalizePrice(result, symbol); + + // + return result; +} + +// +// 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; +} + +// +// Get 1 Pip in Price Value ... +double GetPipPrice() +{ + // + double result = _Point; + if (_Digits == 3 || _Digits == 5) + { + result *= 10; + } + + // + return result; +} +double GetPipPrice( + string symbol // selected symbol for calculations +) +{ + // + double symbolPoint = GetPoints(symbol); + int symbolDigits = GetDigits(symbol); + + // + double result = symbolPoint; + if (symbolDigits == 3 || symbolDigits == 5) + { + result *= 10; + } + + // + return result; +} + +// +// Converts Pips To Price ... +double PipsToPrice( + int pips // pips amount +) +{ + // + int digits = GetDigits(); + double pipValue = GetPipPrice(); + double result = pips * pipValue; + + // + result = NormalizeDouble(result, digits); + + // + return result; +} +double PipsToPrice( + double pips // pips amount +) +{ + // + int digits = GetDigits(); + double pipValue = GetPipPrice(); + double result = pips * pipValue; + + // + result = NormalizeDouble(result, digits); + + // + return result; +} +double PipsToPrice( + string symbol, // selected symbol for calculation + int pips // pips amount +) +{ + // + int digits = GetDigits(symbol); + double pipValue = GetPipPrice(symbol); + double result = pips * pipValue; + + // + result = NormalizeDouble(result, digits); + + // + return result; +} +double PipsToPrice( + string symbol, // selected symbol for calculation + double pips // pips amount +) +{ + // + int digits = GetDigits(symbol); + double pipValue = GetPipPrice(symbol); + double result = pips * pipValue; + + // + result = NormalizeDouble(result, digits); + + // + return result; +} + +// +// Converts Price to Pips ... +double PriceToPips( + double price // the price amount which required to calculate +) +{ + // + int digits = GetDigits(); + double pipPrice = GetPipPrice(); + + // + double result = price / pipPrice; + + // + result = NormalizeDouble(result, digits); + + // + return result; +} +double PriceToPips( + string symbol, // Selected Symbol + double price // the price amount which required to calculate +) +{ + // + int digits = GetDigits(symbol); + double pipPrice = GetPipPrice(symbol); + + // + double result = price / pipPrice; + + // + result = NormalizeDouble(result, digits); + + // + return result; +} + +// +// Convert Price to Point ... +double PriceToPoint( + double price // the price amount which required to calculate +) +{ + return PriceToPoint(_Symbol, price); +} +double PriceToPoint( + string symbol, // Selected Symbol + double price // the price amount which required to calculate +) +{ + // + double result = 0; + + // + double point = GetPoints(symbol); + result = price / point; + + // + return result; +} + +// +// Converts Point to Price ... +double PointToPrice( + double points // Points Size +) +{ + return PointToPrice(_Symbol, points); +} +double PointToPrice( + string symbol, // Selected Symbol + double points // Points Size +) +{ + // + double result = 0; + + // + double point = GetPoints(symbol); + result = points * point; + + // + return result; +} + +// +// CANDLES ... + +// +// Validate Candle ... +bool IsValid( + XOHCL &candle // specified candle +) +{ + // + bool result = false; + + // + result = + // + candle.open > 0 && + candle.close > 0 && + candle.high > 0 && + candle.low > 0 + // + ; + + // + return result; +} + +// +// Get a Candle Body ... +double GetCandleBody( + XOHCL &candle // specified candle +) +{ + // + double result = 0; + + // + bool isValid = IsValid(candle); + if (!isValid) + { + return result; + } + + // + result = MathAbs(candle.open - candle.close); + + // + return result; +} + +// +// Get a Candle Range ... +double GetCandleRange( + XOHCL &candle // specified candle +) +{ + // + double result = 0; + + // + bool isValid = IsValid(candle); + if (!isValid) + { + return result; + } + + // + result = MathAbs(candle.high - candle.low); + + // + return result; +} + +// +// Get a Candle Shadow ... +double GetCandleShadow( + XOHCL &candle // specified candle +) +{ + // + double result = 0; + + // + bool isValid = IsValid(candle); + if (!isValid) + { + return 0; + } + + // + double range = GetCandleRange(candle); + double body = GetCandleBody(candle); + + // + result = MathAbs(range - body); + + // + return result; +} + +// +// Retrieve High Shadow of Candle ... +double GetCandleHighShadow( + XOHCL &candle // specified candle +) +{ + // + double result = 0; + + // + bool isValid = IsValid(candle); + if (!isValid) + { + return result; + } + + // + double upPrice = MathMax(candle.open, candle.close); + + // + result = candle.high - upPrice; + + // + return result; +} + +// +// Retrieve Low Shadow of Candle ... +double GetCandleLowShadow( + XOHCL &candle // specified candle +) +{ + // + double result = 0; + + // + bool isValid = IsValid(candle); + if (!isValid) + { + return result; + } + + // + double downPrice = MathMin(candle.open, candle.close); + + // + result = downPrice - candle.low; + + // + return result; +} + +// +// Check a Candle is Base Candle for RTM or not ... +bool IsBaseCandle( + XOHCL &candle // specified candle +) +{ + // + double range = GetCandleRange(candle); + double body = GetCandleBody(candle); + + // + bool result = body > range; + + // + return result; +} + +// +// Check Candle Body Bigger Than it's Shadow ... +bool CandleHasStrongBody(XOHCL &candle) +{ + // + double bodySize = MathAbs(candle.open - candle.close); + double shadowSize = MathAbs(candle.high - candle.low) - bodySize; + + // + bool result = bodySize > (shadowSize * 1.5); + + // + return result; +} + +// +// Detect Doji Candle ... +bool IsDojiCandle( + XOHCL &candle, // Specified Candle + double detectFactor = 0.05 // Detect Factor +) +{ + // + bool result = false; + + // + bool isValid = IsValid(candle); + if ( + !isValid || + detectFactor <= 0 || + detectFactor > 1) + { + return result; + } + + // + // Retrieve Candle Parts ... + double body = GetCandleBody(candle); + double range = GetCandleRange(candle); + double shadows = GetCandleShadow(candle); + + // + // Calculate Candle Rate ... + double factor = range * detectFactor; + double shadowFactor = (1 - detectFactor) * range; + + // + result = + // + body > 0 && + range > 0 && + factor > 0 && + shadows > 0 && + body <= factor && + shadowFactor > 0 && + shadows >= shadowFactor + // + ; + + // + return result; +} + +// +// Detect Shadows of Specific Candles must be same .. +bool IsCrossShadowCandle( + XOHCL &candle, // Specified Candle + double smoothingFactor = 0.05 // Smoothing Factor +) +{ + // + bool result = false; + + // + bool isValid = IsValid(candle); + if (!isValid || + smoothingFactor <= 0 || + smoothingFactor >= 1) + { + return result; + } + + // + // Retrieve Candle Parts ... + double body = GetCandleBody(candle); + double range = GetCandleRange(candle); + double shadows = GetCandleShadow(candle); + + // + double upBody = MathMax(candle.open, candle.close); + double downBody = MathMin(candle.open, candle.close); + + // + double upShadow = candle.high - upBody; + double downShadow = downBody - candle.low; + + // + // Calculate Candle Rate ... + double factor = range * smoothingFactor; + + // + result = + upShadow > 0 && + downShadow > 0 && + body > 0 && + range > 0 && + shadows > 0 && + ((upShadow == downShadow) || + MathAbs(upShadow - downShadow) <= factor); + + // + return result; +} + +// +// Detect a Candle Shadow Hunt Specific price or not ... +bool IsShadowHuntCandle( + XOHCL &candle, // Specified Candle + double price // Specified Price +) +{ + // + bool result = false; + + // + // Validate Args ... + bool isValid = IsValid(candle); + if (!isValid || price <= 0) + { + return result; + } + + // + double upBody = MathMax(candle.open, candle.close); + double downBody = MathMin(candle.open, candle.close); + + // + double hShadow = GetCandleHighShadow(candle); + double lShadow = GetCandleLowShadow(candle); + + // + double range = GetCandleRange(candle); + double factor = range * 0.3; + + // + bool isStrongHShadow = hShadow >= factor; + bool isStrongLShadow = lShadow >= factor; + + // + bool isPriceUp = + price >= candle.high || + price >= upBody; + + // + result = + // + isPriceUp + // + ? + // + isStrongHShadow && + (price == candle.high || + (price > upBody && price < candle.high)) + // + : + // + isStrongLShadow && + (price == candle.low || + (price < downBody && price > candle.low)) + // + ; + + // + return result; +} + +// +// Check a Candle is Bullish or not ... +bool IsBullishCandle( + XOHCL &candle // specified candle +) +{ + // + bool result = false; + + // + bool isValid = IsValid(candle); + if (!isValid) + { + return result; + } + + // + result = candle.open < candle.close; + + // + return result; +} +bool IsBullishCandle( + int bar_index // candle index +) +{ + // + bool result = false; + + // + XOHCL candle = GetCandle(bar_index); + + // + result = IsBullishCandle(candle); + + // + return result; +} +bool IsBullishCandle( + string symbol, // specify symbol + ENUM_TIMEFRAMES mPeriod, // specify timeframe + int bar_index // candle index +) +{ + // + bool result = false; + + // + XOHCL candle = GetCandle( + symbol, + mPeriod, + bar_index); + + // + result = IsBullishCandle(candle); + + // + return result; +} + +// +// Check a Candle is Bullish or not ... +bool IsBearishCandle( + XOHCL &candle // specified candle +) +{ + // + bool result = false; + + // + bool isValid = IsValid(candle); + if (!isValid) + { + return result; + } + + // + result = candle.open > candle.close; + + // + return result; +} +bool IsBearishCandle( + int bar_index // candle index +) +{ + // + bool result = false; + + // + XOHCL candle = GetCandle(bar_index); + + // + result = IsBearishCandle(candle); + + // + return result; +} +bool IsBearishCandle( + string symbol, // specify symbol + ENUM_TIMEFRAMES mPeriod, // specify timeframe + int bar_index // candle index +) +{ + // + bool result = false; + + // + XOHCL candle = GetCandle( + symbol, + mPeriod, + bar_index); + + // + result = IsBearishCandle(candle); + + // + return result; +} + +// +// Retrieve Applied Price at Specific Candle ... +double GetAppliedPrice( + XOHCL &candle, // specified candle + ENUM_APPLIED_PRICE source = PRICE_CLOSE // specified Applied To +) +{ + // + double result = EMPTY_VALUE; + + // + switch (source) + { + // + // Open ... + case PRICE_OPEN: + result = candle.open; + break; + + // + // High ... + case PRICE_HIGH: + result = candle.high; + break; + + // + // Low ... + case PRICE_LOW: + result = candle.low; + break; + + // + // Median ((High + Low) / 2) ... + case PRICE_MEDIAN: + result = (candle.high + candle.low) / 2; + break; + + // + // Typical ((High + Low + Close)/3) ... + case PRICE_TYPICAL: + result = (candle.high + candle.low + candle.close) / 3; + break; + + // + // Weighted ((High + Low + Close + Close)/4) ... + case PRICE_WEIGHTED: + result = (candle.high + candle.low + (candle.close * 2)) / 4; + break; + + // + // Close ... + default: + case PRICE_CLOSE: + result = candle.close; + break; + } + + // + return result; +} +double GetAppliedPrice( + int bar_index, // specify candle index + ENUM_APPLIED_PRICE source = PRICE_CLOSE // specified Applied To +) +{ + // + double result = EMPTY_VALUE; + + // + XOHCL candle = GetCandle(bar_index); + result = GetAppliedPrice(candle, source); + + // + return result; +} +double GetAppliedPrice( + int bar_index, // specify candle index + ENUM_SERIESMODE mode // converts Series Mode to Applied Price ... +) +{ + // + double result = 0; + + // + ENUM_APPLIED_PRICE mAppliedTo = To(mode); + result = GetAppliedPrice( + bar_index, + mAppliedTo); + + // + return result; +} + +// +template +double GetAppliedPrice(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); +} + +// +// Converts ... +ENUM_APPLIED_PRICE To( + ENUM_SERIESMODE mode // converts Series Mode to Applied Price ... +) +{ + // + ENUM_APPLIED_PRICE result = PRICE_CLOSE; + + // + switch (mode) + { + // + // High ... + case MODE_HIGH: + result = PRICE_HIGH; + break; + + // + // Open ... + case MODE_OPEN: + result = PRICE_OPEN; + break; + + // + // Low ... + case MODE_LOW: + result = PRICE_LOW; + break; + + // + // Close ... + // Default ... + case MODE_CLOSE: + default: + result = PRICE_CLOSE; + break; + } + + // + return result; +} + +// +// Retrieve a Candel Data ... +XOHCL GetCandle(int bar_index) +{ + // + XOHCL result = {}; + + // + double open = iOpen(_Symbol, _Period, bar_index); + double high = iHigh(_Symbol, _Period, bar_index); + double close = iClose(_Symbol, _Period, bar_index); + double low = iLow(_Symbol, _Period, bar_index); + + // + result.low = low; + result.open = open; + result.high = high; + result.close = close; + + // + return result; +} +XOHCL GetCandle( + ENUM_TIMEFRAMES mPeriod, // specify timeframe + int bar_index // specify candle index +) +{ + // + XOHCL result = {}; + + // + double open = iOpen(_Symbol, mPeriod, bar_index); + double high = iHigh(_Symbol, mPeriod, bar_index); + double close = iClose(_Symbol, mPeriod, bar_index); + double low = iLow(_Symbol, mPeriod, bar_index); + + // + result.low = low; + result.open = open; + result.high = high; + result.close = close; + + // + return result; +} +XOHCL GetCandle( + string symbol, // specify symbol + ENUM_TIMEFRAMES mPeriod, // specify timeframe + int bar_index // specify candle index +) +{ + // + XOHCL result = {}; + + // + double open = iOpen(symbol, mPeriod, bar_index); + double high = iHigh(symbol, mPeriod, bar_index); + double close = iClose(symbol, mPeriod, bar_index); + double low = iLow(symbol, mPeriod, bar_index); + + // + result.low = low; + result.open = open; + result.high = high; + result.close = close; + + // + return result; +} + +// +// Get a Series Of Candles ... +bool GetCandles( + XOHCL &result[], // Hold Result ... + string mSymbol = NULL, // Specified Symbol ... + ENUM_TIMEFRAMES mPeriod = NULL, // Specified Period ... + int mStart = 0, // Start Bar Index ... + int mCount = 1 // Specified Number of Candles ... +) +{ + // + bool mResult = false; + + // + if (mStart < 0) + { + mStart = 0; + } + + // + if (mCount <= 0) + { + mCount = 1; + } + + // + Clean(result); + + // + for (int i = mStart; i < mStart + mCount; i++) + { + // + XOHCL iC = GetCandle( + mSymbol, + mPeriod, + i); + + // + Add( + iC, + result); + } + + // + mResult = ArraySize(result) > 0; + + // + return mResult; +} + +// +// Retrieve a candle index in current timeframe inside another timeframe ... +int GetCandleBarIndex( + int bar_index, // Specify Candle index in current timeframe + ENUM_TIMEFRAMES destPeriod // Specify destination timeframe +) +{ + // + int result = -1; + + // + datetime barTime = iTime(_Symbol, _Period, bar_index); + result = iBarShift(_Symbol, destPeriod, barTime); + + // + return result; +} + +// +// Retrieve a symbol candle index in source time frame inside dest timeframe ... +int GetCandleBarIndex( + int bar_index, // Specify Candle index in current timeframe + string symbol, // Specify desired Symbol + ENUM_TIMEFRAMES sourcePeriod, // Specify bar_index timeframe + ENUM_TIMEFRAMES destPeriod // Specify destination timeframe +) +{ + // + int result = -1; + + // + datetime barTime = iTime(symbol, sourcePeriod, bar_index); + result = iBarShift(symbol, destPeriod, barTime); + + // + return result; +} + +// +// Determines a cnadle is Swing High +// or Swing Low order block ... +ENUM_X_SWING_TYPE GetCandleSwing(int bar_index) +{ + // + ENUM_X_SWING_TYPE result = X_NO_SWING; + + // + // Reading Candle Models ... + XOHCL candles[3]; + candles[0] = GetCandle(bar_index + 1); + candles[1] = GetCandle(bar_index + 2); + candles[2] = GetCandle(bar_index + 3); + + // + // Check Swing Start Candle has Strong Body ... + bool isStrongBodyCandle = CandleHasStrongBody(candles[2]); + if (!isStrongBodyCandle) + { + return result; + } + + // + // Check Swing Low Conditions ... + bool isSwingLowOrderBlock = + candles[2].low < candles[1].low && + candles[1].low < candles[0].low && + candles[2].low < candles[0].low; + if (isSwingLowOrderBlock) + { + result = X_SWING_LOW; + } + + // + // Check Swing High Conditions ... + bool isSwingHighOrderBlock = + candles[2].high > candles[1].high && + candles[1].high > candles[0].high && + candles[2].high > candles[0].high; + if (isSwingHighOrderBlock) + { + result = X_SWING_HIGH; + } + + // + return result; +} +ENUM_X_SWING_TYPE GetCandleSwing( + ENUM_TIMEFRAMES mPeriod, // specify timeframe + int bar_index // specify candle index +) +{ + // + ENUM_X_SWING_TYPE result = X_NO_SWING; + + // + // Reading Candle Models ... + XOHCL candles[3]; + candles[0] = GetCandle(mPeriod, bar_index + 1); + candles[1] = GetCandle(mPeriod, bar_index + 2); + candles[2] = GetCandle(mPeriod, bar_index + 3); + + // + // Check Swing Start Candle has Strong Body ... + bool isStrongBodyCandle = CandleHasStrongBody(candles[2]); + if (!isStrongBodyCandle) + { + return result; + } + + // + // Check Swing Low Conditions ... + bool isSwingLowOrderBlock = + candles[2].low < candles[1].low && + candles[1].low < candles[0].low && + candles[2].low < candles[0].low; + if (isSwingLowOrderBlock) + { + result = X_SWING_LOW; + } + + // + // Check Swing High Conditions ... + bool isSwingHighOrderBlock = + candles[2].high > candles[1].high && + candles[1].high > candles[0].high && + candles[2].high > candles[0].high; + if (isSwingHighOrderBlock) + { + result = X_SWING_HIGH; + } + + // + return result; +} +ENUM_X_SWING_TYPE GetCandleSwing( + string symbol, // specify symbol + ENUM_TIMEFRAMES mPeriod, // specify timeframe + int bar_index // specify candle index +) +{ + // + ENUM_X_SWING_TYPE result = X_NO_SWING; + + // + // Reading Candle Models ... + XOHCL candles[3]; + candles[0] = GetCandle(symbol, mPeriod, bar_index + 1); + candles[1] = GetCandle(symbol, mPeriod, bar_index + 2); + candles[2] = GetCandle(symbol, mPeriod, bar_index + 3); + + // + // Check Swing Start Candle has Strong Body ... + bool isStrongBodyCandle = CandleHasStrongBody(candles[2]); + if (!isStrongBodyCandle) + { + return result; + } + + // + // Check Swing Low Conditions ... + bool isSwingLowOrderBlock = + candles[2].low < candles[1].low && + candles[1].low < candles[0].low && + candles[2].low < candles[0].low; + if (isSwingLowOrderBlock) + { + result = X_SWING_LOW; + } + + // + // Check Swing High Conditions ... + bool isSwingHighOrderBlock = + candles[2].high > candles[1].high && + candles[1].high > candles[0].high && + candles[2].high > candles[0].high; + if (isSwingHighOrderBlock) + { + result = X_SWING_HIGH; + } + + // + return result; +} + +// +// Find Swing Points ... +int FindSwing( + string mSymbol, // Trading Symbol ... + ENUM_TIMEFRAMES mPeriod, // Trading Period ... + ENUM_SERIESMODE mode, // Swing Based On Price mode ... + int mLength, // Loopback ... + int bar_index // BarIndex ... +) +{ + // + int result = -1; + + // + if (StringLen(mSymbol) == 0 || (mode != MODE_HIGH && mode != MODE_LOW)) + { + return result; + } + + // + int current = bar_index; + int founded = FindNextSwing( + mSymbol, + mPeriod, + mode, + (mLength * 2) + 1, + current - mLength); + + // + while (founded != current) + { + // + current = FindNextSwing( + mSymbol, + mPeriod, + mode, + mLength, + current + 1); + + // + founded = FindNextSwing( + mSymbol, + mPeriod, + mode, + (mLength * 2) + 1, + current - mLength); + } + + // + result = current; + + // + return result; +} + +// +// Find Next Swing ... +int FindNextSwing( + string mSymbol, // Trading Symbol ... + ENUM_TIMEFRAMES mPeriod, // Trading Period ... + ENUM_SERIESMODE mode, // 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; + } + + // + result = mode == MODE_HIGH + ? iHighest( + mSymbol, + mPeriod, + mode, + mLength, + bar_index) + : iLowest( + mSymbol, + mPeriod, + mode, + mLength, + bar_index); + + // + return result; +} + +// +// Retrieve Market Highest High ... +double GetHighestHigh( + int mLength, // Which market Length use + int bar_index // bar index +) +{ + // + double result = -1; + + // + int rIdx = iHighest( + _Symbol, + _Period, + MODE_HIGH, + mLength, + bar_index); + + // + result = iHigh( + _Symbol, + _Period, + rIdx); + + // + return result; +} +double GetHighestHigh( + int mLength, // Which market Length use + int bar_index, // bar index + ENUM_SERIESMODE mode // Calculation mode +) +{ + // + double result = -1; + + // + int rIdx = iHighest( + _Symbol, + _Period, + mode, + mLength, + bar_index); + + // + result = iHigh( + _Symbol, + _Period, + rIdx); + + // + return result; +} +double GetHighestHigh( + string symbol, // Specified Symbol + ENUM_TIMEFRAMES mPeriod, // Specified Period + int mLength, // Which market Length use + int bar_index // bar index +) +{ + // + double result = -1; + + // + int rIdx = iHighest( + symbol, + mPeriod, + MODE_HIGH, + mLength, + bar_index); + + // + result = iHigh( + symbol, + mPeriod, + rIdx); + + // + return result; +} +double GetHighestHigh( + string symbol, // Specified Symbol + ENUM_TIMEFRAMES mPeriod, // Specified Period + ENUM_SERIESMODE mode, // Calculation mode + int mLength, // Which market Length use + int bar_index // bar index +) +{ + // + double result = -1; + + // + int rIdx = iHighest( + symbol, + mPeriod, + mode, + mLength, + bar_index); + + // + result = iHigh( + symbol, + mPeriod, + rIdx); + + // + return result; +} + +// +// Retrieve Market Lowest Low ... +double GetLowestLow( + int mLength, // Which market Length use + int bar_index // bar index +) +{ + // + double result = -1; + + // + int rIdx = iLowest( + _Symbol, + _Period, + MODE_LOW, + mLength, + bar_index); + + // + result = iLow( + _Symbol, + _Period, + rIdx); + + // + return result; +} +double GetLowestLow( + int mLength, // Which market Length use + int bar_index, // bar index + ENUM_SERIESMODE mode // Calculation mode +) +{ + // + double result = -1; + + // + int rIdx = iLowest( + _Symbol, + _Period, + mode, + mLength, + bar_index); + + // + result = iLow( + _Symbol, + _Period, + rIdx); + + // + return result; +} +double GetLowestLow( + string symbol, // Specified Symbol + ENUM_TIMEFRAMES mPeriod, // Specified Period + int mLength, // Which market Length use + int bar_index // bar index +) +{ + // + double result = -1; + + // + int rIdx = iLowest( + symbol, + mPeriod, + MODE_LOW, + mLength, + bar_index); + + // + result = iLow( + symbol, + mPeriod, + rIdx); + + // + return result; +} +double GetLowestLow( + string symbol, // Specified Symbol + ENUM_TIMEFRAMES mPeriod, // Specified Period + ENUM_SERIESMODE mode, // Calculation mode + int mLength, // Which market Length use + int bar_index // bar index +) +{ + // + double result = -1; + + // + int rIdx = iLowest( + symbol, + mPeriod, + mode, + mLength, + bar_index); + + // + result = iLow( + symbol, + mPeriod, + rIdx); + + // + return result; +} + +// +// Find Support and Resistance for Specific Bar based on provided Buffer ... +XOHCLSupRes ExtractSupportAndResistance( + int barIndex, // Bar Index ... + const double &pivots[], // Provided Pivot Points ... + int count = 3, // Number of Requireds ... + string mSymbol = NULL, // Trading Symbol ... + ENUM_TIMEFRAMES mPeriod = NULL // Trading Period ... +) +{ + // + if (StringLen(mSymbol) == 0 || mSymbol == NULL) + { + mSymbol = _Symbol; + } + + // + if (mPeriod == NULL) + { + mPeriod = _Period; + } + + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + XOHCLSupRes result; + Clean(result.res); + Clean(result.sup); + + // + int pivotsCount = ArraySize(pivots); + if (pivotsCount <= 0) + { + return result; + } + + // + if (count <= 0 || + count > pivotsCount - 1) + { + return result; + } + + // + XOHCL cBar = GetCandle( + mSymbol, + mPeriod, + barIndex); + + // + double tmpR[]; + + // + 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 > cBar.high) + { + Add( + iFlat, + tmpR); + } + else if (iFlat < cBar.low) + { + Add( + iFlat, + tmpS); + } + } + + // + // 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( + result.res, + tmpR); + } + else + { + // + ArrayCopy( + result.res, + tmpR, + 0, + 0, + count); + } + } + + // + // Fill Supports ... + int tmpSCount = ArraySize(tmpS); + if (tmpSCount > 0) + { + // + if (tmpSCount < count) + { + // + ArrayCopy( + result.sup, + tmpS); + } + else + { + // + ArrayCopy( + result.sup, + tmpS, + 0, + 0, + count); + } + } + + // + return result; +} + +// +// Find Support and Resistance for Specific Price based on provided Buffer ... +XOHCLSupRes ExtractSupportAndResistance( + double price, // Price ... + const double &pivots[], // Provided Pivot Points ... + int count = 3 // Number of Requireds ... +) +{ + // + XOHCLSupRes result; + Clean(result.res); + Clean(result.sup); + + // + if (price <= 0) + { + return result; + } + + // + int pivotsCount = ArraySize(pivots); + if (pivotsCount <= 0) + { + return result; + } + + // + if (count <= 0 || + count > pivotsCount - 1) + { + return result; + } + + // + double tmpR[]; + + // + 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) + { + Add( + iFlat, + tmpR); + } + else if (iFlat < price) + { + Add( + iFlat, + tmpS); + } + } + + // + // 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( + result.res, + tmpR); + } + else + { + // + ArrayCopy( + result.res, + tmpR, + 0, + 0, + count); + } + } + + // + // Fill Supports ... + int tmpSCount = ArraySize(tmpS); + if (tmpSCount > 0) + { + // + if (tmpSCount < count) + { + // + ArrayCopy( + result.sup, + tmpS); + } + else + { + // + ArrayCopy( + result.sup, + tmpS, + 0, + 0, + count); + } + } + + // + return result; +} + +// +// Find a Value less than Specified ... +double FindLesserThanValue( + double value, // Specified Value ... + const double &source[], // Source ... + bool isDescend = false // Find Biggest Lesser Value ... +) +{ + // + double result = -1; + + // + int itemsCount = ArraySize(source); + if (itemsCount <= 0) + { + return result; + } + + // + // Make a Copy of source ... + double 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++) + { + // + double iValue = tmp[i]; + + // + if (iValue < value) + { + // + result = iValue; + break; + } + } + + // + return result; +} + +// +// Find a Value less than Specified ... +double FindBiggerThanValue( + double value, // Specified Value ... + const double &source[], // Source ... + bool isDescend = false // Find Smallest Bigger Value ... +) +{ + // + double result = -1; + + // + int itemsCount = ArraySize(source); + if (itemsCount <= 0) + { + return result; + } + + // + // Make a Copy of source ... + double 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++) + { + // + double iValue = tmp[i]; + + // + if (iValue > value) + { + // + result = iValue; + break; + } + } + + // + return result; +} + +// +// Calculate Fib Level ... +double GetFibonacciLevel( + double upPrice, + double downPrice, + double level, + int direction) +{ + // + double ling = upPrice - downPrice; + double pLevel = (ling / 100) * (level * 100); + + // + double result = direction > 0 ? upPrice - pLevel : downPrice + pLevel; + result = NormalizeDouble(result, _Digits); + + // + return result; +} + +// +// Check first Cross Over second at bar_index ... +bool IsCrossOver( + const double &first[], // the buffer which check crossing over second buffer + const double &second[], // first buffer checks based on this buffer + const int bar_index // check crosses in specific index +) +{ + // + bool result = false; + + // + ArraySetAsSeries(first, true); + ArraySetAsSeries(second, true); + + // + // Validate Args ... + if (ArraySize(first) < bar_index + 1 || ArraySize(second) < bar_index + 1) + { + return result; + } + + // + result = first[bar_index] > second[bar_index] && + !(first[bar_index + 1] > second[bar_index + 1]); + + // + return result; +} + +// +// Check first is Over second at bar_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 bar_index // check crosses in specific index +) +{ + // + bool result = false; + + // + ArraySetAsSeries(first, true); + ArraySetAsSeries(second, true); + + // + // Validate Args ... + if (ArraySize(first) < bar_index + 1 || ArraySize(second) < bar_index + 1) + { + return result; + } + + // + result = first[bar_index] > second[bar_index] && + first[bar_index + 1] > second[bar_index + 1]; + + // + return result; +} + +// +// Check first Cross Under second at bar_index ... +bool IsCrossUnder( + const double &first[], // the buffer which check crossing under second buffer + const double &second[], // first buffer checks based on this buffer + const int bar_index // check crosses in specific index +) +{ + // + bool result = false; + + // + ArraySetAsSeries(first, true); + ArraySetAsSeries(second, true); + + // + // Validate Args ... + if (ArraySize(first) < bar_index + 1 || ArraySize(second) < bar_index + 1) + { + return result; + } + + // + result = first[bar_index] < second[bar_index] && + !(first[bar_index + 1] < second[bar_index + 1]); + + // + return result; +} + +// +// Check first is Under second at bar_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 bar_index // check crosses in specific index +) +{ + // + bool result = false; + + // + ArraySetAsSeries(first, true); + ArraySetAsSeries(second, true); + + // + // Validate Args ... + if (ArraySize(first) < bar_index + 1 || ArraySize(second) < bar_index + 1) + { + return result; + } + + // + result = first[bar_index] < second[bar_index] && + first[bar_index + 1] < second[bar_index + 1]; + + // + return result; +} + +// +// Calculate Slope of Specified Buffer at Specified Index ... +double GetSlope( + int from, // In Past Index ... + int to, // In Past Index ... + double &buffer[]) +{ + // + double result = 0; + + // + double toValue = buffer[to]; + double fromValue = buffer[from]; + double deltaValue = toValue - fromValue; + double deltaTime = from - to; + + // + result = deltaValue / deltaTime; + + // + return result; +} + +// +// Check if a Value Increasing in Loopback ... +bool IsIncreasing( + int from, // Last Time Index + int to, // Fisr Tima Index + 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( + int from, // Last Time Index + int to, // Fisr Tima Index + 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; +} + +// +// Get Max Value of Specific Loopback of a Buffer ... +double GetMaxValue( + int mLoopback, // loopback length + double &buffer[] // the Buffer which required to search +) +{ + // + double result = 0; + + // + // Validate Args ... + if ( + mLoopback < 2 || + ArraySize(buffer) < mLoopback) + { + return result; + } + + // + // Loop Through LoopBack ... + for (int i = 0; i < mLoopback; i++) + { + // + double iValue = buffer[i]; + + // + result = + // + result == 0 || result < iValue + // + ? iValue + // + : result + // + ; + } + + // + return result; +} + +// +// Get Min Value of Specific Loopback of a Buffer ... +double GetMinValue( + int mLoopback, // loopback length + double &buffer[] // the Buffer which required to search +) +{ + // + double result = 0; + + // + // Validate Args ... + if ( + mLoopback < 2 || + ArraySize(buffer) < mLoopback) + { + return result; + } + + // + // Loop Through LoopBack ... + for (int i = 0; i < mLoopback; i++) + { + // + double iValue = buffer[i]; + + // + result = + // + result == 0 || result > iValue + // + ? iValue + // + : result + // + ; + } + + // + return result; +} + +// +// Find Same Values in Array ... +void FindSameValueInBuffer( + double &result[], // Holds Result ... + double &source[], // Source ... + int verifications = 3 // Number of Consequence Repeat ... +) +{ + // + Clean(result); + + // + // TenkanSen Flats ... + int sourceCount = ArraySize(source); + if (sourceCount > verifications) + { + // + double mLast = 0; + int mVerified = 0; + for (int i = 0; i < sourceCount; i++) + { + // + double 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; + } + } + } +} + +// +bool IsInPeak( + int mLoopback, // loopback length + double &buffer[] // the Buffer which required to search +) +{ + // + bool result = false; + + // + // Validate Args ... + if ( + mLoopback < 2 || + ArraySize(buffer) < mLoopback + 1) + { + return result; + } + + // + int q1Length = mLoopback / 4; + int halfLength = mLoopback / 2; + int q2Length = halfLength + q1Length; + + // + double firstValue = buffer[1]; + double q1Value = buffer[q1Length]; + double q2Value = buffer[q2Length]; + double halfValue = buffer[halfLength]; + double lastValue = buffer[ArraySize(buffer) - 1]; + + // + // Peak ... + result = + // + firstValue > lastValue + // + && + // + ( + firstValue > q1Value && + firstValue > halfValue) + // + ; + + // + return result; +} + +// +bool IsInVale( + int mLoopback, // loopback length + double &buffer[] // the Buffer which required to search +) +{ + // + bool result = false; + + // + // Validate Args ... + if ( + mLoopback < 2 || + ArraySize(buffer) < mLoopback + 1) + { + return result; + } + + // + int q1Length = mLoopback / 4; + int halfLength = mLoopback / 2; + int q2Length = halfLength + q1Length; + + // + double firstValue = buffer[1]; + double q1Value = buffer[q1Length]; + double q2Value = buffer[q2Length]; + double halfValue = buffer[halfLength]; + double lastValue = buffer[ArraySize(buffer) - 1]; + + // + // Peak ... + result = + // + firstValue < lastValue + // + && + // + ( + firstValue < q1Value && + firstValue < halfValue) + // + ; + + // + return result; +} + +// +// Check Sharp Happens or not ... +bool IsSharpChanged( + double fromValue, // Past Value + double toValue, // Present Value + double maxValue, // Max in Range Value + double minValue // Min in Range Value +) +{ + // + bool result = false; + + // + // This Used In Increased or Decreased Sharp Detection ... + bool isIncreased = toValue > fromValue; + + // + double toFromDelta = MathAbs(toValue - fromValue); + double minMaxDelta = maxValue - minValue; + + // + result = toFromDelta >= (minMaxDelta / 3); + + // + return result; +} +bool IsSharpChanged( + int from, // Past Index in Series + int to, // Present Index in Series + 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]; + + // + // This Used In Increased or Decreased Sharp Detection ... + bool isIncreased = toValue > fromValue; + + // + double minValue = GetMinValue( + ArraySize(buffer) - 1, + buffer); + double maxValue = GetMaxValue( + ArraySize(buffer) - 1, + buffer); + double minMaxDelta = maxValue - minValue; + + // + // Sharp Detection ... + result = IsSharpChanged( + fromValue, + toValue, + maxValue, + minValue); + + // + return result; +} +bool IsSharpChanged( + int from, // Past Bar Index + int to, // Present Bar Index + ENUM_APPLIED_PRICE appliedPrice // Which Price Choose in From or To +) +{ + // + bool result = false; + + // + double toValue = GetAppliedPrice( + to, + appliedPrice); + double fromValue = GetAppliedPrice( + from, + appliedPrice); + + // + int hIdx = iHighest( + _Symbol, + _Period, + MODE_HIGH, + from, + to); + double maxValue = iHigh( + _Symbol, + _Period, + hIdx); + + // + int lIdx = iLowest( + _Symbol, + _Period, + MODE_LOW, + from, + to); + double minValue = iLow( + _Symbol, + _Period, + lIdx); + + // + result = IsSharpChanged( + fromValue, + toValue, + maxValue, + minValue); + + // + return result; +} + +// +// Check InCreased Sharp Happens or not ... +bool IsSharpIncreasedChanged( + double fromValue, // Past Value + double toValue, // Present Value + double maxValue, // Max in Range Value + double minValue // Min in Range Value +) +{ + // + bool result = false; + + // + // This Used In Increased or Decreased Sharp Detection ... + bool isIncreased = toValue > fromValue; + + // + double toFromDelta = MathAbs(toValue - fromValue); + double minMaxDelta = maxValue - minValue; + + // + result = + isIncreased && + toFromDelta >= (minMaxDelta / 3); + + // + return result; +} +bool IsSharpIncreasedChanged( + int from, // Past Index in Series + int to, // Present Index in Series + 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]; + + // + double minValue = GetMinValue( + ArraySize(buffer) - 1, + buffer); + double maxValue = GetMaxValue( + ArraySize(buffer) - 1, + buffer); + double minMaxDelta = maxValue - minValue; + + // + // Sharp Detection ... + result = IsSharpIncreasedChanged( + fromValue, + toValue, + maxValue, + minValue); + + // + return result; +} +bool IsSharpIncreasedChanged( + int from, // Past Bar Index + int to, // Present Bar Index + ENUM_APPLIED_PRICE appliedPrice // Which Price Choose in From or To +) +{ + // + bool result = false; + + // + double toValue = GetAppliedPrice( + to, + appliedPrice); + double fromValue = GetAppliedPrice( + from, + appliedPrice); + + // + int hIdx = iHighest( + _Symbol, + _Period, + MODE_HIGH, + from, + to); + double maxValue = iHigh( + _Symbol, + _Period, + hIdx); + + // + int lIdx = iLowest( + _Symbol, + _Period, + MODE_LOW, + from, + to); + double minValue = iLow( + _Symbol, + _Period, + lIdx); + + // + result = IsSharpIncreasedChanged( + fromValue, + toValue, + maxValue, + minValue); + + // + return result; +} + +// +// Check Decreased Sharp Happens or not ... +bool IsSharpDecreasedChanged( + double fromValue, // Past Value + double toValue, // Present Value + double maxValue, // Max in Range Value + double minValue // Min in Range Value +) +{ + // + bool result = false; + + // + // This Used In Increased or Decreased Sharp Detection ... + bool isIncreased = toValue > fromValue; + + // + double toFromDelta = MathAbs(toValue - fromValue); + double minMaxDelta = maxValue - minValue; + + // + result = + !isIncreased && + toFromDelta >= (minMaxDelta / 3); + + // + return result; +} +bool IsSharpDecreasedChanged( + int from, // Past Index in Series + int to, // Present Index in Series + 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]; + + // + double minValue = GetMinValue( + ArraySize(buffer) - 1, + buffer); + double maxValue = GetMaxValue( + ArraySize(buffer) - 1, + buffer); + double minMaxDelta = maxValue - minValue; + + // + // Sharp Detection ... + result = IsSharpDecreasedChanged( + fromValue, + toValue, + maxValue, + minValue); + + // + return result; +} +bool IsSharpDecreasedChanged( + int from, // Past Bar Index + int to, // Present Bar Index + ENUM_APPLIED_PRICE appliedPrice // Which Price Choose in From or To +) +{ + // + bool result = false; + + // + double toValue = GetAppliedPrice( + to, + appliedPrice); + double fromValue = GetAppliedPrice( + from, + appliedPrice); + + // + int hIdx = iHighest( + _Symbol, + _Period, + MODE_HIGH, + from, + to); + double maxValue = iHigh( + _Symbol, + _Period, + hIdx); + + // + int lIdx = iLowest( + _Symbol, + _Period, + MODE_LOW, + from, + to); + double minValue = iLow( + _Symbol, + _Period, + lIdx); + + // + result = IsSharpDecreasedChanged( + fromValue, + toValue, + maxValue, + minValue); + + // + return result; +} + +// +void Clean(int &buffer[]) +{ + // + ArrayFree(buffer); + ArrayResize(buffer, 0); +} +void Clean(ulong &buffer[]) +{ + // + ArrayFree(buffer); + ArrayResize(buffer, 0); +} +void Clean(string &buffer[]) +{ + // + ArrayFree(buffer); + ArrayResize(buffer, 0); +} +void Clean(double &buffer[]) +{ + // + ArrayFree(buffer); + ArrayResize(buffer, 0); +} + +// +bool GetLastItem( + double &item, // Holds Result + double &buffer[] // Specified Buffer +) +{ + // + bool result = false; + + // + int bufferSize = ArraySize(buffer); + if (bufferSize <= 0) + { + return result; + } + + // + item = buffer[bufferSize - 1]; + + // + result = true; + return result; +} +bool GetLastItem( + datetime &item, // Holds Result + datetime &buffer[] // Specified Buffer +) +{ + // + bool result = false; + + // + int bufferSize = ArraySize(buffer); + if (bufferSize <= 0) + { + return result; + } + + // + item = buffer[bufferSize - 1]; + + // + result = true; + return result; +} + +// +void Add( + int item, // item want to add + int &buffer[] // Destination buffer +) +{ + // + ArrayResize( + buffer, + ArraySize(buffer) + 1); + + // + buffer[ArraySize(buffer) - 1] = item; +} +void Add( + ulong item, // item want to add + ulong &buffer[] // Destination buffer +) +{ + // + ArrayResize( + buffer, + ArraySize(buffer) + 1); + + // + buffer[ArraySize(buffer) - 1] = item; +} +void Add( + string item, // item want to add + string &buffer[] // Destination buffer +) +{ + // + ArrayResize( + buffer, + ArraySize(buffer) + 1); + + // + buffer[ArraySize(buffer) - 1] = item; +} +void Add( + double item, // item want to add + double &buffer[] // Destination buffer +) +{ + // + ArrayResize( + buffer, + ArraySize(buffer) + 1); + + // + buffer[ArraySize(buffer) - 1] = item; +} +void Add( + XOHCL &item, // item want to add + XOHCL &buffer[] // Destination buffer +) +{ + // + ArrayResize( + buffer, + ArraySize(buffer) + 1); + + // + buffer[ArraySize(buffer) - 1] = item; +} +void Add( + datetime &item, // item want to add + datetime &buffer[] // Destination buffer +) +{ + // + ArrayResize( + buffer, + ArraySize(buffer) + 1); + + // + buffer[ArraySize(buffer) - 1] = item; +} + +// +// 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); + } +} + +// +// Converts a Buffer to String Representation ... +string ToString( + const int &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; +} +string ToString( + const double &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; +} +string ToString( + const string &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; +} +string ToString( + const datetime &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; +} +template +string ToString(T value) +{ + return (string)value; +} + +// +// Converts String to boolean ... +bool ToBoolean(string value) +{ + // + bool result = false; + + // + if (StringLen(value) <= 0) + { + return result; + } + + // + StringToLower(value); + result = value == "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; +} + +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; +} + +// +// Split an String Representation of an Array ... +void SplitContent( + string &result[], // Hold Result ... + string content, // Source ... + string separator = ",", // Separator ... + bool forceCleanResult = true // Clean Result ... +) +{ + // + if (forceCleanResult) + { + Clean(result); + } + + // + if (separator == NULL || StringLen(separator) == 0) + { + separator = ","; + } + + // + if (StringLen(content) == 0) + { + return; + } + + // + StringSplit( + content, + StringGetCharacter( + separator, + 0), + result); +} + +// +// 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; +} + +// +// Normalize a give Volume ... +double NormalizeVolume( + double volume, // desired volume to normalize + string symbol = NULL, // Specified Symbol for Normalization + int mLength = 2 // Length of Digits +) +{ + // + double result = volume; + + // + // Normalize Symbol ... + if (StringLen(symbol) == 0) + { + symbol = _Symbol; + } + + // + // Normalize Digits ... + int digits = GetDigits(symbol); + mLength = + mLength == 0 || mLength > digits + ? digits + : MathMin(mLength, digits); + + // + // Normalize Volume ... + result = NormalizeDouble(result, mLength); + + // + double maxAvailableVolume = SymbolInfoDouble(symbol, SYMBOL_VOLUME_MAX); + double minAvailableVolume = SymbolInfoDouble(symbol, SYMBOL_VOLUME_MIN); + + // + // Validate Result ... + if (result > maxAvailableVolume) + { + result = maxAvailableVolume; + } + else if (result < minAvailableVolume) + { + result = minAvailableVolume; + } + + // + return result; +} + +// +// Normallize Price ... +double NormalizePrice( + double price, // desired Price for normalization + string symbol = NULL // Specified Symbol for Normalization +) +{ + // + double result = 0; + + // + // Mormalize Symbol ... + if (StringLen(symbol) == 0) + { + symbol = _Symbol; + } + + // + int digits = GetDigits(symbol); + result = NormalizeDouble(price, digits); + + // + return result; +} + +// +// Do All Normalization on Specific Signal ... +void NormalizeSignal(XSignal &signal) +{ + // + // ENTRY ... + if (signal.entry > 0) + { + signal.entry = NormalizePrice(signal.entry, signal.symbol); + } + + // + // TP ... + if (signal.tp > 0) + { + signal.tp = NormalizePrice(signal.tp, signal.symbol); + } + + // + // SL ... + if (signal.sl > 0) + { + signal.sl = NormalizePrice(signal.sl, signal.symbol); + } + + // + // VOLUME ... + if (signal.volume > 0) + { + signal.volume = NormalizeVolume(signal.volume, signal.symbol); + } +} + +// +// Check Expert Running in Testing Mode or not ... +bool IsRunningOnTestMode() +{ + // + bool result = false; + + // + // check programm mode ... + result = MQL5InfoInteger(MQL5_TESTING); + + // + return result; +} + +// +// Calculate Volume Weighted Moving Average ... +double iVWMA( + double price, + double volume, + int period, + int i, + int bars, + int instance = 0 // +) +{ +#define ¤ instance +#ifdef _averageInstances +#define _functionInstances _averageInstances +#else #define _functionInstances 1 +#endif + struct sVwmaArrayStruct + { + double price; + double volume; + double sump; + double sumv; + }; + static sVwmaArrayStruct m_array[][_functionInstances]; + static int m_arraySize = 0; + if (m_arraySize < bars) + { + int _res = ArrayResize(m_array, bars + 500); + if (_res <= bars) + return (0); + m_arraySize = _res; + } + + // + //--- + // + + if (volume == 0) + volume = 1; + m_array[i][¤].price = volume * price; + m_array[i][¤].volume = volume; + if (i > period) + { + m_array[i][¤].sump = m_array[i - 1][¤].sump + m_array[i][¤].price - m_array[i - period][¤].price; + m_array[i][¤].sumv = m_array[i - 1][¤].sumv + volume - m_array[i - period][¤].volume; + } + else + { + m_array[i][¤].sump = m_array[i][¤].price; + m_array[i][¤].sumv = m_array[i][¤].volume; + for (int k = 1; k < period && i >= k; k++) + { + m_array[i][¤].sump += m_array[i - k][¤].price; + m_array[i][¤].sumv += m_array[i - k][¤].volume; + } + } + return (m_array[i][¤].sump / m_array[i][¤].sumv); + + // + //--- + // + +#undef ¤ #undef _functionInstances +} + +// +// Date Time Manipulation Functions ... +// + +// +// 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; +} + +// +// Retrieve Specified Candle Time ... +datetime GetCandleTime( + string symbol = "", // Specify Symbol + ENUM_TIMEFRAMES period = NULL, // Specify TimeFrame + int bar_index = 0 // Specify Bar Index +) +{ + // + // Validate and Normalize Args ... + + // + // Normalize Symbol ... + symbol = StringLen(symbol) == 0 + ? _Symbol + : symbol; + + // + // Normalize Period ... + period = period == NULL + ? _Period + : period; + + // + // Retrieve Bar Time ... + datetime result = iTime( + symbol, + period, + bar_index); + + // + return result; +} + +// +// Retrieve Specified Candle Time ... +ulong GetCandleTimeAsSeconds( + string symbol = "", // Specify Symbol + ENUM_TIMEFRAMES period = NULL, // Specify TimeFrame + int bar_index = 0 // Specify Bar Index +) +{ + // + // Retrieve Bar Time ... + datetime time = GetCandleTime( + symbol, + period, + bar_index); + + // + ulong result = TimeToSeconds(time); + + // + return result; +} + +// +// Retrieve Specified Candle Time ... +ulong GetCandleTimeAsMilliSeconds( + string symbol = "", // Specify Symbol + ENUM_TIMEFRAMES period = NULL, // Specify TimeFrame + int bar_index = 0 // Specify Bar Index +) +{ + // + // Retrieve Bar Time ... + datetime time = GetCandleTime( + symbol, + period, + bar_index); + + // + ulong result = TimeToMilliSeconds(time); + + // + return result; +} + +// +// Retrieve a Candle Time Structure ... +MqlDateTime GetCandleTimeStruct( + string symbol = "", // Specify Symbol + ENUM_TIMEFRAMES period = NULL, // Specify TimeFrame + int bar_index = 0 // Specify Bar Index +) +{ + // + MqlDateTime result = {}; + + // + // Retrieve Bar Time ... + datetime barTime = GetCandleTime( + symbol, + period, + bar_index); + + // + // Convert to Structure ... + TimeToStruct(barTime, result); + + // + return result; +} + +// +// Retrieve Number of Candles in a Day ... +int GetDailyCandleCount(ENUM_TIMEFRAMES mPeriod) +{ + // + int seconds = PeriodSeconds(mPeriod); + + // + int daySeconds = 24 * 60 * 60; + + // + int result = daySeconds / seconds; + + // + return result; +} + +int GetDailyCandleCount() +{ + // + int result = GetDailyCandleCount(_Period); + + // + return result; +} + +// +// +// + +// +// Holds Month ... +static int xMonth = -1; + +// +// Holds Day Of Week ... +static int xDayOfWeek = -1; +static int xForWeekDay = -1; + +// +// Holds Day ... +static int xDay = -1; + +// +// Holds Hour ... +static int xHour = -1; + +// +// Reset Timing Variables ... +void ResetTiming() +{ + // + xHour = -1; + xDay = -1; + xDayOfWeek = -1; + xMonth = -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; +} + +// +// Find Hindmost Time Frame ... +ENUM_TIMEFRAMES GetHindmostTimeFrame( + ENUM_TIMEFRAMES mPeriod // Specified Period +) +{ + // + ENUM_TIMEFRAMES result = NULL; + + // + // Normalize Period ... + if ( + mPeriod < 0 || + mPeriod == NULL) + { + mPeriod = _Period; + } + + // + switch (mPeriod) + { + // + case PERIOD_M1: + case PERIOD_M2: + case PERIOD_M3: + case PERIOD_M4: + result = PERIOD_H4; + break; + + // + case PERIOD_M5: + case PERIOD_M6: + case PERIOD_M10: + case PERIOD_M12: + result = PERIOD_H8; + break; + + // + case PERIOD_M15: + case PERIOD_M20: + result = PERIOD_H12; + break; + + // + case PERIOD_M30: + result = PERIOD_D1; + break; + + // + case PERIOD_H1: + case PERIOD_H2: + case PERIOD_H3: + result = PERIOD_W1; + break; + + // + case PERIOD_H4: + case PERIOD_H6: + case PERIOD_H8: + result = PERIOD_MN1; + break; + + // + case PERIOD_H12: + result = PERIOD_MN1; + break; + + // + case PERIOD_D1: + result = PERIOD_MN1; + break; + + // + case PERIOD_W1: + result = PERIOD_MN1; + break; + + // + default: + result = PERIOD_MN1; + break; + } + + // + return result; +} + +// +// Find Farest Time Frame ... +ENUM_TIMEFRAMES GetFarestTimeFrame( + ENUM_TIMEFRAMES mPeriod // Specified Period +) +{ + // + ENUM_TIMEFRAMES result = NULL; + + // + // Normalize Period ... + if ( + mPeriod < 0 || + mPeriod == NULL) + { + mPeriod = _Period; + } + + // + switch (mPeriod) + { + // + case PERIOD_M1: + case PERIOD_M2: + 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_H3; + break; + + // + case PERIOD_M30: + result = PERIOD_H4; + break; + + // + case PERIOD_H1: + case PERIOD_H2: + case PERIOD_H3: + result = PERIOD_H8; + break; + + // + case PERIOD_H4: + case PERIOD_H6: + case PERIOD_H8: + result = PERIOD_D1; + break; + + // + case PERIOD_H12: + result = PERIOD_MN1; + break; + + // + case PERIOD_D1: + result = PERIOD_MN1; + break; + + // + case PERIOD_W1: + result = PERIOD_MN1; + break; + + // + default: + result = PERIOD_MN1; + break; + } + + // + return result; +} + +// +// Find Medium Time Frame ... +ENUM_TIMEFRAMES GetMediestTimeFrame( + ENUM_TIMEFRAMES mPeriod // Specified Period +) +{ + // + ENUM_TIMEFRAMES result = NULL; + + // + // Normalize Period ... + if ( + mPeriod < 0 || + mPeriod == NULL) + { + mPeriod = _Period; + } + + // + switch (mPeriod) + { + // + case PERIOD_M1: + case PERIOD_M2: + case PERIOD_M3: + case PERIOD_M4: + result = PERIOD_M12; + break; + + // + case PERIOD_M5: + case PERIOD_M6: + case PERIOD_M10: + case PERIOD_M12: + result = PERIOD_M30; + break; + + // + case PERIOD_M15: + case PERIOD_M20: + result = PERIOD_H1; + break; + + // + case PERIOD_M30: + result = PERIOD_H2; + break; + + // + case PERIOD_H1: + case PERIOD_H2: + case PERIOD_H3: + result = PERIOD_H6; + break; + + // + case PERIOD_H4: + case PERIOD_H6: + case PERIOD_H8: + result = PERIOD_H12; + break; + + // + case PERIOD_H12: + result = PERIOD_W1; + break; + + // + case PERIOD_D1: + result = PERIOD_MN1; + break; + + // + case PERIOD_W1: + result = PERIOD_MN1; + break; + + // + default: + result = PERIOD_MN1; + break; + } + + // + return result; +} + +// +// Find Nearest Time Frame ... +ENUM_TIMEFRAMES GetNearestTimeFrame( + ENUM_TIMEFRAMES mPeriod // Specified Period +) +{ + // + ENUM_TIMEFRAMES result = NULL; + + // + // Normalize Period ... + if ( + mPeriod < 0 || + mPeriod == NULL) + { + mPeriod = _Period; + } + + // + switch (mPeriod) + { + // + case PERIOD_M1: + case PERIOD_M2: + case PERIOD_M3: + case PERIOD_M4: + result = PERIOD_M5; + 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_M30: + result = PERIOD_H1; + break; + + // + case PERIOD_H1: + case PERIOD_H2: + case PERIOD_H3: + result = PERIOD_H4; + break; + + // + case PERIOD_H4: + case PERIOD_H6: + case PERIOD_H8: + result = PERIOD_H12; + break; + + // + case PERIOD_H12: + result = PERIOD_D1; + break; + + // + case PERIOD_D1: + result = PERIOD_W1; + break; + + // + case PERIOD_W1: + result = PERIOD_MN1; + break; + + // + default: + result = PERIOD_MN1; + break; + } + + // + return result; +} + +// +// 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 ... +) +{ + // + // Normalize Arg ... + + // + if ( + mSymbol == NULL || + StringLen(mSymbol) == 0) + { + mSymbol = _Symbol; + } + + // + if ( + mPeriod < 0 || + mPeriod == NULL) + { + mPeriod = _Period; + } + + // + if ( + mTime < 0 || + mTime == NULL) + { + mTime = TimeCurrent(); + } + + // + int barIndex = iBarShift( + mSymbol, + mPeriod, + mTime, + false); + + // + datetime result = iTime( + mSymbol, + mPeriod, + barIndex); + + // + return result; +} + +// +struct XCandleRemains +{ + // + int days; + int hours; + int minutes; + int seconds; +}; + +// +string ToString( + XCandleRemains &item, + string dayId = "d", + string hourId = "h", + string minuteId = "m", + string secondId = "s", + string idSeparator = ": ", + string separator = ", ", + bool ignoreZeroValues = true) +{ + // + string result = ""; + + // + // Days ... + if (!ignoreZeroValues || item.days > 0) + { + result += dayId + idSeparator + (string)item.days + separator; + } + + // + // Hours ... + if (!ignoreZeroValues || item.hours > 0) + { + // + string strHour = ToString(item.hours); + if (StringLen(strHour) == 1) + { + strHour = "0" + strHour; + } + + // + result += hourId + idSeparator + strHour + separator; + } + + // + // Minutes ... + if (!ignoreZeroValues || item.minutes > 0) + { + // + string strMinute = ToString(item.minutes); + if (StringLen(strMinute) == 1) + { + strMinute = "0" + strMinute; + } + + // + result += minuteId + idSeparator + strMinute + separator; + } + + // + // Seconds ... + if (!ignoreZeroValues || item.seconds > 0) + { + // + string strSec = ToString(item.seconds); + if (StringLen(strSec) == 1) + { + strSec = "0" + strSec; + } + + // + result += secondId + idSeparator + strSec; + } + + // + return result; +} + +// +// Retrieve Specific Candles Ramained Time ... +void GetCandleRemainsTime( + XCandleRemains &result, // Holds Result ... + string mSymbol = NULL, // Specified Symbol ... + ENUM_TIMEFRAMES mPeriod = NULL, // Specified Period ... + int mBarIndex = 0 // Specified Bar Index ... +) +{ + // + int minuteSecoonds = 60; + int hourSeconds = minuteSecoonds * 60; + int daySeconds = 24 * hourSeconds; + + // + int periodSeconds = PeriodSeconds( + mPeriod); + datetime startTime = GetCandleTime( + mSymbol, + mPeriod, + mBarIndex); + + // + int secondsDiff = (int)startTime + periodSeconds - (int)TimeCurrent(); + + // + int days = 0; + int hours = 0; + int minutes = 0; + int seconds = 0; + + // + 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.days = days; + result.hours = hours; + result.minutes = minutes; + result.seconds = seconds; +} + +// +// 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 period) +{ + // + string result = ""; + + // + string mPStr = EnumToString(period); + + string mPStrParts[]; + int partsCount = StringSplit( + mPStr, + StringGetCharacter("_", 0), + mPStrParts); + if (partsCount <= 0) + { + return result; + } + + // + result = mPStrParts[1]; + + // + return result; +} + +// +// TYPES ... +// + +// +// Retrieve Specific Object Types Name ... +template +string GetTypeName(const T &t) +{ + return typename(T); +} + +// +// END Provided Functions ... +// diff --git a/MQLTestWorkspace/X121/14030217/Libraries/x-saherelm.draw.lib.ex5 b/MQLTestWorkspace/X121/14030217/Libraries/x-saherelm.draw.lib.ex5 new file mode 100644 index 0000000..1be4338 Binary files /dev/null and b/MQLTestWorkspace/X121/14030217/Libraries/x-saherelm.draw.lib.ex5 differ diff --git a/MQLTestWorkspace/X121/14030217/Libraries/x-saherelm.draw.lib.mq5 b/MQLTestWorkspace/X121/14030217/Libraries/x-saherelm.draw.lib.mq5 new file mode 100644 index 0000000..7771f54 --- /dev/null +++ b/MQLTestWorkspace/X121/14030217/Libraries/x-saherelm.draw.lib.mq5 @@ -0,0 +1,2462 @@ +/////////////////////////////////////////////////////// +// +// 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 + +// +// START Inputs ... +// +// +// END Inputs ... +// + +// +// Include Logger Library ... +#include "x-saherelm.log.lib.mq5" +#include "x-saherelm.common.lib.mq5" + +// +// START Global Definitions: Variables, Properties and etc ... +// +string drawPrefix = "X-OBJ"; +// +// END Global Definitions: Variables, Properties and etc ... +// + +// +// START Provided Functions ... +// +// +// DeInitial Library if required ... +void OnDeinitDrawLibrary() +{ + RemoveDraws(); +} + +// +// remove drawn objects ... +void RemoveDraws( + string tag = NULL, + int 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, + int 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, + int 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; +} +// +// END Provided Functions ... +// + +// +// START Regular Draws ... +// + +// +// START 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 ... +) +{ + // + // 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 ... + if (!ObjectCreate(chartID, objName, OBJ_ARROW, subWindow, time, price)) + { + // + string message = + __FUNCTION__ + + ": failed to create an arrow! Error code = " + + (string)GetLastError(); + + // + LogMessage(message); + + // + return false; + } + + // + // 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 true; +} + +// +// 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 +) +{ + // + // 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); + } + + // + // reset the error value + ResetLastError(); + + // + // move the anchor point ... + if (!ObjectMove(chartID, name, 0, time, price)) + { + // + string message = + __FUNCTION__ + + ": failed to move the anchor point! Error code = " + + (string)GetLastError(); + + // + LogMessage(message); + + // + return false; + } + + // + // successful execution ... + return true; +} + +// +// Delete an arrow ... +bool DeleteArrow( + const long chartID = 0, // chart's ID + const string name = "Arrow" // arrow name +) +{ + // + // reset the error value ... + ResetLastError(); + + // + // delete an arrow ... + if (!ObjectDelete(chartID, name)) + { + // + string message = + __FUNCTION__ + + ": failed to delete an arrow! Error code = " + + (string)GetLastError(); + + // + LogMessage(message); + + // + return false; + } + + // + // successful execution ... + return true; +} + +// +// 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 +) +{ + // + // reset the error value ... + ResetLastError(); + + // + // change the arrow code ... + if (!ObjectSetInteger(chartID, name, OBJPROP_ARROWCODE, code)) + { + // + string message = + __FUNCTION__ + + ": failed to change the arrow code! Error code = " + + (string)GetLastError(); + + // + LogMessage(message); + + // + return false; + } + + // + // successful execution ... + return true; +} + +// +// 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 +) +{ + // + // reset the error value ... + ResetLastError(); + + // + // change anchor type ... + if (!ObjectSetInteger(chartID, name, OBJPROP_ANCHOR, anchor)) + { + // + string message = + __FUNCTION__ + + ": failed to change anchor type! Error code = " + + (string)GetLastError(); + + // + LogMessage(message); + + // + return false; + } + + // + // successful execution ... + return true; +} + +// +// 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); + } +} +// +// END Arrow Functions ... +// + +// +// START 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 +) +{ + // + // if the price is not set, set it at the current Bid price level ... + if (!price) + { + price = SymbolInfoDouble(Symbol(), SYMBOL_BID); + } + + // + // reset the error value ... + ResetLastError(); + + // + // Normalize Name ... + string objName = drawPrefix + "_" + name; + + // + // create a horizontal line ... + if (!ObjectCreate(chartID, objName, OBJ_HLINE, subWindow, 0, price)) + { + // + string message = + __FUNCTION__ + + ": failed to create a horizontal line! Error code = " + + (string)GetLastError(); + + // + LogMessage(message); + + // + return false; + } + + // + // 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 true; +} + +// +// Move horizontal line ... +bool MoveHorizontalLine( + const long chartID = 0, // chart's ID + const string name = "HLine", // line name + double price = 0 // line price +) +{ + // + // if the line price is not set, move it to the current Bid price level ... + if (!price) + { + price = SymbolInfoDouble(Symbol(), SYMBOL_BID); + } + + // + // reset the error value ... + ResetLastError(); + + // + // move a horizontal line ... + if (!ObjectMove(chartID, name, 0, 0, price)) + { + // + string message = + __FUNCTION__ + + ": failed to move the horizontal line! Error code = " + + (string)GetLastError(); + + // + LogMessage(message); + + // + return false; + } + + // + // successful execution ... + return true; +} + +// +// Delete a horizontal line ... +bool DeleteHorizontalLine( + const long chartID = 0, // chart's ID + const string name = "HLine" // line name +) +{ + // + // reset the error value ... + ResetLastError(); + + // + // delete a horizontal line ... + if (!ObjectDelete(chartID, name)) + { + // + string message = + __FUNCTION__ + + ": failed to delete a horizontal line! Error code = " + + (string)GetLastError(); + + // + LogMessage(message); + + // + return false; + } + + // + // successful execution ... + return true; +} +// +// END Horizontal Line Functions ... +// + +// +// START 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 +) +{ + // + // if the line time is not set, draw it via the last bar ... + if (!time) + { + time = TimeCurrent(); + } + + // + // reset the error value + ResetLastError(); + + // + // Normalize Name ... + string objName = drawPrefix + "_" + name; + + // + // create a vertical line ... + if (!ObjectCreate(chartID, objName, OBJ_VLINE, subWindow, time, 0)) + { + // + string message = + __FUNCTION__ + + ": failed to create a vertical line! Error code = " + + (string)GetLastError(); + + // + LogMessage(message); + + // + return false; + } + + // + // 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 true; +} + +// +// Move the vertical line ... +bool MoveVerticalLine( + const long chartID = 0, // chart's ID + const string name = "VLine", // line name + datetime time = 0 // line time +) +{ + // + // if line time is not set, move the line to the last bar ... + if (!time) + { + time = TimeCurrent(); + } + + // + // reset the error value ... + ResetLastError(); + + // + // move the vertical line ... + if (!ObjectMove(chartID, name, 0, time, 0)) + { + // + string message = + __FUNCTION__ + + ": failed to move the vertical line! Error code = " + + (string)GetLastError(); + + // + LogMessage(message); + + // + return false; + } + + // + // successful execution ... + return true; +} + +// +// Delete the vertical line ... +bool DeleteVerticalLine( + const long chartID = 0, // chart's ID + const string name = "VLine" // line name +) +{ + // + // reset the error value ... + ResetLastError(); + + // + // delete the vertical line ... + if (!ObjectDelete(chartID, name)) + { + // + string message = + __FUNCTION__ + + ": failed to delete the vertical line! Error code = " + + (string)GetLastError(); + + // + LogMessage(message); + + // + return false; + } + + // + // successful execution ... + return true; +} +// +// END Vertical Line Functions ... +// + +// +// START 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 +) +{ + // + // reset the error value ... + ResetLastError(); + + // + // Normalize Name ... + string objName = drawPrefix + "_" + name; + + // + // + // create a rectangle label + if (!ObjectCreate(chartID, objName, OBJ_RECTANGLE_LABEL, subWindow, 0, 0)) + { + // + string message = + __FUNCTION__ + + ": failed to create a rectangle label! Error code = " + + (string)GetLastError(); + + // + LogMessage(message); + + // + return false; + } + + // + // 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 true; +} + +// +// 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 +) +{ + // + // reset the error value ... + ResetLastError(); + + // + // move the rectangle label ... + if (!ObjectSetInteger(chartID, name, OBJPROP_XDISTANCE, x)) + { + // + string message = + __FUNCTION__ + + ": failed to move X coordinate of the label! Error code = " + + (string)GetLastError(); + + // + LogMessage(message); + + // + return false; + } + + // + if (!ObjectSetInteger(chartID, name, OBJPROP_YDISTANCE, y)) + { + // + string message = + __FUNCTION__ + + ": failed to move Y coordinate of the label! Error code = " + + (string)GetLastError(); + + // + return false; + } + + // + // successful execution ... + return true; +} + +// +// Delete the rectangle label ... +bool DeleteRectangleLabel( + const long chartID = 0, // chart's ID + const string name = "RectLabel" // label name +) +{ + // + // reset the error value ... + ResetLastError(); + + // + // delete the label ... + if (!ObjectDelete(chartID, name)) + { + // + string message = + __FUNCTION__ + + ": failed to delete a rectangle label! Error code = " + + (string)GetLastError(); + + // + LogMessage(message); + + // + return false; + } + + // + // successful execution ... + return true; +} + +// +// 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 +) +{ + // + // reset the error value ... + ResetLastError(); + + // + // change label size ... + if (!ObjectSetInteger(chartID, name, OBJPROP_XSIZE, width)) + { + // + string message = + __FUNCTION__ + + ": failed to change the label's width! Error code = " + + (string)GetLastError(); + + // + LogMessage(message); + + // + return false; + } + + // + if (!ObjectSetInteger(chartID, name, OBJPROP_YSIZE, height)) + { + // + string message = + __FUNCTION__ + + ": failed to change the label's height! Error code = " + + (string)GetLastError(); + + // + LogMessage(message); + + // + return false; + } + + // + // successful execution ... + return true; +} + +// +// 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 +) +{ + // + // reset the error value ... + ResetLastError(); + + // + // change border type ... + if (!ObjectSetInteger(chartID, name, OBJPROP_BORDER_TYPE, border)) + { + // + string message = + __FUNCTION__ + + ": failed to change the border type! Error code = " + + (string)GetLastError(); + + // + LogMessage(message); + + // + return false; + } + + // + // successful execution ... + return true; +} +// +// END RectangleLabel Functions ... +// + +// +// START 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 +) +{ + // + // set anchor points' coordinates if they are not set ... + ChangeTrendLineEmptyPoints( + time1, + price1, + time2, + price2); + + // + // reset the error value ... + ResetLastError(); + + // + // Normalize Name ... + string objName = drawPrefix + "_" + name; + + // + // create a trend line by the given coordinates ... + if (!ObjectCreate(chartID, objName, OBJ_TREND, subWindow, time1, price1, time2, price2)) + { + // + string message = + __FUNCTION__ + + ": failed to create a trend line! Error code = " + + (string)GetLastError(); + + // + LogMessage(message); + + // + return false; + } + + // + // 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 true; +} + +// +// 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 +) +{ + // + // 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); + } + + // + // reset the error value ... + ResetLastError(); + + // + // move trend line's anchor point ... + if (!ObjectMove(chartID, name, pointindex, time, price)) + { + // + string message = + __FUNCTION__ + + ": failed to move the anchor point! Error code = " + + (string)GetLastError(); + + // + LogMessage(message); + + // + return false; + } + + // + // successful execution ... + return true; +} + +// +// The function deletes the trend line from the chart ... +bool DeleteTrendLine( + const long chartID = 0, // chart's ID + const string name = "TrendLine" // line name +) +{ + // + // reset the error value ... + ResetLastError(); + + // + // delete a trend line ... + if (!ObjectDelete(chartID, name)) + { + // + string message = + __FUNCTION__ + + ": failed to delete a trend line! Error code = " + + (string)GetLastError(); + + // + LogMessage(message); + + // + return false; + } + + // + // successful execution ... + return true; +} + +// +// 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; + } +} +// +// END TrendLine Functions ... +// + +// +// START 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 +) +{ + // + // set anchor point coordinates if they are not set ... + ChangeTextEmptyPoint(time, price); + + // + // reset the error value ... + ResetLastError(); + + // + // Normalize Name ... + string objName = drawPrefix + "_" + name; + + // + // + // create Text object + if (!ObjectCreate(chartID, objName, OBJ_TEXT, subWindow, time, price)) + { + // + string message = + __FUNCTION__ + + ": failed to create \"Text\" object! Error code = " + + (string)GetLastError(); + + // + LogMessage(message); + + // + return false; + } + + // + // 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 true; +} + +// +// 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 +) +{ + // + // + // 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); + } + + // + // reset the error value ... + ResetLastError(); + + // + // move the anchor point .. + if (!ObjectMove(chartID, name, 0, time, price)) + { + // + string message = + __FUNCTION__ + + ": failed to move the anchor point! Error code = " + + (string)GetLastError(); + + // + LogMessage(message); + + // + return false; + } + + // + // successful execution ... + return true; +} + +// +// Change the object text ... +bool ChangeText( + const long chartID = 0, // chart's ID + const string name = "Text", // object name + const string text = "Text" // text +) +{ + // + // reset the error value ... + ResetLastError(); + + // + // change object text ... + if (!ObjectSetString(chartID, name, OBJPROP_TEXT, text)) + { + // + string message = + __FUNCTION__ + + ": failed to change the text! Error code = " + + (string)GetLastError(); + + // + LogMessage(message); + + // + return false; + } + + // + // successful execution ... + return true; +} + +// +// Delete Text object ... +bool DeleteText( + const long chartID = 0, // chart's ID + const string name = "Text" // object name +) +{ + // + // reset the error value ... + ResetLastError(); + + // + // delete the object ... + if (!ObjectDelete(chartID, name)) + { + // + string message = + __FUNCTION__ + + ": failed to delete \"Text\" object! Error code = " + + (string)GetLastError(); + + // + LogMessage(message); + + // + return false; + } + + // + // successful execution + return true; +} + +// +// 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); + } +} +// +// END Text Functions ... +// + +// +// START 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 +) +{ + // + // set anchor points' coordinates if they are not set ... + ChangeFibonacciEmptyPoints(time1, price1, time2, price2); + + // + // reset the error value ... + ResetLastError(); + + // + // Normalize Name ... + string objName = drawPrefix + "_" + name; + + // + // Create Fibonacci Retracement by the given coordinates ... + if (!ObjectCreate(chartID, objName, OBJ_FIBO, subWindow, time1, price1, time2, price2)) + { + // + string message = + __FUNCTION__ + + ": failed to create \"Fibonacci Retracement\"! Error code = " + + (string)GetLastError(); + + // + LogMessage(message); + + // + return false; + } + + // + // 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 true; +} + +// +// 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 +) +{ + // + // set anchor points' coordinates if they are not set ... + ChangeFibonacciEmptyPoints(time1, price1, time2, price2); + + // + // reset the error value ... + ResetLastError(); + + // + // Normalize Name ... + string objName = drawPrefix + "_" + name; + + // + // Create Fibonacci Retracement by the given coordinates ... + if (!ObjectCreate(chartID, name, OBJ_FIBO, subWindow, time1, price1, time2, price2)) + { + // + string message = + __FUNCTION__ + + ": failed to create \"Fibonacci Retracement\"! Error code = " + + (string)GetLastError(); + + // + LogMessage(message); + + // + return false; + } + + // + // 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 ... + bool 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 +) +{ + // + // check array sizes ... + if ( + levels != ArraySize(colors) || + levels != ArraySize(styles) || + levels != ArraySize(widths) || + levels != ArraySize(widths)) + { + // + string message = + __FUNCTION__ + + ": array length does not correspond to the number of levels, error!"; + + // + LogMessage(message); + + // + return false; + } + + // + // 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 true; +} + +// +// 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 +) +{ + // + // 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); + } + + // + // reset the error value ... + ResetLastError(); + + // + // move the anchor point ... + if (!ObjectMove(chartID, name, pointIndex, time, price)) + { + // + string message = + __FUNCTION__ + + ": failed to move the anchor point! Error code = " + + (string)GetLastError(); + + // + LogMessage(message); + + // + return false; + } + + // + // successful execution ... + return true; +} + +// +// Delete Fibonacci Retracement ... +bool DeleteFibonachi( + const long chartID = 0, // chart's ID + const string name = "Fibonacci" // object name +) +{ + // + // reset the error value ... + ResetLastError(); + + // + // delete the object ... + if (!ObjectDelete(chartID, name)) + { + // + string message = + __FUNCTION__ + + ": failed to delete \"Fibonacci Retracement\"! Error code = " + + (string)GetLastError(); + + // + LogMessage(message); + + // + return false; + } + + // + // successful execution ... + return true; +} + +// +// 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); + } +} +// +// END Fibonacci Functions ... +// + +// +// START 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 +) +{ + // + if (!time) + { + time = TimeCurrent(); + } + + // + ResetLastError(); + + // + if (!ObjectCreate(chartID, name, OBJ_EVENT, subWindow, time, 0)) + { + // + string message = + __FUNCTION__ + + ": failed to create \"Event\" object! Error code = " + + (string)GetLastError(); + + // + LogMessage(message); + + // + return false; + } + + // + // 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 true; +} + +// +// Change Event object text +bool EventTextChange( + const long chartID = 0, // chart's ID + const string name = "Event", // event name + const string text = "Content" // text +) +{ + // + // reset the error value + ResetLastError(); + + // + // change object text + if (!ObjectSetString(chartID, name, OBJPROP_TEXT, text)) + { + // + string message = + __FUNCTION__ + + ": failed to change the text! Error code = " + + (string)GetLastError(); + + // + LogMessage(message); + + // + return false; + } + + // + // successful execution + return true; +} + +// +// Move Event object +bool EventMove( + const long chartID = 0, // chart's ID + const string name = "Event", // event name + datetime time = 0 // time +) +{ + // + // if time is not set, move event to the last bar + if (!time) + { + time = TimeCurrent(); + } + + // + // reset the error value + ResetLastError(); + + // + // move the object + if (!ObjectMove(chartID, name, 0, time, 0)) + { + // + string message = + __FUNCTION__ + + ": failed to move \"Event\" object! Error code = " + + (string)GetLastError(); + + // + LogMessage(message); + + // + return false; + } + + // + // successful execution + return true; +} + +// +// Delete Event object +bool EventDelete( + const long chartID = 0, // chart's ID + const string name = "Event" // event name +) +{ + // + // reset the error value + ResetLastError(); + + // + // delete the object + if (!ObjectDelete(chartID, name)) + { + // + string message = + __FUNCTION__ + + ": failed to delete \"Event\" object! Error code = " + + (string)GetLastError(); + + // + LogMessage(message); + + // + return false; + } + + // + // successful execution + return true; +} + +// +// END Event Functions ... +// + +// +// START 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; +} +// +// END Button Functions ... +// + +// +// END Regular Draws ... +// + +// +// START 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); +} + +// +// Retrieve Chart Size in Pixel ... +struct XSize +{ + long width; + long height; + + // + int x; + int y; + int w; + int h; + + // + int wStep; + int hStep; +}; + +// +// 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; +} + +// +// END Chart Style Drawers ... +// \ No newline at end of file diff --git a/MQLTestWorkspace/X121/14030217/Libraries/x-saherelm.http.lib.ex5 b/MQLTestWorkspace/X121/14030217/Libraries/x-saherelm.http.lib.ex5 new file mode 100644 index 0000000..87463a3 Binary files /dev/null and b/MQLTestWorkspace/X121/14030217/Libraries/x-saherelm.http.lib.ex5 differ diff --git a/MQLTestWorkspace/X121/14030217/Libraries/x-saherelm.http.lib.mq5 b/MQLTestWorkspace/X121/14030217/Libraries/x-saherelm.http.lib.mq5 new file mode 100644 index 0000000..97f7ac0 --- /dev/null +++ b/MQLTestWorkspace/X121/14030217/Libraries/x-saherelm.http.lib.mq5 @@ -0,0 +1,177 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Http Library +// ------------------------------------------ +// Name: XHttp +// Description: provide http communication +// 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 + +// +// START Model Definition ... +// +enum X_HTTP_METHOD +{ + X_HTTP_GET, + X_HTTP_POST +}; +// +// END Model Definition ... +// + +// +// START Inputs ... +// +// +// END Inputs ... +// + +// +// START Global Definitions: Variables, Properties and etc ... +// +// +// END Global Definitions: Variables, Properties and etc ... +// + +// +// START Provided Functions ... +// +// +// Initial Library if required ... +bool OnInInitHttpLibrary() +{ + return false; +} + +// +// DeInitial Library if required ... +void OnDeinitHttpLibrary() +{ +} + +// +// 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; +} + +// +// 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; + } + + // + result = WebRequest( + strMethod, + url, + headers, + timeout, + payload, + response, + responseHeaders + ); + + // + 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; +} +// +// END Provided Functions ... +// diff --git a/MQLTestWorkspace/X121/14030217/Libraries/x-saherelm.log.lib.ex5 b/MQLTestWorkspace/X121/14030217/Libraries/x-saherelm.log.lib.ex5 new file mode 100644 index 0000000..cf6a0cc Binary files /dev/null and b/MQLTestWorkspace/X121/14030217/Libraries/x-saherelm.log.lib.ex5 differ diff --git a/MQLTestWorkspace/X121/14030217/Libraries/x-saherelm.log.lib.mq5 b/MQLTestWorkspace/X121/14030217/Libraries/x-saherelm.log.lib.mq5 new file mode 100644 index 0000000..3e30eb9 --- /dev/null +++ b/MQLTestWorkspace/X121/14030217/Libraries/x-saherelm.log.lib.mq5 @@ -0,0 +1,1088 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Logger Library +// --------------------------------------- +// Name: XLogger +// Description: provides Logging 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 + +// +// START Inputs ... +// +// input group "Logging"; +// input bool enableLogging = true; // Enable Logging +bool enableLogging = true; // Enable Logging +// +// END Inputs ... +// + +// +// Including Models ... +#include "x-saherelm.models.lib.mq5" + +// +// START Global Definitions: Variables, Properties and etc ... +// +string logTag = "X-Logger"; // LogTag +// +// END Global Definitions: Variables, Properties and etc ... +// + +// +// START Provided Functions ... +// +// +// Logging a Message ... +void LogMessage(string message) +{ + // + if (!enableLogging) + { + return; + } + + // + Print(logTag, " > ", message); +} +void LogMessage(string tag, string message) +{ + // + if (!enableLogging) + { + return; + } + + // + Print(tag, " > ", message); +} + +// +void LogEmptyLine() +{ + LogMessage(" "); +} + +// +void LogError( + int error = -1 // Specific Error +) { + // + if (error <= -1) { + error = GetLastError(); + } + + // + string errorMsg = GetErrorDescription(error); + + // + LogMessage("Error: " + errorMsg); +} + +// +// Logging an Array ... +void LogArray(int &array[]) +{ + // + if (!enableLogging) + { + return; + } + + // + Print(logTag, ">"); + ArrayPrint(array); +} +void LogArray(double &array[]) +{ + // + if (!enableLogging) + { + return; + } + + // + Print(logTag, ">"); + ArrayPrint(array); +} +void LogArray(string &array[]) +{ + // + if (!enableLogging) + { + return; + } + + // + Print(logTag, ">"); + ArrayPrint(array); +} +// +// END Provided Functions ... +// + + +// +// Error Descriptions Functions ... +// + +// +// 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; +} diff --git a/MQLTestWorkspace/X121/14030217/Libraries/x-saherelm.models.lib.ex5 b/MQLTestWorkspace/X121/14030217/Libraries/x-saherelm.models.lib.ex5 new file mode 100644 index 0000000..243afa6 Binary files /dev/null and b/MQLTestWorkspace/X121/14030217/Libraries/x-saherelm.models.lib.ex5 differ diff --git a/MQLTestWorkspace/X121/14030217/Libraries/x-saherelm.models.lib.mq5 b/MQLTestWorkspace/X121/14030217/Libraries/x-saherelm.models.lib.mq5 new file mode 100644 index 0000000..5d26b43 --- /dev/null +++ b/MQLTestWorkspace/X121/14030217/Libraries/x-saherelm.models.lib.mq5 @@ -0,0 +1,303 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Models Library +// --------------------------------------- +// Name: XModels +// Description: provides all required models ... +// +// +// 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 Inputs ... +// +// +// END Inputs ... +// + +// +// START Global Definitions: Variables, Properties and etc ... +// +// +// END Global Definitions: Variables, Properties and etc ... +// + +// +// START Provided Functions ... +// + +// +// How To Calculate Static Volume ... +enum ENUM_STATIC_VOLUME_METHODS +{ + // + // Based On Deposit ... + X_STATIC_VOLUME_BASED_ON_DEPOSIT, + // + // Based On Balance ... + X_STATIC_VOLUME_BASED_ON_BALANCE, +}; + +// +// START Model Definitions ... +// +// +// OHCL Candel Model ... +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, +}; + +// +// 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_ALL, // Min +}; + +// +// 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 +}; + +// +// Model Guard Info ... +struct XGuard +{ + string symbol; + string provider; + ENUM_TIMEFRAMES period; + ENUM_POSITION_TYPE type; + ENUM_X_GUARD_ACTIONS action; + + // + double dblPayLoad; + string strPayload; +}; + +// +// Describe an Specific Candle ... +struct XOHCL +{ + double high; + double open; + double close; + double low; +}; + +// +// Model Support and Resistance +// for Specific Bar ... +struct XOHCLSupRes +{ + // + double res[]; + + // + double sup[]; +}; + +// +// Available Order Modes ... +enum ENUM_X_ORDER_MODES +{ + X_ORDER_MODE_MARKET = 0, // Market Order + X_ORDER_MODE_STOP = 1, // Pending Stop Order + X_ORDER_MODE_LIMIT = 2, // Pending Limit Order + X_ORDER_MODE_STOP_LIMIT = 3, // Pending Stop Limit Order +}; + +// +// Model a Signal ... +struct XSignal +{ + // + string providers[]; + + // + string symbol; + + // + ENUM_TIMEFRAMES period; + + // + ENUM_POSITION_TYPE type; + + // + ENUM_X_ORDER_MODES mode; + + // + double entry; + + // + double riskAmount; + + // + double tp; + + // + double sl; + + // + double r2r; + + // + double volume; + + // + bool calculateTP; + + // + bool ignoreSL; + bool ignoreTP; + + // + bool useSupportAndResistance; + + // + bool useRiskAmountAsVolume; + + // + // Support Signals ... + XSignal supports[]; + + // + XOHCLSupRes supportAndResistance; +}; +// +// EXTENSION Methods ... + +// +// Clear an Specific Signal Item ... +void Clean(XSignal &item) +{ + // + Clean(item.providers); + + // + Clean(item.supports); + + // + Clean(item.supportAndResistance); + + // + item.symbol = ""; + item.type = NULL; + item.mode = NULL; + item.period = NULL; + + // + item.tp = 0; + item.sl = 0; + item.r2r = 0; + item.entry = 0; + item.volume = 0; + item.riskAmount = 0; + + // + item.ignoreSL = false; + item.ignoreTP = false; + item.calculateTP = false; + item.useRiskAmountAsVolume = false; + item.useSupportAndResistance = false; +} + +// +void Clean(XOHCLSupRes &item) +{ + Clean(item.sup); + Clean(item.res); +} + +template +void Add( + T &item, + T &buffer[]) +{ + // + ArrayResize( + buffer, + ArraySize(buffer) + 1); + + // + buffer[ArraySize(buffer) - 1] = item; +} + +template +void Clean(T &buffer[]) +{ + // + ArrayFree(buffer); + ArrayResize(buffer, 0); +} + +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]; + + // + Add( + iSource, + dest); + } +} + +// +// END Provided Functions ... +// diff --git a/MQLTestWorkspace/X121/14030217/Libraries/x-saherelm.seriallizer.lib.ex5 b/MQLTestWorkspace/X121/14030217/Libraries/x-saherelm.seriallizer.lib.ex5 new file mode 100644 index 0000000..d0c83c5 Binary files /dev/null and b/MQLTestWorkspace/X121/14030217/Libraries/x-saherelm.seriallizer.lib.ex5 differ diff --git a/MQLTestWorkspace/X121/14030217/Libraries/x-saherelm.seriallizer.lib.mq5 b/MQLTestWorkspace/X121/14030217/Libraries/x-saherelm.seriallizer.lib.mq5 new file mode 100644 index 0000000..2c7aa24 --- /dev/null +++ b/MQLTestWorkspace/X121/14030217/Libraries/x-saherelm.seriallizer.lib.mq5 @@ -0,0 +1,1273 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Seriallize Library +// --------------------------------------- +// Name: XSeriallizer +// Description: provides Seriallizing EA 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 + +// +#include "../Libraries/x-saherelm.models.lib.mq5" +#include "../Libraries/x-saherelm.common.lib.mq5" +#include "../Classes/x-saherelm.xtrade.class.mq5" +#include "../Classes/x-saherelm.x121.provider.class.mq5" + +// +string XProviderToken = "PRV"; +string XSupportToken = "SP"; +string XSLTrailToken = "SLT"; +string XPeriodToken = "PR"; + +// +string XConfigToken = "XPV"; +string XItemSeparator = "|"; +string XItemContentSeparator = ","; + +// +// PERIOD ... + +// +// Detect a Comment has period or not ... +bool HasPeriod(string comment) +{ + // + bool result = false; + + // + if (StringLen(comment) == 0) + { + return result; + } + + // + int tokenPos = StringFind( + comment, + XPeriodToken); + result = tokenPos >= 0; + + // + return result; +} + +// +// Extract Period String ... +string ExtractPeriodString(string comment) +{ + // + string result = ""; + + // + bool hasPeriod = HasPeriod(comment); + if (!hasPeriod) + { + return result; + } + + // + result = ExtractString( + comment, + XPeriodToken + "(", + ")"); + + // + return result; +} + +// +// Extract Time Frame From Comment ... +ENUM_TIMEFRAMES ExtractPeriod(string comment) +{ + // + ENUM_TIMEFRAMES result = NULL; + + // + if (StringLen(comment) <= 0) + { + return result; + } + + // + string periodStr = ExtractPeriodString(comment); + if (StringLen(periodStr) <= 0) + { + return result; + } + + // + result = ToPeriod(periodStr); + + // + return result; +} + +// +// PROVIDER ... + +// +// Extract a Provider name if exists from a Comment ... +string ExtractProvider(string comment) +{ + // + string result = ""; + if (StringLen(comment) <= 0) + { + return result; + } + + // + result = ExtractString( + comment, + XProviderToken + "(", + ")"); + + // + return result; +} + +// +// Generate Provider String for Using in Positions Comment ... +// NOTE: if there is more than One Provider, it takes first +// provider as main and the others used to increase volume ... +string GenerateProvidersString(XSignal &signal) +{ + // + string result = ""; + + // + int providersCount = ArraySize(signal.providers); + if (providersCount <= 0) + { + return result; + } + + // + result = XProviderToken + "(" + signal.providers[0] + ")"; + + // + return result; +} + +// +// SLTRAIL ... + +// +string GenerateSLTrailComment(int level) +{ + // + string result = ""; + + // + if (level <= 0) + { + return result; + } + + // + result = XSLTrailToken + "(" + ToString(level) + ")"; + + // + return result; +} + +// +int ExtractSLTrailLevel(string comment) +{ + // + int result = 0; + + // + if (StringLen(comment) == 0) + { + return result; + } + + // + string levelStr = ExtractString( + comment, + XSLTrailToken + "(", + ")"); + if (StringLen(levelStr) == 0) + { + return result; + } + + // + result = (int)levelStr; + + // + return result; +} + +// +string PrepareSLTrailComment( + const string comment // Original Position Comment ... +) +{ + // + string result = ""; + + // + if (StringLen(comment) == 0) + { + return result; + } + + // + 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 = GenerateSLTrailComment(lastTrailLevel); + StringReplace( + result, + lastLevelStr, + ""); + } + + // + // Generate level Comment ... + string levelStr = GenerateSLTrailComment(level); + result += levelStr; + + // + return result; +} + +// +// SUPPORT ... + +// +// Generate Specific Position's Support Comment +// index is number of Supports ... +string GenerateSupportSignalComment( + ulong ticket, // Position/Order Ticket + int index // Support Index ... +) +{ + // + string result = ""; + + // + result = XSupportToken + "(" + (string)ticket + "," + ToString(index) + ")"; + + // + return result; +} + +// +// Extract Support Parameters String from specified Comment ... +string ExtractSupportParam(string comment) +{ + // + string result = ""; + if (StringLen(comment) <= 0) + { + return result; + } + + // + result = ExtractString( + comment, + XSupportToken + "(", + ")"); + + // + return result; +} + +// +// Extract Support Info as String array for Specific Comment ... +bool ExtractSupportParams( + string comment, // Specified Comment ... + string ¶ms[] // Hold Result ... +) +{ + // + bool result = false; + + // + string supParam = ExtractSupportParam(comment); + if (StringLen(supParam) == 0) + { + return result; + } + + // + SplitContent( + params, + supParam); + int paramsCount = ArraySize(params); + + // + result = paramsCount == 2; + + // + return result; +} + +// +// Extract Support Parent Ticket ... +ulong ExtractParentTicket(string comment) +{ + // + ulong result = 0; + + // + string params[]; + bool isSupport = ExtractSupportParams( + comment, + params); + if (!isSupport) + { + return result; + } + + // + result = (ulong)params[0]; + + // + return result; +} + +// +// Extract Support Index ... +int ExtractSupportIndex(string comment) +{ + // + int result = -1; + + // + string params[]; + bool isSupport = ExtractSupportParams( + comment, + params); + if (!isSupport) + { + return result; + } + + // + result = (int)params[1]; + + // + return result; +} + +// +// XCONFIG X121Provider Struct ... + +// +// Extract Signallers from User Input ... +int ExtractSignallers( + string &result[], // Hold Result + const string source // Source Content +) +{ + // + int mResult = 0; + + // + Clean(result); + + // + SplitContent( + result, + source); + + // + mResult = ArraySize(result); + + // + return mResult; +} + +// +// Validate Specified Provider Descriptor Model ... +bool IsValid(X121SignalProvider &item) +{ + // + bool result = false; + + // + result = + // + StringLen(item.symbol) > 0 && + item.period != NULL && + item.riskAmount > 0 + // + ; + + // + return result; +} + +// +// Compare Source item with Dest item to check their Same or not ... +bool IsSame( + X121SignalProvider &source, // Source Item + X121SignalProvider &dest // Dest Item +) +{ + // + bool result = false; + + // + bool isValidDest = IsValid(dest); + bool isValidSource = IsValid(source); + if (!isValidDest || + !isValidSource) + { + return result; + } + + // + result = + // + source.symbol == dest.symbol && + source.period == dest.period && + source.riskAmount == dest.riskAmount && + source.useRiskAmountAsStaticVolume == dest.useRiskAmountAsStaticVolume + // + ; + + // + return result; +} + +// +// Check Specified Provider Exists in a Collection or not ... +bool Contains( + X121SignalProvider &item, // Specified Item + X121SignalProvider &items[] // Given Collection +) +{ + // + bool result = false; + + // + int itemsCount = ArraySize(items); + if (itemsCount <= 0) + { + return result; + } + + // + for (int i = 0; i < itemsCount; i++) + { + // + X121SignalProvider iProvider = items[i]; + + // + result = IsSame(item, iProvider); + if (result) + { + // + break; + } + } + + // + return result; +} + +// +// Extract Provider Descriptor Parts from given Source Input ... +int ExtractProviderDescriptorItems( + string &result[], // Hold Result + const string source // Source Descriptor +) +{ + // + int mResult = 0; + + // + Clean(result); + + // + SplitContent( + result, + source, + XItemSeparator); + + // + mResult = ArraySize(result); + + // + return mResult; +} + +// +// Extract Provider Descriptor Items Content from given Source Input ... +int ExtractProviderDescriptorItemsContent( + string &result[], // Hold Result + const string source // Source Descriptor +) +{ + // + int mResult = 0; + + // + Clean(result); + + // + SplitContent( + result, + source, + XItemContentSeparator); + + // + mResult = ArraySize(result); + + // + return mResult; +} + +// +// Validate and add provider to providers if not exists ... +bool AddProviderDescriptor( + X121SignalProvider &item, + X121SignalProvider &items[]) +{ + // + bool result = false; + + // + // Validate and add ... + result = IsValid(item); + if (!result) + { + return result; + } + + // + bool isExists = Contains( + item, + items); + if (isExists) + { + return result; + } + + // + result = true; + + // + Add( + item, + items); + + // + return result; +} + +// +// Extract Provider Descriptors from given Source Input ... +int ExtractProviderConfigurations( + X121SignalProvider &result[], // Hold Result + const string source, // Source String + const string defaultSignallers, // Default Available Signallers for Each Providers + const double defaultRiskAmount, // Default Risk Amount per Trade for Each Provider + const bool useRiskAmountAsStaticVolume = true // Use Provided Risk Amount as Static Volume +) +{ + // + int mResult = 0; + + // + Clean(result); + + // + // if there is no Pairs ... + // Check as One Model ... + string descriptors[]; + mResult = ExtractStrings( + descriptors, + source, + XConfigToken + "(", + ")"); + + // + // Retrieve Signallers ... + string defaultSignallersArr[]; + ExtractSignallers( + defaultSignallersArr, + defaultSignallers); + + // + if (mResult == 0) + { + // + // Here we Check given source String Length ... + // if it is bigger than zero we assuem it is one line descriptor ... + if (StringLen(source) > 0) + { + // + // One Model ... + Add( + source, + descriptors); + } + } + + // + // Each Provider Must Contains at least two things : + // - Asset; + int descriptorsCount = ArraySize(descriptors); + if (descriptorsCount > 0) + { + // + // Loop through descriptors to parse models ... + for (int i = 0; i < descriptorsCount; i++) + { + // + string iDescriptor = descriptors[i]; + + // + X121SignalProvider iProviderDescriptor; + iProviderDescriptor.symbol = ""; + iProviderDescriptor.period = NULL; + iProviderDescriptor.riskAmount = 0; + Clean(iProviderDescriptor.providers); + + // + string iParts[]; + int iPartsCount = ExtractProviderDescriptorItems( + iParts, + iDescriptor); + + // + // Check Parts Count ... + // Now we have to Decide How to Config Signal Providers using Parts ... + + // + // asset => default; + // period => default; + // risk amount => default; + // signallers => default; + // use as static volume => default; + if (iPartsCount == 0) + { + // + // Here we Instance as Current Config Descriptor ... + iProviderDescriptor.symbol = _Symbol; + iProviderDescriptor.period = _Period; + iProviderDescriptor.riskAmount = defaultRiskAmount; + iProviderDescriptor.useRiskAmountAsStaticVolume = useRiskAmountAsStaticVolume; + + // + // Add Default Signallers ... + Copy( + defaultSignallersArr, + iProviderDescriptor.providers); + + // + AddProviderDescriptor( + iProviderDescriptor, + result); + + // + continue; + } + + // + // asset => provided; + // period => default; + // risk amount => default; + // signallers => default; + // use as static volume => default; + if (iPartsCount == 1) + { + + // + iProviderDescriptor.period = _Period; + iProviderDescriptor.riskAmount = defaultRiskAmount; + iProviderDescriptor.useRiskAmountAsStaticVolume = useRiskAmountAsStaticVolume; + + // + // Add Default Signallers ... + Copy( + defaultSignallersArr, + iProviderDescriptor.providers); + + // + // Extract Provided Assets ... + string symbols[]; + int symbolsCount = ExtractProviderDescriptorItemsContent( + symbols, + iParts[0]); + for (int j = 0; j < symbolsCount; j++) + { + // + string jSymbol = symbols[j]; + + // + iProviderDescriptor.symbol = jSymbol; + + // + AddProviderDescriptor( + iProviderDescriptor, + result); + } + + // + continue; + } + + // + // asset => provided; + // period => provided; + // risk amount => default; + // signallers => default; + // use as static volume => default; + if (iPartsCount == 2) + { + // + iProviderDescriptor.riskAmount = defaultRiskAmount; + iProviderDescriptor.useRiskAmountAsStaticVolume = useRiskAmountAsStaticVolume; + + // + // Add Default Signallers ... + Copy( + defaultSignallersArr, + iProviderDescriptor.providers); + + // + // Extract Provided Assets ... + string symbols[]; + int symbolsCount = ExtractProviderDescriptorItemsContent( + symbols, + iParts[0]); + for (int j = 0; j < symbolsCount; j++) + { + // + string jSymbol = symbols[j]; + + // + iProviderDescriptor.symbol = jSymbol; + + // + // Extract Periods ... + string periods[]; + int periodsCount = ExtractProviderDescriptorItemsContent( + periods, + iParts[1]); + for (int k = 0; k < periodsCount; k++) + { + // + string kPeriodStr = periods[k]; + ENUM_TIMEFRAMES kPeriod = ToPeriod(kPeriodStr); + + // + iProviderDescriptor.period = kPeriod; + + // + AddProviderDescriptor( + iProviderDescriptor, + result); + } + } + + // + continue; + } + + // + // asset => provided; + // period => provided; + // risk amount => provided; + // signallers => default; + // use as static volume => default; + if (iPartsCount == 3) + { + // + iProviderDescriptor.useRiskAmountAsStaticVolume = useRiskAmountAsStaticVolume; + + // + // Add Default Signallers ... + Copy( + defaultSignallersArr, + iProviderDescriptor.providers); + + // + // Extract Provided Assets ... + string symbols[]; + int symbolsCount = ExtractProviderDescriptorItemsContent( + symbols, + iParts[0]); + + // + string riskAmounts[]; + int riskAmountsCount = ExtractProviderDescriptorItemsContent( + riskAmounts, + iParts[2]); + + // + for (int j = 0; j < symbolsCount; j++) + { + // + string jSymbol = symbols[j]; + + // + iProviderDescriptor.symbol = jSymbol; + + // + // Extract Periods ... + string periods[]; + int periodsCount = ExtractProviderDescriptorItemsContent( + periods, + iParts[1]); + for (int k = 0; k < periodsCount; k++) + { + // + string kPeriodStr = periods[k]; + ENUM_TIMEFRAMES kPeriod = ToPeriod(kPeriodStr); + + // + iProviderDescriptor.period = kPeriod; + + // + string selectedRiskAmount = + riskAmountsCount == 0 + ? ToString(defaultRiskAmount) + : riskAmountsCount == periodsCount + ? riskAmounts[k] + : riskAmounts[0]; + double riskAmount = (double)selectedRiskAmount; + iProviderDescriptor.riskAmount = riskAmount; + + // + AddProviderDescriptor( + iProviderDescriptor, + result); + } + } + + // + continue; + } + + // + // asset => provided; + // period => provided; + // risk amount => provided; + // signallers => provided; + // use as static volume => default; + if (iPartsCount == 4) + { + // + iProviderDescriptor.useRiskAmountAsStaticVolume = useRiskAmountAsStaticVolume; + + // + // Extract Signallers ... + string signallers[]; + int signallersCount = ExtractSignallers( + signallers, + iParts[3]); + if (signallersCount <= 0) + { + // + Copy( + defaultSignallersArr, + signallers); + } + + // + // Set Extracted Signallers in Provider Descriptor ... + Copy( + signallers, + iProviderDescriptor.providers); + + // + // + // Extract Provided Assets ... + string symbols[]; + int symbolsCount = ExtractProviderDescriptorItemsContent( + symbols, + iParts[0]); + + // + string riskAmounts[]; + int riskAmountsCount = ExtractProviderDescriptorItemsContent( + riskAmounts, + iParts[2]); + + // + for (int j = 0; j < symbolsCount; j++) + { + // + string jSymbol = symbols[j]; + + // + iProviderDescriptor.symbol = jSymbol; + + // + // Extract Periods ... + string periods[]; + int periodsCount = ExtractProviderDescriptorItemsContent( + periods, + iParts[1]); + for (int k = 0; k < periodsCount; k++) + { + // + string kPeriodStr = periods[k]; + ENUM_TIMEFRAMES kPeriod = ToPeriod(kPeriodStr); + + // + iProviderDescriptor.period = kPeriod; + + // + string selectedRiskAmount = + riskAmountsCount == 0 + ? ToString(defaultRiskAmount) + : riskAmountsCount == periodsCount + ? riskAmounts[k] + : riskAmounts[0]; + double riskAmount = (double)selectedRiskAmount; + iProviderDescriptor.riskAmount = riskAmount; + + // + AddProviderDescriptor( + iProviderDescriptor, + result); + } + } + + // + continue; + } + + // + // asset => provided; + // period => provided; + // risk amount => provided; + // signallers => provided; + // use as static volume => provided; + if (iPartsCount == 5) + { + // + // Extract Signallers ... + string signallers[]; + int signallersCount = ExtractSignallers( + signallers, + iParts[3]); + if (signallersCount <= 0) + { + // + Copy( + defaultSignallersArr, + signallers); + } + + // + // Set Extracted Signallers in Provider Descriptor ... + Copy( + signallers, + iProviderDescriptor.providers); + + // + // + // Extract Provided Assets ... + string symbols[]; + int symbolsCount = ExtractProviderDescriptorItemsContent( + symbols, + iParts[0]); + + // + string riskAmounts[]; + int riskAmountsCount = ExtractProviderDescriptorItemsContent( + riskAmounts, + iParts[2]); + + // + string useRiskAmountAsStaticVolumes[]; + int useRiskAmountAsStaticVolumesCount = ExtractProviderDescriptorItemsContent( + useRiskAmountAsStaticVolumes, + iParts[4]); + + // + for (int j = 0; j < symbolsCount; j++) + { + // + string jSymbol = symbols[j]; + + // + iProviderDescriptor.symbol = jSymbol; + + // + // Extract Periods ... + string periods[]; + int periodsCount = ExtractProviderDescriptorItemsContent( + periods, + iParts[1]); + for (int k = 0; k < periodsCount; k++) + { + // + string kPeriodStr = periods[k]; + ENUM_TIMEFRAMES kPeriod = ToPeriod(kPeriodStr); + + // + iProviderDescriptor.period = kPeriod; + + // + string selectedRiskAmount = + riskAmountsCount == 0 + ? ToString(defaultRiskAmount) + : riskAmountsCount == periodsCount + ? riskAmounts[k] + : riskAmounts[0]; + double riskAmount = (double)selectedRiskAmount; + iProviderDescriptor.riskAmount = riskAmount; + + // + string selectedUseRiskAmountAsStaticVolume = + useRiskAmountAsStaticVolumesCount == 0 + ? ToString(useRiskAmountAsStaticVolume) + : useRiskAmountAsStaticVolumesCount == periodsCount + ? useRiskAmountAsStaticVolumes[k] + : useRiskAmountAsStaticVolumes[0]; + bool useRiskAmountAsStaticVolume = ToBoolean(selectedUseRiskAmountAsStaticVolume); + iProviderDescriptor.useRiskAmountAsStaticVolume = useRiskAmountAsStaticVolume; + + // + AddProviderDescriptor( + iProviderDescriptor, + result); + } + } + + // + continue; + } + } + } + else + { + // + // Use All Defaults to Create One Instance ... + X121SignalProvider iProviderDescriptor; + iProviderDescriptor.symbol = ""; + iProviderDescriptor.period = NULL; + iProviderDescriptor.riskAmount = 0; + Clean(iProviderDescriptor.providers); + + // + iProviderDescriptor.symbol = _Symbol; + iProviderDescriptor.period = _Period; + iProviderDescriptor.riskAmount = defaultRiskAmount; + iProviderDescriptor.useRiskAmountAsStaticVolume = useRiskAmountAsStaticVolume; + + // + // Add Default Signallers ... + Copy( + defaultSignallersArr, + iProviderDescriptor.providers); + + // + AddProviderDescriptor( + iProviderDescriptor, + result); + } + + // + mResult = ArraySize(result); + + // + return mResult; +} + +// +// START XEQM Support ... +// + +// +string XEQMSupportToken = "XEQM"; + +// +// Generate String Tag for EQM Support Signals ... +string GenerateXEQMSupportComment() +{ + // + string result = XEQMSupportToken; + + // + return result; +} + +// +// Check a Comment belongs to a EQM Support or not ... +bool IsEQMSupport(string comment) +{ + // + bool result = false; + + // + if (StringLen(comment) <= 0) + { + return result; + } + + // + int tokenPosition = StringFind( + comment, + XEQMSupportToken); + result = tokenPosition >= 0; + + // + return result; +} + +// +// Select EQM Support Orders ... +int GetEQMSupportOrders( + XOrder &supports[], // Hold Result ... + XOrder &orders[], // List of All Orders ... + ENUM_TIMEFRAMES period = NULL // Specified Period ... +) +{ + // + int result = 0; + + // + // Cleanup Array ... + Clean(supports); + + // + // Count Orders ... + int ordersCount = ArraySize(orders); + if (ordersCount <= 0) + { + return result; + } + + // + // Loop through Orders ... + for (int i = 0; i < ordersCount; i++) + { + // + // Select Indexed Order ... + XOrder iOrder = orders[i]; + + // + // Check Order is Support or not ... + bool isSupport = IsEQMSupport(iOrder.comment); + if (!isSupport) + { + continue; + } + + // + // Check Order is not Triggered ... + if (iOrder.state != ORDER_STATE_PLACED) + { + continue; + } + + // + // Check Period ... + if (period != NULL && iOrder.period != period) + { + continue; + } + + // + // we now sure this order is EQM Support ... + Add( + iOrder, + supports); + } + + // + // Count Result ... + result = ArraySize(supports); + + // + return result; +} + +// +// Select EQM Support Positions ... +int GetEQMSupportPositions( + XPosition &supports[], // Hold Result ... + XPosition &positions[], // List of All Positions ... + ENUM_TIMEFRAMES period = NULL // Specified Period ... +) +{ + // + int result = 0; + + // + // Cleanup Array ... + Clean(supports); + + // + // Count Positions ... + int positionsCount = ArraySize(positions); + if (positionsCount <= 0) + { + return result; + } + + // + // Loop through Positions ... + for (int i = 0; i < positionsCount; i++) + { + // + // Select Indexed Position ... + XPosition iPosition = positions[i]; + + // + // Check Position is Support or not ... + bool isSupport = IsEQMSupport(iPosition.comment); + if (!isSupport) + { + continue; + } + + // + // Check Period ... + if (period != NULL && iPosition.period != period) + { + continue; + } + + // + // we now sure this order is EQM Support ... + Add( + iPosition, + supports); + } + + // + // Count Result ... + result = ArraySize(supports); + + // + return result; +} + +// +// END XEQM Support ... +// \ No newline at end of file diff --git a/MQLTestWorkspace/X121/14030217/Libraries/x-saherelm.x121.condition.parser.lib.mq5 b/MQLTestWorkspace/X121/14030217/Libraries/x-saherelm.x121.condition.parser.lib.mq5 new file mode 100644 index 0000000..5815ba6 --- /dev/null +++ b/MQLTestWorkspace/X121/14030217/Libraries/x-saherelm.x121.condition.parser.lib.mq5 @@ -0,0 +1,2475 @@ +//////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 X12 Conditions Parser Library +// ----------------------------------------------------- +// Name: X121ConditionsParser +// Description: provides Market Conditions +// Parsing 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 "../Libraries/x-saherelm.common.lib.mq5" +#include "../Libraries/x-saherelm.models.lib.mq5" +#include "../Classes/x-saherelm.x121.provider.class.mq5" + +// +// START Functions ... +// + +// +// PARSE STATES ... +// + +// +// SSLC ... +// + +// +bool IsSSLCBullish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + conditions.xmanInfo.sslcUps[index] > conditions.xmanInfo.sslcDowns[index] + // + ; + + // + return result; +} + +// +bool IsSSLCSwitchedToBullish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + IsSSLCBullish(conditions, index) && + !IsSSLCBullish(conditions, index + 1) + // + ; + + // + return result; +} + +// +bool IsSSLCBearish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + conditions.xmanInfo.sslcUps[index] < conditions.xmanInfo.sslcDowns[index] + // + ; + + // + return result; +} + +// +bool IsSSLCSwitchedToBearish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + IsSSLCBearish(conditions, index) && + !IsSSLCBearish(conditions, index + 1) + // + ; + + // + return result; +} + +// +// HULL ... +// + +// +bool IsHullBullish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + IsHullUpBullish(conditions, index) && + IsHullDownBullish(conditions, index) + // + ; + + // + return result; +} + +// +bool IsHullSwitchedBullish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + IsHullBullish(conditions, index) && + !IsHullBullish(conditions, index + 1) + // + ; + + // + return result; +} + +// +bool IsHullBearish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + IsHullUpBearish(conditions, index) && + IsHullDownBearish(conditions, index) + // + ; + + // + return result; +} + +// +bool IsHullSwitchedBearish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + IsHullBearish(conditions, index) && + !IsHullBearish(conditions, index + 1) + // + ; + + // + return result; +} + +// +// UP ... + +// +// BULLISH ... + +// +bool IsHullUpBullish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + conditions.xmanInfo.hullUps[index] > conditions.xmanInfo.hullUps[index + 1] + // + ; + + // + return result; +} + +// +bool IsHullUpSwitchedToBullish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + IsHullUpBullish(conditions, index) && + !IsHullUpBullish(conditions, index + 1) + // + ; + + // + return result; +} + +// +// BEARISH ... + +// +bool IsHullUpBearish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + conditions.xmanInfo.hullUps[index] < conditions.xmanInfo.hullUps[index + 1] + // + ; + + // + return result; +} + +// +bool IsHullUpSwitchedToBearish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + IsHullUpBearish(conditions, index) && + !IsHullUpBearish(conditions, index + 1) + // + ; + + // + return result; +} + +// +// DOWN ... + +// +// BULLISH ... + +// +bool IsHullDownBullish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + conditions.xmanInfo.hullDowns[index] > conditions.xmanInfo.hullDowns[index + 1] + // + ; + + // + return result; +} + +// +bool IsHullDownSwitchedToBullish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + IsHullDownBullish(conditions, index) && + !IsHullDownBullish(conditions, index + 1) + // + ; + + // + return result; +} + +// +// BEARISH ... + +// +bool IsHullDownBearish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + conditions.xmanInfo.hullDowns[index] < conditions.xmanInfo.hullDowns[index + 1] + // + ; + + // + return result; +} + +// +bool IsHullDownSwitchedToBearish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + IsHullDownBearish(conditions, index) && + !IsHullDownBearish(conditions, index + 1) + // + ; + + // + return result; +} + +// +// TREND ... +// + +// +// Check Trend Bullish ... +bool IsTrendBullish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + conditions.candles[index].low > conditions.xmanInfo.trends[index] + // + ; + + // + return result; +} + +// +// Check Trend Switched To Bullish ... +bool IsTrendSwitchedToBullish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + IsTrendBullish(conditions, index) && + !IsTrendBullish(conditions, index + 1) + // + ; + + // + return result; +} + +// +// Check Trend Bearish ... +bool IsTrendBearish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + conditions.candles[index].high < conditions.xmanInfo.trends[index] + // + ; + + // + return result; +} + +// +// Check Trend Switched To Bearish ... +bool IsTrendSwitchedToBearish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + IsTrendBearish(conditions, index) && + !IsTrendBearish(conditions, index + 1) + // + ; + + // + return result; +} + +// +// RIBBON ... +// + +// +double GetRibbonMax( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + double result = 0; + + // + result = MathMax(conditions.xmanInfo.ribbon1s[index], conditions.xmanInfo.ribbon2s[index]); + result = MathMax(result, conditions.xmanInfo.ribbon3s[index]); + result = MathMax(result, conditions.xmanInfo.ribbon4s[index]); + result = MathMax(result, conditions.xmanInfo.ribbon5s[index]); + result = MathMax(result, conditions.xmanInfo.ribbon6s[index]); + + // + return result; +} + +// +double GetRibbonMin( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + double result = 0; + + // + result = MathMin(conditions.xmanInfo.ribbon1s[index], conditions.xmanInfo.ribbon2s[index]); + result = MathMin(result, conditions.xmanInfo.ribbon3s[index]); + result = MathMin(result, conditions.xmanInfo.ribbon4s[index]); + result = MathMin(result, conditions.xmanInfo.ribbon5s[index]); + result = MathMin(result, conditions.xmanInfo.ribbon6s[index]); + + // + return result; +} + +// +// Check Ribbon States ... +// Working With Price and Ribbon Values ... +bool IsRibbonBullish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + conditions.candles[index].low > conditions.xmanInfo.ribbon1s[index] && + conditions.candles[index].low > conditions.xmanInfo.ribbon2s[index] && + conditions.candles[index].low > conditions.xmanInfo.ribbon3s[index] && + conditions.candles[index].low > conditions.xmanInfo.ribbon4s[index] && + conditions.candles[index].low > conditions.xmanInfo.ribbon5s[index] && + conditions.candles[index].low > conditions.xmanInfo.ribbon6s[index] + // + ; + + // + return result; +} + +// +// Check Ribbons Sequntial Statements ... +// Working with Price and Ribbon Values and also Ribbon Orders +bool IsRibbonOrderBullish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + IsRibbonBullish(conditions, index) + // + && + // + GetRibbonMax(conditions, index) == conditions.xmanInfo.ribbon1s[index] + // + && + // + GetRibbonMin(conditions, index) == conditions.xmanInfo.ribbon6s[index] + // + ; + + // + return result; +} + +// +bool IsRibbonSwitchedToBullish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + IsRibbonBullish(conditions, index) && + !IsRibbonBullish(conditions, index + 1) + // + ; + + // + return result; +} + +// +// Check Ribbons Sequntial Statements ... +bool IsRibbonOrderSwitchedToBullish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + IsRibbonOrderBullish(conditions, index) && + !IsRibbonOrderBullish(conditions, index + 1) + // + ; + + // + return result; +} + +// +// Check Ribbon States ... +// Working With Price and Ribbon Values ... +bool IsRibbonBearish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + conditions.candles[index].high < conditions.xmanInfo.ribbon1s[index] && + conditions.candles[index].high < conditions.xmanInfo.ribbon2s[index] && + conditions.candles[index].high < conditions.xmanInfo.ribbon3s[index] && + conditions.candles[index].high < conditions.xmanInfo.ribbon4s[index] && + conditions.candles[index].high < conditions.xmanInfo.ribbon5s[index] && + conditions.candles[index].high < conditions.xmanInfo.ribbon6s[index] + // + ; + + // + return result; +} + +// +// Check Ribbons Sequntial Statements ... +// Working with Price and Ribbon Values and also Ribbon Orders +bool IsRibbonOrderBearish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + IsRibbonBearish(conditions, index) + // + && + // + GetRibbonMax(conditions, index) == conditions.xmanInfo.ribbon1s[index] + // + && + // + GetRibbonMin(conditions, index) == conditions.xmanInfo.ribbon6s[index] + // + ; + + // + return result; +} + +// +bool IsRibbonSwitchedToBearish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + IsRibbonBearish(conditions, index) && + !IsRibbonBearish(conditions, index + 1) + // + ; + + // + return result; +} + +// +// Check Ribbons Sequntial Statements ... +bool IsRibbonOrderSwitchedToBearish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + IsRibbonOrderBearish(conditions, index) && + !IsRibbonOrderBearish(conditions, index + 1) + // + ; + + // + return result; +} + +// +// PEAKS and VALES and Levels ... +// + +// +// Check New Peaks Happens ... +bool IsNewPeak( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + conditions.xmanInfo.peaks[index] != EMPTY_VALUE && + conditions.xmanInfo.peaks[index] != conditions.xmanInfo.peaks[index + 1] + // + ; + + // + return result; +} + +// +// Check New Peaks Happens Over Last ... +bool IsNewPeakOverLast( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + IsNewPeak(conditions, index) && + conditions.xmanInfo.peaks[index] > conditions.xmanInfo.peaks[index + 1] + // + ; + + // + return result; +} + +// +// Check New Peaks Happens Under Last ... +bool IsNewPeakUnderLast( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + IsNewPeak(conditions, index) && + conditions.xmanInfo.peaks[index] < conditions.xmanInfo.peaks[index + 1] + // + ; + + // + return result; +} + +// +// Check New Vales Happens ... +bool IsNewVale( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + conditions.xmanInfo.vales[index] != EMPTY_VALUE && + conditions.xmanInfo.vales[index] != conditions.xmanInfo.vales[index + 1] + // + ; + + // + return result; +} + +// +// Check New Vales Happens Over Last ... +bool IsNewValeOverLast( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + IsNewVale(conditions, index) && + conditions.xmanInfo.vales[index] > conditions.xmanInfo.vales[index + 1] + // + ; + + // + return result; +} + +// +// Check New Vales Happens Under Last ... +bool IsNewValeUnderLast( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + IsNewVale(conditions, index) && + conditions.xmanInfo.vales[index] < conditions.xmanInfo.vales[index + 1] + // + ; + + // + return result; +} + +// +// Market Cycles ... + +// +// ALL Cycles ... + +// +bool IsCyclesBullish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + IsSCBullish(conditions, index) && + IsMCBullish(conditions, index) && + IsLCBullish(conditions, index) && + IsHCBullish(conditions, index) + // + ; + + // + return result; +} + +// +bool IsCyclesSwitchedToBullish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + IsCyclesBullish(conditions, index) && + !IsCyclesBullish(conditions, index + 1) + // + ; + + // + return result; +} + +// +bool IsCyclesBearish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + IsSCBearish(conditions, index) && + IsMCBearish(conditions, index) && + IsLCBearish(conditions, index) && + IsHCBearish(conditions, index) + // + ; + + // + return result; +} + +// +bool IsCyclesSwitchedToBearish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + IsCyclesBearish(conditions, index) && + !IsCyclesBearish(conditions, index + 1) + // + ; + + // + return result; +} + +// +bool IsCyclesLowBullish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + IsSCLowBullish(conditions, index) && + IsMCLowBullish(conditions, index) && + IsLCLowBullish(conditions, index) && + IsHCLowBullish(conditions, index) + // + ; + + // + return result; +} + +// +bool IsCyclesLowSwitchedToBullish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + IsCyclesLowBullish(conditions, index) && + !IsCyclesLowBullish(conditions, index + 1) + // + ; + + // + return result; +} + +// +bool IsCyclesLowBearish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + IsSCLowBearish(conditions, index) && + IsMCLowBearish(conditions, index) && + IsLCLowBearish(conditions, index) && + IsHCLowBearish(conditions, index) + // + ; + + // + return result; +} + +// +bool IsCyclesLowSwitchedToBearish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + IsCyclesLowBearish(conditions, index) && + !IsCyclesLowBearish(conditions, index + 1) + // + ; + + // + return result; +} + +// +bool IsCyclesHighBullish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + IsSCHighBullish(conditions, index) && + IsMCHighBullish(conditions, index) && + IsLCHighBullish(conditions, index) && + IsHCHighBullish(conditions, index) + // + ; + + // + return result; +} + +// +bool IsCyclesHighSwitchedToBullish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + IsCyclesHighBullish(conditions, index) && + !IsCyclesHighBullish(conditions, index + 1) + // + ; + + // + return result; +} + +// +bool IsCyclesHighBearish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + IsSCHighBearish(conditions, index) && + IsMCHighBearish(conditions, index) && + IsLCHighBearish(conditions, index) && + IsHCHighBearish(conditions, index) + // + ; + + // + return result; +} + +// +bool IsCyclesHighSwitchedToBearish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + IsCyclesHighBearish(conditions, index) && + !IsCyclesHighBearish(conditions, index + 1) + // + ; + + // + return result; +} + +// +// INHIND Cycles ... + +// +bool IsInHindCyclesBullish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + IsSCBullish(conditions, index) && + IsMCBullish(conditions, index) && + IsLCBullish(conditions, index) + // + ; + + // + return result; +} + +// +bool IsInHindCyclesSwitchedToBullish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + IsInHindCyclesBullish(conditions, index) && + !IsInHindCyclesBullish(conditions, index + 1) + // + ; + + // + return result; +} + +// +bool IsInHindCyclesBearish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + IsSCBearish(conditions, index) && + IsMCBearish(conditions, index) && + IsLCBearish(conditions, index) + // + ; + + // + return result; +} + +// +bool IsInHindCyclesSwitchedToBearish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + IsInHindCyclesBearish(conditions, index) && + !IsInHindCyclesBearish(conditions, index + 1) + // + ; + + // + return result; +} + +// +bool IsInHindCyclesLowBullish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + IsSCLowBullish(conditions, index) && + IsMCLowBullish(conditions, index) && + IsLCLowBullish(conditions, index) + // + ; + + // + return result; +} + +// +bool IsInHindCyclesLowSwitchedToBullish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + IsInHindCyclesLowBullish(conditions, index) && + !IsInHindCyclesLowBullish(conditions, index + 1) + // + ; + + // + return result; +} + +// +bool IsInHindCyclesHighBullish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + IsSCHighBullish(conditions, index) && + IsMCHighBullish(conditions, index) && + IsLCHighBullish(conditions, index) + // + ; + + // + return result; +} + +// +bool IsInHindCyclesHighSwitchedToBullish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + IsInHindCyclesHighBullish(conditions, index) && + !IsInHindCyclesHighBullish(conditions, index + 1) + // + ; + + // + return result; +} + +// +// INLONG Cycles ... + +// +bool IsInLongCyclesBullish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + IsSCBullish(conditions, index) && + IsMCBullish(conditions, index) + // + ; + + // + return result; +} + +// +bool IsInLongCyclesSwitchedToBullish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + IsInLongCyclesBullish(conditions, index) && + !IsInLongCyclesBullish(conditions, index + 1) + // + ; + + // + return result; +} + +// +bool IsInLongCyclesBearish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + IsSCBearish(conditions, index) && + IsMCBearish(conditions, index) + // + ; + + // + return result; +} + +// +bool IsInLongCyclesSwitchedToBearish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + IsInLongCyclesBearish(conditions, index) && + !IsInLongCyclesBearish(conditions, index + 1) + // + ; + + // + return result; +} + +// +// SHORT ... + +// +bool IsSCBullish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + IsSCHighBullish(conditions, index) && + IsSCLowBullish(conditions, index) + // + ; + + // + return result; +} + +// +bool IsSCSwitchedToBullish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + IsSCBullish(conditions, index) && + !IsSCBullish(conditions, index + 1) + // + ; + + // + return result; +} + +// +bool IsSCBearish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + IsSCHighBearish(conditions, index) && + IsSCLowBearish(conditions, index) + // + ; + + // + return result; +} + +// +bool IsSCSwitchedToBearish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + IsSCBearish(conditions, index) && + !IsSCBearish(conditions, index + 1) + // + ; + + // + return result; +} + +// +// SHORT HIGH ... + +// +bool IsSCHighBullish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + conditions.xmanInfo.sHHs[index] > conditions.xmanInfo.sHHs[index + 1] + // + ; + + // + return result; +} + +// +bool IsSCHighSwitchedBullish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + IsSCHighBullish(conditions, index) && + !IsSCHighBullish(conditions, index + 1) + // + ; + + // + return result; +} + +// +bool IsSCHighBearish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + conditions.xmanInfo.sHHs[index] < conditions.xmanInfo.sHHs[index + 1] + // + ; + + // + return result; +} + +// +bool IsSCHighSwitchedToBearish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + IsSCHighBearish(conditions, index) && + !IsSCHighBearish(conditions, index + 1) + // + ; + + // + return result; +} + +// +// SHORT LOW ... + +// +bool IsSCLowBullish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + conditions.xmanInfo.sLLs[index] > conditions.xmanInfo.sLLs[index + 1] + // + ; + + // + return result; +} + +// +bool IsSCLowSwitchedBullish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + IsSCLowBullish(conditions, index) && + !IsSCLowBullish(conditions, index + 1) + // + ; + + // + return result; +} + +// +bool IsSCLowBearish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + conditions.xmanInfo.sLLs[index] < conditions.xmanInfo.sLLs[index + 1] + // + ; + + // + return result; +} + +// +bool IsSCLowSwitchedToBearish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + IsSCLowBearish(conditions, index) && + !IsSCLowBearish(conditions, index + 1) + // + ; + + // + return result; +} + +// +// MEDIUM ... + +// +bool IsMCBullish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + IsMCHighBullish(conditions, index) && + IsMCLowBullish(conditions, index) + // + ; + + // + return result; +} + +// +bool IsMCSwitchedToBullish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + IsMCBullish(conditions, index) && + !IsMCBullish(conditions, index + 1) + // + ; + + // + return result; +} + +// +bool IsMCBearish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + IsMCHighBearish(conditions, index) && + IsMCLowBearish(conditions, index) + // + ; + + // + return result; +} + +// +bool IsMCSwitchedToBearish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + IsMCBearish(conditions, index) && + !IsMCBearish(conditions, index + 1) + // + ; + + // + return result; +} + +// +// MEDIUM HIGH ... + +// +bool IsMCHighBullish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + conditions.xmanInfo.mHHs[index] > conditions.xmanInfo.mHHs[index + 1] + // + ; + + // + return result; +} + +// +bool IsMCHighSwitchedBullish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + IsMCHighBullish(conditions, index) && + !IsMCHighBullish(conditions, index + 1) + // + ; + + // + return result; +} + +// +bool IsMCHighBearish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + conditions.xmanInfo.mHHs[index] < conditions.xmanInfo.mHHs[index + 1] + // + ; + + // + return result; +} + +// +bool IsMCHighSwitchedToBearish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + IsMCHighBearish(conditions, index) && + !IsMCHighBearish(conditions, index + 1) + // + ; + + // + return result; +} + +// +// MEDIUM LOW ... + +// +bool IsMCLowBullish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + conditions.xmanInfo.mLLs[index] > conditions.xmanInfo.mLLs[index + 1] + // + ; + + // + return result; +} + +// +bool IsMCLowSwitchedBullish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + IsMCLowBullish(conditions, index) && + !IsMCLowBullish(conditions, index + 1) + // + ; + + // + return result; +} + +// +bool IsMCLowBearish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + conditions.xmanInfo.mLLs[index] < conditions.xmanInfo.mLLs[index + 1] + // + ; + + // + return result; +} + +// +bool IsMCLowSwitchedToBearish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + IsMCLowBearish(conditions, index) && + !IsMCLowBearish(conditions, index + 1) + // + ; + + // + return result; +} + +// +// LONG ... + +// +bool IsLCBullish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + IsLCHighBullish(conditions, index) && + IsLCLowBullish(conditions, index) + // + ; + + // + return result; +} + +// +bool IsLCSwitchedToBullish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + IsLCBullish(conditions, index) && + !IsLCBullish(conditions, index + 1) + // + ; + + // + return result; +} + +// +bool IsLCBearish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + IsLCHighBearish(conditions, index) && + IsLCLowBearish(conditions, index) + // + ; + + // + return result; +} + +// +bool IsLCSwitchedToBearish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + IsLCBearish(conditions, index) && + !IsLCBearish(conditions, index + 1) + // + ; + + // + return result; +} + +// +// LONG HIGH ... + +// +bool IsLCHighBullish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + conditions.xmanInfo.lHHs[index] > conditions.xmanInfo.lHHs[index + 1] + // + ; + + // + return result; +} + +// +bool IsLCHighSwitchedBullish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + IsLCHighBullish(conditions, index) && + !IsLCHighBullish(conditions, index + 1) + // + ; + + // + return result; +} + +// +bool IsLCHighBearish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + conditions.xmanInfo.lHHs[index] < conditions.xmanInfo.lHHs[index + 1] + // + ; + + // + return result; +} + +// +bool IsLCHighSwitchedToBearish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + IsLCHighBearish(conditions, index) && + !IsLCHighBearish(conditions, index + 1) + // + ; + + // + return result; +} + +// +// LONG LOW ... + +// +bool IsLCLowBullish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + conditions.xmanInfo.lLLs[index] > conditions.xmanInfo.lLLs[index + 1] + // + ; + + // + return result; +} + +// +bool IsLCLowSwitchedBullish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + IsLCLowBullish(conditions, index) && + !IsLCLowBullish(conditions, index + 1) + // + ; + + // + return result; +} + +// +bool IsLCLowBearish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + conditions.xmanInfo.lLLs[index] < conditions.xmanInfo.lLLs[index + 1] + // + ; + + // + return result; +} + +// +bool IsLCLowSwitchedToBearish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + IsLCLowBearish(conditions, index) && + !IsLCLowBearish(conditions, index + 1) + // + ; + + // + return result; +} + +// +// HIND ... + +// +bool IsHCBullish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + IsHCHighBullish(conditions, index) && + IsHCLowBullish(conditions, index) + // + ; + + // + return result; +} + +// +bool IsHCSwitchedToBullish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + IsHCBullish(conditions, index) && + !IsHCBullish(conditions, index + 1) + // + ; + + // + return result; +} + +// +bool IsHCBearish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + IsHCHighBearish(conditions, index) && + IsHCLowBearish(conditions, index) + // + ; + + // + return result; +} + +// +bool IsHCSwitchedToBearish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + IsHCBearish(conditions, index) && + !IsHCBearish(conditions, index + 1) + // + ; + + // + return result; +} + +// +// HIND HIGH ... + +// +bool IsHCHighBullish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + conditions.xmanInfo.hHHs[index] > conditions.xmanInfo.hHHs[index + 1] + // + ; + + // + return result; +} + +// +bool IsHCHighSwitchedBullish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + IsHCHighBullish(conditions, index) && + !IsHCHighBullish(conditions, index + 1) + // + ; + + // + return result; +} + +// +bool IsHCHighBearish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + conditions.xmanInfo.hHHs[index] < conditions.xmanInfo.hHHs[index + 1] + // + ; + + // + return result; +} + +// +bool IsHCHighSwitchedToBearish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + IsHCHighBearish(conditions, index) && + !IsHCHighBearish(conditions, index + 1) + // + ; + + // + return result; +} + +// +// HIND LOW ... + +// +bool IsHCLowBullish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + conditions.xmanInfo.hLLs[index] > conditions.xmanInfo.hLLs[index + 1] + // + ; + + // + return result; +} + +// +bool IsHCLowSwitchedBullish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + IsHCLowBullish(conditions, index) && + !IsHCLowBullish(conditions, index + 1) + // + ; + + // + return result; +} + +// +bool IsHCLowBearish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + conditions.xmanInfo.hLLs[index] < conditions.xmanInfo.hLLs[index + 1] + // + ; + + // + return result; +} + +// +bool IsHCLowSwitchedToBearish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + IsHCLowBearish(conditions, index) && + !IsHCLowBearish(conditions, index + 1) + // + ; + + // + return result; +} + +// +// END Functions ... +// + +// +// START Combination .... +// + +// +bool IsMarketBullish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + IsHullBullish(conditions, index) && + IsSSLCBullish(conditions, index) && + IsTrendBullish(conditions, index) && + IsRibbonOrderBullish(conditions, index) + // + ; + + // + return result; +} + +// +bool IsMarketBearish( + X121MarketConditions &conditions, // Specified Conditions + int index = 0 // Array Index +) +{ + // + bool result = false; + + // + result = + // + false + // + ; + + // + return result; +} + +// +// END Combination .... +// diff --git a/MQLTestWorkspace/X121/14030217/Libraries/x-saherelm.x121.draw.lib.ex5 b/MQLTestWorkspace/X121/14030217/Libraries/x-saherelm.x121.draw.lib.ex5 new file mode 100644 index 0000000..405ae96 Binary files /dev/null and b/MQLTestWorkspace/X121/14030217/Libraries/x-saherelm.x121.draw.lib.ex5 differ diff --git a/MQLTestWorkspace/X121/14030217/Libraries/x-saherelm.x121.draw.lib.mq5 b/MQLTestWorkspace/X121/14030217/Libraries/x-saherelm.x121.draw.lib.mq5 new file mode 100644 index 0000000..4ea43b6 --- /dev/null +++ b/MQLTestWorkspace/X121/14030217/Libraries/x-saherelm.x121.draw.lib.mq5 @@ -0,0 +1,276 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 X12 Draw Library +// ------------------------------------------ +// Name: X121Draw +// Description: provides Draw 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 "../Libraries/x-saherelm.draw.lib.mq5" +#include "../Libraries/x-saherelm.common.lib.mq5" +#include "../Libraries/x-saherelm.models.lib.mq5" + +// +// START Draw Functions ... +// + +// +// Draw Signal ... +void DrawSignal(const ulong ticket, XSignal &signal) +{ + // + bool isLong = IsLong(signal.type); + + // + string prefix = (string)ticket + "_" + ToString(signal.period); + + // + // Retrieve Time ... + datetime time = iTime( + signal.symbol, + signal.period, + 0); + + // + // Retrieve 3 Time ... + datetime time3 = iTime( + signal.symbol, + signal.period, + 3); + + // + color posColor = isLong + ? clrSpringGreen + : clrTomato; + color tpColor = clrSpringGreen; + color slColor = clrTomato; + color entryColor = clrGold; + + // + 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; + + // + long chartID = ChartID(); + + // + // Vertical Line ... + string vlName = prefix + "_" + (string)time; + + // + DrawVerticalLine( + chartID, + vlName, + 0, + time, + posColor, + vLineStyle, + lineWidth); + + // + // TP ... + double profit = (MathAbs(signal.tp - signal.entry)) * signal.volume; + string tpName = prefix + "_TP_" + (string)profit; + + // + DrawTrendLine( + chartID, + tpName, + 0, + time3, + signal.tp, + time, + signal.tp, + tpColor, + tpLineStyle, + lineWidth); + + // + // SL ... + double lost = (MathAbs(signal.sl - signal.entry)) * signal.volume; + string slName = prefix + "_SL_" + (string)lost; + + // + DrawTrendLine( + chartID, + slName, + 0, + time3, + signal.sl, + time, + signal.sl, + slColor, + slLineStyle, + lineWidth); + + // + // ENTRY ... + string entryName = prefix + "_ENTRY_" + (string)lost; + + // + DrawTrendLine( + chartID, + entryName, + 0, + time3, + signal.entry, + time, + signal.entry, + entryColor, + entryLineStyle, + lineWidth); +} + +// +void DrawSignals( + XSignal &signals[], // Signals To Draw + bool drawSupportAndResistances = false // Draw Signal Support and Resistance +) +{ + // + int signalsCount = ArraySize(signals); + if (signalsCount <= 0) + { + return; + } + + // + for (int i = 0; i < signalsCount; i++) + { + // + XSignal iSignal = signals[i]; + + // + ulong iTicket = MathRand() * 10000; + + // + DrawSignal(iTicket, iSignal); + + // + // Check For Draw Support and Resistances ... + bool isValidSupRes = ArraySize(iSignal.supportAndResistance.sup) > 0 || ArraySize(iSignal.supportAndResistance.res) > 0; + if (drawSupportAndResistances && isValidSupRes) + { + DrawSupportResistance(0, iSignal.supportAndResistance); + } + } +} + +// +// Draw Support and Resistance ... +void DrawSupportResistance( + int bar_index, + XOHCLSupRes &data, + string prefix = "", + color supportColor = clrOrange, + color resistanceColor = clrOrange) +{ + // + datetime barTime = GetCandleTime( + _Symbol, + _Period, + bar_index); + + // + datetime prevBarTime = GetCandleTime( + _Symbol, + _Period, + bar_index + 5); + + // + long chID = ChartID(); + int subWindiw = 0; + int lineWidth = 1; + + // + string mPrefix = prefix + "_" + (string)barTime + "_"; + + // + // SUPPORTS ... + + // + int supCount = ArraySize(data.sup); + if (supCount > 0) + { + // + for (int i = 0; i < supCount; i++) + { + // + double iSup = data.sup[i]; + + // + string supTlName = mPrefix + "SUP[" + (string)(i + 1) + "]_(" + (string)iSup + ")"; + + // + // Draw Support ... + DrawTrendLine( + chID, + supTlName, + subWindiw, + prevBarTime, + iSup, + barTime, + iSup, + supportColor, + STYLE_DOT, + lineWidth, + true); + } + } + + // + // RESISTANCES ... + + // + int resCount = ArraySize(data.res); + if (resCount > 0) + { + // + for (int i = 0; i < resCount; i++) + { + // + double iRes = data.res[i]; + + // + string resTlName = mPrefix + "RES[" + (string)(i + 1) + "]_(" + (string)iRes + ")"; + + // + // Draw Support ... + DrawTrendLine( + chID, + resTlName, + subWindiw, + prevBarTime, + iRes, + barTime, + iRes, + resistanceColor, + STYLE_DOT, + lineWidth, + true); + } + } +} + +// +// END Draw Functions ... +// diff --git a/MQLTestWorkspace/X121/14030217/Libraries/x-saherelm.x121.signaller.lib.ex5 b/MQLTestWorkspace/X121/14030217/Libraries/x-saherelm.x121.signaller.lib.ex5 new file mode 100644 index 0000000..25845ef Binary files /dev/null and b/MQLTestWorkspace/X121/14030217/Libraries/x-saherelm.x121.signaller.lib.ex5 differ diff --git a/MQLTestWorkspace/X121/14030217/Libraries/x-saherelm.x121.support.lib.ex5 b/MQLTestWorkspace/X121/14030217/Libraries/x-saherelm.x121.support.lib.ex5 new file mode 100644 index 0000000..93661ef Binary files /dev/null and b/MQLTestWorkspace/X121/14030217/Libraries/x-saherelm.x121.support.lib.ex5 differ diff --git a/MQLTestWorkspace/X121/14030217/Libraries/x-saherelm.xman.parser.lib.ex5 b/MQLTestWorkspace/X121/14030217/Libraries/x-saherelm.xman.parser.lib.ex5 new file mode 100644 index 0000000..f907a81 Binary files /dev/null and b/MQLTestWorkspace/X121/14030217/Libraries/x-saherelm.xman.parser.lib.ex5 differ diff --git a/MQLTestWorkspace/X121/14030217/Libraries/x-saherelm.xman.parser.lib.mq5 b/MQLTestWorkspace/X121/14030217/Libraries/x-saherelm.xman.parser.lib.mq5 new file mode 100644 index 0000000..bf6639e --- /dev/null +++ b/MQLTestWorkspace/X121/14030217/Libraries/x-saherelm.xman.parser.lib.mq5 @@ -0,0 +1,1674 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 XMAN Parser Library +// ----------------------------------------------- +// Name: XMANParser +// Description: Parsing XMAN Config ... +// +// +// 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 + +// +// Candle Timer Config ... +// candleTimerColor(clrGold)candleTimerCorner(2) +// +// Chrt Style ... +// upColor(clrLime) downColor(clrRed) lineColor(clrLime) bearishColor(clrRed) bullishColor(clrLime) volumesColor(clrGreen) chartMode(1) +// +// Market Cycles ... +// +// Short ... +// l1Method(1)l1Period(NULL) +// +// Medium ... +// l2Method(1)l2Period(NULL) +// +// Long ... +// l3Method(1)l3Period(NULL) +// +// Hind ... +// l4Method(1)l4Period(NULL) +// +// Fibonacci ... +// fiboLevel1(0.236)fiboLevel2(0.382)fiboLevel3(0.5)fiboLevel4(0.618)fiboLevel5(0.764) +// +// Boundary Detection Mode ... +// hhMode(2)llMode(1) +// +// Trend Detection ... +// trendMultiplier(3)trendPriceAppliedTo(4) +// +// Ribbon Detection ... +// ribbonMode(5) +// +// Hull Trend Detection ... +// hullDivisor(2.0)hullUpAppliedTo(3)hullDownAppliedTo(4) +// +// SSL Channel ... +// sslcMode(1)sslcUpAppliedTo(3)sslcDownAppliedTo(4) +// +// Style Presentation Config ... +// showCandleTimer(true)showCandles(true)showHKCandles(false)showSMHKCandles(false) +// +// +// PV Presentation Config ... +// showPeaksAndVales(true)showLevels(false)showConsolidations(false) +// +// +// Trend Presentation Config ... +// showHull(false)showTrends(false)fillTrends(false)showRibbons(false)showSSLChannel(false) +// +// +// Fibo Presentation Config ... +// showFibo1Levels(false)showFibo2Levels(false)showFibo3Levels(false)showFibo4Levels(false)showFibo5Levels(false) +// +#include "../Libraries/x-saherelm.models.lib.mq5" +#include "../Libraries/x-saherelm.common.lib.mq5" + +// +// XPERIOD Calculation Method ... +// USED For Multiple Time Frames ... +enum ENUM_X_PERIOD_METHOD +{ + // + X_PERIOD_NOTHING, // Nothing + X_PERIOD_AUTO, // Auto Select + X_PERIOD_MANUALLY // Manually +}; + +// +enum ENUM_X_MA_METHOD +{ + X_MA_NOTHING, // Nothing + X_MA_SMA, // Simple + X_MA_EMA, // Expotential + X_MA_SMMA, // Smoothed Simple + X_MA_LWMA, // Linear Weighted + X_MA_AMA // Adaptive +}; + +// +// PARSERS ... + +// +// CTIMER ... + +// +string candleTimerColorToken = "candleTimerColor"; +string candleTimerCornerToken = "candleTimerCorner"; + +// +struct XCTimerConfig +{ + color candleTimerColor; // Text Color + ENUM_BASE_CORNER candleTimerCorner; // Text Position +}; + +// +string GenerateCTimerConfig( + color mCandleTimerColor = clrGold, // Text Color + ENUM_BASE_CORNER mCandleTimerCorner = CORNER_RIGHT_UPPER // Text Position +) +{ + // + string result = + candleTimerColorToken + "(" + ToString(mCandleTimerColor) + ")" + + candleTimerCornerToken + "(" + ToString((int)mCandleTimerCorner) + ")"; + + // + return result; +} + +// +string ToString(XCTimerConfig &config) +{ + // + return GenerateCTimerConfig( + config.candleTimerColor, + config.candleTimerCorner); +} + +// +XCTimerConfig ParseCTimerConfig( + string config // Source Config +) +{ + // + XCTimerConfig result; + + // + // CandleTimerColor ... + string candleTimerColorStr = + // + ExtractString( + config, + candleTimerColorToken + "(", + ")"); + // + ; + if (StringLen(candleTimerColorStr) > 0) + { + // + color mCandleTimerColor = (color)candleTimerColorStr; + result.candleTimerColor = mCandleTimerColor; + } + + // + // CandleTimerCorner ... + string candleTimerCornerStr = + // + ExtractString( + config, + candleTimerCornerToken + "(", + ")"); + // + ; + if (StringLen(candleTimerCornerStr) > 0) + { + // + ENUM_BASE_CORNER mCandleTimerCorner = (ENUM_BASE_CORNER)((int)candleTimerCornerStr); + result.candleTimerCorner = mCandleTimerCorner; + } + + // + return result; +} + +// +// CHARTSTYLE ... + +// +string upColorToken = "upColor"; +string downColorToken = "downColor"; +string lineColorToken = "lineColor"; +string bearishColorToken = "bearishColor"; +string bullishColorToken = "bullishColor"; +string volumesColorToken = "volumesColor"; +string chartModeToken = "chartMode"; + +// +struct XChartStyleConfig +{ + 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 + ENUM_CHART_MODE chartMode; // Chart Mode +}; + +// +string GenerateChartStyleConfig( + color mUpColor = clrLime, // Up Color + color mDownColor = clrRed, // Down Color + color mLineColor = clrLime, // Line mode and Doji candlestick Color + color mBearishColor = clrRed, // Bullish Color + color mBullishColor = clrLime, // Bearish Color + color mVolumesColor = clrGreen, // Volumes Color + ENUM_CHART_MODE mChartMode = CHART_CANDLES // Chart Mode +) +{ + // + string result = ""; + + // + result = + // + upColorToken + "(" + ToString(mUpColor) + ")" + + downColorToken + "(" + ToString(mDownColor) + ")" + + lineColorToken + "(" + ToString(mLineColor) + ")" + + bearishColorToken + "(" + ToString(mBearishColor) + ")" + + bullishColorToken + "(" + ToString(mBullishColor) + ")" + + volumesColorToken + "(" + ToString(mVolumesColor) + ")" + + chartModeToken + "(" + ToString((int)mChartMode) + ")" + // + ; + + // + return result; +} + +// +string ToString(XChartStyleConfig &config) +{ + return GenerateChartStyleConfig( + config.upColor, + config.downColor, + config.lineColor, + config.bearishColor, + config.bullishColor, + config.volumesColor, + config.chartMode); +} + +// +XChartStyleConfig ParseChartStyleConfig(string config) +{ + // + XChartStyleConfig result; + + // + string upColorStr = + // + ExtractString( + config, + upColorToken + "(", + ")") + // + ; + if (StringLen(upColorStr) > 0) + { + // + color mUpColor = (color)upColorStr; + result.upColor = mUpColor; + } + + // + string downColorStr = + // + ExtractString( + config, + downColorToken + "(", + ")") + // + ; + if (StringLen(downColorStr) > 0) + { + // + color mDownColor = (color)downColorStr; + result.downColor = mDownColor; + } + + // + string lineColorStr = + // + ExtractString( + config, + lineColorToken + "(", + ")") + // + ; + if (StringLen(lineColorStr) > 0) + { + // + color mLineColor = (color)lineColorStr; + result.lineColor = mLineColor; + } + + // + string bearishColorStr = + // + ExtractString( + config, + bearishColorToken + "(", + ")") + // + ; + if (StringLen(bearishColorStr) > 0) + { + // + color mBearishColor = (color)bearishColorStr; + result.bearishColor = mBearishColor; + } + + // + string bullishColorStr = + // + ExtractString( + config, + bullishColorToken + "(", + ")") + // + ; + if (StringLen(bullishColorStr) > 0) + { + // + color mBullishColor = (color)bullishColorStr; + result.bullishColor = mBullishColor; + } + + // + string volumesColorStr = + // + ExtractString( + config, + volumesColorToken + "(", + ")") + // + ; + if (StringLen(volumesColorStr) > 0) + { + // + color mVolumesColor = (color)volumesColorStr; + result.volumesColor = mVolumesColor; + } + + // + string chartModeStr = + // + ExtractString( + config, + chartModeToken + "(", + ")") + // + ; + if (StringLen(chartModeStr) > 0) + { + // + ENUM_CHART_MODE mChartMode = (ENUM_CHART_MODE)((int)chartModeStr); + result.chartMode = mChartMode; + } + + // + return result; +} + +// +// MARKETCYCLES ... + +// +// SHORT ... + +// +string l1MethodToken = "l1Method"; +string l1PeriodToken = "l1Period"; + +// +struct XSCConfig +{ + ENUM_X_PERIOD_METHOD l1Method; // How to Find Period + ENUM_TIMEFRAMES l1Period; // Time Period +}; + +// +string GenerateSCConfig( + ENUM_X_PERIOD_METHOD mML1Method = X_PERIOD_AUTO, // How to Find Period + ENUM_TIMEFRAMES mML1Period = NULL // Time Period +) +{ + // + string result = ""; + + // + result = + // + l1MethodToken + "(" + ToString(mML1Method) + ")" + + l1PeriodToken + "(" + ToString(mML1Period) + ")" + // + ; + + // + return result; +} + +// +string ToString(XSCConfig &config) +{ + return GenerateSCConfig( + config.l1Method, + config.l1Period); +} + +// +XSCConfig PrseSCConfig(string config) +{ + // + XSCConfig result; + + // + string l1MethodStr = ExtractString( + config, + l1MethodToken + "(", + ")"); + if (StringLen(l1MethodStr) > 0) + { + // + ENUM_X_PERIOD_METHOD mML1Method = (ENUM_X_PERIOD_METHOD)((int)l1MethodStr); + result.l1Method = mML1Method; + } + + // + string l1PeriodStr = ExtractString( + config, + l1PeriodToken + "(", + ")"); + if (StringLen(l1PeriodStr) > 0) + { + // + ENUM_TIMEFRAMES mML1Period = (ENUM_TIMEFRAMES)((int)l1PeriodStr); + result.l1Period = mML1Period; + } + + // + return result; +} + +// +// MEDIUM ... + +// +string l2MethodToken = "l2Method"; +string l2PeriodToken = "l2Period"; + +// +struct XMCConfig +{ + ENUM_X_PERIOD_METHOD l2Method; // How to Find Period + ENUM_TIMEFRAMES l2Period; // Time Period +}; + +// +string GenerateMCConfig( + ENUM_X_PERIOD_METHOD mML2Method = X_PERIOD_AUTO, // How to Find Period + ENUM_TIMEFRAMES mML2Period = NULL // Time Period +) +{ + // + string result = ""; + + // + result = + // + l2MethodToken + "(" + ToString(mML2Method) + ")" + + l2PeriodToken + "(" + ToString(mML2Period) + ")" + // + ; + + // + return result; +} + +// +string ToString(XMCConfig &config) +{ + return GenerateSCConfig( + config.l2Method, + config.l2Period); +} + +// +XMCConfig PrseMCConfig(string config) +{ + // + XMCConfig result; + + // + string l2MethodStr = ExtractString( + config, + l2MethodToken + "(", + ")"); + if (StringLen(l2MethodStr) > 0) + { + // + ENUM_X_PERIOD_METHOD mML2Method = (ENUM_X_PERIOD_METHOD)((int)l2MethodStr); + result.l2Method = mML2Method; + } + + // + string l2PeriodStr = ExtractString( + config, + l2PeriodToken + "(", + ")"); + if (StringLen(l2PeriodStr) > 0) + { + // + ENUM_TIMEFRAMES mML2Period = (ENUM_TIMEFRAMES)((int)l2PeriodStr); + result.l2Period = mML2Period; + } + + // + return result; +} + +// +// LONG ... + +// +string l3MethodToken = "l3Method"; +string l3PeriodToken = "l3Period"; + +// +struct XLCConfig +{ + ENUM_X_PERIOD_METHOD l3Method; // How to Find Period + ENUM_TIMEFRAMES l3Period; // Time Period +}; + +// +string GenerateLCConfig( + ENUM_X_PERIOD_METHOD mML3Method = X_PERIOD_AUTO, // How to Find Period + ENUM_TIMEFRAMES mML3Period = NULL // Time Period +) +{ + // + string result = ""; + + // + result = + // + l3MethodToken + "(" + ToString(mML3Method) + ")" + + l3PeriodToken + "(" + ToString(mML3Period) + ")" + // + ; + + // + return result; +} + +// +string ToString(XLCConfig &config) +{ + return GenerateSCConfig( + config.l3Method, + config.l3Period); +} + +// +XLCConfig PrseLCConfig(string config) +{ + // + XLCConfig result; + + // + string l3MethodStr = ExtractString( + config, + l3MethodToken + "(", + ")"); + if (StringLen(l3MethodStr) > 0) + { + // + ENUM_X_PERIOD_METHOD mML3Method = (ENUM_X_PERIOD_METHOD)((int)l3MethodStr); + result.l3Method = mML3Method; + } + + // + string l3PeriodStr = ExtractString( + config, + l3PeriodToken + "(", + ")"); + if (StringLen(l3PeriodStr) > 0) + { + // + ENUM_TIMEFRAMES mML3Period = (ENUM_TIMEFRAMES)((int)l3PeriodStr); + result.l3Period = mML3Period; + } + + // + return result; +} + +// +// HIND ... + +// +string l4MethodToken = "l4Method"; +string l4PeriodToken = "l4Period"; + +// +struct XHCConfig +{ + ENUM_X_PERIOD_METHOD l4Method; // How to Find Period + ENUM_TIMEFRAMES l4Period; // Time Period +}; + +// +string GenerateHCConfig( + ENUM_X_PERIOD_METHOD mML4Method = X_PERIOD_AUTO, // How to Find Period + ENUM_TIMEFRAMES mML4Period = NULL // Time Period +) +{ + // + string result = ""; + + // + result = + // + l4MethodToken + "(" + ToString(mML4Method) + ")" + + l4PeriodToken + "(" + ToString(mML4Period) + ")" + // + ; + + // + return result; +} + +// +string ToString(XHCConfig &config) +{ + return GenerateSCConfig( + config.l4Method, + config.l4Period); +} + +// +XHCConfig PrseHCConfig(string config) +{ + // + XHCConfig result; + + // + string l4MethodStr = ExtractString( + config, + l4MethodToken + "(", + ")"); + if (StringLen(l4MethodStr) > 0) + { + // + ENUM_X_PERIOD_METHOD mML4Method = (ENUM_X_PERIOD_METHOD)((int)l4MethodStr); + result.l4Method = mML4Method; + } + + // + string l4PeriodStr = ExtractString( + config, + l4PeriodToken + "(", + ")"); + if (StringLen(l4PeriodStr) > 0) + { + // + ENUM_TIMEFRAMES mML4Period = (ENUM_TIMEFRAMES)((int)l4PeriodStr); + result.l4Period = mML4Period; + } + + // + return result; +} + +// +// XFIBONACCI ... + +// +string fiboLevel1Token = "fiboLevel1"; +string fiboLevel2Token = "fiboLevel2"; +string fiboLevel3Token = "fiboLevel3"; +string fiboLevel4Token = "fiboLevel4"; +string fiboLevel5Token = "fiboLevel5"; + +// +struct XFiboConfig +{ + 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 +}; + +// +string GenerateFibonacciConfig( + double mFiboLevel1 = 0.236, // Fibio 1st Level + double mFiboLevel2 = 0.382, // Fibio 2st Level + double mFiboLevel3 = 0.5, // Fibio 3rd Level + double mFiboLevel4 = 0.618, // Fibio 4th Level + double mFiboLevel5 = 0.764 // Fibio 5th Level +) +{ + // + string result = ""; + + // + result = + // + fiboLevel1Token + "(" + ToString(mFiboLevel1) + ")" + + fiboLevel2Token + "(" + ToString(mFiboLevel2) + ")" + + fiboLevel3Token + "(" + ToString(mFiboLevel3) + ")" + + fiboLevel4Token + "(" + ToString(mFiboLevel4) + ")" + + fiboLevel5Token + "(" + ToString(mFiboLevel5) + ")" + // + ; + + // + return result; +} + +// +string ToString(XFiboConfig &config) +{ + return GenerateFibonacciConfig( + config.fiboLevel1, + config.fiboLevel2, + config.fiboLevel3, + config.fiboLevel4, + config.fiboLevel5); +} + +// +XFiboConfig PrseFiboConfig(string config) +{ + // + XFiboConfig result; + + // + string fiboLevel1Str = ExtractString( + config, + fiboLevel1Token + "(", + ")"); + if (StringLen(fiboLevel1Str) > 0) + { + // + double mFiboLevel1 = (double)fiboLevel1Str; + result.fiboLevel1 = mFiboLevel1; + } + + // + string fiboLevel2Str = ExtractString( + config, + fiboLevel2Token + "(", + ")"); + if (StringLen(fiboLevel2Str) > 0) + { + // + double mFiboLevel2 = (double)fiboLevel2Str; + result.fiboLevel2 = mFiboLevel2; + } + + // + string fiboLevel3Str = ExtractString( + config, + fiboLevel3Token + "(", + ")"); + if (StringLen(fiboLevel3Str) > 0) + { + // + double mFiboLevel3 = (double)fiboLevel3Str; + result.fiboLevel3 = mFiboLevel3; + } + + // + string fiboLevel4Str = ExtractString( + config, + fiboLevel4Token + "(", + ")"); + if (StringLen(fiboLevel4Str) > 0) + { + // + double mFiboLevel4 = (double)fiboLevel4Str; + result.fiboLevel4 = mFiboLevel4; + } + + // + string fiboLevel5Str = ExtractString( + config, + fiboLevel5Token + "(", + ")"); + if (StringLen(fiboLevel5Str) > 0) + { + // + double mFiboLevel5 = (double)fiboLevel5Str; + result.fiboLevel5 = mFiboLevel5; + } + + // + return result; +} + +// +// BOUNDARYDETECTION ... + +// +string hhModeToken = "hhMode"; +string llModeToken = "llMode"; + +// +struct XBDConfig +{ + ENUM_SERIESMODE hhMode; // Highest High Calculation Method + ENUM_SERIESMODE llMode; // Lowest Low Calculation Method +}; + +// +string GenerateBDConfig( + ENUM_SERIESMODE mHhMode = MODE_HIGH, // Highest High Calculation Method + ENUM_SERIESMODE mLlMode = MODE_LOW // Lowest Low Calculation Method +) +{ + // + string result = ""; + + // + result = + // + hhModeToken + "(" + ToString((int)mHhMode) + ")" + + llModeToken + "(" + ToString((int)mLlMode) + ")" + // + ; + + // + return result; +} + +// +string ToString(XBDConfig &config) +{ + return GenerateBDConfig( + config.hhMode, + config.llMode); +} + +// +XBDConfig ParseBDConfig(string config) +{ + // + XBDConfig result; + + // + string hhModeStr = ExtractString( + config, + hhModeToken + "(", + ")"); + if (StringLen(hhModeStr) > 0) + { + // + ENUM_SERIESMODE mHhMode = (ENUM_SERIESMODE)((int)hhModeStr); + result.hhMode = mHhMode; + } + + // + string llModeStr = ExtractString( + config, + llModeToken + "(", + ")"); + if (StringLen(llModeStr) > 0) + { + // + ENUM_SERIESMODE mLlMode = (ENUM_SERIESMODE)((int)llModeStr); + result.llMode = mLlMode; + } + + // + return result; +} + +// +// TREND ... + +// +string trendMultiplierToken = "trendMultiplier"; +string trendPriceAppliedToToken = "trendPriceAppliedTo"; + +// +struct XTDConfig +{ + double trendMultiplier; // Multiplier + ENUM_APPLIED_PRICE trendPriceAppliedTo; // Applied To +}; + +// +string GenerateTDConfig( + double mTrendMultiplier = 3, // Multiplier + ENUM_APPLIED_PRICE mTrendPriceAppliedTo = PRICE_MEDIAN // Applied To +) +{ + // + string result = ""; + + // + result = + // + trendMultiplierToken + "(" + ToString(mTrendMultiplier) + ")" + + trendPriceAppliedToToken + "(" + ToString(mTrendPriceAppliedTo) + ")" + // + ; + + // + return result; +} + +// +string ToString(XTDConfig &config) +{ + return GenerateTDConfig( + config.trendMultiplier, + config.trendPriceAppliedTo); +} + +// +XTDConfig ParseTDConfig(string config) +{ + // + XTDConfig result; + + // + string trendMultiplierStr = ExtractString( + config, + trendMultiplierToken + "(", + ")"); + if (StringLen(trendMultiplierStr) > 0) + { + // + double mTrendMultiplier = (double)trendMultiplierStr; + result.trendMultiplier = mTrendMultiplier; + } + + // + string trendPriceAppliedToStr = ExtractString( + config, + trendPriceAppliedToToken + "(", + ")"); + if (StringLen(trendPriceAppliedToStr) > 0) + { + // + ENUM_APPLIED_PRICE mTrendPriceAppliedTo = (ENUM_APPLIED_PRICE)((int)trendPriceAppliedToStr); + // + result.trendPriceAppliedTo = mTrendPriceAppliedTo; + } + + // + return result; +} + +// +// RIBBON RB ... + +// +string ribbonModeToken = "ribbonMode"; + +// +struct XRBConfig +{ + ENUM_X_MA_METHOD ribbonMode; // How to Calculate +}; + +// +string GenerateRBConfig( + ENUM_X_MA_METHOD mRibbonMode = X_MA_AMA // How to Calculate +) +{ + // + string result = ""; + + // + result = + // + ribbonModeToken + "(" + ToString(mRibbonMode) + ")" + // + ; + + // + return result; +} + +// +string ToString(XRBConfig &config) +{ + // + return GenerateRBConfig( + config.ribbonMode); +} + +// +XRBConfig ParseRBConfig(string config) +{ + // + XRBConfig result; + + // + string ribbonModeStr = ExtractString( + config, + ribbonModeToken + "(", + ")"); + if (StringLen(ribbonModeStr) > 0) + { + // + ENUM_X_MA_METHOD mRibbonMode = (ENUM_X_MA_METHOD)((int)ribbonModeStr); + result.ribbonMode = mRibbonMode; + } + + // + return result; +} + +// +// HULL ... + +// +string hullDivisorToken = "hullDivisor"; +string hullUpAppliedToToken = "hullUpAppliedTo"; +string hullDownAppliedToToken = "hullDownAppliedTo"; + +// +struct XHullConfig +{ + double hullDivisor; // Divisor (Speed) + ENUM_APPLIED_PRICE hullUpAppliedTo; // Up Zone Applied to + ENUM_APPLIED_PRICE hullDownAppliedTo; // Down Zone Applied to +}; + +// +string GenerateHullConfig( + double mHullDivisor = 2.0, // Divisor (Speed) + ENUM_APPLIED_PRICE mHullUpAppliedTo = PRICE_HIGH, // Up Zone Applied to + ENUM_APPLIED_PRICE mHullDownAppliedTo = PRICE_LOW // Down Zone Applied to +) +{ + // + string result = ""; + + // + result = + // + hullDivisorToken + "(" + ToString(mHullDivisor) + ")" + + hullUpAppliedToToken + "(" + ToString(mHullUpAppliedTo) + ")" + + hullDownAppliedToToken + "(" + ToString(mHullDownAppliedTo) + ")" + // + ; + + // + return result; +} + +// +string ToString(XHullConfig &config) +{ + // + return GenerateHullConfig( + config.hullDivisor, + config.hullUpAppliedTo, + config.hullDownAppliedTo); +} + +// +XHullConfig ParseHullConfig(string config) +{ + // + XHullConfig result; + + // + string hullDivisorStr = ExtractString( + config, + hullDivisorToken + "(", + ")"); + if (StringLen(hullDivisorStr) > 0) + { + // + double mHullDivisor = (double)hullDivisorStr; + result.hullDivisor = mHullDivisor; + } + + // + string hullUpAppliedToStr = ExtractString( + config, + hullUpAppliedToToken + "(", + ")"); + if (StringLen(hullUpAppliedToStr) > 0) + { + // + ENUM_APPLIED_PRICE mHullUpAppliedTo = (ENUM_APPLIED_PRICE)((int)hullUpAppliedToStr); + result.hullUpAppliedTo = mHullUpAppliedTo; + } + + // + string hullDownAppliedToStr = ExtractString( + config, + hullDownAppliedToToken + "(", + ")"); + if (StringLen(hullDownAppliedToStr) > 0) + { + // + ENUM_APPLIED_PRICE mHullDownAppliedTo = (ENUM_APPLIED_PRICE)((int)hullDownAppliedToStr); + result.hullDownAppliedTo = mHullDownAppliedTo; + } + + // + return result; +} + +// +// SSLC ... + +// +string sslcModeToken = "sslcMode"; +string sslcUpAppliedToToken = "sslcUpAppliedTo"; +string sslcDownAppliedToToken = "sslcDownAppliedTo"; + +// +struct XSSLCConfig +{ + ENUM_X_MA_METHOD sslcMode; // How to Calculate + ENUM_APPLIED_PRICE sslcUpAppliedTo; // Up Applied To + ENUM_APPLIED_PRICE sslcDownAppliedTo; // Down Applied To +}; + +// +string GenerateSSLCConfig( + ENUM_X_MA_METHOD mSslcMode = X_MA_SMA, // How to Calculate + ENUM_APPLIED_PRICE mSslcUpAppliedTo = PRICE_HIGH, // Up Applied To + ENUM_APPLIED_PRICE mSslcDownAppliedTo = PRICE_LOW // Down Applied To +) +{ + // + string result; + + // + result = + // + sslcModeToken + "(" + ToString(mSslcMode) + ")" + + sslcUpAppliedToToken + "(" + ToString(mSslcUpAppliedTo) + ")" + + sslcDownAppliedToToken + "(" + ToString(mSslcDownAppliedTo) + ")" + // + ; + + // + return result; +} + +// +string ToString(XSSLCConfig &config) +{ + return GenerateSSLCConfig( + config.sslcMode, + config.sslcUpAppliedTo, + config.sslcDownAppliedTo); +} + +// +XSSLCConfig ParseSSLCConfig(string config) +{ + // + XSSLCConfig result; + + // + string sslcModeStr = ExtractString( + config, + sslcModeToken + "(", + ")"); + if (StringLen(sslcModeStr) > 0) + { + // + ENUM_X_MA_METHOD mSslcMode = (ENUM_X_MA_METHOD)((int)sslcModeStr); + result.sslcMode = mSslcMode; + } + + // + string sslcUpAppliedToStr = ExtractString( + config, + sslcUpAppliedToToken + "(", + ")"); + if (StringLen(sslcUpAppliedToStr) > 0) + { + // + ENUM_APPLIED_PRICE mSslcUpAppliedTo = (ENUM_APPLIED_PRICE)((int)sslcUpAppliedToStr); + result.sslcUpAppliedTo = mSslcUpAppliedTo; + } + + // + string sslcDownAppliedToStr = ExtractString( + config, + sslcDownAppliedToToken + "(", + ")"); + if (StringLen(sslcDownAppliedToStr) > 0) + { + // + ENUM_APPLIED_PRICE mSslcDownAppliedTo = (ENUM_APPLIED_PRICE)((int)sslcDownAppliedToStr); + result.sslcDownAppliedTo = mSslcDownAppliedTo; + } + + // + return result; +} + +// +// PRESENTATION ... + +// +string showCandleTimerToken = "showCandleTimer"; +string showCandlesToken = "showCandles"; +string showHKCandlesToken = "showHKCandles"; +string showSMHKCandlesToken = "showSMHKCandles"; +string showPeaksAndValesToken = "showPeaksAndVales"; +string showTrendsToken = "showTrends"; +string fillTrendsToken = "fillTrends"; +string showLevelsToken = "showLevels"; +string showConsolidationsToken = "showConsolidations"; +string showRibbonsToken = "showRibbons"; +string showHullToken = "showHull"; +string showSSLChannelToken = "showSSLChannel"; +string showFibo1LevelsToken = "showFibo1Levels"; +string showFibo2LevelsToken = "showFibo2Levels"; +string showFibo3LevelsToken = "showFibo3Levels"; +string showFibo4LevelsToken = "showFibo4Levels"; +string showFibo5LevelsToken = "showFibo5Levels"; + +// +struct XStylePresentationConfig +{ + bool showCandleTimer; // Show Candle Time + bool showCandles; // Show Candles + bool showHKCandles; // Draw Hiken Ashi Candle + bool showSMHKCandles; // Draw Smoothed Hiken Ashi Candle +}; + +// +string GenerateStylePresentationConfig( + bool mShowCandleTimer = true, // Show Candle Time + bool mShowCandles = true, // Show Candles + bool mShowHKCandles = false, // Draw Hiken Ashi Candle + bool mShowSMHKCandles = false // Draw Smoothed Hiken Ashi Candle +) +{ + // + string result = ""; + + // + result = + // + showCandleTimerToken + "(" + ToString(mShowCandleTimer) + ")" + + showCandlesToken + "(" + ToString(mShowCandles) + ")" + + showHKCandlesToken + "(" + ToString(mShowHKCandles) + ")" + + showSMHKCandlesToken + "(" + ToString(mShowSMHKCandles) + ")" + // + ; + + // + return result; +} + +// +XStylePresentationConfig ParseStylePresentationConfig(string config) +{ + // + XStylePresentationConfig result; + + // + string showCandleTimerStr = ExtractString( + config, + showCandleTimerToken + "(", + ")"); + if (StringLen(showCandleTimerStr) > 0) + { + // + bool mShowCandleTimer = ToBoolean(showCandleTimerStr); + result.showCandleTimer = mShowCandleTimer; + } + + // + string showCandlesStr = ExtractString( + config, + showCandlesToken + "(", + ")"); + if (StringLen(showCandlesStr) > 0) + { + // + bool mShowCandles = ToBoolean(showCandlesStr); + result.showCandles = mShowCandles; + } + + // + string showHKCandlesStr = ExtractString( + config, + showHKCandlesToken + "(", + ")"); + if (StringLen(showHKCandlesStr) > 0) + { + // + bool mShowHKCandles = ToBoolean(showHKCandlesStr); + result.showHKCandles = mShowHKCandles; + } + + // + string showSMHKCandlesStr = ExtractString( + config, + showSMHKCandlesToken + "(", + ")"); + if (StringLen(showSMHKCandlesStr) > 0) + { + // + bool mShowSMHKCandles = ToBoolean(showSMHKCandlesStr); + result.showSMHKCandles = mShowSMHKCandles; + } + + // + return result; +} + +// +string ToString(XStylePresentationConfig &config) +{ + // + return GenerateStylePresentationConfig( + config.showCandleTimer, + config.showCandles, + config.showHKCandles, + config.showSMHKCandles); +} + +// +struct XPVPresentationConfig +{ + bool showPeaksAndVales; // Show Peaks and Vales + bool showLevels; // Show Levels + bool showConsolidations; // Show Consolidations +}; + +// +string GeneratePVPresentationConfig( + bool mShowPeaksAndVales = true, // Show Peaks and Vales + bool mShowLevels = false, // Show Levels + bool mShowConsolidations = false // Show Consolidations +) +{ + // + string result; + + // + result = + // + showPeaksAndValesToken + "(" + ToString(mShowPeaksAndVales) + ")" + + showLevelsToken + "(" + ToString(mShowLevels) + ")" + + showConsolidationsToken + "(" + ToString(mShowConsolidations) + ")" + // + ; + + // + return result; +} + +// +string ToString(XPVPresentationConfig &config) +{ + // + return GeneratePVPresentationConfig( + config.showPeaksAndVales, + config.showLevels, + config.showConsolidations); +} + +// +XPVPresentationConfig ParsePVPresentationConfig(string config) +{ + // + XPVPresentationConfig result; + + // + string showPeaksAndValesStr = ExtractString( + config, + showPeaksAndValesToken + "(", + ")"); + if (StringLen(showPeaksAndValesStr) > 0) + { + // + bool mShowPeaksAndVales = ToBoolean(showPeaksAndValesStr); + result.showPeaksAndVales = mShowPeaksAndVales; + } + + // + string showLevelsStr = ExtractString( + config, + showLevelsToken + "(", + ")"); + if (StringLen(showLevelsStr) > 0) + { + // + bool mShowLevels = ToBoolean(showLevelsStr); + result.showLevels = mShowLevels; + } + + // + string showConsolidationsStr = ExtractString( + config, + showConsolidationsToken + "(", + ")"); + if (StringLen(showConsolidationsStr) > 0) + { + // + bool mShowConsolidations = ToBoolean(showConsolidationsStr); + result.showConsolidations = mShowConsolidations; + } + + // + return result; +} + +// +struct XTrendPresentationConfig +{ + bool showHull; // Show Hull + bool showTrends; // Show Trends + bool fillTrends; // Fill Trends + bool showRibbons; // Show Ribbons + bool showSSLChannel; // Show SSL Channel +}; + +// +string GenerateTrendPresentationConfig( + bool mShowTrends = true, // Show Trends + bool mFillTrends = false, // Fill Trends + bool mShowRibbons = false, // Show Ribbons + bool mShowHull = false, // Show Hull + bool mShowSSLChannel = false // Show SSL Channel +) +{ + // + string result; + + // + result = + // + showTrendsToken + "(" + ToString(mShowTrends) + ")" + + fillTrendsToken + "(" + ToString(mFillTrends) + ")" + + showRibbonsToken + "(" + ToString(mShowRibbons) + ")" + + showHullToken + "(" + ToString(mShowHull) + ")" + + showSSLChannelToken + "(" + ToString(mShowSSLChannel) + ")" + // + ; + + // + return result; +} + +// +string ToString(XTrendPresentationConfig &config) +{ + // + return GenerateTrendPresentationConfig( + config.showHull, + config.showTrends, + config.fillTrends, + config.showRibbons, + config.showSSLChannel); +} + +// +XTrendPresentationConfig ParseTrendPresentationConfig(string config) +{ + // + XTrendPresentationConfig result; + + // + string showTrendsStr = ExtractString( + config, + showTrendsToken + "(", + ")"); + if (StringLen(showTrendsStr) > 0) + { + // + bool mShowTrends = ToBoolean(showTrendsStr); + result.showTrends = mShowTrends; + } + + // + string fillTrendsStr = ExtractString( + config, + fillTrendsToken + "(", + ")"); + if (StringLen(fillTrendsStr) > 0) + { + // + bool mFillTrends = ToBoolean(fillTrendsStr); + result.fillTrends = mFillTrends; + } + + // + string showRibbonsStr = ExtractString( + config, + showRibbonsToken + "(", + ")"); + if (StringLen(showRibbonsStr) > 0) + { + // + bool mShowRibbons = ToBoolean(showRibbonsStr); + result.showRibbons = mShowRibbons; + } + + // + string showHullStr = ExtractString( + config, + showHullToken + "(", + ")"); + if (StringLen(showHullStr) > 0) + { + // + bool mShowHull = ToBoolean(showHullStr); + result.showHull = mShowHull; + } + + // + string showSSLChannelStr = ExtractString( + config, + showSSLChannelToken + "(", + ")"); + if (StringLen(showSSLChannelStr) > 0) + { + // + bool mShowSSLChannel = ToBoolean(showSSLChannelStr); + result.showSSLChannel = mShowSSLChannel; + } + + // + return result; +} + +// +struct XFiboPresentationConfig +{ + 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 +}; + +// +string GenerateFiboPresentationConfig( + bool mShowFibo1Levels = false, // Show Fibo 1st Level + bool mShowFibo2Levels = false, // Show Fibo 2nd Level + bool mShowFibo3Levels = false, // Show Fibo 3rd Level + bool mShowFibo4Levels = false, // Show Fibo 4th Level + bool mShowFibo5Levels = false // Show Fibo 5th Level +) +{ + // + string result = ""; + + // + result = + // + showFibo1LevelsToken + "(" + ToString(mShowFibo1Levels) + ")" + + showFibo2LevelsToken + "(" + ToString(mShowFibo2Levels) + ")" + + showFibo3LevelsToken + "(" + ToString(mShowFibo3Levels) + ")" + + showFibo4LevelsToken + "(" + ToString(mShowFibo4Levels) + ")" + + showFibo5LevelsToken + "(" + ToString(mShowFibo5Levels) + ")" + // + ; + + // + return result; +} + +// +string ToString(XFiboPresentationConfig &config) +{ + // + return GenerateFiboPresentationConfig( + config.showFibo1Levels, + config.showFibo2Levels, + config.showFibo3Levels, + config.showFibo4Levels, + config.showFibo5Levels); +} + +// +XFiboPresentationConfig ParePresentationConfig(string config) +{ + // + XFiboPresentationConfig result; + + // + string showFibo1LevelsStr = ExtractString( + config, + showFibo1LevelsToken + "(", + ")"); + if (StringLen(showFibo1LevelsStr) > 0) + { + // + bool mShowFibo1Levels = ToBoolean(showFibo1LevelsStr); + result.showFibo1Levels = mShowFibo1Levels; + } + + // + string showFibo2LevelsStr = ExtractString( + config, + showFibo2LevelsToken + "(", + ")"); + if (StringLen(showFibo2LevelsStr) > 0) + { + // + bool mShowFibo2Levels = ToBoolean(showFibo2LevelsStr); + result.showFibo2Levels = mShowFibo2Levels; + } + + // + string showFibo3LevelsStr = ExtractString( + config, + showFibo3LevelsToken + "(", + ")"); + if (StringLen(showFibo3LevelsStr) > 0) + { + // + bool mShowFibo3Levels = ToBoolean(showFibo3LevelsStr); + result.showFibo3Levels = mShowFibo3Levels; + } + + // + string showFibo4LevelsStr = ExtractString( + config, + showFibo4LevelsToken + "(", + ")"); + if (StringLen(showFibo4LevelsStr) > 0) + { + // + bool mShowFibo4Levels = ToBoolean(showFibo4LevelsStr); + result.showFibo4Levels = mShowFibo4Levels; + } + + // + string showFibo5LevelsStr = ExtractString( + config, + showFibo5LevelsToken + "(", + ")"); + if (StringLen(showFibo5LevelsStr) > 0) + { + // + bool mShowFibo5Levels = ToBoolean(showFibo5LevelsStr); + result.showFibo5Levels = mShowFibo5Levels; + } + + // + return result; +} + +// +// +//