diff --git a/BKPS/14040203/Classes/x-saherelm.base.class.mq5 b/BKPS/14040203/Classes/x-saherelm.base.class.mq5 new file mode 100644 index 0000000..0e7557f --- /dev/null +++ b/BKPS/14040203/Classes/x-saherelm.base.class.mq5 @@ -0,0 +1,101 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Class Library +// -------------------------------------- +// Name: XBaseClass +// Description: provides all based classes for use ... +// +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +////////////////////////////////////////////////////// +// +// Global Properties ... +#property library +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://www.saherelm.ir" +#property version "1.00" +#property strict + +// +#include "../Libraries/x-saherelm.common.lib.mq5" + +// +// XBase Class ... +class XCBase +{ + // + // Public ... + public: + // + // Protected ... + + // + // Represent Basic Unique Tag ... + virtual string GetTag() { + return NULL; + } + + // + // Retrieve Class Token ... + virtual string GetToken() { + return NULL; + } + + // + // Protected + protected: + // + // Private ... + private: +}; + +// +template +string GenerateSpecifiedCommonSummary( + T &mItem, + string separator = "\n", + bool includeScores = true, + bool setLabel = false // +) +{ + // + string result = NULL; + + // + double bullishScore = 0; + double bearishScore = 0; + mItem.GenerateScore( + bullishScore, + bearishScore // + ); + + // + result = + // + (!setLabel + ? "" + : "Commons:" + separator) + + "---------------" + separator + + "Symbol: " + mItem.symbol + separator + + "Period: " + ToString(mItem.period) + separator + + "Time: " + ToString(mItem.time) + separator + + (includeScores + ? "---------------" + separator + + "Scores:" + separator + + "---------------" + separator + + "Bullish: " + ToString(bullishScore) + separator + + "Bearish: " + ToString(bearishScore) + separator + + "---------------" + separator + : "") + + "" + // + ; + + // + return result; +} + +// diff --git a/BKPS/14040203/Classes/x-saherelm.x-account.class.mq5 b/BKPS/14040203/Classes/x-saherelm.x-account.class.mq5 new file mode 100644 index 0000000..c451091 --- /dev/null +++ b/BKPS/14040203/Classes/x-saherelm.x-account.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 "../Classes/x-saherelm.base.class.mq5" +#include + +// +// END Import and Inclused requirements ... +// + +// +// START Overrides ... +// + +// +// END Overrides ... +// + +// +// a Class for Manage Account ... +class XCAccount : public XCBase +{ + // + // Public ... + public: + // + // Constructor ... + void XCAccount() + { + // + mAccountInfo = new CAccountInfo(); + } + + // + // Deconstructor ... + void ~XCAccount() + { + } + + // + // 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/BKPS/14040203/Classes/x-saherelm.x-alert.class.mq5 b/BKPS/14040203/Classes/x-saherelm.x-alert.class.mq5 new file mode 100644 index 0000000..c92a6d5 --- /dev/null +++ b/BKPS/14040203/Classes/x-saherelm.x-alert.class.mq5 @@ -0,0 +1,1580 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Class Library +// ---------------------------------------------- +// Name: XSCAlert +// Description: provides all Alerts requirements ... +// +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +////////////////////////////////////////////////////// +// +// Global Properties ... +#property library +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://www.saherelm.ir" +#property version "1.00" +#property strict + +// +// Imports ... +#include "../Classes/x-saherelm.base.class.mq5" + +// +// Class Definition ... + +class XCAlert : public XCBase +{ + // + // Public ... + public: + // + // Props ... + + // + // Constructor ... + XCAlert( + string prefix = "X-Alert", // Alerts Prefixe + bool enableAlerts = true, // Enable Alerts + bool logAlerts = true, // Log Alerts + bool terminalAlerts = false, // Terminal Alerts + bool mailAlerts = false, // Mail Alerts + bool pushAlerts = false // Push Alerts + ) + { + // + mPrefix = prefix; + mLogAlerts = logAlerts; + mMailAlerts = mailAlerts; + mPushAlerts = pushAlerts; + mEnableAlerts = enableAlerts; + mTerminalAlerts = terminalAlerts; + + // + // Normalize Prefix if Not Provided ... + if (!IsValid(mPrefix)) + { + mPrefix = GetTag(); + } + } + + // + // Deconstructor ... + ~XCAlert() + { + } + + // + // Override ... + string GetTag() override + { + return GetSpecificToken(this); + } + + // + // Properties Getter(s) / Setter(s) ... + + // + string GetPrefix() + { + return mPrefix; + } + + // + void SetPrefix(string value) + { + mPrefix = value; + } + + // + bool GetLogAlerts() + { + return mLogAlerts; + } + + // + void SetLogAlerts(bool value) + { + mLogAlerts = value; + } + + // + bool GetEnableAlerts() + { + return mEnableAlerts; + } + + // + void SetEnableAlerts(bool value) + { + mEnableAlerts = value; + } + + // + bool GetPushAlerts() + { + return mPushAlerts; + } + + // + void SetPushAlerts(bool value) + { + mPushAlerts = value; + } + + // + bool GetMailAlerts() + { + return mMailAlerts; + } + + // + void SetMailAlerts(bool value) + { + mMailAlerts = value; + } + + // + bool GetTerminalAlerts() + { + return mTerminalAlerts; + } + + // + void SetTerminalAlerts(bool value) + { + mTerminalAlerts = value; + } + + // + // Tools Funtions ... + + // + // Alerts ... + + // + // Logging an Alert ... + void LogAlert(string message) + { + // + // Validate Args ... + if (!CanLogAlert()) + { + return; + } + + // + Log(message); + } + + // + // Terminal Alert ... + void TerminalAlert(string message) + { + // + // Validate Args ... + if (!CanTerminalAlert()) + { + return; + } + + // + // Prepare Message ... + message = PrepareMessage(message); + + // Send Terminal Alert ... + Alert(message); + } + + // + // Mail Alert ... + void MailAlert(string message) + { + // + // Validate Args ... + if (!CanMailAlert()) + { + return; + } + + // + // Send Mail Alert ... + SendMail(GetPrefix(), message); + } + + // + // Send Push Notification ... + void PushAlert(string message) + { + // + // Validate Args ... + if (!CanPushAlert()) + { + return; + } + + // + // Prepare Message ... + message = PrepareMessage(message); + + // + // Send Push Notification Alert ... + SendNotification(message); + } + + // + // Send an Alert by Handling all Different Specified + // type's of Alert's if they are Enabled ... + void Alert(string message) + { + // + // Handle Log, if Enabled ... + LogAlert(message); + + // + // Handle Mail if Enabled ... + MailAlert(message); + + // + // Handle Push if Enabled ... + PushAlert(message); + + // + // Handle Terminal if Enabled ... + TerminalAlert(message); + } + + // + // Logs ... + + // + // Log a Message ... + void Log(string message) + { + // + if (!CanLog()) + { + return; + } + + // + Print(GetPrefix(), " > ", message); + } + void Log(string tag, string message) + { + // + if (!CanLog()) + { + return; + } + + // + Print(GetPrefix(), "_", tag, " > ", message); + } + void LogEmpty() + { + // + if (!CanLog()) + { + return; + } + + // + Print(" "); + } + + // + // Log Specific Array ... + template + void LogArray( + T &array[], // Array to Log + string label = NULL // Array Label + ) + { + // + if (!CanLog()) + { + return; + } + + // + Print(GetPrefix(), ">", (IsValid(label) ? label : "")); + ArrayPrint(array); + } + + // + // Error ... + + // + // Log an Error ... + void LogError( + int error = -1 // Specific Error, if it's equal to -1, use Last Error ... + ) + { + // + if (!CanLog()) + { + return; + } + + // + if (error <= -1) + { + error = GetLastError(); + } + + // + string errorMsg = GetErrorDescription(error); + + // + Log("Error: " + errorMsg); + } + + // + // Retrieve Specified Error Code Description ... + string GetErrorDescription(int err_code) + { + // + string result = ""; + + // + switch (err_code) + { + // + //--- Constant Description + + // + case ERR_SUCCESS: + result = "The operation completed successfully"; + break; + + // + case ERR_INTERNAL_ERROR: + result = "Unexpected internal error"; + break; + + // + case ERR_WRONG_INTERNAL_PARAMETER: + result = "Wrong parameter in the inner call of the client terminal function"; + break; + + // + case ERR_INVALID_PARAMETER: + result = "Wrong parameter when calling the system function"; + break; + + // + case ERR_NOT_ENOUGH_MEMORY: + result = "Not enough memory to perform the system function"; + break; + + // + case ERR_STRUCT_WITHOBJECTS_ORCLASS: + result = "The structure contains objects of strings and/or dynamic arrays and/or structure of such objects and/or classes"; + break; + + // + case ERR_INVALID_ARRAY: + result = "Array of a wrong type, wrong size, or a damaged object of a dynamic array"; + break; + + // + case ERR_ARRAY_RESIZE_ERROR: + result = "Not enough memory for the relocation of an array, or an attempt to change the size of a static array"; + break; + + // + case ERR_STRING_RESIZE_ERROR: + result = "Not enough memory for the relocation of string"; + break; + + // + case ERR_NOTINITIALIZED_STRING: + result = "Not initialized string"; + break; + + // + case ERR_INVALID_DATETIME: + result = "Invalid date and/or time"; + break; + + // + case ERR_ARRAY_BAD_SIZE: + result = "Requested array size exceeds 2 GB"; + break; + + // + case ERR_INVALID_POINTER: + result = "Wrong pointer"; + break; + + // + case ERR_INVALID_POINTER_TYPE: + result = "Wrong type of pointer"; + break; + + // + case ERR_FUNCTION_NOT_ALLOWED: + result = "System function is not allowed to call"; + break; + + // + //--- Charts + + // + case ERR_CHART_WRONG_ID: + result = "Wrong chart ID"; + break; + + // + case ERR_CHART_NO_REPLY: + result = "Chart does not respond"; + break; + + // + case ERR_CHART_NOT_FOUND: + result = "Chart not found"; + break; + + // + case ERR_CHART_NO_EXPERT: + result = "No Expert Advisor in the chart that could handle the event"; + break; + + // + case ERR_CHART_CANNOT_OPEN: + result = "Chart opening error"; + break; + + // + case ERR_CHART_CANNOT_CHANGE: + result = "Failed to change chart symbol and period"; + break; + + // + case ERR_CHART_CANNOT_CREATE_TIMER: + result = "Failed to create timer"; + break; + + // + case ERR_CHART_WRONG_PROPERTY: + result = "Wrong chart property ID"; + break; + + // + case ERR_CHART_SCREENSHOT_FAILED: + result = "Error creating screenshots"; + break; + + // + case ERR_CHART_NAVIGATE_FAILED: + result = "Error navigating through chart"; + break; + + // + case ERR_CHART_TEMPLATE_FAILED: + result = "Error applying template"; + break; + + // + case ERR_CHART_WINDOW_NOT_FOUND: + result = "Subwindow containing the indicator was not found"; + break; + + // + case ERR_CHART_INDICATOR_CANNOT_ADD: + result = "Error adding an indicator to chart"; + break; + + // + case ERR_CHART_INDICATOR_CANNOT_DEL: + result = "Error deleting an indicator from the chart"; + break; + + // + case ERR_CHART_INDICATOR_NOT_FOUND: + result = "Indicator not found on the specified chart"; + break; + + // + //--- Graphical Objects + case ERR_OBJECT_ERROR: + result = "Error working with a graphical object"; + break; + + // + case ERR_OBJECT_NOT_FOUND: + result = "Graphical object was not found"; + break; + + // + case ERR_OBJECT_WRONG_PROPERTY: + result = "Wrong ID of a graphical object property"; + break; + + // + case ERR_OBJECT_GETDATE_FAILED: + result = "Unable to get date corresponding to the value"; + break; + + // + case ERR_OBJECT_GETVALUE_FAILED: + result = "Unable to get value corresponding to the date"; + break; + + // + //--- MarketInfo + + // + case ERR_MARKET_UNKNOWN_SYMBOL: + result = "Unknown symbol"; + break; + + // + case ERR_MARKET_NOT_SELECTED: + result = "Symbol is not selected in MarketWatch"; + break; + + // + case ERR_MARKET_WRONG_PROPERTY: + result = "Wrong identifier of a symbol property"; + break; + + // + case ERR_MARKET_LASTTIME_UNKNOWN: + result = "Time of the last tick is not known (no ticks)"; + break; + + // + case ERR_MARKET_SELECT_ERROR: + result = "Error adding or deleting a symbol in MarketWatch"; + break; + + // + //--- History Access + + // + case ERR_HISTORY_NOT_FOUND: + result = "Requested history not found"; + break; + + // + case ERR_HISTORY_WRONG_PROPERTY: + result = "Wrong ID of the history property"; + break; + + // + //--- Global_Variables + + // + case ERR_GLOBALVARIABLE_NOT_FOUND: + result = "Global variable of the client terminal is not found"; + break; + + // + case ERR_GLOBALVARIABLE_EXISTS: + result = "Global variable of the client terminal with the same name already exists"; + break; + + // + case ERR_MAIL_SEND_FAILED: + result = "Email sending failed"; + break; + + // + case ERR_PLAY_SOUND_FAILED: + result = "Sound playing failed"; + break; + + // + case ERR_MQL5_WRONG_PROPERTY: + result = "Wrong identifier of the program property"; + break; + + // + case ERR_TERMINAL_WRONG_PROPERTY: + result = "Wrong identifier of the terminal property"; + break; + + // + case ERR_FTP_SEND_FAILED: + result = "File sending via ftp failed"; + break; + + // + case ERR_NOTIFICATION_SEND_FAILED: + result = "Error in sending notification"; + break; + + // + //--- Custom Indicator Buffers + + // + case ERR_BUFFERS_NO_MEMORY: + result = "Not enough memory for the distribution of indicator buffers"; + break; + + // + case ERR_BUFFERS_WRONG_INDEX: + result = "Wrong indicator buffer index"; + break; + + // + //--- Custom Indicator Properties + + // + case ERR_CUSTOM_WRONG_PROPERTY: + result = "Wrong ID of the custom indicator property"; + break; + + // + //--- Account + + // + case ERR_ACCOUNT_WRONG_PROPERTY: + result = "Wrong account property ID"; + break; + + // + case ERR_TRADE_WRONG_PROPERTY: + result = "Wrong trade property ID"; + break; + + // + case ERR_TRADE_DISABLED: + result = "Trading by Expert Advisors prohibited"; + break; + + // + case ERR_TRADE_POSITION_NOT_FOUND: + result = "Position not found"; + break; + + // + case ERR_TRADE_ORDER_NOT_FOUND: + result = "Order not found"; + break; + + // + case ERR_TRADE_DEAL_NOT_FOUND: + result = "Deal not found"; + break; + + // + case ERR_TRADE_SEND_FAILED: + result = "Trade request sending failed"; + break; + + // + //--- Indicators + + // + case ERR_INDICATOR_UNKNOWN_SYMBOL: + result = "Unknown symbol"; + break; + + // + case ERR_INDICATOR_CANNOT_CREATE: + result = "Indicator cannot be created"; + break; + + // + case ERR_INDICATOR_NO_MEMORY: + result = "Not enough memory to add the indicator"; + break; + + // + case ERR_INDICATOR_CANNOT_APPLY: + result = "The indicator cannot be applied to another indicator"; + break; + + // + case ERR_INDICATOR_CANNOT_ADD: + result = "Error applying an indicator to chart"; + break; + + // + case ERR_INDICATOR_DATA_NOT_FOUND: + result = "Requested data not found"; + break; + + // + case ERR_INDICATOR_WRONG_HANDLE: + result = "Wrong indicator handle"; + break; + + // + case ERR_INDICATOR_WRONG_PARAMETERS: + result = "Wrong number of parameters when creating an indicator"; + break; + + // + case ERR_INDICATOR_PARAMETERS_MISSING: + result = "No parameters when creating an indicator"; + break; + + // + case ERR_INDICATOR_CUSTOM_NAME: + result = "The first parameter in the array must be the name of the custom indicator"; + break; + + // + case ERR_INDICATOR_PARAMETER_TYPE: + result = "Invalid parameter type in the array when creating an indicator"; + break; + + // + case ERR_INDICATOR_WRONG_INDEX: + result = "Wrong index of the requested indicator buffer"; + break; + + // + //--- Depth of Market + + // + case ERR_BOOKS_CANNOT_ADD: + result = "Depth Of Market can not be added"; + break; + + // + case ERR_BOOKS_CANNOT_DELETE: + result = "Depth Of Market can not be removed"; + break; + + // + case ERR_BOOKS_CANNOT_GET: + result = "The data from Depth Of Market can not be obtained"; + break; + + // + case ERR_BOOKS_CANNOT_SUBSCRIBE: + result = "Error in subscribing to receive new data from Depth Of Market"; + break; + + // + //--- File Operations + + // + case ERR_TOO_MANY_FILES: + result = "More than 64 files cannot be opened at the same time"; + break; + + // + case ERR_WRONG_FILENAME: + result = "Invalid file name"; + break; + + // + case ERR_TOO_LONG_FILENAME: + result = "Too long file name"; + break; + + // + case ERR_CANNOT_OPEN_FILE: + result = "File opening error"; + break; + + // + case ERR_FILE_CACHEBUFFER_ERROR: + result = "Not enough memory for cache to read"; + break; + + // + case ERR_CANNOT_DELETE_FILE: + result = "File deleting error"; + break; + + // + case ERR_INVALID_FILEHANDLE: + result = "A file with this handle was closed, or was not opening at all"; + break; + + // + case ERR_WRONG_FILEHANDLE: + result = "Wrong file handle"; + break; + + // + case ERR_FILE_NOTTOWRITE: + result = "The file must be opened for writing"; + break; + + // + case ERR_FILE_NOTTOREAD: + result = "The file must be opened for reading"; + break; + + // + case ERR_FILE_NOTBIN: + result = "The file must be opened as a binary one"; + break; + + // + case ERR_FILE_NOTTXT: + result = "The file must be opened as a text"; + break; + + // + case ERR_FILE_NOTTXTORCSV: + result = "The file must be opened as a text or CSV"; + break; + + // + case ERR_FILE_NOTCSV: + result = "The file must be opened as CSV"; + break; + + // + case ERR_FILE_READERROR: + result = "File reading error"; + break; + + // + case ERR_FILE_BINSTRINGSIZE: + result = "String size must be specified, because the file is opened as binary"; + break; + + // + case ERR_INCOMPATIBLE_FILE: + result = "A text file must be for string arrays, for other arrays - binary"; + break; + + // + case ERR_FILE_IS_DIRECTORY: + result = "This is not a file, this is a directory"; + break; + + // + case ERR_FILE_NOT_EXIST: + result = "File does not exist"; + break; + + // + case ERR_FILE_CANNOT_REWRITE: + result = "File can not be rewritten"; + break; + + // + case ERR_WRONG_DIRECTORYNAME: + result = "Wrong directory name"; + break; + + // + case ERR_DIRECTORY_NOT_EXIST: + result = "Directory does not exist"; + break; + + // + case ERR_FILE_ISNOT_DIRECTORY: + result = "This is a file, not a directory"; + break; + + // + case ERR_CANNOT_DELETE_DIRECTORY: + result = "The directory cannot be removed"; + break; + + // + case ERR_CANNOT_CLEAN_DIRECTORY: + result = "Failed to clear the directory (probably one or more files are blocked and removal operation failed)"; + break; + + // + case ERR_FILE_WRITEERROR: + result = "Failed to write a resource to a file"; + break; + + // + //--- String Casting + + // + case ERR_NO_STRING_DATE: + result = "No date in the string"; + break; + + // + case ERR_WRONG_STRING_DATE: + result = "Wrong date in the string"; + break; + + // + case ERR_WRONG_STRING_TIME: + result = "Wrong time in the string"; + break; + + // + case ERR_STRING_TIME_ERROR: + result = "Error converting string to date"; + break; + + // + case ERR_STRING_OUT_OF_MEMORY: + result = "Not enough memory for the string"; + break; + + // + case ERR_STRING_SMALL_LEN: + result = "The string length is less than expected"; + break; + + // + case ERR_STRING_TOO_BIGNUMBER: + result = "Too large number, more than ULONG_MAX"; + break; + + // + case ERR_WRONG_FORMATSTRING: + result = "Invalid format string"; + break; + + // + case ERR_TOO_MANY_FORMATTERS: + result = "Amount of format specifiers more than the parameters"; + break; + + // + case ERR_TOO_MANY_PARAMETERS: + result = "Amount of parameters more than the format specifiers"; + break; + + // + case ERR_WRONG_STRING_PARAMETER: + result = "Damaged parameter of string type"; + break; + + // + case ERR_STRINGPOS_OUTOFRANGE: + result = "Position outside the string"; + break; + + // + case ERR_STRING_ZEROADDED: + result = "0 added to the string end, a useless operation"; + break; + + // + case ERR_STRING_UNKNOWNTYPE: + result = "Unknown data type when converting to a string"; + break; + + // + case ERR_WRONG_STRING_OBJECT: + result = "Damaged string object"; + break; + + // + //--- Operations with Arrays + + // + case ERR_INCOMPATIBLE_ARRAYS: + result = "Copying incompatible arrays. String array can be copied only to a string array, and a numeric array - in numeric array only"; + break; + + // + case ERR_SMALL_ASSERIES_ARRAY: + result = "The receiving array is declared as AS_SERIES, and it is of insufficient size"; + break; + + // + case ERR_SMALL_ARRAY: + result = "Too small array, the starting position is outside the array"; + break; + + // + case ERR_ZEROSIZE_ARRAY: + result = "An array of zero length"; + break; + + // + case ERR_NUMBER_ARRAYS_ONLY: + result = "Must be a numeric array"; + break; + + // + case ERR_ONEDIM_ARRAYS_ONLY: + result = "Must be a one-dimensional array"; + break; + + // + case ERR_SERIES_ARRAY: + result = "Timeseries cannot be used"; + break; + + // + case ERR_DOUBLE_ARRAY_ONLY: + result = "Must be an array of type double"; + break; + + // + case ERR_FLOAT_ARRAY_ONLY: + result = "Must be an array of type float"; + break; + + // + case ERR_LONG_ARRAY_ONLY: + result = "Must be an array of type long"; + break; + + // + case ERR_INT_ARRAY_ONLY: + result = "Must be an array of type int"; + break; + + // + case ERR_SHORT_ARRAY_ONLY: + result = "Must be an array of type short"; + break; + + // + case ERR_CHAR_ARRAY_ONLY: + result = "Must be an array of type char"; + break; + + // + //--- Operations with OpenCL + + // + case ERR_OPENCL_NOT_SUPPORTED: + result = "OpenCL functions are not supported on this computer"; + break; + + // + case ERR_OPENCL_INTERNAL: + result = "Internal error occurred when running OpenCL"; + break; + + // + case ERR_OPENCL_INVALID_HANDLE: + result = "Invalid OpenCL handle"; + break; + + // + case ERR_OPENCL_CONTEXT_CREATE: + result = "Error creating the OpenCL context"; + break; + + // + case ERR_OPENCL_QUEUE_CREATE: + result = "Failed to create a run queue in OpenCL"; + break; + + // + case ERR_OPENCL_PROGRAM_CREATE: + result = "Error occurred when compiling an OpenCL program"; + break; + + // + case ERR_OPENCL_TOO_LONG_KERNEL_NAME: + result = "Too long kernel name (OpenCL kernel)"; + break; + + // + case ERR_OPENCL_KERNEL_CREATE: + result = "Error creating an OpenCL kernel"; + break; + + // + case ERR_OPENCL_SET_KERNEL_PARAMETER: + result = "Error occurred when setting parameters for the OpenCL kernel"; + break; + + // + case ERR_OPENCL_EXECUTE: + result = "OpenCL program runtime error"; + break; + + // + case ERR_OPENCL_WRONG_BUFFER_SIZE: + result = "Invalid size of the OpenCL buffer"; + break; + + // + case ERR_OPENCL_WRONG_BUFFER_OFFSET: + result = "Invalid offset in the OpenCL buffer"; + break; + + // + case ERR_OPENCL_BUFFER_CREATE: + result = "Failed to create and OpenCL buffer"; + break; + + // + //--- User-Defined Errors + default: + result = "UNKNOWN Erro ..."; + break; + } + + // + return result; + } + + // + // Retrieve Specified Error Code Description ... + string GetTradeServerReturnCodeDescription(int return_code) + { + // + string result = ""; + + // + switch (return_code) + { + // + case TRADE_RETCODE_REQUOTE: + result = "Requote"; + break; + + // + case TRADE_RETCODE_REJECT: + result = "Request rejected"; + break; + + // + case TRADE_RETCODE_CANCEL: + result = "Request canceled by trader"; + break; + + // + case TRADE_RETCODE_PLACED: + result = "Order placed"; + break; + + // + case TRADE_RETCODE_DONE: + result = "Request completed"; + break; + + // + case TRADE_RETCODE_DONE_PARTIAL: + result = "Only part of the request was completed"; + break; + + // + case TRADE_RETCODE_ERROR: + result = "Request processing error"; + break; + + // + case TRADE_RETCODE_TIMEOUT: + result = "Request canceled by timeout"; + break; + + // + case TRADE_RETCODE_INVALID: + result = "Invalid request"; + break; + + // + case TRADE_RETCODE_INVALID_VOLUME: + result = "Invalid volume in the request"; + break; + + // + case TRADE_RETCODE_INVALID_PRICE: + result = "Invalid price in the request"; + break; + + // + case TRADE_RETCODE_INVALID_STOPS: + result = "Invalid stops in the request"; + break; + + // + case TRADE_RETCODE_TRADE_DISABLED: + result = "Trade is disabled"; + break; + + // + case TRADE_RETCODE_MARKET_CLOSED: + result = "Market is closed"; + break; + + // + case TRADE_RETCODE_NO_MONEY: + result = "There is not enough money to complete the request"; + break; + + // + case TRADE_RETCODE_PRICE_CHANGED: + result = "Prices changed"; + break; + + // + case TRADE_RETCODE_PRICE_OFF: + result = "There are no quotes to process the request"; + break; + + // + case TRADE_RETCODE_INVALID_EXPIRATION: + result = "Invalid order expiration date in the request"; + break; + + // + case TRADE_RETCODE_ORDER_CHANGED: + result = "Order state changed"; + break; + + // + case TRADE_RETCODE_TOO_MANY_REQUESTS: + result = "Too frequent requests"; + break; + + // + case TRADE_RETCODE_NO_CHANGES: + result = "No changes in request"; + break; + + // + case TRADE_RETCODE_SERVER_DISABLES_AT: + result = "Autotrading disabled by server"; + break; + + // + case TRADE_RETCODE_CLIENT_DISABLES_AT: + result = "Autotrading disabled by client terminal"; + break; + + // + case TRADE_RETCODE_LOCKED: + result = "Request locked for processing"; + break; + + // + case TRADE_RETCODE_FROZEN: + result = "Order or position frozen"; + break; + + // + case TRADE_RETCODE_INVALID_FILL: + result = "Invalid order filling type"; + break; + + // + case TRADE_RETCODE_CONNECTION: + result = "No connection with the trade server"; + break; + + // + case TRADE_RETCODE_ONLY_REAL: + result = "Operation is allowed only for live accounts"; + break; + + // + case TRADE_RETCODE_LIMIT_ORDERS: + result = "The number of pending orders has reached the limit"; + break; + + // + case TRADE_RETCODE_LIMIT_VOLUME: + result = "The volume of orders and positions for the symbol has reached the limit"; + break; + + // + default: + result = "Invalid return code of the trade server"; + break; + } + + // + return result; + } + + // + // Protected ... + protected: + // + // Private ... + + // + bool CanLog() + { + return mLogAlerts; + } + + // + bool CanLogAlert() + { + // + bool result = GetEnableAlerts() && GetLogAlerts(); + + // + return result; + } + + // + bool CanTerminalAlert() + { + // + bool result = GetEnableAlerts() && GetTerminalAlerts(); + + // + return result; + } + + // + bool CanMailAlert() + { + // + bool result = GetEnableAlerts() && GetMailAlerts(); + + // + return result; + } + + // + bool CanPushAlert() + { + // + bool result = GetEnableAlerts() && GetPushAlerts(); + + // + return result; + } + + private: + // + // Props ... + string mPrefix; // Alerts Prefixe + bool mEnableAlerts; // Enable Alerts + bool mLogAlerts; // Log Alerts + bool mTerminalAlerts; // Terminal Alerts + bool mMailAlerts; // Mail Alerts + bool mPushAlerts; // Push Alerts + + // + // Tools ... + + // + // Clear Escape String and + // Attach Alert Prefix to Message ... + string PrepareMessage(string message) + { + // + StringReplace(message, "\n", " | "); + + // + StringConcatenate(message, GetPrefix(), " > ", message); + + // + return message; + } +}; + +// +// a Base Class by Support Alert ... +class XCBaseAlert : public XCBase +{ + // + // Public ... + public: + // + // Props ... + + // + // Constructor(s) ... + void XCBaseAlert() + { + // + // Instance Alert ... + mAlert = new XCAlert(); + } + + // + // Deconstructors ... + void ~XCBaseAlert() + { + // + delete mAlert; + + // + ZeroMemory(mAlert); + } + + // + // Alert Handler Functions ... + + // + // Alert Functions Getter(s) / Setters(s) ... + + // + string GetAlertPrefix() + { + return mAlert.GetPrefix(); + } + + // + void SetAlertPrefix(string value) + { + mAlert.SetPrefix(value); + } + + // + bool GetAlertLogAlerts() + { + return mAlert.GetLogAlerts(); + } + + // + void SetAlertLogAlerts(bool value) + { + mAlert.SetLogAlerts(value); + } + + // + bool GetAlertEnableAlerts() + { + return mAlert.GetEnableAlerts(); + } + + // + void SetAlertEnableAlerts(bool value) + { + mAlert.SetEnableAlerts(value); + } + + // + bool GetAlertPushAlerts() + { + return mAlert.GetPushAlerts(); + } + + // + void SetAlertPushAlerts(bool value) + { + mAlert.SetPushAlerts(value); + } + + // + bool GetAlertMailAlerts() + { + return mAlert.GetMailAlerts(); + } + + // + void SetAlertMailAlerts(bool value) + { + mAlert.SetMailAlerts(value); + } + + // + bool GetAlertTerminalAlerts() + { + return mAlert.GetTerminalAlerts(); + } + + // + void SetAlertTerminalAlerts(bool value) + { + mAlert.SetTerminalAlerts(value); + } + + // + // Alert Actions ... + + // + // Logging an Alert ... + void LogAlert(string message) + { + mAlert.LogAlert(message); + } + + // + // Terminal Alert ... + void TerminalAlert(string message) + { + mAlert.TerminalAlert(message); + } + + // + // Mail Alert ... + void MailAlert(string message) + { + mAlert.MailAlert(message); + } + + // + // Send Push Notification ... + void PushAlert(string message) + { + mAlert.PushAlert(message); + } + + // + // Send an Alert by Handling all Different Specified + // type's of Alert's if they are Enabled ... + void Alert(string message) + { + mAlert.Alert(message); + } + + // + // Logs ... + + // + // Log a Message ... + void Log(string message) + { + mAlert.Log(message); + } + void Log(string tag, string message) + { + mAlert.Log(tag, message); + } + void LogEmpty() + { + mAlert.LogEmpty(); + } + + // + // Log Specific Array ... + template + void LogArray( + T &array[], // Array to Log + string label = NULL // Array Label + ) + { + mAlert.LogArray(array, label); + } + + // + // Error ... + + // + // Log an Error ... + void LogError( + int error = -1 // Specific Error, if it's equal to -1, use Last Error ... + ) + { + mAlert.LogError(error); + } + + // + // Retrieve Specified Error Code Description ... + string GetErrorDescription(int err_code) + { + return mAlert.GetErrorDescription(err_code); + } + + // + // Retrieve Specified Error Code Description ... + string GetTradeServerReturnCodeDescription(int return_code) + { + return mAlert.GetTradeServerReturnCodeDescription(return_code); + } + + // + // Protected ... + protected: + // + // Alert ... + XCAlert *mAlert; + + // + // Private ... + private: +}; + +// \ No newline at end of file diff --git a/BKPS/14040203/Classes/x-saherelm.x-app-dialog.class.mq5 b/BKPS/14040203/Classes/x-saherelm.x-app-dialog.class.mq5 new file mode 100644 index 0000000..fc3de5e --- /dev/null +++ b/BKPS/14040203/Classes/x-saherelm.x-app-dialog.class.mq5 @@ -0,0 +1,278 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Class Library +// -------------------------------------- +// Name: XCPanel +// Description: provides all based classes for use ... +// +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +////////////////////////////////////////////////////// +// +// Global Properties ... +#property library +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://www.saherelm.ir" +#property version "1.00" +#property strict + +// +// Imports ... + +// +#include + +// +#include "../Classes/x-saherelm.base.class.mq5" + +// +// Extentions ... + +/** + * Check a Qery Contains in a Content or not ... + * + * @param mQuery: String ... + * @param mContent: String ... + * @param ignoreCase: Boolean ... + * + * @return ( bool ) + */ +bool XContains( + string mQuery, // Search String + string mContent, // Search Content + bool ignoreCase = true // Ignore Case +) +{ + return Contains( + mQuery, + mContent, + ignoreCase // + ); +} + +// +// Implementation ... + +// +// a Base App Dialog Class ... +class XCAppDialog : public CAppDialog +{ + public: + // + // Action ... + + // + // Virual ... + + /** + * Override Close Button Click Action ... + */ + void OnClickButtonClose() + { + // + bool isClosed = ConfirmDialog("Close EA ?"); + + // + if (isClosed) + { + Destroy(); + } + } + + // + // Configuration Actions ... + + /** + * Show or Hide Minimize Button ... + * + * @param show: boolean + */ + void MinimizeButton(bool show) + { + // + int controlIDX = ControlFind("MinMax"); + if (!IsValidIndex(controlIDX)) + { + return; + } + + // + if (show) + { + Control(controlIDX).Show(); + } + else + { + Control(controlIDX).Hide(); + } + } + + /** + * Show or Hide Close Button ... + * + * @param show: boolean + */ + void CloseButton(bool show) + { + // + int controlIDX = ControlFind("Close"); + if (!IsValidIndex(controlIDX)) + { + return; + } + + // + if (show) + { + Control(controlIDX).Show(); + } + else + { + Control(controlIDX).Hide(); + } + } + + /** + * Minimize Functionality Implementation ... + */ + void Minimize() + { + // + m_minimized = true; + Rebound(m_min_rect); + ClientAreaVisible(false); + } + + /** + * Set Background Color ... + * + * @param clr: Color ... + */ + void BackgroundColor(color clr) + { + // + int controlIDX = ControlFind("Client"); + if (!IsValidIndex(controlIDX)) + { + return; + } + + // + CWnd *obj = Control(controlIDX); + CWndClient *wndclient = (CWndClient *)obj; + + // + wndclient.ColorBackground(clr); + } + + // + // Overrides ... + + // + protected: + // + + /** + * Find Specific Control in Dialog ... + * + * @param name: String to Search + * + * @return ( int ) + */ + int ControlFind(string name) + { + // + int result = -1; + + // + if (!IsValid(name)) + { + return result; + } + + // + int count = ControlsTotal(); + if (!IsValidSize(count)) + { + return result; + } + + // + for (int i = 0; i < count; i++) + { + // + string iName = Control(i).Name(); + + // + bool isContains = XContains( + name, + iName, + true // Ignore Case ... + ); + if (isContains) + { + // + result = i; + break; + } + } + + // + return result; + } + + /** + * Create and Run Confirm Dialog ... + * + * @param message: message for Message Box ... + * + * @return ( bool ) + */ + bool ConfirmDialog(string message = NULL) + { + // + bool result = false; + + // + if (!IsValid(message)) + { + message = "Confirm ?"; + } + + // + int dialogResult = MessageBox(message, NULL, MB_YESNO); + + // + // use 'switch' or 'if' as needed + switch (dialogResult) + { + // + // Yes ... + case IDYES: + result = true; + break; + // + // No ... + case IDNO: + result = false; + break; + // + // Cancel ... + case IDCANCEL: + result = false; + break; + } + + // + return result; + } + + // + private: + // + + // +}; \ No newline at end of file diff --git a/BKPS/14040203/Classes/x-saherelm.x-bar.analyser.class.mq5 b/BKPS/14040203/Classes/x-saherelm.x-bar.analyser.class.mq5 new file mode 100644 index 0000000..b8e5f8a --- /dev/null +++ b/BKPS/14040203/Classes/x-saherelm.x-bar.analyser.class.mq5 @@ -0,0 +1,2755 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Class Library +// -------------------------------------- +// Name: XPOI +// Description: Bar Analysing ... +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +////////////////////////////////////////////////////// +// +// Global Properties ... +#property library +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://www.saherelm.ir" +#property version "1.00" +#property strict + +// +// Imports ... +#include "../Classes/x-saherelm.base.class.mq5" +#include "../Libraries/x-saherelm.x-poi.lib.mq5" + +// +// Definitions ... + +// +// Implementations ... +class XCBarAnalyser : public XCBase +{ + // + public: + // + + // + // Constructor(s) ... + void XCBarAnalyser() + { + } + + // + // Deconstructor ... + void ~XCBarAnalyser() + { + } + + // + // Getter(s) / Setter(s) ... + + // + // Providers ... + + /** + * Calculate Loopback Data for Specific Bar ... + * + * @param index: Integer, Bar Current Index ... + * @param start: Integer, Start of Loopback ... + * @param end: Integer, End of Loopback ... + * @param count: Integer, Number of Calculating Bars ... + * @param bar: XOHCL instance, Specified Bar ... + * @param loopback: Integer, Loopback Length ... + * @return ( bool ) + */ + bool CalculateLoopbackData( + int &index, + int &start, + int &end, + int &count, + XOHCL &bar, + int loopback = 1 // + ) + { + // + bool result = false; + + // + if (loopback < 1) + { + loopback = 1; + } + + // + index = -1; + start = -1; + end = -1; + count = -1; + + // + result = bar.IsValid(); + if (!result) + { + return result; + } + + // + index = bar.Index(); + start = index + 1; + end = start + loopback; + count = end - start; + result = count >= 1; + if (!result) + { + return result; + } + + // + return result; + } + + /** + * Retrieve Loopback HH & LL Data ... + * + * @param hhIDX: Integer, HH Index ... + * @param hh: Double, HH Value ... + * @param llIDX: Integer, LL Index ... + * @param ll: Double, LL Value ... + * @param bar: XOHCL instance ... + * @param loopback: Integer, Loopback Length ... + * + * @return ( bool ) + */ + bool CalculateLoopbackHLData( + int &hhIDX, + double &hh, + int &llIDX, + double &ll, + XOHCL &bar, + int loopback // + ) + { + // + bool result = false; + + // + if (loopback < 1) + { + loopback = 1; + } + + // + int index = -1; + int start = -1; + int end = -1; + int count = -1; + result = CalculateLoopbackData( + index, + start, + end, + count, + bar, + loopback // + ); + if (!result) + { + return result; + } + + // + hhIDX = iHighest( + bar.symbol, + bar.period, + MODE_HIGH, + count, + start // + ); + result = IsValidIndex(hhIDX); + if (!result) + { + return result; + } + + // + llIDX = iLowest( + bar.symbol, + bar.period, + MODE_LOW, + count, + start // + ); + result = IsValidIndex(llIDX); + if (!result) + { + return result; + } + + // + hh = iHigh( + bar.symbol, + bar.period, + hhIDX // + ); + ll = iLow( + bar.symbol, + bar.period, + llIDX // + ); + + // + return result; + } + + /** + * Fill Prices ... + * + * @param prices: double collection + * @param bar: XOHCL instance reference, Provides Start ... + * @param loopback: int, Specified How Many Bars Process ... + * @param type: ENUM_X_PRICE member, Specified Price Type ... + * + * @return ( bool ) + */ + int FillPrice( + double &prices[], + XOHCL &bar, + int loopback = 14, + ENUM_X_PRICE type = X_PRICE_CLOSE // + ) + { + // + int result = 0; + + // + Clean(prices); + + // + loopback = NormalizeInt(loopback, 1); + + // + bool has = IsValid(type) && + bar.IsValid(); + if (!has) + { + return result; + } + + // + string symbol = bar.symbol; + ENUM_TIMEFRAMES period = bar.period; + + // + // Calculate Loopback Data ... + int index = -1; + int start = -1; + int end = -1; + int count = -1; + has = CalculateLoopbackData( + index, + start, + end, + count, + bar, + loopback // + ); + if (!has) + { + return result; + } + + // + for (int i = start; i < end; i++) + { + // + XOHCL iBar; + bool isInited = iBar.Init( + symbol, + period, + i // + ); + if (!isInited) + { + // + iBar.Clean(); + continue; + } + + // + double iPrice = iBar.GetPrice(type); + + // + isInited = NotEmptyZero(iPrice); + if (isInited) + { + // + Add( + iPrice, + prices // + ); + } + + // + iBar.Clean(); + } + + // + result = ArraySize(prices); + has = result == count; + if (!has) + { + // + Clean(prices); + } + + // + ArrayReverse(prices); + + // + return result; + } + + /** + * Calculate Price Range ... + * + * @param ranges: double Collection, Calculated Ranges ... + * @param bar: XOHCL instance Reference, Start Bar ... + * @param forceBody: bool, Force to Calculate Range using Body ... + * @param loopback: int, loopback period for Range Calculations ... + * + * @return ( int ) + */ + int GetPriceRange( + double &ranges[], + XOHCL &bar, + bool forceBody = false, + int loopback = 14 // + ) + { + // + int result = 0; + + // + Clean(ranges); + + // + loopback = NormalizeInt(loopback, 1); + + // + if (!bar.IsValid()) + { + return result; + } + + // + bool has = false; + + // + // Select Uppers Prices ... + double uppers[]; + int uppersCount = 0; + if (forceBody) + { + // + has = FillPrice( + uppers, + bar, + loopback, + X_PRICE_UP // + ); + } + else + { + // + has = FillPrice( + uppers, + bar, + loopback, + X_PRICE_HIGH // + ); + } + if (has) + { + uppersCount = ArraySize(uppers); + } + + // + // Select Lower Prices ... + double lowers[]; + int lowersCount = 0; + if (forceBody) + { + // + has = FillPrice( + lowers, + bar, + loopback, + X_PRICE_DOWN // + ); + } + else + { + // + has = FillPrice( + lowers, + bar, + loopback, + X_PRICE_LOW // + ); + } + if (has) + { + lowersCount = ArraySize(lowers); + } + + // + // Validate Filled Prices ... + has = + IsValidSize(uppersCount) && + IsValidSize(lowersCount) && + uppersCount == lowersCount; + if (!has) + { + // + Clean(uppers); + Clean(lowers); + + // + return result; + } + + // + for (int i = 0; i < uppersCount; i++) + { + // + double iValue = lowers[i] + (uppers[i] - lowers[i]); + + // + Add( + iValue, + ranges // + ); + } + + // + result = ArraySize(ranges); + ArrayReverse(ranges); + + // + // Cleanup Resources ... + + // + Clean(uppers); + Clean(lowers); + + // + return result; + } + + /** + * Retrieve Price Velocities ... + * + * @param velocities: double Collection, Price Velocities ... + * @param bar: XOHCL instance Reference, Start Bar ... + * @param type: ENUM_X_PRICE member ... + * @param loopback: int, loopback period for Calculations ... + * + * @return ( int ) + */ + int GetPriceVelocity( + double &velocities[], + XOHCL &bar, + ENUM_X_PRICE type = X_PRICE_CLOSE, + int loopback = 14 // + ) + { + // + int result = 0; + + // + Clean(velocities); + loopback = NormalizeInt(loopback, 1); + + // + result = IsValid(type) && + bar.IsValid(); + + // + int to = bar.Index(); + int from = to + loopback; + for (int i = to; i < from; i++) + { + // + double iPrice = GetAppliedPrice( + bar.symbol, + bar.period, + i, + type // + ); + + // + double pPrice = GetAppliedPrice( + bar.symbol, + bar.period, + i + 1, + type // + ); + + // + double iVelocity = MathAbs(iPrice - pPrice); + Add( + iVelocity, + velocities // + ); + } + + // + result = ArraySize(velocities); + + // + return result; + } + + /** + * Calculate Price Change Percent ... + * + * @param bar: XOHCL instance Reference, Start Bar ... + * @param type: ENUM_X_PRICE member, Specified Price Type ... + * @param loopback: int, loopback period for Range Calculated ... + * + * @return ( double ) + */ + double GetPriceChangeRate( + XOHCL &bar, + ENUM_X_PRICE type = X_PRICE_MEDIAN, + int loopback = 14 // + ) + { + // + double result = 0; + + // + bool has = false; + + // + loopback = NormalizeInt(loopback, 1); + + // + has = + bar.IsValid() && + IsValid(type); + if (!has) + { + return result; + } + + // + XOHCL oldBar; + has = oldBar.Init( + bar.symbol, + bar.period, + bar.Index() + loopback // + ); + if (!has) + { + // + oldBar.Clean(); + + // + return result; + } + double newPrice = bar.GetPrice(type); + double oldPrice = oldBar.GetPrice(type); + + // + result = ((newPrice - oldPrice) / oldPrice) / 100; + + // + oldBar.Clean(); + + // + return result; + } + + /** + * Detect Same Bars ... + * + * @param bar: XOHCL instance, Start Bar ... + * @param dir: ENUM_X_DIRECTION member, Holds Result Direction ... + * @param index: Integer, Holds Result Index ... + * @param sameBars: Iteger, Required Same Bar ... + * + * @return ( bool ) + */ + bool HasSameBars( + XOHCL &bar, + ENUM_X_DIRECTION &dir, + int &index, + int sameBars = 3 // + ) + { + // + bool result = false; + + // + dir = X_DIRECTION_NONE; + + // + if (sameBars < 1) + { + sameBars = 1; + } + + // + result = bar.IsValid(); + if (!result) + { + return result; + } + + // + index = bar.Index() + 1; + bool canContinue = true; + int sameBullishBarsFounded = 0; + int sameBearishBarsFounded = 0; + bool canContinueForBullish = true; + bool canContinueForBearish = true; + while (canContinue) + { + // + XOHCL iBar; + result = iBar.Init( + bar.symbol, + bar.period, + index // + ); + if (!result) + { + break; + } + + // + bool isBullish = iBar.IsBullish(); + bool isBearish = iBar.IsBearish(); + result = isBullish || + isBearish; + if (!result) + { + break; + } + + // + if (isBullish) + { + // + sameBullishBarsFounded++; + canContinueForBearish = false; + } + else if (isBearish) + { + // + sameBearishBarsFounded++; + canContinueForBullish = false; + } + else + { + // + sameBullishBarsFounded = 0; + sameBearishBarsFounded = 0; + canContinueForBullish = false; + canContinueForBearish = false; + } + + // + result = canContinueForBullish || + canContinueForBearish; + if (!result) + { + break; + } + + // + canContinueForBullish = + canContinueForBullish && + sameBullishBarsFounded > 0; + + // + canContinueForBearish = + canContinueForBearish && + sameBearishBarsFounded > 0; + + // + canContinue = + canContinueForBullish || + canContinueForBearish; + if (canContinue) + { + index++; + } + } + + // + bool hasBullishSameBars = + sameBullishBarsFounded >= sameBars; + + // + bool hasBearishSameBars = + sameBearishBarsFounded >= sameBars; + + // + result = hasBullishSameBars || + hasBearishSameBars; + if (!result) + { + return result; + } + + // + index--; + + // + dir = + hasBullishSameBars + ? X_DIRECTION_BULLISH + : X_DIRECTION_BEARISH; + + // + return result; + } + + /** + * Check Fibonacci Level 382 Pressure ... + * + * @param bar: XOHCL instance ... + * @param dir: ENUM_X_DIRECTION member ... + * + * @return ( bool ) + */ + bool HasFiboPressure( + XOHCL &bar, + ENUM_X_DIRECTION forDir, + ENUM_X_FIBO_LEVELS level // + ) + { + // + bool result = false; + + // + result = bar.IsValid() && + HasDirection(forDir); + if (!result) + { + return result; + } + + // + bool isBullish = IsBullish(forDir); + bool isBearish = IsBearish(forDir); + + // + double fiboLevelValue = GetFibonacciLevel( + bar.high, + bar.low, + level, + forDir // + ); + + // + bool isBullishPressured = + isBullish && + bar.GetDown() > fiboLevelValue; + bool isBearishPressured = + isBearish && + bar.GetUp() < fiboLevelValue; + + // + result = isBullishPressured || + isBearishPressured; + + // + return result; + } + + /** + * Detect Big Price Change Happens or not ... + * + * @param bar: XOHCL instance reference, Start Bar ... + * @param dir: ENUM_X_DIRECTION member, Event Direction ... + * @param rootIDX: int, Root of Momentum Index ... + * @param type: ENUM_X_PRICE member, Price Type ... + * @param forcBodyInRange: bool, Use Body in Range Detection ... + * @param rangeExtendMultiplier: double, a Multiplier for Checking Price Range ... + * + * @return ( bool ) + */ + bool IsSharp( + XOHCL &bar, + ENUM_X_DIRECTION &dir, + int &rootIDX, + ENUM_X_PRICE type = X_PRICE_CLOSE, + bool forcBodyInRange = true, + double rangeExtendMultiplier = 2.0 // + ) + { + // + bool result = false; + + // + dir = X_DIRECTION_NONE; + rangeExtendMultiplier = NormalizeDouble(rangeExtendMultiplier, 1); + + // + result = + bar.IsValid() && + IsValid(type); + if (!result) + { + return result; + } + + // + double minPriceChangePercent = 0; + int loopback = GetPeriodSharpData( + minPriceChangePercent, + bar.period // + ); + + // + // Retrieve Price Change Percent ... + double priceChangePercent = GetPriceChangeRate( + bar, + type, + loopback // + ); + + // + // Velocities ... + double velocities[]; + int velocitiesCount = GetPriceVelocity( + velocities, + bar, + type, + loopback // + ); + double velocitiesAvg = GetAverage(velocities); + double oldPrice = GetAppliedPrice( + bar.symbol, + bar.period, + bar.Index() + loopback, + type // + ); + double newPrice = bar.GetPrice(type); + double currVelocity = MathAbs(oldPrice - newPrice); + + // + // Calculate HH and LL ... + + // + double hh = 0; + double ll = 0; + int hhIDX = -1; + int llIDX = -1; + result = CalculateLoopbackHLData( + hhIDX, + hh, + llIDX, + ll, + bar, + loopback // + ); + result = + result && + ll > 0 && + hh > ll && + IsValidIndex(llIDX) && + IsValidIndex(hhIDX); + if (!result) + { + return result; + } + + // + int hhDiff = (hhIDX - bar.Index()); + int llDiff = (llIDX - bar.Index()); + + // + // Bool Get Boundary Direction ... + + // + // Check Price Change Rate ... + + // + bool isBullish = + // + hhDiff <= 1 && + llIDX > hhIDX && + priceChangePercent > 0 && + priceChangePercent >= minPriceChangePercent && + currVelocity > (velocitiesAvg * rangeExtendMultiplier) + // + ; + + // + bool isBearish = + // + llDiff <= 1 && + hhIDX > llIDX && + priceChangePercent < 0 && + MathAbs(priceChangePercent) >= minPriceChangePercent && + currVelocity > (velocitiesAvg * rangeExtendMultiplier) + // + ; + + // + result = isBullish || + isBearish; + if (result) + { + // + rootIDX = + isBullish + ? llIDX + : hhIDX; + + // + dir = isBullish + ? X_DIRECTION_BULLISH + : X_DIRECTION_BEARISH; + } + + // + return result; + } + + // + // Actions ... + + /** + * Detect Spike ... + * + * @param bar: XOHCL instance reference, Start Bar ... + * @param dir: ENUM_X_DIRECTION member, Event Direction ... + * @param type: ENUM_X_PRICE member, Price Type ... + * @param forcBodyInRange: bool, Use Body in Range Detection ... + * @param rangeExtendMultiplier: double, a Multiplier for Checking Price Range ... + * @param sameBars: int, Specified How Many Same Bars Required for an Spike ... + * + * @return ( bool ) + */ + bool IsSpike( + XOHCL &bar, + ENUM_X_DIRECTION &dir, + int &rootIDX, + ENUM_X_PRICE type = X_PRICE_CLOSE, + bool forcBodyInRange = true, + double rangeExtendMultiplier = 2.0, + int sameBars = 3 // + ) + { + // + bool result = false; + + // + dir = X_DIRECTION_NONE; + sameBars = NormalizeInt(sameBars, 2); + + // + result = IsValid(type) && + bar.IsValid(); + if (!result) + { + return result; + } + + // + // First We Have to Has a Big Change ... + int sharpRootIDX = -1; + result = IsSharp( + bar, + dir, + sharpRootIDX, + type, + forcBodyInRange, + rangeExtendMultiplier // + ); + if (!result) + { + return result; + } + + // + // Check Has Same Bars ... + int sameBarsIndex = -1; + ENUM_X_DIRECTION sameBarsDir; + result = HasSameBars( + bar, + sameBarsDir, + sameBarsIndex, + sameBars // + ); + if (!result) + { + return result; + } + + // + // Check Same Bars Direction sames To Price Change ... + result = sameBarsDir == dir; + if (!result) + { + return result; + } + + // + rootIDX = sharpRootIDX; + + // + return result; + } + + /** + * Check a Bar is Support Bar or not ... + * + * @param bar: XOHCL instance ... + * @param supportBar: XOHCL instance, Provides Fouded Support Bar ... + * @param range: Integer, Specified Verifiation Range ... + * + * @return ( bool ) + */ + bool HasSupport( + XOHCL &bar, + XOHCL &supportBar, + int range = 21 // + ) + { + // + bool result = false; + + // + result = bar.IsValid(); + if (!result) + { + return result; + } + + // + int supportIDX = bar.Index() + range; + result = supportBar.Init( + bar.symbol, + bar.period, + supportIDX // + ); + if (!result) + { + // + supportBar.Clean(); + return result; + } + + // + result = bar.low > supportBar.low; + if (!result) + { + // + supportBar.Clean(); + return result; + } + + // + // Validate Point ... + for (int i = 1; i < range; i++) + { + // + XOHCL iPBar; + XOHCL iNBar; + bool iHas = false; + + // + iHas = iPBar.Init( + bar.symbol, + bar.period, + supportIDX + i // + ); + result = iHas; + if (!result) + { + break; + } + + // + iHas = iNBar.Init( + bar.symbol, + bar.period, + supportIDX - i // + ); + result = iHas; + if (!result) + { + break; + } + + // + result = supportBar.low < iPBar.low && + supportBar.low < iNBar.low; + if (!result) + { + break; + } + } + + // + return result; + } + + /** + * Check a Bar is Resistance Bar or not ... + * + * @param bar: XOHCL instance ... + * @param resistanceBar: XOHCL instance, Provides Fouded Support Bar ... + * @param range: Integer, Specified Verifiation Range ... + * + * @return ( bool ) + */ + bool HasResistance( + XOHCL &bar, + XOHCL &resistanceBar, + int range = 21 // + ) + { + // + bool result = false; + + // + result = bar.IsValid(); + if (!result) + { + return result; + } + + // + int resistanceIDX = bar.Index() + range; + result = resistanceBar.Init( + bar.symbol, + bar.period, + resistanceIDX // + ); + if (!result) + { + // + resistanceBar.Clean(); + return result; + } + + // + result = bar.high < resistanceBar.high; + if (!result) + { + // + resistanceBar.Clean(); + return result; + } + + // + // Validate Point ... + for (int i = 1; i < range; i++) + { + // + XOHCL iPBar; + XOHCL iNBar; + bool iHas = false; + + // + iHas = iPBar.Init( + bar.symbol, + bar.period, + resistanceIDX + i // + ); + result = iHas; + if (!result) + { + break; + } + + // + iHas = iNBar.Init( + bar.symbol, + bar.period, + resistanceIDX - i // + ); + result = iHas; + if (!result) + { + break; + } + + // + result = resistanceBar.high > iPBar.high && + resistanceBar.high > iNBar.high; + if (!result) + { + break; + } + } + + // + return result; + } + + /** + * Detect a Fair Value Gap Based on Given Bar ... + * + * @param bar: XOHCL instance, Specified Start Bar ... + * @param fromBar: XOHCL instance, Provides Start Bar of FVG ... + * @param toBar: XOHCL instance, Provides End Bar of FVG ... + * @param dir: ENUM_X_DIRECTION member, Specified Founded Order Block Direction ... + * @param sameBars: Integer, Specified Min Same Bars for Detecting Order Block ... + * @return ( bool ) + */ + bool HasFairValueGap( + XOHCL &bar, + XOHCL &fromBar, + XOHCL &toBar, + ENUM_X_DIRECTION &dir, + int sameBars = 3 // + ) + { + // + bool result = false; + + // + toBar.Clean(); + fromBar.Clean(); + dir = X_DIRECTION_NONE; + sameBars = NormalizeInt(sameBars, 1); + + // + result = bar.IsValid(); + if (!result) + { + // + toBar.Clean(); + fromBar.Clean(); + return result; + } + + // + int index = 0; + result = HasSameBars( + bar, + dir, + index, + sameBars // + ); + if (!result) + { + return result; + } + + // + bool isBullish = IsBullish(dir); + + // + int to = bar.Index(); + int from = + index > (to + sameBars) + ? to + sameBars + : index; + for (int i = from; i > to; i--) + { + // + result = fromBar.Init( + bar.symbol, + bar.period, + i // + ); + if (!result) + { + break; + } + + // + result = toBar.Init( + bar.symbol, + bar.period, + i - 2 // + ); + if (!result) + { + break; + } + + // + result = isBullish + ? fromBar.high < toBar.low + : fromBar.low > toBar.high; + if (result) + { + break; + } + } + + // + if (!result) + { + // + toBar.Clean(); + fromBar.Clean(); + dir = X_DIRECTION_NONE; + } + + // + return result; + } + + /** + * Detect an Order Block Based on Given Bar ... + * + * @param bar: XOHCL instance, Specified Start Bar ... + * @param ob: XOHCL instance, Fill it if Order Block Found ... + * @param dir: ENUM_X_DIRECTION member, Specified Founded Order Block Direction ... + * @param sameBars: Integer, Specified Min Same Bars for Detecting Order Block ... + * + * @return ( bool ) + */ + bool HasOrderBlock( + XOHCL &bar, + XOHCL &ob, + ENUM_X_DIRECTION &dir, + int sameBars = 3, + bool forceSpike = true, + bool forceFairValueGap = true, + bool forceSupportResistance = true // + ) + { + // + bool result = false; + + // + ob.Clean(); + dir = X_DIRECTION_NONE; + sameBars = NormalizeInt(sameBars, 1); + + // + result = bar.IsValid(); + if (!result) + { + return result; + } + + // + XOHCL sBar; + if (bar.Index() == 0) + { + // + result = bar.GetPreviousBar(sBar); + if (!result) + { + // + sBar.Clean(); + return result; + } + } + else + { + sBar = bar; + } + + // + // First Step We Have to Check Same Bars ... + int spikeRootIDX = -1; + int sameBarsIndex = -1; + result = HasSameBars( + bar, + dir, + sameBarsIndex, + sameBars // + ); + if (!result) + { + // + ob.Clean(); + return result; + } + + // + // Must an Spike Happens ... + if (forceSpike) + { + // + ENUM_X_DIRECTION spikeDir; + result = IsSpike( + bar, + spikeDir, + spikeRootIDX, // Spike Root Index ... + X_PRICE_CLOSE, // Price Type ... + true, // Force Body ... + 1.5, // Range Extend Multiplier ... + sameBars // + ); + result = + result && + dir == spikeDir; + if (!result) + { + // + ob.Clean(); + return result; + } + } + + // + // Select OB Candidate Bars ... + + XOHCL sameBar; + XOHCL rootBar; + XOHCL rootPBar; + result = sameBar.Init( + bar.symbol, + bar.period, + sameBarsIndex + 1 // + ); + if (!result) + { + // + sBar.Clean(); + sameBar.Clean(); + return result; + } + result = rootBar.Init( + bar.symbol, + bar.period, + spikeRootIDX // + ); + if (!result) + { + // + sBar.Clean(); + rootBar.Clean(); + sameBar.Clean(); + return result; + } + result = rootBar.GetPreviousBar(rootPBar); + if (!result) + { + // + sBar.Clean(); + rootBar.Clean(); + sameBar.Clean(); + rootPBar.Clean(); + return result; + } + + // + // Select ob Bar ... + if (rootBar.GetDirection() == Opposit(dir)) + { + ob = rootBar; + } + else if (rootPBar.GetDirection() == Opposit(dir)) + { + ob = rootPBar; + } + else if (sameBar.GetDirection() == Opposit(dir)) + { + ob = sameBar; + } + else + { + ob.Clean(); + } + + // + // Select Order Block Bar ... + result = ob.IsValid(); + ENUM_X_DIRECTION obDir = ob.GetDirection(); + result = + result && + dir == Opposit(obDir); + if (!result) + { + // + sBar.Clean(); + rootBar.Clean(); + sameBar.Clean(); + rootPBar.Clean(); + + // + return result; + } + + // + // if Bullish OB => Supports ... + // if Bearish OB => Resistance ... + if (forceSupportResistance) + { + // + XOHCL supResBar; + + // + // Check Support ... + bool isSupport = HasSupport( + ob, + supResBar // + ); + + // + // Check Resistance ... + bool isResistance = HasResistance( + ob, + supResBar // + ); + + // + supResBar.Clean(); + + // + result = + result && + (IsBullish(dir) + ? isSupport + : isResistance); + + // + if (!result) + { + // + ob.Clean(); + sBar.Clean(); + rootBar.Clean(); + sameBar.Clean(); + rootPBar.Clean(); + + // + return result; + } + } + + // + // Force Check Fair ValueGaps ... + if (forceFairValueGap) + { + // + XOHCL toBar; + XOHCL fromBar; + ENUM_X_DIRECTION fvgDir; + bool isFVG = HasFairValueGap( + bar, + fromBar, + toBar, + fvgDir, + sameBars // + ); + + // + result = + isFVG && + result && + dir == fvgDir; + + // + toBar.Clean(); + fromBar.Clean(); + } + + // + // Cleanup Resource ... + + // + sBar.Clean(); + rootBar.Clean(); + sameBar.Clean(); + rootPBar.Clean(); + + // + return result; + } + + /** + * Check a Bar has Consolidation Zone or not ... + * + * @param bar: XOHCL instance, Specified Start Bar ... + * @param zone: XConsolidationZone instance, consolidation Zone Object ... + * @param minLoopback: int, min Allowed Lopback for Consolidating ... + * @param range: double, Consolidation Range ... + * @param upperAppliedTo: ENUM_X_PRICE member, Upper Selection Price ... + * @param lowerAppliedTo: ENUM_X_PRICE member, Lower Selection Price ... + * + * @return ( bool ) + */ + bool HasConsolidationZone( + XOHCL &bar, + XConsolidationZone &zone, + int minLoopback = 7, + double range = 50, + ENUM_X_PRICE upperAppliedTo = X_PRICE_HIGH, + ENUM_X_PRICE lowerAppliedTo = X_PRICE_LOW // + ) + { + // + bool result = false; + + // + zone.Clean(); + range = NormalizeDouble(range, 50); + minLoopback = NormalizeInt(minLoopback, 7); + + // + result = bar.IsValid(); + if (!result) + { + return result; + } + + // + double points = GetPoints(bar.symbol); + int index = bar.Index() + 1; + int length = minLoopback; + + // + double upperPrice[]; + int upperPriceCount = FillPrice( + upperPrice, + bar, + length, + upperAppliedTo // + ); + + // + double lowerPrice[]; + int lowerPriceCount = FillPrice( + lowerPrice, + bar, + length, + lowerAppliedTo // + ); + + // + result = upperPriceCount == lowerPriceCount && + lowerPriceCount == length; + if (!result) + { + // + Clean(upperPrice); + Clean(lowerPrice); + + // + return result; + } + + // + double upper = upperPrice[ArrayMaximum(upperPrice)]; + double lower = lowerPrice[ArrayMinimum(lowerPrice)]; + + // + bool isBullishBreake = + bar.low > lower && + bar.high > upper && + bar.GetUp() > upper; + bool isBearishBreake = + bar.high < upper && + bar.low < lower && + bar.GetDown() < lower; + result = isBullishBreake || + isBearishBreake; + if (!result) + { + // + Clean(upperPrice); + Clean(lowerPrice); + + // + return result; + } + + // + double delta = upper - lower; + result = delta <= range * points; + if (!result) + { + // + Clean(upperPrice); + Clean(lowerPrice); + + // + return result; + } + + // + while (delta <= range * points) + { + // + length++; + + // + upperPriceCount = FillPrice( + upperPrice, + bar, + length, + upperAppliedTo // + ); + + // + lowerPriceCount = FillPrice( + lowerPrice, + bar, + length, + lowerAppliedTo // + ); + + // + bool isValid = upperPriceCount == lowerPriceCount && + lowerPriceCount == length; + if (!isValid) + { + break; + } + + // + double iUpper = upperPrice[ArrayMaximum(upperPrice)]; + double iLower = lowerPrice[ArrayMinimum(lowerPrice)]; + + // + delta = iUpper - iLower; + if (delta <= range * points) + { + // + upper = iUpper; + lower = iLower; + } + } + + // + Clean(upperPrice); + Clean(lowerPrice); + + // + // Filling Zone ... + zone.upper = upper; + zone.lower = lower; + zone.symbol = bar.symbol; + zone.period = bar.period; + zone.to = iTime( + bar.symbol, + bar.period, + bar.Index() + 1 // + ); + zone.from = iTime( + bar.symbol, + bar.period, + bar.Index() + length // + ); + zone.dir = isBullishBreake + ? X_DIRECTION_BULLISH + : X_DIRECTION_BEARISH; + + // + result = zone.IsValid(); + if (!result) + { + zone.Clean(); + } + + // + return result; + } + + // + // Custom Logics ... + + /** + * Check a Bar is End of an FVG Bar or Not ... + * + * @param bar: XOHCL ... + * @param box: XBoxZone ... + * @param forceType: bool, Force all Bars must be Same as Direction ... + * + * @return ( bool ) + */ + bool IsFVG( + XOHCL &bar, + XBoxZone &box, + bool forceType = false // + ) + { + // + bool result = false; + + // + box.Clean(); + + // + result = bar.IsValid(); + if (!result) + { + return result; + } + + // + XOHCL pBar; + XOHCL p2Bar; + result = bar.GetPreviousBar(pBar); + result = result && + pBar.GetPreviousBar(p2Bar); + if (!result) + { + // + pBar.Clean(); + p2Bar.Clean(); + + // + return result; + } + + // + bool isBullish = p2Bar.high < bar.low; + bool isBearish = p2Bar.low > bar.high; + + // + result = isBullish || + isBearish; + + // + // Apply Force Type ... + if (result) + { + // + if (isBullish) + { + // + result = + bar.IsBullish() && + pBar.IsBullish() && + p2Bar.IsBullish(); + } + else if (isBearish) + { + // + result = + bar.IsBearish() && + pBar.IsBearish() && + p2Bar.IsBearish(); + } + } + + // + if (result) + { + // + box.to = bar.time; + box.from = p2Bar.time; + box.symbol = bar.symbol; + box.period = bar.period; + box.dir = isBullish + ? X_DIRECTION_BULLISH + : X_DIRECTION_BEARISH; + box.upper = isBullish + ? bar.low + : p2Bar.low; + box.lower = isBullish + ? p2Bar.high + : bar.high; + box.type = "XFVG"; + } + + // + pBar.Clean(); + p2Bar.Clean(); + + // + result = box.IsValid(); + + // + return result; + } + + // + // Candlestick ... + + /** + * Check Specified Bar is Doji Pattern or not ... + * + * @param bar: XOHCL instance reference, Specified Bar to Check ... + * @param dir: ENUM_X_DIRECTION member, Specified Doji Direction ... + * @param shadowMultiplier: double, Specified Shadow Multiplier ... + * + * @return ( bool ) + */ + bool IsDoji( + XOHCL &bar, + ENUM_X_DIRECTION &dir, + double shadowMultiplier = 1.5 // + ) + { + // + bool result = false; + + // + dir = X_DIRECTION_NONE; + shadowMultiplier = NormalizeDouble(shadowMultiplier, 1.5, 3); + + // + result = bar.IsValid(); + if (!result) + { + return result; + } + + // + double body = bar.GetBody(); + double range = bar.GetRange(); + + // + result = + body > 0 && + range > 0 + ? (body / range < 0.1) + : false; + if (result) + { + // + dir = + bar.GetLowShadow() >= (bar.GetHighShadow() * shadowMultiplier) + ? X_DIRECTION_BULLISH + : bar.GetHighShadow() >= (bar.GetLowShadow() * shadowMultiplier) + ? X_DIRECTION_BEARISH + : X_DIRECTION_NONE; + // + result = HasDirection(dir); + } + + // + return result; + } + + /** + * Check Specified Bar is Pullback or not ... + * + * @param bar: XOHCL instance reference, Specified Bar to Check ... + * @param dir: ENUM_X_DIRECTION member, Specified Doji Direction ... + * @param loopback: int, Specified Loopback ... + * + * @return ( bool ) + */ + bool IsSwing( + XOHCL &bar, + ENUM_X_DIRECTION &dir, + int loopback = 7 // + ) + { + // + bool result = false; + + // + dir = X_DIRECTION_NONE; + loopback = NormalizeInt(loopback, 1); + + // + result = bar.IsValid(); + if (!result) + { + return result; + } + + // + XOHCL pBar; + result = bar.GetPreviousBar(pBar); + if (!result) + { + // + pBar.Clean(); + return result; + } + + // + XOHCL ppBar; + result = pBar.GetPreviousBar(ppBar); + if (!result) + { + // + pBar.Clean(); + ppBar.Clean(); + return result; + } + + // + bool isBullish = + // + pBar.low < bar.low && + pBar.low < ppBar.low && + bar.GetDown() > pBar.low + // + ; + + // + bool isBearish = + // + pBar.high > bar.high && + pBar.high > ppBar.high && + bar.GetUp() < pBar.high + // + ; + + // + result = isBullish || + isBearish; + if (result) + { + // + dir = + isBullish + ? X_DIRECTION_BULLISH + : X_DIRECTION_BEARISH; + + // + ppBar.Clean(); + int pBarIDX = pBar.Index(); + for (int i = pBarIDX + 1; i < pBarIDX + loopback; i++) + { + // + bool has = ppBar.Init( + pBar.symbol, + pBar.period, + i // + ); + + // + isBullish = + has && + isBullish && + pBar.low < ppBar.low; + + // + isBearish = + has && + isBearish && + pBar.high > ppBar.high; + } + + // + result = isBullish || + isBearish; + if (!result) + { + dir = X_DIRECTION_NONE; + } + } + + // + // Cleanup Resources ... + + // + pBar.Clean(); + ppBar.Clean(); + + // + return result; + } + + /** + * Check Specified Bar is Hammer Pattern or not ... + * + * @param bar: XOHCL instance reference, Specified Bar to Check ... + * @param dir: ENUM_X_DIRECTION member, Specified Doji Direction ... + * @param bodyMultiplier: double, Specified Body Multiplier ... + * + * @return ( bool ) + */ + bool IsHammer( + XOHCL &bar, + ENUM_X_DIRECTION &dir, + double bodyMultiplier = 2.0 // + ) + { + // + bool result = false; + + // + dir = X_DIRECTION_NONE; + bodyMultiplier = NormalizeDouble(bodyMultiplier, 1.5, 3); + + // + result = bar.IsValid(); + if (!result) + { + return result; + } + + // + double body = bar.GetBody(); + double lShadow = bar.GetLowShadow(); + double hShadow = bar.GetHighShadow(); + + // + bool isBullish = + hShadow < body && + lShadow > (bodyMultiplier * body); + + // + bool isBearish = + lShadow < body && + hShadow > (bodyMultiplier * body); + + // + result = isBullish || + isBearish; + if (result) + { + // + dir = + isBullish + ? X_DIRECTION_BULLISH + : X_DIRECTION_BEARISH; + } + + // + return result; + } + + /** + * Check Specified Bar is Engulfed Prev Bar or not ... + * + * @param bar: XOHCL instance reference, Specified Bar to Check ... + * @param dir: ENUM_X_DIRECTION member, Specified Doji Direction ... + * + * @return ( bool ) + */ + bool IsEngulfed( + XOHCL &bar, + ENUM_X_DIRECTION &dir // + ) + { + // + bool result = false; + + // + dir = X_DIRECTION_NONE; + + // + result = bar.IsValid(); + if (!result) + { + return result; + } + + // + XOHCL pBar; + result = bar.GetPreviousBar(pBar); + if (!result) + { + // + pBar.Clean(); + return result; + } + + // + result = bar.GetBody() > pBar.GetBody(); + if (!result) + { + // + pBar.Clean(); + return result; + } + + // + bool isBullish = + bar.IsBullish() && + pBar.IsBearish() && + bar.GetDown() <= pBar.GetDown() && + bar.GetUp() > pBar.GetUp(); + + // + bool isBearish = + bar.IsBearish() && + pBar.IsBullish() && + bar.GetUp() >= pBar.GetUp() && + bar.GetDown() < pBar.GetDown(); + + // + result = isBullish || + isBearish; + if (result) + { + // + dir = + isBullish + ? X_DIRECTION_BULLISH + : X_DIRECTION_BEARISH; + } + + // + // Cleanup Resources ... + + // + pBar.Clean(); + + // + return result; + } + + /** + * Check Specified Bar is Momentum Bar or not ... + * + * @param bar: XOHCL instance reference, Specified Bar to Check ... + * @param dir: ENUM_X_DIRECTION member, Specified Doji Direction ... + * @param forceBarType: bool, Force Apply Bar Type ... + * @param forceFiboPressure: bool, Force Apply Bar Type ... + * + * @return ( bool ) + */ + bool IsRejected( + XOHCL &bar, + ENUM_X_DIRECTION &dir, + bool forceBarType = true, + bool forceFiboPressure = true // + ) + { + // + bool result = false; + + // + dir = X_DIRECTION_NONE; + + // + result = bar.IsValid(); + if (!result) + { + return result; + } + + // + XOHCL pBar; + result = bar.GetPreviousBar(pBar); + if (!result) + { + // + pBar.Clean(); + return result; + } + + // + bool isBullish = + // + bar.low < pBar.low && + bar.GetShadows() > bar.GetBody() && + bar.GetLowShadow() > bar.GetBody() && + bar.GetLowShadow() > bar.GetHighShadow() + // + ; + + // + bool isBearish = + // + bar.high > pBar.high && + bar.GetShadows() > bar.GetBody() && + bar.GetHighShadow() > bar.GetBody() && + bar.GetHighShadow() > bar.GetLowShadow() + // + ; + + // + result = isBullish || + isBearish; + if (!result) + { + // + pBar.Clean(); + return result; + } + + // + // Check Force Type ... + if (forceBarType) + { + // + isBullish = + isBullish && + bar.IsBullish(); + + // + isBearish = + isBearish && + bar.IsBearish(); + + // + result = isBullish || + isBearish; + if (!result) + { + // + pBar.Clean(); + return result; + } + } + + // + // Check Force Fibo Pressure ... + if (forceFiboPressure) + { + // + bool hasBullishFiboPressure = + HasFiboPressure( + bar, + X_DIRECTION_BULLISH, + X_FIBO_LEVEL_236 // + ); + + // + bool hasBearishFiboPressure = + HasFiboPressure( + bar, + X_DIRECTION_BEARISH, + X_FIBO_LEVEL_236 // + ); + + // + isBullish = + isBullish && + hasBullishFiboPressure; + + // + isBearish = + isBearish && + hasBearishFiboPressure; + } + + // + result = isBullish || + isBearish; + if (result) + { + // + dir = + isBullish + ? X_DIRECTION_BULLISH + : X_DIRECTION_BEARISH; + } + + // + pBar.Clean(); + + // + return result; + } + + /** + * Check Specified Bar is Momentum Bar or not ... + * + * @param bar: XOHCL instance reference, Specified Bar to Check ... + * @param dir: ENUM_X_DIRECTION member, Specified Doji Direction ... + * @param loopback: int, Specified Loopback ... + * + * @return ( bool ) + */ + bool IsMomentum( + XOHCL &bar, + ENUM_X_DIRECTION &dir, + int loopback = 2 // + ) + { + // + bool result = false; + + // + dir = X_DIRECTION_NONE; + loopback = NormalizeInt(loopback, 1); + + // + result = bar.IsValid(); + if (!result) + { + return result; + } + + // + XOHCL pBar; + result = bar.GetPreviousBar(pBar); + if (!result) + { + // + pBar.Clean(); + return result; + } + + // + // Calculate HH and LL ... + double hh = 0; + double ll = 0; + int hhIDX = -1; + int llIDX = -1; + result = CalculateLoopbackHLData( + hhIDX, + hh, + llIDX, + ll, + bar, + loopback // s + ); + result = + result && + ll > 0 && + hh > ll && + IsValidIndex(llIDX) && + IsValidIndex(hhIDX); + if (!result) + { + // + pBar.Clean(); + return result; + } + + // + bool isBullish = + bar.low > ll && + bar.close >= hh && + bar.IsBullish() && + bar.low > pBar.low && + bar.high > pBar.high && + bar.GetBody() > pBar.GetBody() && + bar.GetRange() > pBar.GetRange() && + bar.GetShadows() < pBar.GetShadows(); + + // + bool isBearish = + bar.high < hh && + bar.close <= ll && + bar.IsBearish() && + bar.low < pBar.low && + bar.high < pBar.high && + bar.GetBody() > pBar.GetBody() && + bar.GetRange() > pBar.GetRange() && + bar.GetShadows() < pBar.GetShadows(); + + // + result = isBullish || + isBearish; + if (result) + { + // + dir = + isBullish + ? X_DIRECTION_BULLISH + : X_DIRECTION_BEARISH; + } + + // + pBar.Clean(); + + // + return result; + } + + /** + * Check Specified Bar is Pullback or not ... + * + * @param bar: XOHCL instance reference, Specified Bar to Check ... + * @param dir: ENUM_X_DIRECTION member, Specified Doji Direction ... + * @param loopback: int, Specified Loopback ... + * @param forceBody: bool, Force Using Body ... + * + * @return ( bool ) + */ + bool IsPullback( + XOHCL &bar, + ENUM_X_DIRECTION &dir, + int loopback = 3, + bool forceBody = false // + ) + { + // + bool result = false; + + // + dir = X_DIRECTION_NONE; + loopback = NormalizeInt(loopback, 3); + + // + result = bar.IsValid(); + if (!result) + { + return result; + } + + // + // Check Bar Must Engulfed ... + result = IsEngulfed( + bar, + dir // + ); + if (!result) + { + return result; + } + + // + // Calculate HH and LL ... + double hh = 0; + double ll = 0; + int hhIDX = -1; + int llIDX = -1; + result = CalculateLoopbackHLData( + hhIDX, + hh, + llIDX, + ll, + bar, + loopback // + ); + result = + result && + ll > 0 && + hh > ll && + IsValidIndex(llIDX) && + IsValidIndex(hhIDX); + if (!result) + { + return result; + } + + // + bool isBullish = + bar.high > hh && + bar.low > ll; + + // + bool isBearish = + bar.high < hh && + bar.low < ll; + + // + result = isBullish || + isBearish; + if (result) + { + // + if (forceBody) + { + // + isBullish = + isBullish && + bar.GetUp() > hh && + bar.GetDown() > ll && + llIDX == bar.Index() + 1; + + // + isBearish = + isBearish && + bar.GetUp() < hh && + bar.GetDown() < ll && + hhIDX == bar.Index() + 1; + + // + result = isBullish || + isBearish; + } + + // + if (result) + { + // + dir = + isBullish + ? X_DIRECTION_BULLISH + : X_DIRECTION_BEARISH; + } + } + + // + return result; + } + + // + // + // + + /** + * Check a Bar is Valid for Specified Direction of Positions ... + * + * @param bar: XOHCL instance, Start Bar ... + * @param dir: ENUM_X_DIRECTION member, Provide Direction ... + * + * @return ( bool ) + */ + bool IsValidForPosition( + XOHCL &bar, + ENUM_X_DIRECTION &dir // + ) + { + // + bool result = false; + + // + int loopback = 3; + dir = X_DIRECTION_NONE; + + // + result = bar.IsValid(); + if (!result) + { + return result; + } + + // + // DOJI ... + ENUM_X_DIRECTION dojiDir; + bool isDoji = IsDoji( + bar, + dojiDir // + ); + bool isBullishDoji = + isDoji && + IsBullish(dojiDir); + bool isBearishDoji = + isDoji && + IsBearish(dojiDir); + + // + // SWING ... + ENUM_X_DIRECTION swingDir; + bool isSwing = IsSwing( + bar, + swingDir // + ); + bool isBullishSwing = + isSwing && + IsBullish(swingDir); + bool isBearishSwing = + isSwing && + IsBearish(swingDir); + + // + // HAMMER ... + ENUM_X_DIRECTION hammerDir; + bool isHammer = IsHammer( + bar, + hammerDir // + ); + bool isBullishHammer = + isHammer && + IsBullish(hammerDir); + bool isBearishHammer = + isHammer && + IsBearish(hammerDir); + + // + // ENGULF ... + ENUM_X_DIRECTION engulfDir; + bool isEngulfed = IsEngulfed( + bar, + engulfDir // + ); + bool isBullishEngulfed = + isEngulfed && + IsBullish(engulfDir); + bool isBearishEngulfed = + isEngulfed && + IsBearish(engulfDir); + + // + // REJECTED ... + ENUM_X_DIRECTION rejectedDir; + bool isRejected = IsRejected( + bar, + rejectedDir // + ); + bool isBullishRejected = + isRejected && + IsBullish(rejectedDir); + bool isBearishRejected = + isRejected && + IsBearish(rejectedDir); + + // + // MOMENTUM ... + ENUM_X_DIRECTION momentumDir; + bool isMomentum = IsMomentum( + bar, + momentumDir // + ); + bool isBullishMomentum = + isMomentum && + IsBullish(momentumDir); + bool isBearishMomentum = + isMomentum && + IsBearish(momentumDir); + + // + // PULLBACK ... + ENUM_X_DIRECTION pullbackDir; + bool isPullback = IsPullback( + bar, + pullbackDir // + ); + bool isBullishPullback = + isPullback && + IsBullish(pullbackDir); + bool isBearishPullback = + isPullback && + IsBearish(pullbackDir); + + // + // Summarize Conditions ... + + // + bool isBullishOr = + isBullishDoji || + isBullishSwing || + isBullishHammer || + isBullishEngulfed || + isBullishRejected || + isBullishMomentum || + isBullishPullback; + + // + bool isBearishOr = + isBearishDoji || + isBearishSwing || + isBearishHammer || + isBearishEngulfed || + isBearishRejected || + isBearishMomentum || + isBearishPullback; + + // + bool isBullish = + isBullishOr && + !isBearishOr; + + // + bool isBearish = + !isBullishOr && + isBearishOr; + + // + result = isBullish || + isBearish; + if (result) + { + // + dir = + isBullish + ? X_DIRECTION_BULLISH + : X_DIRECTION_BEARISH; + } + + // + return result; + } + + // + protected: + // + + // + private: + // + + // + // Props ... + + // + // Actions ... + + // +}; + +// \ No newline at end of file diff --git a/BKPS/14040203/Classes/x-saherelm.x-cobject.class.mq5 b/BKPS/14040203/Classes/x-saherelm.x-cobject.class.mq5 new file mode 100644 index 0000000..0cac5cd --- /dev/null +++ b/BKPS/14040203/Classes/x-saherelm.x-cobject.class.mq5 @@ -0,0 +1,3178 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Class Library +// -------------------------------------- +// Name: XChartObjects +// Description: provides all require Chart Objects ... +// +// +// 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.x-poi.lib.mq5" +#include "../Libraries/x-saherelm.x-trade.lib.mq5" + +// +#include +#include +#include +#include +#include +#include + +// +// Definitions ... + +enum ENUM_XCHARTOBJECTS +{ + // + // Global ... + X_ZONE_OBJ = 7860, + X_BOX_OBJ = 7861, + X_BAR_ARROW_OBJ = 7862, + // + X_SIGNAL_OBJ = 8860, + X_TREND_OBJ = 8861, + X_XPVPIVOT_OBJ = 8862, + X_OHCL_OBJ = 8863, + X_RR_OBJ = 8864, + // + // Structured ... + X_TRADE_DAY_OBJ = 9860, + X_MARKET_SESSION_OBJ = 9861, + X_SWING_HIGH_OBJ = 9862, + X_SWING_LOW_OBJ = 9863, + X_BULLISH_MOMENTUM_BAR_OBJ = 9864, + X_BEARISH_MOMENTUM_BAR_OBJ = 9865, + X_BULLISH_REJECTION_BAR_OBJ = 9866, + X_BEARISH_REJECTION_BAR_OBJ = 9867, + X_SUPPORT_ZONE_OBJ = 9868, + X_RESISTANCE_ZONE_OBJ = 9869, + X_SUPPLY_ZONE_OBJ = 9870, + X_DEMAND_ZONE_OBJ = 9871, + X_BULLISH_ORDERBLOCK_OBJ = 9872, + X_BEARISH_ORDERBLOCK_OBJ = 9873, + X_BULLISH_FVG_OBJ = 9874, + X_BEARISH_FVG_OBJ = 9875, + X_TICK_ZONE_OBJ = 9876, + X_TICKS_ZONE_OBJ = 9877, + X_CONSOLIDATION_ZONE_OBJ = 9878, +}; + +enum ENUM_X_CHART_IDS +{ + X_TO, + X_FROM, + X_UPPER, + X_LOWER, + X_ENTRY, + X_TARGET, + X_SL, + X_TP, + X_BAR_H_SHW, + X_BAR_BDY, + X_BAR_L_SHW, +}; + +string ToString(ENUM_X_CHART_IDS value) +{ + // + string result = NULL; + + // + switch (value) + { + // + case X_TO: + result = "TO"; + break; + + // + case X_FROM: + result = "FROM"; + break; + + // + case X_UPPER: + result = "UPPER"; + break; + + // + case X_LOWER: + result = "LOWER"; + break; + + // + case X_ENTRY: + result = "ENTRY"; + break; + + // + case X_TARGET: + result = "TARGET"; + break; + + // + case X_SL: + result = "SL"; + break; + + // + case X_TP: + result = "TP"; + break; + + // + case X_BAR_H_SHW: + result = "HSHW"; + break; + + // + case X_BAR_BDY: + result = "BODY"; + break; + + // + case X_BAR_L_SHW: + result = "LSHW"; + break; + + // + } + + // + return result; +} + +// +// Implementation ... + +// +// Global Chart Objects ... + +// +// Bas Chart Object ... +class XCBaseObject : public CChartObject +{ + // + public: + // + + // + // Getter(s) / Setter(s) ... + + /** + * Get Object Specified Name ... + * + * @return ( string ) + */ + string ObjName() + { + return mObjName; + } + + /** + * Set Object Specified Name ... + * + * @param value: String ... + */ + void ObjName(string value) + { + mObjName = value; + } + + // + private: + // + + // + // Props ... + string mObjName; // Object Specified Name ... + + // +}; + +class XCBarArrowObject : public XCBaseObject +{ + // + public: + // + + /** + * Creator ... + * + * @param chart_id: Long, Specified Chart ID ... + * @param name: String, Specified Object ID ... + * @param window: Integer, Specified Chart Window ID ... + * @param swing: XCSwing instance ... + * + * @return ( bool ) + */ + bool CreateByBar( + long chart_id, + string name, + int window, + int arrow, + XOHCL &bar, + ENUM_X_PRICE priceType // + ) + { + // + bool result = false; + + // + result = + // + bar.IsValid() && + IsValid(name) + // + ; + if (!result) + { + return result; + } + + // + datetime time = bar.time; + double price = bar.GetPrice(priceType); + + // + result = mArrow.Create( + chart_id, + name, + window, + time, + price, + (char)arrow // + ); + + // + if (result) + { + ObjName(name); + } + + // + return result; + } + + // + // Virtual ... + + // + // Setter(s) ... + + /** + * Set Arrow Anchor ... + * + * @param value: ENUM_ARROW_ANCHOR member ... + */ + void ArrowAnchor(ENUM_ARROW_ANCHOR value) + { + mArrow.Anchor(value); + } + + /** + * Set Arrow Color ... + * + * @param value: Color ... + */ + void ArrowColor(color value) + { + mArrow.Color(value); + } + + /** + * Set Arrow Width ... + * + * @param value: Integer ... + */ + void ArrowWidth(int value) + { + mArrow.Width(value); + } + + // + private: + // + CChartObjectArrow mArrow; + + // +}; + +// +// Swing ... +class XCSwingObject : public XCBarArrowObject +{ + // + public: + // + + /** + * Creator ... + * + * @param chart_id: Long, Specified Chart ID ... + * @param window: Integer, Specified Chart Window ID ... + * @param swing: XCSwing instance ... + * @param prefix: String ... + * + * @return ( bool ) + */ + bool CreateBySwing( + long chart_id, + int window, + int arrow, + XCSwing &swing, + string prefix = NULL // + ) + { + // + bool result = false; + + // + result = + // + swing.IsValid() + // + ; + if (!result) + { + return result; + } + + // + string name = swing.GetTag(); + if (IsValid(prefix)) + { + name = prefix + "_" + name; + } + + // + XOHCL bar; + result = swing.FillBar(bar); + if (!result) + { + return result; + } + + // + ENUM_X_PRICE price = swing.IsSwingHigh() + ? X_PRICE_HIGH + : X_PRICE_LOW; + + // + result = CreateByBar( + chart_id, + name, + window, + arrow, + bar, + price // + ); + + // + if (result) + { + ObjName(name); + } + + // + return result; + } +}; + +// +// Swing High ... +class XCSwingHighObject : public XCSwingObject +{ + // + public: + // + + /** + * Creator ... + * + * @param chart_id: Long, Specified Chart ID ... + * @param window: Integer, Specified Chart Window ID ... + * @param arrow: Integer, Specified Arrow Code ... + * @param swing: XCSwing instance ... + * @param prefix: String ... + * + * @return ( bool ) + */ + bool Create( + long chart_id, + int window, + int arrow, + XCSwing &swing, + string prefix = NULL // + ) + { + // + bool result = false; + + // + result = swing.IsValid() && + swing.IsSwingHigh(); + if (!result) + { + return result; + } + + // + result = CreateBySwing( + chart_id, + window, + arrow, + swing, + prefix // + ); + + // + return result; + } + + /** + * Retrieve Object Type ... + * + * @return ( ENUM_XCHARTOBJECTS ) + */ + virtual ENUM_XCHARTOBJECTS Type() + { + return X_SWING_HIGH_OBJ; + } + + // +}; + +// +// Swing Low ... +class XCSwingLowObject : public XCSwingObject +{ + // + public: + // + + /** + * Creator ... + * + * @param chart_id: Long, Specified Chart ID ... + * @param window: Integer, Specified Chart Window ID ... + * @param arrow: Integer, Specified Arrow Code ... + * @param swing: XCSwing instance ... + * @param prefix: String ... + * + * @return ( bool ) + */ + bool Create( + long chart_id, + int window, + int arrow, + XCSwing &swing, + string prefix = NULL // + ) + { + // + bool result = false; + + // + result = swing.IsValid() && + swing.IsSwingLow(); + if (!result) + { + return result; + } + + // + result = CreateBySwing( + chart_id, + window, + arrow, + swing, + prefix // + ); + + // + return result; + } + + /** + * Retrieve Object Type ... + * + * @return ( ENUM_XCHARTOBJECTS ) + */ + virtual ENUM_XCHARTOBJECTS Type() + { + return X_SWING_LOW_OBJ; + } + + // +}; + +// +// Momentum ... +class XCMomentumBarObject : public XCBarArrowObject +{ + // + public: + // + + /** + * Creator ... + * + * @param chart_id: Long, Specified Chart ID ... + * @param window: Integer, Specified Chart Window ID ... + * @param momentumBar: XCMomentumBar instance ... + * @param prefix: String ... + * + * @return ( bool ) + */ + bool CreateByMomentum( + long chart_id, + int window, + int arrow, + XCMomentumBar &momentumBar, + string prefix = NULL // + ) + { + // + bool result = false; + + // + result = + // + momentumBar.IsValid() + // + ; + if (!result) + { + return result; + } + + // + string name = momentumBar.GetTag(); + if (IsValid(prefix)) + { + name = prefix + "_" + name; + } + + // + XOHCL bar; + result = momentumBar.FillBar(bar); + if (!result) + { + return result; + } + + // + ENUM_X_PRICE price = momentumBar.IsBullish() + ? X_PRICE_LOW + : X_PRICE_HIGH; + + // + result = CreateByBar( + chart_id, + name, + window, + arrow, + bar, + price // + ); + + // + if (result) + { + ObjName(name); + } + + // + return result; + } +}; + +// +// Bullish Momentum Bar ... +class XCBullishMomentumBarObject : public XCMomentumBarObject +{ + // + public: + // + + /** + * Creator ... + * + * @param chart_id: Long, Specified Chart ID ... + * @param window: Integer, Specified Chart Window ID ... + * @param arrow: Integer, Specified Arrow Code ... + * @param momentumBar: XCMomentumBar instance ... + * @param prefix: String ... + * + * @return ( bool ) + */ + bool Create( + long chart_id, + int window, + int arrow, + XCMomentumBar &momentumBar, + string prefix = NULL // + ) + { + // + bool result = false; + + // + result = momentumBar.IsValid() && + momentumBar.IsBullish(); + if (!result) + { + return result; + } + + // + result = CreateByMomentum( + chart_id, + window, + arrow, + momentumBar, + prefix // + ); + + // + return result; + } + + /** + * Retrieve Object Type ... + * + * @return ( ENUM_XCHARTOBJECTS ) + */ + virtual ENUM_XCHARTOBJECTS Type() + { + return X_BULLISH_MOMENTUM_BAR_OBJ; + } + + // +}; + +// +// Bearish Momentum Bar ... +class XCBearishMomentumBarObject : public XCMomentumBarObject +{ + // + public: + // + + /** + * Creator ... + * + * @param chart_id: Long, Specified Chart ID ... + * @param window: Integer, Specified Chart Window ID ... + * @param arrow: Integer, Specified Arrow Code ... + * @param momentumBar: XCMomentumBar instance ... + * @param prefix: String ... + * + * @return ( bool ) + */ + bool Create( + long chart_id, + int window, + int arrow, + XCMomentumBar &momentumBar, + string prefix = NULL // + ) + { + // + bool result = false; + + // + result = momentumBar.IsValid() && + momentumBar.IsBearish(); + if (!result) + { + return result; + } + + // + result = CreateByMomentum( + chart_id, + window, + arrow, + momentumBar, + prefix // + ); + + // + return result; + } + + /** + * Retrieve Object Type ... + * + * @return ( ENUM_XCHARTOBJECTS ) + */ + virtual ENUM_XCHARTOBJECTS Type() + { + return X_BEARISH_MOMENTUM_BAR_OBJ; + } + + // +}; + +// +// Rejection ... +class XCRejectionBarObject : public XCBarArrowObject +{ + // + public: + // + + /** + * Creator ... + * + * @param chart_id: Long, Specified Chart ID ... + * @param window: Integer, Specified Chart Window ID ... + * @param rejectionBar: XCRejectionBar instance ... + * @param prefix: String ... + * + * @return ( bool ) + */ + bool CreateByRejection( + long chart_id, + int window, + int arrow, + XCRejectionBar &rejectionBar, + string prefix = NULL // + ) + { + // + bool result = false; + + // + result = + // + rejectionBar.IsValid() + // + ; + if (!result) + { + return result; + } + + // + string name = rejectionBar.GetTag(); + if (IsValid(prefix)) + { + name = prefix + "_" + name; + } + + // + XOHCL bar; + result = rejectionBar.FillBar(bar); + if (!result) + { + return result; + } + + // + ENUM_X_PRICE price = rejectionBar.IsBullish() + ? X_PRICE_LOW + : X_PRICE_HIGH; + + // + result = CreateByBar( + chart_id, + name, + window, + arrow, + bar, + price // + ); + + // + if (result) + { + ObjName(name); + } + + // + return result; + } +}; + +// +// Bullish Rejection Bar ... +class XCBullishRejectionBarObject : public XCRejectionBarObject +{ + // + public: + // + + /** + * Creator ... + * + * @param chart_id: Long, Specified Chart ID ... + * @param window: Integer, Specified Chart Window ID ... + * @param arrow: Integer, Specified Arrow Code ... + * @param rejectionBar: XCRejectionBar instance ... + * @param prefix: String ... + * + * @return ( bool ) + */ + bool Create( + long chart_id, + int window, + int arrow, + XCRejectionBar &rejectionBar, + string prefix = NULL // + ) + { + // + bool result = false; + + // + result = rejectionBar.IsValid() && + rejectionBar.IsBullish(); + if (!result) + { + return result; + } + + // + result = CreateByRejection( + chart_id, + window, + arrow, + rejectionBar, + prefix // + ); + + // + return result; + } + + /** + * Retrieve Object Type ... + * + * @return ( ENUM_XCHARTOBJECTS ) + */ + virtual ENUM_XCHARTOBJECTS Type() + { + return X_BULLISH_REJECTION_BAR_OBJ; + } + + // +}; + +// +// Bearish Rejection Bar ... +class XCBearishRejectionBarObject : public XCRejectionBarObject +{ + // + public: + // + + /** + * Creator ... + * + * @param chart_id: Long, Specified Chart ID ... + * @param window: Integer, Specified Chart Window ID ... + * @param arrow: Integer, Specified Arrow Code ... + * @param rejectionBar: XCRejectionBar instance ... + * @param prefix: String ... + * + * @return ( bool ) + */ + bool Create( + long chart_id, + int window, + int arrow, + XCRejectionBar &rejectionBar, + string prefix = NULL // + ) + { + // + bool result = false; + + // + result = rejectionBar.IsValid() && + rejectionBar.IsBearish(); + if (!result) + { + return result; + } + + // + result = CreateByRejection( + chart_id, + window, + arrow, + rejectionBar, + prefix // + ); + + // + return result; + } + + /** + * Retrieve Object Type ... + * + * @return ( ENUM_XCHARTOBJECTS ) + */ + virtual ENUM_XCHARTOBJECTS Type() + { + return X_BEARISH_REJECTION_BAR_OBJ; + } + + // +}; + +// +// XCZoneObject ... +class XCZoneObject : public XCBaseObject +{ + // + public: + // + + /** + * Creator ... + * + * @param chart_id: Long, Specified Chart ID ... + * @param name: String, Specified Object Identifier on Chart ... + * @param window: Integer, Specified Chart Window ID ... + * @param zone: XCZone instance ... + * @param prefix: String ... + * + * @return ( bool ) + */ + bool CreateByZone( + long chart_id, + string name, + int window, + XCZone &zone, + string prefix = NULL // + ) + { + // + bool result = false; + + // + bool isValidFrom = zone.IsValidFrom(); + bool isValidBoundary = zone.IsValidBoundary(); + + // + result = + // + IsValid(name) && + isValidFrom && + isValidBoundary + // + ; + if (!result) + { + return result; + } + + // + if (IsValid(prefix)) + { + name = prefix + "_" + name; + } + + // + datetime from = zone.From(); + datetime to = NormalizeTime(zone.To()); + + // + double upper = zone.Upper(); + double lower = zone.Lower(); + + // + result = mRect.Create( + chart_id, + name, + window, + from, + upper, + to, + lower // + ); + + // + if (result) + { + ObjName(name); + } + + // + return result; + } + + // + // Virtual ... + + /** + * Retrieve Object Type ... + * + * @return ( ENUM_XCHARTOBJECTS ) + */ + virtual ENUM_XCHARTOBJECTS Type() + { + return X_ZONE_OBJ; + } + + // + // Setter(s) ... + + /** + * Set Zone Width ... + * + * @param value: Integer ... + */ + void ZoneWidth(int value) + { + // + if (value < 1) + { + value = 1; + } + + // + mRect.Width(value); + } + + /** + * Set Zone Color ... + * + * @param value: Color ... + */ + void ZoneColor(color value) + { + mRect.Color(value); + } + + /** + * Set Zone Style ... + * + * @param value: ENUM_LINE_STYLE member ... + */ + void ZoneStyle(ENUM_LINE_STYLE value) + { + mRect.Style(value); + } + + /** + * Set Zone Fill ... + * + * @param value: Boolean ... + */ + void ZoneFill(bool value) + { + mRect.Fill(value); + } + + // + private: + // + CChartObjectRectangle mRect; + + // +}; + +// +// Support Zone ... +class XCSupportZoneObject : public XCZoneObject +{ + // + public: + // + + /** + * Creator ... + * + * @param chart_id: Long, Specified Chart ID ... + * @param window: Integer, Specified Chart Window ID ... + * @param zone: XCSupportZone instance ... + * @param prefix: String ... + * + * @return ( bool ) + */ + bool Create( + long chart_id, + int window, + XCSupportZone &zone, + string prefix = NULL // + ) + { + // + bool result = false; + + // + result = zone.IsValid(); + if (!result) + { + return result; + } + + // + string name = zone.GetTag(); + + // + result = CreateByZone( + chart_id, + name, + window, + zone, + prefix // + ); + + // + return result; + } + + // + // Virtual ... + + /** + * Retrieve Object Type ... + * + * @return ( ENUM_XCHARTOBJECTS ) + */ + virtual ENUM_XCHARTOBJECTS Type() + { + return X_SUPPORT_ZONE_OBJ; + } +}; + +// +// Resistance Zone ... +class XCResistanceZoneObject : public XCZoneObject +{ + // + public: + // + + /** + * Creator ... + * + * @param chart_id: Long, Specified Chart ID ... + * @param window: Integer, Specified Chart Window ID ... + * @param zone: XCResistanceZone instance ... + * @param prefix: String ... + * + * @return ( bool ) + */ + bool Create( + long chart_id, + int window, + XCResistanceZone &zone, + string prefix = NULL // + ) + { + // + bool result = false; + + // + result = zone.IsValid(); + if (!result) + { + return result; + } + + // + string name = zone.GetTag(); + + // + result = CreateByZone( + chart_id, + name, + window, + zone, + prefix // + ); + + // + return result; + } + + // + // Virtual ... + + /** + * Retrieve Object Type ... + * + * @return ( ENUM_XCHARTOBJECTS ) + */ + virtual ENUM_XCHARTOBJECTS Type() + { + return X_RESISTANCE_ZONE_OBJ; + } +}; + +// +// Supply Zone ... +class XCSupplyZoneObject : public XCZoneObject +{ + // + public: + // + + /** + * Creator ... + * + * @param chart_id: Long, Specified Chart ID ... + * @param window: Integer, Specified Chart Window ID ... + * @param zone: XCSupplyZone instance ... + * @param prefix: String ... + * + * @return ( bool ) + */ + bool Create( + long chart_id, + int window, + XCSupplyZone &zone, + string prefix = NULL // + ) + { + // + bool result = false; + + // + result = zone.IsValid(); + if (!result) + { + return result; + } + + // + string name = zone.GetTag(); + + // + result = CreateByZone( + chart_id, + name, + window, + zone, + prefix // + ); + + // + return result; + } + + // + // Virtual ... + + /** + * Retrieve Object Type ... + * + * @return ( ENUM_XCHARTOBJECTS ) + */ + virtual ENUM_XCHARTOBJECTS Type() + { + return X_SUPPLY_ZONE_OBJ; + } +}; + +// +// Demand Zone ... +class XCDemandZoneObject : public XCZoneObject +{ + // + public: + // + + /** + * Creator ... + * + * @param chart_id: Long, Specified Chart ID ... + * @param window: Integer, Specified Chart Window ID ... + * @param zone: XCDemandZone instance ... + * @param prefix: String ... + * + * @return ( bool ) + */ + bool Create( + long chart_id, + int window, + XCDemandZone &zone, + string prefix = NULL // + ) + { + // + bool result = false; + + // + result = zone.IsValid(); + if (!result) + { + return result; + } + + // + string name = zone.GetTag(); + + // + result = CreateByZone( + chart_id, + name, + window, + zone, + prefix // + ); + + // + return result; + } + + // + // Virtual ... + + /** + * Retrieve Object Type ... + * + * @return ( ENUM_XCHARTOBJECTS ) + */ + virtual ENUM_XCHARTOBJECTS Type() + { + return X_DEMAND_ZONE_OBJ; + } +}; + +// +// Bullish Order Block ... +class XCBullishOrderBlockObject : public XCZoneObject +{ + // + public: + // + + /** + * Creator ... + * + * @param chart_id: Long, Specified Chart ID ... + * @param window: Integer, Specified Chart Window ID ... + * @param zone: XCOrderBlock instance ... + * @param prefix: String ... + * + * @return ( bool ) + */ + bool Create( + long chart_id, + int window, + XCOrderBlock &zone, + string prefix = NULL // + ) + { + // + bool result = false; + + // + result = zone.IsValid() && + zone.IsBullish(); + if (!result) + { + return result; + } + + // + string name = zone.GetTag(); + + // + result = CreateByZone( + chart_id, + name, + window, + zone, + prefix // + ); + + // + return result; + } + + // + // Virtual ... + + /** + * Retrieve Object Type ... + * + * @return ( ENUM_XCHARTOBJECTS ) + */ + virtual ENUM_XCHARTOBJECTS Type() + { + return X_BULLISH_ORDERBLOCK_OBJ; + } +}; + +// +// Bearish Order Block ... +class XCBearishOrderBlockObject : public XCZoneObject +{ + // + public: + // + + /** + * Creator ... + * + * @param chart_id: Long, Specified Chart ID ... + * @param window: Integer, Specified Chart Window ID ... + * @param zone: XCOrderBlock instance ... + * @param prefix: String ... + * + * @return ( bool ) + */ + bool Create( + long chart_id, + int window, + XCOrderBlock &zone, + string prefix = NULL // + ) + { + // + bool result = false; + + // + result = zone.IsValid() && + zone.IsBearish(); + if (!result) + { + return result; + } + + // + string name = zone.GetTag(); + + // + result = CreateByZone( + chart_id, + name, + window, + zone, + prefix // + ); + + // + return result; + } + + // + // Virtual ... + + /** + * Retrieve Object Type ... + * + * @return ( ENUM_XCHARTOBJECTS ) + */ + virtual ENUM_XCHARTOBJECTS Type() + { + return X_BULLISH_ORDERBLOCK_OBJ; + } +}; + +// +// Bullish Fair Value Gaps ... +class XCBullishFairValueGapObject : public XCZoneObject +{ + // + public: + // + + /** + * Creator ... + * + * @param chart_id: Long, Specified Chart ID ... + * @param window: Integer, Specified Chart Window ID ... + * @param zone: XCOrderBlock instance ... + * @param prefix: String ... + * + * @return ( bool ) + */ + bool Create( + long chart_id, + int window, + XCFVG &zone, + string prefix = NULL // + ) + { + // + bool result = false; + + // + result = zone.IsValid() && + zone.IsBullish(); + if (!result) + { + return result; + } + + // + string name = zone.GetTag(); + + // + result = CreateByZone( + chart_id, + name, + window, + zone, + prefix // + ); + + // + return result; + } + + // + // Virtual ... + + /** + * Retrieve Object Type ... + * + * @return ( ENUM_XCHARTOBJECTS ) + */ + virtual ENUM_XCHARTOBJECTS Type() + { + return X_BULLISH_FVG_OBJ; + } +}; + +class XCConsolidationZoneObject : public XCBaseObject +{ + // + public: + // + + /** + * Creator ... + * + * @param chart_id: Long, Specified Chart ID ... + * @param window: Integer, Specified Chart Window ID ... + * @param zone: XConsolidationZone instance ... + * @param prefix: String ... + * + * @return ( bool ) + */ + bool Create( + long chart_id, + int window, + XConsolidationZone &zone, + string prefix = NULL // + ) + { + // + bool result = false; + + // + result = zone.IsValid(); + if (!result) + { + return result; + } + + // + string name = zone.GetTag(); + if (IsValid(prefix)) + { + name = prefix + "_" + name; + } + + // + result = mRect.Create( + chart_id, + name, + window, + zone.from, + zone.upper, + zone.to, + zone.lower // + ); + + // + if (result) + { + ObjName(name); + } + + // + return result; + } + + // + // Virtual ... + + /** + * Retrieve Object Type ... + * + * @return ( ENUM_XCHARTOBJECTS ) + */ + virtual ENUM_XCHARTOBJECTS Type() + { + return X_CONSOLIDATION_ZONE_OBJ; + } + + // + // Setter(s) ... + + /** + * Set Zone Width ... + * + * @param value: Integer ... + */ + void ZoneWidth(int value) + { + // + if (value < 1) + { + value = 1; + } + + // + mRect.Width(value); + } + + /** + * Set Zone Color ... + * + * @param value: Color ... + */ + void ZoneColor(color value) + { + mRect.Color(value); + } + + /** + * Set Zone Style ... + * + * @param value: ENUM_LINE_STYLE member ... + */ + void ZoneStyle(ENUM_LINE_STYLE value) + { + mRect.Style(value); + } + + /** + * Set Zone Fill ... + * + * @param value: Boolean ... + */ + void ZoneFill(bool value) + { + mRect.Fill(value); + } + + // + private: + // + CChartObjectRectangle mRect; + + // +}; + +// +// Bearish Fair Value Gaps ... +class XCBearishFairValueGapObject : public XCZoneObject +{ + // + public: + // + + /** + * Creator ... + * + * @param chart_id: Long, Specified Chart ID ... + * @param window: Integer, Specified Chart Window ID ... + * @param zone: XCOrderBlock instance ... + * @param prefix: String ... + * + * @return ( bool ) + */ + bool Create( + long chart_id, + int window, + XCFVG &zone, + string prefix = NULL // + ) + { + // + bool result = false; + + // + result = zone.IsValid() && + zone.IsBearish(); + if (!result) + { + return result; + } + + // + string name = zone.GetTag(); + + // + result = CreateByZone( + chart_id, + name, + window, + zone, + prefix // + ); + + // + return result; + } + + // + // Virtual ... + + /** + * Retrieve Object Type ... + * + * @return ( ENUM_XCHARTOBJECTS ) + */ + virtual ENUM_XCHARTOBJECTS Type() + { + return X_BEARISH_FVG_OBJ; + } +}; + +// +// Signal ... +class XCSignalObject : public XCBaseObject +{ + // + public: + // + + // + // Constructor ... + void XCSignalObject() + { + } + + // + // Deconstructor ... + void ~XCSignalObject() + { + } + + /** + * Create a Signal Object on Chart ... + * + * @param chart_id: Long ... + * @param name: String ... + * @param window: Integer ... + * @param signal: XSignal instance ... + * + * @return ( bool ) + */ + bool Create( + long chart_id, + const int window, + XSignal &signal, + string prefix = NULL // + ) + { + // + bool result = false; + + // + result = signal.IsValid(); + if (!result) + { + return result; + } + + // + string name = signal.GetTag(); + if (IsValid(prefix)) + { + name = prefix + "_" + name; + } + string nameMD5 = ToMD5(name); + + // + int delay = (PeriodSeconds(signal.period) * 2); + datetime time1 = (datetime)((int)signal.time - delay); + datetime time2 = (datetime)((int)signal.time + delay); + + // + // TP ... + string tpName = ToString(X_TP) + "_" + nameMD5; + result = mTPTrend.Create( + chart_id, + tpName, + window, + time1, + signal.tp, + time2, + signal.tp // + ); + if (!result) + { + return result; + } + + // + // SL ... + string slName = ToString(X_SL) + "_" + nameMD5; + result = mSLTrend.Create( + chart_id, + slName, + window, + time1, + signal.sl, + time2, + signal.sl // + ); + if (!result) + { + // + mTPTrend.Delete(); + return result; + } + + // + // TARGET ... + bool hasTargets = HasChild(signal.targets); + if (hasTargets) + { + // + int targetsCount = ArraySize(signal.targets); + for (int i = 0; i < targetsCount; i++) + { + // + string targetName = ToString(X_TARGET) + "_" + ToString(i) + "_" + nameMD5; + CChartObjectTrend *mTargetTrend; + mTargetTrend = new CChartObjectTrend(); + result = mTargetTrend.Create( + chart_id, + targetName, + window, + time1, + signal.targets[i], + time2, + signal.targets[i] // + ); + if (!result) + { + // + mTPTrend.Delete(); + mSLTrend.Delete(); + break; + } + + // + mTargetTrends.Add(mTargetTrend); + } + } + + // + // ENTRY ... + string entrName = ToString(X_ENTRY) + "_" + nameMD5; + result = mEntryTrend.Create( + chart_id, + entrName, + window, + time1, + signal.entry, + time2, + signal.entry // + ); + if (!result) + { + // + mTPTrend.Delete(); + mSLTrend.Delete(); + mTargetTrends.Clear(); + return result; + } + + // + // Set Object Name ... + ObjName(name); + + // + return result; + } + + // + // Setter(s) ... + + // + // TP ... + + /** + * Set TP Width ... + * + * @param value: Integer ... + */ + void TPWidth(int value) + { + // + if (value < 1) + { + value = 1; + } + + // + mTPTrend.Width(value); + } + + /** + * Set TP Color ... + * + * @param value: Color ... + */ + void TPColor(color value) + { + mTPTrend.Color(value); + } + + /** + * Set TP Style ... + * + * @param value: ENUM_LINE_STYLE ... + */ + void TPStyle(ENUM_LINE_STYLE value) + { + mTPTrend.Style(value); + } + + // + // SL ... + + /** + * Set SL Width ... + * + * @param value: Integer ... + */ + void SLWidth(int value) + { + // + if (value < 1) + { + value = 1; + } + + // + mSLTrend.Width(value); + } + + /** + * Set SL Color ... + * + * @param value: Color ... + */ + void SLColor(color value) + { + mSLTrend.Color(value); + } + + /** + * Set SL Style ... + * + * @param value: ENUM_LINE_STYLE ... + */ + void SLStyle(ENUM_LINE_STYLE value) + { + mSLTrend.Style(value); + } + + // + // TARGET ... + + /** + * Set Target Width ... + * + * @param value: Integer ... + */ + void TargetWidth(int value) + { + // + if (value < 1) + { + value = 1; + } + + // + for (int i = 0; i < mTargetTrends.Total(); i++) + { + // + CChartObjectTrend *iTrend = (CChartObjectTrend *)mTargetTrends.At(i); + iTrend.Width(value); + } + } + + /** + * Set Target Color ... + * + * @param value: Color ... + */ + void TargetColor(color value) + { + // + for (int i = 0; i < mTargetTrends.Total(); i++) + { + // + CChartObjectTrend *iTrend = (CChartObjectTrend *)mTargetTrends.At(i); + iTrend.Color(value); + } + } + + /** + * Set Target Style ... + * + * @param value: ENUM_LINE_STYLE ... + */ + void TargetStyle(ENUM_LINE_STYLE value) + { + // + for (int i = 0; i < mTargetTrends.Total(); i++) + { + // + CChartObjectTrend *iTrend = (CChartObjectTrend *)mTargetTrends.At(i); + iTrend.Style(value); + } + } + + // + // ENTRY ... + + /** + * Set Entry Width ... + * + * @param value: Integer ... + */ + void EntryWidth(int value) + { + // + if (value < 1) + { + value = 1; + } + + // + mEntryTrend.Width(value); + } + + /** + * Set Entry Color ... + * + * @param value: Color ... + */ + void EntryColor(color value) + { + mEntryTrend.Color(value); + } + + /** + * Set Entry Style ... + * + * @param value: ENUM_LINE_STYLE ... + */ + void EntryStyle(ENUM_LINE_STYLE value) + { + mEntryTrend.Style(value); + } + + /** + * Retrieve Object Type ... + * + * @return ( ENUM_XCHARTOBJECTS ) + */ + virtual ENUM_XCHARTOBJECTS Type() + { + return X_SIGNAL_OBJ; + } + + // + private: + // + + // + CChartObjectTrend mTPTrend; + CChartObjectTrend mSLTrend; + CChartObjectTrend mEntryTrend; + CArrayObj mTargetTrends; +}; + +class XCOHCLObject : public XCBaseObject +{ + // + public: + // + + /** + * Creator ... + * + * @param chart_id: Long, Specified Chart ID ... + * @param window: Integer, Specified Chart Window ID ... + * @param pivot: XPVPivot instance ... + * @param prefix: String ... + * + * @return ( bool ) + */ + bool Create( + long chart_id, + int window, + XOHCL &bar, + datetime to, + string prefix = NULL // + ) + { + // + bool result = false; + + // + result = bar.IsValid() && + IsValid(to); + if (!result) + { + return result; + } + + // + string name = bar.GetTag(); + if (IsValid(prefix)) + { + name = prefix + "_" + name; + } + string nameMD5 = ToMD5(name); + + // + // High Shadow ... + string hShadowName = ToString(X_BAR_H_SHW) + "_" + nameMD5; + + // + result = mHighShadowRect.Create( + chart_id, + hShadowName, + window, + bar.time, + bar.high, + to, + bar.GetUp() // + ); + if (!result) + { + return result; + } + + // + // Body ... + string bodyName = ToString(X_BAR_BDY) + "_" + nameMD5; + + // + result = mBodyRect.Create( + chart_id, + bodyName, + window, + bar.time, + bar.GetUp(), + to, + bar.GetDown() // + ); + if (!result) + { + // + mHighShadowRect.Delete(); + mHighShadowRect.Detach(); + return result; + } + + // + // Low Shadow ... + string lShadowName = ToString(X_BAR_L_SHW) + "_" + nameMD5; + + // + result = mLowShadowRect.Create( + chart_id, + lShadowName, + window, + bar.time, + bar.GetDown(), + to, + bar.low // + ); + if (!result) + { + // + mBodyRect.Delete(); + mBodyRect.Detach(); + mHighShadowRect.Delete(); + mHighShadowRect.Detach(); + return result; + } + + // + if (result) + { + ObjName(name); + } + + // + return result; + } + + // + // Getter(s) / Setter(s) ... + + /** + * Set High Shadow Width ... + * + * @param value: Integer ... + */ + void HighShadowWidth(int value) + { + // + if (value < 1) + { + value = 1; + } + + // + mHighShadowRect.Width(value); + } + + /** + * Set High Shadow Color ... + * + * @param value: Color ... + */ + void HighShadowColor(color value) + { + mHighShadowRect.Color(value); + } + + /** + * Set High Shadow Style ... + * + * @param value: ENUM_LINE_STYLE member ... + */ + void HighShadowStyle(ENUM_LINE_STYLE value) + { + mHighShadowRect.Style(value); + } + + /** + * Set High Shadow Fill ... + * + * @param value: Boolean ... + */ + void HighShadowFill(bool value) + { + mHighShadowRect.Fill(value); + } + + /** + * Set Body Width ... + * + * @param value: Integer ... + */ + void BodyWidth(int value) + { + // + if (value < 1) + { + value = 1; + } + + // + mBodyRect.Width(value); + } + + /** + * Set Body Color ... + * + * @param value: Color ... + */ + void BodyColor(color value) + { + mBodyRect.Color(value); + } + + /** + * Set Body Style ... + * + * @param value: ENUM_LINE_STYLE member ... + */ + void BodyStyle(ENUM_LINE_STYLE value) + { + mBodyRect.Style(value); + } + + /** + * Set Body Fill ... + * + * @param value: Boolean ... + */ + void BodyFill(bool value) + { + mBodyRect.Fill(value); + } + + /** + * Set Low Shadow Width ... + * + * @param value: Integer ... + */ + void LowShadowWidth(int value) + { + // + if (value < 1) + { + value = 1; + } + + // + mLowShadowRect.Width(value); + } + + /** + * Set Low Shadow Color ... + * + * @param value: Color ... + */ + void LowShadowColor(color value) + { + mLowShadowRect.Color(value); + } + + /** + * Set Low Shadow Style ... + * + * @param value: ENUM_LINE_STYLE member ... + */ + void LowShadowStyle(ENUM_LINE_STYLE value) + { + mLowShadowRect.Style(value); + } + + /** + * Set Low Shadow Fill ... + * + * @param value: Boolean ... + */ + void LowShadowFill(bool value) + { + mLowShadowRect.Fill(value); + } + + void BarSpes( + int width = 1, + color clr = clrNONE, + ENUM_LINE_STYLE style = STYLE_SOLID, + bool fill = false // + ) + { + // + BodyWidth(width); + LowShadowWidth(width); + HighShadowWidth(width); + + // + BodyColor(clr); + LowShadowColor(clr); + HighShadowColor(clr); + + // + BodyStyle(style); + LowShadowStyle(style); + HighShadowStyle(style); + + // + BodyFill(fill); + LowShadowFill(fill); + HighShadowFill(fill); + } + + // + // Virtual ... + + /** + * Retrieve Object Type ... + * + * @return ( ENUM_XCHARTOBJECTS ) + */ + virtual ENUM_XCHARTOBJECTS Type() + { + return X_OHCL_OBJ; + } + + // + private: + // + + // + // Props ... + CChartObjectRectangle mHighShadowRect; + CChartObjectRectangle mBodyRect; + CChartObjectRectangle mLowShadowRect; +}; + +class XCBoxObject : public XCBaseObject +{ + // + public: + // + + /** + * Creator ... + * + * @param chart_id: Long, Specified Chart ID ... + * @param window: Integer, Specified Chart Window ID ... + * @param pivot: XPVPivot instance ... + * @param prefix: String ... + * + * @return ( bool ) + */ + bool Create( + long chart_id, + int window, + string name, + double upper, + double lower, + datetime from, + datetime to, + string prefix = NULL // + ) + { + // + bool result = false; + + // + result = + upper > 0 && + lower > 0 && + to > from && + IsValid(to) && + IsValid(name) && + IsValid(from) && + upper > lower; + if (!result) + { + return result; + } + + // + if (IsValid(prefix)) + { + name = prefix + "_" + name; + } + string nameMD5 = ToMD5(name); + + // + result = mRect.Create( + chart_id, + name, + window, + from, + upper, + to, + lower // + ); + if (!result) + { + return result; + } + + // + if (result) + { + ObjName(name); + } + + // + return result; + } + + // + // Getter(s) / Setter(s) ... + + /** + * Set Width ... + * + * @param value: Integer ... + */ + void BoxWidth(int value) + { + // + if (value < 1) + { + value = 1; + } + + // + mRect.Width(value); + } + + /** + * Set Color ... + * + * @param value: Color ... + */ + void BoxColor(color value) + { + mRect.Color(value); + } + + /** + * Set Style ... + * + * @param value: ENUM_LINE_STYLE member ... + */ + void BoxStyle(ENUM_LINE_STYLE value) + { + mRect.Style(value); + } + + /** + * Set Fill ... + * + * @param value: Boolean ... + */ + void BoxFill(bool value) + { + mRect.Fill(value); + } + + // + // Virtual ... + + /** + * Retrieve Object Type ... + * + * @return ( ENUM_XCHARTOBJECTS ) + */ + virtual ENUM_XCHARTOBJECTS Type() + { + return X_BOX_OBJ; + } + + // + private: + // + + // + // Props ... + CChartObjectRectangle mRect; +}; + +// +// Zone Ticks ... + +// +// Specify How to Draws Specified Levels ... +struct XTickZoneLevelSpecs +{ + // + double percent; // Max Allowed Percent of Tick Zone ... + + // + // Label Info ... + color labelColor; + string labelFont; + int labelFontSize; + double labelAngel; + + // + // Zone Info ... + bool zoneFill; + int zoneWidth; + color zoneColor; + ENUM_LINE_STYLE zoneStyle; + + // + // Constructor ... + XTickZoneLevelSpecs() + { + Default(); + } + + // + // Tools ... + + /** + * Initialize Drawing Specs ... + * + * @param _percent: Double, Max Allowed Percent ... + * @param _labelColor: Color, Specified Label Color ... + * @param _zoneColoe: Color, Specified Zone Color ... + * @param _zoneFill: Boolean, Specified Fill Zone or not ... + * @param _zoneStyle: ENUM_LINE_STYLE member, Specified Zone Style ... + * @param _labelFontSize: Integer, Specified Label Font Size ... + * @param _labelFont: String, Specified Label Font Name ... + * @param _labelAngel: Double, Specified Label Angel ... + * + * @return ( bool ) + */ + bool Init( + double _percent, + color _labelColor = clrWhite, + color _zoneColor = clrWhite, + bool _zoneFill = false, + ENUM_LINE_STYLE _zoneStyle = STYLE_DOT, + int _zoneWidth = 1, + int _labelFontSize = 12, + string _labelFont = "Arial", + double _labelAngel = 0 // + ) + { + // + bool result = false; + + // + Default(); + + // + result = _percent > 0; + if (!result) + { + return result; + } + + // + percent = _percent; + labelColor = _labelColor; + zoneColor = _zoneColor; + zoneFill = _zoneFill; + zoneStyle = _zoneStyle; + + // + if (_zoneWidth > 0) + { + zoneWidth = _zoneWidth; + } + + // + if (_labelFontSize > 0) + { + labelFontSize = _labelFontSize; + } + + // + if (IsSpecifiedValid(_labelFont)) + { + labelFont = _labelFont; + } + + // + if (_labelAngel >= 0) + { + labelAngel = _labelAngel; + } + + // + result = IsValid(); + + // + return result; + } + + /** + * Set Default Properties ... + */ + void Default() + { + // + percent = 0; + + // + // Label ... + labelAngel = 0; + labelFontSize = 13; + labelFont = "Arial"; + labelColor = clrWhite; + + // + // Zone ... + zoneWidth = 1; + zoneFill = false; + zoneColor = clrWhite; + zoneStyle = STYLE_DOT; + } + + /** + * Validate ... + * + * @return ( bool ) + */ + bool IsValid() + { + // + bool result = false; + + // + result = + // + percent > 0 && + // + // Zone ... + zoneWidth > 0 && + // + // Label ... + labelFontSize > 0 && + IsSpecifiedValid(labelFont) + // + ; + + // + return result; + } + + // +}; + +class XCTickZoneObject : public XCBaseObject +{ + // + public: + // + + /** + * Creator ... + * + * @param chart_id: Long, Specified Chart ID ... + * @param window: Integer, Specified Chart Window ID ... + * @param name: String, Specify Chart Object Identifier ... + * @param from: Datetime ... + * @param to: Datetime ... + * @param zone: XCTickZone instance ... + * @param prefix: String ... + * + * @return ( bool ) + */ + bool Create( + long chart_id, + int window, + string name, + datetime from, + datetime to, + XCTickZone *zone, + string prefix = NULL // + ) + { + // + bool result = false; + + // + result = + IsValid(name) && + zone.IsValid() && + IsValid(to) && + IsValid(from); + if (!result) + { + return result; + } + + // + double points = GetPoints(zone.symbol); + if (points <= 0) + { + points = 1; + } + double distance = 1 * points; + + // + if (IsValid(prefix)) + { + name = prefix + "_" + name; + } + + // + string rectName = "TKZ_" + name; + result = mRect.Create( + chart_id, + rectName, + window, + from, + zone.high, + to, + zone.low // + ); + if (!result) + { + return result; + } + + // + int fromToDiff = ((int)to - (int)from); + datetime labelsDate = (datetime)((int)to - (fromToDiff / 5)); + + // + string lblName = "LBLT_" + name; + result = mTLabel.Create( + chart_id, + lblName, + window, + labelsDate, + zone.high - distance // + ); + if (!result) + { + return result; + } + + // + mTLabel.Description("T: " + ToString(zone.percent) + "%"); + + // + string lblVName = "LBLV_" + name; + result = mVLabel.Create( + chart_id, + lblVName, + window, + labelsDate, + zone.low + (2.5 * distance) // + ); + if (!result) + { + return result; + } + + // + mVLabel.Description("V: " + ToString(zone.volumePercent) + "%"); + + // + ObjName(name); + + // + return result; + } + + // + // Virtual ... + + /** + * Retrieve Object Type ... + * + * @return ( ENUM_XCHARTOBJECTS ) + */ + virtual ENUM_XCHARTOBJECTS Type() + { + return X_TICK_ZONE_OBJ; + } + + // + // Getter(s) / Setter(s) ... + + /** + * Set Zone Width ... + * + * @param value: Integer ... + */ + void ZoneWidth(int value) + { + // + if (value < 1) + { + value = 1; + } + + // + mRect.Width(value); + } + + /** + * Set Zone Color ... + * + * @param value: Color ... + */ + void ZoneColor(color value) + { + mRect.Color(value); + } + + /** + * Set Zone Style ... + * + * @param value: ENUM_LINE_STYLE member ... + */ + void ZoneStyle(ENUM_LINE_STYLE value) + { + mRect.Style(value); + } + + /** + * Set Zone Fill ... + * + * @param value: Boolean ... + */ + void ZoneFill(bool value) + { + mRect.Fill(value); + } + + /** + * Set Label Color ... + * + * @param value: Color ... + */ + void LabelColor(color value) + { + // + mTLabel.Color(value); + mVLabel.Color(value); + } + + /** + * Set Label Size ... + * + * @param value: Integer ... + */ + void LabelSize(int value) + { + // + mTLabel.FontSize(value); + mVLabel.FontSize(value); + } + + /** + * Set Label Font ... + * + * @param value: String ... + */ + void LabelFont(string value) + { + // + mTLabel.Font(value); + mVLabel.Font(value); + } + + /** + * Set Label Angle ... + * + * @param value: double ... + */ + void LabelAngle(double value) + { + // + mTLabel.Angle(value); + mVLabel.Angle(value); + } + + // + private: + // + // Props ... + CChartObjectRectangle mRect; + CChartObjectLabel mTLabel; + CChartObjectLabel mVLabel; + + // +}; +class XCTicksZoneObject : public XCBaseObject +{ + // + public: + // + + // + void ~XCTicksZoneObject() + { + mZones.Clear(); + } + + /** + * Creator ... + * + * @param chart_id: Long, Specified Chart ID ... + * @param window: Integer, Specified Chart Window ID ... + * @param zone: XCTicksZone instance ... + * @param prefix: String ... + * + * @return ( bool ) + */ + bool Create( + long chart_id, + int window, + XCTicksZone &zone, + XTickZoneLevelSpecs &specs[], + string prefix = NULL // + ) + { + // + bool result = false; + + // + result = zone.IsValid(); + if (!result) + { + return result; + } + + // + string name = zone.GetTag(); + int levels = zone.Levels(); + result = levels > 0; + if (!result) + { + return result; + } + + // + for (int i = 0; i < levels; i++) + { + // + XCTickZone *iZone = zone.GetZone(i); + XCTickZoneObject *iObj; + iObj = new XCTickZoneObject(); + bool isCreated = iObj.Create( + chart_id, + window, + ToString(i) + "_" + name, + zone.From(), + zone.To(), + iZone, + prefix // + ); + if (!isCreated) + { + break; + } + + // + XTickZoneLevelSpecs iSpec; + bool hasSpecs = FindSpecs( + iZone, + iSpec, + specs // + ); + if (hasSpecs) + { + // + // Label ... + iObj.LabelFont(iSpec.labelFont); + iObj.LabelAngle(iSpec.labelAngel); + iObj.LabelColor(iSpec.labelColor); + iObj.LabelSize(iSpec.labelFontSize); + + // + // Zone ... + iObj.ZoneFill(iSpec.zoneFill); + iObj.ZoneColor(iSpec.zoneColor); + iObj.ZoneWidth(iSpec.zoneWidth); + iObj.ZoneStyle(iSpec.zoneStyle); + } + + // + mZones.Add(iObj); + } + + // + if (result) + { + ObjName(name); + } + else + { + mZones.Clear(); + } + + // + return result; + } + + // + // Virtual ... + + /** + * Retrieve Object Type ... + * + * @return ( ENUM_XCHARTOBJECTS ) + */ + virtual ENUM_XCHARTOBJECTS Type() + { + return X_TICKS_ZONE_OBJ; + } + + // + // Getter(s) / Setter(s) ... + + // + // Actions ... + + /** + * Destroy Object ... + */ + void Destroy() + { + mZones.Clear(); + } + + /** + * Find Specified TickZone Drawing Specs ... + * + * @param zone: XCTickZone instance, reference to Search For it ... + * @param spec: XTickZoneLevelSpecs instance, reference to Result ... + * @param specs: XTickZoneLevelSpecs instance Collection for Search ... + * + * @return ( bool ) + */ + bool FindSpecs( + XCTickZone *zone, + XTickZoneLevelSpecs &spec, + XTickZoneLevelSpecs &specs[] // + ) + { + // + bool result = false; + + // + int count = ArraySize(specs); + result = + zone.IsValid() && + IsValidSize(count); + if (!result) + { + return result; + } + + // + for (int i = 0; i < count; i++) + { + // + XTickZoneLevelSpecs iSpecs = specs[i]; + + // + bool isSpecValidForZone = + !spec.IsValid() + ? zone.percent <= iSpecs.percent + : zone.percent <= iSpecs.percent && + spec.percent > iSpecs.percent; + if (isSpecValidForZone) + { + spec = iSpecs; + } + } + + // + result = spec.IsValid(); + + // + return result; + } + + // + private: + // + // Props ... + CArrayObj mZones; + + // +}; + +// \ No newline at end of file diff --git a/BKPS/14040203/Classes/x-saherelm.x-expert.class.mq5 b/BKPS/14040203/Classes/x-saherelm.x-expert.class.mq5 new file mode 100644 index 0000000..db922b4 --- /dev/null +++ b/BKPS/14040203/Classes/x-saherelm.x-expert.class.mq5 @@ -0,0 +1,967 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Class Library +// -------------------------------------- +// Name: XCBaseExpert +// Description: provides all based classes for use ... +// +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +////////////////////////////////////////////////////// +// +// Global Properties ... +#property library +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://www.saherelm.ir" +#property version "1.00" +#property strict + +// +// Imports ... +#include "../Classes/x-saherelm.x-alert.class.mq5" +#include "../Classes/x-saherelm.x-trade.class.mq5" + +// +// Definitions ... +string XCBaseExpertToken = "XCBaseEA"; + +// +// Inputs ... + +// +// Implementations ... +class XCBaseExpert : public XCBaseAlert +{ + // + public: + // + + // + XCTrade *mTrader; // Trader of Expert Adviser ... + + // + // Constructur(s) ... + void XCBaseExpert() + { + } + + // + // Deconstructor ... + void ~XCBaseExpert() + { + // + delete mTrader; + + // + ZeroMemory(mTrader); + } + + // + // Getter(s) / Setter(s) ... + + // + // Common ... + + /** + * Get Magic Number ... + * + * @return ( long ) + */ + long MagicNumber() + { + return mMagicNumber; + } + + /** + * Set Magic Number ... + * + * @param value: Long ... + */ + void MagicNumber(long value) + { + // + mMagicNumber = value; + ReConfigure(); + } + + /** + * Get Slippage ... + * + * @return ( int ) + */ + int Slippage() + { + return mSlippage; + } + + /** + * Set Slippage ... + * + * @param value: Integer ... + */ + void Slippage(int value) + { + // + mSlippage = value; + ReConfigure(); + } + + /** + * Get Tag Prefix ... + * + * @return ( string ) + */ + string TagPrefix() + { + return mTagPrefix; + } + + /** + * Set Tag Prefix ... + * + * @param value: String ... + */ + void TagPrefix(string value) + { + // + mTagPrefix = value; + ReConfigure(); + } + + // + // Symbol ... + + /** + * Get Period ... + * + * @return ( ENUM_TIMEFRAMES ) + */ + ENUM_TIMEFRAMES GetPeriod() + { + return mPeriod; + } + + /** + * Set Period ... + * + * @param value: ENUM_TIMEFRAMES member ... + */ + void SetPeriod(ENUM_TIMEFRAMES value) + { + // + mPeriod = value; + ReConfigure(); + } + + /** + * Get Symbol ... + * + * @return ( string ) + */ + string GetSymbol() + { + return mSymbol; + } + + /** + * Set Symbol ... + * + * @param value: String ... + */ + void SetSymbol(string value) + { + // + mSymbol = value; + ReConfigure(); + } + + /** + * Get Multi Symbol is Enable or Not ... + * + * @return ( bool ) + */ + bool MultiSymbol() + { + return mMultiSymbol; + } + + /** + * Set Multi Symbol is Enable or Not ... + * + * @param value: Boolean ... + */ + void MultiSymbol(bool value) + { + // + mMultiSymbol = value; + ReConfigure(); + } + + /** + * Get Multi Provided Symbols ... + * + * @return ( string ) + */ + string Symbols() + { + return mSymbols; + } + + /** + * Set Multi Provided Symbols ... + * + * @param value: String ... + */ + void Symbols(string value) + { + // + mSymbols = value; + ReConfigure(); + } + + // + // Signalling ... + + /** + * Get Force Disable Signalling ... + * + * @return ( bool ) + */ + bool Disabled() + { + return mDisabled; + } + + /** + * Set Force Disable Signalling ... + * + * @param value: Boolean ... + */ + void Disabled(bool value) + { + // + mDisabled = value; + ReConfigure(); + } + + /** + * Get Allow Long Signals ... + * + * @return ( bool ) + */ + bool AllowLong() + { + return mAllowLong; + } + + /** + * Set Allow Long Signals ... + * + * @param value: Boolean ... + */ + void AllowLong(bool value) + { + // + mAllowLong = value; + ReConfigure(); + } + + /** + * Get Allow Short Signalling ... + * + * @return ( bool ) + */ + bool AllowShort() + { + return mAllowShort; + } + + /** + * Set Allow Short Signalling ... + * + * @param value: Boolean ... + */ + void AllowShort(bool value) + { + // + mAllowShort = value; + ReConfigure(); + } + + // + // Reports ... + + /** + * Get Report New Month State ... + * + * @return ( bool ) + */ + bool ReportNewMonths() + { + return mReportNewMonths; + } + + /** + * Set Report New Month State ... + * + * @param value: Boolean ... + */ + void ReportNewMonths(bool value) + { + // + mReportNewMonths = value; + ReConfigure(); + } + + /** + * Get Report New Weeks State ... + * + * @return ( bool ) + */ + bool ReportNewWeeks() + { + return mReportNewWeeks; + } + + /** + * Set Report New Weeks State ... + * + * @param value: Boolean ... + */ + void ReportNewWeeks(bool value) + { + // + mReportNewWeeks = value; + ReConfigure(); + } + + /** + * Get Report New Days State ... + * + * @return ( bool ) + */ + bool ReportNewDays() + { + return mReportNewDays; + } + + /** + * Set Report New Days State ... + * + * @param value: Boolean ... + */ + void ReportNewDays(bool value) + { + // + mReportNewDays = value; + ReConfigure(); + } + + /** + * Get Report New Hours State ... + * + * @return ( bool ) + */ + bool ReportNewHours() + { + return mReportNewHours; + } + + /** + * Set Report New Hours State ... + * + * @param value: Boolean ... + */ + void ReportNewHours(bool value) + { + // + mReportNewHours = value; + ReConfigure(); + } + + // + // Actions ... + + /** + * Handle Expert OnInit Event ... + * + * @return ( bool ) + */ + bool HandleOnInit() + { + // + bool result = false; + + // + string message = ""; + + // + // Validate Input ... + result = ValidateInputs(); + if (!result) + { + // + message = "Invalid Inputs ...."; + + // + Alert(message); + } + + // + // Initial All Requirements ... + result = InitEA(); + if (!result) + { + return result; + } + + // + // Initial All GUI Requirements ... + result = InitGUI(); + if (!result) + { + return result; + } + + // + message = "Initialized Successfully ..."; + Alert(message); + + // + return result; + } + + /** + * Handle Expert OnDeInit Event ... + */ + void HandleOnDeInit() + { + // + // Destroy all GUI Requirements ... + DestroyGUI(); + + // + // Alert De Initialization Succeeded ... + string msg = "De Initialized Successfully ..."; + Alert(msg); + + // + // Destroy all EA Requirements ... + DestroyEA(); + } + + /** + * Handle Expert OnTick Event ... + */ + void HandleOnTick() + { + // + UpdateGUI(); + HandleReportTime(); + HandleStrategiesOnTick(); + HandleStrategiesGuard(); + } + + /** + * Handle Expert OnTrade Event ... + */ + void HandleOnTrade() + { + mTrader.HandleOnTrade(); + } + + /** + * Handle Expert OnTimer Event ... + */ + void HandleOnTimer() + { + } + + /** + * Handle Expert OnChart Event ... + */ + void HandleOnChartEvent( + const int id, + const long &lparam, + const double &dparam, + const string &sparam // + ) + { + } + + // + // Virtual Actions ... + + /** + * Apply Default Configurations ... + */ + virtual void DefaultConfigure() + { + // + // Commons ... + Slippage(10); + TagPrefix(""); + MagicNumber(1694056); + + // + // Symbol ... + SetSymbol(_Symbol); + SetPeriod(_Period); + MultiSymbol(false); + Symbols("EURUSDb,GBPUSDb,USDJPYb,USDCHFb,DowJones30,XAUUSDb"); + + // + // Signalling ... + Disabled(false); + AllowLong(true); + AllowShort(true); + + // + string tag = GetTag(); + + // + // Alert ... + SetAlertPrefix(tag); + SetAlertLogAlerts(true); + SetAlertPushAlerts(true); + SetAlertMailAlerts(false); + SetAlertEnableAlerts(true); + SetAlertTerminalAlerts(false); + + // + // Reports ... + ReportNewDays(true); + ReportNewWeeks(false); + ReportNewHours(false); + ReportNewMonths(false); + } + + /** + * Vaslidate Inputs ... + * + * @return ( virtual bool ) + */ + virtual bool ValidateInputs() + { + // + bool result = false; + + // + string errMessage = ""; + + // + bool isCommonValid = ( + // + mSlippage > 0 && + mMagicNumber > 0 + // + ); + if (!isCommonValid) + { + // + errMessage += "common configurations error;" + "\n"; + } + + // + result = + // + // Common ... + isCommonValid && + // + // Otere ... + true + // + ; + + // + if (!result) + { + // + // Since here Logger not Initiallized, we Use Raw Print Command ... + errMessage = " Errors: \n" + errMessage; + Alert(errMessage); + } + + // + return result; + } + + // + // Initializers and DeInitializers ... + + /** + * Initial EA Requirements ... + * + * @return ( virtual bool ) + */ + virtual bool InitEA() + { + // + bool result = false; + + // + // Initialize Indicator Helpers ... + + // + // Create Trader Instance and Configure it ... + mTrader = new XCTrade( + mSlippage, + mMagicNumber // + ); + + // + return result; + } + + /** + * Destroy Initialized Requirements ... + */ + virtual void DestroyEA() + { + // + delete mTrader; + + // + ZeroMemory(mTrader); + } + + /** + * GUI Initialize if required ... + * + * @return ( virtual bool ) + */ + virtual bool InitGUI() + { + // + bool result = false; + + // + result = true; + + // + return result; + } + + /** + * Update All GUI Contents ... + */ + virtual void UpdateGUI() + { + } + + /** + * Destroy all Initialized GUi Elements ... + */ + virtual void DestroyGUI() + { + } + + // + // Event Handlers ... + + /** + * Calls When a Position's SL Triggered ... + * + * @param deal: XDeal instance ... + */ + virtual void HandleOnStopLossTriggered(const XDeal &deal) + { + HandleReportBalance(); + } + + /** + * Calls When a Position's TP Triggered ... + * + * @param deal: XDeal instance ... + */ + virtual void HandleOnTakeProfitTriggered(const XDeal &deal) + { + HandleReportBalance(); + } + + /** + * Handle Force Close a Position ... + * + * @param ticket: Position Ticket ... + * @param position: XPosition ... + * @param comment: Closing Comment ... + */ + virtual void HandleOnPositionForceClosed( + const ulong ticket, + const XPosition &position, + const string comment // + ) + { + HandleReportBalance(); + } + + /** + * Handle Position Modified ... + * + * @param ticket: ULONG ... + * @param profit: Double ... + * @param comment: String ... + */ + virtual void HandleOnPositionModified( + const ulong ticket, + const double profit, + const string comment // + ) + { + } + + /** + * Handle Position Partially Closed ... + * + * @param ticket: ULONG ... + * @param profit: Double ... + * @param comment: String ... + */ + virtual void HandleOnPositionPartialClosed( + const ulong ticket, + const double profit, + const string comment // + ) + { + } + + /** + * Handle Deals Changed ... + * + * @param count: Integer, Number of Changes ... + */ + virtual void HandleOnDealsChanged(int count) + { + } + + /** + * Handle Orders Changed ... + * + * @param count: Integer, Number of Changes ... + */ + virtual void HandleOnOrdersChanged(int count) + { + } + + /** + * Handle Positions Changed ... + * + * @param count: Integer, Number of Changes ... + */ + virtual void HandleOnPositionsChanged(int count) + { + } + + /** + * Do All Signalling Processing Here ... + */ + virtual void HandleStrategiesOnTick() + { + } + + /** + * Check Strategies for Guards and then Apply Them ... + */ + virtual void HandleStrategiesGuard() + { + } + + // + // Time Handlers ... + + virtual void HandleOnNewMonth() + { + } + + virtual void HandleOnNewWeek() + { + } + + virtual void HandleOnNewDay() + { + } + + virtual void HandleOnNewHour() + { + } + + virtual void ReConfigure() + { + } + + /** + * Generate Identifier Tag ... + * + * @return ( virtual string ) + */ + virtual string GetTag() + { + // + string result = NULL; + + // + string tagPrefix = TagPrefix(); + if (IsValid(tagPrefix)) + { + result = tagPrefix; + } + else + { + result = ""; + } + + // + result = + XCBaseExpertToken + result; + + // + return result; + } + + // + protected: + // + + // + // Props ... + + // + XTimeTracker mTimeTracker; // Time Tracker for Providing Reports ... + + // + // Actions ... + + /** + * Report Account Balance ... + */ + void HandleReportBalance() + { + // + if (!IsRunningOnTestMode()) + { + return; + } + + // + string msg = "Balance: " + ToString(mTrader.mAccount.GetBalance()); + Log(msg); + } + + /** + * Time Reporting based on Inputs ... + */ + void HandleReportTime() + { + // + // Monthly Report .... + if (mTimeTracker.IsNewMonth()) + { + // + HandleOnNewMonth(); + + // + if (mReportNewMonths) + { + // + string msg = "New Month ..."; + + // + Alert(msg); + } + } + + // + // Weekly Report .... + if (mTimeTracker.IsNewWeek()) + { + // + HandleOnNewWeek(); + + // + if (mReportNewWeeks) + { + // + string msg = "New Week ..."; + + // + Alert(msg); + } + } + + // + // Daily Report .... + if (mTimeTracker.IsNewDay()) + { + // + HandleOnNewDay(); + + // + if (mReportNewDays) + { + // + string msg = "New Day ..."; + + // + Alert(msg); + } + } + + // + // Hourly Report .... + if (mTimeTracker.IsNewHour()) + { + // + HandleOnNewHour(); + + // + if (mReportNewHours) + { + // + string msg = "New Hour ..."; + + // + Alert(msg); + } + } + } + + // + private: + // + + // + // Props ... + + // + // Common ... + long mMagicNumber; // Magic Number ... + int mSlippage; // Slippage ... + string mTagPrefix; // Tag Prefix ... + + // + // Symbol ... + ENUM_TIMEFRAMES mPeriod; // Period ... + string mSymbol; // Symbol ... + bool mMultiSymbol; // Multi Symbol is Enable or Not ... + string mSymbols; // Multi Provided Symbols ... + + // + // Signalling ... + bool mDisabled; // Force Disable Signalling ... + bool mAllowLong; // Allow Long Signals ... + bool mAllowShort; // Allow Short Signals ... + + // + // Reports ... + bool mReportNewMonths; // Report New Month ... + bool mReportNewWeeks; // Report New Weeks ... + bool mReportNewDays; // Report New Days ... + bool mReportNewHours; // Report New Hours ... + + // +}; + +// \ No newline at end of file diff --git a/BKPS/14040203/Classes/x-saherelm.x-helper.class.mq5 b/BKPS/14040203/Classes/x-saherelm.x-helper.class.mq5 new file mode 100644 index 0000000..945ba69 --- /dev/null +++ b/BKPS/14040203/Classes/x-saherelm.x-helper.class.mq5 @@ -0,0 +1,151 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Class Library +// ---------------------------------------------- +// Name: XSCBaseHelper +// Description: provides all Base Indicator +// Helper requirements ... +// +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +////////////////////////////////////////////////////// +// +// Global Properties ... +#property library +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://www.saherelm.ir" +#property version "1.00" +#property strict + +// +// Includes ... +#include "../Classes/x-saherelm.base.class.mq5" + +// +// Definitions ... + +// +// a Class for Handle base requirements ... +// for indicators ... +class XCBaseHelper : public XCBase +{ + // + // Public ... + public: + // + // Constructor ... + void XCBaseHelper( + string symbol, // Trading Symbol + ENUM_TIMEFRAMES period // Trading Time Frame + ) + { + // + mSymbol = symbol; + mPeriod = period; + } + + // + // Deconstructor ... + void ~XCBaseHelper() + { + // + IndicatorRelease(mHandler); + } + + // + // Setter(s) / Getter(s) ... + + // + // Symbol ... + string GetSymbol() + { + return mSymbol; + } + + // + // Period ... + ENUM_TIMEFRAMES GetPeriod() + { + return mPeriod; + } + + // + // Retrieve Bars ... + int CountBars() + { + // + int result = + Bars( + mSymbol, + mPeriod + // + ); + + // + return result; + } + + // + // Retrieve Indicator Calculated Bars ... + int CountCalculatedBars() + { + return BarsCalculated(mHandler); + } + + // + virtual void Free() {} + + // + // Generate Tag ... + virtual string GetTag() + { + // + string result = NULL; + + // + result = + // + GetToken() + + "[" + + GetSymbol() + "|" + + ToString(GetPeriod()) + + "]" + // + ; + + // + return result; + } + + // + // Functions ... + + // + // Protected ... + protected: + // + // Props ... + + // + // Symbol ... + string mSymbol; + + // + // Period ... + ENUM_TIMEFRAMES mPeriod; + + // + // Indicator Handler ... + int mHandler; + + // + // Private ... + private: + // +}; + +// +// Tools .... \ No newline at end of file diff --git a/BKPS/14040203/Classes/x-saherelm.x-http.class.mq5 b/BKPS/14040203/Classes/x-saherelm.x-http.class.mq5 new file mode 100644 index 0000000..631532f --- /dev/null +++ b/BKPS/14040203/Classes/x-saherelm.x-http.class.mq5 @@ -0,0 +1,373 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Class Library +// ---------------------------------------------- +// Name: XSCHttp +// Description: provides all HTTP requirements ... +// +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +////////////////////////////////////////////////////// +// +// Global Properties ... +#property library +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://www.saherelm.ir" +#property version "1.00" +#property strict + +// +// Definitions ... + +// +enum X_HTTP_METHOD +{ + X_HTTP_GET, + X_HTTP_POST +}; + +// +// Imports ... + +// +// Includes ... +#include "../Classes/x-saherelm.base.class.mq5" +#include "../Libraries/x-saherelm.common.lib.mq5" + +// +// a Class for Manage Account ... +class XCHttp : public XCBase +{ + // + // Public ... + public: + // + // Constructor ... + void XCHttp() + { + XCHttp("", 10000); + } + void XCHttp( + string path, // Base Folder to Store Data + int timeout // base timeout for Requests + ) + { + // + Path(path); + Timeout(timeout); + } + + // + // Deconstructor ... + void ~XCHttp() + { + } + + // + // Properties Getter(s) / Setter(s) ... + + // + // Path ... + void Path(string value) + { + // + mPath = value; + + // + if (!IsValid(mPath)) + { + mPath = GetTag(); + } + } + + string Path() + { + return mPath; + } + + // + // Timeout ... + void Timeout(int value) + { + mTimeout = value; + } + + // + int Timeout() + { + return mTimeout; + } + + // + // Error ... + int Error() + { + return mError; + } + + // + // Response ... + string Response() + { + return mResponse; + } + + // + // Overrides ... + string GetTag() override + { + return GetSpecificToken(this); + } + + // + // Tools ... + + // + // Send Global Request ... + int SendRequest( + X_HTTP_METHOD method, // Httm Request Method + const string url, // Server Address + const string headers, // Headers providing + const char &payload[], // the Data which needs to Send + char &response[], // Response of request + string responseHeaders, // Response Headers + int timeout = 500 // Timeout for response default is 500 + ) + { + // + int result = -1; + + // + string strMethod = ToString(method); + if (StringLen(strMethod) == 0) + { + return result; + } + + // + // Reset State ... + ResetState(); + + // + result = WebRequest( + strMethod, + url, + headers, + timeout, + payload, + response, + responseHeaders); + + // + if (result < 0) + { + mError = GetLastError(); + } + else + { + mResponse = CharArrayToString(response); + } + + // + return result; + } + + // + // Get Request ... + int GetRequest( + const string url, // Server Address + const string headers, // Headers providing + const char &payload[], // the Data which needs to Send + char &response[], // Response of request + string responseHeaders, // Response Headers + int timeout = 500 // Timeout for response default is 500 + ) + { + // + int result = SendRequest( + X_HTTP_GET, + url, + headers, + payload, + response, + responseHeaders, + timeout); + + // + return result; + } + + // + // Post Request ... + int PostRequest( + const string url, // Server Address + const string headers, // Headers providing + const char &payload[], // the Data which needs to Send + char &response[], // Response of request + string responseHeaders, // Response Headers + int timeout = 500 // Timeout for response default is 500 + ) + { + // + int result = SendRequest( + X_HTTP_POST, + url, + headers, + payload, + response, + responseHeaders, + timeout); + + // + return result; + } + + // + // Handle Download Specific URL Content to Specific Path and File Name ... + bool Download( + string url, // the URL address which going to download + string fileName // Specify Destination file name to Store Response + ) + { + // + bool result = false; + + // + string filePath = GetFilePath(fileName); + string cookie = NULL; + string referer = NULL; + int timeout = Timeout(); + + // + char payload[]; + string headers; + char response[]; + string responseHeaders; + + // + // Send Request ... + int requestResult = GetRequest( + url, + headers, + payload, + response, + responseHeaders, + timeout); + + // + // Define File Handler ... + int mFileHandler = FileOpen( + filePath, + FILE_WRITE | FILE_BIN); + if (mFileHandler == INVALID_HANDLE) + { + // + mError = GetLastError(); + return result; + } + + // + // Write Response to File ... + uint writed = FileWriteArray( + mFileHandler, + response, + 0, + ArraySize(response)); + FileFlush(mFileHandler); + FileClose(mFileHandler); + + // + result = writed > 0; + + // + return result; + } + + // + // END Provided Functions ... + // + + // + // Protected ... + protected: + // + // Destintion Folder Path ... + string mPath; + + // + // WEB Request Timeout Value ... + int mTimeout; + + // + // WEB Request's Response ... + string mResponse; + + // + // Error Value ... + int mError; + + // + // Private ... + private: + // + // Reset Errors State ... + void ResetState() + { + // + // Reset Errors ... + mError = -1; + mResponse = ""; + ResetLastError(); + } + + // + // Generate Full File Path ... + string GetFilePath(string fileName) + { + // + string result = ""; + + // + result = + // + Path() + "\\" + fileName + // + ; + + // + return result; + } +}; + +// +// Tools ... + +// +// Convert enum to String ... +string ToString(X_HTTP_METHOD method) +{ + // + string result = ""; + + // + switch (method) + { + // + case X_HTTP_GET: + result = "GET"; + break; + + // + case X_HTTP_POST: + result = "POST"; + break; + } + + // + return result; +} + +// \ No newline at end of file diff --git a/BKPS/14040203/Classes/x-saherelm.x-md5.class.mq5 b/BKPS/14040203/Classes/x-saherelm.x-md5.class.mq5 new file mode 100644 index 0000000..e5cc201 --- /dev/null +++ b/BKPS/14040203/Classes/x-saherelm.x-md5.class.mq5 @@ -0,0 +1,445 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Class Library +// ---------------------------------------------- +// Name: XSCMD5 +// Description: Provides MD5 Hashing Requirements ... +// +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +////////////////////////////////////////////////////// +// +// Global Properties ... +#property library +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://www.saherelm.ir" +#property version "1.00" +#property strict + +// +// START Definitions ... +// + +// +static uchar _md5_PADDING[64] = + { + 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; + +// +#define _md5_F(x, y, z) (((x) & (y)) | ((~x) & (z))) +#define _md5_G(x, y, z) (((x) & (z)) | ((y) & (~z))) +#define _md5_H(x, y, z) ((x) ^ (y) ^ (z)) +#define _md5_I(x, y, z) ((y) ^ ((x) | (~z))) +#define _md5_ROTATE_LEFT(x, n) (((x) << (n)) | ((x) >> (32 - (n)))) + +// +#define _md5_FF(a, b, c, d, x, s, ac) \ + { \ + (a) += _md5_F((b), (c), (d)) + (x) + (uint)(ac); \ + (a) = _md5_ROTATE_LEFT((a), (s)); \ + (a) += (b); \ + } + +// +#define _md5_GG(a, b, c, d, x, s, ac) \ + { \ + (a) += _md5_G((b), (c), (d)) + (x) + (uint)(ac); \ + (a) = _md5_ROTATE_LEFT((a), (s)); \ + (a) += (b); \ + } + +// +#define _md5_HH(a, b, c, d, x, s, ac) \ + { \ + (a) += _md5_H((b), (c), (d)) + (x) + (uint)(ac); \ + (a) = _md5_ROTATE_LEFT((a), (s)); \ + (a) += (b); \ + } + +// +#define _md5_II(a, b, c, d, x, s, ac) \ + { \ + (a) += _md5_I((b), (c), (d)) + (x) + (uint)(ac); \ + (a) = _md5_ROTATE_LEFT((a), (s)); \ + (a) += (b); \ + } + +// +#define _md5_INIT_STATE_0 0x67452301 +#define _md5_INIT_STATE_1 0xefcdab89 +#define _md5_INIT_STATE_2 0x98badcfe +#define _md5_INIT_STATE_3 0x10325476 + +// +#define _md5_S11 7 +#define _md5_S12 12 +#define _md5_S13 17 +#define _md5_S14 22 + +// +#define _md5_S21 5 +#define _md5_S22 9 +#define _md5_S23 14 +#define _md5_S24 20 + +// +#define _md5_S31 4 +#define _md5_S32 11 +#define _md5_S33 16 +#define _md5_S34 23 + +// +#define _md5_S41 6 +#define _md5_S42 10 +#define _md5_S43 15 +#define _md5_S44 21 + +// +// END Definitions ... +// + +// +// XCMD5 a library for Hashing ... +class XCMD5 +{ + // + // Public Provides ... + public: + // + // Protected Provides ... + + // + // Constructor ... + XCMD5(void) + { + } + + // + // Deconstructor ... + ~XCMD5(void) + { + } + + // + // Hash Specified Char Array ... + string Hash( + uchar &mSource[], // Specify Char Array to Hash + int mLength = 0 // Specify Length of Char Array which required to hash + ) + { + // + string result = ""; + + // + int sourceCount = ArraySize(mSource); + + // + // Validate Args ... + if ( + sourceCount <= 0 || + (sourceCount > 0 && mLength > sourceCount)) + { + return result; + } + + // + // Normalize Args ... + if (mLength == 0) + { + mLength = sourceCount; + } + + // + // Init MD5 ... + MD5Init(); + + // + // Update Buffer ... + MD5Update(mSource, mLength); + + // + // Calculate Result ... + result = MD5Final(); + + // + return result; + } + + // + // Hash Specified String ... + string Hash( + string mSource // Specified String + ) + { + // + string result = ""; + + // + // Converts String to Char Array ... + uchar bytes[]; + StringToCharArray( + mSource, + bytes, + 0, + StringLen(mSource)); + + // + result = Hash( + bytes, + ArraySize(bytes)); + + // + return result; + } + + protected: + // + // Private Provides ... + private: + // + uint m_lMD5[4]; + uint m_nCount[2]; + uchar m_lpszBuffer[64]; + + // + // Convert Byte to DWord ... + void ByteToDWord(int &out[], uint &in[], uint len) + { + // + uint i = 0; + uint j = 0; + + // + for (; j < len; i++, j += 4) + { + out[i] = (int)in[j] | (int)in[j + 1] << 8 | (int)in[j + 2] << 16 | (int)in[j + 3] << 24; + } + } + + // + // Convert DWord to Byte ... + void DWordToByte(uchar &out[], int &in[], uint len) + { + // + uint i = 0; + uint j = 0; + + // + for (; j < len; i++, j += 4) + { + // + out[j] = (uchar)(in[i] & 0xff); + out[j + 1] = (uchar)((in[i] >> 8) & 0xff); + out[j + 2] = (uchar)((in[i] >> 16) & 0xff); + out[j + 3] = (uchar)((in[i] >> 24) & 0xff); + } + } + + // + // Init MD5 Array ... + void MD5Init() + { + // + ArrayInitialize(m_lpszBuffer, 64); + + // + m_nCount[0] = m_nCount[1] = 0; + m_lMD5[0] = _md5_INIT_STATE_0; + m_lMD5[1] = _md5_INIT_STATE_1; + m_lMD5[2] = _md5_INIT_STATE_2; + m_lMD5[3] = _md5_INIT_STATE_3; + } + + // + // Update MD5 ... + void MD5Update(uchar &inBuf[], uint inLen) + { + // + int i, ii; + int mdi; + + // + uint in[16]; + int i0 = 0; + + // + mdi = (int)((m_nCount[0] >> 3) & 0x3F); + + // + if ((m_nCount[0] + ((uint)inLen << 3)) < m_nCount[0]) + { + m_nCount[1]++; + } + + // + m_nCount[0] += ((uint)inLen << 3); + m_nCount[1] += ((uint)inLen >> 29); + + // + while ((inLen--) > 0) + { + // + m_lpszBuffer[mdi++] = inBuf[i0++]; + if (mdi == 0x40) + { + // + for (i = 0, ii = 0; i < 16; i++, ii += 4) + { + in[i] = (((uint)m_lpszBuffer[ii + 3]) << 24) | (((uint)m_lpszBuffer[ii + 2]) << 16) | (((uint)m_lpszBuffer[ii + 1]) << 8) | ((uint)m_lpszBuffer[ii]); + } + + // + Transform(m_lMD5, in); + + // + mdi = 0; + } + } + } + + // + // Finalize an MD5 Expression ... + string MD5Final() + { + // + uchar bits[8]; + int nIndex; + uint nPadLen; + const int nMD5Size = 16; + uchar lpszMD5[16]; + string temp; + string out = ""; + int i; + + // + DWordToByte(bits, m_nCount, 8); + nIndex = (int)((m_nCount[0] >> 3) & 0x3f); + nPadLen = (nIndex < 56) ? (56 - nIndex) : (120 - nIndex); + MD5Update(_md5_PADDING, nPadLen); + MD5Update(bits, 8); + DWordToByte(lpszMD5, m_lMD5, nMD5Size); + + // + for (i = 0; i < nMD5Size; i++) + { + // + if (lpszMD5[i] == 0) + { + temp = "00"; + } + else if (lpszMD5[i] <= 15) + { + temp = StringFormat("0%x", lpszMD5[i]); + } + else + { + temp = StringFormat("%x", lpszMD5[i]); + } + + // + out += temp; + } + + // + lpszMD5[0] = '\0'; + + // + return (out); + } + + // + // Transform Buffers ... + void Transform(uint &buf[], uint &in[]) + { + // + uint a = buf[0], b = buf[1], c = buf[2], d = buf[3]; + + // + _md5_FF(a, b, c, d, in[0], _md5_S11, 0xD76AA478); + _md5_FF(d, a, b, c, in[1], _md5_S12, 0xE8C7B756); + _md5_FF(c, d, a, b, in[2], _md5_S13, 0x242070DB); + _md5_FF(b, c, d, a, in[3], _md5_S14, 0xC1BDCEEE); + _md5_FF(a, b, c, d, in[4], _md5_S11, 0xF57C0FAF); + _md5_FF(d, a, b, c, in[5], _md5_S12, 0x4787C62A); + _md5_FF(c, d, a, b, in[6], _md5_S13, 0xA8304613); + _md5_FF(b, c, d, a, in[7], _md5_S14, 0xFD469501); + _md5_FF(a, b, c, d, in[8], _md5_S11, 0x698098D8); + _md5_FF(d, a, b, c, in[9], _md5_S12, 0x8B44F7AF); + _md5_FF(c, d, a, b, in[10], _md5_S13, 0xFFFF5BB1); + _md5_FF(b, c, d, a, in[11], _md5_S14, 0x895CD7BE); + _md5_FF(a, b, c, d, in[12], _md5_S11, 0x6B901122); + _md5_FF(d, a, b, c, in[13], _md5_S12, 0xFD987193); + _md5_FF(c, d, a, b, in[14], _md5_S13, 0xA679438E); + _md5_FF(b, c, d, a, in[15], _md5_S14, 0x49B40821); + + // + _md5_GG(a, b, c, d, in[1], _md5_S21, 0xF61E2562); + _md5_GG(d, a, b, c, in[6], _md5_S22, 0xC040B340); + _md5_GG(c, d, a, b, in[11], _md5_S23, 0x265E5A51); + _md5_GG(b, c, d, a, in[0], _md5_S24, 0xE9B6C7AA); + _md5_GG(a, b, c, d, in[5], _md5_S21, 0xD62F105D); + _md5_GG(d, a, b, c, in[10], _md5_S22, 0x02441453); + _md5_GG(c, d, a, b, in[15], _md5_S23, 0xD8A1E681); + _md5_GG(b, c, d, a, in[4], _md5_S24, 0xE7D3FBC8); + _md5_GG(a, b, c, d, in[9], _md5_S21, 0x21E1CDE6); + _md5_GG(d, a, b, c, in[14], _md5_S22, 0xC33707D6); + _md5_GG(c, d, a, b, in[3], _md5_S23, 0xF4D50D87); + _md5_GG(b, c, d, a, in[8], _md5_S24, 0x455A14ED); + _md5_GG(a, b, c, d, in[13], _md5_S21, 0xA9E3E905); + _md5_GG(d, a, b, c, in[2], _md5_S22, 0xFCEFA3F8); + _md5_GG(c, d, a, b, in[7], _md5_S23, 0x676F02D9); + _md5_GG(b, c, d, a, in[12], _md5_S24, 0x8D2A4C8A); + + // + _md5_HH(a, b, c, d, in[5], _md5_S31, 0xFFFA3942); + _md5_HH(d, a, b, c, in[8], _md5_S32, 0x8771F681); + _md5_HH(c, d, a, b, in[11], _md5_S33, 0x6D9D6122); + _md5_HH(b, c, d, a, in[14], _md5_S34, 0xFDE5380C); + _md5_HH(a, b, c, d, in[1], _md5_S31, 0xA4BEEA44); + _md5_HH(d, a, b, c, in[4], _md5_S32, 0x4BDECFA9); + _md5_HH(c, d, a, b, in[7], _md5_S33, 0xF6BB4B60); + _md5_HH(b, c, d, a, in[10], _md5_S34, 0xBEBFBC70); + _md5_HH(a, b, c, d, in[13], _md5_S31, 0x289B7EC6); + _md5_HH(d, a, b, c, in[0], _md5_S32, 0xEAA127FA); + _md5_HH(c, d, a, b, in[3], _md5_S33, 0xD4EF3085); + _md5_HH(b, c, d, a, in[6], _md5_S34, 0x04881D05); + _md5_HH(a, b, c, d, in[9], _md5_S31, 0xD9D4D039); + _md5_HH(d, a, b, c, in[12], _md5_S32, 0xE6DB99E5); + _md5_HH(c, d, a, b, in[15], _md5_S33, 0x1FA27CF8); + _md5_HH(b, c, d, a, in[2], _md5_S34, 0xC4AC5665); + + // + _md5_II(a, b, c, d, in[0], _md5_S41, 0xF4292244); + _md5_II(d, a, b, c, in[7], _md5_S42, 0x432AFF97); + _md5_II(c, d, a, b, in[14], _md5_S43, 0xAB9423A7); + _md5_II(b, c, d, a, in[5], _md5_S44, 0xFC93A039); + _md5_II(a, b, c, d, in[12], _md5_S41, 0x655B59C3); + _md5_II(d, a, b, c, in[3], _md5_S42, 0x8F0CCC92); + _md5_II(c, d, a, b, in[10], _md5_S43, 0xFFEFF47D); + _md5_II(b, c, d, a, in[1], _md5_S44, 0x85845DD1); + _md5_II(a, b, c, d, in[8], _md5_S41, 0x6FA87E4F); + _md5_II(d, a, b, c, in[15], _md5_S42, 0xFE2CE6E0); + _md5_II(c, d, a, b, in[6], _md5_S43, 0xA3014314); + _md5_II(b, c, d, a, in[13], _md5_S44, 0x4E0811A1); + _md5_II(a, b, c, d, in[4], _md5_S41, 0xF7537E82); + _md5_II(d, a, b, c, in[11], _md5_S42, 0xBD3AF235); + _md5_II(c, d, a, b, in[2], _md5_S43, 0x2AD7D2BB); + _md5_II(b, c, d, a, in[9], _md5_S44, 0xEB86D391); + + // + buf[0] += a; + buf[1] += b; + buf[2] += c; + buf[3] += d; + } +}; diff --git a/BKPS/14040203/Classes/x-saherelm.x-poi.class.mq5 b/BKPS/14040203/Classes/x-saherelm.x-poi.class.mq5 new file mode 100644 index 0000000..d3338fa --- /dev/null +++ b/BKPS/14040203/Classes/x-saherelm.x-poi.class.mq5 @@ -0,0 +1,3513 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Class Library +// -------------------------------------- +// Name: XPOI +// Description: Provides Point of Interests ... +// - Swing Highs; +// - Swing Lows; +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +////////////////////////////////////////////////////// +// +// Global Properties ... +#property library +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://www.saherelm.ir" +#property version "1.00" +#property strict + +// +// Imports ... + +// +#include "../Classes/x-saherelm.x-alert.class.mq5" +#include "../Classes/x-saherelm.x-bar.analyser.class.mq5" +#include "../Libraries/x-saherelm.x-poi.state.lib.mq5" + +// +// Implementation ... + +// +// POI Detector Class ... +class XCPOIDetector : public XCBaseAlert +{ + // + public: + // + + // + // Constructors ... + /** + * Create an Instance ... + * + * @param symbol: String ... + * @param period: ENUM_TIMEFRAMES member ... + */ + void XCPOIDetector( + string symbol, + ENUM_TIMEFRAMES period) + { + // + // Attach Required Properties ... + mSymbol = symbol; + mPeriod = period; + + // + // Initialize Bar Tracker ... + mBarTracker.Init( + mSymbol, + mPeriod // + ); + + // + mBarAnalyser = new XCBarAnalyser(); + + // + // Apply Default Configurations ... + Default(); + } + + // + // Deconstructor ... + void ~XCPOIDetector() + { + Destroy(); + } + + // + // Getter(s) / Setter(s) ... + + /** + * Retrieve Detector Symbol ... + * + * @return ( string ) + */ + string GetSymbol() + { + return mSymbol; + } + + /** + * Retrieve Detector Period ... + * + * @return ( ENUM_TIMEFRAMES ) + */ + ENUM_TIMEFRAMES GetPeriod() + { + return mPeriod; + } + + /** + * Get Max Required POI(s) allowed to Holds ... + * + * @return ( int ) + */ + int MaxRequiredPOIs() + { + return mMaxRequiredPOIs; + } + + /** + * Set Max Required POI(s) allowed to Holds ... + * + * @param value: int ... + */ + void MaxRequiredPOIs(int value) + { + // + if (value < 0) + { + value = 5; + } + + // + mMaxRequiredPOIs = value; + } + + /** + * Get Max Allowed Loopback for POI(s) Detection on Initialization Process ... + * + * @return ( int ) + */ + int MaxAllowedLoopbackForInit() + { + return maxAllowedLoopbackForInit; + } + + /** + * Set Max Allowed Loopback for POI(s) Detection on Initialization Process ... + * + * @param value: int ... + */ + void MaxAllowedLoopbackForInit(int value) + { + // + if (value < 0) + { + value = 578; + } + + // + maxAllowedLoopbackForInit = value; + } + + // + // + // + + /** + * Get Swing Range Validation ... + * + * @return ( int ) + */ + int SwingRange() + { + return mSwingRange; + } + + /** + * Set Swing Range Validation ... + * + * @param value: int ... + */ + void SwingRange(int value) + { + // + value = NormalizeInt(value, 1); + + // + mSwingRange = value; + } + + /** + * Get Pullback Range Validation ... + * + * @return ( int ) + */ + int PullbackRange() + { + return mPullbackRange; + } + + /** + * Set Pullback Range Validation ... + * + * @param value: int ... + */ + void PullbackRange(int value) + { + // + value = NormalizeInt(value, 1); + + // + mPullbackRange = value; + } + + /** + * Get Momentum Detecting Loopback ... + * + * @return ( int ) + */ + int MomentumLoopback() + { + return mMomentumLoopback; + } + + /** + * Set Momentum Detecting Loopback ... + * + * @param value: int ... + */ + void MomentumLoopback(int value) + { + // + value = NormalizeInt(value, 1); + + // + mMomentumLoopback = value; + } + + /** + * Get Rejection Detecting Force Bar Type State ... + * + * @return ( bool ) + */ + bool RejectionForceBarType() + { + return mRejectionForceBarType; + } + + /** + * Set Rejection Detecting Force Bar Type State ... + * + * @param value: bool ... + */ + void RejectionForceBarType(bool value) + { + mRejectionForceBarType = value; + } + + /** + * Get Rejection Detecting Force Fibo Pressure State ... + * + * @return ( bool ) + */ + bool RejectionForceFiboPressure() + { + return mRejectionForceFiboPressure; + } + + /** + * Set Rejection Detecting Force Fibo Pressure State ... + * + * @param value: bool ... + */ + void RejectionForceFiboPressure(bool value) + { + mRejectionForceFiboPressure = value; + } + + /** + * Get Minimum Length of Cnsolidation Zone ... + * + * @return ( int ) + */ + int ConsolidationZoneMinLoopback() + { + return mConsolidationZoneMinLoopback; + } + + /** + * Set Minimum Length of Cnsolidation Zone ... + * + * @param value: int ... + */ + void ConsolidationZoneMinLoopback(int value) + { + // + value = NormalizeInt(value, 1); + + // + mConsolidationZoneMinLoopback = value; + } + + /** + * Get Consolidation Zone Range in Point ... + * + * @return ( double ) + */ + double ConsolidationZoneRangeInPoint() + { + return mConsolidationZoneRangeInPoint; + } + + /** + * Set Consolidation Zone Range in Point ... + * + * @param value: double ... + */ + void ConsolidationZoneRangeInPoint(double value) + { + // + value = NormalizeDouble(value, 0); + + // + mConsolidationZoneRangeInPoint = value; + } + + /** + * Get Consolidation Zone Lower Applied To ... + * + * @return ( ENUM_X_PRICE ) + */ + ENUM_X_PRICE ConsolidationZonesLowerAppliedTo() + { + return mConsolidationZonesLowerAppliedTo; + } + + /** + * Get Consolidation Zone Lower Applied To ... + * + * @param value: ENUM_X_PRICE member ... + */ + void ConsolidationZonesLowerAppliedTo(ENUM_X_PRICE value) + { + mConsolidationZonesLowerAppliedTo = value; + } + + /** + * Get Consolidation Zone Upper Applied To ... + * + * @return ( ENUM_X_PRICE ) + */ + ENUM_X_PRICE ConsolidationZonesUpperAppliedTo() + { + return mConsolidationZonesUpperAppliedTo; + } + + /** + * Get Consolidation Zone Upper Applied To ... + * + * @param value: ENUM_X_PRICE member ... + */ + void ConsolidationZonesUpperAppliedTo(ENUM_X_PRICE value) + { + mConsolidationZonesUpperAppliedTo = value; + } + + /** + * Get Spike Detection Price Type ... + * + * @return ( ENUM_X_PRICE ) + */ + ENUM_X_PRICE SpikePriceType() + { + return mSpikePriceType; + } + + /** + * Set Spike Detection Price Type ... + * + * @param value: ENUM_X_PRICE member ... + */ + void SpikePriceType(ENUM_X_PRICE value) + { + mSpikePriceType = value; + } + + /** + * Get Spike Detection Force Body In Range State ... + * + * @return ( bool ) + */ + bool SpikeForcBodyInRange() + { + return mSpikeForcBodyInRange; + } + + /** + * Set Spike Detection Force Body In Range State ... + * + * @param value: bool ... + */ + void SpikeForcBodyInRange(bool value) + { + mSpikeForcBodyInRange = value; + } + + /** + * Get Spike Detection Range Extends Multiplier ... + * + * @return ( double ) + */ + double SpikeRangeExtendMultiplier() + { + return mSpikeRangeExtendMultiplier; + } + + /** + * Set Spike Detection Range Extends Multiplier ... + * + * @param value: double ... + */ + void SpikeRangeExtendMultiplier(double value) + { + // + value = NormalizeDouble(value, 1); + + // + mSpikeRangeExtendMultiplier = value; + } + + /** + * Get Spike Detection Same Bars ... + * + * @return ( int ) + */ + int SpikeSameBars() + { + return mSpikeSameBars; + } + + /** + * Set Spike Detection Same Bars ... + * + * @param value: int ... + */ + void SpikeSameBars(int value) + { + // + value = NormalizeInt(value, 1); + + // + mSpikeSameBars = value; + } + + /** + * Get Support and Resistance Detection Range ... + * + * @return ( int ) + */ + int SupResRange() + { + return mSupResRange; + } + + /** + * Set Support and Resistance Detection Range ... + * + * @param value: int ... + */ + void SupResRange(int value) + { + // + value = NormalizeInt(value, 5); + + // + mSupResRange = value; + } + + /** + * Get use Support and Resistance Range as Start ... + * + * @return ( bool ) + */ + bool SupResRangeAsStart() + { + return mSupResRangeAsStart; + } + + /** + * Set use Support and Resistance Range as Start ... + * + * @param value: bool ... + */ + void SupResRangeAsStart(bool value) + { + mSupResRangeAsStart = value; + } + + /** + * Get Force Activations in Supply/Demand and Support/Resistance Detections State ... + * + * @return ( bool ) + */ + bool SupResForceActivation() + { + return mSupResForceActivation; + } + + /** + * Set Force Activations in Supply/Demand and Support/Resistance Detections State ... + * + * @param value: bool ... + */ + void SupResForceActivation(bool value) + { + mSupResForceActivation = value; + } + + /** + * Get FairValueGap Detection Same Bars ... + * + * @return ( int ) + */ + int FairValueGapSameBars() + { + return mFairValueGapSameBars; + } + + /** + * Set FairValueGap Detection Same Bars ... + * + * @param value: int ... + */ + void FairValueGapSameBars(int value) + { + // + value = NormalizeInt(value, 2); + + // + mFairValueGapSameBars = value; + } + + /** + * Get FairValueGap Detection Force Check Activation State ... + * + * @return ( bool ) + */ + bool FairValueGapForceActivation() + { + return mFairValueGapForceActivation; + } + + /** + * Set FairValueGap Detection Force Check Activation State ... + * + * @param value: bool ... + */ + void FairValueGapForceActivation(bool value) + { + mFairValueGapForceActivation = value; + } + + /** + * Get OrderBlock Detection Same Bars ... + * + * @return ( int ) + */ + int OrderBlockSameBars() + { + return mOrderBlockSameBars; + } + + /** + * Set OrderBlock Detection Same Bars ... + * + * @param value: int ... + */ + void OrderBlockSameBars(int value) + { + // + value = NormalizeInt(value, 1); + + // + mOrderBlockSameBars = value; + } + + /** + * Get Order Blocs Detection Force Spike State ... + * + * @return ( bool ) + */ + bool OrderBlockForceSpike() + { + return mOrderBlockForceSpike; + } + + /** + * Set Order Blocs Detection Force Spike State ... + * + * @param value: bool ... + */ + void OrderBlockForceSpike(bool value) + { + mOrderBlockForceSpike = value; + } + + /** + * Get Order Blocs Detection Force Fair Value Gaps State ... + * + * @return ( bool ) + */ + bool OrderBlockForceFairValueGap() + { + return mOrderBlockForceFairValueGap; + } + + /** + * Set Order Blocs Detection Force Fair Value Gaps State ... + * + * @param value: bool ... + */ + void OrderBlockForceFairValueGap(bool value) + { + mOrderBlockForceFairValueGap = value; + } + + /** + * Get Order Blocs Detection Force Support/Resisatnce ... + * + * @return ( bool ) + */ + bool OrderBlockForceSupportResistance() + { + return mOrderBlockForceSupportResistance; + } + + /** + * Set Order Blocs Detection Force Support/Resisatnce ... + * + * @param value: bool ... + */ + void OrderBlockForceSupportResistance(bool value) + { + mOrderBlockForceSupportResistance = value; + } + + /** + * Get OrderBlock Detection Force Check Activation State ... + * + * @return ( bool ) + */ + bool OrderBlockForceActivation() + { + return mOrderBlockForceActivation; + } + + /** + * Set OrderBlock Detection Force Check Activation State ... + * + * @param value: bool ... + */ + void OrderBlockForceActivation(bool value) + { + mOrderBlockForceActivation = value; + } + + // + // + // + // + // + // + + // + // Actions ... + + /** + * Apply Default Configurations ... + */ + virtual void Default() + { + // + // Default Props ... + MaxRequiredPOIs(100); + MaxAllowedLoopbackForInit(578); + + // + SwingRange(7); + MomentumLoopback(2); + + // + PullbackRange(3); + + // + MomentumLoopback(2); + + // + RejectionForceBarType(true); + RejectionForceFiboPressure(true); + + // + ConsolidationZoneMinLoopback(7); + ConsolidationZoneRangeInPoint(50); + ConsolidationZonesLowerAppliedTo(X_PRICE_LOW); + ConsolidationZonesUpperAppliedTo(X_PRICE_HIGH); + + // + SpikePriceType(X_PRICE_CLOSE); + SpikeForcBodyInRange(true); + SpikeRangeExtendMultiplier(2.0); + SpikeSameBars(3); + + // + SupResRange(21); + SupResRangeAsStart(true); + SupResForceActivation(true); + + // + FairValueGapSameBars(3); + + // + OrderBlockSameBars(3); + OrderBlockForceSpike(true); + OrderBlockForceFairValueGap(true); + OrderBlockForceSupportResistance(false); + } + + /** + * Add Event Listener ... + * + * @param listener: TOnPOIEvent instance ... + */ + void AddEventListener(TOnPOIEvent listener) + { + // + Add( + listener, + mEventListeners // + ); + } + + /** + * Initialize Instance ... + */ + void Init( + int barIndex = 0, + bool ignoreMaxAllowed = true // + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + if (maxAllowedLoopbackForInit <= 0) + { + return; + } + + // + mLock = true; + bool canContinue = true; + int index = barIndex + maxAllowedLoopbackForInit; + if (!IsValidIndex(index)) + { + // + mLock = false; + return; + } + + // + while (canContinue) + { + // + XOHCL iBar; + bool has = iBar.Init( + mSymbol, + mPeriod, + index // + ); + index--; + + // + int count = 0; + ENUM_XPOI_EVENTS iEvent = X_POI_EVENT_NONE; + + // + // Swings ... + DetectSwing( + iBar, + iEvent // + ); + + // + // Momentum ... + DetectMomentum( + iBar, + iEvent // + ); + + // + // Rejection ... + DetectRejection( + iBar, + iEvent // + ); + + // + // Pullback ... + DetetctPullback( + iBar, + iEvent // + ); + + // + // Consolidation Zone ... + DetectConsolidationZone( + iBar, + iEvent // + ); + + // + // Spike ... + DetectSharp( + iBar, + iEvent // + ); + + // + // Spike ... + DetectSpike( + iBar, + iEvent // + ); + + // + // Support ... + DetectSupportZone( + iBar, + iEvent // + ); + + // + // Resistance ... + DetectResistanceZone( + iBar, + iEvent // + ); + + // + // Supply ... + DetectSupplyZone( + iBar, + iEvent // + ); + + // + // Demand ... + DetectDemandZone( + iBar, + iEvent // + ); + + // + // FairValueGap ... + DetectFairValueGap( + iBar, + iEvent // + ); + + // + // OrderBlock ... + DetectOrderBlock( + iBar, + iEvent // + ); + + // + canContinue = + has && + index >= 0; + + // + iBar.Clean(); + } + + // + ReverseCollections(); + + // + mLock = false; + } + + /** + * Update POI(s) ... + * @param events: ENUM_XPOI_EVENTS member Collection ... + */ + void Update( + ENUM_XPOI_EVENTS &events[], + int barIndex = 0 // + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Clean(events); + + // + if (mLock) + { + return; + } + + // + // Check Bar Tracker if Waits ... + if (!mBarTracker.IsNewBar()) + { + return; + } + + // + mLock = true; + + // + XOHCL iBar; + bool has = iBar.Init( + mSymbol, + mPeriod, + barIndex // + ); + + // + if (!has) + { + // + iBar.Clean(); + + // + return; + } + + // + int count = 0; + ENUM_XPOI_EVENTS iEvent = X_POI_EVENT_NONE; + + // + // Swings ... + has = DetectSwing( + iBar, + iEvent // + ); + if (has) + { + // + Add( + iEvent, + events // + ); + } + + // + // Momentum ... + has = DetectMomentum( + iBar, + iEvent // + ); + if (has) + { + // + Add( + iEvent, + events // + ); + } + + // + // Rejection ... + has = DetectRejection( + iBar, + iEvent // + ); + if (has) + { + // + Add( + iEvent, + events // + ); + } + + // + // Pullback ... + has = DetetctPullback( + iBar, + iEvent // + ); + if (has) + { + // + Add( + iEvent, + events // + ); + } + + // + // Consolidation Zone ... + has = DetectConsolidationZone( + iBar, + iEvent // + ); + if (has) + { + // + Add( + iEvent, + events // + ); + } + + // + // Sharp ... + has = DetectSharp( + iBar, + iEvent // + ); + if (has) + { + // + Add( + iEvent, + events // + ); + } + + // + // Spike ... + has = DetectSpike( + iBar, + iEvent // + ); + if (has) + { + // + Add( + iEvent, + events // + ); + } + + // + // Support ... + has = DetectSupportZone( + iBar, + iEvent // + ); + if (has) + { + // + Add( + iEvent, + events // + ); + } + + // + // Resistance ... + has = DetectResistanceZone( + iBar, + iEvent // + ); + if (has) + { + // + Add( + iEvent, + events // + ); + } + + // + // Supply ... + has = DetectSupplyZone( + iBar, + iEvent // + ); + if (has) + { + // + Add( + iEvent, + events // + ); + } + + // + // Demand ... + has = DetectDemandZone( + iBar, + iEvent // + ); + if (has) + { + // + Add( + iEvent, + events // + ); + } + + // + // FairValueGap ... + has = DetectFairValueGap( + iBar, + iEvent // + ); + if (has) + { + // + Add( + iEvent, + events // + ); + } + + // + // OrderBlock ... + has = DetectOrderBlock( + iBar, + iEvent // + ); + if (has) + { + // + Add( + iEvent, + events // + ); + } + + // + iBar.Clean(); + mLock = false; + + // + if (HasChild(events)) + { + CleanupUnusedCollections(); + } + } + + /** + * Get Current State of POIs ... + * + * @param state: XPOIState instance ... + */ + void GetState( + XPOIState &state // + ) + { + // + state.Clean(); + + // + state.symbol = mSymbol; + state.period = mPeriod; + state.time = TimeCurrent(); + + // + // Swings ... + + // + Copy( + mSwings, + state.swings // + ); + + // + Copy( + mSwingLows, + state.swingLows // + ); + + // + Copy( + mSwingHighs, + state.swingHighs // + ); + + // + // Pullbacks ... + + // + Copy( + mPullbacks, + state.pullbacks // + ); + + // + Copy( + mBullishPullbacks, + state.bullishPullbacks // + ); + + // + Copy( + mBearishPullbacks, + state.bearishPullbacks // + ); + + // + // Momentums ... + + // + Copy( + mMomentums, + state.momentums // + ); + + // + Copy( + mBullishMomentums, + state.bullishMomentums // + ); + + // + Copy( + mBearishMomentums, + state.bearishMomentums // + ); + + // + // Rejections ... + + // + Copy( + mRejections, + state.rejections // + ); + + // + Copy( + mBullishRejections, + state.bullishRejections // + ); + + // + Copy( + mBearishRejections, + state.bearishRejections // + ); + + // + // Support and Resistances ... + + // + Copy( + mSupportZones, + state.supportZones // + ); + + // + Copy( + mResistanceZones, + state.resistanceZones // + ); + + // + // Supply and Demand ... + + // + Copy( + mSupplyZones, + state.supplyZones // + ); + + // + Copy( + mDemandZones, + state.demandZones // + ); + + // + // Spikes ... + + // + Copy( + mSpikes, + state.spikes // + ); + + // + Copy( + mBullishSpikes, + state.bullishSpikes // + ); + + // + Copy( + mBearishSpikes, + state.bearishSpikes // + ); + + // + // Sharps ... + + // + Copy( + mSharps, + state.sharps // + ); + + // + Copy( + mBullishSharps, + state.bullishSharps // + ); + + // + Copy( + mBearishSharps, + state.bearishSharps // + ); + + // + // Consolidation Zones ... + + // + Copy( + mConsolidationZones, + state.consolidationZones // + ); + + // + Copy( + mBullishConsolidationZones, + state.bullishConsolidationZones // + ); + + // + Copy( + mBearishConsolidationZones, + state.bearishConsolidationZones // + ); + + // + // Fair Value Gaps ... + + // + Copy( + mFairValueGaps, + state.fairValueGaps // + ); + + // + Copy( + mBullishFairValueGaps, + state.bullishFairValueGaps // + ); + + // + Copy( + mBearishFairValueGaps, + state.bearishFairValueGaps // + ); + + // + // Order Blocks ... + + // + Copy( + mOrderBlocks, + state.orderBlocks // + ); + + // + Copy( + mBullishOrderBlocks, + state.bullishOrderBlocks // + ); + + // + Copy( + mBearishOrderBlocks, + state.bearishOrderBlocks // + ); + } + + /** + * Destroy Instance ... + */ + void Destroy() + { + // + mBarTracker.Clean(); + ZeroMemory(mBarAnalyser); + + // + CleanCollections(); + } + + // + // + // + // + // + // + + /** + * Detect Swing ... + * + * @param bar: XOHCL instance ... + * @param state: ENUM_XPOI_EVENTS member ... + * + * @return ( bool ) + */ + bool DetectSwing( + XOHCL &bar, + ENUM_XPOI_EVENTS &state // + ) + { + // + bool result = false; + + // + state = X_POI_EVENT_NONE; + + // + result = bar.IsValid(); + if (!result) + { + return result; + } + + // + XOHCL sBar; + if (bar.Index() == 0) + { + // + result = bar.GetPreviousBar(sBar); + if (!result) + { + // + sBar.Clean(); + return result; + } + } + else + { + sBar = bar; + } + + // + ENUM_X_DIRECTION iDir; + result = mBarAnalyser.IsSwing( + sBar, + iDir, + mSwingRange // + ); + + // + result = result && + HasDirection(iDir); + if (!result) + { + // + sBar.Clean(); + return result; + } + + // + bool checkBar = bar.Index() != sBar.Index(); + + // + bool isBullish = + IsBullish(iDir) && + (!checkBar + ? true + : bar.low > sBar.low); + bool isBearish = + IsBearish(iDir) && + (!checkBar + ? true + : bar.high < sBar.high); + result = isBullish || + isBearish; + if (!result) + { + // + sBar.Clean(); + return result; + } + + // + XOHCL swingBar; + result = sBar.GetPreviousBar(swingBar); + if (!result) + { + // + sBar.Clean(); + swingBar.Clean(); + return result; + } + + // + ENUM_XPOIS type = + isBullish + ? X_POI_SWING_LOW + : X_POI_SWING_HIGH; + + // + // Swing Object ... + XCSwing *swing; + swing = new XCSwing(); + result = swing.Init( + swingBar, + type // + ); + if (!result) + { + // + sBar.Clean(); + swingBar.Clean(); + return result; + } + + // + // Add ... + + // + int idx = FindIndex( + swing, + mSwings // + ); + result = !IsValidIndex(idx); + if (!result) + { + // + sBar.Clean(); + swingBar.Clean(); + return result; + } + + // + // Add All Collection ... + Add( + swing, + mSwings // + ); + + // + // Bullish Swings (Swing Low) ... + if (isBullish) + { + // + Add( + swing, + mSwingLows // + ); + } + + // + // Bearish Swings (Swing High) ... + if (isBearish) + { + // + Add( + swing, + mSwingHighs // + ); + } + + // + // Prepare State ... + state = + isBullish + ? X_SWING_LOW_DETECTED + : X_SWING_HIGH_DETECTED; + + // + // Cleanup Resources ... + + // + sBar.Clean(); + swingBar.Clean(); + + // + return result; + } + + /** + * Detect Momentums ... + * + * @param bar: XOHCL instance ... + * @param state: ENUM_XPOI_EVENTS member ... + * + * @return ( bool ) + */ + bool DetectMomentum( + XOHCL &bar, + ENUM_XPOI_EVENTS &state // + ) + { + // + bool result = false; + + // + state = X_POI_EVENT_NONE; + + // + result = bar.IsValid(); + if (!result) + { + return result; + } + + // + XOHCL sBar; + if (bar.Index() == 0) + { + // + result = sBar.Init( + bar.symbol, + bar.period, + bar.Index() + 1 // + ); + if (!result) + { + // + sBar.Clean(); + return result; + } + } + else + { + sBar = bar; + } + + // + ENUM_X_DIRECTION iDir; + result = mBarAnalyser.IsMomentum( + sBar, + iDir, + mMomentumLoopback // + ); + + // + result = result && + HasDirection(iDir); + if (!result) + { + // + sBar.Clean(); + return result; + } + + // + bool isBullish = IsBullish(iDir); + bool isBearish = IsBearish(iDir); + + // + ENUM_XPOIS type = + isBullish + ? X_POI_MOMENTUM_BAR + : X_POI_MOMENTUM_BAR; + + // + // Swing Object ... + XCMomentumBar *momentum; + momentum = new XCMomentumBar(); + result = momentum.Init( + sBar // + ); + if (!result) + { + // + sBar.Clean(); + return result; + } + + // + int idx = FindIndex( + momentum, + mMomentums // + ); + result = !IsValidIndex(idx); + if (!result) + { + // + sBar.Clean(); + return result; + } + + // + // Momentums ... + Add( + momentum, + mMomentums // + ); + + // + if (isBullish) + { + // + Add( + momentum, + mBullishMomentums // + ); + } + + // + if (isBearish) + { + // + Add( + momentum, + mBearishMomentums // + ); + } + + // + state = + isBullish + ? X_BULLISH_MOMENTUM_BAR_DETECTED + : X_BEARISH_MOMENTUM_BAR_DETECTED; + + // + sBar.Clean(); + + // + return result; + } + + /** + * Detect Rejections ... + * + * @param bar: XOHCL instance ... + * @param state: ENUM_XPOI_EVENTS member ... + * + * @return ( bool ) + */ + bool DetectRejection( + XOHCL &bar, + ENUM_XPOI_EVENTS &state // + ) + { + // + bool result = false; + + // + state = X_POI_EVENT_NONE; + + // + result = bar.IsValid(); + if (!result) + { + return result; + } + + // + XOHCL sBar; + if (bar.Index() == 0) + { + // + result = sBar.Init( + bar.symbol, + bar.period, + bar.Index() + 1 // + ); + if (!result) + { + // + sBar.Clean(); + return result; + } + } + else + { + sBar = bar; + } + + // + ENUM_X_DIRECTION iDir; + result = mBarAnalyser.IsRejected( + sBar, + iDir, + mRejectionForceBarType, + mRejectionForceFiboPressure // + ); + + // + result = result && + HasDirection(iDir); + if (!result) + { + // + sBar.Clean(); + return result; + } + + // + bool isBullish = IsBullish(iDir); + bool isBearish = IsBearish(iDir); + + // + ENUM_XPOIS type = + isBullish + ? X_POI_MOMENTUM_BAR + : X_POI_MOMENTUM_BAR; + + // + // Swing Object ... + XCRejectionBar *rejection; + rejection = new XCRejectionBar(); + result = rejection.Init( + sBar // + ); + if (!result) + { + // + sBar.Clean(); + return result; + } + + // + int idx = FindIndex( + rejection, + mRejections // + ); + result = !IsValidIndex(idx); + if (!result) + { + // + sBar.Clean(); + return result; + } + + // + Add( + rejection, + mRejections // + ); + + // + if (isBullish) + { + // + Add( + rejection, + mBullishRejections // + ); + } + + // + if (isBearish) + { + // + Add( + rejection, + mBearishRejections // + ); + } + + // + state = + isBullish + ? X_BULLISH_REJECTION_BAR_DETECTED + : X_BEARISH_REJECTION_BAR_DETECTED; + + // + return result; + } + + /** + * Detect Pullback ... + * + * @param bar: XOHCL instance ... + * @param state: ENUM_XPOI_EVENTS member ... + * + * @return ( bool ) + */ + bool DetetctPullback( + XOHCL &bar, + ENUM_XPOI_EVENTS &state // + ) + { + // + bool result = false; + + // + state = X_POI_EVENT_NONE; + + // + result = bar.IsValid(); + if (!result) + { + return result; + } + + // + XOHCL sBar; + if (bar.Index() == 0) + { + // + result = sBar.Init( + bar.symbol, + bar.period, + bar.Index() + 1 // + ); + if (!result) + { + // + sBar.Clean(); + return result; + } + } + else + { + sBar = bar; + } + + // + ENUM_X_DIRECTION iDir; + result = mBarAnalyser.IsPullback( + sBar, + iDir, + mPullbackRange, + true // Force Body ... + ); + if (!result) + { + // + sBar.Clean(); + return result; + } + + // + bool isBullish = IsBullish(iDir); + bool isBearish = IsBearish(iDir); + result = isBullish || + isBearish; + if (!result) + { + // + sBar.Clean(); + return result; + } + + // + XOHCL fromBar; + result = fromBar.Init( + bar.symbol, + bar.period, + sBar.Index() + mPullbackRange // + ); + if (!result) + { + // + fromBar.Clean(); + return result; + } + + // + XBoxZone box; + + // + box.dir = iDir; + box.to = sBar.time; + box.from = fromBar.time; + box.symbol = fromBar.symbol; + box.period = fromBar.period; + box.lower = MathMin(sBar.low, fromBar.low); + box.upper = MathMax(sBar.high, fromBar.high); + box.type = ToString(iDir) + "_XPullBK" + box.symbol + "_" + ToString(box.period); + + // + result = box.IsValid(); + if (result) + { + // + AddRef( + box, + mPullbacks // + ); + + // + if (isBullish) + { + // + AddRef( + box, + mBullishPullbacks // + ); + } + + // + if (isBearish) + { + // + AddRef( + box, + mBearishPullbacks // + ); + } + + // + state = + isBullish + ? X_BULLISH_PULLBACK_DETECTED + : X_BEARISH_PULLBACK_DETECTED; + } + + // + // Cleanup Resources ... + + // + box.Clean(); + sBar.Clean(); + fromBar.Clean(); + + // + return result; + } + + /** + * Detect Consolidation Zones ... + * + * @param bar: XOHCL instance ... + * @param state: ENUM_XPOI_EVENTS member ... + * + * @return ( bool ) + */ + bool DetectConsolidationZone( + XOHCL &bar, + ENUM_XPOI_EVENTS &state // + ) + { + // + bool result = false; + + // + state = X_POI_EVENT_NONE; + + // + XOHCL sBar; + if (bar.Index() == 0) + { + // + result = sBar.Init( + bar.symbol, + bar.period, + bar.Index() + 1 // + ); + if (!result) + { + // + sBar.Clean(); + return result; + } + } + else + { + sBar = bar; + } + + // + XConsolidationZone cZone; + result = mBarAnalyser.HasConsolidationZone( + sBar, + cZone, + mConsolidationZoneMinLoopback, + mConsolidationZoneRangeInPoint, + mConsolidationZonesUpperAppliedTo, + mConsolidationZonesLowerAppliedTo // + ); + if (!result) + { + // + sBar.Clean(); + cZone.Clean(); + + // + return result; + } + + // + // Add ... + + // + bool isBullish = IsBullish(cZone.dir); + bool isBearish = IsBearish(cZone.dir); + + // + int idx = FindIndex( + cZone, + mConsolidationZones // + ); + result = !IsValidIndex(idx); + if (!result) + { + // + sBar.Clean(); + cZone.Clean(); + + // + return result; + } + + // + AddRef( + cZone, + mConsolidationZones // + ); + + // + if (isBullish) + { + // + AddRef( + cZone, + mBullishConsolidationZones // + ); + } + + // + if (isBearish) + { + // + AddRef( + cZone, + mBearishConsolidationZones // + ); + } + + // + state = + IsBullish(cZone.dir) + ? X_BULLISH_CONSOLIDATION_ZONE_DETECTED + : X_BEARISH_CONSOLIDATION_ZONE_DETECTED; + + // + cZone.Clean(); + + // + return result; + } + + /** + * Detect Sharp Change ... + * + * @param bar: XOHCL instance ... + * @param state: ENUM_XPOI_EVENTS member ... + * + * @return ( bool ) + */ + bool DetectSharp( + XOHCL &bar, + ENUM_XPOI_EVENTS &state // + ) + { + // + bool result = false; + + // + state = X_POI_EVENT_NONE; + + // + result = bar.IsValid(); + if (!result) + { + return result; + } + + // + int sharpRootIDX = -1; + ENUM_X_DIRECTION iDir; + result = mBarAnalyser.IsSharp( + bar, + iDir, + sharpRootIDX, + mSpikePriceType, + mSpikeForcBodyInRange, + mSpikeRangeExtendMultiplier // + ); + if (!result) + { + return result; + } + + // + bool isBullish = IsBullish(iDir); + bool isBearish = IsBearish(iDir); + + // + XOHCL fromBar; + result = fromBar.Init( + bar.symbol, + bar.period, + sharpRootIDX // + ); + if (!result) + { + // + fromBar.Clean(); + return result; + } + + // + XBoxZone box; + + // + box.dir = iDir; + box.to = bar.time; + box.from = fromBar.time; + box.symbol = fromBar.symbol; + box.period = fromBar.period; + box.type = ToString(iDir) + "_XSharp" + box.symbol + "_" + ToString(box.period); + + // + box.upper = + isBullish + ? bar.high + : fromBar.high; + + // + box.lower = + isBullish + ? fromBar.low + : bar.low; + + // + result = box.IsValid(); + if (result) + { + // + AddRef( + box, + mSharps // + ); + + // + if (isBullish) + { + // + AddRef( + box, + mBullishSharps // + ); + } + + // + if (isBearish) + { + // + AddRef( + box, + mBearishSharps // + ); + } + + // + state = + isBullish + ? X_BULLISH_SHARP_DETECTED + : X_BEARISH_SHARP_DETECTED; + } + + // + // Cleanup Resources ... + + // + box.Clean(); + fromBar.Clean(); + + // + return result; + } + + /** + * Detect Spike ... + * + * @param bar: XOHCL instance ... + * @param state: ENUM_XPOI_EVENTS member ... + * + * @return ( bool ) + */ + bool DetectSpike( + XOHCL &bar, + ENUM_XPOI_EVENTS &state // + ) + { + // + bool result = false; + + // + state = X_POI_EVENT_NONE; + + // + result = bar.IsValid(); + if (!result) + { + return result; + } + + // + int rootIDX = -1; + ENUM_X_DIRECTION iDir; + result = mBarAnalyser.IsSpike( + bar, + iDir, + rootIDX, + mSpikePriceType, + mSpikeForcBodyInRange, + mSpikeRangeExtendMultiplier, + mSpikeSameBars // + ); + if (!result) + { + return result; + } + + // + // Chek Same Bars ... + int sameBarsIndex = -1; + ENUM_X_DIRECTION sameBarsDir; + result = mBarAnalyser.HasSameBars( + bar, + sameBarsDir, + sameBarsIndex, + mSpikeSameBars // + ); + if (!result) + { + return result; + } + + // + // Validate Same Bars Dir and Spike Dir ... + result = iDir == sameBarsDir; + if (!result) + { + return result; + } + + // + bool isBullish = IsBullish(iDir); + bool isBearish = IsBearish(iDir); + + // + XOHCL fromBar; + result = fromBar.Init( + bar.symbol, + bar.period, + rootIDX // + ); + if (!result) + { + // + fromBar.Clean(); + return result; + } + + // + XBoxZone box; + + // + box.dir = iDir; + box.to = bar.time; + box.from = fromBar.time; + box.symbol = fromBar.symbol; + box.period = fromBar.period; + box.type = ToString(iDir) + "_XSpike_" + box.symbol + "_" + ToString(box.period); + + // + box.upper = + isBullish + ? bar.high + : fromBar.high; + + // + box.lower = + isBullish + ? fromBar.low + : bar.low; + + // + result = box.IsValid(); + if (result) + { + // + AddRef( + box, + mSpikes // + ); + + // + if (isBullish) + { + // + AddRef( + box, + mBullishSpikes // + ); + } + + // + if (isBearish) + { + // + AddRef( + box, + mBearishSpikes // + ); + } + + // + state = + isBullish + ? X_BULLISH_SPIKE_DETECTED + : X_BEARISH_SPIKE_DETECTED; + } + + // + // Cleanup Resources ... + + // + box.Clean(); + fromBar.Clean(); + + // + return result; + } + + /** + * Detect Support Zone ... + * + * @param bar: XOHCL instance ... + * @param state: ENUM_XPOI_EVENTS member ... + * + * @return ( bool ) + */ + bool DetectSupportZone( + XOHCL &bar, + ENUM_XPOI_EVENTS &state // + ) + { + // + bool result = false; + + // + state = X_POI_EVENT_NONE; + + // + result = bar.IsValid(); + if (!result) + { + return result; + } + + // + XOHCL supportBar; + result = mBarAnalyser + .HasSupport( + bar, + supportBar, + mSupResRange // + ); + if (!result) + { + // + supportBar.Clean(); + + // + return result; + } + + // + XCSupportZone *supportZone; + supportZone = new XCSupportZone(); + result = supportZone.Init( + supportBar, + mSupResRange, + mSupResRangeAsStart // Use Range As Start ... + ); + if (!result) + { + // + supportBar.Clean(); + ZeroMemory(supportZone); + + // + return result; + } + + // + // Check Zone Not Activated ... + if (mSupResForceActivation) + { + // + XOHCL activationBar; + bool isActivationBarBodyIn = false; + bool isActivated = supportZone.IsActivated( + X_DIRECTION_BULLISH, + activationBar, + isActivationBarBodyIn, + false, + bar.period // + ); + result = !isActivated; + if (!result) + { + // + supportBar.Clean(); + activationBar.Clean(); + ZeroMemory(supportZone); + + // + return result; + } + + // + activationBar.Clean(); + } + + // + // Add ... + + // + int idx = FindIndex( + supportZone, + mSupportZones // + ); + result = !IsValidIndex(idx); + if (!result) + { + // + supportBar.Clean(); + ZeroMemory(supportZone); + + // + return result; + } + + // + Add( + supportZone, + mSupportZones // + ); + + // + state = X_SUPPORT_ZONE_DETECTED; + + // + supportBar.Clean(); + + // + return result; + } + + /** + * Detect Resistance Zone ... + * + * @param bar: XOHCL instance ... + * @param state: ENUM_XPOI_EVENTS member ... + * + * @return ( bool ) + */ + bool DetectResistanceZone( + XOHCL &bar, + ENUM_XPOI_EVENTS &state // + ) + { + // + bool result = false; + + // + state = X_POI_EVENT_NONE; + + // + result = bar.IsValid(); + if (!result) + { + return result; + } + + // + XOHCL resistanceBar; + result = mBarAnalyser + .HasResistance( + bar, + resistanceBar, + mSupResRange // + ); + if (!result) + { + // + resistanceBar.Clean(); + + // + return result; + } + + // + XCResistanceZone *resistanceZone; + resistanceZone = new XCResistanceZone(); + result = resistanceZone.Init( + resistanceBar, + mSupResRange, + mSupResRangeAsStart // Use Range As Start ... + ); + if (!result) + { + // + resistanceBar.Clean(); + ZeroMemory(resistanceZone); + + // + return result; + } + + // + // Check Zone Not Activated ... + if (mSupResForceActivation) + { + // + XOHCL activationBar; + bool isActivationBarBodyIn = false; + bool isActivated = resistanceZone.IsActivated( + X_DIRECTION_BULLISH, + activationBar, + isActivationBarBodyIn, + false, + bar.period // + ); + result = !isActivated; + if (!result) + { + // + resistanceBar.Clean(); + activationBar.Clean(); + ZeroMemory(resistanceZone); + + // + return result; + } + + // + activationBar.Clean(); + } + + // + // Add ... + + // + int idx = FindIndex( + resistanceZone, + mResistanceZones // + ); + result = !IsValidIndex(idx); + if (!result) + { + // + resistanceBar.Clean(); + ZeroMemory(resistanceZone); + + // + return result; + } + + // + Add( + resistanceZone, + mResistanceZones // + ); + + // + state = X_RESISTANCE_ZONE_DETECTED; + + // + resistanceBar.Clean(); + + // + return result; + } + + /** + * Detect Supply Zone ... + * + * @param bar: XOHCL instance ... + * @param state: ENUM_XPOI_EVENTS member ... + * + * @return ( bool ) + */ + bool DetectSupplyZone( + XOHCL &bar, + ENUM_XPOI_EVENTS &state // + ) + { + // + bool result = false; + + // + state = X_POI_EVENT_NONE; + + // + result = bar.IsValid(); + if (!result) + { + return result; + } + + // + int mSupDemRange = mSupResRange * 2; + + // + XOHCL supplyBar; + result = mBarAnalyser + .HasResistance( + bar, + supplyBar, + mSupDemRange // + ); + if (!result) + { + // + supplyBar.Clean(); + + // + return result; + } + + // + XCSupplyZone *supplyZone; + supplyZone = new XCSupplyZone(); + result = supplyZone.Init( + supplyBar, + mSupDemRange, + mSupResRangeAsStart // Use Range As Start ... + ); + if (!result) + { + // + supplyBar.Clean(); + ZeroMemory(supplyZone); + + // + return result; + } + + // + // Check Zone Not Activated ... + if (mSupResForceActivation) + { + // + XOHCL activationBar; + bool isActivationBarBodyIn = false; + bool isActivated = supplyZone.IsActivated( + X_DIRECTION_BULLISH, + activationBar, + isActivationBarBodyIn, + false, + bar.period // + ); + result = !isActivated; + if (!result) + { + // + supplyBar.Clean(); + activationBar.Clean(); + ZeroMemory(supplyZone); + + // + return result; + } + + // + activationBar.Clean(); + } + + // + // Add ... + + // + int idx = FindIndex( + supplyZone, + mSupplyZones // + ); + result = !IsValidIndex(idx); + if (!result) + { + // + supplyBar.Clean(); + ZeroMemory(supplyZone); + + // + return result; + } + + // + Add( + supplyZone, + mSupplyZones // + ); + + // + state = X_SUPPLY_ZONE_DETECTED; + + // + supplyBar.Clean(); + + // + return result; + } + + /** + * Detect Demand Zone ... + * + * @param bar: XOHCL instance ... + * @param state: ENUM_XPOI_EVENTS member ... + * + * @return ( bool ) + */ + bool DetectDemandZone( + XOHCL &bar, + ENUM_XPOI_EVENTS &state // + ) + { + // + bool result = false; + + // + state = X_POI_EVENT_NONE; + + // + result = bar.IsValid(); + if (!result) + { + return result; + } + + // + int mSupDemRange = mSupResRange * 2; + + // + XOHCL demandBar; + result = mBarAnalyser + .HasSupport( + bar, + demandBar, + mSupDemRange // + ); + if (!result) + { + // + demandBar.Clean(); + + // + return result; + } + + // + XCDemandZone *demandZone; + demandZone = new XCDemandZone(); + result = demandZone.Init( + demandBar, + mSupDemRange, + mSupResRangeAsStart // Use Range As Start ... + ); + if (!result) + { + // + demandBar.Clean(); + ZeroMemory(demandZone); + + // + return result; + } + + // + // Check Zone Not Activated ... + if (mSupResForceActivation) + { + // + XOHCL activationBar; + bool isActivationBarBodyIn = false; + bool isActivated = demandZone.IsActivated( + X_DIRECTION_BULLISH, + activationBar, + isActivationBarBodyIn, + false, + bar.period // + ); + result = !isActivated; + if (!result) + { + // + demandBar.Clean(); + activationBar.Clean(); + ZeroMemory(demandZone); + + // + return result; + } + + // + activationBar.Clean(); + } + + // + // Add ... + + // + int idx = FindIndex( + demandZone, + mDemandZones // + ); + result = !IsValidIndex(idx); + if (!result) + { + // + demandBar.Clean(); + ZeroMemory(demandZone); + + // + return result; + } + + // + Add( + demandZone, + mDemandZones // + ); + + // + state = X_DEMAND_ZONE_DETECTED; + + // + demandBar.Clean(); + + // + return result; + } + + /** + * Detect Fair Value Gaps ... + * + * @param bar: XOHCL instance ... + * @param state: ENUM_XPOI_EVENTS member ... + * + * @return ( bool ) + */ + bool DetectFairValueGap( + XOHCL &bar, + ENUM_XPOI_EVENTS &state // + ) + { + // + bool result = false; + + // + state = X_POI_EVENT_NONE; + + // + result = bar.IsValid(); + if (!result) + { + return result; + } + + // + XOHCL fvgStartBar; + XOHCL fvgEndBar; + ENUM_X_DIRECTION fvgDir; + result = mBarAnalyser.HasFairValueGap( + bar, + fvgStartBar, + fvgEndBar, + fvgDir, + mFairValueGapSameBars // + ); + if (!result) + { + // + fvgEndBar.Clean(); + fvgStartBar.Clean(); + + // + return result; + } + + // + XCFVG *fvg; + fvg = new XCFVG(); + result = fvg.Init( + fvgStartBar, + fvgEndBar, + fvgDir // + ); + if (!result) + { + // + ZeroMemory(fvg); + fvgEndBar.Clean(); + fvgStartBar.Clean(); + + // + return result; + } + + // + bool isBullish = IsBullish(fvgDir); + bool isBearish = IsBearish(fvgDir); + + // + // Check Zone Not Activated ... + if (mFairValueGapForceActivation) + { + // + XOHCL activationBar; + bool isActivationBarBodyIn = false; + bool isActivated = fvg.IsActivated( + fvgDir, + activationBar, + isActivationBarBodyIn, + false, + bar.period // + ); + result = !isActivated; + if (!result) + { + // + ZeroMemory(fvg); + fvgEndBar.Clean(); + fvgStartBar.Clean(); + activationBar.Clean(); + + // + return result; + } + + // + activationBar.Clean(); + } + + // + int idx = FindIndex( + fvg, + mFairValueGaps // + ); + result = !IsValidIndex(idx); + if (!result) + { + // + ZeroMemory(fvg); + fvgEndBar.Clean(); + fvgStartBar.Clean(); + + // + return result; + } + + // + Add( + fvg, + mFairValueGaps // + ); + + // + if (isBullish) + { + // + Add( + fvg, + mBullishFairValueGaps // + ); + } + + // + if (isBearish) + { + // + Add( + fvg, + mBearishFairValueGaps // + ); + } + + // + state = + isBullish + ? X_BULLISH_FVG_DETECTED + : X_BEARISH_FVG_DETECTED; + + // + fvgEndBar.Clean(); + fvgStartBar.Clean(); + + // + return result; + } + + /** + * Detect Order Blocks ... + * + * @param bar: XOHCL instance ... + * @param state: ENUM_XPOI_EVENTS member ... + * + * @return ( bool ) + */ + bool DetectOrderBlock( + XOHCL &bar, + ENUM_XPOI_EVENTS &state // + ) + { + // + bool result = false; + + // + state = X_POI_EVENT_NONE; + + // + result = bar.IsValid(); + if (!result) + { + return result; + } + + // + XOHCL obBar; + ENUM_X_DIRECTION obDir; + result = mBarAnalyser.HasOrderBlock( + bar, + obBar, + obDir, + mOrderBlockSameBars, + mOrderBlockForceSpike, + mOrderBlockForceFairValueGap, + mOrderBlockForceSupportResistance // + ); + if (!result) + { + // + obBar.Clean(); + + // + return result; + } + + // + XCOrderBlock *ob; + ob = new XCOrderBlock(); + result = ob.Init( + obBar, + obDir // + ); + if (!result) + { + // + obBar.Clean(); + ZeroMemory(ob); + + // + return result; + } + + // + bool isBullish = IsBullish(obDir); + bool isBearish = IsBearish(obDir); + + // + // Check Zone Not Activated ... + if (mOrderBlockForceActivation) + { + // + XOHCL activationBar; + bool isActivationBarBodyIn = false; + bool isActivated = ob.IsActivated( + obDir, + activationBar, + isActivationBarBodyIn, + false, + bar.period // + ); + result = !isActivated; + if (!result) + { + // + obBar.Clean(); + activationBar.Clean(); + ZeroMemory(ob); + + // + return result; + } + + // + activationBar.Clean(); + } + + // + int idx = FindIndex( + ob, + mOrderBlocks // + ); + result = !IsValidIndex(idx); + if (!result) + { + // + obBar.Clean(); + ZeroMemory(ob); + + // + return result; + } + + // + Add( + ob, + mOrderBlocks // + ); + + // + if (isBullish) + { + // + Add( + ob, + mBullishOrderBlocks // + ); + } + + // + if (isBearish) + { + // + Add( + ob, + mBearishOrderBlocks // + ); + } + + // + state = + isBullish + ? X_BULLISH_ORDERBLOCK_DETECTED + : X_BEARISH_ORDERBLOCK_DETECTED; + + // + obBar.Clean(); + + // + return result; + } + + // + protected: + // + + /** + * Notify Event Listeners ... + * + * @param event: ENUM_XPOI_EVENTS member, Specified Occured Event ... + * @param param: XCBasePOI implementation, Specified Event Object ... + */ + void NotifyEventListeners( + ENUM_XPOI_EVENTS event, + XCBasePOI *param // + ) + { + // + int count = ArraySize(mEventListeners); + if (!IsValidSize(count)) + { + return; + } + + // + for (int i = 0; i < count; i++) + { + // + mEventListeners[i]( + event, + param // + ); + } + } + + // + private: + // + + // + // Props ... + string mSymbol; // Market Symbol ... + ENUM_TIMEFRAMES mPeriod; // Market Period ... + XBarTracker mBarTracker; // Market Bar Tracker ... + XCBarAnalyser *mBarAnalyser; // Bar Analyser ... + + // + bool mLock; + + // + int mMaxRequiredPOIs; // Max Allowed Holds POI(s) ... + int maxAllowedLoopbackForInit; // Max Allowed Loopback for POI(s) Detection on Initialization Process ... + + // + TOnPOIEvent mEventListeners[]; // Event Listeners ... + + // + // Swings ... + XCSwing *mSwings[]; // Holds Founded Swing ... + XCSwing *mSwingLows[]; // Holds Founded Swing Lows ... + XCSwing *mSwingHighs[]; // Holds Founded Swing Highs ... + int mSwingRange; // Swing Detection Range ... + + // + // Pullbacks ... + XBoxZone mPullbacks[]; // Holds Founded Pullbacks ... + XBoxZone mBullishPullbacks[]; // Holds Founded Bullish Pullbacks ... + XBoxZone mBearishPullbacks[]; // Holds Founded Bearish Pullbacks ... + int mPullbackRange; // Pullback Detection Range ... + + // + // Momentums ... + XCMomentumBar *mMomentums[]; // Holds Founded Momentum Bars ... + XCMomentumBar *mBullishMomentums[]; // Holds Founded Bullish Momentum Bars ... + XCMomentumBar *mBearishMomentums[]; // Holds Founded Bearish Momentum Bars ... + int mMomentumLoopback; // Momentum Detecting Loopback ... + + // + // Rejections ... + XCRejectionBar *mRejections[]; // Holds Founded Rejection Bars ... + XCRejectionBar *mBullishRejections[]; // Holds Founded Bullish Rejection Bars ... + XCRejectionBar *mBearishRejections[]; // Holds Founded Bearish Rejection Bars ... + bool mRejectionForceBarType; // Rejection Detecting Force Bar Type ... + bool mRejectionForceFiboPressure; // Rejection Detecting Force Fibo Pressure ... + + // + // Consolidation Zones ... + XConsolidationZone mConsolidationZones[]; // Holds Founded Consolidation Zones ... + XConsolidationZone mBullishConsolidationZones[]; // Holds Founded Bullish Consolidation Zones ... + XConsolidationZone mBearishConsolidationZones[]; // Holds Founded Bearish Consolidation Zones ... + int mConsolidationZoneMinLoopback; // Minimum Length of Cnsolidation Zone ... + double mConsolidationZoneRangeInPoint; // Consolidation Zone Range in Point ... + ENUM_X_PRICE mConsolidationZonesLowerAppliedTo; // Consolidation Zone Upper Applied To ... + ENUM_X_PRICE mConsolidationZonesUpperAppliedTo; // Consolidation Zone Lower Applied To ... + + // + // Spike/Sharp Zones ... + XBoxZone mSharps[]; // Holds Founded Sharps ... + XBoxZone mBullishSharps[]; // Holds Founded Bullish Sharps ... + XBoxZone mBearishSharps[]; // Holds Founded Bearish Sharps ... + XBoxZone mSpikes[]; // Holds Founded Spikes ... + XBoxZone mBullishSpikes[]; // Holds Founded Bullish Spikes ... + XBoxZone mBearishSpikes[]; // Holds Founded Bearish Spikes ... + ENUM_X_PRICE mSpikePriceType; // Spike Detection Price Type ... + bool mSpikeForcBodyInRange; // Spike Detection Force Body In Range ... + double mSpikeRangeExtendMultiplier; // Spike Detection Range Extends Multiplier ... + int mSpikeSameBars; // Spike Detection Same Bars ... + + // + // Support and Resistance ... + // Supply and Demand ... + + // + int mSupResRange; // Support and Resistance Detection Range ... + bool mSupResRangeAsStart; // use Support and Resistance Range as Start ... + bool mSupResForceActivation; // Force Activations in Supply/Demand and Support/Resistance Detections ... + + // + XCSupplyZone *mSupplyZones[]; // Holds Detected Supply Zones ... + XCDemandZone *mDemandZones[]; // Holds Detected Demand Zones ... + + // + XCSupportZone *mSupportZones[]; // Holds Detected Support Zones ... + XCResistanceZone *mResistanceZones[]; // Holds Detected Resistance Zones ... + + // + // Fair Value Gaps ... + XCFVG *mFairValueGaps[]; // Holds Founded FairValueGaps ... + XCFVG *mBullishFairValueGaps[]; // Holds Founded Bullish FairValueGaps ... + XCFVG *mBearishFairValueGaps[]; // Holds Founded Bearish FairValueGaps ... + int mFairValueGapSameBars; // FairValueGap Detection Same Bars ... + bool mFairValueGapForceActivation; // FairValueGap Detection Force Check Activation ... + + // + // Order Blocks ... + XCOrderBlock *mOrderBlocks[]; // Holds Founded OrderBlocks ... + XCOrderBlock *mBullishOrderBlocks[]; // Holds Founded Bullish OrderBlocks ... + XCOrderBlock *mBearishOrderBlocks[]; // Holds Founded Bearish OrderBlocks ... + int mOrderBlockSameBars; // OrderBlock Detection Same Bars ... + bool mOrderBlockForceSpike; // Order Blocs Detection Force Spike ... + bool mOrderBlockForceFairValueGap; // Order Blocs Detection Force Fair Value Gaps ... + bool mOrderBlockForceSupportResistance; // Order Blocs Detection Force Support/Resisatnce ... + bool mOrderBlockForceActivation; // Order Blocs Detection Force Check Activation ... + + /** + * Clean All Collections ... + */ + void CleanCollections() + { + // + Clean(mSwings); + Clean(mSwingLows); + Clean(mSwingHighs); + Clean(mMomentums); + Clean(mBullishMomentums); + Clean(mBearishMomentums); + Clean(mRejections); + Clean(mBullishRejections); + Clean(mBearishRejections); + Clean(mConsolidationZones); + Clean(mBullishConsolidationZones); + Clean(mBearishConsolidationZones); + Clean(mSpikes); + Clean(mBullishSpikes); + Clean(mBearishSpikes); + Clean(mSupplyZones); + Clean(mDemandZones); + Clean(mSupportZones); + Clean(mResistanceZones); + Clean(mFairValueGaps); + Clean(mBullishFairValueGaps); + Clean(mBearishFairValueGaps); + Clean(mOrderBlocks); + Clean(mBullishOrderBlocks); + Clean(mBearishOrderBlocks); + } + + /** + * Reverse Collections ... + */ + void ReverseCollections() + { + // + ArrayReverse(mSwings); + ArrayReverse(mSwingLows); + ArrayReverse(mSwingHighs); + ArrayReverse(mMomentums); + ArrayReverse(mBullishMomentums); + ArrayReverse(mBearishMomentums); + ArrayReverse(mRejections); + ArrayReverse(mBullishRejections); + ArrayReverse(mBearishRejections); + ArrayReverse(mConsolidationZones); + ArrayReverse(mBullishConsolidationZones); + ArrayReverse(mBearishConsolidationZones); + ArrayReverse(mSpikes); + ArrayReverse(mBullishSpikes); + ArrayReverse(mBearishSpikes); + ArrayReverse(mSupplyZones); + ArrayReverse(mDemandZones); + ArrayReverse(mSupportZones); + ArrayReverse(mResistanceZones); + ArrayReverse(mFairValueGaps); + ArrayReverse(mBullishFairValueGaps); + ArrayReverse(mBearishFairValueGaps); + ArrayReverse(mOrderBlocks); + ArrayReverse(mBullishOrderBlocks); + ArrayReverse(mBearishOrderBlocks); + } + + /** + * Cleanup Unused Collection Items ... + * + * @param maxAllowed: int, Max Allowed ... + */ + void CleanupUnusedCollections( + int maxAllowed = 0 // + ) + { + // + maxAllowed = MaxRequiredPOIs(); + + // + if (maxAllowed <= 0) + { + return; + } + + // + CleanupArray(mSwings, maxAllowed); + CleanupArray(mSwingLows, maxAllowed); + CleanupArray(mSwingHighs, maxAllowed); + CleanupArray(mMomentums, maxAllowed); + CleanupArray(mBullishMomentums, maxAllowed); + CleanupArray(mBearishMomentums, maxAllowed); + CleanupArray(mRejections, maxAllowed); + CleanupArray(mBullishRejections, maxAllowed); + CleanupArray(mBearishRejections, maxAllowed); + CleanupArray(mConsolidationZones, maxAllowed); + CleanupArray(mBullishConsolidationZones, maxAllowed); + CleanupArray(mBearishConsolidationZones, maxAllowed); + CleanupArray(mSpikes, maxAllowed); + CleanupArray(mBullishSpikes, maxAllowed); + CleanupArray(mBearishSpikes, maxAllowed); + CleanupArray(mSupplyZones, maxAllowed); + CleanupArray(mDemandZones, maxAllowed); + CleanupArray(mSupportZones, maxAllowed); + CleanupArray(mResistanceZones, maxAllowed); + CleanupArray(mFairValueGaps, maxAllowed); + CleanupArray(mBullishFairValueGaps, maxAllowed); + CleanupArray(mBearishFairValueGaps, maxAllowed); + CleanupArray(mOrderBlocks, maxAllowed); + CleanupArray(mBullishOrderBlocks, maxAllowed); + CleanupArray(mBearishOrderBlocks, maxAllowed); + } + + // +}; + +// \ No newline at end of file diff --git a/BKPS/14040203/Classes/x-saherelm.x-poi.drawer.class.mq5 b/BKPS/14040203/Classes/x-saherelm.x-poi.drawer.class.mq5 new file mode 100644 index 0000000..5a31af8 --- /dev/null +++ b/BKPS/14040203/Classes/x-saherelm.x-poi.drawer.class.mq5 @@ -0,0 +1,4356 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Class Library +// -------------------------------------- +// Name: XPOIDrawer +// Description: Provides Point of Interests +// Drawing Tools ... +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +////////////////////////////////////////////////////// +// +// Global Properties ... +#property library +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://www.saherelm.ir" +#property version "1.00" +#property strict + +// +// Imports ... +#include "../Classes/x-saherelm.base.class.mq5" +#include "../Classes/x-saherelm.x-cobject.class.mq5" +#include "../Libraries/x-saherelm.x-poi.extensions.lib.mq5" +#include "../Libraries/x-saherelm.x-poi.state.lib.mq5" + +// +// Definitions ... +class XCPOIDrawer : public XCBase +{ + // + public: + // + + // + // Constructor ... + void XCPOIDrawer() + { + // + Default(); + } + + // + // Deconstructor ... + void ~XCPOIDrawer() + { + // + Clean(mTicksZoneSpecs); + } + + // + // Setter Getter (s) ... + + /** + * Get Prefix ... + * + * @return ( string ) + */ + string Prefix() + { + return mPrefix; + } + + /** + * Set Prifx ... + * + * @param value: String ... + */ + void Prefix(string value) + { + mPrefix = value; + } + + /** + * Get Chart ID ... + * + * @return ( long ) + */ + long ChartIdentification() + { + return mChartIdentification; + } + + /** + * Set Chart ID ... + * + * @param value: Long ... + */ + void ChartIdentification(long value) + { + // + if (value < 0) + { + value = 0; + } + + // + mChartIdentification = value; + } + + /** + * Get SubWindow Id ... + * + * @return ( int ) + */ + int SubWindowIdentification() + { + return mSubWindowIdentification; + } + + /** + * Set SubWindow Id ... + * + * @param value: Integer ... + */ + void SubWindowIdentification(int value) + { + // + if (value < 0) + { + value = 0; + } + + // + mSubWindowIdentification = value; + } + + // + // XOHCL ... + + /** + * Get Bar Width ... + * + * @return ( int ) + */ + int BarWidth() + { + return mBarWidth; + } + + /** + * Set Bar Width ... + * + * @param value: Integer ... + */ + void BarWidth(int value) + { + // + if (value < 0) + { + value = 0; + } + + // + mBarWidth = value; + } + + /** + * Get Bar Bullish Color ... + * + * @return ( color ) + */ + color BarBullishColor() + { + return mBarBullishColor; + } + + /** + * Set Bar Bullish Color ... + * + * @param value: Color ... + */ + void BarBullishColor(color value) + { + mBarBullishColor = value; + } + + /** + * Get Bar Bearish Color ... + * + * @return ( color ) + */ + color BarBearishColor() + { + return mBarBearishColor; + } + + /** + * Set Bar Bearish Color ... + * + * @param value: Color ... + */ + void BarBearishColor(color value) + { + mBarBearishColor = value; + } + + /** + * Get Fill Bar High Shadow State ... + * + * @return ( bool ) + */ + bool BarFillHighShadow() + { + return mBarFillHighShadow; + } + + /** + * Set Fill Bar High Shadow State ... + * + * @param value: Boolean ... + */ + void BarFillHighShadow(bool value) + { + mBarFillHighShadow = value; + } + + /** + * Get Bar High Shadow Style ... + * + * @return ( ENUM_LINE_STYLE ) + */ + ENUM_LINE_STYLE BarHighShadowStyle() + { + return mBarHighShadowStyle; + } + + /** + * Set Bar High Shadow Style ... + * + * @param value: ENUM_LINE_STYLE member ... + */ + void BarHighShadowStyle(ENUM_LINE_STYLE value) + { + mBarHighShadowStyle = value; + } + + /** + * Get Fill Bar Body State ... + * + * @return ( bool ) + */ + bool BarFillBody() + { + return mBarFillBody; + } + + /** + * Set Fill Bar Body State ... + * + * @param value: Boolean ... + */ + void BarFillBody(bool value) + { + mBarFillBody = value; + } + + /** + * Get Bar Body Style ... + * + * @return ( ENUM_LINE_STYLE ) + */ + ENUM_LINE_STYLE BarBodyStyle() + { + return mBarBodyStyle; + } + + /** + * Set Bar Body Style ... + * + * @param value: ENUM_LINE_STYLE member ... + */ + void BarBodyStyle(ENUM_LINE_STYLE value) + { + mBarBodyStyle = value; + } + + /** + * Get Fill Bar Low Show State ... + * + * @return ( bool ) + */ + bool BarFillLowShadow() + { + return mBarFillLowShadow; + } + + /** + * Set Fill Bar Low Show State ... + * + * @param value: Boolean ... + */ + void BarFillLowShadow(bool value) + { + mBarFillLowShadow = value; + } + + /** + * Get Bar Low Shadow Style ... + * + * @return ( ENUM_LINE_STYLE ) + */ + ENUM_LINE_STYLE BarLowShadowStyle() + { + return mBarLowShadowStyle; + } + + /** + * Set Bar Low Shadow Style ... + * + * @param value: ENUM_LINE_STYLE member ... + */ + void BarLowShadowStyle(ENUM_LINE_STYLE value) + { + mBarLowShadowStyle = value; + } + + // + // Swing Low ... + + /** + * Get Swing Low Width ... + * + * @return ( int ) + */ + int SwingLowWidth() + { + return mSwingLowWidth; + } + + /** + * Set Swing Low Width ... + * + * @param value: Integer ... + */ + void SwingLowWidth(int value) + { + // + if (value < 1) + { + value = 1; + } + + // + mSwingLowWidth = value; + } + + /** + * Get Swing Low Arrow Code ... + * + * @return ( int ) + */ + int SwingLowArrow() + { + return mSwingLowArrow; + } + + /** + * Set Swing Low Arrow Code ... + * + * @param value: Integer ... + */ + void SwingLowArrow(int value) + { + // + mSwingLowArrow = value; + } + + /** + * Get Swing Low Color ... + * + * @return ( color ) + */ + color SwingLowColor() + { + return mSwingLowColor; + } + + /** + * Set Swing Low Color ... + * + * @param value: Color ... + */ + void SwingLowColor(color value) + { + mSwingLowColor = value; + } + + // + // Swing High ... + + /** + * Get Swing High Width ... + * + * @return ( int ) + */ + int SwingHighWidth() + { + return mSwingHighWidth; + } + + /** + * Set Swing High Width ... + * + * @param value: Integer ... + */ + void SwingHighWidth(int value) + { + // + if (value < 1) + { + value = 1; + } + + // + mSwingHighWidth = value; + } + + /** + * Get Swing High Arrow Code ... + * + * @return ( int ) + */ + int SwingHighArrow() + { + return mSwingHighArrow; + } + + /** + * Set Swing High Arrow Code ... + * + * @param value: Integer ... + */ + void SwingHighArrow(int value) + { + // + mSwingHighArrow = value; + } + + /** + * Get Swing High Color ... + * + * @return ( color ) + */ + color SwingHighColor() + { + return mSwingHighColor; + } + + /** + * Set Swing High Color ... + * + * @param value: Color ... + */ + void SwingHighColor(color value) + { + mSwingHighColor = value; + } + + // + // Bullish Momentum Bar ... + + /** + * Get Bullish Momentum Bar Width ... + * + * @return ( int ) + */ + int BullishMomentumBarWidth() + { + return mBullishMomentumBarWidth; + } + + /** + * Set Bullish Momentum Bar Width ... + * + * @param value: Integer ... + */ + void BullishMomentumBarWidth(int value) + { + // + if (value < 1) + { + value = 1; + } + + // + mBullishMomentumBarWidth = value; + } + + /** + * Get Bullish Momentum Bar Arrow Code ... + * + * @return ( int ) + */ + int BullishMomentumBarArrow() + { + return mBullishMomentumBarArrow; + } + + /** + * Set Bullish Momentum Bar Arrow Code ... + * + * @param value: Integer ... + */ + void BullishMomentumBarArrow(int value) + { + // + mBullishMomentumBarArrow = value; + } + + /** + * Get Bullish Momentum Bar Color ... + * + * @return ( color ) + */ + color BullishMomentumBarColor() + { + return mBullishMomentumBarColor; + } + + /** + * Set Bullish Momentum Bar Color ... + * + * @param value: Color ... + */ + void BullishMomentumBarColor(color value) + { + mBullishMomentumBarColor = value; + } + + // + // Bearish Momentum Bar ... + + /** + * Get Bearish Momentum Bar Width ... + * + * @return ( int ) + */ + int BearishMomentumBarWidth() + { + return mBearishMomentumBarWidth; + } + + /** + * Set Bearish Momentum Bar Width ... + * + * @param value: Integer ... + */ + void BearishMomentumBarWidth(int value) + { + // + if (value < 1) + { + value = 1; + } + + // + mBearishMomentumBarWidth = value; + } + + /** + * Get Bearish Momentum Bar Arrow Code ... + * + * @return ( int ) + */ + int BearishMomentumBarArrow() + { + return mBearishMomentumBarArrow; + } + + /** + * Set Bearish Momentum Bar Arrow Code ... + * + * @param value: Integer ... + */ + void BearishMomentumBarArrow(int value) + { + // + mBearishMomentumBarArrow = value; + } + + /** + * Get Bearish Momentum Bar Color ... + * + * @return ( color ) + */ + color BearishMomentumBarColor() + { + return mBearishMomentumBarColor; + } + + /** + * Set Bearish Momentum Bar Color ... + * + * @param value: Color ... + */ + void BearishMomentumBarColor(color value) + { + mBearishMomentumBarColor = value; + } + + // + // Bullish Rejection Bar ... + + /** + * Get Bullish Rejection Bar Width ... + * + * @return ( int ) + */ + int BullishRejectionBarWidth() + { + return mBullishRejectionBarWidth; + } + + /** + * Set Bullish Rejection Bar Width ... + * + * @param value: Integer ... + */ + void BullishRejectionBarWidth(int value) + { + // + if (value < 1) + { + value = 1; + } + + // + mBullishRejectionBarWidth = value; + } + + /** + * Get Bullish Rejection Bar Arrow Code ... + * + * @return ( int ) + */ + int BullishRejectionBarArrow() + { + return mBullishRejectionBarArrow; + } + + /** + * Set Bullish Rejection Bar Arrow Code ... + * + * @param value: Integer ... + */ + void BullishRejectionBarArrow(int value) + { + // + mBullishRejectionBarArrow = value; + } + + /** + * Get Bullish Rejection Bar Color ... + * + * @return ( color ) + */ + color BullishRejectionBarColor() + { + return mBullishRejectionBarColor; + } + + /** + * Set Bullish Rejection Bar Color ... + * + * @param value: Color ... + */ + void BullishRejectionBarColor(color value) + { + mBullishRejectionBarColor = value; + } + + // + // Bearish Rejection Bar ... + + /** + * Get Bearish Rejection Bar Width ... + * + * @return ( int ) + */ + int BearishRejectionBarWidth() + { + return mBearishRejectionBarWidth; + } + + /** + * Set Bearish Rejection Bar Width ... + * + * @param value: Integer ... + */ + void BearishRejectionBarWidth(int value) + { + // + if (value < 1) + { + value = 1; + } + + // + mBearishRejectionBarWidth = value; + } + + /** + * Get Bearish Rejection Bar Arrow Code ... + * + * @return ( int ) + */ + int BearishRejectionBarArrow() + { + return mBearishRejectionBarArrow; + } + + /** + * Set Bearish Rejection Bar Arrow Code ... + * + * @param value: Integer ... + */ + void BearishRejectionBarArrow(int value) + { + // + mBearishRejectionBarArrow = value; + } + + /** + * Get Bearish Rejection Bar Color ... + * + * @return ( color ) + */ + color BearishRejectionBarColor() + { + return mBearishRejectionBarColor; + } + + /** + * Set Bearish Rejection Bar Color ... + * + * @param value: Color ... + */ + void BearishRejectionBarColor(color value) + { + mBearishRejectionBarColor = value; + } + + // + // Supply Zone ... + + /** + * Get Fill Supply Zone ... + * + * @return ( bool ) + */ + bool SupplyZoneFill() + { + return mSupplyZoneFill; + } + + /** + * Set Fill Supply Zone ... + * + * @param value: Boolean ... + */ + void SupplyZoneFill(bool value) + { + mSupplyZoneFill = value; + } + + /** + * Get Supply Zone Width ... + * + * @return ( int ) + */ + int SupplyZoneWidth() + { + return mSupplyZoneWidth; + } + + /** + * Set Supply Zone Width ... + * + * @param value: Integer ... + */ + void SupplyZoneWidth(int value) + { + // + if (value < 1) + { + value = 1; + } + + // + mSupplyZoneWidth = value; + } + + /** + * Get Supply Zone Color ... + * + * @return ( color ) + */ + color SupplyZoneColor() + { + return mSupplyZoneColor; + } + + /** + * Set Supply Zone Color ... + * + * @param value: Color ... + */ + void SupplyZoneColor(color value) + { + mSupplyZoneColor = value; + } + + /** + * Get Supply Zone Style ... + * + * @return ( ENUM_LINE_STYLE ) + */ + ENUM_LINE_STYLE SupplyZoneStyle() + { + return mSupplyZoneStyle; + } + + /** + * Set Supply Zone Style ... + * + * @param value: ENUM_LINE_STYLE member ... + */ + void SupplyZoneStyle(ENUM_LINE_STYLE value) + { + mSupplyZoneStyle = value; + } + + // + // Demand Zone ... + + /** + * Get Fill Demand Zone ... + * + * @return ( bool ) + */ + bool DemandZoneFill() + { + return mDemandZoneFill; + } + + /** + * Set Fill Demand Zone ... + * + * @param value: Boolean ... + */ + void DemandZoneFill(bool value) + { + mDemandZoneFill = value; + } + + /** + * Get Demand Zone Width ... + * + * @return ( int ) + */ + int DemandZoneWidth() + { + return mDemandZoneWidth; + } + + /** + * Set Demand Zone Width ... + * + * @param value: Integer ... + */ + void DemandZoneWidth(int value) + { + // + if (value < 1) + { + value = 1; + } + + // + mDemandZoneWidth = value; + } + + /** + * Get Demand Zone Color ... + * + * @return ( color ) + */ + color DemandZoneColor() + { + return mDemandZoneColor; + } + + /** + * Set Demand Zone Color ... + * + * @param value: Color ... + */ + void DemandZoneColor(color value) + { + mDemandZoneColor = value; + } + + /** + * Get Demand Zone Style ... + * + * @return ( ENUM_LINE_STYLE ) + */ + ENUM_LINE_STYLE DemandZoneStyle() + { + return mDemandZoneStyle; + } + + /** + * Set Demand Zone Style ... + * + * @param value: ENUM_LINE_STYLE member ... + */ + void DemandZoneStyle(ENUM_LINE_STYLE value) + { + mDemandZoneStyle = value; + } + + // + // Resistance Zone ... + + /** + * Get Fill Resistance Zone ... + * + * @return ( bool ) + */ + bool ResistanceZoneFill() + { + return mResistanceZoneFill; + } + + /** + * Set Fill Resistance Zone ... + * + * @param value: Boolean ... + */ + void ResistanceZoneFill(bool value) + { + mResistanceZoneFill = value; + } + + /** + * Get Resistance Zone Width ... + * + * @return ( int ) + */ + int ResistanceZoneWidth() + { + return mResistanceZoneWidth; + } + + /** + * Set Resistance Zone Width ... + * + * @param value: Integer ... + */ + void ResistanceZoneWidth(int value) + { + // + if (value < 1) + { + value = 1; + } + + // + mResistanceZoneWidth = value; + } + + /** + * Get Resistance Zone Color ... + * + * @return ( color ) + */ + color ResistanceZoneColor() + { + return mResistanceZoneColor; + } + + /** + * Set Resistance Zone Color ... + * + * @param value: Color ... + */ + void ResistanceZoneColor(color value) + { + mResistanceZoneColor = value; + } + + /** + * Get Resistance Zone Style ... + * + * @return ( ENUM_LINE_STYLE ) + */ + ENUM_LINE_STYLE ResistanceZoneStyle() + { + return mResistanceZoneStyle; + } + + /** + * Set Resistance Zone Style ... + * + * @param value: ENUM_LINE_STYLE member ... + */ + void ResistanceZoneStyle(ENUM_LINE_STYLE value) + { + mResistanceZoneStyle = value; + } + + // + // Support Zone ... + + /** + * Get Fill Support Zone ... + * + * @return ( bool ) + */ + bool SupportZoneFill() + { + return mSupportZoneFill; + } + + /** + * Set Fill Support Zone ... + * + * @param value: Boolean ... + */ + void SupportZoneFill(bool value) + { + mSupportZoneFill = value; + } + + /** + * Get Support Zone Width ... + * + * @return ( int ) + */ + int SupportZoneWidth() + { + return mSupportZoneWidth; + } + + /** + * Set Support Zone Width ... + * + * @param value: Integer ... + */ + void SupportZoneWidth(int value) + { + // + if (value < 1) + { + value = 1; + } + + // + mSupportZoneWidth = value; + } + + /** + * Get Support Zone Color ... + * + * @return ( color ) + */ + color SupportZoneColor() + { + return mSupportZoneColor; + } + + /** + * Set Support Zone Color ... + * + * @param value: Color ... + */ + void SupportZoneColor(color value) + { + mSupportZoneColor = value; + } + + /** + * Get Support Zone Style ... + * + * @return ( ENUM_LINE_STYLE ) + */ + ENUM_LINE_STYLE SupportZoneStyle() + { + return mSupportZoneStyle; + } + + /** + * Set Support Zone Style ... + * + * @param value: ENUM_LINE_STYLE member ... + */ + void SupportZoneStyle(ENUM_LINE_STYLE value) + { + mSupportZoneStyle = value; + } + + // + // Bullish Order Block ... + + /** + * Get Fill Bullish Order Block ... + * + * @return ( bool ) + */ + bool BullishOrderBlockFill() + { + return mBullishOrderBlockFill; + } + + /** + * Set Fill Bullish Order Block ... + * + * @param value: Boolean ... + */ + void BullishOrderBlockFill(bool value) + { + mBullishOrderBlockFill = value; + } + + /** + * Get Bullish Order Block Width ... + * + * @return ( int ) + */ + int BullishOrderBlockWidth() + { + return mBullishOrderBlockWidth; + } + + /** + * Set Bullish Order Block Width ... + * + * @param value: Integer ... + */ + void BullishOrderBlockWidth(int value) + { + // + if (value < 1) + { + value = 1; + } + + // + mBullishOrderBlockWidth = value; + } + + /** + * Get Bullish Order Block Color ... + * + * @return ( color ) + */ + color BullishOrderBlockColor() + { + return mBullishOrderBlockColor; + } + + /** + * Set Bullish Order Block Color ... + * + * @param value: Color ... + */ + void BullishOrderBlockColor(color value) + { + mBullishOrderBlockColor = value; + } + + /** + * Get Bullish Order Block Style ... + * + * @return ( ENUM_LINE_STYLE ) + */ + ENUM_LINE_STYLE BullishOrderBlockStyle() + { + return mBullishOrderBlockStyle; + } + + /** + * Set Bullish Order Block Style ... + * + * @param value: ENUM_LINE_STYLE member ... + */ + void BullishOrderBlockStyle(ENUM_LINE_STYLE value) + { + mBullishOrderBlockStyle = value; + } + + // + // Bearish Order Block ... + + /** + * Get Fill Bearish Order Block ... + * + * @return ( bool ) + */ + bool BearishOrderBlockFill() + { + return mBearishOrderBlockFill; + } + + /** + * Set Fill Bearish Order Block ... + * + * @param value: Boolean ... + */ + void BearishOrderBlockFill(bool value) + { + mBearishOrderBlockFill = value; + } + + /** + * Get Bearish Order Block Width ... + * + * @return ( int ) + */ + int BearishOrderBlockWidth() + { + return mBearishOrderBlockWidth; + } + + /** + * Set Bearish Order Block Width ... + * + * @param value: Integer ... + */ + void BearishOrderBlockWidth(int value) + { + // + if (value < 1) + { + value = 1; + } + + // + mBearishOrderBlockWidth = value; + } + + /** + * Get Bearish Order Block Color ... + * + * @return ( color ) + */ + color BearishOrderBlockColor() + { + return mBearishOrderBlockColor; + } + + /** + * Set Bearish Order Block Color ... + * + * @param value: Color ... + */ + void BearishOrderBlockColor(color value) + { + mBearishOrderBlockColor = value; + } + + /** + * Get Bearish Order Block Style ... + * + * @return ( ENUM_LINE_STYLE ) + */ + ENUM_LINE_STYLE BearishOrderBlockStyle() + { + return mBearishOrderBlockStyle; + } + + /** + * Set Bearish Order Block Style ... + * + * @param value: ENUM_LINE_STYLE member ... + */ + void BearishOrderBlockStyle(ENUM_LINE_STYLE value) + { + mBearishOrderBlockStyle = value; + } + + // + // Bullish FVG ... + + /** + * Get Fill Bullish FVG ... + * + * @return ( bool ) + */ + bool BullishFVGFill() + { + return mBullishFVGFill; + } + + /** + * Set Fill Bullish FVG ... + * + * @param value: Boolean ... + */ + void BullishFVGFill(bool value) + { + mBullishFVGFill = value; + } + + /** + * Get Bullish FVG Width ... + * + * @return ( int ) + */ + int BullishFVGWidth() + { + return mBullishFVGWidth; + } + + /** + * Set Bullish FVG Width ... + * + * @param value: Integer ... + */ + void BullishFVGWidth(int value) + { + // + if (value < 1) + { + value = 1; + } + + // + mBullishFVGWidth = value; + } + + /** + * Get Bullish FVG Color ... + * + * @return ( color ) + */ + color BullishFVGColor() + { + return mBullishFVGColor; + } + + /** + * Set Bullish FVG Color ... + * + * @param value: Color ... + */ + void BullishFVGColor(color value) + { + mBullishFVGColor = value; + } + + /** + * Get Bullish FVG Style ... + * + * @return ( ENUM_LINE_STYLE ) + */ + ENUM_LINE_STYLE BullishFVGStyle() + { + return mBullishFVGStyle; + } + + /** + * Set Bullish FVG Style ... + * + * @param value: ENUM_LINE_STYLE member ... + */ + void BullishFVGStyle(ENUM_LINE_STYLE value) + { + mBullishFVGStyle = value; + } + + // + // Bearish FVG ... + + /** + * Get Fill Bearish FVG ... + * + * @return ( bool ) + */ + bool BearishFVGFill() + { + return mBearishFVGFill; + } + + /** + * Set Fill Bearish FVG ... + * + * @param value: Boolean ... + */ + void BearishFVGFill(bool value) + { + mBearishFVGFill = value; + } + + /** + * Get Bearish FVG Width ... + * + * @return ( int ) + */ + int BearishFVGWidth() + { + return mBearishFVGWidth; + } + + /** + * Set Bearish FVG Width ... + * + * @param value: Integer ... + */ + void BearishFVGWidth(int value) + { + // + if (value < 1) + { + value = 1; + } + + // + mBearishFVGWidth = value; + } + + /** + * Get Bearish FVG Color ... + * + * @return ( color ) + */ + color BearishFVGColor() + { + return mBearishFVGColor; + } + + /** + * Set Bearish FVG Color ... + * + * @param value: Color ... + */ + void BearishFVGColor(color value) + { + mBearishFVGColor = value; + } + + /** + * Get Bearish FVG Style ... + * + * @return ( ENUM_LINE_STYLE ) + */ + ENUM_LINE_STYLE BearishFVGStyle() + { + return mBearishFVGStyle; + } + + /** + * Set Bearish FVG Style ... + * + * @param value: ENUM_LINE_STYLE member ... + */ + void BearishFVGStyle(ENUM_LINE_STYLE value) + { + mBearishFVGStyle = value; + } + + // + // Virtuals ... + + /** + * Apply Default Configurations ... + */ + virtual void Default() + { + // + // Apply Default Props ... + + // + Prefix(NULL); + ChartIdentification(0); + SubWindowIdentification(0); + + // + BarWidth(1); + BarBearishColor(clrRed); + BarBullishColor(clrLime); + BarFillBody(false); + BarFillHighShadow(false); + BarFillLowShadow(false); + BarBodyStyle(STYLE_DOT); + BarLowShadowStyle(STYLE_DOT); + BarHighShadowStyle(STYLE_DOT); + + // + int arrowWidth = 1; + + // + SwingLowArrow(108); + SwingLowColor(clrAqua); + SwingLowWidth(arrowWidth); + + // + SwingHighArrow(108); + SwingHighWidth(arrowWidth); + SwingHighColor(clrMagenta); + + // + arrowWidth++; + + // + BullishMomentumBarArrow(225); + BullishMomentumBarWidth(arrowWidth); + BullishMomentumBarColor(clrAqua); + + // + BearishMomentumBarArrow(226); + BearishMomentumBarWidth(arrowWidth); + BearishMomentumBarColor(clrMagenta); + + // + arrowWidth++; + + // + BullishRejectionBarArrow(217); + BullishRejectionBarWidth(arrowWidth); + BullishRejectionBarColor(clrAqua); + + // + BearishRejectionBarArrow(218); + BearishRejectionBarWidth(arrowWidth); + BearishRejectionBarColor(clrMagenta); + + // + SupportZoneFill(false); + SupportZoneWidth(1); + SupportZoneStyle(STYLE_DOT); + SupportZoneColor(clrLime); + + // + ResistanceZoneFill(false); + ResistanceZoneWidth(1); + ResistanceZoneStyle(STYLE_DOT); + ResistanceZoneColor(clrRed); + + // + SupplyZoneFill(false); + SupplyZoneWidth(1); + SupplyZoneStyle(STYLE_DOT); + SupplyZoneColor(clrRed); + + // + DemandZoneFill(false); + DemandZoneWidth(1); + DemandZoneStyle(STYLE_DOT); + DemandZoneColor(clrGreen); + + // + BullishOrderBlockFill(false); + BullishOrderBlockWidth(1); + BullishOrderBlockStyle(STYLE_DASHDOT); + BullishOrderBlockColor(clrLime); + + // + BearishOrderBlockFill(false); + BearishOrderBlockWidth(1); + BearishOrderBlockStyle(STYLE_DASHDOT); + BearishOrderBlockColor(clrRed); + + // + BullishFVGFill(false); + BullishFVGWidth(1); + BullishFVGStyle(STYLE_DOT); + BullishFVGColor(clrLime); + + // + BearishFVGFill(false); + BearishFVGWidth(1); + BearishFVGStyle(STYLE_DOT); + BearishFVGColor(clrRed); + + // + // Add Default TickZone Specs ... + bool isSpecsInited = false; + bool fillTickZone = false; + XTickZoneLevelSpecs specs10; + isSpecsInited = specs10.Init( + 10, + clrWhite, + clrWhite, + fillTickZone // + ); + if (isSpecsInited) + { + AddTickZoneLevelSpecs(specs10); + } + + // + XTickZoneLevelSpecs specs20; + isSpecsInited = specs20.Init( + 20, + clrOrange, + clrOrange, + fillTickZone // + ); + if (isSpecsInited) + { + AddTickZoneLevelSpecs(specs20); + } + + // + XTickZoneLevelSpecs specs30; + isSpecsInited = specs30.Init( + 30, + clrOrange, + clrOrange, + fillTickZone // + ); + if (isSpecsInited) + { + AddTickZoneLevelSpecs(specs30); + } + + // + XTickZoneLevelSpecs specs40; + isSpecsInited = specs40.Init( + 40, + clrOrange, + clrOrange, + fillTickZone // + ); + if (isSpecsInited) + { + AddTickZoneLevelSpecs(specs40); + } + + // + XTickZoneLevelSpecs specs50; + isSpecsInited = specs50.Init( + 50, + clrYellow, + clrYellow, + fillTickZone // + ); + if (isSpecsInited) + { + AddTickZoneLevelSpecs(specs50); + } + + // + XTickZoneLevelSpecs specs60; + isSpecsInited = specs60.Init( + 60, + clrYellow, + clrYellow, + fillTickZone // + ); + if (isSpecsInited) + { + AddTickZoneLevelSpecs(specs60); + } + + // + XTickZoneLevelSpecs specs70; + isSpecsInited = specs70.Init( + 70, + clrYellow, + clrYellow, + fillTickZone // + ); + if (isSpecsInited) + { + AddTickZoneLevelSpecs(specs70); + } + + // + XTickZoneLevelSpecs specs80; + isSpecsInited = specs80.Init( + 80, + clrRed, + clrRed, + fillTickZone // + ); + if (isSpecsInited) + { + AddTickZoneLevelSpecs(specs80); + } + + // + XTickZoneLevelSpecs specs90; + isSpecsInited = specs90.Init( + 90, + clrRed, + clrRed, + fillTickZone // + ); + if (isSpecsInited) + { + AddTickZoneLevelSpecs(specs90); + } + + // + XTickZoneLevelSpecs specs100; + isSpecsInited = specs100.Init( + 100, + clrRed, + clrRed, + fillTickZone // + ); + if (isSpecsInited) + { + AddTickZoneLevelSpecs(specs100); + } + + // + } + + // + // Object Creators ... + + // + // Swings ... + + /** + * Create Swing High Object ... + * + * @param swing: XCSwing instance ... + * @param object: XCSwingHighObject pointer ... + * + * @return ( bool ) + */ + bool CreateSwingHigh( + XCSwing &swing, + XCSwingHighObject *&object // + ) + { + // + bool result = false; + + // + object = NULL; + + // + result = + swing.IsValid() && + swing.IsSwingHigh(); + if (!result) + { + return result; + } + + // + string prefix = Prefix(); + long chartID = ChartIdentification(); + int window = SubWindowIdentification(); + + // + int arrow = SwingHighArrow(); + int width = SwingHighWidth(); + color crl = SwingHighColor(); + + // + object = new XCSwingHighObject(); + result = object.Create( + chartID, + window, + arrow, + swing, + prefix // + ); + + // + if (!result) + { + return result; + } + + // + object.ArrowColor(crl); + object.ArrowWidth(width); + object.ArrowAnchor(ANCHOR_BOTTOM); + + // + return result; + } + + /** + * Create Swing Low Object ... + * + * @param swing: XCSwing instance ... + * @param object: XCSwingLowObject pointer ... + * + * @return ( bool ) + */ + bool CreateSwingLow( + XCSwing &swing, + XCSwingLowObject *&object // + ) + { + // + bool result = false; + + // + object = NULL; + + // + result = + swing.IsValid() && + swing.IsSwingLow(); + if (!result) + { + return result; + } + + // + string prefix = Prefix(); + long chartID = ChartIdentification(); + int window = SubWindowIdentification(); + + // + int arrow = SwingLowArrow(); + int width = SwingLowWidth(); + color crl = SwingLowColor(); + + // + object = new XCSwingLowObject(); + result = object.Create( + chartID, + window, + arrow, + swing, + prefix // + ); + + // + if (!result) + { + return result; + } + + // + object.ArrowColor(crl); + object.ArrowWidth(width); + object.ArrowAnchor(ANCHOR_TOP); + + // + return result; + } + + // + // Momentum Bars ... + + /** + * Create Bullish Momentum Bar Object ... + * + * @param momentumBar: XCMomentumBar instance ... + * @param object: XCBullishMomentumObject pointer ... + * + * @return ( bool ) + */ + bool CreateBullishMomentumBar( + XCMomentumBar &momentumBar, + XCBullishMomentumBarObject *&object // + ) + { + // + bool result = false; + + // + object = NULL; + + // + result = + momentumBar.IsValid() && + momentumBar.IsBullish(); + if (!result) + { + return result; + } + + // + string prefix = Prefix(); + long chartID = ChartIdentification(); + int window = SubWindowIdentification(); + + // + int arrow = BullishMomentumBarArrow(); + int width = BullishMomentumBarWidth(); + color crl = BullishMomentumBarColor(); + + // + object = new XCBullishMomentumBarObject(); + result = object.Create( + chartID, + window, + arrow, + momentumBar, + prefix // + ); + + // + if (!result) + { + return result; + } + + // + object.ArrowColor(crl); + object.ArrowWidth(width); + object.ArrowAnchor(ANCHOR_TOP); + + // + return result; + } + + /** + * Create Bearish Momentum Bar Object ... + * + * @param momentumBar: XCMomentumBar instance ... + * @param object: XCBearishMomentumObject pointer ... + * + * @return ( bool ) + */ + bool CreateBearishMomentumBar( + XCMomentumBar &momentumBar, + XCBearishMomentumBarObject *&object // + ) + { + // + bool result = false; + + // + object = NULL; + + // + result = + momentumBar.IsValid() && + momentumBar.IsBearish(); + if (!result) + { + return result; + } + + // + string prefix = Prefix(); + long chartID = ChartIdentification(); + int window = SubWindowIdentification(); + + // + int arrow = BearishMomentumBarArrow(); + int width = BearishMomentumBarWidth(); + color crl = BearishMomentumBarColor(); + + // + object = new XCBearishMomentumBarObject(); + result = object.Create( + chartID, + window, + arrow, + momentumBar, + prefix // + ); + + // + if (!result) + { + return result; + } + + // + object.ArrowColor(crl); + object.ArrowWidth(width); + object.ArrowAnchor(ANCHOR_BOTTOM); + + // + return result; + } + + // + // Rejection Bars ... + + /** + * Create Bullish Rejection Bar Object ... + * + * @param momentumBar: XCRejectionBar instance ... + * @param object: XCBullishRejectionObject pointer ... + * + * @return ( bool ) + */ + bool CreateBullishRejectionBar( + XCRejectionBar &rejectionBar, + XCBullishRejectionBarObject *&object // + ) + { + // + bool result = false; + + // + object = NULL; + + // + result = + rejectionBar.IsValid() && + rejectionBar.IsBullish(); + if (!result) + { + return result; + } + + // + string prefix = Prefix(); + long chartID = ChartIdentification(); + int window = SubWindowIdentification(); + + // + int arrow = BullishRejectionBarArrow(); + int width = BullishRejectionBarWidth(); + color crl = BullishRejectionBarColor(); + + // + object = new XCBullishRejectionBarObject(); + result = object.Create( + chartID, + window, + arrow, + rejectionBar, + prefix // + ); + + // + if (!result) + { + return result; + } + + // + object.ArrowColor(crl); + object.ArrowWidth(width); + object.ArrowAnchor(ANCHOR_TOP); + + // + return result; + } + + /** + * Create Bearish Rejection Bar Object ... + * + * @param rejectionBar: XCRejectionBar instance ... + * @param object: XCBearishRejectionObject pointer ... + * + * @return ( bool ) + */ + bool CreateBearishRejectionBar( + XCRejectionBar &rejectionBar, + XCBearishRejectionBarObject *&object // + ) + { + // + bool result = false; + + // + object = NULL; + + // + result = + rejectionBar.IsValid() && + rejectionBar.IsBearish(); + if (!result) + { + return result; + } + + // + string prefix = Prefix(); + long chartID = ChartIdentification(); + int window = SubWindowIdentification(); + + // + int arrow = BearishRejectionBarArrow(); + int width = BearishRejectionBarWidth(); + color crl = BearishRejectionBarColor(); + + // + object = new XCBearishRejectionBarObject(); + result = object.Create( + chartID, + window, + arrow, + rejectionBar, + prefix // + ); + + // + if (!result) + { + return result; + } + + // + object.ArrowColor(crl); + object.ArrowWidth(width); + object.ArrowAnchor(ANCHOR_BOTTOM); + + // + return result; + } + + // + // Support and Resistance ... + + /** + * Create Support Object ... + * + * @param zone: XCSupportZone instance ... + * @param object: XCSupportZoneObject pointer ... + * + * @return ( bool ) + */ + bool CreateSupportZone( + XCSupportZone &zone, + XCSupportZoneObject *&object // + ) + { + // + bool result = false; + + // + object = NULL; + + // + result = + zone.IsValid(); + if (!result) + { + return result; + } + + // + string prefix = Prefix(); + long chartID = ChartIdentification(); + int window = SubWindowIdentification(); + + // + bool fill = SupportZoneFill(); + int width = SupportZoneWidth(); + color crl = SupportZoneColor(); + ENUM_LINE_STYLE style = SupportZoneStyle(); + + // + object = new XCSupportZoneObject(); + result = object.Create( + chartID, + window, + zone, + prefix // + ); + + // + if (!result) + { + return result; + } + + // + object.ZoneFill(fill); + object.ZoneColor(crl); + object.ZoneWidth(width); + object.ZoneStyle(style); + + // + return result; + } + + /** + * Create Resistance Object ... + * + * @param zone: XCResistanceZone instance ... + * @param object: XCResistanceZoneObject pointer ... + * + * @return ( bool ) + */ + bool CreateResistanceZone( + XCResistanceZone &zone, + XCResistanceZoneObject *&object // + ) + { + // + bool result = false; + + // + object = NULL; + + // + result = + zone.IsValid(); + if (!result) + { + return result; + } + + // + string prefix = Prefix(); + long chartID = ChartIdentification(); + int window = SubWindowIdentification(); + + // + bool fill = ResistanceZoneFill(); + int width = ResistanceZoneWidth(); + color crl = ResistanceZoneColor(); + ENUM_LINE_STYLE style = ResistanceZoneStyle(); + + // + object = new XCResistanceZoneObject(); + result = object.Create( + chartID, + window, + zone, + prefix // + ); + + // + if (!result) + { + return result; + } + + // + object.ZoneFill(fill); + object.ZoneColor(crl); + object.ZoneWidth(width); + object.ZoneStyle(style); + + // + return result; + } + + // + // Supply and Demand Zones ... + + /** + * Create Supply Object ... + * + * @param zone: XCSupplyZone instance ... + * @param object: XCSupplyZoneObject pointer ... + * + * @return ( bool ) + */ + bool CreateSupplyZone( + XCSupplyZone &zone, + XCSupplyZoneObject *&object // + ) + { + // + bool result = false; + + // + object = NULL; + + // + result = + zone.IsValid(); + if (!result) + { + return result; + } + + // + string prefix = Prefix(); + long chartID = ChartIdentification(); + int window = SubWindowIdentification(); + + // + bool fill = SupplyZoneFill(); + int width = SupplyZoneWidth(); + color crl = SupplyZoneColor(); + ENUM_LINE_STYLE style = SupplyZoneStyle(); + + // + object = new XCSupplyZoneObject(); + result = object.Create( + chartID, + window, + zone, + prefix // + ); + + // + if (!result) + { + return result; + } + + // + object.ZoneFill(fill); + object.ZoneColor(crl); + object.ZoneWidth(width); + object.ZoneStyle(style); + + // + return result; + } + + /** + * Create Demand Object ... + * + * @param zone: XCDemandZone instance ... + * @param object: XCDemandZoneObject pointer ... + * + * @return ( bool ) + */ + bool CreateDemandZone( + XCDemandZone &zone, + XCDemandZoneObject *&object // + ) + { + // + bool result = false; + + // + object = NULL; + + // + result = + zone.IsValid(); + if (!result) + { + return result; + } + + // + string prefix = Prefix(); + long chartID = ChartIdentification(); + int window = SubWindowIdentification(); + + // + bool fill = DemandZoneFill(); + int width = DemandZoneWidth(); + color crl = DemandZoneColor(); + ENUM_LINE_STYLE style = DemandZoneStyle(); + + // + object = new XCDemandZoneObject(); + result = object.Create( + chartID, + window, + zone, + prefix // + ); + + // + if (!result) + { + return result; + } + + // + object.ZoneFill(fill); + object.ZoneColor(crl); + object.ZoneWidth(width); + object.ZoneStyle(style); + + // + return result; + } + + // + // Order Blocks ... + + /** + * Create Bullish Order Block Object ... + * + * @param zone: XCOrderBlock instance ... + * @param object: XCBullishOrderBlockObject pointer ... + * + * @return ( bool ) + */ + bool CreateBullishOrderBlock( + XCOrderBlock &zone, + XCBullishOrderBlockObject *&object // + ) + { + // + bool result = false; + + // + object = NULL; + + // + result = + zone.IsValid() && + zone.IsBullish(); + if (!result) + { + return result; + } + + // + string prefix = Prefix(); + long chartID = ChartIdentification(); + int window = SubWindowIdentification(); + + // + bool fill = BullishOrderBlockFill(); + int width = BullishOrderBlockWidth(); + color crl = BullishOrderBlockColor(); + ENUM_LINE_STYLE style = BullishOrderBlockStyle(); + + // + object = new XCBullishOrderBlockObject(); + result = object.Create( + chartID, + window, + zone, + prefix // + ); + + // + if (!result) + { + return result; + } + + // + object.ZoneFill(fill); + object.ZoneColor(crl); + object.ZoneWidth(width); + object.ZoneStyle(style); + + // + return result; + } + + /** + * Create Bearish Order Block Object ... + * + * @param zone: XCOrderBlock instance ... + * @param object: XCBearishOrderBlockObject pointer ... + * + * @return ( bool ) + */ + bool CreateBearishOrderBlock( + XCOrderBlock &zone, + XCBearishOrderBlockObject *&object // + ) + { + // + bool result = false; + + // + object = NULL; + + // + result = + zone.IsValid() && + zone.IsBearish(); + if (!result) + { + return result; + } + + // + string prefix = Prefix(); + long chartID = ChartIdentification(); + int window = SubWindowIdentification(); + + // + bool fill = BearishOrderBlockFill(); + int width = BearishOrderBlockWidth(); + color crl = BearishOrderBlockColor(); + ENUM_LINE_STYLE style = BearishOrderBlockStyle(); + + // + object = new XCBearishOrderBlockObject(); + result = object.Create( + chartID, + window, + zone, + prefix // + ); + + // + if (!result) + { + return result; + } + + // + object.ZoneFill(fill); + object.ZoneColor(crl); + object.ZoneWidth(width); + object.ZoneStyle(style); + + // + return result; + } + + bool CreateOrderBlock( + XCOrderBlock &zone, + XCBaseObject *&object // + ) + { + // + bool result = false; + + // + object = NULL; + + // + result = zone.IsValid(); + if (!result) + { + return result; + } + + // + bool isBullish = zone.IsBullish(); + if (isBullish) + { + // + XCBullishOrderBlockObject *iObj; + result = CreateBullishOrderBlock( + zone, + iObj // + ); + if (result) + { + object = (XCBaseObject *)iObj; + } + } + else + { + // + XCBearishOrderBlockObject *iObj; + result = CreateBearishOrderBlock( + zone, + iObj // + ); + if (result) + { + object = (XCBaseObject *)iObj; + } + } + + // + return result; + } + + // + // Fair Value Gaps ... + + /** + * Create Bullish Fair Value Gap Object ... + * + * @param zone: XCFVG instance ... + * @param object: XCBullishOrderBlockObject pointer ... + * + * @return ( bool ) + */ + bool CreateBullishFairValueGap( + XCFVG &zone, + XCBullishFairValueGapObject *&object // + ) + { + // + bool result = false; + + // + result = zone.IsValid() && + zone.IsBullish(); + if (!result) + { + return result; + } + + // + string prefix = Prefix(); + long chartID = ChartIdentification(); + int window = SubWindowIdentification(); + + // + bool fill = BullishFVGFill(); + int width = BullishFVGWidth(); + color crl = BullishFVGColor(); + ENUM_LINE_STYLE style = BullishFVGStyle(); + + // + object = new XCBullishFairValueGapObject(); + result = object.Create( + chartID, + window, + zone, + prefix // + ); + + // + if (!result) + { + return result; + } + + // + object.ZoneFill(fill); + object.ZoneColor(crl); + object.ZoneWidth(width); + object.ZoneStyle(style); + + // + return result; + } + + /** + * Create Bearish Fair Value Gap Object ... + * + * @param zone: XCFVG instance ... + * @param object: XCBearishOrderBlockObject pointer ... + * + * @return ( bool ) + */ + bool CreateBearishFairValueGap( + XCFVG &zone, + XCBearishFairValueGapObject *&object // + ) + { + // + bool result = false; + + // + result = zone.IsValid() && + zone.IsBearish(); + if (!result) + { + return result; + } + + // + string prefix = Prefix(); + long chartID = ChartIdentification(); + int window = SubWindowIdentification(); + + // + bool fill = BearishFVGFill(); + int width = BearishFVGWidth(); + color crl = BearishFVGColor(); + ENUM_LINE_STYLE style = BearishFVGStyle(); + + // + object = new XCBearishFairValueGapObject(); + result = object.Create( + chartID, + window, + zone, + prefix // + ); + + // + if (!result) + { + return result; + } + + // + object.ZoneFill(fill); + object.ZoneColor(crl); + object.ZoneWidth(width); + object.ZoneStyle(style); + + // + return result; + } + + bool CreateFairValueGap( + XCFVG &zone, + XCBaseObject *&object // + ) + { + // + bool result = false; + + // + object = NULL; + + // + result = zone.IsValid(); + if (!result) + { + return result; + } + + // + bool isBullish = zone.IsBullish(); + if (isBullish) + { + // + XCBullishFairValueGapObject *iObj; + result = CreateBullishFairValueGap( + zone, + iObj // + ); + if (result) + { + object = (XCBaseObject *)iObj; + } + } + else + { + // + XCBearishFairValueGapObject *iObj; + result = CreateBearishFairValueGap( + zone, + iObj // + ); + if (result) + { + object = (XCBaseObject *)iObj; + } + } + + // + return result; + } + + // + // Ticks Zone ... + + /** + * Add Tick Zone Draw Specifications ... + * + * @param specs: XTickZoneLevelSpecs instance ... + */ + void AddTickZoneLevelSpecs( + XTickZoneLevelSpecs &specs // + ) + { + // + if (!specs.IsValid()) + { + return; + } + + // + bool isExists = false; + int count = ArraySize(mTicksZoneSpecs); + if (IsValidSize(count)) + { + // + for (int i = 0; i < count; i++) + { + // + XTickZoneLevelSpecs iSpec = mTicksZoneSpecs[i]; + + // + isExists = specs.percent == iSpec.percent; + if (isExists) + { + break; + } + } + } + if (isExists) + { + return; + } + + // + AddRef( + specs, + mTicksZoneSpecs // + ); + } + + /** + * Draw Specified Ticker Zone ... + * + * @param zone: XCTicksZone instance Specified Ticker Zone ... + * @param object: XCTicksZoneObject pointer ... + * + * @return ( bool ) + */ + bool CreateTicksZone( + XCTicksZone &zone, + XCTicksZoneObject *&object // + ) + { + // + bool result = false; + + // + object = NULL; + + // + result = zone.IsValid(); + if (!result) + { + return result; + } + + // + string prefix = Prefix(); + long chartID = ChartIdentification(); + int window = SubWindowIdentification(); + + // + object = new XCTicksZoneObject(); + result = object.Create( + chartID, + window, + zone, + mTicksZoneSpecs, + prefix // + ); + + // + if (!result) + { + return result; + } + + // + return result; + } + + /** + * Create Consolidation Zone Object ... + * + * @param zone: XConsolidationZone instance Reference ... + * + * @return ( bool ) + */ + bool CreateConsolidationZone( + XConsolidationZone &zone, + XCConsolidationZoneObject *&object // + ) + { + // + bool result = false; + + // + object = NULL; + + // + result = zone.IsValid(); + if (!result) + { + return result; + } + + // + string prefix = Prefix(); + long chartID = ChartIdentification(); + int window = SubWindowIdentification(); + + // + color czColor = IsBullish(zone.dir) + ? BarBullishColor() + : BarBearishColor(); + + // + object = new XCConsolidationZoneObject(); + result = object.Create( + chartID, + window, + zone, + prefix // + ); + + // + if (result) + { + object.ZoneColor(czColor); + } + + // + return result; + } + + /** + * Create Bar Object ... + * + * @param bar: XOHCL instance Reference ... + * @param object: XCOHCLObject pointer Reference .. + * @param to: Datetime ... + * + * @return ( bool ) + */ + bool CreateBar( + XOHCL &bar, + XCOHCLObject *&object, + datetime to = NULL // + ) + { + // + bool result = false; + + // + object = NULL; + + // + result = bar.IsValid(); + if (!result) + { + return result; + } + + // + to = NormalizeTime(to); + + // + string prefix = Prefix(); + long chartID = ChartIdentification(); + int window = SubWindowIdentification(); + + // + int width = BarWidth(); + + // + color mBullishColor = BarBullishColor(); + color mBearishColor = BarBearishColor(); + + // + bool fillBody = BarFillBody(); + bool fillHighShadow = BarFillHighShadow(); + bool fillLowShadow = BarFillLowShadow(); + + // + ENUM_LINE_STYLE bodyStyle = BarBodyStyle(); + ENUM_LINE_STYLE highShadowStyle = BarHighShadowStyle(); + ENUM_LINE_STYLE lowShadowStyle = BarLowShadowStyle(); + + // + object = new XCOHCLObject(); + result = object.Create( + chartID, + window, + bar, + to, + prefix // + ); + if (result) + { + // + // Apply Styling ... + + // + object.BodyWidth(width); + object.LowShadowWidth(width); + object.HighShadowWidth(width); + + // + object.BodyStyle(bodyStyle); + object.LowShadowStyle(lowShadowStyle); + object.HighShadowStyle(highShadowStyle); + + // + bool isBullish = bar.IsBullish(); + if (isBullish) + { + // + object.BodyColor(mBullishColor); + object.LowShadowColor(mBullishColor); + object.HighShadowColor(mBullishColor); + } + else + { + // + object.BodyColor(mBearishColor); + object.LowShadowColor(mBearishColor); + object.HighShadowColor(mBearishColor); + } + + // + object.BodyFill(fillBody); + object.HighShadowFill(fillHighShadow); + object.LowShadowFill(fillLowShadow); + } + + // + return result; + } + + /** + * Create Bar Arrow Object ... + * + * @param bar: XOHCL instance Reference ... + * @param priceType: ENUM_X_PRICE member ... + * @param arrow: int, Arrow Code ... + * @param clr: color, Arro Color ... + * @param width: int, Arrow Width ... + * @param anchor: ENUM_ARROW_ANCHOR, anchor of Arrow ... + * @param name: string, name of Arrow ... + * + * @return ( bool ) + */ + bool CreateBarArrow( + XOHCL &bar, + XCBarArrowObject *&object, + ENUM_X_PRICE priceType, + int arrow = 159, + color clr = clrYellow, + int width = 3, + ENUM_ARROW_ANCHOR anchor = ANCHOR_BOTTOM, + string name = NULL // + ) + { + // + bool result = false; + + // + object = NULL; + + // + result = bar.IsValid(); + if (!result) + { + return result; + } + + // + string barTag = bar.GetTag(name); + + // + string prefix = Prefix(); + long chartID = ChartIdentification(); + int window = SubWindowIdentification(); + + // + color mBullishColor = BarBullishColor(); + color mBearishColor = BarBearishColor(); + + // + prefix = + (IsValid(prefix) + ? prefix + "_" + : prefix) + + barTag; + + // + object = new XCBarArrowObject(); + result = object + .CreateByBar( + chartID, + prefix, + window, + arrow, + bar, + priceType // + ); + if (result) + { + // + object.ArrowColor(clr); + object.ArrowWidth(width); + } + + // + return result; + } + + /** + * Create Specific Box on Chart ... + * + * @param upper: Double ... + * @param lower: Double ... + * @param from: Datetime ... + * @param to: Datetime ... + * @param clr: Color ... + * @param width: Integer ... + * @param fill: Boolean ... + * @param style: ENUM_LINE_STYLE member ... + * + * @return ( bool ) + */ + bool CreateBox( + XCBoxObject *&object, + string name, + double upper, + double lower, + datetime from, + datetime to, + color clr = clrYellowGreen, + int width = 1, + bool fill = false, + ENUM_LINE_STYLE style = STYLE_SOLID // + ) + { + // + bool result = false; + + // + object = NULL; + + // + to = NormalizeTime(to); + + // + string dateStr = ToFormatString(from) + "|" + ToFormatString(to); + string dateMD5 = ToMD5(dateStr); + if (!IsValid(name)) + { + // + name = "XBox_" + + ToString(upper) + "_" + + ToString(lower) + "_" + + dateMD5; + } + + // + result = + upper > 0 && + lower > 0 && + to > from && + IsValid(to) && + IsValid(name) && + IsValid(from) && + upper > lower; + if (!result) + { + return result; + } + + // + string prefix = Prefix(); + long chartID = ChartIdentification(); + int window = SubWindowIdentification(); + + // + object = new XCBoxObject(); + result = object.Create( + chartID, + window, + name, + upper, + lower, + from, + to, + prefix // + ); + + // + if (!result) + { + return result; + } + + // + object.BoxColor(clr); + object.BoxFill(fill); + object.BoxWidth(width); + object.BoxStyle(style); + + // + return result; + } + + /** + * Create Specific Box on Chart ... + * + * @param box: XBoxZone instance Reference ... + * @param clr: Color ... + * @param width: Integer ... + * @param fill: Boolean ... + * @param style: ENUM_LINE_STYLE member ... + * + * @return ( bool ) + */ + bool DrawBox( + XBoxZone &box, + XCBoxObject *&object // + ) + { + // + bool result = false; + + // + object = NULL; + + // + result = box.IsValid(); + if (!result) + { + return result; + } + + // + int width = 1; + bool fill = false; + color clr = + box.IsBullish() + ? BullishFVGColor() + : BearishFVGColor(); + ENUM_LINE_STYLE style = STYLE_DASHDOTDOT; + string name = box.GetTag(); + + // + result = CreateBox( + object, + name, + box.upper, + box.lower, + box.from, + box.to, + clr, + width, + fill, + style // + ); + + // + return result; + } + + /** + * Create Specific Box on Chart ... + * + * @param box: XBoxZone instance Reference ... + * @param clr: Color ... + * @param width: Integer ... + * @param fill: Boolean ... + * @param style: ENUM_LINE_STYLE member ... + * + * @return ( bool ) + */ + bool CreateBox( + XBoxZone &box, + XCBoxObject *&object, + color clr = clrYellowGreen, + int width = 1, + bool fill = false, + ENUM_LINE_STYLE style = STYLE_SOLID // + ) + { + // + bool result = false; + + // + object = NULL; + + // + result = box.IsValid(); + if (!result) + { + return result; + } + + // + string name = box.GetTag(); + + // + result = CreateBox( + object, + name, + box.upper, + box.lower, + box.from, + box.to, + clr, + width, + fill, + style // + ); + + // + return result; + } + + /** + * Draw Specified Signal ... + * + * @param signal: XSignal instance ... + */ + bool DrawSignal( + XSignal &signal, + XCSignalObject *&object // + ) + { + // + bool result = false; + + // + object = NULL; + + // + result = signal.IsValid(); + if (!result) + { + return result; + } + + // + string prefix = Prefix(); + long chartID = ChartIdentification(); + int window = SubWindowIdentification(); + + // + object = new XCSignalObject(); + result = object.Create( + chartID, + window, + signal, + prefix // + ); + if (!result) + { + return result; + } + + // + object.TPWidth(1); + object.TPColor(clrGreen); + object.TPWidth(STYLE_DOT); + + // + object.SLWidth(1); + object.SLColor(clrRed); + object.SLWidth(STYLE_DOT); + + // + object.TargetWidth(1); + object.TargetColor(clrLightBlue); + object.TargetWidth(STYLE_DOT); + + // + object.EntryWidth(1); + object.EntryColor(clrYellow); + object.EntryWidth(STYLE_DOT); + + // + return result; + } + + /** + * Draw Signal Box ... + * + * @param box: XSignalBox instance Reference ... + * @param objects: XCBaseObject pointer instance Reference ... + * + * @return ( bool ) + */ + bool DrawSignalBox( + XSignalBox &box, + XCBaseObject *&objects[], + color clr = CLR_NONE // + ) + { + // + bool result = false; + + // + Clean(objects); + + // + bool has = false; + bool hasColor = clr != CLR_NONE; + + // + // Order Block ... + if (box.ob.IsValid()) + { + // + XCBoxObject *iObj; + has = DrawBox( + box.ob, + iObj // + ); + if (has) + { + // + iObj.BoxStyle(STYLE_DASH); + + // + if (hasColor) + { + iObj.BoxColor(clr); + } + + // + Add( + (XCBaseObject *)iObj, + objects // + ); + } + } + + // + // Fair Value Gap ... + if (box.fvg.IsValid()) + { + // + XCBoxObject *iObj; + has = DrawBox( + box.fvg, + iObj // + ); + if (has) + { + // + iObj.BoxStyle(STYLE_SOLID); + + // + if (hasColor) + { + iObj.BoxColor(clr); + } + + // + Add( + (XCBaseObject *)iObj, + objects // + ); + } + } + + // + // Sharp Zone ... + if (box.sharp.IsValid()) + { + // + XCBoxObject *iObj; + has = DrawBox( + box.sharp, + iObj // + ); + if (has) + { + // + iObj.BoxStyle(STYLE_DOT); + + // + if (hasColor) + { + iObj.BoxColor(clr); + } + + // + Add( + (XCBaseObject *)iObj, + objects // + ); + } + } + + // + result = HasChild(objects); + + // + return result; + } + + /** + * Draw Specified POI State ... + * + * @param state: XPOIState instance Reference ... + * @param drawnObjects: CArrayObj instance for Holding Drawn Objects ... + * @param drawTicksZone: Boolean ... + * @param ignoreSwingHighs: Boolean ... + * @param ignoreSwingLows: Boolean ... + * @param ignoreSupportZones: Boolean ... + * @param ignoreResistanceZones: Boolean ... + * @param ignoreSupplyZones: Boolean ... + * @param ignoreDemandZones: Boolean ... + * @param ignoreBullishOrderBlocks: Boolean ... + * @param ignoreBearishOrderBlocks: Boolean ... + * @param ignoreBullishFairValueGaps: Boolean ... + * @param ignoreBearishFairValueGaps: Boolean ... + * @param ignoreBullishRejectionBars: Boolean ... + * @param ignoreBearishRejectionBars: Boolean ... + * @param ignoreBullishMomentumBars: Boolean ... + * @param ignoreBearishMomentumBars: Boolean ... + */ + int DrawState( + XPOIState &state, + XCBaseObject *&drawnObjects[], + // + // Bullish ... + bool ignoreSwingLows = false, + bool ignoreDemandZones = false, + bool ignoreSupportZones = false, + bool ignoreBullishSharps = false, + bool ignoreBullishSpikes = false, + bool ignoreBullishPullbacks = false, + bool ignoreBullishMomentums = false, + bool ignoreBullishRejections = false, + bool ignoreBullishOrderBlocks = false, + bool ignoreBullishFairValueGaps = false, + bool ignoreBullishConsolidationZones = false, + // + // Bearish ... + bool ignoreSwingHighs = false, + bool ignoreSupplyZones = false, + bool ignoreResistanceZones = false, + bool ignoreBearishSharps = false, + bool ignoreBearishSpikes = false, + bool ignoreBearishPullbacks = false, + bool ignoreBearishMomentums = false, + bool ignoreBearishRejections = false, + bool ignoreBearishOrderBlocks = false, + bool ignoreBearishFairValueGaps = false, + bool ignoreBearishConsolidationZones = false // + ) + { + // + int result = 0; + + // + if (!state.IsValid() || + !state.HasChild()) + { + return result; + } + + // + Clean(drawnObjects); + + // + // Swings ... + + // + // SwingHighs ... + if (!ignoreSwingHighs) + { + // + int count = state.CountSwingHighs(); + if (IsValidSize(count)) + { + // + for (int i = 0; i < count; i++) + { + // + XCSwing *iSwing = state.swingHighs[i]; + XCSwingHighObject *iObj; + + // + bool isCreated = CreateSwingHigh( + iSwing, + iObj // + ); + if (isCreated) + { + // + Add( + (XCBaseObject *)iObj, + drawnObjects // + ); + } + } + } + } + + // + // SwingLows ... + if (!ignoreSwingLows) + { + // + int count = state.CountSwingLows(); + if (IsValidSize(count)) + { + // + for (int i = 0; i < count; i++) + { + // + XCSwing *iSwing = state.swingLows[i]; + XCSwingLowObject *iObj; + + // + bool isCreated = CreateSwingLow( + iSwing, + iObj // + ); + if (isCreated) + { + // + Add( + (XCBaseObject *)iObj, + drawnObjects // + ); + } + } + } + } + + // + // Support / Resistance ... + + // + // SupportZones ... + if (!ignoreSupportZones) + { + // + int count = state.CountSupportZones(); + if (IsValidSize(count)) + { + // + for (int i = 0; i < count; i++) + { + // + XCSupportZone *iZone = state.supportZones[i]; + XCSupportZoneObject *iObj; + + // + bool isCreated = CreateSupportZone( + iZone, + iObj // + ); + if (isCreated) + { + // + Add( + (XCBaseObject *)iObj, + drawnObjects // + ); + } + } + } + } + + // + // ResistanceZones ... + if (!ignoreResistanceZones) + { + // + int count = state.CountResistanceZones(); + if (IsValidSize(count)) + { + // + for (int i = 0; i < count; i++) + { + // + XCResistanceZone *iZone = state.resistanceZones[i]; + XCResistanceZoneObject *iObj; + + // + bool isCreated = CreateResistanceZone( + iZone, + iObj // + ); + if (isCreated) + { + // + Add( + (XCBaseObject *)iObj, + drawnObjects // + ); + } + } + } + } + + // + // Supply / Demand ... + + // + // SupplyZones ... + if (!ignoreSupplyZones) + { + // + int count = state.CountSupplyZones(); + if (IsValidSize(count)) + { + // + for (int i = 0; i < count; i++) + { + // + XCSupplyZone *iZone = state.supplyZones[i]; + XCSupplyZoneObject *iObj; + + // + bool isCreated = CreateSupplyZone( + iZone, + iObj // + ); + if (isCreated) + { + // + Add( + (XCBaseObject *)iObj, + drawnObjects // + ); + } + } + } + } + + // + // DemandZones ... + if (!ignoreDemandZones) + { + // + int count = state.CountDemandZones(); + if (IsValidSize(count)) + { + // + for (int i = 0; i < count; i++) + { + // + XCDemandZone *iZone = state.demandZones[i]; + XCDemandZoneObject *iObj; + + // + bool isCreated = CreateDemandZone( + iZone, + iObj // + ); + if (isCreated) + { + // + Add( + (XCBaseObject *)iObj, + drawnObjects // + ); + } + } + } + } + + // + // Order Blocks ... + + // + // BullishOrderBlocks ... + if (!ignoreBullishOrderBlocks) + { + // + int count = state.CountBullishOrderBlocks(); + if (IsValidSize(count)) + { + // + for (int i = 0; i < count; i++) + { + // + XCOrderBlock *iZone = state.bullishOrderBlocks[i]; + XCBullishOrderBlockObject *iObj; + + // + bool isCreated = CreateBullishOrderBlock( + iZone, + iObj // + ); + if (isCreated) + { + // + Add( + (XCBaseObject *)iObj, + drawnObjects // + ); + } + } + } + } + + // + // BearishOrderBlocks ... + if (!ignoreBearishOrderBlocks) + { + // + int count = state.CountBearishOrderBlocks(); + if (IsValidSize(count)) + { + // + for (int i = 0; i < count; i++) + { + // + XCOrderBlock *iZone = state.bearishOrderBlocks[i]; + XCBearishOrderBlockObject *iObj; + + // + bool isCreated = CreateBearishOrderBlock( + iZone, + iObj // + ); + if (isCreated) + { + // + Add( + (XCBaseObject *)iObj, + drawnObjects // + ); + } + } + } + } + + // + // Fair Value Gaps ... + + // + // BullishFairValueGaps ... + if (!ignoreBullishFairValueGaps) + { + // + int count = state.CountBullishFairValueGaps(); + if (IsValidSize(count)) + { + // + for (int i = 0; i < count; i++) + { + // + XCFVG *iZone = state.bullishFairValueGaps[i]; + XCBullishFairValueGapObject *iObj; + + // + bool isCreated = CreateBullishFairValueGap( + iZone, + iObj // + ); + if (isCreated) + { + // + Add( + (XCBaseObject *)iObj, + drawnObjects // + ); + } + } + } + } + + // + // BearishFairValueGaps ... + if (!ignoreBearishFairValueGaps) + { + // + int count = state.CountBearishFairValueGaps(); + if (IsValidSize(count)) + { + // + for (int i = 0; i < count; i++) + { + // + XCFVG *iZone = state.bearishFairValueGaps[i]; + XCBearishFairValueGapObject *iObj; + + // + bool isCreated = CreateBearishFairValueGap( + iZone, + iObj // + ); + if (isCreated) + { + // + Add( + (XCBaseObject *)iObj, + drawnObjects // + ); + } + } + } + } + + // + // Rejections ... + + // + // BullishRejectionBars ... + if (!ignoreBullishRejections) + { + // + int count = state.CountBullishRejections(); + if (IsValidSize(count)) + { + // + for (int i = 0; i < count; i++) + { + // + XCRejectionBar *iBar = state.bullishRejections[i]; + XCBullishRejectionBarObject *iObj; + + // + bool isCreated = CreateBullishRejectionBar( + iBar, + iObj // + ); + if (isCreated) + { + // + Add( + (XCBaseObject *)iObj, + drawnObjects // + ); + } + } + } + } + + // + // BearishRejectionBars ... + if (!ignoreBearishRejections) + { + // + int count = state.CountBearishRejections(); + if (IsValidSize(count)) + { + // + for (int i = 0; i < count; i++) + { + // + XCRejectionBar *iBar = state.bearishRejections[i]; + XCBearishRejectionBarObject *iObj; + + // + bool isCreated = CreateBearishRejectionBar( + iBar, + iObj // + ); + if (isCreated) + { + // + Add( + (XCBaseObject *)iObj, + drawnObjects // + ); + } + } + } + } + + // + // Momentums ... + + // + // BullishMomentumBars ... + if (!ignoreBullishMomentums) + { + // + int count = state.CountBullishMomentums(); + if (IsValidSize(count)) + { + // + for (int i = 0; i < count; i++) + { + // + XCMomentumBar *iBar = state.bullishMomentums[i]; + XCBullishMomentumBarObject *iObj; + + // + bool isCreated = CreateBullishMomentumBar( + iBar, + iObj // + ); + if (isCreated) + { + // + Add( + (XCBaseObject *)iObj, + drawnObjects // + ); + } + } + } + } + + // + // BearishMomentumBars ... + if (!ignoreBearishMomentums) + { + // + int count = state.CountBearishMomentums(); + if (IsValidSize(count)) + { + // + for (int i = 0; i < count; i++) + { + // + XCMomentumBar *iBar = state.bearishMomentums[i]; + XCBearishMomentumBarObject *iObj; + + // + bool isCreated = CreateBearishMomentumBar( + iBar, + iObj // + ); + if (isCreated) + { + // + Add( + (XCBaseObject *)iObj, + drawnObjects // + ); + } + } + } + } + + // + // Pullbacks ... + + // + // Bullish ... + if (!ignoreBullishPullbacks) + { + // + int count = state.CountBullishPullbacks(); + if (IsValidSize(count)) + { + // + for (int i = 0; i < count; i++) + { + // + XCBoxObject *iObj; + bool isCreated = DrawBox( + state.bullishPullbacks[i], + iObj // + ); + if (isCreated) + { + // + Add( + (XCBaseObject *)iObj, + drawnObjects // + ); + } + } + } + } + + // + // Bearish ... + if (!ignoreBearishPullbacks) + { + // + int count = state.CountBearishPullbacks(); + if (IsValidSize(count)) + { + // + for (int i = 0; i < count; i++) + { + // + XCBoxObject *iObj; + bool isCreated = DrawBox( + state.bearishPullbacks[i], + iObj // + ); + if (isCreated) + { + // + Add( + (XCBaseObject *)iObj, + drawnObjects // + ); + } + } + } + } + + // + // Consolidation Zones ... + + // + // Bullish Consolidation Zones ... + if (!ignoreBullishConsolidationZones) + { + // + int count = state.CountBullishConsolidationZones(); + if (IsValidSize(count)) + { + // + for (int i = 0; i < count; i++) + { + // + XCConsolidationZoneObject *iObj; + bool isCreated = CreateConsolidationZone( + state.bullishConsolidationZones[i], + iObj // + ); + if (isCreated) + { + // + Add( + (XCBaseObject *)iObj, + drawnObjects // + ); + } + } + } + } + + // + // Bearish Consolidation Zones ... + if (!ignoreBearishConsolidationZones) + { + // + int count = state.CountBearishConsolidationZones(); + if (IsValidSize(count)) + { + // + for (int i = 0; i < count; i++) + { + // + XCConsolidationZoneObject *iObj; + bool isCreated = CreateConsolidationZone( + state.bearishConsolidationZones[i], + iObj // + ); + if (isCreated) + { + // + Add( + (XCBaseObject *)iObj, + drawnObjects // + ); + } + } + } + } + + // + // Spikes ... + + // + // Bullish ... + if (!ignoreBullishSpikes) + { + // + int count = state.CountBullishSpikes(); + if (IsValidSize(count)) + { + // + for (int i = 0; i < count; i++) + { + // + XCBoxObject *iObj; + bool isCreated = DrawBox( + state.bullishSpikes[i], + iObj // + ); + if (isCreated) + { + // + Add( + (XCBaseObject *)iObj, + drawnObjects // + ); + } + } + } + } + + // + // Bearish ... + if (!ignoreBearishSpikes) + { + // + int count = state.CountBearishSpikes(); + if (IsValidSize(count)) + { + // + for (int i = 0; i < count; i++) + { + // + XCBoxObject *iObj; + bool isCreated = DrawBox( + state.bearishSpikes[i], + iObj // + ); + if (isCreated) + { + // + Add( + (XCBaseObject *)iObj, + drawnObjects // + ); + } + } + } + } + + // + // Sharps ... + + // + // Bullish ... + if (!ignoreBullishSharps) + { + // + int count = state.CountBullishSharps(); + if (IsValidSize(count)) + { + // + for (int i = 0; i < count; i++) + { + // + XCBoxObject *iObj; + bool isCreated = DrawBox( + state.bullishSharps[i], + iObj // + ); + if (isCreated) + { + // + Add( + (XCBaseObject *)iObj, + drawnObjects // + ); + } + } + } + } + + // + // Bearish ... + if (!ignoreBearishSharps) + { + // + int count = state.CountBearishSharps(); + if (IsValidSize(count)) + { + // + for (int i = 0; i < count; i++) + { + // + XCBoxObject *iObj; + bool isCreated = DrawBox( + state.bearishSharps[i], + iObj // + ); + if (isCreated) + { + // + Add( + (XCBaseObject *)iObj, + drawnObjects // + ); + } + } + } + } + + // + result = ArraySize(drawnObjects); + + // + return result; + } + + // + protected: + // + + // + private: + // + + // + // Props ... + + // + string mPrefix; // Prefix of Created Objects ... + long mChartIdentification; // Chart Id ... + int mSubWindowIdentification; // Sub Window ... + + // + // XOHCL ... + int mBarWidth; // Bar Width ... + color mBarBullishColor; // Bar Bullish Color ... + color mBarBearishColor; // Bar Bearish Color ... + bool mBarFillHighShadow; // Fill Bar High Shadow ... + ENUM_LINE_STYLE mBarHighShadowStyle; // Bar High Shadow Style ... + bool mBarFillBody; // Fill Bar Body ... + ENUM_LINE_STYLE mBarBodyStyle; // Bar Body Style ... + bool mBarFillLowShadow; // Fill Bar Low Show ... + ENUM_LINE_STYLE mBarLowShadowStyle; // Bar Low Shadow Style ... + + // + // Swing Low ... + int mSwingLowWidth; // Swing Low Width ... + int mSwingLowArrow; // Swing Low Arrow Code ... + color mSwingLowColor; // Swing Low Color ... + + // + // Swing High ... + int mSwingHighWidth; // Swing High Width ... + int mSwingHighArrow; // Swing High Arrow Code ... + color mSwingHighColor; // Swing High Color ... + + // + // Bullish Momentum Bar ... + int mBullishMomentumBarWidth; // Bullish Momentum Bar Width ... + int mBullishMomentumBarArrow; // Bullish Momentum Bar Arrow Code ... + color mBullishMomentumBarColor; // Bullish Momentum Bar Color ... + + // + // Bearish Momentum Bar ... + int mBearishMomentumBarWidth; // Bearish Momentum Bar Width ... + int mBearishMomentumBarArrow; // Bearish Momentum Bar Arrow Code ... + color mBearishMomentumBarColor; // Bearish Momentum Bar Color ... + + // + // Bullish Rejection Bar ... + int mBullishRejectionBarWidth; // Bullish Rejection Bar High Width ... + int mBullishRejectionBarArrow; // Bullish Rejection Bar High Arrow Code ... + color mBullishRejectionBarColor; // Bullish Rejection Bar High Color ... + + // + // Bearish Rejection Bar ... + int mBearishRejectionBarWidth; // Bearish Rejection Bar Width ... + int mBearishRejectionBarArrow; // Bearish Rejection Bar Arrow Code ... + color mBearishRejectionBarColor; // Bearish Rejection Bar Color ... + + // + // Supply Zone ... + bool mSupplyZoneFill; // Fill Supply Zone ... + int mSupplyZoneWidth; // Supply Zone Width ... + color mSupplyZoneColor; // Supply Zone Color ... + ENUM_LINE_STYLE mSupplyZoneStyle; // Supply Zone Style ... + + // + // Demand Zone ... + bool mDemandZoneFill; // Fill Demand Zone ... + int mDemandZoneWidth; // Demand Zone Width ... + color mDemandZoneColor; // Demand Zone Color ... + ENUM_LINE_STYLE mDemandZoneStyle; // Demand Zone Style ... + + // + // Resistance Zone ... + bool mResistanceZoneFill; // Fill Resistance Zone ... + int mResistanceZoneWidth; // Resistance Zone Width ... + color mResistanceZoneColor; // Resistance Zone Color ... + ENUM_LINE_STYLE mResistanceZoneStyle; // Resistance Zone Style ... + + // + // Support Zone ... + bool mSupportZoneFill; // Fill Support Zone ... + int mSupportZoneWidth; // Support Zone Width ... + color mSupportZoneColor; // Support Zone Color ... + ENUM_LINE_STYLE mSupportZoneStyle; // Support Zone Style ... + + // + // Bullish Order Block ... + bool mBullishOrderBlockFill; // Fill Bullish Order Block ... + int mBullishOrderBlockWidth; // Bullish Order Block Width ... + color mBullishOrderBlockColor; // Bullish Order Block Color ... + ENUM_LINE_STYLE mBullishOrderBlockStyle; // Bullish Order Block Style ... + + // + // Bearish Order Block ... + bool mBearishOrderBlockFill; // Fill Bearish Order Block ... + int mBearishOrderBlockWidth; // Bearish Order Block Width ... + color mBearishOrderBlockColor; // Bearish Order Block Color ... + ENUM_LINE_STYLE mBearishOrderBlockStyle; // Bearish Order Block Style ... + + // + // Bullish FVG ... + bool mBullishFVGFill; // Fill Bullish FVG ... + int mBullishFVGWidth; // Bullish FVG Width ... + color mBullishFVGColor; // Bullish FVG Color ... + ENUM_LINE_STYLE mBullishFVGStyle; // Bullish FVG Style ... + + // + // Bearish FVG ... + bool mBearishFVGFill; // Fill Bearish FVG ... + int mBearishFVGWidth; // Bearish FVG Width ... + color mBearishFVGColor; // Bearish FVG Color ... + ENUM_LINE_STYLE mBearishFVGStyle; // Bearish FVG Style ... + + // + // Ticks Zone ... + XTickZoneLevelSpecs mTicksZoneSpecs[]; // Zone Draw Specifications ... + + // +}; \ No newline at end of file diff --git a/BKPS/14040203/Classes/x-saherelm.x-rm.panel.class.mq5 b/BKPS/14040203/Classes/x-saherelm.x-rm.panel.class.mq5 new file mode 100644 index 0000000..d3808dc --- /dev/null +++ b/BKPS/14040203/Classes/x-saherelm.x-rm.panel.class.mq5 @@ -0,0 +1,1162 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Class Library +// -------------------------------------- +// Name: XCRMPanel +// Description: provides all based classes for use ... +// +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +////////////////////////////////////////////////////// +// +// Global Properties ... +#property library +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://www.saherelm.ir" +#property version "1.00" +#property strict + +// +// Imports ... +#include "../Classes/x-saherelm.x-app-dialog.class.mq5" +#include "../Classes/x-saherelm.x-trade.class.mq5" + +// +#include +#include +#include +#include +#include +#include + +// +// Implementation ... + +// +class XCRMPanel : public XCAppDialog +{ + // + public: + // + // Event Binding ... + // EVENT_MAP_BEGIN(XCRMPanel) + // ON_EVENT(ON_CLICK, btnBuy, HandleBtnBuyClicked) + // ON_EVENT(ON_CLICK, btnSell, HandleBtnSellClicked) + // EVENT_MAP_END(XCRMPanel) + + // + // Constructor(s) ... + void XCRMPanel() + { + // + Default(); + } + + // + // Deconstructor ... + void ~XCRMPanel() + { + // + HandleRemoveObjects(); + + // + ZeroMemory(mTrader); + } + + // + // Props ... + + // + int SubWindow() + { + return subWindow; + } + + // + void SubWindow(int value) + { + // + if (value < 0) + { + value = 0; + } + + // + subWindow = value; + } + + // + // BUY ... + + // + string BtnBuyLabel() + { + return buyLabelStr; + } + + // + void BtnBuyLabel(string value) + { + buyLabelStr = value; + } + + // + color BtnBuyBGColor() + { + return btnBuyBGColor; + } + + // + void BtnBuyBGColor(color value) + { + btnBuyBGColor = value; + } + + // + // SELL ... + + // + string BtnSellLabel() + { + return sellLabelStr; + } + + // + void BtnSellLabel(string value) + { + sellLabelStr = value; + } + + // + color BtnSellBGColor() + { + return btnSellBGColor; + } + + // + void BtnSellBGColor(color value) + { + btnSellBGColor = value; + } + + // + double RiskPercent() + { + return riskPercent; + } + + // + void RiskPercent(double value) + { + // + if (value < minAllowedRiskPercent) + { + value = minAllowedRiskPercent; + } + + // + if (value > maxAllowedRiskPercent) + { + value = maxAllowedRiskPercent; + } + + // + riskPercent = value; + + // + tbRisk.Text((string)value); + } + + // + // + // + + bool HasSL() + { + return slLine != NULL; + } + + double ReadSL() + { + // + double result = 0; + + // + if (HasSL()) + { + // + result = slLine.GetDouble(OBJPROP_PRICE); + result = NormalizePrice(result, _Symbol); + } + + // + return result; + } + + bool HasTP() + { + return tpLine != NULL; + } + + double ReadTP() + { + // + double result = 0; + + // + if (HasTP()) + { + // + result = tpLine.GetDouble(OBJPROP_PRICE); + result = NormalizePrice(result, _Symbol); + } + + // + return result; + } + + bool HasEntry() + { + return entryLine != NULL; + } + + double ReadEntry() + { + // + double result = 0; + + // + if (HasEntry()) + { + // + result = entryLine.GetDouble(OBJPROP_PRICE); + result = NormalizePrice(result, _Symbol); + } + + // + return result; + } + + bool GetDirection(ENUM_X_DIRECTION &dir) + { + // + bool result = false; + + // + dir = X_DIRECTION_NONE; + + // + result = HasTP() && + HasSL() && + HasEntry(); + + // + if (!result) + { + return result; + } + + // + double sl = ReadSL(); + double tp = ReadTP(); + double entry = ReadEntry(); + + // + result = sl > 0 && + tp > 0 && + entry > 0; + if (!result) + { + return result; + } + + // + bool isBullish = + tp > entry && + tp > sl && + entry > sl; + bool isBearish = + tp < entry && + tp < sl && + entry < sl; + result = isBullish || + isBearish; + if (!result) + { + return result; + } + + // + dir = isBullish + ? X_DIRECTION_BULLISH + : X_DIRECTION_BEARISH; + + // + return result; + } + + // + // Tools ... + + // + void Default() + { + // + string prefix = CreateInstanceId(); + + // + defaultR2R = 2; + riskPercent = 1; + defaultRisk = 50; + minAllowedRiskPercent = 0.5; + maxAllowedRiskPercent = 10.0; + + // + disabledBtnColor = clrLightGray; + disabledBtnBGColor = clrGray; + + // + tbRiskID = prefix + "_RiskTB"; + + // + buyLabelStr = "Buy"; + btnBuyBGColor = clrLime; + btnBuyColor = clrDarkBlue; + btnBuyID = prefix + "_" + buyLabelStr; + + // + sellLabelStr = "Sell"; + btnSellBGColor = clrRed; + btnSellColor = clrDarkBlue; + btnSellID = prefix + "_" + sellLabelStr; + + // + slLine = NULL; + slColor = clrMagenta; + slID = prefix + "_SL"; + + // + tpLine = NULL; + tpColor = clrAqua; + tpID = prefix + "_TP"; + + // + entryLine = NULL; + entryColor = clrYellow; + entryID = prefix + "_Entry"; + + // + btnDrawRemoveID = prefix + "_DrawRemove"; + drawLabelStr = "Draw"; + removeLabelStr = "Remove"; + btnDrawColor = clrWhite; + btnDrawBGColor = clrDarkBlue; + btnRemoveColor = clrYellow; + btnRemoveBGColor = clrDarkRed; + + // + slippage = 10; + magicNumber = 1694056; + + // + // Create Trader Instance and Configure it ... + mTrader = new XCTrade( + slippage, + magicNumber // + ); + } + + // + void UpdateState() + { + // + bool canEnable = HasSL() && + HasTP() && + HasEntry(); + + // + if (canEnable) + { + SetRemoveMode(); + } + else + { + SetDrawMode(); + } + + // + double entry = GetBid(_Symbol); + ENUM_X_DIRECTION dir; + if (GetDirection(dir)) + { + entry = GetEntry(_Symbol, dir); + } + + // + if (HasEntry()) + { + double iEntry = ReadEntry(); + if (iEntry != entry) + { + SetEntry(entry); + } + } + } + + // + // Handlers ... + + /** + * Handle Btn Buy Clicked ... + */ + void HandleBtnBuyClicked() + { + // + ENUM_X_DIRECTION dir; + bool has = GetDirection(dir); + bool isBullish = has & + IsBullish(dir); + if (!has || !isBullish) + { + return; + } + + // + double tp = ReadTP(); + double sl = ReadSL(); + double entry = ReadEntry(); + + // + mTrader.Buy( + _Symbol, + _Period, + volume, + entry, + sl, + tp // + ); + } + + /** + * Handle Btn Sell Clicked ... + */ + void HandleBtnSellClicked() + { + // + ENUM_X_DIRECTION dir; + bool has = GetDirection(dir); + bool isBearish = has & + IsBearish(dir); + if (!has || !isBearish) + { + return; + } + + // + double tp = ReadTP(); + double sl = ReadSL(); + double entry = ReadEntry(); + + // + mTrader.Sell( + _Symbol, + _Period, + volume, + entry, + sl, + tp // + ); + } + + /** + * Handle Draw Remove Position ... + */ + void HandleBtnDrawRemoveClicked() + { + // + string btnText = btnDrawRemove.Text(); + if (btnText == drawLabelStr) + { + HandleDrawObjects(); + } + else if (btnText == removeLabelStr) + { + HandleRemoveObjects(); + } + } + + /** + * Handle Risk Percent Changed ... + */ + void HandleOnRiskPercentChanged() + { + // + string tbRiskStr = tbRisk.Text(); + + // + double tbNewRisk = (double)tbRiskStr; + RiskPercent(tbNewRisk); + } + + // + // Virtuals ... + + // + virtual bool OnEvent( + const int id, + const long &lparam, + const double &dparam, + const string &sparam // + ) + { + // + bool result = false; + + // + XCAppDialog::OnEvent(id, lparam, dparam, sparam); + + // + // Check if the event is a button click + if (id == ON_CLICK + CHARTEVENT_CUSTOM) + { + // + // Verify if the clicked object is this button + if (lparam == btnBuy.Id()) + { + // + HandleBtnBuyClicked(); + result = true; + } + else if (lparam == btnSell.Id()) + { + // + HandleBtnSellClicked(); + result = true; + } + else if (lparam == btnDrawRemove.Id()) + { + // + HandleBtnDrawRemoveClicked(); + result = true; + } + } + else if (id == ON_END_EDIT + CHARTEVENT_CUSTOM) + { + // + if (lparam == tbRisk.Id()) + { + // + HandleOnRiskPercentChanged(); + result = true; + } + } + else if (id == CHARTEVENT_OBJECT_DRAG) + { + // + if (sparam == entryLine.Name()) + { + // + CalculateData(); + result = true; + } + else if (sparam == tpLine.Name()) + { + // + CalculateData(); + result = true; + } + else if (sparam == slLine.Name()) + { + // + CalculateData(); + result = true; + } + } + + // + return result; + } + + // + // Overrides ... + + // + bool Create( + const long chart, + const string name, + const int subwin, + const int x1, + const int y1, + const int x2, + const int y2 // + ) + { + // + bool result = false; + + // + // Create App Dialog instance it Self ... + result = XCAppDialog::Create( + chart, + name, + subwin, + x1, + y1, + x2, + y2 // + ); + if (!result) + { + return result; + } + + // + chartId = chart; + subWindow = subwin; + + // + // Configure Dialog ... + BackgroundColor(clrBlack); + + // + int top = Top(); + int left = Left(); + int right = Right(); + int bottom = Bottom(); + + // + int width = Width(); + int height = Height(); + + // + int desiredWidth = width - left; + int desiredHeight = height - top; + + // + int btnWidth = desiredWidth / 2; + int btnHeight = desiredHeight / 3; + + // + // Risk Edit ... + int tbRiskX1 = 0; + int tbRiskY1 = 0; + int tbRiskX2 = tbRiskX1 + (btnWidth * 2); + int tbRiskY2 = tbRiskY1 + btnHeight; + result = tbRisk.Create( + chart, + tbRiskID, + subWindow, + tbRiskX1, + tbRiskY1, + tbRiskX2, + tbRiskY2 // + ); + if (!result) + { + return result; + } + + // + result = tbRisk.Text((string)riskPercent); + result = tbRisk.TextAlign(ALIGN_CENTER); + + // + result = Add(tbRisk); + + // + // Create Draw/Remove Button ... + int btnDrawX1 = 0; + int btnDrawY1 = desiredHeight - (btnHeight * 2); + int btnDrawX2 = btnDrawX1 + (btnWidth * 2); + int btnDrawY2 = btnDrawY1 + btnHeight; + result = btnDrawRemove.Create( + chart, + btnDrawRemoveID, + subWindow, + btnDrawX1, + btnDrawY1, + btnDrawX2, + btnDrawY2 // + ); + if (!result) + { + return result; + } + + // + result = btnDrawRemove.Text(drawLabelStr); + result = btnDrawRemove.Color(btnDrawColor); + result = btnDrawRemove.ColorBackground(btnDrawBGColor); + + // + result = Add(btnDrawRemove); + + // + // Create Buy Button ... + int btnBuyX1 = 0; + int btnBuyY1 = desiredHeight - btnHeight; + int btnBuyX2 = btnBuyX1 + btnWidth; + int btnBuyY2 = btnBuyY1 + btnHeight; + result = btnBuy.Create( + chart, + btnBuyID, + subWindow, + btnBuyX1, + btnBuyY1, + btnBuyX2, + btnBuyY2 // + ); + if (!result) + { + return result; + } + + // + result = btnBuy.Text(buyLabelStr); + result = btnBuy.Color(btnBuyColor); + result = btnBuy.ColorBackground(btnBuyBGColor); + + // + result = Add(btnBuy); + + // + // Create Sell Button ... + int btnSellX1 = btnBuyX2; + int btnSellY1 = btnBuyY1; + int btnSellX2 = btnSellX1 + btnWidth; + int btnSellY2 = btnSellY1 + btnHeight; + result = btnSell.Create( + chart, + btnSellID, + subWindow, + btnSellX1, + btnSellY1, + btnSellX2, + btnSellY2 // + ); + if (!result) + { + return result; + } + + // + result = btnSell.Text(sellLabelStr); + result = btnSell.Color(btnSellColor); + result = btnSell.ColorBackground(btnSellBGColor); + + // + result = Add(btnSell); + + // + if (result) + { + // + UpdateState(); + CalculateData(); + } + + // + return result; + } + + // + protected: + // + XCTrade *mTrader; + int slippage; + long magicNumber; + + // + long chartId; + int subWindow; + + // + string slID; + color slColor; + CChartObjectHLine *slLine; + + // + string tpID; + color tpColor; + CChartObjectHLine *tpLine; + + // + string entryID; + color entryColor; + CChartObjectHLine *entryLine; + + // + double riskPercent; + double minAllowedRiskPercent; + double maxAllowedRiskPercent; + + // + double volume; + + // + double defaultR2R; + double defaultRisk; + + // + color disabledBtnColor; + color disabledBtnBGColor; + + // + // Risk Percent Edit ... + CEdit tbRisk; + string tbRiskID; + + // + // BUY Button ... + CButton btnBuy; + string btnBuyID; + string buyLabelStr; + color btnBuyColor; + color btnBuyBGColor; + + // + // SELL Button ... + CButton btnSell; + string btnSellID; + string sellLabelStr; + color btnSellColor; + color btnSellBGColor; + + // + // DRAW / REMOVE Button ... + CButton btnDrawRemove; + string btnDrawRemoveID; + string drawLabelStr; + string removeLabelStr; + color btnDrawColor; + color btnDrawBGColor; + color btnRemoveColor; + color btnRemoveBGColor; + + // + private: + // + + bool EnableBuy(bool value) + { + // + bool result = false; + + // + btnBuy.Locking(!value); + btnSell.Pressed(value); + if (!value) + { + // + // Disabled ... + btnBuy.Color(disabledBtnColor); + btnBuy.ColorBackground(disabledBtnBGColor); + } + else + { + // + // Enable ... + btnBuy.Color(btnBuyColor); + btnBuy.ColorBackground(btnBuyBGColor); + } + + // + return result; + } + + bool EnableSell(bool value) + { + // + bool result = false; + + // + btnSell.Locking(!value); + btnSell.Pressed(value); + if (!value) + { + // + // Disabled ... + btnSell.Color(disabledBtnColor); + btnSell.ColorBackground(disabledBtnBGColor); + } + else + { + // + // Enable ... + btnSell.Color(btnSellColor); + btnSell.ColorBackground(btnSellBGColor); + } + + // + return result; + } + + bool SetDrawMode() + { + // + bool result = false; + + // + result = btnDrawRemove.Text(drawLabelStr); + result = btnDrawRemove.Color(btnDrawColor); + result = btnDrawRemove.ColorBackground(btnDrawBGColor); + + // + return result; + } + + bool SetRemoveMode() + { + // + bool result = false; + + // + result = btnDrawRemove.Text(removeLabelStr); + result = btnDrawRemove.Color(btnRemoveColor); + result = btnDrawRemove.ColorBackground(btnRemoveBGColor); + + // + return result; + } + + void HandleDrawObjects() + { + // + double entry = GetBid(_Symbol); + double points = GetPoints(_Symbol); + double riskRatio = defaultRisk * points; + double rewardRatio = riskRatio * defaultR2R; + double sl = entry - riskRatio; + double tp = entry + rewardRatio; + + // + datetime rectTime1 = iTime( + _Symbol, + _Period, + 20 // + ); + datetime rectTime2 = iTime( + _Symbol, + _Period, + 19 // + ); + + // + bool has = false; + + // + // Create Entry Line ... + entryLine = new CChartObjectHLine(); + has = entryLine.Create( + chartId, + entryID, + subWindow, + entry // + ); + if (!has) + { + // + HandleRemoveObjects(); + return; + } + entryLine.Selectable(false); + entryLine.Color(entryColor); + + // + // Create SL Line ... + slLine = new CChartObjectHLine(); + has = slLine.Create( + chartId, + slID, + subWindow, + sl // + ); + if (!has) + { + // + HandleRemoveObjects(); + return; + } + slLine.Color(slColor); + slLine.Selectable(true); + + // + // Create TP Line ... + tpLine = new CChartObjectHLine(); + has = tpLine.Create( + chartId, + tpID, + subWindow, + tp // + ); + if (!has) + { + // + HandleRemoveObjects(); + return; + } + tpLine.Color(tpColor); + tpLine.Selectable(true); + + // + CalculateData(); + } + + void HandleRemoveObjects() + { + // + if (HasSL()) + { + // + slLine.Delete(); + slLine.Detach(); + ZeroMemory(slLine); + } + + // + if (HasTP()) + { + // + tpLine.Delete(); + tpLine.Detach(); + ZeroMemory(tpLine); + } + + // + if (HasEntry()) + { + // + entryLine.Delete(); + entryLine.Detach(); + ZeroMemory(entryLine); + } + + // + UpdateState(); + CalculateData(); + } + + void CalculateData() + { + // + EnableBuy(false); + EnableSell(false); + + // + ENUM_X_DIRECTION dir; + bool has = GetDirection(dir); + if (!has) + { + return; + } + + // + bool isBullish = IsBullish(dir); + bool isBearish = IsBearish(dir); + + // + if (isBullish) + { + // + EnableBuy(true); + EnableSell(false); + } + else if (isBearish) + { + // + EnableSell(true); + EnableBuy(false); + } + + // + double sl = ReadSL(); + double tp = ReadTP(); + double entry = ReadEntry(); + double points = GetPoints(_Symbol); + + // + double risk = MathAbs(entry - sl); + int riskPoints = (int)(risk / points); + double riskRewardRatio = MathAbs(tp - entry) / risk; + riskRewardRatio = NormalizeDouble(riskRewardRatio, 2); + + // + double balance = GetBalance(); + + // + double riskAmount = riskPercent * (balance / 100); + riskAmount = NormalizePrice(riskAmount, _Symbol); + + // + double rewardAmount = riskAmount * riskRewardRatio; + rewardAmount = NormalizePrice(rewardAmount, _Symbol); + + // + string currency = mTrader.mAccount.GetCurrency(); + + // + volume = mTrader + .mAccount + .CalculateVolume( + _Symbol, + riskAmount, + riskPoints // + ); + volume = NormalizeVolume(volume, _Symbol); + + // + string slDesc = "SL: " + ToString(sl) + + ", Risk: " + ToString(riskPoints) + " pt (" + ToString(riskPercent) + "%)" + + ", Amount: " + ToString(riskAmount) + currency; + slLine.Tooltip(slDesc); + slLine.Description(slDesc); + + // + string tpDesc = "TP: " + ToString(tp) + " (" + ToString(rewardAmount) + " " + currency + ")" + + ", R2R: 1:" + ToString(riskRewardRatio); + tpLine.Tooltip(tpDesc); + tpLine.Description(tpDesc); + + // + string entryDesc = "Entry: " + ToString(entry) + + ", Volume: " + ToString(volume); + entryLine.Tooltip(entryDesc); + entryLine.Description(entryDesc); + + // + } + + void SetEntry(double value) + { + // + if (value <= 0 || + !HasEntry()) + { + return; + } + + // + bool has = entryLine + .SetDouble(OBJPROP_PRICE, value); + } + + double GetBalance() + { + // + double result = 0; + + // + // TODO: Change This ... + return mTrader.mAccount.GetBalance(); + + // + return result; + } + + // +}; + +// \ No newline at end of file diff --git a/BKPS/14040203/Classes/x-saherelm.x-trade.class.mq5 b/BKPS/14040203/Classes/x-saherelm.x-trade.class.mq5 new file mode 100644 index 0000000..7bdd19f --- /dev/null +++ b/BKPS/14040203/Classes/x-saherelm.x-trade.class.mq5 @@ -0,0 +1,3934 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Class Library +// ---------------------------------------------- +// Name: XSCTrade +// Description: provides all Trade requirements ... +// +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +////////////////////////////////////////////////////// +// +// Global Properties ... +#property library +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://www.saherelm.ir" +#property version "1.00" +#property strict + +// +// Imports ... +#include "../Classes/x-saherelm.base.class.mq5" +#include "../Classes/x-saherelm.x-account.class.mq5" +#include "../Classes/x-saherelm.x-alert.class.mq5" +#include "../Libraries/x-saherelm.x-trade.lib.mq5" + +// +// Definitions ... + +// +// Overrides ... + +// +// XCTrade Base Class ... +class XCTradeBase : public CTrade +{ + public: + // + // Modify Specific Position, by Specific Comment ... + bool PositionModify( + const string symbol, // Symbol + const double sl, // Stop Loss + const double tp, // Take Profit + const string comment = "" // Comment For Modify + ) + { + // + // check stopped + if (IsStopped(__FUNCTION__)) + { + return (false); + } + + // + // check position existence + if (!SelectPosition(symbol)) + { + return (false); + } + + // + // clean + ClearStructures(); + + // + // setting request + m_request.action = TRADE_ACTION_SLTP; + m_request.symbol = symbol; + m_request.magic = m_magic; + m_request.sl = sl; + m_request.tp = tp; + m_request.position = PositionGetInteger(POSITION_TICKET); + + // + // Specified Comment ... + if (StringLen(comment) > 0) + { + m_request.comment = comment; + } + + // + // action and return the result + return (OrderSend(m_request, m_result)); + } + bool PositionModify( + const ulong ticket, // Position Ticket + const double sl, // Stop Loss + const double tp, // Take Profit + const string comment = "" // Comment For Modify + ) + { + // + // check stopped + if (IsStopped(__FUNCTION__)) + { + return (false); + } + + // + // check position existence + if (!PositionSelectByTicket(ticket)) + { + return (false); + } + + // + // clean + ClearStructures(); + + // + // setting request + m_request.action = TRADE_ACTION_SLTP; + m_request.position = ticket; + m_request.symbol = PositionGetString(POSITION_SYMBOL); + m_request.magic = m_magic; + m_request.sl = sl; + m_request.tp = tp; + + // + // Specified Comment ... + if (StringLen(comment) > 0) + { + m_request.comment = comment; + } + + // + // action and return the result + return (OrderSend(m_request, m_result)); + } + + // + // Close Specific Position, by Specific Comment ... + bool PositionClose( + const string symbol, // Symbol + const ulong deviation, // Deviation + const string comment = "" // Comment For Close + ) + { + // + bool partial_close = false; + int retry_count = 10; + uint retcode = TRADE_RETCODE_REJECT; + + // + // check stopped + if (IsStopped(__FUNCTION__)) + { + return (false); + } + + // + // clean + ClearStructures(); + + // + // check filling + if (!FillingCheck(symbol)) + { + return (false); + } + + // + do + { + // + // check + if (SelectPosition(symbol)) + { + // + if ((ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY) + { + // + // prepare request for close BUY position + m_request.type = ORDER_TYPE_SELL; + m_request.price = SymbolInfoDouble(symbol, SYMBOL_BID); + } + else + { + // + // prepare request for close SELL position + m_request.type = ORDER_TYPE_BUY; + m_request.price = SymbolInfoDouble(symbol, SYMBOL_ASK); + } + } + else + { + // + // position not found + m_result.retcode = retcode; + return (false); + } + + // + // setting request + m_request.action = TRADE_ACTION_DEAL; + m_request.symbol = symbol; + m_request.volume = PositionGetDouble(POSITION_VOLUME); + m_request.magic = m_magic; + m_request.deviation = (deviation == ULONG_MAX) ? m_deviation : deviation; + m_request.position = PositionGetInteger(POSITION_TICKET); + + // + // Specify Comment ... + m_request.comment = comment; + + // + // check volume + double max_volume = SymbolInfoDouble(symbol, SYMBOL_VOLUME_MAX); + if (m_request.volume > max_volume) + { + // + m_request.volume = max_volume; + partial_close = true; + } + else + { + partial_close = false; + } + + // + // hedging? just send order + if (IsHedging()) + { + return (OrderSend(m_request, m_result)); + } + + // + // order send + if (!OrderSend(m_request, m_result)) + { + // + if (--retry_count != 0) + { + continue; + } + + // + if (retcode == TRADE_RETCODE_DONE_PARTIAL) + { + m_result.retcode = retcode; + } + + // + return (false); + } + + // + //--- WARNING. If position volume exceeds the maximum volume allowed for deal, + //--- and when the asynchronous trade mode is on, for safety reasons, position is closed not completely, + //--- but partially. It is decreased by the maximum volume allowed for deal. + if (m_async_mode) + { + break; + } + + // + retcode = TRADE_RETCODE_DONE_PARTIAL; + if (partial_close) + { + Sleep(1000); + } + } while (partial_close); + + // + // succeed + return (true); + } + bool PositionClose( + const ulong ticket, // Position Ticket + const ulong deviation, // Deviation + const string comment = "" // Comment For Close + ) + { + // + // check stopped + if (IsStopped(__FUNCTION__)) + { + return (false); + } + + // + // check position existence + if (!PositionSelectByTicket(ticket)) + { + return (false); + } + + // + string symbol = PositionGetString(POSITION_SYMBOL); + + // + // clean + ClearStructures(); + + // + // check filling + if (!FillingCheck(symbol)) + { + return (false); + } + + // + // check + if ((ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY) + { + // + // prepare request for close BUY position + m_request.type = ORDER_TYPE_SELL; + m_request.price = SymbolInfoDouble(symbol, SYMBOL_BID); + } + else + { + // + // prepare request for close SELL position + m_request.type = ORDER_TYPE_BUY; + m_request.price = SymbolInfoDouble(symbol, SYMBOL_ASK); + } + + // + // setting request + m_request.action = TRADE_ACTION_DEAL; + m_request.position = ticket; + m_request.symbol = symbol; + m_request.volume = PositionGetDouble(POSITION_VOLUME); + m_request.magic = m_magic; + m_request.deviation = (deviation == ULONG_MAX) ? m_deviation : deviation; + + // + // Specify Comment ... + m_request.comment = comment; + + // + // close position + return (OrderSend(m_request, m_result)); + } + + // + // Partial Close Specific Position, by Specific Comment ... + bool PositionClosePartial( + const string symbol, // Symbol + const double volume, // Partial Closing Volume + const ulong deviation, // Deviation + const string comment = "" // Comment For Close + ) + { + // + uint retcode = TRADE_RETCODE_REJECT; + + // + // check stopped + if (IsStopped(__FUNCTION__)) + { + return (false); + } + + // + // for hedging mode only + if (!IsHedging()) + { + return (false); + } + + // + // clean + ClearStructures(); + + // + // check filling + if (!FillingCheck(symbol)) + { + return (false); + } + + // + // check + if (SelectPosition(symbol)) + { + // + if ((ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY) + { + // + // prepare request for close BUY position + m_request.type = ORDER_TYPE_SELL; + m_request.price = SymbolInfoDouble(symbol, SYMBOL_BID); + } + else + { + // + // prepare request for close SELL position + m_request.type = ORDER_TYPE_BUY; + m_request.price = SymbolInfoDouble(symbol, SYMBOL_ASK); + } + } + else + { + // + // position not found + m_result.retcode = retcode; + return (false); + } + + // + // check volume + double position_volume = PositionGetDouble(POSITION_VOLUME); + if (position_volume > volume) + { + position_volume = volume; + } + + // + // setting request + m_request.action = TRADE_ACTION_DEAL; + m_request.symbol = symbol; + m_request.volume = position_volume; + m_request.magic = m_magic; + m_request.deviation = (deviation == ULONG_MAX) ? m_deviation : deviation; + m_request.position = PositionGetInteger(POSITION_TICKET); + + // + // Specifieng Comment ... + m_request.comment = comment; + + // + // hedging? just send order + return (OrderSend(m_request, m_result)); + } + bool PositionClosePartial( + const ulong ticket, // Position Ticket + const double volume, // Partial Closing Volume + const ulong deviation, // Deviation + const string comment = "" // Comment For Close + ) + { + // + // check stopped + if (IsStopped(__FUNCTION__)) + { + return (false); + } + + // + // for hedging mode only + if (!IsHedging()) + { + return (false); + } + + // + // check position existence + if (!PositionSelectByTicket(ticket)) + { + return (false); + } + + // + string symbol = PositionGetString(POSITION_SYMBOL); + + // + // clean + ClearStructures(); + + // + // check filling + if (!FillingCheck(symbol)) + { + return (false); + } + + // + // check + if ((ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY) + { + // + // prepare request for close BUY position + m_request.type = ORDER_TYPE_SELL; + m_request.price = SymbolInfoDouble(symbol, SYMBOL_BID); + } + else + { + // + // prepare request for close SELL position + m_request.type = ORDER_TYPE_BUY; + m_request.price = SymbolInfoDouble(symbol, SYMBOL_ASK); + } + + // + // check volume + double position_volume = PositionGetDouble(POSITION_VOLUME); + if (position_volume > volume) + { + position_volume = volume; + } + + // + // setting request + m_request.action = TRADE_ACTION_DEAL; + m_request.position = ticket; + m_request.symbol = symbol; + m_request.volume = position_volume; + m_request.magic = m_magic; + m_request.deviation = (deviation == ULONG_MAX) ? m_deviation : deviation; + + // + // Specifieng Comment ... + m_request.comment = comment; + + // + // close position + return (OrderSend(m_request, m_result)); + } +}; + +// +// Implementation ... + +// +// a Class For Manage Trades and Handle Trading Actions ... +class XCTrade : public XCBase +{ + // + // Public ... + public: + // + // Props ... + XCAccount *mAccount; // Account Info Provider + + // + // Constructors ... + void XCTrade( + int slippage, // Specify Slippage + ulong magicNumber, // Specify Magic Number + double maxAllowedSpread = 0, // Max Allowed Spred for Opening Trades + int maxAllowedPositions = 0, // Max Allowed Positions + double maxAllowedDrawdownFactor = 0 // Max Allowed Drawdown Factor + ) + { + // + // Setting Props ... + mSlippage = slippage; + mMagicNumber = magicNumber; + + // + mMaxAllowedSpread = maxAllowedSpread; + mMaxAllowedPositions = maxAllowedPositions; + mMaxAllowedDrawdownFactor = maxAllowedDrawdownFactor; + + // + mAccount = new XCAccount(); + + // + // Instance Base Trader Class ... + mTrader = new XCTradeBase(); + + // + // Configuring Base Trader Class ... + mTrader.SetAsyncMode(false); + mTrader.SetDeviationInPoints(mSlippage); + mTrader.SetExpertMagicNumber(mMagicNumber); + + // + // Setting Log Level ... + mTrader.LogLevel(LOG_LEVEL_ERRORS); + + // + // OnTrade Context ... + + // + mDaysForRead = 1; + mScanStarted = false; + + // + // Reset On Trade Counter ... + ResetOnTradeContext(); + + // + // Init On Trade Context ... + InitOnTradeContext(); + } + + // + // Deconstructor ... + ~XCTrade() + { + // + // Remove Pointer ... + delete mTrader; + delete mAccount; + + // + ZeroMemory(mTrader); + ZeroMemory(mAccount); + + // + Clean(mOnModifyEventHandlers); + Clean(mStopLossEventHandlers); + Clean(mTakeProfitEventHandlers); + Clean(mOnForceCloseEventHandlers); + Clean(mDealsChangedEventHandlers); + Clean(mOrdersChangedEventHandlers); + Clean(mOnPartialCloseEventHandlers); + Clean(mPositionsChangedEventHandlers); + Clean(mTradeStateChangedEventHandlers); + } + + // + // Props ... + + // + // Retrieve Slippage ... + int GetSlippage() + { + return mSlippage; + } + + // + // Retrieve Magic Number ... + ulong GetMagicNumber() + { + return mMagicNumber; + } + + // + double GetMaxAllowedSpread() + { + return mMaxAllowedSpread; + } + + // + int GetMaxAllowedPositions() + { + return mMaxAllowedPositions; + } + + // + void SetMaxAllowedPositions(int value) + { + // + if (value < 0) + { + value = 0; + } + + // + mMaxAllowedPositions = value; + } + + // + double GetMaxAllowedDrawdownFactor() + { + return mMaxAllowedDrawdownFactor; + } + + // + // Add Event Listeners ... + + // + void AddOnModifyPositionEventHandler(TOnModify handler) + { + // + if (handler == NULL) + { + return; + } + + // + Add( + handler, + mOnModifyEventHandlers + // + ); + } + + // + void AddOnForceClosePositionEventHandler(TOnForceClose handler) + { + // + if (handler == NULL) + { + return; + } + + // + Add( + handler, + mOnForceCloseEventHandlers + // + ); + } + + // + void AddOnPartialClosePositionEventHandler(TOnPartialClose handler) + { + // + if (handler == NULL) + { + return; + } + + // + Add( + handler, + mOnPartialCloseEventHandlers + // + ); + } + + // + // Add New Deals Changed Event Handler ... + void AddOnTradeStateChangedEventHandler(TOnTradeStateChanged handler) + { + // + if (handler == NULL) + { + return; + } + + // + Add( + handler, + mTradeStateChangedEventHandlers + // + ); + } + + // + // Add New Deals Changed Event Handler ... + void AddOnDealsChangedEventHandler(TOnDealsChanged handler) + { + // + if (handler == NULL) + { + return; + } + + // + Add( + handler, + mDealsChangedEventHandlers + // + ); + } + + // + // Add New Orders Changed Event Handler ... + void AddOnOrdersChangedEventHandler(TOnOrdersChanged handler) + { + // + if (handler == NULL) + { + return; + } + + // + Add( + handler, + mOrdersChangedEventHandlers + // + ); + } + + // + // Add New Positions Changed Event Handler ... + void AddOnPositionsChangedEventHandler(TOnPositionsChanged handler) + { + // + if (handler == NULL) + { + return; + } + + // + Add( + handler, + mPositionsChangedEventHandlers + // + ); + } + + // + // Add New Stop Loss Event Handler ... + void AddOnStopLossEventHandler(TOnStopLoss handler) + { + // + if (handler == NULL) + { + return; + } + + // + Add( + handler, + mStopLossEventHandlers + // + ); + } + + // + // Add New Stop Loss Event Handler ... + void AddOnTakeProfitEventHandler(TOnTakeProfit handler) + { + // + if (handler == NULL) + { + return; + } + + // + Add( + handler, + mTakeProfitEventHandlers + // + ); + } + + // + // Functions ... + + // + // Handlers ... + + // + // Process On Trade Requirement ... + // this Only Used when we Have to Proccess OnTrade Event in EA(s) ... + void HandleOnTradeEvent( + XOnTradeHandlerState &result // Hold's Result + ) + { + // + result.Clean(); + + // + if (mScanStarted) + { + // + ProcessOnTradeContext(result); + } + else + { + // + // Init Trade Context ... + InitOnTradeContext(); + + // + return; + } + + // + // Here we Can Check the Start ... + bool isValid = + // + result.IsValid() && + // + !result.hasNewDeal && + !result.hasNewOrder && + !result.hasNewPosition && + !result.hasNewHistoryOrder + // + ; + if (!isValid) + { + return; + } + + // + // State ... + + // + // Notfy Trade State Changed Event ... + NotifyTradeStateChangeEvent(result); + + // + // Deals ... + if (result.hasNewDeal) + { + // + // Notfy Deals Changed Event ... + NotifyDealsChangeEvent(result.newDeals); + + // + // Retrieve Last Deal ... + XDeal deals[]; + int dealsCount = GetDeals(deals); + if (dealsCount > 0) + { + // + XDeal lastDeal = deals[0]; + + // + if (lastDeal.reason == DEAL_REASON_TP) + { + NotifyTakeProfitEvent(lastDeal); + } + else if (lastDeal.reason == DEAL_REASON_SL) + { + NotifyStopLossEvent(lastDeal); + } + } + } + + // + // Orders ... + if (result.hasNewOrder || result.hasNewHistoryOrder) + { + // + // Notfy Orders Changed Event ... + NotifyOrdersChangeEvent(result.newOrders + result.newHistoryOrders); + } + + // + // Positions ... + if (result.hasNewPosition) + { + // + // Notfy Positions Changed Event ... + NotifyPositionsChangeEvent(result.newPositions); + } + } + + // + // This Must be Called Every time OnTrade Event Happening ... + // this Used for Implementing Custom Senarios ... + XOnTradeHandlerState HandleOnTrade() + { + // + // Handle OnTrade Event ... + XOnTradeHandlerState state; + HandleOnTradeEvent(state); + if ( + !state.hasNewDeal && + !state.hasNewOrder && + !state.hasNewPosition && + !state.hasNewHistoryOrder) + { + return state; + } + + // + // State ... + + // + // Notfy Trade State Changed Event ... + NotifyTradeStateChangeEvent(state); + + // + // DEALS ... + if (state.hasNewDeal) + { + // + // Notfy Deals Changed Event ... + NotifyDealsChangeEvent(state.newDeals); + + // + // Retrieve Last Deal ... + XDeal deals[]; + GetDeals(deals); + int dealsCount = ArraySize(deals); + if (dealsCount > 0) + { + // + XDeal lastDeal = deals[0]; + + // + if (lastDeal.reason == DEAL_REASON_TP) + { + NotifyTakeProfitEvent(lastDeal); + } + else if (lastDeal.reason == DEAL_REASON_SL) + { + NotifyStopLossEvent(lastDeal); + } + } + } + + // + // ORDERS ... + if (state.hasNewOrder || state.hasNewHistoryOrder) + { + // + // Notfy Orders Changed Event ... + NotifyOrdersChangeEvent(state.newOrders + state.newHistoryOrders); + } + + // + // POSITIONS ... + if (state.hasNewPosition) + { + // + // Notfy Positions Changed Event ... + NotifyPositionsChangeEvent(state.newPositions); + } + + // + return state; + } + + // + // Trade Actions ... + + // + // Main ... + + // + // Policies ... + + // + // Check Acocunt Balance is Allow new Trades or not ... + bool CheckEquityForTrade() + { + // + bool result = false; + + // + if (mMaxAllowedDrawdownFactor <= 0) + { + // + result = true; + return result; + } + + // + double equity = mAccount.GetEquity(); + double balance = mAccount.GetBalance(); + + // + double selectedBalance = MathMax(equity, balance) - MathMin(equity, balance); + + // + double maxAllowedBalanceDrawDown = GetMaxAllowedEquity(); + + // + result = equity > balance || + (equity <= balance && + selectedBalance <= maxAllowedBalanceDrawDown); + + // + return result; + } + + // + // Check Max Allowed Positions Policy for Trade ... + bool CheckPositionsForTrade() + { + // + bool result = false; + + // + if (mMaxAllowedPositions <= 0) + { + // + result = true; + return result; + } + + // + XPosition positions[]; + int positionsCount = GetPositions(positions); + if (positionsCount <= 0) + { + // + result = true; + return result; + } + + // + result = positionsCount < mMaxAllowedPositions; + + // + return result; + } + + // + // Check Spread is Ok for Executing Specific Signal ... + bool CheckSpreadForSignalExecution(XSignal &mSignal) + { + // + bool result = false; + + // + bool isSpreadCheckEnable = mMaxAllowedSpread > 0; + if (!isSpreadCheckEnable) + { + result = true; + } + else + { + // + // Retrieve Signal Spread ... + double spread = GetSpread(mSignal.symbol); + result = spread <= mMaxAllowedSpread; + } + + // + return result; + } + + // + // Check Account Policy ... + bool CheckAccountPolicy( + XSignal &mSignal, // For Executing Signal + ENUM_X_SIGNAL_EXECUTION_RESULT &state // State Holder + ) + { + // + bool result = false; + + // + // Check Positions For Trade ... + result = CheckPositionsForTrade(); + if (!result) + { + // + state = X_SIGNAL_EXECUTION_FAILED_MAX_REACHED; + return result; + } + + // + // Check Equity For Trade ... + result = CheckEquityForTrade(); + if (!result) + { + // + state = X_SIGNAL_EXECUTION_FAILED_NO_EQUITY; + return result; + } + + // + // Check Spread for Trade ... + result = CheckSpreadForSignalExecution(mSignal); + if (!result) + { + // + state = X_SIGNAL_EXECUTION_FAILED_SPREAD; + return result; + } + + // + return result; + } + + // + // Execute a Signal ... + bool ExecuteSignal( + XSignal &mSignal, // Signal + ENUM_X_SIGNAL_EXECUTION_RESULT &state, // Result + ENUM_ORDER_TYPE_TIME lifetime = ORDER_TIME_GTC, // Order LifeTime + datetime expiration = NULL, // order expiration time + bool checkPolicies = true // Check Account Policies + ) + { + // + bool result = false; + state = X_SIGNAL_EXECUTION_UNKNOWN; + + // + double currentEntry = GetEntry( + mSignal.symbol, + mSignal.type + // + ); + bool isLong = IsLong(mSignal.type); + + // + if (!mSignal.IsValid()) + { + // + state = X_SIGNAL_EXECUTION_FAILED_INVALID_PARAMS; + return result; + } + + // + // Prepare Signal Comment ... + string mSComment = mSignal.GenerateComment(); + if (!Contains(mSComment, mSignal.comment)) + { + mSignal.comment += mSComment; + } + + // + // Handle Market Execution ... + if (mSignal.mode == X_ORDER_MODE_MARKET) + { + // + // Do Apply Policies here ... + bool hasPolicy = !checkPolicies + ? true + : CheckAccountPolicy(mSignal, state); + if (!hasPolicy) + { + result = false; + } + else + { + // + if (isLong) + { + // + result = Buy( + mSignal.symbol, + mSignal.period, + mSignal.volume, + mSignal.entry, + mSignal.sl, + mSignal.tp, + mSignal.comment + // + ); + } + else + { + // + result = Sell( + mSignal.symbol, + mSignal.period, + mSignal.volume, + mSignal.entry, + mSignal.sl, + mSignal.tp, + mSignal.comment + // + ); + } + } + } + // + // Handle Stop Execution ... + else if (mSignal.mode == X_ORDER_MODE_STOP) + { + + // + // Check Conditions ... + + // + // Check Price ... + result = isLong + ? mSignal.entry > currentEntry + : mSignal.entry < currentEntry; + if (!result) + { + // + state = X_SIGNAL_EXECUTION_FAILED_PRICE_ERROR; + return result; + } + + // + // Execute Order ... + if (isLong) + { + // + result = BuyStop( + mSignal.symbol, + mSignal.period, + mSignal.volume, + mSignal.entry, + mSignal.sl, + mSignal.tp, + lifetime, + expiration, + mSignal.comment + // + ); + } + else + { + // + result = SellStop( + mSignal.symbol, + mSignal.period, + mSignal.volume, + mSignal.entry, + mSignal.sl, + mSignal.tp, + lifetime, + expiration, + mSignal.comment + // + ); + } + } + // + // Handle Limit Execution ... + else if (mSignal.mode == X_ORDER_MODE_LIMIT) + { + // + // Check Conditions ... + + // + // Check Price ... + result = isLong + ? mSignal.entry < currentEntry + : mSignal.entry > currentEntry; + if (!result) + { + // + state = X_SIGNAL_EXECUTION_FAILED_PRICE_ERROR; + return result; + } + + // + // Execute Order ... + if (isLong) + { + // + result = BuyLimit( + mSignal.symbol, + mSignal.period, + mSignal.volume, + mSignal.entry, + mSignal.sl, + mSignal.tp, + lifetime, + expiration, + mSignal.comment + // + ); + } + else + { + // + result = SellLimit( + mSignal.symbol, + mSignal.period, + mSignal.volume, + mSignal.entry, + mSignal.sl, + mSignal.tp, + lifetime, + expiration, + mSignal.comment + // + ); + } + } + + // + // Handle Ticket ... + if (result) + { + // + state = X_SIGNAL_EXECUTION_SUCCEED; + + // + ulong ticket; + if (mSignal.mode == X_ORDER_MODE_MARKET) + { + ticket = GetLastOpenPositionTicket(); + } + else + { + ticket = GetLastPlacedOrderTicket(); + } + + // + mSignal.positionId = ticket; + + // + // Handle Store XPositionInfo ... + if (mSignal.mode == X_ORDER_MODE_MARKET) + { + // + // TODO: Implement this ... + } + + // + // Handle Executing Support Signals ... + int supportsCount = ArraySize(mSignal.supports); + if (supportsCount > 0) + { + // + int executed = 0; + for (int i = 0; i < supportsCount; i++) + { + // + XSignal iSupport = mSignal.supports[i]; + + // + int supIndex = i + 1; + string iComment = GenerateSupportTag(ticket); + iSupport.comment = iComment; + + // + bool isExecuted = ExecuteSignal( + iSupport, + state, + lifetime, + expiration + // + ); + if (isExecuted) + { + executed++; + } + } + + // + result = executed == supportsCount; + } + } + + // + return result; + } + + // + // Execute a Collection Of Signals ... + int ExecuteSignals( + XSignal &signals[], // Collection of Signal for Execution + ENUM_X_SIGNAL_EXECUTION_RESULT &states[], // Signal Execution Result + ENUM_ORDER_TYPE_TIME lifetime = ORDER_TIME_GTC, // Order LifeTime + datetime expiration = NULL, // order expiration time + bool checkPolicies = true // Check Account Policies + ) + { + // + int result = 0; + + // + Clean(states); + + // + int signalsCount = ArraySize(signals); + if (signalsCount <= 0) + { + return result; + } + + // + ArrayResize(states, signalsCount); + ArrayInitialize(states, X_SIGNAL_EXECUTION_UNKNOWN); + for (int i = 0; i < signalsCount; i++) + { + // + bool isExecuted = ExecuteSignal( + signals[i], + states[i], + lifetime, + expiration, + checkPolicies + // + ); + + // + if (isExecuted) + { + result++; + } + } + + // + return result; + } + + // + int ExecuteSpecifiedSignals( + XSignal &signals[], // Collection of Signal for Execution + XSignal ¬Executeds[], // Not Executed Signal + ENUM_X_SIGNAL_EXECUTION_RESULT &states[], // Signal Execution Result + ENUM_ORDER_TYPE_TIME lifetime = ORDER_TIME_GTC, // Order LifeTime + datetime expiration = NULL, // order expiration time + bool checkPolicies = true // Check Account Policies + ) + { + // + int result = 0; + + // + Clean(states); + Clean(notExecuteds); + + // + int signalsCount = ArraySize(signals); + if (signalsCount <= 0) + { + return result; + } + + // + ArrayResize(states, signalsCount); + ArrayInitialize(states, X_SIGNAL_EXECUTION_UNKNOWN); + for (int i = 0; i < signalsCount; i++) + { + // + bool isExecuted = ExecuteSignal( + signals[i], + states[i], + lifetime, + expiration + // + ); + + // + if (isExecuted) + { + result++; + } + else + { + // + AddRef( + signals[i], + notExecuteds // + ); + } + } + + // + return result; + } + + // + // Regular Trade Actions ... + + // + // Buy ... + + // + // Force Open a Buy/Long Position ... + bool Buy( + string symbol, // Specified Symbol + ENUM_TIMEFRAMES period, // Specified Trade's Period + double volume, // position volume + double price, // execution price + double sl = 0, // stop loss price + double tp = 0, // take profit price + string comment = NULL // comment + ) + { + // + bool result = false; + + // + ENUM_TIMEFRAMES mPeriod = ExtractPeriod(comment); + if (!IsValid(comment) || + !IsValid(mPeriod)) + { + // + string mPeriodStr = GeneratePeriodTag(period); + + // + comment += mPeriodStr; + } + + // + result = mTrader.Buy( + volume, + symbol, + price, + sl, + tp, + comment + // + ); + + // + return result; + } + + // + // Send BUY LIMIT order ... + bool BuyLimit( + string symbol, // Specified Symbol + ENUM_TIMEFRAMES period, // Specified Trade's Period + double volume, // order volume + double price, // order price + double sl = 0.0, // stop loss price + double tp = 0.0, // take profit price + ENUM_ORDER_TYPE_TIME typeTime = ORDER_TIME_GTC, // order lifetime + datetime expiration = 0, // order expiration time + string comment = NULL // comment + ) + { + // + bool result = false; + + // + ENUM_TIMEFRAMES mPeriod = ExtractPeriod(comment); + if (!IsValid(comment) || + !IsValid(mPeriod)) + { + // + string mPeriodStr = GeneratePeriodTag(period); + + // + comment += mPeriodStr; + } + + // + result = mTrader.BuyLimit( + volume, + price, + symbol, + sl, + tp, + typeTime, + expiration, + comment + // + ); + + // + return result; + } + + // + // Send BUY STOP order ... + bool BuyStop( + string symbol, // Specified Symbol + ENUM_TIMEFRAMES period, // Specified Trade's Period + double volume, // order volume + double price, // order price + double sl = 0.0, // stop loss price + double tp = 0.0, // take profit price + ENUM_ORDER_TYPE_TIME typeTime = ORDER_TIME_GTC, // order lifetime + datetime expiration = 0, // order expiration time + string comment = NULL // comment + ) + { + // + bool result = false; + + // + ENUM_TIMEFRAMES mPeriod = ExtractPeriod(comment); + if (!IsValid(comment) || + !IsValid(mPeriod)) + { + // + string mPeriodStr = GeneratePeriodTag(period); + + // + comment += mPeriodStr; + } + + // + result = mTrader.BuyStop( + volume, + price, + symbol, + sl, + tp, + typeTime, + expiration, + comment + // + ); + + // + return result; + } + + // + // Sell ... + + // + // Force Open a Sell/Short Position ... + bool Sell( + string symbol, // Specified Symbol + ENUM_TIMEFRAMES period, // Specified Trade's Period + double volume, // position volume + double price, // execution price + double sl = 0, // stop loss price + double tp = 0, // take profit price + string comment = NULL // comment + ) + { + // + bool result = false; + + // + ENUM_TIMEFRAMES mPeriod = ExtractPeriod(comment); + if (!IsValid(comment) || + !IsValid(mPeriod)) + { + // + string mPeriodStr = GeneratePeriodTag(period); + + // + comment += mPeriodStr; + } + + // + result = mTrader.Sell( + volume, + symbol, + price, + sl, + tp, + comment + // + ); + + // + return result; + } + + // + // Send SELL LIMIT order ... + bool SellLimit( + string symbol, // Specified Symbol + ENUM_TIMEFRAMES period, // Specified Trade's Period + double volume, // order volume + double price, // order price + double sl = 0.0, // stop loss price + double tp = 0.0, // take profit price + ENUM_ORDER_TYPE_TIME typeTime = ORDER_TIME_GTC, // order lifetime + datetime expiration = 0, // order expiration time + string comment = NULL // comment + ) + { + // + bool result = false; + + // + ENUM_TIMEFRAMES mPeriod = ExtractPeriod(comment); + if (!IsValid(comment) || + !IsValid(mPeriod)) + { + // + string mPeriodStr = GeneratePeriodTag(period); + + // + comment += mPeriodStr; + } + + // + result = mTrader.SellLimit( + volume, + price, + symbol, + sl, + tp, + typeTime, + expiration, + comment + // + ); + + // + return result; + } + + // + // Send SELL STOP order ... + bool SellStop( + string symbol, // Specified Symbol + ENUM_TIMEFRAMES period, // Specified Trade's Period + double volume, // order volume + double price, // order price + double sl = 0.0, // stop loss price + double tp = 0.0, // take profit price + ENUM_ORDER_TYPE_TIME typeTime = ORDER_TIME_GTC, // order lifetime + datetime expiration = 0, // order expiration time + string comment = NULL // comment + ) + { + // + bool result = false; + + // + ENUM_TIMEFRAMES mPeriod = ExtractPeriod(comment); + if (!IsValid(comment) || + !IsValid(mPeriod)) + { + // + string mPeriodStr = GeneratePeriodTag(period); + + // + comment += mPeriodStr; + } + + // + result = mTrader.SellStop( + volume, + price, + symbol, + sl, + tp, + typeTime, + expiration, + comment + // + ); + + // + return result; + } + + // + // Check a Position is Exists Open or not ... + bool IsOpen( + ulong ticket // Specified Position Ticket + ) + { + // + bool result = false; + + // + result = mPositionInfo + .SelectByTicket(ticket); + + // + return result; + } + + // + // Modify Position ... + bool Modify( + const ulong ticket, // position ticket + double sl = 0, // stop loss price + double tp = 0, // take profit + string comment = NULL // comment + ) + { + // + bool result = false; + + // + // Validate Args ... + XPosition position; + result = + GetPosition( + ticket, + position // + ) && + (tp >= 0 || sl >= 0); + if (!result) + { + return result; + } + + // + // Use Position Comment when there isn't new One ... + if (!IsValid(comment) == 0) + { + // + // if there isn't provided Comment + // Use Position Comment for default ... + comment = "Modify " + GetPositionComment(ticket); + } + + // + result = mTrader.PositionModify( + ticket, + sl, + tp, + comment + // + ); + if (result) + { + // + NotifyModifyEvent( + ticket, + position.profit, + comment // + ); + } + + // + return result; + } + + // + // Close Position By Ticket ... + bool Close( + ulong ticket, // Position Ticket + string comment = NULL // Close Position By Specific Comment + ) + { + // + bool result = false; + + // + // Check Position Open ... + XPosition position; + result = GetPosition( + ticket, + position // + ); + if (!result) + { + return result; + } + + // + // Use Default Position Comment if it's Not Provided ... + if (!IsValid(comment)) + { + comment = "Close " + GetPositionComment(ticket); + } + + // + // Close Position By Specific Comment ... + result = mTrader.PositionClose( + ticket, + mSlippage, + comment + // + ); + if (result) + { + // + NotifyForceCloseEvent( + ticket, + position, + comment // + ); + } + + // + return result; + } + + // + // Close Specified Positions ... + int Close( + string comment = NULL, // Close Position By Specific Comment + string symbol = NULL, // Trading Symbol + string provider = NULL, // Signal Provider + ENUM_TIMEFRAMES period = NULL, // Trading Period + ENUM_X_POSITION_TYPES type = NULL, // Long (Buy) or Short (Sell) + bool filterByMagic = true // Get Only Self Open Positions + ) + { + // + int result = 0; + + // + XPosition positions[]; + int positionsCount = GetPositions( + positions, + symbol, + provider, + period, + type, + filterByMagic); + if (positionsCount <= 0) + { + return result; + } + + // + for (int i = 0; i < positionsCount; i++) + { + // + XPosition iPosition = positions[i]; + + // + bool isClosed = Close( + iPosition.ticket, + comment + // + ); + if (isClosed) + { + result++; + } + } + + // + return result; + } + + // + // Close a Collection of Positions ... + int Close( + XPosition &positions[], // Collection of Positions + string comment // Close Comment + ) + { + // + int result = 0; + + // + int positionsCount = ArraySize(positions); + if (positionsCount <= 0) + { + return result; + } + + // + for (int i = 0; i < positionsCount; i++) + { + // + XPosition iPosition = positions[i]; + + // + bool isClosed = Close( + iPosition.ticket, + comment + // + ); + if (isClosed) + { + result++; + } + } + + // + return result; + } + + // + // Close Partial By Ticket ... + bool ClosePartial( + ulong ticket, // Position Ticket + double volume, // Volume Size for Partial Closing + string comment = NULL // Close Position By Specific Comment + ) + { + // + bool result = false; + + // + XPosition position; + result = GetPosition( + ticket, + position // + ); + if (!result) + { + return result; + } + + // + // Use Default Partial Close Comment ... + if (!IsValid(comment)) + { + // + comment += "PClose " + GetPositionComment(ticket); + } + + // + result = mTrader.PositionClosePartial( + ticket, + volume, + mSlippage, + comment + // + ); + if (result) + { + // + NotifyPartialCloseEvent( + ticket, + position.profit, + comment // + ); + } + + // + return result; + } + + // + // Cancel Specific Order ... + bool CancelOrder(ulong ticket) + { + return mTrader + .OrderDelete(ticket); + } + + // + // Cancel Specific Orders ... + int CancelOrders( + XOrder &orders[] // Specified Orders ... + ) + { + // + int result = 0; + + // + int ordersCount = ArraySize(orders); + if (ordersCount <= 0) + { + return result; + } + + // + for (int i = 0; i < ordersCount; i++) + { + // + XOrder iOrder = orders[i]; + + // + bool isDeleted = mTrader + .OrderDelete(iOrder.ticket); + if (isDeleted && !result) + { + result++; + } + } + + // + return result; + } + + // + // Extractors ... + + // + // Positions ... + + // + // Calculate Positions Profit ... + double Profit( + string symbol = NULL, // Trading Symbol + string provider = NULL, // Signal Provider + ENUM_TIMEFRAMES period = NULL, // Trading Period + ENUM_X_POSITION_TYPES type = NULL, // Long (Buy) or Short (Sell) + bool filterByMagic = true // Get Only Self Open Positions + ) + { + // + double result = 0; + + // + // Retrieve Positions ... + XPosition positions[]; + int positionsCount = GetPositions( + positions, + symbol, + provider, + period, + type, + filterByMagic + // + ); + if (positionsCount <= 0) + { + return result; + } + + // + for (int i = 0; i < positionsCount; i++) + { + result += positions[i].profit; + } + + // + return result; + } + + // + // Retrieve Specific Position by Index ... + bool GetPosition( + int index, // Specified Index + XPosition &result // Hold's Result + ) + { + // + bool isInited = result + .ByIndex(index); + + // + return isInited; + } + + // + // Retrieve Specific Position by Ticket ... + bool GetPosition( + ulong ticket, // Specified Ticket + XPosition &result // Hold's Result + ) + { + // + bool isInited = result + .ByTicket(ticket); + + // + return isInited; + } + + // + double GetPositionCommission( + ulong ticket // Specified Ticket + ) + { + // + double result = 0; + + // + XPosition position; + bool hasPosition = GetPosition( + ticket, + position // + ); + if (!hasPosition) + { + return result; + } + + // + XDeal deals[]; + int dealsCount = GetDeals( + deals, + position.symbol, + position.provider, + position.period, + NULL, + DEAL_ENTRY_IN // + ); + if (IsValidSize(dealsCount)) + { + // + for (int i = 0; i < dealsCount; i++) + { + // + XDeal iDeal = deals[i]; + if (iDeal.positionId == ticket) + { + // + result = iDeal.commission; + break; + } + } + } + + // + return result; + } + + // + // Retrieve Positions ... + int GetPositions( + XPosition &result[], // Hold's Result + string symbol = NULL, // Trading Symbol + string provider = NULL, // Signal Provider + ENUM_TIMEFRAMES period = NULL, // Trading Period + ENUM_X_POSITION_TYPES type = NULL, // Long (Buy) or Short (Sell) + bool filterByMagic = true, // Get Only Self Open Positions + bool forceClean = true // Clean Result Array + ) + { + // + int mResult = 0; + + // + int before = ArraySize(result); + + // + if (forceClean) + { + Clean(result); + } + + // + // Count Positions ... + int itemsCount = PositionsTotal(); + if (itemsCount <= 0) + { + return mResult; + } + + // + // Loop Through all Positions ... + for (int i = itemsCount - 1; i >= 0; i--) + { + // + XPosition iItem; + bool isLoaded = iItem.ByIndex(i); + if (!isLoaded) + { + continue; + } + + // + // Now we have to Check Given Filters ... + bool isFiltersPassed = + iItem.IsFiltersPassed( + symbol, + provider, + period, + type, + mMagicNumber, + filterByMagic + // + ); + if (!isFiltersPassed) + { + continue; + } + + // + // Add Filtered Item into Result ... + AddRef( + iItem, + result + // + ); + } + + // + int after = ArraySize(result); + + // + mResult = after - before; + + // + return mResult; + } + + // + void GetPositions( + XPosition &longs[], // Hold's Longs Result + XPosition &shorts[], // Hold's Shorts Result + string symbol = NULL, // Trading Symbol + string provider = NULL, // Signal Provider + ENUM_TIMEFRAMES period = NULL, // Trading Period + bool filterByMagic = true, // Get Only Self Open Positions + bool forceClean = true // Clean Result Array + ) + { + // + // Retrieve Long Positions ... + GetPositions( + longs, + symbol, + provider, + period, + X_POSITION_TYPE_LONG, + filterByMagic, + forceClean // + ); + + // + // Retrieve Short Positions ... + GetPositions( + shorts, + symbol, + provider, + period, + X_POSITION_TYPE_SHORT, + filterByMagic, + forceClean // + ); + } + + // + // Select In Profit Positions ... + int GetInProfitPositions( + XPosition &result[], // Hold's Result + string symbol = NULL, // Trading Symbol + string provider = NULL, // Signal Provider + ENUM_TIMEFRAMES period = NULL, // Trading Period + ENUM_X_POSITION_TYPES type = NULL, // Long (Buy) or Short (Sell) + ENUM_X_POSITION_SELECT_METHODS method = NULL, // Selection Method + bool filterByMagic = true, // Get Only Self Open Positions + bool forceClean = true // Clean Result Array + ) + { + // + int mResult = 0; + + // + int before = ArraySize(result); + + // + if (forceClean) + { + Clean(result); + } + + // + XPosition positions[]; + int positionsCount = GetPositions( + positions, + symbol, + provider, + period, + type, + filterByMagic, + forceClean); + if (positionsCount <= 0) + { + return mResult; + } + + // + XPosition min; + XPosition max; + + // + for (int i = 0; i < positionsCount; i++) + { + // + XPosition iPosition = positions[i]; + + // + if (iPosition.profit <= 0) + { + continue; + } + + // + // Calculate Min and Max ... + + // + // Min ... + if (!min.IsValid() || min.profit <= 0 || min.profit > iPosition.profit) + { + min = iPosition; + } + + // + // Max ... + if (!max.IsValid() || max.profit <= 0 || max.profit < iPosition.profit) + { + max = iPosition; + } + + // + bool isSelectionMethodFilterPassed = + // + (method == NULL || + method == X_POSITION_SELECT_ALL) + ? true + : false; + // + ; + if (!isSelectionMethodFilterPassed) + { + continue; + } + + // + AddRef( + iPosition, + result + // + ); + } + + // + if (min.IsValid() && + (method == X_POSITION_SELECT_MIN || + method == X_POSITION_SELECT_BOTH)) + { + // + AddRef( + min, + result + // + ); + } + + // + if (max.IsValid() && + (method == X_POSITION_SELECT_MAX || + method == X_POSITION_SELECT_BOTH)) + { + // + AddRef( + max, + result + // + ); + } + + // + int after = ArraySize(result); + + // + mResult = after - before; + + // + return mResult; + } + + // + // Select In Drawdown Positions ... + int GetInDrawdownPositions( + XPosition &result[], // Hold's Result + string symbol = NULL, // Trading Symbol + string provider = NULL, // Signal Provider + ENUM_TIMEFRAMES period = NULL, // Trading Period + ENUM_X_POSITION_TYPES type = NULL, // Long (Buy) or Short (Sell) + ENUM_X_POSITION_SELECT_METHODS method = NULL, // Selection Method + bool filterByMagic = true, // Get Only Self Open Positions + bool forceClean = true // Clean Result Array + ) + { + // + int mResult = 0; + + // + int before = ArraySize(result); + + // + if (forceClean) + { + Clean(result); + } + + // + XPosition positions[]; + int positionsCount = GetPositions( + positions, + symbol, + provider, + period, + type, + filterByMagic, + forceClean); + if (positionsCount <= 0) + { + return mResult; + } + + // + XPosition min; + XPosition max; + + // + for (int i = 0; i < positionsCount; i++) + { + // + XPosition iPosition = positions[i]; + + // + if (iPosition.profit >= 0) + { + continue; + } + + // + // Calculate Min and Max ... + + // + // Min ... + if (!min.IsValid() || min.profit <= 0 || min.profit > iPosition.profit) + { + min = iPosition; + } + + // + // Max ... + if (!max.IsValid() || max.profit <= 0 || max.profit < iPosition.profit) + { + max = iPosition; + } + + // + bool isSelectionMethodFilterPassed = + // + (method == NULL || + method == X_POSITION_SELECT_ALL) + ? true + : false; + // + ; + if (!isSelectionMethodFilterPassed) + { + continue; + } + + // + AddRef( + iPosition, + result + // + ); + } + + // + if (min.IsValid() && + (method == X_POSITION_SELECT_MIN || + method == X_POSITION_SELECT_BOTH)) + { + // + AddRef( + min, + result + // + ); + } + + // + if (max.IsValid() && + (method == X_POSITION_SELECT_MAX || + method == X_POSITION_SELECT_BOTH)) + { + // + AddRef( + max, + result + // + ); + } + + // + int after = ArraySize(result); + + // + mResult = after - before; + + // + return mResult; + } + + // + // Orders ... + + // + // Retrieve Specific Order by Index ... + bool GetOrder( + int index, // Specified Index + XOrder &result // Hold's Result + ) + { + // + return result + .ByIndex(index); + } + + // + // Retrieve Specific Positions Orders ... + int GetOrders( + ulong ticket, // Positions Ticket + XOrder &result[], // Hold's Result + bool forceClean = true // Clean Result Array + ) + { + // + int mResult = 0; + + // + // Select History by Specified Ticket ... + bool isHistorySelected = HistorySelectByPosition(ticket); + if (!isHistorySelected) + { + return mResult; + } + + // + int ordersCount = HistoryOrdersTotal(); + if (ordersCount <= 0) + { + return mResult; + } + + // + int before = ArraySize(result); + + // + if (forceClean) + { + Clean(result); + } + + // + for (int i = 0; i < ordersCount; i++) + { + // + XOrder iOrder; + bool isLoaded = iOrder.HistoryByIndex(i); + if (!isLoaded) + { + continue; + } + + // + bool isTicketFilterPassed = + // + iOrder.ticket = ticket + // + ; + if (!isTicketFilterPassed) + { + continue; + } + + // + AddRef( + iOrder, + result + // + ); + } + + // + int after = ArraySize(result); + + // + mResult = after - before; + + // + return mResult; + } + + // + // Retrieve All Orders ... + int GetOrders( + XOrder &result[], // Hold's Result + string symbol = NULL, // Trading Symbol + string provider = NULL, // Signal Provider + ENUM_TIMEFRAMES period = NULL, // Trading Period + ENUM_X_POSITION_TYPES type = NULL, // Long (Buy) or Short (Sell) + ENUM_ORDER_STATE state = NULL, // Order State + bool filterByMagic = true, // Get Only Self Open Positions + bool forceClean = true // Clean Result Array + ) + { + // + int mResult = 0; + + // + int before = ArraySize(result); + + // + if (forceClean) + { + Clean(result); + } + + // + // Count Positions ... + int itemsCount = OrdersTotal(); + if (itemsCount <= 0) + { + return mResult; + } + + // + // Loop Through all Positions ... + for (int i = itemsCount - 1; i >= 0; i--) + { + // + XOrder iItem; + bool isLoaded = iItem.ByIndex(i); + if (!isLoaded) + { + continue; + } + + // + // Now we have to Check Given Filters ... + bool isFiltersPassed = + iItem.IsFiltersPassed( + symbol, + provider, + period, + type, + state, + mMagicNumber, + filterByMagic + // + ); + if (!isFiltersPassed) + { + continue; + } + + // + // Add Filtered Item into Result ... + AddRef( + iItem, + result + // + ); + } + + // + int after = ArraySize(result); + + // + mResult = after - before; + + // + return mResult; + } + + // + // Retrieve Historical Orders ... + int GetOrders( + XOrder &result[], // Hold's Result + string symbol = NULL, // Trading Symbol + string provider = NULL, // Signal Provider + ENUM_TIMEFRAMES period = NULL, // Trading Period + ENUM_X_POSITION_TYPES type = NULL, // Long (Buy) or Short (Sell) + ENUM_ORDER_STATE state = NULL, // Order State + datetime startDate = NULL, // Specify Start Date + datetime endDate = NULL, // Specify End Date + bool filterByMagic = true, // Get Only Self Open Positions + bool forceClean = true // Clean Result Array + ) + { + // + int mResult = 0; + + // + endDate = NormalizeTime(endDate); + + // + if (!IsValid(startDate)) + { + startDate = endDate - PeriodSeconds(PERIOD_D1); + } + + // + bool isHistorySelected = HistorySelect( + startDate, + endDate); + if (!isHistorySelected) + { + return mResult; + } + + // + int before = ArraySize(result); + + // + if (forceClean) + { + Clean(result); + } + + // + // Count Positions ... + int itemsCount = OrdersTotal(); + if (itemsCount <= 0) + { + return mResult; + } + + // + // Loop Through all Positions ... + for (int i = itemsCount - 1; i >= 0; i--) + { + // + XOrder iItem; + bool isLoaded = iItem.HistoryByIndex(i); + if (!isLoaded) + { + continue; + } + + // + // Now we have to Check Given Filters ... + bool isFiltersPassed = + iItem.IsFiltersPassed( + symbol, + provider, + period, + type, + state, + mMagicNumber, + filterByMagic + // + ); + if (!isFiltersPassed) + { + continue; + } + + // + // Add Filtered Item into Result ... + AddRef( + iItem, + result + // + ); + } + + // + int after = ArraySize(result); + + // + mResult = after - before; + + // + return mResult; + } + + // + // Deals ... + + // + // Retrieve Specific Deal by Index ... + bool GetDeal( + int index, // Specified Index + XDeal &result // Hold's Result + ) + { + // + return result + .ByIndex(index); + } + + // + bool GetLastDeal( + XDeal &result // Hold's Result + ) + { + // + bool mResult = false; + + // + mResult = HistorySelect(0, TimeCurrent()); + if (!mResult) + { + return mResult; + } + + // + int lastDealIndex = HistoryDealsTotal() - 1; + + // + mResult = GetDeal( + lastDealIndex, + result // + ); + + // + return mResult; + } + + // + // Retrieve Specified Deal's History ... + int GetDealsHistory( + XDeal &deal, // Specified Deal + XOrder &history[], // Deals History + bool forceClean = true // Clean Result Array + ) + { + // + int result = 0; + + // + if (!deal.IsValid()) + { + return result; + } + + // + result = GetOrders( + deal.positionId, + history, + forceClean); + + // + return result; + } + + // + // Retrieve All Deals ... + int GetDeals( + XDeal &result[], // Hold's Result + string symbol = NULL, // Trading Symbol + string provider = NULL, // Signal Provider + ENUM_TIMEFRAMES period = NULL, // Trading Period + ENUM_DEAL_TYPE type = NULL, // Deal Type + ENUM_DEAL_ENTRY entry = NULL, // Deal Entry + ENUM_DEAL_REASON reason = NULL, // Deal Reason + datetime startDate = NULL, // Specify Start Date + datetime endDate = NULL, // Specify End Date + bool filterByMagic = true, // Get Only Self Open Positions + bool forceClean = true // Clean Result Array + ) + { + // + int mResult = 0; + + // + endDate = NormalizeTime(endDate); + + // + if (!IsValid(startDate)) + { + startDate = endDate - PeriodSeconds(PERIOD_D1); + } + + // + bool isHistorySelected = HistorySelect( + startDate, + endDate); + if (!isHistorySelected) + { + return mResult; + } + + // + int before = ArraySize(result); + + // + if (forceClean) + { + Clean(result); + } + + // + // Count Positions ... + int itemsCount = HistoryDealsTotal(); + if (itemsCount <= 0) + { + return mResult; + } + + // + // Loop Through all Positions ... + for (int i = itemsCount - 1; i >= 0; i--) + { + // + XDeal iItem; + bool isLoaded = iItem.ByIndex(i); + if (!isLoaded) + { + continue; + } + + // + // Now we have to Check Given Filters ... + bool isFiltersPassed = + iItem.IsFiltersPassed( + symbol, + provider, + period, + type, + entry, + reason, + mMagicNumber, + filterByMagic + // + ); + if (!isFiltersPassed) + { + continue; + } + + // + // Add Filtered Item into Result ... + AddRef( + iItem, + result + // + ); + } + + // + int after = ArraySize(result); + + // + mResult = after - before; + + // + return mResult; + } + + // + // Support Functions ... + + // + // Check a Position has Support or not ... + bool HasSupport( + ulong ticket, + bool forceOpen = true // + ) + { + // + bool result = false; + + // + result = ticket > 0; + if (!result) + { + return result; + } + + // + if (forceOpen) + { + // + result = IsOpen(ticket); + if (!result) + { + return result; + } + } + + // + XPosition positions[]; + int positionsCount = GetPositions(positions); + result = IsValidSize(positionsCount); + if (!result) + { + return result; + } + + // + // Extract Support Positions ... + XPosition supports[]; + int supportsCount = ExtractSupports( + positions, + supports // + ); + result = IsValidSize(supportsCount); + if (!result) + { + return result; + } + + // + // Loop Through Supports ... + for (int i = 0; i < supportsCount; i++) + { + // + XPosition iSupport = supports[i]; + + // + ulong supportedTicket = ExtractSupportedTicket(iSupport.comment); + ulong eqmSupportedTicket = ExtractEQMSupportedTicket(iSupport.comment); + + // + result = + // + (supportedTicket > 0 && ticket == supportedTicket) + // + || + // + (eqmSupportedTicket > 0 && ticket == eqmSupportedTicket) + // + ; + if (result) + { + break; + } + } + + // + return result; + } + + // + // Retrieve Specific Position's Supports ... + int GetSupports( + ulong ticket, + XPosition &dest[], // Result ... + bool forceOpen = true // + ) + { + // + int result = 0; + + // + Clean(dest); + + // + bool hasSupport = HasSupport( + ticket, + forceOpen // + ); + if (!hasSupport) + { + return result; + } + + // + XPosition positions[]; + int positionsCount = GetPositions(positions); + if (!IsValidSize(positionsCount)) + { + return result; + } + + // + // Extract Support Positions ... + XPosition supports[]; + int supportsCount = ExtractSupports( + positions, + supports // + ); + if (!IsValidSize(supportsCount)) + { + return result; + } + + // + // Loop Through Supports ... + for (int i = 0; i < supportsCount; i++) + { + // + XPosition iSupport = supports[i]; + + // + ulong supportedTicket = ExtractSupportedTicket(iSupport.comment); + ulong eqmSupportedTicket = ExtractEQMSupportedTicket(iSupport.comment); + + // + bool isOwn = + // + (supportedTicket > 0 && ticket == supportedTicket) + // + || + // + (eqmSupportedTicket > 0 && ticket == eqmSupportedTicket) + // + ; + if (isOwn) + { + // + AddRef( + iSupport, + dest // + ); + } + } + + // + result = ArraySize(dest); + + // + return result; + } + + // + // Retrieve Specific Position's Supports ... + int GetSupports( + ulong ticket, + XOrder &dest[], // Result ... + bool forceOpen = true // + ) + { + // + int result = 0; + + // + Clean(dest); + + // + bool hasSupport = HasSupport( + ticket, + forceOpen // + ); + if (!hasSupport) + { + return result; + } + + // + XOrder orders[]; + int ordersCount = GetOrders( + orders, + NULL, // All Symbols ... + NULL, // All Providers ... + NULL, // All Periods ... + X_POSITION_TYPE_ALL, // All Types ... + ORDER_STATE_PLACED, // Untriggere Orders ... + true // + ); + if (!IsValidSize(ordersCount)) + { + return result; + } + + // + // Extract Support Positions ... + XOrder supports[]; + int supportsCount = ExtractSupports( + orders, + supports // + ); + if (!IsValidSize(supportsCount)) + { + return result; + } + + // + // Loop Through Supports ... + for (int i = 0; i < supportsCount; i++) + { + // + XOrder iSupport = supports[i]; + + // + ulong supportedTicket = ExtractSupportedTicket(iSupport.comment); + ulong eqmSupportedTicket = ExtractEQMSupportedTicket(iSupport.comment); + + // + bool isOwn = + // + (supportedTicket > 0 && ticket == supportedTicket) + // + || + // + (eqmSupportedTicket > 0 && ticket == eqmSupportedTicket) + // + ; + if (isOwn) + { + // + AddRef( + iSupport, + dest // + ); + } + } + + // + result = ArraySize(dest); + + // + return result; + } + + // + // Tools ... + + // + // Retrieve Last Open Position Ticket ... + ulong GetLastOpenPositionTicket() + { + // + ulong result = 0; + + int positionsCount = PositionsTotal(); + if (positionsCount <= 0) + { + return result; + } + + // + result = PositionGetTicket(PositionsTotal() - 1); + + // + return result; + } + + // + // Retrieve Last Placed Order Ticket ... + ulong GetLastPlacedOrderTicket() + { + // + ulong result = 0; + + int ordersCount = OrdersTotal(); + if (ordersCount <= 0) + { + return result; + } + + // + if (mOrderInfo.SelectByIndex(ordersCount - 1)) + { + result = mOrderInfo.Ticket(); + } + + // + return result; + } + + // + // Prepare Dynamic Volume ... + double GetDynamicVolume( + string _symbol, + double _balanceFactor, + double _volumeStep // + ) + { + // + double result = 0; + + // + // Validate Inputs ... + if (!IsValid(_symbol) || + _volumeStep <= 0 || + _balanceFactor <= 0) + { + return result; + } + + // + // Retrieve Account Balance ... + double balance = mAccount.GetBalance(); + + // + double bStep = balance / _balanceFactor; + bStep = MathFloor(bStep); + if (bStep == 0) + { + bStep = 1; + } + + // + result = bStep * _volumeStep; + + // + result = NormalizeVolume( + result, + _symbol // + ); + + // + return result; + } + + // + // Protected ... + protected: + // + // Props ... + + // + // Event Listener Notifiers ... + + // + // State ... + void NotifyTradeStateChangeEvent(const XOnTradeHandlerState &state) + { + // + int count = ArraySize(mTradeStateChangedEventHandlers); + if (count <= 0) + { + return; + } + + // + for (int i = 0; i < count; i++) + { + // + TOnTradeStateChanged iHandler = mTradeStateChangedEventHandlers[i]; + iHandler(state); + } + } + + // + // Deals ... + void NotifyDealsChangeEvent(int changes) + { + // + int count = ArraySize(mDealsChangedEventHandlers); + if (count <= 0) + { + return; + } + + // + for (int i = 0; i < count; i++) + { + // + TOnDealsChanged iHandler = mDealsChangedEventHandlers[i]; + iHandler(changes); + } + } + + // + // Orders ... + void NotifyOrdersChangeEvent(int changes) + { + // + int count = ArraySize(mOrdersChangedEventHandlers); + if (count <= 0) + { + return; + } + + // + for (int i = 0; i < count; i++) + { + // + TOnOrdersChanged iHandler = mOrdersChangedEventHandlers[i]; + iHandler(changes); + } + } + + // + // Positions ... + void NotifyPositionsChangeEvent(int changes) + { + // + int count = ArraySize(mPositionsChangedEventHandlers); + if (count <= 0) + { + return; + } + + // + for (int i = 0; i < count; i++) + { + // + TOnPositionsChanged iHandler = mPositionsChangedEventHandlers[i]; + iHandler(changes); + } + } + + // + // StopLoss ... + void NotifyStopLossEvent(const XDeal &deal) + { + // + int count = ArraySize(mStopLossEventHandlers); + if (count <= 0) + { + return; + } + + // + for (int i = 0; i < count; i++) + { + // + TOnStopLoss iHandler = mStopLossEventHandlers[i]; + iHandler(deal); + } + } + + // + // Take Profit ... + void NotifyTakeProfitEvent(const XDeal &deal) + { + // + int count = ArraySize(mTakeProfitEventHandlers); + if (count <= 0) + { + return; + } + + // + for (int i = 0; i < count; i++) + { + // + TOnTakeProfit iHandler = mTakeProfitEventHandlers[i]; + iHandler(deal); + } + } + + // + void NotifyModifyEvent( + ulong ticket, + double profit, + string comment // + ) + { + // + int count = ArraySize(mOnModifyEventHandlers); + if (count <= 0) + { + return; + } + + // + for (int i = 0; i < count; i++) + { + // + TOnModify iHandler = mOnModifyEventHandlers[i]; + iHandler( + ticket, + profit, + comment // + ); + } + } + + // + void NotifyForceCloseEvent( + ulong ticket, + XPosition &position, + string comment // + ) + { + // + int count = ArraySize(mOnForceCloseEventHandlers); + if (count <= 0) + { + return; + } + + // + for (int i = 0; i < count; i++) + { + // + TOnForceClose iHandler = mOnForceCloseEventHandlers[i]; + iHandler( + ticket, + position, + comment // + ); + } + } + + // + void NotifyPartialCloseEvent( + ulong ticket, + double profit, + string comment // + ) + { + // + int count = ArraySize(mOnPartialCloseEventHandlers); + if (count <= 0) + { + return; + } + + // + for (int i = 0; i < count; i++) + { + // + TOnModify iHandler = mOnPartialCloseEventHandlers[i]; + iHandler( + ticket, + profit, + comment // + ); + } + } + + // + // Tools ... + + // + // Retrieve Specified Position Comment ... + string GetPositionComment(ulong ticket) + { + // + string result = NULL; + + // + if (!IsOpen(ticket)) + { + return result; + } + + // + XPosition position; + bool isLoaded = position.ByTicket(ticket); + if (!isLoaded) + { + return result; + } + + // + result = position.comment; + + // + return result; + } + + // + ENUM_TIMEFRAMES GetDealPeriod(XDeal &deal) + { + // + ENUM_TIMEFRAMES result = NULL; + + // + XOrder orders[]; + int ordersCount = GetDealsHistory( + deal, + orders); + if (!ordersCount) + { + return result; + } + + // + for (int i = 0; i < ordersCount; i++) + { + // + XOrder iOrder = orders[i]; + + // + if (IsValid(iOrder.comment)) + { + // + ENUM_TIMEFRAMES iPeriod = ExtractPeriod(iOrder.comment); + if (IsValid(iPeriod)) + { + result = iPeriod; + break; + } + } + } + + // + return result; + } + + // + double GetMaxAllowedEquity() + { + // + double equity = mAccount.GetEquity(); + double balance = mAccount.GetBalance(); + + // + double balanceForFactor = MathAbs(equity - balance); + if (balanceForFactor <= 0) + { + balanceForFactor = balance; + } + else + { + balanceForFactor = equity; + } + + // + double result = balanceForFactor * mMaxAllowedDrawdownFactor; + + // + return result; + } + + // + // Private ... + private: + // + // Props ... + + // + int mSlippage; // Slippage ... + ulong mMagicNumber; // Magic Number (Unique Identifier) ... + + // + double mMaxAllowedSpread; // Max Allowed Spred for Opening Trades + int mMaxAllowedPositions; // Max Allowed Same Positions + double mMaxAllowedDrawdownFactor; // Max Allowed Drawdown Factor + + // + XCTradeBase *mTrader; // Base CTrade Manipulated Instance ... + + // + CDealInfo mDealInfo; // Deals Info ... + COrderInfo mOrderInfo; // Order Info ... + CPositionInfo mPositionInfo; // Positions Info + CHistoryOrderInfo mHistoryOrderInfo; // History Orders Info ... + + // + // Position Info Collector ... + + // + // Tools ... + + // + // OnTrade Event Handlers Section ... + + // + // Props ... + + // + int mDaysForRead; // Reading Dates for Trade History Checker ... + datetime mEndDate; // End Date for Trade history Checking ... + datetime mStartDate; // Start Date for Trade history Checking ... ... + int mOrdersCount; // Number of Active orders ... + int mPositionsCount; // Number of Open positions ... + int mDealsCount; // Number of Deals in the Trade History Checking ... + int mHistoryOrdersCount; // Number of Orders in the Trade History Checking ... + bool mScanStarted; // a Flag of counter relevance ... + + // + // Event Listeners ... + + // + // Deals Changed Event Handlers ... + TOnDealsChanged mDealsChangedEventHandlers[]; + + // + // Orders Changed Event Handlers ... + TOnOrdersChanged mOrdersChangedEventHandlers[]; + + // + // Positions Changed Event Handlers ... + TOnPositionsChanged mPositionsChangedEventHandlers[]; + + // + // Trade State Changed Event Handlers ... + TOnTradeStateChanged mTradeStateChangedEventHandlers[]; + + // + TOnModify mOnModifyEventHandlers[]; + TOnForceClose mOnForceCloseEventHandlers[]; + TOnPartialClose mOnPartialCloseEventHandlers[]; + + // + // TPSL ... + TOnStopLoss mStopLossEventHandlers[]; + TOnTakeProfit mTakeProfitEventHandlers[]; + + // + // Reset On Trade Scanner Context ... + void ResetOnTradeContext() + { + // + mEndDate = TimeCurrent(); + mStartDate = mEndDate - (mDaysForRead * PeriodSeconds(PERIOD_D1)); + } + + // + // Initial Context Of Trade Scanner ... + void InitOnTradeContext() + { + // + ResetLastError(); + + // + mOrdersCount = OrdersTotal(); + mPositionsCount = PositionsTotal(); + + // + // load history ... + bool selected = HistorySelect(mStartDate, mEndDate); + if (!selected) + { + return; + } + + // + // get the current value ... + mDealsCount = HistoryDealsTotal(); + mHistoryOrdersCount = HistoryOrdersTotal(); + + // + mScanStarted = true; + } + + // + // Check Statrt Date In Trade History ... + void CheckStartDateInTradeHistory() + { + // + // initial interval, if we were to start working right now .. + datetime currStart = TimeCurrent() - (mDaysForRead * PeriodSeconds(PERIOD_D1)); + + // + // make sure that the start limit of the trade history has not gone + // more than 1 day over the intended date ... + if (currStart - mStartDate > PeriodSeconds(PERIOD_D1)) + { + // + // correct the start date of history to be loaded in the cache ... + mStartDate = currStart; + + // + // now reload the trade history for the updated interval ... + HistorySelect(mStartDate, mEndDate); + + // + // correct the deal and order counters in history for further comparison + mHistoryOrdersCount = HistoryOrdersTotal(); + mDealsCount = HistoryDealsTotal(); + } + } + + // + // Process On Trade Context ... + void ProcessOnTradeContext( + XOnTradeHandlerState &result // Hold's Result + ) + { + // + mEndDate = TimeCurrent(); + + // + ResetLastError(); + + // + // download trading history from the specified interval to the program cache ... + bool selected = HistorySelect(mStartDate, mEndDate); + if (!selected) + { + return; + } + + // + // get the current values ... + int currOrders = OrdersTotal(); + int currPositions = PositionsTotal(); + int currDeals = HistoryDealsTotal(); + int currHistoryOrders = HistoryOrdersTotal(); + + // + // Orders ... + // check if the number of active orders has been changed ... + if (currOrders != mOrdersCount) + { + // + // number of active orders has been changed ... + result.hasNewOrder = true; + result.newOrders = currOrders - mOrdersCount; + + // + // update the value ... + mOrdersCount = currOrders; + } + + // + // Positions ... + // changes in the number of open positions ... + if (currPositions != mPositionsCount) + { + // + // number of open positions has been changed ... + result.hasNewPosition = true; + result.newPositions = currPositions - mPositionsCount; + + // + // update the value ... + mPositionsCount = currPositions; + } + + // + // Deals ... + // changes in the number of deals in the trade history cache ... + if (currDeals != mDealsCount) + { + // + // number of deals in the trade history cache has been changed ... + result.hasNewDeal = true; + result.newDeals = currDeals - mDealsCount; + + // + // update the value ... + mDealsCount = currDeals; + } + + // + // History Orders ... + // changes in the number of history orders in the trade history cache ... + if (currHistoryOrders != mHistoryOrdersCount) + { + // + // number of history orders in the trade history cache has been changed ... + result.hasNewHistoryOrder = true; + result.newHistoryOrders = currHistoryOrders - mHistoryOrdersCount; + + // + // update the value ... + mHistoryOrdersCount = currHistoryOrders; + } + + // + // checking if it is necessary to change the limits of the trade history to be requested in cache ... + CheckStartDateInTradeHistory(); + } +}; + +// \ No newline at end of file diff --git a/BKPS/14040203/Classes/x-saherelm.x-volume.class.mq5 b/BKPS/14040203/Classes/x-saherelm.x-volume.class.mq5 new file mode 100644 index 0000000..09720c3 --- /dev/null +++ b/BKPS/14040203/Classes/x-saherelm.x-volume.class.mq5 @@ -0,0 +1,792 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Class Library +// -------------------------------------- +// Name: XCVolume +// Description: provides all Requirements for Volume Managing ... +// +// +// 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 + +// +// Template Variables of Inputs for Using ... +// input group "Volume"; +// input ENUM_X_VOLUME_SELECT_TYPE eaVolumeSelect = X_VOLUME_STATIC; // Volume Applying Type +// input double eaStaticVoluem = X_MIN_VOLUME; // Static Volume +// input double eaDynamicVolumeStepBalance = 0.0; // Step of Balance for Increase Volume +// input double eaDynamicVolumeStepVolume = X_MIN_VOLUME; // Step of Volume Increasing +// input double eaConstantRiskBalance = 0.0; // Constant Risk Balance per Trade +// input double eaConstantPercent = 0.0; // Constant Percent of Balance Per Trade +// input double eaConstantBalance = 0.0; // Constant Balance for Calculations +// XCVolume *eaVolume; +// eaVolume = new XCVolume(); +// bool result = eaVolume.Init( +// eaVolumeSelect, +// eaStaticVoluem, +// eaDynamicVolumeStepBalance, +// eaDynamicVolumeStepVolume, +// eaConstantRiskBalance, +// eaConstantPercent, +// eaConstantBalance // +// ); +// if (!result) { +// return INIT_FAILED; +// } + +// +// Imports ... +#include "../Classes/x-saherelm.x-account.class.mq5" +#include "../Libraries/x-saherelm.x-trade.lib.mq5" + +// +// Definitions ... +#define X_MIN_VOLUME 0.01 + +// +enum ENUM_X_VOLUME_SELECT_TYPE +{ + X_VOLUME_NONE, // None + X_VOLUME_STATIC, // Static Volume + X_VOLUME_CURRENT, // Current Balance + X_VOLUME_EQUITY, // Current Equity + X_VOLUME_CONSTANT // Constant Value +}; + +// +bool IsValid(ENUM_X_VOLUME_SELECT_TYPE value) +{ + // + bool result = false; + + // + result = value != X_VOLUME_NONE; + + // + return result; +} + +// +string ToString(ENUM_X_VOLUME_SELECT_TYPE value) +{ + // + string result = NULL; + + // + result = EnumToString(value); + + // + return result; +} + +// +// Implementation ... +class XCVolume : public XCBase +{ + // + // Public ... + public: + // + // Props ... + XCAccount *account; + + // + // Constructor ... + XCVolume() + { + // + account = new XCAccount(); + + // + Default(); + } + + // + // Deconstructor ... + ~XCVolume() + { + // + ZeroMemory(account); + } + + // + bool Init( + ENUM_X_VOLUME_SELECT_TYPE _SelectType, + double _StaticVolume, + double _DynamicVolumeStepBalance, + double _DynamicVolumeStepVolume, + double _ConstantRiskBalance, + double _ConstantPercent, + double _ConstantBalance // + ) + { + // + bool result = false; + + // + mVolumeType = _SelectType; + mStaticVolume = _StaticVolume; + mConstantPercent = _ConstantPercent; + mConstantBalance = _ConstantBalance; + mConstantRiskBalance = _ConstantRiskBalance; + mDynamicVolumeStepVolume = _DynamicVolumeStepVolume; + mDynamicVolumeStepBalance = _DynamicVolumeStepBalance; + + // + result = + // + CanUseStaticVolume() || + CanUseDynamicVolume() || + CanUseConstantRiskBalance() || + CanUseConstantBalancePercent() + // + ; + + // + return result; + } + + // + // Prperties ... + + /** + * Get Volume Calculating Method ... + * + * @return (ENUM_X_VOLUME_SELECT_TYPE) + */ + ENUM_X_VOLUME_SELECT_TYPE VolumeType() + { + return mVolumeType; + } + + /** + * Set Volume Calculating Method ... + * + * @param value: ENUM_X_VOLUME_SELECT_TYPE member ... + */ + void VolumeType(ENUM_X_VOLUME_SELECT_TYPE value) + { + mVolumeType = value; + } + + /** + * Get Static Volume ... + * + * @return ( double ) + */ + double StaticVolume() + { + return mStaticVolume; + } + + /** + * Set Static Volume ... + * + * @param value: double + */ + void StaticVolume(double value) + { + // + value = NormalizeDouble(value, 0.01, 1); + + // + mStaticVolume = value; + } + + /** + * Get Dynamic Volume Step Balance ... + * used to Calculate Final Lottage ... + * + * @return ( double ) + */ + double DynamicVolumeStepBalance() + { + return mDynamicVolumeStepBalance; + } + + /** + * Set Dynamic Volume Step Balance ... + * used to Calculate Final Lottage ... + * + * @param value: Argument 1 + */ + void DynamicVolumeStepBalance(double value) + { + // + value = NormalizeDouble(value, 0); + + // + mDynamicVolumeStepBalance = value; + } + + /** + * Get Dynamic Volume Step Volume ... + * used to Calculate Final Lottage ... + * how much increase Final Volume based oBalance Step ... + * + * @return ( double ) + */ + double DynamicVolumeStepVolume() + { + return mDynamicVolumeStepVolume; + } + + /** + * Get Dynamic Volume Step Volume ... + * used to Calculate Final Lottage ... + * how much increase Final Volume based oBalance Step ... + * + * @param value: double + */ + void DynamicVolumeStepVolume(double value) + { + // + value = NormalizeDouble(value, 0.01, 0.1); + + // + mDynamicVolumeStepVolume = value; + } + + /** + * Get Constant Balance Use for Dyamic Volume Calculation ... + * + * @return ( double ) + */ + double ConstantBalance() + { + return mConstantBalance; + } + + /** + * Set Constant Balance Use for Dyamic Volume Calculation ... + * + * @param value: Argument 1 + */ + void ConstantBalance(double value) + { + // + value = NormalizeDouble(value, 0); + + // + mConstantBalance = value; + } + + /** + * Get Constant Risk Value Based on Account Currency ... + * + * @return ( double ) + */ + double ConstantRiskBalance() + { + return mConstantRiskBalance; + } + + /** + * Get Constant Risk Value Based on Account Currency ... + * + * @param value: double + */ + void ConstantRiskBalance(double value) + { + // + value = NormalizeDouble(value, 0); + + // + mConstantRiskBalance = value; + } + + /** + * Get Constant Percent Based On Selected Balance ... + * + * @return ( double ) + */ + double ConstantPercent() + { + return mConstantPercent; + } + + /** + * Set Constant Percent Based On Selected Balance ... + * + * @param value: double ... + */ + void ConstantPercent(double value) + { + // + value = NormalizeDouble(value, 0, 100); + + // + mConstantPercent = value; + } + + // + // Tools ... + + /** + * Retrieve Balance based on Provided Volume Type ... + * + * @return ( double ) + */ + double GetBalance() + { + // + double result = 0; + + // + if (!IsValid(mVolumeType)) + { + return result; + } + + // + if (mConstantBalance > 0 && + mVolumeType == X_VOLUME_CONSTANT) + { + result = mConstantBalance; + } + else if (mVolumeType == X_VOLUME_CURRENT) + { + result = account.GetBalance(); + } + else if (mVolumeType == X_VOLUME_EQUITY) + { + result = account.GetEquity(); + } + + // + return result; + } + + /** + * Retrieve Balance based on Provided Volume Type ... + * + * @return ( double ) + */ + double GetBalance(ENUM_X_VOLUME_SELECT_TYPE type) + { + // + double result = 0; + + // + if (!IsValid(type)) + { + return result; + } + + // + if (mConstantBalance > 0 && + type == X_VOLUME_CONSTANT) + { + result = mConstantBalance; + } + else if (type == X_VOLUME_CURRENT) + { + result = account.GetBalance(); + } + else if (type == X_VOLUME_EQUITY) + { + result = account.GetEquity(); + } + + // + return result; + } + + /** + * Calculate Volume Based On Given Configuration ... + * + * @param symbol: string, Trading Symbol ... + * @param entry: double, Entry Price ... + * @param sl: double, Stop Loss Price ... + * + * @return ( double ) + */ + double CalculateVolume( + string symbol, + double entry, + double sl // + ) + { + // + double result = X_MIN_VOLUME; + + // + bool has = false; + + // + // Validate Args ... + has = + sl > 0 && + entry > 0 && + IsValid(symbol); + if (!has) + { + return result; + } + + // + // Retrieve Balance Type ... + double balance = GetBalance(); + double points = GetPoints(symbol); + double riskPrice = MathAbs(entry - sl); + double riskInPoints = riskPrice / points; + + // + has = CanUseStaticVolume(); + if (has) + { + result = mStaticVolume; + } + + // + has = CanUseDynamicVolume(); + if (has) + { + // + double multiplier = balance / mDynamicVolumeStepBalance; + if (multiplier < 0) + { + multiplier = 1; + } + + // + result = multiplier * mDynamicVolumeStepVolume; + } + + // + has = CanUseConstantRiskBalance(); + if (has) + { + // + result = account.CalculateVolume( + symbol, + mConstantRiskBalance, + riskInPoints // + ); + } + + // + has = CanUseConstantBalancePercent(); + if (has) + { + // + double riskAmountPerBalance = (mConstantPercent * balance) / 100; + + // + result = account.CalculateVolume( + symbol, + riskAmountPerBalance, + riskInPoints // + ); + } + + // + if (result < X_MIN_VOLUME) + { + result = X_MIN_VOLUME; + } + + // + // Normalize Volume ... + result = NormalizeVolume(result, symbol); + + // + return result; + } + + /** + * Calculate Volume Based On Given Configuration ... + * + * @param signal: XSignal instance reference, provided required Data ... + * + * @return ( double ) + */ + double CalculateVolume(XSignal &signal) + { + // + double result = X_MIN_VOLUME; + + // + if (!signal.IsValid()) + { + return result; + } + + // + result = CalculateVolume( + signal.symbol, + signal.entry, + signal.sl // + ); + + // + return result; + } + + /** + * Calculate Specified Percent of Selected Balance for Volume ... + * + * @param percent: double, percent of Balance Risking ... + * @param symbol: string, Trading Symbol ... + * @param entry: double, Entry Price ... + * @param sl: double Stop Loss Price ... + * + * @return ( double ) + */ + double CalculateVolume( + ENUM_X_VOLUME_SELECT_TYPE selectType, + double percent, + string symbol, + double entry, + double sl // + ) + { + // + double result = X_MIN_VOLUME; + + // + bool has = false; + + // + // Validate Args ... + has = + sl > 0 && + entry > 0 && + percent > 0 && + IsValid(symbol) && + IsValid(selectType) && + (selectType == X_VOLUME_EQUITY || + selectType == X_VOLUME_CURRENT); + if (!has) + { + return result; + } + + // + // Retrieve Balance Type ... + double points = GetPoints(symbol); + double riskPrice = MathAbs(entry - sl); + double balance = GetBalance(selectType); + double riskInPoints = riskPrice / points; + + // + double riskAmountPerBalance = (percent * balance) / 100; + + // + result = account.CalculateVolume( + symbol, + riskAmountPerBalance, + riskInPoints // + ); + + // + return result; + } + + // + // Protected ... + protected: + // + // Tools ... + + /** + * Set Default Props ... + */ + void Default() + { + // + VolumeType(X_VOLUME_STATIC); + StaticVolume(0.01); + + // + ConstantBalance(0); + ConstantPercent(0); + ConstantRiskBalance(0); + + // + DynamicVolumeStepBalance(0); + DynamicVolumeStepVolume(0.01); + } + + /** + * Check Configuration is Valid For Static Volume ... + * + * @return ( bool ) + */ + bool CanUseStaticVolume() + { + // + bool result = false; + + // + result = IsValid(mVolumeType); + if (!result) + { + return result; + } + + // + // Static Volume ... + result = + // + mVolumeType == X_VOLUME_STATIC && + mStaticVolume > 0 && + // + mDynamicVolumeStepBalance == 0 && + // + mConstantBalance == 0 && + mConstantPercent == 0 && + mConstantRiskBalance == 0 + // + ; + + // + return result; + } + + /** + * Check Configuration is Valid For Dynamic Volume ... + * + * @return ( bool ) + */ + bool CanUseDynamicVolume() + { + // + bool result = false; + + // + result = IsValid(mVolumeType); + if (!result) + { + return result; + } + + // + result = + // + (mVolumeType == X_VOLUME_CURRENT || + mVolumeType == X_VOLUME_EQUITY || + (mVolumeType == X_VOLUME_CONSTANT && + mConstantBalance > 0)) && + // + mDynamicVolumeStepBalance > 0 && + mDynamicVolumeStepVolume > 0 && + // + mStaticVolume == 0 && + mConstantPercent == 0 && + mConstantRiskBalance == 0 + // + ; + + // + return result; + } + + /** + * Check Configuration is Valid For Constant Risk Balance ... + * + * @return ( bool ) + */ + bool CanUseConstantRiskBalance() + { + // + bool result = false; + + // + result = IsValid(mVolumeType); + if (!result) + { + return result; + } + + // + result = + // + (mVolumeType == X_VOLUME_CURRENT || + mVolumeType == X_VOLUME_EQUITY || + (mVolumeType == X_VOLUME_CONSTANT && + mConstantBalance > 0)) && + // + mConstantRiskBalance > 0 && + // + mStaticVolume == 0 && + mConstantPercent == 0 && + mDynamicVolumeStepBalance == 0 + // + ; + + // + return result; + } + + /** + * Check Configuration is Valid For Constant Risk Percent ... + * + * @return ( bool ) + */ + bool CanUseConstantBalancePercent() + { + // + bool result = false; + + // + result = IsValid(mVolumeType); + if (!result) + { + return result; + } + + // + result = + // + (mVolumeType == X_VOLUME_CURRENT || + mVolumeType == X_VOLUME_EQUITY || + (mVolumeType == X_VOLUME_CONSTANT && + mConstantBalance > 0)) && + // + mConstantPercent > 0 && + // + mStaticVolume == 0 && + mConstantRiskBalance == 0 && + mDynamicVolumeStepBalance == 0 + // + ; + + // + return result; + } + + // + // Private ... + private: + // + // Props ... + + // + ENUM_X_VOLUME_SELECT_TYPE mVolumeType; // Balance Type ... + + // + // Static Volume ... + double mStaticVolume; // Static Volume ... + + // + double mDynamicVolumeStepBalance; // Step of Balance ... + double mDynamicVolumeStepVolume; // Step of Volume ... + + // + double mConstantBalance; // Constant Balance .... + double mConstantRiskBalance; // Constant Risk Balance ... + double mConstantPercent; // Constant Percent of Balance ... +}; + +// \ No newline at end of file diff --git a/BKPS/14040203/Documents/BKP/1.mq5 b/BKPS/14040203/Documents/BKP/1.mq5 new file mode 100644 index 0000000..53a541f --- /dev/null +++ b/BKPS/14040203/Documents/BKP/1.mq5 @@ -0,0 +1,236 @@ + // + // HTF Proves ... + + // // + // double scoreMultiplier = 1.5; + + // // + // bool isConsolidationScoreBullish = + // provider.consolidationBullishScore > (provider.consolidationBearishScore * scoreMultiplier); + + // // + // bool isConsolidationScoreBearish = + // provider.consolidationBearishScore > (provider.consolidationBullishScore * scoreMultiplier); + + // + // + // + + // // + // // Detect Kumo Trend ... + // bool isKumoBullish = provider.decisionXConditions.isSenkouSpanAOverB; + // bool isKumoBearish = provider.decisionXConditions.isSenkouSpanAUnderB; + + // // + // // Detect Nearest Cross ... + // XOHCL tkCrossedBar; + // ENUM_X_DIRECTION tkCrossDir; + // bool hasNearestTenkanSenKijunSenCross = + // provider + // .decisionCycleHelper + // .DetectNearestTenKijCross( + // tkCrossedBar, + // tkCrossDir, + // zIndex // + // ); + + // // + // bool isNearestTenkensSenCrossedOverKijunSen = + // hasNearestTenkanSenKijunSenCross && + // IsBullish(tkCrossDir); + + // // + // bool isNearestTenkensSenCrossedUnderKijunSen = + // hasNearestTenkanSenKijunSenCross && + // IsBearish(tkCrossDir); + + // // + // // Detect Nearest Volume ... + // XOHCL vSwitchedBar; + // ENUM_X_DIRECTION vSwitchedDir; + // bool isVolumeSwitched = + // provider + // .decisionCycleHelper + // .DetectNearestVolumeSwitched( + // vSwitchedBar, + // vSwitchedDir, + // zIndex // + // ); + // bool isVolumeBullish = + // isVolumeSwitched && + // IsBullish(vSwitchedDir); + // bool isVolumeBearish = + // isVolumeSwitched && + // IsBearish(vSwitchedDir); + + // // + // // Detect Nearest Delta Crossed ... + // XOHCL deltaCrossedBar; + // ENUM_X_DIRECTION deltaCrossedDir; + // bool isDeltaCrossed = + // provider + // .decisionCycleHelper + // .DetectNearestDeltaSwitched( + // deltaCrossedBar, + // deltaCrossedDir, + // zIndex // + // ); + // bool isDeltaBullish = + // isDeltaCrossed && + // IsBullish(deltaCrossedDir); + // bool isDeltaBearish = + // isDeltaCrossed && + // IsBearish(deltaCrossedDir); + + // // + // // Detect Nearest Str Switched ... + // XOHCL strSwitchedBar; + // ENUM_X_DIRECTION strSwitchedDir; + // bool isStrSwitched = + // provider + // .decisionCycleHelper + // .DetectNearestStrSwitched( + // strSwitchedBar, + // strSwitchedDir, + // zIndex // + // ); + // bool isStrBullish = + // isStrSwitched && + // IsBullish(deltaCrossedDir); + // bool isStrBearish = + // isStrSwitched && + // IsBearish(deltaCrossedDir); + + // // + // // Detect Price in TK Zone ... + // bool isBarInsideTKZone = + // isNearestTenkensSenCrossedOverKijunSen + // ? cBar.low < provider.decisionXConditions.tenkanSenBuffer[cIndex] + // : isNearestTenkensSenCrossedUnderKijunSen + // ? cBar.high > provider.decisionXConditions.tenkanSenBuffer[cIndex] + // : false; + + // // + // // Checking Bar Based on Positions State ... + // ENUM_X_DIRECTION iBarPosDir; + // bool isBarValidForDir = provider.decisionCycleHelper + // .mBarAnalyser + // .IsValidForPosition( + // cBar, + // iBarPosDir // + // ); + // bool isBarValidForBullish = + // isBarValidForDir && + // IsBullish(iBarPosDir); + // bool isBarValidForBearish = + // isBarValidForDir && + // IsBearish(iBarPosDir); + + // + // Summarize Conditions ... + + // + isBullish = + // + false + // isStrBullish && + // isKumoBullish && + // isDeltaBullish && + // isVolumeBullish && + // isBarInsideTKZone && + // isBarValidForBullish && + // isConsolidationScoreBullish && + // isNearestTenkensSenCrossedOverKijunSen + // + ; + + // + isBearish = + // + false + // isStrBearish && + // isKumoBearish && + // isDeltaBearish && + // isVolumeBearish && + // isBarInsideTKZone && + // isBarValidForBearish && + // isConsolidationScoreBearish && + // isNearestTenkensSenCrossedUnderKijunSen + // + ; + +/////////////////////////////////////////////////////////////////////////////// + + // + iBox.to = TimeCurrent(); + XCBoxObject *iObj; + has = helper.poiDrawer.DrawBox( + iBox, + iObj // + ); + if (has) + { + // + iObj.BoxWidth(2); + + // + color iCLR = + iBox.IsBullish() + ? clrAqua + : clrMagenta; + iObj.BoxColor(iCLR); + iObj.BoxStyle(STYLE_SOLID); + } + +////////////////////////////////////////////////////////////////////////////////////// + + // + // COMPLEX ... + + // + double iKTIRNDs[] = { + cKI, + cTKI, + cTrend // + }; + + // + double iKTIRNDMax = GetMax(iKTIRNDs); + double iKTIRNDMin = GetMin(iKTIRNDs); + + // + // Conditions Preparing ... + + // + bool isTKITRNDBullish = + cKIState > 0 && + cTKIState > 0 && + ctrendState > 0; + + // + bool isTKITRNDBullishPrev = + pKIState > 0 && + pTKIState > 0 && + ptrendState > 0; + + // + bool isTKITRNDBearish = + cKIState < 0 && + cTKIState < 0 && + ctrendState < 0; + + // + bool isTKITRNDBearishPrev = + pKIState < 0 && + pTKIState < 0 && + ptrendState < 0; + + // + bool isTKITRNDSwitchedToBullish = + isTKITRNDBullish && + !isTKITRNDBullishPrev; + + // + bool isTKITRNDSwitchedToBearish = + isTKITRNDBearish && + !isTKITRNDBearishPrev; diff --git a/BKPS/14040203/Documents/BKP/1/signals/2.mq5 b/BKPS/14040203/Documents/BKP/1/signals/2.mq5 new file mode 100644 index 0000000..4d60af7 --- /dev/null +++ b/BKPS/14040203/Documents/BKP/1/signals/2.mq5 @@ -0,0 +1,2184 @@ + +// +// Checking Conditions ... + +// +// Retrieve Some Values ... + +// +double peak = cXConditions.peaksBuffer[cIDX]; +double peakZ = cXConditions.peaksBuffer[zIDX]; +double peakP = cXConditions.peaksBuffer[pIDX]; +double peakPP = cXConditions.peaksBuffer[ppIDX]; + +// +double vale = cXConditions.valesBuffer[cIDX]; +double valeZ = cXConditions.valesBuffer[zIDX]; +double valeP = cXConditions.valesBuffer[pIDX]; +double valePP = cXConditions.valesBuffer[ppIDX]; + +// +double cSMHKOpen = cXConditions.xhkSMOpenBuffer[cIDX]; +double cSMHKHigh = cXConditions.xhkSMHighBuffer[cIDX]; +double cSMHKClose = cXConditions.xhkSMCloseBuffer[cIDX]; +double cSMHKLow = cXConditions.xhkSMLowBuffer[cIDX]; +double cSMHKMin = MathMin(cSMHKOpen, cSMHKClose); +double cSMHKMax = MathMax(cSMHKOpen, cSMHKClose); + +// +double pSMHKOpen = cXConditions.xhkSMOpenBuffer[pIDX]; +double pSMHKHigh = cXConditions.xhkSMHighBuffer[pIDX]; +double pSMHKClose = cXConditions.xhkSMCloseBuffer[pIDX]; +double pSMHKLow = cXConditions.xhkSMLowBuffer[pIDX]; +double pSMHKMin = MathMin(pSMHKOpen, pSMHKClose); +double pSMHKMax = MathMax(pSMHKOpen, pSMHKClose); + +// +double atrUpperSM = cXConditions.atrUpperSMBuffer[cIDX]; +double atrLowerSM = cXConditions.atrLowerSMBuffer[cIDX]; + +// +double atrUpperSMZ = cXConditions.atrUpperSMBuffer[zIDX]; +double atrLowerSMZ = cXConditions.atrLowerSMBuffer[zIDX]; + +// +double atrUpperSMP = cXConditions.atrUpperSMBuffer[pIDX]; +double atrLowerSMP = cXConditions.atrLowerSMBuffer[pIDX]; + +// +double atrUpperSMPP = cXConditions.atrUpperSMBuffer[ppIDX]; +double atrLowerSMPP = cXConditions.atrLowerSMBuffer[ppIDX]; + +// +double rsiChange = cXConditions.rsiChangeBuffer[cIDX]; +double rsiChangeZ = cXConditions.rsiChangeBuffer[zIDX]; +double rsiChangeP = cXConditions.rsiChangeBuffer[pIDX]; +double rsiChangePP = cXConditions.rsiChangeBuffer[ppIDX]; + +// +double rsiChangeSM = cXConditions.rsiChangeSMBuffer[cIDX]; +double rsiChangeSMZ = cXConditions.rsiChangeSMBuffer[zIDX]; +double rsiChangeSMP = cXConditions.rsiChangeSMBuffer[pIDX]; +double rsiChangeSMPP = cXConditions.rsiChangeSMBuffer[ppIDX]; + +// +double peaksGolden = cXConditions.peaksGoldenBuffer[cIDX]; +double peaksGoldenZ = cXConditions.peaksGoldenBuffer[zIDX]; +double peaksGoldenP = cXConditions.peaksGoldenBuffer[pIDX]; +double peaksGoldenPP = cXConditions.peaksGoldenBuffer[ppIDX]; + +// +double valesGolden = cXConditions.valesGoldenBuffer[cIDX]; +double valesGoldenZ = cXConditions.valesGoldenBuffer[zIDX]; +double valesGoldenP = cXConditions.valesGoldenBuffer[pIDX]; +double valesGoldenPP = cXConditions.valesGoldenBuffer[ppIDX]; + +// +double priceChange = cXConditions.priceChangeBuffer[cIDX]; +double priceChangeZ = cXConditions.priceChangeBuffer[zIDX]; +double priceChangeP = cXConditions.priceChangeBuffer[pIDX]; +double priceChangePP = cXConditions.priceChangeBuffer[ppIDX]; + +// +double priceChangeSM = cXConditions.priceChangeSMBuffer[cIDX]; +double priceChangeSMZ = cXConditions.priceChangeSMBuffer[zIDX]; +double priceChangeSMP = cXConditions.priceChangeSMBuffer[pIDX]; +double priceChangeSMPP = cXConditions.priceChangeSMBuffer[ppIDX]; + +// +// +// + +// +// XHK ... + +// +bool isPBarClosedOverSMHK = + // + pBar.IsBullish() && + pBar.GetUp() > pSMHKMax && + pBar.GetDown() < pSMHKMin + // + ; + +// +bool isPBarClosedUnderSMHK = + // + pBar.IsBearish() && + pBar.GetUp() > pSMHKMax && + pBar.GetDown() < pSMHKMin + // + ; + +// +bool isPBarBullishPriceChangeVPattern = + priceChangeP > priceChangePP && + priceChangeP > priceChange; + +// +bool isPBarBerishPriceChangeVPattern = + priceChangeP < priceChangePP && + priceChangeP < priceChange; + +// +bool isPBarPriceChangeOverPeak = + priceChangeP > peak && + priceChangeP > peakP && + priceChangeP > peakPP; + +// +bool isPBarPriceChangeUnderVale = + priceChangeP < vale && + priceChangeP < valeP && + priceChangeP < valePP; + +// +bool isPBarCloseOverPeaksGoldenZone = + pBar.close > peaksGoldenP; + +// +bool isPBarCloseUnderValesGoldenZone = + pBar.close < valesGoldenP; + +// +bool isPBarPriceChangeOverAtrUpper = + priceChangeP > atrUpperSMP; + +// +bool isPBarPriceChangeUnderAtrLower = + priceChangeP < atrLowerSMP; + +// +isBullish = + // + // false + // + hasSelectedBox && + selectedBox.IsBullish() && + cXConditions.isStrBullish + // + // cBar.IsBullish() && + // isPBarPriceChangeUnderVale && + // isPBarPriceChangeUnderAtrLower && + // isPBarBerishPriceChangeVPattern && + // isPBarCloseUnderValesGoldenZone + // + ; + +// +isBearish = + // + // false + // + hasSelectedBox && + selectedBox.IsBearish() && + cXConditions.isStrBearish + // + // cBar.IsBearish() && + // isPBarPriceChangeOverPeak && + // isPBarPriceChangeOverAtrUpper && + // isPBarCloseOverPeaksGoldenZone && + // isPBarBullishPriceChangeVPattern + // + ; + +///////////////////////////////////////////////////////// + +// +double xhkSL; +ENUM_X_DIRECTION xhkDir; +bool isXHKPassed = IsHKConditionsPassed( + xhkSL, + xhkDir, + cHelper, + cXConditions, + barIndex // +); +bool isXHKBullish = + isXHKPassed && + IsBullish(xhkDir); +bool isXHKBearish = + isXHKPassed && + IsBearish(xhkDir); + +///////////////////////////////////////////////////////// + +// +bool IsRejectedBox( + XOHCL &bar, // CBar ... + XBoxZone &box, + X121Conditions &conditions // +) +{ + // + bool result = false; + + // + result = + bar.IsValid() && + box.IsValid(); + if (!result) + { + return result; + } + + // + bool isBullish = box.IsBullish(); + + // + bool isBullishRejected = + isBullish && + bar.IsRejected( + box.upper, + box.dir, + true, // Force Type ... + true // Force Pressure ... + ); + + // + bool isBearishRejected = + !isBullish && + bar.IsRejected( + box.lower, + box.dir, + true, // Force Type ... + true // Force Pressure ... + ); + + // + result = isBullishRejected || + isBearishRejected; + + // + return result; +} + +// +bool IsPeaksOrValesPassedBox( + XBoxZone &box, + X121Conditions &conditions // +) +{ + // + bool result = false; + + // + result = box.IsValid(); + if (!result) + { + return result; + } + + // + double peakZ = conditions.peaksBuffer[0]; + double peakC = conditions.peaksBuffer[1]; + double peakP = conditions.peaksBuffer[2]; + double peakPP = conditions.peaksBuffer[3]; + + // + double valeZ = conditions.valesBuffer[0]; + double valeC = conditions.valesBuffer[1]; + double valeP = conditions.valesBuffer[2]; + double valePP = conditions.valesBuffer[3]; + + // + double boxQ = ((box.upper - box.lower) / 100) * 25; + double upperQuarter = box.upper - boxQ; + double lowerQuarter = box.lower + boxQ; + + // + bool isPPeakInsideUpperQ = + peakP < box.upper && + peakP > upperQuarter; + + // + bool isPValeInsideLowerQ = + valeP > box.lower && + valeP < lowerQuarter; + + // + bool isPPPeakInsideUpperQ = + peakPP < box.upper && + peakPP > upperQuarter; + + // + bool isPPValeInsideLowerQ = + valePP > box.lower && + valePP < lowerQuarter; + + // + result = + // + (box.IsBullish() && + (isPValeInsideLowerQ || + isPPValeInsideLowerQ) && + (valeC == valeP || + valeP == valePP)) + // + || + // + (box.IsBearish() && + (isPPeakInsideUpperQ || + isPPPeakInsideUpperQ) && + (peakC == peakP || + peakP == peakPP)) + // + ; + + // + return result; +} + +// +bool IsX3MaPassedBox( + XOHCL &bar, // CBar ... + XBoxZone &box, + X121Conditions &conditions // +) +{ + // + bool result = false; + + // + result = + bar.IsValid() && + box.IsValid(); + if (!result) + { + return result; + } + + // + double x3maFast = conditions.x3maFastBuffer[1]; + double x3maMid = conditions.x3maMidBuffer[1]; + double x3maSlow = conditions.x3maSlowBuffer[1]; + + // + bool isx3MaInsideBox = + // + // Fast ... + x3maFast < box.upper && + x3maFast > box.lower + // + && + // + // Mid ... + x3maMid < box.upper && + x3maMid > box.lower + // + && + // + // Slow ... + x3maSlow < box.upper && + x3maSlow > box.lower + // + ; + + // + bool isX3maSwitchedToBullishOrdered = + bar.IsBullish() && + box.IsBullish() && + isx3MaInsideBox && + bar.close > conditions.x3maFastBuffer[1] && + conditions.isX3MaSwitchedToBullishOrdered; + + // + bool isX3maSwitchedToBearishOrdered = + bar.IsBearish() && + box.IsBearish() && + isx3MaInsideBox && + bar.close < conditions.x3maFastBuffer[1] && + conditions.isX3MaSwitchedToBearishOrdered; + + // + result = isX3maSwitchedToBullishOrdered || + isX3maSwitchedToBearishOrdered; + + // + return result; +} + +// +// TODO: Complete this ... +bool IsActivatedBoxPassed( + XBoxZone &box, + X121Conditions &conditions // +) +{ + // + bool result = false; + + // + result = box.IsValid(); + if (!result) + { + return result; + } + + // + return result; +} + +// +// +// + +// +bool IsHKConditionsPassed( + double &sl, + ENUM_X_DIRECTION &dir, + XC121SMCCycleHelper *helper, + X121Conditions &conditions, + int barIndex = 0 // +) +{ + // + bool result = false; + + // + sl = 0; + dir = X_DIRECTION_NONE; + + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + int zIDX = 0; + int cIDX = zIDX + 1; + int pIDX = cIDX + 1; + int ppIDX = pIDX + 1; + + // + XOHCL zBar; + XOHCL cBar; + XOHCL pBar; + XOHCL ppBar; + + // + // Retrieve Bars ... + result = zBar.Init( + conditions.symbol, + conditions.period, + barIndex // + ); + result = + result && + zBar.GetPreviousBar(cBar); + result = + result && + cBar.GetPreviousBar(pBar); + result = + result && + pBar.GetPreviousBar(ppBar); + if (!result) + { + // + zBar.Clean(); + cBar.Clean(); + pBar.Clean(); + ppBar.Clean(); + + // + return result; + } + + // + // Check PBar Swing ... + ENUM_X_DIRECTION pBarSwingDir; + bool isPBarSwing = helper + .mBarAnalyser + .IsSwing( + pBar, + pBarSwingDir, + 3 // + ); + + // + bool isPBarSwingLow = + isPBarSwing && + IsBullish(pBarSwingDir); + + // + bool isPBarSwingHigh = + isPBarSwing && + IsBearish(pBarSwingDir); + + // + // Check PBar Rejection ... + ENUM_X_DIRECTION pBarRejectionDir; + bool isPBarRejected = helper + .mBarAnalyser + .IsRejected( + pBar, + pBarRejectionDir, + false, + true // + ); + + // + bool isPBarBullishRejected = + isPBarRejected && + IsBullish(pBarRejectionDir); + + // + bool isPBarBearishRejected = + isPBarRejected && + IsBearish(pBarRejectionDir); + + // + // Checking Str Incresing/Decreasing ... + + // + bool isStrIncresing = + // + (conditions.strBuffer[zIDX] > conditions.strBuffer[cIDX] && + conditions.strBuffer[zIDX] > conditions.strBuffer[pIDX] && + conditions.strBuffer[zIDX] > conditions.strBuffer[ppIDX]) + // + && + // + ( + // + (conditions.strBuffer[zIDX] > conditions.strBuffer[cIDX] && + conditions.strBuffer[cIDX] > conditions.strBuffer[pIDX]) + // + || + // + (conditions.strBuffer[cIDX] > conditions.strBuffer[pIDX] && + conditions.strBuffer[pIDX] > conditions.strBuffer[ppIDX]) + // + ) + // + ; + + // + bool isStrDecreasing = + // + (conditions.strBuffer[zIDX] < conditions.strBuffer[cIDX] && + conditions.strBuffer[zIDX] < conditions.strBuffer[pIDX] && + conditions.strBuffer[zIDX] < conditions.strBuffer[ppIDX]) + // + && + // + ( + // + (conditions.strBuffer[zIDX] < conditions.strBuffer[cIDX] && + conditions.strBuffer[cIDX] < conditions.strBuffer[pIDX]) + // + || + // + (conditions.strBuffer[cIDX] < conditions.strBuffer[pIDX] && + conditions.strBuffer[pIDX] < conditions.strBuffer[ppIDX]) + // + ) + // + ; + + // + bool isBullish = + // + isPBarSwingLow && + isStrIncresing && + cBar.IsBullish() && + cBar.low > pBar.low && + cBar.open > pBar.low && + zBar.open > cBar.low && + // isPBarBullishRejected && + conditions.isSarBullish && + conditions.isStrBullish && + conditions.isSMHKBullish + // + ; + + // + bool isBearish = + // + isPBarSwingHigh && + isStrDecreasing && + cBar.IsBearish() && + cBar.high < pBar.high && + cBar.open < pBar.high && + zBar.open < cBar.high && + // isPBarBearishRejected && + conditions.isSarBearish && + conditions.isStrBearish && + conditions.isSMHKBearish + // + ; + + // + result = isBullish || + isBearish; + if (result) + { + // + dir = isBullish + ? X_DIRECTION_BULLISH + : X_DIRECTION_BEARISH; + + // + // Selecting SL ... + sl = + isBullish + ? cBar.low + : cBar.high; + } + + // + // Cleanup Resources ... + zBar.Clean(); + cBar.Clean(); + pBar.Clean(); + ppBar.Clean(); + + // + return result; +} + +// +bool IsSARConditionsPassed( + double &sl, + ENUM_X_DIRECTION &dir, + XC121SMCCycleHelper *helper, + X121Conditions &conditions, + int barIndex = 0 // +) +{ + // + bool result = false; + + // + sl = 0; + dir = X_DIRECTION_NONE; + + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + int zIDX = 0; + int cIDX = zIDX + 1; + int pIDX = cIDX + 1; + int ppIDX = pIDX + 1; + + // + XOHCL zBar; + XOHCL cBar; + XOHCL pBar; + XOHCL ppBar; + + // + // Retrieve Bars ... + result = zBar.Init( + conditions.symbol, + conditions.period, + barIndex // + ); + result = + result && + zBar.GetPreviousBar(cBar); + result = + result && + cBar.GetPreviousBar(pBar); + result = + result && + pBar.GetPreviousBar(ppBar); + if (!result) + { + // + zBar.Clean(); + cBar.Clean(); + pBar.Clean(); + ppBar.Clean(); + + // + return result; + } + + // + // Check PBar Swing ... + ENUM_X_DIRECTION pBarSwingDir; + bool isPBarSwing = helper + .mBarAnalyser + .IsSwing( + pBar, + pBarSwingDir, + 3 // + ); + + // + bool isPBarSwingLow = + isPBarSwing && + IsBullish(pBarSwingDir); + + // + bool isPBarSwingHigh = + isPBarSwing && + IsBearish(pBarSwingDir); + + // + bool isBullish = + // + isPBarSwingLow && + cBar.IsBullish() && + cBar.low > pBar.low && + cBar.open > pBar.low && + zBar.open > cBar.low && + conditions.isSarSwitchedToBullish + // + ; + + // + bool isBearish = + // + isPBarSwingHigh && + isStrDecreasing && + cBar.IsBearish() && + cBar.high < pBar.high && + cBar.open < pBar.high && + zBar.open < cBar.high && + conditions.isSarSwitchedToBearish + // + ; + + // + result = isBullish || + isBearish; + if (result) + { + // + dir = isBullish + ? X_DIRECTION_BULLISH + : X_DIRECTION_BEARISH; + + // + // Selecting SL ... + sl = + isBullish + ? cBar.low + : cBar.high; + } + + // + // Cleanup Resources ... + zBar.Clean(); + cBar.Clean(); + pBar.Clean(); + ppBar.Clean(); + + // + return result; +} + +///////////////////////////////////////////////////////// + +// // +// bool isPVPassed = IsPeaksOrValesPassedBox( +// iBox, +// cXConditions // +// ); +// if (isPVPassed) +// { +// // +// selectedBox = iBox; +// iBox.Clean(); +// break; +// } + +// +// bool isx3MaPassed = IsX3MaPassedBox( +// cBar, +// iBox, +// cXConditions // +// ); +// if (isx3MaPassed) +// { +// // +// selectedBox = iBox; +// iBox.Clean(); +// break; +// } + +// +// bool isRejected = IsRejectedBox( +// cBar, +// iBox, +// cXConditions // +// ); +// if (isRejected) +// { +// // +// selectedBox = iBox; +// iBox.Clean(); +// break; +// } + +///////////////////////////////////////////////////////// + +// +// Checking Bullish Fair Value Gaps ... +has = cState.HasBullishFairValueGaps(); +if (has) +{ + // + XBoxZone tmpBoxes[]; + ToBox( + cState.bullishFairValueGaps, + tmpBoxes // + ); + + // + count = ArraySize(tmpBoxes); + has = IsValidSize(count); + if (has) + { + // + for (int i = 0; i < count; i++) + { + // + XBoxZone iBox = tmpBoxes[i]; + bool isValid = IsBoxValid( + iBox, + 0, + iBox.period // + ); + if (!isValid) + { + // + iBox.Clean(); + continue; + } + + // + has = IsBoxExists(iBox); + if (!has) + { + // + AddRef( + iBox, + mWaitingBoxes // + ); + } + + // + iBox.Clean(); + } + } + + // + Clean(tmpBoxes); +} + +// +// Checking Bearish Fair Value Gaps ... +has = cState.HasBearishFairValueGaps(); +if (has) +{ + // + XBoxZone tmpBoxes[]; + ToBox( + cState.bearishFairValueGaps, + tmpBoxes // + ); + + // + count = ArraySize(tmpBoxes); + has = IsValidSize(count); + if (has) + { + // + for (int i = 0; i < count; i++) + { + // + XBoxZone iBox = tmpBoxes[i]; + bool isValid = IsBoxValid( + iBox, + 0, + iBox.period // + ); + if (!isValid) + { + // + iBox.Clean(); + continue; + ; + } + + // + has = IsBoxExists(iBox); + if (!has) + { + // + AddRef( + iBox, + mWaitingBoxes // + ); + } + + // + iBox.Clean(); + } + } + + // + Clean(tmpBoxes); +} + +///////////////////////////////////////////////////////// + +// +bool GeneratePVBox( + XBoxZone &box, + int barIndex = 0 // +) +{ + // + bool result = false; + + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + box.Clean(); + box.symbol = GetSymbol(); + box.period = GetPeriod(); + + // + int index = barIndex; + + // + // Peak ... + datetime peaksSameFrom = NULL; + double peak = mX121Helper.xpvHelper.GetPeak(index); + double prevPeak = mX121Helper.xpvHelper.GetPeak(index + 1); + bool startsByPeak = peak == prevPeak; + + // + // Vale ... + datetime valesSameFrom = NULL; + double vale = mX121Helper.xpvHelper.GetVale(index); + double prevVale = mX121Helper.xpvHelper.GetVale(index + 1); + bool startsByVale = + !startsByPeak && + vale == prevVale; + + // + bool canBreak = false; + while (!canBreak) + { + // + index++; + + // + datetime cTime = iTime( + box.symbol, + box.period, + index // + ); + + // + // Peak ... + double iPeak = mX121Helper.xpvHelper.GetPeak(index); + + // + // Vale ... + double iVale = mX121Helper.xpvHelper.GetVale(index); + + // + // Start By Peak or Value ... + bool isSame = false; + if (startsByPeak) + { + // + isSame = iPeak == peak; + bool canSetVale = vale == 0 + ? true + : iVale > vale; + if (canSetVale) + { + vale = iVale; + } + } + else if (startsByVale) + { + // + isSame = iVale == vale; + bool canSetPeak = peak == 0 + ? true + : iPeak < peak; + if (canSetPeak) + { + peak = iPeak; + } + } + + // + if (isSame) + { + // + box.from = cTime; + box.upper = peak; + box.lower = vale; + } + else if (IsValid(box.from)) + { + // + // Complete Box ... + box.to = iTime( + box.symbol, + box.period, + barIndex // + ); + + // + box.type = "XPVBox"; + box.dir = startsByPeak + ? X_DIRECTION_BEARISH + : startsByVale + ? X_DIRECTION_BULLISH + : X_DIRECTION_NONE; + } + + // + canBreak = !isSame; + } + + // + result = box.IsValid(); + if (!result) + { + box.Clean(); + } + + // + return result; +} + +// +void DetectPVPivots( + int barIndex = 0, + int validation = 50, + int loopback = 100 // +) +{ + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + loopback = NormalizeInt(loopback, 10); + validation = NormalizeInt(validation, 5); + + // + int iPeakVerified = 0; + int iValeVerified = 0; + datetime iPeakTo = GetBarTime( + GetSymbol(), + GetPeriod(), + barIndex // + ); + datetime iValeTo = GetBarTime( + GetSymbol(), + GetPeriod(), + barIndex // + ); + double iPeak = mX121Helper.xpvHelper.GetPeak(barIndex); + double iVale = mX121Helper.xpvHelper.GetVale(barIndex); + double iPeakGolden = mX121Helper.xpvHelper.GetPeakGoldenZone(barIndex); + double iValeGolden = mX121Helper.xpvHelper.GetValeGoldenZone(barIndex); + for (int i = barIndex + 1; i < barIndex + 1 + loopback; i++) + { + // + double iiPeak = mX121Helper.xpvHelper.GetPeak(i); + double iiVale = mX121Helper.xpvHelper.GetVale(i); + double iiPeakGolden = mX121Helper.xpvHelper.GetPeakGoldenZone(i); + double iiValeGolden = mX121Helper.xpvHelper.GetValeGoldenZone(i); + + // + if (iiPeak == iPeak) + { + // + iPeakVerified++; + iPeakGolden = iPeakGolden < iiPeakGolden + ? iiPeakGolden + : iPeakGolden; + } + else + { + // + if (iPeakVerified > 0 && + iPeakVerified < validation) + { + // + // Reset ... + iPeak = iiPeak; + iPeakVerified = 0; + iPeakGolden = iiPeakGolden; + iPeakTo = GetBarTime( + GetSymbol(), + GetPeriod(), + i // + ); + } + } + + // + if (iiVale == iVale) + { + // + iValeVerified++; + iValeGolden = iValeGolden > iiValeGolden + ? iiValeGolden + : iValeGolden; + } + else + { + // + if (iValeVerified > 0 && + iValeVerified < validation) + { + // + // Reset ... + iVale = iiVale; + iValeVerified = 0; + iValeGolden = iiValeGolden; + iValeTo = GetBarTime( + GetSymbol(), + GetPeriod(), + i // + ); + } + } + + // + if (iPeakVerified >= validation && + iValeVerified >= validation) + { + break; + } + } + + // + // Checking PV Pivots ... + + // + if (iPeakVerified >= validation) + { + // + XPVPivot iPivot; + + // + iPivot.to = iPeakTo; + iPivot.value = iPeak; + iPivot.type = X_PV_PEAK; + iPivot.golden = iPeakGolden; + iPivot.symbol = GetSymbol(); + iPivot.period = GetPeriod(); + iPivot.from = ((datetime)iPeakTo - (PeriodSeconds(GetPeriod()) * iPeakVerified)); + + // + if (iPivot.IsValid()) + { + // + AddRef( + iPivot, + mPVPivots // + ); + + // + XBoxZone iBox; + XCBoxObject *iObj; + bool iHas = iPivot.AsBox(iBox); + if (iHas) + { + // + iHas = mPOIDrawer.DrawBox( + iBox, + iObj // + ); + if (iHas) + { + Print("Peak Pivot ..."); + } + } + } + + // + iPivot.Clean(); + } + + // + if (iValeVerified >= validation) + { + // + XPVPivot iPivot; + + // + iPivot.to = iValeTo; + iPivot.value = iVale; + iPivot.type = X_PV_VALE; + iPivot.symbol = GetSymbol(); + iPivot.period = GetPeriod(); + iPivot.golden = iValeGolden; + iPivot.from = ((datetime)iValeTo - (PeriodSeconds(GetPeriod()) * iValeVerified)); + + // + if (iPivot.IsValid()) + { + // + AddRef( + iPivot, + mPVPivots // + ); + + // + XBoxZone iBox; + XCBoxObject *iObj; + bool iHas = iPivot.AsBox(iBox); + if (iHas) + { + // + iHas = mPOIDrawer.DrawBox( + iBox, + iObj // + ); + if (iHas) + { + Print("Vale Pivot ..."); + } + } + } + + // + iPivot.Clean(); + } + + // +} + +// +DetectPVPivots(barIndex); + +///////////////////////////////////////////////////////// +// +// Detect Support and Resistances ... +XBoxZone tmpBoxes[]; +XBoxZone selectedSupRes[]; +count = provider.triggerState.SupportResistancesAsBox(tmpBoxes); +has = IsValidSize(count); +if (has) +{ + // + for (int i = 0; i < count; i++) + { + // + XBoxZone iBox = tmpBoxes[i]; + + // + // Validate Box ... + bool isDirPassed = iBox.dir == selectedBox.dir; + bool isPlacePassed = IsBoxInsideOr(iBox, selectedBox, true); + has = isDirPassed && + isPlacePassed; + if (has) + { + // + AddRef( + iBox, + selectedSupRes // + ); + } + + // + iBox.Clean(); + } + + // + Clean(tmpBoxes); +} +has = HasChild(selectedSupRes); +if (has) +{ + // + count = ArraySize(selectedSupRes); + for (int i = 0; i < count; i++) + { + // + selectedSupRes[i].to = TimeCurrent(); + + // + XCBoxObject *iObj; + has = drawer.DrawBox( + selectedSupRes[i], + iObj // + ); + } +} + +///////////////////////////////////////////////////////// + // + // double strSupport = 0; + // datetime strIn = NULL; + // datetime strOut = NULL; + // bool isStrInBox = false; + // double strResistance = 0; + // bool isStrOutBox = false; + // Checking STR Variables ... + // CheckBoxStr( + // cHelper, + // selectedBox, + // isStrInBox, + // strIn, + // isStrOutBox, + // strOut, + // strSupport, + // strResistance // + // ); + + +///////////////////////////////////////////////////////// + +// +bool IsFVGBoxValid( + XBoxZone &box, + ENUM_X_CYCLES cycle, + X121SMCStrategySignalProviderData &provider // +) +{ + // + bool result = false; + + // + result = box.IsValid(); + if (!result) + { + return result; + } + + // + // Fil Selected Data ... + XPOIState cState; + X121Conditions cXConditions; + XPOIStateEvents cStateEvents; + XC121SMCCycleHelper *cHelper; + X121SMCCycleConditions cConditions; + result = provider.SelectCycle( + cycle, + cState, + cStateEvents, + cXConditions, + cHelper, + cConditions // + ); + if (!result) + { + // + cState.Clean(); + ZeroMemory(cHelper); + cConditions.Clean(); + cXConditions.Clean(); + cStateEvents.Clean(); + + // + return result; + } + + // + bool isBoxBullish = box.IsBullish(); + + // + int count = 0; + bool has = false; + + // + XBoxZone tmpBoxes[]; + count = cState.FairValueGapsAsBox(tmpBoxes); + has = IsValidSize(count); + + // + // Check Must Contains Inner Cycle FVG ... + XBoxZone selectedBox; + bool hasSelectedBox = false; + if (has) + { + // + for (int i = 0; i < count; i++) + { + // + XBoxZone iBox = tmpBoxes[i]; + + // + // Regular Validation of Boxes ... + bool isValid = IsBoxValid( + iBox, + 0, + iBox.period // + ); + bool isTypePassed = iBox.dir == box.dir; + bool isFromPssed = iBox.from >= box.from; + bool isPlacePassed = + IsBoxInsideOr( + iBox, + box // + ) && + (isBoxBullish + ? iBox.lower >= box.lower + : iBox.upper <= box.upper); + has = + isValid && + isFromPssed && + isTypePassed && + isPlacePassed; + if (!has) + { + // + iBox.Clean(); + continue; + } + + // + has = + !hasSelectedBox + ? true + : isBoxBullish + ? selectedBox.upper > iBox.upper + : selectedBox.lower < iBox.lower; + if (has) + { + // + selectedBox = iBox; + hasSelectedBox = selectedBox.IsValid(); + } + + // + iBox.Clean(); + } + } + + // + result = hasSelectedBox; + + // + // IGNORE Box Validations ... + // if (result) + // { + // // // + // // // From Index ... + // // int fromIndex = GetBarIndex( + // // selectedBox.symbol, + // // selectedBox.period, + // // selectedBox.from // + // // ) + + // // 1; + // // result = IsValidIndex(fromIndex); + + // // // + // // // To Index ... + // // int toIndex = GetBarIndex( + // // selectedBox.symbol, + // // selectedBox.period, + // // selectedBox.to // + // // ); + // // if (toIndex < 1) + // // { + // // toIndex = 1; + // // } + // // result = IsValidIndex(toIndex); + + // // // + // // // Now we Have Retrieve X121Conditions between from and to Indexes ... + // // // for Check States ... + + // // // + // // bool hasNewValeUnderLast = false; + // // bool isStrSwitchedToBullish = false; + // // bool isSarSwitchedToBullish = false; + // // bool hasValueGoldenZoneBreak = false; + // // bool isSMHKSwitchedToBullish = false; + // // bool isVWapSwitchedToBullishState = false; + // // bool isX3MaSwitchedToBullishState = false; + // // bool isVWapSwitchedToBullishOrdered = false; + // // bool isX3MaSwitchedToBullishOrdered = false; + + // // // + // // bool hasNewPeakOverLast = false; + // // bool isStrSwitchedToBearish = false; + // // bool isSarSwitchedToBearish = false; + // // bool hasPeakGoldenZoneBreak = false; + // // bool isSMHKSwitchedToBearish = false; + // // bool isVWapSwitchedToBearishState = false; + // // bool isX3MaSwitchedToBearishState = false; + // // bool isVWapSwitchedToBearishOrdered = false; + // // bool isX3MaSwitchedToBearishOrdered = false; + + // // // + // // for (int i = fromIndex; i >= toIndex; i--) + // // { + // // // + // // XOHCL iBar; + // // has = iBar.Init( + // // cState.symbol, + // // cState.period, + // // i // + // // ); + // // X121Conditions iConditions; + // // has = has && + // // cHelper.mX121Helper.GetConditions( + // // iConditions, + // // i // + // // ); + // // if (!has) + // // { + // // continue; + // // } + + // // // + // // // Bullish ... + + // // // + // // if (!hasNewValeUnderLast) + // // { + // // hasNewValeUnderLast = iConditions.isNewValeUnderLast; + // // } + + // // // + // // if (!isStrSwitchedToBullish) + // // { + // // isStrSwitchedToBullish = iConditions.isStrSwitchedToBullish; + // // } + + // // // + // // if (!isSarSwitchedToBullish) + // // { + // // isSarSwitchedToBullish = iConditions.isSarSwitchedToBullish; + // // } + + // // // + // // if (!hasValueGoldenZoneBreak) + // // { + // // // + // // hasValueGoldenZoneBreak = + // // iBar.IsBullish() && + // // iBar.GetUp() > iConditions.valesGoldenBuffer[1] && + // // iBar.GetDown() < iConditions.valesGoldenBuffer[1]; + // // } + + // // // + // // if (!isSMHKSwitchedToBullish) + // // { + // // isSMHKSwitchedToBullish = iConditions.isSMHKSwitchedToBullish; + // // } + + // // // + // // if (!isVWapSwitchedToBullishState) + // // { + // // isVWapSwitchedToBullishState = iConditions.isVWapSwitchedToBullishState; + // // } + + // // // + // // if (!isX3MaSwitchedToBullishState) + // // { + // // isX3MaSwitchedToBullishState = iConditions.isX3MaSwitchedToBullishState; + // // } + + // // // + // // if (!isVWapSwitchedToBullishOrdered) + // // { + // // isVWapSwitchedToBullishOrdered = iConditions.isVWapSwitchedToBullishOrdered; + // // } + + // // // + // // if (!isX3MaSwitchedToBullishOrdered) + // // { + // // isX3MaSwitchedToBullishOrdered = iConditions.isX3MaSwitchedToBullishOrdered; + // // } + + // // // + // // // Bearish ... + + // // // + // // if (!hasNewPeakOverLast) + // // { + // // hasNewPeakOverLast = iConditions.isNewPeakOverLast; + // // } + + // // // + // // if (!isStrSwitchedToBearish) + // // { + // // isStrSwitchedToBearish = iConditions.isStrSwitchedToBearish; + // // } + + // // // + // // if (!isSarSwitchedToBearish) + // // { + // // isSarSwitchedToBearish = iConditions.isSarSwitchedToBearish; + // // } + + // // // + // // if (!hasPeakGoldenZoneBreak) + // // { + // // // + // // hasPeakGoldenZoneBreak = + // // iBar.IsBearish() && + // // iBar.GetUp() > iConditions.peaksGoldenBuffer[1] && + // // iBar.GetDown() < iConditions.peaksGoldenBuffer[1]; + // // } + + // // // + // // if (!isSMHKSwitchedToBearish) + // // { + // // isSMHKSwitchedToBearish = iConditions.isSMHKSwitchedToBearish; + // // } + + // // // + // // if (!isVWapSwitchedToBearishState) + // // { + // // isVWapSwitchedToBearishState = iConditions.isVWapSwitchedToBearishState; + // // } + + // // // + // // if (!isX3MaSwitchedToBearishState) + // // { + // // isX3MaSwitchedToBearishState = iConditions.isX3MaSwitchedToBearishState; + // // } + + // // // + // // if (!isVWapSwitchedToBearishOrdered) + // // { + // // isVWapSwitchedToBearishOrdered = iConditions.isVWapSwitchedToBearishOrdered; + // // } + + // // // + // // if (!isX3MaSwitchedToBearishOrdered) + // // { + // // isX3MaSwitchedToBearishOrdered = iConditions.isX3MaSwitchedToBearishOrdered; + // // } + + // // // + // // iConditions.Clean(); + // // } + + // // // + // // // Bullish Conditions Summary ... + + // // // + // // bool hasBullishOrConditions = + // // hasNewValeUnderLast || + // // isStrSwitchedToBullish || + // // isSarSwitchedToBullish || + // // hasValueGoldenZoneBreak || + // // isSMHKSwitchedToBullish || + // // isVWapSwitchedToBullishState || + // // isX3MaSwitchedToBullishState || + // // isVWapSwitchedToBullishOrdered || + // // isX3MaSwitchedToBullishOrdered; + + // // // + // // bool hasBullishAndConditions = + // // hasNewValeUnderLast && + // // hasValueGoldenZoneBreak && + // // (isStrSwitchedToBullish || + // // isSarSwitchedToBullish || + // // isSMHKSwitchedToBullish || + // // isVWapSwitchedToBullishState || + // // isX3MaSwitchedToBullishState || + // // isVWapSwitchedToBullishOrdered || + // // isX3MaSwitchedToBullishOrdered); + + // // // + // // // Bearish Conditions Summary ... + + // // // + // // bool hasBearishOrConditions = + // // hasNewPeakOverLast || + // // isStrSwitchedToBearish || + // // isSarSwitchedToBearish || + // // hasPeakGoldenZoneBreak || + // // isSMHKSwitchedToBearish || + // // isVWapSwitchedToBearishState || + // // isX3MaSwitchedToBearishState || + // // isVWapSwitchedToBearishOrdered || + // // isX3MaSwitchedToBearishOrdered; + + // // // + // // bool hasBearishAndConditions = + // // hasNewPeakOverLast && + // // hasPeakGoldenZoneBreak && + // // (isStrSwitchedToBearish || + // // isSarSwitchedToBearish || + // // isSMHKSwitchedToBearish || + // // isVWapSwitchedToBearishState || + // // isX3MaSwitchedToBearishState || + // // isVWapSwitchedToBearishOrdered || + // // isX3MaSwitchedToBearishOrdered); + + // // + // bool isBullish = + // isBoxBullish + // // && + // // !hasBearishOrConditions && + // // hasBullishOrConditions + // ; + + // // + // bool isBearish = + // !isBoxBullish + // // && + // // !hasBullishOrConditions && + // // hasBearishOrConditions + // ; + + // // + // result = isBullish || + // isBearish; + + // // + // // if (result) + // // { + // // // + // // XCBoxObject *iBoxObj; + // // XCBoxObject *iInBoxObj; + + // // // + // // has = provider + // // .verificationCycleHelper + // // .mPOIDrawer + // // .DrawBox( + // // box, + // // iBoxObj // + // // ); + // // if (has) + // // { + // // // + // // iBoxObj.BoxWidth(2); + // // iBoxObj.BoxStyle(STYLE_SOLID); + // // } + + // // // + // // has = provider + // // .verificationCycleHelper + // // .mPOIDrawer + // // .DrawBox( + // // selectedBox, + // // iInBoxObj // + // // ); + // // if (has) + // // { + // // // + // // iInBoxObj.BoxWidth(2); + // // iInBoxObj.BoxStyle(STYLE_DASH); + // // } + + // // // + // // Print("Inside Selected Box ..."); + // // } + // } + + // + // Cleanup Resources ... + + // + cState.Clean(); + Clean(tmpBoxes); + selectedBox.Clean(); + ZeroMemory(cHelper); + cConditions.Clean(); + cXConditions.Clean(); + cStateEvents.Clean(); + + // + return result; +} + +///////////////////////////////////////////////////////// +// + +bool DetectXCAEAConditions( + XCAEAConditions &conditions, + XBoxZone &box, + ENUM_X_DIRECTION &dir, + XCXCAEAHelper *helper, + int barIndex = 0, + int loopback = 10 // +) +{ + // + bool result = false; + + // + box.Clean(); + conditions.Clean(); + dir = X_DIRECTION_NONE; + + // + if (barIndex < 0) + { + barIndex = 0; + } + loopback = NormalizeInt(loopback, 5); + + // + string symbol = helper.GetSymbol(); + ENUM_TIMEFRAMES period = helper.GetPeriod(); + + // + result = helper.GetConditions( + conditions, + barIndex, + loopback // + ); + if (!result) + { + // + conditions.Clean(); + return result; + } + + // + int zIDX = barIndex; + int cIDX = zIDX + 1; + int pIDX = cIDX + 1; + int ppIDX = pIDX + 1; + int p3IDX = ppIDX + 1; + int p4IDX = p3IDX + 1; + + // + XOHCL zBar; + XOHCL cBar; + XOHCL pBar; + XOHCL ppBar; + XOHCL p3Bar; + XOHCL p4Bar; + result = zBar.Init( + symbol, + period, + zIDX // + ); + result = + result && + zBar.GetPreviousBar(cBar); + result = + result && + cBar.GetPreviousBar(pBar); + result = + result && + pBar.GetPreviousBar(ppBar); + result = + result && + ppBar.GetPreviousBar(p3Bar); + result = + result && + p3Bar.GetPreviousBar(p4Bar); + if (!result) + { + // + zBar.Clean(); + cBar.Clean(); + pBar.Clean(); + ppBar.Clean(); + p3Bar.Clean(); + p4Bar.Clean(); + + // + box.Clean(); + conditions.Clean(); + + // + return result; + } + + // + // Bars Conditions ... + + // + ENUM_X_DIRECTION cBarDir; + + // + // Hammer ... + bool isCBarHammer = helper + .barAnalyser + .IsHammer( + cBar, + cBarDir // + ); + bool isCBarBullishHammer = + isCBarHammer && + IsBullish(cBarDir); + bool isCBarBearishHammer = + isCBarHammer && + IsBearish(cBarDir); + + // + // Rejected ... + bool isCBarRejected = helper + .barAnalyser + .IsRejected( + cBar, + cBarDir, + false, // Force Type ... + true // Force Fibo Pressure ... + ); + bool isCBarBullishRejected = + isCBarRejected && + IsBullish(cBarDir); + bool isCBarBearishRejected = + isCBarRejected && + IsBearish(cBarDir); + + // + // Engulfed ... + bool isCBarEngulfed = helper + .barAnalyser + .IsEngulfed( + cBar, + cBarDir // + ); + bool isCBarBullishEngulfed = + isCBarEngulfed && + IsBullish(cBarDir); + bool isCBarBearishEngulfed = + isCBarEngulfed && + IsBearish(cBarDir); + + // + // Momentum ... + bool isCBarMomentum = helper + .barAnalyser + .IsMomentum( + cBar, + cBarDir, + 1 // + ); + bool isCBarBullishMomentum = + isCBarMomentum && + IsBullish(cBarDir); + bool isCBarBearishMomentum = + isCBarMomentum && + IsBearish(cBarDir); + + // + // Bar Sumarise ... + + // + bool isCBarValidForBullish = + (isCBarBullishHammer || + isCBarBullishRejected || + isCBarBullishMomentum || + isCBarBullishEngulfed); + + // + bool isCBarValidForBearish = + (isCBarBearishHammer || + isCBarBearishRejected || + isCBarBearishMomentum || + isCBarBearishEngulfed); + + // + // Conditions ... + + // + bool isLowsUnderValesGolden = + // + pBar.low < conditions.valesGoldenBuffer[pIDX] && + ppBar.low < conditions.valesGoldenBuffer[ppIDX] && + p3Bar.low < conditions.valesGoldenBuffer[p3IDX] && + p4Bar.low < conditions.valesGoldenBuffer[p4IDX] + // + ; + + // + bool isHighsOverPeaksGolden = + // + pBar.high > conditions.peaksGoldenBuffer[pIDX] && + ppBar.high > conditions.peaksGoldenBuffer[ppIDX] && + p3Bar.high > conditions.peaksGoldenBuffer[p3IDX] && + p4Bar.high > conditions.peaksGoldenBuffer[p4IDX] + // + ; + + // + bool isSwingLowSameAsVale = + conditions.swingLowsBuffer[p4IDX] == conditions.valesBuffer[p4IDX]; + + // + bool isSwingHighSameAsPeak = + conditions.swingHighsBuffer[p4IDX] == conditions.peaksBuffer[p4IDX]; + + // + bool isStrSame = conditions.strBuffer[cIDX] == conditions.strBuffer[pIDX] && + conditions.strBuffer[pIDX] == conditions.strBuffer[ppIDX]; + + // + bool isSameStrBreakedUp = + isStrSame && + conditions.strBuffer[zIDX] > conditions.strBuffer[cIDX]; + + // + bool isSameStrBreakedDown = + isStrSame && + conditions.strBuffer[zIDX] < conditions.strBuffer[cIDX]; + + // + bool isStrBullishVPattern = + // + conditions.strStateBuffer[zIDX] > 0 && + conditions.strStateBuffer[cIDX] > 0 && + conditions.strStateBuffer[pIDX] > 0 && + conditions.strBuffer[pIDX] < conditions.strBuffer[ppIDX] && + conditions.strBuffer[pIDX] < conditions.strBuffer[cIDX] && + conditions.strBuffer[pIDX] < conditions.strBuffer[zIDX] && + conditions.strBuffer[zIDX] > conditions.strBuffer[cIDX] + // + ; + + // + bool isStrBearishVPattern = + // + conditions.strStateBuffer[zIDX] < 0 && + conditions.strStateBuffer[cIDX] < 0 && + conditions.strStateBuffer[pIDX] < 0 && + conditions.strBuffer[pIDX] > conditions.strBuffer[ppIDX] && + conditions.strBuffer[pIDX] > conditions.strBuffer[cIDX] && + conditions.strBuffer[pIDX] > conditions.strBuffer[zIDX] && + conditions.strBuffer[zIDX] < conditions.strBuffer[cIDX] + // + ; + + // + bool isCBarLowInTKZone = + // + cBar.low < conditions.tenkanSenBuffer[cIDX] && + cBar.low > conditions.kijunSenBuffer[cIDX] + // + ; + + // + bool isCBarHighInTKZone = + // + cBar.high > conditions.tenkanSenBuffer[cIDX] && + cBar.high < conditions.kijunSenBuffer[cIDX] + // + ; + + // + // Summarise Conditions ... + + // + bool isBullish = + // + isCBarLowInTKZone && + isCBarBullishRejected && + isCBarValidForBullish && + conditions.isX3MaSlowBullish && + conditions.isTenkanSenOverKijunSen && + conditions.kijunSenBuffer[cIDX] > conditions.x3maSlowBuffer[cIDX] + // + ; + + // + bool isBearish = + // + isCBarHighInTKZone && + isCBarBearishRejected && + isCBarValidForBearish && + conditions.isX3MaSlowBearish && + conditions.isTenkanSenUnderKijunSen && + conditions.kijunSenBuffer[cIDX] < conditions.x3maSlowBuffer[cIDX] + // + ; + + // + result = isBullish || + isBearish; + if (result) + { + // + dir = + isBullish + ? X_DIRECTION_BULLISH + : X_DIRECTION_BEARISH; + + // + double entry = GetEntry( + conditions.symbol, + dir // + ); + double sl = conditions.kijunSenBuffer[cIDX]; + + // + box.dir = dir; + box.symbol = conditions.symbol; + box.period = conditions.period; + + // + box.upper = + isBullish + ? entry + : sl; + + // + box.lower = + isBullish + ? sl + : entry; + + // + box.to = zBar.time; + box.from = p4Bar.time; + + // + box.type = ToString(dir) + "_Signal_" + conditions.symbol + "_" + ToString(conditions.period); + } + + // + result = box.IsValid() && + HasDirection(dir); + + // + // Cleanup Resources ... + + // + if (!result) + { + // + box.Clean(); + conditions.Clean(); + } + + // + zBar.Clean(); + cBar.Clean(); + pBar.Clean(); + ppBar.Clean(); + p3Bar.Clean(); + p4Bar.Clean(); + + // + return result; +} + +///////////////////////////////////////////////////////// + +///////////////////////////////////////////////////////// + +///////////////////////////////////////////////////////// + +///////////////////////////////////////////////////////// + +///////////////////////////////////////////////////////// + +///////////////////////////////////////////////////////// + +///////////////////////////////////////////////////////// + +///////////////////////////////////////////////////////// diff --git a/BKPS/14040203/Documents/BKP/1/signals/3.mq5 b/BKPS/14040203/Documents/BKP/1/signals/3.mq5 new file mode 100644 index 0000000..4b32c90 --- /dev/null +++ b/BKPS/14040203/Documents/BKP/1/signals/3.mq5 @@ -0,0 +1,36 @@ + // isLowsUnderValesGolden && + // conditions.isStrSwitchedToBullish + // + // conditions.isStrBullish && + // conditions.isRejectUpHSM // && + // + // isStrBullishVPattern && + // isSwingLowSameAsVale && + // !conditions.isNewPeakUnderLast + // + // zBar.IsBullish() && + // isSameStrBreakedUp && + // isCBarValidForBullish && + // conditions.isStrBullish && + // conditions.isATROverLast && + // conditions.isVidyaUnderLSM // && + // zBar.close > conditions.strSMHighBuffer[cIDX] + // + + + // isHighsOverPeaksGolden && + // conditions.isStrSwitchedToBearish + // conditions.isStrBearish && + // conditions.isRejectDownLSM // && + // + // isStrBearishVPattern && + // isSwingHighSameAsPeak && + // !conditions.isNewValeOverLast + // + // zBar.IsBearish() && + // isSameStrBreakedDown && + // isCBarValidForBearish && + // conditions.isStrBearish && + // conditions.isATRUnderLast && + // conditions.isVidyaOverHSM // && + // zBar.close < conditions.strSMLowBuffer[cIDX] diff --git a/BKPS/14040203/Documents/BKP/1/signals/f.mq5 b/BKPS/14040203/Documents/BKP/1/signals/f.mq5 new file mode 100644 index 0000000..759608d --- /dev/null +++ b/BKPS/14040203/Documents/BKP/1/signals/f.mq5 @@ -0,0 +1,959 @@ +// +// Detect Signals Based On XPV Indicator Golden Zones ... +// +bool HasXPVConditions( + ENUM_X_CYCLES cycle, + XBoxZone &box, + ENUM_X_DIRECTION &dir, + X121SMCStrategySignalProviderData &provider, + int barIndex = 0 // +) +{ + // + bool result = false; + + // + box.Clean(); + dir = X_DIRECTION_NONE; + + // + // Fil Selected Data ... + XPOIState cState; + X121Conditions cXConditions; + XPOIStateEvents cStateEvents; + XC121SMCCycleHelper *cHelper; + X121SMCCycleConditions cConditions; + result = provider.SelectCycle( + cycle, + cState, + cStateEvents, + cXConditions, + cHelper, + cConditions // + ); + if (!result) + { + // + cState.Clean(); + ZeroMemory(cHelper); + cConditions.Clean(); + cXConditions.Clean(); + cStateEvents.Clean(); + + // + return result; + } + + // + // Normalize Args ... + + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + int idx = -1; + int count = 0; + bool has = false; + + // + int zIDX = barIndex; + int cIDX = zIDX + 1; + int pIDX = cIDX + 1; + int ppIDX = pIDX + 1; + + // + bool isBullish = false; + bool isBearish = false; + + // + XOHCL zBar; + XOHCL cBar; + XOHCL pBar; + XOHCL pPBar; + + // + // Initial Bars ... + result = zBar.Init( + cState.symbol, + cState.period, + barIndex // + ); + result = + result && + zBar.GetPreviousBar(cBar); + result = + result && + cBar.GetPreviousBar(pBar); + result = + result && + pBar.GetPreviousBar(pPBar); + if (!result) + { + // + zBar.Clean(); + cBar.Clean(); + pBar.Clean(); + cState.Clean(); + ZeroMemory(cHelper); + cConditions.Clean(); + cXConditions.Clean(); + + // + return result; + } + + // + // Checking Conditions ... + + // + // Retrieve Some Values ... + + // + double peak = cXConditions.peaksBuffer[cIDX]; + double peakZ = cXConditions.peaksBuffer[zIDX]; + double peakP = cXConditions.peaksBuffer[pIDX]; + double peakPP = cXConditions.peaksBuffer[ppIDX]; + + // + double vale = cXConditions.valesBuffer[cIDX]; + double valeZ = cXConditions.valesBuffer[zIDX]; + double valeP = cXConditions.valesBuffer[pIDX]; + double valePP = cXConditions.valesBuffer[ppIDX]; + + // + double atrUpperSM = cXConditions.atrUpperSMBuffer[cIDX]; + double atrLowerSM = cXConditions.atrLowerSMBuffer[cIDX]; + + // + double atrUpperSMZ = cXConditions.atrUpperSMBuffer[zIDX]; + double atrLowerSMZ = cXConditions.atrLowerSMBuffer[zIDX]; + + // + double atrUpperSMP = cXConditions.atrUpperSMBuffer[pIDX]; + double atrLowerSMP = cXConditions.atrLowerSMBuffer[pIDX]; + + // + double atrUpperSMPP = cXConditions.atrUpperSMBuffer[ppIDX]; + double atrLowerSMPP = cXConditions.atrLowerSMBuffer[ppIDX]; + + // + double rsiChange = cXConditions.rsiChangeBuffer[cIDX]; + double rsiChangeZ = cXConditions.rsiChangeBuffer[zIDX]; + double rsiChangeP = cXConditions.rsiChangeBuffer[pIDX]; + double rsiChangePP = cXConditions.rsiChangeBuffer[ppIDX]; + + // + double rsiChangeSM = cXConditions.rsiChangeSMBuffer[cIDX]; + double rsiChangeSMZ = cXConditions.rsiChangeSMBuffer[zIDX]; + double rsiChangeSMP = cXConditions.rsiChangeSMBuffer[pIDX]; + double rsiChangeSMPP = cXConditions.rsiChangeSMBuffer[ppIDX]; + + // + double peaksGolden = cXConditions.peaksGoldenBuffer[cIDX]; + double peaksGoldenZ = cXConditions.peaksGoldenBuffer[zIDX]; + double peaksGoldenP = cXConditions.peaksGoldenBuffer[pIDX]; + double peaksGoldenPP = cXConditions.peaksGoldenBuffer[ppIDX]; + + // + double valesGolden = cXConditions.valesGoldenBuffer[cIDX]; + double valesGoldenZ = cXConditions.valesGoldenBuffer[zIDX]; + double valesGoldenP = cXConditions.valesGoldenBuffer[pIDX]; + double valesGoldenPP = cXConditions.valesGoldenBuffer[ppIDX]; + + // + double priceChange = cXConditions.priceChangeBuffer[cIDX]; + double priceChangeZ = cXConditions.priceChangeBuffer[zIDX]; + double priceChangeP = cXConditions.priceChangeBuffer[pIDX]; + double priceChangePP = cXConditions.priceChangeBuffer[ppIDX]; + + // + double priceChangeSM = cXConditions.priceChangeSMBuffer[cIDX]; + double priceChangeSMZ = cXConditions.priceChangeSMBuffer[zIDX]; + double priceChangeSMP = cXConditions.priceChangeSMBuffer[pIDX]; + double priceChangeSMPP = cXConditions.priceChangeSMBuffer[ppIDX]; + + // + // + // + + // + bool isPSwingLow = + // + (pBar.low < pPBar.low && + pBar.low < cBar.low && + zBar.open > cBar.low) + // + ; + + // + bool isCSwingLow = + // + (pBar.low < pPBar.low && + cBar.low < pBar.low && + zBar.close > cBar.low) + // + ; + + // + bool isSwingLow = + // + isPSwingLow || + isCSwingLow + // + ; + + // + bool isPSwingHigh = + // + pBar.high >= pPBar.high && + pBar.high > cBar.high && + zBar.open < cBar.high + // + ; + + // + bool isCSwingHigh = + // + (pBar.high >= pPBar.high && + cBar.high > pBar.high && + zBar.close < cBar.high) + // + ; + + // + bool isSwingHigh = + // + isPSwingHigh && + isCSwingHigh + // + ; + + // + bool isBarsOverPeaksGoldenZone = + // + cBar.high > peaksGolden && + pBar.high > peaksGoldenP + // + ; + + // + bool isBarsUnderValesGoldenZone = + // + cBar.low < valesGolden && + pBar.low < valesGoldenP + // + ; + + // + bool isBarsOverAtrUpper = + // + cBar.high > atrUpperSM && + pBar.high > atrUpperSMP + // + ; + + // + bool isBarsUnderAtrLower = + // + cBar.low < atrLowerSM && + pBar.low < atrLowerSMP + // + ; + + // + bool isRsiChangeOverAtrUpper = + rsiChangeP > atrUpperSMP; + + // + bool isRsiChangeUnderAtrLower = + rsiChangeP < atrLowerSMP; + + // + bool isRsiChangeOverPeaksGoldenZone = + rsiChangeP > peaksGoldenP; + + // + bool isRsiChangeUnderValesGoldenZone = + rsiChangeP < valesGoldenP; + + // + bool isPriceChangeOverAtrUpper = + priceChangeP > atrUpperSMP; + + // + bool isPriceChangeUnderAtrLower = + priceChangeP < atrLowerSMP; + + // + bool isPriceChangeOverPeaksGoldenZone = + priceChangeP > peaksGoldenP; + + // + bool isPriceChangeUnderValesGoldenZone = + priceChangeP < valesGoldenP; + + // + // XPV Peaks or Vales ... + + // + bool isCBarEqualsToPeak = cBar.high == peak; + bool isCBarEqualsToVale = cBar.low == vale; + + // + bool isPBarEqualsToPeak = pBar.high == peakP; + bool isPBarEqualsToVale = pBar.low == valeP; + + // + bool isPPBarEqualsToPeak = pPBar.high == peakPP; + bool isPPBarEqualsToVale = pPBar.low == valePP; + + // + bool isBarsEqualsToPeak = isCBarEqualsToPeak || + isPBarEqualsToPeak || + isPPBarEqualsToPeak; + bool isBarsEqualsToVale = isCBarEqualsToVale || + isPBarEqualsToVale || + isPPBarEqualsToVale; + + // + // Detect VPatterns ... + + // + bool isRsiChangeBullishVPattern = + // + rsiChangeP < rsiChangePP && + rsiChangeP < rsiChange && + rsiChangeP < rsiChangeZ + // + ; + + // + bool isRsiChangeBearishVPattern = + // + rsiChangeP > rsiChangePP && + rsiChangeP > rsiChange && + rsiChangeP > rsiChangeZ + // + ; + + // + bool isRsiChangeBullish = + // + (isRsiChangeUnderAtrLower && + isRsiChangeBullishVPattern && + isRsiChangeUnderValesGoldenZone) + // + ; + + bool isRsiChangeBearish = + // + (isRsiChangeOverAtrUpper && + isRsiChangeBearishVPattern && + isRsiChangeOverPeaksGoldenZone) + // + ; + + // + bool isPriceChangeBullishVPattern = + // + priceChangeP < priceChangePP && + priceChangeP < priceChange && + priceChangeP < priceChangeZ + // + ; + + // + bool isPriceChangeBearishVPattern = + // + priceChangeP > priceChangePP && + priceChangeP > priceChange && + priceChangeP > priceChangeZ + // + ; + + // + bool isPriceChangeBullish = + // + (isPriceChangeUnderAtrLower && + isPriceChangeBullishVPattern && + isPriceChangeUnderValesGoldenZone) + // + ; + + // + bool isPriceChangeBearish = + // + (isPriceChangeOverAtrUpper && + isPriceChangeBearishVPattern && + isPriceChangeOverPeaksGoldenZone) + // + ; + + // + // XVWAP ... + + // + bool isVWapIsBullish = + // + (cXConditions.isVWapBullishOrdered && + cXConditions.isVWapSwitchedToBullishState) + // + || + // + (cXConditions.isVWapBullishState && + cXConditions.isVWapSwitchedToBullishOrdered) + // + ; + + // + bool isVWapIsBearish = + // + (cXConditions.isVWapBearishOrdered && + cXConditions.isVWapSwitchedToBearishState) + // + || + // + (cXConditions.isVWapBearishState && + cXConditions.isVWapSwitchedToBearishOrdered) + // + ; + + // + // Checking Bar States ... + + // + ENUM_X_DIRECTION cBarPosDir; + bool isCBarValidForPosition = + cHelper + .mBarAnalyser + .IsValidForPosition( + cBar, + cBarPosDir // + ); + + // + ENUM_X_DIRECTION pBarPosDir; + bool isPBarValidForPosition = + cHelper + .mBarAnalyser + .IsValidForPosition( + pBar, + pBarPosDir // + ); + + // + bool isBarValidForBullish = + // + (isCBarValidForPosition && + IsBullish(cBarPosDir)) + // + && + // + (isPBarValidForPosition && + IsBullish(pBarPosDir)) + // + ; + + // + bool isBarValidForBearish = + // + (isCBarValidForPosition && + IsBearish(cBarPosDir)) + // + && + // + (isPBarValidForPosition && + IsBearish(pBarPosDir)) + // + ; + + // + // Summarize Conditions ... + + // + isBullish = + // + // isVWapIsBullish && + // isBarsEqualsToVale && + // isBarValidForBullish && + isSwingLow && + isBarsUnderAtrLower && + isRsiChangeBullish && + isPriceChangeBullish && + isBarsUnderValesGoldenZone + // + ; + + // + isBearish = + // + // isVWapIsBearish && + // isBarsEqualsToPeak && + // isBarValidForBearish && + isSwingHigh && + isBarsOverAtrUpper && + isRsiChangeBearish && + isPriceChangeBearish && + isBarsOverPeaksGoldenZone + // + ; + + // + // Filling Requirements ... + result = + isBullish || + isBearish; + if (result) + { + // + dir = + isBullish + ? X_DIRECTION_BULLISH + : X_DIRECTION_BEARISH; + + // + box.dir = dir; + box.from = pPBar.time; + box.to = TimeCurrent(); + box.symbol = cBar.symbol; + box.period = cBar.period; + + // + double points = GetPoints(box.symbol); + + // + // Usually is Preffered SL ... + double pivot = 0; + + // + // Usually is Current Price or Entry Price ... + double point = GetEntry( + cBar.symbol, + dir // + ); + + // + box.upper = + isBullish + ? point + : pivot; + + // + box.lower = + isBullish + ? pivot + : point; + + // + XCPOIDrawer *drawer = provider.visionCycleHelper.mPOIDrawer; + bool drawBoxes = true; + if (drawBoxes) + { + // + if (box.IsValid()) + { + // + XCBoxObject *iObj; + bool isCreated = drawer.DrawBox( + box, + iObj // + ); + + // + if (isCreated) + { + // + // TODO: ... + } + } + } + } + + // + // Check All Conditions ... + result = + box.IsValid() && + HasDirection(dir) && + (isBullish || + isBearish); + + // + // Cleanup Resources ... + zBar.Clean(); + cBar.Clean(); + pBar.Clean(); + pPBar.Clean(); + cState.Clean(); + cConditions.Clean(); + cConditions.Clean(); + ZeroMemory(cHelper); + cStateEvents.Clean(); + cXConditions.Clean(); + + // + return result; +} + +// +bool HasXSTRConditions( + ENUM_X_CYCLES cycle, + XBoxZone &box, + ENUM_X_DIRECTION &dir, + X121SMCStrategySignalProviderData &provider, + int barIndex = 0 // +) +{ + // + bool result = false; + + // + box.Clean(); + dir = X_DIRECTION_NONE; + + // + // Fil Selected Data ... + XPOIState cState; + X121Conditions cXConditions; + XPOIStateEvents cStateEvents; + XC121SMCCycleHelper *cHelper; + X121SMCCycleConditions cConditions; + result = provider.SelectCycle( + cycle, + cState, + cStateEvents, + cXConditions, + cHelper, + cConditions // + ); + if (!result) + { + // + cState.Clean(); + ZeroMemory(cHelper); + cConditions.Clean(); + cXConditions.Clean(); + cStateEvents.Clean(); + + // + return result; + } + + // + // Normalize Args ... + + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + int idx = -1; + int count = 0; + bool has = false; + + // + int zIDX = barIndex; + int cIDX = zIDX + 1; + int pIDX = cIDX + 1; + int ppIDX = pIDX + 1; + + // + bool isBullish = false; + bool isBearish = false; + + // + XOHCL zBar; + XOHCL cBar; + XOHCL pBar; + XOHCL pPBar; + + // + // Initial Bars ... + result = zBar.Init( + cState.symbol, + cState.period, + barIndex // + ); + result = + result && + zBar.GetPreviousBar(cBar); + result = + result && + cBar.GetPreviousBar(pBar); + result = + result && + pBar.GetPreviousBar(pPBar); + if (!result) + { + // + zBar.Clean(); + cBar.Clean(); + pBar.Clean(); + cState.Clean(); + ZeroMemory(cHelper); + cConditions.Clean(); + cXConditions.Clean(); + + // + return result; + } + + // + // Checking Conditions ... + + // + // XSTR ... + bool isStrIsBullish = + (cXConditions.isStrBullish || + cXConditions.isStrSwitchedToBullish); + bool isStrIsBearish = + (cXConditions.isStrBearish || + cXConditions.isStrSwitchedToBearish); + + // + // Detecting Str Box ... + XBoxZone strBox; + bool hasStrBox = false; + if (!hasStrBox) + { + // + hasStrBox = + cXConditions.isStrBullish || + cXConditions.isStrBearish; + if (hasStrBox) + { + // + ENUM_X_DIRECTION strDir = + cXConditions.isStrBullish + ? X_DIRECTION_BULLISH + : X_DIRECTION_BEARISH; + + // + XOHCL lastBar; + ENUM_X_DIRECTION lastDir; + bool hasLast = + cHelper + .DetectNearestStrSwitched( + lastBar, + lastDir, + zIDX // + ); + + // + XOHCL prevBar; + ENUM_X_DIRECTION prevDir; + bool hasPrev = + hasLast && + cHelper + .DetectNearestStrSwitched( + prevBar, + prevDir, + lastBar.Index() + 1 // + ); + + // + hasStrBox = + hasLast && + hasPrev; + if (hasStrBox) + { + // + int fromIDX = MathMax( + lastBar.Index(), + prevBar.Index() // + ); + + // + string symbol = cBar.symbol; + ENUM_TIMEFRAMES period = cBar.period; + + // + datetime from = GetBarTime( + symbol, + period, + fromIDX // + ); + + // + int length = fromIDX - barIndex; + + // + double upper = zBar.FindHighest( + length, + MODE_HIGH // + ); + + // + double lower = zBar.FindLowest( + length, + MODE_LOW // + ); + + // + strBox.from = from; + strBox.dir = strDir; + strBox.lower = lower; + strBox.upper = upper; + strBox.symbol = symbol; + strBox.period = period; + strBox.type = "XSTRBox"; + strBox.to = TimeCurrent(); + + // + hasStrBox = strBox.IsValid(); + } + + // + lastBar.Clean(); + prevBar.Clean(); + } + } + + // + // XFastMa ... + + // + bool isFastMaOverStr = + (cXConditions.x3maFastBuffer[cIDX] > cXConditions.strBuffer[cIDX]); + + // + bool isFastMaUnderStr = + (cXConditions.x3maFastBuffer[cIDX] < cXConditions.strBuffer[cIDX]); + + // + bool isFastMaBullishReject = + cBar.low < pBar.low && + cBar.low > cXConditions.strBuffer[cIDX] && + cBar.low < cXConditions.x3maFastBuffer[cIDX] && + cBar.GetDown() > cXConditions.x3maFastBuffer[cIDX]; + + // + bool isFastMaBearishReject = + cBar.high > pBar.high && + cBar.high < cXConditions.strBuffer[cIDX] && + cBar.high > cXConditions.x3maFastBuffer[cIDX] && + cBar.GetUp() < cXConditions.x3maFastBuffer[cIDX]; + + // + // Summarize Conditions ... + + // + isBullish = + // + // false + hasStrBox && + isStrIsBullish && + isFastMaOverStr && + isFastMaBullishReject + // + // + ; + + // + isBearish = + // + // false + hasStrBox && + isStrIsBearish && + isFastMaUnderStr && + isFastMaBearishReject + // + ; + + // + // Filling Requirements ... + result = + isBullish || + isBearish; + if (result) + { + // + XCPOIDrawer *drawer = provider.visionCycleHelper.mPOIDrawer; + XCBoxObject *iObj; + bool isCreated = drawer.DrawBox( + strBox, + iObj // + ); + if (isCreated) + { + // + Print("STRBox"); + } + + // + dir = + isBullish + ? X_DIRECTION_BULLISH + : X_DIRECTION_BEARISH; + + // + box.dir = dir; + box.from = pPBar.time; + box.to = TimeCurrent(); + box.symbol = cBar.symbol; + box.period = cBar.period; + + // + double points = GetPoints(box.symbol); + + // + double pivot = cXConditions.strBuffer[cIDX]; + // isBullish + // ? cBar.low - (points * 5) + // : cBar.high + (points * 5); + + // + double point = GetEntry( + cBar.symbol, + dir // + ); + + // + box.upper = + isBullish + ? point + : pivot; + + // + box.lower = + isBullish + ? pivot + : point; + + // + bool drawBoxes = true; + if (drawBoxes) + { + // + } + } + + // + // Check All Conditions ... + result = + box.IsValid() && + HasDirection(dir) && + (isBullish || + isBearish); + + // + // Cleanup Resources ... + zBar.Clean(); + cBar.Clean(); + pBar.Clean(); + pPBar.Clean(); + cState.Clean(); + strBox.Clean(); + cConditions.Clean(); + cConditions.Clean(); + ZeroMemory(cHelper); + cStateEvents.Clean(); + cXConditions.Clean(); + + // + return result; +} diff --git a/BKPS/14040203/Documents/BKP/Indicators/bos-choch.ex5 b/BKPS/14040203/Documents/BKP/Indicators/bos-choch.ex5 new file mode 100644 index 0000000..b3aea77 Binary files /dev/null and b/BKPS/14040203/Documents/BKP/Indicators/bos-choch.ex5 differ diff --git a/BKPS/14040203/Documents/BKP/Indicators/bos-choch.mq5 b/BKPS/14040203/Documents/BKP/Indicators/bos-choch.mq5 new file mode 100644 index 0000000..f8ea516 --- /dev/null +++ b/BKPS/14040203/Documents/BKP/Indicators/bos-choch.mq5 @@ -0,0 +1,128 @@ +#property copyright "Your Name" +#property link "https://www.example.com" +#property version "1.00" +#property indicator_chart_window +#property indicator_buffers 0 +#property indicator_plots 0 + +// Input parameters +input int SwingPeriod = 5; // Lookback period for swing detection + +// Global variables +double LastSwingHigh = 0, LastSwingLow = 0; +bool IsBullish = false; + +//+------------------------------------------------------------------+ +int OnInit() +{ + return(INIT_SUCCEEDED); +} + +//+------------------------------------------------------------------+ +int OnCalculate(const int rates_total, + const int prev_calculated, + const datetime &time[], + const double &open[], + const double &high[], + const double &low[], + const double &close[], + const long &tick_volume[], + const long &volume[], + const int &spread[]) +{ + // Start from the latest bar + for(int i = rates_total - prev_calculated - 1; i >= 0; i--) + { + // Detect swing high and low + if(IsSwingHigh(high, low, i, SwingPeriod)) + { + LastSwingHigh = high[i]; + CheckStructure(i, high[i], low[i], time[i]); + } + if(IsSwingLow(high, low, i, SwingPeriod)) + { + LastSwingLow = low[i]; + CheckStructure(i, high[i], low[i], time[i]); + } + } + return(rates_total); +} + +//+------------------------------------------------------------------+ +bool IsSwingHigh(const double &high[], const double &low[], int index, int period) +{ + if(index < period || index >= ArraySize(high) - period) return false; + for(int i = 1; i <= period; i++) + { + if(high[index] <= high[index - i] || high[index] <= high[index + i]) + return false; + } + return true; +} + +//+------------------------------------------------------------------+ +bool IsSwingLow(const double &high[], const double &low[], int index, int period) +{ + if(index < period || index >= ArraySize(low) - period) return false; + for(int i = 1; i <= period; i++) + { + if(low[index] >= low[index - i] || low[index] >= low[index + i]) + return false; + } + return true; +} + +//+------------------------------------------------------------------+ +void CheckStructure(int index, double high, double low, datetime time) +{ + // Determine trend direction + if(LastSwingHigh > 0 && LastSwingLow > 0) + { + IsBullish = (LastSwingHigh > LastSwingLow); + + // Check for BOS + if(IsBullish && high > LastSwingHigh) + { + LastSwingHigh = high; + ObjectCreate(0, "BOS_" + TimeToString(time), OBJ_TEXT, 0, time, high); + ObjectSetString(0, "BOS_" + TimeToString(time), OBJPROP_TEXT, "BOS"); + ObjectSetInteger(0, "BOS_" + TimeToString(time), OBJPROP_COLOR, clrGreen); + Alert("Break of Structure (BOS) detected at " + DoubleToString(high, 5)); + } + else if(!IsBullish && low < LastSwingLow) + { + LastSwingLow = low; + ObjectCreate(0, "BOS_" + TimeToString(time), OBJ_TEXT, 0, time, low); + ObjectSetString(0, "BOS_" + TimeToString(time), OBJPROP_TEXT, "BOS"); + ObjectSetInteger(0, "BOS_" + TimeToString(time), OBJPROP_COLOR, clrRed); + Alert("Break of Structure (BOS) detected at " + DoubleToString(low, 5)); + } + + // Check for CHoCH + if(IsBullish && low < LastSwingLow) + { + LastSwingLow = low; + ObjectCreate(0, "CHoCH_" + TimeToString(time), OBJ_TEXT, 0, time, low); + ObjectSetString(0, "CHoCH_" + TimeToString(time), OBJPROP_TEXT, "CHoCH"); + ObjectSetInteger(0, "CHoCH_" + TimeToString(time), OBJPROP_COLOR, clrRed); + Alert("Change of Character (CHoCH) detected at " + DoubleToString(low, 5)); + IsBullish = false; // Trend may reverse + } + else if(!IsBullish && high > LastSwingHigh) + { + LastSwingHigh = high; + ObjectCreate(0, "CHoCH_" + TimeToString(time), OBJ_TEXT, 0, time, high); + ObjectSetString(0, "CHoCH_" + TimeToString(time), OBJPROP_TEXT, "CHoCH"); + ObjectSetInteger(0, "CHoCH_" + TimeToString(time), OBJPROP_COLOR, clrGreen); + Alert("Change of Character (CHoCH) detected at " + DoubleToString(high, 5)); + IsBullish = true; // Trend may reverse + } + } +} + +//+------------------------------------------------------------------+ +void OnDeinit(const int reason) +{ + ObjectsDeleteAll(0, "BOS_"); + ObjectsDeleteAll(0, "CHoCH_"); +} \ No newline at end of file diff --git a/BKPS/14040203/Documents/BKP/Indicators/x-saherelm.x121.xsmc.mq5 b/BKPS/14040203/Documents/BKP/Indicators/x-saherelm.x121.xsmc.mq5 new file mode 100644 index 0000000..44b827b --- /dev/null +++ b/BKPS/14040203/Documents/BKP/Indicators/x-saherelm.x121.xsmc.mq5 @@ -0,0 +1,888 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Indicator +// ------------------------------------------------- +// Name: X121 XSMC +// Description: XSMC ... +// +// +// 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 XSMC Indicator" +#property strict + +// +// Definitions ... + +// +#define ShortName "X121 XSMC" + +// +// Includes Common Library ... +#include "../Libraries/x-saherelm.common.lib.mq5" + +// +// Inputs ... + +// +// Market ... +input group "Market"; +input int swingLength = 5; // Swing Length + +// +input group "Presentation"; + +// +input int startCalculationForLastBars = 1000; // Calculate Last n Bars +input int trendArrowCode = 117; // Trend Arrow +input int swingLowsArrowCode = 159; // Swing Lows Arrow +input int swingHighsArrowCode = 159; // Swing Highs Arrow +input int swingLowBOSArrowCode = 233; // Swing Low BOS Arrow +input int swingHighBOSArrowCode = 234; // Swing High BOS Arrow +input int swingLowCHOCHArrowCode = 225; // Swing Low CHOCH Arrow +input int swingHighCHOCHArrowCode = 226; // Swing High CHOCH Arrow + +// +input bool showTrend = true; // Show Trend +input bool showSwingLows = true; // Show Swing Lows +input bool showSwingHighs = true; // Show Swing Highs +input bool showSwingLowBOS = true; // Show Swing Low BOS +input bool showSwingHighBOS = true; // Show Swing High BOS +input bool showSwingLowCHOCH = true; // Show Swing Low CHOCH +input bool showSwingHighCHOCH = true; // Show Swing High CHOCH + +// +// Buffers ... + +// +#define hideColorIDX 0 +#define bullishColorIDX 1 +#define bearishColorIDX 2 +#define neuturalColorIDX 3 + +// +#define emptyValue 0.0 + +// +#property indicator_chart_window + +// +#property indicator_buffers 9 +#property indicator_plots 7 + +// +// Plot Buffers ... + +// +// Swing Lows ... + +// +#define swingLowsBufferIndex 0 +double swingLowsBuffer[]; + +// +#property indicator_label1 "X121 SWL" +#property indicator_type1 DRAW_ARROW +#property indicator_color1 clrAqua +#property indicator_width1 1 + +// +// Swng Highs ... + +// +#define swingHighsBufferIndex 1 +double swingHighsBuffer[]; + +// +#property indicator_label2 "X121 SWH" +#property indicator_type2 DRAW_ARROW +#property indicator_color2 clrMagenta +#property indicator_width2 1 + +// +// Swing Low BOS ... +#define swingLowsBOSBufferIndex 2 +double swingLowsBOSBuffer[]; + +// +#property indicator_label3 "X121 SWLBOS" +#property indicator_type3 DRAW_ARROW +#property indicator_color3 clrAqua +#property indicator_width3 3 + +// +// Swing High BOS ... +#define swingHighsBOSBufferIndex 3 +double swingHighsBOSBuffer[]; + +// +#property indicator_label4 "X121 SWHBOS" +#property indicator_type4 DRAW_ARROW +#property indicator_color4 clrMagenta +#property indicator_width4 3 + +// +// Swing Low CHOCH ... +#define swingLowsCHOCHBufferIndex 4 +double swingLowsCHOCHBuffer[]; + +// +#property indicator_label5 "X121 SWLCHOCH" +#property indicator_type5 DRAW_ARROW +#property indicator_color5 clrYellow +#property indicator_width5 3 + +// +// Swing High CHOCH ... +#define swingHighsCHOCHBufferIndex 5 +double swingHighsCHOCHBuffer[]; + +// +#property indicator_label6 "X121 SWHCHOCH" +#property indicator_type6 DRAW_ARROW +#property indicator_color6 clrYellow +#property indicator_width6 3 + +// +// Trend ... +#define trendBufferIndex 6 +double trendBuffer[]; + +#define trendColorBufferIndex 7 +double trendColorBuffer[]; + +// +#property indicator_label7 "X121 TRND" +#property indicator_type7 DRAW_COLOR_ARROW +#property indicator_color7 CLR_NONE, clrAqua, clrMagenta, clrGray +#property indicator_width7 3 + +// +// Data Buffers ... + +// +int mLastBufferIndex = 7; + +// +// Trend State ... +#define trendStateBufferIndex mLastBufferIndex + 1 +double trendStateBuffer[]; + +// +// Variables, Properties and etc ... + +// +// this counts Available Bars ... +int limit; + +// +int maxLength; + +// +double lastSwing = 0.0; +ENUM_X_DIRECTION lastSwingDir = X_DIRECTION_NONE; + +// +// Event Handlers ... + +/** + * Initialize Indicator ... + * + * @return ( int ) + */ +int OnInit() +{ + // + // Validate Inputs ... + if (!ValidateInputs()) + { + return INIT_PARAMETERS_INCORRECT; + } + + // + // Initialize Indicator Handlers ... + + // + // because in some cases we may have more than one input for + // calculation and we must prevent any calculation + // untill we pass the biggest input length, here we get max Input length + // and then wait until pass it ... + maxLength = ExtractMaxLengthOfInputs(); + + // + // Define Index Buffers ... + DefineBuffers(); + + // + // Set Indicator ShortName ... + SetIndicatorName(); + + // + // Init Succeed ... + return INIT_SUCCEEDED; +} + +/** + * De Initialize Indicator ... + * + * @param reason: Integer, De Initialization Reason ... + */ +void OnDeinit(const int reason) +{ + // + // REASON_PROGRAM 0 The EA has stopped working calling the ExpertRemove() function + // REASON_REMOVE 1 Program removed from a chart + // REASON_RECOMPILE 2 Program recompiled + // REASON_CHARTCHANGE 3 A symbol or a chart period is changed + // REASON_CHARTCLOSE 4 Chart closed + // REASON_PARAMETERS 5 Inputs changed by a user + // REASON_ACCOUNT 6 Another account has been activated or reconnection to the trade server has occurred due to changes in the account settings + // REASON_TEMPLATE 7 Another chart template applied + // REASON_INITFAILED 8 The OnInit() handler returned a non-zero value + // REASON_CLOSE 9 Terminal closed +} + +/** + * Calculate Bars ... + * + * @param rates_total: Integer, Total Bars on Chart ... + * @param prev_calculated: Integer, Total Calculated Bars on Charts ... + * @param time: DateTime Array, History of Open Time ... + * @param open: Double Array, History of Open Prices ... + * @param high: Double Array, History of High Prices ... + * @param low: Double Array, History of Low Prices ... + * @param close: Double Array, History of Close Prices ... + * @param tick_volume: Long, History of Tick Volumes on Bar ... + * @param volume: Long, History of Trade Volumes ... + * @param spread: Double, History of Spread Price ... + * + * @return ( int ) + */ +int OnCalculate( + const int rates_total, + const int prev_calculated, + const datetime &time[], + const double &open[], + const double &high[], + const double &low[], + const double &close[], + const long &tick_volume[], + const long &volume[], + const int &spread[] // +) +{ + // + // Prepare Buffers ... + ArraySetAsSeries(time, true); + ArraySetAsSeries(open, true); + ArraySetAsSeries(high, true); + ArraySetAsSeries(low, true); + ArraySetAsSeries(close, true); + ArraySetAsSeries(tick_volume, true); + ArraySetAsSeries(volume, true); + ArraySetAsSeries(spread, true); + + // + limit = (prev_calculated > rates_total || prev_calculated <= 0) + ? rates_total + : (rates_total - prev_calculated) + 1; + + // + // Main Loop ... + for (int i = limit - 1; i >= 0 && !IsStopped(); i--) + { + // + CalculateBuffers( + i, + prev_calculated, + rates_total, + // + open, + high, + close, + low, + tick_volume // + ); + } + + // + return rates_total; +} + +// +// Functions ... + +/** + * Validate Input Args for Initialization ... + * + * @return ( bool ) + */ +bool ValidateInputs() +{ + // + bool result = + // + swingLength > 0 + // + ; + + // + return result; +} + +/** + * Extract Max Length of Inputs ... + * + * @return ( int ) + */ +int ExtractMaxLengthOfInputs() +{ + // + int result = 0; + + // + result = swingLength; + + // + return result; +} + +/** + * Define Required Buffers ... + */ +void DefineBuffers() +{ + // + // Plot Buffers ... + + // + // Swing Lows ... + + // + ENUM_DRAW_TYPE swingLowsDrawType = showSwingLows ? DRAW_ARROW : DRAW_NONE; + + // + ArraySetAsSeries(swingLowsBuffer, true); + SetIndexBuffer(swingLowsBufferIndex, swingLowsBuffer, INDICATOR_DATA); + + // + PlotIndexSetInteger(swingLowsBufferIndex, PLOT_SHOW_DATA, showSwingLows); + PlotIndexSetInteger(swingLowsBufferIndex, PLOT_DRAW_TYPE, swingLowsDrawType); + + // + PlotIndexSetDouble(swingLowsBufferIndex, PLOT_EMPTY_VALUE, emptyValue); + PlotIndexSetInteger(swingLowsBufferIndex, PLOT_ARROW, swingLowsArrowCode); + + // + // Swing Highs ... + + // + ENUM_DRAW_TYPE swingHighsDrawType = showSwingHighs ? DRAW_ARROW : DRAW_NONE; + + // + ArraySetAsSeries(swingHighsBuffer, true); + SetIndexBuffer(swingHighsBufferIndex, swingHighsBuffer, INDICATOR_DATA); + + // + PlotIndexSetInteger(swingHighsBufferIndex, PLOT_SHOW_DATA, showSwingHighs); + PlotIndexSetInteger(swingHighsBufferIndex, PLOT_DRAW_TYPE, swingHighsDrawType); + + // + PlotIndexSetDouble(swingHighsBufferIndex, PLOT_EMPTY_VALUE, emptyValue); + PlotIndexSetInteger(swingHighsBufferIndex, PLOT_ARROW, swingHighsArrowCode); + + // + // Trends ... + + // + ENUM_DRAW_TYPE trendDrawType = showTrend ? DRAW_COLOR_ARROW : DRAW_NONE; + + // + ArraySetAsSeries(trendBuffer, true); + SetIndexBuffer(trendBufferIndex, trendBuffer, INDICATOR_DATA); + + // + PlotIndexSetInteger(trendBufferIndex, PLOT_SHOW_DATA, showTrend); + PlotIndexSetInteger(trendBufferIndex, PLOT_DRAW_TYPE, trendDrawType); + + // + PlotIndexSetDouble(trendBufferIndex, PLOT_EMPTY_VALUE, emptyValue); + PlotIndexSetInteger(trendBufferIndex, PLOT_ARROW, trendArrowCode); + + // + ArraySetAsSeries(trendColorBuffer, true); + SetIndexBuffer(trendColorBufferIndex, trendColorBuffer, INDICATOR_COLOR_INDEX); + + // + // SWLBOS ... + + // + ENUM_DRAW_TYPE swingLowBOSDrawType = showSwingLowBOS ? DRAW_ARROW : DRAW_NONE; + + // + ArraySetAsSeries(swingLowsBOSBuffer, true); + SetIndexBuffer(swingLowsBOSBufferIndex, swingLowsBOSBuffer, INDICATOR_DATA); + + // + PlotIndexSetInteger(swingLowsBOSBufferIndex, PLOT_SHOW_DATA, showSwingLowBOS); + PlotIndexSetInteger(swingLowsBOSBufferIndex, PLOT_DRAW_TYPE, swingLowBOSDrawType); + + // + PlotIndexSetDouble(swingLowsBOSBufferIndex, PLOT_EMPTY_VALUE, emptyValue); + PlotIndexSetInteger(swingLowsBOSBufferIndex, PLOT_ARROW, swingLowBOSArrowCode); + + // + // SWHBOS ... + + // + ENUM_DRAW_TYPE swingHighBOSDrawType = showSwingHighBOS ? DRAW_ARROW : DRAW_NONE; + + // + ArraySetAsSeries(swingHighsBOSBuffer, true); + SetIndexBuffer(swingHighsBOSBufferIndex, swingHighsBOSBuffer, INDICATOR_DATA); + + // + PlotIndexSetInteger(swingHighsBOSBufferIndex, PLOT_SHOW_DATA, showSwingHighBOS); + PlotIndexSetInteger(swingHighsBOSBufferIndex, PLOT_DRAW_TYPE, swingHighBOSDrawType); + + // + PlotIndexSetDouble(swingHighsBOSBufferIndex, PLOT_EMPTY_VALUE, emptyValue); + PlotIndexSetInteger(swingHighsBOSBufferIndex, PLOT_ARROW, swingHighBOSArrowCode); + + // + // SWLCHOCH ... + + // + ENUM_DRAW_TYPE swingLowCHOCHDrawType = showSwingLowCHOCH ? DRAW_ARROW : DRAW_NONE; + + // + ArraySetAsSeries(swingLowsCHOCHBuffer, true); + SetIndexBuffer(swingLowsCHOCHBufferIndex, swingLowsCHOCHBuffer, INDICATOR_DATA); + + // + PlotIndexSetInteger(swingLowsCHOCHBufferIndex, PLOT_SHOW_DATA, showSwingLowCHOCH); + PlotIndexSetInteger(swingLowsCHOCHBufferIndex, PLOT_DRAW_TYPE, swingLowCHOCHDrawType); + + // + PlotIndexSetDouble(swingLowsCHOCHBufferIndex, PLOT_EMPTY_VALUE, emptyValue); + PlotIndexSetInteger(swingLowsCHOCHBufferIndex, PLOT_ARROW, swingLowCHOCHArrowCode); + + // + // SWHCHOCH ... + + // + ENUM_DRAW_TYPE swingHighCHOCHDrawType = showSwingHighCHOCH ? DRAW_ARROW : DRAW_NONE; + + // + ArraySetAsSeries(swingHighsCHOCHBuffer, true); + SetIndexBuffer(swingHighsCHOCHBufferIndex, swingHighsCHOCHBuffer, INDICATOR_DATA); + + // + PlotIndexSetInteger(swingHighsCHOCHBufferIndex, PLOT_SHOW_DATA, showSwingHighCHOCH); + PlotIndexSetInteger(swingHighsCHOCHBufferIndex, PLOT_DRAW_TYPE, swingHighCHOCHDrawType); + + // + PlotIndexSetDouble(swingHighsCHOCHBufferIndex, PLOT_EMPTY_VALUE, emptyValue); + PlotIndexSetInteger(swingHighsCHOCHBufferIndex, PLOT_ARROW, swingHighCHOCHArrowCode); + + // + // Data Buffers ... + + // + ArraySetAsSeries(trendStateBuffer, true); + SetIndexBuffer(trendStateBufferIndex, trendStateBuffer, INDICATOR_CALCULATIONS); +} + +/** + * Set Indicator Short Name and also we can define Buffers Labels ... + */ +void SetIndicatorName() +{ + // + IndicatorSetString(INDICATOR_SHORTNAME, ShortName); + IndicatorSetInteger(INDICATOR_DIGITS, 2); +} + +/** + * Calculate Custom Buffers ... + * + * @param bar_index: Integer, Represent Current Bar ... + * @param prevCalculated: Integer, Represent Previous Calculated Bars ... + * @param ratesTotal: Integer, Represents All Available Bars ... + * @param open: Double Array, History of Open Prices ... + * @param high: Double Array, History of High Prices ... + * @param close: Double Array, History of Close Prices ... + * @param low: Double Array, History of Low Prices ... + * @param tickVolume: Long, History of Tick Volumes on Bar ... + */ +void CalculateBuffers( + int bar_index, // Selected Bar Index + const int prevCalculated, + const int ratesTotal, + const double &open[], + const double &high[], + const double &close[], + const double &low[], + const long &tickVolume[] // +) +{ + // + int barsLimit = startCalculationForLastBars > 0 + ? startCalculationForLastBars + : 0; + // + // bool canCalculate = true; + bool canCalculate = + barsLimit == 0 || + bar_index <= barsLimit; + if (canCalculate) + { + // + CalculateValues( + bar_index, + prevCalculated, + ratesTotal, + open, + high, + close, + low // + ); + } + else + { + FillBuffersZero(bar_index); + } +} + +// +// Custom ... + +/** + * Fill All Bufers to Zero Vlue for Specified Bar Index ... + * + * @param barIndex: Integer ... + */ +void FillBuffersZero(int barIndex) +{ + // + trendBuffer[barIndex] = emptyValue; + swingLowsBuffer[barIndex] = emptyValue; + swingHighsBuffer[barIndex] = emptyValue; + swingLowsBOSBuffer[barIndex] = emptyValue; + swingHighsBOSBuffer[barIndex] = emptyValue; + swingLowsCHOCHBuffer[barIndex] = emptyValue; + swingHighsCHOCHBuffer[barIndex] = emptyValue; + + // + trendColorBuffer[barIndex] = hideColorIDX; + trendStateBuffer[barIndex] = (double)((int)X_DIRECTION_NONE); +} + +/** + * Calculate Values ... + * + * @param bar_index: Integer, Represent Current Bar ... + * @param prevCalculated: Integer, Represent Previous Calculated Bars ... + * @param ratesTotal: Integer, Represents All Available Bars ... + * @param open: Double Array, History of Open Prices ... + * @param high: Double Array, History of High Prices ... + * @param close: Double Array, History of Close Prices ... + * @param low: Double Array, History of Low Prices ... + */ +void CalculateValues( + int bar_index, // Selected Bar Index + const int prevCalculated, + const int ratesTotal, + const double &open[], + const double &high[], + const double &close[], + const double &low[] // +) +{ + // + int lastBarIndex = bar_index + 1; + bool isFirstBar = + startCalculationForLastBars > 0 + ? bar_index == startCalculationForLastBars + : bar_index == ratesTotal; + + // + double iLow = low[bar_index]; + double iHigh = high[bar_index]; + + // + // Swing Low ... + double lastSwingLow = isFirstBar + ? emptyValue + : swingLowsBuffer[lastBarIndex]; + bool isSwingLow = IsSwingLow(high, low, bar_index, swingLength); + double iSwingLow = + !isSwingLow + ? lastSwingLow + : iLow; + swingLowsBuffer[bar_index] = iSwingLow; + + // + // Swing High ... + double lastSwingHigh = isFirstBar + ? emptyValue + : swingHighsBuffer[lastBarIndex]; + bool isSwingHigh = IsSwingHigh(high, low, bar_index, swingLength); + double iSwingHigh = + !isSwingHigh + ? lastSwingHigh + : iHigh; + swingHighsBuffer[bar_index] = iSwingHigh; + + // + // Detect Last Swing/Last Swing Direction ... + bool isSwing = isSwingLow || + isSwingHigh; + if (isSwing) + { + // + if (isSwingLow) + { + // + lastSwing = iSwingLow; + lastSwingDir = X_DIRECTION_BULLISH; + } + else if (isSwingHigh) + { + // + lastSwing = iSwingHigh; + lastSwingDir = X_DIRECTION_BEARISH; + } + } + + // + // Detect Trend ... + + // + // Detecting Trend Direction ... + ENUM_X_DIRECTION lastTendDir = + isFirstBar + ? X_DIRECTION_NONE + : (ENUM_X_DIRECTION)((int)trendStateBuffer[lastBarIndex]); + ENUM_X_DIRECTION iTrendDir = + isSwingLow && + iSwingLow > lastSwingLow + ? X_DIRECTION_BULLISH + : isSwingHigh && + iSwingHigh < lastSwingHigh + ? X_DIRECTION_BEARISH + : lastTendDir; + bool isTrendChanged = + HasDirection(lastTendDir) && + HasDirection(iTrendDir) && + lastTendDir != iTrendDir; + + // + // Detecting Trend State ... + double iTrendState = (int)iTrendDir; + trendStateBuffer[bar_index] = iTrendState; + + // + // Detecting Trend Value ... + double lastTrendValue = + isFirstBar + ? emptyValue + : trendBuffer[lastBarIndex]; + double iTrendValue = + IsBullish(iTrendDir) + ? isTrendChanged + ? iLow + : lastTrendValue + : IsBearish(iTrendDir) + ? isTrendChanged + ? iHigh + : lastTrendValue + : lastTrendValue; + trendBuffer[bar_index] = iTrendValue; + + // + // Detecting Trend Color ... + double iTrendColorValue = + IsBullish(iTrendDir) + ? bullishColorIDX + : IsBearish(iTrendDir) + ? bearishColorIDX + : hideColorIDX; + bool isTrendBreaked = false; + if (IsBullish(iTrendDir)) + { + // + isTrendBreaked = iHigh < lastTrendValue; + if (isTrendBreaked) + { + iTrendColorValue = bearishColorIDX; + } + } + else if (IsBearish(iTrendDir)) + { + // + isTrendBreaked = iLow > lastTrendValue; + if (isTrendBreaked) + { + iTrendColorValue = bullishColorIDX; + } + } + trendColorBuffer[bar_index] = iTrendColorValue; + + // + bool isTrendBullish = iTrendColorValue == bullishColorIDX; + bool isTrendBearish = iTrendColorValue == bearishColorIDX; + + // + // Detecting BOS ... + + // + // Swing Low BOS ... + double lastSwingLowBOSValue = + isFirstBar + ? emptyValue + : swingLowsBOSBuffer[lastBarIndex]; + double iSwingLowBOSValue = + isTrendBullish && + iHigh > lastSwing + ? iLow + : emptyValue; + bool isSwingLowBOSBreaked = + iSwingLowBOSValue != emptyValue && + iLow < iSwingLowBOSValue; + if (isSwingLowBOSBreaked) + { + iSwingLowBOSValue = emptyValue; + } + swingLowsBOSBuffer[bar_index] = iSwingLowBOSValue; + + // + // Swing High BOS ... + double lastSwingHighBOSValue = + isFirstBar + ? emptyValue + : swingHighsBOSBuffer[lastBarIndex]; + double iSwingHighBOSValue = + isTrendBearish && + iLow < lastSwing + ? iHigh + : emptyValue; + bool isSwingHighBOSBreaked = + iSwingHighBOSValue != emptyValue && + iHigh > iSwingHighBOSValue; + if (isSwingHighBOSBreaked) + { + iSwingHighBOSValue = emptyValue; + } + swingHighsBOSBuffer[bar_index] = iSwingHighBOSValue; + + // + // Detecting CHOCHs ... + + // + // Swing Low CHOCH ... + double lastSwingLowCHOCHValue = + isFirstBar + ? emptyValue + : swingLowsCHOCHBuffer[lastBarIndex]; + double iSwingLowCHOCHValue = + isTrendBullish && + iLow < lastSwing + ? iLow + : emptyValue; + swingLowsCHOCHBuffer[bar_index] = iSwingLowCHOCHValue; + + // + // Swing High CHOCH ... + double lastSwingHighCHOCHValue = + isFirstBar + ? emptyValue + : swingHighsCHOCHBuffer[lastBarIndex]; + double iSwingHighCHOCHValue = + isTrendBearish && + iHigh > lastSwing + ? iHigh + : emptyValue; + swingHighsCHOCHBuffer[bar_index] = iSwingHighCHOCHValue; +} + +// +// Tools ... + +// +bool IsSwingLow( + const double &high[], + const double &low[], + int index, + int length // +) +{ + // + bool result = false; + + // + result = index - length > 0; + if (!result) + { + return result; + } + + // + for (int i = 1; i <= length; i++) + { + // + result = low[index] < low[index - 1] && + low[index] < low[index + i]; + if (!result) + { + break; + } + } + + // + return result; +} + +// +bool IsSwingHigh( + const double &high[], + const double &low[], + int index, + int length // +) +{ + // + bool result = false; + + // + result = index - length > 0; + if (!result) + { + return result; + } + + // + for (int i = 1; i <= length; i++) + { + // + result = high[index] > high[index - 1] && + high[index] > high[index + i]; + if (!result) + { + break; + } + } + + // + return result; +} + +// \ No newline at end of file diff --git a/BKPS/14040203/Documents/BKP/Indicators/x-saherelm.x121.xstr.helper.mq5 b/BKPS/14040203/Documents/BKP/Indicators/x-saherelm.x121.xstr.helper.mq5 new file mode 100644 index 0000000..bdfc79e --- /dev/null +++ b/BKPS/14040203/Documents/BKP/Indicators/x-saherelm.x121.xstr.helper.mq5 @@ -0,0 +1,1142 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Helper Class Library +// ---------------------------------------------- +// Name: XCX121XSTRHelper +// Description: provides all Indicator +// Helper requirements ... +// +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +////////////////////////////////////////////////////// +// +// Global Properties ... +#property library +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://www.saherelm.ir" +#property version "1.00" +#property strict + +// +// Imports ... +#include "../Classes/x-saherelm.x-helper.class.mq5" + +// +// Definitions ... + +// +// Definitions ... +enum ENUM_X121_XSTR_BUFFERS +{ + // + X121_XSTR_LINE = 0, + X121_XSTR_UP_LINE = 2, + X121_XSTR_DOWN_LINE = 3, + X121_XSTR_ATR_LINE = 4, + X121_XSTR_PRICE_LINE = 5, + X121_XSTR_STATE_LINE = 6, +}; + +// +// Input Models ... +struct X121XSTRInputs +{ + // + // Props ... + + int strLength; // Length + double strMultiplier; // Multiplier + ENUM_APPLIED_PRICE strAppliedTo; // Applied To + + // + bool showStr; // Show Upper Zone + bool showStrUpper; // Show Str Upper + bool showStrLower; // Show Str Lower + + // + // Constructor(s) ... + X121XSTRInputs() + { + // + Clean(); + } + + // + // Tools ... + + // + // Clean ... + void Clean() + { + // + strLength = 0; + strMultiplier = 0.0; + strAppliedTo = PRICE_MEDIAN; + + // + showStr = false; + showStrUpper = false; + showStrLower = false; + + // + ZeroMemory(this); + } + + // + // Default ... + void Default() + { + // + strLength = 14; + strMultiplier = 3.0; + strAppliedTo = PRICE_CLOSE; + + // + showStr = true; + showStrUpper = true; + showStrLower = true; + } + + // + // Validate ... + bool IsValid() + { + // + bool result = false; + + // + result = + // + strLength > 0 && + strMultiplier > 0 + // + ; + + // + return result; + } + + // + // Retrieve MAx Length ... + int Max() + { + // + int result = 0; + + // + result = MathMax(1, strLength); + + // + return result; + } +}; + +// +// Conditions ... +struct X121XSTRConditions +{ + // + // Common ... + string symbol; + ENUM_TIMEFRAMES period; + datetime time; + + // + // Buffers ... + double strBuffer[]; + double atrBuffer[]; + double strPriceBuffer[]; + double strUpBuffer[]; + double strDownBuffer[]; + double strStateBuffer[]; + + // + // Conditions ... + + // + bool isStrBullish; + bool isStrBearish; + + // + bool isStrSwitchedToBullish; + bool isStrSwitchedToBearish; + + // + // bool isCloseLower + + // + // Constructor ... + X121XSTRConditions() + { + Clean(); + } + + // + // Tools ... + + /** + * Cleaning Up ... + */ + void Clean() + { + // + // Commons ... + symbol = NULL; + period = NULL; + time = NULL; + + // + // Buffers ... + + // + Clean(strBuffer); + Clean(atrBuffer); + Clean(strPriceBuffer); + Clean(strUpBuffer); + Clean(strDownBuffer); + Clean(strStateBuffer); + + // + ArraySetAsSeries(strBuffer, true); + ArraySetAsSeries(atrBuffer, true); + ArraySetAsSeries(strPriceBuffer, true); + ArraySetAsSeries(strUpBuffer, true); + ArraySetAsSeries(strDownBuffer, true); + ArraySetAsSeries(strStateBuffer, true); + + // + // Conditions ... + + // + isStrBullish = false; + isStrBearish = false; + + // + isStrSwitchedToBullish = false; + isStrSwitchedToBearish = false; + + // + ZeroMemory(this); + } + + /** + * Generate Conditions Scores ... + * + * @param bullishScore: Double, Directional Scores Reference ... + * @param bearishScore: Double, Directional Scores Reference ... + */ + void GenerateScore( + double &bullishScore, + double &bearishScore // + ) + { + // + bullishScore = 0; + bearishScore = 0; + + // + double score = 1; + double minScore = 0.5; + double highScore = 1.5; + + // + if (isStrBullish) + { + bullishScore += minScore; + } + if (isStrSwitchedToBullish) + { + bullishScore += score; + } + + // + if (isStrBearish) + { + bearishScore += minScore; + } + if (isStrSwitchedToBearish) + { + bearishScore += score; + } + } + + /** + * Generate Summary String for Represent Conditions State ... + * + * @param onlyCommons: Boolean, Just Generate Only Commons Conditions ... + * @param onlyConditions: Boolean, Just Generate Only Conditions ... + * @param includeScores: Boolean, Attach Scores Representations on Result ... + * @param ignoreFalseConditions: Boolean, Ignore False Conditions on Result ... + * @param separator: String, Separate Lines ... + * + * @return ( string ) + */ + string GenerateSummary( + bool onlyCommons = false, + bool onlyConditions = false, + bool includeScores = true, + bool ignoreFalseConditions = true, + string separator = "\n" // + ) + { + // + string result = NULL; + + // + double bullishScore = 0; + double bearishScore = 0; + GenerateScore( + bullishScore, + bearishScore // + ); + + // + string scoresStr = + // + "Scores: " + separator + + "---------------" + separator + + "Bullish: " + ToString(bullishScore) + separator + + "Bearish: " + ToString(bearishScore) + separator + + "" + // + ; + + // + string commonStr = GenerateSpecifiedCommonSummary( + this, + separator, + includeScores // + ); + + // + string conditionsStr = + // + "-----------------------" + separator + + "XSTR: " + separator + + "-----------------------" + separator + + ToString("isStrBullish", isStrBullish, ignoreFalseConditions, separator) + + ToString("isStrBearish", isStrBearish, ignoreFalseConditions, separator) + + ToString("isStrSwitchedToBullish", isStrSwitchedToBullish, ignoreFalseConditions, separator) + + ToString("isStrSwitchedToBearish", isStrSwitchedToBearish, ignoreFalseConditions, separator) + + // + "" + // + ; + + // + result = + // + "[" + GetTag() + "]" + separator + + (onlyConditions + ? "" + : commonStr) + + (!includeScores + ? "" + : scoresStr) + + " " + separator + + (onlyCommons + ? "" + : conditionsStr) + + "" + // + ; + + // + return result; + } + + /** + * Retrieve nique Tag Identifier ... + * + * @return ( string ) + */ + string GetTag() + { + return GetTypeName(this); + } + + // +}; + +// +// Class ... +class XCX121XSTRHelper : public XCBaseHelper +{ + // + // Public ... + public: + // + // Props ... + + // + // Constructors ... + XCX121XSTRHelper() + : XCBaseHelper(_Symbol, _Period) + { + } + + // + // Deconstructor ... + ~XCX121XSTRHelper() + { + // + mInputs.Clean(); + + // + Clean(strBuffer); + Clean(atrBuffer); + Clean(strPriceBuffer); + Clean(strUpBuffer); + Clean(strDownBuffer); + Clean(strStateBuffer); + } + + // + // Tools ... + bool Init( + string symbol, // Trading Symbol + ENUM_TIMEFRAMES period, // Trading Period + X121XSTRInputs &inputs // Inputs + ) + { + // + bool result = false; + + // + mSymbol = symbol; + mPeriod = period; + + // + result = inputs.IsValid(); + if (!result) + { + return result; + } + + // + ArraySetAsSeries(strBuffer, true); + ArraySetAsSeries(atrBuffer, true); + ArraySetAsSeries(strPriceBuffer, true); + ArraySetAsSeries(strUpBuffer, true); + ArraySetAsSeries(strDownBuffer, true); + ArraySetAsSeries(strStateBuffer, true); + + // + mInputs = inputs; + + // + mHandler = iCustom( + mSymbol, + mPeriod, + "x-saherelm.x121.xstr", + // + // Inputs ... + // + // Market ... + "", + mInputs.strLength, + mInputs.strMultiplier, + mInputs.strAppliedTo, + // + // Presentation ... + "", + mInputs.showStr, + mInputs.showStrUpper, + mInputs.showStrLower + // + ); + result = mHandler != INVALID_HANDLE; + if (!result) + { + return result; + } + + // + return result; + } + + // + // Inputs ... + + // + X121XSTRInputs GetInputs() + { + return mInputs; + } + + // + bool SetInputs( + X121XSTRInputs &inputs // Configs + ) + { + // + return Init( + mSymbol, + mPeriod, + inputs + // + ); + } + + // + // Readers ... + + // + // ATR ... + + // + double GetATR( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(atrBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return atrBuffer[barIndex]; + } + + // + int CopyATR( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + atrBuffer, + buffer, + forceClean + // + ); + } + + // + double GetSTR( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(strBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return strBuffer[barIndex]; + } + + // + int CopySTR( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + strBuffer, + buffer, + forceClean + // + ); + } + + // + double GetSTRState( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(strStateBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return strStateBuffer[barIndex]; + } + + // + int CopySTRState( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + strStateBuffer, + buffer, + forceClean + // + ); + } + + // + double GetSTRPrice( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(strPriceBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return strPriceBuffer[barIndex]; + } + + // + int CopySTRPrice( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + strPriceBuffer, + buffer, + forceClean + // + ); + } + + // + double GetSTRUp( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(strUpBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return strUpBuffer[barIndex]; + } + + // + int CopySTRUp( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + strUpBuffer, + buffer, + forceClean + // + ); + } + + // + double GetSTRDown( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(strDownBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return strDownBuffer[barIndex]; + } + + // + int CopySTRDown( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + strDownBuffer, + buffer, + forceClean + // + ); + } + + // + double GetLastSTR( + ENUM_X_DIRECTION dir, + int barIndex = 0 // + ) + { + // + double result = 0; + + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + if (!HasDirection(dir)) + { + return result; + } + + // + int index = barIndex; + bool isBullish = IsBullish(dir); + + // + bool canContinue = true; + while (canContinue) + { + // + double iStr = GetSTR(index); + double iState = GetSTRState(index); + + // + canContinue = + isBullish + ? iState < 0 + : iState > 0; + if (!canContinue) + { + // + result = iStr; + break; + } + + // + index++; + } + + // + return result; + } + + // + void Free() override + { + Cleanup(10); + } + + // + bool GetConditions( + X121XSTRConditions &conditions, // + int barIndex = 0, // + int loopback = 5 // + ) + { + // + bool result = true; + + // + if (loopback < 5) + { + loopback = 5; + } + + // + conditions.Clean(); + + // + conditions.symbol = mSymbol; + conditions.period = mPeriod; + conditions.time = TimeCurrent(); + + // + int zIndex = barIndex; + int cIndex = zIndex + 1; + int pIndex = cIndex + 1; + int ppIndex = pIndex + 1; + + // + XOHCL zBar; + result = zBar.Init( + mSymbol, + mPeriod, + zIndex // + ); + if (!result) + { + return result; + } + + // + XOHCL cBar; + result = cBar.Init( + mSymbol, + mPeriod, + cIndex // + ); + if (!result) + { + return result; + } + + // + XOHCL pBar; + result = pBar.Init( + mSymbol, + mPeriod, + pIndex // + ); + if (!result) + { + return result; + } + + // + // Buffers ... + + // + CopyATR( + zIndex, + loopback, + conditions.atrBuffer // + ); + + // + CopySTR( + zIndex, + loopback, + conditions.strBuffer // + ); + + // + CopySTRState( + zIndex, + loopback, + conditions.strStateBuffer // + ); + + // + CopySTRPrice( + zIndex, + loopback, + conditions.strPriceBuffer // + ); + + // + CopySTRUp( + zIndex, + loopback, + conditions.strUpBuffer // + ); + + // + CopySTRDown( + zIndex, + loopback, + conditions.strDownBuffer // + ); + + // + // Conditions ... + + // + int cIDX = 1; + int pIDX = cIDX + 1; + + // + bool isStrBullish = strStateBuffer[cIDX] > 0; + bool isStrBullishPrev = strStateBuffer[pIDX] > 0; + + // + bool isStrBearish = strStateBuffer[cIDX] < 0; + bool isStrBearishPrev = strStateBuffer[pIDX] < 0; + + // + bool isStrSwitchedToBullish = isStrBullish && + !isStrBullishPrev; + bool isStrSwitchedToBearish = isStrBearish && + !isStrBearishPrev; + + // + conditions.isStrBullish = isStrBullish; + conditions.isStrBearish = isStrBearish; + conditions.isStrSwitchedToBullish = isStrSwitchedToBullish; + conditions.isStrSwitchedToBearish = isStrSwitchedToBearish; + + // + Cleanup(); + + // + zBar.Clean(); + cBar.Clean(); + pBar.Clean(); + + // + return result; + } + + // + // Protected ... + protected: + // + // Private ... + private: + // + // Props ... + X121XSTRInputs mInputs; // Inputs ... + + // + // Buffers ... + double strBuffer[]; + double atrBuffer[]; + double strPriceBuffer[]; + double strUpBuffer[]; + double strDownBuffer[]; + double strStateBuffer[]; + + // + void Calculate( + int barIndex = 0, + int maxRequiredBars = 100 // + ) + { + // + // Buffers ... + if (barIndex < 0) + { + barIndex = 0; + } + + // + // STR ... + CopyBuffer( + mHandler, + X121_XSTR_LINE, + barIndex, + maxRequiredBars, + strBuffer + // + ); + + // + // State ... + CopyBuffer( + mHandler, + X121_XSTR_STATE_LINE, + barIndex, + maxRequiredBars, + strStateBuffer + // + ); + + // + // Price ... + CopyBuffer( + mHandler, + X121_XSTR_PRICE_LINE, + barIndex, + maxRequiredBars, + strPriceBuffer + // + ); + + // + // Up ... + CopyBuffer( + mHandler, + X121_XSTR_UP_LINE, + barIndex, + maxRequiredBars, + strUpBuffer + // + ); + + // + // STR ... + CopyBuffer( + mHandler, + X121_XSTR_DOWN_LINE, + barIndex, + maxRequiredBars, + strDownBuffer + // + ); + + // + // ATR ... + + // + CopyBuffer( + mHandler, + X121_XSTR_ATR_LINE, + barIndex, + maxRequiredBars, + atrBuffer + // + ); + } + + // + void Cleanup( + int maxAllowed = 100 // + ) + { + // + CleanupArray( + strBuffer, + maxAllowed // + ); + + // + CleanupArray( + atrBuffer, + maxAllowed // + ); + + // + CleanupArray( + strPriceBuffer, + maxAllowed // + ); + + // + CleanupArray( + strUpBuffer, + maxAllowed // + ); + + // + CleanupArray( + strDownBuffer, + maxAllowed // + ); + + // + CleanupArray( + strStateBuffer, + maxAllowed // + ); + + // + } + + // +}; + +// +// Tools ... \ No newline at end of file diff --git a/BKPS/14040203/Documents/BKP/Indicators/x-saherelm.x121.xstr.mq5 b/BKPS/14040203/Documents/BKP/Indicators/x-saherelm.x121.xstr.mq5 new file mode 100644 index 0000000..bd69c20 --- /dev/null +++ b/BKPS/14040203/Documents/BKP/Indicators/x-saherelm.x121.xstr.mq5 @@ -0,0 +1,637 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Indicator +// ------------------------------------------------- +// Name: X121 XSTR +// Description: XSTR ... +// +// +// 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 XSTR Indicator" +#property strict + +// +// Definitions ... + +// +#define ShortName "X121 XSTR" + +// +// Includes Common Library ... +#include "../Libraries/x-saherelm.common.lib.mq5" + +// +// Inputs ... + +// +// Market ... +input group "Market"; +input int strLength = 14; // Length +input double strMultiplier = 3; // Multiplier +input ENUM_APPLIED_PRICE strAppliedTo = PRICE_MEDIAN; // Applied To + +// +input group "Presentation"; + +// +input bool showStr = true; // Show Str +input bool showStrUpper = true; // Show Str Upper +input bool showStrLower = true; // Show Str Lower + +// +// Buffers ... + +// +#define hideColorIDX 0 +#define bullishColorIDX 1 +#define bearishColorIDX 2 +#define neuturalColorIDX 3 + +// +#property indicator_chart_window + +// +#property indicator_buffers 7 +#property indicator_plots 3 + +// +// STR ... +#define strBufferIndex 0 +double strBuffer[]; + +#define strColorBufferIndex 1 +double strColorBuffer[]; + +// +#define strPlotBufferIndex 0 +#property indicator_label1 "X121 STR" +#property indicator_type1 DRAW_COLOR_LINE +#property indicator_color1 CLR_NONE, clrLime, clrRed, clrGray +#property indicator_style1 STYLE_SOLID +#property indicator_width1 2 + +// +// Up ... +#define strUpBufferIndex 2 +double strUpBuffer[]; + +// +#define strUpPlotBufferIndex 1 +#property indicator_label2 "X121 STR U" +#property indicator_type2 DRAW_LINE +#property indicator_color2 C'255,106,0' +#property indicator_style2 STYLE_SOLID +#property indicator_width2 1 + +// +// Down ... +#define strDownBufferIndex 3 +double strDownBuffer[]; + +// +#define strDownPlotBufferIndex 2 +#property indicator_label3 "X121 STR D" +#property indicator_type3 DRAW_LINE +#property indicator_color3 C'255,106,0' +#property indicator_style3 STYLE_SOLID +#property indicator_width3 1 + +// +// Data Buffers ... + +// +int mLastBufferIndex = 3; + +// +// STR ... + +// +// Atr ... +#define atrBufferIndex mLastBufferIndex + 1 +double atrBuffer[]; + +// +// Price ... +#define strPriceBufferIndex mLastBufferIndex + 2 +double strPriceBuffer[]; + +// +// Trend ... +#define strStateBufferIndex mLastBufferIndex + 3 +double strStateBuffer[]; + +// +// Variables, Properties and etc ... + +// +// this counts Available Bars ... +int limit; + +// +int maxLength; + +// +// ATR Handler ... +int atrHandler = INVALID_HANDLE; + +// +bool isStrTrendChanged; +bool isStrStartBearishTrend; +bool isStrStartBullishTrend; + +// +int changeOfTrend; +int startBearishTrend; +int startBullishTrend; + +// +// Event Handlers ... + +/** + * Initialize Indicator ... + * + * @return ( int ) + */ +int OnInit() +{ + // + // Validate Inputs ... + if (!ValidateInputs()) + { + return INIT_PARAMETERS_INCORRECT; + } + + // + // Initialize Indicator Handlers ... + + // + // ATR ... + atrHandler = iATR( + _Symbol, + _Period, + strLength // + ); + bool isInited = atrHandler != INVALID_HANDLE; + if (!isInited) + { + return INIT_FAILED; + } + + // + // because in some cases we may have more than one input for + // calculation and we must prevent any calculation + // untill we pass the biggest input length, here we get max Input length + // and then wait until pass it ... + maxLength = ExtractMaxLengthOfInputs(); + + // + // Define Index Buffers ... + DefineBuffers(); + + // + // Set Indicator ShortName ... + SetIndicatorName(); + + // + // Init Succeed ... + return INIT_SUCCEEDED; +} + +/** + * De Initialize Indicator ... + * + * @param reason: Integer, De Initialization Reason ... + */ +void OnDeinit(const int reason) +{ + // + // REASON_PROGRAM 0 The EA has stopped working calling the ExpertRemove() function + // REASON_REMOVE 1 Program removed from a chart + // REASON_RECOMPILE 2 Program recompiled + // REASON_CHARTCHANGE 3 A symbol or a chart period is changed + // REASON_CHARTCLOSE 4 Chart closed + // REASON_PARAMETERS 5 Inputs changed by a user + // REASON_ACCOUNT 6 Another account has been activated or reconnection to the trade server has occurred due to changes in the account settings + // REASON_TEMPLATE 7 Another chart template applied + // REASON_INITFAILED 8 The OnInit() handler returned a non-zero value + // REASON_CLOSE 9 Terminal closed + + // + IndicatorRelease(atrHandler); +} + +/** + * Calculate Bars ... + * + * @param rates_total: Integer, Total Bars on Chart ... + * @param prev_calculated: Integer, Total Calculated Bars on Charts ... + * @param time: DateTime Array, History of Open Time ... + * @param open: Double Array, History of Open Prices ... + * @param high: Double Array, History of High Prices ... + * @param low: Double Array, History of Low Prices ... + * @param close: Double Array, History of Close Prices ... + * @param tick_volume: Long, History of Tick Volumes on Bar ... + * @param volume: Long, History of Trade Volumes ... + * @param spread: Double, History of Spread Price ... + * + * @return ( int ) + */ +int OnCalculate( + const int rates_total, + const int prev_calculated, + const datetime &time[], + const double &open[], + const double &high[], + const double &low[], + const double &close[], + const long &tick_volume[], + const long &volume[], + const int &spread[] // +) +{ + // + // Prepare Buffers ... + + // + // Validate Calculated Bars ... + + // + // ATR ... + int atrCalculatedBars = BarsCalculated(atrHandler); + + // + bool isPassedRequiredCalculatedBars = + // + // ATR ... + atrCalculatedBars >= 0 + // + ; + if (!isPassedRequiredCalculatedBars) + { + return prev_calculated; + } + + // + // + // checking for the limit start of calculation of an indicator ... + limit = + (prev_calculated > rates_total || prev_calculated <= 0) + ? maxLength + : prev_calculated - 1; + + // + // Buffers Copy ... + + // + // ATR ... + int copiedAtrs = CopyBuffer(atrHandler, 0, 0, rates_total, atrBuffer); + + // + // Validate Copied Items ... + bool isPassedRequiredCopiedItems = + // + // ATR ... + copiedAtrs >= 0 + // + ; + if (!isPassedRequiredCopiedItems) + { + return prev_calculated; + } + + // + // Main Loop ... + for (int i = limit; i < rates_total && !IsStopped(); i++) + { + // + CalculateBuffers( + i, + prev_calculated, + rates_total, + // + open, + high, + close, + low, + tick_volume // + ); + } + + // + return rates_total; +} + +// +// Functions ... + +/** + * Validate Input Args for Initialization ... + * + * @return ( bool ) + */ +bool ValidateInputs() +{ + // + bool result = + // + // STR ... + strLength > 0 && + strMultiplier > 0 + // + ; + + // + return result; +} + +/** + * Extract Max Length of Inputs ... + * + * @return ( int ) + */ +int ExtractMaxLengthOfInputs() +{ + // + int result = 0; + + // + result = MathMax(1, strLength); + + // + return result; +} + +/** + * Define Required Buffers ... + */ +void DefineBuffers() +{ + // + // STR ... + SetIndexBuffer(strBufferIndex, strBuffer, INDICATOR_DATA); + SetIndexBuffer(strColorBufferIndex, strColorBuffer, INDICATOR_COLOR_INDEX); + + // + ENUM_DRAW_TYPE strUpDrawType = showStrUpper ? DRAW_LINE : DRAW_NONE; + SetIndexBuffer(strUpBufferIndex, strUpBuffer, INDICATOR_DATA); + PlotIndexSetDouble(strUpPlotBufferIndex, PLOT_EMPTY_VALUE, EMPTY_VALUE); + PlotIndexSetInteger(strUpPlotBufferIndex, PLOT_SHOW_DATA, showStrUpper); + PlotIndexSetInteger(strUpPlotBufferIndex, PLOT_DRAW_TYPE, strUpDrawType); + + // + ENUM_DRAW_TYPE strDownDrawType = showStrLower ? DRAW_LINE : DRAW_NONE; + SetIndexBuffer(strDownBufferIndex, strDownBuffer, INDICATOR_DATA); + PlotIndexSetDouble(strDownPlotBufferIndex, PLOT_EMPTY_VALUE, EMPTY_VALUE); + PlotIndexSetInteger(strDownPlotBufferIndex, PLOT_SHOW_DATA, showStrLower); + PlotIndexSetInteger(strDownPlotBufferIndex, PLOT_DRAW_TYPE, strDownDrawType); + + // + // Data Buffers ... + + // + // STR ... + + // + SetIndexBuffer(strPriceBufferIndex, strPriceBuffer, INDICATOR_CALCULATIONS); + SetIndexBuffer(strStateBufferIndex, strStateBuffer, INDICATOR_CALCULATIONS); +} + +/** + * Set Indicator Short Name and also we can define Buffers Labels ... + */ +void SetIndicatorName() +{ + IndicatorSetString(INDICATOR_SHORTNAME, ShortName); +} + +/** + * Calculate Custom Buffers ... + * + * @param bar_index: Integer, Represent Current Bar ... + * @param prevCalculated: Integer, Represent Previous Calculated Bars ... + * @param ratesTotal: Integer, Represents All Available Bars ... + * @param open: Double Array, History of Open Prices ... + * @param high: Double Array, History of High Prices ... + * @param close: Double Array, History of Close Prices ... + * @param low: Double Array, History of Low Prices ... + * @param tickVolume: Long, History of Tick Volumes on Bar ... + */ +void CalculateBuffers( + int bar_index, // Selected Bar Index + const int prevCalculated, + const int ratesTotal, + const double &open[], + const double &high[], + const double &close[], + const double &low[], + const long &tickVolume[] // +) +{ + // + CalculateStr( + bar_index, + prevCalculated, + ratesTotal, + open, + high, + close, + low // + ); +} + +// +// Custom ... + +/** + * Fill All Bufers to Zero Vlue for Specified Bar Index ... + * + * @param barIndex: Integer ... + */ +void FillBuffersZero(int barIndex) +{ + // + // STR ... + strBuffer[barIndex] = 0; + strUpBuffer[barIndex] = 0; + strDownBuffer[barIndex] = 0; + strPriceBuffer[barIndex] = 0; + strColorBuffer[barIndex] = hideColorIDX; + strStateBuffer[barIndex] = hideColorIDX; +} + +/** + * Calculate STR ... + * + * @param bar_index: Integer, Represent Current Bar ... + * @param prevCalculated: Integer, Represent Previous Calculated Bars ... + * @param ratesTotal: Integer, Represents All Available Bars ... + * @param open: Double Array, History of Open Prices ... + * @param high: Double Array, History of High Prices ... + * @param close: Double Array, History of Close Prices ... + * @param low: Double Array, History of Low Prices ... + */ +void CalculateStr( + int bar_index, // Selected Bar Index + const int prevCalculated, + const int ratesTotal, + const double &open[], + const double &high[], + const double &close[], + const double &low[] // +) +{ + // + // Calculated Price ... + ENUM_X_PRICE mPTYpe = ToXPrice(strAppliedTo); + double price = GetAppliedPrice( + mPTYpe, + open, + high, + low, + close, + bar_index // + ); + strPriceBuffer[bar_index] = price; + + // + double atr = atrBuffer[bar_index]; + + // + // Up ... + strUpBuffer[bar_index] = price + (strMultiplier * atr); + + // + // Down ... + strDownBuffer[bar_index] = price - (strMultiplier * atr); + + // + if (close[bar_index] > strUpBuffer[bar_index - 1]) + { + // + strStateBuffer[bar_index] = 1; + if (strStateBuffer[bar_index - 1] == -1) + { + changeOfTrend = 1; + } + } + else if (close[bar_index] < strDownBuffer[bar_index - 1]) + { + // + strStateBuffer[bar_index] = -1; + if (strStateBuffer[bar_index - 1] == 1) + { + changeOfTrend = 1; + } + } + else if (strStateBuffer[bar_index - 1] == 1) + { + // + strStateBuffer[bar_index] = 1; + changeOfTrend = 0; + } + else if (strStateBuffer[bar_index - 1] == -1) + { + // + strStateBuffer[bar_index] = -1; + changeOfTrend = 0; + } + + // + // Down Trend Starting ... + if (strStateBuffer[bar_index] < 0 && strStateBuffer[bar_index - 1] > 0) + { + startBearishTrend = 1; + } + else + { + startBearishTrend = 0; + } + + // + // Up Trend Starting ... + if (strStateBuffer[bar_index] > 0 && strStateBuffer[bar_index - 1] < 0) + { + startBullishTrend = 1; + } + else + { + startBullishTrend = 0; + } + + // + if (strStateBuffer[bar_index] > 0 && strDownBuffer[bar_index] < strDownBuffer[bar_index - 1]) + { + strDownBuffer[bar_index] = strDownBuffer[bar_index - 1]; + } + + // + if (strStateBuffer[bar_index] < 0 && strUpBuffer[bar_index] > strUpBuffer[bar_index - 1]) + { + strUpBuffer[bar_index] = strUpBuffer[bar_index - 1]; + } + + // + if (startBearishTrend == 1) + { + strUpBuffer[bar_index] = strPriceBuffer[bar_index] + (strMultiplier * atr); + } + + // + if (startBullishTrend == 1) + { + strDownBuffer[bar_index] = strPriceBuffer[bar_index] - (strMultiplier * atr); + } + + // + // Draw the indicator ... + + // + double colorIDX = hideColorIDX; + strColorBuffer[bar_index] = colorIDX; + + // + if (strStateBuffer[bar_index] == 1) + { + // + strBuffer[bar_index] = strDownBuffer[bar_index]; + if (changeOfTrend == 1) + { + strBuffer[bar_index - 1] = strBuffer[bar_index - 2]; + changeOfTrend = 0; + } + + // + colorIDX = bullishColorIDX; + } + else if (strStateBuffer[bar_index] == -1) + { + // + strBuffer[bar_index] = strUpBuffer[bar_index]; + if (changeOfTrend == 1) + { + // + strBuffer[bar_index - 1] = strBuffer[bar_index - 2]; + changeOfTrend = 0; + } + + // + colorIDX = bearishColorIDX; + } + + // + if (showStr) + { + strColorBuffer[bar_index] = colorIDX; + } +} + +// \ No newline at end of file diff --git a/BKPS/14040203/Documents/BKP/Indicators/x-saherelm.x121.xstr.v2.mq5 b/BKPS/14040203/Documents/BKP/Indicators/x-saherelm.x121.xstr.v2.mq5 new file mode 100644 index 0000000..915dd23 --- /dev/null +++ b/BKPS/14040203/Documents/BKP/Indicators/x-saherelm.x121.xstr.v2.mq5 @@ -0,0 +1,793 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Indicator +// ------------------------------------------------- +// Name: X121 XSTR +// Description: XSTR ... +// +// +// 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 XSTR Indicator" +#property strict + +// +// Definitions ... + +// +#define ShortName "X121 XSTR" + +// +// Includes Common Library ... +#include "../Libraries/x-saherelm.common.lib.mq5" + +// +// Inputs ... + +// +// Market ... +input group "Market"; +input int strLength = 14; // Length +input double strMultiplier = 3; // Multiplier +input ENUM_MA_METHOD strBoundaryMode = MODE_SMA; // Boundary Mode +input ENUM_APPLIED_PRICE strAppliedTo = PRICE_MEDIAN; // Applied To + +// +input group "Presentation"; +input bool showStr = true; // Show Str +input bool showStrMid = true; // Show Str Mid +input bool showStrUpper = true; // Show Str Upper +input bool showStrLower = true; // Show Str Lower +input bool showStrLowMa = true; // Show Low Smoothed Buffer +input bool showStrHighMa = true; // Show High Smoothed Buffer + +// +// Buffers ... + +// +#define hideColorIDX 0 +#define bullishColorIDX 1 +#define bearishColorIDX 2 +#define neuturalColorIDX 3 + +// +#define emptyValue 0.0 + +// +#property indicator_chart_window + +// +#property indicator_buffers 11 +#property indicator_plots 6 + +// +// STR ... +#define strBufferIndex 0 +double strBuffer[]; + +#define strColorBufferIndex 1 +double strColorBuffer[]; + +// +#define strPlotBufferIndex 0 +#property indicator_label1 "X121 STR" +#property indicator_type1 DRAW_COLOR_LINE +#property indicator_color1 CLR_NONE, clrLime, clrRed, clrGray +#property indicator_style1 STYLE_SOLID +#property indicator_width1 2 + +// +// Up ... +#define strUpBufferIndex 2 +double strUpBuffer[]; + +// +#define strUpPlotBufferIndex 1 +#property indicator_label2 "X121 STR U" +#property indicator_type2 DRAW_LINE +#property indicator_color2 clrBlueViolet +#property indicator_style2 STYLE_SOLID +#property indicator_width2 1 + +// +// Down ... +#define strDownBufferIndex 3 +double strDownBuffer[]; + +// +#define strDownPlotBufferIndex 2 +#property indicator_label3 "X121 STR D" +#property indicator_type3 DRAW_LINE +#property indicator_color3 clrBlueViolet +#property indicator_style3 STYLE_SOLID +#property indicator_width3 1 + +// +// High MA ... +#define strHighMaBufferIndex 4 +double strHighMaBuffer[]; + +// +#define strHighMaPlotBufferIndex 3 +#property indicator_label4 "X121 STR HSM" +#property indicator_type4 DRAW_LINE +#property indicator_color4 clrAqua +#property indicator_style4 STYLE_SOLID +#property indicator_width4 1 + +// +// Low Ma ... +#define strLowMaBufferIndex 5 +double strLowMaBuffer[]; + +// +#define strLowMaPlotBufferIndex 4 +#property indicator_label5 "X121 STR LSM" +#property indicator_type5 DRAW_LINE +#property indicator_color5 clrMagenta +#property indicator_style5 STYLE_SOLID +#property indicator_width5 1 + +// +// STR Mmid ... +#define strMidBufferIndex 6 +double strMidBuffer[]; + +#define strMidColorBufferIndex 7 +double strMidColorBuffer[]; + +// +#define strMidPlotBufferIndex 5 +#property indicator_label6 "X121 STR Mid" +#property indicator_type6 DRAW_COLOR_LINE +#property indicator_color6 CLR_NONE, clrLime, clrRed, clrGray +#property indicator_style6 STYLE_SOLID +#property indicator_width6 1 + +// +// Data Buffers ... + +// +int mLastBufferIndex = 7; + +// +// STR ... + +// +// Atr ... +#define atrBufferIndex mLastBufferIndex + 1 +double atrBuffer[]; + +// +// Price ... +#define strPriceBufferIndex mLastBufferIndex + 2 +double strPriceBuffer[]; + +// +// Trend ... +#define strStateBufferIndex mLastBufferIndex + 3 +double strStateBuffer[]; + +// +// Variables, Properties and etc ... + +// +// this counts Available Bars ... +int limit; + +// +int maxLength; + +// +// ATR Handler ... +int atrHandler = INVALID_HANDLE; + +// +// MA Handler ... +int lowMaHandler = INVALID_HANDLE; +int highMaHandler = INVALID_HANDLE; + +// +bool isStrTrendChanged; +bool isStrStartBearishTrend; +bool isStrStartBullishTrend; + +// +int changeOfTrend; +int startBearishTrend; +int startBullishTrend; + +// +// Event Handlers ... + +/** + * Initialize Indicator ... + * + * @return ( int ) + */ +int OnInit() +{ + // + // Validate Inputs ... + if (!ValidateInputs()) + { + return INIT_PARAMETERS_INCORRECT; + } + + // + // Initialize Indicator Handlers ... + + // + // ATR ... + atrHandler = iATR( + _Symbol, + _Period, + strLength // + ); + bool isInited = atrHandler != INVALID_HANDLE; + if (!isInited) + { + return INIT_FAILED; + } + + // + // Low Ma ... + lowMaHandler = iMA( + _Symbol, + _Period, + strLength, + 0, + strBoundaryMode, + PRICE_LOW // + ); + isInited = lowMaHandler != INVALID_HANDLE; + if (!isInited) + { + return INIT_FAILED; + } + + // + // High Ma ... + highMaHandler = iMA( + _Symbol, + _Period, + strLength, + 0, + strBoundaryMode, + PRICE_HIGH // + ); + isInited = highMaHandler != INVALID_HANDLE; + if (!isInited) + { + return INIT_FAILED; + } + + // + // because in some cases we may have more than one input for + // calculation and we must prevent any calculation + // untill we pass the biggest input length, here we get max Input length + // and then wait until pass it ... + maxLength = ExtractMaxLengthOfInputs(); + + // + // Define Index Buffers ... + DefineBuffers(); + + // + // Set Indicator ShortName ... + SetIndicatorName(); + + // + // Init Succeed ... + return INIT_SUCCEEDED; +} + +/** + * De Initialize Indicator ... + * + * @param reason: Integer, De Initialization Reason ... + */ +void OnDeinit(const int reason) +{ + // + // REASON_PROGRAM 0 The EA has stopped working calling the ExpertRemove() function + // REASON_REMOVE 1 Program removed from a chart + // REASON_RECOMPILE 2 Program recompiled + // REASON_CHARTCHANGE 3 A symbol or a chart period is changed + // REASON_CHARTCLOSE 4 Chart closed + // REASON_PARAMETERS 5 Inputs changed by a user + // REASON_ACCOUNT 6 Another account has been activated or reconnection to the trade server has occurred due to changes in the account settings + // REASON_TEMPLATE 7 Another chart template applied + // REASON_INITFAILED 8 The OnInit() handler returned a non-zero value + // REASON_CLOSE 9 Terminal closed + + // + IndicatorRelease(atrHandler); + IndicatorRelease(lowMaHandler); + IndicatorRelease(highMaHandler); +} + +/** + * Calculate Bars ... + * + * @param rates_total: Integer, Total Bars on Chart ... + * @param prev_calculated: Integer, Total Calculated Bars on Charts ... + * @param time: DateTime Array, History of Open Time ... + * @param open: Double Array, History of Open Prices ... + * @param high: Double Array, History of High Prices ... + * @param low: Double Array, History of Low Prices ... + * @param close: Double Array, History of Close Prices ... + * @param tick_volume: Long, History of Tick Volumes on Bar ... + * @param volume: Long, History of Trade Volumes ... + * @param spread: Double, History of Spread Price ... + * + * @return ( int ) + */ +int OnCalculate( + const int rates_total, + const int prev_calculated, + const datetime &time[], + const double &open[], + const double &high[], + const double &low[], + const double &close[], + const long &tick_volume[], + const long &volume[], + const int &spread[] // +) +{ + // + // Prepare Buffers ... + + // + // Validate Calculated Bars ... + + // + // ATR ... + int atrCalculatedBars = BarsCalculated(atrHandler); + + // + // Low Ma ... + int lowMaCalculatedBars = BarsCalculated(lowMaHandler); + + // + // High Ma ... + int highMaCalculatedBars = BarsCalculated(highMaHandler); + + // + bool isPassedRequiredCalculatedBars = + // + // ATR ... + atrCalculatedBars >= 0 && + // + // Low Ma ... + lowMaCalculatedBars >= 0 && + // + // High Ma ... + highMaCalculatedBars >= 0 + // + ; + if (!isPassedRequiredCalculatedBars) + { + return prev_calculated; + } + + // + // + // checking for the limit start of calculation of an indicator ... + limit = + (prev_calculated > rates_total || prev_calculated <= 0) + ? maxLength + : prev_calculated - 1; + + // + // Buffers Copy ... + + // + // ATR ... + int copiedAtrs = CopyBuffer(atrHandler, 0, 0, rates_total, atrBuffer); + + // + // Low Ma ... + int copiedLowMas = CopyBuffer(lowMaHandler, 0, 0, rates_total, strLowMaBuffer); + + // + // High Ma ... + int copiedHighMas = CopyBuffer(highMaHandler, 0, 0, rates_total, strHighMaBuffer); + + // + // Validate Copied Items ... + bool isPassedRequiredCopiedItems = + // + // ATR ... + copiedAtrs >= 0 && + // + // Low Ma ... + copiedLowMas >= 0 && + // + // Hig Ma ... + copiedHighMas >= 0 + // + ; + if (!isPassedRequiredCopiedItems) + { + return prev_calculated; + } + + // + // Main Loop ... + for (int i = limit; i < rates_total && !IsStopped(); i++) + { + // + CalculateBuffers( + i, + prev_calculated, + rates_total, + // + open, + high, + close, + low, + tick_volume // + ); + } + + // + return rates_total; +} + +// +// Functions ... + +/** + * Validate Input Args for Initialization ... + * + * @return ( bool ) + */ +bool ValidateInputs() +{ + // + bool result = + // + // STR ... + strLength > 0 && + strMultiplier > 0 + // + ; + + // + return result; +} + +/** + * Extract Max Length of Inputs ... + * + * @return ( int ) + */ +int ExtractMaxLengthOfInputs() +{ + // + int result = 0; + + // + result = MathMax(1, strLength); + + // + return result; +} + +/** + * Define Required Buffers ... + */ +void DefineBuffers() +{ + // + // STR ... + SetIndexBuffer(strBufferIndex, strBuffer, INDICATOR_DATA); + SetIndexBuffer(strColorBufferIndex, strColorBuffer, INDICATOR_COLOR_INDEX); + + // + ENUM_DRAW_TYPE strUpDrawType = showStrUpper ? DRAW_LINE : DRAW_NONE; + SetIndexBuffer(strUpBufferIndex, strUpBuffer, INDICATOR_DATA); + PlotIndexSetDouble(strUpPlotBufferIndex, PLOT_EMPTY_VALUE, emptyValue); + PlotIndexSetInteger(strUpPlotBufferIndex, PLOT_SHOW_DATA, showStrUpper); + PlotIndexSetInteger(strUpPlotBufferIndex, PLOT_DRAW_TYPE, strUpDrawType); + + // + ENUM_DRAW_TYPE strDownDrawType = showStrLower ? DRAW_LINE : DRAW_NONE; + SetIndexBuffer(strDownBufferIndex, strDownBuffer, INDICATOR_DATA); + PlotIndexSetDouble(strDownPlotBufferIndex, PLOT_EMPTY_VALUE, emptyValue); + PlotIndexSetInteger(strDownPlotBufferIndex, PLOT_SHOW_DATA, showStrLower); + PlotIndexSetInteger(strDownPlotBufferIndex, PLOT_DRAW_TYPE, strDownDrawType); + + // + ENUM_DRAW_TYPE strLowMaDrawType = showStrLowMa ? DRAW_LINE : DRAW_NONE; + SetIndexBuffer(strLowMaBufferIndex, strLowMaBuffer, INDICATOR_DATA); + PlotIndexSetDouble(strLowMaPlotBufferIndex, PLOT_EMPTY_VALUE, emptyValue); + PlotIndexSetInteger(strLowMaPlotBufferIndex, PLOT_SHOW_DATA, showStrLowMa); + PlotIndexSetInteger(strLowMaPlotBufferIndex, PLOT_DRAW_TYPE, strLowMaDrawType); + + // + ENUM_DRAW_TYPE strHighMaDrawType = showStrHighMa ? DRAW_LINE : DRAW_NONE; + SetIndexBuffer(strHighMaBufferIndex, strHighMaBuffer, INDICATOR_DATA); + PlotIndexSetDouble(strHighMaPlotBufferIndex, PLOT_EMPTY_VALUE, emptyValue); + PlotIndexSetInteger(strHighMaPlotBufferIndex, PLOT_SHOW_DATA, showStrHighMa); + PlotIndexSetInteger(strHighMaPlotBufferIndex, PLOT_DRAW_TYPE, strHighMaDrawType); + + // + ENUM_DRAW_TYPE strMidDrawType = showStrMid ? DRAW_COLOR_LINE : DRAW_NONE; + SetIndexBuffer(strMidBufferIndex, strMidBuffer, INDICATOR_DATA); + SetIndexBuffer(strMidColorBufferIndex, strMidColorBuffer, INDICATOR_COLOR_INDEX); + PlotIndexSetDouble(strMidPlotBufferIndex, PLOT_EMPTY_VALUE, emptyValue); + PlotIndexSetInteger(strMidPlotBufferIndex, PLOT_SHOW_DATA, showStrMid); + PlotIndexSetInteger(strMidPlotBufferIndex, PLOT_DRAW_TYPE, strMidDrawType); + + // + // Data Buffers ... + + // + SetIndexBuffer(strPriceBufferIndex, strPriceBuffer, INDICATOR_CALCULATIONS); + SetIndexBuffer(strStateBufferIndex, strStateBuffer, INDICATOR_CALCULATIONS); +} + +/** + * Set Indicator Short Name and also we can define Buffers Labels ... + */ +void SetIndicatorName() +{ + IndicatorSetString(INDICATOR_SHORTNAME, ShortName); +} + +/** + * Calculate Custom Buffers ... + * + * @param bar_index: Integer, Represent Current Bar ... + * @param prevCalculated: Integer, Represent Previous Calculated Bars ... + * @param ratesTotal: Integer, Represents All Available Bars ... + * @param open: Double Array, History of Open Prices ... + * @param high: Double Array, History of High Prices ... + * @param close: Double Array, History of Close Prices ... + * @param low: Double Array, History of Low Prices ... + * @param tickVolume: Long, History of Tick Volumes on Bar ... + */ +void CalculateBuffers( + int bar_index, // Selected Bar Index + const int prevCalculated, + const int ratesTotal, + const double &open[], + const double &high[], + const double &close[], + const double &low[], + const long &tickVolume[] // +) +{ + // + CalculateStr( + bar_index, + prevCalculated, + ratesTotal, + open, + high, + close, + low // + ); +} + +// +// Custom ... + +/** + * Fill All Bufers to Zero Vlue for Specified Bar Index ... + * + * @param barIndex: Integer ... + */ +void FillBuffersZero(int barIndex) +{ + // + // STR ... + strBuffer[barIndex] = emptyValue; + strUpBuffer[barIndex] = emptyValue; + strMidBuffer[barIndex] = emptyValue; + strMidBuffer[barIndex] = emptyValue; + strDownBuffer[barIndex] = emptyValue; + strPriceBuffer[barIndex] = emptyValue; + strLowMaBuffer[barIndex] = emptyValue; + strHighMaBuffer[barIndex] = emptyValue; + + // + strColorBuffer[barIndex] = hideColorIDX; + strStateBuffer[barIndex] = hideColorIDX; +} + +/** + * Calculate STR ... + * + * @param bar_index: Integer, Represent Current Bar ... + * @param prevCalculated: Integer, Represent Previous Calculated Bars ... + * @param ratesTotal: Integer, Represents All Available Bars ... + * @param open: Double Array, History of Open Prices ... + * @param high: Double Array, History of High Prices ... + * @param close: Double Array, History of Close Prices ... + * @param low: Double Array, History of Low Prices ... + */ +void CalculateStr( + int bar_index, // Selected Bar Index + const int prevCalculated, + const int ratesTotal, + const double &open[], + const double &high[], + const double &close[], + const double &low[] // +) +{ + // + // Calculated Price ... + ENUM_X_PRICE mPType = ToXPrice(strAppliedTo); + double price = GetAppliedPrice( + mPType, + open, + high, + low, + close, + bar_index // + ); + strPriceBuffer[bar_index] = price; + + // + double atr = atrBuffer[bar_index]; + + // + // Up ... + strUpBuffer[bar_index] = price + (strMultiplier * atr); + + // + // Down ... + strDownBuffer[bar_index] = price - (strMultiplier * atr); + + // + if (close[bar_index] > strUpBuffer[bar_index - 1]) + { + // + strStateBuffer[bar_index] = 1; + if (strStateBuffer[bar_index - 1] == -1) + { + changeOfTrend = 1; + } + } + else if (close[bar_index] < strDownBuffer[bar_index - 1]) + { + // + strStateBuffer[bar_index] = -1; + if (strStateBuffer[bar_index - 1] == 1) + { + changeOfTrend = 1; + } + } + else if (strStateBuffer[bar_index - 1] == 1) + { + // + strStateBuffer[bar_index] = 1; + changeOfTrend = 0; + } + else if (strStateBuffer[bar_index - 1] == -1) + { + // + strStateBuffer[bar_index] = -1; + changeOfTrend = 0; + } + + // + // Down Trend Starting ... + if (strStateBuffer[bar_index] < 0 && strStateBuffer[bar_index - 1] > 0) + { + startBearishTrend = 1; + } + else + { + startBearishTrend = 0; + } + + // + // Up Trend Starting ... + if (strStateBuffer[bar_index] > 0 && strStateBuffer[bar_index - 1] < 0) + { + startBullishTrend = 1; + } + else + { + startBullishTrend = 0; + } + + // + if (strStateBuffer[bar_index] > 0 && strDownBuffer[bar_index] < strDownBuffer[bar_index - 1]) + { + strDownBuffer[bar_index] = strDownBuffer[bar_index - 1]; + } + + // + if (strStateBuffer[bar_index] < 0 && strUpBuffer[bar_index] > strUpBuffer[bar_index - 1]) + { + strUpBuffer[bar_index] = strUpBuffer[bar_index - 1]; + } + + // + if (startBearishTrend == 1) + { + strUpBuffer[bar_index] = strPriceBuffer[bar_index] + (strMultiplier * atr); + } + + // + if (startBullishTrend == 1) + { + strDownBuffer[bar_index] = strPriceBuffer[bar_index] - (strMultiplier * atr); + } + + // + // Draw the indicator ... + + // + double colorIDX = hideColorIDX; + strColorBuffer[bar_index] = colorIDX; + + // + if (strStateBuffer[bar_index] == 1) + { + // + strBuffer[bar_index] = strDownBuffer[bar_index]; + if (changeOfTrend == 1) + { + strBuffer[bar_index - 1] = strBuffer[bar_index - 2]; + changeOfTrend = 0; + } + + // + colorIDX = bullishColorIDX; + } + else if (strStateBuffer[bar_index] == -1) + { + // + strBuffer[bar_index] = strUpBuffer[bar_index]; + if (changeOfTrend == 1) + { + // + strBuffer[bar_index - 1] = strBuffer[bar_index - 2]; + changeOfTrend = 0; + } + + // + colorIDX = bearishColorIDX; + } + + // + if (showStr) + { + strColorBuffer[bar_index] = colorIDX; + } + + // + // Str Mid ... + + // + double iStrMid = strDownBuffer[bar_index] + ((strUpBuffer[bar_index] - strDownBuffer[bar_index]) / 2); + strMidBuffer[bar_index] = iStrMid; + + // + double iStrColor = close[bar_index] > strMidBuffer[bar_index] + ? bullishColorIDX + : close[bar_index] < strMidBuffer[bar_index] + ? bearishColorIDX + : neuturalColorIDX; + strMidColorBuffer[bar_index] = iStrColor; + + // +} + +// \ No newline at end of file diff --git a/BKPS/14040203/Documents/BKP/X121HelperTMPs/1.mq5 b/BKPS/14040203/Documents/BKP/X121HelperTMPs/1.mq5 new file mode 100644 index 0000000..b4b6876 --- /dev/null +++ b/BKPS/14040203/Documents/BKP/X121HelperTMPs/1.mq5 @@ -0,0 +1,27 @@ + + // + // XCC ... + + // + // XPV ... + + // + // XHK ... + + // + // XMAS ... + + // + // XATR ... + + // + // XSTR ... + + // + // XCHE ... + + // + // X3MA ... + + // + // XVWAP ... diff --git a/BKPS/14040203/Documents/BKP/X121HelperTMPs/2.mq5 b/BKPS/14040203/Documents/BKP/X121HelperTMPs/2.mq5 new file mode 100644 index 0000000..f9ee217 --- /dev/null +++ b/BKPS/14040203/Documents/BKP/X121HelperTMPs/2.mq5 @@ -0,0 +1,82 @@ + + // + // XCC ... + + // + // Buffers ... + + // + // Conditions ... + + // + // XPV ... + + // + // Buffers ... + + // + // Conditions ... + + // + // XHK ... + + // + // Buffers ... + + // + // Conditions ... + + // + // XMAS ... + + // + // Buffers ... + + // + // Conditions ... + + // + // XATR ... + + // + // Buffers ... + + // + // Conditions ... + + // + // XSTR ... + + // + // Buffers ... + + // + // Conditions ... + + // + // XCHE ... + + // + // Buffers ... + + // + // Conditions ... + + // + // X3MA ... + + // + // Buffers ... + + // + // Conditions ... + + // + // XVWAP ... + + // + // Buffers ... + + // + // Conditions ... + diff --git a/BKPS/14040203/Documents/BKP/X121HelperTMPs/3.mq5 b/BKPS/14040203/Documents/BKP/X121HelperTMPs/3.mq5 new file mode 100644 index 0000000..235ec40 --- /dev/null +++ b/BKPS/14040203/Documents/BKP/X121HelperTMPs/3.mq5 @@ -0,0 +1,359 @@ + + // + // XCC ... + + // + // Buffers ... + + // + // Conditions ... + + // + // XPV ... + + // + // Buffers ... + + // + double sarBuffer[]; + double cHHBuffer[]; + double cLLBuffer[]; + double sHHBuffer[]; + double sLLBuffer[]; + double mHHBuffer[]; + double mLLBuffer[]; + double lHHBuffer[]; + double lLLBuffer[]; + double hHHBuffer[]; + double hLLBuffer[]; + double peaksBuffer[]; + double valesBuffer[]; + double supportsBuffer[]; + double peaksGoldenBuffer[]; + double valesGoldenBuffer[]; + double resistancesBuffer[]; + double fractalsUpperBuffer[]; + double fractalsLowerBuffer[]; + + // + // Conditions ... + + // + bool isSarBullish; + bool isSarBearish; + + // + bool isSarSwitchedToBullish; + bool isSarSwitchedToBearish; + + // + bool isNewPeak; + bool isNewPeakOverLast; + bool isNewPeakUnderLast; + + // + bool isNewVale; + bool isNewValeOverLast; + bool isNewValeUnderLast; + + // + // XHK ... + + // + // Buffers ... + + // + double xhkSMLowBuffer[]; + double xhkRawLowBuffer[]; + double xhkSMOpenBuffer[]; + double xhkSMHighBuffer[]; + double xhkRawOpenBuffer[]; + double xhkRawHighBuffer[]; + double xhkSMCloseBuffer[]; + double xhkRawCloseBuffer[]; + + // + // Conditions ... + + // + bool isSMHKBullish; + bool isRawHKBullish; + bool isSMHKSwitchedToBullish; + bool isRawHKSwitchedToBullish; + + // + bool isSMHKBearish; + bool isRawHKBearish; + bool isSMHKSwitchedToBearish; + bool isRawHKSwitchedToBearish; + + // + bool isClosedOverSMHK; + bool isClosedUnderSMHK; + bool isClosedOverRawHK; + bool isClosedUnderRawHK; + + // + bool isRawHKClosedOverSMHK; + bool isRawHKClosedUnderSMHK; + + // + // XMAS ... + + // + // Buffers ... + + // + double midBuffer[]; + double upperBuffer[]; + double lowerBuffer[]; + + // + // Conditions ... + + // + // XATR ... + + // + // Buffers ... + + // + double rsiBuffer[]; + double atrBuffer[]; + double atrUpperBuffer[]; + double atrLowerBuffer[]; + double atrUpperSMBuffer[]; + double atrLowerSMBuffer[]; + double rsiChangeBuffer[]; + double rsiChangeSMBuffer[]; + double priceChangeBuffer[]; + double priceChangeSMBuffer[]; + + // + // Conditions ... + + // + bool isRsiInRange; + bool isRsiOverSold; + bool isRsiOverBought; + bool isRsiCrossedOverOverSold; + bool isRsiCrossedUnderOverSold; + bool isRsiCrossedOverOverBought; + bool isRsiCrossedUnderOverBought; + + // + bool isRsiSMOverPriceChange; + bool isRsiSMUnderPriceChange; + + // + bool isRsiSMCrossedOverPriceChange; + bool isRsiSMCrossedUnderPriceChange; + + // + bool isPriceChangeSMOverRsi; + bool isPriceChangeSMUnderRsi; + + // + bool isPriceChangeSMCrossedOverRsi; + bool isPriceChangeSMCrossedUnderRsi; + + // + bool isRsiOverRsiSM; + bool isRsiUnderRsiSM; + + // + bool isRsiCrossedOverRsiSM; + bool isRsiCrossedUnderRsiSM; + + // + bool isPriceChangeOverPriceChangeSM; + bool isPriceChangeUnderPriceChangeSM; + + // + bool isPriceChangeCrossedOverPriceChangeSM; + bool isPriceChangeCrossedUnderPriceChangeSM; + + // + // XSTR ... + + // + // Buffers ... + + // + double strBuffer[]; + double strUpBuffer[]; + double strDownBuffer[]; + double strPriceBuffer[]; + double strStateBuffer[]; + + // + // Conditions ... + + // + bool isStrBullish; + bool isStrBearish; + + // + bool isStrSwitchedToBullish; + bool isStrSwitchedToBearish; + + // + // XCHE ... + + // + // Buffers ... + + // + double le1Buffer[]; + double se1Buffer[]; + double le2Buffer[]; + double se2Buffer[]; + double le1StartBuffer[]; + double se1StartBuffer[]; + double le2StartBuffer[]; + double se2StartBuffer[]; + + // + // Conditions ... + + // + bool isChe1Bullish; + bool isChe1Bearish; + + // + bool isChe1SwitchedToBullish; + bool isChe1SwitchedToBearish; + + // + bool isChe2Bullish; + bool isChe2Bearish; + + // + bool isChe2SwitchedToBullish; + bool isChe2SwitchedToBearish; + + // + bool isCheBullish; + bool isCheBearish; + + // + bool isCheSwitchedToBullish; + bool isCheSwitchedToBearish; + + // + // X3MA ... + + // + // Buffers ... + + // + double x3maMidBuffer[]; + double x3maFastBuffer[]; + double x3maSlowBuffer[]; + double x3maMidStateBuffer[]; + double x3maFastStateBuffer[]; + double x3maSlowStateBuffer[]; + + // + // Conditions ... + + // + bool isX3MaFastBullish; + bool isX3MaFastBearish; + bool isX3MaFastNeutural; + + // + bool isX3MaMidBullish; + bool isX3MaMidBearish; + bool isX3MaMidNeutural; + + // + bool isX3MaSlowBullish; + bool isX3MaSlowBearish; + bool isX3MaSlowNeutural; + + // + bool isX3MaFastOverMid; + bool isX3MaMidOverSlow; + + // + bool isX3MaFastUnderMid; + bool isX3MaMidUnderSlow; + + // + bool isX3MaBullishState; + bool isX3MaBearishState; + bool isX3MaNeuturalState; + + // + bool isX3MaBullishOrdered; + bool isX3MaBearishOrdered; + + // + bool isX3MaSwitchedToBullishOrdered; + bool isX3MaSwitchedToBearishOrdered; + + // + bool isX3MaSwitchedToBullishState; + bool isX3MaSwitchedToBearishState; + bool isX3MaSwitchedToNeuturalState; + + // + // XVWAP ... + + // + // Buffers ... + + // + double vwapMidBuffer[]; + double vwapFastBuffer[]; + double vwapSlowBuffer[]; + double vwapPriceBuffer[]; + double vwapVolumeBuffer[]; + double vwapMidStateBuffer[]; + double vwapFastStateBuffer[]; + double vwapSlowStateBuffer[]; + + // + // Conditions ... + + // + bool isVWapFastBullish; + bool isVWapFastBearish; + bool isVWapFastNeutural; + + // + bool isVWapMidBullish; + bool isVWapMidBearish; + bool isVWapMidNeutural; + + // + bool isVWapSlowBullish; + bool isVWapSlowBearish; + bool isVWapSlowNeutural; + + // + bool isVWapFastOverMid; + bool isVWapMidOverSlow; + + // + bool isVWapFastUnderMid; + bool isVWapMidUnderSlow; + + // + bool isVWapBullishState; + bool isVWapBearishState; + bool isVWapNeuturalState; + + // + bool isVWapBullishOrdered; + bool isVWapBearishOrdered; + + // + bool isVWapSwitchedToBullishOrdered; + bool isVWapSwitchedToBearishOrdered; + + // + bool isVWapSwitchedToBullishState; + bool isVWapSwitchedToBearishState; + bool isVWapSwitchedToNeuturalState; diff --git a/BKPS/14040203/Documents/BKP/X121HelperTMPs/4.mq5 b/BKPS/14040203/Documents/BKP/X121HelperTMPs/4.mq5 new file mode 100644 index 0000000..47b8958 --- /dev/null +++ b/BKPS/14040203/Documents/BKP/X121HelperTMPs/4.mq5 @@ -0,0 +1,408 @@ + // + // XPV ... + + // + // Buffers ... + + // + // Clean ... + + // + Clean(sarBuffer); + Clean(cHHBuffer); + Clean(cLLBuffer); + Clean(sHHBuffer); + Clean(sLLBuffer); + Clean(mHHBuffer); + Clean(mLLBuffer); + Clean(lHHBuffer); + Clean(lLLBuffer); + Clean(hHHBuffer); + Clean(hLLBuffer); + Clean(peaksBuffer); + Clean(valesBuffer); + Clean(supportsBuffer); + Clean(peaksGoldenBuffer); + Clean(valesGoldenBuffer); + Clean(resistancesBuffer); + Clean(fractalsUpperBuffer); + Clean(fractalsLowerBuffer); + + // + // Set As Series ... + + // + ArraySetAsSeries(sarBuffer, true); + ArraySetAsSeries(cHHBuffer, true); + ArraySetAsSeries(cLLBuffer, true); + ArraySetAsSeries(sHHBuffer, true); + ArraySetAsSeries(sLLBuffer, true); + ArraySetAsSeries(mHHBuffer, true); + ArraySetAsSeries(mLLBuffer, true); + ArraySetAsSeries(lHHBuffer, true); + ArraySetAsSeries(lLLBuffer, true); + ArraySetAsSeries(hHHBuffer, true); + ArraySetAsSeries(hLLBuffer, true); + ArraySetAsSeries(peaksBuffer, true); + ArraySetAsSeries(valesBuffer, true); + ArraySetAsSeries(supportsBuffer, true); + ArraySetAsSeries(peaksGoldenBuffer, true); + ArraySetAsSeries(valesGoldenBuffer, true); + ArraySetAsSeries(resistancesBuffer, true); + ArraySetAsSeries(fractalsUpperBuffer, true); + ArraySetAsSeries(fractalsLowerBuffer, true); + + // + // Conditions ... + + // + isNewPeak = false; + isNewVale = false; + isSarBullish = false; + isSarBearish = false; + isNewPeakOverLast = false; + isNewValeOverLast = false; + isNewPeakUnderLast = false; + isNewValeUnderLast = false; + isSarSwitchedToBullish = false; + isSarSwitchedToBearish = false; + + // + // XHK ... + + // + // Buffers ... + + // + // Clean ... + + // + Clean(xhkSMLowBuffer); + Clean(xhkRawLowBuffer); + Clean(xhkSMOpenBuffer); + Clean(xhkSMHighBuffer); + Clean(xhkRawOpenBuffer); + Clean(xhkRawHighBuffer); + Clean(xhkSMCloseBuffer); + Clean(xhkRawCloseBuffer); + + // + // Set As Series ... + + // + ArraySetAsSeries(xhkSMLowBuffer, true); + ArraySetAsSeries(xhkRawLowBuffer, true); + ArraySetAsSeries(xhkSMOpenBuffer, true); + ArraySetAsSeries(xhkSMHighBuffer, true); + ArraySetAsSeries(xhkRawOpenBuffer, true); + ArraySetAsSeries(xhkRawHighBuffer, true); + ArraySetAsSeries(xhkSMCloseBuffer, true); + ArraySetAsSeries(xhkRawCloseBuffer, true); + + // + // Conditions ... + + // + isSMHKBullish = false; + isSMHKBearish = false; + isRawHKBullish = false; + isRawHKBearish = false; + isClosedOverSMHK = false; + isClosedUnderSMHK = false; + isClosedOverRawHK = false; + isClosedUnderRawHK = false; + isRawHKClosedOverSMHK = false; + isRawHKClosedUnderSMHK = false; + isSMHKSwitchedToBearish = false; + isSMHKSwitchedToBullish = false; + isRawHKSwitchedToBullish = false; + isRawHKSwitchedToBearish = false; + + // + // XMAS ... + + // + // Buffers ... + + // + // Clean ... + + // + Clean(midBuffer); + Clean(upperBuffer); + Clean(lowerBuffer); + + // + // Set As Series ... + + // + ArraySetAsSeries(midBuffer, true); + ArraySetAsSeries(upperBuffer, true); + ArraySetAsSeries(lowerBuffer, true); + + // + // Conditions ... + + // + // XATR ... + + // + // Buffers ... + + // + // Clean ... + + // + Clean(rsiBuffer); + Clean(atrBuffer); + Clean(atrUpperBuffer); + Clean(atrLowerBuffer); + Clean(rsiChangeBuffer); + Clean(atrUpperSMBuffer); + Clean(atrLowerSMBuffer); + Clean(rsiChangeSMBuffer); + Clean(priceChangeBuffer); + Clean(priceChangeSMBuffer); + + // + // Set As Series ... + + // + ArraySetAsSeries(rsiBuffer, true); + ArraySetAsSeries(atrBuffer, true); + ArraySetAsSeries(atrUpperBuffer, true); + ArraySetAsSeries(atrLowerBuffer, true); + ArraySetAsSeries(rsiChangeBuffer, true); + ArraySetAsSeries(atrUpperSMBuffer, true); + ArraySetAsSeries(atrLowerSMBuffer, true); + ArraySetAsSeries(rsiChangeSMBuffer, true); + ArraySetAsSeries(priceChangeBuffer, true); + ArraySetAsSeries(priceChangeSMBuffer, true); + + // + // Conditions ... + + // + isRsiInRange = false; + isRsiOverSold = false; + isRsiOverRsiSM = false; + isRsiUnderRsiSM = false; + isRsiOverBought = false; + isRsiCrossedOverRsiSM = false; + isRsiCrossedUnderRsiSM = false; + isPriceChangeSMOverRsi = false; + isRsiSMOverPriceChange = false; + isRsiSMUnderPriceChange = false; + isPriceChangeSMUnderRsi = false; + isRsiCrossedOverOverSold = false; + isRsiCrossedUnderOverSold = false; + isRsiCrossedOverOverBought = false; + isRsiCrossedUnderOverBought = false; + isRsiSMCrossedOverPriceChange = false; + isPriceChangeSMCrossedOverRsi = false; + isRsiSMCrossedUnderPriceChange = false; + isPriceChangeSMCrossedUnderRsi = false; + isPriceChangeOverPriceChangeSM = false; + isPriceChangeUnderPriceChangeSM = false; + isPriceChangeCrossedOverPriceChangeSM = false; + isPriceChangeCrossedUnderPriceChangeSM = false; + + // + // XSTR ... + + // + // Buffers ... + + // + // Clean ... + + // + Clean(strBuffer); + Clean(strUpBuffer); + Clean(strDownBuffer); + Clean(strPriceBuffer); + Clean(strStateBuffer); + + // + // Set As Series ... + + // + ArraySetAsSeries(strBuffer, true); + ArraySetAsSeries(strUpBuffer, true); + ArraySetAsSeries(strDownBuffer, true); + ArraySetAsSeries(strPriceBuffer, true); + ArraySetAsSeries(strStateBuffer, true); + + // + // Conditions ... + + // + isStrBullish = false; + isStrBearish = false; + isStrSwitchedToBullish = false; + isStrSwitchedToBearish = false; + + // + // XCHE ... + + // + // Buffers ... + + // + // Clean ... + + // + Clean(le1Buffer); + Clean(se1Buffer); + Clean(le2Buffer); + Clean(se2Buffer); + Clean(le1StartBuffer); + Clean(se1StartBuffer); + Clean(le2StartBuffer); + Clean(se2StartBuffer); + + // + // Set As Series ... + + // + ArraySetAsSeries(le1Buffer, true); + ArraySetAsSeries(se1Buffer, true); + ArraySetAsSeries(le2Buffer, true); + ArraySetAsSeries(se2Buffer, true); + ArraySetAsSeries(le1StartBuffer, true); + ArraySetAsSeries(se1StartBuffer, true); + ArraySetAsSeries(le2StartBuffer, true); + ArraySetAsSeries(se2StartBuffer, true); + + // + // Conditions ... + + // + isCheBullish = false; + isCheBearish = false; + isChe1Bullish = false; + isChe1Bearish = false; + isChe2Bullish = false; + isChe2Bearish = false; + isCheSwitchedToBullish = false; + isCheSwitchedToBearish = false; + isChe1SwitchedToBullish = false; + isChe1SwitchedToBearish = false; + isChe2SwitchedToBullish = false; + isChe2SwitchedToBearish = false; + + // + // X3MA ... + + // + // Buffers ... + + // + // Clean ... + + // + Clean(x3maMidBuffer); + Clean(x3maFastBuffer); + Clean(x3maSlowBuffer); + Clean(x3maMidStateBuffer); + Clean(x3maFastStateBuffer); + Clean(x3maSlowStateBuffer); + + // + // Set As Series ... + + // + ArraySetAsSeries(x3maMidBuffer, true); + ArraySetAsSeries(x3maFastBuffer, true); + ArraySetAsSeries(x3maSlowBuffer, true); + ArraySetAsSeries(x3maMidStateBuffer, true); + ArraySetAsSeries(x3maFastStateBuffer, true); + ArraySetAsSeries(x3maSlowStateBuffer, true); + + // + // Conditions ... + + // + isX3MaMidBullish = false; + isX3MaMidBearish = false; + isX3MaFastBullish = false; + isX3MaFastBearish = false; + isX3MaMidNeutural = false; + isX3MaSlowBullish = false; + isX3MaSlowBearish = false; + isX3MaFastOverMid = false; + isX3MaMidOverSlow = false; + isX3MaFastNeutural = false; + isX3MaSlowNeutural = false; + isX3MaFastUnderMid = false; + isX3MaMidUnderSlow = false; + isX3MaBullishState = false; + isX3MaBearishState = false; + isX3MaNeuturalState = false; + isX3MaBullishOrdered = false; + isX3MaBearishOrdered = false; + isX3MaSwitchedToBullishState = false; + isX3MaSwitchedToBearishState = false; + isX3MaSwitchedToNeuturalState = false; + isX3MaSwitchedToBullishOrdered = false; + isX3MaSwitchedToBearishOrdered = false; + + // + // XVWAP ... + + // + // Buffers ... + + // + // Clean ... + + // + Clean(vwapMidBuffer); + Clean(vwapFastBuffer); + Clean(vwapSlowBuffer); + Clean(vwapPriceBuffer); + Clean(vwapVolumeBuffer); + Clean(vwapMidStateBuffer); + Clean(vwapFastStateBuffer); + Clean(vwapSlowStateBuffer); + + // + // Set As Series ... + + // + ArraySetAsSeries(vwapMidBuffer, true); + ArraySetAsSeries(vwapFastBuffer, true); + ArraySetAsSeries(vwapSlowBuffer, true); + ArraySetAsSeries(vwapPriceBuffer, true); + ArraySetAsSeries(vwapVolumeBuffer, true); + ArraySetAsSeries(vwapMidStateBuffer, true); + ArraySetAsSeries(vwapFastStateBuffer, true); + ArraySetAsSeries(vwapSlowStateBuffer, true); + + // + // Conditions ... + + // + isVWapMidBullish = false; + isVWapMidBearish = false; + isVWapMidNeutural = false; + isVWapFastBullish = false; + isVWapFastBearish = false; + isVWapSlowBullish = false; + isVWapSlowBearish = false; + isVWapFastOverMid = false; + isVWapMidOverSlow = false; + isVWapFastNeutural = false; + isVWapSlowNeutural = false; + isVWapFastUnderMid = false; + isVWapMidUnderSlow = false; + isVWapBullishState = false; + isVWapBearishState = false; + isVWapNeuturalState = false; + isVWapBullishOrdered = false; + isVWapBearishOrdered = false; + isVWapSwitchedToBullishState = false; + isVWapSwitchedToBearishState = false; + isVWapSwitchedToNeuturalState = false; + isVWapSwitchedToBullishOrdered = false; + isVWapSwitchedToBearishOrdered = false; diff --git a/BKPS/14040203/Documents/BKP/X121HelperTMPs/5.mq5 b/BKPS/14040203/Documents/BKP/X121HelperTMPs/5.mq5 new file mode 100644 index 0000000..e8d2ee6 --- /dev/null +++ b/BKPS/14040203/Documents/BKP/X121HelperTMPs/5.mq5 @@ -0,0 +1,96 @@ + + // + // XDON ... + x121Inputs.xdonInputs.showOpen = showAll || false; + x121Inputs.xdonInputs.showClose = showAll || false; + x121Inputs.xdonInputs.showLow = showAll || false; + x121Inputs.xdonInputs.showHigh = showAll || false; + + // + // XICH ... + x121Inputs.xichInputs.showTenkanSen = showAll || false; + x121Inputs.xichInputs.showKijunSen = showAll || false; + x121Inputs.xichInputs.showChikouSpan = showAll || false; + x121Inputs.xichInputs.showSenkouSpanA = showAll || false; + x121Inputs.xichInputs.showSenkouSpanB = showAll || false; + x121Inputs.xichInputs.showKumo = showAll || false; + + // + // XCC ... + x121Inputs.xccInputs.showCandles = showAll || true; + + // + // XPV ... + + // + x121Inputs.xpvInputs.showSar = showAll || false; + x121Inputs.xpvInputs.showPeaks = showAll || true; + x121Inputs.xpvInputs.showVales = showAll || true; + x121Inputs.xpvInputs.showSupports = showAll || false; + x121Inputs.xpvInputs.showResistances = showAll || false; + x121Inputs.xpvInputs.showGoldenZones = showAll || true; + + // + // XHK ... + + // + x121Inputs.xhkInputs.drawRawXHKCandles = showAll || false; + x121Inputs.xhkInputs.drawSmoothedXHKCandles = showAll || false; + + // + // XMAS ... + + // + x121Inputs.xmasInputs.showUpper = showAll || false; + x121Inputs.xmasInputs.showMid = showAll || false; + x121Inputs.xmasInputs.showLower = showAll || false; + + // + // XATR ... + x121Inputs.xatrInputs.showATRUpper = showAll || false; + x121Inputs.xatrInputs.showATRLower = showAll || false; + + // + // XSTR ... + x121Inputs.xstrInputs.showStr = showAll || true; + x121Inputs.xstrInputs.showStrUpper = showAll || false; + x121Inputs.xstrInputs.showStrLower = showAll || false; + + // + // XCHE ... + x121Inputs.xcheInputs.showLE1 = showAll || false; + x121Inputs.xcheInputs.showLE2 = showAll || false; + x121Inputs.xcheInputs.showSE1 = showAll || false; + x121Inputs.xcheInputs.showSE2 = showAll || false; + + // + // XVWAP ... + x121Inputs.xvwapInputs.showVWapFast = showAll || false; + x121Inputs.xvwapInputs.showVWapMedium = showAll || false; + x121Inputs.xvwapInputs.showVWapSlow = showAll || false; + + // + // X3MA ... + x121Inputs.x3maInputs.showX3MaFast = showAll || true; + x121Inputs.x3maInputs.showX3MaMid = showAll || false; + x121Inputs.x3maInputs.showX3MaSlow = showAll || false; + + // + + // + // x121Inputs.xcheInputs.cheLength = 14; + // x121Inputs.xcheInputs.cheLoopback = 7; + // x121Inputs.xcheInputs.cheMultiplier1 = 1.5; + // x121Inputs.xcheInputs.cheMultiplier2 = 2; + + // + // x121Inputs.xstrInputs.strLength = 14; + // x121Inputs.xstrInputs.strMultiplier = 1.5; + + // + // x121Inputs.xccInputs.upColor = clrLime; + // x121Inputs.xccInputs.downColor = clrRed; + // x121Inputs.xccInputs.lineColor = CLR_NONE; + // x121Inputs.xccInputs.bearishColor = clrRed; + // x121Inputs.xccInputs.bullishColor = clrLime; + // x121Inputs.xccInputs.volumesColor = clrGreen; diff --git a/BKPS/14040203/Documents/BKP/autofibgage.pine b/BKPS/14040203/Documents/BKP/autofibgage.pine new file mode 100644 index 0000000..adbdf08 --- /dev/null +++ b/BKPS/14040203/Documents/BKP/autofibgage.pine @@ -0,0 +1,411 @@ +// This indicator is created under TechnoBlooms - Innovating Trading Indicators and Strategies. +// All rights reserved. Unauthorized copying or distribution is prohibited. +// © TechnoBlooms + +//@version=6 +indicator("AutoFibGauge (TechnoBlooms) ", overlay=true) + +//---------------------------------------------------------------------------- +// Initialize with a default value that's not NaN +//---------------------------------------------------------------------------- +var float highestHigh = 0.0 +var float lowestLow = 0.0 +var float level0 = na +var float level100 = na +var float level236 = na +var float level382 = na +var float level500 = na +var float level618 = na +var float level786 = na + +// Variables for labels +var label label0 = na +var label label100 = na +var label label236 = na +var label label382 = na +var label label500 = na +var label label618 = na +var label label786 = na + +var int positionState = 0 // 0 = neutral, 1 = buy, -1 = sell +Thermometer_position = input.string("Middle right", title="Position", options=["Middle left", "Middle right"], group='Thermometer Settings') + + + +//------------------------------------------------------------------------------- +//input how many candles to consider for drawing fibonacci +//------------------------------------------------------------------------------- +num_of_cand = input(25,"No of Candles to find fib") + +//------------------------------------------------------------------------------- +// Calculate the highest high and lowest low of the last n candles +//------------------------------------------------------------------------------- +highestHigh := ta.highest(high, num_of_cand) +lowestLow := ta.lowest(low, num_of_cand) + +hhBar = ta.highestbars(high, num_of_cand) +llBar = ta.lowestbars(low, num_of_cand) + +// Calculate actual bar indices (negative offsets need to be converted) +currentBar = bar_index +highBarIndex = currentBar + hhBar +lowBarIndex = currentBar + llBar + + +//------------------------------------------------------------------------------- +// Calculate Simple Moving Average (SMA) +//------------------------------------------------------------------------------- +SLength = input(20,"Short Length") +LLength = input(55,"Long Length") // You can adjust this to change the SMA period +Strend = ta.sma(close,SLength) +LTrend = ta.sma(close, LLength) + +//------------------------------------------------------------------------------------------- +// Determine if we're in an uptrend or downtrend based on the current close relative to SMA +//------------------------------------------------------------------------------------------- +isUptrend = Strend > LTrend +barColor = isUptrend ?#26a6c6 : #9c1f98 +barcolor(barColor, title="Trend-Based Bar Color") + + + +//---------------------------------------- +//Choose Visibility of MA lines +//---------------------------------------- +showSMAShort = input.bool(false,"Short SMA") +showSMALong = input.bool(false,"Long SMA") + +//--------------------------------------------------- +//Choose which all fib lines to display +//--------------------------------------------------- +showFib0 = input.bool(true, "Fib 0",group = "Show Fib Lines") +showFib236 = input.bool(true,"Fib 23.6",group = "Show Fib Lines") +showFib382 = input.bool(true,"Fib 38.2",group = "Show Fib Lines") +showFib500 = input.bool(true,"Fib 50",group = "Show Fib Lines") +showFib618 = input.bool(true,"Fib 61.8",group = "Show Fib Lines") +showFib786 = input.bool(true,"Fib 78.6",group = "Show Fib Lines") +showFib100 = input.bool(true,"Fib 100",group = "Show Fib Lines") + +//---------------------------------------------------------------- +// Choose background color of thermometer +//---------------------------------------------------------------- +color0 = color.from_gradient(0, 0, 7, color.aqua, color.purple) +color1 = color.from_gradient(1, 0, 7, color.aqua, color.purple) +color2 = color.from_gradient(2, 0, 7, color.aqua, color.purple) +color3 = color.from_gradient(3, 0, 7, color.aqua, color.purple) +color4 = color.from_gradient(4, 0, 7, color.aqua, color.purple) +color5 = color.from_gradient(5, 0, 7, color.aqua, color.purple) +color6 = color.from_gradient(6, 0, 7, color.aqua, color.purple) +color7 = color.from_gradient(7, 7, 14, color.purple, color.red) +color8 = color.from_gradient(8, 7, 14, color.purple, color.red) +color9 = color.from_gradient(9, 7, 14, color.purple, color.red) +color10 = color.from_gradient(10, 7, 14, color.purple, color.red) +color11 = color.from_gradient(11, 7, 14, color.purple, color.red) +color12 = color.from_gradient(12, 7, 14, color.purple, color.red) +color13 = color.from_gradient(13, 7, 14,color.purple, color.red) + + +//--------------------------------------------------------------------- +// Calculate Fibonacci levels based on trend +//--------------------------------------------------------------------- +if not na(highestHigh) and not na(lowestLow) and highestHigh != lowestLow + float diff = highestHigh - lowestLow + + if isUptrend + level0 := highestHigh + level100 := lowestLow + level236 := highestHigh - (diff * 0.236) + level382 := highestHigh - (diff * 0.382) + level500 := highestHigh - (diff * 0.500) + level618 := highestHigh - (diff * 0.618) + level786 := highestHigh - (diff * 0.786) + else + level0 := lowestLow + level100 := highestHigh + level236 := lowestLow + (diff * 0.236) + level382 := lowestLow + (diff * 0.382) + level500 := lowestLow + (diff * 0.500) + level618 := lowestLow + (diff * 0.618) + level786 := lowestLow + (diff * 0.786) + +//------------------------------------------------- +// Delete old labels +//------------------------------------------------- + label.delete(label0) + label.delete(label100) + label.delete(label236) + label.delete(label382) + label.delete(label500) + label.delete(label618) + label.delete(label786) + +//---------------------------------------------------- +// Draw new labels, considering trend +//---------------------------------------------------- + if showFib0 + label0 := label.new(bar_index+5, level0, text="0.0%", color=color0, textcolor=color.white, style=label.style_label_left) + if showFib100 + label100 := label.new(bar_index+5, level100, text="100.0%", color=color12, textcolor=color.white, style=label.style_label_left) + if showFib236 + label236 := label.new(bar_index+5, level236, text="23.6%", color=color2, textcolor=color.white, style=label.style_label_left) + if showFib382 + label382 := label.new(bar_index+5, level382, text="38.2%", color=color4, textcolor=color.white, style=label.style_label_left) + if showFib500 + label500 := label.new(bar_index+5, level500, text="50.0%", color=color6, textcolor=color.white, style=label.style_label_left) + if showFib618 + label618 := label.new(bar_index+5, level618, text="61.8%", color=color8, textcolor=color.white, style=label.style_label_left) + if showFib786 + label786 := label.new(bar_index+5, level786, text="78.6%", color=color10, textcolor=color.white, style=label.style_label_left) + +//--------------------------------------------------------------- +// Draw straight lines to 20 candles back +//--------------------------------------------------------------- + var line line0 = na + var line line100 = na + var line line236 = na + var line line382 = na + var line line500 = na + var line line618 = na + var line line786 = na + + line.delete(line0) + line.delete(line100) + line.delete(line236) + line.delete(line382) + line.delete(line500) + line.delete(line618) + line.delete(line786) + + if showFib0 + line0 := line.new(bar_index[num_of_cand], level0, bar_index+5, level0, color=color0, width=1) + if showFib100 + line100 := line.new(bar_index[num_of_cand], level100, bar_index+5, level100, color=color12, width=1) + if showFib236 + line236 := line.new(bar_index[num_of_cand], level236, bar_index+5, level236, color=color2, width=1) + if showFib382 + line382 := line.new(bar_index[num_of_cand], level382, bar_index+5, level382, color=color4, width=1) + if showFib500 + line500 := line.new(bar_index[num_of_cand], level500, bar_index+5, level500, color=color6,width = 1) + if showFib618 + line618 := line.new(bar_index[num_of_cand], level618, bar_index+5, level618, color=color8,width = 1) + if showFib786 + line786 := line.new(bar_index[num_of_cand], level786, bar_index+5, level786, color=color10,width = 1) + + // Draw dashed line for showing Fib range + var line fibline = na + + //------------------------------------------------------------------------- + //Highlight Golden Ration region + //------------------------------------------------------------------------- + var box box1 = na + var box box2 = na + var box box3 = na + var box box2_lower = na + var box box2_upper = na + var box box3_lower = na + var box box3_upper = na + // Draw gradient shading with darker areas above and below 61.8%, fading toward 38.2% and 78.6% + // Delete previous boxes + if not na(box1) + box.delete(box1) + if not na(box2_lower) + box.delete(box2_lower) + if not na(box2_upper) + box.delete(box2_upper) + if not na(box3_lower) + box.delete(box3_lower) + if not na(box3_upper) + box.delete(box3_upper) + + // Base layer: Full range (38.2% to 78.6%) - lightest shade + // box1 := box.new(left=bar_index[num_of_cand], top=level786, right=bar_index+5, bottom=level382, bgcolor=color.new(color.yellow, 100), border_width=0) + + // Middle layers: Split around 61.8%, fading outward + box2_lower := box.new(left=bar_index[num_of_cand], top=(level618 + level382)/2, right=bar_index+5, bottom=level382, bgcolor=color.new(color.yellow, 100), border_width=0) + box2_upper := box.new(left=bar_index[num_of_cand], top=level786, right=bar_index+5, bottom=(level786 + level618)/2, bgcolor=color.new(color.yellow, 100), border_width=0) + + // Core layers: Closest to 61.8%, darkest shade + box3_lower := box.new(left=bar_index[num_of_cand], top=level618, right=bar_index+5, bottom=(level618 + level382)/2, bgcolor=color.new(color.yellow, 85), border_width=0) + box3_upper := box.new(left=bar_index[num_of_cand], top=(level786 + level618)/2, right=bar_index+5, bottom=level618, bgcolor=color.new(color.yellow, 85), border_width=0) + if isUptrend + line.delete(fibline) + fibline := line.new(lowBarIndex, lowestLow, highBarIndex, highestHigh, color=color.gray, style=line.style_dashed) + else + line.delete(fibline) + fibline := line.new(highBarIndex, highestHigh, lowBarIndex, lowestLow, color=color.gray, style=line.style_dashed) + +//------------------------- +// Plot SMA +//------------------------- +plot(showSMAShort? Strend:na, title="SMA", color=color.blue, linewidth=1) +plot(showSMALong? LTrend:na, title="Strend", color=#f321b4, linewidth=1) + +//----------------------------------------------------------- +//create labels in Thermometer when trend = 1 (uptrend) +//----------------------------------------------------------- +var table_position = Thermometer_position == 'Top right' ? position.top_right : + Thermometer_position == 'Top left' ? position.top_left : + Thermometer_position == 'Top center' ? position.top_center : + Thermometer_position == 'Bottom right' ? position.bottom_right : + Thermometer_position == 'Bottom left' ? position.bottom_left : + Thermometer_position == 'Bottom center' ? position.bottom_center : + Thermometer_position == 'Middle right' ? position.middle_right : position.middle_right + + +tbl = table.new(position=table_position, columns = 100, rows=100) +closenum=math.round(close,0) + +if level0 < level100 + + table.cell(tbl,0,0,text = label100.get_text() , text_color = #f83f8c) + table.cell(tbl,0,11,text = label236.get_text() ,text_color = #f83f8c) + table.cell(tbl,0,8,text = label382.get_text() ,text_color = #f83f8c) + table.cell(tbl,0,5,text = label618.get_text() , text_color =#f83f8c) + table.cell(tbl,0,2,text = label786.get_text(),text_color = #f83f8c) + table.cell(tbl,0,13,text = label0.get_text(), text_color = #f83f8c) + + + table.cell(tbl,2,13,text = str.tostring(level0," #,###"), text_color = #f83f8c) + table.cell(tbl,2,11,text = str.tostring(level236, " #,###"),text_color = #f83f8c) + table.cell(tbl,2,8,text = str.tostring(level382, " #,###"),text_color = #f83f8c) + table.cell(tbl,2,5,text = str.tostring(level618, " #,###"), text_color =#f83f8c) + table.cell(tbl,2,2,text = str.tostring(level786, " #,###"),text_color = #f83f8c) + table.cell(tbl,2,0,text = str.tostring(level100," #,###"), text_color = #f83f8c) + + for i = 0 to 13 by 1 + table.cell(tbl, 1, i, "", bgcolor = i < 8 ? color.from_gradient(i, 0, 7, color.aqua, color.purple) : color.from_gradient(i, 7, 14, color.purple, color.red)) + + var reg = 0 + bkcolor = color.aqua + + if closenum > level0 and closenum < level236 + reg := 12 + if closenum > level236 and closenum < level382 + reg := 9 + if closenum > level382 and closenum < level618 + reg := 6 + if closenum > level618 and closenum < level786 + reg := 3 + if closenum > level786 and closenum < level100 + reg := 1 + if closenum == level0 + reg := 0 + if closenum == level236 + reg := 11 + if closenum == level382 + reg := 8 + if closenum == level618 + reg := 5 + if closenum == level786 + reg := 2 + + + if reg == 12 + bkcolor := color12 + if reg == 9 + bkcolor := color9 + if reg == 6 + bkcolor := color6 + if reg == 3 + bkcolor := color3 + if reg == 1 + bkcolor := color1 + if reg == 2 + bkcolor := color2 + + if reg == 4 + bkcolor := color4 + if reg == 5 + bkcolor := color5 + if reg == 7 + bkcolor := color7 + if reg == 8 + bkcolor := color8 + if reg == 10 + bkcolor := color10 + if reg == 11 + bkcolor := color11 + if reg == 13 + bkcolor := color13 + + + table.cell(tbl,1,reg,"🌕", text_size = size.small,bgcolor = bkcolor) +//----------------------------------------------------------- +//create labels in Thermometer +//----------------------------------------------------------- +else + table.cell(tbl,0,13,text = label100.get_text() , text_color = #f83f8c) + table.cell(tbl,0,2,text = label236.get_text() ,text_color = #f83f8c) + table.cell(tbl,0,5,text = label382.get_text() ,text_color = #f83f8c) + table.cell(tbl,0,8,text = label618.get_text() , text_color =#f83f8c) + table.cell(tbl,0,11,text = label786.get_text(),text_color = #f83f8c) + table.cell(tbl,0,0,text = label0.get_text(), text_color = #f83f8c) + + + table.cell(tbl,2,0,text = str.tostring(level0," #,###"), text_color = #f83f8c) + table.cell(tbl,2,2,text = str.tostring(level236, " #,###"),text_color = #f83f8c) + table.cell(tbl,2,5,text = str.tostring(level382, " #,###"),text_color = #f83f8c) + table.cell(tbl,2,8,text = str.tostring(level618, " #,###"), text_color =#f83f8c) + table.cell(tbl,2,11,text = str.tostring(level786, " #,###"),text_color = #f83f8c) + table.cell(tbl,2,13,text = str.tostring(level100," #,###"), text_color = #f83f8c) + + for i = 0 to 13 by 1 + table.cell(tbl, 1, i, "", bgcolor = i < 8 ? color.from_gradient(i, 0, 7, color.aqua, color.purple) : color.from_gradient(i, 7, 14, color.purple, color.red)) + + var reg = 0 + bkcolor = color.aqua + + if closenum > level100 and closenum < level786 + reg := 12 + if closenum > level786 and closenum < level618 + reg := 9 + if closenum > level618 and closenum < level382 + reg := 6 + if closenum > level382 and closenum < level236 + reg := 3 + if closenum > level236 and closenum < level0 + reg := 1 + if closenum == level0 + reg := 0 + if closenum == level236 + reg := 11 + if closenum == level382 + reg := 8 + if closenum == level618 + reg := 5 + if closenum == level786 + reg := 2 + + + if reg == 12 + bkcolor := color12 + if reg == 9 + bkcolor := color9 + if reg == 6 + bkcolor := color6 + if reg == 3 + bkcolor := color3 + if reg == 1 + bkcolor := color1 + if reg == 2 + bkcolor := color2 + + if reg == 4 + bkcolor := color4 + if reg == 5 + bkcolor := color5 + if reg == 7 + bkcolor := color7 + if reg == 8 + bkcolor := color8 + if reg == 10 + bkcolor := color10 + if reg == 11 + bkcolor := color11 + if reg == 13 + bkcolor := color13 + + + table.cell(tbl,1,reg,"🌕", text_size = size.small,bgcolor = bkcolor) + + diff --git a/BKPS/14040203/Documents/BKP/cumulative-delta.1.pine b/BKPS/14040203/Documents/BKP/cumulative-delta.1.pine new file mode 100644 index 0000000..5ced2ed --- /dev/null +++ b/BKPS/14040203/Documents/BKP/cumulative-delta.1.pine @@ -0,0 +1,75 @@ +// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ +// © LonesomeTheBlue + +//@version=4 +study("Cumulative Delta Volume", "CDV") +linestyle = input(defval = 'Candle', title = "Style", options = ['Candle', 'Line']) +hacandle = input(defval = true, title = "Heikin Ashi Candles?") +showma1 = input(defval = false, title = "SMA 1", inline = "ma1") +ma1len = input(defval = 50, title = "", minval = 1, inline = "ma1") +ma1col = input(defval = color.lime, title = "", inline = "ma1") +showma2 = input(defval = false, title = "SMA 2", inline = "ma2") +ma2len = input(defval = 200, title = "", minval = 1, inline = "ma2") +ma2col = input(defval = color.red, title = "", inline = "ma2") +showema1 = input(defval = false, title = "EMA 1", inline = "ema1") +ema1len = input(defval = 50, title = "", minval = 1, inline = "ema1") +ema1col = input(defval = color.lime, title = "", inline = "ema1") +showema2 = input(defval = false, title = "EMA 2", inline = "ema2") +ema2len = input(defval = 200, title = "", minval = 1, inline = "ema2") +ema2col = input(defval = color.red, title = "", inline = "ema2") +colorup = input(defval = color.lime, title = "Body", inline = "bcol") +colordown = input(defval = color.red, title = "", inline = "bcol") +bcolup = input(defval = #74e05e, title = "Border", inline = "bocol") +bcoldown = input(defval = #ffad7d, title = "", inline = "bocol") +wcolup = input(defval = #b5b5b8, title = "Wicks", inline = "wcol") +wcoldown = input(defval = #b5b5b8, title = "", inline = "wcol") + +tw = high - max(open, close) +bw = min(open, close) - low +body = abs(close - open) + +_rate(cond) => + ret = 0.5 * (tw + bw + (cond ? 2 * body : 0)) / (tw + bw + body) + ret := nz(ret) == 0 ? 0.5 : ret + ret + +deltaup = volume * _rate(open <= close) +deltadown = volume * _rate(open > close) +delta = close >= open ? deltaup : -deltadown +cumdelta = cum(delta) +float ctl = na +float o = na +float h = na +float l = na +float c = na +if linestyle == 'Candle' + o := cumdelta[1] + h := max(cumdelta, cumdelta[1]) + l := min(cumdelta, cumdelta[1]) + c := cumdelta + ctl +else + ctl := cumdelta + +plot(ctl, title = "CDV Line", color = color.blue, linewidth = 2) + +float haclose = na +float haopen = na +float hahigh = na +float halow = na +haclose := (o + h + l + c) / 4 +haopen := na(haopen[1]) ? (o + c) / 2 : (haopen[1] + haclose[1]) / 2 +hahigh := max(h, max(haopen, haclose)) +halow := min(l, min(haopen, haclose)) + +c_ = hacandle ? haclose : c +o_ = hacandle ? haopen : o +h_ = hacandle ? hahigh : h +l_ = hacandle ? halow : l + +plotcandle(o_, h_, l_, c_, title='CDV Candles', color = o_ <= c_ ? colorup : colordown, bordercolor = o_ <= c_ ? bcolup : bcoldown, wickcolor = o_ <= c_ ? bcolup : bcoldown) + +plot(showma1 and linestyle == "Candle" ? sma(c_, ma1len) : na, title = "SMA 1", color = ma1col) +plot(showma2 and linestyle == "Candle" ? sma(c_, ma2len) : na, title = "SMA 2", color = ma2col) +plot(showema1 and linestyle == "Candle" ? ema(c_, ema1len) : na, title = "EMA 1", color = ema1col) +plot(showema2 and linestyle == "Candle" ? ema(c_, ema2len) : na, title = "EMA 2", color = ema2col) diff --git a/BKPS/14040203/Documents/BKP/cumulative-delta.pine b/BKPS/14040203/Documents/BKP/cumulative-delta.pine new file mode 100644 index 0000000..cc9afc0 --- /dev/null +++ b/BKPS/14040203/Documents/BKP/cumulative-delta.pine @@ -0,0 +1,37 @@ +// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ +// © Ankit_1618 + +//@version=4 +study("Cumulative Volume Delta") + +upper_wick = close>open ? high-close : high-open +lower_wick = close>open ? open-low : close-low +spread = high-low +body_length = spread - (upper_wick + lower_wick) + +percent_upper_wick = upper_wick/spread +percent_lower_wick = lower_wick/spread +percent_body_length = body_length/spread + + +buying_volume = close>open ? (percent_body_length + (percent_upper_wick + percent_lower_wick)/2)*volume : ((percent_upper_wick + percent_lower_wick)/2) * volume +selling_volume = close cumulative_selling_volume ? color.green : cumulative_buying_volume < cumulative_selling_volume ? color.red : color.yellow + +pb = plot(cumulative_buying_volume, color=color.green , transp=70) +ps = plot(cumulative_selling_volume, color=color.red , transp=70) + +fill(pb, ps, color = fill_color) + +volume_strength_wave = cumulative_buying_volume > cumulative_selling_volume ? cumulative_buying_volume : cumulative_selling_volume +ema_volume_strength_wave = ema(volume_strength_wave , cumulation_length) +plot(ema_volume_strength_wave, color=color.gray, transp=80) + +cumulative_volume_delta = cumulative_buying_volume - cumulative_selling_volume +plot(cumulative_volume_delta, color= cumulative_volume_delta>0 ? color.green : color.red, style=plot.style_columns, transp=61) + diff --git a/BKPS/14040203/Documents/BKP/cuvdelta.mq5 b/BKPS/14040203/Documents/BKP/cuvdelta.mq5 new file mode 100644 index 0000000..92d26fb --- /dev/null +++ b/BKPS/14040203/Documents/BKP/cuvdelta.mq5 @@ -0,0 +1,135 @@ +//+------------------------------------------------------------------+ +//| CumulativeDelta.mq5 | +//| Copyright © 2023, YourName | +//| | +//+------------------------------------------------------------------+ +#property copyright "YourName" +#property link "https://www.yourwebsite.com" +#property version "1.00" + +// +#include "../Libraries/x-saherelm.common.lib.mq5" + +// +#property indicator_separate_window +#property indicator_buffers 3 +#property indicator_plots 3 + +// +//--- Plot settings for Line +#property indicator_label1 "Cumulative Delta" +#property indicator_type1 DRAW_LINE +#property indicator_color1 clrYellow + +// +//--- Plot settings for Histogram +#property indicator_label2 "Delta" +#property indicator_type2 DRAW_HISTOGRAM +#property indicator_color2 clrGray + +// +//--- Plot settings for Moving Average line +#property indicator_label3 "Signal" +#property indicator_type3 DRAW_LINE +#property indicator_color3 clrOrchid + +// +//--- Input parameters +input int MAPeriod = 14; // Period for the moving average + +// +//--- Indicator buffers +double MABuffer[]; +double DeltaBuffer[]; +double CumulativeDeltaBuffer[]; + +//+------------------------------------------------------------------+ +//| Custom indicator initialization function | +//+------------------------------------------------------------------+ +int OnInit() +{ + // + // Attach buffer to the indicator + SetIndexBuffer(2, MABuffer, INDICATOR_DATA); + SetIndexBuffer(1, DeltaBuffer, INDICATOR_DATA); + SetIndexBuffer(0, CumulativeDeltaBuffer, INDICATOR_DATA); + IndicatorSetString(INDICATOR_SHORTNAME, "Cumulative Delta"); + + // + return (INIT_SUCCEEDED); +} + +//+------------------------------------------------------------------+ +//| Custom indicator iteration function | +//+------------------------------------------------------------------+ +int OnCalculate(const int rates_total, + const int prev_calculated, + const datetime &time[], + const double &open[], + const double &high[], + const double &low[], + const double &close[], + const long &tick_volume[], + const long &volume[], + const int &spread[] // +) +{ + // + // Start from the first uncalculated bar + int start = MathMax(prev_calculated - 1, 0); + + // + // Loop through bars + for (int i = start; i < rates_total; i++) + { + // + // Calculate Delta based on bar-level data + double delta = 0.0; + if (close[i] > open[i]) + { + delta = (double)tick_volume[i]; // Buying pressure (bullish bar) + } + else if (close[i] < open[i]) + { + delta = -(double)tick_volume[i]; // Selling pressure (bearish bar) + } + + // + // Accumulate cumulative delta + if (i == 0) + { + // + DeltaBuffer[i] = delta; + CumulativeDeltaBuffer[i] = delta; // First bar starts with delta + } + else + { + // + DeltaBuffer[i] = DeltaBuffer[i - 1] + delta; + CumulativeDeltaBuffer[i] = CumulativeDeltaBuffer[i - 1] + delta; + } + + // + // Calculate Moving Average of Cumulative Delta + if (i >= MAPeriod - 1) + { + // + double sum = 0.0; + for (int j = 0; j < MAPeriod; j++) + { + sum += CumulativeDeltaBuffer[i - j]; + } + + // + MABuffer[i] = sum / MAPeriod; // Simple Moving Average + } + else + { + MABuffer[i] = EMPTY_VALUE; // Not enough data for MA + } + } + + // + return (rates_total); +} +//+------------------------------------------------------------------+ \ No newline at end of file diff --git a/BKPS/14040203/Documents/BKP/forex.sessions.ex5 b/BKPS/14040203/Documents/BKP/forex.sessions.ex5 new file mode 100644 index 0000000..622d1c7 Binary files /dev/null and b/BKPS/14040203/Documents/BKP/forex.sessions.ex5 differ diff --git a/BKPS/14040203/Documents/BKP/forex.sessions.mq5 b/BKPS/14040203/Documents/BKP/forex.sessions.mq5 new file mode 100644 index 0000000..ee310f6 --- /dev/null +++ b/BKPS/14040203/Documents/BKP/forex.sessions.mq5 @@ -0,0 +1,347 @@ +//+------------------------------------------------------------------+ +//| ForexSessionHighLowIndicator.mq5 | +//| Copyright 2023, MetaQuotes Software Corp. | +//| https://www.metaquotes.net/ | +//+------------------------------------------------------------------+ +#property copyright "Copyright 2023, MetaQuotes Software Corp." +#property link "https://www.metaquotes.net/" +#property version "1.00" +#property indicator_chart_window +#property indicator_buffers 8 +#property indicator_plots 4 + +// Session times (in broker time) +input string SydneyStart = "22:00"; // Sydney session start (GMT+10 when DST) +input string SydneyEnd = "07:00"; // Sydney session end +input string TokyoStart = "00:00"; // Tokyo session start (GMT+9) +input string TokyoEnd = "09:00"; // Tokyo session end +input string LondonStart = "08:00"; // London session start (GMT+0) +input string LondonEnd = "17:00"; // London session end +input string NewYorkStart = "13:00"; // New York session start (GMT-4/5) +input string NewYorkEnd = "22:00"; // New York session end + +input color SydneyColor = clrDodgerBlue; // Sydney session color +input color TokyoColor = clrMediumSeaGreen; // Tokyo session color +input color LondonColor = clrGold; // London session color +input color NewYorkColor = clrTomato; // New York session color +input int LineWidth = 1; // Line width +input bool ShowLabels = true; // Show session labels +input bool ShowHighLow = true; // Show high/low prices + +// Buffers for session high/low +double SydneyHighBuffer[]; +double SydneyLowBuffer[]; +double TokyoHighBuffer[]; +double TokyoLowBuffer[]; +double LondonHighBuffer[]; +double LondonLowBuffer[]; +double NewYorkHighBuffer[]; +double NewYorkLowBuffer[]; + +// Global variables +int SydneyStartHour, SydneyStartMin; +int SydneyEndHour, SydneyEndMin; +int TokyoStartHour, TokyoStartMin; +int TokyoEndHour, TokyoEndMin; +int LondonStartHour, LondonStartMin; +int LondonEndHour, LondonEndMin; +int NewYorkStartHour, NewYorkStartMin; +int NewYorkEndHour, NewYorkEndMin; + +//+------------------------------------------------------------------+ +//| Custom indicator initialization function | +//+------------------------------------------------------------------+ +int OnInit() +{ + // Parse session times + ParseTime(SydneyStart, SydneyStartHour, SydneyStartMin); + ParseTime(SydneyEnd, SydneyEndHour, SydneyEndMin); + ParseTime(TokyoStart, TokyoStartHour, TokyoStartMin); + ParseTime(TokyoEnd, TokyoEndHour, TokyoEndMin); + ParseTime(LondonStart, LondonStartHour, LondonStartMin); + ParseTime(LondonEnd, LondonEndHour, LondonEndMin); + ParseTime(NewYorkStart, NewYorkStartHour, NewYorkStartMin); + ParseTime(NewYorkEnd, NewYorkEndHour, NewYorkEndMin); + + // Set indicator properties + SetIndexBuffer(0, SydneyHighBuffer, INDICATOR_DATA); + SetIndexBuffer(1, SydneyLowBuffer, INDICATOR_DATA); + SetIndexBuffer(2, TokyoHighBuffer, INDICATOR_DATA); + SetIndexBuffer(3, TokyoLowBuffer, INDICATOR_DATA); + SetIndexBuffer(4, LondonHighBuffer, INDICATOR_DATA); + SetIndexBuffer(5, LondonLowBuffer, INDICATOR_DATA); + SetIndexBuffer(6, NewYorkHighBuffer, INDICATOR_DATA); + SetIndexBuffer(7, NewYorkLowBuffer, INDICATOR_DATA); + + // Set drawing styles + PlotIndexSetInteger(0, PLOT_DRAW_TYPE, DRAW_LINE); + PlotIndexSetInteger(0, PLOT_LINE_COLOR, SydneyColor); + PlotIndexSetInteger(0, PLOT_LINE_WIDTH, LineWidth); + PlotIndexSetString(0, PLOT_LABEL, "Sydney High"); + + PlotIndexSetInteger(1, PLOT_DRAW_TYPE, DRAW_LINE); + PlotIndexSetInteger(1, PLOT_LINE_COLOR, SydneyColor); + PlotIndexSetInteger(1, PLOT_LINE_STYLE, STYLE_DOT); + PlotIndexSetInteger(1, PLOT_LINE_WIDTH, LineWidth); + PlotIndexSetString(1, PLOT_LABEL, "Sydney Low"); + + PlotIndexSetInteger(2, PLOT_DRAW_TYPE, DRAW_LINE); + PlotIndexSetInteger(2, PLOT_LINE_COLOR, TokyoColor); + PlotIndexSetInteger(2, PLOT_LINE_WIDTH, LineWidth); + PlotIndexSetString(2, PLOT_LABEL, "Tokyo High"); + + PlotIndexSetInteger(3, PLOT_DRAW_TYPE, DRAW_LINE); + PlotIndexSetInteger(3, PLOT_LINE_COLOR, TokyoColor); + PlotIndexSetInteger(3, PLOT_LINE_STYLE, STYLE_DOT); + PlotIndexSetInteger(3, PLOT_LINE_WIDTH, LineWidth); + PlotIndexSetString(3, PLOT_LABEL, "Tokyo Low"); + + return(INIT_SUCCEEDED); +} + +//+------------------------------------------------------------------+ +//| Custom indicator iteration function | +//+------------------------------------------------------------------+ +int OnCalculate(const int rates_total, + const int prev_calculated, + const datetime &time[], + const double &open[], + const double &high[], + const double &low[], + const double &close[], + const long &tick_volume[], + const long &volume[], + const int &spread[]) +{ + // Check if we have enough data + if(rates_total < 2) return(0); + + // Set all buffers to EMPTY_VALUE initially + ArrayInitialize(SydneyHighBuffer, EMPTY_VALUE); + ArrayInitialize(SydneyLowBuffer, EMPTY_VALUE); + ArrayInitialize(TokyoHighBuffer, EMPTY_VALUE); + ArrayInitialize(TokyoLowBuffer, EMPTY_VALUE); + ArrayInitialize(LondonHighBuffer, EMPTY_VALUE); + ArrayInitialize(LondonLowBuffer, EMPTY_VALUE); + ArrayInitialize(NewYorkHighBuffer, EMPTY_VALUE); + ArrayInitialize(NewYorkLowBuffer, EMPTY_VALUE); + + // Calculate start position + int start = (prev_calculated == 0) ? 0 : prev_calculated - 1; + + // Main calculation loop + for(int i = start; i < rates_total; i++) + { + MqlDateTime dt; + TimeToStruct(time[i], dt); + + // Check if current time is within any session + bool inSydney = IsInSession(dt.hour, dt.min, SydneyStartHour, SydneyStartMin, SydneyEndHour, SydneyEndMin); + bool inTokyo = IsInSession(dt.hour, dt.min, TokyoStartHour, TokyoStartMin, TokyoEndHour, TokyoEndMin); + bool inLondon = IsInSession(dt.hour, dt.min, LondonStartHour, LondonStartMin, LondonEndHour, LondonEndMin); + bool inNewYork = IsInSession(dt.hour, dt.min, NewYorkStartHour, NewYorkStartMin, NewYorkEndHour, NewYorkEndMin); + + // Find session boundaries and calculate high/low + if(inSydney) + { + CalculateSessionHighLow(i, rates_total, time, high, low, SydneyHighBuffer, SydneyLowBuffer, SydneyStartHour, SydneyStartMin, SydneyEndHour, SydneyEndMin); + } + + if(inTokyo) + { + CalculateSessionHighLow(i, rates_total, time, high, low, TokyoHighBuffer, TokyoLowBuffer, TokyoStartHour, TokyoStartMin, TokyoEndHour, TokyoEndMin); + } + + if(inLondon) + { + CalculateSessionHighLow(i, rates_total, time, high, low, LondonHighBuffer, LondonLowBuffer, LondonStartHour, LondonStartMin, LondonEndHour, LondonEndMin); + } + + if(inNewYork) + { + CalculateSessionHighLow(i, rates_total, time, high, low, NewYorkHighBuffer, NewYorkLowBuffer, NewYorkStartHour, NewYorkStartMin, NewYorkEndHour, NewYorkEndMin); + } + + // Add labels if enabled + if(ShowLabels && i == rates_total - 1) + { + AddSessionLabels(time[rates_total-1], high[rates_total-1], low[rates_total-1]); + } + } + + return(rates_total); +} + +//+------------------------------------------------------------------+ +//| Parse time string into hours and minutes | +//+------------------------------------------------------------------+ +void ParseTime(string timeStr, int &hour, int &min) +{ + string parts[]; + StringSplit(timeStr, ':', parts); + hour = (int)StringToInteger(parts[0]); + min = (ArraySize(parts) > 1) ? (int)StringToInteger(parts[1]) : 0; +} + +//+------------------------------------------------------------------+ +//| Check if current time is within a session | +//+------------------------------------------------------------------+ +bool IsInSession(int currentHour, int currentMin, int startHour, int startMin, int endHour, int endMin) +{ + int currentTime = currentHour * 100 + currentMin; + int sessionStart = startHour * 100 + startMin; + int sessionEnd = endHour * 100 + endMin; + + // Handle sessions that cross midnight + if(sessionStart > sessionEnd) + { + return(currentTime >= sessionStart || currentTime < sessionEnd); + } + else + { + return(currentTime >= sessionStart && currentTime < sessionEnd); + } +} + +//+------------------------------------------------------------------+ +//| Calculate session high and low | +//+------------------------------------------------------------------+ +void CalculateSessionHighLow(int index, int rates_total, const datetime &time[], const double &high[], const double &low[], + double &highBuffer[], double &lowBuffer[], int startHour, int startMin, int endHour, int endMin) +{ + // Find the start of the current session + MqlDateTime currentDt, sessionStartDt; + TimeToStruct(time[index], currentDt); + TimeToStruct(time[index], sessionStartDt); + + sessionStartDt.hour = startHour; + sessionStartDt.min = startMin; + sessionStartDt.sec = 0; + + datetime sessionStartTime = StructToTime(sessionStartDt); + + // If session crosses midnight, adjust the start time + int sessionStart = startHour * 100 + startMin; + int sessionEnd = endHour * 100 + endMin; + + if(sessionStart > sessionEnd) + { + // Session crosses midnight, check if we need to use previous day + int currentTime = currentDt.hour * 100 + currentDt.min; + if(currentTime < sessionEnd) + { + sessionStartTime -= 86400; // Subtract one day + } + } + + // Find the bar index for the session start + int sessionStartIndex = iBarShift(NULL, 0, sessionStartTime); + if(sessionStartIndex < 0) sessionStartIndex = 0; + + // Calculate high and low for the session + double sessionHigh = high[sessionStartIndex]; + double sessionLow = low[sessionStartIndex]; + + for(int j = sessionStartIndex; j <= index; j++) + { + if(j >= rates_total) continue; + + if(high[j] > sessionHigh) sessionHigh = high[j]; + if(low[j] < sessionLow) sessionLow = low[j]; + } + + // Store the values in buffers + highBuffer[index] = sessionHigh; + lowBuffer[index] = sessionLow; + + // If ShowHighLow is enabled, draw the levels + if(ShowHighLow && index == rates_total - 1) + { + string sessionName = ""; + color sessionClr = clrNONE; + + if(startHour == SydneyStartHour && startMin == SydneyStartMin) + { + sessionName = "Sydney"; + sessionClr = SydneyColor; + } + else if(startHour == TokyoStartHour && startMin == TokyoStartMin) + { + sessionName = "Tokyo"; + sessionClr = TokyoColor; + } + else if(startHour == LondonStartHour && startMin == LondonStartMin) + { + sessionName = "London"; + sessionClr = LondonColor; + } + else if(startHour == NewYorkStartHour && startMin == NewYorkStartMin) + { + sessionName = "NewYork"; + sessionClr = NewYorkColor; + } + + if(sessionName != "") + { + string highLabel = sessionName + " High: " + DoubleToString(sessionHigh, _Digits); + string lowLabel = sessionName + " Low: " + DoubleToString(sessionLow, _Digits); + + ObjectCreate(0, highLabel, OBJ_HLINE, 0, 0, sessionHigh); + ObjectSetInteger(0, highLabel, OBJPROP_COLOR, sessionClr); + ObjectSetInteger(0, highLabel, OBJPROP_WIDTH, LineWidth); + ObjectSetInteger(0, highLabel, OBJPROP_BACK, true); + + ObjectCreate(0, lowLabel, OBJ_HLINE, 0, 0, sessionLow); + ObjectSetInteger(0, lowLabel, OBJPROP_COLOR, sessionClr); + ObjectSetInteger(0, lowLabel, OBJPROP_WIDTH, LineWidth); + ObjectSetInteger(0, lowLabel, OBJPROP_STYLE, STYLE_DOT); + ObjectSetInteger(0, lowLabel, OBJPROP_BACK, true); + } + } +} + +//+------------------------------------------------------------------+ +//| Add session labels to the chart | +//+------------------------------------------------------------------+ +void AddSessionLabels(datetime currentTime, double currentHigh, double currentLow) +{ + MqlDateTime dt; + TimeToStruct(currentTime, dt); + + // Remove previous labels + ObjectsDeleteAll(0, "SessionLabel_"); + + if(IsInSession(dt.hour, dt.min, SydneyStartHour, SydneyStartMin, SydneyEndHour, SydneyEndMin)) + { + ObjectCreate(0, "SessionLabel_Sydney", OBJ_TEXT, 0, currentTime, currentHigh + 10 * _Point); + ObjectSetString(0, "SessionLabel_Sydney", OBJPROP_TEXT, "Sydney Session"); + ObjectSetInteger(0, "SessionLabel_Sydney", OBJPROP_COLOR, SydneyColor); + ObjectSetInteger(0, "SessionLabel_Sydney", OBJPROP_ANCHOR, ANCHOR_LEFT_UPPER); + } + + if(IsInSession(dt.hour, dt.min, TokyoStartHour, TokyoStartMin, TokyoEndHour, TokyoEndMin)) + { + ObjectCreate(0, "SessionLabel_Tokyo", OBJ_TEXT, 0, currentTime, currentHigh + 20 * _Point); + ObjectSetString(0, "SessionLabel_Tokyo", OBJPROP_TEXT, "Tokyo Session"); + ObjectSetInteger(0, "SessionLabel_Tokyo", OBJPROP_COLOR, TokyoColor); + ObjectSetInteger(0, "SessionLabel_Tokyo", OBJPROP_ANCHOR, ANCHOR_LEFT_UPPER); + } + + if(IsInSession(dt.hour, dt.min, LondonStartHour, LondonStartMin, LondonEndHour, LondonEndMin)) + { + ObjectCreate(0, "SessionLabel_London", OBJ_TEXT, 0, currentTime, currentHigh + 30 * _Point); + ObjectSetString(0, "SessionLabel_London", OBJPROP_TEXT, "London Session"); + ObjectSetInteger(0, "SessionLabel_London", OBJPROP_COLOR, LondonColor); + ObjectSetInteger(0, "SessionLabel_London", OBJPROP_ANCHOR, ANCHOR_LEFT_UPPER); + } + + if(IsInSession(dt.hour, dt.min, NewYorkStartHour, NewYorkStartMin, NewYorkEndHour, NewYorkEndMin)) + { + ObjectCreate(0, "SessionLabel_NewYork", OBJ_TEXT, 0, currentTime, currentHigh + 40 * _Point); + ObjectSetString(0, "SessionLabel_NewYork", OBJPROP_TEXT, "New York Session"); + ObjectSetInteger(0, "SessionLabel_NewYork", OBJPROP_COLOR, NewYorkColor); + ObjectSetInteger(0, "SessionLabel_NewYork", OBJPROP_ANCHOR, ANCHOR_LEFT_UPPER); + } +} + +//+------------------------------------------------------------------+ \ No newline at end of file diff --git a/BKPS/14040203/Documents/BKP/fvg.detection.mq5 b/BKPS/14040203/Documents/BKP/fvg.detection.mq5 new file mode 100644 index 0000000..ae01c30 --- /dev/null +++ b/BKPS/14040203/Documents/BKP/fvg.detection.mq5 @@ -0,0 +1,35 @@ + // + XCPOIDrawer *drawer = cHelper.mPOIDrawer; + + // + if (cStateEvents.hasNewFairValueGap) + { + // + int idx = GetYoungest(cState.fairValueGaps); + has = IsValidIndex(idx); + if (has) + { + // + XBoxZone box; + has = ToBox( + box, + cState.fairValueGaps[idx] // + ); + if (has) + { + // + XCBoxObject *iObj; + has = drawer.DrawBox( + box, + iObj // + ); + if (has) + { + Print("Box Drawn ..."); + } + } + } + } + + // + ZeroMemory(drawer); diff --git a/BKPS/14040203/Documents/BKP/percentile.supertrend.pine b/BKPS/14040203/Documents/BKP/percentile.supertrend.pine new file mode 100644 index 0000000..9859bf9 --- /dev/null +++ b/BKPS/14040203/Documents/BKP/percentile.supertrend.pine @@ -0,0 +1,66 @@ +// This Pine Scriptâ„¢ code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ +// © Mattes00 + +//@version=6 +indicator("25-75 Percentile SuperTrend | Mattes", shorttitle = "25-75 ST | Mattes", overlay = true) + +subject = input.int (14,"Supertrend length", minval = 2 , group="25-75 Percentile SuperTrend") +mult = input.float (1, "Multiplier", step=0.05,group="25-75 Percentile SuperTrend") +slen = input.int (27, "Percentile length", group="25-75 Percentile SuperTrend") +src_2575 = input.source(high, "Median smoothing source", group="25-75 Percentile SuperTrend") + +smooth_lower = ta.percentile_nearest_rank(src_2575, slen, 25) +smooth_upper = ta.percentile_nearest_rank(src_2575, slen, 75) + + +Percentile_SuperTrend_func(mult, atrPeriod) => + src_long = smooth_upper + src_short = smooth_lower + + atr = ta.atr(atrPeriod) + upper = src_long + mult * atr + lower = src_short - mult * atr + pl = nz(lower[1]) + pu = nz(upper[1]) + + lower := lower > pl or close[1] < pl ? lower : pl + upper := upper < pu or close[1] > pu ? upper : pu + + int dist = na + float st = na + pt = st[1] + if na(atr[1]) + dist := 1 + else if pt == pu + dist := close > upper ? -1 : 1 + else + dist := close < lower ? 1 : -1 + st := dist == -1 ? lower : upper + [st, dist] + + +[x, dist] = Percentile_SuperTrend_func(mult, subject) + +ST_L = ta.crossunder(dist, 0) +ST_S = ta.crossover(dist, 0) + +Long = ST_L +Short = ST_S + +var Mattes = 0 +if (Long and not Short) + Mattes := 1 +if Short + Mattes := -1 + +syscol = Mattes == 1 ? color.rgb(45, 162, 252) : Mattes == -1 ? color.rgb(113, 59, 249) : color.gray +BlueTransParent = color.new(color.rgb(45, 162, 252), 50) +PurpleTransParent = color.new(color.rgb(113, 59, 249), 50) + +plotcandle(open, high, low, close, 'BarColor', color = syscol, bordercolor = syscol, wickcolor = syscol,force_overlay = true) +upTrend = plot(dist < 0 ? x : na, "Up Trend", color = color.rgb(45, 162, 252), style = plot.style_linebr, linewidth = 2) +downTrend = plot(dist < 0 ? na : x, "Down Trend", color = color.rgb(113, 59, 249), style = plot.style_linebr, linewidth = 2) +s = plot((smooth_lower + smooth_upper) / 2, color = syscol) +fill(s, upTrend, BlueTransParent, fillgaps = false) +fill(s, downTrend, PurpleTransParent, fillgaps = false) + diff --git a/BKPS/14040203/Documents/BKP/session.detector.mq5 b/BKPS/14040203/Documents/BKP/session.detector.mq5 new file mode 100644 index 0000000..8ac3c89 --- /dev/null +++ b/BKPS/14040203/Documents/BKP/session.detector.mq5 @@ -0,0 +1,318 @@ +//+------------------------------------------------------------------+ +//| Forex Sessions and Day Range Indicator | +//+------------------------------------------------------------------+ +#property copyright "Your Name" +#property link "https://www.example.com" +#property version "1.00" +#property indicator_chart_window +#property indicator_buffers 8 // 4 sessions * (High + Low) + +#include "../Libraries/x-saherelm.common.lib.mq5" +#include + +// Define an enumeration for DST rules +enum DST_RULE +{ + DST_SYDNEY, + DST_TOKYO, + DST_LONDON, + DST_NEW_YORK +}; + +struct SessionInfo +{ + string name; + int startHour; // Standard start hour (GMT) + int startMinute; + int endHour; // Standard end hour (GMT) + int endMinute; + DST_RULE dstRule; // DST rule for the session + int dstAdjustment; // Hours to add during DST +}; + +SessionInfo sessions[] = { + {"Sydney", 21, 0, 5, 0, DST_SYDNEY, 1}, + {"Tokyo", 23, 0, 8, 0, DST_TOKYO, 0}, + {"London", 7, 0, 15, 0, DST_LONDON, 1}, + {"New York", 12, 0, 17, 0, DST_NEW_YORK, 1}}; + +double sessionHighBuffers[]; // Buffer for session highs +double sessionLowBuffers[]; // Buffer for session lows + +bool sessionActive[]; +double sessionHigh[]; +double sessionLow[]; +datetime sessionStartTime[]; +datetime sessionEndTime[]; + +double dayHigh = 0; +double dayLow = 0; +datetime dayStartTime; + +// Function to extract the year from a datetime value +int GetYear(datetime time) +{ + return (int)StringSubstr(TimeToString(time, TIME_DATE), 0, 4); +} + +// Function to extract the day of the month from a datetime value +int GetDay(datetime time) +{ + MqlDateTime dt; + TimeToStruct(time, dt); + return dt.day; +} + +// Function to extract the day of the week from a datetime value (0=Sunday, 6=Saturday) +int GetDayOfWeek(datetime time) +{ + MqlDateTime dt; + TimeToStruct(time, dt); + return dt.day_of_week; +} + +//+------------------------------------------------------------------+ +//| Custom indicator initialization function | +//+------------------------------------------------------------------+ +int OnInit() +{ + ArrayResize(sessionActive, ArraySize(sessions)); + ArrayResize(sessionHigh, ArraySize(sessions)); + ArrayResize(sessionLow, ArraySize(sessions)); + ArrayResize(sessionStartTime, ArraySize(sessions)); + ArrayResize(sessionEndTime, ArraySize(sessions)); + + for (int i = 0; i < ArraySize(sessions); i++) + { + sessionActive[i] = false; + sessionHigh[i] = 0; + sessionLow[i] = 0; + sessionStartTime[i] = 0; + sessionEndTime[i] = 0; + } + + dayHigh = 0; + dayLow = 0; + dayStartTime = 0; + + // Initialize buffers for session highs and lows + int totalSessions = ArraySize(sessions); + int totalBars = iBars(NULL, 0); // Get the number of bars on the chart + + ArrayResize(sessionHighBuffers, totalBars); // Resize to match the number of bars + ArrayResize(sessionLowBuffers, totalBars); // Resize to match the number of bars + + for (int i = 0; i < totalSessions; i++) + { + SetIndexBuffer(i * 2, sessionHighBuffers, INDICATOR_DATA); + SetIndexBuffer(i * 2 + 1, sessionLowBuffers, INDICATOR_DATA); + + // Optional: Set colors for high and low buffers + PlotIndexSetInteger(i * 2, PLOT_LINE_COLOR, clrGreen); + PlotIndexSetInteger(i * 2 + 1, PLOT_LINE_COLOR, clrRed); + + IndicatorSetInteger(INDICATOR_LEVELS, 0); // No predefined levels + IndicatorSetString(INDICATOR_SHORTNAME, "Forex Sessions"); + } + + return (INIT_SUCCEEDED); +} + +//+------------------------------------------------------------------+ +//| Custom indicator iteration function | +//+------------------------------------------------------------------+ +int OnCalculate(const int rates_total, + const int prev_calculated, + const datetime &time[], + const double &open[], + const double &high[], + const double &low[], + const double &close[], + const long &tick_volume[], + const long &volume[], + const int &spread[]) +{ + // Ensure buffers are resized to match the number of bars + if (ArraySize(sessionHighBuffers) < rates_total) + { + ArrayResize(sessionHighBuffers, rates_total); + ArrayResize(sessionLowBuffers, rates_total); + } + + datetime currentTime = TimeCurrent(); + + // Retrieve Ask and Bid prices dynamically + double askPrice = SymbolInfoDouble(Symbol(), SYMBOL_ASK); + double bidPrice = SymbolInfoDouble(Symbol(), SYMBOL_BID); + + // Check each session + for (int i = 0; i < ArraySize(sessions); i++) + { + SessionInfo session = sessions[i]; + + // Determine if DST is active using the session's DST rule + bool dstActive = IsDSTActive(session.dstRule, currentTime); + int adjStartHour = session.startHour + (dstActive ? session.dstAdjustment : 0); + int adjEndHour = session.endHour + (dstActive ? session.dstAdjustment : 0); + + datetime todayStart = StringToTime(TimeToString(currentTime, TIME_DATE) + " " + + IntegerToString(adjStartHour) + ":" + + IntegerToString(session.startMinute)); + datetime todayEnd = StringToTime(TimeToString(currentTime, TIME_DATE) + " " + + IntegerToString(adjEndHour) + ":" + + IntegerToString(session.endMinute)); + + // Handle sessions spanning midnight + if (adjEndHour < adjStartHour) + { + todayEnd += 24 * 3600; + } + + if (currentTime >= todayStart && currentTime < todayEnd) + { + if (!sessionActive[i]) + { + sessionActive[i] = true; + sessionStartTime[i] = todayStart; + sessionEndTime[i] = todayEnd; + sessionHigh[i] = askPrice; + sessionLow[i] = bidPrice; + } + else + { + if (askPrice > sessionHigh[i]) + sessionHigh[i] = askPrice; + if (bidPrice < sessionLow[i]) + sessionLow[i] = bidPrice; + } + + // Update buffers for the current bar + sessionHighBuffers[rates_total - 1] = sessionHigh[i]; + sessionLowBuffers[rates_total - 1] = sessionLow[i]; + } + else + { + sessionActive[i] = false; + sessionHighBuffers[rates_total - 1] = EMPTY_VALUE; // Clear buffer when session is inactive + sessionLowBuffers[rates_total - 1] = EMPTY_VALUE; + } + } + + // Check day range + bool dstActiveNY = IsDSTActive(DST_NEW_YORK, currentTime); + int dayStartHour = dstActiveNY ? 21 : 22; + datetime todayDayStart = StringToTime(TimeToString(currentTime, TIME_DATE) + " " + + IntegerToString(dayStartHour) + ":00"); + + if (currentTime < todayDayStart) + { + todayDayStart -= 24 * 3600; + } + + if (dayStartTime != todayDayStart) + { + dayStartTime = todayDayStart; + dayHigh = askPrice; + dayLow = bidPrice; + } + else + { + if (askPrice > dayHigh) + dayHigh = askPrice; + if (bidPrice < dayLow) + dayLow = bidPrice; + } + + // Display information on chart + string comment = "Active Forex Sessions:\n"; + for (int i = 0; i < ArraySize(sessions); i++) + { + if (sessionActive[i]) + { + comment += sessions[i].name + " Session\n" + + "High: " + DoubleToString(sessionHigh[i], _Digits) + "\n" + + "Low: " + DoubleToString(sessionLow[i], _Digits) + "\n"; + } + } + comment += "\nDay Range:\n" + + "High: " + DoubleToString(dayHigh, _Digits) + "\n" + + "Low: " + DoubleToString(dayLow, _Digits); + Comment(comment); + + return (rates_total); +} + +//+------------------------------------------------------------------+ +//| Check if DST is active for a given session | +//+------------------------------------------------------------------+ +bool IsDSTActive(DST_RULE dstRule, datetime time) +{ + switch (dstRule) + { + case DST_SYDNEY: + return IsSydneyDST(time); + case DST_TOKYO: + return IsTokyoDST(time); + case DST_LONDON: + return IsLondonDST(time); + case DST_NEW_YORK: + return IsNewYorkDST(time); + default: + return false; + } +} + +//+------------------------------------------------------------------+ +//| DST Check Functions | +//+------------------------------------------------------------------+ +bool IsLondonDST(datetime time) +{ + int year = GetYear(time); + datetime march31 = StringToTime(ToString(year) + ".03.31 00:00"); + int lastSundayMarch = GetDay(march31) - (GetDayOfWeek(march31) % 7); + datetime dstStart = StringToTime(ToString(year) + ".03." + IntegerToString(lastSundayMarch) + " 01:00"); + + datetime oct31 = StringToTime(ToString(year) + ".10.31 00:00"); + int lastSundayOct = GetDay(oct31) - (GetDayOfWeek(oct31) % 7); + datetime dstEnd = StringToTime(ToString(year) + ".10." + IntegerToString(lastSundayOct) + " 01:00"); + + return time >= dstStart && time < dstEnd; +} + +bool IsNewYorkDST(datetime time) +{ + int year = GetYear(time); + datetime march1 = StringToTime(ToString(year) + ".03.01 00:00"); + int dayOfWeekMarch1 = GetDayOfWeek(march1); + int secondSundayMarch = 1 + (7 - dayOfWeekMarch1) % 7 + 7; + datetime dstStart = StringToTime(ToString(year) + ".03." + IntegerToString(secondSundayMarch) + " 07:00"); + + datetime nov1 = StringToTime(ToString(year) + ".11.01 00:00"); + int dayOfWeekNov1 = GetDayOfWeek(nov1); + int firstSundayNov = 1 + (7 - dayOfWeekNov1) % 7; + datetime dstEnd = StringToTime(ToString(year) + ".11." + IntegerToString(firstSundayNov) + " 06:00"); + + return time >= dstStart && time < dstEnd; +} + +bool IsSydneyDST(datetime time) +{ + int year = GetYear(time); + datetime oct1 = StringToTime(ToString(year) + ".10.01 00:00"); + int dayOfWeekOct1 = GetDayOfWeek(oct1); + int firstSundayOct = 1 + (7 - dayOfWeekOct1) % 7; + datetime dstStart = StringToTime(ToString(year) + ".10." + IntegerToString(firstSundayOct) + " 13:00"); + + datetime apr1 = StringToTime(ToString(year) + ".04.01 00:00"); + int dayOfWeekApr1 = GetDayOfWeek(apr1); + int firstSundayApr = 1 + (7 - dayOfWeekApr1) % 7; + datetime dstEnd = StringToTime(ToString(year) + ".04." + IntegerToString(firstSundayApr) + " 15:00"); + + return time >= dstStart && time < dstEnd; +} + +bool IsTokyoDST(datetime time) +{ + // Tokyo does not observe Daylight Saving Time (DST) + return false; +} \ No newline at end of file diff --git a/BKPS/14040203/Documents/BKP/tmp.sig.codes.mq5 b/BKPS/14040203/Documents/BKP/tmp.sig.codes.mq5 new file mode 100644 index 0000000..70060d0 --- /dev/null +++ b/BKPS/14040203/Documents/BKP/tmp.sig.codes.mq5 @@ -0,0 +1,798 @@ + +// +// Checking Bar Based on Positions State ... +ENUM_X_DIRECTION iBarPosDir; +bool isBarValidForDir = cHelper + .mBarAnalyser + .IsValidForPosition( + cBar, + iBarPosDir // + ); +bool isBarValidForBullish = + isBarValidForDir && + IsBullish(iBarPosDir); +bool isBarValidForBearish = + isBarValidForDir && + IsBearish(iBarPosDir); + +// +// Check Bar Place Based on Golden Zones ... + +// +bool isBarInPeaksGoldenZone = + cBar.high <= cXConditions.peaksBuffer[cIDX] && + cBar.low >= cXConditions.peaksGoldenBuffer[cIDX]; + +// +bool isBarInValesGoldenZone = + cBar.high >= cXConditions.valesBuffer[cIDX] && + cBar.low <= cXConditions.valesGoldenBuffer[cIDX]; + +// +XCPOIDrawer *drawer = provider.visionCycleHelper.mPOIDrawer; + +// +// X3MA ... + +// +bool isX3MaFastMidOverPeaksGoldeZone = + isX3MaFastOverPeaksGoldenZone && + isX3MaMidOverPeaksGoldenZone; + +// +bool isX3MaFastMidUnderValesGoldeZone = + isX3MaFastUnderValesGoldenZone && + isX3MaMidUnderValesGoldenZone; + +// +// XVWAP ... + +// +bool isVWapFastMidOverPeaksGoldeZone = + isVWapFastOverPeaksGoldenZone && + isVWapMidOverPeaksGoldenZone; + +// +bool isVWapFastMidUnderValesGoldeZone = + isVWapFastUnderValesGoldenZone && + isVWapMidUnderValesGoldenZone; + +// +// + +// +bool isX3MaVWapFastUnderValuesGoldenZone = + isX3MaFastUnderValesGoldenZone && + isVWapFastUnderValesGoldenZone; + +// +bool isX3MaVWapFastOverPeaksGoldenZone = + isX3MaFastOverPeaksGoldenZone && + isVWapFastOverPeaksGoldenZone; + +// +// + +// +double x3MaFastMidMax = MathMax( + cXConditions.x3maFastBuffer[cIDX], + cXConditions.x3maMidBuffer[cIDX] // +); + +// +double x3MaFastMidMin = MathMin( + cXConditions.x3maFastBuffer[cIDX], + cXConditions.x3maMidBuffer[cIDX] // +); + +// +double vwapFastMidMax = MathMax( + cXConditions.vwapFastBuffer[cIDX], + cXConditions.vwapMidBuffer[cIDX] // +); + +// +double vwapFastMidMin = MathMin( + cXConditions.vwapFastBuffer[cIDX], + cXConditions.vwapMidBuffer[cIDX] // +); + +// +// + +// +double x3maVWapFastMidMax = MathMax(x3MaFastMidMax, vwapFastMidMax); +double x3maVWapFastMidMin = MathMin(x3MaFastMidMin, vwapFastMidMin); + +// +double x3maVWapMax = MathMax(cXConditions.x3maMax, cXConditions.vwapMax); +double x3maVWapMin = MathMin(cXConditions.x3maMin, cXConditions.vwapMin); + +// +double x3maVWapDiff = x3maVWapMax - x3maVWapMin; + +// +double atr = cXConditions.atrBuffer[cIDX]; + +// +bool isConsolidate = x3maVWapDiff <= (3 * atr); + +// +bool isX3MaVWapSwitchedToBullish = + // + // VWap ... + ( + // + (cXConditions.isVWapBullishOrdered && + cXConditions.isVWapSwitchedToBullishState) || + (cXConditions.isVWapBullishState && + cXConditions.isVWapSwitchedToBullishOrdered) + // + ) + // + || + // + // X3Ma ... + ( + // + (cXConditions.isX3MaBullishOrdered && + cXConditions.isX3MaSwitchedToBullishState) || + (cXConditions.isX3MaBullishState && + cXConditions.isX3MaSwitchedToBullishOrdered) + // + ) + // + ; + +// +bool isX3MaVWapSwitchedToBearish = + // + // VWap ... + ( + // + (cXConditions.isVWapBearishOrdered && + cXConditions.isVWapSwitchedToBearishState) || + (cXConditions.isVWapBearishState && + cXConditions.isVWapSwitchedToBearishOrdered) + // + ) + // + || + // + // X3Ma ... + ( + // + (cXConditions.isX3MaBearishOrdered && + cXConditions.isX3MaSwitchedToBearishState) || + (cXConditions.isX3MaBearishState && + cXConditions.isX3MaSwitchedToBearishOrdered) + // + ) + // + ; + +// +// Bullish Conditions ... +isBullish = + // + // Base Condition ... + ( + // + false + // + // isConsolidate && + // isBarValidForBullish && + // cXConditions.isSarBullish && + // isX3MaVWapSwitchedToBullish && + // cXConditions.isNewPeakOverLast // && + // isVWapFastMidUnderValesGoldeZone // && + // cXConditions.isAtrLowerSlopeBullish + // + ) + // + ; + +// +// Bearish Conditions ... +isBearish = + // + // Base Condition ... + ( + // + false + // + // isConsolidate && + // isBarValidForBearish && + // cXConditions.isSarBearish && + // isX3MaVWapSwitchedToBearish && + // cXConditions.isNewValeUnderLast // && + // isVWapFastMidOverPeaksGoldeZone // && + // cXConditions.isAtrUpperSlopeBearish + // + ) + // + ; + +//////////////////////////////////////////////////////////////////// + +// +// XWPVZ ... +bool HasXWPVZConditions( + ENUM_X_CYCLES cycle, + XSignalBox &box, + ENUM_X_DIRECTION &dir, + X121SMCStrategySignalProviderData &provider, + int barIndex = 0 // +) +{ + // + bool result = false; + + // + box.Clean(); + dir = X_DIRECTION_NONE; + + // + // Fil Selected Data ... + XPOIState cState; + X121Conditions cXConditions; + XPOIStateEvents cStateEvents; + XC121SMCCycleHelper *cHelper; + X121SMCCycleConditions cConditions; + result = provider.SelectCycle( + cycle, + cState, + cStateEvents, + cXConditions, + cHelper, + cConditions // + ); + if (!result) + { + // + cState.Clean(); + ZeroMemory(cHelper); + cConditions.Clean(); + cXConditions.Clean(); + cStateEvents.Clean(); + + // + return result; + } + Parse(cXConditions); + + // + // Normalize Args ... + + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + int idx = -1; + int count = 0; + bool has = false; + + // + int zIDX = barIndex; + int cIDX = zIDX + 1; + int pIDX = cIDX + 1; + int ppIDX = pIDX + 1; + + // + bool isBullish = false; + bool isBearish = false; + + // + XOHCL zBar; + XOHCL cBar; + XOHCL pBar; + + // + // Initial Bars ... + result = zBar.Init( + cState.symbol, + cState.period, + barIndex // + ); + result = + result && + zBar.GetPreviousBar(cBar); + result = + result && + cBar.GetPreviousBar(pBar); + if (!result) + { + // + zBar.Clean(); + cBar.Clean(); + pBar.Clean(); + cState.Clean(); + ZeroMemory(cHelper); + cConditions.Clean(); + cXConditions.Clean(); + + // + return result; + } + + // + XCPOIDrawer *drawer = provider.visionCycleHelper.mPOIDrawer; + + // + // Checking Other Conditions ... + + // + // Checking Bar Based on Positions State ... + ENUM_X_DIRECTION iBarPosDir; + bool isBarValidForDir = cHelper + .mBarAnalyser + .IsValidForPosition( + cBar, + iBarPosDir // + ); + bool isBarValidForBullish = + isBarValidForDir && + IsBullish(iBarPosDir); + bool isBarValidForBearish = + isBarValidForDir && + IsBearish(iBarPosDir); + + // // + // // Continuation Bullish ... + // bool isContinuationBullish = + // // + // isBarValidForBullish && + // cXConditions.isSarBullish && + // cXConditions.isStrBullish && + // cXConditions.isNewPeakOverLast + // // + // ; + + // // + // // Continuation Bearish ... + // bool isContinuationBearish = + // // + // isBarValidForBearish && + // cXConditions.isSarBearish && + // cXConditions.isStrBearish && + // cXConditions.isNewValeUnderLast + // // + // ; + + // + XBoxZone obBox; + XBoxZone fvgBox; + XBoxZone supResBox; + XBoxZone tmpBoxes[]; + bool isBullishFVGRejected = false; + bool isBearishFVGRejected = false; + bool isFVGLowerBullishRejected = false; + bool isFVGUpperBullishRejected = false; + bool isFVGLowerBearishRejected = false; + bool isFVGUpperBearishRejected = false; + has = cState.HasFairValueGaps(); + if (has) + { + // + // Converts FairValueGaps to Box ... + ToBox( + cState.fairValueGaps, + tmpBoxes // + ); + + // + // Select FVG ... + while (HasChild(tmpBoxes)) + { + // + idx = GetYoungest(tmpBoxes); + has = IsValidIndex(idx); + if (!has) + { + break; + } + + // + XBoxZone iBox = tmpBoxes[idx]; + ArrayRemove( + tmpBoxes, + idx, + 1 // + ); + + // + isFVGLowerBullishRejected = + // + cBar.low < iBox.lower && + cBar.GetDown() > iBox.lower + // + ; + + // + isFVGUpperBullishRejected = + // + cBar.low < iBox.upper && + cBar.GetDown() > iBox.upper + // + ; + + // + isFVGLowerBearishRejected = + // + cBar.high > iBox.lower && + cBar.GetUp() < iBox.lower + // + ; + + // + isFVGUpperBearishRejected = + // + cBar.high > iBox.upper && + cBar.GetUp() < iBox.upper + // + ; + + // + // + + // + isBullishFVGRejected = + // + iBox.IsBullish() && + cBar.IsBullish() && + (isFVGLowerBullishRejected + // || isFVGUpperBullishRejected + ) + // + ; + + // + isBearishFVGRejected = + // + iBox.IsBearish() && + cBar.IsBearish() && + ( // isFVGLowerBearishRejected || + isFVGUpperBearishRejected) + // + ; + + // + has = isBullishFVGRejected || + isBearishFVGRejected; + if (has) + { + // + iBox.to = TimeCurrent(); + fvgBox = iBox; + iBox.Clean(); + break; + } + + // + iBox.Clean(); + } + Clean(tmpBoxes); + + // + // Select Order Block which FVG is Inside it ... + has = fvgBox.IsValid(); + if (has) + { + // + // Converts Order Blocks to Box ... + ToBox( + cState.orderBlocks, + tmpBoxes // + ); + + // + // Select Order Blocks ... + has = HasChild(tmpBoxes); + if (has) + { + // + while (HasChild(tmpBoxes)) + { + // + idx = GetYoungest(tmpBoxes); + has = IsValidIndex(idx); + if (!has) + { + break; + } + + // + XBoxZone iBox = tmpBoxes[idx]; + ArrayRemove( + tmpBoxes, + idx, + 1 // + ); + + // + // Validate Order Blocks ... + bool isSameDir = iBox.dir == fvgBox.dir; + bool isFVGInsideOB = IsBoxInsideOr( + fvgBox, + iBox // + ); + + // + has = + isSameDir && + isFVGInsideOB; + if (has) + { + // + iBox.to = TimeCurrent(); + obBox = iBox; + iBox.Clean(); + break; + } + + // + iBox.Clean(); + } + } + } + + // + has = obBox.IsValid(); + if (!has) + { + // + obBox.Clean(); + fvgBox.Clean(); + + // + isBullishFVGRejected = false; + isBearishFVGRejected = false; + isFVGLowerBullishRejected = false; + isFVGUpperBullishRejected = false; + isFVGLowerBearishRejected = false; + isFVGUpperBearishRejected = false; + } + Clean(tmpBoxes); + + // + // Checking Support nad Resistance ... + bool isDirBullish = + obBox.IsBullish() && + fvgBox.IsBullish(); + has = + obBox.IsValid() && + fvgBox.IsValid(); + if (has) + { + // + // Converts Support or Resistance to Boxes ... + if (isDirBullish) + { + // + ToBox( + cState.supportZones, + tmpBoxes // + ); + } + else + { + // + ToBox( + cState.resistanceZones, + tmpBoxes // + ); + } + + // + // Selecting Support nad Resistance ... + has = HasChild(tmpBoxes); + if (has) + { + // + while (HasChild(tmpBoxes)) + { + // + idx = GetYoungest(tmpBoxes); + has = IsValidIndex(idx); + if (!has) + { + break; + } + + // + XBoxZone iBox = tmpBoxes[idx]; + ArrayRemove( + tmpBoxes, + idx, + 1 // + ); + + // + // Validate Support and Resistane ... + bool isDirPassed = iBox.dir == obBox.dir; + bool isPlacePassed = + IsBoxAbove( + iBox, + fvgBox // + ) || + IsBoxAbove( + fvgBox, + iBox // + ) || + IsBoxInside( + iBox, + fvgBox // + ) || + IsBoxInside( + fvgBox, + iBox // + ); + + has = + isDirPassed && + isPlacePassed; + if (has) + { + // + iBox.to = TimeCurrent(); + supResBox = iBox; + iBox.Clean(); + break; + } + + // + iBox.Clean(); + } + } + + // + has = obBox.IsValid() && + fvgBox.IsValid() && + supResBox.IsValid(); + if (!has) + { + // + obBox.Clean(); + fvgBox.Clean(); + supResBox.Clean(); + + // + isBullishFVGRejected = false; + isBearishFVGRejected = false; + isFVGLowerBullishRejected = false; + isFVGUpperBullishRejected = false; + isFVGLowerBearishRejected = false; + isFVGUpperBearishRejected = false; + } + } + } + Clean(tmpBoxes); + + // + // Checking OB and FVG Validation ... + has = obBox.IsValid() && + fvgBox.IsValid() && + supResBox.IsValid(); + if (has) + { + // + // Draw OB ... + if (obBox.IsValid()) + { + // + XCBoxObject *iObj; + has = drawer.DrawBox( + obBox, + iObj // + ); + if (has) + { + iObj.BoxStyle(STYLE_DASH); + } + } + + // + // Draw FVG ... + if (fvgBox.IsValid()) + { + // + XCBoxObject *iObj; + has = drawer.DrawBox( + fvgBox, + iObj // + ); + if (has) + { + iObj.BoxStyle(STYLE_SOLID); + } + } + + // + // Draw Sup/Res Box ... + if (supResBox.IsValid()) + { + // + XCBoxObject *iObj; + has = drawer.DrawBox( + supResBox, + iObj // + ); + if (has) + { + iObj.BoxStyle(STYLE_DOT); + } + } + } + + // + // Bullish Conditions ... + isBullish = + // + // Base Condition ... + ( + // + // false + isBullishFVGRejected + // + ) + // + ; + + // + // Bearish Conditions ... + isBearish = + // + // Base Condition ... + ( + // + // false + isBearishFVGRejected + // + ) + // + ; + + // + // Filling Requirements ... + result = + isBullish || + isBearish; + if (result) + { + // + dir = + isBullish + ? X_DIRECTION_BULLISH + : X_DIRECTION_BEARISH; + + // + box.ob = obBox; + box.fvg = fvgBox; + box.sharp = supResBox; + } + + // + // Check All Conditions ... + result = + box.IsValid() && + HasDirection(dir) && + (isBullish || + isBearish); + + // + // Cleanup Resources ... + zBar.Clean(); + cBar.Clean(); + pBar.Clean(); + cState.Clean(); + ZeroMemory(cHelper); + cConditions.Clean(); + cStateEvents.Clean(); + cXConditions.Clean(); + + // + return result; +} diff --git a/BKPS/14040203/Documents/BKP/volume.ex5 b/BKPS/14040203/Documents/BKP/volume.ex5 new file mode 100644 index 0000000..67e36f5 Binary files /dev/null and b/BKPS/14040203/Documents/BKP/volume.ex5 differ diff --git a/BKPS/14040203/Documents/BKP/volume.mq5 b/BKPS/14040203/Documents/BKP/volume.mq5 new file mode 100644 index 0000000..588abc9 --- /dev/null +++ b/BKPS/14040203/Documents/BKP/volume.mq5 @@ -0,0 +1,210 @@ +//+------------------------------------------------------------------+ +//| BuySellVolumes.mq5 | +//| Copyright © 2023, YourName | +//| | +//+------------------------------------------------------------------+ +#property copyright "YourName" +#property link "https://www.yourwebsite.com" +#property version "1.00" + +// +#property indicator_separate_window +#property indicator_buffers 4 +#property indicator_plots 4 + +//--- Plot settings for Buy Volume +#property indicator_label1 "Buy Volume" +#property indicator_type1 DRAW_HISTOGRAM +#property indicator_color1 clrLime + +//--- Plot settings for Sell Volume +#property indicator_label2 "Sell Volume" +#property indicator_type2 DRAW_HISTOGRAM +#property indicator_color2 clrRed + +//--- Plot settings for Buy Volume MA +#property indicator_label3 "Buy Volume MA" +#property indicator_type3 DRAW_LINE +#property indicator_color3 clrGreen + +//--- Plot settings for Sell Volume MA +#property indicator_label4 "Sell Volume MA" +#property indicator_type4 DRAW_LINE +#property indicator_color4 clrRed + +//--- Input parameters +input int MAPeriod = 14; // Period for the moving average + +//--- Indicator buffers +double BuyVolumeBuffer[]; // Buffer for Buy Volume +double SellVolumeBuffer[]; // Buffer for Sell Volume +double BuyVolumeMABuffer[]; // Buffer for Buy Volume Moving Average +double SellVolumeMABuffer[]; // Buffer for Sell Volume Moving Average + +//+------------------------------------------------------------------+ +//| Custom indicator initialization function | +//+------------------------------------------------------------------+ +int OnInit() +{ + // + // Attach buffers to the indicator + SetIndexBuffer(0, BuyVolumeBuffer, INDICATOR_DATA); + SetIndexBuffer(1, SellVolumeBuffer, INDICATOR_DATA); + SetIndexBuffer(2, BuyVolumeMABuffer, INDICATOR_DATA); + SetIndexBuffer(3, SellVolumeMABuffer, INDICATOR_DATA); + + // + // Set short name for the indicator + IndicatorSetString(INDICATOR_SHORTNAME, "Buy and Sell Volumes"); + + // + return (INIT_SUCCEEDED); +} + +//+------------------------------------------------------------------+ +//| Custom indicator iteration function | +//+------------------------------------------------------------------+ +int OnCalculate(const int rates_total, + const int prev_calculated, + const datetime &time[], + const double &open[], + const double &high[], + const double &low[], + const double &close[], + const long &tick_volume[], + const long &volume[], + const int &spread[] // +) +{ + // + // Start from the first uncalculated bar + int start = MathMax(prev_calculated - 1, 0); + + // + // Loop through bars + for (int i = start; i < rates_total; i++) + { + // + // Calculate Buy and Sell Volumes based on bar-level data + double buyVolume = 0.0; + double sellVolume = 0.0; + + // + if (close[i] > open[i]) + { + // + buyVolume = (double)tick_volume[i]; // Buying pressure (bullish bar) + sellVolume = 0.0; + } + else if (close[i] < open[i]) + { + // + sellVolume = (double)tick_volume[i]; // Selling pressure (bearish bar) + buyVolume = 0.0; + } + else + { + // + // Neutral bar: split volume equally between buy and sell + buyVolume = tick_volume[i] / 2.0; + sellVolume = tick_volume[i] / 2.0; + } + + // + // Store Buy and Sell Volumes in their respective buffers + BuyVolumeBuffer[i] = buyVolume; + SellVolumeBuffer[i] = sellVolume; + + // + // Calculate Moving Averages for Buy and Sell Volumes + if (i >= MAPeriod - 1) + { + // + // Calculate Simple Moving Average for Buy Volume + double buySum = 0.0; + for (int j = 0; j < MAPeriod; j++) + buySum += BuyVolumeBuffer[i - j]; + BuyVolumeMABuffer[i] = buySum / MAPeriod; + + // + // Calculate Simple Moving Average for Sell Volume + double sellSum = 0.0; + for (int j = 0; j < MAPeriod; j++) + sellSum += SellVolumeBuffer[i - j]; + SellVolumeMABuffer[i] = sellSum / MAPeriod; + } + else + { + // + // Not enough data for MA + BuyVolumeMABuffer[i] = EMPTY_VALUE; + SellVolumeMABuffer[i] = EMPTY_VALUE; + } + } + + // + // Normalize all values between 0 and 100 + // NormalizeValues(rates_total); + + // + return (rates_total); +} + +//+------------------------------------------------------------------+ +//| Normalize all values between 0 and 100 | +//+------------------------------------------------------------------+ +void NormalizeValues(int rates_total) +{ + // + // Find the maximum and minimum values across all buffers + double maxValue = 0.0; + double minValue = DBL_MAX; + + // + for (int i = 0; i < rates_total; i++) + { + // + if (BuyVolumeBuffer[i] != EMPTY_VALUE && BuyVolumeBuffer[i] > maxValue) + maxValue = BuyVolumeBuffer[i]; + if (SellVolumeBuffer[i] != EMPTY_VALUE && SellVolumeBuffer[i] > maxValue) + maxValue = SellVolumeBuffer[i]; + if (BuyVolumeMABuffer[i] != EMPTY_VALUE && BuyVolumeMABuffer[i] > maxValue) + maxValue = BuyVolumeMABuffer[i]; + if (SellVolumeMABuffer[i] != EMPTY_VALUE && SellVolumeMABuffer[i] > maxValue) + maxValue = SellVolumeMABuffer[i]; + + // + if (BuyVolumeBuffer[i] != EMPTY_VALUE && BuyVolumeBuffer[i] < minValue) + minValue = BuyVolumeBuffer[i]; + if (SellVolumeBuffer[i] != EMPTY_VALUE && SellVolumeBuffer[i] < minValue) + minValue = SellVolumeBuffer[i]; + if (BuyVolumeMABuffer[i] != EMPTY_VALUE && BuyVolumeMABuffer[i] < minValue) + minValue = BuyVolumeMABuffer[i]; + if (SellVolumeMABuffer[i] != EMPTY_VALUE && SellVolumeMABuffer[i] < minValue) + minValue = SellVolumeMABuffer[i]; + } + + // + // Avoid division by zero + if (maxValue == minValue) + return; + + // + // Normalize all values + for (int i = 0; i < rates_total; i++) + { + // + if (BuyVolumeBuffer[i] != EMPTY_VALUE) + BuyVolumeBuffer[i] = ((BuyVolumeBuffer[i] - minValue) / (maxValue - minValue)) * 100.0; + + if (SellVolumeBuffer[i] != EMPTY_VALUE) + SellVolumeBuffer[i] = ((SellVolumeBuffer[i] - minValue) / (maxValue - minValue)) * 100.0; + + if (BuyVolumeMABuffer[i] != EMPTY_VALUE) + BuyVolumeMABuffer[i] = ((BuyVolumeMABuffer[i] - minValue) / (maxValue - minValue)) * 100.0; + + if (SellVolumeMABuffer[i] != EMPTY_VALUE) + SellVolumeMABuffer[i] = ((SellVolumeMABuffer[i] - minValue) / (maxValue - minValue)) * 100.0; + } +} +//+------------------------------------------------------------------+ diff --git a/BKPS/14040203/Documents/BKP/x-121.smc.market.cycle.helper.class copy.mq5 b/BKPS/14040203/Documents/BKP/x-121.smc.market.cycle.helper.class copy.mq5 new file mode 100644 index 0000000..827b5c8 --- /dev/null +++ b/BKPS/14040203/Documents/BKP/x-121.smc.market.cycle.helper.class copy.mq5 @@ -0,0 +1,4783 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Class Library +// -------------------------------------- +// Name: XC121SMCCycleHelper +// Description: provides all based classes for use ... +// +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +////////////////////////////////////////////////////// +// +// Global Properties ... +#property library +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://www.saherelm.ir" +#property version "1.00" +#property strict + +// +// Imports ... +#include "../../Classes/x-saherelm.x-bar.analyser.class.mq5" +#include "../../Classes/x-saherelm.x-poi.class.mq5" +#include "../Libraries/x-121.smc.lib.mq5" + +// +// Definitions ... + +// +// Implementations ... + +// +// Cycles Enumeration ... +enum ENUM_X_CYCLES +{ + X_CYCLE_NONE, + X_CYCLE_TRIGGER, + X_CYCLE_DECISION, + X_CYCLE_ANALYSE, + X_CYCLE_VERIFICATION, + X_CYCLE_CONSOLIDATION, + X_CYCLE_VISION, +}; + +// +// String Representation of Cycles Enumeration ... +string ToString(ENUM_X_CYCLES value) +{ + // + string result = EnumToString(value); + + // + StringReplace(result, "X_CYCLE_", ""); + + // + return result; +} + +// +// Validate a Cycle ... +bool IsValid(ENUM_X_CYCLES value) +{ + // + bool result = false; + + // + result = + value != X_CYCLE_NONE; + + // + return result; +} + +// +// Cycle Events Enumeration ... +enum ENUM_X_CYCLE_EVENTS +{ + SAR_CHANGE_DETECTED, + NEW_PEAK_DETECTED, + NEW_VALE_DETECTED, + PIVOT_POINT_DETECTED, + VWAP_ORDER_CHANGE_ETECTED, + VWAP_STATE_CHANGE_DETCTED, + CONSOLIDATION_BREAKED_DETECTED, + PEAK_PIVOT_STARTED, + PEAK_PIVOT_ENDED, + VALE_PIVOT_STARTED, + VALE_PIVOT_ENDED, +}; + +// +// Cycle Helper ... +class XC121SMCCycleHelper : public XCBase +{ + // + public: + // + // Props ... + + // + // X121 ... + XCX121Helper *mX121Helper; + + // + // POI Detector ... + XCPOIDrawer *mPOIDrawer; + XCPOIDetector *mPOIDetector; + + // + // Bar Analyser + XCBarAnalyser *mBarAnalyser; + + // + // Constructor(s) ... + XC121SMCCycleHelper() + { + Default(); + } + + // + // Deconstructor ... + ~XC121SMCCycleHelper() + { + DeInit(); + } + + // + // Getter/Setter(s) ... + + // + // Actions ... + + /** + * Initialize ... + * + * @param symbol: String ... + * @param period: ENUM_TIMEFRAMES member ... + * @param x121Inputs: X121Inputs instance ... + * + * @return ( bool ) + */ + bool Init( + string symbol, + ENUM_TIMEFRAMES period, + X121Inputs &x121Inputs, + int requiredPOIs = 50 // + ) + { + // + bool result = false; + + // + if (requiredPOIs < 0) + { + requiredPOIs = 0; + } + + // + result = IsValid(symbol) && + IsValid(period); + if (!result) + { + return result; + } + + // + mSymbol = symbol; + mPeriod = period; + + // + // X121 ... + mX121Helper = new XCX121Helper(); + result = mX121Helper.Init( + symbol, + period, + x121Inputs // + ); + if (!result) + { + return result; + } + + // + mPOIDetector = new XCPOIDetector( + symbol, + period // + ); + mPOIDetector.MaxRequiredPOIs(requiredPOIs); + + // + int maxLoopbackBars = mPOIDetector.MaxAllowedLoopbackForInit(); + int periodSeconds = PeriodSeconds(period); + if (periodSeconds > PeriodSeconds(PERIOD_M15)) + { + // + int multiplier = periodSeconds / PeriodSeconds(PERIOD_M15); + + // + if (multiplier >= 1) + { + maxLoopbackBars *= 2; + } + } + mPOIDetector.MaxAllowedLoopbackForInit(maxLoopbackBars); + mPOIDetector.Init(); + + // + // Initialize Bar Analyser Class Instance ... + mBarAnalyser = new XCBarAnalyser(); + + // + // Initial and Configure POI Drawer if Required ... + mPOIDrawer = new XCPOIDrawer(); + mPOIDrawer.ChartIdentification(0); + mPOIDrawer.SubWindowIdentification(0); + + // + mPOIDrawer.DemandZoneFill(false); + mPOIDrawer.SupplyZoneFill(false); + mPOIDrawer.BullishFVGFill(false); + mPOIDrawer.BearishFVGFill(false); + mPOIDrawer.SupportZoneFill(false); + mPOIDrawer.ResistanceZoneFill(false); + mPOIDrawer.BullishOrderBlockFill(false); + mPOIDrawer.BearishOrderBlockFill(false); + + // + // Set Chart Style ... + ApplyChartStyle(); + + // + return result; + } + + /** + * Retrieve Symbol ... + * + * @return ( string ) + */ + string GetSymbol() + { + return mSymbol; + } + + /** + * Retrieve TimeFrame (Period) ... + * + * @return ( ENUM_TIMEFRAMES ) + */ + ENUM_TIMEFRAMES GetPeriod() + { + return mPeriod; + } + + /** + * Get Specified Bar ... + * + * @param source: XOHCL instance, Source Bar ... + * @param bar: XOHCL instance, Dest Bar ... + * + * @return ( bool ) + */ + bool GetBar( + XOHCL &source, + XOHCL &bar // + ) + { + // + bool result = false; + + // + bar.Clean(); + + // + string symbol = GetSymbol(); + ENUM_TIMEFRAMES period = GetPeriod(); + + // + result = + IsValid(symbol) && + IsValid(period) && + source.IsValid(); + if (!result) + { + return result; + } + + // + int index = iBarShift( + symbol, + period, + source.time // + ); + result = bar.Init( + symbol, + period, + index // + ); + if (!result) + { + // + bar.Clean(); + return result; + } + + // + return result; + } + + /** + * Retrieve Specified Bar ... + * + * @param bar: XOHCL instance ... + * @param index: Integer ... + * + * @return ( bool ) + */ + bool GetBar( + XOHCL &bar, + int index = 0 // + ) + { + // + bool result = false; + + // + bar.Clean(); + + // + if (index < 0) + { + index = 0; + } + + // + string symbol = GetSymbol(); + ENUM_TIMEFRAMES period = GetPeriod(); + + // + result = bar.Init( + symbol, + period, + index // + ); + + // + return result; + } + + /** + * Retrieve Specified Bar ... + * + * @param bar: XOHCL instance ... + * @param time: Datetime ... + * + * @return ( bool ) + */ + bool GetBar( + XOHCL &bar, + datetime time = NULL // + ) + { + // + bool result = false; + + // + int index = GetBarIndex(time); + result = GetBar(bar, + index // + ); + + // + return result; + } + + /** + * Retrieve Specified Time Bar Index ... + * + * @param time: DateTime ... + * + * @return ( int ) + */ + int GetBarIndex(datetime time = NULL) + { + // + int result = -1; + + // + time = NormalizeTime(time); + + // + string symbol = GetSymbol(); + ENUM_TIMEFRAMES period = GetPeriod(); + + // + result = iBarShift( + symbol, + period, + time // + ); + + // + return result; + } + + /** + * Retrieve Cycle Conditions ... + * + * @param events: ENUM_X_CYCLE_EVENTS member, Array ... + * @param conditions: X121SMCCycleConditions instance ... + * @param barIndex: Integer ... + * @param loopback: Integer ... + * + * @return ( bool ) + */ + bool GetConditions( + ENUM_X_CYCLE_EVENTS &events[], + ENUM_XPOI_EVENTS &poiEvents[], + X121SMCCycleConditions &conditions, + int barIndex = 0, + int loopback = 7 // + ) + { + // + bool result = false; + + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + if (loopback < 5) + { + loopback = 5; + } + + // + Clean(events); + Clean(poiEvents); + conditions.Clean(); + + // + result = mX121Helper.GetConditions( + conditions.x121Conditions, + barIndex, + loopback // + ); + if (!result) + { + // + conditions.Clean(); + return result; + } + + // + mPOIDetector.Update(poiEvents); + mPOIDetector.GetState(conditions.state); + + // + conditions.symbol = GetSymbol(); + conditions.period = GetPeriod(); + conditions.time = TimeCurrent(); + + // + // Update(); + + // + result = conditions.IsValid(); + + // + return result; + } + + // + // Tools ... + + // + bool GeneratePVBox( + XBoxZone &box, + int barIndex = 0 // + ) + { + // + bool result = false; + + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + box.Clean(); + box.symbol = GetSymbol(); + box.period = GetPeriod(); + + // + int index = barIndex; + + // + // Peak ... + datetime peaksSameFrom = NULL; + double peak = mX121Helper.xpvHelper.GetPeak(index); + double prevPeak = mX121Helper.xpvHelper.GetPeak(index + 1); + bool startsByPeak = peak == prevPeak; + + // + // Vale ... + datetime valesSameFrom = NULL; + double vale = mX121Helper.xpvHelper.GetVale(index); + double prevVale = mX121Helper.xpvHelper.GetVale(index + 1); + bool startsByVale = + !startsByPeak && + vale == prevVale; + + // + bool canBreak = false; + while (!canBreak) + { + // + index++; + + // + datetime cTime = iTime( + box.symbol, + box.period, + index // + ); + + // + // Peak ... + double iPeak = mX121Helper.xpvHelper.GetPeak(index); + + // + // Vale ... + double iVale = mX121Helper.xpvHelper.GetVale(index); + + // + // Start By Peak or Value ... + bool isSame = false; + if (startsByPeak) + { + // + isSame = iPeak == peak; + bool canSetVale = vale == 0 + ? true + : iVale > vale; + if (canSetVale) + { + vale = iVale; + } + } + else if (startsByVale) + { + // + isSame = iVale == vale; + bool canSetPeak = peak == 0 + ? true + : iPeak < peak; + if (canSetPeak) + { + peak = iPeak; + } + } + + // + if (isSame) + { + // + box.from = cTime; + box.upper = peak; + box.lower = vale; + } + else if (IsValid(box.from)) + { + // + // Complete Box ... + box.to = iTime( + box.symbol, + box.period, + barIndex // + ); + + // + box.type = "XPVBox"; + box.dir = startsByPeak + ? X_DIRECTION_BEARISH + : startsByVale + ? X_DIRECTION_BULLISH + : X_DIRECTION_NONE; + } + + // + canBreak = !isSame; + } + + // + result = box.IsValid(); + if (!result) + { + box.Clean(); + } + + // + return result; + } + + // + int DetectRejections( + XBoxZone &rejections[], + int barIndex = 0, + bool forceBarType = true, + bool forceFiboPressure = true, + bool forceUnUsedRejections = true, + int maxAllowedLoopback = 587 // + ) + { + // + int result = 0; + + // + // Normalize Args ... + Clean(rejections); + + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + int idx = -1; + bool has = false; + for (int i = barIndex + 1; i < barIndex + maxAllowedLoopback; i++) + { + // + // Init Indexed Bar ... + XOHCL iBar; + XOHCL iCBar; + XOHCL iPBar; + has = GetBar(iBar, i); + has = + has && + iBar.GetPreviousBar(iCBar); + has = + has && + iCBar.GetPreviousBar(iPBar); + if (!has) + { + // + iBar.Clean(); + iCBar.Clean(); + iPBar.Clean(); + break; + } + + // + // Check CBar Bullish Fibo Pressure ... + bool cBarHasBullishFiboPressure = + mBarAnalyser + .HasFiboPressure( + iCBar, + X_DIRECTION_BULLISH, + X_FIBO_LEVEL_382 // + ); + + // + // Check CBar Bearish Fibo Pressure ... + bool cBarHasBearishFiboPressure = + mBarAnalyser + .HasFiboPressure( + iCBar, + X_DIRECTION_BEARISH, + X_FIBO_LEVEL_382 // + ); + + // + // Check Bar is Bullish Rejection Swing ... + bool isBullishRejection = + // + iCBar.low < iBar.low && + iCBar.low < iPBar.low && + // + iCBar.low < iCBar.GetDown() && + iCBar.GetLowShadow() > iCBar.GetBody() && + iCBar.GetLowShadow() > iCBar.GetHighShadow() + // + ; + + // + // Check Bar is Bearish Rejection Swing ... + bool isBearishRejection = + // + iCBar.high > iBar.high && + iCBar.high > iPBar.high && + // + iCBar.high > iCBar.GetUp() && + iCBar.GetHighShadow() > iCBar.GetBody() && + iCBar.GetHighShadow() > iCBar.GetLowShadow() + // + ; + + // + // Apply Fibo Pressure ... + if (forceFiboPressure) + { + // + isBullishRejection = + isBullishRejection && + cBarHasBullishFiboPressure; + + // + isBearishRejection = + isBearishRejection && + cBarHasBearishFiboPressure; + } + + // + // Apply Force Bar Type ... + if (forceBarType) + { + // + isBullishRejection = + isBullishRejection && + iCBar.IsBullish(); + + // + isBearishRejection = + isBearishRejection && + iCBar.IsBearish(); + } + + // + // Summarize Result ... + has = isBullishRejection || + isBearishRejection; + if (has) + { + // + XBoxZone iBox; + + // + iBox.to = iBar.time; + iBox.from = iCBar.time; + iBox.period = iBar.period; + iBox.symbol = iBar.symbol; + + // + iBox.dir = + isBullishRejection + ? X_DIRECTION_BULLISH + : X_DIRECTION_BEARISH; + + // + iBox.upper = + isBullishRejection + ? iCBar.GetDown() + : iCBar.high; + + // + iBox.lower = + isBullishRejection + ? iCBar.low + : iCBar.GetUp(); + + // + iBox.type = + isBullishRejection + ? "XSwingLow" + : "XSwingHigh"; + + // + // Validate Box ... + has = iBox.IsValid(); + if (has) + { + // + // Apply Force Unused Rejections ... + if (forceUnUsedRejections) + { + // + has = !IsBoxBreaked( + iBox, + iCBar.Index() + 1, + barIndex // + ); + } + + // + if (has) + { + // + idx = FindIndex( + iBox, + rejections // + ); + has = !IsValidIndex(idx); + if (has) + { + // + AddRef( + iBox, + rejections // + ); + } + } + } + + // + iBox.Clean(); + } + + // + iBar.Clean(); + iCBar.Clean(); + iPBar.Clean(); + } + + // + result = ArraySize(rejections); + + // + return result; + } + + // + datetime DetectNearestCloseOverX3MAFast( + XOHCL &bar, + int maxAllowedBars = 20 // + ) + { + // + datetime result = NULL; + + // + if (!bar.IsValid()) + { + return result; + } + + // + bool has = false; + int idx = bar.Index(); + int start = idx; + int end = start + maxAllowedBars; + bool canContinue = true; + while (canContinue) + { + // + XOHCL iBar; + has = iBar.Init( + bar.symbol, + bar.period, + start // + ); + if (!has) + { + // + iBar.Clean(); + break; + } + + // + double iFast = mX121Helper + .x3maHelper + .GetX3MaFast(start); + + // + has = iBar.close > iFast && + iBar.open < iFast; + if (has) + { + result = iBar.time; + } + + // + canContinue = + start < end && + !IsValid(result); + + // + start++; + + // + iBar.Clean(); + } + + // + return result; + } + + // + datetime DetectNearestCloseUnderX3MAFast( + XOHCL &bar, + int maxAllowedBars = 20 // + ) + { + // + datetime result = NULL; + + // + if (!bar.IsValid()) + { + return result; + } + + // + bool has = false; + int idx = bar.Index(); + int start = idx; + int end = start + maxAllowedBars; + bool canContinue = true; + while (canContinue) + { + // + XOHCL iBar; + has = iBar.Init( + bar.symbol, + bar.period, + start // + ); + if (!has) + { + // + iBar.Clean(); + break; + } + + // + double iFast = mX121Helper + .x3maHelper + .GetX3MaFast(start); + + // + has = iBar.close < iFast && + iBar.open > iFast; + if (has) + { + result = iBar.time; + } + + // + canContinue = + start < end && + !IsValid(result); + + // + start++; + + // + iBar.Clean(); + } + + // + return result; + } + + // + bool DetectNearestStrSwitched( + XOHCL &bar, + ENUM_X_DIRECTION &dir, + int barIndex = 0, + int maxAllowedBars = 20 // + ) + { + // + bool result = false; + + // + bar.Clean(); + dir = X_DIRECTION_NONE; + barIndex = NormalizeInt(barIndex, 0); + maxAllowedBars = NormalizeInt(maxAllowedBars, 20); + + // + // Looping Through LoopBack Period ... + // for Detecting Result ... + for (int i = barIndex; i < barIndex + maxAllowedBars; i++) + { + // + XOHCL iBar; + result = iBar.Init( + GetSymbol(), + GetPeriod(), + i // + ); + if (!result) + { + // + iBar.Clean(); + break; + } + + // + double iStrState = mX121Helper.xstrHelper.GetSTRState(i); + double iStrStateP = mX121Helper.xstrHelper.GetSTRState(i + 1); + + // + bool isStrBullish = iStrState > 0; + bool isStrBullishP = iStrStateP > 0; + + // + bool isStrBearish = iStrState < 0; + bool isStrBearishP = iStrStateP < 0; + + // + bool isBullish = isStrBullish && + !isStrBullishP; + + // + bool isBearish = isStrBearish && + !isStrBearishP; + + // + result = isBullish || + isBearish; + if (result) + { + // + bar = iBar; + + // + dir = isBullish + ? X_DIRECTION_BULLISH + : X_DIRECTION_BEARISH; + + // + iBar.Clean(); + break; + } + + // + iBar.Clean(); + } + + // + return result; + } + + // + // Virtuals ... + + /** + * Set Default Properties Values ... + */ + virtual void Default() + { + } + + // + protected: + // + + // + private: + // + // Props ... + string mSymbol; + ENUM_TIMEFRAMES mPeriod; + + // + // Actions ... + + /** + * Release All Resources ... + */ + void DeInit() + { + // + ZeroMemory(mX121Helper); + ZeroMemory(mPOIDetector); + ZeroMemory(mBarAnalyser); + + // + delete mX121Helper; + delete mPOIDetector; + delete mBarAnalyser; + } + + /** + * Apply Chart Style ... + */ + void ApplyChartStyle() + { + // + // Retrieve Current Chart ID ... + long chartId = ChartID(); + + // + 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 = true; // 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 + + // + ChartSetInteger(chartId, CHART_SHOW_BID_LINE, mShowBidLine); + ChartSetInteger(chartId, CHART_SHOW_ASK_LINE, mShowAskLine); + ChartSetInteger(chartId, CHART_SHOW_GRID, mShowGrid); + ChartSetInteger(chartId, CHART_SHOW_VOLUMES, mShowVolumes); + ChartSetInteger(chartId, CHART_SHOW_TRADE_LEVELS, mShowTradeLevels); + ChartSetInteger(chartId, CHART_AUTOSCROLL, mAutoScroll); + ChartSetInteger(chartId, CHART_QUICK_NAVIGATION, mQuickNavigation); + ChartSetInteger(chartId, CHART_COLOR_FOREGROUND, mForeGroundColor); + ChartSetInteger(chartId, CHART_COLOR_BACKGROUND, mBackGroundColor); + ChartSetInteger(chartId, CHART_COLOR_GRID, mGridColor); + ChartSetInteger(chartId, CHART_COLOR_BID, mBidLineColor); + ChartSetInteger(chartId, CHART_COLOR_ASK, mAskLineColor); + ChartSetInteger(chartId, CHART_COLOR_STOP_LEVEL, mStopColor); + ChartSetInteger(chartId, CHART_COLOR_VOLUME, mVolumesColor); + + // + // For Enabling XCC ... + // ChartSetInteger(chartId, CHART_MODE, mMode); + // ChartSetInteger(chartId, CHART_COLOR_CHART_UP, mUpColor); + // ChartSetInteger(chartId, CHART_COLOR_CHART_DOWN, mDownColor); + // ChartSetInteger(chartId, CHART_COLOR_CANDLE_BULL, mBullishColor); + // ChartSetInteger(chartId, CHART_COLOR_CANDLE_BEAR, mBearishColor); + // ChartSetInteger(chartId, CHART_COLOR_CHART_LINE, mLineColor); + } + + // +}; + +// +// Signal Provider Data ... +struct X121SMCStrategySignalProviderData +{ + // + // Props ... + + // + // Trigger ... + XPOIState triggerState; + double triggerBullishScore; + double triggerBearishScore; + X121Conditions triggerXConditions; + ENUM_XPOI_EVENTS triggerPoiEvents[]; + XC121SMCCycleHelper *triggerCycleHelper; + ENUM_X_CYCLE_EVENTS triggerCycleEvents[]; + X121SMCCycleConditions triggerConditions; + + // + // Decision ... + XPOIState decisionState; + double decisionBullishScore; + double decisionBearishScore; + X121Conditions decisionXConditions; + ENUM_XPOI_EVENTS decisionPoiEvents[]; + XC121SMCCycleHelper *decisionCycleHelper; + ENUM_X_CYCLE_EVENTS decisionCycleEvents[]; + X121SMCCycleConditions decisionConditions; + + // + // Analyse ... + XPOIState analyseState; + double analyseBullishScore; + double analyseBearishScore; + X121Conditions analyseXConditions; + ENUM_XPOI_EVENTS analysePoiEvents[]; + XC121SMCCycleHelper *analyseCycleHelper; + ENUM_X_CYCLE_EVENTS analyseCycleEvents[]; + X121SMCCycleConditions analyseConditions; + + // + // Verification ... + XPOIState verificationState; + double verificationBullishScore; + double verificationBearishScore; + X121Conditions verificationXConditions; + ENUM_XPOI_EVENTS verificationPoiEvents[]; + XC121SMCCycleHelper *verificationCycleHelper; + ENUM_X_CYCLE_EVENTS verificationCycleEvents[]; + X121SMCCycleConditions verificationConditions; + + // + // Consolidation ... + XPOIState consolidationState; + double consolidationBullishScore; + double consolidationBearishScore; + X121Conditions consolidationXConditions; + ENUM_XPOI_EVENTS consolidationPoiEvents[]; + XC121SMCCycleHelper *consolidationCycleHelper; + ENUM_X_CYCLE_EVENTS consolidationCycleEvents[]; + X121SMCCycleConditions consolidationConditions; + + // + // Vision ... + XPOIState visionState; + double visionBullishScore; + double visionBearishScore; + X121Conditions visionXConditions; + ENUM_XPOI_EVENTS visionPoiEvents[]; + XC121SMCCycleHelper *visionCycleHelper; + ENUM_X_CYCLE_EVENTS visionCycleEvents[]; + X121SMCCycleConditions visionConditions; + + // + // Constructor ... + X121SMCStrategySignalProviderData() + { + Clean(); + } + + // + // Tools ... + + // + // Cleanup ... + void Clean() + { + // + // Trigger ... + triggerState.Clean(); + triggerBullishScore = 0; + triggerBearishScore = 0; + Clean(triggerPoiEvents); + Clean(triggerCycleEvents); + triggerConditions.Clean(); + triggerXConditions.Clean(); + + // + // Decision ... + decisionState.Clean(); + decisionBullishScore = 0; + decisionBearishScore = 0; + Clean(decisionPoiEvents); + Clean(decisionCycleEvents); + decisionConditions.Clean(); + decisionXConditions.Clean(); + + // + // Analyse ... + analyseState.Clean(); + analyseBullishScore = 0; + analyseBearishScore = 0; + Clean(analysePoiEvents); + Clean(analyseCycleEvents); + analyseConditions.Clean(); + analyseXConditions.Clean(); + + // + // Verification ... + verificationState.Clean(); + verificationBullishScore = 0; + verificationBearishScore = 0; + Clean(verificationPoiEvents); + Clean(verificationCycleEvents); + verificationConditions.Clean(); + verificationXConditions.Clean(); + + // + // Consolidation ... + consolidationState.Clean(); + consolidationBullishScore = 0; + consolidationBearishScore = 0; + Clean(consolidationPoiEvents); + Clean(consolidationCycleEvents); + consolidationConditions.Clean(); + consolidationXConditions.Clean(); + + // + // Vision ... + visionState.Clean(); + visionBullishScore = 0; + visionBearishScore = 0; + Clean(visionPoiEvents); + Clean(visionCycleEvents); + visionConditions.Clean(); + visionXConditions.Clean(); + } + + // + void Destroy() + { + // + Clean(); + + // + ZeroMemory(visionCycleHelper); + ZeroMemory(triggerCycleHelper); + ZeroMemory(analyseCycleHelper); + ZeroMemory(decisionCycleHelper); + ZeroMemory(verificationCycleHelper); + ZeroMemory(consolidationCycleHelper); + + // + ZeroMemory(this); + } + + // + bool IsValid() + { + // + bool result = false; + + // + result = + visionCycleHelper != NULL && + triggerCycleHelper != NULL && + analyseCycleHelper != NULL && + decisionCycleHelper != NULL && + verificationCycleHelper != NULL && + consolidationCycleHelper != NULL; + + // + return result; + } + + // + // Initialize ... + bool Init( + XC121SMCCycleHelper *_triggerCycleHelper, + XC121SMCCycleHelper *_decisionCycleHelper, + XC121SMCCycleHelper *_analyseCycleHelper, + XC121SMCCycleHelper *_verificationCycleHelper, + XC121SMCCycleHelper *_consolidationCycleHelper, + XC121SMCCycleHelper *_visionCycleHelper // + ) + { + // + bool result = false; + + // + // Validate Cycle Helpers ... + result = + // + _visionCycleHelper != NULL && + _triggerCycleHelper != NULL && + _analyseCycleHelper != NULL && + _decisionCycleHelper != NULL && + _verificationCycleHelper != NULL && + _consolidationCycleHelper != NULL + // + ; + if (!result) + { + return result; + } + + // + visionCycleHelper = _visionCycleHelper; + triggerCycleHelper = _triggerCycleHelper; + analyseCycleHelper = _analyseCycleHelper; + decisionCycleHelper = _decisionCycleHelper; + verificationCycleHelper = _verificationCycleHelper; + consolidationCycleHelper = _consolidationCycleHelper; + + // + result = IsValid(); + + // + return result; + } + + // + // Prepare all ... + bool Prepare( + int barIndex = 0, + int loopback = 10, + bool trigger = false, + bool decision = true, + bool analyse = true, + bool verification = false, + bool consolidation = true, + bool vision = true // + ) + { + // + bool result = false; + + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + if (loopback < 7) + { + loopback = 7; + } + + // + result = IsValid(); + if (!result) + { + return result; + } + + // + // Trigger ... + if (trigger) + { + // + result = triggerCycleHelper.GetConditions( + triggerCycleEvents, + triggerPoiEvents, + triggerConditions, + barIndex, + loopback // + ); + if (!result) + { + // + Clean(triggerPoiEvents); + Clean(triggerCycleEvents); + + // + triggerConditions.Clean(); + + // + return result; + } + } + + // + // Decision ... + if (decision) + { + // + result = decisionCycleHelper.GetConditions( + decisionCycleEvents, + decisionPoiEvents, + decisionConditions, + barIndex, + loopback // + ); + if (!result) + { + // + Clean(triggerPoiEvents); + Clean(decisionPoiEvents); + Clean(triggerCycleEvents); + triggerConditions.Clean(); + Clean(decisionCycleEvents); + decisionConditions.Clean(); + + // + return result; + } + } + + // + // Analyse ... + if (analyse) + { + // + result = analyseCycleHelper.GetConditions( + analyseCycleEvents, + analysePoiEvents, + analyseConditions, + barIndex, + loopback // + ); + if (!result) + { + // + Clean(triggerPoiEvents); + Clean(analysePoiEvents); + Clean(decisionPoiEvents); + Clean(triggerCycleEvents); + Clean(analyseCycleEvents); + triggerConditions.Clean(); + analyseConditions.Clean(); + Clean(decisionCycleEvents); + decisionConditions.Clean(); + + // + return result; + } + } + + // + // Verification ... + if (verification) + { + // + result = verificationCycleHelper.GetConditions( + verificationCycleEvents, + verificationPoiEvents, + verificationConditions, + barIndex, + loopback // + ); + if (!result) + { + // + Clean(triggerPoiEvents); + Clean(analysePoiEvents); + Clean(decisionPoiEvents); + Clean(triggerCycleEvents); + Clean(analyseCycleEvents); + triggerConditions.Clean(); + analyseConditions.Clean(); + Clean(decisionCycleEvents); + decisionConditions.Clean(); + Clean(verificationPoiEvents); + Clean(verificationCycleEvents); + verificationConditions.Clean(); + + // + return result; + } + } + + // + // Consolidation ... + if (consolidation) + { + // + result = consolidationCycleHelper.GetConditions( + consolidationCycleEvents, + consolidationPoiEvents, + consolidationConditions, + barIndex, + loopback // + ); + if (!result) + { + // + Clean(triggerPoiEvents); + Clean(analysePoiEvents); + Clean(decisionPoiEvents); + Clean(triggerCycleEvents); + Clean(analyseCycleEvents); + triggerConditions.Clean(); + analyseConditions.Clean(); + Clean(decisionCycleEvents); + decisionConditions.Clean(); + Clean(verificationPoiEvents); + Clean(consolidationPoiEvents); + Clean(verificationCycleEvents); + verificationConditions.Clean(); + Clean(consolidationCycleEvents); + consolidationConditions.Clean(); + + // + return result; + } + } + + // + // Vision ... + if (vision) + { + result = visionCycleHelper.GetConditions( + visionCycleEvents, + visionPoiEvents, + visionConditions, + barIndex, + loopback // + ); + if (!result) + { + // + Clean(visionPoiEvents); + Clean(triggerPoiEvents); + Clean(analysePoiEvents); + Clean(visionCycleEvents); + visionConditions.Clean(); + Clean(decisionPoiEvents); + Clean(triggerCycleEvents); + Clean(analyseCycleEvents); + triggerConditions.Clean(); + analyseConditions.Clean(); + Clean(decisionCycleEvents); + decisionConditions.Clean(); + Clean(verificationPoiEvents); + Clean(consolidationPoiEvents); + Clean(verificationCycleEvents); + verificationConditions.Clean(); + Clean(consolidationCycleEvents); + consolidationConditions.Clean(); + + // + return result; + } + } + + // + // Cycles POI States ... + visionState = visionConditions.state; + triggerState = triggerConditions.state; + analyseState = analyseConditions.state; + decisionState = decisionConditions.state; + verificationState = verificationConditions.state; + consolidationState = consolidationConditions.state; + + // + // Cycle X121Conditions ... + visionXConditions = visionConditions.x121Conditions; + triggerXConditions = triggerConditions.x121Conditions; + analyseXConditions = analyseConditions.x121Conditions; + decisionXConditions = decisionConditions.x121Conditions; + verificationXConditions = verificationConditions.x121Conditions; + consolidationXConditions = consolidationConditions.x121Conditions; + + // + // Trigger ... + triggerXConditions.GenerateScore( + triggerBullishScore, + triggerBearishScore // + ); + + // + // Decision ... + decisionXConditions.GenerateScore( + decisionBullishScore, + decisionBearishScore // + ); + + // + // Analyse ... + analyseXConditions.GenerateScore( + analyseBullishScore, + analyseBearishScore // + ); + + // + // Verification ... + verificationXConditions.GenerateScore( + verificationBullishScore, + verificationBearishScore // + ); + + // + // Consolidation ... + consolidationXConditions.GenerateScore( + consolidationBullishScore, + consolidationBearishScore // + ); + + // + // Vision ... + visionXConditions.GenerateScore( + visionBullishScore, + visionBearishScore // + ); + + // + return result; + } + + // + bool SelectCycle( + ENUM_X_CYCLES cycle, + XPOIState &cState, + XPOIStateEvents &cStateEvents, + X121Conditions &cXConditions, + XC121SMCCycleHelper *&cHelper, + X121SMCCycleConditions &cConditions // + ) + { + // + bool result = false; + + // + cState.Clean(); + ZeroMemory(cHelper); + cConditions.Clean(); + cStateEvents.Clean(); + cXConditions.Clean(); + + // + result = cycle != X_CYCLE_NONE; + if (!result) + { + return result; + } + + // + if (cycle == X_CYCLE_TRIGGER) + { + // + cState = triggerState; + cHelper = triggerCycleHelper; + cConditions = triggerConditions; + cXConditions = triggerXConditions; + cStateEvents.Init(triggerPoiEvents); + } + else if (cycle == X_CYCLE_DECISION) + { + // + cState = decisionState; + cHelper = decisionCycleHelper; + cConditions = decisionConditions; + cXConditions = decisionXConditions; + cStateEvents.Init(decisionPoiEvents); + } + else if (cycle == X_CYCLE_ANALYSE) + { + // + cState = analyseState; + cHelper = analyseCycleHelper; + cConditions = analyseConditions; + cXConditions = analyseXConditions; + cStateEvents.Init(analysePoiEvents); + } + else if (cycle == X_CYCLE_VERIFICATION) + { + // + cState = verificationState; + cHelper = verificationCycleHelper; + cConditions = verificationConditions; + cXConditions = verificationXConditions; + cStateEvents.Init(verificationPoiEvents); + } + else if (cycle == X_CYCLE_CONSOLIDATION) + { + // + cState = consolidationState; + cHelper = consolidationCycleHelper; + cConditions = consolidationConditions; + cXConditions = consolidationXConditions; + cStateEvents.Init(consolidationPoiEvents); + } + else if (cycle == X_CYCLE_VISION) + { + // + cState = visionState; + cHelper = visionCycleHelper; + cConditions = visionConditions; + cXConditions = visionXConditions; + cStateEvents.Init(visionPoiEvents); + } + + // + result = cState.IsValid() && + cHelper != NULL; + + // + return result; + } + + // + void MaxRequiredPOIs(int value) + { + // + if (!IsValid()) + { + return; + } + + // + visionCycleHelper.mPOIDetector.MaxRequiredPOIs(value); + analyseCycleHelper.mPOIDetector.MaxRequiredPOIs(value); + decisionCycleHelper.mPOIDetector.MaxRequiredPOIs(value); + consolidationCycleHelper.mPOIDetector.MaxRequiredPOIs(value); + } + + // + void MaxAllowedLoopbackForInit(int value) + { + // + if (!IsValid()) + { + return; + } + + // + visionCycleHelper.mPOIDetector.MaxAllowedLoopbackForInit(value); + analyseCycleHelper.mPOIDetector.MaxAllowedLoopbackForInit(value); + decisionCycleHelper.mPOIDetector.MaxAllowedLoopbackForInit(value); + consolidationCycleHelper.mPOIDetector.MaxAllowedLoopbackForInit(value); + } + + // +}; + +// +// Condition Parser ... +struct X121SMCStrategyConditionParser +{ + // + // Props ... + + // + // XMA ... + + // + bool isX3MaFastUnderValesGoldenZone; + bool isX3MaMidUnderValesGoldenZone; + bool isX3MaSlowUnderValesGoldenZone; + + // + bool isX3MaFastCrossedUnderValesGoldenZone; + bool isX3MaMidCrossedUnderValesGoldenZone; + bool isX3MaSlowCrossedUnderValesGoldenZone; + + // + bool isX3MaFastOverPeaksGoldenZone; + bool isX3MaMidOverPeaksGoldenZone; + bool isX3MaSlowOverPeaksGoldenZone; + + // + bool isX3MaFastCrossedOverPeaksGoldenZone; + bool isX3MaMidCrossedOverPeaksGoldenZone; + bool isX3MaSlowCrossedOverPeaksGoldenZone; + + // + // XVWAP ... + + // + bool isVWapFastUnderValesGoldenZone; + bool isVWapMidUnderValesGoldenZone; + bool isVWapSlowUnderValesGoldenZone; + + // + bool isVWapFastCrossedUnderValesGoldenZone; + bool isVWapMidCrossedUnderValesGoldenZone; + bool isVWapSlowCrossedUnderValesGoldenZone; + + // + bool isVWapFastOverPeaksGoldenZone; + bool isVWapMidOverPeaksGoldenZone; + bool isVWapSlowOverPeaksGoldenZone; + + // + bool isVWapFastCrossedOverPeaksGoldenZone; + bool isVWapMidCrossedOverPeaksGoldenZone; + bool isVWapSlowCrossedOverPeaksGoldenZone; + + // + // XHK ... + + // + bool isSMHKUnderValesGoldenZone; + bool isRawHKUnderValesGoldenZone; + + // + bool isSMHKCrossedUnderValesGoldenZone; + bool isRawHKCrossedUnderValesGoldenZone; + + // + bool isSMHKOverPeaksGoldenZone; + bool isRawHKOverPeaksGoldenZone; + + // + bool isSMHKCrossedOverPeaksGoldenZone; + bool isRawHKCrossedOverPeaksGoldenZone; + + // + // XSTR ... + + // + bool isStrUnderValesGoldenZone; + bool isStrCrossedUnderValesGoldenZone; + + // + bool isStrOverPeaksGoldenZone; + bool isStrCrossedOverPeaksGoldenZone; + + // + + // + // Constructor ... + X121SMCStrategyConditionParser() + { + Clean(); + } + + // + // Tools ... + + // + void Clean() + { + // + isX3MaFastUnderValesGoldenZone = false; + isX3MaFastCrossedUnderValesGoldenZone = false; + + // + isX3MaMidUnderValesGoldenZone = false; + isX3MaMidCrossedUnderValesGoldenZone = false; + + // + isX3MaSlowUnderValesGoldenZone = false; + isX3MaSlowCrossedUnderValesGoldenZone = false; + + // + isX3MaFastOverPeaksGoldenZone = false; + isX3MaFastCrossedOverPeaksGoldenZone = false; + + // + isX3MaMidOverPeaksGoldenZone = false; + isX3MaMidCrossedOverPeaksGoldenZone = false; + + // + isX3MaSlowOverPeaksGoldenZone = false; + isX3MaSlowCrossedOverPeaksGoldenZone = false; + + // + isVWapFastUnderValesGoldenZone = false; + isVWapFastCrossedUnderValesGoldenZone = false; + + // + isVWapMidUnderValesGoldenZone = false; + isVWapMidCrossedUnderValesGoldenZone = false; + + // + isVWapSlowUnderValesGoldenZone = false; + isVWapSlowCrossedUnderValesGoldenZone = false; + + // + isVWapFastOverPeaksGoldenZone = false; + isVWapFastCrossedOverPeaksGoldenZone = false; + + // + isVWapMidOverPeaksGoldenZone = false; + isVWapMidCrossedOverPeaksGoldenZone = false; + + // + isVWapSlowOverPeaksGoldenZone = false; + isVWapSlowCrossedOverPeaksGoldenZone = false; + + // + isSMHKUnderValesGoldenZone = false; + isSMHKCrossedUnderValesGoldenZone = false; + + // + isRawHKUnderValesGoldenZone = false; + isRawHKCrossedUnderValesGoldenZone = false; + + // + isSMHKOverPeaksGoldenZone = false; + isSMHKCrossedOverPeaksGoldenZone = false; + + // + isRawHKOverPeaksGoldenZone = false; + isRawHKCrossedOverPeaksGoldenZone = false; + + // + isStrUnderValesGoldenZone = false; + isStrCrossedUnderValesGoldenZone = false; + + // + isStrOverPeaksGoldenZone = false; + isStrCrossedOverPeaksGoldenZone = false; + + // + ZeroMemory(this); + } + + // + void Parse( + X121Conditions &conditions // + ) + { + // + Clean(); + + // + // + int zIDX = 0; + int cIDX = zIDX + 1; + int pIDX = cIDX + 1; + + // + // Reading Required Materials ... + + // + // + + // + double peak = conditions.peaksBuffer[cIDX]; + double vale = conditions.valesBuffer[cIDX]; + + // + double peakP = conditions.peaksBuffer[pIDX]; + double valeP = conditions.valesBuffer[pIDX]; + + // + // + + // + double str = conditions.strBuffer[cIDX]; + double strP = conditions.strBuffer[pIDX]; + + // + // + + // + double smhkO = conditions.xhkSMOpenBuffer[cIDX]; + double smhkC = conditions.xhkSMCloseBuffer[cIDX]; + + // + double smhkMax = MathMax(smhkO, smhkC); + double smhkMin = MathMin(smhkO, smhkC); + + // + double smhkOP = conditions.xhkSMOpenBuffer[pIDX]; + double smhkCP = conditions.xhkSMCloseBuffer[pIDX]; + + // + double smhkMaxP = MathMax(smhkOP, smhkCP); + double smhkMinP = MathMin(smhkOP, smhkCP); + + // + double rawhkO = conditions.xhkRawOpenBuffer[cIDX]; + double rawhkH = conditions.xhkRawHighBuffer[cIDX]; + double rawhkC = conditions.xhkRawCloseBuffer[cIDX]; + double rawhkL = conditions.xhkRawLowBuffer[cIDX]; + + // + double rawhkOP = conditions.xhkRawOpenBuffer[pIDX]; + double rawhkHP = conditions.xhkRawHighBuffer[pIDX]; + double rawhkCP = conditions.xhkRawCloseBuffer[pIDX]; + double rawhkLP = conditions.xhkRawLowBuffer[pIDX]; + + // + // + + // + double support = conditions.supportsBuffer[cIDX]; + double resistance = conditions.resistancesBuffer[cIDX]; + + // + double supportP = conditions.supportsBuffer[pIDX]; + double resistanceP = conditions.resistancesBuffer[pIDX]; + + // + double peakGolden = conditions.peaksGoldenBuffer[cIDX]; + double valeGolden = conditions.valesGoldenBuffer[cIDX]; + + // + double peakGoldenP = conditions.peaksGoldenBuffer[pIDX]; + double valeGoldenP = conditions.valesGoldenBuffer[pIDX]; + + // + // + + // + double x3maFast = conditions.x3maFastBuffer[cIDX]; + double x3maMid = conditions.x3maMidBuffer[cIDX]; + double x3maSlow = conditions.x3maSlowBuffer[cIDX]; + + // + double x3maFastP = conditions.x3maFastBuffer[pIDX]; + double x3maMidP = conditions.x3maMidBuffer[pIDX]; + double x3maSlowP = conditions.x3maSlowBuffer[pIDX]; + + // + double vwapFast = conditions.vwapFastBuffer[cIDX]; + double vwapMid = conditions.vwapMidBuffer[cIDX]; + double vwapSlow = conditions.vwapSlowBuffer[cIDX]; + + // + double vwapFastP = conditions.vwapFastBuffer[pIDX]; + double vwapMidP = conditions.vwapMidBuffer[pIDX]; + double vwapSlowP = conditions.vwapSlowBuffer[pIDX]; + + // + // X3MA ... + + // + isX3MaFastUnderValesGoldenZone = + x3maFast >= vale && + x3maFast <= valeGolden; + + // + bool isX3MaFastUnderValesGoldenZoneP = + x3maFastP >= valeP && + x3maFastP <= valeGoldenP; + + // + isX3MaFastCrossedUnderValesGoldenZone = + isX3MaFastUnderValesGoldenZone && + !isX3MaFastUnderValesGoldenZoneP; + + // + // + + // + isX3MaMidUnderValesGoldenZone = + x3maMid >= vale && + x3maMid <= valeGolden; + + // + bool isX3MaMidUnderValesGoldenZoneP = + x3maMidP >= valeP && + x3maMidP <= valeGoldenP; + + // + isX3MaMidCrossedUnderValesGoldenZone = + isX3MaMidUnderValesGoldenZone && + !isX3MaMidUnderValesGoldenZoneP; + + // + // + + // + isX3MaSlowUnderValesGoldenZone = + x3maSlow >= vale && + x3maSlow <= valeGolden; + + // + bool isX3MaSlowUnderValesGoldenZoneP = + x3maSlowP >= valeP && + x3maSlowP <= valeGoldenP; + + // + isX3MaSlowCrossedUnderValesGoldenZone = + isX3MaSlowUnderValesGoldenZone && + !isX3MaSlowUnderValesGoldenZoneP; + + // + // + + // + isX3MaFastOverPeaksGoldenZone = + x3maFast <= peak && + x3maFast >= peakGolden; + + // + bool isX3MaFastOverPeaksGoldenZoneP = + x3maFastP <= peakP && + x3maFastP >= peakGoldenP; + + // + isX3MaFastCrossedOverPeaksGoldenZone = + isX3MaFastOverPeaksGoldenZone && + !isX3MaFastOverPeaksGoldenZoneP; + + // + // + + // + isX3MaMidOverPeaksGoldenZone = + x3maMid <= peak && + x3maMid >= peakGolden; + + // + bool isX3MaMidOverPeaksGoldenZoneP = + x3maMidP <= peakP && + x3maMidP >= peakGoldenP; + + // + isX3MaMidCrossedOverPeaksGoldenZone = + isX3MaMidOverPeaksGoldenZone && + !isX3MaMidOverPeaksGoldenZoneP; + + // + // + + // + isX3MaSlowOverPeaksGoldenZone = + x3maSlow <= peak && + x3maSlow >= peakGolden; + + // + bool isX3MaSlowOverPeaksGoldenZoneP = + x3maSlowP <= peakP && + x3maSlowP >= peakGoldenP; + + // + isX3MaSlowCrossedOverPeaksGoldenZone = + isX3MaSlowOverPeaksGoldenZone && + !isX3MaSlowOverPeaksGoldenZoneP; + + // + // XVWAP ... + + // + // + + // + isVWapFastUnderValesGoldenZone = + vwapFast >= vale && + vwapFast <= valeGolden; + + // + bool isVWapFastUnderValesGoldenZoneP = + vwapFastP >= valeP && + vwapFastP <= valeGoldenP; + + // + isVWapFastCrossedUnderValesGoldenZone = + isVWapFastUnderValesGoldenZone && + !isVWapFastUnderValesGoldenZoneP; + + // + // + + // + isVWapMidUnderValesGoldenZone = + vwapMid >= vale && + vwapMid <= valeGolden; + + // + bool isVWapMidUnderValesGoldenZoneP = + vwapMidP >= valeP && + vwapMidP <= valeGoldenP; + + // + isVWapMidCrossedUnderValesGoldenZone = + isVWapMidUnderValesGoldenZone && + !isVWapMidUnderValesGoldenZoneP; + + // + // + + // + isVWapSlowUnderValesGoldenZone = + vwapSlow >= vale && + vwapSlow <= valeGolden; + + // + bool isVWapSlowUnderValesGoldenZoneP = + vwapSlowP >= valeP && + vwapSlowP <= valeGoldenP; + + // + isVWapSlowCrossedUnderValesGoldenZone = + isVWapSlowUnderValesGoldenZone && + !isVWapSlowUnderValesGoldenZoneP; + + // + // + + // + isVWapFastOverPeaksGoldenZone = + vwapFast <= peak && + vwapFast >= peakGolden; + + // + bool isVWapFastOverPeaksGoldenZoneP = + vwapFastP <= peakP && + vwapFastP >= peakGoldenP; + + // + isVWapFastCrossedOverPeaksGoldenZone = + isVWapFastOverPeaksGoldenZone && + !isVWapFastOverPeaksGoldenZoneP; + + // + // + + // + isVWapMidOverPeaksGoldenZone = + vwapMid <= peak && + vwapMid >= peakGolden; + + // + bool isVWapMidOverPeaksGoldenZoneP = + vwapMidP <= peakP && + vwapMidP >= peakGoldenP; + + // + isVWapMidCrossedOverPeaksGoldenZone = + isVWapMidOverPeaksGoldenZone && + !isVWapMidOverPeaksGoldenZoneP; + + // + // + + // + isVWapSlowOverPeaksGoldenZone = + vwapSlow <= peak && + vwapSlow >= peakGolden; + + // + bool isVWapSlowOverPeaksGoldenZoneP = + vwapSlowP <= peakP && + vwapSlowP >= peakGoldenP; + + // + isVWapSlowCrossedOverPeaksGoldenZone = + isVWapSlowOverPeaksGoldenZone && + !isVWapSlowOverPeaksGoldenZoneP; + + // + // XHK ... + + // + // + + // + isSMHKUnderValesGoldenZone = + smhkMax >= vale && + smhkMax <= valeGolden; + + // + bool isSMHKUnderValesGoldenZoneP = + smhkMaxP >= valeP && + smhkMaxP <= valeGoldenP; + + // + isSMHKCrossedUnderValesGoldenZone = + isSMHKUnderValesGoldenZone && + !isSMHKUnderValesGoldenZoneP; + + // + // + + // + isRawHKUnderValesGoldenZone = + rawhkH >= vale && + rawhkH <= valeGolden; + + // + bool isRawHKUnderValesGoldenZoneP = + rawhkHP >= valeP && + rawhkHP <= valeGoldenP; + + // + isRawHKCrossedUnderValesGoldenZone = + isRawHKUnderValesGoldenZone && + !isRawHKUnderValesGoldenZoneP; + + // + // + + // + isSMHKOverPeaksGoldenZone = + smhkMin <= peak && + smhkMin >= peakGolden; + + // + bool isSMHKOverPeaksGoldenZoneP = + smhkMinP <= peakP && + smhkMinP >= peakGoldenP; + + // + isSMHKCrossedOverPeaksGoldenZone = + isSMHKOverPeaksGoldenZone && + !isSMHKOverPeaksGoldenZoneP; + + // + // + + // + isRawHKOverPeaksGoldenZone = + rawhkL <= peak && + rawhkL >= peakGolden; + + // + bool isRawHKOverPeaksGoldenZoneP = + rawhkLP <= peakP && + rawhkLP >= peakGoldenP; + + // + isRawHKCrossedOverPeaksGoldenZone = + isRawHKOverPeaksGoldenZone && + !isRawHKOverPeaksGoldenZoneP; + + // + // XSTR ... + + // + // + + // + isStrUnderValesGoldenZone = + str >= vale && + str <= valeGolden; + + // + bool isStrUnderValesGoldenZoneP = + strP >= valeP && + strP <= valeGoldenP; + + // + isStrCrossedUnderValesGoldenZone = + isStrUnderValesGoldenZone && + !isStrUnderValesGoldenZoneP; + + // + // + + // + isStrOverPeaksGoldenZone = + str <= peak && + str >= peakGolden; + + // + bool isStrOverPeaksGoldenZoneP = + strP <= peakP && + strP >= peakGoldenP; + + // + isStrCrossedOverPeaksGoldenZone = + isStrOverPeaksGoldenZone && + !isStrOverPeaksGoldenZoneP; + } + + // + // Rejected Boxes ... + bool HasRejectedBoxConditions( + ENUM_X_CYCLES cycle, + XSignalBox &box, + ENUM_X_DIRECTION &dir, + XSignalBox &waitingBoxes[], + X121SMCStrategySignalProviderData &provider, + int barIndex = 0 // + ) + { + // + bool result = false; + + // + box.Clean(); + dir = X_DIRECTION_NONE; + + // + // Checking Waiting Baoxes Exists ... + result = HasChild(waitingBoxes); + if (!result) + { + return result; + } + + // + // Fil Selected Data ... + XPOIState cState; + X121Conditions cXConditions; + XPOIStateEvents cStateEvents; + XC121SMCCycleHelper *cHelper; + X121SMCCycleConditions cConditions; + result = provider.SelectCycle( + cycle, + cState, + cStateEvents, + cXConditions, + cHelper, + cConditions // + ); + if (!result) + { + // + cState.Clean(); + ZeroMemory(cHelper); + cConditions.Clean(); + cXConditions.Clean(); + cStateEvents.Clean(); + + // + return result; + } + Parse(cXConditions); + + // + // Normalize Args ... + + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + int idx = -1; + int count = 0; + bool has = false; + + // + int zIDX = barIndex; + int cIDX = zIDX + 1; + int pIDX = cIDX + 1; + int ppIDX = pIDX + 1; + + // + bool isBullish = false; + bool isBearish = false; + + // + XOHCL zBar; + XOHCL cBar; + XOHCL pBar; + + // + // Initial Bars ... + result = zBar.Init( + cState.symbol, + cState.period, + barIndex // + ); + result = + result && + zBar.GetPreviousBar(cBar); + result = + result && + cBar.GetPreviousBar(pBar); + if (!result) + { + // + zBar.Clean(); + cBar.Clean(); + pBar.Clean(); + cState.Clean(); + ZeroMemory(cHelper); + cConditions.Clean(); + cXConditions.Clean(); + + // + return result; + } + + // + // Checking Bar Based on Positions State ... + ENUM_X_DIRECTION iBarPosDir; + bool isBarValidForDir = cHelper + .mBarAnalyser + .IsValidForPosition( + cBar, + iBarPosDir // + ); + bool isBarValidForBullish = + isBarValidForDir && + IsBullish(iBarPosDir); + bool isBarValidForBearish = + isBarValidForDir && + IsBearish(iBarPosDir); + + // + // Extract Selected Boxes ... + XBoxZone selectedBox; + XSignalBox iSignalBox; + count = ArraySize(waitingBoxes); + has = IsValidSize(count); + if (has) + { + // + for (int i = 0; i < count; i++) + { + // + XSignalBox iBox = waitingBoxes[i]; + + // + bool isBullish = iBox.ob.IsBullish(); + + // + bool isOBBullishRejected = + // + cBar.low < iBox.ob.upper && + cBar.GetDown() > iBox.ob.upper + // + ; + + // + bool isOBBearishRejected = + // + cBar.high > iBox.ob.lower && + cBar.GetUp() < iBox.ob.lower + // + ; + + // + has = + isBullish + ? isOBBullishRejected + : isOBBearishRejected; + + // + // Force Using OB ... + if (has) + { + // + iSignalBox = iBox; + if (!selectedBox.IsValid()) + { + selectedBox = iBox.ob; + } + iBox.Clean(); + break; + } + + // + iBox.Clean(); + } + } + result = + iSignalBox.IsValid() && + selectedBox.IsValid(); + if (!result) + { + // + zBar.Clean(); + cBar.Clean(); + pBar.Clean(); + cState.Clean(); + iSignalBox.Clean(); + selectedBox.Clean(); + ZeroMemory(cHelper); + cConditions.Clean(); + cXConditions.Clean(); + + // + return result; + } + + // + bool hasSignalBox = iSignalBox.IsValid(); + bool isSignalBoxBullish = IsBullish(iSignalBox.ob.dir); + + // + // Checking Other Conditions ... + bool isVWapSlowPassed = + isSignalBoxBullish + ? cXConditions.isVWapSlowBullish + : cXConditions.isVWapSlowBearish; + + // + // Bullish Conditions ... + isBullish = + // + // Base Condition ... + ( + // + hasSignalBox && + isVWapSlowPassed && + isSignalBoxBullish && + isBarValidForBullish + // + ) + // + ; + + // + // Bearish Conditions ... + isBearish = + // + // Base Condition ... + ( + // + hasSignalBox && + isVWapSlowPassed && + !isSignalBoxBullish && + isBarValidForBearish + // + ) + // + ; + + // + // Filling Requirements ... + result = + isBullish || + isBearish; + if (result) + { + // + dir = + isBullish + ? X_DIRECTION_BULLISH + : X_DIRECTION_BEARISH; + + // + box = iSignalBox; + box.UpdateTo(TimeCurrent()); + } + + // + // Check All Conditions ... + result = + box.IsValid() && + HasDirection(dir) && + (isBullish || + isBearish); + + // + // Cleanup Resources ... + zBar.Clean(); + cBar.Clean(); + pBar.Clean(); + cState.Clean(); + iSignalBox.Clean(); + selectedBox.Clean(); + ZeroMemory(cHelper); + cConditions.Clean(); + cStateEvents.Clean(); + cXConditions.Clean(); + + // + return result; + } + + // + // Activated Boxes ... + bool HasActivatedBoxConditions( + ENUM_X_CYCLES cycle, + XSignalBox &box, + ENUM_X_DIRECTION &dir, + XSignalBox &waitingBoxes[], + X121SMCStrategySignalProviderData &provider, + int barIndex = 0 // + ) + { + // + bool result = false; + + // + box.Clean(); + dir = X_DIRECTION_NONE; + + // + // Checking Waiting Baoxes Exists ... + result = HasChild(waitingBoxes); + if (!result) + { + return result; + } + + // + // Fil Selected Data ... + XPOIState cState; + X121Conditions cXConditions; + XPOIStateEvents cStateEvents; + XC121SMCCycleHelper *cHelper; + X121SMCCycleConditions cConditions; + result = provider.SelectCycle( + cycle, + cState, + cStateEvents, + cXConditions, + cHelper, + cConditions // + ); + if (!result) + { + // + cState.Clean(); + ZeroMemory(cHelper); + cConditions.Clean(); + cXConditions.Clean(); + cStateEvents.Clean(); + + // + return result; + } + Parse(cXConditions); + + // + // Normalize Args ... + + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + int idx = -1; + int count = 0; + bool has = false; + + // + int zIDX = barIndex; + int cIDX = zIDX + 1; + int pIDX = cIDX + 1; + int ppIDX = pIDX + 1; + + // + bool isBullish = false; + bool isBearish = false; + + // + XOHCL zBar; + XOHCL cBar; + XOHCL pBar; + + // + // Initial Bars ... + result = zBar.Init( + cState.symbol, + cState.period, + barIndex // + ); + result = + result && + zBar.GetPreviousBar(cBar); + result = + result && + cBar.GetPreviousBar(pBar); + if (!result) + { + // + zBar.Clean(); + cBar.Clean(); + pBar.Clean(); + cState.Clean(); + ZeroMemory(cHelper); + cConditions.Clean(); + cXConditions.Clean(); + + // + return result; + } + + // + // Checking Bar Based on Positions State ... + ENUM_X_DIRECTION iBarPosDir; + bool isBarValidForDir = cHelper + .mBarAnalyser + .IsValidForPosition( + cBar, + iBarPosDir // + ); + bool isBarValidForBullish = + isBarValidForDir && + IsBullish(iBarPosDir); + bool isBarValidForBearish = + isBarValidForDir && + IsBearish(iBarPosDir); + + // + // Extract Selected Boxes ... + XBoxZone selectedBox; + XSignalBox iSignalBox; + count = ArraySize(waitingBoxes); + has = IsValidSize(count); + if (has) + { + // + for (int i = 0; i < count; i++) + { + // + XSignalBox iBox = waitingBoxes[i]; + + // + bool isBullish = iBox.ob.IsBullish(); + + // + has = cBar.low < iBox.sharp.upper && + cBar.low > iBox.sharp.lower && + cBar.high > iBox.sharp.lower && + cBar.high < iBox.sharp.upper; + + // + // Force Using OB ... + if (has) + { + // + iSignalBox = iBox; + if (!selectedBox.IsValid()) + { + selectedBox = iBox.ob; + } + iBox.Clean(); + break; + } + + // + iBox.Clean(); + } + } + result = + iSignalBox.IsValid() && + selectedBox.IsValid(); + if (!result) + { + // + zBar.Clean(); + cBar.Clean(); + pBar.Clean(); + cState.Clean(); + iSignalBox.Clean(); + selectedBox.Clean(); + ZeroMemory(cHelper); + cConditions.Clean(); + cXConditions.Clean(); + + // + return result; + } + + // + bool hasSignalBox = iSignalBox.IsValid(); + bool isSignalBoxBullish = IsBullish(iSignalBox.ob.dir); + + // + // Checking Other Conditions ... + + // + // XVWAP ... + + // + bool isVWapSlopeBullish = + cXConditions.isVwapFastSlopeBullish && + cXConditions.isVwapMidSlopeBullish && + cXConditions.isVwapSlowSlopeBullish; + + // + bool isVWapSlopeBearish = + cXConditions.isVwapFastSlopeBearish && + cXConditions.isVwapMidSlopeBearish && + cXConditions.isVwapSlowSlopeBearish; + + // + bool isVWapBullishCondition = + (cXConditions.isVWapBullishOrdered && + cXConditions.isVWapSwitchedToBullishState) || + (cXConditions.isVWapBullishState && + cXConditions.isVWapSwitchedToBullishOrdered); + + // + bool isVWapBearishCondition = + (cXConditions.isVWapBearishOrdered && + cXConditions.isVWapSwitchedToBearishState) || + (cXConditions.isVWapBearishState && + cXConditions.isVWapSwitchedToBearishOrdered); + + // + // Bullish Conditions ... + isBullish = + // + // Base Condition ... + ( + // + hasSignalBox && + isSignalBoxBullish && + isVWapSlopeBullish && + isBarValidForBullish && + isVWapBullishCondition + // + ) + // + ; + + // + // Bearish Conditions ... + isBearish = + // + // Base Condition ... + ( + // + hasSignalBox && + isVWapSlopeBearish && + !isSignalBoxBullish && + isBarValidForBearish && + isVWapBearishCondition + // + ) + // + ; + + // + // Filling Requirements ... + result = + isBullish || + isBearish; + if (result) + { + // + dir = + isBullish + ? X_DIRECTION_BULLISH + : X_DIRECTION_BEARISH; + + // + box = iSignalBox; + box.UpdateTo(TimeCurrent()); + + // + // Provide TP/SL ... + + // + box.sl = isBullish + ? cXConditions.vwapMin + : cXConditions.vwapMax; + + // + box.tp = isBullish + ? box.sharp.upper + : box.sharp.lower; + } + + // + // Check All Conditions ... + result = + box.IsValid() && + HasDirection(dir) && + (isBullish || + isBearish); + + // + // Cleanup Resources ... + zBar.Clean(); + cBar.Clean(); + pBar.Clean(); + cState.Clean(); + iSignalBox.Clean(); + selectedBox.Clean(); + ZeroMemory(cHelper); + cConditions.Clean(); + cStateEvents.Clean(); + cXConditions.Clean(); + + // + return result; + } + + // + // Breaked Boxes ... + bool HasBreakedBoxConditions( + ENUM_X_CYCLES cycle, + XSignalBox &box, + ENUM_X_DIRECTION &dir, + XSignalBox &breakedBoxes[], + X121SMCStrategySignalProviderData &provider, + int barIndex = 0 // + ) + { + // + bool result = false; + + // + box.Clean(); + dir = X_DIRECTION_NONE; + + // + // Checking Waiting Baoxes Exists ... + result = HasChild(breakedBoxes); + if (!result) + { + return result; + } + + // + // Fil Selected Data ... + XPOIState cState; + X121Conditions cXConditions; + XPOIStateEvents cStateEvents; + XC121SMCCycleHelper *cHelper; + X121SMCCycleConditions cConditions; + result = provider.SelectCycle( + cycle, + cState, + cStateEvents, + cXConditions, + cHelper, + cConditions // + ); + if (!result) + { + // + cState.Clean(); + ZeroMemory(cHelper); + cConditions.Clean(); + cXConditions.Clean(); + cStateEvents.Clean(); + + // + return result; + } + Parse(cXConditions); + + // + // Normalize Args ... + + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + int idx = -1; + int count = 0; + bool has = false; + + // + int zIDX = barIndex; + int cIDX = zIDX + 1; + int pIDX = cIDX + 1; + int ppIDX = pIDX + 1; + + // + bool isBullish = false; + bool isBearish = false; + + // + XOHCL zBar; + XOHCL cBar; + XOHCL pBar; + + // + // Initial Bars ... + result = zBar.Init( + cState.symbol, + cState.period, + barIndex // + ); + result = + result && + zBar.GetPreviousBar(cBar); + result = + result && + cBar.GetPreviousBar(pBar); + if (!result) + { + // + zBar.Clean(); + cBar.Clean(); + pBar.Clean(); + cState.Clean(); + ZeroMemory(cHelper); + cConditions.Clean(); + cXConditions.Clean(); + + // + return result; + } + + // + // Checking Bar Based on Positions State ... + ENUM_X_DIRECTION iBarPosDir; + bool isBarValidForDir = cHelper + .mBarAnalyser + .IsValidForPosition( + cBar, + iBarPosDir // + ); + bool isBarValidForBullish = + isBarValidForDir && + IsBullish(iBarPosDir); + bool isBarValidForBearish = + isBarValidForDir && + IsBearish(iBarPosDir); + + // + // Extract Selected Boxes ... + XBoxZone selectedBox; + XSignalBox iSignalBox; + count = ArraySize(breakedBoxes); + has = IsValidSize(count); + if (has) + { + // + for (int i = 0; i < count; i++) + { + // + XSignalBox iBox = breakedBoxes[i]; + + // + bool isBullish = iBox.ob.IsBullish(); + + // + has = cBar.low < iBox.sharp.upper && + cBar.low > iBox.sharp.lower && + cBar.high > iBox.sharp.lower && + cBar.high < iBox.sharp.upper; + + // + // Force Using OB ... + if (has) + { + // + iSignalBox = iBox; + if (!selectedBox.IsValid()) + { + selectedBox = iBox.ob; + } + iBox.Clean(); + break; + } + + // + iBox.Clean(); + } + } + result = + iSignalBox.IsValid() && + selectedBox.IsValid(); + if (!result) + { + // + zBar.Clean(); + cBar.Clean(); + pBar.Clean(); + cState.Clean(); + iSignalBox.Clean(); + selectedBox.Clean(); + ZeroMemory(cHelper); + cConditions.Clean(); + cXConditions.Clean(); + + // + return result; + } + + // + bool hasSignalBox = iSignalBox.IsValid(); + bool isSignalBoxBullish = IsBullish(iSignalBox.ob.dir); + + // + // Checking Other Conditions ... + + // + // XVWAP ... + + // + bool isVWapSlopeBullish = + cXConditions.isVwapFastSlopeBullish && + cXConditions.isVwapMidSlopeBullish && + cXConditions.isVwapSlowSlopeBullish; + + // + bool isVWapSlopeBearish = + cXConditions.isVwapFastSlopeBearish && + cXConditions.isVwapMidSlopeBearish && + cXConditions.isVwapSlowSlopeBearish; + + // + bool isVWapBullishCondition = + (cXConditions.isVWapBullishOrdered && + cXConditions.isVWapSwitchedToBullishState) || + (cXConditions.isVWapBullishState && + cXConditions.isVWapSwitchedToBullishOrdered); + + // + bool isVWapBearishCondition = + (cXConditions.isVWapBearishOrdered && + cXConditions.isVWapSwitchedToBearishState) || + (cXConditions.isVWapBearishState && + cXConditions.isVWapSwitchedToBearishOrdered); + + // + // Bullish Conditions ... + isBullish = + // + // Base Condition ... + ( + // + hasSignalBox && + isSignalBoxBullish && + isVWapSlopeBullish && + isBarValidForBullish && + isVWapBullishCondition + // + ) + // + ; + + // + // Bearish Conditions ... + isBearish = + // + // Base Condition ... + ( + // + hasSignalBox && + isVWapSlopeBearish && + !isSignalBoxBullish && + isBarValidForBearish && + isVWapBearishCondition + // + ) + // + ; + + // + // Filling Requirements ... + result = + isBullish || + isBearish; + if (result) + { + // + dir = + isBullish + ? X_DIRECTION_BULLISH + : X_DIRECTION_BEARISH; + + // + box = iSignalBox; + box.UpdateTo(TimeCurrent()); + + // + // Provide TP/SL ... + + // + box.sl = isBullish + ? cXConditions.vwapMin + : cXConditions.vwapMax; + + // + box.tp = isBullish + ? box.sharp.upper + : box.sharp.lower; + } + + // + // Check All Conditions ... + result = + box.IsValid() && + HasDirection(dir) && + (isBullish || + isBearish); + + // + // Cleanup Resources ... + zBar.Clean(); + cBar.Clean(); + pBar.Clean(); + cState.Clean(); + iSignalBox.Clean(); + selectedBox.Clean(); + ZeroMemory(cHelper); + cConditions.Clean(); + cStateEvents.Clean(); + cXConditions.Clean(); + + // + return result; + } + + // + // XFVGMA ... + bool HasXFVGMAConditions( + ENUM_X_CYCLES cycle, + XSignalBox &box, + ENUM_X_DIRECTION &dir, + XSignalBox &waitingBoxes[], + X121SMCStrategySignalProviderData &provider, + int barIndex = 0 // + ) + { + // + bool result = false; + + // + box.Clean(); + dir = X_DIRECTION_NONE; + + // + result = HasChild(waitingBoxes); + if (!result) + { + return result; + } + + // + // Fil Selected Data ... + XPOIState cState; + X121Conditions cXConditions; + XPOIStateEvents cStateEvents; + XC121SMCCycleHelper *cHelper; + X121SMCCycleConditions cConditions; + result = provider.SelectCycle( + cycle, + cState, + cStateEvents, + cXConditions, + cHelper, + cConditions // + ); + if (!result) + { + // + cState.Clean(); + ZeroMemory(cHelper); + cConditions.Clean(); + cXConditions.Clean(); + cStateEvents.Clean(); + + // + return result; + } + Parse(cXConditions); + + // + // Normalize Args ... + + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + int idx = -1; + int count = 0; + bool has = false; + + // + int zIDX = barIndex; + int cIDX = zIDX + 1; + int pIDX = cIDX + 1; + int ppIDX = pIDX + 1; + + // + bool isBullish = false; + bool isBearish = false; + + // + XOHCL zBar; + XOHCL cBar; + XOHCL pBar; + + // + // Initial Bars ... + result = zBar.Init( + cState.symbol, + cState.period, + barIndex // + ); + result = + result && + zBar.GetPreviousBar(cBar); + result = + result && + cBar.GetPreviousBar(pBar); + if (!result) + { + // + zBar.Clean(); + cBar.Clean(); + pBar.Clean(); + cState.Clean(); + ZeroMemory(cHelper); + cConditions.Clean(); + cXConditions.Clean(); + + // + return result; + } + + // + // Select Waiting Box ... + XBoxZone selectedBox; + XSignalBox selectedSignalBox; + count = ArraySize(waitingBoxes); + for (int i = 0; i < count; i++) + { + // + XSignalBox iSBox = waitingBoxes[i]; + bool isBullish = iSBox.ob.IsBullish(); + + // + bool isInsidePassed = + isBullish + ? cBar.low < iSBox.ob.upper && + cBar.low > iSBox.ob.lower + : cBar.high > iSBox.ob.lower && + cBar.high < iSBox.ob.upper; + + // + bool isTypePassed = iSBox.sharp.type == "XSHPOBX"; + + // + has = isTypePassed && + isInsidePassed; + if (has) + { + // + selectedBox = iSBox.ob; + selectedSignalBox = iSBox; + break; + } + } + result = selectedBox.IsValid() && + selectedSignalBox.IsValid(); + if (!result) + { + // + zBar.Clean(); + cBar.Clean(); + pBar.Clean(); + cState.Clean(); + ZeroMemory(cHelper); + cConditions.Clean(); + selectedBox.Clean(); + cXConditions.Clean(); + selectedSignalBox.Clean(); + + // + return result; + } + + // + bool isSignalBoxBullish = selectedBox.IsBullish(); + + // + // Checking Other Conditions ... + + // + // Checking Bar Based on Positions State ... + ENUM_X_DIRECTION iBarPosDir; + bool isBarValidForDir = cHelper + .mBarAnalyser + .IsValidForPosition( + cBar, + iBarPosDir // + ); + bool isBarValidForBullish = + isBarValidForDir && + IsBullish(iBarPosDir); + bool isBarValidForBearish = + isBarValidForDir && + IsBearish(iBarPosDir); + + // + // Bullish Conditions ... + isBullish = + // + // Base Condition ... + ( + // + isSignalBoxBullish && + isBarValidForBullish + // + ) + // + ; + + // + // Bearish Conditions ... + isBearish = + // + // Base Condition ... + ( + // + !isSignalBoxBullish && + isBarValidForBearish + // + ) + // + ; + + // + // Filling Requirements ... + result = + isBullish || + isBearish; + if (result) + { + // + dir = + isBullish + ? X_DIRECTION_BULLISH + : X_DIRECTION_BEARISH; + + // + box = selectedSignalBox; + box.ob.to = TimeCurrent(); + } + + // + // Check All Conditions ... + result = + box.IsValid() && + HasDirection(dir) && + (isBullish || + isBearish); + + // + // Cleanup Resources ... + zBar.Clean(); + cBar.Clean(); + pBar.Clean(); + cState.Clean(); + selectedBox.Clean(); + ZeroMemory(cHelper); + cConditions.Clean(); + cStateEvents.Clean(); + cXConditions.Clean(); + selectedSignalBox.Clean(); + + // + return result; + } + + // + // XWPVZ ... + bool HasXWPVZConditions( + ENUM_X_CYCLES cycle, + ENUM_X_CYCLES vCycle, + XSignalBox &box, + ENUM_X_DIRECTION &dir, + X121SMCStrategySignalProviderData &provider, + int barIndex = 0 // + ) + { + // + bool result = false; + + // + box.Clean(); + dir = X_DIRECTION_NONE; + + // + // Fil Selected Data ... + XPOIState cState; + X121Conditions cXConditions; + XPOIStateEvents cStateEvents; + XC121SMCCycleHelper *cHelper; + X121SMCCycleConditions cConditions; + result = provider.SelectCycle( + cycle, + cState, + cStateEvents, + cXConditions, + cHelper, + cConditions // + ); + if (!result) + { + // + cState.Clean(); + ZeroMemory(cHelper); + cConditions.Clean(); + cXConditions.Clean(); + cStateEvents.Clean(); + + // + return result; + } + Parse(cXConditions); + + // + // Fil Selected Data ... + XPOIState vState; + X121Conditions vXConditions; + XPOIStateEvents vStateEvents; + XC121SMCCycleHelper *vHelper; + X121SMCCycleConditions vConditions; + result = provider.SelectCycle( + vCycle, + vState, + vStateEvents, + vXConditions, + vHelper, + vConditions // + ); + if (!result) + { + // + cState.Clean(); + ZeroMemory(cHelper); + cConditions.Clean(); + cXConditions.Clean(); + cStateEvents.Clean(); + + // + vState.Clean(); + ZeroMemory(vHelper); + cConditions.Clean(); + vXConditions.Clean(); + vStateEvents.Clean(); + + // + return result; + } + Parse(vXConditions); + + // + // Normalize Args ... + + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + int idx = -1; + int count = 0; + bool has = false; + + // + int zIDX = barIndex; + int cIDX = zIDX + 1; + int pIDX = cIDX + 1; + int ppIDX = pIDX + 1; + + // + bool isBullish = false; + bool isBearish = false; + + // + XOHCL zBar; + XOHCL cBar; + XOHCL pBar; + XOHCL pPBar; + + // + // Initial Bars ... + result = zBar.Init( + cState.symbol, + cState.period, + barIndex // + ); + result = + result && + zBar.GetPreviousBar(cBar); + result = + result && + cBar.GetPreviousBar(pBar); + result = + result && + pBar.GetPreviousBar(pPBar); + if (!result) + { + // + zBar.Clean(); + cBar.Clean(); + pBar.Clean(); + cState.Clean(); + ZeroMemory(cHelper); + cConditions.Clean(); + cXConditions.Clean(); + + // + return result; + } + + // + XCPOIDrawer *drawer = provider.visionCycleHelper.mPOIDrawer; + + // + // Checking Other Conditions ... + + // + // Checking Bar Based on Positions State ... + ENUM_X_DIRECTION iBarPosDir; + bool isBarValidForDir = cHelper + .mBarAnalyser + .IsValidForPosition( + cBar, + iBarPosDir // + ); + bool isBarValidForBullish = + isBarValidForDir && + IsBullish(iBarPosDir); + bool isBarValidForBearish = + isBarValidForDir && + IsBearish(iBarPosDir); + + // + // Senkou Span A/B Rejections ... + + // + bool forceType = false; + bool forcePressure = true; + + // + bool isBullishRejectSenkouAB = cBar.IsRejected( + cXConditions.senkouMax, + X_DIRECTION_BULLISH, + forceType, // Force Type ... + forcePressure // Force Pressure ... + ); + + // + bool isBearishRejectSenkouAB = cBar.IsRejected( + cXConditions.senkouMin, + X_DIRECTION_BEARISH, + forceType, // Force Type ... + forcePressure // Force Pressure ... + ); + + // + // TenkanSen/KijunSen Rejections ... + + // + bool isBullishRejectTenKij = cBar.IsRejected( + cXConditions.tenKijMax, + X_DIRECTION_BULLISH, + forceType, // Force Type ... + forcePressure // Force Pressure ... + ); + + // + bool isBearishRejectTenKij = cBar.IsRejected( + cXConditions.tenKijMin, + X_DIRECTION_BEARISH, + forceType, // Force Type ... + forcePressure // Force Pressure ... + ); + + // + // X3MaFast Rejections ... + + // + bool isBullishRejectedFastMa = cBar.IsRejected( + cXConditions.x3maFastBuffer[cIDX], + X_DIRECTION_BULLISH, + forceType, // Force Type ... + forcePressure // Force Pressure ... + ); + + // + bool isBearishRejectedFastMa = cBar.IsRejected( + cXConditions.x3maFastBuffer[cIDX], + X_DIRECTION_BEARISH, + forceType, // Force Type ... + forcePressure // Force Pressure ... + ); + + // + bool isValidBullishRejectedFastMa = + isBullishRejectedFastMa && + cBar.low > cXConditions.senkouMax; + + // + bool isValidBearishRejectedFastMa = + isBearishRejectedFastMa && + cBar.high < cXConditions.senkouMin; + + // + // Bigger Cycle Verification ... + + // + double vBullishScore = 0; + double vBearishScore = 0; + vXConditions.GenerateScore( + vBullishScore, + vBearishScore // + ); + + // + bool isVBUllishPassed = + cBar.low > vXConditions.senkouMax && + vBullishScore > (vBearishScore * 1.5); + + // + bool isVBearishPassed = + cBar.high < vXConditions.senkouMin && + vBearishScore > (vBullishScore * 1.5); + + // + // ichimokou ... + + // + // Bullish Conditions ... + isBullish = + // + isVBUllishPassed && + isBullishRejectSenkouAB + // + ; + + // + // Bearish Conditions ... + isBearish = + // + isVBearishPassed && + isBearishRejectSenkouAB + // + ; + + // + result = isBullish || + isBearish; + if (result) + { + // + dir = + isBullish + ? X_DIRECTION_BULLISH + : X_DIRECTION_BEARISH; + } + + // + // Detecting a Zone and Validate it ... + + // + XBoxZone tmpBoxes[]; + + // + XBoxZone obBox; + XBoxZone fvgBox; + XBoxZone supResBox; + bool hasOB = false; + bool hasFVG = false; + bool hasSupRes = false; + + // + // Select Support and Resistance ... + if (result) + { + // + if (!hasSupRes) + { + // + cState.OrderBlocksAsBox(tmpBoxes); + cState.FairValueGapsAsBox(tmpBoxes); + cState.SupplyDemandsAsBox(tmpBoxes); + cState.SupportResistancesAsBox(tmpBoxes); + + // + has = HasChild(tmpBoxes); + if (has) + { + // + while (HasChild(tmpBoxes)) + { + // + idx = GetOldest(tmpBoxes); + has = IsValidIndex(idx); + if (!has) + { + break; + } + + // + XBoxZone iBox = tmpBoxes[idx]; + ArrayRemove( + tmpBoxes, + idx, + 1 // + ); + iBox.to = TimeCurrent(); + + // + // Try to Validate Support and Resistance ... + int retests = CountBoxRetest( + iBox, + dir, + cBar.period // + ); + bool isTyped = + isBullish + ? iBox.IsBullish() + : iBox.IsBearish(); + bool isRetested = retests >= 1; + bool isPlaced = + isBullish + ? ( + // + (cBar.low < iBox.upper && + cBar.low > iBox.lower) + // + ) + : ( + // + (cBar.high < iBox.upper && + cBar.high > iBox.lower) + // + ); + + // + has = + isTyped && + isPlaced && + isRetested; + if (has) + { + // + supResBox = iBox; + iBox.Clean(); + break; + } + + // + iBox.Clean(); + } + } + + // + hasSupRes = supResBox.IsValid(); + Clean(tmpBoxes); + } + } + + // + Clean(tmpBoxes); + + // + // Bullish Conditions ... + isBullish = + // + isBullish && + hasSupRes + // + ; + + // + // Bearish Conditions ... + isBearish = + // + isBearish && + hasSupRes + // + ; + + // + // Filling Requirements ... + result = + isBullish || + isBearish; + if (result) + { + // + bool drawBoxes = true; + if (drawBoxes) + { + // + if (hasSupRes) + { + // + supResBox.to = TimeCurrent(); + + // + XCBoxObject *iObj; + has = drawer.DrawBox( + supResBox, + iObj // + ); + + // + if (has) + { + iObj.BoxWidth(2); + iObj.BoxStyle(STYLE_DOT); + } + } + } + + // + Print("Signal ..."); + result = false; + isBearish = false; + isBullish = false; + } + + // + // Check All Conditions ... + result = + box.IsValid() && + HasDirection(dir) && + (isBullish || + isBearish); + + // + // Cleanup Resources ... + zBar.Clean(); + cBar.Clean(); + pBar.Clean(); + pPBar.Clean(); + cState.Clean(); + vState.Clean(); + cConditions.Clean(); + cConditions.Clean(); + ZeroMemory(cHelper); + ZeroMemory(vHelper); + cStateEvents.Clean(); + cXConditions.Clean(); + vXConditions.Clean(); + vStateEvents.Clean(); + + // + return result; + } + + // + bool HasXICHConditions( + ENUM_X_CYCLES cycle, + XBoxZone &box, + ENUM_X_DIRECTION &dir, + X121SMCStrategySignalProviderData &provider, + int barIndex = 0 // + ) + { + // + bool result = false; + + // + box.Clean(); + dir = X_DIRECTION_NONE; + + // + // Fil Selected Data ... + XPOIState cState; + X121Conditions cXConditions; + XPOIStateEvents cStateEvents; + XC121SMCCycleHelper *cHelper; + X121SMCCycleConditions cConditions; + result = provider.SelectCycle( + cycle, + cState, + cStateEvents, + cXConditions, + cHelper, + cConditions // + ); + if (!result) + { + // + cState.Clean(); + ZeroMemory(cHelper); + cConditions.Clean(); + cXConditions.Clean(); + cStateEvents.Clean(); + + // + return result; + } + Parse(cXConditions); + + // + // Normalize Args ... + + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + int idx = -1; + int count = 0; + bool has = false; + + // + int zIDX = barIndex; + int cIDX = zIDX + 1; + int pIDX = cIDX + 1; + int ppIDX = pIDX + 1; + + // + bool isBullish = false; + bool isBearish = false; + + // + XOHCL zBar; + XOHCL cBar; + XOHCL pBar; + XOHCL pPBar; + + // + // Initial Bars ... + result = zBar.Init( + cState.symbol, + cState.period, + barIndex // + ); + result = + result && + zBar.GetPreviousBar(cBar); + result = + result && + cBar.GetPreviousBar(pBar); + result = + result && + pBar.GetPreviousBar(pPBar); + if (!result) + { + // + zBar.Clean(); + cBar.Clean(); + pBar.Clean(); + cState.Clean(); + ZeroMemory(cHelper); + cConditions.Clean(); + cXConditions.Clean(); + + // + return result; + } + + // + // Checking Conditions ... + // + // XDELTA ... + + // + bool isDeltaSwitchedToBullish = + (cXConditions.isDeltaCrossedOverMa && + cXConditions.isDeltaSwitchedToBullish); + bool isDeltaBullish = + (cXConditions.isDeltaOverMa && + cXConditions.isDeltaBullish); + bool isDeltaIsBullish = + isDeltaBullish || + isDeltaSwitchedToBullish; + + // + bool isDeltaSwitchedToBearish = + (cXConditions.isDeltaCrossedUnderMa && + cXConditions.isDeltaSwitchedToBearish); + bool isDeltaBearish = + (cXConditions.isDeltaUnderMa && + cXConditions.isDeltaBearish); + bool isDeltaIsBearish = + isDeltaBearish || + isDeltaSwitchedToBearish; + + // + // XVOLUME ... + + // + bool isVolumeSwitchedToBullish = + (cXConditions.isVolumeSwitchedToBullish && + cXConditions.isBullishVolumeSwitchedToIncreased); + bool isVolumeBullish = + (cXConditions.isBullishVolumeIncreased && + cXConditions.isBullishVolumeMaOverBearishVolumeMa); + bool isVolumeIsBullish = + isVolumeBullish || + isVolumeSwitchedToBullish; + + // + bool isVolumeSwitchedToBearish = + (cXConditions.isVolumeSwitchedToBearish && + cXConditions.isBearishVolumeSwitchedToIncreased); + bool isVolumeBearish = + (cXConditions.isBullishVolumeMaUnderBearishVolumeMa && + cXConditions.isBearishVolumeIncreased); + bool isVolumeIsBearish = + isVolumeBearish || + isVolumeSwitchedToBearish; + + // + // XSTR ... + bool isStrIsBullish = + (cXConditions.isStrBullish || + cXConditions.isStrSwitchedToBullish); + bool isStrIsBearish = + (cXConditions.isStrBearish || + cXConditions.isStrSwitchedToBearish); + + // + // XICH ... + bool isIchIsBullish = + (cXConditions.isTenkanSenOverKijunSen || + cXConditions.isTenkanSenCrossedOverKijunSen); + bool isIchIsBearish = + (cXConditions.isTenkanSenUnderKijunSen || + cXConditions.isTenkanSenCrossedUnderKijunSen); + + // + // Checking TK Zone ... + + // + bool isBullishTKZone = + isIchIsBullish && + cBar.low < cXConditions.tenkanSenBuffer[cIDX] && + cBar.low > cXConditions.kijunSenBuffer[cIDX] && + cBar.low < pBar.low && + zBar.open > cBar.low; + + // + bool isBearishTKZone = + isIchIsBearish && + cBar.high > cXConditions.tenkanSenBuffer[cIDX] && + cBar.high < cXConditions.kijunSenBuffer[cIDX] && + cBar.high > pBar.high && + zBar.open < cBar.high; + + // + // Summarize Conditions ... + + // + isBullish = + // + // false + isStrIsBullish && + isIchIsBullish && + isBullishTKZone && + isDeltaIsBullish && + isVolumeIsBullish + // + // + ; + + // + isBearish = + // + // false + isStrIsBearish && + isIchIsBearish && + isBearishTKZone && + isDeltaIsBearish && + isVolumeIsBearish + // + ; + + // + // Filling Requirements ... + result = + isBullish || + isBearish; + if (result) + { + // + dir = + isBullish + ? X_DIRECTION_BULLISH + : X_DIRECTION_BEARISH; + + // + box.dir = dir; + box.from = pPBar.time; + box.to = TimeCurrent(); + box.symbol = cBar.symbol; + box.period = cBar.period; + + // + double points = GetPoints(box.symbol); + + // + double pivot = isBullish + ? cBar.low - (points * 5) + : cBar.high + (points * 5); + + // + double point = GetEntry( + cBar.symbol, + dir // + ); + + // + box.upper = + isBullish + ? point + : pivot; + + // + box.lower = + isBullish + ? pivot + : point; + + // + bool drawBoxes = true; + if (drawBoxes) + { + // + } + } + + // + // Check All Conditions ... + result = + box.IsValid() && + HasDirection(dir) && + (isBullish || + isBearish); + + // + // Cleanup Resources ... + zBar.Clean(); + cBar.Clean(); + pBar.Clean(); + pPBar.Clean(); + cState.Clean(); + cConditions.Clean(); + cConditions.Clean(); + ZeroMemory(cHelper); + cStateEvents.Clean(); + cXConditions.Clean(); + + // + return result; + } + + // + bool HasXSTRConditions( + ENUM_X_CYCLES cycle, + XBoxZone &box, + ENUM_X_DIRECTION &dir, + X121SMCStrategySignalProviderData &provider, + int barIndex = 0 // + ) + { + // + bool result = false; + + // + box.Clean(); + dir = X_DIRECTION_NONE; + + // + // Fil Selected Data ... + XPOIState cState; + X121Conditions cXConditions; + XPOIStateEvents cStateEvents; + XC121SMCCycleHelper *cHelper; + X121SMCCycleConditions cConditions; + result = provider.SelectCycle( + cycle, + cState, + cStateEvents, + cXConditions, + cHelper, + cConditions // + ); + if (!result) + { + // + cState.Clean(); + ZeroMemory(cHelper); + cConditions.Clean(); + cXConditions.Clean(); + cStateEvents.Clean(); + + // + return result; + } + Parse(cXConditions); + + // + // Normalize Args ... + + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + int idx = -1; + int count = 0; + bool has = false; + + // + int zIDX = barIndex; + int cIDX = zIDX + 1; + int pIDX = cIDX + 1; + int ppIDX = pIDX + 1; + + // + bool isBullish = false; + bool isBearish = false; + + // + XOHCL zBar; + XOHCL cBar; + XOHCL pBar; + XOHCL pPBar; + + // + // Initial Bars ... + result = zBar.Init( + cState.symbol, + cState.period, + barIndex // + ); + result = + result && + zBar.GetPreviousBar(cBar); + result = + result && + cBar.GetPreviousBar(pBar); + result = + result && + pBar.GetPreviousBar(pPBar); + if (!result) + { + // + zBar.Clean(); + cBar.Clean(); + pBar.Clean(); + cState.Clean(); + ZeroMemory(cHelper); + cConditions.Clean(); + cXConditions.Clean(); + + // + return result; + } + + // + // Checking Conditions ... + // + // XDELTA ... + + // + bool isDeltaSwitchedToBullish = + (cXConditions.isDeltaCrossedOverMa && + cXConditions.isDeltaSwitchedToBullish); + bool isDeltaBullish = + (cXConditions.isDeltaOverMa && + cXConditions.isDeltaBullish); + bool isDeltaIsBullish = + isDeltaBullish || + isDeltaSwitchedToBullish; + + // + bool isDeltaSwitchedToBearish = + (cXConditions.isDeltaCrossedUnderMa && + cXConditions.isDeltaSwitchedToBearish); + bool isDeltaBearish = + (cXConditions.isDeltaUnderMa && + cXConditions.isDeltaBearish); + bool isDeltaIsBearish = + isDeltaBearish || + isDeltaSwitchedToBearish; + + // + // XVOLUME ... + + // + bool isVolumeSwitchedToBullish = + (cXConditions.isVolumeSwitchedToBullish && + cXConditions.isBullishVolumeSwitchedToIncreased); + bool isVolumeBullish = + (cXConditions.isBullishVolumeIncreased && + cXConditions.isBullishVolumeMaOverBearishVolumeMa); + bool isVolumeIsBullish = + isVolumeBullish || + isVolumeSwitchedToBullish; + + // + bool isVolumeSwitchedToBearish = + (cXConditions.isVolumeSwitchedToBearish && + cXConditions.isBearishVolumeSwitchedToIncreased); + bool isVolumeBearish = + (cXConditions.isBullishVolumeMaUnderBearishVolumeMa && + cXConditions.isBearishVolumeIncreased); + bool isVolumeIsBearish = + isVolumeBearish || + isVolumeSwitchedToBearish; + + // + // XSTR ... + bool isStrIsBullish = + (cXConditions.isStrBullish || + cXConditions.isStrSwitchedToBullish); + bool isStrIsBearish = + (cXConditions.isStrBearish || + cXConditions.isStrSwitchedToBearish); + + // + // Detecting Str Box ... + XBoxZone strBox; + bool hasStrBox = false; + if (!hasStrBox) + { + // + hasStrBox = + cXConditions.isStrBullish || + cXConditions.isStrBearish; + if (hasStrBox) + { + // + ENUM_X_DIRECTION strDir = + cXConditions.isStrBullish + ? X_DIRECTION_BULLISH + : X_DIRECTION_BEARISH; + + // + XOHCL lastBar; + ENUM_X_DIRECTION lastDir; + bool hasLast = + cHelper + .DetectNearestStrSwitched( + lastBar, + lastDir, + zIDX // + ); + + // + XOHCL prevBar; + ENUM_X_DIRECTION prevDir; + bool hasPrev = + hasLast && + cHelper + .DetectNearestStrSwitched( + prevBar, + prevDir, + lastBar.Index() + 1 // + ); + + // + hasStrBox = + hasLast && + hasPrev; + if (hasStrBox) + { + // + int fromIDX = MathMax( + lastBar.Index(), + prevBar.Index() // + ); + + // + string symbol = cBar.symbol; + ENUM_TIMEFRAMES period = cBar.period; + + // + datetime from = GetBarTime( + symbol, + period, + fromIDX // + ); + + // + int length = fromIDX - barIndex; + + // + double upper = zBar.FindHighest( + length, + MODE_HIGH // + ); + + // + double lower = zBar.FindLowest( + length, + MODE_LOW // + ); + + // + strBox.from = from; + strBox.dir = strDir; + strBox.lower = lower; + strBox.upper = upper; + strBox.symbol = symbol; + strBox.period = period; + strBox.type = "XSTRBox"; + strBox.to = TimeCurrent(); + + // + hasStrBox =strBox.IsValid(); + } + + // + lastBar.Clean(); + prevBar.Clean(); + } + } + + // + // XFastMa ... + + // + bool isFastMaOverStr = + (cXConditions.x3maFastBuffer[cIDX] > cXConditions.strBuffer[cIDX]); + + // + bool isFastMaUnderStr = + (cXConditions.x3maFastBuffer[cIDX] < cXConditions.strBuffer[cIDX]); + + // + bool isFastMaBullishReject = + cBar.low < pBar.low && + cBar.low > cXConditions.strBuffer[cIDX] && + cBar.low < cXConditions.x3maFastBuffer[cIDX] && + cBar.GetDown() > cXConditions.x3maFastBuffer[cIDX]; + + // + bool isFastMaBearishReject = + cBar.high > pBar.high && + cBar.high < cXConditions.strBuffer[cIDX] && + cBar.high > cXConditions.x3maFastBuffer[cIDX] && + cBar.GetUp() < cXConditions.x3maFastBuffer[cIDX]; + + // + // Summarize Conditions ... + + // + isBullish = + // + // false + hasStrBox && + isStrIsBullish && + isFastMaOverStr && + // isDeltaIsBullish && + // isVolumeIsBullish && + isFastMaBullishReject + // + // + ; + + // + isBearish = + // + // false + hasStrBox && + isStrIsBearish && + isFastMaUnderStr && + // isDeltaIsBearish && + // isVolumeIsBearish && + isFastMaBearishReject + // + ; + + // + // Filling Requirements ... + result = + isBullish || + isBearish; + if (result) + { + // + XCPOIDrawer *drawer = provider.visionCycleHelper.mPOIDrawer; + XCBoxObject *iObj; + bool isCreated = drawer.DrawBox( + strBox, + iObj // + ); + if (isCreated) { + // + Print("STRBox"); + } + + // + dir = + isBullish + ? X_DIRECTION_BULLISH + : X_DIRECTION_BEARISH; + + // + box.dir = dir; + box.from = pPBar.time; + box.to = TimeCurrent(); + box.symbol = cBar.symbol; + box.period = cBar.period; + + // + double points = GetPoints(box.symbol); + + // + double pivot = cXConditions.strBuffer[cIDX]; + // isBullish + // ? cBar.low - (points * 5) + // : cBar.high + (points * 5); + + // + double point = GetEntry( + cBar.symbol, + dir // + ); + + // + box.upper = + isBullish + ? point + : pivot; + + // + box.lower = + isBullish + ? pivot + : point; + + // + bool drawBoxes = true; + if (drawBoxes) + { + // + } + } + + // + // Check All Conditions ... + result = + box.IsValid() && + HasDirection(dir) && + (isBullish || + isBearish); + + // + // Cleanup Resources ... + zBar.Clean(); + cBar.Clean(); + pBar.Clean(); + pPBar.Clean(); + cState.Clean(); + strBox.Clean(); + cConditions.Clean(); + cConditions.Clean(); + ZeroMemory(cHelper); + cStateEvents.Clean(); + cXConditions.Clean(); + + // + return result; + } + + // +}; diff --git a/BKPS/14040203/Documents/BKP/x-121.smc.market.cycle.helper.class.mq5 b/BKPS/14040203/Documents/BKP/x-121.smc.market.cycle.helper.class.mq5 new file mode 100644 index 0000000..e3e96a0 --- /dev/null +++ b/BKPS/14040203/Documents/BKP/x-121.smc.market.cycle.helper.class.mq5 @@ -0,0 +1,4024 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Class Library +// -------------------------------------- +// Name: XC121SMCCycleHelper +// Description: provides all based classes for use ... +// +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +////////////////////////////////////////////////////// +// +// Global Properties ... +#property library +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://www.saherelm.ir" +#property version "1.00" +#property strict + +// +// Imports ... +#include "../../Classes/x-saherelm.x-bar.analyser.class.mq5" +#include "../../Classes/x-saherelm.x-poi.class.mq5" +#include "../Libraries/x-121.smc.lib.mq5" + +// +// Definitions ... + +// +// Implementations ... + +// +// Cycles Enumeration ... +enum ENUM_X_CYCLES +{ + X_CYCLE_NONE, + X_CYCLE_TRIGGER, + X_CYCLE_DECISION, + X_CYCLE_ANALYSE, + X_CYCLE_VERIFICATION, + X_CYCLE_CONSOLIDATION, + X_CYCLE_VISION, +}; + +// +// String Representation of Cycles Enumeration ... +string ToString(ENUM_X_CYCLES value) +{ + // + string result = EnumToString(value); + + // + StringReplace(result, "X_CYCLE_", ""); + + // + return result; +} + +// +// Validate a Cycle ... +bool IsValid(ENUM_X_CYCLES value) +{ + // + bool result = false; + + // + result = + value != X_CYCLE_NONE; + + // + return result; +} + +// +// Cycle Events Enumeration ... +enum ENUM_X_CYCLE_EVENTS +{ + SAR_CHANGE_DETECTED, + NEW_PEAK_DETECTED, + NEW_VALE_DETECTED, + PIVOT_POINT_DETECTED, + VWAP_ORDER_CHANGE_ETECTED, + VWAP_STATE_CHANGE_DETCTED, + CONSOLIDATION_BREAKED_DETECTED, + PEAK_PIVOT_STARTED, + PEAK_PIVOT_ENDED, + VALE_PIVOT_STARTED, + VALE_PIVOT_ENDED, +}; + +// +// Cycle Helper ... +class XC121SMCCycleHelper : public XCBase +{ + // + public: + // + // Props ... + + // + // X121 ... + XCX121Helper *mX121Helper; + + // + // POI Detector ... + XCPOIDrawer *mPOIDrawer; + XCPOIDetector *mPOIDetector; + + // + // Bar Analyser + XCBarAnalyser *mBarAnalyser; + + // + // Constructor(s) ... + XC121SMCCycleHelper() + { + Default(); + } + + // + // Deconstructor ... + ~XC121SMCCycleHelper() + { + DeInit(); + } + + // + // Getter/Setter(s) ... + + // + // Actions ... + + /** + * Initialize ... + * + * @param symbol: String ... + * @param period: ENUM_TIMEFRAMES member ... + * @param x121Inputs: X121Inputs instance ... + * + * @return ( bool ) + */ + bool Init( + string symbol, + ENUM_TIMEFRAMES period, + X121Inputs &x121Inputs, + int requiredPOIs = 50 // + ) + { + // + bool result = false; + + // + if (requiredPOIs < 0) + { + requiredPOIs = 0; + } + + // + result = IsValid(symbol) && + IsValid(period); + if (!result) + { + return result; + } + + // + mSymbol = symbol; + mPeriod = period; + + // + // X121 ... + mX121Helper = new XCX121Helper(); + result = mX121Helper.Init( + symbol, + period, + x121Inputs // + ); + if (!result) + { + return result; + } + + // + mPOIDetector = new XCPOIDetector( + symbol, + period // + ); + mPOIDetector.MaxRequiredPOIs(requiredPOIs); + + // + int maxLoopbackBars = mPOIDetector.MaxAllowedLoopbackForInit(); + int periodSeconds = PeriodSeconds(period); + if (periodSeconds > PeriodSeconds(PERIOD_M15)) + { + // + int multiplier = periodSeconds / PeriodSeconds(PERIOD_M15); + + // + if (multiplier >= 1) + { + maxLoopbackBars *= 2; + } + } + mPOIDetector.MaxAllowedLoopbackForInit(maxLoopbackBars); + mPOIDetector.Init(); + + // + // Initialize Bar Analyser Class Instance ... + mBarAnalyser = new XCBarAnalyser(); + + // + // Initial and Configure POI Drawer if Required ... + mPOIDrawer = new XCPOIDrawer(); + mPOIDrawer.ChartIdentification(0); + mPOIDrawer.SubWindowIdentification(0); + + // + mPOIDrawer.DemandZoneFill(false); + mPOIDrawer.SupplyZoneFill(false); + mPOIDrawer.BullishFVGFill(false); + mPOIDrawer.BearishFVGFill(false); + mPOIDrawer.SupportZoneFill(false); + mPOIDrawer.ResistanceZoneFill(false); + mPOIDrawer.BullishOrderBlockFill(false); + mPOIDrawer.BearishOrderBlockFill(false); + + // + // Set Chart Style ... + ApplyChartStyle(); + + // + return result; + } + + /** + * Retrieve Symbol ... + * + * @return ( string ) + */ + string GetSymbol() + { + return mSymbol; + } + + /** + * Retrieve TimeFrame (Period) ... + * + * @return ( ENUM_TIMEFRAMES ) + */ + ENUM_TIMEFRAMES GetPeriod() + { + return mPeriod; + } + + /** + * Get Specified Bar ... + * + * @param source: XOHCL instance, Source Bar ... + * @param bar: XOHCL instance, Dest Bar ... + * + * @return ( bool ) + */ + bool GetBar( + XOHCL &source, + XOHCL &bar // + ) + { + // + bool result = false; + + // + bar.Clean(); + + // + string symbol = GetSymbol(); + ENUM_TIMEFRAMES period = GetPeriod(); + + // + result = + IsValid(symbol) && + IsValid(period) && + source.IsValid(); + if (!result) + { + return result; + } + + // + int index = iBarShift( + symbol, + period, + source.time // + ); + result = bar.Init( + symbol, + period, + index // + ); + if (!result) + { + // + bar.Clean(); + return result; + } + + // + return result; + } + + /** + * Retrieve Specified Bar ... + * + * @param bar: XOHCL instance ... + * @param index: Integer ... + * + * @return ( bool ) + */ + bool GetBar( + XOHCL &bar, + int index = 0 // + ) + { + // + bool result = false; + + // + bar.Clean(); + + // + if (index < 0) + { + index = 0; + } + + // + string symbol = GetSymbol(); + ENUM_TIMEFRAMES period = GetPeriod(); + + // + result = bar.Init( + symbol, + period, + index // + ); + + // + return result; + } + + /** + * Retrieve Specified Bar ... + * + * @param bar: XOHCL instance ... + * @param time: Datetime ... + * + * @return ( bool ) + */ + bool GetBar( + XOHCL &bar, + datetime time = NULL // + ) + { + // + bool result = false; + + // + int index = GetBarIndex(time); + result = GetBar(bar, + index // + ); + + // + return result; + } + + /** + * Retrieve Specified Time Bar Index ... + * + * @param time: DateTime ... + * + * @return ( int ) + */ + int GetBarIndex(datetime time = NULL) + { + // + int result = -1; + + // + time = NormalizeTime(time); + + // + string symbol = GetSymbol(); + ENUM_TIMEFRAMES period = GetPeriod(); + + // + result = iBarShift( + symbol, + period, + time // + ); + + // + return result; + } + + /** + * Retrieve Cycle Conditions ... + * + * @param events: ENUM_X_CYCLE_EVENTS member, Array ... + * @param conditions: X121SMCCycleConditions instance ... + * @param barIndex: Integer ... + * @param loopback: Integer ... + * + * @return ( bool ) + */ + bool GetConditions( + ENUM_X_CYCLE_EVENTS &events[], + ENUM_XPOI_EVENTS &poiEvents[], + X121SMCCycleConditions &conditions, + int barIndex = 0, + int loopback = 7 // + ) + { + // + bool result = false; + + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + if (loopback < 5) + { + loopback = 5; + } + + // + Clean(events); + Clean(poiEvents); + conditions.Clean(); + + // + result = mX121Helper.GetConditions( + conditions.x121Conditions, + barIndex, + loopback // + ); + if (!result) + { + // + conditions.Clean(); + return result; + } + + // + mPOIDetector.Update(poiEvents); + mPOIDetector.GetState(conditions.state); + + // + conditions.symbol = GetSymbol(); + conditions.period = GetPeriod(); + conditions.time = TimeCurrent(); + + // + // Update(); + + // + result = conditions.IsValid(); + + // + return result; + } + + // + bool GeneratePVBox( + XBoxZone &box, + int barIndex = 0 // + ) + { + // + bool result = false; + + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + box.Clean(); + box.symbol = GetSymbol(); + box.period = GetPeriod(); + + // + int index = barIndex; + + // + // Peak ... + datetime peaksSameFrom = NULL; + double peak = mX121Helper.xpvHelper.GetPeak(index); + double prevPeak = mX121Helper.xpvHelper.GetPeak(index + 1); + bool startsByPeak = peak == prevPeak; + + // + // Vale ... + datetime valesSameFrom = NULL; + double vale = mX121Helper.xpvHelper.GetVale(index); + double prevVale = mX121Helper.xpvHelper.GetVale(index + 1); + bool startsByVale = + !startsByPeak && + vale == prevVale; + + // + bool canBreak = false; + while (!canBreak) + { + // + index++; + + // + datetime cTime = iTime( + box.symbol, + box.period, + index // + ); + + // + // Peak ... + double iPeak = mX121Helper.xpvHelper.GetPeak(index); + + // + // Vale ... + double iVale = mX121Helper.xpvHelper.GetVale(index); + + // + // Start By Peak or Value ... + bool isSame = false; + if (startsByPeak) + { + // + isSame = iPeak == peak; + bool canSetVale = vale == 0 + ? true + : iVale > vale; + if (canSetVale) + { + vale = iVale; + } + } + else if (startsByVale) + { + // + isSame = iVale == vale; + bool canSetPeak = peak == 0 + ? true + : iPeak < peak; + if (canSetPeak) + { + peak = iPeak; + } + } + + // + if (isSame) + { + // + box.from = cTime; + box.upper = peak; + box.lower = vale; + } + else if (IsValid(box.from)) + { + // + // Complete Box ... + box.to = iTime( + box.symbol, + box.period, + barIndex // + ); + + // + box.type = "XPVBox"; + box.dir = startsByPeak + ? X_DIRECTION_BEARISH + : startsByVale + ? X_DIRECTION_BULLISH + : X_DIRECTION_NONE; + } + + // + canBreak = !isSame; + } + + // + result = box.IsValid(); + if (!result) + { + box.Clean(); + } + + // + return result; + } + + // + int DetectRejections( + XBoxZone &rejections[], + int barIndex = 0, + bool forceBarType = true, + bool forceFiboPressure = true, + bool forceUnUsedRejections = true, + int maxAllowedLoopback = 587 // + ) + { + // + int result = 0; + + // + // Normalize Args ... + Clean(rejections); + + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + int idx = -1; + bool has = false; + for (int i = barIndex + 1; i < barIndex + maxAllowedLoopback; i++) + { + // + // Init Indexed Bar ... + XOHCL iBar; + XOHCL iCBar; + XOHCL iPBar; + has = GetBar(iBar, i); + has = + has && + iBar.GetPreviousBar(iCBar); + has = + has && + iCBar.GetPreviousBar(iPBar); + if (!has) + { + // + iBar.Clean(); + iCBar.Clean(); + iPBar.Clean(); + break; + } + + // + // Check CBar Bullish Fibo Pressure ... + bool cBarHasBullishFiboPressure = + mBarAnalyser + .HasFiboPressure( + iCBar, + X_DIRECTION_BULLISH, + X_FIBO_LEVEL_382 // + ); + + // + // Check CBar Bearish Fibo Pressure ... + bool cBarHasBearishFiboPressure = + mBarAnalyser + .HasFiboPressure( + iCBar, + X_DIRECTION_BEARISH, + X_FIBO_LEVEL_382 // + ); + + // + // Check Bar is Bullish Rejection Swing ... + bool isBullishRejection = + // + iCBar.low < iBar.low && + iCBar.low < iPBar.low && + // + iCBar.low < iCBar.GetDown() && + iCBar.GetLowShadow() > iCBar.GetBody() && + iCBar.GetLowShadow() > iCBar.GetHighShadow() + // + ; + + // + // Check Bar is Bearish Rejection Swing ... + bool isBearishRejection = + // + iCBar.high > iBar.high && + iCBar.high > iPBar.high && + // + iCBar.high > iCBar.GetUp() && + iCBar.GetHighShadow() > iCBar.GetBody() && + iCBar.GetHighShadow() > iCBar.GetLowShadow() + // + ; + + // + // Apply Fibo Pressure ... + if (forceFiboPressure) + { + // + isBullishRejection = + isBullishRejection && + cBarHasBullishFiboPressure; + + // + isBearishRejection = + isBearishRejection && + cBarHasBearishFiboPressure; + } + + // + // Apply Force Bar Type ... + if (forceBarType) + { + // + isBullishRejection = + isBullishRejection && + iCBar.IsBullish(); + + // + isBearishRejection = + isBearishRejection && + iCBar.IsBearish(); + } + + // + // Summarize Result ... + has = isBullishRejection || + isBearishRejection; + if (has) + { + // + XBoxZone iBox; + + // + iBox.to = iBar.time; + iBox.from = iCBar.time; + iBox.period = iBar.period; + iBox.symbol = iBar.symbol; + + // + iBox.dir = + isBullishRejection + ? X_DIRECTION_BULLISH + : X_DIRECTION_BEARISH; + + // + iBox.upper = + isBullishRejection + ? iCBar.GetDown() + : iCBar.high; + + // + iBox.lower = + isBullishRejection + ? iCBar.low + : iCBar.GetUp(); + + // + iBox.type = + isBullishRejection + ? "XSwingLow" + : "XSwingHigh"; + + // + // Validate Box ... + has = iBox.IsValid(); + if (has) + { + // + // Apply Force Unused Rejections ... + if (forceUnUsedRejections) + { + // + has = !IsBoxBreaked( + iBox, + iCBar.Index() + 1, + barIndex // + ); + } + + // + if (has) + { + // + idx = FindIndex( + iBox, + rejections // + ); + has = !IsValidIndex(idx); + if (has) + { + // + AddRef( + iBox, + rejections // + ); + } + } + } + + // + iBox.Clean(); + } + + // + iBar.Clean(); + iCBar.Clean(); + iPBar.Clean(); + } + + // + result = ArraySize(rejections); + + // + return result; + } + + // + datetime DetectNearestCloseOverX3MAFast( + XOHCL &bar, + int maxAllowedBars = 20 // + ) + { + // + datetime result = NULL; + + // + if (!bar.IsValid()) + { + return result; + } + + // + bool has = false; + int idx = bar.Index(); + int start = idx; + int end = start + maxAllowedBars; + bool canContinue = true; + while (canContinue) + { + // + XOHCL iBar; + has = iBar.Init( + bar.symbol, + bar.period, + start // + ); + if (!has) + { + // + iBar.Clean(); + break; + } + + // + double iFast = mX121Helper + .x3maHelper + .GetX3MaFast(start); + + // + has = iBar.close > iFast && + iBar.open < iFast; + if (has) + { + result = iBar.time; + } + + // + canContinue = + start < end && + !IsValid(result); + + // + start++; + + // + iBar.Clean(); + } + + // + return result; + } + + // + datetime DetectNearestCloseUnderX3MAFast( + XOHCL &bar, + int maxAllowedBars = 20 // + ) + { + // + datetime result = NULL; + + // + if (!bar.IsValid()) + { + return result; + } + + // + bool has = false; + int idx = bar.Index(); + int start = idx; + int end = start + maxAllowedBars; + bool canContinue = true; + while (canContinue) + { + // + XOHCL iBar; + has = iBar.Init( + bar.symbol, + bar.period, + start // + ); + if (!has) + { + // + iBar.Clean(); + break; + } + + // + double iFast = mX121Helper + .x3maHelper + .GetX3MaFast(start); + + // + has = iBar.close < iFast && + iBar.open > iFast; + if (has) + { + result = iBar.time; + } + + // + canContinue = + start < end && + !IsValid(result); + + // + start++; + + // + iBar.Clean(); + } + + // + return result; + } + + // + // Virtuals ... + + /** + * Set Default Properties Values ... + */ + virtual void Default() + { + } + + // + protected: + // + + // + private: + // + // Props ... + string mSymbol; + ENUM_TIMEFRAMES mPeriod; + + // + // Actions ... + + /** + * Release All Resources ... + */ + void DeInit() + { + // + ZeroMemory(mX121Helper); + ZeroMemory(mPOIDetector); + ZeroMemory(mBarAnalyser); + + // + delete mX121Helper; + delete mPOIDetector; + delete mBarAnalyser; + } + + /** + * Apply Chart Style ... + */ + void ApplyChartStyle() + { + // + // Retrieve Current Chart ID ... + long chartId = ChartID(); + + // + 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 = true; // 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 + + // + ChartSetInteger(chartId, CHART_SHOW_BID_LINE, mShowBidLine); + ChartSetInteger(chartId, CHART_SHOW_ASK_LINE, mShowAskLine); + ChartSetInteger(chartId, CHART_SHOW_GRID, mShowGrid); + ChartSetInteger(chartId, CHART_SHOW_VOLUMES, mShowVolumes); + ChartSetInteger(chartId, CHART_SHOW_TRADE_LEVELS, mShowTradeLevels); + ChartSetInteger(chartId, CHART_AUTOSCROLL, mAutoScroll); + ChartSetInteger(chartId, CHART_QUICK_NAVIGATION, mQuickNavigation); + ChartSetInteger(chartId, CHART_COLOR_FOREGROUND, mForeGroundColor); + ChartSetInteger(chartId, CHART_COLOR_BACKGROUND, mBackGroundColor); + ChartSetInteger(chartId, CHART_COLOR_GRID, mGridColor); + ChartSetInteger(chartId, CHART_COLOR_BID, mBidLineColor); + ChartSetInteger(chartId, CHART_COLOR_ASK, mAskLineColor); + ChartSetInteger(chartId, CHART_COLOR_STOP_LEVEL, mStopColor); + ChartSetInteger(chartId, CHART_COLOR_VOLUME, mVolumesColor); + + // + // For Enabling XCC ... + // ChartSetInteger(chartId, CHART_MODE, mMode); + // ChartSetInteger(chartId, CHART_COLOR_CHART_UP, mUpColor); + // ChartSetInteger(chartId, CHART_COLOR_CHART_DOWN, mDownColor); + // ChartSetInteger(chartId, CHART_COLOR_CANDLE_BULL, mBullishColor); + // ChartSetInteger(chartId, CHART_COLOR_CANDLE_BEAR, mBearishColor); + // ChartSetInteger(chartId, CHART_COLOR_CHART_LINE, mLineColor); + } + + // +}; + +// +// Signal Provider Data ... +struct X121SMCStrategySignalProviderData +{ + // + // Props ... + + // + // Trigger ... + XPOIState triggerState; + double triggerBullishScore; + double triggerBearishScore; + X121Conditions triggerXConditions; + ENUM_XPOI_EVENTS triggerPoiEvents[]; + XC121SMCCycleHelper *triggerCycleHelper; + ENUM_X_CYCLE_EVENTS triggerCycleEvents[]; + X121SMCCycleConditions triggerConditions; + + // + // Decision ... + XPOIState decisionState; + double decisionBullishScore; + double decisionBearishScore; + X121Conditions decisionXConditions; + ENUM_XPOI_EVENTS decisionPoiEvents[]; + XC121SMCCycleHelper *decisionCycleHelper; + ENUM_X_CYCLE_EVENTS decisionCycleEvents[]; + X121SMCCycleConditions decisionConditions; + + // + // Analyse ... + XPOIState analyseState; + double analyseBullishScore; + double analyseBearishScore; + X121Conditions analyseXConditions; + ENUM_XPOI_EVENTS analysePoiEvents[]; + XC121SMCCycleHelper *analyseCycleHelper; + ENUM_X_CYCLE_EVENTS analyseCycleEvents[]; + X121SMCCycleConditions analyseConditions; + + // + // Verification ... + XPOIState verificationState; + double verificationBullishScore; + double verificationBearishScore; + X121Conditions verificationXConditions; + ENUM_XPOI_EVENTS verificationPoiEvents[]; + XC121SMCCycleHelper *verificationCycleHelper; + ENUM_X_CYCLE_EVENTS verificationCycleEvents[]; + X121SMCCycleConditions verificationConditions; + + // + // Consolidation ... + XPOIState consolidationState; + double consolidationBullishScore; + double consolidationBearishScore; + X121Conditions consolidationXConditions; + ENUM_XPOI_EVENTS consolidationPoiEvents[]; + XC121SMCCycleHelper *consolidationCycleHelper; + ENUM_X_CYCLE_EVENTS consolidationCycleEvents[]; + X121SMCCycleConditions consolidationConditions; + + // + // Vision ... + XPOIState visionState; + double visionBullishScore; + double visionBearishScore; + X121Conditions visionXConditions; + ENUM_XPOI_EVENTS visionPoiEvents[]; + XC121SMCCycleHelper *visionCycleHelper; + ENUM_X_CYCLE_EVENTS visionCycleEvents[]; + X121SMCCycleConditions visionConditions; + + // + // Constructor ... + X121SMCStrategySignalProviderData() + { + Clean(); + } + + // + // Tools ... + + // + // Cleanup ... + void Clean() + { + // + // Trigger ... + triggerState.Clean(); + triggerBullishScore = 0; + triggerBearishScore = 0; + Clean(triggerPoiEvents); + Clean(triggerCycleEvents); + triggerConditions.Clean(); + triggerXConditions.Clean(); + + // + // Decision ... + decisionState.Clean(); + decisionBullishScore = 0; + decisionBearishScore = 0; + Clean(decisionPoiEvents); + Clean(decisionCycleEvents); + decisionConditions.Clean(); + decisionXConditions.Clean(); + + // + // Analyse ... + analyseState.Clean(); + analyseBullishScore = 0; + analyseBearishScore = 0; + Clean(analysePoiEvents); + Clean(analyseCycleEvents); + analyseConditions.Clean(); + analyseXConditions.Clean(); + + // + // Verification ... + verificationState.Clean(); + verificationBullishScore = 0; + verificationBearishScore = 0; + Clean(verificationPoiEvents); + Clean(verificationCycleEvents); + verificationConditions.Clean(); + verificationXConditions.Clean(); + + // + // Consolidation ... + consolidationState.Clean(); + consolidationBullishScore = 0; + consolidationBearishScore = 0; + Clean(consolidationPoiEvents); + Clean(consolidationCycleEvents); + consolidationConditions.Clean(); + consolidationXConditions.Clean(); + + // + // Vision ... + visionState.Clean(); + visionBullishScore = 0; + visionBearishScore = 0; + Clean(visionPoiEvents); + Clean(visionCycleEvents); + visionConditions.Clean(); + visionXConditions.Clean(); + } + + // + void Destroy() + { + // + Clean(); + + // + ZeroMemory(visionCycleHelper); + ZeroMemory(triggerCycleHelper); + ZeroMemory(analyseCycleHelper); + ZeroMemory(decisionCycleHelper); + ZeroMemory(verificationCycleHelper); + ZeroMemory(consolidationCycleHelper); + + // + ZeroMemory(this); + } + + // + bool IsValid() + { + // + bool result = false; + + // + result = + visionCycleHelper != NULL && + triggerCycleHelper != NULL && + analyseCycleHelper != NULL && + decisionCycleHelper != NULL && + verificationCycleHelper != NULL && + consolidationCycleHelper != NULL; + + // + return result; + } + + // + // Initialize ... + bool Init( + XC121SMCCycleHelper *_triggerCycleHelper, + XC121SMCCycleHelper *_decisionCycleHelper, + XC121SMCCycleHelper *_analyseCycleHelper, + XC121SMCCycleHelper *_verificationCycleHelper, + XC121SMCCycleHelper *_consolidationCycleHelper, + XC121SMCCycleHelper *_visionCycleHelper // + ) + { + // + bool result = false; + + // + // Validate Cycle Helpers ... + result = + // + _visionCycleHelper != NULL && + _triggerCycleHelper != NULL && + _analyseCycleHelper != NULL && + _decisionCycleHelper != NULL && + _verificationCycleHelper != NULL && + _consolidationCycleHelper != NULL + // + ; + if (!result) + { + return result; + } + + // + visionCycleHelper = _visionCycleHelper; + triggerCycleHelper = _triggerCycleHelper; + analyseCycleHelper = _analyseCycleHelper; + decisionCycleHelper = _decisionCycleHelper; + verificationCycleHelper = _verificationCycleHelper; + consolidationCycleHelper = _consolidationCycleHelper; + + // + result = IsValid(); + + // + return result; + } + + // + // Prepare all ... + bool Prepare( + int barIndex = 0, + int loopback = 10, + bool trigger = false, + bool decision = true, + bool analyse = true, + bool verification = false, + bool consolidation = true, + bool vision = true // + ) + { + // + bool result = false; + + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + if (loopback < 7) + { + loopback = 7; + } + + // + result = IsValid(); + if (!result) + { + return result; + } + + // + // Trigger ... + if (trigger) + { + // + result = triggerCycleHelper.GetConditions( + triggerCycleEvents, + triggerPoiEvents, + triggerConditions, + barIndex, + loopback // + ); + if (!result) + { + // + Clean(triggerPoiEvents); + Clean(triggerCycleEvents); + + // + triggerConditions.Clean(); + + // + return result; + } + } + + // + // Decision ... + if (decision) + { + // + result = decisionCycleHelper.GetConditions( + decisionCycleEvents, + decisionPoiEvents, + decisionConditions, + barIndex, + loopback // + ); + if (!result) + { + // + Clean(triggerPoiEvents); + Clean(decisionPoiEvents); + Clean(triggerCycleEvents); + triggerConditions.Clean(); + Clean(decisionCycleEvents); + decisionConditions.Clean(); + + // + return result; + } + } + + // + // Analyse ... + if (analyse) + { + // + result = analyseCycleHelper.GetConditions( + analyseCycleEvents, + analysePoiEvents, + analyseConditions, + barIndex, + loopback // + ); + if (!result) + { + // + Clean(triggerPoiEvents); + Clean(analysePoiEvents); + Clean(decisionPoiEvents); + Clean(triggerCycleEvents); + Clean(analyseCycleEvents); + triggerConditions.Clean(); + analyseConditions.Clean(); + Clean(decisionCycleEvents); + decisionConditions.Clean(); + + // + return result; + } + } + + // + // Verification ... + if (verification) + { + // + result = verificationCycleHelper.GetConditions( + verificationCycleEvents, + verificationPoiEvents, + verificationConditions, + barIndex, + loopback // + ); + if (!result) + { + // + Clean(triggerPoiEvents); + Clean(analysePoiEvents); + Clean(decisionPoiEvents); + Clean(triggerCycleEvents); + Clean(analyseCycleEvents); + triggerConditions.Clean(); + analyseConditions.Clean(); + Clean(decisionCycleEvents); + decisionConditions.Clean(); + Clean(verificationPoiEvents); + Clean(verificationCycleEvents); + verificationConditions.Clean(); + + // + return result; + } + } + + // + // Consolidation ... + if (consolidation) + { + // + result = consolidationCycleHelper.GetConditions( + consolidationCycleEvents, + consolidationPoiEvents, + consolidationConditions, + barIndex, + loopback // + ); + if (!result) + { + // + Clean(triggerPoiEvents); + Clean(analysePoiEvents); + Clean(decisionPoiEvents); + Clean(triggerCycleEvents); + Clean(analyseCycleEvents); + triggerConditions.Clean(); + analyseConditions.Clean(); + Clean(decisionCycleEvents); + decisionConditions.Clean(); + Clean(verificationPoiEvents); + Clean(consolidationPoiEvents); + Clean(verificationCycleEvents); + verificationConditions.Clean(); + Clean(consolidationCycleEvents); + consolidationConditions.Clean(); + + // + return result; + } + } + + // + // Vision ... + if (vision) + { + result = visionCycleHelper.GetConditions( + visionCycleEvents, + visionPoiEvents, + visionConditions, + barIndex, + loopback // + ); + if (!result) + { + // + Clean(visionPoiEvents); + Clean(triggerPoiEvents); + Clean(analysePoiEvents); + Clean(visionCycleEvents); + visionConditions.Clean(); + Clean(decisionPoiEvents); + Clean(triggerCycleEvents); + Clean(analyseCycleEvents); + triggerConditions.Clean(); + analyseConditions.Clean(); + Clean(decisionCycleEvents); + decisionConditions.Clean(); + Clean(verificationPoiEvents); + Clean(consolidationPoiEvents); + Clean(verificationCycleEvents); + verificationConditions.Clean(); + Clean(consolidationCycleEvents); + consolidationConditions.Clean(); + + // + return result; + } + } + + // + // Cycles POI States ... + visionState = visionConditions.state; + triggerState = triggerConditions.state; + analyseState = analyseConditions.state; + decisionState = decisionConditions.state; + verificationState = verificationConditions.state; + consolidationState = consolidationConditions.state; + + // + // Cycle X121Conditions ... + visionXConditions = visionConditions.x121Conditions; + triggerXConditions = triggerConditions.x121Conditions; + analyseXConditions = analyseConditions.x121Conditions; + decisionXConditions = decisionConditions.x121Conditions; + verificationXConditions = verificationConditions.x121Conditions; + consolidationXConditions = consolidationConditions.x121Conditions; + + // + // Trigger ... + triggerXConditions.GenerateScore( + triggerBullishScore, + triggerBearishScore // + ); + + // + // Decision ... + decisionXConditions.GenerateScore( + decisionBullishScore, + decisionBearishScore // + ); + + // + // Analyse ... + analyseXConditions.GenerateScore( + analyseBullishScore, + analyseBearishScore // + ); + + // + // Verification ... + verificationXConditions.GenerateScore( + verificationBullishScore, + verificationBearishScore // + ); + + // + // Consolidation ... + consolidationXConditions.GenerateScore( + consolidationBullishScore, + consolidationBearishScore // + ); + + // + // Vision ... + visionXConditions.GenerateScore( + visionBullishScore, + visionBearishScore // + ); + + // + return result; + } + + // + bool SelectCycle( + ENUM_X_CYCLES cycle, + XPOIState &cState, + XPOIStateEvents &cStateEvents, + X121Conditions &cXConditions, + XC121SMCCycleHelper *&cHelper, + X121SMCCycleConditions &cConditions // + ) + { + // + bool result = false; + + // + cState.Clean(); + ZeroMemory(cHelper); + cConditions.Clean(); + cStateEvents.Clean(); + cXConditions.Clean(); + + // + result = cycle != X_CYCLE_NONE; + if (!result) + { + return result; + } + + // + if (cycle == X_CYCLE_TRIGGER) + { + // + cState = triggerState; + cHelper = triggerCycleHelper; + cConditions = triggerConditions; + cXConditions = triggerXConditions; + cStateEvents.Init(triggerPoiEvents); + } + else if (cycle == X_CYCLE_DECISION) + { + // + cState = decisionState; + cHelper = decisionCycleHelper; + cConditions = decisionConditions; + cXConditions = decisionXConditions; + cStateEvents.Init(decisionPoiEvents); + } + else if (cycle == X_CYCLE_ANALYSE) + { + // + cState = analyseState; + cHelper = analyseCycleHelper; + cConditions = analyseConditions; + cXConditions = analyseXConditions; + cStateEvents.Init(analysePoiEvents); + } + else if (cycle == X_CYCLE_VERIFICATION) + { + // + cState = verificationState; + cHelper = verificationCycleHelper; + cConditions = verificationConditions; + cXConditions = verificationXConditions; + cStateEvents.Init(verificationPoiEvents); + } + else if (cycle == X_CYCLE_CONSOLIDATION) + { + // + cState = consolidationState; + cHelper = consolidationCycleHelper; + cConditions = consolidationConditions; + cXConditions = consolidationXConditions; + cStateEvents.Init(consolidationPoiEvents); + } + else if (cycle == X_CYCLE_VISION) + { + // + cState = visionState; + cHelper = visionCycleHelper; + cConditions = visionConditions; + cXConditions = visionXConditions; + cStateEvents.Init(visionPoiEvents); + } + + // + result = cState.IsValid() && + cHelper != NULL; + + // + return result; + } + + // + void MaxRequiredPOIs(int value) + { + // + if (!IsValid()) + { + return; + } + + // + visionCycleHelper.mPOIDetector.MaxRequiredPOIs(value); + analyseCycleHelper.mPOIDetector.MaxRequiredPOIs(value); + decisionCycleHelper.mPOIDetector.MaxRequiredPOIs(value); + consolidationCycleHelper.mPOIDetector.MaxRequiredPOIs(value); + } + + // + void MaxAllowedLoopbackForInit(int value) + { + // + if (!IsValid()) + { + return; + } + + // + visionCycleHelper.mPOIDetector.MaxAllowedLoopbackForInit(value); + analyseCycleHelper.mPOIDetector.MaxAllowedLoopbackForInit(value); + decisionCycleHelper.mPOIDetector.MaxAllowedLoopbackForInit(value); + consolidationCycleHelper.mPOIDetector.MaxAllowedLoopbackForInit(value); + } + + // +}; + +// +// Condition Parser ... +struct X121SMCStrategyConditionParser +{ + // + // Props ... + + // + // XSAR ... + + // + bool isSarBullishOverPeaksGoldenZone; + bool isSarSwitchedToBullishOverPeaksGoldenZone; + bool isSarBearishOverPeaksGoldenZone; + bool isSarSwitchedToBearishOverPeaksGoldenZone; + bool isSarBullishUnderValesGoldenZone; + bool isSarSwitchedToBullishUnderValesGoldenZone; + bool isSarBearishUnderValesGoldenZone; + bool isSarSwitchedToBearishUnderValesGoldenZone; + + // + // XMA ... + + // + bool isX3MaFastUnderValesGoldenZone; + bool isX3MaMidUnderValesGoldenZone; + bool isX3MaSlowUnderValesGoldenZone; + bool isX3MaFastCrossedUnderValesGoldenZone; + + // + bool isX3MaFastOverPeaksGoldenZone; + bool isX3MaMidOverPeaksGoldenZone; + bool isX3MaFastCrossedOverPeaksGoldenZone; + + // + bool isX3MaInsidePeaksGoldenZone; + bool isX3MaCrossedInsidePeaksGoldenZone; + bool isX3MaInsideValesGoldenZone; + bool isX3MaCrossedInsideValesGoldenZone; + + // + bool isX3MaBullishStateOverPeaksGoldenZone; + bool isX3MaBearishStateOverPeaksGoldenZone; + bool isX3MaSwitchedToBullishStateOverPeaksGoldenZone; + bool isX3MaSwitchedToBearishStateOverPeaksGoldenZone; + + // + bool isX3MaBullishOrderedOverPeaksGoldenZone; + bool isX3MaBearishOrderedOverPeaksGoldenZone; + bool isX3MaSwitchedToBullishOrderedOverPeaksGoldenZone; + bool isX3MaSwitchedToBearishOrderedOverPeaksGoldenZone; + + // + bool isX3MaBullishStateUnderValesGoldenZone; + bool isX3MaBearishStateUnderValesGoldenZone; + bool isX3MaSwitchedToBullishStateUnderValesGoldenZone; + bool isX3MaSwitchedToBearishStateUnderValesGoldenZone; + + // + bool isX3MaBullishOrderedUnderValesGoldenZone; + bool isX3MaBearishOrderedUnderValesGoldenZone; + bool isX3MaSwitchedToBullishOrderedUnderValesGoldenZone; + bool isX3MaSwitchedToBearishOrderedUnderValesGoldenZone; + + // + // XVWAP ... + + // + bool isVWapFastUnderValesGoldenZone; + bool isVWapMidUnderValesGoldenZone; + bool isVWapFastCrossedUnderValesGoldenZone; + + // + bool isVWapFastOverPeaksGoldenZone; + bool isVWapMidOverPeaksGoldenZone; + bool isVWapFastCrossedOverPeaksGoldenZone; + + // + bool isVWapInsidePeaksGoldenZone; + bool isVWapCrossedInsidePeaksGoldenZone; + bool isVWapInsideValesGoldenZone; + bool isVWapCrossedInsideValesGoldenZone; + + // + bool isVWapBullishStateOverPeaksGoldenZone; + bool isVWapBearishStateOverPeaksGoldenZone; + bool isVWapSwitchedToBullishStateOverPeaksGoldenZone; + bool isVWapSwitchedToBearishStateOverPeaksGoldenZone; + + // + bool isVWapBullishOrderedOverPeaksGoldenZone; + bool isVWapBearishOrderedOverPeaksGoldenZone; + bool isVWapSwitchedToBullishOrderedOverPeaksGoldenZone; + bool isVWapSwitchedToBearishOrderedOverPeaksGoldenZone; + + // + bool isVWapBullishStateUnderValesGoldenZone; + bool isVWapBearishStateUnderValesGoldenZone; + bool isVWapSwitchedToBullishStateUnderValesGoldenZone; + bool isVWapSwitchedToBearishStateUnderValesGoldenZone; + + // + bool isVWapBullishOrderedUnderValesGoldenZone; + bool isVWapBearishOrderedUnderValesGoldenZone; + bool isVWapSwitchedToBullishOrderedUnderValesGoldenZone; + bool isVWapSwitchedToBearishOrderedUnderValesGoldenZone; + + // + // XHK ... + + // + // XRWHK ... + + // + bool isRawHKBearishOverPeaksGoldenZone; + bool isRawHKSwitchedToBearishOverPeaksGoldenZone; + bool isRawHKBullishUnderValesGoldenZone; + bool isRawHKSwitchedToBullishUnderValesGoldenZone; + + // + // XSMHK ... + + // + bool isSMHKBearishOverPeaksGoldenZone; + bool isSMHKSwitchedToBearishOverPeaksGoldenZone; + bool isSMHKBullishUnderValesGoldenZone; + bool isSMHKSwitchedToBullishUnderValesGoldenZone; + + // + // XATR ... + + // + bool isAtrUpperOverPeaksGoldenZone; + bool isAtrLowerOverPeaksGoldenZone; + bool isAtrOverPeaksGoldenZone; + bool isAtrCrossedOverPeaksGoldenZone; + + // + bool isAtrUpperUnderValesGoldenZone; + bool isAtrLowerUnderValesGoldenZone; + bool isAtrUnderValesGoldenZone; + bool isAtrCrossedUnderValesGoldenZone; + + // + // XSTR ... + + // + bool isStrBullishOverPeaksGoldenZone; + bool isStrBearishOverPeaksGoldenZone; + bool isStrSwitchedToBullishOverPeaksGoldenZone; + bool isStrSwitchedToBearishOverPeaksGoldenZone; + + // + bool isStrBullishUnderValesGoldenZone; + bool isStrBearishUnderValesGoldenZone; + bool isStrSwitchedToBullishUnderValesGoldenZone; + bool isStrSwitchedToBearishUnderValesGoldenZone; + + // + // XCHE ... + + // + bool isCheBullishOverPeaksGoldenZone; + bool isCheBearishOverPeaksGoldenZone; + bool isCheSwitchedBullishOverPeaksGoldenZone; + bool isCheSwitchedBearishOverPeaksGoldenZone; + + // + bool isCheBullishUnderValesGoldenZone; + bool isCheBearishUnderValesGoldenZone; + bool isCheSwitchedBullishUnderValesGoldenZone; + bool isCheSwitchedBearishUnderValesGoldenZone; + + // + // Constructor ... + X121SMCStrategyConditionParser() + { + Clean(); + } + + // + // Tools ... + + // + void Clean() + { + // + // XSAR ... + + // + isSarBullishOverPeaksGoldenZone = false; + isSarSwitchedToBullishOverPeaksGoldenZone = false; + isSarBearishOverPeaksGoldenZone = false; + isSarSwitchedToBearishOverPeaksGoldenZone = false; + isSarBullishUnderValesGoldenZone = false; + isSarSwitchedToBullishUnderValesGoldenZone = false; + isSarBearishUnderValesGoldenZone = false; + isSarSwitchedToBearishUnderValesGoldenZone = false; + + // + // X3MA ... + + // + isX3MaFastUnderValesGoldenZone = false; + isX3MaFastCrossedUnderValesGoldenZone = false; + isX3MaFastOverPeaksGoldenZone = false; + isX3MaFastCrossedOverPeaksGoldenZone = false; + + // + isX3MaInsidePeaksGoldenZone = false; + isX3MaCrossedInsidePeaksGoldenZone = false; + isX3MaInsideValesGoldenZone = false; + isX3MaCrossedInsideValesGoldenZone = false; + + // + isX3MaBullishStateOverPeaksGoldenZone = false; + isX3MaBearishStateOverPeaksGoldenZone = false; + isX3MaSwitchedToBullishStateOverPeaksGoldenZone = false; + isX3MaSwitchedToBearishStateOverPeaksGoldenZone = false; + + // + isX3MaBullishOrderedOverPeaksGoldenZone = false; + isX3MaBearishOrderedOverPeaksGoldenZone = false; + isX3MaSwitchedToBullishOrderedOverPeaksGoldenZone = false; + isX3MaSwitchedToBearishOrderedOverPeaksGoldenZone = false; + + // + isX3MaBullishStateUnderValesGoldenZone = false; + isX3MaBearishStateUnderValesGoldenZone = false; + isX3MaSwitchedToBullishStateUnderValesGoldenZone = false; + isX3MaSwitchedToBearishStateUnderValesGoldenZone = false; + + // + isX3MaBullishOrderedUnderValesGoldenZone = false; + isX3MaBearishOrderedUnderValesGoldenZone = false; + isX3MaSwitchedToBullishOrderedUnderValesGoldenZone = false; + isX3MaSwitchedToBearishOrderedUnderValesGoldenZone = false; + + // + // XVWAP ... + + // + isVWapFastUnderValesGoldenZone = false; + isVWapMidUnderValesGoldenZone = false; + isVWapFastCrossedUnderValesGoldenZone = false; + + // + isVWapFastOverPeaksGoldenZone = false; + isVWapMidOverPeaksGoldenZone = false; + isVWapFastCrossedOverPeaksGoldenZone = false; + + // + isVWapInsidePeaksGoldenZone = false; + isVWapCrossedInsidePeaksGoldenZone = false; + isVWapInsideValesGoldenZone = false; + isVWapCrossedInsideValesGoldenZone = false; + + // + isVWapBullishStateOverPeaksGoldenZone = false; + isVWapBearishStateOverPeaksGoldenZone = false; + isVWapSwitchedToBullishStateOverPeaksGoldenZone = false; + isVWapSwitchedToBearishStateOverPeaksGoldenZone = false; + + // + isVWapBullishOrderedOverPeaksGoldenZone = false; + isVWapBearishOrderedOverPeaksGoldenZone = false; + isVWapSwitchedToBullishOrderedOverPeaksGoldenZone = false; + isVWapSwitchedToBearishOrderedOverPeaksGoldenZone = false; + + // + isVWapBullishStateUnderValesGoldenZone = false; + isVWapBearishStateUnderValesGoldenZone = false; + isVWapSwitchedToBullishStateUnderValesGoldenZone = false; + isVWapSwitchedToBearishStateUnderValesGoldenZone = false; + + // + isVWapBullishOrderedUnderValesGoldenZone = false; + isVWapBearishOrderedUnderValesGoldenZone = false; + isVWapSwitchedToBullishOrderedUnderValesGoldenZone = false; + isVWapSwitchedToBearishOrderedUnderValesGoldenZone = false; + + // + // XHK ... + + // + // XRWHK ... + + // + isRawHKBearishOverPeaksGoldenZone = false; + isRawHKSwitchedToBearishOverPeaksGoldenZone = false; + isRawHKBullishUnderValesGoldenZone = false; + isRawHKSwitchedToBullishUnderValesGoldenZone = false; + + // + // XSMHK ... + + // + isSMHKBearishOverPeaksGoldenZone = false; + isSMHKSwitchedToBearishOverPeaksGoldenZone = false; + isSMHKBullishUnderValesGoldenZone = false; + isSMHKSwitchedToBullishUnderValesGoldenZone = false; + + // + // XATR ... + + // + isAtrUpperOverPeaksGoldenZone = false; + isAtrLowerOverPeaksGoldenZone = false; + isAtrOverPeaksGoldenZone = false; + isAtrCrossedOverPeaksGoldenZone = false; + + // + isAtrUpperUnderValesGoldenZone = false; + isAtrLowerUnderValesGoldenZone = false; + isAtrUnderValesGoldenZone = false; + isAtrCrossedUnderValesGoldenZone = false; + + // + // XSTR ... + + // + isStrBullishOverPeaksGoldenZone = false; + isStrBearishOverPeaksGoldenZone = false; + isStrSwitchedToBullishOverPeaksGoldenZone = false; + isStrSwitchedToBearishOverPeaksGoldenZone = false; + + // + isStrBullishUnderValesGoldenZone = false; + isStrBearishUnderValesGoldenZone = false; + isStrSwitchedToBullishUnderValesGoldenZone = false; + isStrSwitchedToBearishUnderValesGoldenZone = false; + + // + // XCHE ... + + // + isCheBullishOverPeaksGoldenZone = false; + isCheBearishOverPeaksGoldenZone = false; + isCheSwitchedBullishOverPeaksGoldenZone = false; + isCheSwitchedBearishOverPeaksGoldenZone = false; + + // + isCheBullishUnderValesGoldenZone = false; + isCheBearishUnderValesGoldenZone = false; + isCheSwitchedBullishUnderValesGoldenZone = false; + isCheSwitchedBearishUnderValesGoldenZone = false; + + // + ZeroMemory(this); + } + + // + void Parse( + X121Conditions &conditions // + ) + { + // + Clean(); + + // + // + int zIDX = 0; + int cIDX = zIDX + 1; + int pIDX = cIDX + 1; + + // + // XSAR ... + + // + isSarBullishOverPeaksGoldenZone = + conditions.isSarBullish && + conditions.sarBuffer[cIDX] > conditions.peaksGoldenBuffer[cIDX]; + + // + isSarSwitchedToBullishOverPeaksGoldenZone = + conditions.isSarSwitchedToBullish && + conditions.sarBuffer[cIDX] > conditions.peaksGoldenBuffer[cIDX]; + + // + isSarBearishOverPeaksGoldenZone = + conditions.isSarBearish && + conditions.sarBuffer[cIDX] > conditions.peaksGoldenBuffer[cIDX]; + + // + isSarSwitchedToBearishOverPeaksGoldenZone = + conditions.isSarSwitchedToBearish && + conditions.sarBuffer[cIDX] > conditions.peaksGoldenBuffer[cIDX]; + + // + isSarBullishUnderValesGoldenZone = + conditions.isSarBullish && + conditions.sarBuffer[cIDX] < conditions.valesGoldenBuffer[cIDX]; + + // + isSarSwitchedToBullishUnderValesGoldenZone = + conditions.isSarSwitchedToBullish && + conditions.sarBuffer[cIDX] < conditions.valesGoldenBuffer[cIDX]; + + // + isSarBearishUnderValesGoldenZone = + conditions.isSarBearish && + conditions.sarBuffer[cIDX] < conditions.valesGoldenBuffer[cIDX]; + + // + isSarSwitchedToBearishUnderValesGoldenZone = + conditions.isSarSwitchedToBearish && + conditions.sarBuffer[cIDX] < conditions.valesGoldenBuffer[cIDX]; + + // + // X3MA ... + + // + isX3MaFastUnderValesGoldenZone = + conditions.x3maFastBuffer[cIDX] < conditions.valesGoldenBuffer[cIDX]; + + // + isX3MaFastCrossedUnderValesGoldenZone = + isX3MaFastUnderValesGoldenZone && + conditions.x3maFastBuffer[pIDX] >= conditions.valesGoldenBuffer[pIDX]; + + // + isX3MaFastOverPeaksGoldenZone = + conditions.x3maFastBuffer[cIDX] > conditions.peaksGoldenBuffer[cIDX]; + + // + isX3MaFastCrossedOverPeaksGoldenZone = + isX3MaFastOverPeaksGoldenZone && + conditions.x3maFastBuffer[pIDX] <= conditions.peaksGoldenBuffer[pIDX]; + + // + isX3MaInsidePeaksGoldenZone = + // + conditions.x3maMin < conditions.peaksBuffer[cIDX] && + conditions.x3maMin > conditions.peaksGoldenBuffer[cIDX] && + // + conditions.x3maMax < conditions.peaksBuffer[cIDX] && + conditions.x3maMax > conditions.peaksGoldenBuffer[cIDX] + // + ; + + // + isX3MaCrossedInsidePeaksGoldenZone = + isX3MaInsidePeaksGoldenZone && + !( + // + conditions.x3maMin < conditions.peaksBuffer[pIDX] && + conditions.x3maMin > conditions.peaksGoldenBuffer[pIDX] && + // + conditions.x3maMax < conditions.peaksBuffer[pIDX] && + conditions.x3maMax > conditions.peaksGoldenBuffer[pIDX] + // + ); + + // + isX3MaInsideValesGoldenZone = + // + conditions.x3maMin > conditions.valesBuffer[cIDX] && + conditions.x3maMin < conditions.valesGoldenBuffer[cIDX] && + // + conditions.x3maMax > conditions.valesBuffer[cIDX] && + conditions.x3maMax < conditions.valesGoldenBuffer[cIDX] + // + ; + + isX3MaCrossedInsideValesGoldenZone = + isX3MaInsideValesGoldenZone && + !( + // + conditions.x3maMin > conditions.valesBuffer[pIDX] && + conditions.x3maMin < conditions.valesGoldenBuffer[pIDX] && + // + conditions.x3maMax > conditions.valesBuffer[pIDX] && + conditions.x3maMax < conditions.valesGoldenBuffer[pIDX] + // + ); + + // + isX3MaBullishStateOverPeaksGoldenZone = + isX3MaInsidePeaksGoldenZone && + conditions.isX3MaBullishState; + + // + isX3MaBearishStateOverPeaksGoldenZone = + isX3MaInsidePeaksGoldenZone && + conditions.isX3MaBearishState; + + // + isX3MaSwitchedToBullishStateOverPeaksGoldenZone = + isX3MaInsidePeaksGoldenZone && + conditions.isX3MaSwitchedToBullishState; + + // + isX3MaSwitchedToBearishStateOverPeaksGoldenZone = + isX3MaInsidePeaksGoldenZone && + conditions.isX3MaSwitchedToBearishState; + + // + isX3MaBullishOrderedOverPeaksGoldenZone = + isX3MaInsidePeaksGoldenZone && + conditions.isX3MaBullishOrdered; + + // + isX3MaBearishOrderedOverPeaksGoldenZone = + isX3MaInsidePeaksGoldenZone && + conditions.isX3MaBearishOrdered; + + // + isX3MaSwitchedToBullishOrderedOverPeaksGoldenZone = + isX3MaInsidePeaksGoldenZone && + conditions.isX3MaSwitchedToBullishOrdered; + + // + isX3MaSwitchedToBearishOrderedOverPeaksGoldenZone = + isX3MaInsidePeaksGoldenZone && + conditions.isX3MaSwitchedToBearishOrdered; + + // + isX3MaBullishStateUnderValesGoldenZone = + isX3MaInsideValesGoldenZone && + conditions.isX3MaBullishState; + + // + isX3MaBearishStateUnderValesGoldenZone = + isX3MaInsideValesGoldenZone && + conditions.isX3MaBearishState; + + // + isX3MaSwitchedToBullishStateUnderValesGoldenZone = + isX3MaInsideValesGoldenZone && + conditions.isX3MaSwitchedToBullishState; + + // + isX3MaSwitchedToBearishStateUnderValesGoldenZone = + isX3MaInsideValesGoldenZone && + conditions.isX3MaSwitchedToBearishState; + + // + isX3MaBullishOrderedUnderValesGoldenZone = + isX3MaInsideValesGoldenZone && + conditions.isX3MaBullishOrdered; + + // + isX3MaBearishOrderedUnderValesGoldenZone = + isX3MaInsideValesGoldenZone && + conditions.isX3MaBearishOrdered; + + // + isX3MaSwitchedToBullishOrderedUnderValesGoldenZone = + isX3MaInsideValesGoldenZone && + conditions.isX3MaSwitchedToBullishOrdered; + + // + isX3MaSwitchedToBearishOrderedUnderValesGoldenZone = + isX3MaInsideValesGoldenZone && + conditions.isX3MaSwitchedToBearishOrdered; + + // + // XVWAP ... + + // + isVWapFastUnderValesGoldenZone = + conditions.vwapFastBuffer[cIDX] < conditions.valesGoldenBuffer[cIDX]; + + // + isVWapMidUnderValesGoldenZone = + conditions.vwapMidBuffer[cIDX] < conditions.valesGoldenBuffer[cIDX]; + + // + isVWapFastCrossedUnderValesGoldenZone = + isVWapFastUnderValesGoldenZone && + conditions.vwapFastBuffer[pIDX] >= conditions.valesGoldenBuffer[pIDX]; + + // + isVWapFastOverPeaksGoldenZone = + conditions.vwapFastBuffer[cIDX] > conditions.peaksGoldenBuffer[cIDX]; + + // + isVWapMidOverPeaksGoldenZone = + conditions.vwapFastBuffer[cIDX] > conditions.peaksGoldenBuffer[cIDX]; + + // + isVWapFastCrossedOverPeaksGoldenZone = + isVWapFastOverPeaksGoldenZone && + conditions.vwapFastBuffer[pIDX] <= conditions.peaksGoldenBuffer[pIDX]; + + // + isVWapInsidePeaksGoldenZone = + // + conditions.vwapMin < conditions.peaksBuffer[cIDX] && + conditions.vwapMin > conditions.peaksGoldenBuffer[cIDX] && + // + conditions.vwapMax < conditions.peaksBuffer[cIDX] && + conditions.vwapMax > conditions.peaksGoldenBuffer[cIDX] + // + ; + + // + isVWapCrossedInsidePeaksGoldenZone = + isVWapInsidePeaksGoldenZone && + !( + // + conditions.vwapMin < conditions.peaksBuffer[pIDX] && + conditions.vwapMin > conditions.peaksGoldenBuffer[pIDX] && + // + conditions.vwapMax < conditions.peaksBuffer[pIDX] && + conditions.vwapMax > conditions.peaksGoldenBuffer[pIDX] + // + ); + + // + isVWapInsideValesGoldenZone = + // + conditions.vwapMin > conditions.valesBuffer[cIDX] && + conditions.vwapMin < conditions.valesGoldenBuffer[cIDX] && + // + conditions.vwapMax > conditions.valesBuffer[cIDX] && + conditions.vwapMax < conditions.valesGoldenBuffer[cIDX] + // + ; + + // + isVWapCrossedInsideValesGoldenZone = + isVWapInsideValesGoldenZone && + !( + // + conditions.vwapMin > conditions.valesBuffer[pIDX] && + conditions.vwapMin < conditions.valesGoldenBuffer[pIDX] && + // + conditions.vwapMax > conditions.valesBuffer[pIDX] && + conditions.vwapMax < conditions.valesGoldenBuffer[pIDX] + // + ); + + // + isVWapBullishStateOverPeaksGoldenZone = + isVWapInsidePeaksGoldenZone && + conditions.isVWapBullishState; + + // + isVWapBearishStateOverPeaksGoldenZone = + isVWapInsidePeaksGoldenZone && + conditions.isVWapBearishState; + + // + isVWapSwitchedToBullishStateOverPeaksGoldenZone = + isVWapInsidePeaksGoldenZone && + conditions.isVWapSwitchedToBullishState; + + // + isVWapSwitchedToBearishStateOverPeaksGoldenZone = + isVWapInsidePeaksGoldenZone && + conditions.isVWapSwitchedToBearishState; + + // + isVWapBullishOrderedOverPeaksGoldenZone = + isVWapInsidePeaksGoldenZone && + conditions.isVWapBullishOrdered; + + // + isVWapBearishOrderedOverPeaksGoldenZone = + isVWapInsidePeaksGoldenZone && + conditions.isVWapBearishOrdered; + + // + isVWapSwitchedToBullishOrderedOverPeaksGoldenZone = + isVWapInsidePeaksGoldenZone && + conditions.isVWapSwitchedToBullishOrdered; + + // + isVWapSwitchedToBearishOrderedOverPeaksGoldenZone = + isVWapInsidePeaksGoldenZone && + conditions.isVWapSwitchedToBearishOrdered; + + // + isVWapBullishStateUnderValesGoldenZone = + isVWapInsideValesGoldenZone && + conditions.isVWapBullishState; + + // + isVWapBearishStateUnderValesGoldenZone = + isVWapInsideValesGoldenZone && + conditions.isVWapBearishState; + + // + isVWapSwitchedToBullishStateUnderValesGoldenZone = + isVWapInsideValesGoldenZone && + conditions.isVWapSwitchedToBullishState; + + // + isVWapSwitchedToBearishStateUnderValesGoldenZone = + isVWapInsideValesGoldenZone && + conditions.isVWapSwitchedToBearishState; + + // + isVWapBullishOrderedUnderValesGoldenZone = + isVWapInsideValesGoldenZone && + conditions.isVWapBullishOrdered; + + // + isVWapBearishOrderedUnderValesGoldenZone = + isVWapInsideValesGoldenZone && + conditions.isVWapBearishOrdered; + + // + isVWapSwitchedToBullishOrderedUnderValesGoldenZone = + isVWapInsideValesGoldenZone && + conditions.isVWapSwitchedToBullishOrdered; + + // + isVWapSwitchedToBearishOrderedUnderValesGoldenZone = + isVWapInsideValesGoldenZone && + conditions.isVWapSwitchedToBearishOrdered; + + // + // XHK ... + + // + // XRWHK ... + + // + isRawHKBearishOverPeaksGoldenZone = + conditions.isRawHKBearish && + conditions.xhkRawHighBuffer[cIDX] > conditions.peaksGoldenBuffer[cIDX]; + + // + isRawHKSwitchedToBearishOverPeaksGoldenZone = + conditions.isRawHKSwitchedToBearish && + conditions.xhkRawHighBuffer[cIDX] > conditions.peaksGoldenBuffer[cIDX]; + + // + isRawHKBullishUnderValesGoldenZone = + conditions.isRawHKBullish && + conditions.xhkRawLowBuffer[cIDX] < conditions.valesGoldenBuffer[cIDX]; + + // + isRawHKSwitchedToBullishUnderValesGoldenZone = + conditions.isRawHKSwitchedToBullish && + conditions.xhkRawLowBuffer[cIDX] < conditions.valesGoldenBuffer[cIDX]; + + // + // XSMHK ... + + // + isSMHKBearishOverPeaksGoldenZone = + conditions.isSMHKBearish && + conditions.xhkSMHighBuffer[cIDX] > conditions.peaksGoldenBuffer[cIDX]; + + // + isSMHKSwitchedToBearishOverPeaksGoldenZone = + conditions.isSMHKSwitchedToBearish && + conditions.xhkSMHighBuffer[cIDX] > conditions.peaksGoldenBuffer[cIDX]; + + // + isSMHKBullishUnderValesGoldenZone = + conditions.isSMHKBullish && + conditions.xhkSMLowBuffer[cIDX] < conditions.valesGoldenBuffer[cIDX]; + + // + isSMHKSwitchedToBullishUnderValesGoldenZone = + conditions.isSMHKSwitchedToBullish && + conditions.xhkSMLowBuffer[cIDX] < conditions.valesGoldenBuffer[cIDX]; + + // + // XATR ... + + // + isAtrUpperOverPeaksGoldenZone = + conditions.atrUpperBuffer[cIDX] < conditions.peaksBuffer[cIDX] && + conditions.atrUpperBuffer[cIDX] > conditions.peaksGoldenBuffer[cIDX]; + + // + isAtrLowerOverPeaksGoldenZone = + conditions.atrLowerBuffer[cIDX] < conditions.peaksBuffer[cIDX] && + conditions.atrLowerBuffer[cIDX] > conditions.peaksGoldenBuffer[cIDX]; + + // + isAtrOverPeaksGoldenZone = + isAtrUpperOverPeaksGoldenZone && + isAtrLowerOverPeaksGoldenZone; + + // + isAtrCrossedOverPeaksGoldenZone = + isAtrOverPeaksGoldenZone && + !( + // + conditions.atrUpperBuffer[pIDX] < conditions.peaksBuffer[pIDX] && + conditions.atrUpperBuffer[pIDX] > conditions.peaksGoldenBuffer[pIDX] + // + && + // + conditions.atrLowerBuffer[pIDX] < conditions.peaksBuffer[pIDX] && + conditions.atrLowerBuffer[pIDX] > conditions.peaksGoldenBuffer[pIDX] + // + ); + + // + isAtrUpperUnderValesGoldenZone = + conditions.atrUpperBuffer[cIDX] > conditions.valesBuffer[cIDX] && + conditions.atrUpperBuffer[cIDX] < conditions.valesGoldenBuffer[cIDX]; + + // + isAtrLowerUnderValesGoldenZone = + conditions.atrLowerBuffer[cIDX] > conditions.valesBuffer[cIDX] && + conditions.atrLowerBuffer[cIDX] < conditions.valesGoldenBuffer[cIDX]; + + // + isAtrUnderValesGoldenZone = + isAtrUpperUnderValesGoldenZone && + isAtrLowerUnderValesGoldenZone; + + // + isAtrCrossedUnderValesGoldenZone = + isAtrUnderValesGoldenZone && + !( + // + conditions.atrUpperBuffer[pIDX] > conditions.valesBuffer[pIDX] && + conditions.atrUpperBuffer[pIDX] < conditions.valesGoldenBuffer[pIDX] + // + && + // + conditions.atrLowerBuffer[pIDX] > conditions.valesBuffer[pIDX] && + conditions.atrLowerBuffer[pIDX] < conditions.valesGoldenBuffer[pIDX] + // + ); + + // + // XSTR ... + + // + isStrBullishOverPeaksGoldenZone = + conditions.isStrBullish && + conditions.strBuffer[cIDX] < conditions.peaksBuffer[cIDX] && + conditions.strBuffer[cIDX] > conditions.peaksGoldenBuffer[cIDX]; + + // + isStrBearishOverPeaksGoldenZone = + conditions.isStrBearish && + conditions.strBuffer[cIDX] < conditions.peaksBuffer[cIDX] && + conditions.strBuffer[cIDX] > conditions.peaksGoldenBuffer[cIDX]; + + // + isStrSwitchedToBullishOverPeaksGoldenZone = + conditions.isStrSwitchedToBullish && + conditions.strBuffer[cIDX] < conditions.peaksBuffer[cIDX] && + conditions.strBuffer[cIDX] > conditions.peaksGoldenBuffer[cIDX]; + + // + isStrSwitchedToBearishOverPeaksGoldenZone = + conditions.isStrSwitchedToBearish && + conditions.strBuffer[cIDX] < conditions.peaksBuffer[cIDX] && + conditions.strBuffer[cIDX] > conditions.peaksGoldenBuffer[cIDX]; + + // + isStrBullishUnderValesGoldenZone = + conditions.isStrBullish && + conditions.strBuffer[cIDX] > conditions.valesBuffer[cIDX] && + conditions.strBuffer[cIDX] < conditions.valesGoldenBuffer[cIDX]; + + // + isStrBearishUnderValesGoldenZone = + conditions.isStrBearish && + conditions.strBuffer[cIDX] > conditions.valesBuffer[cIDX] && + conditions.strBuffer[cIDX] < conditions.valesGoldenBuffer[cIDX]; + + // + isStrSwitchedToBullishUnderValesGoldenZone = + conditions.isStrSwitchedToBullish && + conditions.strBuffer[cIDX] > conditions.valesBuffer[cIDX] && + conditions.strBuffer[cIDX] < conditions.valesGoldenBuffer[cIDX]; + + // + isStrSwitchedToBearishUnderValesGoldenZone = + conditions.isStrSwitchedToBearish && + conditions.strBuffer[cIDX] > conditions.valesBuffer[cIDX] && + conditions.strBuffer[cIDX] < conditions.valesGoldenBuffer[cIDX]; + + // + // XCHE ... + + // + isCheBullishOverPeaksGoldenZone = + conditions.isCheBullish && + conditions.le1Buffer[cIDX] < conditions.peaksBuffer[cIDX] && + conditions.le1Buffer[cIDX] > conditions.peaksGoldenBuffer[cIDX] && + conditions.le2Buffer[cIDX] < conditions.peaksBuffer[cIDX] && + conditions.le2Buffer[cIDX] > conditions.peaksGoldenBuffer[cIDX]; + + // + isCheBearishOverPeaksGoldenZone = + conditions.isCheSwitchedToBullish && + conditions.se1Buffer[cIDX] < conditions.peaksBuffer[cIDX] && + conditions.se1Buffer[cIDX] > conditions.peaksGoldenBuffer[cIDX] && + conditions.se2Buffer[cIDX] < conditions.peaksBuffer[cIDX] && + conditions.se2Buffer[cIDX] > conditions.peaksGoldenBuffer[cIDX]; + + // + isCheSwitchedBullishOverPeaksGoldenZone = + conditions.isCheSwitchedToBullish && + conditions.le1Buffer[cIDX] < conditions.peaksBuffer[cIDX] && + conditions.le1Buffer[cIDX] > conditions.peaksGoldenBuffer[cIDX] && + conditions.le2Buffer[cIDX] < conditions.peaksBuffer[cIDX] && + conditions.le2Buffer[cIDX] > conditions.peaksGoldenBuffer[cIDX]; + + // + isCheSwitchedBearishOverPeaksGoldenZone = + conditions.isCheSwitchedToBearish && + conditions.se1Buffer[cIDX] < conditions.peaksBuffer[cIDX] && + conditions.se1Buffer[cIDX] > conditions.peaksGoldenBuffer[cIDX] && + conditions.se2Buffer[cIDX] < conditions.peaksBuffer[cIDX] && + conditions.se2Buffer[cIDX] > conditions.peaksGoldenBuffer[cIDX]; + + // + isCheBullishUnderValesGoldenZone = + conditions.isCheBullish && + conditions.cheMin > conditions.valesBuffer[cIDX] && + conditions.cheMin < conditions.valesGoldenBuffer[cIDX] && + conditions.cheMax > conditions.valesBuffer[cIDX] && + conditions.cheMax < conditions.valesGoldenBuffer[cIDX]; + + // + isCheBearishUnderValesGoldenZone = + conditions.isCheBearish && + conditions.cheMin > conditions.valesBuffer[cIDX] && + conditions.cheMin < conditions.valesGoldenBuffer[cIDX] && + conditions.cheMax > conditions.valesBuffer[cIDX] && + conditions.cheMax < conditions.valesGoldenBuffer[cIDX]; + + // + isCheSwitchedBullishUnderValesGoldenZone = + conditions.isCheSwitchedToBullish && + conditions.cheMin > conditions.valesBuffer[cIDX] && + conditions.cheMin < conditions.valesGoldenBuffer[cIDX] && + conditions.cheMax > conditions.valesBuffer[cIDX] && + conditions.cheMax < conditions.valesGoldenBuffer[cIDX]; + + // + isCheSwitchedBearishUnderValesGoldenZone = + conditions.isCheSwitchedToBearish && + conditions.cheMin > conditions.valesBuffer[cIDX] && + conditions.cheMin < conditions.valesGoldenBuffer[cIDX] && + conditions.cheMax > conditions.valesBuffer[cIDX] && + conditions.cheMax < conditions.valesGoldenBuffer[cIDX]; + } + + // + // Rejected Boxes ... + bool HasRejectedBoxConditions( + ENUM_X_CYCLES cycle, + XSignalBox &box, + ENUM_X_DIRECTION &dir, + XSignalBox &waitingBoxes[], + X121SMCStrategySignalProviderData &provider, + int barIndex = 0 // + ) + { + // + bool result = false; + + // + box.Clean(); + dir = X_DIRECTION_NONE; + + // + // Checking Waiting Baoxes Exists ... + result = HasChild(waitingBoxes); + if (!result) + { + return result; + } + + // + // Fil Selected Data ... + XPOIState cState; + X121Conditions cXConditions; + XPOIStateEvents cStateEvents; + XC121SMCCycleHelper *cHelper; + X121SMCCycleConditions cConditions; + result = provider.SelectCycle( + cycle, + cState, + cStateEvents, + cXConditions, + cHelper, + cConditions // + ); + if (!result) + { + // + cState.Clean(); + ZeroMemory(cHelper); + cConditions.Clean(); + cXConditions.Clean(); + cStateEvents.Clean(); + + // + return result; + } + Parse(cXConditions); + + // + // Normalize Args ... + + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + int idx = -1; + int count = 0; + bool has = false; + + // + int zIDX = barIndex; + int cIDX = zIDX + 1; + int pIDX = cIDX + 1; + int ppIDX = pIDX + 1; + + // + bool isBullish = false; + bool isBearish = false; + + // + XOHCL zBar; + XOHCL cBar; + XOHCL pBar; + + // + // Initial Bars ... + result = zBar.Init( + cState.symbol, + cState.period, + barIndex // + ); + result = + result && + zBar.GetPreviousBar(cBar); + result = + result && + cBar.GetPreviousBar(pBar); + if (!result) + { + // + zBar.Clean(); + cBar.Clean(); + pBar.Clean(); + cState.Clean(); + ZeroMemory(cHelper); + cConditions.Clean(); + cXConditions.Clean(); + + // + return result; + } + + // + // Checking Bar Based on Positions State ... + ENUM_X_DIRECTION iBarPosDir; + bool isBarValidForDir = cHelper + .mBarAnalyser + .IsValidForPosition( + cBar, + iBarPosDir // + ); + bool isBarValidForBullish = + isBarValidForDir && + IsBullish(iBarPosDir); + bool isBarValidForBearish = + isBarValidForDir && + IsBearish(iBarPosDir); + + // + // Extract Selected Boxes ... + XBoxZone selectedBox; + XSignalBox iSignalBox; + count = ArraySize(waitingBoxes); + has = IsValidSize(count); + if (has) + { + // + for (int i = 0; i < count; i++) + { + // + XSignalBox iBox = waitingBoxes[i]; + + // + bool isBullish = iBox.ob.IsBullish(); + + // + bool isOBBullishRejected = + // + cBar.low < iBox.ob.upper && + cBar.GetDown() > iBox.ob.upper + // + ; + + // + bool isOBBearishRejected = + // + cBar.high > iBox.ob.lower && + cBar.GetUp() < iBox.ob.lower + // + ; + + // + has = + isBullish + ? isOBBullishRejected + : isOBBearishRejected; + + // + // Force Using OB ... + if (has) + { + // + iSignalBox = iBox; + if (!selectedBox.IsValid()) + { + selectedBox = iBox.ob; + } + iBox.Clean(); + break; + } + + // + iBox.Clean(); + } + } + result = + iSignalBox.IsValid() && + selectedBox.IsValid(); + if (!result) + { + // + zBar.Clean(); + cBar.Clean(); + pBar.Clean(); + cState.Clean(); + iSignalBox.Clean(); + selectedBox.Clean(); + ZeroMemory(cHelper); + cConditions.Clean(); + cXConditions.Clean(); + + // + return result; + } + + // + bool hasSignalBox = iSignalBox.IsValid(); + bool isSignalBoxBullish = IsBullish(iSignalBox.ob.dir); + + // + // Checking Other Conditions ... + bool isVWapSlowPassed = + isSignalBoxBullish + ? cXConditions.isVWapSlowBullish + : cXConditions.isVWapSlowBearish; + + // + // Bullish Conditions ... + isBullish = + // + // Base Condition ... + ( + // + hasSignalBox && + isVWapSlowPassed && + isSignalBoxBullish && + isBarValidForBullish + // + ) + // + ; + + // + // Bearish Conditions ... + isBearish = + // + // Base Condition ... + ( + // + hasSignalBox && + isVWapSlowPassed && + !isSignalBoxBullish && + isBarValidForBearish + // + ) + // + ; + + // + // Filling Requirements ... + result = + isBullish || + isBearish; + if (result) + { + // + dir = + isBullish + ? X_DIRECTION_BULLISH + : X_DIRECTION_BEARISH; + + // + box = iSignalBox; + box.UpdateTo(TimeCurrent()); + } + + // + // Check All Conditions ... + result = + box.IsValid() && + HasDirection(dir) && + (isBullish || + isBearish); + + // + // Cleanup Resources ... + zBar.Clean(); + cBar.Clean(); + pBar.Clean(); + cState.Clean(); + iSignalBox.Clean(); + selectedBox.Clean(); + ZeroMemory(cHelper); + cConditions.Clean(); + cStateEvents.Clean(); + cXConditions.Clean(); + + // + return result; + } + + // + // Activated Boxes ... + bool HasActivatedBoxConditions( + ENUM_X_CYCLES cycle, + XSignalBox &box, + ENUM_X_DIRECTION &dir, + XSignalBox &waitingBoxes[], + X121SMCStrategySignalProviderData &provider, + int barIndex = 0 // + ) + { + // + bool result = false; + + // + box.Clean(); + dir = X_DIRECTION_NONE; + + // + // Checking Waiting Baoxes Exists ... + result = HasChild(waitingBoxes); + if (!result) + { + return result; + } + + // + // Fil Selected Data ... + XPOIState cState; + X121Conditions cXConditions; + XPOIStateEvents cStateEvents; + XC121SMCCycleHelper *cHelper; + X121SMCCycleConditions cConditions; + result = provider.SelectCycle( + cycle, + cState, + cStateEvents, + cXConditions, + cHelper, + cConditions // + ); + if (!result) + { + // + cState.Clean(); + ZeroMemory(cHelper); + cConditions.Clean(); + cXConditions.Clean(); + cStateEvents.Clean(); + + // + return result; + } + Parse(cXConditions); + + // + // Normalize Args ... + + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + int idx = -1; + int count = 0; + bool has = false; + + // + int zIDX = barIndex; + int cIDX = zIDX + 1; + int pIDX = cIDX + 1; + int ppIDX = pIDX + 1; + + // + bool isBullish = false; + bool isBearish = false; + + // + XOHCL zBar; + XOHCL cBar; + XOHCL pBar; + + // + // Initial Bars ... + result = zBar.Init( + cState.symbol, + cState.period, + barIndex // + ); + result = + result && + zBar.GetPreviousBar(cBar); + result = + result && + cBar.GetPreviousBar(pBar); + if (!result) + { + // + zBar.Clean(); + cBar.Clean(); + pBar.Clean(); + cState.Clean(); + ZeroMemory(cHelper); + cConditions.Clean(); + cXConditions.Clean(); + + // + return result; + } + + // + // Checking Bar Based on Positions State ... + ENUM_X_DIRECTION iBarPosDir; + bool isBarValidForDir = cHelper + .mBarAnalyser + .IsValidForPosition( + cBar, + iBarPosDir // + ); + bool isBarValidForBullish = + isBarValidForDir && + IsBullish(iBarPosDir); + bool isBarValidForBearish = + isBarValidForDir && + IsBearish(iBarPosDir); + + // + // Extract Selected Boxes ... + XBoxZone selectedBox; + XSignalBox iSignalBox; + count = ArraySize(waitingBoxes); + has = IsValidSize(count); + if (has) + { + // + for (int i = 0; i < count; i++) + { + // + XSignalBox iBox = waitingBoxes[i]; + + // + bool isBullish = iBox.ob.IsBullish(); + + // + has = cBar.low < iBox.sharp.upper && + cBar.low > iBox.sharp.lower && + cBar.high > iBox.sharp.lower && + cBar.high < iBox.sharp.upper; + + // + // Force Using OB ... + if (has) + { + // + iSignalBox = iBox; + if (!selectedBox.IsValid()) + { + selectedBox = iBox.ob; + } + iBox.Clean(); + break; + } + + // + iBox.Clean(); + } + } + result = + iSignalBox.IsValid() && + selectedBox.IsValid(); + if (!result) + { + // + zBar.Clean(); + cBar.Clean(); + pBar.Clean(); + cState.Clean(); + iSignalBox.Clean(); + selectedBox.Clean(); + ZeroMemory(cHelper); + cConditions.Clean(); + cXConditions.Clean(); + + // + return result; + } + + // + bool hasSignalBox = iSignalBox.IsValid(); + bool isSignalBoxBullish = IsBullish(iSignalBox.ob.dir); + + // + // Checking Other Conditions ... + + // + // XVWAP ... + + // + bool isVWapSlopeBullish = + cXConditions.isVwapFastSlopeBullish && + cXConditions.isVwapMidSlopeBullish && + cXConditions.isVwapSlowSlopeBullish; + + // + bool isVWapSlopeBearish = + cXConditions.isVwapFastSlopeBearish && + cXConditions.isVwapMidSlopeBearish && + cXConditions.isVwapSlowSlopeBearish; + + // + bool isVWapBullishCondition = + (cXConditions.isVWapBullishOrdered && + cXConditions.isVWapSwitchedToBullishState) || + (cXConditions.isVWapBullishState && + cXConditions.isVWapSwitchedToBullishOrdered); + + // + bool isVWapBearishCondition = + (cXConditions.isVWapBearishOrdered && + cXConditions.isVWapSwitchedToBearishState) || + (cXConditions.isVWapBearishState && + cXConditions.isVWapSwitchedToBearishOrdered); + + // + // Bullish Conditions ... + isBullish = + // + // Base Condition ... + ( + // + hasSignalBox && + isSignalBoxBullish && + isVWapSlopeBullish && + isBarValidForBullish && + isVWapBullishCondition + // + ) + // + ; + + // + // Bearish Conditions ... + isBearish = + // + // Base Condition ... + ( + // + hasSignalBox && + isVWapSlopeBearish && + !isSignalBoxBullish && + isBarValidForBearish && + isVWapBearishCondition + // + ) + // + ; + + // + // Filling Requirements ... + result = + isBullish || + isBearish; + if (result) + { + // + dir = + isBullish + ? X_DIRECTION_BULLISH + : X_DIRECTION_BEARISH; + + // + box = iSignalBox; + box.UpdateTo(TimeCurrent()); + + // + // Provide TP/SL ... + + // + box.sl = isBullish + ? cXConditions.vwapMin + : cXConditions.vwapMax; + + // + box.tp = isBullish + ? box.sharp.upper + : box.sharp.lower; + } + + // + // Check All Conditions ... + result = + box.IsValid() && + HasDirection(dir) && + (isBullish || + isBearish); + + // + // Cleanup Resources ... + zBar.Clean(); + cBar.Clean(); + pBar.Clean(); + cState.Clean(); + iSignalBox.Clean(); + selectedBox.Clean(); + ZeroMemory(cHelper); + cConditions.Clean(); + cStateEvents.Clean(); + cXConditions.Clean(); + + // + return result; + } + + // + // Breaked Boxes ... + bool HasBreakedBoxConditions( + ENUM_X_CYCLES cycle, + XSignalBox &box, + ENUM_X_DIRECTION &dir, + XSignalBox &breakedBoxes[], + X121SMCStrategySignalProviderData &provider, + int barIndex = 0 // + ) + { + // + bool result = false; + + // + box.Clean(); + dir = X_DIRECTION_NONE; + + // + // Checking Waiting Baoxes Exists ... + result = HasChild(breakedBoxes); + if (!result) + { + return result; + } + + // + // Fil Selected Data ... + XPOIState cState; + X121Conditions cXConditions; + XPOIStateEvents cStateEvents; + XC121SMCCycleHelper *cHelper; + X121SMCCycleConditions cConditions; + result = provider.SelectCycle( + cycle, + cState, + cStateEvents, + cXConditions, + cHelper, + cConditions // + ); + if (!result) + { + // + cState.Clean(); + ZeroMemory(cHelper); + cConditions.Clean(); + cXConditions.Clean(); + cStateEvents.Clean(); + + // + return result; + } + Parse(cXConditions); + + // + // Normalize Args ... + + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + int idx = -1; + int count = 0; + bool has = false; + + // + int zIDX = barIndex; + int cIDX = zIDX + 1; + int pIDX = cIDX + 1; + int ppIDX = pIDX + 1; + + // + bool isBullish = false; + bool isBearish = false; + + // + XOHCL zBar; + XOHCL cBar; + XOHCL pBar; + + // + // Initial Bars ... + result = zBar.Init( + cState.symbol, + cState.period, + barIndex // + ); + result = + result && + zBar.GetPreviousBar(cBar); + result = + result && + cBar.GetPreviousBar(pBar); + if (!result) + { + // + zBar.Clean(); + cBar.Clean(); + pBar.Clean(); + cState.Clean(); + ZeroMemory(cHelper); + cConditions.Clean(); + cXConditions.Clean(); + + // + return result; + } + + // + // Checking Bar Based on Positions State ... + ENUM_X_DIRECTION iBarPosDir; + bool isBarValidForDir = cHelper + .mBarAnalyser + .IsValidForPosition( + cBar, + iBarPosDir // + ); + bool isBarValidForBullish = + isBarValidForDir && + IsBullish(iBarPosDir); + bool isBarValidForBearish = + isBarValidForDir && + IsBearish(iBarPosDir); + + // + // Extract Selected Boxes ... + XBoxZone selectedBox; + XSignalBox iSignalBox; + count = ArraySize(breakedBoxes); + has = IsValidSize(count); + if (has) + { + // + for (int i = 0; i < count; i++) + { + // + XSignalBox iBox = breakedBoxes[i]; + + // + bool isBullish = iBox.ob.IsBullish(); + + // + has = cBar.low < iBox.sharp.upper && + cBar.low > iBox.sharp.lower && + cBar.high > iBox.sharp.lower && + cBar.high < iBox.sharp.upper; + + // + // Force Using OB ... + if (has) + { + // + iSignalBox = iBox; + if (!selectedBox.IsValid()) + { + selectedBox = iBox.ob; + } + iBox.Clean(); + break; + } + + // + iBox.Clean(); + } + } + result = + iSignalBox.IsValid() && + selectedBox.IsValid(); + if (!result) + { + // + zBar.Clean(); + cBar.Clean(); + pBar.Clean(); + cState.Clean(); + iSignalBox.Clean(); + selectedBox.Clean(); + ZeroMemory(cHelper); + cConditions.Clean(); + cXConditions.Clean(); + + // + return result; + } + + // + bool hasSignalBox = iSignalBox.IsValid(); + bool isSignalBoxBullish = IsBullish(iSignalBox.ob.dir); + + // + // Checking Other Conditions ... + + // + // XVWAP ... + + // + bool isVWapSlopeBullish = + cXConditions.isVwapFastSlopeBullish && + cXConditions.isVwapMidSlopeBullish && + cXConditions.isVwapSlowSlopeBullish; + + // + bool isVWapSlopeBearish = + cXConditions.isVwapFastSlopeBearish && + cXConditions.isVwapMidSlopeBearish && + cXConditions.isVwapSlowSlopeBearish; + + // + bool isVWapBullishCondition = + (cXConditions.isVWapBullishOrdered && + cXConditions.isVWapSwitchedToBullishState) || + (cXConditions.isVWapBullishState && + cXConditions.isVWapSwitchedToBullishOrdered); + + // + bool isVWapBearishCondition = + (cXConditions.isVWapBearishOrdered && + cXConditions.isVWapSwitchedToBearishState) || + (cXConditions.isVWapBearishState && + cXConditions.isVWapSwitchedToBearishOrdered); + + // + // Bullish Conditions ... + isBullish = + // + // Base Condition ... + ( + // + hasSignalBox && + isSignalBoxBullish && + isVWapSlopeBullish && + isBarValidForBullish && + isVWapBullishCondition + // + ) + // + ; + + // + // Bearish Conditions ... + isBearish = + // + // Base Condition ... + ( + // + hasSignalBox && + isVWapSlopeBearish && + !isSignalBoxBullish && + isBarValidForBearish && + isVWapBearishCondition + // + ) + // + ; + + // + // Filling Requirements ... + result = + isBullish || + isBearish; + if (result) + { + // + dir = + isBullish + ? X_DIRECTION_BULLISH + : X_DIRECTION_BEARISH; + + // + box = iSignalBox; + box.UpdateTo(TimeCurrent()); + + // + // Provide TP/SL ... + + // + box.sl = isBullish + ? cXConditions.vwapMin + : cXConditions.vwapMax; + + // + box.tp = isBullish + ? box.sharp.upper + : box.sharp.lower; + } + + // + // Check All Conditions ... + result = + box.IsValid() && + HasDirection(dir) && + (isBullish || + isBearish); + + // + // Cleanup Resources ... + zBar.Clean(); + cBar.Clean(); + pBar.Clean(); + cState.Clean(); + iSignalBox.Clean(); + selectedBox.Clean(); + ZeroMemory(cHelper); + cConditions.Clean(); + cStateEvents.Clean(); + cXConditions.Clean(); + + // + return result; + } + + // + // XFVGMA ... + bool HasXFVGMAConditions( + ENUM_X_CYCLES cycle, + XSignalBox &box, + ENUM_X_DIRECTION &dir, + XSignalBox &waitingBoxes[], + X121SMCStrategySignalProviderData &provider, + int barIndex = 0 // + ) + { + // + bool result = false; + + // + box.Clean(); + dir = X_DIRECTION_NONE; + + // + result = HasChild(waitingBoxes); + if (!result) + { + return result; + } + + // + // Fil Selected Data ... + XPOIState cState; + X121Conditions cXConditions; + XPOIStateEvents cStateEvents; + XC121SMCCycleHelper *cHelper; + X121SMCCycleConditions cConditions; + result = provider.SelectCycle( + cycle, + cState, + cStateEvents, + cXConditions, + cHelper, + cConditions // + ); + if (!result) + { + // + cState.Clean(); + ZeroMemory(cHelper); + cConditions.Clean(); + cXConditions.Clean(); + cStateEvents.Clean(); + + // + return result; + } + Parse(cXConditions); + + // + // Normalize Args ... + + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + int idx = -1; + int count = 0; + bool has = false; + + // + int zIDX = barIndex; + int cIDX = zIDX + 1; + int pIDX = cIDX + 1; + int ppIDX = pIDX + 1; + + // + bool isBullish = false; + bool isBearish = false; + + // + XOHCL zBar; + XOHCL cBar; + XOHCL pBar; + + // + // Initial Bars ... + result = zBar.Init( + cState.symbol, + cState.period, + barIndex // + ); + result = + result && + zBar.GetPreviousBar(cBar); + result = + result && + cBar.GetPreviousBar(pBar); + if (!result) + { + // + zBar.Clean(); + cBar.Clean(); + pBar.Clean(); + cState.Clean(); + ZeroMemory(cHelper); + cConditions.Clean(); + cXConditions.Clean(); + + // + return result; + } + + // + // Select Waiting Box ... + XBoxZone selectedBox; + XSignalBox selectedSignalBox; + count = ArraySize(waitingBoxes); + for (int i = 0; i < count; i++) + { + // + XSignalBox iSBox = waitingBoxes[i]; + bool isBullish = iSBox.ob.IsBullish(); + + // + bool isInsidePassed = + isBullish + ? cBar.low < iSBox.ob.upper && + cBar.low > iSBox.ob.lower + : cBar.high > iSBox.ob.lower && + cBar.high < iSBox.ob.upper; + + // + bool isTypePassed = iSBox.sharp.type == "XSHPOBX"; + + // + has = isTypePassed && + isInsidePassed; + if (has) + { + // + selectedBox = iSBox.ob; + selectedSignalBox = iSBox; + break; + } + } + result = selectedBox.IsValid() && + selectedSignalBox.IsValid(); + if (!result) + { + // + zBar.Clean(); + cBar.Clean(); + pBar.Clean(); + cState.Clean(); + ZeroMemory(cHelper); + cConditions.Clean(); + selectedBox.Clean(); + cXConditions.Clean(); + selectedSignalBox.Clean(); + + // + return result; + } + + // + bool isSignalBoxBullish = selectedBox.IsBullish(); + + // + // Checking Other Conditions ... + + // + // Checking Bar Based on Positions State ... + ENUM_X_DIRECTION iBarPosDir; + bool isBarValidForDir = cHelper + .mBarAnalyser + .IsValidForPosition( + cBar, + iBarPosDir // + ); + bool isBarValidForBullish = + isBarValidForDir && + IsBullish(iBarPosDir); + bool isBarValidForBearish = + isBarValidForDir && + IsBearish(iBarPosDir); + + // + // Bullish Conditions ... + isBullish = + // + // Base Condition ... + ( + // + isSignalBoxBullish && + isBarValidForBullish + // + ) + // + ; + + // + // Bearish Conditions ... + isBearish = + // + // Base Condition ... + ( + // + !isSignalBoxBullish && + isBarValidForBearish + // + ) + // + ; + + // + // Filling Requirements ... + result = + isBullish || + isBearish; + if (result) + { + // + dir = + isBullish + ? X_DIRECTION_BULLISH + : X_DIRECTION_BEARISH; + + // + box = selectedSignalBox; + box.ob.to = TimeCurrent(); + } + + // + // Check All Conditions ... + result = + box.IsValid() && + HasDirection(dir) && + (isBullish || + isBearish); + + // + // Cleanup Resources ... + zBar.Clean(); + cBar.Clean(); + pBar.Clean(); + cState.Clean(); + selectedBox.Clean(); + ZeroMemory(cHelper); + cConditions.Clean(); + cStateEvents.Clean(); + cXConditions.Clean(); + selectedSignalBox.Clean(); + + // + return result; + } + + // + // XWPVZ ... + bool HasXWPVZConditions( + ENUM_X_CYCLES cycle, + XSignalBox &box, + ENUM_X_DIRECTION &dir, + X121SMCStrategySignalProviderData &provider, + int barIndex = 0 // + ) + { + // + bool result = false; + + // + box.Clean(); + dir = X_DIRECTION_NONE; + + // + // Fil Selected Data ... + XPOIState cState; + X121Conditions cXConditions; + XPOIStateEvents cStateEvents; + XC121SMCCycleHelper *cHelper; + X121SMCCycleConditions cConditions; + result = provider.SelectCycle( + cycle, + cState, + cStateEvents, + cXConditions, + cHelper, + cConditions // + ); + if (!result) + { + // + cState.Clean(); + ZeroMemory(cHelper); + cConditions.Clean(); + cXConditions.Clean(); + cStateEvents.Clean(); + + // + return result; + } + Parse(cXConditions); + + // + // Normalize Args ... + + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + int idx = -1; + int count = 0; + bool has = false; + + // + int zIDX = barIndex; + int cIDX = zIDX + 1; + int pIDX = cIDX + 1; + int ppIDX = pIDX + 1; + + // + bool isBullish = false; + bool isBearish = false; + + // + XOHCL zBar; + XOHCL cBar; + XOHCL pBar; + + // + // Initial Bars ... + result = zBar.Init( + cState.symbol, + cState.period, + barIndex // + ); + result = + result && + zBar.GetPreviousBar(cBar); + result = + result && + cBar.GetPreviousBar(pBar); + if (!result) + { + // + zBar.Clean(); + cBar.Clean(); + pBar.Clean(); + cState.Clean(); + ZeroMemory(cHelper); + cConditions.Clean(); + cXConditions.Clean(); + + // + return result; + } + + // + // Checking Other Conditions ... + + // + // Checking Bar Based on Positions State ... + ENUM_X_DIRECTION iBarPosDir; + bool isBarValidForDir = cHelper + .mBarAnalyser + .IsValidForPosition( + cBar, + iBarPosDir // + ); + bool isBarValidForBullish = + isBarValidForDir && + IsBullish(iBarPosDir); + bool isBarValidForBearish = + isBarValidForDir && + IsBearish(iBarPosDir); + + // + XCPOIDrawer *drawer = provider.visionCycleHelper.mPOIDrawer; + + if (result) + { + // + result = false; + Print("Salam"); + } + + // + // Bullish Conditions ... + isBullish = + // + // Base Condition ... + ( + // + false + // + ) + // + ; + + // + // Bearish Conditions ... + isBearish = + // + // Base Condition ... + ( + // + false + // + ) + // + ; + + // + // Filling Requirements ... + result = + isBullish || + isBearish; + if (result) + { + // + dir = + isBullish + ? X_DIRECTION_BULLISH + : X_DIRECTION_BEARISH; + + // + } + + // + // Check All Conditions ... + result = + box.IsValid() && + HasDirection(dir) && + (isBullish || + isBearish); + + // + // Cleanup Resources ... + zBar.Clean(); + cBar.Clean(); + pBar.Clean(); + cState.Clean(); + ZeroMemory(cHelper); + cConditions.Clean(); + cStateEvents.Clean(); + cXConditions.Clean(); + + // + return result; + } + + // +}; diff --git a/BKPS/14040203/Documents/BKP/x-cycle.helper.tmp.mq5 b/BKPS/14040203/Documents/BKP/x-cycle.helper.tmp.mq5 new file mode 100644 index 0000000..0ce99ea --- /dev/null +++ b/BKPS/14040203/Documents/BKP/x-cycle.helper.tmp.mq5 @@ -0,0 +1,580 @@ + + // + bool DetectNearestTenKijCross( + XOHCL &bar, + ENUM_X_DIRECTION &dir, + int barIndex = 0, + int maxAllowedBars = 20 // + ) + { + // + bool result = false; + + // + bar.Clean(); + dir = X_DIRECTION_NONE; + barIndex = NormalizeInt(barIndex, 0); + maxAllowedBars = NormalizeInt(maxAllowedBars, 20); + + // + // Looping Through LoopBack Period ... + // for Detecting Result ... + for (int i = barIndex; i < barIndex + maxAllowedBars; i++) + { + // + XOHCL iBar; + result = iBar.Init( + GetSymbol(), + GetPeriod(), + i // + ); + if (!result) + { + // + iBar.Clean(); + break; + } + + // + double iTSen = mX121Helper.xichHelper.GetTenkanSen(i); + double iTSenP = mX121Helper.xichHelper.GetTenkanSen(i + 1); + + // + double iKSen = mX121Helper.xichHelper.GetKijunSen(i); + double iKSenP = mX121Helper.xichHelper.GetKijunSen(i + 1); + + // + bool isTSenOverKSen = iTSen > iKSen; + bool isTSenOverKSenP = iTSenP > iKSenP; + + // + bool isTSenUnderKSen = iTSen < iKSen; + bool isTSenUnderKSenP = iTSenP < iKSenP; + + // + + // + bool isTSenCrossedOverKSen = isTSenOverKSen && + !isTSenOverKSenP; + + // + bool isTSenCrossedUnderKSen = isTSenUnderKSen && + !isTSenUnderKSenP; + + // + result = isTSenCrossedOverKSen || + isTSenCrossedUnderKSen; + if (result) + { + // + bar = iBar; + + // + dir = isTSenCrossedOverKSen + ? X_DIRECTION_BULLISH + : X_DIRECTION_BEARISH; + + // + iBar.Clean(); + break; + } + + // + iBar.Clean(); + } + + // + return result; + } + + // + bool DetectNearestVolumeSwitched( + XOHCL &bar, + ENUM_X_DIRECTION &dir, + int barIndex = 0, + int maxAllowedBars = 20 // + ) + { + // + bool result = false; + + // + bar.Clean(); + dir = X_DIRECTION_NONE; + barIndex = NormalizeInt(barIndex, 0); + maxAllowedBars = NormalizeInt(maxAllowedBars, 20); + + // + // Looping Through LoopBack Period ... + // for Detecting Result ... + for (int i = barIndex; i < barIndex + maxAllowedBars; i++) + { + // + XOHCL iBar; + result = iBar.Init( + GetSymbol(), + GetPeriod(), + i // + ); + if (!result) + { + // + iBar.Clean(); + break; + } + + // + double iBullVMa = mX121Helper.xvolumeHelper.GetBullishVolumeMa(i); + double iBullVMaP = mX121Helper.xvolumeHelper.GetBullishVolumeMa(i + 1); + + // + double iBearVMa = mX121Helper.xvolumeHelper.GetBearishVolumeMa(i); + double iBearVMaP = mX121Helper.xvolumeHelper.GetBearishVolumeMa(i + 1); + + // + bool isBullVMaOverBearVMa = iBullVMa > iBearVMa; + bool isBullVMaOverBearVMaP = iBullVMaP > iBearVMaP; + bool isCrossOver = isBullVMaOverBearVMa && + !isBullVMaOverBearVMaP; + + // + bool isBullVMaUnderBearVMa = iBullVMa < iBearVMa; + bool isBullVMaUnderBearVMaP = iBullVMaP < iBearVMaP; + bool isCrossUnder = isBullVMaUnderBearVMa && + !isBullVMaUnderBearVMaP; + + // + result = isCrossOver || + isCrossUnder; + if (result) + { + // + bar = iBar; + + // + dir = isCrossOver + ? X_DIRECTION_BULLISH + : X_DIRECTION_BEARISH; + + // + iBar.Clean(); + break; + } + + // + iBar.Clean(); + } + + // + return result; + } + + // + bool DetectNearestDeltaSwitched( + XOHCL &bar, + ENUM_X_DIRECTION &dir, + int barIndex = 0, + int maxAllowedBars = 20 // + ) + { + // + bool result = false; + + // + bar.Clean(); + dir = X_DIRECTION_NONE; + barIndex = NormalizeInt(barIndex, 0); + maxAllowedBars = NormalizeInt(maxAllowedBars, 20); + + // + // Looping Through LoopBack Period ... + // for Detecting Result ... + for (int i = barIndex; i < barIndex + maxAllowedBars; i++) + { + // + XOHCL iBar; + result = iBar.Init( + GetSymbol(), + GetPeriod(), + i // + ); + if (!result) + { + // + iBar.Clean(); + break; + } + + // + double iDelta = mX121Helper.xdeltaHelper.GetDelta(i); + double iDeltaP = mX121Helper.xdeltaHelper.GetDelta(i + 1); + + // + double iDeltaMa = mX121Helper.xdeltaHelper.GetDeltaMa(i); + double iDeltaMaP = mX121Helper.xdeltaHelper.GetDeltaMa(i + 1); + + // + bool isDeltaOverMa = iDelta > iDeltaMa; + bool isDeltaOverMaP = iDeltaP > iDeltaMaP; + + // + bool isDeltaUnderMa = iDelta < iDeltaMa; + bool isDeltaUnderMaP = iDeltaP < iDeltaMaP; + + // + bool isCrossOver = isDeltaOverMa && + !isDeltaOverMaP; + + // + bool isCrossUnder = isDeltaUnderMa && + !isDeltaUnderMaP; + + // + result = isCrossOver || + isCrossUnder; + if (result) + { + // + bar = iBar; + + // + dir = isCrossOver + ? X_DIRECTION_BULLISH + : X_DIRECTION_BEARISH; + + // + iBar.Clean(); + break; + } + + // + iBar.Clean(); + } + + // + return result; + } + + + //////////////////////////////////////////////////////////////////////////// + + + + // + // Activated Boxes ... + bool HasActivatedBoxConditions( + ENUM_X_CYCLES cycle, + XSignalBox &box, + ENUM_X_DIRECTION &dir, + XSignalBox &waitingBoxes[], + X121SMCStrategySignalProviderData &provider, + int barIndex = 0 // + ) + { + // + bool result = false; + + // + box.Clean(); + dir = X_DIRECTION_NONE; + + // + // Checking Waiting Baoxes Exists ... + result = HasChild(waitingBoxes); + if (!result) + { + return result; + } + + // + // Fil Selected Data ... + XPOIState cState; + X121Conditions cXConditions; + XPOIStateEvents cStateEvents; + XC121SMCCycleHelper *cHelper; + X121SMCCycleConditions cConditions; + result = provider.SelectCycle( + cycle, + cState, + cStateEvents, + cXConditions, + cHelper, + cConditions // + ); + if (!result) + { + // + cState.Clean(); + ZeroMemory(cHelper); + cConditions.Clean(); + cXConditions.Clean(); + cStateEvents.Clean(); + + // + return result; + } + Parse(cXConditions); + + // + // Normalize Args ... + + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + int idx = -1; + int count = 0; + bool has = false; + + // + int zIDX = barIndex; + int cIDX = zIDX + 1; + int pIDX = cIDX + 1; + int ppIDX = pIDX + 1; + + // + bool isBullish = false; + bool isBearish = false; + + // + XOHCL zBar; + XOHCL cBar; + XOHCL pBar; + + // + // Initial Bars ... + result = zBar.Init( + cState.symbol, + cState.period, + barIndex // + ); + result = + result && + zBar.GetPreviousBar(cBar); + result = + result && + cBar.GetPreviousBar(pBar); + if (!result) + { + // + zBar.Clean(); + cBar.Clean(); + pBar.Clean(); + cState.Clean(); + ZeroMemory(cHelper); + cConditions.Clean(); + cXConditions.Clean(); + + // + return result; + } + + // + // Checking Bar Based on Positions State ... + ENUM_X_DIRECTION iBarPosDir; + bool isBarValidForDir = cHelper + .mBarAnalyser + .IsValidForPosition( + cBar, + iBarPosDir // + ); + bool isBarValidForBullish = + isBarValidForDir && + IsBullish(iBarPosDir); + bool isBarValidForBearish = + isBarValidForDir && + IsBearish(iBarPosDir); + + // + // Extract Selected Boxes ... + XBoxZone selectedBox; + XSignalBox iSignalBox; + count = ArraySize(waitingBoxes); + has = IsValidSize(count); + if (has) + { + // + for (int i = 0; i < count; i++) + { + // + XSignalBox iBox = waitingBoxes[i]; + + // + bool isBullish = iBox.ob.IsBullish(); + + // + has = cBar.low < iBox.sharp.upper && + cBar.low > iBox.sharp.lower && + cBar.high > iBox.sharp.lower && + cBar.high < iBox.sharp.upper; + + // + // Force Using OB ... + if (has) + { + // + iSignalBox = iBox; + if (!selectedBox.IsValid()) + { + selectedBox = iBox.ob; + } + iBox.Clean(); + break; + } + + // + iBox.Clean(); + } + } + result = + iSignalBox.IsValid() && + selectedBox.IsValid(); + if (!result) + { + // + zBar.Clean(); + cBar.Clean(); + pBar.Clean(); + cState.Clean(); + iSignalBox.Clean(); + selectedBox.Clean(); + ZeroMemory(cHelper); + cConditions.Clean(); + cXConditions.Clean(); + + // + return result; + } + + // + bool hasSignalBox = iSignalBox.IsValid(); + bool isSignalBoxBullish = IsBullish(iSignalBox.ob.dir); + + // + // Checking Other Conditions ... + + // + // XVWAP ... + + // + bool isVWapSlopeBullish = + cXConditions.isVwapFastSlopeBullish && + cXConditions.isVwapMidSlopeBullish && + cXConditions.isVwapSlowSlopeBullish; + + // + bool isVWapSlopeBearish = + cXConditions.isVwapFastSlopeBearish && + cXConditions.isVwapMidSlopeBearish && + cXConditions.isVwapSlowSlopeBearish; + + // + bool isVWapBullishCondition = + (cXConditions.isVWapBullishOrdered && + cXConditions.isVWapSwitchedToBullishState) || + (cXConditions.isVWapBullishState && + cXConditions.isVWapSwitchedToBullishOrdered); + + // + bool isVWapBearishCondition = + (cXConditions.isVWapBearishOrdered && + cXConditions.isVWapSwitchedToBearishState) || + (cXConditions.isVWapBearishState && + cXConditions.isVWapSwitchedToBearishOrdered); + + // + // Bullish Conditions ... + isBullish = + // + // Base Condition ... + ( + // + hasSignalBox && + isSignalBoxBullish && + isVWapSlopeBullish && + isBarValidForBullish && + isVWapBullishCondition + // + ) + // + ; + + // + // Bearish Conditions ... + isBearish = + // + // Base Condition ... + ( + // + hasSignalBox && + isVWapSlopeBearish && + !isSignalBoxBullish && + isBarValidForBearish && + isVWapBearishCondition + // + ) + // + ; + + // + // Filling Requirements ... + result = + isBullish || + isBearish; + if (result) + { + // + dir = + isBullish + ? X_DIRECTION_BULLISH + : X_DIRECTION_BEARISH; + + // + box = iSignalBox; + box.UpdateTo(TimeCurrent()); + + // + // Provide TP/SL ... + + // + box.sl = isBullish + ? cXConditions.vwapMin + : cXConditions.vwapMax; + + // + box.tp = isBullish + ? box.sharp.upper + : box.sharp.lower; + } + + // + // Check All Conditions ... + result = + box.IsValid() && + HasDirection(dir) && + (isBullish || + isBearish); + + // + // Cleanup Resources ... + zBar.Clean(); + cBar.Clean(); + pBar.Clean(); + cState.Clean(); + iSignalBox.Clean(); + selectedBox.Clean(); + ZeroMemory(cHelper); + cConditions.Clean(); + cStateEvents.Clean(); + cXConditions.Clean(); + + // + return result; + } + + ///////////////////////////////////////////////////////////////////////////////////// + + \ No newline at end of file diff --git a/BKPS/14040203/Documents/BKP/x-pv.qween.ea.mq5 b/BKPS/14040203/Documents/BKP/x-pv.qween.ea.mq5 new file mode 100644 index 0000000..683980d --- /dev/null +++ b/BKPS/14040203/Documents/BKP/x-pv.qween.ea.mq5 @@ -0,0 +1,232 @@ +//+------------------------------------------------------------------+ +//| SaherElm IT Center MQL5 Expert Advisor | +//| | +//| Name: X121 XPV EA | +//| Description: Multi-Timeframe Peak & Vale Breakout Strategy | +//| Maintainer: Hadi Khazaee Asl | +//+------------------------------------------------------------------+ +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://saherelm.ir" +#property version "1.00" +#property strict + +// +#include "../Helpers/x-saherelm.x121.xpv.helper.mq5" + +// Input Parameters +input double RiskPercent = 1.0; // Risk per trade in percentage +input int StopLossPips = 50; // Stop Loss in pips +input int TakeProfitPips = 100; // Take Profit in pips +input bool UseTrailingStop = true; // Enable trailing stop +input int TrailingStopPips = 30; // Trailing stop distance in pips +input int MagicNumber = 123456; // Unique identifier for trades +input bool DebugMode = true; // Enable debug messages + +// +// Global Variables ... +X121XPVInputs mXPVInputs; +XCX121XPVHelper *mXPVHelper; + +//+------------------------------------------------------------------+ +//| Expert Initialization Function | +//+------------------------------------------------------------------+ +int OnInit() +{ + // + // Attach the X121 XPV indicator ... + mXPVInputs.Default(); + mXPVHelper = new XCX121XPVHelper(); + bool isInited = mXPVHelper.Init( + _Symbol, + _Period, + mXPVInputs // + ); + if (!isInited) + { + return INIT_FAILED; + } + + // + Print("X121 XPV EA Initialized."); + return INIT_SUCCEEDED; +} + +//+------------------------------------------------------------------+ +//| Expert Deinitialization Function | +//+------------------------------------------------------------------+ +void OnDeinit(const int reason) +{ + // + mXPVInputs.Clean(); + ZeroMemory(mXPVHelper); + Print("X121 XPV EA Deinitialized."); +} + +//+------------------------------------------------------------------+ +//| Expert Tick Function | +//+------------------------------------------------------------------+ +void OnTick() +{ + // + // Check if there are open positions for this symbol + if (PositionSelect(_Symbol)) + { + ManageOpenPosition(); + return; + } + + // + X121XPVConditions pvConditions; + bool isRetrieved = mXPVHelper.GetConditions( + pvConditions, + 1 // + ); + if (!isRetrieved) + { + return; + } + + // + // Get indicator values + double peak = pvConditions.peaksBuffer[0]; + double vale = pvConditions.valesBuffer[0]; + double peakGoldenZone = pvConditions.peaksGoldenBuffer[0]; + double valeGoldenZone = pvConditions.valesGoldenBuffer[0]; + + // + // Validate indicator values + if (peak == EMPTY_VALUE || vale == EMPTY_VALUE || peakGoldenZone == EMPTY_VALUE || valeGoldenZone == EMPTY_VALUE) + { + // + if (DebugMode) + Print("Invalid indicator values. Skipping..."); + return; + } + + // + // Entry Conditions + double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID); + double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK); + + // + // Long Entry + if (bid > peak && bid > peakGoldenZone) + { + OpenTrade(ORDER_TYPE_BUY, peak, valeGoldenZone); + } + + // + // Short Entry + if (ask < vale && ask < valeGoldenZone) + { + OpenTrade(ORDER_TYPE_SELL, vale, peakGoldenZone); + } +} + +//+------------------------------------------------------------------+ +//| Open a Trade | +//+------------------------------------------------------------------+ +void OpenTrade(int orderType, double entryLevel, double targetLevel) +{ + // + double lotSize = CalculateLotSize(entryLevel, targetLevel); + double sl = (orderType == ORDER_TYPE_BUY) ? entryLevel - StopLossPips * Point() : entryLevel + StopLossPips * Point(); + double tp = (orderType == ORDER_TYPE_BUY) ? entryLevel + TakeProfitPips * Point() : entryLevel - TakeProfitPips * Point(); + + // + // Prepare trade request + MqlTradeRequest request = {}; + MqlTradeResult result = {}; + + // + request.action = TRADE_ACTION_DEAL; + request.symbol = _Symbol; + request.volume = lotSize; + request.type = (ENUM_ORDER_TYPE)orderType; + request.price = (orderType == ORDER_TYPE_BUY) ? SymbolInfoDouble(_Symbol, SYMBOL_ASK) : SymbolInfoDouble(_Symbol, SYMBOL_BID); + request.sl = sl; + request.tp = tp; + request.deviation = 10; + request.magic = MagicNumber; + + // + // Send trade request + if (!OrderSend(request, result)) + { + Print("Trade failed: ", result.retcode); + } + else + { + Print("Trade opened successfully."); + } +} + +//+------------------------------------------------------------------+ +//| Manage Open Position | +//+------------------------------------------------------------------+ +void ManageOpenPosition() +{ + ulong ticket = PositionGetInteger(POSITION_TICKET); + double currentPrice = (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY) ? SymbolInfoDouble(_Symbol, SYMBOL_BID) : SymbolInfoDouble(_Symbol, SYMBOL_ASK); + double openPrice = PositionGetDouble(POSITION_PRICE_OPEN); + double sl = PositionGetDouble(POSITION_SL); + double tp = PositionGetDouble(POSITION_TP); + + // Trailing Stop Logic + if (UseTrailingStop) + { + double newSL = (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY) + ? currentPrice - TrailingStopPips * Point() + : currentPrice + TrailingStopPips * Point(); + + if ((PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY && newSL > sl) || + (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL && newSL < sl)) + { + ModifyPosition(ticket, newSL, tp); + } + } +} + +//+------------------------------------------------------------------+ +//| Modify Position | +//+------------------------------------------------------------------+ +void ModifyPosition(ulong ticket, double newSL, double newTP) +{ + MqlTradeRequest request = {}; + MqlTradeResult result = {}; + + request.action = TRADE_ACTION_SLTP; + request.position = ticket; + request.sl = newSL; + request.tp = newTP; + + if (!OrderSend(request, result)) + { + Print("Failed to modify position: ", result.retcode); + } + else + { + Print("Position modified successfully."); + } +} + +//+------------------------------------------------------------------+ +//| Calculate Lot Size | +//+------------------------------------------------------------------+ +double CalculateLotSize(double entryLevel, double targetLevel) +{ + double riskAmount = AccountInfoDouble(ACCOUNT_BALANCE) * RiskPercent / 100; + double stopLossDistance = MathAbs(entryLevel - targetLevel) / Point(); + double tickValue = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_VALUE); + double lotSize = riskAmount / (stopLossDistance * tickValue); + + // Normalize lot size + double minLot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN); + double maxLot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX); + double stepLot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP); + + lotSize = MathFloor(lotSize / stepLot) * stepLot; + lotSize = MathMax(minLot, MathMin(maxLot, lotSize)); + + return lotSize; +} \ No newline at end of file diff --git a/BKPS/14040203/Documents/BKP/x-saherelm.x121.helper.mq5 b/BKPS/14040203/Documents/BKP/x-saherelm.x121.helper.mq5 new file mode 100644 index 0000000..5dbfce6 --- /dev/null +++ b/BKPS/14040203/Documents/BKP/x-saherelm.x121.helper.mq5 @@ -0,0 +1,4949 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Helper Class Library +// ---------------------------------------------- +// Name: XCX121Helper +// Description: provides all Indicator +// Helper requirements ... +// +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +////////////////////////////////////////////////////// +// +// Global Properties ... +#property library +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://www.saherelm.ir" +#property version "1.00" +#property strict + +// +// Imports ... +#include "../Helpers/x-saherelm.x121.x3ma.helper.mq5" +#include "../Helpers/x-saherelm.x121.xatr.helper.mq5" +#include "../Helpers/x-saherelm.x121.xcc.helper.mq5" +#include "../Helpers/x-saherelm.x121.xche.helper.mq5" +#include "../Helpers/x-saherelm.x121.xdelta.helper.mq5" +#include "../Helpers/x-saherelm.x121.xdon.helper.mq5" +#include "../Helpers/x-saherelm.x121.xhk.helper.mq5" +#include "../Helpers/x-saherelm.x121.xich.helper.mq5" +#include "../Helpers/x-saherelm.x121.xmas.helper.mq5" +#include "../Helpers/x-saherelm.x121.xpv.helper.mq5" +#include "../Helpers/x-saherelm.x121.xstr.helper.mq5" +#include "../Helpers/x-saherelm.x121.xvolume.helper.mq5" +#include "../Helpers/x-saherelm.x121.xvwap.helper.mq5" + +// +// Inputs ... +struct X121Inputs +{ + // + // Props ... + bool showRSI; + X121XCCInputs xccInputs; + X121XPVInputs xpvInputs; + X121XHKInputs xhkInputs; + X121XICHInputs xichInputs; + X121XMASInputs xmasInputs; + X121XATRInputs xatrInputs; + X121XSTRInputs xstrInputs; + X121XCHEInputs xcheInputs; + X121XDONInputs xdonInputs; + X121X3MAInputs x3maInputs; + X121XVWAPInputs xvwapInputs; + X121XDELTAInputs xdeltaInputs; + X121XVOLUMEInputs xvolumeInputs; + + // + // Constructor ... + X121Inputs() + { + Clean(); + } + + // + // Tools ... + + /** + * Cleaning Up ... + */ + void Clean() + { + // + xccInputs.Clean(); + xpvInputs.Clean(); + xhkInputs.Clean(); + xichInputs.Clean(); + xmasInputs.Clean(); + xatrInputs.Clean(); + xstrInputs.Clean(); + xcheInputs.Clean(); + xdonInputs.Clean(); + xvwapInputs.Clean(); + xdeltaInputs.Clean(); + xvolumeInputs.Clean(); + + // + ZeroMemory(this); + } + + /** + * Set Default Values ... + */ + void Default() + { + // + xccInputs.Default(); + xpvInputs.Default(); + xhkInputs.Default(); + xichInputs.Default(); + xmasInputs.Default(); + xatrInputs.Default(); + xstrInputs.Default(); + xcheInputs.Default(); + xdonInputs.Default(); + x3maInputs.Default(); + xvwapInputs.Default(); + xdeltaInputs.Default(); + xvolumeInputs.Default(); + } + + /** + * Validate ... + * + * @return ( bool ) + */ + bool IsValid() + { + // + bool result = false; + + // + result = + // + xccInputs.IsValid() && + xpvInputs.IsValid() && + xhkInputs.IsValid() && + xichInputs.IsValid() && + xmasInputs.IsValid() && + xatrInputs.IsValid() && + xstrInputs.IsValid() && + xcheInputs.IsValid() && + xdonInputs.IsValid() && + xvwapInputs.IsValid() && + xdeltaInputs.IsValid() && + xvolumeInputs.IsValid() + // + ; + + // + return result; + } + + /** + * Extract Max Input Length ... + * + * @return ( int ) + */ + int Max() + { + // + int result = 0; + + // + int xpvMax = xpvInputs.Max(); + int xhkMax = xhkInputs.Max(); + int xmasMax = xmasInputs.Max(); + int xatrMax = xatrInputs.Max(); + int xstrMax = xstrInputs.Max(); + int xcheMax = xcheInputs.Max(); + int xdonMax = xdonInputs.Max(); + int xichMax = xichInputs.Max(); + int xvwapMax = xvwapInputs.Max(); + int xdeltaMax = xdeltaInputs.Max(); + int xvolumeMax = xvolumeInputs.Max(); + + // + result = MathMax(xpvMax, xhkMax); + result = MathMax(result, xmasMax); + result = MathMax(result, xatrMax); + result = MathMax(result, xstrMax); + result = MathMax(result, xcheMax); + result = MathMax(result, xdonMax); + result = MathMax(result, xichMax); + result = MathMax(result, xvwapMax); + result = MathMax(result, xdeltaMax); + result = MathMax(result, xvolumeMax); + + // + return result; + } +}; + +// +// Conditions ... +struct X121Conditions +{ + // + // Common ... + string symbol; + ENUM_TIMEFRAMES period; + datetime time; + + // + // Buffers ... + double maBuffer[]; + double rsiBuffer[]; + double atrBuffer[]; + double strBuffer[]; + double le1Buffer[]; + double se1Buffer[]; + double le2Buffer[]; + double se2Buffer[]; + double sarBuffer[]; + double cHHBuffer[]; + double cLLBuffer[]; + double sHHBuffer[]; + double sLLBuffer[]; + double mHHBuffer[]; + double mLLBuffer[]; + double lHHBuffer[]; + double lLLBuffer[]; + double hHHBuffer[]; + double hLLBuffer[]; + double upTBuffer[]; + double adxBuffer[]; + double adxPBuffer[]; + double adxMBuffer[]; + long volumeBuffer[]; + double peaksBuffer[]; + double valesBuffer[]; + double strUpBuffer[]; + double downTBuffer[]; + double deltaBuffer[]; + double masMidBuffer[]; + double deltaMaBuffer[]; + double strDownBuffer[]; + double vwapMidBuffer[]; + double upTrendBuffer[]; + double x3maMidBuffer[]; + double masUpperBuffer[]; + double masLowerBuffer[]; + double kijunSenBuffer[]; + double le1StartBuffer[]; + double se1StartBuffer[]; + double le2StartBuffer[]; + double se2StartBuffer[]; + double strPriceBuffer[]; + double atrUpperBuffer[]; + double atrLowerBuffer[]; + double strStateBuffer[]; + double vwapFastBuffer[]; + double vwapSlowBuffer[]; + double xhkSMLowBuffer[]; + double x3maFastBuffer[]; + double x3maSlowBuffer[]; + double supportsBuffer[]; + double tenkanSenBuffer[]; + double downTrendBuffer[]; + double vwapPriceBuffer[]; + double xhkRawLowBuffer[]; + double xhkSMOpenBuffer[]; + double xhkSMHighBuffer[]; + double deltaStateBuffer[]; + double xhkRawOpenBuffer[]; + double xhkRawHighBuffer[]; + double xhkSMCloseBuffer[]; + double vwapVolumeBuffer[]; + double chikouSpanBuffer[]; + double senkouSpanABuffer[]; + double senkouSpanBBuffer[]; + double peaksGoldenBuffer[]; + double valesGoldenBuffer[]; + double xhkRawCloseBuffer[]; + double atrUpperRawBuffer[]; + double atrLowerRawBuffer[]; + double donLowUpperBuffer[]; + double donLowLowerBuffer[]; + double resistancesBuffer[]; + double vwapMidStateBuffer[]; + double donOpenUpperBuffer[]; + double donOpenLowerBuffer[]; + double donHighUpperBuffer[]; + double donHighLowerBuffer[]; + double x3maMidStateBuffer[]; + double bullishVolumeBuffer[]; + double bearishVolumeBuffer[]; + double fractalsUpperBuffer[]; + double fractalsLowerBuffer[]; + double vwapFastStateBuffer[]; + double vwapSlowStateBuffer[]; + double donCloseUpperBuffer[]; + double donCloseLowerBuffer[]; + double x3maFastStateBuffer[]; + double x3maSlowStateBuffer[]; + double bullishVolumeMaBuffer[]; + double bearishVolumeMaBuffer[]; + + // + double rsiSlope; + double strSlope; + double atrUpperSlope; + double atrLowerSlope; + double vwapFastSlope; + double vwapMidSlope; + double vwapSlowSlope; + + // + // Conditions ... + + // + bool isRsiSlopeBullish; + bool isStrSlopeBullish; + bool isAtrUpperSlopeBullish; + bool isAtrLowerSlopeBullish; + bool isVwapFastSlopeBullish; + bool isVwapMidSlopeBullish; + bool isVwapSlowSlopeBullish; + + // + bool isRsiSlopeBearish; + bool isStrSlopeBearish; + bool isAtrUpperSlopeBearish; + bool isAtrLowerSlopeBearish; + bool isVwapFastSlopeBearish; + bool isVwapMidSlopeBearish; + bool isVwapSlowSlopeBearish; + + // + bool isRsiOverSold; + bool isRsiOverBought; + bool isRsiCrossedOverOverSold; + bool isRsiCrossedUnderOverSold; + bool isRsiCrossedOverOverBought; + bool isRsiCrossedUnderOverBought; + + // + bool isClosedOverAtrUpper; + bool isClosedOverAtrLower; + bool isClosedUnderAtrUpper; + bool isClosedUnderAtrLower; + + // + bool isSarBullish; + bool isSarBearish; + bool isSarSwitchedToBullish; + bool isSarSwitchedToBearish; + + // + bool isNewPeak; + bool isNewPeakOverLast; + bool isNewPeakUnderLast; + + // + bool isNewVale; + bool isNewValeOverLast; + bool isNewValeUnderLast; + + // + bool isStrBullish; + bool isStrBearish; + bool isStrSwitchedToBullish; + bool isStrSwitchedToBearish; + + // + bool isChe1Bullish; + bool isChe1Bearish; + bool isChe1SwitchedToBullish; + bool isChe1SwitchedToBearish; + + // + bool isChe2Bullish; + bool isChe2Bearish; + bool isChe2SwitchedToBullish; + bool isChe2SwitchedToBearish; + + // + bool isCheBullish; + bool isCheBearish; + bool isCheSwitchedToBullish; + bool isCheSwitchedToBearish; + + // + bool isVWapMidBullish; + bool isVWapMidBearish; + bool isVWapFastBullish; + bool isVWapFastBearish; + bool isVWapMidNeutural; + bool isVWapSlowBullish; + bool isVWapSlowBearish; + bool isVWapFastOverMid; + bool isVWapMidOverSlow; + bool isVWapFastNeutural; + bool isVWapSlowNeutural; + bool isVWapFastUnderMid; + bool isVWapMidUnderSlow; + bool isVWapBullishState; + bool isVWapBearishState; + bool isVWapNeuturalState; + bool isVWapBullishOrdered; + bool isVWapBearishOrdered; + bool isVWapSwitchedToBullishState; + bool isVWapSwitchedToBearishState; + bool isVWapSwitchedToNeuturalState; + bool isVWapSwitchedToBullishOrdered; + bool isVWapSwitchedToBearishOrdered; + + // + bool isX3MaMidBullish; + bool isX3MaMidBearish; + bool isX3MaFastBullish; + bool isX3MaFastBearish; + bool isX3MaMidNeutural; + bool isX3MaSlowBullish; + bool isX3MaSlowBearish; + bool isX3MaFastOverMid; + bool isX3MaMidOverSlow; + bool isX3MaFastNeutural; + bool isX3MaSlowNeutural; + bool isX3MaFastUnderMid; + bool isX3MaMidUnderSlow; + bool isX3MaBullishState; + bool isX3MaBearishState; + bool isX3MaNeuturalState; + bool isX3MaBullishOrdered; + bool isX3MaBearishOrdered; + bool isX3MaSwitchedToBullishState; + bool isX3MaSwitchedToBearishState; + bool isX3MaSwitchedToNeuturalState; + bool isX3MaSwitchedToBullishOrdered; + bool isX3MaSwitchedToBearishOrdered; + + // + bool isSMHKBullish; + bool isRawHKBullish; + bool isSMHKBearish; + bool isRawHKBearish; + bool isClosedOverSMHK; + bool isClosedUnderSMHK; + bool isClosedOverRawHK; + bool isClosedUnderRawHK; + bool isRawHKClosedOverSMHK; + bool isRawHKClosedUnderSMHK; + bool isSMHKSwitchedToBullish; + bool isSMHKSwitchedToBearish; + bool isRawHKSwitchedToBearish; + bool isRawHKSwitchedToBullish; + + // + // XICH ... + + // + bool isSenkouSpanAOverB; + bool isSenkouSpanAUnderB; + bool isTenkanSenOverKijunSen; + bool isTenkanSenUnderKijunSen; + bool isSenkouSpanACrossedOverB; + bool isSenkouSpanACrossedUnderB; + bool isTenkanSenCrossedOverKijunSen; + bool isTenkanSenCrossedUnderKijunSen; + + // + // XDELTA ... + + // + bool isDeltaBullish; + bool isDeltaBearish; + bool isDeltaSwitchedToBullish; + bool isDeltaSwitchedToBearish; + + // + bool isDeltaOverMa; + bool isDeltaUnderMa; + bool isDeltaCrossedOverMa; + bool isDeltaCrossedUnderMa; + + // + // XVOLUME ... + + bool isBullishVolumeOverMa; + bool isBullishVolumeCrossedOverMa; + + // + bool isBullishVolumeUnderMa; + bool isBullishVolumeCrossedUnderMa; + + // + bool isBullishVolumeIncreased; + bool isBullishVolumeSwitchedToIncreased; + + // + bool isBullishVolumeDecreased; + bool isBullishVolumeSwitchedToDecreased; + + // + bool isBearishVolumeOverMa; + bool isBearishVolumeCrossedOverMa; + + // + bool isBearishVolumeUnderMa; + bool isBearishVolumeCrossedUnderMa; + + // + bool isBearishVolumeIncreased; + bool isBearishVolumeSwitchedToIncreased; + + // + bool isBearishVolumeDecreased; + bool isBearishVolumeSwitchedToDecreased; + + // + bool isVolumeSwitchedToBullish; + bool isVolumeSwitchedToBearish; + + // + bool isBullishVolumeMaOverBearishVolumeMa; + bool isBullishVolumeMaUnderBearishVolumeMa; + + // + // Complex Conditions ... + + // + double cheMin; + double cheMax; + double x3maMin; + double x3maMax; + double vwapMin; + double vwapMax; + double senkouMax; + double senkouMin; + double tenKijMax; + double tenKijMin; + + // + bool isSarIncreased; + bool isSarDecreased; + bool isX3MaFatsOverMid; + bool isSarEqualsToPeak; + bool isSarEqualsToVale; + bool isStrEqualsToPeak; + bool isStrEqualsToVale; + bool isX3MaFatsUnderMid; + bool isX3MaFatsOverSlow; + bool isAtrUpperOverPeak; + bool isPeakOverAtrUpper; + bool isStrUpperOverPeak; + bool isStrLowerOverVale; + bool isClosedOverCheMin; + bool isClosedOverCheMax; + bool isX3MaFatsUnderSlow; + bool isAtrLowerUnderVale; + bool isClosedOverX3MaMin; + bool isClosedOverX3MaMax; + bool isValeUnderAtrLower; + bool isStrUpperUnderPeak; + bool isStrLowerUnderVale; + bool isClosedUnderCheMin; + bool isClosedUnderCheMax; + bool isClosedOverVWapMin; + bool isClosedOverVWapMax; + bool isClosedUnderX3MaMin; + bool isClosedUnderX3MaMax; + bool isStrCrossedOverVale; + bool isSarCrossedOverVale; + bool isClosedUnderVWapMin; + bool isClosedUnderVWapMax; + bool isX3MaFatsOverMidPrev; + bool isSarCrossedUnderPeak; + bool isStrCrossedUnderPeak; + bool isNewPeakOverAtrUpper; + bool isX3MaFatsUnderMidPrev; + bool isX3MaFatsOverSlowPrev; + bool isAtrUpperEqualsToPeak; + bool isAtrLowerEqualsToVale; + bool isStrUpperOverAtrUpper; + bool isStrLowerOverAtrLower; + bool isNewValeUnderAtrLower; + bool isAtrUpperCrossedUpPeak; + bool isAtrLowerCrossedUpVale; + bool isStrUpperUnderAtrUpper; + bool isStrLowerUnderAtrLower; + bool isX3MaFatsUnderSlowPrev; + bool isX3MaFastCrossedOverMid; + bool isVWapFastCrossedOverMid; + bool isX3MaFastCrossedUnderMid; + bool isX3MaFastCrossedOverSlow; + bool isAtrUpperCrossedDownPeak; + bool isAtrLowerCrossedDownVale; + bool isStrLowerOverDonLowLower; + bool isVWapFastCrossedUnderMid; + bool isStrUpperCrossedOverPeak; + bool isStrLowerCrossedOverVale; + bool isDonLowLowerEqualsToVale; + bool isVWapFastCrossedOverSlow; + bool isX3MaFastCrossedUnderSlow; + bool isStrUpperOverDonHighUpper; + bool isStrLowerUnderDonLowLower; + bool isVWapFastCrossedUnderSlow; + bool isStrUpperCrossedUnderPeak; + bool isStrLowerCrossedUnderVale; + bool isDonHighUpperEqualsToPeak; + bool isStrUpperUnderDonHighUpper; + bool isStrUpperCrossedOverAtrUpper; + bool isStrLowerCrossedOverAtrLower; + bool isStrUpperCrossedUnderAtrUpper; + bool isStrLowerCrossedUnderAtrLower; + bool isStrLowerCrossedOverDonLowLower; + bool isStrUpperCrossedOverDonHighUpper; + bool isStrLowerCrossedUnderDonLowLower; + bool isStrUpperCrossedUnderDonHighUpper; + + // + // Constructor ... + X121Conditions() + { + Clean(); + } + + // + // Tools ... + + /** + * Cleaning Up ... + */ + void Clean() + { + // + // Commons ... + symbol = NULL; + period = NULL; + time = NULL; + + // + // Buffers ... + + // + Clean(maBuffer); + Clean(rsiBuffer); + Clean(atrBuffer); + Clean(strBuffer); + Clean(le1Buffer); + Clean(se1Buffer); + Clean(le2Buffer); + Clean(se2Buffer); + Clean(sarBuffer); + Clean(cHHBuffer); + Clean(cLLBuffer); + Clean(sHHBuffer); + Clean(sLLBuffer); + Clean(mHHBuffer); + Clean(mLLBuffer); + Clean(lHHBuffer); + Clean(lLLBuffer); + Clean(hHHBuffer); + Clean(hLLBuffer); + Clean(upTBuffer); + Clean(adxBuffer); + Clean(adxPBuffer); + Clean(adxMBuffer); + Clean(peaksBuffer); + Clean(valesBuffer); + Clean(strUpBuffer); + Clean(downTBuffer); + Clean(deltaBuffer); + Clean(volumeBuffer); + Clean(masMidBuffer); + Clean(strDownBuffer); + Clean(vwapMidBuffer); + Clean(upTrendBuffer); + Clean(x3maMidBuffer); + Clean(deltaMaBuffer); + Clean(masUpperBuffer); + Clean(masLowerBuffer); + Clean(le1StartBuffer); + Clean(se1StartBuffer); + Clean(le2StartBuffer); + Clean(se2StartBuffer); + Clean(strPriceBuffer); + Clean(atrUpperBuffer); + Clean(atrLowerBuffer); + Clean(strStateBuffer); + Clean(vwapFastBuffer); + Clean(vwapSlowBuffer); + Clean(xhkSMLowBuffer); + Clean(x3maFastBuffer); + Clean(x3maSlowBuffer); + Clean(supportsBuffer); + Clean(kijunSenBuffer); + Clean(tenkanSenBuffer); + Clean(downTrendBuffer); + Clean(vwapPriceBuffer); + Clean(xhkRawLowBuffer); + Clean(xhkSMOpenBuffer); + Clean(xhkSMHighBuffer); + Clean(chikouSpanBuffer); + Clean(xhkRawOpenBuffer); + Clean(xhkRawHighBuffer); + Clean(xhkSMCloseBuffer); + Clean(vwapVolumeBuffer); + Clean(deltaStateBuffer); + Clean(senkouSpanABuffer); + Clean(senkouSpanBBuffer); + Clean(peaksGoldenBuffer); + Clean(valesGoldenBuffer); + Clean(xhkRawCloseBuffer); + Clean(atrUpperRawBuffer); + Clean(atrLowerRawBuffer); + Clean(donLowUpperBuffer); + Clean(donLowLowerBuffer); + Clean(resistancesBuffer); + Clean(vwapMidStateBuffer); + Clean(donOpenUpperBuffer); + Clean(donOpenLowerBuffer); + Clean(donHighUpperBuffer); + Clean(donHighLowerBuffer); + Clean(x3maMidStateBuffer); + Clean(bullishVolumeBuffer); + Clean(bearishVolumeBuffer); + Clean(fractalsUpperBuffer); + Clean(fractalsLowerBuffer); + Clean(vwapFastStateBuffer); + Clean(vwapSlowStateBuffer); + Clean(donCloseUpperBuffer); + Clean(donCloseLowerBuffer); + Clean(x3maFastStateBuffer); + Clean(x3maSlowStateBuffer); + Clean(bullishVolumeMaBuffer); + Clean(bearishVolumeMaBuffer); + + // + ArraySetAsSeries(maBuffer, true); + ArraySetAsSeries(rsiBuffer, true); + ArraySetAsSeries(atrBuffer, true); + ArraySetAsSeries(strBuffer, true); + ArraySetAsSeries(le1Buffer, true); + ArraySetAsSeries(se1Buffer, true); + ArraySetAsSeries(le2Buffer, true); + ArraySetAsSeries(se2Buffer, true); + ArraySetAsSeries(sarBuffer, true); + ArraySetAsSeries(cHHBuffer, true); + ArraySetAsSeries(cLLBuffer, true); + ArraySetAsSeries(sHHBuffer, true); + ArraySetAsSeries(sLLBuffer, true); + ArraySetAsSeries(mHHBuffer, true); + ArraySetAsSeries(mLLBuffer, true); + ArraySetAsSeries(lHHBuffer, true); + ArraySetAsSeries(lLLBuffer, true); + ArraySetAsSeries(hHHBuffer, true); + ArraySetAsSeries(hLLBuffer, true); + ArraySetAsSeries(upTBuffer, true); + ArraySetAsSeries(adxBuffer, true); + ArraySetAsSeries(adxPBuffer, true); + ArraySetAsSeries(adxMBuffer, true); + ArraySetAsSeries(peaksBuffer, true); + ArraySetAsSeries(valesBuffer, true); + ArraySetAsSeries(strUpBuffer, true); + ArraySetAsSeries(downTBuffer, true); + ArraySetAsSeries(deltaBuffer, true); + ArraySetAsSeries(volumeBuffer, true); + ArraySetAsSeries(masMidBuffer, true); + ArraySetAsSeries(deltaMaBuffer, true); + ArraySetAsSeries(strDownBuffer, true); + ArraySetAsSeries(vwapMidBuffer, true); + ArraySetAsSeries(upTrendBuffer, true); + ArraySetAsSeries(x3maMidBuffer, true); + ArraySetAsSeries(masUpperBuffer, true); + ArraySetAsSeries(masLowerBuffer, true); + ArraySetAsSeries(le1StartBuffer, true); + ArraySetAsSeries(se1StartBuffer, true); + ArraySetAsSeries(le2StartBuffer, true); + ArraySetAsSeries(se2StartBuffer, true); + ArraySetAsSeries(strPriceBuffer, true); + ArraySetAsSeries(atrUpperBuffer, true); + ArraySetAsSeries(atrLowerBuffer, true); + ArraySetAsSeries(strStateBuffer, true); + ArraySetAsSeries(vwapFastBuffer, true); + ArraySetAsSeries(vwapSlowBuffer, true); + ArraySetAsSeries(xhkSMLowBuffer, true); + ArraySetAsSeries(x3maFastBuffer, true); + ArraySetAsSeries(x3maSlowBuffer, true); + ArraySetAsSeries(supportsBuffer, true); + ArraySetAsSeries(kijunSenBuffer, true); + ArraySetAsSeries(tenkanSenBuffer, true); + ArraySetAsSeries(downTrendBuffer, true); + ArraySetAsSeries(vwapPriceBuffer, true); + ArraySetAsSeries(xhkRawLowBuffer, true); + ArraySetAsSeries(xhkSMOpenBuffer, true); + ArraySetAsSeries(xhkSMHighBuffer, true); + ArraySetAsSeries(deltaStateBuffer, true); + ArraySetAsSeries(chikouSpanBuffer, true); + ArraySetAsSeries(xhkRawOpenBuffer, true); + ArraySetAsSeries(xhkRawHighBuffer, true); + ArraySetAsSeries(xhkSMCloseBuffer, true); + ArraySetAsSeries(vwapVolumeBuffer, true); + ArraySetAsSeries(senkouSpanABuffer, true); + ArraySetAsSeries(senkouSpanBBuffer, true); + ArraySetAsSeries(peaksGoldenBuffer, true); + ArraySetAsSeries(valesGoldenBuffer, true); + ArraySetAsSeries(xhkRawCloseBuffer, true); + ArraySetAsSeries(atrUpperRawBuffer, true); + ArraySetAsSeries(atrLowerRawBuffer, true); + ArraySetAsSeries(donLowUpperBuffer, true); + ArraySetAsSeries(donLowLowerBuffer, true); + ArraySetAsSeries(resistancesBuffer, true); + ArraySetAsSeries(vwapMidStateBuffer, true); + ArraySetAsSeries(donOpenUpperBuffer, true); + ArraySetAsSeries(donOpenLowerBuffer, true); + ArraySetAsSeries(donHighUpperBuffer, true); + ArraySetAsSeries(donHighLowerBuffer, true); + ArraySetAsSeries(x3maMidStateBuffer, true); + ArraySetAsSeries(bullishVolumeBuffer, true); + ArraySetAsSeries(bearishVolumeBuffer, true); + ArraySetAsSeries(fractalsUpperBuffer, true); + ArraySetAsSeries(fractalsLowerBuffer, true); + ArraySetAsSeries(vwapFastStateBuffer, true); + ArraySetAsSeries(vwapSlowStateBuffer, true); + ArraySetAsSeries(donCloseUpperBuffer, true); + ArraySetAsSeries(donCloseLowerBuffer, true); + ArraySetAsSeries(x3maFastStateBuffer, true); + ArraySetAsSeries(x3maSlowStateBuffer, true); + ArraySetAsSeries(bullishVolumeMaBuffer, true); + ArraySetAsSeries(bearishVolumeMaBuffer, true); + + // + cheMin = 0; + cheMax = 0; + vwapMin = 0; + vwapMax = 0; + x3maMin = 0; + x3maMax = 0; + senkouMax = 0; + senkouMin = 0; + tenKijMax = 0; + tenKijMin = 0; + // + // Slopes ... + + rsiSlope = 0; + strSlope = 0; + atrUpperSlope = 0; + atrLowerSlope = 0; + vwapFastSlope = 0; + vwapMidSlope = 0; + vwapSlowSlope = 0; + + // + // Conditions ... + + // + isRsiSlopeBullish = false; + isStrSlopeBullish = false; + isAtrUpperSlopeBullish = false; + isAtrLowerSlopeBullish = false; + isVwapFastSlopeBullish = false; + isVwapMidSlopeBullish = false; + isVwapSlowSlopeBullish = false; + + // + isRsiSlopeBearish = false; + isStrSlopeBearish = false; + isAtrUpperSlopeBearish = false; + isAtrLowerSlopeBearish = false; + isVwapFastSlopeBearish = false; + isVwapMidSlopeBearish = false; + isVwapSlowSlopeBearish = false; + + // + // RSI ... + + // + isRsiOverBought = false; + isRsiCrossedOverOverBought = false; + isRsiCrossedUnderOverBought = false; + + // + isRsiOverSold = false; + isRsiCrossedUnderOverSold = false; + isRsiCrossedOverOverSold = false; + + // + // ATR ... + + // + isClosedOverAtrUpper = false; + isClosedOverAtrLower = false; + isClosedUnderAtrUpper = false; + isClosedUnderAtrLower = false; + + // + // DON ... + + // + // SAR ... + + // + isSarBullish = false; + isSarBearish = false; + isSarSwitchedToBullish = false; + isSarSwitchedToBearish = false; + + // + // PV ... + + // + isNewPeak = false; + isNewPeakOverLast = false; + isNewPeakUnderLast = false; + + // + isNewVale = false; + isNewValeOverLast = false; + isNewValeUnderLast = false; + + // + // STR ... + + // + isStrBullish = false; + isStrBearish = false; + isStrSwitchedToBullish = false; + isStrSwitchedToBearish = false; + + // + // VWAP ... + isVWapMidBullish = false; + isVWapMidBearish = false; + isVWapMidNeutural = false; + isVWapSlowBullish = false; + isVWapSlowBearish = false; + isVWapFastBullish = false; + isVWapFastBearish = false; + isVWapFastOverMid = false; + isVWapMidOverSlow = false; + isVWapFastNeutural = false; + isVWapSlowNeutural = false; + isVWapFastUnderMid = false; + isVWapMidUnderSlow = false; + isVWapBullishState = false; + isVWapBearishState = false; + isVWapNeuturalState = false; + isVWapBullishOrdered = false; + isVWapBearishOrdered = false; + isVWapSwitchedToBullishState = false; + isVWapSwitchedToBearishState = false; + isVWapSwitchedToNeuturalState = false; + isVWapSwitchedToBullishOrdered = false; + isVWapSwitchedToBearishOrdered = false; + + // + // X3MA ... + isX3MaMidBullish = false; + isX3MaMidBearish = false; + isX3MaFastBullish = false; + isX3MaFastBearish = false; + isX3MaMidNeutural = false; + isX3MaSlowBullish = false; + isX3MaSlowBearish = false; + isX3MaFastOverMid = false; + isX3MaMidOverSlow = false; + isX3MaFastNeutural = false; + isX3MaSlowNeutural = false; + isX3MaFastUnderMid = false; + isX3MaMidUnderSlow = false; + isX3MaBullishState = false; + isX3MaBearishState = false; + isX3MaNeuturalState = false; + isX3MaBullishOrdered = false; + isX3MaBearishOrdered = false; + isX3MaSwitchedToBullishState = false; + isX3MaSwitchedToBearishState = false; + isX3MaSwitchedToNeuturalState = false; + isX3MaSwitchedToBullishOrdered = false; + isX3MaSwitchedToBearishOrdered = false; + + // + // CHE ... + + // + isCheBullish = false; + isCheBearish = false; + isChe1Bullish = false; + isChe1Bearish = false; + isChe2Bullish = false; + isChe2Bearish = false; + isClosedOverCheMin = false; + isClosedOverCheMax = false; + isClosedUnderCheMin = false; + isClosedUnderCheMax = false; + isCheSwitchedToBullish = false; + isCheSwitchedToBearish = false; + isChe1SwitchedToBullish = false; + isChe1SwitchedToBearish = false; + isChe2SwitchedToBullish = false; + isChe2SwitchedToBearish = false; + + // + // XHK ... + isSMHKBullish = false; + isRawHKBullish = false; + isSMHKBearish = false; + isRawHKBearish = false; + isClosedOverSMHK = false; + isClosedUnderSMHK = false; + isClosedOverRawHK = false; + isClosedUnderRawHK = false; + isRawHKClosedOverSMHK = false; + isSMHKSwitchedToBearish = false; + isRawHKSwitchedToBearish = false; + isRawHKClosedUnderSMHK = false; + isSMHKSwitchedToBullish = false; + isRawHKSwitchedToBullish = false; + + // + // XICH ... + isSenkouSpanAOverB = false; + isSenkouSpanAUnderB = false; + isTenkanSenOverKijunSen = false; + isTenkanSenUnderKijunSen = false; + isSenkouSpanACrossedOverB = false; + isSenkouSpanACrossedUnderB = false; + isTenkanSenCrossedOverKijunSen = false; + isTenkanSenCrossedUnderKijunSen = false; + + // + // XDELTA ... + + // + isDeltaBullish = false; + isDeltaBearish = false; + isDeltaSwitchedToBullish = false; + isDeltaSwitchedToBearish = false; + + // + isDeltaOverMa = false; + isDeltaUnderMa = false; + isDeltaCrossedOverMa = false; + isDeltaCrossedUnderMa = false; + + // + // XVOLUME ... + + // + isBullishVolumeOverMa = false; + isBullishVolumeCrossedOverMa = false; + + // + isBullishVolumeUnderMa = false; + isBullishVolumeCrossedUnderMa = false; + + // + isBullishVolumeIncreased = false; + isBullishVolumeSwitchedToIncreased = false; + + // + isBullishVolumeDecreased = false; + isBullishVolumeSwitchedToDecreased = false; + + // + isBearishVolumeOverMa = false; + isBearishVolumeCrossedOverMa = false; + + // + isBearishVolumeUnderMa = false; + isBearishVolumeCrossedUnderMa = false; + + // + isBearishVolumeIncreased = false; + isBearishVolumeSwitchedToIncreased = false; + + // + isBearishVolumeDecreased = false; + isBearishVolumeSwitchedToDecreased = false; + + // + isVolumeSwitchedToBullish = false; + isVolumeSwitchedToBearish = false; + + // + isBullishVolumeMaOverBearishVolumeMa = false; + isBullishVolumeMaUnderBearishVolumeMa = false; + + // + // Complex Conditions ... + + // + isSarIncreased = false; + isSarDecreased = false; + isX3MaFatsOverMid = false; + isSarEqualsToPeak = false; + isSarEqualsToVale = false; + isStrEqualsToPeak = false; + isStrEqualsToVale = false; + isX3MaFatsUnderMid = false; + isX3MaFatsOverSlow = false; + isAtrUpperOverPeak = false; + isPeakOverAtrUpper = false; + isStrUpperOverPeak = false; + isStrLowerOverVale = false; + isClosedOverCheMin = false; + isClosedOverCheMax = false; + isX3MaFatsUnderSlow = false; + isAtrLowerUnderVale = false; + isClosedOverX3MaMin = false; + isClosedOverX3MaMax = false; + isValeUnderAtrLower = false; + isStrUpperUnderPeak = false; + isStrLowerUnderVale = false; + isClosedUnderCheMin = false; + isClosedUnderCheMax = false; + isClosedOverVWapMin = false; + isClosedOverVWapMax = false; + isClosedUnderX3MaMin = false; + isClosedUnderX3MaMax = false; + isStrCrossedOverVale = false; + isSarCrossedOverVale = false; + isClosedUnderVWapMin = false; + isClosedUnderVWapMax = false; + isX3MaFatsOverMidPrev = false; + isSarCrossedUnderPeak = false; + isStrCrossedUnderPeak = false; + isNewPeakOverAtrUpper = false; + isX3MaFatsUnderMidPrev = false; + isX3MaFatsOverSlowPrev = false; + isAtrUpperEqualsToPeak = false; + isAtrLowerEqualsToVale = false; + isStrUpperOverAtrUpper = false; + isStrLowerOverAtrLower = false; + isNewValeUnderAtrLower = false; + isAtrUpperCrossedUpPeak = false; + isAtrLowerCrossedUpVale = false; + isStrUpperUnderAtrUpper = false; + isStrLowerUnderAtrLower = false; + isX3MaFatsUnderSlowPrev = false; + isX3MaFastCrossedOverMid = false; + isVWapFastCrossedOverMid = false; + isX3MaFastCrossedUnderMid = false; + isX3MaFastCrossedOverSlow = false; + isAtrUpperCrossedDownPeak = false; + isAtrLowerCrossedDownVale = false; + isStrLowerOverDonLowLower = false; + isVWapFastCrossedUnderMid = false; + isStrUpperCrossedOverPeak = false; + isStrLowerCrossedOverVale = false; + isDonLowLowerEqualsToVale = false; + isVWapFastCrossedOverSlow = false; + isX3MaFastCrossedUnderSlow = false; + isStrUpperOverDonHighUpper = false; + isStrLowerUnderDonLowLower = false; + isVWapFastCrossedUnderSlow = false; + isStrUpperCrossedUnderPeak = false; + isStrLowerCrossedUnderVale = false; + isDonHighUpperEqualsToPeak = false; + isStrUpperUnderDonHighUpper = false; + isStrUpperCrossedOverAtrUpper = false; + isStrLowerCrossedOverAtrLower = false; + isStrUpperCrossedUnderAtrUpper = false; + isStrLowerCrossedUnderAtrLower = false; + isStrLowerCrossedOverDonLowLower = false; + isStrUpperCrossedOverDonHighUpper = false; + isStrLowerCrossedUnderDonLowLower = false; + isStrUpperCrossedUnderDonHighUpper = false; + + // + ZeroMemory(this); + } + + /** + * Generate Conditions Scores ... + * + * @param bullishScore: Double, Directional Scores Reference ... + * @param bearishScore: Double, Directional Scores Reference ... + */ + void GenerateScore( + double &bullishScore, + double &bearishScore // + ) + { + // + bullishScore = 0; + bearishScore = 0; + + // + double score = 1; + double minScore = 0.5; + double highScore = 1.5; + + // + // SLOPES ... + + // + if (isRsiSlopeBullish) + { + bullishScore += minScore; + } + if (isStrSlopeBullish) + { + bullishScore += minScore; + } + if (isAtrUpperSlopeBullish) + { + bullishScore += minScore; + } + if (isAtrLowerSlopeBullish) + { + bullishScore += minScore; + } + if (isVwapFastSlopeBullish) + { + bullishScore += minScore; + } + if (isVwapMidSlopeBullish) + { + bullishScore += minScore; + } + if (isVwapSlowSlopeBullish) + { + bullishScore += minScore; + } + + // + if (isRsiSlopeBearish) + { + bearishScore += minScore; + } + if (isStrSlopeBearish) + { + bearishScore += minScore; + } + if (isAtrUpperSlopeBearish) + { + bearishScore += minScore; + } + if (isAtrLowerSlopeBearish) + { + bearishScore += minScore; + } + if (isVwapFastSlopeBearish) + { + bearishScore += minScore; + } + if (isVwapMidSlopeBearish) + { + bearishScore += minScore; + } + if (isVwapSlowSlopeBearish) + { + bearishScore += minScore; + } + + // + // COMPLEX ... + + // + if (isRsiOverSold) + { + bullishScore += score; + } + if (isRsiCrossedUnderOverSold) + { + bullishScore += highScore; + } + + // + if (isRsiOverBought) + { + bearishScore += score; + } + if (isRsiCrossedOverOverBought) + { + bearishScore += highScore; + } + + // + // XSAR ... + + // + if (isSarBullish) + { + bullishScore += minScore; + } + if (isSarSwitchedToBullish) + { + bullishScore += score; + } + + // + if (isSarBearish) + { + bearishScore += minScore; + } + if (isSarSwitchedToBearish) + { + bearishScore += score; + } + + // + // XSTR ... + + // + if (isStrBullish) + { + bullishScore += minScore; + } + if (isStrSwitchedToBullish) + { + bullishScore += score; + } + + // + if (isStrBearish) + { + bearishScore += minScore; + } + if (isStrSwitchedToBearish) + { + bearishScore += score; + } + + // + // XCHE ... + + // + if (isCheBullish) + { + bullishScore += score; + } + if (isCheSwitchedToBullish) + { + bullishScore += highScore; + } + if (isChe1Bullish && + !isCheBullish && + !isCheSwitchedToBullish) + { + bullishScore += minScore; + } + if (isChe1SwitchedToBullish && + !isCheBullish && + !isCheSwitchedToBullish) + { + bullishScore += minScore; + } + + // + if (isCheBearish) + { + bearishScore += score; + } + if (isCheSwitchedToBearish) + { + bearishScore += highScore; + } + if (isChe1Bearish && + !isCheBearish && + !isCheSwitchedToBearish) + { + bearishScore += minScore; + } + if (isChe1SwitchedToBearish && + !isCheBearish && + !isCheSwitchedToBearish) + { + bearishScore += minScore; + } + + // + // XVWAP ... + + // + if (isVWapBullishState) + { + bullishScore += score; + } + if (isVWapBullishOrdered) + { + bullishScore += score; + } + if (isVWapSwitchedToBullishState) + { + bullishScore += highScore; + } + if (isVWapSwitchedToBullishOrdered) + { + bullishScore += highScore; + } + if (!isVWapBullishState && + !isVWapSwitchedToBullishState) + { + // + if (isVWapFastBullish) + { + bullishScore += minScore; + } + if (isVWapSlowBullish) + { + bullishScore += minScore; + } + } + if (!isVWapBullishOrdered && + !isVWapSwitchedToBullishOrdered) + { + // + if (isVWapFastOverMid) + { + bullishScore += minScore; + } + if (isVWapMidOverSlow) + { + bullishScore += minScore; + } + } + + // + if (isVWapBearishState) + { + bearishScore += score; + } + if (isVWapBearishOrdered) + { + bearishScore += score; + } + if (isVWapSwitchedToBearishState) + { + bearishScore += highScore; + } + if (isVWapSwitchedToBearishOrdered) + { + bearishScore += highScore; + } + if (!isVWapBearishState && + !isVWapSwitchedToBearishState) + { + // + if (isVWapFastBearish) + { + bearishScore += minScore; + } + if (isVWapSlowBearish) + { + bearishScore += minScore; + } + } + if (!isVWapBearishOrdered && + !isVWapSwitchedToBearishOrdered) + { + // + if (isVWapFastUnderMid) + { + bearishScore += minScore; + } + if (isVWapMidUnderSlow) + { + bearishScore += minScore; + } + } + + // + // X3MA ... + + // + if (isX3MaBullishState) + { + bullishScore += score; + } + if (isX3MaBullishOrdered) + { + bullishScore += score; + } + if (isX3MaSwitchedToBullishState) + { + bullishScore += highScore; + } + if (isX3MaSwitchedToBullishOrdered) + { + bullishScore += highScore; + } + if (!isX3MaBullishState && + !isX3MaSwitchedToBullishState) + { + // + if (isX3MaFastBullish) + { + bullishScore += minScore; + } + if (isX3MaSlowBullish) + { + bullishScore += minScore; + } + } + if (!isX3MaBullishOrdered && + !isX3MaSwitchedToBullishOrdered) + { + // + if (isX3MaFastOverMid) + { + bullishScore += minScore; + } + if (isX3MaMidOverSlow) + { + bullishScore += minScore; + } + } + + // + if (isX3MaBearishState) + { + bearishScore += score; + } + if (isX3MaBearishOrdered) + { + bearishScore += score; + } + if (isX3MaSwitchedToBearishState) + { + bearishScore += highScore; + } + if (isX3MaSwitchedToBearishOrdered) + { + bearishScore += highScore; + } + if (!isX3MaBearishState && + !isX3MaSwitchedToBearishState) + { + // + if (isX3MaFastBearish) + { + bearishScore += minScore; + } + if (isX3MaSlowBearish) + { + bearishScore += minScore; + } + } + if (!isX3MaBearishOrdered && + !isX3MaSwitchedToBearishOrdered) + { + // + if (isX3MaFastUnderMid) + { + bearishScore += minScore; + } + if (isX3MaMidUnderSlow) + { + bearishScore += minScore; + } + } + + // + // XSMHK ... + + // + if (isSMHKBullish) + { + bullishScore += minScore; + } + if (isRawHKBullish) + { + bullishScore += minScore; + } + if (isClosedOverSMHK) + { + bullishScore += minScore; + } + if (isClosedOverRawHK) + { + bullishScore += minScore; + } + if (isRawHKClosedOverSMHK) + { + bullishScore += minScore; + } + if (isSMHKSwitchedToBullish) + { + bullishScore += highScore; + } + if (isRawHKSwitchedToBullish) + { + bullishScore += highScore; + } + + // + if (isSMHKBearish) + { + bearishScore += minScore; + } + if (isRawHKBearish) + { + bearishScore += minScore; + } + if (isClosedUnderSMHK) + { + bearishScore += minScore; + } + if (isClosedUnderRawHK) + { + bearishScore += minScore; + } + if (isRawHKClosedUnderSMHK) + { + bearishScore += minScore; + } + if (isSMHKSwitchedToBearish) + { + bearishScore += highScore; + } + if (isRawHKSwitchedToBullish) + { + bearishScore += highScore; + } + + // + // XICH ... + if (isSenkouSpanAOverB) + { + bullishScore += minScore; + } + if (isTenkanSenOverKijunSen) + { + bullishScore += minScore; + } + if (isSenkouSpanACrossedOverB) + { + bullishScore += highScore; + } + if (isTenkanSenCrossedOverKijunSen) + { + bullishScore += highScore; + } + if (isSenkouSpanAUnderB) + { + bearishScore += minScore; + } + if (isTenkanSenUnderKijunSen) + { + bearishScore += minScore; + } + if (isSenkouSpanACrossedUnderB) + { + bearishScore += highScore; + } + if (isTenkanSenCrossedUnderKijunSen) + { + bearishScore += highScore; + } + + // + // Complex Conditions ... + + // + if (isSarIncreased) + { + bullishScore += minScore; + } + if (isSarEqualsToVale) + { + bullishScore += minScore; + } + if (isSarCrossedOverVale) + { + bullishScore += score; + } + + // + if (isAtrLowerUnderVale) + { + bullishScore += minScore; + } + if (isValeUnderAtrLower) + { + bullishScore += minScore; + } + if (isNewValeUnderAtrLower) + { + bullishScore += minScore; + } + if (isAtrLowerEqualsToVale) + { + bullishScore += minScore; + } + if (isStrLowerOverAtrLower) + { + bullishScore += minScore; + } + if (isStrUpperOverAtrUpper) + { + bullishScore += minScore; + } + if (isAtrLowerCrossedUpVale) + { + bullishScore += score; + } + if (isAtrUpperCrossedUpPeak) + { + bullishScore += score; + } + if (isStrLowerCrossedOverAtrLower) + { + bullishScore += score; + } + if (isStrUpperCrossedOverAtrUpper) + { + bullishScore += score; + } + + // + if (isStrEqualsToVale) + { + bullishScore += minScore; + } + if (isStrLowerOverVale) + { + bullishScore += minScore; + } + if (isStrLowerUnderVale) + { + bullishScore += minScore; + } + if (isStrCrossedOverVale) + { + bullishScore += score; + } + if (isStrUpperCrossedOverPeak) + { + bullishScore += score; + } + if (isStrLowerCrossedOverVale) + { + bullishScore += score; + } + if (isStrLowerUnderDonLowLower) + { + bullishScore += minScore; + } + if (isStrLowerCrossedOverDonLowLower) + { + bullishScore += score; + } + if (isStrUpperCrossedOverDonHighUpper) + { + bullishScore += score; + } + + // + if (isClosedOverVWapMin) + { + bullishScore += minScore; + } + if (isClosedOverVWapMax) + { + bullishScore += minScore; + } + if (isVWapFastCrossedOverMid) + { + bullishScore += score; + } + if (isVWapFastCrossedOverSlow) + { + bullishScore += score; + } + + // + if (isClosedOverX3MaMin) + { + bullishScore += minScore; + } + if (isClosedOverX3MaMax) + { + bullishScore += minScore; + } + if (isX3MaFastCrossedOverMid) + { + bullishScore += score; + } + if (isX3MaFastCrossedOverSlow) + { + bullishScore += score; + } + + // + if (isClosedOverCheMin) + { + bullishScore += minScore; + } + if (isClosedOverCheMax) + { + bullishScore += minScore; + } + if (isDonLowLowerEqualsToVale) + { + bullishScore += minScore; + } + + // + // XDELTA ... + + // + if (isDeltaOverMa) + { + bullishScore += minScore; + } + if (isDeltaBullish) + { + bullishScore += minScore; + } + if (isDeltaCrossedOverMa) + { + bullishScore += score; + } + if (isDeltaSwitchedToBullish) + { + bullishScore += score; + } + + if (isDeltaBearish) + { + bearishScore += minScore; + } + if (isDeltaUnderMa) + { + bearishScore += minScore; + } + if (isDeltaCrossedUnderMa) + { + bearishScore += score; + } + if (isDeltaSwitchedToBearish) + { + bearishScore += score; + } + + // + // XVOLUME ... + + // + if (isBullishVolumeOverMa) + { + bullishScore += minScore; + } + if (isBearishVolumeUnderMa) + { + bullishScore += minScore; + } + if (isBullishVolumeIncreased) + { + bullishScore += minScore; + } + if (isBearishVolumeDecreased) + { + bullishScore += minScore; + } + if (isBullishVolumeMaOverBearishVolumeMa) + { + bullishScore += minScore; + } + + // + if (isVolumeSwitchedToBullish) + { + bullishScore += score; + } + if (isBullishVolumeCrossedOverMa) + { + bullishScore += score; + } + if (isBearishVolumeCrossedUnderMa) + { + bullishScore += score; + } + if (isBullishVolumeSwitchedToIncreased) + { + bullishScore += score; + } + if (isBearishVolumeSwitchedToDecreased) + { + bullishScore += score; + } + + // + if (isBearishVolumeOverMa) + { + bearishScore += minScore; + } + if (isBullishVolumeUnderMa) + { + bearishScore += minScore; + } + if (isBullishVolumeDecreased) + { + bearishScore += minScore; + } + if (isBearishVolumeIncreased) + { + bearishScore += minScore; + } + if (isBullishVolumeMaUnderBearishVolumeMa) + { + bearishScore += minScore; + } + + // + if (isVolumeSwitchedToBearish) + { + bearishScore += score; + } + if (isBearishVolumeCrossedOverMa) + { + bearishScore += score; + } + if (isBullishVolumeCrossedUnderMa) + { + bearishScore += score; + } + if (isBullishVolumeSwitchedToDecreased) + { + bearishScore += score; + } + if (isBearishVolumeSwitchedToIncreased) + { + bearishScore += score; + } + + // + // + // + + // + if (isSarDecreased) + { + bearishScore += minScore; + } + if (isSarEqualsToPeak) + { + bearishScore += minScore; + } + if (isSarCrossedUnderPeak) + { + bearishScore += score; + } + + // + if (isAtrUpperOverPeak) + { + bearishScore += minScore; + } + if (isPeakOverAtrUpper) + { + bearishScore += minScore; + } + if (isNewPeakOverAtrUpper) + { + bearishScore += minScore; + } + if (isAtrUpperEqualsToPeak) + { + bearishScore += minScore; + } + if (isStrLowerUnderAtrLower) + { + bearishScore += minScore; + } + if (isStrUpperUnderAtrUpper) + { + bearishScore += minScore; + } + if (isAtrLowerCrossedDownVale) + { + bearishScore += score; + } + if (isAtrUpperCrossedDownPeak) + { + bearishScore += score; + } + if (isStrLowerCrossedUnderAtrLower) + { + bearishScore += score; + } + if (isStrUpperCrossedUnderAtrUpper) + { + bearishScore += score; + } + + // + if (isStrEqualsToPeak) + { + bearishScore += minScore; + } + if (isStrUpperOverPeak) + { + bearishScore += minScore; + } + if (isStrUpperUnderPeak) + { + bearishScore += minScore; + } + if (isStrCrossedUnderPeak) + { + bearishScore += score; + } + if (isStrLowerOverDonLowLower) + { + bearishScore += minScore; + } + if (isStrUpperOverDonHighUpper) + { + bearishScore += minScore; + } + if (isStrUpperCrossedUnderPeak) + { + bearishScore += score; + } + if (isStrLowerCrossedUnderVale) + { + bearishScore += score; + } + if (isStrUpperUnderDonHighUpper) + { + bearishScore += minScore; + } + if (isStrLowerCrossedUnderDonLowLower) + { + bearishScore += score; + } + if (isStrUpperCrossedUnderDonHighUpper) + { + bearishScore += score; + } + + // + if (isClosedUnderVWapMin) + { + bearishScore += minScore; + } + if (isClosedUnderVWapMax) + { + bearishScore += minScore; + } + if (isVWapFastCrossedUnderMid) + { + bearishScore += score; + } + if (isVWapFastCrossedUnderSlow) + { + bearishScore += score; + } + + // + if (isClosedUnderX3MaMin) + { + bearishScore += minScore; + } + if (isClosedUnderX3MaMax) + { + bearishScore += minScore; + } + if (isX3MaFastCrossedUnderMid) + { + bearishScore += score; + } + if (isX3MaFastCrossedUnderSlow) + { + bearishScore += score; + } + + // + if (isClosedUnderCheMin) + { + bearishScore += minScore; + } + if (isClosedUnderCheMax) + { + bearishScore += minScore; + } + if (isDonHighUpperEqualsToPeak) + { + bearishScore += minScore; + } + + // + // + // + } + + /** + * Generate Summary String for Represent Conditions State ... + * + * @param onlyCommons: Boolean, Just Generate Only Commons Conditions ... + * @param onlyConditions: Boolean, Just Generate Only Conditions ... + * @param includeScores: Boolean, Attach Scores Representations on Result ... + * @param ignoreFalseConditions: Boolean, Ignore False Conditions on Result ... + * @param separator: String, Separate Lines ... + * + * @return ( string ) + */ + string GenerateSummary( + bool onlyCommons = false, + bool onlyConditions = false, + bool includeScores = true, + bool ignoreFalseConditions = true, + string separator = "\n" // + ) + { + // + string result = NULL; + + // + double bullishScore = 0; + double bearishScore = 0; + GenerateScore( + bullishScore, + bearishScore // + ); + + // + string scoresStr = + // + "Scores: " + separator + + "---------------" + separator + + "Bullish: " + ToString(bullishScore) + separator + + "Bearish: " + ToString(bearishScore) + separator + + "" + // + ; + + // + string commonStr = GenerateSpecifiedCommonSummary( + this, + separator, + includeScores // + ); + + // + string conditionsStr = + // + "-----------------------" + separator + + "SAR ..." + separator + + "-----------------------" + separator + + ToString("isSarBullish", isSarBullish, ignoreFalseConditions, separator) + + ToString("isSarBearish", isSarBearish, ignoreFalseConditions, separator) + + ToString("isSarSwitchedToBullish", isSarSwitchedToBullish, ignoreFalseConditions, separator) + + ToString("isSarSwitchedToBearish", isSarSwitchedToBearish, ignoreFalseConditions, separator) + + // + "-----------------------" + separator + + "STR ..." + separator + + "-----------------------" + separator + + ToString("isStrBullish", isStrBullish, ignoreFalseConditions, separator) + + ToString("isStrBearish", isStrBearish, ignoreFalseConditions, separator) + + ToString("isStrSwitchedToBullish", isStrSwitchedToBullish, ignoreFalseConditions, separator) + + ToString("isStrSwitchedToBearish", isStrSwitchedToBearish, ignoreFalseConditions, separator) + + // + "-----------------------" + separator + + "PV ..." + separator + + "-----------------------" + separator + + ToString("isNewPeak", isNewPeak, ignoreFalseConditions, separator) + + ToString("isNewPeakOverLast", isNewPeakOverLast, ignoreFalseConditions, separator) + + ToString("isNewPeakUnderLast", isNewPeakUnderLast, ignoreFalseConditions, separator) + + ToString("isNewVale", isNewVale, ignoreFalseConditions, separator) + + ToString("isNewValeOverLast", isNewValeOverLast, ignoreFalseConditions, separator) + + ToString("isNewValeUnderLast", isNewValeUnderLast, ignoreFalseConditions, separator) + + // + "-----------------------" + separator + + "> RSI ..." + separator + + "-----------------------" + separator + + ToString("isRsiOverBought", isRsiOverBought, ignoreFalseConditions, separator) + + ToString("isRsiCrossedOverOverBought", isRsiCrossedOverOverBought, ignoreFalseConditions, separator) + + ToString("isRsiCrossedUnderOverBought", isRsiCrossedUnderOverBought, ignoreFalseConditions, separator) + + ToString("isRsiOverSold", isRsiOverSold, ignoreFalseConditions, separator) + + ToString("isRsiCrossedUnderOverSold", isRsiCrossedUnderOverSold, ignoreFalseConditions, separator) + + ToString("isRsiCrossedOverOverSold", isRsiCrossedOverOverSold, ignoreFalseConditions, separator) + + // + "-----------------------" + separator + + "ATR ..." + separator + + "-----------------------" + separator + + ToString("isClosedOverAtrUpper", isClosedOverAtrUpper, ignoreFalseConditions, separator) + + ToString("isClosedOverAtrLower", isClosedOverAtrLower, ignoreFalseConditions, separator) + + ToString("isClosedUnderAtrUpper", isClosedUnderAtrUpper, ignoreFalseConditions, separator) + + ToString("isClosedUnderAtrLower", isClosedUnderAtrLower, ignoreFalseConditions, separator) + + // + "-----------------------" + separator + + "DON ..." + separator + + "-----------------------" + separator + + // + "-----------------------" + separator + + "VWAP ..." + separator + + "-----------------------" + separator + + ToString("isVWapFastBullish", isVWapFastBullish, ignoreFalseConditions, separator) + + ToString("isVWapFastBearish", isVWapFastBearish, ignoreFalseConditions, separator) + + ToString("isVWapFastNeutural", isVWapFastNeutural, ignoreFalseConditions, separator) + + ToString("isVWapMidBullish", isVWapMidBullish, ignoreFalseConditions, separator) + + ToString("isVWapMidBearish", isVWapMidBearish, ignoreFalseConditions, separator) + + ToString("isVWapMidNeutural", isVWapMidNeutural, ignoreFalseConditions, separator) + + ToString("isVWapSlowBullish", isVWapSlowBullish, ignoreFalseConditions, separator) + + ToString("isVWapSlowBearish", isVWapSlowBearish, ignoreFalseConditions, separator) + + ToString("isVWapSlowNeutural", isVWapSlowNeutural, ignoreFalseConditions, separator) + + ToString("isVWapFastOverMid", isVWapFastOverMid, ignoreFalseConditions, separator) + + ToString("isVWapMidOverSlow", isVWapMidOverSlow, ignoreFalseConditions, separator) + + ToString("isVWapFastUnderMid", isVWapFastUnderMid, ignoreFalseConditions, separator) + + ToString("isVWapMidUnderSlow", isVWapMidUnderSlow, ignoreFalseConditions, separator) + + ToString("isVWapBullishState", isVWapBullishState, ignoreFalseConditions, separator) + + ToString("isVWapBearishState", isVWapBearishState, ignoreFalseConditions, separator) + + ToString("isVWapNeuturalState", isVWapNeuturalState, ignoreFalseConditions, separator) + + ToString("isVWapBullishOrdered", isVWapBullishOrdered, ignoreFalseConditions, separator) + + ToString("isVWapBearishOrdered", isVWapBearishOrdered, ignoreFalseConditions, separator) + + ToString("isVWapSwitchedToBullishOrdered", isVWapSwitchedToBullishOrdered, ignoreFalseConditions, separator) + + ToString("isVWapSwitchedToBearishOrdered", isVWapSwitchedToBearishOrdered, ignoreFalseConditions, separator) + + ToString("isVWapSwitchedToBullishState", isVWapSwitchedToBullishState, ignoreFalseConditions, separator) + + ToString("isVWapSwitchedToBearishState", isVWapSwitchedToBearishState, ignoreFalseConditions, separator) + + ToString("isVWapSwitchedToNeuturalState", isVWapSwitchedToNeuturalState, ignoreFalseConditions, separator) + + // + "-----------------------" + separator + + "X3MA ..." + separator + + "-----------------------" + separator + + ToString("isX3MaMidBullish", isX3MaMidBullish, ignoreFalseConditions, separator) + + ToString("isX3MaMidBearish", isX3MaMidBearish, ignoreFalseConditions, separator) + + ToString("isX3MaFastBullish", isX3MaFastBullish, ignoreFalseConditions, separator) + + ToString("isX3MaFastBearish", isX3MaFastBearish, ignoreFalseConditions, separator) + + ToString("isX3MaMidNeutural", isX3MaMidNeutural, ignoreFalseConditions, separator) + + ToString("isX3MaSlowBullish", isX3MaSlowBullish, ignoreFalseConditions, separator) + + ToString("isX3MaSlowBearish", isX3MaSlowBearish, ignoreFalseConditions, separator) + + ToString("isX3MaFastOverMid", isX3MaFastOverMid, ignoreFalseConditions, separator) + + ToString("isX3MaMidOverSlow", isX3MaMidOverSlow, ignoreFalseConditions, separator) + + ToString("isX3MaFastNeutural", isX3MaFastNeutural, ignoreFalseConditions, separator) + + ToString("isX3MaSlowNeutural", isX3MaSlowNeutural, ignoreFalseConditions, separator) + + ToString("isX3MaFastUnderMid", isX3MaFastUnderMid, ignoreFalseConditions, separator) + + ToString("isX3MaMidUnderSlow", isX3MaMidUnderSlow, ignoreFalseConditions, separator) + + ToString("isX3MaBullishState", isX3MaBullishState, ignoreFalseConditions, separator) + + ToString("isX3MaBearishState", isX3MaBearishState, ignoreFalseConditions, separator) + + ToString("isX3MaNeuturalState", isX3MaNeuturalState, ignoreFalseConditions, separator) + + ToString("isX3MaBullishOrdered", isX3MaBullishOrdered, ignoreFalseConditions, separator) + + ToString("isX3MaBearishOrdered", isX3MaBearishOrdered, ignoreFalseConditions, separator) + + ToString("isX3MaSwitchedToBullishState", isX3MaSwitchedToBullishState, ignoreFalseConditions, separator) + + ToString("isX3MaSwitchedToBearishState", isX3MaSwitchedToBearishState, ignoreFalseConditions, separator) + + ToString("isX3MaSwitchedToNeuturalState", isX3MaSwitchedToNeuturalState, ignoreFalseConditions, separator) + + ToString("isX3MaSwitchedToBullishOrdered", isX3MaSwitchedToBullishOrdered, ignoreFalseConditions, separator) + + ToString("isX3MaSwitchedToBearishOrdered", isX3MaSwitchedToBearishOrdered, ignoreFalseConditions, separator) + + // + "-----------------------" + separator + + "CHE ..." + separator + + "-----------------------" + separator + + ToString("isChe1Bullish", isChe1Bullish, ignoreFalseConditions, separator) + + ToString("isChe1Bearish", isChe1Bearish, ignoreFalseConditions, separator) + + ToString("isChe1SwitchedToBullish", isChe1SwitchedToBullish, ignoreFalseConditions, separator) + + ToString("isChe1SwitchedToBearish", isChe1SwitchedToBearish, ignoreFalseConditions, separator) + + ToString("isChe2Bullish", isChe2Bullish, ignoreFalseConditions, separator) + + ToString("isChe2Bearish", isChe2Bearish, ignoreFalseConditions, separator) + + ToString("isChe2SwitchedToBullish", isChe2SwitchedToBullish, ignoreFalseConditions, separator) + + ToString("isChe2SwitchedToBearish", isChe2SwitchedToBearish, ignoreFalseConditions, separator) + + ToString("isCheBullish", isCheBullish, ignoreFalseConditions, separator) + + ToString("isCheBearish", isCheBearish, ignoreFalseConditions, separator) + + ToString("isCheSwitchedToBullish", isCheSwitchedToBullish, ignoreFalseConditions, separator) + + ToString("isCheSwitchedToBearish", isCheSwitchedToBearish, ignoreFalseConditions, separator) + + ToString("isClosedOverCheMin", isClosedOverCheMin, ignoreFalseConditions, separator) + + ToString("isClosedOverCheMax", isClosedOverCheMax, ignoreFalseConditions, separator) + + ToString("isClosedUnderCheMin", isClosedUnderCheMin, ignoreFalseConditions, separator) + + ToString("isClosedUnderCheMax", isClosedUnderCheMax, ignoreFalseConditions, separator) + + // + "-----------------------" + separator + + "HK ..." + separator + + "-----------------------" + separator + + ToString("isSMHKBullish", isSMHKBullish, ignoreFalseConditions, separator) + + ToString("isRawHKBullish", isRawHKBullish, ignoreFalseConditions, separator) + + ToString("isSMHKBearish", isSMHKBearish, ignoreFalseConditions, separator) + + ToString("isRawHKBearish", isRawHKBearish, ignoreFalseConditions, separator) + + ToString("isClosedOverSMHK", isClosedOverSMHK, ignoreFalseConditions, separator) + + ToString("isClosedUnderSMHK", isClosedUnderSMHK, ignoreFalseConditions, separator) + + ToString("isClosedOverRawHK", isClosedOverRawHK, ignoreFalseConditions, separator) + + ToString("isClosedUnderRawHK", isClosedUnderRawHK, ignoreFalseConditions, separator) + + ToString("isRawHKClosedOverSMHK", isRawHKClosedOverSMHK, ignoreFalseConditions, separator) + + ToString("isSMHKSwitchedToBearish", isSMHKSwitchedToBearish, ignoreFalseConditions, separator) + + ToString("isRawHKSwitchedToBearish", isRawHKSwitchedToBearish, ignoreFalseConditions, separator) + + ToString("isRawHKClosedUnderSMHK", isRawHKClosedUnderSMHK, ignoreFalseConditions, separator) + + ToString("isSMHKSwitchedToBullish", isSMHKSwitchedToBullish, ignoreFalseConditions, separator) + + ToString("isRawHKSwitchedToBullish", isRawHKSwitchedToBullish, ignoreFalseConditions, separator) + + // + "-----------------------" + separator + + "XICH ..." + separator + + "-----------------------" + separator + + ToString("isTenkanSenOverKijunSen", isTenkanSenOverKijunSen, ignoreFalseConditions, separator) + + ToString("isTenkanSenUnderKijunSen", isTenkanSenUnderKijunSen, ignoreFalseConditions, separator) + + ToString("isTenkanSenCrossedOverKijunSen", isTenkanSenCrossedOverKijunSen, ignoreFalseConditions, separator) + + ToString("isTenkanSenCrossedUnderKijunSen", isTenkanSenCrossedUnderKijunSen, ignoreFalseConditions, separator) + + ToString("isSenkouSpanAOverB", isSenkouSpanAOverB, ignoreFalseConditions, separator) + + ToString("isSenkouSpanAUnderB", isSenkouSpanAUnderB, ignoreFalseConditions, separator) + + ToString("isSenkouSpanACrossedOverB", isSenkouSpanACrossedOverB, ignoreFalseConditions, separator) + + ToString("isSenkouSpanACrossedUnderB", isSenkouSpanACrossedUnderB, ignoreFalseConditions, separator) + + // + "-----------------------" + separator + + "XDELTA ..." + separator + + "-----------------------" + separator + + ToString("isDeltaBullish", isDeltaBullish, ignoreFalseConditions, separator) + + ToString("isDeltaBearish", isDeltaBearish, ignoreFalseConditions, separator) + + ToString("isDeltaSwitchedToBullish", isDeltaSwitchedToBullish, ignoreFalseConditions, separator) + + ToString("isDeltaSwitchedToBearish", isDeltaSwitchedToBearish, ignoreFalseConditions, separator) + + ToString("isDeltaOverMa", isDeltaOverMa, ignoreFalseConditions, separator) + + ToString("isDeltaUnderMa", isDeltaUnderMa, ignoreFalseConditions, separator) + + ToString("isDeltaCrossedOverMa", isDeltaCrossedOverMa, ignoreFalseConditions, separator) + + ToString("isDeltaCrossedUnderMa", isDeltaCrossedUnderMa, ignoreFalseConditions, separator) + + // + "-----------------------" + separator + + "XVOLUME ..." + separator + + "-----------------------" + separator + + ToString("isBullishVolumeOverMa", isBullishVolumeOverMa, ignoreFalseConditions, separator) + + ToString("isBullishVolumeCrossedOverMa", isBullishVolumeCrossedOverMa, ignoreFalseConditions, separator) + + ToString("isBullishVolumeUnderMa", isBullishVolumeUnderMa, ignoreFalseConditions, separator) + + ToString("isBullishVolumeCrossedUnderMa", isBullishVolumeCrossedUnderMa, ignoreFalseConditions, separator) + + ToString("isBullishVolumeIncreased", isBullishVolumeIncreased, ignoreFalseConditions, separator) + + ToString("isBullishVolumeSwitchedToIncreased", isBullishVolumeSwitchedToIncreased, ignoreFalseConditions, separator) + + ToString("isBullishVolumeDecreased", isBullishVolumeDecreased, ignoreFalseConditions, separator) + + ToString("isBullishVolumeSwitchedToDecreased", isBullishVolumeSwitchedToDecreased, ignoreFalseConditions, separator) + + ToString("isBearishVolumeOverMa", isBearishVolumeOverMa, ignoreFalseConditions, separator) + + ToString("isBearishVolumeCrossedOverMa", isBearishVolumeCrossedOverMa, ignoreFalseConditions, separator) + + ToString("isBearishVolumeUnderMa", isBearishVolumeUnderMa, ignoreFalseConditions, separator) + + ToString("isBearishVolumeCrossedUnderMa", isBearishVolumeCrossedUnderMa, ignoreFalseConditions, separator) + + ToString("isBearishVolumeIncreased", isBearishVolumeIncreased, ignoreFalseConditions, separator) + + ToString("isBearishVolumeSwitchedToIncreased", isBearishVolumeSwitchedToIncreased, ignoreFalseConditions, separator) + + ToString("isBearishVolumeDecreased", isBearishVolumeDecreased, ignoreFalseConditions, separator) + + ToString("isBearishVolumeSwitchedToDecreased", isBearishVolumeSwitchedToDecreased, ignoreFalseConditions, separator) + + ToString("isVolumeSwitchedToBullish", isVolumeSwitchedToBullish, ignoreFalseConditions, separator) + + ToString("isVolumeSwitchedToBearish", isVolumeSwitchedToBearish, ignoreFalseConditions, separator) + + ToString("isBullishVolumeMaOverBearishVolumeMa", isBullishVolumeMaOverBearishVolumeMa, ignoreFalseConditions, separator) + + ToString("isBullishVolumeMaUnderBearishVolumeMa", isBullishVolumeMaUnderBearishVolumeMa, ignoreFalseConditions, separator) + + // + "-----------------------" + separator + + "Slopes ..." + separator + + "-----------------------" + separator + + ToString("isRsiSlopeBullish", isRsiSlopeBullish, ignoreFalseConditions, separator) + + ToString("isStrSlopeBullish", isStrSlopeBullish, ignoreFalseConditions, separator) + + ToString("isAtrUpperSlopeBullish", isAtrUpperSlopeBullish, ignoreFalseConditions, separator) + + ToString("isAtrLowerSlopeBullish", isAtrLowerSlopeBullish, ignoreFalseConditions, separator) + + ToString("isVwapFastSlopeBullish", isVwapFastSlopeBullish, ignoreFalseConditions, separator) + + ToString("isVwapMidSlopeBullish", isVwapMidSlopeBullish, ignoreFalseConditions, separator) + + ToString("isVwapSlowSlopeBullish", isVwapSlowSlopeBullish, ignoreFalseConditions, separator) + + ToString("isRsiSlopeBearish", isRsiSlopeBearish, ignoreFalseConditions, separator) + + ToString("isStrSlopeBearish", isStrSlopeBearish, ignoreFalseConditions, separator) + + ToString("isAtrUpperSlopeBearish", isAtrUpperSlopeBearish, ignoreFalseConditions, separator) + + ToString("isAtrLowerSlopeBearish", isAtrLowerSlopeBearish, ignoreFalseConditions, separator) + + ToString("isVwapFastSlopeBearish", isVwapFastSlopeBearish, ignoreFalseConditions, separator) + + ToString("isVwapMidSlopeBearish", isVwapMidSlopeBearish, ignoreFalseConditions, separator) + + ToString("isVwapSlowSlopeBearish", isVwapSlowSlopeBearish, ignoreFalseConditions, separator) + + // + "-----------------------" + separator + + "Coplex ..." + separator + + "-----------------------" + separator + + ToString("isSarIncreased", isSarIncreased, ignoreFalseConditions, separator) + + ToString("isSarDecreased", isSarDecreased, ignoreFalseConditions, separator) + + ToString("isSarEqualsToPeak", isSarEqualsToPeak, ignoreFalseConditions, separator) + + ToString("isStrEqualsToPeak", isStrEqualsToPeak, ignoreFalseConditions, separator) + + ToString("isStrEqualsToVale", isStrEqualsToVale, ignoreFalseConditions, separator) + + ToString("isPeakOverAtrUpper", isPeakOverAtrUpper, ignoreFalseConditions, separator) + + ToString("isStrUpperOverPeak", isStrUpperOverPeak, ignoreFalseConditions, separator) + + ToString("isStrLowerOverVale", isStrLowerOverVale, ignoreFalseConditions, separator) + + ToString("isAtrUpperOverPeak", isAtrUpperOverPeak, ignoreFalseConditions, separator) + + ToString("isAtrLowerUnderVale", isAtrLowerUnderVale, ignoreFalseConditions, separator) + + ToString("isClosedOverVWapMin", isClosedOverVWapMin, ignoreFalseConditions, separator) + + ToString("isClosedOverVWapMax", isClosedOverVWapMax, ignoreFalseConditions, separator) + + ToString("isStrUpperUnderPeak", isStrUpperUnderPeak, ignoreFalseConditions, separator) + + ToString("isValeUnderAtrLower", isValeUnderAtrLower, ignoreFalseConditions, separator) + + ToString("isStrLowerUnderVale", isStrLowerUnderVale, ignoreFalseConditions, separator) + + ToString("isClosedUnderVWapMin", isClosedUnderVWapMin, ignoreFalseConditions, separator) + + ToString("isClosedUnderVWapMax", isClosedUnderVWapMax, ignoreFalseConditions, separator) + + ToString("isSarCrossedOverVale", isSarCrossedOverVale, ignoreFalseConditions, separator) + + ToString("isStrCrossedOverVale", isStrCrossedOverVale, ignoreFalseConditions, separator) + + ToString("isSarCrossedUnderPeak", isSarCrossedUnderPeak, ignoreFalseConditions, separator) + + ToString("isStrCrossedUnderPeak", isStrCrossedUnderPeak, ignoreFalseConditions, separator) + + ToString("isNewPeakOverAtrUpper", isNewPeakOverAtrUpper, ignoreFalseConditions, separator) + + ToString("isNewValeUnderAtrLower", isNewValeUnderAtrLower, ignoreFalseConditions, separator) + + ToString("isStrUpperOverAtrUpper", isStrUpperOverAtrUpper, ignoreFalseConditions, separator) + + ToString("isStrLowerOverAtrLower", isStrLowerOverAtrLower, ignoreFalseConditions, separator) + + ToString("isAtrUpperEqualsToPeak", isAtrUpperEqualsToPeak, ignoreFalseConditions, separator) + + ToString("isAtrLowerEqualsToVale", isAtrLowerEqualsToVale, ignoreFalseConditions, separator) + + ToString("isAtrUpperCrossedUpPeak", isAtrUpperCrossedUpPeak, ignoreFalseConditions, separator) + + ToString("isAtrLowerCrossedUpVale", isAtrLowerCrossedUpVale, ignoreFalseConditions, separator) + + ToString("isStrUpperUnderAtrUpper", isStrUpperUnderAtrUpper, ignoreFalseConditions, separator) + + ToString("isStrLowerUnderAtrLower", isStrLowerUnderAtrLower, ignoreFalseConditions, separator) + + ToString("isVWapFastCrossedOverMid", isVWapFastCrossedOverMid, ignoreFalseConditions, separator) + + ToString("isAtrUpperCrossedDownPeak", isAtrUpperCrossedDownPeak, ignoreFalseConditions, separator) + + ToString("isAtrLowerCrossedDownVale", isAtrLowerCrossedDownVale, ignoreFalseConditions, separator) + + ToString("isVWapFastCrossedUnderMid", isVWapFastCrossedUnderMid, ignoreFalseConditions, separator) + + ToString("isVWapFastCrossedOverSlow", isVWapFastCrossedOverSlow, ignoreFalseConditions, separator) + + ToString("isStrUpperCrossedOverPeak", isStrUpperCrossedOverPeak, ignoreFalseConditions, separator) + + ToString("isStrLowerOverDonLowLower", isStrLowerOverDonLowLower, ignoreFalseConditions, separator) + + ToString("isStrLowerCrossedOverVale", isStrLowerCrossedOverVale, ignoreFalseConditions, separator) + + ToString("isDonLowLowerEqualsToVale", isDonLowLowerEqualsToVale, ignoreFalseConditions, separator) + + ToString("isVWapFastCrossedUnderSlow", isVWapFastCrossedUnderSlow, ignoreFalseConditions, separator) + + ToString("isStrUpperCrossedUnderPeak", isStrUpperCrossedUnderPeak, ignoreFalseConditions, separator) + + ToString("isStrLowerCrossedUnderVale", isStrLowerCrossedUnderVale, ignoreFalseConditions, separator) + + ToString("isDonHighUpperEqualsToPeak", isDonHighUpperEqualsToPeak, ignoreFalseConditions, separator) + + ToString("isStrUpperOverDonHighUpper", isStrUpperOverDonHighUpper, ignoreFalseConditions, separator) + + ToString("isStrLowerUnderDonLowLower", isStrLowerUnderDonLowLower, ignoreFalseConditions, separator) + + ToString("isStrUpperUnderDonHighUpper", isStrUpperUnderDonHighUpper, ignoreFalseConditions, separator) + + ToString("isStrUpperCrossedOverAtrUpper", isStrUpperCrossedOverAtrUpper, ignoreFalseConditions, separator) + + ToString("isStrLowerCrossedOverAtrLower", isStrLowerCrossedOverAtrLower, ignoreFalseConditions, separator) + + ToString("isStrUpperCrossedUnderAtrUpper", isStrUpperCrossedUnderAtrUpper, ignoreFalseConditions, separator) + + ToString("isStrLowerCrossedUnderAtrLower", isStrLowerCrossedUnderAtrLower, ignoreFalseConditions, separator) + + ToString("isStrLowerCrossedOverDonLowLower", isStrLowerCrossedOverDonLowLower, ignoreFalseConditions, separator) + + ToString("isStrUpperCrossedOverDonHighUpper", isStrUpperCrossedOverDonHighUpper, ignoreFalseConditions, separator) + + ToString("isStrLowerCrossedUnderDonLowLower", isStrLowerCrossedUnderDonLowLower, ignoreFalseConditions, separator) + + ToString("isStrUpperCrossedUnderDonHighUpper", isStrUpperCrossedUnderDonHighUpper, ignoreFalseConditions, separator) + + // + "" + // + ; + + // + result = + // + "[" + GetTag() + "]" + separator + + (onlyConditions + ? "" + : commonStr) + + (!includeScores + ? "" + : scoresStr) + + " " + separator + + (onlyCommons + ? "" + : conditionsStr) + + "" + // + ; + + // + return result; + } + + /** + * Retrieve nique Tag Identifier ... + * + * @return ( string ) + */ + string GetTag() + { + return GetTypeName(this); + } + + // +}; + +// +// Implementation ... +class XCX121Helper : public XCBase +{ + // + public: + // + + // + // Helpers ... + XCX121XCCHelper *xccHelper; + XCX121XPVHelper *xpvHelper; + XCX121XHKHelper *xhkHelper; + XCX121XICHHelper *xichHelper; + XCX121XMASHelper *xmasHelper; + XCX121XATRHelper *xatrHelper; + XCX121XSTRHelper *xstrHelper; + XCX121XCHEHelper *xcheHelper; + XCX121XDONHelper *xdonHelper; + XCX121X3MAHelper *x3maHelper; + XCX121XVWAPHelper *xvwapHelper; + XCX121XDELTAHelper *xdeltaHelper; + XCX121XVOLUMEHelper *xvolumeHelper; + + // + // Constructors ... + XCX121Helper() + { + } + + // + // Deconstructor ... + ~XCX121Helper() + { + // + mInputs.Clean(); + xccInputs.Clean(); + xpvInputs.Clean(); + xhkInputs.Clean(); + xichInputs.Clean(); + xmasInputs.Clean(); + xatrInputs.Clean(); + xdonInputs.Clean(); + xstrInputs.Clean(); + xcheInputs.Clean(); + x3maInputs.Clean(); + xvwapInputs.Clean(); + xdeltaInputs.Clean(); + xvolumeInputs.Clean(); + + // + delete xccHelper; + delete xpvHelper; + delete xhkHelper; + delete xichHelper; + delete xmasHelper; + delete xatrHelper; + delete xstrHelper; + delete xcheHelper; + delete xdonHelper; + delete x3maHelper; + delete xvwapHelper; + delete xdeltaHelper; + delete xvolumeHelper; + + // + ZeroMemory(xccHelper); + ZeroMemory(xpvHelper); + ZeroMemory(xhkHelper); + ZeroMemory(xichHelper); + ZeroMemory(xmasHelper); + ZeroMemory(xatrHelper); + ZeroMemory(xstrHelper); + ZeroMemory(xcheHelper); + ZeroMemory(xdonHelper); + ZeroMemory(x3maHelper); + ZeroMemory(xvwapHelper); + ZeroMemory(xdeltaHelper); + ZeroMemory(xvolumeHelper); + } + + // + string GetSymbol() + { + return mSymbol; + } + + // + ENUM_TIMEFRAMES GetPeriod() + { + return mPeriod; + } + + // + // Tools ... + + /** + * Initialize Indicator Helper ... + * + * @param symbol: String, Symbol ... + * @param period: ENUM_TIMEFRAMES member, Period ... + * @param inputs: X121Inputs instance, Indicator Inputs ... + * + * @return ( bool ) + */ + bool Init( + string symbol, // Trading Symbol + ENUM_TIMEFRAMES period, // Trading Period + X121Inputs &inputs // Inputs + ) + { + // + bool result = false; + + // + result = + IsValid(symbol) && + IsValid(period) && + inputs.IsValid(); + if (!result) + { + return result; + } + + // + mSymbol = symbol; + mPeriod = period; + + // + // Setting Inputs ... + + // + mInputs = inputs; + xccInputs = inputs.xccInputs; + xpvInputs = inputs.xpvInputs; + xhkInputs = inputs.xhkInputs; + xichInputs = inputs.xichInputs; + xmasInputs = inputs.xmasInputs; + xatrInputs = inputs.xatrInputs; + xstrInputs = inputs.xstrInputs; + xcheInputs = inputs.xcheInputs; + xdonInputs = inputs.xdonInputs; + x3maInputs = inputs.x3maInputs; + xvwapInputs = inputs.xvwapInputs; + xdeltaInputs = inputs.xdeltaInputs; + xvolumeInputs = inputs.xvolumeInputs; + + // + // Initial Helpers ... + + // + // XCC ... + xccHelper = new XCX121XCCHelper(); + result = xccHelper.Init( + symbol, + period, + xccInputs // + ); + if (!result) + { + // + ZeroMemory(xccHelper); + ZeroMemory(xpvHelper); + ZeroMemory(xhkHelper); + ZeroMemory(xmasHelper); + ZeroMemory(xatrHelper); + ZeroMemory(xichHelper); + ZeroMemory(xstrHelper); + ZeroMemory(xcheHelper); + ZeroMemory(xdonHelper); + ZeroMemory(x3maHelper); + ZeroMemory(xvwapHelper); + ZeroMemory(xdeltaHelper); + ZeroMemory(xvolumeHelper); + + // + return result; + } + + // + // XPV ... + xpvHelper = new XCX121XPVHelper(); + result = xpvHelper.Init( + symbol, + period, + xpvInputs // + ); + if (!result) + { + // + ZeroMemory(xccHelper); + ZeroMemory(xpvHelper); + ZeroMemory(xhkHelper); + ZeroMemory(xmasHelper); + ZeroMemory(xatrHelper); + ZeroMemory(xichHelper); + ZeroMemory(xstrHelper); + ZeroMemory(xcheHelper); + ZeroMemory(xdonHelper); + ZeroMemory(x3maHelper); + ZeroMemory(xvwapHelper); + ZeroMemory(xdeltaHelper); + ZeroMemory(xvolumeHelper); + + // + return result; + } + + // + // XHK ... + xhkHelper = new XCX121XHKHelper(); + result = xhkHelper.Init( + symbol, + period, + xhkInputs // + ); + if (!result) + { + // + ZeroMemory(xccHelper); + ZeroMemory(xpvHelper); + ZeroMemory(xhkHelper); + ZeroMemory(xmasHelper); + ZeroMemory(xatrHelper); + ZeroMemory(xichHelper); + ZeroMemory(xstrHelper); + ZeroMemory(xcheHelper); + ZeroMemory(xdonHelper); + ZeroMemory(x3maHelper); + ZeroMemory(xvwapHelper); + ZeroMemory(xdeltaHelper); + ZeroMemory(xvolumeHelper); + + // + return result; + } + + // + // XMAS ... + xmasHelper = new XCX121XMASHelper(); + result = xmasHelper.Init( + symbol, + period, + xmasInputs // + ); + if (!result) + { + // + ZeroMemory(xccHelper); + ZeroMemory(xpvHelper); + ZeroMemory(xhkHelper); + ZeroMemory(xmasHelper); + ZeroMemory(xatrHelper); + ZeroMemory(xichHelper); + ZeroMemory(xstrHelper); + ZeroMemory(xcheHelper); + ZeroMemory(xdonHelper); + ZeroMemory(x3maHelper); + ZeroMemory(xvwapHelper); + ZeroMemory(xdeltaHelper); + ZeroMemory(xvolumeHelper); + + // + return result; + } + + // + // XATR ... + xatrHelper = new XCX121XATRHelper(); + result = xatrHelper.Init( + symbol, + period, + xatrInputs // + ); + if (!result) + { + // + ZeroMemory(xccHelper); + ZeroMemory(xpvHelper); + ZeroMemory(xhkHelper); + ZeroMemory(xmasHelper); + ZeroMemory(xatrHelper); + ZeroMemory(xichHelper); + ZeroMemory(xstrHelper); + ZeroMemory(xcheHelper); + ZeroMemory(xdonHelper); + ZeroMemory(x3maHelper); + ZeroMemory(xvwapHelper); + ZeroMemory(xdeltaHelper); + ZeroMemory(xvolumeHelper); + + // + return result; + } + + // + // XICH ... + xichHelper = new XCX121XICHHelper(); + result = xichHelper.Init( + symbol, + period, + xichInputs // + ); + if (!result) + { + // + ZeroMemory(xccHelper); + ZeroMemory(xpvHelper); + ZeroMemory(xhkHelper); + ZeroMemory(xmasHelper); + ZeroMemory(xatrHelper); + ZeroMemory(xichHelper); + ZeroMemory(xstrHelper); + ZeroMemory(xcheHelper); + ZeroMemory(xdonHelper); + ZeroMemory(x3maHelper); + ZeroMemory(xvwapHelper); + ZeroMemory(xdeltaHelper); + ZeroMemory(xvolumeHelper); + + // + return result; + } + + // + // XSTR ... + xstrHelper = new XCX121XSTRHelper(); + result = xstrHelper.Init( + symbol, + period, + xstrInputs // + ); + if (!result) + { + // + ZeroMemory(xccHelper); + ZeroMemory(xpvHelper); + ZeroMemory(xhkHelper); + ZeroMemory(xmasHelper); + ZeroMemory(xatrHelper); + ZeroMemory(xichHelper); + ZeroMemory(xstrHelper); + ZeroMemory(xcheHelper); + ZeroMemory(xdonHelper); + ZeroMemory(x3maHelper); + ZeroMemory(xvwapHelper); + ZeroMemory(xdeltaHelper); + ZeroMemory(xvolumeHelper); + + // + return result; + } + + // + // XCHE ... + xcheHelper = new XCX121XCHEHelper(); + result = xcheHelper.Init( + symbol, + period, + xcheInputs // + ); + if (!result) + { + // + ZeroMemory(xccHelper); + ZeroMemory(xpvHelper); + ZeroMemory(xhkHelper); + ZeroMemory(xmasHelper); + ZeroMemory(xatrHelper); + ZeroMemory(xichHelper); + ZeroMemory(xstrHelper); + ZeroMemory(xcheHelper); + ZeroMemory(xdonHelper); + ZeroMemory(x3maHelper); + ZeroMemory(xvwapHelper); + ZeroMemory(xdeltaHelper); + ZeroMemory(xvolumeHelper); + + // + return result; + } + + // + // XDON ... + xdonHelper = new XCX121XDONHelper(); + result = xdonHelper.Init( + symbol, + period, + xdonInputs // + ); + if (!result) + { + // + ZeroMemory(xccHelper); + ZeroMemory(xpvHelper); + ZeroMemory(xhkHelper); + ZeroMemory(xmasHelper); + ZeroMemory(xatrHelper); + ZeroMemory(xichHelper); + ZeroMemory(xstrHelper); + ZeroMemory(xcheHelper); + ZeroMemory(xdonHelper); + ZeroMemory(x3maHelper); + ZeroMemory(xvwapHelper); + ZeroMemory(xdeltaHelper); + ZeroMemory(xvolumeHelper); + + // + return result; + } + + // + // X3MA ... + x3maHelper = new XCX121X3MAHelper(); + result = x3maHelper.Init( + symbol, + period, + x3maInputs // + ); + if (!result) + { + // + ZeroMemory(xccHelper); + ZeroMemory(xpvHelper); + ZeroMemory(xhkHelper); + ZeroMemory(xmasHelper); + ZeroMemory(xatrHelper); + ZeroMemory(xichHelper); + ZeroMemory(xstrHelper); + ZeroMemory(xcheHelper); + ZeroMemory(xdonHelper); + ZeroMemory(x3maHelper); + ZeroMemory(xvwapHelper); + ZeroMemory(xdeltaHelper); + ZeroMemory(xvolumeHelper); + + // + return result; + } + + // + // XVWAP ... + xvwapHelper = new XCX121XVWAPHelper(); + result = xvwapHelper.Init( + symbol, + period, + xvwapInputs // + ); + if (!result) + { + // + ZeroMemory(xccHelper); + ZeroMemory(xpvHelper); + ZeroMemory(xhkHelper); + ZeroMemory(xmasHelper); + ZeroMemory(xatrHelper); + ZeroMemory(xichHelper); + ZeroMemory(xstrHelper); + ZeroMemory(xcheHelper); + ZeroMemory(xdonHelper); + ZeroMemory(x3maHelper); + ZeroMemory(xvwapHelper); + ZeroMemory(xdeltaHelper); + ZeroMemory(xvolumeHelper); + + // + return result; + } + + // + // XDELTA ... + xdeltaHelper = new XCX121XDELTAHelper(); + result = xdeltaHelper.Init( + symbol, + period, + xdeltaInputs // + ); + if (!result) + { + // + ZeroMemory(xccHelper); + ZeroMemory(xpvHelper); + ZeroMemory(xhkHelper); + ZeroMemory(xmasHelper); + ZeroMemory(xatrHelper); + ZeroMemory(xichHelper); + ZeroMemory(xstrHelper); + ZeroMemory(xcheHelper); + ZeroMemory(xdonHelper); + ZeroMemory(x3maHelper); + ZeroMemory(xvwapHelper); + ZeroMemory(xdeltaHelper); + ZeroMemory(xvolumeHelper); + + // + return result; + } + + // + // XVOLUME ... + xvolumeHelper = new XCX121XVOLUMEHelper(); + result = xvolumeHelper.Init( + symbol, + period, + xvolumeInputs // + ); + if (!result) + { + // + ZeroMemory(xccHelper); + ZeroMemory(xpvHelper); + ZeroMemory(xhkHelper); + ZeroMemory(xmasHelper); + ZeroMemory(xatrHelper); + ZeroMemory(xichHelper); + ZeroMemory(xstrHelper); + ZeroMemory(xcheHelper); + ZeroMemory(xdonHelper); + ZeroMemory(x3maHelper); + ZeroMemory(xvwapHelper); + ZeroMemory(xdeltaHelper); + ZeroMemory(xvolumeHelper); + + // + return result; + } + + // + if (inputs.showRSI) + { + // + mRSIHandler = iRSI( + symbol, + period, + xatrInputs.rsiLength, + xatrInputs.rsiAppliedTo // + ); + + // + result = mRSIHandler != INVALID_HANDLE; + if (!result) + { + // + ZeroMemory(xccHelper); + ZeroMemory(xpvHelper); + ZeroMemory(xhkHelper); + ZeroMemory(xmasHelper); + ZeroMemory(xatrHelper); + ZeroMemory(xichHelper); + ZeroMemory(xstrHelper); + ZeroMemory(xcheHelper); + ZeroMemory(xdonHelper); + ZeroMemory(x3maHelper); + ZeroMemory(xvwapHelper); + ZeroMemory(xdeltaHelper); + ZeroMemory(xvolumeHelper); + + // + return result; + } + } + + // + return result; + } + + // + // Conditions Readers ... + + // + // XPV ... + bool GetPVConditions( + X121XPVConditions &conditions, // + int barIndex = 0, // + int loopback = 5 // + ) + { + // + bool result = false; + + // + result = xpvHelper.GetConditions( + conditions, + barIndex, + loopback // + ); + + // + return result; + } + + // + // XHK ... + bool GetHKConditions( + X121XHKConditions &conditions, // + int barIndex = 0, // + int loopback = 5 // + ) + { + // + bool result = false; + + // + result = xhkHelper.GetConditions( + conditions, + barIndex, + loopback // + ); + + // + return result; + } + + // + // XMAS ... + bool GetMASConditions( + X121XMASConditions &conditions, // + int barIndex = 0, // + int loopback = 5 // + ) + { + // + bool result = false; + + // + result = xmasHelper.GetConditions( + conditions, + barIndex, + loopback // + ); + + // + return result; + } + + // + // XICH ... + bool GetICHConditions( + X121XICHConditions &conditions, // + int barIndex = 0, // + int loopback = 5 // + ) + { + // + bool result = false; + + // + result = xichHelper.GetConditions( + conditions, + barIndex, + loopback // + ); + + // + return result; + } + + // + // XATR ... + bool GetATRConditions( + X121XATRConditions &conditions, // + int barIndex = 0, // + int loopback = 5 // + ) + { + // + bool result = false; + + // + result = xatrHelper.GetConditions( + conditions, + barIndex, + loopback // + ); + + // + return result; + } + + // + // XSTR ... + bool GetSTRConditions( + X121XSTRConditions &conditions, // + int barIndex = 0, // + int loopback = 5 // + ) + { + // + bool result = false; + + // + result = xstrHelper.GetConditions( + conditions, + barIndex, + loopback // + ); + + // + return result; + } + + // + // XCHE ... + bool GetCHEConditions( + X121XCHEConditions &conditions, // + int barIndex = 0, // + int loopback = 5 // + ) + { + // + bool result = false; + + // + result = xcheHelper.GetConditions( + conditions, + barIndex, + loopback // + ); + + // + return result; + } + + // + // XDON ... + bool GetDONConditions( + X121XDONConditions &conditions, // + int barIndex = 0, // + int loopback = 5 // + ) + { + // + bool result = false; + + // + result = xdonHelper.GetConditions( + conditions, + barIndex, + loopback // + ); + + // + return result; + } + + // + // X3MA ... + bool Get3MAConditions( + X121X3MAConditions &conditions, // + int barIndex = 0, // + int loopback = 5 // + ) + { + // + bool result = false; + + // + result = x3maHelper.GetConditions( + conditions, + barIndex, + loopback // + ); + + // + return result; + } + + // + // XVWAP ... + bool GetVWAPConditions( + X121XVWAPConditions &conditions, // + int barIndex = 0, // + int loopback = 5 // + ) + { + // + bool result = false; + + // + result = xvwapHelper.GetConditions( + conditions, + barIndex, + loopback // + ); + + // + return result; + } + + // + // XDELTA ... + bool GetDELTAConditions( + X121XDELTAConditions &conditions, // + int barIndex = 0, // + int loopback = 5 // + ) + { + // + bool result = false; + + // + result = xdeltaHelper.GetConditions( + conditions, + barIndex, + loopback // + ); + + // + return result; + } + + // + // XVOLUME ... + bool GetVOLUMEConditions( + X121XVOLUMEConditions &conditions, // + int barIndex = 0, // + int loopback = 5 // + ) + { + // + bool result = false; + + // + result = xvolumeHelper.GetConditions( + conditions, + barIndex, + loopback // + ); + + // + return result; + } + + // + void Free() + { + // + xpvHelper.Free(); + xhkHelper.Free(); + xichHelper.Free(); + xmasHelper.Free(); + xatrHelper.Free(); + xstrHelper.Free(); + xcheHelper.Free(); + xdonHelper.Free(); + xvwapHelper.Free(); + } + + // + bool GetConditions( + X121Conditions &conditions, // + int barIndex = 0, // + int loopback = 5 // + ) + { + // + bool result = true; + + // + if (loopback < 5) + { + loopback = 5; + } + + // + conditions.Clean(); + + // + conditions.symbol = mSymbol; + conditions.period = mPeriod; + conditions.time = TimeCurrent(); + + // + int zIndex = barIndex; + int cIndex = zIndex + 1; + int pIndex = cIndex + 1; + int ppIndex = pIndex + 1; + + // + XOHCL zBar; + result = zBar.Init( + mSymbol, + mPeriod, + zIndex // + ); + if (!result) + { + return result; + } + + // + XOHCL cBar; + result = cBar.Init( + mSymbol, + mPeriod, + cIndex // + ); + if (!result) + { + return result; + } + + // + XOHCL pBar; + result = pBar.Init( + mSymbol, + mPeriod, + pIndex // + ); + if (!result) + { + return result; + } + + // + // XPV ... + X121XPVConditions xpvConditions; + result = GetPVConditions( + xpvConditions, + barIndex, + loopback // + ); + if (!result) + { + // + xpvConditions.Clean(); + + // + return result; + } + + // + // XHK ... + X121XHKConditions xhkConditions; + result = GetHKConditions( + xhkConditions, + barIndex, + loopback // + ); + if (!result) + { + // + xpvConditions.Clean(); + xhkConditions.Clean(); + + // + return result; + } + + // + // XICH ... + X121XICHConditions xichConditions; + result = GetICHConditions( + xichConditions, + barIndex, + loopback // + ); + if (!result) + { + // + xpvConditions.Clean(); + xhkConditions.Clean(); + xichConditions.Clean(); + + // + return result; + } + + // + // XMAS ... + X121XMASConditions xmasConditions; + result = GetMASConditions( + xmasConditions, + barIndex, + loopback // + ); + if (!result) + { + // + xpvConditions.Clean(); + xhkConditions.Clean(); + xichConditions.Clean(); + xmasConditions.Clean(); + + // + return result; + } + + // + // XATR ... + X121XATRConditions xatrConditions; + result = GetATRConditions( + xatrConditions, + barIndex, + loopback // + ); + if (!result) + { + // + xpvConditions.Clean(); + xhkConditions.Clean(); + xichConditions.Clean(); + xmasConditions.Clean(); + xatrConditions.Clean(); + + // + return result; + } + + // + // XSTR ... + X121XSTRConditions xstrConditions; + result = GetSTRConditions( + xstrConditions, + barIndex, + loopback // + ); + if (!result) + { + // + xpvConditions.Clean(); + xhkConditions.Clean(); + xichConditions.Clean(); + xmasConditions.Clean(); + xatrConditions.Clean(); + xstrConditions.Clean(); + + // + return result; + } + + // + // XCHE ... + X121XCHEConditions xcheConditions; + result = GetCHEConditions( + xcheConditions, + barIndex, + loopback // + ); + if (!result) + { + // + xpvConditions.Clean(); + xhkConditions.Clean(); + xichConditions.Clean(); + xmasConditions.Clean(); + xatrConditions.Clean(); + xstrConditions.Clean(); + xcheConditions.Clean(); + + // + return result; + } + + // + // XDON ... + X121XDONConditions xdonConditions; + result = GetDONConditions( + xdonConditions, + barIndex, + loopback // + ); + if (!result) + { + // + xpvConditions.Clean(); + xhkConditions.Clean(); + xichConditions.Clean(); + xmasConditions.Clean(); + xatrConditions.Clean(); + xstrConditions.Clean(); + xcheConditions.Clean(); + xdonConditions.Clean(); + + // + return result; + } + + // + // X3MA ... + X121X3MAConditions x3maConditions; + result = Get3MAConditions( + x3maConditions, + barIndex, + loopback // + ); + if (!result) + { + // + xpvConditions.Clean(); + xhkConditions.Clean(); + xichConditions.Clean(); + xmasConditions.Clean(); + xatrConditions.Clean(); + xstrConditions.Clean(); + xcheConditions.Clean(); + xdonConditions.Clean(); + x3maConditions.Clean(); + + // + return result; + } + + // + // XVWAP ... + X121XVWAPConditions xvwapConditions; + result = GetVWAPConditions( + xvwapConditions, + barIndex, + loopback // + ); + if (!result) + { + // + xpvConditions.Clean(); + xhkConditions.Clean(); + xichConditions.Clean(); + xmasConditions.Clean(); + xatrConditions.Clean(); + xstrConditions.Clean(); + xcheConditions.Clean(); + xdonConditions.Clean(); + x3maConditions.Clean(); + xvwapConditions.Clean(); + + // + return result; + } + + // + // XDELTA ... + X121XDELTAConditions xdeltaConditions; + result = GetDELTAConditions( + xdeltaConditions, + barIndex, + loopback // + ); + if (!result) + { + // + xpvConditions.Clean(); + xhkConditions.Clean(); + xichConditions.Clean(); + xmasConditions.Clean(); + xatrConditions.Clean(); + xstrConditions.Clean(); + xcheConditions.Clean(); + xdonConditions.Clean(); + x3maConditions.Clean(); + xvwapConditions.Clean(); + xdeltaConditions.Clean(); + + // + return result; + } + + // + // XVOLUME ... + X121XVOLUMEConditions xvolumeConditions; + result = GetVOLUMEConditions( + xvolumeConditions, + barIndex, + loopback // + ); + if (!result) + { + // + xpvConditions.Clean(); + xhkConditions.Clean(); + xichConditions.Clean(); + xmasConditions.Clean(); + xatrConditions.Clean(); + xstrConditions.Clean(); + xcheConditions.Clean(); + xdonConditions.Clean(); + x3maConditions.Clean(); + xvwapConditions.Clean(); + xdeltaConditions.Clean(); + xvolumeConditions.Clean(); + + // + return result; + } + + // + // Fill Volume Buffer ... + for (int i = barIndex; i < barIndex + loopback; i++) + { + // + // Reading Bar Valuem ... + long iVol = iVolume( + mSymbol, + mPeriod, + i // + ); + + // + Add( + iVol, + conditions.volumeBuffer // + ); + } + + // + // Fill X121 Conditions Reference by Using + // Retrieved Conditions ... + + // + int cIDX = 1; + int pIDX = cIDX + 1; + + // + // XPV ... + + // + // Buffers ... + + // + Copy( + xpvConditions.peaksBuffer, + conditions.peaksBuffer // + ); + + // + Copy( + xpvConditions.valesBuffer, + conditions.valesBuffer // + ); + + // + Copy( + xpvConditions.supportsBuffer, + conditions.supportsBuffer // + ); + + // + Copy( + xpvConditions.resistancesBuffer, + conditions.resistancesBuffer // + ); + + // + Copy( + xpvConditions.peaksGoldenBuffer, + conditions.peaksGoldenBuffer // + ); + + // + Copy( + xpvConditions.valesGoldenBuffer, + conditions.valesGoldenBuffer // + ); + + // + Copy( + xpvConditions.sarBuffer, + conditions.sarBuffer // + ); + + // + Copy( + xpvConditions.cHHBuffer, + conditions.cHHBuffer // + ); + + // + Copy( + xpvConditions.cLLBuffer, + conditions.cLLBuffer // + ); + + // + Copy( + xpvConditions.sHHBuffer, + conditions.sHHBuffer // + ); + + // + Copy( + xpvConditions.sLLBuffer, + conditions.sLLBuffer // + ); + + // + Copy( + xpvConditions.mHHBuffer, + conditions.mHHBuffer // + ); + + // + Copy( + xpvConditions.mLLBuffer, + conditions.mLLBuffer // + ); + + // + Copy( + xpvConditions.lHHBuffer, + conditions.lHHBuffer // + ); + + // + Copy( + xpvConditions.lLLBuffer, + conditions.lLLBuffer // + ); + + // + Copy( + xpvConditions.hHHBuffer, + conditions.hHHBuffer // + ); + + // + Copy( + xpvConditions.hLLBuffer, + conditions.hLLBuffer // + ); + + // + Copy( + xpvConditions.fractalsUpperBuffer, + conditions.fractalsUpperBuffer // + ); + + // + Copy( + xpvConditions.fractalsLowerBuffer, + conditions.fractalsLowerBuffer // + ); + + // + // Conditions ... + + // + conditions.isNewPeak = xpvConditions.isNewPeak; + conditions.isNewVale = xpvConditions.isNewVale; + conditions.isSarBullish = xpvConditions.isSarBullish; + conditions.isSarBearish = xpvConditions.isSarBearish; + conditions.isNewPeakOverLast = xpvConditions.isNewPeakOverLast; + conditions.isNewValeOverLast = xpvConditions.isNewValeOverLast; + conditions.isNewPeakUnderLast = xpvConditions.isNewPeakUnderLast; + conditions.isNewValeUnderLast = xpvConditions.isNewValeUnderLast; + conditions.isSarSwitchedToBullish = xpvConditions.isSarSwitchedToBullish; + conditions.isSarSwitchedToBearish = xpvConditions.isSarSwitchedToBearish; + + // + // XHK ... + + // + // Buffers ... + + // + Copy( + xhkConditions.xhkRawOpenBuffer, + conditions.xhkRawOpenBuffer // + ); + + // + Copy( + xhkConditions.xhkRawHighBuffer, + conditions.xhkRawHighBuffer // + ); + + // + Copy( + xhkConditions.xhkRawLowBuffer, + conditions.xhkRawLowBuffer // + ); + + // + Copy( + xhkConditions.xhkRawCloseBuffer, + conditions.xhkRawCloseBuffer // + ); + + // + Copy( + xhkConditions.xhkSMOpenBuffer, + conditions.xhkSMOpenBuffer // + ); + + // + Copy( + xhkConditions.xhkSMHighBuffer, + conditions.xhkSMHighBuffer // + ); + + // + Copy( + xhkConditions.xhkSMLowBuffer, + conditions.xhkSMLowBuffer // + ); + + // + Copy( + xhkConditions.xhkSMCloseBuffer, + conditions.xhkSMCloseBuffer // + ); + + // + // Conditions ... + conditions.isSMHKBullish = xhkConditions.isSMHKBullish; + conditions.isRawHKBullish = xhkConditions.isRawHKBullish; + conditions.isSMHKBearish = xhkConditions.isSMHKBearish; + conditions.isRawHKBearish = xhkConditions.isRawHKBearish; + conditions.isClosedOverSMHK = xhkConditions.isClosedOverSMHK; + conditions.isClosedUnderSMHK = xhkConditions.isClosedUnderSMHK; + conditions.isClosedOverRawHK = xhkConditions.isClosedOverRawHK; + conditions.isClosedUnderRawHK = xhkConditions.isClosedUnderRawHK; + conditions.isRawHKClosedOverSMHK = xhkConditions.isRawHKClosedOverSMHK; + conditions.isSMHKSwitchedToBearish = xhkConditions.isSMHKSwitchedToBearish; + conditions.isRawHKSwitchedToBearish = xhkConditions.isRawHKSwitchedToBearish; + conditions.isRawHKClosedUnderSMHK = xhkConditions.isRawHKClosedUnderSMHK; + conditions.isSMHKSwitchedToBullish = xhkConditions.isSMHKSwitchedToBullish; + conditions.isRawHKSwitchedToBullish = xhkConditions.isRawHKSwitchedToBullish; + + // + // XMAS ... + + // + // Buffers ... + + // + Copy( + xmasConditions.upperBuffer, + conditions.masUpperBuffer // + ); + + // + Copy( + xmasConditions.midBuffer, + conditions.masMidBuffer // + ); + + // + Copy( + xmasConditions.lowerBuffer, + conditions.masLowerBuffer // + ); + + // + // XATR ... + + // + // Buffers ... + + // + Copy( + xatrConditions.atrUpperBuffer, + conditions.atrUpperBuffer // + ); + + // + Copy( + xatrConditions.atrLowerBuffer, + conditions.atrLowerBuffer // + ); + + // + Copy( + xatrConditions.atrUpperRawBuffer, + conditions.atrUpperRawBuffer // + ); + + // + Copy( + xatrConditions.atrLowerRawBuffer, + conditions.atrLowerRawBuffer // + ); + + // + Copy( + xatrConditions.atrBuffer, + conditions.atrBuffer // + ); + + // + Copy( + xatrConditions.rsiBuffer, + conditions.rsiBuffer // + ); + + // + // Conditions ... + + // + conditions.isRsiOverSold = xatrConditions.isRsiOverSold; + conditions.isRsiOverBought = xatrConditions.isRsiOverBought; + conditions.isClosedOverAtrUpper = xatrConditions.isClosedOverAtrUpper; + conditions.isClosedOverAtrLower = xatrConditions.isClosedOverAtrLower; + conditions.isClosedUnderAtrUpper = xatrConditions.isClosedUnderAtrUpper; + conditions.isClosedUnderAtrLower = xatrConditions.isClosedUnderAtrLower; + conditions.isRsiCrossedOverOverSold = xatrConditions.isRsiCrossedOverOverSold; + conditions.isRsiCrossedUnderOverSold = xatrConditions.isRsiCrossedUnderOverSold; + conditions.isRsiCrossedOverOverBought = xatrConditions.isRsiCrossedOverOverBought; + conditions.isRsiCrossedUnderOverBought = xatrConditions.isRsiCrossedUnderOverBought; + + // + // XSTR ... + + // + // Buffers ... + + // + Copy( + xstrConditions.strBuffer, + conditions.strBuffer // + ); + + // + Copy( + xstrConditions.strPriceBuffer, + conditions.strPriceBuffer // + ); + + // + Copy( + xstrConditions.strUpBuffer, + conditions.strUpBuffer // + ); + + // + Copy( + xstrConditions.strDownBuffer, + conditions.strDownBuffer // + ); + + // + Copy( + xstrConditions.strStateBuffer, + conditions.strStateBuffer // + ); + + // + // Conditions ... + + // + conditions.isStrBullish = xstrConditions.isStrBullish; + conditions.isStrBearish = xstrConditions.isStrBearish; + conditions.isStrSwitchedToBullish = xstrConditions.isStrSwitchedToBullish; + conditions.isStrSwitchedToBearish = xstrConditions.isStrSwitchedToBearish; + + // + // XCHE ... + + // + // Buffers ... + + // + Copy( + xcheConditions.le1Buffer, + conditions.le1Buffer // + ); + + // + Copy( + xcheConditions.se1Buffer, + conditions.se1Buffer // + ); + + // + Copy( + xcheConditions.le2Buffer, + conditions.le2Buffer // + ); + + // + Copy( + xcheConditions.se2Buffer, + conditions.se2Buffer // + ); + + // + Copy( + xcheConditions.le1StartBuffer, + conditions.le1StartBuffer // + ); + + // + Copy( + xcheConditions.se1StartBuffer, + conditions.se1StartBuffer // + ); + + // + Copy( + xcheConditions.le2StartBuffer, + conditions.le2StartBuffer // + ); + + // + Copy( + xcheConditions.se2StartBuffer, + conditions.se2StartBuffer // + ); + + // + // Conditions ... + + conditions.isCheBullish = xcheConditions.isCheBullish; + conditions.isCheBearish = xcheConditions.isCheBearish; + conditions.isChe1Bullish = xcheConditions.isChe1Bullish; + conditions.isChe1Bearish = xcheConditions.isChe1Bearish; + conditions.isChe2Bullish = xcheConditions.isChe2Bullish; + conditions.isChe2Bearish = xcheConditions.isChe2Bearish; + conditions.isClosedOverCheMin = xcheConditions.isClosedOverCheMin; + conditions.isClosedOverCheMax = xcheConditions.isClosedOverCheMax; + conditions.isClosedUnderCheMin = xcheConditions.isClosedUnderCheMin; + conditions.isClosedUnderCheMax = xcheConditions.isClosedUnderCheMax; + conditions.isCheSwitchedToBullish = xcheConditions.isCheSwitchedToBullish; + conditions.isCheSwitchedToBearish = xcheConditions.isCheSwitchedToBearish; + conditions.isChe1SwitchedToBullish = xcheConditions.isChe1SwitchedToBullish; + conditions.isChe1SwitchedToBearish = xcheConditions.isChe1SwitchedToBearish; + conditions.isChe2SwitchedToBullish = xcheConditions.isChe2SwitchedToBullish; + conditions.isChe2SwitchedToBearish = xcheConditions.isChe2SwitchedToBearish; + + // + // XDON ... + + // + // Buffers ... + + // + Copy( + xdonConditions.donOpenUpperBuffer, + conditions.donOpenUpperBuffer // + ); + + // + Copy( + xdonConditions.donOpenLowerBuffer, + conditions.donOpenLowerBuffer // + ); + + // + Copy( + xdonConditions.donHighUpperBuffer, + conditions.donHighUpperBuffer // + ); + + // + Copy( + xdonConditions.donHighLowerBuffer, + conditions.donHighLowerBuffer // + ); + + // + Copy( + xdonConditions.donLowUpperBuffer, + conditions.donLowUpperBuffer // + ); + + // + Copy( + xdonConditions.donLowLowerBuffer, + conditions.donLowLowerBuffer // + ); + + // + Copy( + xdonConditions.donCloseUpperBuffer, + conditions.donCloseUpperBuffer // + ); + + // + Copy( + xdonConditions.donCloseLowerBuffer, + conditions.donCloseLowerBuffer // + ); + + // + // Conditions ... + + // + // X3MA ... + + // + // Buffers ... + + // + Copy( + x3maConditions.x3maFastBuffer, + conditions.x3maFastBuffer // + ); + + // + Copy( + x3maConditions.x3maMidBuffer, + conditions.x3maMidBuffer // + ); + + // + Copy( + x3maConditions.x3maSlowBuffer, + conditions.x3maSlowBuffer // + ); + + // + Copy( + x3maConditions.x3maFastStateBuffer, + conditions.x3maFastStateBuffer // + ); + + // + Copy( + x3maConditions.x3maMidStateBuffer, + conditions.x3maMidStateBuffer // + ); + + // + Copy( + x3maConditions.x3maSlowStateBuffer, + conditions.x3maSlowStateBuffer // + ); + + // + // Conditions ... + + // + conditions.isX3MaMidBullish = x3maConditions.isX3MaMidBullish; + conditions.isX3MaMidBearish = x3maConditions.isX3MaMidBearish; + conditions.isX3MaFastBullish = x3maConditions.isX3MaFastBullish; + conditions.isX3MaFastBearish = x3maConditions.isX3MaFastBearish; + conditions.isX3MaMidNeutural = x3maConditions.isX3MaMidNeutural; + conditions.isX3MaSlowBullish = x3maConditions.isX3MaSlowBullish; + conditions.isX3MaSlowBearish = x3maConditions.isX3MaSlowBearish; + conditions.isX3MaFastOverMid = x3maConditions.isX3MaFastOverMid; + conditions.isX3MaMidOverSlow = x3maConditions.isX3MaMidOverSlow; + conditions.isX3MaFastNeutural = x3maConditions.isX3MaFastNeutural; + conditions.isX3MaSlowNeutural = x3maConditions.isX3MaSlowNeutural; + conditions.isX3MaFastUnderMid = x3maConditions.isX3MaFastUnderMid; + conditions.isX3MaMidUnderSlow = x3maConditions.isX3MaMidUnderSlow; + conditions.isX3MaBullishState = x3maConditions.isX3MaBullishState; + conditions.isX3MaBearishState = x3maConditions.isX3MaBearishState; + conditions.isX3MaNeuturalState = x3maConditions.isX3MaNeuturalState; + conditions.isX3MaBullishOrdered = x3maConditions.isX3MaBullishOrdered; + conditions.isX3MaBearishOrdered = x3maConditions.isX3MaBearishOrdered; + conditions.isX3MaSwitchedToBullishState = x3maConditions.isX3MaSwitchedToBullishState; + conditions.isX3MaSwitchedToBearishState = x3maConditions.isX3MaSwitchedToBearishState; + conditions.isX3MaSwitchedToNeuturalState = x3maConditions.isX3MaSwitchedToNeuturalState; + conditions.isX3MaSwitchedToBullishOrdered = x3maConditions.isX3MaSwitchedToBullishOrdered; + conditions.isX3MaSwitchedToBearishOrdered = x3maConditions.isX3MaSwitchedToBearishOrdered; + + // + // XVWAP ... + + // + // Buffers ... + + // + Copy( + xvwapConditions.vwapFastBuffer, + conditions.vwapFastBuffer // + ); + + // + Copy( + xvwapConditions.vwapMidBuffer, + conditions.vwapMidBuffer // + ); + + // + Copy( + xvwapConditions.vwapSlowBuffer, + conditions.vwapSlowBuffer // + ); + + // + Copy( + xvwapConditions.vwapVolumeBuffer, + conditions.vwapVolumeBuffer // + ); + + // + Copy( + xvwapConditions.vwapPriceBuffer, + conditions.vwapPriceBuffer // + ); + + // + Copy( + xvwapConditions.vwapFastStateBuffer, + conditions.vwapFastStateBuffer // + ); + + // + Copy( + xvwapConditions.vwapMidStateBuffer, + conditions.vwapMidStateBuffer // + ); + + // + Copy( + xvwapConditions.vwapSlowStateBuffer, + conditions.vwapSlowStateBuffer // + ); + + // + // Conditions ... + + // + conditions.isVWapMidBullish = xvwapConditions.isVWapMidBullish; + conditions.isVWapMidBearish = xvwapConditions.isVWapMidBearish; + conditions.isVWapFastBullish = xvwapConditions.isVWapFastBullish; + conditions.isVWapFastBearish = xvwapConditions.isVWapFastBearish; + conditions.isVWapMidNeutural = xvwapConditions.isVWapMidNeutural; + conditions.isVWapSlowBullish = xvwapConditions.isVWapSlowBullish; + conditions.isVWapSlowBearish = xvwapConditions.isVWapSlowBearish; + conditions.isVWapFastOverMid = xvwapConditions.isVWapFastOverMid; + conditions.isVWapMidOverSlow = xvwapConditions.isVWapMidOverSlow; + conditions.isVWapFastNeutural = xvwapConditions.isVWapFastNeutural; + conditions.isVWapSlowNeutural = xvwapConditions.isVWapSlowNeutural; + conditions.isVWapFastUnderMid = xvwapConditions.isVWapFastUnderMid; + conditions.isVWapMidUnderSlow = xvwapConditions.isVWapMidUnderSlow; + conditions.isVWapBullishState = xvwapConditions.isVWapBullishState; + conditions.isVWapBearishState = xvwapConditions.isVWapBearishState; + conditions.isVWapNeuturalState = xvwapConditions.isVWapNeuturalState; + conditions.isVWapBullishOrdered = xvwapConditions.isVWapBullishOrdered; + conditions.isVWapBearishOrdered = xvwapConditions.isVWapBearishOrdered; + conditions.isVWapSwitchedToBullishState = xvwapConditions.isVWapSwitchedToBullishState; + conditions.isVWapSwitchedToBearishState = xvwapConditions.isVWapSwitchedToBearishState; + conditions.isVWapSwitchedToNeuturalState = xvwapConditions.isVWapSwitchedToNeuturalState; + conditions.isVWapSwitchedToBullishOrdered = xvwapConditions.isVWapSwitchedToBullishOrdered; + conditions.isVWapSwitchedToBearishOrdered = xvwapConditions.isVWapSwitchedToBearishOrdered; + + // + // XICH ... + + // + // Buffers ... + + // + Copy( + xichConditions.kijunSenBuffer, + conditions.kijunSenBuffer // + ); + + // + Copy( + xichConditions.tenkanSenBuffer, + conditions.tenkanSenBuffer // + ); + + // + Copy( + xichConditions.chikouSpanBuffer, + conditions.chikouSpanBuffer // + ); + + // + Copy( + xichConditions.senkouSpanABuffer, + conditions.senkouSpanABuffer // + ); + + // + Copy( + xichConditions.senkouSpanBBuffer, + conditions.senkouSpanBBuffer // + ); + + // + // Conditions ... + + // + conditions.isTenkanSenOverKijunSen = xichConditions.isTenkanSenOverKijunSen; + conditions.isTenkanSenUnderKijunSen = xichConditions.isTenkanSenUnderKijunSen; + + // + conditions.isTenkanSenCrossedOverKijunSen = xichConditions.isTenkanSenCrossedOverKijunSen; + conditions.isTenkanSenCrossedUnderKijunSen = xichConditions.isTenkanSenCrossedUnderKijunSen; + + // + conditions.isSenkouSpanAOverB = xichConditions.isSenkouSpanAOverB; + conditions.isSenkouSpanAUnderB = xichConditions.isSenkouSpanAUnderB; + + // + conditions.isSenkouSpanACrossedOverB = xichConditions.isSenkouSpanACrossedOverB; + conditions.isSenkouSpanACrossedUnderB = xichConditions.isSenkouSpanACrossedUnderB; + + // + conditions.tenKijMax = MathMax(xichConditions.tenkanSenBuffer[cIDX], xichConditions.kijunSenBuffer[cIDX]); + conditions.tenKijMin = MathMin(xichConditions.tenkanSenBuffer[cIDX], xichConditions.kijunSenBuffer[cIDX]); + conditions.senkouMax = MathMax(xichConditions.senkouSpanABuffer[cIDX], xichConditions.senkouSpanBBuffer[cIDX]); + conditions.senkouMin = MathMin(xichConditions.senkouSpanABuffer[cIDX], xichConditions.senkouSpanBBuffer[cIDX]); + + // + // XDELTA ... + + // + // Buffers ... + + // + Copy( + xdeltaConditions.deltaBuffer, + conditions.deltaBuffer // + ); + + // + Copy( + xdeltaConditions.deltaMaBuffer, + conditions.deltaMaBuffer // + ); + + // + Copy( + xdeltaConditions.deltaStateBuffer, + conditions.deltaStateBuffer // + ); + + // + // Conditions ... + + // + conditions.isDeltaBullish = xdeltaConditions.isDeltaBullish; + conditions.isDeltaBearish = xdeltaConditions.isDeltaBearish; + conditions.isDeltaSwitchedToBullish = xdeltaConditions.isDeltaSwitchedToBullish; + conditions.isDeltaSwitchedToBearish = xdeltaConditions.isDeltaSwitchedToBearish; + + // + conditions.isDeltaOverMa = xdeltaConditions.isDeltaOverMa; + conditions.isDeltaUnderMa = xdeltaConditions.isDeltaUnderMa; + conditions.isDeltaCrossedOverMa = xdeltaConditions.isDeltaCrossedOverMa; + conditions.isDeltaCrossedUnderMa = xdeltaConditions.isDeltaCrossedUnderMa; + + // + // XVOLUME ... + + // + // Buffers ... + + // + Copy( + xvolumeConditions.bullishVolumeBuffer, + conditions.bullishVolumeBuffer // + ); + + // + Copy( + xvolumeConditions.bullishVolumeMaBuffer, + conditions.bullishVolumeMaBuffer // + ); + + // + Copy( + xvolumeConditions.bearishVolumeBuffer, + conditions.bearishVolumeBuffer // + ); + + // + Copy( + xvolumeConditions.bearishVolumeMaBuffer, + conditions.bearishVolumeMaBuffer // + ); + + // + // Conditions ... + + // + conditions.isBullishVolumeOverMa = xvolumeConditions.isBullishVolumeOverMa; + conditions.isBullishVolumeCrossedOverMa = xvolumeConditions.isBullishVolumeCrossedOverMa; + + // + conditions.isBullishVolumeUnderMa = xvolumeConditions.isBullishVolumeUnderMa; + conditions.isBullishVolumeCrossedUnderMa = xvolumeConditions.isBullishVolumeCrossedUnderMa; + + // + conditions.isBullishVolumeIncreased = xvolumeConditions.isBullishVolumeIncreased; + conditions.isBullishVolumeSwitchedToIncreased = xvolumeConditions.isBullishVolumeSwitchedToIncreased; + + // + conditions.isBullishVolumeDecreased = xvolumeConditions.isBullishVolumeDecreased; + conditions.isBullishVolumeSwitchedToDecreased = xvolumeConditions.isBullishVolumeSwitchedToDecreased; + + // + conditions.isBearishVolumeOverMa = xvolumeConditions.isBearishVolumeOverMa; + conditions.isBearishVolumeCrossedOverMa = xvolumeConditions.isBearishVolumeCrossedOverMa; + + // + conditions.isBearishVolumeUnderMa = xvolumeConditions.isBearishVolumeUnderMa; + conditions.isBearishVolumeCrossedUnderMa = xvolumeConditions.isBearishVolumeCrossedUnderMa; + + // + conditions.isBearishVolumeIncreased = xvolumeConditions.isBearishVolumeIncreased; + conditions.isBearishVolumeSwitchedToIncreased = xvolumeConditions.isBearishVolumeSwitchedToIncreased; + + // + conditions.isBearishVolumeDecreased = xvolumeConditions.isBearishVolumeDecreased; + conditions.isBearishVolumeSwitchedToDecreased = xvolumeConditions.isBearishVolumeSwitchedToDecreased; + + // + conditions.isVolumeSwitchedToBullish = xvolumeConditions.isVolumeSwitchedToBullish; + conditions.isVolumeSwitchedToBearish = xvolumeConditions.isVolumeSwitchedToBearish; + + // + conditions.isBullishVolumeMaOverBearishVolumeMa = xvolumeConditions.isBullishVolumeMaOverBearishVolumeMa; + conditions.isBullishVolumeMaUnderBearishVolumeMa = xvolumeConditions.isBullishVolumeMaUnderBearishVolumeMa; + + // + // Slopes ... + + // + double rsiSlope = GetSlope(conditions.rsiBuffer, pIDX, cIDX); + double strSlope = GetSlope(conditions.strBuffer, pIDX, cIDX); + double atrUpperSlope = GetSlope(conditions.atrUpperBuffer, pIDX, cIDX); + double atrLowerSlope = GetSlope(conditions.atrLowerBuffer, pIDX, cIDX); + double vwapFastSlope = GetSlope(conditions.vwapFastBuffer, pIDX, cIDX); + double vwapMidSlope = GetSlope(conditions.vwapMidBuffer, pIDX, cIDX); + double vwapSlowSlope = GetSlope(conditions.vwapSlowBuffer, pIDX, cIDX); + + // + bool isRsiSlopeBullish = rsiSlope > 0; + bool isStrSlopeBullish = strSlope > 0; + bool isAtrUpperSlopeBullish = atrUpperSlope > 0; + bool isAtrLowerSlopeBullish = atrLowerSlope > 0; + bool isVwapFastSlopeBullish = vwapFastSlope > 0; + bool isVwapMidSlopeBullish = vwapMidSlope > 0; + bool isVwapSlowSlopeBullish = vwapSlowSlope > 0; + + // + bool isRsiSlopeBearish = rsiSlope < 0; + bool isStrSlopeBearish = strSlope < 0; + bool isAtrUpperSlopeBearish = atrUpperSlope < 0; + bool isAtrLowerSlopeBearish = atrLowerSlope < 0; + bool isVwapFastSlopeBearish = vwapFastSlope < 0; + bool isVwapMidSlopeBearish = vwapMidSlope < 0; + bool isVwapSlowSlopeBearish = vwapSlowSlope < 0; + + // + conditions.rsiSlope = rsiSlope; + conditions.strSlope = strSlope; + conditions.vwapMidSlope = vwapMidSlope; + conditions.vwapSlowSlope = vwapSlowSlope; + conditions.atrUpperSlope = atrUpperSlope; + conditions.atrLowerSlope = atrLowerSlope; + conditions.vwapFastSlope = vwapFastSlope; + conditions.isRsiSlopeBearish = isRsiSlopeBearish; + conditions.isStrSlopeBearish = isStrSlopeBearish; + conditions.isRsiSlopeBullish = isRsiSlopeBullish; + conditions.isStrSlopeBullish = isStrSlopeBullish; + conditions.isVwapMidSlopeBearish = isVwapMidSlopeBearish; + conditions.isVwapMidSlopeBullish = isVwapMidSlopeBullish; + conditions.isAtrUpperSlopeBearish = isAtrUpperSlopeBearish; + conditions.isAtrLowerSlopeBearish = isAtrLowerSlopeBearish; + conditions.isVwapFastSlopeBearish = isVwapFastSlopeBearish; + conditions.isVwapSlowSlopeBearish = isVwapSlowSlopeBearish; + conditions.isAtrUpperSlopeBullish = isAtrUpperSlopeBullish; + conditions.isAtrLowerSlopeBullish = isAtrLowerSlopeBullish; + conditions.isVwapFastSlopeBullish = isVwapFastSlopeBullish; + conditions.isVwapSlowSlopeBullish = isVwapSlowSlopeBullish; + + // + // Complex Conditions ... + + // + double x3maFast = conditions.x3maFastBuffer[cIDX]; + double x3maMid = conditions.x3maMidBuffer[cIDX]; + double x3maSlow = conditions.x3maSlowBuffer[cIDX]; + + // + double x3mas[3] = { + x3maFast, + x3maMid, + x3maSlow // + }; + + // + double x3maMin = GetMin(x3mas); + double x3maMax = GetMax(x3mas); + + // + bool isX3MaFatsOverMid = conditions.x3maFastBuffer[cIDX] > conditions.x3maMidBuffer[cIDX]; + bool isX3MaFatsOverMidPrev = conditions.x3maFastBuffer[pIDX] > conditions.x3maMidBuffer[pIDX]; + + // + bool isX3MaFatsUnderMid = conditions.x3maFastBuffer[cIDX] < conditions.x3maMidBuffer[cIDX]; + bool isX3MaFatsUnderMidPrev = conditions.x3maFastBuffer[pIDX] < conditions.x3maMidBuffer[pIDX]; + + // + bool isX3MaFatsOverSlow = conditions.x3maFastBuffer[cIDX] > conditions.x3maSlowBuffer[cIDX]; + bool isX3MaFatsOverSlowPrev = conditions.x3maFastBuffer[pIDX] > conditions.x3maSlowBuffer[pIDX]; + + // + bool isX3MaFatsUnderSlow = conditions.x3maFastBuffer[cIDX] < conditions.x3maSlowBuffer[cIDX]; + bool isX3MaFatsUnderSlowPrev = conditions.x3maFastBuffer[pIDX] < conditions.x3maSlowBuffer[pIDX]; + + // + bool isX3MaFastCrossedOverMid = isX3MaFatsOverMid && + !isX3MaFatsOverMidPrev; + bool isX3MaFastCrossedUnderMid = isX3MaFatsUnderMid && + !isX3MaFatsUnderMidPrev; + + // + bool isX3MaFastCrossedOverSlow = isX3MaFatsOverSlow && + !isX3MaFatsOverSlowPrev; + bool isX3MaFastCrossedUnderSlow = isX3MaFatsUnderSlow && + !isX3MaFatsUnderSlowPrev; + + // + bool isClosedOverX3MaMin = cBar.close > x3maMin; + bool isClosedUnderX3MaMin = cBar.close < x3maMin; + + // + bool isClosedOverX3MaMax = cBar.close > x3maMax; + bool isClosedUnderX3MaMax = cBar.close < x3maMax; + + // + // + // + + // + double vwapFast = conditions.vwapFastBuffer[cIDX]; + double vwapMid = conditions.vwapMidBuffer[cIDX]; + double vwapSlow = conditions.vwapSlowBuffer[cIDX]; + + // + double vwaps[3] = { + vwapFast, + vwapMid, + vwapSlow // + }; + + // + double vwapMin = GetMin(vwaps); + double vwapMax = GetMax(vwaps); + + // + bool isVWapFatsOverMid = conditions.vwapFastBuffer[cIDX] > conditions.vwapMidBuffer[cIDX]; + bool isVWapFatsOverMidPrev = conditions.vwapFastBuffer[pIDX] > conditions.vwapMidBuffer[pIDX]; + + // + bool isVWapFatsUnderMid = conditions.vwapFastBuffer[cIDX] < conditions.vwapMidBuffer[cIDX]; + bool isVWapFatsUnderMidPrev = conditions.vwapFastBuffer[pIDX] < conditions.vwapMidBuffer[pIDX]; + + // + bool isVWapFatsOverSlow = conditions.vwapFastBuffer[cIDX] > conditions.vwapSlowBuffer[cIDX]; + bool isVWapFatsOverSlowPrev = conditions.vwapFastBuffer[pIDX] > conditions.vwapSlowBuffer[pIDX]; + + // + bool isVWapFatsUnderSlow = conditions.vwapFastBuffer[cIDX] < conditions.vwapSlowBuffer[cIDX]; + bool isVWapFatsUnderSlowPrev = conditions.vwapFastBuffer[pIDX] < conditions.vwapSlowBuffer[pIDX]; + + // + bool isVWapFastCrossedOverMid = isVWapFatsOverMid && + !isVWapFatsOverMidPrev; + bool isVWapFastCrossedUnderMid = isVWapFatsUnderMid && + !isVWapFatsUnderMidPrev; + + // + bool isVWapFastCrossedOverSlow = isVWapFatsOverSlow && + !isVWapFatsOverSlowPrev; + bool isVWapFastCrossedUnderSlow = isVWapFatsUnderSlow && + !isVWapFatsUnderSlowPrev; + + // + bool isClosedOverVWapMin = cBar.close > vwapMin; + bool isClosedUnderVWapMin = cBar.close < vwapMin; + + // + bool isClosedOverVWapMax = cBar.close > vwapMax; + bool isClosedUnderVWapMax = cBar.close < vwapMax; + + // + bool isSarEqualsToPeak = + conditions.sarBuffer[cIDX] == conditions.peaksBuffer[cIDX]; + bool isSarEqualsToVale = + conditions.sarBuffer[cIDX] == conditions.valesBuffer[cIDX]; + + // + bool isSarIncreased = conditions.sarBuffer[cIDX] > conditions.sarBuffer[pIDX]; + bool isSarDecreased = conditions.sarBuffer[cIDX] < conditions.sarBuffer[pIDX]; + + // + double prevSar = conditions.sarBuffer[pIDX]; + double prevStr = conditions.strBuffer[pIDX]; + double prevCheLE1 = conditions.le1Buffer[pIDX]; + double prevCheLE2 = conditions.le2Buffer[pIDX]; + double prevCheSE1 = conditions.se1Buffer[pIDX]; + double prevCheSE2 = conditions.se2Buffer[pIDX]; + double prevAtrUpper = conditions.atrUpperBuffer[pIDX]; + double prevAtrLower = conditions.atrLowerBuffer[pIDX]; + + // + double ches[]; + if (prevCheLE1 != EMPTY_VALUE) + { + // + Add( + prevCheLE1, + ches // + ); + } + if (prevCheLE2 != EMPTY_VALUE) + { + // + Add( + prevCheLE2, + ches // + ); + } + if (prevCheSE1 != EMPTY_VALUE) + { + // + Add( + prevCheSE1, + ches // + ); + } + if (prevCheSE2 != EMPTY_VALUE) + { + // + Add( + prevCheSE2, + ches // + ); + } + + // + double cheMin = GetMin(ches); + double cheMax = GetMax(ches); + + // + bool isSarCrossedUnderPeak = + conditions.sarBuffer[cIDX] < conditions.peaksBuffer[cIDX] && + !(conditions.sarBuffer[pIDX] < conditions.peaksBuffer[pIDX]); + bool isSarCrossedOverVale = + conditions.sarBuffer[cIDX] > conditions.valesBuffer[cIDX] && + !(conditions.sarBuffer[pIDX] > conditions.valesBuffer[pIDX]); + + // + bool isStrEqualsToPeak = + conditions.strBuffer[cIDX] == conditions.peaksBuffer[cIDX]; + bool isStrEqualsToVale = + conditions.strBuffer[cIDX] == conditions.valesBuffer[cIDX]; + + // + bool isStrCrossedUnderPeak = + conditions.strBuffer[cIDX] < conditions.peaksBuffer[cIDX] && + !(conditions.strBuffer[pIDX] < conditions.peaksBuffer[pIDX]); + bool isStrCrossedOverVale = + conditions.strBuffer[cIDX] > conditions.valesBuffer[cIDX] && + !(conditions.strBuffer[pIDX] > conditions.valesBuffer[pIDX]); + + // + bool isPeakOverAtrUpper = + conditions.peaksBuffer[cIDX] > conditions.atrUpperBuffer[cIDX]; + bool isValeUnderAtrLower = + conditions.valesBuffer[cIDX] > conditions.atrLowerBuffer[cIDX]; + + // + bool isNewPeakOverAtrUpper = + isPeakOverAtrUpper && + conditions.isNewPeak; + bool isNewValeUnderAtrLower = + isValeUnderAtrLower && + conditions.isNewVale; + + // + bool isStrUpperOverPeak = + conditions.strBuffer[cIDX] > conditions.peaksBuffer[cIDX]; + bool isStrUpperOverPeakPrev = + conditions.strBuffer[pIDX] > conditions.peaksBuffer[pIDX]; + + // + bool isStrUpperUnderPeak = + conditions.strBuffer[cIDX] < conditions.peaksBuffer[cIDX]; + bool isStrUpperUnderPeakPrev = + conditions.strBuffer[pIDX] < conditions.peaksBuffer[pIDX]; + + // + bool isStrUpperCrossedOverPeak = isStrUpperOverPeak && + !isStrUpperOverPeakPrev; + bool isStrUpperCrossedUnderPeak = isStrUpperUnderPeak && + !isStrUpperUnderPeakPrev; + + // + bool isStrLowerOverVale = + conditions.strBuffer[cIDX] > conditions.valesBuffer[cIDX]; + bool isStrLowerOverValePrev = + conditions.strBuffer[pIDX] > conditions.valesBuffer[pIDX]; + + // + bool isStrLowerUnderVale = + conditions.strBuffer[cIDX] < conditions.valesBuffer[cIDX]; + bool isStrLowerUnderValePrev = + conditions.strBuffer[pIDX] < conditions.valesBuffer[pIDX]; + + // + bool isStrLowerCrossedOverVale = isStrLowerOverVale && + !isStrLowerOverValePrev; + bool isStrLowerCrossedUnderVale = isStrLowerUnderVale && + !isStrLowerUnderValePrev; + + // + bool isDonHighUpperEqualsToPeak = + conditions.donHighUpperBuffer[cIDX] == conditions.peaksBuffer[cIDX]; + bool isDonLowLowerEqualsToVale = + conditions.donLowLowerBuffer[cIDX] == conditions.valesBuffer[cIDX]; + + // + bool isStrUpperOverAtrUpper = + conditions.strUpBuffer[cIDX] > conditions.atrUpperBuffer[cIDX]; + bool isStrUpperOverAtrUpperPrev = + conditions.strUpBuffer[pIDX] > conditions.atrUpperBuffer[pIDX]; + bool isStrUpperCrossedOverAtrUpper = isStrUpperOverAtrUpper && + !isStrUpperOverAtrUpperPrev; + + // + bool isStrUpperUnderAtrUpper = + conditions.strUpBuffer[cIDX] < conditions.atrUpperBuffer[cIDX]; + bool isStrUpperUnderAtrUpperPrev = + conditions.strUpBuffer[pIDX] < conditions.atrUpperBuffer[pIDX]; + bool isStrUpperCrossedUnderAtrUpper = isStrUpperUnderAtrUpper && + !isStrUpperUnderAtrUpperPrev; + + // + bool isStrLowerOverAtrLower = + conditions.strDownBuffer[cIDX] > conditions.atrLowerBuffer[cIDX]; + bool isStrLowerOverAtrLowerPrev = + conditions.strDownBuffer[pIDX] > conditions.atrLowerBuffer[pIDX]; + bool isStrLowerCrossedOverAtrLower = isStrLowerOverAtrLower && + !isStrLowerOverAtrLowerPrev; + + // + bool isStrLowerUnderAtrLower = + conditions.strDownBuffer[cIDX] < conditions.atrLowerBuffer[cIDX]; + bool isStrLowerUnderAtrLowerPrev = + conditions.strDownBuffer[pIDX] < conditions.atrLowerBuffer[pIDX]; + bool isStrLowerCrossedUnderAtrLower = isStrLowerUnderAtrLower && + !isStrLowerUnderAtrLowerPrev; + + // + bool isStrUpperOverDonHighUpper = + conditions.strUpBuffer[cIDX] > conditions.donHighUpperBuffer[cIDX]; + bool isStrUpperOverDonHighUpperPrev = + conditions.strUpBuffer[pIDX] > conditions.donHighUpperBuffer[pIDX]; + bool isStrUpperCrossedOverDonHighUpper = isStrUpperOverDonHighUpper && + !isStrUpperOverDonHighUpperPrev; + + // + bool isStrUpperUnderDonHighUpper = + conditions.strUpBuffer[cIDX] < conditions.donHighUpperBuffer[cIDX]; + bool isStrUpperUnderDonHighUpperPrev = + conditions.strUpBuffer[pIDX] < conditions.donHighUpperBuffer[pIDX]; + bool isStrUpperCrossedUnderDonHighUpper = isStrUpperUnderDonHighUpper && + !isStrUpperUnderDonHighUpperPrev; + + // + bool isStrLowerOverDonLowLower = + conditions.strDownBuffer[cIDX] > conditions.donLowLowerBuffer[cIDX]; + bool isStrLowerOverDonLowLowerPrev = + conditions.strDownBuffer[pIDX] > conditions.donLowLowerBuffer[pIDX]; + bool isStrLowerCrossedOverDonLowLower = isStrLowerOverDonLowLower && + !isStrLowerOverDonLowLowerPrev; + + // + bool isStrLowerUnderDonLowLower = + conditions.strDownBuffer[cIDX] < conditions.donLowLowerBuffer[cIDX]; + bool isStrLowerUnderDonLowLowerPrev = + conditions.strDownBuffer[pIDX] < conditions.donLowLowerBuffer[pIDX]; + bool isStrLowerCrossedUnderDonLowLower = isStrLowerUnderDonLowLower && + !isStrLowerUnderDonLowLowerPrev; + + // + bool isAtrUpperOverPeak = conditions.atrUpperBuffer[cIDX] > conditions.peaksBuffer[cIDX]; + bool isAtrUpperEqualsToPeak = conditions.atrUpperBuffer[cIDX] == conditions.peaksBuffer[cIDX]; + + // + bool isAtrUpperCrossedUpPeak = conditions.atrUpperBuffer[cIDX] > conditions.peaksBuffer[cIDX] && + !(conditions.atrUpperBuffer[cIDX] > conditions.peaksBuffer[cIDX]); + bool isAtrUpperCrossedDownPeak = conditions.atrUpperBuffer[cIDX] < conditions.peaksBuffer[cIDX] && + !(conditions.atrUpperBuffer[cIDX] < conditions.peaksBuffer[cIDX]); + + // + bool isAtrLowerUnderVale = conditions.atrUpperBuffer[cIDX] < conditions.valesBuffer[cIDX]; + bool isAtrLowerEqualsToVale = conditions.atrUpperBuffer[cIDX] == conditions.valesBuffer[cIDX]; + + // + bool isAtrLowerCrossedUpVale = conditions.atrUpperBuffer[cIDX] > conditions.valesBuffer[cIDX] && + !(conditions.atrUpperBuffer[cIDX] > conditions.valesBuffer[cIDX]); + bool isAtrLowerCrossedDownVale = conditions.atrUpperBuffer[cIDX] < conditions.valesBuffer[cIDX] && + !(conditions.atrUpperBuffer[cIDX] < conditions.valesBuffer[cIDX]); + + // + conditions.cheMin = cheMin; + conditions.cheMax = cheMax; + conditions.x3maMin = x3maMin; + conditions.x3maMax = x3maMax; + conditions.vwapMin = vwapMin; + conditions.vwapMax = vwapMax; + + // + conditions.isSarIncreased = isSarIncreased; + conditions.isSarDecreased = isSarDecreased; + conditions.isSarEqualsToPeak = isSarEqualsToPeak; + conditions.isSarEqualsToVale = isSarEqualsToVale; + conditions.isStrEqualsToPeak = isStrEqualsToPeak; + conditions.isStrEqualsToVale = isStrEqualsToVale; + conditions.isX3MaFatsOverMid = isX3MaFatsOverMid; + conditions.isX3MaFatsUnderMid = isX3MaFatsUnderMid; + conditions.isX3MaFatsOverSlow = isX3MaFatsOverSlow; + conditions.isStrUpperOverPeak = isStrUpperOverPeak; + conditions.isPeakOverAtrUpper = isPeakOverAtrUpper; + conditions.isStrLowerOverVale = isStrLowerOverVale; + conditions.isAtrUpperOverPeak = isAtrUpperOverPeak; + conditions.isClosedOverX3MaMin = isClosedOverX3MaMin; + conditions.isClosedOverX3MaMax = isClosedOverX3MaMax; + conditions.isX3MaFatsUnderSlow = isX3MaFatsUnderSlow; + conditions.isAtrLowerUnderVale = isAtrLowerUnderVale; + conditions.isStrLowerUnderVale = isStrLowerUnderVale; + conditions.isStrUpperUnderPeak = isStrUpperUnderPeak; + conditions.isValeUnderAtrLower = isValeUnderAtrLower; + conditions.isClosedOverVWapMin = isClosedOverVWapMin; + conditions.isClosedOverVWapMax = isClosedOverVWapMax; + conditions.isClosedUnderX3MaMin = isClosedUnderX3MaMin; + conditions.isClosedUnderX3MaMax = isClosedUnderX3MaMax; + conditions.isClosedUnderVWapMin = isClosedUnderVWapMin; + conditions.isClosedUnderVWapMax = isClosedUnderVWapMax; + conditions.isSarCrossedOverVale = isSarCrossedOverVale; + conditions.isStrCrossedOverVale = isStrCrossedOverVale; + conditions.isX3MaFatsOverMidPrev = isX3MaFatsOverMidPrev; + conditions.isSarCrossedUnderPeak = isSarCrossedUnderPeak; + conditions.isStrCrossedUnderPeak = isStrCrossedUnderPeak; + conditions.isNewPeakOverAtrUpper = isNewPeakOverAtrUpper; + conditions.isX3MaFatsUnderMidPrev = isX3MaFatsUnderMidPrev; + conditions.isX3MaFatsOverSlowPrev = isX3MaFatsOverSlowPrev; + conditions.isAtrUpperEqualsToPeak = isAtrUpperEqualsToPeak; + conditions.isAtrLowerEqualsToVale = isAtrLowerEqualsToVale; + conditions.isNewValeUnderAtrLower = isNewValeUnderAtrLower; + conditions.isStrUpperOverAtrUpper = isStrUpperOverAtrUpper; + conditions.isStrLowerOverAtrLower = isStrLowerOverAtrLower; + conditions.isX3MaFatsUnderSlowPrev = isX3MaFatsUnderSlowPrev; + conditions.isStrUpperUnderAtrUpper = isStrUpperUnderAtrUpper; + conditions.isStrLowerUnderAtrLower = isStrLowerUnderAtrLower; + conditions.isAtrUpperCrossedUpPeak = isAtrUpperCrossedUpPeak; + conditions.isAtrLowerCrossedUpVale = isAtrLowerCrossedUpVale; + conditions.isX3MaFastCrossedOverMid = isX3MaFastCrossedOverMid; + conditions.isVWapFastCrossedOverMid = isVWapFastCrossedOverMid; + conditions.isX3MaFastCrossedUnderMid = isX3MaFastCrossedUnderMid; + conditions.isX3MaFastCrossedOverSlow = isX3MaFastCrossedOverSlow; + conditions.isAtrUpperCrossedDownPeak = isAtrUpperCrossedDownPeak; + conditions.isAtrLowerCrossedDownVale = isAtrLowerCrossedDownVale; + conditions.isVWapFastCrossedUnderMid = isVWapFastCrossedUnderMid; + conditions.isDonLowLowerEqualsToVale = isDonLowLowerEqualsToVale; + conditions.isStrUpperCrossedOverPeak = isStrUpperCrossedOverPeak; + conditions.isStrLowerCrossedOverVale = isStrLowerCrossedOverVale; + conditions.isStrLowerOverDonLowLower = isStrLowerOverDonLowLower; + conditions.isVWapFastCrossedOverSlow = isVWapFastCrossedOverSlow; + conditions.isX3MaFastCrossedUnderSlow = isX3MaFastCrossedUnderSlow; + conditions.isVWapFastCrossedUnderSlow = isVWapFastCrossedUnderSlow; + conditions.isStrUpperOverDonHighUpper = isStrUpperOverDonHighUpper; + conditions.isStrLowerUnderDonLowLower = isStrLowerUnderDonLowLower; + conditions.isDonHighUpperEqualsToPeak = isDonHighUpperEqualsToPeak; + conditions.isStrUpperCrossedUnderPeak = isStrUpperCrossedUnderPeak; + conditions.isStrLowerCrossedUnderVale = isStrLowerCrossedUnderVale; + conditions.isStrUpperUnderDonHighUpper = isStrUpperUnderDonHighUpper; + conditions.isStrLowerCrossedOverAtrLower = isStrLowerCrossedOverAtrLower; + conditions.isStrUpperCrossedOverAtrUpper = isStrUpperCrossedOverAtrUpper; + conditions.isStrUpperCrossedUnderAtrUpper = isStrUpperCrossedUnderAtrUpper; + conditions.isStrLowerCrossedUnderAtrLower = isStrLowerCrossedUnderAtrLower; + conditions.isStrLowerCrossedOverDonLowLower = isStrLowerCrossedOverDonLowLower; + conditions.isStrUpperCrossedOverDonHighUpper = isStrUpperCrossedOverDonHighUpper; + conditions.isStrLowerCrossedUnderDonLowLower = isStrLowerCrossedUnderDonLowLower; + conditions.isStrUpperCrossedUnderDonHighUpper = isStrUpperCrossedUnderDonHighUpper; + + // + // + xpvConditions.Clean(); + xhkConditions.Clean(); + xichConditions.Clean(); + xmasConditions.Clean(); + xatrConditions.Clean(); + xstrConditions.Clean(); + xcheConditions.Clean(); + xdonConditions.Clean(); + x3maConditions.Clean(); + xvwapConditions.Clean(); + + // + Free(); + + // + return result; + } + + // + protected: + // + + // + private: + // + + // + string mSymbol; // Trading Symbol + ENUM_TIMEFRAMES mPeriod; // Trading Period + + // + // Inputs ... + X121Inputs mInputs; + X121XCCInputs xccInputs; + X121XPVInputs xpvInputs; + X121XHKInputs xhkInputs; + X121XICHInputs xichInputs; + X121XMASInputs xmasInputs; + X121XATRInputs xatrInputs; + X121XDONInputs xdonInputs; + X121XSTRInputs xstrInputs; + X121XCHEInputs xcheInputs; + X121X3MAInputs x3maInputs; + X121XVWAPInputs xvwapInputs; + X121XDELTAInputs xdeltaInputs; + X121XVOLUMEInputs xvolumeInputs; + + // + int mRSIHandler; +}; + +// \ No newline at end of file diff --git a/BKPS/14040203/Documents/BKP/x-saherelm.x121.xcdv.mq5 b/BKPS/14040203/Documents/BKP/x-saherelm.x121.xcdv.mq5 new file mode 100644 index 0000000..ce81dda --- /dev/null +++ b/BKPS/14040203/Documents/BKP/x-saherelm.x121.xcdv.mq5 @@ -0,0 +1,573 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Ocillator +// ------------------------------------------------- +// Name: X121 XCDV +// Description: Detect Comulative Delta Volume ... +// +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +////////////////////////////////////////////////////// +// +// Global Properties ... +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://saherelm.ir" +#property version "1.00" +#property description "SaherElm X121 XCDV Ocillator" +#property strict + +// +// Definitions ... + +// +#define ShortName "X121_XCDV" + +// +// Imports ... +#include "../Libraries/x-saherelm.common.lib.mq5" + +// +// Inputs ... + +// +// Makret ... +input group "Market"; +input int maLength = 14; // Moving Averge Length +input ENUM_X_PRICE maAppliedTo = X_PRICE_CLOSE; // Moving Averge Applied To +input ENUM_X_MA_METHOD maMethod = X_MA_MODE_EMA; // Moving Averge Method + +// +// Presentation ... +input group "Presentation"; +input int startCalculationForLastBars = 1000; // Calculate Last n Bars +input bool showCDV = true; // Show Delta Line +input bool showMA = true; // Show Delta Histogram + +// +// Buffers Props ... + +// +#property indicator_separate_window + +// +#property indicator_buffers 10 +#property indicator_plots 2 + +// +#define hideColorIDX 0 +#define bullishColorIDX 1 +#define bearishColorIDX 2 + +// +// Buffers ... + +// +#define openBufferIndex 0 +double openBuffer[]; + +// +#define highBufferIndex 1 +double highBuffer[]; + +// +#define lowBufferIndex 2 +double lowBuffer[]; + +// +#define closeBufferIndex 3 +double closeBuffer[]; + +// +#define colorBufferIndex 4 +double colorBuffer[]; + +// +#define barBufferIndex 0 +#property indicator_label1 "X121 XCDV Open;X121 XCDV High;X121 XCDV Low;X121 XCDV Close" +#property indicator_type1 DRAW_COLOR_CANDLES +#property indicator_color1 CLR_NONE, clrLime, clrRed + +// +#define maBufferIndex 5 +double maBuffer[]; + +#property indicator_label2 "MA" +#property indicator_type2 DRAW_LINE +#property indicator_color2 clrYellow +#property indicator_style2 STYLE_SOLID +#property indicator_width2 1 + +// +// Data Buffers ... + +#define mLastBufferIndex 5 + +#define priceBufferIndex mLastBufferIndex + 1 +double priceBuffer[]; + +#define deltaBufferIndex mLastBufferIndex + 2 +double deltaBuffer[]; + +#define cumulativeDeltaBufferIndex mLastBufferIndex + 3 +double cumulativeDeltaBuffer[]; + +// +// Variables, Properties and etc ... + +// +// this counts Available Bars ... +int limit; + +// +int maxLength; + +// +double lastCDV = 0.0; + +// +// Event Handlers ... + +/** + * Initialize Indicator ... + * + * @return ( int ) + */ +int OnInit() +{ + // + // Validate Inputs ... + if (!ValidateInputs()) + { + return INIT_PARAMETERS_INCORRECT; + } + + // + // Initialize Indicator Handlers ... + + // + // because in some cases we may have more than one input for + // calculation and we must prevent any calculation + // untill we pass the biggest input length, here we get max Input length + // and then wait until pass it ... + maxLength = ExtractMaxLengthOfInputs(); + + // + // Define Index Buffers ... + DefineBuffers(); + + // + // Set Indicator ShortName ... + SetIndicatorName(); + IndicatorSetInteger(INDICATOR_DIGITS, 2); + + // + // Init Succeed ... + return INIT_SUCCEEDED; +} + +/** + * De Initialize Indicator ... + * + * @param reason: Integer, De Initialization Reason ... + */ +void OnDeinit(const int reason) +{ + // + // REASON_PROGRAM 0 The EA has stopped working calling the ExpertRemove() function + // REASON_REMOVE 1 Program removed from a chart + // REASON_RECOMPILE 2 Program recompiled + // REASON_CHARTCHANGE 3 A symbol or a chart period is changed + // REASON_CHARTCLOSE 4 Chart closed + // REASON_PARAMETERS 5 Inputs changed by a user + // REASON_ACCOUNT 6 Another account has been activated or reconnection to the trade server has occurred due to changes in the account settings + // REASON_TEMPLATE 7 Another chart template applied + // REASON_INITFAILED 8 The OnInit() handler returned a non-zero value + // REASON_CLOSE 9 Terminal closed +} + +/** + * Calculate Bars ... + * + * @param rates_total: Integer, Total Bars on Chart ... + * @param prev_calculated: Integer, Total Calculated Bars on Charts ... + * @param time: DateTime Array, History of Open Time ... + * @param open: Double Array, History of Open Prices ... + * @param high: Double Array, History of High Prices ... + * @param low: Double Array, History of Low Prices ... + * @param close: Double Array, History of Close Prices ... + * @param tick_volume: Long, History of Tick Volumes on Bar ... + * @param volume: Long, History of Trade Volumes ... + * @param spread: Double, History of Spread Price ... + * + * @return ( int ) + */ +int OnCalculate( + const int rates_total, + const int prev_calculated, + const datetime &time[], + const double &open[], + const double &high[], + const double &low[], + const double &close[], + const long &tick_volume[], + const long &volume[], + const int &spread[] // +) +{ + // + // Prepare Buffers ... + ArraySetAsSeries(time, true); + ArraySetAsSeries(open, true); + ArraySetAsSeries(high, true); + ArraySetAsSeries(low, true); + ArraySetAsSeries(close, true); + ArraySetAsSeries(tick_volume, true); + ArraySetAsSeries(volume, true); + ArraySetAsSeries(spread, true); + + // + limit = (prev_calculated > rates_total || prev_calculated <= 0) + ? rates_total + : (rates_total - prev_calculated) + 1; + + // + // Main Loop ... + for (int i = limit - 1; i >= 0 && !IsStopped(); i--) + { + // + CalculateBuffers( + // + i, + prev_calculated, + rates_total, + // + open, + high, + close, + low, + tick_volume // + ); + } + + // + return rates_total; +} + +// +// Functions ... + +/** + * Validate Input Args for Initialization ... + * + * @return ( bool ) + */ +bool ValidateInputs() +{ + // + bool result = false; + + // + result = maLength > 0 && + IsValid(maMethod) && + IsValid(maAppliedTo); + + // + return result; +} + +/** + * Extract Max Length of Inputs ... + * + * @return ( int ) + */ +int ExtractMaxLengthOfInputs() +{ + // + int result = 0; + + // + result = MathMax(0, maLength); + + // + return result; +} + +/** + * Set Indicator Short Name and also we can define Buffers Labels ... + */ +void SetIndicatorName() +{ + IndicatorSetString(INDICATOR_SHORTNAME, ShortName); +} + +/** + * Define Required Buffers ... + */ +void DefineBuffers() +{ + // + // Plot Buffers ... + + // + // CDV ... + + // + // Raw Candles Color ... + ArraySetAsSeries(colorBuffer, true); + SetIndexBuffer(colorBufferIndex, colorBuffer, INDICATOR_COLOR_INDEX); + + // + ENUM_DRAW_TYPE barDrawType = showCDV ? DRAW_COLOR_CANDLES : DRAW_NONE; + + // + // Set EMPTY_VALUE on Candles Buffer ... + PlotIndexSetDouble(barBufferIndex, PLOT_EMPTY_VALUE, 0.0); + PlotIndexSetInteger(barBufferIndex, PLOT_SHOW_DATA, showCDV); + PlotIndexSetInteger(barBufferIndex, PLOT_DRAW_TYPE, barDrawType); + + // + // Open ... + ArraySetAsSeries(openBuffer, true); + SetIndexBuffer(openBufferIndex, openBuffer, INDICATOR_DATA); + + // + // High ... + ArraySetAsSeries(highBuffer, true); + SetIndexBuffer(highBufferIndex, highBuffer, INDICATOR_DATA); + + // + // Close ... + ArraySetAsSeries(closeBuffer, true); + SetIndexBuffer(closeBufferIndex, closeBuffer, INDICATOR_DATA); + + // + // Low ... + ArraySetAsSeries(lowBuffer, true); + SetIndexBuffer(lowBufferIndex, lowBuffer, INDICATOR_DATA); + + // + // Ma ... + ENUM_DRAW_TYPE maDrawType = showMA ? DRAW_LINE : DRAW_NONE; + + // + ArraySetAsSeries(maBuffer, true); + SetIndexBuffer(maBufferIndex, maBuffer, INDICATOR_DATA); + PlotIndexSetDouble(maBufferIndex, PLOT_EMPTY_VALUE, 0); + PlotIndexSetInteger(maBufferIndex, PLOT_SHOW_DATA, showMA); + PlotIndexSetInteger(maBufferIndex, PLOT_DRAW_TYPE, maDrawType); + + // + // Data Buffers ... + + // + ArraySetAsSeries(priceBuffer, true); + SetIndexBuffer(priceBufferIndex, priceBuffer, INDICATOR_CALCULATIONS); + + // + ArraySetAsSeries(deltaBuffer, true); + SetIndexBuffer(deltaBufferIndex, deltaBuffer, INDICATOR_CALCULATIONS); + + // + ArraySetAsSeries(cumulativeDeltaBuffer, true); + SetIndexBuffer(cumulativeDeltaBufferIndex, cumulativeDeltaBuffer, INDICATOR_CALCULATIONS); +} + +/** + * Calculate Custom Buffers ... + * + * @param bar_index: Integer, Represent Current Bar ... + * @param prevCalculated: Integer, Represent Previous Calculated Bars ... + * @param ratesTotal: Integer, Represents All Available Bars ... + * @param open: Double Array, History of Open Prices ... + * @param high: Double Array, History of High Prices ... + * @param close: Double Array, History of Close Prices ... + * @param low: Double Array, History of Low Prices ... + * @param tickVolume: Long, History of Tick Volumes on Bar ... + */ +void CalculateBuffers( + int bar_index, // Selected Bar Index + const int prevCalculated, + const int ratesTotal, + const double &open[], + const double &high[], + const double &close[], + const double &low[], + const long &tickVolume[] // +) +{ + // + int barsLimit = startCalculationForLastBars > 0 + ? startCalculationForLastBars + : 0; + // + // bool canCalculate = true; + bool canCalculate = + barsLimit == 0 || + bar_index <= barsLimit; + if (canCalculate) + { + // + CalculateValues( + bar_index, + prevCalculated, + ratesTotal, + open, + high, + close, + low, + tickVolume // + ); + } + else + { + FillBuffersZero(bar_index); + } +} + +/** + * Fill All Bufers to Zero Vlue for Specified Bar Index ... + * + * @param barIndex: Integer ... + */ +void FillBuffersZero(int barIndex) +{ + // + openBuffer[barIndex] = 0.0; + highBuffer[barIndex] = 0.0; + closeBuffer[barIndex] = 0.0; + lowBuffer[barIndex] = 0.0; + colorBuffer[barIndex] = hideColorIDX; +} + +/** + * Calculate Vales ... + * + * @param bar_index: Integer, Represent Current Bar ... + * @param prevCalculated: Integer, Represent Previous Calculated Bars ... + * @param ratesTotal: Integer, Represents All Available Bars ... + * @param open: Double Array, History of Open Prices ... + * @param high: Double Array, History of High Prices ... + * @param close: Double Array, History of Close Prices ... + * @param low: Double Array, History of Low Prices ... + * @param tickVolume: Long, History of Tick Volumes on Bar ... + */ +void CalculateValues( + int bar_index, // Selected Bar Index + const int prevCalculated, + const int ratesTotal, + const double &open[], + const double &high[], + const double &close[], + const double &low[], + const long &tickVolume[] // +) +{ + // + XOHCL bar; + bool has = bar.Init( + _Symbol, + _Period, + bar_index // + ); + if (!has) + { + return; + } + + // + double lowShadow = bar.GetLowShadow(); + double highShadow = bar.GetHighShadow(); + double body = bar.GetBody(); + bool isBullish = bar.IsBullish(); + bool hasDir = HasDirection(bar.GetDirection()); + + // + double iRate = 0.5 * (highShadow + lowShadow + (hasDir ? 2 * body : 0)) / (highShadow + lowShadow + body); + iRate = iRate <= 0 + ? 0.5 + : iRate; + + // + double iVRate = tickVolume[bar_index] * iRate; + double iDelta = isBullish + ? iVRate + : -1 * iVRate; + deltaBuffer[bar_index] = iDelta; + + // + double iCumulate = lastCDV + iDelta; + cumulativeDeltaBuffer[bar_index] = iCumulate; + lastCDV = iCumulate; + + // + bool isFirstBar = + startCalculationForLastBars > 0 + ? bar_index == startCalculationForLastBars + : bar_index == ratesTotal; + + // + double iO = 0; + double iH = 0; + double iL = 0; + double iC = 0; + if (!isFirstBar) + { + // + iO = cumulativeDeltaBuffer[bar_index + 1]; + iH = MathMax(cumulativeDeltaBuffer[bar_index], cumulativeDeltaBuffer[bar_index + 1]); + iL = MathMin(cumulativeDeltaBuffer[bar_index], cumulativeDeltaBuffer[bar_index + 1]); + iC = iCumulate; + } + + // + double iClose = (iO + iH + iL + iC) / 4; + double iOpen = isFirstBar + ? (iO + iC) / 2 + : (openBuffer[bar_index + 1] + closeBuffer[bar_index + 1]) / 2; + double iLow = MathMin(iL, MathMin(iOpen, iClose)); + double iHigh = MathMax(iH, MathMax(iOpen, iClose)); + + // + lowBuffer[bar_index] = iLow; + openBuffer[bar_index] = iOpen; + highBuffer[bar_index] = iHigh; + closeBuffer[bar_index] = iClose; + + // + bool isCBullish = iOpen <= iClose; + double iColor = isCBullish + ? bullishColorIDX + : bearishColorIDX; + colorBuffer[bar_index] = iColor; + + // + double iPrice = GetAppliedPrice( + maAppliedTo, + openBuffer, + highBuffer, + lowBuffer, + closeBuffer, + bar_index // + ); + priceBuffer[bar_index] = iPrice; + + // + // Calculate Moving Averages ... + int deltaMAsCount = iMAOnBuffer( + ratesTotal, + prevCalculated, + bar_index, + maLength, + priceBuffer, + maBuffer, + maMethod // + ); + + // + bar.Clean(); +} + +// diff --git a/BKPS/14040203/Documents/BKP/x-saherelm.x121.xich.mq5 b/BKPS/14040203/Documents/BKP/x-saherelm.x121.xich.mq5 new file mode 100644 index 0000000..02df92f --- /dev/null +++ b/BKPS/14040203/Documents/BKP/x-saherelm.x121.xich.mq5 @@ -0,0 +1,846 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Indicator +// ------------------------------------------------- +// Name: XICH +// Description: Ichimoku Kinko Hyo ... +// +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +////////////////////////////////////////////////////// +// +// Global Properties ... +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://saherelm.ir" +#property version "1.00" +#property description "SaherElm XICH Indicator" +#property strict + +// +// START Constants ... +// + +// +// Indicator Short Name ... +#define ShortName "X121 XICH" + +// +// Ichimoku Golden Numbers ... +enum ENUM_X_ICHIMOKU_GOLDEN_NUMBERS +{ + X_ICH_BASE = 9, + X_ICH_GOLDEN = 17, + X_ICH_CYCLE = 26, + X_ICH_PERIOD = 35, + X_ICH_STAR = 45, + X_ICH_MED = 52, + X_ICH_LONG = 63, + X_ICH_FULL = 72 +}; + +// +// Ichimoku Lines Calculator Mode ... +enum ENUM_X_ICHIMOKU_CALCULATION_MODE +{ + // + X_XICH_HH_LL_MODE = 1, // Highest High and Lowest Low + X_XICH_HO_LC_MODE = 2, // Highest Open and Lowest Close +}; + +// +// END Constants ... +// + +// +// START Inputs ... +// + +// +// ICHIMOKU Kinko Hyo ... + +// +// TENKANSEN ... +input group "Tenkan Sen"; +input int tenkanSenLength = 9; // Length +input ENUM_X_ICHIMOKU_CALCULATION_MODE tenkanSenMode = X_XICH_HH_LL_MODE; // Calculation Mode + +// +// KIJUNSEN ... +input group "Kijun Sen"; +input int kijunSenLength = 26; // Length +input ENUM_X_ICHIMOKU_CALCULATION_MODE kijunSenMode = X_XICH_HH_LL_MODE; // Calculation Mode + +// +// SENKOUSPANB ... +input group "Senkou Span B"; +input int senkouSpanBLength = 52; // Length +input ENUM_X_ICHIMOKU_CALCULATION_MODE senkouSpanBMode = X_XICH_HH_LL_MODE; // Calculation Mode + +// +// CHIKOUSPAN ... +input group "Chikou Span"; +input ENUM_APPLIED_PRICE chikuoSpanAppliedTo = PRICE_CLOSE; // Price Type + +// +input group "Presentation"; +input bool showTenkanSen = true; // Show Tenkan Sen +input bool showKijunSen = true; // Show Kijun Sen +input bool showKijunSenPlus = false; // Show Kijun Sen + +input bool showKijunSenNegative = false; // Show Kijun Sen - +input bool showChikouSpan = true; // Show Chikou Span +input bool showSenkouSpanA = true; // Show Senkou Span A +input bool showSenkouSpanB = true; // Show Senkou Span B +input bool showKumo = true; // Show Kumo +input bool shiftKumo = true; // Shift Kumo to Future + +// +// END Inputs ... +// + +// +// START Includes and Imports ... +// + +// +// Includes Common Library ... +#include "../Libraries/x-saherelm.common.lib.mq5" + +// +// END Includes and Imports ... +// + +// +// START Buffers ... +// +#property indicator_chart_window + +// +#property indicator_buffers 15 +#property indicator_plots 8 + +// +// PLOTTED Buffers ... + +// +// ICHIMOKU ... + +// +// TENKANSEN ... + +// +#define tenkanSenBufferIndex 0 +double tenkanSenBuffer[]; + +// +#property indicator_label1 "XICH TK" +#property indicator_type1 DRAW_LINE +#property indicator_color1 clrBrown +#property indicator_style1 STYLE_SOLID +#property indicator_width1 1 + +// +// KIJUNSEN ... + +// +#define kijunSenBufferIndex 1 +double kijunSenBuffer[]; + +// +#property indicator_label2 "XICH KJ" +#property indicator_type2 DRAW_LINE +#property indicator_color2 clrDodgerBlue +#property indicator_style2 STYLE_SOLID +#property indicator_width2 1 + +// +#define kijunSenPlusBufferIndex 2 +double kijunSenPlusBuffer[]; + +// +#property indicator_label3 "XICH KJ+" +#property indicator_type3 DRAW_LINE +#property indicator_color3 clrMediumTurquoise +#property indicator_style3 STYLE_DOT +#property indicator_width3 1 + +// +#define kijunSenNegativeBufferIndex 3 +double kijunSenNegativeBuffer[]; + +// +#property indicator_label4 "XICH KJ-" +#property indicator_type4 DRAW_LINE +#property indicator_color4 clrDarkSeaGreen +#property indicator_style4 STYLE_DOT +#property indicator_width4 1 + +// +// CHIKOUSPAN ... + +// +#define chikouSpanBufferIndex 4 +double chikouSpanBuffer[]; + +// +#property indicator_label5 "XICH CS" +#property indicator_type5 DRAW_LINE +#property indicator_color5 clrDarkGreen +#property indicator_style5 STYLE_SOLID +#property indicator_width5 1 + +// +#define senkouABufferIndex 5 +double senkouABuffer[]; + +// +#property indicator_label6 "XICH SSA" +#property indicator_type6 DRAW_LINE +#property indicator_color6 clrLightGray +#property indicator_style6 STYLE_DASHDOTDOT +#property indicator_width6 1 + +// +#define senkouBBufferIndex 6 +double senkouBBuffer[]; + +// +#property indicator_label7 "XICH SSB" +#property indicator_type7 DRAW_LINE +#property indicator_color7 clrLightGray +#property indicator_style7 STYLE_DASHDOTDOT +#property indicator_width7 1 + +// +// KUMO ... + +// +// SENKOUSPANA ... + +// +#define senkouSpanABufferIndex 7 +double senkouSpanABuffer[]; + +// +// SENKOUSPANB ... + +// +#define senkouSpanBBufferIndex 8 +double senkouSpanBBuffer[]; + +// +// KUMOCLOUD ... + +// +#define kumoBufferIndex 7 + +// +#property indicator_label8 "XICH Kumo" +#property indicator_type8 DRAW_FILLING +#property indicator_color8 clrAqua, clrMagenta +#property indicator_style8 STYLE_SOLID +#property indicator_width8 1 + +// +// DATA Buffers ... + +// +#define dTenkanBufferIndex 9 +double dTenkanBuffer[]; + +// +#define dKijunBufferIndex 10 +double dKijunBuffer[]; + +// +#define dChikouBufferIndex 11 +double dChikouBuffer[]; + +// +#define dSSABufferIndex 12 +double dSSABuffer[]; + +// +#define dSSBBufferIndex 13 +double dSSBBuffer[]; + +// +// END Buffers ... +// + +// +// START Global Definitions: Variables, Properties and etc ... +// + +// +int maxLength; +int mHandler; + +// +ENUM_SERIESMODE mTenkanSenTopMode = NULL; +ENUM_SERIESMODE mTenkanSenBottomMode = NULL; + +// +ENUM_SERIESMODE mKijunSenTopMode = NULL; +ENUM_SERIESMODE mKijunSenBottomMode = NULL; + +// +ENUM_SERIESMODE mSenkouSpanBTopMode = NULL; +ENUM_SERIESMODE mSenkouSpanBBottomMode = NULL; + +// +// END Global Definitions: Variables, Properties and etc ... +// + +// +// START Event Handlers ... +// + +// +// Initialization ... +int OnInit() +{ + // + // Validate Inputs ... + if (!ValidateInputs()) + { + return INIT_PARAMETERS_INCORRECT; + } + + // + // because in some cases we may have more than one input for + // calculation and we must prevent any calculation + // untill we pass the biggest input length, here we get max Input length + // and then wait until pass it ... + maxLength = ExtractMaxLengthOfInputs(); + + // + // Define Index Buffers ... + DefineBuffers(); + + // + // Init Handler ... + mHandler = iIchimoku( + _Symbol, + _Period, + tenkanSenLength, + kijunSenLength, + senkouSpanBLength); + if (mHandler == INVALID_HANDLE) + { + return INIT_FAILED; + } + + // + // Set Indicator ShortName ... + SetIndicatorName(); + + // + // Init Succeed ... + return INIT_SUCCEEDED; +} + +// +// DeInitialization ... +void OnDeinit(const int reason) +{ + // + // REASON_PROGRAM 0 The EA has stopped working calling the ExpertRemove() function + // REASON_REMOVE 1 Program removed from a chart + // REASON_RECOMPILE 2 Program recompiled + // REASON_CHARTCHANGE 3 A symbol or a chart period is changed + // REASON_CHARTCLOSE 4 Chart closed + // REASON_PARAMETERS 5 Inputs changed by a user + // REASON_ACCOUNT 6 Another account has been activated or reconnection to the trade server has occurred due to changes in the account settings + // REASON_TEMPLATE 7 Another chart template applied + // REASON_INITFAILED 8 The OnInit() handler returned a non-zero value + // REASON_CLOSE 9 Terminal closed + + // + IndicatorRelease(mHandler); +} + +// +// Calculating what we want ... +int OnCalculate( + // + // total Candles on chart ... + const int rates_total, + // + // total calculated Candles on charts ... + const int prev_calculated, + // + // history of Candles Open Time ... + const datetime &time[], + // + // history of Candles Open Price ... + const double &open[], + // + // history of Candles High Price ... + const double &high[], + // + // history of Candles Low Price ... + const double &low[], + // + // history of Candles Close Price ... + const double &close[], + // + // history of Tick Volumes on Candle ... + const long &tick_volume[], + // + // history of Trade Volumes ... + const long &volume[], + // + // history of Candles Spread Price ... + const int &spread[]) +{ + // + // Prepare Buffers ... + ArraySetAsSeries(time, true); + ArraySetAsSeries(open, true); + ArraySetAsSeries(high, true); + ArraySetAsSeries(low, true); + ArraySetAsSeries(close, true); + ArraySetAsSeries(tick_volume, true); + ArraySetAsSeries(volume, true); + ArraySetAsSeries(spread, true); + + // + // this counts Available Bars ... + int limit; + + // + // Check Calculated Bars ... + int ichCalculatedBars = BarsCalculated(mHandler); + if (ichCalculatedBars < maxLength) + { + return prev_calculated; + } + + // + limit = (prev_calculated > rates_total || prev_calculated <= 0) ? rates_total : (rates_total - prev_calculated) + 1; + + // + // Buffers Copy ... + int copiedTenkans = CopyBuffer(mHandler, TENKANSEN_LINE, 0, limit, dTenkanBuffer); + int copiedKijuns = CopyBuffer(mHandler, KIJUNSEN_LINE, 0, limit, dKijunBuffer); + int copiedChikous = CopyBuffer(mHandler, CHIKOUSPAN_LINE, 0, limit, dChikouBuffer); + int copiedSSAs = CopyBuffer(mHandler, SENKOUSPANA_LINE, 0, limit, dSSABuffer); + int copiedSSBs = CopyBuffer(mHandler, SENKOUSPANB_LINE, 0, limit, dSSBBuffer); + if ( + copiedSSAs < 0 || + copiedSSBs < 0 || + copiedKijuns < 0 || + copiedTenkans < 0 || + copiedChikous < 0) + { + return prev_calculated; + } + + // + // Main Loop ... + for (int i = limit - 1; i >= 0 && !IsStopped(); i--) + { + CalculateBuffers(i); + } + + // + return rates_total; +} + +// +// END Event Handlers ... +// + +// +// START Functions ... +// + +// +// Validate Input Args for Initialization ... +bool ValidateInputs() +{ + // + bool result = + // + (tenkanSenLength > 2 && + kijunSenLength > tenkanSenLength && + senkouSpanBLength > kijunSenLength) + // + ; + + // + return result; +} + +// +// Retrieve all Exists Input Max Length ... +// use for Start Of Drawing ... +int ExtractMaxLengthOfInputs() +{ + // + int result = 0; + + // + // Ichimoku ... + result = MathMax(result, tenkanSenLength); + result = MathMax(result, kijunSenLength); + result = MathMax(result, senkouSpanBLength); + + // + return result; +} + +// +// Define Indexes and Styles ... +void DefineBuffers() +{ + // + // ICHIMOKU ... + + // + // TENKANSEN ... + + // + ENUM_DRAW_TYPE tenkanSenDrawType = showTenkanSen ? DRAW_LINE : DRAW_NONE; + + // + ArraySetAsSeries(tenkanSenBuffer, true); + SetIndexBuffer(tenkanSenBufferIndex, tenkanSenBuffer, INDICATOR_DATA); + PlotIndexSetInteger(tenkanSenBufferIndex, PLOT_DRAW_BEGIN, maxLength); + PlotIndexSetInteger(tenkanSenBufferIndex, PLOT_SHOW_DATA, showTenkanSen); + PlotIndexSetInteger(tenkanSenBufferIndex, PLOT_DRAW_TYPE, tenkanSenDrawType); + + // + // KIJUNSEN ... + + // + ENUM_DRAW_TYPE kijunSenDrawType = showKijunSen ? DRAW_LINE : DRAW_NONE; + + // + ArraySetAsSeries(kijunSenBuffer, true); + SetIndexBuffer(kijunSenBufferIndex, kijunSenBuffer, INDICATOR_DATA); + PlotIndexSetInteger(kijunSenBufferIndex, PLOT_DRAW_BEGIN, maxLength); + PlotIndexSetInteger(kijunSenBufferIndex, PLOT_SHOW_DATA, showKijunSen); + PlotIndexSetInteger(kijunSenBufferIndex, PLOT_DRAW_TYPE, kijunSenDrawType); + + // + // KIJUNSEN Plus ... + + // + ENUM_DRAW_TYPE kijunSenPlusDrawType = showKijunSenPlus ? DRAW_LINE : DRAW_NONE; + + // + ArraySetAsSeries(kijunSenPlusBuffer, true); + SetIndexBuffer(kijunSenPlusBufferIndex, kijunSenPlusBuffer, INDICATOR_DATA); + PlotIndexSetInteger(kijunSenPlusBufferIndex, PLOT_DRAW_BEGIN, maxLength); + PlotIndexSetInteger(kijunSenPlusBufferIndex, PLOT_SHIFT, kijunSenLength); + PlotIndexSetInteger(kijunSenPlusBufferIndex, PLOT_SHOW_DATA, false); + PlotIndexSetInteger(kijunSenPlusBufferIndex, PLOT_DRAW_TYPE, kijunSenPlusDrawType); + + // + // KIJUNSEN Negative ... + + // + ENUM_DRAW_TYPE kijunSenNegativeDrawType = showKijunSenNegative ? DRAW_LINE : DRAW_NONE; + + // + ArraySetAsSeries(kijunSenNegativeBuffer, true); + SetIndexBuffer(kijunSenNegativeBufferIndex, kijunSenNegativeBuffer, INDICATOR_DATA); + PlotIndexSetInteger(kijunSenNegativeBufferIndex, PLOT_DRAW_BEGIN, maxLength); + PlotIndexSetInteger(kijunSenNegativeBufferIndex, PLOT_SHIFT, -kijunSenLength); + PlotIndexSetInteger(kijunSenNegativeBufferIndex, PLOT_SHOW_DATA, false); + PlotIndexSetInteger(kijunSenNegativeBufferIndex, PLOT_DRAW_TYPE, kijunSenNegativeDrawType); + + // + // CHIKOUSPAN ... + + // + ENUM_DRAW_TYPE chikouSpanDrawType = showChikouSpan ? DRAW_LINE : DRAW_NONE; + + // + ArraySetAsSeries(chikouSpanBuffer, true); + SetIndexBuffer(chikouSpanBufferIndex, chikouSpanBuffer, INDICATOR_DATA); + PlotIndexSetInteger(chikouSpanBufferIndex, PLOT_DRAW_BEGIN, maxLength); + PlotIndexSetInteger(chikouSpanBufferIndex, PLOT_SHIFT, -kijunSenLength); + PlotIndexSetInteger(chikouSpanBufferIndex, PLOT_SHOW_DATA, showChikouSpan); + PlotIndexSetInteger(chikouSpanBufferIndex, PLOT_DRAW_TYPE, chikouSpanDrawType); + + // + // SENKOUSPAN A and B ... + int shiftSize = shiftKumo ? kijunSenLength : 0; + + // + // SENKOUSPANA ... + ENUM_DRAW_TYPE senkouSpanADrawType = showSenkouSpanA ? DRAW_LINE : DRAW_NONE; + ArraySetAsSeries(senkouABuffer, true); + SetIndexBuffer(senkouABufferIndex, senkouABuffer, INDICATOR_DATA); + PlotIndexSetInteger(senkouABufferIndex, PLOT_SHIFT, shiftSize); + PlotIndexSetInteger(senkouABufferIndex, PLOT_SHOW_DATA, showSenkouSpanA); + PlotIndexSetInteger(senkouABufferIndex, PLOT_DRAW_TYPE, senkouSpanADrawType); + + // + // SENKOUSPANB ... + ENUM_DRAW_TYPE senkouSpanBDrawType = showSenkouSpanB ? DRAW_LINE : DRAW_NONE; + ArraySetAsSeries(senkouBBuffer, true); + SetIndexBuffer(senkouBBufferIndex, senkouBBuffer, INDICATOR_DATA); + PlotIndexSetInteger(senkouBBufferIndex, PLOT_SHIFT, shiftSize); + PlotIndexSetInteger(senkouBBufferIndex, PLOT_SHOW_DATA, showSenkouSpanB); + PlotIndexSetInteger(senkouBBufferIndex, PLOT_DRAW_TYPE, senkouSpanBDrawType); + + // + // KUMO ... + + // + // SENKOUSPANA ... + ArraySetAsSeries(senkouSpanABuffer, true); + SetIndexBuffer(senkouSpanABufferIndex, senkouSpanABuffer, INDICATOR_DATA); + PlotIndexSetInteger(senkouSpanABufferIndex, PLOT_DRAW_BEGIN, maxLength); + + // + // SENKOUSPANB ... + ArraySetAsSeries(senkouSpanBBuffer, true); + SetIndexBuffer(senkouSpanBBufferIndex, senkouSpanBBuffer, INDICATOR_DATA); + PlotIndexSetInteger(senkouSpanBBufferIndex, PLOT_DRAW_BEGIN, maxLength); + + // + // KUMO ... + + // + ENUM_DRAW_TYPE kumoDrawType = showKumo ? DRAW_FILLING : DRAW_NONE; + + // + PlotIndexSetInteger(kumoBufferIndex, PLOT_SHIFT, shiftSize); + PlotIndexSetInteger(kumoBufferIndex, PLOT_SHOW_DATA, false); + PlotIndexSetInteger(kumoBufferIndex, PLOT_DRAW_TYPE, kumoDrawType); + + // + // DATA Buffers ... + + // + // D Tenkan ... + ArraySetAsSeries(dTenkanBuffer, true); + SetIndexBuffer(dTenkanBufferIndex, dTenkanBuffer, INDICATOR_CALCULATIONS); + + // + // D Kijun ... + ArraySetAsSeries(dKijunBuffer, true); + SetIndexBuffer(dKijunBufferIndex, dKijunBuffer, INDICATOR_CALCULATIONS); + + // + // D Chikou ... + ArraySetAsSeries(dChikouBuffer, true); + SetIndexBuffer(dChikouBufferIndex, dChikouBuffer, INDICATOR_CALCULATIONS); + + // + // D SSA ... + ArraySetAsSeries(dSSABuffer, true); + SetIndexBuffer(dSSABufferIndex, dSSABuffer, INDICATOR_CALCULATIONS); + + // + // D SSB ... + ArraySetAsSeries(dSSBBuffer, true); + SetIndexBuffer(dSSBBufferIndex, dSSBBuffer, INDICATOR_CALCULATIONS); +} + +// +// Set Indicator Short Name and also we can define Buffers Labels ... +void SetIndicatorName() +{ + IndicatorSetString(INDICATOR_SHORTNAME, ShortName); +} + +// +// Calculate Buffers ... +void CalculateBuffers( + int bar_index // Selected Bar Index +) +{ + // + // ICHIMOKU ... + + // + double topValue; + double bottomValue; + + // + // TENKANSEN ... + + // + // Extract Tenkan Sen Top/Bottom Calculation Mode based on User Input ... + if (mTenkanSenTopMode == NULL || mTenkanSenBottomMode == NULL) + { + // + switch (tenkanSenMode) + { + // + case X_XICH_HH_LL_MODE: + // + mTenkanSenTopMode = MODE_HIGH; + mTenkanSenBottomMode = MODE_LOW; + break; + + // + case X_XICH_HO_LC_MODE: + // + mTenkanSenTopMode = MODE_OPEN; + mTenkanSenBottomMode = MODE_CLOSE; + break; + } + } + + // + XOHCL bar; + bar.Init( + _Symbol, + _Period, + bar_index + // + ); + + // + // Calculate Top ... + topValue = bar + .FindHighest( + tenkanSenLength, + mTenkanSenTopMode + // + ); + + // + // Calculate Bottom ... + bottomValue = bar + .FindLowest( + tenkanSenLength, + mTenkanSenBottomMode + // + ); + + // + double tenkanSenValue = (topValue + bottomValue) / 2; + tenkanSenBuffer[bar_index] = tenkanSenValue; + + // + // KIJUNSEN ... + + // + // Extract Kijun Sen Top/Bottom Calculation Mode based on User Input ... + if (mKijunSenTopMode == NULL || mKijunSenBottomMode == NULL) + { + // + switch (kijunSenMode) + { + // + case X_XICH_HH_LL_MODE: + // + mKijunSenTopMode = MODE_HIGH; + mKijunSenBottomMode = MODE_LOW; + break; + + // + case X_XICH_HO_LC_MODE: + // + mKijunSenTopMode = MODE_OPEN; + mKijunSenBottomMode = MODE_CLOSE; + break; + } + } + + // + // Calculate Top ... + topValue = bar + .FindHighest( + kijunSenLength, + mKijunSenTopMode + // + ); + + // + // Calculate Bottom ... + bottomValue = bar + .FindLowest( + kijunSenLength, + mKijunSenBottomMode + // + ); + + // + double kijunSenValue = (topValue + bottomValue) / 2; + kijunSenBuffer[bar_index] = kijunSenValue; + + // + kijunSenPlusBuffer[bar_index] = kijunSenValue; + kijunSenNegativeBuffer[bar_index] = kijunSenValue; + + // + // CHIKOUSPAN ... + double chikouSpanValue = bar + .GetPrice(chikuoSpanAppliedTo); + + // + chikouSpanBuffer[bar_index] = chikouSpanValue; + + // + // KUMO ... + + // + // SENKOUSPANA ... + double senkouSpanAValue = (tenkanSenValue + kijunSenValue) / 2; + senkouABuffer[bar_index] = senkouSpanAValue; + senkouSpanABuffer[bar_index] = senkouSpanAValue; + + // + // SENKOUSPANB ... + + // + // Extract Senkou Span B Top/Bottom Calculation Mode based on User Input ... + if (mSenkouSpanBTopMode == NULL || mSenkouSpanBBottomMode == NULL) + { + // + switch (senkouSpanBMode) + { + // + case X_XICH_HH_LL_MODE: + // + mSenkouSpanBTopMode = MODE_HIGH; + mSenkouSpanBBottomMode = MODE_LOW; + break; + + // + case X_XICH_HO_LC_MODE: + // + mSenkouSpanBTopMode = MODE_OPEN; + mSenkouSpanBBottomMode = MODE_CLOSE; + break; + } + } + + // + // Calculate Top ... + topValue = bar + .FindHighest( + senkouSpanBLength, + mSenkouSpanBTopMode + // + ); + + // + // Calculate Bottom ... + bottomValue = bar + .FindLowest( + senkouSpanBLength, + mSenkouSpanBBottomMode + // + ); + + // + double senkouSpanBValue = (topValue + bottomValue) / 2; + senkouBBuffer[bar_index] = senkouSpanBValue; + senkouSpanBBuffer[bar_index] = senkouSpanBValue; +} + +// +// END Functions ... +// diff --git a/BKPS/14040203/Documents/BKP/x121.helper.bkp.mq5 b/BKPS/14040203/Documents/BKP/x121.helper.bkp.mq5 new file mode 100644 index 0000000..1487eca --- /dev/null +++ b/BKPS/14040203/Documents/BKP/x121.helper.bkp.mq5 @@ -0,0 +1,393 @@ + + // // + // // XICH ... + // X121XICHConditions xichConditions; + // result = GetICHConditions( + // xichConditions, + // barIndex, + // loopback // + // ); + // if (!result) + // { + // // + // xpvConditions.Clean(); + // xhkConditions.Clean(); + // xichConditions.Clean(); + + // // + // return result; + // } + + // // + // // XDON ... + // X121XDONConditions xdonConditions; + // result = GetDONConditions( + // xdonConditions, + // barIndex, + // loopback // + // ); + // if (!result) + // { + // // + // xpvConditions.Clean(); + // xhkConditions.Clean(); + // xichConditions.Clean(); + // xmasConditions.Clean(); + // xatrConditions.Clean(); + // xstrConditions.Clean(); + // xcheConditions.Clean(); + // xdonConditions.Clean(); + + // // + // return result; + // } + + // // + // // XDELTA ... + // X121XDELTAConditions xdeltaConditions; + // result = GetDELTAConditions( + // xdeltaConditions, + // barIndex, + // loopback // + // ); + // if (!result) + // { + // // + // xpvConditions.Clean(); + // xhkConditions.Clean(); + // xichConditions.Clean(); + // xmasConditions.Clean(); + // xatrConditions.Clean(); + // xstrConditions.Clean(); + // xcheConditions.Clean(); + // xdonConditions.Clean(); + // x3maConditions.Clean(); + // xvwapConditions.Clean(); + // xdeltaConditions.Clean(); + + // // + // return result; + // } + + // // + // // XVOLUME ... + // X121XVOLUMEConditions xvolumeConditions; + // result = GetVOLUMEConditions( + // xvolumeConditions, + // barIndex, + // loopback // + // ); + // if (!result) + // { + // // + // xpvConditions.Clean(); + // xhkConditions.Clean(); + // xichConditions.Clean(); + // xmasConditions.Clean(); + // xatrConditions.Clean(); + // xstrConditions.Clean(); + // xcheConditions.Clean(); + // xdonConditions.Clean(); + // x3maConditions.Clean(); + // xvwapConditions.Clean(); + // xdeltaConditions.Clean(); + // xvolumeConditions.Clean(); + + // // + // return result; + // } + + // + // xichConditions.Clean(); + // xdonConditions.Clean(); + // xdeltaConditions.Clean(); + // xvolumeConditions.Clean(); + + + // // + // // XICH ... + // bool GetICHConditions( + // X121XICHConditions &conditions, // + // int barIndex = 0, // + // int loopback = 5 // + // ) + // { + // // + // bool result = false; + + // // + // result = xichHelper.GetConditions( + // conditions, + // barIndex, + // loopback // + // ); + + // // + // return result; + // } + + // // + // // XDON ... + // bool GetDONConditions( + // X121XDONConditions &conditions, // + // int barIndex = 0, // + // int loopback = 5 // + // ) + // { + // // + // bool result = false; + + // // + // result = xdonHelper.GetConditions( + // conditions, + // barIndex, + // loopback // + // ); + + // // + // return result; + // } + + // // + // // XDELTA ... + // bool GetDELTAConditions( + // X121XDELTAConditions &conditions, // + // int barIndex = 0, // + // int loopback = 5 // + // ) + // { + // // + // bool result = false; + + // // + // result = xdeltaHelper.GetConditions( + // conditions, + // barIndex, + // loopback // + // ); + + // // + // return result; + // } + + // // + // // XVOLUME ... + // bool GetVOLUMEConditions( + // X121XVOLUMEConditions &conditions, // + // int barIndex = 0, // + // int loopback = 5 // + // ) + // { + // // + // bool result = false; + + // // + // result = xvolumeHelper.GetConditions( + // conditions, + // barIndex, + // loopback // + // ); + + // // + // return result; + // } + + + // + // xichInputs = inputs.xichInputs; + // xdonInputs = inputs.xdonInputs; + // xdeltaInputs = inputs.xdeltaInputs; + // xvolumeInputs = inputs.xvolumeInputs; + + + + // // + // // XICH ... + // xichHelper = new XCX121XICHHelper(); + // result = xichHelper.Init( + // symbol, + // period, + // xichInputs // + // ); + // if (!result) + // { + // // + // ZeroMemory(xccHelper); + // ZeroMemory(xpvHelper); + // ZeroMemory(xhkHelper); + // ZeroMemory(xmasHelper); + // ZeroMemory(xatrHelper); + // ZeroMemory(xstrHelper); + // ZeroMemory(xcheHelper); + // ZeroMemory(x3maHelper); + // ZeroMemory(xvwapHelper); + + // // + // // ZeroMemory(xichHelper); + // // ZeroMemory(xdonHelper); + // // ZeroMemory(xdeltaHelper); + // // ZeroMemory(xvolumeHelper); + + // // + // return result; + // } + + // // + // // XDON ... + // xdonHelper = new XCX121XDONHelper(); + // result = xdonHelper.Init( + // symbol, + // period, + // xdonInputs // + // ); + // if (!result) + // { + // // + // ZeroMemory(xccHelper); + // ZeroMemory(xpvHelper); + // ZeroMemory(xhkHelper); + // ZeroMemory(xmasHelper); + // ZeroMemory(xatrHelper); + // ZeroMemory(xstrHelper); + // ZeroMemory(xcheHelper); + // ZeroMemory(x3maHelper); + // ZeroMemory(xvwapHelper); + + // // + // // ZeroMemory(xichHelper); + // // ZeroMemory(xdonHelper); + // // ZeroMemory(xdeltaHelper); + // // ZeroMemory(xvolumeHelper); + + // // + // return result; + // } + + // // + // // XDELTA ... + // xdeltaHelper = new XCX121XDELTAHelper(); + // result = xdeltaHelper.Init( + // symbol, + // period, + // xdeltaInputs // + // ); + // if (!result) + // { + // // + // ZeroMemory(xccHelper); + // ZeroMemory(xpvHelper); + // ZeroMemory(xhkHelper); + // ZeroMemory(xmasHelper); + // ZeroMemory(xatrHelper); + // ZeroMemory(xstrHelper); + // ZeroMemory(xcheHelper); + // ZeroMemory(x3maHelper); + // ZeroMemory(xvwapHelper); + + // // + // // ZeroMemory(xichHelper); + // // ZeroMemory(xdonHelper); + // // ZeroMemory(xdeltaHelper); + // // ZeroMemory(xvolumeHelper); + + // // + // return result; + // } + + // // + // // XVOLUME ... + // xvolumeHelper = new XCX121XVOLUMEHelper(); + // result = xvolumeHelper.Init( + // symbol, + // period, + // xvolumeInputs // + // ); + // if (!result) + // { + // // + // ZeroMemory(xccHelper); + // ZeroMemory(xpvHelper); + // ZeroMemory(xhkHelper); + // ZeroMemory(xmasHelper); + // ZeroMemory(xatrHelper); + // ZeroMemory(xstrHelper); + // ZeroMemory(xcheHelper); + // ZeroMemory(x3maHelper); + // ZeroMemory(xvwapHelper); + + // // + // // ZeroMemory(xichHelper); + // // ZeroMemory(xdonHelper); + // // ZeroMemory(xdeltaHelper); + // // ZeroMemory(xvolumeHelper); + + // // + // return result; + // } + + + // + // ZeroMemory(xichHelper); + // ZeroMemory(xdonHelper); + // ZeroMemory(xdeltaHelper); + // ZeroMemory(xvolumeHelper); + + + // + // XCX121XICHHelper *xichHelper; + // XCX121XDONHelper *xdonHelper; + // XCX121XDELTAHelper *xdeltaHelper; + // XCX121XVOLUMEHelper *xvolumeHelper; + + + // + // int xdonMax = xdonInputs.Max(); + // int xichMax = xichInputs.Max(); + // int xdeltaMax = xdeltaInputs.Max(); + // int xvolumeMax = xvolumeInputs.Max(); + + + // + // result = MathMax(result, xdonMax); + // result = MathMax(result, xichMax); + // result = MathMax(result, xdeltaMax); + // result = MathMax(result, xvolumeMax); + + // && + // xichInputs.IsValid() && + // xdonInputs.IsValid() && + // xdeltaInputs.IsValid() && + // xvolumeInputs.IsValid() + // + + + // + // xichInputs.Default(); + // xdonInputs.Default(); + // xdeltaInputs.Default(); + // xvolumeInputs.Default(); + + + // + // xichInputs.Clean(); + // xdonInputs.Clean(); + // xdeltaInputs.Clean(); + // xvolumeInputs.Clean(); + + // + // xichInputs.Clean(); + // xdonInputs.Clean(); + // xdeltaInputs.Clean(); + // xvolumeInputs.Clean(); + + // + // delete xichHelper; + // delete xdonHelper; + // delete xdeltaHelper; + // delete xvolumeHelper; + + // + // ZeroMemory(xichHelper); + // ZeroMemory(xdonHelper); + // ZeroMemory(xdeltaHelper); + // ZeroMemory(xvolumeHelper); diff --git a/BKPS/14040203/Documents/BKP/xaea.tmp.signaller.bkp.mq5 b/BKPS/14040203/Documents/BKP/xaea.tmp.signaller.bkp.mq5 new file mode 100644 index 0000000..daf60bf --- /dev/null +++ b/BKPS/14040203/Documents/BKP/xaea.tmp.signaller.bkp.mq5 @@ -0,0 +1,431 @@ + // + bool isPeakPivot = conditions.isPeakIsPivot; + bool isValePivot = conditions.isValeIsPivot; + + // + bool isPivotBullish = isValePivot && + isCBarValidForBullish; + + // + bool isPivotBearish = isPeakPivot && + isCBarValidForBearish; + + // + bool isPivotBullishReversal = + // + isPivotBullish && + conditions.isKIBearish && + conditions.isSarBearish && + conditions.isTrendBearish && + conditions.isLastSupportRejected + // + ; + + // + bool isPivotBearishReversal = + // + isPivotBearish && + conditions.isKIBullish && + conditions.isSarBullish && + conditions.isTrendBullish && + conditions.isLastResistanceRejected + // + ; + + // + bool isPivot = isPivotBullishReversal || + isPivotBearishReversal; + + if (isPivot) + { + Print("Pivot: "); + + // + if (isPivotBullish) + { + Print("Bullish: ", isPivotBullish); + } + + // + if (isPivotBearish) + { + Print("Bearish: ", isPivotBearish); + } + + // + Print("Bullish Score: ", bullishScore); + Print("Bearish Score: ", bearishScore); + } + + // + bool isOverFib2 = pBar.low > conditions.fiboLevel2Buffer[cIDX]; + bool isUnderFib2 = pBar.high < conditions.fiboLevel2Buffer[cIDX]; + + // + bool isTrendBasedBullish = + isUnderFib2 && + isCBarValidForBullish && + conditions.isTrendRejectUp; + + // + bool isTrendBasedBearish = + isOverFib2 && + isCBarValidForBearish && + conditions.isTrendRejectDown; + + // + bool isTrend = + isTrendBasedBullish || + isTrendBasedBearish; + + // + if (isTrend) + { + Print("Trend Based ..."); + } + + // + bool isBarBreakedKITrendBullish = + cBar.IsBullish() && + isCBarBullishMomentum && + cBar.open < conditions.kiBuffer[cIDX] && + cBar.close > conditions.kiBuffer[cIDX] && + cBar.open < conditions.trendBuffer[cIDX] && + cBar.close > conditions.trendBuffer[cIDX]; + + // + bool isBarBreakedKITrendBearish = + cBar.IsBearish() && + isCBarBearishMomentum && + cBar.open > conditions.kiBuffer[cIDX] && + cBar.close < conditions.kiBuffer[cIDX] && + cBar.open > conditions.trendBuffer[cIDX] && + cBar.close > conditions.trendBuffer[cIDX]; + + // + bool isKITrendBreaked = + isBarBreakedKITrendBullish || + isBarBreakedKITrendBearish; + + // + if (isKITrendBreaked) + { + Print("KI Trend Breaked ..."); + } + + + ///////////////////////////////////////////////////////////// + + + // while (index <= end) + // { + // // + // XCAEAConditions iConditions; + // bool has = helper.GetConditions( + // iConditions, + // index, + // 5 // + // ); + // if (!has) + // { + // // + // iConditions.Clean(); + // continue; + // } + + // // + // zIDX = 0; + // cIDX = zIDX + 1; + // pIDX = cIDX + 1; + // p2IDX = pIDX + 1; + + // // + // XOHCL cBar; + // has = cBar.Init( + // iConditions.symbol, + // iConditions.period, + // index + 1 // + // ); + // if (!has) + // { + // // + // cBar.Clean(); + // iConditions.Clean(); + // continue; + // } + + // // + // // Read Reuired Data ... + + // // + // // KI ... + + // // + // double cKI = iConditions.kiBuffer[cIDX]; + // double pKI = iConditions.kiBuffer[pIDX]; + // double p2KI = iConditions.kiBuffer[p2IDX]; + + // // + // double cKIState = iConditions.kiStateBuffer[cIDX]; + // double pKIState = iConditions.kiStateBuffer[pIDX]; + // double p2KIState = iConditions.kiStateBuffer[p2IDX]; + + // // + // // TKI ... + + // // + // double cTKI = iConditions.tkiBuffer[cIDX]; + // double pTKI = iConditions.tkiBuffer[pIDX]; + // double p2TKI = iConditions.tkiBuffer[p2IDX]; + + // // + // double cTKIState = iConditions.tkiStateBuffer[cIDX]; + // double pTKIState = iConditions.tkiStateBuffer[pIDX]; + // double p2TKIState = iConditions.tkiStateBuffer[p2IDX]; + + // // + // // TREND ... + + // // + // double cTrend = iConditions.trendBuffer[cIDX]; + // double pTrend = iConditions.trendBuffer[pIDX]; + // double p2Trend = iConditions.trendBuffer[p2IDX]; + + // // + // double ctrendState = iConditions.trendStateBuffer[cIDX]; + // double ptrendState = iConditions.trendStateBuffer[pIDX]; + // double p2trendState = iConditions.trendStateBuffer[p2IDX]; + + // // + // // SWING Low ... + + // // + // double cSWL = iConditions.swingLowBuffer[cIDX]; + // double pSWL = iConditions.swingLowBuffer[pIDX]; + // double p2SWL = iConditions.swingLowBuffer[p2IDX]; + + // // + // // SWING High ... + + // // + // double cSWH = iConditions.swingHighBuffer[cIDX]; + // double pSWH = iConditions.swingHighBuffer[pIDX]; + // double p2SWH = iConditions.swingHighBuffer[p2IDX]; + + // // + // // PEAK ... + + // // + // double cPeak = iConditions.peakBuffer[cIDX]; + // double pPeak = iConditions.peakBuffer[pIDX]; + // double p2Peak = iConditions.peakBuffer[p2IDX]; + + // // + // // VALE ... + + // // + // double cVale = iConditions.valeBuffer[cIDX]; + // double pVale = iConditions.valeBuffer[pIDX]; + // double p2Vale = iConditions.valeBuffer[p2IDX]; + + // // + // // Required Condirions ... + + // // + // bool isTKITRNDBullish = + // iConditions.isKIBullish && + // iConditions.isTKIBullish && + // iConditions.isTrendBullish; + + // // + // bool isTKITRNDBearish = + // iConditions.isKIBearish && + // iConditions.isTKIBearish && + // iConditions.isTrendBearish; + + // // + // XBoxZone iBox; + + // // + // // Check FVG ... + // bool isFVG = barAnalyser.IsFVG( + // cBar, + // iBox, + // false // Force Same Bars ... + // ); + // if (isFVG) + // { + // // + // // Validate FVG ... + // bool isFVGBullish = iBox.IsBullish(); + + // // // + // // isFVG = + // // isFVGBullish + // // ? isTKITRNDBullish + // // : isTKITRNDBearish; + + // // + // if (isFVG) + // { + // // + // XCBoxObject *iObj; + // has = drawer.DrawBox( + // iBox, + // iObj // + // ); + // if (has) + // { + // iObj.BoxWidth(2); + // } + // } + // } + + // // + // index++; + // cBar.Clean(); + // iConditions.Clean(); + // } + + //////////////////////////////////////////////////////////////////// + + // + XBoxZone tmpFVGBoxes[]; + + // + int index = barIndex; + int end = index + loopback; + while (index <= end) + { + // + XOHCL cBar; + bool has = cBar.Init( + helper.GetSymbol(), + helper.GetPeriod(), + index + 1 // + ); + if (!has) + { + // + cBar.Clean(); + continue; + } + + // + // Check FVG ... + XBoxZone iBox; + bool isFVG = barAnalyser.IsFVG( + cBar, + iBox, + false // Force Same Bars ... + ); + if (isFVG) + { + // + AddBox( + iBox, + tmpFVGBoxes // + ); + } + + // + index++; + cBar.Clean(); + } + + // + int idx = -1; + bool has = false; + if (HasChild(tmpFVGBoxes)) + { + // + while (HasChild(tmpFVGBoxes)) + { + // + idx = GetYoungest(tmpFVGBoxes); + has = IsValidIndex(idx); + if (!has) + { + break; + } + + // + XBoxZone iBox = tmpFVGBoxes[idx]; + ArrayRemove( + tmpFVGBoxes, + idx, + 1 // + ); + + // + // Here We Have to Validate FVG ... + + // + XCBoxObject *iObj; + has = drawer.DrawBox( + iBox, + iObj // + ); + + // + } + } + + +////////////////////////////////////////////////////////////////////////////////// + +has = HasPeakPivots(); +if (has) +{ + // + count = CountPeakPivots(); + for (int i = 0; i < count; i++) + { + // + XCAPivot iPivot = peakPivots[i]; + + // + int toIDX = iPivot.ToIndex(); + int fromIDX = iPivot.FromIndex(); + has = IsValidIndex(toIDX) && + IsValidIndex(fromIDX); + if (!has) + { + // + iPivot.Clean(); + continue; + } + + // + for (int j = toIDX; j <= fromIDX; j++) { + // + XCAEAConditions jConditions; + has = helper.GetConditions( + jConditions, + j, + 5 // + ); + if (!has) { + // + jConditions.Clean(); + continue; + } + + // + datetime jTime = GetBarTime( + jConditions.symbol, + jConditions.period, + j // + ); + + // + + } + + // + iPivot.Clean(); + } +} + +////////////////////////////////////////////////////////////////////////////////////////// + diff --git a/BKPS/14040203/Documents/BKP/xcaea.pivots.tmp.mq5 b/BKPS/14040203/Documents/BKP/xcaea.pivots.tmp.mq5 new file mode 100644 index 0000000..15e291f --- /dev/null +++ b/BKPS/14040203/Documents/BKP/xcaea.pivots.tmp.mq5 @@ -0,0 +1,45 @@ + + // + // PEAKS ... + + // + // VALES ... + + // + // PEAK SWH RES ... + + // + // VALE SWL SUP ... + + // + // SWING HIGH ... + + // + // SWING LOW ... + + // + // KI ... + + // + // TKI ... + + // + // FVG ... + + // + // TREND ... + + // + // TKITRND ... + + // + // SAME CYCLES HH / LL ... + + // + // OSCS ... + + // + // RSI ... + + // + // CCI ... diff --git a/BKPS/14040203/Documents/BKP/xcaea.tmp.signal.lib.mq5 b/BKPS/14040203/Documents/BKP/xcaea.tmp.signal.lib.mq5 new file mode 100644 index 0000000..c48ebf9 --- /dev/null +++ b/BKPS/14040203/Documents/BKP/xcaea.tmp.signal.lib.mq5 @@ -0,0 +1,816 @@ +///////////////////////////////////////////////////////////////////////////////// + +// +bool DetectXCAEAConditions( + XBoxZone &boxes[], + XCAEAConditions &conditions, + XBoxZone &pivotBox, + XBoxZone &box, + ENUM_X_DIRECTION &dir, + XCXCAEAHelper *helper, + int barIndex = 0, + int loopback = 10 // +) +{ + // + bool result = false; + + // + int idx = -1; + int count = 0; + bool has = false; + + // + box.Clean(); + conditions.Clean(); + dir = X_DIRECTION_NONE; + + // + if (barIndex < 0) + { + barIndex = 0; + } + loopback = NormalizeInt(loopback, 5); + + // + string symbol = helper.GetSymbol(); + ENUM_TIMEFRAMES period = helper.GetPeriod(); + + // + result = helper.GetConditions( + conditions, + barIndex, + loopback // + ); + if (!result) + { + // + conditions.Clean(); + return result; + } + + // + int zIDX = barIndex; + int cIDX = zIDX + 1; + int pIDX = cIDX + 1; + int p2IDX = pIDX + 1; + int p3IDX = p2IDX + 1; + int p4IDX = p3IDX + 1; + + // + // Reading Parameters ... + + // + // KI ... + + // + double cKI = conditions.kiBuffer[cIDX]; + double pKI = conditions.kiBuffer[pIDX]; + double p2KI = conditions.kiBuffer[p2IDX]; + + // + double cKIState = conditions.kiStateBuffer[cIDX]; + double pKIState = conditions.kiStateBuffer[pIDX]; + double p2KIState = conditions.kiStateBuffer[p2IDX]; + + // + // TKI ... + + // + double cTKI = conditions.tkiBuffer[cIDX]; + double pTKI = conditions.tkiBuffer[pIDX]; + double p2TKI = conditions.tkiBuffer[p2IDX]; + + // + double cTKIState = conditions.tkiStateBuffer[cIDX]; + double pTKIState = conditions.tkiStateBuffer[pIDX]; + double p2TKIState = conditions.tkiStateBuffer[p2IDX]; + + // + // TREND ... + + // + double cTrend = conditions.trendBuffer[cIDX]; + double pTrend = conditions.trendBuffer[pIDX]; + double p2Trend = conditions.trendBuffer[p2IDX]; + + // + double ctrendState = conditions.trendStateBuffer[cIDX]; + double ptrendState = conditions.trendStateBuffer[pIDX]; + double p2trendState = conditions.trendStateBuffer[p2IDX]; + + // + // SWING Low ... + double cSWL = conditions.swingLowBuffer[cIDX]; + double pSWL = conditions.swingLowBuffer[pIDX]; + double p2SWL = conditions.swingLowBuffer[p2IDX]; + + // + // SWING High ... + double cSWH = conditions.swingHighBuffer[cIDX]; + double pSWH = conditions.swingHighBuffer[pIDX]; + double p2SWH = conditions.swingHighBuffer[p2IDX]; + + // + // PEAK ... + double zPeak = conditions.peakBuffer[zIDX]; + double cPeak = conditions.peakBuffer[cIDX]; + double pPeak = conditions.peakBuffer[pIDX]; + double p2Peak = conditions.peakBuffer[p2IDX]; + double p3Peak = conditions.peakBuffer[p3IDX]; + + // + // VALE ... + double zVale = conditions.valeBuffer[zIDX]; + double cVale = conditions.valeBuffer[cIDX]; + double pVale = conditions.valeBuffer[pIDX]; + double p2Vale = conditions.valeBuffer[p2IDX]; + double p3Vale = conditions.valeBuffer[p3IDX]; + + // + // RSI ... + double zRSI = conditions.rsiBuffer[zIDX]; + double cRSI = conditions.rsiBuffer[cIDX]; + double pRSI = conditions.rsiBuffer[pIDX]; + double p2RSI = conditions.rsiBuffer[p2IDX]; + double p3RSI = conditions.rsiBuffer[p3IDX]; + + // + // CCI ... + double zCCI = conditions.cciBuffer[zIDX]; + double cCCI = conditions.cciBuffer[cIDX]; + double pCCI = conditions.cciBuffer[pIDX]; + double p2CCI = conditions.cciBuffer[p2IDX]; + double p3CCI = conditions.cciBuffer[p3IDX]; + + // + // RVI ... + + // + double zRVI = conditions.rviBuffer[zIDX]; + double cRVI = conditions.rviBuffer[cIDX]; + double pRVI = conditions.rviBuffer[pIDX]; + double p2RVI = conditions.rviBuffer[p2IDX]; + double p3RVI = conditions.rviBuffer[p3IDX]; + + // + double zRVISignal = conditions.rviSignalBuffer[zIDX]; + double cRVISignal = conditions.rviSignalBuffer[cIDX]; + double pRVISignal = conditions.rviSignalBuffer[pIDX]; + double p2RVISignal = conditions.rviSignalBuffer[p2IDX]; + double p3RVISignal = conditions.rviSignalBuffer[p3IDX]; + + // + // Reading Bars ... + + // + XOHCL zBar; + XOHCL cBar; + XOHCL pBar; + XOHCL p2Bar; + XOHCL p3Bar; + XOHCL p4Bar; + result = zBar.Init( + symbol, + period, + zIDX // + ); + result = + result && + zBar.GetPreviousBar(cBar); + result = + result && + cBar.GetPreviousBar(pBar); + result = + result && + pBar.GetPreviousBar(p2Bar); + result = + result && + p2Bar.GetPreviousBar(p3Bar); + result = + result && + p3Bar.GetPreviousBar(p4Bar); + if (!result) + { + // + zBar.Clean(); + cBar.Clean(); + pBar.Clean(); + p2Bar.Clean(); + p3Bar.Clean(); + p4Bar.Clean(); + + // + box.Clean(); + conditions.Clean(); + + // + return result; + } + + // + // Bars Conditions ... + + // + ENUM_X_DIRECTION cBarDir; + + // + // Hammer ... + bool isCBarHammer = helper + .barAnalyser + .IsHammer( + cBar, + cBarDir // + ); + bool isCBarBullishHammer = + isCBarHammer && + IsBullish(cBarDir); + bool isCBarBearishHammer = + isCBarHammer && + IsBearish(cBarDir); + + // + // Rejected ... + bool isCBarRejected = helper + .barAnalyser + .IsRejected( + cBar, + cBarDir, + false, // Force Type ... + true // Force Fibo Pressure ... + ); + bool isCBarBullishRejected = + isCBarRejected && + IsBullish(cBarDir); + bool isCBarBearishRejected = + isCBarRejected && + IsBearish(cBarDir); + + // + // Engulfed ... + bool isCBarEngulfed = helper + .barAnalyser + .IsEngulfed( + cBar, + cBarDir // + ); + bool isCBarBullishEngulfed = + isCBarEngulfed && + IsBullish(cBarDir); + bool isCBarBearishEngulfed = + isCBarEngulfed && + IsBearish(cBarDir); + + // + // Momentum ... + bool isCBarMomentum = helper + .barAnalyser + .IsMomentum( + cBar, + cBarDir, + 1 // + ); + bool isCBarBullishMomentum = + isCBarMomentum && + IsBullish(cBarDir); + bool isCBarBearishMomentum = + isCBarMomentum && + IsBearish(cBarDir); + + // + // Bar Sumarise ... + + // + bool isCBarValidForBullish = + (isCBarBullishHammer || + isCBarBullishRejected || + isCBarBullishMomentum || + isCBarBullishEngulfed); + + // + bool isCBarValidForBearish = + (isCBarBearishHammer || + isCBarBearishRejected || + isCBarBearishMomentum || + isCBarBearishEngulfed); + + // + double pBarLowShadow = pBar.GetLowShadow(); + double pBarHighShadow = pBar.GetHighShadow(); + + // + bool isPBarSwingLow = + pBarLowShadow > 0 && + pBar.low < p2Bar.low && + pBar.low < cBar.low && + p2Bar.GetUp() >= pBar.low && + p2Bar.GetDown() <= pBar.high && + cBar.GetUp() >= pBar.low && + cBar.GetDown() <= pBar.high; + + // + bool isPBarSwingHigh = + pBarHighShadow > 0 && + pBar.high > p2Bar.high && + pBar.high > cBar.high && + p2Bar.GetUp() >= pBar.low && + p2Bar.GetDown() <= pBar.high && + cBar.GetUp() >= pBar.low && + cBar.GetDown() <= pBar.high; + + // + // Score ... + + // + double bullishScore = 0; + double bearishScore = 0; + conditions.GenerateScore( + bullishScore, + bearishScore // + ); + + // + bool isScoreBullish = + bullishScore > bearishScore; + + // + bool isScoreBearish = + bearishScore > bullishScore; + + // + string summary = + conditions + .GenerateSummary(); + + // + // Detect Selected Box ... + double providedSL = 0; + bool isBoxRejected = false; + bool isBoxActivated = false; + bool hasBoxes = HasChild(boxes); + if (hasBoxes) + { + // + // Detect Selected Boxes ... + XBoxZone tmp[]; + Copy( + boxes, + tmp // + ); + while (HasChild(tmp)) + { + // + idx = GetYoungest(tmp); + has = IsValidIndex(idx); + if (!has) + { + break; + } + + // + XBoxZone iBox; + iBox = tmp[idx]; + ArrayRemove( + tmp, + idx, + 1 // + ); + + // + // Check Selected Box not RSI or CCI ... + has = iBox.type == ToString(XCA_PEAKSWHRES) || + iBox.type == ToString(XCA_VALESWLSUP); + if (!has) + { + continue; + } + + // + bool isBullish = iBox.IsBullish(); + bool isBearish = iBox.IsBearish(); + + // + double rejectedCheckPrice = + isBullish + ? iBox.upper + : iBox.lower; + + // + // Check Box Selecting Senarios ... + + // + // Selecting Rejected Boxes ... + isBoxRejected = cBar.IsRejected( + rejectedCheckPrice, + iBox.dir, + false, + false // + ); + + // + // Selecting Activation Boxes ... + + // + bool isBullishActivated = + isBullish && + isPBarSwingLow && + cBar.IsBullish() && + cBar.GetUp() > rejectedCheckPrice && + cBar.GetDown() < rejectedCheckPrice; + + // + bool isBearishActivated = + isBearish && + isPBarSwingHigh && + cBar.IsBearish() && + cBar.GetUp() > rejectedCheckPrice && + cBar.GetDown() < rejectedCheckPrice; + + // + isBoxActivated = isBullishActivated || + isBearishActivated; + + // + // Detect Box is Selected or not ... + has = + isBoxRejected || + isBoxActivated; + if (has) + { + // + pivotBox = iBox; + + // + iBox.Clean(); + break; + } + + // + iBox.Clean(); + } + + // + Clean(tmp); + } + + // + // Force Conditions to Have Selected Box ... + result = hasBoxes && + pivotBox.IsValid(); + if (!result) + { + // + zBar.Clean(); + cBar.Clean(); + pBar.Clean(); + p2Bar.Clean(); + p3Bar.Clean(); + p4Bar.Clean(); + + // + box.Clean(); + pivotBox.Clean(); + conditions.Clean(); + + // + return result; + } + + // + // Conditions ... + + // + bool isRSIBullish = + zRSI >= cRSI && + cRSI > pRSI; + bool isRSIBearish = + zRSI <= cRSI && + cRSI < pRSI; + + // + bool isCCIBullish = + zCCI >= cCCI && + cCCI > pCCI && + (zCCI > conditions.cciOSLevel || + cCCI > conditions.cciOSLevel); + bool isCCIBearish = + zCCI >= cCCI && + cCCI > pCCI && + (zCCI < conditions.cciOBLevel || + cCCI < conditions.cciOBLevel); + + // + // Signaller Summarization ... + + // + // Cond1 Act Using Box Activation ... + + // + bool isCond1Bullish = + // + false && + isCCIBullish && + isBoxActivated && + pivotBox.IsValid() && + pivotBox.IsBullish() + // + ; + + // + bool isCond1Bearish = + // + false && + isCCIBearish && + isBoxActivated && + pivotBox.IsValid() && + pivotBox.IsBearish() + // + ; + + // + bool isCond1 = isCond1Bullish || + isCond1Bearish; + if (isCond1) + { + // + providedSL = + isCond1Bullish + ? MathMin(pBar.low, pivotBox.lower) + : MathMax(pBar.high, pivotBox.upper); + + // + Print("Cond1"); + } + + // + // Cond2 Act Using Box Rejection ... + + // + bool isCond2Bullish = + // + false && + isBoxRejected && + pivotBox.IsValid() && + pivotBox.IsBullish() + // + ; + + // + bool isCond2Bearish = + // + false && + isBoxRejected && + pivotBox.IsValid() && + pivotBox.IsBearish() + // + ; + + // + bool isCond2 = isCond2Bullish || + isCond2Bearish; + if (isCond2) + { + // + providedSL = + isCond1Bullish + ? MathMin(pBar.low, pivotBox.lower) + : MathMax(pBar.high, pivotBox.upper); + + // + Print("Cond2"); + } + + // + // Cond3 Act Using CCi Peaks and Vales ... + + // + bool isCond3Bullish = false; + + // + bool isCond3Bearish = false; + + // + bool isCond3 = isCond3Bullish || + isCond3Bearish; + if (isCond3) + { + // + + // + Print("Cond3"); + } + + // + // Summarise Conditions ... + + // + bool isBullish = + // + isCond1Bullish || + isCond2Bullish; + // + ; + + // + bool isBearish = + // + isCond1Bearish || + isCond2Bearish + // + ; + + // + result = isBullish || + isBearish; + if (result) + { + // + dir = + isBullish + ? X_DIRECTION_BULLISH + : X_DIRECTION_BEARISH; + + // + double entry = GetEntry( + conditions.symbol, + dir // + ); + + // + double sl = + providedSL > 0 + ? providedSL + : isBullish + ? pivotBox.lower + : pivotBox.upper; + + // + box.dir = dir; + box.symbol = conditions.symbol; + box.period = conditions.period; + + // + box.upper = + isBullish + ? entry + : sl; + + // + box.lower = + isBullish + ? sl + : entry; + + // + box.to = zBar.time; + box.from = p4Bar.time; + + // + box.type = "XCASignal"; + } + + // + result = box.IsValid() && + HasDirection(dir); + + // + // Cleanup Resources ... + + // + if (!result) + { + // + box.Clean(); + pivotBox.Clean(); + conditions.Clean(); + } + + // + zBar.Clean(); + cBar.Clean(); + pBar.Clean(); + p2Bar.Clean(); + p3Bar.Clean(); + p4Bar.Clean(); + + // + return result; +} + +/////////////////////////////////////////////////////////////////////////////////// + // + // Detect Trend Lines ... + + // + // RSI ... + bool canLookupValeTrendLine = + detector.HasRSIValePivots() && + detector.CountRSIValePivots() >= 2; + if (canLookupValeTrendLine) + { + // + XBoxZone rsiVale; + XBoxZone rsiValePrev; + count = detector.CountRSIValePivots(); + has = detector.rsiValePivots[count - 1].AsBox(rsiValePrev); + has = has && + detector.rsiValePivots[count - 2].AsBox(rsiVale); + bool hasTrend = has && + rsiVale.lower > rsiValePrev.lower; + + // + if (hasTrend) + { + // + string valeTrendLineName = "RSIValeTrendLine"; + CChartObjectTrend *iVTLine; + iVTLine = new CChartObjectTrend(); + has = iVTLine.Create( + 0, + valeTrendLineName, + 0, + rsiValePrev.from, + rsiValePrev.lower, + rsiVale.to, + rsiVale.lower // + ); + if (has) + { + // + iVTLine.RayRight(true); + iVTLine.Width(2); + iVTLine.Color(clrAqua); + iVTLine.Style(STYLE_SOLID); + + // + mObjects.Add(iVTLine); + } + } + + // + rsiVale.Clean(); + rsiValePrev.Clean(); + } + + // + // CCI ... + // canLookupValeTrendLine = + // detector.HasCCIValePivots() && + // detector.CountCCIValePivots() >= 2; + // if (canLookupValeTrendLine) + // { + // // + // XBoxZone cciVale; + // XBoxZone cciValePrev; + // count = detector.CountCCIValePivots(); + // has = detector.cciValePivots[count - 1].AsBox(cciValePrev); + // has = has && + // detector.cciValePivots[count - 2].AsBox(cciVale); + // bool hasTrend = has && + // cciVale.lower > cciValePrev.lower; + + // // + // if (hasTrend) + // { + // // + // string valeTrendLineName = "CCIValeTrendLine"; + // CChartObjectTrend *iVTLine; + // iVTLine = new CChartObjectTrend(); + // has = iVTLine.Create( + // 0, + // valeTrendLineName, + // 0, + // cciValePrev.from, + // cciValePrev.lower, + // cciVale.to, + // cciVale.lower // + // ); + // if (has) + // { + // // + // iVTLine.RayRight(true); + // iVTLine.Width(2); + // iVTLine.Color(clrAqua); + // iVTLine.Style(STYLE_SOLID); + + // // + // mObjects.Add(iVTLine); + // } + // } + + // // + // cciVale.Clean(); + // cciValePrev.Clean(); + // } + +/////////////////////////////////////////////////////////////////////////////////// + +/////////////////////////////////////////////////////////////////////////////////// + +/////////////////////////////////////////////////////////////////////////////////// + +/////////////////////////////////////////////////////////////////////////////////// + +/////////////////////////////////////////////////////////////////////////////////// + +/////////////////////////////////////////////////////////////////////////////////// diff --git a/BKPS/14040203/Documents/BKP/xcaea.x-poi.detector.class.mq5 b/BKPS/14040203/Documents/BKP/xcaea.x-poi.detector.class.mq5 new file mode 100644 index 0000000..73fab8f --- /dev/null +++ b/BKPS/14040203/Documents/BKP/xcaea.x-poi.detector.class.mq5 @@ -0,0 +1,481 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Indicator +// ------------------------------------------------- +// Name: XCXCAEAPOIDetector ... +// Description: Class for XCAEA POI Detector ... +// +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +////////////////////////////////////////////////////// +// +// Global Properties ... +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://saherelm.ir" +#property version "1.00" +#property description "SaherElm Class for XCAEA POI Detector" +#property strict + +// +// Imports ... +#include "../../Classes/x-saherelm.x-bar.analyser.class.mq5" +#include "../Helpers/xcaea.helper.mq5" + +// +// Definitions ... + +// enum ENUM_X_PIVOT_KINDS +// { +// X_PIVOT_SWL, // SWL +// X_PIVOT_SWH, // SWH +// }; + +// string ToString(ENUM_X_PIVOT_KINDS value) +// { +// // +// string result = NULL; + +// // +// result = EnumToString(value); + +// // +// return result; +// } + +// struct XSamePivot +// { +// // +// // Props ... +// datetime to; +// string type; +// double value; +// datetime from; +// string symbol; +// ENUM_X_DIRECTION dir; +// ENUM_TIMEFRAMES period; + +// // +// // Constructor ... +// XSamePivot() +// { +// Clean(); +// } + +// // +// // Tools ... + +// /** +// * Cleanup Model ... +// */ +// void Clean() +// { +// // +// to = NULL; +// value = 0; +// from = NULL; +// type = NULL; +// symbol = NULL; +// period = NULL; +// dir = X_DIRECTION_NONE; +// } + +// /** +// * Validate Model ... +// * +// * @return ( bool ) +// */ +// bool IsValid() +// { +// // +// bool result = false; + +// // +// result = +// // +// from < to && +// value != 0 && +// IsValid(to) && +// IsValid(from) && +// IsValid(symbol) && +// IsValid(period) && +// HasDirection(dir) +// // +// ; + +// // +// return result; +// } + +// /** +// * Check a Model is Same As Other ... +// * +// * @return ( bool ) +// */ +// bool IsSameAs(XSamePivot &item) +// { +// // +// bool result = false; + +// // +// result = IsValid() && +// item.IsValid(); +// if (!result) +// { +// return result; +// } + +// // +// result = +// // +// to == item.to && +// dir == item.dir && +// from == item.from && +// type == item.type && +// value == item.value && +// symbol == item.symbol && +// period == item.period +// // +// ; + +// // +// return result; +// } + +// // +// }; + +// +// Implementations ... +class XCXCAEAPOIDetector : public XCBase +{ + // + // Public ... + public: + // + // Props ... + + // + // Constructors ... + XCXCAEAPOIDetector( + XCXCAEAHelper *_helper // + ) + { + // + helper = _helper; + barAnalyser = new XCBarAnalyser(); + + // + Default(); + } + + // + // De Constructors ... + ~XCXCAEAPOIDetector() + { + // + Clean(tkitrndPivots); + + // + ZeroMemory(helper); + ZeroMemory(barAnalyser); + } + + // + // Properties ... + + int TITrndPivotVerification() + { + return tkitrndPivotVerification; + } + + void TKITrndPivotVerification(int value) + { + // + value = NormalizeInt(value, 0); + + // + tkitrndPivotVerification = value; + } + + // + // Tools ... + + virtual void Default() + { + // + TKITrndPivotVerification(10); + } + + // + void Update( + int barIndex = 0, + int loopback = 100 // + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + loopback = NormalizeInt(loopback, 100); + + // + int index = barIndex; + int end = index + loopback; + while (index <= end) + { + // + XCAEAConditions iConditions; + bool has = helper.GetConditions( + iConditions, + index, + loopback // + ); + + // + // Detecting Same Pivots ... + // HandleTKITRNDPivotDetection(iConditions, index); + + // + index++; + iConditions.Clean(); + } + + // + } + + // + // POI Handlers ... + + // bool HasTKITRNDPivots() + // { + // return HasChild(tkitrndPivots); + // } + + // int CountTKITRNDPivots() + // { + // return ArraySize(tkitrndPivots); + // } + + // int FillTKITRNDPivots(XSamePivot &pivots[]) + // { + // // + // int result = 0; + + // // + // if (!HasTKITRNDPivots()) + // { + // return result; + // } + + // // + // Copy( + // tkitrndPivots, + // pivots // + // ); + + // // + // result = ArraySize(pivots); + + // // + // return result; + // } + + // bool IsTKITRNDPivotExists( + // int &index, + // XSamePivot &pivot // + // ) + // { + // // + // bool result = false; + + // // + // index = -1; + + // // + // result = pivot.IsValid() && + // HasTKITRNDPivots(); + // if (!result) + // { + // return result; + // } + + // // + // int count = CountTKITRNDPivots(); + // for (int i = 0; i < count; i++) + // { + // // + // XSamePivot iPivot = tkitrndPivots[i]; + + // // + // bool isSame = + // pivot.IsSameAs(iPivot); + // if (isSame) + // { + // // + // index = i; + // iPivot.Clean(); + + // // + // break; + // } + + // // + // iPivot.Clean(); + // } + + // // + // result = IsValidIndex(index); + + // // + // return result; + // } + + // + // Protected ... + protected: + // + // Props ... + + // // + // void HandleTKITRNDPivotDetection( + // XCAEAConditions &conditions, + // int barIndex = 0 // + // ) + // { + // // + // if (barIndex < 0) + // { + // barIndex = 0; + // } + + // // + // if (tkitrndPivotVerification <= 0) + // { + // return; + // } + + // // + // datetime barTime = GetBarTime( + // conditions.symbol, + // conditions.period, + // barIndex + 1 // + // ); + + // // + // int index = 2; + // datetime cTime = barTime; + // int end = ArraySize(conditions.swingLowBuffer); + + // // + // int swingLowVerified = 0; + // datetime swingLowFinishAt = NULL; + // datetime swingLowStartAt = barTime; + // double swingLow = conditions.swingLowBuffer[1]; + // bool canLookupSwingLow = true; + + // // + // bool isVerified = false; + // bool canContinue = true; + // while (index < end && canContinue) + // { + // // + // cTime += PeriodSeconds(conditions.period); + + // // + // // Swing Low ... + // double iSWL = conditions.swingLowBuffer[index]; + // if (iSWL == swingLow) + // { + // swingLowVerified++; + // } + // else if (iSWL != swingLow) + // { + // // + // isVerified = swingLowVerified >= tkitrndPivotVerification; + // if (isVerified) + // { + // // + // swingLowFinishAt = cTime; + + // // + // XSamePivot iPivot; + + // // + // iPivot.value = swingLow; + // iPivot.to = swingLowFinishAt; + // iPivot.from = swingLowStartAt; + // iPivot.dir = X_DIRECTION_BULLISH; + // iPivot.symbol = conditions.symbol; + // iPivot.period = conditions.period; + // iPivot.type = ToString(X_PIVOT_SWL); + + // // + // if (iPivot.IsValid()) + // { + // AddOrUpdateTKITRNDPivot(iPivot); + // } + // } + + // // + // // Reset ... + // swingLow = iSWL; + // swingLowVerified = 0; + // swingLowFinishAt = NULL; + // swingLowStartAt = cTime; + // canLookupSwingLow = true; + // } + + // // + // index++; + + // // + // canContinue = canLookupSwingLow; + // } + // } + + // // + // void AddOrUpdateTKITRNDPivot(XSamePivot &pivot) + // { + // // + // int idx = -1; + // bool isExists = IsTKITRNDPivotExists( + // idx, + // pivot // + // ); + // if (isExists) + // { + // return; + // } + + // // + // AddRef( + // pivot, + // tkitrndPivots // + // ); + // } + + // + // Prrivate ... + private: + // + // Props ... + int tkitrndPivotVerification; // KI/TKI/Trend Verification ... + + // + XCXCAEAHelper *helper; + XCBarAnalyser *barAnalyser; + + // + // Same Pivots ... + // XSamePivot tkitrndPivots[]; // TKITrend is Bullish/Bearish and Swing Low/High Under / Over Min / Max ... + + // +}; + +// \ No newline at end of file diff --git a/BKPS/14040203/Documents/Diagrams/Position Protection.drawio b/BKPS/14040203/Documents/Diagrams/Position Protection.drawio new file mode 100644 index 0000000..d425cb2 --- /dev/null +++ b/BKPS/14040203/Documents/Diagrams/Position Protection.drawio @@ -0,0 +1,279 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/BKPS/14040203/Documents/JsModules/x-color.tools.js b/BKPS/14040203/Documents/JsModules/x-color.tools.js new file mode 100644 index 0000000..c3ac5f9 --- /dev/null +++ b/BKPS/14040203/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/BKPS/14040203/Documents/JsModules/x-file.tools.js b/BKPS/14040203/Documents/JsModules/x-file.tools.js new file mode 100644 index 0000000..2a3535d --- /dev/null +++ b/BKPS/14040203/Documents/JsModules/x-file.tools.js @@ -0,0 +1,887 @@ +/** + * 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; +} + +/** + * Extract Specific files from a folder and it's content ... + * + * @param {string} path Folder Path ... + * @returns + */ +async function extractFiles(path = "", ext = [], excludeWorkspaceFolders = []) { + // + const result = []; + + // + if (!ext || ext.length == 0) { + return result; + } + + // + const pathContent = await getDirectoryContents(path); + if (!pathContent || pathContent.length == 0) { + return result; + } + + // + // Loop through Content ... + for (const c of pathContent) { + // + // Prepare full path ... + const cPath = joinPath(path, c); + + // + // check content path is file or not ... + const isCFile = isFileExists(cPath); + const isCDirectory = isDirectoryExists(cPath); + if (isCFile) { + // + // Check it is MQL file or not ... + const cExt = getFileExtension(cPath); + if (ext.includes(cExt)) { + result.push(cPath); + } + } else if (isCDirectory) { + // + const destFolderName = basename(cPath); + const isExcluded = excludeWorkspaceFolders.includes(destFolderName); + if (isExcluded) { + continue; + } + + // + const cFiles = await extractFiles(cPath, ext); + if (cFiles && cFiles.length > 0) { + result.push(...cFiles); + } + } + } + + // + 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, + extractFiles, + + // + copyFolder, + createDirectory, + removeDirectory, + isDirectoryExists, + getDirectoryFiles, + getDirectoryFolders, + getDirectoryContents, +}; +//#endregion \ No newline at end of file diff --git a/BKPS/14040203/Documents/JsModules/x-shell.tools.js b/BKPS/14040203/Documents/JsModules/x-shell.tools.js new file mode 100644 index 0000000..0ee13de --- /dev/null +++ b/BKPS/14040203/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/BKPS/14040203/Documents/JsModules/x-type-detector.tools.js b/BKPS/14040203/Documents/JsModules/x-type-detector.tools.js new file mode 100644 index 0000000..86ed3d8 --- /dev/null +++ b/BKPS/14040203/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/BKPS/14040203/Documents/JsModules/x-value.tools.js b/BKPS/14040203/Documents/JsModules/x-value.tools.js new file mode 100644 index 0000000..81cfcc4 --- /dev/null +++ b/BKPS/14040203/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/BKPS/14040203/Documents/Temlates/signalling.function.template.mq5 b/BKPS/14040203/Documents/Temlates/signalling.function.template.mq5 new file mode 100644 index 0000000..3cbd45a --- /dev/null +++ b/BKPS/14040203/Documents/Temlates/signalling.function.template.mq5 @@ -0,0 +1,221 @@ + +// +// Detect Signals Based On XPV Indicator Golden Zones ... +// +bool HasTMPConditions( + ENUM_X_CYCLES cycle, + XBoxZone &box, + ENUM_X_DIRECTION &dir, + X121SMCStrategySignalProviderData &provider, + int barIndex = 0 // +) +{ + // + bool result = false; + + // + box.Clean(); + dir = X_DIRECTION_NONE; + + // + // Fil Selected Data ... + XPOIState cState; + X121Conditions cXConditions; + XPOIStateEvents cStateEvents; + XC121SMCCycleHelper *cHelper; + X121SMCCycleConditions cConditions; + result = provider.SelectCycle( + cycle, + cState, + cStateEvents, + cXConditions, + cHelper, + cConditions // + ); + if (!result) + { + // + cState.Clean(); + ZeroMemory(cHelper); + cConditions.Clean(); + cXConditions.Clean(); + cStateEvents.Clean(); + + // + return result; + } + + // + // Normalize Args ... + + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + int idx = -1; + int count = 0; + bool has = false; + + // + int zIDX = barIndex; + int cIDX = zIDX + 1; + int pIDX = cIDX + 1; + int ppIDX = pIDX + 1; + + // + bool isBullish = false; + bool isBearish = false; + + // + XOHCL zBar; + XOHCL cBar; + XOHCL pBar; + XOHCL pPBar; + + // + // Initial Bars ... + result = zBar.Init( + cState.symbol, + cState.period, + barIndex // + ); + result = + result && + zBar.GetPreviousBar(cBar); + result = + result && + cBar.GetPreviousBar(pBar); + result = + result && + pBar.GetPreviousBar(pPBar); + if (!result) + { + // + zBar.Clean(); + cBar.Clean(); + pBar.Clean(); + cState.Clean(); + ZeroMemory(cHelper); + cConditions.Clean(); + cXConditions.Clean(); + + // + return result; + } + + // + // Checking Conditions ... + + // + // Summarize Conditions ... + + // + isBullish = + // + false + // + ; + + // + isBearish = + // + false + // + ; + + // + // Filling Requirements ... + result = + isBullish || + isBearish; + if (result) + { + // + dir = + isBullish + ? X_DIRECTION_BULLISH + : X_DIRECTION_BEARISH; + + // + box.dir = dir; + box.from = pPBar.time; + box.to = TimeCurrent(); + box.symbol = cBar.symbol; + box.period = cBar.period; + + // + double points = GetPoints(box.symbol); + + // + // Usually is Preffered SL ... + double pivot = 0; + + // + // Usually is Current Price or Entry Price ... + double point = GetEntry( + cBar.symbol, + dir // + ); + + // + box.upper = + isBullish + ? point + : pivot; + + // + box.lower = + isBullish + ? pivot + : point; + + // + XCPOIDrawer *drawer = provider.visionCycleHelper.mPOIDrawer; + bool drawBoxes = true; + if (drawBoxes) + { + // + if (box.IsValid()) { + // + XCBoxObject *iObj; + bool isCreated = drawer.DrawBox( + box, + iObj // + ); + + // + if (isCreated) { + // + // TODO: ... + } + } + } + } + + // + // Check All Conditions ... + result = + box.IsValid() && + HasDirection(dir) && + (isBullish || + isBearish); + + // + // Cleanup Resources ... + zBar.Clean(); + cBar.Clean(); + pBar.Clean(); + pPBar.Clean(); + cState.Clean(); + cConditions.Clean(); + cConditions.Clean(); + ZeroMemory(cHelper); + cStateEvents.Clean(); + cXConditions.Clean(); + + // + return result; +} diff --git a/BKPS/14040203/Documents/Temlates/x-saherelm.x-ea.template.ea.mq5 b/BKPS/14040203/Documents/Temlates/x-saherelm.x-ea.template.ea.mq5 new file mode 100644 index 0000000..ec3e257 --- /dev/null +++ b/BKPS/14040203/Documents/Temlates/x-saherelm.x-ea.template.ea.mq5 @@ -0,0 +1,542 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center XTest MQL5 Expert Advisor +// ------------------------------------------------- +// Name: XEATemplate +// Description: a Template For Exper Advisors +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +//////////////////////////////////////////////////////x +// +// Global Properties ... +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://saherelm.ir" +#property version "1.00" +#property description "SaherElm XEATemplate" +#property strict + +// +#define ShortName "XEATemplate" + +// +// Imports ... +#include "../Classes/x-saherelm.xalert.class.mq5" +#include "../Classes/x-saherelm.xtrade.class.mq5" +#include "../Helpers/x-saherelm.xcc.helper.mq5" +#include "../Helpers/x-saherelm.xct.helper.mq5" + +// +// Inputs ... + +// +// Common ... +input group "Common"; +input long eaMagicNumber = 78692110; // Magic Number +input int eaSlippage = 10; // Slippgae +input string eaLogSuffix = ""; // Log Suffix + +// +// Alert ... +// Here we Provider All Requirements for +// Configuring Alert Provider ... +input group "Alert"; +input bool eAEnableAlerts = true; // Enable Alerts +input bool eALogAlerts = true; // Log Alerts +input bool eAMailAlerts = false; // Mail Alerts +input bool eAPushAlerts = false; // Push Alerts +input bool eATerminalAlerts = false; // Terminal Alerts + +// +// Time Report ... +input group "Reports"; +input bool eaReportNewMonths = false; // Report New Month +input bool eaReportNewWeeks = false; // Report New Weeks +input bool eaReportNewDays = false; // Report New Days +input bool eaReportNewHours = false; // Report New Hours + +// +// Define Local Variables ... + +// +string eaLogTag; // EA Log Prefix ... +XSCAlert *eaAlert; // Alert Provider for Expert Adviser ... +XSCTrade *eaTrader; // Trader of Expert Adviser ... +XTimeTracker eaTimeTracker; // Time Tracker for Providing Reports ... +XSCXCTHelper *eaCHelper; // Bar Timer Indicator Helper class ... +XSCXCCHelper *eaCCHelper; // Chart Styler Indicator Helper Class ... + +// +// Event Handlers ... + +// +// Initialization ... +int OnInit() +{ + // + // Validate Inputs and Required Parameters + // for EA to Works fine ... + if (!ValidateInputs()) + { + return INIT_PARAMETERS_INCORRECT; + } + + // + // Initialize Timer ... + if (!InitTimer()) { + return INIT_FAILED; + } + + // + // Initialize all Requirements ... + if (!InitEA()) + { + return INIT_FAILED; + } + + // + // Initialize all GUI Objects and Classes ... + if (!InitGUI()) + { + return INIT_FAILED; + } + + // + // Alert Initialization ... + string msg = "Initialized Successfully ..."; + eaAlert.Alert(msg); + + // + // 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 + + // + // Destroy Timer ... + DestroyTimer(); + + // + // Destroy all GUI Requirements ... + DestroyGUI(); + + // + // Alert De Initialization Succeeded ... + string msg = "De Initialized Successfully ..."; + eaAlert.Alert(msg); + + // + // Destroy all EA Requirements ... + DestroyEA(); +} + +// +// On Tick Handler ... +void OnTick() +{ + // + UpdateGUI(); + HandleReportTime(); + UpdatePositionsState(); + + // + // TODO: Implemetn Tick Processors Algorithm ... +} + +// +// Handle On Trade Event ... +void OnTrade() +{ + eaTrader.HandleOnTrade(); +} + +// +// On Timer ... +void OnTimer() +{ + // + // TODO: Implement Time Based Functionalities ... +} + +// +// Chart Event Handler ... +void OnChartEvent( + const int id, + const long &lparam, + const double &dparam, + const string &sparam // +) +{ + // + // Handle OnClick Event ... + if (id == CHARTEVENT_OBJECT_CLICK) + { + HandleOnClickEvent(sparam); + } +} + +// +// Custom Event Handlers ... + +/** + * Handle StopLoss Triggered Positions ... + * + * @param deal: XDeal ... + */ +void OnStopLossTriggered(const XDeal &deal) +{ + // + HandleReportBalance(); +} + +/** + * Handle Take Profit Triggered Positions ... + * + * @param deal: XDeal ... + */ +void OnTakeProfitTriggered(const XDeal &deal) +{ + // + HandleReportBalance(); +} + +/** + * Handle Force Close a Position ... + * + * @param ticket: Position Ticket ... + * @param position: XPosition ... + * @param comment: Closing Comment ... + */ +void OnPositionForceClosed( + const ulong ticket, + const XPosition &position, + const string comment // +) +{ + // + HandleReportBalance(); +} + +// +// Custom Functions ... + +/** + * Validate all Inputs of Expert Adviser ... + * + * @return ( bool ) + */ +bool ValidateInputs() +{ + // + bool result = false; + + // + string errMessage = ""; + + // + bool isCommonValid = ( + // + eaSlippage > 0 && + eaMagicNumber > 0 + // + ); + if (!isCommonValid) + { + // + errMessage += "common configurations error;" + "\n"; + } + + // + result = + // + // Common ... + isCommonValid && + // + // Otere ... + true + // + ; + + // + if (!result) + { + // + // Since here Logger not Initiallized, we Use Raw Print Command ... + Print(ShortName + " Errors: \n", errMessage); + } + + // + return result; +} + +/** + * Initialize Timer ... + * + * @return ( bool ) + */ +bool InitTimer() { + // + bool result = false; + + // + // TODO: Initialize Timer if necessary ... + // result = EventSetTimer(1); + // result = EventSetMillisecondTimer(100); + result = true; + + // + return result; +} + +/** + * Destroy Timer ... + */ +void DestroyTimer() { + // + // TODO: Use This ... + // EventKillTimer(); +} + +/** + * Initialize all Requirements for Working Fine ... + * + * @return ( bool ) + */ +bool InitEA() +{ + // + bool result = false; + + // + // Locally Apply Changes on Prefix ... + eaLogTag = ShortName + ">" + eaLogSuffix; + + // + // Bar Timer ... + XCTInputs ctInputs; + ctInputs.Default(); // Default Configurations ... + eaCHelper = new XSCXCTHelper(); + result = eaCHelper.Init( + _Symbol, + _Period, + ctInputs // + ); + if (!result) + { + return result; + } + + // + // Bar Styles ... + XCCInputs ccInputs; + ccInputs.Default(); // Default Configurations ... + eaCCHelper = new XSCXCCHelper(); + result = eaCCHelper.Init( + _Symbol, + _Period, + ccInputs // + ); + if (!result) + { + return result; + } + + // + // Create Instance of Alert Class and Configure it ... + eaAlert = new XSCAlert(); + eaAlert.SetPrefix(eaLogTag); + eaAlert.SetLogAlerts(eALogAlerts); + eaAlert.SetMailAlerts(eAMailAlerts); + eaAlert.SetPushAlerts(eAPushAlerts); + eaAlert.SetEnableAlerts(eAEnableAlerts); + eaAlert.SetTerminalAlerts(eATerminalAlerts); + + // + // Create Trader Instance and Configure it ... + eaTrader = new XSCTrade( + eaSlippage, + eaMagicNumber // + ); + eaTrader.AddOnStopLossEventHandler(OnStopLossTriggered); + eaTrader.AddOnTakeProfitEventHandler(OnTakeProfitTriggered); + eaTrader.AddOnForceClosePositionEventHandler(OnPositionForceClosed); + + // + return result; +} + +/** + * Destroy all Initialized EA Requirements ... + */ +void DestroyEA() +{ + // + delete eaCHelper; + delete eaCCHelper; + + // + delete eaAlert; +} + +/** + * Initialize all GUI Requirements for EA ... + * + * @return ( bool ) + */ +bool InitGUI() +{ + // + bool result = false; + + // + // TODO: Fix This ... + result = true; + + // + return result; +} + +/** + * Update GUI based on Each Ticks ... + */ +void UpdateGUI() +{ + // + // TODO: Implement this ... +} + +/** + * Destroy all Initialized GUi Requirements ... + */ +void DestroyGUI() +{ + // + // TODO: Complete this ... +} + +// +// Others ... + +/** + * Update Positions States ... + */ +void UpdatePositionsState() +{ + // + // TODO: Implement this ... +} + +/** + * Handle On Click Event for GUI Components ... + * + * @param name: Object Name ... + */ +void HandleOnClickEvent(string name) +{ + // + if (!IsValid(name)) + { + return; + } + + // + bool isClicked = false; + + // + // TODO: Implement Chart Objects On Click ... + + // + if (isClicked) + { + UpdateGUI(); + } +} + +/** + * Report Account Balance ... + */ +void HandleReportBalance() +{ + // + if (!IsRunningOnTestMode()) + { + return; + } + + // + string msg = "Balance: " + ToString(eaTrader.mAccount.GetBalance()); + eaAlert.Log(msg); +} + +/** + * Time Reporting based on Inputs ... + */ +void HandleReportTime() +{ + // + // Monthly Report .... + if (eaReportNewMonths && + eaTimeTracker.IsNewMonth()) + { + // + string msg = "New Month ..."; + + // + eaAlert.Alert(msg); + } + + // + // Weekly Report .... + if (eaReportNewWeeks && + eaTimeTracker.IsNewWeek()) + { + // + string msg = "New Week ..."; + + // + eaAlert.Alert(msg); + } + + // + // Daily Report .... + if (eaReportNewDays && + eaTimeTracker.IsNewDay()) + { + // + string msg = "New Day ..."; + + // + eaAlert.Alert(msg); + } + + // + // Hourly Report .... + if (eaReportNewHours && + eaTimeTracker.IsNewHour()) + { + // + string msg = "New Hour ..."; + + // + eaAlert.Alert(msg); + } +} + +// diff --git a/BKPS/14040203/Documents/Temlates/x-saherelm.x-panel.ea.mq5 b/BKPS/14040203/Documents/Temlates/x-saherelm.x-panel.ea.mq5 new file mode 100644 index 0000000..c04228d --- /dev/null +++ b/BKPS/14040203/Documents/Temlates/x-saherelm.x-panel.ea.mq5 @@ -0,0 +1,575 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center XTest MQL5 Expert Advisor +// ------------------------------------------------- +// Name: XPanelEA +// Description: an Exper Advisor which used Panels +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +//////////////////////////////////////////////////////x +// +// Global Properties ... +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://saherelm.ir" +#property version "1.00" +#property description "SaherElm XPanelEA" +#property strict + +// +#define ShortName "XPANELEA" + +// +// Imports ... +#include "../Classes/x-saherelm.x-app-dialog.class.mq5" +#include "../Classes/x-saherelm.xalert.class.mq5" +#include "../Classes/x-saherelm.xtrade.class.mq5" +#include "../Helpers/x-saherelm.xcc.helper.mq5" +#include "../Helpers/x-saherelm.xct.helper.mq5" + +// +// Inputs ... + +// +// Common ... +input group "Common"; +input long eaMagicNumber = 78692110; // Magic Number +input int eaSlippage = 10; // Slippgae +input string eaLogSuffix = ""; // Log Suffix + +// +// Alert ... +// Here we Provider All Requirements for +// Configuring Alert Provider ... +input group "Alert"; +input bool eAEnableAlerts = true; // Enable Alerts +input bool eALogAlerts = true; // Log Alerts +input bool eAMailAlerts = false; // Mail Alerts +input bool eAPushAlerts = false; // Push Alerts +input bool eATerminalAlerts = false; // Terminal Alerts + +// +// Time Report ... +input group "Reports"; +input bool eaReportNewMonths = false; // Report New Month +input bool eaReportNewWeeks = false; // Report New Weeks +input bool eaReportNewDays = false; // Report New Days +input bool eaReportNewHours = false; // Report New Hours + +// +// Define Local Variables ... + +// +string eaLogTag; // EA Log Prefix ... +XSCAlert *eaAlert; // Alert Provider for Expert Adviser ... +XSCTrade *eaTrader; // Trader of Expert Adviser ... +XTimeTracker eaTimeTracker; // Time Tracker for Providing Reports ... +XSCXCTHelper *eaCTHelper; // Bar Timer Indicator Helper class ... +XSCXCCHelper *eaCCHelper; // Chart Styler Indicator Helper Class ... + +// +XCAppDialog eaMainWindow; // EA Main Dialog ... + +// +// Event Handlers ... + +// +// Initialization ... +int OnInit() +{ + // + // Validate Inputs and Required Parameters + // for EA to Works fine ... + if (!ValidateInputs()) + { + return INIT_PARAMETERS_INCORRECT; + } + + // + // Initialize Timer ... + if (!InitTimer()) + { + return INIT_FAILED; + } + + // + // Initialize all Requirements ... + if (!InitEA()) + { + return INIT_FAILED; + } + + // + // Initialize all GUI Objects and Classes ... + if (!InitGUI()) + { + return INIT_FAILED; + } + + // + // Alert Initialization ... + string msg = "Initialized Successfully ..."; + eaAlert.Alert(msg); + + // + // 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 + + // + // Destroy Timer ... + DestroyTimer(); + + // + // Destroy all GUI Requirements ... + DestroyGUI(); + + // + // Alert De Initialization Succeeded ... + string msg = "De Initialized Successfully ..."; + eaAlert.Alert(msg); + + // + // Destroy all EA Requirements ... + DestroyEA(); +} + +// +// On Tick Handler ... +void OnTick() +{ + // + UpdateGUI(); + HandleReportTime(); + UpdatePositionsState(); + + // + // TODO: Implemetn Tick Processors Algorithm ... +} + +// +// Handle On Trade Event ... +void OnTrade() +{ + eaTrader.HandleOnTrade(); +} + +// +// On Timer ... +void OnTimer() +{ + // + // TODO: Implement Time Based Functionalities ... +} + +// +// Chart Event Handler ... +void OnChartEvent( + const int id, + const long &lparam, + const double &dparam, + const string &sparam // +) +{ + // + // Apply Chart Event on Main Window ... + eaMainWindow.ChartEvent(id, lparam, dparam, sparam); + + // + // Handle OnClick Event ... + if (id == CHARTEVENT_OBJECT_CLICK) + { + HandleOnClickEvent(sparam); + } +} + +// +// Custom Event Handlers ... + +/** + * Handle StopLoss Triggered Positions ... + * + * @param deal: XDeal ... + */ +void OnStopLossTriggered(const XDeal &deal) +{ + // + HandleReportBalance(); +} + +/** + * Handle Take Profit Triggered Positions ... + * + * @param deal: XDeal ... + */ +void OnTakeProfitTriggered(const XDeal &deal) +{ + // + HandleReportBalance(); +} + +/** + * Handle Force Close a Position ... + * + * @param ticket: Position Ticket ... + * @param position: XPosition ... + * @param comment: Closing Comment ... + */ +void OnPositionForceClosed( + const ulong ticket, + const XPosition &position, + const string comment // +) +{ + // + HandleReportBalance(); +} + +// +// Custom Functions ... + +/** + * Validate all Inputs of Expert Adviser ... + * + * @return ( bool ) + */ +bool ValidateInputs() +{ + // + bool result = false; + + // + string errMessage = ""; + + // + bool isCommonValid = ( + // + eaSlippage > 0 && + eaMagicNumber > 0 + // + ); + if (!isCommonValid) + { + // + errMessage += "common configurations error;" + "\n"; + } + + // + result = + // + // Common ... + isCommonValid && + // + // Otere ... + true + // + ; + + // + if (!result) + { + // + // Since here Logger not Initiallized, we Use Raw Print Command ... + Print(ShortName + " Errors: \n", errMessage); + } + + // + return result; +} + +/** + * Initialize Timer ... + * + * @return ( bool ) + */ +bool InitTimer() +{ + // + bool result = false; + + // + // TODO: Initialize Timer if necessary ... + // result = EventSetTimer(1); + // result = EventSetMillisecondTimer(100); + result = true; + + // + return result; +} + +/** + * Destroy Timer ... + */ +void DestroyTimer() +{ + // + // TODO: Use This ... + // EventKillTimer(); +} + +/** + * Initialize all Requirements for Working Fine ... + * + * @return ( bool ) + */ +bool InitEA() +{ + // + bool result = false; + + // + // Locally Apply Changes on Prefix ... + eaLogTag = ShortName + ">" + eaLogSuffix; + + // + // Bar Timer ... + XCTInputs ctInputs; + ctInputs.Default(); // Default Configurations ... + eaCTHelper = new XSCXCTHelper(); + result = eaCTHelper.Init( + _Symbol, + _Period, + ctInputs // + ); + if (!result) + { + return result; + } + + // + // Bar Styles ... + XCCInputs ccInputs; + ccInputs.Default(); // Default Configurations ... + eaCCHelper = new XSCXCCHelper(); + result = eaCCHelper.Init( + _Symbol, + _Period, + ccInputs // + ); + if (!result) + { + return result; + } + + // + // Create Instance of Alert Class and Configure it ... + eaAlert = new XSCAlert(); + eaAlert.SetPrefix(eaLogTag); + eaAlert.SetLogAlerts(eALogAlerts); + eaAlert.SetMailAlerts(eAMailAlerts); + eaAlert.SetPushAlerts(eAPushAlerts); + eaAlert.SetEnableAlerts(eAEnableAlerts); + eaAlert.SetTerminalAlerts(eATerminalAlerts); + + // + // Create Trader Instance and Configure it ... + eaTrader = new XSCTrade( + eaSlippage, + eaMagicNumber // + ); + eaTrader.AddOnStopLossEventHandler(OnStopLossTriggered); + eaTrader.AddOnTakeProfitEventHandler(OnTakeProfitTriggered); + eaTrader.AddOnForceClosePositionEventHandler(OnPositionForceClosed); + + // + return result; +} + +/** + * Destroy all Initialized EA Requirements ... + */ +void DestroyEA() +{ + // + delete eaCTHelper; + delete eaCCHelper; + + // + delete eaAlert; +} + +/** + * Initialize all GUI Requirements for EA ... + * + * @return ( bool ) + */ +bool InitGUI() +{ + // + bool result = false; + + // + // Initialize Application Main Window ... + result = eaMainWindow.Create( + ChartID(), + ShortName, // Dialog Name ... + 0, // SubWindow ... + 10, // X1 ... + 35, // Y1 ... + 300, // X2 ... + 200 // Y2 ... + ); + + // + // Configuring Dialog ... + // eaMainWindow.MinimizeButton(false); // Hide Minimize Button ... + // eaMainWindow.CloseButton(false); // Hide Close Button ... + eaMainWindow.BackgroundColor(clrBlack); + // result = true; + + // + // Try To Run Main Window ... + if (result) + { + eaMainWindow.Run(); + } + + // + return result; +} + +/** + * Update GUI based on Each Ticks ... + */ +void UpdateGUI() +{ + // + // TODO: Implement this ... +} + +/** + * Destroy all Initialized GUi Requirements ... + */ +void DestroyGUI() +{ + // + eaMainWindow.Destroy(); +} + +// +// Others ... + +/** + * Update Positions States ... + */ +void UpdatePositionsState() +{ + // + // TODO: Implement this ... +} + +/** + * Handle On Click Event for GUI Components ... + * + * @param name: Object Name ... + */ +void HandleOnClickEvent(string name) +{ + // + if (!IsValid(name)) + { + return; + } + + // + bool isClicked = false; + + // + // TODO: Implement Chart Objects On Click ... + + // + if (isClicked) + { + UpdateGUI(); + } +} + +/** + * Report Account Balance ... + */ +void HandleReportBalance() +{ + // + if (!IsRunningOnTestMode()) + { + return; + } + + // + string msg = "Balance: " + ToString(eaTrader.mAccount.GetBalance()); + eaAlert.Log(msg); +} + +/** + * Time Reporting based on Inputs ... + */ +void HandleReportTime() +{ + // + // Monthly Report .... + if (eaReportNewMonths && + eaTimeTracker.IsNewMonth()) + { + // + string msg = "New Month ..."; + + // + eaAlert.Alert(msg); + } + + // + // Weekly Report .... + if (eaReportNewWeeks && + eaTimeTracker.IsNewWeek()) + { + // + string msg = "New Week ..."; + + // + eaAlert.Alert(msg); + } + + // + // Daily Report .... + if (eaReportNewDays && + eaTimeTracker.IsNewDay()) + { + // + string msg = "New Day ..."; + + // + eaAlert.Alert(msg); + } + + // + // Hourly Report .... + if (eaReportNewHours && + eaTimeTracker.IsNewHour()) + { + // + string msg = "New Hour ..."; + + // + eaAlert.Alert(msg); + } +} + +// diff --git a/BKPS/14040203/Documents/Temlates/xwz.signal.senario.template.mq5 b/BKPS/14040203/Documents/Temlates/xwz.signal.senario.template.mq5 new file mode 100644 index 0000000..f9f6052 --- /dev/null +++ b/BKPS/14040203/Documents/Temlates/xwz.signal.senario.template.mq5 @@ -0,0 +1,187 @@ + + // + // Senario 3: + // ---------- + bool useSenario3 = false; + bool isSenario3Happend = false; + bool isSenario3Bullish = false; + bool isSenario3Bearish = false; + if (useSenario3) + { + // + // Senario 3 Bullish Conditions ... + isSenario3Bullish = false; + + // + // Senario 3 Bearish Conditions ... + isSenario3Bearish = false; + + // + // Filling Requirements using Senario 3 ... + isSenario3Happend = + isSenario3Bullish || + isSenario3Bearish; + if (isSenario3Happend) + { + // + dir = + isSenario3Bullish + ? X_DIRECTION_BULLISH + : X_DIRECTION_BEARISH; + + // + box.dir = dir; + box.to = TimeCurrent(); + box.symbol = provider + .decisionXConditions + .symbol; + box.period = provider + .decisionXConditions + .period; + + // + int fromIDX = -1; + if (isSenario3Bullish) + { + // + double vale = provider + .decisionXConditions + .valesBuffer[cIDX]; + + // + box.lower = vale; + + // + box.upper = provider + .decisionXConditions + .valesGoldenBuffer[cIDX]; + + // + int lowerValeIDX = -1; + double lowerVale = provider + .decisionCycleHelper + .mX121Helper + .xpvHelper + .GetLowerVale( + lowerValeIDX, + vale, + cBar.Index() // + ); + + // + int higherValeIDX = -1; + double higherVale = provider + .decisionCycleHelper + .mX121Helper + .xpvHelper + .GetHigherVale( + higherValeIDX, + vale, + cBar.Index() // + ); + + // + if (IsValidIndex(lowerValeIDX) && + IsValidIndex(higherValeIDX)) + { + // + fromIDX = + lowerValeIDX < higherValeIDX + ? lowerValeIDX + : higherValeIDX; + } + else if (IsValidIndex(lowerValeIDX) && + !IsValidIndex(higherValeIDX)) + { + // + fromIDX = lowerValeIDX; + } + else if (!IsValidIndex(lowerValeIDX) && + IsValidIndex(higherValeIDX)) + { + // + fromIDX = higherValeIDX; + } + } + else + { + // + double peak = provider + .decisionXConditions + .peaksBuffer[cIDX]; + + // + box.upper = peak; + + // + box.lower = provider + .decisionXConditions + .peaksGoldenBuffer[cIDX]; + + // + int lowerPeakIDX = -1; + double lowerPeak = provider + .decisionCycleHelper + .mX121Helper + .xpvHelper + .GetLowerPeak( + lowerPeakIDX, + peak, + cBar.Index() // + ); + + // + int higherPeakIDX = -1; + double higherPeak = provider + .decisionCycleHelper + .mX121Helper + .xpvHelper + .GetHigherPeak( + higherPeakIDX, + peak, + cBar.Index() // + ); + + // + if (IsValidIndex(lowerPeakIDX) && + IsValidIndex(higherPeakIDX)) + { + // + fromIDX = + lowerPeakIDX < higherPeakIDX + ? lowerPeakIDX + : higherPeakIDX; + } + else if (IsValidIndex(lowerPeakIDX) && + !IsValidIndex(higherPeakIDX)) + { + // + fromIDX = lowerPeakIDX; + } + else if (!IsValidIndex(lowerPeakIDX) && + IsValidIndex(higherPeakIDX)) + { + // + fromIDX = higherPeakIDX; + } + } + + // + if (IsValidIndex(fromIDX)) + { + // + box.from = iTime( + zBar.symbol, + zBar.period, + fromIDX // + ); + } + else + { + box.from = pBar.time; + } + + // + signalProvider = X121SMC_XWZ_PROVIDER_ACTIVATED_BOX; + } + } diff --git a/BKPS/14040203/Experts/x-saherelm.rr.tools.mq5 b/BKPS/14040203/Experts/x-saherelm.rr.tools.mq5 new file mode 100644 index 0000000..3166105 --- /dev/null +++ b/BKPS/14040203/Experts/x-saherelm.rr.tools.mq5 @@ -0,0 +1,431 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center XTest MQL5 Expert Advisor +// ------------------------------------------------- +// Name: XRRToolsEA +// Description: a Template For Exper Advisors +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +//////////////////////////////////////////////////////x +// +// Global Properties ... +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://saherelm.ir" +#property version "1.00" +#property description "SaherElm XRRToolsEA" +#property strict + +// +#define ShortName "XRRTools" + +// +// Imports ... +#include "../Classes/x-saherelm.x-alert.class.mq5" +#include "../Classes/x-saherelm.x-rm.panel.class.mq5" +#include "../Classes/x-saherelm.x-trade.class.mq5" +#include "../Helpers/x-saherelm.x121.xcc.helper.mq5" +#include "../Helpers/x-saherelm.x121.xct.helper.mq5" + +// +// Inputs ... + +// +// Common ... +input group "Common"; +input long eaMagicNumber = 78692110; // Magic Number +input int eaSlippage = 10; // Slippgae +input string eaLogSuffix = ""; // Log Suffix + +// +// Alert ... +// Here we Provider All Requirements for +// Configuring Alert Provider ... +input group "Alert"; +input bool eAEnableAlerts = true; // Enable Alerts +input bool eALogAlerts = true; // Log Alerts +input bool eAMailAlerts = false; // Mail Alerts +input bool eAPushAlerts = false; // Push Alerts +input bool eATerminalAlerts = false; // Terminal Alerts + +// +// Define Local Variables ... + +// +string eaLogTag; // EA Log Prefix ... +XCAlert *eaAlert; // Alert Provider for Expert Adviser ... +XCTrade *eaTrader; // Trader of Expert Adviser ... +XCRMPanel eaMainWindow; // Main Window ... +XCX121XCTHelper *eaCTHelper; // Bar Timer Indicator Helper class ... +XCX121XCCHelper *eaCCHelper; // Chart Styler Indicator Helper Class ... + +// +// Event Handlers ... + +// +// Initialization ... +int OnInit() +{ + // + // Validate Inputs and Required Parameters + // for EA to Works fine ... + if (!ValidateInputs()) + { + return INIT_PARAMETERS_INCORRECT; + } + + // + // Initialize Timer ... + if (!InitTimer()) + { + return INIT_FAILED; + } + + // + // Initialize all Requirements ... + if (!InitEA()) + { + return INIT_FAILED; + } + + // + // Initialize all GUI Objects and Classes ... + if (!InitGUI()) + { + return INIT_FAILED; + } + + // + // Alert Initialization ... + string msg = "Initialized Successfully ..."; + eaAlert.Alert(msg); + + // + // 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 + + // + // Destroy Timer ... + DestroyTimer(); + + // + // Destroy all GUI Requirements ... + DestroyGUI(); + + // + // Alert De Initialization Succeeded ... + string msg = "De Initialized Successfully ..."; + eaAlert.Alert(msg); + + // + // Destroy all EA Requirements ... + DestroyEA(); +} + +// +// On Tick Handler ... +void OnTick() +{ + // + UpdateGUI(); +} + +// +// Handle On Trade Event ... +void OnTrade() +{ + eaTrader.HandleOnTrade(); +} + +// +// On Timer ... +void OnTimer() +{ + // + // TODO: Implement Time Based Functionalities ... +} + +// +// Chart Event Handler ... +void OnChartEvent( + const int id, + const long &lparam, + const double &dparam, + const string &sparam // +) +{ + // + // Apply Chart Event on Main Window ... + eaMainWindow.ChartEvent(id, lparam, dparam, sparam); +} + +// +// Custom Event Handlers ... + +/** + * Handle StopLoss Triggered Positions ... + * + * @param deal: XDeal ... + */ +void OnStopLossTriggered(const XDeal &deal) +{ +} + +/** + * Handle Take Profit Triggered Positions ... + * + * @param deal: XDeal ... + */ +void OnTakeProfitTriggered(const XDeal &deal) +{ +} + +/** + * Handle Force Close a Position ... + * + * @param ticket: Position Ticket ... + * @param position: XPosition ... + * @param comment: Closing Comment ... + */ +void OnPositionForceClosed( + const ulong ticket, + const XPosition &position, + const string comment // +) +{ +} + +// +// Custom Functions ... + +/** + * Validate all Inputs of Expert Adviser ... + * + * @return ( bool ) + */ +bool ValidateInputs() +{ + // + bool result = false; + + // + string errMessage = ""; + + // + bool isCommonValid = ( + // + eaSlippage > 0 && + eaMagicNumber > 0 + // + ); + if (!isCommonValid) + { + // + errMessage += "common configurations error;" + "\n"; + } + + // + result = + // + // Common ... + isCommonValid && + // + // Otere ... + true + // + ; + + // + if (!result) + { + // + // Since here Logger not Initiallized, we Use Raw Print Command ... + Print(ShortName + " Errors: \n", errMessage); + } + + // + return result; +} + +/** + * Initialize Timer ... + * + * @return ( bool ) + */ +bool InitTimer() +{ + // + bool result = false; + + // + // TODO: Initialize Timer if necessary ... + // result = EventSetTimer(1); + // result = EventSetMillisecondTimer(100); + result = true; + + // + return result; +} + +/** + * Destroy Timer ... + */ +void DestroyTimer() +{ + // + // TODO: Use This ... + // EventKillTimer(); +} + +/** + * Initialize all Requirements for Working Fine ... + * + * @return ( bool ) + */ +bool InitEA() +{ + // + bool result = false; + + // + // Locally Apply Changes on Prefix ... + eaLogTag = ShortName + ">" + eaLogSuffix; + + // + // Bar Timer ... + X121XCTInputs ctInputs; + ctInputs.Default(); // Default Configurations ... + eaCTHelper = new XCX121XCTHelper(); + result = eaCTHelper.Init( + _Symbol, + _Period, + ctInputs // + ); + if (!result) + { + return result; + } + + // + // Bar Styles ... + X121XCCInputs ccInputs; + ccInputs.Default(); // Default Configurations ... + eaCCHelper = new XCX121XCCHelper(); + result = eaCCHelper.Init( + _Symbol, + _Period, + ccInputs // + ); + if (!result) + { + return result; + } + + // + // Create Instance of Alert Class and Configure it ... + eaAlert = new XCAlert(); + eaAlert.SetPrefix(eaLogTag); + eaAlert.SetLogAlerts(eALogAlerts); + eaAlert.SetMailAlerts(eAMailAlerts); + eaAlert.SetPushAlerts(eAPushAlerts); + eaAlert.SetEnableAlerts(eAEnableAlerts); + eaAlert.SetTerminalAlerts(eATerminalAlerts); + + // + // Create Trader Instance and Configure it ... + eaTrader = new XCTrade( + eaSlippage, + eaMagicNumber // + ); + eaTrader.AddOnStopLossEventHandler(OnStopLossTriggered); + eaTrader.AddOnTakeProfitEventHandler(OnTakeProfitTriggered); + eaTrader.AddOnForceClosePositionEventHandler(OnPositionForceClosed); + + // + return result; +} + +/** + * Destroy all Initialized EA Requirements ... + */ +void DestroyEA() +{ + // + delete eaCTHelper; + delete eaCCHelper; + + // + delete eaAlert; +} + +/** + * Initialize all GUI Requirements for EA ... + * + * @return ( bool ) + */ +bool InitGUI() +{ + // + bool result = false; + + // + // Initialize Application Main Window ... + result = eaMainWindow.Create( + ChartID(), + ShortName, // Dialog Name ... + 0, // SubWindow ... + 10, // X1 ... + 35, // Y1 ... + 300, // X2 ... + 200 // Y2 ... + ); + + // + // Try To Run Main Window ... + if (result) + { + eaMainWindow.Run(); + } + + // + return result; +} + +/** + * Update GUI based on Each Ticks ... + */ +void UpdateGUI() +{ + // + eaMainWindow.UpdateState(); +} + +/** + * Destroy all Initialized GUi Requirements ... + */ +void DestroyGUI() +{ + // + eaMainWindow.Destroy(); +} + +// diff --git a/BKPS/14040203/Experts/x-saherelm.x-121.smc.ea.mq5 b/BKPS/14040203/Experts/x-saherelm.x-121.smc.ea.mq5 new file mode 100644 index 0000000..8a7cace --- /dev/null +++ b/BKPS/14040203/Experts/x-saherelm.x-121.smc.ea.mq5 @@ -0,0 +1,462 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center XTest MQL5 Expert Advisor +// ------------------------------------------------- +// Name: X121SMCEA +// Description: an Exper Advisor which used Panels +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +////////////////////////////////////////////////////// +// +// Global Properties ... +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://saherelm.ir" +#property version "1.00" +#property description "SaherElm X121SMCEA" +#property strict + +// +#define ShortName "X121SMCEA" + +// +// Imports ... +#include "../X121SMCEA/Experts/x-121.smc.expert.class.mq5" + +// +// Inputs ... + +// +// Common ... +input group "Common"; +input long eaMagicNumber = 78692110; // Magic Number +input int eaSlippage = 10; // Slippgae +input string eaLogSuffix = ""; // Log Suffix + +// +// Symbols ... +input group "Symbols"; +input bool eaMultiSymbol = false; // Use Multi Symbol +input string eaSymbols = "EURUSDb,GBPUSDb,USDCHFb,USDJPYb"; // Trading Symbols + +// +// Signalling ... +input group "Signalling"; +input bool eaAllowLong = true; // Allow Long Signals +input bool eaAllowShort = true; // Allow Short Signals +input int eaMaxAllowedLongs = 5; // Max Allowed Long Signals +input int eaMaxAllowedShorts = 5; // Max Allowed Short Signals +input bool eaUseMaxAllowedSignalsPerSymbol = true; // Use Max Allowed Signal Types Per Symbol +input double eaLastPositionProfitForAcceptNextInPoint = 0; // Last Position Profit In Points for Accept new Signal +input int eaDelaysBetweenTwoSignalsInBar = 0; // Delay between two Signals in Bars +input double eaMaxAllowedSpread = 0; // Max Allowed Spread for Signalling + +// +// Trade ... +input group "Trade"; +input bool eaAllowTrade = true; // Allow Open Trade On Signals +input string eaStartTradeAt = ""; // Enable Trade on Signals on Time +input string eaStopTradeAt = ""; // Enable Trade on Signals on Time +input string eaCloseAllTradesAt = ""; // Enable Close All Trades on Signals on Time + +// +// Risk Management ... +input group "Risk Management"; +input double eaR2R = 6; // Signallers Risk to Reward Ratio +input double eaVolume = 0; // Static Volume +input double eaStaticBalance = 1000; // Static Balance +input double eaBalancePerTrade = 5; // Balance Used in Each Trade +input double eaRiskPercentPerBalance = 0; // Risk Percent Per Balance in Each Trade +input bool eaDynamicRiskManagement = false; // Dynamic Risk Management +input bool eaUseDynamicVolume = false; // Use Dynamic Volume +input double eaDynamicVolumeStep = 0.01; // Increase Volume Step +input double eaDynamicVolumeBalanceFactor = 200; // Balance Factor for Generate Dynamic Volume +input double eaMaxAllowedDrawdownToOpenTrades = 3; // Max Allowed Drawdown for Open Trades +input int eaMaxAllowedSLToPauseSignallingPerSymbol = 0; // Max Allowed SL for Pause Signalling Per Symbol +input int eaPauseSignallingAfterReachesMaxAllowedSLInSecconds = 0; // Pause Signalling Per Symbol afte Max Allowed SL Reached In Seconds + +// +// Protection ... +input group "Protection"; +input bool eaAllowHedging = false; // Allow Hedge Positions +input int eaMinOpenTradesFroHedging = 4; // Minimum Open Positions for Hedging +input double eaHedgingMinVolumeStep = 0.01; // Minimum Volume Step for Hedging +input double eaHedgeingMinRequiredProfitPerVolumeStep = 1.0; // Minimum Required Profit Per Volume Step for Hedging + +// +// Alert ... +// Here we Provider All Requirements for +// Configuring Alert Provider ... +input group "Alert"; +input bool eaEnableAlerts = true; // Enable Alerts +input bool eaLogAlerts = true; // Log Alerts +input bool eaMailAlerts = false; // Mail Alerts +input bool eaPushAlerts = false; // Push Alerts +input bool eaTerminalAlerts = false; // Terminal Alerts + +// +// Time Report ... +input group "Reports"; +input bool eaReportNewMonths = false; // Report New Month +input bool eaReportNewWeeks = false; // Report New Weeks +input bool eaReportNewDays = true; // Report New Days +input bool eaReportNewHours = false; // Report New Hours + +// +// Define Local Variables ... + +XC121SMCExpert *eaExpert; + +// +// Event Handlers ... + +// +// Initialization ... +int OnInit() +{ + // + // Validate Inputs and Required Parameters + // for EA to Works fine ... + if (!ValidateInputs()) + { + return INIT_PARAMETERS_INCORRECT; + } + + // + // Initialize Timer ... + if (!InitTimer()) + { + return INIT_FAILED; + } + + // + // Configure EA Expert Class ... + eaExpert = new XC121SMCExpert(); + + // + // Event Handlers ... + eaExpert.OnSignalEventListener = OnSignalRecieved; + eaExpert.OnDealsChangedEventListener = OnDealsChanged; + eaExpert.OnOrdersChangedEventListener = OnOrdersChanged; + eaExpert.OnPositionSLEventListener = OnStopLossTriggered; + eaExpert.OnPositionTPEventListener = OnTakeProfitTriggered; + eaExpert.OnPositionsChangedEventListener = OnPositionsChanged; + eaExpert.OnPositionForceCloseEventListener = OnPositionForceClosed; + + // + // Common ... + eaExpert.MagicNumber(eaMagicNumber); + eaExpert.Slippage(eaSlippage); + eaExpert.TagPrefix(eaLogSuffix); + + // + // Symbol ... + eaExpert.SetSymbol(_Symbol); + eaExpert.SetPeriod(_Period); + eaExpert.Symbols(eaSymbols); + eaExpert.MultiSymbol(eaMultiSymbol); + + // + // Signalling ... + eaExpert.AllowLong(eaAllowLong); + eaExpert.AllowShort(eaAllowShort); + eaExpert.MaxAllowedLongs(eaMaxAllowedLongs); + eaExpert.MaxAllowedShorts(eaMaxAllowedShorts); + eaExpert.UseMaxAllowedSignalsPerSymbol(eaUseMaxAllowedSignalsPerSymbol); + eaExpert.LastPositionProfitForAcceptNextInPoint(eaLastPositionProfitForAcceptNextInPoint); + eaExpert.DelaysBetweenTwoSignalsInBar(eaDelaysBetweenTwoSignalsInBar); + eaExpert.MaxAllowedSpread(eaMaxAllowedSpread); + + // + // Trade ... + eaExpert.AllowTrade(eaAllowTrade); + eaExpert.StartTradeAt(eaStartTradeAt); + eaExpert.StopTradeAt(eaStopTradeAt); + eaExpert.CloseAllTradesAt(eaCloseAllTradesAt); + + // + // Risk Management ... + eaExpert.R2R(eaR2R); + eaExpert.Volume(eaVolume); + eaExpert.StaticBalance(eaStaticBalance); + eaExpert.BalancePerTrade(eaBalancePerTrade); + eaExpert.RiskPercentPerBalance(eaRiskPercentPerBalance); + eaExpert.DynamicRiskManagement(eaDynamicRiskManagement); + eaExpert.UseDynamicVolume(eaUseDynamicVolume); + eaExpert.DynamicVolumeStep(eaDynamicVolumeStep); + eaExpert.DynamicVolumeBalanceFactor(eaDynamicVolumeBalanceFactor); + eaExpert.MaxAllowedDrawdownToOpenTrades(eaMaxAllowedDrawdownToOpenTrades); + eaExpert.MaxAllowedSLToPauseSignallingPerSymbol(eaMaxAllowedSLToPauseSignallingPerSymbol); + eaExpert.PauseSignallingAfterReachesMaxAllowedSLInSecconds(eaPauseSignallingAfterReachesMaxAllowedSLInSecconds); + + // + // Protection ... + eaExpert.AllowHedging(eaAllowHedging); + eaExpert.MinOpenTradesFroHedging(eaMinOpenTradesFroHedging); + eaExpert.HedgingMinVolumeStep(eaHedgingMinVolumeStep); + eaExpert.HedgeingMinRequiredProfitPerVolumeStep(eaHedgeingMinRequiredProfitPerVolumeStep); + + // + // Alert ... + eaExpert.SetAlertEnableAlerts(eaEnableAlerts); + eaExpert.SetAlertLogAlerts(eaLogAlerts); + eaExpert.SetAlertMailAlerts(eaMailAlerts); + eaExpert.SetAlertPushAlerts(eaPushAlerts); + eaExpert.SetAlertTerminalAlerts(eaTerminalAlerts); + + // + // Reports ... + eaExpert.ReportNewMonths(eaReportNewMonths); + eaExpert.ReportNewWeeks(eaReportNewWeeks); + eaExpert.ReportNewDays(eaReportNewDays); + eaExpert.ReportNewHours(eaReportNewHours); + + // + bool isInited = eaExpert.HandleOnInit(); + if (!isInited) + { + 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 + + // + // Destroy Timer ... + eaExpert.HandleOnDeInit(); + + // + delete eaExpert; + + // + ZeroMemory(eaExpert); +} + +// +// On Tick Handler ... +void OnTick() +{ + eaExpert.HandleOnTick(); +} + +// +// Handle On Trade Event ... +void OnTrade() +{ + eaExpert.HandleOnTrade(); +} + +// +// On Timer ... +void OnTimer() +{ + eaExpert.HandleOnTimer(); +} + +// +// Chart Event Handler ... +void OnChartEvent( + const int id, + const long &lparam, + const double &dparam, + const string &sparam // +) +{ + eaExpert.HandleOnChartEvent(id, lparam, dparam, sparam); +} + +// +// Event Listeners ... + +/** + * Do What we Want by Specific Signal ... + * + * @param signal: XSignal instance ... + * @param conditions: XStrategyConditions instance ... + */ +void OnSignalRecieved( + XSignal &signal, + X121SMCStrategyConditions &conditions // +) +{ + // + eaExpert.HandleOnSignalRecieved( + signal, + conditions // + ); +} + +/** + * Handle StopLoss Triggered Positions ... + * + * @param deal: XDeal instance ... + */ +void OnStopLossTriggered(const XDeal &deal) +{ + eaExpert.HandleOnStopLossTriggered(deal); +} + +/** + * Handle Take Profit Triggered Positions ... + * + * @param deal: XDeal instance ... + */ +void OnTakeProfitTriggered(const XDeal &deal) +{ + eaExpert.HandleOnTakeProfitTriggered(deal); +} + +/** + * Handle Force Close a Position ... + * + * @param ticket: ULONG ... + * @param position: XPosition instance ... + * @param comment: String ... + */ +void OnPositionForceClosed( + const ulong ticket, + const XPosition &position, + const string comment // +) +{ + // + eaExpert.HandleOnPositionForceClosed( + ticket, + position, + comment // + ); +} + +/** + * Handle Deals Changes ... + * + * @param count: Integer, Number of Changes ... + */ +void OnDealsChanged(int count) +{ + eaExpert.HandleOnDealsChanged(count); +} + +/** + * Handle Orders Changes ... + * + * @param count: Integer, Number of Changes ... + */ +void OnOrdersChanged(int count) +{ + eaExpert.HandleOnOrdersChanged(count); +} + +/** + * Handle Positions Changes ... + * + * @param count: Integer, Number of Changes ... + */ +void OnPositionsChanged(int count) +{ + eaExpert.HandleOnPositionsChanged(count); +} + +// +// Custom Functions ... + +/** + * Validate all Inputs of Expert Adviser ... + * + * @return ( bool ) + */ +bool ValidateInputs() +{ + // + bool result = false; + + // + string errMessage = ""; + + // + bool isCommonValid = ( + // + eaSlippage > 0 && + eaMagicNumber > 0 + // + ); + if (!isCommonValid) + { + // + errMessage += "common configurations error;" + "\n"; + } + + // + result = + // + // Common ... + isCommonValid && + // + // Otere ... + true + // + ; + + // + if (!result) + { + // + // Since here Logger not Initiallized, we Use Raw Print Command ... + Print(ShortName + " Errors: \n", errMessage); + } + + // + return result; +} + +/** + * Initialize Timer ... + * + * @return ( bool ) + */ +bool InitTimer() +{ + // + bool result = false; + + // + // TODO: Initialize Timer if necessary ... + // result = EventSetTimer(1); + // result = EventSetMillisecondTimer(100); + result = true; + + // + return result; +} + +/** + * Destroy Timer ... + */ +void DestroyTimer() +{ + // + // TODO: Use This ... + // EventKillTimer(); +} + +// diff --git a/BKPS/14040203/Experts/x-saherelm.xcaea.ea.mq5 b/BKPS/14040203/Experts/x-saherelm.xcaea.ea.mq5 new file mode 100644 index 0000000..d83c374 --- /dev/null +++ b/BKPS/14040203/Experts/x-saherelm.xcaea.ea.mq5 @@ -0,0 +1,624 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center XTest MQL5 Expert Advisor +// ------------------------------------------------- +// Name: XCAEA +// Description: an Exper Advisor which used Panels +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +////////////////////////////////////////////////////// +// +// Global Properties ... +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://saherelm.ir" +#property version "1.00" +#property description "SaherElm XCAEA EA" +#property strict + +// +// Imports ... +#include "../Classes/x-saherelm.x-alert.class.mq5" +#include "../Classes/x-saherelm.x-trade.class.mq5" +#include "../Classes/x-saherelm.x-volume.class.mq5" +#include "../XCAEA/Classes/xcaea.x-trade.manager.class.mq5" +#include "../XCAEA/Signals/xcaea.signaller.class.mq5" + +// +#define ShortName "XCAEAEA" + +// +// Inputs ... + +// +// Common ... +input group "Common"; +input long eaMagicNumber = 78692110; // Magic Number +input int eaSlippage = 10; // Slippgae +input string eaLogSuffix = ""; // Log Suffix + +// +// Volume ... +input group "Volume"; +input ENUM_X_VOLUME_SELECT_TYPE eaVolumeSelect = X_VOLUME_EQUITY; // Volume Applying Type +input double eaStaticVoluem = 0.0; // Static Volume +input double eaDynamicVolumeStepBalance = 0.0; // Step of Balance for Increase Volume +input double eaDynamicVolumeStepVolume = X_MIN_VOLUME; // Step of Volume Increasing +input double eaConstantRiskBalance = 0.0; // Constant Risk Balance per Trade +input double eaConstantPercent = 0.5; // Constant Percent of Balance Per Trade +input double eaConstantBalance = 0.0; // Constant Balance for Calculations + +// +// Alert ... +// Here we Provider All Requirements for +// Configuring Alert Provider ... +input group "Alert"; +input bool eaEnableAlerts = true; // Enable Alerts +input bool eaLogAlerts = true; // Log Alerts +input bool eaMailAlerts = false; // Mail Alerts +input bool eaPushAlerts = false; // Push Alerts +input bool eaTerminalAlerts = false; // Terminal Alerts + +// +// Time Report ... +input group "Reports"; +input bool eaReportNewMonths = false; // Report New Month +input bool eaReportNewWeeks = false; // Report New Weeks +input bool eaReportNewDays = true; // Report New Days +input bool eaReportNewHours = false; // Report New Hours + +// +// Variables, Instances ... +XCAlert *eaAlert; +XCTrade *eaTrade; +XSignal eaSignal; +XCVolume *eaVolume; +XCXCAEASignaller *eaSignaller; +XCXCAEATradeManager *eaTradeManager; +XCAEAStrategyConditions eaConditions; + +// +int eaMaxAllowedPositions = 5; +double eaMaxAllowedSpread = 25; +double eaMaxAllowedDrawdownFactor = 0.3; + +// +string eaTag = ""; + +// +// Event Handlers ... + +// +// Initialization ... +int OnInit() +{ + // + // Validate Inputs and Required Parameters + // for EA to Works fine ... + if (!ValidateInputs()) + { + return INIT_PARAMETERS_INCORRECT; + } + + // + // Initialize Timer ... + if (!InitTimer()) + { + return INIT_FAILED; + } + + // + // Initial Requirements ... + InitRequirements(); + + // + // Initialize Volume Manger ... + if (!InitVolume()) + { + return INIT_FAILED; + } + + // + // Init Succeed ... + return INIT_SUCCEEDED; +} + +// +// DeInitialization ... +void OnDeinit(const int reason) +{ + // + // REASON_PROGRAM 0 The EA has stopped working calling the ExpertRemove() function + // REASON_REMOVE 1 Program removed from a chart + // REASON_RECOMPILE 2 Program recompiled + // REASON_CHARTCHANGE 3 A symbol or a chart period is changed + // REASON_CHARTCLOSE 4 Chart closed + // REASON_PARAMETERS 5 Inputs changed by a user + // REASON_ACCOUNT 6 Another account has been activated or reconnection to the trade server has occurred due to changes in the account settings + // REASON_TEMPLATE 7 Another chart template applied + // REASON_INITFAILED 8 The OnInit() handler returned a non-zero value + // REASON_CLOSE 9 Terminal closed + + // + ZeroMemory(eaAlert); + ZeroMemory(eaTrade); + ZeroMemory(eaVolume); + ZeroMemory(eaSignaller); + + // + eaSignal.Clean(); + eaConditions.Clean(); + + // + DestroyTimer(); +} + +// +// On Tick Handler ... +void OnTick() +{ + // + int idx = -1; + int count = 0; + bool has = false; + + // + // Handle Position Management / Protections ... + eaTradeManager.Manage(); + + // + eaSignal.Clean(); + eaConditions.Clean(); + + // + double r2r = 5; + string provider = "XCAEA"; + ENUM_POSITION_TYPE type = POSITION_TYPE_BUY; + ENUM_X_ORDER_MODES mode = X_ORDER_MODE_MARKET; + + // + bool hasLong = false; + bool hasShort = false; + + // + // Start Calculations ... + + // + // Retrieve Common Data ... + string symbol = eaSignaller.GetSymbol(); + ENUM_TIMEFRAMES period = eaSignaller.GetPeriod(); + + // + datetime cTime = TimeCurrent(); + + // + // Required Value For SL/TP Calculations ... + double points = GetPoints(symbol); + double pip = GetPipPrice(symbol); + double pip2 = 2 * pip; + + // + has = eaSignaller.DetectSignalSetup( + r2r, + 300 // Max Allowed SL Distance ... + ); + if (has) + { + // + count = eaSignaller + .AddConditionsIfNotExists(); + + // + eaSignaller.mConditions.Clean(); + } + + // + // Check Setuped Conditions Exists ... + count = ArraySize(eaSignaller.mConditionsCollection); + has = IsValidSize(count); + if (!has) + { + return; + } + + // + for (int i = 0; i < count; i++) + { + // + has = eaSignaller + .DetectSignalTrigger(eaSignaller + .mConditionsCollection[i]); + + // + if (has) + { + // + idx = i; + eaConditions = eaSignaller.mConditionsCollection[i]; + break; + } + } + + // + has = IsValidIndex(idx); + if (has) + { + // + ArrayRemove( + eaSignaller.mConditionsCollection, + idx, + 1 // + ); + } + + // + // Check EA Conditions is Valid or not ... + has = eaConditions.IsSetuped() && + eaConditions.CanTrigger(); + if (!has) + { + // + eaConditions.Clean(); + return; + } + + // + // Setting Time to Conditions ... + eaConditions.time = cTime; + has = ToPositionType( + type, + eaConditions.type // + ); + if (!has) + { + // + eaSignal.Clean(); + eaConditions.Clean(); + + // + return; + } + + // + // Checking Trigger Direction ... + hasLong = eaConditions.HasBullishSignal(); + hasShort = eaConditions.HasBearishSignal(); + has = hasLong || + hasShort; + if (!has) + { + // + eaSignal.Clean(); + eaConditions.Clean(); + + // + return; + } + + // + // Preparing Signal ... + // + eaSignal.mode = mode; + eaSignal.type = type; + eaSignal.entry = GetEntry( + eaConditions.symbol, + eaConditions.dir // + ); + eaSignal.provider = provider; + eaSignal.sl = eaConditions.sl; + eaSignal.tp = eaConditions.tp; + eaSignal.volume = X_MIN_VOLUME; + eaSignal.time = eaConditions.time; + eaSignal.symbol = eaConditions.symbol; + eaSignal.period = eaConditions.period; + + // + Copy( + eaConditions.targets, + eaSignal.targets // + ); + + // + has = eaSignal.IsValid(); + if (!has) + { + // + eaSignal.Clean(); + eaConditions.Clean(); + return; + } + + // + // Handle Volume Management ... + double iVolume = eaVolume.CalculateVolume(eaSignal); + if (iVolume > X_MIN_VOLUME && + iVolume != eaSignal.volume) + { + eaSignal.volume = iVolume; + } + + // + // Draw Signal ... + + // + // Execute Signal ... + + // + has = eaTradeManager.Execute( + eaSignal, + eaConditions // + ); + if (has) + { + // + // Do What we Want on Successfully Execution Signal ... + Print("Signal Executed ..."); + } + + // + eaSignal.Clean(); + eaConditions.Clean(); +} + +// +// Handle On Trade Event ... +void OnTrade() +{ +} + +// +// On Timer ... +void OnTimer() +{ +} + +// +// Chart Event Handler ... +void OnChartEvent( + const int id, + const long &lparam, + const double &dparam, + const string &sparam // +) +{ +} + +// +// Event Listeners ... + +/** + * Handle StopLoss Triggered Positions ... + * + * @param deal: XDeal instance ... + */ +void OnStopLossTriggered(const XDeal &deal) +{ + eaTradeManager.HandleSL(deal); +} + +/** + * Handle Take Profit Triggered Positions ... + * + * @param deal: XDeal instance ... + */ +void OnTakeProfitTriggered(const XDeal &deal) +{ + eaTradeManager.HandleTP(deal); +} + +/** + * Handle Force Close a Position ... + * + * @param ticket: ULONG ... + * @param position: XPosition instance ... + * @param comment: String ... + */ +void OnPositionForceClosed( + const ulong ticket, + const XPosition &position, + const string comment // +) +{ + eaTradeManager.HandleForceClose(position); +} + +/** + * Handle Deals Changes ... + * + * @param count: Integer, Number of Changes ... + */ +void OnDealsChanged(int count) +{ +} + +/** + * Handle Orders Changes ... + * + * @param count: Integer, Number of Changes ... + */ +void OnOrdersChanged(int count) +{ +} + +/** + * Handle Positions Changes ... + * + * @param count: Integer, Number of Changes ... + */ +void OnPositionsChanged(int count) +{ +} + +// +// Custom Functions ... + +/** + * Validate all Inputs of Expert Adviser ... + * + * @return ( bool ) + */ +bool ValidateInputs() +{ + // + bool result = false; + + // + string errMessage = ""; + + // + bool isCommonValid = ( + // + eaSlippage > 0 && + eaMagicNumber > 0 + // + ); + if (!isCommonValid) + { + // + errMessage += "common configurations error;" + "\n"; + } + + // + result = + // + // Common ... + isCommonValid && + // + // Otere ... + true + // + ; + + // + if (!result) + { + // + // Since here Logger not Initiallized, we Use Raw Print Command ... + Print(ShortName + " Errors: \n", errMessage); + } + + // + return result; +} + +/** + * Initialize Timer ... + * + * @return ( bool ) + */ +bool InitTimer() +{ + // + bool result = false; + + // + // TODO: Initialize Timer if necessary ... + // result = EventSetTimer(1); + // result = EventSetMillisecondTimer(100); + result = true; + + // + return result; +} + +/** + * Destroy Timer ... + */ +void DestroyTimer() +{ + // + // TODO: Use This ... + // EventKillTimer(); +} + +/** + * Initial Volume Manager Class Based on Given Configuration ... + * + * @return ( bool ) + */ +bool InitVolume() +{ + // + bool result = false; + + // + eaVolume = new XCVolume(); + + // + result = eaVolume.Init( + eaVolumeSelect, + eaStaticVoluem, + eaDynamicVolumeStepBalance, + eaDynamicVolumeStepVolume, + eaConstantRiskBalance, + eaConstantPercent, + eaConstantBalance // + ); + + // + return result; +} + +/** + * Initial Requirements of EA ... + * + */ +void InitRequirements() +{ + // + // Preparing Tags ... + eaTag = + (IsValid(eaLogSuffix) + ? eaLogSuffix + "_" + : "") + + ShortName; + + // + // EA Alert ... + eaAlert = new XCAlert( + eaTag, + eaEnableAlerts, + eaLogAlerts, + eaTerminalAlerts, + eaMailAlerts, + eaPushAlerts // + ); + + // + // EA Trade ... + eaTrade = new XCTrade( + eaSlippage, + eaMagicNumber, + eaMaxAllowedSpread, + eaMaxAllowedPositions, + eaMaxAllowedDrawdownFactor // + ); + eaTrade.AddOnStopLossEventHandler(OnStopLossTriggered); + eaTrade.AddOnTakeProfitEventHandler(OnTakeProfitTriggered); + eaTrade.AddOnForceClosePositionEventHandler(OnPositionForceClosed); + + // + // EA Trae Manager ... + eaTradeManager = new XCXCAEATradeManager( + eaTrade // + ); + eaTradeManager.SetAlertEnableAlerts(eaEnableAlerts); + eaTradeManager.SetAlertPrefix(eaTag); + eaTradeManager.SetAlertLogAlerts(eaLogAlerts); + eaTradeManager.SetAlertMailAlerts(eaMailAlerts); + eaTradeManager.SetAlertPushAlerts(eaPushAlerts); + eaTradeManager.SetAlertTerminalAlerts(eaTerminalAlerts); + + // + // EA Signaller ... + eaSignaller = new XCXCAEASignaller( + _Symbol, + _Period // + ); + + // +} + +// diff --git a/BKPS/14040203/Helpers/x-saherelm.x121.helper.mq5 b/BKPS/14040203/Helpers/x-saherelm.x121.helper.mq5 new file mode 100644 index 0000000..a8b644d --- /dev/null +++ b/BKPS/14040203/Helpers/x-saherelm.x121.helper.mq5 @@ -0,0 +1,3123 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Helper Class Library +// ---------------------------------------------- +// Name: XCX121Helper +// Description: provides all Indicator +// Helper requirements ... +// +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +////////////////////////////////////////////////////// +// +// Global Properties ... +#property library +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://www.saherelm.ir" +#property version "1.00" +#property strict + +// +// Imports ... +#include "../Helpers/x-saherelm.x121.x3ma.helper.mq5" +#include "../Helpers/x-saherelm.x121.xatr.helper.mq5" +#include "../Helpers/x-saherelm.x121.xcc.helper.mq5" +#include "../Helpers/x-saherelm.x121.xche.helper.mq5" +#include "../Helpers/x-saherelm.x121.xhk.helper.mq5" +#include "../Helpers/x-saherelm.x121.xmas.helper.mq5" +#include "../Helpers/x-saherelm.x121.xpv.helper.mq5" +#include "../Helpers/x-saherelm.x121.xstr.helper.mq5" +#include "../Helpers/x-saherelm.x121.xvwap.helper.mq5" + +// +// Inputs ... +struct X121Inputs +{ + // + // Props ... + bool showRSI; + X121XCCInputs xccInputs; + X121XPVInputs xpvInputs; + X121XHKInputs xhkInputs; + X121XMASInputs xmasInputs; + X121XATRInputs xatrInputs; + X121XSTRInputs xstrInputs; + X121XCHEInputs xcheInputs; + X121X3MAInputs x3maInputs; + X121XVWAPInputs xvwapInputs; + + // + // X121XICHInputs xichInputs; + // X121XDONInputs xdonInputs; + // X121XDELTAInputs xdeltaInputs; + // X121XVOLUMEInputs xvolumeInputs; + + // + // Constructor ... + X121Inputs() + { + Clean(); + } + + // + // Tools ... + + /** + * Cleaning Up ... + */ + void Clean() + { + // + xccInputs.Clean(); + xpvInputs.Clean(); + xhkInputs.Clean(); + xmasInputs.Clean(); + xatrInputs.Clean(); + xstrInputs.Clean(); + xcheInputs.Clean(); + x3maInputs.Clean(); + xvwapInputs.Clean(); + + // + ZeroMemory(this); + } + + /** + * Set Default Values ... + */ + void Default() + { + // + xccInputs.Default(); + xpvInputs.Default(); + xhkInputs.Default(); + xmasInputs.Default(); + xatrInputs.Default(); + xstrInputs.Default(); + xcheInputs.Default(); + x3maInputs.Default(); + xvwapInputs.Default(); + } + + /** + * Validate ... + * + * @return ( bool ) + */ + bool IsValid() + { + // + bool result = false; + + // + result = + // + xccInputs.IsValid() && + xpvInputs.IsValid() && + xhkInputs.IsValid() && + xmasInputs.IsValid() && + xatrInputs.IsValid() && + xstrInputs.IsValid() && + xcheInputs.IsValid() && + x3maInputs.IsValid() && + xvwapInputs.IsValid(); + + // + return result; + } + + /** + * Extract Max Input Length ... + * + * @return ( int ) + */ + int Max() + { + // + int result = 0; + + // + int xpvMax = xpvInputs.Max(); + int xhkMax = xhkInputs.Max(); + int xmasMax = xmasInputs.Max(); + int xatrMax = xatrInputs.Max(); + int xstrMax = xstrInputs.Max(); + int xcheMax = xcheInputs.Max(); + int x3maMax = x3maInputs.Max(); + int xvwapMax = xvwapInputs.Max(); + + // + result = MathMax(xpvMax, xhkMax); + result = MathMax(result, xmasMax); + result = MathMax(result, xatrMax); + result = MathMax(result, xstrMax); + result = MathMax(result, xcheMax); + result = MathMax(result, x3maMax); + result = MathMax(result, xvwapMax); + + // + return result; + } +}; + +// +// Conditions ... +struct X121Conditions +{ + // + // Common ... + string symbol; + ENUM_TIMEFRAMES period; + datetime time; + + // + // XCC ... + + // + // Buffers ... + + // + // Conditions ... + + // + // XPV ... + + // + // Buffers ... + + // + double sarBuffer[]; + double cHHBuffer[]; + double cLLBuffer[]; + double sHHBuffer[]; + double sLLBuffer[]; + double mHHBuffer[]; + double mLLBuffer[]; + double lHHBuffer[]; + double lLLBuffer[]; + double hHHBuffer[]; + double hLLBuffer[]; + double peaksBuffer[]; + double valesBuffer[]; + double supportsBuffer[]; + double peaksGoldenBuffer[]; + double valesGoldenBuffer[]; + double resistancesBuffer[]; + double fractalsUpperBuffer[]; + double fractalsLowerBuffer[]; + + // + // Conditions ... + + // + bool isSarBullish; + bool isSarBearish; + + // + bool isSarSwitchedToBullish; + bool isSarSwitchedToBearish; + + // + bool isNewPeak; + bool isNewPeakOverLast; + bool isNewPeakUnderLast; + + // + bool isNewVale; + bool isNewValeOverLast; + bool isNewValeUnderLast; + + // + // XHK ... + + // + // Buffers ... + + // + double xhkSMLowBuffer[]; + double xhkRawLowBuffer[]; + double xhkSMOpenBuffer[]; + double xhkSMHighBuffer[]; + double xhkRawOpenBuffer[]; + double xhkRawHighBuffer[]; + double xhkSMCloseBuffer[]; + double xhkRawCloseBuffer[]; + + // + // Conditions ... + + // + bool isSMHKBullish; + bool isRawHKBullish; + bool isSMHKSwitchedToBullish; + bool isRawHKSwitchedToBullish; + + // + bool isSMHKBearish; + bool isRawHKBearish; + bool isSMHKSwitchedToBearish; + bool isRawHKSwitchedToBearish; + + // + bool isClosedOverSMHK; + bool isClosedUnderSMHK; + bool isClosedOverRawHK; + bool isClosedUnderRawHK; + + // + bool isRawHKClosedOverSMHK; + bool isRawHKClosedUnderSMHK; + + // + // XMAS ... + + // + // Buffers ... + + // + double midBuffer[]; + double upperBuffer[]; + double lowerBuffer[]; + + // + // Conditions ... + + // + // XATR ... + + // + // Buffers ... + + // + double rsiBuffer[]; + double atrBuffer[]; + double atrUpperBuffer[]; + double atrLowerBuffer[]; + double atrUpperSMBuffer[]; + double atrLowerSMBuffer[]; + double rsiChangeBuffer[]; + double rsiChangeSMBuffer[]; + double priceChangeBuffer[]; + double priceChangeSMBuffer[]; + + // + // Conditions ... + + // + bool isRsiInRange; + bool isRsiOverSold; + bool isRsiOverBought; + bool isRsiCrossedOverOverSold; + bool isRsiCrossedUnderOverSold; + bool isRsiCrossedOverOverBought; + bool isRsiCrossedUnderOverBought; + + // + bool isRsiSMOverPriceChange; + bool isRsiSMUnderPriceChange; + + // + bool isRsiSMCrossedOverPriceChange; + bool isRsiSMCrossedUnderPriceChange; + + // + bool isPriceChangeSMOverRsi; + bool isPriceChangeSMUnderRsi; + + // + bool isPriceChangeSMCrossedOverRsi; + bool isPriceChangeSMCrossedUnderRsi; + + // + bool isRsiOverRsiSM; + bool isRsiUnderRsiSM; + + // + bool isRsiCrossedOverRsiSM; + bool isRsiCrossedUnderRsiSM; + + // + bool isPriceChangeOverPriceChangeSM; + bool isPriceChangeUnderPriceChangeSM; + + // + bool isPriceChangeCrossedOverPriceChangeSM; + bool isPriceChangeCrossedUnderPriceChangeSM; + + // + // XSTR ... + + // + // Buffers ... + + // + double strBuffer[]; + double vidyaBuffer[]; + double strUpBuffer[]; + double strMidBuffer[]; + double strDownBuffer[]; + double strPriceBuffer[]; + double strStateBuffer[]; + double strSMLowBuffer[]; + double strSMHighBuffer[]; + double strMidStateBuffer[]; + + // + // Conditions ... + + // + bool isStrBullish; + bool isStrBearish; + + // + bool isStrSwitchedToBullish; + bool isStrSwitchedToBearish; + + // + // XCHE ... + + // + // Buffers ... + + // + double le1Buffer[]; + double se1Buffer[]; + double le2Buffer[]; + double se2Buffer[]; + double le1StartBuffer[]; + double se1StartBuffer[]; + double le2StartBuffer[]; + double se2StartBuffer[]; + + // + // Conditions ... + + // + bool isChe1Bullish; + bool isChe1Bearish; + + // + bool isChe1SwitchedToBullish; + bool isChe1SwitchedToBearish; + + // + bool isChe2Bullish; + bool isChe2Bearish; + + // + bool isChe2SwitchedToBullish; + bool isChe2SwitchedToBearish; + + // + bool isCheBullish; + bool isCheBearish; + + // + bool isCheSwitchedToBullish; + bool isCheSwitchedToBearish; + + // + // X3MA ... + + // + // Buffers ... + + // + double x3maMidBuffer[]; + double x3maFastBuffer[]; + double x3maSlowBuffer[]; + double x3maMidStateBuffer[]; + double x3maFastStateBuffer[]; + double x3maSlowStateBuffer[]; + + // + // Conditions ... + + // + bool isX3MaFastBullish; + bool isX3MaFastBearish; + bool isX3MaFastNeutural; + + // + bool isX3MaMidBullish; + bool isX3MaMidBearish; + bool isX3MaMidNeutural; + + // + bool isX3MaSlowBullish; + bool isX3MaSlowBearish; + bool isX3MaSlowNeutural; + + // + bool isX3MaFastOverMid; + bool isX3MaMidOverSlow; + + // + bool isX3MaFastUnderMid; + bool isX3MaMidUnderSlow; + + // + bool isX3MaBullishState; + bool isX3MaBearishState; + bool isX3MaNeuturalState; + + // + bool isX3MaBullishOrdered; + bool isX3MaBearishOrdered; + + // + bool isX3MaSwitchedToBullishOrdered; + bool isX3MaSwitchedToBearishOrdered; + + // + bool isX3MaSwitchedToBullishState; + bool isX3MaSwitchedToBearishState; + bool isX3MaSwitchedToNeuturalState; + + // + // XVWAP ... + + // + // Buffers ... + + // + double vwapMidBuffer[]; + double vwapFastBuffer[]; + double vwapSlowBuffer[]; + double vwapPriceBuffer[]; + double vwapVolumeBuffer[]; + double vwapMidStateBuffer[]; + double vwapFastStateBuffer[]; + double vwapSlowStateBuffer[]; + + // + // Conditions ... + + // + bool isVWapFastBullish; + bool isVWapFastBearish; + bool isVWapFastNeutural; + + // + bool isVWapMidBullish; + bool isVWapMidBearish; + bool isVWapMidNeutural; + + // + bool isVWapSlowBullish; + bool isVWapSlowBearish; + bool isVWapSlowNeutural; + + // + bool isVWapFastOverMid; + bool isVWapMidOverSlow; + + // + bool isVWapFastUnderMid; + bool isVWapMidUnderSlow; + + // + bool isVWapBullishState; + bool isVWapBearishState; + bool isVWapNeuturalState; + + // + bool isVWapBullishOrdered; + bool isVWapBearishOrdered; + + // + bool isVWapSwitchedToBullishOrdered; + bool isVWapSwitchedToBearishOrdered; + + // + bool isVWapSwitchedToBullishState; + bool isVWapSwitchedToBearishState; + bool isVWapSwitchedToNeuturalState; + + // + // Constructor ... + X121Conditions() + { + Clean(); + } + + // + // Tools ... + + /** + * Cleaning Up ... + */ + void Clean() + { + // + // Commons ... + symbol = NULL; + period = NULL; + time = NULL; + + // + // XPV ... + + // + // Buffers ... + + // + // Clean ... + + // + Clean(sarBuffer); + Clean(cHHBuffer); + Clean(cLLBuffer); + Clean(sHHBuffer); + Clean(sLLBuffer); + Clean(mHHBuffer); + Clean(mLLBuffer); + Clean(lHHBuffer); + Clean(lLLBuffer); + Clean(hHHBuffer); + Clean(hLLBuffer); + Clean(peaksBuffer); + Clean(valesBuffer); + Clean(supportsBuffer); + Clean(peaksGoldenBuffer); + Clean(valesGoldenBuffer); + Clean(resistancesBuffer); + Clean(fractalsUpperBuffer); + Clean(fractalsLowerBuffer); + + // + // Set As Series ... + + // + ArraySetAsSeries(sarBuffer, true); + ArraySetAsSeries(cHHBuffer, true); + ArraySetAsSeries(cLLBuffer, true); + ArraySetAsSeries(sHHBuffer, true); + ArraySetAsSeries(sLLBuffer, true); + ArraySetAsSeries(mHHBuffer, true); + ArraySetAsSeries(mLLBuffer, true); + ArraySetAsSeries(lHHBuffer, true); + ArraySetAsSeries(lLLBuffer, true); + ArraySetAsSeries(hHHBuffer, true); + ArraySetAsSeries(hLLBuffer, true); + ArraySetAsSeries(peaksBuffer, true); + ArraySetAsSeries(valesBuffer, true); + ArraySetAsSeries(supportsBuffer, true); + ArraySetAsSeries(peaksGoldenBuffer, true); + ArraySetAsSeries(valesGoldenBuffer, true); + ArraySetAsSeries(resistancesBuffer, true); + ArraySetAsSeries(fractalsUpperBuffer, true); + ArraySetAsSeries(fractalsLowerBuffer, true); + + // + // Conditions ... + + // + isNewPeak = false; + isNewVale = false; + isSarBullish = false; + isSarBearish = false; + isNewPeakOverLast = false; + isNewValeOverLast = false; + isNewPeakUnderLast = false; + isNewValeUnderLast = false; + isSarSwitchedToBullish = false; + isSarSwitchedToBearish = false; + + // + // XHK ... + + // + // Buffers ... + + // + // Clean ... + + // + Clean(xhkSMLowBuffer); + Clean(xhkRawLowBuffer); + Clean(xhkSMOpenBuffer); + Clean(xhkSMHighBuffer); + Clean(xhkRawOpenBuffer); + Clean(xhkRawHighBuffer); + Clean(xhkSMCloseBuffer); + Clean(xhkRawCloseBuffer); + + // + // Set As Series ... + + // + ArraySetAsSeries(xhkSMLowBuffer, true); + ArraySetAsSeries(xhkRawLowBuffer, true); + ArraySetAsSeries(xhkSMOpenBuffer, true); + ArraySetAsSeries(xhkSMHighBuffer, true); + ArraySetAsSeries(xhkRawOpenBuffer, true); + ArraySetAsSeries(xhkRawHighBuffer, true); + ArraySetAsSeries(xhkSMCloseBuffer, true); + ArraySetAsSeries(xhkRawCloseBuffer, true); + + // + // Conditions ... + + // + isSMHKBullish = false; + isSMHKBearish = false; + isRawHKBullish = false; + isRawHKBearish = false; + isClosedOverSMHK = false; + isClosedUnderSMHK = false; + isClosedOverRawHK = false; + isClosedUnderRawHK = false; + isRawHKClosedOverSMHK = false; + isRawHKClosedUnderSMHK = false; + isSMHKSwitchedToBearish = false; + isSMHKSwitchedToBullish = false; + isRawHKSwitchedToBullish = false; + isRawHKSwitchedToBearish = false; + + // + // XMAS ... + + // + // Buffers ... + + // + // Clean ... + + // + Clean(midBuffer); + Clean(upperBuffer); + Clean(lowerBuffer); + + // + // Set As Series ... + + // + ArraySetAsSeries(midBuffer, true); + ArraySetAsSeries(upperBuffer, true); + ArraySetAsSeries(lowerBuffer, true); + + // + // Conditions ... + + // + // XATR ... + + // + // Buffers ... + + // + // Clean ... + + // + Clean(rsiBuffer); + Clean(atrBuffer); + Clean(atrUpperBuffer); + Clean(atrLowerBuffer); + Clean(rsiChangeBuffer); + Clean(atrUpperSMBuffer); + Clean(atrLowerSMBuffer); + Clean(rsiChangeSMBuffer); + Clean(priceChangeBuffer); + Clean(priceChangeSMBuffer); + + // + // Set As Series ... + + // + ArraySetAsSeries(rsiBuffer, true); + ArraySetAsSeries(atrBuffer, true); + ArraySetAsSeries(atrUpperBuffer, true); + ArraySetAsSeries(atrLowerBuffer, true); + ArraySetAsSeries(rsiChangeBuffer, true); + ArraySetAsSeries(atrUpperSMBuffer, true); + ArraySetAsSeries(atrLowerSMBuffer, true); + ArraySetAsSeries(rsiChangeSMBuffer, true); + ArraySetAsSeries(priceChangeBuffer, true); + ArraySetAsSeries(priceChangeSMBuffer, true); + + // + // Conditions ... + + // + isRsiInRange = false; + isRsiOverSold = false; + isRsiOverRsiSM = false; + isRsiUnderRsiSM = false; + isRsiOverBought = false; + isRsiCrossedOverRsiSM = false; + isRsiCrossedUnderRsiSM = false; + isPriceChangeSMOverRsi = false; + isRsiSMOverPriceChange = false; + isRsiSMUnderPriceChange = false; + isPriceChangeSMUnderRsi = false; + isRsiCrossedOverOverSold = false; + isRsiCrossedUnderOverSold = false; + isRsiCrossedOverOverBought = false; + isRsiCrossedUnderOverBought = false; + isRsiSMCrossedOverPriceChange = false; + isPriceChangeSMCrossedOverRsi = false; + isRsiSMCrossedUnderPriceChange = false; + isPriceChangeSMCrossedUnderRsi = false; + isPriceChangeOverPriceChangeSM = false; + isPriceChangeUnderPriceChangeSM = false; + isPriceChangeCrossedOverPriceChangeSM = false; + isPriceChangeCrossedUnderPriceChangeSM = false; + + // + // XSTR ... + + // + // Buffers ... + + // + // Clean ... + + // + Clean(strBuffer); + Clean(vidyaBuffer); + Clean(strUpBuffer); + Clean(strMidBuffer); + Clean(strDownBuffer); + Clean(strPriceBuffer); + Clean(strStateBuffer); + Clean(strSMLowBuffer); + Clean(strSMHighBuffer); + Clean(strMidStateBuffer); + + // + // Set As Series ... + + // + ArraySetAsSeries(strBuffer, true); + ArraySetAsSeries(vidyaBuffer, true); + ArraySetAsSeries(strUpBuffer, true); + ArraySetAsSeries(strMidBuffer, true); + ArraySetAsSeries(strDownBuffer, true); + ArraySetAsSeries(strPriceBuffer, true); + ArraySetAsSeries(strStateBuffer, true); + ArraySetAsSeries(strSMLowBuffer, true); + ArraySetAsSeries(strSMHighBuffer, true); + ArraySetAsSeries(strMidStateBuffer, true); + + // + // Conditions ... + + // + isStrBullish = false; + isStrBearish = false; + isStrSwitchedToBullish = false; + isStrSwitchedToBearish = false; + + // + // XCHE ... + + // + // Buffers ... + + // + // Clean ... + + // + Clean(le1Buffer); + Clean(se1Buffer); + Clean(le2Buffer); + Clean(se2Buffer); + Clean(le1StartBuffer); + Clean(se1StartBuffer); + Clean(le2StartBuffer); + Clean(se2StartBuffer); + + // + // Set As Series ... + + // + ArraySetAsSeries(le1Buffer, true); + ArraySetAsSeries(se1Buffer, true); + ArraySetAsSeries(le2Buffer, true); + ArraySetAsSeries(se2Buffer, true); + ArraySetAsSeries(le1StartBuffer, true); + ArraySetAsSeries(se1StartBuffer, true); + ArraySetAsSeries(le2StartBuffer, true); + ArraySetAsSeries(se2StartBuffer, true); + + // + // Conditions ... + + // + isCheBullish = false; + isCheBearish = false; + isChe1Bullish = false; + isChe1Bearish = false; + isChe2Bullish = false; + isChe2Bearish = false; + isCheSwitchedToBullish = false; + isCheSwitchedToBearish = false; + isChe1SwitchedToBullish = false; + isChe1SwitchedToBearish = false; + isChe2SwitchedToBullish = false; + isChe2SwitchedToBearish = false; + + // + // X3MA ... + + // + // Buffers ... + + // + // Clean ... + + // + Clean(x3maMidBuffer); + Clean(x3maFastBuffer); + Clean(x3maSlowBuffer); + Clean(x3maMidStateBuffer); + Clean(x3maFastStateBuffer); + Clean(x3maSlowStateBuffer); + + // + // Set As Series ... + + // + ArraySetAsSeries(x3maMidBuffer, true); + ArraySetAsSeries(x3maFastBuffer, true); + ArraySetAsSeries(x3maSlowBuffer, true); + ArraySetAsSeries(x3maMidStateBuffer, true); + ArraySetAsSeries(x3maFastStateBuffer, true); + ArraySetAsSeries(x3maSlowStateBuffer, true); + + // + // Conditions ... + + // + isX3MaMidBullish = false; + isX3MaMidBearish = false; + isX3MaFastBullish = false; + isX3MaFastBearish = false; + isX3MaMidNeutural = false; + isX3MaSlowBullish = false; + isX3MaSlowBearish = false; + isX3MaFastOverMid = false; + isX3MaMidOverSlow = false; + isX3MaFastNeutural = false; + isX3MaSlowNeutural = false; + isX3MaFastUnderMid = false; + isX3MaMidUnderSlow = false; + isX3MaBullishState = false; + isX3MaBearishState = false; + isX3MaNeuturalState = false; + isX3MaBullishOrdered = false; + isX3MaBearishOrdered = false; + isX3MaSwitchedToBullishState = false; + isX3MaSwitchedToBearishState = false; + isX3MaSwitchedToNeuturalState = false; + isX3MaSwitchedToBullishOrdered = false; + isX3MaSwitchedToBearishOrdered = false; + + // + // XVWAP ... + + // + // Buffers ... + + // + // Clean ... + + // + Clean(vwapMidBuffer); + Clean(vwapFastBuffer); + Clean(vwapSlowBuffer); + Clean(vwapPriceBuffer); + Clean(vwapVolumeBuffer); + Clean(vwapMidStateBuffer); + Clean(vwapFastStateBuffer); + Clean(vwapSlowStateBuffer); + + // + // Set As Series ... + + // + ArraySetAsSeries(vwapMidBuffer, true); + ArraySetAsSeries(vwapFastBuffer, true); + ArraySetAsSeries(vwapSlowBuffer, true); + ArraySetAsSeries(vwapPriceBuffer, true); + ArraySetAsSeries(vwapVolumeBuffer, true); + ArraySetAsSeries(vwapMidStateBuffer, true); + ArraySetAsSeries(vwapFastStateBuffer, true); + ArraySetAsSeries(vwapSlowStateBuffer, true); + + // + // Conditions ... + + // + isVWapMidBullish = false; + isVWapMidBearish = false; + isVWapMidNeutural = false; + isVWapFastBullish = false; + isVWapFastBearish = false; + isVWapSlowBullish = false; + isVWapSlowBearish = false; + isVWapFastOverMid = false; + isVWapMidOverSlow = false; + isVWapFastNeutural = false; + isVWapSlowNeutural = false; + isVWapFastUnderMid = false; + isVWapMidUnderSlow = false; + isVWapBullishState = false; + isVWapBearishState = false; + isVWapNeuturalState = false; + isVWapBullishOrdered = false; + isVWapBearishOrdered = false; + isVWapSwitchedToBullishState = false; + isVWapSwitchedToBearishState = false; + isVWapSwitchedToNeuturalState = false; + isVWapSwitchedToBullishOrdered = false; + isVWapSwitchedToBearishOrdered = false; + + // + ZeroMemory(this); + } + + /** + * Generate Conditions Scores ... + * + * @param bullishScore: Double, Directional Scores Reference ... + * @param bearishScore: Double, Directional Scores Reference ... + */ + void GenerateScore( + double &bullishScore, + double &bearishScore // + ) + { + // + bullishScore = 0; + bearishScore = 0; + + // + double score = 1; + double minScore = 0.5; + double highScore = 1.5; + + // + // XCC ... + + // + // XPV ... + + // + if (isSarBullish) + { + bullishScore += minScore; + } + if (isSarSwitchedToBullish) + { + bullishScore += score; + } + + // + if (isSarBearish) + { + bearishScore += minScore; + } + if (isSarSwitchedToBearish) + { + bearishScore += score; + } + + // + // XHK ... + + // + if (isSMHKBullish) + { + bullishScore += minScore; + } + if (isRawHKBullish) + { + bullishScore += minScore; + } + if (isClosedOverSMHK) + { + bullishScore += minScore; + } + if (isClosedOverRawHK) + { + bullishScore += minScore; + } + if (isRawHKClosedOverSMHK) + { + bullishScore += minScore; + } + if (isSMHKSwitchedToBullish) + { + bullishScore += highScore; + } + if (isRawHKSwitchedToBullish) + { + bullishScore += highScore; + } + + // + if (isSMHKBearish) + { + bearishScore += minScore; + } + if (isRawHKBearish) + { + bearishScore += minScore; + } + if (isClosedUnderSMHK) + { + bearishScore += minScore; + } + if (isClosedUnderRawHK) + { + bearishScore += minScore; + } + if (isRawHKClosedUnderSMHK) + { + bearishScore += minScore; + } + if (isSMHKSwitchedToBearish) + { + bearishScore += highScore; + } + if (isRawHKSwitchedToBullish) + { + bearishScore += highScore; + } + + // + // XMAS ... + + // + // XATR ... + + // + if (isRsiOverSold) + { + bullishScore += minScore; + } + if (isRsiOverRsiSM) + { + bullishScore += minScore; + } + if (isRsiSMOverPriceChange) + { + bullishScore += minScore; + } + if (isPriceChangeSMOverRsi) + { + bullishScore += minScore; + } + if (isPriceChangeOverPriceChangeSM) + { + bullishScore += minScore; + } + + // + if (isRsiCrossedOverRsiSM) + { + bullishScore += score; + } + if (isRsiCrossedOverOverSold) + { + bullishScore += score; + } + if (isRsiCrossedUnderOverBought) + { + bullishScore += score; + } + if (isRsiSMCrossedOverPriceChange) + { + bullishScore += score; + } + if (isPriceChangeSMCrossedOverRsi) + { + bullishScore += score; + } + if (isPriceChangeCrossedOverPriceChangeSM) + { + bullishScore += score; + } + + // + if (isRsiOverBought) + { + bearishScore += minScore; + } + if (isRsiUnderRsiSM) + { + bearishScore += minScore; + } + if (isRsiSMUnderPriceChange) + { + bearishScore += minScore; + } + if (isPriceChangeSMUnderRsi) + { + bearishScore += minScore; + } + if (isPriceChangeUnderPriceChangeSM) + { + bearishScore += minScore; + } + + // + if (isRsiCrossedUnderRsiSM) + { + bearishScore += score; + } + if (isRsiCrossedUnderOverSold) + { + bearishScore += score; + } + if (isRsiCrossedOverOverBought) + { + bearishScore += score; + } + if (isRsiSMCrossedUnderPriceChange) + { + bearishScore += score; + } + if (isPriceChangeSMCrossedUnderRsi) + { + bearishScore += score; + } + if (isPriceChangeCrossedUnderPriceChangeSM) + { + bearishScore += score; + } + + // + // XSTR ... + + // + if (isStrBullish) + { + bullishScore += minScore; + } + if (isStrSwitchedToBullish) + { + bullishScore += score; + } + + // + if (isStrBearish) + { + bearishScore += minScore; + } + if (isStrSwitchedToBearish) + { + bearishScore += score; + } + + // + // XCHE ... + + // + if (isCheBullish) + { + bullishScore += score; + } + if (isCheSwitchedToBullish) + { + bullishScore += highScore; + } + if (isChe1Bullish && + !isCheBullish && + !isCheSwitchedToBullish) + { + bullishScore += minScore; + } + if (isChe1SwitchedToBullish && + !isCheBullish && + !isCheSwitchedToBullish) + { + bullishScore += minScore; + } + + // + if (isCheBearish) + { + bearishScore += score; + } + if (isCheSwitchedToBearish) + { + bearishScore += highScore; + } + if (isChe1Bearish && + !isCheBearish && + !isCheSwitchedToBearish) + { + bearishScore += minScore; + } + if (isChe1SwitchedToBearish && + !isCheBearish && + !isCheSwitchedToBearish) + { + bearishScore += minScore; + } + + // + // X3MA ... + + // + if (isX3MaBullishState) + { + bullishScore += score; + } + if (isX3MaBullishOrdered) + { + bullishScore += score; + } + if (isX3MaSwitchedToBullishState) + { + bullishScore += highScore; + } + if (isX3MaSwitchedToBullishOrdered) + { + bullishScore += highScore; + } + if (!isX3MaBullishState && + !isX3MaSwitchedToBullishState) + { + // + if (isX3MaFastBullish) + { + bullishScore += minScore; + } + if (isX3MaSlowBullish) + { + bullishScore += minScore; + } + } + if (!isX3MaBullishOrdered && + !isX3MaSwitchedToBullishOrdered) + { + // + if (isX3MaFastOverMid) + { + bullishScore += minScore; + } + if (isX3MaMidOverSlow) + { + bullishScore += minScore; + } + } + + // + if (isX3MaBearishState) + { + bearishScore += score; + } + if (isX3MaBearishOrdered) + { + bearishScore += score; + } + if (isX3MaSwitchedToBearishState) + { + bearishScore += highScore; + } + if (isX3MaSwitchedToBearishOrdered) + { + bearishScore += highScore; + } + if (!isX3MaBearishState && + !isX3MaSwitchedToBearishState) + { + // + if (isX3MaFastBearish) + { + bearishScore += minScore; + } + if (isX3MaSlowBearish) + { + bearishScore += minScore; + } + } + if (!isX3MaBearishOrdered && + !isX3MaSwitchedToBearishOrdered) + { + // + if (isX3MaFastUnderMid) + { + bearishScore += minScore; + } + if (isX3MaMidUnderSlow) + { + bearishScore += minScore; + } + } + + // + // XVWAP ... + + // + if (isVWapBullishState) + { + bullishScore += score; + } + if (isVWapBullishOrdered) + { + bullishScore += score; + } + if (isVWapSwitchedToBullishState) + { + bullishScore += highScore; + } + if (isVWapSwitchedToBullishOrdered) + { + bullishScore += highScore; + } + if (!isVWapBullishState && + !isVWapSwitchedToBullishState) + { + // + if (isVWapFastBullish) + { + bullishScore += minScore; + } + if (isVWapSlowBullish) + { + bullishScore += minScore; + } + } + if (!isVWapBullishOrdered && + !isVWapSwitchedToBullishOrdered) + { + // + if (isVWapFastOverMid) + { + bullishScore += minScore; + } + if (isVWapMidOverSlow) + { + bullishScore += minScore; + } + } + + // + if (isVWapBearishState) + { + bearishScore += score; + } + if (isVWapBearishOrdered) + { + bearishScore += score; + } + if (isVWapSwitchedToBearishState) + { + bearishScore += highScore; + } + if (isVWapSwitchedToBearishOrdered) + { + bearishScore += highScore; + } + if (!isVWapBearishState && + !isVWapSwitchedToBearishState) + { + // + if (isVWapFastBearish) + { + bearishScore += minScore; + } + if (isVWapSlowBearish) + { + bearishScore += minScore; + } + } + if (!isVWapBearishOrdered && + !isVWapSwitchedToBearishOrdered) + { + // + if (isVWapFastUnderMid) + { + bearishScore += minScore; + } + if (isVWapMidUnderSlow) + { + bearishScore += minScore; + } + } + } + + /** + * Generate Summary String for Represent Conditions State ... + * + * @param onlyCommons: Boolean, Just Generate Only Commons Conditions ... + * @param onlyConditions: Boolean, Just Generate Only Conditions ... + * @param includeScores: Boolean, Attach Scores Representations on Result ... + * @param ignoreFalseConditions: Boolean, Ignore False Conditions on Result ... + * @param separator: String, Separate Lines ... + * + * @return ( string ) + */ + string GenerateSummary( + bool onlyCommons = false, + bool onlyConditions = false, + bool includeScores = true, + bool ignoreFalseConditions = true, + string separator = "\n" // + ) + { + // + string result = NULL; + + // + double bullishScore = 0; + double bearishScore = 0; + GenerateScore( + bullishScore, + bearishScore // + ); + + // + string scoresStr = + // + "Scores: " + separator + + "---------------" + separator + + "Bullish: " + ToString(bullishScore) + separator + + "Bearish: " + ToString(bearishScore) + separator + + "" + // + ; + + // + string commonStr = GenerateSpecifiedCommonSummary( + this, + separator, + includeScores // + ); + + // + // XCC ... + + // + // XPV ... + + // + string pvConditionsStr = + // + "-----------------------" + separator + + "XPV: " + separator + + "-----------------------" + separator + + ToString("isSarBullish", isSarBullish, ignoreFalseConditions, separator) + + ToString("isSarBearish", isSarBearish, ignoreFalseConditions, separator) + + ToString("isSarSwitchedToBullish", isSarSwitchedToBullish, ignoreFalseConditions, separator) + + ToString("isSarSwitchedToBearish", isSarSwitchedToBearish, ignoreFalseConditions, separator) + + ToString("isNewPeak", isNewPeak, ignoreFalseConditions, separator) + + ToString("isNewPeakOverLast", isNewPeakOverLast, ignoreFalseConditions, separator) + + ToString("isNewPeakUnderLast", isNewPeakUnderLast, ignoreFalseConditions, separator) + + ToString("isNewVale", isNewVale, ignoreFalseConditions, separator) + + ToString("isNewValeOverLast", isNewValeOverLast, ignoreFalseConditions, separator) + + ToString("isNewValeUnderLast", isNewValeUnderLast, ignoreFalseConditions, separator) + + // + "" + // + ; + + // + // XHK ... + + // + string hkConditionsStr = + // + "-----------------------" + separator + + "XHK: " + separator + + "-----------------------" + separator + + ToString("isSMHKBullish", isSMHKBullish, ignoreFalseConditions, separator) + + ToString("isRawHKBullish", isRawHKBullish, ignoreFalseConditions, separator) + + ToString("isSMHKSwitchedToBullish", isSMHKSwitchedToBullish, ignoreFalseConditions, separator) + + ToString("isRawHKSwitchedToBullish", isRawHKSwitchedToBullish, ignoreFalseConditions, separator) + + ToString("isSMHKBearish", isSMHKBearish, ignoreFalseConditions, separator) + + ToString("isRawHKBearish", isRawHKBearish, ignoreFalseConditions, separator) + + ToString("isSMHKSwitchedToBearish", isSMHKSwitchedToBearish, ignoreFalseConditions, separator) + + ToString("isRawHKSwitchedToBearish", isRawHKSwitchedToBearish, ignoreFalseConditions, separator) + + ToString("isClosedOverSMHK", isClosedOverSMHK, ignoreFalseConditions, separator) + + ToString("isClosedUnderSMHK", isClosedUnderSMHK, ignoreFalseConditions, separator) + + ToString("isClosedOverRawHK", isClosedOverRawHK, ignoreFalseConditions, separator) + + ToString("isClosedUnderRawHK", isClosedUnderRawHK, ignoreFalseConditions, separator) + + ToString("isRawHKClosedOverSMHK", isRawHKClosedOverSMHK, ignoreFalseConditions, separator) + + ToString("isRawHKClosedUnderSMHK", isRawHKClosedUnderSMHK, ignoreFalseConditions, separator) + + // + "" + // + ; + + // + // XMAS ... + + // + // XATR ... + + // + string atrConditionsStr = + // + "-----------------------" + separator + + "XATR: " + separator + + "-----------------------" + separator + + ToString("isRsiInRange", isRsiInRange, ignoreFalseConditions, separator) + + ToString("isRsiOverSold", isRsiOverSold, ignoreFalseConditions, separator) + + ToString("isRsiOverBought", isRsiOverBought, ignoreFalseConditions, separator) + + ToString("isRsiCrossedOverOverSold", isRsiCrossedOverOverSold, ignoreFalseConditions, separator) + + ToString("isRsiCrossedUnderOverSold", isRsiCrossedUnderOverSold, ignoreFalseConditions, separator) + + ToString("isRsiCrossedOverOverBought", isRsiCrossedOverOverBought, ignoreFalseConditions, separator) + + ToString("isRsiCrossedUnderOverBought", isRsiCrossedUnderOverBought, ignoreFalseConditions, separator) + + // + ToString("isRsiSMOverPriceChange", isRsiSMOverPriceChange, ignoreFalseConditions, separator) + + ToString("isRsiSMUnderPriceChange", isRsiSMUnderPriceChange, ignoreFalseConditions, separator) + + ToString("isRsiSMCrossedOverPriceChange", isRsiSMCrossedOverPriceChange, ignoreFalseConditions, separator) + + ToString("isRsiSMCrossedUnderPriceChange", isRsiSMCrossedUnderPriceChange, ignoreFalseConditions, separator) + + ToString("isPriceChangeSMOverRsi", isPriceChangeSMOverRsi, ignoreFalseConditions, separator) + + ToString("isPriceChangeSMUnderRsi", isPriceChangeSMUnderRsi, ignoreFalseConditions, separator) + + ToString("isPriceChangeSMCrossedOverRsi", isPriceChangeSMCrossedOverRsi, ignoreFalseConditions, separator) + + ToString("isPriceChangeSMCrossedUnderRsi", isPriceChangeSMCrossedUnderRsi, ignoreFalseConditions, separator) + + ToString("isRsiOverRsiSM", isRsiOverRsiSM, ignoreFalseConditions, separator) + + ToString("isRsiUnderRsiSM", isRsiUnderRsiSM, ignoreFalseConditions, separator) + + ToString("isRsiCrossedOverRsiSM", isRsiCrossedOverRsiSM, ignoreFalseConditions, separator) + + ToString("isRsiCrossedUnderRsiSM", isRsiCrossedUnderRsiSM, ignoreFalseConditions, separator) + + ToString("isPriceChangeOverPriceChangeSM", isPriceChangeOverPriceChangeSM, ignoreFalseConditions, separator) + + ToString("isPriceChangeUnderPriceChangeSM", isPriceChangeUnderPriceChangeSM, ignoreFalseConditions, separator) + + ToString("isPriceChangeCrossedOverPriceChangeSM", isPriceChangeCrossedOverPriceChangeSM, ignoreFalseConditions, separator) + + ToString("isPriceChangeCrossedUnderPriceChangeSM", isPriceChangeCrossedUnderPriceChangeSM, ignoreFalseConditions, separator) + + // + "" + // + ; + + // + // XSTR ... + + // + string strConditionsStr = + // + "-----------------------" + separator + + "XSTR: " + separator + + "-----------------------" + separator + + ToString("isStrBullish", isStrBullish, ignoreFalseConditions, separator) + + ToString("isStrBearish", isStrBearish, ignoreFalseConditions, separator) + + ToString("isStrSwitchedToBullish", isStrSwitchedToBullish, ignoreFalseConditions, separator) + + ToString("isStrSwitchedToBearish", isStrSwitchedToBearish, ignoreFalseConditions, separator) + + // + "" + // + ; + + // + // XCHE ... + + // + string cheConditionsStr = + // + "-----------------------" + separator + + "XCHE: " + separator + + "-----------------------" + separator + + ToString("isChe1Bullish", isChe1Bullish, ignoreFalseConditions, separator) + + ToString("isChe1Bearish", isChe1Bearish, ignoreFalseConditions, separator) + + ToString("isChe1SwitchedToBullish", isChe1SwitchedToBullish, ignoreFalseConditions, separator) + + ToString("isChe1SwitchedToBearish", isChe1SwitchedToBearish, ignoreFalseConditions, separator) + + ToString("isChe2Bullish", isChe2Bullish, ignoreFalseConditions, separator) + + ToString("isChe2Bearish", isChe2Bearish, ignoreFalseConditions, separator) + + ToString("isChe2SwitchedToBullish", isChe2SwitchedToBullish, ignoreFalseConditions, separator) + + ToString("isChe2SwitchedToBearish", isChe2SwitchedToBearish, ignoreFalseConditions, separator) + + ToString("isCheBullish", isCheBullish, ignoreFalseConditions, separator) + + ToString("isCheBearish", isCheBearish, ignoreFalseConditions, separator) + + ToString("isCheSwitchedToBullish", isCheSwitchedToBullish, ignoreFalseConditions, separator) + + ToString("isCheSwitchedToBearish", isCheSwitchedToBearish, ignoreFalseConditions, separator) + + // + "" + // + ; + + // + // X3MA ... + + // + string x3maonditionsStr = + // + "-----------------------" + separator + + "X3MA: " + separator + + "-----------------------" + separator + + ToString("isX3MaFastBullish", isX3MaFastBullish, ignoreFalseConditions, separator) + + ToString("isX3MaFastBearish", isX3MaFastBearish, ignoreFalseConditions, separator) + + ToString("isX3MaFastNeutural", isX3MaFastNeutural, ignoreFalseConditions, separator) + + ToString("isX3MaMidBullish", isX3MaMidBullish, ignoreFalseConditions, separator) + + ToString("isX3MaMidBearish", isX3MaMidBearish, ignoreFalseConditions, separator) + + ToString("isX3MaMidNeutural", isX3MaMidNeutural, ignoreFalseConditions, separator) + + ToString("isX3MaSlowBullish", isX3MaSlowBullish, ignoreFalseConditions, separator) + + ToString("isX3MaSlowBearish", isX3MaSlowBearish, ignoreFalseConditions, separator) + + ToString("isX3MaSlowNeutural", isX3MaSlowNeutural, ignoreFalseConditions, separator) + + ToString("isX3MaFastOverMid", isX3MaFastOverMid, ignoreFalseConditions, separator) + + ToString("isX3MaMidOverSlow", isX3MaMidOverSlow, ignoreFalseConditions, separator) + + ToString("isX3MaFastUnderMid", isX3MaFastUnderMid, ignoreFalseConditions, separator) + + ToString("isX3MaMidUnderSlow", isX3MaMidUnderSlow, ignoreFalseConditions, separator) + + ToString("isX3MaBullishState", isX3MaBullishState, ignoreFalseConditions, separator) + + ToString("isX3MaBearishState", isX3MaBearishState, ignoreFalseConditions, separator) + + ToString("isX3MaNeuturalState", isX3MaNeuturalState, ignoreFalseConditions, separator) + + ToString("isX3MaBullishOrdered", isX3MaBullishOrdered, ignoreFalseConditions, separator) + + ToString("isX3MaBearishOrdered", isX3MaBearishOrdered, ignoreFalseConditions, separator) + + ToString("isX3MaSwitchedToBullishOrdered", isX3MaSwitchedToBullishOrdered, ignoreFalseConditions, separator) + + ToString("isX3MaSwitchedToBearishOrdered", isX3MaSwitchedToBearishOrdered, ignoreFalseConditions, separator) + + ToString("isX3MaSwitchedToBullishState", isX3MaSwitchedToBullishState, ignoreFalseConditions, separator) + + ToString("isX3MaSwitchedToBearishState", isX3MaSwitchedToBearishState, ignoreFalseConditions, separator) + + ToString("isX3MaSwitchedToNeuturalState", isX3MaSwitchedToNeuturalState, ignoreFalseConditions, separator) + + // + "" + // + ; + + // + // XVWAP ... + + // + string vwapConditionsStr = + // + "-----------------------" + separator + + "XVWAP: " + separator + + "-----------------------" + separator + + ToString("isVWapFastBullish", isVWapFastBullish, ignoreFalseConditions, separator) + + ToString("isVWapFastBearish", isVWapFastBearish, ignoreFalseConditions, separator) + + ToString("isVWapFastNeutural", isVWapFastNeutural, ignoreFalseConditions, separator) + + ToString("isVWapMidBullish", isVWapMidBullish, ignoreFalseConditions, separator) + + ToString("isVWapMidBearish", isVWapMidBearish, ignoreFalseConditions, separator) + + ToString("isVWapMidNeutural", isVWapMidNeutural, ignoreFalseConditions, separator) + + ToString("isVWapSlowBullish", isVWapSlowBullish, ignoreFalseConditions, separator) + + ToString("isVWapSlowBearish", isVWapSlowBearish, ignoreFalseConditions, separator) + + ToString("isVWapSlowNeutural", isVWapSlowNeutural, ignoreFalseConditions, separator) + + ToString("isVWapFastOverMid", isVWapFastOverMid, ignoreFalseConditions, separator) + + ToString("isVWapMidOverSlow", isVWapMidOverSlow, ignoreFalseConditions, separator) + + ToString("isVWapFastUnderMid", isVWapFastUnderMid, ignoreFalseConditions, separator) + + ToString("isVWapMidUnderSlow", isVWapMidUnderSlow, ignoreFalseConditions, separator) + + ToString("isVWapBullishState", isVWapBullishState, ignoreFalseConditions, separator) + + ToString("isVWapBearishState", isVWapBearishState, ignoreFalseConditions, separator) + + ToString("isVWapNeuturalState", isVWapNeuturalState, ignoreFalseConditions, separator) + + ToString("isVWapBullishOrdered", isVWapBullishOrdered, ignoreFalseConditions, separator) + + ToString("isVWapBearishOrdered", isVWapBearishOrdered, ignoreFalseConditions, separator) + + ToString("isVWapSwitchedToBullishOrdered", isVWapSwitchedToBullishOrdered, ignoreFalseConditions, separator) + + ToString("isVWapSwitchedToBearishOrdered", isVWapSwitchedToBearishOrdered, ignoreFalseConditions, separator) + + ToString("isVWapSwitchedToBullishState", isVWapSwitchedToBullishState, ignoreFalseConditions, separator) + + ToString("isVWapSwitchedToBearishState", isVWapSwitchedToBearishState, ignoreFalseConditions, separator) + + ToString("isVWapSwitchedToNeuturalState", isVWapSwitchedToNeuturalState, ignoreFalseConditions, separator) + + // + "" + // + ; + + // + string conditionsStr = + // + pvConditionsStr + separator + + hkConditionsStr + separator + + atrConditionsStr + separator + + strConditionsStr + separator + + cheConditionsStr + separator + + x3maonditionsStr + separator + + vwapConditionsStr + separator + + "" + // + ; + + // + result = + // + "[" + GetTag() + "]" + separator + + (onlyConditions + ? "" + : commonStr) + + (!includeScores + ? "" + : scoresStr) + + " " + separator + + (onlyCommons + ? "" + : conditionsStr) + + "" + // + ; + + // + return result; + } + + /** + * Retrieve nique Tag Identifier ... + * + * @return ( string ) + */ + string GetTag() + { + return GetTypeName(this); + } + + // +}; + +// +// Implementation ... +class XCX121Helper : public XCBase +{ + // + public: + // + + // + // Helpers ... + XCX121XCCHelper *xccHelper; + XCX121XPVHelper *xpvHelper; + XCX121XHKHelper *xhkHelper; + XCX121XMASHelper *xmasHelper; + XCX121XATRHelper *xatrHelper; + XCX121XSTRHelper *xstrHelper; + XCX121XCHEHelper *xcheHelper; + XCX121X3MAHelper *x3maHelper; + XCX121XVWAPHelper *xvwapHelper; + + // + // Constructors ... + XCX121Helper() + { + } + + // + // Deconstructor ... + ~XCX121Helper() + { + // + mInputs.Clean(); + xccInputs.Clean(); + xpvInputs.Clean(); + xhkInputs.Clean(); + xmasInputs.Clean(); + xatrInputs.Clean(); + xstrInputs.Clean(); + xcheInputs.Clean(); + x3maInputs.Clean(); + xvwapInputs.Clean(); + + // + delete xccHelper; + delete xpvHelper; + delete xhkHelper; + delete xmasHelper; + delete xatrHelper; + delete xstrHelper; + delete xcheHelper; + delete x3maHelper; + delete xvwapHelper; + + // + ZeroMemory(xccHelper); + ZeroMemory(xpvHelper); + ZeroMemory(xhkHelper); + ZeroMemory(xmasHelper); + ZeroMemory(xatrHelper); + ZeroMemory(xstrHelper); + ZeroMemory(xcheHelper); + ZeroMemory(x3maHelper); + ZeroMemory(xvwapHelper); + } + + // + string GetSymbol() + { + return mSymbol; + } + + // + ENUM_TIMEFRAMES GetPeriod() + { + return mPeriod; + } + + // + // Tools ... + + /** + * Initialize Indicator Helper ... + * + * @param symbol: String, Symbol ... + * @param period: ENUM_TIMEFRAMES member, Period ... + * @param inputs: X121Inputs instance, Indicator Inputs ... + * + * @return ( bool ) + */ + bool Init( + string symbol, // Trading Symbol + ENUM_TIMEFRAMES period, // Trading Period + X121Inputs &inputs // Inputs + ) + { + // + bool result = false; + + // + result = + IsValid(symbol) && + IsValid(period) && + inputs.IsValid(); + if (!result) + { + return result; + } + + // + mSymbol = symbol; + mPeriod = period; + + // + // Setting Inputs ... + + // + mInputs = inputs; + xccInputs = inputs.xccInputs; + xpvInputs = inputs.xpvInputs; + xhkInputs = inputs.xhkInputs; + xmasInputs = inputs.xmasInputs; + xatrInputs = inputs.xatrInputs; + xstrInputs = inputs.xstrInputs; + xcheInputs = inputs.xcheInputs; + x3maInputs = inputs.x3maInputs; + xvwapInputs = inputs.xvwapInputs; + + // + // Initial Helpers ... + + // + // XCC ... + xccHelper = new XCX121XCCHelper(); + result = + result && + xccHelper.Init( + symbol, + period, + xccInputs // + ); + + // + // XPV ... + xpvHelper = new XCX121XPVHelper(); + result = + result && + xpvHelper.Init( + symbol, + period, + xpvInputs // + ); + + // + // XHK ... + xhkHelper = new XCX121XHKHelper(); + result = + result && + xhkHelper.Init( + symbol, + period, + xhkInputs // + ); + if (!result) + { + // + ZeroMemory(xccHelper); + ZeroMemory(xpvHelper); + ZeroMemory(xhkHelper); + ZeroMemory(xmasHelper); + ZeroMemory(xatrHelper); + ZeroMemory(xstrHelper); + ZeroMemory(xcheHelper); + ZeroMemory(x3maHelper); + ZeroMemory(xvwapHelper); + + // + // ZeroMemory(xichHelper); + // ZeroMemory(xdonHelper); + // ZeroMemory(xdeltaHelper); + // ZeroMemory(xvolumeHelper); + + // + return result; + } + + // + // XMAS ... + xmasHelper = new XCX121XMASHelper(); + result = + result && + xmasHelper.Init( + symbol, + period, + xmasInputs // + ); + + // + // XATR ... + xatrHelper = new XCX121XATRHelper(); + result = + result && + xatrHelper.Init( + symbol, + period, + xatrInputs // + ); + + // + // XSTR ... + xstrHelper = new XCX121XSTRHelper(); + result = + result && + xstrHelper.Init( + symbol, + period, + xstrInputs // + ); + + // + // XCHE ... + xcheHelper = new XCX121XCHEHelper(); + result = + result && + xcheHelper.Init( + symbol, + period, + xcheInputs // + ); + + // + // X3MA ... + x3maHelper = new XCX121X3MAHelper(); + result = + result && + x3maHelper.Init( + symbol, + period, + x3maInputs // + ); + + // + // XVWAP ... + xvwapHelper = new XCX121XVWAPHelper(); + result = + result && + xvwapHelper.Init( + symbol, + period, + xvwapInputs // + ); + + // + // Show RSI ... + if (inputs.showRSI) + { + // + ENUM_APPLIED_PRICE rsiAppliedTo = ToAppliedPrice(xatrInputs.rsiPriceType); + mRSIHandler = iRSI( + symbol, + period, + xatrInputs.rsiLength, + rsiAppliedTo // + ); + + // + result = + result && + mRSIHandler != INVALID_HANDLE; + } + + // + // If Result is False, Cleanup Resources ... + if (!result) + { + // + mInputs.Clean(); + + // + xccInputs.Clean(); + xpvInputs.Clean(); + xhkInputs.Clean(); + xmasInputs.Clean(); + xatrInputs.Clean(); + xstrInputs.Clean(); + xcheInputs.Clean(); + x3maInputs.Clean(); + xvwapInputs.Clean(); + + // + ZeroMemory(xccHelper); + ZeroMemory(xpvHelper); + ZeroMemory(xhkHelper); + ZeroMemory(xmasHelper); + ZeroMemory(xatrHelper); + ZeroMemory(xstrHelper); + ZeroMemory(xcheHelper); + ZeroMemory(x3maHelper); + ZeroMemory(xvwapHelper); + + // + return result; + } + + // + return result; + } + + // + // Conditions Readers ... + + // + // XPV ... + bool GetPVConditions( + X121XPVConditions &conditions, // + int barIndex = 0, // + int loopback = 5 // + ) + { + // + bool result = false; + + // + result = xpvHelper.GetConditions( + conditions, + barIndex, + loopback // + ); + + // + return result; + } + + // + // XHK ... + bool GetHKConditions( + X121XHKConditions &conditions, // + int barIndex = 0, // + int loopback = 5 // + ) + { + // + bool result = false; + + // + result = xhkHelper.GetConditions( + conditions, + barIndex, + loopback // + ); + + // + return result; + } + + // + // XMAS ... + bool GetMASConditions( + X121XMASConditions &conditions, // + int barIndex = 0, // + int loopback = 5 // + ) + { + // + bool result = false; + + // + result = xmasHelper.GetConditions( + conditions, + barIndex, + loopback // + ); + + // + return result; + } + + // + // XATR ... + bool GetATRConditions( + X121XATRConditions &conditions, // + int barIndex = 0, // + int loopback = 5 // + ) + { + // + bool result = false; + + // + result = xatrHelper.GetConditions( + conditions, + barIndex, + loopback // + ); + + // + return result; + } + + // + // XSTR ... + bool GetSTRConditions( + X121XSTRConditions &conditions, // + int barIndex = 0, // + int loopback = 5 // + ) + { + // + bool result = false; + + // + result = xstrHelper.GetConditions( + conditions, + barIndex, + loopback // + ); + + // + return result; + } + + // + // XCHE ... + bool GetCHEConditions( + X121XCHEConditions &conditions, // + int barIndex = 0, // + int loopback = 5 // + ) + { + // + bool result = false; + + // + result = xcheHelper.GetConditions( + conditions, + barIndex, + loopback // + ); + + // + return result; + } + + // + // X3MA ... + bool Get3MAConditions( + X121X3MAConditions &conditions, // + int barIndex = 0, // + int loopback = 5 // + ) + { + // + bool result = false; + + // + result = x3maHelper.GetConditions( + conditions, + barIndex, + loopback // + ); + + // + return result; + } + + // + // XVWAP ... + bool GetVWAPConditions( + X121XVWAPConditions &conditions, // + int barIndex = 0, // + int loopback = 5 // + ) + { + // + bool result = false; + + // + result = xvwapHelper.GetConditions( + conditions, + barIndex, + loopback // + ); + + // + return result; + } + + // + void Free() + { + // + xpvHelper.Free(); + xhkHelper.Free(); + xmasHelper.Free(); + xatrHelper.Free(); + xstrHelper.Free(); + xcheHelper.Free(); + xvwapHelper.Free(); + + // + // xichHelper.Free(); + // xdonHelper.Free(); + // xdeltaHelper.Free(); + // xvolumeHelper.Free(); + } + + // + bool GetConditions( + X121Conditions &conditions, // + int barIndex = 0, // + int loopback = 5 // + ) + { + // + bool result = true; + + // + if (loopback < 5) + { + loopback = 5; + } + + // + conditions.Clean(); + + // + conditions.symbol = mSymbol; + conditions.period = mPeriod; + conditions.time = TimeCurrent(); + + // + int zIndex = barIndex; + int cIndex = zIndex + 1; + int pIndex = cIndex + 1; + int ppIndex = pIndex + 1; + + // + XOHCL zBar; + XOHCL cBar; + XOHCL pBar; + + // + X121XPVConditions xpvConditions; + X121XHKConditions xhkConditions; + X121XMASConditions xmasConditions; + X121XATRConditions xatrConditions; + X121XSTRConditions xstrConditions; + X121XCHEConditions xcheConditions; + X121X3MAConditions x3maConditions; + X121XVWAPConditions xvwapConditions; + + // + result = zBar.Init( + mSymbol, + mPeriod, + zIndex // + ); + result = + result && + zBar.GetPreviousBar(cBar); + result = + result && + cBar.GetPreviousBar(pBar); + + // + // Conditions Retriever ... + + // + // XPV ... + result = + result && + GetPVConditions( + xpvConditions, + barIndex, + loopback // + ); + + // + // XHK ... + result = + result && + GetHKConditions( + xhkConditions, + barIndex, + loopback // + ); + + // + // XMAS ... + result = + result && + GetMASConditions( + xmasConditions, + barIndex, + loopback // + ); + + // + // XATR ... + result = + result && + GetATRConditions( + xatrConditions, + barIndex, + loopback // + ); + + // + // XSTR ... + result = + result && + GetSTRConditions( + xstrConditions, + barIndex, + loopback // + ); + + // + // XCHE ... + result = + result && + GetCHEConditions( + xcheConditions, + barIndex, + loopback // + ); + + // + // X3MA ... + result = + result && + Get3MAConditions( + x3maConditions, + barIndex, + loopback // + ); + + // + // XVWAP ... + result = + result && + GetVWAPConditions( + xvwapConditions, + barIndex, + loopback // + ); + + // + // Check Result ... + if (!result) + { + // + zBar.Clean(); + cBar.Clean(); + pBar.Clean(); + + // + xpvConditions.Clean(); + xhkConditions.Clean(); + xmasConditions.Clean(); + xatrConditions.Clean(); + xstrConditions.Clean(); + xcheConditions.Clean(); + x3maConditions.Clean(); + xvwapConditions.Clean(); + + // + return result; + } + + // + // Fill X121 Conditions Reference by Using + // Retrieved Conditions ... + + // + int cIDX = 1; + int pIDX = cIDX + 1; + + // + // Conditions ... + + // + // XCC ... + + // + // Buffers ... + + // + // Conditions ... + + // + // XPV ... + + // + // Buffers ... + + // + Copy( + xpvConditions.sarBuffer, + conditions.sarBuffer // + ); + + // + Copy( + xpvConditions.cHHBuffer, + conditions.cHHBuffer // + ); + + // + Copy( + xpvConditions.cLLBuffer, + conditions.cLLBuffer // + ); + + // + Copy( + xpvConditions.sHHBuffer, + conditions.sHHBuffer // + ); + + // + Copy( + xpvConditions.sLLBuffer, + conditions.sLLBuffer // + ); + + // + Copy( + xpvConditions.mHHBuffer, + conditions.mHHBuffer // + ); + + // + Copy( + xpvConditions.mLLBuffer, + conditions.mLLBuffer // + ); + + // + Copy( + xpvConditions.lHHBuffer, + conditions.lHHBuffer // + ); + + // + Copy( + xpvConditions.lLLBuffer, + conditions.lLLBuffer // + ); + + // + Copy( + xpvConditions.hHHBuffer, + conditions.hHHBuffer // + ); + + // + Copy( + xpvConditions.hLLBuffer, + conditions.hLLBuffer // + ); + + // + Copy( + xpvConditions.peaksBuffer, + conditions.peaksBuffer // + ); + + // + Copy( + xpvConditions.valesBuffer, + conditions.valesBuffer // + ); + + // + Copy( + xpvConditions.supportsBuffer, + conditions.supportsBuffer // + ); + + // + Copy( + xpvConditions.peaksGoldenBuffer, + conditions.peaksGoldenBuffer // + ); + + // + Copy( + xpvConditions.valesGoldenBuffer, + conditions.valesGoldenBuffer // + ); + + // + Copy( + xpvConditions.resistancesBuffer, + conditions.resistancesBuffer // + ); + + // + Copy( + xpvConditions.fractalsUpperBuffer, + conditions.fractalsUpperBuffer // + ); + + // + Copy( + xpvConditions.fractalsLowerBuffer, + conditions.fractalsLowerBuffer // + ); + + // + // Conditions ... + + // + conditions.isNewPeak = xpvConditions.isNewPeak; + conditions.isNewVale = xpvConditions.isNewVale; + conditions.isSarBullish = xpvConditions.isSarBullish; + conditions.isSarBearish = xpvConditions.isSarBearish; + conditions.isNewPeakOverLast = xpvConditions.isNewPeakOverLast; + conditions.isNewValeOverLast = xpvConditions.isNewValeOverLast; + conditions.isNewPeakUnderLast = xpvConditions.isNewPeakUnderLast; + conditions.isNewValeUnderLast = xpvConditions.isNewValeUnderLast; + conditions.isSarSwitchedToBullish = xpvConditions.isSarSwitchedToBullish; + conditions.isSarSwitchedToBearish = xpvConditions.isSarSwitchedToBearish; + + // + // XHK ... + + // + // Buffers ... + + // + Copy( + xhkConditions.xhkSMLowBuffer, + conditions.xhkSMLowBuffer // + ); + + // + Copy( + xhkConditions.xhkRawLowBuffer, + conditions.xhkRawLowBuffer // + ); + + // + Copy( + xhkConditions.xhkSMOpenBuffer, + conditions.xhkSMOpenBuffer // + ); + + // + Copy( + xhkConditions.xhkSMHighBuffer, + conditions.xhkSMHighBuffer // + ); + + // + Copy( + xhkConditions.xhkRawOpenBuffer, + conditions.xhkRawOpenBuffer // + ); + + // + Copy( + xhkConditions.xhkRawHighBuffer, + conditions.xhkRawHighBuffer // + ); + + // + Copy( + xhkConditions.xhkSMCloseBuffer, + conditions.xhkSMCloseBuffer // + ); + + // + Copy( + xhkConditions.xhkRawCloseBuffer, + conditions.xhkRawCloseBuffer // + ); + + // + // Conditions ... + + // + conditions.isSMHKBullish = xhkConditions.isSMHKBullish; + conditions.isSMHKBearish = xhkConditions.isSMHKBearish; + conditions.isRawHKBullish = xhkConditions.isRawHKBullish; + conditions.isRawHKBearish = xhkConditions.isRawHKBearish; + conditions.isClosedOverSMHK = xhkConditions.isClosedOverSMHK; + conditions.isClosedUnderSMHK = xhkConditions.isClosedUnderSMHK; + conditions.isClosedOverRawHK = xhkConditions.isClosedOverRawHK; + conditions.isClosedUnderRawHK = xhkConditions.isClosedUnderRawHK; + conditions.isRawHKClosedOverSMHK = xhkConditions.isRawHKClosedOverSMHK; + conditions.isRawHKClosedUnderSMHK = xhkConditions.isRawHKClosedUnderSMHK; + conditions.isSMHKSwitchedToBearish = xhkConditions.isSMHKSwitchedToBearish; + conditions.isSMHKSwitchedToBullish = xhkConditions.isSMHKSwitchedToBullish; + conditions.isRawHKSwitchedToBullish = xhkConditions.isRawHKSwitchedToBullish; + conditions.isRawHKSwitchedToBearish = xhkConditions.isRawHKSwitchedToBearish; + + // + // XMAS ... + + // + // Buffers ... + + // + Copy( + xmasConditions.midBuffer, + conditions.midBuffer // + ); + + // + Copy( + xmasConditions.upperBuffer, + conditions.upperBuffer // + ); + + // + Copy( + xmasConditions.lowerBuffer, + conditions.lowerBuffer // + ); + + // + // Conditions ... + + // + // XATR ... + + // + // Buffers ... + + // + Copy( + xatrConditions.rsiBuffer, + conditions.rsiBuffer // + ); + + // + Copy( + xatrConditions.atrBuffer, + conditions.atrBuffer // + ); + + // + Copy( + xatrConditions.atrUpperBuffer, + conditions.atrUpperBuffer // + ); + + // + Copy( + xatrConditions.atrLowerBuffer, + conditions.atrLowerBuffer // + ); + + // + Copy( + xatrConditions.rsiChangeBuffer, + conditions.rsiChangeBuffer // + ); + + // + Copy( + xatrConditions.atrUpperSMBuffer, + conditions.atrUpperSMBuffer // + ); + + // + Copy( + xatrConditions.atrLowerSMBuffer, + conditions.atrLowerSMBuffer // + ); + + // + Copy( + xatrConditions.rsiChangeSMBuffer, + conditions.rsiChangeSMBuffer // + ); + + // + Copy( + xatrConditions.priceChangeBuffer, + conditions.priceChangeBuffer // + ); + + // + Copy( + xatrConditions.priceChangeSMBuffer, + conditions.priceChangeSMBuffer // + ); + + // + // Conditions ... + + // + conditions.isRsiInRange = xatrConditions.isRsiInRange; + conditions.isRsiOverSold = xatrConditions.isRsiOverSold; + conditions.isRsiOverRsiSM = xatrConditions.isRsiOverRsiSM; + conditions.isRsiUnderRsiSM = xatrConditions.isRsiUnderRsiSM; + conditions.isRsiOverBought = xatrConditions.isRsiOverBought; + conditions.isRsiCrossedOverRsiSM = xatrConditions.isRsiCrossedOverRsiSM; + conditions.isRsiCrossedUnderRsiSM = xatrConditions.isRsiCrossedUnderRsiSM; + conditions.isPriceChangeSMOverRsi = xatrConditions.isPriceChangeSMOverRsi; + conditions.isRsiSMOverPriceChange = xatrConditions.isRsiSMOverPriceChange; + conditions.isRsiSMUnderPriceChange = xatrConditions.isRsiSMUnderPriceChange; + conditions.isPriceChangeSMUnderRsi = xatrConditions.isPriceChangeSMUnderRsi; + conditions.isRsiCrossedOverOverSold = xatrConditions.isRsiCrossedOverOverSold; + conditions.isRsiCrossedUnderOverSold = xatrConditions.isRsiCrossedUnderOverSold; + conditions.isRsiCrossedOverOverBought = xatrConditions.isRsiCrossedOverOverBought; + conditions.isRsiCrossedUnderOverBought = xatrConditions.isRsiCrossedUnderOverBought; + conditions.isRsiSMCrossedOverPriceChange = xatrConditions.isRsiSMCrossedOverPriceChange; + conditions.isPriceChangeSMCrossedOverRsi = xatrConditions.isPriceChangeSMCrossedOverRsi; + conditions.isRsiSMCrossedUnderPriceChange = xatrConditions.isRsiSMCrossedUnderPriceChange; + conditions.isPriceChangeSMCrossedUnderRsi = xatrConditions.isPriceChangeSMCrossedUnderRsi; + conditions.isPriceChangeOverPriceChangeSM = xatrConditions.isPriceChangeOverPriceChangeSM; + conditions.isPriceChangeUnderPriceChangeSM = xatrConditions.isPriceChangeUnderPriceChangeSM; + conditions.isPriceChangeCrossedOverPriceChangeSM = xatrConditions.isPriceChangeCrossedOverPriceChangeSM; + conditions.isPriceChangeCrossedUnderPriceChangeSM = xatrConditions.isPriceChangeCrossedUnderPriceChangeSM; + + // + // XSTR ... + + // + // Buffers ... + + // + Copy( + xstrConditions.vidyaBuffer, + conditions.vidyaBuffer // + ); + + // + Copy( + xstrConditions.strBuffer, + conditions.strBuffer // + ); + + // + Copy( + xstrConditions.strUpBuffer, + conditions.strUpBuffer // + ); + + // + Copy( + xstrConditions.strDownBuffer, + conditions.strDownBuffer // + ); + + // + Copy( + xstrConditions.strPriceBuffer, + conditions.strPriceBuffer // + ); + + // + Copy( + xstrConditions.strStateBuffer, + conditions.strStateBuffer // + ); + + // + Copy( + xstrConditions.strSMLowBuffer, + conditions.strSMLowBuffer // + ); + + // + Copy( + xstrConditions.strSMHighBuffer, + conditions.strSMHighBuffer // + ); + + // + // Conditions ... + + // + conditions.isStrBullish = xstrConditions.isStrBullish; + conditions.isStrBearish = xstrConditions.isStrBearish; + conditions.isStrSwitchedToBullish = xstrConditions.isStrSwitchedToBullish; + conditions.isStrSwitchedToBearish = xstrConditions.isStrSwitchedToBearish; + + // + // XCHE ... + + // + // Buffers ... + + // + Copy( + xcheConditions.le1Buffer, + conditions.le1Buffer // + ); + + // + Copy( + xcheConditions.se1Buffer, + conditions.se1Buffer // + ); + + // + Copy( + xcheConditions.le2Buffer, + conditions.le2Buffer // + ); + + // + Copy( + xcheConditions.se2Buffer, + conditions.se2Buffer // + ); + + // + Copy( + xcheConditions.le1StartBuffer, + conditions.le1StartBuffer // + ); + + // + Copy( + xcheConditions.se1StartBuffer, + conditions.se1StartBuffer // + ); + + // + Copy( + xcheConditions.le2StartBuffer, + conditions.le2StartBuffer // + ); + + // + Copy( + xcheConditions.se2StartBuffer, + conditions.se2StartBuffer // + ); + + // + // Conditions ... + + // + conditions.isCheBullish = xcheConditions.isCheBullish; + conditions.isCheBearish = xcheConditions.isCheBearish; + conditions.isChe1Bullish = xcheConditions.isChe1Bullish; + conditions.isChe1Bearish = xcheConditions.isChe1Bearish; + conditions.isChe2Bullish = xcheConditions.isChe2Bullish; + conditions.isChe2Bearish = xcheConditions.isChe2Bearish; + conditions.isCheSwitchedToBullish = xcheConditions.isCheSwitchedToBullish; + conditions.isCheSwitchedToBearish = xcheConditions.isCheSwitchedToBearish; + conditions.isChe1SwitchedToBullish = xcheConditions.isChe1SwitchedToBullish; + conditions.isChe1SwitchedToBearish = xcheConditions.isChe1SwitchedToBearish; + conditions.isChe2SwitchedToBullish = xcheConditions.isChe2SwitchedToBullish; + conditions.isChe2SwitchedToBearish = xcheConditions.isChe2SwitchedToBearish; + + // + // X3MA ... + + // + // Buffers ... + + // + Copy( + x3maConditions.x3maMidBuffer, + conditions.x3maMidBuffer // + ); + + // + Copy( + x3maConditions.x3maFastBuffer, + conditions.x3maFastBuffer // + ); + + // + Copy( + x3maConditions.x3maSlowBuffer, + conditions.x3maSlowBuffer // + ); + + // + Copy( + x3maConditions.x3maMidStateBuffer, + conditions.x3maMidStateBuffer // + ); + + // + Copy( + x3maConditions.x3maFastStateBuffer, + conditions.x3maFastStateBuffer // + ); + + // + Copy( + x3maConditions.x3maSlowStateBuffer, + conditions.x3maSlowStateBuffer // + ); + + // + // Conditions ... + + // + conditions.isX3MaMidBullish = x3maConditions.isX3MaMidBullish; + conditions.isX3MaMidBearish = x3maConditions.isX3MaMidBearish; + conditions.isX3MaFastBullish = x3maConditions.isX3MaFastBullish; + conditions.isX3MaFastBearish = x3maConditions.isX3MaFastBearish; + conditions.isX3MaMidNeutural = x3maConditions.isX3MaMidNeutural; + conditions.isX3MaSlowBullish = x3maConditions.isX3MaSlowBullish; + conditions.isX3MaSlowBearish = x3maConditions.isX3MaSlowBearish; + conditions.isX3MaFastOverMid = x3maConditions.isX3MaFastOverMid; + conditions.isX3MaMidOverSlow = x3maConditions.isX3MaMidOverSlow; + conditions.isX3MaFastNeutural = x3maConditions.isX3MaFastNeutural; + conditions.isX3MaSlowNeutural = x3maConditions.isX3MaSlowNeutural; + conditions.isX3MaFastUnderMid = x3maConditions.isX3MaFastUnderMid; + conditions.isX3MaMidUnderSlow = x3maConditions.isX3MaMidUnderSlow; + conditions.isX3MaBullishState = x3maConditions.isX3MaBullishState; + conditions.isX3MaBearishState = x3maConditions.isX3MaBearishState; + conditions.isX3MaNeuturalState = x3maConditions.isX3MaNeuturalState; + conditions.isX3MaBullishOrdered = x3maConditions.isX3MaBullishOrdered; + conditions.isX3MaBearishOrdered = x3maConditions.isX3MaBearishOrdered; + conditions.isX3MaSwitchedToBullishState = x3maConditions.isX3MaSwitchedToBullishState; + conditions.isX3MaSwitchedToBearishState = x3maConditions.isX3MaSwitchedToBearishState; + conditions.isX3MaSwitchedToNeuturalState = x3maConditions.isX3MaSwitchedToNeuturalState; + conditions.isX3MaSwitchedToBullishOrdered = x3maConditions.isX3MaSwitchedToBullishOrdered; + conditions.isX3MaSwitchedToBearishOrdered = x3maConditions.isX3MaSwitchedToBearishOrdered; + + // + // XVWAP ... + + // + // Buffers ... + + // + Copy( + xvwapConditions.vwapMidBuffer, + conditions.vwapMidBuffer // + ); + + // + Copy( + xvwapConditions.vwapFastBuffer, + conditions.vwapFastBuffer // + ); + + // + Copy( + xvwapConditions.vwapSlowBuffer, + conditions.vwapSlowBuffer // + ); + + // + Copy( + xvwapConditions.vwapPriceBuffer, + conditions.vwapPriceBuffer // + ); + + // + Copy( + xvwapConditions.vwapVolumeBuffer, + conditions.vwapVolumeBuffer // + ); + + // + Copy( + xvwapConditions.vwapMidStateBuffer, + conditions.vwapMidStateBuffer // + ); + + // + Copy( + xvwapConditions.vwapFastStateBuffer, + conditions.vwapFastStateBuffer // + ); + + // + Copy( + xvwapConditions.vwapSlowStateBuffer, + conditions.vwapSlowStateBuffer // + ); + + // + // Conditions ... + + // + conditions.isVWapMidBullish = xvwapConditions.isVWapMidBullish; + conditions.isVWapMidBearish = xvwapConditions.isVWapMidBearish; + conditions.isVWapMidNeutural = xvwapConditions.isVWapMidNeutural; + conditions.isVWapFastBullish = xvwapConditions.isVWapFastBullish; + conditions.isVWapFastBearish = xvwapConditions.isVWapFastBearish; + conditions.isVWapSlowBullish = xvwapConditions.isVWapSlowBullish; + conditions.isVWapSlowBearish = xvwapConditions.isVWapSlowBearish; + conditions.isVWapFastOverMid = xvwapConditions.isVWapFastOverMid; + conditions.isVWapMidOverSlow = xvwapConditions.isVWapMidOverSlow; + conditions.isVWapFastNeutural = xvwapConditions.isVWapFastNeutural; + conditions.isVWapSlowNeutural = xvwapConditions.isVWapSlowNeutural; + conditions.isVWapFastUnderMid = xvwapConditions.isVWapFastUnderMid; + conditions.isVWapMidUnderSlow = xvwapConditions.isVWapMidUnderSlow; + conditions.isVWapBullishState = xvwapConditions.isVWapBullishState; + conditions.isVWapBearishState = xvwapConditions.isVWapBearishState; + conditions.isVWapNeuturalState = xvwapConditions.isVWapNeuturalState; + conditions.isVWapBullishOrdered = xvwapConditions.isVWapBullishOrdered; + conditions.isVWapBearishOrdered = xvwapConditions.isVWapBearishOrdered; + conditions.isVWapSwitchedToBullishState = xvwapConditions.isVWapSwitchedToBullishState; + conditions.isVWapSwitchedToBearishState = xvwapConditions.isVWapSwitchedToBearishState; + conditions.isVWapSwitchedToNeuturalState = xvwapConditions.isVWapSwitchedToNeuturalState; + conditions.isVWapSwitchedToBullishOrdered = xvwapConditions.isVWapSwitchedToBullishOrdered; + conditions.isVWapSwitchedToBearishOrdered = xvwapConditions.isVWapSwitchedToBearishOrdered; + + // + // Cleanup Resource ... + + // + zBar.Clean(); + cBar.Clean(); + pBar.Clean(); + + // + xpvConditions.Clean(); + xhkConditions.Clean(); + xmasConditions.Clean(); + xatrConditions.Clean(); + xstrConditions.Clean(); + xcheConditions.Clean(); + x3maConditions.Clean(); + xvwapConditions.Clean(); + + // + Free(); + + // + return result; + } + + // + protected: + // + + // + private: + // + + // + string mSymbol; // Trading Symbol + ENUM_TIMEFRAMES mPeriod; // Trading Period + + // + // Inputs ... + X121Inputs mInputs; + X121XCCInputs xccInputs; + X121XPVInputs xpvInputs; + X121XHKInputs xhkInputs; + X121XMASInputs xmasInputs; + X121XATRInputs xatrInputs; + X121XSTRInputs xstrInputs; + X121XCHEInputs xcheInputs; + X121X3MAInputs x3maInputs; + X121XVWAPInputs xvwapInputs; + + // + // X121XICHInputs xichInputs; + // X121XDONInputs xdonInputs; + // X121XDELTAInputs xdeltaInputs; + // X121XVOLUMEInputs xvolumeInputs; + + // + int mRSIHandler; +}; + +// diff --git a/BKPS/14040203/Helpers/x-saherelm.x121.x3ma.helper.mq5 b/BKPS/14040203/Helpers/x-saherelm.x121.x3ma.helper.mq5 new file mode 100644 index 0000000..2c5a269 --- /dev/null +++ b/BKPS/14040203/Helpers/x-saherelm.x121.x3ma.helper.mq5 @@ -0,0 +1,1439 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Helper Class Library +// ---------------------------------------------- +// Name: XCX121X3MAHelper +// Description: provides all Indicator +// Helper requirements ... +// +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +////////////////////////////////////////////////////// +// +// Global Properties ... +#property library +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://www.saherelm.ir" +#property version "1.00" +#property strict + +// +// Imports ... +#include "../Classes/x-saherelm.x-helper.class.mq5" + +// +// Definitions ... + +// +// Definitions ... +enum ENUM_X121_X3MA_BUFFERS +{ + // + X121_X3MA_FAST_LINE = 0, + X121_X3MA_FAST_STATE_LINE = 6, + X121_X3MA_MID_LINE = 2, + X121_X3MA_MID_STATE_LINE = 7, + X121_X3MA_SLOW_LINE = 4, + X121_X3MA_SLOW_STATE_LINE = 8, +}; + +// +enum ENUM_X3MA_STATES +{ + X3MA_STATE_BULLISH = 1, + X3MA_STATE_BEARISH = 2, + X3MA_STATE_NEUTURAL = 3, +}; + +// +// Input Models ... +struct X121X3MAInputs +{ + // + // Props ... + int x3maFastMALength; // Fast MA Length + int x3maMidMALength; // Mid MA Length + int x3maSlowMALength; // Slow MA Length + ENUM_MA_METHOD x3maMaMethod; // MA Method + ENUM_APPLIED_PRICE x3maMaAppliedTo; // Applied To + + // + int startCalculationForLastBars; // Calculate Last n Bars + + // + bool showX3MaFast; // Show X3Ma Fast + bool showX3MaMid; // Show X3Ma Medium + bool showX3MaSlow; // Show X3Ma Slow + + // + // Constructor(s) ... + X121X3MAInputs() + { + Clean(); + } + + // + // Tools ... + + // + // Clean ... + void Clean() + { + // + x3maFastMALength = 0; + x3maMidMALength = 0; + x3maSlowMALength = 0; + x3maMaMethod = MODE_EMA; + x3maMaAppliedTo = PRICE_CLOSE; + startCalculationForLastBars = 0; + showX3MaFast = false; + showX3MaMid = false; + showX3MaSlow = false; + + // + ZeroMemory(this); + } + + // + // Default ... + void Default() + { + // + x3maFastMALength = 20; + x3maMidMALength = 50; + x3maSlowMALength = 200; + x3maMaMethod = MODE_EMA; + x3maMaAppliedTo = PRICE_CLOSE; + startCalculationForLastBars = 1000; + showX3MaFast = true; + showX3MaMid = true; + showX3MaSlow = true; + } + + // + // Validate ... + bool IsValid() + { + // + bool result = false; + + // + result = + // + x3maFastMALength > 2 && + x3maMidMALength > x3maFastMALength && + x3maSlowMALength > x3maMidMALength + // + ; + + // + return result; + } + + // + // Retrieve MAx Length ... + int Max() + { + // + int result = 0; + + // + result = MathMax(x3maFastMALength, x3maMidMALength); + result = MathMax(result, x3maSlowMALength); + + // + return result; + } +}; + +// +// Conditions ... +struct X121X3MAConditions +{ + // + // Common ... + string symbol; + ENUM_TIMEFRAMES period; + datetime time; + + // + // Buffers ... + double x3maFastBuffer[]; + double x3maMidBuffer[]; + double x3maSlowBuffer[]; + double x3maFastStateBuffer[]; + double x3maMidStateBuffer[]; + double x3maSlowStateBuffer[]; + + // + // Conditions ... + + // + bool isX3MaFastBullish; + bool isX3MaFastBearish; + bool isX3MaFastNeutural; + + // + bool isX3MaMidBullish; + bool isX3MaMidBearish; + bool isX3MaMidNeutural; + + // + bool isX3MaSlowBullish; + bool isX3MaSlowBearish; + bool isX3MaSlowNeutural; + + // + bool isX3MaFastOverMid; + bool isX3MaMidOverSlow; + + // + bool isX3MaFastUnderMid; + bool isX3MaMidUnderSlow; + + // + bool isX3MaBullishState; + bool isX3MaBearishState; + bool isX3MaNeuturalState; + + // + bool isX3MaBullishOrdered; + bool isX3MaBearishOrdered; + + // + bool isX3MaSwitchedToBullishOrdered; + bool isX3MaSwitchedToBearishOrdered; + + // + bool isX3MaSwitchedToBullishState; + bool isX3MaSwitchedToBearishState; + bool isX3MaSwitchedToNeuturalState; + + // + // Constructor ... + X121X3MAConditions() + { + Clean(); + } + + // + // Tools ... + + /** + * Cleaning Up ... + */ + void Clean() + { + // + // Commons ... + symbol = NULL; + period = NULL; + time = NULL; + + // + // Buffers ... + + // + Clean(x3maFastBuffer); + Clean(x3maMidBuffer); + Clean(x3maSlowBuffer); + Clean(x3maFastStateBuffer); + Clean(x3maMidStateBuffer); + Clean(x3maSlowStateBuffer); + + // + ArraySetAsSeries(x3maFastBuffer, true); + ArraySetAsSeries(x3maMidBuffer, true); + ArraySetAsSeries(x3maSlowBuffer, true); + ArraySetAsSeries(x3maFastStateBuffer, true); + ArraySetAsSeries(x3maMidStateBuffer, true); + ArraySetAsSeries(x3maSlowStateBuffer, true); + + // + // Conditions ... + + // + isX3MaFastBullish = false; + isX3MaFastBearish = false; + isX3MaFastNeutural = false; + + // + isX3MaMidBullish = false; + isX3MaMidBearish = false; + isX3MaMidNeutural = false; + + // + isX3MaSlowBullish = false; + isX3MaSlowBearish = false; + isX3MaSlowNeutural = false; + + // + isX3MaFastOverMid = false; + isX3MaMidOverSlow = false; + + // + isX3MaFastUnderMid = false; + isX3MaMidUnderSlow = false; + + // + isX3MaBullishState = false; + isX3MaBearishState = false; + isX3MaNeuturalState = false; + + // + isX3MaBullishOrdered = false; + isX3MaBearishOrdered = false; + + // + isX3MaSwitchedToBullishOrdered = false; + isX3MaSwitchedToBearishOrdered = false; + + // + isX3MaSwitchedToBullishState = false; + isX3MaSwitchedToBearishState = false; + isX3MaSwitchedToNeuturalState = false; + + // + ZeroMemory(this); + } + + /** + * Generate Conditions Scores ... + * + * @param bullishScore: Double, Directional Scores Reference ... + * @param bearishScore: Double, Directional Scores Reference ... + */ + void GenerateScore( + double &bullishScore, + double &bearishScore // + ) + { + // + bullishScore = 0; + bearishScore = 0; + + // + double score = 1; + double minScore = 0.5; + double highScore = 1.5; + + // + // X3MA ... + + // + if (isX3MaBullishState) + { + bullishScore += score; + } + if (isX3MaBullishOrdered) + { + bullishScore += score; + } + if (isX3MaSwitchedToBullishState) + { + bullishScore += highScore; + } + if (isX3MaSwitchedToBullishOrdered) + { + bullishScore += highScore; + } + if (!isX3MaBullishState && + !isX3MaSwitchedToBullishState) + { + // + if (isX3MaFastBullish) + { + bullishScore += minScore; + } + if (isX3MaSlowBullish) + { + bullishScore += minScore; + } + } + if (!isX3MaBullishOrdered && + !isX3MaSwitchedToBullishOrdered) + { + // + if (isX3MaFastOverMid) + { + bullishScore += minScore; + } + if (isX3MaMidOverSlow) + { + bullishScore += minScore; + } + } + + // + if (isX3MaBearishState) + { + bearishScore += score; + } + if (isX3MaBearishOrdered) + { + bearishScore += score; + } + if (isX3MaSwitchedToBearishState) + { + bearishScore += highScore; + } + if (isX3MaSwitchedToBearishOrdered) + { + bearishScore += highScore; + } + if (!isX3MaBearishState && + !isX3MaSwitchedToBearishState) + { + // + if (isX3MaFastBearish) + { + bearishScore += minScore; + } + if (isX3MaSlowBearish) + { + bearishScore += minScore; + } + } + if (!isX3MaBearishOrdered && + !isX3MaSwitchedToBearishOrdered) + { + // + if (isX3MaFastUnderMid) + { + bearishScore += minScore; + } + if (isX3MaMidUnderSlow) + { + bearishScore += minScore; + } + } + } + + /** + * Generate Summary String for Represent Conditions State ... + * + * @param onlyCommons: Boolean, Just Generate Only Commons Conditions ... + * @param onlyConditions: Boolean, Just Generate Only Conditions ... + * @param includeScores: Boolean, Attach Scores Representations on Result ... + * @param ignoreFalseConditions: Boolean, Ignore False Conditions on Result ... + * @param separator: String, Separate Lines ... + * + * @return ( string ) + */ + string GenerateSummary( + bool onlyCommons = false, + bool onlyConditions = false, + bool includeScores = true, + bool ignoreFalseConditions = true, + string separator = "\n" // + ) + { + // + string result = NULL; + + // + double bullishScore = 0; + double bearishScore = 0; + GenerateScore( + bullishScore, + bearishScore // + ); + + // + string scoresStr = + // + "Scores: " + separator + + "---------------" + separator + + "Bullish: " + ToString(bullishScore) + separator + + "Bearish: " + ToString(bearishScore) + separator + + "" + // + ; + + // + string commonStr = GenerateSpecifiedCommonSummary( + this, + separator, + includeScores // + ); + + // + string conditionsStr = + // + "-----------------------" + separator + + "X3MA: " + separator + + "-----------------------" + separator + + ToString("isX3MaFastBullish", isX3MaFastBullish, ignoreFalseConditions, separator) + + ToString("isX3MaFastBearish", isX3MaFastBearish, ignoreFalseConditions, separator) + + ToString("isX3MaFastNeutural", isX3MaFastNeutural, ignoreFalseConditions, separator) + + ToString("isX3MaMidBullish", isX3MaMidBullish, ignoreFalseConditions, separator) + + ToString("isX3MaMidBearish", isX3MaMidBearish, ignoreFalseConditions, separator) + + ToString("isX3MaMidNeutural", isX3MaMidNeutural, ignoreFalseConditions, separator) + + ToString("isX3MaSlowBullish", isX3MaSlowBullish, ignoreFalseConditions, separator) + + ToString("isX3MaSlowBearish", isX3MaSlowBearish, ignoreFalseConditions, separator) + + ToString("isX3MaSlowNeutural", isX3MaSlowNeutural, ignoreFalseConditions, separator) + + ToString("isX3MaFastOverMid", isX3MaFastOverMid, ignoreFalseConditions, separator) + + ToString("isX3MaMidOverSlow", isX3MaMidOverSlow, ignoreFalseConditions, separator) + + ToString("isX3MaFastUnderMid", isX3MaFastUnderMid, ignoreFalseConditions, separator) + + ToString("isX3MaMidUnderSlow", isX3MaMidUnderSlow, ignoreFalseConditions, separator) + + ToString("isX3MaBullishState", isX3MaBullishState, ignoreFalseConditions, separator) + + ToString("isX3MaBearishState", isX3MaBearishState, ignoreFalseConditions, separator) + + ToString("isX3MaNeuturalState", isX3MaNeuturalState, ignoreFalseConditions, separator) + + ToString("isX3MaBullishOrdered", isX3MaBullishOrdered, ignoreFalseConditions, separator) + + ToString("isX3MaBearishOrdered", isX3MaBearishOrdered, ignoreFalseConditions, separator) + + ToString("isX3MaSwitchedToBullishOrdered", isX3MaSwitchedToBullishOrdered, ignoreFalseConditions, separator) + + ToString("isX3MaSwitchedToBearishOrdered", isX3MaSwitchedToBearishOrdered, ignoreFalseConditions, separator) + + ToString("isX3MaSwitchedToBullishState", isX3MaSwitchedToBullishState, ignoreFalseConditions, separator) + + ToString("isX3MaSwitchedToBearishState", isX3MaSwitchedToBearishState, ignoreFalseConditions, separator) + + ToString("isX3MaSwitchedToNeuturalState", isX3MaSwitchedToNeuturalState, ignoreFalseConditions, separator) + + // + "" + // + ; + + // + result = + // + "[" + GetTag() + "]" + separator + + (onlyConditions + ? "" + : commonStr) + + (!includeScores + ? "" + : scoresStr) + + " " + separator + + (onlyCommons + ? "" + : conditionsStr) + + "" + // + ; + + // + return result; + } + + /** + * Retrieve nique Tag Identifier ... + * + * @return ( string ) + */ + string GetTag() + { + return GetTypeName(this); + } + + // +}; + +// +// Class ... +class XCX121X3MAHelper : public XCBaseHelper +{ + // + // Public ... + public: + // + // Props ... + + // + // Constructors ... + XCX121X3MAHelper() + : XCBaseHelper(_Symbol, _Period) + { + } + + // + // Deconstructor ... + ~XCX121X3MAHelper() + { + // + mInputs.Clean(); + + // + Clean(x3maFastBuffer); + Clean(x3maMidBuffer); + Clean(x3maSlowBuffer); + Clean(x3maFastStateBuffer); + Clean(x3maMidStateBuffer); + Clean(x3maSlowStateBuffer); + } + + // + // Tools ... + bool Init( + string symbol, // Trading Symbol + ENUM_TIMEFRAMES period, // Trading Period + X121X3MAInputs &inputs // Inputs + ) + { + // + bool result = false; + + // + mSymbol = symbol; + mPeriod = period; + + // + result = inputs.IsValid(); + if (!result) + { + return result; + } + + // + ArraySetAsSeries(x3maFastBuffer, true); + ArraySetAsSeries(x3maMidBuffer, true); + ArraySetAsSeries(x3maSlowBuffer, true); + ArraySetAsSeries(x3maFastStateBuffer, true); + ArraySetAsSeries(x3maMidStateBuffer, true); + ArraySetAsSeries(x3maSlowStateBuffer, true); + + // + mInputs = inputs; + + // + mHandler = iCustom( + mSymbol, + mPeriod, + "x-saherelm.x121.x3ma", + // + // Inputs ... + // + // Market ... + "", + mInputs.x3maFastMALength, + mInputs.x3maMidMALength, + mInputs.x3maSlowMALength, + mInputs.x3maMaMethod, + mInputs.x3maMaAppliedTo, + // + // Presentation ... + "", + // + mInputs.startCalculationForLastBars, + // + mInputs.showX3MaFast, + mInputs.showX3MaMid, + mInputs.showX3MaSlow + // + ); + result = mHandler != INVALID_HANDLE; + if (!result) + { + return result; + } + + // + return result; + } + + // + // Inputs ... + + // + X121X3MAInputs GetInputs() + { + return mInputs; + } + + // + bool SetInputs( + X121X3MAInputs &inputs // Configs + ) + { + // + return Init( + mSymbol, + mPeriod, + inputs + // + ); + } + + // + // Readers ... + + // + // FAST ... + + // + double GetX3MaFast( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(x3maFastBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return x3maFastBuffer[barIndex]; + } + + // + int CopyX3MaFast( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + x3maFastBuffer, + buffer, + forceClean + // + ); + } + + // + // STATE FAST ... + + // + double GetX3MaFastState( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(x3maFastStateBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return x3maFastStateBuffer[barIndex]; + } + + // + int CopyX3MaFastState( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + x3maFastStateBuffer, + buffer, + forceClean + // + ); + } + + // + // MID ... + + // + double GetX3MaMid( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(x3maMidBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return x3maMidBuffer[barIndex]; + } + + // + int CopyX3MaMid( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + x3maMidBuffer, + buffer, + forceClean + // + ); + } + + // + // STATE MID ... + + // + double GetX3MaMidState( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(x3maMidStateBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return x3maMidStateBuffer[barIndex]; + } + + // + int CopyX3MaMidState( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + x3maMidStateBuffer, + buffer, + forceClean + // + ); + } + + // + // SLOW ... + + // + double GetX3MaSlowBuffer( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(x3maSlowBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return x3maSlowBuffer[barIndex]; + } + + // + int CopyX3MaSlow( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + x3maSlowBuffer, + buffer, + forceClean + // + ); + } + + // + // STATE SLOW ... + + // + double GetX3MaSlowState( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(x3maSlowStateBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return x3maSlowStateBuffer[barIndex]; + } + + // + int CopyX3MaSlowState( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + x3maSlowStateBuffer, + buffer, + forceClean + // + ); + } + + // + // Converts to State ... + ENUM_X3MA_STATES ToX3MAState(double value) + { + // + ENUM_X3MA_STATES result = + value == 1 + ? X3MA_STATE_BULLISH + : value == 2 + ? X3MA_STATE_BEARISH + : X3MA_STATE_NEUTURAL; + + // + return result; + } + + // + bool IsX3MABullish(double value) + { + // + bool result = false; + + // + result = ToX3MAState(value) == X3MA_STATE_BULLISH; + + // + return result; + } + + // + bool IsX3MABearish(double value) + { + // + bool result = false; + + // + result = ToX3MAState(value) == X3MA_STATE_BEARISH; + + // + return result; + } + + // + bool IsX3MANeutural(double value) + { + // + bool result = false; + + // + result = ToX3MAState(value) == X3MA_STATE_NEUTURAL; + + // + return result; + } + + // + void Free() override + { + Cleanup(10); + } + + // + bool GetConditions( + X121X3MAConditions &conditions, // + int barIndex = 0, // + int loopback = 5 // + ) + { + // + bool result = true; + + // + if (loopback < 5) + { + loopback = 5; + } + + // + conditions.Clean(); + + // + conditions.symbol = mSymbol; + conditions.period = mPeriod; + conditions.time = TimeCurrent(); + + // + int zIndex = barIndex; + int cIndex = zIndex + 1; + int pIndex = cIndex + 1; + int ppIndex = pIndex + 1; + + // + XOHCL zBar; + result = zBar.Init( + mSymbol, + mPeriod, + zIndex // + ); + if (!result) + { + return result; + } + + // + XOHCL cBar; + result = cBar.Init( + mSymbol, + mPeriod, + cIndex // + ); + if (!result) + { + return result; + } + + // + XOHCL pBar; + result = pBar.Init( + mSymbol, + mPeriod, + pIndex // + ); + if (!result) + { + return result; + } + + // + // Buffers ... + + // + CopyX3MaFast( + zIndex, + loopback, + conditions.x3maFastBuffer // + ); + + // + CopyX3MaFastState( + zIndex, + loopback, + conditions.x3maFastStateBuffer // + ); + + // + CopyX3MaMid( + zIndex, + loopback, + conditions.x3maMidBuffer // + ); + + // + CopyX3MaMidState( + zIndex, + loopback, + conditions.x3maMidStateBuffer // + ); + + // + CopyX3MaSlow( + zIndex, + loopback, + conditions.x3maSlowBuffer // + ); + + // + CopyX3MaSlowState( + zIndex, + loopback, + conditions.x3maSlowStateBuffer // + ); + + // + // Conditions ... + + // + int cIDX = 1; + int pIDX = cIDX + 1; + + // + // SAR ... + + // + bool isX3MaFastBullish = IsX3MABullish(conditions.x3maFastStateBuffer[cIDX]); + bool isX3MaFastBullishPrev = IsX3MABullish(conditions.x3maFastStateBuffer[pIDX]); + + // + bool isX3MaFastBearish = IsX3MABearish(conditions.x3maFastStateBuffer[cIDX]); + bool isX3MaFastBearishPrev = IsX3MABearish(conditions.x3maFastStateBuffer[pIDX]); + + // + bool isX3MaFastNeutural = IsX3MANeutural(conditions.x3maFastStateBuffer[cIDX]); + bool isX3MaFastNeuturalPrev = IsX3MANeutural(conditions.x3maFastStateBuffer[pIDX]); + + // + bool isX3MaMidBullish = IsX3MABullish(conditions.x3maMidStateBuffer[cIDX]); + bool isX3MaMidBullishPrev = IsX3MABullish(conditions.x3maMidStateBuffer[pIDX]); + + // + bool isX3MaMidBearish = IsX3MABearish(conditions.x3maMidStateBuffer[cIDX]); + bool isX3MaMidBearishPrev = IsX3MABearish(conditions.x3maMidStateBuffer[pIDX]); + + // + bool isX3MaMidNeutural = IsX3MANeutural(conditions.x3maMidStateBuffer[cIDX]); + bool isX3MaMidNeuturalPrev = IsX3MANeutural(conditions.x3maMidStateBuffer[pIDX]); + + // + bool isX3MaSlowBullish = IsX3MABullish(conditions.x3maSlowStateBuffer[cIDX]); + bool isX3MaSlowBullishPrev = IsX3MABullish(conditions.x3maSlowStateBuffer[pIDX]); + + // + bool isX3MaSlowBearish = IsX3MABearish(conditions.x3maSlowStateBuffer[cIDX]); + bool isX3MaSlowBearishPrev = IsX3MABearish(conditions.x3maSlowStateBuffer[pIDX]); + + // + bool isX3MaSlowNeutural = IsX3MANeutural(conditions.x3maSlowStateBuffer[cIDX]); + bool isX3MaSlowNeuturalPrev = IsX3MANeutural(conditions.x3maSlowStateBuffer[pIDX]); + + // + bool isX3MaFastOverMid = conditions.x3maFastBuffer[cIDX] > conditions.x3maMidBuffer[cIDX]; + bool isX3MaFastOverMidPrev = conditions.x3maFastBuffer[pIDX] > conditions.x3maMidBuffer[pIDX]; + + // + bool isX3MaMidOverSlow = conditions.x3maMidBuffer[cIDX] > conditions.x3maSlowBuffer[cIDX]; + bool isX3MaMidOverSlowPrev = conditions.x3maMidBuffer[pIDX] > conditions.x3maSlowBuffer[pIDX]; + + // + bool isX3MaFastUnderMid = conditions.x3maFastBuffer[cIDX] < conditions.x3maMidBuffer[cIDX]; + bool isX3MaFastUnderMidPrev = conditions.x3maFastBuffer[pIDX] < conditions.x3maMidBuffer[pIDX]; + + // + bool isX3MaMidUnderSlow = conditions.x3maMidBuffer[cIDX] < conditions.x3maSlowBuffer[cIDX]; + bool isX3MaMidUnderSlowPrev = conditions.x3maMidBuffer[pIDX] < conditions.x3maSlowBuffer[pIDX]; + + // + bool isX3MaBullishState = isX3MaFastBullish && + isX3MaMidBullish && + isX3MaSlowBullish; + bool isX3MaBullishStatePrev = isX3MaFastBullishPrev && + isX3MaMidBullishPrev && + isX3MaSlowBullishPrev; + + // + bool isX3MaBearishState = isX3MaFastBearish && + isX3MaMidBearish && + isX3MaSlowBearish; + bool isX3MaBearishStatePrev = isX3MaFastBearishPrev && + isX3MaMidBearishPrev && + isX3MaSlowBearishPrev; + + // + bool isX3MaNeuturalState = isX3MaFastNeutural && + isX3MaMidNeutural && + isX3MaSlowNeutural; + bool isX3MaNeuturalStatePrev = isX3MaFastNeuturalPrev && + isX3MaMidNeuturalPrev && + isX3MaSlowNeuturalPrev; + + // + bool isX3MaBullishOrdered = isX3MaFastOverMid && + isX3MaMidOverSlow; + bool isX3MaBullishOrderedPrev = isX3MaFastOverMidPrev && + isX3MaMidOverSlowPrev; + + // + bool isX3MaBearishOrdered = isX3MaFastUnderMid && + isX3MaMidUnderSlow; + bool isX3MaBearishOrderedPrev = isX3MaFastUnderMidPrev && + isX3MaMidUnderSlowPrev; + + // + bool isX3MaSwitchedToBullishOrdered = isX3MaBullishOrdered && + !isX3MaBullishOrderedPrev; + bool isX3MaSwitchedToBearishOrdered = isX3MaBearishOrdered && + !isX3MaBearishOrderedPrev; + + // + bool isX3MaSwitchedToBullishState = isX3MaBullishState && + !isX3MaBullishStatePrev; + bool isX3MaSwitchedToBearishState = isX3MaBearishState && + !isX3MaBearishStatePrev; + bool isX3MaSwitchedToNeuturalState = isX3MaNeuturalState && + !isX3MaNeuturalStatePrev; + + // + conditions.isX3MaFastBullish = isX3MaFastBullish; + conditions.isX3MaFastBearish = isX3MaFastBearish; + conditions.isX3MaFastNeutural = isX3MaFastNeutural; + conditions.isX3MaMidBullish = isX3MaMidBullish; + conditions.isX3MaMidBearish = isX3MaMidBearish; + conditions.isX3MaMidNeutural = isX3MaMidNeutural; + conditions.isX3MaSlowBullish = isX3MaSlowBullish; + conditions.isX3MaSlowBearish = isX3MaSlowBearish; + conditions.isX3MaSlowNeutural = isX3MaSlowNeutural; + conditions.isX3MaFastOverMid = isX3MaFastOverMid; + conditions.isX3MaMidOverSlow = isX3MaMidOverSlow; + conditions.isX3MaFastUnderMid = isX3MaFastUnderMid; + conditions.isX3MaMidUnderSlow = isX3MaMidUnderSlow; + conditions.isX3MaBullishState = isX3MaBullishState; + conditions.isX3MaBearishState = isX3MaBearishState; + conditions.isX3MaNeuturalState = isX3MaNeuturalState; + conditions.isX3MaBullishOrdered = isX3MaBullishOrdered; + conditions.isX3MaBearishOrdered = isX3MaBearishOrdered; + conditions.isX3MaSwitchedToBullishOrdered = isX3MaSwitchedToBullishOrdered; + conditions.isX3MaSwitchedToBearishOrdered = isX3MaSwitchedToBearishOrdered; + conditions.isX3MaSwitchedToBullishState = isX3MaSwitchedToBullishState; + conditions.isX3MaSwitchedToBearishState = isX3MaSwitchedToBearishState; + conditions.isX3MaSwitchedToNeuturalState = isX3MaSwitchedToNeuturalState; + + // + Cleanup(); + + // + zBar.Clean(); + cBar.Clean(); + pBar.Clean(); + + // + return result; + } + + // + // Protected ... + protected: + // + // Private ... + private: + // + // Props ... + X121X3MAInputs mInputs; // Inputs ... + + // + // Buffers ... + double x3maFastBuffer[]; + double x3maMidBuffer[]; + double x3maSlowBuffer[]; + double x3maFastStateBuffer[]; + double x3maMidStateBuffer[]; + double x3maSlowStateBuffer[]; + + // + void Calculate( + int barIndex = 0, + int maxRequiredBars = 100 // + ) + { + // + // Buffers ... + if (barIndex < 0) { + barIndex = 0; + } + + // + // FAST ... + CopyBuffer( + mHandler, + X121_X3MA_FAST_LINE, + barIndex, + maxRequiredBars, + x3maFastBuffer + // + ); + + // + // FAST STATE ... + CopyBuffer( + mHandler, + X121_X3MA_FAST_STATE_LINE, + barIndex, + maxRequiredBars, + x3maFastStateBuffer + // + ); + + // + // MID ... + CopyBuffer( + mHandler, + X121_X3MA_MID_LINE, + barIndex, + maxRequiredBars, + x3maMidBuffer + // + ); + + // + // MID STATE ... + CopyBuffer( + mHandler, + X121_X3MA_MID_STATE_LINE, + barIndex, + maxRequiredBars, + x3maMidStateBuffer + // + ); + + // + // SLOW ... + CopyBuffer( + mHandler, + X121_X3MA_SLOW_LINE, + barIndex, + maxRequiredBars, + x3maSlowBuffer + // + ); + + // + // SLOW STATE ... + CopyBuffer( + mHandler, + X121_X3MA_SLOW_STATE_LINE, + barIndex, + maxRequiredBars, + x3maSlowStateBuffer + // + ); + } + + // + void Cleanup( + int maxAllowed = 100 // + ) + { + // + CleanupArray( + x3maFastBuffer, + maxAllowed // + ); + + // + CleanupArray( + x3maMidBuffer, + maxAllowed // + ); + + // + CleanupArray( + x3maSlowBuffer, + maxAllowed // + ); + + // + CleanupArray( + x3maFastStateBuffer, + maxAllowed // + ); + + // + CleanupArray( + x3maMidStateBuffer, + maxAllowed // + ); + + // + CleanupArray( + x3maSlowStateBuffer, + maxAllowed // + ); + + // + } + + // +}; + +// +// Tools ... \ No newline at end of file diff --git a/BKPS/14040203/Helpers/x-saherelm.x121.xatr.helper.mq5 b/BKPS/14040203/Helpers/x-saherelm.x121.xatr.helper.mq5 new file mode 100644 index 0000000..4a2365f --- /dev/null +++ b/BKPS/14040203/Helpers/x-saherelm.x121.xatr.helper.mq5 @@ -0,0 +1,1824 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Helper Class Library +// ---------------------------------------------- +// Name: XCX121XATRHelper +// Description: provides all Indicator +// Helper requirements ... +// +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +////////////////////////////////////////////////////// +// +// Global Properties ... +#property library +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://www.saherelm.ir" +#property version "1.00" +#property strict + +// +// Imports ... +#include "../Classes/x-saherelm.x-helper.class.mq5" + +// +// Definitions ... + +// +// Definitions ... +enum ENUM_X121_XATR_BUFFERS +{ + // + X121_ATR_UPPER_LINE = 0, + X121_ATR_LOWER_LINE = 1, + X121_ATR_SM_UPPER_LINE = 2, + X121_ATR_SM_LOWER_LINE = 3, + X121_PRICE_CHANGE_LINE = 4, + X121_PRICE_CHANGE_SM_LINE = 5, + X121_RSI_CHANGE_LINE = 6, + X121_RSI_CHANGE_SM_LINE = 7, + X121_ATR_LINE = 8, + X121_RSI_LINE = 9, +}; + +// +// Input Models ... +struct X121XATRInputs +{ + // + // Props ... + + // + // RSI Detection ... + int rsiLength; // Length + ENUM_X_PRICE rsiPriceType; // Applied To + ENUM_X_MA_METHOD rsiSmoothingMethod; // Smoothing Method; + + // + // ATR Detection ... + int atrLength; // Length + double atrMultiplier; // Multiplier + ENUM_X_PRICE atrUpperPriceType; // Upper Zone Applied To + ENUM_X_PRICE atrLowerPriceType; // Lower Zone Applied To + ENUM_X_MA_METHOD atrSmoothingMethod; // Smoothing Method + + // + // Price Change ... + int priceChangeSmoothingLength; // Length + ENUM_X_PRICE priceChangeType; // Price Type + ENUM_X_MA_METHOD priceChangeSmoothingMethod; // Moving Average Moethod + + // + // Presentation ... + int startCalculationForLastBars; // Calculate Last n Bars + bool showAtrUpper; // Show Upper Zone + bool showAtrLower; // Show Lower Zone + bool showSmoothedAtrUpper; // Show Smoothed Upper Zone + bool showSmoothedAtrLower; // Show Smoothed Lower Zone + bool showRSIChange; // Show RSI Change + bool showSmoothedRSIChange; // ShowSmoothed RSI Change + bool showPriceChange; // Show Price Change + bool showSmoothedPriceChange; // ShowSmoothed Price Change + + // + // Custom Props ... + int rsiOverSoldLevel; // RSI Over Sold Level ... + int rsiOverBoughtLevel; // RSI Over Bought Level ... + + // + // Constructor(s) ... + X121XATRInputs() + { + // + Clean(); + } + + // + // Tools ... + + // + // Clean ... + void Clean() + { + // + // RSI Detection ... + rsiLength = 0; // Length + rsiPriceType = X_PRICE_NONE; // Applied To + rsiSmoothingMethod = X_MA_MODE_NONE; // Smoothing Method; + + // + // ATR Detection ... + atrLength = 0; // Length + atrMultiplier = 0; // Multiplier + atrUpperPriceType = X_PRICE_NONE; // Upper Zone Applied To + atrLowerPriceType = X_PRICE_NONE; // Lower Zone Applied To + atrSmoothingMethod = X_MA_MODE_NONE; // Smoothing Method + + // + // Price Change ... + priceChangeSmoothingLength = 0; // Length + priceChangeType = X_PRICE_NONE; // Price Type + priceChangeSmoothingMethod = X_MA_MODE_NONE; // Moving Average Moethod + + // + // Presentation ... + startCalculationForLastBars = 0; // Calculate Last n Bars + showAtrUpper = false; // Show Upper Zone + showAtrLower = false; // Show Lower Zone + showSmoothedAtrUpper = false; // Show Smoothed Upper Zone + showSmoothedAtrLower = false; // Show Smoothed Lower Zone + showRSIChange = false; // Show RSI Change + showSmoothedRSIChange = false; // ShowSmoothed RSI Change + showPriceChange = false; // Show Price Change + showSmoothedPriceChange = false; // ShowSmoothed Price Change + + // + rsiOverSoldLevel = 0; + rsiOverBoughtLevel = 0; + + // + ZeroMemory(this); + } + + // + // Default ... + void Default() + { + // + // RSI Detection ... + rsiLength = 14; // Length + rsiPriceType = X_PRICE_CLOSE; // Applied To + rsiSmoothingMethod = X_MA_MODE_SMA; // Smoothing Method; + + // + // ATR Detection ... + atrLength = 14; // Length + atrMultiplier = 1; // Multiplier + atrUpperPriceType = X_PRICE_HIGH; // Upper Zone Applied To + atrLowerPriceType = X_PRICE_LOW; // Lower Zone Applied To + atrSmoothingMethod = X_MA_MODE_SMA; // Smoothing Method + + // + // Price Change ... + priceChangeSmoothingLength = 14; // Length + priceChangeType = X_PRICE_CLOSE; // Price Type + priceChangeSmoothingMethod = X_MA_MODE_SMA; // Moving Average Moethod + + // + // Presentation ... + startCalculationForLastBars = 1000; // Calculate Last n Bars + showAtrUpper = true; // Show Upper Zone + showAtrLower = true; // Show Lower Zone + showSmoothedAtrUpper = true; // Show Smoothed Upper Zone + showSmoothedAtrLower = true; // Show Smoothed Lower Zone + showRSIChange = true; // Show RSI Change + showSmoothedRSIChange = true; // ShowSmoothed RSI Change + showPriceChange = true; // Show Price Change + showSmoothedPriceChange = true; // ShowSmoothed Price Change + + // + rsiOverSoldLevel = 30; + rsiOverBoughtLevel = 70; + } + + // + // Validate ... + bool IsValid() + { + // + bool result = false; + + // + result = + // + // RSI ... + rsiLength > 0 && + // + // ATR ... + atrLength > 0 && + atrMultiplier > 0 && + // + // RSI Levels ... + rsiOverSoldLevel > 0 && + rsiOverSoldLevel < 100 && + rsiOverBoughtLevel > 0 && + rsiOverBoughtLevel < 100 && + rsiOverSoldLevel < rsiOverBoughtLevel && + // + priceChangeSmoothingLength > 0 && + // + IsValid(rsiPriceType) && + IsValid(priceChangeType) && + IsValid(atrUpperPriceType) && + IsValid(atrLowerPriceType) + // + ; + + // + return result; + } + + // + // Retrieve MAx Length ... + int Max() + { + // + int result = 0; + + // + result = MathMax(rsiLength, atrLength); + result = MathMax(result, priceChangeSmoothingLength); + + // + return result; + } +}; + +// +// Conditions ... +struct X121XATRConditions +{ + // + // Common ... + string symbol; + ENUM_TIMEFRAMES period; + datetime time; + + // + // Buffers ... + double rsiBuffer[]; + double atrBuffer[]; + double atrUpperBuffer[]; + double atrLowerBuffer[]; + double atrUpperSMBuffer[]; + double atrLowerSMBuffer[]; + double rsiChangeBuffer[]; + double rsiChangeSMBuffer[]; + double priceChangeBuffer[]; + double priceChangeSMBuffer[]; + + // + // Conditions ... + + // + // RSI ... + bool isRsiInRange; + bool isRsiOverSold; + bool isRsiOverBought; + bool isRsiCrossedOverOverSold; + bool isRsiCrossedUnderOverSold; + bool isRsiCrossedOverOverBought; + bool isRsiCrossedUnderOverBought; + + // + // Other ... + + // + bool isRsiSMOverPriceChange; + bool isRsiSMUnderPriceChange; + + // + bool isRsiSMCrossedOverPriceChange; + bool isRsiSMCrossedUnderPriceChange; + + // + bool isPriceChangeSMOverRsi; + bool isPriceChangeSMUnderRsi; + + // + bool isPriceChangeSMCrossedOverRsi; + bool isPriceChangeSMCrossedUnderRsi; + + // + bool isRsiOverRsiSM; + bool isRsiUnderRsiSM; + + // + bool isRsiCrossedOverRsiSM; + bool isRsiCrossedUnderRsiSM; + + // + bool isPriceChangeOverPriceChangeSM; + bool isPriceChangeUnderPriceChangeSM; + + // + bool isPriceChangeCrossedOverPriceChangeSM; + bool isPriceChangeCrossedUnderPriceChangeSM; + + // + // bool isCloseLower + + // + // Constructor ... + X121XATRConditions() + { + Clean(); + } + + // + // Tools ... + + /** + * Cleaning Up ... + */ + void Clean() + { + // + // Commons ... + symbol = NULL; + period = NULL; + time = NULL; + + // + // Buffers ... + + // + Clean(rsiBuffer); + Clean(atrBuffer); + Clean(atrUpperBuffer); + Clean(atrLowerBuffer); + Clean(atrUpperSMBuffer); + Clean(atrLowerSMBuffer); + Clean(rsiChangeBuffer); + Clean(rsiChangeSMBuffer); + Clean(priceChangeBuffer); + Clean(priceChangeSMBuffer); + + // + ArraySetAsSeries(rsiBuffer, true); + ArraySetAsSeries(atrBuffer, true); + ArraySetAsSeries(atrUpperBuffer, true); + ArraySetAsSeries(atrLowerBuffer, true); + ArraySetAsSeries(atrUpperSMBuffer, true); + ArraySetAsSeries(atrLowerSMBuffer, true); + ArraySetAsSeries(rsiChangeBuffer, true); + ArraySetAsSeries(rsiChangeSMBuffer, true); + ArraySetAsSeries(priceChangeBuffer, true); + ArraySetAsSeries(priceChangeSMBuffer, true); + + // + // Conditions ... + + // + // RSI ... + isRsiInRange = false; + isRsiOverSold = false; + isRsiOverBought = false; + isRsiCrossedOverOverSold = false; + isRsiCrossedUnderOverSold = false; + isRsiCrossedOverOverBought = false; + isRsiCrossedUnderOverBought = false; + + // + // Other ... + + // + isRsiSMOverPriceChange = false; + isRsiSMUnderPriceChange = false; + + // + isRsiSMCrossedOverPriceChange = false; + isRsiSMCrossedUnderPriceChange = false; + + // + isPriceChangeSMOverRsi = false; + isPriceChangeSMUnderRsi = false; + + // + isPriceChangeSMCrossedOverRsi = false; + isPriceChangeSMCrossedUnderRsi = false; + + // + isRsiOverRsiSM = false; + isRsiUnderRsiSM = false; + + // + isRsiCrossedOverRsiSM = false; + isRsiCrossedUnderRsiSM = false; + + // + isPriceChangeOverPriceChangeSM = false; + isPriceChangeUnderPriceChangeSM = false; + + // + isPriceChangeCrossedOverPriceChangeSM = false; + isPriceChangeCrossedUnderPriceChangeSM = false; + + // + ZeroMemory(this); + } + + /** + * Generate Conditions Scores ... + * + * @param bullishScore: Double, Directional Scores Reference ... + * @param bearishScore: Double, Directional Scores Reference ... + */ + void GenerateScore( + double &bullishScore, + double &bearishScore // + ) + { + // + bullishScore = 0; + bearishScore = 0; + + // + double score = 1; + double minScore = 0.5; + double highScore = 1.5; + + // + if (isRsiOverSold) + { + bullishScore += minScore; + } + if (isRsiOverRsiSM) + { + bullishScore += minScore; + } + if (isRsiSMOverPriceChange) + { + bullishScore += minScore; + } + if (isPriceChangeSMOverRsi) + { + bullishScore += minScore; + } + if (isPriceChangeOverPriceChangeSM) + { + bullishScore += minScore; + } + + // + if (isRsiCrossedOverRsiSM) + { + bullishScore += score; + } + if (isRsiCrossedOverOverSold) + { + bullishScore += score; + } + if (isRsiCrossedUnderOverBought) + { + bullishScore += score; + } + if (isRsiSMCrossedOverPriceChange) + { + bullishScore += score; + } + if (isPriceChangeSMCrossedOverRsi) + { + bullishScore += score; + } + if (isPriceChangeCrossedOverPriceChangeSM) + { + bullishScore += score; + } + + // + if (isRsiOverBought) + { + bearishScore += minScore; + } + if (isRsiUnderRsiSM) + { + bearishScore += minScore; + } + if (isRsiSMUnderPriceChange) + { + bearishScore += minScore; + } + if (isPriceChangeSMUnderRsi) + { + bearishScore += minScore; + } + if (isPriceChangeUnderPriceChangeSM) + { + bearishScore += minScore; + } + + // + if (isRsiCrossedUnderRsiSM) + { + bearishScore += score; + } + if (isRsiCrossedUnderOverSold) + { + bearishScore += score; + } + if (isRsiCrossedOverOverBought) + { + bearishScore += score; + } + if (isRsiSMCrossedUnderPriceChange) + { + bearishScore += score; + } + if (isPriceChangeSMCrossedUnderRsi) + { + bearishScore += score; + } + if (isPriceChangeCrossedUnderPriceChangeSM) + { + bearishScore += score; + } + } + + /** + * Generate Summary String for Represent Conditions State ... + * + * @param onlyCommons: Boolean, Just Generate Only Commons Conditions ... + * @param onlyConditions: Boolean, Just Generate Only Conditions ... + * @param includeScores: Boolean, Attach Scores Representations on Result ... + * @param ignoreFalseConditions: Boolean, Ignore False Conditions on Result ... + * @param separator: String, Separate Lines ... + * + * @return ( string ) + */ + string GenerateSummary( + bool onlyCommons = false, + bool onlyConditions = false, + bool includeScores = true, + bool ignoreFalseConditions = true, + string separator = "\n" // + ) + { + // + string result = NULL; + + // + double bullishScore = 0; + double bearishScore = 0; + GenerateScore( + bullishScore, + bearishScore // + ); + + // + string scoresStr = + // + "Scores: " + separator + + "---------------" + separator + + "Bullish: " + ToString(bullishScore) + separator + + "Bearish: " + ToString(bearishScore) + separator + + "" + // + ; + + // + string commonStr = GenerateSpecifiedCommonSummary( + this, + separator, + includeScores // + ); + + // + string conditionsStr = + // + "-----------------------" + separator + + "XATR: " + separator + + "-----------------------" + separator + + ToString("isRsiInRange", isRsiInRange, ignoreFalseConditions, separator) + + ToString("isRsiOverSold", isRsiOverSold, ignoreFalseConditions, separator) + + ToString("isRsiOverBought", isRsiOverBought, ignoreFalseConditions, separator) + + ToString("isRsiCrossedOverOverSold", isRsiCrossedOverOverSold, ignoreFalseConditions, separator) + + ToString("isRsiCrossedUnderOverSold", isRsiCrossedUnderOverSold, ignoreFalseConditions, separator) + + ToString("isRsiCrossedOverOverBought", isRsiCrossedOverOverBought, ignoreFalseConditions, separator) + + ToString("isRsiCrossedUnderOverBought", isRsiCrossedUnderOverBought, ignoreFalseConditions, separator) + + // + ToString("isRsiSMOverPriceChange", isRsiSMOverPriceChange, ignoreFalseConditions, separator) + + ToString("isRsiSMUnderPriceChange", isRsiSMUnderPriceChange, ignoreFalseConditions, separator) + + ToString("isRsiSMCrossedOverPriceChange", isRsiSMCrossedOverPriceChange, ignoreFalseConditions, separator) + + ToString("isRsiSMCrossedUnderPriceChange", isRsiSMCrossedUnderPriceChange, ignoreFalseConditions, separator) + + ToString("isPriceChangeSMOverRsi", isPriceChangeSMOverRsi, ignoreFalseConditions, separator) + + ToString("isPriceChangeSMUnderRsi", isPriceChangeSMUnderRsi, ignoreFalseConditions, separator) + + ToString("isPriceChangeSMCrossedOverRsi", isPriceChangeSMCrossedOverRsi, ignoreFalseConditions, separator) + + ToString("isPriceChangeSMCrossedUnderRsi", isPriceChangeSMCrossedUnderRsi, ignoreFalseConditions, separator) + + ToString("isRsiOverRsiSM", isRsiOverRsiSM, ignoreFalseConditions, separator) + + ToString("isRsiUnderRsiSM", isRsiUnderRsiSM, ignoreFalseConditions, separator) + + ToString("isRsiCrossedOverRsiSM", isRsiCrossedOverRsiSM, ignoreFalseConditions, separator) + + ToString("isRsiCrossedUnderRsiSM", isRsiCrossedUnderRsiSM, ignoreFalseConditions, separator) + + ToString("isPriceChangeOverPriceChangeSM", isPriceChangeOverPriceChangeSM, ignoreFalseConditions, separator) + + ToString("isPriceChangeUnderPriceChangeSM", isPriceChangeUnderPriceChangeSM, ignoreFalseConditions, separator) + + ToString("isPriceChangeCrossedOverPriceChangeSM", isPriceChangeCrossedOverPriceChangeSM, ignoreFalseConditions, separator) + + ToString("isPriceChangeCrossedUnderPriceChangeSM", isPriceChangeCrossedUnderPriceChangeSM, ignoreFalseConditions, separator) + + // + "" + // + ; + + // + result = + // + "[" + GetTag() + "]" + separator + + (onlyConditions + ? "" + : commonStr) + + (!includeScores + ? "" + : scoresStr) + + " " + separator + + (onlyCommons + ? "" + : conditionsStr) + + "" + // + ; + + // + return result; + } + + /** + * Retrieve nique Tag Identifier ... + * + * @return ( string ) + */ + string GetTag() + { + return GetTypeName(this); + } + + // +}; + +// +// Class ... +class XCX121XATRHelper : public XCBaseHelper +{ + // + // Public ... + public: + // + // Props ... + + // + // Constructors ... + XCX121XATRHelper() + : XCBaseHelper(_Symbol, _Period) + { + } + + // + // Deconstructor ... + ~XCX121XATRHelper() + { + // + Clean(rsiBuffer); + Clean(atrBuffer); + Clean(atrUpperBuffer); + Clean(atrLowerBuffer); + Clean(atrUpperSMBuffer); + Clean(atrLowerSMBuffer); + Clean(rsiChangeBuffer); + Clean(rsiChangeSMBuffer); + Clean(priceChangeBuffer); + Clean(priceChangeSMBuffer); + + // + mInputs.Clean(); + } + + // + // Tools ... + bool Init( + string symbol, // Trading Symbol + ENUM_TIMEFRAMES period, // Trading Period + X121XATRInputs &inputs // Inputs + ) + { + // + bool result = false; + + // + mSymbol = symbol; + mPeriod = period; + + // + result = inputs.IsValid(); + if (!result) + { + return result; + } + + // + ArraySetAsSeries(rsiBuffer, true); + ArraySetAsSeries(atrBuffer, true); + ArraySetAsSeries(atrUpperBuffer, true); + ArraySetAsSeries(atrLowerBuffer, true); + ArraySetAsSeries(atrUpperSMBuffer, true); + ArraySetAsSeries(atrLowerSMBuffer, true); + ArraySetAsSeries(rsiChangeBuffer, true); + ArraySetAsSeries(rsiChangeSMBuffer, true); + ArraySetAsSeries(priceChangeBuffer, true); + ArraySetAsSeries(priceChangeSMBuffer, true); + + // + mInputs = inputs; + + // + mHandler = iCustom( + mSymbol, + mPeriod, + "x-saherelm.x121.xatr", + // + // Inputs ... + // + // Market ... + "", + // + // RSI Detection ... + "", + mInputs.rsiLength, // Length + mInputs.rsiPriceType, // Applied To + mInputs.rsiSmoothingMethod, // Smoothing Method; + // + // ATR Detection ... + "", + mInputs.atrLength, // Length + mInputs.atrMultiplier, // Multiplier + mInputs.atrUpperPriceType, // Upper Zone Applied To + mInputs.atrLowerPriceType, // Lower Zone Applied To + mInputs.atrSmoothingMethod, // Smoothing Method + // + // Price Change ... + "", + mInputs.priceChangeSmoothingLength, // Length + mInputs.priceChangeType, // Price Type + mInputs.priceChangeSmoothingMethod, // Moving Average Moethod + // + // Presentation ... + "", + mInputs.startCalculationForLastBars, // Calculate Last n Bars + mInputs.showAtrUpper, // Show Upper Zone + mInputs.showAtrLower, // Show Lower Zone + mInputs.showSmoothedAtrUpper, // Show Smoothed Upper Zone + mInputs.showSmoothedAtrLower, // Show Smoothed Lower Zone + mInputs.showRSIChange, // Show RSI Change + mInputs.showSmoothedRSIChange, // ShowSmoothed RSI Change + mInputs.showPriceChange, // Show Price Change + mInputs.showSmoothedPriceChange // ShowSmoothed Price Change + // + ); + result = mHandler != INVALID_HANDLE; + if (!result) + { + return result; + } + + // + return result; + } + + // + // Inputs ... + + // + X121XATRInputs GetInputs() + { + return mInputs; + } + + // + bool SetInputs( + X121XATRInputs &inputs // Configs + ) + { + // + return Init( + mSymbol, + mPeriod, + inputs + // + ); + } + + // + // Readers ... + + // + // RSI ... + + // + double GetRSI( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(rsiBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return rsiBuffer[barIndex]; + } + + // + int CopyRSI( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + rsiBuffer, + buffer, + forceClean + // + ); + } + + // + // ATR ... + + // + double GetATR( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(atrBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return atrBuffer[barIndex]; + } + + // + int CopyATR( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + atrBuffer, + buffer, + forceClean + // + ); + } + + // + double GetATRUpper( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(atrUpperBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return atrUpperBuffer[barIndex]; + } + + // + int CopyATRUpper( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + atrUpperBuffer, + buffer, + forceClean + // + ); + } + + // + double GetATRLower( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(atrLowerBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return atrLowerBuffer[barIndex]; + } + + // + int CopyATRLower( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + atrLowerBuffer, + buffer, + forceClean + // + ); + } + + // + double GetSMATRUpper( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(atrUpperSMBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return atrUpperSMBuffer[barIndex]; + } + + // + int CopySMATRUpper( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + atrUpperSMBuffer, + buffer, + forceClean + // + ); + } + + // + double GetSMATRLower( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(atrLowerSMBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return atrLowerSMBuffer[barIndex]; + } + + // + int CopySMATRLower( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + atrLowerSMBuffer, + buffer, + forceClean + // + ); + } + + // + // PRICE Change ... + + // + double GetPriceChange( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(priceChangeBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return priceChangeBuffer[barIndex]; + } + + // + int CopyPriceChange( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + priceChangeBuffer, + buffer, + forceClean + // + ); + } + + // + double GetSMPriceChange( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(priceChangeSMBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return priceChangeSMBuffer[barIndex]; + } + + // + int CopySMPriceChange( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + priceChangeSMBuffer, + buffer, + forceClean + // + ); + } + + // + // RSI Change ... + + // + double GetRsiChange( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(rsiChangeBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return rsiChangeBuffer[barIndex]; + } + + // + int CopyRsiChange( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + rsiChangeBuffer, + buffer, + forceClean + // + ); + } + + // + double GetSMRsiChange( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(rsiChangeSMBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return rsiChangeSMBuffer[barIndex]; + } + + // + int CopySMRsiChange( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + rsiChangeSMBuffer, + buffer, + forceClean + // + ); + } + + // + void Free() override + { + Cleanup(10); + } + + // + bool GetConditions( + X121XATRConditions &conditions, // + int barIndex = 0, // + int loopback = 5 // + ) + { + // + bool result = true; + + // + if (loopback < 5) + { + loopback = 5; + } + + // + conditions.Clean(); + + // + conditions.symbol = mSymbol; + conditions.period = mPeriod; + conditions.time = TimeCurrent(); + + // + int zIndex = barIndex; + int cIndex = zIndex + 1; + int pIndex = cIndex + 1; + int ppIndex = pIndex + 1; + + // + XOHCL zBar; + result = zBar.Init( + mSymbol, + mPeriod, + zIndex // + ); + if (!result) + { + return result; + } + + // + XOHCL cBar; + result = cBar.Init( + mSymbol, + mPeriod, + cIndex // + ); + if (!result) + { + return result; + } + + // + XOHCL pBar; + result = pBar.Init( + mSymbol, + mPeriod, + pIndex // + ); + if (!result) + { + return result; + } + + // + // Buffers ... + + // + CopyRSI( + zIndex, + loopback, + conditions.rsiBuffer // + ); + + // + CopyATR( + zIndex, + loopback, + conditions.atrBuffer // + ); + + // + CopyATRUpper( + zIndex, + loopback, + conditions.atrUpperBuffer // + ); + + // + CopyATRLower( + zIndex, + loopback, + conditions.atrLowerBuffer // + ); + + // + CopySMATRUpper( + zIndex, + loopback, + conditions.atrUpperSMBuffer // + ); + + // + CopySMATRLower( + zIndex, + loopback, + conditions.atrLowerSMBuffer // + ); + + // + CopyPriceChange( + zIndex, + loopback, + conditions.priceChangeBuffer // + ); + + // + CopySMPriceChange( + zIndex, + loopback, + conditions.priceChangeSMBuffer // + ); + + // + CopyRsiChange( + zIndex, + loopback, + conditions.rsiChangeBuffer // + ); + + // + CopySMRsiChange( + zIndex, + loopback, + conditions.rsiChangeSMBuffer // + ); + + // + // Conditions ... + + // + int zIDX = 0; + int cIDX = zIDX + 1; + int pIDX = cIDX + 1; + int pPIDX = pIDX + 1; + + // + double cRSI = conditions.rsiBuffer[cIDX]; + double pRSI = conditions.rsiBuffer[pIDX]; + double pPRSI = conditions.rsiBuffer[pPIDX]; + + // + // RSI ... + + // + bool isRsiInRange = + cRSI > mInputs.rsiOverSoldLevel && + cRSI < mInputs.rsiOverBoughtLevel; + bool isRsiInRangeP = + pRSI > mInputs.rsiOverSoldLevel && + pRSI < mInputs.rsiOverBoughtLevel; + + // + bool isRsiOverSold = + cRSI < mInputs.rsiOverSoldLevel; + bool isRsiOverSoldP = + pRSI < mInputs.rsiOverSoldLevel; + bool isRsiCrossedOverOverSold = isRsiOverSold && + !isRsiOverSoldP; + bool isRsiCrossedUnderOverSold = isRsiOverSoldP && + !isRsiOverSold; + + // + bool isRsiOverBought = + cRSI > mInputs.rsiOverBoughtLevel; + bool isRsiOverBoughtP = + pRSI > mInputs.rsiOverBoughtLevel; + bool isRsiCrossedOverOverBought = isRsiOverBought && + !isRsiOverBoughtP; + bool isRsiCrossedUnderOverBought = isRsiOverBoughtP && + !isRsiOverBought; + + // + // Other ... + + // + double rsiChange = conditions.rsiChangeBuffer[cIDX]; + double rsiChangeP = conditions.rsiChangeBuffer[pIDX]; + + // + double rsiChangeSM = conditions.rsiChangeSMBuffer[cIDX]; + double rsiChangeSMP = conditions.rsiChangeSMBuffer[pIDX]; + + // + double priceChange = conditions.priceChangeBuffer[cIDX]; + double priceChangeP = conditions.priceChangeBuffer[pIDX]; + + // + double priceChangeSM = conditions.priceChangeSMBuffer[cIDX]; + double priceChangeSMP = conditions.priceChangeSMBuffer[pIDX]; + + // + // + // + + // + bool isRsiSMOverPriceChange = rsiChangeSM > priceChangeSM; + bool isRsiSMOverPriceChangeP = rsiChangeSMP > priceChangeSMP; + bool isRsiSMCrossedOverPriceChange = isRsiSMOverPriceChange && + !isRsiSMOverPriceChangeP; + + // + bool isRsiSMUnderPriceChange = rsiChangeSM < priceChangeSM; + bool isRsiSMUnderPriceChangeP = rsiChangeSMP < priceChangeSMP; + bool isRsiSMCrossedUnderPriceChange = isRsiSMUnderPriceChange && + !isRsiSMUnderPriceChangeP; + + // + bool isPriceChangeSMOverRsi = priceChangeSM > rsiChangeSM; + bool isPriceChangeSMOverRsiP = priceChangeSMP > rsiChangeSMP; + bool isPriceChangeSMCrossedOverRsi = isPriceChangeSMOverRsi && + !isPriceChangeSMOverRsiP; + + // + bool isPriceChangeSMUnderRsi = priceChangeSM < rsiChangeSM; + bool isPriceChangeSMUnderRsiP = priceChangeSMP < rsiChangeSMP; + bool isPriceChangeSMCrossedUnderRsi = isPriceChangeSMUnderRsi && + !isPriceChangeSMUnderRsiP; + + // + bool isRsiOverRsiSM = rsiChange > rsiChangeSM; + bool isRsiOverRsiSMP = rsiChangeP > rsiChangeSMP; + bool isRsiCrossedOverRsiSM = isRsiOverRsiSM && + !isRsiOverRsiSMP; + + // + bool isRsiUnderRsiSM = rsiChange < rsiChangeSM; + bool isRsiUnderRsiSMP = rsiChangeP < rsiChangeSMP; + bool isRsiCrossedUnderRsiSM = isRsiUnderRsiSM && + !isRsiUnderRsiSMP; + + // + bool isPriceChangeOverPriceChangeSM = priceChange > priceChangeSM; + bool isPriceChangeOverPriceChangeSMP = priceChangeP > priceChangeSMP; + bool isPriceChangeCrossedOverPriceChangeSM = isPriceChangeOverPriceChangeSM && + !isPriceChangeOverPriceChangeSMP; + + // + bool isPriceChangeUnderPriceChangeSM = priceChange < priceChangeSM; + bool isPriceChangeUnderPriceChangeSMP = priceChangeP < priceChangeSMP; + bool isPriceChangeCrossedUnderPriceChangeSM = isPriceChangeUnderPriceChangeSM && + !isPriceChangeUnderPriceChangeSMP; + + // + // + // + + // + conditions.isRsiInRange = isRsiInRange; + conditions.isRsiOverSold = isRsiOverSold; + conditions.isRsiOverRsiSM = isRsiOverRsiSM; + conditions.isRsiOverBought = isRsiOverBought; + conditions.isRsiUnderRsiSM = isRsiUnderRsiSM; + conditions.isRsiCrossedOverRsiSM = isRsiCrossedOverRsiSM; + conditions.isRsiCrossedUnderRsiSM = isRsiCrossedUnderRsiSM; + conditions.isPriceChangeSMOverRsi = isPriceChangeSMOverRsi; + conditions.isRsiSMOverPriceChange = isRsiSMOverPriceChange; + conditions.isPriceChangeSMUnderRsi = isPriceChangeSMUnderRsi; + conditions.isRsiSMUnderPriceChange = isRsiSMUnderPriceChange; + conditions.isRsiCrossedOverOverSold = isRsiCrossedOverOverSold; + conditions.isRsiCrossedUnderOverSold = isRsiCrossedUnderOverSold; + conditions.isRsiCrossedOverOverBought = isRsiCrossedOverOverBought; + conditions.isRsiCrossedUnderOverBought = isRsiCrossedUnderOverBought; + conditions.isPriceChangeSMCrossedOverRsi = isPriceChangeSMCrossedOverRsi; + conditions.isRsiSMCrossedOverPriceChange = isRsiSMCrossedOverPriceChange; + conditions.isRsiSMCrossedUnderPriceChange = isRsiSMCrossedUnderPriceChange; + conditions.isPriceChangeSMCrossedUnderRsi = isPriceChangeSMCrossedUnderRsi; + conditions.isPriceChangeOverPriceChangeSM = isPriceChangeOverPriceChangeSM; + conditions.isPriceChangeUnderPriceChangeSM = isPriceChangeUnderPriceChangeSM; + conditions.isPriceChangeCrossedOverPriceChangeSM = isPriceChangeCrossedOverPriceChangeSM; + conditions.isPriceChangeCrossedUnderPriceChangeSM = isPriceChangeCrossedUnderPriceChangeSM; + + // + Cleanup(); + + // + zBar.Clean(); + cBar.Clean(); + pBar.Clean(); + + // + return result; + } + + // + // Protected ... + protected: + // + // Private ... + private: + // + // Props ... + X121XATRInputs mInputs; // Inputs ... + + // + // Buffers ... + double rsiBuffer[]; + double atrBuffer[]; + double atrUpperBuffer[]; + double atrLowerBuffer[]; + double atrUpperSMBuffer[]; + double atrLowerSMBuffer[]; + double rsiChangeBuffer[]; + double rsiChangeSMBuffer[]; + double priceChangeBuffer[]; + double priceChangeSMBuffer[]; + + // + void Calculate( + int barIndex = 0, + int maxRequiredBars = 100 // + ) + { + // + // Buffers ... + if (barIndex < 0) + { + barIndex = 0; + } + + // + // RSI ... + CopyBuffer( + mHandler, + X121_RSI_LINE, + barIndex, + maxRequiredBars, + rsiBuffer + // + ); + + // + // ATR ... + CopyBuffer( + mHandler, + X121_ATR_LINE, + barIndex, + maxRequiredBars, + atrBuffer // + ); + + // + // ATR Band ... + + // + // Upper ... + CopyBuffer( + mHandler, + X121_ATR_UPPER_LINE, + barIndex, + maxRequiredBars, + atrUpperBuffer // + ); + + // + // Lower ... + CopyBuffer( + mHandler, + X121_ATR_LOWER_LINE, + barIndex, + maxRequiredBars, + atrLowerBuffer // + ); + + // + // SM Upper ... + CopyBuffer( + mHandler, + X121_ATR_SM_UPPER_LINE, + barIndex, + maxRequiredBars, + atrUpperSMBuffer // + ); + + // + // Lower ... + CopyBuffer( + mHandler, + X121_ATR_SM_LOWER_LINE, + barIndex, + maxRequiredBars, + atrLowerSMBuffer // + ); + + // + // PRICE Change ... + + // + CopyBuffer( + mHandler, + X121_PRICE_CHANGE_LINE, + barIndex, + maxRequiredBars, + priceChangeBuffer // + ); + + // + CopyBuffer( + mHandler, + X121_PRICE_CHANGE_SM_LINE, + barIndex, + maxRequiredBars, + priceChangeSMBuffer // + ); + + // + // RSI Change ... + + // + CopyBuffer( + mHandler, + X121_RSI_CHANGE_LINE, + barIndex, + maxRequiredBars, + rsiChangeBuffer // + ); + + // + CopyBuffer( + mHandler, + X121_RSI_CHANGE_SM_LINE, + barIndex, + maxRequiredBars, + rsiChangeSMBuffer // + ); + + // + } + + // + void Cleanup( + int maxAllowed = 100 // + ) + { + // + CleanupArray( + rsiBuffer, + maxAllowed // + ); + + // + CleanupArray( + atrBuffer, + maxAllowed // + ); + + // + CleanupArray( + atrUpperBuffer, + maxAllowed // + ); + + // + CleanupArray( + atrLowerBuffer, + maxAllowed // + ); + + // + CleanupArray( + atrUpperSMBuffer, + maxAllowed // + ); + + // + CleanupArray( + atrLowerSMBuffer, + maxAllowed // + ); + + // + CleanupArray( + rsiChangeBuffer, + maxAllowed // + ); + + // + CleanupArray( + rsiChangeSMBuffer, + maxAllowed // + ); + + // + CleanupArray( + priceChangeBuffer, + maxAllowed // + ); + + // + CleanupArray( + priceChangeSMBuffer, + maxAllowed // + ); + + // + } + + // +}; + +// +// Tools ... \ No newline at end of file diff --git a/BKPS/14040203/Helpers/x-saherelm.x121.xca.helper.mq5 b/BKPS/14040203/Helpers/x-saherelm.x121.xca.helper.mq5 new file mode 100644 index 0000000..e556191 --- /dev/null +++ b/BKPS/14040203/Helpers/x-saherelm.x121.xca.helper.mq5 @@ -0,0 +1,3871 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Helper Class Library +// ---------------------------------------------- +// Name: XCX121XCAHelper +// Description: provides all Indicator +// Helper requirements ... +// +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +////////////////////////////////////////////////////// +// +// Global Properties ... +#property library +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://www.saherelm.ir" +#property version "1.00" +#property strict + +// +// Imports ... +#include "../Classes/x-saherelm.x-helper.class.mq5" + +// +// Definitions ... + +// +// Definitions ... +enum ENUM_X121_XCA_BUFFERS +{ + // + X121_XCA_S_HH_LINE = 0, + X121_XCA_S_LL_LINE = 1, + X121_XCA_M_HH_LINE = 2, + X121_XCA_M_LL_LINE = 3, + X121_XCA_L_HH_LINE = 4, + X121_XCA_L_LL_LINE = 5, + X121_XCA_H_HH_LINE = 6, + X121_XCA_H_LL_LINE = 7, + X121_XCA_SUPPORT_LINE = 8, + X121_XCA_RESISTANCE_LINE = 9, + X121_XCA_PEAK_LINE = 10, + X121_XCA_PEAK_GOLDEN_LINE = 11, + X121_XCA_VALE_LINE = 12, + X121_XCA_VALE_GOLDEN_LINE = 13, + X121_XCA_FIBO_L1_LINE = 14, + X121_XCA_FIBO_L2_LINE = 15, + X121_XCA_FIBO_L3_LINE = 16, + X121_XCA_SAR_LINE = 17, + X121_XCA_TREND_LINE = 18, + X121_XCA_KI_LINE = 20, + X121_XCA_SWING_LOW_LINE = 22, + X121_XCA_SWING_HIGH_LINE = 23, + X121_XCA_TKI_LINE = 24, + X121_XCA_TREND_STATE_LINE = 26, + X121_XCA_KI_STATE_LINE = 27, + X121_XCA_TKI_STATE_LINE = 28, +}; + +// +// Input Models ... +struct X121XCAInputs +{ + // + // Props ... + + // + // Market ... + + // + // Short ... + ENUM_X_PERIOD_METHOD scMethod; // How to Find Period + ENUM_TIMEFRAMES scPeriod; // Time Period + + // + // Medium ... + ENUM_X_PERIOD_METHOD mcMethod; // How to Find Period + ENUM_TIMEFRAMES mcPeriod; // Time Period + + // + // Long ... + ENUM_X_PERIOD_METHOD lcMethod; // How to Find Period + ENUM_TIMEFRAMES lcPeriod; // Time Period + + // + // Hind ... + ENUM_X_PERIOD_METHOD hcMethod; // How to Find Period + ENUM_TIMEFRAMES hcPeriod; // Time Period + + // + // Boundary Detection ... + ENUM_SERIESMODE hhMode; // Highest High Calculation Method + ENUM_SERIESMODE llMode; // Lowest Low Calculation Method + ENUM_X_FIBO_LEVELS goldenZoneLevel; // Golden Zone Detection + + // + // Fibo Levels ... + ENUM_X_FIBO_LEVELS fiboLevel1; // Fibo Level 1 + ENUM_X_FIBO_LEVELS fiboLevel2; // Fibo Level 2 + ENUM_X_FIBO_LEVELS fiboLevel3; // Fibo Level 3 + + // + // Sar Detection ... + double sarStep; // Step + double sarMax; // Maximum + + // + // KI ... + int kiLength; // KI Length + + // + // Swing Detection ... + int swingLength; // Length + + // + // Support and Resistance ... + int supResSmoothingLength; // Smoothing Length + ENUM_X_MA_METHOD supResSmoothingMode; // Smoothing Method + + // + // Presentation ... + + // + int startCalculationForLastBars; // Calculate Last n Bars + + // + bool showSar; // Show Sar + bool showKI; // Show KI + bool showTKI; // Show TKI + bool showTrend; // Show Trend + bool showSwings; // Show Swings + bool showFiboLevel1; // Show Fibo Level 1 + bool showFiboLevel2; // Show Fibo Level 2 + bool showFiboLevel3; // Show Fibo Level 3 + bool showPeaksAndVales; // Show Peaks And Vales + bool showPeakAndValeGolden; // Show Peak and Vale Golden + bool showSupportAndResistance; // Show Support and Resistance + bool showShortCycle; // Show Short Cycle + bool showMediumCycle; // Show Medium Cycle + bool showLongCycle; // Show Long Cycle + bool showHindCycle; // Show Hind Cycle + + // + int sarArrowCode; // Parabolic Sar Arrow Code + int peakArrowCode; // Peaks Arrow Code + int valeArrowCode; // Vales Arrow Code + int swingLowArrowCode; // Swing Low Arrow Code + int swingHighArrowCode; // Swing High Arrow Code + + // + // Constructor(s) ... + X121XCAInputs() + { + // + Clean(); + } + + // + // Tools ... + + // + // Clean ... + void Clean() + { + // + // Market ... + + // + // Short ... + scMethod = X_PERIOD_AUTO; // How to Find Period + scPeriod = NULL; // Time Period + + // + // Medium ... + mcMethod = X_PERIOD_AUTO; // How to Find Period + mcPeriod = NULL; // Time Period + + // + // Long ... + lcMethod = X_PERIOD_AUTO; // How to Find Period + lcPeriod = NULL; // Time Period + + // + // Hind ... + hcMethod = X_PERIOD_AUTO; // How to Find Period + hcPeriod = NULL; // Time Period + + // + // Boundary Detection ... + hhMode = MODE_HIGH; // Highest High Calculation Method + llMode = MODE_LOW; // Lowest Low Calculation Method + + // + // Fibo Levels ... + fiboLevel1 = X_FIBO_LEVEL_236; // Fibo Level 1 + fiboLevel2 = X_FIBO_LEVEL_500; // Fibo Level 2 + fiboLevel3 = X_FIBO_LEVEL_764; // Fibo Level 3 + + // + // Sar Detection ... + sarStep = 0; // Step + sarMax = 0; // Maximum + + // + // KI ... + kiLength = 0; // KI Length + + // + // Swing Detection ... + swingLength = 0; // Length + + // + // Support and Resistance ... + supResSmoothingLength = 0; // Smoothing Length + supResSmoothingMode = X_MA_MODE_NONE; // Smoothing Method + + // + // Presentation ... + + // + startCalculationForLastBars = 0; // Calculate Last n Bars + + // + showSar = true; // Show Sar + showKI = true; // Show KI + showTKI = true; // Show TKI + showTrend = true; // Show Trend + showSwings = true; // Show Swings + showFiboLevel1 = true; // Show Fibo Level 1 + showFiboLevel2 = true; // Show Fibo Level 2 + showFiboLevel3 = true; // Show Fibo Level 3 + showPeaksAndVales = true; // Show Peaks And Vales + showPeakAndValeGolden = true; // Show Peak and Vale Golden + showSupportAndResistance = true; // Show Support and Resistance + showShortCycle = true; // Show Short Cycle + showMediumCycle = true; // Show Medium Cycle + showLongCycle = true; // Show Long Cycle + showHindCycle = true; // Show Hind Cycle + + // + sarArrowCode = 0; // Parabolic Sar Arrow Code + peakArrowCode = 0; // Peaks Arrow Code + valeArrowCode = 0; // Vales Arrow Code + swingLowArrowCode = 0; // Swing Low Arrow Code + swingHighArrowCode = 0; // Swing High Arrow Code + + // + ZeroMemory(this); + } + + // + // Default ... + void Default() + { + // + // Market ... + + // + // Short ... + scMethod = X_PERIOD_AUTO; // How to Find Period + scPeriod = NULL; // Time Period + + // + // Medium ... + mcMethod = X_PERIOD_AUTO; // How to Find Period + mcPeriod = NULL; // Time Period + + // + // Long ... + lcMethod = X_PERIOD_AUTO; // How to Find Period + lcPeriod = NULL; // Time Period + + // + // Hind ... + hcMethod = X_PERIOD_AUTO; // How to Find Period + hcPeriod = NULL; // Time Period + + // + // Boundary Detection ... + hhMode = MODE_HIGH; // Highest High Calculation Method + llMode = MODE_LOW; // Lowest Low Calculation Method + + // + // Fibo Levels ... + fiboLevel1 = X_FIBO_LEVEL_236; // Fibo Level 1 + fiboLevel2 = X_FIBO_LEVEL_500; // Fibo Level 2 + fiboLevel3 = X_FIBO_LEVEL_764; // Fibo Level 3 + + // + // Sar Detection ... + sarStep = 0.02; // Step + sarMax = 0.2; // Maximum + + // + // KI ... + kiLength = 26; // KI Length + + // + // Swing Detection ... + swingLength = 5; // Length + + // + // Presentation ... + + // + startCalculationForLastBars = 1000; // Calculate Last n Bars + + // + showSar = true; // Show Sar + showKI = true; // Show KI + showTKI = true; // Show TKI + showTrend = true; // Show Trend + showSwings = true; // Show Swings + showFiboLevel1 = true; // Show Fibo Level 1 + showFiboLevel2 = true; // Show Fibo Level 2 + showFiboLevel3 = true; // Show Fibo Level 3 + showPeaksAndVales = true; // Show Peaks And Vales + showPeakAndValeGolden = true; // Show Peak and Vale Golden + showSupportAndResistance = true; // Show Support and Resistance + showShortCycle = true; // Show Short Cycle + showMediumCycle = true; // Show Medium Cycle + showLongCycle = true; // Show Long Cycle + showHindCycle = true; // Show Hind Cycle + + // + sarArrowCode = 159; // Parabolic Sar Arrow Code + peakArrowCode = 159; // Peaks Arrow Code + valeArrowCode = 159; // Vales Arrow Code + swingLowArrowCode = 225; // Swing Low Arrow Code + swingHighArrowCode = 226; // Swing High Arrow Code + } + + // + // Validate ... + bool IsValid() + { + // + bool result = false; + + // + result = + // + // SAR ... + sarMax > 0 && + sarStep > 0 && + kiLength > 0 && + swingLength > 0 && + sarMax > sarStep && + // + // XCA ... + (IsValid(scMethod, scPeriod) && + IsValid(mcMethod, mcPeriod) && + IsValid(lcMethod, lcPeriod) && + IsValid(hcMethod, hcPeriod)) + // + ; + + // + return result; + } + + // + // Retrieve MAx Length ... + int Max() + { + // + int result = 0; + + // + result = MathMax(kiLength, swingLength); + + // + return result; + } +}; + +// +// Conditions ... +struct X121XCAConditions +{ + // + // Common ... + string symbol; + ENUM_TIMEFRAMES period; + datetime time; + + // + // Buffers ... + double kiBuffer[]; + double tkiBuffer[]; + double sHHBuffer[]; + double sLLBuffer[]; + double mHHBuffer[]; + double mLLBuffer[]; + double lHHBuffer[]; + double lLLBuffer[]; + double hHHBuffer[]; + double hLLBuffer[]; + double sarBuffer[]; + double peakBuffer[]; + double valeBuffer[]; + double trendBuffer[]; + double kiStateBuffer[]; + double supportBuffer[]; + double tkiStateBuffer[]; + double swingLowBuffer[]; + double swingHighBuffer[]; + double resistanceBuffer[]; + double peakGoldenBuffer[]; + double valeGoldenBuffer[]; + double fiboLevel1Buffer[]; + double fiboLevel2Buffer[]; + double fiboLevel3Buffer[]; + double trendStateBuffer[]; + + // + // Conditions ... + + // + // KI ... + + // + bool isKIRejectUp; + bool isKIRejectDown; + + // + bool isKIBullish; + bool isKIBearish; + + // + bool isKISwitchedToBullish; + bool isKISwitchedToBearish; + + // + // TKI ... + + // + bool isTKIRejectUp; + bool isTKIRejectDown; + + // + bool isTKIBullish; + bool isTKIBearish; + + // + bool isTKISwitchedToBullish; + bool isTKISwitchedToBearish; + + // + // SAR ... + + // + bool isSarBullish; + bool isSarBearish; + + // + bool isSarSwitchedToBullish; + bool isSarSwitchedToBearish; + + // + // PEAK ... + + // + bool isPeakSameLast; + bool isPeakOverLast; + bool isPeakUnderLast; + + // + // VALE ... + + // + bool isValeSameLast; + bool isValeOverLast; + bool isValeUnderLast; + + // + // TREND ... + + // + bool isTrendRejectUp; + bool isTrendRejectDown; + + // + bool isTrendBullish; + bool isTrendBearish; + + // + bool isTrendSwitchedToBullish; + bool isTrendSwitchedToBearish; + + // + // SUPPORT ... + + // + bool isSupportSameLast; + bool isSupportOverLast; + bool isSupportUnderLast; + + // + bool isLastSupportBreaked; + bool isLastSupportRejected; + + // + // RESISTANCE ... + + // + bool isResistanceSameLast; + bool isResistanceOverLast; + bool isResistanceUnderLast; + + // + bool isLastResistanceBreaked; + bool isLastResistanceRejected; + + // + // SWING Low ... + + // + bool isSwingLowSameLast; + bool isSwingLowOverLast; + bool isSwingLowUnderLast; + + // + bool isLastSwingLowBreaked; + bool isLastSwingLowRejected; + + // + // SWING High ... + + // + bool isSwingHighSameLast; + bool isSwingHighOverLast; + bool isSwingHighUnderLast; + + // + bool isLastSwingHighBreaked; + bool isLastSwingHighRejected; + + // + // COMPLEX Conditions ... + + // + bool isPeakIsPivot; + bool isValeIsPivot; + + // + bool isSwingLowSameAsVale; + bool isSwingHighSameAsPeak; + + // + bool isSupportSameAsVale; + bool isResistanceSameAsPeak; + + // + bool isSupportSameAsSwingLow; + bool isResistanceSameAsSwingHigh; + + // + // Constructor ... + X121XCAConditions() + { + Clean(); + } + + // + // Tools ... + + /** + * Cleaning Up ... + */ + void Clean() + { + // + // Commons ... + symbol = NULL; + period = NULL; + time = NULL; + + // + // Buffers ... + + // + Clean(kiBuffer); + Clean(tkiBuffer); + Clean(sHHBuffer); + Clean(sLLBuffer); + Clean(mHHBuffer); + Clean(mLLBuffer); + Clean(lHHBuffer); + Clean(lLLBuffer); + Clean(hHHBuffer); + Clean(hLLBuffer); + Clean(sarBuffer); + Clean(peakBuffer); + Clean(valeBuffer); + Clean(trendBuffer); + Clean(kiStateBuffer); + Clean(supportBuffer); + Clean(tkiStateBuffer); + Clean(swingLowBuffer); + Clean(swingHighBuffer); + Clean(resistanceBuffer); + Clean(peakGoldenBuffer); + Clean(valeGoldenBuffer); + Clean(fiboLevel1Buffer); + Clean(fiboLevel2Buffer); + Clean(fiboLevel3Buffer); + Clean(trendStateBuffer); + + // + ArraySetAsSeries(kiBuffer, true); + ArraySetAsSeries(tkiBuffer, true); + ArraySetAsSeries(sHHBuffer, true); + ArraySetAsSeries(sLLBuffer, true); + ArraySetAsSeries(mHHBuffer, true); + ArraySetAsSeries(mLLBuffer, true); + ArraySetAsSeries(lHHBuffer, true); + ArraySetAsSeries(lLLBuffer, true); + ArraySetAsSeries(hHHBuffer, true); + ArraySetAsSeries(hLLBuffer, true); + ArraySetAsSeries(sarBuffer, true); + ArraySetAsSeries(peakBuffer, true); + ArraySetAsSeries(valeBuffer, true); + ArraySetAsSeries(trendBuffer, true); + ArraySetAsSeries(kiStateBuffer, true); + ArraySetAsSeries(supportBuffer, true); + ArraySetAsSeries(tkiStateBuffer, true); + ArraySetAsSeries(swingLowBuffer, true); + ArraySetAsSeries(swingHighBuffer, true); + ArraySetAsSeries(resistanceBuffer, true); + ArraySetAsSeries(peakGoldenBuffer, true); + ArraySetAsSeries(valeGoldenBuffer, true); + ArraySetAsSeries(fiboLevel1Buffer, true); + ArraySetAsSeries(fiboLevel2Buffer, true); + ArraySetAsSeries(fiboLevel3Buffer, true); + ArraySetAsSeries(trendStateBuffer, true); + + // + // Conditions ... + + // + // KI ... + + // + isKIRejectUp = false; + isKIRejectDown = false; + + // + isKIBullish = false; + isKIBearish = false; + + // + isKISwitchedToBullish = false; + isKISwitchedToBearish = false; + + // + // TKI ... + + // + isTKIRejectUp = false; + isTKIRejectDown = false; + + // + isTKIBullish = false; + isTKIBearish = false; + + // + isTKISwitchedToBullish = false; + isTKISwitchedToBearish = false; + + // + // SAR ... + + // + isSarBullish = false; + isSarBearish = false; + + // + isSarSwitchedToBullish = false; + isSarSwitchedToBearish = false; + + // + // PEAK ... + + // + isPeakSameLast = false; + isPeakOverLast = false; + isPeakUnderLast = false; + + // + // VALE ... + + // + isValeSameLast = false; + isValeOverLast = false; + isValeUnderLast = false; + + // + // TREND ... + + // + isTrendRejectUp = false; + isTrendRejectDown = false; + + // + isTrendBullish = false; + isTrendBearish = false; + + // + isTrendSwitchedToBullish = false; + isTrendSwitchedToBearish = false; + + // + // SUPPORT ... + + // + isSupportSameLast = false; + isSupportOverLast = false; + isSupportUnderLast = false; + + // + isLastSupportBreaked = false; + isLastSupportRejected = false; + + // + // RESISTANCE ... + + // + isResistanceSameLast = false; + isResistanceOverLast = false; + isResistanceUnderLast = false; + + // + isLastResistanceBreaked = false; + isLastResistanceRejected = false; + + // + // SWING Low ... + + // + isSwingLowSameLast = false; + isSwingLowOverLast = false; + isSwingLowUnderLast = false; + + // + isLastSwingLowBreaked = false; + isLastSwingLowRejected = false; + + // + // SWING High ... + + // + isSwingHighSameLast = false; + isSwingHighOverLast = false; + isSwingHighUnderLast = false; + + // + isLastSwingHighBreaked = false; + isLastSwingHighRejected = false; + + // + // COMPLEX Conditions ... + + // + isPeakIsPivot = false; + isValeIsPivot = false; + + // + isSwingLowSameAsVale = false; + isSwingHighSameAsPeak = false; + + // + isSupportSameAsVale = false; + isResistanceSameAsPeak = false; + + // + isSupportSameAsSwingLow = false; + isResistanceSameAsSwingHigh = false; + + // + ZeroMemory(this); + } + + /** + * Generate Conditions Scores ... + * + * @param bullishScore: Double, Directional Scores Reference ... + * @param bearishScore: Double, Directional Scores Reference ... + */ + void GenerateScore( + double &bullishScore, + double &bearishScore // + ) + { + // + bullishScore = 0; + bearishScore = 0; + + // + double score = 1; + double minScore = 0.5; + double highScore = 1.5; + + // + // KI ... + + // + if (isKIBullish) + { + bullishScore += minScore; + } + if (isKIRejectUp) + { + bullishScore += minScore; + } + if (isKISwitchedToBullish) + { + bullishScore += minScore; + } + + // + if (isKIBearish) + { + bearishScore += minScore; + } + if (isKIRejectDown) + { + bearishScore += minScore; + } + if (isKISwitchedToBearish) + { + bearishScore += minScore; + } + + // + // TKI ... + + // + if (isTKIBullish) + { + bullishScore += minScore; + } + if (isTKIRejectUp) + { + bullishScore += minScore; + } + if (isTKISwitchedToBullish) + { + bullishScore += minScore; + } + + // + if (isTKIBearish) + { + bearishScore += minScore; + } + if (isTKIRejectDown) + { + bearishScore += minScore; + } + if (isTKISwitchedToBearish) + { + bearishScore += minScore; + } + + // + // SAR ... + + // + if (isSarBullish) + { + bullishScore += minScore; + } + if (isSarSwitchedToBullish) + { + bullishScore += minScore; + } + + // + if (isSarBearish) + { + bearishScore += minScore; + } + if (isSarSwitchedToBearish) + { + bearishScore += minScore; + } + + // + // TREND ... + + // + if (isTrendBullish) + { + bullishScore += minScore; + } + if (isTrendRejectUp) + { + bullishScore += minScore; + } + if (isTrendSwitchedToBullish) + { + bullishScore += minScore; + } + + // + if (isTrendBearish) + { + bearishScore += minScore; + } + if (isTrendRejectDown) + { + bearishScore += minScore; + } + if (isTrendSwitchedToBearish) + { + bearishScore += minScore; + } + + // + // SUPPORT ... + + // + if (isSupportSameLast) + { + bullishScore += minScore; + } + if (isSupportOverLast) + { + bullishScore += minScore; + } + if (isLastSupportRejected) + { + bullishScore += minScore; + } + + // + if (isSupportUnderLast) + { + bearishScore += minScore; + } + if (isLastSupportBreaked) + { + bearishScore += minScore; + } + + // + // RESISTANCE ... + + // + if (isResistanceOverLast) + { + bullishScore += minScore; + } + if (isLastResistanceBreaked) + { + bullishScore += minScore; + } + + // + if (isResistanceSameLast) + { + bearishScore += minScore; + } + if (isResistanceUnderLast) + { + bearishScore += minScore; + } + if (isLastResistanceRejected) + { + bearishScore += minScore; + } + + // + // SWING Low ... + + // + if (isSwingLowSameLast) + { + bullishScore += minScore; + } + if (isSwingLowOverLast) + { + bullishScore += minScore; + } + if (isLastSwingLowRejected) + { + bullishScore += minScore; + } + + // + if (isSwingLowUnderLast) + { + bearishScore += minScore; + } + if (isLastSwingLowBreaked) + { + bearishScore += minScore; + } + + // + // SWING High ... + + // + if (isSwingHighOverLast) + { + bullishScore += minScore; + } + if (isLastSwingHighBreaked) + { + bullishScore += minScore; + } + + // + if (isSwingHighSameLast) + { + bearishScore += minScore; + } + if (isSwingHighUnderLast) + { + bearishScore += minScore; + } + if (isLastSwingHighRejected) + { + bearishScore += minScore; + } + + // + // COMPLEX Conditions ... + + // + if (isValeIsPivot) + { + bullishScore += score; + } + if (isSupportSameAsVale) + { + bullishScore += score; + } + if (isSwingLowSameAsVale) + { + bullishScore += score; + } + if (isSupportSameAsSwingLow) + { + bullishScore += score; + } + + // + if (isPeakIsPivot) + { + bearishScore += score; + } + if (isSwingHighSameAsPeak) + { + bearishScore += score; + } + if (isResistanceSameAsPeak) + { + bearishScore += score; + } + if (isResistanceSameAsSwingHigh) + { + bearishScore += score; + } + + // + } + + /** + * Generate Summary String for Represent Conditions State ... + * + * @param onlyCommons: Boolean, Just Generate Only Commons Conditions ... + * @param onlyConditions: Boolean, Just Generate Only Conditions ... + * @param includeScores: Boolean, Attach Scores Representations on Result ... + * @param ignoreFalseConditions: Boolean, Ignore False Conditions on Result ... + * @param separator: String, Separate Lines ... + * + * @return ( string ) + */ + string GenerateSummary( + bool onlyCommons = false, + bool onlyConditions = false, + bool includeScores = true, + bool ignoreFalseConditions = true, + string separator = "\n" // + ) + { + // + string result = NULL; + + // + double bullishScore = 0; + double bearishScore = 0; + GenerateScore( + bullishScore, + bearishScore // + ); + + // + string scoresStr = + // + "Scores: " + separator + + "---------------" + separator + + "Bullish: " + ToString(bullishScore) + separator + + "Bearish: " + ToString(bearishScore) + separator + + "" + // + ; + + // + string commonStr = GenerateSpecifiedCommonSummary( + this, + separator, + includeScores // + ); + + // + string conditionsStr = + // + "-----------------------" + separator + + "XCA: " + separator + + "-----------------------" + separator + + ToString("isKIRejectUp", isKIRejectUp, ignoreFalseConditions, separator) + + ToString("isKIRejectDown", isKIRejectDown, ignoreFalseConditions, separator) + + ToString("isKIBullish", isKIBullish, ignoreFalseConditions, separator) + + ToString("isKIBearish", isKIBearish, ignoreFalseConditions, separator) + + ToString("isKISwitchedToBullish", isKISwitchedToBullish, ignoreFalseConditions, separator) + + ToString("isKISwitchedToBearish", isKISwitchedToBearish, ignoreFalseConditions, separator) + + ToString("isTKIRejectUp", isTKIRejectUp, ignoreFalseConditions, separator) + + ToString("isTKIRejectDown", isTKIRejectDown, ignoreFalseConditions, separator) + + ToString("isTKIBullish", isTKIBullish, ignoreFalseConditions, separator) + + ToString("isTKIBearish", isTKIBearish, ignoreFalseConditions, separator) + + ToString("isTKISwitchedToBullish", isTKISwitchedToBullish, ignoreFalseConditions, separator) + + ToString("isTKISwitchedToBearish", isTKISwitchedToBearish, ignoreFalseConditions, separator) + + ToString("isSarBullish", isSarBullish, ignoreFalseConditions, separator) + + ToString("isSarBearish", isSarBearish, ignoreFalseConditions, separator) + + ToString("isSarSwitchedToBullish", isSarSwitchedToBullish, ignoreFalseConditions, separator) + + ToString("isSarSwitchedToBearish", isSarSwitchedToBearish, ignoreFalseConditions, separator) + + ToString("isPeakSameLast", isPeakSameLast, ignoreFalseConditions, separator) + + ToString("isPeakOverLast", isPeakOverLast, ignoreFalseConditions, separator) + + ToString("isPeakUnderLast", isPeakUnderLast, ignoreFalseConditions, separator) + + ToString("isValeSameLast", isValeSameLast, ignoreFalseConditions, separator) + + ToString("isValeOverLast", isValeOverLast, ignoreFalseConditions, separator) + + ToString("isValeUnderLast", isValeUnderLast, ignoreFalseConditions, separator) + + ToString("isTrendRejectUp", isTrendRejectUp, ignoreFalseConditions, separator) + + ToString("isTrendRejectDown", isTrendRejectDown, ignoreFalseConditions, separator) + + ToString("isTrendBullish", isTrendBullish, ignoreFalseConditions, separator) + + ToString("isTrendBearish", isTrendBearish, ignoreFalseConditions, separator) + + ToString("isTrendSwitchedToBullish", isTrendSwitchedToBullish, ignoreFalseConditions, separator) + + ToString("isTrendSwitchedToBearish", isTrendSwitchedToBearish, ignoreFalseConditions, separator) + + ToString("isSupportSameLast", isSupportSameLast, ignoreFalseConditions, separator) + + ToString("isSupportOverLast", isSupportOverLast, ignoreFalseConditions, separator) + + ToString("isSupportUnderLast", isSupportUnderLast, ignoreFalseConditions, separator) + + ToString("isLastSupportBreaked", isLastSupportBreaked, ignoreFalseConditions, separator) + + ToString("isLastSupportRejected", isLastSupportRejected, ignoreFalseConditions, separator) + + ToString("isResistanceSameLast", isResistanceSameLast, ignoreFalseConditions, separator) + + ToString("isResistanceOverLast", isResistanceOverLast, ignoreFalseConditions, separator) + + ToString("isResistanceUnderLast", isResistanceUnderLast, ignoreFalseConditions, separator) + + ToString("isLastResistanceBreaked", isLastResistanceBreaked, ignoreFalseConditions, separator) + + ToString("isLastResistanceRejected", isLastResistanceRejected, ignoreFalseConditions, separator) + + ToString("isSwingLowSameLast", isSwingLowSameLast, ignoreFalseConditions, separator) + + ToString("isSwingLowOverLast", isSwingLowOverLast, ignoreFalseConditions, separator) + + ToString("isSwingLowUnderLast", isSwingLowUnderLast, ignoreFalseConditions, separator) + + ToString("isLastSwingLowBreaked", isLastSwingLowBreaked, ignoreFalseConditions, separator) + + ToString("isLastSwingLowRejected", isLastSwingLowRejected, ignoreFalseConditions, separator) + + ToString("isSwingHighSameLast", isSwingHighSameLast, ignoreFalseConditions, separator) + + ToString("isSwingHighOverLast", isSwingHighOverLast, ignoreFalseConditions, separator) + + ToString("isSwingHighUnderLast", isSwingHighUnderLast, ignoreFalseConditions, separator) + + ToString("isLastSwingHighBreaked", isLastSwingHighBreaked, ignoreFalseConditions, separator) + + ToString("isLastSwingHighRejected", isLastSwingHighRejected, ignoreFalseConditions, separator) + + ToString("isPeakIsPivot", isPeakIsPivot, ignoreFalseConditions, separator) + + ToString("isValeIsPivot", isValeIsPivot, ignoreFalseConditions, separator) + + ToString("isSwingLowSameAsVale", isSwingLowSameAsVale, ignoreFalseConditions, separator) + + ToString("isSwingHighSameAsPeak", isSwingHighSameAsPeak, ignoreFalseConditions, separator) + + ToString("isSupportSameAsVale", isSupportSameAsVale, ignoreFalseConditions, separator) + + ToString("isResistanceSameAsPeak", isResistanceSameAsPeak, ignoreFalseConditions, separator) + + ToString("isSupportSameAsSwingLow", isSupportSameAsSwingLow, ignoreFalseConditions, separator) + + ToString("isResistanceSameAsSwingHigh", isResistanceSameAsSwingHigh, ignoreFalseConditions, separator) + + // + "" + // + ; + + // + result = + // + "[" + GetTag() + "]" + separator + + (onlyConditions + ? "" + : commonStr) + + (!includeScores + ? "" + : scoresStr) + + " " + separator + + (onlyCommons + ? "" + : conditionsStr) + + "" + // + ; + + // + return result; + } + + /** + * Retrieve nique Tag Identifier ... + * + * @return ( string ) + */ + string GetTag() + { + return GetTypeName(this); + } + + // +}; + +// +// Class ... +class XCX121XCAHelper : public XCBaseHelper +{ + // + // Public ... + public: + // + // Props ... + + // + // Constructors ... + XCX121XCAHelper() + : XCBaseHelper(_Symbol, _Period) + { + } + + // + // Deconstructor ... + ~XCX121XCAHelper() + { + // + mInputs.Clean(); + + // + Clean(kiBuffer); + Clean(tkiBuffer); + Clean(sHHBuffer); + Clean(sLLBuffer); + Clean(mHHBuffer); + Clean(mLLBuffer); + Clean(lHHBuffer); + Clean(lLLBuffer); + Clean(hHHBuffer); + Clean(hLLBuffer); + Clean(sarBuffer); + Clean(peakBuffer); + Clean(valeBuffer); + Clean(trendBuffer); + Clean(kiStateBuffer); + Clean(supportBuffer); + Clean(tkiStateBuffer); + Clean(swingLowBuffer); + Clean(swingHighBuffer); + Clean(resistanceBuffer); + Clean(peakGoldenBuffer); + Clean(valeGoldenBuffer); + Clean(fiboLevel1Buffer); + Clean(fiboLevel2Buffer); + Clean(fiboLevel3Buffer); + Clean(trendStateBuffer); + } + + // + // Tools ... + bool Init( + string symbol, // Trading Symbol + ENUM_TIMEFRAMES period, // Trading Period + X121XCAInputs &inputs // Inputs + ) + { + // + bool result = false; + + // + mSymbol = symbol; + mPeriod = period; + + // + result = inputs.IsValid(); + if (!result) + { + return result; + } + + // + ArraySetAsSeries(kiBuffer, true); + ArraySetAsSeries(tkiBuffer, true); + ArraySetAsSeries(sHHBuffer, true); + ArraySetAsSeries(sLLBuffer, true); + ArraySetAsSeries(mHHBuffer, true); + ArraySetAsSeries(mLLBuffer, true); + ArraySetAsSeries(lHHBuffer, true); + ArraySetAsSeries(lLLBuffer, true); + ArraySetAsSeries(hHHBuffer, true); + ArraySetAsSeries(hLLBuffer, true); + ArraySetAsSeries(sarBuffer, true); + ArraySetAsSeries(peakBuffer, true); + ArraySetAsSeries(valeBuffer, true); + ArraySetAsSeries(trendBuffer, true); + ArraySetAsSeries(kiStateBuffer, true); + ArraySetAsSeries(supportBuffer, true); + ArraySetAsSeries(tkiStateBuffer, true); + ArraySetAsSeries(swingLowBuffer, true); + ArraySetAsSeries(swingHighBuffer, true); + ArraySetAsSeries(resistanceBuffer, true); + ArraySetAsSeries(peakGoldenBuffer, true); + ArraySetAsSeries(valeGoldenBuffer, true); + ArraySetAsSeries(fiboLevel1Buffer, true); + ArraySetAsSeries(fiboLevel2Buffer, true); + ArraySetAsSeries(fiboLevel3Buffer, true); + ArraySetAsSeries(trendStateBuffer, true); + + // + mInputs = inputs; + + // + mHandler = iCustom( + mSymbol, + mPeriod, + "x-saherelm.x121.xca", + "", // Market ... + "", // Short ... + mInputs.scMethod, + mInputs.scPeriod, + "", // Medium ... + mInputs.mcMethod, + mInputs.mcPeriod, + "", // Long ... + mInputs.lcMethod, + mInputs.lcPeriod, + "", // Hind ... + mInputs.hcMethod, + mInputs.hcPeriod, + "", // Boundary Detection ... + mInputs.hhMode, + mInputs.llMode, + "", // Fibo Levels ... + mInputs.fiboLevel1, + mInputs.fiboLevel2, + mInputs.fiboLevel3, + "", // Sar Detection ... + mInputs.sarStep, + mInputs.sarMax, + "", // KI ... + mInputs.kiLength, + "", // Swing Detection ... + mInputs.swingLength, + "", // Support and Resistance ... + mInputs.supResSmoothingLength, + mInputs.supResSmoothingMode, + "", // Presentation ... + mInputs.startCalculationForLastBars, + mInputs.showSar, + mInputs.showKI, + mInputs.showTKI, + mInputs.showTrend, + mInputs.showSwings, + mInputs.showFiboLevel1, + mInputs.showFiboLevel2, + mInputs.showFiboLevel3, + mInputs.showPeaksAndVales, + mInputs.showPeakAndValeGolden, + mInputs.showSupportAndResistance, + mInputs.showShortCycle, + mInputs.showMediumCycle, + mInputs.showLongCycle, + mInputs.showHindCycle, + // + mInputs.sarArrowCode, + mInputs.peakArrowCode, + mInputs.valeArrowCode, + mInputs.swingLowArrowCode, + mInputs.swingHighArrowCode + // + ); + result = mHandler != INVALID_HANDLE; + if (!result) + { + return result; + } + + // + return result; + } + + // + // Inputs ... + + // + X121XCAInputs GetInputs() + { + return mInputs; + } + + // + bool SetInputs( + X121XCAInputs &inputs // Configs + ) + { + // + return Init( + mSymbol, + mPeriod, + inputs + // + ); + } + + // + // Readers ... + + // + // KI ... + + // + double GetKI( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(kiBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return kiBuffer[barIndex]; + } + + // + int CopyKI( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + kiBuffer, + buffer, + forceClean + // + ); + } + + // + // KI STATE ... + + // + double GetKIState( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(kiStateBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return kiStateBuffer[barIndex]; + } + + // + int CopyKIState( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + kiStateBuffer, + buffer, + forceClean + // + ); + } + + // + // TKI ... + + // + double GetTKI( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(tkiBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return tkiBuffer[barIndex]; + } + + // + int CopyTKI( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + tkiBuffer, + buffer, + forceClean + // + ); + } + + // + // TKI STATE ... + + // + double GetTKIState( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(tkiStateBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return tkiStateBuffer[barIndex]; + } + + // + int CopyTKIState( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + tkiStateBuffer, + buffer, + forceClean + // + ); + } + + // + // SHORT ... + + // + // HH ... + + // + double GetSHH( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(sHHBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return sHHBuffer[barIndex]; + } + + // + int CopySHH( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + sHHBuffer, + buffer, + forceClean + // + ); + } + + // + // LL ... + + // + double GetSLL( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(sLLBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return sLLBuffer[barIndex]; + } + + // + int CopySLL( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + sLLBuffer, + buffer, + forceClean + // + ); + } + + // + // MEDIUM ... + + // + // HH ... + + // + double GetMHH( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(mHHBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return mHHBuffer[barIndex]; + } + + // + int CopyMHH( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + mHHBuffer, + buffer, + forceClean + // + ); + } + + // + // LL ... + + // + double GetMLL( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(mLLBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return mLLBuffer[barIndex]; + } + + // + int CopyMLL( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + mLLBuffer, + buffer, + forceClean + // + ); + } + + // + // LONG ... + + // + // HH ... + + // + double GetLHH( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(lHHBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return lHHBuffer[barIndex]; + } + + // + int CopyLHH( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + lHHBuffer, + buffer, + forceClean + // + ); + } + + // + // LL ... + + // + double GetLLL( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(lLLBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return lLLBuffer[barIndex]; + } + + // + int CopyLLL( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + lLLBuffer, + buffer, + forceClean + // + ); + } + + // + // HIND ... + + // + // HH ... + + // + double GetHHH( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(hHHBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return hHHBuffer[barIndex]; + } + + // + int CopyHHH( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + hHHBuffer, + buffer, + forceClean + // + ); + } + + // + // LL ... + + // + double GetHLL( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(hLLBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return hLLBuffer[barIndex]; + } + + // + int CopyHLL( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + hLLBuffer, + buffer, + forceClean + // + ); + } + + // + // SAR ... + + // + double GetSar( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(sarBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return sarBuffer[barIndex]; + } + + // + int CopySar( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + sarBuffer, + buffer, + forceClean + // + ); + } + + // + // PEAK ... + + // + double GetPeak( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(peakBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return peakBuffer[barIndex]; + } + + // + int CopyPeak( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + peakBuffer, + buffer, + forceClean + // + ); + } + + // + // PEAK Golden ... + + // + double GetPeakGolden( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(peakGoldenBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return peakGoldenBuffer[barIndex]; + } + + // + int CopyPeakGolden( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + peakGoldenBuffer, + buffer, + forceClean + // + ); + } + + // + // VALE ... + + // + double GetVale( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(valeBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return valeBuffer[barIndex]; + } + + // + int CopyVale( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + valeBuffer, + buffer, + forceClean + // + ); + } + + // + // VALE Golden ... + + // + double GetValeGolden( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(valeGoldenBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return valeGoldenBuffer[barIndex]; + } + + // + int CopyValeGolden( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + valeGoldenBuffer, + buffer, + forceClean + // + ); + } + + // + // TREND ... + + // + double GetTrend( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(trendBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return trendBuffer[barIndex]; + } + + // + int CopyTrend( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + trendBuffer, + buffer, + forceClean + // + ); + } + + // + // TREND ... + + // + double GetTrendState( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(trendStateBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return trendStateBuffer[barIndex]; + } + + // + int CopyTrendState( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + trendStateBuffer, + buffer, + forceClean + // + ); + } + + // + // SUPPORT ... + + // + double GetSupport( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(supportBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return supportBuffer[barIndex]; + } + + // + int CopySupport( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + supportBuffer, + buffer, + forceClean + // + ); + } + + // + // RESISTANCE ... + + // + double GetResistance( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(resistanceBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return resistanceBuffer[barIndex]; + } + + // + int CopyResistance( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + resistanceBuffer, + buffer, + forceClean + // + ); + } + + // + // SWING Low ... + + // + double GetSwingLow( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(swingLowBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return swingLowBuffer[barIndex]; + } + + // + int CopySwingLow( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + swingLowBuffer, + buffer, + forceClean + // + ); + } + + // + // SWING High ... + + // + double GetSwingHigh( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(swingHighBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return swingHighBuffer[barIndex]; + } + + // + int CopySwingHigh( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + swingHighBuffer, + buffer, + forceClean + // + ); + } + + // + // FIBO Level 1 ... + + // + double GetFiboLevel1( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(fiboLevel1Buffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return fiboLevel1Buffer[barIndex]; + } + + // + int CopyFiboLevel1( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + fiboLevel1Buffer, + buffer, + forceClean + // + ); + } + + // + // FIBO Level 2 ... + + // + double GetFiboLevel2( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(fiboLevel2Buffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return fiboLevel2Buffer[barIndex]; + } + + // + int CopyFiboLevel2( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + fiboLevel2Buffer, + buffer, + forceClean + // + ); + } + + // + // FIBO Level 3 ... + + // + double GetFiboLevel3( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(fiboLevel3Buffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return fiboLevel3Buffer[barIndex]; + } + + // + int CopyFiboLevel3( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + fiboLevel3Buffer, + buffer, + forceClean + // + ); + } + + // + void Free() override + { + Cleanup(10); + } + + // + bool GetConditions( + X121XCAConditions &conditions, // + int barIndex = 0, // + int loopback = 5 // + ) + { + // + bool result = true; + + // + if (loopback < 5) + { + loopback = 5; + } + + // + conditions.Clean(); + + // + conditions.symbol = mSymbol; + conditions.period = mPeriod; + conditions.time = TimeCurrent(); + + // + int zIndex = barIndex; + int cIndex = zIndex + 1; + int pIndex = cIndex + 1; + int ppIndex = pIndex + 1; + + // + XOHCL zBar; + result = zBar.Init( + mSymbol, + mPeriod, + zIndex // + ); + if (!result) + { + return result; + } + + // + XOHCL cBar; + result = cBar.Init( + mSymbol, + mPeriod, + cIndex // + ); + if (!result) + { + return result; + } + + // + XOHCL pBar; + result = pBar.Init( + mSymbol, + mPeriod, + pIndex // + ); + if (!result) + { + return result; + } + + // + // Buffers ... + + // + CopyKI( + zIndex, + loopback, + conditions.kiBuffer // + ); + + // + CopyKIState( + zIndex, + loopback, + conditions.kiStateBuffer // + ); + + // + CopyTKI( + zIndex, + loopback, + conditions.tkiBuffer // + ); + + // + CopyTKIState( + zIndex, + loopback, + conditions.tkiStateBuffer // + ); + + // + CopySHH( + zIndex, + loopback, + conditions.sHHBuffer // + ); + + // + CopySLL( + zIndex, + loopback, + conditions.sLLBuffer // + ); + + // + CopyMHH( + zIndex, + loopback, + conditions.mHHBuffer // + ); + + // + CopyMLL( + zIndex, + loopback, + conditions.mLLBuffer // + ); + + // + CopyLHH( + zIndex, + loopback, + conditions.lHHBuffer // + ); + + // + CopyLLL( + zIndex, + loopback, + conditions.lLLBuffer // + ); + + // + CopyHHH( + zIndex, + loopback, + conditions.hHHBuffer // + ); + + // + CopyHLL( + zIndex, + loopback, + conditions.hLLBuffer // + ); + + // + CopySar( + zIndex, + loopback, + conditions.sarBuffer // + ); + + // + CopyPeak( + zIndex, + loopback, + conditions.peakBuffer // + ); + + // + CopyPeakGolden( + zIndex, + loopback, + conditions.peakGoldenBuffer // + ); + + // + CopyVale( + zIndex, + loopback, + conditions.valeBuffer // + ); + + // + CopyValeGolden( + zIndex, + loopback, + conditions.valeGoldenBuffer // + ); + + // + CopyTrend( + zIndex, + loopback, + conditions.trendBuffer // + ); + + // + CopyTrendState( + zIndex, + loopback, + conditions.trendStateBuffer // + ); + + // + CopySupport( + zIndex, + loopback, + conditions.supportBuffer // + ); + + // + CopyResistance( + zIndex, + loopback, + conditions.resistanceBuffer // + ); + + // + CopySwingLow( + zIndex, + loopback, + conditions.swingLowBuffer // + ); + + // + CopySwingHigh( + zIndex, + loopback, + conditions.swingHighBuffer // + ); + + // + CopyFiboLevel1( + zIndex, + loopback, + conditions.fiboLevel1Buffer // + ); + + // + CopyFiboLevel2( + zIndex, + loopback, + conditions.fiboLevel2Buffer // + ); + + // + CopyFiboLevel3( + zIndex, + loopback, + conditions.fiboLevel3Buffer // + ); + + // + // Conditions ... + + // + int zIDX = 0; + int cIDX = 1; + int pIDX = cIDX + 1; + int p2IDX = pIDX + 1; + int p3IDX = p2IDX + 1; + int p4IDX = p3IDX + 1; + + // + // Calculate ... + + // + // KI ... + + // + double cKI = conditions.kiBuffer[cIDX]; + double pKI = conditions.kiBuffer[pIDX]; + double p2KI = conditions.kiBuffer[p2IDX]; + + // + double cKIState = conditions.kiStateBuffer[cIDX]; + double pKIState = conditions.kiStateBuffer[pIDX]; + double p2KIState = conditions.kiStateBuffer[p2IDX]; + + // + bool isKIRejectUp = cBar.IsRejected( + cKI, + X_DIRECTION_BULLISH, + false, + false // + ); + bool isKIRejectDown = cBar.IsRejected( + cKI, + X_DIRECTION_BEARISH, + false, + false // + ); + + // + bool isKIBullish = cKIState > 0; + bool isKIBullishPrev = pKIState > 0; + + // + bool isKIBearish = cKIState < 0; + bool isKIBearishPrev = pKIState < 0; + + // + bool isKISwitchedToBullish = isKIBullish && + !isKIBullishPrev; + bool isKISwitchedToBearish = isKIBearish && + !isKIBearishPrev; + + // + // TKI ... + + // + double cTKI = conditions.tkiBuffer[cIDX]; + double pTKI = conditions.tkiBuffer[pIDX]; + double p2TKI = conditions.tkiBuffer[p2IDX]; + + // + double cTKIState = conditions.tkiStateBuffer[cIDX]; + double pTKIState = conditions.tkiStateBuffer[pIDX]; + double p2TKIState = conditions.tkiStateBuffer[p2IDX]; + + // + bool isTKIRejectUp = cBar.IsRejected( + cTKI, + X_DIRECTION_BULLISH, + false, + false // + ); + bool isTKIRejectDown = cBar.IsRejected( + cTKI, + X_DIRECTION_BEARISH, + false, + false // + ); + + // + bool isTKIBullish = cTKIState > 0; + bool isTKIBullishPrev = pTKIState > 0; + + // + bool isTKIBearish = cTKIState < 0; + bool isTKIBearishPrev = pTKIState < 0; + + // + bool isTKISwitchedToBullish = isTKIBullish && + !isTKIBullishPrev; + bool isTKISwitchedToBearish = isTKIBearish && + !isTKIBearishPrev; + + // + // SAR ... + + // + double cSar = conditions.sarBuffer[cIDX]; + double pSar = conditions.sarBuffer[pIDX]; + + // + bool isSarBullish = cBar.low > cSar; + bool isSarBullishPrev = pBar.low > pSar; + + // + bool isSarBearish = cBar.high < cSar; + bool isSarBearishPrev = pBar.high < pSar; + + // + bool isSarSwitchedToBullish = isSarBullish && + !isSarBullishPrev; + bool isSarSwitchedToBearish = isSarBearish && + !isSarBearishPrev; + + // + // PEAK ... + + // + double cPeak = conditions.peakBuffer[cIDX]; + double pPeak = conditions.peakBuffer[pIDX]; + + // + bool isPeakSameLast = cPeak == pPeak; + bool isPeakOverLast = cPeak > pPeak; + bool isPeakUnderLast = cPeak < pPeak; + + // + // VALE ... + + // + double cVale = conditions.valeBuffer[cIDX]; + double pVale = conditions.valeBuffer[pIDX]; + + // + bool isValeSameLast = cVale == pVale; + bool isValeOverLast = cVale > pVale; + bool isValeUnderLast = cVale < pVale; + + // + // TREND ... + + // + double cTrend = conditions.trendBuffer[cIDX]; + double pTrend = conditions.trendBuffer[pIDX]; + + // + double cTrendState = conditions.trendStateBuffer[cIDX]; + double pTrendState = conditions.trendStateBuffer[pIDX]; + + // + bool isTrendRejectUp = cBar.IsRejected( + cTrend, + X_DIRECTION_BULLISH, + false, + false // + ); + bool isTrendRejectDown = cBar.IsRejected( + cTrend, + X_DIRECTION_BEARISH, + false, + false // + ); + + // + bool isTrendBullish = cTrendState > 0; + bool isTrendBullishPrev = pTrendState > 0; + + // + bool isTrendBearish = cTrendState < 0; + bool isTrendBearishPrev = pTrendState < 0; + + // + bool isTrendSwitchedToBullish = isTrendBullish && + !isTrendBullishPrev; + bool isTrendSwitchedToBearish = isTrendBearish && + !isTrendBearishPrev; + + // + // SUPPORT ... + + // + double cSupport = conditions.supportBuffer[cIDX]; + double pSupport = conditions.supportBuffer[pIDX]; + + // + bool isSupportSameLast = cSupport == pSupport; + bool isSupportOverLast = cSupport > pSupport; + bool isSupportUnderLast = cSupport < pSupport; + + // + bool isLastSupportBreaked = cBar.IsBreaked( + pSupport, + X_DIRECTION_BEARISH // + ); + bool isLastSupportRejected = cBar.IsRejected( + pSupport, + X_DIRECTION_BULLISH, + false, + false // + ); + + // + // RESISTANCE ... + + // + double cResistance = conditions.resistanceBuffer[cIDX]; + double pResistance = conditions.resistanceBuffer[pIDX]; + + // + bool isResistanceSameLast = cResistance == pResistance; + bool isResistanceOverLast = cResistance > pResistance; + bool isResistanceUnderLast = cResistance < pResistance; + + // + bool isLastResistanceBreaked = cBar.IsBreaked( + pResistance, + X_DIRECTION_BULLISH // + ); + bool isLastResistanceRejected = cBar.IsRejected( + pResistance, + X_DIRECTION_BEARISH, + false, + false // + ); + + // + // SWING Low ... + + // + double cSwingLow = conditions.swingLowBuffer[cIDX]; + double pSwingLow = conditions.swingLowBuffer[pIDX]; + + // + bool isSwingLowSameLast = cSwingLow == pSwingLow; + bool isSwingLowOverLast = cSwingLow > pSwingLow; + bool isSwingLowUnderLast = cSwingLow < pSwingLow; + + // + bool isLastSwingLowBreaked = cBar.IsBreaked( + pSwingLow, + X_DIRECTION_BEARISH // + ); + bool isLastSwingLowRejected = cBar.IsRejected( + pSwingLow, + X_DIRECTION_BULLISH, + false, + false // + ); + + // + // SWING High ... + + // + double cSwingHigh = conditions.swingHighBuffer[cIDX]; + double pSwingHigh = conditions.swingHighBuffer[pIDX]; + + // + bool isSwingHighSameLast = cSwingHigh == pSwingHigh; + bool isSwingHighOverLast = cSwingHigh > pSwingHigh; + bool isSwingHighUnderLast = cSwingHigh < pSwingHigh; + + // + bool isLastSwingHighBreaked = cBar.IsBreaked( + pSwingHigh, + X_DIRECTION_BULLISH // + ); + bool isLastSwingHighRejected = cBar.IsRejected( + pSwingHigh, + X_DIRECTION_BEARISH, + false, + false // + ); + + // + // COMPLEX Conditions ... + + // + bool isSwingLowSameAsVale = cSwingLow == cVale; + bool isSwingHighSameAsPeak = cSwingHigh == cPeak; + + // + bool isSupportSameAsVale = cSupport == cVale; + bool isResistanceSameAsPeak = cResistance == cPeak; + + // + bool isSupportSameAsSwingLow = cSupport == cSwingLow; + bool isResistanceSameAsSwingHigh = cResistance == cSwingHigh; + + // + bool isPeakIsPivot = isSwingHighSameAsPeak && + isResistanceSameAsPeak && + isResistanceSameAsSwingHigh; + bool isValeIsPivot = isSwingLowSameAsVale && + isSupportSameAsVale && + isSupportSameAsSwingLow; + + // + // Attached ... + + // + conditions.isKIBullish = isKIBullish; + conditions.isKIBearish = isKIBearish; + conditions.isKIRejectUp = isKIRejectUp; + conditions.isTKIBullish = isTKIBullish; + conditions.isTKIBearish = isTKIBearish; + conditions.isSarBullish = isSarBullish; + conditions.isSarBearish = isSarBearish; + conditions.isTKIRejectUp = isTKIRejectUp; + conditions.isPeakIsPivot = isPeakIsPivot; + conditions.isValeIsPivot = isValeIsPivot; + conditions.isKIRejectDown = isKIRejectDown; + conditions.isPeakSameLast = isPeakSameLast; + conditions.isPeakOverLast = isPeakOverLast; + conditions.isValeSameLast = isValeSameLast; + conditions.isValeOverLast = isValeOverLast; + conditions.isTrendBullish = isTrendBullish; + conditions.isTrendBearish = isTrendBearish; + conditions.isTKIRejectDown = isTKIRejectDown; + conditions.isPeakUnderLast = isPeakUnderLast; + conditions.isValeUnderLast = isValeUnderLast; + conditions.isTrendRejectUp = isTrendRejectUp; + conditions.isTrendRejectDown = isTrendRejectDown; + conditions.isSupportSameLast = isSupportSameLast; + conditions.isSupportOverLast = isSupportOverLast; + conditions.isSupportUnderLast = isSupportUnderLast; + conditions.isSwingLowSameLast = isSwingLowSameLast; + conditions.isSwingLowOverLast = isSwingLowOverLast; + conditions.isSwingLowUnderLast = isSwingLowUnderLast; + conditions.isSwingHighSameLast = isSwingHighSameLast; + conditions.isSwingHighOverLast = isSwingHighOverLast; + conditions.isSupportSameAsVale = isSupportSameAsVale; + conditions.isLastSupportBreaked = isLastSupportBreaked; + conditions.isResistanceSameLast = isResistanceSameLast; + conditions.isResistanceOverLast = isResistanceOverLast; + conditions.isSwingHighUnderLast = isSwingHighUnderLast; + conditions.isSwingLowSameAsVale = isSwingLowSameAsVale; + conditions.isLastSupportRejected = isLastSupportRejected; + conditions.isResistanceUnderLast = isResistanceUnderLast; + conditions.isKISwitchedToBullish = isKISwitchedToBullish; + conditions.isKISwitchedToBearish = isKISwitchedToBearish; + conditions.isLastSwingLowBreaked = isLastSwingLowBreaked; + conditions.isSwingHighSameAsPeak = isSwingHighSameAsPeak; + conditions.isTKISwitchedToBullish = isTKISwitchedToBullish; + conditions.isTKISwitchedToBearish = isTKISwitchedToBearish; + conditions.isLastSwingLowRejected = isLastSwingLowRejected; + conditions.isSarSwitchedToBullish = isSarSwitchedToBullish; + conditions.isSarSwitchedToBearish = isSarSwitchedToBearish; + conditions.isLastSwingHighBreaked = isLastSwingHighBreaked; + conditions.isResistanceSameAsPeak = isResistanceSameAsPeak; + conditions.isLastSwingHighRejected = isLastSwingHighRejected; + conditions.isLastResistanceBreaked = isLastResistanceBreaked; + conditions.isSupportSameAsSwingLow = isSupportSameAsSwingLow; + conditions.isLastResistanceRejected = isLastResistanceRejected; + conditions.isTrendSwitchedToBullish = isTrendSwitchedToBullish; + conditions.isTrendSwitchedToBearish = isTrendSwitchedToBearish; + conditions.isResistanceSameAsSwingHigh = isResistanceSameAsSwingHigh; + + // + Cleanup(); + + // + zBar.Clean(); + cBar.Clean(); + pBar.Clean(); + + // + return result; + } + + // + // Protected ... + protected: + // + // Private ... + private: + // + // Props ... + X121XCAInputs mInputs; // Inputs ... + + // + // Buffers ... + double kiBuffer[]; + double tkiBuffer[]; + double sHHBuffer[]; + double sLLBuffer[]; + double mHHBuffer[]; + double mLLBuffer[]; + double lHHBuffer[]; + double lLLBuffer[]; + double hHHBuffer[]; + double hLLBuffer[]; + double sarBuffer[]; + double peakBuffer[]; + double valeBuffer[]; + double trendBuffer[]; + double kiStateBuffer[]; + double supportBuffer[]; + double tkiStateBuffer[]; + double swingLowBuffer[]; + double swingHighBuffer[]; + double resistanceBuffer[]; + double peakGoldenBuffer[]; + double valeGoldenBuffer[]; + double fiboLevel1Buffer[]; + double fiboLevel2Buffer[]; + double fiboLevel3Buffer[]; + double trendStateBuffer[]; + + // + void Calculate( + int barIndex = 0, + int maxRequiredBars = 100 // + ) + { + // + // Buffers ... + if (barIndex < 0) + { + barIndex = 0; + } + + // + CopyBuffer( + mHandler, + X121_XCA_KI_LINE, + barIndex, + maxRequiredBars, + kiBuffer // + ); + + // + CopyBuffer( + mHandler, + X121_XCA_TKI_LINE, + barIndex, + maxRequiredBars, + tkiBuffer // + ); + + // + CopyBuffer( + mHandler, + X121_XCA_S_HH_LINE, + barIndex, + maxRequiredBars, + sHHBuffer // + ); + + // + CopyBuffer( + mHandler, + X121_XCA_S_LL_LINE, + barIndex, + maxRequiredBars, + sLLBuffer // + ); + + // + CopyBuffer( + mHandler, + X121_XCA_M_HH_LINE, + barIndex, + maxRequiredBars, + mHHBuffer // + ); + + // + CopyBuffer( + mHandler, + X121_XCA_M_LL_LINE, + barIndex, + maxRequiredBars, + mLLBuffer // + ); + + // + CopyBuffer( + mHandler, + X121_XCA_L_HH_LINE, + barIndex, + maxRequiredBars, + lHHBuffer // + ); + + // + CopyBuffer( + mHandler, + X121_XCA_L_LL_LINE, + barIndex, + maxRequiredBars, + lLLBuffer // + ); + + // + CopyBuffer( + mHandler, + X121_XCA_H_HH_LINE, + barIndex, + maxRequiredBars, + hHHBuffer // + ); + + // + CopyBuffer( + mHandler, + X121_XCA_H_LL_LINE, + barIndex, + maxRequiredBars, + hLLBuffer // + ); + + // + CopyBuffer( + mHandler, + X121_XCA_SAR_LINE, + barIndex, + maxRequiredBars, + sarBuffer // + ); + + // + CopyBuffer( + mHandler, + X121_XCA_PEAK_LINE, + barIndex, + maxRequiredBars, + peakBuffer // + ); + + // + CopyBuffer( + mHandler, + X121_XCA_VALE_LINE, + barIndex, + maxRequiredBars, + valeBuffer // + ); + + // + CopyBuffer( + mHandler, + X121_XCA_TREND_LINE, + barIndex, + maxRequiredBars, + trendBuffer // + ); + + // + CopyBuffer( + mHandler, + X121_XCA_KI_STATE_LINE, + barIndex, + maxRequiredBars, + kiStateBuffer // + ); + + // + CopyBuffer( + mHandler, + X121_XCA_TKI_STATE_LINE, + barIndex, + maxRequiredBars, + tkiStateBuffer // + ); + + // + CopyBuffer( + mHandler, + X121_XCA_SUPPORT_LINE, + barIndex, + maxRequiredBars, + supportBuffer // + ); + + // + CopyBuffer( + mHandler, + X121_XCA_SWING_LOW_LINE, + barIndex, + maxRequiredBars, + swingLowBuffer // + ); + + // + CopyBuffer( + mHandler, + X121_XCA_SWING_HIGH_LINE, + barIndex, + maxRequiredBars, + swingHighBuffer // + ); + + // + CopyBuffer( + mHandler, + X121_XCA_RESISTANCE_LINE, + barIndex, + maxRequiredBars, + resistanceBuffer // + ); + + // + CopyBuffer( + mHandler, + X121_XCA_PEAK_GOLDEN_LINE, + barIndex, + maxRequiredBars, + peakGoldenBuffer // + ); + + // + CopyBuffer( + mHandler, + X121_XCA_VALE_GOLDEN_LINE, + barIndex, + maxRequiredBars, + valeGoldenBuffer // + ); + + // + CopyBuffer( + mHandler, + X121_XCA_FIBO_L1_LINE, + barIndex, + maxRequiredBars, + fiboLevel1Buffer // + ); + + // + CopyBuffer( + mHandler, + X121_XCA_FIBO_L2_LINE, + barIndex, + maxRequiredBars, + fiboLevel2Buffer // + ); + + // + CopyBuffer( + mHandler, + X121_XCA_FIBO_L3_LINE, + barIndex, + maxRequiredBars, + fiboLevel3Buffer // + ); + + // + CopyBuffer( + mHandler, + X121_XCA_TREND_STATE_LINE, + barIndex, + maxRequiredBars, + trendStateBuffer // + ); + } + + // + void Cleanup( + int maxAllowed = 100 // + ) + { + // + CleanupArray( + kiBuffer, + maxAllowed // + ); + + // + CleanupArray( + tkiBuffer, + maxAllowed // + ); + + // + CleanupArray( + sHHBuffer, + maxAllowed // + ); + + // + CleanupArray( + sLLBuffer, + maxAllowed // + ); + + // + CleanupArray( + mHHBuffer, + maxAllowed // + ); + + // + CleanupArray( + mLLBuffer, + maxAllowed // + ); + + // + CleanupArray( + lHHBuffer, + maxAllowed // + ); + + // + CleanupArray( + lLLBuffer, + maxAllowed // + ); + + // + CleanupArray( + hHHBuffer, + maxAllowed // + ); + + // + CleanupArray( + hLLBuffer, + maxAllowed // + ); + + // + CleanupArray( + sarBuffer, + maxAllowed // + ); + + // + CleanupArray( + peakBuffer, + maxAllowed // + ); + + // + CleanupArray( + valeBuffer, + maxAllowed // + ); + + // + CleanupArray( + trendBuffer, + maxAllowed // + ); + + // + CleanupArray( + kiStateBuffer, + maxAllowed // + ); + + // + CleanupArray( + tkiStateBuffer, + maxAllowed // + ); + + // + CleanupArray( + supportBuffer, + maxAllowed // + ); + + // + CleanupArray( + swingLowBuffer, + maxAllowed // + ); + + // + CleanupArray( + swingHighBuffer, + maxAllowed // + ); + + // + CleanupArray( + resistanceBuffer, + maxAllowed // + ); + + // + CleanupArray( + peakGoldenBuffer, + maxAllowed // + ); + + // + CleanupArray( + valeGoldenBuffer, + maxAllowed // + ); + + // + CleanupArray( + fiboLevel1Buffer, + maxAllowed // + ); + + // + CleanupArray( + fiboLevel2Buffer, + maxAllowed // + ); + + // + CleanupArray( + fiboLevel3Buffer, + maxAllowed // + ); + + // + CleanupArray( + trendStateBuffer, + maxAllowed // + ); + } + + // +}; + +// +// Tools ... \ No newline at end of file diff --git a/BKPS/14040203/Helpers/x-saherelm.x121.xcc.helper.mq5 b/BKPS/14040203/Helpers/x-saherelm.x121.xcc.helper.mq5 new file mode 100644 index 0000000..1663ae7 --- /dev/null +++ b/BKPS/14040203/Helpers/x-saherelm.x121.xcc.helper.mq5 @@ -0,0 +1,252 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Helper Class Library +// ---------------------------------------------- +// Name: XSCX121XCCHelper +// Description: provides all Indicator +// Helper requirements ... +// +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +////////////////////////////////////////////////////// +// +// Global Properties ... +#property library +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://www.saherelm.ir" +#property version "1.00" +#property strict + +// +// Imports ... +#include "../Classes/x-saherelm.x-helper.class.mq5" + +// +// Definitions ... + +// +// Input Models ... +struct X121XCCInputs +{ + // + // Props ... + + // + // Chart Style ... + ENUM_CHART_MODE mode; // Mode + color upColor; // Up Color + color downColor; // Down Color + color lineColor; // Line mode and Doji candlestick Color + color bearishColor; // Bullish Color + color bullishColor; // Bearish Color + color volumesColor; // Volumes Color + + // + // Presentation ... + bool showCandles; // Show Candles + + // + // Constructor(s) ... + X121XCCInputs() + { + // + Clean(); + } + + // + // Tools ... + + // + // Clean ... + void Clean() + { + // + mode = CHART_CANDLES; + + // + upColor = CLR_NONE; + downColor = CLR_NONE; + lineColor = CLR_NONE; + bearishColor = CLR_NONE; + bullishColor = CLR_NONE; + volumesColor = CLR_NONE; + + // + showCandles = false; + + // + ZeroMemory(this); + } + + // + // Default ... + void Default() + { + // + mode = CHART_CANDLES; + + // + upColor = clrLime; + downColor = clrRed; + lineColor = clrLime; + bearishColor = clrRed; + bullishColor = clrLime; + volumesColor = clrGreen; + // + showCandles = true; + } + + // + // Validate ... + bool IsValid() + { + // + bool result = false; + + // + result = + // + true + // + ; + + // + return result; + } + + // + // Retrieve MAx Length ... + int Max() + { + // + int result = 0; + + // + result = MathMax(0, 0); + + // + return result; + } +}; + +// +// Class ... +class XCX121XCCHelper : public XCBaseHelper +{ + // + // Public ... + public: + // + // Props ... + + // + // Constructors ... + XCX121XCCHelper() + : XCBaseHelper(_Symbol, _Period) + { + } + + // + // Deconstructor ... + ~XCX121XCCHelper() + { + mInputs.Clean(); + } + + // + // Tools ... + bool Init( + string symbol, // Trading Symbol + ENUM_TIMEFRAMES period, // Trading Period + X121XCCInputs &inputs // Inputs + ) + { + // + bool result = false; + + // + mSymbol = symbol; + mPeriod = period; + + // + result = inputs.IsValid(); + if (!result) + { + return result; + } + + // + mInputs = inputs; + + // + mHandler = iCustom( + mSymbol, + mPeriod, + "x-saherelm.x121.xcc", + // + // Inputs ... + // + // Chart Style ... + "", + mInputs.mode, // Mode + mInputs.upColor, // Up Color + mInputs.downColor, // Down Color + mInputs.lineColor, // Line mode and Doji candlestick Color + mInputs.bullishColor, // Bearish Color + mInputs.bearishColor, // Bullish Color + mInputs.volumesColor, // Volumes Color + // + // Presentation ... + "", + mInputs.showCandles // Show Candles + // + ); + result = mHandler != INVALID_HANDLE; + if (!result) + { + return result; + } + + // + return result; + } + + // + // Inputs ... + + // + X121XCCInputs GetInputs() + { + return mInputs; + } + + // + bool SetInputs( + X121XCCInputs &inputs // Configs + ) + { + // + return Init( + mSymbol, + mPeriod, + inputs + // + ); + } + + // + // Protected ... + protected: + // + // Private ... + private: + // + // Props ... + X121XCCInputs mInputs; // Inputs ... +}; + +// +// Tools ... \ No newline at end of file diff --git a/BKPS/14040203/Helpers/x-saherelm.x121.xche.helper.mq5 b/BKPS/14040203/Helpers/x-saherelm.x121.xche.helper.mq5 new file mode 100644 index 0000000..c1d0133 --- /dev/null +++ b/BKPS/14040203/Helpers/x-saherelm.x121.xche.helper.mq5 @@ -0,0 +1,1373 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Helper Class Library +// ---------------------------------------------- +// Name: XCX121XCHEHelper +// Description: provides all Indicator +// Helper requirements ... +// +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +////////////////////////////////////////////////////// +// +// Global Properties ... +#property library +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://www.saherelm.ir" +#property version "1.00" +#property strict + +// +// Imports ... +#include "../Classes/x-saherelm.x-helper.class.mq5" + +// +// Definitions ... + +// +// Definitions ... +enum ENUM_X121_XCHE_BUFFERS +{ + // + X121_XCHE_LE_1_LINE = 0, + X121_XCHE_SE_1_LINE = 1, + X121_XCHE_LE_2_LINE = 2, + X121_XCHE_SE_2_LINE = 3, + X121_XCHE_LE_1_S_LINE = 4, + X121_XCHE_SE_1_S_LINE = 5, + X121_XCHE_LE_2_S_LINE = 6, + X121_XCHE_SE_2_S_LINE = 7, +}; + +// +// Input Models ... +struct X121XCHEInputs +{ + // + // Props ... + + int cheLength; // Length + int cheLoopback; // Loopback + double cheMultiplier1; // 1st Multiplier + double cheMultiplier2; // 2nd Multiplier + ENUM_APPLIED_PRICE cheUpperAppliedTo; // Upper Zone Applied to + ENUM_APPLIED_PRICE cheLowerAppliedTo; // Lower Zone Applied to + + // + int cheArrowCode; // CHE Arrow Code + + // + bool showLE1; // Show 1st Long Exit + bool showSE1; // Show 1st Short Exit + bool showLE2; // Show 2st Long Exit + bool showSE2; // Show 2st Short Exit + + // + // Constructor(s) ... + X121XCHEInputs() + { + // + Clean(); + } + + // + // Tools ... + + // + // Clean ... + void Clean() + { + // + cheLength = 0; + cheLoopback = 0; + cheMultiplier1 = 0; + cheMultiplier2 = 0; + cheUpperAppliedTo = PRICE_HIGH; + cheLowerAppliedTo = PRICE_LOW; + + // + cheArrowCode = 0; + + // + showLE1 = false; + showSE1 = false; + showLE2 = false; + showSE2 = false; + + // + ZeroMemory(this); + } + + // + // Default ... + void Default() + { + // + cheLength = 35; + cheLoopback = 26; + cheMultiplier1 = 3.0; + cheMultiplier2 = 3.5; + cheUpperAppliedTo = PRICE_HIGH; + cheLowerAppliedTo = PRICE_LOW; + + // + cheArrowCode = 159; + + // + showLE1 = true; + showSE1 = true; + showLE2 = true; + showSE2 = true; + } + + // + // Validate ... + bool IsValid() + { + // + bool result = true; + + // + result = + cheLength >= 9 && + cheLoopback >= 0; + + // + return result; + } + + // + // Retrieve MAx Length ... + int Max() + { + // + int result = 0; + + // + result = MathMax(cheLength, cheLoopback); + + // + return result; + } +}; + +// +// Conditions ... +struct X121XCHEConditions +{ + // + // Common ... + string symbol; + ENUM_TIMEFRAMES period; + datetime time; + + // + // Buffers ... + double le1Buffer[]; + double se1Buffer[]; + double le2Buffer[]; + double se2Buffer[]; + double le1StartBuffer[]; + double se1StartBuffer[]; + double le2StartBuffer[]; + double se2StartBuffer[]; + + // + // Conditions ... + + // + bool isChe1Bullish; + bool isChe1Bearish; + + // + bool isChe1SwitchedToBullish; + bool isChe1SwitchedToBearish; + + // + bool isChe2Bullish; + bool isChe2Bearish; + + // + bool isChe2SwitchedToBullish; + bool isChe2SwitchedToBearish; + + // + bool isCheBullish; + bool isCheBearish; + + // + bool isCheSwitchedToBullish; + bool isCheSwitchedToBearish; + + // + // Constructor ... + X121XCHEConditions() + { + Clean(); + } + + // + // Tools ... + + /** + * Cleaning Up ... + */ + void Clean() + { + // + // Commons ... + symbol = NULL; + period = NULL; + time = NULL; + + // + // Buffers ... + + // + Clean(le1Buffer); + Clean(se1Buffer); + Clean(le2Buffer); + Clean(se2Buffer); + Clean(le1StartBuffer); + Clean(se1StartBuffer); + Clean(le2StartBuffer); + Clean(se2StartBuffer); + + // + ArraySetAsSeries(le1Buffer, true); + ArraySetAsSeries(se1Buffer, true); + ArraySetAsSeries(le2Buffer, true); + ArraySetAsSeries(se2Buffer, true); + ArraySetAsSeries(le1StartBuffer, true); + ArraySetAsSeries(se1StartBuffer, true); + ArraySetAsSeries(le2StartBuffer, true); + ArraySetAsSeries(se2StartBuffer, true); + + // + // Conditions ... + + // + isChe1Bullish = false; + isChe1Bearish = false; + + // + isChe1SwitchedToBullish = false; + isChe1SwitchedToBearish = false; + + // + isChe2Bullish = false; + isChe2Bearish = false; + + // + isChe2SwitchedToBullish = false; + isChe2SwitchedToBearish = false; + + // + isCheBullish = false; + isCheBearish = false; + + // + isCheSwitchedToBullish = false; + isCheSwitchedToBearish = false; + + // + ZeroMemory(this); + } + + /** + * Generate Conditions Scores ... + * + * @param bullishScore: Double, Directional Scores Reference ... + * @param bearishScore: Double, Directional Scores Reference ... + */ + void GenerateScore( + double &bullishScore, + double &bearishScore // + ) + { + // + bullishScore = 0; + bearishScore = 0; + + // + double score = 1; + double minScore = 0.5; + double highScore = 1.5; + + // + // XCHE ... + + // + if (isCheBullish) + { + bullishScore += score; + } + if (isCheSwitchedToBullish) + { + bullishScore += highScore; + } + if (isChe1Bullish && + !isCheBullish && + !isCheSwitchedToBullish) + { + bullishScore += minScore; + } + if (isChe1SwitchedToBullish && + !isCheBullish && + !isCheSwitchedToBullish) + { + bullishScore += minScore; + } + + // + if (isCheBearish) + { + bearishScore += score; + } + if (isCheSwitchedToBearish) + { + bearishScore += highScore; + } + if (isChe1Bearish && + !isCheBearish && + !isCheSwitchedToBearish) + { + bearishScore += minScore; + } + if (isChe1SwitchedToBearish && + !isCheBearish && + !isCheSwitchedToBearish) + { + bearishScore += minScore; + } + } + + /** + * Generate Summary String for Represent Conditions State ... + * + * @param onlyCommons: Boolean, Just Generate Only Commons Conditions ... + * @param onlyConditions: Boolean, Just Generate Only Conditions ... + * @param includeScores: Boolean, Attach Scores Representations on Result ... + * @param ignoreFalseConditions: Boolean, Ignore False Conditions on Result ... + * @param separator: String, Separate Lines ... + * + * @return ( string ) + */ + string GenerateSummary( + bool onlyCommons = false, + bool onlyConditions = false, + bool includeScores = true, + bool ignoreFalseConditions = true, + string separator = "\n" // + ) + { + // + string result = NULL; + + // + double bullishScore = 0; + double bearishScore = 0; + GenerateScore( + bullishScore, + bearishScore // + ); + + // + string scoresStr = + // + "Scores: " + separator + + "---------------" + separator + + "Bullish: " + ToString(bullishScore) + separator + + "Bearish: " + ToString(bearishScore) + separator + + "" + // + ; + + // + string commonStr = GenerateSpecifiedCommonSummary( + this, + separator, + includeScores // + ); + + // + string conditionsStr = + // + "-----------------------" + separator + + "XCHE: " + separator + + "-----------------------" + separator + + ToString("isChe1Bullish", isChe1Bullish, ignoreFalseConditions, separator) + + ToString("isChe1Bearish", isChe1Bearish, ignoreFalseConditions, separator) + + ToString("isChe1SwitchedToBullish", isChe1SwitchedToBullish, ignoreFalseConditions, separator) + + ToString("isChe1SwitchedToBearish", isChe1SwitchedToBearish, ignoreFalseConditions, separator) + + ToString("isChe2Bullish", isChe2Bullish, ignoreFalseConditions, separator) + + ToString("isChe2Bearish", isChe2Bearish, ignoreFalseConditions, separator) + + ToString("isChe2SwitchedToBullish", isChe2SwitchedToBullish, ignoreFalseConditions, separator) + + ToString("isChe2SwitchedToBearish", isChe2SwitchedToBearish, ignoreFalseConditions, separator) + + ToString("isCheBullish", isCheBullish, ignoreFalseConditions, separator) + + ToString("isCheBearish", isCheBearish, ignoreFalseConditions, separator) + + ToString("isCheSwitchedToBullish", isCheSwitchedToBullish, ignoreFalseConditions, separator) + + ToString("isCheSwitchedToBearish", isCheSwitchedToBearish, ignoreFalseConditions, separator) + + // + "" + // + ; + + // + result = + // + "[" + GetTag() + "]" + separator + + (onlyConditions + ? "" + : commonStr) + + (!includeScores + ? "" + : scoresStr) + + " " + separator + + (onlyCommons + ? "" + : conditionsStr) + + "" + // + ; + + // + return result; + } + + /** + * Retrieve nique Tag Identifier ... + * + * @return ( string ) + */ + string GetTag() + { + return GetTypeName(this); + } + + // +}; + +// +// Class ... +class XCX121XCHEHelper : public XCBaseHelper +{ + // + // Public ... + public: + // + // Props ... + + // + // Constructors ... + XCX121XCHEHelper() + : XCBaseHelper(_Symbol, _Period) + { + } + + // + // Deconstructor ... + ~XCX121XCHEHelper() + { + // + mInputs.Clean(); + + // + Clean(le1Buffer); + Clean(se1Buffer); + Clean(le2Buffer); + Clean(se2Buffer); + Clean(le1StartBuffer); + Clean(se1StartBuffer); + Clean(le2StartBuffer); + Clean(se2StartBuffer); + } + + // + // Tools ... + bool Init( + string symbol, // Trading Symbol + ENUM_TIMEFRAMES period, // Trading Period + X121XCHEInputs &inputs // Inputs + ) + { + // + bool result = false; + + // + mSymbol = symbol; + mPeriod = period; + + // + result = inputs.IsValid(); + if (!result) + { + return result; + } + + // + ArraySetAsSeries(le1Buffer, true); + ArraySetAsSeries(se1Buffer, true); + ArraySetAsSeries(le2Buffer, true); + ArraySetAsSeries(se2Buffer, true); + ArraySetAsSeries(le1StartBuffer, true); + ArraySetAsSeries(se1StartBuffer, true); + ArraySetAsSeries(le2StartBuffer, true); + ArraySetAsSeries(se2StartBuffer, true); + + // + mInputs = inputs; + + // + mHandler = iCustom( + mSymbol, + mPeriod, + "x-saherelm.x121.xche", + // + // Inputs ... + // + // Market ... + "", + mInputs.cheLength, + mInputs.cheLoopback, + mInputs.cheMultiplier1, + mInputs.cheMultiplier2, + mInputs.cheUpperAppliedTo, + mInputs.cheLowerAppliedTo, + // + // Presentation ... + "", + mInputs.cheArrowCode, + mInputs.showLE1, + mInputs.showSE1, + mInputs.showLE2, + mInputs.showSE2 + // + ); + result = mHandler != INVALID_HANDLE; + if (!result) + { + return result; + } + + // + return result; + } + + // + // Inputs ... + + // + X121XCHEInputs GetInputs() + { + return mInputs; + } + + // + bool SetInputs( + X121XCHEInputs &inputs // Configs + ) + { + // + return Init( + mSymbol, + mPeriod, + inputs + // + ); + } + + // + // Readers ... + + // + double GetLE1( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(le1Buffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return le1Buffer[barIndex]; + } + + // + int CopyLE1( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + le1Buffer, + buffer, + forceClean + // + ); + } + + // + double GetLE1Start( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(le1StartBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return le1StartBuffer[barIndex]; + } + + // + int CopyLE1Start( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + le1StartBuffer, + buffer, + forceClean + // + ); + } + + // + double GetLE2( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(le2Buffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return le2Buffer[barIndex]; + } + + // + int CopyLE2( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + le2Buffer, + buffer, + forceClean + // + ); + } + + // + double GetLE2Start( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(le2StartBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return le2StartBuffer[barIndex]; + } + + // + int CopyLE2Start( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + le2StartBuffer, + buffer, + forceClean + // + ); + } + + // + double GetSE1( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(se1Buffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return se1Buffer[barIndex]; + } + + // + int CopySE1( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceCsean = true // Force To Csean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + se1Buffer, + buffer, + forceCsean + // + ); + } + + // + double GetSE1Start( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(se1StartBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return se1StartBuffer[barIndex]; + } + + // + int CopySE1Start( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceCsean = true // Force To Csean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + se1StartBuffer, + buffer, + forceCsean + // + ); + } + + // + double GetSE2( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(se2Buffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return se2Buffer[barIndex]; + } + + // + int CopySE2( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceCsean = true // Force To Csean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + se2Buffer, + buffer, + forceCsean + // + ); + } + + // + double GetSE2Start( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(se2StartBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return se2StartBuffer[barIndex]; + } + + // + int CopySE2Start( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceCsean = true // Force To Csean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + se2StartBuffer, + buffer, + forceCsean + // + ); + } + + // + void Free() override + { + Cleanup(10); + } + + // + bool GetConditions( + X121XCHEConditions &conditions, // + int barIndex = 0, // + int loopback = 5 // + ) + { + // + bool result = true; + + // + if (loopback < 5) + { + loopback = 5; + } + + // + conditions.Clean(); + + // + conditions.symbol = mSymbol; + conditions.period = mPeriod; + conditions.time = TimeCurrent(); + + // + int zIndex = barIndex; + int cIndex = zIndex + 1; + int pIndex = cIndex + 1; + int ppIndex = pIndex + 1; + + // + // Buffers ... + + // + CopyLE1( + zIndex, + loopback, + conditions.le1Buffer // + ); + + // + CopySE1( + zIndex, + loopback, + conditions.se1Buffer // + ); + + // + CopyLE2( + zIndex, + loopback, + conditions.le2Buffer // + ); + + // + CopySE2( + zIndex, + loopback, + conditions.se2Buffer // + ); + + // + CopyLE1Start( + zIndex, + loopback, + conditions.le1StartBuffer // + ); + + // + CopySE1Start( + zIndex, + loopback, + conditions.se1StartBuffer // + ); + + // + CopyLE2Start( + zIndex, + loopback, + conditions.le2StartBuffer // + ); + + // + CopySE2Start( + zIndex, + loopback, + conditions.se2StartBuffer // + ); + + // + // Conditions ... + + // + int cIDX = 1; + int pIDX = cIDX + 1; + + // + bool isChe1Bullish = le1Buffer[cIDX] != EMPTY_VALUE && + se1Buffer[cIDX] == EMPTY_VALUE; + bool isChe1BullishPrev = le1Buffer[cIDX] != EMPTY_VALUE && + se1Buffer[pIDX] == EMPTY_VALUE; + + // + bool isChe1Bearish = se1Buffer[cIDX] != EMPTY_VALUE && + le1Buffer[cIDX] == EMPTY_VALUE; + bool isChe1BearishPrev = se1Buffer[pIDX] != EMPTY_VALUE && + le1Buffer[pIDX] == EMPTY_VALUE; + + // + bool isChe1SwitchedToBullish = isChe1Bullish && + !isChe1BullishPrev; + bool isChe1SwitchedToBearish = isChe1Bearish && + !isChe1BearishPrev; + + // + bool isChe2Bullish = le2Buffer[cIDX] != EMPTY_VALUE && + se2Buffer[cIDX] == EMPTY_VALUE; + bool isChe2BullishPrev = le2Buffer[pIDX] != EMPTY_VALUE && + se2Buffer[pIDX] == EMPTY_VALUE; + + // + bool isChe2Bearish = se2Buffer[cIDX] != EMPTY_VALUE && + le2Buffer[cIDX] == EMPTY_VALUE; + bool isChe2BearishPrev = se2Buffer[pIDX] != EMPTY_VALUE && + le2Buffer[pIDX] == EMPTY_VALUE; + + // + bool isChe2SwitchedToBullish = isChe2Bullish && + !isChe2BullishPrev; + bool isChe2SwitchedToBearish = isChe2Bearish && + !isChe2BearishPrev; + + // + bool isCheBullish = isChe1Bullish && + isChe2Bullish; + bool isCheBullishPrev = isChe1BullishPrev && + isChe2BullishPrev; + + // + bool isCheBearish = isChe1Bearish && + isChe2Bearish; + bool isCheBearishPrev = isChe1BearishPrev && + isChe2BearishPrev; + + // + bool isCheSwitchedToBullish = isCheBullish && + !isCheBullishPrev; + bool isCheSwitchedToBearish = isCheBearish && + !isCheBearishPrev; + + // + double ches[]; + double prevCheLE1 = le1Buffer[pIDX]; + double prevCheLE2 = le2Buffer[pIDX]; + double prevCheSE1 = se1Buffer[pIDX]; + double prevCheSE2 = se2Buffer[pIDX]; + if (prevCheLE1 != EMPTY_VALUE) + { + // + Add( + prevCheLE1, + ches // + ); + } + if (prevCheLE2 != EMPTY_VALUE) + { + // + Add( + prevCheLE2, + ches // + ); + } + if (prevCheSE1 != EMPTY_VALUE) + { + // + Add( + prevCheSE1, + ches // + ); + } + if (prevCheSE2 != EMPTY_VALUE) + { + // + Add( + prevCheSE2, + ches // + ); + } + + // + double cheMin = GetMin(ches); + double cheMax = GetMax(ches); + + // + conditions.isChe1Bullish = isChe1Bullish; + conditions.isChe1Bearish = isChe1Bearish; + conditions.isChe1SwitchedToBullish = isChe1SwitchedToBullish; + conditions.isChe1SwitchedToBearish = isChe1SwitchedToBearish; + conditions.isChe2Bullish = isChe2Bullish; + conditions.isChe2Bearish = isChe2Bearish; + conditions.isChe2SwitchedToBullish = isChe2SwitchedToBullish; + conditions.isChe2SwitchedToBearish = isChe2SwitchedToBearish; + conditions.isCheBullish = isCheBullish; + conditions.isCheBearish = isCheBearish; + conditions.isCheSwitchedToBullish = isCheSwitchedToBullish; + conditions.isCheSwitchedToBearish = isCheSwitchedToBearish; + + // + Cleanup(); + + // + return result; + } + + // + // Protected ... + protected: + // + // Private ... + private: + // + // Props ... + X121XCHEInputs mInputs; // Inputs ... + + // + // Buffers ... + double le1Buffer[]; + double se1Buffer[]; + double le2Buffer[]; + double se2Buffer[]; + double le1StartBuffer[]; + double se1StartBuffer[]; + double le2StartBuffer[]; + double se2StartBuffer[]; + + // + void Calculate( + int barIndex = 0, + int maxRequiredBars = 100 // + ) + { + // + // Buffers ... + if (barIndex < 0) + { + barIndex = 0; + } + + // + // LE1 Start ... + CopyBuffer( + mHandler, + X121_XCHE_LE_1_S_LINE, + barIndex, + maxRequiredBars, + le1StartBuffer // + ); + + // + // LE1 ... + CopyBuffer( + mHandler, + X121_XCHE_LE_1_LINE, + barIndex, + maxRequiredBars, + le1Buffer // + ); + + // + // LE2 Start ... + CopyBuffer( + mHandler, + X121_XCHE_LE_2_S_LINE, + barIndex, + maxRequiredBars, + le2StartBuffer // + ); + + // + // LE2 ... + CopyBuffer( + mHandler, + X121_XCHE_LE_2_LINE, + barIndex, + maxRequiredBars, + le2Buffer // + ); + + // + // SE1 Start ... + CopyBuffer( + mHandler, + X121_XCHE_SE_1_S_LINE, + barIndex, + maxRequiredBars, + se1StartBuffer // + ); + + // + // SE1 ... + CopyBuffer( + mHandler, + X121_XCHE_SE_1_LINE, + barIndex, + maxRequiredBars, + se1Buffer // + ); + + // + // SE2 Start ... + CopyBuffer( + mHandler, + X121_XCHE_SE_2_S_LINE, + barIndex, + maxRequiredBars, + se2StartBuffer // + ); + + // + // SE2 ... + CopyBuffer( + mHandler, + X121_XCHE_SE_2_LINE, + barIndex, + maxRequiredBars, + se2Buffer // + ); + } + + // + void Cleanup( + int maxAllowed = 100 // + ) + { + // + CleanupArray( + le1Buffer, + maxAllowed // + ); + + // + CleanupArray( + se1Buffer, + maxAllowed // + ); + + // + CleanupArray( + le2Buffer, + maxAllowed // + ); + + // + CleanupArray( + se2Buffer, + maxAllowed // + ); + + // + CleanupArray( + le1StartBuffer, + maxAllowed // + ); + + // + CleanupArray( + se1StartBuffer, + maxAllowed // + ); + + // + CleanupArray( + le2StartBuffer, + maxAllowed // + ); + + // + CleanupArray( + se2StartBuffer, + maxAllowed // + ); + + // + } + + // +}; + +// +// Tools ... \ No newline at end of file diff --git a/BKPS/14040203/Helpers/x-saherelm.x121.xct.helper.mq5 b/BKPS/14040203/Helpers/x-saherelm.x121.xct.helper.mq5 new file mode 100644 index 0000000..c444481 --- /dev/null +++ b/BKPS/14040203/Helpers/x-saherelm.x121.xct.helper.mq5 @@ -0,0 +1,234 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Helper Class Library +// ---------------------------------------------- +// Name: XSCX121XCTHelper +// Description: provides all Indicator +// Helper requirements ... +// +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +////////////////////////////////////////////////////// +// +// Global Properties ... +#property library +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://www.saherelm.ir" +#property version "1.00" +#property strict + +// +// Imports ... +#include "../Classes/x-saherelm.x-helper.class.mq5" + +// +// Definitions ... + +// +// Input Models ... +struct X121XCTInputs +{ + // + // Props ... + + // + string font; // Font + int fontSize; // Font Size; + color clr; // Text Color + ENUM_BASE_CORNER corner; // Text Position + + // + // Presentation ... + bool showCandleTime; // Show Candle Time + + // + // Constructor(s) ... + X121XCTInputs() + { + Clean(); + } + + // + // Tools ... + + // + // Clean ... + void Clean() + { + // + font = NULL; + fontSize = 15; + clr = CLR_NONE; + corner = CORNER_RIGHT_LOWER; + + // + // Presentation ... + showCandleTime = false; + + // + ZeroMemory(this); + } + + // + // Default ... + void Default() + { + // + font = "Arial"; + fontSize = 15; + clr = clrYellow; + corner = CORNER_RIGHT_LOWER; + + // + // Presentation ... + showCandleTime = true; + } + + // + // Validate ... + bool IsValid() + { + // + bool result = false; + + // + result = + // + true + // + ; + + // + return result; + } + + // + // Retrieve MAx Length ... + int Max() + { + // + int result = 0; + + // + result = MathMax(0, 0); + + // + return result; + } +}; + +// +// Class ... +class XCX121XCTHelper : public XCBaseHelper +{ + // + // Public ... + public: + // + // Props ... + + // + // Constructors ... + XCX121XCTHelper() + : XCBaseHelper(_Symbol, _Period) + { + } + + // + // Deconstructor ... + ~XCX121XCTHelper() + { + mInputs.Clean(); + } + + // + // Tools ... + bool Init( + string symbol, // Trading Symbol + ENUM_TIMEFRAMES period, // Trading Period + X121XCTInputs &inputs // Inputs + ) + { + // + bool result = false; + + // + mSymbol = symbol; + mPeriod = period; + + // + result = inputs.IsValid(); + if (!result) + { + return result; + } + + // + mInputs = inputs; + + // + mHandler = iCustom( + mSymbol, + mPeriod, + "x-saherelm.x121.xct", + // + // Inputs ... + mInputs.fontSize, // Font Size ... + mInputs.font, // Font ... + mInputs.clr, // Text Color ... + mInputs.corner, // Text Position ... + // + // Presentation ... + "", + mInputs.showCandleTime // Show Candle Time + // + ); + result = mHandler != INVALID_HANDLE; + if (!result) + { + return result; + } + + // + return result; + } + + // + // Inputs ... + + // + X121XCTInputs GetInputs() + { + return mInputs; + } + + // + bool SetInputs( + X121XCTInputs &inputs // Configs + ) + { + // + return Init( + mSymbol, + mPeriod, + inputs + // + ); + } + + // + // Protected ... + protected: + // + // Private ... + private: + // + // Props ... + X121XCTInputs mInputs; // Inputs ... +}; + +// +// Tools ... \ No newline at end of file diff --git a/BKPS/14040203/Helpers/x-saherelm.x121.xdelta.helper.mq5 b/BKPS/14040203/Helpers/x-saherelm.x121.xdelta.helper.mq5 new file mode 100644 index 0000000..bdebbe9 --- /dev/null +++ b/BKPS/14040203/Helpers/x-saherelm.x121.xdelta.helper.mq5 @@ -0,0 +1,856 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Helper Class Library +// ---------------------------------------------- +// Name: XCX121XDELTASHelper +// Description: provides all Indicator +// Helper requirements ... +// +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +////////////////////////////////////////////////////// +// +// Global Properties ... +#property library +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://www.saherelm.ir" +#property version "1.00" +#property strict + +// +// Imports ... +#include "../Classes/x-saherelm.x-helper.class.mq5" + +// +// Definitions ... +enum ENUM_X121_XDELTA_BUFFERS +{ + // + X121_XDELTA_VOLUME_LINE = 0, + X121_XDELTA_HISTOGRAM_LINE = 1, + X121_XDELTA_MA_LINE = 3, + X121_XDELTA_STATE_LINE = 5, +}; + +// +// Input Models ... +struct X121XDELTAInputs +{ + // + // Props ... + + // + // Makret ... + int maLength; // Moving Averge Length + ENUM_X_MA_METHOD maMethod; // Moving Averge Method + + // + // Presentation ... + int startCalculationForLastBars; // Calculate Last n Bars + bool showDeltaLine; // Show Delta Line + bool showDeltaHistogram; // Show Delta Histogram + bool showDeltaMa; // Show Delta Moving Average + + // + // Constructor(s) ... + X121XDELTAInputs() + { + Clean(); + } + + // + // Tools ... + + /** + * Cleanup Model ... + */ + void Clean() + { + // + // Makret ... + maLength = 0; // Moving Averge Length + maMethod = X_MA_MODE_NONE; // Moving Averge Method + + // + // Presentation ... + startCalculationForLastBars = 0; // Calculate Last n Bars + showDeltaLine = false; // Show Delta Line + showDeltaHistogram = false; // Show Delta Histogram + showDeltaMa = false; // Show Delta Moving Average + + // + ZeroMemory(this); + } + + /** + * Default Inputs ... + */ + void Default() + { + // + // Makret ... + maLength = 14; // Moving Averge Length + maMethod = X_MA_MODE_EMA; // Moving Averge Method + + // + // Presentation ... + startCalculationForLastBars = 1000; // Calculate Last n Bars + showDeltaLine = true; // Show Delta Line + showDeltaHistogram = true; // Show Delta Histogram + showDeltaMa = true; // Show Delta Moving Average + } + + /** + * Validate Model ... + * + * @return ( bool ) + */ + bool IsValid() + { + // + bool result = false; + + // + result = + // + maLength > 0 && + IsValid(maMethod) + // + ; + + // + return result; + } + + /** + * Retrieve Max Input Length ... + * + * @return ( int ) + */ + int Max() + { + // + int result = 0; + + // + result = MathMax(result, maLength); + + // + return result; + } + + // +}; + +// +// Conditions ... +struct X121XDELTAConditions +{ + // + // Common ... + string symbol; + ENUM_TIMEFRAMES period; + datetime time; + + // + // Buffers ... + double deltaBuffer[]; + double deltaMaBuffer[]; + double deltaStateBuffer[]; + + // + // Conditions ... + + // + bool isDeltaBullish; + bool isDeltaBearish; + bool isDeltaSwitchedToBullish; + bool isDeltaSwitchedToBearish; + + // + bool isDeltaOverMa; + bool isDeltaUnderMa; + bool isDeltaCrossedOverMa; + bool isDeltaCrossedUnderMa; + + // + // Constructor ... + X121XDELTAConditions() + { + Clean(); + } + + // + // Tools ... + + /** + * Cleaning Up ... + */ + void Clean() + { + // + // Commons ... + time = NULL; + symbol = NULL; + period = NULL; + + // + // Buffers ... + + // + Clean(deltaBuffer); + Clean(deltaMaBuffer); + Clean(deltaStateBuffer); + + // + ArraySetAsSeries(deltaBuffer, true); + ArraySetAsSeries(deltaMaBuffer, true); + ArraySetAsSeries(deltaStateBuffer, true); + + // + // Conditions ... + + // + isDeltaBullish = false; + isDeltaBearish = false; + isDeltaSwitchedToBullish = false; + isDeltaSwitchedToBearish = false; + + // + isDeltaOverMa = false; + isDeltaUnderMa = false; + isDeltaCrossedOverMa = false; + isDeltaCrossedUnderMa = false; + + // + ZeroMemory(this); + } + + /** + * Generate Conditions Scores ... + * + * @param bullishScore: Double, Directional Scores Reference ... + * @param bearishScore: Double, Directional Scores Reference ... + */ + void GenerateScore( + double &bullishScore, + double &bearishScore // + ) + { + // + bullishScore = 0; + bearishScore = 0; + + // + double score = 1; + double minScore = 0.5; + double highScore = 1.5; + + // + if (isDeltaOverMa) + { + bullishScore += minScore; + } + if (isDeltaBullish) + { + bullishScore += minScore; + } + if (isDeltaCrossedOverMa) + { + bullishScore += score; + } + if (isDeltaSwitchedToBullish) + { + bullishScore += score; + } + + if (isDeltaBearish) + { + bearishScore += minScore; + } + if (isDeltaUnderMa) + { + bearishScore += minScore; + } + if (isDeltaCrossedUnderMa) + { + bearishScore += score; + } + if (isDeltaSwitchedToBearish) + { + bearishScore += score; + } + } + + /** + * Generate Summary String for Represent Conditions State ... + * + * @param onlyCommons: Boolean, Just Generate Only Commons Conditions ... + * @param onlyConditions: Boolean, Just Generate Only Conditions ... + * @param includeScores: Boolean, Attach Scores Representations on Result ... + * @param ignoreFalseConditions: Boolean, Ignore False Conditions on Result ... + * @param separator: String, Separate Lines ... + * + * @return ( string ) + */ + string GenerateSummary( + bool onlyCommons = false, + bool onlyConditions = false, + bool includeScores = true, + bool ignoreFalseConditions = true, + string separator = "\n" // + ) + { + // + string result = NULL; + + // + double bullishScore = 0; + double bearishScore = 0; + GenerateScore( + bullishScore, + bearishScore // + ); + + // + string scoresStr = + // + "Scores: " + separator + + "---------------" + separator + + "Bullish: " + ToString(bullishScore) + separator + + "Bearish: " + ToString(bearishScore) + separator + + "" + // + ; + + // + string commonStr = GenerateSpecifiedCommonSummary( + this, + separator, + includeScores // + ); + + // + string conditionsStr = + // + "-----------------------" + separator + + "XDELTA: " + separator + + "-----------------------" + separator + + ToString("isDeltaBullish", isDeltaBullish, ignoreFalseConditions, separator) + + ToString("isDeltaBearish", isDeltaBearish, ignoreFalseConditions, separator) + + ToString("isDeltaSwitchedToBullish", isDeltaSwitchedToBullish, ignoreFalseConditions, separator) + + ToString("isDeltaSwitchedToBearish", isDeltaSwitchedToBearish, ignoreFalseConditions, separator) + + ToString("isDeltaOverMa", isDeltaOverMa, ignoreFalseConditions, separator) + + ToString("isDeltaUnderMa", isDeltaUnderMa, ignoreFalseConditions, separator) + + ToString("isDeltaCrossedOverMa", isDeltaCrossedOverMa, ignoreFalseConditions, separator) + + ToString("isDeltaCrossedUnderMa", isDeltaCrossedUnderMa, ignoreFalseConditions, separator) + + // + "" + // + ; + + // + result = + // + "[" + GetTag() + "]" + separator + + (onlyConditions + ? "" + : commonStr) + + (!includeScores + ? "" + : scoresStr) + + " " + separator + + (onlyCommons + ? "" + : conditionsStr) + + "" + // + ; + + // + return result; + } + + /** + * Retrieve nique Tag Identifier ... + * + * @return ( string ) + */ + string GetTag() + { + return GetTypeName(this); + } + + // +}; + +// +// Class ... +class XCX121XDELTAHelper : public XCBaseHelper +{ + // + // Public ... + public: + // + // Props ... + + // + // Constructors ... + XCX121XDELTAHelper() + : XCBaseHelper(_Symbol, _Period) + { + } + + // + // Deconstructor ... + ~XCX121XDELTAHelper() + { + // + mInputs.Clean(); + + // + Clean(deltaBuffer); + Clean(deltaMaBuffer); + Clean(deltaStateBuffer); + } + + // + // Tools ... + bool Init( + string symbol, // Trading Symbol + ENUM_TIMEFRAMES period, // Trading Period + X121XDELTAInputs &inputs // Inputs + ) + { + // + bool result = false; + + // + mSymbol = symbol; + mPeriod = period; + + // + result = inputs.IsValid(); + if (!result) + { + return result; + } + + // + ArraySetAsSeries(deltaBuffer, true); + ArraySetAsSeries(deltaMaBuffer, true); + ArraySetAsSeries(deltaStateBuffer, true); + + // + mInputs = inputs; + + // + mHandler = iCustom( + mSymbol, + mPeriod, + "x-saherelm.x121.xdelta", + // + // Inputs ... + // + // Market ... + "", + mInputs.maLength, + mInputs.maMethod, + // + // Presentation ... + "", + // + mInputs.startCalculationForLastBars, + mInputs.showDeltaLine, + mInputs.showDeltaHistogram, + mInputs.showDeltaMa + // + ); + result = mHandler != INVALID_HANDLE; + if (!result) + { + return result; + } + + // + return result; + } + + // + // Inputs ... + + // + X121XDELTAInputs GetInputs() + { + return mInputs; + } + + // + bool SetInputs( + X121XDELTAInputs &inputs // Configs + ) + { + // + return Init( + mSymbol, + mPeriod, + inputs + // + ); + } + + // + // Readers ... + + // + // Bullish ... + + // + double GetDelta( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(deltaBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return deltaBuffer[barIndex]; + } + + // + int CopyDelta( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + deltaBuffer, + buffer, + forceClean + // + ); + } + + // + double GetDeltaState( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(deltaStateBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return deltaStateBuffer[barIndex]; + } + + // + int CopyDeltaState( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + deltaStateBuffer, + buffer, + forceClean + // + ); + } + + // + double GetDeltaMa( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(deltaMaBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return deltaMaBuffer[barIndex]; + } + + // + int CopyDeltaMa( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + deltaMaBuffer, + buffer, + forceClean + // + ); + } + + // + void Free() override + { + Cleanup(10); + } + + // + bool GetConditions( + X121XDELTAConditions &conditions, // + int barIndex = 0, // + int loopback = 5 // + ) + { + // + bool result = true; + + // + if (loopback < 5) + { + loopback = 5; + } + + // + conditions.Clean(); + + // + conditions.symbol = mSymbol; + conditions.period = mPeriod; + conditions.time = TimeCurrent(); + + // + int zIndex = barIndex; + int cIndex = zIndex + 1; + int pIndex = cIndex + 1; + int ppIndex = pIndex + 1; + + // + // Buffers ... + + // + CopyDelta( + zIndex, + loopback, + conditions.deltaBuffer // + ); + + // + CopyDeltaState( + zIndex, + loopback, + conditions.deltaStateBuffer // + ); + + // + CopyDeltaMa( + zIndex, + loopback, + conditions.deltaMaBuffer // + ); + + // + // Conditions ... + + // + int cIDX = 1; + int pIDX = cIDX + 1; + int pPIDX = pIDX + 1; + + // + bool isDeltaBullish = conditions.deltaBuffer[cIDX] > conditions.deltaBuffer[pIDX]; + bool isDeltaBullishP = conditions.deltaBuffer[pIDX] > conditions.deltaBuffer[pPIDX]; + bool isDeltaSwitchedToBullish = isDeltaBullish && + !isDeltaBullishP; + + // + bool isDeltaBearish = conditions.deltaBuffer[cIDX] < conditions.deltaBuffer[pIDX]; + bool isDeltaBearishP = conditions.deltaBuffer[pIDX] < conditions.deltaBuffer[pPIDX]; + bool isDeltaSwitchedToBearish = isDeltaBearish && + !isDeltaBearishP; + + // + bool isDeltaOverMa = conditions.deltaBuffer[cIDX] > conditions.deltaMaBuffer[cIDX]; + bool isDeltaOverMaP = conditions.deltaBuffer[pIDX] > conditions.deltaMaBuffer[pIDX]; + bool isDeltaCrossedOverMa = isDeltaOverMa && + !isDeltaOverMaP; + + // + bool isDeltaUnderMa = conditions.deltaBuffer[cIDX] < conditions.deltaMaBuffer[cIDX]; + bool isDeltaUnderMaP = conditions.deltaBuffer[pIDX] < conditions.deltaMaBuffer[pIDX]; + bool isDeltaCrossedUnderMa = isDeltaUnderMa && + !isDeltaUnderMaP; + + // + conditions.isDeltaBullish = isDeltaBullish; + conditions.isDeltaBearish = isDeltaBearish; + conditions.isDeltaSwitchedToBullish = isDeltaSwitchedToBullish; + conditions.isDeltaSwitchedToBearish = isDeltaSwitchedToBearish; + + // + conditions.isDeltaOverMa = isDeltaOverMa; + conditions.isDeltaUnderMa = isDeltaUnderMa; + conditions.isDeltaCrossedOverMa = isDeltaCrossedOverMa; + conditions.isDeltaCrossedUnderMa = isDeltaCrossedUnderMa; + + // + Cleanup(); + + // + return result; + } + + // + // Protected ... + protected: + // + // Private ... + private: + // + // Props ... + X121XDELTAInputs mInputs; // Inputs ... + + // + // Buffers ... + double deltaBuffer[]; + double deltaMaBuffer[]; + double deltaStateBuffer[]; + + // + void Calculate( + int barIndex = 0, + int maxRequiredBars = 100 // + ) + { + // + // Buffers ... + if (barIndex < 0) + { + barIndex = 0; + } + + // + CopyBuffer( + mHandler, + X121_XDELTA_VOLUME_LINE, + barIndex, + maxRequiredBars, + deltaBuffer + // + ); + + // + CopyBuffer( + mHandler, + X121_XDELTA_MA_LINE, + barIndex, + maxRequiredBars, + deltaMaBuffer + // + ); + + // + CopyBuffer( + mHandler, + X121_XDELTA_STATE_LINE, + barIndex, + maxRequiredBars, + deltaStateBuffer + // + ); + } + + // + void Cleanup( + int maxAllowed = 100 // + ) + { + // + CleanupArray( + deltaBuffer, + maxAllowed // + ); + + // + CleanupArray( + deltaMaBuffer, + maxAllowed // + ); + + // + CleanupArray( + deltaStateBuffer, + maxAllowed // + ); + } + + // +}; + +// diff --git a/BKPS/14040203/Helpers/x-saherelm.x121.xdon.helper.mq5 b/BKPS/14040203/Helpers/x-saherelm.x121.xdon.helper.mq5 new file mode 100644 index 0000000..9957b6f --- /dev/null +++ b/BKPS/14040203/Helpers/x-saherelm.x121.xdon.helper.mq5 @@ -0,0 +1,1202 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Helper Class Library +// ---------------------------------------------- +// Name: XCX121XDONHelper +// Description: provides all Indicator +// Helper requirements ... +// +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +////////////////////////////////////////////////////// +// +// Global Properties ... +#property library +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://www.saherelm.ir" +#property version "1.00" +#property strict + +// +// Imports ... +#include "../Classes/x-saherelm.x-helper.class.mq5" + +// +// Definitions ... + +// +// Definitions ... +enum ENUM_X121_XDON_BUFFERS +{ + // + X121_XDON_OPEN_UPPER_LINE = 0, + X121_XDON_OPEN_LOWER_LINE = 1, + X121_XDON_HIGH_UPPER_LINE = 2, + X121_XDON_HIGH_LOWER_LINE = 3, + X121_XDON_LOW_UPPER_LINE = 4, + X121_XDON_LOW_LOWER_LINE = 5, + X121_XDON_CLOSE_UPPER_LINE = 6, + X121_XDON_CLOSE_LOWER_LINE = 7, +}; + +// +// Input Models ... +struct X121XDONInputs +{ + // + // Props ... + + // + int donchainLength; // Donchain Length + + // + int startCalculationForLastBars; // Calculate Last n Bars + + // + bool showUpper; // Show Upper Band + bool showLower; // Show Lower Band + + // + bool showOpen; // Show Open + bool showHigh; // Show High + bool showClose; // Show Close + bool showLow; // Show Low + + // + // Constructor(s) ... + X121XDONInputs() + { + // + Clean(); + } + + // + // Tools ... + + // + // Clean ... + void Clean() + { + // + donchainLength = 0; + + // + startCalculationForLastBars = 0; + + // + showUpper = false; + showLower = false; + + // + showOpen = false; + showHigh = false; + showClose = false; + showLow = false; + + // + ZeroMemory(this); + } + + // + // Default ... + void Default() + { + // + donchainLength = 40; + + // + startCalculationForLastBars = 1000; + + // + showUpper = true; + showLower = true; + + // + showOpen = true; + showHigh = true; + showClose = true; + showLow = true; + } + + // + // Validate ... + bool IsValid() + { + // + bool result = false; + + // + result = + // + donchainLength > 0 + // + ; + + // + return result; + } + + // + // Retrieve MAx Length ... + int Max() + { + // + int result = 0; + + // + result = MathMax(1, donchainLength); + + // + return result; + } +}; + +// +// Conditions ... +struct X121XDONConditions +{ + // + // Common ... + string symbol; + ENUM_TIMEFRAMES period; + datetime time; + + // + // Buffers ... + double donOpenUpperBuffer[]; + double donOpenLowerBuffer[]; + double donHighUpperBuffer[]; + double donHighLowerBuffer[]; + double donLowUpperBuffer[]; + double donLowLowerBuffer[]; + double donCloseUpperBuffer[]; + double donCloseLowerBuffer[]; + + // + // Conditions ... + + // + // Constructor ... + X121XDONConditions() + { + Clean(); + } + + // + // Tools ... + + /** + * Cleaning Up ... + */ + void Clean() + { + // + // Commons ... + symbol = NULL; + period = NULL; + time = NULL; + + // + // Buffers ... + + // + Clean(donOpenUpperBuffer); + Clean(donOpenLowerBuffer); + Clean(donHighUpperBuffer); + Clean(donHighLowerBuffer); + Clean(donLowUpperBuffer); + Clean(donLowLowerBuffer); + Clean(donCloseUpperBuffer); + Clean(donCloseLowerBuffer); + + // + ArraySetAsSeries(donOpenUpperBuffer, true); + ArraySetAsSeries(donOpenLowerBuffer, true); + ArraySetAsSeries(donHighUpperBuffer, true); + ArraySetAsSeries(donHighLowerBuffer, true); + ArraySetAsSeries(donLowUpperBuffer, true); + ArraySetAsSeries(donLowLowerBuffer, true); + ArraySetAsSeries(donCloseUpperBuffer, true); + ArraySetAsSeries(donCloseLowerBuffer, true); + + // + // Conditions ... + + // + ZeroMemory(this); + } + + /** + * Generate Conditions Scores ... + * + * @param bullishScore: Double, Directional Scores Reference ... + * @param bearishScore: Double, Directional Scores Reference ... + */ + void GenerateScore( + double &bullishScore, + double &bearishScore // + ) + { + // + bullishScore = 0; + bearishScore = 0; + + // + // TODO: Implement if Required ... + } + + /** + * Generate Summary String for Represent Conditions State ... + * + * @param onlyCommons: Boolean, Just Generate Only Commons Conditions ... + * @param onlyConditions: Boolean, Just Generate Only Conditions ... + * @param includeScores: Boolean, Attach Scores Representations on Result ... + * @param ignoreFalseConditions: Boolean, Ignore False Conditions on Result ... + * @param separator: String, Separate Lines ... + * + * @return ( string ) + */ + string GenerateSummary( + bool onlyCommons = false, + bool onlyConditions = false, + bool includeScores = true, + bool ignoreFalseConditions = true, + string separator = "\n" // + ) + { + // + string result = NULL; + + // + double bullishScore = 0; + double bearishScore = 0; + GenerateScore( + bullishScore, + bearishScore // + ); + + // + string scoresStr = + // + "Scores: " + separator + + "---------------" + separator + + "Bullish: " + ToString(bullishScore) + separator + + "Bearish: " + ToString(bearishScore) + separator + + "" + // + ; + + // + string commonStr = GenerateSpecifiedCommonSummary( + this, + separator, + includeScores // + ); + + // + string conditionsStr = + // + // + "" + // + ; + + // + result = + // + "[" + GetTag() + "]" + separator + + (onlyConditions + ? "" + : commonStr) + + (!includeScores + ? "" + : scoresStr) + + " " + separator + + (onlyCommons + ? "" + : conditionsStr) + + "" + // + ; + + // + return result; + } + + /** + * Retrieve nique Tag Identifier ... + * + * @return ( string ) + */ + string GetTag() + { + return GetTypeName(this); + } + + // +}; + +// +// Class ... +class XCX121XDONHelper : public XCBaseHelper +{ + // + // Public ... + public: + // + // Props ... + + // + // Constructors ... + XCX121XDONHelper() + : XCBaseHelper(_Symbol, _Period) + { + } + + // + // Deconstructor ... + ~XCX121XDONHelper() + { + // + mInputs.Clean(); + + // + Clean(donOpenUpperBuffer); + Clean(donOpenLowerBuffer); + Clean(donHighUpperBuffer); + Clean(donHighLowerBuffer); + Clean(donLowUpperBuffer); + Clean(donLowLowerBuffer); + Clean(donCloseUpperBuffer); + Clean(donCloseLowerBuffer); + } + + // + // Tools ... + bool Init( + string symbol, // Trading Symbol + ENUM_TIMEFRAMES period, // Trading Period + X121XDONInputs &inputs // Inputs + ) + { + // + bool result = false; + + // + mSymbol = symbol; + mPeriod = period; + + // + result = inputs.IsValid(); + if (!result) + { + return result; + } + + // + ArraySetAsSeries(donOpenUpperBuffer, true); + ArraySetAsSeries(donOpenLowerBuffer, true); + ArraySetAsSeries(donHighUpperBuffer, true); + ArraySetAsSeries(donHighLowerBuffer, true); + ArraySetAsSeries(donLowUpperBuffer, true); + ArraySetAsSeries(donLowLowerBuffer, true); + ArraySetAsSeries(donCloseUpperBuffer, true); + ArraySetAsSeries(donCloseLowerBuffer, true); + + // + mInputs = inputs; + + // + mHandler = iCustom( + mSymbol, + mPeriod, + "x-saherelm.x121.xdon", + // + // Inputs ... + // + // Market ... + "", + mInputs.donchainLength, + // + // Presentation ... + "", + mInputs.startCalculationForLastBars, + // + mInputs.showUpper, + mInputs.showLower, + // + mInputs.showOpen, + mInputs.showHigh, + mInputs.showClose, + mInputs.showLow + // + ); + result = mHandler != INVALID_HANDLE; + if (!result) + { + return result; + } + + // + return result; + } + + // + // Inputs ... + + // + X121XDONInputs GetInputs() + { + return mInputs; + } + + // + bool SetInputs( + X121XDONInputs &inputs // Configs + ) + { + // + return Init( + mSymbol, + mPeriod, + inputs + // + ); + } + + // + // Readers ... + + // + // OPEN ... + + // + // UPPER ... + + // + double GetDonOpenUpper( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(donOpenUpperBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return donOpenUpperBuffer[barIndex]; + } + + // + int CopyDonOpenUpper( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + donOpenUpperBuffer, + buffer, + forceClean + // + ); + } + + // + // LOWER ... + + // + double GetDonOpenLower( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(donOpenLowerBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return donOpenLowerBuffer[barIndex]; + } + + // + int CopyDonOpenLower( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + donOpenLowerBuffer, + buffer, + forceClean + // + ); + } + + // + // CLOSE ... + + // + // UPPER ... + + // + double GetDonCloseUpper( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(donCloseUpperBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return donCloseUpperBuffer[barIndex]; + } + + // + int CopyDonCloseUpper( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + donCloseUpperBuffer, + buffer, + forceClean + // + ); + } + + // + // LOWER ... + + // + double GetDonCloseLower( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(donCloseLowerBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return donCloseLowerBuffer[barIndex]; + } + + // + int CopyDonCloseLower( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + donCloseLowerBuffer, + buffer, + forceClean + // + ); + } + + // + // HIGH ... + + // + // UPPER ... + + // + double GetDonHighUpper( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(donHighUpperBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return donHighUpperBuffer[barIndex]; + } + + // + int CopyDonHighUpper( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + donHighUpperBuffer, + buffer, + forceClean + // + ); + } + + // + // LOWER ... + + // + double GetDonHighLower( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(donHighLowerBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return donHighLowerBuffer[barIndex]; + } + + // + int CopyDonHighLower( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + donHighLowerBuffer, + buffer, + forceClean + // + ); + } + + // + // LOW ... + + // + // UPPER ... + + // + double GetDonLowUpper( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(donLowUpperBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return donLowUpperBuffer[barIndex]; + } + + // + int CopyDonLowUpper( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + donLowUpperBuffer, + buffer, + forceClean + // + ); + } + + // + // LOWER ... + + // + double GetDonLoweLower( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(donLowLowerBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return donLowLowerBuffer[barIndex]; + } + + // + int CopyDonLoweLower( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + donLowLowerBuffer, + buffer, + forceClean + // + ); + } + + // + void Free() override + { + Cleanup(10); + } + + // + bool GetConditions( + X121XDONConditions &conditions, // + int barIndex = 0, // + int loopback = 5 // + ) + { + // + bool result = true; + + // + if (loopback < 5) + { + loopback = 5; + } + + // + conditions.Clean(); + + // + conditions.symbol = mSymbol; + conditions.period = mPeriod; + conditions.time = TimeCurrent(); + + // + int zIndex = barIndex; + int cIndex = zIndex + 1; + int pIndex = cIndex + 1; + int ppIndex = pIndex + 1; + + // + // Buffers ... + + // + CopyDonOpenUpper( + zIndex, + loopback, + conditions.donOpenUpperBuffer // + ); + + // + CopyDonOpenLower( + zIndex, + loopback, + conditions.donOpenLowerBuffer // + ); + + // + CopyDonCloseUpper( + zIndex, + loopback, + conditions.donCloseUpperBuffer // + ); + + // + CopyDonCloseLower( + zIndex, + loopback, + conditions.donCloseLowerBuffer // + ); + + // + CopyDonHighUpper( + zIndex, + loopback, + conditions.donHighUpperBuffer // + ); + + // + CopyDonHighLower( + zIndex, + loopback, + conditions.donHighLowerBuffer // + ); + + // + CopyDonLowUpper( + zIndex, + loopback, + conditions.donLowUpperBuffer // + ); + + // + CopyDonLoweLower( + zIndex, + loopback, + conditions.donLowLowerBuffer // + ); + + // + // Conditions ... + + // + int cIDX = 1; + int pIDX = cIDX + 1; + + // + Cleanup(); + + // + return result; + } + + // + // Protected ... + protected: + // + // Private ... + private: + // + // Props ... + X121XDONInputs mInputs; // Inputs ... + + // + // Buffers ... + double donLowUpperBuffer[]; + double donLowLowerBuffer[]; + double donOpenUpperBuffer[]; + double donOpenLowerBuffer[]; + double donHighUpperBuffer[]; + double donHighLowerBuffer[]; + double donCloseUpperBuffer[]; + double donCloseLowerBuffer[]; + + // + void Calculate( + int barIndex = 0, + int maxRequiredBars = 100 // + ) + { + // + // Buffers ... + if (barIndex < 0) + { + barIndex = 0; + } + + // + // Upper ... + CopyBuffer( + mHandler, + X121_XDON_OPEN_UPPER_LINE, + barIndex, + maxRequiredBars, + donOpenUpperBuffer + // + ); + + // + // Lower ... + CopyBuffer( + mHandler, + X121_XDON_OPEN_LOWER_LINE, + barIndex, + maxRequiredBars, + donOpenLowerBuffer + // + ); + + // + // CLOSE ... + + // + // Upper ... + CopyBuffer( + mHandler, + X121_XDON_CLOSE_UPPER_LINE, + barIndex, + maxRequiredBars, + donCloseUpperBuffer + // + ); + + // + // Lower ... + CopyBuffer( + mHandler, + X121_XDON_CLOSE_LOWER_LINE, + barIndex, + maxRequiredBars, + donCloseLowerBuffer + // + ); + + // + // HIGH ... + + // + // Upper ... + CopyBuffer( + mHandler, + X121_XDON_HIGH_UPPER_LINE, + barIndex, + maxRequiredBars, + donHighUpperBuffer + // + ); + + // + // Lower ... + CopyBuffer( + mHandler, + X121_XDON_HIGH_LOWER_LINE, + barIndex, + maxRequiredBars, + donHighLowerBuffer + // + ); + + // + // LOW ... + + // + // Upper ... + CopyBuffer( + mHandler, + X121_XDON_LOW_UPPER_LINE, + barIndex, + maxRequiredBars, + donLowUpperBuffer + // + ); + + // + // Lower ... + CopyBuffer( + mHandler, + X121_XDON_LOW_LOWER_LINE, + barIndex, + maxRequiredBars, + donLowLowerBuffer + // + ); + } + + // + void Cleanup( + int maxAllowed = 100 // + ) + { + // + CleanupArray( + donOpenUpperBuffer, + maxAllowed // + ); + + // + CleanupArray( + donOpenLowerBuffer, + maxAllowed // + ); + + // + CleanupArray( + donHighUpperBuffer, + maxAllowed // + ); + + // + CleanupArray( + donHighLowerBuffer, + maxAllowed // + ); + + // + CleanupArray( + donLowUpperBuffer, + maxAllowed // + ); + + // + CleanupArray( + donLowLowerBuffer, + maxAllowed // + ); + + // + CleanupArray( + donCloseUpperBuffer, + maxAllowed // + ); + + // + CleanupArray( + donCloseLowerBuffer, + maxAllowed // + ); + + // + } + + // +}; + +// +// Tools ... \ No newline at end of file diff --git a/BKPS/14040203/Helpers/x-saherelm.x121.xhk.helper.mq5 b/BKPS/14040203/Helpers/x-saherelm.x121.xhk.helper.mq5 new file mode 100644 index 0000000..0f66528 --- /dev/null +++ b/BKPS/14040203/Helpers/x-saherelm.x121.xhk.helper.mq5 @@ -0,0 +1,1490 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Helper Class Library +// ---------------------------------------------- +// Name: XCX121XHKHelper +// Description: provides all Indicator +// Helper requirements ... +// +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +////////////////////////////////////////////////////// +// +// Global Properties ... +#property library +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://www.saherelm.ir" +#property version "1.00" +#property strict + +// +// Imports ... +#include "../Classes/x-saherelm.x-helper.class.mq5" + +// +// Definitions ... + +// +// Definitions ... +enum ENUM_X121_XHK_BUFFERS +{ + // + X121_XHK_RAW_OPEN_LINE = 0, + X121_XHK_RAW_HIGH_LINE = 1, + X121_XHK_RAW_LOW_LINE = 2, + X121_XHK_RAW_CLOSE_LINE = 3, + // + X121_XHK_SM_OPEN_LINE = 5, + X121_XHK_SM_HIGH_LINE = 6, + X121_XHK_SM_LOW_LINE = 7, + X121_XHK_SM_CLOSE_LINE = 8, +}; + +// +// Input Models ... +struct X121XHKInputs +{ + // + // Props ... + int xhkSmoothingLength; // Length + ENUM_X_MA_METHOD xhkSmoothingMode; // Smoothing Method + bool xhkIgnoreSmoothingShadows; // Ignore Smoothed Bar Shadows + int startCalculationForLastBars; // Calculate Last n Bars + bool drawRawXHKCandles; // Draw Raw Candle + bool drawSmoothedXHKCandles; // Draw Smoothed Candle + + // + // Constructor(s) ... + X121XHKInputs() + { + // + Clean(); + } + + // + // Tools ... + + // + // Clean ... + void Clean() + { + // + xhkSmoothingLength = 0; + xhkSmoothingMode = X_MA_MODE_NONE; + xhkIgnoreSmoothingShadows = false; + startCalculationForLastBars = 1500; + drawRawXHKCandles = false; + drawSmoothedXHKCandles = false; + + // + ZeroMemory(this); + } + + // + // Default ... + void Default() + { + // + xhkSmoothingLength = 14; + xhkSmoothingMode = X_MA_MODE_EMA; + xhkIgnoreSmoothingShadows = false; + startCalculationForLastBars = 1500; + drawRawXHKCandles = true; + drawSmoothedXHKCandles = true; + } + + // + // Validate ... + bool IsValid() + { + // + bool result = false; + + // + result = + // + xhkSmoothingLength > 0 + // + ; + + // + return result; + } + + // + // Retrieve MAx Length ... + int Max() + { + // + int result = 0; + + // + result = MathMax(0, xhkSmoothingLength); + + // + return result; + } +}; + +// +// Conditions ... +struct X121XHKConditions +{ + // + // Common ... + string symbol; + ENUM_TIMEFRAMES period; + datetime time; + + // + // Buffers ... + + // + double xhkRawOpenBuffer[]; + double xhkRawHighBuffer[]; + double xhkRawLowBuffer[]; + double xhkRawCloseBuffer[]; + + // + double xhkSMOpenBuffer[]; + double xhkSMHighBuffer[]; + double xhkSMLowBuffer[]; + double xhkSMCloseBuffer[]; + + // + // Conditions ... + + // + bool isSMHKBullish; + bool isRawHKBullish; + bool isSMHKSwitchedToBullish; + bool isRawHKSwitchedToBullish; + + // + bool isSMHKBearish; + bool isRawHKBearish; + bool isSMHKSwitchedToBearish; + bool isRawHKSwitchedToBearish; + + // + bool isClosedOverSMHK; + bool isClosedUnderSMHK; + bool isClosedOverRawHK; + bool isClosedUnderRawHK; + + // + bool isRawHKClosedOverSMHK; + bool isRawHKClosedUnderSMHK; + + // + // Constructor ... + X121XHKConditions() + { + Clean(); + } + + // + // Tools ... + + /** + * Cleaning Up ... + */ + void Clean() + { + // + // Commons ... + symbol = NULL; + period = NULL; + time = NULL; + + // + // Buffers ... + + // + Clean(xhkRawOpenBuffer); + Clean(xhkRawHighBuffer); + Clean(xhkRawLowBuffer); + Clean(xhkRawCloseBuffer); + Clean(xhkSMOpenBuffer); + Clean(xhkSMHighBuffer); + Clean(xhkSMLowBuffer); + Clean(xhkSMCloseBuffer); + + // + ArraySetAsSeries(xhkRawOpenBuffer, true); + ArraySetAsSeries(xhkRawHighBuffer, true); + ArraySetAsSeries(xhkRawLowBuffer, true); + ArraySetAsSeries(xhkRawCloseBuffer, true); + ArraySetAsSeries(xhkSMOpenBuffer, true); + ArraySetAsSeries(xhkSMHighBuffer, true); + ArraySetAsSeries(xhkSMLowBuffer, true); + ArraySetAsSeries(xhkSMCloseBuffer, true); + + // + // Conditions ... + + // + isSMHKBullish = false; + isRawHKBullish = false; + isSMHKSwitchedToBullish = false; + isRawHKSwitchedToBullish = false; + + // + isSMHKBearish = false; + isRawHKBearish = false; + isSMHKSwitchedToBearish = false; + isRawHKSwitchedToBearish = false; + + // + isClosedOverSMHK = false; + isClosedUnderSMHK = false; + isClosedOverRawHK = false; + isClosedUnderRawHK = false; + + // + isRawHKClosedOverSMHK = false; + isRawHKClosedUnderSMHK = false; + + // + ZeroMemory(this); + } + + /** + * Generate Conditions Scores ... + * + * @param bullishScore: Double, Directional Scores Reference ... + * @param bearishScore: Double, Directional Scores Reference ... + */ + void GenerateScore( + double &bullishScore, + double &bearishScore // + ) + { + // + bullishScore = 0; + bearishScore = 0; + + // + double score = 1; + double minScore = 0.5; + double highScore = 1.5; + + // + if (isSMHKBullish) + { + bullishScore += minScore; + } + if (isRawHKBullish) + { + bullishScore += minScore; + } + if (isClosedOverSMHK) + { + bullishScore += minScore; + } + if (isClosedOverRawHK) + { + bullishScore += minScore; + } + if (isRawHKClosedOverSMHK) + { + bullishScore += minScore; + } + if (isSMHKSwitchedToBullish) + { + bullishScore += highScore; + } + if (isRawHKSwitchedToBullish) + { + bullishScore += highScore; + } + + // + if (isSMHKBearish) + { + bearishScore += minScore; + } + if (isRawHKBearish) + { + bearishScore += minScore; + } + if (isClosedUnderSMHK) + { + bearishScore += minScore; + } + if (isClosedUnderRawHK) + { + bearishScore += minScore; + } + if (isRawHKClosedUnderSMHK) + { + bearishScore += minScore; + } + if (isSMHKSwitchedToBearish) + { + bearishScore += highScore; + } + if (isRawHKSwitchedToBullish) + { + bearishScore += highScore; + } + } + + /** + * Generate Summary String for Represent Conditions State ... + * + * @param onlyCommons: Boolean, Just Generate Only Commons Conditions ... + * @param onlyConditions: Boolean, Just Generate Only Conditions ... + * @param includeScores: Boolean, Attach Scores Representations on Result ... + * @param ignoreFalseConditions: Boolean, Ignore False Conditions on Result ... + * @param separator: String, Separate Lines ... + * + * @return ( string ) + */ + string GenerateSummary( + bool onlyCommons = false, + bool onlyConditions = false, + bool includeScores = true, + bool ignoreFalseConditions = true, + string separator = "\n" // + ) + { + // + string result = NULL; + + // + double bullishScore = 0; + double bearishScore = 0; + GenerateScore( + bullishScore, + bearishScore // + ); + + // + string scoresStr = + // + "Scores: " + separator + + "---------------" + separator + + "Bullish: " + ToString(bullishScore) + separator + + "Bearish: " + ToString(bearishScore) + separator + + "" + // + ; + + // + string commonStr = GenerateSpecifiedCommonSummary( + this, + separator, + includeScores // + ); + + // + string conditionsStr = + // + "-----------------------" + separator + + "XHK: " + separator + + "-----------------------" + separator + + ToString("isSMHKBullish", isSMHKBullish, ignoreFalseConditions, separator) + + ToString("isRawHKBullish", isRawHKBullish, ignoreFalseConditions, separator) + + ToString("isSMHKSwitchedToBullish", isSMHKSwitchedToBullish, ignoreFalseConditions, separator) + + ToString("isRawHKSwitchedToBullish", isRawHKSwitchedToBullish, ignoreFalseConditions, separator) + + ToString("isSMHKBearish", isSMHKBearish, ignoreFalseConditions, separator) + + ToString("isRawHKBearish", isRawHKBearish, ignoreFalseConditions, separator) + + ToString("isSMHKSwitchedToBearish", isSMHKSwitchedToBearish, ignoreFalseConditions, separator) + + ToString("isRawHKSwitchedToBearish", isRawHKSwitchedToBearish, ignoreFalseConditions, separator) + + ToString("isClosedOverSMHK", isClosedOverSMHK, ignoreFalseConditions, separator) + + ToString("isClosedUnderSMHK", isClosedUnderSMHK, ignoreFalseConditions, separator) + + ToString("isClosedOverRawHK", isClosedOverRawHK, ignoreFalseConditions, separator) + + ToString("isClosedUnderRawHK", isClosedUnderRawHK, ignoreFalseConditions, separator) + + ToString("isRawHKClosedOverSMHK", isRawHKClosedOverSMHK, ignoreFalseConditions, separator) + + ToString("isRawHKClosedUnderSMHK", isRawHKClosedUnderSMHK, ignoreFalseConditions, separator) + + // + "" + // + ; + + // + result = + // + "[" + GetTag() + "]" + separator + + (onlyConditions + ? "" + : commonStr) + + (!includeScores + ? "" + : scoresStr) + + " " + separator + + (onlyCommons + ? "" + : conditionsStr) + + "" + // + ; + + // + return result; + } + + /** + * Retrieve nique Tag Identifier ... + * + * @return ( string ) + */ + string GetTag() + { + return GetTypeName(this); + } + + // +}; + +// +// Class ... +class XCX121XHKHelper : public XCBaseHelper +{ + // + // Public ... + public: + // + // Props ... + + // + // Constructors ... + XCX121XHKHelper() + : XCBaseHelper(_Symbol, _Period) + { + } + + // + // Deconstructor ... + ~XCX121XHKHelper() + { + // + Clean(xhkRawOpenBuffer); + Clean(xhkRawHighBuffer); + Clean(xhkRawLowBuffer); + Clean(xhkRawCloseBuffer); + Clean(xhkSMOpenBuffer); + Clean(xhkSMHighBuffer); + Clean(xhkSMLowBuffer); + Clean(xhkSMCloseBuffer); + + // + mInputs.Clean(); + } + + // + // Tools ... + bool Init( + string symbol, // Trading Symbol + ENUM_TIMEFRAMES period, // Trading Period + X121XHKInputs &inputs // Inputs + ) + { + // + bool result = false; + + // + mSymbol = symbol; + mPeriod = period; + + // + result = inputs.IsValid(); + if (!result) + { + return result; + } + + // + ArraySetAsSeries(xhkRawOpenBuffer, true); + ArraySetAsSeries(xhkRawHighBuffer, true); + ArraySetAsSeries(xhkRawLowBuffer, true); + ArraySetAsSeries(xhkRawCloseBuffer, true); + ArraySetAsSeries(xhkSMOpenBuffer, true); + ArraySetAsSeries(xhkSMHighBuffer, true); + ArraySetAsSeries(xhkSMLowBuffer, true); + ArraySetAsSeries(xhkSMCloseBuffer, true); + + // + mInputs = inputs; + + // + mHandler = iCustom( + mSymbol, + mPeriod, + "x-saherelm.x121.xhk", + // + // Inputs ... + // + // Market ... + "", + mInputs.xhkSmoothingLength, + mInputs.xhkSmoothingMode, + mInputs.xhkIgnoreSmoothingShadows, + // + // Presentation ... + "", + mInputs.startCalculationForLastBars, + mInputs.drawRawXHKCandles, + mInputs.drawSmoothedXHKCandles + // + ); + result = mHandler != INVALID_HANDLE; + if (!result) + { + return result; + } + + // + return result; + } + + // + // Inputs ... + + // + X121XHKInputs GetInputs() + { + return mInputs; + } + + // + bool SetInputs( + X121XHKInputs &inputs // Configs + ) + { + // + return Init( + mSymbol, + mPeriod, + inputs + // + ); + } + + // + // Readers ... + + // + double GetRawHKOpen( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(xhkRawOpenBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return xhkRawOpenBuffer[barIndex]; + } + + // + int CopyRawHKOpen( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + xhkRawOpenBuffer, + buffer, + forceClean + // + ); + } + + // + double GetRawHKHigh( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(xhkRawHighBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return xhkRawHighBuffer[barIndex]; + } + + // + int CopyRawHKHigh( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + xhkRawHighBuffer, + buffer, + forceClean + // + ); + } + + // + double GetRawHKLow( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(xhkRawLowBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return xhkRawLowBuffer[barIndex]; + } + + // + int CopyRawHKLow( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + xhkRawLowBuffer, + buffer, + forceClean + // + ); + } + + // + double GetRawHKClose( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(xhkRawCloseBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return xhkRawCloseBuffer[barIndex]; + } + + // + int CopyRawHKClose( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + xhkRawCloseBuffer, + buffer, + forceClean + // + ); + } + + // + double GetSMHKOpen( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(xhkSMOpenBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return xhkSMOpenBuffer[barIndex]; + } + + // + int CopySMHKOpen( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + xhkSMOpenBuffer, + buffer, + forceClean + // + ); + } + + // + double GetSMHKHigh( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(xhkSMHighBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return xhkSMHighBuffer[barIndex]; + } + + // + int CopySMHKHigh( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + xhkSMHighBuffer, + buffer, + forceClean + // + ); + } + + // + double GetSMHKLow( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(xhkSMLowBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return xhkSMLowBuffer[barIndex]; + } + + // + int CopySMHKLow( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + xhkSMLowBuffer, + buffer, + forceClean + // + ); + } + + // + double GetSMHKClose( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(xhkSMCloseBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return xhkSMCloseBuffer[barIndex]; + } + + // + int CopySMHKClose( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + xhkSMCloseBuffer, + buffer, + forceClean + // + ); + } + + // + bool GetRawHKAsXOHCL( + int barIndex, // Bar Index + XOHCL &bar // Bar Result + ) + { + // + bool result = false; + + // + bar.Clean(); + + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + result = bar.Init( + GetSymbol(), + GetPeriod(), + barIndex // + ); + if (!result) + { + return result; + } + + // + bar.open = xhkRawOpenBuffer[0]; + bar.high = xhkRawHighBuffer[0]; + bar.low = xhkRawLowBuffer[0]; + bar.close = xhkRawCloseBuffer[0]; + + // + return result; + } + + // + bool GetSMHKAsXOHCL( + int barIndex, // Bar Index + XOHCL &bar // Bar Result + ) + { + // + bool result = false; + + // + bar.Clean(); + + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + result = bar.Init( + GetSymbol(), + GetPeriod(), + barIndex // + ); + if (!result) + { + return result; + } + + // + bar.open = xhkSMOpenBuffer[0]; + bar.high = xhkSMHighBuffer[0]; + bar.low = xhkSMLowBuffer[0]; + bar.close = xhkSMCloseBuffer[0]; + + // + return result; + } + + // + void Free() override + { + Cleanup(10); + } + + // + bool GetConditions( + X121XHKConditions &conditions, // + int barIndex = 0, // + int loopback = 5 // + ) + { + // + bool result = true; + + // + if (loopback < 5) + { + loopback = 5; + } + + // + conditions.Clean(); + + // + conditions.symbol = mSymbol; + conditions.period = mPeriod; + conditions.time = TimeCurrent(); + + // + int zIndex = barIndex; + int cIndex = zIndex + 1; + int pIndex = cIndex + 1; + int ppIndex = pIndex + 1; + + // + XOHCL zBar; + result = zBar.Init( + mSymbol, + mPeriod, + zIndex // + ); + if (!result) + { + return result; + } + + // + XOHCL cBar; + result = cBar.Init( + mSymbol, + mPeriod, + cIndex // + ); + if (!result) + { + return result; + } + + // + XOHCL pBar; + result = pBar.Init( + mSymbol, + mPeriod, + pIndex // + ); + if (!result) + { + return result; + } + + // + // Buffers ... + + // + CopyRawHKOpen( + zIndex, + loopback, + conditions.xhkRawOpenBuffer // + ); + + // + CopyRawHKHigh( + zIndex, + loopback, + conditions.xhkRawHighBuffer // + ); + + // + CopyRawHKLow( + zIndex, + loopback, + conditions.xhkRawLowBuffer // + ); + + // + CopyRawHKClose( + zIndex, + loopback, + conditions.xhkRawCloseBuffer // + ); + + // + CopySMHKOpen( + zIndex, + loopback, + conditions.xhkSMOpenBuffer // + ); + + // + CopySMHKHigh( + zIndex, + loopback, + conditions.xhkSMHighBuffer // + ); + + // + CopySMHKLow( + zIndex, + loopback, + conditions.xhkSMLowBuffer // + ); + + // + CopySMHKClose( + zIndex, + loopback, + conditions.xhkSMCloseBuffer // + ); + + // + // Conditions ... + + // + int cIDX = 1; + int pIDX = cIDX + 1; + + // + double smHKLow = conditions.xhkSMLowBuffer[cIDX]; + double smHKHigh = conditions.xhkSMHighBuffer[cIDX]; + double smHKOpen = conditions.xhkSMOpenBuffer[cIDX]; + double smHKClose = conditions.xhkSMCloseBuffer[cIDX]; + + // + double smHKLowPrev = conditions.xhkSMLowBuffer[pIDX]; + double smHKHighPrev = conditions.xhkSMHighBuffer[pIDX]; + double smHKOpenPrev = conditions.xhkSMOpenBuffer[pIDX]; + double smHKClosePrev = conditions.xhkSMCloseBuffer[pIDX]; + + // + double rawHKLow = conditions.xhkRawLowBuffer[cIDX]; + double rawHKHigh = conditions.xhkRawHighBuffer[cIDX]; + double rawHKOpen = conditions.xhkRawOpenBuffer[cIDX]; + double rawHKClose = conditions.xhkRawCloseBuffer[cIDX]; + + // + double rawHKLowPrev = conditions.xhkRawLowBuffer[pIDX]; + double rawHKHighPrev = conditions.xhkRawHighBuffer[pIDX]; + double rawHKOpenPrev = conditions.xhkRawOpenBuffer[pIDX]; + double rawHKClosePrev = conditions.xhkRawCloseBuffer[pIDX]; + + // + double smHKUp = MathMax(smHKOpen, smHKClose); + double smHKUpPrev = MathMax(smHKOpenPrev, smHKClosePrev); + + // + double smHKDown = MathMin(smHKOpen, smHKClose); + double smHKDownPrev = MathMin(smHKOpenPrev, smHKClosePrev); + + // + double rawHKUp = MathMax(rawHKOpen, rawHKClose); + double rawHKUpPrev = MathMax(rawHKOpenPrev, rawHKClosePrev); + + // + double rawHKDown = MathMin(rawHKOpen, rawHKClose); + double rawHKDownPrev = MathMin(rawHKOpenPrev, rawHKClosePrev); + + // + XOHCL rawHKCBar; + bool hasRawHKBar = GetRawHKAsXOHCL( + cIndex, + rawHKCBar // + ); + + // + // + // + + // + bool isSMHKBullish = smHKOpen < smHKClose; + bool isSMHKBullishPrev = smHKOpenPrev < smHKClosePrev; + + // + bool isRawHKBullish = rawHKOpen < rawHKClose; + bool isRawHKBullishPrev = rawHKOpenPrev < rawHKClosePrev; + + // + bool isSMHKSwitchedToBullish = isSMHKBullish && + !isSMHKBullishPrev; + bool isRawHKSwitchedToBullish = isRawHKBullish && + !isRawHKBullishPrev; + + // + bool isSMHKBearish = smHKOpen > smHKClose; + bool isSMHKBearishPrev = smHKOpenPrev > smHKClosePrev; + + // + bool isRawHKBearish = rawHKOpen > rawHKClose; + bool isRawHKBearishPrev = rawHKOpenPrev > rawHKClosePrev; + + // + bool isSMHKSwitchedToBearish = isSMHKBearish && + !isSMHKBearishPrev; + bool isRawHKSwitchedToBearish = isRawHKBearish && + !isRawHKBearishPrev; + + // + bool isClosedOverSMHK = cBar.close > smHKUp; + bool isClosedUnderSMHK = cBar.close < smHKDown; + + // + bool isClosedOverRawHK = cBar.close > rawHKUp; + bool isClosedUnderRawHK = cBar.close < rawHKDown; + + // + bool isRawHKClosedOverSMHK = rawHKClose > smHKUp; + bool isRawHKClosedUnderSMHK = rawHKClose < smHKDown; + + // + conditions.isSMHKBullish = isSMHKBullish; + conditions.isRawHKBullish = isRawHKBullish; + conditions.isSMHKSwitchedToBullish = isSMHKSwitchedToBullish; + conditions.isRawHKSwitchedToBullish = isRawHKSwitchedToBullish; + conditions.isSMHKBearish = isSMHKBearish; + conditions.isRawHKBearish = isRawHKBearish; + conditions.isSMHKSwitchedToBearish = isSMHKSwitchedToBearish; + conditions.isRawHKSwitchedToBearish = isRawHKSwitchedToBearish; + conditions.isClosedOverSMHK = isClosedOverSMHK; + conditions.isClosedUnderSMHK = isClosedUnderSMHK; + conditions.isClosedOverRawHK = isClosedOverRawHK; + conditions.isClosedUnderRawHK = isClosedUnderRawHK; + conditions.isRawHKClosedOverSMHK = isRawHKClosedOverSMHK; + conditions.isRawHKClosedUnderSMHK = isRawHKClosedUnderSMHK; + + // + Cleanup(); + + // + zBar.Clean(); + cBar.Clean(); + pBar.Clean(); + + // + rawHKCBar.Clean(); + + // + return result; + } + + // + // Protected ... + protected: + // + // Private ... + private: + // + // Props ... + X121XHKInputs mInputs; // Inputs ... + + // + // Buffers ... + double xhkRawOpenBuffer[]; + double xhkRawHighBuffer[]; + double xhkRawLowBuffer[]; + double xhkRawCloseBuffer[]; + double xhkSMOpenBuffer[]; + double xhkSMHighBuffer[]; + double xhkSMLowBuffer[]; + double xhkSMCloseBuffer[]; + + // + void Calculate( + int barIndex = 0, + int maxRequiredBars = 100 // + ) + { + // + // Buffers ... + if (barIndex < 0) + { + barIndex = 0; + } + + // + // RAW Open ... + CopyBuffer( + mHandler, + X121_XHK_RAW_OPEN_LINE, + barIndex, + maxRequiredBars, + xhkRawOpenBuffer + // + ); + + // + // RAW High ... + CopyBuffer( + mHandler, + X121_XHK_RAW_HIGH_LINE, + barIndex, + maxRequiredBars, + xhkRawHighBuffer + // + ); + + // + // RAW Low ... + CopyBuffer( + mHandler, + X121_XHK_RAW_LOW_LINE, + barIndex, + maxRequiredBars, + xhkRawLowBuffer + // + ); + + // + // RAW Close ... + CopyBuffer( + mHandler, + X121_XHK_RAW_CLOSE_LINE, + barIndex, + maxRequiredBars, + xhkRawCloseBuffer + // + ); + + // + // SM Open ... + CopyBuffer( + mHandler, + X121_XHK_SM_OPEN_LINE, + barIndex, + maxRequiredBars, + xhkSMOpenBuffer + // + ); + + // + // SM High ... + CopyBuffer( + mHandler, + X121_XHK_SM_HIGH_LINE, + barIndex, + maxRequiredBars, + xhkSMHighBuffer + // + ); + + // + // SM Low ... + CopyBuffer( + mHandler, + X121_XHK_SM_LOW_LINE, + barIndex, + maxRequiredBars, + xhkSMLowBuffer + // + ); + + // + // SM Close ... + CopyBuffer( + mHandler, + X121_XHK_SM_CLOSE_LINE, + barIndex, + maxRequiredBars, + xhkSMCloseBuffer + // + ); + } + + // + void Cleanup( + int maxAllowed = 100 // + ) + { + // + CleanupArray( + xhkRawOpenBuffer, + maxAllowed // + ); + + // + CleanupArray( + xhkRawHighBuffer, + maxAllowed // + ); + + // + CleanupArray( + xhkRawLowBuffer, + maxAllowed // + ); + + // + CleanupArray( + xhkRawCloseBuffer, + maxAllowed // + ); + + // + CleanupArray( + xhkSMOpenBuffer, + maxAllowed // + ); + + // + CleanupArray( + xhkSMHighBuffer, + maxAllowed // + ); + + // + CleanupArray( + xhkSMLowBuffer, + maxAllowed // + ); + + // + CleanupArray( + xhkSMCloseBuffer, + maxAllowed // + ); + + // + } + + // +}; + +// +// Tools ... \ No newline at end of file diff --git a/BKPS/14040203/Helpers/x-saherelm.x121.xich.helper.mq5 b/BKPS/14040203/Helpers/x-saherelm.x121.xich.helper.mq5 new file mode 100644 index 0000000..d57234a --- /dev/null +++ b/BKPS/14040203/Helpers/x-saherelm.x121.xich.helper.mq5 @@ -0,0 +1,1107 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Helper Class Library +// ---------------------------------------------- +// Name: XCX121XICHHelper +// Description: provides all Indicator +// Helper requirements ... +// +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +////////////////////////////////////////////////////// +// +// Global Properties ... +#property library +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://www.saherelm.ir" +#property version "1.00" +#property strict + +// +// Imports ... +#include "../Classes/x-saherelm.x-helper.class.mq5" + +// +// Definitions ... + +// +// Definitions ... +enum ENUM_X121_XICH_BUFFERS +{ + X121_XICH_TENKANSEN_LINE = 0, + X121_XICH_KIJUNSEN_LINE = 1, + X121_XICH_CHIKOUSPAN_LINE = 2, + X121_XICH_SENKOUSPANA_LINE = 3, + X121_XICH_SENKOUSPANB_LINE = 4, +}; + +// +// Input Models ... +struct X121XICHInputs +{ + // + // Props ... + + // + // Market ... + ENUM_X_PRICE chikouSpanMode; // ChikouSpan Mode + int tenkanSenLength; // TenkanSen Length + ENUM_X_BOUNDARY_PRICE tenkanSenMode; // TencanSen Mode + int kijunSenLength; // KijunSen Length + ENUM_X_BOUNDARY_PRICE kijunSenMode; // KijunSen Mode + int senkouSpanBLength; // SenkouSpan B Length + ENUM_X_BOUNDARY_PRICE senkouSpanBMode; // SenkouSpan B Mode + + // + // Presentation ... + int startCalculationForLastBars; // Calculate Last n Bars + bool shiftKumo; // Shift Kumo + bool showTenkanSen; // Show TenkanSen + bool showKijunSen; // Show KijunSen + bool showChikouSpan; // Show ChikouSpan + bool showSenkouSpanA; // Show Senkou Span A + bool showSenkouSpanB; // Show Senkou Span B + bool showKumo; // Show Kumo + + // + // Constructor(s) ... + X121XICHInputs() + { + Clean(); + } + + // + // Tools ... + + // + // Clean ... + void Clean() + { + // + // Market ... + chikouSpanMode = X_PRICE_NONE; // ChikouSpan Mode + tenkanSenLength = 0; // TenkanSen Length + tenkanSenMode = X_BOUNDARY_PRICE_NONE; // TencanSen Mode + kijunSenLength = 0; // KijunSen Length + kijunSenMode = X_BOUNDARY_PRICE_NONE; // KijunSen Mode + senkouSpanBLength = 0; // SenkouSpan B Length + senkouSpanBMode = X_BOUNDARY_PRICE_NONE; // SenkouSpan B Mode + + // + // Presentation ... + startCalculationForLastBars = 0; // Calculate Last n Bars + shiftKumo = false; // Shift Kumo + showTenkanSen = false; // Show TenkanSen + showKijunSen = false; // Show KijunSen + showChikouSpan = false; // Show ChikouSpan + showSenkouSpanA = false; // Show Senkou Span A + showSenkouSpanB = false; // Show Senkou Span B + showKumo = false; // Show Kumo + + // + ZeroMemory(this); + } + + // + // Default ... + void Default() + { + // + // Market ... + chikouSpanMode = X_PRICE_CLOSE; // ChikouSpan Mode + tenkanSenLength = 9; // TenkanSen Length + tenkanSenMode = X_BOUNDARY_PRICE_HIGH_LOW; // TencanSen Mode + kijunSenLength = 26; // KijunSen Length + kijunSenMode = X_BOUNDARY_PRICE_HIGH_LOW; // KijunSen Mode + senkouSpanBLength = 52; // SenkouSpan B Length + senkouSpanBMode = X_BOUNDARY_PRICE_HIGH_LOW; // SenkouSpan B Mode + + // + // Presentation ... + startCalculationForLastBars = 1000; // Calculate Last n Bars + shiftKumo = true; // Shift Kumo + showTenkanSen = true; // Show TenkanSen + showKijunSen = true; // Show KijunSen + showChikouSpan = true; // Show ChikouSpan + showSenkouSpanA = true; // Show Senkou Span A + showSenkouSpanB = true; // Show Senkou Span B + showKumo = true; // Show Kumo + } + + // + // Validate ... + bool IsValid() + { + // + bool result = false; + + // + result = + // + kijunSenLength > 0 && + tenkanSenLength > 0 && + senkouSpanBLength > 0 && + IsValid(kijunSenMode) && + IsValid(tenkanSenMode) && + IsValid(chikouSpanMode) && + IsValid(senkouSpanBMode) + // + ; + + // + return result; + } + + // + // Retrieve MAx Length ... + int Max() + { + // + int result = 0; + + // + result = MathMax(kijunSenLength, tenkanSenLength); + result = MathMax(result, senkouSpanBLength); + + // + return result; + } +}; + +// +// Conditions ... +struct X121XICHConditions +{ + // + // Common ... + string symbol; + ENUM_TIMEFRAMES period; + datetime time; + + // + // Buffers ... + + // + double kijunSenBuffer[]; + double tenkanSenBuffer[]; + double chikouSpanBuffer[]; + double senkouSpanABuffer[]; + double senkouSpanBBuffer[]; + + // + // Conditions ... + + // + bool isTenkanSenOverKijunSen; + bool isTenkanSenUnderKijunSen; + + // + bool isTenkanSenCrossedOverKijunSen; + bool isTenkanSenCrossedUnderKijunSen; + + // + bool isSenkouSpanAOverB; + bool isSenkouSpanAUnderB; + + // + bool isSenkouSpanACrossedOverB; + bool isSenkouSpanACrossedUnderB; + + // + // Constructor ... + X121XICHConditions() + { + Clean(); + } + + // + // Tools ... + + /** + * Cleaning Up ... + */ + void Clean() + { + // + // Commons ... + symbol = NULL; + period = NULL; + time = NULL; + + // + // Buffers ... + + // + Clean(kijunSenBuffer); + Clean(tenkanSenBuffer); + Clean(chikouSpanBuffer); + Clean(senkouSpanABuffer); + Clean(senkouSpanBBuffer); + + // + ArraySetAsSeries(kijunSenBuffer, true); + ArraySetAsSeries(tenkanSenBuffer, true); + ArraySetAsSeries(chikouSpanBuffer, true); + ArraySetAsSeries(senkouSpanABuffer, true); + ArraySetAsSeries(senkouSpanBBuffer, true); + + // + // Conditions ... + + // + isTenkanSenOverKijunSen = false; + isTenkanSenUnderKijunSen = false; + + // + isTenkanSenCrossedOverKijunSen = false; + isTenkanSenCrossedUnderKijunSen = false; + + // + isSenkouSpanAOverB = false; + isSenkouSpanAUnderB = false; + + // + isSenkouSpanACrossedOverB = false; + isSenkouSpanACrossedUnderB = false; + + // + ZeroMemory(this); + } + + /** + * Generate Conditions Scores ... + * + * @param bullishScore: Double, Directional Scores Reference ... + * @param bearishScore: Double, Directional Scores Reference ... + */ + void GenerateScore( + double &bullishScore, + double &bearishScore // + ) + { + // + bullishScore = 0; + bearishScore = 0; + + // + double score = 1; + double minScore = 0.5; + double highScore = 1.5; + + // + if (isSenkouSpanAOverB) + { + bullishScore += minScore; + } + if (isTenkanSenOverKijunSen) + { + bullishScore += minScore; + } + if (isSenkouSpanACrossedOverB) + { + bullishScore += highScore; + } + if (isTenkanSenCrossedOverKijunSen) + { + bullishScore += highScore; + } + + // + if (isSenkouSpanAUnderB) + { + bearishScore += minScore; + } + if (isTenkanSenUnderKijunSen) + { + bearishScore += minScore; + } + if (isSenkouSpanACrossedUnderB) + { + bearishScore += highScore; + } + if (isTenkanSenCrossedUnderKijunSen) + { + bearishScore += highScore; + } + } + + /** + * Generate Summary String for Represent Conditions State ... + * + * @param onlyCommons: Boolean, Just Generate Only Commons Conditions ... + * @param onlyConditions: Boolean, Just Generate Only Conditions ... + * @param includeScores: Boolean, Attach Scores Representations on Result ... + * @param ignoreFalseConditions: Boolean, Ignore False Conditions on Result ... + * @param separator: String, Separate Lines ... + * + * @return ( string ) + */ + string GenerateSummary( + bool onlyCommons = false, + bool onlyConditions = false, + bool includeScores = true, + bool ignoreFalseConditions = true, + string separator = "\n" // + ) + { + // + string result = NULL; + + // + double bullishScore = 0; + double bearishScore = 0; + GenerateScore( + bullishScore, + bearishScore // + ); + + // + string scoresStr = + // + "Scores: " + separator + + "---------------" + separator + + "Bullish: " + ToString(bullishScore) + separator + + "Bearish: " + ToString(bearishScore) + separator + + "" + // + ; + + // + string commonStr = GenerateSpecifiedCommonSummary( + this, + separator, + includeScores // + ); + + // + string conditionsStr = + // + "-----------------------" + separator + + "XICH: " + separator + + "-----------------------" + separator + + ToString("isTenkanSenOverKijunSen", isTenkanSenOverKijunSen, ignoreFalseConditions, separator) + + ToString("isTenkanSenUnderKijunSen", isTenkanSenUnderKijunSen, ignoreFalseConditions, separator) + + ToString("isTenkanSenCrossedOverKijunSen", isTenkanSenCrossedOverKijunSen, ignoreFalseConditions, separator) + + ToString("isTenkanSenCrossedUnderKijunSen", isTenkanSenCrossedUnderKijunSen, ignoreFalseConditions, separator) + + ToString("isSenkouSpanAOverB", isSenkouSpanAOverB, ignoreFalseConditions, separator) + + ToString("isSenkouSpanAUnderB", isSenkouSpanAUnderB, ignoreFalseConditions, separator) + + ToString("isSenkouSpanACrossedOverB", isSenkouSpanACrossedOverB, ignoreFalseConditions, separator) + + ToString("isSenkouSpanACrossedUnderB", isSenkouSpanACrossedUnderB, ignoreFalseConditions, separator) + + // + "" + // + ; + + // + result = + // + "[" + GetTag() + "]" + separator + + (onlyConditions + ? "" + : commonStr) + + (!includeScores + ? "" + : scoresStr) + + " " + separator + + (onlyCommons + ? "" + : conditionsStr) + + "" + // + ; + + // + return result; + } + + /** + * Retrieve nique Tag Identifier ... + * + * @return ( string ) + */ + string GetTag() + { + return GetTypeName(this); + } + + // +}; + +// +// Class ... +class XCX121XICHHelper : public XCBaseHelper +{ + // + // Public ... + public: + // + // Props ... + + // + // Constructors ... + XCX121XICHHelper() + : XCBaseHelper(_Symbol, _Period) + { + } + + // + // Deconstructor ... + ~XCX121XICHHelper() + { + // + Clean(kijunSenBuffer); + Clean(tenkanSenBuffer); + Clean(chikouSpanBuffer); + Clean(senkouSpanABuffer); + Clean(senkouSpanBBuffer); + + // + mInputs.Clean(); + } + + // + // Tools ... + bool Init( + string symbol, // Trading Symbol + ENUM_TIMEFRAMES period, // Trading Period + X121XICHInputs &inputs // Inputs + ) + { + // + bool result = false; + + // + mSymbol = symbol; + mPeriod = period; + + // + result = inputs.IsValid(); + if (!result) + { + return result; + } + + // + ArraySetAsSeries(kijunSenBuffer, true); + ArraySetAsSeries(tenkanSenBuffer, true); + ArraySetAsSeries(chikouSpanBuffer, true); + ArraySetAsSeries(senkouSpanABuffer, true); + ArraySetAsSeries(senkouSpanBBuffer, true); + + // + mInputs = inputs; + + // + mHandler = iCustom( + mSymbol, + mPeriod, + "x-saherelm.x121.xich", + // + // Inputs ... + // + // Market ... + "", + mInputs.chikouSpanMode, // ChikouSpan Mode + mInputs.tenkanSenLength, // TenkanSen Length + mInputs.tenkanSenMode, // TencanSen Mode + mInputs.kijunSenLength, // KijunSen Length + mInputs.kijunSenMode, // KijunSen Mode + mInputs.senkouSpanBLength, // SenkouSpan B Length + mInputs.senkouSpanBMode, // SenkouSpan B Mode + // + // Presentation ... + "", + mInputs.startCalculationForLastBars, // Calculate Last n Bars + mInputs.shiftKumo, // Shift Kumo + mInputs.showTenkanSen, // Show TenkanSen + mInputs.showKijunSen, // Show KijunSen + mInputs.showChikouSpan, // Show ChikouSpan + mInputs.showSenkouSpanA, // Show Senkou Span A + mInputs.showSenkouSpanB, // Show Senkou Span B + mInputs.showKumo // Show Kumo + // + ); + result = mHandler != INVALID_HANDLE; + if (!result) + { + return result; + } + + // + return result; + } + + // + // Inputs ... + + // + X121XICHInputs GetInputs() + { + return mInputs; + } + + // + bool SetInputs( + X121XICHInputs &inputs // Configs + ) + { + // + return Init( + mSymbol, + mPeriod, + inputs + // + ); + } + + // + // Readers ... + + // + double GetTenkanSen( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(tenkanSenBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return tenkanSenBuffer[barIndex]; + } + + // + int CopyTenkanSen( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + tenkanSenBuffer, + buffer, + forceClean + // + ); + } + + // + double GetKijunSen( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(kijunSenBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return kijunSenBuffer[barIndex]; + } + + // + int CopyKijunSen( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + kijunSenBuffer, + buffer, + forceClean + // + ); + } + + // + double GetChikouSpan( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(chikouSpanBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return chikouSpanBuffer[barIndex]; + } + + // + int CopyChikouSpan( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + chikouSpanBuffer, + buffer, + forceClean + // + ); + } + + // + double GetSenkouSpanA( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(senkouSpanABuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return senkouSpanABuffer[barIndex]; + } + + // + int CopySenkouSpanA( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + senkouSpanABuffer, + buffer, + forceClean + // + ); + } + + // + double GetSenkouSpanB( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(senkouSpanBBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return senkouSpanBBuffer[barIndex]; + } + + // + int CopySenkouSpanB( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + senkouSpanBBuffer, + buffer, + forceClean + // + ); + } + + // + void Free() override + { + Cleanup(10); + } + + // + bool GetConditions( + X121XICHConditions &conditions, // + int barIndex = 0, // + int loopback = 5 // + ) + { + // + bool result = true; + + // + if (loopback < 5) + { + loopback = 5; + } + + // + conditions.Clean(); + + // + conditions.symbol = mSymbol; + conditions.period = mPeriod; + conditions.time = TimeCurrent(); + + // + int zIndex = barIndex; + int cIndex = zIndex + 1; + int pIndex = cIndex + 1; + int ppIndex = pIndex + 1; + + // + XOHCL zBar; + result = zBar.Init( + mSymbol, + mPeriod, + zIndex // + ); + if (!result) + { + return result; + } + + // + XOHCL cBar; + result = cBar.Init( + mSymbol, + mPeriod, + cIndex // + ); + if (!result) + { + return result; + } + + // + XOHCL pBar; + result = pBar.Init( + mSymbol, + mPeriod, + pIndex // + ); + if (!result) + { + return result; + } + + // + // Buffers ... + + // + CopyTenkanSen( + zIndex, + loopback, + conditions.tenkanSenBuffer // + ); + + // + CopyKijunSen( + zIndex, + loopback, + conditions.kijunSenBuffer // + ); + + // + CopyChikouSpan( + zIndex, + loopback, + conditions.chikouSpanBuffer // + ); + + // + CopySenkouSpanA( + zIndex, + loopback, + conditions.senkouSpanABuffer // + ); + + // + CopySenkouSpanB( + zIndex, + loopback, + conditions.senkouSpanBBuffer // + ); + + // + // Conditions ... + + // + int cIDX = 1; + int pIDX = cIDX + 1; + + // + bool isTenkanSenOverKijunSen = + conditions.tenkanSenBuffer[cIDX] > conditions.kijunSenBuffer[cIDX]; + bool isTenkanSenOverKijunSenPrev = + conditions.tenkanSenBuffer[pIDX] > conditions.kijunSenBuffer[pIDX]; + + // + bool isTenkanSenUnderKijunSen = + conditions.tenkanSenBuffer[cIDX] < conditions.kijunSenBuffer[cIDX]; + bool isTenkanSenUnderKijunSenPrev = + conditions.tenkanSenBuffer[pIDX] < conditions.kijunSenBuffer[pIDX]; + + // + bool isTenkanSenCrossedOverKijunSen = isTenkanSenOverKijunSen && + !isTenkanSenOverKijunSenPrev; + bool isTenkanSenCrossedUnderKijunSen = isTenkanSenUnderKijunSen && + !isTenkanSenUnderKijunSenPrev; + + // + bool isSenkouSpanAOverB = + conditions.senkouSpanABuffer[cIDX] > conditions.senkouSpanBBuffer[cIDX]; + bool isSenkouSpanAOverBPrev = + conditions.senkouSpanABuffer[pIDX] > conditions.senkouSpanBBuffer[pIDX]; + + // + bool isSenkouSpanAUnderB = + conditions.senkouSpanABuffer[cIDX] < conditions.senkouSpanBBuffer[cIDX]; + bool isSenkouSpanAUnderBPrev = + conditions.senkouSpanABuffer[pIDX] < conditions.senkouSpanBBuffer[pIDX]; + + // + bool isSenkouSpanACrossedOverB = isSenkouSpanAOverB && + !isSenkouSpanAOverBPrev; + bool isSenkouSpanACrossedUnderB = isSenkouSpanAUnderB && + !isSenkouSpanAUnderBPrev; + + // + conditions.isSenkouSpanAOverB = isSenkouSpanAOverB; + conditions.isSenkouSpanAUnderB = isSenkouSpanAUnderB; + conditions.isTenkanSenOverKijunSen = isTenkanSenOverKijunSen; + conditions.isTenkanSenUnderKijunSen = isTenkanSenUnderKijunSen; + conditions.isSenkouSpanACrossedOverB = isSenkouSpanACrossedOverB; + conditions.isSenkouSpanACrossedUnderB = isSenkouSpanACrossedUnderB; + conditions.isTenkanSenCrossedOverKijunSen = isTenkanSenCrossedOverKijunSen; + conditions.isTenkanSenCrossedUnderKijunSen = isTenkanSenCrossedUnderKijunSen; + + // + Cleanup(); + + // + zBar.Clean(); + cBar.Clean(); + pBar.Clean(); + + // + return result; + } + + // + // Protected ... + protected: + // + // Private ... + private: + // + // Props ... + X121XICHInputs mInputs; // Inputs ... + + // + // Buffers ... + double kijunSenBuffer[]; + double tenkanSenBuffer[]; + double chikouSpanBuffer[]; + double senkouSpanABuffer[]; + double senkouSpanBBuffer[]; + + // + void Calculate( + int barIndex = 0, + int maxRequiredBars = 100 // + ) + { + // + // Buffers ... + if (barIndex < 0) + { + barIndex = 0; + } + + // + CopyBuffer( + mHandler, + X121_XICH_KIJUNSEN_LINE, + barIndex, + maxRequiredBars, + kijunSenBuffer + // + ); + + // + CopyBuffer( + mHandler, + X121_XICH_TENKANSEN_LINE, + barIndex, + maxRequiredBars, + tenkanSenBuffer + // + ); + + // + CopyBuffer( + mHandler, + X121_XICH_CHIKOUSPAN_LINE, + barIndex, + maxRequiredBars, + chikouSpanBuffer + // + ); + + // + CopyBuffer( + mHandler, + X121_XICH_SENKOUSPANA_LINE, + barIndex, + maxRequiredBars, + senkouSpanABuffer + // + ); + + // + CopyBuffer( + mHandler, + X121_XICH_SENKOUSPANB_LINE, + barIndex, + maxRequiredBars, + senkouSpanBBuffer + // + ); + } + + // + void Cleanup( + int maxAllowed = 100 // + ) + { + // + CleanupArray( + kijunSenBuffer, + maxAllowed // + ); + + // + CleanupArray( + tenkanSenBuffer, + maxAllowed // + ); + + // + CleanupArray( + chikouSpanBuffer, + maxAllowed // + ); + + // + CleanupArray( + senkouSpanABuffer, + maxAllowed // + ); + + // + CleanupArray( + senkouSpanBBuffer, + maxAllowed // + ); + + // + } + + // +}; + +// +// Tools ... \ No newline at end of file diff --git a/BKPS/14040203/Helpers/x-saherelm.x121.xmas.helper.mq5 b/BKPS/14040203/Helpers/x-saherelm.x121.xmas.helper.mq5 new file mode 100644 index 0000000..5fbedf3 --- /dev/null +++ b/BKPS/14040203/Helpers/x-saherelm.x121.xmas.helper.mq5 @@ -0,0 +1,797 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Helper Class Library +// ---------------------------------------------- +// Name: XCX121XMASHelper +// Description: provides all Indicator +// Helper requirements ... +// +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +////////////////////////////////////////////////////// +// +// Global Properties ... +#property library +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://www.saherelm.ir" +#property version "1.00" +#property strict + +// +// Imports ... +#include "../Classes/x-saherelm.x-helper.class.mq5" + +// +// Definitions ... + +enum ENUM_X121_XMAS_BUFFERS +{ + // + X121_XMAS_UPPER_LINE = 0, + X121_XMAS_MID_LINE = 1, + X121_XMAS_LOWER_LINE = 2, +}; + +// +// Input Models ... +struct X121XMASInputs +{ + // + // Props ... + int length; // MA Length + ENUM_MA_METHOD method; // MA Method + ENUM_APPLIED_PRICE upperAppliedTo; // Upper Applied To + ENUM_APPLIED_PRICE midAppliedTo; // Mid Applied To + ENUM_APPLIED_PRICE lowerAppliedTo; // Lower Applied To + + // + int startCalculationForLastBars; // Calculate Last n Bars + bool showUpper; // Show Upper + bool showMid; // Show Mid + bool showLower; // Show Lower + + // + // Constructor(s) ... + X121XMASInputs() + { + Clean(); + } + + // + // Tools ... + + // + // Clean ... + void Clean() + { + // + length = 0; // MA Length + method = MODE_EMA; // MA Method + upperAppliedTo = PRICE_HIGH; // Upper Applied To + midAppliedTo = PRICE_MEDIAN; // Mid Applied To + lowerAppliedTo = PRICE_LOW; // Lower Applied To + + // + startCalculationForLastBars = 0; // Calculate Last n Bars + showUpper = false; // Show Upper + showMid = false; // Show Mid + showLower = false; // Show Lower + + // + ZeroMemory(this); + } + + // + // Default ... + void Default() + { + // + length = 14; // MA Length + method = MODE_EMA; // MA Method + upperAppliedTo = PRICE_HIGH; // Upper Applied To + midAppliedTo = PRICE_MEDIAN; // Mid Applied To + lowerAppliedTo = PRICE_LOW; // Lower Applied To + + // + startCalculationForLastBars = 1000; // Calculate Last n Bars + showUpper = true; // Show Upper + showMid = true; // Show Mid + showLower = true; // Show Lower + } + + // + // Validate ... + bool IsValid() + { + // + bool result = false; + + // + result = + // + length > 0 + // + ; + + // + return result; + } + + // + // Retrieve MAx Length ... + int Max() + { + // + int result = 0; + + // + result = MathMax(result, length); + + // + return result; + } +}; + +// +// Conditions ... +struct X121XMASConditions +{ + // + // Common ... + string symbol; + ENUM_TIMEFRAMES period; + datetime time; + + // + // Buffers ... + double upperBuffer[]; + double midBuffer[]; + double lowerBuffer[]; + + // + // Conditions ... + + // + // Constructor ... + X121XMASConditions() + { + Clean(); + } + + // + // Tools ... + + /** + * Cleaning Up ... + */ + void Clean() + { + // + // Commons ... + symbol = NULL; + period = NULL; + time = NULL; + + // + // Buffers ... + + // + Clean(upperBuffer); + Clean(midBuffer); + Clean(lowerBuffer); + + // + ArraySetAsSeries(upperBuffer, true); + ArraySetAsSeries(midBuffer, true); + ArraySetAsSeries(lowerBuffer, true); + + // + // Conditions ... + + // + ZeroMemory(this); + } + + /** + * Generate Conditions Scores ... + * + * @param bullishScore: Double, Directional Scores Reference ... + * @param bearishScore: Double, Directional Scores Reference ... + */ + void GenerateScore( + double &bullishScore, + double &bearishScore // + ) + { + // + bullishScore = 0; + bearishScore = 0; + + // + // TODO: Implement if Required ... + } + + /** + * Generate Summary String for Represent Conditions State ... + * + * @param onlyCommons: Boolean, Just Generate Only Commons Conditions ... + * @param onlyConditions: Boolean, Just Generate Only Conditions ... + * @param includeScores: Boolean, Attach Scores Representations on Result ... + * @param ignoreFalseConditions: Boolean, Ignore False Conditions on Result ... + * @param separator: String, Separate Lines ... + * + * @return ( string ) + */ + string GenerateSummary( + bool onlyCommons = false, + bool onlyConditions = false, + bool includeScores = true, + bool ignoreFalseConditions = true, + string separator = "\n" // + ) + { + // + string result = NULL; + + // + double bullishScore = 0; + double bearishScore = 0; + GenerateScore( + bullishScore, + bearishScore // + ); + + // + string scoresStr = + // + "Scores: " + separator + + "---------------" + separator + + "Bullish: " + ToString(bullishScore) + separator + + "Bearish: " + ToString(bearishScore) + separator + + "" + // + ; + + // + string commonStr = GenerateSpecifiedCommonSummary( + this, + separator, + includeScores // + ); + + // + string conditionsStr = + // + // + "" + // + ; + + // + result = + // + "[" + GetTag() + "]" + separator + + (onlyConditions + ? "" + : commonStr) + + (!includeScores + ? "" + : scoresStr) + + " " + separator + + (onlyCommons + ? "" + : conditionsStr) + + "" + // + ; + + // + return result; + } + + /** + * Retrieve nique Tag Identifier ... + * + * @return ( string ) + */ + string GetTag() + { + return GetTypeName(this); + } + + // +}; + +// +// Class ... +class XCX121XMASHelper : public XCBaseHelper +{ + // + // Public ... + public: + // + // Props ... + + // + // Constructors ... + XCX121XMASHelper() + : XCBaseHelper(_Symbol, _Period) + { + } + + // + // Deconstructor ... + ~XCX121XMASHelper() + { + // + mInputs.Clean(); + + // + Clean(upperBuffer); + Clean(midBuffer); + Clean(lowerBuffer); + } + + // + // Tools ... + bool Init( + string symbol, // Trading Symbol + ENUM_TIMEFRAMES period, // Trading Period + X121XMASInputs &inputs // Inputs + ) + { + // + bool result = false; + + // + mSymbol = symbol; + mPeriod = period; + + // + result = inputs.IsValid(); + if (!result) + { + return result; + } + + // + ArraySetAsSeries(upperBuffer, true); + ArraySetAsSeries(midBuffer, true); + ArraySetAsSeries(lowerBuffer, true); + + // + mInputs = inputs; + + // + mHandler = iCustom( + mSymbol, + mPeriod, + "x-saherelm.x121.xmas", + // + // Inputs ... + // + // Market ... + "", + mInputs.length, + mInputs.method, + mInputs.upperAppliedTo, + mInputs.midAppliedTo, + mInputs.lowerAppliedTo, + // + // Presentation ... + "", + // + mInputs.startCalculationForLastBars, + // + mInputs.showUpper, + mInputs.showMid, + mInputs.showLower + // + ); + result = mHandler != INVALID_HANDLE; + if (!result) + { + return result; + } + + // + return result; + } + + // + // Inputs ... + + // + X121XMASInputs GetInputs() + { + return mInputs; + } + + // + bool SetInputs( + X121XMASInputs &inputs // Configs + ) + { + // + return Init( + mSymbol, + mPeriod, + inputs + // + ); + } + + // + // Readers ... + + // + // Upper ... + + // + double GetUpper( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(upperBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return upperBuffer[barIndex]; + } + + // + int CopyUpper( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + upperBuffer, + buffer, + forceClean + // + ); + } + + // + // Mid ... + + // + double GetUMid( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(midBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return midBuffer[barIndex]; + } + + // + int CopyMid( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + midBuffer, + buffer, + forceClean + // + ); + } + + // + // Lower ... + + // + double GetULower( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(lowerBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return lowerBuffer[barIndex]; + } + + // + int CopyLower( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + lowerBuffer, + buffer, + forceClean + // + ); + } + + // + void Free() override + { + Cleanup(10); + } + + // + bool GetConditions( + X121XMASConditions &conditions, // + int barIndex = 0, // + int loopback = 5 // + ) + { + // + bool result = true; + + // + if (loopback < 5) + { + loopback = 5; + } + + // + conditions.Clean(); + + // + conditions.symbol = mSymbol; + conditions.period = mPeriod; + conditions.time = TimeCurrent(); + + // + int zIndex = barIndex; + int cIndex = zIndex + 1; + int pIndex = cIndex + 1; + int ppIndex = pIndex + 1; + + // + XOHCL zBar; + result = zBar.Init( + mSymbol, + mPeriod, + zIndex // + ); + if (!result) + { + return result; + } + + // + XOHCL cBar; + result = cBar.Init( + mSymbol, + mPeriod, + cIndex // + ); + if (!result) + { + return result; + } + + // + XOHCL pBar; + result = pBar.Init( + mSymbol, + mPeriod, + pIndex // + ); + if (!result) + { + return result; + } + + // + // Buffers ... + + // + CopyUpper( + zIndex, + loopback, + conditions.upperBuffer // + ); + + // + CopyMid( + zIndex, + loopback, + conditions.midBuffer // + ); + + // + CopyLower( + zIndex, + loopback, + conditions.lowerBuffer // + ); + + // + // Conditions ... + + // + int cIDX = 1; + int pIDX = cIDX + 1; + + // + // SAR ... + + // + Cleanup(); + + // + zBar.Clean(); + cBar.Clean(); + pBar.Clean(); + + // + return result; + } + + // + // Protected ... + protected: + // + // Private ... + private: + // + // Props ... + X121XMASInputs mInputs; // Inputs ... + + // + // Buffers ... + double upperBuffer[]; + double midBuffer[]; + double lowerBuffer[]; + + // + void Calculate( + int barIndex = 0, + int maxRequiredBars = 100 // + ) + { + // + // Buffers ... + if (barIndex < 0) + { + barIndex = 0; + } + + // + // FAST ... + CopyBuffer( + mHandler, + X121_XMAS_UPPER_LINE, + barIndex, + maxRequiredBars, + upperBuffer + // + ); + + // + // FAST STATE ... + CopyBuffer( + mHandler, + X121_XMAS_MID_LINE, + barIndex, + maxRequiredBars, + midBuffer + // + ); + + // + // MID ... + CopyBuffer( + mHandler, + X121_XMAS_LOWER_LINE, + barIndex, + maxRequiredBars, + lowerBuffer + // + ); + } + + // + void Cleanup( + int maxAllowed = 100 // + ) + { + // + CleanupArray( + upperBuffer, + maxAllowed // + ); + + // + CleanupArray( + midBuffer, + maxAllowed // + ); + + // + CleanupArray( + lowerBuffer, + maxAllowed // + ); + + // + } + + // +}; + +// +// Tools ... \ No newline at end of file diff --git a/BKPS/14040203/Helpers/x-saherelm.x121.xoscs.helper.mq5 b/BKPS/14040203/Helpers/x-saherelm.x121.xoscs.helper.mq5 new file mode 100644 index 0000000..720c8d3 --- /dev/null +++ b/BKPS/14040203/Helpers/x-saherelm.x121.xoscs.helper.mq5 @@ -0,0 +1,3498 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Helper Class Library +// ---------------------------------------------- +// Name: XCX121XOCSHelper +// Description: provides all Indicator +// Helper requirements ... +// +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +////////////////////////////////////////////////////// +// +// Global Properties ... +#property library +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://www.saherelm.ir" +#property version "1.00" +#property strict + +// +// Imports ... +#include "../Classes/x-saherelm.x-helper.class.mq5" + +// +// Buffers ... +enum ENUM_X121_XOSCS_BUFFERS +{ + // + // https://www.mql5.com/en/articles/11467 ... + X121_XOSCS_XAC_LINE = 0, + // https://www.mql5.com/en/articles/10993 ... + X121_XOSCS_XAD_LINE = 1, + // https://www.mql5.com/en/articles/10715 ... + X121_XOSCS_XADX_LINE = 2, + X121_XOSCS_XADX_P_LINE = 3, + X121_XOSCS_XADX_N_LINE = 4, + // https://www.mql5.com/en/articles/10748 ... + X121_XOSCS_XATR_LINE = 5, + // https://www.mql5.com/en/articles/10592 ... + X121_XOSCS_XCCI_LINE = 6, + // https://www.mql5.com/en/articles/10528 ... + X121_XOSCS_XRSI_LINE = 7, + // https://www.mql5.com/en/articles/11037 ... + X121_XOSCS_XMFI_LINE = 8, + // https://www.mql5.com/en/articles/11425 ... + X121_XOSCS_XRVI_LINE = 9, + X121_XOSCS_XRVI_S_LINE = 10, + // https://www.mql5.com/en/articles/10674 ... + X121_XOSCS_XMACD_LINE = 11, + X121_XOSCS_XMACD_S_LINE = 12, + // https://www.mql5.com/en/articles/10547 ... + X121_XOSCS_XMOMENTUM_LINE = 13, + // https://www.mql5.com/en/articles/10692 .. + X121_XOSCS_XSTOCHASTIC_LINE = 14, + X121_XOSCS_XSTOCHASTIC_S_LINE = 15, +}; + +// +// Inputs ... +struct X121XOCSInputs +{ + // + // Props ... + + // + // Accumulation/Distribution ... + ENUM_APPLIED_VOLUME adAppliedTo; // Applied To + + // + // AC ... + int acBullishLevel; // Bullish Level + int acBearishLevel; // Bearish Level + + // + // ADX ... + int adxLength; // Length + int adxThreshold; // Big Movement Threshold + + // + // ATR ... + int atrLength; // Length + + // + // CCI ... + int cciLength; // Length + ENUM_APPLIED_PRICE cciAppliedTo; // Applied To + int cciOBLevel; // Over Bought Level + int cciOSLevel; // Over Sold Level + int cciReversalLevel; // Reversal Level + + // + // RSI ... + int rsiLength; // Length + ENUM_APPLIED_PRICE rsiAppliedTo; // Applied To + int rsiOBLevel; // Over Bought Level + int rsiOSLevel; // Over Sold Level + int rsiReversalLevel; // Reversal Level + + // + // MFI ... + int mfiLength; // Length + ENUM_APPLIED_VOLUME mfiAppliedTo; // Applied To + int mfiOBLevel; // Over Bought Level + int mfiOSLevel; // Over Sold Level + int mfiReversalLevel; // Reversal Level + + // + // RVI ... + int rviLength; // Length + int rviBullishLevel; // Bullish Level + int rviBearishLevel; // Bearish Level + + // + // MACD ... + int macdFastLength; // Fast EMA Length + int macdSlowLength; // Slow EMA Length + int macdSignalLength; // Signal Length + ENUM_APPLIED_PRICE macdAppliedTo; // Applied To + int macdBullishLevel; // Bullish Level + int macdBearishLevel; // Bearish Level + + // + // Momentum ... + int momentumLength; // Length + ENUM_APPLIED_PRICE momentumAppliedTo; // Applied To + int momentumBullishLevel; // Bullish Level + int momentumBearishLevel; // Bearish Level + + // + // Stochastic ... + int stochasticKLength; // K Length (Bars for Calculation) + int stochasticDLength; // D Length (first Smoothing) + int stochasticSmoothingLength; // Smoothing Length + ENUM_MA_METHOD stochasticSmoothingMethod; // Smoothing Method + ENUM_STO_PRICE stochasticAppliedTo; // Applied To + int stochasticOBLevel; // Over Bought Level + int stochasticOSLevel; // Over Sold Level + int stochasticReversalLevel; // Reversal Level + + // + // Presentation ... + int startCalculationForLastBars; // Calculate Last n Bars + + // + // Constructor(s) ... + X121XOCSInputs() + { + Clean(); + } + + // + // Tools ... + + // + // Clean ... + void Clean() + { + // + // Accumulation/Distribution ... + adAppliedTo = VOLUME_TICK; // Applied To + + // + // AC ... + acBullishLevel = 0; + acBearishLevel = 0; + + // + // ADX ... + adxLength = 0; // Length + adxThreshold = 0; // Big Movement Threshold + + // + // ATR ... + atrLength = 0; // Length + + // + // CCI ... + cciLength = 0; // Length + cciAppliedTo = PRICE_TYPICAL; // Applied To + cciOBLevel = 100; // Over Bought Level + cciOSLevel = -100; // Over Sold Level + cciReversalLevel = 0; // Reversal Level + + // + // RSI ... + rsiLength = 0; // Length + rsiAppliedTo = PRICE_CLOSE; // Applied To + rsiOBLevel = 0; // Over Bought Level + rsiOSLevel = 0; // Over Sold Level + rsiReversalLevel = 0; // Reversal Level + + // + // MFI ... + mfiLength = 0; // Length + mfiAppliedTo = VOLUME_TICK; // Applied To + mfiOBLevel = 0; // Over Bought Level + mfiOSLevel = 0; // Over Sold Level + mfiReversalLevel = 0; // Reversal Level + + // + // RVI ... + rviLength = 0; // Length + rviBullishLevel = 0; // Bullish Level + rviBearishLevel = 0; // Bearish Level + + // + // MACD ... + macdFastLength = 0; // Fast EMA Length + macdSlowLength = 0; // Slow EMA Length + macdSignalLength = 0; // Signal Length + macdAppliedTo = PRICE_CLOSE; // Applied To + macdBullishLevel = 0; // Bullish Level + macdBearishLevel = 0; // Bearish Level + + // + // Momentum ... + momentumLength = 0; // Length + momentumAppliedTo = PRICE_CLOSE; // Applied To + momentumBullishLevel = 0; // Bullish Level + momentumBearishLevel = 0; // Bearish Level + + // + // Stochastic ... + stochasticKLength = 0; // K Length (Bars for Calculation) + stochasticDLength = 0; // D Length (first Smoothing) + stochasticSmoothingLength = 0; // Smoothing Length + stochasticSmoothingMethod = MODE_SMA; // Smoothing Method + stochasticAppliedTo = STO_LOWHIGH; // Applied To + stochasticOBLevel = 0; // Over Bought Level + stochasticOSLevel = 0; // Over Sold Level + stochasticReversalLevel = 0; // Reversal Level + + // + // Presentation ... + startCalculationForLastBars = 0; // Calculate Last n Bars + + // + ZeroMemory(this); + } + + // + // Default ... + void Default() + { + // + // Accumulation/Distribution ... + adAppliedTo = VOLUME_TICK; // Applied To + + // + // AC ... + acBullishLevel = 0; + acBearishLevel = 0; + + // + // ADX ... + adxLength = 14; // Length + adxThreshold = 25; // Big Movement Threshold + + // + // ATR ... + atrLength = 14; // Length + + // + // CCI ... + cciLength = 14; // Length + cciAppliedTo = PRICE_TYPICAL; // Applied To + cciOBLevel = 100; // Over Bought Level + cciOSLevel = -100; // Over Sold Level + cciReversalLevel = 0; // Reversal Level + + // + // RSI ... + rsiLength = 14; // Length + rsiAppliedTo = PRICE_CLOSE; // Applied To + rsiOBLevel = 70; // Over Bought Level + rsiOSLevel = 30; // Over Sold Level + rsiReversalLevel = 50; // Reversal Level + + // + // MFI ... + mfiLength = 14; // Length + mfiAppliedTo = VOLUME_TICK; // Applied To + mfiOBLevel = 80; // Over Bought Level + mfiOSLevel = 20; // Over Sold Level + mfiReversalLevel = 50; // Reversal Level + + // + // RVI ... + rviLength = 14; // Length + rviBullishLevel = 0; // Bullish Level + rviBearishLevel = 0; // Bearish Level + + // + // MACD ... + macdFastLength = 12; // Fast EMA Length + macdSlowLength = 26; // Slow EMA Length + macdSignalLength = 9; // Signal Length + macdAppliedTo = PRICE_CLOSE; // Applied To + macdBullishLevel = 0; // Bullish Level + macdBearishLevel = 0; // Bearish Level + + // + // Momentum ... + momentumLength = 14; // Length + momentumAppliedTo = PRICE_CLOSE; // Applied To + momentumBullishLevel = 100; // Bullish Level + momentumBearishLevel = 100; // Bearish Level + + // + // Stochastic ... + stochasticKLength = 5; // K Length (Bars for Calculation) + stochasticDLength = 3; // D Length (first Smoothing) + stochasticSmoothingLength = 3; // Smoothing Length + stochasticSmoothingMethod = MODE_SMA; // Smoothing Method + stochasticAppliedTo = STO_LOWHIGH; // Applied To + stochasticOBLevel = 80; // Over Bought Level + stochasticOSLevel = 20; // Over Sold Level + stochasticReversalLevel = 50; // Reversal Level + + // + // Presentation ... + startCalculationForLastBars = 1000; // Calculate Last n Bars + } + + // + // Validate ... + bool IsValid() + { + // + bool result = false; + + // + result = + // + adxLength > 0 && + adxThreshold > 0 && + // + atrLength > 0 && + // + cciLength > 0 && + cciOBLevel > 0 && + cciOSLevel != 0 && + cciOBLevel > cciReversalLevel && + cciOSLevel < cciReversalLevel && + // + rsiLength > 0 && + rsiOBLevel > 0 && + rsiOSLevel > 0 && + rsiReversalLevel > 0 && + rsiOBLevel > rsiReversalLevel && + rsiOSLevel < rsiReversalLevel && + // + mfiLength > 0 && + mfiOBLevel > 0 && + mfiOSLevel > 0 && + mfiReversalLevel > 0 && + mfiOBLevel > mfiReversalLevel && + mfiOSLevel < mfiReversalLevel && + // + rviLength > 0 && + // + macdFastLength > 0 && + macdSlowLength > 0 && + macdSignalLength > 0 && + macdFastLength < macdSlowLength && + // + stochasticKLength > 0 && + stochasticDLength > 0 && + stochasticSmoothingLength > 0 && + stochasticOBLevel > 0 && + stochasticOSLevel > 0 && + stochasticReversalLevel > 0 && + stochasticOBLevel > stochasticReversalLevel && + stochasticOSLevel < stochasticReversalLevel && + // + momentumLength > 0 + // + ; + + // + return result; + } + + // + // Retrieve MAx Length ... + int Max() + { + // + int result = 0; + + // + result = MathMax(adxLength, atrLength); + result = MathMax(result, cciLength); + result = MathMax(result, rsiLength); + result = MathMax(result, mfiLength); + result = MathMax(result, rviLength); + result = MathMax(result, momentumLength); + result = MathMax(result, macdFastLength); + result = MathMax(result, macdSlowLength); + result = MathMax(result, macdSignalLength); + result = MathMax(result, stochasticKLength); + result = MathMax(result, stochasticDLength); + result = MathMax(result, stochasticSmoothingLength); + + // + return result; + } +}; + +// +// Conditions ... +struct X121XOCSConditions +{ + // + // Common ... + string symbol; + ENUM_TIMEFRAMES period; + datetime time; + + // + // Buffers ... + double acBuffer[]; + double adBuffer[]; + double atrBuffer[]; + double cciBuffer[]; + double rsiBuffer[]; + double mfiBuffer[]; + double rviBuffer[]; + double adxBuffer[]; + double adxpBuffer[]; + double adxnBuffer[]; + double macdBuffer[]; + double momentumBuffer[]; + double rviSignalBuffer[]; + double macdSignalBuffer[]; + double stochasticBuffer[]; + double stochasticSignalBuffer[]; + + // + // Values ... + + // + double adxThreshold; // Big Movement Threshold + double cciOBLevel; // Over Bought Level + double cciOSLevel; // Over Sold Level + double cciReversalLevel; // Reversal Level + double rsiOBLevel; // Over Bought Level + double rsiOSLevel; // Over Sold Level + double rsiReversalLevel; // Reversal Level + double mfiOBLevel; // Over Bought Level + double mfiOSLevel; // Over Sold Level + double mfiReversalLevel; // Reversal Level + double rviBullishLevel; // Bullish Level + double rviBearishLevel; // Bearish Level + double macdBullishLevel; // Bullish Level + double macdBearishLevel; // Bearish Level + double momentumBullishLevel; // Bullish Level + double momentumBearishLevel; // Bearish Level + double stochasticOBLevel; // Over Bought Level + double stochasticOSLevel; // Over Sold Level + double stochasticReversalLevel; // Reversal Level + + // + // Conditions ... + + // + // AC ... + + // + bool isACBullish; + bool isACBearish; + + // + bool isACSwitchedToBullish; + bool isACSwitchedToBearish; + + // + bool isACOverMax; + bool isACUnderMin; + + // + // AD ... + + // + bool isADBiggerLast; + bool isADLesserLast; + + // + bool isADOverMax; + bool isADUnderMin; + + // + // ADX ... + + // + bool isADXBiggerLast; + bool isADXLesserLast; + + // + bool isADXOverThreshold; + bool isADXUnderThreshold; + + // + bool isDXPBiggerThanDXN; + bool isDXNBiggerThanDXP; + + // + bool isADXBullish; + bool isADXBearish; + + // + bool isADXSwitchedToBullish; + bool isADXSwitchedToBearish; + + // + // ATR ... + + bool isATROverLast; + bool isATRUnderLast; + + // + // CCI ... + + // + bool isCCIBullish; + bool isCCIBearish; + + // + bool isCCISwitchedToBullish; + bool isCCISwitchedToBearish; + + // + bool isCCIOB; + bool isCCIOS; + + // + bool isCCICrossedOverOB; + bool isCCICrossedOverOS; + + // + bool isCCICrossedUnderOB; + bool isCCICrossedUnderOS; + + // + // RSI ... + + // + bool isRSIBullish; + bool isRSIBearish; + + // + bool isRSISwitchedToBullish; + bool isRSISwitchedToBearish; + + // + bool isRSIOB; + bool isRSIOS; + + // + bool isRSICrossedOverOB; + bool isRSICrossedOverOS; + + // + bool isRSICrossedUnderOB; + bool isRSICrossedUnderOS; + + // + // MFI ... + + // + bool isMFIBullish; + bool isMFIBearish; + + // + bool isMFISwitchedToBullish; + bool isMFISwitchedToBearish; + + // + bool isMFIOB; + bool isMFIOS; + + // + bool isMFICrossedOverOB; + bool isMFICrossedOverOS; + + // + bool isMFICrossedUnderOB; + bool isMFICrossedUnderOS; + + // + // RVI ... + + // + bool isRVIBullish; + bool isRVIBearish; + + // + bool isRVISwitchedToBullish; + bool isRVISwitchedToBearish; + + // + bool isRVIOverSignal; + bool isRVIUnderSignal; + + // + bool isRVICrossedOverSignal; + bool isRVICrossedUnderSignal; + + // + // MACD ... + + // + bool isMACDBullish; + bool isMACDBearish; + + // + bool isMACDSwitchedToBullish; + bool isMACDSwitchedToBearish; + + // + bool isMACDOverSignal; + bool isMACDUnderSignal; + + // + bool isMACDCrossedOverSignal; + bool isMACDCrossedUnderSignal; + + // + // MOMENTUM ... + + // + bool isMomentumBullish; + bool isMomentumBearish; + + // + bool isMomentumSwitchedToBullish; + bool isMomentumSwitchedToBearish; + + // + // STOCHASTIC ... + + // + bool isStochasticBullish; + bool isStochasticBearish; + + // + bool isStochasticSwitchedToBullish; + bool isStochasticSwitchedToBearish; + + // + bool isStochasticOverSignal; + bool isStochasticUnderSignal; + + // + bool isStochasticCrossedOverSignal; + bool isStochasticCrossedUnderSignal; + + // + bool isStochasticOB; + bool isStochasticOS; + + // + bool isStochasticCrossedOverOB; + bool isStochasticCrossedOverOS; + + // + bool isStochasticCrossedUnderOB; + bool isStochasticCrossedUnderOS; + + // + // Constructor ... + X121XOCSConditions() + { + Clean(); + } + + // + // Tools ... + + /** + * Cleaning Up ... + */ + void Clean() + { + // + // Commons ... + symbol = NULL; + period = NULL; + time = NULL; + + // + // Buffers ... + + // + Clean(acBuffer); + Clean(adBuffer); + Clean(atrBuffer); + Clean(cciBuffer); + Clean(rsiBuffer); + Clean(mfiBuffer); + Clean(rviBuffer); + Clean(adxBuffer); + Clean(adxpBuffer); + Clean(adxnBuffer); + Clean(macdBuffer); + Clean(momentumBuffer); + Clean(rviSignalBuffer); + Clean(macdSignalBuffer); + Clean(stochasticBuffer); + Clean(stochasticSignalBuffer); + + // + ArraySetAsSeries(acBuffer, true); + ArraySetAsSeries(adBuffer, true); + ArraySetAsSeries(atrBuffer, true); + ArraySetAsSeries(cciBuffer, true); + ArraySetAsSeries(rsiBuffer, true); + ArraySetAsSeries(mfiBuffer, true); + ArraySetAsSeries(rviBuffer, true); + ArraySetAsSeries(adxBuffer, true); + ArraySetAsSeries(adxpBuffer, true); + ArraySetAsSeries(adxnBuffer, true); + ArraySetAsSeries(macdBuffer, true); + ArraySetAsSeries(momentumBuffer, true); + ArraySetAsSeries(rviSignalBuffer, true); + ArraySetAsSeries(macdSignalBuffer, true); + ArraySetAsSeries(stochasticBuffer, true); + ArraySetAsSeries(stochasticSignalBuffer, true); + + // + // Values ... + + // + adxThreshold = 0.0; + cciOBLevel = 0.0; + cciOSLevel = 0.0; + cciReversalLevel = 0.0; + rsiOBLevel = 0.0; + rsiOSLevel = 0.0; + rsiReversalLevel = 0.0; + mfiOBLevel = 0.0; + mfiOSLevel = 0.0; + mfiReversalLevel = 0.0; + rviBullishLevel = 0.0; + rviBearishLevel = 0.0; + macdBullishLevel = 0.0; + macdBearishLevel = 0.0; + momentumBullishLevel = 0.0; + momentumBearishLevel = 0.0; + stochasticOBLevel = 0.0; + stochasticOSLevel = 0.0; + stochasticReversalLevel = 0.0; + + // + // Conditions ... + + // + // AC ... + + // + isACBullish = false; + isACBearish = false; + isACSwitchedToBullish = false; + isACSwitchedToBearish = false; + isACOverMax = false; + isACUnderMin = false; + + // + // AD ... + + // + isADBiggerLast = false; + isADLesserLast = false; + isADOverMax = false; + isADUnderMin = false; + + // + // ADX ... + + // + isADXBiggerLast = false; + isADXLesserLast = false; + isADXOverThreshold = false; + isADXUnderThreshold = false; + isDXPBiggerThanDXN = false; + isDXNBiggerThanDXP = false; + isADXBullish = false; + isADXBearish = false; + isADXSwitchedToBullish = false; + isADXSwitchedToBearish = false; + + // + // ATR ... + + // + isATROverLast = false; + isATRUnderLast = false; + + // + // CCI ... + + // + isCCIBullish = false; + isCCIBearish = false; + isCCISwitchedToBullish = false; + isCCISwitchedToBearish = false; + isCCIOB = false; + isCCIOS = false; + isCCICrossedOverOB = false; + isCCICrossedOverOS = false; + isCCICrossedUnderOB = false; + isCCICrossedUnderOS = false; + + // + // RSI ... + + // + isRSIBullish = false; + isRSIBearish = false; + isRSISwitchedToBullish = false; + isRSISwitchedToBearish = false; + isRSIOB = false; + isRSIOS = false; + isRSICrossedOverOB = false; + isRSICrossedOverOS = false; + isRSICrossedUnderOB = false; + isRSICrossedUnderOS = false; + + // + // MFI ... + + // + isMFIBullish = false; + isMFIBearish = false; + isMFISwitchedToBullish = false; + isMFISwitchedToBearish = false; + isMFIOB = false; + isMFIOS = false; + isMFICrossedOverOB = false; + isMFICrossedOverOS = false; + isMFICrossedUnderOB = false; + isMFICrossedUnderOS = false; + + // + // RVI ... + + // + isRVIBullish = false; + isRVIBearish = false; + isRVISwitchedToBullish = false; + isRVISwitchedToBearish = false; + isRVIOverSignal = false; + isRVIUnderSignal = false; + isRVICrossedOverSignal = false; + isRVICrossedUnderSignal = false; + + // + // MACD ... + + // + isMACDBullish = false; + isMACDBearish = false; + isMACDSwitchedToBullish = false; + isMACDSwitchedToBearish = false; + isMACDOverSignal = false; + isMACDUnderSignal = false; + isMACDCrossedOverSignal = false; + isMACDCrossedUnderSignal = false; + + // + // MOMENTUM ... + + // + isMomentumBullish = false; + isMomentumBearish = false; + isMomentumSwitchedToBullish = false; + isMomentumSwitchedToBearish = false; + + // + // STOCHASTIC ... + + // + isStochasticBullish = false; + isStochasticBearish = false; + isStochasticSwitchedToBullish = false; + isStochasticSwitchedToBearish = false; + isStochasticOverSignal = false; + isStochasticUnderSignal = false; + isStochasticCrossedOverSignal = false; + isStochasticCrossedUnderSignal = false; + isStochasticOB = false; + isStochasticOS = false; + isStochasticCrossedOverOB = false; + isStochasticCrossedOverOS = false; + isStochasticCrossedUnderOB = false; + isStochasticCrossedUnderOS = false; + + // + ZeroMemory(this); + } + + /** + * Generate Conditions Scores ... + * + * @param bullishScore: Double, Directional Scores Reference ... + * @param bearishScore: Double, Directional Scores Reference ... + */ + void GenerateScore( + double &bullishScore, + double &bearishScore // + ) + { + // + bullishScore = 0; + bearishScore = 0; + + // + double score = 1; + double minScore = 0.5; + double highScore = 1.5; + + // + + // + // AC ... + + // + if (isACBullish) + { + bullishScore += minScore; + } + if (isACOverMax) + { + bullishScore += minScore; + } + if (isACSwitchedToBullish) + { + bullishScore += minScore; + } + + // + if (isACBearish) + { + bearishScore += minScore; + } + if (isACUnderMin) + { + bearishScore += minScore; + } + if (isACSwitchedToBearish) + { + bearishScore += minScore; + } + + // + // AD ... + + // + if (isADOverMax) + { + bullishScore += minScore; + } + if (isADBiggerLast) + { + bullishScore += minScore; + } + + // + if (isADUnderMin) + { + bearishScore += minScore; + } + if (isADLesserLast) + { + bearishScore += minScore; + } + + // + // ADX ... + + // + if (isADXBullish) + { + bullishScore += minScore; + } + if (isADXBiggerLast) + { + bullishScore += minScore; + } + if (isADXOverThreshold) + { + bullishScore += minScore; + } + if (isDXPBiggerThanDXN) + { + bullishScore += minScore; + } + if (isADXSwitchedToBullish) + { + bullishScore += minScore; + } + + // + if (isADXBearish) + { + bearishScore += minScore; + } + if (isADXLesserLast) + { + bearishScore += minScore; + } + if (isDXNBiggerThanDXP) + { + bearishScore += minScore; + } + if (isADXUnderThreshold) + { + bearishScore += minScore; + } + if (isADXSwitchedToBearish) + { + bearishScore += minScore; + } + + // + // ATR ... + + // + if (isATROverLast) + { + bullishScore += minScore; + } + + // + if (isATRUnderLast) + { + bearishScore += minScore; + } + + // + // CCI ... + + // + if (isCCIOS) + { + bullishScore += minScore; + } + if (isCCIBullish) + { + bullishScore += minScore; + } + if (isCCICrossedOverOS) + { + bullishScore += minScore; + } + if (isCCICrossedOverOB) + { + bullishScore += minScore; + } + if (isCCISwitchedToBullish) + { + bullishScore += minScore; + } + + // + if (isCCIOB) + { + bearishScore += minScore; + } + if (isCCIBearish) + { + bearishScore += minScore; + } + if (isCCICrossedUnderOS) + { + bearishScore += minScore; + } + if (isCCICrossedUnderOB) + { + bearishScore += minScore; + } + if (isCCISwitchedToBearish) + { + bearishScore += minScore; + } + + // + // RSI ... + + // + if (isRSIOS) + { + bullishScore += minScore; + } + if (isRSIBullish) + { + bullishScore += minScore; + } + if (isRSICrossedOverOB) + { + bullishScore += minScore; + } + if (isRSICrossedOverOS) + { + bullishScore += minScore; + } + if (isRSISwitchedToBullish) + { + bullishScore += minScore; + } + + // + if (isRSIOB) + { + bearishScore += minScore; + } + if (isRSIBearish) + { + bearishScore += minScore; + } + if (isRSICrossedUnderOB) + { + bearishScore += minScore; + } + if (isRSICrossedUnderOS) + { + bearishScore += minScore; + } + if (isRSISwitchedToBearish) + { + bearishScore += minScore; + } + + // + // MFI ... + + // + if (isMFIOS) + { + bullishScore += minScore; + } + if (isMFIBullish) + { + bullishScore += minScore; + } + if (isMFICrossedOverOB) + { + bullishScore += minScore; + } + if (isMFICrossedOverOS) + { + bullishScore += minScore; + } + if (isMFISwitchedToBullish) + { + bullishScore += minScore; + } + + // + if (isMFIOB) + { + bearishScore += minScore; + } + if (isMFIBearish) + { + bearishScore += minScore; + } + if (isMFICrossedUnderOB) + { + bearishScore += minScore; + } + if (isMFICrossedUnderOS) + { + bearishScore += minScore; + } + if (isMFISwitchedToBearish) + { + bearishScore += minScore; + } + + // + // RVI ... + + // + if (isRVIBullish) + { + bullishScore += minScore; + } + if (isRVIOverSignal) + { + bullishScore += minScore; + } + if (isRVISwitchedToBullish) + { + bullishScore += minScore; + } + if (isRVICrossedOverSignal) + { + bullishScore += minScore; + } + + // + if (isRVIBearish) + { + bearishScore += minScore; + } + if (isRVIUnderSignal) + { + bearishScore += minScore; + } + if (isRVISwitchedToBearish) + { + bearishScore += minScore; + } + if (isRVICrossedUnderSignal) + { + bearishScore += minScore; + } + + // + // MACD ... + + // + if (isMACDBullish) + { + bullishScore += minScore; + } + if (isMACDOverSignal) + { + bullishScore += minScore; + } + if (isMACDSwitchedToBullish) + { + bullishScore += minScore; + } + if (isMACDCrossedOverSignal) + { + bullishScore += minScore; + } + + // + if (isMACDBearish) + { + bearishScore += minScore; + } + if (isMACDUnderSignal) + { + bearishScore += minScore; + } + if (isMACDSwitchedToBearish) + { + bearishScore += minScore; + } + if (isMACDCrossedUnderSignal) + { + bearishScore += minScore; + } + + // + // MOMENTUM ... + + // + if (isMomentumBullish) + { + bullishScore += minScore; + } + if (isMomentumSwitchedToBullish) + { + bullishScore += minScore; + } + + // + if (isMomentumBearish) + { + bearishScore += minScore; + } + if (isMomentumSwitchedToBearish) + { + bearishScore += minScore; + } + + // + // STOCHASTIC ... + + // + if (isStochasticOS) + { + bullishScore += minScore; + } + if (isStochasticOverSignal) + { + bullishScore += minScore; + } + if (isStochasticBullish) + { + bullishScore += minScore; + } + if (isStochasticCrossedOverSignal) + { + bullishScore += minScore; + } + if (isStochasticCrossedOverOB) + { + bullishScore += minScore; + } + if (isStochasticCrossedOverOS) + { + bullishScore += minScore; + } + if (isStochasticSwitchedToBullish) + { + bullishScore += minScore; + } + + // + if (isStochasticOB) + { + bearishScore += minScore; + } + if (isStochasticUnderSignal) + { + bearishScore += minScore; + } + if (isStochasticBearish) + { + bearishScore += minScore; + } + if (isStochasticCrossedUnderSignal) + { + bearishScore += minScore; + } + if (isStochasticCrossedUnderOB) + { + bearishScore += minScore; + } + if (isStochasticCrossedUnderOS) + { + bearishScore += minScore; + } + if (isStochasticSwitchedToBearish) + { + bearishScore += minScore; + } + + // + } + + /** + * Generate Summary String for Represent Conditions State ... + * + * @param onlyCommons: Boolean, Just Generate Only Commons Conditions ... + * @param onlyConditions: Boolean, Just Generate Only Conditions ... + * @param includeScores: Boolean, Attach Scores Representations on Result ... + * @param ignoreFalseConditions: Boolean, Ignore False Conditions on Result ... + * @param separator: String, Separate Lines ... + * + * @return ( string ) + */ + string GenerateSummary( + bool onlyCommons = false, + bool onlyConditions = false, + bool includeScores = true, + bool ignoreFalseConditions = true, + string separator = "\n" // + ) + { + // + string result = NULL; + + // + double bullishScore = 0; + double bearishScore = 0; + GenerateScore( + bullishScore, + bearishScore // + ); + + // + string scoresStr = + // + "Scores: " + separator + + "---------------" + separator + + "Bullish: " + ToString(bullishScore) + separator + + "Bearish: " + ToString(bearishScore) + separator + + "" + // + ; + + // + string commonStr = GenerateSpecifiedCommonSummary( + this, + separator, + includeScores // + ); + + // + string conditionsStr = + // + "-----------------------" + separator + + "XOSCS: " + separator + + "-----------------------" + separator + + ToString("isACBullish", isACBullish, ignoreFalseConditions, separator) + + ToString("isACBearish", isACBearish, ignoreFalseConditions, separator) + + ToString("isACSwitchedToBullish", isACSwitchedToBullish, ignoreFalseConditions, separator) + + ToString("isACSwitchedToBearish", isACSwitchedToBearish, ignoreFalseConditions, separator) + + ToString("isACOverMax", isACOverMax, ignoreFalseConditions, separator) + + ToString("isACUnderMin", isACUnderMin, ignoreFalseConditions, separator) + + ToString("isADBiggerLast", isADBiggerLast, ignoreFalseConditions, separator) + + ToString("isADLesserLast", isADLesserLast, ignoreFalseConditions, separator) + + ToString("isADOverMax", isADOverMax, ignoreFalseConditions, separator) + + ToString("isADUnderMin", isADUnderMin, ignoreFalseConditions, separator) + + ToString("isADXBiggerLast", isADXBiggerLast, ignoreFalseConditions, separator) + + ToString("isADXLesserLast", isADXLesserLast, ignoreFalseConditions, separator) + + ToString("isADXOverThreshold", isADXOverThreshold, ignoreFalseConditions, separator) + + ToString("isADXUnderThreshold", isADXUnderThreshold, ignoreFalseConditions, separator) + + ToString("isDXPBiggerThanDXN", isDXPBiggerThanDXN, ignoreFalseConditions, separator) + + ToString("isDXNBiggerThanDXP", isDXNBiggerThanDXP, ignoreFalseConditions, separator) + + ToString("isADXBullish", isADXBullish, ignoreFalseConditions, separator) + + ToString("isADXBearish", isADXBearish, ignoreFalseConditions, separator) + + ToString("isADXSwitchedToBullish", isADXSwitchedToBullish, ignoreFalseConditions, separator) + + ToString("isADXSwitchedToBearish", isADXSwitchedToBearish, ignoreFalseConditions, separator) + + ToString("isATROverLast", isATROverLast, ignoreFalseConditions, separator) + + ToString("isATRUnderLast", isATRUnderLast, ignoreFalseConditions, separator) + + ToString("isCCIBullish", isCCIBullish, ignoreFalseConditions, separator) + + ToString("isCCIBearish", isCCIBearish, ignoreFalseConditions, separator) + + ToString("isCCISwitchedToBullish", isCCISwitchedToBullish, ignoreFalseConditions, separator) + + ToString("isCCISwitchedToBearish", isCCISwitchedToBearish, ignoreFalseConditions, separator) + + ToString("isCCIOB", isCCIOB, ignoreFalseConditions, separator) + + ToString("isCCIOS", isCCIOS, ignoreFalseConditions, separator) + + ToString("isCCICrossedOverOB", isCCICrossedOverOB, ignoreFalseConditions, separator) + + ToString("isCCICrossedOverOS", isCCICrossedOverOS, ignoreFalseConditions, separator) + + ToString("isCCICrossedUnderOB", isCCICrossedUnderOB, ignoreFalseConditions, separator) + + ToString("isCCICrossedUnderOS", isCCICrossedUnderOS, ignoreFalseConditions, separator) + + ToString("isRSIBullish", isRSIBullish, ignoreFalseConditions, separator) + + ToString("isRSIBearish", isRSIBearish, ignoreFalseConditions, separator) + + ToString("isRSISwitchedToBullish", isRSISwitchedToBullish, ignoreFalseConditions, separator) + + ToString("isRSISwitchedToBearish", isRSISwitchedToBearish, ignoreFalseConditions, separator) + + ToString("isRSIOB", isRSIOB, ignoreFalseConditions, separator) + + ToString("isRSIOS", isRSIOS, ignoreFalseConditions, separator) + + ToString("isRSICrossedOverOB", isRSICrossedOverOB, ignoreFalseConditions, separator) + + ToString("isRSICrossedOverOS", isRSICrossedOverOS, ignoreFalseConditions, separator) + + ToString("isRSICrossedUnderOB", isRSICrossedUnderOB, ignoreFalseConditions, separator) + + ToString("isRSICrossedUnderOS", isRSICrossedUnderOS, ignoreFalseConditions, separator) + + ToString("isMFIBullish", isMFIBullish, ignoreFalseConditions, separator) + + ToString("isMFIBearish", isMFIBearish, ignoreFalseConditions, separator) + + ToString("isMFISwitchedToBullish", isMFISwitchedToBullish, ignoreFalseConditions, separator) + + ToString("isMFISwitchedToBearish", isMFISwitchedToBearish, ignoreFalseConditions, separator) + + ToString("isMFIOB", isMFIOB, ignoreFalseConditions, separator) + + ToString("isMFIOS", isMFIOS, ignoreFalseConditions, separator) + + ToString("isMFICrossedOverOB", isMFICrossedOverOB, ignoreFalseConditions, separator) + + ToString("isMFICrossedOverOS", isMFICrossedOverOS, ignoreFalseConditions, separator) + + ToString("isMFICrossedUnderOB", isMFICrossedUnderOB, ignoreFalseConditions, separator) + + ToString("isMFICrossedUnderOS", isMFICrossedUnderOS, ignoreFalseConditions, separator) + + ToString("isRVIBullish", isRVIBullish, ignoreFalseConditions, separator) + + ToString("isRVIBearish", isRVIBearish, ignoreFalseConditions, separator) + + ToString("isRVISwitchedToBullish", isRVISwitchedToBullish, ignoreFalseConditions, separator) + + ToString("isRVISwitchedToBearish", isRVISwitchedToBearish, ignoreFalseConditions, separator) + + ToString("isRVIOverSignal", isRVIOverSignal, ignoreFalseConditions, separator) + + ToString("isRVIUnderSignal", isRVIUnderSignal, ignoreFalseConditions, separator) + + ToString("isRVICrossedOverSignal", isRVICrossedOverSignal, ignoreFalseConditions, separator) + + ToString("isRVICrossedUnderSignal", isRVICrossedUnderSignal, ignoreFalseConditions, separator) + + ToString("isMACDBullish", isMACDBullish, ignoreFalseConditions, separator) + + ToString("isMACDBearish", isMACDBearish, ignoreFalseConditions, separator) + + ToString("isMACDSwitchedToBullish", isMACDSwitchedToBullish, ignoreFalseConditions, separator) + + ToString("isMACDSwitchedToBearish", isMACDSwitchedToBearish, ignoreFalseConditions, separator) + + ToString("isMACDOverSignal", isMACDOverSignal, ignoreFalseConditions, separator) + + ToString("isMACDUnderSignal", isMACDUnderSignal, ignoreFalseConditions, separator) + + ToString("isMACDCrossedOverSignal", isMACDCrossedOverSignal, ignoreFalseConditions, separator) + + ToString("isMACDCrossedUnderSignal", isMACDCrossedUnderSignal, ignoreFalseConditions, separator) + + ToString("isMomentumBullish", isMomentumBullish, ignoreFalseConditions, separator) + + ToString("isMomentumBearish", isMomentumBearish, ignoreFalseConditions, separator) + + ToString("isMomentumSwitchedToBullish", isMomentumSwitchedToBullish, ignoreFalseConditions, separator) + + ToString("isMomentumSwitchedToBearish", isMomentumSwitchedToBearish, ignoreFalseConditions, separator) + + ToString("isStochasticBullish", isStochasticBullish, ignoreFalseConditions, separator) + + ToString("isStochasticBearish", isStochasticBearish, ignoreFalseConditions, separator) + + ToString("isStochasticSwitchedToBullish", isStochasticSwitchedToBullish, ignoreFalseConditions, separator) + + ToString("isStochasticSwitchedToBearish", isStochasticSwitchedToBearish, ignoreFalseConditions, separator) + + ToString("isStochasticOverSignal", isStochasticOverSignal, ignoreFalseConditions, separator) + + ToString("isStochasticUnderSignal", isStochasticUnderSignal, ignoreFalseConditions, separator) + + ToString("isStochasticCrossedOverSignal", isStochasticCrossedOverSignal, ignoreFalseConditions, separator) + + ToString("isStochasticCrossedUnderSignal", isStochasticCrossedUnderSignal, ignoreFalseConditions, separator) + + ToString("isStochasticOB", isStochasticOB, ignoreFalseConditions, separator) + + ToString("isStochasticOS", isStochasticOS, ignoreFalseConditions, separator) + + ToString("isStochasticCrossedOverOB", isStochasticCrossedOverOB, ignoreFalseConditions, separator) + + ToString("isStochasticCrossedOverOS", isStochasticCrossedOverOS, ignoreFalseConditions, separator) + + ToString("isStochasticCrossedUnderOB", isStochasticCrossedUnderOB, ignoreFalseConditions, separator) + + ToString("isStochasticCrossedUnderOS", isStochasticCrossedUnderOS, ignoreFalseConditions, separator) + + // + "" + // + ; + + // + result = + // + "[" + GetTag() + "]" + separator + + (onlyConditions + ? "" + : commonStr) + + (!includeScores + ? "" + : scoresStr) + + " " + separator + + (onlyCommons + ? "" + : conditionsStr) + + "" + // + ; + + // + return result; + } + + /** + * Retrieve nique Tag Identifier ... + * + * @return ( string ) + */ + string GetTag() + { + return GetTypeName(this); + } +}; + +// +// Helper Class Implementation ... +class XCX121XOCSHelper : XCBaseHelper +{ + // + // Public ... + public: + // + // Props ... + + // + // Constructors ... + XCX121XOCSHelper() + : XCBaseHelper(_Symbol, _Period) + { + } + + // + // Deconstructor ... + ~XCX121XOCSHelper() + { + // + mInputs.Clean(); + + // + Clean(acBuffer); + Clean(adBuffer); + Clean(atrBuffer); + Clean(cciBuffer); + Clean(rsiBuffer); + Clean(mfiBuffer); + Clean(rviBuffer); + Clean(adxBuffer); + Clean(adxpBuffer); + Clean(adxnBuffer); + Clean(macdBuffer); + Clean(momentumBuffer); + Clean(rviSignalBuffer); + Clean(macdSignalBuffer); + Clean(stochasticBuffer); + Clean(stochasticSignalBuffer); + } + + // + // Tools ... + bool Init( + string symbol, // Trading Symbol + ENUM_TIMEFRAMES period, // Trading Period + X121XOCSInputs &inputs // Inputs + ) + { + // + bool result = false; + + // + mSymbol = symbol; + mPeriod = period; + + // + result = inputs.IsValid(); + if (!result) + { + return result; + } + + // + ArraySetAsSeries(acBuffer, true); + ArraySetAsSeries(adBuffer, true); + ArraySetAsSeries(atrBuffer, true); + ArraySetAsSeries(cciBuffer, true); + ArraySetAsSeries(rsiBuffer, true); + ArraySetAsSeries(mfiBuffer, true); + ArraySetAsSeries(rviBuffer, true); + ArraySetAsSeries(adxBuffer, true); + ArraySetAsSeries(adxpBuffer, true); + ArraySetAsSeries(adxnBuffer, true); + ArraySetAsSeries(macdBuffer, true); + ArraySetAsSeries(momentumBuffer, true); + ArraySetAsSeries(rviSignalBuffer, true); + ArraySetAsSeries(macdSignalBuffer, true); + ArraySetAsSeries(stochasticBuffer, true); + ArraySetAsSeries(stochasticSignalBuffer, true); + + // + mInputs = inputs; + + // + mHandler = iCustom( + mSymbol, + mPeriod, + "x-saherelm.x121.xoscs", + // + // Inputs ... + // + // AD ... + "", + mInputs.adAppliedTo, + // + // ADX ... + "", + mInputs.adxLength, + // + // ATR ... + "", + mInputs.atrLength, + // + // CCI ... + "", + mInputs.cciLength, + mInputs.cciAppliedTo, + // + // RSI ... + "", + mInputs.rsiLength, + mInputs.rsiAppliedTo, + // + // MFI ... + "", + mInputs.mfiLength, + mInputs.mfiAppliedTo, + // + // RVI ... + "", + mInputs.rviLength, + // + // MACD ... + "", + mInputs.macdFastLength, + mInputs.macdSlowLength, + mInputs.macdSignalLength, + mInputs.macdAppliedTo, + // + // MOMENTUM ... + "", + mInputs.momentumLength, + mInputs.momentumAppliedTo, + // + // STOCHASTIC ... + "", + mInputs.stochasticKLength, + mInputs.stochasticDLength, + mInputs.stochasticSmoothingLength, + mInputs.stochasticSmoothingMethod, + mInputs.stochasticAppliedTo, + // + // Presentation ... + "", + // + mInputs.startCalculationForLastBars + // + ); + result = mHandler != INVALID_HANDLE; + if (!result) + { + return result; + } + + // + return result; + } + + // + // Inputs ... + + // + X121XOCSInputs GetInputs() + { + return mInputs; + } + + // + bool SetInputs( + X121XOCSInputs &inputs // Configs + ) + { + // + return Init( + mSymbol, + mPeriod, + inputs + // + ); + } + + // + // Readers ... + + // + // AC ... + + // + double GetAC( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(acBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return acBuffer[barIndex]; + } + + // + int CopyAC( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + acBuffer, + buffer, + forceClean + // + ); + } + + // + // AD ... + + // + double GetAD( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(adBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return adBuffer[barIndex]; + } + + // + int CopyAD( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + adBuffer, + buffer, + forceClean + // + ); + } + + // + // ADX ... + + // + double GetADX( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(adxBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return adxBuffer[barIndex]; + } + + // + int CopyADX( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + adxBuffer, + buffer, + forceClean + // + ); + } + + // + // ADXP ... + + // + double GetADXP( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(adxpBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return adxpBuffer[barIndex]; + } + + // + int CopyADXP( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + adxpBuffer, + buffer, + forceClean + // + ); + } + + // + // ADXN ... + + // + double GetADXN( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(adxnBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return adxnBuffer[barIndex]; + } + + // + int CopyADXN( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + adxnBuffer, + buffer, + forceClean + // + ); + } + + // + // ATR ... + + // + double GetATR( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(atrBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return atrBuffer[barIndex]; + } + + // + int CopyATR( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + atrBuffer, + buffer, + forceClean + // + ); + } + + // + // CCI ... + + // + double GetCCI( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(cciBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return cciBuffer[barIndex]; + } + + // + int CopyCCI( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + cciBuffer, + buffer, + forceClean + // + ); + } + + // + // RSI ... + + // + double GetRSI( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(rsiBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return rsiBuffer[barIndex]; + } + + // + int CopyRSI( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + rsiBuffer, + buffer, + forceClean + // + ); + } + + // + // MFI ... + + // + double GetMFI( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(mfiBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return mfiBuffer[barIndex]; + } + + // + int CopyMFI( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + mfiBuffer, + buffer, + forceClean + // + ); + } + + // + // Momentum ... + + // + double GetMomentum( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(momentumBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return momentumBuffer[barIndex]; + } + + // + int CopyMomentum( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + momentumBuffer, + buffer, + forceClean + // + ); + } + + // + // RVI ... + + // + double GetRVI( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(rviBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return rviBuffer[barIndex]; + } + + // + int CopyRVI( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + rviBuffer, + buffer, + forceClean + // + ); + } + + // + // RVI Signal ... + + // + double GetRVISignal( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(rviSignalBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return rviSignalBuffer[barIndex]; + } + + // + int CopyRVISignal( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + rviSignalBuffer, + buffer, + forceClean + // + ); + } + + // + // MACD ... + + // + double GetMACD( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(macdBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return macdBuffer[barIndex]; + } + + // + int CopyMACD( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + macdBuffer, + buffer, + forceClean + // + ); + } + + // + // MACD Signal ... + + // + double GetMACDSignal( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(macdSignalBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return macdSignalBuffer[barIndex]; + } + + // + int CopyMACDSignal( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + macdSignalBuffer, + buffer, + forceClean + // + ); + } + + // + // Stochastic ... + + // + double GetStochastic( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(stochasticBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return stochasticBuffer[barIndex]; + } + + // + int CopyStochastic( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + stochasticBuffer, + buffer, + forceClean + // + ); + } + + // + // Stochastic Signal ... + + // + double GetStochasticSignal( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(stochasticSignalBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return stochasticSignalBuffer[barIndex]; + } + + // + int CopyStochasticSignal( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + stochasticSignalBuffer, + buffer, + forceClean + // + ); + } + + // + void Free() override + { + Cleanup(10); + } + + // + bool GetConditions( + X121XOCSConditions &conditions, // + int barIndex = 0, // + int loopback = 5 // + ) + { + // + bool result = true; + + // + if (loopback < 5) + { + loopback = 5; + } + + // + conditions.Clean(); + + // + conditions.symbol = mSymbol; + conditions.period = mPeriod; + conditions.time = TimeCurrent(); + + // + int zIndex = barIndex; + int cIndex = zIndex + 1; + int pIndex = cIndex + 1; + int ppIndex = pIndex + 1; + + // + XOHCL zBar; + result = zBar.Init( + mSymbol, + mPeriod, + zIndex // + ); + if (!result) + { + return result; + } + + // + XOHCL cBar; + result = cBar.Init( + mSymbol, + mPeriod, + cIndex // + ); + if (!result) + { + return result; + } + + // + XOHCL pBar; + result = pBar.Init( + mSymbol, + mPeriod, + pIndex // + ); + if (!result) + { + return result; + } + + // + // Buffers ... + + // + CopyAC( + zIndex, + loopback, + conditions.acBuffer // + ); + + // + CopyAD( + zIndex, + loopback, + conditions.adBuffer // + ); + + // + CopyADX( + zIndex, + loopback, + conditions.adxBuffer // + ); + + // + CopyADXP( + zIndex, + loopback, + conditions.adxpBuffer // + ); + + // + CopyADXN( + zIndex, + loopback, + conditions.adxnBuffer // + ); + + // + CopyATR( + zIndex, + loopback, + conditions.atrBuffer // + ); + + // + CopyCCI( + zIndex, + loopback, + conditions.cciBuffer // + ); + + // + CopyRSI( + zIndex, + loopback, + conditions.rsiBuffer // + ); + + // + CopyMFI( + zIndex, + loopback, + conditions.mfiBuffer // + ); + + // + CopyMomentum( + zIndex, + loopback, + conditions.momentumBuffer // + ); + + // + CopyRVI( + zIndex, + loopback, + conditions.rviBuffer // + ); + + // + CopyRVISignal( + zIndex, + loopback, + conditions.rviSignalBuffer // + ); + + // + CopyMACD( + zIndex, + loopback, + conditions.macdBuffer // + ); + + // + CopyMACDSignal( + zIndex, + loopback, + conditions.macdSignalBuffer // + ); + + // + CopyStochastic( + zIndex, + loopback, + conditions.stochasticBuffer // + ); + + // + CopyStochasticSignal( + zIndex, + loopback, + conditions.stochasticSignalBuffer // + ); + + // + // Values ... + + // + conditions.adxThreshold = mInputs.adxThreshold; + conditions.cciOBLevel = mInputs.cciOBLevel; + conditions.cciOSLevel = mInputs.cciOSLevel; + conditions.cciReversalLevel = mInputs.cciReversalLevel; + conditions.rsiOBLevel = mInputs.rsiOBLevel; + conditions.rsiOSLevel = mInputs.rsiOSLevel; + conditions.rsiReversalLevel = mInputs.rsiReversalLevel; + conditions.mfiOBLevel = mInputs.mfiOBLevel; + conditions.mfiOSLevel = mInputs.mfiOSLevel; + conditions.mfiReversalLevel = mInputs.mfiReversalLevel; + conditions.rviBullishLevel = mInputs.rviBullishLevel; + conditions.rviBearishLevel = mInputs.rviBearishLevel; + conditions.macdBullishLevel = mInputs.macdBullishLevel; + conditions.macdBearishLevel = mInputs.macdBearishLevel; + conditions.momentumBullishLevel = mInputs.momentumBullishLevel; + conditions.momentumBearishLevel = mInputs.momentumBearishLevel; + conditions.stochasticOBLevel = mInputs.stochasticOBLevel; + conditions.stochasticOSLevel = mInputs.stochasticOSLevel; + conditions.stochasticReversalLevel = mInputs.stochasticReversalLevel; + + // + // Conditions ... + + // + int cIDX = 1; + int pIDX = cIDX + 1; + int ppIDX = pIDX + 1; + + // + // AC ... + + // + bool isACBullish = conditions.acBuffer[cIDX] > mInputs.acBullishLevel; + bool isACBullishPrev = conditions.acBuffer[pIDX] > mInputs.acBullishLevel; + bool isACSwitchedToBullish = isACBullish && + !isACBullishPrev; + + // + bool isACBearish = conditions.acBuffer[cIDX] < mInputs.acBearishLevel; + bool isACBearishPrev = conditions.acBuffer[pIDX] < mInputs.acBearishLevel; + bool isACSwitchedToBearish = isACBearish && + !isACBearishPrev; + + // + bool isACOverMax = conditions.acBuffer[cIDX] >= GetMax(conditions.acBuffer); + bool isACUnderMin = conditions.acBuffer[cIDX] <= GetMin(conditions.acBuffer); + + // + // AD ... + + // + bool isADBiggerLast = conditions.adBuffer[cIDX] > conditions.adBuffer[pIDX]; + bool isADLesserLast = conditions.adBuffer[cIDX] < conditions.adBuffer[pIDX]; + + // + bool isADOverMax = conditions.adBuffer[cIDX] >= GetMax(conditions.adBuffer); + bool isADUnderMin = conditions.adBuffer[cIDX] <= GetMin(conditions.adBuffer); + + // + // ADX ... + + // + bool isADXBiggerLast = conditions.adxBuffer[cIDX] > conditions.adxBuffer[pIDX]; + bool isADXBiggerLastPrev = conditions.adxBuffer[pIDX] > conditions.adxBuffer[ppIDX]; + + // + bool isADXLesserLast = conditions.adxBuffer[cIDX] < conditions.adxBuffer[pIDX]; + bool isADXLesserLastPrev = conditions.adxBuffer[pIDX] < conditions.adxBuffer[ppIDX]; + + // + bool isADXOverThreshold = conditions.adxBuffer[cIDX] > mInputs.adxThreshold; + bool isADXOverThresholdPrev = conditions.adxBuffer[pIDX] > mInputs.adxThreshold; + + // + bool isADXUnderThreshold = conditions.adxBuffer[cIDX] < mInputs.adxThreshold; + bool isADXUnderThresholdPrev = conditions.adxBuffer[pIDX] < mInputs.adxThreshold; + + // + bool isDXPBiggerThanDXN = conditions.adxpBuffer[cIDX] > conditions.adxnBuffer[cIDX]; + bool isDXPBiggerThanDXNPrev = conditions.adxpBuffer[pIDX] > conditions.adxnBuffer[pIDX]; + + // + bool isDXNBiggerThanDXP = conditions.adxnBuffer[cIDX] > conditions.adxpBuffer[cIDX]; + bool isDXNBiggerThanDXPPrev = conditions.adxnBuffer[pIDX] > conditions.adxpBuffer[pIDX]; + + // + bool isADXBullish = isADXBiggerLast && + isDXPBiggerThanDXN && + isADXOverThreshold; + bool isADXBullishPrev = isADXBiggerLastPrev && + isDXPBiggerThanDXNPrev && + isADXOverThresholdPrev; + bool isADXSwitchedToBullish = isADXBullish && + !isADXBullishPrev; + + // + bool isADXBearish = isADXLesserLast && + isDXNBiggerThanDXP && + isADXUnderThreshold; + bool isADXBearishPrev = isADXLesserLastPrev && + isDXNBiggerThanDXP && + isADXUnderThresholdPrev; + bool isADXSwitchedToBearish = isADXBearish && + !isADXBearishPrev; + + // + // ATR ... + + // + bool isATROverLast = conditions.atrBuffer[cIDX] > conditions.atrBuffer[pIDX]; + bool isATRUnderLast = conditions.atrBuffer[cIDX] < conditions.atrBuffer[pIDX]; + + // + // CCI ... + + // + bool isCCIBullish = conditions.cciBuffer[cIDX] > mInputs.cciReversalLevel; + bool isCCIBullishPrev = conditions.cciBuffer[pIDX] > mInputs.cciReversalLevel; + bool isCCISwitchedToBullish = isCCIBullish && + !isCCIBullishPrev; + + // + bool isCCIBearish = conditions.cciBuffer[cIDX] < mInputs.cciReversalLevel; + bool isCCIBearishPrev = conditions.cciBuffer[pIDX] < mInputs.cciReversalLevel; + bool isCCISwitchedToBearish = isCCIBearish && + !isCCIBearishPrev; + + // + bool isCCIOB = conditions.cciBuffer[cIDX] > mInputs.cciOBLevel; + bool isCCIOBPrev = conditions.cciBuffer[pIDX] > mInputs.cciOBLevel; + bool isCCICrossedOverOB = isCCIOB && + !isCCIOBPrev; + + // + bool isCCIUnderOB = conditions.cciBuffer[cIDX] < mInputs.cciOBLevel; + bool isCCIUnderOBPrev = conditions.cciBuffer[pIDX] < mInputs.cciOBLevel; + bool isCCICrossedUnderOB = isCCIUnderOB && + !isCCIUnderOBPrev; + + // + bool isCCIOS = conditions.cciBuffer[cIDX] < mInputs.cciOSLevel; + bool isCCIOSPrev = conditions.cciBuffer[pIDX] < mInputs.cciOSLevel; + bool isCCICrossedUnderOS = isCCIOS && + !isCCIOSPrev; + + // + bool isCCIOverOS = conditions.cciBuffer[cIDX] > mInputs.cciOSLevel; + bool isCCIOverOSPrev = conditions.cciBuffer[pIDX] > mInputs.cciOSLevel; + bool isCCICrossedOverOS = isCCIOverOS && + !isCCIOverOSPrev; + + // + // RSI ... + + // + bool isRSIBullish = conditions.rsiBuffer[cIDX] > mInputs.rsiReversalLevel; + bool isRSIBullishPrev = conditions.rsiBuffer[pIDX] > mInputs.rsiReversalLevel; + bool isRSISwitchedToBullish = isRSIBullish && + !isRSIBullishPrev; + + // + bool isRSIBearish = conditions.rsiBuffer[cIDX] < mInputs.rsiReversalLevel; + bool isRSIBearishPrev = conditions.rsiBuffer[pIDX] < mInputs.rsiReversalLevel; + bool isRSISwitchedToBearish = isRSIBearish && + !isRSIBearishPrev; + + // + bool isRSIOB = conditions.rsiBuffer[cIDX] > mInputs.rsiOBLevel; + bool isRSIOBPrev = conditions.rsiBuffer[pIDX] > mInputs.rsiOBLevel; + bool isRSICrossedOverOB = isRSIOB && + !isRSIOBPrev; + + // + bool isRSIUnderOB = conditions.rsiBuffer[cIDX] < mInputs.rsiOBLevel; + bool isRSIUnderOBPrev = conditions.rsiBuffer[pIDX] < mInputs.rsiOBLevel; + bool isRSICrossedUnderOB = isRSIUnderOB && + !isRSIUnderOBPrev; + + // + bool isRSIOS = conditions.rsiBuffer[cIDX] < mInputs.rsiOSLevel; + bool isRSIOSPrev = conditions.rsiBuffer[pIDX] < mInputs.rsiOSLevel; + bool isRSICrossedUnderOS = isRSIOS && + !isRSIOSPrev; + + // + bool isRSIOverOS = conditions.rsiBuffer[cIDX] > mInputs.rsiOSLevel; + bool isRSIOverOSPrev = conditions.rsiBuffer[pIDX] > mInputs.rsiOSLevel; + bool isRSICrossedOverOS = isRSIOverOS && + !isRSIOverOSPrev; + + // + // MFI ... + + // + bool isMFIBullish = conditions.mfiBuffer[cIDX] > mInputs.mfiReversalLevel; + bool isMFIBullishPrev = conditions.mfiBuffer[pIDX] > mInputs.mfiReversalLevel; + bool isMFISwitchedToBullish = isMFIBullish && + !isMFIBullishPrev; + + // + bool isMFIBearish = conditions.mfiBuffer[cIDX] < mInputs.mfiReversalLevel; + bool isMFIBearishPrev = conditions.mfiBuffer[pIDX] < mInputs.mfiReversalLevel; + bool isMFISwitchedToBearish = isMFIBearish && + !isMFIBearishPrev; + + // + bool isMFIOB = conditions.mfiBuffer[cIDX] > mInputs.mfiOBLevel; + bool isMFIOBPrev = conditions.mfiBuffer[pIDX] > mInputs.mfiOBLevel; + bool isMFICrossedOverOB = isMFIOB && + !isMFIOBPrev; + + // + bool isMFIUnderOB = conditions.mfiBuffer[cIDX] < mInputs.mfiOBLevel; + bool isMFIUnderOBPrev = conditions.mfiBuffer[pIDX] < mInputs.mfiOBLevel; + bool isMFICrossedUnderOB = isMFIUnderOB && + !isMFIUnderOBPrev; + + // + bool isMFIOS = conditions.mfiBuffer[cIDX] < mInputs.mfiOSLevel; + bool isMFIOSPrev = conditions.mfiBuffer[pIDX] < mInputs.mfiOSLevel; + bool isMFICrossedUnderOS = isMFIOS && + !isMFIOSPrev; + + // + bool isMFIOverOS = conditions.mfiBuffer[cIDX] > mInputs.mfiOSLevel; + bool isMFIOverOSPrev = conditions.mfiBuffer[pIDX] > mInputs.mfiOSLevel; + bool isMFICrossedOverOS = isMFIOverOS && + !isMFIOverOSPrev; + + // + // RVI ... + + // + bool isRVIBullish = conditions.rviBuffer[cIDX] > mInputs.rviBullishLevel; + bool isRVIBullishPrev = conditions.rviBuffer[pIDX] > mInputs.rviBullishLevel; + bool isRVISwitchedToBullish = isRVIBullish && + !isRVIBullishPrev; + + // + bool isRVIBearish = conditions.rviBuffer[cIDX] < mInputs.rviBearishLevel; + bool isRVIBearishPrev = conditions.rviBuffer[pIDX] < mInputs.rviBearishLevel; + bool isRVISwitchedToBearish = isRVIBearish && + !isRVIBearishPrev; + + // + bool isRVIOverSignal = conditions.rviBuffer[cIDX] > conditions.rviSignalBuffer[cIDX]; + bool isRVIOverSignalPrev = conditions.rviBuffer[pIDX] > conditions.rviSignalBuffer[pIDX]; + bool isRVICrossedOverSignal = isRVIOverSignal && + !isRVIOverSignalPrev; + + // + bool isRVIUnderSignal = conditions.rviBuffer[cIDX] < conditions.rviSignalBuffer[cIDX]; + bool isRVIUnderSignalPrev = conditions.rviBuffer[pIDX] < conditions.rviSignalBuffer[pIDX]; + bool isRVICrossedUnderSignal = isRVIUnderSignal && + !isRVIUnderSignalPrev; + + // + // MACD ... + + // + bool isMACDBullish = conditions.macdBuffer[cIDX] > mInputs.macdBullishLevel; + bool isMACDBullishPrev = conditions.macdBuffer[pIDX] > mInputs.macdBullishLevel; + bool isMACDSwitchedToBullish = isMACDBullish && + !isMACDBullishPrev; + + // + bool isMACDBearish = conditions.macdBuffer[cIDX] < mInputs.macdBearishLevel; + bool isMACDBearishPrev = conditions.macdBuffer[pIDX] < mInputs.macdBearishLevel; + bool isMACDSwitchedToBearish = isMACDBearish && + !isMACDBearishPrev; + + // + bool isMACDOverSignal = conditions.macdBuffer[cIDX] > conditions.macdSignalBuffer[cIDX]; + bool isMACDOverSignalPrev = conditions.macdBuffer[pIDX] > conditions.macdSignalBuffer[pIDX]; + bool isMACDCrossedOverSignal = isMACDOverSignal && + !isMACDOverSignalPrev; + + // + bool isMACDUnderSignal = conditions.macdBuffer[cIDX] < conditions.macdSignalBuffer[cIDX]; + bool isMACDUnderSignalPrev = conditions.macdBuffer[pIDX] < conditions.macdSignalBuffer[pIDX]; + bool isMACDCrossedUnderSignal = isMACDUnderSignal && + !isMACDUnderSignalPrev; + + // + // MOMENTUM ... + + // + bool isMomentumBullish = conditions.momentumBuffer[cIDX] > mInputs.momentumBullishLevel; + bool isMomentumBullishPrev = conditions.momentumBuffer[pIDX] > mInputs.momentumBullishLevel; + bool isMomentumSwitchedToBullish = isMomentumBullish && + !isMomentumBullishPrev; + + // + bool isMomentumBearish = conditions.momentumBuffer[cIDX] < mInputs.momentumBearishLevel; + bool isMomentumBearishPrev = conditions.momentumBuffer[pIDX] < mInputs.momentumBearishLevel; + bool isMomentumSwitchedToBearish = isMomentumBearish && + !isMomentumBearishPrev; + + // + // STOCHASTIC ... + + // + bool isStochasticBullish = conditions.stochasticBuffer[cIDX] > mInputs.stochasticReversalLevel; + bool isStochasticBullishPrev = conditions.stochasticBuffer[pIDX] > mInputs.stochasticReversalLevel; + bool isStochasticSwitchedToBullish = isStochasticBullish && + !isStochasticBullishPrev; + + // + bool isStochasticBearish = conditions.stochasticBuffer[cIDX] < mInputs.stochasticReversalLevel; + bool isStochasticBearishPrev = conditions.stochasticBuffer[pIDX] < mInputs.stochasticReversalLevel; + bool isStochasticSwitchedToBearish = isStochasticBearish && + !isStochasticBearishPrev; + + // + bool isStochasticOverSignal = conditions.stochasticBuffer[cIDX] > conditions.stochasticSignalBuffer[cIDX]; + bool isStochasticOverSignalPrev = conditions.stochasticBuffer[pIDX] > conditions.stochasticSignalBuffer[pIDX]; + bool isStochasticCrossedOverSignal = isStochasticOverSignal && + !isStochasticOverSignalPrev; + + // + bool isStochasticUnderSignal = conditions.stochasticBuffer[cIDX] < conditions.stochasticSignalBuffer[cIDX]; + bool isStochasticUnderSignalPrev = conditions.stochasticBuffer[pIDX] < conditions.stochasticSignalBuffer[pIDX]; + bool isStochasticCrossedUnderSignal = isStochasticUnderSignal && + !isStochasticUnderSignalPrev; + + // + bool isStochasticOB = conditions.stochasticBuffer[cIDX] > mInputs.stochasticOBLevel; + bool isStochasticOBPrev = conditions.stochasticBuffer[pIDX] > mInputs.stochasticOBLevel; + bool isStochasticCrossedOverOB = isStochasticOB && + !isStochasticOBPrev; + + // + bool isStochasticUnderOB = conditions.stochasticBuffer[cIDX] < mInputs.stochasticOBLevel; + bool isStochasticUnderOBPrev = conditions.stochasticBuffer[pIDX] < mInputs.stochasticOBLevel; + bool isStochasticCrossedUnderOB = isStochasticUnderOB && + !isStochasticUnderOBPrev; + + // + bool isStochasticOS = conditions.stochasticBuffer[cIDX] < mInputs.stochasticOSLevel; + bool isStochasticOSPrev = conditions.stochasticBuffer[pIDX] < mInputs.stochasticOSLevel; + bool isStochasticCrossedUnderOS = isStochasticOS && + !isStochasticOSPrev; + + // + bool isStochasticOverOS = conditions.stochasticBuffer[cIDX] > mInputs.stochasticOSLevel; + bool isStochasticOverOSPrev = conditions.stochasticBuffer[pIDX] > mInputs.stochasticOSLevel; + bool isStochasticCrossedOverOS = isStochasticOverOS && + !isStochasticOverOSPrev; + + // + // + // + + // + conditions.isCCIOB = isCCIOB; + conditions.isCCIOS = isCCIOS; + conditions.isRSIOB = isRSIOB; + conditions.isRSIOS = isRSIOS; + conditions.isMFIOB = isMFIOB; + conditions.isMFIOS = isMFIOS; + conditions.isACBullish = isACBullish; + conditions.isACBearish = isACBearish; + conditions.isACOverMax = isACOverMax; + conditions.isADOverMax = isADOverMax; + conditions.isACUnderMin = isACUnderMin; + conditions.isADUnderMin = isADUnderMin; + conditions.isADXBullish = isADXBullish; + conditions.isADXBearish = isADXBearish; + conditions.isCCIBullish = isCCIBullish; + conditions.isCCIBearish = isCCIBearish; + conditions.isRSIBullish = isRSIBullish; + conditions.isRSIBearish = isRSIBearish; + conditions.isMFIBullish = isMFIBullish; + conditions.isMFIBearish = isMFIBearish; + conditions.isRVIBullish = isRVIBullish; + conditions.isRVIBearish = isRVIBearish; + conditions.isATROverLast = isATROverLast; + conditions.isMACDBullish = isMACDBullish; + conditions.isMACDBearish = isMACDBearish; + conditions.isATRUnderLast = isATRUnderLast; + conditions.isADBiggerLast = isADBiggerLast; + conditions.isADLesserLast = isADLesserLast; + conditions.isStochasticOB = isStochasticOB; + conditions.isStochasticOS = isStochasticOS; + conditions.isADXBiggerLast = isADXBiggerLast; + conditions.isADXLesserLast = isADXLesserLast; + conditions.isRVIOverSignal = isRVIOverSignal; + conditions.isRVIUnderSignal = isRVIUnderSignal; + conditions.isMACDOverSignal = isMACDOverSignal; + conditions.isMACDUnderSignal = isMACDUnderSignal; + conditions.isMomentumBullish = isMomentumBullish; + conditions.isMomentumBearish = isMomentumBearish; + conditions.isADXOverThreshold = isADXOverThreshold; + conditions.isDXPBiggerThanDXN = isDXPBiggerThanDXN; + conditions.isDXNBiggerThanDXP = isDXNBiggerThanDXP; + conditions.isCCICrossedOverOB = isCCICrossedOverOB; + conditions.isCCICrossedOverOS = isCCICrossedOverOS; + conditions.isRSICrossedOverOB = isRSICrossedOverOB; + conditions.isRSICrossedOverOS = isRSICrossedOverOS; + conditions.isMFICrossedOverOB = isMFICrossedOverOB; + conditions.isMFICrossedOverOS = isMFICrossedOverOS; + conditions.isADXUnderThreshold = isADXUnderThreshold; + conditions.isCCICrossedUnderOB = isCCICrossedUnderOB; + conditions.isCCICrossedUnderOS = isCCICrossedUnderOS; + conditions.isRSICrossedUnderOB = isRSICrossedUnderOB; + conditions.isRSICrossedUnderOS = isRSICrossedUnderOS; + conditions.isMFICrossedUnderOB = isMFICrossedUnderOB; + conditions.isMFICrossedUnderOS = isMFICrossedUnderOS; + conditions.isStochasticBullish = isStochasticBullish; + conditions.isStochasticBearish = isStochasticBearish; + conditions.isACSwitchedToBullish = isACSwitchedToBullish; + conditions.isACSwitchedToBearish = isACSwitchedToBearish; + conditions.isADXSwitchedToBullish = isADXSwitchedToBullish; + conditions.isADXSwitchedToBearish = isADXSwitchedToBearish; + conditions.isCCISwitchedToBullish = isCCISwitchedToBullish; + conditions.isCCISwitchedToBearish = isCCISwitchedToBearish; + conditions.isRSISwitchedToBullish = isRSISwitchedToBullish; + conditions.isRSISwitchedToBearish = isRSISwitchedToBearish; + conditions.isMFISwitchedToBullish = isMFISwitchedToBullish; + conditions.isMFISwitchedToBearish = isMFISwitchedToBearish; + conditions.isRVISwitchedToBullish = isRVISwitchedToBullish; + conditions.isRVISwitchedToBearish = isRVISwitchedToBearish; + conditions.isRVICrossedOverSignal = isRVICrossedOverSignal; + conditions.isStochasticOverSignal = isStochasticOverSignal; + conditions.isStochasticUnderSignal = isStochasticUnderSignal; + conditions.isRVICrossedUnderSignal = isRVICrossedUnderSignal; + conditions.isMACDSwitchedToBullish = isMACDSwitchedToBullish; + conditions.isMACDSwitchedToBearish = isMACDSwitchedToBearish; + conditions.isMACDCrossedOverSignal = isMACDCrossedOverSignal; + conditions.isMACDCrossedUnderSignal = isMACDCrossedUnderSignal; + conditions.isStochasticCrossedOverOB = isStochasticCrossedOverOB; + conditions.isStochasticCrossedOverOS = isStochasticCrossedOverOS; + conditions.isStochasticCrossedUnderOB = isStochasticCrossedUnderOB; + conditions.isStochasticCrossedUnderOS = isStochasticCrossedUnderOS; + conditions.isMomentumSwitchedToBullish = isMomentumSwitchedToBullish; + conditions.isMomentumSwitchedToBearish = isMomentumSwitchedToBearish; + conditions.isStochasticSwitchedToBullish = isStochasticSwitchedToBullish; + conditions.isStochasticSwitchedToBearish = isStochasticSwitchedToBearish; + conditions.isStochasticCrossedOverSignal = isStochasticCrossedOverSignal; + conditions.isStochasticCrossedUnderSignal = isStochasticCrossedUnderSignal; + + // + Cleanup(); + + // + zBar.Clean(); + cBar.Clean(); + pBar.Clean(); + + // + return result; + } + + // + // Protected ... + protected: + // + // Private ... + private: + // + // Props ... + X121XOCSInputs mInputs; // Inputs ... + + // + // Buffers ... + double acBuffer[]; + double adBuffer[]; + double atrBuffer[]; + double cciBuffer[]; + double rsiBuffer[]; + double mfiBuffer[]; + double rviBuffer[]; + double adxBuffer[]; + double adxpBuffer[]; + double adxnBuffer[]; + double macdBuffer[]; + double momentumBuffer[]; + double rviSignalBuffer[]; + double macdSignalBuffer[]; + double stochasticBuffer[]; + double stochasticSignalBuffer[]; + + // + void Calculate( + int barIndex = 0, + int maxRequiredBars = 100 // + ) + { + // + // Buffers ... + if (barIndex < 0) + { + barIndex = 0; + } + + // + // AC ... + CopyBuffer( + mHandler, + X121_XOSCS_XAC_LINE, + barIndex, + maxRequiredBars, + acBuffer // + ); + + // + // AD ... + CopyBuffer( + mHandler, + X121_XOSCS_XAD_LINE, + barIndex, + maxRequiredBars, + adBuffer // + ); + + // + // ADX ... + CopyBuffer( + mHandler, + X121_XOSCS_XADX_LINE, + barIndex, + maxRequiredBars, + adxBuffer // + ); + + // + // ADX P ... + CopyBuffer( + mHandler, + X121_XOSCS_XADX_P_LINE, + barIndex, + maxRequiredBars, + adxpBuffer // + ); + + // + // ADX N ... + CopyBuffer( + mHandler, + X121_XOSCS_XADX_N_LINE, + barIndex, + maxRequiredBars, + adxnBuffer // + ); + + // + // ATR ... + CopyBuffer( + mHandler, + X121_XOSCS_XATR_LINE, + barIndex, + maxRequiredBars, + atrBuffer // + ); + + // + // CCI ... + CopyBuffer( + mHandler, + X121_XOSCS_XCCI_LINE, + barIndex, + maxRequiredBars, + cciBuffer // + ); + + // + // RSI ... + CopyBuffer( + mHandler, + X121_XOSCS_XRSI_LINE, + barIndex, + maxRequiredBars, + rsiBuffer // + ); + + // + // MFI ... + CopyBuffer( + mHandler, + X121_XOSCS_XMFI_LINE, + barIndex, + maxRequiredBars, + mfiBuffer // + ); + + // + // MOMENTUM ... + CopyBuffer( + mHandler, + X121_XOSCS_XMOMENTUM_LINE, + barIndex, + maxRequiredBars, + momentumBuffer // + ); + + // + // RVI ... + CopyBuffer( + mHandler, + X121_XOSCS_XRVI_LINE, + barIndex, + maxRequiredBars, + rviBuffer // + ); + + // + // RVI Signal ... + CopyBuffer( + mHandler, + X121_XOSCS_XRVI_S_LINE, + barIndex, + maxRequiredBars, + rviSignalBuffer // + ); + + // + // MACD ... + CopyBuffer( + mHandler, + X121_XOSCS_XMACD_LINE, + barIndex, + maxRequiredBars, + macdBuffer // + ); + + // + // MACD Signal ... + CopyBuffer( + mHandler, + X121_XOSCS_XMACD_S_LINE, + barIndex, + maxRequiredBars, + macdSignalBuffer // + ); + + // + // STOCHASTIC ... + CopyBuffer( + mHandler, + X121_XOSCS_XSTOCHASTIC_LINE, + barIndex, + maxRequiredBars, + stochasticBuffer // + ); + + // + // STOCHASTIC Signal ... + CopyBuffer( + mHandler, + X121_XOSCS_XSTOCHASTIC_S_LINE, + barIndex, + maxRequiredBars, + stochasticSignalBuffer // + ); + } + + // + void Cleanup( + int maxAllowed = 100 // + ) + { + // + CleanupArray( + acBuffer, + maxAllowed // + ); + + // + CleanupArray( + adBuffer, + maxAllowed // + ); + + // + CleanupArray( + atrBuffer, + maxAllowed // + ); + + // + CleanupArray( + cciBuffer, + maxAllowed // + ); + + // + CleanupArray( + rsiBuffer, + maxAllowed // + ); + + // + CleanupArray( + mfiBuffer, + maxAllowed // + ); + + // + CleanupArray( + rviBuffer, + maxAllowed // + ); + + // + CleanupArray( + adxBuffer, + maxAllowed // + ); + + // + CleanupArray( + adxpBuffer, + maxAllowed // + ); + + // + CleanupArray( + adxnBuffer, + maxAllowed // + ); + + // + CleanupArray( + macdBuffer, + maxAllowed // + ); + + // + CleanupArray( + momentumBuffer, + maxAllowed // + ); + + // + CleanupArray( + rviSignalBuffer, + maxAllowed // + ); + + // + CleanupArray( + macdSignalBuffer, + maxAllowed // + ); + + // + CleanupArray( + stochasticBuffer, + maxAllowed // + ); + + // + CleanupArray( + stochasticSignalBuffer, + maxAllowed // + ); + } + + // +}; diff --git a/BKPS/14040203/Helpers/x-saherelm.x121.xpv.helper.mq5 b/BKPS/14040203/Helpers/x-saherelm.x121.xpv.helper.mq5 new file mode 100644 index 0000000..7152924 --- /dev/null +++ b/BKPS/14040203/Helpers/x-saherelm.x121.xpv.helper.mq5 @@ -0,0 +1,3276 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Helper Class Library +// ---------------------------------------------- +// Name: XCX121XPVHelper +// Description: provides all Indicator +// Helper requirements ... +// +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +////////////////////////////////////////////////////// +// +// Global Properties ... +#property library +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://www.saherelm.ir" +#property version "1.00" +#property strict + +// +// Imports ... +#include "../Classes/x-saherelm.x-helper.class.mq5" + +// +// Definitions ... + +// +// Definitions ... +enum ENUM_X121_XPV_BUFFERS +{ + // + X121_XPV_PEAK_LINE = 0, + X121_XPV_VALE_LINE = 1, + X121_XPV_SAR_LINE = 2, + X121_XPV_SWING_LOW_LINE = 3, + X121_XPV_SWING_HIGH_LINE = 4, + X121_XPV_PEAK_GOLDEN_ZONE_LINE = 5, + X121_XPV_VALE_GOLDEN_ZONE_LINE = 6, + X121_XPV_SUPPORT_LINE = 7, + X121_XPV_RESISTANCE_LINE = 8, + X121_XPV_TREND_LINE = 9, + X121_XPV_TREND_COLOR_LINE = 10, + X121_XPV_C_HH_LINE = 11, + X121_XPV_C_LL_LINE = 12, + X121_XPV_S_HH_LINE = 13, + X121_XPV_S_LL_LINE = 14, + X121_XPV_M_HH_LINE = 15, + X121_XPV_M_LL_LINE = 16, + X121_XPV_L_HH_LINE = 17, + X121_XPV_L_LL_LINE = 18, + X121_XPV_H_HH_LINE = 19, + X121_XPV_H_LL_LINE = 20, + X121_XPV_FRACTALS_UPPER_LINE = 21, + X121_XPV_FRACTALS_LOWER_LINE = 22, + X121_XPV_TREND_STATE_LINE = 23, +}; + +// +// Input Models ... +struct X121XPVInputs +{ + // + // Props ... + + // + // Short ... + ENUM_X_PERIOD_METHOD scMethod; // How to Find Period + ENUM_TIMEFRAMES scPeriod; // Time Period + + // + // Medium ... + ENUM_X_PERIOD_METHOD mcMethod; // How to Find Period + ENUM_TIMEFRAMES mcPeriod; // Time Period + + // + // Long ... + ENUM_X_PERIOD_METHOD lcMethod; // How to Find Period + ENUM_TIMEFRAMES lcPeriod; // Time Period + + // + // Hind ... + ENUM_X_PERIOD_METHOD hcMethod; // How to Find Period + ENUM_TIMEFRAMES hcPeriod; // Time Period + + // + // Boundary Detection ... + ENUM_SERIESMODE hhMode; // Highest High Calculation Method + ENUM_SERIESMODE llMode; // Lowest Low Calculation Method + ENUM_X_FIBO_LEVELS goldenZoneLevel; // Golden Zone Detection + + // + // Sar Detection ... + double sarStep; // Step + double sarMax; // Maximum + + // + // Swing Detection ... + int swingLength; // Length + + // + int startCalculationForLastBars; // Calculate Last n Bars + + // + int sarArrowCode; // Parabolic Sar Arrow Code + int peaksArrowCode; // Peaks Arrow Code + int valesArrowCode; // Vales Arrow Code + int trendArrowCode; // Trend Arrow Code + int swingLowsArrowCode; // Swing Lows Arrow Code + int swingHighsArrowCode; // Swing Highs Arrow Code + int supportsArrowCode; // Supports Arrow Code + int resistancesArrowCode; // Resistances Arrow Code + + // + bool showSar; // Show Parabolic Sar + bool showPeaks; // Show Peaks + bool showVales; // Show Vales + bool showGoldenZones; // Show Golden Zones + bool showTrend; // Show Trend + bool showSwingLows; // Show Swing Lows + bool showSwingHighs; // Show Swing Highs + bool showSupports; // Show Supports + bool showResistances; // Show Resistances + + // + // Constructor(s) ... + X121XPVInputs() + { + // + Clean(); + } + + // + // Tools ... + + // + // Clean ... + void Clean() + { + // + // Short ... + scMethod = X_PERIOD_NONE; + scPeriod = NULL; + + // + // Medium ... + mcMethod = X_PERIOD_NONE; + mcPeriod = NULL; + + // + // Long ... + lcMethod = X_PERIOD_NONE; + lcPeriod = NULL; + + // + // Hind ... + hcMethod = X_PERIOD_NONE; + hcPeriod = NULL; + + // + // Boundary Detection ... + hhMode = MODE_HIGH; + llMode = MODE_LOW; + goldenZoneLevel = X_FIBO_LEVEL_382; + + // + sarStep = 0; + sarMax = 0; + + // + swingLength = 0; + + // + startCalculationForLastBars = 0; + + // + sarArrowCode = 0; + peaksArrowCode = 0; + valesArrowCode = 0; + trendArrowCode = 0; + swingLowsArrowCode = 0; + swingHighsArrowCode = 0; + supportsArrowCode = 0; + resistancesArrowCode = 0; + + // + showSar = false; + showPeaks = false; + showVales = false; + showTrend = false; + showSwingLows = false; + showSwingHighs = false; + showGoldenZones = false; + showSupports = false; + showResistances = false; + + // + ZeroMemory(this); + } + + // + // Default ... + void Default() + { + // + // Short ... + scMethod = X_PERIOD_AUTO; + scPeriod = NULL; + + // + // Medium ... + mcMethod = X_PERIOD_AUTO; + mcPeriod = NULL; + + // + // Long ... + lcMethod = X_PERIOD_AUTO; + lcPeriod = NULL; + + // + // Hind ... + hcMethod = X_PERIOD_AUTO; + hcPeriod = NULL; + + // + // Boundary Detection ... + hhMode = MODE_HIGH; + llMode = MODE_LOW; + goldenZoneLevel = X_FIBO_LEVEL_236; + + // + sarStep = 0.02; + sarMax = 0.2; + + // + swingLength = 5; + + // + startCalculationForLastBars = 1000; + + // + sarArrowCode = 159; + peaksArrowCode = 159; + valesArrowCode = 159; + trendArrowCode = 117; + swingLowsArrowCode = 225; + swingHighsArrowCode = 226; + supportsArrowCode = 159; + resistancesArrowCode = 159; + + // + showSar = true; + showPeaks = true; + showVales = true; + showTrend = true; + showSwingLows = true; + showSwingHighs = true; + showGoldenZones = true; + showSupports = true; + showResistances = true; + } + + // + // Validate ... + bool IsValid() + { + // + bool result = false; + + // + result = + // + // SAR ... + sarMax > 0 && + sarStep > 0 && + swingLength > 0 && + sarMax > sarStep && + // + // XPV ... + (IsValid(scMethod, scPeriod) && + IsValid(mcMethod, mcPeriod) && + IsValid(lcMethod, lcPeriod) && + IsValid(hcMethod, hcPeriod)) + // + ; + + // + return result; + } + + // + // Retrieve MAx Length ... + int Max() + { + // + int result = 0; + + // + result = MathMax(0, swingLength); + + // + return result; + } +}; + +// +// Conditions ... +struct X121XPVConditions +{ + // + // Common ... + string symbol; + ENUM_TIMEFRAMES period; + datetime time; + + // + // Buffers ... + double sarBuffer[]; + double cHHBuffer[]; + double cLLBuffer[]; + double sHHBuffer[]; + double sLLBuffer[]; + double mHHBuffer[]; + double mLLBuffer[]; + double lHHBuffer[]; + double lLLBuffer[]; + double hHHBuffer[]; + double hLLBuffer[]; + double trendBuffer[]; + double peaksBuffer[]; + double valesBuffer[]; + double supportsBuffer[]; + double swingLowsBuffer[]; + double swingHighsBuffer[]; + double trendColorBuffer[]; + double trendStateBuffer[]; + double peaksGoldenBuffer[]; + double valesGoldenBuffer[]; + double resistancesBuffer[]; + double fractalsUpperBuffer[]; + double fractalsLowerBuffer[]; + + // + // Conditions ... + + // + // SAR ... + + // + bool isSarBullish; + bool isSarBearish; + + // + bool isSarSwitchedToBullish; + bool isSarSwitchedToBearish; + + // + // XPV ... + + // + bool isNewPeak; + bool isNewPeakOverLast; + bool isNewPeakUnderLast; + + // + bool isNewVale; + bool isNewValeOverLast; + bool isNewValeUnderLast; + + // + // Constructor ... + X121XPVConditions() + { + Clean(); + } + + // + // Tools ... + + /** + * Cleaning Up ... + */ + void Clean() + { + // + // Commons ... + symbol = NULL; + period = NULL; + time = NULL; + + // + // Buffers ... + + // + Clean(sarBuffer); + Clean(cHHBuffer); + Clean(cLLBuffer); + Clean(sHHBuffer); + Clean(sLLBuffer); + Clean(mHHBuffer); + Clean(mLLBuffer); + Clean(lHHBuffer); + Clean(lLLBuffer); + Clean(hHHBuffer); + Clean(hLLBuffer); + Clean(trendBuffer); + Clean(peaksBuffer); + Clean(valesBuffer); + Clean(supportsBuffer); + Clean(swingLowsBuffer); + Clean(swingHighsBuffer); + Clean(trendColorBuffer); + Clean(trendStateBuffer); + Clean(peaksGoldenBuffer); + Clean(valesGoldenBuffer); + Clean(resistancesBuffer); + Clean(fractalsUpperBuffer); + Clean(fractalsLowerBuffer); + + // + // Clean(bullishTrendBuffer); + // Clean(bearishTrendBuffer); + + // + ArraySetAsSeries(sarBuffer, true); + ArraySetAsSeries(cHHBuffer, true); + ArraySetAsSeries(cLLBuffer, true); + ArraySetAsSeries(sHHBuffer, true); + ArraySetAsSeries(sLLBuffer, true); + ArraySetAsSeries(mHHBuffer, true); + ArraySetAsSeries(mLLBuffer, true); + ArraySetAsSeries(lHHBuffer, true); + ArraySetAsSeries(lLLBuffer, true); + ArraySetAsSeries(hHHBuffer, true); + ArraySetAsSeries(hLLBuffer, true); + ArraySetAsSeries(trendBuffer, true); + ArraySetAsSeries(peaksBuffer, true); + ArraySetAsSeries(valesBuffer, true); + ArraySetAsSeries(supportsBuffer, true); + ArraySetAsSeries(swingLowsBuffer, true); + ArraySetAsSeries(swingHighsBuffer, true); + ArraySetAsSeries(trendColorBuffer, true); + ArraySetAsSeries(trendStateBuffer, true); + ArraySetAsSeries(peaksGoldenBuffer, true); + ArraySetAsSeries(valesGoldenBuffer, true); + ArraySetAsSeries(resistancesBuffer, true); + ArraySetAsSeries(fractalsUpperBuffer, true); + ArraySetAsSeries(fractalsLowerBuffer, true); + + // + // Conditions ... + + // + isSarBullish = false; + isSarBearish = false; + + // + isSarSwitchedToBullish = false; + isSarSwitchedToBearish = false; + + // + isNewPeak = false; + isNewPeakOverLast = false; + isNewPeakUnderLast = false; + + // + isNewVale = false; + isNewValeOverLast = false; + isNewValeUnderLast = false; + + // + ZeroMemory(this); + } + + /** + * Generate Conditions Scores ... + * + * @param bullishScore: Double, Directional Scores Reference ... + * @param bearishScore: Double, Directional Scores Reference ... + */ + void GenerateScore( + double &bullishScore, + double &bearishScore // + ) + { + // + bullishScore = 0; + bearishScore = 0; + + // + double score = 1; + double minScore = 0.5; + double highScore = 1.5; + + // + if (isSarBullish) + { + bullishScore += minScore; + } + if (isSarSwitchedToBullish) + { + bullishScore += score; + } + + // + if (isSarBearish) + { + bearishScore += minScore; + } + if (isSarSwitchedToBearish) + { + bearishScore += score; + } + } + + /** + * Generate Summary String for Represent Conditions State ... + * + * @param onlyCommons: Boolean, Just Generate Only Commons Conditions ... + * @param onlyConditions: Boolean, Just Generate Only Conditions ... + * @param includeScores: Boolean, Attach Scores Representations on Result ... + * @param ignoreFalseConditions: Boolean, Ignore False Conditions on Result ... + * @param separator: String, Separate Lines ... + * + * @return ( string ) + */ + string GenerateSummary( + bool onlyCommons = false, + bool onlyConditions = false, + bool includeScores = true, + bool ignoreFalseConditions = true, + string separator = "\n" // + ) + { + // + string result = NULL; + + // + double bullishScore = 0; + double bearishScore = 0; + GenerateScore( + bullishScore, + bearishScore // + ); + + // + string scoresStr = + // + "Scores: " + separator + + "---------------" + separator + + "Bullish: " + ToString(bullishScore) + separator + + "Bearish: " + ToString(bearishScore) + separator + + "" + // + ; + + // + string commonStr = GenerateSpecifiedCommonSummary( + this, + separator, + includeScores // + ); + + // + string conditionsStr = + // + "-----------------------" + separator + + "XPV: " + separator + + "-----------------------" + separator + + ToString("isSarBullish", isSarBullish, ignoreFalseConditions, separator) + + ToString("isSarBearish", isSarBearish, ignoreFalseConditions, separator) + + ToString("isSarSwitchedToBullish", isSarSwitchedToBullish, ignoreFalseConditions, separator) + + ToString("isSarSwitchedToBearish", isSarSwitchedToBearish, ignoreFalseConditions, separator) + + ToString("isNewPeak", isNewPeak, ignoreFalseConditions, separator) + + ToString("isNewPeakOverLast", isNewPeakOverLast, ignoreFalseConditions, separator) + + ToString("isNewPeakUnderLast", isNewPeakUnderLast, ignoreFalseConditions, separator) + + ToString("isNewVale", isNewVale, ignoreFalseConditions, separator) + + ToString("isNewValeOverLast", isNewValeOverLast, ignoreFalseConditions, separator) + + ToString("isNewValeUnderLast", isNewValeUnderLast, ignoreFalseConditions, separator) + + // + "" + // + ; + + // + result = + // + "[" + GetTag() + "]" + separator + + (onlyConditions + ? "" + : commonStr) + + (!includeScores + ? "" + : scoresStr) + + " " + separator + + (onlyCommons + ? "" + : conditionsStr) + + "" + // + ; + + // + return result; + } + + /** + * Retrieve nique Tag Identifier ... + * + * @return ( string ) + */ + string GetTag() + { + return GetTypeName(this); + } + + // +}; + +// +// Class ... +class XCX121XPVHelper : public XCBaseHelper +{ + // + // Public ... + public: + // + // Props ... + + // + // Constructors ... + XCX121XPVHelper() + : XCBaseHelper(_Symbol, _Period) + { + } + + // + // Deconstructor ... + ~XCX121XPVHelper() + { + // + mInputs.Clean(); + + // + Clean(sarBuffer); + Clean(cHHBuffer); + Clean(cLLBuffer); + Clean(sHHBuffer); + Clean(sLLBuffer); + Clean(mHHBuffer); + Clean(mLLBuffer); + Clean(lHHBuffer); + Clean(lLLBuffer); + Clean(hHHBuffer); + Clean(hLLBuffer); + Clean(trendBuffer); + Clean(peaksBuffer); + Clean(valesBuffer); + Clean(supportsBuffer); + Clean(swingLowsBuffer); + Clean(swingHighsBuffer); + Clean(trendColorBuffer); + Clean(trendStateBuffer); + Clean(peaksGoldenBuffer); + Clean(valesGoldenBuffer); + Clean(resistancesBuffer); + Clean(fractalsUpperBuffer); + Clean(fractalsLowerBuffer); + } + + // + // Tools ... + bool Init( + string symbol, // Trading Symbol + ENUM_TIMEFRAMES period, // Trading Period + X121XPVInputs &inputs // Inputs + ) + { + // + bool result = false; + + // + mSymbol = symbol; + mPeriod = period; + + // + result = inputs.IsValid(); + if (!result) + { + return result; + } + + // + ArraySetAsSeries(sarBuffer, true); + ArraySetAsSeries(cHHBuffer, true); + ArraySetAsSeries(cLLBuffer, true); + ArraySetAsSeries(sHHBuffer, true); + ArraySetAsSeries(sLLBuffer, true); + ArraySetAsSeries(mHHBuffer, true); + ArraySetAsSeries(mLLBuffer, true); + ArraySetAsSeries(lHHBuffer, true); + ArraySetAsSeries(lLLBuffer, true); + ArraySetAsSeries(hHHBuffer, true); + ArraySetAsSeries(hLLBuffer, true); + ArraySetAsSeries(trendBuffer, true); + ArraySetAsSeries(peaksBuffer, true); + ArraySetAsSeries(valesBuffer, true); + ArraySetAsSeries(supportsBuffer, true); + ArraySetAsSeries(swingLowsBuffer, true); + ArraySetAsSeries(swingHighsBuffer, true); + ArraySetAsSeries(trendColorBuffer, true); + ArraySetAsSeries(trendStateBuffer, true); + ArraySetAsSeries(peaksGoldenBuffer, true); + ArraySetAsSeries(valesGoldenBuffer, true); + ArraySetAsSeries(resistancesBuffer, true); + ArraySetAsSeries(fractalsUpperBuffer, true); + ArraySetAsSeries(fractalsLowerBuffer, true); + + // + mInputs = inputs; + + // + mHandler = iCustom( + mSymbol, + mPeriod, + "x-saherelm.x121.xpv", + // + // Inputs ... + // + // Market ... + "", + // + // Short ... + "", + mInputs.scMethod, + mInputs.scPeriod, + // + // Medium ... + "", + mInputs.mcMethod, + mInputs.mcPeriod, + // + // Long ... + "", + mInputs.lcMethod, + mInputs.lcPeriod, + // + // Hind ... + "", + mInputs.hcMethod, + mInputs.hcPeriod, + // + // Boundary Detection ... + "", + mInputs.hhMode, + mInputs.llMode, + mInputs.goldenZoneLevel, + // + // SAr Detection ... + "", + mInputs.sarStep, + mInputs.sarMax, + // + // Swing Detection ... + "", + mInputs.swingLength, + // + // Presentation ... + "", + // + mInputs.startCalculationForLastBars, + mInputs.sarArrowCode, + mInputs.peaksArrowCode, + mInputs.valesArrowCode, + mInputs.trendArrowCode, + mInputs.swingLowsArrowCode, + mInputs.swingHighsArrowCode, + mInputs.supportsArrowCode, + mInputs.resistancesArrowCode, + // + mInputs.showSar, + mInputs.showPeaks, + mInputs.showVales, + mInputs.showTrend, + mInputs.showSwingLows, + mInputs.showSwingHighs, + mInputs.showGoldenZones, + mInputs.showSupports, + mInputs.showResistances + // + ); + result = mHandler != INVALID_HANDLE; + if (!result) + { + return result; + } + + // + return result; + } + + // + // Inputs ... + + // + X121XPVInputs GetInputs() + { + return mInputs; + } + + // + bool SetInputs( + X121XPVInputs &inputs // Configs + ) + { + // + return Init( + mSymbol, + mPeriod, + inputs + // + ); + } + + // + // Readers ... + + // + // SAR ... + + // + double GetSar( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(sarBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return sarBuffer[barIndex]; + } + + // + int CopySar( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + sarBuffer, + buffer, + forceClean + // + ); + } + + // + // PV ... + + // + // PEAKS ... + + // + double GetPeak( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(peaksBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return peaksBuffer[barIndex]; + } + + // + int CopyPeak( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + peaksBuffer, + buffer, + forceClean + // + ); + } + + // + // VALES ... + + // + double GetVale( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(valesBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return valesBuffer[barIndex]; + } + + // + int CopyVale( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + valesBuffer, + buffer, + forceClean + // + ); + } + + // + // SWINGLOW ... + + // + double GetSwingLow( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(swingLowsBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return swingLowsBuffer[barIndex]; + } + + // + int CopySwingLow( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + swingLowsBuffer, + buffer, + forceClean + // + ); + } + + // + // SWINGHIGH ... + + // + double GetSwingHigh( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(swingHighsBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return swingHighsBuffer[barIndex]; + } + + // + int CopySwingHigh( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + swingHighsBuffer, + buffer, + forceClean + // + ); + } + + // + // TREND ... + + // + double GetTrend( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(trendBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return trendBuffer[barIndex]; + } + + // + int CopyTrend( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + trendBuffer, + buffer, + forceClean + // + ); + } + + // + // TRENDCOLOR ... + + // + double GetTrendColor( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(trendColorBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return trendColorBuffer[barIndex]; + } + + // + int CopyTrendColor( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + trendColorBuffer, + buffer, + forceClean + // + ); + } + + // + // TRENDSTATE ... + + // + double GetTrendState( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(trendStateBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return trendStateBuffer[barIndex]; + } + + // + int CopyTrendState( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + trendStateBuffer, + buffer, + forceClean + // + ); + } + + // + // SUPPORTS ... + + // + double GetSupport( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(supportsBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return supportsBuffer[barIndex]; + } + + // + int CopySupport( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + supportsBuffer, + buffer, + forceClean + // + ); + } + + // + // RESISTANCES ... + + // + double GetResistance( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(resistancesBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return resistancesBuffer[barIndex]; + } + + // + int CopyResistance( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + resistancesBuffer, + buffer, + forceClean + // + ); + } + + // + // GOLDEN PEAKS ... + + // + double GetPeakGoldenZone( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(peaksGoldenBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return peaksGoldenBuffer[barIndex]; + } + + // + int CopyPeakGoldenZone( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + peaksGoldenBuffer, + buffer, + forceClean + // + ); + } + + // + // GOLDEN VALES ... + + // + double GetValeGoldenZone( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(valesGoldenBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return valesGoldenBuffer[barIndex]; + } + + // + int CopyValeGoldenZone( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + valesGoldenBuffer, + buffer, + forceClean + // + ); + } + + // + // CURRENT ... + + // + // HH ... + + // + double GetCHH( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(cHHBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return cHHBuffer[barIndex]; + } + + // + int CopyCHH( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + cHHBuffer, + buffer, + forceClean + // + ); + } + + // + // LL ... + + // + double GetCLL( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(cLLBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return cLLBuffer[barIndex]; + } + + // + int CopyCLL( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + cLLBuffer, + buffer, + forceClean + // + ); + } + + // + // SHORT ... + + // + // HH ... + + // + double GetSHH( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(sHHBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return sHHBuffer[barIndex]; + } + + // + int CopySHH( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + sHHBuffer, + buffer, + forceClean + // + ); + } + + // + // LL ... + + // + double GetSLL( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(sLLBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return sLLBuffer[barIndex]; + } + + // + int CopySLL( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + sLLBuffer, + buffer, + forceClean + // + ); + } + + // + // MEDIUM ... + + // + // HH ... + + // + double GetMHH( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(mHHBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return mHHBuffer[barIndex]; + } + + // + int CopyMHH( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + mHHBuffer, + buffer, + forceClean + // + ); + } + + // + // LL ... + + // + double GetMLL( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(mLLBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return mLLBuffer[barIndex]; + } + + // + int CopyMLL( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + mLLBuffer, + buffer, + forceClean + // + ); + } + + // + // LONG ... + + // + // HH ... + + // + double GetLHH( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(lHHBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return lHHBuffer[barIndex]; + } + + // + int CopyLHH( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + lHHBuffer, + buffer, + forceClean + // + ); + } + + // + // LL ... + + // + double GetLLL( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(lLLBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return lLLBuffer[barIndex]; + } + + // + int CopyLLL( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + lLLBuffer, + buffer, + forceClean + // + ); + } + + // + // HIND ... + + // + // HH ... + + // + double GetHHH( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(hHHBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return hHHBuffer[barIndex]; + } + + // + int CopyHHH( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + hHHBuffer, + buffer, + forceClean + // + ); + } + + // + // LL ... + + // + double GetHLL( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(hLLBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return hLLBuffer[barIndex]; + } + + // + int CopyHLL( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + hLLBuffer, + buffer, + forceClean + // + ); + } + + // + // FRACTALS Upper ... + + // + double GetFractalsUpper( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(fractalsUpperBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return fractalsUpperBuffer[barIndex]; + } + + // + int CopyFractalsUpper( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + fractalsUpperBuffer, + buffer, + forceClean + // + ); + } + + // + // FRACTALS Lower ... + + // + double GetFractalsLower( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(fractalsLowerBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return fractalsLowerBuffer[barIndex]; + } + + // + int CopyFractalsLower( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + fractalsLowerBuffer, + buffer, + forceClean + // + ); + } + + // + // Tools Function ... + + // + double GetHigherPeak( + int &index, // Bar Index + double peak, // Peak Source + int barIndex = 0, // Bar Index + int loopback = 576 // Max Allowed Loopback + ) + { + // + double result = 0; + + // + index = -1; + + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + if (loopback < 576) + { + loopback = 576; + } + + // + if (peak <= 0) + { + return result; + } + + // + double iValue = 0; + int sIndex = barIndex; + bool canContinue = true; + while (canContinue) + { + // + iValue = GetPeak(sIndex); + if (iValue > peak) + { + // + index = sIndex; + result = iValue; + break; + } + + // + canContinue = sIndex < barIndex + loopback; + sIndex++; + } + + // + return result; + } + + // + double GetLowerPeak( + int &index, // Bar Index + double peak, // Peak Source + int barIndex = 0, // Bar Index + int loopback = 576 // Max Allowed Loopback + ) + { + // + double result = 0; + + // + index = -1; + + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + if (loopback < 576) + { + loopback = 576; + } + + // + if (peak <= 0) + { + return result; + } + + // + double iValue = 0; + int sIndex = barIndex; + bool canContinue = true; + while (canContinue) + { + // + iValue = GetPeak(sIndex); + if (iValue < peak) + { + // + index = sIndex; + result = iValue; + break; + } + + // + canContinue = sIndex < barIndex + loopback; + sIndex++; + } + + // + return result; + } + + // + double GetHigherVale( + int &index, // Bar Index + double vale, // Vale Source + int barIndex = 0, // Bar Index + int loopback = 576 // Max Allowed Loopback + ) + { + // + double result = 0; + + // + index = -1; + + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + if (loopback < 576) + { + loopback = 576; + } + + // + if (vale <= 0) + { + return result; + } + + // + double iValue = 0; + int sIndex = barIndex; + bool canContinue = true; + while (canContinue) + { + // + iValue = GetVale(sIndex); + if (iValue > vale) + { + // + index = sIndex; + result = iValue; + break; + } + + // + canContinue = sIndex < barIndex + loopback; + sIndex++; + } + + // + return result; + } + + // + double GetLowerVale( + int &index, // Bar Index + double vale, // Vale Source + int barIndex = 0, // Bar Index + int loopback = 576 // Max Allowed Loopback + ) + { + // + double result = 0; + + // + index = -1; + + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + if (loopback < 576) + { + loopback = 576; + } + + // + if (vale <= 0) + { + return result; + } + + // + double iValue = 0; + int sIndex = barIndex; + bool canContinue = true; + while (canContinue) + { + // + iValue = GetVale(sIndex); + if (iValue < vale) + { + // + index = sIndex; + result = iValue; + break; + } + + // + canContinue = sIndex < barIndex + loopback; + sIndex++; + } + + // + return result; + } + + // + double GetLowestPeak( + int barIndex, + int &index, + double &vale, + int loopback = 576 // + ) + { + // + double result = 0; + + // + index = -1; + vale = 0; + + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + if (loopback < 576) + { + loopback = 576; + } + + // + Calculate(barIndex); + + // + for (int i = 0; i < barIndex + loopback; i++) + { + // + double iPeak = GetPeak(i); + if (iPeak == 0) + { + break; + } + + // + if (iPeak > 0 && (result == 0 || + result >= iPeak)) + { + // + index = i; + result = iPeak; + vale = GetVale(index); + } + } + + // + return result; + } + + // + double GetHighestPeak( + int barIndex, + int &index, + double &vale, + int loopback = 576 // + ) + { + // + double result = 0; + + // + index = -1; + vale = 0; + + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + if (loopback < 576) + { + loopback = 576; + } + + // + Calculate(barIndex); + + // + for (int i = 0; i < barIndex + loopback; i++) + { + // + double iPeak = GetPeak(i); + if (iPeak == 0) + { + break; + } + + // + if (iPeak > 0 && (result == 0 || + result <= iPeak)) + { + // + index = i; + result = iPeak; + vale = GetVale(index); + } + } + + // + return result; + } + + // + double GetLowestVale( + int barIndex, + int &index, + double &peak, + int loopback = 576 // + ) + { + // + double result = 0; + + // + index = -1; + peak = 0; + + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + if (loopback < 576) + { + loopback = 576; + } + + // + Calculate(barIndex); + + // + for (int i = 0; i < barIndex + loopback; i++) + { + // + double iPeak = GetVale(i); + if (iPeak == 0) + { + break; + } + + // + if (iPeak > 0 && (result == 0 || + result >= iPeak)) + { + // + index = i; + result = iPeak; + peak = GetPeak(index); + } + } + + // + return result; + } + + // + double GetHighestVale( + int barIndex, + int &index, + double &peak, + int loopback = 576 // + ) + { + // + double result = 0; + + // + index = -1; + peak = 0; + + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + if (loopback < 576) + { + loopback = 576; + } + + // + Calculate(barIndex); + + // + for (int i = 0; i < barIndex + loopback; i++) + { + // + double iPeak = GetVale(i); + if (iPeak == 0) + { + break; + } + + // + if (iPeak > 0 && (result == 0 || + result <= iPeak)) + { + // + index = i; + result = iPeak; + peak = GetPeak(index); + } + } + + // + return result; + } + + // + void Free() override + { + Cleanup(10); + } + + // + bool GetConditions( + X121XPVConditions &conditions, // + int barIndex = 0, // + int loopback = 5 // + ) + { + // + bool result = true; + + // + if (loopback < 5) + { + loopback = 5; + } + + // + conditions.Clean(); + + // + conditions.symbol = mSymbol; + conditions.period = mPeriod; + conditions.time = TimeCurrent(); + + // + int zIndex = barIndex; + int cIndex = zIndex + 1; + int pIndex = cIndex + 1; + int ppIndex = pIndex + 1; + + // + XOHCL zBar; + result = zBar.Init( + mSymbol, + mPeriod, + zIndex // + ); + if (!result) + { + return result; + } + + // + XOHCL cBar; + result = cBar.Init( + mSymbol, + mPeriod, + cIndex // + ); + if (!result) + { + return result; + } + + // + XOHCL pBar; + result = pBar.Init( + mSymbol, + mPeriod, + pIndex // + ); + if (!result) + { + return result; + } + + // + // Buffers ... + + // + CopySar( + zIndex, + loopback, + conditions.sarBuffer // + ); + + // + CopyCHH( + zIndex, + loopback, + conditions.cHHBuffer // + ); + + // + CopyCLL( + zIndex, + loopback, + conditions.cLLBuffer // + ); + + // + CopySHH( + zIndex, + loopback, + conditions.sHHBuffer // + ); + + // + CopySLL( + zIndex, + loopback, + conditions.sLLBuffer // + ); + + // + CopyMHH( + zIndex, + loopback, + conditions.mHHBuffer // + ); + + // + CopyMLL( + zIndex, + loopback, + conditions.mLLBuffer // + ); + + // + CopyLHH( + zIndex, + loopback, + conditions.lHHBuffer // + ); + + // + CopyLLL( + zIndex, + loopback, + conditions.lLLBuffer // + ); + + // + CopyHHH( + zIndex, + loopback, + conditions.hHHBuffer // + ); + + // + CopyHLL( + zIndex, + loopback, + conditions.hLLBuffer // + ); + + // + CopyTrend( + zIndex, + loopback, + conditions.trendBuffer // + ); + + // + CopyPeak( + zIndex, + loopback, + conditions.peaksBuffer // + ); + + // + CopyVale( + zIndex, + loopback, + conditions.valesBuffer // + ); + + // + CopySupport( + zIndex, + loopback, + conditions.supportsBuffer // + ); + + // + CopySwingLow( + zIndex, + loopback, + conditions.swingLowsBuffer // + ); + + // + CopySwingHigh( + zIndex, + loopback, + conditions.swingHighsBuffer // + ); + + // + CopyTrendColor( + zIndex, + loopback, + conditions.trendColorBuffer // + ); + + // + CopyTrendState( + zIndex, + loopback, + conditions.trendStateBuffer // + ); + + // + CopyPeakGoldenZone( + zIndex, + loopback, + conditions.peaksGoldenBuffer // + ); + + // + CopyValeGoldenZone( + zIndex, + loopback, + conditions.valesGoldenBuffer // + ); + + // + CopyResistance( + zIndex, + loopback, + conditions.resistancesBuffer // + ); + + // + CopyFractalsUpper( + zIndex, + loopback, + conditions.fractalsUpperBuffer // + ); + + // + CopyFractalsLower( + zIndex, + loopback, + conditions.fractalsLowerBuffer // + ); + + // + // Conditions ... + + // + int cIDX = 1; + int pIDX = cIDX + 1; + + // + // SAR ... + + // + bool isSarBullish = conditions.sarBuffer[cIDX] < cBar.low; + bool isSarBullishPrev = conditions.sarBuffer[pIDX] < pBar.low; + + // + bool isSarBearish = conditions.sarBuffer[cIDX] > cBar.high; + bool isSarBearishPrev = conditions.sarBuffer[pIDX] > pBar.high; + + // + bool isSarSwitchedToBullish = isSarBullish && + !isSarBullishPrev; + bool isSarSwitchedToBearish = isSarBearish && + !isSarBearishPrev; + + // + // XPV ... + + // + bool isNewPeak = conditions.peaksBuffer[cIDX] != conditions.peaksBuffer[pIDX]; + bool isNewPeakOverLast = isNewPeak && + conditions.peaksBuffer[cIDX] > conditions.peaksBuffer[pIDX]; + bool isNewPeakUnderLast = isNewPeak && + conditions.peaksBuffer[cIDX] < conditions.peaksBuffer[pIDX]; + + // + bool isNewVale = conditions.valesBuffer[cIDX] != conditions.valesBuffer[pIDX]; + bool isNewValeOverLast = isNewVale && + conditions.valesBuffer[cIDX] > conditions.valesBuffer[pIDX]; + bool isNewValeUnderLast = isNewVale && + conditions.valesBuffer[cIDX] < conditions.valesBuffer[pIDX]; + + // + conditions.isSarBullish = isSarBullish; + conditions.isSarBearish = isSarBearish; + conditions.isSarSwitchedToBullish = isSarSwitchedToBullish; + conditions.isSarSwitchedToBearish = isSarSwitchedToBearish; + conditions.isNewPeak = isNewPeak; + conditions.isNewPeakOverLast = isNewPeakOverLast; + conditions.isNewPeakUnderLast = isNewPeakUnderLast; + conditions.isNewVale = isNewVale; + conditions.isNewValeOverLast = isNewValeOverLast; + conditions.isNewValeUnderLast = isNewValeUnderLast; + + // + Cleanup(); + + // + zBar.Clean(); + cBar.Clean(); + pBar.Clean(); + + // + return result; + } + + // + // Protected ... + protected: + // + // Private ... + private: + // + // Props ... + X121XPVInputs mInputs; // Inputs ... + + // + // Buffers ... + double sarBuffer[]; + double cHHBuffer[]; + double cLLBuffer[]; + double sHHBuffer[]; + double sLLBuffer[]; + double mHHBuffer[]; + double mLLBuffer[]; + double lHHBuffer[]; + double lLLBuffer[]; + double hHHBuffer[]; + double hLLBuffer[]; + double trendBuffer[]; + double peaksBuffer[]; + double valesBuffer[]; + double supportsBuffer[]; + double swingLowsBuffer[]; + double swingHighsBuffer[]; + double trendColorBuffer[]; + double trendStateBuffer[]; + double peaksGoldenBuffer[]; + double valesGoldenBuffer[]; + double resistancesBuffer[]; + double fractalsUpperBuffer[]; + double fractalsLowerBuffer[]; + + // + void Calculate( + int barIndex = 0, + int maxRequiredBars = 100 // + ) + { + // + // Buffers ... + if (barIndex < 0) + { + barIndex = 0; + } + + // + CopyBuffer( + mHandler, + X121_XPV_SAR_LINE, + barIndex, + maxRequiredBars, + sarBuffer // + ); + + // + CopyBuffer( + mHandler, + X121_XPV_C_HH_LINE, + barIndex, + maxRequiredBars, + cHHBuffer // + ); + + // + CopyBuffer( + mHandler, + X121_XPV_C_LL_LINE, + barIndex, + maxRequiredBars, + cLLBuffer // + ); + + // + CopyBuffer( + mHandler, + X121_XPV_S_HH_LINE, + barIndex, + maxRequiredBars, + sHHBuffer // + ); + + // + CopyBuffer( + mHandler, + X121_XPV_S_LL_LINE, + barIndex, + maxRequiredBars, + sLLBuffer // + ); + + // + CopyBuffer( + mHandler, + X121_XPV_M_HH_LINE, + barIndex, + maxRequiredBars, + mHHBuffer // + ); + + // + CopyBuffer( + mHandler, + X121_XPV_M_LL_LINE, + barIndex, + maxRequiredBars, + mLLBuffer // + ); + + // + CopyBuffer( + mHandler, + X121_XPV_L_HH_LINE, + barIndex, + maxRequiredBars, + lHHBuffer // + ); + + // + CopyBuffer( + mHandler, + X121_XPV_L_LL_LINE, + barIndex, + maxRequiredBars, + lLLBuffer // + ); + + // + CopyBuffer( + mHandler, + X121_XPV_H_HH_LINE, + barIndex, + maxRequiredBars, + hHHBuffer // + ); + + // + CopyBuffer( + mHandler, + X121_XPV_H_LL_LINE, + barIndex, + maxRequiredBars, + hLLBuffer // + ); + + // + CopyBuffer( + mHandler, + X121_XPV_TREND_LINE, + barIndex, + maxRequiredBars, + trendBuffer // + ); + + // + CopyBuffer( + mHandler, + X121_XPV_PEAK_LINE, + barIndex, + maxRequiredBars, + peaksBuffer // + ); + + // + CopyBuffer( + mHandler, + X121_XPV_VALE_LINE, + barIndex, + maxRequiredBars, + valesBuffer // + ); + + // + CopyBuffer( + mHandler, + X121_XPV_SUPPORT_LINE, + barIndex, + maxRequiredBars, + supportsBuffer // + ); + + // + CopyBuffer( + mHandler, + X121_XPV_SWING_LOW_LINE, + barIndex, + maxRequiredBars, + swingLowsBuffer // + ); + + // + CopyBuffer( + mHandler, + X121_XPV_SWING_HIGH_LINE, + barIndex, + maxRequiredBars, + swingHighsBuffer // + ); + + // + CopyBuffer( + mHandler, + X121_XPV_TREND_COLOR_LINE, + barIndex, + maxRequiredBars, + trendColorBuffer // + ); + + // + CopyBuffer( + mHandler, + X121_XPV_TREND_STATE_LINE, + barIndex, + maxRequiredBars, + trendStateBuffer // + ); + + // + CopyBuffer( + mHandler, + X121_XPV_PEAK_GOLDEN_ZONE_LINE, + barIndex, + maxRequiredBars, + peaksGoldenBuffer // + ); + + // + CopyBuffer( + mHandler, + X121_XPV_VALE_GOLDEN_ZONE_LINE, + barIndex, + maxRequiredBars, + valesGoldenBuffer // + ); + + // + CopyBuffer( + mHandler, + X121_XPV_RESISTANCE_LINE, + barIndex, + maxRequiredBars, + resistancesBuffer // + ); + + // + CopyBuffer( + mHandler, + X121_XPV_FRACTALS_UPPER_LINE, + barIndex, + maxRequiredBars, + fractalsUpperBuffer // + ); + + // + CopyBuffer( + mHandler, + X121_XPV_FRACTALS_LOWER_LINE, + barIndex, + maxRequiredBars, + fractalsLowerBuffer // + ); + } + + // + void Cleanup( + int maxAllowed = 100 // + ) + { + // + CleanupArray( + sarBuffer, + maxAllowed // + ); + + // + CleanupArray( + cHHBuffer, + maxAllowed // + ); + + // + CleanupArray( + cLLBuffer, + maxAllowed // + ); + + // + CleanupArray( + sHHBuffer, + maxAllowed // + ); + + // + CleanupArray( + sLLBuffer, + maxAllowed // + ); + + // + CleanupArray( + mHHBuffer, + maxAllowed // + ); + + // + CleanupArray( + mLLBuffer, + maxAllowed // + ); + + // + CleanupArray( + lHHBuffer, + maxAllowed // + ); + + // + CleanupArray( + lLLBuffer, + maxAllowed // + ); + + // + CleanupArray( + hHHBuffer, + maxAllowed // + ); + + // + CleanupArray( + hLLBuffer, + maxAllowed // + ); + + // + CleanupArray( + trendBuffer, + maxAllowed // + ); + + // + CleanupArray( + peaksBuffer, + maxAllowed // + ); + + // + CleanupArray( + valesBuffer, + maxAllowed // + ); + + // + CleanupArray( + supportsBuffer, + maxAllowed // + ); + + // + CleanupArray( + swingLowsBuffer, + maxAllowed // + ); + + // + CleanupArray( + swingHighsBuffer, + maxAllowed // + ); + + // + CleanupArray( + trendColorBuffer, + maxAllowed // + ); + + // + CleanupArray( + trendStateBuffer, + maxAllowed // + ); + + // + CleanupArray( + peaksGoldenBuffer, + maxAllowed // + ); + + // + CleanupArray( + valesGoldenBuffer, + maxAllowed // + ); + + // + CleanupArray( + resistancesBuffer, + maxAllowed // + ); + + // + CleanupArray( + fractalsUpperBuffer, + maxAllowed // + ); + + // + CleanupArray( + fractalsLowerBuffer, + maxAllowed // + ); + } + + // +}; + +// +// Tools ... \ No newline at end of file diff --git a/BKPS/14040203/Helpers/x-saherelm.x121.xstr.helper.mq5 b/BKPS/14040203/Helpers/x-saherelm.x121.xstr.helper.mq5 new file mode 100644 index 0000000..79dd07d --- /dev/null +++ b/BKPS/14040203/Helpers/x-saherelm.x121.xstr.helper.mq5 @@ -0,0 +1,1900 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Helper Class Library +// ---------------------------------------------- +// Name: XCX121XSTRHelper +// Description: provides all Indicator +// Helper requirements ... +// +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +////////////////////////////////////////////////////// +// +// Global Properties ... +#property library +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://www.saherelm.ir" +#property version "1.00" +#property strict + +// +// Imports ... +#include "../Classes/x-saherelm.x-helper.class.mq5" + +// +// Definitions ... + +// +// Definitions ... +enum ENUM_X121_XSTR_BUFFERS +{ + // + X121_XSTR_LINE = 0, + X121_XSTR_COLOR_LINE = 1, + X121_XSTR_UP_LINE = 2, + X121_XSTR_DOWN_LINE = 3, + X121_XSTR_HSM_LINE = 4, + X121_XSTR_LSM_LINE = 5, + X121_XSTR_XVIDYA_LINE = 6, + X121_XSTR_ATR_LINE = 7, + X121_XSTR_PRICE_LINE = 8, + X121_XSTR_STATE_LINE = 9, +}; + +// +// Input Models ... +struct X121XSTRInputs +{ + // + // Props ... + + int strLength; // Length + double strMultiplier; // Multiplier + int vidyaLength; // Smothing Length + ENUM_MA_METHOD strBoundaryMode; // Boundary Mode + ENUM_APPLIED_PRICE strAppliedTo; // Applied To + ENUM_APPLIED_PRICE vidyaAppliedTo; // Smoothing Applied To + + // + bool showStr; // Show Str + bool showVidya; // Show Vidya + bool showStrUpper; // Show Str Upper + bool showStrLower; // Show Str Lower + bool showStrSMLow; // Show Str SM Low + bool showStrSMHigh; // Show Str SM High + + // + // Constructor(s) ... + X121XSTRInputs() + { + // + Clean(); + } + + // + // Tools ... + + // + // Clean ... + void Clean() + { + // + strLength = 0; + strMultiplier = 0.0; + vidyaLength = 0; + strBoundaryMode = MODE_SMA; + strAppliedTo = PRICE_MEDIAN; + vidyaAppliedTo = PRICE_CLOSE; + + // + showStr = false; + showVidya = false; + showStrUpper = false; + showStrLower = false; + showStrSMLow = false; + showStrSMHigh = false; + + // + ZeroMemory(this); + } + + // + // Default ... + void Default() + { + // + strLength = 14; + vidyaLength = 14; + strMultiplier = 3.0; + strBoundaryMode = MODE_SMA; + strAppliedTo = PRICE_CLOSE; + vidyaAppliedTo = PRICE_CLOSE; + + // + showStr = true; + showVidya = true; + showStrUpper = true; + showStrLower = true; + showStrSMLow = true; + showStrSMHigh = true; + } + + // + // Validate ... + bool IsValid() + { + // + bool result = false; + + // + result = + // + strLength > 0 && + strMultiplier > 0 + // + ; + + // + return result; + } + + // + // Retrieve MAx Length ... + int Max() + { + // + int result = 0; + + // + result = MathMax(strLength, vidyaLength); + + // + return result; + } +}; + +// +// Conditions ... +struct X121XSTRConditions +{ + // + // Common ... + string symbol; + ENUM_TIMEFRAMES period; + datetime time; + + // + // Buffers ... + double strBuffer[]; + double atrBuffer[]; + double vidyaBuffer[]; + double strUpBuffer[]; + double strDownBuffer[]; + double strPriceBuffer[]; + double strStateBuffer[]; + double strSMLowBuffer[]; + double strSMHighBuffer[]; + + // + // Conditions ... + + // + // STR ... + + // + bool isStrBullish; + bool isStrBearish; + + // + bool isStrSwitchedToBullish; + bool isStrSwitchedToBearish; + + // + // VIDYA ... + + // + bool isRejectUpVidya; + bool isCloseOverVidya; + bool isCrossedOverVidya; + + // + bool isRejectDownVidya; + bool isCloseUnderVidya; + bool isCrossedUnderVidya; + + // + // HMS ... + + // + bool isRejectUpLSM; + bool isCloseOverLSM; + bool isCrossedOverLSM; + + // + bool isRejectDownLSM; + bool isCloseUnderLSM; + bool isCrossedUnderLSM; + + // + // HSM .. + + // + bool isRejectUpHSM; + bool isCloseOverHSM; + bool isCrossedOverHSM; + + // + bool isRejectDownHSM; + bool isCloseUnderHSM; + bool isCrossedUnderHSM; + + // + // STR ... + + // + bool isRejectUpStr; + bool isCloseOverStr; + bool isCrossedOverStr; + + // + bool isRejectDownStr; + bool isCloseUnderStr; + bool isCrossedUnderStr; + + // + // HSM / ViDYA ... + + // + bool isVidyaOverHSM; + bool isVidyaCrossedOverHSM; + + // + bool isVidyaUnderHSM; + bool isVidyaCrossedUnderHSM; + + // + // LSM / VIDYA ... + + // + bool isVidyaOverLSM; + bool isVidyaCrossedOverLSM; + + // + bool isVidyaUnderLSM; + bool isVidyaCrossedUnderLSM; + + // + // STR / VIDYA ... + + // + bool isVidyaOverStr; + bool isVidyaCrossedOverStr; + + // + bool isVidyaUnderStr; + bool isVidyaCrossedUnderStr; + + // + // bool isCloseLower + + // + // Constructor ... + X121XSTRConditions() + { + Clean(); + } + + // + // Tools ... + + /** + * Cleaning Up ... + */ + void Clean() + { + // + // Commons ... + symbol = NULL; + period = NULL; + time = NULL; + + // + // Buffers ... + + // + Clean(strBuffer); + Clean(atrBuffer); + Clean(vidyaBuffer); + Clean(strUpBuffer); + Clean(strDownBuffer); + Clean(strPriceBuffer); + Clean(strStateBuffer); + Clean(strSMLowBuffer); + Clean(strSMHighBuffer); + + // + ArraySetAsSeries(strBuffer, true); + ArraySetAsSeries(atrBuffer, true); + ArraySetAsSeries(vidyaBuffer, true); + ArraySetAsSeries(strUpBuffer, true); + ArraySetAsSeries(strDownBuffer, true); + ArraySetAsSeries(strPriceBuffer, true); + ArraySetAsSeries(strStateBuffer, true); + ArraySetAsSeries(strSMLowBuffer, true); + ArraySetAsSeries(strSMHighBuffer, true); + + // + // Conditions ... + + isStrBullish = false; + isStrBearish = false; + isRejectUpLSM = false; + isRejectUpHSM = false; + isRejectUpStr = false; + isCloseOverHSM = false; + isCloseOverLSM = false; + isCloseOverStr = false; + isVidyaOverHSM = false; + isVidyaOverLSM = false; + isVidyaOverStr = false; + isRejectDownLSM = false; + isRejectDownHSM = false; + isVidyaUnderStr = false; + isVidyaUnderHSM = false; + isVidyaUnderLSM = false; + isCloseUnderStr = false; + isRejectDownStr = false; + isRejectUpVidya = false; + isCloseUnderHSM = false; + isCloseUnderLSM = false; + isCrossedOverLSM = false; + isCrossedOverHSM = false; + isCrossedOverStr = false; + isCrossedUnderHSM = false; + isCrossedUnderLSM = false; + isCrossedUnderStr = false; + isCloseOverVidya = false; + isRejectDownVidya = false; + isCloseUnderVidya = false; + isCrossedOverVidya = false; + isCrossedUnderVidya = false; + isVidyaCrossedOverHSM = false; + isVidyaCrossedOverStr = false; + isVidyaCrossedOverLSM = false; + isVidyaCrossedUnderHSM = false; + isVidyaCrossedUnderLSM = false; + isVidyaCrossedUnderStr = false; + isStrSwitchedToBullish = false; + isStrSwitchedToBearish = false; + + // + ZeroMemory(this); + } + + /** + * Generate Conditions Scores ... + * + * @param bullishScore: Double, Directional Scores Reference ... + * @param bearishScore: Double, Directional Scores Reference ... + */ + void GenerateScore( + double &bullishScore, + double &bearishScore // + ) + { + // + bullishScore = 0; + bearishScore = 0; + + // + double score = 1; + double minScore = 0.5; + double highScore = 1.5; + + // + if (isStrBullish) + { + bullishScore += minScore; + } + if (isStrSwitchedToBullish) + { + bullishScore += score; + } + if (isRejectUpVidya) + { + bullishScore += minScore; + } + if (isCloseOverVidya) + { + bullishScore += minScore; + } + if (isCrossedOverVidya) + { + bullishScore += minScore; + } + if (isRejectUpLSM) + { + bullishScore += minScore; + } + if (isCloseOverLSM) + { + bullishScore += minScore; + } + if (isCrossedOverLSM) + { + bullishScore += minScore; + } + if (isRejectUpHSM) + { + bullishScore += minScore; + } + if (isCloseOverHSM) + { + bullishScore += minScore; + } + if (isCrossedOverHSM) + { + bullishScore += minScore; + } + if (isRejectUpStr) + { + bullishScore += minScore; + } + if (isCloseOverStr) + { + bullishScore += minScore; + } + if (isCrossedOverStr) + { + bullishScore += minScore; + } + if (isVidyaOverHSM) + { + bullishScore += minScore; + } + if (isVidyaCrossedOverHSM) + { + bullishScore += minScore; + } + if (isVidyaOverLSM) + { + bullishScore += minScore; + } + if (isVidyaCrossedOverLSM) + { + bullishScore += minScore; + } + if (isVidyaOverStr) + { + bullishScore += minScore; + } + if (isVidyaCrossedOverStr) + { + bullishScore += minScore; + } + + // + if (isStrBearish) + { + bearishScore += minScore; + } + if (isStrSwitchedToBearish) + { + bearishScore += score; + } + if (isRejectDownVidya) + { + bearishScore += minScore; + } + if (isCloseUnderVidya) + { + bearishScore += minScore; + } + if (isCrossedUnderVidya) + { + bearishScore += minScore; + } + if (isRejectDownLSM) + { + bearishScore += minScore; + } + if (isCloseUnderLSM) + { + bearishScore += minScore; + } + if (isCrossedUnderLSM) + { + bearishScore += minScore; + } + if (isRejectDownHSM) + { + bearishScore += minScore; + } + if (isCloseUnderHSM) + { + bearishScore += minScore; + } + if (isCrossedUnderHSM) + { + bearishScore += minScore; + } + if (isRejectDownStr) + { + bearishScore += minScore; + } + if (isCloseUnderStr) + { + bearishScore += minScore; + } + if (isCrossedUnderStr) + { + bearishScore += minScore; + } + if (isVidyaUnderHSM) + { + bearishScore += minScore; + } + if (isVidyaCrossedUnderHSM) + { + bearishScore += minScore; + } + if (isVidyaUnderLSM) + { + bearishScore += minScore; + } + if (isVidyaCrossedUnderLSM) + { + bearishScore += minScore; + } + if (isVidyaUnderStr) + { + bearishScore += minScore; + } + if (isVidyaCrossedUnderStr) + { + bearishScore += minScore; + } + } + + /** + * Generate Summary String for Represent Conditions State ... + * + * @param onlyCommons: Boolean, Just Generate Only Commons Conditions ... + * @param onlyConditions: Boolean, Just Generate Only Conditions ... + * @param includeScores: Boolean, Attach Scores Representations on Result ... + * @param ignoreFalseConditions: Boolean, Ignore False Conditions on Result ... + * @param separator: String, Separate Lines ... + * + * @return ( string ) + */ + string GenerateSummary( + bool onlyCommons = false, + bool onlyConditions = false, + bool includeScores = true, + bool ignoreFalseConditions = true, + string separator = "\n" // + ) + { + // + string result = NULL; + + // + double bullishScore = 0; + double bearishScore = 0; + GenerateScore( + bullishScore, + bearishScore // + ); + + // + string scoresStr = + // + "Scores: " + separator + + "---------------" + separator + + "Bullish: " + ToString(bullishScore) + separator + + "Bearish: " + ToString(bearishScore) + separator + + "" + // + ; + + // + string commonStr = GenerateSpecifiedCommonSummary( + this, + separator, + includeScores // + ); + + // + string conditionsStr = + // + "-----------------------" + separator + + "XSTR: " + separator + + "-----------------------" + separator + + ToString("isStrBullish", isStrBullish, ignoreFalseConditions, separator) + + ToString("isStrBearish", isStrBearish, ignoreFalseConditions, separator) + + ToString("isStrSwitchedToBullish", isStrSwitchedToBullish, ignoreFalseConditions, separator) + + ToString("isStrSwitchedToBearish", isStrSwitchedToBearish, ignoreFalseConditions, separator) + + ToString("isRejectUpVidya", isRejectUpVidya, ignoreFalseConditions, separator) + + ToString("isCloseOverVidya", isCloseOverVidya, ignoreFalseConditions, separator) + + ToString("isCrossedOverVidya", isCrossedOverVidya, ignoreFalseConditions, separator) + + ToString("isRejectDownVidya", isRejectDownVidya, ignoreFalseConditions, separator) + + ToString("isCloseUnderVidya", isCloseUnderVidya, ignoreFalseConditions, separator) + + ToString("isCrossedUnderVidya", isCrossedUnderVidya, ignoreFalseConditions, separator) + + ToString("isRejectUpLSM", isRejectUpLSM, ignoreFalseConditions, separator) + + ToString("isCloseOverLSM", isCloseOverLSM, ignoreFalseConditions, separator) + + ToString("isCrossedOverLSM", isCrossedOverLSM, ignoreFalseConditions, separator) + + ToString("isRejectDownLSM", isRejectDownLSM, ignoreFalseConditions, separator) + + ToString("isCloseUnderLSM", isCloseUnderLSM, ignoreFalseConditions, separator) + + ToString("isCrossedUnderLSM", isCrossedUnderLSM, ignoreFalseConditions, separator) + + ToString("isRejectUpHSM", isRejectUpHSM, ignoreFalseConditions, separator) + + ToString("isCloseOverHSM", isCloseOverHSM, ignoreFalseConditions, separator) + + ToString("isCrossedOverHSM", isCrossedOverHSM, ignoreFalseConditions, separator) + + ToString("isRejectDownHSM", isRejectDownHSM, ignoreFalseConditions, separator) + + ToString("isCloseUnderHSM", isCloseUnderHSM, ignoreFalseConditions, separator) + + ToString("isCrossedUnderHSM", isCrossedUnderHSM, ignoreFalseConditions, separator) + + ToString("isRejectUpStr", isRejectUpStr, ignoreFalseConditions, separator) + + ToString("isCloseOverStr", isCloseOverStr, ignoreFalseConditions, separator) + + ToString("isCrossedOverStr", isCrossedOverStr, ignoreFalseConditions, separator) + + ToString("isRejectDownStr", isRejectDownStr, ignoreFalseConditions, separator) + + ToString("isCloseUnderStr", isCloseUnderStr, ignoreFalseConditions, separator) + + ToString("isCrossedUnderStr", isCrossedUnderStr, ignoreFalseConditions, separator) + + ToString("isVidyaOverHSM", isVidyaOverHSM, ignoreFalseConditions, separator) + + ToString("isVidyaCrossedOverHSM", isVidyaCrossedOverHSM, ignoreFalseConditions, separator) + + ToString("isVidyaUnderHSM", isVidyaUnderHSM, ignoreFalseConditions, separator) + + ToString("isVidyaCrossedUnderHSM", isVidyaCrossedUnderHSM, ignoreFalseConditions, separator) + + ToString("isVidyaOverLSM", isVidyaOverLSM, ignoreFalseConditions, separator) + + ToString("isVidyaCrossedOverLSM", isVidyaCrossedOverLSM, ignoreFalseConditions, separator) + + ToString("isVidyaUnderLSM", isVidyaUnderLSM, ignoreFalseConditions, separator) + + ToString("isVidyaCrossedUnderLSM", isVidyaCrossedUnderLSM, ignoreFalseConditions, separator) + + ToString("isVidyaOverStr", isVidyaOverStr, ignoreFalseConditions, separator) + + ToString("isVidyaCrossedOverStr", isVidyaCrossedOverStr, ignoreFalseConditions, separator) + + ToString("isVidyaUnderStr", isVidyaUnderStr, ignoreFalseConditions, separator) + + ToString("isVidyaCrossedUnderStr", isVidyaCrossedUnderStr, ignoreFalseConditions, separator) + + // + "" + // + ; + + // + result = + // + "[" + GetTag() + "]" + separator + + (onlyConditions + ? "" + : commonStr) + + (!includeScores + ? "" + : scoresStr) + + " " + separator + + (onlyCommons + ? "" + : conditionsStr) + + "" + // + ; + + // + return result; + } + + /** + * Retrieve nique Tag Identifier ... + * + * @return ( string ) + */ + string GetTag() + { + return GetTypeName(this); + } + + // +}; + +// +// Class ... +class XCX121XSTRHelper : public XCBaseHelper +{ + // + // Public ... + public: + // + // Props ... + + // + // Constructors ... + XCX121XSTRHelper() + : XCBaseHelper(_Symbol, _Period) + { + } + + // + // Deconstructor ... + ~XCX121XSTRHelper() + { + // + mInputs.Clean(); + + // + Clean(strBuffer); + Clean(atrBuffer); + Clean(strPriceBuffer); + Clean(strUpBuffer); + Clean(strDownBuffer); + Clean(strStateBuffer); + } + + // + // Tools ... + bool Init( + string symbol, // Trading Symbol + ENUM_TIMEFRAMES period, // Trading Period + X121XSTRInputs &inputs // Inputs + ) + { + // + bool result = false; + + // + mSymbol = symbol; + mPeriod = period; + + // + result = inputs.IsValid(); + if (!result) + { + return result; + } + + // + ArraySetAsSeries(strBuffer, true); + ArraySetAsSeries(atrBuffer, true); + ArraySetAsSeries(vidyaBuffer, true); + ArraySetAsSeries(strUpBuffer, true); + ArraySetAsSeries(strDownBuffer, true); + ArraySetAsSeries(strPriceBuffer, true); + ArraySetAsSeries(strStateBuffer, true); + ArraySetAsSeries(strSMLowBuffer, true); + ArraySetAsSeries(strSMHighBuffer, true); + + // + mInputs = inputs; + + // + mHandler = iCustom( + mSymbol, + mPeriod, + "x-saherelm.x121.xstr", + // + // Inputs ... + // + // Market ... + "", + mInputs.strLength, + mInputs.strMultiplier, + mInputs.vidyaLength, + mInputs.strBoundaryMode, + mInputs.strAppliedTo, + mInputs.vidyaAppliedTo, + // + // Presentation ... + "", + mInputs.showStr, + mInputs.showVidya, + mInputs.showStrUpper, + mInputs.showStrLower, + mInputs.showStrSMLow, + mInputs.showStrSMHigh + // + ); + result = mHandler != INVALID_HANDLE; + if (!result) + { + return result; + } + + // + return result; + } + + // + // Inputs ... + + // + X121XSTRInputs GetInputs() + { + return mInputs; + } + + // + bool SetInputs( + X121XSTRInputs &inputs // Configs + ) + { + // + return Init( + mSymbol, + mPeriod, + inputs + // + ); + } + + // + // Readers ... + + // + // Vidya ... + + // + double GetVidya( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(vidyaBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return vidyaBuffer[barIndex]; + } + + // + int CopyVidya( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + vidyaBuffer, + buffer, + forceClean + // + ); + } + + // + // ATR ... + + // + double GetATR( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(atrBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return atrBuffer[barIndex]; + } + + // + int CopyATR( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + atrBuffer, + buffer, + forceClean + // + ); + } + + // + double GetSTR( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(strBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return strBuffer[barIndex]; + } + + // + int CopySTR( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + strBuffer, + buffer, + forceClean + // + ); + } + + // + double GetSTRState( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(strStateBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return strStateBuffer[barIndex]; + } + + // + int CopySTRState( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + strStateBuffer, + buffer, + forceClean + // + ); + } + + // + double GetSTRPrice( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(strPriceBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return strPriceBuffer[barIndex]; + } + + // + int CopySTRPrice( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + strPriceBuffer, + buffer, + forceClean + // + ); + } + + // + double GetSTRUp( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(strUpBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return strUpBuffer[barIndex]; + } + + // + int CopySTRUp( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + strUpBuffer, + buffer, + forceClean + // + ); + } + + // + double GetSTRDown( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(strDownBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return strDownBuffer[barIndex]; + } + + // + int CopySTRDown( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + strDownBuffer, + buffer, + forceClean + // + ); + } + + // + double GetSTRSMLow( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(strSMLowBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return strSMLowBuffer[barIndex]; + } + + // + int CopySTRSMLow( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + strSMLowBuffer, + buffer, + forceClean + // + ); + } + + // + double GetSTRSMHigh( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(strSMHighBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return strSMHighBuffer[barIndex]; + } + + // + int CopySTRSMHigh( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + strSMHighBuffer, + buffer, + forceClean + // + ); + } + + // + double GetLastSTR( + ENUM_X_DIRECTION dir, + int barIndex = 0 // + ) + { + // + double result = 0; + + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + if (!HasDirection(dir)) + { + return result; + } + + // + int index = barIndex; + bool isBullish = IsBullish(dir); + + // + bool canContinue = true; + while (canContinue) + { + // + double iStr = GetSTR(index); + double iState = GetSTRState(index); + + // + canContinue = + isBullish + ? iState < 0 + : iState > 0; + if (!canContinue) + { + // + result = iStr; + break; + } + + // + index++; + } + + // + return result; + } + + // + void Free() override + { + Cleanup(10); + } + + // + bool GetConditions( + X121XSTRConditions &conditions, // + int barIndex = 0, // + int loopback = 5 // + ) + { + // + bool result = true; + + // + if (loopback < 5) + { + loopback = 5; + } + + // + conditions.Clean(); + + // + conditions.symbol = mSymbol; + conditions.period = mPeriod; + conditions.time = TimeCurrent(); + + // + int zIndex = barIndex; + int cIndex = zIndex + 1; + int pIndex = cIndex + 1; + int ppIndex = pIndex + 1; + + // + XOHCL zBar; + result = zBar.Init( + mSymbol, + mPeriod, + zIndex // + ); + if (!result) + { + return result; + } + + // + XOHCL cBar; + result = cBar.Init( + mSymbol, + mPeriod, + cIndex // + ); + if (!result) + { + return result; + } + + // + XOHCL pBar; + result = pBar.Init( + mSymbol, + mPeriod, + pIndex // + ); + if (!result) + { + return result; + } + + // + // Buffers ... + + // + CopyVidya( + zIndex, + loopback, + conditions.vidyaBuffer // + ); + + // + CopyATR( + zIndex, + loopback, + conditions.atrBuffer // + ); + + // + CopySTR( + zIndex, + loopback, + conditions.strBuffer // + ); + + // + CopySTRState( + zIndex, + loopback, + conditions.strStateBuffer // + ); + + // + CopySTRPrice( + zIndex, + loopback, + conditions.strPriceBuffer // + ); + + // + CopySTRUp( + zIndex, + loopback, + conditions.strUpBuffer // + ); + + // + CopySTRDown( + zIndex, + loopback, + conditions.strDownBuffer // + ); + + // + CopySTRSMLow( + zIndex, + loopback, + conditions.strSMLowBuffer // + ); + + // + CopySTRSMHigh( + zIndex, + loopback, + conditions.strSMHighBuffer // + ); + + // + // Conditions ... + + // + int cIDX = 1; + int pIDX = cIDX + 1; + + // + // STR ... + + // + bool isStrBullish = strStateBuffer[cIDX] > 0; + bool isStrBullishPrev = strStateBuffer[pIDX] > 0; + + // + bool isStrBearish = strStateBuffer[cIDX] < 0; + bool isStrBearishPrev = strStateBuffer[pIDX] < 0; + + // + bool isStrSwitchedToBullish = isStrBullish && + !isStrBullishPrev; + bool isStrSwitchedToBearish = isStrBearish && + !isStrBearishPrev; + + // + // VIDYA ... + + // + bool isRejectUpVidya = cBar.IsRejected( + vidyaBuffer[cIDX], + X_DIRECTION_BULLISH // + ); + + // + bool isCloseOverVidya = cBar.close > vidyaBuffer[cIDX]; + bool isCloseOverVidyaPrev = pBar.close > vidyaBuffer[pIDX]; + bool isCrossedOverVidya = isCloseOverVidya && + !isCloseOverVidyaPrev; + + // + bool isRejectDownVidya = cBar.IsRejected( + vidyaBuffer[cIDX], + X_DIRECTION_BEARISH // + ); + + // + bool isCloseUnderVidya = cBar.close < vidyaBuffer[cIDX]; + bool isCloseUnderVidyaPrev = pBar.close < vidyaBuffer[pIDX]; + bool isCrossedUnderVidya = isCloseUnderVidya && + !isCloseUnderVidyaPrev; + + // + // LMS ... + + // + bool isRejectUpLSM = cBar.IsRejected( + strSMLowBuffer[cIDX], + X_DIRECTION_BULLISH // + ); + + // + bool isCloseOverLSM = cBar.close > strSMLowBuffer[cIDX]; + bool isCloseOverLSMPrev = pBar.close > strSMLowBuffer[pIDX]; + bool isCrossedOverLSM = isCloseOverLSM && + !isCloseOverLSMPrev; + + // + bool isRejectDownLSM = cBar.IsRejected( + strSMLowBuffer[cIDX], + X_DIRECTION_BEARISH // + ); + + // + bool isCloseUnderLSM = cBar.close < strSMLowBuffer[cIDX]; + bool isCloseUnderLSMPrev = pBar.close < strSMLowBuffer[pIDX]; + bool isCrossedUnderLSM = isCloseUnderLSM && + !isCloseUnderLSMPrev; + + // + // HSM .. + + // + bool isRejectUpHSM = cBar.IsRejected( + strSMHighBuffer[cIDX], + X_DIRECTION_BULLISH // + ); + + // + bool isCloseOverHSM = cBar.close > strSMHighBuffer[cIDX]; + bool isCloseOverHSMPrev = pBar.close > strSMHighBuffer[pIDX]; + bool isCrossedOverHSM = isCloseOverHSM && + !isCloseOverHSMPrev; + + // + bool isRejectDownHSM = cBar.IsRejected( + strSMHighBuffer[cIDX], + X_DIRECTION_BEARISH // + ); + + // + bool isCloseUnderHSM = cBar.close > strSMHighBuffer[cIDX]; + bool isCloseUnderHSMPrev = pBar.close > strSMHighBuffer[pIDX]; + bool isCrossedUnderHSM = isCloseUnderHSM && + !isCloseUnderHSMPrev; + + // + // STR ... + + // + bool isRejectUpStr = cBar.IsRejected( + strBuffer[cIDX], + X_DIRECTION_BULLISH // + ); + + // + bool isCloseOverStr = cBar.close > strBuffer[cIDX]; + bool isCloseOverStrPrev = pBar.close > strBuffer[pIDX]; + bool isCrossedOverStr = isCloseOverStr && + !isCloseOverStrPrev; + + // + bool isRejectDownStr = cBar.IsRejected( + strBuffer[cIDX], + X_DIRECTION_BEARISH // + ); + + // + bool isCloseUnderStr = cBar.close < strBuffer[cIDX]; + bool isCloseUnderStrPrev = pBar.close < strBuffer[pIDX]; + bool isCrossedUnderStr = isCloseUnderStr && + !isCloseUnderStrPrev; + + // + // HSM / ViDYA ... + + // + bool isVidyaOverHSM = vidyaBuffer[cIDX] > strSMHighBuffer[cIDX]; + bool isVidyaOverHSMPrev = vidyaBuffer[pIDX] > strSMHighBuffer[pIDX]; + bool isVidyaCrossedOverHSM = isVidyaOverHSM && + !isVidyaOverHSMPrev; + + // + bool isVidyaUnderHSM = vidyaBuffer[cIDX] < strSMHighBuffer[cIDX]; + bool isVidyaUnderHSMPrev = vidyaBuffer[pIDX] < strSMHighBuffer[pIDX]; + bool isVidyaCrossedUnderHSM = isVidyaUnderHSM && + !isVidyaUnderHSMPrev; + + // + // LSM / VIDYA ... + + // + bool isVidyaOverLSM = vidyaBuffer[cIDX] > strSMLowBuffer[cIDX]; + bool isVidyaOverLSMPrev = vidyaBuffer[pIDX] > strSMLowBuffer[pIDX]; + bool isVidyaCrossedOverLSM = isVidyaOverLSM && + !isVidyaOverLSMPrev; + + // + bool isVidyaUnderLSM = vidyaBuffer[cIDX] < strSMLowBuffer[cIDX]; + bool isVidyaUnderLSMPrev = vidyaBuffer[pIDX] < strSMLowBuffer[pIDX]; + bool isVidyaCrossedUnderLSM = isVidyaUnderLSM && + !isVidyaUnderLSMPrev; + + // + // STR / VIDYA ... + + // + bool isVidyaOverStr = vidyaBuffer[cIDX] > strBuffer[cIDX]; + bool isVidyaOverStrPrev = vidyaBuffer[pIDX] > strBuffer[pIDX]; + bool isVidyaCrossedOverStr = isVidyaOverStr && + !isVidyaOverStrPrev; + + // + bool isVidyaUnderStr = vidyaBuffer[cIDX] < strBuffer[cIDX]; + bool isVidyaUnderStrPrev = vidyaBuffer[pIDX] < strBuffer[pIDX]; + bool isVidyaCrossedUnderStr = isVidyaUnderStr && + !isVidyaUnderStrPrev; + + // + // + // + + // + conditions.isStrBullish = isStrBullish; + conditions.isStrBearish = isStrBearish; + conditions.isRejectUpLSM = isRejectUpLSM; + conditions.isRejectUpHSM = isRejectUpHSM; + conditions.isRejectUpStr = isRejectUpStr; + conditions.isCloseOverHSM = isCloseOverHSM; + conditions.isCloseOverLSM = isCloseOverLSM; + conditions.isCloseOverStr = isCloseOverStr; + conditions.isVidyaOverHSM = isVidyaOverHSM; + conditions.isVidyaOverLSM = isVidyaOverLSM; + conditions.isVidyaOverStr = isVidyaOverStr; + conditions.isRejectDownLSM = isRejectDownLSM; + conditions.isRejectDownHSM = isRejectDownHSM; + conditions.isVidyaUnderStr = isVidyaUnderStr; + conditions.isVidyaUnderHSM = isVidyaUnderHSM; + conditions.isVidyaUnderLSM = isVidyaUnderLSM; + conditions.isCloseUnderStr = isCloseUnderStr; + conditions.isRejectDownStr = isRejectDownStr; + conditions.isRejectUpVidya = isRejectUpVidya; + conditions.isCloseUnderHSM = isCloseUnderHSM; + conditions.isCloseUnderLSM = isCloseUnderLSM; + conditions.isCrossedOverLSM = isCrossedOverLSM; + conditions.isCrossedOverHSM = isCrossedOverHSM; + conditions.isCrossedOverStr = isCrossedOverStr; + conditions.isCrossedUnderHSM = isCrossedUnderHSM; + conditions.isCrossedUnderLSM = isCrossedUnderLSM; + conditions.isCrossedUnderStr = isCrossedUnderStr; + conditions.isCloseOverVidya = isCloseOverVidya; + conditions.isRejectDownVidya = isRejectDownVidya; + conditions.isCloseUnderVidya = isCloseUnderVidya; + conditions.isCrossedOverVidya = isCrossedOverVidya; + conditions.isCrossedUnderVidya = isCrossedUnderVidya; + conditions.isVidyaCrossedOverHSM = isVidyaCrossedOverHSM; + conditions.isVidyaCrossedOverStr = isVidyaCrossedOverStr; + conditions.isVidyaCrossedOverLSM = isVidyaCrossedOverLSM; + conditions.isVidyaCrossedUnderHSM = isVidyaCrossedUnderHSM; + conditions.isVidyaCrossedUnderLSM = isVidyaCrossedUnderLSM; + conditions.isVidyaCrossedUnderStr = isVidyaCrossedUnderStr; + conditions.isStrSwitchedToBullish = isStrSwitchedToBullish; + conditions.isStrSwitchedToBearish = isStrSwitchedToBearish; + + // + Cleanup(); + + // + zBar.Clean(); + cBar.Clean(); + pBar.Clean(); + + // + return result; + } + + // + // Protected ... + protected: + // + // Private ... + private: + // + // Props ... + X121XSTRInputs mInputs; // Inputs ... + + // + // Buffers ... + double strBuffer[]; + double atrBuffer[]; + double vidyaBuffer[]; + double strUpBuffer[]; + double strDownBuffer[]; + double strPriceBuffer[]; + double strStateBuffer[]; + double strSMLowBuffer[]; + double strSMHighBuffer[]; + + // + void Calculate( + int barIndex = 0, + int maxRequiredBars = 100 // + ) + { + // + // Buffers ... + if (barIndex < 0) + { + barIndex = 0; + } + + // + // VIDYA ... + CopyBuffer( + mHandler, + X121_XSTR_XVIDYA_LINE, + barIndex, + maxRequiredBars, + vidyaBuffer + // + ); + + // + // STR ... + CopyBuffer( + mHandler, + X121_XSTR_LINE, + barIndex, + maxRequiredBars, + strBuffer + // + ); + + // + // State ... + CopyBuffer( + mHandler, + X121_XSTR_STATE_LINE, + barIndex, + maxRequiredBars, + strStateBuffer + // + ); + + // + // Price ... + CopyBuffer( + mHandler, + X121_XSTR_PRICE_LINE, + barIndex, + maxRequiredBars, + strPriceBuffer + // + ); + + // + // Up ... + CopyBuffer( + mHandler, + X121_XSTR_UP_LINE, + barIndex, + maxRequiredBars, + strUpBuffer + // + ); + + // + // STR ... + CopyBuffer( + mHandler, + X121_XSTR_DOWN_LINE, + barIndex, + maxRequiredBars, + strDownBuffer + // + ); + + // + CopyBuffer( + mHandler, + X121_XSTR_LSM_LINE, + barIndex, + maxRequiredBars, + strSMLowBuffer + // + ); + + // + CopyBuffer( + mHandler, + X121_XSTR_HSM_LINE, + barIndex, + maxRequiredBars, + strSMHighBuffer + // + ); + + // + // ATR ... + + // + CopyBuffer( + mHandler, + X121_XSTR_ATR_LINE, + barIndex, + maxRequiredBars, + atrBuffer + // + ); + } + + // + void Cleanup( + int maxAllowed = 100 // + ) + { + // + CleanupArray( + vidyaBuffer, + maxAllowed // + ); + + // + CleanupArray( + strBuffer, + maxAllowed // + ); + + // + CleanupArray( + atrBuffer, + maxAllowed // + ); + + // + CleanupArray( + strUpBuffer, + maxAllowed // + ); + + // + CleanupArray( + strDownBuffer, + maxAllowed // + ); + + // + CleanupArray( + strPriceBuffer, + maxAllowed // + ); + + // + CleanupArray( + strStateBuffer, + maxAllowed // + ); + + // + CleanupArray( + strSMLowBuffer, + maxAllowed // + ); + + // + CleanupArray( + strSMHighBuffer, + maxAllowed // + ); + } + + // +}; + +// +// Tools ... \ No newline at end of file diff --git a/BKPS/14040203/Helpers/x-saherelm.x121.xtrend.helper.mq5 b/BKPS/14040203/Helpers/x-saherelm.x121.xtrend.helper.mq5 new file mode 100644 index 0000000..c3b8eaf --- /dev/null +++ b/BKPS/14040203/Helpers/x-saherelm.x121.xtrend.helper.mq5 @@ -0,0 +1,1309 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Helper Class Library +// ---------------------------------------------- +// Name: XCX121XTRENDHelper +// Description: provides all Indicator +// Helper requirements ... +// +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +////////////////////////////////////////////////////// +// +// Global Properties ... +#property library +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://www.saherelm.ir" +#property version "1.00" +#property strict + +// +// Imports ... +#include "../Classes/x-saherelm.x-helper.class.mq5" + +// +// Definitions ... + +// +// Definitions ... +enum ENUM_X121_XTREND_BUFFERS +{ + // + X121_XTREND_UP_LINE = 0, + X121_XTREND_DOWN_LINE = 1, + X121_XTREND_MA_LINE = 2, + X121_XTREND_ADX_LINE = 3, + X121_XTREND_ADX_P_LINE = 4, + X121_XTREND_ADX_M_LINE = 5, + X121_XTREND_UP_T_LINE = 6, + X121_XTREND_DOWN_T_LINE = 7, +}; + +// +// Input Models ... +struct X121XTRENDInputs +{ + // + // Props ... + // + // Market ... + ENUM_APPLIED_PRICE trendPriceType; // Detect Trend Price Type + + // + // MA Detection ... + int maLength; // MA Length + ENUM_MA_METHOD maMethod; // MA Method + ENUM_APPLIED_PRICE maAppliedTo; // MA Applied To + + // + // ADX Detection ... + int adxLength; // ADX Length + double adxThreshold; // ADX Threshold for Strong Trends + + // + // Presentation ... + + // + int startCalculationForLastBars; // Calculate Last n Bars + int upTrendArrowCode; // Up Trend Arrow Code + int downTrendArrowCode; // Down Trend Arrow Code + + // + bool showOnlyTrendStart; // Show Only Trend Start + bool showUpTrend; // Show Up Trend + bool showDownTrend; // Show Down Trend + + // + // Constructor(s) ... + X121XTRENDInputs() + { + Clean(); + } + + // + // Tools ... + + // + // Clean ... + void Clean() + { + // + trendPriceType = PRICE_CLOSE; + maLength = 50; + maMethod = MODE_EMA; + maAppliedTo = PRICE_CLOSE; + adxLength = 14; + adxThreshold = 25; + startCalculationForLastBars = 1000; + upTrendArrowCode = 233; + downTrendArrowCode = 234; + showOnlyTrendStart = false; + showUpTrend = false; + showDownTrend = false; + + // + ZeroMemory(this); + } + + // + // Default ... + void Default() + { + // + trendPriceType = PRICE_CLOSE; + maLength = 50; + maMethod = MODE_EMA; + maAppliedTo = PRICE_CLOSE; + adxLength = 14; + adxThreshold = 25; + startCalculationForLastBars = 1000; + upTrendArrowCode = 233; + downTrendArrowCode = 234; + showOnlyTrendStart = true; + showUpTrend = true; + showDownTrend = true; + } + + // + // Validate ... + bool IsValid() + { + // + bool result = false; + + // + result = + // + // MA ... + maLength > 0 && + // + // ADX ... + adxLength > 0 && + adxThreshold > 0 + // + ; + + // + return result; + } + + // + // Retrieve MAx Length ... + int Max() + { + // + int result = 0; + + // + result = MathMax(maLength, adxLength); + + // + return result; + } +}; + +// +// Conditions ... +struct X121XTRENDConditions +{ + // + // Common ... + string symbol; + ENUM_TIMEFRAMES period; + datetime time; + + // + // Buffers ... + double upTrendBuffer[]; + double downTrendBuffer[]; + double maBuffer[]; + double adxBuffer[]; + double adxPBuffer[]; + double adxMBuffer[]; + double upTBuffer[]; + double downTBuffer[]; + + // + // Conditions ... + + // + bool isTrendBullish; + bool isTrendBearish; + + // + bool isTrendSwitchedToBullish; + bool isTrendSwitchedToBearish; + + // + // bool isCloseLower + + // + // Constructor ... + X121XTRENDConditions() + { + Clean(); + } + + // + // Tools ... + + /** + * Cleaning Up ... + */ + void Clean() + { + // + // Commons ... + symbol = NULL; + period = NULL; + time = NULL; + + // + // Buffers ... + + // + Clean(upTrendBuffer); + Clean(downTrendBuffer); + Clean(maBuffer); + Clean(adxBuffer); + Clean(adxPBuffer); + Clean(adxMBuffer); + Clean(upTBuffer); + Clean(downTBuffer); + + // + ArraySetAsSeries(upTrendBuffer, true); + ArraySetAsSeries(downTrendBuffer, true); + ArraySetAsSeries(maBuffer, true); + ArraySetAsSeries(adxBuffer, true); + ArraySetAsSeries(adxPBuffer, true); + ArraySetAsSeries(adxMBuffer, true); + ArraySetAsSeries(upTBuffer, true); + ArraySetAsSeries(downTBuffer, true); + + // + // Conditions ... + + // + isTrendBullish = false; + isTrendBearish = false; + + // + isTrendSwitchedToBullish = false; + isTrendSwitchedToBearish = false; + + // + ZeroMemory(this); + } + + /** + * Generate Conditions Scores ... + * + * @param bullishScore: Double, Directional Scores Reference ... + * @param bearishScore: Double, Directional Scores Reference ... + */ + void GenerateScore( + double &bullishScore, + double &bearishScore // + ) + { + // + bullishScore = 0; + bearishScore = 0; + + // + double score = 1; + double minScore = 0.5; + double highScore = 1.5; + + // + if (isTrendBullish) + { + bullishScore += minScore; + } + if (isTrendSwitchedToBullish) + { + bullishScore += score; + } + + // + if (isTrendBearish) + { + bearishScore += minScore; + } + if (isTrendSwitchedToBearish) + { + bearishScore += score; + } + } + + /** + * Generate Summary String for Represent Conditions State ... + * + * @param onlyCommons: Boolean, Just Generate Only Commons Conditions ... + * @param onlyConditions: Boolean, Just Generate Only Conditions ... + * @param includeScores: Boolean, Attach Scores Representations on Result ... + * @param ignoreFalseConditions: Boolean, Ignore False Conditions on Result ... + * @param separator: String, Separate Lines ... + * + * @return ( string ) + */ + string GenerateSummary( + bool onlyCommons = false, + bool onlyConditions = false, + bool includeScores = true, + bool ignoreFalseConditions = true, + string separator = "\n" // + ) + { + // + string result = NULL; + + // + double bullishScore = 0; + double bearishScore = 0; + GenerateScore( + bullishScore, + bearishScore // + ); + + // + string scoresStr = + // + "Scores: " + separator + + "---------------" + separator + + "Bullish: " + ToString(bullishScore) + separator + + "Bearish: " + ToString(bearishScore) + separator + + "" + // + ; + + // + string commonStr = GenerateSpecifiedCommonSummary( + this, + separator, + includeScores // + ); + + // + string conditionsStr = + // + "-----------------------" + separator + + "XTREND: " + separator + + "-----------------------" + separator + + ToString("isTrendBullish", isTrendBullish, ignoreFalseConditions, separator) + + ToString("isTrendBearish", isTrendBearish, ignoreFalseConditions, separator) + + ToString("isTrendSwitchedToBullish", isTrendSwitchedToBullish, ignoreFalseConditions, separator) + + ToString("isTrendSwitchedToBearish", isTrendSwitchedToBearish, ignoreFalseConditions, separator) + + // + "" + // + ; + + // + result = + // + "[" + GetTag() + "]" + separator + + (onlyConditions + ? "" + : commonStr) + + (!includeScores + ? "" + : scoresStr) + + " " + separator + + (onlyCommons + ? "" + : conditionsStr) + + "" + // + ; + + // + return result; + } + + /** + * Retrieve nique Tag Identifier ... + * + * @return ( string ) + */ + string GetTag() + { + return GetTypeName(this); + } + + // +}; + +// +// Class ... +class XCX121XTRENDHelper : public XCBaseHelper +{ + // + // Public ... + public: + // + // Props ... + + // + // Constructors ... + XCX121XTRENDHelper() + : XCBaseHelper(_Symbol, _Period) + { + } + + // + // Deconstructor ... + ~XCX121XTRENDHelper() + { + // + mInputs.Clean(); + + // + Clean(upTrendBuffer); + Clean(downTrendBuffer); + Clean(maBuffer); + Clean(adxBuffer); + Clean(adxPBuffer); + Clean(adxMBuffer); + Clean(upTBuffer); + Clean(downTBuffer); + } + + // + // Tools ... + bool Init( + string symbol, // Trading Symbol + ENUM_TIMEFRAMES period, // Trading Period + X121XTRENDInputs &inputs // Inputs + ) + { + // + bool result = false; + + // + mSymbol = symbol; + mPeriod = period; + + // + result = inputs.IsValid(); + if (!result) + { + return result; + } + + // + ArraySetAsSeries(upTrendBuffer, true); + ArraySetAsSeries(downTrendBuffer, true); + ArraySetAsSeries(maBuffer, true); + ArraySetAsSeries(adxBuffer, true); + ArraySetAsSeries(adxPBuffer, true); + ArraySetAsSeries(adxMBuffer, true); + ArraySetAsSeries(upTBuffer, true); + ArraySetAsSeries(downTBuffer, true); + + // + mInputs = inputs; + + // + mHandler = iCustom( + mSymbol, + mPeriod, + "x-saherelm.x121.xtrend", + // + // Inputs ... + // + // Market ... + "", + mInputs.trendPriceType, + // + // MA Detection ... + "", + mInputs.maLength, + mInputs.maMethod, + mInputs.maAppliedTo, + // + // ADX Detection ... + "", + mInputs.adxLength, + mInputs.adxThreshold, + // + // Presentation ... + "", + mInputs.startCalculationForLastBars, + mInputs.upTrendArrowCode, + mInputs.downTrendArrowCode, + mInputs.showOnlyTrendStart, + mInputs.showUpTrend, + mInputs.showDownTrend + // + ); + result = mHandler != INVALID_HANDLE; + if (!result) + { + return result; + } + + // + return result; + } + + // + // Inputs ... + + // + X121XTRENDInputs GetInputs() + { + return mInputs; + } + + // + bool SetInputs( + X121XTRENDInputs &inputs // Configs + ) + { + // + return Init( + mSymbol, + mPeriod, + inputs + // + ); + } + + // + // Readers ... + + // + // Up Trend ... + + // + double GetUpTrend( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(upTrendBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return upTrendBuffer[barIndex]; + } + + // + int CopyUpTrend( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + upTrendBuffer, + buffer, + forceClean + // + ); + } + + // + // Down Trend ... + + // + double GetDownTrend( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(downTrendBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return downTrendBuffer[barIndex]; + } + + // + int CopyDownTrend( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + downTrendBuffer, + buffer, + forceClean + // + ); + } + + // + // Ma ... + + // + double GetMA( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(downTrendBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return downTrendBuffer[barIndex]; + } + + // + int CopyMA( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + downTrendBuffer, + buffer, + forceClean + // + ); + } + + // + // ADX ... + + // + double GetADX( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(adxBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return adxBuffer[barIndex]; + } + + // + int CopyADX( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + adxBuffer, + buffer, + forceClean + // + ); + } + + // + // ADX P... + + // + double GetADXP( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(adxPBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return adxPBuffer[barIndex]; + } + + // + int CopyADXP( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + adxPBuffer, + buffer, + forceClean + // + ); + } + + // + // ADX M ... + + // + double GetADXM( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(adxMBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return adxMBuffer[barIndex]; + } + + // + int CopyADXM( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + adxMBuffer, + buffer, + forceClean + // + ); + } + + // + // Up Trend ... + + // + double GetUpT( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(upTBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return upTBuffer[barIndex]; + } + + // + int CopyUpT( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + upTBuffer, + buffer, + forceClean + // + ); + } + + // + // Down Trend ... + + // + double GetDownT( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(downTBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return downTBuffer[barIndex]; + } + + // + int CopyDownT( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + downTBuffer, + buffer, + forceClean + // + ); + } + + // + void Free() override + { + Cleanup(10); + } + + // + bool GetConditions( + X121XTRENDConditions &conditions, // + int barIndex = 0, // + int loopback = 5 // + ) + { + // + bool result = true; + + // + if (loopback < 5) + { + loopback = 5; + } + + // + conditions.Clean(); + + // + conditions.symbol = mSymbol; + conditions.period = mPeriod; + conditions.time = TimeCurrent(); + + // + int zIndex = barIndex; + int cIndex = zIndex + 1; + int pIndex = cIndex + 1; + int ppIndex = pIndex + 1; + + // + XOHCL zBar; + result = zBar.Init( + mSymbol, + mPeriod, + zIndex // + ); + if (!result) + { + return result; + } + + // + XOHCL cBar; + result = cBar.Init( + mSymbol, + mPeriod, + cIndex // + ); + if (!result) + { + return result; + } + + // + XOHCL pBar; + result = pBar.Init( + mSymbol, + mPeriod, + pIndex // + ); + if (!result) + { + return result; + } + + // + // Buffers ... + + // + CopyUpTrend( + zIndex, + loopback, + conditions.upTrendBuffer // + ); + + // + CopyDownTrend( + zIndex, + loopback, + conditions.downTrendBuffer // + ); + + // + CopyMA( + zIndex, + loopback, + conditions.maBuffer // + ); + + // + CopyADX( + zIndex, + loopback, + conditions.adxBuffer // + ); + + // + CopyADXP( + zIndex, + loopback, + conditions.adxPBuffer // + ); + + // + CopyADXM( + zIndex, + loopback, + conditions.adxMBuffer // + ); + + // + CopyUpT( + zIndex, + loopback, + conditions.upTBuffer // + ); + + // + CopyDownT( + zIndex, + loopback, + conditions.downTBuffer // + ); + + // + // Conditions ... + + // + int cIDX = 1; + int pIDX = cIDX + 1; + + // + bool isTrendBullish = upTBuffer[cIDX] != 0; + bool isTrendBullishPrev = upTBuffer[pIDX] != 0; + + // + bool isTrendBearish = downTBuffer[cIDX] != 0; + bool isTrendBearishPrev = downTBuffer[pIDX] != 0; + + // + bool isTrendSwitchedToBullish = isTrendBullish && + !isTrendBullishPrev; + bool isTrendSwitchedToBearish = isTrendBearish && + !isTrendBearishPrev; + + // + conditions.isTrendBullish = isTrendBullish; + conditions.isTrendBearish = isTrendBearish; + conditions.isTrendSwitchedToBullish = isTrendSwitchedToBullish; + conditions.isTrendSwitchedToBearish = isTrendSwitchedToBearish; + + // + Cleanup(); + + // + zBar.Clean(); + cBar.Clean(); + pBar.Clean(); + + // + return result; + } + + // + // Protected ... + protected: + // + // Private ... + private: + // + // Props ... + X121XTRENDInputs mInputs; // Inputs ... + + // + // Buffers ... + double upTrendBuffer[]; + double downTrendBuffer[]; + double maBuffer[]; + double adxBuffer[]; + double adxPBuffer[]; + double adxMBuffer[]; + double upTBuffer[]; + double downTBuffer[]; + + // + void Calculate( + int barIndex = 0, + int maxRequiredBars = 100 // + ) + { + // + // Buffers ... + if (barIndex < 0) + { + barIndex = 0; + } + + // + // Up Trend ... + CopyBuffer( + mHandler, + X121_XTREND_UP_LINE, + barIndex, + maxRequiredBars, + upTrendBuffer + // + ); + + // + // Down Trend ... + CopyBuffer( + mHandler, + X121_XTREND_DOWN_LINE, + barIndex, + maxRequiredBars, + downTrendBuffer + // + ); + + // + // MA ... + CopyBuffer( + mHandler, + X121_XTREND_MA_LINE, + barIndex, + maxRequiredBars, + maBuffer + // + ); + + // + // ADX ... + CopyBuffer( + mHandler, + X121_XTREND_ADX_LINE, + barIndex, + maxRequiredBars, + adxBuffer + // + ); + + // + // ADX P ... + CopyBuffer( + mHandler, + X121_XTREND_ADX_P_LINE, + barIndex, + maxRequiredBars, + adxPBuffer + // + ); + + // + // ADX M ... + CopyBuffer( + mHandler, + X121_XTREND_ADX_M_LINE, + barIndex, + maxRequiredBars, + adxMBuffer + // + ); + + // + // Up T ... + CopyBuffer( + mHandler, + X121_XTREND_UP_T_LINE, + barIndex, + maxRequiredBars, + upTBuffer + // + ); + + // + // Down T ... + CopyBuffer( + mHandler, + X121_XTREND_DOWN_T_LINE, + barIndex, + maxRequiredBars, + downTBuffer + // + ); + } + + // + void Cleanup( + int maxAllowed = 100 // + ) + { + // + CleanupArray( + upTrendBuffer, + maxAllowed // + ); + + // + CleanupArray( + downTrendBuffer, + maxAllowed // + ); + + // + CleanupArray( + maBuffer, + maxAllowed // + ); + + // + CleanupArray( + adxBuffer, + maxAllowed // + ); + + // + CleanupArray( + adxPBuffer, + maxAllowed // + ); + + // + CleanupArray( + adxMBuffer, + maxAllowed // + ); + + // + CleanupArray( + upTBuffer, + maxAllowed // + ); + + // + CleanupArray( + downTBuffer, + maxAllowed // + ); + + // + } + + // +}; + +// +// Tools ... \ No newline at end of file diff --git a/BKPS/14040203/Helpers/x-saherelm.x121.xvolume.helper.mq5 b/BKPS/14040203/Helpers/x-saherelm.x121.xvolume.helper.mq5 new file mode 100644 index 0000000..4fc0c24 --- /dev/null +++ b/BKPS/14040203/Helpers/x-saherelm.x121.xvolume.helper.mq5 @@ -0,0 +1,1158 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Helper Class Library +// ---------------------------------------------- +// Name: XCX121XVOLUMESHelper +// Description: provides all Indicator +// Helper requirements ... +// +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +////////////////////////////////////////////////////// +// +// Global Properties ... +#property library +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://www.saherelm.ir" +#property version "1.00" +#property strict + +// +// Imports ... +#include "../Classes/x-saherelm.x-helper.class.mq5" + +// +// Definitions ... +enum ENUM_X121_XVOLUME_BUFFERS +{ + // + X121_XVOLUME_BULLISH_LINE = 0, + X121_XVOLUME_BULLISH_MA_LINE = 1, + X121_XVOLUME_BEARISH_LINE = 2, + X121_XVOLUME_BEARISH_MA_LINE = 3, +}; + +// +// Input Models ... +struct X121XVOLUMEInputs +{ + // + // Props ... + + // + // Makret ... + int maLength; // Moving Averge Length + ENUM_X_MA_METHOD maMethod; // Moving Averge Method + + // + // Presentation ... + int startCalculationForLastBars; // Calculate Last n Bars + bool showBullishVolume; // Show Bullish Volume + bool showBullishVolumeMa; // Show Bullish Volume Moving Average + bool showBearishVolume; // Show Bearish Volume + bool showBearishVolumeMa; // Show Bearish Volume Moving Average + + // + // Constructor(s) ... + X121XVOLUMEInputs() + { + Clean(); + } + + // + // Tools ... + + /** + * Cleanup Model ... + */ + void Clean() + { + // + // Makret ... + maLength = 0; // Moving Averge Length + maMethod = X_MA_MODE_NONE; // Moving Averge Method + + // + // Presentation ... + startCalculationForLastBars = 0; // Calculate Last n Bars + showBullishVolume = false; // Show Bullish Volume + showBullishVolumeMa = false; // Show Bullish Volume Moving Average + showBearishVolume = false; // Show Bearish Volume + showBearishVolumeMa = false; // Show Bearish Volume Moving Average + + // + ZeroMemory(this); + } + + /** + * Default Inputs ... + */ + void Default() + { + // + // Makret ... + maLength = 14; // Moving Averge Length + maMethod = X_MA_MODE_EMA; // Moving Averge Method + + // + // Presentation ... + startCalculationForLastBars = 1000; // Calculate Last n Bars + showBullishVolume = true; // Show Bullish Volume + showBullishVolumeMa = true; // Show Bullish Volume Moving Average + showBearishVolume = true; // Show Bearish Volume + showBearishVolumeMa = true; // Show Bearish Volume Moving Average + } + + /** + * Validate Model ... + * + * @return ( bool ) + */ + bool IsValid() + { + // + bool result = false; + + // + result = + // + maLength > 0 && + IsValid(maMethod) + // + ; + + // + return result; + } + + /** + * Retrieve Max Input Length ... + * + * @return ( int ) + */ + int Max() + { + // + int result = 0; + + // + result = MathMax(result, maLength); + + // + return result; + } + + // +}; + +// +// Conditions ... +struct X121XVOLUMEConditions +{ + // + // Common ... + string symbol; + ENUM_TIMEFRAMES period; + datetime time; + + // + // Buffers ... + double bullishVolumeBuffer[]; + double bullishVolumeMaBuffer[]; + double bearishVolumeBuffer[]; + double bearishVolumeMaBuffer[]; + + // + // Conditions ... + + // + bool isBullishVolumeOverMa; + bool isBullishVolumeCrossedOverMa; + + // + bool isBullishVolumeUnderMa; + bool isBullishVolumeCrossedUnderMa; + + // + bool isBullishVolumeIncreased; + bool isBullishVolumeSwitchedToIncreased; + + // + bool isBullishVolumeDecreased; + bool isBullishVolumeSwitchedToDecreased; + + // + bool isBearishVolumeOverMa; + bool isBearishVolumeCrossedOverMa; + + // + bool isBearishVolumeUnderMa; + bool isBearishVolumeCrossedUnderMa; + + // + bool isBearishVolumeIncreased; + bool isBearishVolumeSwitchedToIncreased; + + // + bool isBearishVolumeDecreased; + bool isBearishVolumeSwitchedToDecreased; + + // + bool isVolumeSwitchedToBullish; + bool isVolumeSwitchedToBearish; + bool isBullishVolumeMaOverBearishVolumeMa; + bool isBullishVolumeMaUnderBearishVolumeMa; + + // + // Constructor ... + X121XVOLUMEConditions() + { + Clean(); + } + + // + // Tools ... + + /** + * Cleaning Up ... + */ + void Clean() + { + // + // Commons ... + time = NULL; + symbol = NULL; + period = NULL; + + // + // Buffers ... + + // + Clean(bullishVolumeBuffer); + Clean(bullishVolumeMaBuffer); + Clean(bearishVolumeBuffer); + Clean(bearishVolumeMaBuffer); + + // + ArraySetAsSeries(bullishVolumeBuffer, true); + ArraySetAsSeries(bullishVolumeMaBuffer, true); + ArraySetAsSeries(bearishVolumeBuffer, true); + ArraySetAsSeries(bearishVolumeMaBuffer, true); + + // + // Conditions ... + + // + isBullishVolumeOverMa = false; + isBullishVolumeCrossedOverMa = false; + + // + isBullishVolumeUnderMa = false; + isBullishVolumeCrossedUnderMa = false; + + // + isBullishVolumeIncreased = false; + isBullishVolumeSwitchedToIncreased = false; + + // + isBullishVolumeDecreased = false; + isBullishVolumeSwitchedToDecreased = false; + + // + isBearishVolumeOverMa = false; + isBearishVolumeCrossedOverMa = false; + + // + isBearishVolumeUnderMa = false; + isBearishVolumeCrossedUnderMa = false; + + // + isBearishVolumeIncreased = false; + isBearishVolumeSwitchedToIncreased = false; + + // + isBearishVolumeDecreased = false; + isBearishVolumeSwitchedToDecreased = false; + + // + isVolumeSwitchedToBullish = false; + isVolumeSwitchedToBearish = false; + isBullishVolumeMaOverBearishVolumeMa = false; + isBullishVolumeMaUnderBearishVolumeMa = false; + + // + ZeroMemory(this); + } + + /** + * Generate Conditions Scores ... + * + * @param bullishScore: Double, Directional Scores Reference ... + * @param bearishScore: Double, Directional Scores Reference ... + */ + void GenerateScore( + double &bullishScore, + double &bearishScore // + ) + { + // + bullishScore = 0; + bearishScore = 0; + + // + double score = 1; + double minScore = 0.5; + double highScore = 1.5; + + // + if (isBullishVolumeOverMa) + { + bullishScore += minScore; + } + if (isBearishVolumeUnderMa) + { + bullishScore += minScore; + } + if (isBullishVolumeIncreased) + { + bullishScore += minScore; + } + if (isBearishVolumeDecreased) + { + bullishScore += minScore; + } + if (isBullishVolumeMaOverBearishVolumeMa) + { + bullishScore += minScore; + } + + // + if (isVolumeSwitchedToBullish) + { + bullishScore += score; + } + if (isBullishVolumeCrossedOverMa) + { + bullishScore += score; + } + if (isBearishVolumeCrossedUnderMa) + { + bullishScore += score; + } + if (isBullishVolumeSwitchedToIncreased) + { + bullishScore += score; + } + if (isBearishVolumeSwitchedToDecreased) + { + bullishScore += score; + } + + // + if (isBearishVolumeOverMa) + { + bearishScore += minScore; + } + if (isBullishVolumeUnderMa) + { + bearishScore += minScore; + } + if (isBullishVolumeDecreased) + { + bearishScore += minScore; + } + if (isBearishVolumeIncreased) + { + bearishScore += minScore; + } + if (isBullishVolumeMaUnderBearishVolumeMa) + { + bearishScore += minScore; + } + + // + if (isVolumeSwitchedToBearish) + { + bearishScore += score; + } + if (isBearishVolumeCrossedOverMa) + { + bearishScore += score; + } + if (isBullishVolumeCrossedUnderMa) + { + bearishScore += score; + } + if (isBullishVolumeSwitchedToDecreased) + { + bearishScore += score; + } + if (isBearishVolumeSwitchedToIncreased) + { + bearishScore += score; + } + } + + /** + * Generate Summary String for Represent Conditions State ... + * + * @param onlyCommons: Boolean, Just Generate Only Commons Conditions ... + * @param onlyConditions: Boolean, Just Generate Only Conditions ... + * @param includeScores: Boolean, Attach Scores Representations on Result ... + * @param ignoreFalseConditions: Boolean, Ignore False Conditions on Result ... + * @param separator: String, Separate Lines ... + * + * @return ( string ) + */ + string GenerateSummary( + bool onlyCommons = false, + bool onlyConditions = false, + bool includeScores = true, + bool ignoreFalseConditions = true, + string separator = "\n" // + ) + { + // + string result = NULL; + + // + double bullishScore = 0; + double bearishScore = 0; + GenerateScore( + bullishScore, + bearishScore // + ); + + // + string scoresStr = + // + "Scores: " + separator + + "---------------" + separator + + "Bullish: " + ToString(bullishScore) + separator + + "Bearish: " + ToString(bearishScore) + separator + + "" + // + ; + + // + string commonStr = GenerateSpecifiedCommonSummary( + this, + separator, + includeScores // + ); + + // + string conditionsStr = + // + "-----------------------" + separator + + "XVOLUME: " + separator + + "-----------------------" + separator + + ToString("isBullishVolumeOverMa", isBullishVolumeOverMa, ignoreFalseConditions, separator) + + ToString("isBullishVolumeCrossedOverMa", isBullishVolumeCrossedOverMa, ignoreFalseConditions, separator) + + ToString("isBullishVolumeUnderMa", isBullishVolumeUnderMa, ignoreFalseConditions, separator) + + ToString("isBullishVolumeCrossedUnderMa", isBullishVolumeCrossedUnderMa, ignoreFalseConditions, separator) + + ToString("isBullishVolumeIncreased", isBullishVolumeIncreased, ignoreFalseConditions, separator) + + ToString("isBullishVolumeSwitchedToIncreased", isBullishVolumeSwitchedToIncreased, ignoreFalseConditions, separator) + + ToString("isBullishVolumeDecreased", isBullishVolumeDecreased, ignoreFalseConditions, separator) + + ToString("isBullishVolumeSwitchedToDecreased", isBullishVolumeSwitchedToDecreased, ignoreFalseConditions, separator) + + ToString("isBearishVolumeOverMa", isBearishVolumeOverMa, ignoreFalseConditions, separator) + + ToString("isBearishVolumeCrossedOverMa", isBearishVolumeCrossedOverMa, ignoreFalseConditions, separator) + + ToString("isBearishVolumeUnderMa", isBearishVolumeUnderMa, ignoreFalseConditions, separator) + + ToString("isBearishVolumeCrossedUnderMa", isBearishVolumeCrossedUnderMa, ignoreFalseConditions, separator) + + ToString("isBearishVolumeIncreased", isBearishVolumeIncreased, ignoreFalseConditions, separator) + + ToString("isBearishVolumeSwitchedToIncreased", isBearishVolumeSwitchedToIncreased, ignoreFalseConditions, separator) + + ToString("isBearishVolumeDecreased", isBearishVolumeDecreased, ignoreFalseConditions, separator) + + ToString("isBearishVolumeSwitchedToDecreased", isBearishVolumeSwitchedToDecreased, ignoreFalseConditions, separator) + + ToString("isVolumeSwitchedToBullish", isVolumeSwitchedToBullish, ignoreFalseConditions, separator) + + ToString("isVolumeSwitchedToBearish", isVolumeSwitchedToBearish, ignoreFalseConditions, separator) + + ToString("isBullishVolumeMaOverBearishVolumeMa", isBullishVolumeMaOverBearishVolumeMa, ignoreFalseConditions, separator) + + ToString("isBullishVolumeMaUnderBearishVolumeMa", isBullishVolumeMaUnderBearishVolumeMa, ignoreFalseConditions, separator) + + // + "" + // + ; + + // + result = + // + "[" + GetTag() + "]" + separator + + (onlyConditions + ? "" + : commonStr) + + (!includeScores + ? "" + : scoresStr) + + " " + separator + + (onlyCommons + ? "" + : conditionsStr) + + "" + // + ; + + // + return result; + } + + /** + * Retrieve nique Tag Identifier ... + * + * @return ( string ) + */ + string GetTag() + { + return GetTypeName(this); + } + + // +}; + +// +// Class ... +class XCX121XVOLUMEHelper : public XCBaseHelper +{ + // + // Public ... + public: + // + // Props ... + + // + // Constructors ... + XCX121XVOLUMEHelper() + : XCBaseHelper(_Symbol, _Period) + { + } + + // + // Deconstructor ... + ~XCX121XVOLUMEHelper() + { + // + mInputs.Clean(); + + // + Clean(bullishVolumeBuffer); + Clean(bullishVolumeMaBuffer); + Clean(bearishVolumeBuffer); + Clean(bearishVolumeMaBuffer); + } + + // + // Tools ... + bool Init( + string symbol, // Trading Symbol + ENUM_TIMEFRAMES period, // Trading Period + X121XVOLUMEInputs &inputs // Inputs + ) + { + // + bool result = false; + + // + mSymbol = symbol; + mPeriod = period; + + // + result = inputs.IsValid(); + if (!result) + { + return result; + } + + // + ArraySetAsSeries(bullishVolumeBuffer, true); + ArraySetAsSeries(bullishVolumeMaBuffer, true); + ArraySetAsSeries(bearishVolumeBuffer, true); + ArraySetAsSeries(bearishVolumeMaBuffer, true); + + // + mInputs = inputs; + + // + mHandler = iCustom( + mSymbol, + mPeriod, + "x-saherelm.x121.xvolume", + // + // Inputs ... + // + // Market ... + "", + mInputs.maLength, + mInputs.maMethod, + // + // Presentation ... + "", + // + mInputs.startCalculationForLastBars, + mInputs.showBullishVolume, + mInputs.showBullishVolumeMa, + mInputs.showBearishVolume, + mInputs.showBearishVolumeMa + // + ); + result = mHandler != INVALID_HANDLE; + if (!result) + { + return result; + } + + // + return result; + } + + // + // Inputs ... + + // + X121XVOLUMEInputs GetInputs() + { + return mInputs; + } + + // + bool SetInputs( + X121XVOLUMEInputs &inputs // Configs + ) + { + // + return Init( + mSymbol, + mPeriod, + inputs + // + ); + } + + // + // Readers ... + + // + // Bullish ... + + // + double GetBullishVolume( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(bullishVolumeBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return bullishVolumeBuffer[barIndex]; + } + + // + int CopyBullishVolume( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + bullishVolumeBuffer, + buffer, + forceClean + // + ); + } + + // + double GetBullishVolumeMa( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(bullishVolumeMaBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return bullishVolumeMaBuffer[barIndex]; + } + + // + int CopyBullishVolumeMa( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + bullishVolumeMaBuffer, + buffer, + forceClean + // + ); + } + + // + // Bearish ... + + // + double GetBearishVolume( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(bearishVolumeBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return bearishVolumeBuffer[barIndex]; + } + + // + int CopyBearishVolume( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + bearishVolumeBuffer, + buffer, + forceClean + // + ); + } + + // + double GetBearishVolumeMa( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(bearishVolumeMaBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return bearishVolumeMaBuffer[barIndex]; + } + + // + int CopyBearishVolumeMa( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + bearishVolumeMaBuffer, + buffer, + forceClean + // + ); + } + + // + bool GetConditions( + X121XVOLUMEConditions &conditions, // + int barIndex = 0, // + int loopback = 5 // + ) + { + // + bool result = true; + + // + if (loopback < 5) + { + loopback = 5; + } + + // + conditions.Clean(); + + // + conditions.symbol = mSymbol; + conditions.period = mPeriod; + conditions.time = TimeCurrent(); + + // + int zIndex = barIndex; + int cIndex = zIndex + 1; + int pIndex = cIndex + 1; + int ppIndex = pIndex + 1; + + // + XOHCL zBar; + result = zBar.Init( + mSymbol, + mPeriod, + zIndex // + ); + if (!result) + { + return result; + } + + // + XOHCL cBar; + result = cBar.Init( + mSymbol, + mPeriod, + cIndex // + ); + if (!result) + { + return result; + } + + // + XOHCL pBar; + result = pBar.Init( + mSymbol, + mPeriod, + pIndex // + ); + if (!result) + { + return result; + } + + // + // Buffers ... + + // + CopyBullishVolume( + zIndex, + loopback, + conditions.bullishVolumeBuffer // + ); + + // + CopyBullishVolumeMa( + zIndex, + loopback, + conditions.bullishVolumeMaBuffer // + ); + + // + CopyBearishVolume( + zIndex, + loopback, + conditions.bearishVolumeBuffer // + ); + + // + CopyBearishVolumeMa( + zIndex, + loopback, + conditions.bearishVolumeMaBuffer // + ); + + // + // Conditions ... + + // + int cIDX = 1; + int pIDX = cIDX + 1; + int pPIDX = pIDX + 1; + + // + bool isBullishVolumeOverMa = conditions.bullishVolumeBuffer[cIDX] > conditions.bullishVolumeMaBuffer[cIDX]; + bool isBullishVolumeOverMaP = conditions.bullishVolumeBuffer[pIDX] > conditions.bullishVolumeMaBuffer[pIDX]; + bool isBullishVolumeCrossedOverMa = isBullishVolumeOverMa && + !isBullishVolumeOverMaP; + + // + bool isBullishVolumeUnderMa = conditions.bullishVolumeBuffer[cIDX] < conditions.bullishVolumeMaBuffer[cIDX]; + bool isBullishVolumeUnderMaP = conditions.bullishVolumeBuffer[pIDX] < conditions.bullishVolumeMaBuffer[pIDX]; + bool isBullishVolumeCrossedUnderMa = isBullishVolumeUnderMa && + !isBullishVolumeUnderMaP; + + // + bool isBullishVolumeIncreased = conditions.bullishVolumeBuffer[cIDX] > conditions.bullishVolumeBuffer[pIDX]; + bool isBullishVolumeIncreasedP = conditions.bullishVolumeBuffer[pIDX] > conditions.bullishVolumeBuffer[pPIDX]; + bool isBullishVolumeSwitchedToIncreased = isBullishVolumeIncreased && + !isBullishVolumeIncreasedP; + + // + bool isBullishVolumeDecreased = conditions.bullishVolumeBuffer[cIDX] < conditions.bullishVolumeBuffer[pIDX]; + bool isBullishVolumeDecreasedP = conditions.bullishVolumeBuffer[pIDX] < conditions.bullishVolumeBuffer[pPIDX]; + bool isBullishVolumeSwitchedToDecreased = isBullishVolumeDecreased && + !isBullishVolumeDecreasedP; + + // + bool isBearishVolumeOverMa = conditions.bearishVolumeBuffer[cIDX] > conditions.bearishVolumeMaBuffer[cIDX]; + bool isBearishVolumeOverMaP = conditions.bearishVolumeBuffer[pIDX] > conditions.bearishVolumeMaBuffer[pIDX]; + bool isBearishVolumeCrossedOverMa = isBearishVolumeOverMa && + !isBearishVolumeOverMaP; + + // + bool isBearishVolumeUnderMa = conditions.bearishVolumeBuffer[cIDX] < conditions.bearishVolumeMaBuffer[cIDX]; + bool isBearishVolumeUnderMaP = conditions.bearishVolumeBuffer[pIDX] < conditions.bearishVolumeMaBuffer[pIDX]; + bool isBearishVolumeCrossedUnderMa = isBearishVolumeUnderMa && + !isBearishVolumeUnderMaP; + + // + bool isBearishVolumeIncreased = conditions.bearishVolumeBuffer[cIDX] > conditions.bearishVolumeBuffer[pIDX]; + bool isBearishVolumeIncreasedP = conditions.bearishVolumeBuffer[pIDX] > conditions.bearishVolumeBuffer[pPIDX]; + bool isBearishVolumeSwitchedToIncreased = isBearishVolumeIncreased && + !isBearishVolumeIncreasedP; + + // + bool isBearishVolumeDecreased = conditions.bearishVolumeBuffer[cIDX] < conditions.bearishVolumeBuffer[pIDX]; + bool isBearishVolumeDecreasedP = conditions.bearishVolumeBuffer[pIDX] < conditions.bearishVolumeBuffer[pPIDX]; + bool isBearishVolumeSwitchedToDecreased = isBearishVolumeDecreased && + !isBearishVolumeDecreasedP; + + // + bool isBullishVolumeMaOverBearishVolumeMa = conditions.bullishVolumeMaBuffer[cIDX] > conditions.bearishVolumeMaBuffer[cIDX]; + bool isBullishVolumeMaOverBearishVolumeMaP = conditions.bullishVolumeMaBuffer[pIDX] > conditions.bearishVolumeMaBuffer[pIDX]; + bool isVolumeSwitchedToBullish = isBullishVolumeMaOverBearishVolumeMa && + !isBullishVolumeMaOverBearishVolumeMaP; + + // + bool isBullishVolumeMaUnderBearishVolumeMa = conditions.bullishVolumeMaBuffer[cIDX] < conditions.bearishVolumeMaBuffer[cIDX]; + bool isBullishVolumeMaUnderBearishVolumeMaP = conditions.bullishVolumeMaBuffer[pIDX] < conditions.bearishVolumeMaBuffer[pIDX]; + bool isVolumeSwitchedToBearish = isBullishVolumeMaUnderBearishVolumeMa && + !isBullishVolumeMaUnderBearishVolumeMaP; + + // + // + // + + // + conditions.isBullishVolumeOverMa = isBullishVolumeOverMa; + conditions.isBullishVolumeCrossedOverMa = isBullishVolumeCrossedOverMa; + + // + conditions.isBullishVolumeUnderMa = isBullishVolumeUnderMa; + conditions.isBullishVolumeCrossedUnderMa = isBullishVolumeCrossedUnderMa; + + // + conditions.isBullishVolumeIncreased = isBullishVolumeIncreased; + conditions.isBullishVolumeSwitchedToIncreased = isBullishVolumeSwitchedToIncreased; + + // + conditions.isBullishVolumeDecreased = isBullishVolumeDecreased; + conditions.isBullishVolumeSwitchedToDecreased = isBullishVolumeSwitchedToDecreased; + + // + conditions.isBearishVolumeOverMa = isBearishVolumeOverMa; + conditions.isBearishVolumeCrossedOverMa = isBearishVolumeCrossedOverMa; + + // + conditions.isBearishVolumeUnderMa = isBearishVolumeUnderMa; + conditions.isBearishVolumeCrossedUnderMa = isBearishVolumeCrossedUnderMa; + + // + conditions.isBearishVolumeIncreased = isBearishVolumeIncreased; + conditions.isBearishVolumeSwitchedToIncreased = isBearishVolumeSwitchedToIncreased; + + // + conditions.isBearishVolumeDecreased = isBearishVolumeDecreased; + conditions.isBearishVolumeSwitchedToDecreased = isBearishVolumeSwitchedToDecreased; + + // + conditions.isVolumeSwitchedToBullish = isVolumeSwitchedToBullish; + conditions.isVolumeSwitchedToBearish = isVolumeSwitchedToBearish; + conditions.isBullishVolumeMaOverBearishVolumeMa = isBullishVolumeMaOverBearishVolumeMa; + conditions.isBullishVolumeMaUnderBearishVolumeMa = isBullishVolumeMaUnderBearishVolumeMa; + + // + Cleanup(); + + // + zBar.Clean(); + cBar.Clean(); + pBar.Clean(); + + // + return result; + } + + // + // Protected ... + protected: + // + // Private ... + private: + // + // Props ... + X121XVOLUMEInputs mInputs; // Inputs ... + + // + // Buffers ... + double bullishVolumeBuffer[]; + double bullishVolumeMaBuffer[]; + double bearishVolumeBuffer[]; + double bearishVolumeMaBuffer[]; + + // + void Calculate( + int barIndex = 0, + int maxRequiredBars = 100 // + ) + { + // + // Buffers ... + if (barIndex < 0) { + barIndex = 0; + } + + // + CopyBuffer( + mHandler, + X121_XVOLUME_BULLISH_LINE, + barIndex, + maxRequiredBars, + bullishVolumeBuffer + // + ); + + // + CopyBuffer( + mHandler, + X121_XVOLUME_BULLISH_MA_LINE, + barIndex, + maxRequiredBars, + bullishVolumeMaBuffer + // + ); + + // + CopyBuffer( + mHandler, + X121_XVOLUME_BEARISH_LINE, + barIndex, + maxRequiredBars, + bearishVolumeBuffer + // + ); + + // + CopyBuffer( + mHandler, + X121_XVOLUME_BEARISH_MA_LINE, + barIndex, + maxRequiredBars, + bearishVolumeMaBuffer + // + ); + } + + // + void Cleanup( + int maxAllowed = 100 // + ) + { + // + CleanupArray( + bullishVolumeBuffer, + maxAllowed // + ); + + // + CleanupArray( + bullishVolumeMaBuffer, + maxAllowed // + ); + + // + CleanupArray( + bearishVolumeBuffer, + maxAllowed // + ); + + // + CleanupArray( + bearishVolumeMaBuffer, + maxAllowed // + ); + } + + // +}; + +// diff --git a/BKPS/14040203/Helpers/x-saherelm.x121.xvwap.helper.mq5 b/BKPS/14040203/Helpers/x-saherelm.x121.xvwap.helper.mq5 new file mode 100644 index 0000000..3ac9211 --- /dev/null +++ b/BKPS/14040203/Helpers/x-saherelm.x121.xvwap.helper.mq5 @@ -0,0 +1,1605 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Helper Class Library +// ---------------------------------------------- +// Name: XCX121XVWAPHelper +// Description: provides all Indicator +// Helper requirements ... +// +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +////////////////////////////////////////////////////// +// +// Global Properties ... +#property library +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://www.saherelm.ir" +#property version "1.00" +#property strict + +// +// Imports ... +#include "../Classes/x-saherelm.x-helper.class.mq5" + +// +// Definitions ... + +// +// Definitions ... +enum ENUM_X121_XVWAP_BUFFERS +{ + // + X121_XVWAP_FAST_LINE = 0, + X121_XVWAP_FAST_STATE_LINE = 8, + X121_XVWAP_MID_LINE = 2, + X121_XVWAP_MID_STATE_LINE = 9, + X121_XVWAP_SLOW_LINE = 4, + X121_XVWAP_SLOW_STATE_LINE = 10, + X121_XVWAP_VOLUME_LINE = 6, + X121_XVWAP_PRICE_LINE = 7, +}; + +// +enum ENUM_XVWAP_STATES +{ + XVWAP_STATE_BULLISH = 1, + XVWAP_STATE_BEARISH = 2, + XVWAP_STATE_NEUTURAL = 3, +}; + +// +// Input Models ... +struct X121XVWAPInputs +{ + // + // Props ... + + int vwapFastLength; // Fast Length + int vwapMidLength; // Mid Length + int vwapSlowLength; // Slow Length + ENUM_APPLIED_PRICE vwapAppliedTo; // Applied To + + // + int startCalculationForLastBars; // Calculate Last n Bars + + // + bool showVWapFast; // Show VWap Fast + bool showVWapMedium; // Show VWap Medium + bool showVWapSlow; // Show VWap Slow + + // + // Constructor(s) ... + X121XVWAPInputs() + { + // + Clean(); + } + + // + // Tools ... + + // + // Clean ... + void Clean() + { + // + vwapFastLength = 0; + vwapMidLength = 0; + vwapSlowLength = 0; + vwapAppliedTo = PRICE_CLOSE; + + // + startCalculationForLastBars = 0; + + // + showVWapFast = false; + showVWapMedium = false; + showVWapSlow = false; + + // + ZeroMemory(this); + } + + // + // Default ... + void Default() + { + // + vwapFastLength = 20; + vwapMidLength = 50; + vwapSlowLength = 200; + vwapAppliedTo = PRICE_CLOSE; + + // + startCalculationForLastBars = 1000; + + // + showVWapFast = true; + showVWapMedium = true; + showVWapSlow = true; + } + + // + // Validate ... + bool IsValid() + { + // + bool result = false; + + // + result = + // + vwapFastLength > 2 && + vwapMidLength > vwapFastLength && + vwapSlowLength > vwapMidLength + // + ; + + // + return result; + } + + // + // Retrieve MAx Length ... + int Max() + { + // + int result = 0; + + // + result = MathMax(vwapFastLength, vwapMidLength); + result = MathMax(result, vwapSlowLength); + + // + return result; + } +}; + +// +// Conditions ... +struct X121XVWAPConditions +{ + // + // Common ... + string symbol; + ENUM_TIMEFRAMES period; + datetime time; + + // + // Buffers ... + double vwapFastBuffer[]; + double vwapMidBuffer[]; + double vwapSlowBuffer[]; + double vwapVolumeBuffer[]; + double vwapPriceBuffer[]; + double vwapFastStateBuffer[]; + double vwapMidStateBuffer[]; + double vwapSlowStateBuffer[]; + + // + // Conditions ... + + // + bool isVWapFastBullish; + bool isVWapFastBearish; + bool isVWapFastNeutural; + + // + bool isVWapMidBullish; + bool isVWapMidBearish; + bool isVWapMidNeutural; + + // + bool isVWapSlowBullish; + bool isVWapSlowBearish; + bool isVWapSlowNeutural; + + // + bool isVWapFastOverMid; + bool isVWapMidOverSlow; + + // + bool isVWapFastUnderMid; + bool isVWapMidUnderSlow; + + // + bool isVWapBullishState; + bool isVWapBearishState; + bool isVWapNeuturalState; + + // + bool isVWapBullishOrdered; + bool isVWapBearishOrdered; + + // + bool isVWapSwitchedToBullishOrdered; + bool isVWapSwitchedToBearishOrdered; + + // + bool isVWapSwitchedToBullishState; + bool isVWapSwitchedToBearishState; + bool isVWapSwitchedToNeuturalState; + + // + // Constructor ... + X121XVWAPConditions() + { + Clean(); + } + + // + // Tools ... + + /** + * Cleaning Up ... + */ + void Clean() + { + // + // Commons ... + symbol = NULL; + period = NULL; + time = NULL; + + // + // Buffers ... + + // + Clean(vwapFastBuffer); + Clean(vwapMidBuffer); + Clean(vwapSlowBuffer); + Clean(vwapVolumeBuffer); + Clean(vwapPriceBuffer); + Clean(vwapFastStateBuffer); + Clean(vwapMidStateBuffer); + Clean(vwapSlowStateBuffer); + + // + ArraySetAsSeries(vwapFastBuffer, true); + ArraySetAsSeries(vwapMidBuffer, true); + ArraySetAsSeries(vwapSlowBuffer, true); + ArraySetAsSeries(vwapVolumeBuffer, true); + ArraySetAsSeries(vwapPriceBuffer, true); + ArraySetAsSeries(vwapFastStateBuffer, true); + ArraySetAsSeries(vwapMidStateBuffer, true); + ArraySetAsSeries(vwapSlowStateBuffer, true); + + // + // Conditions ... + + // + isVWapFastBullish = false; + isVWapFastBearish = false; + isVWapFastNeutural = false; + + // + isVWapMidBullish = false; + isVWapMidBearish = false; + isVWapMidNeutural = false; + + // + isVWapSlowBullish = false; + isVWapSlowBearish = false; + isVWapSlowNeutural = false; + + // + isVWapFastOverMid = false; + isVWapMidOverSlow = false; + + // + isVWapFastUnderMid = false; + isVWapMidUnderSlow = false; + + // + isVWapBullishState = false; + isVWapBearishState = false; + isVWapNeuturalState = false; + + // + isVWapBullishOrdered = false; + isVWapBearishOrdered = false; + + // + isVWapSwitchedToBullishOrdered = false; + isVWapSwitchedToBearishOrdered = false; + + // + isVWapSwitchedToBullishState = false; + isVWapSwitchedToBearishState = false; + isVWapSwitchedToNeuturalState = false; + + // + ZeroMemory(this); + } + + /** + * Generate Conditions Scores ... + * + * @param bullishScore: Double, Directional Scores Reference ... + * @param bearishScore: Double, Directional Scores Reference ... + */ + void GenerateScore( + double &bullishScore, + double &bearishScore // + ) + { + // + bullishScore = 0; + bearishScore = 0; + // + double score = 1; + double minScore = 0.5; + double highScore = 1.5; + + // + if (isVWapBullishState) + { + bullishScore += score; + } + if (isVWapBullishOrdered) + { + bullishScore += score; + } + if (isVWapSwitchedToBullishState) + { + bullishScore += highScore; + } + if (isVWapSwitchedToBullishOrdered) + { + bullishScore += highScore; + } + if (!isVWapBullishState && + !isVWapSwitchedToBullishState) + { + // + if (isVWapFastBullish) + { + bullishScore += minScore; + } + if (isVWapSlowBullish) + { + bullishScore += minScore; + } + } + if (!isVWapBullishOrdered && + !isVWapSwitchedToBullishOrdered) + { + // + if (isVWapFastOverMid) + { + bullishScore += minScore; + } + if (isVWapMidOverSlow) + { + bullishScore += minScore; + } + } + + // + if (isVWapBearishState) + { + bearishScore += score; + } + if (isVWapBearishOrdered) + { + bearishScore += score; + } + if (isVWapSwitchedToBearishState) + { + bearishScore += highScore; + } + if (isVWapSwitchedToBearishOrdered) + { + bearishScore += highScore; + } + if (!isVWapBearishState && + !isVWapSwitchedToBearishState) + { + // + if (isVWapFastBearish) + { + bearishScore += minScore; + } + if (isVWapSlowBearish) + { + bearishScore += minScore; + } + } + if (!isVWapBearishOrdered && + !isVWapSwitchedToBearishOrdered) + { + // + if (isVWapFastUnderMid) + { + bearishScore += minScore; + } + if (isVWapMidUnderSlow) + { + bearishScore += minScore; + } + } + } + + /** + * Generate Summary String for Represent Conditions State ... + * + * @param onlyCommons: Boolean, Just Generate Only Commons Conditions ... + * @param onlyConditions: Boolean, Just Generate Only Conditions ... + * @param includeScores: Boolean, Attach Scores Representations on Result ... + * @param ignoreFalseConditions: Boolean, Ignore False Conditions on Result ... + * @param separator: String, Separate Lines ... + * + * @return ( string ) + */ + string GenerateSummary( + bool onlyCommons = false, + bool onlyConditions = false, + bool includeScores = true, + bool ignoreFalseConditions = true, + string separator = "\n" // + ) + { + // + string result = NULL; + + // + double bullishScore = 0; + double bearishScore = 0; + GenerateScore( + bullishScore, + bearishScore // + ); + + // + string scoresStr = + // + "Scores: " + separator + + "---------------" + separator + + "Bullish: " + ToString(bullishScore) + separator + + "Bearish: " + ToString(bearishScore) + separator + + "" + // + ; + + // + string commonStr = GenerateSpecifiedCommonSummary( + this, + separator, + includeScores // + ); + + // + string conditionsStr = + // + "-----------------------" + separator + + "XVWAP: " + separator + + "-----------------------" + separator + + ToString("isVWapFastBullish", isVWapFastBullish, ignoreFalseConditions, separator) + + ToString("isVWapFastBearish", isVWapFastBearish, ignoreFalseConditions, separator) + + ToString("isVWapFastNeutural", isVWapFastNeutural, ignoreFalseConditions, separator) + + ToString("isVWapMidBullish", isVWapMidBullish, ignoreFalseConditions, separator) + + ToString("isVWapMidBearish", isVWapMidBearish, ignoreFalseConditions, separator) + + ToString("isVWapMidNeutural", isVWapMidNeutural, ignoreFalseConditions, separator) + + ToString("isVWapSlowBullish", isVWapSlowBullish, ignoreFalseConditions, separator) + + ToString("isVWapSlowBearish", isVWapSlowBearish, ignoreFalseConditions, separator) + + ToString("isVWapSlowNeutural", isVWapSlowNeutural, ignoreFalseConditions, separator) + + ToString("isVWapFastOverMid", isVWapFastOverMid, ignoreFalseConditions, separator) + + ToString("isVWapMidOverSlow", isVWapMidOverSlow, ignoreFalseConditions, separator) + + ToString("isVWapFastUnderMid", isVWapFastUnderMid, ignoreFalseConditions, separator) + + ToString("isVWapMidUnderSlow", isVWapMidUnderSlow, ignoreFalseConditions, separator) + + ToString("isVWapBullishState", isVWapBullishState, ignoreFalseConditions, separator) + + ToString("isVWapBearishState", isVWapBearishState, ignoreFalseConditions, separator) + + ToString("isVWapNeuturalState", isVWapNeuturalState, ignoreFalseConditions, separator) + + ToString("isVWapBullishOrdered", isVWapBullishOrdered, ignoreFalseConditions, separator) + + ToString("isVWapBearishOrdered", isVWapBearishOrdered, ignoreFalseConditions, separator) + + ToString("isVWapSwitchedToBullishOrdered", isVWapSwitchedToBullishOrdered, ignoreFalseConditions, separator) + + ToString("isVWapSwitchedToBearishOrdered", isVWapSwitchedToBearishOrdered, ignoreFalseConditions, separator) + + ToString("isVWapSwitchedToBullishState", isVWapSwitchedToBullishState, ignoreFalseConditions, separator) + + ToString("isVWapSwitchedToBearishState", isVWapSwitchedToBearishState, ignoreFalseConditions, separator) + + ToString("isVWapSwitchedToNeuturalState", isVWapSwitchedToNeuturalState, ignoreFalseConditions, separator) + + // + "" + // + ; + + // + result = + // + "[" + GetTag() + "]" + separator + + (onlyConditions + ? "" + : commonStr) + + (!includeScores + ? "" + : scoresStr) + + " " + separator + + (onlyCommons + ? "" + : conditionsStr) + + "" + // + ; + + // + return result; + } + + /** + * Retrieve nique Tag Identifier ... + * + * @return ( string ) + */ + string GetTag() + { + return GetTypeName(this); + } + + // +}; + +// +// Class ... +class XCX121XVWAPHelper : public XCBaseHelper +{ + // + // Public ... + public: + // + // Props ... + + // + // Constructors ... + XCX121XVWAPHelper() + : XCBaseHelper(_Symbol, _Period) + { + } + + // + // Deconstructor ... + ~XCX121XVWAPHelper() + { + // + mInputs.Clean(); + + // + Clean(vwapFastBuffer); + Clean(vwapMidBuffer); + Clean(vwapSlowBuffer); + Clean(vwapVolumeBuffer); + Clean(vwapPriceBuffer); + Clean(vwapFastStateBuffer); + Clean(vwapMidStateBuffer); + Clean(vwapSlowStateBuffer); + } + + // + // Tools ... + bool Init( + string symbol, // Trading Symbol + ENUM_TIMEFRAMES period, // Trading Period + X121XVWAPInputs &inputs // Inputs + ) + { + // + bool result = false; + + // + mSymbol = symbol; + mPeriod = period; + + // + result = inputs.IsValid(); + if (!result) + { + return result; + } + + // + ArraySetAsSeries(vwapFastBuffer, true); + ArraySetAsSeries(vwapMidBuffer, true); + ArraySetAsSeries(vwapSlowBuffer, true); + ArraySetAsSeries(vwapVolumeBuffer, true); + ArraySetAsSeries(vwapPriceBuffer, true); + ArraySetAsSeries(vwapFastStateBuffer, true); + ArraySetAsSeries(vwapMidStateBuffer, true); + ArraySetAsSeries(vwapSlowStateBuffer, true); + + // + mInputs = inputs; + + // + mHandler = iCustom( + mSymbol, + mPeriod, + "x-saherelm.x121.xvwap", + // + // Inputs ... + // + // Market ... + "", + mInputs.vwapFastLength, + mInputs.vwapMidLength, + mInputs.vwapSlowLength, + mInputs.vwapAppliedTo, + // + // Presentation ... + "", + // + mInputs.startCalculationForLastBars, + // + mInputs.showVWapFast, + mInputs.showVWapMedium, + mInputs.showVWapSlow + // + ); + result = mHandler != INVALID_HANDLE; + if (!result) + { + return result; + } + + // + return result; + } + + // + // Inputs ... + + // + X121XVWAPInputs GetInputs() + { + return mInputs; + } + + // + bool SetInputs( + X121XVWAPInputs &inputs // Configs + ) + { + // + return Init( + mSymbol, + mPeriod, + inputs + // + ); + } + + // + // Readers ... + + // + double GetVWapFast( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(vwapFastBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return vwapFastBuffer[barIndex]; + } + + // + int CopyVWapFast( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + vwapFastBuffer, + buffer, + forceClean + // + ); + } + + // + // STATE FAST ... + + // + double GetVWapFastState( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(vwapFastStateBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return vwapFastStateBuffer[barIndex]; + } + + // + int CopyVWapFastState( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + vwapFastStateBuffer, + buffer, + forceClean + // + ); + } + + // + // MID ... + + // + double GetVWapMid( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(vwapMidBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return vwapMidBuffer[barIndex]; + } + + // + int CopyVWapMid( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + vwapMidBuffer, + buffer, + forceClean + // + ); + } + + // + // STATE MID ... + + // + double GetVWapMidState( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(vwapMidStateBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return vwapMidStateBuffer[barIndex]; + } + + // + int CopyVWapMidState( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + vwapMidStateBuffer, + buffer, + forceClean + // + ); + } + + // + // SLOW ... + + // + double GetVWapSlowBuffer( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(vwapSlowBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return vwapSlowBuffer[barIndex]; + } + + // + int CopyVWapSlow( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + vwapSlowBuffer, + buffer, + forceClean + // + ); + } + + // + // STATE SLOW ... + + // + double GetVWapSlowState( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(vwapSlowStateBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return vwapSlowStateBuffer[barIndex]; + } + + // + int CopyVWapSlowState( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + vwapSlowStateBuffer, + buffer, + forceClean + // + ); + } + + // + // VOLUME ... + + // + double GetVWapVolume( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(vwapVolumeBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return vwapVolumeBuffer[barIndex]; + } + + // + int CopyVWapVolume( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + vwapVolumeBuffer, + buffer, + forceClean + // + ); + } + + // + // PRICE ... + + // + double GetVWapPrice( + int barIndex // Bar Index + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + Calculate(barIndex); + + // + int count = ArraySize(vwapPriceBuffer); + if (barIndex >= count) + { + barIndex = count - 1; + } + + // + return vwapPriceBuffer[barIndex]; + } + + // + int CopyVWapPrice( + int start, // Start + int count, // Number of Items for read + double &buffer[], // Dest Buffer + bool forceClean = true // Force To Clean buffer + ) + { + // + // Update Calculations ... + Calculate(start); + + // + // Copy Items ... + return Copy( + 0, + count, + vwapPriceBuffer, + buffer, + forceClean + // + ); + } + + // + // Converts to State ... + ENUM_XVWAP_STATES ToVWAPState(double value) + { + // + ENUM_XVWAP_STATES result = + value == 1 + ? XVWAP_STATE_BULLISH + : value == 2 + ? XVWAP_STATE_BEARISH + : XVWAP_STATE_NEUTURAL; + + // + return result; + } + + // + bool IsVWAPBullish(double value) + { + // + bool result = false; + + // + result = ToVWAPState(value) == XVWAP_STATE_BULLISH; + + // + return result; + } + + // + bool IsVWAPBearish(double value) + { + // + bool result = false; + + // + result = ToVWAPState(value) == XVWAP_STATE_BEARISH; + + // + return result; + } + + // + bool IsVWAPNeutural(double value) + { + // + bool result = false; + + // + result = ToVWAPState(value) == XVWAP_STATE_NEUTURAL; + + // + return result; + } + + // + void Free() override + { + Cleanup(10); + } + + // + bool GetConditions( + X121XVWAPConditions &conditions, // + int barIndex = 0, // + int loopback = 5 // + ) + { + // + bool result = true; + + // + if (loopback < 5) + { + loopback = 5; + } + + // + conditions.Clean(); + + // + conditions.symbol = mSymbol; + conditions.period = mPeriod; + conditions.time = TimeCurrent(); + + // + int zIndex = barIndex; + int cIndex = zIndex + 1; + int pIndex = cIndex + 1; + int ppIndex = pIndex + 1; + + // + XOHCL zBar; + result = zBar.Init( + mSymbol, + mPeriod, + zIndex // + ); + if (!result) + { + return result; + } + + // + XOHCL cBar; + result = cBar.Init( + mSymbol, + mPeriod, + cIndex // + ); + if (!result) + { + return result; + } + + // + XOHCL pBar; + result = pBar.Init( + mSymbol, + mPeriod, + pIndex // + ); + if (!result) + { + return result; + } + + // + // Buffers ... + + // + CopyVWapFast( + zIndex, + loopback, + conditions.vwapFastBuffer // + ); + + // + CopyVWapFastState( + zIndex, + loopback, + conditions.vwapFastStateBuffer // + ); + + // + CopyVWapMid( + zIndex, + loopback, + conditions.vwapMidBuffer // + ); + + // + CopyVWapMidState( + zIndex, + loopback, + conditions.vwapMidStateBuffer // + ); + + // + CopyVWapSlow( + zIndex, + loopback, + conditions.vwapSlowBuffer // + ); + + // + CopyVWapSlowState( + zIndex, + loopback, + conditions.vwapSlowStateBuffer // + ); + + // + CopyVWapVolume( + zIndex, + loopback, + conditions.vwapVolumeBuffer // + ); + + // + CopyVWapPrice( + zIndex, + loopback, + conditions.vwapPriceBuffer // + ); + + // + // Conditions ... + + // + int cIDX = 1; + int pIDX = cIDX + 1; + + // + // SAR ... + + // + bool isVWapFastBullish = IsVWAPBullish(conditions.vwapFastStateBuffer[cIDX]); + bool isVWapFastBullishPrev = IsVWAPBullish(conditions.vwapFastStateBuffer[pIDX]); + + // + bool isVWapFastBearish = IsVWAPBearish(conditions.vwapFastStateBuffer[cIDX]); + bool isVWapFastBearishPrev = IsVWAPBearish(conditions.vwapFastStateBuffer[pIDX]); + + // + bool isVWapFastNeutural = IsVWAPNeutural(conditions.vwapFastStateBuffer[cIDX]); + bool isVWapFastNeuturalPrev = IsVWAPNeutural(conditions.vwapFastStateBuffer[pIDX]); + + // + bool isVWapMidBullish = IsVWAPBullish(conditions.vwapMidStateBuffer[cIDX]); + bool isVWapMidBullishPrev = IsVWAPBullish(conditions.vwapMidStateBuffer[pIDX]); + + // + bool isVWapMidBearish = IsVWAPBearish(conditions.vwapMidStateBuffer[cIDX]); + bool isVWapMidBearishPrev = IsVWAPBearish(conditions.vwapMidStateBuffer[pIDX]); + + // + bool isVWapMidNeutural = IsVWAPNeutural(conditions.vwapMidStateBuffer[cIDX]); + bool isVWapMidNeuturalPrev = IsVWAPNeutural(conditions.vwapMidStateBuffer[pIDX]); + + // + bool isVWapSlowBullish = IsVWAPBullish(conditions.vwapSlowStateBuffer[cIDX]); + bool isVWapSlowBullishPrev = IsVWAPBullish(conditions.vwapSlowStateBuffer[pIDX]); + + // + bool isVWapSlowBearish = IsVWAPBearish(conditions.vwapSlowStateBuffer[cIDX]); + bool isVWapSlowBearishPrev = IsVWAPBearish(conditions.vwapSlowStateBuffer[pIDX]); + + // + bool isVWapSlowNeutural = IsVWAPNeutural(conditions.vwapSlowStateBuffer[cIDX]); + bool isVWapSlowNeuturalPrev = IsVWAPNeutural(conditions.vwapSlowStateBuffer[pIDX]); + + // + bool isVWapFastOverMid = conditions.vwapFastBuffer[cIDX] > conditions.vwapMidBuffer[cIDX]; + bool isVWapFastOverMidPrev = conditions.vwapFastBuffer[pIDX] > conditions.vwapMidBuffer[pIDX]; + + // + bool isVWapMidOverSlow = conditions.vwapMidBuffer[cIDX] > conditions.vwapSlowBuffer[cIDX]; + bool isVWapMidOverSlowPrev = conditions.vwapMidBuffer[pIDX] > conditions.vwapSlowBuffer[pIDX]; + + // + bool isVWapFastUnderMid = conditions.vwapFastBuffer[cIDX] < conditions.vwapMidBuffer[cIDX]; + bool isVWapFastUnderMidPrev = conditions.vwapFastBuffer[pIDX] < conditions.vwapMidBuffer[pIDX]; + + // + bool isVWapMidUnderSlow = conditions.vwapMidBuffer[cIDX] < conditions.vwapSlowBuffer[cIDX]; + bool isVWapMidUnderSlowPrev = conditions.vwapMidBuffer[pIDX] < conditions.vwapSlowBuffer[pIDX]; + + // + bool isVWapBullishState = isVWapFastBullish && + isVWapMidBullish && + isVWapSlowBullish; + bool isVWapBullishStatePrev = isVWapFastBullishPrev && + isVWapMidBullishPrev && + isVWapSlowBullishPrev; + + // + bool isVWapBearishState = isVWapFastBearish && + isVWapMidBearish && + isVWapSlowBearish; + bool isVWapBearishStatePrev = isVWapFastBearishPrev && + isVWapMidBearishPrev && + isVWapSlowBearishPrev; + + // + bool isVWapNeuturalState = isVWapFastNeutural && + isVWapMidNeutural && + isVWapSlowNeutural; + bool isVWapNeuturalStatePrev = isVWapFastNeuturalPrev && + isVWapMidNeuturalPrev && + isVWapSlowNeuturalPrev; + + // + bool isVWapBullishOrdered = isVWapFastOverMid && + isVWapMidOverSlow; + bool isVWapBullishOrderedPrev = isVWapFastOverMidPrev && + isVWapMidOverSlowPrev; + + // + bool isVWapBearishOrdered = isVWapFastUnderMid && + isVWapMidUnderSlow; + bool isVWapBearishOrderedPrev = isVWapFastUnderMidPrev && + isVWapMidUnderSlowPrev; + + // + bool isVWapSwitchedToBullishOrdered = isVWapBullishOrdered && + !isVWapBullishOrderedPrev; + bool isVWapSwitchedToBearishOrdered = isVWapBearishOrdered && + !isVWapBearishOrderedPrev; + + // + bool isVWapSwitchedToBullishState = isVWapBullishState && + !isVWapBullishStatePrev; + bool isVWapSwitchedToBearishState = isVWapBearishState && + !isVWapBearishStatePrev; + bool isVWapSwitchedToNeuturalState = isVWapNeuturalState && + !isVWapNeuturalStatePrev; + + // + conditions.isVWapFastBullish = isVWapFastBullish; + conditions.isVWapFastBearish = isVWapFastBearish; + conditions.isVWapFastNeutural = isVWapFastNeutural; + conditions.isVWapMidBullish = isVWapMidBullish; + conditions.isVWapMidBearish = isVWapMidBearish; + conditions.isVWapMidNeutural = isVWapMidNeutural; + conditions.isVWapSlowBullish = isVWapSlowBullish; + conditions.isVWapSlowBearish = isVWapSlowBearish; + conditions.isVWapSlowNeutural = isVWapSlowNeutural; + conditions.isVWapFastOverMid = isVWapFastOverMid; + conditions.isVWapMidOverSlow = isVWapMidOverSlow; + conditions.isVWapFastUnderMid = isVWapFastUnderMid; + conditions.isVWapMidUnderSlow = isVWapMidUnderSlow; + conditions.isVWapBullishState = isVWapBullishState; + conditions.isVWapBearishState = isVWapBearishState; + conditions.isVWapNeuturalState = isVWapNeuturalState; + conditions.isVWapBullishOrdered = isVWapBullishOrdered; + conditions.isVWapBearishOrdered = isVWapBearishOrdered; + conditions.isVWapSwitchedToBullishOrdered = isVWapSwitchedToBullishOrdered; + conditions.isVWapSwitchedToBearishOrdered = isVWapSwitchedToBearishOrdered; + conditions.isVWapSwitchedToBullishState = isVWapSwitchedToBullishState; + conditions.isVWapSwitchedToBearishState = isVWapSwitchedToBearishState; + conditions.isVWapSwitchedToNeuturalState = isVWapSwitchedToNeuturalState; + + // + Cleanup(); + + // + zBar.Clean(); + cBar.Clean(); + pBar.Clean(); + + // + return result; + } + + // + // Protected ... + protected: + // + // Private ... + private: + // + // Props ... + X121XVWAPInputs mInputs; // Inputs ... + + // + // Buffers ... + double vwapFastBuffer[]; + double vwapMidBuffer[]; + double vwapSlowBuffer[]; + double vwapVolumeBuffer[]; + double vwapPriceBuffer[]; + double vwapFastStateBuffer[]; + double vwapMidStateBuffer[]; + double vwapSlowStateBuffer[]; + + // + void Calculate( + int barIndex = 0, + int maxRequiredBars = 100 // + ) + { + // + // Buffers ... + if (barIndex < 0) + { + barIndex = 0; + } + + // + // FAST ... + CopyBuffer( + mHandler, + X121_XVWAP_FAST_LINE, + barIndex, + maxRequiredBars, + vwapFastBuffer + // + ); + + // + // FAST STATE ... + CopyBuffer( + mHandler, + X121_XVWAP_FAST_STATE_LINE, + barIndex, + maxRequiredBars, + vwapFastStateBuffer + // + ); + + // + // MID ... + CopyBuffer( + mHandler, + X121_XVWAP_MID_LINE, + barIndex, + maxRequiredBars, + vwapMidBuffer + // + ); + + // + // MID STATE ... + CopyBuffer( + mHandler, + X121_XVWAP_MID_STATE_LINE, + barIndex, + maxRequiredBars, + vwapMidStateBuffer + // + ); + + // + // SLOW ... + CopyBuffer( + mHandler, + X121_XVWAP_SLOW_LINE, + barIndex, + maxRequiredBars, + vwapSlowBuffer + // + ); + + // + // SLOW STATE ... + CopyBuffer( + mHandler, + X121_XVWAP_SLOW_STATE_LINE, + barIndex, + maxRequiredBars, + vwapSlowStateBuffer + // + ); + + // + // VOLUME ... + CopyBuffer( + mHandler, + X121_XVWAP_VOLUME_LINE, + barIndex, + maxRequiredBars, + vwapVolumeBuffer + // + ); + + // + // PRICE ... + CopyBuffer( + mHandler, + X121_XVWAP_PRICE_LINE, + barIndex, + maxRequiredBars, + vwapPriceBuffer + // + ); + } + + // + void Cleanup( + int maxAllowed = 100 // + ) + { + // + CleanupArray( + vwapFastBuffer, + maxAllowed // + ); + + // + CleanupArray( + vwapMidBuffer, + maxAllowed // + ); + + // + CleanupArray( + vwapSlowBuffer, + maxAllowed // + ); + + // + CleanupArray( + vwapVolumeBuffer, + maxAllowed // + ); + + // + CleanupArray( + vwapPriceBuffer, + maxAllowed // + ); + + // + CleanupArray( + vwapFastStateBuffer, + maxAllowed // + ); + + // + CleanupArray( + vwapMidStateBuffer, + maxAllowed // + ); + + // + CleanupArray( + vwapSlowStateBuffer, + maxAllowed // + ); + + // + } + + // +}; + +// +// Tools ... \ No newline at end of file diff --git a/BKPS/14040203/Indicators/x-saherelm.x121.x3ma.mq5 b/BKPS/14040203/Indicators/x-saherelm.x121.x3ma.mq5 new file mode 100644 index 0000000..7950817 --- /dev/null +++ b/BKPS/14040203/Indicators/x-saherelm.x121.x3ma.mq5 @@ -0,0 +1,659 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Indicator +// ------------------------------------------------- +// Name: X121 XWZ +// Description: XWZ ... +// +// +// 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 XWZ Indicator" +#property strict + +// +// Definitions ... + +// +#define ShortName "X121_X3MA" + +// +// Imports ... +#include "../Libraries/x-saherelm.common.lib.mq5" + +// +// Inputs ... + +// +// Market ... +input group "Market"; +input int fastMALength = 20; // Fast MA Length +input int midMALength = 50; // Mid MA Length +input int slowMALength = 200; // Slow MA Length +input ENUM_MA_METHOD maMethod = MODE_EMA; // MA Method +input ENUM_APPLIED_PRICE maAppliedTo = PRICE_CLOSE; // Applied To + +// +// Presentation ... +input group "Presentation"; + +// +input int startCalculationForLastBars = 1000; // Calculate Last n Bars +input bool showMaFast = true; // Show Fast MA +input bool showMaMid = true; // Show Mid MA +input bool showMaSlow = true; // Show Slow MA + +// +// Buffers ... + +// +#define hideColorIDX 0 +#define bullishColorIDX 1 +#define bearishColorIDX 2 +#define neuturalColorIDX 3 + +// +#property indicator_chart_window + +// +#property indicator_buffers 9 +#property indicator_plots 3 + +// +// Plot Buffers ... + +// +// FAST ... +#define maFastBufferIndex 0 +double maFastBuffer[]; + +#define maFastColorBufferIndex 1 +double maFastColorBuffer[]; + +// +#define maFastPlotBufferIndex 0 +#property indicator_label1 "X121 MAF" +#property indicator_type1 DRAW_COLOR_LINE +#property indicator_color1 CLR_NONE, clrAqua, clrMagenta, clrGray +#property indicator_style1 STYLE_SOLID +#property indicator_width1 2 + +// +// MID ... +#define maMidBufferIndex 2 +double maMidBuffer[]; + +#define maMidColorBufferIndex 3 +double maMidColorBuffer[]; + +// +#define maMidPlotBufferIndex 1 +#property indicator_label2 "X121 MAM" +#property indicator_type2 DRAW_COLOR_LINE +#property indicator_color2 CLR_NONE, clrGreen, clrRed, clrGray +#property indicator_style2 STYLE_SOLID +#property indicator_width2 2 + +// +// SLOW ... +#define maSlowBufferIndex 4 +double maSlowBuffer[]; + +#define maSlowColorBufferIndex 5 +double maSlowColorBuffer[]; + +// +#define maSlowPlotBufferIndex 2 +#property indicator_label3 "X121 MAS" +#property indicator_type3 DRAW_COLOR_LINE +#property indicator_color3 CLR_NONE, clrSteelBlue, clrDarkRed, clrGray +#property indicator_style3 STYLE_SOLID +#property indicator_width3 2 + +// +// Data Buffers ... + +// +int mLastBufferIndex = 5; + +// +// Fast State ... +#define maFastStateBufferIndex mLastBufferIndex + 1 +double maFastStateBuffer[]; + +// +// Mid State ... +#define maMidStateBufferIndex mLastBufferIndex + 2 +double maMidStateBuffer[]; + +// +// Slow State ... +#define maSlowStateBufferIndex mLastBufferIndex + 3 +double maSlowStateBuffer[]; + +// +// Variables, Properties and etc ... + +// +// this counts Available Bars ... +int limit; + +// +int maxLength; + +// +int maFastHandler = INVALID_HANDLE; +int maMidHandler = INVALID_HANDLE; +int maSlowHandler = INVALID_HANDLE; + +// +// Event Handlers ... + +/** + * Initialize Indicator ... + * + * @return ( int ) + */ +int OnInit() +{ + // + // Validate Inputs ... + if (!ValidateInputs()) + { + return INIT_PARAMETERS_INCORRECT; + } + + // + // Initialize Indicator Handlers ... + + // + // Fast MA ... + maFastHandler = iMA( + _Symbol, + _Period, + fastMALength, + 0, + maMethod, + maAppliedTo // + ); + bool isInited = maFastHandler != INVALID_HANDLE; + if (!isInited) + { + return INIT_FAILED; + } + + // + // Mid MA ... + maMidHandler = iMA( + _Symbol, + _Period, + midMALength, + 0, + maMethod, + maAppliedTo // + ); + isInited = maMidHandler != INVALID_HANDLE; + if (!isInited) + { + return INIT_FAILED; + } + + // + // Slow MA ... + maSlowHandler = iMA( + _Symbol, + _Period, + slowMALength, + 0, + maMethod, + maAppliedTo // + ); + isInited = maSlowHandler != INVALID_HANDLE; + if (!isInited) + { + return INIT_FAILED; + } + + // + // because in some cases we may have more than one input for + // calculation and we must prevent any calculation + // untill we pass the biggest input length, here we get max Input length + // and then wait until pass it ... + maxLength = ExtractMaxLengthOfInputs(); + + // + // Define Index Buffers ... + DefineBuffers(); + + // + // Set Indicator ShortName ... + SetIndicatorName(); + IndicatorSetInteger(INDICATOR_DIGITS, 2); + + // + // Init Succeed ... + return INIT_SUCCEEDED; +} + +/** + * De Initialize Indicator ... + * + * @param reason: Integer, De Initialization Reason ... + */ +void OnDeinit(const int reason) +{ + // + // REASON_PROGRAM 0 The EA has stopped working calling the ExpertRemove() function + // REASON_REMOVE 1 Program removed from a chart + // REASON_RECOMPILE 2 Program recompiled + // REASON_CHARTCHANGE 3 A symbol or a chart period is changed + // REASON_CHARTCLOSE 4 Chart closed + // REASON_PARAMETERS 5 Inputs changed by a user + // REASON_ACCOUNT 6 Another account has been activated or reconnection to the trade server has occurred due to changes in the account settings + // REASON_TEMPLATE 7 Another chart template applied + // REASON_INITFAILED 8 The OnInit() handler returned a non-zero value + // REASON_CLOSE 9 Terminal closed + + // + IndicatorRelease(maFastHandler); + IndicatorRelease(maMidHandler); + IndicatorRelease(maSlowHandler); +} + +/** + * Calculate Bars ... + * + * @param rates_total: Integer, Total Bars on Chart ... + * @param prev_calculated: Integer, Total Calculated Bars on Charts ... + * @param time: DateTime Array, History of Open Time ... + * @param open: Double Array, History of Open Prices ... + * @param high: Double Array, History of High Prices ... + * @param low: Double Array, History of Low Prices ... + * @param close: Double Array, History of Close Prices ... + * @param tick_volume: Long, History of Tick Volumes on Bar ... + * @param volume: Long, History of Trade Volumes ... + * @param spread: Double, History of Spread Price ... + * + * @return ( int ) + */ +int OnCalculate( + const int rates_total, + const int prev_calculated, + const datetime &time[], + const double &open[], + const double &high[], + const double &low[], + const double &close[], + const long &tick_volume[], + const long &volume[], + const int &spread[] // +) +{ + // + // Prepare Buffers ... + ArraySetAsSeries(time, true); + ArraySetAsSeries(open, true); + ArraySetAsSeries(high, true); + ArraySetAsSeries(low, true); + ArraySetAsSeries(close, true); + ArraySetAsSeries(tick_volume, true); + ArraySetAsSeries(volume, true); + ArraySetAsSeries(spread, true); + + // + // Validate Calculated Bars ... + + // + // Fast MA ... + int maFastCalculatedBars = BarsCalculated(maFastHandler); + + // + // Mid MA ... + int maMidCalculatedBars = BarsCalculated(maMidHandler); + + // + // Slow MA ... + int maSlowCalculatedBars = BarsCalculated(maSlowHandler); + + // + bool isPassedRequiredCalculatedBars = + // + // Fast MA ... + maFastCalculatedBars >= maxLength && + // + // Slow MA ... + maMidCalculatedBars >= maxLength && + // + // Slow MA ... + maSlowCalculatedBars >= maxLength + // + ; + if (!isPassedRequiredCalculatedBars) + { + return prev_calculated; + } + + // + limit = (prev_calculated > rates_total || prev_calculated <= 0) + ? rates_total + : (rates_total - prev_calculated) + 1; + + // + // Buffers Copy ... + + // + // Fast MA ... + int copiedFastMas = CopyBuffer(maFastHandler, 0, 0, limit, maFastBuffer); + + // + // Mid MA ... + int copiedMidMas = CopyBuffer(maMidHandler, 0, 0, limit, maMidBuffer); + + // + // Slow MA ... + int copiedSlowMas = CopyBuffer(maSlowHandler, 0, 0, limit, maSlowBuffer); + + // + // Validate Copied Items ... + bool isPassedRequiredCopiedItems = + // + // Fast MA ... + copiedFastMas > 0 && + // + // Mid MA ... + copiedMidMas > 0 && + // + // Slow MA ... + copiedSlowMas > 0 + // + ; + if (!isPassedRequiredCopiedItems) + { + return prev_calculated; + } + + // + // Main Loop ... + for (int i = limit - 1; i >= 0 && !IsStopped(); i--) + { + // + CalculateBuffers( + // + i, + prev_calculated, + rates_total, + // + open, + high, + close, + low, + tick_volume // + ); + } + + // + return rates_total; +} + +// +// Functions ... + +/** + * Validate Input Args for Initialization ... + * + * @return ( bool ) + */ +bool ValidateInputs() +{ + // + bool result = false; + + // + result = fastMALength > 0 && + midMALength > 0 && + slowMALength > 0 && + midMALength > fastMALength && + slowMALength > midMALength; + + // + return result; +} + +/** + * Extract Max Length of Inputs ... + * + * @return ( int ) + */ +int ExtractMaxLengthOfInputs() +{ + // + int result = 0; + + // + result = MathMax(fastMALength, midMALength); + result = MathMax(result, slowMALength); + + // + return result; +} + +/** + * Set Indicator Short Name and also we can define Buffers Labels ... + */ +void SetIndicatorName() +{ + IndicatorSetString(INDICATOR_SHORTNAME, ShortName); +} + +/** + * Define Required Buffers ... + */ +void DefineBuffers() +{ + // + // Plot Buffers ... + + // + // Fast ... + ArraySetAsSeries(maFastBuffer, true); + ArraySetAsSeries(maFastColorBuffer, true); + SetIndexBuffer(maFastBufferIndex, maFastBuffer, INDICATOR_DATA); + SetIndexBuffer(maFastColorBufferIndex, maFastColorBuffer, INDICATOR_COLOR_INDEX); + + // + // Mid ... + ArraySetAsSeries(maMidBuffer, true); + ArraySetAsSeries(maMidColorBuffer, true); + SetIndexBuffer(maMidBufferIndex, maMidBuffer, INDICATOR_DATA); + SetIndexBuffer(maMidColorBufferIndex, maMidColorBuffer, INDICATOR_COLOR_INDEX); + + // + // Slow ... + ArraySetAsSeries(maSlowBuffer, true); + ArraySetAsSeries(maSlowColorBuffer, true); + SetIndexBuffer(maSlowBufferIndex, maSlowBuffer, INDICATOR_DATA); + SetIndexBuffer(maSlowColorBufferIndex, maSlowColorBuffer, INDICATOR_COLOR_INDEX); + + // + // Data Buffers ... + + // + // Fast State ... + ArraySetAsSeries(maFastStateBuffer, true); + SetIndexBuffer(maFastStateBufferIndex, maFastStateBuffer, INDICATOR_CALCULATIONS); + + // + // Mid State ... + ArraySetAsSeries(maMidStateBuffer, true); + SetIndexBuffer(maMidStateBufferIndex, maMidStateBuffer, INDICATOR_CALCULATIONS); + + // + // Slow State ... + ArraySetAsSeries(maSlowStateBuffer, true); + SetIndexBuffer(maSlowStateBufferIndex, maSlowStateBuffer, INDICATOR_CALCULATIONS); +} + +/** + * Calculate Custom Buffers ... + * + * @param bar_index: Integer, Represent Current Bar ... + * @param prevCalculated: Integer, Represent Previous Calculated Bars ... + * @param ratesTotal: Integer, Represents All Available Bars ... + * @param open: Double Array, History of Open Prices ... + * @param high: Double Array, History of High Prices ... + * @param close: Double Array, History of Close Prices ... + * @param low: Double Array, History of Low Prices ... + * @param tickVolume: Long, History of Tick Volumes on Bar ... + */ +void CalculateBuffers( + int bar_index, // Selected Bar Index + const int prevCalculated, + const int ratesTotal, + const double &open[], + const double &high[], + const double &close[], + const double &low[], + const long &tickVolume[] // +) +{ + // + int barsLimit = startCalculationForLastBars > 0 + ? startCalculationForLastBars + : 0; + // + // bool canCalculate = true; + bool canCalculate = + barsLimit == 0 || + bar_index <= barsLimit; + if (canCalculate) + { + // + CalculateValues( + bar_index, + prevCalculated, + ratesTotal, + open, + high, + close, + low, + tickVolume // + ); + } + else + { + FillBuffersZero(bar_index); + } +} + +/** + * Fill All Bufers to Zero Vlue for Specified Bar Index ... + * + * @param barIndex: Integer ... + */ +void FillBuffersZero(int barIndex) +{ + // + maMidBuffer[barIndex] = 0; + maFastBuffer[barIndex] = 0; + maSlowBuffer[barIndex] = 0; + + // + maFastColorBuffer[barIndex] = hideColorIDX; + maMidColorBuffer[barIndex] = hideColorIDX; + maSlowColorBuffer[barIndex] = hideColorIDX; + maFastStateBuffer[barIndex] = hideColorIDX; + maMidStateBuffer[barIndex] = hideColorIDX; + maSlowStateBuffer[barIndex] = hideColorIDX; +} + +/** + * Calculate Vales ... + * + * @param bar_index: Integer, Represent Current Bar ... + * @param prevCalculated: Integer, Represent Previous Calculated Bars ... + * @param ratesTotal: Integer, Represents All Available Bars ... + * @param open: Double Array, History of Open Prices ... + * @param high: Double Array, History of High Prices ... + * @param close: Double Array, History of Close Prices ... + * @param low: Double Array, History of Low Prices ... + * @param tickVolume: Long, History of Tick Volumes on Bar ... + */ +void CalculateValues( + int bar_index, // Selected Bar Index + const int prevCalculated, + const int ratesTotal, + const double &open[], + const double &high[], + const double &close[], + const double &low[], + const long &tickVolume[] // +) +{ + // + // Implement Colorify Mechanism ... + + // + // Calculate Applied Price ... + ENUM_X_PRICE mPType = ToXPrice(maAppliedTo); + double iPrice = GetAppliedPrice( + mPType, + open, + high, + low, + close, + bar_index // + ); + + // + double iFast = maFastBuffer[bar_index]; + double iMid = maMidBuffer[bar_index]; + double iSlow = maSlowBuffer[bar_index]; + + // + double iFastState = iPrice > iFast + ? bullishColorIDX + : iPrice < iFast + ? bearishColorIDX + : neuturalColorIDX; + double iMidState = iPrice > iMid + ? bullishColorIDX + : iPrice < iMid + ? bearishColorIDX + : neuturalColorIDX; + double iSlowState = iPrice > iSlow + ? bullishColorIDX + : iPrice < iSlow + ? bearishColorIDX + : neuturalColorIDX; + + // + maFastColorBuffer[bar_index] = + showMaFast + ? iFastState + : hideColorIDX; + maFastStateBuffer[bar_index] = iFastState; + + // + maMidColorBuffer[bar_index] = + showMaMid + ? iMidState + : hideColorIDX; + maMidStateBuffer[bar_index] = iMidState; + + // + maSlowColorBuffer[bar_index] = + showMaSlow + ? iSlowState + : hideColorIDX; + maSlowStateBuffer[bar_index] = iSlowState; +} + +// diff --git a/BKPS/14040203/Indicators/x-saherelm.x121.xatr.mq5 b/BKPS/14040203/Indicators/x-saherelm.x121.xatr.mq5 new file mode 100644 index 0000000..08dbc82 --- /dev/null +++ b/BKPS/14040203/Indicators/x-saherelm.x121.xatr.mq5 @@ -0,0 +1,882 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Indicator +// ------------------------------------------------- +// Name: X121 XATR +// Description: XATR ... +// +// +// 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 XATR Indicator" +#property strict + +// +// Definitions ... + +// +#define ShortName "X121 XATR" + +// +// Includes Common Library ... +#include "../Libraries/x-saherelm.common.lib.mq5" + +// +// Inputs ... + +// +// Market ... +input group "Market"; + +// +input group "RSI Detection"; +input int rsiLength = 14; // Length +input ENUM_X_PRICE rsiPriceType = X_PRICE_CLOSE; // Applied To +input ENUM_X_MA_METHOD rsiSmoothingMethod = X_MA_MODE_SMA; // Smoothing Method; + +// +input group "ATR Detection"; +input int atrLength = 14; // Length +input double atrMultiplier = 1; // Multiplier +input ENUM_X_PRICE atrUpperPriceType = X_PRICE_HIGH; // Upper Zone Applied To +input ENUM_X_PRICE atrLowerPriceType = X_PRICE_LOW; // Lower Zone Applied To +input ENUM_X_MA_METHOD atrSmoothingMethod = X_MA_MODE_SMA; // Smoothing Method + +// +input group "Price Change"; +input int priceChangeSmoothingLength = 14; // Length +input ENUM_X_PRICE priceChangeType = X_PRICE_CLOSE; // Price Type +input ENUM_X_MA_METHOD priceChangeSmoothingMethod = X_MA_MODE_SMA; // Moving Average Moethod + +// +input group "Presentation"; + +// +input int startCalculationForLastBars = 1000; // Calculate Last n Bars + +// +input bool showAtrUpper = true; // Show Upper Zone +input bool showAtrLower = true; // Show Lower Zone +input bool showSmoothedAtrUpper = true; // Show Smoothed Upper Zone +input bool showSmoothedAtrLower = true; // Show Smoothed Lower Zone +input bool showRSIChange = true; // Show RSI Change +input bool showSmoothedRSIChange = true; // ShowSmoothed RSI Change +input bool showPriceChange = true; // Show Price Change +input bool showSmoothedPriceChange = true; // ShowSmoothed Price Change + +// +// Buffers ... + +// +#define hideColorIDX 0 +#define bullishColorIDX 1 +#define bearishColorIDX 2 +#define neuturalColorIDX 3 + +// +#property indicator_chart_window + +// +#property indicator_buffers 10 +#property indicator_plots 8 + +// +// ATR ... + +// +// Upper ... + +// +#define atrUpperBufferIndex 0 +double atrUpperBuffer[]; + +#property indicator_label1 "X121 ATRU" +#property indicator_type1 DRAW_LINE +#property indicator_color1 clrYellow +#property indicator_style1 STYLE_SOLID +#property indicator_width1 1 + +// +// Lower ... + +// +#define atrLowerBufferIndex 1 +double atrLowerBuffer[]; + +#property indicator_label2 "X121 ATRL" +#property indicator_type2 DRAW_LINE +#property indicator_color2 clrYellow +#property indicator_style2 STYLE_SOLID +#property indicator_width2 1 + +// +// ATR Smoothed ... + +// +// Upper ... + +// +#define atrSmoothedUpperBufferIndex 2 +double atrSmoothedUpperBuffer[]; + +#property indicator_label3 "X121 ATRUSM" +#property indicator_type3 DRAW_LINE +#property indicator_color3 clrYellow +#property indicator_style3 STYLE_DASH +#property indicator_width3 1 + +// +// Lower ... + +// +#define atrSmoothedLowerBufferIndex 3 +double atrSmoothedLowerBuffer[]; + +#property indicator_label4 "X121 ATRLSM" +#property indicator_type4 DRAW_LINE +#property indicator_color4 clrYellow +#property indicator_style4 STYLE_DASH +#property indicator_width4 1 + +// +// Price Change ... + +// +#define priceChangeBufferIndex 4 +double priceChangeBuffer[]; + +#property indicator_label5 "X121 PCH" +#property indicator_type5 DRAW_LINE +#property indicator_color5 clrOrchid +#property indicator_style5 STYLE_SOLID +#property indicator_width5 1 + +// +// Price Change Smoothed ... + +// +#define priceChangeSmoothedBufferIndex 5 +double priceChangeSmoothedBuffer[]; + +#property indicator_label6 "X121 PCHSM" +#property indicator_type6 DRAW_LINE +#property indicator_color6 clrOrchid +#property indicator_style6 STYLE_SOLID +#property indicator_width6 1 + +// +// RSI Change ... + +// +#define rsiChangeBufferIndex 6 +double rsiChangeBuffer[]; + +#property indicator_label7 "X121 RSICH" +#property indicator_type7 DRAW_LINE +#property indicator_color7 clrCornflowerBlue +#property indicator_style7 STYLE_SOLID +#property indicator_width7 1 + +// +// RSI Change Smoothed ... + +// +#define rsiChangeSmoothedBufferIndex 7 +double rsiChangeSmoothedBuffer[]; + +#property indicator_label8 "X121 RSICHSM" +#property indicator_type8 DRAW_LINE +#property indicator_color8 clrCornflowerBlue +#property indicator_style8 STYLE_SOLID +#property indicator_width8 1 + +// +// Data Buffers ... + +// +int mLastBufferIndex = 7; + +// +// ATR ... + +#define atrBufferIndex mLastBufferIndex + 1 +double atrBuffer[]; + +// +// RSI ... +#define rsiBufferIndex mLastBufferIndex + 2 +double rsiBuffer[]; + +// +// Variables, Properties and etc ... + +// +// this counts Available Bars ... +int limit; + +// +int maxLength; + +// +// RSI Handler ... +int rsiHandler = INVALID_HANDLE; + +// +// ATR Handler ... +int atrHandler = INVALID_HANDLE; + +// +ENUM_APPLIED_PRICE rsiAppliedTo = ToAppliedPrice(rsiPriceType); + +// +// Event Handlers ... + +/** + * Initialize Indicator ... + * + * @return ( int ) + */ +int OnInit() +{ + // + // Validate Inputs ... + if (!ValidateInputs()) + { + return INIT_PARAMETERS_INCORRECT; + } + + // + // Initialize Indicator Handlers ... + + // + // RSI ... + rsiHandler = iRSI( + _Symbol, + _Period, + rsiLength, + rsiAppliedTo // + ); + bool isInited = rsiHandler != INVALID_HANDLE; + if (!isInited) + { + return INIT_FAILED; + } + + // + // ATR ... + atrHandler = iATR( + _Symbol, + _Period, + atrLength // + ); + isInited = atrHandler != INVALID_HANDLE; + if (!isInited) + { + return INIT_FAILED; + } + + // + // because in some cases we may have more than one input for + // calculation and we must prevent any calculation + // untill we pass the biggest input length, here we get max Input length + // and then wait until pass it ... + maxLength = ExtractMaxLengthOfInputs(); + + // + // Define Index Buffers ... + DefineBuffers(); + + // + // Set Indicator ShortName ... + SetIndicatorName(); + + // + // Init Succeed ... + return INIT_SUCCEEDED; +} + +/** + * De Initialize Indicator ... + * + * @param reason: Integer, De Initialization Reason ... + */ +void OnDeinit(const int reason) +{ + // + // REASON_PROGRAM 0 The EA has stopped working calling the ExpertRemove() function + // REASON_REMOVE 1 Program removed from a chart + // REASON_RECOMPILE 2 Program recompiled + // REASON_CHARTCHANGE 3 A symbol or a chart period is changed + // REASON_CHARTCLOSE 4 Chart closed + // REASON_PARAMETERS 5 Inputs changed by a user + // REASON_ACCOUNT 6 Another account has been activated or reconnection to the trade server has occurred due to changes in the account settings + // REASON_TEMPLATE 7 Another chart template applied + // REASON_INITFAILED 8 The OnInit() handler returned a non-zero value + // REASON_CLOSE 9 Terminal closed + + // + IndicatorRelease(rsiHandler); + IndicatorRelease(atrHandler); +} + +/** + * Calculate Bars ... + * + * @param rates_total: Integer, Total Bars on Chart ... + * @param prev_calculated: Integer, Total Calculated Bars on Charts ... + * @param time: DateTime Array, History of Open Time ... + * @param open: Double Array, History of Open Prices ... + * @param high: Double Array, History of High Prices ... + * @param low: Double Array, History of Low Prices ... + * @param close: Double Array, History of Close Prices ... + * @param tick_volume: Long, History of Tick Volumes on Bar ... + * @param volume: Long, History of Trade Volumes ... + * @param spread: Double, History of Spread Price ... + * + * @return ( int ) + */ +int OnCalculate( + const int rates_total, + const int prev_calculated, + const datetime &time[], + const double &open[], + const double &high[], + const double &low[], + const double &close[], + const long &tick_volume[], + const long &volume[], + const int &spread[] // +) +{ + // + // Prepare Buffers ... + ArraySetAsSeries(time, true); + ArraySetAsSeries(open, true); + ArraySetAsSeries(high, true); + ArraySetAsSeries(low, true); + ArraySetAsSeries(close, true); + ArraySetAsSeries(tick_volume, true); + ArraySetAsSeries(volume, true); + ArraySetAsSeries(spread, true); + + // + // Fill All Buffers by Zero ... + if (prev_calculated == 0) + { + } + + // + // Validate Calculated Bars ... + + // + // RSI ... + int rsiCalculatedBars = BarsCalculated(rsiHandler); + + // + // ATR ... + int atrCalculatedBars = BarsCalculated(atrHandler); + + // + bool isPassedRequiredCalculatedBars = + // + // RSI ... + rsiCalculatedBars >= maxLength && + // + // ATR ... + atrCalculatedBars >= maxLength + // + ; + if (!isPassedRequiredCalculatedBars) + { + return prev_calculated; + } + + // + limit = (prev_calculated > rates_total || prev_calculated <= 0) + ? rates_total + : (rates_total - prev_calculated) + 1; + + // + // Buffers Copy ... + + // + // RSI ... + int copiedRsis = CopyBuffer(rsiHandler, 0, 0, limit, rsiBuffer); + + // + // ATR ... + int copiedAtrs = CopyBuffer(atrHandler, 0, 0, limit, atrBuffer); + + // + // Validate Copied Items ... + bool isPassedRequiredCopiedItems = + // + // + // RSI ... + copiedRsis > 0 && + // + // ATR ... + copiedAtrs > 0 + // + ; + if (!isPassedRequiredCopiedItems) + { + return prev_calculated; + } + + // + // Main Loop ... + for (int i = limit - 1; i >= 0 && !IsStopped(); i--) + { + // + CalculateBuffers( + i, + prev_calculated, + rates_total, + // + open, + high, + close, + low, + tick_volume // + ); + } + + // + return rates_total; +} + +// +// Functions ... + +/** + * Validate Input Args for Initialization ... + * + * @return ( bool ) + */ +bool ValidateInputs() +{ + // + bool result = + // + // RSI ... + rsiLength > 0 && + // + // ATR ... + atrLength > 0 && + atrMultiplier > 0 && + // + priceChangeSmoothingLength > 0 && + // + IsValid(rsiPriceType) && + IsValid(priceChangeType) && + IsValid(atrUpperPriceType) && + IsValid(atrLowerPriceType) + // + ; + + // + return result; +} + +/** + * Extract Max Length of Inputs ... + * + * @return ( int ) + */ +int ExtractMaxLengthOfInputs() +{ + // + int result = 0; + + // + result = MathMax(rsiLength, atrLength); + result = MathMax(result, priceChangeSmoothingLength); + + // + return result; +} + +/** + * Define Required Buffers ... + */ +void DefineBuffers() +{ + // + // ATR ... + + // + // UPPER ... + ENUM_DRAW_TYPE atrUpperDrawType = showAtrUpper ? DRAW_LINE : DRAW_NONE; + ArraySetAsSeries(atrUpperBuffer, true); + SetIndexBuffer(atrUpperBufferIndex, atrUpperBuffer, INDICATOR_DATA); + PlotIndexSetDouble(atrUpperBufferIndex, PLOT_EMPTY_VALUE, EMPTY_VALUE); + PlotIndexSetInteger(atrUpperBufferIndex, PLOT_SHOW_DATA, showAtrUpper); + PlotIndexSetInteger(atrUpperBufferIndex, PLOT_DRAW_TYPE, atrUpperDrawType); + + // + // LOWER ... + ENUM_DRAW_TYPE atrLowerDrawType = showAtrLower ? DRAW_LINE : DRAW_NONE; + ArraySetAsSeries(atrLowerBuffer, true); + SetIndexBuffer(atrLowerBufferIndex, atrLowerBuffer, INDICATOR_DATA); + PlotIndexSetDouble(atrLowerBufferIndex, PLOT_EMPTY_VALUE, EMPTY_VALUE); + PlotIndexSetInteger(atrLowerBufferIndex, PLOT_SHOW_DATA, showAtrLower); + PlotIndexSetInteger(atrLowerBufferIndex, PLOT_DRAW_TYPE, atrLowerDrawType); + + // + // ATR Smoothed ... + + // + // UPPER ... + ENUM_DRAW_TYPE atrSmoothedUpperDrawType = showSmoothedAtrUpper ? DRAW_LINE : DRAW_NONE; + ArraySetAsSeries(atrSmoothedUpperBuffer, true); + SetIndexBuffer(atrSmoothedUpperBufferIndex, atrSmoothedUpperBuffer, INDICATOR_DATA); + PlotIndexSetDouble(atrSmoothedUpperBufferIndex, PLOT_EMPTY_VALUE, EMPTY_VALUE); + PlotIndexSetInteger(atrSmoothedUpperBufferIndex, PLOT_SHOW_DATA, showSmoothedAtrUpper); + PlotIndexSetInteger(atrSmoothedUpperBufferIndex, PLOT_DRAW_TYPE, atrSmoothedUpperDrawType); + + // + // LOWER ... + ENUM_DRAW_TYPE atrSmoothedLowerDrawType = showSmoothedAtrLower ? DRAW_LINE : DRAW_NONE; + ArraySetAsSeries(atrSmoothedLowerBuffer, true); + SetIndexBuffer(atrSmoothedLowerBufferIndex, atrSmoothedLowerBuffer, INDICATOR_DATA); + PlotIndexSetDouble(atrSmoothedLowerBufferIndex, PLOT_EMPTY_VALUE, EMPTY_VALUE); + PlotIndexSetInteger(atrSmoothedLowerBufferIndex, PLOT_SHOW_DATA, showSmoothedAtrLower); + PlotIndexSetInteger(atrSmoothedLowerBufferIndex, PLOT_DRAW_TYPE, atrSmoothedLowerDrawType); + + // + // PriceChange ... + ENUM_DRAW_TYPE priceChangeDrawType = showPriceChange ? DRAW_LINE : DRAW_NONE; + ArraySetAsSeries(priceChangeBuffer, true); + SetIndexBuffer(priceChangeBufferIndex, priceChangeBuffer, INDICATOR_DATA); + PlotIndexSetDouble(priceChangeBufferIndex, PLOT_EMPTY_VALUE, 0.0); + PlotIndexSetInteger(priceChangeBufferIndex, PLOT_SHOW_DATA, showPriceChange); + PlotIndexSetInteger(priceChangeBufferIndex, PLOT_DRAW_TYPE, priceChangeDrawType); + + // + // PriceChange Smoothed ... + ENUM_DRAW_TYPE priceChangeSmoothedaDrawType = showSmoothedPriceChange ? DRAW_LINE : DRAW_NONE; + ArraySetAsSeries(priceChangeSmoothedBuffer, true); + SetIndexBuffer(priceChangeSmoothedBufferIndex, priceChangeSmoothedBuffer, INDICATOR_DATA); + PlotIndexSetDouble(priceChangeSmoothedBufferIndex, PLOT_EMPTY_VALUE, 0.0); + PlotIndexSetInteger(priceChangeSmoothedBufferIndex, PLOT_SHOW_DATA, showSmoothedPriceChange); + PlotIndexSetInteger(priceChangeSmoothedBufferIndex, PLOT_DRAW_TYPE, priceChangeSmoothedaDrawType); + + // + // RSIChange ... + ENUM_DRAW_TYPE rsiChangeDrawType = showRSIChange ? DRAW_LINE : DRAW_NONE; + ArraySetAsSeries(rsiChangeBuffer, true); + SetIndexBuffer(rsiChangeBufferIndex, rsiChangeBuffer, INDICATOR_DATA); + PlotIndexSetDouble(rsiChangeBufferIndex, PLOT_EMPTY_VALUE, 0.0); + PlotIndexSetInteger(rsiChangeBufferIndex, PLOT_SHOW_DATA, showRSIChange); + PlotIndexSetInteger(rsiChangeBufferIndex, PLOT_DRAW_TYPE, rsiChangeDrawType); + + // + // RSIChangeMa ... + ENUM_DRAW_TYPE rsiChangeMaDrawType = showSmoothedRSIChange ? DRAW_LINE : DRAW_NONE; + ArraySetAsSeries(rsiChangeSmoothedBuffer, true); + SetIndexBuffer(rsiChangeSmoothedBufferIndex, rsiChangeSmoothedBuffer, INDICATOR_DATA); + PlotIndexSetDouble(rsiChangeSmoothedBufferIndex, PLOT_EMPTY_VALUE, 0.0); + PlotIndexSetInteger(rsiChangeSmoothedBufferIndex, PLOT_SHOW_DATA, showSmoothedRSIChange); + PlotIndexSetInteger(rsiChangeSmoothedBufferIndex, PLOT_DRAW_TYPE, rsiChangeMaDrawType); + + // + // Data Buffers ... + + // + // ATR ... + ArraySetAsSeries(atrBuffer, true); + SetIndexBuffer(atrBufferIndex, atrBuffer, INDICATOR_CALCULATIONS); + + // + // RSI ... + ArraySetAsSeries(rsiBuffer, true); + SetIndexBuffer(rsiBufferIndex, rsiBuffer, INDICATOR_CALCULATIONS); +} + +/** + * Set Indicator Short Name and also we can define Buffers Labels ... + */ +void SetIndicatorName() +{ + // + IndicatorSetString(INDICATOR_SHORTNAME, ShortName); + IndicatorSetInteger(INDICATOR_DIGITS, 2); +} + +/** + * Calculate Custom Buffers ... + * + * @param bar_index: Integer, Represent Current Bar ... + * @param prevCalculated: Integer, Represent Previous Calculated Bars ... + * @param ratesTotal: Integer, Represents All Available Bars ... + * @param open: Double Array, History of Open Prices ... + * @param high: Double Array, History of High Prices ... + * @param close: Double Array, History of Close Prices ... + * @param low: Double Array, History of Low Prices ... + * @param tickVolume: Long, History of Tick Volumes on Bar ... + */ +void CalculateBuffers( + int bar_index, // Selected Bar Index + const int prevCalculated, + const int ratesTotal, + const double &open[], + const double &high[], + const double &close[], + const double &low[], + const long &tickVolume[] // +) +{ + // + int barsLimit = startCalculationForLastBars > 0 + ? startCalculationForLastBars + : 0; + // + // bool canCalculate = true; + bool canCalculate = + barsLimit == 0 || + bar_index <= barsLimit; + if (canCalculate) + { + // + CalculateAtrZones( + bar_index, + prevCalculated, + ratesTotal, + open, + high, + close, + low // + ); + } + else + { + FillBuffersZero(bar_index); + } +} + +// +// Custom ... + +/** + * Fill All Bufers to Zero Vlue for Specified Bar Index ... + * + * @param barIndex: Integer ... + */ +void FillBuffersZero(int barIndex) +{ + // + rsiBuffer[barIndex] = 0; + atrBuffer[barIndex] = 0; + atrUpperBuffer[barIndex] = 0; + atrLowerBuffer[barIndex] = 0; + rsiChangeBuffer[barIndex] = 0; + priceChangeBuffer[barIndex] = 0; + atrSmoothedUpperBuffer[barIndex] = 0; + atrSmoothedLowerBuffer[barIndex] = 0; + rsiChangeSmoothedBuffer[barIndex] = 0; + priceChangeSmoothedBuffer[barIndex] = 0; +} + +/** + * Calculate ATR Zones ... + * + * @param bar_index: Integer, Represent Current Bar ... + * @param prevCalculated: Integer, Represent Previous Calculated Bars ... + * @param ratesTotal: Integer, Represents All Available Bars ... + * @param open: Double Array, History of Open Prices ... + * @param high: Double Array, History of High Prices ... + * @param close: Double Array, History of Close Prices ... + * @param low: Double Array, History of Low Prices ... + */ +void CalculateAtrZones( + 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 points = GetPoints(_Symbol); + + // + // ATR Calculations ... + double iAtr = atrBuffer[bar_index]; + double iMultiPliedAtr = iAtr * atrMultiplier; + + // + // Select Upper Price ... + double iUpperPrice = GetAppliedPrice( + atrUpperPriceType, + open, + high, + low, + close, + bar_index // + ); + + // + // Select Lower Price ... + double iLowerPrice = GetAppliedPrice( + atrLowerPriceType, + open, + high, + low, + close, + bar_index // + ); + + // + // Calculate Atrs ... + + // + double iAtrUpper = iUpperPrice + iMultiPliedAtr; + double iAtrLower = iLowerPrice - iMultiPliedAtr; + + // + atrUpperBuffer[bar_index] = iAtrUpper; + atrLowerBuffer[bar_index] = iAtrLower; + + // + bool canSmoothAtr = atrSmoothingMethod != X_MA_MODE_NONE; + if (canSmoothAtr) + { + // + // Upper ... + iMAOnBuffer( + ratesTotal, + prevCalculated, + bar_index, + atrLength, + atrUpperBuffer, + atrSmoothedUpperBuffer, + atrSmoothingMethod // + ); + + // + // Lower ... + iMAOnBuffer( + ratesTotal, + prevCalculated, + bar_index, + atrLength, + atrLowerBuffer, + atrSmoothedLowerBuffer, + atrSmoothingMethod // + ); + } + else + { + // + atrSmoothedUpperBuffer[bar_index] = iAtrUpper; + atrSmoothedLowerBuffer[bar_index] = iAtrLower; + } + + // + // RSI Change Calculations ... + + // + double iRsi = rsiBuffer[bar_index]; + double iRsiP = rsiBuffer[bar_index + 1]; + double iRsiPrice = GetAppliedPrice( + rsiPriceType, + open, + high, + low, + close, + bar_index // + ); + + // + double iRsiChanged = iRsi - iRsiP; + double iRsiPointsChanged = iRsiChanged / points; + + // + double iRChange = iRsiPrice + (iRsiChanged * points); + rsiChangeBuffer[bar_index] = iRChange; + + // + bool canSmoothRsi = rsiSmoothingMethod != X_MA_MODE_NONE; + if (canSmoothRsi) + { + // + // Upper ... + iMAOnBuffer( + ratesTotal, + prevCalculated, + bar_index, + atrLength, + rsiChangeBuffer, + rsiChangeSmoothedBuffer, + rsiSmoothingMethod // + ); + } + else + { + rsiChangeSmoothedBuffer[bar_index] = iRChange; + } + + // + // PRICE Change Calculation ... + + // + double iPChangePrice = GetAppliedPrice( + priceChangeType, + open, + high, + low, + close, + bar_index // + ); + double iPPChangePrice = GetAppliedPrice( + priceChangeType, + open, + high, + low, + close, + bar_index + 1 // + ); + + // + double iPriceChange = iPChangePrice - iPPChangePrice; + double iPricePointsChanged = iPriceChange / points; + double iVolatilityChange = iPriceChange / iAtr; + + // + double iPChange = iPChangePrice + (iPricePointsChanged * points); + priceChangeBuffer[bar_index] = iPChange; + + // + bool canSmoothPriceChange = priceChangeSmoothingMethod != X_MA_MODE_NONE; + if (canSmoothPriceChange) + { + // + // Upper ... + iMAOnBuffer( + ratesTotal, + prevCalculated, + bar_index, + atrLength, + priceChangeBuffer, + priceChangeSmoothedBuffer, + priceChangeSmoothingMethod // + ); + } + else + { + priceChangeSmoothedBuffer[bar_index] = iPChange; + } +} + +// \ No newline at end of file diff --git a/BKPS/14040203/Indicators/x-saherelm.x121.xca.mq5 b/BKPS/14040203/Indicators/x-saherelm.x121.xca.mq5 new file mode 100644 index 0000000..5b1b1e1 --- /dev/null +++ b/BKPS/14040203/Indicators/x-saherelm.x121.xca.mq5 @@ -0,0 +1,2079 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Indicator +// ------------------------------------------------- +// Name: X121 XCA +// Description: XCA ... +// +// +// 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 XCA Indicator" +#property strict + +// +// Definitions ... + +// +#define ShortName "X121 XCA" + +// +// Includes Common Library ... +#include "../Libraries/x-saherelm.common.lib.mq5" + +// +// Inputs ... + +// +input group "Market"; + +// +input group "Short"; +input ENUM_X_PERIOD_METHOD scMethod = X_PERIOD_AUTO; // How to Find Period +input ENUM_TIMEFRAMES scPeriod = NULL; // Time Period + +// +input group "Medium"; +input ENUM_X_PERIOD_METHOD mcMethod = X_PERIOD_AUTO; // How to Find Period +input ENUM_TIMEFRAMES mcPeriod = NULL; // Time Period + +// +input group "Long"; +input ENUM_X_PERIOD_METHOD lcMethod = X_PERIOD_AUTO; // How to Find Period +input ENUM_TIMEFRAMES lcPeriod = NULL; // Time Period + +// +input group "Hind"; +input ENUM_X_PERIOD_METHOD hcMethod = X_PERIOD_AUTO; // How to Find Period +input ENUM_TIMEFRAMES hcPeriod = NULL; // Time Period + +// +input group "Boundary Detection"; +input ENUM_SERIESMODE hhMode = MODE_HIGH; // Highest High Calculation Method +input ENUM_SERIESMODE llMode = MODE_LOW; // Lowest Low Calculation Method + +// +input group "Fibo Levels"; +input ENUM_X_FIBO_LEVELS fiboLevel1 = X_FIBO_LEVEL_236; // Fibo Level 1 +input ENUM_X_FIBO_LEVELS fiboLevel2 = X_FIBO_LEVEL_500; // Fibo Level 2 +input ENUM_X_FIBO_LEVELS fiboLevel3 = X_FIBO_LEVEL_764; // Fibo Level 3 + +// +input group "Sar Detection"; +input double sarStep = 0.02; // Step +input double sarMax = 0.2; // Maximum + +// +// KI ... +input group "KI"; +input int kiLength = 26; // KI Length + +// +input group "Swing Detection"; +input int swingLength = 5; // Length + +// +input group "Support and Resistance"; +input int supResSmoothingLength = 7; // Smoothing Length +input ENUM_X_MA_METHOD supResSmoothingMode = X_MA_MODE_SMA; // Smoothing Method + +// +// Presentation ... +input group "Presentation"; + +// +input int startCalculationForLastBars = 1000; // Calculate Last n Bars + +// +input bool showSar = true; // Show Sar +input bool showKI = true; // Show KI +input bool showTKI = true; // Show KI Trend +input bool showTrend = true; // Show Trend +input bool showSwings = true; // Show Swings +input bool showFiboLevel1 = true; // Show Fibo Level 1 +input bool showFiboLevel2 = true; // Show Fibo Level 2 +input bool showFiboLevel3 = true; // Show Fibo Level 3 +input bool showPeaksAndVales = true; // Show Peaks And Vales +input bool showPeakAndValeGolden = true; // Show Peak and Vale Golden +input bool showSupportAndResistance = true; // Show Support and Resistance +input bool showShortCycle = true; // Show Short Cycle +input bool showMediumCycle = true; // Show Medium Cycle +input bool showLongCycle = true; // Show Long Cycle +input bool showHindCycle = true; // Show Hind Cycle + +// +input int sarArrowCode = 159; // Parabolic Sar Arrow Code +input int peakArrowCode = 159; // Peaks Arrow Code +input int valeArrowCode = 159; // Vales Arrow Code +input int swingLowArrowCode = 225; // Swing Low Arrow Code +input int swingHighArrowCode = 226; // Swing High Arrow Code + +// +// Buffers ... + +// +#define hideColorIDX 0 +#define bullishColorIDX 1 +#define bearishColorIDX 2 +#define neuturalColorIDX 3 + +// +#define bullishState 1 +#define neuturalState 0 +#define bearishState -1 + +// +#define emptyValue 0.0 + +// +#property indicator_chart_window + +// +#property indicator_buffers 31 +#property indicator_plots 23 + +// +// Plot Buffers ... + +// +// SHORT ... + +// +#define sHHBufferIndex 0 +double sHHBuffer[]; + +// +#property indicator_label1 "SH" +#property indicator_type1 DRAW_LINE +#property indicator_color1 clrGray +#property indicator_style1 STYLE_DOT +#property indicator_width1 1 + +// +#define sLLBufferIndex 1 +double sLLBuffer[]; + +// +#property indicator_label2 "SL" +#property indicator_type2 DRAW_LINE +#property indicator_color2 clrGray +#property indicator_style2 STYLE_DOT +#property indicator_width2 1 + +// +// MEDIUM ... + +// +#define mHHBufferIndex 2 +double mHHBuffer[]; + +// +#property indicator_label3 "MH" +#property indicator_type3 DRAW_LINE +#property indicator_color3 clrIndigo +#property indicator_style3 STYLE_DOT +#property indicator_width3 1 + +// +#define mLLBufferIndex 3 +double mLLBuffer[]; + +// +#property indicator_label4 "ML" +#property indicator_type4 DRAW_LINE +#property indicator_color4 clrIndigo +#property indicator_style4 STYLE_DOT +#property indicator_width4 1 + +// +// LONG ... + +// +#define lHHBufferIndex 4 +double lHHBuffer[]; + +// +#property indicator_label5 "LH" +#property indicator_type5 DRAW_LINE +#property indicator_color5 clrGoldenrod +#property indicator_style5 STYLE_DOT +#property indicator_width5 1 + +// +#define lLLBufferIndex 5 +double lLLBuffer[]; + +// +#property indicator_label6 "LL" +#property indicator_type6 DRAW_LINE +#property indicator_color6 clrGoldenrod +#property indicator_style6 STYLE_DOT +#property indicator_width6 1 + +// +// HIND ... + +// +#define hHHBufferIndex 6 +double hHHBuffer[]; + +// +#property indicator_label7 "HH" +#property indicator_type7 DRAW_LINE +#property indicator_color7 clrBrown +#property indicator_style7 STYLE_DOT +#property indicator_width7 1 + +// +#define hLLBufferIndex 7 +double hLLBuffer[]; + +// +#property indicator_label8 "HL" +#property indicator_type8 DRAW_LINE +#property indicator_color8 clrBrown +#property indicator_style8 STYLE_DOT +#property indicator_width8 1 + +// +// SUPPORT ... + +// +#define supportBufferIndex 8 +double supportBuffer[]; + +// +#property indicator_label9 "SUPPORT" +#property indicator_type9 DRAW_LINE +#property indicator_color9 clrLime +#property indicator_style9 STYLE_SOLID +#property indicator_width9 1 + +// +// RESISTANCE ... + +// +#define resistanceBufferIndex 9 +double resistanceBuffer[]; + +// +#property indicator_label10 "RESISTANCE" +#property indicator_type10 DRAW_LINE +#property indicator_color10 clrRed +#property indicator_style10 STYLE_SOLID +#property indicator_width10 1 + +// +// PEAKS ... + +// +#define peakBufferIndex 10 +double peakBuffer[]; + +// +#property indicator_label11 "PEAK" +#property indicator_type11 DRAW_ARROW +#property indicator_color11 clrMagenta +#property indicator_width11 1 + +// +// PEAKS Golden ... + +// +#define peakGoldenBufferIndex 11 +double peakGoldenBuffer[]; + +// +#property indicator_label12 "PEAK Golden" +#property indicator_type12 DRAW_LINE +#property indicator_color12 clrMagenta +#property indicator_style2 STYLE_DOT +#property indicator_width12 1 + +// +// VALES ... + +// +#define valeBufferIndex 12 +double valeBuffer[]; + +// +#property indicator_label13 "VALE" +#property indicator_type13 DRAW_ARROW +#property indicator_color13 clrAqua +#property indicator_width13 1 + +// +// VALE Golden ... + +// +#define valeGoldenBufferIndex 13 +double valeGoldenBuffer[]; + +// +#property indicator_label14 "VALES Golden" +#property indicator_type14 DRAW_LINE +#property indicator_color14 clrAqua +#property indicator_style4 STYLE_DOT +#property indicator_width14 1 + +// +// FIBO Level 1 + +// +#define fiboLevel1BufferIndex 14 +double fiboLevel1Buffer[]; + +// +#property indicator_label15 "Fibo L1" +#property indicator_type15 DRAW_LINE +#property indicator_color15 clrGold +#property indicator_style15 STYLE_DOT +#property indicator_width15 1 + +// +// FIBO Level 2 + +// +#define fiboLevel2BufferIndex 15 +double fiboLevel2Buffer[]; + +// +#property indicator_label16 "Fibo L2" +#property indicator_type16 DRAW_LINE +#property indicator_color16 clrYellow +#property indicator_style16 STYLE_DASH +#property indicator_width16 1 + +// +// FIBO Level 3 + +// +#define fiboLevel3BufferIndex 16 +double fiboLevel3Buffer[]; + +// +#property indicator_label17 "Fibo L3" +#property indicator_type17 DRAW_LINE +#property indicator_color17 clrGold +#property indicator_style17 STYLE_DOT +#property indicator_width17 1 + +// +// SAR ... + +// +#define sarBufferIndex 17 +double sarBuffer[]; + +// +#property indicator_label18 "SAR" +#property indicator_type18 DRAW_ARROW +#property indicator_color18 clrYellow +#property indicator_width18 1 + +// +// TREND ... + +// +#define trendBufferIndex 18 +#define trendBufferPlotIndex 18 +double trendBuffer[]; + +// +#define trendColorBufferIndex 19 +double trendColorBuffer[]; + +// +#property indicator_label19 "TRND" +#property indicator_type19 DRAW_COLOR_LINE +#property indicator_color19 CLR_NONE, clrAqua, clrMagenta, clrGray +#property indicator_style19 STYLE_DASH +#property indicator_width19 2 + +// +// KI ... + +// +#define kiBufferIndex 20 +#define kiBufferPlotIndex 19 +double kiBuffer[]; + +// +#define kiColorBufferIndex 21 +double kiColorBuffer[]; + +// +#property indicator_label20 "KI" +#property indicator_type20 DRAW_COLOR_LINE +#property indicator_color20 CLR_NONE, clrGreen, clrRed, clrGray +#property indicator_style20 STYLE_DASHDOTDOT +#property indicator_width20 2 + +// +// SWING Low ... + +// +#define swingLowBufferIndex 22 +#define swingLowBufferPlotIndex 20 +double swingLowBuffer[]; + +// +#property indicator_label21 "SWL" +#property indicator_type21 DRAW_ARROW +#property indicator_color21 clrGreen +#property indicator_width21 1 + +// +// SWING High ... + +// +#define swingHighBufferIndex 23 +#define swingHighBufferPlotIndex 21 +double swingHighBuffer[]; + +// +#property indicator_label22 "SWH" +#property indicator_type22 DRAW_ARROW +#property indicator_color22 clrRed +#property indicator_width22 1 + +// +// TKI ... + +// +#define tkiBufferIndex 24 +#define tkiBufferPlotIndex 22 +double tkiBuffer[]; + +// +#define tkiColorBufferIndex 25 +double tkiColorBuffer[]; + +// +#property indicator_label23 "TKI" +#property indicator_type23 DRAW_COLOR_LINE +#property indicator_color23 CLR_NONE, clrGreen, clrRed, clrGray +#property indicator_style23 STYLE_DASHDOTDOT +#property indicator_width23 2 + +// +// Data Buffers ... + +#define mLastBufferIndex 25 + +// +#define trendStateBufferIndex mLastBufferIndex + 1 +double trendStateBuffer[]; + +// +#define kiStateBufferIndex mLastBufferIndex + 2 +double kiStateBuffer[]; + +// +#define tkiStateBufferIndex mLastBufferIndex + 3 +double tkiStateBuffer[]; + +// +#define supBufferIndex mLastBufferIndex + 4 +double supBuffer[]; + +// +#define resBufferIndex mLastBufferIndex + 5 +double resBuffer[]; + +// +// Variables, Properties and etc ... + +// +// this counts Available Bars ... +int limit; + +// +int maxLength; + +// +// SAR Handler ... +int sarHandler = INVALID_HANDLE; + +// +// TREND Handler ... +int tkiHandler = INVALID_HANDLE; +int trendHandler = INVALID_HANDLE; + +// +// XMarketCycle sc; +int mSCLength = 0; +ENUM_TIMEFRAMES mSCPeriod = NULL; + +// +// XMarketCycle mc; +int mMCLength = 0; +ENUM_TIMEFRAMES mMCPeriod = NULL; + +// +// XMarketCycle lc; +int mLCLength = 0; +ENUM_TIMEFRAMES mLCPeriod = NULL; + +// +// XMarketCycle hc; +int mHCLength = 0; +ENUM_TIMEFRAMES mHCPeriod = NULL; + +// +// Event Handlers ... + +/** + * Initialize Indicator ... + * + * @return ( int ) + */ +int OnInit() +{ + // + // Validate Inputs ... + if (!ValidateInputs()) + { + return INIT_PARAMETERS_INCORRECT; + } + + // + if (!InitMarketCycles()) + { + return INIT_PARAMETERS_INCORRECT; + } + + // + // Initialize Indicator Handlers ... + + // + // SAR ... + sarHandler = iSAR( + _Symbol, + _Period, + sarStep, + sarMax // + ); + bool isInited = sarHandler != INVALID_HANDLE; + if (!isInited) + { + return INIT_FAILED; + } + + // + // TKI ... + tkiHandler = iMA( + _Symbol, + _Period, + kiLength, + 0, + MODE_SMA, + PRICE_MEDIAN // + ); + isInited = tkiHandler != INVALID_HANDLE; + if (!isInited) + { + return INIT_FAILED; + } + + // + // TREND ... + trendHandler = iMA( + _Symbol, + _Period, + mHCLength, + 0, + MODE_EMA, + PRICE_CLOSE // + ); + isInited = trendHandler != INVALID_HANDLE; + if (!isInited) + { + return INIT_FAILED; + } + + // + // because in some cases we may have more than one input for + // calculation and we must prevent any calculation + // untill we pass the biggest input length, here we get max Input length + // and then wait until pass it ... + maxLength = ExtractMaxLengthOfInputs(); + + // + // Define Index Buffers ... + DefineBuffers(); + + // + // Set Indicator ShortName ... + SetIndicatorName(); + + // + // Init Succeed ... + return INIT_SUCCEEDED; +} + +/** + * De Initialize Indicator ... + * + * @param reason: Integer, De Initialization Reason ... + */ +void OnDeinit(const int reason) +{ + // + // REASON_PROGRAM 0 The EA has stopped working calling the ExpertRemove() function + // REASON_REMOVE 1 Program removed from a chart + // REASON_RECOMPILE 2 Program recompiled + // REASON_CHARTCHANGE 3 A symbol or a chart period is changed + // REASON_CHARTCLOSE 4 Chart closed + // REASON_PARAMETERS 5 Inputs changed by a user + // REASON_ACCOUNT 6 Another account has been activated or reconnection to the trade server has occurred due to changes in the account settings + // REASON_TEMPLATE 7 Another chart template applied + // REASON_INITFAILED 8 The OnInit() handler returned a non-zero value + // REASON_CLOSE 9 Terminal closed + + // + IndicatorRelease(sarHandler); + IndicatorRelease(trendHandler); +} + +/** + * Calculate Bars ... + * + * @param rates_total: Integer, Total Bars on Chart ... + * @param prev_calculated: Integer, Total Calculated Bars on Charts ... + * @param time: DateTime Array, History of Open Time ... + * @param open: Double Array, History of Open Prices ... + * @param high: Double Array, History of High Prices ... + * @param low: Double Array, History of Low Prices ... + * @param close: Double Array, History of Close Prices ... + * @param tick_volume: Long, History of Tick Volumes on Bar ... + * @param volume: Long, History of Trade Volumes ... + * @param spread: Double, History of Spread Price ... + * + * @return ( int ) + */ +int OnCalculate( + const int rates_total, + const int prev_calculated, + const datetime &time[], + const double &open[], + const double &high[], + const double &low[], + const double &close[], + const long &tick_volume[], + const long &volume[], + const int &spread[] // +) +{ + // + // Prepare Buffers ... + ArraySetAsSeries(time, true); + ArraySetAsSeries(open, true); + ArraySetAsSeries(high, true); + ArraySetAsSeries(low, true); + ArraySetAsSeries(close, true); + ArraySetAsSeries(tick_volume, true); + ArraySetAsSeries(volume, true); + ArraySetAsSeries(spread, true); + + // + // Validate Calculated Bars ... + + // + // SAR ... + int sarCalculatedBars = BarsCalculated(sarHandler); + + // + // TKI ... + int tkiCalculatedBars = BarsCalculated(tkiHandler); + + // + // TREND ... + int trendCalculatedBars = BarsCalculated(trendHandler); + + // + bool isPassedRequiredCalculatedBars = + // + // SAR ... + sarCalculatedBars >= maxLength && + // + // TKI ... + tkiCalculatedBars >= maxLength && + // + // TREND ... + trendCalculatedBars >= maxLength + // + ; + if (!isPassedRequiredCalculatedBars) + { + return prev_calculated; + } + + // + limit = (prev_calculated > rates_total || prev_calculated <= 0) + ? rates_total + : (rates_total - prev_calculated) + 1; + + // + // Buffers Copy ... + + // + // SAR ... + int copiedSars = CopyBuffer(sarHandler, 0, 0, limit, sarBuffer); + + // + // TKI ... + int copiedTKIs = CopyBuffer(tkiHandler, 0, 0, limit, tkiBuffer); + + // + // TREND ... + int copiedTrends = CopyBuffer(trendHandler, MAIN_LINE, 0, limit + 1, trendBuffer); + + // + // Validate Copied Items ... + bool isPassedRequiredCopiedItems = + // + // SAR ... + copiedSars >= limit && + // + // TKI ... + copiedTKIs >= limit && + // + // TREND ... + copiedTrends >= limit + // + ; + if (!isPassedRequiredCopiedItems) + { + return prev_calculated; + } + + // + // Main Loop ... + for (int i = limit - 1; i >= 0 && !IsStopped(); i--) + { + // + CalculateBuffers( + i, + prev_calculated, + rates_total, + // + open, + high, + close, + low, + tick_volume // + ); + } + + // + return rates_total; +} + +// +// Functions ... + +/** + * Validate Input Args for Initialization ... + * + * @return ( bool ) + */ +bool ValidateInputs() +{ + // + bool result = false; + + // + result = + // + // SAR ... + sarMax > 0 && + sarStep > 0 && + kiLength > 0 && + swingLength > 0 && + sarMax > sarStep && + // + // XCA ... + (IsValid(scMethod, scPeriod) && + IsValid(mcMethod, mcPeriod) && + IsValid(lcMethod, lcPeriod) && + IsValid(hcMethod, hcPeriod)) + // + ; + + // + return result; +} + +/** + * Extract Max Length of Inputs ... + * + * @return ( int ) + */ +int ExtractMaxLengthOfInputs() +{ + // + int result = 0; + + // + result = MathMax(kiLength, swingLength); + + // + return result; +} + +/** + * Define Required Buffers ... + */ +void DefineBuffers() +{ + // + // Plot Buffers ... + + // + // SHORT ... + + // + ENUM_DRAW_TYPE sDrawType = showShortCycle ? DRAW_LINE : DRAW_NONE; + + // + // HH ... + + // + ArraySetAsSeries(sHHBuffer, true); + SetIndexBuffer(sHHBufferIndex, sHHBuffer, INDICATOR_DATA); + + // + PlotIndexSetInteger(sHHBufferIndex, PLOT_SHOW_DATA, showShortCycle); + PlotIndexSetInteger(sHHBufferIndex, PLOT_DRAW_TYPE, sDrawType); + + // + PlotIndexSetDouble(sHHBufferIndex, PLOT_EMPTY_VALUE, emptyValue); + + // + // LL ... + + // + ArraySetAsSeries(sLLBuffer, true); + SetIndexBuffer(sLLBufferIndex, sLLBuffer, INDICATOR_DATA); + + // + PlotIndexSetInteger(sLLBufferIndex, PLOT_SHOW_DATA, showShortCycle); + PlotIndexSetInteger(sLLBufferIndex, PLOT_DRAW_TYPE, sDrawType); + + // + PlotIndexSetDouble(sLLBufferIndex, PLOT_EMPTY_VALUE, emptyValue); + + // + // MEDIUM ... + + // + ENUM_DRAW_TYPE mDrawType = showMediumCycle ? DRAW_LINE : DRAW_NONE; + + // + // HH ... + + // + ArraySetAsSeries(mHHBuffer, true); + SetIndexBuffer(mHHBufferIndex, mHHBuffer, INDICATOR_DATA); + + // + PlotIndexSetInteger(mHHBufferIndex, PLOT_SHOW_DATA, showMediumCycle); + PlotIndexSetInteger(mHHBufferIndex, PLOT_DRAW_TYPE, mDrawType); + + // + PlotIndexSetDouble(mHHBufferIndex, PLOT_EMPTY_VALUE, emptyValue); + + // + // LL ... + + // + ArraySetAsSeries(mLLBuffer, true); + SetIndexBuffer(mLLBufferIndex, mLLBuffer, INDICATOR_DATA); + + // + PlotIndexSetInteger(mLLBufferIndex, PLOT_SHOW_DATA, showMediumCycle); + PlotIndexSetInteger(mLLBufferIndex, PLOT_DRAW_TYPE, mDrawType); + + // + PlotIndexSetDouble(mLLBufferIndex, PLOT_EMPTY_VALUE, emptyValue); + + // + // LONG ... + + // + ENUM_DRAW_TYPE lDrawType = showLongCycle ? DRAW_LINE : DRAW_NONE; + + // + // HH ... + + // + ArraySetAsSeries(lHHBuffer, true); + SetIndexBuffer(lHHBufferIndex, lHHBuffer, INDICATOR_DATA); + + // + PlotIndexSetInteger(lHHBufferIndex, PLOT_SHOW_DATA, showLongCycle); + PlotIndexSetInteger(lHHBufferIndex, PLOT_DRAW_TYPE, lDrawType); + + // + PlotIndexSetDouble(lHHBufferIndex, PLOT_EMPTY_VALUE, emptyValue); + + // + // LL ... + + // + ArraySetAsSeries(lLLBuffer, true); + SetIndexBuffer(lLLBufferIndex, lLLBuffer, INDICATOR_DATA); + + // + PlotIndexSetInteger(lLLBufferIndex, PLOT_SHOW_DATA, showLongCycle); + PlotIndexSetInteger(lLLBufferIndex, PLOT_DRAW_TYPE, lDrawType); + + // + PlotIndexSetDouble(lLLBufferIndex, PLOT_EMPTY_VALUE, emptyValue); + + // + // HIND ... + + // + ENUM_DRAW_TYPE hDrawType = showHindCycle ? DRAW_LINE : DRAW_NONE; + + // + // HH ... + + // + ArraySetAsSeries(hHHBuffer, true); + SetIndexBuffer(hHHBufferIndex, hHHBuffer, INDICATOR_DATA); + + // + PlotIndexSetInteger(hHHBufferIndex, PLOT_SHOW_DATA, showHindCycle); + PlotIndexSetInteger(hHHBufferIndex, PLOT_DRAW_TYPE, hDrawType); + + // + PlotIndexSetDouble(hHHBufferIndex, PLOT_EMPTY_VALUE, emptyValue); + + // + // LL ... + + // + ArraySetAsSeries(hLLBuffer, true); + SetIndexBuffer(hLLBufferIndex, hLLBuffer, INDICATOR_DATA); + + // + PlotIndexSetInteger(hLLBufferIndex, PLOT_SHOW_DATA, showHindCycle); + PlotIndexSetInteger(hLLBufferIndex, PLOT_DRAW_TYPE, hDrawType); + + // + PlotIndexSetDouble(hLLBufferIndex, PLOT_EMPTY_VALUE, emptyValue); + + // + // SUPPORT / RESISTANCE ... + + // + ENUM_DRAW_TYPE supResDrawType = showSupportAndResistance ? DRAW_LINE : DRAW_NONE; + + // + // SUPPORT ... + + // + ArraySetAsSeries(supportBuffer, true); + SetIndexBuffer(supportBufferIndex, supportBuffer, INDICATOR_DATA); + + // + PlotIndexSetInteger(supportBufferIndex, PLOT_SHOW_DATA, showSupportAndResistance); + PlotIndexSetInteger(supportBufferIndex, PLOT_DRAW_TYPE, supResDrawType); + + // + PlotIndexSetDouble(supportBufferIndex, PLOT_EMPTY_VALUE, emptyValue); + + // + // RESISTANCE ... + + // + ArraySetAsSeries(resistanceBuffer, true); + SetIndexBuffer(resistanceBufferIndex, resistanceBuffer, INDICATOR_DATA); + + // + PlotIndexSetInteger(resistanceBufferIndex, PLOT_SHOW_DATA, showSupportAndResistance); + PlotIndexSetInteger(resistanceBufferIndex, PLOT_DRAW_TYPE, supResDrawType); + + // + PlotIndexSetDouble(resistanceBufferIndex, PLOT_EMPTY_VALUE, emptyValue); + + // + // PEAK / VALE ... + + // + ENUM_DRAW_TYPE pvDrawType = showPeaksAndVales ? DRAW_ARROW : DRAW_NONE; + + // + // PEAK ... + + // + ArraySetAsSeries(peakBuffer, true); + SetIndexBuffer(peakBufferIndex, peakBuffer, INDICATOR_DATA); + + // + PlotIndexSetInteger(peakBufferIndex, PLOT_SHOW_DATA, showPeaksAndVales); + PlotIndexSetInteger(peakBufferIndex, PLOT_DRAW_TYPE, pvDrawType); + + // + PlotIndexSetDouble(peakBufferIndex, PLOT_EMPTY_VALUE, emptyValue); + PlotIndexSetInteger(peakBufferIndex, PLOT_ARROW, peakArrowCode); + + // + // VALE ... + + // + ArraySetAsSeries(valeBuffer, true); + SetIndexBuffer(valeBufferIndex, valeBuffer, INDICATOR_DATA); + + // + PlotIndexSetInteger(valeBufferIndex, PLOT_SHOW_DATA, showPeaksAndVales); + PlotIndexSetInteger(valeBufferIndex, PLOT_DRAW_TYPE, pvDrawType); + + // + PlotIndexSetDouble(valeBufferIndex, PLOT_EMPTY_VALUE, emptyValue); + PlotIndexSetInteger(valeBufferIndex, PLOT_ARROW, valeArrowCode); + + // + // PV GOLDEN ... + + // + ENUM_DRAW_TYPE pvGoldenDrawType = showPeakAndValeGolden ? DRAW_LINE : DRAW_NONE; + + // + // PEAK Golden ... + + // + ArraySetAsSeries(peakGoldenBuffer, true); + SetIndexBuffer(peakGoldenBufferIndex, peakGoldenBuffer, INDICATOR_DATA); + + // + PlotIndexSetInteger(peakGoldenBufferIndex, PLOT_SHOW_DATA, showPeakAndValeGolden); + PlotIndexSetInteger(peakGoldenBufferIndex, PLOT_DRAW_TYPE, pvGoldenDrawType); + + // + PlotIndexSetDouble(peakGoldenBufferIndex, PLOT_EMPTY_VALUE, emptyValue); + + // + // VALE Golden ... + + // + ArraySetAsSeries(valeGoldenBuffer, true); + SetIndexBuffer(valeGoldenBufferIndex, valeGoldenBuffer, INDICATOR_DATA); + + // + PlotIndexSetInteger(valeGoldenBufferIndex, PLOT_SHOW_DATA, showPeakAndValeGolden); + PlotIndexSetInteger(valeGoldenBufferIndex, PLOT_DRAW_TYPE, pvGoldenDrawType); + + // + PlotIndexSetDouble(valeGoldenBufferIndex, PLOT_EMPTY_VALUE, emptyValue); + + // + // FIBO L1 ... + + // + ENUM_DRAW_TYPE fiboL1DrawType = showFiboLevel1 ? DRAW_LINE : DRAW_NONE; + + // + ArraySetAsSeries(fiboLevel1Buffer, true); + SetIndexBuffer(fiboLevel1BufferIndex, fiboLevel1Buffer, INDICATOR_DATA); + + // + PlotIndexSetInteger(fiboLevel1BufferIndex, PLOT_SHOW_DATA, showFiboLevel1); + PlotIndexSetInteger(fiboLevel1BufferIndex, PLOT_DRAW_TYPE, fiboL1DrawType); + + // + PlotIndexSetDouble(fiboLevel1BufferIndex, PLOT_EMPTY_VALUE, emptyValue); + + // + // FIBO L2 ... + + // + ENUM_DRAW_TYPE fiboL2DrawType = showFiboLevel2 ? DRAW_LINE : DRAW_NONE; + + // + ArraySetAsSeries(fiboLevel2Buffer, true); + SetIndexBuffer(fiboLevel2BufferIndex, fiboLevel2Buffer, INDICATOR_DATA); + + // + PlotIndexSetInteger(fiboLevel2BufferIndex, PLOT_SHOW_DATA, showFiboLevel2); + PlotIndexSetInteger(fiboLevel2BufferIndex, PLOT_DRAW_TYPE, fiboL2DrawType); + + // + PlotIndexSetDouble(fiboLevel2BufferIndex, PLOT_EMPTY_VALUE, emptyValue); + + // + // FIBO L3 ... + + // + ENUM_DRAW_TYPE fiboL3DrawType = showFiboLevel3 ? DRAW_LINE : DRAW_NONE; + + // + ArraySetAsSeries(fiboLevel3Buffer, true); + SetIndexBuffer(fiboLevel3BufferIndex, fiboLevel3Buffer, INDICATOR_DATA); + + // + PlotIndexSetInteger(fiboLevel3BufferIndex, PLOT_SHOW_DATA, showFiboLevel3); + PlotIndexSetInteger(fiboLevel3BufferIndex, PLOT_DRAW_TYPE, fiboL3DrawType); + + // + PlotIndexSetDouble(fiboLevel3BufferIndex, PLOT_EMPTY_VALUE, emptyValue); + + // + // SAR ... + + // + ENUM_DRAW_TYPE sarDrawType = showSar ? DRAW_ARROW : DRAW_NONE; + + // + ArraySetAsSeries(sarBuffer, true); + SetIndexBuffer(sarBufferIndex, sarBuffer, INDICATOR_DATA); + + // + PlotIndexSetInteger(sarBufferIndex, PLOT_SHOW_DATA, showSar); + PlotIndexSetInteger(sarBufferIndex, PLOT_DRAW_TYPE, sarDrawType); + + // + PlotIndexSetDouble(sarBufferIndex, PLOT_EMPTY_VALUE, emptyValue); + PlotIndexSetInteger(sarBufferIndex, PLOT_ARROW, sarArrowCode); + + // + // TREND ... + + // + ENUM_DRAW_TYPE trendDrawType = showTrend ? DRAW_COLOR_LINE : DRAW_NONE; + + // + ArraySetAsSeries(trendBuffer, true); + SetIndexBuffer(trendBufferIndex, trendBuffer, INDICATOR_DATA); + + // + PlotIndexSetInteger(trendBufferPlotIndex, PLOT_SHOW_DATA, showTrend); + // PlotIndexSetInteger(trendBufferPlotIndex, PLOT_DRAW_TYPE, trendDrawType); + + // + PlotIndexSetDouble(trendBufferPlotIndex, PLOT_EMPTY_VALUE, emptyValue); + + // + ArraySetAsSeries(trendColorBuffer, true); + SetIndexBuffer(trendColorBufferIndex, trendColorBuffer, INDICATOR_COLOR_INDEX); + + // + // KI ... + + // + ENUM_DRAW_TYPE kiDrawType = showKI ? DRAW_COLOR_LINE : DRAW_NONE; + + // + ArraySetAsSeries(kiBuffer, true); + SetIndexBuffer(kiBufferIndex, kiBuffer, INDICATOR_DATA); + + // + PlotIndexSetInteger(kiBufferPlotIndex, PLOT_SHOW_DATA, showKI); + // PlotIndexSetInteger(kiBufferPlotIndex, PLOT_DRAW_TYPE, kiDrawType); + + // + PlotIndexSetDouble(kiBufferPlotIndex, PLOT_EMPTY_VALUE, emptyValue); + + // + ArraySetAsSeries(kiColorBuffer, true); + SetIndexBuffer(kiColorBufferIndex, kiColorBuffer, INDICATOR_COLOR_INDEX); + + // + // TKI ... + + // + ENUM_DRAW_TYPE tkiDrawType = showTKI ? DRAW_COLOR_LINE : DRAW_NONE; + + // + ArraySetAsSeries(tkiBuffer, true); + SetIndexBuffer(tkiBufferIndex, tkiBuffer, INDICATOR_DATA); + + // + PlotIndexSetInteger(tkiBufferPlotIndex, PLOT_SHOW_DATA, showKI); + // PlotIndexSetInteger(tkiBufferPlotIndex, PLOT_DRAW_TYPE, kiDrawType); + + // + PlotIndexSetDouble(tkiBufferPlotIndex, PLOT_EMPTY_VALUE, emptyValue); + + // + ArraySetAsSeries(tkiColorBuffer, true); + SetIndexBuffer(tkiColorBufferIndex, tkiColorBuffer, INDICATOR_COLOR_INDEX); + + // + // SWINGS ... + + // + ENUM_DRAW_TYPE swingDrawType = showSwings ? DRAW_ARROW : DRAW_NONE; + + // + // SWING Low ... + + // + ArraySetAsSeries(swingLowBuffer, true); + SetIndexBuffer(swingLowBufferIndex, swingLowBuffer, INDICATOR_DATA); + + // + PlotIndexSetInteger(swingLowBufferPlotIndex, PLOT_SHOW_DATA, showSwings); + PlotIndexSetInteger(swingLowBufferPlotIndex, PLOT_DRAW_TYPE, swingDrawType); + + // + PlotIndexSetDouble(swingLowBufferPlotIndex, PLOT_EMPTY_VALUE, emptyValue); + PlotIndexSetInteger(swingLowBufferPlotIndex, PLOT_ARROW, swingLowArrowCode); + + // + // SWING High ... + + // + ArraySetAsSeries(swingHighBuffer, true); + SetIndexBuffer(swingHighBufferIndex, swingHighBuffer, INDICATOR_DATA); + + // + PlotIndexSetInteger(swingHighBufferPlotIndex, PLOT_SHOW_DATA, showSwings); + PlotIndexSetInteger(swingHighBufferPlotIndex, PLOT_DRAW_TYPE, swingDrawType); + + // + PlotIndexSetDouble(swingHighBufferPlotIndex, PLOT_EMPTY_VALUE, emptyValue); + PlotIndexSetInteger(swingHighBufferPlotIndex, PLOT_ARROW, swingHighArrowCode); + + // + // Data Buffers ... + + // + ArraySetAsSeries(trendStateBuffer, true); + SetIndexBuffer(trendStateBufferIndex, trendStateBuffer, INDICATOR_CALCULATIONS); + + // + ArraySetAsSeries(kiStateBuffer, true); + SetIndexBuffer(kiStateBufferIndex, kiStateBuffer, INDICATOR_CALCULATIONS); + + // + ArraySetAsSeries(supBuffer, true); + SetIndexBuffer(supBufferIndex, supBuffer, INDICATOR_CALCULATIONS); + + // + ArraySetAsSeries(resBuffer, true); + SetIndexBuffer(resBufferIndex, resBuffer, INDICATOR_CALCULATIONS); + + // + ArraySetAsSeries(tkiStateBuffer, true); + SetIndexBuffer(tkiStateBufferIndex, tkiStateBuffer, INDICATOR_CALCULATIONS); + + // +} + +/** + * Set Indicator Short Name and also we can define Buffers Labels ... + */ +void SetIndicatorName() +{ + // + IndicatorSetInteger(INDICATOR_DIGITS, _Digits); + IndicatorSetString(INDICATOR_SHORTNAME, ShortName); +} + +/** + * Calculate Custom Buffers ... + * + * @param bar_index: Integer, Represent Current Bar ... + * @param prevCalculated: Integer, Represent Previous Calculated Bars ... + * @param ratesTotal: Integer, Represents All Available Bars ... + * @param open: Double Array, History of Open Prices ... + * @param high: Double Array, History of High Prices ... + * @param close: Double Array, History of Close Prices ... + * @param low: Double Array, History of Low Prices ... + * @param tickVolume: Long, History of Tick Volumes on Bar ... + */ +void CalculateBuffers( + int bar_index, // Selected Bar Index + const int prevCalculated, + const int ratesTotal, + const double &open[], + const double &high[], + const double &close[], + const double &low[], + const long &tickVolume[] // +) +{ + // + int barsLimit = startCalculationForLastBars > 0 + ? startCalculationForLastBars + : 0; + // + // bool canCalculate = true; + bool canCalculate = + barsLimit == 0 || + bar_index <= barsLimit; + if (canCalculate) + { + // + // Calculate Cycles ... + CalculateCycles(bar_index); + + // + // Calculate Support nad Resistance ... + CalculateValues( + bar_index, + prevCalculated, + ratesTotal, + open, + high, + close, + low, + tickVolume // + ); + + // + int swingBarIndex = bar_index; + if (bar_index < swingLength) + { + swingBarIndex = bar_index + swingLength; + } + + // // + // // Calcultae Swing High and Low and Trends ... + // CalculateSwingsAndTrend( + // swingBarIndex, + // prevCalculated, + // ratesTotal, + // open, + // high, + // close, + // low, + // tickVolume // + // ); + + // + if (bar_index < swingLength) + { + // + // for (int i = bar_index; i < bar_index + swingLength; i++) + // { + // // + // trendBuffer[i] = lTrend; + // swingLowsBuffer[i] = lSwingLow; + // swingHighsBuffer[i] = lSwingHigh; + // trendStateBuffer[i] = lTrendState; + // trendColorBuffer[i] = lTrendColor; + // } + } + } + else + { + FillBuffersZero(bar_index); + } +} + +// +// Custom ... + +/** + * Initial Market Cycles ... + * + * @return ( bool ) + */ +bool InitMarketCycles() +{ + // + bool result = false; + + // + int cPeriodSeconds = PeriodSeconds(_Period); + + // + // Find Cycle Period ... + if (scMethod == X_PERIOD_AUTO) + { + // + // Select Period ... + mSCPeriod = GetCyclePeriod( + X_MARKET_CYCLE_SHORT, + _Period // + ); + } + else + { + mSCPeriod = scPeriod; + } + + // + if (IsValid(mSCPeriod)) + { + mSCLength = PeriodSeconds(mSCPeriod) / cPeriodSeconds; + } + + // + // Find Cycle Period ... + if (mcMethod == X_PERIOD_AUTO) + { + // + // Select Period ... + mMCPeriod = GetCyclePeriod( + X_MARKET_CYCLE_MEDIUM, + _Period // + ); + } + else + { + mMCPeriod = mcPeriod; + } + + // + if (IsValid(mMCPeriod)) + { + mMCLength = PeriodSeconds(mMCPeriod) / cPeriodSeconds; + } + + // + // Find Cycle Period ... + if (lcMethod == X_PERIOD_AUTO) + { + // + // Select Period ... + mLCPeriod = GetCyclePeriod( + X_MARKET_CYCLE_LONG, + _Period // + ); + } + else + { + mLCPeriod = lcPeriod; + } + + // + if (IsValid(mLCPeriod)) + { + mLCLength = PeriodSeconds(mLCPeriod) / cPeriodSeconds; + } + + // + // Find Cycle Period ... + if (hcMethod == X_PERIOD_AUTO) + { + // + // Select Period ... + mHCPeriod = GetCyclePeriod( + X_MARKET_CYCLE_HIND, + _Period // + ); + } + else + { + mHCPeriod = hcPeriod; + } + + // + if (IsValid(mHCPeriod)) + { + mHCLength = PeriodSeconds(mHCPeriod) / cPeriodSeconds; + } + + // + result = mSCLength > 0 && + mMCLength > mSCLength && + mLCLength > mMCLength && + mHCLength > mLCLength; + + // + return result; +} + +/** + * Fill All Bufers to Zero Vlue for Specified Bar Index ... + * + * @param barIndex: Integer ... + */ +void FillBuffersZero(int barIndex) +{ + // + // SHORT ... + sHHBuffer[barIndex] = emptyValue; + sLLBuffer[barIndex] = emptyValue; + + // + // MEDIUM ... + mHHBuffer[barIndex] = emptyValue; + mLLBuffer[barIndex] = emptyValue; + + // + // LONG ... + lHHBuffer[barIndex] = emptyValue; + lLLBuffer[barIndex] = emptyValue; + + // + // HIND ... + hHHBuffer[barIndex] = emptyValue; + hLLBuffer[barIndex] = emptyValue; + + // + // SUPPORT / RESISTANCE ... + supBuffer[barIndex] = emptyValue; + resBuffer[barIndex] = emptyValue; + supportBuffer[barIndex] = emptyValue; + resistanceBuffer[barIndex] = emptyValue; + + // + // PEAKS ... + peakBuffer[barIndex] = emptyValue; + peakGoldenBuffer[barIndex] = emptyValue; + + // + // VALES ... + valeBuffer[barIndex] = emptyValue; + valeGoldenBuffer[barIndex] = emptyValue; + + // + // SAR ... + sarBuffer[barIndex] = emptyValue; + + // + // TREND ... + trendBuffer[barIndex] = emptyValue; + trendColorBuffer[barIndex] = hideColorIDX; + trendStateBuffer[barIndex] = hideColorIDX; + + // + // KI ... + kiBuffer[barIndex] = emptyValue; + kiColorBuffer[barIndex] = hideColorIDX; + kiStateBuffer[barIndex] = hideColorIDX; + + // + // TKI ... + tkiBuffer[barIndex] = emptyValue; + tkiColorBuffer[barIndex] = hideColorIDX; + tkiStateBuffer[barIndex] = hideColorIDX; + + // + // SWINGS ... + swingLowBuffer[barIndex] = emptyValue; + swingHighBuffer[barIndex] = emptyValue; +} + +/** + * Calculate Specified Market Cycle Info ... + * + * @param barIndex: Integer, Bar Index ... + * @param cycle: ENUM_X_MARKET_CYCLES member, Specified Cycle ... + * @param hhBuffer: Highest High Buffer Reference ... + * @param llBuffer: Lowest Low Buffer Reference ... + */ +void CalculateCycle( + int barIndex, + ENUM_X_MARKET_CYCLES cycle, + double &hhBuffer[], + double &llBuffer[] // +) +{ + // + XOHCL bar; + bool isBarInited = bar.Init( + _Symbol, + _Period, + barIndex + // + ); + if (!isBarInited) + { + return; + } + + // + int mLength = 0; + switch (cycle) + { + // + case X_MARKET_CYCLE_SHORT: + mLength = mSCLength; + break; + + // + case X_MARKET_CYCLE_MEDIUM: + mLength = mMCLength; + break; + + // + case X_MARKET_CYCLE_LONG: + mLength = mLCLength; + break; + + // + case X_MARKET_CYCLE_HIND: + mLength = mHCLength; + break; + } + + // + if (mLength == 0) + { + return; + } + + // + // Find Highest High ... + double hhValue = bar.FindHighest( + mLength, + hhMode + // + ); + hhBuffer[barIndex] = hhValue; + + // + // Find Lowest Low ... + double llValue = bar.FindLowest( + mLength, + llMode + // + ); + llBuffer[barIndex] = llValue; +} + +/** + * Claculate Cycles ... + * + * @param barIndex: Integer, Bar Index ... + */ +void CalculateCycles(int barIndex) +{ + // + // SHORT ... + CalculateCycle( + barIndex, + X_MARKET_CYCLE_SHORT, + sHHBuffer, + sLLBuffer // + ); + + // + // MEDIUM ... + CalculateCycle( + barIndex, + X_MARKET_CYCLE_MEDIUM, + mHHBuffer, + mLLBuffer // + ); + + // + // LONG ... + CalculateCycle( + barIndex, + X_MARKET_CYCLE_LONG, + lHHBuffer, + lLLBuffer // + ); + + // + // HIND ... + CalculateCycle( + barIndex, + X_MARKET_CYCLE_HIND, + hHHBuffer, + hLLBuffer // + ); +} + +/** + * Calculate Values ... + * + * @param bar_index: int, Specified Bar Index ... + * @param prevCalculated: int, Provides Previous Calculated Bars ... + * @param ratesTotal: int, Provides All Availabled Bars ... + * @param open: double Collection, Provides Open Prices Time Series ... + * @param high: double Collection, Provides High Prices Time Series ... + * @param close: double Collection, Provides Close Prices Time Series ... + * @param low: double Collection, Provides Low Prices Time Series ... + * @param tickVolume: long Collection, Provides Ticks Volume Prices Time Series ... + */ +void CalculateValues( + int bar_index, // Selected Bar Index + const int prevCalculated, + const int ratesTotal, + const double &open[], + const double &high[], + const double &close[], + const double &low[], + const long &tickVolume[] // +) +{ + // + // Check Prev Bar ... + // + int lastBarIndex = bar_index + 1; + bool isFirstBar = + startCalculationForLastBars > 0 + ? bar_index == startCalculationForLastBars + : bar_index == ratesTotal; + + XOHCL iBar; + bool isInited = iBar.Init( + _Symbol, + _Period, + bar_index // + ); + + // + double iSHH = sHHBuffer[bar_index]; + double iSLL = sLLBuffer[bar_index]; + + // + double iMHH = mHHBuffer[bar_index]; + double iMLL = mLLBuffer[bar_index]; + + // + double iLHH = lHHBuffer[bar_index]; + double iLLL = lLLBuffer[bar_index]; + + // + double iHHH = hHHBuffer[bar_index]; + double iHLL = hLLBuffer[bar_index]; + + // + // Calculate BOS ... + + // + // Calculate CHOCH ... + + // + // Calculate Support ... + double lastSupport = + isFirstBar + ? emptyValue + : supBuffer[lastBarIndex]; + bool isSupport = iSLL == iMLL; + double iSupport = + isSupport + ? iSLL + : lastSupport; + supBuffer[bar_index] = iSupport; + + // + // Calculate Vale ... + double lastVale = + isFirstBar + ? emptyValue + : valeBuffer[lastBarIndex]; + bool isVale = + isSupport && + iMLL == iLLL && + iLLL == iHLL; + double iVale = + isVale + ? iMLL + : lastVale; + valeBuffer[bar_index] = iVale; + + // + // Calculate Resistance ... + double lastResistance = + isFirstBar + ? emptyValue + : resBuffer[lastBarIndex]; + bool isResistance = iSHH == iMHH; + double iResistance = + isResistance + ? iSHH + : lastResistance; + resBuffer[bar_index] = iResistance; + + // + // Calculate Peak ... + double lastPeak = + isFirstBar + ? emptyValue + : peakBuffer[lastBarIndex]; + bool isPeak = + isResistance && + iMHH == iLHH && + iLHH == iHHH; + double iPeak = + isPeak + ? iMHH + : lastPeak; + peakBuffer[bar_index] = iPeak; + + // + bool canSmooth = + supResSmoothingLength > 0 && + supResSmoothingMode != X_MA_MODE_NONE; + if (!canSmooth) + { + // + supportBuffer[bar_index] = iSupport; + resistanceBuffer[bar_index] = iResistance; + } + else + { + // + // Support ... + iMAOnBuffer( + ratesTotal, + prevCalculated, + bar_index, + supResSmoothingLength, + supBuffer, + supportBuffer, + supResSmoothingMode // + ); + + // + // Resistance ... + iMAOnBuffer( + ratesTotal, + prevCalculated, + bar_index, + supResSmoothingLength, + resBuffer, + resistanceBuffer, + supResSmoothingMode // + ); + } + + // + // Calculate Fibo Levels ... + + // + double iFiboUpper = peakBuffer[bar_index]; + double iFiboLower = valeBuffer[bar_index]; + + // + double iFiboLevel1 = GetFibonacciLevel( + iFiboUpper, + iFiboLower, + fiboLevel1, + X_DIRECTION_BEARISH // + ); + fiboLevel1Buffer[bar_index] = iFiboLevel1; + + // + double iFiboLevel2 = GetFibonacciLevel( + iFiboUpper, + iFiboLower, + fiboLevel2, + X_DIRECTION_BEARISH // + ); + fiboLevel2Buffer[bar_index] = iFiboLevel2; + + // + double iFiboLevel3 = GetFibonacciLevel( + iFiboUpper, + iFiboLower, + fiboLevel3, + X_DIRECTION_BEARISH // + ); + fiboLevel3Buffer[bar_index] = iFiboLevel3; + + // + // Calculate Trend Color Buffer ... + double iClose = close[bar_index]; + double iTrend = trendBuffer[bar_index]; + + // + double iTrendState = neuturalState; + double iTrendColor = neuturalColorIDX; + if (iClose > iTrend) + { + // + iTrendState = bullishState; + iTrendColor = !showTrend + ? hideColorIDX + : bullishColorIDX; + } + else if (iClose < iTrend) + { + // + iTrendState = bearishState; + iTrendColor = !showTrend + ? hideColorIDX + : bearishColorIDX; + } + trendStateBuffer[bar_index] = iTrendState; + trendColorBuffer[bar_index] = iTrendColor; + + // + // Calculate KI / Color ... + if (isInited) + { + // + double iLLKI = iBar.FindLowest(kiLength, MODE_LOW); + double iHHKI = iBar.FindHighest(kiLength, MODE_HIGH); + + // + double iKI = (iHHKI + iLLKI) / 2; + kiBuffer[bar_index] = iKI; + + // + double iKIState = neuturalState; + double iKIColor = neuturalColorIDX; + if (iClose > iKI) + { + // + iKIState = bullishState; + iKIColor = + !showKI + ? hideColorIDX + : bullishColorIDX; + } + else if (iClose < iKI) + { + // + iKIState = bearishState; + iKIColor = + !showKI + ? hideColorIDX + : bearishColorIDX; + } + kiStateBuffer[bar_index] = iKIState; + kiColorBuffer[bar_index] = iKIColor; + } + + // + // Calculate PV Gold ... + if (isInited) + { + // + double iPeakGold = iBar.FindHighest(mHCLength, MODE_CLOSE); + peakGoldenBuffer[bar_index] = iPeakGold; + + // + double iValeGold = iBar.FindLowest(mHCLength, MODE_CLOSE); + valeGoldenBuffer[bar_index] = iValeGold; + } + + // + // Calculate Swings ... + + // + double lastSwingLow = + isFirstBar + ? emptyValue + : swingLowBuffer[lastBarIndex]; + bool isSwingLow = IsSwingLow( + high, + low, + bar_index, + swingLength // + ); + double iSwingLow = + isSwingLow + ? low[bar_index] + : lastSwingLow; + swingLowBuffer[bar_index] = iSwingLow; + + // + double lastSwingHigh = + isFirstBar + ? emptyValue + : swingHighBuffer[lastBarIndex]; + bool isSwingHigh = IsSwingHigh( + high, + low, + bar_index, + swingLength // + ); + double iSwingHigh = + isSwingHigh + ? high[bar_index] + : lastSwingHigh; + swingHighBuffer[bar_index] = iSwingHigh; + + // + // TKI State and Color ... + + // + double iTKI = tkiBuffer[bar_index]; + + // + double iTKIState = neuturalState; + double iTKIColor = neuturalColorIDX; + if (iClose > iTKI) + { + // + iTKIState = bullishState; + iTKIColor = + !showTKI + ? hideColorIDX + : bullishColorIDX; + } + else if (iClose < iTKI) + { + // + iTKIState = bearishState; + iTKIColor = + !showTKI + ? hideColorIDX + : bearishColorIDX; + } + tkiStateBuffer[bar_index] = iTKIState; + tkiColorBuffer[bar_index] = iTKIColor; + + // + // Cleanup Resources ... + + // + iBar.Clean(); +} + +// +bool IsSwingLow( + const double &high[], + const double &low[], + int index, + int length // +) +{ + // + bool result = false; + + // + for (int i = index + 1; i <= index + length; i++) + { + // + result = low[index] < low[i]; + if (!result) + { + break; + } + } + + // + return result; +} + +// +bool IsSwingHigh( + const double &high[], + const double &low[], + int index, + int length // +) +{ + // + bool result = false; + + // + for (int i = index + 1; i <= index + length; i++) + { + // + result = high[index] > high[i]; + if (!result) + { + break; + } + } + + // + return result; +} + +// \ No newline at end of file diff --git a/BKPS/14040203/Indicators/x-saherelm.x121.xcc.mq5 b/BKPS/14040203/Indicators/x-saherelm.x121.xcc.mq5 new file mode 100644 index 0000000..2f45b84 --- /dev/null +++ b/BKPS/14040203/Indicators/x-saherelm.x121.xcc.mq5 @@ -0,0 +1,437 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Candle Styles +// --------------------------------------------------- +// Name: X121 XCC +// Description: Candle Styles ... +// +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +////////////////////////////////////////////////////// +// +// Global Properties ... +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://saherelm.ir" +#property version "1.00" +#property description "SaherElm X121 XCC Indicator" +#property strict + +// +// START Constants ... +// + +// +// Indicator Short Name ... +#define ShortName "X121 XCC" + +// +// Holds an SnapShot of Charts Configuration ... +struct XChartStyle +{ + // + // chart's ID ... + long chartId; + // + // chart's mode ... + ENUM_CHART_MODE mode; + // + // show bid line ... + bool showBidLine; + // + // show ask line ... + bool showAskLine; + // + // show grids on chart ... + bool showGrid; + // + // show volumes ... + bool showVolumes; + // + // Displaying trade levels in the chart (levels of open positions, Stop Loss, Take Profit and pending orders) ... + bool showTradeLevels; + // + // chart autoscroll ... + bool autoScroll; + // + // chart quick navigation state ... + bool quickNavigation; + // + // chart's foreground color ... + color foreGroundColor; + // + // chart's background color ... + color backGroundColor; + // + // Up Color ... + color upColor; + // + // Down Color ... + color downColor; + // + // Bullish color ... + color bullishColor; + // + // Bearish color ... + color bearishColor; + // + // grid color ... + color gridColor; + // + // bid line color ... + color bidLineColor; + // + // ask line color ... + color askLineColor; + // + // line mode and doji candlestick color ... + color lineColor; + // + // Color of stop order levels (Stop Loss and Take Profit) ... + color stopColor; + // + // volumes color ... + color volumesColor; +}; + +// +// END Constants ... +// + +// +// START Inputs ... +// + +// +input group "Chart Style"; +input ENUM_CHART_MODE mode = CHART_CANDLES; // Mode +input color upColor = clrGreen; // Up Color +input color downColor = clrRed; // Down Color +input color lineColor = clrGreen; // Line mode and Doji candlestick Color +input color bullishColor = clrGreen; // Bullish Color +input color bearishColor = clrRed; // Bearish Color +input color volumesColor = clrGreen; // Volumes Color + +// +input group "Presentation"; +input bool showCandles = true; // Show Candles + +// +// END Inputs ... +// + +// +// START Includes and Imports ... +// + +// +// Includes Draw Library ... +#include "../Libraries/x-saherelm.draw.lib.mq5" + +// +// Includes Common Library ... +#include "../Libraries/x-saherelm.common.lib.mq5" + +// +// END Includes and Imports ... +// + +// +// START Buffers ... +// + +// +#property indicator_chart_window + +// +#property indicator_buffers 0 +#property indicator_plots 0 + +// +// END Buffers ... +// + +// +// START Global Definitions: Variables, Properties and etc ... +// + +// +int maxLength; + +// +XChartStyle chartStyle; +XChartStyle clearStyle; + +// +// END Global Definitions: Variables, Properties and etc ... +// + +// +// START Event Handlers ... +// + +// +// Initialization ... +int OnInit() +{ + // + // Validate Inputs ... + if (!ValidateInputs()) + { + return INIT_PARAMETERS_INCORRECT; + } + + // + drawPrefix = ShortName; + + // + // because in some cases we may have more than one input for + // calculation and we must prevent any calculation + // untill we pass the biggest input length, here we get max Input length + // and then wait until pass it ... + maxLength = ExtractMaxLengthOfInputs(); + + // + // Define Index Buffers ... + DefineBuffers(); + + // + // Set Indicator ShortName ... + SetIndicatorName(); + + // + // Apply Chart Style ... + ApplyCustomChartStyle(); + + // + // Init Succeed ... + return INIT_SUCCEEDED; +} + +// +// DeInitialization ... +void OnDeinit(const int reason) +{ + // + // REASON_PROGRAM 0 The EA has stopped working calling the ExpertRemove() function + // REASON_REMOVE 1 Program removed from a chart + // REASON_RECOMPILE 2 Program recompiled + // REASON_CHARTCHANGE 3 A symbol or a chart period is changed + // REASON_CHARTCLOSE 4 Chart closed + // REASON_PARAMETERS 5 Inputs changed by a user + // REASON_ACCOUNT 6 Another account has been activated or reconnection to the trade server has occurred due to changes in the account settings + // REASON_TEMPLATE 7 Another chart template applied + // REASON_INITFAILED 8 The OnInit() handler returned a non-zero value + // REASON_CLOSE 9 Terminal closed +} + +// +// Calculating what we want ... +int OnCalculate( + const int rates_total, // Total Bars on Chart ... + const int prev_calculated, // Total Calculated Bars on Charts ... + const datetime &time[], // History of Open Time ... + const double &open[], // History of Open Price ... + const double &high[], // History of High Price ... + const double &low[], // History of Low Price ... + const double &close[], // History of Close Price ... + const long &tick_volume[], // History of Tick Volumes on Bar ... + const long &volume[], // History of Trade Volumes ... + const int &spread[] // History of Spread Price ... +) +{ + // + // Prepare Buffers ... + ArraySetAsSeries(time, true); + ArraySetAsSeries(open, true); + ArraySetAsSeries(high, true); + ArraySetAsSeries(low, true); + ArraySetAsSeries(close, true); + ArraySetAsSeries(tick_volume, true); + ArraySetAsSeries(volume, true); + ArraySetAsSeries(spread, true); + + // + // this counts Available Bars ... + int limit; + + // + limit = (prev_calculated > rates_total || prev_calculated <= 0) ? rates_total : (rates_total - prev_calculated) + 1; + + // + // Main Loop ... + for (int i = limit - 1; i >= 0 && !IsStopped(); i--) + { + CalculateBuffers(i); + } + + // + return rates_total; +} + +// +// END Event Handlers ... +// + +// +// START Functions ... +// + +// +// Validate Input Args for Initialization ... +bool ValidateInputs() +{ + // + bool result = true; + + // + return result; +} + +// +// Retrieve all Exists Input Max Length ... +// use for Start Of Drawing ... +int ExtractMaxLengthOfInputs() +{ + // + int result = 0; + + // + return result; +} + +// +// Define Indexes and Styles ... +void DefineBuffers() +{ +} + +// +// Set Indicator Short Name and also we can define Buffers Labels ... +void SetIndicatorName() +{ + IndicatorSetString(INDICATOR_SHORTNAME, ShortName); +} + +// +// Calculate Buffers ... +void CalculateBuffers( + int bar_index // Selected Bar Index +) +{ +} + +// +// Apply Custom Chart Style ... +void ApplyCustomChartStyle() +{ + // + // Read Current Chart Config and Store it ... + ReadChartStyle(); + + // + // After Reading Current Chart Style ... + // we have to Save Configs and Change Styles ... + clearStyle = chartStyle; + + // + clearStyle.upColor = CLR_NONE; + clearStyle.downColor = CLR_NONE; + clearStyle.lineColor = CLR_NONE; + clearStyle.bullishColor = CLR_NONE; + clearStyle.bearishColor = CLR_NONE; + + // + // Decide to Show or not Candles based on User Input ... + if (showCandles) + { + SetChartStyle(chartStyle); + } + else + { + SetChartStyle(clearStyle); + } +} + +// +// Read Previous Chart Style ... +void ReadChartStyle() +{ + // + // Retrieve Current Chart ID ... + long chartId = ChartID(); + chartStyle.chartId = chartId; + + // + // Retrieve Chart Mode ... + chartStyle.mode = (ENUM_CHART_MODE)ChartGetInteger(chartId, CHART_MODE); + + // + chartStyle.showBidLine = (bool)ChartGetInteger(chartId, CHART_SHOW_BID_LINE); + chartStyle.showAskLine = (bool)ChartGetInteger(chartId, CHART_SHOW_ASK_LINE); + chartStyle.showGrid = (bool)ChartGetInteger(chartId, CHART_SHOW_GRID); + chartStyle.showVolumes = (bool)ChartGetInteger(chartId, CHART_SHOW_VOLUMES); + chartStyle.showTradeLevels = (bool)ChartGetInteger(chartId, CHART_SHOW_TRADE_LEVELS); + chartStyle.autoScroll = (bool)ChartGetInteger(chartId, CHART_AUTOSCROLL); + chartStyle.quickNavigation = (bool)ChartGetInteger(chartId, CHART_QUICK_NAVIGATION); + + // + chartStyle.foreGroundColor = (color)ChartGetInteger(chartId, CHART_COLOR_FOREGROUND); + chartStyle.backGroundColor = (color)ChartGetInteger(chartId, CHART_COLOR_BACKGROUND); + chartStyle.upColor = (color)ChartGetInteger(chartId, CHART_COLOR_CHART_UP); + chartStyle.downColor = (color)ChartGetInteger(chartId, CHART_COLOR_CHART_DOWN); + chartStyle.bullishColor = (color)ChartGetInteger(chartId, CHART_COLOR_CANDLE_BULL); + chartStyle.bearishColor = (color)ChartGetInteger(chartId, CHART_COLOR_CANDLE_BEAR); + chartStyle.gridColor = (color)ChartGetInteger(chartId, CHART_COLOR_GRID); + chartStyle.bidLineColor = (color)ChartGetInteger(chartId, CHART_COLOR_BID); + chartStyle.askLineColor = (color)ChartGetInteger(chartId, CHART_COLOR_ASK); + chartStyle.stopColor = (color)ChartGetInteger(chartId, CHART_COLOR_STOP_LEVEL); + chartStyle.lineColor = (color)ChartGetInteger(chartId, CHART_COLOR_CHART_LINE); + chartStyle.volumesColor = (color)ChartGetInteger(chartId, CHART_COLOR_VOLUME); + + // + chartStyle.mode = mode; + chartStyle.upColor = upColor; + chartStyle.downColor = downColor; + chartStyle.lineColor = lineColor; + chartStyle.bearishColor = bearishColor; + chartStyle.bullishColor = bullishColor; + chartStyle.volumesColor = volumesColor; +} + +// +// Set Chart Style ... +void SetChartStyle( + XChartStyle &mChartStyle // Chart Style to Apply +) +{ + // + ApplyChartStyle( + mChartStyle.chartId, + mChartStyle.mode, + mChartStyle.showBidLine, + mChartStyle.showAskLine, + mChartStyle.showGrid, + mChartStyle.showVolumes, + mChartStyle.showTradeLevels, + mChartStyle.autoScroll, + mChartStyle.quickNavigation, + mChartStyle.foreGroundColor, + mChartStyle.backGroundColor, + mChartStyle.upColor, + mChartStyle.downColor, + mChartStyle.bullishColor, + mChartStyle.bearishColor, + mChartStyle.gridColor, + mChartStyle.bidLineColor, + mChartStyle.askLineColor, + mChartStyle.lineColor, + mChartStyle.stopColor, + mChartStyle.volumesColor); +} + +// +// END Functions ... +// diff --git a/BKPS/14040203/Indicators/x-saherelm.x121.xche.mq5 b/BKPS/14040203/Indicators/x-saherelm.x121.xche.mq5 new file mode 100644 index 0000000..d8ed104 --- /dev/null +++ b/BKPS/14040203/Indicators/x-saherelm.x121.xche.mq5 @@ -0,0 +1,624 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Indicator +// ------------------------------------------------- +// Name: X121 XCHE +// Description: XCHE ... +// +// +// 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 XCHE Indicator" +#property strict + +// +// Definitions ... + +// +#define ShortName "X121 XCHE" + +// +// Includes Common Library ... +#include "../Libraries/x-saherelm.common.lib.mq5" + +// +// Inputs ... + +// +// Market ... +input group "Market"; +input int cheLength = 35; // Length +input int cheLoopback = 26; // Loopback +input double cheMultiplier1 = 3.0; // 1st Multiplier +input double cheMultiplier2 = 3.5; // 2nd Multiplier +input ENUM_APPLIED_PRICE cheUpperAppliedTo = PRICE_HIGH; // Upper Zone Applied to +input ENUM_APPLIED_PRICE cheLowerAppliedTo = PRICE_LOW; // Lower Zone Applied to + +// +input group "Presentation"; + +// +input int cheArrowCode = 159; // CHE Arrow Code + +// +input bool showLE1 = true; // Show 1st Long Exit +input bool showSE1 = true; // Show 1st Short Exit +input bool showLE2 = true; // Show 2st Long Exit +input bool showSE2 = true; // Show 2st Short Exit + +// +// Buffers ... + +// +#define hideColorIDX 0 +#define bullishColorIDX 1 +#define bearishColorIDX 2 +#define neuturalColorIDX 3 + +// +#property indicator_chart_window + +// +#property indicator_buffers 8 +#property indicator_plots 8 + +// +// Exit 1 ... + +// +// LONG ... + +// +#define le1BufferIndex 0 +double le1Buffer[]; + +#property indicator_label1 "X121 LE1" +#property indicator_type1 DRAW_LINE +#property indicator_color1 clrAqua +#property indicator_style1 STYLE_DOT +#property indicator_width1 1 + +// +// SHORT ... + +// +#define se1BufferIndex 1 +double se1Buffer[]; + +#property indicator_label2 "X121 SE1" +#property indicator_type2 DRAW_LINE +#property indicator_color2 clrMagenta +#property indicator_style2 STYLE_DOT +#property indicator_width2 1 + +// +// Exit 2 ... + +// +// LONG ... + +// +#define le2BufferIndex 2 +double le2Buffer[]; + +#property indicator_label3 "X121 LE2" +#property indicator_type3 DRAW_LINE +#property indicator_color3 clrAqua +#property indicator_style3 STYLE_SOLID +#property indicator_width3 1 + +// +// SHORT ... + +// +#define se2BufferIndex 3 +double se2Buffer[]; + +#property indicator_label4 "X121 SE2" +#property indicator_type4 DRAW_LINE +#property indicator_color4 clrMagenta +#property indicator_style4 STYLE_SOLID +#property indicator_width4 1 + +// +// Start Buffers ... + +// +#define le1StartBufferIndex 4 +double le1StartBuffer[]; + +// +#property indicator_label5 "X121 LE1 S" +#property indicator_type5 DRAW_ARROW +#property indicator_color5 clrLime + +// +#define se1StartBufferIndex 5 +double se1StartBuffer[]; + +// +#property indicator_label6 "X121 SE1 S" +#property indicator_type6 DRAW_ARROW +#property indicator_color6 clrRed + +// +#define le2StartBufferIndex 6 +double le2StartBuffer[]; + +// +#property indicator_label7 "X121 LE2 S" +#property indicator_type7 DRAW_ARROW +#property indicator_color7 clrLime + +// +#define se2StartBufferIndex 7 +double se2StartBuffer[]; + +// +#property indicator_label8 "X121 SE2 S" +#property indicator_type8 DRAW_ARROW +#property indicator_color8 clrRed + +// +// Variables, Properties and etc ... + +// +// this counts Available Bars ... +int limit; + +// +int maxLength; + +// +// Working Array ... +double work[][6]; +#define hi1Idx 0 +#define lo1Idx 1 +#define hi2Idx 2 +#define lo2Idx 3 +#define trend1Idx 4 +#define trend2Idx 5 + +// +// Event Handlers ... + +/** + * Initialize Indicator ... + * + * @return ( int ) + */ +int OnInit() +{ + // + // Validate Inputs ... + if (!ValidateInputs()) + { + return INIT_PARAMETERS_INCORRECT; + } + + // + // because in some cases we may have more than one input for + // calculation and we must prevent any calculation + // untill we pass the biggest input cheLength, here we get max Input cheLength + // and then wait until pass it ... + maxLength = ExtractMaxLengthOfInputs(); + + // + // Define Index Buffers ... + DefineBuffers(); + + // + // Set Indicator ShortName ... + SetIndicatorName(); + + // + // Init Succeed ... + return INIT_SUCCEEDED; +} + +/** + * De Initialize Indicator ... + * + * @param reason: Integer, De Initialization Reason ... + */ +void OnDeinit(const int reason) +{ + // + // REASON_PROGRAM 0 The EA has stopped working calling the ExpertRemove() function + // REASON_REMOVE 1 Program removed from a chart + // REASON_RECOMPILE 2 Program recompiled + // REASON_CHARTCHANGE 3 A symbol or a chart period is changed + // REASON_CHARTCLOSE 4 Chart closed + // REASON_PARAMETERS 5 Inputs changed by a user + // REASON_ACCOUNT 6 Another account has been activated or reconnection to the trade server has occurred due to changes in the account settings + // REASON_TEMPLATE 7 Another chart template applied + // REASON_INITFAILED 8 The OnInit() handler returned a non-zero value + // REASON_CLOSE 9 Terminal closed +} + +/** + * Calculate Bars ... + * + * @param rates_total: Integer, Total Bars on Chart ... + * @param prev_calculated: Integer, Total Calculated Bars on Charts ... + * @param time: DateTime Array, History of Open Time ... + * @param open: Double Array, History of Open Prices ... + * @param high: Double Array, History of High Prices ... + * @param low: Double Array, History of Low Prices ... + * @param close: Double Array, History of Close Prices ... + * @param tick_volume: Long, History of Tick Volumes on Bar ... + * @param volume: Long, History of Trade Volumes ... + * @param spread: Double, History of Spread Price ... + * + * @return ( int ) + */ +int OnCalculate( + const int rates_total, + const int prev_calculated, + const datetime &time[], + const double &open[], + const double &high[], + const double &low[], + const double &close[], + const long &tick_volume[], + const long &volume[], + const int &spread[] // +) +{ + // + if (Bars(_Symbol, _Period) < rates_total) + { + return (prev_calculated); + } + + // + if (ArrayRange(work, 0) != rates_total) + { + ArrayResize(work, rates_total); + } + + // + // this counts Available Bars ... + + // + limit = prev_calculated - 1; + if (limit < 0) + { + limit = 0; + } + + // + // Main Loop ... + for (int i = limit; i < rates_total && !IsStopped(); i++) + { + CalculateBuffers( + i, + prev_calculated, + rates_total, + // + open, + high, + low, + close); + } + + // + return rates_total; +} + +// +// Functions ... + +/** + * Validate Input Args for Initialization ... + * + * @return ( bool ) + */ +bool ValidateInputs() +{ + // + bool result = true; + + // + result = + cheLength >= 9 && + cheLoopback >= 0; + + // + return result; +} + +/** + * Extract Max Length of Inputs ... + * + * @return ( int ) + */ +int ExtractMaxLengthOfInputs() +{ + // + int result = 0; + + // + result = MathMax(cheLength, cheLoopback); + + // + return result; +} + +/** + * Define Required Buffers ... + */ +void DefineBuffers() +{ + // + // LEVEL 1 ... + + // + // Long Exit 1 ... + + // + // Draw Type ... + ENUM_DRAW_TYPE le1DrawType = showLE1 ? DRAW_LINE : DRAW_NONE; + ENUM_DRAW_TYPE le1StartDrawType = showLE1 ? DRAW_ARROW : DRAW_NONE; + + // + // Buffer ... + SetIndexBuffer(le1BufferIndex, le1Buffer, INDICATOR_DATA); + PlotIndexSetInteger(le1BufferIndex, PLOT_SHOW_DATA, showLE1); + PlotIndexSetInteger(le1BufferIndex, PLOT_DRAW_TYPE, le1DrawType); + + // + // Start Buffer ... + SetIndexBuffer(le1StartBufferIndex, le1StartBuffer, INDICATOR_DATA); + PlotIndexSetInteger(le1StartBufferIndex, PLOT_SHOW_DATA, false); + PlotIndexSetInteger(le1StartBufferIndex, PLOT_DRAW_TYPE, le1StartDrawType); + PlotIndexSetInteger(le1StartBufferIndex, PLOT_ARROW, cheArrowCode); + + // + // Short Exit 1 ... + + // + // Draw Type ... + ENUM_DRAW_TYPE se1DrawType = showSE1 ? DRAW_LINE : DRAW_NONE; + ENUM_DRAW_TYPE se1StartDrawType = showSE1 ? DRAW_ARROW : DRAW_NONE; + + // + // Buffer ... + SetIndexBuffer(se1BufferIndex, se1Buffer, INDICATOR_DATA); + PlotIndexSetInteger(se1BufferIndex, PLOT_SHOW_DATA, showSE1); + PlotIndexSetInteger(se1BufferIndex, PLOT_DRAW_TYPE, se1DrawType); + + // + // Start Buffer ... + SetIndexBuffer(se1StartBufferIndex, se1StartBuffer, INDICATOR_DATA); + PlotIndexSetInteger(se1StartBufferIndex, PLOT_SHOW_DATA, false); + PlotIndexSetInteger(se1StartBufferIndex, PLOT_DRAW_TYPE, se1StartDrawType); + PlotIndexSetInteger(se1StartBufferIndex, PLOT_ARROW, cheArrowCode); + + // + // LEVEL 2 ... + + // + // Long Exit 2 ... + + // + // Draw Type ... + ENUM_DRAW_TYPE le2DrawType = showLE2 ? DRAW_LINE : DRAW_NONE; + ENUM_DRAW_TYPE le2StartDrawType = showLE2 ? DRAW_ARROW : DRAW_NONE; + + // + // Buffer ... + SetIndexBuffer(le2BufferIndex, le2Buffer, INDICATOR_DATA); + PlotIndexSetInteger(le2BufferIndex, PLOT_SHOW_DATA, showLE2); + PlotIndexSetInteger(le2BufferIndex, PLOT_DRAW_TYPE, le2DrawType); + + // + // Start Buffer ... + SetIndexBuffer(le2StartBufferIndex, le2StartBuffer, INDICATOR_DATA); + PlotIndexSetInteger(le2StartBufferIndex, PLOT_SHOW_DATA, false); + PlotIndexSetInteger(le2StartBufferIndex, PLOT_DRAW_TYPE, le2StartDrawType); + PlotIndexSetInteger(le2StartBufferIndex, PLOT_ARROW, cheArrowCode); + + // + // Short Exit 2 ... + + // + // Draw Type ... + ENUM_DRAW_TYPE se2DrawType = showSE2 ? DRAW_LINE : DRAW_NONE; + ENUM_DRAW_TYPE se2StartDrawType = showSE2 ? DRAW_ARROW : DRAW_NONE; + + // + // Buffer ... + SetIndexBuffer(se2BufferIndex, se2Buffer, INDICATOR_DATA); + PlotIndexSetInteger(se2BufferIndex, PLOT_SHOW_DATA, showSE2); + PlotIndexSetInteger(se2BufferIndex, PLOT_DRAW_TYPE, se2DrawType); + + // + // Start Buffer ... + SetIndexBuffer(se2StartBufferIndex, se2StartBuffer, INDICATOR_DATA); + PlotIndexSetInteger(se2StartBufferIndex, PLOT_SHOW_DATA, false); + PlotIndexSetInteger(se2StartBufferIndex, PLOT_DRAW_TYPE, se2StartDrawType); + PlotIndexSetInteger(se2StartBufferIndex, PLOT_ARROW, cheArrowCode); +} + +/** + * Set Indicator Short Name and also we can define Buffers Labels ... + */ +void SetIndicatorName() +{ + IndicatorSetString(INDICATOR_SHORTNAME, ShortName); +} + +/** + * Calculate Buffers ... + */ +void CalculateBuffers( + int bar_index, // Selected Bar Index + int prevCalculated, // Previous Calculated + int ratesTotal, // Total Rates + const double &open[], // Rates Open ... + const double &high[], // Rates High ... + const double &low[], // Rates Low ... + const double &close[] // Rates Close ... +) +{ + // + // Cleanup Buffers ... + le1Buffer[bar_index] = le1StartBuffer[bar_index] = se1Buffer[bar_index] = se1StartBuffer[bar_index] = EMPTY_VALUE; + le2Buffer[bar_index] = le2StartBuffer[bar_index] = se2Buffer[bar_index] = se2StartBuffer[bar_index] = EMPTY_VALUE; + + // + int start = MathMax(bar_index - cheLoopback, 0); + + // + // Calculate ATR Value ... + double atrValue = 0; + for (int k = 1; k <= cheLength && (bar_index - k - 1) >= 0; k++) + { + // + atrValue += MathMax(high[bar_index - k], close[MathMax(bar_index - k - 1, 0)]) - + MathMin(low[bar_index - k], close[MathMax(bar_index - k - 1, 0)]); + } + atrValue /= (double)cheLength; + + // + // Retrieve Highest High and Lowest Lows ... + double cheLoopbackMax = high[ArrayMaximum(high, start, cheLoopback)]; + double cheLoopbackMin = low[ArrayMinimum(low, start, cheLoopback)]; + + // + // Fill Multi Dimesional Working Array ... + work[bar_index][hi1Idx] = cheLoopbackMax - cheMultiplier1 * atrValue; + work[bar_index][lo1Idx] = cheLoopbackMin + cheMultiplier1 * atrValue; + work[bar_index][hi2Idx] = cheLoopbackMax - cheMultiplier2 * atrValue; + work[bar_index][lo2Idx] = cheLoopbackMin + cheMultiplier2 * atrValue; + work[bar_index][trend1Idx] = (bar_index > 0) ? work[bar_index - 1][trend1Idx] : 0; + work[bar_index][trend2Idx] = (bar_index > 0) ? work[bar_index - 1][trend2Idx] : 0; + + // + if (bar_index > 0) + { + // + // Calculate Trends ... + if (close[bar_index] > work[bar_index - 1][lo1Idx]) + { + work[bar_index][trend1Idx] = 1; + } + + // + if (close[bar_index] < work[bar_index - 1][hi1Idx]) + { + work[bar_index][trend1Idx] = -1; + } + + // + if (close[bar_index] > work[bar_index - 1][lo2Idx]) + { + work[bar_index][trend2Idx] = 1; + } + + // + if (close[bar_index] < work[bar_index - 1][hi2Idx]) + { + work[bar_index][trend2Idx] = -1; + } + + // + // Calculate Exit Values ... + + // + // Exit 1 ... + + // + // Long ... + if (cheMultiplier1 > 0 && work[bar_index][trend1Idx] == 1) + { + // + if (work[bar_index][hi1Idx] < work[bar_index - 1][hi1Idx]) + { + work[bar_index][hi1Idx] = work[bar_index - 1][hi1Idx]; + } + + // + le1Buffer[bar_index] = work[bar_index][hi1Idx]; + + // + if (le1Buffer[bar_index - 1] == EMPTY_VALUE) + { + le1StartBuffer[bar_index] = le1Buffer[bar_index]; + } + } + + // + // Short ... + if (cheMultiplier1 > 0 && work[bar_index][trend1Idx] == -1) + { + // + if (work[bar_index][lo1Idx] > work[bar_index - 1][lo1Idx]) + { + work[bar_index][lo1Idx] = work[bar_index - 1][lo1Idx]; + } + + // + se1Buffer[bar_index] = work[bar_index][lo1Idx]; + + // + if (se1Buffer[bar_index - 1] == EMPTY_VALUE) + { + se1StartBuffer[bar_index] = se1Buffer[bar_index]; + } + } + + // + // Exit 2 ... + + // + // Long ... + if (cheMultiplier2 > 0 && work[bar_index][trend2Idx] == 1) + { + if (work[bar_index][hi2Idx] < work[bar_index - 1][hi2Idx]) + { + work[bar_index][hi2Idx] = work[bar_index - 1][hi2Idx]; + } + + // + le2Buffer[bar_index] = work[bar_index][hi2Idx]; + + // + if (le2Buffer[bar_index - 1] == EMPTY_VALUE) + { + le2StartBuffer[bar_index] = le2Buffer[bar_index]; + } + } + + // + // Short ... + if (cheMultiplier2 > 0 && work[bar_index][trend2Idx] == -1) + { + // + if (work[bar_index][lo2Idx] > work[bar_index - 1][lo2Idx]) + { + work[bar_index][lo2Idx] = work[bar_index - 1][lo2Idx]; + } + + // + se2Buffer[bar_index] = work[bar_index][lo2Idx]; + + // + if (se2Buffer[bar_index - 1] == EMPTY_VALUE) + { + se2StartBuffer[bar_index] = se2Buffer[bar_index]; + } + } + } +} + +// \ No newline at end of file diff --git a/BKPS/14040203/Indicators/x-saherelm.x121.xct.mq5 b/BKPS/14040203/Indicators/x-saherelm.x121.xct.mq5 new file mode 100644 index 0000000..286882a --- /dev/null +++ b/BKPS/14040203/Indicators/x-saherelm.x121.xct.mq5 @@ -0,0 +1,262 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Indicator +// --------------------------------------------- +// Name: X121 XCT +// Description: Trend Magic Indicator ... +// +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +////////////////////////////////////////////////////// +// +// Global Properties ... +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://saherelm.ir" +#property version "1.00" +#property description "SaherElm X121 XCT Indicator" +#property strict + +// +// START Constants ... +// + +// +#define ShortName "X121 XCT" +#include "../Libraries/x-saherelm.common.lib.mq5" + +// +// END Constants ... +// + +// +// START Inputs ... +// + +// +input int fontSize = 15; // Font Size +input string font = "Arial"; // Font +input color clr = clrYellow; // Text Color +input ENUM_BASE_CORNER corner = CORNER_RIGHT_LOWER; // Text Position + +// +input group "Presentation"; +input bool showTimer = true; // Show Candle Time + +// +// END Inputs ... +// + +// +// START Buffers ... +// + +// +#property indicator_chart_window + +// +#property indicator_buffers 0 +#property indicator_plots 0 + +// +// END Buffers ... +// + +// +// START Global Definitions: Variables, Properties and etc ... +// +bool isCreatedObject; +string tag; +// +// END Global Definitions: Variables, Properties and etc ... +// + +// +// START Event Handlers ... +// + +// +// Initialization ... +int OnInit() +{ + // + // Validate Inputs ... + + // + tag = ShortName + _Symbol + ToString(_Period); + + // + // Set Indicator ShortName ... + SetIndicatorName(); + + // + // Init Succeed ... + return INIT_SUCCEEDED; +} + +// +// DeInitialization ... +void OnDeinit(const int reason) +{ + // + // REASON_PROGRAM 0 The EA has stopped working calling the ExpertRemove() function + // REASON_REMOVE 1 Program removed from a chart + // REASON_RECOMPILE 2 Program recompiled + // REASON_CHARTCHANGE 3 A symbol or a chart period is changed + // REASON_CHARTCLOSE 4 Chart closed + // REASON_PARAMETERS 5 Inputs changed by a user + // REASON_ACCOUNT 6 Another account has been activated or reconnection to the trade server has occurred due to changes in the account settings + // REASON_TEMPLATE 7 Another chart template applied + // REASON_INITFAILED 8 The OnInit() handler returned a non-zero value + // REASON_CLOSE 9 Terminal closed + + // + // Delete Object ... + ObjectDelete(0, tag); + + // + Comment(""); +} + +// +// Calculating what we want ... +int OnCalculate( + const int rates_total, // Total Bars on Chart ... + const int prev_calculated, // Total Calculated Bars on Charts ... + const datetime &time[], // History of Open Time ... + const double &open[], // History of Open Price ... + const double &high[], // History of High Price ... + const double &low[], // History of Low Price ... + const double &close[], // History of Close Price ... + const long &tick_volume[], // History of Tick Volumes on Bar ... + const long &volume[], // History of Trade Volumes ... + const int &spread[] // History of Spread Price ... +) +{ + // + if (!showTimer) + { + return rates_total; + } + + // + XBarRemainsTime barRemains; + barRemains.Init( + _Symbol, + _Period + // + ); + + // + string msg = barRemains + .ToString( + "", + "", + "", + "", + "", + ":", + true + // + ); + + // + long mSpread = SymbolInfoInteger(Symbol(), SYMBOL_SPREAD); + + // + string _sp = ""; + if (mSpread < 10) + _sp = ".."; + else if (mSpread < 100) + _sp = "."; + + // + string objText = "Spread: " + IntegerToString(mSpread) + _sp + ", Next Bar in: " + msg; + + // + if (IsValid(tag) && !isCreatedObject) + { + CreateIndicatorObject(); + } + + // + if (isCreatedObject) + { + ObjectSetString(0, tag, OBJPROP_TEXT, objText); + } + + // + return rates_total; +} + +// +// END Event Handlers ... +// + +// +// START Functions ... +// + +// +// Set Indicator Short Name and also we can define Buffers Labels ... +void SetIndicatorName() +{ + IndicatorSetString(INDICATOR_SHORTNAME, ShortName); +} + +// +void CreateIndicatorObject() +{ + // + if (!showTimer || + !IsValid(tag)) + { + return; + } + + // + isCreatedObject = ObjectCreate(0, tag, OBJ_LABEL, 0, 0, 0); + ObjectSetInteger(0, tag, OBJPROP_CORNER, corner); + ObjectSetInteger(0, tag, OBJPROP_XDISTANCE, 10); + ObjectSetInteger(0, tag, OBJPROP_YDISTANCE, 2); + + // + ENUM_ANCHOR_POINT Anchor = ANCHOR_LEFT_UPPER; + switch (corner) + { + case CORNER_LEFT_UPPER: + Anchor = ANCHOR_LEFT_UPPER; + break; + case CORNER_RIGHT_UPPER: + Anchor = ANCHOR_RIGHT_UPPER; + break; + case CORNER_LEFT_LOWER: + Anchor = ANCHOR_LEFT_LOWER; + break; + case CORNER_RIGHT_LOWER: + Anchor = ANCHOR_RIGHT_LOWER; + break; + } + + // + int mFontSize = fontSize > 0 + ? fontSize + : 10; + + // + string mFont = IsValid(font) + ? font + : "Arial"; + + // + ObjectSetString(0, tag, OBJPROP_FONT, mFont); + ObjectSetInteger(0, tag, OBJPROP_COLOR, clr); + ObjectSetInteger(0, tag, OBJPROP_ANCHOR, Anchor); + ObjectSetInteger(0, tag, OBJPROP_FONTSIZE, mFontSize); +} + +// +// END Functions ... +// diff --git a/BKPS/14040203/Indicators/x-saherelm.x121.xdelta.mq5 b/BKPS/14040203/Indicators/x-saherelm.x121.xdelta.mq5 new file mode 100644 index 0000000..b422765 --- /dev/null +++ b/BKPS/14040203/Indicators/x-saherelm.x121.xdelta.mq5 @@ -0,0 +1,532 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Ocillator +// ------------------------------------------------- +// Name: X121 XDelta +// Description: Detect Comulative Volumes Delta ... +// +// +// 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 XDelta Ocillator" +#property strict + +// +// Definitions ... + +// +#define ShortName "X121_XDELTA" + +// +// Imports ... +#include "../Libraries/x-saherelm.common.lib.mq5" + +// +// Inputs ... + +// +// Makret ... +input group "Market"; +input int maLength = 14; // Moving Averge Length +input ENUM_X_MA_METHOD maMethod = X_MA_MODE_EMA; // Moving Averge Method + +// +// Presentation ... +input group "Presentation"; +input int startCalculationForLastBars = 1000; // Calculate Last n Bars +input bool showDeltaLine = true; // Show Delta Line +input bool showDeltaHistogram = true; // Show Delta Histogram +input bool showDeltaMa = true; // Show Delta Moving Average + +// +// Buffers Props ... + +// +#property indicator_separate_window + +// +#property indicator_buffers 6 +#property indicator_plots 3 + +// +#define hideColorIDX 0 +#define bullishColorIDX 1 +#define bearishColorIDX 2 + +// +// Buffers ... + +// +#define deltaLineBufferIndex 0 +double deltaLineBuffer[]; + +#property indicator_label1 "Delta Line" +#property indicator_type1 DRAW_LINE +#property indicator_color1 clrYellow +#property indicator_style1 STYLE_SOLID +#property indicator_width1 1 + +// +#define deltaHistogramBufferIndex 1 +double deltaHistogramBuffer[]; + +// +#define deltaHistogramColorBufferIndex 2 +double deltaHistogramColorBuffer[]; + +#property indicator_label2 "Delta Histogram" +#property indicator_type2 DRAW_COLOR_HISTOGRAM +#property indicator_color2 CLR_NONE, clrGreen, clrDarkRed +#property indicator_style2 STYLE_DOT +#property indicator_width2 1 + +// +#define deltaMaBufferIndex 3 +double deltaMaBuffer[]; + +#property indicator_label3 "Delta MA" +#property indicator_type3 DRAW_LINE +#property indicator_color3 clrOrchid +#property indicator_style3 STYLE_SOLID +#property indicator_width3 1 + +// +// Data Buffers ... + +#define mLastBufferIndex 3 + +// +#define rawDeltaBufferIndex mLastBufferIndex + 1 +double rawDeltaBuffer[]; + +// +#define deltaStateBufferIndex mLastBufferIndex + 2 +double deltaStateBuffer[]; + +// +// Variables, Properties and etc ... + +// +// this counts Available Bars ... +int limit; + +// +int maxLength; + +// +// Event Handlers ... + +/** + * Initialize Indicator ... + * + * @return ( int ) + */ +int OnInit() +{ + // + // Validate Inputs ... + if (!ValidateInputs()) + { + return INIT_PARAMETERS_INCORRECT; + } + + // + // Initialize Indicator Handlers ... + + // + // because in some cases we may have more than one input for + // calculation and we must prevent any calculation + // untill we pass the biggest input length, here we get max Input length + // and then wait until pass it ... + maxLength = ExtractMaxLengthOfInputs(); + + // + // Define Index Buffers ... + DefineBuffers(); + + // + // Set Indicator ShortName ... + SetIndicatorName(); + IndicatorSetInteger(INDICATOR_DIGITS, 2); + + // + // Init Succeed ... + return INIT_SUCCEEDED; +} + +/** + * De Initialize Indicator ... + * + * @param reason: Integer, De Initialization Reason ... + */ +void OnDeinit(const int reason) +{ + // + // REASON_PROGRAM 0 The EA has stopped working calling the ExpertRemove() function + // REASON_REMOVE 1 Program removed from a chart + // REASON_RECOMPILE 2 Program recompiled + // REASON_CHARTCHANGE 3 A symbol or a chart period is changed + // REASON_CHARTCLOSE 4 Chart closed + // REASON_PARAMETERS 5 Inputs changed by a user + // REASON_ACCOUNT 6 Another account has been activated or reconnection to the trade server has occurred due to changes in the account settings + // REASON_TEMPLATE 7 Another chart template applied + // REASON_INITFAILED 8 The OnInit() handler returned a non-zero value + // REASON_CLOSE 9 Terminal closed +} + +/** + * Calculate Bars ... + * + * @param rates_total: Integer, Total Bars on Chart ... + * @param prev_calculated: Integer, Total Calculated Bars on Charts ... + * @param time: DateTime Array, History of Open Time ... + * @param open: Double Array, History of Open Prices ... + * @param high: Double Array, History of High Prices ... + * @param low: Double Array, History of Low Prices ... + * @param close: Double Array, History of Close Prices ... + * @param tick_volume: Long, History of Tick Volumes on Bar ... + * @param volume: Long, History of Trade Volumes ... + * @param spread: Double, History of Spread Price ... + * + * @return ( int ) + */ +int OnCalculate( + const int rates_total, + const int prev_calculated, + const datetime &time[], + const double &open[], + const double &high[], + const double &low[], + const double &close[], + const long &tick_volume[], + const long &volume[], + const int &spread[] // +) +{ + // + // Prepare Buffers ... + ArraySetAsSeries(time, true); + ArraySetAsSeries(open, true); + ArraySetAsSeries(high, true); + ArraySetAsSeries(low, true); + ArraySetAsSeries(close, true); + ArraySetAsSeries(tick_volume, true); + ArraySetAsSeries(volume, true); + ArraySetAsSeries(spread, true); + + // + limit = (prev_calculated > rates_total || prev_calculated <= 0) + ? rates_total + : (rates_total - prev_calculated) + 1; + + // + // Main Loop ... + for (int i = limit - 1; i >= 0 && !IsStopped(); i--) + { + // + CalculateBuffers( + // + i, + prev_calculated, + rates_total, + // + open, + high, + close, + low, + tick_volume // + ); + } + + // + return rates_total; +} + +// +// Functions ... + +/** + * Validate Input Args for Initialization ... + * + * @return ( bool ) + */ +bool ValidateInputs() +{ + // + bool result = false; + + // + result = maLength > 0 && + IsValid(maMethod); + + // + return result; +} + +/** + * Extract Max Length of Inputs ... + * + * @return ( int ) + */ +int ExtractMaxLengthOfInputs() +{ + // + int result = 0; + + // + result = MathMax(0, maLength); + + // + return result; +} + +/** + * Set Indicator Short Name and also we can define Buffers Labels ... + */ +void SetIndicatorName() +{ + IndicatorSetString(INDICATOR_SHORTNAME, ShortName); +} + +/** + * Define Required Buffers ... + */ +void DefineBuffers() +{ + // + // Plot Buffers ... + + // + // Delta Line ... + ENUM_DRAW_TYPE deltaLineDrawType = showDeltaLine ? DRAW_LINE : DRAW_NONE; + + // + ArraySetAsSeries(deltaLineBuffer, true); + SetIndexBuffer(deltaLineBufferIndex, deltaLineBuffer, INDICATOR_DATA); + PlotIndexSetDouble(deltaLineBufferIndex, PLOT_EMPTY_VALUE, 0.0); + PlotIndexSetInteger(deltaLineBufferIndex, PLOT_SHOW_DATA, showDeltaLine); + PlotIndexSetInteger(deltaLineBufferIndex, PLOT_DRAW_TYPE, deltaLineDrawType); + + // + // Delta Histogram ... + ENUM_DRAW_TYPE deltaHistogramDrawType = showDeltaHistogram ? DRAW_COLOR_HISTOGRAM : DRAW_NONE; + + // + ArraySetAsSeries(deltaHistogramBuffer, true); + SetIndexBuffer(deltaHistogramBufferIndex, deltaHistogramBuffer, INDICATOR_DATA); + PlotIndexSetDouble(deltaHistogramBufferIndex, PLOT_EMPTY_VALUE, 0.0); + PlotIndexSetInteger(deltaHistogramBufferIndex, PLOT_SHOW_DATA, showDeltaHistogram); + PlotIndexSetInteger(deltaHistogramBufferIndex, PLOT_DRAW_TYPE, deltaHistogramDrawType); + + // + ArraySetAsSeries(deltaHistogramColorBuffer, true); + SetIndexBuffer(deltaHistogramColorBufferIndex, deltaHistogramColorBuffer, INDICATOR_COLOR_INDEX); + + // + // Delta Ma ... + ENUM_DRAW_TYPE deltaMaDrawType = showDeltaMa ? DRAW_LINE : DRAW_NONE; + + // + ArraySetAsSeries(deltaMaBuffer, true); + SetIndexBuffer(deltaMaBufferIndex, deltaMaBuffer, INDICATOR_DATA); + PlotIndexSetDouble(deltaMaBufferIndex, PLOT_EMPTY_VALUE, EMPTY_VALUE); + PlotIndexSetInteger(deltaMaBufferIndex, PLOT_SHOW_DATA, showDeltaMa); + PlotIndexSetInteger(deltaMaBufferIndex, PLOT_DRAW_TYPE, deltaMaDrawType); + + // + // Data Buffers ... + + // + ArraySetAsSeries(rawDeltaBuffer, true); + SetIndexBuffer(rawDeltaBufferIndex, rawDeltaBuffer, INDICATOR_CALCULATIONS); + + // + ArraySetAsSeries(deltaStateBuffer, true); + SetIndexBuffer(deltaStateBufferIndex, deltaStateBuffer, INDICATOR_CALCULATIONS); +} + +/** + * Calculate Custom Buffers ... + * + * @param bar_index: Integer, Represent Current Bar ... + * @param prevCalculated: Integer, Represent Previous Calculated Bars ... + * @param ratesTotal: Integer, Represents All Available Bars ... + * @param open: Double Array, History of Open Prices ... + * @param high: Double Array, History of High Prices ... + * @param close: Double Array, History of Close Prices ... + * @param low: Double Array, History of Low Prices ... + * @param tickVolume: Long, History of Tick Volumes on Bar ... + */ +void CalculateBuffers( + int bar_index, // Selected Bar Index + const int prevCalculated, + const int ratesTotal, + const double &open[], + const double &high[], + const double &close[], + const double &low[], + const long &tickVolume[] // +) +{ + // + int barsLimit = startCalculationForLastBars > 0 + ? startCalculationForLastBars + : 0; + // + // bool canCalculate = true; + bool canCalculate = + barsLimit == 0 || + bar_index <= barsLimit; + if (canCalculate) + { + // + CalculateValues( + bar_index, + prevCalculated, + ratesTotal, + open, + high, + close, + low, + tickVolume // + ); + } + else + { + FillBuffersZero(bar_index); + } +} + +/** + * Fill All Bufers to Zero Vlue for Specified Bar Index ... + * + * @param barIndex: Integer ... + */ +void FillBuffersZero(int barIndex) +{ + // + rawDeltaBuffer[barIndex] = 0.0; + deltaLineBuffer[barIndex] = 0.0; + deltaStateBuffer[barIndex] = 0.0; + deltaHistogramBuffer[barIndex] = 0.0; + deltaMaBuffer[barIndex] = 0.0; + deltaHistogramColorBuffer[barIndex] = hideColorIDX; +} + +/** + * Calculate Vales ... + * + * @param bar_index: Integer, Represent Current Bar ... + * @param prevCalculated: Integer, Represent Previous Calculated Bars ... + * @param ratesTotal: Integer, Represents All Available Bars ... + * @param open: Double Array, History of Open Prices ... + * @param high: Double Array, History of High Prices ... + * @param close: Double Array, History of Close Prices ... + * @param low: Double Array, History of Low Prices ... + * @param tickVolume: Long, History of Tick Volumes on Bar ... + */ +void CalculateValues( + int bar_index, // Selected Bar Index + const int prevCalculated, + const int ratesTotal, + const double &open[], + const double &high[], + const double &close[], + const double &low[], + const long &tickVolume[] // +) +{ + // + XOHCL bar; + bool has = bar.Init( + _Symbol, + _Period, + bar_index // + ); + if (!has) + { + return; + } + + // + double iDelta = 0.0; + + // + // Detecting Delta Volume ... + if (bar.IsBullish()) + { + iDelta = (double)bar.volume; + } + else if (bar.IsBearish()) + { + iDelta = -(double)bar.volume; + } + + // + // Checking First Bar Conditions ... + bool isFirstBar = + startCalculationForLastBars > 0 + ? bar_index == startCalculationForLastBars + : bar_index == ratesTotal; + if (isFirstBar) + { + // + rawDeltaBuffer[bar_index] = iDelta; + deltaLineBuffer[bar_index] = iDelta; + deltaHistogramBuffer[bar_index] = iDelta; + } + else + { + // + iDelta += deltaLineBuffer[bar_index + 1]; + + // + rawDeltaBuffer[bar_index] = iDelta; + deltaLineBuffer[bar_index] = iDelta; + deltaHistogramBuffer[bar_index] = iDelta; + } + + // + // Setting iDelta State ... + double iState = iDelta > 0 + ? bullishColorIDX + : iDelta < 0 + ? bearishColorIDX + : hideColorIDX; + // + // Setting iDelta Color ... + double iDeltaColor = iDelta > 0 + ? bullishColorIDX + : iDelta < 0 + ? bearishColorIDX + : hideColorIDX; + + // + deltaStateBuffer[bar_index] = iState; + deltaHistogramColorBuffer[bar_index] = iDeltaColor; + + // + // Calculate Moving Averages ... + int deltaMAsCount = iMAOnBuffer( + ratesTotal, + prevCalculated, + bar_index, + maLength, + rawDeltaBuffer, + deltaMaBuffer, + maMethod // + ); + + // + bar.Clean(); +} + +// diff --git a/BKPS/14040203/Indicators/x-saherelm.x121.xdon.mq5 b/BKPS/14040203/Indicators/x-saherelm.x121.xdon.mq5 new file mode 100644 index 0000000..49785d4 --- /dev/null +++ b/BKPS/14040203/Indicators/x-saherelm.x121.xdon.mq5 @@ -0,0 +1,692 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Indicator +// ------------------------------------------------- +// Name: X121 XDON +// Description: XDON ... +// +// +// 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 XDON Indicator" +#property strict + +// +// Definitions ... + +// +#define ShortName "X121 XDON" + +// +// Includes Common Library ... +#include "../Libraries/x-saherelm.common.lib.mq5" + +// +// Inputs ... + +// +// Market ... +input group "Market"; +input int donchainLength = 40; // Donchain Length + +// +// Presentation ... +input group "Presentation"; + +// +input int startCalculationForLastBars = 1000; // Calculate Last n Bars + +// +input bool showUpper = true; // Show Upper Band +input bool showLower = true; // Show Lower Band + +// +input bool showOpen = true; // Show Open +input bool showHigh = true; // Show High +input bool showClose = true; // Show Close +input bool showLow = true; // Show Low + +// +// Buffers ... + +// +#define hideColorIDX 0 +#define bullishColorIDX 1 +#define bearishColorIDX 2 +#define neuturalColorIDX 3 + +// +#property indicator_chart_window + +// +#property indicator_buffers 8 +#property indicator_plots 8 + +// +// Plot Buffers ... + +// +// Open ... + +// +#define donOpenUpperBufferIndex 0 +double donOpenUpperBuffer[]; + +// +#define donOpenUpperPlotBufferIndex 0 +#property indicator_label1 "X121 O U" +#property indicator_type1 DRAW_LINE +#property indicator_color1 clrCornflowerBlue +#property indicator_width1 1 + +// +#define donOpenLowerBufferIndex 1 +double donOpenLowerBuffer[]; + +// +#define donOpenLowerPlotBufferIndex 1 +#property indicator_label2 "X121 O L" +#property indicator_type2 DRAW_LINE +#property indicator_color2 clrCornflowerBlue +#property indicator_width2 1 + +// +// High ... + +// +#define donHighUpperBufferIndex 2 +double donHighUpperBuffer[]; + +// +#define donHighUpperPlotBufferIndex 2 +#property indicator_label3 "X121 H U" +#property indicator_type3 DRAW_LINE +#property indicator_color3 clrAquamarine +#property indicator_width3 1 + +// +#define donHighLowerBufferIndex 3 +double donHighLowerBuffer[]; + +// +#define donHighLowerPlotBufferIndex 3 +#property indicator_label4 "X121 H L" +#property indicator_type4 DRAW_LINE +#property indicator_color4 clrAquamarine +#property indicator_width4 1 + +// +// Low ... + +// +#define donLowUpperBufferIndex 4 +double donLowUpperBuffer[]; + +// +#define donLowUpperPlotBufferIndex 4 +#property indicator_label5 "X121 L U" +#property indicator_type5 DRAW_LINE +#property indicator_color5 clrDarkOrchid +#property indicator_width5 1 + +// +#define donLowLowerBufferIndex 5 +double donLowLowerBuffer[]; + +// +#define donLowLowerPlotBufferIndex 5 +#property indicator_label6 "X121 L L" +#property indicator_type6 DRAW_LINE +#property indicator_color6 clrDarkOrchid +#property indicator_width6 1 + +// +// Close ... + +// +#define donCloseUpperBufferIndex 6 +double donCloseUpperBuffer[]; + +// +#define donCloseUpperPlotBufferIndex 6 +#property indicator_label7 "X121 C U" +#property indicator_type7 DRAW_LINE +#property indicator_color7 clrCoral +#property indicator_width7 1 + +// +#define donCloseLowerBufferIndex 7 +double donCloseLowerBuffer[]; + +// +#define donCloseLowerPlotBufferIndex 7 +#property indicator_label8 "X121 C L" +#property indicator_type8 DRAW_LINE +#property indicator_color8 clrCoral +#property indicator_width8 1 + +// +// Data Buffers ... + +// +int mLastBufferIndex = 7; + +// +// Variables, Properties and etc ... + +// +// this counts Available Bars ... +int limit; + +// +int maxLength; + +// +// Event Handlers ... + +/** + * Initialize Indicator ... + * + * @return ( int ) + */ +int OnInit() +{ + // + // Validate Inputs ... + if (!ValidateInputs()) + { + return INIT_PARAMETERS_INCORRECT; + } + + // + // Initialize Indicator Handlers ... + + // + // because in some cases we may have more than one input for + // calculation and we must prevent any calculation + // untill we pass the biggest input length, here we get max Input length + // and then wait until pass it ... + maxLength = ExtractMaxLengthOfInputs(); + + // + // Define Index Buffers ... + DefineBuffers(); + + // + // Set Indicator ShortName ... + SetIndicatorName(); + + // + // Init Succeed ... + return INIT_SUCCEEDED; +} + +/** + * De Initialize Indicator ... + * + * @param reason: Integer, De Initialization Reason ... + */ +void OnDeinit(const int reason) +{ + // + // REASON_PROGRAM 0 The EA has stopped working calling the ExpertRemove() function + // REASON_REMOVE 1 Program removed from a chart + // REASON_RECOMPILE 2 Program recompiled + // REASON_CHARTCHANGE 3 A symbol or a chart period is changed + // REASON_CHARTCLOSE 4 Chart closed + // REASON_PARAMETERS 5 Inputs changed by a user + // REASON_ACCOUNT 6 Another account has been activated or reconnection to the trade server has occurred due to changes in the account settings + // REASON_TEMPLATE 7 Another chart template applied + // REASON_INITFAILED 8 The OnInit() handler returned a non-zero value + // REASON_CLOSE 9 Terminal closed +} + +/** + * Calculate Bars ... + * + * @param rates_total: Integer, Total Bars on Chart ... + * @param prev_calculated: Integer, Total Calculated Bars on Charts ... + * @param time: DateTime Array, History of Open Time ... + * @param open: Double Array, History of Open Prices ... + * @param high: Double Array, History of High Prices ... + * @param low: Double Array, History of Low Prices ... + * @param close: Double Array, History of Close Prices ... + * @param tick_volume: Long, History of Tick Volumes on Bar ... + * @param volume: Long, History of Trade Volumes ... + * @param spread: Double, History of Spread Price ... + * + * @return ( int ) + */ +int OnCalculate( + const int rates_total, + const int prev_calculated, + const datetime &time[], + const double &open[], + const double &high[], + const double &low[], + const double &close[], + const long &tick_volume[], + const long &volume[], + const int &spread[] // +) +{ + // + // Prepare Buffers ... + ArraySetAsSeries(time, true); + ArraySetAsSeries(open, true); + ArraySetAsSeries(high, true); + ArraySetAsSeries(low, true); + ArraySetAsSeries(close, true); + ArraySetAsSeries(tick_volume, true); + ArraySetAsSeries(volume, true); + ArraySetAsSeries(spread, true); + + // + // Validate Calculated Bars ... + + // + limit = (prev_calculated > rates_total || prev_calculated <= 0) + ? rates_total + : (rates_total - prev_calculated) + 1; + + // + // Buffers Copy ... + + // + // Main Loop ... + for (int i = limit - 1; i >= 0 && !IsStopped(); i--) + { + // + CalculateBuffers( + i, + prev_calculated, + rates_total, + // + open, + high, + close, + low, + tick_volume // + ); + } + + // + return rates_total; +} + +// +// Functions ... + +/** + * Validate Input Args for Initialization ... + * + * @return ( bool ) + */ +bool ValidateInputs() +{ + // + bool result = false; + + // + result = + // + donchainLength > 0 + // + ; + + // + return result; +} + +/** + * Extract Max Length of Inputs ... + * + * @return ( int ) + */ +int ExtractMaxLengthOfInputs() +{ + // + int result = 0; + + // + return result; +} + +/** + * Define Required Buffers ... + */ +void DefineBuffers() +{ + // + // Plot Buffers ... + // + // Open ... + + // + // UPPER ... + bool canShowCOpenUpper = showUpper && showOpen; + ENUM_DRAW_TYPE donOpenUpperDrawType = canShowCOpenUpper ? DRAW_LINE : DRAW_NONE; + ArraySetAsSeries(donOpenUpperBuffer, true); + SetIndexBuffer(donOpenUpperBufferIndex, donOpenUpperBuffer, INDICATOR_DATA); + PlotIndexSetDouble(donOpenUpperPlotBufferIndex, PLOT_EMPTY_VALUE, EMPTY_VALUE); + PlotIndexSetInteger(donOpenUpperPlotBufferIndex, PLOT_SHOW_DATA, canShowCOpenUpper); + PlotIndexSetInteger(donOpenUpperPlotBufferIndex, PLOT_DRAW_TYPE, donOpenUpperDrawType); + + // + // LOWER ... + bool canShowCOpenLower = showLower && showOpen; + ENUM_DRAW_TYPE donOpenLowerDrawType = canShowCOpenLower ? DRAW_LINE : DRAW_NONE; + ArraySetAsSeries(donOpenLowerBuffer, true); + SetIndexBuffer(donOpenLowerBufferIndex, donOpenLowerBuffer, INDICATOR_DATA); + PlotIndexSetDouble(donOpenLowerPlotBufferIndex, PLOT_EMPTY_VALUE, EMPTY_VALUE); + PlotIndexSetInteger(donOpenLowerPlotBufferIndex, PLOT_SHOW_DATA, canShowCOpenLower); + PlotIndexSetInteger(donOpenLowerPlotBufferIndex, PLOT_DRAW_TYPE, donOpenLowerDrawType); + + // + // Close ... + + // + // UPPER ... + bool canShowCCloseUpper = showUpper && showClose; + ENUM_DRAW_TYPE donCloseUpperDrawType = canShowCCloseUpper ? DRAW_LINE : DRAW_NONE; + ArraySetAsSeries(donCloseUpperBuffer, true); + SetIndexBuffer(donCloseUpperBufferIndex, donCloseUpperBuffer, INDICATOR_DATA); + PlotIndexSetDouble(donCloseUpperPlotBufferIndex, PLOT_EMPTY_VALUE, EMPTY_VALUE); + PlotIndexSetInteger(donCloseUpperPlotBufferIndex, PLOT_SHOW_DATA, canShowCCloseUpper); + PlotIndexSetInteger(donCloseUpperPlotBufferIndex, PLOT_DRAW_TYPE, donCloseUpperDrawType); + + // + // LOWER ... + bool canShowCCloseLower = showLower && showClose; + ENUM_DRAW_TYPE donCloseLowerDrawType = canShowCCloseLower ? DRAW_LINE : DRAW_NONE; + ArraySetAsSeries(donCloseLowerBuffer, true); + SetIndexBuffer(donCloseLowerBufferIndex, donCloseLowerBuffer, INDICATOR_DATA); + PlotIndexSetDouble(donCloseLowerPlotBufferIndex, PLOT_EMPTY_VALUE, EMPTY_VALUE); + PlotIndexSetInteger(donCloseLowerPlotBufferIndex, PLOT_SHOW_DATA, canShowCCloseLower); + PlotIndexSetInteger(donCloseLowerPlotBufferIndex, PLOT_DRAW_TYPE, donCloseLowerDrawType); + + // + // High ... + + // + // UPPER ... + bool canShowCHighUpper = showUpper && showHigh; + ENUM_DRAW_TYPE donHighUpperDrawType = canShowCHighUpper ? DRAW_LINE : DRAW_NONE; + ArraySetAsSeries(donHighUpperBuffer, true); + SetIndexBuffer(donHighUpperBufferIndex, donHighUpperBuffer, INDICATOR_DATA); + PlotIndexSetDouble(donHighUpperPlotBufferIndex, PLOT_EMPTY_VALUE, EMPTY_VALUE); + PlotIndexSetInteger(donHighUpperPlotBufferIndex, PLOT_SHOW_DATA, canShowCHighUpper); + PlotIndexSetInteger(donHighUpperPlotBufferIndex, PLOT_DRAW_TYPE, donHighUpperDrawType); + + // + // LOWER ... + bool canShowCHighLower = showLower && showHigh; + ENUM_DRAW_TYPE donHighLowerDrawType = canShowCHighLower ? DRAW_LINE : DRAW_NONE; + ArraySetAsSeries(donHighLowerBuffer, true); + SetIndexBuffer(donHighLowerBufferIndex, donHighLowerBuffer, INDICATOR_DATA); + PlotIndexSetDouble(donHighLowerPlotBufferIndex, PLOT_EMPTY_VALUE, EMPTY_VALUE); + PlotIndexSetInteger(donHighLowerPlotBufferIndex, PLOT_SHOW_DATA, canShowCHighLower); + PlotIndexSetInteger(donHighLowerPlotBufferIndex, PLOT_DRAW_TYPE, donHighLowerDrawType); + + // + // Low ... + + // + // UPPER ... + bool canShowCLowUpper = showUpper && showLow; + ENUM_DRAW_TYPE donLowUpperDrawType = canShowCLowUpper ? DRAW_LINE : DRAW_NONE; + ArraySetAsSeries(donLowUpperBuffer, true); + SetIndexBuffer(donLowUpperBufferIndex, donLowUpperBuffer, INDICATOR_DATA); + PlotIndexSetDouble(donLowUpperPlotBufferIndex, PLOT_EMPTY_VALUE, EMPTY_VALUE); + PlotIndexSetInteger(donLowUpperPlotBufferIndex, PLOT_SHOW_DATA, canShowCLowUpper); + PlotIndexSetInteger(donLowUpperPlotBufferIndex, PLOT_DRAW_TYPE, donLowUpperDrawType); + + // + // LOWER ... + bool canShowCLowLower = showLower && showLow; + ENUM_DRAW_TYPE donLowLowerDrawType = canShowCLowLower ? DRAW_LINE : DRAW_NONE; + ArraySetAsSeries(donLowLowerBuffer, true); + SetIndexBuffer(donLowLowerBufferIndex, donLowLowerBuffer, INDICATOR_DATA); + PlotIndexSetDouble(donLowLowerPlotBufferIndex, PLOT_EMPTY_VALUE, EMPTY_VALUE); + PlotIndexSetInteger(donLowLowerPlotBufferIndex, PLOT_SHOW_DATA, canShowCLowLower); + PlotIndexSetInteger(donLowLowerPlotBufferIndex, PLOT_DRAW_TYPE, donLowLowerDrawType); + + // + // Data Buffers ... +} + +/** + * Set Indicator Short Name and also we can define Buffers Labels ... + */ +void SetIndicatorName() +{ + IndicatorSetString(INDICATOR_SHORTNAME, ShortName); +} + +/** + * Calculate Custom Buffers ... + * + * @param bar_index: Integer, Represent Current Bar ... + * @param prevCalculated: Integer, Represent Previous Calculated Bars ... + * @param ratesTotal: Integer, Represents All Available Bars ... + * @param open: Double Array, History of Open Prices ... + * @param high: Double Array, History of High Prices ... + * @param close: Double Array, History of Close Prices ... + * @param low: Double Array, History of Low Prices ... + * @param tickVolume: Long, History of Tick Volumes on Bar ... + */ +void CalculateBuffers( + int bar_index, // Selected Bar Index + const int prevCalculated, + const int ratesTotal, + const double &open[], + const double &high[], + const double &close[], + const double &low[], + const long &tickVolume[] // +) +{ + // + int barsLimit = startCalculationForLastBars > 0 + ? startCalculationForLastBars + : 0; + // + // bool canCalculate = true; + bool canCalculate = + barsLimit == 0 || + bar_index <= barsLimit; + if (canCalculate) + { + // + CalculateDonchains( + bar_index, + prevCalculated, + ratesTotal, + open, + high, + close, + low, + tickVolume // + ); + } + else + { + FillBuffersZero(bar_index); + } +} + +// +// Custom ... + +/** + * Fill All Bufers to Zero Vlue for Specified Bar Index ... + * + * @param barIndex: Integer ... + */ +void FillBuffersZero(int barIndex) +{ + // + donOpenUpperBuffer[barIndex] = EMPTY_VALUE; + donOpenLowerBuffer[barIndex] = EMPTY_VALUE; + donCloseUpperBuffer[barIndex] = EMPTY_VALUE; + donCloseLowerBuffer[barIndex] = EMPTY_VALUE; + donHighUpperBuffer[barIndex] = EMPTY_VALUE; + donHighLowerBuffer[barIndex] = EMPTY_VALUE; + donLowUpperBuffer[barIndex] = EMPTY_VALUE; + donLowLowerBuffer[barIndex] = EMPTY_VALUE; +} + +/** + * Calculate Donchain ... + * + * @param bar_index: Integer, Bar Index ... + * @param prevCalculated: Integer, Represent Previous Calculated Bars ... + * @param ratesTotal: Integer, Represents All Available Bars ... + * @param open: Double Array, History of Open Prices ... + * @param high: Double Array, History of High Prices ... + * @param close: Double Array, History of Close Prices ... + * @param low: Double Array, History of Low Prices ... + * @param tickVolume: Long, History of Tick Volumes on Bar ... + * @param _length: Integer, Donchain Length ... + * @param _ouBuffer: Double Array Reference ... + * @param _olBuffer: Double Array Reference ... + * @param _huBuffer: Double Array Reference ... + * @param _hlBuffer: Double Array Reference ... + * @param _luBuffer: Double Array Reference ... + * @param _llBuffer: Double Array Reference ... + * @param _cuBuffer: Double Array Reference ... + * @param _clBuffer: Double Array Reference ... + */ +void CalculateDonchain( + int bar_index, // Selected Bar Index + const int prevCalculated, + const int ratesTotal, + // + const double &open[], + const double &high[], + const double &close[], + const double &low[], + const long &tickVolume[], + // + int _length, + // + double &_ouBuffer[], + double &_olBuffer[], + double &_huBuffer[], + double &_hlBuffer[], + double &_luBuffer[], + double &_llBuffer[], + double &_cuBuffer[], + double &_clBuffer[] // +) +{ + // + double iUpper = 0; + double iLower = 0; + + // + // OPEN ... + + // + int from = bar_index; + + // + iUpper = open[ArrayMaximum(open, from, _length)]; + iLower = open[ArrayMinimum(open, from, _length)]; + + // + _ouBuffer[bar_index] = iUpper; + _olBuffer[bar_index] = iLower; + + // + // HIGH ... + + // + iUpper = high[ArrayMaximum(high, from, _length)]; + iLower = high[ArrayMinimum(high, from, _length)]; + + // + _huBuffer[bar_index] = iUpper; + _hlBuffer[bar_index] = iLower; + + // + // LOW ... + + // + iUpper = low[ArrayMaximum(low, from, _length)]; + iLower = low[ArrayMinimum(low, from, _length)]; + + // + _luBuffer[bar_index] = iUpper; + _llBuffer[bar_index] = iLower; + + // + // CLOSE ... + + // + iUpper = close[ArrayMaximum(close, from, _length)]; + iLower = close[ArrayMinimum(close, from, _length)]; + + // + _cuBuffer[bar_index] = iUpper; + _clBuffer[bar_index] = iLower; +} + +/** + * Calculate Different VWaps ... + * + * @param bar_index: Integer, Represent Current Bar ... + * @param prevCalculated: Integer, Represent Previous Calculated Bars ... + * @param ratesTotal: Integer, Represents All Available Bars ... + * @param open: Double Array, History of Open Prices ... + * @param high: Double Array, History of High Prices ... + * @param close: Double Array, History of Close Prices ... + * @param low: Double Array, History of Low Prices ... + * @param tickVolume: Long, History of Tick Volumes on Bar ... + */ +void CalculateDonchains( + int bar_index, // Selected Bar Index + const int prevCalculated, + const int ratesTotal, + const double &open[], + const double &high[], + const double &close[], + const double &low[], + const long &tickVolume[] // +) +{ + // + CalculateDonchain( + // + bar_index, + prevCalculated, + ratesTotal, + // + open, + high, + close, + low, + tickVolume, + // + donchainLength, + // + donOpenUpperBuffer, + donOpenLowerBuffer, + donHighUpperBuffer, + donHighLowerBuffer, + donLowUpperBuffer, + donLowLowerBuffer, + donCloseUpperBuffer, + donCloseLowerBuffer // + ); +} + +// \ No newline at end of file diff --git a/BKPS/14040203/Indicators/x-saherelm.x121.xhk.mq5 b/BKPS/14040203/Indicators/x-saherelm.x121.xhk.mq5 new file mode 100644 index 0000000..c6a7cfe --- /dev/null +++ b/BKPS/14040203/Indicators/x-saherelm.x121.xhk.mq5 @@ -0,0 +1,616 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Indicator +// ------------------------------------------------- +// Name: X121 XHK +// Description: XHK ... +// +// +// 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 XHK Indicator" +#property strict + +// +// Definitions ... + +// +#define ShortName "X121 XHK" + +// +// Includes Common Library ... +#include "../Libraries/x-saherelm.common.lib.mq5" + +// +// Inputs ... + +// +// Market ... +input group "Market"; +input int xhkSmoothingLength = 14; // Length +input ENUM_X_MA_METHOD xhkSmoothingMode = X_MA_MODE_EMA; // Smoothing Method +input bool xhkIgnoreSmoothingShadows = false; // Ignore Smoothed Bar Shadows + +// +input group "Presentation"; + +// +input int startCalculationForLastBars = 1000; // Calculate Last n Bars + +// +input bool drawRawXHKCandles = true; // Draw Raw Candle +input bool drawSmoothedXHKCandles = true; // Draw Smoothed Candle + +// +// Buffers ... + +// +#property indicator_chart_window + +// +#property indicator_buffers 10 +#property indicator_plots 2 + +// +#define hideColorIDX 0 +#define bullishColorIDX 1 +#define bearishColorIDX 2 +#define neuturalColorIDX 3 + +// +// PLOTTED Buffers ... + +// +#define openHKBufferIndex 0 +double openHKBuffer[]; + +// +#define highHKBufferIndex 1 +double highHKBuffer[]; + +// +#define lowHKBufferIndex 2 +double lowHKBuffer[]; + +// +#define closeHKBufferIndex 3 +double closeHKBuffer[]; + +// +#define rawHKColorBufferIndex 4 +double rawHKColorBuffer[]; + +// +#define rawHKBufferIndex 0 +#property indicator_label1 "X121 XHK Open;X121 XHK High;X121 XHK Low;X121 XHK Close" +#property indicator_type1 DRAW_COLOR_CANDLES +#property indicator_color1 CLR_NONE, clrDodgerBlue, clrDarkGoldenrod + +// +// Open ... +#define openBufferIndex 5 +double openBuffer[]; + +// +// High ... +#define highBufferIndex 6 +double highBuffer[]; + +// +// Low ... +#define lowBufferIndex 7 +double lowBuffer[]; + +// +// Close ... +#define closeBufferIndex 8 +double closeBuffer[]; + +// +// Candle Color ... +#define candleColorBufferIndex 9 +double candleColorBuffer[]; + +// +#define candlesBufferIndex 1 +#property indicator_label2 "X121 XHKSM Open;X121 XHKSM High;X121 XHKSM Low;X121 XHKSM Close" +#property indicator_type2 DRAW_COLOR_CANDLES +#property indicator_color2 CLR_NONE, clrAqua, clrMagenta + +// +// Variables, Properties and etc ... + +// +// this counts Available Bars ... +int limit; + +// +int maxLength; + +// + +// +// Event Handlers ... + +/** + * Initialize Indicator ... + * + * @return ( int ) + */ +int OnInit() +{ + // + // Validate Inputs ... + if (!ValidateInputs()) + { + return INIT_PARAMETERS_INCORRECT; + } + + // + // Initialize Indicator Handlers ... + + // + // because in some cases we may have more than one input for + // calculation and we must prevent any calculation + // untill we pass the biggest input length, here we get max Input length + // and then wait until pass it ... + maxLength = ExtractMaxLengthOfInputs(); + + // + // Define Index Buffers ... + DefineBuffers(); + + // + // Set Indicator ShortName ... + SetIndicatorName(); + + // + // Init Succeed ... + return INIT_SUCCEEDED; +} + +/** + * De Initialize Indicator ... + * + * @param reason: Integer, De Initialization Reason ... + */ +void OnDeinit(const int reason) +{ + // + // REASON_PROGRAM 0 The EA has stopped working calling the ExpertRemove() function + // REASON_REMOVE 1 Program removed from a chart + // REASON_RECOMPILE 2 Program recompiled + // REASON_CHARTCHANGE 3 A symbol or a chart period is changed + // REASON_CHARTCLOSE 4 Chart closed + // REASON_PARAMETERS 5 Inputs changed by a user + // REASON_ACCOUNT 6 Another account has been activated or reconnection to the trade server has occurred due to changes in the account settings + // REASON_TEMPLATE 7 Another chart template applied + // REASON_INITFAILED 8 The OnInit() handler returned a non-zero value + // REASON_CLOSE 9 Terminal closed + + // +} + +/** + * Calculate Bars ... + * + * @param rates_total: Integer, Total Bars on Chart ... + * @param prev_calculated: Integer, Total Calculated Bars on Charts ... + * @param time: DateTime Array, History of Open Time ... + * @param open: Double Array, History of Open Prices ... + * @param high: Double Array, History of High Prices ... + * @param low: Double Array, History of Low Prices ... + * @param close: Double Array, History of Close Prices ... + * @param tick_volume: Long, History of Tick Volumes on Bar ... + * @param volume: Long, History of Trade Volumes ... + * @param spread: Double, History of Spread Price ... + * + * @return ( int ) + */ +int OnCalculate( + const int rates_total, + const int prev_calculated, + const datetime &time[], + const double &open[], + const double &high[], + const double &low[], + const double &close[], + const long &tick_volume[], + const long &volume[], + const int &spread[] // +) +{ + // + // Prepare Buffers ... + ArraySetAsSeries(time, true); + ArraySetAsSeries(open, true); + ArraySetAsSeries(high, true); + ArraySetAsSeries(low, true); + ArraySetAsSeries(close, true); + ArraySetAsSeries(tick_volume, true); + ArraySetAsSeries(volume, true); + ArraySetAsSeries(spread, true); + + // + // Fill All Buffers by Zero ... + if (prev_calculated == 0) + { + } + + // + limit = (prev_calculated > rates_total || prev_calculated <= 0) + ? rates_total + : (rates_total - prev_calculated) + 1; + + // + // Main Loop ... + for (int i = limit - 1; i >= 0 && !IsStopped(); i--) + { + // + CalculateBuffers( + i, + prev_calculated, + rates_total, + // + open, + high, + close, + low, + tick_volume // + ); + } + + // + return rates_total; +} + +// +// Functions ... + +/** + * Validate Input Args for Initialization ... + * + * @return ( bool ) + */ +bool ValidateInputs() +{ + // + bool result = + // + true + // + ; + + // + return result; +} + +/** + * Extract Max Length of Inputs ... + * + * @return ( int ) + */ +int ExtractMaxLengthOfInputs() +{ + // + int result = 0; + + // + result = MathMax(0, xhkSmoothingLength); + + // + return result; +} + +/** + * Define Required Buffers ... + */ +void DefineBuffers() +{ + + // + // RAW ... + + // + // Raw Candles Color ... + ArraySetAsSeries(rawHKColorBuffer, true); + SetIndexBuffer(rawHKColorBufferIndex, rawHKColorBuffer, INDICATOR_COLOR_INDEX); + + // + // Set EMPTY_VALUE on Candles Buffer ... + PlotIndexSetDouble(rawHKBufferIndex, PLOT_EMPTY_VALUE, 0.0); + PlotIndexSetInteger(rawHKBufferIndex, PLOT_SHOW_DATA, false); + + // + // Open ... + ArraySetAsSeries(openHKBuffer, true); + SetIndexBuffer(openHKBufferIndex, openHKBuffer, INDICATOR_DATA); + + // + // High ... + ArraySetAsSeries(highHKBuffer, true); + SetIndexBuffer(highHKBufferIndex, highHKBuffer, INDICATOR_DATA); + + // + // Close ... + ArraySetAsSeries(closeHKBuffer, true); + SetIndexBuffer(closeHKBufferIndex, closeHKBuffer, INDICATOR_DATA); + + // + // Low ... + ArraySetAsSeries(lowHKBuffer, true); + SetIndexBuffer(lowHKBufferIndex, lowHKBuffer, INDICATOR_DATA); + + // + // SMOOTHED ... + + // + // Candles Color ... + ArraySetAsSeries(candleColorBuffer, true); + SetIndexBuffer(candleColorBufferIndex, candleColorBuffer, INDICATOR_COLOR_INDEX); + + // + // Set EMPTY_VALUE on Candles Buffer ... + PlotIndexSetDouble(candlesBufferIndex, PLOT_EMPTY_VALUE, 0.0); + PlotIndexSetInteger(candlesBufferIndex, PLOT_SHOW_DATA, false); + + // + // Open ... + ArraySetAsSeries(openBuffer, true); + SetIndexBuffer(openBufferIndex, openBuffer, INDICATOR_DATA); + + // + // High ... + ArraySetAsSeries(highBuffer, true); + SetIndexBuffer(highBufferIndex, highBuffer, INDICATOR_DATA); + + // + // Close ... + ArraySetAsSeries(closeBuffer, true); + SetIndexBuffer(closeBufferIndex, closeBuffer, INDICATOR_DATA); + + // + // Low ... + ArraySetAsSeries(lowBuffer, true); + SetIndexBuffer(lowBufferIndex, lowBuffer, INDICATOR_DATA); +} + +/** + * Set Indicator Short Name and also we can define Buffers Labels ... + */ +void SetIndicatorName() +{ + IndicatorSetString(INDICATOR_SHORTNAME, ShortName); +} + +/** + * Calculate Custom Buffers ... + * + * @param bar_index: Integer, Represent Current Bar ... + * @param prevCalculated: Integer, Represent Previous Calculated Bars ... + * @param ratesTotal: Integer, Represents All Available Bars ... + * @param open: Double Array, History of Open Prices ... + * @param high: Double Array, History of High Prices ... + * @param close: Double Array, History of Close Prices ... + * @param low: Double Array, History of Low Prices ... + * @param tickVolume: Long, History of Tick Volumes on Bar ... + */ +void CalculateBuffers( + int bar_index, // Selected Bar Index + const int prevCalculated, + const int ratesTotal, + const double &open[], + const double &high[], + const double &close[], + const double &low[], + const long &tickVolume[] // +) +{ + // + int barsLimit = startCalculationForLastBars > 0 + ? startCalculationForLastBars + : 0; + // + bool canCalculate = + barsLimit == 0 || + bar_index <= barsLimit; + if (canCalculate) + { + // + CalculateXHK( + bar_index, + prevCalculated, + ratesTotal, + open, + high, + close, + low // + ); + } + else + { + FillBuffersZero(bar_index); + } +} + +// +// Custom ... + +/** + * Fill All Bufers to Zero Vlue for Specified Bar Index ... + * + * @param barIndex: Integer ... + */ +void FillBuffersZero(int barIndex) +{ + // + lowHKBuffer[barIndex] = 0.0; + openHKBuffer[barIndex] = 0.0; + highHKBuffer[barIndex] = 0.0; + closeHKBuffer[barIndex] = 0.0; + rawHKColorBuffer[barIndex] = hideColorIDX; + + // + lowBuffer[barIndex] = 0.0; + openBuffer[barIndex] = 0.0; + highBuffer[barIndex] = 0.0; + closeBuffer[barIndex] = 0.0; + candleColorBuffer[barIndex] = hideColorIDX; +} + +/** + * Calculate ATR Zones ... + * + * @param bar_index: Integer, Represent Current Bar ... + * @param prevCalculated: Integer, Represent Previous Calculated Bars ... + * @param ratesTotal: Integer, Represents All Available Bars ... + * @param open: Double Array, History of Open Prices ... + * @param high: Double Array, History of High Prices ... + * @param close: Double Array, History of Close Prices ... + * @param low: Double Array, History of Low Prices ... + */ +void CalculateXHK( + 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 = openHKBuffer[bar_index + 1]; + mPrevHKCloseValue = closeHKBuffer[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)); + + // + double candleColorValue = + mHKOpenValue < mHKCloseValue ? bullishColorIDX : bearishColorIDX; + + // + // Raw HK Buffers ... + openHKBuffer[bar_index] = mHKOpenValue; + highHKBuffer[bar_index] = mHKHighValue; + lowHKBuffer[bar_index] = mHKLowValue; + closeHKBuffer[bar_index] = mHKCloseValue; + rawHKColorBuffer[bar_index] = drawRawXHKCandles ? candleColorValue : hideColorIDX; + + // + // Apply Smoothing ... + bool canSmooth = xhkSmoothingLength > 0 && + xhkSmoothingMode != X_MA_MODE_NONE; + if (!canSmooth) + { + // + double min = MathMin(mHKOpenValue, mHKCloseValue); + double max = MathMax(mHKOpenValue, mHKCloseValue); + + // + openBuffer[bar_index] = mHKOpenValue; + highBuffer[bar_index] = xhkIgnoreSmoothingShadows ? max : mHKHighValue; + lowBuffer[bar_index] = xhkIgnoreSmoothingShadows ? min : mHKLowValue; + closeBuffer[bar_index] = mHKCloseValue; + candleColorBuffer[bar_index] = drawSmoothedXHKCandles ? candleColorValue : hideColorIDX; + } + else + { + // + // Open ... + iMAOnBuffer( + ratesTotal, + prevCalculated, + bar_index, + xhkSmoothingLength, + openHKBuffer, + openBuffer, + xhkSmoothingMode // + ); + + // + // Close ... + iMAOnBuffer( + ratesTotal, + prevCalculated, + bar_index, + xhkSmoothingLength, + closeHKBuffer, + closeBuffer, + xhkSmoothingMode // + ); + + // + // Ignoring Shadows ... + if (!xhkIgnoreSmoothingShadows) + { + // + // High ... + iMAOnBuffer( + ratesTotal, + prevCalculated, + bar_index, + xhkSmoothingLength, + highHKBuffer, + highBuffer, + xhkSmoothingMode // + ); + + // + // Low ... + iMAOnBuffer( + ratesTotal, + prevCalculated, + bar_index, + xhkSmoothingLength, + lowHKBuffer, + lowBuffer, + xhkSmoothingMode // + ); + } + else + { + // + double min = MathMin(closeBuffer[bar_index], openBuffer[bar_index]); + double max = MathMin(closeBuffer[bar_index], openBuffer[bar_index]); + + // + lowBuffer[bar_index] = min; + highBuffer[bar_index] = max; + } + + // + // Calculate Smoothed Color ... + candleColorValue = + openBuffer[bar_index] < closeBuffer[bar_index] ? bullishColorIDX : bearishColorIDX; + candleColorBuffer[bar_index] = drawSmoothedXHKCandles ? candleColorValue : hideColorIDX; + } +} + +// \ No newline at end of file diff --git a/BKPS/14040203/Indicators/x-saherelm.x121.xich.mq5 b/BKPS/14040203/Indicators/x-saherelm.x121.xich.mq5 new file mode 100644 index 0000000..89b3fb8 --- /dev/null +++ b/BKPS/14040203/Indicators/x-saherelm.x121.xich.mq5 @@ -0,0 +1,625 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Indicator +// ------------------------------------------------- +// Name: X121 XWZ +// Description: XWZ ... +// +// +// 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 XWZ Indicator" +#property strict + +// +// Definitions ... + +// +#define ShortName "X121_XICH" + +// +// Imports ... +#include "../Libraries/x-saherelm.common.lib.mq5" + +// +// Inputs ... + +// +// Market ... +input group "Market"; +input ENUM_X_PRICE chikouSpanMode = X_PRICE_CLOSE; // ChikouSpan Mode +input int tenkanSenLength = 9; // TenkanSen Length +input ENUM_X_BOUNDARY_PRICE tenkanSenMode = X_BOUNDARY_PRICE_HIGH_LOW; // TencanSen Mode +input int kijunSenLength = 26; // KijunSen Length +input ENUM_X_BOUNDARY_PRICE kijunSenMode = X_BOUNDARY_PRICE_HIGH_LOW; // KijunSen Mode +input int senkouSpanBLength = 52; // SenkouSpan B Length +input ENUM_X_BOUNDARY_PRICE senkouSpanBMode = X_BOUNDARY_PRICE_HIGH_LOW; // SenkouSpan B Mode + +// +// Presentation ... +input group "Presentation"; + +// +input int startCalculationForLastBars = 1000; // Calculate Last n Bars +input bool shiftKumo = true; // Shift Kumo +input bool showTenkanSen = true; // Show TenkanSen +input bool showKijunSen = true; // Show KijunSen +input bool showChikouSpan = true; // Show ChikouSpan +input bool showSenkouSpanA = true; // Show Senkou Span A +input bool showSenkouSpanB = true; // Show Senkou Span B +input bool showKumo = true; // Show Kumo + +// +// Buffers ... + +// +#define hideColorIDX 0 +#define bullishColorIDX 1 +#define bearishColorIDX 2 +#define neuturalColorIDX 3 + +// +#property indicator_chart_window + +// +#property indicator_buffers 8 +#property indicator_plots 6 + +// +// Plot Buffers ... + +// +#define tenkanSenBufferIndex 0 +double tenkanSenBuffer[]; + +// +#property indicator_label1 "XICH TK" +#property indicator_type1 DRAW_LINE +#property indicator_color1 clrBrown +#property indicator_style1 STYLE_SOLID +#property indicator_width1 2 + +// +#define kijunSenBufferIndex 1 +double kijunSenBuffer[]; + +// +#property indicator_label2 "XICH KJ" +#property indicator_type2 DRAW_LINE +#property indicator_color2 clrDodgerBlue +#property indicator_style2 STYLE_SOLID +#property indicator_width2 2 + +// +#define chikouSpanBufferIndex 2 +double chikouSpanBuffer[]; + +// +#property indicator_label3 "XICH CS" +#property indicator_type3 DRAW_LINE +#property indicator_color3 clrDarkGreen +#property indicator_style3 STYLE_SOLID +#property indicator_width3 2 + +// +#define senkouSpanABufferIndex 3 +double senkouSpanABuffer[]; + +// +#property indicator_label4 "XICH SSA" +#property indicator_type4 DRAW_LINE +#property indicator_color4 clrLightGray +#property indicator_style4 STYLE_DASHDOTDOT +#property indicator_width4 2 + +// +#define senkouSpanBBufferIndex 4 +double senkouSpanBBuffer[]; + +// +#property indicator_label5 "XICH SSB" +#property indicator_type5 DRAW_LINE +#property indicator_color5 clrLightGray +#property indicator_style5 STYLE_DASHDOTDOT +#property indicator_width5 2 + +// +#define senkouABufferIndex 5 +double senkouABuffer[]; + +// +#define senkouBBufferIndex 6 +double senkouBBuffer[]; + +// +#define kumoBufferIndex 5 + +// +#property indicator_label6 "XICH Kumo" +#property indicator_type6 DRAW_FILLING +#property indicator_color6 clrAqua, clrMagenta +#property indicator_style6 STYLE_SOLID +#property indicator_width6 2 + +// +// Data Buffers ... + +// +int mLastBufferIndex = 6; + +// +// Variables, Properties and etc ... + +// +// this counts Available Bars ... +int limit; + +// +int maxLength; + +// +// Event Handlers ... + +/** + * Initialize Indicator ... + * + * @return ( int ) + */ +int OnInit() +{ + // + // Validate Inputs ... + if (!ValidateInputs()) + { + return INIT_PARAMETERS_INCORRECT; + } + + // + // because in some cases we may have more than one input for + // calculation and we must prevent any calculation + // untill we pass the biggest input length, here we get max Input length + // and then wait until pass it ... + maxLength = ExtractMaxLengthOfInputs(); + + // + // Define Index Buffers ... + DefineBuffers(); + + // + // Set Indicator ShortName ... + SetIndicatorName(); + IndicatorSetInteger(INDICATOR_DIGITS, 2); + + // + // Init Succeed ... + return INIT_SUCCEEDED; +} + +/** + * De Initialize Indicator ... + * + * @param reason: Integer, De Initialization Reason ... + */ +void OnDeinit(const int reason) +{ + // + // REASON_PROGRAM 0 The EA has stopped working calling the ExpertRemove() function + // REASON_REMOVE 1 Program removed from a chart + // REASON_RECOMPILE 2 Program recompiled + // REASON_CHARTCHANGE 3 A symbol or a chart period is changed + // REASON_CHARTCLOSE 4 Chart closed + // REASON_PARAMETERS 5 Inputs changed by a user + // REASON_ACCOUNT 6 Another account has been activated or reconnection to the trade server has occurred due to changes in the account settings + // REASON_TEMPLATE 7 Another chart template applied + // REASON_INITFAILED 8 The OnInit() handler returned a non-zero value + // REASON_CLOSE 9 Terminal closed +} + +/** + * Calculate Bars ... + * + * @param rates_total: Integer, Total Bars on Chart ... + * @param prev_calculated: Integer, Total Calculated Bars on Charts ... + * @param time: DateTime Array, History of Open Time ... + * @param open: Double Array, History of Open Prices ... + * @param high: Double Array, History of High Prices ... + * @param low: Double Array, History of Low Prices ... + * @param close: Double Array, History of Close Prices ... + * @param tick_volume: Long, History of Tick Volumes on Bar ... + * @param volume: Long, History of Trade Volumes ... + * @param spread: Double, History of Spread Price ... + * + * @return ( int ) + */ +int OnCalculate( + const int rates_total, + const int prev_calculated, + const datetime &time[], + const double &open[], + const double &high[], + const double &low[], + const double &close[], + const long &tick_volume[], + const long &volume[], + const int &spread[] // +) +{ + // + // Prepare Buffers ... + ArraySetAsSeries(time, true); + ArraySetAsSeries(open, true); + ArraySetAsSeries(high, true); + ArraySetAsSeries(low, true); + ArraySetAsSeries(close, true); + ArraySetAsSeries(tick_volume, true); + ArraySetAsSeries(volume, true); + ArraySetAsSeries(spread, true); + + // + limit = (prev_calculated > rates_total || prev_calculated <= 0) + ? rates_total + : (rates_total - prev_calculated) + 1; + + // + // Main Loop ... + for (int i = limit - 1; i >= 0 && !IsStopped(); i--) + { + // + CalculateBuffers( + // + i, + prev_calculated, + rates_total, + // + open, + high, + close, + low, + tick_volume // + ); + } + + // + return rates_total; +} + +// +// Functions ... + +/** + * Validate Input Args for Initialization ... + * + * @return ( bool ) + */ +bool ValidateInputs() +{ + // + bool result = false; + + // + result = + // + kijunSenLength > 0 && + tenkanSenLength > 0 && + senkouSpanBLength > 0 && + IsValid(kijunSenMode) && + IsValid(tenkanSenMode) && + IsValid(chikouSpanMode) && + IsValid(senkouSpanBMode) + // + ; + + // + return result; +} + +/** + * Extract Max Length of Inputs ... + * + * @return ( int ) + */ +int ExtractMaxLengthOfInputs() +{ + // + int result = 0; + + // + result = MathMax(kijunSenLength, tenkanSenLength); + result = MathMax(result, senkouSpanBLength); + + // + return result; +} + +/** + * Set Indicator Short Name and also we can define Buffers Labels ... + */ +void SetIndicatorName() +{ + IndicatorSetString(INDICATOR_SHORTNAME, ShortName); +} + +/** + * Define Required Buffers ... + */ +void DefineBuffers() +{ + // + ENUM_DRAW_TYPE tenkanSenDrawType = showTenkanSen ? DRAW_LINE : DRAW_NONE; + + // + ArraySetAsSeries(tenkanSenBuffer, true); + SetIndexBuffer(tenkanSenBufferIndex, tenkanSenBuffer, INDICATOR_DATA); + PlotIndexSetInteger(tenkanSenBufferIndex, PLOT_DRAW_BEGIN, maxLength); + PlotIndexSetInteger(tenkanSenBufferIndex, PLOT_SHOW_DATA, showTenkanSen); + PlotIndexSetInteger(tenkanSenBufferIndex, PLOT_DRAW_TYPE, tenkanSenDrawType); + + // + ENUM_DRAW_TYPE kijunSenDrawType = showKijunSen ? DRAW_LINE : DRAW_NONE; + + // + ArraySetAsSeries(kijunSenBuffer, true); + SetIndexBuffer(kijunSenBufferIndex, kijunSenBuffer, INDICATOR_DATA); + PlotIndexSetInteger(kijunSenBufferIndex, PLOT_DRAW_BEGIN, maxLength); + PlotIndexSetInteger(kijunSenBufferIndex, PLOT_SHOW_DATA, showKijunSen); + PlotIndexSetInteger(kijunSenBufferIndex, PLOT_DRAW_TYPE, kijunSenDrawType); + + // + ENUM_DRAW_TYPE chikouSpanDrawType = showChikouSpan ? DRAW_LINE : DRAW_NONE; + + // + ArraySetAsSeries(chikouSpanBuffer, true); + SetIndexBuffer(chikouSpanBufferIndex, chikouSpanBuffer, INDICATOR_DATA); + PlotIndexSetInteger(chikouSpanBufferIndex, PLOT_DRAW_BEGIN, maxLength); + PlotIndexSetInteger(chikouSpanBufferIndex, PLOT_SHIFT, -kijunSenLength); + PlotIndexSetInteger(chikouSpanBufferIndex, PLOT_SHOW_DATA, showChikouSpan); + PlotIndexSetInteger(chikouSpanBufferIndex, PLOT_DRAW_TYPE, chikouSpanDrawType); + + // + int shiftSize = shiftKumo ? kijunSenLength : 0; + + // + ENUM_DRAW_TYPE senkouSpanADrawType = showSenkouSpanA ? DRAW_LINE : DRAW_NONE; + + // + ArraySetAsSeries(senkouSpanABuffer, true); + SetIndexBuffer(senkouSpanABufferIndex, senkouSpanABuffer, INDICATOR_DATA); + PlotIndexSetInteger(senkouSpanABufferIndex, PLOT_SHIFT, shiftSize); + PlotIndexSetInteger(senkouSpanABufferIndex, PLOT_SHOW_DATA, showSenkouSpanA); + PlotIndexSetInteger(senkouSpanABufferIndex, PLOT_DRAW_TYPE, senkouSpanADrawType); + + // + ENUM_DRAW_TYPE senkouSpanBDrawType = showSenkouSpanB ? DRAW_LINE : DRAW_NONE; + + // + ArraySetAsSeries(senkouSpanBBuffer, true); + SetIndexBuffer(senkouSpanBBufferIndex, senkouSpanBBuffer, INDICATOR_DATA); + PlotIndexSetInteger(senkouSpanBBufferIndex, PLOT_SHIFT, shiftSize); + PlotIndexSetInteger(senkouSpanBBufferIndex, PLOT_SHOW_DATA, showSenkouSpanB); + PlotIndexSetInteger(senkouSpanBBufferIndex, PLOT_DRAW_TYPE, senkouSpanBDrawType); + + // + ArraySetAsSeries(senkouABuffer, true); + SetIndexBuffer(senkouABufferIndex, senkouABuffer, INDICATOR_DATA); + PlotIndexSetInteger(senkouABufferIndex, PLOT_DRAW_BEGIN, maxLength); + + // + ArraySetAsSeries(senkouBBuffer, true); + SetIndexBuffer(senkouBBufferIndex, senkouBBuffer, INDICATOR_DATA); + PlotIndexSetInteger(senkouBBufferIndex, PLOT_DRAW_BEGIN, maxLength); + + // + ENUM_DRAW_TYPE kumoDrawType = showKumo ? DRAW_FILLING : DRAW_NONE; + + // + PlotIndexSetInteger(kumoBufferIndex, PLOT_SHIFT, shiftSize); + PlotIndexSetInteger(kumoBufferIndex, PLOT_SHOW_DATA, false); + PlotIndexSetInteger(kumoBufferIndex, PLOT_DRAW_TYPE, kumoDrawType); +} + +/** + * Calculate Custom Buffers ... + * + * @param bar_index: Integer, Represent Current Bar ... + * @param prevCalculated: Integer, Represent Previous Calculated Bars ... + * @param ratesTotal: Integer, Represents All Available Bars ... + * @param open: Double Array, History of Open Prices ... + * @param high: Double Array, History of High Prices ... + * @param close: Double Array, History of Close Prices ... + * @param low: Double Array, History of Low Prices ... + * @param tickVolume: Long, History of Tick Volumes on Bar ... + */ +void CalculateBuffers( + int bar_index, // Selected Bar Index + const int prevCalculated, + const int ratesTotal, + const double &open[], + const double &high[], + const double &close[], + const double &low[], + const long &tickVolume[] // +) +{ + // + int barsLimit = startCalculationForLastBars > 0 + ? startCalculationForLastBars + : 0; + // + // bool canCalculate = true; + bool canCalculate = + barsLimit == 0 || + bar_index <= barsLimit; + if (canCalculate) + { + // + CalculateValues( + bar_index, + prevCalculated, + ratesTotal, + open, + high, + close, + low, + tickVolume // + ); + } + else + { + FillBuffersZero(bar_index); + } +} + +/** + * Fill All Bufers to Zero Vlue for Specified Bar Index ... + * + * @param barIndex: Integer ... + */ +void FillBuffersZero(int barIndex) +{ + // + senkouABuffer[barIndex] = 0; + senkouBBuffer[barIndex] = 0; + kijunSenBuffer[barIndex] = 0; + tenkanSenBuffer[barIndex] = 0; + chikouSpanBuffer[barIndex] = 0; + senkouSpanABuffer[barIndex] = 0; + senkouSpanBBuffer[barIndex] = 0; +} + +/** + * Calculate Vales ... + * + * @param bar_index: Integer, Represent Current Bar ... + * @param prevCalculated: Integer, Represent Previous Calculated Bars ... + * @param ratesTotal: Integer, Represents All Available Bars ... + * @param open: Double Array, History of Open Prices ... + * @param high: Double Array, History of High Prices ... + * @param close: Double Array, History of Close Prices ... + * @param low: Double Array, History of Low Prices ... + * @param tickVolume: Long, History of Tick Volumes on Bar ... + */ +void CalculateValues( + int bar_index, // Selected Bar Index + const int prevCalculated, + const int ratesTotal, + const double &open[], + const double &high[], + const double &close[], + const double &low[], + const long &tickVolume[] // +) +{ + // + double uppers[]; + double lowers[]; + + // + double uppersMax = 0; + double uppersMin = 0; + + // + double lowersMax = 0; + double lowersMin = 0; + + // + // Calculate ChikouSpan ... + double iChikouSpan = GetAppliedPrice( + _Symbol, + _Period, + bar_index, + chikouSpanMode // + ); + + // + // Calculate TenkanSen ... + GetPriceBoundary( + uppers, + lowers, + _Symbol, + _Period, + tenkanSenMode, + tenkanSenLength, + bar_index // + ); + + // + uppersMax = uppers[ArrayMaximum(uppers)]; + uppersMin = uppers[ArrayMinimum(uppers)]; + + // + lowersMax = lowers[ArrayMaximum(lowers)]; + lowersMin = lowers[ArrayMinimum(lowers)]; + + // + double iTenkanSen = (uppersMax + lowersMin) / 2; + + // + // Calculate KijunSen ... + GetPriceBoundary( + uppers, + lowers, + _Symbol, + _Period, + kijunSenMode, + kijunSenLength, + bar_index // + ); + + // + uppersMax = uppers[ArrayMaximum(uppers)]; + uppersMin = uppers[ArrayMinimum(uppers)]; + + // + lowersMax = lowers[ArrayMaximum(lowers)]; + lowersMin = lowers[ArrayMinimum(lowers)]; + + // + double iKijunSen = (uppersMax + lowersMin) / 2; + + // + // Calculate SenkouSpanB ... + GetPriceBoundary( + uppers, + lowers, + _Symbol, + _Period, + senkouSpanBMode, + senkouSpanBLength, + bar_index // + ); + + // + uppersMax = uppers[ArrayMaximum(uppers)]; + uppersMin = uppers[ArrayMinimum(uppers)]; + + // + lowersMax = lowers[ArrayMaximum(lowers)]; + lowersMin = lowers[ArrayMinimum(lowers)]; + + // + double iSenkouSpanB = (uppersMax + lowersMin) / 2; + + // + // Calculate SenkouSpanA ... + double iSenkouSpanA = (iTenkanSen + iKijunSen) / 2; + + // + // Setting Buffers ... + kijunSenBuffer[bar_index] = iKijunSen; + senkouABuffer[bar_index] = iSenkouSpanA; + senkouBBuffer[bar_index] = iSenkouSpanB; + tenkanSenBuffer[bar_index] = iTenkanSen; + chikouSpanBuffer[bar_index] = iChikouSpan; + senkouSpanABuffer[bar_index] = iSenkouSpanA; + senkouSpanBBuffer[bar_index] = iSenkouSpanB; +} + +// diff --git a/BKPS/14040203/Indicators/x-saherelm.x121.xmas.mq5 b/BKPS/14040203/Indicators/x-saherelm.x121.xmas.mq5 new file mode 100644 index 0000000..e35f97c --- /dev/null +++ b/BKPS/14040203/Indicators/x-saherelm.x121.xmas.mq5 @@ -0,0 +1,574 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Indicator +// ------------------------------------------------- +// Name: X121 XMAS +// Description: XMAS ... +// +// +// 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 XMAS Indicator" +#property strict + +// +// Definitions ... + +// +#define ShortName "X121_XMAS" + +// +// Imports ... +#include "../Libraries/x-saherelm.common.lib.mq5" + +// +// Inputs ... + +// +// Market ... +input group "Market"; +input int length = 14; // MA Length +input ENUM_MA_METHOD method = MODE_EMA; // MA Method +input ENUM_APPLIED_PRICE upperAppliedTo = PRICE_HIGH; // Upper Applied To +input ENUM_APPLIED_PRICE midAppliedTo = PRICE_MEDIAN; // Mid Applied To +input ENUM_APPLIED_PRICE lowerAppliedTo = PRICE_LOW; // Lower Applied To + +// +// Presentation ... +input group "Presentation"; + +// +input int startCalculationForLastBars = 1000; // Calculate Last n Bars +input bool showUpper = true; // Show Upper +input bool showMid = true; // Show Mid +input bool showLower = true; // Show Lower + +// +// Buffers ... + +// +#define hideColorIDX 0 +#define bullishColorIDX 1 +#define bearishColorIDX 2 +#define neuturalColorIDX 3 + +// +#property indicator_chart_window + +// +#property indicator_buffers 3 +#property indicator_plots 3 + +// +// Plot Buffers ... + +// +// UPPER ... +#define upperBufferIndex 0 +double upperBuffer[]; + +// +#property indicator_label1 "X121 MASU" +#property indicator_type1 DRAW_LINE +#property indicator_color1 clrAqua +#property indicator_style1 STYLE_SOLID +#property indicator_width1 1 + +// +// MID ... +#define midBufferIndex 1 +double midBuffer[]; + +// +#property indicator_label2 "X121 MASM" +#property indicator_type2 DRAW_LINE +#property indicator_color2 clrLightBlue +#property indicator_style2 STYLE_SOLID +#property indicator_width2 1 + +// +// LOWER ... +#define lowerBufferIndex 2 +double lowerBuffer[]; + +// +#property indicator_label3 "X121 MASL" +#property indicator_type3 DRAW_LINE +#property indicator_color3 clrMagenta +#property indicator_style3 STYLE_SOLID +#property indicator_width3 1 + +// +// Data Buffers ... + +// +int mLastBufferIndex = 2; + +// +// Variables, Properties and etc ... + +// +// this counts Available Bars ... +int limit; + +// +int maxLength; + +// +int upperHandler = INVALID_HANDLE; +int midHandler = INVALID_HANDLE; +int lowerHandler = INVALID_HANDLE; + +// +// Event Handlers ... + +/** + * Initialize Indicator ... + * + * @return ( int ) + */ +int OnInit() +{ + // + // Validate Inputs ... + if (!ValidateInputs()) + { + return INIT_PARAMETERS_INCORRECT; + } + + // + // Initialize Indicator Handlers ... + + // + // Upper ... + upperHandler = iMA( + _Symbol, + _Period, + length, + 0, + method, + upperAppliedTo // + ); + bool isInited = upperHandler != INVALID_HANDLE; + if (!isInited) + { + return INIT_FAILED; + } + + // + // Mid ... + midHandler = iMA( + _Symbol, + _Period, + length, + 0, + method, + midAppliedTo // + ); + isInited = midHandler != INVALID_HANDLE; + if (!isInited) + { + return INIT_FAILED; + } + + // + // Lower ... + lowerHandler = iMA( + _Symbol, + _Period, + length, + 0, + method, + lowerAppliedTo // + ); + isInited = lowerHandler != INVALID_HANDLE; + if (!isInited) + { + return INIT_FAILED; + } + + // + // because in some cases we may have more than one input for + // calculation and we must prevent any calculation + // untill we pass the biggest input length, here we get max Input length + // and then wait until pass it ... + maxLength = ExtractMaxLengthOfInputs(); + + // + // Define Index Buffers ... + DefineBuffers(); + + // + // Set Indicator ShortName ... + SetIndicatorName(); + IndicatorSetInteger(INDICATOR_DIGITS, 2); + + // + // Init Succeed ... + return INIT_SUCCEEDED; +} + +/** + * De Initialize Indicator ... + * + * @param reason: Integer, De Initialization Reason ... + */ +void OnDeinit(const int reason) +{ + // + // REASON_PROGRAM 0 The EA has stopped working calling the ExpertRemove() function + // REASON_REMOVE 1 Program removed from a chart + // REASON_RECOMPILE 2 Program recompiled + // REASON_CHARTCHANGE 3 A symbol or a chart period is changed + // REASON_CHARTCLOSE 4 Chart closed + // REASON_PARAMETERS 5 Inputs changed by a user + // REASON_ACCOUNT 6 Another account has been activated or reconnection to the trade server has occurred due to changes in the account settings + // REASON_TEMPLATE 7 Another chart template applied + // REASON_INITFAILED 8 The OnInit() handler returned a non-zero value + // REASON_CLOSE 9 Terminal closed + + // + IndicatorRelease(upperHandler); + IndicatorRelease(midHandler); + IndicatorRelease(lowerHandler); +} + +/** + * Calculate Bars ... + * + * @param rates_total: Integer, Total Bars on Chart ... + * @param prev_calculated: Integer, Total Calculated Bars on Charts ... + * @param time: DateTime Array, History of Open Time ... + * @param open: Double Array, History of Open Prices ... + * @param high: Double Array, History of High Prices ... + * @param low: Double Array, History of Low Prices ... + * @param close: Double Array, History of Close Prices ... + * @param tick_volume: Long, History of Tick Volumes on Bar ... + * @param volume: Long, History of Trade Volumes ... + * @param spread: Double, History of Spread Price ... + * + * @return ( int ) + */ +int OnCalculate( + const int rates_total, + const int prev_calculated, + const datetime &time[], + const double &open[], + const double &high[], + const double &low[], + const double &close[], + const long &tick_volume[], + const long &volume[], + const int &spread[] // +) +{ + // + // Prepare Buffers ... + ArraySetAsSeries(time, true); + ArraySetAsSeries(open, true); + ArraySetAsSeries(high, true); + ArraySetAsSeries(low, true); + ArraySetAsSeries(close, true); + ArraySetAsSeries(tick_volume, true); + ArraySetAsSeries(volume, true); + ArraySetAsSeries(spread, true); + + // + // Validate Calculated Bars ... + + // + // Upper ... + int upperCalculatedBars = BarsCalculated(upperHandler); + + // + // Mid ... + int midCalculatedBars = BarsCalculated(midHandler); + + // + // Lower ... + int lowerCalculatedBars = BarsCalculated(lowerHandler); + + // + bool isPassedRequiredCalculatedBars = + // + // Upper ... + upperCalculatedBars >= maxLength && + // + // Mid ... + midCalculatedBars >= maxLength && + // + // Lower ... + lowerCalculatedBars >= maxLength + // + ; + if (!isPassedRequiredCalculatedBars) + { + return prev_calculated; + } + + // + limit = (prev_calculated > rates_total || prev_calculated <= 0) + ? rates_total + : (rates_total - prev_calculated) + 1; + + // + // Buffers Copy ... + + // + // Upper ... + int copiedUppers = CopyBuffer(upperHandler, 0, 0, limit, upperBuffer); + + // + // Mid ... + int copiedMids = CopyBuffer(midHandler, 0, 0, limit, midBuffer); + + // + // Lower ... + int copiedLowers = CopyBuffer(lowerHandler, 0, 0, limit, lowerBuffer); + + // + // Validate Copied Items ... + bool isPassedRequiredCopiedItems = + // + // Upper ... + copiedUppers > 0 && + // + // Mid ... + copiedMids > 0 && + // + // Lower ... + copiedLowers > 0 + // + ; + if (!isPassedRequiredCopiedItems) + { + return prev_calculated; + } + + // + // Main Loop ... + for (int i = limit - 1; i >= 0 && !IsStopped(); i--) + { + // + CalculateBuffers( + // + i, + prev_calculated, + rates_total, + // + open, + high, + close, + low, + tick_volume // + ); + } + + // + return rates_total; +} + +// +// Functions ... + +/** + * Validate Input Args for Initialization ... + * + * @return ( bool ) + */ +bool ValidateInputs() +{ + // + bool result = false; + + // + result = length > 0; + + // + return result; +} + +/** + * Extract Max Length of Inputs ... + * + * @return ( int ) + */ +int ExtractMaxLengthOfInputs() +{ + // + int result = 0; + + // + result = MathMax(result, length); + + // + return result; +} + +/** + * Set Indicator Short Name and also we can define Buffers Labels ... + */ +void SetIndicatorName() +{ + IndicatorSetString(INDICATOR_SHORTNAME, ShortName); +} + +/** + * Define Required Buffers ... + */ +void DefineBuffers() +{ + // + // Plot Buffers ... + + // + // Upper ... + + // + ENUM_DRAW_TYPE upperDrawType = showUpper ? DRAW_LINE : DRAW_NONE; + + // + ArraySetAsSeries(upperBuffer, true); + SetIndexBuffer(upperBufferIndex, upperBuffer, INDICATOR_DATA); + + // + PlotIndexSetInteger(upperBufferIndex, PLOT_SHOW_DATA, showUpper); + PlotIndexSetInteger(upperBufferIndex, PLOT_DRAW_TYPE, upperDrawType); + + // + PlotIndexSetDouble(upperBufferIndex, PLOT_EMPTY_VALUE, 0); + + // + // Mid ... + + // + ENUM_DRAW_TYPE midDrawType = showMid ? DRAW_LINE : DRAW_NONE; + + ArraySetAsSeries(midBuffer, true); + SetIndexBuffer(midBufferIndex, midBuffer, INDICATOR_DATA); + + // + PlotIndexSetInteger(midBufferIndex, PLOT_SHOW_DATA, showMid); + PlotIndexSetInteger(midBufferIndex, PLOT_DRAW_TYPE, midDrawType); + + // + PlotIndexSetDouble(midBufferIndex, PLOT_EMPTY_VALUE, 0); + + // + // Lower ... + + // + ENUM_DRAW_TYPE lowerDrawType = showLower ? DRAW_LINE : DRAW_NONE; + + ArraySetAsSeries(lowerBuffer, true); + SetIndexBuffer(lowerBufferIndex, lowerBuffer, INDICATOR_DATA); + + // + PlotIndexSetInteger(lowerBufferIndex, PLOT_SHOW_DATA, showLower); + PlotIndexSetInteger(lowerBufferIndex, PLOT_DRAW_TYPE, lowerDrawType); + + // + PlotIndexSetDouble(lowerBufferIndex, PLOT_EMPTY_VALUE, 0); +} + +/** + * Calculate Custom Buffers ... + * + * @param bar_index: Integer, Represent Current Bar ... + * @param prevCalculated: Integer, Represent Previous Calculated Bars ... + * @param ratesTotal: Integer, Represents All Available Bars ... + * @param open: Double Array, History of Open Prices ... + * @param high: Double Array, History of High Prices ... + * @param close: Double Array, History of Close Prices ... + * @param low: Double Array, History of Low Prices ... + * @param tickVolume: Long, History of Tick Volumes on Bar ... + */ +void CalculateBuffers( + int bar_index, // Selected Bar Index + const int prevCalculated, + const int ratesTotal, + const double &open[], + const double &high[], + const double &close[], + const double &low[], + const long &tickVolume[] // +) +{ + // + int barsLimit = startCalculationForLastBars > 0 + ? startCalculationForLastBars + : 0; + // + // bool canCalculate = true; + bool canCalculate = + barsLimit == 0 || + bar_index <= barsLimit; + if (canCalculate) + { + // + CalculateValues( + bar_index, + prevCalculated, + ratesTotal, + open, + high, + close, + low, + tickVolume // + ); + } + else + { + FillBuffersZero(bar_index); + } +} + +/** + * Fill All Bufers to Zero Vlue for Specified Bar Index ... + * + * @param barIndex: Integer ... + */ +void FillBuffersZero(int barIndex) +{ + // + upperBuffer[barIndex] = 0; + midBuffer[barIndex] = 0; + lowerBuffer[barIndex] = 0; +} + +/** + * Calculate Vales ... + * + * @param bar_index: Integer, Represent Current Bar ... + * @param prevCalculated: Integer, Represent Previous Calculated Bars ... + * @param ratesTotal: Integer, Represents All Available Bars ... + * @param open: Double Array, History of Open Prices ... + * @param high: Double Array, History of High Prices ... + * @param close: Double Array, History of Close Prices ... + * @param low: Double Array, History of Low Prices ... + * @param tickVolume: Long, History of Tick Volumes on Bar ... + */ +void CalculateValues( + int bar_index, // Selected Bar Index + const int prevCalculated, + const int ratesTotal, + const double &open[], + const double &high[], + const double &close[], + const double &low[], + const long &tickVolume[] // +) +{ + // + // Implement Colorify Mechanism ... +} + +// diff --git a/BKPS/14040203/Indicators/x-saherelm.x121.xoscs.mq5 b/BKPS/14040203/Indicators/x-saherelm.x121.xoscs.mq5 new file mode 100644 index 0000000..4c32077 --- /dev/null +++ b/BKPS/14040203/Indicators/x-saherelm.x121.xoscs.mq5 @@ -0,0 +1,1026 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Indicator +// ------------------------------------------------- +// Name: X121 XWZ +// Description: XWZ ... +// +// +// 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 XWZ Indicator" +#property strict + +// +// Definitions ... + +// +#define ShortName "X121_X3MA" + +// +// Imports ... +#include "../Libraries/x-saherelm.common.lib.mq5" + +// +// Inputs ... + +// +input group "Accumulation/Distribution"; +input ENUM_APPLIED_VOLUME adAppliedTo = VOLUME_TICK; // Applied To + +// +input group "ADX"; +input int adxLength = 14; // Length + +// +input group "ATR"; +input int atrLength = 14; // Length + +// +input group "CCI"; +input int cciLength = 14; // Length +input ENUM_APPLIED_PRICE cciAppliedTo = PRICE_TYPICAL; // Applied To + +// +input group "RSI"; +input int rsiLength = 14; // Length +input ENUM_APPLIED_PRICE rsiAppliedTo = PRICE_CLOSE; // Applied To + +// +input group "MFI"; +input int mfiLength = 14; // Length +input ENUM_APPLIED_VOLUME mfiAppliedTo = VOLUME_TICK; // Applied To + +// +input group "RVI"; +input int rviLength = 14; // Length + +// +input group "MACD"; +input int macdFastLength = 12; // Fast EMA Length +input int macdSlowLength = 26; // Slow EMA Length +input int macdSignalLength = 9; // Signal Length +input ENUM_APPLIED_PRICE macdAppliedTo = PRICE_CLOSE; // Applied To + +// +input group "Momentum"; +input int momentumLength = 14; // Length +input ENUM_APPLIED_PRICE momentumAppliedTo = PRICE_CLOSE; // Applied To + +// +input group "Stochastic"; +input int stochasticKLength = 5; // K Length (Bars for Calculation) +input int stochasticDLength = 3; // D Length (first Smoothing) +input int stochasticSmoothingLength = 3; // Smoothing Length +input ENUM_MA_METHOD stochasticSmoothingMethod = MODE_SMA; // Smoothing Method +input ENUM_STO_PRICE stochasticAppliedTo = STO_LOWHIGH; // Applied To + +// +// Presentation ... +input group "Presentation"; + +// +input int startCalculationForLastBars = 1000; // Calculate Last n Bars + +// +// Buffers ... + +// +#define emptyValue 0.0 + +// +#property indicator_chart_window + +// +#property indicator_buffers 16 +#property indicator_plots 0 + +// +// Plot Buffers ... + +// +// Data Buffers ... + +// +int mLastBufferIndex = -1; + +// +// AC ... +#define acBufferIndex mLastBufferIndex + 1 +double acBuffer[]; + +// +// AD ... +#define adBufferIndex mLastBufferIndex + 2 +double adBuffer[]; + +// +// ADX ... +#define adxBufferIndex mLastBufferIndex + 3 +double adxBuffer[]; + +// +// ADX Plus ... +#define adxpBufferIndex mLastBufferIndex + 4 +double adxpBuffer[]; + +// +// ADX Negative ... +#define adxnBufferIndex mLastBufferIndex + 5 +double adxnBuffer[]; + +// +// ATR ... +#define atrBufferIndex mLastBufferIndex + 6 +double atrBuffer[]; + +// +// CCI ... +#define cciBufferIndex mLastBufferIndex + 7 +double cciBuffer[]; + +// +// RSI ... +#define rsiBufferIndex mLastBufferIndex + 8 +double rsiBuffer[]; + +// +// MFI ... +#define mfiBufferIndex mLastBufferIndex + 9 +double mfiBuffer[]; + +// +// RVI ... +#define rviBufferIndex mLastBufferIndex + 10 +double rviBuffer[]; + +// +// RVI Signal ... +#define rviSignalBufferIndex mLastBufferIndex + 11 +double rviSignalBuffer[]; + +// +// MACD ... +#define macdBufferIndex mLastBufferIndex + 12 +double macdBuffer[]; + +// +// MACD Signal ... +#define macdSignalBufferIndex mLastBufferIndex + 13 +double macdSignalBuffer[]; + +// +// Momentum ... +#define momentumBufferIndex mLastBufferIndex + 14 +double momentumBuffer[]; + +// +// Stochstic ... +#define stochasticBufferIndex mLastBufferIndex + 15 +double stochasticBuffer[]; + +// +// Stochstic Signal ... +#define stochasticSignalBufferIndex mLastBufferIndex + 16 +double stochasticSignalBuffer[]; + +// +// Variables, Properties and etc ... + +// +// this counts Available Bars ... +int limit; + +// +int maxLength; + +// +int acHandler = INVALID_HANDLE; +int adHandler = INVALID_HANDLE; +int adxHandler = INVALID_HANDLE; +int atrHandler = INVALID_HANDLE; +int cciHandler = INVALID_HANDLE; +int rsiHandler = INVALID_HANDLE; +int rviHandler = INVALID_HANDLE; +int mfiHandler = INVALID_HANDLE; +int macdHandler = INVALID_HANDLE; +int momentumHandler = INVALID_HANDLE; +int stochasticHandler = INVALID_HANDLE; + +// +// Event Handlers ... + +/** + * Initialize Indicator ... + * + * @return ( int ) + */ +int OnInit() +{ + // + // Validate Inputs ... + if (!ValidateInputs()) + { + return INIT_PARAMETERS_INCORRECT; + } + + // + // Initialize Indicator Handlers ... + if (!InitializeHandlres()) + { + return INIT_FAILED; + } + + // + // because in some cases we may have more than one input for + // calculation and we must prevent any calculation + // untill we pass the biggest input length, here we get max Input length + // and then wait until pass it ... + maxLength = ExtractMaxLengthOfInputs(); + + // + // Define Index Buffers ... + DefineBuffers(); + + // + // Set Indicator ShortName ... + SetIndicatorName(); + IndicatorSetInteger(INDICATOR_DIGITS, 2); + + // + // Init Succeed ... + return INIT_SUCCEEDED; +} + +/** + * De Initialize Indicator ... + * + * @param reason: Integer, De Initialization Reason ... + */ +void OnDeinit(const int reason) +{ + // + // REASON_PROGRAM 0 The EA has stopped working calling the ExpertRemove() function + // REASON_REMOVE 1 Program removed from a chart + // REASON_RECOMPILE 2 Program recompiled + // REASON_CHARTCHANGE 3 A symbol or a chart period is changed + // REASON_CHARTCLOSE 4 Chart closed + // REASON_PARAMETERS 5 Inputs changed by a user + // REASON_ACCOUNT 6 Another account has been activated or reconnection to the trade server has occurred due to changes in the account settings + // REASON_TEMPLATE 7 Another chart template applied + // REASON_INITFAILED 8 The OnInit() handler returned a non-zero value + // REASON_CLOSE 9 Terminal closed + + // + DeInitializeHandlres(); +} + +/** + * Calculate Bars ... + * + * @param rates_total: Integer, Total Bars on Chart ... + * @param prev_calculated: Integer, Total Calculated Bars on Charts ... + * @param time: DateTime Array, History of Open Time ... + * @param open: Double Array, History of Open Prices ... + * @param high: Double Array, History of High Prices ... + * @param low: Double Array, History of Low Prices ... + * @param close: Double Array, History of Close Prices ... + * @param tick_volume: Long, History of Tick Volumes on Bar ... + * @param volume: Long, History of Trade Volumes ... + * @param spread: Double, History of Spread Price ... + * + * @return ( int ) + */ +int OnCalculate( + const int rates_total, + const int prev_calculated, + const datetime &time[], + const double &open[], + const double &high[], + const double &low[], + const double &close[], + const long &tick_volume[], + const long &volume[], + const int &spread[] // +) +{ + // + // Prepare Buffers ... + ArraySetAsSeries(time, true); + ArraySetAsSeries(open, true); + ArraySetAsSeries(high, true); + ArraySetAsSeries(low, true); + ArraySetAsSeries(close, true); + ArraySetAsSeries(tick_volume, true); + ArraySetAsSeries(volume, true); + ArraySetAsSeries(spread, true); + + // + // Validate Calculated Bars ... + + // + // AC ... + int acCalculatedBars = BarsCalculated(acHandler); + + // + // AD ... + int adCalculatedBars = BarsCalculated(adHandler); + + // + // ADX ... + int adxCalculatedBars = BarsCalculated(adHandler); + + // + // ATR ... + int atrCalculatedBars = BarsCalculated(atrHandler); + + // + // CCI ... + int cciCalculatedBars = BarsCalculated(cciHandler); + + // + // RSI ... + int rsiCalculatedBars = BarsCalculated(rsiHandler); + + // + // MFI ... + int mfiCalculatedBars = BarsCalculated(mfiHandler); + + // + // RVI ... + int rviCalculatedBars = BarsCalculated(rviHandler); + + // + // MACD ... + int macdCalculatedBars = BarsCalculated(macdHandler); + + // + // Momentum ... + int momentumCalculatedBars = BarsCalculated(momentumHandler); + + // + // Stochastic ... + int stochasticCalculatedBars = BarsCalculated(stochasticHandler); + + // + bool isPassedRequiredCalculatedBars = + // + // AC ... + acCalculatedBars >= maxLength && + // + // AD ... + adCalculatedBars >= maxLength && + // + // ADX ... + adxCalculatedBars >= maxLength && + // + // ATR ... + atrCalculatedBars >= maxLength && + // + // CCI ... + cciCalculatedBars >= maxLength && + // + // RSI ... + rsiCalculatedBars >= maxLength && + // + // MFI ... + mfiCalculatedBars >= maxLength && + // + // RVI ... + rviCalculatedBars >= maxLength && + // + // MACD ... + macdCalculatedBars >= maxLength && + // + // Momentum ... + momentumCalculatedBars >= maxLength && + // + // Stochastic ... + stochasticCalculatedBars >= maxLength + // + ; + if (!isPassedRequiredCalculatedBars) + { + return prev_calculated; + } + + // + limit = (prev_calculated > rates_total || prev_calculated <= 0) + ? rates_total + : (rates_total - prev_calculated) + 1; + + // + // Buffers Copy ... + + // + // AC ... + int copiedACs = CopyBuffer(acHandler, MAIN_LINE, 0, limit, acBuffer); + + // + // AD ... + int copiedADs = CopyBuffer(adHandler, MAIN_LINE, 0, limit, adBuffer); + + // + // ADX ... + int copiedADXs = CopyBuffer(adxHandler, MAIN_LINE, 0, limit, adxBuffer); + + // + // ADX Plus ... + int copiedADXPs = CopyBuffer(adxHandler, PLUSDI_LINE, 0, limit, adxpBuffer); + + // + // ADX Negative ... + int copiedADXNs = CopyBuffer(adxHandler, MINUSDI_LINE, 0, limit, adxnBuffer); + + // + // ATR ... + int copiedATRs = CopyBuffer(atrHandler, MAIN_LINE, 0, limit, atrBuffer); + + // + // CCI ... + int copiedCCIs = CopyBuffer(cciHandler, MAIN_LINE, 0, limit, cciBuffer); + + // + // RSI ... + int copiedRSIs = CopyBuffer(rsiHandler, MAIN_LINE, 0, limit, rsiBuffer); + + // + // MFI ... + int copiedMFIs = CopyBuffer(mfiHandler, MAIN_LINE, 0, limit, mfiBuffer); + + // + // RVI ... + int copiedRVIs = CopyBuffer(rviHandler, MAIN_LINE, 0, limit, rviBuffer); + + // + // RVI ... + int copiedRVISignals = CopyBuffer(rviHandler, SIGNAL_LINE, 0, limit, rviSignalBuffer); + + // + // MACD ... + int copiedMACDs = CopyBuffer(macdHandler, MAIN_LINE, 0, limit, macdBuffer); + + // + // MACD Signal ... + int copiedMACDSignals = CopyBuffer(macdHandler, SIGNAL_LINE, 0, limit, macdSignalBuffer); + + // + // Momentum ... + int copiedMomentums = CopyBuffer(cciHandler, MAIN_LINE, 0, limit, momentumBuffer); + + // + // Stochastic ... + int copiedStochastics = CopyBuffer(stochasticHandler, MAIN_LINE, 0, limit, stochasticBuffer); + + // + // Stochastic Signal ... + int copiedStochasticSignals = CopyBuffer(stochasticHandler, SIGNAL_LINE, 0, limit, stochasticSignalBuffer); + + // + // Validate Copied Items ... + bool isPassedRequiredCopiedItems = + // + // AC ... + copiedACs > 0 && + // + // AD ... + copiedADs > 0 && + // + // ADX ... + copiedADXs > 0 && + // + // ADX Plus ... + copiedADXPs > 0 && + // + // ADX Negative ... + copiedADXNs > 0 && + // + // ATR ... + copiedATRs > 0 && + // + // CCI ... + copiedCCIs > 0 && + // + // RSI ... + copiedRSIs > 0 && + // + // MFI ... + copiedMFIs > 0 && + // + // RVI ... + copiedRVIs > 0 && + // + // RVI Signal ... + copiedRVISignals > 0 && + // + // MACD ... + copiedMACDs > 0 && + // + // MACD Signal ... + copiedMACDSignals > 0 && + // + // Momentum ... + copiedMomentums > 0 && + // + // Stochastic ... + copiedStochastics > 0 && + // + // Stochastic Signal ... + copiedStochasticSignals > 0 + // + ; + if (!isPassedRequiredCopiedItems) + { + return prev_calculated; + } + + // + // Main Loop ... + for (int i = limit - 1; i >= 0 && !IsStopped(); i--) + { + // + CalculateBuffers( + // + i, + prev_calculated, + rates_total, + // + open, + high, + close, + low, + tick_volume // + ); + } + + // + return rates_total; +} + +// +// Functions ... + +/** + * Validate Input Args for Initialization ... + * + * @return ( bool ) + */ +bool ValidateInputs() +{ + // + bool result = false; + + // + result = + // + adxLength > 0 && + atrLength > 0 && + cciLength > 0 && + rsiLength > 0 && + mfiLength > 0 && + rviLength > 0 && + // + macdFastLength > 0 && + macdSlowLength > 0 && + macdSignalLength > 0 && + macdFastLength < macdSlowLength && + // + stochasticKLength > 0 && + stochasticDLength > 0 && + stochasticSmoothingLength > 0 && + // + momentumLength > 0 + // + ; + + // + return result; +} + +/** + * Initialize All Indicators Handlers ... + * + * @return ( bool ) + */ +bool InitializeHandlres() +{ + // + bool result = false; + + // + // AC ... + acHandler = iAC(_Symbol, _Period); + result = acHandler != INVALID_HANDLE; + if (!result) + { + return result; + } + + // + // AD ... + adHandler = iAD( + _Symbol, + _Period, + adAppliedTo // + ); + result = adHandler != INVALID_HANDLE; + if (!result) + { + return result; + } + + // + // ADX ... + adxHandler = iADX( + _Symbol, + _Period, + adxLength // + ); + result = adxHandler != INVALID_HANDLE; + if (!result) + { + return result; + } + + // + // ATR ... + atrHandler = iATR( + _Symbol, + _Period, + atrLength // + ); + result = atrHandler != INVALID_HANDLE; + if (!result) + { + return result; + } + + // + // CCI ... + cciHandler = iCCI( + _Symbol, + _Period, + cciLength, + cciAppliedTo // + ); + result = cciHandler != INVALID_HANDLE; + if (!result) + { + return result; + } + + // + // RSI ... + rsiHandler = iRSI( + _Symbol, + _Period, + rsiLength, + rsiAppliedTo // + ); + result = rsiHandler != INVALID_HANDLE; + if (!result) + { + return result; + } + + // + // MFI ... + mfiHandler = iMFI( + _Symbol, + _Period, + mfiLength, + mfiAppliedTo // + ); + result = mfiHandler != INVALID_HANDLE; + if (!result) + { + return result; + } + + // + // RVI ... + rviHandler = iRVI( + _Symbol, + _Period, + rviLength // + ); + result = rviHandler != INVALID_HANDLE; + if (!result) + { + return result; + } + + // + // MACD ... + macdHandler = iMACD( + _Symbol, + _Period, + macdFastLength, + macdSlowLength, + macdSignalLength, + macdAppliedTo // + ); + result = macdHandler != INVALID_HANDLE; + if (!result) + { + return result; + } + + // + // Momentum ... + momentumHandler = iMomentum( + _Symbol, + _Period, + momentumLength, + momentumAppliedTo // + ); + result = momentumHandler != INVALID_HANDLE; + if (!result) + { + return result; + } + + // + // Stochastic ... + stochasticHandler = iStochastic( + _Symbol, + _Period, + stochasticKLength, + stochasticDLength, + stochasticSmoothingLength, + stochasticSmoothingMethod, + stochasticAppliedTo // + ); + result = stochasticHandler != INVALID_HANDLE; + if (!result) + { + return result; + } + + // + return result; +} + +/** + * Release All Indicators ... + */ +void DeInitializeHandlres() +{ + // + IndicatorRelease(acHandler); + IndicatorRelease(adHandler); + IndicatorRelease(adxHandler); + IndicatorRelease(atrHandler); + IndicatorRelease(cciHandler); + IndicatorRelease(rsiHandler); + IndicatorRelease(mfiHandler); + IndicatorRelease(rviHandler); + IndicatorRelease(macdHandler); + IndicatorRelease(momentumHandler); + IndicatorRelease(stochasticHandler); +} + +/** + * Extract Max Length of Inputs ... + * + * @return ( int ) + */ +int ExtractMaxLengthOfInputs() +{ + // + int result = 0; + + // + result = MathMax(adxLength, atrLength); + result = MathMax(result, cciLength); + result = MathMax(result, rsiLength); + result = MathMax(result, mfiLength); + result = MathMax(result, rviLength); + result = MathMax(result, momentumLength); + result = MathMax(result, macdFastLength); + result = MathMax(result, macdSlowLength); + result = MathMax(result, macdSignalLength); + result = MathMax(result, stochasticKLength); + result = MathMax(result, stochasticDLength); + result = MathMax(result, stochasticSmoothingLength); + + // + return result; +} + +/** + * Set Indicator Short Name and also we can define Buffers Labels ... + */ +void SetIndicatorName() +{ + // + IndicatorSetInteger(INDICATOR_DIGITS, _Digits); + IndicatorSetString(INDICATOR_SHORTNAME, ShortName); +} + +/** + * Define Required Buffers ... + */ +void DefineBuffers() +{ + // + // Plot Buffers ... + + // + // Data Buffers ... + + // + // AC ... + ArraySetAsSeries(acBuffer, true); + SetIndexBuffer(acBufferIndex, acBuffer, INDICATOR_CALCULATIONS); + + // + // AD ... + ArraySetAsSeries(adBuffer, true); + SetIndexBuffer(adBufferIndex, adBuffer, INDICATOR_CALCULATIONS); + + // + // ADX ... + ArraySetAsSeries(adxBuffer, true); + SetIndexBuffer(adxBufferIndex, adxBuffer, INDICATOR_CALCULATIONS); + + // + // ADX Plus ... + ArraySetAsSeries(adxpBuffer, true); + SetIndexBuffer(adxpBufferIndex, adxpBuffer, INDICATOR_CALCULATIONS); + + // + // ADX Negative ... + ArraySetAsSeries(adxnBuffer, true); + SetIndexBuffer(adxnBufferIndex, adxnBuffer, INDICATOR_CALCULATIONS); + + // + // ATR ... + ArraySetAsSeries(atrBuffer, true); + SetIndexBuffer(atrBufferIndex, atrBuffer, INDICATOR_CALCULATIONS); + + // + // CCI ... + ArraySetAsSeries(cciBuffer, true); + SetIndexBuffer(cciBufferIndex, cciBuffer, INDICATOR_CALCULATIONS); + + // + // RSI ... + ArraySetAsSeries(rsiBuffer, true); + SetIndexBuffer(rsiBufferIndex, rsiBuffer, INDICATOR_CALCULATIONS); + + // + // MFI ... + ArraySetAsSeries(mfiBuffer, true); + SetIndexBuffer(mfiBufferIndex, mfiBuffer, INDICATOR_CALCULATIONS); + + // + // RVI ... + ArraySetAsSeries(rviBuffer, true); + SetIndexBuffer(rviBufferIndex, rviBuffer, INDICATOR_CALCULATIONS); + + // + // RVI Signal ... + ArraySetAsSeries(rviSignalBuffer, true); + SetIndexBuffer(rviSignalBufferIndex, rviSignalBuffer, INDICATOR_CALCULATIONS); + + // + // MACD ... + ArraySetAsSeries(macdBuffer, true); + SetIndexBuffer(macdBufferIndex, macdBuffer, INDICATOR_CALCULATIONS); + + // + // MACD Signal ... + ArraySetAsSeries(macdSignalBuffer, true); + SetIndexBuffer(macdSignalBufferIndex, macdSignalBuffer, INDICATOR_CALCULATIONS); + + // + // Momentum ... + ArraySetAsSeries(momentumBuffer, true); + SetIndexBuffer(momentumBufferIndex, momentumBuffer, INDICATOR_CALCULATIONS); + + // + // Stochastics ... + ArraySetAsSeries(stochasticBuffer, true); + SetIndexBuffer(stochasticBufferIndex, stochasticBuffer, INDICATOR_CALCULATIONS); + + // + // Stochastics Signal ... + ArraySetAsSeries(stochasticSignalBuffer, true); + SetIndexBuffer(stochasticSignalBufferIndex, stochasticSignalBuffer, INDICATOR_CALCULATIONS); +} + +/** + * Calculate Custom Buffers ... + * + * @param bar_index: Integer, Represent Current Bar ... + * @param prevCalculated: Integer, Represent Previous Calculated Bars ... + * @param ratesTotal: Integer, Represents All Available Bars ... + * @param open: Double Array, History of Open Prices ... + * @param high: Double Array, History of High Prices ... + * @param close: Double Array, History of Close Prices ... + * @param low: Double Array, History of Low Prices ... + * @param tickVolume: Long, History of Tick Volumes on Bar ... + */ +void CalculateBuffers( + int bar_index, // Selected Bar Index + const int prevCalculated, + const int ratesTotal, + const double &open[], + const double &high[], + const double &close[], + const double &low[], + const long &tickVolume[] // +) +{ + // + int barsLimit = startCalculationForLastBars > 0 + ? startCalculationForLastBars + : 0; + // + // bool canCalculate = true; + bool canCalculate = + barsLimit == 0 || + bar_index <= barsLimit; + if (canCalculate) + { + // + CalculateValues( + bar_index, + prevCalculated, + ratesTotal, + open, + high, + close, + low, + tickVolume // + ); + } + else + { + FillBuffersZero(bar_index); + } +} + +/** + * Fill All Bufers to Zero Vlue for Specified Bar Index ... + * + * @param barIndex: Integer ... + */ +void FillBuffersZero(int barIndex) +{ + // + acBuffer[barIndex] = emptyValue; + adBuffer[barIndex] = emptyValue; + adxBuffer[barIndex] = emptyValue; + adxpBuffer[barIndex] = emptyValue; + adxnBuffer[barIndex] = emptyValue; + atrBuffer[barIndex] = emptyValue; + cciBuffer[barIndex] = emptyValue; + rsiBuffer[barIndex] = emptyValue; + mfiBuffer[barIndex] = emptyValue; + rviBuffer[barIndex] = emptyValue; + macdBuffer[barIndex] = emptyValue; + momentumBuffer[barIndex] = emptyValue; + rviSignalBuffer[barIndex] = emptyValue; + macdSignalBuffer[barIndex] = emptyValue; + stochasticBuffer[barIndex] = emptyValue; + stochasticSignalBuffer[barIndex] = emptyValue; +} + +/** + * Calculate Vales ... + * + * @param bar_index: Integer, Represent Current Bar ... + * @param prevCalculated: Integer, Represent Previous Calculated Bars ... + * @param ratesTotal: Integer, Represents All Available Bars ... + * @param open: Double Array, History of Open Prices ... + * @param high: Double Array, History of High Prices ... + * @param close: Double Array, History of Close Prices ... + * @param low: Double Array, History of Low Prices ... + * @param tickVolume: Long, History of Tick Volumes on Bar ... + */ +void CalculateValues( + int bar_index, // Selected Bar Index + const int prevCalculated, + const int ratesTotal, + const double &open[], + const double &high[], + const double &close[], + const double &low[], + const long &tickVolume[] // +) +{ + // + // Implement Colorify Mechanism ... +} + +// diff --git a/BKPS/14040203/Indicators/x-saherelm.x121.xpv.mq5 b/BKPS/14040203/Indicators/x-saherelm.x121.xpv.mq5 new file mode 100644 index 0000000..90dd823 --- /dev/null +++ b/BKPS/14040203/Indicators/x-saherelm.x121.xpv.mq5 @@ -0,0 +1,1661 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Indicator +// ------------------------------------------------- +// Name: X121 XPV +// Description: XPV ... +// +// +// 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 XPV Indicator" +#property strict + +// +// Definitions ... + +// +#define ShortName "X121 XPV" + +// +// Includes Common Library ... +#include "../Libraries/x-saherelm.common.lib.mq5" + +// +// Inputs ... + +// +// Market ... +input group "Market"; + +// +input group "Short"; +input ENUM_X_PERIOD_METHOD scMethod = X_PERIOD_AUTO; // How to Find Period +input ENUM_TIMEFRAMES scPeriod = NULL; // Time Period + +// +input group "Medium"; +input ENUM_X_PERIOD_METHOD mcMethod = X_PERIOD_AUTO; // How to Find Period +input ENUM_TIMEFRAMES mcPeriod = NULL; // Time Period + +// +input group "Long"; +input ENUM_X_PERIOD_METHOD lcMethod = X_PERIOD_AUTO; // How to Find Period +input ENUM_TIMEFRAMES lcPeriod = NULL; // Time Period + +// +input group "Hind"; +input ENUM_X_PERIOD_METHOD hcMethod = X_PERIOD_AUTO; // How to Find Period +input ENUM_TIMEFRAMES hcPeriod = NULL; // Time Period + +// +input group "Boundary Detection"; +input ENUM_SERIESMODE hhMode = MODE_HIGH; // Highest High Calculation Method +input ENUM_SERIESMODE llMode = MODE_LOW; // Lowest Low Calculation Method +input ENUM_X_FIBO_LEVELS goldenZoneLevel = X_FIBO_LEVEL_236; // Golden Zone Detection + +// +input group "Sar Detection"; +input double sarStep = 0.02; // Step +input double sarMax = 0.2; // Maximum + +// +input group "Swing Detection"; +input int swingLength = 5; // Length + +// +// Presentation ... +input group "Presentation"; + +// +input int startCalculationForLastBars = 1000; // Calculate Last n Bars +input int sarArrowCode = 159; // Parabolic Sar Arrow Code +input int peaksArrowCode = 159; // Peaks Arrow Code +input int valesArrowCode = 159; // Vales Arrow Code +input int trendArrowCode = 117; // Trend Arrow Code +input int swingLowsArrowCode = 225; // Swing Lows Arrow Code +input int swingHighsArrowCode = 226; // Swing Highs Arrow Code +input int supportsArrowCode = 159; // Supports Arrow Code +input int resistancesArrowCode = 159; // Resistances Arrow Code + +// +input bool showSar = true; // Show Parabolic Sar +input bool showPeaks = true; // Show Peaks +input bool showVales = true; // Show Vales +input bool showTrend = true; // Show Trend +input bool showSwingLows = true; // Show Swing Lows +input bool showSwingHighs = true; // Show Swing Highs +input bool showGoldenZones = true; // Show Golden Zones +input bool showSupports = true; // Show Supports +input bool showResistances = true; // Show Resistances + +// +// Buffers ... + +// +#define hideColorIDX 0 +#define bullishColorIDX 1 +#define bearishColorIDX 2 +#define neuturalColorIDX 3 + +// +#define emptyValue 0.0 + +// +#property indicator_chart_window + +// +#property indicator_buffers 24 +#property indicator_plots 10 + +// +// Plot Buffers ... + +// +// PEAKS ... + +// +#define peaksBufferIndex 0 +double peaksBuffer[]; + +// +#property indicator_label1 "X121 PEAKS" +#property indicator_type1 DRAW_ARROW +#property indicator_color1 clrMagenta +#property indicator_width1 1 + +// +// VALES ... + +// +#define valesBufferIndex 1 +double valesBuffer[]; + +// +#property indicator_label2 "X121 VALES" +#property indicator_type2 DRAW_ARROW +#property indicator_color2 clrAqua +#property indicator_width2 1 + +// +#define sarBufferIndex 2 +double sarBuffer[]; + +// +#property indicator_label3 "X121 SAR" +#property indicator_type3 DRAW_ARROW +#property indicator_color3 clrYellow +#property indicator_width3 1 + +// +// Swing Lows ... + +// +#define swingLowsBufferIndex 3 +double swingLowsBuffer[]; + +// +#property indicator_label4 "X121 SWL" +#property indicator_type4 DRAW_ARROW +#property indicator_color4 clrDodgerBlue +#property indicator_width4 1 + +// +// Swng Highs ... + +// +#define swingHighsBufferIndex 4 +double swingHighsBuffer[]; + +// +#property indicator_label5 "X121 SWH" +#property indicator_type5 DRAW_ARROW +#property indicator_color5 clrSaddleBrown +#property indicator_width5 1 + +// +#define peaksGoldenZoneBufferIndex 5 +double peaksGoldenZoneBuffer[]; + +// +#property indicator_label6 "X121 PEAKGZ" +#property indicator_type6 DRAW_LINE +#property indicator_color6 clrGold +#property indicator_style6 STYLE_DOT +#property indicator_width6 1 + +// +#define valesGoldenZoneBufferIndex 6 +double valesGoldenZoneBuffer[]; + +// +#property indicator_label7 "X121 VALEGZ" +#property indicator_type7 DRAW_LINE +#property indicator_color7 clrGold +#property indicator_style7 STYLE_DOT +#property indicator_width7 1 + +// +#define supportsBufferIndex 7 +double supportsBuffer[]; + +// +#property indicator_label8 "X121 SUPRT" +#property indicator_type8 DRAW_ARROW +#property indicator_color8 clrLime +#property indicator_width8 1 + +// +#define resistancesBufferIndex 8 +double resistancesBuffer[]; + +// +#property indicator_label9 "X121 RESIS" +#property indicator_type9 DRAW_ARROW +#property indicator_color9 clrRed +#property indicator_width9 1 + +// +// Trend ... +#define trendBufferIndex 9 +double trendBuffer[]; + +#define trendColorBufferIndex 10 +double trendColorBuffer[]; + +// +#property indicator_label10 "X121 TRND" +#property indicator_type10 DRAW_COLOR_ARROW +#property indicator_color10 CLR_NONE, clrAqua, clrMagenta, clrGray +#property indicator_width10 2 + +// +// Data Buffers ... + +// +int mLastBufferIndex = 10; + +// +// CURRENT ... + +// +#define cHHBufferIndex mLastBufferIndex + 1 +double cHHBuffer[]; + +// +#define cLLBufferIndex mLastBufferIndex + 2 +double cLLBuffer[]; + +// +// SHORT ... + +// +#define sHHBufferIndex mLastBufferIndex + 3 +double sHHBuffer[]; + +// +#define sLLBufferIndex mLastBufferIndex + 4 +double sLLBuffer[]; + +// +// MEDIUM ... + +// +#define mHHBufferIndex mLastBufferIndex + 5 +double mHHBuffer[]; + +// +#define mLLBufferIndex mLastBufferIndex + 6 +double mLLBuffer[]; + +// +// LONG ... + +// +#define lHHBufferIndex mLastBufferIndex + 7 +double lHHBuffer[]; + +// +#define lLLBufferIndex mLastBufferIndex + 8 +double lLLBuffer[]; + +// +// HIND ... + +// +#define hHHBufferIndex mLastBufferIndex + 9 +double hHHBuffer[]; + +// +#define hLLBufferIndex mLastBufferIndex + 10 +double hLLBuffer[]; + +// +// Support and Resistances ... + +// +#define fractalsUpperBufferIndex mLastBufferIndex + 11 +double fractalsUpperBuffer[]; + +// +#define fractalsLowerBufferIndex mLastBufferIndex + 12 +double fractalsLowerBuffer[]; + +// +#define trendStateBufferIndex mLastBufferIndex + 13 +double trendStateBuffer[]; + +// +// Variables, Properties and etc ... + +// +// this counts Available Bars ... +int limit; + +// +int maxLength; + +// +// SAR Handler ... +int sarHandler = INVALID_HANDLE; + +// +// FRACTALS Handler ... +int fractalHandler = INVALID_HANDLE; + +// +// XMarketCycle sc; +int mSCLength = 0; +ENUM_TIMEFRAMES mSCPeriod = NULL; + +// +// XMarketCycle mc; +int mMCLength = 0; +ENUM_TIMEFRAMES mMCPeriod = NULL; + +// +// XMarketCycle lc; +int mLCLength = 0; +ENUM_TIMEFRAMES mLCPeriod = NULL; + +// +// XMarketCycle hc; +int mHCLength = 0; +ENUM_TIMEFRAMES mHCPeriod = NULL; + +// +// Swings ... +double lSwingLow = emptyValue; +double lSwingHigh = emptyValue; +double lTrend = emptyValue; +double lTrendState = emptyValue; +double lTrendColor = hideColorIDX; + +// +// Event Handlers ... + +/** + * Initialize Indicator ... + * + * @return ( int ) + */ +int OnInit() +{ + // + // Validate Inputs ... + if (!ValidateInputs()) + { + return INIT_PARAMETERS_INCORRECT; + } + + // + // Initialize Indicator Handlers ... + + // + // SAR ... + sarHandler = iSAR( + _Symbol, + _Period, + sarStep, + sarMax // + ); + bool isInited = sarHandler != INVALID_HANDLE; + if (!isInited) + { + return INIT_FAILED; + } + + // + // Fractal ... + fractalHandler = iFractals( + _Symbol, + _Period // + ); + isInited = fractalHandler != INVALID_HANDLE; + if (!isInited) + { + return INIT_FAILED; + } + + // + if (!InitMarketCycles()) + { + return INIT_PARAMETERS_INCORRECT; + } + + // + // because in some cases we may have more than one input for + // calculation and we must prevent any calculation + // untill we pass the biggest input length, here we get max Input length + // and then wait until pass it ... + maxLength = ExtractMaxLengthOfInputs(); + + // + // Define Index Buffers ... + DefineBuffers(); + + // + // Set Indicator ShortName ... + SetIndicatorName(); + + // + // Init Succeed ... + return INIT_SUCCEEDED; +} + +/** + * De Initialize Indicator ... + * + * @param reason: Integer, De Initialization Reason ... + */ +void OnDeinit(const int reason) +{ + // + // REASON_PROGRAM 0 The EA has stopped working calling the ExpertRemove() function + // REASON_REMOVE 1 Program removed from a chart + // REASON_RECOMPILE 2 Program recompiled + // REASON_CHARTCHANGE 3 A symbol or a chart period is changed + // REASON_CHARTCLOSE 4 Chart closed + // REASON_PARAMETERS 5 Inputs changed by a user + // REASON_ACCOUNT 6 Another account has been activated or reconnection to the trade server has occurred due to changes in the account settings + // REASON_TEMPLATE 7 Another chart template applied + // REASON_INITFAILED 8 The OnInit() handler returned a non-zero value + // REASON_CLOSE 9 Terminal closed + + // + IndicatorRelease(sarHandler); + IndicatorRelease(fractalHandler); +} + +/** + * Calculate Bars ... + * + * @param rates_total: Integer, Total Bars on Chart ... + * @param prev_calculated: Integer, Total Calculated Bars on Charts ... + * @param time: DateTime Array, History of Open Time ... + * @param open: Double Array, History of Open Prices ... + * @param high: Double Array, History of High Prices ... + * @param low: Double Array, History of Low Prices ... + * @param close: Double Array, History of Close Prices ... + * @param tick_volume: Long, History of Tick Volumes on Bar ... + * @param volume: Long, History of Trade Volumes ... + * @param spread: Double, History of Spread Price ... + * + * @return ( int ) + */ +int OnCalculate( + const int rates_total, + const int prev_calculated, + const datetime &time[], + const double &open[], + const double &high[], + const double &low[], + const double &close[], + const long &tick_volume[], + const long &volume[], + const int &spread[] // +) +{ + // + // Prepare Buffers ... + ArraySetAsSeries(time, true); + ArraySetAsSeries(open, true); + ArraySetAsSeries(high, true); + ArraySetAsSeries(low, true); + ArraySetAsSeries(close, true); + ArraySetAsSeries(tick_volume, true); + ArraySetAsSeries(volume, true); + ArraySetAsSeries(spread, true); + + // + // Validate Calculated Bars ... + + // + // SAR ... + int sarCalculatedBars = BarsCalculated(sarHandler); + + // + // FRACTALS ... + int fractalsCalculatedBars = BarsCalculated(fractalHandler); + + // + bool isPassedRequiredCalculatedBars = + // + // SAR ... + sarCalculatedBars >= maxLength && + // + // FRACTALS ... + fractalsCalculatedBars >= maxLength + // + ; + if (!isPassedRequiredCalculatedBars) + { + return prev_calculated; + } + + // + limit = (prev_calculated > rates_total || prev_calculated <= 0) + ? rates_total + : (rates_total - prev_calculated) + 1; + + // + // Buffers Copy ... + + // + // SAR ... + int copiedSars = CopyBuffer(sarHandler, 0, 0, limit, sarBuffer); + + // + // FRACTALS ... + int copiedFractalsUppers = CopyBuffer(fractalHandler, UPPER_LINE, 0, limit + 1, fractalsUpperBuffer); + int copiedFractalsLowers = CopyBuffer(fractalHandler, LOWER_LINE, 0, limit + 1, fractalsLowerBuffer); + + // + // Validate Copied Items ... + bool isPassedRequiredCopiedItems = + // + // SAR ... + copiedSars > 0 && + // + // FRACTALS ... + copiedFractalsUppers > 0 && + copiedFractalsLowers > 0 + // + ; + if (!isPassedRequiredCopiedItems) + { + return prev_calculated; + } + + // + // Main Loop ... + for (int i = limit - 1; i >= 0 && !IsStopped(); i--) + { + // + CalculateBuffers( + i, + prev_calculated, + rates_total, + // + open, + high, + close, + low, + tick_volume // + ); + } + + // + return rates_total; +} + +// +// Functions ... + +/** + * Validate Input Args for Initialization ... + * + * @return ( bool ) + */ +bool ValidateInputs() +{ + // + bool result = false; + + // + result = + // + // SAR ... + sarMax > 0 && + sarStep > 0 && + swingLength > 0 && + sarMax > sarStep && + // + // XPV ... + (IsValid(scMethod, scPeriod) && + IsValid(mcMethod, mcPeriod) && + IsValid(lcMethod, lcPeriod) && + IsValid(hcMethod, hcPeriod)) + // + ; + + // + return result; +} + +/** + * Extract Max Length of Inputs ... + * + * @return ( int ) + */ +int ExtractMaxLengthOfInputs() +{ + // + int result = 0; + + // + result = MathMax(0, swingLength); + + // + return result; +} + +/** + * Define Required Buffers ... + */ +void DefineBuffers() +{ + // + // Plot Buffers ... + + // + // PEAKS ... + + // + ENUM_DRAW_TYPE peaksDrawType = showPeaks ? DRAW_ARROW : DRAW_NONE; + + // + ArraySetAsSeries(peaksBuffer, true); + SetIndexBuffer(peaksBufferIndex, peaksBuffer, INDICATOR_DATA); + + // + PlotIndexSetInteger(peaksBufferIndex, PLOT_SHOW_DATA, showPeaks); + PlotIndexSetInteger(peaksBufferIndex, PLOT_DRAW_TYPE, peaksDrawType); + + // + PlotIndexSetDouble(peaksBufferIndex, PLOT_EMPTY_VALUE, EMPTY_VALUE); + PlotIndexSetInteger(peaksBufferIndex, PLOT_ARROW, peaksArrowCode); + + // + // VALES ... + + // + ENUM_DRAW_TYPE valesDrawType = showVales ? DRAW_ARROW : DRAW_NONE; + + // + ArraySetAsSeries(valesBuffer, true); + SetIndexBuffer(valesBufferIndex, valesBuffer, INDICATOR_DATA); + + // + PlotIndexSetInteger(valesBufferIndex, PLOT_SHOW_DATA, showVales); + PlotIndexSetInteger(valesBufferIndex, PLOT_DRAW_TYPE, valesDrawType); + + // + PlotIndexSetDouble(valesBufferIndex, PLOT_EMPTY_VALUE, EMPTY_VALUE); + PlotIndexSetInteger(valesBufferIndex, PLOT_ARROW, valesArrowCode); + + // + // SAR ... + + // + ENUM_DRAW_TYPE sarDrawType = showSar ? DRAW_ARROW : DRAW_NONE; + + // + ArraySetAsSeries(sarBuffer, true); + SetIndexBuffer(sarBufferIndex, sarBuffer, INDICATOR_DATA); + + // + PlotIndexSetInteger(sarBufferIndex, PLOT_SHOW_DATA, showSar); + PlotIndexSetInteger(sarBufferIndex, PLOT_DRAW_TYPE, sarDrawType); + + // + PlotIndexSetDouble(sarBufferIndex, PLOT_EMPTY_VALUE, EMPTY_VALUE); + PlotIndexSetInteger(sarBufferIndex, PLOT_ARROW, sarArrowCode); + + // + // Swing Lows ... + + // + ENUM_DRAW_TYPE swingLowsDrawType = showSwingLows ? DRAW_ARROW : DRAW_NONE; + + // + ArraySetAsSeries(swingLowsBuffer, true); + SetIndexBuffer(swingLowsBufferIndex, swingLowsBuffer, INDICATOR_DATA); + + // + PlotIndexSetInteger(swingLowsBufferIndex, PLOT_SHOW_DATA, showSwingLows); + PlotIndexSetInteger(swingLowsBufferIndex, PLOT_DRAW_TYPE, swingLowsDrawType); + + // + PlotIndexSetDouble(swingLowsBufferIndex, PLOT_EMPTY_VALUE, emptyValue); + PlotIndexSetInteger(swingLowsBufferIndex, PLOT_ARROW, swingLowsArrowCode); + + // + // Swing Highs ... + + // + ENUM_DRAW_TYPE swingHighsDrawType = showSwingHighs ? DRAW_ARROW : DRAW_NONE; + + // + ArraySetAsSeries(swingHighsBuffer, true); + SetIndexBuffer(swingHighsBufferIndex, swingHighsBuffer, INDICATOR_DATA); + + // + PlotIndexSetInteger(swingHighsBufferIndex, PLOT_SHOW_DATA, showSwingHighs); + PlotIndexSetInteger(swingHighsBufferIndex, PLOT_DRAW_TYPE, swingHighsDrawType); + + // + PlotIndexSetDouble(swingHighsBufferIndex, PLOT_EMPTY_VALUE, emptyValue); + PlotIndexSetInteger(swingHighsBufferIndex, PLOT_ARROW, swingHighsArrowCode); + + // + // Support ... + + // + ENUM_DRAW_TYPE supportsDrawType = showSupports ? DRAW_ARROW : DRAW_NONE; + + // + ArraySetAsSeries(supportsBuffer, true); + SetIndexBuffer(supportsBufferIndex, supportsBuffer, INDICATOR_DATA); + + // + PlotIndexSetInteger(supportsBufferIndex, PLOT_SHOW_DATA, showSupports); + PlotIndexSetInteger(supportsBufferIndex, PLOT_DRAW_TYPE, supportsDrawType); + + // + PlotIndexSetDouble(supportsBufferIndex, PLOT_EMPTY_VALUE, EMPTY_VALUE); + PlotIndexSetInteger(supportsBufferIndex, PLOT_ARROW, supportsArrowCode); + + // + // Resistances... + + // + ENUM_DRAW_TYPE resistancesDrawType = showResistances ? DRAW_ARROW : DRAW_NONE; + + // + ArraySetAsSeries(resistancesBuffer, true); + SetIndexBuffer(resistancesBufferIndex, resistancesBuffer, INDICATOR_DATA); + + // + PlotIndexSetInteger(resistancesBufferIndex, PLOT_SHOW_DATA, showResistances); + PlotIndexSetInteger(resistancesBufferIndex, PLOT_DRAW_TYPE, resistancesDrawType); + + // + PlotIndexSetDouble(resistancesBufferIndex, PLOT_EMPTY_VALUE, EMPTY_VALUE); + PlotIndexSetInteger(resistancesBufferIndex, PLOT_ARROW, resistancesArrowCode); + + // + // Golden Zones ... + + // + ENUM_DRAW_TYPE goldenZonesDrawType = showGoldenZones ? DRAW_LINE : DRAW_NONE; + + // + // PEAK Golden Zone ... + + // + ArraySetAsSeries(peaksGoldenZoneBuffer, true); + SetIndexBuffer(peaksGoldenZoneBufferIndex, peaksGoldenZoneBuffer, INDICATOR_DATA); + + // + PlotIndexSetInteger(peaksGoldenZoneBufferIndex, PLOT_SHOW_DATA, showGoldenZones); + PlotIndexSetInteger(peaksGoldenZoneBufferIndex, PLOT_DRAW_TYPE, goldenZonesDrawType); + + // + // VALE Golden Zone ... + + // + ArraySetAsSeries(valesGoldenZoneBuffer, true); + SetIndexBuffer(valesGoldenZoneBufferIndex, valesGoldenZoneBuffer, INDICATOR_DATA); + + // + PlotIndexSetInteger(valesGoldenZoneBufferIndex, PLOT_SHOW_DATA, showGoldenZones); + PlotIndexSetInteger(valesGoldenZoneBufferIndex, PLOT_DRAW_TYPE, goldenZonesDrawType); + + // + // Trends ... + + // + ENUM_DRAW_TYPE trendDrawType = showTrend ? DRAW_COLOR_ARROW : DRAW_NONE; + + // + ArraySetAsSeries(trendBuffer, true); + SetIndexBuffer(trendBufferIndex, trendBuffer, INDICATOR_DATA); + + // + PlotIndexSetInteger(trendBufferIndex, PLOT_SHOW_DATA, showTrend); + PlotIndexSetInteger(trendBufferIndex, PLOT_DRAW_TYPE, trendDrawType); + + // + PlotIndexSetDouble(trendBufferIndex, PLOT_EMPTY_VALUE, emptyValue); + PlotIndexSetInteger(trendBufferIndex, PLOT_ARROW, trendArrowCode); + + // + ArraySetAsSeries(trendColorBuffer, true); + SetIndexBuffer(trendColorBufferIndex, trendColorBuffer, INDICATOR_COLOR_INDEX); + + // + // Data Buffers ... + + // + // CURRENT ... + + // + ArraySetAsSeries(cHHBuffer, true); + SetIndexBuffer(cHHBufferIndex, cHHBuffer, INDICATOR_CALCULATIONS); + + // + ArraySetAsSeries(cLLBuffer, true); + SetIndexBuffer(cLLBufferIndex, cLLBuffer, INDICATOR_CALCULATIONS); + + // + // SHORT ... + + // + ArraySetAsSeries(sHHBuffer, true); + SetIndexBuffer(sHHBufferIndex, sHHBuffer, INDICATOR_CALCULATIONS); + + // + ArraySetAsSeries(sLLBuffer, true); + SetIndexBuffer(sLLBufferIndex, sLLBuffer, INDICATOR_CALCULATIONS); + + // + // MEDIUM ... + + // + ArraySetAsSeries(mHHBuffer, true); + SetIndexBuffer(mHHBufferIndex, mHHBuffer, INDICATOR_CALCULATIONS); + + // + ArraySetAsSeries(mLLBuffer, true); + SetIndexBuffer(mLLBufferIndex, mLLBuffer, INDICATOR_CALCULATIONS); + + // + // LONG ... + + // + ArraySetAsSeries(lHHBuffer, true); + SetIndexBuffer(lHHBufferIndex, lHHBuffer, INDICATOR_CALCULATIONS); + + // + ArraySetAsSeries(lLLBuffer, true); + SetIndexBuffer(lLLBufferIndex, lLLBuffer, INDICATOR_CALCULATIONS); + + // + // HIND ... + + // + ArraySetAsSeries(hHHBuffer, true); + SetIndexBuffer(hHHBufferIndex, hHHBuffer, INDICATOR_CALCULATIONS); + + // + ArraySetAsSeries(hLLBuffer, true); + SetIndexBuffer(hLLBufferIndex, hLLBuffer, INDICATOR_CALCULATIONS); + + // + // FRACTALS ... + + // + ArraySetAsSeries(fractalsUpperBuffer, true); + SetIndexBuffer(fractalsUpperBufferIndex, fractalsUpperBuffer, INDICATOR_CALCULATIONS); + + // + ArraySetAsSeries(fractalsLowerBuffer, true); + SetIndexBuffer(fractalsLowerBufferIndex, fractalsLowerBuffer, INDICATOR_CALCULATIONS); + + // + ArraySetAsSeries(trendStateBuffer, true); + SetIndexBuffer(trendStateBufferIndex, trendStateBuffer, INDICATOR_CALCULATIONS); +} + +/** + * Set Indicator Short Name and also we can define Buffers Labels ... + */ +void SetIndicatorName() +{ + // + IndicatorSetInteger(INDICATOR_DIGITS, 2); + IndicatorSetString(INDICATOR_SHORTNAME, ShortName); +} + +/** + * Calculate Custom Buffers ... + * + * @param bar_index: Integer, Represent Current Bar ... + * @param prevCalculated: Integer, Represent Previous Calculated Bars ... + * @param ratesTotal: Integer, Represents All Available Bars ... + * @param open: Double Array, History of Open Prices ... + * @param high: Double Array, History of High Prices ... + * @param close: Double Array, History of Close Prices ... + * @param low: Double Array, History of Low Prices ... + * @param tickVolume: Long, History of Tick Volumes on Bar ... + */ +void CalculateBuffers( + int bar_index, // Selected Bar Index + const int prevCalculated, + const int ratesTotal, + const double &open[], + const double &high[], + const double &close[], + const double &low[], + const long &tickVolume[] // +) +{ + // + int barsLimit = startCalculationForLastBars > 0 + ? startCalculationForLastBars + : 0; + // + // bool canCalculate = true; + bool canCalculate = + barsLimit == 0 || + bar_index <= barsLimit; + if (canCalculate) + { + // + // Calculate Cycles ... + CalculateCycles(bar_index); + + // + // Calculate Peaks and Vales ... + CalculatePeaksAndVales(bar_index); + + // + // Calculate Support nad Resistance ... + CalculateSupportAndResistance( + bar_index, + prevCalculated, + ratesTotal, + open, + high, + close, + low, + tickVolume // + ); + + // + int swingBarIndex = bar_index; + if (bar_index < swingLength) + { + swingBarIndex = bar_index + swingLength; + } + + // + // Calcultae Swing High and Low and Trends ... + CalculateSwingsAndTrend( + swingBarIndex, + prevCalculated, + ratesTotal, + open, + high, + close, + low, + tickVolume // + ); + + // + if (bar_index < swingLength) + { + // + // for (int i = bar_index; i < bar_index + swingLength; i++) + // { + // // + // trendBuffer[i] = lTrend; + // swingLowsBuffer[i] = lSwingLow; + // swingHighsBuffer[i] = lSwingHigh; + // trendStateBuffer[i] = lTrendState; + // trendColorBuffer[i] = lTrendColor; + // } + } + } + else + { + FillBuffersZero(bar_index); + } +} + +// +// Custom ... + +/** + * Initial Market Cycles ... + * + * @return ( bool ) + */ +bool InitMarketCycles() +{ + // + bool result = false; + + // + int cPeriodSeconds = PeriodSeconds(_Period); + + // + // Find Cycle Period ... + if (scMethod == X_PERIOD_AUTO) + { + // + // Select Period ... + mSCPeriod = GetCyclePeriod( + X_MARKET_CYCLE_SHORT, + _Period // + ); + } + else + { + mSCPeriod = scPeriod; + } + + // + if (IsValid(mSCPeriod)) + { + mSCLength = PeriodSeconds(mSCPeriod) / cPeriodSeconds; + } + + // + // Find Cycle Period ... + if (mcMethod == X_PERIOD_AUTO) + { + // + // Select Period ... + mMCPeriod = GetCyclePeriod( + X_MARKET_CYCLE_MEDIUM, + _Period // + ); + } + else + { + mMCPeriod = mcPeriod; + } + + // + if (IsValid(mMCPeriod)) + { + mMCLength = PeriodSeconds(mMCPeriod) / cPeriodSeconds; + } + + // + // Find Cycle Period ... + if (lcMethod == X_PERIOD_AUTO) + { + // + // Select Period ... + mLCPeriod = GetCyclePeriod( + X_MARKET_CYCLE_LONG, + _Period // + ); + } + else + { + mLCPeriod = lcPeriod; + } + + // + if (IsValid(mLCPeriod)) + { + mLCLength = PeriodSeconds(mLCPeriod) / cPeriodSeconds; + } + + // + // Find Cycle Period ... + if (hcMethod == X_PERIOD_AUTO) + { + // + // Select Period ... + mHCPeriod = GetCyclePeriod( + X_MARKET_CYCLE_HIND, + _Period // + ); + } + else + { + mHCPeriod = hcPeriod; + } + + // + if (IsValid(mHCPeriod)) + { + mHCLength = PeriodSeconds(mHCPeriod) / cPeriodSeconds; + } + + // + result = mSCLength > 0 && + mMCLength > mSCLength && + mLCLength > mMCLength && + mHCLength > mLCLength; + + // + return result; +} + +/** + * Fill All Bufers to Zero Vlue for Specified Bar Index ... + * + * @param barIndex: Integer ... + */ +void FillBuffersZero(int barIndex) +{ + // + // CURRENT ... + cHHBuffer[barIndex] = EMPTY_VALUE; + cLLBuffer[barIndex] = EMPTY_VALUE; + + // + // SHORT ... + sHHBuffer[barIndex] = EMPTY_VALUE; + sLLBuffer[barIndex] = EMPTY_VALUE; + + // + // MEDIUM ... + mHHBuffer[barIndex] = EMPTY_VALUE; + mLLBuffer[barIndex] = EMPTY_VALUE; + + // + // LONG ... + lHHBuffer[barIndex] = EMPTY_VALUE; + lLLBuffer[barIndex] = EMPTY_VALUE; + + // + // HIND ... + hHHBuffer[barIndex] = EMPTY_VALUE; + hLLBuffer[barIndex] = EMPTY_VALUE; + + // + // PEAKS ... + peaksBuffer[barIndex] = EMPTY_VALUE; + + // + // VALES ... + valesBuffer[barIndex] = EMPTY_VALUE; + + // + // SARS ... + sarBuffer[barIndex] = EMPTY_VALUE; + + // + // Support and Resistances ... + supportsBuffer[barIndex] = EMPTY_VALUE; + resistancesBuffer[barIndex] = EMPTY_VALUE; + + // + trendBuffer[barIndex] = emptyValue; + swingLowsBuffer[barIndex] = emptyValue; + swingHighsBuffer[barIndex] = emptyValue; + trendStateBuffer[barIndex] = emptyValue; + trendColorBuffer[barIndex] = hideColorIDX; + + // + // Fractals ... + fractalsUpperBuffer[barIndex] = EMPTY_VALUE; + fractalsLowerBuffer[barIndex] = EMPTY_VALUE; +} + +/** + * Calculate Specified Market Cycle Info ... + * + * @param barIndex: Integer, Bar Index ... + * @param cycle: ENUM_X_MARKET_CYCLES member, Specified Cycle ... + * @param hhBuffer: Highest High Buffer Reference ... + * @param llBuffer: Lowest Low Buffer Reference ... + */ +void CalculateCycle( + int barIndex, + ENUM_X_MARKET_CYCLES cycle, + double &hhBuffer[], + double &llBuffer[] // +) +{ + // + XOHCL bar; + bool isBarInited = bar.Init( + _Symbol, + _Period, + barIndex + // + ); + if (!isBarInited) + { + return; + } + + // + int mLength = 0; + switch (cycle) + { + // + case X_MARKET_CYCLE_SHORT: + mLength = mSCLength; + break; + + // + case X_MARKET_CYCLE_MEDIUM: + mLength = mMCLength; + break; + + // + case X_MARKET_CYCLE_LONG: + mLength = mLCLength; + break; + + // + case X_MARKET_CYCLE_HIND: + mLength = mHCLength; + break; + } + + // + if (mLength == 0) + { + return; + } + + // + // Find Highest High ... + double hhValue = bar.FindHighest( + mLength, + hhMode + // + ); + hhBuffer[barIndex] = hhValue; + + // + // Find Lowest Low ... + double llValue = bar.FindLowest( + mLength, + llMode + // + ); + llBuffer[barIndex] = llValue; +} + +/** + * Claculate Cycles ... + * + * @param barIndex: Integer, Bar Index ... + */ +void CalculateCycles(int barIndex) +{ + // + // SHORT ... + CalculateCycle( + barIndex, + X_MARKET_CYCLE_SHORT, + sHHBuffer, + sLLBuffer // + ); + + // + // MEDIUM ... + CalculateCycle( + barIndex, + X_MARKET_CYCLE_MEDIUM, + mHHBuffer, + mLLBuffer // + ); + + // + // LONG ... + CalculateCycle( + barIndex, + X_MARKET_CYCLE_LONG, + lHHBuffer, + lLLBuffer // + ); + + // + // HIND ... + CalculateCycle( + barIndex, + X_MARKET_CYCLE_HIND, + hHHBuffer, + hLLBuffer // + ); +} + +/** + * Calculate Peaks and Vales ... + * + * @param barIndex: Integer, Bar Index ... + */ +void CalculatePeaksAndVales(int barIndex) +{ + // + int lastIndex = barIndex + 1; + int barsCount = iBars(_Symbol, _Period); + + // + // PEAKS ... + double lastPeak = + lastIndex < barsCount + ? peaksBuffer[lastIndex] + : 0; + + // + double isHH = sHHBuffer[barIndex]; + double imHH = mHHBuffer[barIndex]; + double ilHH = lHHBuffer[barIndex]; + double ihHH = hHHBuffer[barIndex]; + + // + double iHHs[4] = { + isHH, + imHH, + ilHH, + ihHH // + }; + double rValue = GetAverage(iHHs); + bool isPeak = rValue == isHH && + isHH == imHH && + imHH == ilHH && + ilHH == ihHH; + double iPeak = + isPeak + ? rValue + : lastPeak; + peaksBuffer[barIndex] = iPeak; + + // + // VALES ... + double lastVale = + lastIndex < barsCount + ? valesBuffer[lastIndex] + : 0; + + // + double isLL = sLLBuffer[barIndex]; + double imLL = mLLBuffer[barIndex]; + double ilLL = lLLBuffer[barIndex]; + double ihLL = hLLBuffer[barIndex]; + + // + double iLLs[4] = { + isLL, + imLL, + ilLL, + ihLL // + }; + double sValue = GetAverage(iLLs); + bool isVale = sValue == isLL && + isLL == imLL && + imLL == ilLL && + ilLL == ihLL; + double iVale = + isVale + ? sValue + : lastVale; + valesBuffer[barIndex] = iVale; + + // + // Peaks Golden Zone ... + double iPeakGoldenZone = GetFibonacciLevel( + iPeak, + iVale, + goldenZoneLevel, + X_DIRECTION_BULLISH // + ); + peaksGoldenZoneBuffer[barIndex] = iPeakGoldenZone; + + // + // Vales Golden Zone ... + double iValeGoldenZone = GetFibonacciLevel( + iPeak, + iVale, + goldenZoneLevel, + X_DIRECTION_BEARISH // + ); + valesGoldenZoneBuffer[barIndex] = iValeGoldenZone; + + // +} + +/** + * Calculate Support nad Resistances ... + * + * @param bar_index: int, Specified Bar Index ... + * @param prevCalculated: int, Provides Previous Calculated Bars ... + * @param ratesTotal: int, Provides All Availabled Bars ... + * @param open: double Collection, Provides Open Prices Time Series ... + * @param high: double Collection, Provides High Prices Time Series ... + * @param close: double Collection, Provides Close Prices Time Series ... + * @param low: double Collection, Provides Low Prices Time Series ... + * @param tickVolume: long Collection, Provides Ticks Volume Prices Time Series ... + */ +void CalculateSupportAndResistance( + int bar_index, // Selected Bar Index + const int prevCalculated, + const int ratesTotal, + const double &open[], + const double &high[], + const double &close[], + const double &low[], + const long &tickVolume[] // +) +{ + // + double iUpperFractalsPrev = fractalsUpperBuffer[bar_index + 1]; + double iLowerFractalsPrev = fractalsLowerBuffer[bar_index + 1]; + + // + double iHigh = high[bar_index]; + double iLow = low[bar_index]; + + // + double iSupport = iLowerFractalsPrev != EMPTY_VALUE + ? iLow + : supportsBuffer[bar_index + 1]; + double iResistance = iUpperFractalsPrev != EMPTY_VALUE + ? iHigh + : resistancesBuffer[bar_index + 1]; + + // + supportsBuffer[bar_index] = iSupport; + resistancesBuffer[bar_index] = iResistance; +} + +/** + * Calculate Swing High and Low and Trend ... + * + * @param bar_index: int, Specified Bar Index ... + * @param prevCalculated: int, Provides Previous Calculated Bars ... + * @param ratesTotal: int, Provides All Availabled Bars ... + * @param open: double Collection, Provides Open Prices Time Series ... + * @param high: double Collection, Provides High Prices Time Series ... + * @param close: double Collection, Provides Close Prices Time Series ... + * @param low: double Collection, Provides Low Prices Time Series ... + * @param tickVolume: long Collection, Provides Ticks Volume Prices Time Series ... + */ +void CalculateSwingsAndTrend( + int bar_index, // Selected Bar Index + const int prevCalculated, + const int ratesTotal, + const double &open[], + const double &high[], + const double &close[], + const double &low[], + const long &tickVolume[] // +) +{ + // + int lastBarIndex = bar_index + 1; + bool isFirstBar = + startCalculationForLastBars > 0 + ? bar_index == startCalculationForLastBars + : bar_index == ratesTotal; + + // + double iLow = low[bar_index]; + double iHigh = high[bar_index]; + double iOpen = open[bar_index]; + double iClose = close[bar_index]; + + // + // Swing Low ... + double lastSwingLow = isFirstBar + ? emptyValue + : swingLowsBuffer[lastBarIndex]; + bool isSwingLow = IsSwingLow(high, low, bar_index, swingLength); + double iSwingLow = + !isSwingLow + ? lastSwingLow + : iLow; + swingLowsBuffer[bar_index] = iSwingLow; + if (isSwingLow) + { + lSwingLow = iSwingLow; + } + + // + // Swing High ... + double lastSwingHigh = isFirstBar + ? emptyValue + : swingHighsBuffer[lastBarIndex]; + bool isSwingHigh = IsSwingHigh(high, low, bar_index, swingLength); + double iSwingHigh = + !isSwingHigh + ? lastSwingHigh + : iHigh; + swingHighsBuffer[bar_index] = iSwingHigh; + if (isSwingHigh) + { + lSwingHigh = iSwingHigh; + } + + // + // Calculate Trend ... + + // + double lastTrend = isFirstBar + ? emptyValue + : trendBuffer[lastBarIndex]; + double iTrend = + isSwingLow && + iSwingLow > lastSwingLow + ? iSwingLow + : isSwingHigh && + iSwingHigh < lastSwingHigh + ? iSwingHigh + : lastTrend; + trendBuffer[bar_index] = iTrend; + bool isBullTrnd = + isSwingLow && + iSwingLow > lastSwingLow; + bool isBearTrnd = + isSwingHigh && + iSwingHigh < lastSwingHigh; + bool isTrnd = isBullTrnd || + isBearTrnd; + + // + double lastTrendState = isFirstBar + ? emptyValue + : trendStateBuffer[lastBarIndex]; + double iTrendState = + isSwingLow && + iSwingLow > lastSwingLow + ? 1 + : isSwingHigh && + iSwingHigh < lastSwingHigh + ? -1 + : lastTrendState; + + // + bool isTrendBraked = false; + if (!isTrendBraked) + { + // + bool isBullishState = iTrendState > 0; + bool isBearishState = iTrendState < 0; + + // + isTrendBraked = isBullishState + ? iClose < iTrend + : isBearishState + ? iClose > iTrend + : false; + if (isTrendBraked) + { + // + if (isBullishState) + { + iTrendState = -1; + } + + // + if (isBearishState) + { + iTrendState = 1; + } + } + } + trendStateBuffer[bar_index] = iTrendState; + + // + double iTrendColor = iTrendState == 0 + ? neuturalColorIDX + : iTrendState > 0 + ? bullishColorIDX + : iTrendState < 0 + ? bearishColorIDX + : hideColorIDX; + trendColorBuffer[bar_index] = iTrendColor; + + // + if (isTrnd) + { + // + lTrend = iTrend; + lTrendColor = iTrendColor; + lTrendState = iTrendState; + } +} + +// +// Tools ... + +// +bool IsSwingLow( + const double &high[], + const double &low[], + int index, + int length // +) +{ + // + bool result = false; + + // + result = index - length >= 0; + if (!result) + { + return result; + } + + // + for (int i = 1; i <= length; i++) + { + // + result = low[index] < low[index - 1] && + low[index] < low[index + i]; + if (!result) + { + break; + } + } + + // + return result; +} + +// +bool IsSwingHigh( + const double &high[], + const double &low[], + int index, + int length // +) +{ + // + bool result = false; + + // + result = index - length >= 0; + if (!result) + { + return result; + } + + // + for (int i = 1; i <= length; i++) + { + // + result = high[index] > high[index - 1] && + high[index] > high[index + i]; + if (!result) + { + break; + } + } + + // + return result; +} + +// \ No newline at end of file diff --git a/BKPS/14040203/Indicators/x-saherelm.x121.xstr.mq5 b/BKPS/14040203/Indicators/x-saherelm.x121.xstr.mq5 new file mode 100644 index 0000000..3a95d4d --- /dev/null +++ b/BKPS/14040203/Indicators/x-saherelm.x121.xstr.mq5 @@ -0,0 +1,812 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Indicator +// ------------------------------------------------- +// Name: X121 XSTR +// Description: XSTR ... +// +// +// 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 XSTR Indicator" +#property strict + +// +// Definitions ... + +// +#define ShortName "X121 XSTR" + +// +// Includes Common Library ... +#include "../Libraries/x-saherelm.common.lib.mq5" + +// +// Inputs ... + +// +// Market ... +input group "Market"; +input int strLength = 14; // Length +input double strMultiplier = 3; // Multiplier +input int vidyaLength = 14; // Smothing Length +input ENUM_MA_METHOD strBoundaryMode = MODE_SMA; // Boundary Mode +input ENUM_APPLIED_PRICE strAppliedTo = PRICE_MEDIAN; // Applied To +input ENUM_APPLIED_PRICE vidyaAppliedTo = PRICE_CLOSE; // Smoothing Applied To + +// +input group "Presentation"; +input bool showStr = true; // Show Str +input bool showVidya = true; // Show Vidya +input bool showStrUpper = true; // Show Str Upper +input bool showStrLower = true; // Show Str Lower +input bool showStrLowMa = true; // Show Low Smoothed Buffer +input bool showStrHighMa = true; // Show High Smoothed Buffer + +// +// Buffers ... + +// +#define hideColorIDX 0 +#define bullishColorIDX 1 +#define bearishColorIDX 2 +#define neuturalColorIDX 3 + +// +#define emptyValue 0.0 + +// +#property indicator_chart_window + +// +#property indicator_buffers 10 +#property indicator_plots 6 + +// +// STR ... +#define strBufferIndex 0 +double strBuffer[]; + +#define strColorBufferIndex 1 +double strColorBuffer[]; + +// +#define strPlotBufferIndex 0 +#property indicator_label1 "X121 STR" +#property indicator_type1 DRAW_COLOR_LINE +#property indicator_color1 CLR_NONE, clrLime, clrRed, clrGray +#property indicator_style1 STYLE_SOLID +#property indicator_width1 2 + +// +// Up ... +#define strUpBufferIndex 2 +double strUpBuffer[]; + +// +#define strUpPlotBufferIndex 1 +#property indicator_label2 "X121 STR U" +#property indicator_type2 DRAW_LINE +#property indicator_color2 clrBlueViolet +#property indicator_style2 STYLE_SOLID +#property indicator_width2 1 + +// +// Down ... +#define strDownBufferIndex 3 +double strDownBuffer[]; + +// +#define strDownPlotBufferIndex 2 +#property indicator_label3 "X121 STR D" +#property indicator_type3 DRAW_LINE +#property indicator_color3 clrBlueViolet +#property indicator_style3 STYLE_SOLID +#property indicator_width3 1 + +// +// High MA ... +#define strHighMaBufferIndex 4 +double strHighMaBuffer[]; + +// +#define strHighMaPlotBufferIndex 3 +#property indicator_label4 "X121 STR HSM" +#property indicator_type4 DRAW_LINE +#property indicator_color4 clrAqua +#property indicator_style4 STYLE_SOLID +#property indicator_width4 1 + +// +// Low Ma ... +#define strLowMaBufferIndex 5 +double strLowMaBuffer[]; + +// +#define strLowMaPlotBufferIndex 4 +#property indicator_label5 "X121 STR LSM" +#property indicator_type5 DRAW_LINE +#property indicator_color5 clrMagenta +#property indicator_style5 STYLE_SOLID +#property indicator_width5 1 + +// +// VIDYA ... +#define vidyaBufferIndex 6 +double vidyaBuffer[]; + +// +#define vidyaPlotBufferIndex 5 +#property indicator_label6 "X121 VIDYA" +#property indicator_type6 DRAW_LINE +#property indicator_color6 clrYellow +#property indicator_style6 STYLE_SOLID +#property indicator_width6 1 + +// +// Data Buffers ... + +// +int mLastBufferIndex = 6; + +// +// STR ... + +// +// Atr ... +#define atrBufferIndex mLastBufferIndex + 1 +double atrBuffer[]; + +// +// Price ... +#define strPriceBufferIndex mLastBufferIndex + 2 +double strPriceBuffer[]; + +// +// Trend ... +#define strStateBufferIndex mLastBufferIndex + 3 +double strStateBuffer[]; + +// +// Variables, Properties and etc ... + +// +// this counts Available Bars ... +int limit; + +// +int maxLength; + +// +// ATR Handler ... +int atrHandler = INVALID_HANDLE; + +// +// MA Handler ... +int lowMaHandler = INVALID_HANDLE; +int highMaHandler = INVALID_HANDLE; +int vidyaHandler = INVALID_HANDLE; + +// +bool isStrTrendChanged; +bool isStrStartBearishTrend; +bool isStrStartBullishTrend; + +// +int changeOfTrend; +int startBearishTrend; +int startBullishTrend; + +// +// Event Handlers ... + +/** + * Initialize Indicator ... + * + * @return ( int ) + */ +int OnInit() +{ + // + // Validate Inputs ... + if (!ValidateInputs()) + { + return INIT_PARAMETERS_INCORRECT; + } + + // + // Initialize Indicator Handlers ... + + // + // ATR ... + atrHandler = iATR( + _Symbol, + _Period, + strLength // + ); + bool isInited = atrHandler != INVALID_HANDLE; + if (!isInited) + { + return INIT_FAILED; + } + + // + // Low Ma ... + lowMaHandler = iMA( + _Symbol, + _Period, + strLength, + 0, + strBoundaryMode, + PRICE_LOW // + ); + isInited = lowMaHandler != INVALID_HANDLE; + if (!isInited) + { + return INIT_FAILED; + } + + // + // High Ma ... + highMaHandler = iMA( + _Symbol, + _Period, + strLength, + 0, + strBoundaryMode, + PRICE_HIGH // + ); + isInited = highMaHandler != INVALID_HANDLE; + if (!isInited) + { + return INIT_FAILED; + } + + // + // Vidya ... + vidyaHandler = iVIDyA( + _Symbol, + _Period, + strLength, + vidyaLength, + 0, // Shift ... + vidyaAppliedTo // + ); + isInited = vidyaHandler != INVALID_HANDLE; + if (!isInited) + { + return INIT_FAILED; + } + + // + // because in some cases we may have more than one input for + // calculation and we must prevent any calculation + // untill we pass the biggest input length, here we get max Input length + // and then wait until pass it ... + maxLength = ExtractMaxLengthOfInputs(); + + // + // Define Index Buffers ... + DefineBuffers(); + + // + // Set Indicator ShortName ... + SetIndicatorName(); + + // + // Init Succeed ... + return INIT_SUCCEEDED; +} + +/** + * De Initialize Indicator ... + * + * @param reason: Integer, De Initialization Reason ... + */ +void OnDeinit(const int reason) +{ + // + // REASON_PROGRAM 0 The EA has stopped working calling the ExpertRemove() function + // REASON_REMOVE 1 Program removed from a chart + // REASON_RECOMPILE 2 Program recompiled + // REASON_CHARTCHANGE 3 A symbol or a chart period is changed + // REASON_CHARTCLOSE 4 Chart closed + // REASON_PARAMETERS 5 Inputs changed by a user + // REASON_ACCOUNT 6 Another account has been activated or reconnection to the trade server has occurred due to changes in the account settings + // REASON_TEMPLATE 7 Another chart template applied + // REASON_INITFAILED 8 The OnInit() handler returned a non-zero value + // REASON_CLOSE 9 Terminal closed + + // + IndicatorRelease(atrHandler); + IndicatorRelease(vidyaHandler); + IndicatorRelease(lowMaHandler); + IndicatorRelease(highMaHandler); +} + +/** + * Calculate Bars ... + * + * @param rates_total: Integer, Total Bars on Chart ... + * @param prev_calculated: Integer, Total Calculated Bars on Charts ... + * @param time: DateTime Array, History of Open Time ... + * @param open: Double Array, History of Open Prices ... + * @param high: Double Array, History of High Prices ... + * @param low: Double Array, History of Low Prices ... + * @param close: Double Array, History of Close Prices ... + * @param tick_volume: Long, History of Tick Volumes on Bar ... + * @param volume: Long, History of Trade Volumes ... + * @param spread: Double, History of Spread Price ... + * + * @return ( int ) + */ +int OnCalculate( + const int rates_total, + const int prev_calculated, + const datetime &time[], + const double &open[], + const double &high[], + const double &low[], + const double &close[], + const long &tick_volume[], + const long &volume[], + const int &spread[] // +) +{ + // + // Prepare Buffers ... + + // + // Validate Calculated Bars ... + + // + // ATR ... + int atrCalculatedBars = BarsCalculated(atrHandler); + + // + // VIDYA ... + int vidyaCalculatedBars = BarsCalculated(vidyaHandler); + + // + // Low Ma ... + int lowMaCalculatedBars = BarsCalculated(lowMaHandler); + + // + // High Ma ... + int highMaCalculatedBars = BarsCalculated(highMaHandler); + + // + bool isPassedRequiredCalculatedBars = + // + // ATR ... + atrCalculatedBars >= 0 && + // + // VIDYA ... + vidyaCalculatedBars >= 0 && + // + // Low Ma ... + lowMaCalculatedBars >= 0 && + // + // High Ma ... + highMaCalculatedBars >= 0 + // + ; + if (!isPassedRequiredCalculatedBars) + { + return prev_calculated; + } + + // + // + // checking for the limit start of calculation of an indicator ... + limit = + (prev_calculated > rates_total || prev_calculated <= 0) + ? maxLength + : prev_calculated - 1; + + // + // Buffers Copy ... + + // + // ATR ... + int copiedAtrs = CopyBuffer(atrHandler, 0, 0, rates_total, atrBuffer); + + // + // VYDIA ... + int copiedVidyas = CopyBuffer(vidyaHandler, 0, 0, rates_total, vidyaBuffer); + + // + // Low Ma ... + int copiedLowMas = CopyBuffer(lowMaHandler, 0, 0, rates_total, strLowMaBuffer); + + // + // High Ma ... + int copiedHighMas = CopyBuffer(highMaHandler, 0, 0, rates_total, strHighMaBuffer); + + // + // Validate Copied Items ... + bool isPassedRequiredCopiedItems = + // + // ATR ... + copiedAtrs >= 0 && + // + // VIDYA ... + copiedVidyas >= 0 && + // + // Low Ma ... + copiedLowMas >= 0 && + // + // Hig Ma ... + copiedHighMas >= 0 + // + ; + if (!isPassedRequiredCopiedItems) + { + return prev_calculated; + } + + // + // Main Loop ... + for (int i = limit; i < rates_total && !IsStopped(); i++) + { + // + CalculateBuffers( + i, + prev_calculated, + rates_total, + // + open, + high, + close, + low, + tick_volume // + ); + } + + // + return rates_total; +} + +// +// Functions ... + +/** + * Validate Input Args for Initialization ... + * + * @return ( bool ) + */ +bool ValidateInputs() +{ + // + bool result = + // + // STR ... + strLength > 0 && + strMultiplier > 0 + // + ; + + // + return result; +} + +/** + * Extract Max Length of Inputs ... + * + * @return ( int ) + */ +int ExtractMaxLengthOfInputs() +{ + // + int result = 0; + + // + result = MathMax(1, strLength); + + // + return result; +} + +/** + * Define Required Buffers ... + */ +void DefineBuffers() +{ + // + // STR ... + SetIndexBuffer(strBufferIndex, strBuffer, INDICATOR_DATA); + SetIndexBuffer(strColorBufferIndex, strColorBuffer, INDICATOR_COLOR_INDEX); + + // + ENUM_DRAW_TYPE strUpDrawType = showStrUpper ? DRAW_LINE : DRAW_NONE; + SetIndexBuffer(strUpBufferIndex, strUpBuffer, INDICATOR_DATA); + PlotIndexSetDouble(strUpPlotBufferIndex, PLOT_EMPTY_VALUE, emptyValue); + PlotIndexSetInteger(strUpPlotBufferIndex, PLOT_SHOW_DATA, showStrUpper); + PlotIndexSetInteger(strUpPlotBufferIndex, PLOT_DRAW_TYPE, strUpDrawType); + + // + ENUM_DRAW_TYPE strDownDrawType = showStrLower ? DRAW_LINE : DRAW_NONE; + SetIndexBuffer(strDownBufferIndex, strDownBuffer, INDICATOR_DATA); + PlotIndexSetDouble(strDownPlotBufferIndex, PLOT_EMPTY_VALUE, emptyValue); + PlotIndexSetInteger(strDownPlotBufferIndex, PLOT_SHOW_DATA, showStrLower); + PlotIndexSetInteger(strDownPlotBufferIndex, PLOT_DRAW_TYPE, strDownDrawType); + + // + ENUM_DRAW_TYPE strLowMaDrawType = showStrLowMa ? DRAW_LINE : DRAW_NONE; + SetIndexBuffer(strLowMaBufferIndex, strLowMaBuffer, INDICATOR_DATA); + PlotIndexSetDouble(strLowMaPlotBufferIndex, PLOT_EMPTY_VALUE, emptyValue); + PlotIndexSetInteger(strLowMaPlotBufferIndex, PLOT_SHOW_DATA, showStrLowMa); + PlotIndexSetInteger(strLowMaPlotBufferIndex, PLOT_DRAW_TYPE, strLowMaDrawType); + + // + ENUM_DRAW_TYPE strHighMaDrawType = showStrHighMa ? DRAW_LINE : DRAW_NONE; + SetIndexBuffer(strHighMaBufferIndex, strHighMaBuffer, INDICATOR_DATA); + PlotIndexSetDouble(strHighMaPlotBufferIndex, PLOT_EMPTY_VALUE, emptyValue); + PlotIndexSetInteger(strHighMaPlotBufferIndex, PLOT_SHOW_DATA, showStrHighMa); + PlotIndexSetInteger(strHighMaPlotBufferIndex, PLOT_DRAW_TYPE, strHighMaDrawType); + + // + ENUM_DRAW_TYPE vidyaDrawType = showVidya ? DRAW_LINE : DRAW_NONE; + SetIndexBuffer(vidyaBufferIndex, vidyaBuffer, INDICATOR_DATA); + PlotIndexSetDouble(vidyaPlotBufferIndex, PLOT_EMPTY_VALUE, emptyValue); + PlotIndexSetInteger(vidyaPlotBufferIndex, PLOT_SHOW_DATA, showVidya); + PlotIndexSetInteger(vidyaPlotBufferIndex, PLOT_DRAW_TYPE, vidyaDrawType); + + // + // Data Buffers ... + + // + SetIndexBuffer(strPriceBufferIndex, strPriceBuffer, INDICATOR_CALCULATIONS); + SetIndexBuffer(strStateBufferIndex, strStateBuffer, INDICATOR_CALCULATIONS); +} + +/** + * Set Indicator Short Name and also we can define Buffers Labels ... + */ +void SetIndicatorName() +{ + IndicatorSetString(INDICATOR_SHORTNAME, ShortName); +} + +/** + * Calculate Custom Buffers ... + * + * @param bar_index: Integer, Represent Current Bar ... + * @param prevCalculated: Integer, Represent Previous Calculated Bars ... + * @param ratesTotal: Integer, Represents All Available Bars ... + * @param open: Double Array, History of Open Prices ... + * @param high: Double Array, History of High Prices ... + * @param close: Double Array, History of Close Prices ... + * @param low: Double Array, History of Low Prices ... + * @param tickVolume: Long, History of Tick Volumes on Bar ... + */ +void CalculateBuffers( + int bar_index, // Selected Bar Index + const int prevCalculated, + const int ratesTotal, + const double &open[], + const double &high[], + const double &close[], + const double &low[], + const long &tickVolume[] // +) +{ + // + CalculateStr( + bar_index, + prevCalculated, + ratesTotal, + open, + high, + close, + low // + ); +} + +// +// Custom ... + +/** + * Fill All Bufers to Zero Vlue for Specified Bar Index ... + * + * @param barIndex: Integer ... + */ +void FillBuffersZero(int barIndex) +{ + // + // STR ... + strBuffer[barIndex] = emptyValue; + strUpBuffer[barIndex] = emptyValue; + strDownBuffer[barIndex] = emptyValue; + strPriceBuffer[barIndex] = emptyValue; + strLowMaBuffer[barIndex] = emptyValue; + strHighMaBuffer[barIndex] = emptyValue; + + // + strColorBuffer[barIndex] = hideColorIDX; + strStateBuffer[barIndex] = hideColorIDX; +} + +/** + * Calculate STR ... + * + * @param bar_index: Integer, Represent Current Bar ... + * @param prevCalculated: Integer, Represent Previous Calculated Bars ... + * @param ratesTotal: Integer, Represents All Available Bars ... + * @param open: Double Array, History of Open Prices ... + * @param high: Double Array, History of High Prices ... + * @param close: Double Array, History of Close Prices ... + * @param low: Double Array, History of Low Prices ... + */ +void CalculateStr( + int bar_index, // Selected Bar Index + const int prevCalculated, + const int ratesTotal, + const double &open[], + const double &high[], + const double &close[], + const double &low[] // +) +{ + // + // Calculated Price ... + ENUM_X_PRICE mPType = ToXPrice(strAppliedTo); + double price = GetAppliedPrice( + mPType, + open, + high, + low, + close, + bar_index // + ); + strPriceBuffer[bar_index] = price; + + // + double atr = atrBuffer[bar_index]; + + // + // Up ... + strUpBuffer[bar_index] = price + (strMultiplier * atr); + + // + // Down ... + strDownBuffer[bar_index] = price - (strMultiplier * atr); + + // + if (close[bar_index] > strUpBuffer[bar_index - 1]) + { + // + strStateBuffer[bar_index] = 1; + if (strStateBuffer[bar_index - 1] == -1) + { + changeOfTrend = 1; + } + } + else if (close[bar_index] < strDownBuffer[bar_index - 1]) + { + // + strStateBuffer[bar_index] = -1; + if (strStateBuffer[bar_index - 1] == 1) + { + changeOfTrend = 1; + } + } + else if (strStateBuffer[bar_index - 1] == 1) + { + // + strStateBuffer[bar_index] = 1; + changeOfTrend = 0; + } + else if (strStateBuffer[bar_index - 1] == -1) + { + // + strStateBuffer[bar_index] = -1; + changeOfTrend = 0; + } + + // + // Down Trend Starting ... + if (strStateBuffer[bar_index] < 0 && strStateBuffer[bar_index - 1] > 0) + { + startBearishTrend = 1; + } + else + { + startBearishTrend = 0; + } + + // + // Up Trend Starting ... + if (strStateBuffer[bar_index] > 0 && strStateBuffer[bar_index - 1] < 0) + { + startBullishTrend = 1; + } + else + { + startBullishTrend = 0; + } + + // + if (strStateBuffer[bar_index] > 0 && strDownBuffer[bar_index] < strDownBuffer[bar_index - 1]) + { + strDownBuffer[bar_index] = strDownBuffer[bar_index - 1]; + } + + // + if (strStateBuffer[bar_index] < 0 && strUpBuffer[bar_index] > strUpBuffer[bar_index - 1]) + { + strUpBuffer[bar_index] = strUpBuffer[bar_index - 1]; + } + + // + if (startBearishTrend == 1) + { + strUpBuffer[bar_index] = strPriceBuffer[bar_index] + (strMultiplier * atr); + } + + // + if (startBullishTrend == 1) + { + strDownBuffer[bar_index] = strPriceBuffer[bar_index] - (strMultiplier * atr); + } + + // + // Draw the indicator ... + + // + double colorIDX = hideColorIDX; + strColorBuffer[bar_index] = colorIDX; + + // + if (strStateBuffer[bar_index] == 1) + { + // + strBuffer[bar_index] = strDownBuffer[bar_index]; + if (changeOfTrend == 1) + { + strBuffer[bar_index - 1] = strBuffer[bar_index - 2]; + changeOfTrend = 0; + } + + // + colorIDX = bullishColorIDX; + } + else if (strStateBuffer[bar_index] == -1) + { + // + strBuffer[bar_index] = strUpBuffer[bar_index]; + if (changeOfTrend == 1) + { + // + strBuffer[bar_index - 1] = strBuffer[bar_index - 2]; + changeOfTrend = 0; + } + + // + colorIDX = bearishColorIDX; + } + + // + if (showStr) + { + strColorBuffer[bar_index] = colorIDX; + } + + // + // Str Mid ... + + // + double iStrMid = strDownBuffer[bar_index] + ((strUpBuffer[bar_index] - strDownBuffer[bar_index]) / 2); + + // +} + +// \ No newline at end of file diff --git a/BKPS/14040203/Indicators/x-saherelm.x121.xtrend.mq5 b/BKPS/14040203/Indicators/x-saherelm.x121.xtrend.mq5 new file mode 100644 index 0000000..1da2b39 --- /dev/null +++ b/BKPS/14040203/Indicators/x-saherelm.x121.xtrend.mq5 @@ -0,0 +1,701 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Indicator +// ------------------------------------------------- +// Name: X121 XTREND +// Description: XTREND ... +// +// +// 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 XTREND Indicator" +#property strict + +// +// Definitions ... + +// +#define ShortName "X121 XTREND" + +// +// Includes Common Library ... +#include "../Libraries/x-saherelm.common.lib.mq5" + +// +// Inputs ... + +// +// Market ... +input group "Market"; + +input ENUM_APPLIED_PRICE trendPriceType = PRICE_CLOSE; // Detect Trend Price Type + +input group "MA Detection"; +input int maLength = 50; // MA Length +input ENUM_MA_METHOD maMethod = MODE_EMA; // MA Method +input ENUM_APPLIED_PRICE maAppliedTo = PRICE_CLOSE; // MA Applied To + +input group "ADX Detection"; +input int adxLength = 14; // ADX Length +input double adxThreshold = 25; // ADX Threshold for Strong Trends + +// +// Presentation ... +input group "Presentation"; + +// +input int startCalculationForLastBars = 1000; // Calculate Last n Bars +input int upTrendArrowCode = 233; // Up Trend Arrow Code +input int downTrendArrowCode = 234; // Down Trend Arrow Code + +// +input bool showOnlyTrendStart = true; // Show Only Trend Start +input bool showUpTrend = true; // Show Up Trend +input bool showDownTrend = true; // Show Down Trend + +// +#property indicator_chart_window + +// +#property indicator_buffers 8 +#property indicator_plots 2 + +// +// Plot Buffers ... + +// +#define upTrendBufferIndex 0 +double upTrendBuffer[]; + +// +#property indicator_label1 "X121 XTREND Up" +#property indicator_type1 DRAW_ARROW +#property indicator_color1 clrAqua +#property indicator_width1 1 + +// +#define downTrendBufferIndex 1 +double downTrendBuffer[]; + +// +#property indicator_label2 "X121 XTREND Down" +#property indicator_type2 DRAW_ARROW +#property indicator_color2 clrMagenta +#property indicator_width2 1 + +// +// Data Buffers ... + +// +int mLastBufferIndex = 1; + +// +#define maBufferIndex mLastBufferIndex + 1 +double maBuffer[]; + +// +#define adxBufferIndex mLastBufferIndex + 2 +double adxBuffer[]; + +// +#define adxPBufferIndex mLastBufferIndex + 3 +double adxPBuffer[]; + +// +#define adxMBufferIndex mLastBufferIndex + 4 +double adxMBuffer[]; + +// +#define upTBufferIndex mLastBufferIndex + 5 +double upTBuffer[]; + +// +#define downTBufferIndex mLastBufferIndex + 6 +double downTBuffer[]; + +// +// Variables, Properties and etc ... + +// +// this counts Available Bars ... +int limit; + +// +int maxLength; + +// +double lastValue = 0; +ENUM_X_DIRECTION lastTrendDir = X_DIRECTION_NONE; + +// +// MA Handler ... +int maHandler = INVALID_HANDLE; + +// +// ADX Handler ... +int adxHandler = INVALID_HANDLE; + +// +// Event Handlers ... + +/** + * Initialize Indicator ... + * + * @return ( int ) + */ +int OnInit() +{ + // + // Validate Inputs ... + if (!ValidateInputs()) + { + return INIT_PARAMETERS_INCORRECT; + } + + // + // Initialize Indicator Handlers ... + + // + // MA ... + maHandler = iMA( + _Symbol, + _Period, + maLength, + 0, + maMethod, + maAppliedTo // + ); + bool isInited = maHandler != INVALID_HANDLE; + if (!isInited) + { + return INIT_FAILED; + } + + // + // ADx ... + adxHandler = iADX( + _Symbol, + _Period, + adxLength // + ); + isInited = maHandler != INVALID_HANDLE; + if (!isInited) + { + return INIT_FAILED; + } + + // + // because in some cases we may have more than one input for + // calculation and we must prevent any calculation + // untill we pass the biggest input length, here we get max Input length + // and then wait until pass it ... + maxLength = ExtractMaxLengthOfInputs(); + + // + // Define Index Buffers ... + DefineBuffers(); + + // + // Set Indicator ShortName ... + SetIndicatorName(); + IndicatorSetInteger(INDICATOR_DIGITS, 2); + + // + // Init Succeed ... + return INIT_SUCCEEDED; +} + +/** + * De Initialize Indicator ... + * + * @param reason: Integer, De Initialization Reason ... + */ +void OnDeinit(const int reason) +{ + // + // REASON_PROGRAM 0 The EA has stopped working calling the ExpertRemove() function + // REASON_REMOVE 1 Program removed from a chart + // REASON_RECOMPILE 2 Program recompiled + // REASON_CHARTCHANGE 3 A symbol or a chart period is changed + // REASON_CHARTCLOSE 4 Chart closed + // REASON_PARAMETERS 5 Inputs changed by a user + // REASON_ACCOUNT 6 Another account has been activated or reconnection to the trade server has occurred due to changes in the account settings + // REASON_TEMPLATE 7 Another chart template applied + // REASON_INITFAILED 8 The OnInit() handler returned a non-zero value + // REASON_CLOSE 9 Terminal closed + + // + IndicatorRelease(maHandler); + IndicatorRelease(adxHandler); +} + +/** + * Calculate Bars ... + * + * @param rates_total: Integer, Total Bars on Chart ... + * @param prev_calculated: Integer, Total Calculated Bars on Charts ... + * @param time: DateTime Array, History of Open Time ... + * @param open: Double Array, History of Open Prices ... + * @param high: Double Array, History of High Prices ... + * @param low: Double Array, History of Low Prices ... + * @param close: Double Array, History of Close Prices ... + * @param tick_volume: Long, History of Tick Volumes on Bar ... + * @param volume: Long, History of Trade Volumes ... + * @param spread: Double, History of Spread Price ... + * + * @return ( int ) + */ +int OnCalculate( + const int rates_total, + const int prev_calculated, + const datetime &time[], + const double &open[], + const double &high[], + const double &low[], + const double &close[], + const long &tick_volume[], + const long &volume[], + const int &spread[] // +) +{ + // + // Prepare Buffers ... + ArraySetAsSeries(time, true); + ArraySetAsSeries(open, true); + ArraySetAsSeries(high, true); + ArraySetAsSeries(low, true); + ArraySetAsSeries(close, true); + ArraySetAsSeries(tick_volume, true); + ArraySetAsSeries(volume, true); + ArraySetAsSeries(spread, true); + + // + // Validate Calculated Bars ... + + // + // MA ... + int maCalculatedBars = BarsCalculated(maHandler); + + // + // ADX ... + int adxCalculatedBars = BarsCalculated(adxHandler); + + // + bool isPassedRequiredCalculatedBars = + // + // MA ... + maCalculatedBars >= maxLength && + // + // ADX ... + adxCalculatedBars >= maxLength + // + ; + if (!isPassedRequiredCalculatedBars) + { + return prev_calculated; + } + + // + limit = (prev_calculated > rates_total || prev_calculated <= 0) + ? rates_total + : (rates_total - prev_calculated) + 1; + + // + // Buffers Copy ... + + // + // MA ... + int copiedMas = CopyBuffer(maHandler, 0, 0, limit, maBuffer); + + // + // ADX ... + int copiedAdxs = CopyBuffer(adxHandler, MAIN_LINE, 0, limit, adxBuffer); + int copiedAdxPs = CopyBuffer(adxHandler, PLUSDI_LINE, 0, limit, adxPBuffer); + int copiedAdxMs = CopyBuffer(adxHandler, MINUSDI_LINE, 0, limit, adxMBuffer); + + // + // Validate Copied Items ... + bool isPassedRequiredCopiedItems = + // + // MA ... + copiedMas > 0 && + // + // ADX ... + copiedAdxs > 0 && + copiedAdxPs > 0 && + copiedAdxMs > 0 + // + ; + if (!isPassedRequiredCopiedItems) + { + return prev_calculated; + } + + // + // Main Loop ... + for (int i = limit - 1; i >= 0 && !IsStopped(); i--) + { + // + CalculateBuffers( + i, + prev_calculated, + rates_total, + // + open, + high, + close, + low, + tick_volume // + ); + } + + // + return rates_total; +} + +// +// Functions ... + +/** + * Validate Input Args for Initialization ... + * + * @return ( bool ) + */ +bool ValidateInputs() +{ + // + bool result = false; + + // + result = + // + // MA ... + maLength > 0 && + // + // ADX ... + adxLength > 0 && + adxThreshold > 0 + // + ; + + // + return result; +} + +/** + * Extract Max Length of Inputs ... + * + * @return ( int ) + */ +int ExtractMaxLengthOfInputs() +{ + // + int result = 0; + + // + result = MathMax(maLength, adxLength); + + // + return result; +} + +/** + * Set Indicator Short Name and also we can define Buffers Labels ... + */ +void SetIndicatorName() +{ + IndicatorSetString(INDICATOR_SHORTNAME, ShortName); +} + +/** + * Define Required Buffers ... + */ +void DefineBuffers() +{ + // + // Plot Buffers ... + + // + // UP Trend ... + + // + ENUM_DRAW_TYPE upTrendDrawType = showUpTrend ? DRAW_ARROW : DRAW_NONE; + + // + ArraySetAsSeries(upTrendBuffer, true); + SetIndexBuffer(upTrendBufferIndex, upTrendBuffer, INDICATOR_DATA); + + // + PlotIndexSetInteger(upTrendBufferIndex, PLOT_SHOW_DATA, showUpTrend); + PlotIndexSetInteger(upTrendBufferIndex, PLOT_DRAW_TYPE, upTrendDrawType); + + // + PlotIndexSetDouble(upTrendBufferIndex, PLOT_EMPTY_VALUE, 0); + PlotIndexSetInteger(upTrendBufferIndex, PLOT_ARROW, upTrendArrowCode); + + // + // DOWN Trend ... + + // + ENUM_DRAW_TYPE downTrendDrawType = showDownTrend ? DRAW_ARROW : DRAW_NONE; + + // + ArraySetAsSeries(downTrendBuffer, true); + SetIndexBuffer(downTrendBufferIndex, downTrendBuffer, INDICATOR_DATA); + + // + PlotIndexSetInteger(downTrendBufferIndex, PLOT_SHOW_DATA, showDownTrend); + PlotIndexSetInteger(downTrendBufferIndex, PLOT_DRAW_TYPE, downTrendDrawType); + + // + PlotIndexSetDouble(downTrendBufferIndex, PLOT_EMPTY_VALUE, 0); + PlotIndexSetInteger(downTrendBufferIndex, PLOT_ARROW, downTrendArrowCode); + + // + // Data Buffers ... + + // + ArraySetAsSeries(maBuffer, true); + SetIndexBuffer(maBufferIndex, maBuffer, INDICATOR_CALCULATIONS); + + // + ArraySetAsSeries(adxBuffer, true); + SetIndexBuffer(adxBufferIndex, adxBuffer, INDICATOR_CALCULATIONS); + + // + ArraySetAsSeries(adxPBuffer, true); + SetIndexBuffer(adxPBufferIndex, adxPBuffer, INDICATOR_CALCULATIONS); + + // + ArraySetAsSeries(adxMBuffer, true); + SetIndexBuffer(adxMBufferIndex, adxMBuffer, INDICATOR_CALCULATIONS); + + // + ArraySetAsSeries(upTBuffer, true); + SetIndexBuffer(upTBufferIndex, upTBuffer, INDICATOR_CALCULATIONS); + + // + ArraySetAsSeries(downTBuffer, true); + SetIndexBuffer(downTBufferIndex, downTBuffer, INDICATOR_CALCULATIONS); +} + +/** + * Calculate Custom Buffers ... + * + * @param bar_index: Integer, Represent Current Bar ... + * @param prevCalculated: Integer, Represent Previous Calculated Bars ... + * @param ratesTotal: Integer, Represents All Available Bars ... + * @param open: Double Array, History of Open Prices ... + * @param high: Double Array, History of High Prices ... + * @param close: Double Array, History of Close Prices ... + * @param low: Double Array, History of Low Prices ... + * @param tickVolume: Long, History of Tick Volumes on Bar ... + */ +void CalculateBuffers( + int bar_index, // Selected Bar Index + const int prevCalculated, + const int ratesTotal, + const double &open[], + const double &high[], + const double &close[], + const double &low[], + const long &tickVolume[] // +) +{ + // + int barsLimit = startCalculationForLastBars > 0 + ? startCalculationForLastBars + : 0; + // + // bool canCalculate = true; + bool canCalculate = + barsLimit == 0 || + bar_index <= barsLimit; + if (canCalculate) + { + // + CalculateTrend( + bar_index, + prevCalculated, + ratesTotal, + open, + high, + close, + low, + tickVolume // + ); + } + else + { + FillBuffersZero(bar_index); + } +} + +/** + * Fill All Bufers to Zero Vlue for Specified Bar Index ... + * + * @param barIndex: Integer ... + */ +void FillBuffersZero(int barIndex) +{ + // + upTrendBuffer[barIndex] = 0; + downTrendBuffer[barIndex] = 0; + + // + maBuffer[barIndex] = 0; + adxBuffer[barIndex] = 0; + adxPBuffer[barIndex] = 0; + adxMBuffer[barIndex] = 0; +} + +/** + * Calculate Trends ... + * + * @param bar_index: Integer, Represent Current Bar ... + * @param prevCalculated: Integer, Represent Previous Calculated Bars ... + * @param ratesTotal: Integer, Represents All Available Bars ... + * @param open: Double Array, History of Open Prices ... + * @param high: Double Array, History of High Prices ... + * @param close: Double Array, History of Close Prices ... + * @param low: Double Array, History of Low Prices ... + * @param tickVolume: Long, History of Tick Volumes on Bar ... + */ +void CalculateTrend( + int bar_index, // Selected Bar Index + const int prevCalculated, + const int ratesTotal, + const double &open[], + const double &high[], + const double &close[], + const double &low[], + const long &tickVolume[] // +) +{ + // + ENUM_X_PRICE mPType = ToXPrice(trendPriceType); + double iPrice = GetAppliedPrice( + mPType, + open, + high, + low, + close, + bar_index // + ); + + // + double iMa = maBuffer[bar_index]; + double iAdx = adxBuffer[bar_index]; + double points = GetPoints(_Symbol); + double points10 = 10 * points; + + // + bool isUpTrend = + iPrice > iMa && + iAdx > adxThreshold; + bool isDownTrend = + iPrice < iMa && + iAdx > adxThreshold; + + // + if (isUpTrend) + { + // + // double iLastValue = + // prevCalculated <= 0 + // ? 0 + // : upTrendBuffer[bar_index + 1]; + // if (iLastValue > 0 && + // iValue > iLastValue) + // { + // iValue = iLastValue; + // } + + // + double selectedValue = low[bar_index] - points10; + + // + double iValue = + !IsBullish(lastTrendDir) ? selectedValue + : !showOnlyTrendStart + ? lastValue + : 0; + + // + upTrendBuffer[bar_index] = iValue; + upTBuffer[bar_index] = selectedValue; + + // + downTrendBuffer[bar_index] = 0; + + // + lastValue = iValue; + lastTrendDir = X_DIRECTION_BULLISH; + } + else if (isDownTrend) + { + // + // double iLastValue = + // prevCalculated <= 0 + // ? 0 + // : downTrendBuffer[bar_index + 1]; + // if (iLastValue > 0 && + // iValue < iLastValue) + // { + // iValue = iLastValue; + // } + + // + double selectedValue = high[bar_index] + points10; + + // + double iValue = + !IsBearish(lastTrendDir) ? selectedValue + : !showOnlyTrendStart + ? lastValue + : 0; + + // + upTrendBuffer[bar_index] = 0; + downTrendBuffer[bar_index] = iValue; + downTBuffer[bar_index] = selectedValue; + + // + lastValue = iValue; + lastTrendDir = X_DIRECTION_BEARISH; + } + else + { + // + double iValue = + IsBullish(lastTrendDir) + ? showOnlyTrendStart + ? 0 + : lastValue + : IsBearish(lastTrendDir) + ? showOnlyTrendStart + ? 0 + : lastValue + : 0; + + // + upTrendBuffer[bar_index] = 0; + downTrendBuffer[bar_index] = 0; + + // + upTBuffer[bar_index] = 0; + downTBuffer[bar_index] = 0; + + // + lastValue = 0; + lastTrendDir = X_DIRECTION_NONE; + } +} \ No newline at end of file diff --git a/BKPS/14040203/Indicators/x-saherelm.x121.xvolume.mq5 b/BKPS/14040203/Indicators/x-saherelm.x121.xvolume.mq5 new file mode 100644 index 0000000..0c2bb28 --- /dev/null +++ b/BKPS/14040203/Indicators/x-saherelm.x121.xvolume.mq5 @@ -0,0 +1,544 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Ocillator +// ------------------------------------------------- +// Name: X121 XVolume +// Description: Detect Bullish/Bearish Volumes ... +// +// +// 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 XVolume Ocillator" +#property strict + +// +// Definitions ... + +// +#define ShortName "X121_XVOLUME" + +// +// Imports ... +#include "../Libraries/x-saherelm.common.lib.mq5" + +// +// Inputs ... + +// +// Makret ... +input group "Market"; +input int maLength = 14; // Moving Averge Length +input ENUM_X_MA_METHOD maMethod = X_MA_MODE_EMA; // Moving Averge Method + +// +// Presentation ... +input group "Presentation"; +input int startCalculationForLastBars = 1000; // Calculate Last n Bars +input bool showBullishVolume = true; // Show Bullish Volume +input bool showBullishVolumeMa = true; // Show Bullish Volume Moving Average +input bool showBearishVolume = true; // Show Bearish Volume +input bool showBearishVolumeMa = true; // Show Bearish Volume Moving Average + +// +// Buffers Props ... + +// +#property indicator_separate_window + +// +#property indicator_buffers 6 +#property indicator_plots 4 + +// +// Buffers ... + +// +#define bullishVolumeBufferIndex 0 +double bullishVolumeBuffer[]; + +#property indicator_label1 "Bullish Volume" +#property indicator_type1 DRAW_HISTOGRAM +#property indicator_color1 clrLime +#property indicator_style1 STYLE_DOT +#property indicator_width1 1 + +// +#define bullishVolumeMaBufferIndex 1 +double bullishVolumeMaBuffer[]; + +#property indicator_label2 "Bullish Volume MA" +#property indicator_type2 DRAW_LINE +#property indicator_color2 clrLime +#property indicator_style2 STYLE_SOLID +#property indicator_width2 1 + +// +#define bearishVolumeBufferIndex 2 +double bearishVolumeBuffer[]; + +#property indicator_label3 "Bearish Volume" +#property indicator_type3 DRAW_HISTOGRAM +#property indicator_color3 clrRed +#property indicator_style3 STYLE_DOT +#property indicator_width3 1 + +// +#define bearishVolumeMaBufferIndex 3 +double bearishVolumeMaBuffer[]; + +#property indicator_label4 "Bearish Volume MA" +#property indicator_type4 DRAW_LINE +#property indicator_color4 clrRed +#property indicator_style4 STYLE_SOLID +#property indicator_width4 1 + +// +// Data Buffers ... + +#define mLastBufferIndex 3 + +// +#define rawBullishVolumeBufferIndex mLastBufferIndex + 1 +double rawBullishVolumeBuffer[]; + +// +#define rawBearishVolumeBufferIndex mLastBufferIndex + 2 +double rawBearishVolumeBuffer[]; + +// +// Variables, Properties and etc ... + +// +// this counts Available Bars ... +int limit; + +// +int maxLength; + +// +// Event Handlers ... + +/** + * Initialize Indicator ... + * + * @return ( int ) + */ +int OnInit() +{ + // + // Validate Inputs ... + if (!ValidateInputs()) + { + return INIT_PARAMETERS_INCORRECT; + } + + // + // Initialize Indicator Handlers ... + + // + // because in some cases we may have more than one input for + // calculation and we must prevent any calculation + // untill we pass the biggest input length, here we get max Input length + // and then wait until pass it ... + maxLength = ExtractMaxLengthOfInputs(); + + // + // Define Index Buffers ... + DefineBuffers(); + + // + // Set Indicator ShortName ... + SetIndicatorName(); + IndicatorSetInteger(INDICATOR_DIGITS, 2); + + // + // Init Succeed ... + return INIT_SUCCEEDED; +} + +/** + * De Initialize Indicator ... + * + * @param reason: Integer, De Initialization Reason ... + */ +void OnDeinit(const int reason) +{ + // + // REASON_PROGRAM 0 The EA has stopped working calling the ExpertRemove() function + // REASON_REMOVE 1 Program removed from a chart + // REASON_RECOMPILE 2 Program recompiled + // REASON_CHARTCHANGE 3 A symbol or a chart period is changed + // REASON_CHARTCLOSE 4 Chart closed + // REASON_PARAMETERS 5 Inputs changed by a user + // REASON_ACCOUNT 6 Another account has been activated or reconnection to the trade server has occurred due to changes in the account settings + // REASON_TEMPLATE 7 Another chart template applied + // REASON_INITFAILED 8 The OnInit() handler returned a non-zero value + // REASON_CLOSE 9 Terminal closed +} + +/** + * Calculate Bars ... + * + * @param rates_total: Integer, Total Bars on Chart ... + * @param prev_calculated: Integer, Total Calculated Bars on Charts ... + * @param time: DateTime Array, History of Open Time ... + * @param open: Double Array, History of Open Prices ... + * @param high: Double Array, History of High Prices ... + * @param low: Double Array, History of Low Prices ... + * @param close: Double Array, History of Close Prices ... + * @param tick_volume: Long, History of Tick Volumes on Bar ... + * @param volume: Long, History of Trade Volumes ... + * @param spread: Double, History of Spread Price ... + * + * @return ( int ) + */ +int OnCalculate( + const int rates_total, + const int prev_calculated, + const datetime &time[], + const double &open[], + const double &high[], + const double &low[], + const double &close[], + const long &tick_volume[], + const long &volume[], + const int &spread[] // +) +{ + // + // Prepare Buffers ... + ArraySetAsSeries(time, true); + ArraySetAsSeries(open, true); + ArraySetAsSeries(high, true); + ArraySetAsSeries(low, true); + ArraySetAsSeries(close, true); + ArraySetAsSeries(tick_volume, true); + ArraySetAsSeries(volume, true); + ArraySetAsSeries(spread, true); + + // + limit = (prev_calculated > rates_total || prev_calculated <= 0) + ? rates_total + : (rates_total - prev_calculated) + 1; + + // + // Main Loop ... + for (int i = limit - 1; i >= 0 && !IsStopped(); i--) + { + // + CalculateBuffers( + // + i, + prev_calculated, + rates_total, + // + open, + high, + close, + low, + tick_volume // + ); + } + + // + return rates_total; +} + +// +// Functions ... + +/** + * Validate Input Args for Initialization ... + * + * @return ( bool ) + */ +bool ValidateInputs() +{ + // + bool result = false; + + // + result = maLength > 0 && + IsValid(maMethod); + + // + return result; +} + +/** + * Extract Max Length of Inputs ... + * + * @return ( int ) + */ +int ExtractMaxLengthOfInputs() +{ + // + int result = 0; + + // + result = MathMax(0, maLength); + + // + return result; +} + +/** + * Set Indicator Short Name and also we can define Buffers Labels ... + */ +void SetIndicatorName() +{ + IndicatorSetString(INDICATOR_SHORTNAME, ShortName); +} + +/** + * Define Required Buffers ... + */ +void DefineBuffers() +{ + // + // Plot Buffers ... + + // + // Bullish ... + + // + // Volume ... + ENUM_DRAW_TYPE bullishVolumeDrawType = showBullishVolume ? DRAW_HISTOGRAM : DRAW_NONE; + + // + ArraySetAsSeries(bullishVolumeBuffer, true); + SetIndexBuffer(bullishVolumeBufferIndex, bullishVolumeBuffer, INDICATOR_DATA); + PlotIndexSetDouble(bullishVolumeBufferIndex, PLOT_EMPTY_VALUE, EMPTY_VALUE); + PlotIndexSetInteger(bullishVolumeBufferIndex, PLOT_SHOW_DATA, showBullishVolume); + PlotIndexSetInteger(bullishVolumeBufferIndex, PLOT_DRAW_TYPE, bullishVolumeDrawType); + + // + // Average ... + ENUM_DRAW_TYPE bullishVolumeMaDrawType = showBullishVolumeMa ? DRAW_LINE : DRAW_NONE; + + // + ArraySetAsSeries(bullishVolumeMaBuffer, true); + SetIndexBuffer(bullishVolumeMaBufferIndex, bullishVolumeMaBuffer, INDICATOR_DATA); + PlotIndexSetDouble(bullishVolumeMaBufferIndex, PLOT_EMPTY_VALUE, 0.0); + PlotIndexSetInteger(bullishVolumeMaBufferIndex, PLOT_SHOW_DATA, showBullishVolumeMa); + PlotIndexSetInteger(bullishVolumeMaBufferIndex, PLOT_DRAW_TYPE, bullishVolumeMaDrawType); + + // + // Bearish ... + + // + // Volume ... + ENUM_DRAW_TYPE bearishVolumeDrawType = showBearishVolume ? DRAW_HISTOGRAM : DRAW_NONE; + + // + ArraySetAsSeries(bearishVolumeBuffer, true); + SetIndexBuffer(bearishVolumeBufferIndex, bearishVolumeBuffer, INDICATOR_DATA); + PlotIndexSetDouble(bearishVolumeBufferIndex, PLOT_EMPTY_VALUE, EMPTY_VALUE); + PlotIndexSetInteger(bearishVolumeBufferIndex, PLOT_SHOW_DATA, showBearishVolume); + PlotIndexSetInteger(bearishVolumeBufferIndex, PLOT_DRAW_TYPE, bearishVolumeDrawType); + + // + // Average ... + ENUM_DRAW_TYPE bearishVolumeMaDrawType = showBearishVolumeMa ? DRAW_LINE : DRAW_NONE; + + // + ArraySetAsSeries(bearishVolumeMaBuffer, true); + SetIndexBuffer(bearishVolumeMaBufferIndex, bearishVolumeMaBuffer, INDICATOR_DATA); + PlotIndexSetDouble(bearishVolumeMaBufferIndex, PLOT_EMPTY_VALUE, 0.0); + PlotIndexSetInteger(bearishVolumeMaBufferIndex, PLOT_SHOW_DATA, showBearishVolumeMa); + PlotIndexSetInteger(bearishVolumeMaBufferIndex, PLOT_DRAW_TYPE, bearishVolumeMaDrawType); + + // + // Data Buffers ... + + // + ArraySetAsSeries(rawBullishVolumeBuffer, true); + SetIndexBuffer(rawBullishVolumeBufferIndex, rawBullishVolumeBuffer, INDICATOR_CALCULATIONS); + + // + ArraySetAsSeries(rawBearishVolumeBuffer, true); + SetIndexBuffer(rawBearishVolumeBufferIndex, rawBearishVolumeBuffer, INDICATOR_CALCULATIONS); +} + +/** + * Calculate Custom Buffers ... + * + * @param bar_index: Integer, Represent Current Bar ... + * @param prevCalculated: Integer, Represent Previous Calculated Bars ... + * @param ratesTotal: Integer, Represents All Available Bars ... + * @param open: Double Array, History of Open Prices ... + * @param high: Double Array, History of High Prices ... + * @param close: Double Array, History of Close Prices ... + * @param low: Double Array, History of Low Prices ... + * @param tickVolume: Long, History of Tick Volumes on Bar ... + */ +void CalculateBuffers( + int bar_index, // Selected Bar Index + const int prevCalculated, + const int ratesTotal, + const double &open[], + const double &high[], + const double &close[], + const double &low[], + const long &tickVolume[] // +) +{ + // + int barsLimit = startCalculationForLastBars > 0 + ? startCalculationForLastBars + : 0; + // + // bool canCalculate = true; + bool canCalculate = + barsLimit == 0 || + bar_index <= barsLimit; + if (canCalculate) + { + // + CalculateValues( + bar_index, + prevCalculated, + ratesTotal, + open, + high, + close, + low, + tickVolume // + ); + } + else + { + FillBuffersZero(bar_index); + } +} + +/** + * Fill All Bufers to Zero Vlue for Specified Bar Index ... + * + * @param barIndex: Integer ... + */ +void FillBuffersZero(int barIndex) +{ + // + bullishVolumeBuffer[barIndex] = EMPTY_VALUE; + bullishVolumeMaBuffer[barIndex] = EMPTY_VALUE; + rawBullishVolumeBuffer[barIndex] = 0; + + // + bearishVolumeBuffer[barIndex] = EMPTY_VALUE; + bearishVolumeMaBuffer[barIndex] = EMPTY_VALUE; + rawBearishVolumeBuffer[barIndex] = 0; +} + +/** + * Calculate Vales ... + * + * @param bar_index: Integer, Represent Current Bar ... + * @param prevCalculated: Integer, Represent Previous Calculated Bars ... + * @param ratesTotal: Integer, Represents All Available Bars ... + * @param open: Double Array, History of Open Prices ... + * @param high: Double Array, History of High Prices ... + * @param close: Double Array, History of Close Prices ... + * @param low: Double Array, History of Low Prices ... + * @param tickVolume: Long, History of Tick Volumes on Bar ... + */ +void CalculateValues( + int bar_index, // Selected Bar Index + const int prevCalculated, + const int ratesTotal, + const double &open[], + const double &high[], + const double &close[], + const double &low[], + const long &tickVolume[] // +) +{ + // + XOHCL bar; + bool has = bar.Init( + _Symbol, + _Period, + bar_index // + ); + if (!has) + { + return; + } + + // + double iBullishVolume = 0; + double iBearishVolume = 0; + + // + if (bar.IsBullish()) + { + // + iBullishVolume = (double)bar.volume; + iBearishVolume = 0; + } + else if (bar.IsBearish()) + { + // + iBearishVolume = (double)bar.volume; + iBullishVolume = 0; + } + else + { + // + double volume = ((double)bar.volume) / 2.0; + iBullishVolume = volume; + iBearishVolume = volume; + } + + // + bullishVolumeBuffer[bar_index] = + iBullishVolume == 0 + ? EMPTY_VALUE + : iBullishVolume; + rawBullishVolumeBuffer[bar_index] = iBullishVolume; + + // + bearishVolumeBuffer[bar_index] = + iBearishVolume == 0 + ? EMPTY_VALUE + : iBearishVolume; + rawBearishVolumeBuffer[bar_index] = iBearishVolume; + + // + // Calculate Moving Averages ... + + // + int bullishMAsCount = iMAOnBuffer( + ratesTotal, + prevCalculated, + bar_index, + maLength, + rawBullishVolumeBuffer, + bullishVolumeMaBuffer, + maMethod // + ); + + // + int bearishMAsCount = iMAOnBuffer( + ratesTotal, + prevCalculated, + bar_index, + maLength, + rawBearishVolumeBuffer, + bearishVolumeMaBuffer, + maMethod // + ); + + // + bar.Clean(); +} + +// diff --git a/BKPS/14040203/Indicators/x-saherelm.x121.xvwap.mq5 b/BKPS/14040203/Indicators/x-saherelm.x121.xvwap.mq5 new file mode 100644 index 0000000..ca2a2c4 --- /dev/null +++ b/BKPS/14040203/Indicators/x-saherelm.x121.xvwap.mq5 @@ -0,0 +1,712 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Indicator +// ------------------------------------------------- +// Name: X121 XVWAP +// Description: XVWAP ... +// +// +// 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 XVWAP Indicator" +#property strict + +// +// Definitions ... + +// +#define ShortName "X121 XVWAP" + +// +// Includes Common Library ... +#include "../Libraries/x-saherelm.common.lib.mq5" + +// +// Inputs ... + +// +// Market ... +input group "Market"; +input int vwapFastLength = 20; // Fast Length +input int vwapMidLength = 40; // Mid Length +input int vwapSlowLength = 60; // Slow Length +input ENUM_APPLIED_PRICE vwapAppliedTo = PRICE_CLOSE; // Applied To + +// +// Presentation ... +input group "Presentation"; + +// +input int startCalculationForLastBars = 1000; // Calculate Last n Bars + +// +input bool showVWapFast = true; // Show VWap Fast +input bool showVWapMedium = true; // Show VWap Medium +input bool showVWapSlow = true; // Show VWap Slow + +// +// Buffers ... + +// +#define hideColorIDX 0 +#define bullishColorIDX 1 +#define bearishColorIDX 2 +#define neuturalColorIDX 3 + +// +#property indicator_chart_window + +// +#property indicator_buffers 11 +#property indicator_plots 3 + +// +// Plot Buffers ... + +// +// FAST ... +#define vwapFastBufferIndex 0 +double vwapFastBuffer[]; + +#define vwapFastColorBufferIndex 1 +double vwapFastColorBuffer[]; + +// +#define vwapFastPlotBufferIndex 0 +#property indicator_label1 "X121 VWF" +#property indicator_type1 DRAW_COLOR_LINE +#property indicator_color1 CLR_NONE, clrAqua, clrMagenta, clrGray +#property indicator_style1 STYLE_SOLID +#property indicator_width1 2 + +// +// MID ... +#define vwapMidBufferIndex 2 +double vwapMidBuffer[]; + +#define vwapMidColorBufferIndex 3 +double vwapMidColorBuffer[]; + +// +#define vwapMidPlotBufferIndex 1 +#property indicator_label2 "X121 VWM" +#property indicator_type2 DRAW_COLOR_LINE +#property indicator_color2 CLR_NONE, clrGreen, clrRed, clrGray +#property indicator_style2 STYLE_SOLID +#property indicator_width2 2 + +// +// SLOW ... +#define vwapSlowBufferIndex 4 +double vwapSlowBuffer[]; + +#define vwapSlowColorBufferIndex 5 +double vwapSlowColorBuffer[]; + +// +#define vwapSlowPlotBufferIndex 2 +#property indicator_label3 "X121 VWS" +#property indicator_type3 DRAW_COLOR_LINE +#property indicator_color3 CLR_NONE, clrSteelBlue, clrDarkRed, clrGray +#property indicator_style3 STYLE_SOLID +#property indicator_width3 2 + +// +// Data Buffers ... + +// +int mLastBufferIndex = 5; + +// +// Volume ... +#define vwapVolumeBufferIndex mLastBufferIndex + 1 +double vwapVolumeBuffer[]; + +// +// Price ... +#define vwapPriceBufferIndex mLastBufferIndex + 2 +double vwapPriceBuffer[]; + +// +// Fast State ... +#define vwapFastStateBufferIndex mLastBufferIndex + 3 +double vwapFastStateBuffer[]; + +// +// Mid State ... +#define vwapMidStateBufferIndex mLastBufferIndex + 4 +double vwapMidStateBuffer[]; + +// +// Slow State ... +#define vwapSlowStateBufferIndex mLastBufferIndex + 5 +double vwapSlowStateBuffer[]; + +// +// Variables, Properties and etc ... + +// +// this counts Available Bars ... +int limit; + +// +int maxLength; + +// +// Event Handlers ... + +/** + * Initialize Indicator ... + * + * @return ( int ) + */ +int OnInit() +{ + // + // Validate Inputs ... + if (!ValidateInputs()) + { + return INIT_PARAMETERS_INCORRECT; + } + + // + // Initialize Indicator Handlers ... + + // + // because in some cases we may have more than one input for + // calculation and we must prevent any calculation + // untill we pass the biggest input length, here we get max Input length + // and then wait until pass it ... + maxLength = ExtractMaxLengthOfInputs(); + + // + // Define Index Buffers ... + DefineBuffers(); + + // + // Set Indicator ShortName ... + SetIndicatorName(); + + // + // Init Succeed ... + return INIT_SUCCEEDED; +} + +/** + * De Initialize Indicator ... + * + * @param reason: Integer, De Initialization Reason ... + */ +void OnDeinit(const int reason) +{ + // + // REASON_PROGRAM 0 The EA has stopped working calling the ExpertRemove() function + // REASON_REMOVE 1 Program removed from a chart + // REASON_RECOMPILE 2 Program recompiled + // REASON_CHARTCHANGE 3 A symbol or a chart period is changed + // REASON_CHARTCLOSE 4 Chart closed + // REASON_PARAMETERS 5 Inputs changed by a user + // REASON_ACCOUNT 6 Another account has been activated or reconnection to the trade server has occurred due to changes in the account settings + // REASON_TEMPLATE 7 Another chart template applied + // REASON_INITFAILED 8 The OnInit() handler returned a non-zero value + // REASON_CLOSE 9 Terminal closed +} + +/** + * Calculate Bars ... + * + * @param rates_total: Integer, Total Bars on Chart ... + * @param prev_calculated: Integer, Total Calculated Bars on Charts ... + * @param time: DateTime Array, History of Open Time ... + * @param open: Double Array, History of Open Prices ... + * @param high: Double Array, History of High Prices ... + * @param low: Double Array, History of Low Prices ... + * @param close: Double Array, History of Close Prices ... + * @param tick_volume: Long, History of Tick Volumes on Bar ... + * @param volume: Long, History of Trade Volumes ... + * @param spread: Double, History of Spread Price ... + * + * @return ( int ) + */ +int OnCalculate( + const int rates_total, + const int prev_calculated, + const datetime &time[], + const double &open[], + const double &high[], + const double &low[], + const double &close[], + const long &tick_volume[], + const long &volume[], + const int &spread[] // +) +{ + // + // Prepare Buffers ... + ArraySetAsSeries(time, true); + ArraySetAsSeries(open, true); + ArraySetAsSeries(high, true); + ArraySetAsSeries(low, true); + ArraySetAsSeries(close, true); + ArraySetAsSeries(tick_volume, true); + ArraySetAsSeries(volume, true); + ArraySetAsSeries(spread, true); + + // + // Validate Calculated Bars ... + + // + limit = (prev_calculated > rates_total || prev_calculated <= 0) + ? rates_total + : (rates_total - prev_calculated) + 1; + + // + // Buffers Copy ... + + // + // Main Loop ... + for (int i = limit - 1; i >= 0 && !IsStopped(); i--) + { + // + CalculateBuffers( + i, + prev_calculated, + rates_total, + // + open, + high, + close, + low, + tick_volume // + ); + } + + // + return rates_total; +} + +// +// Functions ... + +/** + * Validate Input Args for Initialization ... + * + * @return ( bool ) + */ +bool ValidateInputs() +{ + // + bool result = false; + + // + result = + // + vwapFastLength > 2 && + vwapMidLength > vwapFastLength && + vwapSlowLength > vwapMidLength + // + ; + + // + return result; +} + +/** + * Extract Max Length of Inputs ... + * + * @return ( int ) + */ +int ExtractMaxLengthOfInputs() +{ + // + int result = 0; + + // + // XVWAP ... + result = MathMax(result, vwapFastLength); + result = MathMax(result, vwapMidLength); + result = MathMax(result, vwapSlowLength); + + // + return result; +} + +/** + * Define Required Buffers ... + */ +void DefineBuffers() +{ + // + // Plot Buffers ... + + // + // Fast ... + ArraySetAsSeries(vwapFastBuffer, true); + ArraySetAsSeries(vwapFastColorBuffer, true); + SetIndexBuffer(vwapFastBufferIndex, vwapFastBuffer, INDICATOR_DATA); + SetIndexBuffer(vwapFastColorBufferIndex, vwapFastColorBuffer, INDICATOR_COLOR_INDEX); + + // + // Mid ... + ArraySetAsSeries(vwapMidBuffer, true); + ArraySetAsSeries(vwapMidColorBuffer, true); + SetIndexBuffer(vwapMidBufferIndex, vwapMidBuffer, INDICATOR_DATA); + SetIndexBuffer(vwapMidColorBufferIndex, vwapMidColorBuffer, INDICATOR_COLOR_INDEX); + + // + // Slow ... + ArraySetAsSeries(vwapSlowBuffer, true); + ArraySetAsSeries(vwapSlowColorBuffer, true); + SetIndexBuffer(vwapSlowBufferIndex, vwapSlowBuffer, INDICATOR_DATA); + SetIndexBuffer(vwapSlowColorBufferIndex, vwapSlowColorBuffer, INDICATOR_COLOR_INDEX); + + // + // Data Buffers ... + + // + // Volumes ... + ArraySetAsSeries(vwapVolumeBuffer, true); + SetIndexBuffer(vwapVolumeBufferIndex, vwapVolumeBuffer, INDICATOR_CALCULATIONS); + + // + // Price ... + ArraySetAsSeries(vwapPriceBuffer, true); + SetIndexBuffer(vwapPriceBufferIndex, vwapPriceBuffer, INDICATOR_CALCULATIONS); + + // + // Fast State ... + ArraySetAsSeries(vwapFastStateBuffer, true); + SetIndexBuffer(vwapFastStateBufferIndex, vwapFastStateBuffer, INDICATOR_CALCULATIONS); + + // + // Mid State ... + ArraySetAsSeries(vwapMidStateBuffer, true); + SetIndexBuffer(vwapMidStateBufferIndex, vwapMidStateBuffer, INDICATOR_CALCULATIONS); + + // + // Slow State ... + ArraySetAsSeries(vwapSlowStateBuffer, true); + SetIndexBuffer(vwapSlowStateBufferIndex, vwapSlowStateBuffer, INDICATOR_CALCULATIONS); +} + +/** + * Set Indicator Short Name and also we can define Buffers Labels ... + */ +void SetIndicatorName() +{ + IndicatorSetString(INDICATOR_SHORTNAME, ShortName); +} + +/** + * Calculate Custom Buffers ... + * + * @param bar_index: Integer, Represent Current Bar ... + * @param prevCalculated: Integer, Represent Previous Calculated Bars ... + * @param ratesTotal: Integer, Represents All Available Bars ... + * @param open: Double Array, History of Open Prices ... + * @param high: Double Array, History of High Prices ... + * @param close: Double Array, History of Close Prices ... + * @param low: Double Array, History of Low Prices ... + * @param tickVolume: Long, History of Tick Volumes on Bar ... + */ +void CalculateBuffers( + int bar_index, // Selected Bar Index + const int prevCalculated, + const int ratesTotal, + const double &open[], + const double &high[], + const double &close[], + const double &low[], + const long &tickVolume[] // +) +{ + // + int barsLimit = startCalculationForLastBars > 0 + ? startCalculationForLastBars + : 0; + // + // bool canCalculate = true; + bool canCalculate = + barsLimit == 0 || + bar_index <= barsLimit; + if (canCalculate) + { + // + // Calculate Required VWAP Data Buffers ... + if (ratesTotal - bar_index <= maxLength) + { + // + CalculateVWAPDataBuffers( + bar_index, + prevCalculated, + ratesTotal, + open, + high, + close, + low, + tickVolume // + ); + + // + // Prevent Moving Forward ... + } + else + { + // + CalculateVWAPDataBuffers( + bar_index, + prevCalculated, + ratesTotal, + open, + high, + close, + low, + tickVolume // + ); + + // + CalculateVWAPS( + bar_index, + prevCalculated, + ratesTotal, + open, + high, + close, + low, + tickVolume // + ); + } + } + else + { + FillBuffersZero(bar_index); + } +} + +// +// Custom ... + +/** + * Fill All Bufers to Zero Vlue for Specified Bar Index ... + * + * @param barIndex: Integer ... + */ +void FillBuffersZero(int barIndex) +{ + // + vwapFastBuffer[barIndex] = EMPTY_VALUE; + vwapMidBuffer[barIndex] = EMPTY_VALUE; + vwapSlowBuffer[barIndex] = EMPTY_VALUE; + vwapVolumeBuffer[barIndex] = EMPTY_VALUE; + vwapPriceBuffer[barIndex] = EMPTY_VALUE; + + // + vwapFastColorBuffer[barIndex] = hideColorIDX; + vwapMidColorBuffer[barIndex] = hideColorIDX; + vwapSlowColorBuffer[barIndex] = hideColorIDX; + vwapFastStateBuffer[barIndex] = hideColorIDX; + vwapMidStateBuffer[barIndex] = hideColorIDX; + vwapSlowStateBuffer[barIndex] = hideColorIDX; +} + +/** + * Calculate VWAP Value for Specified Bar ... + * + * @param bar_index: Integer, Represent Current Bar ... + * @param prevCalculated: Integer, Represent Previous Calculated Bars ... + * @param ratesTotal: Integer, Represents All Available Bars ... + * @param open: Double Array, History of Open Prices ... + * @param high: Double Array, History of High Prices ... + * @param close: Double Array, History of Close Prices ... + * @param low: Double Array, History of Low Prices ... + * @param tickVolume: Long, History of Tick Volumes on Bar ... + * @param _length: Integer, Specified VWAP Length ... + * @param _show: Boolean, Specified Show Buffer or not ... + * @param _buffer: Double Array Reference, Points to Buffer ... + * @param _colorBuffer: Double Array Reference, Points to Color Buffer ... + * @param _stateBuffer: Double Array Reference, Points to State Buffer ... + */ +void CalculateVWAP( + int bar_index, // Selected Bar Index + const int prevCalculated, + const int ratesTotal, + const double &open[], + const double &high[], + const double &close[], + const double &low[], + const long &tickVolume[], + // + int _length, // Calculation Length + bool _show, + double &_buffer[], + double &_colorBuffer[], + double &_stateBuffer[] // +) +{ + // + double vSum = 0; + double pSum = 0; + double mSum = 0; + for (int x = 0; x < _length; x++) + { + // + pSum += vwapPriceBuffer[x + bar_index]; + vSum += vwapVolumeBuffer[x + bar_index]; + mSum += vwapPriceBuffer[x + bar_index] * vwapVolumeBuffer[x + bar_index]; + } + + // + double iValue = mSum / vSum; + iValue = NormalizeDouble(iValue, _Digits); + + // + _buffer[bar_index] = iValue; + + // + bool isBullish = low[bar_index] > iValue; + bool isBearish = high[bar_index] < iValue; + + // + double iColor = + isBullish + ? bullishColorIDX + : isBearish + ? bearishColorIDX + : neuturalColorIDX; + + // + _colorBuffer[bar_index] = hideColorIDX; + _stateBuffer[bar_index] = iColor; + if (_show) + { + _colorBuffer[bar_index] = iColor; + } +} + +/** + * Calculate VWAP Required Data Buffers ... + * + * @param bar_index: Integer, Represent Current Bar ... + * @param prevCalculated: Integer, Represent Previous Calculated Bars ... + * @param ratesTotal: Integer, Represents All Available Bars ... + * @param open: Double Array, History of Open Prices ... + * @param high: Double Array, History of High Prices ... + * @param close: Double Array, History of Close Prices ... + * @param low: Double Array, History of Low Prices ... + * @param tickVolume: Long, History of Tick Volumes on Bar ... + */ +void CalculateVWAPDataBuffers( + int bar_index, // Selected Bar Index + const int prevCalculated, + const int ratesTotal, + const double &open[], + const double &high[], + const double &close[], + const double &low[], + const long &tickVolume[] // +) +{ + // + ENUM_X_PRICE mPType = ToXPrice(vwapAppliedTo); + double price = GetAppliedPrice( + mPType, + open, + high, + low, + close, + bar_index // + ); + vwapPriceBuffer[bar_index] = price; + vwapVolumeBuffer[bar_index] = (double)tickVolume[bar_index]; +} + +/** + * Calculate Different VWaps ... + * + * @param bar_index: Integer, Represent Current Bar ... + * @param prevCalculated: Integer, Represent Previous Calculated Bars ... + * @param ratesTotal: Integer, Represents All Available Bars ... + * @param open: Double Array, History of Open Prices ... + * @param high: Double Array, History of High Prices ... + * @param close: Double Array, History of Close Prices ... + * @param low: Double Array, History of Low Prices ... + * @param tickVolume: Long, History of Tick Volumes on Bar ... + */ +void CalculateVWAPS( + int bar_index, // Selected Bar Index + const int prevCalculated, + const int ratesTotal, + const double &open[], + const double &high[], + const double &close[], + const double &low[], + const long &tickVolume[] // +) +{ + // + // Fast ... + CalculateVWAP( + bar_index, + prevCalculated, + ratesTotal, + open, + high, + close, + low, + tickVolume, + // + vwapFastLength, + showVWapFast, + vwapFastBuffer, + vwapFastColorBuffer, + vwapFastStateBuffer // + ); + + // + // Mid ... + CalculateVWAP( + bar_index, + prevCalculated, + ratesTotal, + open, + high, + close, + low, + tickVolume, + // + vwapMidLength, + showVWapMedium, + vwapMidBuffer, + vwapMidColorBuffer, + vwapMidStateBuffer // + ); + + // + // Fast ... + CalculateVWAP( + bar_index, + prevCalculated, + ratesTotal, + open, + high, + close, + low, + tickVolume, + // + vwapSlowLength, + showVWapSlow, + vwapSlowBuffer, + vwapSlowColorBuffer, + vwapSlowStateBuffer // + ); +} + +// \ No newline at end of file diff --git a/BKPS/14040203/Libraries/x-saherelm.common.extensions.lib.mq5 b/BKPS/14040203/Libraries/x-saherelm.common.extensions.lib.mq5 new file mode 100644 index 0000000..a7d7c03 --- /dev/null +++ b/BKPS/14040203/Libraries/x-saherelm.common.extensions.lib.mq5 @@ -0,0 +1,6426 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Common Library +// -------------------------------------- +// Name: XCommonExtensionsLib +// 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 + +// +#include "../Classes/x-saherelm.x-md5.class.mq5" +#include "../Libraries/x-saherelm.x-enums.lib.mq5" + +// +#include + +// +// Constants ... +#define X_MIN_SIZE 0 +#define X_INVALID_INDEX -1 + +// +// START Value Checkers ... +// + +// +// Check a Value Not Empty ... +template +bool NotEmpty(T value) +{ + return value != EMPTY_VALUE; +} + +// +// Check a Value Not Empty and Zero ... +template +bool NotEmptyZero(T value) +{ + return value != 0 && + value != EMPTY_VALUE; +} + +// +// END Value Checkers ... +// + +// +// START Validators ... +// + +/** + * Validate Strings ... + * + * @param value: string + * + * @return ( bool ) + */ +bool IsValid(string value) +{ + // + bool result = false; + + // + result = + // + value != NULL && + StringLen(value) > 0 + // + ; + + // + return result; +} +bool IsSpecifiedValid(string value) +{ + return IsValid(value); +} + +/** + * Validate Date ... + * + * @param value: datetime + * + * @return ( bool ) + */ +bool IsValid(datetime value) +{ + // + bool result = false; + + // + result = NotEmpty(value) && value != NULL; + + // + return result; +} +bool IsSpecifiedValid(datetime value) +{ + return IsValid(value); +} + +/** + * Validate Time Frame ... + * + * @param value: ENUM_TIMEFRAMES member ... + * + * @return ( bool ) + */ +bool IsValid(ENUM_TIMEFRAMES value) +{ + // + bool result = false; + + // + result = + // + value != NULL + // + ; + + // + return result; +} +bool IsSpecifiedValid(ENUM_TIMEFRAMES value) +{ + // + return IsValid(value); +} + +/** + * Validate Specific Period Mode ... + * + * @param mMethod: ENUM_X_PERIOD_METHOD member, Period Select Method ... + * @param mPeriod: ENUM_TIMEFRAMES member, Selected Period ... + * + * @return ( bool ) + */ +bool IsValid( + ENUM_X_PERIOD_METHOD mMethod, + ENUM_TIMEFRAMES mPeriod // +) +{ + // + bool result = false; + + // + result = + // + mMethod == X_PERIOD_NONE + ? false + : mMethod == X_PERIOD_MANUALLY + ? mPeriod != NULL + : mMethod == X_PERIOD_AUTO + ? true + : false + // + ; + + // + return result; +} +bool IsSpecifiedValid( + ENUM_X_PERIOD_METHOD mMethod, + ENUM_TIMEFRAMES mPeriod // +) +{ + return IsValid( + mMethod, + mPeriod // + ); +} + +/** + * Validate a Size Value ... + * + * @param value: int, Provided Size ... + * + * @return ( bool ) + */ +bool IsValidSize(int value) +{ + // + bool result = value > X_MIN_SIZE; + + // + return result; +} + +/** + * Check a Given Index is Valid or not ... + * + * @param value: int, Provided Index ... + * + * @return ( bool ) + */ +bool IsValidIndex(int value) +{ + return value >= X_MIN_SIZE; +} + +// +// END Validators ... +// + +// +// START Normalizations ... +// + +/** + * Normalize Symbol ... + * + * @param value: string, Provided Symbols ... + * + * @return ( string ) + */ +string NormalizeSymbol(string value) +{ + // + string result = value; + + // + if (!IsValid(result)) + { + result = _Symbol; + } + + // + return result; +} + +/** + * Normalize Time ... + * + * @param value: datetime, Provided Time ... + * + * @return ( datetime ) + */ +datetime NormalizeTime(datetime value) +{ + // + datetime result = value; + + // + if (!IsValid(result)) + { + result = TimeCurrent(); + } + + // + return result; +} + +/** + * Normalize Period ... + * + * @param value: ENUM_TIMEFRAMES member, Provided Period ... + * + * @return ( ENUM_TIMEFRAMES ) + */ +ENUM_TIMEFRAMES NormalizePeriod(ENUM_TIMEFRAMES value) +{ + // + ENUM_TIMEFRAMES result = value; + + // + if (!IsValid(value)) + { + result = _Period; + } + + // + return result; +} + +/** + * Normalize Market Cycle ... + * + * @param value: ENUM_X_MARKET_CYCLES, Provided Cycle ... + * + * @return ( ENUM_X_MARKET_CYCLES ) + */ +ENUM_X_MARKET_CYCLES NormalizeCycle(ENUM_X_MARKET_CYCLES value) +{ + // + ENUM_X_MARKET_CYCLES result = value; + + // + if (!IsValid(result)) + { + result = X_MARKET_CYCLE_SHORT; + } + + // + return value; +} + +/** + * Normalize Price Boundary ... + * + * @param value: ENUM_X_BOUNDARY_PRICE, Provided Boundary Mode ... + * + * @return ( ENUM_X_BOUNDARY_PRICE ) + */ +ENUM_X_BOUNDARY_PRICE NormalizeBoundary(ENUM_X_BOUNDARY_PRICE value) +{ + // + ENUM_X_BOUNDARY_PRICE result = value; + + // + if (!IsValid(result)) + { + result = X_BOUNDARY_PRICE_HIGH_LOW; + } + + // + return result; +} + +/** + * Normalize Integer Value ... + * + * @param value: int, Provided Value ... + * @param min: int, Minimum Allowed Value ... + * @param max: int, Maximum Allowed Value ... + * + * @return ( int ) + */ +int NormalizeInt( + int value, + int min = 0, + int max = INT_MAX // +) +{ + // + if (value < min) + { + value = min; + } + + // + if (value > max) + { + value = max; + } + + // + return value; +} + +/** + * Normalize Double Value ... + * + * @param value: double, Provided Value ... + * @param min: double, Minimum Allowed Value ... + * @param max: double, Maximum Allowed Value ... + * + * @return ( double ) + */ +double NormalizeDouble( + double value, + double min = 0, + double max = DBL_MAX // +) +{ + // + if (value < min) + { + value = min; + } + + // + if (value > max) + { + value = max; + } + + // + return value; +} + +/** + * Normalize Index based on Collection ... + * + * @param index: int, Provided Index ... + * @param buffer: Collection Reference ... + */ +template +bool NormalizeIndex( + int &index, + T &buffer[] // +) +{ + // + bool result = false; + + // + int size = ArraySize(buffer); + result = IsValidSize(size); + if (!result) + { + return result; + } + + // + if (!IsValidIndex(index)) + { + index = X_MIN_SIZE; + } + + // + if (index > size - 1) + { + index = size - 1; + } + + // + result = IsValidIndex(index) && + index >= X_MIN_SIZE && + index < size; + + // + return result; +} + +/** + * Normalize Start and Count based on Specified Buffer ... + * + * @param start: int, Provided Start index ... + * @param count: int, Provided Number of Iteration ... + * @param buffer: Collection instance ... + */ +template +void NormalizeCount( + int &start, + int &count, + T &buffer[] // +) +{ + // + // Validate Buffer Size ... + int bufferSize = ArraySize(buffer); + if (!IsValidSize(bufferSize)) + { + return; + } + + // + // Normalization Start ... + NormalizeIndex( + start, + buffer // + ); + + // + if (count < start) + { + count = (start - count); + } + + // + // Normalization Count ... + + // + if (count < 0) + { + count = start; + } + + // + if (count > bufferSize - start) + { + count = bufferSize - start; + } +} + +/** + * Normalize a Volume ... + * + * @param mVolume: double, Provided Volume ... + * @param mSymbol: string, Specified Symbol ... + * @param mLength: int, Provided Default floating Length ... + * + * @return ( double ) + */ +double NormalizeVolume( + double mVolume, + string mSymbol = NULL, + int mLength = 2 // +) +{ + // + double result = mVolume; + + // + mSymbol = NormalizeSymbol(mSymbol); + + // + double maxAvailableVolume = SymbolInfoDouble(mSymbol, SYMBOL_VOLUME_MAX); + double minAvailableVolume = SymbolInfoDouble(mSymbol, SYMBOL_VOLUME_MIN); + + // + // Normalize Digits ... + int digits = GetDigits(minAvailableVolume); + + // + mLength = + mLength == 0 || mLength > digits + ? digits + : MathMin(mLength, digits); + + // + // Normalize Volume ... + result = NormalizeDouble(result, mLength); + + // + // Validate Result ... + if (result > maxAvailableVolume) + { + result = maxAvailableVolume; + } + else if (result < minAvailableVolume) + { + result = minAvailableVolume; + } + + // + return result; +} + +/** + * Normalize a Price Value ... + * + * @param mPrice: double, Provided Price ... + * @param mSymbol: string, Provided Symbol ... + * + * @return ( double ) + */ +double NormalizePrice( + double mPrice, + string mSymbol = NULL // +) +{ + // + double result = 0; + + // + mSymbol = NormalizeSymbol(mSymbol); + + // + double tickSize = 0; + result = SymbolInfoDouble(mSymbol, SYMBOL_TRADE_TICK_SIZE, tickSize); + + // + int digits = GetDigits(mSymbol); + result = NormalizeDouble(MathRound(mPrice / tickSize) * tickSize, digits); + + // + return result; +} + +// +// END Normalizations ... +// + +// +// START Position ... +// + +/** + * Determine a Position type is Long or not ... + * + * @param value: ENUM_POSITION_TYPE member, Specified Type ... + * + * @return ( bool ) + */ +bool IsLong(ENUM_POSITION_TYPE value) +{ + // + bool result = value == POSITION_TYPE_BUY; + + // + return result; +} + +/** + * Determine a Position type is Long or not ... + * + * @param value: ENUM_ORDER_TYPE member, Specified Type ... + * + * @return ( bool ) + */ +bool IsLong(ENUM_ORDER_TYPE value) +{ + // + bool result = value == ORDER_TYPE_BUY; + + // + return result; +} + +/** + * Determine a Position type is Long or not ... + * + * @param value: ENUM_X_DIRECTION member, Specified Type ... + * + * @return ( bool ) + */ +bool IsLong(ENUM_X_DIRECTION value) +{ + // + bool result = value == X_DIRECTION_BULLISH; + + // + return result; +} + +/** + * Determine a Position type is Short or not ... + * + * @param value: ENUM_POSITION_TYPE member, Specified Type ... + * + * @return ( bool ) + */ +bool IsShort(ENUM_POSITION_TYPE value) +{ + // + bool result = value == POSITION_TYPE_SELL; + + // + return result; +} + +/** + * Determine a Position type is Short or not ... + * + * @param value: ENUM_ORDER_TYPE member, Specified Type ... + * + * @return ( bool ) + */ +bool IsShort(ENUM_ORDER_TYPE value) +{ + // + bool result = value == ORDER_TYPE_SELL; + + // + return result; +} + +/** + * Determine a Position type is Short or not ... + * + * @param value: ENUM_X_DIRECTION member, Specified Type ... + * + * @return ( bool ) + */ +bool IsShort(ENUM_X_DIRECTION value) +{ + // + bool result = value == X_DIRECTION_BEARISH; + + // + return result; +} + +/** + * Converts Opposit Direction Type ... + * + * @param value: ENUM_POSITION_TYPE member, Specified Type ... + * + * @return ( ENUM_POSITION_TYPE ) + */ +ENUM_POSITION_TYPE Opposit(ENUM_POSITION_TYPE value) +{ + // + ENUM_POSITION_TYPE result = NULL; + + // + bool isLong = IsLong(value); + result = isLong + ? POSITION_TYPE_SELL + : POSITION_TYPE_BUY; + + // + return result; +} + +/** + * Converts Opposit Direction Type ... + * + * @param value: ENUM_ORDER_TYPE member, Specified Type ... + * + * @return ( ENUM_ORDER_TYPE ) + */ +ENUM_ORDER_TYPE Opposit(ENUM_ORDER_TYPE value) +{ + // + ENUM_ORDER_TYPE result = NULL; + + // + bool isLong = IsLong(value); + result = isLong + ? ORDER_TYPE_SELL + : ORDER_TYPE_BUY; + + // + return result; +} + +/** + * Converts To String ... + * + * @param value: ENUM_POSITION_TYPE member ... + * + * @return ( string ) + */ +string ToString(ENUM_POSITION_TYPE value) +{ + // + string result = NULL; + + // + result = + // + IsLong(value) + ? "Long" + : "Short" + // + ; + + // + return result; +} + +/** + * Converts To String ... + * + * @param value: ENUM_ORDER_TYPE member ... + * + * @return ( string ) + */ +string ToString(ENUM_ORDER_TYPE value) +{ + // + string result = NULL; + + // + result = + // + IsLong(value) + ? "Long" + : "Short" + // + ; + + // + return result; +} + +/** + * Get Ask Price ... + * + * @param mSymbol: string, Provided Symbol ... + * + * @return ( double ) + */ +double GetAsk( + string mSymbol = NULL // +) +{ + // + mSymbol = NormalizeSymbol(mSymbol); + + // + double result = SymbolInfoDouble(mSymbol, SYMBOL_ASK); + + // + return result; +} + +/** + * Get Bid Price ... + * + * @param mSymbol: string, Provided Symbol ... + * + * @return ( double ) + */ +double GetBid( + string mSymbol = NULL // +) +{ + // + mSymbol = NormalizeSymbol(mSymbol); + + // + double result = SymbolInfoDouble(mSymbol, SYMBOL_BID); + + // + return result; +} + +/** + * Get Spread Price ... + * + * @param mSymbol: string, Provided Symbol ... + * + * @return ( double ) + */ +double GetSpread( + string mSymbol = NULL // +) +{ + // + mSymbol = NormalizeSymbol(mSymbol); + + // + double ask = GetAsk(mSymbol); + double bid = GetBid(mSymbol); + + // + double result = MathAbs(ask - bid); + + // + return result; +} + +/** + * Get Point Price ... + * + * @param mSymbol: string, Provided Symbol ... + * + * @return ( double ) + */ +double GetPoints( + string mSymbol = NULL // Trading Symbol +) +{ + // + mSymbol = NormalizeSymbol(mSymbol); + + // + double result = SymbolInfoDouble(mSymbol, SYMBOL_POINT); + + // + return result; +} + +/** + * Converts Price to Point ... + * + * @param price: double, price ... + * @param mSymbol: string, Symbol ... + * + * @return ( double ) + */ +double PriceToPoint( + double mPrice, // the price amount which required to calculate + string mSymbol = NULL // Trading Symbol +) +{ + // + double result = 0; + + // + mSymbol = NormalizeSymbol(mSymbol); + mPrice = NormalizePrice(mPrice, mSymbol); + + // + double point = GetPoints(mSymbol); + result = mPrice / point; + + // + return result; +} + +/** + * Get Digits Length ... + * + * @param mSymbol: string, Provided Symbol ... + * + * @return ( double ) + */ +int GetDigits( + string mSymbol = NULL // Trading Symbol +) +{ + // + mSymbol = NormalizeSymbol(mSymbol); + + // + int result = (int)SymbolInfoInteger(mSymbol, SYMBOL_DIGITS); + + // + return result; +} + +/** + * Get Entry Price ... + * + * @param mSymbol: string, Provided Symbol ... + * @param type: ENUM_POSITION_TYPE member, Specified Entry type ... + * + * @return ( double ) + */ +double GetEntry( + string mSymbol = NULL, + ENUM_POSITION_TYPE type = POSITION_TYPE_BUY // +) +{ + // + double result = 0; + + // + mSymbol = NormalizeSymbol(mSymbol); + + // + result = + IsLong(type) + ? GetAsk(mSymbol) + : GetBid(mSymbol); + result = NormalizePrice(result, mSymbol); + + // + return result; +} + +/** + * Get Entry Price ... + * + * @param mSymbol: string, Provided Symbol ... + * @param type: ENUM_X_DIRECTION member, Specified Entry type ... + * + * @return ( double ) + */ +double GetEntry( + string mSymbol = NULL, + ENUM_X_DIRECTION type = X_DIRECTION_BULLISH // +) +{ + // + double result = 0; + + // + mSymbol = NormalizeSymbol(mSymbol); + + // + result = + IsBullish(type) + ? GetAsk(mSymbol) + : GetBid(mSymbol); + result = NormalizePrice(result, mSymbol); + + // + return result; +} + +/** + * Get Exit Price ... + * + * @param mSymbol: string, Provided Symbol ... + * @param type: ENUM_POSITION_TYPE member, Specified Exit type ... + * + * @return ( double ) + */ +double GetExit( + string mSymbol = NULL, + ENUM_POSITION_TYPE type = POSITION_TYPE_BUY // +) +{ + // + double result = 0; + + // + mSymbol = NormalizeSymbol(mSymbol); + + // + result = + IsLong(type) + ? GetBid(mSymbol) + : GetAsk(mSymbol); + result = NormalizePrice(result, mSymbol); + + // + return result; +} + +/** + * Get Exit Price ... + * + * @param mSymbol: string, Provided Symbol ... + * @param type: ENUM_X_DIRECTION member, Specified Exit type ... + * + * @return ( double ) + */ +double GetExit( + string mSymbol = NULL, + ENUM_X_DIRECTION type = X_DIRECTION_BULLISH // +) +{ + // + double result = 0; + + // + mSymbol = NormalizeSymbol(mSymbol); + + // + result = + IsBullish(type) + ? GetBid(mSymbol) + : GetAsk(mSymbol); + result = NormalizePrice(result, mSymbol); + + // + return result; +} + +/** + * Retrieve Current Tick ... + */ +bool GetTick( + string mSymbol, + MqlTick &tick // +) +{ + return SymbolInfoTick(mSymbol, tick); +} + +// +// END Position ... +// + +// +// START Tools ... +// + +/** + * Check Expert Running in Testing Mode or not ... + * + * @return ( bool ) + */ +bool IsRunningOnTestMode() +{ + // + bool result = false; + + // + // check programm mode ... + result = MQL5InfoInteger(MQL5_TESTING); + + // + return result; +} + +/** + * Find Chart ID ... + * + * @param mSymbol: string, Specified Symbol ... + * @param mPeriod: ENUM_TIMEFRAMES member, Specified Period ... + * + * @return ( long ) + */ +long FindChartID( + string mSymbol = NULL, + ENUM_TIMEFRAMES mPeriod = NULL // +) +{ + // + long result = ChartFirst(); + long first = result; + + // + while (result > 0) + { + // + string chSymbol = ChartSymbol(result); + ENUM_TIMEFRAMES chPeriod = ChartPeriod(result); + + // + bool isOwn = + // + chSymbol == mSymbol && + chPeriod == mPeriod + // + ; + if (isOwn) + { + break; + } + + // + result = ChartNext(result); + } + + // + return result; +} + +/** + * Retrieve Available Symbols ... + * + * @param symbols: string Collection reference to Hold Symbols ... + * @param onlyInWatchList: bool, Force Extracts only Watch List Symbols ... + * + * @return ( int ) + */ +int GetAllSymbols( + string &symbols[], // Hold Result + bool onlyInWatchList = false // Specified Retrieve only Symbols which in Watch List +) +{ + // + int result = 0; + + // + Clean(symbols); + + // + int count = SymbolsTotal(onlyInWatchList); + if (!IsValidSize(count)) + { + return result; + } + + // + for (int i = 0; i < count; i++) + { + // + string iSymbol = SymbolName( + i, + onlyInWatchList // + ); + if (!IsValid(iSymbol)) + { + continue; + } + + // + Add( + iSymbol, + symbols // + ); + } + + // + result = ArraySize(symbols); + + // + return result; +} + +/** + * Filter Symbols Collections ... + * + * @param query: string, Provided Query to Search Symbols ... + * @param symbols: string, Collection resources to Hold's Filtered results ... + * @param onlyInWatchList: bool, Specified Apply Filter only on Watch List Symbols ... + * @param ignoreCase: bool, Ignore Case Sesitive ... + * @param querySeparator: string, Provided Separator of Query ... + * + * @return ( int ) + */ +int FilterSymbols( + string query, + string &symbols[], + bool onlyInWatchList = false, + bool ignoreCase = true, + string querySeparator = "," // If Provided means query is a Collection of Queries and need to be Splitted +) +{ + // + int result = 0; + + // + Clean(symbols); + + // + if (!IsValid(query)) + { + return result; + } + + // + // Check Query is an String array or not ... + string mQueries[]; + int queriesCount = 0; + if (IsValid(querySeparator) && Contains(querySeparator, query, true)) + { + // + queriesCount = SplitContent( + mQueries, + query, + querySeparator // + ); + } + + // + string allSymbols[]; + int allSymbolsCount = GetAllSymbols( + allSymbols, + onlyInWatchList // + ); + if (allSymbolsCount <= 0) + { + return result; + } + + // + // Loop Through all Symbols ... + for (int i = 0; i < allSymbolsCount; i++) + { + // + string iSymbol = allSymbols[i]; + + // + bool isFilterPassed = false; + if (queriesCount == 0) + { + // + isFilterPassed = Contains( + query, + iSymbol, + ignoreCase // + ); + } + else if (queriesCount > 0) + { + // + isFilterPassed = Contains( + mQueries, + iSymbol, + ignoreCase // + ); + } + + // + if (isFilterPassed) + { + // + Add( + iSymbol, + symbols // + ); + } + } + + // + result = ArraySize(symbols); + + // + return result; +} + +/** + * Extract Symbols to Find Only USD Side Assets ... + * + * @param symbols: string, Collection resources to Hold's Filtered results ... + * @param onlyInWatchList: bool, Specified Apply Filter only on Watch List Symbols ... + * @param ignoreCase: bool, Ignore Case Sesitive ... + * @param querySeparator: string, Provided Separator of Query ... + * + * @return ( int ) + */ +int FilterUSDSymbols( + string &symbols[], + bool onlyInWatchList = false, + bool ignoreCase = true, + string querySeparator = "," // +) +{ + // + return FilterSymbols( + "USD", + symbols, + onlyInWatchList, + ignoreCase, + querySeparator // + ); +} + +/** + * Get Digits Length of Specified Double Value ... + * + * @param value: double, Provided Value ... + * + * @return ( int ) + */ +int GetDigits(double value) +{ + // + int d = 0; + double p = 1; + while (MathRound(value * p) / p != value) + { + p = MathPow(10, ++d); + } + + // + return d; +} + +/** + * Retrieve Specific Object Types Name ... + * + * @param t: T object reference ... + * + * @return ( string ) + * + */ +template +string GetTypeName(const T &t) +{ + return typename(T); +} + +/** + * Get Specified Types Token ... + * + * @param item: T, object reference ... + * + * @return ( string ) + */ +template +string GetToken(T &item) +{ + // + string mType = GetTypeName(item); + + // + string result = mType; + + // + string parts[]; + int partsCount = SplitContent( + parts, + result, + " " // + ); + if (partsCount <= 0) + { + // + result = mType; + return result; + } + + // + bool hasLastPart = GetLastItem( + result, + parts // + ); + if (!hasLastPart) + { + // + result = mType; + return result; + } + + // + return result; +} +template +string GetSpecificToken(T &item) +{ + return GetToken(item); +} + +/** + * Generate Unique Tags ... + * + * @param model: T, object reference ... + * + * @return ( string ) + */ +template +string GenerateTag(T &model) +{ + // + string result = ""; + + // + string tag = model.ToString(); + if (StringLen(tag) == 0) + { + return result; + } + + // + XSCMD5 *md5; + md5 = new XCMD5(); + + // + result = md5.Hash(tag); + + // + ZeroMemory(md5); + + // + return result; +} + +/** + * Hash Specified Content ... + * + * @param content: T, Proveded Content ... + * + * @return ( string ) + */ +template +string ToMD5(T content) +{ + // + string result = ""; + + // + string strContent = ToString(content); + if (StringLen(strContent) == 0) + { + return result; + } + + // + XCMD5 *md5; + md5 = new XCMD5(); + + // + result = md5.Hash(strContent); + + // + ZeroMemory(md5); + + // + return result; +} + +/** + * Calculate Fibo Level ... + * + * @param mUp: double, Specified Upper Price ... + * @param mDown: double, Specified Lower Price ... + * @param mLevel: ENUM_X_FIBO_LEVELS member, Specified Fibo Level ... + * @param mForDir: ENUM_X_DIRECTION member, Specified Calculation Direction ... + * + * @return ( double ) + */ +double GetFibonacciLevel( + double mUp, + double mDown, + ENUM_X_FIBO_LEVELS mLevel, + ENUM_X_DIRECTION mForDir // +) +{ + // + double result = 0; + + // + double levelValue = GetFiboLevelValue(mLevel); + + // + bool isValid = + // + mUp > 0 && + mDown > 0 && + levelValue > 0 && + mUp > mDown && + HasDirection(mForDir) + // + ; + if (!isValid) + { + return result; + } + + // + bool isBullish = IsBullish(mForDir); + + // + double ling = mUp - mDown; + double pLevel = (ling / 100) * (levelValue * 100); + + // + result = + isBullish + ? mUp - pLevel + : mDown + pLevel; + + // + return result; +} + +/** + * Calculate Sspecified Buffer's Moving Averages ... + * + * @param rates_total: Integer, number of items ... + * @param prev_calculated: Integer, Previous Calculate Items ... + * @param begin: Integer, Bar Index ... + * @param period: Integer, Moving Average Length ... + * @param source: Double Array, Specified Array for Calculating Moving Averages ... + * @param buffer: Double Array, Specified Array to Apply Calculated Moving Average on it ... + * @param method: ENUM_MA_METHOD member Specified Moving Average Calculation Method ... + * + * @return ( int ) + */ +int iMAOnBuffer( + const int _rates_total, + const int _prev_calculated, + const int _begin, + const int _period, + const double &_source[], + double &_buffer[], + ENUM_X_MA_METHOD _method = X_MA_MODE_SMA // +) +{ + // + int result = 0; + + // + if ( + _period < 0 || + _rates_total <= 0 || + _prev_calculated < 0 || + _method == X_MA_MODE_NONE || + _prev_calculated > _rates_total) + { + return result; + } + + // + switch (_method) + { + // + case X_MA_MODE_SMA: + result = SimpleMAOnBuffer( + _rates_total, + _prev_calculated, + _begin, + _period, + _source, + _buffer // + ); + break; + + // + case X_MA_MODE_EMA: + result = ExponentialMAOnBuffer( + _rates_total, + _prev_calculated, + _begin, + _period, + _source, + _buffer // + ); + break; + + // + case X_MA_MODE_LWMA: + result = LinearWeightedMAOnBuffer( + _rates_total, + _prev_calculated, + _begin, + _period, + _source, + _buffer // + ); + break; + + // + case X_MA_MODE_SMMA: + result = SmoothedMAOnBuffer( + _rates_total, + _prev_calculated, + _begin, + _period, + _source, + _buffer // + ); + break; + } + + // + return result; +} + +// +// END Tools ... +// + +// +// START String ... +// + +/** + * Search a Content Contains Specific String or not ... + * + * @param mQuery: string, Search Query ... + * @param mContent: string, Search Content ... + * @param ignoreCase: bool, Force Ignore Case Sensitive ... + * + * @return ( bool ) + */ +bool Contains( + string mQuery, + string mContent, + bool ignoreCase = true // +) +{ + // + bool result = false; + + // + // Validate Query ... + result = IsValid(mQuery); + if (!result) + { + return result; + } + + // + // Validate Content ... + result = IsValid(mContent); + if (!result) + { + return result; + } + + // + // Normalize Inputs ... + string query = mQuery; + string content = mContent; + if (ignoreCase) + { + // + StringToLower(query); + StringToLower(content); + } + + // + int queryIdx = StringFind( + content, + query); + + // + result = queryIdx >= 0; + + // + return result; +} + +/** + * Search a Content Contains Specifics Query or not ... + * + * @param mQueries: string collection, Search Queries ... + * @param mContent: string, Search Content ... + * @param ignoreCase: bool, Force Ignore Case Sensitive ... + * + * @return ( bool ) + */ +bool Contains( + string &mQueries[], + string mContent, + bool ignoreCase = true // +) +{ + // + bool result = false; + + // + // Validate Queries ... + int queriesCount = ArraySize(mQueries); + result = queriesCount > 0; + if (!result) + { + return result; + } + + // + // Validate Content ... + result = IsValid(mContent); + if (!result) + { + return result; + } + + // + int containsCount = 0; + for (int i = 0; i < queriesCount; i++) + { + // + bool isContains = Contains( + mQueries[i], + mContent, + ignoreCase); + + // + if (!isContains) + { + // + result = false; + break; + } + + // + containsCount++; + } + + // + result = containsCount == queriesCount; + + // + return result; +} + +/** + * Search a Content and Extract Occuranse Indexes ... + * + * @param mQuery: string, Search Query ... + * @param mContent: string, Search Content ... + * @param result: int collection reference, Holds Founded Indexes ... + * @param ignoreCase: bool, Force Ignore Case Sensitive ... + * + * @return ( int ) + */ +int FindIndexes( + string mQuery, + string mContent, + int &result[], + bool ignoreCase = false // +) +{ + // + int mResult = 0; + + // + Clean(result); + + // + // Validate Inputs ... + if (!IsValid(mQuery) || + !IsValid(mContent)) + { + return mResult; + } + + // + // Apply Ignore Case if Provided ... + if (ignoreCase) + { + // + bool isConverted = StringToLower(mQuery); + if (!isConverted) + { + return mResult; + } + + // + isConverted = StringToLower(mContent); + if (!isConverted) + { + return mResult; + } + } + + // + // Search First Index ... + int lastPos = 0; + int idx = StringFind( + mContent, + mQuery, + lastPos // + ); + while (idx >= 0) + { + // + // Add Position to Result ... + Add( + idx, + result // + ); + + // + lastPos = idx + StringLen(mQuery); + idx = StringFind( + mContent, + mQuery, + lastPos // + ); + } + + // + mResult = ArraySize(result); + + // + return mResult; +} + +/** + * Convert From String ... + * + * @param value: string, Provided Value ... + * + * @return ( T ) + */ +template +T FromString(string value) +{ + // + T result = NULL; + + // + if (!IsValid(value)) + { + return result; + } + + // + result = (T)value; + + // + return result; +} + +/** + * Converts to String ... + * + * @param value: T, Provided Value ... + * + * @return ( string ) + */ +template +string ToString(T value) +{ + return (string)value; +} + +// +// Used In Report or Summary Generators ... +string ToString( + string prefix, // Title + bool value, // Value + bool ignoreFalseConditions = true, // Ignore False Conditions + string lineSeparator = "\n", // Line Separator + string prefixSeparator = ":" // Title Separator +) +{ + // + string result = NULL; + + // + result = (value || !ignoreFalseConditions) + ? prefix + + prefixSeparator + " " + + ToString(value) + + lineSeparator + : ""; + + // + return result; +} + +// +template +string ToString( + string prefix, // Title + T value, // Value + string lineSeparator = "\n", // Line Separator + string prefixSeparator = ":" // Title Separator +) +{ + // + string result = NULL; + + // + result = prefix + + prefixSeparator + " " + + ToString(value) + + lineSeparator; + + // + return result; +} + +// +string SetLabel( + string mLabel, // Provided Label ... + string value, // Source Value ... + string separator = "\n", // Line Separator + bool addTopEmptyLine = true // Add Empty Line On top +) +{ + // + string result = value; + + // + if (StringLen(mLabel) <= 0) + { + return result; + } + + // + result = (StringLen(value) > 0) + ? (addTopEmptyLine ? separator : "") + + mLabel + + separator + + "-----------------------------" + + separator + + value + : value; + + // + return result; +} + +// +// Converts a Buffer to String Representation ... +template +string ToString( + const T &buffer[], // Specified Buffer + string separator = ",", // Specified Separator + bool addIndex = false, // Specified Add Items Indexes or Not + string indexLabel = "i:", // Specified Index Label + string indexSeparator = ">" // Specified Index Separator +) +{ + // + string result = ""; + + // + int bufferSize = ArraySize(buffer); + if (bufferSize <= 0) + { + return result; + } + + // + for (int i = 0; i < bufferSize; i++) + { + // + if (addIndex) + { + // + if (StringLen(indexLabel) > 0) + { + result += indexLabel + " "; + } + + // + result += (string)i + " "; + + // + if (StringLen(indexSeparator) > 0) + { + result += indexSeparator + " "; + } + } + + // + string iItemString = (string)buffer[i]; + + // + result += iItemString; + + // + if (i < bufferSize - 1) + { + result += separator; + } + } + + // + return result; +} + +/** + * Converts String to boolean ... + * + * @param value: string, Provided Value ... + * + * @return ( bool ) + */ +bool ToBoolean(string value) +{ + // + bool result = false; + + // + if (StringLen(value) <= 0) + { + return result; + } + + // + StringToLower(value); + result = value == "true"; + + // + return result; +} + +// +// Split an String Representation of an Array ... +int SplitContent( + string &result[], // Hold Result ... + string content, // Source ... + string separator = ",", // Separator ... + bool forceCleanResult = true // Clean Result ... +) +{ + // + int mResult = 0; + + // + if (forceCleanResult) + { + Clean(result); + } + + // + int before = ArraySize(result); + + // + if (separator == NULL || StringLen(separator) == 0) + { + separator = ","; + } + + // + if (StringLen(content) == 0) + { + return mResult; + } + + // + StringSplit( + content, + StringGetCharacter( + separator, + 0), + result); + + // + int after = ArraySize(result); + + // + mResult = after - before; + + // + return mResult; +} + +// +// Extract Data from String ... +string ExtractString( + const string source, // Source String used for Extracting + const string startString = "(", // Expression Start String must be Unique + const string endString = ")" // Where to End Extraction, usually a Sign +) +{ + // + string result = ""; + + // + // Validate String ... + if ( + StringLen(source) == 0 || + StringLen(endString) == 0 || + StringLen(startString) == 0) + { + return result; + } + + // + // Find Start String Position ... + int sPos = StringFind( + source, + startString); + if (sPos < 0) + { + return result; + } + + // + // Find End String Position after Start String ... + int searchEndFromPos = sPos + StringLen(startString); + int ePos = StringFind( + source, + endString, + searchEndFromPos); + if (ePos < 0) + { + return result; + } + + // + // Extract Data from Source ... + int dLength = ePos - searchEndFromPos; + result = StringSubstr( + source, + searchEndFromPos, + dLength); + + // + return result; +} + +// +// Extract an Array of Contents ... +int ExtractStrings( + string &result[], // Hold Result + const string source, // Source String used for Extracting + const string startString = "(", // Expression Start String must be Unique + const string endString = ")" // Where to End Extraction, usually a Sign +) +{ + // + int mResult = 0; + + // + Clean(result); + + // + // Validate Args ... + int sourceLength = StringLen(source); + int startLength = StringLen(startString); + int endLength = StringLen(endString); + + // + int minRequiredLength = startLength + endLength; + + // + if ( + endLength <= 0 || + startLength <= 0 || + sourceLength <= 0 || + sourceLength < minRequiredLength) + { + return mResult; + } + + // + // Make a Copy of Source for Manipulating ... + string workStr = source; + + // + // Define a Loop ... + while (StringLen(workStr) > minRequiredLength) + { + // + // Find Item ... + string item = ExtractString( + workStr, + startString, + endString); + + // + // Breakout when couldn't find anymore item ... + int itemLength = StringLen(item); + if (itemLength <= 0) + { + break; + } + + // + // Prepare Item Source String for Replacing in Work String ... + string itemSource = startString + item + endString; + + // + // Add Item to Result Array ... + Add( + item, + result); + + // + // Replace Item Soure in Work String ... + StringReplace( + workStr, + itemSource, + ""); + } + + // + // Calculate Size of Array ... + mResult = ArraySize(result); + + // + return mResult; +} + +// +string ExtractSurrounded( + const string surrounded, // Surrounded Content + const string mToken, // Specified Token + const string startString = "(", // Expression Start String must be Unique + const string endString = ")" // Where to End Extraction, usually a Sign +) +{ + // + return ExtractString( + surrounded, + mToken + startString, + endString + // + ); +} + +// +int ParseIntSurrounded( + const string surrounded, // Surrounded Content + const string mToken, // Specified Token + const string startString = "(", // Expression Start String must be Unique + const string endString = ")" // Where to End Extraction, usually a Sign +) +{ + // + int result = NULL; + + // + string strContent = ExtractSurrounded( + surrounded, + mToken, + startString, + endString + // + ); + if (!IsValid(strContent)) + { + return result; + } + + // + result = (int)strContent; + + // + return result; +} + +long ParseLongSurrounded( + const string surrounded, // Surrounded Content + const string mToken, // Specified Token + const string startString = "(", // Expression Start String must be Unique + const string endString = ")" // Where to End Extraction, usually a Sign +) +{ + // + long result = NULL; + + // + string strContent = ExtractSurrounded( + surrounded, + mToken, + startString, + endString + // + ); + if (!IsValid(strContent)) + { + return result; + } + + // + result = (long)strContent; + + // + return result; +} + +string ParseStringSurrounded( + const string surrounded, // Surrounded Content + const string mToken, // Specified Token + const string startString = "(", // Expression Start String must be Unique + const string endString = ")" // Where to End Extraction, usually a Sign +) +{ + // + string result = NULL; + + // + string strContent = ExtractSurrounded( + surrounded, + mToken, + startString, + endString + // + ); + if (!IsValid(strContent)) + { + return result; + } + + // + result = (string)strContent; + + // + return result; +} + +double ParseDoubleSurrounded( + const string surrounded, // Surrounded Content + const string mToken, // Specified Token + const string startString = "(", // Expression Start String must be Unique + const string endString = ")" // Where to End Extraction, usually a Sign +) +{ + // + double result = NULL; + + // + string strContent = ExtractSurrounded( + surrounded, + mToken, + startString, + endString + // + ); + if (!IsValid(strContent)) + { + return result; + } + + // + result = (double)strContent; + + // + return result; +} + +datetime ParseTimeSurrounded( + const string surrounded, // Surrounded Content + const string mToken, // Specified Token + const string startString = "(", // Expression Start String must be Unique + const string endString = ")" // Where to End Extraction, usually a Sign +) +{ + // + datetime result = NULL; + + // + string strContent = ExtractSurrounded( + surrounded, + mToken, + startString, + endString + // + ); + if (!IsValid(strContent)) + { + return result; + } + + // + result = (datetime)strContent; + + // + return result; +} + +// +int ParseIntArraySurrounded( + int &result[], // Holds Result + const string surrounded, // Surrounded Content + const string mToken, // Specified Token + string separator = ",", // Separator ... + const string startString = "(", // Expression Start String must be Unique + const string endString = ")", // Where to End Extraction, usually a Sign + bool forceClean = true // Clean Result ... +) +{ + // + int count = 0; + + // + if (forceClean) + { + Clean(result); + } + + // + int before = ArraySize(result); + + // + string contentStr = ParseStringSurrounded(surrounded, mToken); + if (!IsValid(contentStr)) + { + return count; + } + + // + string tmps[]; + int tmpsCount = SplitContent( + tmps, + contentStr + // + ); + if (tmpsCount <= 0) + { + return count; + } + + // + for (int i = 0; i < tmpsCount; i++) + { + // + string iTMP = tmps[i]; + if (!IsValid(iTMP)) + { + continue; + } + + // + int iValue = (int)iTMP; + + // + Add( + iValue, + result + // + ); + } + + // + int after = ArraySize(result); + + // + count = after - before; + + // + return count; +} + +int ParseLongArraySurrounded( + long &result[], // Holds Result + const string surrounded, // Surrounded Content + const string mToken, // Specified Token + string separator = ",", // Separator ... + const string startString = "(", // Expression Start String must be Unique + const string endString = ")", // Where to End Extraction, usually a Sign + bool forceClean = true // Clean Result ... +) +{ + // + int count = 0; + + // + if (forceClean) + { + Clean(result); + } + + // + int before = ArraySize(result); + + // + string contentStr = ParseStringSurrounded(surrounded, mToken); + if (!IsValid(contentStr)) + { + return count; + } + + // + string tmps[]; + int tmpsCount = SplitContent( + tmps, + contentStr + // + ); + if (tmpsCount <= 0) + { + return count; + } + + // + for (int i = 0; i < tmpsCount; i++) + { + // + string iTMP = tmps[i]; + if (!IsValid(iTMP)) + { + continue; + } + + // + long iValue = (long)iTMP; + + // + Add( + iValue, + result + // + ); + } + + // + int after = ArraySize(result); + + // + count = after - before; + + // + return count; +} + +int ParseDoubleArraySurrounded( + double &result[], // Holds Result + const string surrounded, // Surrounded Content + const string mToken, // Specified Token + string separator = ",", // Separator ... + const string startString = "(", // Expression Start String must be Unique + const string endString = ")", // Where to End Extraction, usually a Sign + bool forceClean = true // Clean Result ... +) +{ + // + int count = 0; + + // + if (forceClean) + { + Clean(result); + } + + // + int before = ArraySize(result); + + // + string contentStr = ParseStringSurrounded(surrounded, mToken); + if (!IsValid(contentStr)) + { + return count; + } + + // + string tmps[]; + int tmpsCount = SplitContent( + tmps, + contentStr + // + ); + if (tmpsCount <= 0) + { + return count; + } + + // + for (int i = 0; i < tmpsCount; i++) + { + // + string iTMP = tmps[i]; + if (!IsValid(iTMP)) + { + continue; + } + + // + double iValue = (double)iTMP; + + // + Add( + iValue, + result + // + ); + } + + // + int after = ArraySize(result); + + // + count = after - before; + + // + return count; +} + +int ParseTimeArraySurrounded( + datetime &result[], // Holds Result + const string surrounded, // Surrounded Content + const string mToken, // Specified Token + string separator = ",", // Separator ... + const string startString = "(", // Expression Start String must be Unique + const string endString = ")", // Where to End Extraction, usually a Sign + bool forceClean = true // Clean Result ... +) +{ + // + int count = 0; + + // + if (forceClean) + { + Clean(result); + } + + // + int before = ArraySize(result); + + // + string contentStr = ParseStringSurrounded(surrounded, mToken); + if (!IsValid(contentStr)) + { + return count; + } + + // + string tmps[]; + int tmpsCount = SplitContent( + tmps, + contentStr + // + ); + if (tmpsCount <= 0) + { + return count; + } + + // + for (int i = 0; i < tmpsCount; i++) + { + // + string iTMP = tmps[i]; + if (!IsValid(iTMP)) + { + continue; + } + + // + datetime iValue = (datetime)iTMP; + + // + Add( + iValue, + result + // + ); + } + + // + int after = ArraySize(result); + + // + count = after - before; + + // + return count; +} + +// +// Surround an String by Specific Token ... +template +string Surround( + string mToken, // an String which used to Tokenize + T &value, // a Value for Tokenize it + string startString = "(", // Token Start Content + string endString = ")" // Token End Content +) +{ + // + string result = NULL; + + // + string strValue = ToString(value); + if (!IsValid(strValue)) + { + return result; + } + + // + result = + // + (IsValid(mToken) + ? mToken + : "") + + // + startString + + strValue + + endString + // + ; + + // + return result; +} + +// +template +string SurroundArray( + string mToken, + T &value[], + string startString = "(", // Token Start Content + string endString = ")" // Token End Content +) +{ + // + string result = NULL; + + // + string valueStr = ToString(value); + if (!IsValid(valueStr)) + { + return result; + } + + // + result = Surround( + mToken, + valueStr, + startString, + endString + // + ); + + // + return result; +} + +// +// END String ... +// + +// +// START Cycles ... +// + +/** + * Converts String To Period ... + * + * @param value: string ... + * + * @return ( ENUM_TIMEFRAMES ) + */ +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 To String ... + * + * @param value: ENUM_TIMEFRAMES member ... + * + * @return ( string ) + */ +string ToString(ENUM_TIMEFRAMES value) +{ + // + string result = ""; + + // + string mPStr = EnumToString(value); + + string mPStrParts[]; + int partsCount = StringSplit( + mPStr, + StringGetCharacter("_", 0), + mPStrParts); + if (partsCount <= 0) + { + return result; + } + + // + result = mPStrParts[1]; + + // + return result; +} + +// +// Retrieve All Available Period as an Array ...s +int GetAllAvailablePeriods( + ENUM_TIMEFRAMES &result[] // Holds Result ... +) +{ + // + Clean(result); + + // + Add( + PERIOD_M1, + result + // + ); + + // + Add( + PERIOD_M2, + result + // + ); + + // + Add( + PERIOD_M3, + result + // + ); + + // + Add( + PERIOD_M4, + result + // + ); + + // + Add( + PERIOD_M5, + result + // + ); + + // + Add( + PERIOD_M6, + result + // + ); + + // + Add( + PERIOD_M10, + result + // + ); + + // + Add( + PERIOD_M12, + result + // + ); + + // + Add( + PERIOD_M15, + result + // + ); + + // + Add( + PERIOD_M20, + result + // + ); + + // + Add( + PERIOD_M30, + result + // + ); + + // + Add( + PERIOD_H1, + result + // + ); + + // + Add( + PERIOD_H2, + result + // + ); + + // + Add( + PERIOD_H3, + result + // + ); + + // + Add( + PERIOD_H4, + result + // + ); + + // + Add( + PERIOD_H6, + result + // + ); + + // + Add( + PERIOD_H8, + result + // + ); + + // + Add( + PERIOD_H12, + result + // + ); + + // + Add( + PERIOD_D1, + result + // + ); + + // + Add( + PERIOD_W1, + result + // + ); + + // + Add( + PERIOD_MN1, + result + // + ); + + // + int mResult = ArraySize(result); + + // + return mResult; +} + +// +// Get Specific Time Frame Start Candle Time ... +datetime GetPeriodStartTime( + string mSymbol = NULL, // Specified Symbol ... + ENUM_TIMEFRAMES mPeriod = NULL, // Specified Period ... + datetime mTime = NULL // Specified Bar Time of Host Period ... +) +{ + // + // Normalize Arg ... + mTime = NormalizeTime(mTime); + mSymbol = NormalizeSymbol(mSymbol); + mPeriod = NormalizePeriod(mPeriod); + + // + int barIndex = iBarShift( + mSymbol, + mPeriod, + mTime, + false // + ); + + // + datetime result = GetBarTime( + mSymbol, + mPeriod, + barIndex // + ); + + // + return result; +} + +// +// Retrieve Nearest Period base on Given Period ... +ENUM_TIMEFRAMES GetNearestPeriod(ENUM_TIMEFRAMES mPeriod) +{ + // + ENUM_TIMEFRAMES result = _Period; + + // + mPeriod = NormalizePeriod(mPeriod); + + // + switch (mPeriod) + { + // + case PERIOD_M1: + case PERIOD_M2: + case PERIOD_M3: + result = PERIOD_M5; + break; + + // + case PERIOD_M4: + case PERIOD_M5: + case PERIOD_M6: + result = PERIOD_M10; + break; + + // + case PERIOD_M10: + case PERIOD_M12: + case PERIOD_M15: + result = PERIOD_M20; + break; + + // + case PERIOD_M20: + case PERIOD_M30: + result = PERIOD_H1; + break; + + // + case PERIOD_H1: + case PERIOD_H2: + result = PERIOD_H3; + break; + + // + case PERIOD_H3: + result = PERIOD_H4; + break; + + // + case PERIOD_H4: + result = PERIOD_H6; + break; + + // + case PERIOD_H6: + result = PERIOD_H8; + break; + + // + case PERIOD_H8: + result = PERIOD_H12; + break; + + // + default: + result = mPeriod; + break; + } + + // + return result; +} + +// +// Retrieve Mediest Period base on Given Period ... +ENUM_TIMEFRAMES GetMediestPeriod(ENUM_TIMEFRAMES mPeriod) +{ + // + ENUM_TIMEFRAMES result = _Period; + + // + mPeriod = NormalizePeriod(mPeriod); + + // + switch (mPeriod) + { + // + case PERIOD_M1: + case PERIOD_M2: + case PERIOD_M3: + result = PERIOD_M10; + break; + + // + case PERIOD_M4: + case PERIOD_M5: + case PERIOD_M6: + result = PERIOD_M15; + break; + + // + case PERIOD_M10: + case PERIOD_M12: + case PERIOD_M15: + result = PERIOD_M30; + break; + + // + case PERIOD_M20: + case PERIOD_M30: + result = PERIOD_H2; + break; + + // + case PERIOD_H1: + case PERIOD_H2: + result = PERIOD_H4; + break; + + // + case PERIOD_H3: + result = PERIOD_H6; + break; + + // + case PERIOD_H4: + result = PERIOD_H8; + break; + + // + case PERIOD_H6: + result = PERIOD_H12; + break; + + // + case PERIOD_H8: + result = PERIOD_D1; + break; + + // + default: + result = mPeriod; + break; + } + + // + return result; +} + +// +// Retrieve Longest Period base on Given Period ... +ENUM_TIMEFRAMES GetLongestPeriod(ENUM_TIMEFRAMES mPeriod) +{ + // + ENUM_TIMEFRAMES result = _Period; + + // + mPeriod = NormalizePeriod(mPeriod); + + // + switch (mPeriod) + { + // + case PERIOD_M1: + case PERIOD_M2: + case PERIOD_M3: + result = PERIOD_M30; + break; + + // + case PERIOD_M4: + case PERIOD_M5: + case PERIOD_M6: + result = PERIOD_H1; + break; + + // + case PERIOD_M10: + case PERIOD_M12: + case PERIOD_M15: + result = PERIOD_H2; + break; + + // + case PERIOD_M20: + case PERIOD_M30: + result = PERIOD_H4; + break; + + // + case PERIOD_H1: + case PERIOD_H2: + result = PERIOD_H6; + break; + + // + case PERIOD_H3: + result = PERIOD_H8; + break; + + // + case PERIOD_H4: + result = PERIOD_H12; + break; + + // + case PERIOD_H6: + result = PERIOD_D1; + break; + + // + case PERIOD_H8: + result = PERIOD_W1; + break; + + // + default: + result = mPeriod; + break; + } + + // + return result; +} + +// +// Retrieve Hindmost Period base on Given Period ... +ENUM_TIMEFRAMES GetHindMostPeriod(ENUM_TIMEFRAMES mPeriod) +{ + // + ENUM_TIMEFRAMES result = _Period; + + // + mPeriod = NormalizePeriod(mPeriod); + + // + switch (mPeriod) + { + // + case PERIOD_M1: + case PERIOD_M2: + case PERIOD_M3: + result = PERIOD_H1; + break; + + // + case PERIOD_M4: + case PERIOD_M5: + case PERIOD_M6: + result = PERIOD_H2; + break; + + // + case PERIOD_M10: + case PERIOD_M12: + case PERIOD_M15: + result = PERIOD_H4; + break; + + // + case PERIOD_M20: + case PERIOD_M30: + result = PERIOD_H6; + break; + + // + case PERIOD_H1: + case PERIOD_H2: + result = PERIOD_H8; + break; + + // + case PERIOD_H3: + result = PERIOD_H12; + break; + + // + case PERIOD_H4: + result = PERIOD_D1; + break; + + // + case PERIOD_H6: + result = PERIOD_W1; + break; + + // + case PERIOD_H8: + result = PERIOD_MN1; + break; + + // + default: + result = mPeriod; + break; + } + + // + return result; +} + +// +// Retrieve Specified Cycles Period related to Host Period ... +ENUM_TIMEFRAMES GetCyclePeriod( + ENUM_X_MARKET_CYCLES mCycle = NULL, // Specified Cycle + ENUM_TIMEFRAMES mPeriod = NULL // Host Period +) +{ + // + ENUM_TIMEFRAMES result = NULL; + + // + mPeriod = NormalizePeriod(mPeriod); + mCycle = NormalizeCycle(mCycle); + + // + switch (mCycle) + { + // + // Short ... + case X_MARKET_CYCLE_SHORT: + result = GetNearestPeriod(mPeriod); + break; + + // + // Medium ... + case X_MARKET_CYCLE_MEDIUM: + result = GetMediestPeriod(mPeriod); + break; + + // + // Long ... + case X_MARKET_CYCLE_LONG: + result = GetLongestPeriod(mPeriod); + break; + + // + // Hind ... + case X_MARKET_CYCLE_HIND: + result = GetHindMostPeriod(mPeriod); + break; + } + + // + return result; +} + +// +// Calculate a Cycle Length based on Host Period ... +int GetCycleLengthOn( + ENUM_TIMEFRAMES _hostPeriod, + ENUM_X_MARKET_CYCLES _cycle, + ENUM_X_PERIOD_METHOD _method, + ENUM_TIMEFRAMES _period // +) +{ + // + int result = 0; + + // + // Validate ... + bool isValid = + // + IsValid(_hostPeriod) && + IsValid(_method, _Period) + // + ; + if (!isValid) + { + return result; + } + + // + // Calculate Period ... + isValid = + _method != X_PERIOD_NONE && + _cycle != X_MARKET_CYCLE_UNKNOWN; + if (!isValid) + { + return result; + } + + // + if (_method == X_PERIOD_AUTO) + { + // + _period = GetCyclePeriod( + _cycle, + _hostPeriod // + ); + } + isValid = IsValid(_period); + if (!isValid) + { + return result; + } + + // + int _hostPeriodSeconds = PeriodSeconds(_hostPeriod); + int _periodSeconds = PeriodSeconds(_period); + + // + isValid = _periodSeconds >= _hostPeriodSeconds; + if (!isValid) + { + return result; + } + + // + result = _periodSeconds / _hostPeriodSeconds; + + // + return result; +} + +/** + * Retrieve Sharp Change Info for Specified Period ... + * + * @param priceChange: double, required Price Change ... + * @param mPeriod: ENUM_TIMEFRAMES member, Specified Period ... + * + * @return ( int ) + */ +int GetPeriodSharpData( + double &priceChange, + ENUM_TIMEFRAMES mPeriod = NULL // +) +{ + // + int result = 0; + + // + priceChange = 0.0; + + // + mPeriod = NormalizePeriod(mPeriod); + + // + switch (mPeriod) + { + // + case PERIOD_M1: + // + priceChange = 0.000006; + result = 14; + break; + + // + case PERIOD_M2: + // + priceChange = 0.000006; + result = 14; + break; + + // + case PERIOD_M3: + // + priceChange = 0.00007; + result = 14; + break; + + // + case PERIOD_M4: + // + priceChange = 0.000007; + result = 14; + break; + + // + case PERIOD_M5: + // + priceChange = 0.000009; + result = 14; + break; + + // + case PERIOD_M6: + // + priceChange = 0.000009; + result = 14; + break; + + // + case PERIOD_M10: + // + priceChange = 0.00001; + result = 12; + break; + + // + case PERIOD_M12: + // + priceChange = 0.000011; + result = 11; + break; + + // + case PERIOD_M15: + // + priceChange = 0.000011; + result = 9; + break; + + // + case PERIOD_M20: + // + priceChange = 0.000012; + result = 9; + break; + + // + case PERIOD_M30: + // + priceChange = 0.000012; + result = 7; + break; + + // + case PERIOD_H1: + // + priceChange = 0.000013; + result = 5; + break; + + // + case PERIOD_H2: + // + priceChange = 0.000013; + result = 5; + break; + + // + case PERIOD_H3: + // + priceChange = 0.000014; + result = 5; + break; + + // + case PERIOD_H4: + // + priceChange = 0.000014; + result = 5; + break; + + // + case PERIOD_H6: + // + priceChange = 0.000015; + result = 5; + break; + + // + case PERIOD_H8: + // + priceChange = 0.000017; + result = 5; + break; + + // + case PERIOD_H12: + // + priceChange = 0.000017; + result = 5; + break; + + // + case PERIOD_D1: + // + priceChange = 0.000019; + result = 3; + break; + + // + case PERIOD_W1: + // + priceChange = 0.00002; + result = 3; + break; + + // + case PERIOD_MN1: + // + priceChange = 0.000021; + result = 3; + break; + } + + // + return result; +} + +// +// END Cycles ... +// + +// +// START Collections ... +// + +// +// Add Specified Item to Array ... +template +int Add( + T item, // item want to add + T &buffer[] // Destination buffer +) +{ + // + int result = 0; + + // + ArrayResize( + buffer, + ArraySize(buffer) + 1); + + // + buffer[ArraySize(buffer) - 1] = item; + + // + result = ArraySize(buffer); + + // + return result; +} +template +int AddSpecific( + T item, // item want to add + T &buffer[] // Destination buffer +) +{ + // + return Add( + item, + buffer // + ); +} +template +int AddRef( + T &item, // item want to add + T &buffer[] // Destination buffer +) +{ + // + int result = 0; + + // + ArrayResize( + buffer, + ArraySize(buffer) + 1); + + // + buffer[ArraySize(buffer) - 1] = item; + + // + result = ArraySize(buffer); + + // + return result; +} + +// +// Check Specified Array Has Childs or not ... +template +bool HasChild(T &buffer[]) +{ + return IsValidSize(ArraySize(buffer)); +} +template +bool SpecificHasChild(T &buffer[]) +{ + return HasChild(buffer); +} + +// +// Remove Specified Item from an Array ... +template +bool Remove( + T item, + T &buffer[]) +{ + // + bool result = false; + + // + int itemIndex = FindIndex( + item, + buffer); + if (itemIndex < 0) + { + return result; + } + + // + result = ArrayRemove( + buffer, + itemIndex, + 1); + + // + return result; +} + +// +// Clean Specified Array ... +template +void Clean(T &buffer[]) +{ + // + ArrayResize(buffer, 0); + ArrayFree(buffer); + ZeroMemory(buffer); +} +template +void SpecificClean(T &buffer[]) +{ + Clean(buffer); +} + +// +// Copy Whole Content of Source to Dest array ... +template +void Copy( + T &source[], // Source Buffer ... + T &dest[], // Dest Buffer ... + bool cleanDest = true // Force Clen Dest Buffer ... +) +{ + // + if (cleanDest) + { + Clean(dest); + } + + // + int sourceCount = ArraySize(source); + if (sourceCount <= 0) + { + return; + } + + // + for (int i = 0; i < sourceCount; i++) + { + // + T iSource = source[i]; + + // + AddRef( + iSource, + dest); + } +} + +// +// Copy Items from a Buffer ... +template +int Copy( + int start, // Start + int count, // Number of Items for read + T &source[], // Source Buffer + T &dest[], // Dest Buffer + bool forceClean = true, // Force To Clean buffer + bool forceStart = true // Force To Clean buffer +) +{ + // + int result = 0; + + // + if (forceClean) + { + Clean(dest); + } + + // + if (start < 0 && forceStart) + { + start = 0; + } + + // + if (start >= ArraySize(source)) + { + start = ArraySize(source) - 1; + } + + // + if (count == 0) + { + count = ArraySize(source) - 1 - start; + } + + // + if (start + count > ArraySize(source)) + { + return result; + } + + // + int beforeSize = ArraySize(dest); + + // + bool asSeriesDest = ArrayGetAsSeries(dest); + bool asSeriesSource = ArrayGetAsSeries(source); + + // + ArraySetAsSeries(dest, true); + ArraySetAsSeries(source, true); + + // + ArrayCopy( + dest, + source, + 0, + start, + count + // + ); + + // + int afterSize = ArraySize(dest); + + // + result = afterSize - beforeSize; + + // + ArraySetAsSeries(dest, asSeriesDest); + ArraySetAsSeries(source, asSeriesSource); + + // + return result; +} + +// +// Copy Items from a Buffer ... +template +int CopyRef( + int start, // Start + int count, // Number of Items for read + T &source[], // Source Buffer + T &dest[], // Dest Buffer + bool forceClean = true // Force To Clean buffer +) +{ + // + int result = 0; + + // + if (forceClean) + { + Clean(dest); + } + + // + if (start < 0) + { + start = 0; + } + + // + if (start >= ArraySize(source)) + { + start = ArraySize(source) - 1; + } + + // + int beforeSize = ArraySize(dest); + + // + bool asSeriesDest = ArrayGetAsSeries(dest); + bool asSeriesSource = ArrayGetAsSeries(source); + + // + ArraySetAsSeries(dest, true); + ArraySetAsSeries(source, true); + + // + for (int i = start; i < start + count; i++) + { + // + AddRef( + source[i], + dest + // + ); + } + + // + int afterSize = ArraySize(dest); + + // + result = afterSize - beforeSize; + + // + ArraySetAsSeries(dest, asSeriesDest); + ArraySetAsSeries(source, asSeriesSource); + + // + return result; +} + +// +// Retrive Last Item of Specified Buffer ... +template +bool GetLastItem( + T &item, // Holds Result + T &buffer[] // Specified Buffer +) +{ + // + bool result = false; + + // + int bufferSize = ArraySize(buffer); + if (bufferSize <= 0) + { + return result; + } + + // + item = buffer[bufferSize - 1]; + + // + result = true; + return result; +} + +// +// Remove Last Item of Specified Buffer ... +template +bool RemoveLastItem( + T &buffer[] // Specified Buffer +) +{ + // + bool result = false; + + // + int count = ArraySize(buffer); + result = IsValidSize(count); + if (!result) + { + return result; + } + + // + ArrayRemove( + buffer, + count - 1, + 1 // + ); + + // + return result; +} + +template +void CleanupArray( + T &buffer[], // Buffer to Cleanup ... + int maxAllowed = 0 // Max Allowed Number of items ... +) +{ + // + if (maxAllowed <= 0) + { + return; + } + + // + int count = ArraySize(buffer); + if (!IsValidSize(count) || + count <= maxAllowed) + { + return; + } + + // + int mustRemove = count - maxAllowed; + if (!IsValidSize(mustRemove)) + { + return; + } + + // + ArrayRemove( + buffer, + 0, + mustRemove // + ); +} + +template +void CleanupArray( + int &removedIndexes[], + T &buffer[] // Buffer to Cleanup ... +) +{ + // + bool isValid = HasChild(buffer) && + HasChild(removedIndexes); + if (!isValid) + { + return; + } + + // + for (int i = 0; i < ArraySize(removedIndexes); i++) + { + // + int idx = removedIndexes[i]; + if (IsValidIndex(idx) && ArraySize(buffer) > idx) + { + // + ArrayRemove( + buffer, + idx, + 1 // + ); + } + } + + // + Clean(removedIndexes); +} + +// +// 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; +} +// +// Find Specific Item Index inside a Collection ... +template +int FindIndex( + T &item, // Item to Find + const T &items[] // Items for Search +) +{ + // + int result = -1; + + // + // Check Item Validation ... + if (!item.IsValid()) + { + return result; + } + + // + int itemsCount = ArraySize(items); + if (itemsCount <= 0) + { + return result; + } + + // + for (int i = 0; i < itemsCount; i++) + { + // + T iItem = items[i]; + + // + // Validate Item ... + if (!iItem.IsValid()) + { + continue; + } + + // + bool isSame = item.IsSameAs(iItem); + if (isSame && result <= -1) + { + // + result = i; + break; + } + } + + // + return result; +} + +// +// Check an Array Contains Specified Value ... +template +bool Contains( + T item, // What is Search ... + T &buffer[] // Search in ... +) +{ + // + bool result = false; + + // + int idx = FindIndex( + item, + buffer); + result = idx > -1; + + // + return result; +} + +// +// Calculate a Buffer's Sum ... +template +double GetSum( + T &buffer[], // the Buffer which required to search + int start = 0, // Start Index + int count = 0 // Count for Search +) +{ + // + double result = 0; + + // + T tmp[]; + int tmpCount = Copy( + start, + count, + buffer, + tmp + // + ); + if (tmpCount <= 0) + { + return result; + } + + // + // Calculate Summary ... + for (int i = 0; i < tmpCount; i++) + { + result += buffer[i]; + } + + // + return result; +} + +// +// Calculate a Buffer's Average ... +template +double GetAverage( + T &buffer[], // the Buffer which required to search + int start = 0, // Start Index + int count = 0 // Count for Search +) +{ + // + double result = 0; + + // + T tmp[]; + int tmpCount = Copy( + start, + count, + buffer, + tmp + // + ); + if (tmpCount <= 0) + { + return result; + } + + // + // Calculate Summary ... + for (int i = 0; i < tmpCount; i++) + { + result += buffer[i]; + } + + // + // Calculate Average ... + result = result / tmpCount; + + // + return result; +} + +// +// Get Max of Specific Loopback of a Buffer ... +template +T GetMax( + T &buffer[], // the Buffer which required to search + int start = 0, // Start Index + int count = 0 // Count for Search +) +{ + // + T result = 0; + + // + if (count <= 0) + { + count = ArraySize(buffer); + } + + // + T tmp[]; + int tmpCount = Copy( + start, + count, + buffer, + tmp + // + ); + if (tmpCount <= 0) + { + return result; + } + + // + // Loop Through LoopBack ... + for (int i = 0; i < tmpCount; i++) + { + // + T iValue = tmp[i]; + + // + result = + // + result == 0 || result < iValue + // + ? iValue + // + : result + // + ; + } + + // + return result; +} +template +T GetMax( + T &buffer[], // the Buffer which required to search + int &index, // Item Index ... + int start = 0, // Start Index + int count = 0 // Count for Search +) +{ + // + T result = 0; + index = -1; + + // + if (count <= 0) + { + count = ArraySize(buffer); + } + + // + T tmp[]; + int tmpCount = Copy( + start, + count, + buffer, + tmp + // + ); + if (tmpCount <= 0) + { + return result; + } + + // + // Loop Through LoopBack ... + for (int i = 0; i < tmpCount; i++) + { + // + T iValue = tmp[i]; + + // + bool isNew = result == 0; + bool canSet = isNew || + (!isNew && + result < iValue); + if (canSet) + { + // + index = i; + result = iValue; + } + } + + // + return result; +} +template +T GetSpecifiedMax( + T &buffer[], // the Buffer which required to search + int start = 0, // Start Index + int count = 0 // Count for Search +) +{ + return GetMax( + buffer, + start, + count // + ); +} +template +T GetSpecifiedMax( + T &buffer[], // the Buffer which required to search + int &index, // Item Index ... + int start = 0, // Start Index + int count = 0 // Count for Search +) +{ + return GetMax( + buffer, + index, + start, + count // + ); +} + +// +// Get Min of Specific Loopback of a Buffer ... +template +T GetMin( + T &buffer[], // the Buffer which required to search + int start = 0, // Start Index + int count = 0 // Count for Search +) +{ + // + T result = 0; + + // + if (count <= 0) + { + count = ArraySize(buffer); + } + + // + T tmp[]; + int tmpCount = Copy( + start, + count, + buffer, + tmp + // + ); + if (tmpCount <= 0) + { + return result; + } + + // + // Loop Through LoopBack ... + for (int i = 0; i < tmpCount; i++) + { + // + T iValue = tmp[i]; + + // + result = + // + result == 0 || result > iValue + // + ? iValue + // + : result + // + ; + } + + // + return result; +} +template +T GetMin( + T &buffer[], // the Buffer which required to search + int &index, // Item Index ... + int start = 0, // Start Index + int count = 0 // Count for Search +) +{ + // + T result = 0; + index = -1; + + // + if (count <= 0) + { + count = ArraySize(buffer); + } + + // + T tmp[]; + int tmpCount = Copy( + start, + count, + buffer, + tmp + // + ); + if (tmpCount <= 0) + { + return result; + } + + // + // Loop Through LoopBack ... + for (int i = 0; i < tmpCount; i++) + { + // + T iValue = tmp[i]; + + // + bool isNew = result == 0; + bool canSet = isNew || + (!isNew && + result > iValue); + if (canSet) + { + // + index = i; + result = iValue; + } + } + + // + return result; +} +template +T GetSpecifiedMin( + T &buffer[], // the Buffer which required to search + int start = 0, // Start Index + int count = 0 // Count for Search +) +{ + return GetMin( + buffer, + start, + count // + ); +} +template +T GetSpecifiedMin( + T &buffer[], // the Buffer which required to search + int &index, // Item Index ... + int start = 0, // Start Index + int count = 0 // Count for Search +) +{ + return GetMin( + buffer, + index, + start, + count // + ); +} + +// +// Find a Value less than Specified ... +template +T FindLesserThan( + T value, // Specified Value ... + const T &source[], // Source ... + bool isDescend = false // Find Biggest Lesser Value ... +) +{ + // + T result = -1; + + // + int itemsCount = ArraySize(source); + if (itemsCount <= 0) + { + return result; + } + + // + // Make a Copy of source ... + T tmp[]; + + // + ArrayResize( + tmp, + ArraySize(source) // + ); + + // + ArrayCopy( + tmp, + source // + ); + + // + // Sort Temp Buffer ... + ArraySort(tmp); + if (isDescend) + { + ArrayReverse(tmp); + } + + // + int tmpCount = ArraySize(tmp); + for (int i = 0; i < tmpCount; i++) + { + // + T iValue = tmp[i]; + + // + if (iValue < value) + { + // + result = iValue; + break; + } + } + + // + return result; +} +template +T FindLesserThan( + T value, // Specified Value ... + int &index, // Item Index ... + const T &source[], // Source ... + bool isDescend = false // Find Biggest Lesser Value ... +) +{ + // + T result = -1; + index = -1; + + // + int itemsCount = ArraySize(source); + if (itemsCount <= 0) + { + return result; + } + + // + // Make a Copy of source ... + T tmp[]; + + // + ArrayResize( + tmp, + ArraySize(source) // + ); + + // + ArrayCopy( + tmp, + source // + ); + + // + // Sort Temp Buffer ... + ArraySort(tmp); + if (isDescend) + { + ArrayReverse(tmp); + } + + // + int tmpCount = ArraySize(tmp); + for (int i = 0; i < tmpCount; i++) + { + // + T iValue = tmp[i]; + + // + if (iValue < value) + { + // + index = i; + result = iValue; + break; + } + } + + // + return result; +} + +// +// Find a Value less than Specified ... +template +T FindBiggerThan( + T value, // Specified Value ... + const T &source[], // Source ... + bool isDescend = false // Find Smallest Bigger Value ... +) +{ + // + T result = -1; + + // + int itemsCount = ArraySize(source); + if (itemsCount <= 0) + { + return result; + } + + // + // Make a Copy of source ... + T tmp[]; + + // + ArrayResize( + tmp, + ArraySize(source) // + ); + + // + ArrayCopy( + tmp, + source // + ); + + // + // Sort Temp Buffer ... + ArraySort(tmp); + if (!isDescend) + { + ArrayReverse(tmp); + } + + // + int tmpCount = ArraySize(tmp); + for (int i = 0; i < tmpCount; i++) + { + // + T iValue = tmp[i]; + + // + if (iValue > value) + { + // + result = iValue; + break; + } + } + + // + return result; +} +template +T FindBiggerThan( + T value, // Specified Value ... + int &index, // Item Index ... + const T &source[], // Source ... + bool isDescend = false // Find Smallest Bigger Value ... +) +{ + // + T result = -1; + index = -1; + + // + int itemsCount = ArraySize(source); + if (itemsCount <= 0) + { + return result; + } + + // + // Make a Copy of source ... + T tmp[]; + + // + ArrayResize( + tmp, + ArraySize(source) // + ); + + // + ArrayCopy( + tmp, + source // + ); + + // + // Sort Temp Buffer ... + ArraySort(tmp); + if (!isDescend) + { + ArrayReverse(tmp); + } + + // + int tmpCount = ArraySize(tmp); + for (int i = 0; i < tmpCount; i++) + { + // + T iValue = tmp[i]; + + // + if (iValue > value) + { + // + index = i; + result = iValue; + break; + } + } + + // + return result; +} + +// +// Find Same Values in Array ... +template +void FindSames( + T &result[], // Holds Result ... + T &source[], // Source ... + int verifications = 3 // Number of Consequence Repeat ... +) +{ + // + Clean(result); + + // + // TenkanSen Flats ... + int sourceCount = ArraySize(source); + if (sourceCount > verifications) + { + // + T mLast = 0; + int mVerified = 0; + for (int i = 0; i < sourceCount; i++) + { + // + T iVal = source[i]; + if (mLast == 0) + { + mLast = iVal; + } + else if (mLast == iVal) + { + mVerified++; + } + else + { + mLast = iVal; + mVerified = 0; + } + + // + if (iVal == mLast && mVerified >= verifications) + { + // + Add( + iVal, + result); + + // + mLast = 0; + mVerified = 0; + } + } + } +} + +// +// Add an Item to a Buffer if not Exists ... +void AddIfNotExists( + double value, + double &values[], + double smoothingPoint = 3 // +) +{ + // + double smoothingValue = smoothingPoint * GetPoints(_Symbol); + + // + int valuesCount = ArraySize(values); + if (valuesCount <= 0) + { + // + Add(value, + values); + } + else + { + // + bool isExists = false; + for (int i = 0; i < valuesCount; i++) + { + // + double iVal = values[i]; + + // + double diff = MathAbs(iVal - value); + + // + if (iVal == value || diff < smoothingValue) + { + // + isExists = true; + break; + } + } + + // + if (!isExists) + { + // + Add(value, + values); + } + } +} + +// +// Add a Buffers Child to another Buffer +// if it's not Contains them ... +void AddsIfNotExists( + double &source[], + double &dest[], + double smoothingPoint = 3) +{ + // + double smoothingValue = smoothingPoint * GetPoints(_Symbol); + + // + int sourceCount = ArraySize(source); + if (sourceCount <= 0) + { + return; + } + + // + for (int i = 0; i < sourceCount; i++) + { + // + double iSource = source[i]; + + // + AddIfNotExists( + iSource, + dest, + smoothingPoint); + } +} + +// +// END Collections ... +// + +// +// START Buffers ... +// + +// +template +bool IsSame( + T &buffer[], // Search Buffer + int count = 5, // Number of Searchs + int start = 0 // Start ... +) +{ + // + bool result = false; + + // + int bufferSize = ArraySize(buffer); + result = bufferSize > 0; + if (!result) + { + return result; + } + + // + // Validate Count ... + result = start + count < bufferSize; + if (!result) + { + return result; + } + + // + T iTem = buffer[start]; + for (int i = start; i < start + count; i++) + { + // + if (iTem != buffer[i]) + { + result = false; + break; + } + + // + if (!result) + { + result = true; + } + } + + // + return result; +} + +// +// Check first Cross Over second at index ... +bool IsCrossedOver( + const double &first[], // the buffer which check crossing over second buffer + const double &second[], // first buffer checks based on this buffer + const int index = 0 // check crosses in specific index +) +{ + // + bool result = false; + + // + // Validate Args ... + if (ArraySize(first) < index + 1 || ArraySize(second) < index + 1) + { + return result; + } + + // + result = first[index] > second[index] && + !(first[index + 1] > second[index + 1]); + + // + return result; +} + +// +// Check first is Over second at index ... +bool IsOver( + const double &first[], // the buffer which check over second buffer + const double &second[], // first buffer checks based on this buffer + const int index = 0 // check crosses in specific index +) +{ + // + bool result = false; + + // + // Validate Args ... + if (ArraySize(first) < index + 1 || ArraySize(second) < index + 1) + { + return result; + } + + // + result = first[index] > second[index] && + first[index + 1] > second[index + 1]; + + // + return result; +} + +// +// Check first Cross Under second at index ... +bool IsCrossedUnder( + const double &first[], // the buffer which check crossing under second buffer + const double &second[], // first buffer checks based on this buffer + const int index = 0 // check crosses in specific index +) +{ + // + bool result = false; + + // + // Validate Args ... + if (ArraySize(first) < index + 1 || ArraySize(second) < index + 1) + { + return result; + } + + // + result = first[index] < second[index] && + !(first[index + 1] < second[index + 1]); + + // + return result; +} + +// +// Check first is Under second at index ... +bool IsUnder( + const double &first[], // the buffer which check under second buffer + const double &second[], // first buffer checks based on this buffer + const int index = 0 // check crosses in specific index +) +{ + // + bool result = false; + + // + // Validate Args ... + if (ArraySize(first) < index + 1 || ArraySize(second) < index + 1) + { + return result; + } + + // + result = first[index] < second[index] && + first[index + 1] < second[index + 1]; + + // + return result; +} + +// +// Check if a Value Increasing in Loopback ... +bool IsIncreasing( + const double &buffer[], // the Buffer which required to search + int from = -1, // Last Time Index + int to = -1 // Fisrs Tima Index +) +{ + // + bool result = false; + + // + if (from == -1) + { + from = ArraySize(buffer) - 1; + } + + // + if (to == -1) + { + to = 0; + } + + // + // 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( + buffer, + from, + i // + ); + + // + // Check Result ... + result = result && isPassed && isIIncreasing; + if (!result) + { + break; + } + } + + // + return result; +} + +// +// Check if a Value Decreasing in Loopback ... +bool IsDecreasing( + const double &buffer[], // the Buffer which required to search + int from = -1, // Last Time Index + int to = -1 // Fisrs Tima Index +) +{ + // + bool result = false; + + // + if (from == -1) + { + from = ArraySize(buffer) - 1; + } + + // + if (to == -1) + { + to = 0; + } + + // + // 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( + buffer, + from, + i // + ); + + // + // Check Result ... + result = result && isPassed && isIDecreasing; + if (!result) + { + break; + } + } + + // + return result; +} + +// +bool IsTrendingUp( + const double &buffer1[], // First Buffer + const double &buffer2[] // Seccend Buffer +) +{ + // + bool result = false; + + // + int buffer1Count = ArraySize(buffer1); + int buffer2Count = ArraySize(buffer2); + if (buffer1Count <= 0 || buffer2Count <= 0) + { + return result; + } + + // + int count = MathMin(buffer1Count, buffer2Count); + if (count <= 1) + { + return result; + } + + // + int upCounts = 0; + int downCounts = 0; + double value = MathAbs(buffer1[0] - buffer2[0]); + for (int i = 1; i < count; i++) + { + // + double iValue = MathAbs(buffer1[i] - buffer2[i]); + + // + if (value > iValue) + { + upCounts++; + } + + // + if (value < iValue) + { + downCounts++; + } + } + + // + result = upCounts > 1 && upCounts > downCounts; + + // + return result; +} + +// +bool IsTrendingDown( + const double &buffer1[], // First Buffer + const double &buffer2[] // Seccend Buffer +) +{ + // + bool result = false; + + // + int buffer1Count = ArraySize(buffer1); + int buffer2Count = ArraySize(buffer2); + if (buffer1Count <= 0 || buffer2Count <= 0) + { + return result; + } + + // + int count = MathMin(buffer1Count, buffer2Count); + if (count <= 1) + { + return result; + } + + // + int upCounts = 0; + int downCounts = 0; + double value = MathAbs(buffer1[0] - buffer2[0]); + for (int i = 1; i < count; i++) + { + // + double iValue = MathAbs(buffer1[i] - buffer2[i]); + + // + if (value > iValue) + { + upCounts++; + } + + // + if (value < iValue) + { + downCounts++; + } + } + + // + result = downCounts > 1 && downCounts > upCounts; + + // + return result; +} + +// +// Calculate Slope of Specified Buffer at Specified Index ... +double GetSlope( + const double &buffer[], // Buffer + int from, // In Past Index ... + int to // In Past Index ... +) +{ + // + double result = 0; + + // + if (from > ArraySize(buffer) || to > ArraySize(buffer)) + { + return result; + } + + // + double toValue = buffer[to]; + double fromValue = buffer[from]; + double deltaValue = toValue - fromValue; + double deltaTime = from - to; + + // + result = deltaValue / deltaTime; + + // + return result; +} + +// +// END Buffers ... +// + +// +// START Time ... +// + +// +// 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; +} + +// +// Converts Hours to Seconds ... +int HoursToSeconds(int value) +{ + // + int result = 0; + + // + if (value < 0) + { + value = 0; + } + + // + if (value == 0) + { + return result; + } + + // + result = value * 60 * 60; + + // + return result; +} + +// +// Retrieve DateTime Structure ... +MqlDateTime GetCurrentTime() +{ + // + MqlDateTime result = {}; + + // + datetime cTime = TimeCurrent(); + TimeToStruct(cTime, 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; +} + +// +int GetLocalOffset() +{ + // + MqlDateTime cTimeStruct; + datetime cTime = TimeCurrent(cTimeStruct); + + // + MqlDateTime cLTimeStruct; + datetime cLTime = TimeLocal(cLTimeStruct); + + // + cTimeStruct.sec = 0; + cTime = StructToTime(cTimeStruct); + + // + cLTimeStruct.sec = 0; + cLTime = StructToTime(cLTimeStruct); + + // + int result = ((int)cLTime - (int)cTime); + + // + return result; +} + +// +int GetUTCRequiredTimeOffset() +{ + // + int utcOffset = TimeGMTOffset(); + int localOffset = GetLocalOffset(); + + // + int result = utcOffset + localOffset; + + // + return result; +} + +// +datetime GetUTCTime( + datetime time = NULL, + bool applyTradeServerTime = false // +) +{ + // + datetime result = NULL; + + // + NormalizeTime(time); + + // + datetime cTime = TimeCurrent(); + datetime cTimeLocal = TimeLocal(); + + // + int cLocalOffset = ((int)cTimeLocal - (int)cTime); + int gmtOffset = TimeGMTOffset(); + int offsetDelte = gmtOffset + cLocalOffset; + int requiredUTCOffset = GetUTCRequiredTimeOffset(); + if (requiredUTCOffset > 0) + { + requiredUTCOffset = -1 * requiredUTCOffset; + } + + // + int timeSeconds = (int)time; + int resultSeconds = timeSeconds + requiredUTCOffset; + + // + result = (datetime)(resultSeconds); + + // + return result; +} + +// +// Retrieve only Hour and Minute as String ... +string GetTimeString( + datetime time = NULL // +) +{ + // + NormalizeTime(time); + + // + string result = NULL; + + // + MqlDateTime tStruct; + bool isStructed = TimeToStruct(time, tStruct); + if (!isStructed) + { + return result; + } + + // + string hour = ToString(tStruct.hour); + hour = + StringLen(hour) == 1 + ? "0" + hour + : hour; + + // + string minute = ToString(tStruct.min); + minute = + StringLen(minute) == 1 + ? "0" + minute + : minute; + + // + result = hour + ":" + minute; + + // + return result; +} + +// +// Converts a Date time to File Format ... +string ToFormatString( + datetime mTime, + string separator = "_" // +) +{ + // + string result = NULL; + + // + if (!IsValid(mTime)) + { + return result; + } + + // + MqlDateTime timeStruct; + bool isConverts = TimeToStruct( + mTime, + timeStruct // + ); + if (!isConverts) + { + return result; + } + + // + string year = ToString(timeStruct.year); + string month = ToString(timeStruct.mon); + string day = ToString(timeStruct.day); + string hour = ToString(timeStruct.hour); + string minute = ToString(timeStruct.min); + string second = ToString(timeStruct.sec); + + // + result = + // + // Year ... + year + separator + + // + // Month ... + (StringLen(month) == 1 + ? "0" + month + : month) + + separator + + // + // Day ... + (StringLen(day) == 1 + ? "0" + day + : day) + + separator + + // + // Hour ... + (StringLen(hour) == 1 + ? "0" + hour + : hour) + + separator + + // + // Minute ... + (StringLen(minute) == 1 + ? "0" + minute + : minute) + + separator + + // + // Seconds ... + (StringLen(second) == 1 + ? "0" + second + : second) + + separator + + // + "" + // + ; + + // + return result; +} + +/** + * Converts an String Represetation of Time (00:00) to Date Time .. + * + * @param value: String ... + * + * @return ( datetime ) + */ +datetime ParseDateTimeFromTimeString(string value) +{ + // + datetime result = NULL; + + // + if (!IsValid(value)) + { + return result; + } + + // + // Check Signalling Time ... + MqlDateTime cTime; + bool isTimeRecieved = TimeCurrent(cTime); + if (!isTimeRecieved) + { + return result; + } + + // + // Split ... + string parts[]; + int partsCount = SplitContent( + parts, + value, + ":" + // + ); + if (!IsValidSize(partsCount)) + { + return result; + } + + // + int hour = 0; + int minute = 0; + if (partsCount >= 1) + { + hour = (int)(parts[0]); + } + if (partsCount >= 2) + { + minute = (int)(parts[1]); + } + + // + cTime.day_of_week = 0; + cTime.day_of_year = 0; + + // + cTime.hour = hour; + cTime.min = minute; + + // + result = StructToTime(cTime); + + // + return result; +} + +// +// Check Specific Time in Range of another Time ... +bool IsTimeInRange( + datetime currentTime = NULL, + datetime startTime = NULL, + datetime stopTime = NULL // +) +{ + // + bool result = false; + + // + // Normallize Current Time ... + currentTime = NormalizeTime(currentTime); + + // + result = !IsValid(startTime) && + !IsValid(stopTime); + if (result) + { + return result; + } + + // + result = IsValid(startTime) && + IsValid(stopTime); + if (!result) + { + // + result = IsValid(startTime) && + currentTime >= startTime; + + // + return result; + } + + // + result = currentTime >= startTime && + currentTime < stopTime; + + // + return result; +} +bool IsTimeInRange( + datetime currentTime, + string startTime, + string endTime // +) +{ + // + bool result = false; + + // + result = IsValid(startTime) && + IsValid(endTime); + if (!result) + { + // + // Here Since there isnot provide any + // data source we pass result as true ... + result = true; + return result; + } + + // + // Converts String Representation to Time ... + datetime st = ParseDateTimeFromTimeString(startTime); + datetime et = ParseDateTimeFromTimeString(endTime); + + // + result = IsTimeInRange( + currentTime, + st, + et // + ); + + // + return result; +} + +// +// END Time ... +// + +// +// START Price ... +// + +// +// Get 1 Pip in Price Value ... +double GetPipPrice( + string mSymbol = NULL // Trading Symbol +) +{ + // + mSymbol = NormalizeSymbol(mSymbol); + + // + double symbolPoint = GetPoints(mSymbol); + int symbolDigits = GetDigits(mSymbol); + + // + double result = symbolPoint; + if (symbolDigits == 3 || symbolDigits == 5) + { + result *= 10; + } + + // + return result; +} + +/** + * Calculate Applied Price ... + * + * @param mType: ENUM_X_PRICE member, Price Type ... + * @param mOpen: double collection, Open Prices ... + * @param mHigh: double collection, High Prices ... + * @param mLow: double collection, Low Prices ... + * @param mClose: double collection, Close Prices ... + * @param barIndex: int, Index ... + * + * @return ( double ) + */ +double GetAppliedPrice( + ENUM_X_PRICE mType, // Type of Price Selection + const double &mOpen[], // Open Prices + const double &mHigh[], // High Preices + const double &mLow[], // Low Prices + const double &mClose[], // Close Prices + int barIndex // Bar Index +) +{ + // + double result = 0; + + // + switch (mType) + { + // + case X_PRICE_NONE: + result = 0; + break; + + // + case X_PRICE_HIGH: + result = mHigh[barIndex]; + break; + + // + case X_PRICE_OPEN: + result = mOpen[barIndex]; + break; + + // + case X_PRICE_CLOSE: + result = mClose[barIndex]; + break; + + // + case X_PRICE_LOW: + result = mLow[barIndex]; + break; + + // + case X_PRICE_UP: + result = MathMax(mOpen[barIndex], mClose[barIndex]); + break; + + // + case X_PRICE_DOWN: + result = MathMin(mOpen[barIndex], mClose[barIndex]); + break; + + // + case X_PRICE_MEDIAN: + result = ((mHigh[barIndex] + mLow[barIndex]) / 2.0); + break; + + // + case X_PRICE_BODY_MEDIAN: + result = ((mOpen[barIndex] + mClose[barIndex]) / 2.0); + break; + + // + case X_PRICE_TYPICAL: + result = ((mHigh[barIndex] + mLow[barIndex] + mClose[barIndex]) / 3.0); + break; + + // + case X_PRICE_WEIGHTED: + result = (((mHigh[barIndex] + mLow[barIndex] + mClose[barIndex] + mClose[barIndex]) / 4.0)); + break; + } + + // + return result; +} + +/** + * Calculate Applied Price ... + * + * @param mType: ENUM_X_PRICE member, Price Type ... + * @param mOpen: double, Open Price ... + * @param mHigh: double, High Price ... + * @param mLow: double, Low Price ... + * @param mClose: double, Close Price ... + * @param barIndex: int, Index ... + * + * @return ( double ) + */ +double GetAppliedPrice( + ENUM_X_PRICE mType, // Type of Price Selection + double mOpen, // Open Prices + double mHigh, // High Preices + double mLow, // Low Prices + double mClose // Close Prices +) +{ + // + double result = 0; + + // + switch (mType) + { + // + case X_PRICE_NONE: + result = 0; + break; + + // + case X_PRICE_HIGH: + result = mHigh; + break; + + // + case X_PRICE_OPEN: + result = mOpen; + break; + + // + case X_PRICE_CLOSE: + result = mClose; + break; + + // + case X_PRICE_LOW: + result = mLow; + break; + + // + case X_PRICE_UP: + result = MathMax(mOpen, mClose); + break; + + // + case X_PRICE_DOWN: + result = MathMin(mOpen, mClose); + break; + + // + case X_PRICE_MEDIAN: + result = ((mHigh + mLow) / 2.0); + break; + + // + case X_PRICE_BODY_MEDIAN: + result = ((mOpen + mClose) / 2.0); + break; + + // + case X_PRICE_TYPICAL: + result = ((mHigh + mLow + mClose) / 3.0); + break; + + // + case X_PRICE_WEIGHTED: + result = (((mHigh + mLow + mClose + mClose) / 4.0)); + break; + } + + // + return result; +} + +/** + * Calculate Applied Price ... + * + * @param mSymbol: string, Specified Symbol ... + * @param mPeriod: ENUM_TIMEFRAMES member, Specified PEriod ... + * @param barIndex: int, Specified Bar Index ... + * @param mType: ENUM_X_PRICE member, Specified Price Type ... + * + * @return ( double ) + */ +double GetAppliedPrice( + string mSymbol = NULL, // Symbol + ENUM_TIMEFRAMES mPeriod = NULL, // Period + int barIndex = 0, // Bar Index + ENUM_X_PRICE mType = X_PRICE_CLOSE // Type of Price Selection +) +{ + // + double result = 0; + + // + mSymbol = NormalizeSymbol(mSymbol); + mPeriod = NormalizePeriod(mPeriod); + barIndex = NormalizeInt(barIndex, 0); + + // + bool has = IsValid(mType); + if (!has) + { + return result; + } + + // + double open = iOpen( + mSymbol, + mPeriod, + barIndex // + ); + + // + double high = iHigh( + mSymbol, + mPeriod, + barIndex // + ); + + // + double low = iLow( + mSymbol, + mPeriod, + barIndex // + ); + + // + double close = iClose( + mSymbol, + mPeriod, + barIndex // + ); + + // + // Retrieve Applied Price ... + result = GetAppliedPrice( + mType, + open, + high, + low, + close // + ); + + // + return result; +} + +/** + * Calculate Applied Price ... + * + * @param mSymbol: string, Specified Symbol ... + * @param mPeriod: ENUM_TIMEFRAMES member, Specified PEriod ... + * @param time: int, Specified Bar Time ... + * @param mType: ENUM_X_PRICE member, Specified Price Type ... + * + * @return ( double ) + */ +double GetAppliedPrice( + string mSymbol = NULL, // Symbol + ENUM_TIMEFRAMES mPeriod = NULL, // Period + datetime mTime = NULL, // Bar Time + ENUM_X_PRICE mType = X_PRICE_CLOSE // Type of Price Selection +) +{ + // + double result = 0; + + // + mTime = NormalizeTime(mTime); + mSymbol = NormalizeSymbol(mSymbol); + mPeriod = NormalizePeriod(mPeriod); + + // + bool has = IsValid(mType); + if (!has) + { + return result; + } + + // + int barIndex = GetBarIndex( + mSymbol, + mPeriod, + mTime // + ); + has = IsValidIndex(barIndex); + if (!has) + { + return result; + } + + // + // Retrieve Applied Price ... + result = GetAppliedPrice( + mSymbol, + mPeriod, + barIndex, + mType // + ); + + // + return result; +} + +/** + * Calculate Price Boundary ... + * + * @param upper: double collection reference, Upper Boundary ... + * @param lower: double collection reference, Lower Boundary ... + * @param mSymbol: string, Specified Symbol ... + * @param mPeriod: ENUM_TIMEFRAMES member, Specified PEriod ... + * @param mMode: ENUM_X_BOUNDARY_PRICE member, Specified Boundary Mode ... + * @param mLength: int, Loopback Length of Bondary ... + * @param barIndex: int, Specified Bar Index ... + * @return ( int ) + */ +int GetPriceBoundary( + double &upper[], // Upper Boundary + double &lower[], // Lower Boundary + string mSymbol = NULL, // Symbol + ENUM_TIMEFRAMES mPeriod = NULL, // Period + ENUM_X_BOUNDARY_PRICE mMode = NULL, // Boundary Mode + int mLength = 1, // Length + int barIndex = 0 // Bar Index +) +{ + // + int result = 0; + + // + Clean(upper); + Clean(lower); + + // + // Normalize Args ... + mMode = NormalizeBoundary(mMode); + mSymbol = NormalizeSymbol(mSymbol); + mPeriod = NormalizePeriod(mPeriod); + mLength = NormalizeInt(mLength, 1); + barIndex = NormalizeInt(barIndex, 0); + + // + // Prepare Boundary Price Types ... + ENUM_X_PRICE upperType = + mMode == X_BOUNDARY_PRICE_UP_DOWN + ? X_PRICE_UP + : mMode == X_BOUNDARY_PRICE_HIGH_LOW + ? X_PRICE_HIGH + : X_PRICE_NONE; + ENUM_X_PRICE lowerType = + mMode == X_BOUNDARY_PRICE_UP_DOWN + ? X_PRICE_DOWN + : mMode == X_BOUNDARY_PRICE_HIGH_LOW + ? X_PRICE_LOW + : X_PRICE_NONE; + + // + // Check Boundary Type Validation ... + bool isValid = IsValid(lowerType) && + IsValid(upperType); + if (!isValid) + { + return result; + } + + // + // Loop through Loopbacks ... + int start = barIndex + mLength; + int end = barIndex; + for (int i = start; i >= end; i--) + { + // + double iUpper = GetAppliedPrice( + mSymbol, + mPeriod, + i, + upperType // + ); + double iLower = GetAppliedPrice( + mSymbol, + mPeriod, + i, + lowerType // + ); + + // + Add( + iUpper, + upper // + ); + + // + Add( + iLower, + lower // + ); + } + + // + result = ArraySize(upper); + + // + return result; +} + +// +// END Price ... +// + +// +// START Bar ... +// + +/** + * Retrieve Specific Bar's Time ... + * + * @param mSymbol: string, Provided Symbol ... + * @param mPeriod: ENUM_TIMEFRAMES member, Provided Period ... + * @param barIndex: int, Provided Bar Index ... + * + * @return ( datetime ) + */ +datetime GetBarTime( + string mSymbol = NULL, // Specify Symbol + ENUM_TIMEFRAMES mPeriod = NULL, // Specify TimeFrame + int barIndex = 0 // Specify Bar Index +) +{ + // + // Validate and Normalize Args ... + + // + mSymbol = NormalizeSymbol(mSymbol); + mPeriod = NormalizePeriod(mPeriod); + + // + // Retrieve Bar Time ... + datetime result = iTime( + mSymbol, + mPeriod, + barIndex // + ); + + // + return result; +} + +/** + * Retrieve Specific Bar's Index ... + * + * @param mSymbol: string, Provided Symbol ... + * @param mPeriod: ENUM_TIMEFRAMES member, Provided Period ... + * @param barTime: datetime, Provided Bar Time ... + * + * @return ( datetime ) + */ +int GetBarIndex( + string mSymbol = NULL, // Specify Symbol + ENUM_TIMEFRAMES mPeriod = NULL, // Specify TimeFrame + datetime barTime = NULL // Specify Bar Time +) +{ + // + // Validate and Normalize Args ... + + // + mSymbol = NormalizeSymbol(mSymbol); + mPeriod = NormalizePeriod(mPeriod); + + // + // Retrieve Bar Time ... + int result = iBarShift( + mSymbol, + mPeriod, + barTime // + ); + + // + return result; +} + +// +// END Bar ... +// + +// diff --git a/BKPS/14040203/Libraries/x-saherelm.common.lib.mq5 b/BKPS/14040203/Libraries/x-saherelm.common.lib.mq5 new file mode 100644 index 0000000..cad150f --- /dev/null +++ b/BKPS/14040203/Libraries/x-saherelm.common.lib.mq5 @@ -0,0 +1,157 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Common Library +// -------------------------------------- +// Name: XCommonLib +// Description: provide all commonly used functions ... +// +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +////////////////////////////////////////////////////// +// +// Global Properties ... +#property library +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://www.saherelm.ir" +#property version "1.00" +#property strict + +// +// Imports ... +#include "../Libraries/x-saherelm.common.extensions.lib.mq5" +#include "../Libraries/x-saherelm.common.models.lib.mq5" +#include "../Libraries/x-saherelm.x-ohcl.lib.mq5" + +// +// Models ... + +// +// Consolidation Zone ... +struct XConsolidationZone +{ + // + // Props ... + + // + string symbol; // Symbol ... + ENUM_TIMEFRAMES period; // Period ... + + // + double upper; // Upper ... + double lower; // Lower ... + + // + datetime from; // Start Date + datetime to; // Breake Date + + // + ENUM_X_DIRECTION dir; // Break Direction ... + + // + // Constructor ... + XConsolidationZone() + { + Clean(); + } + + // + // Tools ... + + /** + * Cleanup ... + */ + void Clean() + { + // + upper = 0; + lower = 0; + + // + to = NULL; + from = NULL; + symbol = NULL; + period = NULL; + dir = X_DIRECTION_NONE; + + // + ZeroMemory(this); + } + + /** + * Validate ... + * + * @return ( bool ) + */ + bool IsValid() + { + // + bool result = false; + + // + result = + // + upper > 0 && + lower > 0 && + IsValid(to) && + IsValid(from) && + IsValid(symbol) && + IsValid(period) && + HasDirection(dir) + // + ; + + // + return result; + } + + bool IsSameAs( + XConsolidationZone &item // + ) + { + // + bool result = false; + + // + result = IsValid() && + item.IsValid() && + dir == item.dir && + from == item.from && + upper == item.upper && + lower == item.lower && + symbol == item.symbol && + period == item.period; + + // + return result; + } + + /** + * Retrieve Unique Identifier ... + * + * @return ( string ) + */ + string GetTag() + { + // + string result = + // + "XCZONE" + "_" + + ToString(dir) + "_" + + symbol + "_" + + ToString(period) + "_" + + ToString(upper) + "_" + + ToString(lower) + // + ; + + // + return result; + } + + // +}; + +// \ No newline at end of file diff --git a/BKPS/14040203/Libraries/x-saherelm.common.models.lib.mq5 b/BKPS/14040203/Libraries/x-saherelm.common.models.lib.mq5 new file mode 100644 index 0000000..c8e3186 --- /dev/null +++ b/BKPS/14040203/Libraries/x-saherelm.common.models.lib.mq5 @@ -0,0 +1,392 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Common Library +// -------------------------------------- +// Name: XModelsLib +// 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 + +// +#include "../Libraries/x-saherelm.common.extensions.lib.mq5" + +// +// Use To Parse Symbols for +// Ignore Brokers Additional Suffixes ... +struct XSymbolParser +{ + // + string version; // Temp ... + + // + // Symbol Parsing ... + + // + // Forext ... + + // + bool IsEURUSD(string symbol) + { + // + string symbolIdentifiers[] = { + "EUR", + "USD" // + }; + + // + bool result = Contains( + symbolIdentifiers, + symbol // + ); + + // + return result; + } + + // + bool IsUSDJPY(string symbol) + { + // + string symbolIdentifiers[] = { + "USD", + "JPY" // + }; + + // + bool result = Contains( + symbolIdentifiers, + symbol // + ); + + // + return result; + } + + // + bool IsEURJPY(string symbol) + { + // + string symbolIdentifiers[] = { + "EUR", + "JPY" // + }; + + // + bool result = Contains( + symbolIdentifiers, + symbol // + ); + + // + return result; + } + + // + bool IsUSDCHF(string symbol) + { + // + string symbolIdentifiers[] = { + "USD", + "CHF" // + }; + + // + bool result = Contains( + symbolIdentifiers, + symbol // + ); + + // + return result; + } + + // + bool IsEURCHF(string symbol) + { + // + string symbolIdentifiers[] = { + "EUR", + "CHF" // + }; + + // + bool result = Contains( + symbolIdentifiers, + symbol // + ); + + // + return result; + } + + // + bool IsGBPUSD(string symbol) + { + // + string symbolIdentifiers[] = { + "GBP", + "USD" // + }; + + // + bool result = Contains( + symbolIdentifiers, + symbol // + ); + + // + return result; + } + + // + bool IsEURGBP(string symbol) + { + // + string symbolIdentifiers[] = { + "EUR", + "GBP" // + }; + + // + bool result = Contains( + symbolIdentifiers, + symbol // + ); + + // + return result; + } + + // + bool IsAUDUSD(string symbol) + { + // + string symbolIdentifiers[] = { + "AUD", + "USD" // + }; + + // + bool result = Contains( + symbolIdentifiers, + symbol // + ); + + // + return result; + } + + // + bool IsEURAUD(string symbol) + { + // + string symbolIdentifiers[] = { + "EUR", + "AUD" // + }; + + // + bool result = Contains( + symbolIdentifiers, + symbol // + ); + + // + return result; + } + + // + bool IsUSDCAD(string symbol) + { + // + string symbolIdentifiers[] = { + "USD", + "CAD" // + }; + + // + bool result = Contains( + symbolIdentifiers, + symbol // + ); + + // + return result; + } + + // + bool IsEURCAD(string symbol) + { + // + string symbolIdentifiers[] = { + "EUR", + "CAD" // + }; + + // + bool result = Contains( + symbolIdentifiers, + symbol // + ); + + // + return result; + } + + // + bool IsNZDUSD(string symbol) + { + // + string symbolIdentifiers[] = { + "NZD", + "USD" // + }; + + // + bool result = Contains( + symbolIdentifiers, + symbol // + ); + + // + return result; + } + + // + bool IsEURNZD(string symbol) + { + // + string symbolIdentifiers[] = { + "EUR", + "NZD" // + }; + + // + bool result = Contains( + symbolIdentifiers, + symbol // + ); + + // + return result; + } + + // + // Metals ... + + // + bool IsXAUUSD(string symbol) + { + // + string symbolIdentifiers[] = { + "XAU", + "USD" // + }; + + // + bool result = Contains( + symbolIdentifiers, + symbol // + ); + + // + return result; + } + + // + bool IsXAGUSD(string symbol) + { + // + string symbolIdentifiers[] = { + "XAG", + "USD" // + }; + + // + bool result = Contains( + symbolIdentifiers, + symbol // + ); + + // + return result; + } + + // + // Indexes ... + + // + bool IsDowJones(string symbol) + { + // + bool result = Contains( + "DowJones30", + symbol // + ); + + // + return result; + } + + // + // Oil ... + + // + bool IsBrent(string symbol) + { + // + bool result = Contains( + "BRENT", + symbol // + ); + + // + return result; + } + + // + // Symbol Finder ... + string GetEURUSDSymbol() + { + // + string result = NULL; + + // + string symbols[]; + int symbolsCount = GetAllSymbols( + symbols // + ); + if (!IsValidSize(symbolsCount)) + { + return result; + } + + // + for (int i = 0; i < symbolsCount; i++) + { + // + string iSymbol = symbols[i]; + if (IsEURUSD(iSymbol)) + { + // + result = iSymbol; + break; + } + } + + // + return result; + } +}; diff --git a/BKPS/14040203/Libraries/x-saherelm.draw.lib.mq5 b/BKPS/14040203/Libraries/x-saherelm.draw.lib.mq5 new file mode 100644 index 0000000..ab7f39b --- /dev/null +++ b/BKPS/14040203/Libraries/x-saherelm.draw.lib.mq5 @@ -0,0 +1,2626 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Draw Library +// -------------------------------------- +// Name: XDraw +// Description: provides Draw abilities ... +// +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +////////////////////////////////////////////////////// +// +// Global Properties ... +#property library +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://www.saherelm.ir" +#property version "1.00" +#property strict + +// +// Global Definitions: Variables, Properties and etc ... + +// +// Retrieve Chart Size in Pixel ... +struct XSize +{ + long width; + long height; + + // + int x; + int y; + int w; + int h; + + // + int wStep; + int hStep; +}; + +// +// Define a Draw Specifications ... +struct XDrawSpecifications +{ + // + // Props ... + + // + bool draw; // Draw or Not ... + + // + int width; // Draw Witdth ... + color clr; // Draw Color ... + ENUM_LINE_STYLE style; // Draw Style ... + + // + bool back; // in the background + bool fill; // fill object if supported + bool selection; // highlight to move + bool rayRight; // line's continuation to the right + bool hidden; // hidden in the object list + long zOrder; // priority for mouse click + + // + string label; // Label ... + color labelColor; // Label Color ... + double labelAngel; // Label Angle ... + string labelFont; // Label Font ... + int labelFontSize; // Label Font Size ... + ENUM_ANCHOR_POINT labelAnchor; // Label Anchor Point ... + + // + // Constructor ... + XDrawSpecifications() + { + Clean(); + } + + // + // Operator ... + void operator=(const XDrawSpecifications &value) + { + // + clr = value.clr; + draw = value.draw; + width = value.width; + style = value.style; + + // + back = value.back; + hidden = value.hidden; + zOrder = value.zOrder; + rayRight = value.rayRight; + selection = value.selection; + + // + fill = value.fill; + + // + label = value.label; + labelColor = value.labelColor; + labelAngel = value.labelAngel; + labelFont = value.labelFont; + labelFontSize = value.labelFontSize; + labelAnchor = value.labelAnchor; + } + + // + // Functions ... + + // + void Clean() + { + // + draw = false; + width = 1; + clr = CLR_NONE; + style = STYLE_SOLID; + + // + back = false; + hidden = false; + rayRight = false; + selection = false; + fill = false; + + // + zOrder = 0; + + // + label = ""; + labelColor = CLR_NONE; + labelAngel = 0; + labelFont = "Arial"; + labelFontSize = 20; + labelAnchor = ANCHOR_LEFT_UPPER; + + // + ZeroMemory(this); + } + + // + void Label( + string mLabel = "", // Label ... + color mLabelColor = CLR_NONE, // Label Color ... + string mLabelFont = "Arial", // Label Font ... + int mLabelFontSize = 20, // Label Font Size ... + ENUM_ANCHOR_POINT mLabelAnchor = ANCHOR_LEFT_UPPER, // Label Anchor Point ... + double mLabelAngel = 0 // Label Angle ... + ) + { + // + label = mLabel; + labelFont = mLabelFont; + labelColor = mLabelColor; + labelAngel = mLabelAngel; + labelAnchor = mLabelAnchor; + labelFontSize = mLabelFontSize; + } +}; + +// +// Candle Draw Specifications ... +struct XOHCLDrawSpecification +{ + // + // Props ... + XDrawSpecifications openStyle; + XDrawSpecifications highStyle; + XDrawSpecifications closeStyle; + XDrawSpecifications lowStyle; + + // + // Constructors ... + XOHCLDrawSpecification() + { + Clean(); + } + + // + // Operators ... + void operator=(const XOHCLDrawSpecification &value) + { + // + lowStyle = value.lowStyle; + openStyle = value.openStyle; + highStyle = value.highStyle; + closeStyle = value.closeStyle; + } + + // + // Functions ... + + // + void Clean() + { + // + lowStyle.Clean(); + openStyle.Clean(); + highStyle.Clean(); + closeStyle.Clean(); + + // + ZeroMemory(this); + } + + // + void Default() + { + // + // Open ... + openStyle.width = 1; + openStyle.draw = true; + openStyle.clr = clrLime; + openStyle.style = STYLE_SOLID; + openStyle.Label( + "O", + openStyle.clr); + + // + // High ... + highStyle.width = 1; + highStyle.draw = true; + highStyle.clr = clrAqua; + highStyle.style = STYLE_SOLID; + highStyle.Label( + "H", + highStyle.clr); + + // + // Close ... + closeStyle.width = 1; + closeStyle.draw = true; + closeStyle.clr = clrRed; + closeStyle.style = STYLE_SOLID; + closeStyle.Label( + "C", + closeStyle.clr); + + // + // Low ... + lowStyle.width = 1; + lowStyle.draw = true; + lowStyle.clr = clrMagenta; + lowStyle.style = STYLE_SOLID; + lowStyle.Label( + "L", + lowStyle.clr); + } + + // + void Width(int value) + { + // + lowStyle.width = value; + openStyle.width = value; + highStyle.width = value; + closeStyle.width = value; + } + + // + void Style(ENUM_LINE_STYLE value) + { + // + lowStyle.style = value; + openStyle.style = value; + highStyle.style = value; + closeStyle.style = value; + } + + // + void Color(color value) + { + // + lowStyle.clr = value; + openStyle.clr = value; + highStyle.clr = value; + closeStyle.clr = value; + } + + // + void RayRight(bool value) + { + // + lowStyle.rayRight = value; + openStyle.rayRight = value; + highStyle.rayRight = value; + closeStyle.rayRight = value; + } + + // + void Draw(bool value) + { + // + lowStyle.draw = value; + openStyle.draw = value; + highStyle.draw = value; + closeStyle.draw = value; + } + + // + void Back(bool value) + { + // + lowStyle.back = value; + openStyle.back = value; + highStyle.back = value; + closeStyle.back = value; + } + + // + void Fill(bool value) + { + // + lowStyle.fill = value; + openStyle.fill = value; + highStyle.fill = value; + closeStyle.fill = value; + } + + // + void Label(string value) + { + // + lowStyle.Label(value); + openStyle.Label(value); + highStyle.Label(value); + closeStyle.Label(value); + } + + // + void SetLabelPrefix(string value) + { + // + lowStyle.label = value + " " + lowStyle.label; + openStyle.label = value + " " + openStyle.label; + highStyle.label = value + " " + highStyle.label; + closeStyle.label = value + " " + closeStyle.label; + } +}; + +// +string drawPrefix = "X-OBJ"; + +// +// Common Draw Functions ... + +// +// remove drawn objects ... +void RemoveDraws( + string tag = NULL, + long chartId = -1, + int subWindow = -1 // +) +{ + // + // Normalize Args ... + // + if (tag == NULL) + { + tag = drawPrefix; + } + + // + if (chartId == -1) + { + chartId = 0; + } + + // + if (subWindow == -1) + { + subWindow = 0; + } + + // + for (int iObj = ObjectsTotal(chartId, subWindow) - 1; iObj >= 0; iObj--) + { + // + string on = ObjectName(chartId, iObj, subWindow); + if (StringFind(on, tag) >= 0) + { + ObjectDelete(chartId, on); + } + } + + // + // Redraw Chart ... + ChartRedraw(); +} + +// +bool RemoveDraw( + string name, + long chartId = -1, + int subWindow = -1 // +) +{ + // + bool result = false; + + // + if (chartId == -1) + { + chartId = 0; + } + + // + if (subWindow == -1) + { + subWindow = 0; + } + + // + string objName = ""; + for (int iObj = ObjectsTotal(chartId, subWindow) - 1; iObj >= 0; iObj--) + { + // + string on = ObjectName(chartId, iObj, subWindow); + if (StringFind(on, name) >= 0) + { + // + objName = on; + break; + } + } + + // + if (StringLen(objName) > 0) + { + result = ObjectDelete(chartId, objName); + } + + // + return result; +} + +// +// Deselect All Draws ... +void DeselectAllDraws() +{ + // + int objs = ObjectsTotal(ChartID(), 0); + for (int o = 0; o < objs; o++) + { + ObjectSetInteger(ChartID(), ObjectName(ChartID(), o, 0), OBJPROP_SELECTED, false); + } + + // + ChartRedraw(); +} + +// +// Check Object Exists ... +bool IsDrawExists( + string name, + long chartId = -1, + int subWindow = -1 // +) +{ + // + bool result = false; + + // + if (chartId == -1) + { + chartId = 0; + } + + // + if (subWindow == -1) + { + subWindow = 0; + } + + // + for (int iObj = ObjectsTotal(chartId, subWindow) - 1; iObj >= 0; iObj--) + { + // + string on = ObjectName(chartId, iObj, subWindow); + result = StringFind(on, name) >= 0; + if (result) + { + break; + } + } + + // + return result; +} + +// +// Find Specific Object Name ... +string FindObjectName( + string suggest, + long chartId = 0, + int subWindow = 0 // +) +{ + // + string result = NULL; + + // + int objectsCount = ObjectsTotal(chartId, subWindow); + if (objectsCount <= 0) + { + return result; + } + + // + for (int i = objectsCount - 1; i >= 0; i--) + { + // + string iObjectName = ObjectName(chartId, i, subWindow); + bool isExists = StringFind(iObjectName, suggest) >= 0; + if (isExists) + { + // + result = iObjectName; + break; + } + } + + // + return result; +} + +// +// Regular Draws ... + +// +// Arrow Functions ... + +// +// Draw an Arrow Object on Chart ... +bool DrawArrow( + const long chartID = 0, // chart's ID + const string name = "Arrow", // arrow name + const int subWindow = 0, // subwindow index + datetime time = 0, // anchor point time + double price = 0, // anchor point price + const uchar arrowCode = 252, // arrow code + const ENUM_ARROW_ANCHOR anchor = ANCHOR_BOTTOM, // anchor point position + const color clr = clrAqua, // arrow color + const ENUM_LINE_STYLE style = STYLE_SOLID, // border line style + const int width = 3, // arrow size + const bool back = false, // in the background + const bool selection = false, // highlight to move + const bool hidden = false, // hidden in the object list + const long zOrder = 0 // Order Object ... +) +{ + // + bool result = false; + + // + // set anchor point coordinates if they are not set ... + ChangeArrowEmptyPoint(time, price); + + // + // reset the error value ... + ResetLastError(); + + // + // Normalize Name ... + string objName = drawPrefix + "_" + name; + + // + // create an arrow ... + result = ObjectCreate(chartID, objName, OBJ_ARROW, subWindow, time, price); + if (!result) + { + return result; + } + + // + // set the arrow code ... + ObjectSetInteger(chartID, objName, OBJPROP_ARROWCODE, arrowCode); + + // + // set anchor type ... + ObjectSetInteger(chartID, objName, OBJPROP_ANCHOR, anchor); + + // + // set the arrow color ... + ObjectSetInteger(chartID, objName, OBJPROP_COLOR, clr); + + // + // set the border line style ... + ObjectSetInteger(chartID, objName, OBJPROP_STYLE, style); + + // + // set the arrow's size ... + ObjectSetInteger(chartID, objName, OBJPROP_WIDTH, width); + + // + // display in the foreground false or background true ... + ObjectSetInteger(chartID, objName, OBJPROP_BACK, back); + + // + // enable true or disable false the mode of moving the arrow by mouse + // when creating a graphical object using ObjectCreate function, the object cannot be + // highlighted and moved by default. Inside this method, selection parameter + // is false by default, if you want making it possible to highlight and move the object + // change it to true ... + ObjectSetInteger(chartID, objName, OBJPROP_SELECTABLE, true); + ObjectSetInteger(chartID, objName, OBJPROP_SELECTED, selection); + + // + // hide true or display false graphical object name in the object list ... + ObjectSetInteger(chartID, objName, OBJPROP_HIDDEN, hidden); + + // + // set the priority for receiving the event of a mouse click in the chart ... + ObjectSetInteger(chartID, objName, OBJPROP_ZORDER, zOrder); + + // + // successful execution ... + return result; +} + +// +// Move the anchor point of Arrow ... +bool MoveArrow( + const long chartID = 0, // chart's ID + const string name = "Arrow", // object name + datetime time = 0, // anchor point time coordinate + double price = 0 // anchor point price coordinate +) +{ + // + bool result = false; + + // + // Normalize Name ... + string objName = drawPrefix + "_" + name; + + // + // if point position is not set, move it to the current bar having Bid price ... + if (!time) + { + time = TimeCurrent(); + } + + // + if (!price) + { + price = SymbolInfoDouble(_Symbol, SYMBOL_BID); + } + + // + // move the anchor point ... + result = ObjectMove(chartID, objName, 0, time, price); + + // + return result; +} + +// +// Delete an arrow ... +bool DeleteArrow( + const long chartID = 0, // chart's ID + const string name = "Arrow" // arrow name +) +{ + // + bool result = false; + + // + // Normalize Name ... + string objName = drawPrefix + "_" + name; + + // + // delete an arrow ... + result = !ObjectDelete(chartID, objName); + + // + return result; +} + +// +// Change the arrow code ... +bool ArrowCodeChange( + const long chartID = 0, // chart's ID + const string name = "Arrow", // object name + const uchar code = 252 // arrow code +) +{ + // + bool result = false; + + // + // Normalize Name ... + string objName = drawPrefix + "_" + name; + + // + // change the arrow code ... + result = ObjectSetInteger(chartID, objName, OBJPROP_ARROWCODE, code); + + // + return result; +} + +// +// Change anchor type ... +bool ArrowAnchorChange( + const long chartID = 0, // chart's ID + const string name = "Arrow", // object name + const ENUM_ARROW_ANCHOR anchor = ANCHOR_TOP // anchor type +) +{ + // + bool result = false; + + // + // Normalize Name ... + string objName = drawPrefix + "_" + name; + + // + // change anchor type ... + result = !ObjectSetInteger(chartID, objName, OBJPROP_ANCHOR, anchor); + + // + return result; +} + +// +// Check anchor point values and set default values +// for empty ones ... +void ChangeArrowEmptyPoint( + datetime &time, + double &price // +) +{ + // + // if the point's time is not set, it will be on the current bar ... + if (!time) + { + time = TimeCurrent(); + } + + // + // if the point's price is not set, it will have Bid value ... + if (!price) + { + price = SymbolInfoDouble(_Symbol, SYMBOL_BID); + } +} + +// +// Horizontal Line Functions ... + +// +// Create, Draw the horizontal line ... +bool DrawHorizontalLine( + const long chartID = 0, // chart's ID + const string name = "HLine", // line name + const int subWindow = 0, // subwindow index + double price = 0, // line price + const color clr = clrRed, // line color + const ENUM_LINE_STYLE style = STYLE_SOLID, // line style + const int width = 1, // line width + const bool back = false, // in the background + const bool selection = false, // highlight to move + const bool hidden = false, // hidden in the object list + const long zOrder = 0 // priority for mouse click +) +{ + // + bool result = false; + + // + // if the price is not set, set it at the current Bid price level ... + if (!price) + { + price = SymbolInfoDouble(Symbol(), SYMBOL_BID); + } + + // + // Normalize Name ... + string objName = drawPrefix + "_" + name; + + // + // create a horizontal line ... + result = ObjectCreate(chartID, objName, OBJ_HLINE, subWindow, 0, price); + if (!result) + { + return result; + } + + // + // set line color ... + ObjectSetInteger(chartID, objName, OBJPROP_COLOR, clr); + + // + // set line display style ... + ObjectSetInteger(chartID, objName, OBJPROP_STYLE, style); + + // + // set line width ... + ObjectSetInteger(chartID, objName, OBJPROP_WIDTH, width); + + // + // display in the foreground false or background true ... + ObjectSetInteger(chartID, objName, OBJPROP_BACK, back); + + // + // enable true or disable false the mode of moving the line by mouse + // when creating a graphical object using ObjectCreate function, the object cannot be + // highlighted and moved by default. Inside this method, selection parameter + // is true by default making it possible to highlight and move the object + ObjectSetInteger(chartID, objName, OBJPROP_SELECTABLE, selection); + ObjectSetInteger(chartID, objName, OBJPROP_SELECTED, selection); + + // + // hide true or display false graphical object name in the object list ... + ObjectSetInteger(chartID, objName, OBJPROP_HIDDEN, hidden); + + // + // set the priority for receiving the event of a mouse click in the chart ... + ObjectSetInteger(chartID, objName, OBJPROP_ZORDER, zOrder); + + // + // successful execution ... + return result; +} + +// +// Move horizontal line ... +bool MoveHorizontalLine( + const long chartID = 0, // chart's ID + const string name = "HLine", // line name + double price = 0 // line price +) +{ + // + bool result = false; + + // + // Normalize Name ... + string objName = drawPrefix + "_" + name; + + // + // if the line price is not set, move it to the current Bid price level ... + if (!price) + { + price = SymbolInfoDouble(Symbol(), SYMBOL_BID); + } + + // + // move a horizontal line ... + result = ObjectMove(chartID, objName, 0, 0, price); + + // + return result; +} + +// +// Delete a horizontal line ... +bool DeleteHorizontalLine( + const long chartID = 0, // chart's ID + const string name = "HLine" // line name +) +{ + // + bool result = false; + + // + // Normalize Name ... + string objName = drawPrefix + "_" + name; + + // + // delete a horizontal line ... + result = ObjectDelete(chartID, objName); + + // + return result; +} + +// +// Vertical Line Functions ... + +// +// Create the vertical line ... +bool DrawVerticalLine( + const long chartID = 0, // chart's ID + const string name = "VLine", // line name + const int subWindow = 0, // subwindow index + datetime time = 0, // line time + const color clr = clrRed, // line color + const ENUM_LINE_STYLE style = STYLE_SOLID, // line style + const int width = 1, // line width + const bool back = false, // in the background + const bool selection = false, // highlight to move + const bool hidden = false, // hidden in the object list + const long zOrder = 0 // priority for mouse click +) +{ + // + bool result = false; + + // + // if the line time is not set, draw it via the last bar ... + if (!time) + { + time = TimeCurrent(); + } + + // + // Normalize Name ... + string objName = drawPrefix + "_" + name; + + // + // create a vertical line ... + result = ObjectCreate(chartID, objName, OBJ_VLINE, subWindow, time, 0); + if (!result) + { + return result; + } + + // + // set line color ... + ObjectSetInteger(chartID, objName, OBJPROP_COLOR, clr); + + // + // set line display style ... + ObjectSetInteger(chartID, objName, OBJPROP_STYLE, style); + + // + // set line width ... + ObjectSetInteger(chartID, objName, OBJPROP_WIDTH, width); + + // + // display in the foreground false or background true ... + ObjectSetInteger(chartID, objName, OBJPROP_BACK, back); + + // + // enable true or disable false the mode of moving the line by mouse + // when creating a graphical object using ObjectCreate function, the object cannot be + // highlighted and moved by default. Inside this method, selection parameter + // is true by default making it possible to highlight and move the object ... + ObjectSetInteger(chartID, objName, OBJPROP_SELECTABLE, true); + ObjectSetInteger(chartID, objName, OBJPROP_SELECTED, selection); + + // + // hide true or display false graphical object name in the object list ... + ObjectSetInteger(chartID, objName, OBJPROP_HIDDEN, hidden); + + // + // set the priority for receiving the event of a mouse click in the chart + ObjectSetInteger(chartID, objName, OBJPROP_ZORDER, zOrder); + + // + // successful execution ... + return result; +} + +// +// Move the vertical line ... +bool MoveVerticalLine( + const long chartID = 0, // chart's ID + const string name = "VLine", // line name + datetime time = 0 // line time +) +{ + // + bool result = false; + + // + // Normalize Name ... + string objName = drawPrefix + "_" + name; + + // + // if line time is not set, move the line to the last bar ... + if (!time) + { + time = TimeCurrent(); + } + + // + // move the vertical line ... + result = ObjectMove(chartID, objName, 0, time, 0); + + // + return result; +} + +// +// Delete the vertical line ... +bool DeleteVerticalLine( + const long chartID = 0, // chart's ID + const string name = "VLine" // line name +) +{ + // + bool result = false; + + // + // Normalize Name ... + string objName = drawPrefix + "_" + name; + + // + // delete the vertical line ... + result = ObjectDelete(chartID, objName); + + // + return result; +} + +// +// Rectangle Functions ... + +// +// Create rectangle by the given coordinates ... +bool DrawRectangle( + const long chartID = 0, // chart's ID + const string name = "Rectangle", // rectangle name + const int subWindow = 0, // subwindow index + datetime time1 = 0, // down first point time + double price1 = 0, // down first point price + datetime time2 = 0, // up second point time + double price2 = 0, // up second point price + const color clr = clrRed, // rectangle color + const ENUM_LINE_STYLE style = STYLE_SOLID, // style of rectangle lines + const int width = 1, // width of rectangle lines + const bool fill = false, // filling rectangle with color + const bool back = false, // in the background + const bool selection = true, // highlight to move + const bool hidden = true, // hidden in the object list + const long zOrder = 0 // priority for mouse click +) +{ + // + bool result = false; + + // + // Set anchor points' coordinates if they are not set ... + ChangeRectangleEmptyPoints(time1, price1, time2, price2); + + // + // Normalize Name ... + string objName = drawPrefix + "_" + name; + + // + // Create a rectangle by the given coordinates ... + result = ObjectCreate( + chartID, + objName, + OBJ_RECTANGLE, + subWindow, + time1, + price1, + time2, + price2 // + ); + if (!result) + { + return result; + } + + // + // Set rectangle color ... + ObjectSetInteger(chartID, objName, OBJPROP_COLOR, clr); + + // + // Set the style of rectangle lines + ObjectSetInteger(chartID, objName, OBJPROP_STYLE, style); + + // + // Set width of the rectangle lines ... + ObjectSetInteger(chartID, objName, OBJPROP_WIDTH, width); + + // + // Enable (true) or disable (false) the mode of filling the rectangle ... + ObjectSetInteger(chartID, objName, OBJPROP_FILL, fill); + + // + // Display in the foreground (false) or background (true) ... + ObjectSetInteger(chartID, objName, OBJPROP_BACK, back); + + // + // Enable (true) or disable (false) the mode of highlighting the rectangle for moving + // when creating a graphical object using ObjectCreate function, the object cannot be + // highlighted and moved by default. Inside this method, selection parameter + // is true by default making it possible to highlight and move the object + ObjectSetInteger(chartID, objName, OBJPROP_SELECTABLE, selection); + + // + ObjectSetInteger(chartID, objName, OBJPROP_SELECTED, selection); + + // + // Hide (true) or display (false) graphical object name in the object list ... + ObjectSetInteger(chartID, objName, OBJPROP_HIDDEN, hidden); + + // + // Set the priority for receiving the event of a mouse click in the chart ... + ObjectSetInteger(chartID, objName, OBJPROP_ZORDER, zOrder); + + // + // Successful execution + return result; +} + +// +// Move the rectangle anchor point ...s +bool RectanglePointChange( + const long chartID = 0, // chart's ID + const string name = "Rectangle", // rectangle name + const int pointIndex = 0, // anchor point index + datetime time = 0, // anchor point time coordinate + double price = 0 // anchor point price coordinate +) +{ + // + bool result = false; + + // + // Normalize Name ... + string objName = drawPrefix + "_" + name; + + // + // if point position is not set, move it to the current bar having Bid price ... + if (!time) + { + time = TimeCurrent(); + } + + // + if (!price) + { + price = SymbolInfoDouble(Symbol(), SYMBOL_BID); + } + + // + // Move the anchor point ... + result = ObjectMove(chartID, objName, pointIndex, time, price); + + // + return result; +} + +// +// Delete the rectangle ... +bool DeleteRectangle( + const long chartID = 0, // chart's ID + const string name = "Rectangle" // rectangle name +) +{ + // + bool result = false; + + // + // Normalize Name ... + string objName = drawPrefix + "_" + name; + + // + result = ObjectDelete(chartID, objName); + + // + return result; +} + +// +// Check the values of rectangle's anchor points and set default +// values for empty ones +void ChangeRectangleEmptyPoints( + datetime &time1, double &price1, + datetime &time2, double &price2 // +) +{ + // + // if the first point's time is not set, it will be on the current bar ... + if (!time1) + { + time1 = TimeCurrent(); + } + + // + // if the first point's price is not set, it will have Bid value ... + if (!price1) + { + price1 = SymbolInfoDouble(Symbol(), SYMBOL_BID); + } + + // + // if the second point's time is not set, it is located 9 bars left from the second one ... + if (!time2) + { + // + // array for receiving the open time of the last 10 bars ... + datetime temp[10]; + CopyTime(Symbol(), Period(), time1, 10, temp); + + // + // set the second point 9 bars left from the first one ... + time2 = temp[0]; + } + + // + // if the second point's price is not set, move it 300 points lower than the first one ... + if (!price2) + { + price2 = price1 - 300 * SymbolInfoDouble(Symbol(), SYMBOL_POINT); + } +} + +// +// RectangleLabel Functions ... + +// +// Create Rectangle Label Object ... +bool DrawRectangleLabel( + const long chartID = 0, // chart's ID + const string name = "RectLabel", // label name + const int subWindow = 0, // subwindow index + const int x = 0, // X coordinate + const int y = 0, // Y coordinate + const int width = 50, // width + const int height = 18, // height + const color bgColor = clrWhiteSmoke, // background color + const ENUM_BORDER_TYPE border = BORDER_SUNKEN, // border type + const ENUM_BASE_CORNER corner = CORNER_LEFT_UPPER, // chart corner for anchoring + const color clr = clrRed, // flat border color (Flat) + const ENUM_LINE_STYLE style = STYLE_SOLID, // flat border style + const int lineWidth = 1, // flat border width + const bool back = false, // in the background + const bool selection = false, // highlight to move + const bool hidden = false, // hidden in the object list + const long zOrder = 0 // priority for mouse click +) +{ + // + bool result = false; + + // + // Normalize Name ... + string objName = drawPrefix + "_" + name; + + // + // create a rectangle label + result = ObjectCreate(chartID, objName, OBJ_RECTANGLE_LABEL, subWindow, 0, 0); + if (!result) + { + return result; + } + + // + // set label coordinates ... + ObjectSetInteger(chartID, objName, OBJPROP_XDISTANCE, x); + ObjectSetInteger(chartID, objName, OBJPROP_YDISTANCE, y); + + // + // set label size ... + ObjectSetInteger(chartID, objName, OBJPROP_XSIZE, width); + ObjectSetInteger(chartID, objName, OBJPROP_YSIZE, height); + + // + // set background color ... + ObjectSetInteger(chartID, objName, OBJPROP_BGCOLOR, bgColor); + + // + // set border type ... + ObjectSetInteger(chartID, objName, OBJPROP_BORDER_TYPE, border); + + // + // set the chart's corner, relative to which point coordinates are defined ... + ObjectSetInteger(chartID, objName, OBJPROP_CORNER, corner); + + // + // set flat border color (in Flat mode) ... + ObjectSetInteger(chartID, objName, OBJPROP_COLOR, clr); + + // + // set flat border line style ... + ObjectSetInteger(chartID, objName, OBJPROP_STYLE, style); + + // + // set flat border width ... + ObjectSetInteger(chartID, objName, OBJPROP_WIDTH, lineWidth); + + // + // display in the foreground false or background true ... + ObjectSetInteger(chartID, objName, OBJPROP_BACK, back); + + // + // enable true or disable false the mode of moving the label by mouse ... + ObjectSetInteger(chartID, objName, OBJPROP_SELECTABLE, selection); + ObjectSetInteger(chartID, objName, OBJPROP_SELECTED, selection); + + // + // hide true or display false graphical object name in the object list ... + ObjectSetInteger(chartID, objName, OBJPROP_HIDDEN, hidden); + + // + // set the priority for receiving the event of a mouse click in the chart ... + ObjectSetInteger(chartID, objName, OBJPROP_ZORDER, zOrder); + + // + // successful execution ... + return result; +} + +// +// Move Rectangle Label .. +bool MoveRectangleLabel( + const long chartID = 0, // chart's ID + const string name = "RectLabel", // label name + const int x = 0, // X coordinate + const int y = 0 // Y coordinate +) +{ + // + bool result = false; + + // + // Normalize Name ... + string objName = drawPrefix + "_" + name; + + // + // move the rectangle label ... + result = ObjectSetInteger(chartID, objName, OBJPROP_XDISTANCE, x); + if (!result) + { + return result; + } + + // + result = ObjectSetInteger(chartID, objName, OBJPROP_YDISTANCE, y); + + // + return result; +} + +// +// Delete the rectangle label ... +bool DeleteRectangleLabel( + const long chartID = 0, // chart's ID + const string name = "RectLabel" // label name +) +{ + // + bool result = false; + + // + // Normalize Name ... + string objName = drawPrefix + "_" + name; + + // + // delete the label ... + result = ObjectDelete(chartID, objName); + + // + return result; +} + +// +// Change Rectangle Label Size ... +bool ChangeSizeRectangleLabel( + const long chartID = 0, // chart's ID + const string name = "RectLabel", // label name + const int width = 50, // label width + const int height = 18 // label height +) +{ + // + bool result = false; + + // + // Normalize Name ... + string objName = drawPrefix + "_" + name; + + // + // change label size ... + result = ObjectSetInteger(chartID, objName, OBJPROP_XSIZE, width); + if (!result) + { + return result; + } + + // + result = ObjectSetInteger(chartID, objName, OBJPROP_YSIZE, height); + + // + return result; +} + +// +// Change rectangle label border type ... +bool RectLabelChangeBorderType( + const long chartID = 0, // chart's ID + const string name = "RectLabel", // label name + const ENUM_BORDER_TYPE border = BORDER_SUNKEN // border type +) +{ + // + bool result = false; + + // + // Normalize Name ... + string objName = drawPrefix + "_" + name; + + // + // change border type ... + result = ObjectSetInteger(chartID, objName, OBJPROP_BORDER_TYPE, border); + + // + return result; +} + +// +// TrendLine Funcions ... + +// +// Create a trend line by the given coordinates ... +bool DrawTrendLine( + const long chartID = 0, // chart's ID + const string name = "TrendLine", // line name + const int subWindow = 0, // subwindow index + datetime time1 = 0, // first point time + double price1 = 0, // first point price + datetime time2 = 0, // second point time + double price2 = 0, // second point price + const color clr = clrYellow, // line color + const ENUM_LINE_STYLE style = STYLE_SOLID, // line style + const int width = 1, // line width + const bool back = false, // in the background + const bool selection = false, // highlight to move + const bool rayRight = false, // line's continuation to the right + const bool hidden = false, // hidden in the object list + const long zOrder = 0 // priority for mouse click +) +{ + // + bool result = false; + + // + // set anchor points' coordinates if they are not set ... + ChangeTrendLineEmptyPoints( + time1, + price1, + time2, + price2); + + // + // Normalize Name ... + string objName = drawPrefix + "_" + name; + + // + // create a trend line by the given coordinates ... + result = ObjectCreate(chartID, objName, OBJ_TREND, subWindow, time1, price1, time2, price2); + if (!result) + { + return result; + } + + // + // set line color ... + ObjectSetInteger(chartID, objName, OBJPROP_COLOR, clr); + + // + // set line display style ... + ObjectSetInteger(chartID, objName, OBJPROP_STYLE, style); + + // + // set line width ... + ObjectSetInteger(chartID, objName, OBJPROP_WIDTH, width); + + // + // display in the foreground false or background true ... + ObjectSetInteger(chartID, objName, OBJPROP_BACK, back); + + // + // enable true or disable false the mode of moving the line by mouse + // when creating a graphical object using ObjectCreate function, the object cannot be + // highlighted and moved by default. Inside this method, selection parameter + // is true by default making it possible to highlight and move the object ... + ObjectSetInteger(chartID, objName, OBJPROP_SELECTABLE, true); + ObjectSetInteger(chartID, objName, OBJPROP_SELECTED, selection); + + // + // enable true or disable false the mode of continuation of the line's display to the right ... + ObjectSetInteger(chartID, objName, OBJPROP_RAY_RIGHT, rayRight); + + // + // hide true or display false graphical object name in the object list ... + ObjectSetInteger(chartID, objName, OBJPROP_HIDDEN, hidden); + + // + // set the priority for receiving the event of a mouse click in the chart ... + ObjectSetInteger(chartID, objName, OBJPROP_ZORDER, zOrder); + + // + // successful execution ... + return result; +} + +// +// Move trend line anchor point ... | +bool ChangeTrendLinePoint( + const long chartID = 0, // chart's ID + const string name = "TrendLine", // line name + const int pointindex = 0, // anchor point index + datetime time = 0, // anchor point time coordinate + double price = 0 // anchor point price coordinate +) +{ + // + bool result = false; + + // + // Normalize Name ... + string objName = drawPrefix + "_" + name; + + // + // if point position is not set, move it to the current bar having Bid price ... + if (!time) + { + time = TimeCurrent(); + } + + // + if (!price) + { + price = SymbolInfoDouble(Symbol(), SYMBOL_BID); + } + + // + // move trend line's anchor point ... + result = ObjectMove(chartID, objName, pointindex, time, price); + + // + return result; +} + +// +// The function deletes the trend line from the chart ... +bool DeleteTrendLine( + const long chartID = 0, // chart's ID + const string name = "TrendLine" // line name +) +{ + // + bool result = false; + + // + // Normalize Name ... + string objName = drawPrefix + "_" + name; + + // + // delete a trend line ... + result = ObjectDelete(chartID, objName); + + // + return result; +} + +// +// Check the values of trend line's anchor points and set default ... +// values for empty ones ... +void ChangeTrendLineEmptyPoints( + datetime &time1, + double &price1, + datetime &time2, + double &price2 // +) +{ + // + // if the first point's time is not set, it will be on the current bar ... + if (!time1) + { + time1 = TimeCurrent(); + } + + // + // if the first point's price is not set, it will have Bid value ... + if (!price1) + { + price1 = SymbolInfoDouble(Symbol(), SYMBOL_BID); + } + + // + // if the second point's time is not set, it is located 9 bars left from the second one ... + if (!time2) + { + // + // array for receiving the open time of the last 10 bars ... + datetime temp[10]; + CopyTime(Symbol(), Period(), time1, 10, temp); + + // + // set the second point 9 bars left from the first one ... + time2 = temp[0]; + } + + // + // if the second point's price is not set, it is equal to the first point's one ... + if (!price2) + { + price2 = price1; + } +} + +// +// Text Functions ... + +// +// Create and Draw a Text Object ... +bool DrawText( + const long chartID = 0, // chart's ID + const string name = "Text", // object name + const int subWindow = 0, // subwindow index + datetime time = 0, // anchor point time + double price = 0, // anchor point price + const string text = "Text", // the text itself + const string font = "Arial", // font + const int fontSize = 10, // font size + const color clr = clrRed, // color + const double angle = 0.0, // text slope + const ENUM_ANCHOR_POINT anchor = ANCHOR_CENTER, // anchor type + const bool back = false, // in the background + const bool selection = false, // highlight to move + const bool hidden = true, // hidden in the object list + const long zOrder = 0 // priority for mouse click +) +{ + // + bool result = false; + + // + // set anchor point coordinates if they are not set ... + ChangeTextEmptyPoint(time, price); + + // + // Normalize Name ... + string objName = drawPrefix + "_" + name; + + // + // + // create Text object + result = ObjectCreate(chartID, objName, OBJ_TEXT, subWindow, time, price); + if (!result) + { + return result; + } + + // + // set the text ... + ObjectSetString(chartID, objName, OBJPROP_TEXT, text); + + // + // set text font ... + ObjectSetString(chartID, objName, OBJPROP_FONT, font); + + // + // set font size ... + ObjectSetInteger(chartID, objName, OBJPROP_FONTSIZE, fontSize); + + // + // set the slope angle of the text ... + ObjectSetDouble(chartID, objName, OBJPROP_ANGLE, angle); + + // + // set anchor type ... + ObjectSetInteger(chartID, objName, OBJPROP_ANCHOR, anchor); + + // + // set color ... + ObjectSetInteger(chartID, objName, OBJPROP_COLOR, clr); + + // + // display in the foreground false or background true ... + ObjectSetInteger(chartID, objName, OBJPROP_BACK, back); + + // + // enable true or disable false the mode of moving the object by mouse ... + ObjectSetInteger(chartID, objName, OBJPROP_SELECTABLE, true); + ObjectSetInteger(chartID, objName, OBJPROP_SELECTED, selection); + + // + // hide true or display false graphical object name in the object list ... + ObjectSetInteger(chartID, objName, OBJPROP_HIDDEN, hidden); + + // + // set the priority for receiving the event of a mouse click in the chart ... + ObjectSetInteger(chartID, objName, OBJPROP_ZORDER, zOrder); + + // + // successful execution ... + return result; +} + +// +// Move the anchor point ... +bool MoveText( + const long chartID = 0, // chart's ID + const string name = "Text", // object name + datetime time = 0, // anchor point time coordinate + double price = 0 // anchor point price coordinate +) +{ + // + bool result = false; + + // + // Normalize Name ... + string objName = drawPrefix + "_" + name; + + // + // + // if point position is not set, move it to the current bar having Bid price + if (!time) + { + time = TimeCurrent(); + } + + // + if (!price) + { + price = SymbolInfoDouble(_Symbol, SYMBOL_BID); + } + + // + // move the anchor point ... + result = ObjectMove(chartID, objName, 0, time, price); + + // + return result; +} + +// +// Change the object text ... +bool ChangeText( + const long chartID = 0, // chart's ID + const string name = "Text", // object name + const string text = "Text" // text +) +{ + // + bool result = false; + + // + // Normalize Name ... + string objName = drawPrefix + "_" + name; + + // + // change object text ... + result = ObjectSetString(chartID, objName, OBJPROP_TEXT, text); + + // + return result; +} + +// +// Delete Text object ... +bool DeleteText( + const long chartID = 0, // chart's ID + const string name = "Text" // object name +) +{ + // + bool result = false; + + // + // Normalize Name ... + string objName = drawPrefix + "_" + name; + + // + // delete the object ... + result = ObjectDelete(chartID, objName); + + // + return result; +} + +// +// Check anchor point values and set default values +// for empty ones ... +void ChangeTextEmptyPoint( + datetime &time, + double &price // +) +{ + // + // if the point's time is not set, it will be on the current bar ... + if (!time) + { + time = TimeCurrent(); + } + + // + // if the point's price is not set, it will have Bid value ... + if (!price) + { + price = SymbolInfoDouble(_Symbol, SYMBOL_BID); + } +} + +// +// Fibonacchi Functions ... + +// +// Create Fibonacci Retracement by the given coordinates ... +bool DrawFibonacci( + const long chartID = 0, // chart's ID + const string name = "Fibonacci", // object name + const int subWindow = 0, // subwindow index + datetime time1 = 0, // first point time + double price1 = 0, // first point price + datetime time2 = 0, // second point time + double price2 = 0, // second point price + const color clr = clrRed, // object color + const ENUM_LINE_STYLE style = STYLE_SOLID, // object line style + const int width = 1, // object line width + const bool back = false, // in the background + const bool selection = true, // highlight to move + const bool rayRight = false, // object's continuation to the right + const bool hidden = true, // hidden in the object list + const long zOrder = 0 // priority for mouse click +) +{ + // + bool result = false; + + // + // set anchor points' coordinates if they are not set ... + ChangeFibonacciEmptyPoints(time1, price1, time2, price2); + + // + // Normalize Name ... + string objName = drawPrefix + "_" + name; + + // + // Create Fibonacci Retracement by the given coordinates ... + result = ObjectCreate(chartID, objName, OBJ_FIBO, subWindow, time1, price1, time2, price2); + if (!result) + { + return result; + } + + // + // set color ... + ObjectSetInteger(chartID, objName, OBJPROP_COLOR, clr); + + // + // set line style ... + ObjectSetInteger(chartID, objName, OBJPROP_STYLE, style); + + // + // set line width ... + ObjectSetInteger(chartID, objName, OBJPROP_WIDTH, width); + + // + // display in the foreground false or background true ... + ObjectSetInteger(chartID, objName, OBJPROP_BACK, back); + + // + // enable true or disable false the mode of highlighting the channel for moving + // when creating a graphical object using ObjectCreate function, the object cannot be + // highlighted and moved by default. Inside this method, selection parameter + // is true by default making it possible to highlight and move the object ... + ObjectSetInteger(chartID, objName, OBJPROP_SELECTABLE, true); + ObjectSetInteger(chartID, objName, OBJPROP_SELECTED, selection); + + // + // enable true or disable false the mode of continuation of the object's display to the right ... + ObjectSetInteger(chartID, objName, OBJPROP_RAY_RIGHT, rayRight); + + // + // hide true or display false graphical object name in the object list ... + ObjectSetInteger(chartID, objName, OBJPROP_HIDDEN, hidden); + + // + // set the priority for receiving the event of a mouse click in the chart ... + ObjectSetInteger(chartID, objName, OBJPROP_ZORDER, zOrder); + + // + // successful execution ... + return result; +} + +// +// Create Fibonacci Retracement by the given coordinates ... +bool DrawCustomFibonacci( + // + int levels, // number of level lines + double &values[], // values of level lines + color &colors[], // color of level lines + ENUM_LINE_STYLE &styles[], // style of level lines + int &widths[], // width of level lines + string &descriptions[], // level Descriptions + // + const long chartID = 0, // chart's ID + const string name = "Fibonacci", // object name + const int subWindow = 0, // subwindow index + datetime time1 = 0, // first point time + double price1 = 0, // first point price + datetime time2 = 0, // second point time + double price2 = 0, // second point price + const color clr = clrAqua, // object color + const ENUM_LINE_STYLE style = STYLE_DOT, // object line style + const int width = 1, // object line width + const bool back = false, // in the background + const bool selection = true, // highlight to move + const bool rayRight = false, // object's continuation to the right + const bool hidden = true, // hidden in the object list + const long zOrder = 0 // priority for mouse click +) +{ + // + bool result = false; + + // + // set anchor points' coordinates if they are not set ... + ChangeFibonacciEmptyPoints(time1, price1, time2, price2); + + // + // Normalize Name ... + string objName = drawPrefix + "_" + name; + + // + // Create Fibonacci Retracement by the given coordinates ... + result = ObjectCreate(chartID, name, OBJ_FIBO, subWindow, time1, price1, time2, price2); + if (!result) + { + return result; + } + + // + // set color ... + ObjectSetInteger(chartID, objName, OBJPROP_COLOR, clr); + + // + // set line style ... + ObjectSetInteger(chartID, objName, OBJPROP_STYLE, style); + + // + // set line width ... + ObjectSetInteger(chartID, objName, OBJPROP_WIDTH, width); + + // + // display in the foreground false or background true ... + ObjectSetInteger(chartID, objName, OBJPROP_BACK, back); + + // + // enable true or disable false the mode of highlighting the channel for moving + // when creating a graphical object using ObjectCreate function, the object cannot be + // highlighted and moved by default. Inside this method, selection parameter + // is true by default making it possible to highlight and move the object ... + ObjectSetInteger(chartID, objName, OBJPROP_SELECTABLE, true); + ObjectSetInteger(chartID, objName, OBJPROP_SELECTED, selection); + + // + // enable true or disable false the mode of continuation of the object's display to the right ... + ObjectSetInteger(chartID, objName, OBJPROP_RAY_RIGHT, rayRight); + + // + // hide true or display false graphical object name in the object list ... + ObjectSetInteger(chartID, objName, OBJPROP_HIDDEN, hidden); + + // + // set the priority for receiving the event of a mouse click in the chart ... + ObjectSetInteger(chartID, objName, OBJPROP_ZORDER, zOrder); + + // + // Change Levels Of Fibonacci ... + result = FibonacciLevelsSet( + levels, + values, + colors, + styles, + widths, + descriptions, + chartID, + objName); + + // + // successful execution ... + return result; +} + +// +// Set number of levels and their parameters ... +bool FibonacciLevelsSet( + int levels, // number of level lines + double &values[], // values of level lines + color &colors[], // color of level lines + ENUM_LINE_STYLE &styles[], // style of level lines + int &widths[], // width of level lines + string &descriptions[], // level Descriptions + const long chartID = 0, // chart's ID + const string name = "Fibonacci" // object name +) +{ + // + bool result = false; + + // + // check array sizes ... + result = levels == ArraySize(colors) && + levels == ArraySize(styles) && + levels == ArraySize(widths) && + levels == ArraySize(widths); + if (!result) + { + return result; + } + + // + // Normalize Name ... + string objName = drawPrefix + "_" + name; + + // + // set the number of levels ... + ObjectSetInteger(chartID, objName, OBJPROP_LEVELS, levels); + + // + // set the properties of levels in the loop ... + for (int i = 0; i < levels; i++) + { + // + // level value ... + ObjectSetDouble(chartID, objName, OBJPROP_LEVELVALUE, i, values[i]); + + // + // level color ... + ObjectSetInteger(chartID, objName, OBJPROP_LEVELCOLOR, i, colors[i]); + + // + // level style ... + ObjectSetInteger(chartID, objName, OBJPROP_LEVELSTYLE, i, styles[i]); + + // + // level width ... + ObjectSetInteger(chartID, objName, OBJPROP_LEVELWIDTH, i, widths[i]); + + // + // level description ... + // ObjectSetString(chartID, name, OBJPROP_LEVELTEXT, i, DoubleToString(100 * values[i], 1)); + ObjectSetString(chartID, objName, OBJPROP_LEVELTEXT, i, descriptions[i]); + } + + // + // successful execution ... + return result; +} + +// +// Move Fibonacci Retracement anchor point ... +bool FibonacciPointChange( + const long chartID = 0, // chart's ID + const string name = "Fibonacci", // object name + const int pointIndex = 0, // anchor point index + datetime time = 0, // anchor point time coordinate + double price = 0 // anchor point price coordinate +) +{ + // + bool result = false; + + // + // Normalize Name ... + string objName = drawPrefix + "_" + name; + + // + // if point position is not set, move it to the current bar having Bid price ... + if (!time) + { + time = TimeCurrent(); + } + + // + if (!price) + { + price = SymbolInfoDouble(_Symbol, SYMBOL_BID); + } + + // + // move the anchor point ... + result = ObjectMove(chartID, objName, pointIndex, time, price); + + // + return result; +} + +// +// Delete Fibonacci Retracement ... +bool DeleteFibonachi( + const long chartID = 0, // chart's ID + const string name = "Fibonacci" // object name +) +{ + // + bool result = false; + + // + // Normalize Name ... + string objName = drawPrefix + "_" + name; + + // + // delete the object ... + result = ObjectDelete(chartID, objName); + + // + return result; +} + +// +// Check the values of Fibonacci Retracement anchor points and set +// default values for empty ones ... +void ChangeFibonacciEmptyPoints( + datetime &time1, + double &price1, + datetime &time2, + double &price2 // +) +{ + // + // if the second point's time is not set, it will be on the current bar ... + if (!time2) + { + time2 = TimeCurrent(); + } + + // + // if the second point's price is not set, it will have Bid value ... + if (!price2) + { + price2 = SymbolInfoDouble(_Symbol, SYMBOL_BID); + } + + // + // if the first point's time is not set, it is located 9 bars left from the second one ... + if (!time1) + { + // + // array for receiving the open time of the last 10 bars ... + datetime temp[10]; + CopyTime(Symbol(), Period(), time2, 10, temp); + + // + // set the first point 9 bars left from the second one ... + time1 = temp[0]; + } + + // + // if the first point's price is not set, move it 200 points below the second one ... + if (!price1) + { + price1 = price2 - 200 * SymbolInfoDouble(_Symbol, SYMBOL_POINT); + } +} + +// +// Event Functions ... + +// +// Create an Event ... +bool EventCreate( + const long chartID = 0, // chart's ID + const string name = "Event", // object name + const int subWindow = 0, // subwindow index + const string text = "Content", // event text + datetime time = 0, // anchor point time + const color clr = clrRed, // color + const int width = 1, // point width when highlighted + const bool back = false, // in the background + const bool selection = false, // highlight to move + const bool hidden = true, // hidden in the object list + const long zOrder = 0 // priority for mouse click +) +{ + // + bool result = false; + + // + if (!time) + { + time = TimeCurrent(); + } + + // + // Normalize Name ... + string objName = drawPrefix + "_" + name; + + // + result = ObjectCreate(chartID, objName, OBJ_EVENT, subWindow, time, 0); + if (!result) + { + return result; + } + + // + // set event text + ObjectSetString(chartID, objName, OBJPROP_TEXT, text); + + // + // set color + ObjectSetInteger(chartID, objName, OBJPROP_COLOR, clr); + + // + // set anchor point width if the object is highlighted + 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 event by mouse + ObjectSetInteger(chartID, objName, OBJPROP_SELECTABLE, selection); + ObjectSetInteger(chartID, objName, OBJPROP_SELECTED, selection); + + // + // hide true or display false graphical object name in the object list + ObjectSetInteger(chartID, objName, OBJPROP_HIDDEN, hidden); + + // + // set the priority for receiving the event of a mouse click in the chart + ObjectSetInteger(chartID, objName, OBJPROP_ZORDER, zOrder); + + // + // successful execution + return result; +} + +// +// Change Event object text +bool EventTextChange( + const long chartID = 0, // chart's ID + const string name = "Event", // event name + const string text = "Content" // text +) +{ + // + bool result = false; + + // + // Normalize Name ... + string objName = drawPrefix + "_" + name; + + // + // change object text + result = ObjectSetString(chartID, objName, OBJPROP_TEXT, text); + + // + return result; +} + +// +// Move Event object +bool EventMove( + const long chartID = 0, // chart's ID + const string name = "Event", // event name + datetime time = 0 // time +) +{ + // + bool result = false; + + // + // Normalize Name ... + string objName = drawPrefix + "_" + name; + + // + // if time is not set, move event to the last bar + if (!time) + { + time = TimeCurrent(); + } + + // + // move the object + result = ObjectMove(chartID, objName, 0, time, 0); + + // + return result; +} + +// +// Delete Event object +bool EventDelete( + const long chartID = 0, // chart's ID + const string name = "Event" // event name +) +{ + // + bool result = false; + + // + // Normalize Name ... + string objName = drawPrefix + "_" + name; + + // + // delete the object + result = ObjectDelete(chartID, objName); + + // + return result; +} + +// +// Button Functions ... + +// +// Create the button ... +bool ButtonCreate( + const long chartID = 0, // chart's ID + const string name = "Button", // button name + const int subWindow = 0, // subwindow index + const int x = 0, // X coordinate + const int y = 0, // Y coordinate + const int width = 50, // button width + const int height = 15, // button height + const ENUM_BASE_CORNER corner = CORNER_LEFT_UPPER, // chart corner for anchoring + const string text = "Button", // text + const string font = "Arial", // font + const int fontSize = 8, // font size + const color clr = clrBlack, // text color + const color bgColor = clrLightGray, // background color + const color borderColor = clrNONE, // border color + const bool state = false, // pressed/released + const bool back = false, // in the background + const bool selection = false, // highlight to move + const bool hidden = true, // hidden in the object list + const long zOrder = 0 // priority for mouse click +) +{ + // + bool result = false; + + // + // Normalize Name ... + string objName = drawPrefix + "_" + name; + + // + // create the button + result = ObjectCreate(chartID, objName, OBJ_BUTTON, subWindow, 0, 0); + if (!result) + { + return result; + } + + // + // set button coordinates + ObjectSetInteger(chartID, objName, OBJPROP_XDISTANCE, x); + ObjectSetInteger(chartID, objName, OBJPROP_YDISTANCE, y); + + // + // set button size + ObjectSetInteger(chartID, objName, OBJPROP_XSIZE, width); + ObjectSetInteger(chartID, objName, OBJPROP_YSIZE, height); + + // + // set the chart's corner, relative to which point coordinates are defined + ObjectSetInteger(chartID, objName, OBJPROP_CORNER, corner); + + // + // 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 text color + ObjectSetInteger(chartID, objName, OBJPROP_COLOR, clr); + + // + // set background color + ObjectSetInteger(chartID, objName, OBJPROP_BGCOLOR, bgColor); + + // + // set border color + ObjectSetInteger(chartID, objName, OBJPROP_BORDER_COLOR, borderColor); + + // + // display in the foreground false or background true + ObjectSetInteger(chartID, objName, OBJPROP_BACK, back); + + // + // set button state + ObjectSetInteger(chartID, objName, OBJPROP_STATE, state); + + // + // enable true or disable false the mode of moving the button 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); + + // + 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 + + // + // Normalize Name ... + string objName = drawPrefix + "_" + name; + + // + result = ObjectSetInteger(chartID, objName, OBJPROP_XDISTANCE, x); + if (!result) + { + return result; + } + + // + result = ObjectSetInteger(chartID, objName, 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 + + // + // Normalize Name ... + string objName = drawPrefix + "_" + name; + + // + result = ObjectSetInteger(chartID, objName, OBJPROP_XSIZE, width); + if (!result) + { + return result; + } + + // + result = ObjectSetInteger(chartID, objName, 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; + + // + // Normalize Name ... + string objName = drawPrefix + "_" + name; + + // + // change anchor corner + result = ObjectSetInteger(chartID, objName, 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; + + // + // Normalize Name ... + string objName = drawPrefix + "_" + name; + + // + // change object text + result = ObjectSetString(chartID, objName, 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; + + // + // Normalize Name ... + string objName = drawPrefix + "_" + name; + + // + // delete the button + result = ObjectDelete(chartID, objName); + + // + return result; +} + +// +// Chart Style Drawers ... + +// +// Apply Styles On Chart ... +void ApplyChartStyle( + long mChartId = -1, // chart's ID + ENUM_CHART_MODE mMode = CHART_CANDLES, // chart's mMode + bool mShowBidLine = true, // show bid line + bool mShowAskLine = true, // show ask line + bool mShowGrid = false, // show grids on chart + bool mShowVolumes = false, // show volumes + bool mShowTradeLevels = true, // Displaying trade levels in the chart (levels of open positions, Stop Loss, Take Profit and pending orders) + bool mAutoScroll = true, // chart autoscroll + bool mQuickNavigation = true, // chart quick navigation state + color mForeGroundColor = clrWhite, // chart's foreground color + color mBackGroundColor = clrBlack, // chart's background color + color mUpColor = clrGreen, // Up Color + color mDownColor = clrRed, // Down Color + color mBullishColor = clrGreen, // Bullish color + color mBearishColor = clrRed, // Bearish color + color mGridColor = clrGray, // grid color + color mBidLineColor = clrGray, // bid line color + color mAskLineColor = clrRed, // ask line color + color mLineColor = clrLime, // line mMode and doji candlestick color + color mStopColor = clrGold, // Color of stop order levels (Stop Loss and Take Profit) + color mVolumesColor = clrGreen // volumes color +) +{ + // + // Validate Args ... + if (mChartId == -1) + { + mChartId = 0; + } + + // + ChartSetInteger(mChartId, CHART_MODE, mMode); + ChartSetInteger(mChartId, CHART_SHOW_BID_LINE, mShowBidLine); + ChartSetInteger(mChartId, CHART_SHOW_ASK_LINE, mShowAskLine); + ChartSetInteger(mChartId, CHART_SHOW_GRID, mShowGrid); + ChartSetInteger(mChartId, CHART_SHOW_VOLUMES, mShowVolumes); + ChartSetInteger(mChartId, CHART_SHOW_TRADE_LEVELS, mShowTradeLevels); + ChartSetInteger(mChartId, CHART_AUTOSCROLL, mAutoScroll); + ChartSetInteger(mChartId, CHART_QUICK_NAVIGATION, mQuickNavigation); + ChartSetInteger(mChartId, CHART_COLOR_FOREGROUND, mForeGroundColor); + ChartSetInteger(mChartId, CHART_COLOR_BACKGROUND, mBackGroundColor); + ChartSetInteger(mChartId, CHART_COLOR_CHART_UP, mUpColor); + ChartSetInteger(mChartId, CHART_COLOR_CHART_DOWN, mDownColor); + ChartSetInteger(mChartId, CHART_COLOR_CANDLE_BULL, mBullishColor); + ChartSetInteger(mChartId, CHART_COLOR_CANDLE_BEAR, mBearishColor); + ChartSetInteger(mChartId, CHART_COLOR_GRID, mGridColor); + ChartSetInteger(mChartId, CHART_COLOR_BID, mBidLineColor); + ChartSetInteger(mChartId, CHART_COLOR_ASK, mAskLineColor); + ChartSetInteger(mChartId, CHART_COLOR_STOP_LEVEL, mStopColor); + ChartSetInteger(mChartId, CHART_COLOR_CHART_LINE, mLineColor); + ChartSetInteger(mChartId, CHART_COLOR_VOLUME, mVolumesColor); +} + +// +// Tools ... + +// +// Retrieve Chart Size ... +bool GetChartSize( + XSize &result, // Holds Result ... + long chartID = 0 // Specified Chart ID ... +) +{ + // + bool mResult = false; + + // + mResult = ChartGetInteger(0, CHART_WIDTH_IN_PIXELS, 0, result.width); + if (!mResult) + { + return mResult; + } + + // + mResult = ChartGetInteger(0, CHART_HEIGHT_IN_PIXELS, 0, result.height); + + // + return mResult; +} diff --git a/BKPS/14040203/Libraries/x-saherelm.x-enums.lib.mq5 b/BKPS/14040203/Libraries/x-saherelm.x-enums.lib.mq5 new file mode 100644 index 0000000..e212425 --- /dev/null +++ b/BKPS/14040203/Libraries/x-saherelm.x-enums.lib.mq5 @@ -0,0 +1,1251 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Common Library +// -------------------------------------- +// Name: XEnumsLib +// 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 Price Type ... +// + +// +// Availables Price Types ... +enum ENUM_X_PRICE +{ + X_PRICE_NONE, // None + X_PRICE_HIGH, // High + X_PRICE_OPEN, // Open + X_PRICE_CLOSE, // Close + X_PRICE_LOW, // Low + X_PRICE_UP, // Body Up + X_PRICE_DOWN, // Body Down + X_PRICE_MEDIAN, // Median + X_PRICE_BODY_MEDIAN, // Body Median + X_PRICE_TYPICAL, // Typical + X_PRICE_WEIGHTED // Weighted +}; + +// +// Extensions ... + +/** + * Validate ... + * + * @param value: ENUM_X_PRICE member ... + * + * @return ( bool ) + */ +bool IsValid(ENUM_X_PRICE value) +{ + // + bool result = false; + + // + result = + value != NULL && + value != X_PRICE_NONE; + + // + return result; +} + +/** + * Converts Series Mode to ENUM_X_PRICE ... + * + * @param value: ENUM_SERIESMODE member ... + * + * @return ( ENUM_X_PRICE ) + */ +ENUM_X_PRICE ToXPrice(ENUM_SERIESMODE value) +{ + // + ENUM_X_PRICE result = X_PRICE_CLOSE; + + // + switch (value) + { + // + // High ... + case MODE_HIGH: + result = X_PRICE_HIGH; + break; + + // + // Open ... + case MODE_OPEN: + result = X_PRICE_OPEN; + break; + + // + // Low ... + case MODE_LOW: + result = X_PRICE_LOW; + break; + + // + // Close ... + // Default ... + case MODE_CLOSE: + default: + result = X_PRICE_CLOSE; + break; + } + + // + return result; +} + +/** + * Converts Applied Price to ENUM_X_PRICE ... + * + * @param value: ENUM_APPLIED_PRICE member ... + * + * @return ( ENUM_X_PRICE ) + */ +ENUM_X_PRICE ToXPrice(ENUM_APPLIED_PRICE value) +{ + // + ENUM_X_PRICE result = X_PRICE_NONE; + + // + switch (value) + { + // + case PRICE_HIGH: + result = X_PRICE_HIGH; + break; + + // + case PRICE_OPEN: + result = X_PRICE_OPEN; + break; + + // + case PRICE_CLOSE: + result = X_PRICE_CLOSE; + break; + + // + case PRICE_LOW: + result = X_PRICE_LOW; + break; + + // + case PRICE_MEDIAN: + result = X_PRICE_MEDIAN; + break; + + // + case PRICE_TYPICAL: + result = X_PRICE_TYPICAL; + break; + + // + case PRICE_WEIGHTED: + result = X_PRICE_WEIGHTED; + break; + } + + // + return result; +} + +/** + * Converts Price Type to Applied Price ... + * + * @param value: ENUM_X_PRICE member ... + * + * @return ( ENUM_APPLIED_PRICE ) + */ +ENUM_APPLIED_PRICE ToAppliedPrice(ENUM_X_PRICE value) +{ + // + // Default ... + ENUM_APPLIED_PRICE result = PRICE_CLOSE; + + // + if (!IsValid(value) || + value == X_PRICE_UP || + value == X_PRICE_DOWN || + value == X_PRICE_BODY_MEDIAN) + { + return result; + } + + // + switch (value) + { + // + case X_PRICE_HIGH: + result = PRICE_HIGH; + break; + + // + case X_PRICE_OPEN: + result = PRICE_OPEN; + break; + + // + case X_PRICE_CLOSE: + result = PRICE_CLOSE; + break; + + // + case X_PRICE_LOW: + result = PRICE_LOW; + break; + + // + case X_PRICE_MEDIAN: + result = PRICE_MEDIAN; + break; + + // + case X_PRICE_TYPICAL: + result = PRICE_TYPICAL; + break; + + // + case X_PRICE_WEIGHTED: + result = PRICE_WEIGHTED; + break; + } + + // + return result; +} + +/** + * Converts To String ... + * + * @param value: ENUM_X_PRICE member ... + * + * @return ( string ) + */ +string ToString(ENUM_X_PRICE value) +{ + // + string result = NULL; + + // + switch (value) + { + // + case X_PRICE_NONE: + result = "None"; + break; + + // + case X_PRICE_HIGH: + result = "High"; + break; + + // + case X_PRICE_OPEN: + result = "Open"; + break; + + // + case X_PRICE_CLOSE: + result = "Close"; + break; + + // + case X_PRICE_LOW: + result = "Low"; + break; + + // + case X_PRICE_UP: + result = "Body Up"; + break; + + // + case X_PRICE_DOWN: + result = "Body Down"; + break; + + // + case X_PRICE_MEDIAN: + result = "Median"; + break; + + // + case X_PRICE_BODY_MEDIAN: + result = "Body Median"; + break; + + // + case X_PRICE_TYPICAL: + result = "Typical"; + break; + + // + case X_PRICE_WEIGHTED: + result = "Weighted"; + break; + } + + // + return result; +} + +// +// END Price Type ... +// + +// +// START Boundary Price Type ... +// + +// +// Available Boundary Price Types ... +enum ENUM_X_BOUNDARY_PRICE +{ + X_BOUNDARY_PRICE_NONE, // None + X_BOUNDARY_PRICE_UP_DOWN, // Up/Down + X_BOUNDARY_PRICE_HIGH_LOW, // High/Low +}; + +/** + * Validate ... + * + * @param value: ENUM_X_BOUNDARY_PRICE member ... + * + * @return ( bool ) + */ +bool IsValid(ENUM_X_BOUNDARY_PRICE value) +{ + // + bool result = false; + + // + result = + value != NULL && + value != X_BOUNDARY_PRICE_NONE; + + // + return result; +} + +/** + * Converts To String ... + * + * @param value: ENUM_X_BOUNDARY_PRICE member ... + * + * @return ( string ) + */ +string ToString(ENUM_X_BOUNDARY_PRICE value) +{ + // + string result = NULL; + + // + if (!IsValid(value)) + { + value = X_BOUNDARY_PRICE_NONE; + } + + // + result = EnumToString(value); + + // + return result; +} + +// +// END Boundary Price Type ... +// + +// +// START Direction ... +// + +// +// Directions ... +enum ENUM_X_DIRECTION +{ + X_DIRECTION_ALL, // All + X_DIRECTION_NONE, // None + X_DIRECTION_BULLISH, // Bullish + X_DIRECTION_BEARISH, // Bearish +}; + +// +// Extensions ... + +/** + * Validate ... + * + * @param value: ENUM_X_DIRECTION member ... + * + * @return ( bool ) + */ +bool IsValid(ENUM_X_DIRECTION value) +{ + // + bool result = false; + + // + result = + value != NULL && + value != X_DIRECTION_NONE; + + // + return result; +} + +/** + * Validate value Has Specified Direction ... + * + * @param value: ENUM_X_DIRECTION member ... + * + * @return ( bool ) + */ +bool HasDirection(ENUM_X_DIRECTION value) +{ + // + bool result = false; + + // + result = IsValid(value) && + value != X_DIRECTION_ALL; + + // + return result; +} + +/** + * Check a Direction is Bullish or not ... + * + * @param value: ENUM_X_DIRECTION member ... + * + * @return ( bool ) + */ +bool IsBullish(ENUM_X_DIRECTION value) +{ + // + bool result = false; + + // + result = value == X_DIRECTION_BULLISH; + + // + return result; +} +bool IsSpecifiedBullish(ENUM_X_DIRECTION value) +{ + // + bool result = false; + + // + result = value == X_DIRECTION_BULLISH; + + // + return result; +} + +/** + * Check a Direction is Bearish or not ... + * + * @param value: ENUM_X_DIRECTION member ... + * + * @return ( bool ) + */ +bool IsBearish(ENUM_X_DIRECTION value) +{ + // + bool result = false; + + // + result = value == X_DIRECTION_BEARISH; + + // + return result; +} +bool IsSpecifiedBearish(ENUM_X_DIRECTION value) +{ + // + bool result = false; + + // + result = value == X_DIRECTION_BEARISH; + + // + return result; +} + +/** + * Converts Specified Direction to Opposit ... + * + * @param value: ENUM_X_DIRECTION member ... + * + * @return ( ENUM_X_DIRECTION ) + */ +ENUM_X_DIRECTION Opposit(ENUM_X_DIRECTION value) +{ + // + ENUM_X_DIRECTION result = X_DIRECTION_NONE; + + // + if (!HasDirection(value)) + { + return result; + } + + // + result = + IsBullish(value) + ? X_DIRECTION_BEARISH + : X_DIRECTION_BULLISH; + + // + return result; +} + +/** + * Converts To String ... + * + * @param value: ENUM_X_DIRECTION member ... + * + * @return ( string ) + */ +string ToString(ENUM_X_DIRECTION value) +{ + // + string result = NULL; + + // + switch (value) + { + case X_DIRECTION_ALL: + result = "ALL"; + break; + case X_DIRECTION_NONE: + result = "NONE"; + break; + case X_DIRECTION_BULLISH: + result = "BULLISH"; + break; + case X_DIRECTION_BEARISH: + result = "BEARISH"; + break; + } + + // + return result; +} + +// +// END Direction ... +// + +// +// START Fibo Level ... +// + +// +// Fibonacci Levels ... +enum ENUM_X_FIBO_LEVELS +{ + X_FIBO_LEVEL_236, // 0.236 + X_FIBO_LEVEL_270, // 0.27 + X_FIBO_LEVEL_382, // 0.382 + X_FIBO_LEVEL_500, // 0.5 + X_FIBO_LEVEL_618, // 0.618 + X_FIBO_LEVEL_730, // 0.730 + X_FIBO_LEVEL_764, // 0.764 + X_FIBO_LEVEL_786, // 0.786 +}; + +// +// Extensions ... + +/** + * Converts To String ... + * + * @param value: ENUM_X_FIBO_LEVELS member ... + * + * @return ( string ) + */ +string ToString(ENUM_X_FIBO_LEVELS value) +{ + // + string result = NULL; + + // + switch (value) + { + // + case X_FIBO_LEVEL_236: + result = "0.236"; + break; + + // + case X_FIBO_LEVEL_270: + result = "0.270"; + break; + + // + case X_FIBO_LEVEL_382: + result = "0.382"; + break; + + // + case X_FIBO_LEVEL_500: + result = "0.500"; + break; + + // + case X_FIBO_LEVEL_618: + result = "0.618"; + break; + + // + case X_FIBO_LEVEL_730: + result = "0.730"; + break; + + // + case X_FIBO_LEVEL_764: + result = "0.764"; + break; + + // + case X_FIBO_LEVEL_786: + result = "0.786"; + break; + } + + // + return result; +} + +/** + * Converts To String ... + * + * @param value: ENUM_X_FIBO_LEVELS member ... + * + * @return ( double ) + */ +double GetFiboLevelValue(ENUM_X_FIBO_LEVELS value) +{ + // + double result = 0; + + // + switch (value) + { + // + case X_FIBO_LEVEL_236: + result = 0.236; + break; + + // + case X_FIBO_LEVEL_270: + result = 0.270; + break; + + // + case X_FIBO_LEVEL_382: + result = 0.382; + break; + + // + case X_FIBO_LEVEL_500: + result = 0.500; + break; + + // + case X_FIBO_LEVEL_618: + result = 0.618; + break; + + // + case X_FIBO_LEVEL_730: + result = 0.730; + break; + + // + case X_FIBO_LEVEL_764: + result = 0.764; + break; + + // + case X_FIBO_LEVEL_786: + result = 0.786; + break; + } + + // + return result; +} + +// +// END Fibo Level ... +// + +// +// START Swing Types ... +// + +// +// Swing Types ... +enum ENUM_X_SWING_TYPE +{ + X_SWING_NONE, // None + X_SWING_LOW, // Swing Low + X_SWING_HIGH, // Swing High +}; + +// +// Extensions ... + +/** + * Validate ... + * + * @param value: ENUM_X_DIRECTION member ... + * + * @return ( bool ) + */ +bool IsValid(ENUM_X_SWING_TYPE value) +{ + // + bool result = false; + + // + result = + value != NULL && + value != X_SWING_NONE; + + // + return result; +} + +/** + * Converts To String ... + * + * @param value: ENUM_X_SWING_TYPE member ... + * + * @return ( string ) + */ +string ToString(ENUM_X_SWING_TYPE value) +{ + // + string result = NULL; + + // + switch (value) + { + // + case X_SWING_NONE: + result = "None"; + break; + + // + case X_SWING_LOW: + result = "Swing Low"; + break; + + // + case X_SWING_HIGH: + result = "Swing High"; + break; + } + + // + return result; +} + +/** + * Converts To ENUM_SERIESMODE ... + * + * @param value: ENUM_X_SWING_TYPE member ... + * + * @return ( ENUM_SERIESMODE ) + */ +ENUM_SERIESMODE ToSeriesMode(ENUM_X_SWING_TYPE value) +{ + // + ENUM_SERIESMODE result = MODE_HIGH; + + // + switch (value) + { + // + case X_SWING_HIGH: + result = MODE_HIGH; + break; + + // + case X_SWING_LOW: + default: + result = MODE_LOW; + break; + } + + // + return result; +} + +// +// END Swing Types ... +// + +// +// START Period Method ... +// + +// +// Period Calculation Method ... +enum ENUM_X_PERIOD_METHOD +{ + X_PERIOD_NONE, // None + X_PERIOD_AUTO, // Auto Select + X_PERIOD_MANUALLY // Manually +}; + +// +// Extensions ... + +/** + * Validate ... + * + * @param value: ENUM_X_PERIOD_METHOD member ... + * + * @return ( bool ) + */ +bool IsValid(ENUM_X_PERIOD_METHOD value) +{ + // + bool result = false; + + // + result = + value != NULL && + value != X_PERIOD_NONE; + + // + return result; +} + +/** + * Converts To String ... + * + * @param value: ENUM_X_PERIOD_METHOD member ... + * + * @return ( string ) + */ +string ToString(ENUM_X_PERIOD_METHOD value) +{ + // + string result = NULL; + + // + switch (value) + { + // + case X_PERIOD_NONE: + result = "None"; + break; + + // + case X_PERIOD_AUTO: + result = "Auto Select"; + break; + + // + case X_PERIOD_MANUALLY: + result = "Manually"; + break; + } + + // + return result; +} + +// +// END Period Method ... +// + +// +// START Market Cycles ... +// + +// +// Market Cycles ... +enum ENUM_X_MARKET_CYCLES +{ + X_MARKET_CYCLE_UNKNOWN, // Unknown Cycle + X_MARKET_CYCLE_SHORT, // Short Cycle + X_MARKET_CYCLE_MEDIUM, // Medium Cycle + X_MARKET_CYCLE_LONG, // Long Cycle + X_MARKET_CYCLE_HIND, // Hind Cycle +}; + +// +// Extensions ... + +/** + * Validate ... + * + * @param value: ENUM_X_MARKET_CYCLES member ... + * + * @return ( bool ) + */ +bool IsValid(ENUM_X_MARKET_CYCLES value) +{ + // + bool result = false; + + // + result = + // + value != NULL && + value != X_MARKET_CYCLE_UNKNOWN + // + ; + + // + return result; +} + +/** + * Converts an String to it's related Market Cycle ... + * + * @param value: string ... + * + * @return ( ENUM_X_MARKET_CYCLES ) + */ +ENUM_X_MARKET_CYCLES ToCycle(string value) +{ + // + ENUM_X_MARKET_CYCLES result = X_MARKET_CYCLE_UNKNOWN; + + // + ENUM_X_MARKET_CYCLES cycles[]; + int count = GetAllMarketCycles(cycles); + for (int i = 0; i < count; i++) + { + // + ENUM_X_MARKET_CYCLES iCycle = cycles[i]; + string iStr = ToString(iCycle); + + // + if (value == iStr) + { + // + result = iCycle; + break; + } + } + + // + return result; +} + +/** + * Converts To String ... + * + * @param value: ENUM_X_MARKET_CYCLES member ... + * + * @return ( string ) + */ +string ToString(ENUM_X_MARKET_CYCLES value) +{ + // + string result = NULL; + + // + switch (value) + { + // + case X_MARKET_CYCLE_UNKNOWN: + result = "Unknown Cycle"; + break; + + // + case X_MARKET_CYCLE_SHORT: + result = "Short Cycle"; + break; + + // + case X_MARKET_CYCLE_MEDIUM: + result = "Medium Cycle"; + break; + + // + case X_MARKET_CYCLE_LONG: + result = "Long Cycle"; + break; + + // + case X_MARKET_CYCLE_HIND: + result = "Hind Cycle"; + break; + } + + // + return result; +} + +/** + * Retrieve All Availabled Market Cycles ... + * + * @param cycles: ENUM_X_MARKET_CYCLES member collection ... + * + * @return ( int ) + */ +int GetAllMarketCycles(ENUM_X_MARKET_CYCLES &cycles[]) +{ + // + ZeroMemory(cycles); + ArrayResize(cycles, 0); + + // + ArrayResize(cycles, ArraySize(cycles) + 1); + cycles[ArraySize(cycles) - 1] = X_MARKET_CYCLE_UNKNOWN; + + // + ArrayResize(cycles, ArraySize(cycles) + 1); + cycles[ArraySize(cycles) - 1] = X_MARKET_CYCLE_SHORT; + + // + ArrayResize(cycles, ArraySize(cycles) + 1); + cycles[ArraySize(cycles) - 1] = X_MARKET_CYCLE_MEDIUM; + + // + ArrayResize(cycles, ArraySize(cycles) + 1); + cycles[ArraySize(cycles) - 1] = X_MARKET_CYCLE_LONG; + + // + ArrayResize(cycles, ArraySize(cycles) + 1); + cycles[ArraySize(cycles) - 1] = X_MARKET_CYCLE_HIND; + + // + int result = ArraySize(cycles); + + // + return result; +} + +// +// END Market Cycles ... +// + +// +// START Week Days ... +// + +// +// Week Days ... +enum ENUM_X_WEEK_DAYS +{ + X_WEEK_DAY_NONE = -1, // None + X_WEEK_DAY_SUNDAY = 0, // Sunday + X_WEEK_DAY_MONDAY = 1, // Monday + X_WEEK_DAY_TUESDAY = 2, // Tuesday + X_WEEK_DAY_WEDNESDAY = 3, // Wednesday + X_WEEK_DAY_THURSDAY = 4, // Thursday + X_WEEK_DAY_FRIDAY = 5, // Friday + X_WEEK_DAY_SATURDAY = 6, // Saturday +}; + +// +// Extensions ... + +/** + * Validate ... + * + * @param value: ENUM_X_WEEK_DAYS member ... + * + * @return ( bool ) + */ +bool IsValid(ENUM_X_WEEK_DAYS value) +{ + // + bool result = false; + + // + result = + // + value != NULL && + value != X_WEEK_DAY_NONE + // + ; + + // + return result; +} + +/** + * Converts To String ... + * + * @param value: ENUM_X_WEEK_DAYS member ... + * + * @return ( string ) + */ +string ToString(ENUM_X_WEEK_DAYS value) +{ + // + string result = NULL; + + // + switch (value) + { + // + case X_WEEK_DAY_NONE: + result = "None"; + break; + + // + case X_WEEK_DAY_SUNDAY: + result = "Sunday"; + break; + + // + case X_WEEK_DAY_MONDAY: + result = "Monday"; + break; + + // + case X_WEEK_DAY_TUESDAY: + result = "Tuesday"; + break; + + // + case X_WEEK_DAY_WEDNESDAY: + result = "Wednesday"; + break; + + // + case X_WEEK_DAY_THURSDAY: + result = "Thursday"; + break; + + // + case X_WEEK_DAY_FRIDAY: + result = "Friday"; + break; + + // + case X_WEEK_DAY_SATURDAY: + result = "Saturday"; + break; + } + + // + return result; +} + +// +// END Week Days ... +// + +// +// START Ma Methods ... +// + +// +// Ma Methods ... +enum ENUM_X_MA_METHOD +{ + X_MA_MODE_NONE, // None + X_MA_MODE_SMA, // SMA + X_MA_MODE_EMA, // EMA + X_MA_MODE_LWMA, // LWMA + X_MA_MODE_SMMA, // SMMA +}; + +// +// Extensions ... + +/** + * Validate ... + * + * @param value: ENUM_X_MA_METHOD member ... + * + * @return ( bool ) + */ +bool IsValid(ENUM_X_MA_METHOD value) +{ + // + bool result = false; + + // + result = + // + value != NULL && + value != X_MA_MODE_NONE + // + ; + + // + return result; +} + +/** + * Converts To String ... + * + * @param value: ENUM_X_MA_METHOD member ... + * + * @return ( string ) + */ +string ToString(ENUM_X_MA_METHOD value) +{ + // + string result = NULL; + + // + switch (value) + { + // + case X_MA_MODE_NONE: + result = "None"; + break; + + // + case X_MA_MODE_SMA: + result = "SMA"; + break; + + // + case X_MA_MODE_EMA: + result = "EMA"; + break; + + // + case X_MA_MODE_LWMA: + result = "LWMA"; + break; + + // + case X_MA_MODE_SMMA: + result = "SMMA"; + break; + } + + // + return result; +} + +// +// END Ma Methods ... +// + +// \ No newline at end of file diff --git a/BKPS/14040203/Libraries/x-saherelm.x-ohcl.lib.mq5 b/BKPS/14040203/Libraries/x-saherelm.x-ohcl.lib.mq5 new file mode 100644 index 0000000..943f9d7 --- /dev/null +++ b/BKPS/14040203/Libraries/x-saherelm.x-ohcl.lib.mq5 @@ -0,0 +1,2003 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Common Library +// -------------------------------------- +// Name: XOHCLLib +// 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 + +// +#include "../Libraries/x-saherelm.common.extensions.lib.mq5" + +// +// Describe an Specific Candle ... +struct XOHCL +{ + // + // Props ... + + // + double high; + double open; + double close; + double low; + long volume; + double spread; + + // + string symbol; + datetime time; + ENUM_TIMEFRAMES period; + + // + // Constructor ... + XOHCL() + { + Clean(); + } + + // + // Init a Bar ... + // Using Bar Index ... + bool Init( + string mSymbol = NULL, // Trading Symbol + ENUM_TIMEFRAMES mPeriod = NULL, // Trading Period + int barIndex = 0 // Bar Index + ) + { + // + mSymbol = NormalizeSymbol(mSymbol); + mPeriod = NormalizePeriod(mPeriod); + + // + symbol = mSymbol; + period = mPeriod; + + // + time = iTime( + mSymbol, + mPeriod, + barIndex // + ); + + // + open = iOpen( + mSymbol, + mPeriod, + barIndex // + ); + open = NormalizePrice(open, mSymbol); + + // + close = iClose( + mSymbol, + mPeriod, + barIndex // + ); + close = NormalizePrice(close, mSymbol); + + // + high = iHigh( + mSymbol, + mPeriod, + barIndex // + ); + high = NormalizePrice(high, mSymbol); + + // + low = iLow( + mSymbol, + mPeriod, + barIndex // + ); + low = NormalizePrice(low, mSymbol); + + // + spread = iSpread( + mSymbol, + mPeriod, + barIndex // + ); + spread = NormalizePrice(spread, mSymbol); + + // + volume = iTickVolume( + mSymbol, + mPeriod, + barIndex // + ); + + // + bool result = IsValid(); + + // + return result; + } + + // + // Init a Bar ... + // Using Bar Time ... + bool Init( + string mSymbol = NULL, // Trading Symbol + ENUM_TIMEFRAMES mPeriod = NULL, // Trading Period + datetime mTime = NULL // Bar Time + ) + { + // + mTime = NormalizeTime(mTime); + + // + int barIndex = iBarShift( + mSymbol, + mPeriod, + mTime, + false // + ); + + // + bool result = Init( + mSymbol, + mPeriod, + barIndex + // + ); + + // + return result; + } + + // + // Tools ... + + // + void Clean() + { + // + low = 0; + high = 0; + open = 0; + close = 0; + spread = 0; + volume = 0; + + // + time = NULL; + symbol = NULL; + period = NULL; + + // + ZeroMemory(this); + } + + // + // Validate Bar ... + bool IsValid() + { + // + bool result = false; + + // + result = + // + low > 0 && + high > 0 && + open > 0 && + close > 0 && + spread > 0 && + volume > 0 + // + ; + + // + return result; + } + + // + int TotalBars() + { + // + int result = 0; + + // + result = iBars( + symbol, + period // + ); + + // + return result; + } + + // + // Calculate X_PRICE Specified Type ... + double GetPrice(ENUM_X_PRICE mPType) + { + // + double result = 0; + + // + if (!IsValid()) + { + return result; + } + + // + return GetAppliedPrice( + mPType, + open, + high, + low, + close // + ); + } + + // + // Retrieve Price base On Series Mode ... + double GetPrice(ENUM_SERIESMODE mMode) + { + // + ENUM_X_PRICE mType = ToXPrice(mMode); + + // + return GetPrice(mType); + } + + // + // Calculate Applied Price ... + double GetPrice(ENUM_APPLIED_PRICE mPType) + { + // + ENUM_X_PRICE mType = ToXPrice(mPType); + + // + return GetPrice(mType); + } + + // + // Find Specific Price ... + bool FindHigherPriceBar( + XOHCL &bar, + double price, + ENUM_X_PRICE _type = X_PRICE_HIGH // + ) + { + // + bool result = false; + + // + result = IsValid(); + if (!result) + { + return result; + } + + // + int totalBars = TotalBars(); + result = IsValidSize(totalBars); + if (!result) + { + return result; + } + + // + int start = Index(); + int maxAllowedLoopback = totalBars / 5; + for (int i = start; i < maxAllowedLoopback; i++) + { + // + result = bar.Init( + symbol, + period, + i // + ); + + // + if (!result) + { + break; + } + + // + double iPrice = bar.GetPrice(_type); + + // + result = + // + iPrice > 0 && + iPrice > price + // + ; + if (result) + { + break; + } + } + + // + if (!result) + { + bar.Clean(); + } + + // + return result; + } + + // + // Find Specific Price ... + bool FindLowerPriceBar( + XOHCL &bar, + double price, + ENUM_X_PRICE _type = X_PRICE_HIGH // + ) + { + // + bool result = false; + + // + result = IsValid(); + if (!result) + { + return result; + } + + // + int totalBars = TotalBars(); + result = IsValidSize(totalBars); + if (!result) + { + return result; + } + + // + int start = Index(); + int maxAllowedLoopback = totalBars / 5; + for (int i = start; i < maxAllowedLoopback; i++) + { + // + result = bar.Init( + symbol, + period, + i // + ); + + // + if (!result) + { + break; + } + + // + double iPrice = bar.GetPrice(_type); + + // + result = + // + iPrice > 0 && + iPrice < price + // + ; + if (result) + { + break; + } + } + + // + if (!result) + { + bar.Clean(); + } + + // + return result; + } + + // + // Calculate up Price ... + double GetUp() + { + // + double result = 0; + + // + if (!IsValid()) + { + return result; + } + + // + result = MathMax(open, close); + + // + return result; + } + + // + // Calculate Down Price ... + double GetDown() + { + // + double result = 0; + + // + if (!IsValid()) + { + return result; + } + + // + result = MathMin(open, close); + + // + return result; + } + + // + // Calculate Bar Body ... + double GetBody() + { + // + double result = 0; + + // + if (!IsValid()) + { + return result; + } + + // + result = GetUp() - GetDown(); + + // + return result; + } + + // + // Calculate Bar Range ... + double GetRange() + { + // + double result = 0; + + // + if (!IsValid()) + { + return result; + } + + // + result = high - low; + + // + return result; + } + + // + // Calculate Bar Shadows ... + double GetShadows() + { + // + double result = 0; + + // + if (!IsValid()) + { + return result; + } + + // + result = GetRange() - GetBody(); + + // + return result; + } + + // + // Calculate Bar High Shadow ... + double GetHighShadow() + { + // + double result = 0; + + // + if (!IsValid()) + { + return result; + } + + // + result = + // + high - GetUp() + // + ; + + // + return result; + } + + // + // Calculate Bar Low Shadow ... + double GetLowShadow() + { + // + double result = 0; + + // + if (!IsValid()) + { + return result; + } + + // + result = + // + GetDown() - low; + // + ; + + // + return result; + } + + // + // Check Bar is Bullish ... + bool IsBullish() + { + // + bool result = false; + + // + if (!IsValid()) + { + return result; + } + + // + result = open < close; + + // + return result; + } + + // + // Check Bar is Bearish ... + bool IsBearish() + { + // + bool result = false; + + // + if (!IsValid()) + { + return result; + } + + // + result = open > close; + + // + return result; + } + + // + // Get Direction of Bar ... + ENUM_X_DIRECTION GetDirection() + { + // + ENUM_X_DIRECTION result = X_DIRECTION_NONE; + + // + bool isBullish = IsBullish(); + bool isBearish = IsBearish(); + + // + result = + isBullish && isBearish + ? X_DIRECTION_ALL + : !isBullish && !isBearish + ? X_DIRECTION_NONE + : isBullish + ? X_DIRECTION_BULLISH + : X_DIRECTION_BEARISH; + + // + return result; + } + + // + // Find Next Bar Time ... + datetime NextAt() + { + // + datetime result = NULL; + + // + if (!IsValid()) + { + return result; + } + + // + int prSeconds = PeriodSeconds(period); + + // + result = time + prSeconds; + + // + return result; + } + + // + // Find Prev Bar Time ... + datetime BeforeOn() + { + // + datetime result = NULL; + + // + if (!IsValid()) + { + return result; + } + + // + int prSeconds = PeriodSeconds(period); + + // + result = time - prSeconds; + + // + return result; + } + + // + // Calculate Last Bar Open Time in Smaller Period ... + datetime GetLastBarTimeOfPeriod( + ENUM_TIMEFRAMES smallerPeriod // + ) + { + // + datetime result = NULL; + + // + if (!IsValid()) + { + return result; + } + + // + int sourceSeconds = PeriodSeconds(period); + int destSeconds = PeriodSeconds(smallerPeriod); + if (destSeconds >= sourceSeconds) + { + // + result = time; + return result; + } + + // + result = (datetime)((((int)time) + sourceSeconds) - destSeconds); + + // + return result; + } + + // + // Calculate Close Time ... + datetime GetCloseTime() + { + // + datetime result = NULL; + + // + if (!IsValid()) + { + return result; + } + + // + int seconds = PeriodSeconds(period); + + // + result = (datetime)(((int)time) + seconds); + + // + return result; + } + + // + bool BarAt( + int index, + XOHCL &bar // + ) + { + // + bool result = false; + + // + bar.Clean(); + + // + result = IsValid(); + if (!result) + { + return result; + } + + // + if (index < 0) + { + index = 0; + } + + // + result = bar.Init( + symbol, + period, + index // + ); + + // + return result; + } + + // + bool BarIn( + ENUM_TIMEFRAMES _period, + XOHCL &bar // + ) + { + // + bool result = false; + + // + bar.Clean(); + + // + result = IsValid() && + IsSpecifiedValid(_period); + if (!result) + { + return result; + } + + // + int index = Index(_period); + result = bar.Init( + symbol, + _period, + index // + ); + + // + return result; + } + + // + // Find Current Bar Index on Chart ... + int Index() + { + // + int result = -1; + + // + if (!IsValid()) + { + return result; + } + + // + result = iBarShift( + symbol, + period, + time + // + ); + + // + return result; + } + + // + int Index(datetime value) + { + // + int result = -1; + + // + value = NormalizeTime(value); + + // + result = IsValid(); + if (!result) + { + return result; + } + + // + result = iBarShift( + symbol, + period, + value // + ); + + // + return result; + } + + // + int Index(ENUM_TIMEFRAMES value) + { + // + int result = -1; + + // + result = IsValid() && + IsSpecifiedValid(value); + if (!result) + { + return result; + } + + // + result = iBarShift( + symbol, + value, + time // + ); + + // + return result; + } + + // + bool GetNextBar(XOHCL &bar) + { + // + bool result = false; + + // + result = IsValid(); + if (!result) + { + return result; + } + + // + int idx = Index(); + result = idx > 0; + if (!result) + { + return result; + } + + // + result = bar.Init( + this.symbol, + this.period, + idx - 1 // + ); + + // + if (!result) + { + bar.Clean(); + } + + // + return result; + } + + // + bool GetPreviousBar(XOHCL &bar) + { + // + bool result = false; + + // + result = IsValid(); + if (!result) + { + return result; + } + + // + int idx = Index(); + + // + result = bar.Init( + this.symbol, + this.period, + idx + 1 // + ); + + // + if (!result) + { + bar.Clean(); + } + + // + return result; + } + + // + bool HasFiboPressure( + ENUM_X_DIRECTION forDir, + ENUM_X_FIBO_LEVELS level = X_FIBO_LEVEL_382 // + ) + { + // + bool result = false; + + // + result = IsValid() && + HasDirection(forDir); + if (!result) + { + return result; + } + + // + bool isBullish = IsBullish(forDir); + bool isBearish = IsBearish(forDir); + + // + double fiboLevelValue = GetFibonacciLevel( + high, + low, + level, + forDir // + ); + + // + isBullish = + isBullish && + GetDown() > fiboLevelValue; + isBearish = + isBearish && + GetUp() < fiboLevelValue; + + // + result = isBullish || + isBearish; + + // + return result; + } + + // + bool IsRejected( + double price, + ENUM_X_DIRECTION forDir, + bool forceType = false, + bool forcePressure = false // + ) + { + // + bool result = false; + + // + result = IsValid() && + price > 0 && + HasDirection(forDir); + if (!result) + { + return result; + } + + // + bool isBullish = + IsBullish(forDir) && + low < price && + GetDown() > price; + + // + bool isBearish = + IsBearish(forDir) && + high > price && + GetUp() < price; + + // + if (forceType) + { + // + isBullish = + isBullish && + IsBullish(); + + // + isBearish = + isBearish && + IsBearish(); + } + + // + if (forcePressure) + { + // + isBullish = + isBullish && + HasFiboPressure(forDir); + + // + isBearish = + isBearish && + HasFiboPressure(forDir); + } + + // + result = isBullish || + isBearish; + + // + return result; + } + + // + bool IsBreaked( + double price, + ENUM_X_DIRECTION forDir // + ) + { + // + bool result = false; + + // + result = IsValid() && + price > 0 && + HasDirection(forDir); + if (!result) + { + return result; + } + + // + bool isBullish = + IsBullish() && + IsBullish(forDir) && + close > price && + open < price; + + // + bool isBearish = + IsBearish() && + IsBearish(forDir) && + close < price && + open > price; + + // + result = isBullish || + isBearish; + + // + return result; + } + + // + // Find Highest Bar Index ... + int FindHighestIndex( + int mLength, // Loopback ... + ENUM_SERIESMODE mMode // Calculation mode + ) + { + // + int result = -1; + + // + if (!IsValid()) + { + return result; + } + + // + if (mLength < 2) + { + mLength = 2; + } + + // + result = iHighest( + symbol, + period, + mMode, + mLength, + Index()); + + // + return result; + } + + // + // Find Highest ... + double FindHighest( + int mLength, // Loopback ... + ENUM_SERIESMODE mMode // Calculation mode + ) + { + // + double result = 0; + + // + if (!IsValid()) + { + return result; + } + + // + int idx = FindHighestIndex( + mLength, + mMode); + if (idx <= -1) + { + return result; + } + + // + XOHCL iH; + result = iH.Init( + symbol, + period, + idx + // + ); + if (!result) + { + return result; + } + + // + result = iH.GetPrice(mMode); + + // + return result; + } + + // + // Find Highest ... + double FindHighestUp( + int mLength // Loopback ... + ) + { + // + double result = 0; + + // + if (!IsValid()) + { + return result; + } + + // + result = FindHighest(mLength, MODE_OPEN); + result = MathMax(mLength, FindHighest(mLength, MODE_CLOSE)); + + // + return result; + } + + // + // Find Lowest Bar Index ... + int FindLowestIndex( + int mLength, // Loopback ... + ENUM_SERIESMODE mMode // Calculation mode + ) + { + // + int result = -1; + + // + if (!IsValid()) + { + return result; + } + + // + if (mLength < 2) + { + mLength = 2; + } + + // + result = iLowest( + symbol, + period, + mMode, + mLength, + Index()); + + // + return result; + } + + // + // Find Lowest ... + double FindLowest( + int mLength, // Loopback ... + ENUM_SERIESMODE mMode // Calculation mode + ) + { + // + double result = 0; + + // + if (!IsValid()) + { + return result; + } + + // + int idx = FindLowestIndex( + mLength, + mMode); + if (idx <= -1) + { + return result; + } + + // + XOHCL iL; + result = iL.Init( + symbol, + period, + idx + // + ); + if (!result) + { + return result; + } + + // + result = iL.GetPrice(mMode); + + // + return result; + } + + // + // Find Lowest ... + double FindLowesttDown( + int mLength // Loopback ... + ) + { + // + double result = 0; + + // + if (!IsValid()) + { + return result; + } + + // + result = FindLowest(mLength, MODE_OPEN); + result = MathMax(mLength, FindLowest(mLength, MODE_CLOSE)); + + // + return result; + } + + // + // Other ... + string GetTag(string prefix = "") + { + // + string result = NULL; + + // + result = + (IsValid(prefix) + ? prefix + "_" + : "") + + "XOHCL_" + symbol + "_" + ToString(period) + "_" + ToFormatString(time); + + // + return result; + } + + // + // Convert to String Representation ... + string ToString() + { + // + string result = ""; + + // + result = GetTypeName(this) + + "(O(" + ToString(open) + "),H(" + ToString(high) + "),C(" + ToString(close) + "),L(" + ToString(low) + "))"; + + // + return result; + } +}; + +// +// Models ... + +// +// Model a Bar Remains Time ... +struct XBarRemainsTime +{ + // + int days; + int hours; + int minutes; + int seconds; + + // + // Constructor ... + XBarRemainsTime() + { + Clean(); + } + + // + // Always Calculate Current 0 Bar Timing ... + bool Init( + string mSymbol = NULL, // Trading Symbol + ENUM_TIMEFRAMES mPeriod = NULL // Trading Period + ) + { + // + bool result = false; + + // + mSymbol = NormalizeSymbol(mSymbol); + mPeriod = NormalizePeriod(mPeriod); + + // + int minuteSecoonds = 60; + int hourSeconds = minuteSecoonds * 60; + int daySeconds = 24 * hourSeconds; + + // + int periodSeconds = PeriodSeconds( + mPeriod); + datetime startTime = GetBarTime( + mSymbol, + mPeriod, + 0 + // + ); + + // + int secondsDiff = (int)startTime + periodSeconds - (int)TimeCurrent(); + + // + int mWorkingSecondsDiff = secondsDiff; + if (mWorkingSecondsDiff > daySeconds) + { + // + days = mWorkingSecondsDiff / daySeconds; + mWorkingSecondsDiff -= days * daySeconds; + } + if (mWorkingSecondsDiff > hourSeconds) + { + // + hours = mWorkingSecondsDiff / hourSeconds; + mWorkingSecondsDiff -= hours * hourSeconds; + } + if (mWorkingSecondsDiff > minuteSecoonds) + { + // + minutes = mWorkingSecondsDiff / minuteSecoonds; + mWorkingSecondsDiff -= minutes * minuteSecoonds; + } + seconds = mWorkingSecondsDiff; + + // + result = true; + + // + return result; + } + + // + // Tools ... + + // + // Cleanup ... + void Clean() + { + days = 0; + hours = 0; + minutes = 0; + seconds = 0; + + // + ZeroMemory(this); + } + + // + // To String Representation ... + string ToString( + string dayId = "d", + string hourId = "h", + string minuteId = "m", + string secondId = "s", + string idSeparator = ": ", + string separator = ", ", + bool ignoreZeroValues = true + // + ) + { + // + string result = ""; + + // + // Days ... + if (!ignoreZeroValues || days > 0) + { + result += dayId + idSeparator + (string)days + separator; + } + + // + // Hours ... + if (!ignoreZeroValues || hours > 0) + { + // + string strHour = ToString(hours); + if (StringLen(strHour) == 1) + { + strHour = "0" + strHour; + } + + // + result += hourId + idSeparator + strHour + separator; + } + + // + // Minutes ... + if (!ignoreZeroValues || minutes > 0) + { + // + string strMinute = ToString(minutes); + if (StringLen(strMinute) == 1) + { + strMinute = "0" + strMinute; + } + + // + result += minuteId + idSeparator + strMinute + separator; + } + + // + // Seconds ... + if (!ignoreZeroValues || seconds > 0) + { + // + string strSec = ToString(seconds); + if (StringLen(strSec) == 1) + { + strSec = "0" + strSec; + } + + // + result += secondId + idSeparator + strSec; + } + + // + return result; + } +}; + +// +// Tracking Times ... +struct XTimeTracker +{ + // + // Props ... + int xMonth; + int xDayOfWeek; + int xForWeekDay; + int xDay; + int xHour; + int xMinute; + + // + // Constructor ... + XTimeTracker() + { + Clean(); + } + + // + // Tools ... + + // + void Clean() + { + // + xDay = -1; + xHour = -1; + xMonth = -1; + xMinute = -1; + xDayOfWeek = -1; + xForWeekDay = -1; + + // + ZeroMemory(this); + } + + // + // Detecting New Minute ... + bool IsNewMinute() + { + // + bool result = false; + + // + // Retrieve Current Time as Struct ... + MqlDateTime timeStruct = GetCurrentTime(); + + // + // Check Houre ... + result = timeStruct.min != xMinute; + if (result) + { + xMinute = timeStruct.min; + } + + // + return result; + } + + // + // Detecting New Houre ... + bool IsNewHour() + { + // + bool result = false; + + // + // Retrieve Current Time as Struct ... + MqlDateTime timeStruct = GetCurrentTime(); + + // + // Check Houre ... + result = timeStruct.hour != xHour; + if (result) + { + xHour = timeStruct.hour; + } + + // + return result; + } + + // + // Detecting New Day ... + bool IsNewDay() + { + // + bool result = false; + + // + // Retrieve Current Time as Struct ... + MqlDateTime timeStruct = GetCurrentTime(); + + // + // Check Houre ... + result = timeStruct.day_of_year != xDay; + if (result) + { + xDay = timeStruct.day_of_year; + } + + // + return result; + } + + // + // Detecting New Week ... + bool IsNewWeek() + { + // + bool result = false; + + // + // Retrieve Current Time as Struct ... + MqlDateTime timeStruct = GetCurrentTime(); + + // + // Check Week ... + // Since Week Starts From Monday in Forex World ... + // we Calculate Start of Week by 1-Monday ... + result = + xDayOfWeek == -1 && + xForWeekDay == -1 + ? true + : timeStruct.day_of_week == 1 && + timeStruct.day_of_year > xForWeekDay; + + // + xForWeekDay = timeStruct.day_of_year; + xDayOfWeek = timeStruct.day_of_week; + + // + return result; + } + + // + // Detecting End Of Week ... + bool IsWeekEnd() + { + // + bool result = false; + + // + // Retrieve Current Time as Struct ... + MqlDateTime timeStruct = GetCurrentTime(); + + // + // Check WeekEnd ... + // Since Week Starts From Monday in Forex World ... + // we Calculate End of Week by 5-Friday ... + result = + xDayOfWeek != -1 && + timeStruct.day_of_week == 5 && + timeStruct.hour == 23 && + timeStruct.min == 59 && + timeStruct.sec == 59; + + // + return result; + } + + // + // Detecting New Month ... + bool IsNewMonth() + { + // + bool result = false; + + // + // Retrieve Current Time as Struct ... + MqlDateTime timeStruct = GetCurrentTime(); + + // + // Check Houre ... + result = timeStruct.mon != xMonth; + if (result) + { + xMonth = timeStruct.mon; + } + + // + return result; + } +}; + +// +// Tracking Bars on Specified Environment ... +struct XBarTracker +{ + // + string symbol; // Tracking Symbol + ENUM_TIMEFRAMES period; // Tracking Time Frame + + // + int lastTrackedBar; // Last Tracked Bar ... + + // + bool waitsUntilNext; // Waits Until Next Bar ... + + // + // Constructor ... + XBarTracker() + { + Clean(); + } + + // + // Initializer ... + bool Init( + string mSymbol = NULL, // Trading Symbol + ENUM_TIMEFRAMES mPeriod = NULL // Trading Period + ) + { + // + bool result = false; + + // + mSymbol = NormalizeSymbol(mSymbol); + mPeriod = NormalizePeriod(mPeriod); + + // + this.symbol = mSymbol; + this.period = mPeriod; + + // + this.lastTrackedBar = 0; + + // + result = true; + + // + return result; + } + + // + // Retrieve all Bars ... + int CountBars() + { + // + return iBars( + symbol, + period + // + ); + } + + // + // Check if it's New Bar ... + bool IsNewBar() + { + // + bool result = false; + + // + int currentBars = CountBars(); + + // + result = currentBars > lastTrackedBar; + if (result) + { + lastTrackedBar = currentBars; + } + + // + return result; + } + + // + bool CanProcessBar() + { + // + bool _isInTestMode = IsRunningOnTestMode(); + + // + bool isNewBar = IsNewBar(); + + // + bool result = + _isInTestMode + ? isNewBar + : !waitsUntilNext + ? true + : isNewBar; + if (result && waitsUntilNext) + { + waitsUntilNext = false; + } + + // + return result; + } + + // + void Waits() + { + this.waitsUntilNext = true; + } + + // + // Tools ... + void Clean() + { + // + symbol = NormalizeSymbol(NULL); + period = NormalizePeriod(NULL); + + // + ZeroMemory(this); + } + + // + bool GetBar( + XOHCL &bar, + int index = 0 // + ) + { + // + bool result = false; + + // + result = bar.Init( + symbol, + period, + index // + ); + + // + return result; + } + + // + bool GetBar( + XOHCL &bar, + datetime time = NULL // + ) + { + // + bool result = false; + + // + NormalizeTime(time); + + // + int barIndex = iBarShift( + symbol, + period, + time, + false // + ); + + // + result = barIndex >= 0; + if (!result) + { + return result; + } + + // + result = bar.Init( + symbol, + period, + barIndex // + ); + + // + return result; + } + + // + int Index(datetime time = NULL) + { + // + int result = 0; + + // + NormalizeTime(time); + + // + result = iBarShift( + symbol, + period, + time, + false // + ); + + // + return result; + } +}; + +// +// Extensions ... + +// +// Extract Specific Range of Bars ... +// using Start Bar Index ... +int GetBars( + XOHCL &bars[], // Hold Result + string mSymbol = NULL, // Trading Symbol + ENUM_TIMEFRAMES mPeriod = NULL, // Trading Time Frame + int from = 0, // Start Bar Index + int count = 1 // Number of Bars +) +{ + // + int result = 0; + + // + from = NormalizeInt(from); + mSymbol = NormalizeSymbol(mSymbol); + mPeriod = NormalizePeriod(mPeriod); + + // + int total = Bars( + mSymbol, + mPeriod // + ); + if (from > total - 2) + { + from = total - 2; + } + + // + if (count < 0) + { + count = 1; + } + + // + int start = from; + int end = start + count; + if (end > total - 1) + { + end = total - 1; + } + + // + Clean(bars); + + // + for (int i = start; i < end; i++) + { + // + XOHCL iBar; + bool isValid = iBar.Init( + mSymbol, + mPeriod, + i // + ); + + // + if (isValid) + { + // + AddRef( + iBar, + bars // + ); + } + } + + // + result = ArraySize(bars); + + // + return result; +} + +// +// Extract Specific Range of Bars ... +// using Start Bar Time ... +int GetBars( + XOHCL &bars[], // Hold Result + string mSymbol = NULL, // Trading Symbol + ENUM_TIMEFRAMES mPeriod = NULL, // Trading Time Frame + datetime from = NULL, // Start Bar Time + int count = 1 // Number of Bars +) +{ + // + from = NormalizeTime(from); + mSymbol = NormalizeSymbol(mSymbol); + mPeriod = NormalizePeriod(mPeriod); + + // + int barIndex = GetBarIndex( + mSymbol, + mPeriod, + from // + ); + + // + return GetBars( + bars, + mSymbol, + mPeriod, + barIndex, + count // + ); +} + +// \ No newline at end of file diff --git a/BKPS/14040203/Libraries/x-saherelm.x-poi.extensions.lib.mq5 b/BKPS/14040203/Libraries/x-saherelm.x-poi.extensions.lib.mq5 new file mode 100644 index 0000000..9faf9f9 --- /dev/null +++ b/BKPS/14040203/Libraries/x-saherelm.x-poi.extensions.lib.mq5 @@ -0,0 +1,3471 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Seriallize Library +// --------------------------------------- +// Name: XPOILib +// Description: All models related to POIs ... +// +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +////////////////////////////////////////////////////// +// +// Global Properties ... +#property library +#property copyright "Copyright `023, SaherElm IT Center" +#property link "https://www.saherelm.ir" +#property version "1.00" +#property strict + +// +// Imports ... +#include "../Libraries/x-saherelm.x-poi.lib.mq5" + +// +// Extensions ... + +template +bool ToZone( + T *&source[], + XCZone *&dest[] // +) +{ + // + bool result = false; + + // + Clean(dest); + + // + int count = ArraySize(source); + result = IsValidSize(count); + if (!result) + { + return result; + } + + // + for (int i = 0; i < count; i++) + { + // + T *item = source[i]; + + // + if (item != NULL) + { + // + Add( + (XCZone *)item, + dest // + ); + } + } + + // + int destCount = ArraySize(dest); + result = IsValidSize(destCount); + + // + return result; +} + +template +bool ToBox( + T *&source[], + XBoxZone &dest[] // +) +{ + // + bool result = false; + + // + Clean(dest); + + // + int count = ArraySize(source); + result = IsValidSize(count); + if (!result) + { + return result; + } + + // + for (int i = 0; i < count; i++) + { + // + T *item = source[i]; + + // + if (item != NULL) + { + // + XBoxZone iBox; + bool hasBox = ToBox( + iBox, + item // + ); + + // + if (hasBox) + { + // + AddRef( + iBox, + dest // + ); + } + } + } + + // + int destCount = ArraySize(dest); + result = IsValidSize(destCount); + + // + return result; +} + +template +int GetOldest( + T *&source[] // +) +{ + // + int result = -1; + + // + int count = ArraySize(source); + if (!IsValidSize(count)) + { + return result; + } + + // + XBoxZone boxes[]; + bool isConverted = ToBox( + source, + boxes // + ); + if (!isConverted) + { + return result; + } + + // + int boxesCount = ArraySize(boxes); + + // + if (count != boxesCount) + { + return result; + } + + // + result = GetOldest(boxes); + + // + Clean(boxes); + + // + return result; +} + +template +int GetYoungest( + T *&source[] // +) +{ + // + int result = -1; + + // + int count = ArraySize(source); + if (!IsValidSize(count)) + { + return result; + } + + // + XBoxZone boxes[]; + bool isConverted = ToBox( + source, + boxes // + ); + if (!isConverted) + { + return result; + } + + // + int boxesCount = ArraySize(boxes); + + // + if (count != boxesCount) + { + return result; + } + + // + result = GetYoungest(boxes); + + // + Clean(boxes); + + // + return result; +} + +template +int GetLowest( + T *&source[] // +) +{ + // + int result = -1; + + // + int count = ArraySize(source); + if (!IsValidSize(count)) + { + return result; + } + + // + XBoxZone boxes[]; + bool isConverted = ToBox( + source, + boxes // + ); + if (!isConverted) + { + return result; + } + + // + int boxesCount = ArraySize(boxes); + + // + if (count != boxesCount) + { + return result; + } + + // + result = GetLowest(boxes); + + // + Clean(boxes); + + // + return result; +} + +template +int GetHighest( + T *&source[] // +) +{ + // + int result = -1; + + // + int count = ArraySize(source); + if (!IsValidSize(count)) + { + return result; + } + + // + XBoxZone boxes[]; + bool isConverted = ToBox( + source, + boxes // + ); + if (!isConverted) + { + return result; + } + + // + int boxesCount = ArraySize(boxes); + + // + if (count != boxesCount) + { + return result; + } + + // + result = GetHighest(boxes); + + // + Clean(boxes); + + // + return result; +} + +template +bool IsSame( + T *source, + T *dest // +) +{ + // + bool result = false; + + // + XBoxZone sourceBox; + result = ToBox( + sourceBox, + source // + ); + if (!result) + { + return result; + } + + // + XBoxZone destBox; + result = ToBox( + destBox, + dest // + ); + if (!result) + { + return result; + } + + // + result = sourceBox.IsSameAs(destBox); + + // + return result; +} + +template +bool IsSameDiff( + T *source, + F *dest // +) +{ + // + bool result = false; + + // + XBoxZone sourceBox; + result = ToBox( + sourceBox, + source // + ); + if (!result) + { + return result; + } + + // + XBoxZone destBox; + result = ToBox( + destBox, + dest // + ); + if (!result) + { + return result; + } + + // + result = sourceBox.IsSame(destBox); + + // + return result; +} + +template +bool IsBelow( + T *source, + T *dest, + bool ignoreInside = false // +) +{ + // + bool result = false; + + // + XBoxZone sourceBox; + result = ToBox( + sourceBox, + source // + ); + if (!result) + { + return result; + } + + // + XBoxZone destBox; + result = ToBox( + destBox, + dest // + ); + if (!result) + { + return result; + } + + // + result = IsBoxBelow( + sourceBox, + destBox, + ignoreInside // + ); + + // + return result; +} + +template +bool IsBelowDiff( + T *source, + F *dest, + bool ignoreInside = false // +) +{ + // + bool result = false; + + // + XBoxZone sourceBox; + result = ToBox( + sourceBox, + source // + ); + if (!result) + { + return result; + } + + // + XBoxZone destBox; + result = ToBox( + destBox, + dest // + ); + if (!result) + { + return result; + } + + // + result = IsBoxBelow( + sourceBox, + destBox, + ignoreInside // + ); + + // + return result; +} + +template +bool IsAbove( + T *source, + T *dest, + bool ignoreInside = false // +) +{ + // + bool result = false; + + // + XBoxZone sourceBox; + result = ToBox( + sourceBox, + source // + ); + if (!result) + { + return result; + } + + // + XBoxZone destBox; + result = ToBox( + destBox, + dest // + ); + if (!result) + { + return result; + } + + // + result = IsBoxAbove( + sourceBox, + destBox, + ignoreInside // + ); + + // + return result; +} + +template +bool IsAboveDiff( + T *source, + F *dest, + bool ignoreInside = false // +) +{ + // + bool result = false; + + // + XBoxZone sourceBox; + result = ToBox( + sourceBox, + source // + ); + if (!result) + { + return result; + } + + // + XBoxZone destBox; + result = ToBox( + destBox, + dest // + ); + if (!result) + { + return result; + } + + // + result = IsBoxAbove( + sourceBox, + destBox, + ignoreInside // + ); + + // + return result; +} + +template +bool IsInside( + T *source, + T *dest // +) +{ + // + bool result = false; + + // + XBoxZone sourceBox; + result = ToBox( + sourceBox, + source // + ); + if (!result) + { + return result; + } + + // + XBoxZone destBox; + result = ToBox( + destBox, + dest // + ); + if (!result) + { + return result; + } + + // + result = IsBoxInside( + sourceBox, + destBox // + ); + + // + return result; +} + +template +bool IsInsideOr( + T *source, + T *dest // +) +{ + // + bool result = false; + + // + XBoxZone sourceBox; + result = ToBox( + sourceBox, + source // + ); + if (!result) + { + return result; + } + + // + XBoxZone destBox; + result = ToBox( + destBox, + dest // + ); + if (!result) + { + return result; + } + + // + result = IsBoxInsideOr( + sourceBox, + destBox // + ); + + // + return result; +} + +template +bool IsInsideDiff( + T *source, + F *dest, + bool forceSideOut = false // +) +{ + // + bool result = false; + + // + XBoxZone sourceBox; + result = ToBox( + sourceBox, + source // + ); + if (!result) + { + return result; + } + + // + XBoxZone destBox; + result = ToBox( + destBox, + dest // + ); + if (!result) + { + return result; + } + + // + result = IsBoxInside( + sourceBox, + destBox, + forceSideOut // + ); + + // + return result; +} + +template +bool IsInsideOrDiff( + T *source, + F *dest, + bool forceSideOut = false // +) +{ + // + bool result = false; + + // + XBoxZone sourceBox; + result = ToBox( + sourceBox, + source // + ); + if (!result) + { + return result; + } + + // + XBoxZone destBox; + result = ToBox( + destBox, + dest // + ); + if (!result) + { + return result; + } + + // + result = IsBoxInsideOr( + sourceBox, + destBox // + ); + + // + return result; +} + +template +bool FindIndex( + int &index, + T *item, + T *&items[] // +) +{ + // + bool result = false; + + // + index = -1; + + // + XBoxZone itemBox; + result = ToBox( + itemBox, + item // + ); + if (!result) + { + return result; + } + + // + XBoxZone itemsBox[]; + result = ToBox( + items, + itemsBox // + ); + if (!result) + { + return result; + } + + // + result = FindBoxIndex( + index, + itemBox, + itemsBox // + ); + + // + return result; +} + +template +bool IsInside( + double value, + T *source // +) +{ + // + bool result = false; + + // + XBoxZone sourceBox; + result = ToBox( + sourceBox, + source // + ); + if (!result) + { + return result; + } + + // + result = IsInsideBox( + value, + sourceBox // + ); + + // + return result; +} + +template +bool IsAbove( + double value, + T *source // +) +{ + // + bool result = false; + + // + XBoxZone sourceBox; + result = ToBox( + sourceBox, + source // + ); + if (!result) + { + return result; + } + + // + result = IsAboveBox( + value, + sourceBox // + ); + + // + return result; +} + +template +bool IsBelow( + double value, + T *source // +) +{ + // + bool result = false; + + // + XBoxZone sourceBox; + result = ToBox( + sourceBox, + source // + ); + if (!result) + { + return result; + } + + // + result = IsBelowBox( + value, + sourceBox // + ); + + // + return result; +} + +/** + * Find Specified Box Index inside a Collection of Boxes ... + * + * @param box: XBoxZone instance Reference ... + * @param boxes: XBoxZone instance Reference Collection ... + * + * @return ( int ) + */ +bool FindBoxIndex( + int &index, + XBoxZone &box, + XBoxZone &boxes[] // +) +{ + // + bool result = false; + + // + index = -1; + + // + int count = ArraySize(boxes); + result = box.IsValid() && + IsValidSize(count); + if (!result) + { + return result; + } + + // + for (int i = 0; i < count; i++) + { + // + XBoxZone iBox = boxes[i]; + + // + bool isSame = box.IsSameAs(iBox); + if (isSame) + { + // + index = i; + break; + } + } + + // + result = IsValidIndex(index); + + // + return result; +} + +/** + * Check Source Box is Below Dest ... + * + * @param source: XBoxZone instance Reference ... + * @param dest: XBoxZone instance Reference ... + * @param ignoreInside: bool ... + * + * @return ( bool ) + */ +bool IsBoxBelow( + XBoxZone &source, + XBoxZone &dest, + bool ignoreInside = false // +) +{ + // + bool result = false; + + // + result = source.IsValid() && + dest.IsValid() && + !source.IsSameAs(dest); + if (!result) + { + return result; + } + + // + if (!ignoreInside) + { + result = source.upper < dest.lower; + } + else + { + result = (source.upper < dest.lower || + source.upper >= dest.upper) && + source.lower < dest.lower; + } + + // + return result; +} + +/** + * Check Source Box is Above Dest ... + * + * @param source: XBoxZone instance Reference ... + * @param dest: XBoxZone instance Reference ... + * @param ignoreInside: bool ... + * + * @return ( bool ) + */ +bool IsBoxAbove( + XBoxZone &source, + XBoxZone &dest, + bool ignoreInside = false // +) +{ + // + bool result = false; + + // + result = source.IsValid() && + dest.IsValid() && + !source.IsSameAs(dest); + if (!result) + { + return result; + } + + // + if (!ignoreInside) + { + result = source.lower > dest.upper; + } + else + { + result = (source.lower > dest.upper || + source.lower <= dest.upper) && + source.upper > dest.upper; + } + + // + return result; +} + +/** + * Check Source Box is Inside Dest ... + * + * @param source: XBoxZone instance Reference ... + * @param dest: XBoxZone instance Reference ... + * @param forceSideOut: bool, force check Box has One Side Out ... + * @param ignoreSideOut: bool, Accept if source Box one Side is out of Dest Box ... + * + * @return ( bool ) + */ +bool IsBoxInside( + XBoxZone &source, + XBoxZone &dest, + bool forceSideOut = false, // + bool ignoreSideOut = true // +) +{ + // + bool result = false; + + // + result = source.IsValid() && + dest.IsValid() && + !source.IsSameAs(dest); + if (!result) + { + return result; + } + + // + bool isBullish = IsBullish(dest.dir); + + // + if (!forceSideOut) + { + // + if (ignoreSideOut) + { + // + result = source.lower >= dest.lower && + source.upper <= dest.upper; + } + else + { + result = source.lower >= dest.lower || + source.upper <= dest.upper; + } + } + else + { + // + bool hasSideIn = + isBullish + ? source.lower >= dest.lower + : source.upper <= dest.upper; + bool hasSideOut = + isBullish + ? source.upper >= dest.upper + : source.lower <= dest.lower; + result = + hasSideIn && + hasSideOut; + } + + // + return result; +} + +/** + * Detect source BoX is Inside Dest Box or Have a Side Out on it ... + * + * @param source: XBoxZone instance, source box which checks by dest ... + * @param dest: XBoxZone instance, dest Box which compares source with it ... + * + * @return ( bool ) + */ +bool IsBoxInsideOr( + XBoxZone &source, + XBoxZone &dest, + bool forceInside = false // +) +{ + // + bool result = false; + + // + result = source.IsValid() && + dest.IsValid() && + !source.IsSameAs(dest); + if (!result) + { + return result; + } + + // + bool isInside = + source.upper <= dest.upper && + source.upper >= dest.lower && + source.lower >= dest.lower && + source.lower <= dest.upper; + bool isUpperInside = + source.upper <= dest.upper && + source.upper >= dest.lower; + bool isLowerInside = + source.lower >= dest.lower && + source.lower <= dest.upper; + + // + result = + forceInside + ? isInside + : (isInside || + isLowerInside || + isUpperInside); + + // + return result; +} + +/** + * Check Value is Inside Specified Box ... + * + * @param value: double ... + * @param box: XCBozZone instance Reference ... + * + * @return ( bool ) + */ +bool IsInsideBox( + double value, + XBoxZone &box // +) +{ + // + bool result = false; + + // + result = value > 0 && + box.IsValid() && + value <= box.upper && + value >= box.lower; + + // + return result; +} + +/** + * Check Bar is Inside Specified Box ... + * + * @param bar: XOHCL instance reference, Specified Bar ... + * @param box: XCBozZone instance Reference ... + * + * @return ( bool ) + */ +bool IsInsideBox( + XOHCL &bar, + XBoxZone &box // +) +{ + // + bool result = false; + + // + // Validate Args ... + result = bar.IsValid() && + box.IsValid(); + if (!result) + { + return result; + } + + // + result = + bar.close <= box.upper && + bar.close >= box.lower; + + // + return result; +} + +/** + * Check Value is Above Specified Box ... + * + * @param value: double ... + * @param box: XCBozZone instance Reference ... + * + * @return ( bool ) + */ +bool IsAboveBox( + double value, + XBoxZone &box // +) +{ + // + bool result = false; + + // + result = value > 0 && + box.IsValid() && + value > box.upper; + + // + return result; +} + +/** + * Check Value is Below Specified Box ... + * + * @param value: double ... + * @param box: XCBozZone instance Reference ... + * + * @return ( bool ) + */ +bool IsBelowBox( + double value, + XBoxZone &box // +) +{ + // + bool result = false; + + // + result = value > 0 && + box.IsValid() && + value < box.lower; + + // + return result; +} + +/** + * Check a Box is Used or not ... + * + * @param box: XBoxZone instance Reference ... + * @param fromIndex: int ... + * @param toIndex: int + * @param forPeriod: Specified Period ... + * + * @return ( bool ) + */ +bool IsBoxUsed( + XBoxZone &box, + int fromIndex, + int toIndex = 0, + ENUM_TIMEFRAMES forPeriod = NULL // +) +{ + // + bool result = false; + + // + if (toIndex < 0) + { + toIndex = 0; + } + + // + result = + // + box.IsValid() && + fromIndex > 0 && + fromIndex > toIndex + // + ; + if (!result) + { + return result; + } + + // + if (!IsValid(forPeriod)) + { + forPeriod = box.period; + } + + // + ENUM_X_DIRECTION forDir = box.dir; + bool isBullish = IsBullish(forDir); + + // + bool isTouched = false; + for (int i = fromIndex; i >= toIndex; i--) + { + // + XOHCL iBar; + bool isInited = iBar.Init( + box.symbol, + forPeriod, + i // + ); + + // + isTouched = + isInited && + (isBullish + ? iBar.low > box.upper + : iBar.high < box.lower); + if (!isTouched) + { + continue; + } + + // + iBar.Clean(); + break; + } + + // + result = isTouched; + + // + return result; +} + +/** + * Validate Box ... + * + * @param box: XBoxZone instance ... + * @param barIndex: int, Current Bar Index ... + * @param forPeriod: Testing Period ... + * + * @return ( bool ) + */ +bool IsBoxValid( + XBoxZone &box, + int barIndex = 0, + ENUM_TIMEFRAMES forPeriod = NULL // +) +{ + // + bool result = false; + + // + result = box.IsValid(); + if (!result) + { + return result; + } + + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + if (!IsValid(forPeriod)) + { + forPeriod = box.period; + } + + // + int toIndex = iBarShift( + box.symbol, + forPeriod, + box.to // + ); + result = IsValidIndex(toIndex); + if (!result) + { + return result; + } + + // + XOHCL iBar; + bool isBullish = box.IsBullish(); + for (int i = barIndex; i < toIndex; i++) + { + // + result = iBar.Init( + box.symbol, + forPeriod, + i // + ); + if (!result) + { + break; + } + + // + result = + isBullish + ? iBar.low > box.upper + : iBar.high < box.lower; + if (!result) + { + break; + } + + // + iBar.Clean(); + } + + // + iBar.Clean(); + + // + return result; +} + +/** + * Check Box Breaked ... + * + * @param box: XBoxZone instance ... + * @param barIndex: int, Current Bar Index ... + * @param forPeriod: Testing Period ... + * + * @return ( bool ) + */ +bool IsBoxBreaked( + XBoxZone &box, + int barIndex = 0, + ENUM_TIMEFRAMES forPeriod = NULL // +) +{ + // + bool result = false; + + // + result = box.IsValid(); + if (!result) + { + return result; + } + + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + if (!IsValid(forPeriod)) + { + forPeriod = box.period; + } + + // + int toIndex = iBarShift( + box.symbol, + forPeriod, + box.to // + ); + result = IsValidIndex(toIndex); + if (!result) + { + return result; + } + + // + XOHCL iBar; + bool isBullish = box.IsBullish(); + for (int i = barIndex; i < toIndex; i++) + { + // + result = iBar.Init( + box.symbol, + forPeriod, + i // + ); + if (!result) + { + break; + } + + // + result = + isBullish + ? iBar.high < box.lower + : iBar.low > box.upper; + if (!result) + { + break; + } + + // + iBar.Clean(); + } + + // + iBar.Clean(); + + // + return result; +} + +/** + * Check a Box is Breaked or not ... + * + * @param box: XBoxZone instance Reference ... + * @param fromIndex: int ... + * @param toIndex: int + * @param forPeriod: Specified Period ... + * + * @return ( bool ) + */ +bool IsBoxBreaked( + XBoxZone &box, + int fromIndex, + int toIndex = 0, + ENUM_TIMEFRAMES forPeriod = NULL // +) +{ + // + bool result = false; + + // + if (toIndex < 0) + { + toIndex = 0; + } + + // + result = + // + box.IsValid() && + fromIndex > 0 && + fromIndex > toIndex + // + ; + if (!result) + { + return result; + } + + // + if (!IsValid(forPeriod)) + { + forPeriod = box.period; + } + + // + ENUM_X_DIRECTION forDir = box.dir; + bool isBullish = IsBullish(forDir); + + // + bool isBreaked = false; + for (int i = fromIndex; i >= toIndex; i--) + { + // + XOHCL iBar; + bool isInited = iBar.Init( + box.symbol, + forPeriod, + i // + ); + + // + isBreaked = + isInited && + (isBullish + ? iBar.high <= box.lower + : iBar.low >= box.upper); + if (!isBreaked) + { + continue; + } + + // + iBar.Clean(); + break; + } + + // + result = isBreaked; + + // + return result; +} + +/** + * Find an Inside Box of source in a Collection ... + * + * @param index: int, Founded Index ... + * @param source: XBoxZone instance ... + * @param dest: XBoxZone instance Collection ... + * + * @return ( bool ) + */ +bool HasInsideBox( + int &index, + XBoxZone &source, + XBoxZone &dest[] // +) +{ + // + bool result = false; + + // + index = -1; + + // + result = source.IsValid() && + HasChild(dest); + + // + int count = ArraySize(dest); + for (int i = 0; i < count; i++) + { + // + XBoxZone iBox = dest[i]; + + // + bool isInside = !iBox.IsSameAs(source) && + IsBoxInsideOr( + iBox, + source // + ); + if (isInside) + { + // + index = i; + iBox.Clean(); + + // + break; + } + + // + iBox.Clean(); + } + + // + result = IsValidIndex(index); + + // + return result; +} + +/** + * Converts to XBoxZone ... + * + * @return ( bool ) + */ +bool ToBox( + XBoxZone &box, + XCOrderBlock *item // +) +{ + // + bool result = false; + + // + box.Clean(); + + // + result = item != NULL && + item.IsValid(); + if (!result) + { + return result; + } + + // + box.to = item.To(); + box.from = item.From(); + box.upper = item.Upper(); + box.lower = item.Lower(); + box.symbol = item.GetSymbol(); + box.period = item.GetPeriod(); + box.type = item.TypeAsString(); + box.dir = item.IsBullish() + ? X_DIRECTION_BULLISH + : X_DIRECTION_BEARISH; + + // + result = box.IsValid(); + + // + return result; +} + +/** + * Converts to XBoxZone ... + * + * @return ( bool ) + */ +bool ToBox( + XBoxZone &box, + XCFVG *item // +) +{ + // + bool result = false; + + // + box.Clean(); + + // + result = item != NULL && + item.IsValid(); + if (!result) + { + return result; + } + + // + box.to = item.To(); + box.from = item.From(); + box.upper = item.Upper(); + box.lower = item.Lower(); + box.symbol = item.GetSymbol(); + box.period = item.GetPeriod(); + box.type = item.TypeAsString(); + box.dir = item.IsBullish() + ? X_DIRECTION_BULLISH + : X_DIRECTION_BEARISH; + + // + result = box.IsValid(); + + // + return result; +} + +/** + * Converts to XBoxZone ... + * + * @return ( bool ) + */ +bool ToBox( + XBoxZone &box, + XCSupportZone *item // +) +{ + // + bool result = false; + + // + box.Clean(); + + // + result = item != NULL && + item.IsValid(); + if (!result) + { + return result; + } + + // + box.to = item.To(); + box.from = item.From(); + box.upper = item.Upper(); + box.lower = item.Lower(); + box.symbol = item.GetSymbol(); + box.period = item.GetPeriod(); + box.type = item.TypeAsString(); + box.dir = X_DIRECTION_BULLISH; + + // + result = box.IsValid(); + + // + return result; +} + +/** + * Converts to XBoxZone ... + * + * @return ( bool ) + */ +bool ToBox( + XBoxZone &box, + XCResistanceZone *item // +) +{ + // + bool result = false; + + // + box.Clean(); + + // + result = item != NULL && + item.IsValid(); + if (!result) + { + return result; + } + + // + box.to = item.To(); + box.from = item.From(); + box.upper = item.Upper(); + box.lower = item.Lower(); + box.symbol = item.GetSymbol(); + box.period = item.GetPeriod(); + box.type = item.TypeAsString(); + box.dir = X_DIRECTION_BEARISH; + + // + result = box.IsValid(); + + // + return result; +} + +/** + * Converts to XBoxZone ... + * + * @return ( bool ) + */ +bool ToBox( + XBoxZone &box, + XCSupplyZone *item // +) +{ + // + bool result = false; + + // + box.Clean(); + + // + result = item != NULL && + item.IsValid(); + if (!result) + { + return result; + } + + // + box.to = item.To(); + box.from = item.From(); + box.upper = item.Upper(); + box.lower = item.Lower(); + box.symbol = item.GetSymbol(); + box.period = item.GetPeriod(); + box.type = item.TypeAsString(); + box.dir = X_DIRECTION_BEARISH; + + // + result = box.IsValid(); + + // + return result; +} + +/** + * Converts to XBoxZone ... + * + * @return ( bool ) + */ +bool ToBox( + XBoxZone &box, + XCDemandZone *item // +) +{ + // + bool result = false; + + // + box.Clean(); + + // + result = item != NULL && + item.IsValid(); + if (!result) + { + return result; + } + + // + box.to = item.To(); + box.from = item.From(); + box.upper = item.Upper(); + box.lower = item.Lower(); + box.symbol = item.GetSymbol(); + box.period = item.GetPeriod(); + box.type = item.TypeAsString(); + box.dir = X_DIRECTION_BULLISH; + + // + result = box.IsValid(); + + // + return result; +} + +/** + * Converts to XBoxZone ... + * + * @return ( bool ) + */ +bool ToBox( + XBoxZone &box, + XConsolidationZone &item // +) +{ + // + bool result = false; + + // + box.Clean(); + + // + result = item.IsValid(); + if (!result) + { + return result; + } + + // + box.to = item.to; + box.dir = item.dir; + box.from = item.from; + box.upper = item.upper; + box.lower = item.lower; + box.symbol = item.symbol; + box.period = item.period; + box.type = IsBullish(item.dir) + ? ToString(X_BULLISH_CONSOLIDATION_ZONE) + : ToString(X_BEARISH_CONSOLIDATION_ZONE); + + // + result = box.IsValid(); + + // + return result; +} + +/** + * Converts to XBoxZone ... + * + * @return ( bool ) + */ +int ToBox( + XConsolidationZone &source[], + XBoxZone &dest[] // +) +{ + // + int result = 0; + + // + Clean(dest); + int count = ArraySize(source); + if (!IsValidSize(count)) + { + return result; + } + + // + for (int i = 0; i < count; i++) + { + // + XConsolidationZone iZone = source[i]; + + // + XBoxZone iBox; + bool hasBox = ToBox( + iBox, + iZone // + ); + + // + if (hasBox) + { + // + AddRef( + iBox, + dest // + ); + } + + // + iBox.Clean(); + iZone.Clean(); + } + + // + result = ArraySize(dest); + + // + return result; +} + +/** + * Get Oldest Box Index ... + * + * @param source: XBoxZone instance Reference Collection ... + * + * @return ( int ) + */ +int GetOldest( + XBoxZone &source[] // +) +{ + // + int result = -1; + + // + int count = ArraySize(source); + if (!IsValidSize(count)) + { + return result; + } + + // + XBoxZone selected; + for (int i = 0; i < count; i++) + { + // + XBoxZone iBox = source[i]; + + // + bool canSet = + !selected.IsValid() + ? true + : selected.from > iBox.from; + if (canSet) + { + // + result = i; + selected = iBox; + } + } + + // + selected.Clean(); + + // + return result; +} + +/** + * Get Youngest Box Index ... + * + * @param source: XBoxZone instance Reference Collection ... + * + * @return ( int ) + */ +int GetYoungest( + XBoxZone &source[] // +) +{ + // + int result = -1; + + // + int count = ArraySize(source); + if (!IsValidSize(count)) + { + return result; + } + + // + XBoxZone selected; + for (int i = 0; i < count; i++) + { + // + XBoxZone iBox = source[i]; + + // + bool canSet = + !selected.IsValid() + ? true + : selected.from < iBox.from; + if (canSet) + { + // + result = i; + selected = iBox; + } + } + + // + selected.Clean(); + + // + return result; +} + +/** + * Get Highest Box Index ... + * + * @param source: XBoxZone instance Reference Collection ... + * + * @return ( int ) + */ +int GetHighest( + XBoxZone &source[] // +) +{ + // + int result = -1; + + // + int count = ArraySize(source); + if (!IsValidSize(count)) + { + return result; + } + + // + XBoxZone selected; + for (int i = 0; i < count; i++) + { + // + XBoxZone iBox = source[i]; + + // + bool canSet = + !selected.IsValid() + ? true + : selected.upper < iBox.upper; + if (canSet) + { + // + result = i; + selected = iBox; + } + } + + // + selected.Clean(); + + // + return result; +} + +/** + * Get Lowest Box Index ... + * + * @param source: XBoxZone instance Reference Collection ... + * + * @return ( int ) + */ +int GetLowest( + XBoxZone &source[] // +) +{ + // + int result = -1; + + // + int count = ArraySize(source); + if (!IsValidSize(count)) + { + return result; + } + + // + XBoxZone selected; + for (int i = 0; i < count; i++) + { + // + XBoxZone iBox = source[i]; + + // + bool canSet = + !selected.IsValid() + ? true + : selected.lower > iBox.lower; + if (canSet) + { + // + result = i; + selected = iBox; + } + } + + // + selected.Clean(); + + // + return result; +} + +// +// +// + +/** + * Get Oldest Index ... + * + * @param source: XConsolidationZone instance Reference Collection ... + * + * @return ( int ) + */ +int GetOldest( + XConsolidationZone &source[] // +) +{ + // + int result = -1; + + // + int count = ArraySize(source); + if (!IsValidSize(count)) + { + return result; + } + + // + XBoxZone tmpBoxes[]; + int boxesCount = ToBox( + source, + tmpBoxes // + ); + if (!IsValidSize(boxesCount)) + { + // + Clean(tmpBoxes); + return result; + } + + // + XBoxZone selected; + for (int i = 0; i < boxesCount; i++) + { + // + XBoxZone iBox = tmpBoxes[i]; + + // + bool canSet = + !selected.IsValid() + ? true + : selected.from > iBox.from; + if (canSet) + { + // + result = i; + selected = iBox; + } + } + + // + Clean(tmpBoxes); + selected.Clean(); + + // + return result; +} + +/** + * Get Youngest Index ... + * + * @param source: XConsolidationZone instance Reference Collection ... + * + * @return ( int ) + */ +int GetYoungest( + XConsolidationZone &source[] // +) +{ + // + int result = -1; + + // + int count = ArraySize(source); + if (!IsValidSize(count)) + { + return result; + } + + // + XBoxZone tmpBoxes[]; + int boxesCount = ToBox( + source, + tmpBoxes // + ); + if (!IsValidSize(boxesCount)) + { + // + Clean(tmpBoxes); + return result; + } + + // + XBoxZone selected; + for (int i = 0; i < boxesCount; i++) + { + // + XBoxZone iBox = tmpBoxes[i]; + + // + bool canSet = + !selected.IsValid() + ? true + : selected.from < iBox.from; + if (canSet) + { + // + result = i; + selected = iBox; + } + } + + // + Clean(tmpBoxes); + selected.Clean(); + + // + return result; +} + +/** + * Get Highest Index ... + * + * @param source: XConsolidationZone instance Reference Collection ... + * + * @return ( int ) + */ +int GetHighest( + XConsolidationZone &source[] // +) +{ + // + int result = -1; + + // + int count = ArraySize(source); + if (!IsValidSize(count)) + { + return result; + } + + // + XBoxZone tmpBoxes[]; + int boxesCount = ToBox( + source, + tmpBoxes // + ); + if (!IsValidSize(boxesCount)) + { + // + Clean(tmpBoxes); + return result; + } + + // + XBoxZone selected; + for (int i = 0; i < boxesCount; i++) + { + // + XBoxZone iBox = tmpBoxes[i]; + + // + bool canSet = + !selected.IsValid() + ? true + : selected.upper < iBox.upper; + if (canSet) + { + // + result = i; + selected = iBox; + } + } + + // + Clean(tmpBoxes); + selected.Clean(); + + // + return result; +} + +/** + * Get Lowest Index ... + * + * @param source: XConsolidationZone instance Reference Collection ... + * + * @return ( int ) + */ +int GetLowest( + XConsolidationZone &source[] // +) +{ + // + int result = -1; + + // + int count = ArraySize(source); + if (!IsValidSize(count)) + { + return result; + } + + // + XBoxZone tmpBoxes[]; + int boxesCount = ToBox( + source, + tmpBoxes // + ); + if (!IsValidSize(boxesCount)) + { + // + Clean(tmpBoxes); + return result; + } + + // + XBoxZone selected; + for (int i = 0; i < boxesCount; i++) + { + // + XBoxZone iBox = tmpBoxes[i]; + + // + bool canSet = + !selected.IsValid() + ? true + : selected.lower > iBox.lower; + if (canSet) + { + // + result = i; + selected = iBox; + } + } + + // + Clean(tmpBoxes); + selected.Clean(); + + // + return result; +} + +// +// +// + +// +template +void SortZones( + T *&source[], + ENUM_X_DIRECTION forDir, + bool ignoreInside = true // +) +{ + // + int idx = -1; + int count = 0; + bool has = false; + + // + has = HasDirection(forDir); + if (!has) + { + return; + } + + // + bool isBullish = IsBullish(forDir); + + // + count = ArraySize(source); + has = IsValidSize(count); + if (!has) + { + return; + } + + // + T *tmpItems[]; + T *last = NULL; + bool hasLast = false; + while (HasChild(source)) + { + // + if (!hasLast) + { + // + idx = GetOldest(source); + hasLast = IsValidIndex(idx); + if (hasLast) + { + // + last = source[idx]; + ArrayRemove( + source, + idx, + 1 // + ); + + // + Add( + last, + tmpItems // + ); + } + + // + count = ArraySize(source); + has = IsValidSize(count); + if (!has) + { + // + ZeroMemory(last); + break; + } + } + if (!hasLast) + { + // + ZeroMemory(last); + break; + } + + // + T *item = NULL; + idx = GetOldest(source); + has = IsValidIndex(idx); + if (!has) + { + // + ZeroMemory(last); + ZeroMemory(item); + break; + } + item = source[idx]; + ArrayRemove( + source, + idx, + 1 // + ); + + // + bool isAbove = IsAbove( + item, + last, + ignoreInside // + ); + + // + bool isBelow = IsBelow( + item, + last, + ignoreInside // + ); + + // + has = + isBullish + ? isAbove + : isBelow; + if (has) + { + // + Add( + item, + tmpItems // + ); + + // + last = item; + hasLast = item != NULL; + } + } + + // + Clean(source); + Copy( + tmpItems, + source // + ); + + // + Clean(tmpItems); +} + +/** + * Extract all Zones Which provided bar is Inside it ... + * + * @return ( int ) + */ +template +int ExtractInsideZones( + XOHCL &bar, // Bar ... + T *&zones[], // Source of Zones ... + T *&dest[] // Dest (all inside Zones) ... +) +{ + // + int result = 0; + + // + Clean(dest); + + // + int count = ArraySize(zones); + bool isValid = bar.IsValid() && + IsValidSize(count); + if (!isValid) + { + return result; + } + + // + for (int i = 0; i < count; i++) + { + // + T *iZone = zones[i]; + + // + bool isHighInside = IsInside( + bar.high, + iZone // + ); + + // + bool isLowInside = IsInside( + bar.low, + iZone // + ); + + // + bool isInside = + isLowInside && + isHighInside; + + // + if (isInside) + { + // + Add( + iZone, + dest // + ); + } + + // + ZeroMemory(iZone); + } + + // + result = ArraySize(dest); + + // + return result; +} + +/** + * Add Specific Item into a Collection Reference only if it's not Exists ... + * + * @return ( bool ) + */ +template +bool AddIfNotExists( + T *item, + T *&items[] // +) +{ + // + bool result = false; + + // + result = item != NULL; + if (!result) + { + return result; + } + + // + int before = ArraySize(items); + + // + int idx = FindIndex( + item, + items // + ); + bool has = IsValidIndex(idx); + result = !has; + if (!result) + { + return result; + } + + // + Add( + item, + items // + ); + + // + int after = ArraySize(items); + + // + result = after > before; + + // + return result; +} +bool AddIfNotExists( + XConsolidationZone &item, + XConsolidationZone &items[] // +) +{ + // + bool result = false; + + // + result = item.IsValid(); + if (!result) + { + return result; + } + + // + int before = ArraySize(items); + + // + int idx = FindIndex( + item, + items // + ); + bool has = IsValidIndex(idx); + result = !has; + if (!result) + { + return result; + } + + // + AddRef( + item, + items // + ); + + // + int after = ArraySize(items); + + // + result = after > before; + + // + return result; +} + +/** + * Add items Collection reference Members into source Collection only if it's not Exists ...alignas + * @return ( int ) + */ +template +int AddIfNotExists( + T *&items[], + T *&sources[] // +) +{ + // + int result = 0; + + // + bool has = HasChild(items); + if (!has) + { + return result; + } + + // + int before = ArraySize(sources); + + // + int count = ArraySize(items); + for (int i = 0; i < count; i++) + { + // + has = AddIfNotExists( + items[i], + sources // + ); + } + + // + int after = ArraySize(sources); + + // + result = after > before; + + // + return result; +} +int AddIfNotExists( + XConsolidationZone &items[], + XConsolidationZone &sources[] // +) +{ + // + int result = 0; + + // + bool has = HasChild(items); + if (!has) + { + return result; + } + + // + int before = ArraySize(sources); + + // + int count = ArraySize(items); + for (int i = 0; i < count; i++) + { + // + has = AddIfNotExists( + items[i], + sources // + ); + } + + // + int after = ArraySize(sources); + + // + result = after > before; + + // + return result; +} + +/** + * Update to Time of Specifiex Collection ... + * + * @param items: XOBFVG instance Collection ... + * @param value: datetime ... + */ +template +void SpecifiedUpdateTo( + T *&items[], + datetime value = NULL // +) +{ + // + value = NormalizeTime(value); + + // + int count = ArraySize(items); + bool has = HasChild(items); + if (!has) + { + return; + } + + // + for (int i = 0; i < count; i++) + { + items[i].To(value); + } +} + +// +template +int FilterZones( + // + T *&source[], + // + ENUM_X_DIRECTION forDir, + ENUM_TIMEFRAMES forPeriod = NULL, + datetime after = NULL, + // + // Start ... + ENUM_XZONE_STATE startState = XZONE_STATE_PASSED, + bool forceStartedBodyOut = false, + // + // Activation ... + ENUM_XZONE_STATE activeState = XZONE_STATE_FAILED, + bool forceActivatedBodyIn = false, + // + // Breaktion ... + ENUM_XZONE_STATE breakState = XZONE_STATE_FAILED, + bool forceBreakedBodyOut = false, + // + // Works ... + ENUM_XZONE_STATE workState = XZONE_STATE_FAILED, + bool forceWorkedBodyOut = false, + // + bool applySort = false, + // + bool ignoreInside = true + // +) +{ + // + int result = 0; + + // + int idx = -1; + int count = 0; + bool has = false; + + // + has = HasDirection(forDir); + if (!has) + { + return result; + } + + // + bool isBullish = IsBullish(forDir); + + // + count = ArraySize(source); + has = IsValidSize(count); + if (!has) + { + return result; + } + + // + T *tmpZones[]; + XOHCL passedBar; + bool isPassed = false; + for (int i = 0; i < count; i++) + { + // + T *iZone = source[i]; + + // + // Apply after Filter ... + isPassed = + !IsValid(after) + ? true + : iZone.From() >= after; + if (!isPassed) + { + // + ZeroMemory(iZone); + continue; + } + + // + // Check Started State ... + if (startState == XZONE_STATE_PASSED || + startState == XZONE_STATE_FAILED) + { + // + bool isBodyOut = false; + bool isStarted = iZone.IsStarted( + forDir, + passedBar, + isBodyOut, + forPeriod // + ); + + // + bool isPassed = + startState == XZONE_STATE_FAILED + ? !isStarted + : !forceStartedBodyOut + ? isStarted + : isStarted && + isBodyOut; + + // + passedBar.Clean(); + if (!isPassed) + { + continue; + } + } + + // + // Check Activation State ... + if (activeState == XZONE_STATE_PASSED || + activeState == XZONE_STATE_FAILED) + { + // + bool isBodyIn = false; + bool isActivated = iZone.IsActivated( + forDir, + passedBar, + isBodyIn, + forceStartedBodyOut, + forPeriod // + ); + + // + bool isPassed = + activeState == XZONE_STATE_FAILED + ? !isActivated + : !forceActivatedBodyIn + ? isActivated + : isActivated && + isBodyIn; + + // + passedBar.Clean(); + if (!isPassed) + { + continue; + } + } + + // + // Check Break State ... + if (breakState == XZONE_STATE_PASSED || + breakState == XZONE_STATE_FAILED) + { + // + bool isBodyOut = false; + bool isBreaked = iZone.IsBreaked( + forDir, + passedBar, + isBodyOut, + forceStartedBodyOut, + forPeriod // + ); + + // + bool isPassed = + breakState == XZONE_STATE_FAILED + ? !isBreaked + : !forceBreakedBodyOut + ? isBreaked + : isBreaked && + isBodyOut; + + // + passedBar.Clean(); + if (!isPassed) + { + continue; + } + } + + // + // Check Work State ... + if (workState == XZONE_STATE_PASSED || + workState == XZONE_STATE_FAILED) + { + // + bool ignoreActivation = activeState != XZONE_STATE_PASSED; + + // + bool isBodyOut = false; + bool isWorked = iZone.IsWorked( + forDir, + passedBar, + isBodyOut, + ignoreActivation, + forceStartedBodyOut, + forceActivatedBodyIn, + forPeriod // + ); + + // + bool isPassed = + workState == XZONE_STATE_FAILED + ? !isWorked + : !forceWorkedBodyOut + ? isWorked + : isWorked && + isBodyOut; + + // + passedBar.Clean(); + if (!isPassed) + { + continue; + } + } + + // + // Check Filtered Zone Doesn't Exists ... + has = FindIndex( + idx, + iZone, + tmpZones // + ); + if (has) + { + // + ZeroMemory(iZone); + passedBar.Clean(); + continue; + } + + // + Add( + iZone, + tmpZones // + ); + } + + // + Clean(source); + + // + has = HasChild(tmpZones); + if (!has) + { + // + Clean(tmpZones); + passedBar.Clean(); + return result; + } + + // + // Apply Sorting ... + if (applySort) + { + // + T *last = NULL; + bool hasLast = false; + while (HasChild(tmpZones)) + { + // + idx = GetYoungest(tmpZones); + hasLast = IsValidIndex(idx); + if (hasLast) + { + // + last = tmpZones[idx]; + ArrayRemove( + tmpZones, + idx, + 1 // + ); + + // + Add( + last, + source // + ); + } + + // + has = HasChild(tmpZones); + if (!has) + { + break; + } + + // + T *zone = NULL; + bool hasZone = false; + idx = GetYoungest(tmpZones); + hasZone = IsValidIndex(idx); + if (hasZone) + { + // + zone = tmpZones[idx]; + ArrayRemove( + tmpZones, + idx, + 1 // + ); + } + if (!hasZone) + { + // + ZeroMemory(zone); + continue; + } + + // + bool isAbove = IsAbove( + zone, + last, + ignoreInside // + ); + + // + bool isBelow = IsBelow( + zone, + last, + ignoreInside // + ); + + // + isPassed = + isBullish + ? isAbove + : isBelow; + if (!isPassed) + { + // + ZeroMemory(zone); + continue; + } + + // + Add( + zone, + source // + ); + } + } + else + { + // + Copy( + tmpZones, + source // + ); + } + + // + result = ArraySize(source); + + // + return result; +} + +// +// +// + +/** + * Detect Nearest Price Out of Specified Box ... + * + * @param box: XBoxZone instance Reference ... + * @param outSideBar: XOHCL instance Reference which Represents Out Side Bar if Exists ... + * @param forPeriod: ENUM_TIMEFRAMES member which provides time frame of Out Bar, if not Provides used box Period as Default ... + * @param forDir: ENUM_X_DIRECTION member which Specified outSide Direction, use Box Dir as Default ... + * @param forceBodyIn: bool value which Specifyed Body Breakes or not, Default is false ... + * @param barIndex: integer value which Specified Start Bar Index, Default is 0 ... + * + * @return ( bool ) + */ +bool DetectBoxNearestPriceOut( + XBoxZone &box, + XOHCL &outSideBar, + ENUM_TIMEFRAMES forPeriod = NULL, + ENUM_X_DIRECTION forDir = X_DIRECTION_NONE, + bool forceBodyIn = false, + int barIndex = 0 // +) +{ + // + bool result = false; + + // + outSideBar.Clean(); + + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + result = box.IsValid(); + if (!result) + { + return result; + } + + // + if (!IsValid(forPeriod)) + { + forPeriod = box.period; + } + + // + if (!HasDirection(forDir)) + { + forDir = box.dir; + } + + // + bool isBullish = IsBullish(forDir); + + // + int fromIndex = iBarShift( + box.symbol, + forPeriod, + box.from // + ); + result = IsValidIndex(fromIndex); + if (!result) + { + return result; + } + + // + XOHCL iBar; + XOHCL iPBar; + bool has = false; + for (int i = barIndex; i < fromIndex; i++) + { + // + has = iBar.Init( + box.symbol, + forPeriod, + i // + ); + if (!has) + { + continue; + } + + // + has = iBar.GetPreviousBar(iPBar); + if (!has) + { + continue; + } + + // + bool isInsideFromLower = + iBar.high < box.lower && + iPBar.high > box.lower; + + // + bool isInsideFromUpper = + iBar.low > box.upper && + iPBar.low < box.upper; + + // + bool isInsideBodyFromLower = + iPBar.GetUp() > box.lower; + + // + bool isInsideBodyFromUpper = + iPBar.GetDown() < box.upper; + + // + result = + isBullish + ? (!forceBodyIn + ? isInsideFromLower + : isInsideFromLower && + isInsideBodyFromLower) + : (!forceBodyIn + ? isInsideFromUpper + : isInsideFromUpper && + isInsideBodyFromUpper); + if (result) + { + // + outSideBar = iBar; + break; + } + } + + // + iBar.Clean(); + iPBar.Clean(); + + // + return result; +} + +/** + * Count number of Box Retests ... + * + * @param box: XBoxZone instance Reference ... + * @param forDir: ENUM_X_DIRECTION member, Specified Retesting Direction ... + * @param forPeriod: ENUM_TIMEFRAMES member, Specified Retesting Period ... + * @param forceType: bool, Specified Retest Bar Direction is Same as Retesting Direction ... + * @param forcePressure: bool, Specified Retest Bar must Has Fibo Pressure or not ... + * + * @return ( int ) + */ +int CountBoxRetest( + XBoxZone &box, + ENUM_X_DIRECTION forDir = NULL, + ENUM_TIMEFRAMES forPeriod = NULL, + bool forceType = false, + bool forcePressure = false // +) +{ + // + int result = 0; + + // + if (!IsValid(forPeriod)) + { + forPeriod = box.period; + } + + // + if (!IsValid(forDir)) + { + forDir = box.dir; + } + + // + bool isValid = + box.IsValid() && + IsValid(forDir); + if (!isValid) + { + return result; + } + + // + int fromIDX = GetBarIndex( + box.symbol, + forPeriod, + box.from // + ); + + // + int toIDX = GetBarIndex( + box.symbol, + forPeriod, + box.to // + ); + + // + for (int i = fromIDX; i >= toIDX; i--) + { + // + // Initialize Indexed Bar ... + XOHCL iBar; + isValid = iBar.Init( + box.symbol, + forPeriod, + i // + ); + if (!isValid) + { + // + iBar.Clean(); + continue; + } + + // + bool isUpperBullishRejected = iBar.IsRejected( + box.upper, + X_DIRECTION_BULLISH, + forceType, + forcePressure // + ); + bool isUpperBearishRejected = iBar.IsRejected( + box.upper, + X_DIRECTION_BEARISH, + forceType, + forcePressure // + ); + + // + bool isLowerBullishRejected = iBar.IsRejected( + box.lower, + X_DIRECTION_BULLISH, + forceType, + forcePressure // + ); + bool isLowerBearishRejected = iBar.IsRejected( + box.lower, + X_DIRECTION_BEARISH, + forceType, + forcePressure // + ); + + // + if (forDir == X_DIRECTION_ALL || + forDir == X_DIRECTION_BULLISH) + { + // + if (isUpperBullishRejected || + isLowerBullishRejected) + { + result++; + } + } + + // + if (forDir == X_DIRECTION_ALL || + forDir == X_DIRECTION_BEARISH) + { + // + if (isUpperBearishRejected || + isLowerBearishRejected) + { + result++; + } + } + + // + iBar.Clean(); + } + + // + return result; +} + +// \ No newline at end of file diff --git a/BKPS/14040203/Libraries/x-saherelm.x-poi.lib.mq5 b/BKPS/14040203/Libraries/x-saherelm.x-poi.lib.mq5 new file mode 100644 index 0000000..d2fc14c --- /dev/null +++ b/BKPS/14040203/Libraries/x-saherelm.x-poi.lib.mq5 @@ -0,0 +1,5486 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Seriallize Library +// --------------------------------------- +// Name: XPOILib +// Description: All models related to POIs ... +// +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +////////////////////////////////////////////////////// +// +// Global Properties ... +#property library +#property copyright "Copyright `023, SaherElm IT Center" +#property link "https://www.saherelm.ir" +#property version "1.00" +#property strict + +// +// Imports ... +#include "../Classes/x-saherelm.base.class.mq5" +#include + +// +// Definitions ... + +// +// All Available POI(s) ... +enum ENUM_XPOIS +{ + // + X_POI_NONE, + // + X_POI_TICKS_ZONES, // Ticks Zone ... + // + // Trading Day ... + X_POI_TRADING_DAY, // Trading Day ... + // + // Market Session ... + X_POI_MARKET_SESSION, // Market Session ... + // + // Momentum Bar ... + X_POI_MOMENTUM_BAR, // Momentum Bar ... + // + // Rejection Bar ... + X_POI_REJECTION_BAR, // Rejection Bar ... + // + // Swings ... + X_POI_SWING_HIGH, // Simple Swing High ... + X_POI_SWING_LOW, // Simple Swing Low ... + // + // Support nad Resistance ... + X_POI_SUPPORT_ZONE, // Support Zone ... + X_POI_RESISTANCE_ZONE, // Resistance Zone ... + // + // Supply and Demand Zones ... + X_POI_SUPPLY_ZONE, // Supply Zone ... + X_POI_DEMAND_ZONE, // Demand Zone ... + // + // Order Blocks ... + X_POI_BULLISH_ORDERBLOCK, // Bullish Order Block ... + X_POI_BEARISH_ORDERBLOCK, // Bearish Order Block ... + // + // Fair Value Gaps ... + X_POI_BULLISH_FVG, // Bullish Order Block ... + X_POI_BEARISH_FVG, // Bearish Order Block ... + // + X_BULLISH_CONSOLIDATION_ZONE, + X_BEARISH_CONSOLIDATION_ZONE, + // + X_BULLISH_SHARP, + X_BEARISH_SHARP, + // + X_BULLISH_SPIKE, + X_BEARISH_SPIKE, + // + X_BULLISH_PULLBACK, + X_BEARISH_PULLBACK, +}; + +// +// Event Types ... +enum ENUM_XPOI_EVENTS +{ + // + X_POI_EVENT_NONE, + // + // Trading Days ... + X_TRADE_DAY_FIRST_BAR, // Trading Day First Bar ... + X_TRADE_DAY_LAST_BAR, // Trading Day Last Bar ... + // + // Session ... + X_SESSION_FIRST_BAR, // Session First Bar ... + X_SESSION_LAST_BAR, // Session Last Bar ... + // + // Momentum Bar ... + X_BULLISH_MOMENTUM_BAR_DETECTED, + X_BEARISH_MOMENTUM_BAR_DETECTED, + // + // Rejection Bar ... + X_BULLISH_REJECTION_BAR_DETECTED, + X_BEARISH_REJECTION_BAR_DETECTED, + // + // Swings ... + X_SWING_HIGH_DETECTED, + X_SWING_LOW_DETECTED, + // + // Support nad Resistance ... + X_SUPPORT_ZONE_DETECTED, // Support Zone ... + X_RESISTANCE_ZONE_DETECTED, // Resistance Zone ... + // + // Supply nad Demand ... + X_SUPPLY_ZONE_DETECTED, // Supply Zone ... + X_DEMAND_ZONE_DETECTED, // Demand Zone ... + // + // Order Blocks ... + X_BULLISH_ORDERBLOCK_DETECTED, // Bullish Order Block ... + X_BEARISH_ORDERBLOCK_DETECTED, // Bearish Order Block ... + // + // Fair Value Gaps ... + X_BULLISH_FVG_DETECTED, // Bullish Fair Value GapÙ‘ ... + X_BEARISH_FVG_DETECTED, // Bearish Fair Value GapÙ‘ ... + X_BULLISH_CONSOLIDATION_ZONE_DETECTED, + X_BEARISH_CONSOLIDATION_ZONE_DETECTED, + X_BULLISH_SHARP_DETECTED, + X_BEARISH_SHARP_DETECTED, + X_BULLISH_SPIKE_DETECTED, + X_BEARISH_SPIKE_DETECTED, + X_BULLISH_PULLBACK_DETECTED, + X_BEARISH_PULLBACK_DETECTED, +}; + +// +enum ENUM_XZONE_STATE +{ + XZONE_STATE_NONE, + XZONE_STATE_PASSED, + XZONE_STATE_FAILED, + XZONE_STATE_IGNORED, +}; + +// +// Forext Sessions ... +enum ENUM_XSESSION +{ + X_TOKYO, + X_SYDNEY, + X_LONDON, + X_NEW_YORK, + X_FRANKFORT, +}; + +/** + * Converts ENUM_XPOI value to String Representation ... + * + * @param value: ENUM_XPOI member ... + * + * @return ( string ) + */ +string ToString(ENUM_XPOIS value) +{ + // + string result = NULL; + + // + switch (value) + { + // + case X_POI_TRADING_DAY: + result = "XTDAY"; + break; + + // + case X_POI_MARKET_SESSION: + result = "XMSESS"; + break; + + // + case X_POI_MOMENTUM_BAR: + result = "XMNTMB"; + break; + + // + case X_POI_REJECTION_BAR: + result = "XRJCTB"; + break; + + // + case X_POI_SWING_HIGH: + result = "XSPH"; + break; + + // + case X_POI_SWING_LOW: + result = "XSPL"; + break; + + // + case X_POI_SUPPORT_ZONE: + result = "XSUP"; + break; + + // + case X_POI_RESISTANCE_ZONE: + result = "XRES"; + break; + + // + case X_POI_SUPPLY_ZONE: + result = "XSUPPLY"; + break; + + // + case X_POI_DEMAND_ZONE: + result = "XDEMAND"; + break; + + // + case X_POI_BULLISH_ORDERBLOCK: + result = "XBULLOB"; + break; + + // + case X_POI_BEARISH_ORDERBLOCK: + result = "XBEAROB"; + break; + + // + case X_POI_BULLISH_FVG: + result = "XBULLFVG"; + break; + + // + case X_POI_BEARISH_FVG: + result = "XBEARFVG"; + break; + + // + case X_POI_TICKS_ZONES: + result = "XTKSZ"; + break; + + // + case X_BULLISH_CONSOLIDATION_ZONE: + result = "XBULLCZ"; + break; + + // + case X_BEARISH_CONSOLIDATION_ZONE: + result = "XBEARCZ"; + break; + + // + case X_BULLISH_SPIKE: + result = "XBULLSPK"; + break; + + // + case X_BEARISH_SPIKE: + result = "XBEARSPK"; + break; + } + + // + return result; +} + +/** + * Converts ENUM_XSESSION value to String Representation ... + * + * @param value: ENUM_XSESSION member ... + * + * @return ( string ) + */ +string ToString(ENUM_XSESSION value) +{ + // + string result = NULL; + + // + switch (value) + { + // + case X_SYDNEY: + result = "Sydney"; + break; + + // + case X_TOKYO: + result = "Tokyo"; + break; + + // + case X_FRANKFORT: + result = "FrankGurt"; + break; + + // + case X_LONDON: + result = "London"; + break; + + // + case X_NEW_YORK: + result = "NewYork"; + break; + } + + // + return result; +} + +/** + * Generate General Event Messages ... + * + * @param value: ENUM_XPOI_EVENTS member ... + * + * @return ( string ) + */ +string ToString(ENUM_XPOI_EVENTS value) +{ + // + string result = NULL; + + // + switch (value) + { + // + case X_TRADE_DAY_FIRST_BAR: + result = "First Bar of Day"; + break; + + // + case X_TRADE_DAY_LAST_BAR: + result = "Last Bar of Day"; + break; + + // + case X_SESSION_FIRST_BAR: + result = "First Bar of Session"; + break; + + // + case X_SESSION_LAST_BAR: + result = "Last Bar of Session"; + break; + + // + case X_BULLISH_MOMENTUM_BAR_DETECTED: + result = "Bullish Momentum Bar Detected"; + break; + + // + case X_BEARISH_MOMENTUM_BAR_DETECTED: + result = "Bearish Momentum Bar Detected"; + break; + + // + case X_BULLISH_REJECTION_BAR_DETECTED: + result = "Bullish Rejection Bar Detected"; + break; + + // + case X_BEARISH_REJECTION_BAR_DETECTED: + result = "Bearish Rejection Bar Detected"; + break; + + // + case X_SWING_HIGH_DETECTED: + result = "Swing High Detected"; + break; + + // + case X_SWING_LOW_DETECTED: + result = "Swing Low Detected"; + break; + + // + case X_SUPPORT_ZONE_DETECTED: + result = "Support Zone Detected"; + break; + + // + case X_RESISTANCE_ZONE_DETECTED: + result = "Resistance Zone Detected"; + break; + + // + case X_SUPPLY_ZONE_DETECTED: + result = "Supply Zone Detected"; + break; + + // + case X_DEMAND_ZONE_DETECTED: + result = "Demand Zone Detected"; + break; + + // + case X_BULLISH_ORDERBLOCK_DETECTED: + result = "Bullish Order Block Detected"; + break; + + // + case X_BEARISH_ORDERBLOCK_DETECTED: + result = "Bearish Orer Block Detected"; + break; + + // + case X_BULLISH_FVG_DETECTED: + result = "Bullish FVG Detected"; + break; + + // + case X_BEARISH_FVG_DETECTED: + result = "Bearish FVg Detected"; + break; + } + + // + return result; +} + +// +// Implementation ... + +// +// Base POI Model Class ... +class XCBasePOI : public XCBase +{ + // + public: + // + + // + // Constructor ... + void XCBasePOI() + { + // + Clean(); + + // + mSep = "_"; + mLineSep = "\n"; + } + + // + // Deconstructor ... + void ~XCBasePOI() + { + Clean(); + } + + // + // Virtual ... + + /** + * Cleanup ... + */ + virtual void Clean() + { + mType = X_POI_NONE; + } + + /** + * Validate ... + * + * @return ( virtual bool ) + */ + virtual bool IsValid() + { + return false; + } + + /** + * Retrieve POI Type ... + * + * @return ( virtual ENUM_XPOIS member ) + */ + virtual ENUM_XPOIS Type() + { + return mType; + } + + /** + * Retrieve POI Type ... + * + * @return ( virtual string ) + */ + virtual string TypeAsString() + { + return ToString(mType); + } + + /** + * Retrieve POI Tag ... + * + * @return ( virtual string ) + */ + virtual string GetTag() + { + return NULL; + } + + /** + * Retrieve POI Tooltip ... + * + * @return ( virtual string ) + */ + virtual string GetTooltip() + { + return NULL; + } + + // + protected: + // + // Props ... + string mSep; // Separator ... + string mLineSep; // Line Separator ... + ENUM_XPOIS mType; // Type ... + + // + private: + // +}; + +// +typedef void (*TOnPOIEvent)(ENUM_XPOI_EVENTS event, + XCBasePOI *param // +); + +// +// Zone POI Class ... +class XCZone : public XCBasePOI +{ + // + public: + // + + // + // Constructor ... + void XCZone() + { + } + + // + // Deconstructor ... + void ~XCZone() + { + } + + // + // Tools ... + + // + // Getter(s) / Setter(s) ... + + /** + * Get Zone Upper Boundary ... + * + * @return ( double ) + */ + double Upper() + { + return mUpper; + } + + /** + * Set Zone Upper Boundary ... + */ + void Upper(double value) + { + mUpper = value; + } + + /** + * Get Zone Lower Boundary ... + * + * @return ( double ) + */ + double Lower() + { + return mLower; + } + + /** + * Set Zone Lower Boundary ... + */ + void Lower(double value) + { + mLower = value; + } + + /** + * Retrieve Zone Range ... + * + * @return ( double ) + */ + double Range() + { + // + double result = 0; + + // + double upper = Upper(); + double lower = Lower(); + + // + if (upper > 0 && lower > 0 && upper > lower) + { + result = upper - lower; + } + + // + return result; + } + + double RangePercent() + { + // + double result = 0; + + // + double range = Range(); + if (range > 0) + { + result = range / 100; + } + + // + return result; + } + + // + // Virtuals ... + + /** + * Get Zone Start Date ... + * + * @return ( virtual datetime ) + */ + virtual datetime From() + { + return NULL; + } + + /** + * Get Zone End Date ... + * + * @return ( virtual datetime ) + */ + virtual datetime To() + { + return NULL; + } + + // + // Getter(s) / Setter(s) ... + + // + // Overrides ... + + // + // Validators ... + + /** + * Validate Upper and Lower of Zone ... + * + * @return ( bool ) + */ + bool IsValidBoundary() + { + // + bool result = false; + + // + result = + // + mUpper > 0 && + mLower > 0 && + mUpper >= mLower + // + ; + + // + return result; + } + + /** + * Check From Date of Zone is Valid ... + * + * @return ( bool ) + */ + bool IsValidFrom() + { + // + bool result = false; + + // + datetime from = From(); + result = IsSpecifiedValid(from); + + // + return result; + } + + // + protected: + // + // Props ... + double mUpper; // Zone Upper ... + double mLower; // Zone Lower ... + + // + private: + // + // Props ... + + // +}; + +// +// From To Zone ... +class XCFromToZone : public XCBasePOI +{ + // + public: + // + + // + // Constructor ... + void XCFromToZone() + { + } + + // + // Deconstructor ... + void ~XCFromToZone() + { + } + + // + // Tools ... + + bool InitFromTo( + ENUM_XPOIS type, + string title, + datetime from // + ) + { + // + bool result = false; + + // + result = type != X_POI_NONE && + IsSpecifiedValid(from) && + IsSpecifiedValid(title); + + // + mType = type; + mFrom = from; + mTitle = title; + mTo = TimeCurrent(); + + // + result = IsValid(); + + // + return result; + } + + bool InitFromTo( + ENUM_XPOIS type, + string title, + datetime from, + datetime to // + ) + { + // + bool result = false; + + // + result = IsValid(); + + // + result = InitFromTo( + type, + title, + from // + ); + if (!result) + { + return result; + } + + // + to = NormalizeTime(to); + mTo = to; + + // + result = IsValid(); + + // + return result; + } + + // + // Getter(s) / Setter(s) ... + + /** + * Get Zone Start Time ... + * + * @return ( datetime ) + */ + datetime From() + { + return mFrom; + } + + /** + * Set Zone Start Time ... + * + * @param value: Datetime + */ + void From(datetime value) + { + // + value = NormalizeTime(value); + + // + mFrom = value; + } + + /** + * Get Zone End Time ... + * + * @return ( datetime ) + */ + datetime To() + { + return mTo; + } + + /** + * Set Zone End Time ... + * + * @param value: Datetime + */ + void To(datetime value) + { + // + value = NormalizeTime(value); + + // + mTo = value; + } + + /** + * Get Title ... + * + * @return ( string ) + */ + string Title() + { + return mTitle; + } + + /** + * Set Title ... + * + * @param value: String ... + */ + // void Title(string value) + // { + // mTitle = value; + // } + + // + // Overrides ... + + void Clean() override + { + // + mTo = NULL; + mFrom = NULL; + mType = X_POI_NONE; + } + + bool IsValid() override + { + // + bool result = false; + + // + result = + // + mType != X_POI_NONE && + IsSpecifiedValid(mTo) && + IsSpecifiedValid(mFrom) && + IsSpecifiedValid(mTitle) + // + ; + + // + return result; + } + + string GetTag() override + { + // + string result = NULL; + + // + if (!IsValid()) + { + return result; + } + + // + string hash = TypeAsString() + mSep + ToString(From()) + mSep + Title(); + hash = ToMD5(hash); + + // + result = TypeAsString() + "[" + Title() + "]" + mSep + hash; + + // + return result; + } + + // + protected: + // + + // + private: + // + // Props ... + datetime mFrom; // Start Date + datetime mTo; // End Date + string mTitle; // Zone Title + + // +}; + +// +// Bar Zone ... +class XCBarZone : public XCZone +{ + // + public: + // + + // + // Constructor ... + void XCBarZone() + { + } + + // + // Deconstructor ... + void ~XCBarZone() + { + } + + // + // Tools ... + + /** + * Initialize POI ... + * + * @param bar: XOHCL instance ... + * @param type: ENUM_XPOIS member ... + * @param upperPrice: ENUM_X_PRICE member ... + * @param lowerPrice: ENUM_X_PRICE member ... + * + * @return ( bool ) + */ + bool InitBarZone( + XOHCL &bar, + ENUM_XPOIS type, + ENUM_X_PRICE upperPrice, + ENUM_X_PRICE lowerPrice // + ) + { + // + bool result = false; + + // + result = bar.IsValid() && + type != X_POI_NONE && + upperPrice != lowerPrice; + if (!result) + { + return result; + } + + // + mBar = bar; + mType = type; + mUpperPrice = upperPrice; + mLowerPrice = lowerPrice; + mUpper = bar.GetPrice(upperPrice); + mLower = bar.GetPrice(lowerPrice); + + // + result = IsValidBarZone(); + if (result) + { + // + From(bar.time); + To(TimeCurrent()); + } + + // + return result; + } + + // + // Getter(s) / Setter(s) ... + + /** + * Fill Bar as XOHCL struct ... + * + * @param bar: XOHCL instance ... + * + * @return ( bool ) + */ + bool FillBar( + XOHCL &bar // + ) + { + // + bool result = false; + + // + result = IsValid(); + if (!result) + { + return result; + } + + // + bar = mBar; + result = mBar.IsValid(); + + // + return result; + } + + /** + * Set From Date ... + * + * @param value: DateTime ... + */ + void From(datetime value) + { + // + if (!IsValidBarZone()) + { + return; + } + + // + value = NormalizeTime(value); + + // + mFrom = value; + } + + /** + * Set To Date ... + * + * @param value: DateTime ... + */ + void To(datetime value) + { + // + if (!IsValidBarZone()) + { + return; + } + + // + value = NormalizeTime(value); + + // + mTo = value; + } + + /** + * Retrieve Bar Time ... + * + * @return ( datetime ) + */ + datetime BarTime() + { + return mBar.time; + } + + /** + * Get Symbol ... + * + * @return ( string ) + */ + string GetSymbol() + { + // + string result = NULL; + + // + if (!mBar.IsValid()) + { + return result; + } + + // + return mBar.symbol; + + // + return result; + } + + /** + * Get Period ... + * + * @return ( int ) + */ + ENUM_TIMEFRAMES GetPeriod() + { + // + ENUM_TIMEFRAMES result = NULL; + + // + if (!mBar.IsValid()) + { + return result; + } + + // + return mBar.period; + + // + return result; + } + + /** + * Check Zone Started or not ... + * First Exit in Direction of Zone after From ... + * + * @param forDir: exit direction ... + * @param startedBar: specified Start Bar ... + * @param isBodyOut: specified Start Bar Close is Out of Zone or not ... + * @param forPeriod: specified Period ... + * + * @return ( bool ) + */ + bool IsStarted( + ENUM_X_DIRECTION forDir, + XOHCL &startedBar, + bool &isBodyOut, + ENUM_TIMEFRAMES forPeriod = NULL // + ) + { + // + bool result = false; + + // + isBodyOut = false; + startedBar.Clean(); + + // + result = HasDirection(forDir) && + IsValidBarZone(); + if (!result) + { + return result; + } + + // + bool isBullish = IsBullish(forDir); + + // + if (!IsSpecifiedValid(forPeriod)) + { + forPeriod = GetPeriod(); + } + + // + // Detect From Bar Index ... + int fromIndex = iBarShift( + GetSymbol(), + forPeriod, + From() // + ); + + // + for (int i = fromIndex; i >= 0; i--) + { + // + XOHCL iBar; + bool isInited = iBar.Init( + GetSymbol(), + forPeriod, + i // + ); + result = isInited; + if (!result) + { + // + iBar.Clean(); + continue; + } + + // + bool isBreakedFromUpper = + // + iBar.low > Upper() || + (iBar.low <= Upper() && + iBar.high > Upper() && + iBar.close > Upper()) + // + ; + + // + bool isBreakedFromLower = + // + iBar.low < Lower() || + (iBar.high >= Lower() && + iBar.low < Lower() && + iBar.close < Lower()) + // + ; + + // + bool isBreaked = + isBreakedFromUpper || + isBreakedFromLower; + if (isBreaked) + { + // + result = isBreaked && + isBullish + ? isBreakedFromUpper + : isBreakedFromLower; + if (result) + { + // + startedBar = iBar; + iBar.Clean(); + break; + } + } + + // + iBar.Clean(); + } + + // + result = startedBar.IsValid(); + if (result) + { + // + isBodyOut = + isBullish + ? startedBar.IsBullish() && + startedBar.GetUp() > Upper() + : startedBar.IsBearish() && + startedBar.GetDown() < Lower(); + } + + // + return result; + } + + /** + * Check Zone Activated or not ... + * First Enter in Opposit Direction of Zone after Start ... + * + * @param forDir: exit direction ... + * @param activatedBar: specified Activation Bar ... + * @param isBodyIn: specified Activation Bar Close is Inside of Zone or not ... + * @param forPeriod: specified Period ... + * + * @return ( bool ) + */ + bool IsActivated( + ENUM_X_DIRECTION forDir, + XOHCL &activatedBar, + bool &isBodyIn, + bool forceBodyOutStarted = true, + ENUM_TIMEFRAMES forPeriod = NULL // + ) + { + // + bool result = false; + + // + isBodyIn = false; + activatedBar.Clean(); + + // + result = HasDirection(forDir) && + IsValidBarZone(); + if (!result) + { + return result; + } + + // + bool isBullish = IsBullish(forDir); + + // + if (!IsSpecifiedValid(forPeriod)) + { + forPeriod = GetPeriod(); + } + + // + XOHCL startedBar; + bool isBodyOut = false; + bool isStarted = IsStarted( + forDir, + startedBar, + isBodyOut, + forPeriod // + ); + result = + !forceBodyOutStarted + ? isStarted + : isStarted && + isBodyOut; + if (!result) + { + // + startedBar.Clean(); + return result; + } + + // + int fromIndex = startedBar.Index() - 1; + + // + for (int i = fromIndex; i >= 0; i--) + { + // + XOHCL iBar; + bool isInited = iBar.Init( + GetSymbol(), + forPeriod, + i // + ); + result = isInited; + if (!result) + { + // + iBar.Clean(); + continue; + } + + // + bool isInsideFromUpper = + // + iBar.high < Upper() || + (iBar.high > Upper() && + iBar.low <= Upper() && + iBar.close <= Upper()) + // + ; + + // + bool isInsideFromLower = + // + iBar.low > Lower() || + (iBar.low < Lower() && + iBar.high >= Lower() && + iBar.close >= Lower()) + // + ; + + // + bool isInside = + isInsideFromUpper || + isInsideFromLower; + if (isInside) + { + // + result = isInside && + isBullish + ? isInsideFromUpper + : isInsideFromLower; + if (result) + { + // + activatedBar = iBar; + iBar.Clean(); + startedBar.Clean(); + break; + } + } + + // + iBar.Clean(); + startedBar.Clean(); + } + + // + result = activatedBar.IsValid(); + if (result) + { + // + isBodyIn = + isBullish + ? activatedBar.IsBearish() && + activatedBar.GetDown() < Upper() + : activatedBar.IsBullish() && + activatedBar.GetUp() > Lower(); + } + + // + return result; + } + + /** + * Check Zone Breaked or not ... + * + * @param forDir: exit direction ... + * @param breakedBar: specified Breaked Bar ... + * @param isBodyOut: specified Breaked Bar Close is Out of Zone or not ... + * @param ignoreStart: Ignore Zone Start (Calculate from From()) ... + * @param startedBodyOut: Started Bar Body Close State, if use Start for Calculation ... + * @param forPeriod: specified Period ... + * + * @return ( bool ) + */ + bool IsBreaked( + ENUM_X_DIRECTION forDir, + XOHCL &breakedBar, + bool &isBodyOut, + bool ignoreStart = false, + bool startedBodyOut = false, + ENUM_TIMEFRAMES forPeriod = NULL // + ) + { + // + bool result = false; + + // + isBodyOut = false; + breakedBar.Clean(); + + // + result = HasDirection(forDir) && + IsValidBarZone(); + if (!result) + { + return result; + } + + // + bool isBullish = IsBullish(forDir); + + // + if (!IsSpecifiedValid(forPeriod)) + { + forPeriod = GetPeriod(); + } + + // + int fromIndex = -1; + if (!ignoreStart) + { + // + XOHCL startedBar; + bool isBodyOut = false; + bool isStarted = IsStarted( + forDir, + startedBar, + isBodyOut, + forPeriod // + ); + + // + bool isStartPassed = + !startedBodyOut + ? isStarted + : isStarted && + isBodyOut; + if (isStartPassed) + { + fromIndex = startedBar.Index() - 1; + } + + // + startedBar.Clean(); + } + else + { + // + fromIndex = iBarShift( + GetSymbol(), + forPeriod, + From() // + ); + } + + // + result = IsValidIndex(fromIndex); + if (!result) + { + return result; + } + + // + for (int i = fromIndex; i >= 0; i--) + { + // + XOHCL iBar; + bool isInited = iBar.Init( + GetSymbol(), + forPeriod, + i // + ); + result = isInited; + if (!result) + { + // + iBar.Clean(); + continue; + } + + // + bool isBreakedFromUpper = + // + iBar.low > Upper() || + (iBar.low <= Upper() && + iBar.high > Upper() && + iBar.close > Upper()) + // + ; + + // + bool isBreakedFromLower = + // + iBar.low < Lower() || + (iBar.high >= Lower() && + iBar.low < Lower() && + iBar.close < Lower()) + // + ; + + // + bool isBreaked = + isBreakedFromUpper || + isBreakedFromLower; + if (isBreaked) + { + // + result = isBreaked && + (isBullish + ? isBreakedFromLower + : isBreakedFromUpper); + if (result) + { + // + breakedBar = iBar; + iBar.Clean(); + break; + } + } + + // + iBar.Clean(); + } + + // + result = breakedBar.IsValid(); + if (result) + { + // + isBodyOut = + isBullish + ? breakedBar.IsBearish() && + breakedBar.GetDown() < Lower() + : breakedBar.IsBullish() && + breakedBar.GetUp() > Upper(); + } + + // + return result; + } + + /** + * Check Zone Worked or not ... + * + * @param forDir: exit direction ... + * @param workedBar: specified Worked Bar ... + * @param isBodyOut: specified Worked Bar Close is Out of Zone or not ... + * @param ignoreActivation: Ignore Zone Activation (Calculate from From()) ... + * @param activationStartedOut: Specified Zone Start Bar State ... + * @param activationBodyIn: Specified Zone Activation Bar State ... + * @param forPeriod: specified Period ... + * + * @return ( bool ) + */ + bool IsWorked( + ENUM_X_DIRECTION forDir, + XOHCL &workedBar, + bool &isBodyOut, + bool ignoreActivation = false, + bool activationStartedOut = false, + bool activationBodyIn = false, + ENUM_TIMEFRAMES forPeriod = NULL // + ) + { + // + bool result = false; + + // + isBodyOut = false; + workedBar.Clean(); + + // + result = HasDirection(forDir) && + IsValidBarZone(); + if (!result) + { + return result; + } + + // + bool isBullish = IsBullish(forDir); + + // + if (!IsSpecifiedValid(forPeriod)) + { + forPeriod = GetPeriod(); + } + + // + int fromIndex = -1; + if (!ignoreActivation) + { + // + XOHCL activatedBar; + bool isBodyIn = false; + bool isActivated = IsActivated( + forDir, + activatedBar, + isBodyIn, + activationStartedOut, + forPeriod // + ); + + // + bool isActivationPassed = + !activationBodyIn + ? isActivated + : isActivated && + isBodyIn; + if (isActivationPassed) + { + fromIndex = activatedBar.Index() - 1; + } + + // + activatedBar.Clean(); + } + else + { + // + fromIndex = iBarShift( + GetSymbol(), + forPeriod, + From() // + ); + } + + // + result = IsValidIndex(fromIndex); + if (!result) + { + return result; + } + + // + for (int i = fromIndex; i >= 0; i--) + { + // + XOHCL iBar; + bool isInited = iBar.Init( + GetSymbol(), + forPeriod, + i // + ); + result = isInited; + if (!result) + { + // + iBar.Clean(); + continue; + } + + // + bool isBreakedFromUpper = + // + iBar.low > Upper() || + (iBar.low <= Upper() && + iBar.high > Upper() && + iBar.close > Upper()) + // + ; + + // + bool isBreakedFromLower = + // + iBar.low < Lower() || + (iBar.high >= Lower() && + iBar.low < Lower() && + iBar.close < Lower()) + // + ; + + // + bool isBreaked = + isBreakedFromUpper || + isBreakedFromLower; + if (isBreaked) + { + // + result = isBreaked && + isBullish + ? isBreakedFromUpper + : isBreakedFromLower; + if (result) + { + // + workedBar = iBar; + iBar.Clean(); + break; + } + } + + // + iBar.Clean(); + } + + // + result = workedBar.IsValid(); + if (result) + { + // + isBodyOut = + isBullish + ? workedBar.IsBullish() && + workedBar.GetUp() > Upper() + : workedBar.IsBearish() && + workedBar.GetDown() < Lower(); + } + + // + return result; + } + + /** + * Check to Find Nearest Bar which Breakes Upper ... + * + * @param bar: XOHCL instance Reference, Breaker Bar ... + * @param forPeriod: ENUM_TIMEFRAMES member, Breaker Bar Detection Period, default is Zone Period ... + * + * @return ( bool ) + */ + bool FindNearestInsideBarFromUpper( + XOHCL &bar, + ENUM_TIMEFRAMES forPeriod = NULL // + ) + { + // + bool result = false; + + // + bar.Clean(); + + // + if (!IsSpecifiedValid(forPeriod)) + { + forPeriod = GetPeriod(); + } + + // + result = IsValid(); + if (!result) + { + return result; + } + + // + int from = 1; + int to = iBarShift( + GetSymbol(), + forPeriod, + From() // + ); + + // + for (int i = from; i < to; i++) + { + // + XOHCL iBar; + bool isInited = iBar.Init( + GetSymbol(), + forPeriod, + i // + ); + if (!isInited) + { + break; + } + + // + bool isInside = iBar.low < Upper(); + if (isInside) + { + // + bar = iBar; + break; + } + } + + // + result = bar.IsValid(); + + // + return result; + } + + /** + * Check to Find Nearest Bar which Breakes Lower ... + * + * @param bar: XOHCL instance Reference, Breaker Bar ... + * @param forPeriod: ENUM_TIMEFRAMES member, Breaker Bar Detection Period, default is Zone Period ... + * + * @return ( bool ) + */ + bool FindNearestInsideBarFromLower( + XOHCL &bar, + ENUM_TIMEFRAMES forPeriod = NULL // + ) + { + // + bool result = false; + + // + bar.Clean(); + + // + if (!IsSpecifiedValid(forPeriod)) + { + forPeriod = GetPeriod(); + } + + // + result = IsValid(); + if (!result) + { + return result; + } + + // + int from = 1; + int to = iBarShift( + GetSymbol(), + forPeriod, + From() // + ); + + // + for (int i = from; i < to; i++) + { + // + XOHCL iBar; + bool isInited = iBar.Init( + GetSymbol(), + forPeriod, + i // + ); + if (!isInited) + { + break; + } + + // + bool isInside = iBar.high > Lower(); + if (isInside) + { + // + bar = iBar; + break; + } + } + + // + result = bar.IsValid(); + + // + return result; + } + + // + // Overrides ... + + void Clean() override + { + // + mBar.Clean(); + mUpper = 0; + mLower = 0; + mType = X_POI_NONE; + } + + datetime From() override + { + return mFrom; + } + + datetime To() override + { + return mTo; + } + + string GetTag() override + { + // + string result = NULL; + + // + if (!IsValidBarZone()) + { + return result; + } + + // + string hash = ToMD5(mBar.GetTag()); + + // + result = + // + TypeAsString() + mSep + + ToString(mBar.period) + mSep + + hash + // + ; + + // + return result; + } + + string GetTooltip() override + { + // + string result = NULL; + + // + if (!IsValidBarZone()) + { + return result; + } + + // + return result; + } + + // + protected: + // + // Props ... + XOHCL mBar; // Bar ... + ENUM_X_PRICE mUpperPrice; // Upper Price Selection + ENUM_X_PRICE mLowerPrice; // Lower Price Selection + + /** + * Check Bar Zone Validation ... + * + * @return ( bool ) + */ + bool IsValidBarZone() + { + // + bool result = false; + + // + result = mBar.IsValid() && + mType != X_POI_NONE && + IsValidBoundary(); + + // + return result; + } + + // + private: + // + // Props ... + datetime mFrom; + datetime mTo; + + // +}; +class XCTwoBarZone : public XCZone +{ + // + public: + // + + // + // Constructor ... + void XCTwoBarZone() + { + } + + // + // Deconstructor ... + void ~XCTwoBarZone() + { + } + + // + // Tools ... + + /** + * Initialize POI ... + * + * @param bar: XOHCL instance ... + * @param type: ENUM_XPOIS member ... + * @param upperPrice: ENUM_X_PRICE member ... + * @param lowerPrice: ENUM_X_PRICE member ... + * + * @return ( bool ) + */ + bool InitTwoBarZone( + XOHCL &startBar, + XOHCL &endBar, + ENUM_XPOIS type, + ENUM_X_PRICE startPrice, + ENUM_X_PRICE endPrice // + ) + { + // + bool result = false; + + // + result = startBar.IsValid() && + endBar.IsValid() && + startBar.symbol == endBar.symbol && + startBar.period == endBar.period && + startBar.time < endBar.time && + type != X_POI_NONE; + if (!result) + { + return result; + } + + // + mType = type; + mEndBar = endBar; + mStartBar = startBar; + + // + int startIndex = startBar.Index(); + int endIndex = endBar.Index(); + + // + double mStartPrice = startBar.GetPrice(startPrice); + double mEndPrice = endBar.GetPrice(endPrice); + bool isStartOverEnd = mStartPrice > mEndPrice; + + // + if (isStartOverEnd) + { + // + mUpperPrice = startPrice; + mLowerPrice = endPrice; + } + else + { + // + mUpperPrice = endPrice; + mLowerPrice = startPrice; + } + + // + mUpper = MathMax(mStartPrice, mEndPrice); + mLower = MathMin(mStartPrice, mEndPrice); + + // + result = IsValidTwoBarZone(); + if (result) + { + // + From(startBar.time); + To(endBar.time); + } + + // + return result; + } + + // + // Getter(s) / Setter(s) ... + + /** + * Set From Date ... + * + * @param value: DateTime ... + */ + void From(datetime value) + { + // + if (!IsValidTwoBarZone()) + { + return; + } + + // + value = NormalizeTime(value); + + // + mFrom = value; + } + + /** + * Set To Date ... + * + * @param value: DateTime ... + */ + void To(datetime value) + { + // + if (!IsValidTwoBarZone()) + { + return; + } + + // + value = NormalizeTime(value); + + // + mTo = value; + } + + /** + * Fill Start Bar ... + * + * @param bar: XOHCL instance ... + * + * @return ( bool ) + */ + bool FillStartBar(XOHCL &bar) + { + // + bool result = false; + + // + result = IsValidTwoBarZone(); + if (!result) + { + return result; + } + + // + bar = mStartBar; + + // + return result; + } + + /** + * Fill End Bar ... + * + * @param bar: XOHCL instance ... + * + * @return ( bool ) + */ + bool FillEndBar(XOHCL &bar) + { + // + bool result = false; + + // + result = IsValidTwoBarZone(); + if (!result) + { + return result; + } + + // + bar = mEndBar; + + // + return result; + } + + /** + * Get Symbol ... + * + * @return ( string ) + */ + string GetSymbol() + { + // + string result = NULL; + + // + if (!mStartBar.IsValid()) + { + return result; + } + + // + return mStartBar.symbol; + + // + return result; + } + + /** + * Get Period ... + * + * @return ( int ) + */ + ENUM_TIMEFRAMES GetPeriod() + { + // + ENUM_TIMEFRAMES result = NULL; + + // + if (!mStartBar.IsValid()) + { + return result; + } + + // + return mStartBar.period; + + // + return result; + } + + /** + * Check Zone Started or not ... + * First Exit in Direction of Zone after From ... + * + * @param forDir: exit direction ... + * @param startedBar: specified Start Bar ... + * @param isBodyOut: specified Start Bar Close is Out of Zone or not ... + * @param forPeriod: specified Period ... + * + * @return ( bool ) + */ + bool IsStarted( + ENUM_X_DIRECTION forDir, + XOHCL &startedBar, + bool &isBodyOut, + ENUM_TIMEFRAMES forPeriod = NULL // + ) + { + // + bool result = false; + + // + isBodyOut = false; + startedBar.Clean(); + + // + result = HasDirection(forDir) && + IsValidTwoBarZone(); + if (!result) + { + return result; + } + + // + bool isBullish = IsBullish(forDir); + + // + if (!IsSpecifiedValid(forPeriod)) + { + forPeriod = GetPeriod(); + } + + // + // Detect From Bar Index ... + int fromIndex = iBarShift( + GetSymbol(), + forPeriod, + From() // + ); + + // + for (int i = fromIndex; i >= 0; i--) + { + // + XOHCL iBar; + bool isInited = iBar.Init( + GetSymbol(), + forPeriod, + i // + ); + result = isInited; + if (!result) + { + // + iBar.Clean(); + continue; + } + + // + bool isBreakedFromUpper = + // + iBar.low > Upper() || + (iBar.low <= Upper() && + iBar.high > Upper() && + iBar.close > Upper()) + // + ; + + // + bool isBreakedFromLower = + // + iBar.low < Lower() || + (iBar.high >= Lower() && + iBar.low < Lower() && + iBar.close < Lower()) + // + ; + + // + bool isBreaked = + isBreakedFromUpper || + isBreakedFromLower; + if (isBreaked) + { + // + result = isBreaked && + isBullish + ? isBreakedFromUpper + : isBreakedFromLower; + if (result) + { + // + startedBar = iBar; + iBar.Clean(); + break; + } + } + + // + iBar.Clean(); + } + + // + result = startedBar.IsValid(); + if (result) + { + // + isBodyOut = + isBullish + ? startedBar.IsBullish() && + startedBar.GetUp() > Upper() + : startedBar.IsBearish() && + startedBar.GetDown() < Lower(); + } + + // + return result; + } + + /** + * Check Zone Activated or not ... + * First Enter in Opposit Direction of Zone after Start ... + * + * @param forDir: exit direction ... + * @param activatedBar: specified Activation Bar ... + * @param isBodyIn: specified Activation Bar Close is Inside of Zone or not ... + * @param forPeriod: specified Period ... + * + * @return ( bool ) + */ + bool IsActivated( + ENUM_X_DIRECTION forDir, + XOHCL &activatedBar, + bool &isBodyIn, + bool forceBodyOutStarted = true, + ENUM_TIMEFRAMES forPeriod = NULL // + ) + { + // + bool result = false; + + // + isBodyIn = false; + activatedBar.Clean(); + + // + result = HasDirection(forDir) && + IsValidTwoBarZone(); + if (!result) + { + return result; + } + + // + bool isBullish = IsBullish(forDir); + + // + if (!IsSpecifiedValid(forPeriod)) + { + forPeriod = GetPeriod(); + } + + // + XOHCL startedBar; + bool isBodyOut = false; + bool isStarted = IsStarted( + forDir, + startedBar, + isBodyOut, + forPeriod // + ); + result = + !forceBodyOutStarted + ? isStarted + : isStarted && + isBodyOut; + if (!result) + { + // + startedBar.Clean(); + return result; + } + + // + int fromIndex = startedBar.Index() - 1; + + // + for (int i = fromIndex; i >= 0; i--) + { + // + XOHCL iBar; + bool isInited = iBar.Init( + GetSymbol(), + forPeriod, + i // + ); + result = isInited; + if (!result) + { + // + iBar.Clean(); + continue; + } + + // + bool isInsideFromUpper = + // + iBar.high < Upper() || + (iBar.high > Upper() && + iBar.low <= Upper() && + iBar.close <= Upper()) + // + ; + + // + bool isInsideFromLower = + // + iBar.low > Lower() || + (iBar.low < Lower() && + iBar.high >= Lower() && + iBar.close >= Lower()) + // + ; + + // + bool isInside = + isInsideFromUpper || + isInsideFromLower; + if (isInside) + { + // + result = isInside && + isBullish + ? isInsideFromUpper + : isInsideFromLower; + if (result) + { + // + activatedBar = iBar; + iBar.Clean(); + startedBar.Clean(); + break; + } + } + + // + iBar.Clean(); + startedBar.Clean(); + } + + // + result = activatedBar.IsValid(); + if (result) + { + // + isBodyIn = + isBullish + ? activatedBar.IsBearish() && + activatedBar.GetDown() < Upper() + : activatedBar.IsBullish() && + activatedBar.GetUp() > Lower(); + } + + // + return result; + } + + /** + * Check Zone reaked or not ... + * + * @param forDir: exit direction ... + * @param breakedBar: specified Breaked Bar ... + * @param isBodyOut: specified Breaked Bar Close is Out of Zone or not ... + * @param ignoreStart: Ignore Zone Start (Calculate from From()) ... + * @param startedBodyOut: Started Bar Body Close State, if use Start for Calculation ... + * @param forPeriod: specified Period ... + * + * @return ( bool ) + */ + bool IsBreaked( + ENUM_X_DIRECTION forDir, + XOHCL &breakedBar, + bool &isBodyOut, + bool ignoreStart = false, + bool startedBodyOut = false, + ENUM_TIMEFRAMES forPeriod = NULL // + ) + { + // + bool result = false; + + // + isBodyOut = false; + breakedBar.Clean(); + + // + result = HasDirection(forDir) && + IsValidTwoBarZone(); + if (!result) + { + return result; + } + + // + bool isBullish = IsBullish(forDir); + + // + if (!IsSpecifiedValid(forPeriod)) + { + forPeriod = GetPeriod(); + } + + // + int fromIndex = -1; + if (!ignoreStart) + { + // + XOHCL startedBar; + bool isBodyOut = false; + bool isStarted = IsStarted( + forDir, + startedBar, + isBodyOut, + forPeriod // + ); + + // + bool isStartPassed = + !startedBodyOut + ? isStarted + : isStarted && + isBodyOut; + if (isStartPassed) + { + fromIndex = startedBar.Index() - 1; + } + + // + startedBar.Clean(); + } + else + { + // + fromIndex = iBarShift( + GetSymbol(), + forPeriod, + From() // + ); + } + + // + result = IsValidIndex(fromIndex); + if (!result) + { + return result; + } + + // + for (int i = fromIndex; i >= 0; i--) + { + // + XOHCL iBar; + bool isInited = iBar.Init( + GetSymbol(), + forPeriod, + i // + ); + result = isInited; + if (!result) + { + // + iBar.Clean(); + continue; + } + + // + bool isBreakedFromUpper = + // + iBar.low > Upper() || + (iBar.low <= Upper() && + iBar.high > Upper() && + iBar.close > Upper()) + // + ; + + // + bool isBreakedFromLower = + // + iBar.low < Lower() || + (iBar.high >= Lower() && + iBar.low < Lower() && + iBar.close < Lower()) + // + ; + + // + bool isBreaked = + isBreakedFromUpper || + isBreakedFromLower; + if (isBreaked) + { + // + result = isBreaked && + (isBullish + ? isBreakedFromLower + : isBreakedFromUpper); + if (result) + { + // + breakedBar = iBar; + iBar.Clean(); + break; + } + } + + // + iBar.Clean(); + } + + // + result = breakedBar.IsValid(); + if (result) + { + // + isBodyOut = + isBullish + ? breakedBar.IsBearish() && + breakedBar.GetDown() < Lower() + : breakedBar.IsBullish() && + breakedBar.GetUp() > Upper(); + } + + // + return result; + } + + /** + * Check Zone Worked or not ... + * + * @param forDir: exit direction ... + * @param workedBar: specified Worked Bar ... + * @param isBodyOut: specified Worked Bar Close is Out of Zone or not ... + * @param ignoreActivation: Ignore Zone Activation (Calculate from From()) ... + * @param activationStartedOut: Specified Zone Start Bar State ... + * @param activationBodyIn: Specified Zone Activation Bar State ... + * @param forPeriod: specified Period ... + * + * @return ( bool ) + */ + bool IsWorked( + ENUM_X_DIRECTION forDir, + XOHCL &workedBar, + bool &isBodyOut, + bool ignoreActivation = false, + bool activationStartedOut = false, + bool activationBodyIn = false, + ENUM_TIMEFRAMES forPeriod = NULL // + ) + { + // + bool result = false; + + // + isBodyOut = false; + workedBar.Clean(); + + // + result = HasDirection(forDir) && + IsValidTwoBarZone(); + if (!result) + { + return result; + } + + // + bool isBullish = IsBullish(forDir); + + // + if (!IsSpecifiedValid(forPeriod)) + { + forPeriod = GetPeriod(); + } + + // + int fromIndex = -1; + if (!ignoreActivation) + { + // + XOHCL activatedBar; + bool isBodyIn = false; + bool isActivated = IsActivated( + forDir, + activatedBar, + isBodyIn, + activationStartedOut, + forPeriod // + ); + + // + bool isActivationPassed = + !activationBodyIn + ? isActivated + : isActivated && + isBodyIn; + if (isActivationPassed) + { + fromIndex = activatedBar.Index() - 1; + } + + // + activatedBar.Clean(); + } + else + { + // + fromIndex = iBarShift( + GetSymbol(), + forPeriod, + From() // + ); + } + + // + result = IsValidIndex(fromIndex); + if (!result) + { + return result; + } + + // + for (int i = fromIndex; i >= 0; i--) + { + // + XOHCL iBar; + bool isInited = iBar.Init( + GetSymbol(), + forPeriod, + i // + ); + result = isInited; + if (!result) + { + // + iBar.Clean(); + continue; + } + + // + bool isBreakedFromUpper = + // + iBar.low > Upper() || + (iBar.low <= Upper() && + iBar.high > Upper() && + iBar.close > Upper()) + // + ; + + // + bool isBreakedFromLower = + // + iBar.low < Lower() || + (iBar.high >= Lower() && + iBar.low < Lower() && + iBar.close < Lower()) + // + ; + + // + bool isBreaked = + isBreakedFromUpper || + isBreakedFromLower; + if (isBreaked) + { + // + result = isBreaked && + isBullish + ? isBreakedFromUpper + : isBreakedFromLower; + if (result) + { + // + workedBar = iBar; + iBar.Clean(); + break; + } + } + + // + iBar.Clean(); + } + + // + result = workedBar.IsValid(); + if (result) + { + // + isBodyOut = + isBullish + ? workedBar.IsBullish() && + workedBar.GetUp() > Upper() + : workedBar.IsBearish() && + workedBar.GetDown() < Lower(); + } + + // + return result; + } + + /** + * Check to Find Nearest Bar which Breakes Upper ... + * + * @param bar: XOHCL instance Reference, Breaker Bar ... + * @param forPeriod: ENUM_TIMEFRAMES member, Breaker Bar Detection Period, default is Zone Period ... + * + * @return ( bool ) + */ + bool FindNearestInsideBarFromUpper( + XOHCL &bar, + ENUM_TIMEFRAMES forPeriod = NULL // + ) + { + // + bool result = false; + + // + bar.Clean(); + + // + if (!IsSpecifiedValid(forPeriod)) + { + forPeriod = GetPeriod(); + } + + // + result = IsValid(); + if (!result) + { + return result; + } + + // + int from = 1; + int to = iBarShift( + GetSymbol(), + forPeriod, + From() // + ); + + // + for (int i = from; i < to; i++) + { + // + XOHCL iBar; + bool isInited = iBar.Init( + GetSymbol(), + forPeriod, + i // + ); + if (!isInited) + { + break; + } + + // + bool isInside = iBar.low < Upper(); + if (isInside) + { + // + bar = iBar; + break; + } + } + + // + result = bar.IsValid(); + + // + return result; + } + + /** + * Check to Find Nearest Bar which Breakes Lower ... + * + * @param bar: XOHCL instance Reference, Breaker Bar ... + * @param forPeriod: ENUM_TIMEFRAMES member, Breaker Bar Detection Period, default is Zone Period ... + * + * @return ( bool ) + */ + bool FindNearestInsideBarFromLower( + XOHCL &bar, + ENUM_TIMEFRAMES forPeriod = NULL // + ) + { + // + bool result = false; + + // + bar.Clean(); + + // + if (!IsSpecifiedValid(forPeriod)) + { + forPeriod = GetPeriod(); + } + + // + result = IsValid(); + if (!result) + { + return result; + } + + // + int from = 1; + int to = iBarShift( + GetSymbol(), + forPeriod, + From() // + ); + + // + for (int i = from; i < to; i++) + { + // + XOHCL iBar; + bool isInited = iBar.Init( + GetSymbol(), + forPeriod, + i // + ); + if (!isInited) + { + break; + } + + // + bool isInside = iBar.high > Lower(); + if (isInside) + { + // + bar = iBar; + break; + } + } + + // + result = bar.IsValid(); + + // + return result; + } + + // + // Overrides ... + + void Clean() override + { + // + mStartBar.Clean(); + mEndBar.Clean(); + mUpper = 0; + mLower = 0; + mUseStartBarForUpper = false; + mType = X_POI_NONE; + } + + datetime From() override + { + return mFrom; + } + + datetime To() override + { + return mTo; + } + + string GetTag() override + { + // + string result = NULL; + + // + if (!IsValidTwoBarZone()) + { + return result; + } + + // + string hash = ToMD5(mStartBar.GetTag() + mSep + mEndBar.GetTag()); + + // + result = + // + TypeAsString() + mSep + + ToString(mStartBar.period) + mSep + + hash + // + ; + + // + return result; + } + + string GetTooltip() override + { + // + string result = NULL; + + // + if (!IsValidTwoBarZone()) + { + return result; + } + + // + return result; + } + + // + protected: + // + // Props ... + XOHCL mStartBar; // Start (Oldest) Bar ... + XOHCL mEndBar; // End (Newest) Bar ... + bool mUseStartBarForUpper; // Use Start Bar for Upper Calculation ... + ENUM_X_PRICE mUpperPrice; // Upper Price Selection + ENUM_X_PRICE mLowerPrice; // Lower Price Selection + + /** + * Check Two Bar Zone Validation ... + * + * @return ( bool ) + */ + bool IsValidTwoBarZone() + { + // + bool result = false; + + // + result = mStartBar.IsValid() && + mEndBar.IsValid() && + mStartBar.symbol == mEndBar.symbol && + mStartBar.period == mEndBar.period && + mStartBar.time < mEndBar.time && + mType != X_POI_NONE && + IsValidBoundary(); + + // + return result; + } + + // + private: + // + // Props ... + datetime mFrom; + datetime mTo; + + // +}; + +// +// Swing Class ... +class XCSwing : public XCBasePOI +{ + // + public: + // + + // + // Constructor ... + void XCSwing() + { + } + + // + // Deconstructor ... + void ~XCSwing() + { + } + + // + // Tools ... + + /** + * Initialize POI ... + * + * @param bar: XOHCL instance ... + * @param type: ENUM_XPOIS member ... + * + * @return ( bool ) + */ + bool Init( + XOHCL &bar, + ENUM_XPOIS type // + ) + { + // + bool result = false; + + // + result = bar.IsValid() && + (type == X_POI_SWING_HIGH || + type == X_POI_SWING_LOW); + if (!result) + { + return result; + } + + // + mBar = bar; + mType = type; + + // + result = IsValid(); + + // + return result; + } + + // + // Getter(s) / Setter(s) ... + + /** + * Fill Bar as XOHCL struct ... + * + * @param bar: XOHCL instance ... + * + * @return ( bool ) + */ + bool FillBar( + XOHCL &bar // + ) + { + // + bool result = false; + + // + result = IsValid(); + if (!result) + { + return result; + } + + // + bar = mBar; + result = mBar.IsValid(); + + // + return result; + } + + /** + * Get Time of Swing ... + * + * @return ( datetime ) + */ + datetime GetTime() + { + // + datetime result = NULL; + + // + if (!IsValid() || !mBar.IsValid()) + { + return result; + } + + // + result = mBar.time; + + // + return result; + } + + ENUM_TIMEFRAMES GetPeriod() + { + // + ENUM_TIMEFRAMES result = NULL; + + // + XOHCL bar; + bool isFilled = FillBar(bar); + if (!isFilled) + { + return result; + } + + // + result = bar.period; + + // + return result; + } + + /** + * Check Swing High or not ... + * + * @return ( bool ) + */ + bool IsSwingHigh() + { + // + bool result = false; + + // + result = IsValid(); + if (!result) + { + return result; + } + + // + result = + Type() == X_POI_SWING_HIGH; + + // + return result; + } + + /** + * Check Swing Low or not ... + * + * @return ( bool ) + */ + bool IsSwingLow() + { + // + bool result = false; + + // + result = IsValid(); + if (!result) + { + return result; + } + + // + result = + Type() == X_POI_SWING_LOW; + + // + return result; + } + + /** + * Get Swing Value ... + * + * @return ( double ) + */ + double GetValue() + { + // + double result = 0; + + // + if (!IsValid()) + { + return result; + } + + // + result = + IsSwingHigh() + ? mBar.high + : mBar.low; + + // + return result; + } + + // + // Overrides ... + + void Clean() override + { + // + mBar.Clean(); + mType = X_POI_NONE; + } + + bool IsValid() override + { + // + bool result = false; + + // + result = mBar.IsValid() && + (mType == X_POI_SWING_HIGH || + mType == X_POI_SWING_LOW); + + // + return result; + } + + string GetTag() override + { + // + string result = NULL; + + // + if (!IsValid()) + { + return result; + } + + // + string hash = ToMD5(mBar.GetTag()); + + // + string subType = IsSwingHigh() + ? "High" + : "Low"; + + // + result = + // + TypeAsString() + mSep + + subType + mSep + + ToString(mBar.period) + mSep + + hash + // + ; + + // + return result; + } + + string GetTooltip() override + { + // + string result = NULL; + + // + if (!IsValid()) + { + return result; + } + + // + return result; + } + + // + protected: + // + // Props ... + XOHCL mBar; // Swing Bar ... + + // + private: + // +}; + +// +// Supply Zone ... +class XCSupplyZone : public XCBarZone +{ + // + public: + // + + // + // Constructor ... + void XCSupplyZone() + { + } + + // + // Deconstructor ... + void ~XCSupplyZone() + { + } + + // + // Tools ... + + /** + * Initialize POI ... + * + * @param bar: XOHCL instance ... + * @param range: Integer, Detection Range ... + * + * @return ( bool ) + */ + bool Init( + XOHCL &bar, + int range = 0, + bool useRangeAsStart = false // + ) + { + // + bool result = false; + + // + result = bar.IsValid(); + if (!result) + { + return result; + } + + // + result = InitBarZone( + bar, + X_POI_SUPPLY_ZONE, + X_PRICE_HIGH, + X_PRICE_LOW // + ); + if (!result) + { + return result; + } + + // + result = IsValid(); + if (result && + range > 0) + { + // + datetime time = bar.time; + int periodSeconds = PeriodSeconds(bar.period); + + // + datetime from = + !useRangeAsStart + ? (datetime)((int)time - (range * periodSeconds)) + : time; + datetime to = (datetime)((int)time + (range * periodSeconds)); + + // + From(from); + To(to); + } + + // + return result; + } + + // + // Getter(s) / Setter(s) ... + + // + // Overrides ... + + bool IsValid() override + { + // + bool result = false; + + // + result = IsValidBarZone() && + mType == X_POI_SUPPLY_ZONE; + + // + return result; + } + + // + protected: + // + + // + private: + // + + // +}; + +// +// Demand Zone ... +class XCDemandZone : public XCBarZone +{ + // + public: + // + + // + // Constructor ... + void XCDemandZone() + { + } + + // + // Deconstructor ... + void ~XCDemandZone() + { + } + + // + // Tools ... + + /** + * Initialize POI ... + * + * @param bar: XOHCL instance ... + * @param range: Integer, Detection Range ... + * + * @return ( bool ) + */ + bool Init( + XOHCL &bar, + int range = 0, + bool useRangeAsStart = false // + ) + { + // + bool result = false; + + // + result = bar.IsValid(); + if (!result) + { + return result; + } + + // + result = InitBarZone( + bar, + X_POI_DEMAND_ZONE, + X_PRICE_HIGH, + X_PRICE_LOW // + ); + if (!result) + { + return result; + } + + // + result = IsValid(); + if (result && + range > 0) + { + // + datetime time = bar.time; + int periodSeconds = PeriodSeconds(bar.period); + + // + datetime from = + !useRangeAsStart + ? (datetime)((int)time - (range * periodSeconds)) + : time; + datetime to = (datetime)((int)time + (range * periodSeconds)); + + // + From(from); + To(to); + } + + // + return result; + } + + // + // Getter(s) / Setter(s) ... + + // + // Overrides ... + + bool IsValid() override + { + // + bool result = false; + + // + result = IsValidBarZone() && + mType == X_POI_DEMAND_ZONE; + + // + return result; + } + + // + protected: + // + + // + private: + // + + // +}; + +// +// Support Zone ... +class XCSupportZone : public XCBarZone +{ + // + public: + // + + // + // Constructor ... + void XCSupportZone() + { + } + + // + // Deconstructor ... + void ~XCSupportZone() + { + } + + // + // Tools ... + + /** + * Initialize POI ... + * + * @param bar: XOHCL instance ... + * @param range: Integer, Detection Range ... + * + * @return ( bool ) + */ + bool Init( + XOHCL &bar, + int range = 0, + bool useRangeAsStart = false // + ) + { + // + bool result = false; + + // + result = bar.IsValid(); + if (!result) + { + return result; + } + + // + result = InitBarZone( + bar, + X_POI_SUPPORT_ZONE, + X_PRICE_DOWN, + X_PRICE_LOW // + ); + if (!result) + { + return result; + } + + // + result = IsValid(); + if (result && + range > 0) + { + // + datetime time = bar.time; + int periodSeconds = PeriodSeconds(bar.period); + + // + datetime from = + !useRangeAsStart + ? (datetime)((int)time - (range * periodSeconds)) + : time; + datetime to = (datetime)((int)time + (range * periodSeconds)); + + // + From(from); + To(to); + } + + // + return result; + } + + // + // Getter(s) / Setter(s) ... + + // + // Overrides ... + + bool IsValid() override + { + // + bool result = false; + + // + result = IsValidBarZone() && + mType == X_POI_SUPPORT_ZONE; + + // + return result; + } + + // + protected: + // + + // + private: + // + + // +}; + +// +// Resistance Zone ... +class XCResistanceZone : public XCBarZone +{ + // + public: + // + + // + // Constructor ... + void XCResistanceZone() + { + } + + // + // Deconstructor ... + void ~XCResistanceZone() + { + } + + // + // Tools ... + + /** + * Initialize POI ... + * + * @param bar: XOHCL instance ... + * @param range: Integer, Detection Range ... + * + * @return ( bool ) + */ + bool Init( + XOHCL &bar, + int range = 0, + bool useRangeAsStart = false // + ) + { + // + bool result = false; + + // + result = bar.IsValid(); + if (!result) + { + return result; + } + + // + result = InitBarZone( + bar, + X_POI_RESISTANCE_ZONE, + X_PRICE_HIGH, + X_PRICE_UP // + ); + if (!result) + { + return result; + } + + // + result = IsValid(); + if (result && + range > 0) + { + // + datetime time = bar.time; + int periodSeconds = PeriodSeconds(bar.period); + + // + datetime from = + !useRangeAsStart + ? (datetime)((int)time - (range * periodSeconds)) + : time; + datetime to = (datetime)((int)time + (range * periodSeconds)); + + // + From(from); + To(to); + } + + // + return result; + } + + // + // Getter(s) / Setter(s) ... + + // + // Overrides ... + + bool IsValid() override + { + // + bool result = false; + + // + result = IsValidBarZone() && + mType == X_POI_RESISTANCE_ZONE; + + // + return result; + } + + // + protected: + // + + // + private: + // + + // +}; + +// +// Order Block ... +class XCOrderBlock : public XCBarZone +{ + // + public: + // + + // + // Constructor ... + void XCOrderBlock() + { + } + + // + // Deconstructor ... + void ~XCOrderBlock() + { + } + + // + // Tools ... + + /** + * Initialize POI ... + * + * @param bar: XOHCL instance ... + * @param dir: ENUM_X_DIRECTION member ... + * + * @return ( bool ) + */ + bool Init( + XOHCL &bar, + ENUM_X_DIRECTION dir // + ) + { + // + bool result = false; + + // + result = bar.IsValid() && + (dir == X_DIRECTION_BULLISH || + dir == X_DIRECTION_BEARISH); + if (!result) + { + return result; + } + + // + ENUM_XPOIS mTT = + IsSpecifiedBullish(dir) + ? X_POI_BULLISH_ORDERBLOCK + : X_POI_BEARISH_ORDERBLOCK; + + // + result = InitBarZone( + bar, + mTT, + X_PRICE_HIGH, + X_PRICE_LOW // + ); + if (!result) + { + return result; + } + + // + result = IsValid(); + + // + return result; + } + + // + // Getter(s) / Setter(s) ... + + /** + * Check is Bullish ... + * + * @return ( bool ) + */ + bool IsBullish() + { + // + bool result = false; + + // + result = IsValid() && + Type() == X_POI_BULLISH_ORDERBLOCK; + + // + return result; + } + + /** + * Check is Bearish ... + * + * @return ( bool ) + */ + bool IsBearish() + { + // + bool result = false; + + // + result = IsValid() && + Type() == X_POI_BEARISH_ORDERBLOCK; + + // + return result; + } + + ENUM_X_DIRECTION GetDirection() + { + // + ENUM_X_DIRECTION result = X_DIRECTION_NONE; + + // + if (!IsValid()) + { + return result; + } + + // + result = + IsBullish() + ? X_DIRECTION_BULLISH + : X_DIRECTION_BEARISH; + + // + return result; + } + + // + // Overrides ... + + bool IsValid() override + { + // + bool result = false; + + // + result = IsValidBarZone() && + (mType == X_POI_BULLISH_ORDERBLOCK || + mType == X_POI_BEARISH_ORDERBLOCK); + + // + return result; + } + + // + protected: + // + + // + private: + // + + // +}; + +// +// Rejection Bar ... +class XCRejectionBar : public XCBarZone +{ + // + public: + // + + // + // Constructor ... + void XCRejectionBar() + { + } + + // + // Deconstructor ... + void ~XCRejectionBar() + { + } + + // + // Tools ... + + /** + * Initialize POI ... + * + * @param bar: XOHCL instance ... + * + * @return ( bool ) + */ + bool Init( + XOHCL &bar // + ) + { + // + bool result = false; + + // + result = bar.IsValid(); + if (!result) + { + return result; + } + + // + bool isBullish = + bar.GetLowShadow() > bar.GetHighShadow(); + bool isBearish = + bar.GetHighShadow() > bar.GetLowShadow(); + result = isBullish || + isBearish; + if (!result) + { + return result; + } + + // + ENUM_X_PRICE upPrice = isBullish + ? X_PRICE_HIGH + : X_PRICE_DOWN; + // + ENUM_X_PRICE loPrice = isBullish + ? X_PRICE_UP + : X_PRICE_LOW; + + // + result = InitBarZone( + bar, + X_POI_REJECTION_BAR, + upPrice, + loPrice // + ); + if (!result) + { + return result; + } + + // + result = IsValid(); + + // + return result; + } + + // + // Getter(s) / Setter(s) ... + + /** + * Check is Bullish ... + * + * @return ( bool ) + */ + bool IsBullish() + { + // + bool result = false; + + // + result = IsValid() && + Type() == X_POI_REJECTION_BAR && + mBar.GetLowShadow() > mBar.GetHighShadow(); + + // + return result; + } + + /** + * Check is Bearish ... + * + * @return ( bool ) + */ + bool IsBearish() + { + // + bool result = false; + + // + result = IsValid() && + Type() == X_POI_REJECTION_BAR && + mBar.GetHighShadow() > mBar.GetLowShadow(); + + // + return result; + } + + // + // Overrides ... + + bool IsValid() override + { + // + bool result = false; + + // + result = IsValidBarZone() && + mType == X_POI_REJECTION_BAR; + + // + return result; + } + + // + protected: + // + + // + private: + // + + // +}; + +// +// Momentum Bar ... +class XCMomentumBar : public XCBarZone +{ + // + public: + // + + // + // Constructor ... + void XCMomentumBar() + { + } + + // + // Deconstructor ... + void ~XCMomentumBar() + { + } + + // + // Tools ... + + /** + * Initialize POI ... + * + * @param bar: XOHCL instance ... + * + * @return ( bool ) + */ + bool Init( + XOHCL &bar // + ) + { + // + bool result = false; + + // + result = bar.IsValid(); + if (!result) + { + return result; + } + + // + bool isBullish = bar.IsBullish(); + bool isBearish = bar.IsBearish(); + result = isBullish || + isBearish; + if (!result) + { + return result; + } + + // + result = InitBarZone( + bar, + X_POI_MOMENTUM_BAR, + X_PRICE_HIGH, + X_PRICE_LOW // + ); + if (!result) + { + return result; + } + + // + result = IsValid(); + + // + return result; + } + + // + // Getter(s) / Setter(s) ... + + /** + * Check is Bullish ... + * + * @return ( bool ) + */ + bool IsBullish() + { + // + bool result = false; + + // + result = IsValid() && + mBar.IsBullish() && + Type() == X_POI_MOMENTUM_BAR; + + // + return result; + } + + /** + * Check is Bearish ... + * + * @return ( bool ) + */ + bool IsBearish() + { + // + bool result = false; + + // + result = IsValid() && + mBar.IsBearish() && + Type() == X_POI_MOMENTUM_BAR; + + // + return result; + } + + // + // Overrides ... + + bool IsValid() override + { + // + bool result = false; + + // + result = IsValidBarZone() && + mType == X_POI_MOMENTUM_BAR; + + // + return result; + } + + // + protected: + // + + // + private: + // + + // +}; + +// +// Fair Value Gap ... +class XCFVG : public XCTwoBarZone +{ + // + public: + // + + // + // Constructor ... + void XCFVG() + { + } + + // + // Deconstructor ... + void ~XCFVG() + { + } + + // + // Tools ... + + /** + * Initialize POI ... + * + * @param startBar: XOHCL instance ... + * @param endBar: XOHCL instance ... + * @param dir: ENUM_X_DIRECTION member ... + * + * @return ( bool ) + */ + bool Init( + XOHCL &startBar, + XOHCL &endBar, + ENUM_X_DIRECTION dir // + ) + { + // + bool result = false; + + // + result = endBar.IsValid() && + startBar.IsValid() && + (dir == X_DIRECTION_BULLISH || + dir == X_DIRECTION_BEARISH); + if (!result) + { + return result; + } + + // + bool isDirBullish = IsSpecifiedBullish(dir); + ENUM_XPOIS mTT = + isDirBullish + ? X_POI_BULLISH_FVG + : X_POI_BEARISH_FVG; + + // + ENUM_X_PRICE startPrice = isDirBullish + ? X_PRICE_HIGH + : X_PRICE_LOW; + ENUM_X_PRICE endPrice = isDirBullish + ? X_PRICE_LOW + : X_PRICE_HIGH; + + // + result = InitTwoBarZone( + startBar, + endBar, + mTT, + startPrice, + endPrice // + ); + if (!result) + { + return result; + } + + // + result = IsValid(); + + // + return result; + } + + // + // Getter(s) / Setter(s) ... + + /** + * Check is Bullish ... + * + * @return ( bool ) + */ + bool IsBullish() + { + // + bool result = false; + + // + result = IsValid() && + Type() == X_POI_BULLISH_FVG; + + // + return result; + } + + /** + * Check is Bearish ... + * + * @return ( bool ) + */ + bool IsBearish() + { + // + bool result = false; + + // + result = IsValid() && + Type() == X_POI_BEARISH_FVG; + + // + return result; + } + + ENUM_X_DIRECTION GetDirection() + { + // + ENUM_X_DIRECTION result = X_DIRECTION_NONE; + + // + if (!IsValid()) + { + return result; + } + + // + result = + IsBullish() + ? X_DIRECTION_BULLISH + : X_DIRECTION_BEARISH; + + // + return result; + } + + // + // Overrides ... + + bool IsValid() override + { + // + bool result = false; + + // + result = IsValidTwoBarZone() && + (mType == X_POI_BULLISH_FVG || + mType == X_POI_BEARISH_FVG); + + // + return result; + } + + // + protected: + // + + // + private: + // + + // +}; + +// +// Ticks Zones ... + +// +class XCTickZone : public CObject +{ + // + // Public ... + public: + // + // Props ... + string symbol; + ENUM_TIMEFRAMES period; + + // + double high; + double low; + int ticks; + double percent; + + // + ulong volume; + double volumePercent; + + // + // Compare Two Zone With Each Other ... + virtual int Compare( + const CObject *node, + const int mode = 0 // + ) const + { + // + const XCTickZone *other = (XCTickZone *)node; + + // + return other.ticks - ticks; + } + + // + bool IsValid() + { + // + bool result = false; + + // + result = high > 0 && + low > 0 && + high > low && + ticks > 0 && + percent > 0; + + // + return result; + } + + // + // Protected ... + protected: + // + // Private ... + private: + // +}; + +// +class XCTicksZone : public XCTwoBarZone +{ + // + public: + // + + // + // Constructor ... + void XCTicksZone() + { + Default(); + } + + // + // Deconstructor ... + void ~XCTicksZone() + { + } + + // + // Getter(s) / Setter(s) ... + + /** + * Get Number of Ticks Levels ... + * + * @return ( int ) + */ + int Levels() + { + return mLevels; + } + + /** + * Set Number of Ticks Levels ... + * + * @return ( int ) + */ + void Levels(int value) + { + // + if (value < 2) + { + value = 2; + } + + // + mLevels = value; + } + + /** + * Apply Default Config ... + */ + virtual void Default() + { + // + Levels(10); + } + + // + // Tools ... + + /** + * Initialize POI ... + * + * @param startBar: XOHCL instance ... + * @param endBar: XOHCL instance ... + * + * @return ( bool ) + */ + bool Init( + XOHCL &startBar, + XOHCL &endBar, + ENUM_TIMEFRAMES forPeriod = NULL // + ) + { + // + bool result = false; + + // + result = endBar.IsValid() && + startBar.IsValid(); + if (!result) + { + return result; + } + + // + if (!IsSpecifiedValid(forPeriod)) + { + forPeriod = endBar.period; + } + + // + // Calculate Start and End Time ... + datetime from = startBar.time; + datetime to = endBar.time; + ulong fromM = ((ulong)to * 1000); + ulong toM = ((ulong)from * 1000); + + // + // Symbol and Period ... + string symbol = startBar.symbol; + ENUM_TIMEFRAMES period = startBar.period; + + // + // Prepare Zones Array ... + mZones.Clear(); + + // + // Retrieve Ticks between Times ... + SpecificClean(mTicks); + int res = CopyTicksRange( + symbol, + mTicks, + COPY_TICKS_ALL, + fromM, + toM // + ); + + // + // Ticks Volumes ... + int ticksVolumeCount = CopyTickVolume( + symbol, + forPeriod, + from, + to, + mTickVolumes // + ); + if (IsValidSize(ticksVolumeCount)) + { + // + mVolumes = 0; + for (int i = 0; i < ticksVolumeCount; i++) + { + mVolumes += mTickVolumes[i]; + } + } + + // + // Retrieve Highs ... + SpecificClean(mHighs); + CopyHigh( + symbol, + period, + from, + to, + mHighs // + ); + + // + // Retrieve Lows ... + SpecificClean(mLows); + CopyLow( + symbol, + period, + from, + to, + mLows // + ); + + // + // Find Highest Value in Range ... + int highIDX = ArrayMaximum(mHighs); + mRangeHigh = mHighs[highIDX]; + + // + // Find Lowest Value in Range ... + int lowIDX = ArrayMinimum(mLows); + mRangeLow = mLows[lowIDX]; + + // + datetime mTimes[]; + CopyTime( + symbol, + period, + from, + to, + mTimes // + ); + mRangeHighTime = mTimes[highIDX]; + mRangeLowTime = mTimes[lowIDX]; + + // + double mRangeSize = mRangeHigh - mRangeLow; + + // + // Create Zones ... + for (int i = 0; i < Levels(); i++) + { + // + // Instance a New Zone ... + XCTickZone *iZone = new XCTickZone(); + + // + iZone.symbol = symbol; + iZone.period = period; + + // + // Calculate Each Zones High / Low based on Range ... + double iH = mRangeHigh - mRangeSize * i / Levels(); + double iL = mRangeHigh - mRangeSize * (i + 1) / Levels(); + + // + // Set Zone High Low Properties ... + iZone.low = iL; + iZone.high = iH; + + // + // Add Zone to Zone Array Objects ... + mZones.Add(iZone); + } + + // + // Calculate Each Zone Ticks ... + int ticksCount = ArraySize(mTicks); + for (int i = 0; i < ticksCount; i++) + { + // + // Retrieve Tick ... + MqlTick iTick = mTicks[i]; + + // + // Loop through Zones ... + for (int j = 0; j < Levels(); j++) + { + // + // Rejrieve j indexed Zone Object ... + XCTickZone *jZone = mZones.At(j); + + // + bool isInRange = IsTickInZoneRange( + iTick, + jZone // + ); + if (isInRange) + { + // + jZone.ticks++; + break; + } + } + } + + // + // Calculating Zone Percents ... + for (int i = 0; i < Levels(); i++) + { + // + XCTickZone *iZone = mZones.At(i); + + // + double percent = CalculateZoneTickPercent(iZone); + iZone.percent = percent; + } + + // + // Sort Zones Based on Percents ... + mZones.Sort(); + + // + mUpper = mRangeHigh; + mLower = mRangeLow; + mType = X_POI_TICKS_ZONES; + mEndBar = endBar; + mStartBar = startBar; + From(endBar.time); + To(startBar.time); + + // + result = IsValid(); + if (!result) + { + return result; + } + + // + // Try to Find Out PERIOD_1M times in each zone ... + datetime to1M = (datetime)((int)endBar.time + PeriodSeconds(period) - 60); + int to1MIndex = iBarShift( + symbol, + forPeriod, + to1M // + ); + int from1MIndex = iBarShift( + symbol, + forPeriod, + from // + ); + for (int i = from1MIndex; i > to1MIndex; i--) + { + // + XOHCL iBar; + bool isInited = iBar.Init( + symbol, + forPeriod, + i // + ); + if (!isInited) + { + continue; + } + ulong iVolume = iTickVolume( + symbol, + forPeriod, + i // + ); + + // + // Loop through Zones ... + for (int j = 0; j < Levels(); j++) + { + // + XCTickZone *jZone = mZones.At(j); + if (!jZone.IsValid()) + { + continue; + } + + // + // Check iBar is Inside jZone ... + bool isIBarInside = + iBar.GetUp() < jZone.high && + iBar.GetDown() > jZone.low; + // iBar.low < jZone.high || + // iBar.high > jZone.low; + if (isIBarInside) + { + jZone.volume += iVolume; + } + } + } + + // + // Calculate Volume Percent ... + for (int i = 0; i < Levels(); i++) + { + // + XCTickZone *iZone = mZones.At(i); + + // + if (mVolumes > 0) + { + iZone.volumePercent = (double)(iZone.volume * 100 / mVolumes); + } + } + + // + return result; + } + + // + // Getter(s) / Setter(s) ... + + /** + * Retrieve Zones Count ... + * + * @return ( int ) + */ + int Count() + { + return mZones.Total(); + } + + /** + * Retrieve Specified Sorted Zones ... + * + * @param index: Integer ... + * + * @return ( XCTickZone * ) + */ + XCTickZone *GetZone(int index) + { + // + if (!IsValidIndex(index)) + { + return NULL; + } + + // + return mZones.At(index); + } + + /** + * Calculate Liquidity Percent for Specified Direction ... + * + * @param forDirection: ENUM_X_DIRECTION member, Specified Liquidity ... + * @param price: Double, Specified Price ... + * + * @return ( double ) + */ + double CalculateLiquidityPercent( + ENUM_X_DIRECTION forDirection, + double price // + ) + { + // + double result = 0; + + // + int count = Count(); + if (price <= 0 || + !IsValid() || + !IsValidSize(count) || + forDirection == X_DIRECTION_ALL || + forDirection == X_DIRECTION_NONE) + { + return result; + } + + // + bool isBullish = forDirection == X_DIRECTION_BULLISH; + + // + for (int i = 0; i < count; i++) + { + // + XCTickZone *iZone = GetZone(i); + + // + if (iZone.IsValid()) + { + // + result += !isBullish && + price > iZone.high + ? iZone.percent + : isBullish && + price < iZone.low + ? iZone.percent + : 0; + } + } + + // + return result; + } + + // + // Overrides ... + bool IsValid() override + { + // + bool result = false; + + // + result = + IsValidFrom() && + IsValidTwoBarZone() && + Levels() > 0 && + mZones.Total() == Levels() && + mRangeHigh > 0 && + mRangeLow > 0; + + // + return result; + } + + // + protected: + // + + // + private: + // + // Props ... + + // + MqlTick mTicks[]; + double mHighs[]; + double mLows[]; + ulong mVolumes; + ulong mTickVolumes[]; + double mRangeHigh; + datetime mRangeHighTime; + double mRangeLow; + datetime mRangeLowTime; + + // + int mLevels; // Number of Ticks Levels ... + + // + CArrayObj mZones; + + /** + * Check a Tick is in a Zone rage or not ... + * + * @param tick: MqlTick instance ... + * @param zone: XCTickZone instance ... + * + * @return ( bool ) + */ + bool IsTickInZoneRange( + MqlTick &tick, + XCTickZone *zone // + ) + { + // + bool result = false; + + // + result = + // + tick.bid >= zone.low && + tick.bid <= zone.high + // + ; + + // + return result; + } + + /** + * Calculate Zone Tick Percent ... + * + * @param zone: XCTickZone instance ... + * @param normalizationDigits: Integer ... + * + * @return ( double ) + */ + double CalculateZoneTickPercent( + XCTickZone *zone, + int normalizationDigits = 2 // + ) + { + // + double result = 0; + + // + if (normalizationDigits < 2 || normalizationDigits > 5) + { + normalizationDigits = 2; + } + + // + int ticksCount = ArraySize(mTicks); + if (ticksCount <= 0) + { + return result; + } + + // + result = (double)zone.ticks / ticksCount * 100; + result = NormalizeDouble(result, normalizationDigits); + + // + return result; + } + + // +}; + +// +// Trading Day ... +class XCDay : public XCFromToZone +{ + // + public: + // + + // + // Constructor ... + void XCDay() + { + } + + // + // Deconstructor ... + void ~XCDay() + { + } + + // + // Tools ... + + /** + * Initialize POI ... + * + * @return ( bool ) + */ + bool Init() + { + // + bool result = false; + + // + result = IsValid(); + + // + return result; + } + + // + // Getter(s) / Setter(s) ... + + // + // Overrides ... + + // + protected: + // + + // + private: + // + + // +}; + +// +// Trading Session ... +class XCSession : public XCFromToZone +{ + // + public: + // + + // + // Constructor ... + void XCSession() + { + } + + // + // Deconstructor ... + void ~XCSession() + { + } + + // + // Tools ... + + /** + * Initialize POI ... + * + * @return ( bool ) + */ + bool Init() + { + // + bool result = false; + + // + result = IsValid(); + + // + return result; + } + + // + // Getter(s) / Setter(s) ... + + // + // Overrides ... + + // + protected: + // + + // + private: + // + + // +}; + +// +struct XBoxZone +{ + // + // Props ... + string symbol; + ENUM_TIMEFRAMES period; + + // + double upper; + double lower; + + // + datetime from; + datetime to; + + // + string type; + ENUM_X_DIRECTION dir; + + // + // Constructor ... + XBoxZone() + { + Clean(); + } + + // + // Tools ... + + /** + * Cleanup Model ... + */ + void Clean() + { + // + upper = 0; + lower = 0; + to = NULL; + from = NULL; + symbol = NULL; + period = NULL; + dir = X_DIRECTION_NONE; + + // + ZeroMemory(this); + } + + /** + * Validate Model ... + * + * @return ( bool ) + */ + bool IsValid() + { + // + bool result = false; + + // + result = + // + upper > 0 && + lower > 0 && + from < to && + IsValid(to) && + upper >= lower && + IsValid(from) && + IsValid(symbol) && + IsValid(period) + // + ; + + // + return result; + } + + /** + * Check Box is Bullish or not ... + * + * @return ( bool ) + */ + bool IsBullish() + { + return IsValid() && + IsBullish(dir); + } + + /** + * Check Box is Bearish or not ... + * + * @return ( bool ) + */ + bool IsBearish() + { + return IsValid() && + IsBearish(dir); + } + + /** + * Check Box is Same as Other ... + * + * @param item: XBoxZone instance Resource ... + * + * @return ( bool ) + */ + bool IsSameAs(XBoxZone &item) + { + // + return IsValid() && + item.IsValid() && + dir == item.dir && + from == item.from && + type == item.type && + lower == item.lower && + upper == item.upper && + symbol == item.symbol && + period == item.period; + } + + /** + * Retrieve Box Age ... + * + * @param forPeriod: ENUM_TIMEFRAMES member ... + * + * @return ( int ) + */ + int GetAge( + ENUM_TIMEFRAMES forPeriod = NULL // + ) + { + // + int result = 0; + + // + if (!IsValid()) + { + return result; + } + + // + if (!IsValid(forPeriod)) + { + forPeriod = period; + } + + // + result = iBarShift( + symbol, + forPeriod, + from // + ); + + // + return result; + } + + /** + * To Bar Index ... + * + * @return ( int ) + */ + int ToIndex( + ENUM_TIMEFRAMES forPeriod = NULL // + ) + { + // + int result = -1; + + // + if (!IsValid()) + { + return result; + } + + // + if (!IsValid(forPeriod)) + { + forPeriod = period; + } + + // + result = GetBarIndex( + symbol, + forPeriod, + to // + ); + + // + return result; + } + + /** + * From Bar Index ... + * + * @return ( int ) + */ + int FromIndex( + ENUM_TIMEFRAMES forPeriod = NULL // + ) + { + // + int result = -1; + + // + if (!IsValid()) + { + return result; + } + + // + if (!IsValid(forPeriod)) + { + forPeriod = period; + } + + // + result = GetBarIndex( + symbol, + forPeriod, + from // + ); + + // + return result; + } + + /** + * Retrieve Unique Identifier ... + * + * @return ( string ) + */ + string GetTag() + { + // + int digits = GetDigits(symbol); + double nUpper = NormalizeDouble(NormalizePrice(upper, symbol), digits); + double nLower = NormalizeDouble(NormalizePrice(lower, symbol), digits); + + // + string typeStr = IsValid(type) + ? type + : "XBOX"; + string result = + // + typeStr + "_" + + ToString(dir) + "_" + + symbol + "_" + + ToString(period) + "_" + + ToString(nUpper) + "_" + + ToString(nLower) + // + ; + + // + return result; + } +}; + +// diff --git a/BKPS/14040203/Libraries/x-saherelm.x-poi.state.lib.mq5 b/BKPS/14040203/Libraries/x-saherelm.x-poi.state.lib.mq5 new file mode 100644 index 0000000..3279865 --- /dev/null +++ b/BKPS/14040203/Libraries/x-saherelm.x-poi.state.lib.mq5 @@ -0,0 +1,4677 @@ + +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Seriallize Library +// --------------------------------------- +// Name: XPOILib +// Description: All models related to POIs ... +// +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +////////////////////////////////////////////////////// +// +// Global Properties ... +#property library +#property copyright "Copyright `023, SaherElm IT Center" +#property link "https://www.saherelm.ir" +#property version "1.00" +#property strict + +// +// Imports ... +#include "../Libraries/x-saherelm.x-poi.extensions.lib.mq5" +#include "../Libraries/x-saherelm.x-poi.lib.mq5" + +// +enum ENUM_X_OBFVG_FVG_FILTERS +{ + X_OBFVG_FVG_FILTER_NONE, + X_OBFVG_FVG_FILTER_INSIDE_OR, + X_OBFVG_FVG_FILTER_ABOVE_BELOW, +}; + +// +enum ENUM_X_OBFVG_FVG_SELECTION +{ + X_OBFVG_FVG_SELECT_NONE, + X_OBFVG_FVG_SELECT_OLDEST, + X_OBFVG_FVG_SELECT_LOWEST, + X_OBFVG_FVG_SELECT_HIGHEST, + X_OBFVG_FVG_SELECT_YOUNGEST, + X_OBFVG_FVG_SELECT_HIGHEST_LOWEST, + X_OBFVG_FVG_SELECT_LOWEST_HIGHEST, +}; + +// +struct XSignalBox +{ + // + XBoxZone ob; + XBoxZone fvg; + XBoxZone sharp; + + // + double sl; + double tp; + + // + // Constructor ... + XSignalBox() + { + Clean(); + } + + // + // Tools ... + + /** + * Cleanup Model ... + */ + void Clean() + { + // + sl = 0; + tp = 0; + + // + ob.Clean(); + fvg.Clean(); + sharp.Clean(); + } + + /** + * Validate Model ... + * + * @return ( bool ) + */ + bool IsValid() + { + // + bool result = false; + + // + result = + ob.IsValid() && + fvg.IsValid() && + sharp.IsValid(); + + // + return result; + } + + /** + * Update Structure Models To Date ... + * + * @param value: datetime ... + */ + void UpdateTo(datetime value = NULL) + { + // + value = NormalizeTime(value); + + // + if (ob.IsValid()) + { + ob.to = value; + } + + // + if (fvg.IsValid()) + { + fvg.to = value; + } + + // + if (sharp.IsValid()) + { + sharp.to = value; + } + } + + // +}; + +// +// Model State Parsing ... +struct XPOIStateEvents +{ + // + // Props ... + + // + // Swings ... + bool hasNewSwing; + bool hasNewSwingLow; + bool hasNewSwingHigh; + + // + // Momentums ... + bool hasNewMomentum; + bool hasNewBullishMomentum; + bool hasNewBearishMomentum; + + // + // Rejections ... + bool hasNewRejection; + bool hasNewBullishRejection; + bool hasNewBearishRejection; + + // + // Pullbacks ... + bool hasNewPullback; + bool hasNewBullishPullback; + bool hasNewBearishPullback; + + // + // Support/Resistance (s) ... + bool hasNewSupportZone; + bool hasNewResistanceZone; + + // + // Supply/Demand (s) ... + bool hasNewSupplyZone; + bool hasNewDemandZone; + + // + // Fair Value Gaps ... + bool hasNewFairValueGap; + bool hasNewBullishFairValueGap; + bool hasNewBearishFairValueGap; + + // + // Order Blocks ... + bool hasNewOrderBlock; + bool hasNewBullishOrderBlock; + bool hasNewBearishOrderBlock; + + // + // Spikes ... + bool hasNewSpike; + bool hasNewBullishSpike; + bool hasNewBearishSpike; + + // + // Sharps ... + bool hasNewSharp; + bool hasNewBullishSharp; + bool hasNewBearishSharp; + + // + // Consolidation Zones ... + bool hasNewConsolidationZone; + bool hasNewBullishConsolidationZone; + bool hasNewBearishConsolidationZone; + + // + // Constructor ... + XPOIStateEvents() + { + Clean(); + } + + // + // Tools ... + + /** + * Cleanup Model ... + */ + void Clean() + { + // + hasNewSwing = false; + hasNewSwingLow = false; + hasNewSwingHigh = false; + + // + hasNewMomentum = false; + hasNewBullishMomentum = false; + hasNewBearishMomentum = false; + + // + hasNewRejection = false; + hasNewBullishRejection = false; + hasNewBearishRejection = false; + + // + hasNewSupportZone = false; + hasNewResistanceZone = false; + + // + hasNewSupplyZone = false; + hasNewDemandZone = false; + + // + hasNewFairValueGap = false; + hasNewBullishFairValueGap = false; + hasNewBearishFairValueGap = false; + + // + hasNewOrderBlock = false; + hasNewBullishOrderBlock = false; + hasNewBearishOrderBlock = false; + + // + hasNewSpike = false; + hasNewBullishSpike = false; + hasNewBearishSpike = false; + + // + hasNewSharp = false; + hasNewBullishSharp = false; + hasNewBearishSharp = false; + + // + hasNewConsolidationZone = false; + hasNewBullishConsolidationZone = false; + hasNewBearishConsolidationZone = false; + + // + ZeroMemory(this); + } + + /** + * Initialize Event Parser Model ... + * + * @param events: ENUM_XPOI_EVENTS members Collection Reference ... + */ + void Init(ENUM_XPOI_EVENTS &events[]) + { + // + hasNewSwing = HasNewSwing(events); + hasNewSwingLow = HasNewSwingLow(events); + hasNewSwingHigh = HasNewSwingHigh(events); + + // + hasNewMomentum = HasNewMomentum(events); + hasNewBullishMomentum = HasNewBullishMomentum(events); + hasNewBearishMomentum = HasNewBearishMomentum(events); + + // + hasNewRejection = HasNewRejection(events); + hasNewBullishRejection = HasNewBullishRejection(events); + hasNewBearishRejection = HasNewBearishRejection(events); + + // + hasNewPullback = HasNewPullback(events); + hasNewBullishPullback = HasNewBullishPullback(events); + hasNewBearishPullback = HasNewBearishPullback(events); + + // + hasNewSupportZone = HasNewSupportZone(events); + hasNewResistanceZone = HasNewResistanceZone(events); + + // + hasNewSupplyZone = HasNewSupplyZone(events); + hasNewDemandZone = HasNewDemandZone(events); + + // + hasNewFairValueGap = HasNewFairValueGap(events); + hasNewBullishFairValueGap = HasNewBullishFairValueGap(events); + hasNewBearishFairValueGap = HasNewBearishFairValueGap(events); + + // + hasNewOrderBlock = HasNewOrderBlock(events); + hasNewBullishOrderBlock = HasNewBullishOrderBlock(events); + hasNewBearishOrderBlock = HasNewBearishOrderBlock(events); + + // + hasNewSpike = HasNewSpike(events); + hasNewBullishSpike = HasNewBullishSpike(events); + hasNewBearishSpike = HasNewBearishSpike(events); + + // + hasNewSharp = HasNewSharp(events); + hasNewBullishSharp = HasNewBullishSharp(events); + hasNewBearishSharp = HasNewBearishSharp(events); + + // + hasNewConsolidationZone = HasNewConsolidationZone(events); + hasNewBullishConsolidationZone = HasNewBullishConsolidationZone(events); + hasNewBearishConsolidationZone = HasNewBearishConsolidationZone(events); + } + + // +}; + +// +// Model Exists Founded POIs ... +struct XPOIState +{ + // + string symbol; + ENUM_TIMEFRAMES period; + datetime time; + + // + XCSwing *swings[]; // Holds Founded Swing ... + XCSwing *swingLows[]; // Holds Founded Swing Lows ... + XCSwing *swingHighs[]; // Holds Founded Swing Highs ... + + // + XCMomentumBar *momentums[]; // Holds Founded Momentum Bars ... + XCMomentumBar *bullishMomentums[]; // Holds Founded Bullish Momentum Bars ... + XCMomentumBar *bearishMomentums[]; // Holds Founded Bearish Momentum Bars ... + + // + XCRejectionBar *rejections[]; // Holds Founded Rejection Bars ... + XCRejectionBar *bullishRejections[]; // Holds Founded Bullish Rejection Bars ... + XCRejectionBar *bearishRejections[]; // Holds Founded Bearish Rejection Bars ... + + // + XCSupportZone *supportZones[]; // Holds Founded Support Zones ... + XCResistanceZone *resistanceZones[]; // Holds Founded Resistance Zones ... + + // + XCSupplyZone *supplyZones[]; // Holds Founded Supply Zones ... + XCDemandZone *demandZones[]; // Holds Founded Demand Zones ... + + // + XCOrderBlock *orderBlocks[]; // Holds Founded Order Blocks ... + XCOrderBlock *bullishOrderBlocks[]; // Holds Founded Bullish Order Blocks ... + XCOrderBlock *bearishOrderBlocks[]; // Holds Founded Bearish Order Blocks ... + + // + XCFVG *fairValueGaps[]; // Holds Founded Fair Value Gaps ... + XCFVG *bullishFairValueGaps[]; // Holds Founded Bullish Fair Value Gaps ... + XCFVG *bearishFairValueGaps[]; // Holds Founded Bearish Fair Value Gaps ... + + // + XConsolidationZone consolidationZones[]; // Holds Founded Consolidation Zones ... + XConsolidationZone bullishConsolidationZones[]; // Holds Founded Bullish Consolidation Zones ... + XConsolidationZone bearishConsolidationZones[]; // Holds Founded Bearih Consolidation Zones ... + + // + XBoxZone spikes[]; // Holds Founded Spikes ... + XBoxZone bullishSpikes[]; // Holds Founded Bullish Spikes ... + XBoxZone bearishSpikes[]; // Holds Founded Bearih Spikes ... + + // + XBoxZone sharps[]; // Holds Founded Sharps ... + XBoxZone bullishSharps[]; // Holds Founded Bullish Sharps ... + XBoxZone bearishSharps[]; // Holds Founded Bearih Sharps ... + + // + XBoxZone pullbacks[]; // Holds Founded Pullbacks ... + XBoxZone bullishPullbacks[]; // Holds Founded Bullish Pullbacks ... + XBoxZone bearishPullbacks[]; // Holds Founded Bearish Pullbacks ... + + // + // Constructor ... + void XPOIState() + { + Clean(); + } + + // + // Actions ... + + /** + * Cleanup all props ... + */ + void Clean() + { + // + time = NULL; + symbol = NULL; + period = NULL; + + // + // Swings ... + Clean(swings); + Clean(swingLows); + Clean(swingHighs); + + // + // Momentums ... + Clean(momentums); + Clean(bullishMomentums); + Clean(bearishMomentums); + + // + // Rejections ... + Clean(rejections); + Clean(bullishRejections); + Clean(bearishRejections); + + // + // Support / Resistance Zones ... + Clean(supportZones); + Clean(resistanceZones); + + // + // Supply / Demand Zones ... + Clean(supplyZones); + Clean(demandZones); + + // + // Fair Value Gaps ... + Clean(fairValueGaps); + Clean(bullishFairValueGaps); + Clean(bearishFairValueGaps); + + // + // Order Blocks ... + Clean(orderBlocks); + Clean(bullishOrderBlocks); + Clean(bearishOrderBlocks); + + // + // Spikes ... + Clean(spikes); + Clean(bullishSpikes); + Clean(bearishSpikes); + + // + // Sharps ... + Clean(sharps); + Clean(bullishSharps); + Clean(bearishSharps); + + // + // Pullbaks ... + Clean(pullbacks); + Clean(bullishPullbacks); + Clean(bearishPullbacks); + + // + // Consolidation Zones ... + Clean(consolidationZones); + Clean(bullishConsolidationZones); + Clean(bearishConsolidationZones); + + // + ZeroMemory(this); + } + + /** + * Validate ... + * + * @return ( bool ) + */ + bool IsValid() + { + // + bool result = false; + + // + result = + IsSpecifiedValid(symbol) && + IsSpecifiedValid(period) && + IsSpecifiedValid(time); + + // + return result; + } + + /** + * Check State has Childs or not ... + * + * @return ( bool ) + */ + bool HasChild() + { + // + bool result = false; + + // + result = + // + // Swings ... + HasSwings() || + HasSwingLows() || + HasSwingHighs() || + // + // Momentums ... + HasMomentums() || + HasBullishMomentums() || + HasBearishMomentums() || + // + // Rejections ... + HasRejections() || + HasBullishRejections() || + HasBearishRejections() || + // + // Pullbacks ... + HasPullbacks() || + HasBullishPullbacks() || + HasBearishPullbacks() || + // + // Support / Resistance Zones ... + HasSupportZones() || + HasResistanceZones() || + // + // Supply / Demand Zones ... + HasSupplyZones() || + HasDemandZones() || + // + // Fair Value Gaps ... + HasFairValueGaps() || + HasBullishFairValueGaps() || + HasBearishFairValueGaps() || + // + // Order Blocks ... + HasOrderBlocks() || + HasBullishOrderBlocks() || + HasBearishOrderBlocks() || + // + // Spikes ... + HasSpikes() || + HasBullishSpikes() || + HasBearishSpikes() || + // + // Sharps ... + HasSharps() || + HasBullishSharps() || + HasBearishSharps() || + // + // Consolidation Zones ... + HasConsolidationZones() || + HasBullishConsolidationZones() || + HasBearishConsolidationZones() + // + ; + + // + return result; + } + + // + // Checkers ... + + // + // Swings ... + + // + // Has ... + + // + bool HasSwings() + { + return HasChild(swings); + } + + // + bool HasSwingLows() + { + return HasChild(swingLows); + } + + // + bool HasSwingHighs() + { + return HasChild(swingHighs); + } + + // + // Count ... + + // + int CountSwings() + { + return ArraySize(swings); + } + + // + int CountSwingLows() + { + return ArraySize(swingLows); + } + + // + int CountSwingHighs() + { + return ArraySize(swingHighs); + } + + // + // Momentums ... + + // + // Has ... + + // + bool HasMomentums() + { + return HasChild(momentums); + } + + // + bool HasBullishMomentums() + { + return HasChild(bullishMomentums); + } + + // + bool HasBearishMomentums() + { + return HasChild(bearishMomentums); + } + + // + // Count ... + + // + int CountMomentums() + { + return ArraySize(momentums); + } + + // + int CountBullishMomentums() + { + return ArraySize(bullishMomentums); + } + + // + int CountBearishMomentums() + { + return ArraySize(bearishMomentums); + } + + // + // Rejections ... + + // + // Has ... + + // + bool HasRejections() + { + return HasChild(rejections); + } + + // + bool HasBullishRejections() + { + return HasChild(bullishRejections); + } + + // + bool HasBearishRejections() + { + return HasChild(bearishRejections); + } + + // + // Count ... + + // + int CountRejections() + { + return ArraySize(rejections); + } + + // + int CountBullishRejections() + { + return ArraySize(bullishRejections); + } + + // + int CountBearishRejections() + { + return ArraySize(bearishRejections); + } + + // + // Pullbacks ... + + // + // Has ... + + // + bool HasPullbacks() + { + return HasChild(pullbacks); + } + + // + bool HasBullishPullbacks() + { + return HasChild(bullishPullbacks); + } + + // + bool HasBearishPullbacks() + { + return HasChild(bearishPullbacks); + } + + // + // Count ... + + // + int CountPullbacks() + { + return ArraySize(pullbacks); + } + + // + int CountBullishPullbacks() + { + return ArraySize(bullishPullbacks); + } + + // + int CountBearishPullbacks() + { + return ArraySize(bearishPullbacks); + } + + // + // Support / Resistance Zones ... + + // + // Has ... + + // + bool HasSupportZones() + { + return HasChild(supportZones); + } + + // + bool HasResistanceZones() + { + return HasChild(resistanceZones); + } + + // + // Count ... + + // + int CountSupportZones() + { + return ArraySize(supportZones); + } + + // + int CountResistanceZones() + { + return ArraySize(resistanceZones); + } + + // + // Supply / Demand Zones ... + + // + // Has ... + + // + bool HasSupplyZones() + { + return HasChild(supplyZones); + } + + // + bool HasDemandZones() + { + return HasChild(demandZones); + } + + // + // Count ... + + // + int CountSupplyZones() + { + return ArraySize(supplyZones); + } + + // + int CountDemandZones() + { + return ArraySize(demandZones); + } + + // + // Fair Value Gaps ... + + // + // Has ... + + // + bool HasFairValueGaps() + { + return HasChild(fairValueGaps); + } + + // + bool HasBullishFairValueGaps() + { + return HasChild(bullishFairValueGaps); + } + + // + bool HasBearishFairValueGaps() + { + return HasChild(bearishFairValueGaps); + } + + // + // Count ... + + // + int CountFairValueGaps() + { + return ArraySize(fairValueGaps); + } + + // + int CountBullishFairValueGaps() + { + return ArraySize(bullishFairValueGaps); + } + + // + int CountBearishFairValueGaps() + { + return ArraySize(bearishFairValueGaps); + } + + // + // Order Blocks ... + + // + // Has ... + + // + bool HasOrderBlocks() + { + return HasChild(orderBlocks); + } + + // + bool HasBullishOrderBlocks() + { + return HasChild(bullishOrderBlocks); + } + + // + bool HasBearishOrderBlocks() + { + return HasChild(bearishOrderBlocks); + } + + // + // Count ... + + // + int CountOrderBlocks() + { + return ArraySize(orderBlocks); + } + + // + int CountBullishOrderBlocks() + { + return ArraySize(bullishOrderBlocks); + } + + // + int CountBearishOrderBlocks() + { + return ArraySize(bearishOrderBlocks); + } + + // + // Spikes ... + + // + // Has ... + + // + bool HasSpikes() + { + return HasChild(spikes); + } + + // + bool HasBullishSpikes() + { + return HasChild(bullishSpikes); + } + + // + bool HasBearishSpikes() + { + return HasChild(bearishSpikes); + } + + // + // Count ... + + // + int CountSpikes() + { + return ArraySize(spikes); + } + + // + int CountBullishSpikes() + { + return ArraySize(bullishSpikes); + } + + // + int CountBearishSpikes() + { + return ArraySize(bearishSpikes); + } + + // + // Sharps ... + + // + // Has ... + + // + bool HasSharps() + { + return HasChild(sharps); + } + + // + bool HasBullishSharps() + { + return HasChild(bullishSharps); + } + + // + bool HasBearishSharps() + { + return HasChild(bearishSharps); + } + + // + // Count ... + + // + int CountSharps() + { + return ArraySize(sharps); + } + + // + int CountBullishSharps() + { + return ArraySize(bullishSharps); + } + + // + int CountBearishSharps() + { + return ArraySize(bearishSharps); + } + + // + // Consolidation Zone ... + + // + // Has ... + + // + bool HasConsolidationZones() + { + return HasChild(consolidationZones); + } + + // + bool HasBullishConsolidationZones() + { + return HasChild(bullishConsolidationZones); + } + + // + bool HasBearishConsolidationZones() + { + return HasChild(bearishConsolidationZones); + } + + // + // Count ... + + // + int CountConsolidationZones() + { + return ArraySize(consolidationZones); + } + + // + int CountBullishConsolidationZones() + { + return ArraySize(bullishConsolidationZones); + } + + // + int CountBearishConsolidationZones() + { + return ArraySize(bearishConsolidationZones); + } + + // + // Box Retrievers ... + + // + int SupportResistancesAsBox(XBoxZone &items[]) + { + // + XBoxZone tmpBoxes[]; + + // + ToBox( + supportZones, + tmpBoxes // + ); + Copy( + tmpBoxes, + items, + false // + ); + Clean(tmpBoxes); + + // + ToBox( + resistanceZones, + tmpBoxes // + ); + Copy( + tmpBoxes, + items, + false // + ); + Clean(tmpBoxes); + + // + int result = ArraySize(items); + + // + return result; + } + + // + int SupplyDemandsAsBox(XBoxZone &items[]) + { + // + XBoxZone tmpBoxes[]; + + // + ToBox( + supplyZones, + tmpBoxes // + ); + Copy( + tmpBoxes, + items, + false // + ); + Clean(tmpBoxes); + + // + ToBox( + demandZones, + tmpBoxes // + ); + Copy( + tmpBoxes, + items, + false // + ); + Clean(tmpBoxes); + + // + int result = ArraySize(items); + + // + return result; + } + + // + int OrderBlocksAsBox(XBoxZone &items[]) + { + // + XBoxZone tmpBoxes[]; + + // + ToBox( + bullishOrderBlocks, + tmpBoxes // + ); + Copy( + tmpBoxes, + items, + false // + ); + Clean(tmpBoxes); + + // + ToBox( + bearishOrderBlocks, + tmpBoxes // + ); + Copy( + tmpBoxes, + items, + false // + ); + Clean(tmpBoxes); + + // + int result = ArraySize(items); + + // + return result; + } + + // + int FairValueGapsAsBox(XBoxZone &items[]) + { + // + XBoxZone tmpBoxes[]; + + // + ToBox( + bullishFairValueGaps, + tmpBoxes // + ); + Copy( + tmpBoxes, + items, + false // + ); + Clean(tmpBoxes); + + // + ToBox( + bearishFairValueGaps, + tmpBoxes // + ); + Copy( + tmpBoxes, + items, + false // + ); + Clean(tmpBoxes); + + // + int result = ArraySize(items); + + // + return result; + } + + // + int SpikesAsBox(XBoxZone &items[]) + { + // + Copy( + bullishSpikes, + items, + false // + ); + + // + Copy( + bearishSpikes, + items, + false // + ); + + // + int result = ArraySize(items); + + // + return result; + } + + // + int SharpsAsBox(XBoxZone &items[]) + { + // + Copy( + bullishSharps, + items, + false // + ); + + // + Copy( + bearishSharps, + items, + false // + ); + + // + int result = ArraySize(items); + + // + return result; + } + + // + // Tools ... + + // + void UpdateTo(datetime value = NULL) + { + // + value = NormalizeTime(value); + + // + int count = 0; + bool has = false; + + // + has = HasMomentums(); + if (has) + { + // + count = CountMomentums(); + for (int i = 0; i < count; i++) + { + momentums[i].To(value); + } + } + + // + has = HasBullishMomentums(); + if (has) + { + // + count = CountBullishMomentums(); + for (int i = 0; i < count; i++) + { + bullishMomentums[i].To(value); + } + } + + // + has = HasBearishMomentums(); + if (has) + { + // + count = CountBearishMomentums(); + for (int i = 0; i < count; i++) + { + bearishMomentums[i].To(value); + } + } + + // + has = HasRejections(); + if (has) + { + // + count = CountRejections(); + for (int i = 0; i < count; i++) + { + rejections[i].To(value); + } + } + + // + has = HasBullishRejections(); + if (has) + { + // + count = CountBullishRejections(); + for (int i = 0; i < count; i++) + { + bullishRejections[i].To(value); + } + } + + // + has = HasBearishRejections(); + if (has) + { + // + count = CountBearishRejections(); + for (int i = 0; i < count; i++) + { + bearishRejections[i].To(value); + } + } + + // + has = HasSupportZones(); + if (has) + { + // + count = CountSupportZones(); + for (int i = 0; i < count; i++) + { + supportZones[i].To(value); + } + } + + // + has = HasResistanceZones(); + if (has) + { + // + count = CountResistanceZones(); + for (int i = 0; i < count; i++) + { + resistanceZones[i].To(value); + } + } + + // + has = HasSupplyZones(); + if (has) + { + // + count = CountSupplyZones(); + for (int i = 0; i < count; i++) + { + supplyZones[i].To(value); + } + } + + // + has = HasDemandZones(); + if (has) + { + // + count = CountDemandZones(); + for (int i = 0; i < count; i++) + { + demandZones[i].To(value); + } + } + + // + has = HasOrderBlocks(); + if (has) + { + // + count = CountOrderBlocks(); + for (int i = 0; i < count; i++) + { + orderBlocks[i].To(value); + } + } + + // + has = HasBullishOrderBlocks(); + if (has) + { + // + count = CountBullishOrderBlocks(); + for (int i = 0; i < count; i++) + { + bullishOrderBlocks[i].To(value); + } + } + + // + has = HasBearishOrderBlocks(); + if (has) + { + // + count = CountBearishOrderBlocks(); + for (int i = 0; i < count; i++) + { + bearishOrderBlocks[i].To(value); + } + } + + // + has = HasFairValueGaps(); + if (has) + { + // + count = CountFairValueGaps(); + for (int i = 0; i < count; i++) + { + fairValueGaps[i].To(value); + } + } + + // + has = HasBullishFairValueGaps(); + if (has) + { + // + count = CountBullishFairValueGaps(); + for (int i = 0; i < count; i++) + { + bullishFairValueGaps[i].To(value); + } + } + + // + has = HasBearishFairValueGaps(); + if (has) + { + // + count = CountBearishFairValueGaps(); + for (int i = 0; i < count; i++) + { + bearishFairValueGaps[i].To(value); + } + } + + // + has = HasConsolidationZones(); + if (has) + { + // + count = CountConsolidationZones(); + for (int i = 0; i < count; i++) + { + consolidationZones[i].to = value; + } + } + + // + has = HasBullishConsolidationZones(); + if (has) + { + // + count = CountBullishConsolidationZones(); + for (int i = 0; i < count; i++) + { + bullishConsolidationZones[i].to = value; + } + } + + // + has = HasBearishConsolidationZones(); + if (has) + { + // + count = CountBearishConsolidationZones(); + for (int i = 0; i < count; i++) + { + bearishConsolidationZones[i].to = value; + } + } + + // + has = HasSpikes(); + if (has) + { + // + count = CountSpikes(); + for (int i = 0; i < count; i++) + { + spikes[i].to = value; + } + } + + // + has = HasBullishSpikes(); + if (has) + { + // + count = CountBullishSpikes(); + for (int i = 0; i < count; i++) + { + bullishSpikes[i].to = value; + } + } + + // + has = HasBearishSpikes(); + if (has) + { + // + count = CountBearishSpikes(); + for (int i = 0; i < count; i++) + { + bearishSpikes[i].to = value; + } + } + + // + has = HasSharps(); + if (has) + { + // + count = CountSharps(); + for (int i = 0; i < count; i++) + { + sharps[i].to = value; + } + } + + // + has = HasBullishSharps(); + if (has) + { + // + count = CountBullishSharps(); + for (int i = 0; i < count; i++) + { + bullishSharps[i].to = value; + } + } + + // + has = HasBearishSharps(); + if (has) + { + // + count = CountBearishSharps(); + for (int i = 0; i < count; i++) + { + bearishSharps[i].to = value; + } + } + } + + // + // Filter Zones ... + + // + // Support ... + int FilterSupportZones( + XCSupportZone *&dest[], + ENUM_TIMEFRAMES forPeriod = NULL, + // + // Start ... + ENUM_XZONE_STATE startState = XZONE_STATE_PASSED, + bool forceStartedBodyOut = false, + // + // Activation ... + ENUM_XZONE_STATE activeState = XZONE_STATE_FAILED, + bool forceActivatedBodyIn = false, + // + // Breaktion ... + ENUM_XZONE_STATE breakState = XZONE_STATE_FAILED, + bool forceBreakedBodyOut = false, + // + // Works ... + ENUM_XZONE_STATE workState = XZONE_STATE_FAILED, + bool forceWorkedBodyOut = false // + ) + { + // + int result = 0; + + // + int idx = -1; + int count = 0; + bool has = false; + + // + Clean(dest); + + // + if (!IsValid(forPeriod)) + { + forPeriod = period; + } + + // + has = IsValid() && + HasSupportZones(); + if (!has) + { + return result; + } + + // + XOHCL passedBar; + ENUM_X_DIRECTION passedDir = X_DIRECTION_NONE; + passedDir = X_DIRECTION_BULLISH; + count = CountSupportZones(); + for (int i = 0; i < count; i++) + { + // + XCSupportZone *iZone = supportZones[i]; + + // + // Check Started State ... + if (startState == XZONE_STATE_PASSED || + startState == XZONE_STATE_FAILED) + { + // + bool isBodyOut = false; + bool isStarted = iZone.IsStarted( + passedDir, + passedBar, + isBodyOut, + forPeriod // + ); + + // + bool isPassed = + startState == XZONE_STATE_FAILED + ? !isStarted + : !forceStartedBodyOut + ? isStarted + : isStarted && + isBodyOut; + + // + passedBar.Clean(); + if (!isPassed) + { + continue; + } + } + + // + // Check Activation State ... + if (activeState == XZONE_STATE_PASSED || + activeState == XZONE_STATE_FAILED) + { + // + bool isBodyIn = false; + bool isActivated = iZone.IsActivated( + passedDir, + passedBar, + isBodyIn, + forceStartedBodyOut, + forPeriod // + ); + + // + bool isPassed = + activeState == XZONE_STATE_FAILED + ? !isActivated + : !forceActivatedBodyIn + ? isActivated + : isActivated && + isBodyIn; + + // + passedBar.Clean(); + if (!isPassed) + { + continue; + } + } + + // + // Check Break State ... + if (breakState == XZONE_STATE_PASSED || + breakState == XZONE_STATE_FAILED) + { + // + bool isBodyOut = false; + bool isBreaked = iZone.IsBreaked( + passedDir, + passedBar, + isBodyOut, + forceStartedBodyOut, + forPeriod // + ); + + // + bool isPassed = + breakState == XZONE_STATE_FAILED + ? !isBreaked + : !forceBreakedBodyOut + ? isBreaked + : isBreaked && + isBodyOut; + + // + passedBar.Clean(); + if (!isPassed) + { + continue; + } + } + + // + // Check Work State ... + if (workState == XZONE_STATE_PASSED || + workState == XZONE_STATE_FAILED) + { + // + bool ignoreActivation = activeState != XZONE_STATE_PASSED; + + // + bool isBodyOut = false; + bool isWorked = iZone.IsWorked( + passedDir, + passedBar, + isBodyOut, + ignoreActivation, + forceStartedBodyOut, + forceActivatedBodyIn, + forPeriod // + ); + + // + bool isPassed = + workState == XZONE_STATE_FAILED + ? !isWorked + : !forceWorkedBodyOut + ? isWorked + : isWorked && + isBodyOut; + + // + passedBar.Clean(); + if (!isPassed) + { + continue; + } + } + + // + // Check Filtered Zone Doesn't Exists ... + has = FindIndex( + idx, + iZone, + dest // + ); + if (has) + { + // + passedBar.Clean(); + continue; + } + + // + Add( + iZone, + dest // + ); + + // + // End For ... + } + + // + result = ArraySize(dest); + + // + return result; + } + + // + // Resistance ... + int FilterResistanceZones( + XCResistanceZone *&dest[], + ENUM_TIMEFRAMES forPeriod = NULL, + // + // Start ... + ENUM_XZONE_STATE startState = XZONE_STATE_PASSED, + bool forceStartedBodyOut = false, + // + // Activation ... + ENUM_XZONE_STATE activeState = XZONE_STATE_FAILED, + bool forceActivatedBodyIn = false, + // + // Breaktion ... + ENUM_XZONE_STATE breakState = XZONE_STATE_FAILED, + bool forceBreakedBodyOut = false, + // + // Works ... + ENUM_XZONE_STATE workState = XZONE_STATE_FAILED, + bool forceWorkedBodyOut = false // + ) + { + // + int result = 0; + + // + int idx = -1; + int count = 0; + bool has = false; + + // + Clean(dest); + + // + if (!IsValid(forPeriod)) + { + forPeriod = period; + } + + // + has = IsValid() && + HasResistanceZones(); + if (!has) + { + return result; + } + + // + XOHCL passedBar; + ENUM_X_DIRECTION passedDir = X_DIRECTION_NONE; + passedDir = X_DIRECTION_BEARISH; + count = CountResistanceZones(); + for (int i = 0; i < count; i++) + { + // + XCResistanceZone *iZone = resistanceZones[i]; + + // + // Check Started State ... + if (startState == XZONE_STATE_PASSED || + startState == XZONE_STATE_FAILED) + { + // + bool isBodyOut = false; + bool isStarted = iZone.IsStarted( + passedDir, + passedBar, + isBodyOut, + forPeriod // + ); + + // + bool isPassed = + startState == XZONE_STATE_FAILED + ? !isStarted + : !forceStartedBodyOut + ? isStarted + : isStarted && + isBodyOut; + + // + passedBar.Clean(); + if (!isPassed) + { + continue; + } + } + + // + // Check Activation State ... + if (activeState == XZONE_STATE_PASSED || + activeState == XZONE_STATE_FAILED) + { + // + bool isBodyIn = false; + bool isActivated = iZone.IsActivated( + passedDir, + passedBar, + isBodyIn, + forceStartedBodyOut, + forPeriod // + ); + + // + bool isPassed = + activeState == XZONE_STATE_FAILED + ? !isActivated + : !forceActivatedBodyIn + ? isActivated + : isActivated && + isBodyIn; + + // + passedBar.Clean(); + if (!isPassed) + { + continue; + } + } + + // + // Check Break State ... + if (breakState == XZONE_STATE_PASSED || + breakState == XZONE_STATE_FAILED) + { + // + bool isBodyOut = false; + bool isBreaked = iZone.IsBreaked( + passedDir, + passedBar, + isBodyOut, + forceStartedBodyOut, + forPeriod // + ); + + // + bool isPassed = + breakState == XZONE_STATE_FAILED + ? !isBreaked + : !forceBreakedBodyOut + ? isBreaked + : isBreaked && + isBodyOut; + + // + passedBar.Clean(); + if (!isPassed) + { + continue; + } + } + + // + // Check Work State ... + if (workState == XZONE_STATE_PASSED || + workState == XZONE_STATE_FAILED) + { + // + bool ignoreActivation = activeState != XZONE_STATE_PASSED; + + // + bool isBodyOut = false; + bool isWorked = iZone.IsWorked( + passedDir, + passedBar, + isBodyOut, + ignoreActivation, + forceStartedBodyOut, + forceActivatedBodyIn, + forPeriod // + ); + + // + bool isPassed = + workState == XZONE_STATE_FAILED + ? !isWorked + : !forceWorkedBodyOut + ? isWorked + : isWorked && + isBodyOut; + + // + passedBar.Clean(); + if (!isPassed) + { + continue; + } + } + + // + // Check Filtered Zone Doesn't Exists ... + has = FindIndex( + idx, + iZone, + dest // + ); + if (has) + { + // + passedBar.Clean(); + continue; + } + + // + Add( + iZone, + dest // + ); + + // + // End For ... + } + + // + result = ArraySize(dest); + + // + return result; + } + + // + // Supply ... + int FilterSupplyZones( + XCSupplyZone *&dest[], + ENUM_TIMEFRAMES forPeriod = NULL, + // + // Start ... + ENUM_XZONE_STATE startState = XZONE_STATE_PASSED, + bool forceStartedBodyOut = false, + // + // Activation ... + ENUM_XZONE_STATE activeState = XZONE_STATE_FAILED, + bool forceActivatedBodyIn = false, + // + // Breaktion ... + ENUM_XZONE_STATE breakState = XZONE_STATE_FAILED, + bool forceBreakedBodyOut = false, + // + // Works ... + ENUM_XZONE_STATE workState = XZONE_STATE_FAILED, + bool forceWorkedBodyOut = false // + ) + { + // + int result = 0; + + // + int idx = -1; + int count = 0; + bool has = false; + + // + Clean(dest); + + // + if (!IsValid(forPeriod)) + { + forPeriod = period; + } + + // + has = IsValid() && + HasSupplyZones(); + if (!has) + { + return result; + } + + // + XOHCL passedBar; + ENUM_X_DIRECTION passedDir = X_DIRECTION_NONE; + passedDir = X_DIRECTION_BEARISH; + count = CountSupplyZones(); + for (int i = 0; i < count; i++) + { + // + XCSupplyZone *iZone = supplyZones[i]; + + // + // Check Started State ... + if (startState == XZONE_STATE_PASSED || + startState == XZONE_STATE_FAILED) + { + // + bool isBodyOut = false; + bool isStarted = iZone.IsStarted( + passedDir, + passedBar, + isBodyOut, + forPeriod // + ); + + // + bool isPassed = + startState == XZONE_STATE_FAILED + ? !isStarted + : !forceStartedBodyOut + ? isStarted + : isStarted && + isBodyOut; + + // + passedBar.Clean(); + if (!isPassed) + { + continue; + } + } + + // + // Check Activation State ... + if (activeState == XZONE_STATE_PASSED || + activeState == XZONE_STATE_FAILED) + { + // + bool isBodyIn = false; + bool isActivated = iZone.IsActivated( + passedDir, + passedBar, + isBodyIn, + forceStartedBodyOut, + forPeriod // + ); + + // + bool isPassed = + activeState == XZONE_STATE_FAILED + ? !isActivated + : !forceActivatedBodyIn + ? isActivated + : isActivated && + isBodyIn; + + // + passedBar.Clean(); + if (!isPassed) + { + continue; + } + } + + // + // Check Break State ... + if (breakState == XZONE_STATE_PASSED || + breakState == XZONE_STATE_FAILED) + { + // + bool isBodyOut = false; + bool isBreaked = iZone.IsBreaked( + passedDir, + passedBar, + isBodyOut, + forceStartedBodyOut, + forPeriod // + ); + + // + bool isPassed = + breakState == XZONE_STATE_FAILED + ? !isBreaked + : !forceBreakedBodyOut + ? isBreaked + : isBreaked && + isBodyOut; + + // + passedBar.Clean(); + if (!isPassed) + { + continue; + } + } + + // + // Check Work State ... + if (workState == XZONE_STATE_PASSED || + workState == XZONE_STATE_FAILED) + { + // + bool ignoreActivation = activeState != XZONE_STATE_PASSED; + + // + bool isBodyOut = false; + bool isWorked = iZone.IsWorked( + passedDir, + passedBar, + isBodyOut, + ignoreActivation, + forceStartedBodyOut, + forceActivatedBodyIn, + forPeriod // + ); + + // + bool isPassed = + workState == XZONE_STATE_FAILED + ? !isWorked + : !forceWorkedBodyOut + ? isWorked + : isWorked && + isBodyOut; + + // + passedBar.Clean(); + if (!isPassed) + { + continue; + } + } + + // + // Check Filtered Zone Doesn't Exists ... + has = FindIndex( + idx, + iZone, + dest // + ); + if (has) + { + // + passedBar.Clean(); + continue; + } + + // + Add( + iZone, + dest // + ); + + // + // End For ... + } + + // + result = ArraySize(dest); + + // + return result; + } + + // + // Demand ... + int FilterDemandZones( + XCDemandZone *&dest[], + ENUM_TIMEFRAMES forPeriod = NULL, + // + // Start ... + ENUM_XZONE_STATE startState = XZONE_STATE_PASSED, + bool forceStartedBodyOut = false, + // + // Activation ... + ENUM_XZONE_STATE activeState = XZONE_STATE_FAILED, + bool forceActivatedBodyIn = false, + // + // Breaktion ... + ENUM_XZONE_STATE breakState = XZONE_STATE_FAILED, + bool forceBreakedBodyOut = false, + // + // Works ... + ENUM_XZONE_STATE workState = XZONE_STATE_FAILED, + bool forceWorkedBodyOut = false // + ) + { + // + int result = 0; + + // + int idx = -1; + int count = 0; + bool has = false; + + // + Clean(dest); + + // + if (!IsValid(forPeriod)) + { + forPeriod = period; + } + + // + has = IsValid() && + HasDemandZones(); + if (!has) + { + return result; + } + + // + XOHCL passedBar; + ENUM_X_DIRECTION passedDir = X_DIRECTION_NONE; + passedDir = X_DIRECTION_BULLISH; + count = CountDemandZones(); + for (int i = 0; i < count; i++) + { + // + XCDemandZone *iZone = demandZones[i]; + + // + // Check Started State ... + if (startState == XZONE_STATE_PASSED || + startState == XZONE_STATE_FAILED) + { + // + bool isBodyOut = false; + bool isStarted = iZone.IsStarted( + passedDir, + passedBar, + isBodyOut, + forPeriod // + ); + + // + bool isPassed = + startState == XZONE_STATE_FAILED + ? !isStarted + : !forceStartedBodyOut + ? isStarted + : isStarted && + isBodyOut; + + // + passedBar.Clean(); + if (!isPassed) + { + continue; + } + } + + // + // Check Activation State ... + if (activeState == XZONE_STATE_PASSED || + activeState == XZONE_STATE_FAILED) + { + // + bool isBodyIn = false; + bool isActivated = iZone.IsActivated( + passedDir, + passedBar, + isBodyIn, + forceStartedBodyOut, + forPeriod // + ); + + // + bool isPassed = + activeState == XZONE_STATE_FAILED + ? !isActivated + : !forceActivatedBodyIn + ? isActivated + : isActivated && + isBodyIn; + + // + passedBar.Clean(); + if (!isPassed) + { + continue; + } + } + + // + // Check Break State ... + if (breakState == XZONE_STATE_PASSED || + breakState == XZONE_STATE_FAILED) + { + // + bool isBodyOut = false; + bool isBreaked = iZone.IsBreaked( + passedDir, + passedBar, + isBodyOut, + forceStartedBodyOut, + forPeriod // + ); + + // + bool isPassed = + breakState == XZONE_STATE_FAILED + ? !isBreaked + : !forceBreakedBodyOut + ? isBreaked + : isBreaked && + isBodyOut; + + // + passedBar.Clean(); + if (!isPassed) + { + continue; + } + } + + // + // Check Work State ... + if (workState == XZONE_STATE_PASSED || + workState == XZONE_STATE_FAILED) + { + // + bool ignoreActivation = activeState != XZONE_STATE_PASSED; + + // + bool isBodyOut = false; + bool isWorked = iZone.IsWorked( + passedDir, + passedBar, + isBodyOut, + ignoreActivation, + forceStartedBodyOut, + forceActivatedBodyIn, + forPeriod // + ); + + // + bool isPassed = + workState == XZONE_STATE_FAILED + ? !isWorked + : !forceWorkedBodyOut + ? isWorked + : isWorked && + isBodyOut; + + // + passedBar.Clean(); + if (!isPassed) + { + continue; + } + } + + // + // Check Filtered Zone Doesn't Exists ... + has = FindIndex( + idx, + iZone, + dest // + ); + if (has) + { + // + passedBar.Clean(); + continue; + } + + // + Add( + iZone, + dest // + ); + + // + // End For ... + } + + // + result = ArraySize(dest); + + // + return result; + } + + // + // OrderBlock ... + int FilterOrderBlocks( + XCOrderBlock *&dest[], + ENUM_TIMEFRAMES forPeriod = NULL, + // + // Start ... + ENUM_XZONE_STATE startState = XZONE_STATE_PASSED, + bool forceStartedBodyOut = false, + // + // Activation ... + ENUM_XZONE_STATE activeState = XZONE_STATE_FAILED, + bool forceActivatedBodyIn = false, + // + // Breaktion ... + ENUM_XZONE_STATE breakState = XZONE_STATE_FAILED, + bool forceBreakedBodyOut = false, + // + // Works ... + ENUM_XZONE_STATE workState = XZONE_STATE_FAILED, + bool forceWorkedBodyOut = false // + ) + { + // + int result = 0; + + // + int idx = -1; + int count = 0; + bool has = false; + + // + Clean(dest); + + // + if (!IsValid(forPeriod)) + { + forPeriod = period; + } + + // + has = IsValid() && + HasOrderBlocks(); + if (!has) + { + return result; + } + + // + XOHCL passedBar; + ENUM_X_DIRECTION passedDir = X_DIRECTION_NONE; + count = CountOrderBlocks(); + for (int i = 0; i < count; i++) + { + // + XCOrderBlock *iZone = orderBlocks[i]; + passedDir = iZone.GetDirection(); + + // + // Check Started State ... + if (startState == XZONE_STATE_PASSED || + startState == XZONE_STATE_FAILED) + { + // + bool isBodyOut = false; + bool isStarted = iZone.IsStarted( + passedDir, + passedBar, + isBodyOut, + forPeriod // + ); + + // + bool isPassed = + startState == XZONE_STATE_FAILED + ? !isStarted + : !forceStartedBodyOut + ? isStarted + : isStarted && + isBodyOut; + + // + passedBar.Clean(); + if (!isPassed) + { + continue; + } + } + + // + // Check Activation State ... + if (activeState == XZONE_STATE_PASSED || + activeState == XZONE_STATE_FAILED) + { + // + bool isBodyIn = false; + bool isActivated = iZone.IsActivated( + passedDir, + passedBar, + isBodyIn, + forceStartedBodyOut, + forPeriod // + ); + + // + bool isPassed = + activeState == XZONE_STATE_FAILED + ? !isActivated + : !forceActivatedBodyIn + ? isActivated + : isActivated && + isBodyIn; + + // + passedBar.Clean(); + if (!isPassed) + { + continue; + } + } + + // + // Check Break State ... + if (breakState == XZONE_STATE_PASSED || + breakState == XZONE_STATE_FAILED) + { + // + bool isBodyOut = false; + bool isBreaked = iZone.IsBreaked( + passedDir, + passedBar, + isBodyOut, + forceStartedBodyOut, + forPeriod // + ); + + // + bool isPassed = + breakState == XZONE_STATE_FAILED + ? !isBreaked + : !forceBreakedBodyOut + ? isBreaked + : isBreaked && + isBodyOut; + + // + passedBar.Clean(); + if (!isPassed) + { + continue; + } + } + + // + // Check Work State ... + if (workState == XZONE_STATE_PASSED || + workState == XZONE_STATE_FAILED) + { + // + bool ignoreActivation = activeState != XZONE_STATE_PASSED; + + // + bool isBodyOut = false; + bool isWorked = iZone.IsWorked( + passedDir, + passedBar, + isBodyOut, + ignoreActivation, + forceStartedBodyOut, + forceActivatedBodyIn, + forPeriod // + ); + + // + bool isPassed = + workState == XZONE_STATE_FAILED + ? !isWorked + : !forceWorkedBodyOut + ? isWorked + : isWorked && + isBodyOut; + + // + passedBar.Clean(); + if (!isPassed) + { + continue; + } + } + + // + // Check Filtered Zone Doesn't Exists ... + has = FindIndex( + idx, + iZone, + dest // + ); + if (has) + { + // + passedBar.Clean(); + continue; + } + + // + Add( + iZone, + dest // + ); + + // + // End For ... + } + + // + result = ArraySize(dest); + + // + return result; + } + + // + // Bullish OrderBlock ... + int FilterBullishOrderBlocks( + XCOrderBlock *&dest[], + ENUM_TIMEFRAMES forPeriod = NULL, + // + // Start ... + ENUM_XZONE_STATE startState = XZONE_STATE_PASSED, + bool forceStartedBodyOut = false, + // + // Activation ... + ENUM_XZONE_STATE activeState = XZONE_STATE_FAILED, + bool forceActivatedBodyIn = false, + // + // Breaktion ... + ENUM_XZONE_STATE breakState = XZONE_STATE_FAILED, + bool forceBreakedBodyOut = false, + // + // Works ... + ENUM_XZONE_STATE workState = XZONE_STATE_FAILED, + bool forceWorkedBodyOut = false // + ) + { + // + int result = 0; + + // + int idx = -1; + int count = 0; + bool has = false; + + // + Clean(dest); + + // + if (!IsValid(forPeriod)) + { + forPeriod = period; + } + + // + has = IsValid() && + HasBullishOrderBlocks(); + if (!has) + { + return result; + } + + // + XOHCL passedBar; + ENUM_X_DIRECTION passedDir = X_DIRECTION_NONE; + passedDir = X_DIRECTION_BULLISH; + count = CountBullishOrderBlocks(); + for (int i = 0; i < count; i++) + { + // + XCOrderBlock *iZone = bullishOrderBlocks[i]; + + // + // Check Started State ... + if (startState == XZONE_STATE_PASSED || + startState == XZONE_STATE_FAILED) + { + // + bool isBodyOut = false; + bool isStarted = iZone.IsStarted( + passedDir, + passedBar, + isBodyOut, + forPeriod // + ); + + // + bool isPassed = + startState == XZONE_STATE_FAILED + ? !isStarted + : !forceStartedBodyOut + ? isStarted + : isStarted && + isBodyOut; + + // + passedBar.Clean(); + if (!isPassed) + { + continue; + } + } + + // + // Check Activation State ... + if (activeState == XZONE_STATE_PASSED || + activeState == XZONE_STATE_FAILED) + { + // + bool isBodyIn = false; + bool isActivated = iZone.IsActivated( + passedDir, + passedBar, + isBodyIn, + forceStartedBodyOut, + forPeriod // + ); + + // + bool isPassed = + activeState == XZONE_STATE_FAILED + ? !isActivated + : !forceActivatedBodyIn + ? isActivated + : isActivated && + isBodyIn; + + // + passedBar.Clean(); + if (!isPassed) + { + continue; + } + } + + // + // Check Break State ... + if (breakState == XZONE_STATE_PASSED || + breakState == XZONE_STATE_FAILED) + { + // + bool isBodyOut = false; + bool isBreaked = iZone.IsBreaked( + passedDir, + passedBar, + isBodyOut, + forceStartedBodyOut, + forPeriod // + ); + + // + bool isPassed = + breakState == XZONE_STATE_FAILED + ? !isBreaked + : !forceBreakedBodyOut + ? isBreaked + : isBreaked && + isBodyOut; + + // + passedBar.Clean(); + if (!isPassed) + { + continue; + } + } + + // + // Check Work State ... + if (workState == XZONE_STATE_PASSED || + workState == XZONE_STATE_FAILED) + { + // + bool ignoreActivation = activeState != XZONE_STATE_PASSED; + + // + bool isBodyOut = false; + bool isWorked = iZone.IsWorked( + passedDir, + passedBar, + isBodyOut, + ignoreActivation, + forceStartedBodyOut, + forceActivatedBodyIn, + forPeriod // + ); + + // + bool isPassed = + workState == XZONE_STATE_FAILED + ? !isWorked + : !forceWorkedBodyOut + ? isWorked + : isWorked && + isBodyOut; + + // + passedBar.Clean(); + if (!isPassed) + { + continue; + } + } + + // + // Check Filtered Zone Doesn't Exists ... + has = FindIndex( + idx, + iZone, + dest // + ); + if (has) + { + // + passedBar.Clean(); + continue; + } + + // + Add( + iZone, + dest // + ); + + // + // End For ... + } + + // + result = ArraySize(dest); + + // + return result; + } + + // + // Bearish OrderBlock ... + int FilterBearishOrderBlocks( + XCOrderBlock *&dest[], + ENUM_TIMEFRAMES forPeriod = NULL, + // + // Start ... + ENUM_XZONE_STATE startState = XZONE_STATE_PASSED, + bool forceStartedBodyOut = false, + // + // Activation ... + ENUM_XZONE_STATE activeState = XZONE_STATE_FAILED, + bool forceActivatedBodyIn = false, + // + // Breaktion ... + ENUM_XZONE_STATE breakState = XZONE_STATE_FAILED, + bool forceBreakedBodyOut = false, + // + // Works ... + ENUM_XZONE_STATE workState = XZONE_STATE_FAILED, + bool forceWorkedBodyOut = false // + ) + { + // + int result = 0; + + // + int idx = -1; + int count = 0; + bool has = false; + + // + Clean(dest); + + // + if (!IsValid(forPeriod)) + { + forPeriod = period; + } + + // + has = IsValid() && + HasBearishOrderBlocks(); + if (!has) + { + return result; + } + + // + XOHCL passedBar; + ENUM_X_DIRECTION passedDir = X_DIRECTION_NONE; + passedDir = X_DIRECTION_BEARISH; + count = CountBearishOrderBlocks(); + for (int i = 0; i < count; i++) + { + // + XCOrderBlock *iZone = bearishOrderBlocks[i]; + + // + // Check Started State ... + if (startState == XZONE_STATE_PASSED || + startState == XZONE_STATE_FAILED) + { + // + bool isBodyOut = false; + bool isStarted = iZone.IsStarted( + passedDir, + passedBar, + isBodyOut, + forPeriod // + ); + + // + bool isPassed = + startState == XZONE_STATE_FAILED + ? !isStarted + : !forceStartedBodyOut + ? isStarted + : isStarted && + isBodyOut; + + // + passedBar.Clean(); + if (!isPassed) + { + continue; + } + } + + // + // Check Activation State ... + if (activeState == XZONE_STATE_PASSED || + activeState == XZONE_STATE_FAILED) + { + // + bool isBodyIn = false; + bool isActivated = iZone.IsActivated( + passedDir, + passedBar, + isBodyIn, + forceStartedBodyOut, + forPeriod // + ); + + // + bool isPassed = + activeState == XZONE_STATE_FAILED + ? !isActivated + : !forceActivatedBodyIn + ? isActivated + : isActivated && + isBodyIn; + + // + passedBar.Clean(); + if (!isPassed) + { + continue; + } + } + + // + // Check Break State ... + if (breakState == XZONE_STATE_PASSED || + breakState == XZONE_STATE_FAILED) + { + // + bool isBodyOut = false; + bool isBreaked = iZone.IsBreaked( + passedDir, + passedBar, + isBodyOut, + forceStartedBodyOut, + forPeriod // + ); + + // + bool isPassed = + breakState == XZONE_STATE_FAILED + ? !isBreaked + : !forceBreakedBodyOut + ? isBreaked + : isBreaked && + isBodyOut; + + // + passedBar.Clean(); + if (!isPassed) + { + continue; + } + } + + // + // Check Work State ... + if (workState == XZONE_STATE_PASSED || + workState == XZONE_STATE_FAILED) + { + // + bool ignoreActivation = activeState != XZONE_STATE_PASSED; + + // + bool isBodyOut = false; + bool isWorked = iZone.IsWorked( + passedDir, + passedBar, + isBodyOut, + ignoreActivation, + forceStartedBodyOut, + forceActivatedBodyIn, + forPeriod // + ); + + // + bool isPassed = + workState == XZONE_STATE_FAILED + ? !isWorked + : !forceWorkedBodyOut + ? isWorked + : isWorked && + isBodyOut; + + // + passedBar.Clean(); + if (!isPassed) + { + continue; + } + } + + // + // Check Filtered Zone Doesn't Exists ... + has = FindIndex( + idx, + iZone, + dest // + ); + if (has) + { + // + passedBar.Clean(); + continue; + } + + // + Add( + iZone, + dest // + ); + + // + // End For ... + } + + // + result = ArraySize(dest); + + // + return result; + } + + // + // FairValueGap ... + int FilterFairValueGaps( + XCFVG *&dest[], + ENUM_TIMEFRAMES forPeriod = NULL, + // + // Start ... + ENUM_XZONE_STATE startState = XZONE_STATE_PASSED, + bool forceStartedBodyOut = false, + // + // Activation ... + ENUM_XZONE_STATE activeState = XZONE_STATE_FAILED, + bool forceActivatedBodyIn = false, + // + // Breaktion ... + ENUM_XZONE_STATE breakState = XZONE_STATE_FAILED, + bool forceBreakedBodyOut = false, + // + // Works ... + ENUM_XZONE_STATE workState = XZONE_STATE_FAILED, + bool forceWorkedBodyOut = false // + ) + { + // + int result = 0; + + // + int idx = -1; + int count = 0; + bool has = false; + + // + Clean(dest); + + // + if (!IsValid(forPeriod)) + { + forPeriod = period; + } + + // + has = IsValid() && + HasFairValueGaps(); + if (!has) + { + return result; + } + + // + XOHCL passedBar; + ENUM_X_DIRECTION passedDir = X_DIRECTION_NONE; + count = CountFairValueGaps(); + for (int i = 0; i < count; i++) + { + // + XCFVG *iZone = fairValueGaps[i]; + passedDir = iZone.GetDirection(); + + // + // Check Started State ... + if (startState == XZONE_STATE_PASSED || + startState == XZONE_STATE_FAILED) + { + // + bool isBodyOut = false; + bool isStarted = iZone.IsStarted( + passedDir, + passedBar, + isBodyOut, + forPeriod // + ); + + // + bool isPassed = + startState == XZONE_STATE_FAILED + ? !isStarted + : !forceStartedBodyOut + ? isStarted + : isStarted && + isBodyOut; + + // + passedBar.Clean(); + if (!isPassed) + { + continue; + } + } + + // + // Check Activation State ... + if (activeState == XZONE_STATE_PASSED || + activeState == XZONE_STATE_FAILED) + { + // + bool isBodyIn = false; + bool isActivated = iZone.IsActivated( + passedDir, + passedBar, + isBodyIn, + forceStartedBodyOut, + forPeriod // + ); + + // + bool isPassed = + activeState == XZONE_STATE_FAILED + ? !isActivated + : !forceActivatedBodyIn + ? isActivated + : isActivated && + isBodyIn; + + // + passedBar.Clean(); + if (!isPassed) + { + continue; + } + } + + // + // Check Break State ... + if (breakState == XZONE_STATE_PASSED || + breakState == XZONE_STATE_FAILED) + { + // + bool isBodyOut = false; + bool isBreaked = iZone.IsBreaked( + passedDir, + passedBar, + isBodyOut, + forceStartedBodyOut, + forPeriod // + ); + + // + bool isPassed = + breakState == XZONE_STATE_FAILED + ? !isBreaked + : !forceBreakedBodyOut + ? isBreaked + : isBreaked && + isBodyOut; + + // + passedBar.Clean(); + if (!isPassed) + { + continue; + } + } + + // + // Check Work State ... + if (workState == XZONE_STATE_PASSED || + workState == XZONE_STATE_FAILED) + { + // + bool ignoreActivation = activeState != XZONE_STATE_PASSED; + + // + bool isBodyOut = false; + bool isWorked = iZone.IsWorked( + passedDir, + passedBar, + isBodyOut, + ignoreActivation, + forceStartedBodyOut, + forceActivatedBodyIn, + forPeriod // + ); + + // + bool isPassed = + workState == XZONE_STATE_FAILED + ? !isWorked + : !forceWorkedBodyOut + ? isWorked + : isWorked && + isBodyOut; + + // + passedBar.Clean(); + if (!isPassed) + { + continue; + } + } + + // + // Check Filtered Zone Doesn't Exists ... + has = FindIndex( + idx, + iZone, + dest // + ); + if (has) + { + // + passedBar.Clean(); + continue; + } + + // + Add( + iZone, + dest // + ); + + // + // End For ... + } + + // + result = ArraySize(dest); + + // + return result; + } + + // + // Bullish FairValueGap ... + int FilterBullishFairValueGaps( + XCFVG *&dest[], + ENUM_TIMEFRAMES forPeriod = NULL, + // + // Start ... + ENUM_XZONE_STATE startState = XZONE_STATE_PASSED, + bool forceStartedBodyOut = false, + // + // Activation ... + ENUM_XZONE_STATE activeState = XZONE_STATE_FAILED, + bool forceActivatedBodyIn = false, + // + // Breaktion ... + ENUM_XZONE_STATE breakState = XZONE_STATE_FAILED, + bool forceBreakedBodyOut = false, + // + // Works ... + ENUM_XZONE_STATE workState = XZONE_STATE_FAILED, + bool forceWorkedBodyOut = false // + ) + { + // + int result = 0; + + // + int idx = -1; + int count = 0; + bool has = false; + + // + Clean(dest); + + // + if (!IsValid(forPeriod)) + { + forPeriod = period; + } + + // + has = IsValid() && + HasBullishFairValueGaps(); + if (!has) + { + return result; + } + + // + XOHCL passedBar; + ENUM_X_DIRECTION passedDir = X_DIRECTION_NONE; + passedDir = X_DIRECTION_BULLISH; + count = CountBullishFairValueGaps(); + for (int i = 0; i < count; i++) + { + // + XCFVG *iZone = bullishFairValueGaps[i]; + + // + // Check Started State ... + if (startState == XZONE_STATE_PASSED || + startState == XZONE_STATE_FAILED) + { + // + bool isBodyOut = false; + bool isStarted = iZone.IsStarted( + passedDir, + passedBar, + isBodyOut, + forPeriod // + ); + + // + bool isPassed = + startState == XZONE_STATE_FAILED + ? !isStarted + : !forceStartedBodyOut + ? isStarted + : isStarted && + isBodyOut; + + // + passedBar.Clean(); + if (!isPassed) + { + continue; + } + } + + // + // Check Activation State ... + if (activeState == XZONE_STATE_PASSED || + activeState == XZONE_STATE_FAILED) + { + // + bool isBodyIn = false; + bool isActivated = iZone.IsActivated( + passedDir, + passedBar, + isBodyIn, + forceStartedBodyOut, + forPeriod // + ); + + // + bool isPassed = + activeState == XZONE_STATE_FAILED + ? !isActivated + : !forceActivatedBodyIn + ? isActivated + : isActivated && + isBodyIn; + + // + passedBar.Clean(); + if (!isPassed) + { + continue; + } + } + + // + // Check Break State ... + if (breakState == XZONE_STATE_PASSED || + breakState == XZONE_STATE_FAILED) + { + // + bool isBodyOut = false; + bool isBreaked = iZone.IsBreaked( + passedDir, + passedBar, + isBodyOut, + forceStartedBodyOut, + forPeriod // + ); + + // + bool isPassed = + breakState == XZONE_STATE_FAILED + ? !isBreaked + : !forceBreakedBodyOut + ? isBreaked + : isBreaked && + isBodyOut; + + // + passedBar.Clean(); + if (!isPassed) + { + continue; + } + } + + // + // Check Work State ... + if (workState == XZONE_STATE_PASSED || + workState == XZONE_STATE_FAILED) + { + // + bool ignoreActivation = activeState != XZONE_STATE_PASSED; + + // + bool isBodyOut = false; + bool isWorked = iZone.IsWorked( + passedDir, + passedBar, + isBodyOut, + ignoreActivation, + forceStartedBodyOut, + forceActivatedBodyIn, + forPeriod // + ); + + // + bool isPassed = + workState == XZONE_STATE_FAILED + ? !isWorked + : !forceWorkedBodyOut + ? isWorked + : isWorked && + isBodyOut; + + // + passedBar.Clean(); + if (!isPassed) + { + continue; + } + } + + // + // Check Filtered Zone Doesn't Exists ... + has = FindIndex( + idx, + iZone, + dest // + ); + if (has) + { + // + passedBar.Clean(); + continue; + } + + // + Add( + iZone, + dest // + ); + + // + // End For ... + } + + // + result = ArraySize(dest); + + // + return result; + } + + // + // Bearish FairValueGap ... + int FilterBearishFairValueGaps( + XCFVG *&dest[], + ENUM_TIMEFRAMES forPeriod = NULL, + // + // Start ... + ENUM_XZONE_STATE startState = XZONE_STATE_PASSED, + bool forceStartedBodyOut = false, + // + // Activation ... + ENUM_XZONE_STATE activeState = XZONE_STATE_FAILED, + bool forceActivatedBodyIn = false, + // + // Breaktion ... + ENUM_XZONE_STATE breakState = XZONE_STATE_FAILED, + bool forceBreakedBodyOut = false, + // + // Works ... + ENUM_XZONE_STATE workState = XZONE_STATE_FAILED, + bool forceWorkedBodyOut = false // + ) + { + // + int result = 0; + + // + int idx = -1; + int count = 0; + bool has = false; + + // + Clean(dest); + + // + if (!IsValid(forPeriod)) + { + forPeriod = period; + } + + // + has = IsValid() && + HasBearishFairValueGaps(); + if (!has) + { + return result; + } + + // + XOHCL passedBar; + ENUM_X_DIRECTION passedDir = X_DIRECTION_NONE; + passedDir = X_DIRECTION_BEARISH; + count = CountBearishFairValueGaps(); + for (int i = 0; i < count; i++) + { + // + XCFVG *iZone = bearishFairValueGaps[i]; + + // + // Check Started State ... + if (startState == XZONE_STATE_PASSED || + startState == XZONE_STATE_FAILED) + { + // + bool isBodyOut = false; + bool isStarted = iZone.IsStarted( + passedDir, + passedBar, + isBodyOut, + forPeriod // + ); + + // + bool isPassed = + startState == XZONE_STATE_FAILED + ? !isStarted + : !forceStartedBodyOut + ? isStarted + : isStarted && + isBodyOut; + + // + passedBar.Clean(); + if (!isPassed) + { + continue; + } + } + + // + // Check Activation State ... + if (activeState == XZONE_STATE_PASSED || + activeState == XZONE_STATE_FAILED) + { + // + bool isBodyIn = false; + bool isActivated = iZone.IsActivated( + passedDir, + passedBar, + isBodyIn, + forceStartedBodyOut, + forPeriod // + ); + + // + bool isPassed = + activeState == XZONE_STATE_FAILED + ? !isActivated + : !forceActivatedBodyIn + ? isActivated + : isActivated && + isBodyIn; + + // + passedBar.Clean(); + if (!isPassed) + { + continue; + } + } + + // + // Check Break State ... + if (breakState == XZONE_STATE_PASSED || + breakState == XZONE_STATE_FAILED) + { + // + bool isBodyOut = false; + bool isBreaked = iZone.IsBreaked( + passedDir, + passedBar, + isBodyOut, + forceStartedBodyOut, + forPeriod // + ); + + // + bool isPassed = + breakState == XZONE_STATE_FAILED + ? !isBreaked + : !forceBreakedBodyOut + ? isBreaked + : isBreaked && + isBodyOut; + + // + passedBar.Clean(); + if (!isPassed) + { + continue; + } + } + + // + // Check Work State ... + if (workState == XZONE_STATE_PASSED || + workState == XZONE_STATE_FAILED) + { + // + bool ignoreActivation = activeState != XZONE_STATE_PASSED; + + // + bool isBodyOut = false; + bool isWorked = iZone.IsWorked( + passedDir, + passedBar, + isBodyOut, + ignoreActivation, + forceStartedBodyOut, + forceActivatedBodyIn, + forPeriod // + ); + + // + bool isPassed = + workState == XZONE_STATE_FAILED + ? !isWorked + : !forceWorkedBodyOut + ? isWorked + : isWorked && + isBodyOut; + + // + passedBar.Clean(); + if (!isPassed) + { + continue; + } + } + + // + // Check Filtered Zone Doesn't Exists ... + has = FindIndex( + idx, + iZone, + dest // + ); + if (has) + { + // + passedBar.Clean(); + continue; + } + + // + Add( + iZone, + dest // + ); + + // + // End For ... + } + + // + result = ArraySize(dest); + + // + return result; + } + + // + void Filter( + XPOIState &dest, + ENUM_TIMEFRAMES forPeriod = NULL, + // + // Start ... + ENUM_XZONE_STATE startState = XZONE_STATE_PASSED, + bool forceStartedBodyOut = false, + // + // Activation ... + ENUM_XZONE_STATE activeState = XZONE_STATE_FAILED, + bool forceActivatedBodyIn = false, + // + // Breaktion ... + ENUM_XZONE_STATE breakState = XZONE_STATE_FAILED, + bool forceBreakedBodyOut = false, + // + // Works ... + ENUM_XZONE_STATE workState = XZONE_STATE_FAILED, + bool forceWorkedBodyOut = false // + ) + { + // + int count = 0; + bool has = false; + + // + dest.Clean(); + + // + if (!IsValid(forPeriod)) + { + forPeriod = period; + } + + // + has = IsValid() && + HasChild(); + if (!has) + { + return; + } + + // + dest = this; + + // + // Support Zones ... + FilterSupportZones( + dest.supportZones, + forPeriod, + startState, + forceStartedBodyOut, + activeState, + forceActivatedBodyIn, + breakState, + forceBreakedBodyOut, + workState, + forceWorkedBodyOut // + ); + + // + // Resistance Zones ... + FilterResistanceZones( + dest.resistanceZones, + forPeriod, + startState, + forceStartedBodyOut, + activeState, + forceActivatedBodyIn, + breakState, + forceBreakedBodyOut, + workState, + forceWorkedBodyOut // + ); + + // + // Supply Zones ... + FilterSupplyZones( + dest.supplyZones, + forPeriod, + startState, + forceStartedBodyOut, + activeState, + forceActivatedBodyIn, + breakState, + forceBreakedBodyOut, + workState, + forceWorkedBodyOut // + ); + + // + // Demand Zones ... + FilterDemandZones( + dest.demandZones, + forPeriod, + startState, + forceStartedBodyOut, + activeState, + forceActivatedBodyIn, + breakState, + forceBreakedBodyOut, + workState, + forceWorkedBodyOut // + ); + + // + // OrderBlocks ... + FilterOrderBlocks( + dest.orderBlocks, + forPeriod, + startState, + forceStartedBodyOut, + activeState, + forceActivatedBodyIn, + breakState, + forceBreakedBodyOut, + workState, + forceWorkedBodyOut // + ); + + // + // Bullish OrderBlocks ... + FilterBullishOrderBlocks( + dest.bullishOrderBlocks, + forPeriod, + startState, + forceStartedBodyOut, + activeState, + forceActivatedBodyIn, + breakState, + forceBreakedBodyOut, + workState, + forceWorkedBodyOut // + ); + + // + // Bearish OrderBlocks ... + FilterBearishOrderBlocks( + dest.bearishOrderBlocks, + forPeriod, + startState, + forceStartedBodyOut, + activeState, + forceActivatedBodyIn, + breakState, + forceBreakedBodyOut, + workState, + forceWorkedBodyOut // + ); + + // + // FairValueGaps ... + FilterFairValueGaps( + dest.fairValueGaps, + forPeriod, + startState, + forceStartedBodyOut, + activeState, + forceActivatedBodyIn, + breakState, + forceBreakedBodyOut, + workState, + forceWorkedBodyOut // + ); + + // + // Bullish FairValueGaps ... + FilterBullishFairValueGaps( + dest.bullishFairValueGaps, + forPeriod, + startState, + forceStartedBodyOut, + activeState, + forceActivatedBodyIn, + breakState, + forceBreakedBodyOut, + workState, + forceWorkedBodyOut // + ); + + // + // Bearish FairValueGaps ... + FilterBearishFairValueGaps( + dest.bearishFairValueGaps, + forPeriod, + startState, + forceStartedBodyOut, + activeState, + forceActivatedBodyIn, + breakState, + forceBreakedBodyOut, + workState, + forceWorkedBodyOut // + ); + + // + } + + // +}; + +// +// Extensions Functions ... +// + +/** + * Get Oldest Index ... + * + * @param source: XSignalBox instance Reference Collection ... + * + * @return ( int ) + */ +int GetOldest( + XSignalBox &source[] // +) +{ + // + int result = -1; + + // + int count = ArraySize(source); + if (!IsValidSize(count)) + { + return result; + } + + // + XSignalBox selected; + for (int i = 0; i < count; i++) + { + // + XSignalBox iBox = source[i]; + + // + bool canSet = + !selected.IsValid() + ? true + : selected.fvg.IsValid() && + iBox.fvg.IsValid() + ? selected.fvg.from > iBox.fvg.from + : selected.fvg.IsValid() && + !iBox.fvg.IsValid() + ? selected.fvg.from > iBox.ob.from + : !selected.fvg.IsValid() && + iBox.fvg.IsValid() + ? selected.ob.from > iBox.fvg.from + : !selected.fvg.IsValid() && + !iBox.fvg.IsValid() + ? selected.ob.from > iBox.ob.from + : false; + if (canSet) + { + // + result = i; + selected = iBox; + } + } + + // + selected.Clean(); + + // + return result; +} + +/** + * Get Youngest Index ... + * + * @param source: XSignalBox instance Reference Collection ... + * + * @return ( int ) + */ +int GetYoungest( + XSignalBox &source[] // +) +{ + // + int result = -1; + + // + int count = ArraySize(source); + if (!IsValidSize(count)) + { + return result; + } + + // + XSignalBox selected; + for (int i = 0; i < count; i++) + { + // + XSignalBox iBox = source[i]; + + // + bool canSet = + !selected.IsValid() + ? true + : selected.fvg.IsValid() && + iBox.fvg.IsValid() + ? selected.fvg.from < iBox.fvg.from + : selected.fvg.IsValid() && + !iBox.fvg.IsValid() + ? selected.fvg.from < iBox.ob.from + : !selected.fvg.IsValid() && + iBox.fvg.IsValid() + ? selected.ob.from < iBox.fvg.from + : !selected.fvg.IsValid() && + !iBox.fvg.IsValid() + ? selected.ob.from < iBox.ob.from + : false; + if (canSet) + { + // + result = i; + selected = iBox; + } + } + + // + selected.Clean(); + + // + return result; +} + +/** + * Get Highest Index ... + * + * @param source: XSignalBox instance Reference Collection ... + * + * @return ( int ) + */ +int GetHighest( + XSignalBox &source[] // +) +{ + // + int result = -1; + + // + int count = ArraySize(source); + if (!IsValidSize(count)) + { + return result; + } + + // + XSignalBox selected; + for (int i = 0; i < count; i++) + { + // + XSignalBox iBox = source[i]; + + // + bool canSet = + !selected.IsValid() + ? true + : selected.fvg.IsValid() && + iBox.fvg.IsValid() + ? selected.fvg.upper < iBox.fvg.upper + : selected.fvg.IsValid() && + !iBox.fvg.IsValid() + ? selected.fvg.upper < iBox.ob.upper + : !selected.fvg.IsValid() && + iBox.fvg.IsValid() + ? selected.ob.upper < iBox.fvg.upper + : !selected.fvg.IsValid() && + !iBox.fvg.IsValid() + ? selected.ob.upper < iBox.ob.upper + : false; + if (canSet) + { + // + result = i; + selected = iBox; + } + } + + // + selected.Clean(); + + // + return result; +} + +/** + * Get Lowest Index ... + * + * @param source: XSignalBox instance Reference Collection ... + * + * @return ( int ) + */ +int GetLowest( + XSignalBox &source[] // +) +{ + // + int result = -1; + + // + int count = ArraySize(source); + if (!IsValidSize(count)) + { + return result; + } + + // + XSignalBox selected; + for (int i = 0; i < count; i++) + { + // + XSignalBox iBox = source[i]; + + // + bool canSet = + !selected.IsValid() + ? true + : selected.fvg.IsValid() && + iBox.fvg.IsValid() + ? selected.fvg.lower > iBox.fvg.lower + : selected.fvg.IsValid() && + !iBox.fvg.IsValid() + ? selected.fvg.lower > iBox.ob.lower + : !selected.fvg.IsValid() && + iBox.fvg.IsValid() + ? selected.ob.lower > iBox.fvg.lower + : !selected.fvg.IsValid() && + !iBox.fvg.IsValid() + ? selected.ob.lower > iBox.ob.lower + : false; + if (canSet) + { + // + result = i; + selected = iBox; + } + } + + // + selected.Clean(); + + // + return result; +} + +/** + * Find Index of a Signal Box on another ... + * + * @param index: int, index of exists ... + * @param item: XSignal Box ... + * @param items: XSignal Box Collection ... + * + * @return ( bool ) + */ +bool FindIndex( + int &index, + XSignalBox &item, + XSignalBox &items[] // +) +{ + // + bool result = false; + + // + index = -1; + int count = ArraySize(items); + + // + result = item.IsValid() && + HasChild(items); + if (!result) + { + return result; + } + + // + for (int i = 0; i < count; i++) + { + // + bool isSame = item.ob + .IsSameAs(items[i].ob); + if (isSame) + { + // + index = i; + break; + } + } + + // + result = IsValidIndex(index); + + // + return result; +} + +/** + * Find Index of a Signal Box on another ... + * + * @param index: int, index of exists ... + * @param item: XSignal Box ... + * @param items: XSignal Box Collection ... + * + * @return ( bool ) + */ +bool FindIndex( + int &index, + XBoxZone &item, + XSignalBox &items[] // +) +{ + // + bool result = false; + + // + index = -1; + int count = ArraySize(items); + + // + result = item.IsValid() && + HasChild(items); + if (!result) + { + return result; + } + + // + for (int i = 0; i < count; i++) + { + // + bool isSame = item.IsSameAs(items[i].ob); + if (isSame) + { + // + index = i; + break; + } + + // + isSame = item.IsSameAs(items[i].fvg); + if (isSame) + { + // + index = i; + break; + } + } + + // + result = IsValidIndex(index); + + // + return result; +} + +/** + * Add a Signal Box in a Collection if not Exists ... + * + * @param item: XSignal Box ... + * @param items: XSignal Box Collection ... + * + * @return ( bool ) + */ +bool AddIfNotExists( + XSignalBox &item, + XSignalBox &items[] // +) +{ + // + bool result = false; + + // + result = item.IsValid(); + if (!result) + { + return result; + } + + // + int idx = -1; + result = !FindIndex( + idx, + item, + items // + ); + if (!result) + { + return result; + } + + // + AddRef( + item, + items // + ); + + // + return result; +} + +// +// XPOI State Event Parsers ... + +// +// Swings ... + +// +bool HasNewSwing(ENUM_XPOI_EVENTS &events[]) +{ + return HasNewSwingLow(events) || + HasNewSwingHigh(events); +} + +// +bool HasNewSwingLow(ENUM_XPOI_EVENTS &events[]) +{ + return Contains( + X_SWING_LOW_DETECTED, + events // + ); +} + +// +bool HasNewSwingHigh(ENUM_XPOI_EVENTS &events[]) +{ + return Contains( + X_SWING_HIGH_DETECTED, + events // + ); +} + +// +// Momentums ... + +// +bool HasNewMomentum(ENUM_XPOI_EVENTS &events[]) +{ + return HasNewBullishMomentum(events) || + HasNewBearishMomentum(events); +} + +// +bool HasNewBullishMomentum(ENUM_XPOI_EVENTS &events[]) +{ + return Contains( + X_BULLISH_MOMENTUM_BAR_DETECTED, + events // + ); +} + +// +bool HasNewBearishMomentum(ENUM_XPOI_EVENTS &events[]) +{ + return Contains( + X_BEARISH_MOMENTUM_BAR_DETECTED, + events // + ); +} + +// +// Rejections ... + +// +bool HasNewRejection(ENUM_XPOI_EVENTS &events[]) +{ + return HasNewBullishRejection(events) || + HasNewBearishRejection(events); +} + +// +bool HasNewBullishRejection(ENUM_XPOI_EVENTS &events[]) +{ + return Contains( + X_BULLISH_REJECTION_BAR_DETECTED, + events // + ); +} + +// +bool HasNewBearishRejection(ENUM_XPOI_EVENTS &events[]) +{ + return Contains( + X_BEARISH_REJECTION_BAR_DETECTED, + events // + ); +} + +// +// Support / Resistance Zones ... + +// +bool HasNewSupportZone(ENUM_XPOI_EVENTS &events[]) +{ + return Contains( + X_SUPPORT_ZONE_DETECTED, + events // + ); +} + +// +bool HasNewResistanceZone(ENUM_XPOI_EVENTS &events[]) +{ + return Contains( + X_RESISTANCE_ZONE_DETECTED, + events // + ); +} + +// +// Supply / Demand Zones ... + +// +bool HasNewSupplyZone(ENUM_XPOI_EVENTS &events[]) +{ + return Contains( + X_SUPPLY_ZONE_DETECTED, + events // + ); +} + +// +bool HasNewDemandZone(ENUM_XPOI_EVENTS &events[]) +{ + return Contains( + X_DEMAND_ZONE_DETECTED, + events // + ); +} + +// +// Fair Value Gaps ... + +// +bool HasNewFairValueGap(ENUM_XPOI_EVENTS &events[]) +{ + return HasNewBullishFairValueGap(events) || + HasNewBearishFairValueGap(events); +} + +// +bool HasNewBullishFairValueGap(ENUM_XPOI_EVENTS &events[]) +{ + return Contains( + X_BULLISH_FVG_DETECTED, + events // + ); +} + +// +bool HasNewBearishFairValueGap(ENUM_XPOI_EVENTS &events[]) +{ + return Contains( + X_BEARISH_FVG_DETECTED, + events // + ); +} + +// +// Order Blocks ... + +// +bool HasNewOrderBlock(ENUM_XPOI_EVENTS &events[]) +{ + return HasNewBullishOrderBlock(events) || + HasNewBearishOrderBlock(events); +} + +// +bool HasNewBullishOrderBlock(ENUM_XPOI_EVENTS &events[]) +{ + return Contains( + X_BULLISH_ORDERBLOCK_DETECTED, + events // + ); +} + +// +bool HasNewBearishOrderBlock(ENUM_XPOI_EVENTS &events[]) +{ + return Contains( + X_BEARISH_ORDERBLOCK_DETECTED, + events // + ); +} + +// +// Spikes ... + +// +bool HasNewSpike(ENUM_XPOI_EVENTS &events[]) +{ + return HasNewBullishSpike(events) || + HasNewBearishSpike(events); +} + +// +bool HasNewBullishSpike(ENUM_XPOI_EVENTS &events[]) +{ + return Contains( + X_BULLISH_SPIKE_DETECTED, + events // + ); +} + +// +bool HasNewBearishSpike(ENUM_XPOI_EVENTS &events[]) +{ + return Contains( + X_BEARISH_SPIKE_DETECTED, + events // + ); +} + +// +// Sharps ... + +// +bool HasNewSharp(ENUM_XPOI_EVENTS &events[]) +{ + return HasNewBullishSharp(events) || + HasNewBearishSharp(events); +} + +// +bool HasNewBullishSharp(ENUM_XPOI_EVENTS &events[]) +{ + return Contains( + X_BULLISH_SHARP_DETECTED, + events // + ); +} + +// +bool HasNewBearishSharp(ENUM_XPOI_EVENTS &events[]) +{ + return Contains( + X_BEARISH_SHARP_DETECTED, + events // + ); +} + +// +// Pullbacks ... + +// +bool HasNewPullback(ENUM_XPOI_EVENTS &events[]) +{ + return HasNewBullishPullback(events) || + HasNewBearishPullback(events); +} + +// +bool HasNewBullishPullback(ENUM_XPOI_EVENTS &events[]) +{ + return Contains( + X_BULLISH_PULLBACK_DETECTED, + events // + ); +} + +// +bool HasNewBearishPullback(ENUM_XPOI_EVENTS &events[]) +{ + return Contains( + X_BEARISH_PULLBACK_DETECTED, + events // + ); +} + +// +// Consolidation Zones ... + +// +bool HasNewConsolidationZone(ENUM_XPOI_EVENTS &events[]) +{ + return HasNewBullishConsolidationZone(events) || + HasNewBearishConsolidationZone(events); +} + +// +bool HasNewBullishConsolidationZone(ENUM_XPOI_EVENTS &events[]) +{ + return Contains( + X_BULLISH_CONSOLIDATION_ZONE_DETECTED, + events // + ); +} + +// +bool HasNewBearishConsolidationZone(ENUM_XPOI_EVENTS &events[]) +{ + return Contains( + X_BEARISH_CONSOLIDATION_ZONE_DETECTED, + events // + ); +} diff --git a/BKPS/14040203/Libraries/x-saherelm.x-trade.lib.mq5 b/BKPS/14040203/Libraries/x-saherelm.x-trade.lib.mq5 new file mode 100644 index 0000000..2a708c2 --- /dev/null +++ b/BKPS/14040203/Libraries/x-saherelm.x-trade.lib.mq5 @@ -0,0 +1,6226 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Seriallize Library +// --------------------------------------- +// Name: XTradeLib +// Description: All models related to Trade ... +// +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +////////////////////////////////////////////////////// +// +// Global Properties ... +#property library +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://www.saherelm.ir" +#property version "1.00" +#property strict + +// +// Imports ... +#include "../Libraries/x-saherelm.common.lib.mq5" +#include + +// +// Definitions ... + +// +// a List of Used Tokens ... + +// +// Common ... +string XIDToken = "ID"; +string XTicketToken = "TK"; +string XModeToken = "MD"; +string XTypeToken = "TY"; +string XPeriodToken = "PR"; +string XProviderToken = "PRV"; +string XProfitToken = "PF"; + +// +string XTPToken = "TP"; +string XSLToken = "SL"; +string XTimeToken = "TM"; +string XEntryToken = "EN"; +string XVolumeToken = "VL"; +string XSymbolToken = "SMBL"; + +// +string XSupportToken = "SP"; +string XEQMSupportToken = "EQM"; +string XEQPToken = "EQP"; + +// +string XSLTrailToken = "SLT"; + +// +string XActionToken = "A"; + +// +string XDirectionalToken = "D"; +string XINDirectionalToken = "IND"; + +// +string XRecoveryToken = "XRCV"; + +// +// Available Order Modes ... +enum ENUM_X_ORDER_MODES +{ + X_ORDER_MODE_NOTHING, // Nothing + X_ORDER_MODE_MARKET, // Market Order + X_ORDER_MODE_STOP, // Pending Stop Order + X_ORDER_MODE_LIMIT, // Pending Limit Order + X_ORDER_MODE_STOP_LIMIT, // Pending Stop Limit Order +}; + +// +string ToString(ENUM_X_ORDER_MODES value) +{ + // + string result = NULL; + + // + switch (value) + { + // + case X_ORDER_MODE_MARKET: + result = "Market"; + break; + + // + case X_ORDER_MODE_LIMIT: + result = "Limit"; + break; + + // + case X_ORDER_MODE_STOP: + result = "Stop"; + break; + + // + case X_ORDER_MODE_STOP_LIMIT: + result = "StopLimit"; + break; + } + + // + return result; +} + +// +// Select Positions Type ... +enum ENUM_X_POSITION_SELECT_METHODS +{ + X_POSITION_SELECT_NONE, // None + X_POSITION_SELECT_MAX, // Max + X_POSITION_SELECT_MIN, // Min + X_POSITION_SELECT_BOTH, // Min and Max + X_POSITION_SELECT_ALL, // All +}; + +// +// Signal Execution Result ... +// note that some of them must be handles in +// EA's ... +enum ENUM_X_SIGNAL_EXECUTION_RESULT +{ + // + X_SIGNAL_EXECUTION_UNKNOWN, // Unknown + X_SIGNAL_EXECUTION_SUCCEED, // Succed + X_SIGNAL_EXECUTION_FAILED_SPREAD, // Spread more than Max Allowed + X_SIGNAL_EXECUTION_FAILED_NOT_ALLOWED, // Not Allowed Trade Type + X_SIGNAL_EXECUTION_FAILED_NO_EQUITY, // No Equity for Trade + X_SIGNAL_EXECUTION_FAILED_PRICE_ERROR, // Price Error + X_SIGNAL_EXECUTION_FAILED_PREV_PROFIT_ERROR, // Prev Profit Error + X_SIGNAL_EXECUTION_FAILED_MAX_REACHED, // Max Allowed Positions Reached + X_SIGNAL_EXECUTION_FAILED_DELAY_NOT_PASSED, // Same Positions Delay Not Passed + X_SIGNAL_EXECUTION_FAILED_INVALID_PARAMS, // Invalid Params +}; + +// +// Available Guard Action ... +enum ENUM_X_GUARD_ACTIONS +{ + X_GUARD_ACTION_NOTHING, // Nothing + X_GUARD_ACTION_HEDGE, // Hedge + X_GUARD_PARTIAL_CLOSE, // Partial Close + X_GUARD_ACTION_TRAIL_STOP, // Trail StopLoss + X_GUARD_ACTION_FORCE_CLOSE, // Force Close + X_GUARD_ACTION_ADD_SUPPORT_SIGNAL, // Add Support Signal + X_GUARD_ACTION_CANCEL_PENDING_ORDERS, // Cancel Pending Orders +}; + +// +enum ENUM_X_POSITION_TYPES +{ + X_POSITION_TYPE_NONE = 0, + X_POSITION_TYPE_ALL = 1, + X_POSITION_TYPE_LONG = 2, + X_POSITION_TYPE_SHORT = 3, +}; + +// +string ToString(ENUM_X_POSITION_TYPES value) +{ + // + string result = NULL; + + // + switch (value) + { + // + case X_POSITION_TYPE_ALL: + result = "All"; + break; + + // + case X_POSITION_TYPE_NONE: + result = "NONE"; + break; + + // + case X_POSITION_TYPE_SHORT: + result = "Short"; + break; + + // + case X_POSITION_TYPE_LONG: + result = "Long"; + break; + } + + // + return result; +} + +// +bool IsLong(ENUM_X_POSITION_TYPES value) +{ + return value == X_POSITION_TYPE_LONG; +} + +// +bool ToPositionType( + ENUM_POSITION_TYPE &dest, + ENUM_X_POSITION_TYPES source // +) +{ + // + bool result = false; + + // + result = source == X_POSITION_TYPE_LONG || + source == X_POSITION_TYPE_SHORT; + if (!result) + { + return result; + } + + // + dest = + source == X_POSITION_TYPE_LONG + ? POSITION_TYPE_BUY + : POSITION_TYPE_SELL; + + // + return result; +} + +// +ENUM_X_POSITION_TYPES ToPositionType(ENUM_POSITION_TYPE value) +{ + return IsLong(value) + ? X_POSITION_TYPE_LONG + : X_POSITION_TYPE_SHORT; +} + +// +ENUM_X_POSITION_TYPES OppositPositionType(ENUM_POSITION_TYPE type) +{ + // + ENUM_X_POSITION_TYPES result = X_POSITION_TYPE_NONE; + + // + bool isLong = IsLong(type); + bool isShort = IsShort(type); + + // + result = + // + isLong + ? X_POSITION_TYPE_SHORT + : isShort + ? X_POSITION_TYPE_LONG + : X_POSITION_TYPE_NONE + // + ; + + // + return result; +} + +// +ENUM_X_DIRECTION ToDirection(ENUM_POSITION_TYPE value) +{ + // + ENUM_X_DIRECTION result = X_DIRECTION_NONE; + + // + result = IsLong(value) + ? X_DIRECTION_BULLISH + : X_DIRECTION_BEARISH; + + // + return result; +} + +// +ENUM_X_DIRECTION ToDirection(ENUM_X_POSITION_TYPES value) +{ + // + ENUM_X_DIRECTION result = X_DIRECTION_NONE; + + // + result = value == X_POSITION_TYPE_ALL + ? X_DIRECTION_ALL + : value == X_POSITION_TYPE_LONG + ? X_DIRECTION_BULLISH + : value == X_POSITION_TYPE_SHORT + ? X_DIRECTION_BEARISH + : X_DIRECTION_NONE; + + // + return result; +} + +// +// Structs ... + +// +struct XRR +{ + // + double tps[]; + + // + double sl; + double entry; + + // + string prefix; + string symbol; + datetime time; + ENUM_TIMEFRAMES period; + + // + ENUM_X_POSITION_TYPES type; + + // + // Constructor ... + XRR() + { + Clean(); + } + + // + // Tools ... + + // + void Clean() + { + // + sl = 0; + entry = 0; + + // + time = NULL; + prefix = NULL; + period = NULL; + symbol = NULL; + + // + type = X_POSITION_TYPE_NONE; + + // + Clean(tps); + } + + // + bool Init( + string _symbol, + ENUM_TIMEFRAMES _period, + double _sl, + double _entry, + ENUM_X_POSITION_TYPES _type, + string _prefix = NULL // + ) + { + // + bool result = false; + + // + result = + _sl > 0 && + _entry > 0 && + IsValid(_symbol) && + IsValid(_period) && + _type != X_POSITION_TYPE_ALL && + _type != X_POSITION_TYPE_NONE && + (_type == X_POSITION_TYPE_LONG + ? _entry > _sl + : _entry < _sl); + if (!result) + { + return result; + } + + // + Default(); + + // + sl = _sl; + type = _type; + entry = _entry; + symbol = _symbol; + period = _period; + prefix = _prefix; + + // + time = TimeCurrent(); + + // + result = IsValid(); + + // + return result; + } + + // + void Default() + { + // + Add( + 1.0, + tps // + ); + Add( + 1.5, + tps // + ); + Add( + 2.0, + tps // + ); + Add( + 3.0, + tps // + ); + Add( + 4.0, + tps // + ); + Add( + 5.0, + tps // + ); + Add( + 6.0, + tps // + ); + } + + // + bool IsValid() + { + // + bool result = false; + + // + result = + sl > 0 && + entry > 0 && + IsValid(time) && + IsValid(symbol) && + IsValid(period) && + IsValidSize(ArraySize(tps)) && + type != X_POSITION_TYPE_ALL && + type != X_POSITION_TYPE_NONE && + (type == X_POSITION_TYPE_LONG + ? entry > 0 + : entry < sl); + + // + return result; + } + + // + string GetTag() + { + // + string result = NULL; + + // + if (!IsValid()) + { + // + result = GetTypeName(this); + return result; + } + + // + string sep = "_"; + + // + result = + GetTypeName(this) + sep + (IsValid(prefix) ? prefix + sep : "") + symbol + sep + ToString(period) + sep + ToFormatString(time) + sep + ToString(type); + + // + return result; + } +}; + +// +// Model an Open Position ... +struct XPosition +{ + // + // Props ... + + // + // Magic Number ... + ulong magic; + + // + // Ticket ID ... + ulong ticket; + + // + // Tradinng Symbol ... + string symbol; + + // + // Trading Period ... + ENUM_TIMEFRAMES period; + + // + // Position Type ... + ENUM_POSITION_TYPE type; + + // + // Take Profit ... + double tp; + + // + // Stop Loss ... + double sl; + + // + // Position Current Profit ... + double profit; + + // + // Position Open Price ... + double entry; + + // + // Current Symbol Price ... + double price; + + // + // Position Swap ... + double swap; + + // + // Position Commission ... + double commission; + + // + // Volume ... + double volume; + + // + // Position Open Time ... + datetime openAt; + + // + // Sifnal Provider ... + string provider; + + // + // Position Comment ... + string comment; + + // + // Constructor ... + XPosition() + { + Clean(); + } + + // + // Initializers ... + + bool ByIndex(int index) + { + // + bool result = false; + + // + static CPositionInfo mPositionInfo; + + // + result = mPositionInfo.SelectByIndex(index); + if (!result) + { + return result; + } + + // + ulong mTicket = mPositionInfo.Ticket(); + + // + result = ByTicket(mTicket); + + // + return result; + } + + bool ByTicket(ulong mTicket) + { + // + bool result = false; + + // + static CPositionInfo mPositionInfo; + + // + result = mPositionInfo.SelectByTicket(mTicket); + if (!result) + { + return result; + } + + // + swap = mPositionInfo.Swap(); + magic = mPositionInfo.Magic(); + openAt = mPositionInfo.Time(); + sl = mPositionInfo.StopLoss(); + ticket = mPositionInfo.Ticket(); + symbol = mPositionInfo.Symbol(); + tp = mPositionInfo.TakeProfit(); + profit = mPositionInfo.Profit(); + volume = mPositionInfo.Volume(); + comment = mPositionInfo.Comment(); + entry = mPositionInfo.PriceOpen(); + type = mPositionInfo.PositionType(); + price = mPositionInfo.PriceCurrent(); + commission = mPositionInfo.Commission(); + + // + period = ExtractPeriod(comment); + provider = ExtractProvider(comment); + + // + return result; + } + + // + // Tools ... + + // + // Cleanup ... + void Clean() + { + magic = 0; + ticket = 0; + tp = 0; + sl = 0; + swap = 0; + entry = 0; + price = 0; + profit = 0; + volume = 0; + openAt = 0; + commission = 0; + + // + type = NULL; + period = NULL; + + // + symbol = NULL; + comment = NULL; + provider = NULL; + + // + ZeroMemory(this); + } + + // + // Validate ... + bool IsValid() + { + // + bool result = false; + + // + result = + // + IsValid(symbol) && + NotEmpty(ticket) + // + ; + + // + return result; + } + + // + // Retrieve Entry Price ... + double GetEntry() + { + // + double result = 0; + + // + if (!IsValid()) + { + return result; + } + + // + result = GetEntry( + symbol, + type + // + ); + + // + return result; + } + + // + // Retrieve Exit ... + double GetExit() + { + // + double result = 0; + + // + if (!IsValid()) + { + return result; + } + + // + result = GetExit( + symbol, + type + // + ); + + // + return result; + } + + // + // Get Spread by Point ... + double GetSpread() + { + // + double result = 0; + + // + if (!IsValid()) + { + return result; + } + + // + result = PriceToPoint(GetSpread(symbol)); + + // + return result; + } + + // + double GetPointsValue() + { + // + double result = 0; + + // + if (!IsValid()) + { + return result; + } + + // + result = GetPoints(symbol); + + // + return result; + } + + // + double GetProfitInPoint() + { + // + double result = 0; + + // + if (!IsValid()) + { + return result; + } + + // + double tickSize = SymbolInfoDouble(symbol, SYMBOL_TRADE_TICK_SIZE); // Tick size + double tickValue = SymbolInfoDouble(symbol, SYMBOL_TRADE_TICK_VALUE); // Tick value + double pointSize = SymbolInfoDouble(symbol, SYMBOL_POINT); // Point size + double pointValue = tickValue * pointSize / tickSize; // Point value + + // + result = profit / (volume * tickValue); + + // + return result; + } + + // + // Find Risk ... + double GetRisk() + { + // + double result = 0; + + // + if (!IsValid()) + { + return 0; + } + + // + result = MathAbs(entry - sl); + + // + return result; + } + + // + // Find Reward ... + double GetReward() + { + // + double result = 0; + + // + if (!IsValid()) + { + return result; + } + + // + result = MathAbs(tp - entry); + + // + return result; + } + + // + double GetRewardInPoint() + { + // + double result = 0; + + // + result = GetReward() / GetPoints(); + + // + return result; + } + + // + // Find Risk Reward Ratio ... + double GetRiskRewardRatio() + { + // + double result = 0; + + // + if (!IsValid()) + { + return result; + } + + // + result = GetReward() / GetRisk(); + + // + return result; + } + + // + // Calculate TP Levels ... + int CalculateTPLevels(double &tps[]) + { + + // + int result = 0; + + // + Clean(tps); + + // + bool isValid = IsValid(); + if (!isValid) + { + return result; + } + + // + double risk = GetRisk(); + int r2r = (int)GetRiskRewardRatio(); + bool isLong = IsLong(type); + for (int i = 0; i < r2r; i++) + { + // + double iValue = + isLong + ? entry + risk + (i * risk) + : entry - risk - (i * risk); + // + Add( + iValue, + tps // + ); + } + + // + result = ArraySize(tps); + + // + return result; + } + + // + // Calculate Reached TP Levels ... + void CalculateReahedTP( + double &reachedLevel, + double &reachedPrice // + ) + { + // + reachedLevel = -1; + reachedPrice = 0; + double tps[]; + bool isLong = IsLong(type); + double exitPrice = GetExit(); + int tpLevels = CalculateTPLevels(tps); + if (!IsValidSize(tpLevels) || exitPrice <= 0) + { + return; + } + + // + for (int i = 0; i < tpLevels - 1; i++) + { + // + double cTP = tps[i]; + double nTP = tps[i + 1]; + + // + bool isReached = + isLong + ? exitPrice > cTP && + exitPrice < nTP + : exitPrice < cTP && + exitPrice > nTP; + if (isReached) + { + // + reachedLevel = i + 1; + reachedPrice = cTP; + } + } + } + + // + // Calculate Age ... + int GetAge( + ENUM_TIMEFRAMES mPeriod // Calculate Age based on this period + ) + { + return GetAge(this, mPeriod); + } + + // + // Check this instance is Same os Given instance or not ... + bool IsSameAs( + const XPosition &value // instance for Compare + ) + { + // + bool result = false; + + // + result = + // + type == value.type && + magic == value.magic && + entry == value.entry && + ticket == value.ticket && + volume == value.volume && + symbol == value.symbol && + provider == value.provider + // + ; + + // + return result; + } + + // + // Find index in a Collection ... + int FindIndex( + const XPosition &values[] // Collection to Find + ) + { + // + return FindIndex( + this, + values + // + ); + } + + // + // Check Items Passed Specific Filters or not ... + bool IsFiltersPassed( + string mSymbol = NULL, // Trading Symbol + string mProvider = NULL, // Signal Provider + ENUM_TIMEFRAMES mPeriod = NULL, // Trading Timeframe + ENUM_X_POSITION_TYPES mType = NULL, // Long (Buy), Short (Sell) + ulong mMagic = NULL, // Magic Number + bool mFilterByMagic = true // Get Only Self Open Positions + ) + { + // + bool result = false; + + // + result = + // + // Magic Filter ... + IsMagicFilterPassed( + mMagic, + mFilterByMagic, + this + // + ) + // + && + // + // Symbol Filter ... + IsSymbolFilterPassed( + mSymbol, + this + // + ) + // + && + // + // Provider Filter ... + IsProviderFilterPassed( + mProvider, + this + // + ) + // + && + // + // Period Filter ... + IsPeriodFilterPassed( + mPeriod, + this + // + ) + // + && + // + // Type Filter ... + IsTypeFilterPassed( + mType, + this + // + ) + // + ; + + // + return result; + } +}; + +// +// Model a Signal ... +struct XSignal +{ + // + // Props ... + + // + ulong positionId; // if Executed this filled ... + + // + datetime time; // Issue Time ... + + // + double tp; // Take Profit ... + double sl; // Stop Loss ... + double entry; // Exntry or Execution Price ... + double volume; // Position Volume ... + + // + string symbol; // Trading Symbol ... + string comment; // Comment ... + string provider; // Signaller ... + + // + ENUM_TIMEFRAMES period; // Trading TimeFrame ... + ENUM_POSITION_TYPE type; // Long (Buy) or Short (Sell) ... + ENUM_X_ORDER_MODES mode; // Execution Mode ... + + // + XSignal supports[]; // a Collecion of Support Signals ... + + // + int pushers; // Signal Pushers ... + string conditions; // Signal Conditions ... + + // + // Additional ... + + // + // TP ... + double fullTPLevel; // Full TP ... + double partialCloseMultiplier; // Amount of Partial Close ... + double partialCloseOnTPLevel; // Do Partial Close on TP Level ... + + // + // RF ... + double tpLevelForBreakEven; // TP Level for Break Even ... + bool riskFreeOnBreakEven; // Risk Free Signal On Break Even ... + + // + // Traget ... + double targets[]; // Force Risk Free On Targets ... + bool ignoreEAVolume; // Ignore EA Volume ... + + // + // SL Trail ... + bool trailSL; // Do SL Trail ... + double trailSLStartOnReachTPLevel; // Start SL Trail After Reached TP Level ... + + // + // Constructor ... + XSignal() + { + Clean(); + } + + // + bool Prepare( + string mSymbol, // Trading Symbol + string mProvider, // Signal Provider + ENUM_TIMEFRAMES mPeriod, // Trading TimeFrame + ENUM_POSITION_TYPE mType, // Long (Buy) or Short (Sell) + ENUM_X_ORDER_MODES mMode, // Execution Mode + double mEntry, // Entry Price + double mVolume, // Volume + double mSL = 0, // Stop Loss + double mTP = 0 // Take Profit + ) + { + // + bool result = false; + + // + result = + // + IsValid(mMode) && + IsValid(mSymbol) && + IsValid(mPeriod) && + NotEmpty(mEntry) && + NotEmpty(mVolume) && + IsValid(mProvider) + // + ; + if (!result) + { + return result; + } + + // + if (mTP < 0) + { + mTP = 0; + } + + // + if (mSL < 0) + { + mSL = 0; + } + + // + type = mType; + mode = mMode; + symbol = mSymbol; + period = mPeriod; + provider = mProvider; + + // + // Normalization Values ... + sl = NormalizePrice(mSL, mSymbol); + tp = NormalizePrice(mTP, mSymbol); + mEntry = NormalizePrice(mEntry, mSymbol); + mVolume = NormalizeVolume(mVolume, mSymbol); + + // + entry = mEntry; + volume = mVolume; + + // + result = Normalize(); + + // + return result; + } + + // + bool PrepareComplex( + string mSymbol, // Trading Symbol + string mProvider, // Signal Provider + ENUM_TIMEFRAMES mPeriod, // Trading TimeFrame + ENUM_POSITION_TYPE mType, // Long (Buy) or Short (Sell) + ENUM_X_ORDER_MODES mMode, // Execution Mode + double mEntry, // Entry Price + double mVolume, // Volume + double mSL = 0, // Stop Loss + // + // TP ... + double mFullTPLevel = 0, // Full TP Level + double mPartialCloseOnTPLevel = 0, // Partial Close On TP Level + double mPartialCloseMultiplier = 0, // Partial Close Multiplier + // + // RF ... + bool mRiskFreeOnBreakEven = false, // Risk Free Signal On Break Even ... + double mTpLevelForBreakEven = 0, // TP Level for Break Even ... + // + // SL Trail ... + bool mTrailSL = false, // Trail SL + double mTrailSLStartOnReachTPLevel = 0 // Trail SL Starts after Reached TP Level + ) + { + // + bool result = false; + + // + // Validate Args ... + result = + // + // Common ... + mSL > 0 && + mEntry > 0 && + mVolume > 0 && + IsValid(mSymbol) && + IsValid(mPeriod) && + IsValid(mProvider) && + mMode != X_ORDER_MODE_NOTHING + // + && + // + // TP ... + mFullTPLevel > 0 + // + ; + if (!result) + { + return result; + } + + // + // Prepare Regular Signal Values ... + double _risk = MathAbs(mEntry - mSL); + double _reward = _risk * mFullTPLevel; + + // + bool isLong = IsLong(mType); + + // + sl = mSL; + type = mType; + mode = mMode; + entry = mEntry; + symbol = mSymbol; + period = mPeriod; + volume = mVolume; + provider = mProvider; + fullTPLevel = mFullTPLevel; + tp = isLong + ? mEntry + _reward + : mEntry - _reward; + + // + result = Normalize(); + if (!result) + { + return result; + } + + // + // Calculate Other Conditions ... + + // + bool canPartialClose = + // + mPartialCloseOnTPLevel > 0 && + mPartialCloseMultiplier > 0 && + mPartialCloseOnTPLevel < mFullTPLevel + // + ; + if (canPartialClose) + { + // + partialCloseOnTPLevel = mPartialCloseOnTPLevel; + partialCloseMultiplier = mPartialCloseMultiplier; + } + + // + bool canRFOnBEP = + // + mRiskFreeOnBreakEven && + mTpLevelForBreakEven > 0 + // + ; + if (canRFOnBEP) + { + // + riskFreeOnBreakEven = mRiskFreeOnBreakEven; + tpLevelForBreakEven = mTpLevelForBreakEven; + } + + // + bool canTrailSL = + // + mTrailSL && + mTrailSLStartOnReachTPLevel > 0 && + mTrailSLStartOnReachTPLevel < mFullTPLevel + // + ; + if (canTrailSL) + { + // + trailSL = mTrailSL; + trailSLStartOnReachTPLevel = mTrailSLStartOnReachTPLevel; + } + + // + result = IsValid(); + + // + return result; + } + + // + bool PrepareLong( + string mSymbol, // Trading Symbol + string mProvider, // Signal Provider + ENUM_TIMEFRAMES mPeriod, // Trading TimeFrame + ENUM_X_ORDER_MODES mMode, // Execution Mode + double mEntry, // Entry Price + double mVolume, // Volume + double mSL = 0, // Stop Loss + double mTP = 0 // Take Profit + ) + { + // + return Prepare( + mSymbol, + mProvider, + mPeriod, + POSITION_TYPE_BUY, + mMode, + mEntry, + mVolume, + mSL, + mTP + // + ); + } + + // + bool PrepareShort( + string mSymbol, // Trading Symbol + string mProvider, // Signal Provider + ENUM_TIMEFRAMES mPeriod, // Trading TimeFrame + ENUM_X_ORDER_MODES mMode, // Execution Mode + double mEntry, // Entry Price + double mVolume, // Volume + double mSL = 0, // Stop Loss + double mTP = 0 // Take Profit + ) + { + // + return Prepare( + mSymbol, + mProvider, + mPeriod, + POSITION_TYPE_SELL, + mMode, + mEntry, + mVolume, + mSL, + mTP + // + ); + } + + // + // Market Mode ... + + // + bool PrepareMarketLong( + string mSymbol, // Trading Symbol + string mProvider, // Signal Provider + ENUM_TIMEFRAMES mPeriod, // Trading TimeFrame + double mEntry, // Entry Price + double mVolume, // Volume + double mSL = 0, // Stop Loss + double mTP = 0 // Take Profit + ) + { + // + return PrepareLong( + mSymbol, + mProvider, + mPeriod, + X_ORDER_MODE_MARKET, + mEntry, + mVolume, + mSL, + mTP + // + ); + } + + // + bool PrepareMarketShort( + string mSymbol, // Trading Symbol + string mProvider, // Signal Provider + ENUM_TIMEFRAMES mPeriod, // Trading TimeFrame + double mEntry, // Entry Price + double mVolume, // Volume + double mSL = 0, // Stop Loss + double mTP = 0 // Take Profit + ) + { + // + return PrepareShort( + mSymbol, + mProvider, + mPeriod, + X_ORDER_MODE_MARKET, + mEntry, + mVolume, + mSL, + mTP + // + ); + } + + // + // Stop Mode ... + + // + bool PrepareStopLong( + string mSymbol, // Trading Symbol + string mProvider, // Signal Provider + ENUM_TIMEFRAMES mPeriod, // Trading TimeFrame + double mEntry, // Entry Price + double mVolume, // Volume + double mSL = 0, // Stop Loss + double mTP = 0 // Take Profit + ) + { + // + return PrepareLong( + mSymbol, + mProvider, + mPeriod, + X_ORDER_MODE_STOP, + mEntry, + mVolume, + mSL, + mTP + // + ); + } + + // + bool PrepareStopShort( + string mSymbol, // Trading Symbol + string mProvider, // Signal Provider + ENUM_TIMEFRAMES mPeriod, // Trading TimeFrame + double mEntry, // Entry Price + double mVolume, // Volume + double mSL = 0, // Stop Loss + double mTP = 0 // Take Profit + ) + { + // + return PrepareShort( + mSymbol, + mProvider, + mPeriod, + X_ORDER_MODE_STOP, + mEntry, + mVolume, + mSL, + mTP + // + ); + } + + // + // Limit Mode ... + + // + bool PrepareLimitLong( + string mSymbol, // Trading Symbol + string mProvider, // Signal Provider + ENUM_TIMEFRAMES mPeriod, // Trading TimeFrame + double mEntry, // Entry Price + double mVolume, // Volume + double mSL = 0, // Stop Loss + double mTP = 0 // Take Profit + ) + { + // + return PrepareLong( + mSymbol, + mProvider, + mPeriod, + X_ORDER_MODE_LIMIT, + mEntry, + mVolume, + mSL, + mTP + // + ); + } + + // + bool PrepareLimitShort( + string mSymbol, // Trading Symbol + string mProvider, // Signal Provider + ENUM_TIMEFRAMES mPeriod, // Trading TimeFrame + double mEntry, // Entry Price + double mVolume, // Volume + double mSL = 0, // Stop Loss + double mTP = 0 // Take Profit + ) + { + // + return PrepareShort( + mSymbol, + mProvider, + mPeriod, + X_ORDER_MODE_LIMIT, + mEntry, + mVolume, + mSL, + mTP + // + ); + } + + // + // Generate Opposit Direction ... + bool GenerateOpposit( + XSignal &mSignal // Oppsoit Signal + ) + { + // + bool result = false; + + // + result = IsValid(); + if (!result) + { + return result; + } + + // + ENUM_POSITION_TYPE mType = Opposit(this.type); + double mEntry = GetExit(this.symbol, mType); + + // + bool isLong = IsLong(mType); + + // + // Calculate Risk Reward Ratio ... + double risk = GetRisk(); + double reward = GetReward(); + + // + double mSL = isLong + ? mEntry - risk + : mEntry + risk; + + // + double mTP = isLong + ? mEntry + reward + : mEntry - reward; + + // + result = mSignal.Prepare( + this.symbol, + this.provider, + this.period, + mType, + this.mode, + mEntry, + this.volume, + mSL, + mTP // + ); + + // + return result; + } + + // + // Prepare Opposit Signal based On a Position ... + bool PrepareOpposit( + XPosition &source // Source Data + ) + { + // + bool result = false; + + // + ENUM_POSITION_TYPE mType = Opposit(source.type); + double mEntry = GetEntry(source.symbol, mType); + + // + bool isLong = IsLong(mType); + + // + double risk = source.GetRisk(); + double reward = source.GetReward(); + + // + double mSL = isLong + ? mEntry - risk + : mEntry + risk; + + // + double mTP = isLong + ? mEntry + reward + : mEntry - reward; + + // + return Prepare( + source.symbol, + source.provider, + source.period, + mType, + X_ORDER_MODE_MARKET, + mEntry, + source.volume, + mSL, + mTP // + ); + + // + result = IsValid(); + + // + return result; + } + + // + // Tools ... + + // + // Cleanup ... + void Clean() + { + // + entry = 0; + volume = 0; + pushers = 0; + positionId = 0; + + // + time = NULL; + type = NULL; + mode = NULL; + symbol = NULL; + period = NULL; + comment = NULL; + provider = NULL; + conditions = NULL; + + // + Clean(targets); + ignoreEAVolume = false; + + // + trailSL = false; + riskFreeOnBreakEven = false; + + // + fullTPLevel = 0; + tpLevelForBreakEven = 0; + partialCloseOnTPLevel = 0; + partialCloseMultiplier = 0; + trailSLStartOnReachTPLevel = 0; + + // + Clean(supports); + + // + ZeroMemory(this); + } + + // + // Validate ... + bool IsValid() + { + // + bool result = false; + + // + result = + // + IsValid(period) && + IsValid(symbol) && + NotEmpty(volume) && + NotEmpty(entry) + // + ; + + // + if (!result) + { + return result; + } + + // + return result; + } + + // + // DO All Calculations and Normalizations ... + bool Normalize() + { + // + bool result = false; + + // + // Normalizations ... + symbol = NormalizeSymbol(symbol); + period = NormalizePeriod(period); + + // + time = NormalizeTime(time); + + // + sl = NormalizePrice(sl, symbol); + tp = NormalizePrice(tp, symbol); + entry = NormalizePrice(entry, symbol); + volume = NormalizeVolume(volume, symbol); + + // + result = IsValid(); + + // + return result; + } + + // + // Check Signal Executed or not ... + bool IsExecuted() + { + // + bool result = false; + + // + result = + // + IsValid() && + NotEmpty(positionId) + // + ; + + // + return result; + } + + // + // Generate Comment for Signal ... + string GenerateComment() + { + // + string result = NULL; + + // + if (!IsValid()) + { + return result; + } + + // + if (IsValid(provider)) + { + // + // Generate Provider Tag ... + result += GenerateProviderTag(provider); + } + + // + if (IsValid(period)) + { + // + // Generate Period Tag ... + result += GeneratePeriodTag(period); + } + + // + return result; + } + + // + int GetAge() + { + // + return GetAge( + this, + this.period // + ); + } + + // + // Find Risk ... + double GetRisk() + { + // + double result = 0; + + // + if (!IsValid()) + { + return 0; + } + + // + result = MathAbs(entry - sl); + + // + return result; + } + + // + // Find Reward ... + double GetReward() + { + // + double result = 0; + + // + if (!IsValid()) + { + return result; + } + + // + result = MathAbs(tp - entry); + + // + return result; + } + + // + // Find Risk Reward Ratio ... + double GetRiskRewardRatio() + { + // + double result = 0; + + // + if (!IsValid()) + { + return result; + } + + // + result = GetReward() / GetRisk(); + + // + return result; + } + + // + // Check Can Partial Close on Specified TP Level ... + bool CanPartialClose() + { + // + bool result = false; + + // + result = + IsValid() && + fullTPLevel > 0 && + partialCloseOnTPLevel > 0 && + partialCloseMultiplier > 0 && + partialCloseOnTPLevel < fullTPLevel; + + // + return result; + } + + // + // Check Can Risk Free On Break Even Point ... + bool CanRiskFreeOnBreakEvenPoint() + { + // + bool result = false; + + // + result = + IsValid() && + riskFreeOnBreakEven && + tpLevelForBreakEven > 0; + + // + return result; + } + + // + // Check Can Trail SL ... + bool CanTrailSL() + { + // + bool result = false; + + // + result = + IsValid() && + trailSL && + fullTPLevel > 0 && + trailSLStartOnReachTPLevel > 0 && + trailSLStartOnReachTPLevel < fullTPLevel; + + // + return result; + } + + // + string GetTag() + { + // + string result = NULL; + + // + result = "XSignal_" + + symbol + "_" + + ToString(period) + "_" + + ToString(type) + "_" + + ToString(sl) + "_" + + ToString(tp) + "_" + + ToString(entry); + + // + return result; + } + + // + // Retrieve String Representation of Signal ... + string ToString() + { + // + string result = NULL; + + // + result = + // + ToString("Symbol", symbol) + + ToString("Period", period) + + ToString("Provider", provider) + + ToString("Type", type) + + ToString("Mode", mode) + + ToString("Volume", volume) + + ToString("Entry", entry) + + ToString("TP", tp) + + ToString("SL", sl) + + ToString("Time", time) + + ToString("Comment", comment) + + // + "" + // + ; + + // + return result; + } + + // + bool IsSameAs(XSignal &item) { + // + bool result = false; + + // + result = + // + IsValid() && + item.IsValid() && + // + tp == item.tp && + sl == item.sl && + mode == item.mode && + time == item.time && + type == item.type && + entry == item.entry && + symbol == item.symbol && + period == item.period && + provider == item.provider + // + ; + + // + return result; + } +}; + +// +// Model an Order ... +struct XOrder +{ + // + // Time of order placement ... + datetime setupAt; + + // + // Time of order expiration ... + datetime expiredAt; + + // + // Time of order execution or cancellation ... + datetime executedAt; + + // + // Order type ... + ENUM_ORDER_TYPE type; + + // + // Order state ... + ENUM_ORDER_STATE state; + + // + // Type of execution by remainder ... + ENUM_ORDER_TYPE_FILLING filling; + + // + // Order lifetime ... + ENUM_ORDER_TYPE_TIME lifetime; + + // + // Order ticket ... + ulong ticket; + + // + // Magic Number ... + long magic; + + // + // Position id, that is placed on order, + // when it is executed. Each executed order invokes a + // deal, that opens new or changes existing + // position. Id of that position is placed on + // executed order in this moment. + long positionId; + + // + // Initial volume on order placement ... + double initialVolume; + + // + // Unfilled volume ... + double currentVolume; + + // + // Price, specified in the order ... + double openPrice; + + // + // Current price by order symbol ... + double currentPrice; + + // + // Price of placing Limit order when StopLimit order is triggered ... + double stopLimitPrice; + + // + // Take Profit level ... + double tp; + + // + // Stop Loss level ... + double sl; + + // + // Trading Symbol ... + string symbol; + + // + // Signal Provider ... + string provider; + + // + // Order Comment ... + string comment; + + // + ENUM_TIMEFRAMES period; + + // + // Constructor ... + XOrder() + { + Clean(); + } + + // + // Initializers ... + bool ByIndex( + int index // Fill By Index ... + ) + { + // + bool result = false; + + // + int ordersCount = OrdersTotal(); + if (ordersCount <= 0) + { + return result; + } + + // + static COrderInfo mOrderInfo; + + // + result = mOrderInfo.SelectByIndex(index); + if (!result) + { + return result; + } + + // + // Reading Order Info ... + magic = mOrderInfo.Magic(); + sl = mOrderInfo.StopLoss(); + tp = mOrderInfo.TakeProfit(); + ticket = mOrderInfo.Ticket(); + openPrice = mOrderInfo.PriceOpen(); + positionId = mOrderInfo.PositionId(); + currentPrice = mOrderInfo.PriceCurrent(); + initialVolume = mOrderInfo.VolumeInitial(); + currentVolume = mOrderInfo.VolumeCurrent(); + stopLimitPrice = mOrderInfo.PriceStopLimit(); + + // + symbol = mOrderInfo.Symbol(); + comment = mOrderInfo.Comment(); + + // + state = mOrderInfo.State(); + type = mOrderInfo.OrderType(); + lifetime = mOrderInfo.TypeTime(); + filling = mOrderInfo.TypeFilling(); + + // + setupAt = mOrderInfo.TimeSetup(); + executedAt = mOrderInfo.TimeDone(); + expiredAt = mOrderInfo.TimeExpiration(); + + // + period = ExtractPeriod(comment); + provider = ExtractProvider(comment); + + // + result = IsValid(); + + // + return result; + } + + // + // Retrieve Specific History Order ... + bool HistoryByIndex( + int index // Fill By Index ... + ) + { + // + bool result = false; + + // + int ordersCount = HistoryOrdersTotal(); + if (ordersCount <= 0) + { + return result; + } + + // + static CHistoryOrderInfo mOrderInfo; + + // + result = mOrderInfo.SelectByIndex(index); + if (!result) + { + return result; + } + + // + // Reading Order Info ... + magic = mOrderInfo.Magic(); + sl = mOrderInfo.StopLoss(); + tp = mOrderInfo.TakeProfit(); + ticket = mOrderInfo.Ticket(); + openPrice = mOrderInfo.PriceOpen(); + positionId = mOrderInfo.PositionId(); + currentPrice = mOrderInfo.PriceCurrent(); + initialVolume = mOrderInfo.VolumeInitial(); + currentVolume = mOrderInfo.VolumeCurrent(); + stopLimitPrice = mOrderInfo.PriceStopLimit(); + + // + symbol = mOrderInfo.Symbol(); + comment = mOrderInfo.Comment(); + + // + state = mOrderInfo.State(); + type = mOrderInfo.OrderType(); + lifetime = mOrderInfo.TypeTime(); + filling = mOrderInfo.TypeFilling(); + + // + setupAt = mOrderInfo.TimeSetup(); + executedAt = mOrderInfo.TimeDone(); + expiredAt = mOrderInfo.TimeExpiration(); + + // + period = ExtractPeriod(comment); + provider = ExtractProvider(comment); + + // + result = IsValid(); + + // + return result; + } + + // + // Tools ... + + // + // Cleanup ... + void Clean() + { + // + tp = 0; + sl = 0; + magic = 0; + ticket = 0; + positionId = 0; + openPrice = 0; + currentPrice = 0; + initialVolume = 0; + currentVolume = 0; + stopLimitPrice = 0; + + // + setupAt = NULL; + expiredAt = NULL; + executedAt = NULL; + + // + symbol = NULL; + comment = NULL; + provider = NULL; + + // + type = NULL; + state = NULL; + period = NULL; + filling = NULL; + lifetime = NULL; + + // + ZeroMemory(this); + } + + // + // Validate ... + bool IsValid() + { + // + bool result = false; + + // + result = + // + IsValid(symbol) && + NotEmpty(ticket) && + NotEmpty(positionId) + // + ; + + // + return result; + } + + // + // Calculate Age ... + int GetAge( + ENUM_TIMEFRAMES mPeriod // Calculate Age based on this period + ) + { + return GetAge(this, mPeriod); + } + + // + // Check this instance is Same os Given instance or not ... + bool IsSameAs( + const XOrder &value // instance for Compare + ) + { + // + bool result = false; + + // + result = + // + type == value.type && + state == value.state && + magic == value.magic && + ticket == value.ticket && + symbol == value.symbol && + provider == value.provider && + positionId == value.positionId + // + ; + + // + return result; + } + + // + // Find index in a Collection ... + int FindIndex( + const XOrder &values[] // Collection to Find + ) + { + // + return FindIndex( + this, + values + // + ); + } + + // + // Check Items Passed Specific Filters or not ... + bool IsFiltersPassed( + string mSymbol = NULL, // Trading Symbol + string mProvider = NULL, // Signal Provider + ENUM_TIMEFRAMES mPeriod = NULL, // Trading Timeframe + ENUM_X_POSITION_TYPES mType = NULL, // Long (Buy), Short (Sell) + ENUM_ORDER_STATE mState = NULL, // Order State + ulong mMagic = NULL, // Magic Number + bool mFilterByMagic = true // Get Only Self Open Positions + ) + { + // + bool result = false; + + // + result = + // + // Magic Filter ... + IsMagicFilterPassed( + mMagic, + mFilterByMagic, + this + // + ) + // + && + // + // Symbol Filter ... + IsSymbolFilterPassed( + mSymbol, + this + // + ) + // + && + // + // Provider Filter ... + IsProviderFilterPassed( + mProvider, + this + // + ) + // + && + // + // Period Filter ... + IsPeriodFilterPassed( + mPeriod, + this + // + ) + // + && + // + // Type Filter ... + IsTypeFilterPassed( + mType, + this + // + ) + // + && + // + // State Filter ... + IsStateFilterPassed( + mState, + this + // + ) + // + ; + + // + return result; + } +}; + +// +// Model a Deal ... +struct XDeal +{ + // + // the ID of the Expert Advisor, that executed the deal ... + ulong magic; + + // + // the ID of position, in which the deal was involved ... + ulong positionId; + + // + // Ticket ... + ulong ticket; + + // + // the name of the deal symbol ... + string symbol; + + // + // order by which the deal is executed ... + ulong order; + + // + // the time of deal execution ... + datetime time; + + // + // Deal price ... + double price; + + // + // the financial result of the deal (in deposit currency) ... + double profit; + + // + // the amount of swap when position is closed ... + double swap; + + // + // the amount of commission of the deal ... + double commission; + + // + // the volume of deal ... + double volume; + + // + // the deal comment ... + string comment; + + // + string provider; + + // + ENUM_TIMEFRAMES period; + + // + // the deal type ... + // ------------------------------------------------------------------ + // DEAL_TYPE_BUY => Buy ... + // DEAL_TYPE_SELL => Sell ... + // DEAL_TYPE_BUY_CANCELED => Canceled buy deal ... + // There can be a situation when a previously executed buy deal is canceled. In this case, + // the type of the previously executed deal (DEAL_TYPE_BUY) is changed to DEAL_TYPE_BUY_CANCELED, + // and its profit/loss is zeroized. Previously obtained profit/loss is charged/withdrawn using a separated balance operation ... + // + // DEAL_TYPE_SELL_CANCELED => Canceled sell deal ... + // There can be a situation when a previously executed sell deal is canceled. In this case, + // the type of the previously executed deal (DEAL_TYPE_SELL) is changed to DEAL_TYPE_SELL_CANCELED, + // and its profit/loss is zeroized. Previously obtained profit/loss is charged/withdrawn using a separated balance operation + // + // DEAL_TYPE_BALANCE => Balance ... + // DEAL_TYPE_CREDIT => Credit ... + // DEAL_TYPE_CHARGE => Additional charge ... + // DEAL_TYPE_CORRECTION => Correction ... + // DEAL_TAX => Tax charges ... + // DEAL_TYPE_BONUS => Bonus ... + // DEAL_TYPE_INTEREST => Interest rate ... + // DEAL_DIVIDEND => Dividend operations... + // DEAL_DIVIDEND_FRANKED => Franked (non-taxable) dividend operations ... + // DEAL_TYPE_COMMISSION => Additional commission ... + // DEAL_TYPE_COMMISSION_DAILY => Daily commission ... + // DEAL_TYPE_COMMISSION_MONTHLY => Monthly commission ... + // DEAL_TYPE_COMMISSION_AGENT_DAILY => Daily agent commission ... + // DEAL_TYPE_COMMISSION_AGENT_MONTHLY => Monthly agent commission + ENUM_DEAL_TYPE type; + + // + // the deal direction ... + // ---------------------------------- + // DEAL_ENTRY_IN => Entry in ... + // DEAL_ENTRY_OUT => Entry out ... + // DEAL_ENTRY_INOUT => Reverse ... + // DEAL_ENTRY_OUT_BY => Close a position by an opposite one ... + ENUM_DEAL_ENTRY entry; + + // + // deal reson ... + // --------------------- + // DEAL_REASON_SL => The deal was executed as a result of Stop Loss activation ... + // DEAL_REASON_TP => The deal was executed as a result of Take Profit activation ... + // DEAL_REASON_SO => The deal was executed as a result of the Stop Out event ... + // DEAL_REASON_WEB => The deal was executed as a result of activation of an order placed from the web platform ... + // DEAL_REASON_SPLIT => The deal was executed after the split (price reduction) of an instrument, which had an open position during split announcement ... + // DEAL_REASON_CLIENT => The deal was executed as a result of activation of an order placed from a desktop terminal ... + // DEAL_REASON_MOBILE => The deal was executed as a result of activation of an order placed from a mobile application ... + // DEAL_REASON_EXPERT => The deal was executed as a result of activation of an order placed from an MQL5 program, i.e. an Expert Advisor or a script ... + // DEAL_REASON_VMARGIN => The deal was executed after charging the variation margin ... + // DEAL_REASON_ROLLOVER => The deal was executed due to a rollover ... + ENUM_DEAL_REASON reason; + + // + // Constructor ... + XDeal() + { + Clean(); + } + + // + // Initializers ... + bool ByIndex( + int index // Deal Index + ) + { + // + bool result = false; + + // + int dealsCount = HistoryDealsTotal(); + result = dealsCount > 0; + if (!result) + { + return result; + } + + // + static CDealInfo mDealInfo; + + // + result = mDealInfo.SelectByIndex(index); + if (!result) + { + // + return result; + } + + // + // Reading Order Info ... + swap = mDealInfo.Swap(); + magic = mDealInfo.Magic(); + order = mDealInfo.Order(); + ticket = mDealInfo.Ticket(); + time = mDealInfo.Time(); + price = mDealInfo.Price(); + symbol = mDealInfo.Symbol(); + profit = mDealInfo.Profit(); + volume = mDealInfo.Volume(); + comment = mDealInfo.Comment(); + positionId = mDealInfo.PositionId(); + entry = mDealInfo.Entry(); + commission = mDealInfo.Commission(); + type = mDealInfo.DealType(); + reason = (ENUM_DEAL_REASON)HistoryDealGetInteger( + ticket, + DEAL_REASON); + + // + period = ExtractPeriod(comment); + provider = ExtractProvider(comment); + + // + result = IsValid(); + + // + return result; + } + + // + // Tools ... + + // + // Cleanup ... + void Clean() + { + // + magic = 0; + positionId = 0; + ticket = 0; + order = 0; + time = 0; + price = 0; + profit = 0; + swap = 0; + commission = 0; + volume = 0; + + // + symbol = NULL; + comment = NULL; + provider = NULL; + + // + type = NULL; + entry = NULL; + period = NULL; + reason = NULL; + + // + ZeroMemory(this); + } + + // + // Validate ... + bool IsValid() + { + // + bool result = false; + + // + result = + // + IsValid(symbol) && + NotEmpty(ticket) && + NotEmpty(positionId) + // + ; + + // + return result; + } + + // + // Calculate Age ... + int GetAge( + ENUM_TIMEFRAMES mPeriod // Calculate Age based on this period + ) + { + return GetAge(this, mPeriod); + } + + // + // Check this instance is Same os Given instance or not ... + bool IsSameAs( + const XDeal &value // instance for Compare + ) + { + // + bool result = false; + + // + result = + // + type == value.type && + magic == value.magic && + entry == value.entry && + reason == value.reason && + ticket == value.ticket && + volume == value.volume && + symbol == value.symbol && + provider == value.provider && + positionId == value.positionId + // + ; + + // + return result; + } + + // + // Find index in a Collection ... + int FindIndex( + const XDeal &values[] // Collection to Find + ) + { + // + return FindIndex( + this, + values + // + ); + } + + // + // Check Items Passed Specific Filters or not ... + bool IsFiltersPassed( + string mSymbol = NULL, // Trading Symbol + string mProvider = NULL, // Signal Provider + ENUM_TIMEFRAMES mPeriod = NULL, // Trading Timeframe + ENUM_DEAL_TYPE mType = NULL, // Deal Type + ENUM_DEAL_ENTRY mEntry = NULL, // Deal Entry + ENUM_DEAL_REASON mReason = NULL, // Deal Reason + ulong mMagic = NULL, // Magic Number + bool mFilterByMagic = true // Get Only Self Open Positions + ) + { + // + bool result = false; + + // + result = + // + // Magic Filter ... + IsMagicFilterPassed( + mMagic, + mFilterByMagic, + this + // + ) + // + && + // + // Symbol Filter ... + IsSymbolFilterPassed( + mSymbol, + this + // + ) + // + && + // + // Provider Filter ... + IsProviderFilterPassed( + mProvider, + this + // + ) + // + && + // + // Period Filter ... + IsPeriodFilterPassed( + mPeriod, + this + // + ) + // + && + // + // Type Filter ... + IsTypeFilterPassed( + mType, + this + // + ) + // + && + // + // Entry Filter ... + IsEntryFilterPassed( + mEntry, + this + // + ) + // + && + // + // Reason Filter ... + IsReasonFilterPassed( + mReason, + this + // + ) + // + ; + + // + return result; + } +}; + +// +// Model OnTrade Event Handler Result on XCTrade Class ... +struct XOnTradeHandlerState +{ + // + bool hasNewDeal; + int newDeals; + + // + bool hasNewOrder; + int newOrders; + + // + bool hasNewPosition; + int newPositions; + + // + bool hasNewHistoryOrder; + int newHistoryOrders; + + // + // Constructor ... + XOnTradeHandlerState() + { + Clean(); + } + + // + // Tools ... + + // + // Cleanup ... + void Clean() + { + // + hasNewDeal = false; + hasNewOrder = false; + hasNewPosition = false; + hasNewHistoryOrder = false; + + // + newDeals = 0; + newOrders = 0; + newPositions = 0; + newHistoryOrders = 0; + + // + ZeroMemory(this); + } + + // + // Validate ... + bool IsValid() + { + // + bool result = false; + + // + result = + // + ( + // + hasNewDeal + ? newDeals > 0 + : true + // + ) + // + && + // + ( + // + hasNewOrder + ? newOrders > 0 + : true + // + ) + // + && + // + ( + // + hasNewPosition + ? newPositions > 0 + : true + // + ) + // + && + // + ( + // + hasNewHistoryOrder + ? newHistoryOrders > 0 + : true + // + ) + // + ; + + // + return result; + } +}; + +// +// Model Guard Info ... +struct XGuard +{ + // + string symbol; // Trading Symbol ... + string provider; // Signal Provider ... + ENUM_TIMEFRAMES period; // Trading Timeframe ... + ENUM_X_POSITION_TYPES type; // Position Type ... + ENUM_X_GUARD_ACTIONS action; // Which Action to Do ... + + // + double dblPayLoad; + string strPayload; + + // + // Constructor ... + XGuard() + { + Clean(); + } + + // + // Initialize ... + + // + // Global Initializer ... + bool Init( + string mSymbol, // Trading Symbol ... + ENUM_TIMEFRAMES mPeriod, // Trading Timeframe ... + ENUM_X_GUARD_ACTIONS mAction, // Which Action to Do ... + ENUM_X_POSITION_TYPES mType = NULL, // Position Type ... + string mProvider = NULL, // Signal Provider ... + double mDblPayLoad = NULL, + string mStrPayload = NULL // + ) + { + // + type = mType; + symbol = mSymbol; + period = mPeriod; + action = mAction; + provider = mProvider; + dblPayLoad = mDblPayLoad; + strPayload = mStrPayload; + + // + bool result = IsValid(); + + // + return result; + } + + // + // Tools ... + + // + // Cleanup ... + void Clean() + { + // + symbol = NULL; + provider = NULL; + period = NULL; + action = X_GUARD_ACTION_NOTHING; + + // + strPayload = NULL; + dblPayLoad = EMPTY_VALUE; + + // + ZeroMemory(this); + } + + // + // Validate ... + bool IsValid() + { + // + bool result = false; + + // + result = + // + action != X_GUARD_ACTION_NOTHING + // + ; + + // + return result; + } +}; + +// +// Model a Position with all of it's Supports ... +struct XPositionPack +{ + // + ulong ticket; // Main Position's Ticket + + // + XPosition position; // Main Position (if Exists) + + // + int supportOrdersCount; // Supported Orders (Untriggered) + int supportPositionsCount; // Supported Positions + + // + XOrder supportOrders[]; // Supported Orders (Untriggered) + XPosition supportPositions[]; // Supported Positions + + // + // Constructor ... + XPositionPack() + { + Clean(); + } + + // + // Tools ... + + // + // Cleanup ... + void Clean() + { + // + ticket = 0; + + // + position.Clean(); + + // + supportOrdersCount = 0; + supportPositionsCount = 0; + + // + Clean(supportOrders); + Clean(supportPositions); + + // + ZeroMemory(this); + } + + // + // Validate ... + bool IsValid() + { + // + bool result = false; + + // + result = + // + NotEmpty(ticket) && + ( + // + supportOrdersCount > 0 + ? ArraySize(supportOrders) == supportOrdersCount + : true + // + ) + // + && + // + ( + // + supportPositionsCount > 0 + ? ArraySize(supportPositions) == supportPositionsCount + : true + // + ) + // + ; + + // + return result; + } +}; + +// +// Check Position SL Trails Structure ... +struct XTrail +{ + // + ulong ticket; // Position Ticket ... + ENUM_POSITION_TYPE type; // Type ... + datetime time; // Trail Time ... + double before; // SL Value Before Trailing ... + double after; // SL Value After Trailing ... + int level; // Number of Trails SL ... + double profit; // Profit in SL Time ... + + // + // Constructor ... + XTrail() + { + Clean(); + } + + // + // Tools ... + + // + bool Init( + ulong mTicket, // Ticket + ENUM_POSITION_TYPE mType, // Type + double mProfit, // Profit + double mBefore, // Before + double mAfter // After + ) + { + // + Clean(); + + // + type = mType; + after = mAfter; + ticket = mTicket; + before = mBefore; + profit = mProfit; + + // + level++; + + // + time = TimeCurrent(); + + // + return IsValid(); + } + + // + bool Update( + double mSl, // new SL ... + double mProfit // Profit + ) + { + // + bool result = false; + + // + time = TimeCurrent(); + + // + double cAfter = after; + after = mSl; + before = cAfter; + profit = mProfit; + + // + level++; + + // + result = IsValid(); + + // + return result; + } + + // + string GenerateTag() + { + // + string result = NULL; + + // + string ticketLevelStr = ToString(ticket) + "," + ToString(level); + + // + result = Surround( + XSLTrailToken, + ticketLevelStr // + ); + + // + return result; + } + + // + // Cleanup ... + void Clean() + { + // + ticket = 0; + time = 0; + before = 0; + after = 0; + level = 0; + + // + ZeroMemory(this); + } + + // + // Validate ... + bool IsValid() + { + // + bool result = false; + + // + result = + // + ticket > 0 && + time > 0 && + level > 0 + // + ; + + // + return result; + } +}; + +// +struct XSymbolPositions +{ + // + string symbol; + + // + double profit; + double volume; + + // + double longsProfit; + double longSupportsProfit; + + // + double shortsProfit; + double shortSupportsProfit; + + // + double longsVolume; + double longSupportsVolume; + + // + double shortsVolume; + double shortSupportsVolume; + + // + double requiredProfitForHedge; + + // + XPosition longs[]; + XPosition shorts[]; + XPosition supports[]; + XPosition positions[]; + XPosition longSupports[]; + XPosition shortSupports[]; + + // + bool forceHedge; + + // + XSymbolPositions() + { + Clean(); + } + + // + bool Update( + double mMinProfitPerTrade, + double mMinProfitPerVolumeFactor // + ) + { + // + bool result = false; + + // + bool hasChild = HasChild(); + if (!hasChild) + { + return result; + } + + // + XPosition _supports[]; + XPosition _positions[]; + + // + XPosition _tmp[]; + + // + Copy( + positions, + _tmp // + ); + + // + Clean(positions); + + // + int tmpsCount = ArraySize(_tmp); + for (int i = 0; i < tmpsCount; i++) + { + // + XPosition iPosition = _tmp[i]; + + // + bool isSupport = IsSupport(iPosition.comment); + if (!isSupport) + { + // + AddRef( + iPosition, + _positions // + ); + } + else + { + // + AddRef( + iPosition, + _supports // + ); + } + } + + // + Clean(_tmp); + + // + Copy( + _positions, + positions // + ); + Clean(_positions); + + // + // Extract Types ... + ExtractPositions( + positions, + longs, + shorts // + ); + + // + Copy( + _supports, + supports // + ); + Clean(_supports); + + // + // Extract Types ... + ExtractPositions( + supports, + longSupports, + shortSupports // + ); + + // + int numOfLongs = 0; + int numOfShorts = 0; + CountPositions( + positions, + numOfLongs, + longsProfit, + longsVolume, + numOfShorts, + shortsProfit, + shortsVolume // + ); + + // + numOfLongs = 0; + numOfShorts = 0; + CountPositions( + supports, + numOfLongs, + longSupportsProfit, + longSupportsVolume, + numOfShorts, + shortSupportsProfit, + shortSupportsVolume // + ); + + // + XPosition _allPositions[]; + Copy( + positions, + _allPositions, + false // + ); + Copy( + supports, + _allPositions, + false // + ); + + // + profit = longsProfit + shortsProfit + longSupportsProfit + shortSupportsProfit; + volume = longsVolume + shortsVolume + longSupportsVolume + shortSupportsVolume; + requiredProfitForHedge = SpecifiedCalculateRequiredProfitForHedge( + _allPositions, + mMinProfitPerTrade, + mMinProfitPerVolumeFactor // + ); + + // + Clean(_allPositions); + + // + result = true; + + // + return result; + } + + // + // Tools ... + + // + // Cleanup ... + void Clean() + { + // + symbol = NULL; + forceHedge = false; + + // + profit = 0; + longsProfit = 0; + shortsProfit = 0; + + // + volume = 0; + longsVolume = 0; + shortsVolume = 0; + + // + requiredProfitForHedge = 0; + + // + Clean(longs); + Clean(shorts); + Clean(positions); + + // + ZeroMemory(this); + } + + // + // Validate ... + bool IsValid() + { + // + bool result = false; + + // + result = IsValid(symbol); + + // + return result; + } + + // + // Has Child ... + bool HasChild() + { + // + bool result = false; + + // + result = IsValid(); + if (!result) + { + return result; + } + + // + int count = Count(); + result = IsValidSize(count); + + // + return result; + } + + // + // Count ... + int Count() + { + return ArraySize(positions); + } + + // + int CountSupports() + { + return ArraySize(supports); + } + + // + int CountLongs() + { + return ArraySize(longs); + } + + // + int CountShorts() + { + return ArraySize(shorts); + } + + // + int CountLongSupports() + { + return ArraySize(longSupports); + } + + // + int CountShortSupports() + { + return ArraySize(shortSupports); + } + + // + int GetOldest( + XPosition &_oldest, // + ENUM_POSITION_TYPE _type // + ) + { + // + int result = -1; + + // + bool isLong = IsLong(_type); + + // + int count = + isLong + ? CountLongs() + : CountShorts(); + if (!IsValidSize(count)) + { + return result; + } + + // + if (isLong) + { + // + result = GetOldest( + _oldest, + longs // + ); + } + else + { + // + result = GetOldest( + _oldest, + shorts // + ); + } + + // + return result; + } + + // + int GetYoungest( + XPosition &_youngest, // + ENUM_POSITION_TYPE _type // + ) + { + // + int result = -1; + + // + bool isLong = IsLong(_type); + + // + int count = + isLong + ? CountLongs() + : CountShorts(); + if (!IsValidSize(count)) + { + return result; + } + + // + if (isLong) + { + // + result = GetYoungest( + _youngest, + longs // + ); + } + else + { + // + result = GetYoungest( + _youngest, + shorts // + ); + } + + // + return result; + } + + // + int GetMaxInProfit( + XPosition &_position, + ENUM_POSITION_TYPE _type // + ) + { + // + int result = -1; + + // + bool isLong = IsLong(_type); + + // + int count = + isLong + ? CountLongs() + : CountShorts(); + if (!IsValidSize(count)) + { + return result; + } + + // + if (isLong) + { + // + result = FindMaxProfitIndex( + longs // + ); + + // + if (IsValidIndex(result)) + { + _position = longs[result]; + } + } + else + { + // + result = FindMaxProfitIndex( + shorts // + ); + + // + if (IsValidIndex(result)) + { + _position = shorts[result]; + } + } + + // + return result; + } + + // + int GetMinInProfit( + XPosition &_position, + ENUM_POSITION_TYPE _type // + ) + { + // + int result = -1; + + // + bool isLong = IsLong(_type); + + // + int count = + isLong + ? CountLongs() + : CountShorts(); + if (!IsValidSize(count)) + { + return result; + } + + // + if (isLong) + { + // + result = FindMinProfitIndex( + longs // + ); + + // + if (IsValidIndex(result)) + { + _position = longs[result]; + } + } + else + { + // + result = FindMinProfitIndex( + shorts // + ); + + // + if (IsValidIndex(result)) + { + _position = shorts[result]; + } + } + + // + return result; + } + + // + int GetMaxInDrawdown( + XPosition &_position, + ENUM_POSITION_TYPE _type // + ) + { + // + int result = -1; + + // + bool isLong = IsLong(_type); + + // + int count = + isLong + ? CountLongs() + : CountShorts(); + if (!IsValidSize(count)) + { + return result; + } + + // + if (isLong) + { + // + result = FindMaxInDrawdownIndex( + longs // + ); + + // + if (IsValidIndex(result)) + { + _position = longs[result]; + } + } + else + { + // + result = FindMaxInDrawdownIndex( + shorts // + ); + + // + if (IsValidIndex(result)) + { + _position = shorts[result]; + } + } + + // + return result; + } + + // + int GetMinInDrawdown( + XPosition &_position, + ENUM_POSITION_TYPE _type // + ) + { + // + int result = -1; + + // + bool isLong = IsLong(_type); + + // + int count = + isLong + ? CountLongs() + : CountShorts(); + if (!IsValidSize(count)) + { + return result; + } + + // + if (isLong) + { + // + result = FindMinInDrawdownIndex( + longs // + ); + + // + if (IsValidIndex(result)) + { + _position = longs[result]; + } + } + else + { + // + result = FindMinInDrawdownIndex( + shorts // + ); + + // + if (IsValidIndex(result)) + { + _position = shorts[result]; + } + } + + // + return result; + } + + // +}; + +// +struct XSymbolLastPosition +{ + // + string symbol; + string provider; + datetime time; + + // + XSymbolLastPosition() + { + Clean(); + } + + // + // Tools ... + + void Clean() + { + // + time = NULL; + symbol = NULL; + provider = NULL; + + // + ZeroMemory(this); + } +}; + +// +// an Structure for Holding Positions Data ... +struct XTradeData +{ + // + datetime time; // Issue Time (Open Position) + string symbol; // Trading Symbol + double entry; // Entry Price + double volume; // Volume + string provider; // Signaller + ENUM_TIMEFRAMES period; // Trading Timeframe + ENUM_X_POSITION_TYPES type; // Position Type + + // + ulong ticket; // Position Ticket + double swap; // Swap + double profit; // Profit on Close + double commission; // Commission + double maxDrawdown; // Max Position Drawdown + string message; // Close Reason + datetime endTime; // End Time + + // + XSignal signal; // Signal Object + int pushers; // Signal Pushers + string conditions; // Signal Conditions + + // + // Constructor ... + void XTradeInfo() + { + Clean(); + } + + // + // Filling Trade Handler ... + bool Fill(XSignal &_signal) + { + // + bool result = false; + + // + Clean(); + + // + // Check Signal Validation ... + result = _signal.IsValid(); + if (!result) + { + return result; + } + + // + signal = _signal; + time = _signal.time; + entry = _signal.entry; + symbol = _signal.symbol; + volume = _signal.volume; + period = _signal.period; + pushers = _signal.pushers; + provider = _signal.provider; + conditions = _signal.conditions; + type = ToPositionType(_signal.type); + + // + if (_signal.IsExecuted()) + { + ticket = _signal.positionId; + } + + // + return result; + } + + // + // Filling Trade Handler ... + bool Fill(XPosition &_position) + { + // + bool result = false; + + // + Clean(); + + // + // Check Signal Validation ... + result = _position.IsValid(); + if (!result) + { + return result; + } + + // + time = _position.openAt; + symbol = _position.symbol; + entry = _position.entry; + volume = _position.volume; + provider = _position.provider; + period = _position.period; + type = ToPositionType(_position.type); + + // + ticket = _position.ticket; + + // + return result; + } + + // + // Update Data ... + bool Update(XPosition &_position) + { + // + bool result = false; + + // + result = _position.IsValid(); + if (!result) + { + return result; + } + + // + profit = _position.profit; + swap = _position.swap; + + // + if (profit < 0 && + (maxDrawdown == 0 || + MathAbs(profit) > MathAbs(maxDrawdown))) + { + maxDrawdown = profit; + } + + // + return result; + } + + // + // Tools ... + + // + // Cleanup ... + void Clean() + { + // + time = NULL; + type = NULL; + symbol = NULL; + period = NULL; + endTime = NULL; + message = NULL; + provider = NULL; + + // + swap = 0; + entry = 0; + ticket = 0; + profit = 0; + volume = 0; + commission = 0; + maxDrawdown = 0; + + // + signal.Clean(); + + // + ResetTrail(); + ResetRecovery(); + + // + ZeroMemory(this); + } + + // + // Validation ... + bool IsValid() + { + // + bool result = false; + + // + result = + // + ticket > 0 && + IsValid(time) && + IsValid(symbol) && + IsValid(period) + // + ; + + // + return result; + } + + // + // Retrieve Trade Data Age ... + int GetAge() + { + // + int result = -1; + + // + if (!IsValid(symbol) || + !IsValid(time) || + !IsValid(endTime) || + !IsValid(period)) + { + return result; + } + + // + int startIndex = iBarShift( + symbol, + period, + time, + false // + ); + + // + int endIndex = iBarShift( + symbol, + period, + endTime, + false // + ); + + // + result = MathAbs(startIndex - endIndex); + + // + return result; + } + + // + // Check Own of Trade Data ... + // based on Ticket ... + bool IsOwn( + ulong _ticket // + ) + { + // + bool result = false; + + // + result = _ticket == ticket; + + // + return result; + } + + // + // Check Own of Trade Data ... + // based on Symbol/Provider and Period ... + bool IsOwn( + string _symbol, + string _provider, + ENUM_TIMEFRAMES _period, + ENUM_X_POSITION_TYPES _type // + ) + { + // + bool result = false; + + // + result = + // + IsValid(_symbol) && + IsValid(_period) && + IsValid(_provider) && + type != X_POSITION_TYPE_ALL && + type != X_POSITION_TYPE_NONE && + // + type == _type && + period == _period && + symbol == _symbol && + provider == _provider + // + ; + + // + return result; + } + + // + // Data Collector ... + + // + // Get Data File Name ... + string GetFileName() + { + // + string result = NULL; + + // + if (!IsValid()) + { + return result; + } + + // + result = + // + symbol + "\\" + + ToString(type) + "\\" + + (profit >= 0 ? "Profit" : "Loss") + "\\" + + ToString(ticket) + "_" + + ToString(period) + "_" + + ToFormatString(time) + // + ; + + // + return result; + } + + // + // Get Signal File Name ... + string GetSignalFileName() + { + // + string result = NULL; + + // + result = + // + symbol + "\\" + + ToString(type) + "\\" + + provider + "_" + + ToFormatString(time) + // + ; + + // + return result; + } + + // + // Convert(s) To String Representation(s) ... + string ToString( + bool onlySignals = false // + ) + { + // + string result = NULL; + + // + int age = GetAge(); + + // + result = + // + (onlySignals + ? "" + : ToString("Ticket", ticket)) + + ToString("Symbol", symbol) + + ToString("Period", period) + + ToString("Entry", entry) + + ToString("Provider", provider) + + ToString("Type", ToString(type)) + + ToString("Time", time) + + // + // Attach Trade Info ... + (onlySignals + ? "" + : + // + "-------------" + "\n" + + ToString("Volume", volume) + + ToString("Profit", profit) + + ToString("Commission", commission) + + ToString("Swap", swap) + + ToString("Max Drawdown", maxDrawdown) + + ToString("End Time", endTime) + + ToString("Age", age) + + ToString("Message", message) + + "" + // + ) + + // + // Attach Conditions to Signals ... + (!onlySignals + ? "" + : + // + "-------------" + "\n" + + ToString("Pushers", pushers) + + "Conditions:" + "\n" + + "-------------" + "\n" + + conditions + + "" + // + ) + + // + "" + // + ; + + // + return result; + } + + // + // There are some Controlling Situations for each Trade + // which implemented here ... + + // + // Trailing Stop .... + + // + bool allowTrailStop; // Specified Position Can Trail Stop or not + bool ignoreTPOnTrail; // Ignore TP when SL Trailed + bool trailBasedOnProfit; // Do Trail Based on Profit Points + int trailLevel; // Last Trail Level + double trailStartInPoint; // Trail Starts When Profits Growing in Point + double trailStepInPoint; // Profit Must Grows Point to do Trailling + + // + // Reset all Trailing Configurations .... + void ResetTrail() + { + // + trailLevel = 0; + trailStepInPoint = 0; + trailStartInPoint = 0; + allowTrailStop = false; + ignoreTPOnTrail = false; + trailBasedOnProfit = false; + } + + // + // Recovery ... + + // + bool allowRecover; // Allow Recover Specified Position + double recoveryTPPoint; // Recovery TP Point + double recoverySLPoint; // Recovery SL Point + int maxAllowedRecover; // Max Allowed Recovery + int recoveryLevel; // Number of Recovery Signals + double recoveryVolumeMultiplier; // Recovery Volume Multiplier + double recoveryVolume; // Next Recovery Positioin Volume + ENUM_X_POSITION_TYPES recoveryLookingType; // Looking for Next Recovery Type + + // + void ResetRecovery() + { + // + allowRecover = false; + recoveryLevel = 0; + recoveryVolume = 0; + recoveryTPPoint = 0; + recoverySLPoint = 0; + recoveryVolumeMultiplier = 0; + recoveryLookingType = X_POSITION_TYPE_NONE; + } + + // +}; + +// +// TypeDefs ... + +// +typedef void (*TOnSignal)(XSignal &signal); + +// +typedef void (*TOnDealsChanged)(int count); + +// +typedef void (*TOnOrdersChanged)(int count); + +// +typedef void (*TOnPositionsChanged)(int count); + +// +typedef void (*TOnStopLoss)(const XDeal &deal); +typedef void (*TOnTakeProfit)(const XDeal &deal); + +// +typedef void (*TOnTradeStateChanged)(const XOnTradeHandlerState &state); + +// +typedef void (*TOnForceClose)( + const ulong ticket, + const XPosition &position, + const string comment // +); + +// +typedef void (*TOnPartialClose)( + const ulong ticket, + const double profit, + const string comment // +); + +// +typedef void (*TOnModify)( + const ulong ticket, + const double profit, + const string comment // +); + +// +// Classes ... + +// +// Tools ... + +// +bool IsValid(ENUM_X_ORDER_MODES value) +{ + return value != X_ORDER_MODE_NOTHING; +} + +// +// Ages ... + +// +// Retrieve a Position Age ... +int GetAge( + XSignal &signal, // Selected Signal ... + ENUM_TIMEFRAMES period = NULL // Dest Time Frame ... +) +{ + // + int result = -1; + + // + if (period == NULL) + { + period = _Period; + } + + // + result = iBarShift( + signal.symbol, + period, + signal.time); + + // + return result; +} + +// +// Retrieve a Position Age ... +int GetAge( + XPosition &position, // Selected Position ... + ENUM_TIMEFRAMES period = NULL // Dest Time Frame ... +) +{ + // + int result = -1; + + // + if (period == NULL) + { + period = _Period; + } + + // + result = iBarShift( + position.symbol, + period, + position.openAt); + + // + return result; +} + +// +// Retrieve an Order Age ... +int GetAge( + XOrder &order, // Selected Order ... + ENUM_TIMEFRAMES period = NULL // Dest Time Frame ... +) +{ + // + int result = -1; + + // + if (period == NULL) + { + period = _Period; + } + + // + result = iBarShift( + order.symbol, + period, + order.setupAt); + + // + return result; +} + +// +// Retrieve a Deal Age ... +int GetAge( + XDeal &deal, // Selected Deal ... + ENUM_TIMEFRAMES period = NULL // Dest Time Frame ... +) +{ + // + int result = -1; + + // + if (period == NULL) + { + period = _Period; + } + + // + result = iBarShift( + deal.symbol, + period, + deal.time); + + // + return result; +} + +// +// Get Oldest Deal ... +int GetOldest( + XDeal &item, // Hold Result ... + XDeal &items[] // Source Array ... +) +{ + // + int result = -1; + + // + int itemsCount = ArraySize(items); + if (itemsCount <= 0) + { + return result; + } + + // + int tmpAge = 0; + XDeal tmpItem; + for (int i = 0; i < itemsCount; i++) + { + // + XDeal iItem = items[i]; + + // + int iAge = GetAge(iItem); + if (iAge > 0 && + (tmpAge == 0 || tmpAge < iAge)) + { + // + tmpAge = iAge; + tmpItem = iItem; + } + } + + // + if (tmpAge > 0) + { + // + result = tmpAge; + item = tmpItem; + } + + // + return result; +} + +// +// Get Youngest Deal ... +int GetYoungest( + XDeal &item, // Hold Result ... + XDeal &items[] // Source Array ... +) +{ + // + int result = -1; + + // + int itemsCount = ArraySize(items); + if (itemsCount <= 0) + { + return result; + } + + // + int tmpAge = 0; + XDeal tmpItem; + for (int i = 0; i < itemsCount; i++) + { + // + XDeal iItem = items[i]; + + // + int iAge = GetAge(iItem); + if (iAge > 0 && + (tmpAge == 0 || tmpAge > iAge)) + { + // + tmpAge = iAge; + tmpItem = iItem; + } + } + + // + if (tmpAge > 0) + { + // + result = tmpAge; + item = tmpItem; + } + + // + return result; +} + +// +// Get Oldest Order ... +int GetOldest( + XOrder &item, // Hold Result ... + XOrder &items[] // Source Array ... +) +{ + // + int result = -1; + + // + int itemsCount = ArraySize(items); + if (itemsCount <= 0) + { + return result; + } + + // + int tmpAge = 0; + XOrder tmpItem; + for (int i = 0; i < itemsCount; i++) + { + // + XOrder iItem = items[i]; + + // + int iAge = GetAge(iItem); + if (iAge > 0 && + (tmpAge == 0 || tmpAge < iAge)) + { + // + tmpAge = iAge; + tmpItem = iItem; + } + } + + // + if (tmpAge > 0) + { + // + result = tmpAge; + item = tmpItem; + } + + // + return result; +} + +// +// Get Youngest Order ... +int GetYoungest( + XOrder &item, // Hold Result ... + XOrder &items[] // Source Array ... +) +{ + // + int result = -1; + + // + int itemsCount = ArraySize(items); + if (itemsCount <= 0) + { + return result; + } + + // + int tmpAge = 0; + XOrder tmpItem; + for (int i = 0; i < itemsCount; i++) + { + // + XOrder iItem = items[i]; + + // + int iAge = GetAge(iItem); + if (iAge > 0 && + (tmpAge == 0 || tmpAge > iAge)) + { + // + tmpAge = iAge; + tmpItem = iItem; + } + } + + // + if (tmpAge > 0) + { + // + result = tmpAge; + item = tmpItem; + } + + // + return result; +} + +// +// Get Oldes Position ... +int GetOldest( + XPosition &item, // Hold Result ... + XPosition &items[] // Source Array ... +) +{ + // + int result = -1; + + // + int itemsCount = ArraySize(items); + if (itemsCount <= 0) + { + return result; + } + + // + int tmpAge = 0; + XPosition tmpItem; + for (int i = 0; i < itemsCount; i++) + { + // + XPosition iItem = items[i]; + + // + int iAge = GetAge(iItem); + if (iAge > 0 && + (tmpAge == 0 || tmpAge < iAge)) + { + // + tmpAge = iAge; + tmpItem = iItem; + } + } + + // + if (tmpAge > 0) + { + // + result = tmpAge; + item = tmpItem; + } + + // + return result; +} + +// +// Get Youngest Position ... +int GetYoungest( + XPosition &item, // Hold Result ... + XPosition &items[] // Source Array ... +) +{ + // + int result = -1; + + // + int itemsCount = ArraySize(items); + if (itemsCount <= 0) + { + return result; + } + + // + int tmpAge = 0; + XPosition tmpItem; + for (int i = 0; i < itemsCount; i++) + { + // + XPosition iItem = items[i]; + + // + int iAge = GetAge(iItem); + if (iAge > 0 && + (tmpAge == 0 || tmpAge > iAge)) + { + // + tmpAge = iAge; + tmpItem = iItem; + } + } + + // + if (tmpAge > 0) + { + // + result = tmpAge; + item = tmpItem; + } + + // + return result; +} + +// +int FindMaxProfitIndex( + XPosition &positions[] // Position Collection +) +{ + // + int result = -1; + + // + int positionsCount = ArraySize(positions); + if (!IsValidSize(positionsCount)) + { + return result; + } + + // + double max = 0; + for (int i = 0; i < positionsCount; i++) + { + // + XPosition iPosition = positions[i]; + if (iPosition.profit <= 0) + { + continue; + } + + // + if (max == 0 || + max < iPosition.profit) + { + // + result = i; + max = iPosition.profit; + } + } + + // + return result; +} + +// +int FindMinProfitIndex( + XPosition &positions[] // Position Collection +) +{ + // + int result = -1; + + // + int positionsCount = ArraySize(positions); + if (!IsValidSize(positionsCount)) + { + return result; + } + + // + double min = 0; + for (int i = 0; i < positionsCount; i++) + { + // + XPosition iPosition = positions[i]; + if (iPosition.profit <= 0) + { + continue; + } + + // + if (min == 0 || + min > iPosition.profit) + { + // + result = i; + min = iPosition.profit; + } + } + + // + return result; +} + +// +int ExtractInProfitPositions( + XPosition &positions[], // Position Collection + XPosition &inProfits[] // Result +) +{ + // + int result = 0; + + // + Clean(inProfits); + + // + int positionsCount = ArraySize(positions); + if (!IsValidSize(positionsCount)) + { + return result; + } + + // + for (int i = 0; i < positionsCount; i++) + { + // + XPosition iPosition = positions[i]; + + // + if (iPosition.profit > 0) + { + // + AddRef( + iPosition, + inProfits // + ); + } + } + + // + result = ArraySize(inProfits); + + // + return result; +} + +// +int FindMaxInDrawdownIndex( + XPosition &positions[] // Position Collection +) +{ + // + int result = -1; + + // + int positionsCount = ArraySize(positions); + if (!IsValidSize(positionsCount)) + { + return result; + } + + // + double max = 0; + for (int i = 0; i < positionsCount; i++) + { + // + XPosition iPosition = positions[i]; + if (iPosition.profit >= 0) + { + continue; + } + + // + if (max == 0 || + MathAbs(max) < MathAbs(iPosition.profit)) + { + // + result = i; + max = iPosition.profit; + } + } + + // + return result; +} + +// +int FindMinInDrawdownIndex( + XPosition &positions[] // Position Collection +) +{ + // + int result = -1; + + // + int positionsCount = ArraySize(positions); + if (!IsValidSize(positionsCount)) + { + return result; + } + + // + double min = 0; + for (int i = 0; i < positionsCount; i++) + { + // + XPosition iPosition = positions[i]; + if (iPosition.profit >= 0) + { + continue; + } + + // + if (min == 0 || + min > iPosition.profit) + { + // + result = i; + min = iPosition.profit; + } + } + + // + return result; +} + +// +int ExtractInDrawdownPositions( + XPosition &positions[], // Position Collection + XPosition &inDradowns[] // Result +) +{ + // + int result = 0; + + // + Clean(inDradowns); + + // + int positionsCount = ArraySize(positions); + if (!IsValidSize(positionsCount)) + { + return result; + } + + // + for (int i = 0; i < positionsCount; i++) + { + // + XPosition iPosition = positions[i]; + + // + if (iPosition.profit < 0) + { + // + AddRef( + iPosition, + inDradowns // + ); + } + } + + // + result = ArraySize(inDradowns); + + // + return result; +} + +// +// Check Filters ... + +// +// Magic Filter ... +template +bool IsMagicFilterPassed( + ulong magic, + bool filterByMagic, + T &item + // +) +{ + // + return !filterByMagic + ? true + : !NotEmpty(magic) + ? false + : magic == item.magic; +} + +// +// Symbol Filter ... +template +bool IsSymbolFilterPassed( + string symbol, + T &item + // +) +{ + // + return !IsValid(symbol) + ? true + : symbol == item.symbol; +} + +// +// Provider Filter ... +template +bool IsProviderFilterPassed( + string provider, + T &item + // +) +{ + // + return !IsValid(provider) + ? true + : provider == item.provider; +} + +// +// Period Filter ... +template +bool IsPeriodFilterPassed( + ENUM_TIMEFRAMES period, + T &item + // +) +{ + // + return !IsValid(period) + ? true + : period == item.period; +} + +// +// Type Filter ... +template +bool IsTypeFilterPassed( + ENUM_POSITION_TYPE type, + T &item + // +) +{ + // + bool result = type == item.type; + + // + return result; +} +template +bool IsTypeFilterPassed( + ENUM_X_POSITION_TYPES type, + T &item + // +) +{ + // + bool result = type == NULL || type == X_POSITION_TYPE_ALL + ? true + : ((type == X_POSITION_TYPE_LONG && ((int)item.type == (int)POSITION_TYPE_BUY || (int)item.type == (int)ORDER_TYPE_BUY)) || + (type == X_POSITION_TYPE_SHORT && ((int)item.type == (int)POSITION_TYPE_SELL || (int)item.type == (int)ORDER_TYPE_SELL))); + + // + return result; +} +template +bool IsTypeFilterPassed( + ENUM_ORDER_TYPE type, + T &item + // +) +{ + // + return type == NULL + ? true + : type == item.type; +} +template +bool IsTypeFilterPassed( + ENUM_DEAL_TYPE type, + T &item + // +) +{ + // + return type == NULL + ? true + : type == item.type; +} + +// +// Mode Filter ... +template +bool IsModeFilterPassed( + ENUM_X_ORDER_MODES mode, + T &item + // +) +{ + // + return mode == NULL + ? true + : mode == item.mode; +} + +// +// Entry Filter ... +template +bool IsEntryFilterPassed( + ENUM_DEAL_ENTRY entry, + T &item + // +) +{ + // + return entry == NULL + ? true + : entry == item.entry; +} + +// +// Reason Filter ... +template +bool IsReasonFilterPassed( + ENUM_DEAL_REASON reason, + T &item + // +) +{ + // + return reason == NULL + ? true + : reason == item.reason; +} + +// +// State Filter ... +template +bool IsStateFilterPassed( + ENUM_ORDER_STATE state, + T &item + // +) +{ + // + return state == NULL + ? true + : state == item.state; +} + +// + + +// +// +// Calculate Positions Profit Summary ... +double SpecifiedCalculatePositionsProfit( + XPosition &positions[] // Source +) +{ + // + double result = 0; + + // + int positionsCount = ArraySize(positions); + if (positionsCount <= 0) + { + return result; + } + + // + for (int i = 0; i < positionsCount; i++) + { + // + XPosition iPosition = positions[i]; + + // + result += iPosition.profit; + } + + // + return result; +} + +// +// Calculate Required Profit for Hedging ... +double SpecifiedCalculateRequiredProfitForHedge( + XPosition &positions[], // Source + double mMinProfitPerTrade, + double mMinProfitPerVolumeFactor // +) +{ + // + double result = 0; + + // + int positionsCount = ArraySize(positions); + if (positionsCount <= 0) + { + return result; + } + + // + bool isHedgingEnable = mMinProfitPerTrade > 0 && mMinProfitPerVolumeFactor > 0; + if (!isHedgingEnable) + { + return result; + } + + // + for (int i = 0; i < positionsCount; i++) + { + // + XPosition iPosition = positions[i]; + + // + if (mMinProfitPerTrade > 0 && mMinProfitPerVolumeFactor > 0) + { + // + result += + ((iPosition.volume / mMinProfitPerVolumeFactor) * + mMinProfitPerTrade) + + (-1 * iPosition.swap); + } + } + + // + return result; +} + +// +bool SpecifiedIsPositionsReadyForHedge( + XPosition &positions[], // Source + double mMinProfitPerTrade, + double mMinProfitPerVolumeFactor // +) +{ + // + double profit = SpecifiedCalculatePositionsProfit(positions); + double requiredProfit = SpecifiedCalculateRequiredProfitForHedge( + positions, + mMinProfitPerTrade, + mMinProfitPerVolumeFactor // + ); + + // + bool result = requiredProfit > 0 + ? profit >= requiredProfit + : profit > requiredProfit; + + // + return result; +} + +// +int FindCoverageDrawdownPosition( + XPosition &position, // In Drawdown Position + XPosition &inProfits[], // In Profit Positions + XPosition &coverage[], // Coverage Positons + double mMinProfitPerTrade, + double mMinProfitPerVolumeFactor // +) +{ + // + int result = 0; + + // + Clean(coverage); + + // + if (!position.IsValid() || position.profit >= 0) + { + return result; + } + + // + int inProfitsCount = ArraySize(inProfits); + if (!IsValidSize(inProfitsCount)) + { + return result; + } + + // + // Copy in Profits to TMP ... + XPosition tmp[]; + Copy( + inProfits, + tmp // + ); + + // + bool isCoverPassed = false; + while (!isCoverPassed || ArraySize(tmp) > 0) + { + // + XPosition max; + int idx = FindMaxProfitIndex(tmp); + if (idx >= 0) + { + // + if (tmp[idx].profit > 0) + { + AddRef( + tmp[idx], + coverage // + ); + + // + ArrayRemove( + tmp, + idx, + 1 // + ); + } + } + + // + // Check Cover Passed ... + XPosition tmpPositions[]; + Copy( + coverage, + tmpPositions // + ); + AddRef( + position, + tmpPositions // + ); + + // + double profits = SpecifiedCalculatePositionsProfit(tmpPositions); + double requiredProfit = SpecifiedCalculateRequiredProfitForHedge( + tmpPositions, + mMinProfitPerTrade, + mMinProfitPerVolumeFactor // + ); + isCoverPassed = profits >= requiredProfit; + if (isCoverPassed) + { + break; + } + + // + if (!isCoverPassed && ArraySize(tmp) == 0) + { + break; + } + } + + // + result = ArraySize(coverage); + + // + return result; +} + +// +// Extract a Collection of Positions SL ... +int ExtractSLs( + XPosition &positions[], + double &sls[] // +) +{ + // + int result = 0; + + // + Clean(sls); + + // + int positionsCount = ArraySize(positions); + if (!IsValidSize(positionsCount)) + { + return result; + } + + // + for (int i = 0; i < positionsCount; i++) + { + // + XPosition iPosition = positions[i]; + + // + if (iPosition.sl > 0) + { + // + Add( + iPosition.sl, + sls // + ); + } + } + + // + result = ArraySize(sls); + + // + return result; +} + +// +// Extract a Colletion of Positions TP ... +int ExtractTPs( + XPosition &positions[], + double &tps[] // +) +{ + // + int result = 0; + + // + Clean(tps); + + // + int positionsCount = ArraySize(positions); + if (!IsValidSize(positionsCount)) + { + return result; + } + + // + for (int i = 0; i < positionsCount; i++) + { + // + XPosition iPosition = positions[i]; + + // + if (iPosition.tp > 0) + { + // + Add( + iPosition.tp, + tps // + ); + } + } + + // + result = ArraySize(tps); + + // + return result; +} + +// +// Retrieve String Representation ... +string ToString(ENUM_X_SIGNAL_EXECUTION_RESULT value) +{ + // + string result = NULL; + + // + switch (value) + { + // + case X_SIGNAL_EXECUTION_UNKNOWN: + result = "Unknown"; + break; + + // + case X_SIGNAL_EXECUTION_SUCCEED: + result = "Succed"; + break; + + // + case X_SIGNAL_EXECUTION_FAILED_SPREAD: + result = "Spread more than Max Allowed"; + break; + + // + case X_SIGNAL_EXECUTION_FAILED_NOT_ALLOWED: + result = "not Allowed"; + break; + + // + case X_SIGNAL_EXECUTION_FAILED_NO_EQUITY: + result = "No Equity for Trade"; + break; + + // + case X_SIGNAL_EXECUTION_FAILED_PRICE_ERROR: + result = "Price Error"; + break; + + // + case X_SIGNAL_EXECUTION_FAILED_PREV_PROFIT_ERROR: + result = "Previous Position Profit not Passed for Accept Next"; + break; + + // + case X_SIGNAL_EXECUTION_FAILED_MAX_REACHED: + result = "Max Allowed Positions Reached"; + break; + + // + case X_SIGNAL_EXECUTION_FAILED_DELAY_NOT_PASSED: + result = "Min Delay Between to Signal not Passed"; + break; + + // + case X_SIGNAL_EXECUTION_FAILED_INVALID_PARAMS: + result = "Invalid Params"; + break; + } + + // + return result; +} + +// +// Converts Position Type to Order Type ... +ENUM_ORDER_TYPE ToOrderType(ENUM_POSITION_TYPE value) +{ + // + bool isLong = IsLong(value); + + // + ENUM_ORDER_TYPE result = + isLong + ? ORDER_TYPE_BUY + : ORDER_TYPE_SELL; + + // + return result; +} +ENUM_ORDER_TYPE ToOrderType(ENUM_X_POSITION_TYPES value) +{ + // + ENUM_POSITION_TYPE mType = + value == X_POSITION_TYPE_SHORT + ? POSITION_TYPE_SELL + : POSITION_TYPE_BUY; + + // + bool isLong = IsLong(mType); + + // + ENUM_ORDER_TYPE result = + isLong + ? ORDER_TYPE_BUY + : ORDER_TYPE_SELL; + + // + return result; +} + +// +// Tagging ... + +// +// Generate Specified Tag for Using in Comments ... +string GeneratePeriodTag(ENUM_TIMEFRAMES period) +{ + // + string strPeriod = ToString(period); + return Surround( + XPeriodToken, + strPeriod + // + ); +} + +// +// Extract Period from a Tagged string ... +ENUM_TIMEFRAMES ExtractPeriod(string value) +{ + // + ENUM_TIMEFRAMES result = NULL; + + // + string pStr = ParseStringSurrounded( + value, + XPeriodToken + // + ); + if (!IsValid(pStr)) + { + return result; + } + + // + result = ToPeriod(pStr); + + // + return result; +} + +// Generate Specified Tag for Using in Comments ... +string GenerateProviderTag(string provider) +{ + // + return Surround( + XProviderToken, + provider + // + ); +} + +// +// Extract Provider from a Tagged string ... +string ExtractProvider(string value) +{ + // + return ParseStringSurrounded( + value, + XProviderToken + // + ); +} + +// +// Generate Support Comment Tag ... +string GenerateSupportTag(ulong ticket) +{ + // + return Surround( + XSupportToken, + ticket + // + ); +} + +// +// Extract Support Positions from a Tagged string ... +ulong ExtractSupportedTicket(string value) +{ + // + return ParseLongSurrounded( + value, + XSupportToken + // + ); +} + +// +// Extract Support ... +template +int ExtractSupports( + T &source[], + T &dest[] // Result ... +) +{ + // + int result = 0; + + // + Clean(dest); + + // + int sourceCount = ArraySize(source); + if (!IsValidSize(sourceCount)) + { + return result; + } + + // + for (int i = 0; i < sourceCount; i++) + { + // + T iSource = source[i]; + + // + ulong isSupport = ExtractSupportedTicket(iSource.comment) > 0; + ulong iEQMSupport = ExtractEQMSupportedTicket(iSource.comment) > 0; + if (isSupport || iEQMSupport) + { + // + AddRef( + iSource, + dest // + ); + } + } + + // + result = ArraySize(dest); + + // + return result; +} + +// +// Generate EQM Support Comment Tag ... +string GenerateEQMSupportTag(ulong ticket) +{ + // + return Surround( + XEQMSupportToken, + ticket + // + ); +} + +// +// Extract EQM Support Positions from a Tagged string ... +ulong ExtractEQMSupportedTicket(string value) +{ + // + return ParseLongSurrounded( + value, + XEQMSupportToken + // + ); +} + +// +bool IsSupport(string value) +{ + // + bool result = false; + + // + bool isSupport = ExtractSupportedTicket(value) > 0; + bool isEQMSupport = ExtractEQMSupportedTicket(value) > 0; + + // + result = + // + isSupport + // + || + // + isEQMSupport + // + ; + + // + return result; +} + +// +ulong ExtractParentTicket(string value) +{ + // + ulong result = 0; + + // + if (!IsSupport(value)) + { + return result; + } + + // + result = ExtractSupportedTicket(value); + if (result > 0) + { + return result; + } + + // + result = ExtractEQMSupportedTicket(value); + + // + return result; +} + +// +// XRecovery ... + +// +string GenerateRecoveryTag(ulong ticket) +{ + // + return Surround( + XRecoveryToken, + ticket // + ); +} + +// +ulong ExtractRecoveredTicket(string value) +{ + // + return ParseLongSurrounded( + value, + XRecoveryToken // + ); +} + +// +// Extract Recoveries ... +template +int ExtractRecoveries( + T &source[], + T &dest[] // Result ... +) +{ + // + int result = 0; + + // + Clean(dest); + + // + int sourceCount = ArraySize(source); + if (!IsValidSize(sourceCount)) + { + return result; + } + + // + for (int i = 0; i < sourceCount; i++) + { + // + T iSource = source[i]; + + // + ulong isRecovery = ExtractRecoveredTicket(iSource.comment) > 0; + if (isRecovery) + { + // + AddRef( + iSource, + dest // + ); + } + } + + // + result = ArraySize(dest); + + // + return result; +} + +// +// Extract Specified Position's Recoveries ... +int ExtractRecoveries( + ulong ticket, + XPosition &source[], + XPosition &dest[] // Result ... +) +{ + // + int result = 0; + + // + Clean(dest); + + // + int sourceCount = ArraySize(source); + if (!IsValidSize(sourceCount)) + { + return result; + } + + // + for (int i = 0; i < sourceCount; i++) + { + // + XPosition iSource = source[i]; + + // + ulong parentTicket = ExtractRecoveredTicket(iSource.comment); + bool isRecovery = parentTicket > 0; + if (isRecovery && parentTicket == ticket) + { + // + AddRef( + iSource, + dest // + ); + } + } + + // + result = ArraySize(dest); + + // + return result; +} + +// +// SL Trails ... + +// +// Extract SL Trail Level ... +int ExtractSLTrailLevel(string comment) +{ + // + int result = 0; + + // + if (!IsValid(comment)) + { + return result; + } + + // + result = ParseIntSurrounded( + comment, + XSLTrailToken + // + ); + + // + return result; +} + +// +// Generate SL Trail Comment Tag ... +string GenerateSLTrailTag(int level) +{ + // + string result = NULL; + + // + if (level <= 0) + { + return result; + } + + // + result = Surround( + XSLTrailToken, + level + // + ); + + // + return result; +} + +// +// Prepare SL Trail Comment ... +string PrepareSLTrailTag( + const string comment // Original Position Comment ... +) +{ + // + string result = NULL; + + // + int level = 0; + result = comment; + + // + // Check Comment Contains SL Trailing or not ... + int lastTrailLevel = ExtractSLTrailLevel(comment); + if (lastTrailLevel <= 0) + { + level++; + } + else + { + // + level = lastTrailLevel + 1; + string lastLevelStr = GenerateSLTrailTag(lastTrailLevel); + StringReplace( + result, + lastLevelStr, + "" + // + ); + } + + // + // Generate level Comment ... + string levelStr = GenerateSLTrailTag(level); + result += levelStr; + + // + return result; +} + +// +// Count Positions from a Collection ... +void CountPositions( + const XPosition &positions[], + int &longs, + double &longProfits, + double &longVolumes, // + // + int &shorts, + double &shortProfits, + double &shortVolumes // +) +{ + // + longs = 0; + longProfits = 0; + longVolumes = 0; + + // + shorts = 0; + shortProfits = 0; + shortVolumes = 0; + + // + int positionsCount = ArraySize(positions); + if (!IsValidSize(positionsCount)) + { + return; + } + + // + for (int i = 0; i < positionsCount; i++) + { + // + XPosition iPosition = positions[i]; + + // + bool isLong = IsLong(iPosition.type); + if (isLong) + { + // + longs++; + longProfits += iPosition.profit; + longVolumes += iPosition.volume; + } + else + { + // + shorts++; + shortProfits += iPosition.profit; + shortVolumes += iPosition.volume; + } + } +} + +// +// Extract Positions based On Type ... +void ExtractPositions( + XPosition &positions[], + XPosition &longs[], + XPosition &shorts[] // +) +{ + // + int count = ArraySize(positions); + if (!IsValidSize(count)) + { + return; + } + + // + Clean(longs); + Clean(shorts); + + // + for (int i = 0; i < count; i++) + { + // + XPosition iPosition = positions[i]; + + // + bool isLong = IsLong(iPosition.type); + if (isLong) + { + AddRef( + iPosition, + longs // + ); + } + else + { + AddRef( + iPosition, + shorts // + ); + } + } +} + +// +int FindSymbolIndex( + string mSymbol, + XSymbolPositions &mItems[] // +) +{ + // + int result = -1; + + // + if (!IsValid(mSymbol)) + { + return result; + } + + // + int count = ArraySize(mItems); + if (!IsValidSize(count)) + { + return result; + } + + // + for (int i = 0; i < count; i++) + { + // + XSymbolPositions iItem = mItems[i]; + + // + if (iItem.symbol == mSymbol) + { + // + result = i; + break; + } + } + + // + return result; +} + +// +int ExtractSymbolPositions( + XPosition &positions[], + XSymbolPositions &items[], // Holds Result + double mMinProfitPerTrade, + double mMinProfitPerVolumeFactor // +) +{ + // + int result = 0; + + // + int positionsCount = ArraySize(positions); + if (!IsValidSize(positionsCount)) + { + return result; + } + + // + Clean(items); + + // + for (int i = 0; i < positionsCount; i++) + { + // + XPosition iPosition = positions[i]; + + // + if (!iPosition.IsValid()) + { + continue; + } + + // + int itemIDX = FindSymbolIndex( + iPosition.symbol, + items // + ); + if (!IsValidIndex(itemIDX)) + { + // + // Add New One ... + XSymbolPositions item; + item.symbol = iPosition.symbol; + + // + AddRef( + item, + items // + ); + itemIDX = FindSymbolIndex(iPosition.symbol, items); + } + + // + AddRef( + iPosition, + items[itemIDX].positions // + ); + } + + // + result = ArraySize(items); + if (IsValidSize(result)) + { + // + for (int i = 0; i < result; i++) + { + // + items[i].Update( + mMinProfitPerTrade, + mMinProfitPerVolumeFactor // + ); + } + } + + // + return result; +} + +// \ No newline at end of file diff --git a/BKPS/14040203/X121SMCEA/Classes/x-121.smc.base.strategy.class.mq5 b/BKPS/14040203/X121SMCEA/Classes/x-121.smc.base.strategy.class.mq5 new file mode 100644 index 0000000..302d397 --- /dev/null +++ b/BKPS/14040203/X121SMCEA/Classes/x-121.smc.base.strategy.class.mq5 @@ -0,0 +1,627 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Class Library +// -------------------------------------- +// Name: XSCX121SMCBaseStrategy +// Description: provides all based classes for use ... +// +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +////////////////////////////////////////////////////// +// +// Global Properties ... +#property library +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://www.saherelm.ir" +#property version "1.00" +#property strict + +// +// Imports ... + +// +#include "../../Classes/x-saherelm.x-alert.class.mq5" +#include "../../Classes/x-saherelm.x-bar.analyser.class.mq5" +#include "../../Classes/x-saherelm.x-poi.class.mq5" +#include "../../Classes/x-saherelm.x-trade.class.mq5" +#include "../Classes/x-121.smc.cobjects.class.mq5" +#include "../Libraries/x-121.smc.lib.mq5" + +// +// Helper(s) ... + +// +// XStrategy Class Implementation(s) ... +class XCX121SMCBaseStrategy : public XCBaseAlert +{ + // + // Public ... + public: + // + XCAccount mAccount; + + // + // Constructor(s) ... + XCX121SMCBaseStrategy( + // + // Base ... + string _symbol, // Trading Symbol + ENUM_TIMEFRAMES _period // Trading TimeFrame + ) + { + // + mSymbol = _symbol; + mPeriod = _period; + + // + Init(); + } + + // + // Deconstructor ... + ~XCX121SMCBaseStrategy() + { + DeInit(); + } + + // + // Getter / Setter (s) ... + + /** + * Retrieve Symbol ... + * + * @return ( string ) + */ + string GetSymbol() + { + return mSymbol; + } + + /** + * Retrieve TimeFrame ... + * + * @return ( ENUM_TIMEFRAMES ) + */ + ENUM_TIMEFRAMES GetPeriod() + { + return mPeriod; + } + + /** + * Check Strategy is Disabled or not ... + * + * @return ( bool ) + */ + bool IsDisabled() + { + return mForceDisabled; + } + + /** + * Get Signal Volume ... + * + * @return ( double ) + */ + double Volume() + { + return mVolume; + } + + /** + * Set Signal Volume ... + * + * @param value: Double ... + */ + void Volume(double value) + { + // + if (value < 0.01) + { + value = 0.01; + } + + // + mVolume = value; + } + + /** + * Get Risk/Reward Ratio ... + * + * @return ( double ) + */ + double R2R() + { + return mR2R; + } + + /** + * Set Risk/Reward Ratio ... + * + * @param value: Double ... + */ + void R2R(double value) + { + // + if (value < 0) + { + value = 1.5; + } + + // + mR2R = value; + } + + /** + * Get Long Signalling State ... + * + * @return ( bool ) + */ + bool AllowLong() + { + return mAllowLong; + } + + /** + * Set Long Signalling State ... + * + * @param value: Boolean ... + */ + void AllowLong(bool value) + { + mAllowLong = value; + } + + /** + * Get Short Signalling State ... + * + * @return ( bool ) + */ + bool AllowShort() + { + return mAllowShort; + } + + /** + * Set Short Signalling State ... + * + * @param value: Argument 1 + */ + void AllowShort(bool value) + { + mAllowShort = value; + } + + // + // Actions ... + + /** + * Disable Strategy ... + */ + void Disable() + { + mForceDisabled = true; + } + + /** + * Enable Strategy ... + */ + void Enable() + { + mForceDisabled = false; + } + + /** + * Register Signal Event Handler ... + * + * @param handler: an Instance of TOnXSignal ... + */ + void AddXSignalEventHandler(TOnX121SMCSignal handler) + { + // + Add( + handler, + mSignalEventHandlers // + ); + } + + // + // Virtual Actions ... + + /** + * Destroy All Class Implementations ... + */ + virtual void Destroy() + { + } + + /** + * Handle Tick Processing ... + * + * @param positions: XPosition instance Collection ... + */ + virtual void HandleTick() + { + // + DoUnwaitedTicksWork(); + + // + // Check State ... + if (IsDisabled()) + { + return; + } + + // + // Check Signalling State ... + if (!AllowLong() && !AllowShort()) + { + return; + } + + // + // Check Bar Tracker State ... + if (!mBarTracker.CanProcessBar()) + { + return; + } + + // + // Retrieve Current Tick and Check it's Time + // by Last Issued Tick ... + MqlTick cTick; + bool hasTick = GetTick( + mSymbol, + cTick // + ); + bool isSameAsLast = cTick.time == mLastTick.time; + if (isSameAsLast) + { + return; + } + + // + // Update Last Issued Tick ... + mLastTick = cTick; + + // + // Check Current Processing Tick has Signal or not ... + XSignal signal; + X121SMCStrategyConditions conditions; + bool hasSignal = HasSignal( + signal, + conditions // + ); + if (!hasSignal) + { + return; + } + + // + // Waits Until Next Candle if Current Tick has Signal ... + mBarTracker.Waits(); + + // + // Notify Signal Event Handlers ... + NotifyOnSignalEventHandlers( + signal, + conditions // + ); + } + + /** + * Check for any Guards ... + * + * @param guards: X121SMCGuard instance Collection ... + * @param positions: XPosition instance Collection ... + * + * @return ( virtual bool ) + */ + virtual bool HandleGuard( + X121SMCGuard &guards[], + XPosition &positions[] // + ) + { + // + bool result = false; + + // + // Check State ... + if (IsDisabled()) + { + return result; + } + + // + // Check Signalling State ... + if (!AllowLong() && !AllowShort()) + { + return result; + } + + // + // Check Bar Tracker State ... + if (!mGuardBarTracker.CanProcessBar()) + { + return result; + } + + // + // Check For Guards ... + result = CheckGuard( + guards, + positions // + ); + + // + // Waits Until Next Candle if Current Tick has Guard ... + mGuardBarTracker.Waits(); + + // + Clean(positions); + + // + return result; + } + + /** + * Check For Signal ... + * + * @param signal: XSignal instance ... + * @param conditions: X121SMCStrategyConditions instance ... + * + * @return ( virtual bool ) + */ + virtual bool HasSignal( + XSignal &signal, + X121SMCStrategyConditions &conditions // + ) + { + // + bool result = false; + + // + signal.Clean(); + conditions.Clean(); + + // + return result; + } + + /** + * Check for any Guard Actions ... + * + * @param guards: X121SMCGuard instance Collection ... + * + * @return ( virtual bool ) + */ + virtual bool CheckGuard( + X121SMCGuard &guards[], + const XPosition &positions[] // Positions ... + ) + { + // + bool result = false; + + // + return result; + } + + /** + * Update all Requirements without waiting ... + */ + virtual void DoUnwaitedTicksWork() + { + } + + /** + * Detect SL Candidates based on Strategy and Conditions ... + * + * @param result: Double array reference ... + * @param entry: Double, Position Entry Price ... + * @param conditions: X121SMCStrategyConditions instance, Provides Configurations ... + * @param type: ENUM_X_POSITION_TYPES member, Specified Position Type ... + */ + virtual void DetectSLCandidates( + double &result[], + double entry, + X121SMCStrategyConditions &conditions, + ENUM_X_POSITION_TYPES type // + ) + { + } + + /** + * Customize Strategy Identifier ... + * + * @return ( virtual string ) + */ + virtual string GetTag() + { + return X121SMCStrategyToken; + } + + // + // Protected ... + protected: + // + + // + // Props ... + + // + MqlTick mLastTick; // Last Issued Tick ... + + // + XBarTracker mBarTracker; // Strategy Bar Tracker ... + XBarTracker mGuardBarTracker; // Strategy Guard Bar Tracker ... + XCBarAnalyser *mBarAnalyser; // Bar Analyser Instance + + // + // Actions ... + + /** + * Prepare and Normalize Signal for Execution in Strategy ... + * + * @param signal: XSignal instance ... + * + * @return ( bool ) + */ + bool PrepareSignal(XSignal &signal) + { + // + bool result = false; + + // + // Check Strategy Is Enables ... + result = !IsDisabled(); + if (!result) + { + return result; + } + + // + // Validate Signal ... + result = signal.IsValid(); + if (!result) + { + return result; + } + + // + bool isLong = IsLong(signal.type); + + // + // TODO: Implement Signal Preparation Mechanism here ... + + // + return result; + } + + // + + /** + * Notified Signal Event Handler(s) ... + * + * @param signal: XSignal instance ... + * @param conditions: XStrategyConditions instance ... + */ + void NotifyOnSignalEventHandlers( + XSignal &signal, + X121SMCStrategyConditions &conditions // + ) + { + // + if (!signal.IsValid() || !conditions.IsValid()) + { + return; + } + + // + int count = ArraySize(mSignalEventHandlers); + if (!IsValidSize(count)) + { + return; + } + + // + for (int i = 0; i < count; i++) + { + // + mSignalEventHandlers[i]( + signal, + conditions // + ); + } + } + + // + // Private ... + private: + // + // Props ... + + // + string mSymbol; // Trading Symbol ... + ENUM_TIMEFRAMES mPeriod; // Trading TimeFrame ... + bool mForceDisabled; // Force Disabled ... + bool mAllowLong; // Allow Long Signals + bool mAllowShort; // Allow Short Signals + double mR2R; // Risk/Rewar Ratio ... + double mVolume; // Static Volume Per Trades ... + + // + // On X121 Signal Recieved Event Handler(s) ... + TOnX121SMCSignal mSignalEventHandlers[]; + + // + // Actions ... + + /** + * Install all Helpers and Prepare all Configurations for required Indicators ... + */ + void Init() + { + // + mForceDisabled = false; + + // + R2R(1); + Volume(0.01); + + // + string symbol = Symbol(); + ENUM_TIMEFRAMES period = Period(); + + // + // Initialize Bar Tracker ... + mBarTracker.Init( + symbol, + period // + ); + + // + // Initialize Guard Bar Tracker ... + mGuardBarTracker.Init( + symbol, + period // + ); + + // + mBarAnalyser = new XCBarAnalyser(); + + // + } + + /** + * De Initialize all Tools ... + */ + void DeInit() + { + // + ZeroMemory(mBarAnalyser); + + // + delete mBarAnalyser; + + // + Clean(mSignalEventHandlers); + + // + Destroy(); + } + + /** + * Reste Bar Tracker ... + */ + void ResetBarTracker() + { + mBarTracker.Clean(); + } + + // +}; + +// \ No newline at end of file diff --git a/BKPS/14040203/X121SMCEA/Classes/x-121.smc.cobjects.class.mq5 b/BKPS/14040203/X121SMCEA/Classes/x-121.smc.cobjects.class.mq5 new file mode 100644 index 0000000..3f37d87 --- /dev/null +++ b/BKPS/14040203/X121SMCEA/Classes/x-121.smc.cobjects.class.mq5 @@ -0,0 +1,35 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Class Library +// -------------------------------------- +// Name: XChartObjects +// Description: provides all require Chart Objects ... +// +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +////////////////////////////////////////////////////// +// +// Global Properties ... +#property library +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://www.saherelm.ir" +#property version "1.00" +#property strict + +// +#include "../../Classes/x-saherelm.x-cobject.class.mq5" +#include "../Libraries/x-121.smc.lib.mq5" + +// +// Definitions ... + +enum ENUM_X121SMC_CHARTOBJECTS +{ + X_121_NONE_OBJ +}; + +// +// Implementations ... diff --git a/BKPS/14040203/X121SMCEA/Classes/x-121.smc.ea.panel.class.mq5 b/BKPS/14040203/X121SMCEA/Classes/x-121.smc.ea.panel.class.mq5 new file mode 100644 index 0000000..47d16e0 --- /dev/null +++ b/BKPS/14040203/X121SMCEA/Classes/x-121.smc.ea.panel.class.mq5 @@ -0,0 +1,63 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Class Library +// -------------------------------------- +// Name: XC121Panel +// Description: provides all based classes for use ... +// +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +////////////////////////////////////////////////////// +// +// Global Properties ... +#property library +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://www.saherelm.ir" +#property version "1.00" +#property strict + +// +// Imports ... +#include "../../Classes/x-saherelm.x-app-dialog.class.mq5" + +// +// Implementation ... + +// +class X121CAppDialog : public XCAppDialog +{ + // + public: + // + // Constructor(s) ... + void X121CAppDialog() + { + } + + // + // Deconstructor ... + void ~X121CAppDialog() + { + } + + // + void Configure() + { + // + // Configure Dialog ... + BackgroundColor(clrBlack); + } + + // + protected: + // + + // + private: + // +}; + +// \ No newline at end of file diff --git a/BKPS/14040203/X121SMCEA/Classes/x-121.smc.market.cycle.helper.class.mq5 b/BKPS/14040203/X121SMCEA/Classes/x-121.smc.market.cycle.helper.class.mq5 new file mode 100644 index 0000000..0abcd78 --- /dev/null +++ b/BKPS/14040203/X121SMCEA/Classes/x-121.smc.market.cycle.helper.class.mq5 @@ -0,0 +1,2009 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Class Library +// -------------------------------------- +// Name: XC121SMCCycleHelper +// Description: provides all based classes for use ... +// +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +////////////////////////////////////////////////////// +// +// Global Properties ... +#property library +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://www.saherelm.ir" +#property version "1.00" +#property strict + +// +// Imports ... +#include "../../Classes/x-saherelm.x-bar.analyser.class.mq5" +#include "../../Classes/x-saherelm.x-poi.class.mq5" +#include "../Libraries/x-121.smc.lib.mq5" + +// +// Definitions ... + +// +// Implementations ... + +// +// Cycles Enumeration ... +enum ENUM_X_CYCLES +{ + X_CYCLE_NONE, + X_CYCLE_TRIGGER, + X_CYCLE_DECISION, + X_CYCLE_ANALYSE, + X_CYCLE_VERIFICATION, + X_CYCLE_CONSOLIDATION, + X_CYCLE_VISION, +}; + +// +// String Representation of Cycles Enumeration ... +string ToString(ENUM_X_CYCLES value) +{ + // + string result = EnumToString(value); + + // + StringReplace(result, "X_CYCLE_", ""); + + // + return result; +} + +// +// Validate a Cycle ... +bool IsValid(ENUM_X_CYCLES value) +{ + // + bool result = false; + + // + result = + value != X_CYCLE_NONE; + + // + return result; +} + +// +// Cycle Events Enumeration ... +enum ENUM_X_CYCLE_EVENTS +{ + SAR_CHANGE_DETECTED, + NEW_PEAK_DETECTED, + NEW_VALE_DETECTED, + PIVOT_POINT_DETECTED, + VWAP_ORDER_CHANGE_ETECTED, + VWAP_STATE_CHANGE_DETCTED, + CONSOLIDATION_BREAKED_DETECTED, + PEAK_PIVOT_STARTED, + PEAK_PIVOT_ENDED, + VALE_PIVOT_STARTED, + VALE_PIVOT_ENDED, +}; + +// +// XPV Pivot ... + +// +enum ENUM_X_PV_PIVOT +{ + X_PV_NONE, // None + X_PV_PEAK, // Peak + X_PV_VALE, // Vale +}; + +// +bool IsValid(ENUM_X_PV_PIVOT value) +{ + // + bool result = false; + + // + result = value != X_PV_NONE; + + // + return result; +} + +// +string ToString(ENUM_X_PV_PIVOT value) +{ + // + string result = NULL; + + // + result = EnumToString(value); + + // + return result; +} + +// +struct XPVPivot +{ + // + // Props ... + datetime to; + double value; + double golden; + datetime from; + string symbol; + ENUM_X_PV_PIVOT type; + ENUM_TIMEFRAMES period; + + // + // Constructor ... + XPVPivot() + { + Clean(); + } + + // + // Tools ... + + /** + * Cleanup Model ... + */ + void Clean() + { + // + to = NULL; + value = 0; + from = NULL; + symbol = NULL; + period = NULL; + type = X_PV_NONE; + } + + /** + * Validate Model ... + * + * @return ( bool ) + */ + bool IsValid() + { + // + bool result = false; + + // + result = + // + from < to && + value > 0 && + IsValid(to) && + IsValid(type) && + IsValid(from) && + IsValid(symbol) && + IsValid(period) + // + ; + + // + return result; + } + + /** + * Retrieve Model Direction ... + * + * @return ( ENUM_X_DIRECTION ) + */ + ENUM_X_DIRECTION GetDirection() + { + // + ENUM_X_DIRECTION result = X_DIRECTION_NONE; + + // + if (!IsValid()) + { + return result; + } + + // + switch (type) + { + // + case X_PV_PEAK: + result = X_DIRECTION_BEARISH; + break; + + // + case X_PV_VALE: + result = X_DIRECTION_BULLISH; + break; + } + + // + return result; + } + + /** + * Check Direction is Bullish ... + * + * @return ( bool ) + */ + bool IsBullish() + { + // + bool result = false; + + // + result = IsValid(); + if (!result) + { + return result; + } + + // + ENUM_X_DIRECTION dir = GetDirection(); + result = IsBullish(dir); + + // + return result; + } + + /** + * Check Direction is Bearish ... + * + * @return ( bool ) + */ + bool IsBearish() + { + // + bool result = false; + + // + result = IsValid(); + if (!result) + { + return result; + } + + // + ENUM_X_DIRECTION dir = GetDirection(); + result = IsBearish(dir); + + // + return result; + } + + /** + * To Bar Index ... + * + * @return ( int ) + */ + int ToIndex( + ENUM_TIMEFRAMES forPeriod = NULL // + ) + { + // + int result = -1; + + // + if (!IsValid()) + { + return result; + } + + // + if (!IsValid(forPeriod)) + { + forPeriod = period; + } + + // + result = GetBarIndex( + symbol, + forPeriod, + to // + ); + + // + return result; + } + + /** + * From Bar Index ... + * + * @return ( int ) + */ + int FromIndex( + ENUM_TIMEFRAMES forPeriod = NULL // + ) + { + // + int result = -1; + + // + if (!IsValid()) + { + return result; + } + + // + if (!IsValid(forPeriod)) + { + forPeriod = period; + } + + // + result = GetBarIndex( + symbol, + forPeriod, + from // + ); + + // + return result; + } + + /** + * Check two Pivot is Same or Not ... + * + * @param item: XPVPivot instance Reference ... + * + * @return ( bool ) + */ + bool IsSameAs(XPVPivot &item) + { + // + bool result = false; + + // + result = IsValid() && + item.IsValid(); + if (!result) + { + return result; + } + + // + result = + // + to == item.to && + from == item.from && + type == item.type && + value == item.value && + golden == item.golden && + symbol == item.symbol && + period == item.period + // + ; + + // + return result; + } + + /** + * Conerts to XBoxZone ... + * + * @param box: XBoxZone instance Reference ... + * + * @return ( bool ) + */ + bool AsBox(XBoxZone &box) + { + // + bool result = false; + + // + box.Clean(); + + // + result = IsValid(); + if (!result) + { + return result; + } + + // + box.to = to; + box.from = from; + box.symbol = symbol; + box.period = period; + box.dir = GetDirection(); + box.type = ToString(type); + + // + if (IsBullish()) + { + // + box.lower = value; + box.upper = golden; + } + else if (IsBearish()) + { + // + box.upper = value; + box.lower = golden; + } + + // + result = box.IsValid(); + if (!result) + { + box.Clean(); + } + + // + return result; + } + + // +}; + +// +// Cycle Helper ... +class XC121SMCCycleHelper : public XCBase +{ + // + public: + // + // Props ... + + // + // X121 ... + XCX121Helper *mX121Helper; + + // + // POI Detector ... + XCPOIDrawer *mPOIDrawer; + XCPOIDetector *mPOIDetector; + + // + // Bar Analyser + XCBarAnalyser *mBarAnalyser; + + // + // Constructor(s) ... + XC121SMCCycleHelper() + { + Default(); + } + + // + // Deconstructor ... + ~XC121SMCCycleHelper() + { + DeInit(); + } + + // + // Getter/Setter(s) ... + + // + // Actions ... + + /** + * Initialize ... + * + * @param symbol: String ... + * @param period: ENUM_TIMEFRAMES member ... + * @param x121Inputs: X121Inputs instance ... + * + * @return ( bool ) + */ + bool Init( + string symbol, + ENUM_TIMEFRAMES period, + X121Inputs &x121Inputs, + int requiredPOIs = 50 // + ) + { + // + bool result = false; + + // + if (requiredPOIs < 0) + { + requiredPOIs = 0; + } + + // + result = IsValid(symbol) && + IsValid(period); + if (!result) + { + return result; + } + + // + mSymbol = symbol; + mPeriod = period; + + // + // X121 ... + mX121Helper = new XCX121Helper(); + result = mX121Helper.Init( + symbol, + period, + x121Inputs // + ); + if (!result) + { + return result; + } + + // + mPOIDetector = new XCPOIDetector( + symbol, + period // + ); + mPOIDetector.MaxRequiredPOIs(requiredPOIs); + + // + int maxLoopbackBars = mPOIDetector.MaxAllowedLoopbackForInit(); + int periodSeconds = PeriodSeconds(period); + if (periodSeconds > PeriodSeconds(PERIOD_M15)) + { + // + int multiplier = periodSeconds / PeriodSeconds(PERIOD_M15); + + // + if (multiplier >= 1) + { + maxLoopbackBars *= 2; + } + } + mPOIDetector.MaxAllowedLoopbackForInit(maxLoopbackBars); + mPOIDetector.Init(); + + // + // Initialize Bar Analyser Class Instance ... + mBarAnalyser = new XCBarAnalyser(); + + // + // Initial and Configure POI Drawer if Required ... + mPOIDrawer = new XCPOIDrawer(); + mPOIDrawer.ChartIdentification(0); + mPOIDrawer.SubWindowIdentification(0); + + // + mPOIDrawer.DemandZoneFill(false); + mPOIDrawer.SupplyZoneFill(false); + mPOIDrawer.BullishFVGFill(false); + mPOIDrawer.BearishFVGFill(false); + mPOIDrawer.SupportZoneFill(false); + mPOIDrawer.ResistanceZoneFill(false); + mPOIDrawer.BullishOrderBlockFill(false); + mPOIDrawer.BearishOrderBlockFill(false); + + // + // Set Chart Style ... + ApplyChartStyle(); + + // + return result; + } + + /** + * Retrieve Symbol ... + * + * @return ( string ) + */ + string GetSymbol() + { + return mSymbol; + } + + /** + * Retrieve TimeFrame (Period) ... + * + * @return ( ENUM_TIMEFRAMES ) + */ + ENUM_TIMEFRAMES GetPeriod() + { + return mPeriod; + } + + /** + * Get Specified Bar ... + * + * @param source: XOHCL instance, Source Bar ... + * @param bar: XOHCL instance, Dest Bar ... + * + * @return ( bool ) + */ + bool GetBar( + XOHCL &source, + XOHCL &bar // + ) + { + // + bool result = false; + + // + bar.Clean(); + + // + string symbol = GetSymbol(); + ENUM_TIMEFRAMES period = GetPeriod(); + + // + result = + IsValid(symbol) && + IsValid(period) && + source.IsValid(); + if (!result) + { + return result; + } + + // + int index = iBarShift( + symbol, + period, + source.time // + ); + result = bar.Init( + symbol, + period, + index // + ); + if (!result) + { + // + bar.Clean(); + return result; + } + + // + return result; + } + + /** + * Retrieve Specified Bar ... + * + * @param bar: XOHCL instance ... + * @param index: Integer ... + * + * @return ( bool ) + */ + bool GetBar( + XOHCL &bar, + int index = 0 // + ) + { + // + bool result = false; + + // + bar.Clean(); + + // + if (index < 0) + { + index = 0; + } + + // + string symbol = GetSymbol(); + ENUM_TIMEFRAMES period = GetPeriod(); + + // + result = bar.Init( + symbol, + period, + index // + ); + + // + return result; + } + + /** + * Retrieve Specified Bar ... + * + * @param bar: XOHCL instance ... + * @param time: Datetime ... + * + * @return ( bool ) + */ + bool GetBar( + XOHCL &bar, + datetime time = NULL // + ) + { + // + bool result = false; + + // + int index = GetBarIndex(time); + result = GetBar(bar, + index // + ); + + // + return result; + } + + /** + * Retrieve Specified Time Bar Index ... + * + * @param time: DateTime ... + * + * @return ( int ) + */ + int GetBarIndex(datetime time = NULL) + { + // + int result = -1; + + // + time = NormalizeTime(time); + + // + string symbol = GetSymbol(); + ENUM_TIMEFRAMES period = GetPeriod(); + + // + result = iBarShift( + symbol, + period, + time // + ); + + // + return result; + } + + /** + * Retrieve Cycle Conditions ... + * + * @param events: ENUM_X_CYCLE_EVENTS member, Array ... + * @param conditions: X121SMCCycleConditions instance ... + * @param barIndex: Integer ... + * @param loopback: Integer ... + * + * @return ( bool ) + */ + bool GetConditions( + ENUM_X_CYCLE_EVENTS &events[], + ENUM_XPOI_EVENTS &poiEvents[], + X121SMCCycleConditions &conditions, + int barIndex = 0, + int loopback = 7 // + ) + { + // + bool result = false; + + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + if (loopback < 5) + { + loopback = 5; + } + + // + Clean(events); + Clean(poiEvents); + conditions.Clean(); + + // + result = mX121Helper.GetConditions( + conditions.x121Conditions, + barIndex, + loopback // + ); + if (!result) + { + // + conditions.Clean(); + return result; + } + + // + mPOIDetector.Update(poiEvents); + mPOIDetector.GetState(conditions.state); + + // + conditions.symbol = GetSymbol(); + conditions.period = GetPeriod(); + conditions.time = TimeCurrent(); + + // + // Update(); + + // + result = conditions.IsValid(); + + // + return result; + } + + // + // Tools ... + + // + int DetectRejections( + XBoxZone &rejections[], + int barIndex = 0, + bool forceBarType = true, + bool forceFiboPressure = true, + bool forceUnUsedRejections = true, + int maxAllowedLoopback = 587 // + ) + { + // + int result = 0; + + // + // Normalize Args ... + Clean(rejections); + + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + int idx = -1; + bool has = false; + for (int i = barIndex + 1; i < barIndex + maxAllowedLoopback; i++) + { + // + // Init Indexed Bar ... + XOHCL iBar; + XOHCL iCBar; + XOHCL iPBar; + has = GetBar(iBar, i); + has = + has && + iBar.GetPreviousBar(iCBar); + has = + has && + iCBar.GetPreviousBar(iPBar); + if (!has) + { + // + iBar.Clean(); + iCBar.Clean(); + iPBar.Clean(); + break; + } + + // + // Check CBar Bullish Fibo Pressure ... + bool cBarHasBullishFiboPressure = + mBarAnalyser + .HasFiboPressure( + iCBar, + X_DIRECTION_BULLISH, + X_FIBO_LEVEL_382 // + ); + + // + // Check CBar Bearish Fibo Pressure ... + bool cBarHasBearishFiboPressure = + mBarAnalyser + .HasFiboPressure( + iCBar, + X_DIRECTION_BEARISH, + X_FIBO_LEVEL_382 // + ); + + // + // Check Bar is Bullish Rejection Swing ... + bool isBullishRejection = + // + iCBar.low < iBar.low && + iCBar.low < iPBar.low && + // + iCBar.low < iCBar.GetDown() && + iCBar.GetLowShadow() > iCBar.GetBody() && + iCBar.GetLowShadow() > iCBar.GetHighShadow() + // + ; + + // + // Check Bar is Bearish Rejection Swing ... + bool isBearishRejection = + // + iCBar.high > iBar.high && + iCBar.high > iPBar.high && + // + iCBar.high > iCBar.GetUp() && + iCBar.GetHighShadow() > iCBar.GetBody() && + iCBar.GetHighShadow() > iCBar.GetLowShadow() + // + ; + + // + // Apply Fibo Pressure ... + if (forceFiboPressure) + { + // + isBullishRejection = + isBullishRejection && + cBarHasBullishFiboPressure; + + // + isBearishRejection = + isBearishRejection && + cBarHasBearishFiboPressure; + } + + // + // Apply Force Bar Type ... + if (forceBarType) + { + // + isBullishRejection = + isBullishRejection && + iCBar.IsBullish(); + + // + isBearishRejection = + isBearishRejection && + iCBar.IsBearish(); + } + + // + // Summarize Result ... + has = isBullishRejection || + isBearishRejection; + if (has) + { + // + XBoxZone iBox; + + // + iBox.to = iBar.time; + iBox.from = iCBar.time; + iBox.period = iBar.period; + iBox.symbol = iBar.symbol; + + // + iBox.dir = + isBullishRejection + ? X_DIRECTION_BULLISH + : X_DIRECTION_BEARISH; + + // + iBox.upper = + isBullishRejection + ? iCBar.GetDown() + : iCBar.high; + + // + iBox.lower = + isBullishRejection + ? iCBar.low + : iCBar.GetUp(); + + // + iBox.type = + isBullishRejection + ? "XSwingLow" + : "XSwingHigh"; + + // + // Validate Box ... + has = iBox.IsValid(); + if (has) + { + // + // Apply Force Unused Rejections ... + if (forceUnUsedRejections) + { + // + has = !IsBoxBreaked( + iBox, + iCBar.Index() + 1, + barIndex // + ); + } + + // + if (has) + { + // + idx = FindIndex( + iBox, + rejections // + ); + has = !IsValidIndex(idx); + if (has) + { + // + AddRef( + iBox, + rejections // + ); + } + } + } + + // + iBox.Clean(); + } + + // + iBar.Clean(); + iCBar.Clean(); + iPBar.Clean(); + } + + // + result = ArraySize(rejections); + + // + return result; + } + + // + datetime DetectNearestCloseOverX3MAFast( + XOHCL &bar, + int maxAllowedBars = 20 // + ) + { + // + datetime result = NULL; + + // + if (!bar.IsValid()) + { + return result; + } + + // + bool has = false; + int idx = bar.Index(); + int start = idx; + int end = start + maxAllowedBars; + bool canContinue = true; + while (canContinue) + { + // + XOHCL iBar; + has = iBar.Init( + bar.symbol, + bar.period, + start // + ); + if (!has) + { + // + iBar.Clean(); + break; + } + + // + double iFast = mX121Helper + .x3maHelper + .GetX3MaFast(start); + + // + has = iBar.close > iFast && + iBar.open < iFast; + if (has) + { + result = iBar.time; + } + + // + canContinue = + start < end && + !IsValid(result); + + // + start++; + + // + iBar.Clean(); + } + + // + return result; + } + + // + datetime DetectNearestCloseUnderX3MAFast( + XOHCL &bar, + int maxAllowedBars = 20 // + ) + { + // + datetime result = NULL; + + // + if (!bar.IsValid()) + { + return result; + } + + // + bool has = false; + int idx = bar.Index(); + int start = idx; + int end = start + maxAllowedBars; + bool canContinue = true; + while (canContinue) + { + // + XOHCL iBar; + has = iBar.Init( + bar.symbol, + bar.period, + start // + ); + if (!has) + { + // + iBar.Clean(); + break; + } + + // + double iFast = mX121Helper + .x3maHelper + .GetX3MaFast(start); + + // + has = iBar.close < iFast && + iBar.open > iFast; + if (has) + { + result = iBar.time; + } + + // + canContinue = + start < end && + !IsValid(result); + + // + start++; + + // + iBar.Clean(); + } + + // + return result; + } + + // + bool DetectNearestStrSwitched( + XOHCL &bar, + ENUM_X_DIRECTION &dir, + int barIndex = 0, + int maxAllowedBars = 20 // + ) + { + // + bool result = false; + + // + bar.Clean(); + dir = X_DIRECTION_NONE; + barIndex = NormalizeInt(barIndex, 0); + maxAllowedBars = NormalizeInt(maxAllowedBars, 20); + + // + // Looping Through LoopBack Period ... + // for Detecting Result ... + for (int i = barIndex; i < barIndex + maxAllowedBars; i++) + { + // + XOHCL iBar; + result = iBar.Init( + GetSymbol(), + GetPeriod(), + i // + ); + if (!result) + { + // + iBar.Clean(); + break; + } + + // + double iStrState = mX121Helper.xstrHelper.GetSTRState(i); + double iStrStateP = mX121Helper.xstrHelper.GetSTRState(i + 1); + + // + bool isStrBullish = iStrState > 0; + bool isStrBullishP = iStrStateP > 0; + + // + bool isStrBearish = iStrState < 0; + bool isStrBearishP = iStrStateP < 0; + + // + bool isBullish = isStrBullish && + !isStrBullishP; + + // + bool isBearish = isStrBearish && + !isStrBearishP; + + // + result = isBullish || + isBearish; + if (result) + { + // + bar = iBar; + + // + dir = isBullish + ? X_DIRECTION_BULLISH + : X_DIRECTION_BEARISH; + + // + iBar.Clean(); + break; + } + + // + iBar.Clean(); + } + + // + return result; + } + + // + // Virtuals ... + + /** + * Set Default Properties Values ... + */ + virtual void Default() + { + } + + // + protected: + // + + // + private: + // + // Props ... + string mSymbol; + ENUM_TIMEFRAMES mPeriod; + + // + // Actions ... + + /** + * Release All Resources ... + */ + void DeInit() + { + // + ZeroMemory(mX121Helper); + ZeroMemory(mPOIDetector); + ZeroMemory(mBarAnalyser); + + // + delete mX121Helper; + delete mPOIDetector; + delete mBarAnalyser; + } + + /** + * Apply Chart Style ... + */ + void ApplyChartStyle() + { + // + // Retrieve Current Chart ID ... + long chartId = ChartID(); + + // + 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 + + // + ChartSetInteger(chartId, CHART_SHOW_BID_LINE, mShowBidLine); + ChartSetInteger(chartId, CHART_SHOW_ASK_LINE, mShowAskLine); + ChartSetInteger(chartId, CHART_SHOW_GRID, mShowGrid); + ChartSetInteger(chartId, CHART_SHOW_VOLUMES, mShowVolumes); + ChartSetInteger(chartId, CHART_SHOW_TRADE_LEVELS, mShowTradeLevels); + ChartSetInteger(chartId, CHART_AUTOSCROLL, mAutoScroll); + ChartSetInteger(chartId, CHART_QUICK_NAVIGATION, mQuickNavigation); + ChartSetInteger(chartId, CHART_COLOR_FOREGROUND, mForeGroundColor); + ChartSetInteger(chartId, CHART_COLOR_BACKGROUND, mBackGroundColor); + ChartSetInteger(chartId, CHART_COLOR_GRID, mGridColor); + ChartSetInteger(chartId, CHART_COLOR_BID, mBidLineColor); + ChartSetInteger(chartId, CHART_COLOR_ASK, mAskLineColor); + ChartSetInteger(chartId, CHART_COLOR_STOP_LEVEL, mStopColor); + ChartSetInteger(chartId, CHART_COLOR_VOLUME, mVolumesColor); + + // + // For Enabling XCC ... + // ChartSetInteger(chartId, CHART_MODE, mMode); + // ChartSetInteger(chartId, CHART_COLOR_CHART_UP, mUpColor); + // ChartSetInteger(chartId, CHART_COLOR_CHART_DOWN, mDownColor); + // ChartSetInteger(chartId, CHART_COLOR_CANDLE_BULL, mBullishColor); + // ChartSetInteger(chartId, CHART_COLOR_CANDLE_BEAR, mBearishColor); + // ChartSetInteger(chartId, CHART_COLOR_CHART_LINE, mLineColor); + } + + // +}; + +// +// Signal Provider Data ... +struct X121SMCStrategySignalProviderData +{ + // + // Props ... + + // + // Trigger ... + XPOIState triggerState; + double triggerBullishScore; + double triggerBearishScore; + X121Conditions triggerXConditions; + ENUM_XPOI_EVENTS triggerPoiEvents[]; + XC121SMCCycleHelper *triggerCycleHelper; + ENUM_X_CYCLE_EVENTS triggerCycleEvents[]; + X121SMCCycleConditions triggerConditions; + + // + // Decision ... + XPOIState decisionState; + double decisionBullishScore; + double decisionBearishScore; + X121Conditions decisionXConditions; + ENUM_XPOI_EVENTS decisionPoiEvents[]; + XC121SMCCycleHelper *decisionCycleHelper; + ENUM_X_CYCLE_EVENTS decisionCycleEvents[]; + X121SMCCycleConditions decisionConditions; + + // + // Analyse ... + XPOIState analyseState; + double analyseBullishScore; + double analyseBearishScore; + X121Conditions analyseXConditions; + ENUM_XPOI_EVENTS analysePoiEvents[]; + XC121SMCCycleHelper *analyseCycleHelper; + ENUM_X_CYCLE_EVENTS analyseCycleEvents[]; + X121SMCCycleConditions analyseConditions; + + // + // Verification ... + XPOIState verificationState; + double verificationBullishScore; + double verificationBearishScore; + X121Conditions verificationXConditions; + ENUM_XPOI_EVENTS verificationPoiEvents[]; + XC121SMCCycleHelper *verificationCycleHelper; + ENUM_X_CYCLE_EVENTS verificationCycleEvents[]; + X121SMCCycleConditions verificationConditions; + + // + // Consolidation ... + XPOIState consolidationState; + double consolidationBullishScore; + double consolidationBearishScore; + X121Conditions consolidationXConditions; + ENUM_XPOI_EVENTS consolidationPoiEvents[]; + XC121SMCCycleHelper *consolidationCycleHelper; + ENUM_X_CYCLE_EVENTS consolidationCycleEvents[]; + X121SMCCycleConditions consolidationConditions; + + // + // Vision ... + XPOIState visionState; + double visionBullishScore; + double visionBearishScore; + X121Conditions visionXConditions; + ENUM_XPOI_EVENTS visionPoiEvents[]; + XC121SMCCycleHelper *visionCycleHelper; + ENUM_X_CYCLE_EVENTS visionCycleEvents[]; + X121SMCCycleConditions visionConditions; + + // + // Constructor ... + X121SMCStrategySignalProviderData() + { + Clean(); + } + + // + // Tools ... + + // + // Cleanup ... + void Clean() + { + // + // Trigger ... + triggerState.Clean(); + triggerBullishScore = 0; + triggerBearishScore = 0; + Clean(triggerPoiEvents); + Clean(triggerCycleEvents); + triggerConditions.Clean(); + triggerXConditions.Clean(); + + // + // Decision ... + decisionState.Clean(); + decisionBullishScore = 0; + decisionBearishScore = 0; + Clean(decisionPoiEvents); + Clean(decisionCycleEvents); + decisionConditions.Clean(); + decisionXConditions.Clean(); + + // + // Analyse ... + analyseState.Clean(); + analyseBullishScore = 0; + analyseBearishScore = 0; + Clean(analysePoiEvents); + Clean(analyseCycleEvents); + analyseConditions.Clean(); + analyseXConditions.Clean(); + + // + // Verification ... + verificationState.Clean(); + verificationBullishScore = 0; + verificationBearishScore = 0; + Clean(verificationPoiEvents); + Clean(verificationCycleEvents); + verificationConditions.Clean(); + verificationXConditions.Clean(); + + // + // Consolidation ... + consolidationState.Clean(); + consolidationBullishScore = 0; + consolidationBearishScore = 0; + Clean(consolidationPoiEvents); + Clean(consolidationCycleEvents); + consolidationConditions.Clean(); + consolidationXConditions.Clean(); + + // + // Vision ... + visionState.Clean(); + visionBullishScore = 0; + visionBearishScore = 0; + Clean(visionPoiEvents); + Clean(visionCycleEvents); + visionConditions.Clean(); + visionXConditions.Clean(); + } + + // + void Destroy() + { + // + Clean(); + + // + ZeroMemory(visionCycleHelper); + ZeroMemory(triggerCycleHelper); + ZeroMemory(analyseCycleHelper); + ZeroMemory(decisionCycleHelper); + ZeroMemory(verificationCycleHelper); + ZeroMemory(consolidationCycleHelper); + + // + ZeroMemory(this); + } + + // + bool IsValid() + { + // + bool result = false; + + // + result = + visionCycleHelper != NULL && + triggerCycleHelper != NULL && + analyseCycleHelper != NULL && + decisionCycleHelper != NULL && + verificationCycleHelper != NULL && + consolidationCycleHelper != NULL; + + // + return result; + } + + // + // Initialize ... + bool Init( + XC121SMCCycleHelper *_triggerCycleHelper, + XC121SMCCycleHelper *_decisionCycleHelper, + XC121SMCCycleHelper *_analyseCycleHelper, + XC121SMCCycleHelper *_verificationCycleHelper, + XC121SMCCycleHelper *_consolidationCycleHelper, + XC121SMCCycleHelper *_visionCycleHelper // + ) + { + // + bool result = false; + + // + // Validate Cycle Helpers ... + result = + // + _visionCycleHelper != NULL && + _triggerCycleHelper != NULL && + _analyseCycleHelper != NULL && + _decisionCycleHelper != NULL && + _verificationCycleHelper != NULL && + _consolidationCycleHelper != NULL + // + ; + if (!result) + { + return result; + } + + // + visionCycleHelper = _visionCycleHelper; + triggerCycleHelper = _triggerCycleHelper; + analyseCycleHelper = _analyseCycleHelper; + decisionCycleHelper = _decisionCycleHelper; + verificationCycleHelper = _verificationCycleHelper; + consolidationCycleHelper = _consolidationCycleHelper; + + // + result = IsValid(); + + // + return result; + } + + // + // Prepare all ... + bool Prepare( + int barIndex = 0, + int loopback = 10, + bool trigger = false, + bool decision = true, + bool analyse = true, + bool verification = false, + bool consolidation = true, + bool vision = true // + ) + { + // + bool result = false; + + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + if (loopback < 7) + { + loopback = 7; + } + + // + result = IsValid(); + if (!result) + { + return result; + } + + // + // Trigger ... + if (trigger) + { + // + result = triggerCycleHelper.GetConditions( + triggerCycleEvents, + triggerPoiEvents, + triggerConditions, + barIndex, + loopback // + ); + if (!result) + { + // + Clean(triggerPoiEvents); + Clean(triggerCycleEvents); + + // + triggerConditions.Clean(); + + // + return result; + } + } + + // + // Decision ... + if (decision) + { + // + result = decisionCycleHelper.GetConditions( + decisionCycleEvents, + decisionPoiEvents, + decisionConditions, + barIndex, + loopback // + ); + if (!result) + { + // + Clean(triggerPoiEvents); + Clean(decisionPoiEvents); + Clean(triggerCycleEvents); + triggerConditions.Clean(); + Clean(decisionCycleEvents); + decisionConditions.Clean(); + + // + return result; + } + } + + // + // Analyse ... + if (analyse) + { + // + result = analyseCycleHelper.GetConditions( + analyseCycleEvents, + analysePoiEvents, + analyseConditions, + barIndex, + loopback // + ); + if (!result) + { + // + Clean(triggerPoiEvents); + Clean(analysePoiEvents); + Clean(decisionPoiEvents); + Clean(triggerCycleEvents); + Clean(analyseCycleEvents); + triggerConditions.Clean(); + analyseConditions.Clean(); + Clean(decisionCycleEvents); + decisionConditions.Clean(); + + // + return result; + } + } + + // + // Verification ... + if (verification) + { + // + result = verificationCycleHelper.GetConditions( + verificationCycleEvents, + verificationPoiEvents, + verificationConditions, + barIndex, + loopback // + ); + if (!result) + { + // + Clean(triggerPoiEvents); + Clean(analysePoiEvents); + Clean(decisionPoiEvents); + Clean(triggerCycleEvents); + Clean(analyseCycleEvents); + triggerConditions.Clean(); + analyseConditions.Clean(); + Clean(decisionCycleEvents); + decisionConditions.Clean(); + Clean(verificationPoiEvents); + Clean(verificationCycleEvents); + verificationConditions.Clean(); + + // + return result; + } + } + + // + // Consolidation ... + if (consolidation) + { + // + result = consolidationCycleHelper.GetConditions( + consolidationCycleEvents, + consolidationPoiEvents, + consolidationConditions, + barIndex, + loopback // + ); + if (!result) + { + // + Clean(triggerPoiEvents); + Clean(analysePoiEvents); + Clean(decisionPoiEvents); + Clean(triggerCycleEvents); + Clean(analyseCycleEvents); + triggerConditions.Clean(); + analyseConditions.Clean(); + Clean(decisionCycleEvents); + decisionConditions.Clean(); + Clean(verificationPoiEvents); + Clean(consolidationPoiEvents); + Clean(verificationCycleEvents); + verificationConditions.Clean(); + Clean(consolidationCycleEvents); + consolidationConditions.Clean(); + + // + return result; + } + } + + // + // Vision ... + if (vision) + { + result = visionCycleHelper.GetConditions( + visionCycleEvents, + visionPoiEvents, + visionConditions, + barIndex, + loopback // + ); + if (!result) + { + // + Clean(visionPoiEvents); + Clean(triggerPoiEvents); + Clean(analysePoiEvents); + Clean(visionCycleEvents); + visionConditions.Clean(); + Clean(decisionPoiEvents); + Clean(triggerCycleEvents); + Clean(analyseCycleEvents); + triggerConditions.Clean(); + analyseConditions.Clean(); + Clean(decisionCycleEvents); + decisionConditions.Clean(); + Clean(verificationPoiEvents); + Clean(consolidationPoiEvents); + Clean(verificationCycleEvents); + verificationConditions.Clean(); + Clean(consolidationCycleEvents); + consolidationConditions.Clean(); + + // + return result; + } + } + + // + // Cycles POI States ... + visionState = visionConditions.state; + triggerState = triggerConditions.state; + analyseState = analyseConditions.state; + decisionState = decisionConditions.state; + verificationState = verificationConditions.state; + consolidationState = consolidationConditions.state; + + // + // Cycle X121Conditions ... + visionXConditions = visionConditions.x121Conditions; + triggerXConditions = triggerConditions.x121Conditions; + analyseXConditions = analyseConditions.x121Conditions; + decisionXConditions = decisionConditions.x121Conditions; + verificationXConditions = verificationConditions.x121Conditions; + consolidationXConditions = consolidationConditions.x121Conditions; + + // + // Trigger ... + triggerXConditions.GenerateScore( + triggerBullishScore, + triggerBearishScore // + ); + + // + // Decision ... + decisionXConditions.GenerateScore( + decisionBullishScore, + decisionBearishScore // + ); + + // + // Analyse ... + analyseXConditions.GenerateScore( + analyseBullishScore, + analyseBearishScore // + ); + + // + // Verification ... + verificationXConditions.GenerateScore( + verificationBullishScore, + verificationBearishScore // + ); + + // + // Consolidation ... + consolidationXConditions.GenerateScore( + consolidationBullishScore, + consolidationBearishScore // + ); + + // + // Vision ... + visionXConditions.GenerateScore( + visionBullishScore, + visionBearishScore // + ); + + // + return result; + } + + // + bool SelectCycle( + ENUM_X_CYCLES cycle, + XPOIState &cState, + XPOIStateEvents &cStateEvents, + X121Conditions &cXConditions, + XC121SMCCycleHelper *&cHelper, + X121SMCCycleConditions &cConditions // + ) + { + // + bool result = false; + + // + cState.Clean(); + ZeroMemory(cHelper); + cConditions.Clean(); + cStateEvents.Clean(); + cXConditions.Clean(); + + // + result = cycle != X_CYCLE_NONE; + if (!result) + { + return result; + } + + // + if (cycle == X_CYCLE_TRIGGER) + { + // + cState = triggerState; + cHelper = triggerCycleHelper; + cConditions = triggerConditions; + cXConditions = triggerXConditions; + cStateEvents.Init(triggerPoiEvents); + } + else if (cycle == X_CYCLE_DECISION) + { + // + cState = decisionState; + cHelper = decisionCycleHelper; + cConditions = decisionConditions; + cXConditions = decisionXConditions; + cStateEvents.Init(decisionPoiEvents); + } + else if (cycle == X_CYCLE_ANALYSE) + { + // + cState = analyseState; + cHelper = analyseCycleHelper; + cConditions = analyseConditions; + cXConditions = analyseXConditions; + cStateEvents.Init(analysePoiEvents); + } + else if (cycle == X_CYCLE_VERIFICATION) + { + // + cState = verificationState; + cHelper = verificationCycleHelper; + cConditions = verificationConditions; + cXConditions = verificationXConditions; + cStateEvents.Init(verificationPoiEvents); + } + else if (cycle == X_CYCLE_CONSOLIDATION) + { + // + cState = consolidationState; + cHelper = consolidationCycleHelper; + cConditions = consolidationConditions; + cXConditions = consolidationXConditions; + cStateEvents.Init(consolidationPoiEvents); + } + else if (cycle == X_CYCLE_VISION) + { + // + cState = visionState; + cHelper = visionCycleHelper; + cConditions = visionConditions; + cXConditions = visionXConditions; + cStateEvents.Init(visionPoiEvents); + } + + // + result = cState.IsValid() && + cHelper != NULL; + + // + return result; + } + + // + void MaxRequiredPOIs(int value) + { + // + if (!IsValid()) + { + return; + } + + // + visionCycleHelper.mPOIDetector.MaxRequiredPOIs(value); + analyseCycleHelper.mPOIDetector.MaxRequiredPOIs(value); + decisionCycleHelper.mPOIDetector.MaxRequiredPOIs(value); + consolidationCycleHelper.mPOIDetector.MaxRequiredPOIs(value); + } + + // + void MaxAllowedLoopbackForInit(int value) + { + // + if (!IsValid()) + { + return; + } + + // + visionCycleHelper.mPOIDetector.MaxAllowedLoopbackForInit(value); + analyseCycleHelper.mPOIDetector.MaxAllowedLoopbackForInit(value); + decisionCycleHelper.mPOIDetector.MaxAllowedLoopbackForInit(value); + consolidationCycleHelper.mPOIDetector.MaxAllowedLoopbackForInit(value); + } + + // +}; + +// diff --git a/BKPS/14040203/X121SMCEA/Classes/x-121.smc.x-tradehandler.class.mq5 b/BKPS/14040203/X121SMCEA/Classes/x-121.smc.x-tradehandler.class.mq5 new file mode 100644 index 0000000..ce4d65b --- /dev/null +++ b/BKPS/14040203/X121SMCEA/Classes/x-121.smc.x-tradehandler.class.mq5 @@ -0,0 +1,4403 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Class Library +// -------------------------------------- +// Name: XCX121SMCTradeHandler +// Description: provides all based classes for use ... +// +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +////////////////////////////////////////////////////// +// +// Global Properties ... +#property library +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://www.saherelm.ir" +#property version "1.00" +#property strict + +// +// Imports ... + +// +#include "../../Classes/x-saherelm.x-alert.class.mq5" +#include "../../Classes/x-saherelm.x-bar.analyser.class.mq5" +#include "../../Classes/x-saherelm.x-trade.class.mq5" +#include "../Libraries/x-121.smc.lib.mq5" + +// +// Definitions ... + +// +// Model a Trade Data ... +struct X121SMCTradeData +{ + // + double ask; // Ask Price on Start Time + double bid; // bid Price on Start Time + ulong ticket; // Position Ticket + double swap; // Swap + double profit; // Profit on Close + XSignal signal; // Signal Object + string message; // Message + datetime endTime; // End Time + datetime startTime; // Start Time + double commission; // Commission + string conditions; // Signal Conditions + double maxDrawdown; // Max Position Drawdown + double lastTarget; // Check Last Targetted + double lastTrailedTPLevel; // Hold Last Trailed TP Level + + // + // Constructor ... + X121SMCTradeData() + { + Clean(); + } + + /** + * Initialize Item ... + * + * @param _signal: XSignal instance Reference, Provides Source For Initializaion ... + * + * @return ( bool ) + */ + bool Init(XSignal &_signal) + { + // + bool result = false; + + // + Clean(); + + // + result = _signal.IsValid(); + if (!result) + { + return result; + } + + // + signal = _signal; + + // + result = IsValid(); + + // + return result; + } + + // + // Tools ... + + /** + * Cleaning Up Model ... + */ + void Clean() + { + // + ask = 0; + bid = 0; + swap = 0; + profit = 0; + ticket = 0; + commission = 0; + maxDrawdown = 0; + lastTrailedTPLevel = 0; + + // + endTime = NULL; + message = NULL; + startTime = NULL; + conditions = NULL; + + // + lastTarget = 0; + + // + signal.Clean(); + + // + ZeroMemory(this); + } + + /** + * Validate Model ... + * + * @return ( bool ) + */ + bool IsValid() + { + // + bool result = false; + + // + result = + // + signal.IsValid() + // + ; + + // + return result; + } + + /** + * Calculate Model Age ... + * + * @return ( int ) + */ + int GetAge() + { + // + int result = -1; + + // + if (!IsValid()) + { + return result; + } + + // + int startIndex = iBarShift( + GetSymbol(), + GetPeriod(), + startTime, + false // + ); + + // + datetime mEndTime = IsValid(endTime) + ? endTime + : TimeCurrent(); + int endIndex = iBarShift( + GetSymbol(), + GetPeriod(), + mEndTime, + false // + ); + + // + result = MathAbs(startIndex - endIndex); + + // + return result; + } + + // + // Owner Functions ... + + /** + * Check a Ticket is Own to Model or not ... + * + * @param _ticket: ULONG, Position Ticket ... + * + * @return ( bool ) + */ + bool IsOwn( + ulong _ticket // + ) + { + // + bool result = false; + + // + result = IsValid() && + _ticket == ticket; + + // + return result; + } + + /** + * Check Specified Conditions is Own to Model or not ... + * + * @param _symbol: String, Specified Symbol ... + * @param _provider: String, Specified Provider ... + * @param _period: ENUM_TIMEFRAMES member, Specified Signal Period ... + * @param _type: ENUM_X_POSITION_TYPES member, Specified Signal Type ... + * + * @return ( bool ) + */ + bool IsOwnSignalTime( + string _symbol, + string _provider, + ENUM_TIMEFRAMES _period, + ENUM_X_POSITION_TYPES _type, + datetime _time // + ) + { + // + bool result = false; + + // + result = + // + IsValid(_time) && + Time() == _time && + IsValid(_symbol) && + IsValid(_period) && + XType() == _type && + IsValid(_provider) && + GetPeriod() == _period && + GetSymbol() == _symbol && + Provider() == _provider && + XType() != X_POSITION_TYPE_ALL && + XType() != X_POSITION_TYPE_NONE + // + ; + + // + return result; + } + + /** + * Check Specified Conditions is Own to Model or not ... + * + * @param _symbol: String, Specified Symbol ... + * @param _provider: String, Specified Provider ... + * @param _period: ENUM_TIMEFRAMES member, Specified Signal Period ... + * @param _type: ENUM_X_POSITION_TYPES member, Specified Signal Type ... + * + * @return ( bool ) + */ + bool IsOwnStartTime( + string _symbol, + string _provider, + ENUM_TIMEFRAMES _period, + ENUM_X_POSITION_TYPES _type, + datetime _time // + ) + { + // + bool result = false; + + // + result = + // + IsValid(_time) && + IsValid(_symbol) && + IsValid(_period) && + XType() == _type && + IsValid(startTime) && + startTime == _time && + IsValid(_provider) && + GetPeriod() == _period && + GetSymbol() == _symbol && + Provider() == _provider && + XType() != X_POSITION_TYPE_ALL && + XType() != X_POSITION_TYPE_NONE + // + ; + + // + return result; + } + + /** + * Check Specified Signal is Own to Model or not ... + * + * @param _signal: XSignal instance Reference ... + * + * @return ( bool ) + */ + bool IsOwn(XSignal &_signal) + { + // + bool result = false; + + // + result = + // + IsValid() && + _signal.IsValid() && + IsOwnSignalTime( + _signal.symbol, + _signal.provider, + _signal.period, + ToPositionType(_signal.type), + _signal.time) + // + ; + + // + return result; + } + + /** + * Check Specified Position is Own to Model or not ... + * + * @param _position: XPosition instance Reference ... + * + * @return ( bool ) + */ + bool IsOwn(XPosition &_position) + { + // + bool result = false; + + // + result = + // + IsValid() && + _position.IsValid() && + IsOwnStartTime( + _position.symbol, + _position.provider, + _position.period, + ToPositionType(_position.type), + _position.openAt) + // + ; + + // + return result; + } + + /** + * Check Specified Position is Own to Model or not ... + * + * @param _position: XPosition instance Reference ... + * + * @return ( bool ) + */ + bool IsOwnPosition(XPosition &_position) + { + // + bool result = false; + + // + double tp = TP(); + double sl = SL(); + double entry = Entry(); + double volume = Volume(); + string symbol = GetSymbol(); + string provider = Provider(); + ENUM_POSITION_TYPE type = Type(); + ENUM_TIMEFRAMES period = GetPeriod(); + + // + double pVolume = _position.volume; + double pSL = NormalizePrice(_position.sl, _position.symbol); + double pTP = NormalizePrice(_position.tp, _position.symbol); + double pEntry = NormalizePrice(_position.entry, _position.symbol); + + // + result = + // + IsValid() && + (sl == pSL || + tp == pTP) && + entry == pEntry && + pVolume == volume && + _position.IsValid() && + type == _position.type && + symbol == _position.symbol && + period == _position.period && + provider == _position.provider + // + ; + + // + if (!result) + { + // + result = + // + IsValid() && + _position.IsValid() && + _position.ticket == signal.positionId; + } + + // + return result; + } + + /** + * Update Model Data by Providing Specified Signal ... + * + * @param _signal: XSignal instance Reference ... + * + * @return ( bool ) + */ + bool Update(XSignal &_signal) + { + // + bool result = false; + + // + result = + // + IsValid() && + _signal.IsValid() && + IsOwn(_signal) + // + ; + if (!result) + { + return result; + } + + // + signal = _signal; + + // + return result; + } + + /** + * Update Model Data by Providing Specified Position ... + * + * @param _position: XPosition instance Reference ... + * + * @return ( bool ) + */ + bool Update(XPosition &_position) + { + // + bool result = false; + + // + result = + // + IsValid() && + _position.IsValid() && + IsOwn(_position) + // + ; + if (!result) + { + return result; + } + + // + swap = _position.swap; + ticket = _position.ticket; + profit = _position.profit; + message = _position.comment; + startTime = _position.openAt; + + // + // Set Once ... + if (commission == 0 && + _position.commission != 0) + { + commission = _position.commission; + } + + // + // Set Once ... + if (ask == 0) + { + ask = GetAsk(_position.symbol); + } + + // + // Set Once ... + if (bid == 0) + { + bid = GetBid(_position.symbol); + } + + // + if (profit < 0 && profit < maxDrawdown) + { + maxDrawdown = profit; + } + + // + return result; + } + + /** + * Update Model Data by Providing Specified Position ... + * + * @param _position: XPosition instance Reference ... + * + * @return ( bool ) + */ + bool UpdatePosition(XPosition &_position) + { + // + bool result = false; + + // + result = + // + IsValid() && + _position.IsValid() && + IsOwnPosition(_position) + // + ; + if (!result) + { + return result; + } + + // + swap = _position.swap; + ticket = _position.ticket; + profit = _position.profit; + message = _position.comment; + startTime = _position.openAt; + + // + // Set Once ... + if (commission == 0 && + _position.commission != 0) + { + commission = _position.commission; + } + + // + // Set Once ... + if (ask == 0) + { + ask = GetAsk(_position.symbol); + } + + // + // Set Once ... + if (bid == 0) + { + bid = GetBid(_position.symbol); + } + + // + if (profit < 0 && profit < maxDrawdown) + { + maxDrawdown = profit; + } + + // + return result; + } + + // + // Tools Extensions ... + + /** + * Get Model Symbol ... + * + * @return ( string ) + */ + string GetSymbol() + { + return signal.symbol; + } + + /** + * Get Model Period ... + * + * @return ( ENUM_TIMEFRAMES ) + */ + ENUM_TIMEFRAMES GetPeriod() + { + return signal.period; + } + + /** + * Get Model Provider ... + * + * @return ( string ) + */ + string Provider() + { + return signal.provider; + } + + /** + * Get Model Entry ... + * + * @return ( double ) + */ + double Entry() + { + return signal.entry; + } + + /** + * Get Model Stop Loss ... + * + * @return ( double ) + */ + double SL() + { + return signal.sl; + } + + /** + * Get Model Take Profit ... + * + * @return ( double ) + */ + double TP() + { + return signal.tp; + } + + /** + * Get Model Target ... + * + * @return ( double ) + */ + int Targets(double &targets[]) + { + // + int result = 0; + + // + Copy( + signal.targets, + targets // + ); + + // + result = ArraySize(targets); + + // + return result; + } + + /** + * Get Position Spread on Open Time ... + * + * @return ( double ) + */ + double Spread() + { + return MathAbs(ask - bid); + } + + /** + * Get Model Volume ... + * + * @return ( double ) + */ + double Volume() + { + return signal.volume; + } + + /** + * Get Model Point Value ... + * + * @return ( double ) + */ + double Points() + { + return GetPoints(GetSymbol()); + } + + /** + * Get Model Type ... + * + * @return ( ENUM_POSITION_TYPE ) + */ + ENUM_POSITION_TYPE Type() + { + return signal.type; + } + + /** + * Get Model Type ... + * + * @return ( ENUM_X_POSITION_TYPES ) + */ + ENUM_X_POSITION_TYPES XType() + { + // + ENUM_X_POSITION_TYPES result = X_POSITION_TYPE_NONE; + + // + if (!IsValid()) + { + return result; + } + + // + result = + IsLong(Type()) + ? X_POSITION_TYPE_LONG + : X_POSITION_TYPE_SHORT; + + // + return result; + } + + /** + * Get Model Signal Mode ... + * + * @return ( ENUM_X_ORDER_MODES ) + */ + ENUM_X_ORDER_MODES Mode() + { + return signal.mode; + } + + /** + * Get Model Signal Time ... + * + * @return ( datetime ) + */ + datetime Time() + { + return signal.time; + } + + // + // Additional Helpers Extensions ... + + /** + * Get Signal Full TP Level ... + * + * @return ( double ) + */ + double FullTPLevel() + { + return signal.fullTPLevel; + } + + /** + * Check Can Partial Close Position or not ... + * + * @return ( bool ) + */ + bool CanPartialClose() + { + return signal.CanPartialClose(); + } + + /** + * Retrieve Partial Close Volume Multiplier ... + * + * @return ( double ) + */ + double PartialCloseMultiplier() + { + return signal.partialCloseMultiplier; + } + + /** + * Get Partial Close On TP Level ... + * + * @return ( double ) + */ + double PartialCloseOnTPLevel() + { + return signal.partialCloseOnTPLevel; + } + + /** + * Check Can Risk Free Position on Break Even Point or not ... + * + * @return ( bool ) + */ + bool CanRiskFreeOnBreakEvenPoint() + { + return signal.CanRiskFreeOnBreakEvenPoint(); + } + + /** + * Get Minimum Required Profit after Break Even Point for Risk Free ... + * + * @return ( double ) + */ + double TPLevelForBreakEven() + { + return signal.tpLevelForBreakEven; + } + + /** + * Calculate Break Even Point ... + * + * @return ( double ) + */ + double CalculateBreakEvenPoint() + { + // + double result = 0; + + // + bool isValid = + // + ask > 0 && + bid > 0 && + IsValid() && + ticket > 0 && + signal.IsValid() + // + ; + if (!isValid) + { + return result; + } + + // + // Calculate Spread ... + double spread = Spread(); + if (spread <= 0) + { + return result; + } + + // + // Calculate BEP ... + result = + // + spread + (-1 * swap) + MathAbs(commission) + // + ; + + // + return result; + } + + /** + * Check Can Trail Position Stop Loss or not ... + * + * @return ( bool ) + */ + bool CanTrailSL() + { + return signal.CanTrailSL(); + } + + /** + * Get Start Position SL Trailling on TP Level ... + * + * @return ( double ) + */ + double TrailSLStartOnReachTPLevel() + { + return signal.trailSLStartOnReachTPLevel; + } + + // + // Data Collector Extensions ... + + /** + * Get Data Collection File Name ... + * + * @return ( string ) + */ + string GetFileName() + { + // + string result = NULL; + + // + if (!IsValid()) + { + return result; + } + + // + result = + // + GetSymbol() + "\\" + + ToString(XType()) + "\\" + + (profit >= 0 ? "Profit" : "Loss") + "\\" + + ToString(ticket) + "_" + + ToString(GetPeriod()) + "_" + + ToFormatString(startTime) + // + ; + + // + return result; + } + + /** + * Get Signal Collectiong File Name ... + * + * @return ( string ) + */ + string GetSignalFileName() + { + // + string result = NULL; + + // + result = + // + GetSymbol() + "\\" + + ToString(XType()) + "\\" + + Provider() + "_" + + ToFormatString(startTime) + // + ; + + // + return result; + } + + /** + * Converts Model to String Representation ... + * + * @param onlySignals: Boolean, Specified Represent Only Signal or not ... + * + * @return ( string ) + */ + string ToString( + bool onlySignals = false // + ) + { + // + string result = NULL; + + // + int age = GetAge(); + + // + result = + // + (onlySignals ? "" : ToString("Ticket", ticket)) + + ToString("Symbol", GetSymbol()) + + ToString("Period", GetPeriod()) + + ToString("Entry", Entry()) + + ToString("Provider", Provider()) + + ToString("Type", ToString(XType())) + + ToString("Time", startTime) + + // + // Attach Trade Info ... + (onlySignals ? "" : + // + "-------------" + "\n" + + ToString("Volume", Volume()) + + ToString("Profit", profit) + + ToString("Commission", commission) + + ToString("Swap", swap) + + ToString("Max Drawdown", maxDrawdown) + + ToString("End Time", endTime) + + ToString("Age", age) + + ToString("Message", message) + + "" + // + ) + + // + // Attach Conditions to Signals ... + (!onlySignals ? "" : + // + "-------------" + "\n" + + ToString("Pushers", signal.pushers) + + "Conditions:" + "\n" + + "-------------" + "\n" + + conditions + + "" + // + ) + + // + "" + // + ; + + // + return result; + } + + // + // End Of X121SMCTradeData Model ... +}; + +// +// Model Specified Symbol's Positions States ... +struct X121SMCSymbolPositionInfo +{ + // + string symbol; + + // + datetime enableAt; + + // + int longSLs; + int longTPs; + + // + int shortSLs; + int shortTPs; + + // + int countedSLs; + + // + // Constructor ... + X121SMCSymbolPositionInfo() + { + Clean(); + } + + // + // Tools ... + + /** + * Cleanup ... + */ + void Clean() + { + // + longSLs = 0; + longTPs = 0; + + // + shortSLs = 0; + shortTPs = 0; + + // + countedSLs = 0; + + // + enableAt = NULL; + + // + ZeroMemory(this); + } + + /** + * Check is own Symbol Info ... + * + * @param _symbol: String ... + * + * @return ( bool ) + */ + bool IsOwn(string _symbol) + { + // + bool result = false; + + // + result = + // + IsValid(symbol) && + _symbol == symbol + // + ; + + // + return result; + } + + /** + * Check Symbol Trading is Enable or not ... + * + * @param time: DateTime ... + * + * @return ( bool ) + */ + bool IsEnable(datetime time = NULL) + { + // + bool result = false; + + // + time = NormalizeTime(time); + + // + bool isEnableAtValid = IsValid(enableAt); + + // + result = + !isEnableAtValid + ? true + : time > enableAt; + if (result && + isEnableAtValid) + { + Reset(); + } + + // + return result; + } + + /** + * Pause Symbol Trading ... + * + * @param seconds: Integer ... + */ + void Pause(int seconds) + { + // + if (seconds <= 0) + { + return; + } + + // + datetime _enableAt = ((datetime)((int)TimeCurrent() + seconds)); + enableAt = _enableAt; + } + + /** + * Handle Stop Loss ... + * + * @param _type: ENUM_POSITION_TYPE member ... + */ + void HandleSL(ENUM_POSITION_TYPE _type) + { + // + bool isLong = IsLong(_type); + if (isLong) + { + longSLs++; + } + else + { + shortSLs++; + } + + // + countedSLs++; + } + + /** + * Handle Take Profit ... + * + * @param _type: ENUM_POSITION_TYPE member ... + */ + void HandleTP(ENUM_POSITION_TYPE _type) + { + // + bool isLong = IsLong(_type); + if (isLong) + { + longTPs++; + } + else + { + shortTPs++; + } + + // + countedSLs--; + if (countedSLs < 0) + { + countedSLs = 0; + } + } + + /** + * Reset Counter ... + */ + void Reset() + { + // + countedSLs = 0; + enableAt = NULL; + } + + // + // End of X121SMCSymbolPositionInfo Model ... +}; + +// +// Implementations ... + +// +// a Class For Read and Write Trade Info Data in Files ... +class X121SMCTradeCollector +{ + // + // Public ... + public: + // + // Props ... + + // + // Constructor(s) ... + X121SMCTradeCollector( + string _path = NULL // Base Path + ) + { + // + mAccount = new XCAccount(); + + // + if (IsValid(_path)) + { + mPath = _path; + } + else + { + mPath = "X121SMCTradeData" + "\\" + mAccount.GetCompany(); + } + } + + // + // Deconstructor ... + ~X121SMCTradeCollector() + { + } + + /** + * Check Specified Model is Exists or not ... + * + * @param item: X121SMCTradeData instance Reference, Provides Source Model ... + * + * @return ( bool ) + */ + bool IsExists(X121SMCTradeData &item) + { + // + bool result = false; + + // + int mHandler = GetFileHandlerForRead(item); + result = mHandler != INVALID_HANDLE; + FileClose(mHandler); + + // + return result; + } + + /** + * Save Specified Model as Data ... + * + * @param item: X121SMCTradeData instance Reference, Provides Source Model ... + * + * @return ( bool ) + */ + bool Save(X121SMCTradeData &item) + { + // + bool result = false; + + // + // Check info is Valid ... + result = item.IsValid(); + if (!result) + { + return result; + } + + // + string content = item.ToString(); + content += "\n" + "-----------" + "\n" + "Signal: " + "\n" + "-----------" + "\n" + item.ToString(true); + + // + result = IsValid(content); + if (!result) + { + return result; + } + + // + int mHandler = GetFileHandlerForWrite(item); + result = mHandler != INVALID_HANDLE; + if (!result) + { + return result; + } + + // + FileWrite(mHandler, content); + FileFlush(mHandler); + FileClose(mHandler); + + // + return result; + } + + /** + * Save Specified Model as Signal ... + * + * @param item: X121SMCTradeData instance Reference, Provides Source Model ... + * + * @return ( bool ) + */ + bool SaveSignal(X121SMCTradeData &item) + { + // + bool result = false; + + // + string content = item.ToString(true); + result = IsValid(content); + if (!result) + { + return result; + } + + // + int mHandler = GetSignalFileHandlerForWrite(item); + result = mHandler != INVALID_HANDLE; + if (!result) + { + return result; + } + + // + FileWrite(mHandler, content); + FileFlush(mHandler); + FileClose(mHandler); + + // + return result; + } + + /** + * Save Specified Model Conditions ... + * Conditions only save for Loss Signals ... + * this means the profit must be Lower than Zero ... + * ans also message Contains SL ... + * + * @param item: X121SMCTradeData instance Reference, Provides Source Model ... + * + * @return ( bool ) + */ + bool SaveConditions(X121SMCTradeData &item) + { + // + bool result = false; + + // + // Validate Item ... + result = + // + item.profit < 0 && + Contains("SL", item.message) + // + ; + if (!result) + { + return result; + } + + // + string content = item.signal.conditions; + result = IsValid(content); + if (!result) + { + return result; + } + + // + int mHandler = GetConditionsFileHandlerForWrite(item); + result = mHandler != INVALID_HANDLE; + if (!result) + { + return result; + } + + // + FileSeek(mHandler, 0, SEEK_END); + FileWrite(mHandler, content); + FileFlush(mHandler); + FileClose(mHandler); + + // + return result; + } + + // + // Protected ... + protected: + // + // Private ... + private: + // + // Props ... + + // + string mPath; // Base Path ... + + // + XCAccount *mAccount; + + // + string GetFilePath(X121SMCTradeData &item) + { + // + string fileName = item.GetFileName(); + + // + return GetFilePath(fileName); + } + string GetFilePath(string fileName) + { + // + string result = ""; + + // + result = + // + mPath + "\\" + "Trades" + "\\" + fileName + ".x121.log" + // + ; + + // + return result; + } + + // + string GetSignalFilePath(X121SMCTradeData &item) + { + // + string fileName = item.GetSignalFileName(); + + // + return GetSignalFilePath(fileName); + } + string GetSignalFilePath(string fileName) + { + // + string result = ""; + + // + result = + // + mPath + "\\" + "Signals" + "\\" + fileName + ".x121.log" + // + ; + + // + return result; + } + + // + string GetConditionsFilePath(X121SMCTradeData &item) + { + // + bool isLong = IsLong(item.Type()); + + // + string fileName = + item.GetSymbol() + "\\" + + (isLong ? "Longs" : "Shorts"); + + // + return GetConditionsFilePath(fileName); + } + string GetConditionsFilePath(string fileName) + { + // + string result = ""; + + // + result = + // + mPath + "\\" + "Conditions" + "\\" + fileName + ".x121.log" + // + ; + + // + return result; + } + + // + int GetFileHandlerForRead(X121SMCTradeData &item) + { + // + int result = INVALID_HANDLE; + + // + string filePath = GetFilePath(item); + if (!IsValid(filePath)) + { + return result; + } + + // + result = FileOpen( + filePath, + FILE_READ | FILE_TXT // + ); + + // + return result; + } + int GetFileHandlerForWrite(X121SMCTradeData &item) + { + // + int result = INVALID_HANDLE; + + // + string filePath = GetFilePath(item); + if (!IsValid(filePath)) + { + return result; + } + + // + result = FileOpen( + filePath, + FILE_READ | FILE_WRITE | FILE_TXT // + ); + + // + return result; + } + + // + int GetSignalFileHandlerForRead(X121SMCTradeData &item) + { + // + int result = INVALID_HANDLE; + + // + string filePath = GetSignalFilePath(item); + if (!IsValid(filePath)) + { + return result; + } + + // + result = FileOpen( + filePath, + FILE_READ | FILE_TXT // + ); + + // + return result; + } + int GetSignalFileHandlerForWrite(X121SMCTradeData &item) + { + // + int result = INVALID_HANDLE; + + // + string filePath = GetSignalFilePath(item); + if (!IsValid(filePath)) + { + return result; + } + + // + result = FileOpen( + filePath, + FILE_READ | FILE_WRITE | FILE_TXT // + ); + + // + return result; + } + + // + int GetConditionsFileHandlerForRead(X121SMCTradeData &item) + { + // + int result = INVALID_HANDLE; + + // + string filePath = GetConditionsFilePath(item); + if (!IsValid(filePath)) + { + return result; + } + + // + result = FileOpen( + filePath, + FILE_READ | FILE_TXT // + ); + + // + return result; + } + int GetConditionsFileHandlerForWrite(X121SMCTradeData &item) + { + // + int result = INVALID_HANDLE; + + // + string filePath = GetConditionsFilePath(item); + if (!IsValid(filePath)) + { + return result; + } + + // + result = FileOpen( + filePath, + FILE_READ | FILE_WRITE | FILE_TXT // + ); + + // + return result; + } + + // + // End of X121SMCTradeCollector Class ... +}; + +// +// Trade Handler Class ... +// a Class For Handling All Trade Requirements ... +class XC121SMCTradeHandler : public XCBaseAlert +{ + // + // Public ... + public: + // + + // + // Constructor(s) ... + XC121SMCTradeHandler(XCTrade *trader) + { + // + mTrader = trader; + mAdditionalVolume = 0; + mCollector = new X121SMCTradeCollector(); + } + + // + // Deconstructor ... + ~XC121SMCTradeHandler() + { + // + Clean(mData); + Clean(mSymbolInfos); + Clean(mLastExecutedSignals); + + // + delete mTrader; + delete mCollector; + } + + // + // ReadOnly Props ... + + /** + * Get Max Same Time Trades ... + * + * @return ( double ) + */ + double GetMaxSameTimeTrades() + { + return maxSameTimeTrades; + } + + /** + * Get Max Drawdown Happens ... + * + * @return ( double ) + */ + double GetMaxDrawdown() + { + return maxDrawdown; + } + + /** + * Get Currently Drawdown of Account ... + * + * @return ( double ) + */ + double GetCurrentDrawdown() + { + return currentDrawdown; + } + + /** + * Get Account Current Drawdown Percent ... + * + * @return ( double ) + */ + double GetDrawdownPercent() + { + return drawdownPercent; + } + + // + // Properties Getter(s) / Setter(s) ... + + // + // Saving Properties ... + + /** + * Get Save Signals State ... + * + * @return ( bool ) + */ + bool SaveSignals() + { + return mSaveSignals; + } + + /** + * Set Save Signals State ... + * + * @param value: Boolean ... + */ + void SaveSignals(bool value) + { + mSaveSignals = value; + } + + /** + * Get Save Trades State ... + * + * @return ( bool ) + */ + bool SaveTrades() + { + return mSaveTrades; + } + + /** + * Set Save Trades State ... + * + * @param value: Boolean ... + */ + void SaveTrades(bool value) + { + mSaveTrades = value; + } + + /** + * Get Save Conditions State ... + * + * @return ( bool ) + */ + bool SaveConditions() + { + return mSaveConditions; + } + + /** + * Set Save Conditions State ... + * + * @param value: Boolean ... + */ + void SaveConditions(bool value) + { + mSaveConditions = value; + } + + // + // Signalling Props ... + + /** + * Get Allow Long Signals State ... + * + * @return ( bool ) + */ + bool AllowLong() + { + return mAllowLong; + } + + /** + * Set Allow Long Signals State ... + * + * @param value: Boolean ... + */ + void AllowLong(bool value) + { + mAllowLong = value; + } + + /** + * Get Allow Short Signals State ... + * + * @return ( bool ) + */ + bool AllowShort() + { + return mAllowShort; + } + + /** + * Set Allow Short Signals State ... + * + * @param value: Boolean ... + */ + void AllowShort(bool value) + { + mAllowShort = value; + } + + /** + * Get Max Allowed Long Signals ... + * 0 => Unlimited ... + * + * @return ( int ) + */ + int MaxAllowedLongs() + { + return mMaxAllowedLongs; + } + + /** + * Set Max Allowed Long Signals ... + * + * @param value: Integer ... + * 0 => Unlimited ... + */ + void MaxAllowedLongs(int value) + { + // + if (value < 0) + { + value = 0; + } + + // + mMaxAllowedLongs = value; + } + + /** + * Get Max Allowed Short Signals ... + * 0 => Unlimited ... + * + * @return ( int ) + */ + int MaxAllowedShorts() + { + return mMaxAllowedShorts; + } + + /** + * Set Max Allowed Short Signals ... + * + * @param value: Integer ... + * 0 => Unlimited ... + */ + void MaxAllowedShorts(int value) + { + // + if (value < 0) + { + value = 0; + } + + // + mMaxAllowedShorts = value; + } + + /** + * Get Use Max Allowed Signal Types Per Symbol State ... + * + * @return ( bool ) + */ + bool UseMaxAllowedSignalsPerSymbol() + { + return mUseMaxAllowedSignalsPerSymbol; + } + + /** + * Set Use Max Allowed Signal Types Per Symbol State ... + * + * @param value: Boolean ... + */ + void UseMaxAllowedSignalsPerSymbol(bool value) + { + mUseMaxAllowedSignalsPerSymbol = false; + } + + /** + * Get Last Position Profit In Points for Accept new Signal ... + * 0 => Accept All ... + * + * @return ( double ) + */ + double LastPositionProfitForAcceptNextInPoint() + { + return mLastPositionProfitForAcceptNextInPoint; + } + + /** + * Set Last Position Profit In Points for Accept new Signal ... + * + * @param value: Double ... + * 0 => Accept All ... + */ + void LastPositionProfitForAcceptNextInPoint(double value) + { + // + if (value < 0) + { + value = 0; + } + + // + mLastPositionProfitForAcceptNextInPoint = value; + } + + /** + * Get Delay between two Signals in Bars ... + * 0 => Accept All ... + * + * @return ( int ) + */ + int DelaysBetweenTwoSignalsInBar() + { + return mDelaysBetweenTwoSignalsInBar; + } + + /** + * Set Delay between two Signals in Bars ... + * + * @param value: Integer ... + * 0 => Accept All ... + */ + void DelaysBetweenTwoSignalsInBar(int value) + { + // + if (value < 0) + { + value = 0; + } + + // + mDelaysBetweenTwoSignalsInBar = value; + } + + /** + * Get Max Allowed Spread for Signalling ... + * 0 => Accept All ... + * + * @return ( double ) + */ + double MaxAllowedSpread() + { + return mMaxAllowedSpread; + } + + /** + * Set Max Allowed Spread for Signalling ... + * + * @param value: Double ... + * 0 => Accept All ... + */ + void MaxAllowedSpread(double value) + { + // + if (value < 0) + { + value = 0; + } + + // + mMaxAllowedSpread = value; + } + + /** + * Get Additional Signal Volume ... + * + * @return ( double ) + */ + double AdditionalVolume() + { + return mAdditionalVolume; + } + + /** + * Set Additional Signal Volume ... + * + * @param value: Double ... + * min = 0.01 + */ + void AdditionalVolume(double value) + { + // + if (value < 0) + { + value = 0; + } + + // + if (value > 0 && value < 0.01) + { + value = 0.01; + } + + // + mAdditionalVolume = value; + } + + // + // Risk Management Props ... + + /** + * Get Max Allowed Drawdown Percent for Open Trades ... + * 0 => Ignore ... + * min => 0 ... + * max => 100 ... + * + * @return ( double ) + */ + double MaxAllowedDrawdownToOpenTrades() + { + return mMaxAllowedDrawdownToOpenTrades; + } + + /** + * Set Max Allowed Drawdown Percent for Open Trades ... + * + * @param value: Double ... + * 0 => Ignore ... + * min => 0 ... + * max => 100 ... + */ + void MaxAllowedDrawdownToOpenTrades(double value) + { + // + if (value < 0) + { + value = 0; + } + + // + if (value > 50) + { + value = 50; + } + + // + mMaxAllowedDrawdownToOpenTrades = value; + } + + /** + * Get Max Allowed SL for Pause Signalling Per Symbol ... + * 0 => Unlimited ... + * + * @return ( int ) + */ + int MaxAllowedSLToPauseSignallingPerSymbol() + { + return mMaxAllowedSLToPauseSignallingPerSymbol; + } + + /** + * Set Max Allowed SL for Pause Signalling Per Symbol ... + * + * @param value: Integer ... + * 0 => Unlimited ... + */ + void MaxAllowedSLToPauseSignallingPerSymbol(int value) + { + // + if (value < 0) + { + value = 0; + } + + // + mMaxAllowedSLToPauseSignallingPerSymbol = value; + } + + /** + * Get Pause Signalling Per Symbol afte Max Allowed SL Reached In Seconds ... + * 0 => Ignore ... + * + * @return ( int ) + */ + int PauseSignallingAfterReachesMaxAllowedSLInSecconds() + { + return mPauseSignallingAfterReachesMaxAllowedSLInSecconds; + } + + /** + * Set Pause Signalling Per Symbol afte Max Allowed SL Reached In Seconds ... + * + * @param value: Integer ... + * 0 => Ignore ... + */ + void PauseSignallingAfterReachesMaxAllowedSLInSecconds(int value) + { + // + if (value < 0) + { + value = 0; + } + + // + mPauseSignallingAfterReachesMaxAllowedSLInSecconds = value; + } + + // + // Protection Props ... + + /** + * Get Allow Hedge Positions State ... + * + * @return ( bool ) + */ + bool AllowHedging() + { + return mAllowHedging; + } + + /** + * Set Allow Hedge Positions State ... + * + * @param value: Boolean ... + */ + void AllowHedging(bool value) + { + mAllowHedging = value; + } + + /** + * Get Minimum Open Positions for Hedging ... + * 0 => Ignore ... + * + * @return ( int ) + */ + int MinOpenTradesFroHedging() + { + return mMinOpenTradesFroHedging; + } + + /** + * Set Minimum Open Positions for Hedging ... + * + * @param value: Integer ... + * 0 => Ignore ... + */ + void MinOpenTradesFroHedging(int value) + { + // + if (value < 0) + { + value = 0; + } + + // + mMinOpenTradesFroHedging = value; + } + + /** + * Get Minimum Volume Step for Hedging ... + * 0 => Ignore ... + * + * @return ( double ) + */ + double HedgingMinVolumeStep() + { + return mHedgingMinVolumeStep; + } + + /** + * Set Minimum Volume Step for Hedging ... + * + * @param value: Double ... + * 0 => Ignore ... + */ + void HedgingMinVolumeStep(double value) + { + // + if (value < 0) + { + value = 0; + } + + // + if (value > 0 && value < 0.01) + { + value = 0.01; + } + + // + if (value > 0 && value > 0.1) + { + value = 0.1; + } + + // + mHedgingMinVolumeStep = value; + } + + /** + * Get Minimum Required Profit Per Volume Step for Hedging ... + * 0 => Ignore ... + * + * @return ( double ) + */ + double HedgeingMinRequiredProfitPerVolumeStep() + { + return mHedgeingMinRequiredProfitPerVolumeStep; + } + + /** + * Set Minimum Required Profit Per Volume Step for Hedging ... + * + * @param value: Double ... + * 0 => Ignore ... + */ + void HedgeingMinRequiredProfitPerVolumeStep(double value) + { + // + if (value < 0) + { + value = 0; + } + + // + mHedgeingMinRequiredProfitPerVolumeStep = value; + } + + // + // Actions ... + + // + // Data Collection Actions ... + + /** + * Add Executed Signal Data Model to Trade Datas ... + * + * @param signal: XSignal instance Reference, Issued Signal ... + */ + void Add(XSignal &signal) + { + // + // Check Signal is Valid and also not Exists + // in Datas ... + int idx = -1; + bool hasItem = HasItem( + signal, + idx // + ); + if (hasItem) + { + return; + } + + // + // Initialize Data Item and Add it to Collection of Datas + // if Everythings OK ... + X121SMCTradeData data; + bool isInited = data.Init(signal); + if (isInited) + { + // + Add(data); + SaveSignal(data); + } + } + + /** + * Update a Registered Data Model by Providing Specified Signal ... + * usually used When a signal Modified after Executed for Conditionally Signals ... + * + * @param signal: XSignal instance Reference, Issued Signal ... + */ + void Update(XSignal &signal) + { + // + // Validate Signal ... + if (!signal.IsValid()) + { + return; + } + + // + // Check Signal Registered Before ... + int idx = -1; + bool hasItem = HasItem( + signal, + idx // + ); + bool isUpdated = false; + if (!hasItem) + { + // + // Add New Item if not Exists ... + Add(signal); + isUpdated = true; + } + else + { + // + // Update Data Model in Datas Collection ... + isUpdated = mData[idx].Update(signal); + } + + // + if (isUpdated) + { + SaveSignal(mData[idx]); + } + } + + /** + * Update a Registered Data Model by Providing Specified Position ... + * used for Updating Positions Data or When a Conditional Order Executed as Position ... + * + * @param position: XPosition instance Referece ... + */ + void Update(XPosition &position) + { + // + // Validate Position ... + if (!position.IsValid()) + { + return; + } + + // + // Check Position Registered Before ... + int idx = -1; + bool hasItem = HasItem( + position, + idx // + ); + if (!hasItem) + { + return; + } + + // + // Update Data Model in Datas Collection ... + mData[idx].Update(position); + } + + /** + * Remove Specified Registered Signal from Data Collection ... + * + * @param signal: XSignal instance Reference ... + */ + void Remove(XSignal &signal) + { + // + // Validate Signal ... + if (!signal.IsValid()) + { + return; + } + + // + // Check Signal is Registered or not ... + int idx = -1; + bool hasItem = HasItem( + signal, + idx // + ); + if (!hasItem) + { + return; + } + + // + // Remove Data From Collection ... + ArrayRemove( + mData, + idx, + 1 // + ); + } + + /** + * Handle Position Execution Finished by Providing a Deal ... + * usually used when a Position TP/SL Triggered ... + * + * @param deal: XDeal instance Reference ... + */ + void Finish(const XDeal &deal) + { + // + // Validate Deal ... + // Check Specified Data Registered or not ... + int idx = -1; + bool hasItem = HasItem( + deal.positionId, + idx // + ); + if (!hasItem) + { + return; + } + + // + // Update Data Info ... + mData[idx].swap = deal.swap; + mData[idx].endTime = deal.time; + mData[idx].profit = deal.profit; + + // + // Check Deal Reason ... + bool isTP = deal.reason == DEAL_REASON_TP || + (deal.reason == DEAL_REASON_SL && deal.profit > 0); + bool isSL = deal.reason == DEAL_REASON_SL && deal.profit < 0; + + // + // Prepare Specified Message Based on Deal Reason ... + mData[idx].message = + isTP + ? "TP" + : isSL + ? "SL" + : ""; + + // + // Handle Symbol Positions TP or SL Actions ... + if (isTP || isSL) + { + // + // Check Symbol Position Info Model Exists ... + int symbolIDX = -1; + bool hasInfo = HasSymbol( + mData[idx].GetSymbol(), + symbolIDX // + ); + + // + // Try to Update or Add Symbol Position Info ... + X121SMCSymbolPositionInfo info; + if (!hasInfo) + { + // + // Add New One ... + info.symbol = mData[idx].GetSymbol(); + } + else + { + // + // Update Exists ... + info = mSymbolInfos[symbolIDX]; + + // + // Remove Exists ... + ArrayRemove( + mSymbolInfos, + symbolIDX, + 1 // + ); + } + + // + ENUM_POSITION_TYPE xType = IsLong(mData[idx].Type()) + ? POSITION_TYPE_BUY + : POSITION_TYPE_SELL; + + // + // Call Propper TP / SL Handlers on Symbol Position Info Model ... + if (isTP) + { + info.HandleTP(xType); + } + else if (isSL) + { + info.HandleSL(xType); + } + + // + // Add Model to Symbol Positions Collection ... + AddRef( + info, + mSymbolInfos // + ); + + // + // Try to Check Symbol Positions Info Collection for Pause Specified Symbol ... + HandlePauseSymbol(mData[idx].GetSymbol()); + } + + // + // Save Collector Calss Data Model ... + Save(idx); + } + + /** + * Handle Position Execution Finished by Providing some Data ... + * usually used when a Position Force Closed Triggered ... + * + * @param ticket: ULong, Position ticket ... + * @param position: XPosition instance Reference ... + * @param comment: String, Force Closing Comment ... + */ + void Finish( + const ulong ticket, + const XPosition &position, + const string comment // + ) + { + // + // Validate and Check Data Registered or not ... + int idx = -1; + bool hasItem = HasItem( + ticket, + idx // + ); + if (!hasItem) + { + return; + } + + // + // Update Data Info ... + mData[idx].swap = position.swap; + mData[idx].endTime = TimeCurrent(); + mData[idx].profit = position.profit; + + // + mData[idx].message = comment; + + // + // Handle Force Closes as TP/SL for Updating + // Symbol Info Positions ... + bool handleForceClose = true; + if (handleForceClose) + { + // + // Simulate TP/SL based on Closing Profit ... + bool isTP = position.profit > 0; + bool isSL = position.profit <= 0; + + // + if (isTP || isSL) + { + // + // Check Symbol Position Info Model Exists ... + int symbolIDX = -1; + bool hasInfo = HasSymbol( + mData[idx].GetSymbol(), + symbolIDX // + ); + + // + // Try to Update or Add Symbol Position Info ... + X121SMCSymbolPositionInfo info; + if (!hasInfo) + { + // + // Add New One ... + info.symbol = mData[idx].GetSymbol(); + } + else + { + // + // Update Exists ... + info = mSymbolInfos[symbolIDX]; + + // + // Remove Exists ... + ArrayRemove( + mSymbolInfos, + symbolIDX, + 1 // + ); + } + + // + ENUM_POSITION_TYPE xType = IsLong(mData[idx].Type()) + ? POSITION_TYPE_BUY + : POSITION_TYPE_SELL; + + // + // Call Propper TP / SL Handlers on Symbol Position Info Model ... + if (isTP) + { + info.HandleTP(xType); + } + else if (isSL) + { + info.HandleSL(xType); + } + + // + // Add Model to Symbol Positions Collection ... + AddRef( + info, + mSymbolInfos // + ); + + // + // Try to Check Symbol Positions Info Collection for Pause Specified Symbol ... + HandlePauseSymbol(mData[idx].GetSymbol()); + } + + // + // Save Collector Calss Data Model ... + Save(idx); + } + } + + /** + * Update New Open Positions Data on Collection ... + */ + void HandleNewPosition() + { + // + // Retrieve Last Open Position ... + ulong lastOpenPositionTicket = mTrader.GetLastOpenPositionTicket(); + if (lastOpenPositionTicket == 0) + { + return; + } + + // + XPosition position; + bool hasPosition = mTrader.GetPosition( + lastOpenPositionTicket, + position // + ); + if (!hasPosition) + { + return; + } + + // + // Calculate Position Commission ... + double commission = mTrader.GetPositionCommission(position.ticket); + position.commission = commission; + + // + // Apply Updates on Data Collection ... + int idx = -1; + bool hasItem = HasItemByPosition( + position, + idx // + ); + if (!hasItem) + { + return; + } + + // + mData[idx].UpdatePosition(position); + } + + // + // Symbol Position Info Actions ... + + /** + * Retrieve Specified Symbols Info ... + * + * @param symbol: String ... + * @param info: X121SMCSymbolPositionInfo instance ... + * + * @return ( bool ) + */ + bool GetSymbolInfo( + string symbol, + X121SMCSymbolPositionInfo &info // + ) + { + // + bool result = false; + + // + info.Clean(); + + // + int symbolIDX = -1; + result = HasSymbol( + symbol, + symbolIDX // + ); + if (!result) + { + return result; + } + + // + info = mSymbolInfos[symbolIDX]; + + // + return result; + } + + /** + * Pause Specified Symbol Trading ... + * + * @param symbol: String ... + */ + void HandlePauseSymbol(string symbol) + { + // + if (!IsValid(symbol)) + { + return; + } + + // + int idx = -1; + bool hasItem = HasSymbol( + symbol, + idx // + ); + if (!hasItem) + { + return; + } + + // + int maxAllowedSLToPause = MaxAllowedSLToPauseSignallingPerSymbol(); + int pauseDelay = PauseSignallingAfterReachesMaxAllowedSLInSecconds(); + if (maxAllowedSLToPause <= 0 || pauseDelay <= 0) + { + return; + } + + // + bool canPauseSymbol = + mSymbolInfos[idx].IsEnable() && + mSymbolInfos[idx].countedSLs >= maxAllowedSLToPause; + if (!canPauseSymbol) + { + return; + } + + // + mSymbolInfos[idx].Pause(pauseDelay); + + // + string message = "Pause (" + symbol + ") until: (" + ToString(mSymbolInfos[idx].enableAt) + ") ..."; + Alert(message); + + // + } + + /** + * Reset Specified Symbol Info ... + * + * @param symbol: String ... + */ + void ResetSymbolInfo(string symbol) + { + // + if (!IsValid(symbol)) + { + return; + } + + // + int symbolIDX = -1; + bool hasSymbol = HasSymbol( + symbol, + symbolIDX // + ); + if (!hasSymbol) + { + return; + } + + // + mSymbolInfos[symbolIDX].Reset(); + + // + string message = "Reset " + symbol + ", Pause State ..."; + Alert(message); + } + + /** + * Reset All Paused Symbols ... + */ + void ResumePausedSymbols() + { + // + int count = ArraySize(mSymbolInfos); + if (!IsValidSize(count)) + { + return; + } + + // + for (int i = 0; i < count; i++) + { + // + mSymbolInfos[i].Reset(); + } + + // + string message = "Force Resume Paused Symbols ..."; + Alert(message); + } + + // + // Signal Execution Actions ... + + /** + * Validate Signal For Execution ... + * + * @param signal: XSignal instance Reference ... + * @param state: ENUM_X_SIGNAL_EXECUTION_RESULT Reference for olding Signal Execution Result Reason ... + * + * @return ( bool ) + */ + bool CanExecute( + XSignal &signal, + ENUM_X_SIGNAL_EXECUTION_RESULT &state // Execution State + ) + { + // + bool result = false; + + // + state = X_SIGNAL_EXECUTION_UNKNOWN; + + // + // Validate Signal ... + result = signal.IsValid(); + if (!result) + { + // + state = X_SIGNAL_EXECUTION_FAILED_INVALID_PARAMS; + return result; + } + + // + int symbolIDX = -1; + bool hasSymbolInfo = HasSymbol( + signal.symbol, + symbolIDX // + ); + + // + // Check rading Not Paused ... + result = + !hasSymbolInfo || + mSymbolInfos[symbolIDX].IsEnable(); + if (!result) + { + // + state = X_SIGNAL_EXECUTION_FAILED_NOT_ALLOWED; + return result; + } + + // + bool isLong = IsLong(signal.type); + + // + // Chekc Signalling Enable or not ... + result = + isLong + ? mAllowLong + : mAllowShort; + if (!result) + { + // + state = X_SIGNAL_EXECUTION_FAILED_NOT_ALLOWED; + return result; + } + + // + // Check Signal is Support or not ... + bool isSupport = IsSupport(signal.comment); + result = !isSupport; + if (!result) + { + // + state = X_SIGNAL_EXECUTION_FAILED_NOT_ALLOWED; + return result; + } + + // + ENUM_X_POSITION_TYPES pType = ToPositionType(signal.type); + double requiredProfitForAcceptNext = LastPositionProfitForAcceptNextInPoint(); + + // + // Implement Same Signal Conditions ... + XPosition smaeSymbolPositions[]; + int sameSymbolPositionsCount = mTrader.GetPositions( + smaeSymbolPositions, + signal.symbol, + signal.provider, + signal.period, + pType, + true, // Filter By Magic ... + true // Force Clean ... + ); + XPosition youngestSame; + int youngestSameAge = GetYoungest( + youngestSame, + smaeSymbolPositions // + ); + + // + double youngestSameProfitInPoint = youngestSame.GetProfitInPoint(); + + // + result = + sameSymbolPositionsCount == 0 || + (sameSymbolPositionsCount <= 0 + ? true + : requiredProfitForAcceptNext <= 0 + ? true + : youngestSameAge >= 0 && + youngestSameProfitInPoint >= requiredProfitForAcceptNext); + if (!result) + { + // + state = X_SIGNAL_EXECUTION_FAILED_PREV_PROFIT_ERROR; + return result; + } + + // + // Retrieve Longs and Shorts ... + XPosition longs[]; + XPosition shorts[]; + bool useMaxAllowedPositionsPerSymbol = UseMaxAllowedSignalsPerSymbol(); + + // + // Retrieve Positions ... + if (useMaxAllowedPositionsPerSymbol) + { + // + mTrader.GetPositions( + longs, + shorts, + signal.symbol, + signal.provider // + ); + } + else + { + // + mTrader.GetPositions( + longs, + shorts, + NULL, // All Symbols ... + signal.provider // + ); + } + + // + // Counting ... + int longsCount = ArraySize(longs); + int shortsCount = ArraySize(shorts); + + // + int maxAllowedLongs = MaxAllowedLongs(); + int maxAllowedShorts = MaxAllowedShorts(); + + // + // Check Max Allowed Positions ... + if (maxAllowedLongs > 0 || + maxAllowedShorts > 0) + { + // + if (isLong && maxAllowedLongs > 0 && longsCount > 0) + { + result = longsCount < maxAllowedLongs; + } + else if (!isLong && maxAllowedShorts > 0 && shortsCount > 0) + { + result = shortsCount < maxAllowedShorts; + } + if (!result) + { + // + state = X_SIGNAL_EXECUTION_FAILED_MAX_REACHED; + return result; + } + } + + // + // Check Delays Bar if Provided ... + int delaysBarBetweenTwoSignal = DelaysBetweenTwoSignalsInBar(); + if (delaysBarBetweenTwoSignal > 0) + { + // + // Try To Detect Youngest Position ... + int youngestAge = 0; + XPosition youngestPosition; + + // + // Long Positions when there are Longs ... + if (isLong && longsCount > 0) + { + // + youngestAge = GetYoungest( + youngestPosition, + longs // + ); + } + // + // Short Positions when there are Shorts ... + else if (!isLong && shortsCount > 0) + { + // + youngestAge = GetYoungest( + youngestPosition, + shorts // + ); + } + + // + // Check Delays When Youngest Position Exists ... + if (youngestAge > 0 && youngestPosition.IsValid()) + { + // + result = youngestAge >= delaysBarBetweenTwoSignal; + if (!result) + { + // + state = X_SIGNAL_EXECUTION_FAILED_DELAY_NOT_PASSED; + return result; + } + } + + // + // Check Delays When Youngest Position is not Exists ... + if (!youngestPosition.IsValid()) + { + // + // Try to Detect Last Issued Signal in Model Collections ... + int symbolIDX = FindLastExecutedSignalItem(signal); + if (IsValidIndex(symbolIDX)) + { + // + // Calculate Requirements ... + datetime cTime = TimeCurrent(); + int signalPeriodSeconds = PeriodSeconds(signal.period); + datetime lastExecutedTime = mLastExecutedSignals[symbolIDX].time; + datetime passedTime = ((datetime)lastExecutedTime + + ((delaysBarBetweenTwoSignal * signalPeriodSeconds))); + + // + // Check Conditions ... + result = cTime >= passedTime; + if (!result) + { + // + state = X_SIGNAL_EXECUTION_FAILED_DELAY_NOT_PASSED; + return result; + } + } + } + } + + // + // Check Max Drawdown Percent for Open Trades ... + double maxAllowedDrawdownPercent = MaxAllowedDrawdownToOpenTrades(); + if (maxAllowedDrawdownPercent > 0) + { + // + // Calculate and Update Drawdown Percent ... + double cdPercent = CalculateMaxDrawdownPercent(); + + // + result = cdPercent < maxAllowedDrawdownPercent; + if (!result) + { + // + state = X_SIGNAL_EXECUTION_FAILED_NO_EQUITY; + return result; + } + } + + // + // Check Spread ... + double spread = GetSpread(signal.symbol); + double maxAllowedSpread = MaxAllowedSpread(); + if (maxAllowedSpread > 0) + { + // + result = spread <= maxAllowedSpread; + if (!result) + { + // + state = X_SIGNAL_EXECUTION_FAILED_SPREAD; + return result; + } + } + + // + return result; + } + + /** + * Execute Specific Signal using Trade Handler ... + * + * @param signal: XSignal instance Reference ... + * @param state: ENUM_X_SIGNAL_EXECUTION_RESULT Reference for olding Signal Execution Result Reason ... + * @param ignorePolicies: Boolean ... + * + * @return ( bool ) + */ + bool ExecuteSignal( + XSignal &signal, // Signal for Execution + ENUM_X_SIGNAL_EXECUTION_RESULT &state, // Execution State + bool ignorePolicies = false // Ignore Execution Policies + ) + { + // + bool result = false; + + // + // Check Signal Validation ... + result = signal.IsValid(); + if (!result) + { + return result; + } + + // + // Check Policies ... + if (!ignorePolicies) + { + // + // Filter Signals if Necessary ... + result = CanExecute( + signal, + state // + ); + if (!result) + { + // + AlertSignalExecutionFailed( + signal, + state // + ); + + // + return result; + } + } + + // + // Apply Additional Volume to Signal if Provided ... + double additionalVolume = AdditionalVolume(); + if (additionalVolume > 0) + { + signal.volume += mAdditionalVolume; + } + + // + // Execute Signal ... + result = mTrader.ExecuteSignal( + signal, + state // + ); + if (result) + { + // + // Add XTradeHandler Data ... + Add(signal); + + // + // Handle Last Executed Signal ... + HandleSignalExecuted(signal); + + // + // Alert Executed Signal ... + string msg = (signal.type == POSITION_TYPE_BUY ? "Long" : "Short") + + " Signal Provided by: " + signal.provider + + (signal.pushers > 1 ? " Pushers: " + ToString(signal.pushers) : "") + + " on: " + signal.symbol + + " in: " + ToString(signal.period) + + " Executed Successfully ..."; + Alert(msg); + } + + // + if (!result) + { + // + AlertSignalExecutionFailed( + signal, + state // + ); + } + + // + return result; + } + + /** + * Execute Specific Signal using Trade Handler ... + * + * @param signal: XSignal instance Reference ... + * @param state: ENUM_X_SIGNAL_EXECUTION_RESULT Reference for olding Signal Execution Result Reason ... + * @param ignorePolicies: Boolean ... + * + * @return ( bool ) + */ + bool ExecuteSignal( + XSignal &signal, // Signal for Execution + X121SMCStrategyConditions &conditions, // Signal Conditions + ENUM_X_SIGNAL_EXECUTION_RESULT &state, // Execution State + bool ignorePolicies = false // Ignore Execution Policies + ) + { + // + bool result = false; + + // + // Check Signal Validation ... + result = signal.IsValid() && + conditions.IsValid(); + if (!result) + { + return result; + } + + // + // Check Policies ... + if (!ignorePolicies) + { + // + // Filter Signals if Necessary ... + result = CanExecute( + signal, + state // + ); + if (!result) + { + // + AlertSignalExecutionFailed( + signal, + state // + ); + + // + return result; + } + } + + // + // Apply Additional Volume to Signal if Provided ... + double additionalVolume = AdditionalVolume(); + if (additionalVolume > 0) + { + signal.volume += mAdditionalVolume; + } + + // + // Execute Signal ... + result = mTrader.ExecuteSignal( + signal, + state // + ); + if (result) + { + // + // Add XTradeHandler Data ... + Add(signal); + + // + // Handle Last Executed Signal ... + HandleSignalExecuted(signal); + + // + // Alert Executed Signal ... + string msg = (signal.type == POSITION_TYPE_BUY ? "Long" : "Short") + + " Signal Provided by: " + signal.provider + + (signal.pushers > 1 ? " Pushers: " + ToString(signal.pushers) : "") + + " on: " + signal.symbol + + " in: " + ToString(signal.period) + + " Executed Successfully ..."; + Alert(msg); + } + + // + if (!result) + { + // + AlertSignalExecutionFailed( + signal, + state // + ); + } + + // + return result; + } + + /** + * Force Close Specified Positions ... + * + * @param symbol: String ... + * @param provider: String ... + * @param period: ENUM_TIMEFRAMES member ... + * @param type: ENUM_X_POSITION_TYPES member ... + * + * @return ( bool ) + */ + bool ForceClose( + string symbol = NULL, + string provider = NULL, + ENUM_TIMEFRAMES period = NULL, + ENUM_X_POSITION_TYPES type = NULL // + ) + { + // + bool result = false; + + // + XPosition positions[]; + int count = mTrader.GetPositions( + positions, + symbol, + provider, + period, + type // + ); + result = IsValidSize(count); + if (!result) + { + return result; + } + + // + datetime cTime = TimeCurrent(); + + // + string comment = "Force Close (" + ToString(count) + ") Positions At: " + ToFormatString(cTime) + "..."; + int closedPositionsCount = mTrader.Close( + positions, + comment // + ); + result = IsValidSize(closedPositionsCount); + if (result) + { + // + // Finish Positions and Clear Data ... + for (int i = 0; i < ArraySize(positions); i++) + { + // + XPosition iPosition = positions[i]; + Finish( + iPosition.ticket, + iPosition, + comment // + ); + } + + // + ResetProtections(); + + // + string message = "Force Close (" + ToString(count) + ") Positions At: " + + ToFormatString(cTime) + " Successfully ..."; + Alert(message); + } + + // + return result; + } + + /** + * Force Close Positions ... + * + * @return ( bool ) + */ + bool ForceClose( + XPosition &positions[], + string comment, + string notificationMessage // + ) + { + // + bool result = false; + + // + int count = ArraySize(positions); + result = IsValidSize(count); + if (!result) + { + return result; + } + + // + int closedPositionsCount = mTrader.Close( + positions, + comment // + ); + result = IsValidSize(closedPositionsCount); + if (result) + { + // + // Finish Positions and Clear Data ... + for (int i = 0; i < ArraySize(positions); i++) + { + // + XPosition iPosition = positions[i]; + Finish( + iPosition.ticket, + iPosition, + comment // + ); + } + + // + ResetProtections(); + + // + if (IsValid(notificationMessage)) + { + Alert(notificationMessage); + } + } + + // + return result; + + // + return result; + } + + // + // Timing Actions ... + + /** + * Update Currently Open Positions Info on Data Collection ... + */ + void UpdateData() + { + // + // Retrieve Positions ... + XPosition positions[]; + int count = mTrader.GetPositions(positions); + if (!IsValidSize(count)) + { + return; + } + + // + // Loop Through Positions ... + for (int i = 0; i < count; i++) + { + // + XPosition iPosition = positions[i]; + + // + // Check Position Registered as Data or not ... + int idx = -1; + bool isExists = HasItem( + iPosition.ticket, + idx // + ); + if (isExists) + { + // + // Update Position Data ... + mData[idx].Update(iPosition); + } + } + } + + /** + * Handle Positiona Protections + */ + void HandleProtection() + { + // + string prefix = "Protector: "; + + // + int targetDistance = 5; + + // + // Implement Protection Senario Here ... + int count = Count(); + if (!IsValidSize(count)) + { + // + currentDrawdown = 0; + return; + } + + // + // Calculate Max Same Time Trades ... + maxSameTimeTrades = + maxSameTimeTrades == 0 || + maxSameTimeTrades < count + ? count + : maxSameTimeTrades; + + // + double bepSummary = 0; + double volumeSummary = 0; + double profitSummary = 0; + XPosition positions[]; + bool isProtected = false; + + // + // Loop through Open Positions ... + for (int i = 0; i < count; i++) + { + // + X121SMCTradeData iData = mData[i]; + + // + XPosition iPosition; + bool hasPosition = mTrader.GetPosition( + iData.ticket, + iPosition // + ); + if (!hasPosition) + { + continue; + } + AddRef( + iPosition, + positions // + ); + + // + // Calculate Break Even Point ... + double entry = iPosition.entry; + double points = iData.Points(); + double volume = iPosition.volume; + bool isLong = IsLong(iData.Type()); + double spread = GetSpread(iData.GetSymbol()); + double bep = iData.CalculateBreakEvenPoint(); + double exitPrice = GetExit( + iPosition.symbol, + iPosition.type // + ); + + // + double tps[]; + int reachedTPIndex = -1; + double reachedTPPrice = 0; + double reachedTPLevel = -1; + int tpLevelsCount = iPosition.CalculateTPLevels(tps); + iPosition.CalculateReahedTP( + reachedTPLevel, + reachedTPPrice // + ); + if (reachedTPLevel > 0) + { + // + reachedTPIndex = FindIndex( + reachedTPPrice, + tps // + ); + } + + // + bepSummary += bep; + volumeSummary += volume; + profitSummary += iPosition.profit; + + // + // All Protections Done for InProfit Positions ... + if (iData.profit > 0) + { + // + // Check Break Even ... + bool canRFOnBEP = iData.CanRiskFreeOnBreakEvenPoint(); + if (canRFOnBEP && reachedTPLevel > 0) + { + // + double tpLevel = iData.TPLevelForBreakEven(); + int tpIDX = (int)tpLevel - 1; + double rfTPPrice = tps[tpIDX]; + bool isSLReady = isLong + ? iPosition.sl < rfTPPrice + : iPosition.sl > rfTPPrice; + if (isSLReady && tpLevel == reachedTPLevel - 1) + { + // + double sl = rfTPPrice; + double tp = iPosition.tp; + string comment = "RF on BEP ..."; + bool isModified = mTrader.Modify( + iData.ticket, + sl, + tp, + comment // + ); + if (isModified) + { + // + isProtected = true; + + // + string message = prefix + + ToString(iData.Type()) + + " Position: " + + ToString(iData.ticket) + + " RF On BEP Successfully ..."; + Alert(message); + } + } + } + + // + // Check Partial Close ... + bool canPartialClose = iData.CanPartialClose(); + if (canPartialClose && reachedTPLevel > 0) + { + // + double mainVolume = iData.Volume(); + double currentVolume = iPosition.volume; + double partialCloseOnTP = iData.PartialCloseOnTPLevel(); + double partialCloseVolumeMultiplier = iData.PartialCloseMultiplier(); + double closeVolume = currentVolume * partialCloseVolumeMultiplier; + closeVolume = NormalizeVolume(closeVolume, iPosition.symbol); + canPartialClose = + currentVolume == mainVolume && + reachedTPLevel == partialCloseOnTP; + if (canPartialClose) + { + // + string comment = "PC On TP Level: " + ToString(partialCloseOnTP) + " ..."; + bool isModified = mTrader.ClosePartial( + iData.ticket, + closeVolume, + comment // + ); + if (isModified) + { + // + isProtected = true; + + // + string message = prefix + + ToString(iData.Type()) + + " Position: " + + ToString(iData.ticket) + + " PC (" + ToString(closeVolume) + ") On TP Level: " + + ToString(partialCloseOnTP) + " Successfully ..."; + Alert(message); + + // + // Finish Position ... + if (closeVolume == mainVolume) + { + // + Finish( + iPosition.ticket, + iPosition, + comment // + ); + + // + break; + } + } + } + } + + // + // Check for SL Trail ... + bool canTrailSL = iData.CanTrailSL(); + if (canTrailSL && reachedTPLevel > 0) + { + // + double tSLTPPrice = 0; + + // + double startTrailTPLevel = iData.TrailSLStartOnReachTPLevel(); + if (iData.lastTrailedTPLevel > 0) + { + startTrailTPLevel = iData.lastTrailedTPLevel + 1; + } + + // + canTrailSL = IsValidIndex(reachedTPIndex) && + reachedTPLevel >= startTrailTPLevel; + if (canTrailSL) + { + // + tSLTPPrice = + reachedTPIndex == 0 + ? tps[reachedTPIndex] + : tps[reachedTPIndex - 1]; + + // + canTrailSL = + tSLTPPrice > 0 && + iPosition.sl == 0 + ? (isLong + ? tSLTPPrice > iPosition.entry && + tSLTPPrice < iPosition.price + : tSLTPPrice < iPosition.entry && + tSLTPPrice > iPosition.price) + : (isLong + ? tSLTPPrice > iPosition.sl && + tSLTPPrice > iPosition.entry && + tSLTPPrice < iPosition.price + : tSLTPPrice < iPosition.sl && + tSLTPPrice < iPosition.entry && + tSLTPPrice > iPosition.price); + } + + // + if (canTrailSL) + { + // + string comment = "Trail SL on Reached TP: " + ToString(reachedTPLevel) + " ..."; + double sl = tSLTPPrice; + double tp = iPosition.tp; + bool isModified = mTrader.Modify( + iData.ticket, + sl, + tp, + comment // + ); + if (isModified) + { + // + isProtected = true; + + // + // Update Last Trailed TP Level ... + mData[i].lastTrailedTPLevel = reachedTPLevel; + + // + string message = prefix + + ToString(iData.Type()) + + " Position: " + + ToString(iData.ticket) + + " Trailed SL On Reached TP: " + ToString(reachedTPLevel) + + " Successfully ..."; + Alert(message); + } + } + } + + // + // Handle RF On Target ... + double targets[]; + int targetsCount = iData.Targets(targets); + bool hasTargets = IsValidSize(targetsCount); + if (hasTargets) + { + // + for (int k = 0; k < targetsCount; k++) + { + // + double target = targets[k]; + bool isValidTarget = + iData.lastTarget == 0 + ? true + : isLong + ? target > iData.lastTarget + : target < iData.lastTarget; + if (!isValidTarget) + { + continue; + } + + // + double targetDelta = isLong + ? target + (targetDistance * points) + : target - (targetDistance * points); + bool canRF = + target > 0 && + (isLong ? target > entry + : target < entry) && + (isLong + ? iPosition.sl < target + : iPosition.sl > target) && + (isLong + ? iPosition.price > targetDelta + : iPosition.price < targetDelta); + if (canRF) + { + // + double sl = target; + double tp = iPosition.tp; + string comment = "RF On Target ..."; + bool isModified = mTrader.Modify( + iData.ticket, + sl, + tp, + comment // + ); + if (isModified) + { + // + isProtected = true; + + // + // Update mData ... + mData[i].lastTarget = target; + + // + string message = prefix + + ToString(iData.Type()) + + " Position: " + + ToString(iData.ticket) + + " RF On Traget: " + ToString(target) + + " Successfully ..."; + Alert(message); + } + } + } + } + } + } + + // + // Calculate Max Draw Down ... + maxDrawdown = + profitSummary < 0 && + (maxDrawdown == 0 || + maxDrawdown < profitSummary) + ? profitSummary + : maxDrawdown; + + // + // Calculate Current Drawdown ... + currentDrawdown = + profitSummary < 0 + ? profitSummary + : 0; + + // + // Checking Hedge ... + bool allowHedge = AllowHedging() && + !isProtected; + if (allowHedge) + { + // + double minHedgeVolumeStep = HedgingMinVolumeStep(); + int minRequiredPositionsForHedge = MinOpenTradesFroHedging(); + double minRequiredProfitPerVolumeStepForHedge = HedgeingMinRequiredProfitPerVolumeStep(); + + // + double minRequiredAdditionalProfit = + bepSummary + + ((volumeSummary / minHedgeVolumeStep) * minRequiredProfitPerVolumeStepForHedge); + + // + bool canHedge = AllowHedging() && + profitSummary > 0 && + minHedgeVolumeStep > 0 && + minRequiredProfitPerVolumeStepForHedge > 0 && + profitSummary >= minRequiredAdditionalProfit && + (minRequiredPositionsForHedge <= 0 + ? true + : count >= minRequiredPositionsForHedge); + if (canHedge) + { + // + string comment = "Hedge (" + ToString(ArraySize(positions)) + ") Positions By: " + ToString(profitSummary) + "..."; + int closedPositionsCount = mTrader.Close( + positions, + comment // + ); + if (IsValidSize(closedPositionsCount)) + { + // + // Finish Positions and Clear Data ... + for (int i = 0; i < ArraySize(positions); i++) + { + // + XPosition iPosition = positions[i]; + Finish( + iPosition.ticket, + iPosition, + comment // + ); + } + + // + ResetProtections(); + + // + string message = "Hedge (" + ToString(ArraySize(positions)) + ") Positions By: " + + ToString(profitSummary) + " Successfully ..."; + Alert(message); + } + } + } + } + + // + // Protected ... + protected: + // + XCTrade *mTrader; // Instance of Trader Class + X121SMCTradeCollector *mCollector; // Instance of Trade Collector Class + + // + X121SMCTradeData mData[]; // Hold Trade Data + X121SMCSymbolPositionInfo mSymbolInfos[]; // Symbol Positions Info + XSymbolLastPosition mLastExecutedSignals[]; // Last Executed Signals + + // + void AlertSignalExecutionFailed( + XSignal &signal, + ENUM_X_SIGNAL_EXECUTION_RESULT state // + ) + { + // + // Alert Signal Execution Failed ... + string msg = "Failed To Execute " + + (signal.type == POSITION_TYPE_BUY ? "Long" : "Short") + + " Signal Provided by: " + signal.provider + + (signal.pushers > 1 ? " Pushers: " + ToString(signal.pushers) : "") + + " on: " + signal.symbol + + " in: " + ToString(signal.period) + + " due Reason: " + ToString(state) + " ..."; + Alert(msg); + } + + // + // Private ... + private: + // + // Props ... + + // + // Read Only ... + int maxSameTimeTrades; // Holds Max Same Time Trades + double maxDrawdown; // Max Drawdown + double currentDrawdown; // Current Drawdown + double drawdownPercent; // Drawdown Percent + double staticBalanceForCalculateDrawdown; // Static Balance for Max Drawdown Calculation + + // + bool mSaveSignals; // Save Signals + bool mSaveTrades; // Save Trades + bool mSaveConditions; // Save SL Conditions + + // + // Signalling Props ... + bool mAllowLong; // Allow Long Signals ... + bool mAllowShort; // Allow Short Signals ... + int mMaxAllowedLongs; // Max Allowed Long Signals ... + int mMaxAllowedShorts; // Max Allowed Short Signals ... + bool mUseMaxAllowedSignalsPerSymbol; // Use Max Allowed Signal Types Per Symbol ... + double mLastPositionProfitForAcceptNextInPoint; // Last Position Profit In Points for Accept new Signal ... + int mDelaysBetweenTwoSignalsInBar; // Delay between two Signals in Bars ... + double mMaxAllowedSpread; // Max Allowed Spread for Signalling ... + double mAdditionalVolume; // Volume Additional ... + + // + // Risk Management Props ... + double mMaxAllowedDrawdownToOpenTrades; // Max Allowed Drawdown for Open Trades ... + int mMaxAllowedSLToPauseSignallingPerSymbol; // Max Allowed SL for Pause Signalling Per Symbol ... + int mPauseSignallingAfterReachesMaxAllowedSLInSecconds; // Pause Signalling Per Symbol afte Max Allowed SL Reached In Seconds ... + + // + // Protection Props ... + bool mAllowHedging; // Allow Hedge Positions ... + int mMinOpenTradesFroHedging; // Minimum Open Positions for Hedging ... + double mHedgingMinVolumeStep; // Minimum Volume Step for Hedging ... + double mHedgeingMinRequiredProfitPerVolumeStep; // Minimum Required Profit Per Volume Step for Hedging ... + + // + // Common Functions ... + + // + // Count Data ... + int Count() + { + return ArraySize(mData); + } + + // + // Add Item ... + bool Add(X121SMCTradeData &item) + { + // + bool result = false; + + // + result = item.IsValid(); + if (!result) + { + return result; + } + + // + int index = -1; + if (item.ticket > 0) + { + // + result = !HasItem( + item.ticket, + index // + ); + } + else + { + // + result = !HasItem( + item.signal, + index // + ); + } + if (!result || IsValidIndex(index)) + { + // + result = false; + return result; + } + + // + AddRef( + item, + mData // + ); + + // + return result; + } + + // + // Find Item Index ... + bool HasItem( + ulong ticket, + int &index // + ) + { + // + bool result = false; + + // + index = -1; + + // + int count = Count(); + result = IsValidSize(count); + if (!result) + { + return result; + } + + // + for (int i = 0; i < count; i++) + { + // + result = mData[i].IsOwn(ticket); + if (result) + { + // + index = i; + break; + } + } + + // + return result; + } + + // + bool HasItem( + XSignal &signal, + int &index // + ) + { + // + bool result = false; + + // + index = -1; + + // + int count = Count(); + result = signal.IsValid() && + IsValidSize(count); + if (!result) + { + return result; + } + + // + for (int i = 0; i < count; i++) + { + // + bool isOwn = mData[i].IsOwn(signal); + if (isOwn) + { + // + index = i; + break; + } + } + + // + result = IsValidIndex(index); + + // + return result; + } + + // + bool HasItem( + XPosition &position, + int &index // + ) + { + // + bool result = false; + + // + index = -1; + + // + int count = Count(); + result = position.IsValid() && + IsValidSize(count); + if (!result) + { + return result; + } + + // + for (int i = 0; i < count; i++) + { + // + bool isOwn = mData[i].IsOwn(position); + if (isOwn) + { + // + index = i; + break; + } + } + + // + result = IsValidIndex(index); + + // + return result; + } + + // + bool HasItemByPosition( + XPosition &position, + int &index // + ) + { + // + bool result = false; + + // + index = -1; + + // + int count = Count(); + result = position.IsValid() && + IsValidSize(count); + if (!result) + { + return result; + } + + // + for (int i = 0; i < count; i++) + { + // + bool isOwn = mData[i].IsOwnPosition(position); + if (isOwn) + { + // + index = i; + break; + } + } + + // + result = IsValidIndex(index); + + // + return result; + } + + /** + * Find Specific Symbo Indo Item index ... + * + * @param symbol: String ... + * @param index: Integer ... + * + * @return ( bool ) + */ + bool HasSymbol( + string symbol, + int &index // + ) + { + // + bool result = false; + + // + index = -1; + + // + result = IsValid(symbol); + if (!result) + { + return result; + } + + // + int count = ArraySize(mSymbolInfos); + result = IsValidSize(count); + if (!result) + { + return result; + } + + // + for (int i = 0; i < count; i++) + { + // + bool isOwn = mSymbolInfos[i] + .IsOwn(symbol); + if (isOwn) + { + // + index = i; + break; + } + } + + // + result = IsValidIndex(index); + + // + return result; + } + + // + void Save(int index) + { + // + int count = Count(); + if (!IsValidIndex(index) || index > count - 1) + { + return; + } + + // + // Save Trade ... + if (mSaveTrades) + { + mCollector.Save(mData[index]); + } + + // + if (mSaveConditions) + { + mCollector.SaveConditions(mData[index]); + } + + // + // Remove Item From List ... + ArrayRemove( + mData, + index, + 1 // + ); + } + + // + void SaveSignal(X121SMCTradeData &item) + { + // + if (!mSaveSignals) + { + return; + } + + // + // Save Signal ... + mCollector.SaveSignal(item); + } + + // + // Find Last Signal Execution ... + int FindLastExecutedSignalItem(XSignal &signal) + { + // + int result = -1; + + // + if (!signal.IsValid()) + { + return result; + } + + // + int count = ArraySize(mLastExecutedSignals); + if (!IsValidSize(count)) + { + return result; + } + + // + for (int i = 0; i < count; i++) + { + // + XSymbolLastPosition iLast = mLastExecutedSignals[i]; + if (iLast.symbol == signal.symbol && + iLast.provider == signal.provider) + { + // + result = i; + break; + } + } + + // + return result; + } + + // + // Handle Last Signal Execution ... + void HandleSignalExecuted(XSignal &signal) + { + // + if (!signal.IsValid()) + { + return; + } + + // + datetime cTime = TimeCurrent(); + int symbolIDX = FindLastExecutedSignalItem(signal); + bool hasItem = IsValidIndex(symbolIDX); + if (hasItem) + { + mLastExecutedSignals[symbolIDX].time = cTime; + } + else + { + // + XSymbolLastPosition item; + + // + item.time = cTime; + item.symbol = signal.symbol; + item.provider = signal.provider; + + // + AddRef( + item, + mLastExecutedSignals // + ); + } + } + + // + double CalculateMaxDrawdownPercent() + { + // + double result = 0; + + // + double mEquity = mTrader.mAccount.GetEquity(); + if (mEquity > currentDrawdown) + { + currentDrawdown = mEquity; + } + + // + if (currentDrawdown >= 0) + { + // + drawdownPercent = 0; + return result; + } + + // + drawdownPercent = (currentDrawdown - mEquity) / + (staticBalanceForCalculateDrawdown > 0 + ? staticBalanceForCalculateDrawdown + : currentDrawdown) * + 100; + drawdownPercent = NormalizeDouble(drawdownPercent, 3); + result = drawdownPercent; + + // + return result; + } + + // + void ResetProtections() + { + // + ResumePausedSymbols(); + Clean(mLastExecutedSignals); + } + + // + // End of XC121SMCTradeHandler Class ... +}; + +// \ No newline at end of file diff --git a/BKPS/14040203/X121SMCEA/Experts/x-121.smc.expert.class.mq5 b/BKPS/14040203/X121SMCEA/Experts/x-121.smc.expert.class.mq5 new file mode 100644 index 0000000..78b1769 --- /dev/null +++ b/BKPS/14040203/X121SMCEA/Experts/x-121.smc.expert.class.mq5 @@ -0,0 +1,2446 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Class Library +// -------------------------------------- +// Name: XC121SMCExpert +// Description: provides all based classes for use ... +// +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +////////////////////////////////////////////////////// +// +// Global Properties ... +#property library +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://www.saherelm.ir" +#property version "1.00" +#property strict + +// +// Imports ... +#include "../../Classes/x-saherelm.x-expert.class.mq5" +#include "../../Helpers/x-saherelm.x121.xcc.helper.mq5" +#include "../../Helpers/x-saherelm.x121.xct.helper.mq5" +#include "../Classes/x-121.smc.x-tradehandler.class.mq5" +#include "../Libraries/x-121.smc.lib.mq5" +#include "../Strategy/x-121.smc.strategy.class.mq5" + +// +// Definitions ... +string XC121SMCExpertToken = "XC121SMCEA"; + +// +// Implementation ... + +class XC121SMCExpert : public XCBaseExpert +{ + // + public: + // + XCX121XCCHelper *xccHelper; + XCX121XCTHelper *xctHelper; + + // + // Signal Event Listener ... + TOnStopLoss OnPositionSLEventListener; + TOnTakeProfit OnPositionTPEventListener; + TOnPartialClose OnPositionPartialCloseEventListener; + TOnModify OnPositionModifiedEventListener; + TOnForceClose OnPositionForceCloseEventListener; + + // + TOnDealsChanged OnDealsChangedEventListener; + TOnOrdersChanged OnOrdersChangedEventListener; + TOnPositionsChanged OnPositionsChangedEventListener; + + // + TOnX121SMCSignal OnSignalEventListener; + + // + // Constructor(s) ... + XC121SMCExpert() + { + mShowCandles = true; + } + + // + // Deconstructor(s) ... + ~XC121SMCExpert() + { + Clean(mStrategies); + } + + // + // Getter(s) / Setter(s) ... + + // + // Signalling Props ... + + /** + * Get Allow Long Signals State ... + * + * @return ( bool ) + */ + bool AllowLong() + { + return mAllowLong; + } + + /** + * Set Allow Long Signals State ... + * + * @param value: Boolean ... + */ + void AllowLong(bool value) + { + // + mAllowLong = value; + ReConfigure(); + } + + /** + * Get Allow Short Signals State ... + * + * @return ( bool ) + */ + bool AllowShort() + { + return mAllowShort; + } + + /** + * Set Allow Short Signals State ... + * + * @param value: Boolean ... + */ + void AllowShort(bool value) + { + // + mAllowShort = value; + ReConfigure(); + } + + /** + * Get Max Allowed Long Signals ... + * 0 => Unlimited ... + * + * @return ( int ) + */ + int MaxAllowedLongs() + { + return mMaxAllowedLongs; + } + + /** + * Set Max Allowed Long Signals ... + * + * @param value: Integer ... + * 0 => Unlimited ... + */ + void MaxAllowedLongs(int value) + { + // + if (value < 0) + { + value = 0; + } + + // + mMaxAllowedLongs = value; + ReConfigure(); + } + + /** + * Get Max Allowed Short Signals ... + * 0 => Unlimited ... + * + * @return ( int ) + */ + int MaxAllowedShorts() + { + return mMaxAllowedShorts; + } + + /** + * Set Max Allowed Short Signals ... + * + * @param value: Integer ... + * 0 => Unlimited ... + */ + void MaxAllowedShorts(int value) + { + // + if (value < 0) + { + value = 0; + } + + // + mMaxAllowedShorts = value; + ReConfigure(); + } + + /** + * Get Use Max Allowed Signal Types Per Symbol State ... + * + * @return ( bool ) + */ + bool UseMaxAllowedSignalsPerSymbol() + { + return mUseMaxAllowedSignalsPerSymbol; + } + + /** + * Set Use Max Allowed Signal Types Per Symbol State ... + * + * @param value: Boolean ... + */ + void UseMaxAllowedSignalsPerSymbol(bool value) + { + // + mUseMaxAllowedSignalsPerSymbol = false; + ReConfigure(); + } + + /** + * Get Last Position Profit In Points for Accept new Signal ... + * 0 => Accept All ... + * + * @return ( double ) + */ + double LastPositionProfitForAcceptNextInPoint() + { + return mLastPositionProfitForAcceptNextInPoint; + } + + /** + * Set Last Position Profit In Points for Accept new Signal ... + * + * @param value: Double ... + * 0 => Accept All ... + */ + void LastPositionProfitForAcceptNextInPoint(double value) + { + // + if (value < 0) + { + value = 0; + } + + // + mLastPositionProfitForAcceptNextInPoint = value; + ReConfigure(); + } + + /** + * Get Delay between two Signals in Bars ... + * 0 => Accept All ... + * + * @return ( int ) + */ + int DelaysBetweenTwoSignalsInBar() + { + return mDelaysBetweenTwoSignalsInBar; + } + + /** + * Set Delay between two Signals in Bars ... + * + * @param value: Integer ... + * 0 => Accept All ... + */ + void DelaysBetweenTwoSignalsInBar(int value) + { + // + if (value < 0) + { + value = 0; + } + + // + mDelaysBetweenTwoSignalsInBar = value; + ReConfigure(); + } + + /** + * Get Max Allowed Spread for Signalling ... + * 0 => Accept All ... + * + * @return ( double ) + */ + double MaxAllowedSpread() + { + return mMaxAllowedSpread; + } + + /** + * Set Max Allowed Spread for Signalling ... + * + * @param value: Double ... + * 0 => Accept All ... + */ + void MaxAllowedSpread(double value) + { + // + if (value < 0) + { + value = 0; + } + + // + mMaxAllowedSpread = value; + ReConfigure(); + } + + // + // Trade ... + + /** + * Get Allow Open Trade On Signals State ... + * + * @return ( bool ) + */ + bool AllowTrade() + { + return mAllowTrade; + } + + /** + * Set Allow Open Trade On Signals State ... + * + * @param value: Boolean ... + */ + void AllowTrade(bool value) + { + mAllowTrade = value; + } + + /** + * Get Enable Trade on Signals on Time ... + * + * @return ( string ) + */ + string StartTradeAt() + { + return mStartTradeAt; + } + + /** + * Set Enable Trade on Signals on Time ... + * + * @param value: String ... + */ + void StartTradeAt(string value) + { + mStartTradeAt = value; + } + + /** + * Get Enable Trade on Signals on Time ... + * + * @return ( string ) + */ + string StopTradeAt() + { + return mStopTradeAt; + } + + /** + * Set Enable Trade on Signals on Time ... + * + * @param value: String ... + */ + void StopTradeAt(string value) + { + mStopTradeAt = value; + } + + /** + * Get Enable Close All Trades on Signals on Time ... + * + * @return ( string ) + */ + string CloseAllTradesAt() + { + return mCloseAllTradesAt; + } + + /** + * Set Enable Close All Trades on Signals on Time ... + * + * @param value: String ... + */ + void CloseAllTradesAt(string value) + { + mCloseAllTradesAt = value; + } + + // + // Risk Management Props ... + + /** + * Get Risk to Reward Ratio ... + * + * @return ( double ) + */ + double R2R() + { + return mR2R; + } + + /** + * Set Risk to Reward Ratio ... + * + * @param value: Double ... + */ + void R2R(double value) + { + // + if (value < 1) + { + value = 1; + } + + // + mR2R = value; + ReConfigure(); + } + + /** + * Get Static Volume ... + * + * @return ( double ) + */ + double Volume() + { + return mVolume; + } + + /** + * Set Static Volume ... + * + * @param value: Double ... + */ + void Volume(double value) + { + // + if (value < 0.01) + { + value = 0.01; + } + + // + mVolume = value; + ReConfigure(); + } + + /** + * Get Static Balance for Calculate Trade Volume ... + * + * @return ( double ) + */ + double StaticBalance() + { + return mStaticBalance; + } + + /** + * Set Static Balance for Calculate Trade Volume ... + * + * @param value: Argument 1 + */ + void StaticBalance(double value) + { + // + if (value < 0) + { + value = 0; + } + + // + mStaticBalance = value; + } + + /** + * Get Balance Used In Each Trade ... + * + * @return ( double ) + */ + double BalancePerTrade() + { + return mBalancePerTrade; + } + + /** + * Set Balance Used In Each Trade ... + * + * @param value: Argument 1 + */ + void BalancePerTrade(double value) + { + // + if (value < 0) + { + value = 0; + } + + // + mBalancePerTrade = value; + } + + /** + * Get Risk Percent Per Balance in Each Trade ... + * + * @return ( double ) + */ + double RiskPercentPerBalance() + { + return mRiskPercentPerBalance; + } + + /** + * Set Risk Percent Per Balance in Each Trade ... + * + * @param value: Double + */ + void RiskPercentPerBalance(double value) + { + // + if (value < 0) + { + value = 0; + } + + // + mRiskPercentPerBalance = value; + ReConfigure(); + } + + /** + * Get Dynamic Risk Management State ... + * + * @return ( bool ) + */ + bool DynamicRiskManagement() + { + return mDynamicRiskManagement; + } + + /** + * Set Dynamic Risk Management State ... + * + * @param value: Boolean ... + */ + void DynamicRiskManagement(bool value) + { + // + mDynamicRiskManagement = value; + ReConfigure(); + } + + /** + * Get Use Dynamic Volume State ... + * + * @return ( bool ) + */ + bool UseDynamicVolume() + { + return mUseDynamicVolume; + } + + /** + * Set Use Dynamic Volume State ... + * + * @param value: Boolean ... + */ + void UseDynamicVolume(bool value) + { + // + mUseDynamicVolume = value; + ReConfigure(); + } + + /** + * Get Increase Volume Step ... + * + * @return ( double ) + */ + double DynamicVolumeStep() + { + return mDynamicVolumeStep; + } + + /** + * Set Increase Volume Step ... + * + * @param value: Double ... + */ + void DynamicVolumeStep(double value) + { + // + if (value < 0.01) + { + value = 0.01; + } + + // + mDynamicVolumeStep = value; + ReConfigure(); + } + + /** + * Get Balance Factor for Generate Dynamic Volume ... + * + * @return ( double ) + */ + double DynamicVolumeBalanceFactor() + { + return mDynamicVolumeBalanceFactor; + } + + /** + * Set Balance Factor for Generate Dynamic Volume ... + * + * @param value: Double ... + */ + void DynamicVolumeBalanceFactor(double value) + { + // + if (value < 0) + { + value = 0; + } + + // + mDynamicVolumeBalanceFactor = value; + ReConfigure(); + } + + /** + * Get Max Allowed Drawdown Percent for Open Trades ... + * 0 => Ignore ... + * min => 0 ... + * max => 100 ... + * + * @return ( double ) + */ + double MaxAllowedDrawdownToOpenTrades() + { + return mMaxAllowedDrawdownToOpenTrades; + } + + /** + * Set Max Allowed Drawdown Percent for Open Trades ... + * + * @param value: Double ... + * 0 => Ignore ... + * min => 0 ... + * max => 100 ... + */ + void MaxAllowedDrawdownToOpenTrades(double value) + { + // + if (value < 0) + { + value = 0; + } + + // + if (value > 50) + { + value = 50; + } + + // + mMaxAllowedDrawdownToOpenTrades = value; + ReConfigure(); + } + + /** + * Get Max Allowed SL for Pause Signalling Per Symbol ... + * 0 => Unlimited ... + * + * @return ( int ) + */ + int MaxAllowedSLToPauseSignallingPerSymbol() + { + return mMaxAllowedSLToPauseSignallingPerSymbol; + } + + /** + * Set Max Allowed SL for Pause Signalling Per Symbol ... + * + * @param value: Integer ... + * 0 => Unlimited ... + */ + void MaxAllowedSLToPauseSignallingPerSymbol(int value) + { + // + if (value < 0) + { + value = 0; + } + + // + mMaxAllowedSLToPauseSignallingPerSymbol = value; + ReConfigure(); + } + + /** + * Get Pause Signalling Per Symbol afte Max Allowed SL Reached In Seconds ... + * 0 => Ignore ... + * + * @return ( int ) + */ + int PauseSignallingAfterReachesMaxAllowedSLInSecconds() + { + return mPauseSignallingAfterReachesMaxAllowedSLInSecconds; + } + + /** + * Set Pause Signalling Per Symbol afte Max Allowed SL Reached In Seconds ... + * + * @param value: Integer ... + * 0 => Ignore ... + */ + void PauseSignallingAfterReachesMaxAllowedSLInSecconds(int value) + { + // + if (value < 0) + { + value = 0; + } + + // + mPauseSignallingAfterReachesMaxAllowedSLInSecconds = value; + ReConfigure(); + } + + // + // Protection Props ... + + /** + * Get Allow Hedge Positions State ... + * + * @return ( bool ) + */ + bool AllowHedging() + { + return mAllowHedging; + } + + /** + * Set Allow Hedge Positions State ... + * + * @param value: Boolean ... + */ + void AllowHedging(bool value) + { + // + mAllowHedging = value; + ReConfigure(); + } + + /** + * Get Minimum Open Positions for Hedging ... + * 0 => Ignore ... + * + * @return ( int ) + */ + int MinOpenTradesFroHedging() + { + return mMinOpenTradesFroHedging; + } + + /** + * Set Minimum Open Positions for Hedging ... + * + * @param value: Integer ... + * 0 => Ignore ... + */ + void MinOpenTradesFroHedging(int value) + { + // + if (value < 0) + { + value = 0; + } + + // + mMinOpenTradesFroHedging = value; + ReConfigure(); + } + + /** + * Get Minimum Volume Step for Hedging ... + * 0 => Ignore ... + * + * @return ( double ) + */ + double HedgingMinVolumeStep() + { + return mHedgingMinVolumeStep; + } + + /** + * Set Minimum Volume Step for Hedging ... + * + * @param value: Double ... + * 0 => Ignore ... + */ + void HedgingMinVolumeStep(double value) + { + // + if (value < 0) + { + value = 0; + } + + // + if (value > 0 && value < 0.01) + { + value = 0.01; + } + + // + if (value > 0 && value > 0.1) + { + value = 0.1; + } + + // + mHedgingMinVolumeStep = value; + ReConfigure(); + } + + /** + * Get Minimum Required Profit Per Volume Step for Hedging ... + * 0 => Ignore ... + * + * @return ( double ) + */ + double HedgeingMinRequiredProfitPerVolumeStep() + { + return mHedgeingMinRequiredProfitPerVolumeStep; + } + + /** + * Set Minimum Required Profit Per Volume Step for Hedging ... + * + * @param value: Double ... + * 0 => Ignore ... + */ + void HedgeingMinRequiredProfitPerVolumeStep(double value) + { + // + if (value < 0) + { + value = 0; + } + + // + mHedgeingMinRequiredProfitPerVolumeStep = value; + ReConfigure(); + } + + // + // Actions ... + + /** + * Handle OnSignalRecieved Event ... + * + * @param signal: XSignal instance ... + * @param conditions: X121SMCStrategyConditions instance ... + */ + void HandleOnSignalRecieved( + XSignal &signal, + X121SMCStrategyConditions &conditions // + ) + { + // + // Check Signal and Conditions Validations ... + + // + if (!signal.IsValid()) + { + return; + } + + // + if (!conditions.IsValid()) + { + return; + } + + // + bool isLong = IsLong(signal.type); + + // + // Notify When a Raw (Unfiltered) Signal Recieved + // if it's Provided ... + bool mAlertRawSignals = false; + if (mAlertRawSignals) + { + // + string msg = "Raw " + (IsLong(signal.type) ? "Long" : "Short") + + " Signal Recieved: (" + signal.provider + "," + + signal.symbol + "," + + ToString(signal.period) + + ") ..."; + + // + Alert(msg); + } + + // + // Apply Volume On Signal ... + ApplyVolumeOnSignal(signal); + + // + // Chekc Signalling Enable or not ... + bool canContinue = + isLong + ? AllowLong() + : AllowShort(); + if (!canContinue) + { + return; + } + + // + // TODO: Apply Filtering On Signal ... + bool isFiltered = false; + if (isFiltered) + { + // + mTradeHandler.Remove(signal); + return; + } + + // + // Attach Conditions Summary to Signal ... + string conditionsSummary = conditions.GenerateSummary( + false, + false, + true, + false // + ); + + // + // TODO: Retrieve Conditions Summary based on Filter ... + signal.conditions = conditionsSummary; + + // + datetime currentTime = TimeCurrent(); + + // + // Chack Allow Trades ... + bool allowTrade = AllowTrade(); + if (allowTrade) + { + // + string startTime = StartTradeAt(); + string endTime = StopTradeAt(); + bool isTimePassed = IsTimeInRange( + TimeCurrent(), + startTime, + endTime // + ); + + // + if (isTimePassed) + { + // + // Execute Signal Using Trade Handler ... + ENUM_X_SIGNAL_EXECUTION_RESULT state; + bool isExecuted = mTradeHandler.ExecuteSignal( + signal, + conditions, + state, + false // ignore Policies ... + ); + } + else + { + // + string msg = "Failed To Execute " + + (IsLong(signal.type) + ? "Long" + : "Short") + + " Signal Recieved: (" + + signal.provider + "," + + signal.symbol + "," + + ToString(signal.period) + + ") due Trading offTime ..."; + + // + Alert(msg); + } + } + else + { + // + // Only Alert Signals ... + string msg = (IsLong(signal.type) + ? "Long" + : "Short") + + " Signal Recieved: (" + + signal.provider + "," + + signal.symbol + "," + + ToString(signal.period) + + ") ..."; + + // + Alert(msg); + } + + // + signal.Clean(); + conditions.Clean(); + } + + // + // Override Actions ... + + /** + * Apply Default Configurations ... + */ + void DefaultConfigure() override + { + // + // Commons ... + Slippage(10); + TagPrefix(""); + MagicNumber(1694056); + + // + // Symbol ... + SetSymbol(_Symbol); + SetPeriod(_Period); + MultiSymbol(false); + Symbols("EURUSDb,GBPUSDb,USDJPYb,USDCHFb,DowJones30,XAUUSDb"); + + // + // Signalling ... + Disabled(false); + AllowLong(true); + AllowShort(true); + + // + string tag = GetTag(); + + // + // Alert ... + SetAlertPrefix(tag); + SetAlertLogAlerts(true); + SetAlertPushAlerts(true); + SetAlertMailAlerts(false); + SetAlertEnableAlerts(true); + SetAlertTerminalAlerts(false); + + // + // Reports ... + ReportNewDays(true); + ReportNewWeeks(false); + ReportNewHours(false); + ReportNewMonths(false); + + // + R2R(1); + + // + // Volume Default Configurations ... + Volume(0.01); + UseDynamicVolume(false); + DynamicVolumeStep(0.01); + DynamicVolumeBalanceFactor(200); + + // + RiskPercentPerBalance(0); + DynamicRiskManagement(false); + } + + /** + * Vaslidate Inputs ... + * + * @return ( bool ) + */ + bool ValidateInputs() override + { + // + bool result = false; + + // + string errMessage = ""; + + // + bool isCommonValid = ( + // + Slippage() > 0 && + MagicNumber() > 0 + // + ); + if (!isCommonValid) + { + // + errMessage += "common configurations error;" + "\n"; + } + + // + // Checking Volume ... + bool isVolumeValid = true; + if (UseDynamicVolume()) + { + // + isVolumeValid = + DynamicVolumeStep() > 0 && + DynamicVolumeBalanceFactor() > 0; + if (!isVolumeValid) + { + errMessage += "Dynamic Volume configurations error;" + "\n"; + } + } + isVolumeValid = isVolumeValid && + Volume() > 0; + if (!isVolumeValid) + { + errMessage += "Static Volume configurations error;" + "\n"; + } + + // + result = + // + // Common ... + isCommonValid && + // + // Volume Coniguration ... + isVolumeValid && + // + // Otere ... + true + // + ; + + // + if (!result) + { + // + // Since here Logger not Initiallized, we Use Raw Print Command ... + errMessage = " Errors: \n" + errMessage; + Alert(errMessage); + } + + // + return result; + } + + // + // Initializers and DeInitializers ... + + /** + * Initial EA Requirements ... + * + * @return ( bool ) + */ + bool InitEA() override + { + // + bool result = true; + + // + // Initialize Indicator Helpers ... + + // + X121XCCInputs xccInputs; + xccInputs.Default(); + xccInputs.showCandles = mShowCandles; + xccHelper = new XCX121XCCHelper(); + result = xccHelper.Init( + _Symbol, + _Period, + xccInputs // + ); + if (!result) + { + return result; + } + + // + X121XCTInputs xctInputs; + xctInputs.Default(); + xctHelper = new XCX121XCTHelper(); + result = xctHelper.Init( + _Symbol, + _Period, + xctInputs // + ); + if (!result) + { + return result; + } + + // + // Configure Alerts ... + SetAlertPrefix(GetTag()); + SetAlertEnableAlerts(GetAlertEnableAlerts()); + SetAlertLogAlerts(GetAlertLogAlerts()); + SetAlertMailAlerts(GetAlertMailAlerts()); + SetAlertPushAlerts(GetAlertPushAlerts()); + SetAlertTerminalAlerts(GetAlertTerminalAlerts()); + + // + // Create Trader Instance and Configure it ... + mTrader = new XCTrade( + Slippage(), + MagicNumber() // + ); + mTrader.AddOnStopLossEventHandler(OnPositionSLEventListener); + mTrader.AddOnTakeProfitEventHandler(OnPositionTPEventListener); + mTrader.AddOnDealsChangedEventHandler(OnDealsChangedEventListener); + mTrader.AddOnOrdersChangedEventHandler(OnOrdersChangedEventListener); + mTrader.AddOnModifyPositionEventHandler(OnPositionModifiedEventListener); + mTrader.AddOnPositionsChangedEventHandler(OnPositionsChangedEventListener); + mTrader.AddOnForceClosePositionEventHandler(OnPositionForceCloseEventListener); + mTrader.AddOnPartialClosePositionEventHandler(OnPositionPartialCloseEventListener); + + // + // Initialize Trade Handler ... + mTradeHandler = new XC121SMCTradeHandler(mTrader); + mTradeHandler.SaveTrades(false); + mTradeHandler.SaveSignals(false); + mTradeHandler.SaveConditions(false); + mTradeHandler.MaxAllowedSpread(MaxAllowedSpread()); + + // + ReConfigureTradeHandler(); + + // + // Parsers ... + XSymbolParser _symbolParser; + + // + // Single Symbol ... + if (!MultiSymbol()) + { + // + // Register Strategy ... + + // + // Create Class Instance ... + XCX121SMCBaseStrategy *iX121SMCStrategy; + iX121SMCStrategy = new XCX121SMCStrategy( + _Symbol, + _Period // + ); + + // + iX121SMCStrategy.AddXSignalEventHandler(OnSignalEventListener); + + // + ConfigureStrategy(iX121SMCStrategy); + RegisterStrategy(iX121SMCStrategy); + } + // + // Multi Symbol ... + else + { + // + // Parse Symbols ... + string symbols[]; + int symbolsCount = SplitContent( + symbols, + Symbols() // + ); + result = IsValidSize(symbolsCount); + if (!result) + { + return result; + } + + // + for (int i = 0; i < symbolsCount; i++) + { + // + // Select Symbol ... + string iSymbol = symbols[i]; + + // + // Register Strategy Based On Symbol ... + + // + // Parse Symbol ... + bool isEURUSD = _symbolParser.IsEURUSD(_Symbol); + bool isGBPUSD = _symbolParser.IsGBPUSD(_Symbol); + bool isEURGBP = _symbolParser.IsEURGBP(_Symbol); + bool isUSDCHF = _symbolParser.IsUSDCHF(_Symbol); + bool isEURCHF = _symbolParser.IsEURCHF(_Symbol); + bool isUSDJPY = _symbolParser.IsUSDJPY(_Symbol); + bool isEURJPY = _symbolParser.IsEURJPY(_Symbol); + bool isUSDCAD = _symbolParser.IsUSDCAD(_Symbol); + bool isEURCAD = _symbolParser.IsEURCAD(_Symbol); + bool isAUDUSD = _symbolParser.IsAUDUSD(_Symbol); + bool isEURAUD = _symbolParser.IsEURAUD(_Symbol); + bool isNZDUSD = _symbolParser.IsNZDUSD(_Symbol); + bool isEURNZD = _symbolParser.IsEURNZD(_Symbol); + + // + // Check Symbol Can Register or not ... + bool canRegisterStrategy = true; + + // + if (canRegisterStrategy) + { + // + // Create Class Instance ... + XCX121SMCBaseStrategy *iX121SMCStrategy; + iX121SMCStrategy = new XCX121SMCStrategy( + iSymbol, + _Period // + ); + + // + iX121SMCStrategy.AddXSignalEventHandler(OnSignalEventListener); + + // + // Register Strategy ... + ConfigureStrategy(iX121SMCStrategy); + RegisterStrategy(iX121SMCStrategy); + } + } + + // + Clean(symbols); + } + + // + return result; + } + + /** + * Destroy all Initialized EA Requirements ... + */ + void DestroyEA() override + { + // + ZeroMemory(xccHelper); + ZeroMemory(xctHelper); + ZeroMemory(mTradeHandler); + + // + delete xccHelper; + delete xctHelper; + delete mTradeHandler; + + // + Clean(mStrategies); + } + + /** + * Call all Registered Strategies On Tick ... + */ + void HandleStrategiesOnTick() override + { + // + // Check Force Close ... + string forceCloseTimeStr = CloseAllTradesAt(); + if (IsValid(forceCloseTimeStr)) + { + // + datetime forceCloseTime = ParseDateTimeFromTimeString(forceCloseTimeStr); + bool canForceClose = IsTimeInRange( + TimeCurrent(), + forceCloseTime // + ) && + !mIsForceCloseAtTime; + if (canForceClose) + { + mIsForceCloseAtTime = mTradeHandler.ForceClose(); + } + } + + // + // Update Positions Data ... + mTradeHandler.UpdateData(); + + // + // Protect Positions ... + mTradeHandler.HandleProtection(); + + // + int count = ArraySize(mStrategies); + if (!IsValidSize(count)) + { + return; + } + + // + for (int i = 0; i < count; i++) + { + // + // Call Tick Handler Function ... + mStrategies[i].HandleTick(); + } + } + + /** + * Handle Strategies Guards ... + */ + void HandleStrategiesGuard() override + { + // + int count = ArraySize(mStrategies); + if (!IsValidSize(count)) + { + return; + } + + // + XPosition positions[]; + int positionsCount = mTrader.GetPositions( + positions, // Result ... + NULL, // Symbol ... + NULL, // Provider ... + NULL, // Period ... + X_POSITION_TYPE_ALL // All Types ... + ); + if (!IsValidSize(positionsCount)) + { + return; + } + + // + for (int i = 0; i < count; i++) + { + // + // Call Tick Handler Function ... + X121SMCGuard iGuards[]; + bool hasGuards = mStrategies[i].HandleGuard( + iGuards, + positions // + ); + if (hasGuards) + { + HandleGuards(iGuards); + } + } + + // + Clean(positions); + } + + // + // Event Handlers ... + + /** + * Calls When a Deals Changed Triggered ... + * + * @param count: Integer, Number of Changes ... + */ + void HandleOnDealsChanged(int count) override + { + } + + /** + * Calls When a Order Changed Triggered ... + * + * @param count: Integer, Number of Changes ... + */ + void HandleOnOrdersChanged(int count) override + { + } + + /** + * Calls When a Positions Changed Triggered ... + * + * @param count: Integer, Number of Changes ... + */ + void HandleOnPositionsChanged(int count) override + { + // + if (IsValidSize(count)) + { + mTradeHandler.HandleNewPosition(); + } + } + + /** + * Calls When a Position's SL Triggered ... + * + * @param deal: XDeal instance ... + */ + void HandleOnStopLossTriggered(const XDeal &deal) override + { + // + // Finish ... + mTradeHandler.Finish(deal); + + // + HandleReportBalance(); + } + + /** + * Calls When a Position's TP Triggered ... + * + * @param deal: XDeal instance ... + */ + void HandleOnTakeProfitTriggered(const XDeal &deal) override + { + // + // Finish ... + mTradeHandler.Finish(deal); + + // + bool useDynamicRiskManagement = DynamicRiskManagement(); + if (useDynamicRiskManagement) + { + mTradeHandler.ResetSymbolInfo(deal.symbol); + } + + // + HandleReportBalance(); + } + + /** + * Handle Force Close a Position ... + * + * @param ticket: Position Ticket ... + * @param position: XPosition ... + * @param comment: Closing Comment ... + */ + void HandleOnPositionForceClosed( + const ulong ticket, + const XPosition &position, + const string comment // + ) override + { + // + // Finish ... + mTradeHandler.Finish( + ticket, + position, + comment // + ); + + // + HandleReportBalance(); + } + + /** + * Reset All Paused Symbols on Each New Days ... + */ + void HandleOnNewDay() override + { + // + mIsForceCloseAtTime = false; + mTradeHandler.ResumePausedSymbols(); + } + + /** + * Re Configure Materials on Properties Changed ... + */ + void ReConfigure() override + { + // + ReConfigureTradeHandler(); + ReConfigureAllStrategies(); + } + + /** + * Generate Identifier Tag ... + * + * @return ( string ) + */ + string GetTag() override + { + // + string result = NULL; + + // + string tagPrefix = TagPrefix(); + if (IsValid(tagPrefix)) + { + result = tagPrefix; + } + else + { + result = ""; + } + + // + result = + XC121SMCExpertToken + result; + + // + return result; + } + + // + protected: + // + + // + // Props ... + + // + XC121SMCTradeHandler *mTradeHandler; // Trade Handler ... + XCX121SMCBaseStrategy *mStrategies[]; // Registere Strategies in EA ... + + // + // Actions ... + + /** + * Apply Volume Based On Configurations on Signal ... + * + * @param signal: XSignal instance + */ + void ApplyVolumeOnSignal(XSignal &signal) + { + // + if (signal.ignoreEAVolume) + { + return; + } + + // + double staticVolume = Volume(); + double fVolume = staticVolume > 0 + ? staticVolume + : 0.01; + + // + double staticBalance = StaticBalance(); + double accountBalance = mTrader.mAccount.GetBalance(); + double balance = staticBalance > 0 + ? staticBalance + : accountBalance; + + // + bool useDynamicVolume = UseDynamicVolume(); + double balancePerTrade = BalancePerTrade(); + double dynamicVolumeStep = DynamicVolumeStep(); + double riskPercentPerBalance = RiskPercentPerBalance(); + bool allowDynamicRiskManagement = DynamicRiskManagement(); + double dynamicVolumeBalanceFactor = DynamicVolumeBalanceFactor(); + + // + // Apply Static Volume ... + bool allowStaticVolume = staticVolume > 0; + + // + // Apply Dynamic Volume ... + bool aloowApplyDynamicVolume = useDynamicVolume && + dynamicVolumeStep && + dynamicVolumeBalanceFactor; + + // + // Apply Risk Per Trade Volume ... + bool allowApplyRiskPerTradeVolume = + !aloowApplyDynamicVolume && + riskPercentPerBalance > 0; + + // + // Apply Balance Per Trade Volume ... + bool allowApplyBalacePerTradeVolume = + !aloowApplyDynamicVolume && + !allowApplyRiskPerTradeVolume && + balancePerTrade > 0; + + // + // First Check Dynamic Volume ... + if (aloowApplyDynamicVolume) + { + // + // Dynamic Volume ... + double dVolume = mTrader.GetDynamicVolume( + signal.symbol, + dynamicVolumeBalanceFactor, + dynamicVolumeStep // + ); + if (dVolume < fVolume) + { + dVolume = fVolume; + } + + // + signal.volume = dVolume; + } + else if (allowApplyRiskPerTradeVolume) + { + // + double riskAmountPerBalance = (riskPercentPerBalance * balance) / 100; + + // + double risk = signal.GetRisk(); + double points = GetPoints(signal.symbol); + double riskInPoints = risk / points; + + // + double volume = mTrader.mAccount.CalculateVolume( + signal.symbol, + riskAmountPerBalance, + riskInPoints // + ); + if (volume <= 0) + { + volume = fVolume; + } + + // + // Check Dynamic Risk Management ... + bool allowDynamicRiskManagement = DynamicRiskManagement(); + if (allowDynamicRiskManagement) + { + // + // Calculate Dynamic Additional Risk Management Volume Multiplier ... + double mAdditionalRiskMultiplier = CalculateAdditionalVolumeMultiplier(signal); + if (mAdditionalRiskMultiplier < 1) + { + mAdditionalRiskMultiplier = 1; + } + + // + volume *= mAdditionalRiskMultiplier; + } + + // + signal.volume = volume; + } + else if (allowApplyBalacePerTradeVolume) + { + // + double risk = signal.GetRisk(); + double points = GetPoints(signal.symbol); + double riskInPoints = risk / points; + + // + double volume = mTrader.mAccount.CalculateVolume( + signal.symbol, + balancePerTrade, + riskInPoints // + ); + if (volume <= 0) + { + volume = fVolume; + } + + // + signal.volume = volume; + } + else if (allowStaticVolume) + { + signal.volume = staticVolume; + } + else + { + signal.volume = fVolume; + } + + // + // Normalize Signal Volume ... + signal.volume = NormalizeVolume( + signal.volume, + signal.symbol // + ); + } + + /** + * Configure Startegy ... + */ + void ConfigureStrategy(XCX121SMCBaseStrategy *&strategy) + { + // + if (strategy == NULL) + { + return; + } + + // + // Configure Alerts ... + strategy.SetAlertPrefix(GetTag()); + strategy.SetAlertLogAlerts(GetAlertLogAlerts()); + strategy.SetAlertMailAlerts(GetAlertMailAlerts()); + strategy.SetAlertPushAlerts(GetAlertPushAlerts()); + strategy.SetAlertEnableAlerts(GetAlertEnableAlerts()); + strategy.SetAlertTerminalAlerts(GetAlertTerminalAlerts()); + + // + // Confiugre Signalling ... + + // + strategy.R2R(R2R()); + strategy.AllowLong(AllowLong()); + strategy.AllowShort(AllowShort()); + + // + if (Disabled()) + { + strategy.Disable(); + } + else + { + strategy.Enable(); + } + + // + } + + /** + * Register an Strategy in EA ... + * + * @param strategy: XCX121SMCBaseStrategy instance ... + */ + void RegisterStrategy(XCX121SMCBaseStrategy *strategy) + { + // + if (strategy == NULL) + { + return; + } + + // + ArrayResize( + mStrategies, + ArraySize(mStrategies) + 1 // + ); + + // + mStrategies[ArraySize(mStrategies) - 1] = strategy; + } + + /** + * Re Configure All Registered Strategies ... + */ + void ReConfigureAllStrategies() + { + // + int count = ArraySize(mStrategies); + if (!IsValidSize(count)) + { + return; + } + + // + for (int i = 0; i < count; i++) + { + // + ConfigureStrategy(mStrategies[i]); + } + } + + /** + * Re Configure Trade Handler ... + */ + void ReConfigureTradeHandler() + { + // + if (mTradeHandler == NULL) + { + return; + } + + // + // Configure Alerts ... + mTradeHandler.SetAlertPrefix(GetTag()); + mTradeHandler.SetAlertEnableAlerts(GetAlertEnableAlerts()); + mTradeHandler.SetAlertLogAlerts(GetAlertLogAlerts()); + mTradeHandler.SetAlertMailAlerts(GetAlertMailAlerts()); + mTradeHandler.SetAlertPushAlerts(GetAlertPushAlerts()); + mTradeHandler.SetAlertTerminalAlerts(GetAlertTerminalAlerts()); + + // + mTradeHandler.AllowLong(AllowLong()); + mTradeHandler.AllowShort(AllowShort()); + mTradeHandler.MaxAllowedLongs(MaxAllowedLongs()); + mTradeHandler.MaxAllowedShorts(MaxAllowedShorts()); + mTradeHandler.UseMaxAllowedSignalsPerSymbol(UseMaxAllowedSignalsPerSymbol()); + mTradeHandler.LastPositionProfitForAcceptNextInPoint(LastPositionProfitForAcceptNextInPoint()); + mTradeHandler.DelaysBetweenTwoSignalsInBar(DelaysBetweenTwoSignalsInBar()); + mTradeHandler.MaxAllowedSpread(MaxAllowedSpread()); + mTradeHandler.MaxAllowedDrawdownToOpenTrades(MaxAllowedDrawdownToOpenTrades()); + mTradeHandler.MaxAllowedSLToPauseSignallingPerSymbol(MaxAllowedSLToPauseSignallingPerSymbol()); + mTradeHandler.PauseSignallingAfterReachesMaxAllowedSLInSecconds(PauseSignallingAfterReachesMaxAllowedSLInSecconds()); + mTradeHandler.AllowHedging(AllowHedging()); + mTradeHandler.MinOpenTradesFroHedging(MinOpenTradesFroHedging()); + mTradeHandler.HedgingMinVolumeStep(HedgingMinVolumeStep()); + mTradeHandler.HedgeingMinRequiredProfitPerVolumeStep(HedgeingMinRequiredProfitPerVolumeStep()); + } + + // + private: + // + + // + // Props ... + + // + bool mShowCandles; // Show Candles ... + + // + // Signalling Props ... + bool mAllowLong; // Allow Long Signals ... + bool mAllowShort; // Allow Short Signals ... + int mMaxAllowedLongs; // Max Allowed Long Signals ... + int mMaxAllowedShorts; // Max Allowed Short Signals ... + bool mUseMaxAllowedSignalsPerSymbol; // Use Max Allowed Signal Types Per Symbol ... + double mLastPositionProfitForAcceptNextInPoint; // Last Position Profit In Points for Accept new Signal ... + int mDelaysBetweenTwoSignalsInBar; // Delay between two Signals in Bars ... + double mMaxAllowedSpread; // Max Allowed Spread for Signalling ... + + // + // Trade ... + bool mAllowTrade; // Allow Open Trade On Signals ... + string mStartTradeAt; // Enable Trade on Signals on Time ... + string mStopTradeAt; // Enable Trade on Signals on Time ... + string mCloseAllTradesAt; // Enable Close All Trades on Signals on Time ... + + // + bool mIsForceCloseAtTime; + + // + // Risk Management Props ... + double mR2R; // Signallers Risk to Reward Ratio ... + double mVolume; // Static Volume ... + double mStaticBalance; // Static Balance for Calculate Trade Volume ... + double mBalancePerTrade; // Balance Used in Each Trade ... + double mRiskPercentPerBalance; // Risk Percent Per Balance in Each Trade ... + bool mDynamicRiskManagement; // Dynamic Risk Management ... + bool mUseDynamicVolume; // Use Dynamic Volume ... + double mDynamicVolumeStep; // Increase Volume Step ... + double mDynamicVolumeBalanceFactor; // Balance Factor for Generate Dynamic Volume ... + double mMaxAllowedDrawdownToOpenTrades; // Max Allowed Drawdown for Open Trades ... + int mMaxAllowedSLToPauseSignallingPerSymbol; // Max Allowed SL for Pause Signalling Per Symbol ... + int mPauseSignallingAfterReachesMaxAllowedSLInSecconds; // Pause Signalling Per Symbol afte Max Allowed SL Reached In Seconds ... + + // + // Protection Props ... + bool mAllowHedging; // Allow Hedge Positions ... + int mMinOpenTradesFroHedging; // Minimum Open Positions for Hedging ... + double mHedgingMinVolumeStep; // Minimum Volume Step for Hedging ... + double mHedgeingMinRequiredProfitPerVolumeStep; // Minimum Required Profit Per Volume Step for Hedging ... + + // + double CalculateAdditionalVolumeMultiplier(XSignal &signal) + { + // + double result = 0; + + // + if (!signal.IsValid()) + { + return result; + } + + // + X121SMCSymbolPositionInfo info; + bool hasInfo = mTradeHandler.GetSymbolInfo( + signal.symbol, + info // + ); + if (!hasInfo) + { + return result; + } + + // + if (info.countedSLs >= 2) + { + result = (info.countedSLs / 2) + 1; + } + + // + return result; + } + + /** + * Handle Guard Actions ... + * + * @param guards: X121SMCGuard instance Collection ... + */ + void HandleGuards(X121SMCGuard &guards[]) + { + // + int count = ArraySize(guards); + if (!HasChild(guards)) + { + return; + } + + // + for (int i = 0; i < count; i++) + { + // + X121SMCGuard iGuard = guards[i]; + + // + if (!iGuard.IsValid()) + { + continue; + } + + // + // Here we Have to Handle Guard Actions ... + + // + // Close ... + bool canClose = + NotEmpty(iGuard.ticket) && + iGuard.action == X_121_SMC_GUARD_ACTION_CLOSE; + + // + // Close All ... + bool canCloseAll = iGuard.action == X_121_SMC_GUARD_ACTION_CLOSE_ALL; + + // + // Close Longs ... + bool canCloseLongs = iGuard.action == X_121_SMC_GUARD_ACTION_CLOSE_LONGS; + + // + // Close Shorts ... + bool canCloseShorts = iGuard.action == X_121_SMC_GUARD_ACTION_CLOSE_SHORTS; + + // + // Partial Close ... + bool canPartialClose = + NotEmpty(iGuard.ticket) && + iGuard.volumeMultiplier > 0 && + iGuard.action == X_121_SMC_GUARD_ACTION_PARTIAL_CLOSE; + + // + // Trail Stop ... + bool canTrailStop = + iGuard.sl > 0 && + NotEmpty(iGuard.ticket) && + iGuard.action == X_121_SMC_GUARD_ACTION_TRAIL_STOP; + + // + // Trail Target ... + bool canTrailTarget = + iGuard.tp > 0 && + NotEmpty(iGuard.ticket) && + iGuard.action == X_121_SMC_GUARD_ACTION_TRAIL_TARGET; + + // + // Hedge ... + bool canHedge = iGuard.action == X_121_SMC_GUARD_ACTION_HEDGE; + + // + // Check is Guard Valid ... + bool isValidGuardAction = + canHedge || + canClose || + canCloseAll || + canTrailStop || + canCloseLongs || + canTrailTarget || + canCloseShorts || + canPartialClose; + if (!isValidGuardAction) + { + continue; + } + + // + // Now we Sure to Have a Valid Guard ... + // Start to o Guard Actions ... + + // + // Close All ... + if (canCloseAll) + { + // + XPosition positions[]; + int positionsCount = + mTrader + .GetPositions( + positions, // Result ... + iGuard.symbol, + iGuard.provider, + NULL, // Period ... + X_POSITION_TYPE_ALL, // All Types ... + true // Filter by Magic ... + ); + if (IsValidSize(positionsCount)) + { + // + string comment = "Guard Close All ..."; + string message = "Guard Close All (" + ToString(positionsCount) + ") Positions Successfully ..."; + int forceClosed = mTradeHandler.ForceClose( + positions, + comment, + message // + ); + + // + if (forceClosed) + { + RestEA(120 * 60); + } + } + } + + // + // Close Longs ... + if (canCloseLongs) + { + // + XPosition longPositions[]; + XPosition shortPositions[]; + mTrader + .GetPositions( + longPositions, // Result ... + shortPositions, // Result ... + iGuard.symbol, + iGuard.provider, + NULL, // Period ... + true // Filter by Magic ... + ); + + // + int longPositionsCount = ArraySize(longPositions); + bool hasLongPositions = IsValidSize(longPositionsCount); + + // + int shortPositionsCount = ArraySize(shortPositions); + bool hasShortPositions = IsValidSize(shortPositionsCount); + + // + if (hasLongPositions) + { + // + string comment = "Guard Close Longs ..."; + string message = "Guard Close (" + ToString(longPositionsCount) + ") Long Positions Successfully ..."; + bool isClosed = mTradeHandler.ForceClose( + longPositions, + comment, + message // + ); + + // + if (isClosed) + { + RestEA(120 * 60); + } + } + } + + // + // Close Shorts ... + if (canCloseShorts) + { + // + XPosition longPositions[]; + XPosition shortPositions[]; + mTrader + .GetPositions( + longPositions, // Result ... + shortPositions, // Result ... + iGuard.symbol, + iGuard.provider, + NULL, // Period ... + true // Filter by Magic ... + ); + + // + int longPositionsCount = ArraySize(longPositions); + bool hasLongPositions = IsValidSize(longPositionsCount); + + // + int shortPositionsCount = ArraySize(shortPositions); + bool hasShortPositions = IsValidSize(shortPositionsCount); + + // + if (hasShortPositions) + { + // + string comment = "Guard Close Shorts ..."; + string message = "Guard Close (" + ToString(shortPositionsCount) + ") Short Positions Successfully ..."; + bool isClosed = mTradeHandler.ForceClose( + shortPositions, + comment, + message // + ); + + // + if (isClosed) + { + RestEA(120 * 60); + } + } + } + + // + // Close ... + if (canClose) + { + // + XPosition iPosition; + bool hasPosition = mTrader.GetPosition( + iGuard.ticket, + iPosition // + ); + + // + bool isLong = IsLong(iPosition.type); + + // + if (hasPosition) + { + // + XPosition positions[]; + AddRef( + iPosition, + positions // + ); + + // + string comment = "Guard Close ..."; + string message = "Guard Close " + (isLong ? "Long" : "Short") + " Position: (" + ToString(iGuard.ticket) + ") Successfully ..."; + bool isClosed = mTradeHandler.ForceClose( + positions, + comment, + message // + ); + + // + if (isClosed) + { + RestEA(120 * 60); + } + } + } + + // + // Partial Close ... + if (canPartialClose) + { + // + XPosition iPosition; + bool hasPosition = mTrader.GetPosition( + iGuard.ticket, + iPosition // + ); + + // + bool isLong = IsLong(iPosition.type); + + // + if (hasPosition) + { + // + // Normalize Volume Multiplier ... + double vMult = iGuard.volumeMultiplier; + if (vMult > 0.5) + { + vMult = 0.5; + } + if (vMult < 0) + { + vMult = 0.5; + } + + // + // Calculate and Normalize Volume ... + double volume = iPosition.volume * iGuard.volumeMultiplier; + volume = NormalizeVolume( + volume, + iPosition.symbol // + ); + + // + string comment = "Guard Partially Closed: " + ToString(volume) + " ..."; + string message = "Guard Partially Closed " + (isLong ? "Long" : "Short") + ": " + ToString(volume) + " Successfully ..."; + bool isModified = mTrader.ClosePartial( + iPosition.ticket, + volume, + comment // + ); + if (isModified) + { + // + mTradeHandler.Alert(message); + + // + if (volume == iPosition.volume) + { + // + mTradeHandler.Finish( + iPosition.ticket, + iPosition, + comment // + ); + + // + RestEA(120 * 60); + } + } + } + } + + // + // Hedge ... + if (canHedge) + { + // + XPosition positions[]; + int positionsCount = + mTrader + .GetPositions( + positions, // Result ... + iGuard.symbol, + iGuard.provider, + NULL, // Period ... + X_POSITION_TYPE_ALL, // All Types ... + true // Filter by Magic ... + ); + if (IsValidSize(positionsCount)) + { + // + int longs = 0; + double longProfits = 0; + double longVolumes = 0; + + // + int shorts = 0; + double shortProfits = 0; + double shortVolumes = 0; + CountPositions( + positions, + longs, + longProfits, + longVolumes, + shorts, + shortProfits, + shortVolumes // + ); + + // + int count = longs + shorts; + double profits = longProfits + shortProfits; + double volumes = longVolumes + shortVolumes; + + // + bool canDoHedge = + count > 0 && + profits > 0 && + volumes > 0; + if (canDoHedge) + { + // + string comment = "Guard Hedge ..."; + string message = "Guard Hedge (" + ToString(count) + ") Positions by: (" + ToString(profits) + ") Successfully ..."; + bool isClosed = mTradeHandler.ForceClose( + positions, + comment, + message // + ); + + // + if (isClosed) + { + RestEA(120 * 60); + } + } + } + } + + // + // Trail Stop ... + if (canTrailStop) + { + // + XPosition iPosition; + bool hasPosition = mTrader.GetPosition( + iGuard.ticket, + iPosition // + ); + + // + bool isLong = IsLong(iPosition.type); + + // + bool canDoTrail = + hasPosition && + iPosition.profit > 0 && + isLong + ? iPosition.price > iGuard.sl && + (iPosition.sl == 0 || + iPosition.sl < iGuard.sl) + : iPosition.price < iGuard.sl && + (iPosition.sl == 0 || + iPosition.sl > iGuard.sl); + if (canDoTrail) + { + // + string comment = "Guard Trail Stop ..."; + string message = "Guard Trail " + (isLong ? "Long" : "Short") + " Position: (" + ToString(iGuard.ticket) + ") Stop Successfully ..."; + bool isModified = mTrader.Modify( + iPosition.ticket, + iGuard.sl, + iPosition.tp, + comment // + ); + if (isModified) + { + mTradeHandler.Alert(message); + } + } + } + + // + // Trail Target ... + if (canTrailTarget) + { + // + XPosition iPosition; + bool hasPosition = mTrader.GetPosition( + iGuard.ticket, + iPosition // + ); + + // + bool isLong = IsLong(iPosition.type); + + // + bool canDoTrail = + hasPosition && + iGuard.tp != iPosition.tp && + isLong + ? iGuard.tp > iPosition.price + : iGuard.tp < iPosition.price; + if (canDoTrail) + { + // + string comment = "Guard Trail Target ..."; + string message = "Guard Trail " + (isLong ? "Long" : "Short") + " Position: (" + ToString(iGuard.ticket) + ") Target Successfully ..."; + bool isModified = mTrader.Modify( + iPosition.ticket, + iPosition.sl, + iGuard.tp, + comment // + ); + if (isModified) + { + mTradeHandler.Alert(message); + } + } + } + } + + // + Clean(guards); + Clean(guards); + } + + // + void RestEA(int seconds) + { + // + } + + // +}; + +// \ No newline at end of file diff --git a/BKPS/14040203/X121SMCEA/Libraries/x-121.smc.guard.lib.mq5 b/BKPS/14040203/X121SMCEA/Libraries/x-121.smc.guard.lib.mq5 new file mode 100644 index 0000000..864501d --- /dev/null +++ b/BKPS/14040203/X121SMCEA/Libraries/x-121.smc.guard.lib.mq5 @@ -0,0 +1,970 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 X121 SMC Signal Class +// ------------------------------------------------- +// Name: +// Description: provide all Global Guarding functions ... +// +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +////////////////////////////////////////////////////// +// +// Global Properties ... +#property library +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://www.saherelm.ir" +#property version "1.00" +#property strict + +// +// Imports ... +#include "../Classes/x-121.smc.market.cycle.helper.class.mq5" +#include "../Libraries/x-121.smc.lib.mq5" + +// +bool DetectX121SMCGuards( + // + string signalProvider, // Provider ... + X121SMCGuard &guards[], + const XPosition &positions[], + X121SMCStrategySignalProviderData &provider, + // + // Guard Types ... + ENUM_X_121_SMC_GUARD_ACTIONS &ignoreGuards[], + // + // Required Configurations ... + double breakEvenTPLevel = 2.0 + // +) +{ + // + bool result = false; + + // // + // bool isCycleHelpersValid = + // // + // visionCycleHelper != NULL && + // analyseCycleHelper != NULL && + // decisionCycleHelper != NULL && + // consolidationCycleHelper != NULL + // // + // ; + + // // + // // Ignore Guards ... + // bool hasIgnoreGuards = HasChild(ignoreGuards); + // bool isColseIgnored = + // hasIgnoreGuards && + // Contains( + // X_121_SMC_GUARD_ACTION_CLOSE, + // ignoreGuards // + // ); + // bool isColseAllIgnored = + // hasIgnoreGuards && + // Contains( + // X_121_SMC_GUARD_ACTION_CLOSE_ALL, + // ignoreGuards // + // ); + // bool isColseLongsIgnored = + // hasIgnoreGuards && + // Contains( + // X_121_SMC_GUARD_ACTION_CLOSE_LONGS, + // ignoreGuards // + // ); + // bool isColseShortsIgnored = + // hasIgnoreGuards && + // Contains( + // X_121_SMC_GUARD_ACTION_CLOSE_SHORTS, + // ignoreGuards // + // ); + // bool isPartialColseIgnored = + // hasIgnoreGuards && + // Contains( + // X_121_SMC_GUARD_ACTION_PARTIAL_CLOSE, + // ignoreGuards // + // ); + // bool isTrailStopIgnored = + // hasIgnoreGuards && + // Contains( + // X_121_SMC_GUARD_ACTION_TRAIL_STOP, + // ignoreGuards // + // ); + // bool isTrailTargetIgnored = + // hasIgnoreGuards && + // Contains( + // X_121_SMC_GUARD_ACTION_TRAIL_TARGET, + // ignoreGuards // + // ); + // bool isHedgeIgnored = + // hasIgnoreGuards && + // Contains( + // X_121_SMC_GUARD_ACTION_HEDGE, + // ignoreGuards // + // ); + + // // + // bool isAllIgnores = + // // + // isColseIgnored && + // isHedgeIgnored && + // isColseAllIgnored && + // isTrailStopIgnored && + // isColseLongsIgnored && + // isColseShortsIgnored && + // isTrailTargetIgnored && + // isPartialColseIgnored + // // + // ; + // result = !isAllIgnores && + // isCycleHelpersValid; + // if (!result) + // { + // return result; + // } + + // // + // int count = ArraySize(positions); + // result = IsValidSize(count); + // if (!result) + // { + // return result; + // } + + // // + // string symbol = decisionCycleHelper.GetSymbol(); + // ENUM_TIMEFRAMES period = decisionCycleHelper.GetPeriod(); + + // // + // XPosition ownPositions[]; + // XPosition ownLongPositions[]; + // XPosition ownShortPositions[]; + // for (int i = 0; i < count; i++) + // { + // // + // XPosition iPosition = positions[i]; + // bool isOwn = iPosition + // .IsFiltersPassed( + // symbol, + // provider, + // NULL, + // X_POSITION_TYPE_ALL, + // iPosition.magic // + // ); + // if (isOwn) + // { + // // + // AddRef( + // iPosition, + // ownPositions // + // ); + + // // + // bool isLong = IsLong(positions[i].type); + // if (isLong) + // { + // // + // AddRef( + // iPosition, + // ownLongPositions // + // ); + // } + // else + // { + // // + // AddRef( + // iPosition, + // ownShortPositions // + // ); + // } + // } + // } + + // // + // count = ArraySize(ownPositions); + + // // + // int longsCount = ArraySize(ownLongPositions); + // bool hasLongs = IsValidSize(longsCount); + + // // + // int shortsCount = ArraySize(ownShortPositions); + // bool hasShorts = IsValidSize(shortsCount); + + // // + // result = IsValidSize(count); + // if (!result) + // { + // // + // Clean(ownPositions); + // Clean(ownLongPositions); + // Clean(ownShortPositions); + + // // + // return result; + // } + + // // + // // Here we Are Sure there is Positions to Guard ... + // // based on Current Provider ... + + // // + // // Detect Required Data for Analyse Market to Guard Positions ... + + // // + // int zIndex = 0; + // int cIndex = zIndex + 1; + // int pIndex = cIndex + 1; + // int ppIndex = pIndex + 1; + + // // + // int loopback = 10; + + // // + // XOHCL zBar; + // result = zBar.Init( + // symbol, + // period, + // zIndex // + // ); + // if (!result) + // { + // // + // zBar.Clean(); + // result = HasChild(guards); + // return result; + // } + + // // + // XOHCL cBar; + // result = cBar.Init( + // symbol, + // period, + // cIndex // + // ); + // if (!result) + // { + // // + // zBar.Clean(); + // cBar.Clean(); + // result = HasChild(guards); + // return result; + // } + + // // + // XOHCL pBar; + // result = pBar.Init( + // symbol, + // period, + // pIndex // + // ); + // if (!result) + // { + // // + // zBar.Clean(); + // cBar.Clean(); + // pBar.Clean(); + // result = HasChild(guards); + // return result; + // } + + // // + // XOHCL ppBar; + // result = ppBar.Init( + // symbol, + // period, + // ppIndex // + // ); + // if (!result) + // { + // // + // zBar.Clean(); + // cBar.Clean(); + // pBar.Clean(); + // ppBar.Clean(); + // result = HasChild(guards); + // return result; + // } + + // // + // double ask = GetAsk(symbol); + // double bid = GetBid(symbol); + // datetime cTime = TimeCurrent(); + // double points = GetPoints(symbol); + + // // + + // // + // // Cycles Conditions ... + + // // + // // Decision ... + // ENUM_XPOI_EVENTS decisionPoiEvents[]; + // ENUM_X_CYCLE_EVENTS decisionCycleEvents[]; + // X121SMCCycleConditions decisionConditions; + // result = decisionCycleHelper.GetConditions( + // decisionCycleEvents, + // decisionPoiEvents, + // decisionConditions, + // zIndex, + // loopback // + // ); + // if (!result) + // { + // // + // zBar.Clean(); + // cBar.Clean(); + // pBar.Clean(); + // ppBar.Clean(); + // result = HasChild(guards); + + // // + // Clean(decisionPoiEvents); + // Clean(decisionCycleEvents); + + // // + // decisionConditions.Clean(); + // return result; + // } + + // // + // // Analyse ... + // ENUM_XPOI_EVENTS analysePoiEvents[]; + // ENUM_X_CYCLE_EVENTS analyseCycleEvents[]; + // X121SMCCycleConditions analyseConditions; + // result = analyseCycleHelper.GetConditions( + // analyseCycleEvents, + // analysePoiEvents, + // analyseConditions, + // zIndex, + // loopback // + // ); + // if (!result) + // { + // // + // zBar.Clean(); + // cBar.Clean(); + // pBar.Clean(); + // ppBar.Clean(); + + // // + // Clean(decisionPoiEvents); + // Clean(decisionCycleEvents); + + // // + // decisionConditions.Clean(); + + // // + // Clean(analysePoiEvents); + // Clean(analyseCycleEvents); + + // // + // analyseConditions.Clean(); + + // // + // result = HasChild(guards); + // return result; + // } + + // // + // // Consolidation ... + // ENUM_XPOI_EVENTS consolidationPoiEvents[]; + // ENUM_X_CYCLE_EVENTS consolidationCycleEvents[]; + // X121SMCCycleConditions consolidationConditions; + // result = consolidationCycleHelper.GetConditions( + // consolidationCycleEvents, + // consolidationPoiEvents, + // consolidationConditions, + // zIndex, + // loopback // + // ); + // if (!result) + // { + // // + // zBar.Clean(); + // cBar.Clean(); + // pBar.Clean(); + // ppBar.Clean(); + + // // + // Clean(decisionPoiEvents); + // Clean(decisionCycleEvents); + + // // + // decisionConditions.Clean(); + + // // + // Clean(analysePoiEvents); + // Clean(analyseCycleEvents); + + // // + // analyseConditions.Clean(); + + // // + // Clean(consolidationPoiEvents); + // Clean(consolidationCycleEvents); + + // // + // consolidationConditions.Clean(); + + // // + // result = HasChild(guards); + // return result; + // } + + // // + // // Vision ... + // ENUM_XPOI_EVENTS visionPoiEvents[]; + // ENUM_X_CYCLE_EVENTS visionCycleEvents[]; + // X121SMCCycleConditions visionConditions; + // result = visionCycleHelper.GetConditions( + // visionCycleEvents, + // visionPoiEvents, + // visionConditions, + // zIndex, + // loopback // + // ); + // if (!result) + // { + // // + // zBar.Clean(); + // cBar.Clean(); + // pBar.Clean(); + // ppBar.Clean(); + + // // + // Clean(decisionPoiEvents); + // Clean(decisionCycleEvents); + + // // + // decisionConditions.Clean(); + + // // + // Clean(analysePoiEvents); + // Clean(analyseCycleEvents); + + // // + // analyseConditions.Clean(); + + // // + // Clean(consolidationPoiEvents); + // Clean(consolidationCycleEvents); + + // // + // consolidationConditions.Clean(); + + // // + // Clean(visionPoiEvents); + // Clean(visionCycleEvents); + + // // + // visionConditions.Clean(); + + // // + // result = HasChild(guards); + // return result; + // } + + // // + // // Cycles POI States ... + // XPOIState decisionState = decisionConditions.state; + // XPOIState analyseState = analyseConditions.state; + // XPOIState consolidationState = consolidationConditions.state; + // XPOIState visionState = visionConditions.state; + + // // + // // Cycle X121Conditions ... + // X121Conditions decisionXConditions = decisionConditions.x121Conditions; + // X121Conditions analyseXConditions = analyseConditions.x121Conditions; + // X121Conditions consolidationXConditions = consolidationConditions.x121Conditions; + // X121Conditions visionXConditions = visionConditions.x121Conditions; + + // // + // // + // // + + // // // + // // // Detect Consolidation Zone ... + + // // // + // // // Detect Consolidation Zones ... + + // // // + // // XBoxZone lastBullishBox; + // // XBoxZone prevLastBullishBox; + // // bool hasLastBullishBox = false; + // // bool hasPrevLastBullishBox = false; + // // XConsolidationZone lastBullishZone; + // // bool isLastBullishAbovePrev = false; + // // bool isLastBullishBelowPrev = false; + // // XConsolidationZone prevLastBullishZone; + + // // // + // // XBoxZone lastBearishBox; + // // XBoxZone prevLastBearishBox; + // // bool hasLastBearishBox = false; + // // bool hasPrevLastBearishBox = false; + // // XConsolidationZone lastBearishZone; + // // bool isLastBearishAbovePrev = false; + // // bool isLastBearishBelowPrev = false; + // // XConsolidationZone prevLastBearishZone; + + // // // + // // int bullishConsolidationZonesCount = 0; + // // int bearishConsolidationZonesCount = 0; + // // bool hasBullishConsolidationZones = false; + // // bool hasBearishConsolidationZones = false; + // // XConsolidationZone bullishConsolidationZones[]; + // // XConsolidationZone bearishConsolidationZones[]; + // // bool hasConsolidationZones = decisionCycleHelper.HasConsolidationZones(); + // // int consolidationZonesCount = decisionCycleHelper.CountConsolidationZones(); + // // if (hasConsolidationZones) + // // { + // // // + // // bullishConsolidationZonesCount = decisionCycleHelper + // // .FillConsolidationZones( + // // X_DIRECTION_BULLISH, + // // bullishConsolidationZones // + // // ); + // // hasBullishConsolidationZones = IsValidSize(bullishConsolidationZonesCount); + + // // // + // // bearishConsolidationZonesCount = decisionCycleHelper + // // .FillConsolidationZones( + // // X_DIRECTION_BEARISH, + // // bearishConsolidationZones // + // // ); + // // hasBearishConsolidationZones = IsValidSize(bearishConsolidationZonesCount); + + // // // + // // // + // // // + + // // // + // // if (hasBullishConsolidationZones && + // // bullishConsolidationZonesCount >= 2) + // // { + // // // + // // lastBullishZone = bullishConsolidationZones[bullishConsolidationZonesCount - 1]; + // // prevLastBullishZone = bullishConsolidationZones[bullishConsolidationZonesCount - 2]; + + // // // + // // hasLastBullishBox = ToBox( + // // lastBullishBox, + // // lastBullishZone // + // // ); + // // hasPrevLastBullishBox = ToBox( + // // prevLastBullishBox, + // // prevLastBullishZone // + // // ); + + // // // + // // isLastBullishAbovePrev = hasLastBullishBox && + // // hasPrevLastBullishBox && + // // IsBoxAbove( + // // lastBullishBox, + // // prevLastBullishBox // + // // ); + + // // // + // // isLastBullishBelowPrev = hasLastBullishBox && + // // hasPrevLastBullishBox && + // // IsBoxBelow( + // // lastBullishBox, + // // prevLastBullishBox // + // // ); + // // } + + // // // + // // if (hasBearishConsolidationZones && + // // bearishConsolidationZonesCount >= 2) + // // { + // // // + // // lastBearishZone = bearishConsolidationZones[bearishConsolidationZonesCount - 1]; + // // prevLastBearishZone = bearishConsolidationZones[bearishConsolidationZonesCount - 2]; + + // // // + // // hasLastBearishBox = ToBox( + // // lastBearishBox, + // // lastBearishZone // + // // ); + // // hasPrevLastBearishBox = ToBox( + // // prevLastBearishBox, + // // prevLastBearishZone // + // // ); + + // // // + // // isLastBearishAbovePrev = hasLastBearishBox && + // // hasPrevLastBearishBox && + // // IsBoxAbove( + // // lastBearishBox, + // // prevLastBearishBox // + // // ); + + // // // + // // isLastBearishBelowPrev = hasLastBearishBox && + // // hasPrevLastBearishBox && + // // IsBoxBelow( + // // lastBearishBox, + // // prevLastBearishBox // + // // ); + // // } + + // // // + // // } + + // // + // // Detect High Probability Swings ... + // // bool isSwingLow = + // // // + // // cBar.low > pBar.low && + // // ppBar.low > pBar.low && + // // // + // // zBar.low > pBar.low + // // // + // // ; + // // bool isSwingHigh = + // // // + // // cBar.high < pBar.high && + // // ppBar.high < pBar.high && + // // // + // // zBar.high < pBar.high + // // // + // // ; + // // bool isStrongSwingLow = + // // pBar.IsBullish() && + // // pBar.GetLowShadow() >= pBar.GetBody() * 2; + // // bool isStrongSwingHigh = + // // pBar.IsBearish() && + // // pBar.GetHighShadow() >= pBar.GetBody() * 2; + + // // // + // // bool isStrongSwingLowAboveLastBullishBox = + // // isStrongSwingLow && + // // hasLastBullishBox && + // // pBar.low > lastBullishBox.upper; + + // // // + // // bool isStrongSwingHighBelowLastBearishBox = + // // isStrongSwingHigh && + // // hasLastBearishBox && + // // pBar.high < lastBearishBox.lower; + + // // + // // Here We Have all Requirements for Guarding Positions ... + + // // + // // Available Guards: + // // X_121_SMC_GUARD_ACTION_NONE + // // X_121_SMC_GUARD_ACTION_CLOSE + // // X_121_SMC_GUARD_ACTION_CLOSE_ALL + // // X_121_SMC_GUARD_ACTION_CLOSE_LONGS + // // X_121_SMC_GUARD_ACTION_CLOSE_SHORTS + // // X_121_SMC_GUARD_ACTION_PARTIAL_CLOSE + // // X_121_SMC_GUARD_ACTION_TRAIL_STOP + // // X_121_SMC_GUARD_ACTION_TRAIL_TARGET + // // X_121_SMC_GUARD_ACTION_HEDGE + + // // + // // X_121_SMC_GUARD_ACTION_CLOSE: + // // Close Specified Position on Specified Conditions ... + // if (!isColseIgnored) + // { + // // + // // TODO: + // // - [] Implement Close on Nearest on TP ... + // } + + // // + // // X_121_SMC_GUARD_ACTION_CLOSE_ALL: + // // Close All Positions on Specified Conditions ... + // if (!isColseAllIgnored) + // { + // // + // // TODO: + // // - [] Implement Close All Positions on Weekend ... + // } + + // // + // // X_121_SMC_GUARD_ACTION_CLOSE_LONGS: + // // Close All Long Positions on Specified Conditions ... + // if (!isColseLongsIgnored) + // { + // // + // } + + // // + // // X_121_SMC_GUARD_ACTION_CLOSE_SHORTS: + // // Close All Short Positions on Specified Conditions ... + // if (!isColseShortsIgnored) + // { + // // + // } + + // // + // // X_121_SMC_GUARD_ACTION_PARTIAL_CLOSE: + // // Partial Close Specified Position on Specified Conditions ... + // if (!isPartialColseIgnored) + // { + // // + // // Breake Even ... + // // Usually Break Even Works on TP2 Reached ... + // // when tp reached to required Level, we Close 50% of Entered Volume ... + // bool canBreakEven = breakEvenTPLevel >= 0; + + // // + // for (int i = 0; i < count; i++) + // { + // // + // XPosition iPosition = ownPositions[i]; + + // // + // bool isInProfit = iPosition.profit > 0; + + // // + // double reachedTPLevel = 0; + // double reachedTPPrice = 0; + // if (isInProfit) + // { + // // + // iPosition.CalculateReahedTP( + // reachedTPLevel, + // reachedTPPrice // + // ); + // } + + // // + // // Break Event ... + // if (canBreakEven) + // { + // // + // // Position Must be In Profit ... + // if (!isInProfit) + // { + // continue; + // } + + // // + // bool canDoBreakEven = reachedTPLevel == breakEvenTPLevel && + // reachedTPPrice > 0; + // if (canDoBreakEven) + // { + // // + // X121SMCGuard iGuard; + + // // + // iGuard.time = cTime; + // iGuard.symbol = symbol; + // iGuard.provider = provider; + // iGuard.action = X_121_SMC_GUARD_ACTION_PARTIAL_CLOSE; + + // // + // iGuard.ticket = iPosition.ticket; + + // // + // iGuard.volumeMultiplier = 0.5; + + // // + // AddGuard( + // iGuard, + // guards // + // ); + // } + // } + // } + // } + + // // + // // X_121_SMC_GUARD_ACTION_TRAIL_STOP: + // // Trail Stop Specified Position on Specified Conditions ... + // if (!isTrailStopIgnored) + // { + // // + // for (int i = 0; i < count; i++) + // { + // // + // XPosition iPosition = ownPositions[i]; + + // // + // bool isLong = IsLong(iPosition.type); + // bool isInProfit = iPosition.profit > 0; + + // // + // double reachedTPLevel = 0; + // double reachedTPPrice = 0; + // if (isInProfit) + // { + // // + // iPosition.CalculateReahedTP( + // reachedTPLevel, + // reachedTPPrice // + // ); + // } + + // // + // // Trai Stop ... + // if (!isInProfit) + // { + // continue; + // } + + // // + // double trailedStop = 0; + + // // + // // Trail Stop Senarios ... + // // - occures two same type consolidation zones in order of positions type; + // // - occures a swing in order of consolidation zones ... + + // // // + // // bool canTrailBasedOnTwoZone = + // // isLong + // // ? isLastBullishAbovePrev + // // : isLastBearishBelowPrev; + // // if (canTrailBasedOnTwoZone) + // // { + // // // + // // trailedStop = + // // isLong + // // ? prevLastBullishBox.lower + // // : prevLastBearishBox.upper; + // // } + + // // // + // // bool canTrailBasedOnZoneSwing = + // // trailedStop <= 0 && + // // (isLong + // // ? isStrongSwingLowAboveLastBullishBox + // // : isStrongSwingHighBelowLastBearishBox); + // // if (canTrailBasedOnZoneSwing) + // // { + // // // + // // trailedStop = + // // isLong + // // ? pBar.low + // // : pBar.high; + // // } + + // // // + // // bool canDoTrailStop = + // // trailedStop > 0 && + // // ( + // // // + // // iPosition.sl == 0 + // // ? (isLong + // // ? trailedStop > iPosition.entry && + // // trailedStop < iPosition.price + // // : trailedStop < iPosition.entry && + // // trailedStop > iPosition.price) + // // : (isLong + // // ? trailedStop > iPosition.sl && + // // trailedStop > iPosition.entry && + // // trailedStop < iPosition.price + // // : trailedStop < iPosition.sl && + // // trailedStop < iPosition.entry && + // // trailedStop > iPosition.price) + // // // + // // ) + // // // + // // ; + + // // // + // // if (canDoTrailStop) + // // { + // // // + // // X121SMCGuard iGuard; + + // // // + // // iGuard.time = cTime; + // // iGuard.symbol = symbol; + // // iGuard.provider = provider; + // // iGuard.action = X_121_SMC_GUARD_ACTION_TRAIL_STOP; + + // // // + // // iGuard.ticket = iPosition.ticket; + + // // // + // // iGuard.sl = trailedStop; + + // // // + // // AddGuard( + // // iGuard, + // // guards // + // // ); + // // } + // } + // } + + // // + // // X_121_SMC_GUARD_ACTION_TRAIL_TARGET: + // // Trail Target Specified Position on Specified Conditions ... + // if (!isTrailTargetIgnored) + // { + // // + // } + + // // + // // X_121_SMC_GUARD_ACTION_HEDGE: + // // Hedge all Positions on Specified Conditions ... + // if (!isHedgeIgnored) + // { + // // + // } + + // // + // // Cleanup Collections ... + + // // + // Clean(ownPositions); + // Clean(ownLongPositions); + // Clean(ownShortPositions); + + // // + // zBar.Clean(); + // cBar.Clean(); + // pBar.Clean(); + // ppBar.Clean(); + + // // + // Clean(visionPoiEvents); + // Clean(analysePoiEvents); + // Clean(visionCycleEvents); + // Clean(decisionPoiEvents); + // Clean(analyseCycleEvents); + // Clean(decisionCycleEvents); + // Clean(consolidationPoiEvents); + // Clean(consolidationCycleEvents); + + // // + // visionState.Clean(); + // analyseState.Clean(); + // decisionState.Clean(); + // visionConditions.Clean(); + // analyseConditions.Clean(); + // visionXConditions.Clean(); + // decisionConditions.Clean(); + // consolidationState.Clean(); + // analyseXConditions.Clean(); + // decisionXConditions.Clean(); + // consolidationConditions.Clean(); + // consolidationXConditions.Clean(); + + // // + // // lastBullishBox.Clean(); + // // lastBearishBox.Clean(); + // // lastBullishZone.Clean(); + // // lastBearishZone.Clean(); + // // prevLastBullishBox.Clean(); + // // prevLastBearishBox.Clean(); + // // prevLastBullishZone.Clean(); + // // prevLastBearishZone.Clean(); + + // // + // count = ArraySize(guards); + // result = IsValidSize(count); + + // + return result; +} diff --git a/BKPS/14040203/X121SMCEA/Libraries/x-121.smc.lib.mq5 b/BKPS/14040203/X121SMCEA/Libraries/x-121.smc.lib.mq5 new file mode 100644 index 0000000..ec449b4 --- /dev/null +++ b/BKPS/14040203/X121SMCEA/Libraries/x-121.smc.lib.mq5 @@ -0,0 +1,748 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Common Library +// -------------------------------------- +// Name: X121SMCLib +// Description: provide all commonly used functions ... +// +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +////////////////////////////////////////////////////// +// +// Global Properties ... +#property library +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://www.saherelm.ir" +#property version "1.00" +#property strict + +// +// Imports ... +#include "../../Classes/x-saherelm.base.class.mq5" +#include "../../Classes/x-saherelm.x-poi.drawer.class.mq5" +#include "../../Helpers/x-saherelm.x121.helper.mq5" +#include "../../Libraries/x-saherelm.common.lib.mq5" +#include "../../Libraries/x-saherelm.x-poi.extensions.lib.mq5" +#include "../../Libraries/x-saherelm.x-poi.lib.mq5" +#include "../../Libraries/x-saherelm.x-trade.lib.mq5" + +// +// Definitions ... + +// +const string X121SMCStrategyToken = "X121SMC"; + +// +const string X121SMCXWZToken = "X121XWZ"; +const string X121SMCXICHToken = "X121XICH"; + +// +// X121 SMC Providers ... +enum ENUM_X_121_SMC_PROVIDERS +{ + // + X_121_SMC_PROVIDER_NONE, + X_121_SMC_PROVIDER_XWZ, + X_121_SMC_PROVIDER_XICH, +}; + +// +// Guard Actions ... +enum ENUM_X_121_SMC_GUARD_ACTIONS +{ + X_121_SMC_GUARD_ACTION_NONE, // Nothing to Do + X_121_SMC_GUARD_ACTION_CLOSE, // Close Specified Position + X_121_SMC_GUARD_ACTION_CLOSE_ALL, // Close All Positions + X_121_SMC_GUARD_ACTION_CLOSE_LONGS, // Close All Long Positions + X_121_SMC_GUARD_ACTION_CLOSE_SHORTS, // Close All Short Position + X_121_SMC_GUARD_ACTION_PARTIAL_CLOSE, // Partial Close Specified Position + X_121_SMC_GUARD_ACTION_TRAIL_STOP, // Trail Stop of Specified Position + X_121_SMC_GUARD_ACTION_TRAIL_TARGET, // Trail Target of Specified Position + X_121_SMC_GUARD_ACTION_HEDGE, // Hedge Specified Positions +}; + +// +// Each Market Cycle (Time Frame) Conditions +// Model as this Structure ... +struct X121SMCCycleConditions +{ + // + string symbol; + ENUM_TIMEFRAMES period; + datetime time; + + // + XPOIState state; + X121Conditions x121Conditions; + + // + void X121SMCStrategyConditions() + { + Clean(); + } + + // + // Tools ... + + /** + * Cleanup ... + */ + void Clean() + { + // + symbol = NULL; + period = NULL; + time = NULL; + + // + state.Clean(); + x121Conditions.Clean(); + + // + ZeroMemory(this); + } + + /** + * Validate ... + * + * @return ( bool ) + */ + bool IsValid() + { + // + bool result = false; + + // + result = IsSpecifiedValid(symbol) && + IsSpecifiedValid(period) && + IsSpecifiedValid(time); + // + ; + + // + return result; + } + + // + // Reporter Functions ... + + /** + * Generate Provided Scores ... + * + * @param bullishScore: Integer, reference ... + * @param bearishScore: Integer, referenceF ... + */ + void GenerateScore( + double &bullishScore, + double &bearishScore // + ) + { + // + bullishScore = 0; + bearishScore = 0; + + // + if (!IsValid()) + { + return; + } + + // + double bullScore = 0; + double bearScore = 0; + } + + /** + * Generate Summary ... + * + * @param onlyCommons: Boolean ... + * @param onlyConditions: Boolean ... + * @param includeScores: Boolean ... + * @param ignoreFalseConditions: Boolean ... + * @param separator: String ... + * + * @return ( string ) + */ + string GenerateSummary( + bool onlyCommons = false, + bool onlyConditions = false, + bool includeScores = true, + bool ignoreFalseConditions = true, + string separator = "\n" // + ) + { + // + string result = NULL; + + // + double bullishScore = 0; + double bearishScore = 0; + GenerateScore( + bullishScore, + bearishScore // + ); + + // + string commonStr = GenerateSpecifiedCommonSummary( + this, + separator, + includeScores, + true // + ); + + // + string conditionsStr = + // + "" + // + ; + + // + result = + // + "[" + GetTag() + "]" + separator + + "----------" + separator + + (onlyConditions + ? "" + : commonStr) + + " " + separator + + (onlyCommons + ? "" + : conditionsStr) + + "" + // + ; + + // + return result; + } + + /** + * Get Unique Identifier ... + * + * @param forObject: Boolean ... + * + * @return ( string ) + */ + string GetTag( + bool forObject = false // + ) + { + // + string result = NULL; + + // + string typeName = GetTypeName(this); + + // + if (!forObject) + { + result = typeName; + } + else + { + // + result = typeName + "_" + + symbol + "_" + ToString(period) + "_" + + ToMD5(time); + } + + // + return result; + } + + // +}; + +// +// Model Signalling Conditions ... +struct X121SMCStrategyConditions +{ + // + string symbol; + ENUM_TIMEFRAMES period; + datetime time; + + // + double sl; + double tp; + string provider; + double targets[]; + ENUM_X_DIRECTION signalDir; + + // + void X121SMCStrategyConditions() + { + Clean(); + } + + // + // Tools ... + + /** + * Cleanup ... + */ + void Clean() + { + // + time = NULL; + symbol = NULL; + period = NULL; + + // + sl = 0; + tp = 0; + provider = NULL; + signalDir = X_DIRECTION_NONE; + + // + Clean(targets); + + // + ZeroMemory(this); + } + + /** + * Validate ... + * + * @return ( bool ) + */ + bool IsValid() + { + // + bool result = false; + + // + result = IsSpecifiedValid(symbol) && + IsSpecifiedValid(period) && + IsSpecifiedValid(time); + + // + return result; + } + + /** + * Check Conditions Has Valid Bullish Signal ... + * + * @return ( bool ) + */ + bool HasBullishSignal() + { + // + bool result = false; + + // + result = + (sl > 0 || + tp > 0) && + IsValid() && + HasDirection(signalDir); + if (!result) + { + return result; + } + + // + result = + IsBullish(signalDir); + + // + return result; + } + + /** + * Check Conditions Has Valid Bearish Signal ... + * + * @return ( bool ) + */ + bool HasBearishSignal() + { + // + bool result = false; + + // + result = + (sl > 0 || + tp > 0) && + IsValid() && + HasDirection(signalDir); + if (!result) + { + return result; + } + + // + result = + IsBearish(signalDir); + + // + return result; + } + + // + // Reporter Functions ... + + /** + * Generate Provided Scores ... + * + * @param bullishScore: Integer, reference ... + * @param bearishScore: Integer, referenceF ... + */ + void GenerateScore( + double &bullishScore, + double &bearishScore // + ) + { + // + bullishScore = 0; + bearishScore = 0; + + // + if (!IsValid()) + { + return; + } + + // + double bullScore = 0; + double bearScore = 0; + } + + /** + * Generate Summary ... + * + * @param onlyCommons: Boolean ... + * @param onlyConditions: Boolean ... + * @param includeScores: Boolean ... + * @param ignoreFalseConditions: Boolean ... + * @param separator: String ... + * + * @return ( string ) + */ + string GenerateSummary( + bool onlyCommons = false, + bool onlyConditions = false, + bool includeScores = true, + bool ignoreFalseConditions = true, + string separator = "\n" // + ) + { + // + string result = NULL; + + // + double bullishScore = 0; + double bearishScore = 0; + GenerateScore( + bullishScore, + bearishScore // + ); + + // + string commonStr = GenerateSpecifiedCommonSummary( + this, + separator, + includeScores, + true // + ); + + // + string conditionsStr = + // + "" + // + ; + + // + result = + // + "[" + GetTag() + "]" + separator + + "----------" + separator + + (onlyConditions + ? "" + : commonStr) + + " " + separator + + (onlyCommons + ? "" + : conditionsStr) + + "" + // + ; + + // + return result; + } + + /** + * Get Unique Identifier ... + * + * @param forObject: Boolean ... + * + * @return ( string ) + */ + string GetTag( + bool forObject = false // + ) + { + // + string result = NULL; + + // + string typeName = GetTypeName(this); + + // + if (!forObject) + { + result = typeName; + } + else + { + // + result = typeName + "_" + + symbol + "_" + ToString(period) + "_" + + ToMD5(time); + } + + // + return result; + } + + // +}; + +// +// Model a Guard Action ... +struct X121SMCGuard +{ + // + // Props ... + ENUM_X_121_SMC_GUARD_ACTIONS action; + datetime time; + + // + string symbol; + string provider; + + // + // Specified Position ... + ulong ticket; + + // + // Partial Close ... + double volumeMultiplier; + + // + // SL Trial ... + double sl; + + // + // TP Trial ... + double tp; + + // + // Constructor ... + X121SMCGuard() + { + Clean(); + } + + // + // Tools ... + + /** + * Cleanup ... + */ + void Clean() + { + // + time = NULL; + action = X_121_SMC_GUARD_ACTION_NONE; + + // + symbol = NULL; + provider = NULL; + + // + ticket = 0; + + // + volumeMultiplier = 0; + + // + sl = 0; + tp = 0; + + // + ZeroMemory(this); + } + + /** + * Validate ... + * + * @return ( bool ) + */ + bool IsValid() + { + // + bool result = false; + + // + result = + // + IsValid(time) && + IsValid(symbol) && + IsValid(provider) && + action != X_121_SMC_GUARD_ACTION_NONE + // + ; + if (!result) + { + return result; + } + + // + // Validate Model Based On Specified Guard Actions ... + + // + return result; + } +}; + +/** + * Add Guard to Collection ... + * + * @param guard: X121SMCGuard instance ... + * @param guards: X121SMCGuard instance Collection ... + * + * @return ( int ) + */ +int AddGuard( + X121SMCGuard &guard, + X121SMCGuard &guards[] // +) +{ + // + int result = 0; + + // + if (!guard.IsValid()) + { + return result; + } + + // + AddRef( + guard, + guards // + ); + + // + result = ArraySize(guards); + + // + return result; +} + +// +// +// + +typedef void (*TOnX121SMCSignal)( + XSignal &signal, + X121SMCStrategyConditions &conditions // +); + +// +// Extentions ... + +/** + * Validate a Signal Provider ... + * + * @param value: ENUM_X_121_SMC_PROVIDERS member ... + * + * @return ( bool ) + */ +bool IsValid(ENUM_X_121_SMC_PROVIDERS value) +{ + // + bool result = false; + + // + result = value != X_121_SMC_PROVIDER_NONE; + + // + return result; +} + +/** + * Converts a Signal Provider to String ... + * + * @param value: ENUM_X_121_SMC_PROVIDERS member ... + * + * @return ( string ) + */ +string ToString(ENUM_X_121_SMC_PROVIDERS value) +{ + // + string result = NULL; + + // + if (!IsValid(value)) + { + return result; + } + + // + switch (value) + { + // + case X_121_SMC_PROVIDER_XWZ: + result = X121SMCXWZToken; + break; + + // + case X_121_SMC_PROVIDER_XICH: + result = X121SMCXICHToken; + break; + } + + // + return result; +} + +/** + * Parse Specified String as a Signal Provider ... + * + * @param value: String ... + * + * @return ( ENUM_X_121_SMC_PROVIDERS ) + */ +ENUM_X_121_SMC_PROVIDERS ParseProvider(string value) +{ + // + ENUM_X_121_SMC_PROVIDERS result = X_121_SMC_PROVIDER_NONE; + + // + if (!IsValid(value)) + { + return result; + } + + // + if (Contains(X121SMCXWZToken, value)) + { + result = X_121_SMC_PROVIDER_XWZ; + } + else if (Contains(X121SMCXICHToken, value)) + { + result = X_121_SMC_PROVIDER_XICH; + } + + // + return result; +} + +// diff --git a/BKPS/14040203/X121SMCEA/Signals/x-121.smc.xind.signal.class.mq5 b/BKPS/14040203/X121SMCEA/Signals/x-121.smc.xind.signal.class.mq5 new file mode 100644 index 0000000..2b3efc4 --- /dev/null +++ b/BKPS/14040203/X121SMCEA/Signals/x-121.smc.xind.signal.class.mq5 @@ -0,0 +1,2025 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 X121 SMC Signal Class +// ------------------------------------------------- +// Name: XICH +// Description: provide all Signalling functions ... +// +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +////////////////////////////////////////////////////// +// +// Global Properties ... +#property library +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://www.saherelm.ir" +#property version "1.00" +#property strict + +// +// Imports ... +#include "../Classes/x-121.smc.market.cycle.helper.class.mq5" +#include "../Libraries/x-121.smc.guard.lib.mq5" +#include "../Libraries/x-121.smc.lib.mq5" +#include "./x-121.smc.xind.signal.lib.mq5" + +// +// Definition ... +class XCX121SMCXINDSignalDetector : public XCBase +{ + // + public: + // + // Props ... + bool useGuards; + double rfReward; + bool isPassedBoxes; + XBoxZone mWaitingBoxes[]; + XBoxZone mBreakedBoxes[]; + XBoxZone mActivatedBoxes[]; + bool continuesRFTillTarget; + XBoxZone mUnAvailableBoxes[]; + X121SMCStrategyXINDSignalConditions mConditions; + X121SMCStrategyXINDSignalConditions mConditionsCollection[]; + + // + // Constructor(s) ... + XCX121SMCXINDSignalDetector( + string _symbol, + ENUM_TIMEFRAMES _period // + ) + { + // + symbol = _symbol; + period = _period; + Init(); + } + + // + // Deconstructor ... + ~XCX121SMCXINDSignalDetector() + { + DeInit(); + } + + // + // + // + + /** + * Detect Setup Conditions based on Signalling ... + * + * @param provider: X121SMCStrategySignalProviderData instance Reference, Specified Data for Cycles ... + * @param maxAllowedSLDistanceInPoint: int, Max Allowed SL Distance in Points (if Bigger thn Zero Provided) ... + * + * @return ( bool ) + */ + bool DetectSignalSetup( + X121SMCStrategySignalProviderData &provider, + double tpReward = 3, + double maxAllowedSLDistanceInPoint = 300 // + ) + { + // + bool result = false; + + // + tpReward = NormalizeDouble(tpReward, 2); + + // + // Validate Cycle Helpers ... + result = provider.IsValid(); + if (!result) + { + // + mConditions.Clean(); + + // + return result; + } + + // + bool isBullish = false; + bool isBearish = false; + + // + int zIndex = 0; + int cIndex = zIndex + 1; + int pIndex = cIndex + 1; + int ppIndex = pIndex + 1; + + // + int loopback = 10; + + // + mConditions.symbol = symbol; + mConditions.period = period; + + // + double ask = GetAsk(symbol); + double bid = GetBid(symbol); + datetime cTime = TimeCurrent(); + double points = GetPoints(symbol); + + // + // Cycles Conditions ... + result = provider.Prepare( + zIndex, + loopback, + true, // Trigger ... + true, // Decision ... + true, // Analyse ... + true, // Verification ... + true, // Consolidation ... + true // Vision ... + ); + if (!result) + { + // + mConditions.Clean(); + return result; + } + + // + // Select Drawer Class ... + XCPOIDrawer *drawer = provider.visionCycleHelper.mPOIDrawer; + + // + // Detecting Bars based on Decision Cycle ... + XOHCL zBar; + XOHCL cBar; + XOHCL pBar; + XOHCL pPBar; + XOHCL consolidationZBar; + result = zBar.Init( + provider.decisionXConditions.symbol, + provider.decisionXConditions.period, + zIndex // + ); + result = + result && + zBar.GetPreviousBar(cBar); + result = + result && + cBar.GetPreviousBar(pBar); + result = + result && + pBar.GetPreviousBar(pPBar); + result = + result && + provider.consolidationCycleHelper.GetBar( + consolidationZBar, + zIndex // + ); + if (!result) + { + // + zBar.Clean(); + cBar.Clean(); + pBar.Clean(); + pPBar.Clean(); + consolidationZBar.Clean(); + + // + return result; + } + + // + bool drawBar = false; + if (drawBar) + { + // + DrawBar( + consolidationZBar, + drawer // + ); + } + + // + // + // + + // + // Setup Conditions ... + double sls[]; + double sl = 0; + double pivot = 0; + double point = 0; + double targets[]; + XBoxZone signalBox; + XBoxZone signalZone; + bool hasSignalBox = false; + ENUM_X_DIRECTION signalBoxDir = X_DIRECTION_NONE; + ENUM_X121SMC_XIND_PROVIDERS signalProvider = X121SMC_XIND_PROVIDER_NONE; + + // + // + // + + // + int waitingBoxesCount = UpdateWaitingBoxes( + X_CYCLE_ANALYSE, + X_CYCLE_DECISION, + provider // + ); + bool hasWaitingBoxes = IsValidSize(waitingBoxesCount); + + // + DrawBoxes(drawer); + + // + // Detect Signal Boxes ... + hasSignalBox = HasXINDConditions( + mWaitingBoxes, + mActivatedBoxes, + mBreakedBoxes, + X_CYCLE_DECISION, + signalBox, + signalZone, + signalBoxDir, + provider, + zIndex // + ); + if (hasSignalBox) + { + // + signalProvider = X121SMC_XIND_PROVIDER_XIND; + + // + MakeSignalBoxUnAvailable(signalBox); + MakeSignalBoxUnAvailable(signalZone); + } + + // + // + // + + // + // Cleanup Signal if UnApproved ... + if (!hasSignalBox) + { + // + signalBox.Clean(); + isBullish = false; + isBearish = false; + signalBoxDir = X_DIRECTION_NONE; + } + + // + // Summarize Results ... + result = hasSignalBox; + + // + if (result) + { + // + int idx = -1; + bool has = false; + + // + // Draw Signal Box ... + XCBoxObject *object; + has = drawer.DrawBox( + signalBox, + object // + ); + if (has) + { + mObjects.Add(object); + } + + // + // Detect Signal Direction ... + isBullish = IsBullish(signalBoxDir); + isBearish = IsBearish(signalBoxDir); + + // + pivot = isBullish + ? signalBox.lower + : signalBox.upper; + + // + point = isBullish + ? signalBox.upper + : signalBox.lower; + + // + double entry = GetEntry( + signalBox.symbol, + signalBoxDir // + ); + + // + // Selecting SL(s) ... + + // + double iSL = 0; + + // + // Default SL ... + iSL = pivot; + + // + Add( + iSL, + sls // + ); + + // + // Select and Provide SL Based on ... + double iAtr = 0; + if (signalProvider == X121SMC_XIND_PROVIDER_XIND) + { + // + iAtr = provider.decisionXConditions.atrBuffer[1]; + iAtr *= 0; + + // + // Fix rf Reward ... + rfReward = 2; + } + + // + // Select Condition SL ... + + // + double slsMin = GetMin(sls); + double slsMax = GetMax(sls); + + // + double longSL = slsMax - iAtr; + double shortSL = slsMin + iAtr; + + // + sl = isBullish + ? longSL + : shortSL; + + // + // Targets ... + + // + double risk = MathAbs(entry - sl); + + // + // Checking risk ... + if (risk >= maxAllowedSLDistanceInPoint) + { + // Print("Max Aloowed Risk Point Reached ..."); + } + + // + // Reward to RF ... + if (rfReward > 0) + { + // + double iRFReward = rfReward * risk; + double iRFTP = isBullish + ? entry + iRFReward + : entry - iRFReward; + + // + Add( + iRFTP, + targets // + ); + + // + if (continuesRFTillTarget && + rfReward < tpReward) + { + // + double iReward = rfReward + 1; + while (iReward < tpReward - 1) + { + // + iRFReward = iReward * risk; + iRFTP = isBullish + ? entry + iRFReward + : entry - iRFReward; + + // + Add( + iRFTP, + targets // + ); + + // + iReward++; + } + } + } + + // + Copy( + sls, + mConditions.sls // + ); + Copy( + targets, + mConditions.targets // + ); + + // + mConditions.sl = sl; + mConditions.pivot = pivot; + mConditions.point = point; + mConditions.setupTime = cTime; + mConditions.dir = signalBoxDir; + mConditions.signalBox = signalBox; + mConditions.provider = signalProvider; + } + + // + // + // + + // + // Cleanup Resources ... + + // + Clean(sls); + Clean(targets); + + // + provider.Clean(); + + // + zBar.Clean(); + cBar.Clean(); + pBar.Clean(); + pPBar.Clean(); + signalBox.Clean(); + ZeroMemory(drawer); + consolidationZBar.Clean(); + + // + return result; + } + + /** + * Detect Trigger Conditions for Specified Signal ... + * + * @param conditions: X121SMCStrategyXINDSignalConditions instance Reference, Specified Signal Conditions ... + * @param provider: X121SMCStrategySignalProviderData instance Reference, Specified Data for Cycles ... + * @param maxAllowedSetupAge: specified Setup Age for Expiration (if bigger than Zero) ... + * + * @return ( bool ) + */ + bool DetectSignalTrigger( + X121SMCStrategyXINDSignalConditions &conditions, + X121SMCStrategySignalProviderData &provider, + int maxAllowedSetupAge = 60 // + ) + { + // + bool result = false; + + // + result = + // + provider.IsValid() + // + ; + if (!result) + { + return result; + } + + // + result = conditions.IsSetuped(); + if (!result) + { + return result; + } + + // + datetime setupTime = conditions.setupTime; + ENUM_X_DIRECTION setupDir = conditions.dir; + + // + bool isBullish = IsBullish(setupDir); + bool isBearish = IsBearish(setupDir); + + // + int zIndex = 0; + int cIndex = zIndex + 1; + int pIndex = cIndex + 1; + int ppIndex = pIndex + 1; + + // + int loopback = 10; + + // + double ask = GetAsk(symbol); + double bid = GetBid(symbol); + datetime cTime = TimeCurrent(); + double points = GetPoints(symbol); + + // + // Cycles Conditions ... + result = provider.Prepare( + zIndex, + loopback // + ); + if (!result) + { + return result; + } + + // + double iAtr = provider.decisionXConditions.atrBuffer[1]; + iAtr *= 1.5; + + // + // Check Signal Validation ... + // IMPORTANT: since all Validations done in SetUp Process ... + // here we only Execute Signal ... + + // + result = isBullish || + isBearish; + + // + if (result) + { + // + conditions.triggerTime = cTime; + conditions.type = isBullish + ? X_POSITION_TYPE_LONG + : X_POSITION_TYPE_SHORT; + + // + } + + // + // Cleanup ... + + // + provider.Clean(); + + // + return result; + } + + /** + * Detect Guards bsed on Signalling Class ... + * + * @param guards: X121SMCGuard instance Collection, Holds Provided Guards ... + * @param positions: XPosition instance Collection, Provides Signalling Based Positions for Apply Guards on them ... + * @param provider: X121SMCStrategySignalProviderData instance Reference, Specified Data for Cycles ... + * + * @return ( bool ) + */ + bool DetectGuards( + X121SMCGuard &guards[], + const XPosition &positions[], + X121SMCStrategySignalProviderData &provider) + { + // + bool result = false; + + // + if (!useGuards) + { + return result; + } + + // + Clean(guards); + + // + // Set Provider for Common Guards ... + string signalProvider = ToString(X121SMC_XIND_PROVIDER_XTKKUMO); + + // + int zIndex = 0; + int cIndex = zIndex + 1; + int pIndex = cIndex + 1; + int ppIndex = pIndex + 1; + + // + XOHCL cBar; + + // + int loopback = 10; + + // + double ask = GetAsk(symbol); + double bid = GetBid(symbol); + datetime cTime = TimeCurrent(); + double points = GetPoints(symbol); + + // + // Cycles Conditions ... + result = provider.IsValid(); + result = + result && + provider.Prepare( + zIndex, + loopback // + ); + if (!result) + { + // + provider.Clean(); + return result; + } + + // + // Select Own Positions ... + int count = ArraySize(positions); + result = IsValidSize(count); + if (!result) + { + return result; + } + + // + XPosition ownPositions[]; + XPosition ownLongPositions[]; + XPosition ownShortPositions[]; + for (int i = 0; i < count; i++) + { + // + XPosition iPosition = positions[i]; + bool isOwn = iPosition + .IsFiltersPassed( + symbol, + signalProvider, + NULL, + X_POSITION_TYPE_ALL, + iPosition.magic // + ); + if (isOwn) + { + // + AddRef( + iPosition, + ownPositions // + ); + + // + bool isLong = IsLong(positions[i].type); + if (isLong) + { + // + AddRef( + iPosition, + ownLongPositions // + ); + } + else + { + // + AddRef( + iPosition, + ownShortPositions // + ); + } + } + } + + // + // Check Extracted Positions ... + + // + count = ArraySize(ownPositions); + + // + int longsCount = ArraySize(ownLongPositions); + bool hasLongs = IsValidSize(longsCount); + + // + int shortsCount = ArraySize(ownShortPositions); + bool hasShorts = IsValidSize(shortsCount); + + // + // Validate Own Positions ... + result = IsValidSize(count); + if (!result) + { + // + Clean(ownPositions); + Clean(ownLongPositions); + Clean(ownShortPositions); + + // + return result; + } + + // + // + // + + // + // Get Global and Common Guards ... + + // + // ENUM_X_121_SMC_GUARD_ACTIONS ignoreGuards[1] = { + // X_121_SMC_GUARD_ACTION_TRAIL_STOP // + // }; + // result = DetectX121SMCGuards( + // signalProvider, + // guards, + // positions, + // provider, + // // + // ignoreGuards + // // + // ); + + // + // + // + + // + // Implement Custom Implemented Guards ... + + // + // Here we Are Sure there is Positions to Guard ... + // based on Current Provider ... + + // + // Selected Consolidation Zones ... + + // + int idx = -1; + bool has = false; + + // + bool hasBullishConsolidationZone = false; + XConsolidationZone bullishConsolidationZone; + has = provider.decisionState.HasBullishConsolidationZones(); + if (has) + { + // + idx = GetYoungest(provider.decisionState.bullishConsolidationZones); + hasBullishConsolidationZone = IsValidIndex(idx); + if (hasBullishConsolidationZone) + { + bullishConsolidationZone = provider.decisionState.bullishConsolidationZones[idx]; + } + } + + // + bool hasBearishConsolidationZone = false; + XConsolidationZone bearishConsolidationZone; + has = provider.decisionState.HasBearishConsolidationZones(); + if (has) + { + // + idx = GetYoungest(provider.decisionState.bearishConsolidationZones); + hasBearishConsolidationZone = IsValidIndex(idx); + if (hasBearishConsolidationZone) + { + bearishConsolidationZone = provider.decisionState.bearishConsolidationZones[idx]; + } + } + + // + XBoxZone bullishBox; + bool hasBullishBox = false; + bool isBullishBoxBreaked = false; + if (!hasBullishBox) + { + // + XCOrderBlock *ob = NULL; + idx = GetYoungest(provider.analyseState.bullishOrderBlocks); + has = IsValidIndex(idx); + if (has) + { + // + ob = provider.analyseState.bullishOrderBlocks[idx]; + + // + hasBullishBox = ToBox( + bullishBox, + ob // + ); + } + + // + if (!hasBullishBox) + { + bullishBox.Clean(); + } + + // + ZeroMemory(ob); + } + + // + XBoxZone bearishBox; + bool hasBearishBox = false; + bool isBearishBoxBreaked = false; + if (!hasBearishBox) + { + // + XCOrderBlock *ob = NULL; + idx = GetYoungest(provider.analyseState.bearishOrderBlocks); + has = IsValidIndex(idx); + if (has) + { + // + ob = provider.analyseState.bearishOrderBlocks[idx]; + + // + hasBearishBox = ToBox( + bearishBox, + ob // + ); + } + + // + if (!hasBearishBox) + { + bearishBox.Clean(); + } + + // + ZeroMemory(ob); + } + + // + // Here We Have all Requirements for Guarding Positions ... + + // + // Available Guards: + // X_121_SMC_GUARD_ACTION_NONE + // X_121_SMC_GUARD_ACTION_CLOSE + // X_121_SMC_GUARD_ACTION_CLOSE_ALL + // X_121_SMC_GUARD_ACTION_CLOSE_LONGS + // X_121_SMC_GUARD_ACTION_CLOSE_SHORTS + // X_121_SMC_GUARD_ACTION_PARTIAL_CLOSE + // X_121_SMC_GUARD_ACTION_TRAIL_STOP + // X_121_SMC_GUARD_ACTION_TRAIL_TARGET + // X_121_SMC_GUARD_ACTION_HEDGE + + // + // X_121_SMC_GUARD_ACTION_CLOSE: + // Close Specified Position on Specified Conditions ... + + // + // X_121_SMC_GUARD_ACTION_CLOSE_ALL: + // Close All Positions on Specified Conditions ... + + // + // X_121_SMC_GUARD_ACTION_CLOSE_LONGS: + // Close All Long Positions on Specified Conditions ... + + // + // X_121_SMC_GUARD_ACTION_CLOSE_SHORTS: + // Close All Short Positions on Specified Conditions ... + + // + // X_121_SMC_GUARD_ACTION_PARTIAL_CLOSE: + // Partial Close Specified Position on Specified Conditions ... + + // + // X_121_SMC_GUARD_ACTION_TRAIL_STOP: + // Trail Stop Specified Position on Specified Conditions ... + bool handleStoptrailingBasedOnBoxes = true; + bool handleStoptrailingBasedOnConsolidationZones = true; + for (int i = 0; i < count; i++) + { + // + XPosition iPosition = ownPositions[i]; + + // + bool isInited = cBar.Init( + iPosition.symbol, + iPosition.period, + cIndex // + ); + + // + isBullishBoxBreaked = + isInited && + hasBullishBox && + cBar.high < bullishBox.lower; + + // + isBearishBoxBreaked = + isInited && + hasBearishBox && + cBar.low > bearishBox.upper; + + // + bool isLong = IsLong(iPosition.type); + bool isInProfit = iPosition.profit > 0; + + // + double sl = iPosition.sl; + double tp = iPosition.tp; + + // + // Trail Stops Using Consolidation Zones ... + + // + bool canTraiLonglUsingCZone = + // + handleStoptrailingBasedOnConsolidationZones && + // + (isLong && + isInProfit && + hasBullishConsolidationZone && + bullishConsolidationZone.lower > iPosition.sl && + bullishConsolidationZone.lower > iPosition.entry) + // + ; + if (canTraiLonglUsingCZone) + { + sl = bullishConsolidationZone.lower; + } + + // + bool canTraiShortlUsingCZone = + // + handleStoptrailingBasedOnConsolidationZones && + // + (!isLong && + isInProfit && + hasBearishConsolidationZone && + bearishConsolidationZone.upper < iPosition.sl && + bearishConsolidationZone.upper < iPosition.entry) + // + ; + if (canTraiShortlUsingCZone) + { + sl = bearishConsolidationZone.upper; + } + + // + bool canTrailUsingCZone = + canTraiLonglUsingCZone || + canTraiShortlUsingCZone; + + // + // Trail Stop Using Boxes ... + + // + bool canTraiLonglUsingBox = + // + handleStoptrailingBasedOnBoxes && + // + (isLong && + isInProfit && + hasBullishBox && + bullishBox.lower > iPosition.sl && + bullishBox.lower > iPosition.entry) + // + ; + if (canTraiLonglUsingBox) + { + sl = bullishBox.lower; + } + + // + bool canTraiShortlUsingBox = + // + handleStoptrailingBasedOnBoxes && + // + (!isLong && + isInProfit && + hasBearishBox && + bearishBox.upper < iPosition.sl && + bearishBox.upper < iPosition.entry) + // + ; + if (canTraiShortlUsingBox) + { + sl = bearishBox.upper; + } + + // + bool canTrailUsingBox = + canTraiLonglUsingBox || + canTraiShortlUsingBox; + + // + bool canTraiLonglUsingBreakedBox = + // + handleStoptrailingBasedOnBoxes && + // + (isLong && + isInProfit && + isBearishBoxBreaked && + bearishBox.upper > iPosition.sl && + bearishBox.upper > iPosition.entry) + // + ; + if (canTraiLonglUsingBreakedBox) + { + sl = bearishBox.upper; + } + + // + bool canTraiShortlUsingBreakedBox = + // + handleStoptrailingBasedOnBoxes && + // + (!isLong && + isInProfit && + isBullishBoxBreaked && + bullishBox.lower < iPosition.sl && + bullishBox.lower < iPosition.entry) + // + ; + if (canTraiShortlUsingBreakedBox) + { + sl = bullishBox.lower; + } + + // + bool canTrailUsingBreakedBox = + canTraiLonglUsingBreakedBox || + canTraiShortlUsingBreakedBox; + + // + // Summarize SL ... + + // + bool isSLPassed = + sl > 0 && + (isLong + ? iPosition.price - sl >= points * 15 + : sl - iPosition.price >= points * 15); + + // + bool canTrail = + isSLPassed && + (canTrailUsingBox || + canTrailUsingCZone || + canTrailUsingBreakedBox); + if (canTrail) + { + // + X121SMCGuard iGuard; + + // + iGuard.time = cTime; + iGuard.symbol = symbol; + iGuard.provider = signalProvider; + iGuard.action = X_121_SMC_GUARD_ACTION_TRAIL_STOP; + + // + iGuard.ticket = iPosition.ticket; + + // + iGuard.sl = sl; + + // + AddGuard( + iGuard, + guards // + ); + } + } + + // + // X_121_SMC_GUARD_ACTION_TRAIL_TARGET: + // Trail Target Specified Position on Specified Conditions ... + + // + // X_121_SMC_GUARD_ACTION_HEDGE: + // Hedge all Positions on Specified Conditions ... + + // + // Cleanup Collections ... + + // + cBar.Clean(); + + // + provider.Clean(); + + // + bullishBox.Clean(); + bearishBox.Clean(); + + // + bullishConsolidationZone.Clean(); + bearishConsolidationZone.Clean(); + + // + count = ArraySize(guards); + result = IsValidSize(count); + + // + return result; + } + + /** + * Detect and Manage Important Zones and Categorized them for Signalling Clss ... + * + * @param cycle: ENUM_X_CYCLES member, Specified Source Cycle for Detecting ... + * @param provider: X121SMCStrategySignalProviderData instance Reference, Specified Data for Cycles ... + * + * @return ( int ) + */ + int UpdateWaitingBoxes( + ENUM_X_CYCLES cycle, + ENUM_X_CYCLES vCycle, + X121SMCStrategySignalProviderData &provider, + int maxAllowedAge = 0 // + ) + { + // + int result = ArraySize(mWaitingBoxes) + ArraySize(mActivatedBoxes); + + // + int count = 0; + bool has = false; + + // + // Fil Selected Data ... + XPOIState cState; + X121Conditions cXConditions; + XPOIStateEvents cStateEvents; + XC121SMCCycleHelper *cHelper; + X121SMCCycleConditions cConditions; + has = provider.SelectCycle( + cycle, + cState, + cStateEvents, + cXConditions, + cHelper, + cConditions // + ); + if (!has) + { + // + cState.Clean(); + ZeroMemory(cHelper); + cConditions.Clean(); + cXConditions.Clean(); + cStateEvents.Clean(); + + // + return result; + } + + // + // Detecting New Boxes ... + + // + // At First Try Check All Exists FVGs + // then Only Check Youngest FVG ... + if (!isPassedBoxes) + { + // + XBoxZone tmpBoxes[]; + count = cState.FairValueGapsAsBox(tmpBoxes); + has = IsValidSize(count); + if (has) + { + // + for (int i = 0; i < count; i++) + { + // + XBoxZone iBox = tmpBoxes[i]; + + // + // Regular Validation of Boxes ... + bool isValid = IsBoxValid( + iBox, + 0, + iBox.period // + ); + if (!isValid) + { + // + iBox.Clean(); + continue; + } + + // + // Conditional Validation of FVG Boxes ... + isValid = IsFVGBoxValid( + iBox, + vCycle, + provider // + ); + if (!isValid) + { + // + iBox.Clean(); + continue; + } + + // + has = IsBoxExists(iBox); + if (!has) + { + // + AddRef( + iBox, + mWaitingBoxes // + ); + } + + // + iBox.Clean(); + } + } + Clean(tmpBoxes); + + // + isPassedBoxes = true; + } + else + { + // + XBoxZone iBox; + has = cStateEvents.hasNewFairValueGap; + if (has) + { + // + int idx = GetYoungest(cState.fairValueGaps); + has = IsValidIndex(idx); + if (has) + { + // + has = ToBox( + iBox, + cState.fairValueGaps[idx] // + ); + if (has) + { + // + // Regular Validation of Boxes ... + bool isValid = IsBoxValid( + iBox, + 0, + iBox.period // + ); + if (isValid) + { + // + // Conditional Validation of FVG Boxes ... + isValid = IsFVGBoxValid( + iBox, + vCycle, + provider // + ); + if (isValid) + { + // + has = IsBoxExists(iBox); + if (!has) + { + // + AddRef( + iBox, + mWaitingBoxes // + ); + } + } + } + } + } + } + + // + iBox.Clean(); + } + + // + // Update Times ... + datetime requireTime = GetBarTime( + cState.symbol, + cState.period, + 1 // + ); + + // + count = ArraySize(mWaitingBoxes); + has = IsValidSize(count); + if (has) + { + // + for (int i = 0; i < count; i++) + { + mWaitingBoxes[i].to = requireTime; + } + } + + // + count = ArraySize(mActivatedBoxes); + has = IsValidSize(count); + if (has) + { + // + for (int i = 0; i < count; i++) + { + mActivatedBoxes[i].to = requireTime; + } + } + + // + // Validate Exists Boxes ... + + // + // Waiting Boxes ... + count = ArraySize(mWaitingBoxes); + has = IsValidSize(count); + if (has) + { + // + int mustRemove[]; + for (int i = 0; i < count; i++) + { + // + XBoxZone iBox = mWaitingBoxes[i]; + + // + // Check Box Validation ... + bool isValid = IsBoxValid( + iBox, + 0, + iBox.period // + ); + + // + // Check Box Breaked ... + bool isBreaked = IsBoxBreaked( + iBox, + 0, + iBox.period // + ); + + // + // Checking Box Age ... + int age = iBox.GetAge(); + bool isAgeBreaked = + maxAllowedAge > 0 && + age > maxAllowedAge; + if (isAgeBreaked) + { + // + Add( + i, + mustRemove // + ); + + // + AddRef( + iBox, + mUnAvailableBoxes // + ); + + // + iBox.Clean(); + continue; + } + + // + // Box Waiting ... + if (isValid) + { + // + iBox.Clean(); + continue; + } + + // + // Box Breaked ... + if (isBreaked) + { + // + Add( + i, + mustRemove // + ); + + // + AddRef( + iBox, + mBreakedBoxes // + ); + + // + iBox.Clean(); + continue; + } + + // + // Box Activated ... + if (!isValid) + { + // + Add( + i, + mustRemove // + ); + + // + AddRef( + iBox, + mActivatedBoxes // + ); + + // + iBox.Clean(); + continue; + } + + // + iBox.Clean(); + } + + // + CleanupArray( + mustRemove, + mWaitingBoxes // + ); + } + + // + // Activated Boxes ... + count = ArraySize(mActivatedBoxes); + has = IsValidSize(count); + if (has) + { + // + int mustRemove[]; + for (int i = 0; i < count; i++) + { + // + XBoxZone iBox = mActivatedBoxes[i]; + + // + // Checking Box Age ... + int age = iBox.GetAge(); + bool isAgeBreaked = + maxAllowedAge > 0 && + age > maxAllowedAge; + if (isAgeBreaked) + { + // + Add( + i, + mustRemove // + ); + + // + AddRef( + iBox, + mUnAvailableBoxes // + ); + + // + iBox.Clean(); + continue; + } + + // + // Check Breaked ... + bool isBreaked = IsBoxBreaked( + iBox, + 0, + iBox.period // + ); + if (isBreaked) + { + // + Add( + i, + mustRemove // + ); + + // + AddRef( + iBox, + mBreakedBoxes // + ); + + // + iBox.Clean(); + continue; + } + + // + iBox.Clean(); + } + + // + CleanupArray( + mustRemove, + mActivatedBoxes // + ); + } + + // + // Cleanup Resources ... + + // + cState.Clean(); + ZeroMemory(cHelper); + cConditions.Clean(); + cXConditions.Clean(); + cStateEvents.Clean(); + + // + result = ArraySize(mWaitingBoxes) + ArraySize(mActivatedBoxes); + + // + return result; + } + + /** + * Make a Detected Signal Box UnAvailable for Prevent of Double Executing ... + * + * @param box: XBoxZone instance Reference, Specified Signal Box ... + */ + void MakeSignalBoxUnAvailable( + XBoxZone &box // + ) + { + // + int idx = -1; + int count = 0; + bool has = false; + + // + // Validate Box ... + has = box.IsValid(); + if (!has) + { + return; + } + + // + // Check Waiting Boxes ... + count = ArraySize(mWaitingBoxes); + has = IsValidSize(count); + if (has) + { + // + has = FindBoxIndex( + idx, + box, + mWaitingBoxes // + ); + if (has) + { + // + // Remove Signal Box From Collection ... + ArrayRemove( + mWaitingBoxes, + idx, + 1 // + ); + + // + // Add Signal Box to UnAvailable Boxes ... + AddRef( + box, + mUnAvailableBoxes // + ); + + // + return; + } + } + + // + // Check Activated Boxes ... + count = ArraySize(mActivatedBoxes); + has = IsValidSize(count); + if (has) + { + // + has = FindBoxIndex( + idx, + box, + mActivatedBoxes // + ); + if (has) + { + // + // Remove Signal Box From Collection ... + ArrayRemove( + mActivatedBoxes, + idx, + 1 // + ); + + // + // Add Signal Box to UnAvailable Boxes ... + AddRef( + box, + mUnAvailableBoxes // + ); + + // + return; + } + } + + // + // Check Breaked Boxes ... + count = ArraySize(mBreakedBoxes); + has = IsValidSize(count); + if (has) + { + // + has = FindBoxIndex( + idx, + box, + mBreakedBoxes // + ); + if (has) + { + // + // Remove Signal Box From Collection ... + ArrayRemove( + mBreakedBoxes, + idx, + 1 // + ); + + // + // Add Signal Box to UnAvailable Boxes ... + AddRef( + box, + mUnAvailableBoxes // + ); + + // + return; + } + } + } + + /** + * Check a Box is Exists in Box Collections of Signalling Collections ... + * + * @param box: XBoxZone instance Reference, Specified Box to Check ... + * + * @return ( bool ) + */ + bool IsBoxExists(XBoxZone &box) + { + // + bool result = false; + + // + int idx = -1; + int count = 0; + bool has = false; + + // + // Witing Boxes ... + count = ArraySize(mWaitingBoxes); + has = IsValidSize(count); + if (has) + { + // + has = FindBoxIndex( + idx, + box, + mWaitingBoxes // + ); + result = has; + if (result) + { + return result; + } + } + + // + // Activated Boxes ... + count = ArraySize(mActivatedBoxes); + has = IsValidSize(count); + if (has) + { + // + has = FindBoxIndex( + idx, + box, + mActivatedBoxes // + ); + result = has; + if (result) + { + return result; + } + } + + // + // Breaked Boxes ... + count = ArraySize(mBreakedBoxes); + has = IsValidSize(count); + if (has) + { + // + has = FindBoxIndex( + idx, + box, + mBreakedBoxes // + ); + result = has; + if (result) + { + return result; + } + } + + // + // UnAvailable Boxes ... + count = ArraySize(mUnAvailableBoxes); + has = IsValidSize(count); + if (has) + { + // + has = FindBoxIndex( + idx, + box, + mUnAvailableBoxes // + ); + result = has; + if (result) + { + return result; + } + } + + // + return result; + } + + /** + * Add Conditions to Conditions Collection if not Exists ... + * + * @param maxAllowed: int, Specified Max Allowed Holding Conditions ... + * + * @return ( int ) + */ + int AddConditionsIfNotExists( + int maxAllowed = 10 // + ) + { + // + int result = 0; + + // + bool isSetuped = IsValid(mConditions.setupTime) && + HasDirection(mConditions.dir); + if (!isSetuped) + { + return result; + } + + // + int count = ArraySize(mConditionsCollection); + if (IsValidSize(count)) + { + // + // Copy Original Items ... + X121SMCStrategyXINDSignalConditions tmpItems[]; + Copy( + mConditionsCollection, + tmpItems // + ); + + // + // Prese Item Data ... + bool isBullish = IsBullish(mConditions.dir); + + // + for (int i = 0; i < count; i++) + { + // + X121SMCStrategyXINDSignalConditions iItem = tmpItems[i]; + + // + bool canRemove = mConditions.dir == iItem.dir && + mConditions.pivot == iItem.pivot; + if (canRemove) + { + // + ArrayRemove( + mConditionsCollection, + i, + 1 // + ); + } + } + + // + Clean(tmpItems); + } + + // + AddRef( + mConditions, + mConditionsCollection // + ); + + // + // Remove Olds ... + CleanupArray( + mConditionsCollection, + maxAllowed // + ); + + // + result = ArraySize(mConditionsCollection); + + // + return result; + } + + // + // Draw Functions ... + + /** + * Draw Specified Bar on Chart ... + * + * @param bar: XOHCL instance Reference, Specified Bar ... + * @param forceClean: force Clean Drawn Objects ... + */ + void DrawBar( + XOHCL &bar, + XCPOIDrawer *drawer, + bool forceClean = true // + ) + { + // + if (forceClean) + { + mBarObjects.Clear(); + } + + // + if (drawer == NULL || + !bar.IsValid()) + { + return; + } + + // + bool isBullish = bar.IsBullish(); + + // + int widthBar = 2; + bool fillShadowsBar = true; + ENUM_LINE_STYLE styleBar = STYLE_SOLID; + color clrBar = + isBullish + ? clrAqua + : clrMagenta; + + // + datetime to = bar.NextAt(); + + // + XCOHCLObject *iObj; + bool isCreated = drawer + .CreateBar( + bar, + iObj, + to // + ); + if (isCreated) + { + // + iObj.BarSpes( + widthBar, + clrBar, + styleBar // + ); + + // + iObj.LowShadowFill(fillShadowsBar); + iObj.HighShadowFill(fillShadowsBar); + + // + mBarObjects.Add(iObj); + } + } + + /** + * Draw Boxes of Signallings on Chart ... + * + * @param forceClean: force Clean Drawn Objects ... + */ + void DrawBoxes( + XCPOIDrawer *drawer, + bool forceClean = false // + ) + { + // + if (forceClean) + { + mObjects.Clear(); + } + + // + int count = 0; + bool has = false; + + // + // Waiting Boxes ... + count = ArraySize(mWaitingBoxes); + has = IsValidSize(count); + if (has) + { + // + for (int i = 0; i < count; i++) + { + // + XCBoxObject *iObj; + has = drawer.DrawBox( + mWaitingBoxes[i], + iObj // + ); + if (has) + { + mObjects.Add(iObj); + } + } + } + + // + // Activated Boxes ... + count = ArraySize(mActivatedBoxes); + has = IsValidSize(count); + if (has) + { + // + for (int i = 0; i < count; i++) + { + // + XCBoxObject *iObj; + has = drawer.DrawBox( + mActivatedBoxes[i], + iObj // + ); + if (has) + { + // + if (mActivatedBoxes[i].IsBullish()) + { + iObj.BoxColor(clrYellow); + } + else + { + iObj.BoxColor(clrOrange); + } + + // + mObjects.Add(iObj); + } + } + } + } + + // + protected: + // + + // + private: + // + // Props ... + string symbol; + ENUM_TIMEFRAMES period; + CArrayObj mObjects; + CArrayObj mBarObjects; + + /** + * Initialize ... + */ + void Init() + { + // + rfReward = 2; + useGuards = false; + isPassedBoxes = false; + continuesRFTillTarget = true; + } + + /** + * DeInitialize ... + */ + void DeInit() + { + // + mConditions.Clean(); + Clean(mConditionsCollection); + + // + mObjects.Clear(); + mBarObjects.Clear(); + } + + // +}; + +// \ No newline at end of file diff --git a/BKPS/14040203/X121SMCEA/Signals/x-121.smc.xind.signal.lib.mq5 b/BKPS/14040203/X121SMCEA/Signals/x-121.smc.xind.signal.lib.mq5 new file mode 100644 index 0000000..d439c15 --- /dev/null +++ b/BKPS/14040203/X121SMCEA/Signals/x-121.smc.xind.signal.lib.mq5 @@ -0,0 +1,1735 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 X121 SMC Signal Class +// ------------------------------------------------- +// Name: XICH +// Description: provide all Signalling functions ... +// +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +////////////////////////////////////////////////////// +// +// Global Properties ... +#property library +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://www.saherelm.ir" +#property version "1.00" +#property strict + +// +// Imports ... +// #include "../../Libraries/x-trade.lib" +#include "../Classes/x-121.smc.market.cycle.helper.class.mq5" +#include "../Libraries/x-121.smc.guard.lib.mq5" +#include "../Libraries/x-121.smc.lib.mq5" + +// +// Provided Signals Enumeration ... +enum ENUM_X121SMC_XIND_PROVIDERS +{ + X121SMC_XIND_PROVIDER_NONE, + X121SMC_XIND_PROVIDER_XIND, + X121SMC_XIND_PROVIDER_XTKKUMO, +}; + +// +// Definitions ... + +// +// XIND Signal Conditions ... +struct X121SMCStrategyXINDSignalConditions +{ + // + // Props ... + + // + string symbol; + ENUM_TIMEFRAMES period; + + // + double sl; + ENUM_X_DIRECTION dir; + ENUM_X_POSITION_TYPES type; + + // + // Setup Props ... + + // + datetime setupTime; + datetime triggerTime; + + // + double pivot; + double point; + double sls[]; + double targets[]; + + // + XBoxZone signalBox; + + // + ENUM_X121SMC_XIND_PROVIDERS provider; + + // + // Constructor ... + X121SMCStrategyXINDSignalConditions() + { + Clean(); + } + + // + // Tools ... + + /** + * Cleaning Up ... + */ + void Clean() + { + // + sl = 0; + + // + dir = X_DIRECTION_NONE; + type = X_POSITION_TYPE_NONE; + + // + symbol = NULL; + period = NULL; + setupTime = NULL; + triggerTime = NULL; + + // + ExtensionClean(); + + // + ZeroMemory(this); + } + + /** + * Check Condition is Setting Up ... + * + * @param dir: ENUM_X_DIRECTION member, Setting Up Direction ... + * + * @return ( bool ) + */ + bool IsSetuped() + { + // + bool result = false; + + // + result = IsValid(setupTime) && + HasDirection(dir); + if (!result) + { + return result; + } + + // + return result; + } + + /** + * Calculate Setup Age ... + * + * @return ( int ) + */ + int GetSetupAge() + { + // + int result = 0; + + // + if (!IsSetuped()) + { + return result; + } + + // + result = (int)(TimeCurrent() - setupTime) / PeriodSeconds(period); + + // + return result; + } + + /** + * Detect How we Can Trigger Signal ... + * + * @return ( bool ) + */ + bool CanTrigger() + { + // + bool result = false; + + // + result = + // + sl > 0 && + IsValid(symbol) && + IsValid(period) && + IsValid(triggerTime) && + type != X_POSITION_TYPE_ALL && + type != X_POSITION_TYPE_NONE + // + ; + + // + return result; + } + + // + // Extensions ... + + /** + * Clean Additional Properties ... + */ + void ExtensionClean() + { + // + pivot = 0; + point = 0; + + // + Clean(sls); + Clean(targets); + signalBox.Clean(); + + // + provider = X121SMC_XIND_PROVIDER_NONE; + } + + // + // + // + + // + void UpdateTo(datetime value = NULL) + { + // + value = NormalizeTime(value); + + // + int count = 0; + bool has = false; + } + + // +}; + +// +// Extension Functions ... + +// +// Validate FVG BOXes ... + +// +bool IsFVGBoxValid( + XBoxZone &box, + ENUM_X_CYCLES cycle, + X121SMCStrategySignalProviderData &provider // +) +{ + // + bool result = false; + + // + result = box.IsValid(); + if (!result) + { + return result; + } + + // + // Fil Selected Data ... + XPOIState cState; + X121Conditions cXConditions; + XPOIStateEvents cStateEvents; + XC121SMCCycleHelper *cHelper; + X121SMCCycleConditions cConditions; + result = provider.SelectCycle( + cycle, + cState, + cStateEvents, + cXConditions, + cHelper, + cConditions // + ); + if (!result) + { + // + cState.Clean(); + ZeroMemory(cHelper); + cConditions.Clean(); + cXConditions.Clean(); + cStateEvents.Clean(); + + // + return result; + } + + // + bool isBoxBullish = box.IsBullish(); + + // + int count = 0; + bool has = false; + + // + XBoxZone tmpBoxes[]; + count = cState.FairValueGapsAsBox(tmpBoxes); + has = IsValidSize(count); + + // + // Check Must Contains Inner Cycle FVG ... + XBoxZone selectedBox; + bool hasSelectedBox = false; + if (has) + { + // + for (int i = 0; i < count; i++) + { + // + XBoxZone iBox = tmpBoxes[i]; + + // + // Regular Validation of Boxes ... + bool isValid = IsBoxValid( + iBox, + 0, + iBox.period // + ); + bool isTypePassed = iBox.dir == box.dir; + bool isFromPssed = iBox.from >= box.from; + bool isPlacePassed = + IsBoxInsideOr( + iBox, + box // + ) && + (isBoxBullish + ? iBox.lower >= box.lower + : iBox.upper <= box.upper); + has = + isValid && + isFromPssed && + isTypePassed && + isPlacePassed; + if (!has) + { + // + iBox.Clean(); + continue; + } + + // + has = + !hasSelectedBox + ? true + : isBoxBullish + ? selectedBox.upper > iBox.upper + : selectedBox.lower < iBox.lower; + if (has) + { + // + selectedBox = iBox; + hasSelectedBox = selectedBox.IsValid(); + } + + // + iBox.Clean(); + } + } + + // + result = hasSelectedBox; + + // + cState.Clean(); + Clean(tmpBoxes); + selectedBox.Clean(); + ZeroMemory(cHelper); + cConditions.Clean(); + cXConditions.Clean(); + cStateEvents.Clean(); + + // + return result; +} + +// +bool CheckConsolidationPassedBox( + XBoxZone &consolidationBox, + XBoxZone &box, + XPOIState &state // +) +{ + // + bool result = false; + + // + result = box.IsValid(); + if (!result) + { + return result; + } + + // + int idx = -1; + int count = 0; + bool has = false; + + // + XBoxZone selectedBox; + has = state.HasConsolidationZones(); + if (has) + { + // + count = state.CountConsolidationZones(); + for (int i = 0; i < count; i++) + { + // + XConsolidationZone iZone = state.consolidationZones[i]; + has = ToBox( + selectedBox, + iZone // + ); + if (!has) + { + // + iZone.Clean(); + selectedBox.Clean(); + continue; + }; + + // + // Check Selected Box is Related to BOX or not ... + bool isValid = + // + // Direction Passed ... + selectedBox.dir == box.dir && + // + // Time Passe ... + selectedBox.to > box.from && + selectedBox.from < box.from && + // + // Place Passed ... + ( + // + // Upper Inside ... + (selectedBox.upper >= box.lower && + selectedBox.upper <= box.upper) + // + || + // + // Lower Inside ... + (selectedBox.lower <= box.upper && + selectedBox.lower >= box.lower) + // + || + // + // Fully Inside ... + (selectedBox.upper <= box.upper && + selectedBox.lower >= box.lower) + // + ); + if (isValid) + { + // + iZone.Clean(); + break; + } + + // + iZone.Clean(); + selectedBox.Clean(); + } + } + + // + result = selectedBox.IsValid(); + if (result) + { + consolidationBox = selectedBox; + } + selectedBox.Clean(); + + // + return result; +} + +// +// Signalling Conditions Parsers ... + +// +// Detect Signals Based On XPV Indicator Golden Zones ... +bool HasXINDConditions( + XBoxZone &waitingBoxes[], + XBoxZone &activatedBoxes[], + XBoxZone &breakedBoxes[], + ENUM_X_CYCLES cycle, + XBoxZone &box, + XBoxZone &zone, + ENUM_X_DIRECTION &dir, + X121SMCStrategySignalProviderData &provider, + int barIndex = 0 // +) +{ + // + bool result = false; + + // + box.Clean(); + zone.Clean(); + dir = X_DIRECTION_NONE; + + // + // Checking Required Zone Boxes for Signalling ... + int waitingBoxesCount = ArraySize(waitingBoxes); + int breakedBoxesCount = ArraySize(breakedBoxes); + int activatedBoxesCount = ArraySize(activatedBoxes); + + // + // Fil Selected Data ... + XPOIState cState; + X121Conditions cXConditions; + XPOIStateEvents cStateEvents; + XC121SMCCycleHelper *cHelper; + X121SMCCycleConditions cConditions; + result = provider.SelectCycle( + cycle, + cState, + cStateEvents, + cXConditions, + cHelper, + cConditions // + ); + if (!result) + { + // + cState.Clean(); + ZeroMemory(cHelper); + cConditions.Clean(); + cXConditions.Clean(); + cStateEvents.Clean(); + + // + return result; + } + + // + // Normalize Args ... + + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + int idx = -1; + int count = 0; + bool has = false; + + // + int zIDX = barIndex; + int cIDX = zIDX + 1; + int pIDX = cIDX + 1; + int ppIDX = pIDX + 1; + + // + bool isBullish = false; + bool isBearish = false; + + // + XOHCL zBar; + XOHCL cBar; + XOHCL pBar; + XOHCL pPBar; + + // + // Initial Bars ... + result = zBar.Init( + cState.symbol, + cState.period, + barIndex // + ); + result = + result && + zBar.GetPreviousBar(cBar); + result = + result && + cBar.GetPreviousBar(pBar); + result = + result && + pBar.GetPreviousBar(pPBar); + if (!result) + { + // + zBar.Clean(); + cBar.Clean(); + pBar.Clean(); + cState.Clean(); + ZeroMemory(cHelper); + cConditions.Clean(); + cXConditions.Clean(); + + // + return result; + } + + // + XCPOIDrawer *drawer = provider.visionCycleHelper.mPOIDrawer; + + // + // Select Waiting Box ... + XBoxZone selectedBox; + bool hasSelectedBox = false; + bool useWaitingBoxes = true; + bool useActivtedBoxes = true; + bool useBreakedBoxes = false; + XBoxZone selectedConsolidationBox; + bool hasSelectedConsolidationBox = false; + if (useWaitingBoxes && IsValidSize(waitingBoxesCount)) + { + // + for (int i = 0; i < waitingBoxesCount; i++) + { + // + XBoxZone iBox = waitingBoxes[i]; + + // + // Check PV Passed Box ... + has = IsBoxPVPassed( + iBox, + cXConditions // + ); + if (has) + { + // + selectedBox = iBox; + iBox.Clean(); + + // + break; + } + + // + // Check Consolidation Passed Box ... + has = CheckConsolidationPassedBox( + selectedConsolidationBox, + iBox, + cState // + ); + if (has) + { + // + selectedBox = iBox; + iBox.Clean(); + + // + break; + } + + // + iBox.Clean(); + } + + // + hasSelectedBox = selectedBox.IsValid(); + if (!hasSelectedBox) + { + selectedBox.Clean(); + } + + // + hasSelectedConsolidationBox = selectedConsolidationBox.IsValid(); + if (!hasSelectedConsolidationBox) + { + selectedConsolidationBox.Clean(); + } + } + if (useActivtedBoxes && !hasSelectedBox && IsValidSize(activatedBoxesCount)) + { + // + for (int i = 0; i < activatedBoxesCount; i++) + { + // + XBoxZone iBox = activatedBoxes[i]; + + // + // Check PV Passed Box ... + has = IsBoxPVPassed( + iBox, + cXConditions // + ); + if (has) + { + // + selectedBox = iBox; + iBox.Clean(); + + // + break; + } + + // + // Check Consolidation Passed Box ... + has = CheckConsolidationPassedBox( + selectedConsolidationBox, + iBox, + cState // + ); + if (has) + { + // + selectedBox = iBox; + iBox.Clean(); + + // + break; + } + + // + iBox.Clean(); + } + + // + hasSelectedBox = selectedBox.IsValid(); + if (!hasSelectedBox) + { + selectedBox.Clean(); + } + + // + hasSelectedConsolidationBox = selectedConsolidationBox.IsValid(); + if (!hasSelectedConsolidationBox) + { + selectedConsolidationBox.Clean(); + } + } + if (useBreakedBoxes && !hasSelectedBox && IsValidSize(breakedBoxesCount)) + { + // + for (int i = 0; i < breakedBoxesCount; i++) + { + // + XBoxZone iBox = breakedBoxes[i]; + + // + iBox.Clean(); + } + + // + hasSelectedBox = selectedBox.IsValid(); + if (!hasSelectedBox) + { + selectedBox.Clean(); + } + } + + // + double selectedBoxMid = 0; + double selectedBoxStr = 0; + if (hasSelectedBox) + { + // + selectedBoxMid = (selectedBox.lower + ((selectedBox.upper - selectedBox.lower) / 2)); + + // + selectedBox.to = zBar.time; + CheckBoxStr( + cHelper, + selectedBox, + selectedBoxStr // + ); + + // + if (selectedBoxStr != 0) + { + // + long chartId = drawer.ChartIdentification(); + int subWindow = drawer.SubWindowIdentification(); + string name = selectedBox.GetTag() + "_SUPRES"; + + // + CChartObjectTrend *iObj; + iObj = new CChartObjectTrend(); + has = iObj.Create( + chartId, + name, + subWindow, + selectedBox.from, + selectedBoxStr, + selectedBox.to, + selectedBoxStr // + ); + if (has) + { + // + color lineColor = + selectedBox.IsBullish() + ? clrLime + : clrRed; + iObj.Color(lineColor); + iObj.Width(2); + } + } + + // + XCBoxObject *iObj; + has = drawer.DrawBox( + selectedBox, + iObj // + ); + if (has) + { + // + iObj.BoxColor(clrCornflowerBlue); + iObj.BoxStyle(STYLE_SOLID); + iObj.BoxWidth(2); + + // + Print("Selected Box ..."); + } + } + + // + if (hasSelectedConsolidationBox) + { + // + XCBoxObject *iObj; + has = drawer.DrawBox( + selectedConsolidationBox, + iObj // + ); + if (has) + { + // + iObj.BoxWidth(2); + iObj.BoxStyle(STYLE_SOLID); + } + } + + // + // Detect Bullish and Bearish Consolidation Zones ... + XBoxZone consolidationBox; + bool hasConsolidationBox = false; + if (!hasConsolidationBox) + { + // + hasConsolidationBox = cStateEvents.hasNewConsolidationZone; + if (hasConsolidationBox) + { + // + idx = GetYoungest(cState.consolidationZones); + has = IsValidIndex(idx); + if (has) + { + // + XConsolidationZone cZone = cState.consolidationZones[idx]; + + // + ToBox( + consolidationBox, + cZone // + ); + } + } + + // + hasConsolidationBox = consolidationBox.IsValid(); + // if (hasConsolidationBox) + // { + // // + // XCBoxObject *iObj; + // has = drawer.DrawBox( + // consolidationBox, + // iObj // + // ); + // if (has) + // { + // // + // color crlBox = consolidationBox.IsBullish() + // ? clrBlue + // : clrDarkRed; + + // // + // iObj.BoxWidth(2); + // iObj.BoxColor(crlBox); + // iObj.BoxStyle(STYLE_SOLID); + // } + // } + } + + // + // + // + + // + // Reading Resources ... + + // + double sarZ = cXConditions.sarBuffer[zIDX]; + double sarC = cXConditions.sarBuffer[cIDX]; + double sarP = cXConditions.sarBuffer[pIDX]; + double sarPP = cXConditions.sarBuffer[ppIDX]; + + // + double peakZ = cXConditions.peaksBuffer[zIDX]; + double peakC = cXConditions.peaksBuffer[cIDX]; + double peakP = cXConditions.peaksBuffer[pIDX]; + double peakPP = cXConditions.peaksBuffer[ppIDX]; + + // + double valeZ = cXConditions.valesBuffer[zIDX]; + double valeC = cXConditions.valesBuffer[cIDX]; + double valeP = cXConditions.valesBuffer[pIDX]; + double valePP = cXConditions.valesBuffer[ppIDX]; + + // + double strZ = cXConditions.strBuffer[zIDX]; + double strC = cXConditions.strBuffer[cIDX]; + double strP = cXConditions.strBuffer[pIDX]; + double strPP = cXConditions.strBuffer[ppIDX]; + + // + double priceChangeZ = cXConditions.priceChangeBuffer[zIDX]; + double priceChangeC = cXConditions.priceChangeBuffer[cIDX]; + double priceChangeP = cXConditions.priceChangeBuffer[pIDX]; + double priceChangePP = cXConditions.priceChangeBuffer[ppIDX]; + + // + double peaksGoldenZ = cXConditions.peaksGoldenBuffer[zIDX]; + double peaksGoldenC = cXConditions.peaksGoldenBuffer[cIDX]; + double peaksGoldenP = cXConditions.peaksGoldenBuffer[pIDX]; + double peaksGoldenPP = cXConditions.peaksGoldenBuffer[ppIDX]; + + // + double valesGoldenZ = cXConditions.valesGoldenBuffer[zIDX]; + double valesGoldenC = cXConditions.valesGoldenBuffer[cIDX]; + double valesGoldenP = cXConditions.valesGoldenBuffer[pIDX]; + double valesGoldenPP = cXConditions.valesGoldenBuffer[ppIDX]; + + // + // Generate Conditions ... + + // + bool isPBarBullishPriceChangeVPattern = + priceChangeP > priceChangePP && + priceChangeP > priceChangeC; + + // + bool isPBarBearishPriceChangeVPattern = + priceChangeP < priceChangePP && + priceChangeP < priceChangeC; + + // + bool isCBarBullishPriceChangeVPattern = + priceChangeC > priceChangeP && + priceChangeC > priceChangeZ; + + // + bool isCBarBearishPriceChangeVPattern = + priceChangeC < priceChangeP && + priceChangeC < priceChangeZ; + + // + bool isCPriceChangeUnderSelectedBoxMid = + selectedBoxMid > 0 && + priceChangeC < selectedBoxMid; + + // + bool isCPriceChangeOverSelectedBoxMid = + selectedBoxMid > 0 && + priceChangeC > selectedBoxMid; + + // + bool isPPriceChangeUnderSelectedBoxMid = + selectedBoxMid > 0 && + priceChangeP < selectedBoxMid; + + // + bool isPPriceChangeOverSelectedBoxMid = + selectedBoxMid > 0 && + priceChangeP > selectedBoxMid; + + // + bool isPriceChangeUnderSelectedBoxMid = + isCPriceChangeUnderSelectedBoxMid || + isPPriceChangeUnderSelectedBoxMid; + + // + bool isPriceChangeOverSelectedBoxMid = + isCPriceChangeOverSelectedBoxMid || + isPPriceChangeOverSelectedBoxMid; + + // + bool isBarBullishPriceChangeVPattern = + isPBarBullishPriceChangeVPattern || + isCBarBullishPriceChangeVPattern; + + // + bool isBarBearishPriceChangeVPattern = + isPBarBearishPriceChangeVPattern || + isCBarBearishPriceChangeVPattern; + + // + bool isPriceChangeBullishRejectedStr = + // + cXConditions.strStateBuffer[zIDX] > 0 && + cXConditions.strStateBuffer[cIDX] > 0 && + cXConditions.strStateBuffer[pIDX] > 0 && + // + cXConditions.strBuffer[zIDX] == cXConditions.strBuffer[cIDX] && + cXConditions.strBuffer[zIDX] == cXConditions.strBuffer[pIDX] && + // + ((priceChangeP < strC && + priceChangeC > strC) || + (priceChangeC < strC && + priceChangeZ > strC)) + // + ; + + // + bool isPriceChangeBearishRejectedStr = + // + cXConditions.strStateBuffer[zIDX] < 0 && + cXConditions.strStateBuffer[cIDX] < 0 && + cXConditions.strStateBuffer[pIDX] < 0 && + // + cXConditions.strBuffer[zIDX] == cXConditions.strBuffer[cIDX] && + cXConditions.strBuffer[zIDX] == cXConditions.strBuffer[pIDX] && + // + ((priceChangeP > strC && + priceChangeC < strC) || + (priceChangeC > strC && + priceChangeZ > strC)) + // + ; + + // + bool isCBarBullishRejectedStr = + cBar.low < strC && + cBar.GetDown() > strC; + + // + bool isPBarBullishRejectedStr = + pBar.low < strP && + pBar.GetDown() > strP; + + // + bool isBarBullishRejectedStr = + isCBarBullishRejectedStr || + isPBarBullishRejectedStr; + + // + bool isCBarBearishRejectedStr = + cBar.high > strC && + cBar.GetUp() < strC; + + // + bool isPBarBearishRejectedStr = + pBar.high > strP && + pBar.GetUp() < strP; + + // + bool isBarBearishRejectedStr = + isCBarBearishRejectedStr || + isPBarBearishRejectedStr; + + // + bool isCPVsPeakSame = + provider.decisionXConditions.peaksBuffer[cIDX] == provider.analyseXConditions.peaksBuffer[cIDX] && + provider.analyseXConditions.peaksBuffer[cIDX] == provider.consolidationXConditions.peaksBuffer[cIDX]; + + bool isPPVsPeakSame = + provider.decisionXConditions.peaksBuffer[pIDX] == provider.analyseXConditions.peaksBuffer[pIDX] && + provider.analyseXConditions.peaksBuffer[pIDX] == provider.consolidationXConditions.peaksBuffer[pIDX]; + + // + bool isCPVsValeSame = + provider.decisionXConditions.valesBuffer[cIDX] == provider.analyseXConditions.valesBuffer[cIDX] && + provider.analyseXConditions.valesBuffer[cIDX] == provider.consolidationXConditions.valesBuffer[cIDX]; + + bool isPPVsValeSame = + provider.decisionXConditions.valesBuffer[pIDX] == provider.analyseXConditions.valesBuffer[pIDX] && + provider.analyseXConditions.valesBuffer[pIDX] == provider.consolidationXConditions.valesBuffer[pIDX]; + + // + bool isPeaksSame = isCPVsPeakSame && isPPVsPeakSame; + bool isValesSame = isCPVsValeSame && isPPVsValeSame; + + // + // Bars Conditions ... + + // + ENUM_X_DIRECTION cBarDir; + + // + // Hammer ... + bool isCBarHammer = cHelper + .mBarAnalyser + .IsHammer( + cBar, + cBarDir // + ); + bool isCBarBullishHammer = + isCBarHammer && + IsBullish(cBarDir); + bool isCBarBearishHammer = + isCBarHammer && + IsBearish(cBarDir); + + // + // Rejected ... + bool isCBarRejected = cHelper + .mBarAnalyser + .IsRejected( + cBar, + cBarDir, + false, // Force Type ... + true // Force Fibo Pressure ... + ); + bool isCBarBullishRejected = + isCBarRejected && + IsBullish(cBarDir); + bool isCBarBearishRejected = + isCBarRejected && + IsBearish(cBarDir); + + // + // Engulfed ... + bool isCBarEngulfed = cHelper + .mBarAnalyser + .IsEngulfed( + cBar, + cBarDir // + ); + bool isCBarBullishEngulfed = + isCBarEngulfed && + IsBullish(cBarDir); + bool isCBarBearishEngulfed = + isCBarEngulfed && + IsBearish(cBarDir); + + // + // Momentum ... + bool isCBarMomentum = cHelper + .mBarAnalyser + .IsMomentum( + cBar, + cBarDir, + 1 // + ); + bool isCBarBullishMomentum = + isCBarMomentum && + IsBullish(cBarDir); + bool isCBarBearishMomentum = + isCBarMomentum && + IsBearish(cBarDir); + + // + // Bar Sumarise ... + + // + bool isCBarValidForBullish = + (isCBarBullishHammer || + isCBarBullishRejected || + isCBarBullishMomentum || + isCBarBullishEngulfed); + + // + bool isCBarValidForBearish = + (isCBarBearishHammer || + isCBarBearishRejected || + isCBarBearishMomentum || + isCBarBearishEngulfed); + + // + bool isCBarBreakUpLastPeak = + cBar.IsBullish() && + cBar.GetUp() > peakP && + cBar.GetDown() < peakP; + + // + bool isCBarBreakDownLastPeak = + cBar.IsBearish() && + cBar.GetUp() > peakP && + cBar.GetDown() < peakP; + + // + bool isCBarBreakUpLastVale = + cBar.IsBullish() && + cBar.GetUp() > valeP && + cBar.GetDown() < valeP; + + // + bool isCBarBreakDownLastVale = + cBar.IsBearish() && + cBar.GetUp() > valeP && + cBar.GetDown() < valeP; + + // + bool isCBarBreakUpPeakGolden = + cBar.IsBullish() && + cBar.GetUp() > peaksGoldenC && + cBar.GetDown() < peaksGoldenC; + + // + bool isCBarBreakDownPeakGolden = + cBar.IsBearish() && + cBar.GetUp() > peaksGoldenC && + cBar.GetDown() < peaksGoldenC; + + // + bool isCBarBreakUpValeGolden = + cBar.IsBullish() && + cBar.GetUp() > valesGoldenC && + cBar.GetDown() < valesGoldenC; + + // + bool isCBarBreakDownValeGolden = + cBar.IsBearish() && + cBar.GetUp() > valesGoldenC && + cBar.GetDown() < valesGoldenC; + + // + // Summarize Conditions ... + + // + bool isBoxSignalBullish = + // + hasSelectedBox && + selectedBox.IsBullish() + // + ; + + // + bool isBoxSignalBearish = + // + hasSelectedBox && + selectedBox.IsBearish() + // + ; + + // + bool isConsolidationBoxSignalBullish = + isBoxSignalBullish && + hasSelectedConsolidationBox && + selectedConsolidationBox.IsBullish(); + + // + bool isConsolidationBoxSignalBearish = + isBoxSignalBearish && + hasSelectedConsolidationBox && + selectedConsolidationBox.IsBearish(); + + // + // + // + + // + bool isCond1Bullish = + // + isBoxSignalBullish && + selectedBoxStr > 0 && + isCBarValidForBullish && + (cXConditions.isStrBullish + ? isBarBullishRejectedStr + : true) && + !hasSelectedConsolidationBox && + isBarBullishPriceChangeVPattern + // + ; + + // + bool isCond1Bearish = + // + isBoxSignalBearish && + selectedBoxStr > 0 && + isCBarValidForBearish && + (cXConditions.isStrBearish + ? isBarBearishRejectedStr + : true) && + !hasSelectedConsolidationBox && + isBarBearishPriceChangeVPattern + // + ; + + // + bool isCond2Bullish = + // + isCBarValidForBullish && + isBarBullishPriceChangeVPattern && + isConsolidationBoxSignalBullish && + (isPriceChangeBullishRejectedStr || + isPriceChangeUnderSelectedBoxMid) + // + ; + + bool isCond2Bearish = + // + isCBarValidForBearish && + isBarBearishPriceChangeVPattern && + isConsolidationBoxSignalBearish && + (isPriceChangeBearishRejectedStr || + isPriceChangeOverSelectedBoxMid) + // + ; + + // + bool isCond3Bullish = + // + false + // + ; + + bool isCond3Bearish = + // + false + // + ; + + // + // + // + + // + isBullish = + // + isCond1Bullish || + isCond2Bullish || + isCond3Bullish + // + ; + + // + isBearish = + // + isCond1Bearish || + isCond2Bearish || + isCond3Bearish + // + ; + + // // + // if (isBoxSignalBullish || isBoxSignalBearish) + // { + // Print("Box Has Signal ..."); + // } + + // + // if (isPeaksSame || + // isValesSame) + // { + // // + // long chartId = drawer.ChartIdentification(); + // int subWindow = drawer.SubWindowIdentification(); + + // // + // string name1 = "decision_"; + // string name2 = "analyse_"; + // string name3 = "consolidation_"; + + // // + // CChartObjectTrend *t1Obj; + // t1Obj = new CChartObjectTrend(); + + // // + // CChartObjectTrend *t2Obj; + // t2Obj = new CChartObjectTrend(); + + // // + // CChartObjectTrend *t3Obj; + // t3Obj = new CChartObjectTrend(); + + // // + // color tValeColor = clrAqua; + // color tPeakColor = clrMagenta; + + // // + // datetime from = pBar.time; + // datetime to = zBar.time; + + // // + // if (isPeaksSame) + // { + // // + // // Prepare Names ... + // name1 = name1 + "_Vale"; + // name2 = name2 + "_Vale"; + // name3 = name3 + "_Vale"; + + // // + // // T1 ... + // has = t1Obj.Create( + // chartId, + // name1, + // subWindow, + // from, + // provider.decisionXConditions.valesBuffer[cIDX], + // to, + // provider.decisionXConditions.valesBuffer[cIDX] // + // ); + // if (has) + // { + // t1Obj.Color(tValeColor); + // } + + // // + // // T2 ... + // has = t2Obj.Create( + // chartId, + // name2, + // subWindow, + // from, + // provider.analyseXConditions.valesBuffer[cIDX], + // to, + // provider.analyseXConditions.valesBuffer[cIDX] // + // ); + // if (has) + // { + // t2Obj.Color(tValeColor); + // } + + // // + // // T3 ... + // has = t3Obj.Create( + // chartId, + // name1, + // subWindow, + // from, + // provider.consolidationXConditions.valesBuffer[cIDX], + // to, + // provider.consolidationXConditions.valesBuffer[cIDX] // + // ); + // if (has) + // { + // t3Obj.Color(tValeColor); + // } + // } + + // // + // if (isValesSame) + // { + // // + // // Prepare Names ... + // name1 = name1 + "_Peak"; + // name2 = name2 + "_Peak"; + // name3 = name3 + "_Peak"; + + // // + // // T1 ... + // has = t1Obj.Create( + // chartId, + // name1, + // subWindow, + // from, + // provider.decisionXConditions.peaksBuffer[cIDX], + // to, + // provider.decisionXConditions.peaksBuffer[cIDX] // + // ); + // if (has) + // { + // t1Obj.Color(tPeakColor); + // } + + // // + // // T2 ... + // has = t2Obj.Create( + // chartId, + // name2, + // subWindow, + // from, + // provider.analyseXConditions.peaksBuffer[cIDX], + // to, + // provider.analyseXConditions.peaksBuffer[cIDX] // + // ); + // if (has) + // { + // t2Obj.Color(tPeakColor); + // } + + // // + // // T3 ... + // has = t3Obj.Create( + // chartId, + // name1, + // subWindow, + // from, + // provider.consolidationXConditions.peaksBuffer[cIDX], + // to, + // provider.consolidationXConditions.peaksBuffer[cIDX] // + // ); + // if (has) + // { + // t3Obj.Color(tPeakColor); + // } + // } + + // // + // Print("PVS Same ..."); + // } + + // + if (isConsolidationBoxSignalBullish || + isConsolidationBoxSignalBearish) + { + Print("Has Consolidation Selected Box ..."); + } + + // + // Filling Requirements ... + result = + isBullish || + isBearish; + if (result) + { + // + dir = + isBullish + ? X_DIRECTION_BULLISH + : X_DIRECTION_BEARISH; + + // + box.dir = dir; + box.from = pPBar.time; + box.to = TimeCurrent(); + box.symbol = cBar.symbol; + box.period = cBar.period; + + // + double points = GetPoints(box.symbol); + + // + // Usually is Preffered SL ... + double pivot = 0; + if (isBullish) + { + // + if (isCond1Bullish) + { + pivot = selectedBoxStr; + } + else if (isCond2Bullish) + { + pivot = selectedBoxMid; + } + else if (hasSelectedBox) + { + // + // Default Box SL ... + pivot = selectedBox.lower; + } + else + { + // + // Default Non Box SL ... + pivot = cBar.low; + } + } + else if (isBearish) + { + // + if (isCond1Bearish) + { + pivot = selectedBoxStr; + } + else if (isCond2Bearish) + { + pivot = selectedBoxMid; + } + else if (hasSelectedBox) + { + // + // Default Box SL ... + pivot = selectedBox.upper; + } + else + { + // + // Default Non Box SL ... + pivot = cBar.high; + } + } + + // + // Usually is Current Price or Entry Price ... + double point = GetEntry( + cBar.symbol, + dir // + ); + + // + box.upper = + isBullish + ? point + : pivot; + + // + box.lower = + isBullish + ? pivot + : point; + + // + zone = selectedBox; + } + + // + // Check All Conditions ... + result = + box.IsValid() && + HasDirection(dir) && + (isBullish || + isBearish); + + // + // Cleanup Resources ... + zBar.Clean(); + cBar.Clean(); + pBar.Clean(); + pPBar.Clean(); + cState.Clean(); + cConditions.Clean(); + cConditions.Clean(); + ZeroMemory(cHelper); + selectedBox.Clean(); + cStateEvents.Clean(); + cXConditions.Clean(); + + // + ZeroMemory(drawer); + + // + return result; +} + +// +// +// + +// +bool IsBoxPVPassed( + XBoxZone &box, + X121Conditions &conditions // +) +{ + // + bool result = false; + + // + result = box.IsValid(); + if (!result) + { + return result; + } + + // + // double boxValue = box.lower + ((box.upper - box.lower) / 2); + + // + bool isBullishPassed = + box.IsBullish() && + conditions.valesBuffer[0] < box.upper && + conditions.valesBuffer[0] > box.lower; + + // + bool isBearishPassed = + box.IsBearish() && + conditions.peaksBuffer[0] > box.lower && + conditions.peaksBuffer[0] < box.upper; + + // + result = isBullishPassed || + isBearishPassed; + + // + return result; +} + +// +void CheckBoxStr( + XC121SMCCycleHelper *helper, + XBoxZone &box, + double &value // +) +{ + // + value = 0; + + // + if (!box.IsValid()) + { + return; + } + + // + ENUM_TIMEFRAMES _period = helper.GetPeriod(); + + // + int toIDX = box.ToIndex(_period); + int fromIDX = box.FromIndex(_period); + if (!IsValidIndex(toIDX) || + !IsValidIndex(fromIDX)) + { + return; + } + + // + bool isBullish = box.IsBullish(); + XCX121XSTRHelper *strHelper = helper.mX121Helper.xstrHelper; + for (int i = fromIDX; i >= toIDX; i--) + { + // + double iStr = strHelper.GetSTR(i); + double iPStr = strHelper.GetSTR(i); + double iStrState = strHelper.GetSTRState(i); + + // + bool isSame = iStr == iPStr; + bool isStrBullish = iStrState > 0; + bool isStrBearish = iStrState < 0; + bool isStrInBox = + iStr <= box.upper && + iStr >= box.lower; + + // + if (isSame && isStrInBox) + { + // + if (isBullish && isStrBullish) + { + // + // Min Bullish Str as Support ... + value = + value <= 0 + ? iStr + : value > iStr + ? iStr + : value; + } + else if (!isBullish && isStrBearish) + { + // + // Max Bearish Str as Resistance ... + value = + value <= 0 + ? iStr + : value < iStr + ? iStr + : value; + } + } + } + + // + ZeroMemory(strHelper); + + // +} + +// \ No newline at end of file diff --git a/BKPS/14040203/X121SMCEA/Signals/x-121.smc.xwz.signal.class.mq5 b/BKPS/14040203/X121SMCEA/Signals/x-121.smc.xwz.signal.class.mq5 new file mode 100644 index 0000000..19900f9 --- /dev/null +++ b/BKPS/14040203/X121SMCEA/Signals/x-121.smc.xwz.signal.class.mq5 @@ -0,0 +1,1844 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 X121 SMC Signal Class +// ------------------------------------------------- +// Name: XWZ +// Description: provide all Signalling functions ... +// +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +////////////////////////////////////////////////////// +// +// Global Properties ... +#property library +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://www.saherelm.ir" +#property version "1.00" +#property strict + +// +// Imports ... +#include "../Classes/x-121.smc.market.cycle.helper.class.mq5" +#include "../Libraries/x-121.smc.guard.lib.mq5" +#include "../Libraries/x-121.smc.lib.mq5" +#include "./x-121.smc.xwz.signal.lib.mq5" + +// +// Definition ... +class XCX121SMCXWZSignalDetector : public XCBase +{ + // + public: + // + // Props ... + bool useGuards; + double rfRewar; + bool useQuarterTargets; + X121SMCStrategyXWZWorkingZone workingZone; + X121SMCStrategyXWZSignalConditions mConditions; + X121SMCStrategyXWZSignalConditions mConditionsCollection[]; + + // + // Constructor(s) ... + XCX121SMCXWZSignalDetector( + string _symbol, + ENUM_TIMEFRAMES _period // + ) + { + // + symbol = _symbol; + period = _period; + Init(); + } + + // + // Deconstructor ... + ~XCX121SMCXWZSignalDetector() + { + DeInit(); + } + + // + // + // + + // + // Detect Setup Conditions ... + bool DetectSignalSetup( + // + X121SMCStrategySignalProviderData &provider, + // + double maxAllowedSLDistanceInPoint = 300 + // + ) + { + // + bool result = false; + + // + // Validate Cycle Helpers ... + result = provider.IsValid(); + if (!result) + { + // + mConditions.Clean(); + + // + return result; + } + + // + bool isBullish = false; + bool isBearish = false; + + // + int zIndex = 0; + int cIndex = zIndex + 1; + int pIndex = cIndex + 1; + int ppIndex = pIndex + 1; + + // + int loopback = 10; + + // + mConditions.symbol = symbol; + mConditions.period = period; + + // + double ask = GetAsk(symbol); + double bid = GetBid(symbol); + datetime cTime = TimeCurrent(); + double points = GetPoints(symbol); + + // + // Cycles Conditions ... + result = provider.Prepare( + zIndex, + loopback, + true, // Trigger ... + true, // Decision ... + true, // Analyse ... + true, // Verification ... + true, // Consolidation ... + true // Vision ... + ); + if (!result) + { + // + mConditions.Clean(); + return result; + } + + // + // Select Drawer Class ... + XCPOIDrawer *drawer = provider.visionCycleHelper.mPOIDrawer; + + // + XOHCL consolidationZBar; + result = provider.consolidationCycleHelper.GetBar( + consolidationZBar, + zIndex // + ); + if (!result) + { + // + consolidationZBar.Clean(); + return result; + } + + // + bool drawBar = false; + if (drawBar) + { + // + DrawBar( + consolidationZBar, + drawer // + ); + } + + // + // + // + + // + // Setup Conditions ... + double sls[]; + double sl = 0; + double pivot = 0; + double point = 0; + double targets[]; + double reward = 0; + XSignalBox signalBox; + bool hasTrend = false; + bool hasPriority = false; + double amountPercent = -1; + bool hasSignalBox = false; + bool hasWaitingBoxes = false; + bool hasRewardAmount = false; + ENUM_X_DIRECTION trend = X_DIRECTION_NONE; + ENUM_X_DIRECTION signalBoxDir = X_DIRECTION_NONE; + ENUM_X121SMC_XWZ_PRIORITY priority = X121SMC_XWZ_PRIORITY_NONE; + ENUM_X121SMC_XWZ_PROVIDERS signalProvider = X121SMC_XWZ_PROVIDER_NONE; + + // + // + // + + // + // First We Have to Has Working Zone ... + // bool hasWorkingZone = workingZone.IsValid(); + // if (!hasWorkingZone) + // { + // // + // hasWorkingZone = workingZone.Init( + // symbol, + // period, + // zIndex, + // provider // + // ); + // } + + // // + // // Update Working Zone ... + // if (hasWorkingZone) + // { + // // + // // Reset POI Detector Required POI(s) ... + // provider.MaxRequiredPOIs(50); + + // // + // // Reset POI Detector Allowed Loopback ... + // provider.MaxAllowedLoopbackForInit(578); + + // // + // // Check Working Zone Has Trend ... + // hasTrend = workingZone.DetectTreand( + // X_CYCLE_CONSOLIDATION, + // trend, + // provider, + // zIndex // + // ); + + // // + // // Detectiong Signal Boxes ... + // // hasWaitingBoxes = workingZone + // // .DetectWaitingBoxes( + // // X_CYCLE_ANALYSE, + // // X_CYCLE_DECISION, + // // provider, + // // zIndex // + // // ); + // if (hasWaitingBoxes) + // { + // // + // // Validate Working Zone Waiting Boxes ... + // workingZone.ValidateWaitingBoxes(zIndex); + + // // + // // Double Check Has Waiting Boxes or not ... + // hasWaitingBoxes = workingZone.HasWaitingBoxes(); + // } + + // // + // // Checking Working Zone Destory or not ... + // bool isWorkingZoneDestroyed = workingZone.IsDestroyed( + // zIndex, + // period // + // ); + + // // + // // Cleanup WorkingZone and ignore all conditions ... + // if (isWorkingZoneDestroyed) + // { + // // + // result = false; + // workingZone.Clean(); + // hasWorkingZone = false; + + // // + // // Cleanup Resources ... + // provider.Clean(); + + // // + // mConditions.Clean(); + // consolidationZBar.Clean(); + + // // + // return result; + // } + // } + + // + // Update Models To Time ... + UpdateTo(cTime); + + // + // Draw Working Zone ... + workingZone.Draw( + drawer, + // + false, // Draw Supply Zone ... + false, // Draw Demand Zone ... + true, // Draw Waiting Zones ... + false // Draw Trend ... + ); + + // + // Detect Signal Box ... + hasSignalBox = + // hasWorkingZone && + workingZone.DetectSignalConditions( + signalBox, + signalBoxDir, + signalProvider, + provider, + zIndex // + ); + + // + // Remove Signal Box form + // Waiting Boxes and Breaked Boxes + // if Exists on them, then add it to + // UnAvailable Boxes ... + if (hasSignalBox) + { + // + // Remove Signal Box from UnAvailable Box ... + // if Exists ... + bool hasBreakedBoxes = workingZone + .HasBreakedBoxes(); + if (hasBreakedBoxes) + { + // + int idx = -1; + bool has = FindIndex( + idx, + signalBox, + workingZone.breakedBoxes // + ); + if (has) + { + // + ArrayRemove( + workingZone.breakedBoxes, + idx, + 1 // + ); + } + } + + // + // Add Signal Box to UnAvailable Boxes ... + // if Exists in Waiting Boxes ... + if (hasWaitingBoxes) + { + // + int idx = -1; + bool has = FindIndex( + idx, + signalBox, + workingZone.waitingBoxes // + ); + if (has) + { + // + ArrayRemove( + workingZone.waitingBoxes, + idx, + 1 // + ); + } + } + + // + // Adding to UnAvailable Box ... + AddRef( + signalBox, + workingZone.unavailableBoxes // + ); + } + + // + // + // + + // + // Cleanup Signal if UnApproved ... + if (!hasSignalBox) + { + // + signalBox.Clean(); + signalBoxDir = X_DIRECTION_NONE; + } + + // + // Check Priority Exists ... + // hasPriority = + // hasWorkingZone && + // workingZone + // .DetectPriority( + // priority, + // signalBoxDir, + // zIndex, + // period // + // ); + + // + // Check Price Reward and Amount Exists ... + // hasRewardAmount = + // hasWorkingZone && + // CalculateRiskReward( + // priority, + // reward, + // amountPercent // + // ); + + // + // Check Signal Conditions ... + if (hasSignalBox) + { + // + int idx = -1; + bool has = false; + + // + // Draw Signal Box ... + XCBaseObject *objects[]; + has = drawer.DrawSignalBox( + signalBox, + objects, + clrYellow // + ); + if (has) + { + // + int count = ArraySize(objects); + for (int i = 0; i < count; i++) + { + workingZone.mDrawnObjects.Add(objects[i]); + } + } + Clean(objects); + + // + // Detect Signal Direction ... + isBullish = IsBullish(signalBoxDir); + isBearish = IsBearish(signalBoxDir); + + // + pivot = isBullish + ? signalBox.ob.lower + : signalBox.ob.upper; + + // + point = isBullish + ? signalBox.ob.upper + : signalBox.ob.lower; + + // + double entry = GetEntry( + signalBox.ob.symbol, + signalBoxDir // + ); + + // + // Selecting SL(s) ... + + // + double iSL = 0; + + // + // Default SL ... + iSL = pivot; + + // + Add( + iSL, + sls // + ); + + // + // Select and Provide SL Based on ... + double iAtr = 0; + if (signalProvider == X121SMC_XWZ_PROVIDER_XREJECTED_BOX) + { + // + iAtr = provider.decisionXConditions.atrBuffer[1]; + iAtr *= 0; + + // + // Fix rf Reward ... + rfRewar = 2; + } + else if (signalProvider == X121SMC_XWZ_PROVIDER_XACTIVATED_BOX) + { + // + iAtr = provider.decisionXConditions.atrBuffer[1]; + iAtr *= 0; + + // + Clean(sls); + + // + // Prepare Box fro SL ... + iSL = signalBox.sl; + Add( + iSL, + sls // + ); + + // + // Fix rf Reward ... + rfRewar = 1.5; + } + else if (signalProvider == X121SMC_XWZ_PROVIDER_XBREAKED_BOX) + { + // + iAtr = provider.decisionXConditions.atrBuffer[1]; + iAtr *= 0; + + // + Clean(sls); + + // + // Prepare Box fro SL ... + iSL = pivot; + Add( + iSL, + sls // + ); + + // + // Fix rf Reward ... + rfRewar = 2; + } + else if (signalProvider == X121SMC_XWZ_PROVIDER_XWPVZ) + { + // + iAtr = provider.decisionXConditions.atrBuffer[1]; + iAtr *= 0; + + // + Clean(sls); + + // + // Prepare Box fro SL ... + double risk = pivot - point; + + iSL = risk <= (100 * points) + ? pivot + : isBullish + ? NormalizePrice(entry - (50 * points), signalBox.ob.symbol) + : NormalizePrice(entry + (50 * points), signalBox.ob.symbol); + Add( + iSL, + sls // + ); + + // + // Fix rf Reward ... + rfRewar = 2; + } + + // + Print("XWZ ", ToString(signalBoxDir), " Signal Provided: ", EnumToString(signalProvider)); + + // + // Select Condition SL ... + + // + double slsMin = GetMin(sls); + double slsMax = GetMax(sls); + + // + double longSL = slsMax - iAtr; + double shortSL = slsMin + iAtr; + + // + sl = isBullish + ? longSL + : shortSL; + + // + // Targets ... + + // + double risk = MathAbs(entry - sl); + + // + // Checking risk ... + if (risk >= maxAllowedSLDistanceInPoint) + { + // Print("Max Aloowed Risk Point Reached ..."); + } + + // + // Reward to RF ... + if (rfRewar > 0) + { + // + double iRFReward = rfRewar * risk; + double iRFTP = isBullish + ? entry + iRFReward + : entry - iRFReward; + + // + Add( + iRFTP, + targets // + ); + } + + // + // Based On Priority ... + useQuarterTargets = false; + if (useQuarterTargets) + { + // + has = priority != X121SMC_XWZ_PRIORITY_NONE; + if (has) + { + // + switch (priority) + { + // + case X121SMC_XWZ_PRIORITY_WEAK: + // + if (isBullish) + { + // + // Weak ... + Add( + workingZone.supplyZone.Lower(), + targets // + ); + } + else + { + // + // Weak ... + Add( + workingZone.demandZone.Upper(), + targets // + ); + } + break; + + // + case X121SMC_XWZ_PRIORITY_LOW: + // + if (isBullish) + { + // + // Weak ... + Add( + workingZone.supplyZone.Lower(), + targets // + ); + + // + // Low ... + Add( + workingZone.quarter1, + targets // + ); + } + else + { + // + // Weak ... + Add( + workingZone.demandZone.Upper(), + targets // + ); + + // + // Low ... + Add( + workingZone.quarter3, + targets // + ); + } + break; + + // + case X121SMC_XWZ_PRIORITY_REGULAR: + // + if (isBullish) + { + // + // Weak ... + Add( + workingZone.supplyZone.Lower(), + targets // + ); + + // + // Low ... + Add( + workingZone.quarter1, + targets // + ); + + // + // Regular ... + Add( + workingZone.quarter2, + targets // + ); + } + else + { + // + // Weak ... + Add( + workingZone.demandZone.Upper(), + targets // + ); + + // + // Low ... + Add( + workingZone.quarter3, + targets // + ); + + // + // Regular ... + Add( + workingZone.quarter2, + targets // + ); + } + break; + + // + case X121SMC_XWZ_PRIORITY_HIGH: + // + if (isBullish) + { + // + // Weak ... + Add( + workingZone.supplyZone.Lower(), + targets // + ); + + // + // Low ... + Add( + workingZone.quarter1, + targets // + ); + + // + // Regular ... + Add( + workingZone.quarter2, + targets // + ); + + // + // High ... + Add( + workingZone.quarter3, + targets // + ); + } + else + { + // + // Weak ... + Add( + workingZone.demandZone.Upper(), + targets // + ); + + // + // Low ... + Add( + workingZone.quarter3, + targets // + ); + + // + // Regular ... + Add( + workingZone.quarter2, + targets // + ); + + // + // High ... + Add( + workingZone.quarter1, + targets // + ); + } + break; + + // + case X121SMC_XWZ_PRIORITY_STRONG_HIGH: + // + if (isBullish) + { + // + // Weak ... + Add( + workingZone.supplyZone.Lower(), + targets // + ); + + // + // Low ... + Add( + workingZone.quarter1, + targets // + ); + + // + // Regular ... + Add( + workingZone.quarter2, + targets // + ); + + // + // High ... + Add( + workingZone.quarter3, + targets // + ); + + // + // Strong High ... + Add( + workingZone.demandZone.Upper(), + targets // + ); + } + else + { + // + // Weak ... + Add( + workingZone.demandZone.Upper(), + targets // + ); + + // + // Low ... + Add( + workingZone.quarter3, + targets // + ); + + // + // Regular ... + Add( + workingZone.quarter2, + targets // + ); + + // + // High ... + Add( + workingZone.quarter1, + targets // + ); + + // + // Strong High ... + Add( + workingZone.supplyZone.Lower(), + targets // + ); + } + break; + } + } + } + } + + // + // Summarize Results ... + // result = hasPriority && + // hasSignalBox && + // hasRewardAmount; + result = hasSignalBox; + + // + if (result) + { + // + Copy( + sls, + mConditions.sls // + ); + Copy( + targets, + mConditions.targets // + ); + + // + mConditions.sl = sl; + mConditions.pivot = pivot; + mConditions.point = point; + mConditions.reward = reward; + mConditions.setupTime = cTime; + mConditions.dir = signalBoxDir; + mConditions.priority = priority; + mConditions.signalBox = signalBox.ob; + mConditions.provider = signalProvider; + mConditions.amountPercent = amountPercent; + } + + // + // + // + + // + // Cleanup Resources ... + + // + Clean(sls); + Clean(targets); + + // + provider.Clean(); + + // + signalBox.Clean(); + consolidationZBar.Clean(); + + // + return result; + } + + // + // Detect Trigger Conditions ... + bool DetectSignalTrigger( + // + X121SMCStrategyXWZSignalConditions &conditions, + // + X121SMCStrategySignalProviderData &provider, + // + int maxAllowedSetupAge = 60 + // + ) + { + // + bool result = false; + + // + result = + // + provider.IsValid() + // + ; + if (!result) + { + return result; + } + + // + result = conditions.IsSetuped(); + if (!result) + { + return result; + } + + // + datetime setupTime = conditions.setupTime; + ENUM_X_DIRECTION setupDir = conditions.dir; + + // + bool isBullish = IsBullish(setupDir); + bool isBearish = IsBearish(setupDir); + + // + int zIndex = 0; + int cIndex = zIndex + 1; + int pIndex = cIndex + 1; + int ppIndex = pIndex + 1; + + // + int loopback = 10; + + // + double ask = GetAsk(symbol); + double bid = GetBid(symbol); + datetime cTime = TimeCurrent(); + double points = GetPoints(symbol); + + // + // Cycles Conditions ... + result = provider.Prepare( + zIndex, + loopback // + ); + if (!result) + { + return result; + } + + // + double iAtr = provider.decisionXConditions.atrBuffer[1]; + iAtr *= 1.5; + + // + // Check Signal Validation ... + // IMPORTANT: since all Validations done in SetUp Process ... + // here we only Execute Signal ... + + // + result = isBullish || + isBearish; + + // + if (result) + { + // + conditions.triggerTime = cTime; + conditions.type = isBullish + ? X_POSITION_TYPE_LONG + : X_POSITION_TYPE_SHORT; + + // + } + + // + // Cleanup ... + + // + provider.Clean(); + + // + return result; + } + + // + // Detect Guards ... + bool DetectGuards( + // + X121SMCGuard &guards[], + const XPosition &positions[], + // + X121SMCStrategySignalProviderData &provider + // + ) + { + // + bool result = false; + + // + if (!useGuards) + { + return result; + } + + // + Clean(guards); + + // + // Set Provider for Common Guards ... + string signalProvider = ToString(X_121_SMC_PROVIDER_XWZ); + + // + int zIndex = 0; + int cIndex = zIndex + 1; + int pIndex = cIndex + 1; + int ppIndex = pIndex + 1; + + // + XOHCL cBar; + + // + int loopback = 10; + + // + double ask = GetAsk(symbol); + double bid = GetBid(symbol); + datetime cTime = TimeCurrent(); + double points = GetPoints(symbol); + + // + // Cycles Conditions ... + result = provider.IsValid(); + result = + result && + provider.Prepare( + zIndex, + loopback // + ); + if (!result) + { + // + provider.Clean(); + return result; + } + + // + // Select Own Positions ... + int count = ArraySize(positions); + result = IsValidSize(count); + if (!result) + { + return result; + } + + // + XPosition ownPositions[]; + XPosition ownLongPositions[]; + XPosition ownShortPositions[]; + for (int i = 0; i < count; i++) + { + // + XPosition iPosition = positions[i]; + bool isOwn = iPosition + .IsFiltersPassed( + symbol, + signalProvider, + NULL, + X_POSITION_TYPE_ALL, + iPosition.magic // + ); + if (isOwn) + { + // + AddRef( + iPosition, + ownPositions // + ); + + // + bool isLong = IsLong(positions[i].type); + if (isLong) + { + // + AddRef( + iPosition, + ownLongPositions // + ); + } + else + { + // + AddRef( + iPosition, + ownShortPositions // + ); + } + } + } + + // + // Check Extracted Positions ... + + // + count = ArraySize(ownPositions); + + // + int longsCount = ArraySize(ownLongPositions); + bool hasLongs = IsValidSize(longsCount); + + // + int shortsCount = ArraySize(ownShortPositions); + bool hasShorts = IsValidSize(shortsCount); + + // + // Validate Own Positions ... + result = IsValidSize(count); + if (!result) + { + // + Clean(ownPositions); + Clean(ownLongPositions); + Clean(ownShortPositions); + + // + return result; + } + + // + // + // + + // + // Get Global and Common Guards ... + + // + // ENUM_X_121_SMC_GUARD_ACTIONS ignoreGuards[1] = { + // X_121_SMC_GUARD_ACTION_TRAIL_STOP // + // }; + // result = DetectX121SMCGuards( + // signalProvider, + // guards, + // positions, + // provider, + // // + // ignoreGuards + // // + // ); + + // + // + // + + // + // Implement Custom Implemented Guards ... + + // + // Here we Are Sure there is Positions to Guard ... + // based on Current Provider ... + + // + // Selected Consolidation Zones ... + + // + int idx = -1; + bool has = false; + + // + bool hasBullishConsolidationZone = false; + XConsolidationZone bullishConsolidationZone; + has = provider.decisionState.HasBullishConsolidationZones(); + if (has) + { + // + idx = GetYoungest(provider.decisionState.bullishConsolidationZones); + hasBullishConsolidationZone = IsValidIndex(idx); + if (hasBullishConsolidationZone) + { + bullishConsolidationZone = provider.decisionState.bullishConsolidationZones[idx]; + } + } + + // + bool hasBearishConsolidationZone = false; + XConsolidationZone bearishConsolidationZone; + has = provider.decisionState.HasBearishConsolidationZones(); + if (has) + { + // + idx = GetYoungest(provider.decisionState.bearishConsolidationZones); + hasBearishConsolidationZone = IsValidIndex(idx); + if (hasBearishConsolidationZone) + { + bearishConsolidationZone = provider.decisionState.bearishConsolidationZones[idx]; + } + } + + // + XBoxZone bullishBox; + bool hasBullishBox = false; + bool isBullishBoxBreaked = false; + if (!hasBullishBox) + { + // + XCOrderBlock *ob = NULL; + idx = GetYoungest(provider.analyseState.bullishOrderBlocks); + has = IsValidIndex(idx); + if (has) + { + // + ob = provider.analyseState.bullishOrderBlocks[idx]; + + // + hasBullishBox = ToBox( + bullishBox, + ob // + ); + } + + // + if (!hasBullishBox) + { + bullishBox.Clean(); + } + + // + ZeroMemory(ob); + } + + // + XBoxZone bearishBox; + bool hasBearishBox = false; + bool isBearishBoxBreaked = false; + if (!hasBearishBox) + { + // + XCOrderBlock *ob = NULL; + idx = GetYoungest(provider.analyseState.bearishOrderBlocks); + has = IsValidIndex(idx); + if (has) + { + // + ob = provider.analyseState.bearishOrderBlocks[idx]; + + // + hasBearishBox = ToBox( + bearishBox, + ob // + ); + } + + // + if (!hasBearishBox) + { + bearishBox.Clean(); + } + + // + ZeroMemory(ob); + } + + // + // Here We Have all Requirements for Guarding Positions ... + + // + // Available Guards: + // X_121_SMC_GUARD_ACTION_NONE + // X_121_SMC_GUARD_ACTION_CLOSE + // X_121_SMC_GUARD_ACTION_CLOSE_ALL + // X_121_SMC_GUARD_ACTION_CLOSE_LONGS + // X_121_SMC_GUARD_ACTION_CLOSE_SHORTS + // X_121_SMC_GUARD_ACTION_PARTIAL_CLOSE + // X_121_SMC_GUARD_ACTION_TRAIL_STOP + // X_121_SMC_GUARD_ACTION_TRAIL_TARGET + // X_121_SMC_GUARD_ACTION_HEDGE + + // + // X_121_SMC_GUARD_ACTION_CLOSE: + // Close Specified Position on Specified Conditions ... + + // + // X_121_SMC_GUARD_ACTION_CLOSE_ALL: + // Close All Positions on Specified Conditions ... + + // + // X_121_SMC_GUARD_ACTION_CLOSE_LONGS: + // Close All Long Positions on Specified Conditions ... + + // + // X_121_SMC_GUARD_ACTION_CLOSE_SHORTS: + // Close All Short Positions on Specified Conditions ... + + // + // X_121_SMC_GUARD_ACTION_PARTIAL_CLOSE: + // Partial Close Specified Position on Specified Conditions ... + + // + // X_121_SMC_GUARD_ACTION_TRAIL_STOP: + // Trail Stop Specified Position on Specified Conditions ... + bool handleStoptrailingBasedOnBoxes = true; + bool handleStoptrailingBasedOnConsolidationZones = true; + for (int i = 0; i < count; i++) + { + // + XPosition iPosition = ownPositions[i]; + + // + bool isInited = cBar.Init( + iPosition.symbol, + iPosition.period, + cIndex // + ); + + // + isBullishBoxBreaked = + isInited && + hasBullishBox && + cBar.high < bullishBox.lower; + + // + isBearishBoxBreaked = + isInited && + hasBearishBox && + cBar.low > bearishBox.upper; + + // + bool isLong = IsLong(iPosition.type); + bool isInProfit = iPosition.profit > 0; + + // + double sl = iPosition.sl; + double tp = iPosition.tp; + + // + // Trail Stops Using Consolidation Zones ... + + // + bool canTraiLonglUsingCZone = + // + handleStoptrailingBasedOnConsolidationZones && + // + (isLong && + isInProfit && + hasBullishConsolidationZone && + bullishConsolidationZone.lower > iPosition.sl && + bullishConsolidationZone.lower > iPosition.entry) + // + ; + if (canTraiLonglUsingCZone) + { + sl = bullishConsolidationZone.lower; + } + + // + bool canTraiShortlUsingCZone = + // + handleStoptrailingBasedOnConsolidationZones && + // + (!isLong && + isInProfit && + hasBearishConsolidationZone && + bearishConsolidationZone.upper < iPosition.sl && + bearishConsolidationZone.upper < iPosition.entry) + // + ; + if (canTraiShortlUsingCZone) + { + sl = bearishConsolidationZone.upper; + } + + // + bool canTrailUsingCZone = + canTraiLonglUsingCZone || + canTraiShortlUsingCZone; + + // + // Trail Stop Using Boxes ... + + // + bool canTraiLonglUsingBox = + // + handleStoptrailingBasedOnBoxes && + // + (isLong && + isInProfit && + hasBullishBox && + bullishBox.lower > iPosition.sl && + bullishBox.lower > iPosition.entry) + // + ; + if (canTraiLonglUsingBox) + { + sl = bullishBox.lower; + } + + // + bool canTraiShortlUsingBox = + // + handleStoptrailingBasedOnBoxes && + // + (!isLong && + isInProfit && + hasBearishBox && + bearishBox.upper < iPosition.sl && + bearishBox.upper < iPosition.entry) + // + ; + if (canTraiShortlUsingBox) + { + sl = bearishBox.upper; + } + + // + bool canTrailUsingBox = + canTraiLonglUsingBox || + canTraiShortlUsingBox; + + // + bool canTraiLonglUsingBreakedBox = + // + handleStoptrailingBasedOnBoxes && + // + (isLong && + isInProfit && + isBearishBoxBreaked && + bearishBox.upper > iPosition.sl && + bearishBox.upper > iPosition.entry) + // + ; + if (canTraiLonglUsingBreakedBox) + { + sl = bearishBox.upper; + } + + // + bool canTraiShortlUsingBreakedBox = + // + handleStoptrailingBasedOnBoxes && + // + (!isLong && + isInProfit && + isBullishBoxBreaked && + bullishBox.lower < iPosition.sl && + bullishBox.lower < iPosition.entry) + // + ; + if (canTraiShortlUsingBreakedBox) + { + sl = bullishBox.lower; + } + + // + bool canTrailUsingBreakedBox = + canTraiLonglUsingBreakedBox || + canTraiShortlUsingBreakedBox; + + // + // Summarize SL ... + + // + bool isSLPassed = + sl > 0 && + (isLong + ? iPosition.price - sl >= points * 15 + : sl - iPosition.price >= points * 15); + + // + bool canTrail = + isSLPassed && + (canTrailUsingBox || + canTrailUsingCZone || + canTrailUsingBreakedBox); + if (canTrail) + { + // + X121SMCGuard iGuard; + + // + iGuard.time = cTime; + iGuard.symbol = symbol; + iGuard.provider = signalProvider; + iGuard.action = X_121_SMC_GUARD_ACTION_TRAIL_STOP; + + // + iGuard.ticket = iPosition.ticket; + + // + iGuard.sl = sl; + + // + AddGuard( + iGuard, + guards // + ); + } + } + + // + // X_121_SMC_GUARD_ACTION_TRAIL_TARGET: + // Trail Target Specified Position on Specified Conditions ... + + // + // X_121_SMC_GUARD_ACTION_HEDGE: + // Hedge all Positions on Specified Conditions ... + + // + // Cleanup Collections ... + + // + cBar.Clean(); + + // + provider.Clean(); + + // + bullishBox.Clean(); + bearishBox.Clean(); + + // + bullishConsolidationZone.Clean(); + bearishConsolidationZone.Clean(); + + // + count = ArraySize(guards); + result = IsValidSize(count); + + // + return result; + } + + // + // Add Conditions to Conditions Collection ... + int AddConditionsIfNotExists( + int maxAllowed = 10 // + ) + { + // + int result = 0; + + // + bool isSetuped = IsValid(mConditions.setupTime) && + HasDirection(mConditions.dir); + if (!isSetuped) + { + return result; + } + + // + int count = ArraySize(mConditionsCollection); + if (IsValidSize(count)) + { + // + // Copy Original Items ... + X121SMCStrategyXWZSignalConditions tmpItems[]; + Copy( + mConditionsCollection, + tmpItems // + ); + + // + // Prese Item Data ... + bool isBullish = IsBullish(mConditions.dir); + + // + for (int i = 0; i < count; i++) + { + // + X121SMCStrategyXWZSignalConditions iItem = tmpItems[i]; + + // + bool canRemove = mConditions.dir == iItem.dir && + mConditions.pivot == iItem.pivot; + if (canRemove) + { + // + ArrayRemove( + mConditionsCollection, + i, + 1 // + ); + } + } + + // + Clean(tmpItems); + } + + // + AddRef( + mConditions, + mConditionsCollection // + ); + + // + // Remove Olds ... + CleanupArray( + mConditionsCollection, + maxAllowed // + ); + + // + result = ArraySize(mConditionsCollection); + + // + return result; + } + + // + // Draw Functions ... + // + + // + void DrawBar( + XOHCL &bar, + XCPOIDrawer *drawer, + bool forceClean = true // + ) + { + // + if (forceClean) + { + mBarObjects.Clear(); + } + + // + if (drawer == NULL || + !bar.IsValid()) + { + return; + } + + // + bool isBullish = bar.IsBullish(); + + // + int widthBar = 2; + bool fillShadowsBar = true; + ENUM_LINE_STYLE styleBar = STYLE_SOLID; + color clrBar = + isBullish + ? clrAqua + : clrMagenta; + + // + datetime to = bar.NextAt(); + + // + XCOHCLObject *iObj; + bool isCreated = drawer + .CreateBar( + bar, + iObj, + to // + ); + if (isCreated) + { + // + iObj.BarSpes( + widthBar, + clrBar, + styleBar // + ); + + // + iObj.LowShadowFill(fillShadowsBar); + iObj.HighShadowFill(fillShadowsBar); + + // + mBarObjects.Add(iObj); + } + } + + // + protected: + // + + // + private: + // + // Props ... + string symbol; + ENUM_TIMEFRAMES period; + CArrayObj mObjects; + CArrayObj mBarObjects; + CArrayObj mWorkingZoneObjects; + + /** + * Initialize ... + */ + void Init() + { + // + rfRewar = 2; + useGuards = false; + useQuarterTargets = false; + } + + /** + * DeInitialize ... + */ + void DeInit() + { + // + mConditions.Clean(); + workingZone.Clean(); + Clean(mConditionsCollection); + + // + mBarObjects.Clear(); + } + + /** + * Update To Time of Exists Components ... + * + * @param value: updated time ... + */ + void UpdateTo( + datetime value = NULL // + ) + { + // + value = NormalizeTime(value); + + // + workingZone.UpdateTo(value); + } + + // + // Helpers ... + + // + bool CalculateRiskReward( + ENUM_X121SMC_XWZ_PRIORITY priority, + double &reward, + double &amountPercent // + ) + { + // + bool result = false; + + // + reward = 0; + amountPercent = 0; + + // + result = priority != X121SMC_XWZ_PRIORITY_NONE; + if (!result) + { + return result; + } + + // + switch (priority) + { + // + case X121SMC_XWZ_PRIORITY_STRONG_HIGH: + // + reward = 6; + amountPercent = 2; + break; + + // + case X121SMC_XWZ_PRIORITY_HIGH: + // + reward = 4; + amountPercent = 2; + break; + + // + case X121SMC_XWZ_PRIORITY_REGULAR: + // + reward = 3; + amountPercent = 1.5; + break; + + // + case X121SMC_XWZ_PRIORITY_LOW: + // + reward = 2; + amountPercent = 1; + break; + + // + case X121SMC_XWZ_PRIORITY_WEAK: + // + reward = 1; + amountPercent = 0.5; + break; + } + + // + result = + // + reward > 0 && + amountPercent > 0 + // + ; + + // + return result; + } + + // +}; + +// \ No newline at end of file diff --git a/BKPS/14040203/X121SMCEA/Signals/x-121.smc.xwz.signal.lib.mq5 b/BKPS/14040203/X121SMCEA/Signals/x-121.smc.xwz.signal.lib.mq5 new file mode 100644 index 0000000..8f43bce --- /dev/null +++ b/BKPS/14040203/X121SMCEA/Signals/x-121.smc.xwz.signal.lib.mq5 @@ -0,0 +1,2784 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 X121 SMC Signal Class +// ------------------------------------------------- +// Name: XWZ +// Description: provide all Signalling functions ... +// +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +////////////////////////////////////////////////////// +// +// Global Properties ... +#property library +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://www.saherelm.ir" +#property version "1.00" +#property strict + +// +// Imports ... +// #include "../../Libraries/x-trade.lib" +#include "../Classes/x-121.smc.market.cycle.helper.class.mq5" +#include "../Libraries/x-121.smc.guard.lib.mq5" +#include "../Libraries/x-121.smc.lib.mq5" + +// +// Provided Signals Enumeration ... +enum ENUM_X121SMC_XWZ_PROVIDERS +{ + X121SMC_XWZ_PROVIDER_NONE, + X121SMC_XWZ_PROVIDER_XWPVZ, + X121SMC_XWZ_PROVIDER_XFVGMA, + X121SMC_XWZ_PROVIDER_XBREAKED_BOX, + X121SMC_XWZ_PROVIDER_XREJECTED_BOX, + X121SMC_XWZ_PROVIDER_XACTIVATED_BOX, +}; + +// +// Provided Priority based on Working Zone and +// Quarter Places ... +enum ENUM_X121SMC_XWZ_PRIORITY +{ + X121SMC_XWZ_PRIORITY_NONE, + X121SMC_XWZ_PRIORITY_WEAK, + X121SMC_XWZ_PRIORITY_LOW, + X121SMC_XWZ_PRIORITY_REGULAR, + X121SMC_XWZ_PRIORITY_HIGH, + X121SMC_XWZ_PRIORITY_STRONG_HIGH, +}; + +// +// Definitions ... + +// +// XWZ Working Zone Model ... +struct X121SMCStrategyXWZWorkingZone +{ + // + // Props ... + + // + string symbol; + ENUM_TIMEFRAMES period; + + // + double quarter1; + double quarter2; + double quarter3; + + // + XCSupplyZone *supplyZone; + XCDemandZone *demandZone; + + // + XBoxZone support; + XBoxZone resistance; + ENUM_X_DIRECTION trend; + + // + XSignalBox waitingBoxes[]; + XSignalBox breakedBoxes[]; + XSignalBox unavailableBoxes[]; + + // + CArrayObj mDrawnObjects; + CArrayObj mWorkingZoneObjects; + + // + // Constructor ... + X121SMCStrategyXWZWorkingZone() + { + Clean(); + } + + // + // Properties ... + + /** + * Check Working Zone has Supply Zone as Upper Boundary ... + * + * @return ( bool ) + */ + bool HasSupplyZone() + { + return supplyZone != NULL && + supplyZone.IsValid(); + } + + /** + * Check Working Zone has Demand Zone as Lower Boundary ... + * + * @return ( bool ) + */ + bool HasDemandZone() + { + return demandZone != NULL && + demandZone.IsValid(); + } + + /** + * Check Working Zone has Waiting Boxes or not ... + * + * @return ( bool ) + */ + bool HasWaitingBoxes() + { + return HasChild(waitingBoxes); + } + + /** + * Count Working Zone's Waiting Boxes ... + * + * @return ( int ) + */ + int CountWaitingBoxes() + { + return ArraySize(waitingBoxes); + } + + /** + * Check Working Zone has Breaked Boxes or not ... + * + * @return ( bool ) + */ + bool HasBreakedBoxes() + { + return HasChild(breakedBoxes); + } + + /** + * Count Working Zone's Breaked Boxes ... + * + * @return ( int ) + */ + int CountBreakedBoxes() + { + return ArraySize(breakedBoxes); + } + + /** + * Check Working Zone has Unavailable Boxes or not ... + * + * @return ( bool ) + */ + bool HasUnavailableBoxes() + { + return HasChild(unavailableBoxes); + } + + /** + * Count Working Zone's Unavailable Boxes ... + * + * @return ( int ) + */ + int CountUnavailableBoxes() + { + return ArraySize(unavailableBoxes); + } + + // + // Tools ... + + /** + * Cleanup Model ... + */ + void Clean() + { + // + quarter1 = 0; + quarter2 = 0; + quarter3 = 0; + + // + symbol = NULL; + period = NULL; + + // + Clean(waitingBoxes); + Clean(breakedBoxes); + Clean(unavailableBoxes); + + // + ZeroMemory(supplyZone); + ZeroMemory(demandZone); + + // + mDrawnObjects.Clear(); + mWorkingZoneObjects.Clear(); + } + + /** + * Validate Model ... + * + * @return ( bool ) + */ + bool IsValid() + { + // + bool result = false; + + // + result = + // + quarter1 > 0 && + quarter2 > 0 && + quarter3 > 0 && + HasSupplyZone() && + HasDemandZone() && + quarter1 > quarter2 && + quarter2 > quarter3 + // + ; + + // + return result; + } + + /** + * Checking a Box Exists in Collections or not ... + * + * @param box: XBoxZone instance reference ... + * + * @return ( bool ) + */ + bool IsExists(XSignalBox &box) + { + // + bool result = false; + + // + // Check Validation ... + result = box.IsValid() && + (HasWaitingBoxes() || + HasBreakedBoxes() || + HasUnavailableBoxes()); + if (!result) + { + return result; + } + + // + int idx = -1; + bool has = false; + + // + // Check Index in Waiting Boxes ... + has = HasWaitingBoxes(); + if (has) + { + // + result = FindIndex( + idx, + box, + waitingBoxes // + ); + if (result) + { + return result; + } + } + + // + // Check Index in Breaked Boxes ... + has = HasBreakedBoxes(); + if (has) + { + // + result = FindIndex( + idx, + box, + breakedBoxes // + ); + if (result) + { + return result; + } + } + + // + // Check Index in Unavailable Boxes ... + has = HasUnavailableBoxes(); + if (has) + { + // + result = FindIndex( + idx, + box, + unavailableBoxes // + ); + if (result) + { + return result; + } + } + + // + return result; + } + + /** + * Initialize Working Zone ... + * + * @param _symbol: String ... + * @param _period: ENUM_TIMEFRAMES member ... + * @param barIndex: int ... + * @param provider: X121SMCStrategySignalProviderData instance reference ... + * + * @return ( bool ) + */ + bool Init( + string _symbol, + ENUM_TIMEFRAMES _period, + int barIndex, + X121SMCStrategySignalProviderData &provider // + ) + { + // + bool result = false; + + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + result = + // + IsValid(_symbol) && + IsValid(_period) && + // + provider.IsValid() + // + ; + if (!result) + { + return result; + } + + // + symbol = _symbol; + period = _period; + + // + int idx = -1; + int count = 0; + bool has = false; + + // + XOHCL zBar; + has = zBar.Init( + symbol, + period, + barIndex // + ); + result = has; + if (!result) + { + zBar.Clean(); + return result; + } + double ll5 = zBar.FindLowest(5, MODE_LOW); + double hh5 = zBar.FindHighest(5, MODE_HIGH); + zBar.Clean(); + + // + // Supply Zone ... + has = HasSupplyZone(); + if (!has) + { + // + idx = GetHighest(provider + .consolidationState + .supplyZones // + ); + has = IsValidIndex(idx); + if (has) + { + // + supplyZone = provider + .consolidationState + .supplyZones[idx]; + has = hh5 < supplyZone.Lower(); + if (!has) + { + supplyZone = NULL; + } + } + } + + // + // Demand Zone ... + has = HasDemandZone(); + if (!has) + { + // + idx = GetLowest(provider + .consolidationState + .demandZones // + ); + has = IsValidIndex(idx); + if (has) + { + // + demandZone = provider + .consolidationState + .demandZones[idx]; + has = ll5 > demandZone.Upper(); + if (!has) + { + demandZone = NULL; + } + } + } + + // + if (supplyZone != NULL && + demandZone != NULL && + supplyZone.IsValid() && + demandZone.IsValid()) + { + // + double upper = supplyZone.Lower(); + double lower = demandZone.Upper(); + + // + double delta = ((upper - lower) / 100) * 25; + + // + quarter1 = upper - (1 * delta); + quarter2 = upper - (2 * delta); + quarter3 = upper - (3 * delta); + } + + // + result = IsValid(); + if (!result) + { + Clean(); + } + + // + return result; + } + + /** + * Detect Signal Boxes ... + * + * @param cycle: ENUM_X_CYCLES member ... + * @param provider: X121SMCStrategySignalProviderData instance reference ... + * @param barIndex: int ... + * + * @return ( bool ) + */ + bool DetectWaitingBoxes( + ENUM_X_CYCLES obCycle, + ENUM_X_CYCLES fvgCycle, + X121SMCStrategySignalProviderData &provider, + int barIndex = 0 // + ) + { + // + bool result = false; + + // + int idx = -1; + int count = 0; + bool has = false; + datetime cTime = TimeCurrent(); + + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + // Select OB Cycle ... + XPOIState obState; + XPOIStateEvents obStateEvents; + X121Conditions obXConditions; + XC121SMCCycleHelper *obHelper; + X121SMCCycleConditions obConditions; + result = provider.SelectCycle( + obCycle, + obState, + obStateEvents, + obXConditions, + obHelper, + obConditions // + ); + if (!result) + { + // + obState.Clean(); + ZeroMemory(obHelper); + obConditions.Clean(); + obStateEvents.Clean(); + obXConditions.Clean(); + + // + return result; + } + + // + // Select FVG Cycle ... + XPOIState fvgState; + XPOIStateEvents fvgStateEvents; + X121Conditions fvgXConditions; + XC121SMCCycleHelper *fvgHelper; + X121SMCCycleConditions fvgConditions; + result = provider.SelectCycle( + fvgCycle, + fvgState, + fvgStateEvents, + fvgXConditions, + fvgHelper, + fvgConditions // + ); + if (!result) + { + // + obState.Clean(); + ZeroMemory(obHelper); + obConditions.Clean(); + obStateEvents.Clean(); + obXConditions.Clean(); + + // + fvgState.Clean(); + ZeroMemory(fvgHelper); + fvgConditions.Clean(); + fvgStateEvents.Clean(); + fvgXConditions.Clean(); + + // + return result; + } + + // + // Detect a Sharp Zone Which Contains + // an Order Block and Also an FVG ... + if (obStateEvents.hasNewSharp) + { + // + XBoxZone ob; + XBoxZone fvg; + XBoxZone currSharp; + XBoxZone prevSharp; + XBoxZone sharpConsolidation; + + // + // Retrieve Current Sharp ... + XBoxZone tmpBoxes[]; + Copy( + obState.sharps, + tmpBoxes // + ); + idx = GetYoungest(tmpBoxes); + has = IsValidIndex(idx); + if (has) + { + // + currSharp = tmpBoxes[idx]; + bool isBullish = currSharp.IsBullish(); + + // + ArrayRemove( + tmpBoxes, + idx, + 1 // + ); + + // + while (HasChild(tmpBoxes)) + { + // + idx = GetYoungest(tmpBoxes); + has = IsValidIndex(idx); + + // + if (!has) + { + break; + } + + // + XBoxZone iBox = tmpBoxes[idx]; + ArrayRemove( + tmpBoxes, + idx, + 1 // + ); + + // + if (iBox.dir == currSharp.dir) + { + // + prevSharp = iBox; + iBox.Clean(); + break; + } + + // + iBox.Clean(); + } + + // + Clean(tmpBoxes); + } + Clean(tmpBoxes); + + // + // Preparing Sharp Consolidation Box ... + has = currSharp.IsValid() && + prevSharp.IsValid() && + prevSharp.lower < currSharp.upper; + if (has) + { + // + sharpConsolidation.type = "XSHCNZ"; + sharpConsolidation.dir = currSharp.dir; + sharpConsolidation.symbol = currSharp.symbol; + sharpConsolidation.period = currSharp.period; + + // + sharpConsolidation.from = prevSharp.to; + sharpConsolidation.to = currSharp.from; + + // + int toIDX = GetBarIndex( + currSharp.symbol, + currSharp.period, + sharpConsolidation.to // + ); + int fromIDX = GetBarIndex( + currSharp.symbol, + currSharp.period, + sharpConsolidation.from // + ); + int length = fromIDX - toIDX; + + // + XOHCL toBar; + has = toBar.Init( + sharpConsolidation.symbol, + sharpConsolidation.period, + toIDX // + ); + + // + if (has) + { + // + double upper = toBar.FindHighest( + length, + MODE_HIGH // + ); + + // + double lower = toBar.FindLowest( + length, + MODE_LOW // + ); + + // + sharpConsolidation.upper = upper; + sharpConsolidation.lower = lower; + } + + // + // Detect Order Block / FVG ... + has = sharpConsolidation.IsValid(); + if (has) + { + // + // Check Direction ... + bool isBullish = sharpConsolidation.IsBullish(); + + // + // Find Inside Order Block ... + Clean(tmpBoxes); + if (isBullish) + { + // + ToBox( + obState.bullishOrderBlocks, + tmpBoxes // + ); + } + else + { + // + ToBox( + obState.bearishOrderBlocks, + tmpBoxes // + ); + } + + // + // Select Order Block ... + has = HasChild(tmpBoxes); + if (has) + { + // + while (HasChild(tmpBoxes)) + { + // + idx = GetYoungest(tmpBoxes); + has = IsValidIndex(idx); + if (!has) + { + break; + } + + // + XBoxZone iBox = tmpBoxes[idx]; + ArrayRemove( + tmpBoxes, + idx, + 1 // + ); + + // + // Validate Selected Box ... + bool isDirPassed = iBox.dir == sharpConsolidation.dir; + bool isFromPassed = iBox.from > sharpConsolidation.from; + bool isInsidePassed = IsBoxInside( + iBox, + sharpConsolidation // + ); + bool isValidationPassed = IsBoxValid( + iBox, + barIndex // + ); + + // + has = isDirPassed && + isFromPassed && + isInsidePassed && + isValidationPassed; + if (has) + { + ob = iBox; + } + + // + iBox.Clean(); + + // + if (ob.IsValid()) + { + break; + } + } + } + Clean(tmpBoxes); + + // + // Find Inside FVG ... + has = ob.IsValid(); + if (has) + { + // + Clean(tmpBoxes); + if (isBullish) + { + // + ToBox( + fvgState.bullishFairValueGaps, + tmpBoxes // + ); + } + else + { + // + ToBox( + fvgState.bearishFairValueGaps, + tmpBoxes // + ); + } + + // + // Select FVG ... + has = HasChild(tmpBoxes); + if (has) + { + // + while (HasChild(tmpBoxes)) + { + // + idx = isBullish + ? GetLowest(tmpBoxes) + : GetHighest(tmpBoxes); + has = IsValidIndex(idx); + if (!has) + { + break; + } + + // + XBoxZone iBox = tmpBoxes[idx]; + ArrayRemove( + tmpBoxes, + idx, + 1 // + ); + + // + // Validate Selected Box ... + bool isDirPassed = iBox.dir == ob.dir; + bool isFromPassed = iBox.from > ob.from; + bool isInsidePassed = IsBoxInside( + iBox, + ob // + ); + + // + has = isDirPassed && + isFromPassed && + isInsidePassed; + if (has) + { + fvg = iBox; + } + + // + iBox.Clean(); + + // + if (fvg.IsValid()) + { + break; + } + } + } + Clean(tmpBoxes); + } + } + + // + // Checking Validation of Boxes ... + has = ob.IsValid() && + fvg.IsValid() && + sharpConsolidation.IsValid(); + if (has) + { + // + // Update Time ... + ob.to = cTime; + fvg.to = cTime; + sharpConsolidation.to = cTime; + + // + XSignalBox iSBox; + + // + iSBox.ob = ob; + iSBox.fvg = fvg; + iSBox.sharp = sharpConsolidation; + + // + has = iSBox.IsValid(); + if (has) + { + // + AddRef( + iSBox, + waitingBoxes // + ); + } + + // + iSBox.Clean(); + } + + // + ob.Clean(); + fvg.Clean(); + toBar.Clean(); + currSharp.Clean(); + prevSharp.Clean(); + sharpConsolidation.Clean(); + } + + // + Clean(tmpBoxes); + currSharp.Clean(); + prevSharp.Clean(); + sharpConsolidation.Clean(); + } + + // + // Preparing Waiting Box based on FVG State ... + if (fvgStateEvents.hasNewSharp) + { + // + // Select Newest Sharp Change ... + XBoxZone sharp; + idx = GetYoungest(fvgState.sharps); + has = IsValidIndex(idx); + if (has) + { + // + XOHCL endBar; + XOHCL startBar; + int totalBars = 0; + int orderBlocksIDX[]; + int bullBarsCount = 0; + int bearBarsCount = 0; + int validPercent = 75; + + // + sharp = fvgState.sharps[idx]; + sharp.type = "XSHPOBX"; + bool isSharpBullish = sharp.IsBullish(); + + // + // Validate End Bar ... + if (sharp.IsValid()) + { + // + // Validate End Bar Direction ... + int endBarIDX = GetBarIndex( + sharp.symbol, + sharp.period, + sharp.to // + ); + + // + has = endBar.Init( + sharp.symbol, + sharp.period, + endBarIDX + 1 // + ); + + // + if (has) + { + // + has = sharp.dir == endBar.GetDirection(); + if (!has) + { + sharp.Clean(); + } + } + } + + // + // Validate Start Bar ... + if (sharp.IsValid()) + { + // + // Validate Start Bar Direction ... + int startBarIDX = GetBarIndex( + sharp.symbol, + sharp.period, + sharp.from // + ); + + // + has = startBar.Init( + sharp.symbol, + sharp.period, + startBarIDX + 1 // + ); + + // + if (has) + { + // + has = sharp.dir == Opposit(startBar.GetDirection()); + if (!has) + { + sharp.Clean(); + } + } + } + + // + // Validate OrderBlocks ... + if (sharp.IsValid()) + { + // + int end = endBar.Index(); + int start = startBar.Index(); + for (int i = start; i >= end; i--) + { + // + XOHCL iBar; + has = iBar.Init( + sharp.symbol, + sharp.period, + i // + ); + if (!has) + { + // + iBar.Clean(); + continue; + } + + // + totalBars++; + + // + bool isBullish = iBar.IsBullish(); + if (isBullish) + { + // + bullBarsCount++; + + // + if (!isSharpBullish) + { + // + Add( + i, + orderBlocksIDX // + ); + } + } + else + { + // + bearBarsCount++; + + // + if (isSharpBullish) + { + // + Add( + i, + orderBlocksIDX // + ); + } + } + + // + iBar.Clean(); + } + + // + // Follow Order Blocks ... + has = HasChild(orderBlocksIDX); + if (has) + { + // + int bullBarsPercent = (bullBarsCount * 100) / totalBars; + int bearBarsPercent = (bearBarsCount * 100) / totalBars; + + // + has = isSharpBullish + ? bullBarsPercent >= validPercent + : bearBarsPercent >= validPercent; + if (has) + { + // + // Prepare Waiting Boxes ... + count = ArraySize(orderBlocksIDX); + for (int i = 0; i < count; i++) + { + // + XOHCL iBar; + has = iBar.Init( + sharp.symbol, + sharp.period, + orderBlocksIDX[i] // + ); + if (!has) + { + // + iBar.Clean(); + continue; + } + + // + XBoxZone iOB; + XBoxZone iFVG; + + // + iOB.to = sharp.to; + iOB.type = "XOBX"; + iOB.dir = sharp.dir; + iOB.from = iBar.time; + iOB.lower = iBar.low; + iOB.upper = iBar.high; + iOB.period = iBar.period; + iOB.symbol = iBar.symbol; + + // + // Select FVG ... + has = iOB.IsValid(); + if (has) + { + // + // Select FVG ... + has = HasChild(fvgState.fairValueGaps); + if (has) + { + // + XBoxZone tmpBoxes[]; + if (isSharpBullish) + { + // + ToBox( + fvgState.bullishFairValueGaps, + tmpBoxes // + ); + } + else + { + // + ToBox( + fvgState.bearishFairValueGaps, + tmpBoxes // + ); + } + has = HasChild(tmpBoxes); + if (has) + { + // + while (HasChild(tmpBoxes)) + { + // + idx = GetYoungest(tmpBoxes); + has = IsValidIndex(idx); + if (!has) + { + break; + } + + // + XBoxZone iBox = tmpBoxes[idx]; + ArrayRemove( + tmpBoxes, + idx, + 1 // + ); + + // + // Validate FVG ... + bool isDirPassed = iBox.dir == sharp.dir; + bool isFromPassed = iBox.from >= iOB.from; + bool isPricePassed = IsBoxInsideOr(iBox, iOB); + + // + has = isDirPassed && + isFromPassed && + isPricePassed; + if (has) + { + // + iFVG = iBox; + iBox.Clean(); + break; + } + + // + iBox.Clean(); + } + } + Clean(tmpBoxes); + } + } + + // + has = + sharp.IsValid() && + iOB.IsValid() && + iFVG.IsValid(); + if (has) + { + // + XSignalBox iSBox; + + // + iSBox.ob = iOB; + iSBox.fvg = iFVG; + iSBox.sharp = sharp; + + // + AddRef( + iSBox, + waitingBoxes // + ); + + // + iSBox.Clean(); + } + + // + iOB.Clean(); + iFVG.Clean(); + iBar.Clean(); + } + } + } + else + { + // + // Follow Non Order Block ... + // First Found FVGs ... + XBoxZone iOB; + XBoxZone iFVG; + XBoxZone tmpBoxes[]; + if (isSharpBullish) + { + // + ToBox( + fvgState.bullishFairValueGaps, + tmpBoxes // + ); + } + else + { + // + ToBox( + fvgState.bearishFairValueGaps, + tmpBoxes // + ); + } + has = HasChild(tmpBoxes); + if (has) + { + // + while (HasChild(tmpBoxes)) + { + // + idx = GetYoungest(tmpBoxes); + has = IsValidIndex(idx); + if (!has) + { + break; + } + + // + XBoxZone iBox = tmpBoxes[idx]; + ArrayRemove( + tmpBoxes, + idx, + 1 // + ); + + // + // Validate FVG ... + bool isDirPassed = iBox.dir == sharp.dir; + bool isFromPassed = iBox.from >= sharp.from; + bool isPricePassed = IsBoxInside(iBox, sharp); + + // + has = isDirPassed && + isFromPassed && + isPricePassed; + if (has) + { + // + iFVG = iBox; + + // + // Now we Have to Create an Order Block ... + + // + XOHCL iToBar; + XOHCL iFromBar; + + // + int fromIDX = GetBarIndex( + iBox.symbol, + iBox.period, + iBox.from // + ); + int toIDX = GetBarIndex( + iBox.symbol, + iBox.period, + iBox.to // + ); + has = iToBar.Init( + iBox.symbol, + iBox.period, + toIDX // + ); + has = + has && + iFromBar.Init( + iBox.symbol, + iBox.period, + fromIDX // + ); + if (!has) + { + // + iBox.Clean(); + iToBar.Clean(); + iFromBar.Clean(); + + // + break; + } + + // + iOB.to = iBox.to; + iOB.type = "XOBX"; + iOB.dir = iBox.dir; + iOB.from = iBox.from; + iOB.symbol = iBox.symbol; + iOB.period = iBox.period; + iOB.lower = MathMin(iToBar.low, iFromBar.low); + iOB.upper = MathMax(iToBar.high, iFromBar.high); + + // + iBox.Clean(); + iToBar.Clean(); + iFromBar.Clean(); + break; + } + + // + iBox.Clean(); + } + } + Clean(tmpBoxes); + + // + has = iOB.IsValid() && + iFVG.IsValid() && + sharp.IsValid(); + if (has) + { + // + XSignalBox iSBox; + + // + iSBox.ob = iOB; + iSBox.fvg = iFVG; + iSBox.sharp = sharp; + + // + AddRef( + iSBox, + waitingBoxes // + ); + + // + iSBox.Clean(); + } + + // + iOB.Clean(); + iFVG.Clean(); + } + } + + // + endBar.Clean(); + startBar.Clean(); + Clean(orderBlocksIDX); + } + } + + // + count = CountWaitingBoxes(); + result = IsValidSize(count); + + // + // Cleanup Resources ... + + // + obState.Clean(); + ZeroMemory(obHelper); + obConditions.Clean(); + obStateEvents.Clean(); + obXConditions.Clean(); + + // + fvgState.Clean(); + ZeroMemory(fvgHelper); + fvgConditions.Clean(); + fvgStateEvents.Clean(); + fvgXConditions.Clean(); + + // + return result; + } + + /** + * Validating Waiting Boxes and Detect Breaked Boxes ... + * + * @param barIndex: int ... + * + * @return ( int ) + */ + int ValidateWaitingBoxes( + int barIndex = 0 // + ) + { + // + int result = 0; + + // + bool has = false; + + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + if (barIndex == 0) + { + barIndex = 1; + } + + // + has = HasWaitingBoxes(); + if (!has) + { + return result; + } + + // + int removeIDX[]; + result = CountWaitingBoxes(); + for (int i = 0; i < result; i++) + { + // + XOHCL iBar; + XSignalBox iBox = waitingBoxes[i]; + bool isInite = iBar.Init( + iBox.ob.symbol, + iBox.ob.period, + iBox.ob.from // + ); + + // + has = isInite && + ( + // + IsBoxBreaked( + iBox.ob, + iBar.Index() - 1, + barIndex, + period // + ) + // + ); + if (has) + { + // + Add( + i, + removeIDX // + ); + + // + AddRef( + iBox, + breakedBoxes // + ); + } + + // + // iBox.Clean(); + iBar.Clean(); + } + + // + has = HasChild(removeIDX); + if (has) + { + // + CleanupArray( + removeIDX, + waitingBoxes // + ); + } + Clean(removeIDX); + + // + result = CountWaitingBoxes(); + + // + return result; + } + + /** + * Detect Trend Based On Boxes ... + * + * @param dir: ENUM_X_DIRECTION ember ... + * + * @return ( bool ) + */ + bool DetectTreand( + ENUM_X_CYCLES cycle, + ENUM_X_DIRECTION &dir, + X121SMCStrategySignalProviderData &provider, + int barIndex = 0 // + ) + { + // + bool result = false; + + // + support.Clean(); + resistance.Clean(); + dir = X_DIRECTION_NONE; + trend = X_DIRECTION_NONE; + + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + result = IsValid(cycle); + if (!result) + { + return result; + } + + // + // Select Cycle ... + XPOIState cState; + XPOIStateEvents cStateEvents; + X121Conditions cXConditions; + XC121SMCCycleHelper *cHelper; + X121SMCCycleConditions cConditions; + result = provider.SelectCycle( + cycle, + cState, + cStateEvents, + cXConditions, + cHelper, + cConditions // + ); + if (!result) + { + // + cState.Clean(); + ZeroMemory(cHelper); + cConditions.Clean(); + cStateEvents.Clean(); + cXConditions.Clean(); + + // + return result; + } + + // + // Detect Trend ... + + // + int idx = -1; + bool has = false; + + // + XBoxZone tmp[]; + XBoxZone tmpBoxes[]; + + // + // Select Supports ... + ToBox( + cState.supportZones, + tmp // + ); + Copy( + tmp, + tmpBoxes, + false // + ); + Clean(tmp); + + // + // Select Resistances ... + ToBox( + cState.resistanceZones, + tmp // + ); + Copy( + tmp, + tmpBoxes, + false // + ); + Clean(tmp); + + // + result = HasChild(tmpBoxes); + if (!result) + { + // + Clean(tmpBoxes); + + // + cState.Clean(); + ZeroMemory(cHelper); + cConditions.Clean(); + cStateEvents.Clean(); + cXConditions.Clean(); + + // + return result; + } + + // + // Select Youngest Valid Zone ... + while (HasChild(tmpBoxes) || + !(support.IsValid() && + resistance.IsValid())) + { + // + // Check Yongest Zone ... + idx = GetYoungest(tmpBoxes); + has = IsValidIndex(idx); + if (!has) + { + break; + } + + // + // Remove Extracted Box ... + XBoxZone iBox = tmpBoxes[idx]; + ArrayRemove( + tmpBoxes, + idx, + 1 // + ); + + // + // Check Validation of Box ... + has = IsBoxValid( + iBox, + barIndex, + period // + ); + if (!has) + { + // + iBox.Clean(); + continue; + } + + // + // Assign Support or Resistance ... + bool isBullish = iBox.IsBullish(); + if (isBullish && + !support.IsValid()) + { + support = iBox; + } + else if (!isBullish && + !resistance.IsValid()) + { + resistance = iBox; + } + + // + // Validate Support and Resistance ... + has = + support.IsValid() && + resistance.IsValid(); + if (!has) + { + // + iBox.Clean(); + continue; + } + + // + iBox.Clean(); + } + + // + // Checking Result ... + bool isBullish = + support.from > resistance.from; + bool isBearish = + support.from < resistance.from; + result = isBullish || + isBearish; + if (result) + { + // + dir = + isBullish + ? X_DIRECTION_BULLISH + : X_DIRECTION_BEARISH; + trend = dir; + + // + support.to = TimeCurrent(); + resistance.to = TimeCurrent(); + } + + // + // Cleanup Resources ... + + // + Clean(tmp); + cState.Clean(); + Clean(tmpBoxes); + ZeroMemory(cHelper); + cConditions.Clean(); + cStateEvents.Clean(); + cXConditions.Clean(); + + // + return result; + } + + /** + * Update all Collections Members To Time ... + * + * @param value: datetime, Specified To Time ... + */ + void UpdateTo(datetime value = NULL) + { + // + value = NormalizeTime(value); + + // + int count = 0; + bool has = false; + + // + has = HasSupplyZone(); + if (has) + { + supplyZone.To(value); + } + + // + has = HasDemandZone(); + if (has) + { + demandZone.To(value); + } + + // + has = HasWaitingBoxes(); + if (has) + { + // + count = CountWaitingBoxes(); + for (int i = 0; i < count; i++) + { + waitingBoxes[i].UpdateTo(value); + } + } + + // + } + + /** + * Check Working Zone is Destroyed or not ... + * + * @param barIndex: int, bar index ... + * @param forPeriod: ENUM_TIMEFRAMES member ... + * + * @return ( bool ) + */ + bool IsDestroyed( + int barIndex = 0, + ENUM_TIMEFRAMES forPeriod = NULL // + ) + { + // + bool result = false; + + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + if (!IsValid(forPeriod)) + { + forPeriod = period; + } + + // + result = IsValid(); + if (!result) + { + return result; + } + + // + XOHCL bar; + result = bar.Init( + symbol, + period, + barIndex // + ); + if (!result) + { + // + bar.Clean(); + return result; + } + + // + XOHCL cBar; + result = bar.GetPreviousBar(cBar); + if (!result) + { + // + bar.Clean(); + cBar.Clean(); + + // + return result; + } + + // + bool isSupplyZoneBreaked = + // + bar.low > supplyZone.Upper() && + cBar.low > supplyZone.Upper() + // + ; + + // + bool isDemandZoneBreaked = + // + bar.high < demandZone.Lower() && + cBar.high < demandZone.Lower() + // + ; + + // + bar.Clean(); + cBar.Clean(); + + // + result = isSupplyZoneBreaked || + isDemandZoneBreaked; + + // + return result; + } + + /** + * Detect Signal Box Conditions ... + * + * @param box: XBoxZone instance reference, Signalled Box ... + * @param dir: ENUM_X_DIRECTION member, Specified Signal Direction ... + * @param signalProvider: ENUM_X121SMC_XWZ_PROVIDERS member, Specified Signal Type ... + * @param provider: X121SMCStrategySignalProviderData instance reference ... + * @param barIndex: int ... + * + * @return ( bool ) + */ + bool DetectSignalConditions( + XSignalBox &box, + ENUM_X_DIRECTION &dir, + ENUM_X121SMC_XWZ_PROVIDERS &signalProvider, + X121SMCStrategySignalProviderData &provider, + int barIndex = 0 // + ) + { + // + bool result = false; + + // + // Normalize Bars ... + + // + box.Clean(); + dir = X_DIRECTION_NONE; + signalProvider = X121SMC_XWZ_PROVIDER_NONE; + + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + // TODO: Ignor Working Zone Validation ... + // result = IsValid(); + // if (!result) + // { + // return result; + // } + + // + int idx = -1; + int count = 0; + bool has = false; + + // + int zIDX = barIndex; + int cIDX = zIDX + 1; + int pIDX = cIDX + 1; + + // + bool isBullish = false; + bool isBearish = false; + + // + // Senario 1: + // --------------------------------------------- + // Rejected Box ... + // --------------------------------------------- + bool useSenario1 = false; + bool isSenario1Happend = false; + bool isSenario1Bullish = false; + bool isSenario1Bearish = false; + if (useSenario1) + { + // + isSenario1Happend = false; + + // + isSenario1Bullish = + isSenario1Happend && + IsBullish(dir); + + // + isSenario1Bearish = + isSenario1Happend && + IsBearish(dir); + + // + if (isSenario1Happend) + { + signalProvider = X121SMC_XWZ_PROVIDER_XREJECTED_BOX; + } + } + + // + // Senario 2: + // --------------------------------------------------- + // Activated Box ... + // --------------------------------------------------- + bool useSenario2 = false; + bool isSenario2Happend = false; + bool isSenario2Bullish = false; + bool isSenario2Bearish = false; + if (!isSenario1Happend && + useSenario2) + { + // + isSenario2Happend = false; + + // + isSenario2Bullish = + isSenario2Happend && + IsBullish(dir); + + // + isSenario2Bearish = + isSenario2Happend && + IsBearish(dir); + + // + if (isSenario2Happend) + { + signalProvider = X121SMC_XWZ_PROVIDER_XACTIVATED_BOX; + } + } + + // + // Senario 3: + // --------------------------------------------------- + // Breaked Box ... + // --------------------------------------------------- + bool useSenario3 = false; + bool isSenario3Happend = false; + bool isSenario3Bullish = false; + bool isSenario3Bearish = false; + if (!isSenario1Happend && + !isSenario2Happend && + useSenario3) + { + // + isSenario3Happend = false; + + // + isSenario3Bullish = + isSenario3Happend && + IsBullish(dir); + + // + isSenario3Bearish = + isSenario3Happend && + IsBearish(dir); + + // + if (isSenario3Happend) + { + signalProvider = X121SMC_XWZ_PROVIDER_XACTIVATED_BOX; + } + } + + // + // Senario 4: + // ----------------------------------------------- + // Detect Signal Box Based On FVG Conditions ... + // ----------------------------------------------- + bool useSenario4 = false; + bool isSenario4Happend = false; + bool isSenario4Bullish = false; + bool isSenario4Bearish = false; + if (!isSenario1Happend && + !isSenario2Happend && + !isSenario3Happend && + useSenario4) + { + // + isSenario4Happend = false; + + // + isSenario4Bullish = + isSenario4Happend && + IsBullish(dir); + + // + isSenario4Bearish = + isSenario4Happend && + IsBearish(dir); + + // + if (isSenario4Happend) + { + signalProvider = X121SMC_XWZ_PROVIDER_XFVGMA; + } + } + + // + // Senario 5: + // --------------------------------------------- + // XWPVZ ... + // --------------------------------------------- + bool useSenario5 = true; + bool isSenario5Happend = false; + bool isSenario5Bullish = false; + bool isSenario5Bearish = false; + if (!isSenario1Happend && + !isSenario2Happend && + !isSenario3Happend && + !isSenario4Happend && + useSenario5) + { + // + isSenario5Happend = false; + + // + isSenario5Bullish = + isSenario5Happend && + IsBullish(dir); + + // + isSenario5Bearish = + isSenario5Happend && + IsBearish(dir); + + // + if (isSenario5Happend) + { + signalProvider = X121SMC_XWZ_PROVIDER_XWPVZ; + } + } + + // + // Senario 6: + // --------------------------------------------- + // --------------------------------------------- + bool useSenario6 = false; + bool isSenario6Happend = false; + bool isSenario6Bullish = false; + bool isSenario6Bearish = false; + if (!isSenario1Happend && + !isSenario2Happend && + !isSenario3Happend && + !isSenario4Happend && + !isSenario5Happend && + useSenario6) + { + } + + // + // Summarize All Senario(s) Conditions ... + + // + isBullish = + // + isSenario1Bullish || + isSenario2Bullish || + isSenario3Bullish || + isSenario4Bullish || + isSenario5Bullish || + isSenario6Bullish + // + ; + + // + isBearish = + // + isSenario1Bearish || + isSenario2Bearish || + isSenario3Bearish || + isSenario4Bearish || + isSenario5Bearish || + isSenario6Bearish + // + ; + + // + // Check All Conditions ... + result = + box.IsValid() && + HasDirection(dir) && + (isBullish || + isBearish); + + // + if (!result) + { + box.Clean(); + } + + // + return result; + } + + /** + * Detect a Signal Priority forDynamic Risk Reward ratio ... + * + * @param priority: ENUM_X121SMC_XWZ_PRIORITY member, holds Specified position Priority ... + * @param forDir: ENUM_X_DIRECTION member, Specified Position Direction for Priority ... + * @param barIndex: int ... + * @param forPeriod: ENUM_TIMEFRAMES member ... + * + * @return ( bool ) + */ + bool DetectPriority( + ENUM_X121SMC_XWZ_PRIORITY &priority, + ENUM_X_DIRECTION forDir, + int barIndex = 0, + ENUM_TIMEFRAMES forPeriod = NULL // + ) + { + // + bool result = false; + + // + priority = X121SMC_XWZ_PRIORITY_NONE; + + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + if (!IsValid(forPeriod)) + { + forPeriod = period; + } + + // + result = IsValid() && + HasDirection(forDir); + if (!result) + { + return result; + } + + // + bool isBullish = IsBullish(forDir); + + // + XOHCL bar; + result = bar.Init( + symbol, + forPeriod, + barIndex // + ); + if (!result) + { + // + bar.Clean(); + return result; + } + + // + if (bar.high < supplyZone.Upper() && + bar.low > supplyZone.Lower()) + { + // + priority = + isBullish + ? X121SMC_XWZ_PRIORITY_NONE + : X121SMC_XWZ_PRIORITY_STRONG_HIGH; + } + else if (bar.high < supplyZone.Lower() && + bar.low > quarter1) + { + // + priority = + isBullish + ? X121SMC_XWZ_PRIORITY_WEAK + : X121SMC_XWZ_PRIORITY_HIGH; + } + else if (bar.high < quarter1 && + bar.low > quarter2) + { + // + priority = + isBullish + ? X121SMC_XWZ_PRIORITY_LOW + : X121SMC_XWZ_PRIORITY_REGULAR; + } + else if (bar.high < quarter2 && + bar.low > quarter3) + { + // + priority = + isBullish + ? X121SMC_XWZ_PRIORITY_REGULAR + : X121SMC_XWZ_PRIORITY_LOW; + } + else if (bar.high < quarter3 && + bar.low > demandZone.Upper()) + { + // + priority = + isBullish + ? X121SMC_XWZ_PRIORITY_HIGH + : X121SMC_XWZ_PRIORITY_WEAK; + } + else if (bar.high < demandZone.Upper() && + bar.low > demandZone.Lower()) + { + // + priority = + isBullish + ? X121SMC_XWZ_PRIORITY_STRONG_HIGH + : X121SMC_XWZ_PRIORITY_NONE; + } + + // + result = priority != X121SMC_XWZ_PRIORITY_NONE && + priority != X121SMC_XWZ_PRIORITY_WEAK; + + // + bar.Clean(); + + // + return result; + } + + /** + * Draw Working Zne and all of + * it's Collections and Conditions ... + * + * @param drawSupplyZone: boolean ... + * @param drawDemandZone: boolean ... + * @param drawWaitingBoxes: boolean ... + */ + void Draw( + XCPOIDrawer *drawer, + bool drawSupplyZone = false, + bool drawDemandZone = false, + bool drawWaitingBoxes = false, + bool drawTrend = false // + ) + { + // + if (drawer == NULL) + { + return; + } + + // + int count = 0; + bool has = false; + bool isCreated = false; + + // + ulong chartID = drawer.ChartIdentification(); + int subWindow = drawer.SubWindowIdentification(); + color bullishColor = drawer.BarBullishColor(); + color bearishColor = drawer.BarBearishColor(); + + // + // Supply Zone ... + if (drawSupplyZone) + { + // + has = HasSupplyZone(); + if (has) + { + // + XCSupplyZoneObject *iObj; + isCreated = drawer.CreateSupplyZone( + supplyZone, + iObj // + ); + + // + if (isCreated) + { + mWorkingZoneObjects.Add(iObj); + } + } + } + + // + // Demand Zone ... + if (drawDemandZone) + { + // + has = HasDemandZone(); + if (has) + { + // + XCDemandZoneObject *iObj; + isCreated = drawer.CreateDemandZone( + demandZone, + iObj // + ); + + // + if (isCreated) + { + mWorkingZoneObjects.Add(iObj); + } + } + } + + // + // + // + + // + // Quarters ... + has = IsValid(); + if (has) + { + // + double zoneUpper = supplyZone.Upper(); + double upper = supplyZone.Lower(); + + // + double lower = demandZone.Upper(); + double zoneLower = demandZone.Lower(); + + // + string prefix = "X121WZone_" + symbol + "_" + ToString(period); + + // + // Zone Upper ... + CChartObjectHLine *zoneUpperLine; + zoneUpperLine = new CChartObjectHLine(); + isCreated = zoneUpperLine.Create( + chartID, + prefix + "_ZoneTop", + subWindow, + zoneUpper // + ); + if (isCreated) + { + // + zoneUpperLine.Color(clrRed); + + // + mWorkingZoneObjects.Add(zoneUpperLine); + } + + // + // Zone Lower ... + CChartObjectHLine *zoneLowerLine; + zoneLowerLine = new CChartObjectHLine(); + isCreated = zoneLowerLine.Create( + chartID, + prefix + "_ZoneDown", + subWindow, + zoneLower // + ); + if (isCreated) + { + // + zoneLowerLine.Color(clrRed); + + // + mWorkingZoneObjects.Add(zoneLowerLine); + } + + // + // Upper ... + CChartObjectHLine *upperLine; + upperLine = new CChartObjectHLine(); + isCreated = upperLine.Create( + chartID, + prefix + "_Upper", + subWindow, + upper // + ); + if (isCreated) + { + // + upperLine.Color(clrLime); + + // + mWorkingZoneObjects.Add(upperLine); + } + + // + // Lower ... + CChartObjectHLine *lowerLine; + lowerLine = new CChartObjectHLine(); + isCreated = lowerLine.Create( + chartID, + prefix + "_Lower", + subWindow, + lower // + ); + if (isCreated) + { + // + lowerLine.Color(clrLime); + + // + mWorkingZoneObjects.Add(lowerLine); + } + + // + // Quarters ... + + // + // Quarter 1 ... + CChartObjectHLine *q1Line; + q1Line = new CChartObjectHLine(); + isCreated = q1Line.Create( + chartID, + prefix + "_Q1", + subWindow, + quarter1 // + ); + if (isCreated) + { + // + q1Line.Color(clrYellow); + + // + mWorkingZoneObjects.Add(q1Line); + } + + // + // Quarter 2 ... + CChartObjectHLine *q2Line; + q2Line = new CChartObjectHLine(); + isCreated = q2Line.Create( + chartID, + prefix + "_Q2", + subWindow, + quarter2 // + ); + if (isCreated) + { + // + q2Line.Color(clrYellow); + + // + mWorkingZoneObjects.Add(q2Line); + } + + // + // Quarter 3 ... + CChartObjectHLine *q3Line; + q3Line = new CChartObjectHLine(); + isCreated = q3Line.Create( + chartID, + prefix + "_Q3", + subWindow, + quarter3 // + ); + if (isCreated) + { + // + q3Line.Color(clrYellow); + + // + mWorkingZoneObjects.Add(q3Line); + } + } + + // + // Waiting Zones ... + if (drawWaitingBoxes) + { + // + has = HasWaitingBoxes(); + if (has) + { + // + count = CountWaitingBoxes(); + for (int i = 0; i < count; i++) + { + // + XCBaseObject *objects[]; + has = drawer.DrawSignalBox( + waitingBoxes[i], + objects // + ); + if (has) + { + // + int objectsCount = ArraySize(objects); + for (int i = 0; i < objectsCount; i++) + { + mWorkingZoneObjects.Add(objects[i]); + } + } + Clean(objects); + } + } + } + + // + // Draw Trend if Exists ... + if (drawTrend) + { + // + // Check Trend Exists ... + has = + support.IsValid() && + HasDirection(trend) && + resistance.IsValid(); + if (has) + { + // + // Draw Support ... + XCBoxObject *supportObject; + has = drawer.DrawBox( + support, + supportObject // + ); + if (has) + { + mWorkingZoneObjects.Add(supportObject); + } + + // + // Draw Resistance ... + XCBoxObject *resistanceObject; + has = drawer.DrawBox( + resistance, + resistanceObject // + ); + if (has) + { + mWorkingZoneObjects.Add(resistanceObject); + } + } + } + + // + } + + // +}; + +// +// XWZ Signal Conditions ... +struct X121SMCStrategyXWZSignalConditions +{ + // + // Props ... + + // + string symbol; + ENUM_TIMEFRAMES period; + + // + double sl; + double reward; + double amountPercent; + ENUM_X_DIRECTION dir; + ENUM_X_POSITION_TYPES type; + + // + // Setup Props ... + + // + datetime setupTime; + datetime triggerTime; + + // + double pivot; + double point; + double sls[]; + double targets[]; + + // + XBoxZone signalBox; + + // + ENUM_X121SMC_XWZ_PRIORITY priority; + ENUM_X121SMC_XWZ_PROVIDERS provider; + + // + // Constructor ... + X121SMCStrategyXWZSignalConditions() + { + Clean(); + } + + // + // Tools ... + + /** + * Cleaning Up ... + */ + void Clean() + { + // + sl = 0; + + // + dir = X_DIRECTION_NONE; + type = X_POSITION_TYPE_NONE; + + // + symbol = NULL; + period = NULL; + setupTime = NULL; + triggerTime = NULL; + + // + ExtensionClean(); + + // + ZeroMemory(this); + } + + /** + * Check Condition is Setting Up ... + * + * @param dir: ENUM_X_DIRECTION member, Setting Up Direction ... + * + * @return ( bool ) + */ + bool IsSetuped() + { + // + bool result = false; + + // + result = IsValid(setupTime) && + HasDirection(dir); + if (!result) + { + return result; + } + + // + return result; + } + + /** + * Calculate Setup Age ... + * + * @return ( int ) + */ + int GetSetupAge() + { + // + int result = 0; + + // + if (!IsSetuped()) + { + return result; + } + + // + result = (int)(TimeCurrent() - setupTime) / PeriodSeconds(period); + + // + return result; + } + + /** + * Detect How we Can Trigger Signal ... + * + * @return ( bool ) + */ + bool CanTrigger() + { + // + bool result = false; + + // + result = + // + sl > 0 && + IsValid(symbol) && + IsValid(period) && + IsValid(triggerTime) && + type != X_POSITION_TYPE_ALL && + type != X_POSITION_TYPE_NONE + // + ; + + // + return result; + } + + // + // Extensions ... + + /** + * Clean Additional Properties ... + */ + void ExtensionClean() + { + // + pivot = 0; + point = 0; + + // + reward = 0; + amountPercent = 0; + + // + Clean(sls); + Clean(targets); + signalBox.Clean(); + + // + provider = X121SMC_XWZ_PROVIDER_NONE; + } + + // + // + // + + // + void UpdateTo(datetime value = NULL) + { + // + value = NormalizeTime(value); + + // + int count = 0; + bool has = false; + } + + // +}; + +// +// Extension Functions ... + +// \ No newline at end of file diff --git a/BKPS/14040203/X121SMCEA/Strategy/x-121.smc.strategy.class.mq5 b/BKPS/14040203/X121SMCEA/Strategy/x-121.smc.strategy.class.mq5 new file mode 100644 index 0000000..7d1ce16 --- /dev/null +++ b/BKPS/14040203/X121SMCEA/Strategy/x-121.smc.strategy.class.mq5 @@ -0,0 +1,1497 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Class Library +// -------------------------------------- +// Name: XCX121SMCStrategy +// Description: provides all based classes for use ... +// +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +////////////////////////////////////////////////////// +// +// Global Properties ... +#property library +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://www.saherelm.ir" +#property version "1.00" +#property strict + +// +// Imports ... + +// +#include "../Classes/x-121.smc.base.strategy.class.mq5" +#include "../Classes/x-121.smc.market.cycle.helper.class.mq5" + +// +#include "../Signals/x-121.smc.xind.signal.class.mq5" +#include "../Signals/x-121.smc.xwz.signal.class.mq5" + +// +// Definitions ... + +// +// XStrategy Class Implementation(s) ... +class XCX121SMCStrategy : public XCX121SMCBaseStrategy +{ + // + // Public ... + public: + // + // Props ... + bool useXWZSignal; + bool useXINDSignal; + bool useXWZSignalGuard; + bool useXINDSignalGuard; + XCX121SMCXWZSignalDetector *mXWZSignalDetector; + XCX121SMCXINDSignalDetector *mXINDSignalDetector; + X121SMCStrategySignalProviderData cycleProvider; + + // + // Constructor(s) ... + void XCX121SMCStrategy( + // + // Base ... + string _symbol, // Trading Symbol + ENUM_TIMEFRAMES _period // Trading TimeFrame + ) + : XCX121SMCBaseStrategy(_symbol, _period) + { + // + InitialHelpers(); + + // + mXWZSignalDetector = new XCX121SMCXWZSignalDetector( + _symbol, + _period // + ); + + // + mXINDSignalDetector = new XCX121SMCXINDSignalDetector( + _symbol, + _period // + ); + } + + // + // Deconstructur ... + void ~XCX121SMCStrategy() + { + Destroy(); + } + + // + // Getter(s) / Setter(s) ... + + /** + * Get Max Allowed Required POI(s) to Find ... + * + * @return ( int ) + */ + int MaxAllowedRequiredPOIs() + { + return mMaxAllowedRequiredPOIs; + } + + /** + * Set Max Allowed Required POI(s) to Find ... + * + * @param value: number of Required POIs + */ + void MaxAllowedRequiredPOIs(int value) + { + // + if (value < 0) + { + value = 0; + } + + // + mMaxAllowedRequiredPOIs = value; + } + + // + // Overrides Actions ... + + /** + * Destroy All Class Implementations ... + */ + void Destroy() override + { + // + ZeroMemory(mTriggerCycleHelper); + ZeroMemory(mDecisionCycleHelper); + ZeroMemory(mAnalyseCycleHelper); + ZeroMemory(mVerificationCycleHelper); + ZeroMemory(mConsolidationCycleHelper); + ZeroMemory(mVisionCycleHelper); + + // + ZeroMemory(mXWZSignalDetector); + ZeroMemory(mXINDSignalDetector); + + // + cycleProvider.Destroy(); + } + + /** + * Check Conditions For Signal ... + */ + bool HasSignal( + XSignal &signal, + X121SMCStrategyConditions &conditions // + ) override + { + // + bool result = false; + + // + signal.Clean(); + conditions.Clean(); + + // + int pushers = 0; + + // + double sl = 0; + double tp = 0; + double risk = 0; + double entry = 0; + double reward = 0; + double r2r = R2R(); + string provider = ""; + double volume = Volume(); + ENUM_POSITION_TYPE type = POSITION_TYPE_BUY; + ENUM_X_ORDER_MODES mode = X_ORDER_MODE_MARKET; + + // + bool hasLong = false; + bool hasShort = false; + + // + double selectedSL = 0; + + // + // Start Calculations ... + + // + // Retrieve Common Data ... + string symbol = GetSymbol(); + ENUM_TIMEFRAMES period = GetPeriod(); + + // + datetime cTime = TimeCurrent(); + + // + // Required Value For SL/TP Calculations ... + double points = GetPoints(symbol); + double pip = GetPipPrice(symbol); + double pip2 = 2 * pip; + + // + conditions.time = cTime; + conditions.symbol = symbol; + conditions.period = period; + + // + // Check Spread for Signalling Conditions ... + // TODO: Uncomment this ... + // bool isSpreadPassed = IsSpreadPass(); + // result = isSpreadPassed; + // if (!result) + // { + // // + // conditions.Clean(); + // return result; + // } + + // + // Detect Signal Conditions ... + bool hasSignal = false; + + // + bool hasXWZSignal = false; + bool hasXINDSignal = false; + + // + X121SMCStrategyXWZSignalConditions mXWZConditions; + if (useXWZSignal && !hasSignal) + { + // + hasXWZSignal = DetectXWZSignal( + conditions, + mXWZConditions // + ); + hasSignal = hasXWZSignal; + } + + // + X121SMCStrategyXINDSignalConditions mXICHConditions; + if (useXINDSignal && !hasSignal) + { + // + hasXINDSignal = DetectXINDSignal( + conditions, + mXICHConditions // + ); + hasSignal = hasXINDSignal; + } + + // + result = hasSignal; + if (!result) + { + // + conditions.Clean(); + return result; + } + + // + // Combine all Signals Conditions ... + selectedSL = conditions.sl; + provider = conditions.provider; + + // + hasLong = + // + IsBullish(conditions.signalDir) + // + ; + + // + hasShort = + // + IsBearish(conditions.signalDir) + // + ; + + // + result = hasLong || + hasShort; + + // + // Rmove Signal Condition ... + if (result) + { + // + // TYPE ... + type = + hasLong + ? POSITION_TYPE_BUY + : POSITION_TYPE_SELL; + ENUM_X_POSITION_TYPES xType = + hasLong + ? X_POSITION_TYPE_LONG + : X_POSITION_TYPE_SHORT; + + // + entry = GetEntry( + conditions.symbol, + type // + ); + + // + double spread = GetSpread(conditions.symbol); + + // + double slAddition = 0; + sl = + hasLong + ? selectedSL - slAddition + : selectedSL + slAddition; + + // + // RISK Reward ... + risk = + hasLong + ? entry - sl + : sl - entry; + reward = risk * r2r; + tp = + hasLong + ? entry + reward + : entry - reward; + + // + signal.sl = sl; + signal.tp = tp; + signal.type = type; + signal.mode = mode; + signal.entry = entry; + signal.volume = volume; + signal.symbol = symbol; + signal.period = period; + signal.pushers = pushers; + signal.provider = provider; + signal.time = TimeCurrent(); + + // + Copy( + conditions.targets, + signal.targets // + ); + + // + result = PrepareSignal(signal); + + // + if (result) + { + // + if (useXWZSignal && + hasXWZSignal) + { + // + // Configuring Amount Percent and etc ... + // TODO: Enable if required ... + bool ignoreEAVolume = false && + mXWZConditions.reward > 0 && + mXWZConditions.amountPercent > 0; + if (ignoreEAVolume) + { + // + double cReward = mXWZConditions.reward; + double cAmountPercent = mXWZConditions.amountPercent; + + // + double cRiskReward = risk * cReward; + double cTP = hasLong + ? entry + cRiskReward + : entry - cRiskReward; + + // + double balance = mAccount.GetBalance(); + double cRiskAmount = balance * cAmountPercent / 100; + double cRiskInPoints = risk / points; + double cVolume = mAccount.CalculateVolume( + signal.symbol, + cRiskAmount, + cRiskInPoints // + ); + cVolume = NormalizeVolume(cVolume, signal.symbol); + + // + if (cVolume > 0) + { + // + signal.ignoreEAVolume = ignoreEAVolume; + signal.volume = cVolume; + } + } + } + + // + // Draw Signal Oject ... + XCSignalObject *iSignalObj; + bool isCreated = mVisionCycleHelper + .mPOIDrawer + .DrawSignal(signal, iSignalObj); + if (isCreated) + { + // + mSignalDrawnObjects.Add(iSignalObj); + + // + int maxAllowedDrawnSignals = 15; + int count = mSignalDrawnObjects.Total(); + if (count > maxAllowedDrawnSignals) + { + // + int to = count - maxAllowedDrawnSignals; + mSignalDrawnObjects.DeleteRange( + 0, + to // + ); + } + } + } + + // + // Apply Spread on Signal's TP ... + signal.tp = + hasLong + ? signal.tp + spread + : signal.tp - spread; + + // + hasLong = false; + hasShort = false; + } + + // + mXWZConditions.Clean(); + mXICHConditions.Clean(); + + // + return result; + } + + /** + * Check for any Guard Actions ... + */ + bool CheckGuard( + X121SMCGuard &guards[], + const XPosition &positions[] // + ) override + { + // + bool result = false; + + // + Clean(guards); + + // + int count = ArraySize(positions); + result = IsValidSize(count); + if (!result) + { + return result; + } + + // + // XWZ Guard Detection ... + if (useXWZSignal && + useXWZSignalGuard) + { + // + X121SMCGuard xwzGuards[]; + bool hasGuard = mXWZSignalDetector.DetectGuards( + xwzGuards, + positions, + cycleProvider // + ); + + // + if (hasGuard) + { + // + Copy( + xwzGuards, + guards, + false // + ); + } + + // + Clean(xwzGuards); + } + + // + // XICH Guard Detection ... + if (useXINDSignal && + useXINDSignalGuard) + { + // + X121SMCGuard xichGuards[]; + bool hasGuard = mXINDSignalDetector.DetectGuards( + xichGuards, + positions, + cycleProvider // + ); + + // + if (hasGuard) + { + // + Copy( + xichGuards, + guards, + false // + ); + } + + // + Clean(xichGuards); + } + + // + count = ArraySize(guards); + result = IsValidSize(count); + + // + return result; + } + + /** + * Update all Requirements without waiting ... + */ + void DoUnwaitedTicksWork() override + { + } + + /** + * Customize Strategy Identifier ... + */ + string GetTag() override + { + return X121SMCStrategyToken; + } + + // + // Protected ... + protected: + // + + // + // Props ... + CArrayObj mSignalDrawnObjects; + + // + // XC121SMCCycleHelper *mTriggerCycleHelper; + XC121SMCCycleHelper *mTriggerCycleHelper; + XC121SMCCycleHelper *mDecisionCycleHelper; + XC121SMCCycleHelper *mAnalyseCycleHelper; + XC121SMCCycleHelper *mVerificationCycleHelper; + XC121SMCCycleHelper *mConsolidationCycleHelper; + XC121SMCCycleHelper *mVisionCycleHelper; + + // + // Actions ... + + // + // Signalling Functions ... + + // + // XWZ Signal ... + bool DetectXWZSignal( + X121SMCStrategyConditions &conditions, + X121SMCStrategyXWZSignalConditions &xWZConditions // + ) + { + // + bool result = false; + + // + bool isBullish = false; + bool isBearish = false; + + // + int zIndex = 0; + int cIndex = zIndex + 1; + int pIndex = cIndex + 1; + int ppIndex = pIndex + 1; + + // + string symbol = GetSymbol(); + ENUM_TIMEFRAMES period = GetPeriod(); + + // + datetime cTime = TimeCurrent(); + + // + ENUM_X_121_SMC_PROVIDERS provider = X_121_SMC_PROVIDER_XWZ; + string providerStr = ToString(provider); + + // + // Detect Setup Conditions ... + datetime setupTime = mXWZSignalDetector.mConditions.setupTime; + bool isSetuped = mXWZSignalDetector.mConditions.IsSetuped(); + ENUM_X_DIRECTION setupDir = mXWZSignalDetector.mConditions.dir; + if (!isSetuped) + { + // + // Detect Signal Setup ... + isSetuped = mXWZSignalDetector.DetectSignalSetup( + cycleProvider // + ); + + // + setupDir = mXWZSignalDetector.mConditions.dir; + setupTime = mXWZSignalDetector.mConditions.setupTime; + + // + if (isSetuped) + { + // + int items = mXWZSignalDetector + .AddConditionsIfNotExists(); + + // + mXWZSignalDetector.mConditions.Clean(); + } + } + + // + int conditionsCount = ArraySize(mXWZSignalDetector.mConditionsCollection); + result = IsValidSize(conditionsCount); + if (!result) + { + return result; + } + + // + // Looking For Conditions ... + int selectedIndex = 0; + X121SMCStrategyXWZSignalConditions mTmpConditions[]; + Copy( + mXWZSignalDetector.mConditionsCollection, + mTmpConditions // + ); + X121SMCStrategyXWZSignalConditions mConditions; + for (int i = 0; i < conditionsCount; i++) + { + // + // Check Triggers ... + bool canTrigger = mTmpConditions[i].CanTrigger(); + datetime triggerTime = mTmpConditions[i].triggerTime; + if (!canTrigger) + { + // + // Detect Signal Trigger ... + canTrigger = mXWZSignalDetector + .DetectSignalTrigger( + mTmpConditions[i], + cycleProvider // + ); + + // + result = canTrigger; + if (!result) + { + // + bool isISetuped = mTmpConditions[i].IsSetuped(); + if (!isISetuped) + { + // + ArrayRemove( + mXWZSignalDetector.mConditionsCollection, + i, + 1 // + ); + } + continue; + } + + // + triggerTime = mTmpConditions[i].triggerTime; + } + + // + if (canTrigger) + { + // + selectedIndex = i; + mConditions = mTmpConditions[i]; + break; + } + } + + // + result = IsValid(mConditions.setupTime) && + HasDirection(mConditions.dir); + if (!result) + { + return result; + } + + // + // Remove Selected Index from Main Collection ... + ArrayRemove( + mXWZSignalDetector.mConditionsCollection, + selectedIndex, + 1 // + ); + + // + // Check Signal Direction ... + isBullish = IsBullish(mConditions.dir); + isBearish = IsBearish(mConditions.dir); + result = isBullish || + isBearish; + if (!result) + { + return result; + } + + // + // Issues Signal on Conditions ... + conditions.sl = mConditions.sl; + conditions.provider = providerStr; + conditions.signalDir = mConditions.dir; + + // + Copy( + mConditions.targets, + conditions.targets // + ); + + // + xWZConditions = mConditions; + + // + mConditions.Clean(); + + // + return result; + } + + // + // XICH Signal ... + bool DetectXINDSignal( + X121SMCStrategyConditions &conditions, + X121SMCStrategyXINDSignalConditions &xINDConditions // + ) + { + // + bool result = false; + + // + bool isBullish = false; + bool isBearish = false; + + // + int zIndex = 0; + int cIndex = zIndex + 1; + int pIndex = cIndex + 1; + int ppIndex = pIndex + 1; + + // + string symbol = GetSymbol(); + ENUM_TIMEFRAMES period = GetPeriod(); + + // + datetime cTime = TimeCurrent(); + + // + ENUM_X_121_SMC_PROVIDERS provider = X_121_SMC_PROVIDER_XICH; + string providerStr = ToString(provider); + + // + // Detect Setup Conditions ... + datetime setupTime = mXINDSignalDetector.mConditions.setupTime; + bool isSetuped = mXINDSignalDetector.mConditions.IsSetuped(); + ENUM_X_DIRECTION setupDir = mXINDSignalDetector.mConditions.dir; + if (!isSetuped) + { + // + // Detect Signal Setup ... + isSetuped = mXINDSignalDetector.DetectSignalSetup( + cycleProvider, + R2R() // + ); + + // + setupDir = mXINDSignalDetector.mConditions.dir; + setupTime = mXINDSignalDetector.mConditions.setupTime; + + // + if (isSetuped) + { + // + int items = mXINDSignalDetector + .AddConditionsIfNotExists(); + + // + mXINDSignalDetector.mConditions.Clean(); + } + } + + // + int conditionsCount = ArraySize(mXINDSignalDetector.mConditionsCollection); + result = IsValidSize(conditionsCount); + if (!result) + { + return result; + } + + // + // Looking For Conditions ... + int selectedIndex = 0; + X121SMCStrategyXINDSignalConditions mTmpConditions[]; + Copy( + mXINDSignalDetector.mConditionsCollection, + mTmpConditions // + ); + X121SMCStrategyXINDSignalConditions mConditions; + for (int i = 0; i < conditionsCount; i++) + { + // + // Check Triggers ... + bool canTrigger = mTmpConditions[i].CanTrigger(); + datetime triggerTime = mTmpConditions[i].triggerTime; + if (!canTrigger) + { + // + // Detect Signal Trigger ... + canTrigger = mXINDSignalDetector + .DetectSignalTrigger( + mTmpConditions[i], + cycleProvider // + ); + + // + result = canTrigger; + if (!result) + { + // + bool isISetuped = mTmpConditions[i].IsSetuped(); + if (!isISetuped) + { + // + ArrayRemove( + mXINDSignalDetector.mConditionsCollection, + i, + 1 // + ); + } + continue; + } + + // + triggerTime = mTmpConditions[i].triggerTime; + } + + // + if (canTrigger) + { + // + selectedIndex = i; + mConditions = mTmpConditions[i]; + break; + } + } + + // + result = IsValid(mConditions.setupTime) && + HasDirection(mConditions.dir); + if (!result) + { + return result; + } + + // + // Remove Selected Index from Main Collection ... + ArrayRemove( + mXINDSignalDetector.mConditionsCollection, + selectedIndex, + 1 // + ); + + // + // Check Signal Direction ... + isBullish = IsBullish(mConditions.dir); + isBearish = IsBearish(mConditions.dir); + result = isBullish || + isBearish; + if (!result) + { + return result; + } + + // + // Issues Signal on Conditions ... + conditions.sl = mConditions.sl; + conditions.provider = providerStr; + conditions.signalDir = mConditions.dir; + + // + Copy( + mConditions.targets, + conditions.targets // + ); + + // + xINDConditions = mConditions; + + // + mConditions.Clean(); + + // + return result; + } + + // + // Private ... + private: + // + // Props ... + + // + int mMaxAllowedRequiredPOIs; // Max Allowed Required POI(s) to Find ... + + /** + * Initial Required Indicators Helper ... + */ + void InitialHelpers() + { + // + useXWZSignal = false; + useXWZSignalGuard = false; + + // + useXINDSignal = true; + useXINDSignalGuard = false; + + // + string symbol = GetSymbol(); + ENUM_TIMEFRAMES period = GetPeriod(); + + // + if (mMaxAllowedRequiredPOIs <= 0) + { + mMaxAllowedRequiredPOIs = 0; + } + + // + X121Inputs x121Inputs; + x121Inputs.Default(); + + // + // Short ... + ENUM_X_PERIOD_METHOD scMethod = X_PERIOD_AUTO; // How to Find Period + ENUM_TIMEFRAMES scPeriod = NULL; // Time Period + + // + // Medium ... + ENUM_X_PERIOD_METHOD mcMethod = X_PERIOD_AUTO; // How to Find Period + ENUM_TIMEFRAMES mcPeriod = NULL; // Time Period + + // + // Long ... + ENUM_X_PERIOD_METHOD lcMethod = X_PERIOD_AUTO; // How to Find Period + ENUM_TIMEFRAMES lcPeriod = NULL; // Time Period + + // + // Hind ... + ENUM_X_PERIOD_METHOD hcMethod = X_PERIOD_AUTO; // How to Find Period + ENUM_TIMEFRAMES hcPeriod = NULL; // Time Period + + // + bool showAll = false; + int swingLength = 14; + + // + x121Inputs.showRSI = showAll || false; + + // + // + // + + // + // XCC ... + + // + // Configurations ... + + // + // Presentations ... + x121Inputs.xccInputs.showCandles = showAll || true; + + // + // XPV ... + + // + // Configurations ... + x121Inputs.xpvInputs.scMethod = scMethod; + x121Inputs.xpvInputs.scPeriod = scPeriod; + x121Inputs.xpvInputs.mcMethod = mcMethod; + x121Inputs.xpvInputs.mcPeriod = mcPeriod; + x121Inputs.xpvInputs.lcMethod = lcMethod; + x121Inputs.xpvInputs.lcPeriod = lcPeriod; + x121Inputs.xpvInputs.hcMethod = hcMethod; + x121Inputs.xpvInputs.hcPeriod = hcPeriod; + x121Inputs.xpvInputs.goldenZoneLevel = X_FIBO_LEVEL_236; + + // + // Presentations ... + x121Inputs.xpvInputs.showSar = showAll || true; + x121Inputs.xpvInputs.showPeaks = showAll || true; + x121Inputs.xpvInputs.showVales = showAll || true; + x121Inputs.xpvInputs.showTrend = showAll || false; + x121Inputs.xpvInputs.showSupports = showAll || false; + x121Inputs.xpvInputs.showSwingLows = showAll || false; + x121Inputs.xpvInputs.showSwingHighs = showAll || false; + x121Inputs.xpvInputs.showGoldenZones = showAll || true; + x121Inputs.xpvInputs.showResistances = showAll || false; + + // + // XHK ... + + // + // Configurations ... + x121Inputs.xhkInputs.xhkIgnoreSmoothingShadows = true; + x121Inputs.xhkInputs.xhkSmoothingLength = swingLength; + x121Inputs.xhkInputs.xhkSmoothingMode = X_MA_MODE_SMA; + + // + // Presentations ... + x121Inputs.xhkInputs.drawRawXHKCandles = showAll || false; + x121Inputs.xhkInputs.drawSmoothedXHKCandles = showAll || false; + + // + // XMAS ... + + // + // Configurations ... + x121Inputs.xmasInputs.method = MODE_SMA; + x121Inputs.xmasInputs.length = swingLength; + + // + // Presentations ... + x121Inputs.xmasInputs.showMid = showAll || false; + x121Inputs.xmasInputs.showUpper = showAll || false; + x121Inputs.xmasInputs.showLower = showAll || false; + + // + // XATR ... + + // + // Configurations ... + x121Inputs.xatrInputs.atrMultiplier = 2; + x121Inputs.xatrInputs.rsiLength = swingLength; + x121Inputs.xatrInputs.atrLength = swingLength; + x121Inputs.xatrInputs.priceChangeSmoothingLength = swingLength; + x121Inputs.xatrInputs.rsiSmoothingMethod = X_MA_MODE_SMA; + x121Inputs.xatrInputs.atrSmoothingMethod = X_MA_MODE_SMA; + x121Inputs.xatrInputs.priceChangeSmoothingMethod = X_MA_MODE_SMA; + + // + // Presentations ... + x121Inputs.xatrInputs.showAtrUpper = showAll || false; + x121Inputs.xatrInputs.showAtrLower = showAll || false; + x121Inputs.xatrInputs.showRSIChange = showAll || true; + x121Inputs.xatrInputs.showPriceChange = showAll || true; + x121Inputs.xatrInputs.showSmoothedAtrUpper = showAll || false; + x121Inputs.xatrInputs.showSmoothedAtrLower = showAll || false; + x121Inputs.xatrInputs.showSmoothedRSIChange = showAll || false; + x121Inputs.xatrInputs.showSmoothedPriceChange = showAll || false; + + // + // XSTR ... + + // + // Configurations ... + x121Inputs.xstrInputs.strMultiplier = 5; + x121Inputs.xstrInputs.strLength = swingLength; + x121Inputs.xstrInputs.strBoundaryMode = MODE_SMA; + x121Inputs.xstrInputs.strAppliedTo = PRICE_TYPICAL; + + // + // Presentations ... + x121Inputs.xstrInputs.showStr = showAll || true; + x121Inputs.xstrInputs.showStrMid = showAll || false; + x121Inputs.xstrInputs.showStrUpper = showAll || false; + x121Inputs.xstrInputs.showStrLower = showAll || false; + x121Inputs.xstrInputs.showStrSMLow = showAll || false; + x121Inputs.xstrInputs.showStrSMHigh = showAll || false; + + // + // XCHE ... + + // + // Configurations ... + + // + // Presentations ... + x121Inputs.xcheInputs.showLE1 = showAll || false; + x121Inputs.xcheInputs.showSE1 = showAll || false; + x121Inputs.xcheInputs.showLE2 = showAll || false; + x121Inputs.xcheInputs.showSE2 = showAll || false; + + // + // X3MA ... + + // + // Configurations ... + x121Inputs.x3maInputs.x3maMaMethod = MODE_SMA; + x121Inputs.x3maInputs.x3maFastMALength = swingLength; + x121Inputs.x3maInputs.x3maMidMALength = (swingLength * 2); + x121Inputs.x3maInputs.x3maSlowMALength = 50; + x121Inputs.x3maInputs.x3maMaAppliedTo = PRICE_TYPICAL; + + // + // Presentations ... + x121Inputs.x3maInputs.showX3MaMid = showAll || false; + x121Inputs.x3maInputs.showX3MaFast = showAll || false; + x121Inputs.x3maInputs.showX3MaSlow = showAll || false; + + // + // XVWAP ... + + // + // Configurations ... + x121Inputs.xvwapInputs.vwapFastLength = swingLength; + x121Inputs.xvwapInputs.vwapMidLength = (swingLength * 2); + x121Inputs.xvwapInputs.vwapSlowLength = 50; + x121Inputs.xvwapInputs.vwapAppliedTo = PRICE_TYPICAL; + + // + // Presentations ... + x121Inputs.xvwapInputs.showVWapFast = showAll || false; + x121Inputs.xvwapInputs.showVWapSlow = showAll || false; + x121Inputs.xvwapInputs.showVWapMedium = showAll || false; + + // + // + // + + // + // Initialize Cycle Helpers ... + + // + bool isInited = false; + + // + int requiredPOIS = MaxAllowedRequiredPOIs(); + + // + // Trigger Cycle ... + mTriggerCycleHelper = new XC121SMCCycleHelper(); + isInited = mTriggerCycleHelper.Init( + symbol, + PERIOD_M1, + x121Inputs, + requiredPOIS // + ); + if (isInited) + { + // + // Configure POI Drawer ... + color bullishColor = clrDodgerBlue; + color bearishColor = clrSienna; + + // + // Bars ... + mTriggerCycleHelper.mPOIDrawer.BarBullishColor(bullishColor); + mTriggerCycleHelper.mPOIDrawer.BarBearishColor(bearishColor); + + // + // Swings ... + mTriggerCycleHelper.mPOIDrawer.SwingLowColor(bullishColor); + mTriggerCycleHelper.mPOIDrawer.SwingHighColor(bearishColor); + + // + // Momentum ... + mTriggerCycleHelper.mPOIDrawer.BullishMomentumBarColor(bullishColor); + mTriggerCycleHelper.mPOIDrawer.BearishMomentumBarColor(bearishColor); + + // + // Rejection ... + mTriggerCycleHelper.mPOIDrawer.BullishRejectionBarColor(bullishColor); + mTriggerCycleHelper.mPOIDrawer.BearishRejectionBarColor(bearishColor); + + // + // Support and Resistance ... + mTriggerCycleHelper.mPOIDrawer.SupportZoneColor(bullishColor); + mTriggerCycleHelper.mPOIDrawer.ResistanceZoneColor(bearishColor); + + // + // Demand and Supply ... + mTriggerCycleHelper.mPOIDrawer.DemandZoneColor(bullishColor); + mTriggerCycleHelper.mPOIDrawer.SupplyZoneColor(bearishColor); + + // + // Order Blocks ... + mTriggerCycleHelper.mPOIDrawer.BullishOrderBlockColor(bullishColor); + mTriggerCycleHelper.mPOIDrawer.BearishOrderBlockColor(bearishColor); + + // + // Fair Value Gaps ... + mTriggerCycleHelper.mPOIDrawer.BullishFVGColor(bullishColor); + mTriggerCycleHelper.mPOIDrawer.BearishFVGColor(bearishColor); + } + + // + // Decision Cycle ... + mDecisionCycleHelper = new XC121SMCCycleHelper(); + isInited = mDecisionCycleHelper.Init( + symbol, + PERIOD_M5, + x121Inputs, + requiredPOIS // + ); + if (isInited) + { + // + // Configure POI Drawer ... + color bullishColor = clrDodgerBlue; + color bearishColor = clrSienna; + + // + // Bars ... + mDecisionCycleHelper.mPOIDrawer.BarBullishColor(bullishColor); + mDecisionCycleHelper.mPOIDrawer.BarBearishColor(bearishColor); + + // + // Swings ... + mDecisionCycleHelper.mPOIDrawer.SwingLowColor(bullishColor); + mDecisionCycleHelper.mPOIDrawer.SwingHighColor(bearishColor); + + // + // Momentum ... + mDecisionCycleHelper.mPOIDrawer.BullishMomentumBarColor(bullishColor); + mDecisionCycleHelper.mPOIDrawer.BearishMomentumBarColor(bearishColor); + + // + // Rejection ... + mDecisionCycleHelper.mPOIDrawer.BullishRejectionBarColor(bullishColor); + mDecisionCycleHelper.mPOIDrawer.BearishRejectionBarColor(bearishColor); + + // + // Support and Resistance ... + mDecisionCycleHelper.mPOIDrawer.SupportZoneColor(bullishColor); + mDecisionCycleHelper.mPOIDrawer.ResistanceZoneColor(bearishColor); + + // + // Demand and Supply ... + mDecisionCycleHelper.mPOIDrawer.DemandZoneColor(bullishColor); + mDecisionCycleHelper.mPOIDrawer.SupplyZoneColor(bearishColor); + + // + // Order Blocks ... + mDecisionCycleHelper.mPOIDrawer.BullishOrderBlockColor(bullishColor); + mDecisionCycleHelper.mPOIDrawer.BearishOrderBlockColor(bearishColor); + + // + // Fair Value Gaps ... + mDecisionCycleHelper.mPOIDrawer.BullishFVGColor(bullishColor); + mDecisionCycleHelper.mPOIDrawer.BearishFVGColor(bearishColor); + } + + // + // Analyse Cycle ... + mAnalyseCycleHelper = new XC121SMCCycleHelper(); + isInited = mAnalyseCycleHelper.Init( + symbol, + PERIOD_M15, + x121Inputs, + requiredPOIS // + ); + if (isInited) + { + // + // Configure POI Drawer ... + color bullishColor = clrMediumSeaGreen; + color bearishColor = clrBlueViolet; + + // + // Bars ... + mAnalyseCycleHelper.mPOIDrawer.BarBullishColor(bullishColor); + mAnalyseCycleHelper.mPOIDrawer.BarBearishColor(bearishColor); + + // + // Swings ... + mAnalyseCycleHelper.mPOIDrawer.SwingLowColor(bullishColor); + mAnalyseCycleHelper.mPOIDrawer.SwingHighColor(bearishColor); + + // + // Momentum ... + mAnalyseCycleHelper.mPOIDrawer.BullishMomentumBarColor(bullishColor); + mAnalyseCycleHelper.mPOIDrawer.BearishMomentumBarColor(bearishColor); + + // + // Rejection ... + mAnalyseCycleHelper.mPOIDrawer.BullishRejectionBarColor(bullishColor); + mAnalyseCycleHelper.mPOIDrawer.BearishRejectionBarColor(bearishColor); + + // + // Support and Resistance ... + mAnalyseCycleHelper.mPOIDrawer.SupportZoneColor(bullishColor); + mAnalyseCycleHelper.mPOIDrawer.ResistanceZoneColor(bearishColor); + + // + // Demand and Supply ... + mAnalyseCycleHelper.mPOIDrawer.DemandZoneColor(bullishColor); + mAnalyseCycleHelper.mPOIDrawer.SupplyZoneColor(bearishColor); + + // + // Order Blocks ... + mAnalyseCycleHelper.mPOIDrawer.BullishOrderBlockColor(bullishColor); + mAnalyseCycleHelper.mPOIDrawer.BearishOrderBlockColor(bearishColor); + + // + // Fair Value Gaps ... + mAnalyseCycleHelper.mPOIDrawer.BullishFVGColor(bullishColor); + mAnalyseCycleHelper.mPOIDrawer.BearishFVGColor(bearishColor); + } + + // + // Verification Cycle ... + mVerificationCycleHelper = new XC121SMCCycleHelper(); + isInited = mVerificationCycleHelper.Init( + symbol, + PERIOD_M30, + x121Inputs, + requiredPOIS // + ); + if (isInited) + { + // + // Configure POI Drawer ... + color bullishColor = clrDodgerBlue; + color bearishColor = clrSienna; + + // + // Bars ... + mVerificationCycleHelper.mPOIDrawer.BarBullishColor(bullishColor); + mVerificationCycleHelper.mPOIDrawer.BarBearishColor(bearishColor); + + // + // Swings ... + mVerificationCycleHelper.mPOIDrawer.SwingLowColor(bullishColor); + mVerificationCycleHelper.mPOIDrawer.SwingHighColor(bearishColor); + + // + // Momentum ... + mVerificationCycleHelper.mPOIDrawer.BullishMomentumBarColor(bullishColor); + mVerificationCycleHelper.mPOIDrawer.BearishMomentumBarColor(bearishColor); + + // + // Rejection ... + mVerificationCycleHelper.mPOIDrawer.BullishRejectionBarColor(bullishColor); + mVerificationCycleHelper.mPOIDrawer.BearishRejectionBarColor(bearishColor); + + // + // Support and Resistance ... + mVerificationCycleHelper.mPOIDrawer.SupportZoneColor(bullishColor); + mVerificationCycleHelper.mPOIDrawer.ResistanceZoneColor(bearishColor); + + // + // Demand and Supply ... + mVerificationCycleHelper.mPOIDrawer.DemandZoneColor(bullishColor); + mVerificationCycleHelper.mPOIDrawer.SupplyZoneColor(bearishColor); + + // + // Order Blocks ... + mVerificationCycleHelper.mPOIDrawer.BullishOrderBlockColor(bullishColor); + mVerificationCycleHelper.mPOIDrawer.BearishOrderBlockColor(bearishColor); + + // + // Fair Value Gaps ... + mVerificationCycleHelper.mPOIDrawer.BullishFVGColor(bullishColor); + mVerificationCycleHelper.mPOIDrawer.BearishFVGColor(bearishColor); + } + + // + // Consolidation Cycle ... + mConsolidationCycleHelper = new XC121SMCCycleHelper(); + isInited = mConsolidationCycleHelper.Init( + symbol, + PERIOD_H1, + x121Inputs, + requiredPOIS // + ); + if (isInited) + { + // + // Configure POI Drawer ... + color bullishColor = clrLime; + color bearishColor = clrRed; + + // + // Bars ... + mConsolidationCycleHelper.mPOIDrawer.BarBullishColor(bullishColor); + mConsolidationCycleHelper.mPOIDrawer.BarBearishColor(bearishColor); + + // + // Swings ... + mConsolidationCycleHelper.mPOIDrawer.SwingLowColor(bullishColor); + mConsolidationCycleHelper.mPOIDrawer.SwingHighColor(bearishColor); + + // + // Momentum ... + mConsolidationCycleHelper.mPOIDrawer.BullishMomentumBarColor(bullishColor); + mConsolidationCycleHelper.mPOIDrawer.BearishMomentumBarColor(bearishColor); + + // + // Rejection ... + mConsolidationCycleHelper.mPOIDrawer.BullishRejectionBarColor(bullishColor); + mConsolidationCycleHelper.mPOIDrawer.BearishRejectionBarColor(bearishColor); + + // + // Support and Resistance ... + mConsolidationCycleHelper.mPOIDrawer.SupportZoneColor(bullishColor); + mConsolidationCycleHelper.mPOIDrawer.ResistanceZoneColor(bearishColor); + + // + // Demand and Supply ... + mConsolidationCycleHelper.mPOIDrawer.DemandZoneColor(bullishColor); + mConsolidationCycleHelper.mPOIDrawer.SupplyZoneColor(bearishColor); + + // + // Order Blocks ... + mConsolidationCycleHelper.mPOIDrawer.BullishOrderBlockColor(bullishColor); + mConsolidationCycleHelper.mPOIDrawer.BearishOrderBlockColor(bearishColor); + + // + // Fair Value Gaps ... + mConsolidationCycleHelper.mPOIDrawer.BullishFVGColor(bullishColor); + mConsolidationCycleHelper.mPOIDrawer.BearishFVGColor(bearishColor); + } + + // + // Vision Cycle ... + mVisionCycleHelper = new XC121SMCCycleHelper(); + isInited = mVisionCycleHelper.Init( + symbol, + PERIOD_H4, + x121Inputs, + requiredPOIS // + ); + if (isInited) + { + // + // Configure POI Drawer ... + color bullishColor = clrAqua; + color bearishColor = clrMagenta; + + // + // Bars ... + mVisionCycleHelper.mPOIDrawer.BarBullishColor(bullishColor); + mVisionCycleHelper.mPOIDrawer.BarBearishColor(bearishColor); + + // + // Swings ... + mVisionCycleHelper.mPOIDrawer.SwingLowColor(bullishColor); + mVisionCycleHelper.mPOIDrawer.SwingHighColor(bearishColor); + + // + // Momentum ... + mVisionCycleHelper.mPOIDrawer.BullishMomentumBarColor(bullishColor); + mVisionCycleHelper.mPOIDrawer.BearishMomentumBarColor(bearishColor); + + // + // Rejection ... + mVisionCycleHelper.mPOIDrawer.BullishRejectionBarColor(bullishColor); + mVisionCycleHelper.mPOIDrawer.BearishRejectionBarColor(bearishColor); + + // + // Support and Resistance ... + mVisionCycleHelper.mPOIDrawer.SupportZoneColor(bullishColor); + mVisionCycleHelper.mPOIDrawer.ResistanceZoneColor(bearishColor); + + // + // Demand and Supply ... + mVisionCycleHelper.mPOIDrawer.DemandZoneColor(bullishColor); + mVisionCycleHelper.mPOIDrawer.SupplyZoneColor(bearishColor); + + // + // Order Blocks ... + mVisionCycleHelper.mPOIDrawer.BullishOrderBlockColor(bullishColor); + mVisionCycleHelper.mPOIDrawer.BearishOrderBlockColor(bearishColor); + + // + // Fair Value Gaps ... + mVisionCycleHelper.mPOIDrawer.BullishFVGColor(bullishColor); + mVisionCycleHelper.mPOIDrawer.BearishFVGColor(bearishColor); + } + + // + // Initial Cycle Provider ... + cycleProvider.Init( + mTriggerCycleHelper, + mDecisionCycleHelper, + mAnalyseCycleHelper, + mVerificationCycleHelper, + mConsolidationCycleHelper, + mVisionCycleHelper // + ); + } + + // +}; + +// \ No newline at end of file diff --git a/BKPS/14040203/XCAEA/Classes/xcaea.x-poi.detector.class.mq5 b/BKPS/14040203/XCAEA/Classes/xcaea.x-poi.detector.class.mq5 new file mode 100644 index 0000000..a3d3a6e --- /dev/null +++ b/BKPS/14040203/XCAEA/Classes/xcaea.x-poi.detector.class.mq5 @@ -0,0 +1,7691 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Indicator +// ------------------------------------------------- +// Name: XCXCAEAPOIDetector ... +// Description: Class for XCAEA POI Detector ... +// +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +////////////////////////////////////////////////////// +// +// Global Properties ... +#property library +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://saherelm.ir" +#property version "1.00" +#property description "SaherElm Class for XCAEA POI Detector" +#property strict + +// +// Imports ... +#include "../../Classes/x-saherelm.x-bar.analyser.class.mq5" +#include "../../Classes/x-saherelm.x-poi.drawer.class.mq5" +#include "../Helpers/xcaea.helper.mq5" + +// +// Definitions ... + +// +enum ENUM_XCA_PIVOTS +{ + XCA_NONE, // None + XCA_LL, // LowestLow + XCA_HH, // HighestHigh + XCA_KI, // KI + XCA_SWL, // SWL + XCA_SWH, // SWH + XCA_VALE, // VALE + XCA_PEAK, // PEAK + XCA_FVG_BULL, // FVGBull + XCA_FVG_BEAR, // FVGBear + XCA_RSI_COOS, // RSICOOS + XCA_RSI_CUOB, // RSICUOB + XCA_RSI_PEAK, // RSIPeak + XCA_RSI_VALE, // RSIVale + XCA_CCI_COOS, // CCICOOS + XCA_CCI_CUOB, // CCICUOB + XCA_CCI_PEAK, // CCIPeak + XCA_CCI_VALE, // CCIVale + XCA_KI_BULL, // KIBull + XCA_KI_BEAR, // KIBear + XCA_TKI_BULL, // TKIBull + XCA_TKI_BEAR, // TKIBear + XCA_PEAKSWHRES, // PeakSWHRes + XCA_VALESWLSUP, // ValeSWLSup + XCA_TREND_BULL, // TrendBull + XCA_TREND_BEAR, // TrendBear + XCA_TKITRND_BULL, // TKITRNDBull + XCA_TKITRND_BEAR, // TKITRNDBear +}; + +// +bool IsValid(ENUM_XCA_PIVOTS value) +{ + // + bool result = false; + + // + result = value != XCA_NONE; + + // + return result; +} + +// +string ToString(ENUM_XCA_PIVOTS value) +{ + // + string result = NULL; + + // + result = EnumToString(value); + + // + return result; +} + +// +struct XCAPivot +{ + // + // Props ... + datetime to; + double value; + string symbol; + datetime from; + double reserve; + ENUM_XCA_PIVOTS type; + ENUM_TIMEFRAMES period; + + // + double values[]; + + // + // Constructor ... + XCAPivot() + { + Clean(); + } + + // + // Tools ... + + /** + * Cleanup ... + */ + void Clean() + { + // + value = 0; + to = NULL; + reserve = 0; + from = NULL; + symbol = NULL; + period = NULL; + type = XCA_NONE; + + // + Clean(values); + + // + ZeroMemory(this); + } + + /** + * Validate ... + * + * @return ( bool ) + */ + bool IsValid() + { + // + bool result = false; + + // + result = + from < to && + value != 0 && + IsValid(to) && + IsValid(from) && + IsValid(type) && + IsValid(symbol) && + IsValid(period); + + // + return result; + } + + /** + * Check a Model is Same as this or not ... + * + * @param pivot: XCAPivot ... + * + * @return ( bool ) + */ + bool IsSameAs(XCAPivot &pivot) + { + // + bool result = false; + + // + result = + IsValid() && + pivot.IsValid(); + if (!result) + { + return result; + } + + // + result = + to == pivot.to && + from == pivot.from && + type == pivot.type && + value == pivot.value && + symbol == pivot.symbol && + period == pivot.period; + + // + return result; + } + + /** + * Retrieve To Index ... + * + * @param forPeriod: ENUM_TIMEFRAMES, Specified Period ... + * + * @return ( int ) + */ + int ToIndex( + ENUM_TIMEFRAMES forPeriod = NULL // + ) + { + // + int result = -1; + + // + if (!IsValid()) + { + return result; + } + + // + if (!IsValid(forPeriod)) + { + forPeriod = period; + } + + // + result = GetBarIndex( + symbol, + forPeriod, + to // + ); + + // + return result; + } + + /** + * Retrieve From Index ... + * + * @param forPeriod: ENUM_TIMEFRAMES, Specified Period ... + * + * @return ( int ) + */ + int FromIndex( + ENUM_TIMEFRAMES forPeriod = NULL // + ) + { + // + int result = -1; + + // + if (!IsValid()) + { + return result; + } + + // + if (!IsValid(forPeriod)) + { + forPeriod = period; + } + + // + result = GetBarIndex( + symbol, + forPeriod, + from // + ); + + // + return result; + } + + /** + * Retrieve Age of Pivot ... + * + * @param forPeriod: ENUM_TIMEFRAMES, Specified Period ... + * + * @return ( int ) + */ + int GetAge( + ENUM_TIMEFRAMES forPeriod = NULL // + ) + { + // + int result = 0; + + // + if (!IsValid()) + { + return result; + } + + // + if (!IsValid(forPeriod)) + { + forPeriod = period; + } + + // + int toIDX = ToIndex(forPeriod); + int fromIDX = FromIndex(forPeriod); + + // + result = fromIDX - toIDX; + + // + return result; + } + + /** + * Converts Pivot to Box ... + * + * @param box: XBoxZone instance reference ... + * + * @return ( bool ) + */ + bool AsBox( + XBoxZone &box // + ) + { + // + bool result = false; + + // + box.Clean(); + + // + result = IsValid(); + if (!result) + { + return result; + } + + // + ENUM_X_DIRECTION iDir = X_DIRECTION_NONE; + switch (type) + { + // + case XCA_LL: + case XCA_SWL: + case XCA_VALE: + case XCA_KI_BULL: + case XCA_FVG_BULL: + case XCA_RSI_COOS: + case XCA_RSI_VALE: + case XCA_CCI_COOS: + case XCA_CCI_VALE: + case XCA_TKI_BULL: + case XCA_TREND_BULL: + case XCA_VALESWLSUP: + case XCA_TKITRND_BULL: + iDir = X_DIRECTION_BULLISH; + break; + + // + case XCA_HH: + case XCA_SWH: + case XCA_PEAK: + case XCA_KI_BEAR: + case XCA_FVG_BEAR: + case XCA_RSI_CUOB: + case XCA_RSI_PEAK: + case XCA_CCI_CUOB: + case XCA_CCI_PEAK: + case XCA_TKI_BEAR: + case XCA_TREND_BEAR: + case XCA_PEAKSWHRES: + case XCA_TKITRND_BEAR: + iDir = X_DIRECTION_BEARISH; + break; + } + + // + result = HasDirection(iDir); + if (!result) + { + return result; + } + + // + bool isBullish = + IsBullish(iDir) && + value < reserve; + + // + bool isBearish = + IsBearish(iDir) && + value > reserve; + + // + result = isBullish || + isBearish; + if (!result) + { + return result; + } + + // + box.to = to; + box.dir = iDir; + box.from = from; + box.symbol = symbol; + box.period = period; + + // + string typeStr = ToString(type); + if (type == XCA_KI_BULL || + type == XCA_KI_BEAR) + { + // + typeStr = "XCA_KI"; + } + else if (type == XCA_FVG_BULL || + type == XCA_FVG_BEAR) + { + // + typeStr = "XCA_FVG"; + } + else if (type == XCA_RSI_COOS || + type == XCA_RSI_CUOB) + { + // + typeStr = "XCA_RSI"; + } + else if (type == XCA_CCI_COOS || + type == XCA_CCI_CUOB) + { + // + typeStr = "XCA_CCI"; + } + else if (type == XCA_TKI_BULL || + type == XCA_TKI_BEAR) + { + // + typeStr = "XCA_TKI"; + } + else if (type == XCA_TREND_BULL || + type == XCA_TREND_BEAR) + { + // + typeStr = "XCA_TREND"; + } + else if (type == XCA_TKITRND_BULL || + type == XCA_TKITRND_BEAR) + { + // + typeStr = "XCA_TKITRND"; + } + box.type = typeStr; + + // + box.upper = + isBullish + ? reserve + : value; + box.lower = + isBullish + ? value + : reserve; + + // + result = box.IsValid(); + if (!result) + { + box.Clean(); + } + + // + return result; + } + + // +}; + +// +struct XCAPVPivot +{ + // + // Props ... + double value; + XCAPivot pivots[]; + ENUM_X_DIRECTION dir; + + // + // Constructor ... + XCAPVPivot() + { + Clean(); + } + + // + // Tools ... + + // + void Clean() + { + // + value = 0; + Clean(pivots); + dir = X_DIRECTION_NONE; + + // + ZeroMemory(this); + } + + // + bool IsValid() + { + // + bool result = false; + + // + result = value != 0 && + HasDirection(dir); + + // + return result; + } + + // + void AddPivot(XCAPivot &pivot) + { + // + if (!IsValid() || + !pivot.IsValid()) + { + return; + } + + // + int idx = -1; + bool has = FindPivotIndex( + idx, + pivot, + pivots // + ); + if (has) + { + return; + } + + // + AddRef( + pivot, + pivots // + ); + } + + // + int GetPivots(XBoxZone &pivotBoxes[]) + { + // + int result = 0; + + // + Clean(pivotBoxes); + + // + bool has = false; + + // + has = IsValid() && + HasChild(pivots); + if (!has) + { + return result; + } + + // + int count = ArraySize(pivots); + for (int i = 0; i < count; i++) + { + // + XBoxZone iBox; + has = pivots[i].AsBox(iBox); + if (has) + { + // + AddRef( + iBox, + pivotBoxes // + ); + } + + // + iBox.Clean(); + } + + // + result = ArraySize(pivotBoxes); + + // + return result; + } +}; + +// +struct XCAPVTick +{ + // + XCAPivot pivot; + XCTicksZone *zone; + + // + XCAPVTick() + { + Clean(); + } + + // + // Tools ... + + // + void Clean() + { + // + pivot.Clean(); + + // + ZeroMemory(zone); + ZeroMemory(this); + } + + // + bool IsValid() + { + // + bool result = false; + + // + result = pivot.IsValid() && + zone != NULL; + + // + return result; + } + + // + bool Init(XCAPivot &_pivot) + { + // + bool result = false; + + // + result = _pivot.IsValid(); + if (!result) + { + return result; + } + + // + int toIDX = _pivot.ToIndex(); + int fromIDX = _pivot.FromIndex(); + int rangeLength = fromIDX - toIDX; + result = IsValidIndex(fromIDX) && + IsValidIndex(toIDX); + if (!result) + { + // + Clean(); + return result; + } + + // + XOHCL toBar; + XOHCL fromBar; + result = toBar.Init( + _pivot.symbol, + _pivot.period, + toIDX // + ); + result = result && + fromBar.Init( + _pivot.symbol, + _pivot.period, + fromIDX // + ); + if (!result) + { + // + toBar.Clean(); + fromBar.Clean(); + + // + Clean(); + + // + return result; + } + + // + double rangeDivider = 10 * GetPoints(_pivot.symbol); + double rangeL = toBar.FindLowest(rangeLength, MODE_LOW); + double rangeH = toBar.FindHighest(rangeLength, MODE_HIGH); + double rangeDiff = (rangeH - rangeL); + int zoneLevels = (int)(rangeDiff / rangeDivider); + + // + XCTicksZone *_zone; + _zone = new XCTicksZone(); + _zone.Levels(zoneLevels); + result = _zone.Init( + fromBar, + toBar // + ); + if (!result) + { + // + toBar.Clean(); + fromBar.Clean(); + ZeroMemory(_zone); + + // + Clean(); + + // + return result; + } + + // + pivot = _pivot; + zone = _zone; + + // + result = IsValid(); + if (!result) + { + Clean(); + } + + // + toBar.Clean(); + fromBar.Clean(); + ZeroMemory(_zone); + + // + return result; + } + + // + bool GetMaxVolumeBox(XBoxZone &box) + { + // + bool result = false; + + // + box.Clean(); + + // + result = IsValid(); + if (!result) + { + return result; + } + + // + // Select MAX Volume Zone ... + XCTickZone *selectedZone = NULL; + int zonesCount = zone.Count(); + for (int j = 0; j < zonesCount; j++) + { + // + XCTickZone *jZone = zone.GetZone(j); + + // + bool canSet = + selectedZone == NULL + ? true + : selectedZone.volume < jZone.volume; + if (canSet) + { + selectedZone = jZone; + } + + // + ZeroMemory(jZone); + } + + // + result = selectedZone != NULL; + if (!result) + { + // + box.Clean(); + ZeroMemory(selectedZone); + + // + return result; + } + + // + result = pivot.AsBox(box); + if (!result) + { + // + box.Clean(); + + // + return result; + } + box.upper = selectedZone.high; + box.lower = selectedZone.low; + box.type = + pivot.type == XCA_PEAKSWHRES + ? "PEAKTICK" + : pivot.type == XCA_VALESWLSUP + ? "VALETICK" + : box.type; + + // + return result; + } + + // +}; + +/** + * Find Specified Pivot Index inside a Collection of Pivots ... + * + * @param pivot: XCAPivot instance Reference ... + * @param pivots: XCAPivot instance Reference Collection ... + * + * @return ( int ) + */ +bool FindPivotIndex( + int &index, + XCAPivot &pivot, + XCAPivot &pivots[] // +) +{ + // + bool result = false; + + // + index = -1; + + // + int count = ArraySize(pivots); + result = pivot.IsValid() && + IsValidSize(count); + if (!result) + { + return result; + } + + // + for (int i = 0; i < count; i++) + { + // + XCAPivot iPivot = pivots[i]; + + // + bool isSame = pivot.IsSameAs(iPivot); + if (isSame) + { + // + index = i; + break; + } + } + + // + result = IsValidIndex(index); + + // + return result; +} + +/** + * Add or Update Specified Pivot to Specified Collection ... + * + * @param pivot: XCAPivot instance reference, Specified Item ... + * @param pivots: XCAPivot instance reference Collection ... + * @param maxAllowedPivots: int, Max Allowed Pivots number of Collection ... + */ +void AddPivot( + XCAPivot &pivot, + XCAPivot &pivots[], + int maxAllowedPivots = 50 // +) +{ + // + bool has = pivot.IsValid(); + if (!has) + { + return; + } + + // + int idx = -1; + has = FindPivotIndex( + idx, + pivot, + pivots // + ); + if (has) + { + return; + } + + // + int updateIDX = -1; + int count = ArraySize(pivots); + for (int i = 0; i < count; i++) + { + // + XCAPivot iPivot = pivots[i]; + + // + has = + iPivot.to > pivot.to && + iPivot.from == pivot.from && + iPivot.value == pivot.value && + iPivot.symbol == pivot.symbol && + iPivot.period == pivot.period; + if (has) + { + // + updateIDX = i; + break; + } + } + + // + has = IsValidIndex(updateIDX); + if (!has) + { + // + AddRef( + pivot, + pivots // + ); + } + else + { + pivots[updateIDX].to = pivot.to; + } + + // + // Apply Max Allowed ... + CleanupArray( + pivots, + maxAllowedPivots // + ); +} + +/** + * Add or Update PV FVG item to Specified Collection ... + * + * @param value: double, Peak or Vale Value ... + * @param fvg: XCAPivot instance reference, Specified Pivot ... + * @param collection: XCAPVPivot instance Collection ... + */ +void AddOrUpdatePVFVG( + double value, + XCAPivot &fvg, + XCAPVPivot &collection[] // +) +{ + // + // Validate Args ... + if (value < 0 && + !fvg.IsValid() && + (fvg.type == XCA_FVG_BULL || + fvg.type == XCA_FVG_BEAR)) + { + return; + } + + // + // Check Pivot is Exists or not ... + ENUM_X_DIRECTION dir = + fvg.type == XCA_FVG_BULL + ? X_DIRECTION_BULLISH + : X_DIRECTION_BEARISH; + + // + bool isBullish = IsBullish(dir); + bool isBearish = IsBearish(dir); + + // + // Try to Findout Pivot Value in Collection ... + int idx = -1; + int count = ArraySize(collection); + for (int i = 0; i < count; i++) + { + // + XCAPVPivot iTem = collection[i]; + + // + bool isSameValue = iTem.value == value; + bool isSameDirection = iTem.dir == dir; + + // + bool isValid = isSameValue && + isSameDirection; + if (isValid) + { + // + idx = i; + iTem.Clean(); + break; + } + + // + iTem.Clean(); + } + + // + // Try to Add Or Update Pivots ... + bool hasIndex = IsValidIndex(idx); + if (!hasIndex) + { + // + // New Item ... + XCAPVPivot iPVFVG; + + // + iPVFVG.dir = dir; + iPVFVG.value = value; + + // + AddRef( + fvg, + iPVFVG.pivots // + ); + + // + AddRef( + iPVFVG, + collection // + ); + } + else + { + // + // Add Pivot to Existing Item ... + collection[idx].AddPivot(fvg); + } + + // +} + +/** + * Add Specified PVTick to Collection ... + * + * @param pvTick: XCAPVTick instance Reference ... + * @param pvTicks: XCAPVTickinstance Reference Collection ... + */ +void AddPVTick( + XCAPVTick &pvTick, + XCAPVTick &pvTicks[] // +) +{ + // + bool has = pvTick.IsValid(); + if (!has) + { + return; + } + + // + has = false; + int count = ArraySize(pvTicks); + for (int i = 0; i < count; i++) + { + // + has = pvTicks[i].pivot.IsSameAs(pvTick.pivot); + if (has) + { + break; + } + } + + // + if (has) + { + return; + } + + // + AddRef( + pvTick, + pvTicks // + ); +} + +// +// Implementations ... +class XCXCAEAPOIDetector : public XCBase +{ + // + // Public ... + public: + // + // Props ... + + // + // Pivot Verifications and Max Allowed Holding Items ... + int pivotVerifications; // Pivots Verifications ... + int maxAllowedPivots; // Max Allowed Holding Pibots ... + + // + // Detector Pivots State Properties ... + + // + // PEAK / VALES ... + bool detectPeakPivot; + bool detectValePivot; + + // + // PEAK SWH RES / VALE SWL SUP ... + bool detectPeakSWHResPivot; + bool detectValeSWLSupPivot; + + // + // SWING HIGH / LOW ... + bool detectSWHPivot; + bool detectSWLPivot; + + // + // KI ... + bool detectKIBullishPivot; + bool detectKIBearishPivot; + + // + // TKI ... + bool detectTKIBullishPivot; + bool detectTKIBearishPivot; + + // + // FVG ... + bool detectFVGBullishPivot; + bool detectFVGBearishPivot; + + // + // SAME Cycles HH / LL ... + bool detectCycleSameLLPivot; + bool detectCycleSameHHPivot; + + // + // TREND ... + bool detectTrendBullishPivot; + bool detectTrendBearishPivot; + + // + // TKITRND ... + bool detectTKITRNDBullishPivot; + bool detectTKITRNDBearishPivot; + + // + // OSCS ... + + // + // RSI ... + bool detectRSIPeakPivot; + bool detectRSIValePivot; + bool detectRSICrossedOverOSPivot; + bool detectRSICrossedUnderOBPivot; + + // + // CCI ... + bool detectCCIPeakPivot; + bool detectCCIValePivot; + bool detectCCICrossedOverOSPivot; + bool detectCCICrossedUnderOBPivot; + + // + // Active Pivots ... + XCAPivot swhPivot; + XCAPivot swlPivot; + XCAPivot peakPivot; + XCAPivot valePivot; + XCAPivot sSameHHPivot; + XCAPivot mSameHHPivot; + XCAPivot lSameHHPivot; + XCAPivot hSameHHPivot; + XCAPivot sSameLLPivot; + XCAPivot mSameLLPivot; + XCAPivot lSameLLPivot; + XCAPivot hSameLLPivot; + XCAPivot kiBullishPivot; + XCAPivot kiBearishPivot; + XCAPivot tkiBullishPivot; + XCAPivot tkiBearishPivot; + XCAPivot peakSWHResPivot; + XCAPivot valeSWLSupPivot; + XCAPivot trendBullishPivot; + XCAPivot trendBearishPivot; + XCAPivot tkitrndBullishPivot; + XCAPivot tkitrndBearishPivot; + + // + // UnActive Pivots ... + XCAPivot swhPivots[]; + XCAPivot swlPivots[]; + XCAPivot peakPivots[]; + XCAPivot valePivots[]; + XCAPivot rsiPeakPivots[]; + XCAPivot rsiValePivots[]; + XCAPivot cciPeakPivots[]; + XCAPivot cciValePivots[]; + XCAPivot sSameHHPivots[]; + XCAPivot mSameHHPivots[]; + XCAPivot lSameHHPivots[]; + XCAPivot hSameHHPivots[]; + XCAPivot sSameLLPivots[]; + XCAPivot mSameLLPivots[]; + XCAPivot lSameLLPivots[]; + XCAPivot hSameLLPivots[]; + XCAPivot kiBullishPivots[]; + XCAPivot kiBearishPivots[]; + XCAPivot fvgBullishPivots[]; + XCAPivot fvgBearishPivots[]; + XCAPivot tkiBullishPivots[]; + XCAPivot tkiBearishPivots[]; + XCAPivot peakSWHResPivots[]; + XCAPivot valeSWLSupPivots[]; + XCAPivot trendBullishPivots[]; + XCAPivot trendBearishPivots[]; + XCAPivot tkitrndBullishPivots[]; + XCAPivot tkitrndBearishPivots[]; + XCAPivot rsiCrossedOverOSPivots[]; + XCAPivot cciCrossedOverOSPivots[]; + XCAPivot rsiCrossedUnderOBPivots[]; + XCAPivot cciCrossedUnderOBPivots[]; + + // + XCAPVTick peakTicks[]; + XCAPVTick valeTicks[]; + + // + XCAPVPivot pvFVGBullishPivots[]; + XCAPVPivot pvFVGBearishPivots[]; + + // + // Constructors ... + XCXCAEAPOIDetector( + XCXCAEAHelper *_helper // + ) + { + // + helper = _helper; + drawer = new XCPOIDrawer(); + barAnalyser = new XCBarAnalyser(); + + // + Default(); + } + + // + // De Constructors ... + ~XCXCAEAPOIDetector() + { + // + swhPivot.Clean(); + swlPivot.Clean(); + peakPivot.Clean(); + valePivot.Clean(); + sSameHHPivot.Clean(); + mSameHHPivot.Clean(); + lSameHHPivot.Clean(); + hSameHHPivot.Clean(); + sSameLLPivot.Clean(); + mSameLLPivot.Clean(); + lSameLLPivot.Clean(); + hSameLLPivot.Clean(); + kiBullishPivot.Clean(); + kiBearishPivot.Clean(); + tkiBullishPivot.Clean(); + tkiBearishPivot.Clean(); + peakSWHResPivot.Clean(); + valeSWLSupPivot.Clean(); + trendBullishPivot.Clean(); + trendBearishPivot.Clean(); + tkitrndBullishPivot.Clean(); + tkitrndBearishPivot.Clean(); + + // + Clean(swhPivots); + Clean(swlPivots); + Clean(peakPivots); + Clean(valePivots); + Clean(rsiPeakPivots); + Clean(rsiValePivots); + Clean(cciPeakPivots); + Clean(cciValePivots); + Clean(sSameHHPivots); + Clean(mSameHHPivots); + Clean(lSameHHPivots); + Clean(hSameHHPivots); + Clean(sSameLLPivots); + Clean(mSameLLPivots); + Clean(lSameLLPivots); + Clean(hSameLLPivots); + Clean(kiBullishPivots); + Clean(kiBearishPivots); + Clean(fvgBullishPivots); + Clean(fvgBearishPivots); + Clean(tkiBullishPivots); + Clean(tkiBearishPivots); + Clean(peakSWHResPivots); + Clean(valeSWLSupPivots); + Clean(trendBullishPivots); + Clean(trendBearishPivots); + Clean(tkitrndBullishPivots); + Clean(tkitrndBearishPivots); + Clean(rsiCrossedOverOSPivots); + Clean(cciCrossedOverOSPivots); + Clean(rsiCrossedUnderOBPivots); + Clean(cciCrossedUnderOBPivots); + + // + ZeroMemory(helper); + ZeroMemory(drawer); + ZeroMemory(barAnalyser); + } + + // + // Properties ... + + // + // Tools ... + + // + virtual void Default() + { + // + maxAllowedPivots = 50; + pivotVerifications = 5; + + // + detectSWHPivot = true; + detectSWLPivot = true; + detectPeakPivot = true; + detectValePivot = true; + detectRSIPeakPivot = true; + detectRSIValePivot = true; + detectCCIPeakPivot = true; + detectCCIValePivot = true; + detectKIBullishPivot = true; + detectKIBearishPivot = true; + detectFVGBullishPivot = true; + detectFVGBearishPivot = true; + detectTKIBullishPivot = true; + detectTKIBearishPivot = true; + detectPeakSWHResPivot = true; + detectValeSWLSupPivot = true; + detectCycleSameLLPivot = true; + detectCycleSameHHPivot = true; + detectTrendBullishPivot = true; + detectTrendBearishPivot = true; + detectTKITRNDBullishPivot = true; + detectTKITRNDBearishPivot = true; + detectCCICrossedOverOSPivot = true; + detectCCICrossedUnderOBPivot = true; + } + + // + void Update( + int barIndex = 0, + int loopback = 400 // + ) + { + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + loopback = NormalizeInt(loopback, 400); + + // + int count = 0; + bool has = false; + + // + int zIDX = 0; + int cIDX = zIDX + 1; + int pIDX = cIDX + 1; + int p2IDX = pIDX + 1; + int p3IDX = p2IDX + 1; + + // + int index = barIndex; + int start = index; + int end = index + loopback; + while (start < end) + { + // + // Retrieve Conditions ... + XCAEAConditions iConditions; + has = helper.GetConditions( + iConditions, + start, + 5 // + ); + + // + // Retrieve Bars ... + XOHCL zBar; + XOHCL cBar; + XOHCL pBar; + XOHCL p2Bar; + has = zBar.Init( + iConditions.symbol, + iConditions.period, + start // + ); + has = + has && + zBar.GetPreviousBar(cBar); + has = + has && + cBar.GetPreviousBar(pBar); + has = + has && + pBar.GetPreviousBar(p2Bar); + if (!has) + { + // + zBar.Clean(); + cBar.Clean(); + pBar.Clean(); + p2Bar.Clean(); + iConditions.Clean(); + + // + continue; + } + + // + XBoxZone fvgBox; + bool isFVG = barAnalyser.IsFVG( + cBar, + fvgBox // + ); + + // + bool isBullishFVG = + isFVG && + fvgBox.IsBullish(); + + // + bool isBearishFVG = + isFVG && + fvgBox.IsBearish(); + + // + // Provide Some Conditions ... + + // + double points = GetPoints(zBar.symbol); + + // + // PEAK ... + + // + double cPeak = iConditions.peakBuffer[cIDX]; + double pPeak = iConditions.peakBuffer[pIDX]; + double p2Peak = iConditions.peakBuffer[p2IDX]; + + // + bool isPeakStartSameLast = + cPeak == pPeak && + pPeak != p2Peak; + + // + bool isPeakFinishedSameLast = + cPeak != pPeak && + pPeak == p2Peak; + + // + // VALE ... + + // + double cVale = iConditions.valeBuffer[cIDX]; + double pVale = iConditions.valeBuffer[pIDX]; + double p2Vale = iConditions.valeBuffer[p2IDX]; + + // + bool isValeStartSameLast = + cVale == pVale && + pVale != p2Vale; + + // + bool isValeFinishedSameLast = + cVale != pVale && + pVale == p2Vale; + + // + // SWH ... + + // + double cSWH = iConditions.swingHighBuffer[cIDX]; + double pSWH = iConditions.swingHighBuffer[pIDX]; + double p2SWH = iConditions.swingHighBuffer[p2IDX]; + + // + bool isSWHStartSameLast = + cSWH == pSWH && + pSWH != p2SWH; + + // + bool isSWHFinishedSameLast = + cSWH != pSWH && + pSWH == p2SWH; + + // + // SWL ... + + // + double pSWL = iConditions.swingLowBuffer[pIDX]; + double cSWL = iConditions.swingLowBuffer[cIDX]; + double p2SWL = iConditions.swingLowBuffer[p2IDX]; + + // + bool isSWLStartSameLast = + cSWL == pSWL && + pSWL != p2SWL; + + // + bool isSWLFinishedSameLast = + cSWL != pSWL && + pSWL == p2SWL; + + // + // SUPPORT ... + + // + double cSupport = iConditions.supportBuffer[cIDX]; + double pSupport = iConditions.supportBuffer[pIDX]; + double p2Support = iConditions.supportBuffer[p2IDX]; + + // + bool isSupportStartSameLast = + cSupport == pSupport && + pSupport != p2Support; + + // + bool isSupportFinishedSameLast = + cSupport != pSupport && + pSupport == p2Support; + + // + // RESISTANCE ... + + // + double pResistance = iConditions.resistanceBuffer[pIDX]; + double cResistance = iConditions.resistanceBuffer[cIDX]; + double p2Resistance = iConditions.resistanceBuffer[p2IDX]; + + // + bool isResistanceStartSameLast = + cResistance == pResistance && + pResistance != p2Resistance; + + // + bool isResistanceFinishedSameLast = + cResistance != pResistance && + pResistance == p2Resistance; + + // + // PEAK SWH RES ... + + // + bool isCPeakIsPivot = + cPeak == cSWH && + cSWH == cResistance; + + // + bool isPPeakIsPivot = + pPeak == pSWH && + pSWH == pResistance; + + // + bool isStartPeakIsPivot = + isCPeakIsPivot && + !isPPeakIsPivot; + + // + bool isFinishedPeakIsPivot = + !isCPeakIsPivot && + isPPeakIsPivot; + + // + // VALE SWL SUP ... + + // + bool isCValeIsPivot = + cVale == cSWL && + cSWL == cSupport; + + // + bool isPValeIsPivot = + pVale == pSWL && + pSWL == pSupport; + + // + bool isStartValeIsPivot = + isCValeIsPivot && + !isPValeIsPivot; + + // + bool isFinishedValeIsPivot = + !isCValeIsPivot && + isPValeIsPivot; + + // + // TKITRND ... + + // + double cKI = iConditions.kiBuffer[cIDX]; + double pKI = iConditions.kiBuffer[pIDX]; + double p2KI = iConditions.kiBuffer[p2IDX]; + + // + double cKIState = iConditions.kiStateBuffer[cIDX]; + double pKIState = iConditions.kiStateBuffer[pIDX]; + double p2KIState = iConditions.kiStateBuffer[p2IDX]; + + // + double cTKI = iConditions.tkiBuffer[cIDX]; + double pTKI = iConditions.tkiBuffer[pIDX]; + double p2TKI = iConditions.tkiBuffer[p2IDX]; + + // + double cTKIState = iConditions.tkiStateBuffer[cIDX]; + double pTKIState = iConditions.tkiStateBuffer[pIDX]; + double p2TKIState = iConditions.tkiStateBuffer[p2IDX]; + + // + double cTrend = iConditions.trendBuffer[cIDX]; + double pTrend = iConditions.trendBuffer[pIDX]; + double p2Trend = iConditions.trendBuffer[p2IDX]; + + // + double cTrendState = iConditions.trendStateBuffer[cIDX]; + double pTrendState = iConditions.trendStateBuffer[pIDX]; + double p2TrendState = iConditions.trendStateBuffer[p2IDX]; + + // + double cTKITRNDs[] = { + cKI, + cTKI, + cTrend // + }; + + // + double cTKITRNDMin = GetMin(cTKITRNDs); + double cTKITRNDMax = GetMax(cTKITRNDs); + + // + double pTKITRNDs[] = { + pKI, + pTKI, + pTrend // + }; + + // + double pTKITRNDMin = GetMin(pTKITRNDs); + double pTKITRNDMax = GetMax(pTKITRNDs); + + // + bool isCTKITRNDBullish = + cKIState > 0 && + cTKIState > 0 && + cTrendState > 0; + + // + bool isPTKITRNDBullish = + pKIState > 0 && + pTKIState > 0 && + pTrendState > 0; + + // + bool isTKITRNDSwitchedBullish = + isCTKITRNDBullish && + !isPTKITRNDBullish; + + // + bool isCTKITRNDBearish = + cKIState < 0 && + cTKIState < 0 && + cTrendState < 0; + + // + bool isPTKITRNDBearish = + pKIState < 0 && + pTKIState < 0 && + pTrendState < 0; + + // + bool isTKITRNDSwitchedBearish = + isCTKITRNDBearish && + !isPTKITRNDBearish; + + // + // CYCLES ... + + // + double cSLL = iConditions.sLLBuffer[cIDX]; + double pSLL = iConditions.sLLBuffer[pIDX]; + double p2SLL = iConditions.sLLBuffer[p2IDX]; + + // + double cSHH = iConditions.sHHBuffer[cIDX]; + double pSHH = iConditions.sHHBuffer[pIDX]; + double p2SHH = iConditions.sHHBuffer[p2IDX]; + + // + double cMLL = iConditions.mLLBuffer[cIDX]; + double pMLL = iConditions.mLLBuffer[pIDX]; + double p2MLL = iConditions.mLLBuffer[p2IDX]; + + // + double cMHH = iConditions.mHHBuffer[cIDX]; + double pMHH = iConditions.mHHBuffer[pIDX]; + double p2MHH = iConditions.mHHBuffer[p2IDX]; + + // + double cLLL = iConditions.lLLBuffer[cIDX]; + double pLLL = iConditions.lLLBuffer[pIDX]; + double p2LLL = iConditions.lLLBuffer[p2IDX]; + + // + double cLHH = iConditions.lHHBuffer[cIDX]; + double pLHH = iConditions.lHHBuffer[pIDX]; + double p2LHH = iConditions.lHHBuffer[p2IDX]; + + // + double cHLL = iConditions.hLLBuffer[cIDX]; + double pHLL = iConditions.hLLBuffer[pIDX]; + double p2HLL = iConditions.hLLBuffer[p2IDX]; + + // + double cHHH = iConditions.hHHBuffer[cIDX]; + double pHHH = iConditions.hHHBuffer[pIDX]; + double p2HHH = iConditions.hHHBuffer[p2IDX]; + + // + // Short Cycle ... + + // + // LL ... + + // + bool isCSLLSame = + cSLL == pSLL; + + // + bool isPSLLSame = + pSLL == p2SLL; + + // + bool isSLLStartSame = + isCSLLSame && + !isPSLLSame; + + // + bool isSLLFinishedSame = + !isCSLLSame && + isPSLLSame; + + // + // HH ... + + // + bool isCSHHSame = + cSHH == pSHH; + + // + bool isPSHHSame = + pSHH == p2SHH; + + // + bool isSHHStartSame = + isCSHHSame && + !isPSHHSame; + + // + bool isSHHFinishedSame = + !isCSHHSame && + isPSHHSame; + + // + // Mediu Cycle ... + + // + // LL ... + + // + bool isCMLLSame = + cMLL == pMLL; + + // + bool isPMLLSame = + pMLL == p2MLL; + + // + bool isMLLStartSame = + isCMLLSame && + !isPMLLSame; + + // + bool isMLLFinishedSame = + !isCMLLSame && + isPMLLSame; + + // + // HH ... + + // + bool isCMHHSame = + cMHH == pMHH; + + // + bool isPMHHSame = + pMHH == p2MHH; + + // + bool isMHHStartSame = + isCMHHSame && + !isPMHHSame; + + // + bool isMHHFinishedSame = + !isCMHHSame && + isPMHHSame; + + // + // Long Cycle ... + + // + // LL ... + + // + bool isCLLLSame = + cLLL == pLLL; + + // + bool isPLLLSame = + pLLL == p2LLL; + + // + bool isLLLStartSame = + isCLLLSame && + !isPLLLSame; + + // + bool isLLLFinishedSame = + !isCLLLSame && + isPLLLSame; + + // + // HH ... + + // + bool isCLHHSame = + cLHH == pLHH; + + // + bool isPLHHSame = + pLHH == p2LHH; + + // + bool isLHHStartSame = + isCLHHSame && + !isPLHHSame; + + // + bool isLHHFinishedSame = + !isCLHHSame && + isPLHHSame; + + // + // Hind Cycle ... + + // + // LL ... + + // + bool isCHLLSame = + cHLL == pHLL; + + // + bool isPHLLSame = + pHLL == p2HLL; + + // + bool isHLLStartSame = + isCHLLSame && + !isPHLLSame; + + // + bool isHLLFinishedSame = + !isCHLLSame && + isPHLLSame; + + // + // HH ... + + // + bool isCHHHSame = + cHHH == pHHH; + + // + bool isPHHHSame = + pHHH == p2HHH; + + // + bool isHHHStartSame = + isCHHHSame && + !isPHHHSame; + + // + bool isHHHFinishedSame = + !isCHHHSame && + isPHHHSame; + + // + // KI ... + + // + bool isCKISame = + cKI == pKI; + + // + bool isPKISame = + pKI == p2KI; + + // + bool isKIStartSame = + isCKISame && + !isPKISame; + + // + bool isKIFinishedSame = + !isCKISame && + isPKISame; + + // + // RSI ... + + // + double zRSI = iConditions.rsiBuffer[zIDX]; + double cRSI = iConditions.rsiBuffer[cIDX]; + double pRSI = iConditions.rsiBuffer[pIDX]; + double p2RSI = iConditions.rsiBuffer[p2IDX]; + + // + bool isRSIPeak = + pRSI > cRSI && + pRSI > p2RSI && + pRSI > zRSI; + + // + bool isRSIVale = + pRSI < cRSI && + pRSI < p2RSI && + pRSI < zRSI; + + // + bool isRSIBullishVPattern = + cRSI > pRSI && + p2RSI > pRSI && + cRSI > iConditions.rsiOSLevel && + pRSI < iConditions.rsiOSLevel; + + // + bool isRSIBearishVPattern = + cRSI < pRSI && + p2RSI < pRSI && + cRSI < iConditions.rsiOBLevel && + pRSI > iConditions.rsiOBLevel; + + // + // CCI ... + + // + double zCCI = iConditions.cciBuffer[zIDX]; + double cCCI = iConditions.cciBuffer[cIDX]; + double pCCI = iConditions.cciBuffer[pIDX]; + double p2CCI = iConditions.cciBuffer[p2IDX]; + + // + bool isCCIPeak = + pCCI > cCCI && + pCCI > p2CCI && + pCCI > zCCI; + + // + bool isCCIVale = + pCCI < cCCI && + pCCI < p2CCI && + pCCI < zCCI; + + // + bool isCCIBullishVPattern = + cCCI > pCCI && + p2CCI > pCCI && + cCCI > iConditions.cciOSLevel && + pCCI < iConditions.cciOSLevel; + + // + bool isCCIBearishVPattern = + cCCI < pCCI && + p2CCI < pCCI && + cCCI < iConditions.cciOBLevel && + pCCI > iConditions.cciOBLevel; + + // + // Checking Pivots ... + + // + // Peak Pivot ... + if (detectPeakPivot) + { + // + if (!peakPivot.IsValid()) + { + // + peakPivot.type = XCA_PEAK; + peakPivot.symbol = iConditions.symbol; + peakPivot.period = iConditions.period; + + // + if (isPeakFinishedSameLast) + { + // + peakPivot.Clean(); + + // + peakPivot.type = XCA_PEAK; + peakPivot.symbol = iConditions.symbol; + peakPivot.period = iConditions.period; + + // + peakPivot.to = pBar.time; + peakPivot.from = pBar.time; + peakPivot.value = iConditions.peakBuffer[pIDX]; + peakPivot.reserve = iConditions.peakGoldenBuffer[pIDX]; + } + } + + // + if (iConditions.isPeakSameLast) + { + // + peakPivot.from = pBar.time; + + // + peakPivot.reserve = + peakPivot.reserve == 0 + ? iConditions.peakGoldenBuffer[cIDX] + : MathMax(peakPivot.reserve, iConditions.peakGoldenBuffer[cIDX]); + } + + // + if (isPeakStartSameLast) + { + // + has = + peakPivot.IsValid() && + peakPivot.GetAge() >= pivotVerifications; + if (has) + { + // + AddPivot( + peakPivot, + peakPivots, + maxAllowedPivots // + ); + } + + // + peakPivot.Clean(); + } + } + + // + // Vale Pivot ... + if (detectValePivot) + { + // + if (!valePivot.IsValid()) + { + // + valePivot.type = XCA_VALE; + valePivot.symbol = iConditions.symbol; + valePivot.period = iConditions.period; + + // + if (isValeFinishedSameLast) + { + // + valePivot.Clean(); + + // + valePivot.type = XCA_VALE; + valePivot.symbol = iConditions.symbol; + valePivot.period = iConditions.period; + + // + valePivot.to = pBar.time; + valePivot.from = pBar.time; + valePivot.value = iConditions.valeBuffer[pIDX]; + valePivot.reserve = iConditions.valeGoldenBuffer[pIDX]; + } + } + + // + if (iConditions.isValeSameLast) + { + // + valePivot.from = pBar.time; + + // + valePivot.reserve = + valePivot.reserve == 0 + ? iConditions.valeGoldenBuffer[cIDX] + : MathMin(valePivot.reserve, iConditions.valeGoldenBuffer[cIDX]); + } + + // + if (isValeStartSameLast) + { + // + has = valePivot.IsValid() && + valePivot.GetAge() >= pivotVerifications; + if (has) + { + // + AddPivot( + valePivot, + valePivots, + maxAllowedPivots // + ); + } + + // + valePivot.Clean(); + } + } + + // + // SWH Pivot ... + if (detectSWHPivot) + { + // + if (!swhPivot.IsValid()) + { + // + swhPivot.type = XCA_SWH; + swhPivot.symbol = iConditions.symbol; + swhPivot.period = iConditions.period; + + // + if (isSWHFinishedSameLast) + { + // + swhPivot.Clean(); + + // + swhPivot.type = XCA_SWH; + swhPivot.symbol = iConditions.symbol; + swhPivot.period = iConditions.period; + + // + swhPivot.to = pBar.time; + swhPivot.from = pBar.time; + swhPivot.value = iConditions.swingHighBuffer[pIDX]; + } + } + + // + if (iConditions.isSwingHighSameLast) + { + // + swhPivot.from = pBar.time; + + // + double reserve = swhPivot.reserve; + if (pBar.high == pSWH) + { + // + reserve = + reserve == 0 + ? pBar.GetUp() + : MathMin(reserve, pBar.GetUp()); + } + swhPivot.reserve = reserve; + } + + // + if (isSWHStartSameLast) + { + // + double reserve = swhPivot.reserve; + if (cBar.high == cSWH) + { + // + reserve = + reserve == 0 + ? cBar.GetUp() + : MathMin(reserve, cBar.GetUp()); + } + if (pBar.high == pSWH) + { + // + reserve = + reserve == 0 + ? pBar.GetUp() + : MathMin(reserve, pBar.GetUp()); + } + if (reserve == 0 || reserve == swhPivot.value) + { + reserve = swhPivot.value - (5 * points); + } + swhPivot.reserve = reserve; + + // + has = + swhPivot.IsValid() && + swhPivot.GetAge() >= pivotVerifications; + if (has) + { + // + AddPivot( + swhPivot, + swhPivots, + maxAllowedPivots // + ); + } + + // + swhPivot.Clean(); + } + } + + // + // SWL Pivot ... + if (detectSWLPivot) + { + // + if (!swlPivot.IsValid()) + { + // + swlPivot.type = XCA_SWL; + swlPivot.symbol = iConditions.symbol; + swlPivot.period = iConditions.period; + + // + if (isSWLFinishedSameLast) + { + // + swlPivot.Clean(); + + // + swlPivot.type = XCA_SWL; + swlPivot.symbol = iConditions.symbol; + swlPivot.period = iConditions.period; + + // + swlPivot.to = cBar.time; + swlPivot.from = pBar.time; + swlPivot.value = iConditions.swingLowBuffer[cIDX]; + } + } + + // + if (iConditions.isSwingLowSameLast) + { + // + swlPivot.from = pBar.time; + + // + double reserve = swlPivot.reserve; + if (pBar.low == pSWL) + { + // + reserve = + reserve == 0 + ? pBar.GetDown() + : MathMax(reserve, pBar.GetDown()); + } + swlPivot.reserve = reserve; + } + + // + if (isSWLStartSameLast) + { + // + double reserve = swlPivot.reserve; + if (cBar.low == cSWL) + { + // + reserve = + reserve == 0 + ? cBar.GetDown() + : MathMax(reserve, cBar.GetDown()); + } + if (pBar.low == pSWL) + { + // + reserve = + reserve == 0 + ? pBar.GetDown() + : MathMax(reserve, pBar.GetDown()); + } + if (reserve == 0 || reserve == swlPivot.value) + { + reserve = swlPivot.value + (5 * points); + } + swlPivot.reserve = reserve; + + // + has = + swlPivot.IsValid() && + swlPivot.GetAge() >= pivotVerifications; + if (has) + { + // + AddPivot( + swlPivot, + swlPivots, + maxAllowedPivots // + ); + } + + // + swlPivot.Clean(); + } + } + + // + // Peak SWH Res Pivot ... + if (detectPeakSWHResPivot) + { + // + if (!peakSWHResPivot.IsValid()) + { + // + peakSWHResPivot.type = XCA_PEAKSWHRES; + peakSWHResPivot.symbol = iConditions.symbol; + peakSWHResPivot.period = iConditions.period; + + // + if (isFinishedPeakIsPivot) + { + // + peakSWHResPivot.Clean(); + + // + peakSWHResPivot.type = XCA_PEAKSWHRES; + peakSWHResPivot.symbol = iConditions.symbol; + peakSWHResPivot.period = iConditions.period; + + // + peakSWHResPivot.to = pBar.time; + peakSWHResPivot.from = pBar.time; + peakSWHResPivot.value = iConditions.peakBuffer[pIDX]; + peakSWHResPivot.reserve = iConditions.peakGoldenBuffer[pIDX]; + } + } + + // + if (iConditions.isPeakIsPivot) + { + // + peakSWHResPivot.from = pBar.time; + + // + peakSWHResPivot.reserve = + peakSWHResPivot.reserve == 0 + ? iConditions.peakGoldenBuffer[pIDX] + : MathMax(peakSWHResPivot.reserve, iConditions.peakGoldenBuffer[pIDX]); + } + + // + if (isStartPeakIsPivot) + { + // + has = peakSWHResPivot.IsValid() && + peakSWHResPivot.GetAge() >= pivotVerifications; + if (has) + { + // + AddPivot( + peakSWHResPivot, + peakSWHResPivots, + maxAllowedPivots // + ); + + // + XCAPVTick peakTick; + has = peakTick.Init(peakSWHResPivot); + if (has) + { + // + AddPVTick( + peakTick, + peakTicks // + ); + } + + // + peakTick.Clean(); + } + + // + peakSWHResPivot.Clean(); + } + } + + // + // Vale SWL Sup Pivot ... + if (detectValeSWLSupPivot) + { + // + if (!valeSWLSupPivot.IsValid()) + { + // + valeSWLSupPivot.type = XCA_VALESWLSUP; + valeSWLSupPivot.symbol = iConditions.symbol; + valeSWLSupPivot.period = iConditions.period; + + // + if (isFinishedValeIsPivot) + { + // + valeSWLSupPivot.Clean(); + + // + valeSWLSupPivot.type = XCA_VALESWLSUP; + valeSWLSupPivot.symbol = iConditions.symbol; + valeSWLSupPivot.period = iConditions.period; + + // + valeSWLSupPivot.to = pBar.time; + valeSWLSupPivot.from = pBar.time; + valeSWLSupPivot.value = iConditions.valeBuffer[pIDX]; + valeSWLSupPivot.reserve = iConditions.valeGoldenBuffer[pIDX]; + } + } + + // + if (iConditions.isValeIsPivot) + { + // + valeSWLSupPivot.from = pBar.time; + + // + valeSWLSupPivot.reserve = + valeSWLSupPivot.reserve == 0 + ? iConditions.valeGoldenBuffer[pIDX] + : MathMin(valeSWLSupPivot.reserve, iConditions.valeGoldenBuffer[pIDX]); + } + + // + if (isStartValeIsPivot) + { + // + has = valeSWLSupPivot.IsValid() && + valeSWLSupPivot.GetAge() >= pivotVerifications; + if (has) + { + // + AddPivot( + valeSWLSupPivot, + valeSWLSupPivots, + maxAllowedPivots // + ); + + // + XCAPVTick valeTick; + has = valeTick.Init(valeSWLSupPivot); + if (has) + { + // + AddPVTick( + valeTick, + valeTicks // + ); + } + + // + valeTick.Clean(); + } + + // + valeSWLSupPivot.Clean(); + } + } + + // + // KI Bullish ... + if (detectKIBullishPivot) + { + // + if (!kiBullishPivot.IsValid()) + { + // + kiBullishPivot.type = XCA_KI_BULL; + kiBullishPivot.symbol = iConditions.symbol; + kiBullishPivot.period = iConditions.period; + + // + if (iConditions.isKISwitchedToBearish) + { + // + kiBullishPivot.Clean(); + + // + kiBullishPivot.type = XCA_KI_BULL; + kiBullishPivot.symbol = iConditions.symbol; + kiBullishPivot.period = iConditions.period; + + // + kiBullishPivot.to = pBar.time; + kiBullishPivot.from = pBar.time; + kiBullishPivot.value = iConditions.kiBuffer[pIDX]; + kiBullishPivot.reserve = iConditions.kiBuffer[pIDX]; + } + } + + // + if (iConditions.isKIBullish) + { + // + kiBullishPivot.from = cBar.time; + + // + Add( + iConditions.kiBuffer[cIDX], + kiBullishPivot.values // + ); + + // + kiBullishPivot.value = + kiBullishPivot.value == 0 + ? iConditions.kiBuffer[cIDX] + : MathMin(iConditions.kiBuffer[cIDX], kiBullishPivot.value); + + // + kiBullishPivot.reserve = + kiBullishPivot.reserve == 0 + ? iConditions.kiBuffer[cIDX] + : MathMax(iConditions.kiBuffer[cIDX], kiBullishPivot.reserve); + } + + // + if (iConditions.isKISwitchedToBullish) + { + // + has = + kiBullishPivot.IsValid() && + kiBullishPivot.GetAge() >= pivotVerifications; + if (has) + { + // + AddPivot( + kiBullishPivot, + kiBullishPivots, + maxAllowedPivots // + ); + } + + // + kiBullishPivot.Clean(); + } + } + + // + // KI Bearish ... + if (detectKIBearishPivot) + { + // + if (!kiBearishPivot.IsValid()) + { + // + kiBearishPivot.type = XCA_KI_BEAR; + kiBearishPivot.symbol = iConditions.symbol; + kiBearishPivot.period = iConditions.period; + + // + if (iConditions.isKISwitchedToBullish) + { + // + kiBearishPivot.Clean(); + + // + kiBearishPivot.type = XCA_KI_BEAR; + kiBearishPivot.symbol = iConditions.symbol; + kiBearishPivot.period = iConditions.period; + + // + kiBearishPivot.to = pBar.time; + kiBearishPivot.from = pBar.time; + kiBearishPivot.value = iConditions.kiBuffer[pIDX]; + kiBearishPivot.reserve = iConditions.kiBuffer[pIDX]; + } + } + + // + if (iConditions.isKIBearish) + { + // + kiBearishPivot.from = cBar.time; + + // + Add( + iConditions.kiBuffer[cIDX], + kiBearishPivot.values // + ); + + // + kiBearishPivot.value = + kiBearishPivot.value == 0 + ? iConditions.kiBuffer[cIDX] + : MathMax(iConditions.kiBuffer[cIDX], kiBearishPivot.value); + + // + kiBearishPivot.reserve = + kiBearishPivot.reserve == 0 + ? iConditions.kiBuffer[cIDX] + : MathMin(iConditions.kiBuffer[cIDX], kiBearishPivot.reserve); + } + + // + if (iConditions.isKISwitchedToBearish) + { + // + has = + kiBearishPivot.IsValid() && + kiBearishPivot.GetAge() >= pivotVerifications; + if (has) + { + // + AddPivot( + kiBearishPivot, + kiBearishPivots, + maxAllowedPivots // + ); + } + + // + kiBearishPivot.Clean(); + } + } + + // + // FVG Bullish ... + if (detectFVGBullishPivot) + { + // + if (isBullishFVG) + { + // + XCAPivot iPivot; + + // + iPivot.to = fvgBox.to; + iPivot.from = fvgBox.from; + iPivot.type = XCA_FVG_BULL; + iPivot.value = fvgBox.lower; + iPivot.reserve = fvgBox.upper; + iPivot.symbol = fvgBox.symbol; + iPivot.period = fvgBox.period; + + // + AddPivot( + iPivot, + fvgBullishPivots, + maxAllowedPivots // + ); + + // + double fValue = + fvgBox.IsBullish() + ? cVale + : cPeak; + + // + // XPVFVG Handling ... + AddOrUpdatePVFVG( + fValue, + iPivot, + pvFVGBullishPivots // + ); + + // + iPivot.Clean(); + } + } + + // + // FVG Bearish ... + if (detectFVGBearishPivot) + { + // + if (isBearishFVG) + { + // + XCAPivot iPivot; + + // + iPivot.to = fvgBox.to; + iPivot.from = fvgBox.from; + iPivot.type = XCA_FVG_BEAR; + iPivot.value = fvgBox.upper; + iPivot.reserve = fvgBox.lower; + iPivot.symbol = fvgBox.symbol; + iPivot.period = fvgBox.period; + + // + AddPivot( + iPivot, + fvgBearishPivots, + maxAllowedPivots // + ); + + // + double fValue = + fvgBox.IsBullish() + ? cVale + : cPeak; + + // + // XPVFVG Handling ... + AddOrUpdatePVFVG( + fValue, + iPivot, + pvFVGBearishPivots // + ); + + // + iPivot.Clean(); + } + } + + // + // TKI Bullish ... + if (detectTKIBullishPivot) + { + // + if (!tkiBullishPivot.IsValid()) + { + // + tkiBullishPivot.type = XCA_TKI_BULL; + tkiBullishPivot.symbol = iConditions.symbol; + tkiBullishPivot.period = iConditions.period; + + // + if (iConditions.isTKISwitchedToBearish) + { + // + tkiBullishPivot.Clean(); + + // + tkiBullishPivot.type = XCA_TKI_BULL; + tkiBullishPivot.symbol = iConditions.symbol; + tkiBullishPivot.period = iConditions.period; + + // + tkiBullishPivot.to = pBar.time; + tkiBullishPivot.from = pBar.time; + tkiBullishPivot.value = iConditions.tkiBuffer[pIDX]; + tkiBullishPivot.reserve = iConditions.tkiBuffer[pIDX]; + } + } + + // + if (iConditions.isTKIBullish) + { + // + tkiBullishPivot.from = cBar.time; + + // + Add( + iConditions.tkiBuffer[cIDX], + tkiBullishPivot.values // + ); + + // + tkiBullishPivot.value = + tkiBullishPivot.value == 0 + ? iConditions.tkiBuffer[cIDX] + : MathMin(iConditions.tkiBuffer[cIDX], tkiBullishPivot.value); + + // + tkiBullishPivot.reserve = + tkiBullishPivot.reserve == 0 + ? iConditions.tkiBuffer[cIDX] + : MathMax(iConditions.tkiBuffer[cIDX], tkiBullishPivot.reserve); + } + + // + if (iConditions.isTKISwitchedToBullish) + { + // + has = + tkiBullishPivot.IsValid() && + tkiBullishPivot.GetAge() >= pivotVerifications; + if (has) + { + // + AddPivot( + tkiBullishPivot, + tkiBullishPivots, + maxAllowedPivots // + ); + } + + // + tkiBullishPivot.Clean(); + } + } + + // + // TKI Bearish ... + if (detectTKIBearishPivot) + { + // + if (!tkiBearishPivot.IsValid()) + { + // + tkiBearishPivot.type = XCA_TKI_BEAR; + tkiBearishPivot.symbol = iConditions.symbol; + tkiBearishPivot.period = iConditions.period; + + // + if (iConditions.isTKISwitchedToBullish) + { + // + tkiBearishPivot.Clean(); + + // + tkiBearishPivot.type = XCA_TKI_BEAR; + tkiBearishPivot.symbol = iConditions.symbol; + tkiBearishPivot.period = iConditions.period; + + // + tkiBearishPivot.to = pBar.time; + tkiBearishPivot.from = pBar.time; + tkiBearishPivot.value = iConditions.tkiBuffer[pIDX]; + tkiBearishPivot.reserve = iConditions.tkiBuffer[pIDX]; + } + } + + // + if (iConditions.isTKIBearish) + { + // + tkiBearishPivot.from = cBar.time; + + // + Add( + iConditions.tkiBuffer[cIDX], + tkiBearishPivot.values // + ); + + // + tkiBearishPivot.value = + tkiBearishPivot.value == 0 + ? iConditions.tkiBuffer[cIDX] + : MathMax(iConditions.tkiBuffer[cIDX], tkiBearishPivot.value); + + // + tkiBearishPivot.reserve = + tkiBearishPivot.reserve == 0 + ? iConditions.tkiBuffer[cIDX] + : MathMin(iConditions.tkiBuffer[cIDX], tkiBearishPivot.reserve); + } + + // + if (iConditions.isTKISwitchedToBearish) + { + // + has = + tkiBearishPivot.IsValid() && + tkiBearishPivot.GetAge() >= pivotVerifications; + if (has) + { + // + AddPivot( + tkiBearishPivot, + tkiBearishPivots, + maxAllowedPivots // + ); + } + + // + tkiBearishPivot.Clean(); + } + } + + // + // TREND Bullish ... + if (detectTrendBullishPivot) + { + // + if (!trendBullishPivot.IsValid()) + { + // + trendBullishPivot.type = XCA_TREND_BULL; + trendBullishPivot.symbol = iConditions.symbol; + trendBullishPivot.period = iConditions.period; + + // + if (iConditions.isTrendSwitchedToBearish) + { + // + trendBullishPivot.Clean(); + + // + trendBullishPivot.type = XCA_TREND_BULL; + trendBullishPivot.symbol = iConditions.symbol; + trendBullishPivot.period = iConditions.period; + + // + trendBullishPivot.to = pBar.time; + trendBullishPivot.from = pBar.time; + trendBullishPivot.value = iConditions.trendBuffer[pIDX]; + trendBullishPivot.reserve = iConditions.trendBuffer[pIDX]; + } + } + + // + if (iConditions.isTrendBullish) + { + // + trendBullishPivot.from = cBar.time; + + // + Add( + iConditions.trendBuffer[cIDX], + trendBullishPivot.values // + ); + + // + trendBullishPivot.value = + trendBullishPivot.value == 0 + ? iConditions.trendBuffer[cIDX] + : MathMin(iConditions.trendBuffer[cIDX], trendBullishPivot.value); + + // + trendBullishPivot.reserve = + trendBullishPivot.reserve == 0 + ? iConditions.trendBuffer[cIDX] + : MathMax(iConditions.trendBuffer[cIDX], trendBullishPivot.reserve); + } + + // + if (iConditions.isTrendSwitchedToBullish) + { + // + has = + trendBullishPivot.IsValid() && + trendBullishPivot.GetAge() >= pivotVerifications; + if (has) + { + // + AddPivot( + trendBullishPivot, + trendBullishPivots, + maxAllowedPivots // + ); + } + + // + trendBullishPivot.Clean(); + } + } + + // + // TREND Bearish ... + if (detectTrendBearishPivot) + { + // + if (!trendBearishPivot.IsValid()) + { + // + trendBearishPivot.type = XCA_TREND_BEAR; + trendBearishPivot.symbol = iConditions.symbol; + trendBearishPivot.period = iConditions.period; + + // + if (iConditions.isTrendSwitchedToBullish) + { + // + trendBearishPivot.Clean(); + + // + trendBearishPivot.type = XCA_TREND_BEAR; + trendBearishPivot.symbol = iConditions.symbol; + trendBearishPivot.period = iConditions.period; + + // + trendBearishPivot.to = pBar.time; + trendBearishPivot.from = pBar.time; + trendBearishPivot.value = iConditions.trendBuffer[pIDX]; + trendBearishPivot.reserve = iConditions.trendBuffer[pIDX]; + } + } + + // + if (iConditions.isTrendBearish) + { + // + trendBearishPivot.from = cBar.time; + + // + Add( + iConditions.trendBuffer[cIDX], + trendBearishPivot.values // + ); + + // + trendBearishPivot.value = + trendBearishPivot.value == 0 + ? iConditions.trendBuffer[cIDX] + : MathMax(iConditions.trendBuffer[cIDX], trendBearishPivot.value); + + // + trendBearishPivot.reserve = + trendBearishPivot.reserve == 0 + ? iConditions.trendBuffer[cIDX] + : MathMin(iConditions.trendBuffer[cIDX], trendBearishPivot.reserve); + } + + // + if (iConditions.isTrendSwitchedToBearish) + { + // + has = + trendBearishPivot.IsValid() && + trendBearishPivot.GetAge() >= pivotVerifications; + if (has) + { + // + AddPivot( + trendBearishPivot, + trendBearishPivots, + maxAllowedPivots // + ); + } + + // + trendBearishPivot.Clean(); + } + } + + // + // TKITRND Bullish ... + if (detectTKITRNDBullishPivot) + { + // + if (!tkitrndBullishPivot.IsValid()) + { + // + tkitrndBullishPivot.type = XCA_TKITRND_BULL; + tkitrndBullishPivot.symbol = iConditions.symbol; + tkitrndBullishPivot.period = iConditions.period; + + // + if (!isCTKITRNDBullish && isPTKITRNDBullish) + { + // + tkitrndBullishPivot.Clean(); + + // + tkitrndBullishPivot.type = XCA_TKITRND_BULL; + tkitrndBullishPivot.symbol = iConditions.symbol; + tkitrndBullishPivot.period = iConditions.period; + + // + tkitrndBullishPivot.to = pBar.time; + tkitrndBullishPivot.from = pBar.time; + tkitrndBullishPivot.value = pTKITRNDMin; + tkitrndBullishPivot.reserve = pTKITRNDMax; + } + } + + // + if (isCTKITRNDBullish) + { + // + tkitrndBullishPivot.from = cBar.time; + + // + Add( + cTKITRNDMin, + tkitrndBullishPivot.values // + ); + + // + Add( + cTKITRNDMax, + tkitrndBullishPivot.values // + ); + + // + tkitrndBullishPivot.value = + tkitrndBullishPivot.value == 0 + ? cTKITRNDMin + : MathMin(cTKITRNDMin, tkitrndBullishPivot.value); + + // + tkitrndBullishPivot.reserve = + tkitrndBullishPivot.reserve == 0 + ? cTKITRNDMax + : MathMax(cTKITRNDMax, tkitrndBullishPivot.reserve); + } + + // + if (!isCTKITRNDBullish) + { + // + has = + tkitrndBullishPivot.IsValid() && + tkitrndBullishPivot.GetAge() >= pivotVerifications; + if (has) + { + // + AddPivot( + tkitrndBullishPivot, + tkitrndBullishPivots, + maxAllowedPivots // + ); + } + + // + trendBullishPivot.Clean(); + } + } + + // + // TKITRND Bearish ... + if (detectTKITRNDBearishPivot) + { + // + if (!tkitrndBearishPivot.IsValid()) + { + // + tkitrndBearishPivot.type = XCA_TKITRND_BEAR; + tkitrndBearishPivot.symbol = iConditions.symbol; + tkitrndBearishPivot.period = iConditions.period; + + // + if (!isCTKITRNDBearish && isPTKITRNDBearish) + { + // + tkitrndBearishPivot.Clean(); + + // + tkitrndBearishPivot.type = XCA_TKITRND_BEAR; + tkitrndBearishPivot.symbol = iConditions.symbol; + tkitrndBearishPivot.period = iConditions.period; + + // + tkitrndBearishPivot.to = pBar.time; + tkitrndBearishPivot.from = pBar.time; + tkitrndBearishPivot.value = pTKITRNDMax; + tkitrndBearishPivot.reserve = pTKITRNDMin; + } + } + + // + if (isCTKITRNDBearish) + { + // + tkitrndBearishPivot.from = cBar.time; + + // + Add( + cTKITRNDMin, + tkitrndBearishPivot.values // + ); + + // + Add( + cTKITRNDMax, + tkitrndBearishPivot.values // + ); + + // + tkitrndBearishPivot.value = + tkitrndBearishPivot.value == 0 + ? cTKITRNDMax + : MathMax(cTKITRNDMax, tkitrndBearishPivot.value); + + // + tkitrndBearishPivot.reserve = + tkitrndBearishPivot.reserve == 0 + ? cTKITRNDMin + : MathMin(cTKITRNDMin, tkitrndBearishPivot.reserve); + } + + // + if (!isCTKITRNDBearish) + { + // + has = + tkitrndBearishPivot.IsValid() && + tkitrndBearishPivot.GetAge() >= pivotVerifications; + if (has) + { + // + AddPivot( + tkitrndBearishPivot, + tkitrndBearishPivots, + maxAllowedPivots // + ); + } + + // + trendBearishPivot.Clean(); + } + } + + // + // Cycles LL ... + if (detectCycleSameLLPivot) + { + // + // Short Cycle ... + if (!sSameLLPivot.IsValid()) + { + // + sSameLLPivot.type = XCA_LL; + sSameLLPivot.symbol = iConditions.symbol; + sSameLLPivot.period = iConditions.period; + + // + if (isSLLFinishedSame) + { + // + sSameLLPivot.Clean(); + + // + sSameLLPivot.type = XCA_LL; + sSameLLPivot.symbol = iConditions.symbol; + sSameLLPivot.period = iConditions.period; + + // + sSameLLPivot.to = pBar.time; + sSameLLPivot.from = pBar.time; + sSameLLPivot.value = pSLL; + sSameLLPivot.reserve = pSLL; + } + } + + // + if (isCSLLSame) + { + // + sSameLLPivot.from = pBar.time; + + // + double reserve = sSameLLPivot.reserve; + if (pBar.low == pSLL) + { + // + reserve = + reserve == 0 + ? pBar.GetDown() + : MathMax(reserve, pBar.GetDown()); + } + sSameLLPivot.reserve = reserve; + } + + // + if (isSLLStartSame) + { + // + double reserve = sSameLLPivot.reserve; + if (cBar.low == cSLL) + { + // + reserve = + reserve == 0 + ? cBar.GetDown() + : MathMax(reserve, cBar.GetDown()); + } + if (pBar.low == pSLL) + { + // + reserve = + reserve == 0 + ? pBar.GetDown() + : MathMax(reserve, pBar.GetDown()); + } + if (reserve == 0 || reserve == sSameLLPivot.value) + { + reserve = sSameLLPivot.value + (5 * points); + } + sSameLLPivot.reserve = reserve; + + // + has = + sSameLLPivot.IsValid() && + sSameLLPivot.GetAge() >= pivotVerifications; + if (has) + { + // + AddPivot( + sSameLLPivot, + sSameLLPivots, + maxAllowedPivots // + ); + } + + // + sSameLLPivot.Clean(); + } + + // + // Medium Cycle ... + if (!mSameLLPivot.IsValid()) + { + // + mSameLLPivot.type = XCA_LL; + mSameLLPivot.symbol = iConditions.symbol; + mSameLLPivot.period = iConditions.period; + + // + if (isMLLFinishedSame) + { + // + mSameLLPivot.Clean(); + + // + mSameLLPivot.type = XCA_LL; + mSameLLPivot.symbol = iConditions.symbol; + mSameLLPivot.period = iConditions.period; + + // + mSameLLPivot.to = pBar.time; + mSameLLPivot.from = pBar.time; + mSameLLPivot.value = pMLL; + mSameLLPivot.reserve = pMLL; + } + } + + // + if (isCMLLSame) + { + // + mSameLLPivot.from = pBar.time; + + // + double reserve = mSameLLPivot.reserve; + if (pBar.low == pMLL) + { + // + reserve = + reserve == 0 + ? pBar.GetDown() + : MathMax(reserve, pBar.GetDown()); + } + mSameLLPivot.reserve = reserve; + } + + // + if (isMLLStartSame) + { + // + double reserve = mSameLLPivot.reserve; + if (cBar.low == cMLL) + { + // + reserve = + reserve == 0 + ? cBar.GetDown() + : MathMax(reserve, cBar.GetDown()); + } + if (pBar.low == pMLL) + { + // + reserve = + reserve == 0 + ? pBar.GetDown() + : MathMax(reserve, pBar.GetDown()); + } + if (reserve == 0 || reserve == mSameLLPivot.value) + { + reserve = mSameLLPivot.value + (5 * points); + } + mSameLLPivot.reserve = reserve; + + // + has = + mSameLLPivot.IsValid() && + mSameLLPivot.GetAge() >= pivotVerifications; + if (has) + { + // + AddPivot( + mSameLLPivot, + mSameLLPivots, + maxAllowedPivots // + ); + } + + // + mSameLLPivot.Clean(); + } + + // + // Long Cycle ... + if (!lSameLLPivot.IsValid()) + { + // + lSameLLPivot.type = XCA_LL; + lSameLLPivot.symbol = iConditions.symbol; + lSameLLPivot.period = iConditions.period; + + // + if (isLLLFinishedSame) + { + // + lSameLLPivot.Clean(); + + // + lSameLLPivot.type = XCA_LL; + lSameLLPivot.symbol = iConditions.symbol; + lSameLLPivot.period = iConditions.period; + + // + lSameLLPivot.to = pBar.time; + lSameLLPivot.from = pBar.time; + lSameLLPivot.value = pLLL; + lSameLLPivot.reserve = pLLL; + } + } + + // + if (isCLLLSame) + { + // + lSameLLPivot.from = pBar.time; + + // + double reserve = lSameLLPivot.reserve; + if (pBar.low == pLLL) + { + // + reserve = + reserve == 0 + ? pBar.GetDown() + : MathMax(reserve, pBar.GetDown()); + } + lSameLLPivot.reserve = reserve; + } + + // + if (isLLLStartSame) + { + // + double reserve = lSameLLPivot.reserve; + if (cBar.low == cLLL) + { + // + reserve = + reserve == 0 + ? cBar.GetDown() + : MathMax(reserve, cBar.GetDown()); + } + if (pBar.low == pLLL) + { + // + reserve = + reserve == 0 + ? pBar.GetDown() + : MathMax(reserve, pBar.GetDown()); + } + if (reserve == 0 || reserve == lSameLLPivot.value) + { + reserve = lSameLLPivot.value + (5 * points); + } + lSameLLPivot.reserve = reserve; + + // + has = + lSameLLPivot.IsValid() && + lSameLLPivot.GetAge() >= pivotVerifications; + if (has) + { + // + AddPivot( + lSameLLPivot, + lSameLLPivots, + maxAllowedPivots // + ); + } + + // + lSameLLPivot.Clean(); + } + + // + // Hind Cycle ... + if (!hSameLLPivot.IsValid()) + { + // + hSameLLPivot.type = XCA_LL; + hSameLLPivot.symbol = iConditions.symbol; + hSameLLPivot.period = iConditions.period; + + // + if (isHLLFinishedSame) + { + // + hSameLLPivot.Clean(); + + // + hSameLLPivot.type = XCA_LL; + hSameLLPivot.symbol = iConditions.symbol; + hSameLLPivot.period = iConditions.period; + + // + hSameLLPivot.to = pBar.time; + hSameLLPivot.from = pBar.time; + hSameLLPivot.value = pHLL; + hSameLLPivot.reserve = pHLL; + } + } + + // + if (isCHLLSame) + { + // + hSameLLPivot.from = pBar.time; + + // + double reserve = hSameLLPivot.reserve; + if (pBar.low == pHLL) + { + // + reserve = + reserve == 0 + ? pBar.GetDown() + : MathMax(reserve, pBar.GetDown()); + } + hSameLLPivot.reserve = reserve; + } + + // + if (isHLLStartSame) + { + // + double reserve = hSameLLPivot.reserve; + if (cBar.low == cHLL) + { + // + reserve = + reserve == 0 + ? cBar.GetDown() + : MathMax(reserve, cBar.GetDown()); + } + if (pBar.low == pHLL) + { + // + reserve = + reserve == 0 + ? pBar.GetDown() + : MathMax(reserve, pBar.GetDown()); + } + if (reserve == 0 || reserve == hSameLLPivot.value) + { + reserve = hSameLLPivot.value + (5 * points); + } + hSameLLPivot.reserve = reserve; + + // + has = + hSameLLPivot.IsValid() && + hSameLLPivot.GetAge() >= pivotVerifications; + if (has) + { + // + AddPivot( + hSameLLPivot, + hSameLLPivots, + maxAllowedPivots // + ); + } + + // + hSameLLPivot.Clean(); + } + } + + // + // Cycles HH ... + if (detectCycleSameHHPivot) + { + // + // Short Cycle ... + if (!sSameHHPivot.IsValid()) + { + // + sSameHHPivot.type = XCA_HH; + sSameHHPivot.symbol = iConditions.symbol; + sSameHHPivot.period = iConditions.period; + + // + if (isSHHFinishedSame) + { + // + sSameHHPivot.Clean(); + + // + sSameHHPivot.type = XCA_HH; + sSameHHPivot.symbol = iConditions.symbol; + sSameHHPivot.period = iConditions.period; + + // + sSameHHPivot.to = pBar.time; + sSameHHPivot.from = pBar.time; + sSameHHPivot.value = pSHH; + sSameHHPivot.reserve = pSHH; + } + } + + // + if (isCSHHSame) + { + // + sSameHHPivot.from = pBar.time; + + // + double reserve = sSameHHPivot.reserve; + if (pBar.high == pSHH) + { + // + reserve = + reserve == 0 + ? pBar.GetUp() + : MathMin(reserve, pBar.GetUp()); + } + sSameHHPivot.reserve = reserve; + } + + // + if (isSHHStartSame) + { + // + double reserve = sSameHHPivot.reserve; + if (cBar.high == cSHH) + { + // + reserve = + reserve == 0 + ? cBar.GetUp() + : MathMin(reserve, cBar.GetUp()); + } + if (pBar.high == pSHH) + { + // + reserve = + reserve == 0 + ? pBar.GetUp() + : MathMin(reserve, pBar.GetUp()); + } + if (reserve == 0 || reserve == sSameHHPivot.value) + { + reserve = sSameHHPivot.value + (5 * points); + } + sSameHHPivot.reserve = reserve; + + // + has = + sSameHHPivot.IsValid() && + sSameHHPivot.GetAge() >= pivotVerifications; + if (has) + { + // + AddPivot( + sSameHHPivot, + sSameHHPivots, + maxAllowedPivots // + ); + } + + // + sSameHHPivot.Clean(); + } + + // + // Medium Cycle ... + if (!mSameHHPivot.IsValid()) + { + // + mSameHHPivot.type = XCA_HH; + mSameHHPivot.symbol = iConditions.symbol; + mSameHHPivot.period = iConditions.period; + + // + if (isMHHFinishedSame) + { + // + mSameHHPivot.Clean(); + + // + mSameHHPivot.type = XCA_HH; + mSameHHPivot.symbol = iConditions.symbol; + mSameHHPivot.period = iConditions.period; + + // + mSameHHPivot.to = pBar.time; + mSameHHPivot.from = pBar.time; + mSameHHPivot.value = pMHH; + mSameHHPivot.reserve = pMHH; + } + } + + // + if (isCMHHSame) + { + // + mSameHHPivot.from = pBar.time; + + // + double reserve = mSameHHPivot.reserve; + if (pBar.high == pMHH) + { + // + reserve = + reserve == 0 + ? pBar.GetUp() + : MathMin(reserve, pBar.GetUp()); + } + mSameHHPivot.reserve = reserve; + } + + // + if (isMHHStartSame) + { + // + double reserve = mSameHHPivot.reserve; + if (cBar.high == cMHH) + { + // + reserve = + reserve == 0 + ? cBar.GetUp() + : MathMin(reserve, cBar.GetUp()); + } + if (pBar.high == pMHH) + { + // + reserve = + reserve == 0 + ? pBar.GetUp() + : MathMin(reserve, pBar.GetUp()); + } + if (reserve == 0 || reserve == mSameHHPivot.value) + { + reserve = mSameHHPivot.value + (5 * points); + } + mSameHHPivot.reserve = reserve; + + // + has = + mSameHHPivot.IsValid() && + mSameHHPivot.GetAge() >= pivotVerifications; + if (has) + { + // + AddPivot( + mSameHHPivot, + mSameHHPivots, + maxAllowedPivots // + ); + } + + // + mSameHHPivot.Clean(); + } + + // + // Long Cycle ... + if (!lSameHHPivot.IsValid()) + { + // + lSameHHPivot.type = XCA_HH; + lSameHHPivot.symbol = iConditions.symbol; + lSameHHPivot.period = iConditions.period; + + // + if (isLHHFinishedSame) + { + // + lSameHHPivot.Clean(); + + // + lSameHHPivot.type = XCA_HH; + lSameHHPivot.symbol = iConditions.symbol; + lSameHHPivot.period = iConditions.period; + + // + lSameHHPivot.to = pBar.time; + lSameHHPivot.from = pBar.time; + lSameHHPivot.value = pLHH; + lSameHHPivot.reserve = pLHH; + } + } + + // + if (isCLHHSame) + { + // + lSameHHPivot.from = pBar.time; + + // + double reserve = lSameHHPivot.reserve; + if (pBar.high == pLHH) + { + // + reserve = + reserve == 0 + ? pBar.GetUp() + : MathMin(reserve, pBar.GetUp()); + } + lSameHHPivot.reserve = reserve; + } + + // + if (isLHHStartSame) + { + // + double reserve = lSameHHPivot.reserve; + if (cBar.high == cLHH) + { + // + reserve = + reserve == 0 + ? cBar.GetUp() + : MathMin(reserve, cBar.GetUp()); + } + if (pBar.high == pLHH) + { + // + reserve = + reserve == 0 + ? pBar.GetUp() + : MathMin(reserve, pBar.GetUp()); + } + if (reserve == 0 || reserve == lSameHHPivot.value) + { + reserve = lSameHHPivot.value + (5 * points); + } + lSameHHPivot.reserve = reserve; + + // + has = + lSameHHPivot.IsValid() && + lSameHHPivot.GetAge() >= pivotVerifications; + if (has) + { + // + AddPivot( + lSameHHPivot, + lSameHHPivots, + maxAllowedPivots // + ); + } + + // + lSameHHPivot.Clean(); + } + + // + // Hind Cycle ... + if (!hSameHHPivot.IsValid()) + { + // + hSameHHPivot.type = XCA_HH; + hSameHHPivot.symbol = iConditions.symbol; + hSameHHPivot.period = iConditions.period; + + // + if (isHHHFinishedSame) + { + // + hSameHHPivot.Clean(); + + // + hSameHHPivot.type = XCA_HH; + hSameHHPivot.symbol = iConditions.symbol; + hSameHHPivot.period = iConditions.period; + + // + hSameHHPivot.to = pBar.time; + hSameHHPivot.from = pBar.time; + hSameHHPivot.value = pHHH; + hSameHHPivot.reserve = pHHH; + } + } + + // + if (isCHHHSame) + { + // + hSameHHPivot.from = pBar.time; + + // + double reserve = hSameHHPivot.reserve; + if (pBar.high == pHHH) + { + // + reserve = + reserve == 0 + ? pBar.GetUp() + : MathMin(reserve, pBar.GetUp()); + } + hSameHHPivot.reserve = reserve; + } + + // + if (isHHHStartSame) + { + // + double reserve = hSameHHPivot.reserve; + if (cBar.high == cHHH) + { + // + reserve = + reserve == 0 + ? cBar.GetUp() + : MathMin(reserve, cBar.GetUp()); + } + if (pBar.high == pHHH) + { + // + reserve = + reserve == 0 + ? pBar.GetUp() + : MathMin(reserve, pBar.GetUp()); + } + if (reserve == 0 || reserve == hSameHHPivot.value) + { + reserve = hSameHHPivot.value + (5 * points); + } + hSameHHPivot.reserve = reserve; + + // + has = + hSameHHPivot.IsValid() && + hSameHHPivot.GetAge() >= pivotVerifications; + if (has) + { + // + AddPivot( + hSameHHPivot, + hSameHHPivots, + maxAllowedPivots // + ); + } + + // + hSameHHPivot.Clean(); + } + } + + // + // RSI Peak ... + if (detectRSIPeakPivot) + { + // + if (isRSIPeak) + { + // + XCAPivot iPivot; + + // + iPivot.to = cBar.time; + iPivot.from = p2Bar.time; + iPivot.value = pBar.high; + iPivot.type = XCA_RSI_PEAK; + iPivot.symbol = cBar.symbol; + iPivot.period = cBar.period; + + // + Add( + cBar.high, + iPivot.values // + ); + Add( + pBar.high, + iPivot.values // + ); + Add( + p2Bar.high, + iPivot.values // + ); + Add( + cBar.close, + iPivot.values // + ); + Add( + pBar.close, + iPivot.values // + ); + Add( + p2Bar.close, + iPivot.values // + ); + + // + iPivot.reserve = GetMin(iPivot.values); + + // + AddPivot( + iPivot, + rsiPeakPivots, + maxAllowedPivots // + ); + + // + iPivot.Clean(); + } + } + + // + // RSI Vale ... + if (detectRSIValePivot) + { + // + if (isRSIVale) + { + // + XCAPivot iPivot; + + // + iPivot.to = cBar.time; + iPivot.from = p2Bar.time; + iPivot.value = pBar.low; + iPivot.type = XCA_RSI_VALE; + iPivot.symbol = cBar.symbol; + iPivot.period = cBar.period; + + // + Add( + cBar.low, + iPivot.values // + ); + Add( + pBar.low, + iPivot.values // + ); + Add( + p2Bar.low, + iPivot.values // + ); + Add( + cBar.close, + iPivot.values // + ); + Add( + pBar.close, + iPivot.values // + ); + Add( + p2Bar.close, + iPivot.values // + ); + + // + iPivot.reserve = GetMax(iPivot.values); + + // + AddPivot( + iPivot, + rsiValePivots, + maxAllowedPivots // + ); + + // + iPivot.Clean(); + } + } + + // + // RSI Crossed Over OS ... + if (detectRSICrossedOverOSPivot) + { + // + if (isRSIBullishVPattern) + { + // + XCAPivot iPivot; + + // + iPivot.to = cBar.time; + iPivot.from = p2Bar.time; + iPivot.value = pBar.low; + iPivot.type = XCA_RSI_COOS; + iPivot.symbol = cBar.symbol; + iPivot.period = cBar.period; + + // + Add( + cBar.low, + iPivot.values // + ); + Add( + pBar.low, + iPivot.values // + ); + Add( + p2Bar.low, + iPivot.values // + ); + Add( + cBar.close, + iPivot.values // + ); + Add( + pBar.close, + iPivot.values // + ); + Add( + p2Bar.close, + iPivot.values // + ); + + // + iPivot.reserve = GetMax(iPivot.values); + + // + AddPivot( + iPivot, + rsiCrossedOverOSPivots, + maxAllowedPivots // + ); + + // + iPivot.Clean(); + } + } + + // + // RSI Crossed Under OS ... + if (detectRSICrossedUnderOBPivot) + { + // + if (isRSIBearishVPattern) + { + // + XCAPivot iPivot; + + // + iPivot.to = cBar.time; + iPivot.from = p2Bar.time; + iPivot.value = pBar.high; + iPivot.type = XCA_RSI_CUOB; + iPivot.symbol = cBar.symbol; + iPivot.period = cBar.period; + + // + Add( + cBar.high, + iPivot.values // + ); + Add( + pBar.high, + iPivot.values // + ); + Add( + p2Bar.high, + iPivot.values // + ); + Add( + cBar.close, + iPivot.values // + ); + Add( + pBar.close, + iPivot.values // + ); + Add( + p2Bar.close, + iPivot.values // + ); + + // + iPivot.reserve = GetMin(iPivot.values); + + // + AddPivot( + iPivot, + rsiCrossedUnderOBPivots, + maxAllowedPivots // + ); + + // + iPivot.Clean(); + } + } + + // + // CCI Peak ... + if (detectCCIPeakPivot) + { + // + if (isCCIPeak) + { + // + XCAPivot iPivot; + + // + iPivot.to = cBar.time; + iPivot.from = p2Bar.time; + iPivot.value = pBar.high; + iPivot.type = XCA_CCI_PEAK; + iPivot.symbol = cBar.symbol; + iPivot.period = cBar.period; + + // + Add( + cBar.high, + iPivot.values // + ); + Add( + pBar.high, + iPivot.values // + ); + Add( + p2Bar.high, + iPivot.values // + ); + Add( + cBar.close, + iPivot.values // + ); + Add( + pBar.close, + iPivot.values // + ); + Add( + p2Bar.close, + iPivot.values // + ); + + // + iPivot.reserve = GetMin(iPivot.values); + + // + AddPivot( + iPivot, + cciPeakPivots, + maxAllowedPivots // + ); + + // + iPivot.Clean(); + } + } + + // + // CCI Vale ... + if (detectCCIValePivot) + { + // + if (isCCIVale) + { + // + XCAPivot iPivot; + + // + iPivot.to = cBar.time; + iPivot.from = p2Bar.time; + iPivot.value = pBar.low; + iPivot.type = XCA_CCI_VALE; + iPivot.symbol = cBar.symbol; + iPivot.period = cBar.period; + + // + Add( + cBar.low, + iPivot.values // + ); + Add( + pBar.low, + iPivot.values // + ); + Add( + p2Bar.low, + iPivot.values // + ); + Add( + cBar.close, + iPivot.values // + ); + Add( + pBar.close, + iPivot.values // + ); + Add( + p2Bar.close, + iPivot.values // + ); + + // + iPivot.reserve = GetMax(iPivot.values); + + // + AddPivot( + iPivot, + cciValePivots, + maxAllowedPivots // + ); + + // + iPivot.Clean(); + } + } + + // + // CCI Crossed Over OS ... + if (detectCCICrossedOverOSPivot) + { + // + if (isCCIBullishVPattern) + { + // + XCAPivot iPivot; + + // + iPivot.to = cBar.time; + iPivot.from = p2Bar.time; + iPivot.value = pBar.low; + iPivot.type = XCA_CCI_COOS; + iPivot.symbol = cBar.symbol; + iPivot.period = cBar.period; + + // + Add( + cBar.low, + iPivot.values // + ); + Add( + pBar.low, + iPivot.values // + ); + Add( + p2Bar.low, + iPivot.values // + ); + Add( + cBar.close, + iPivot.values // + ); + Add( + pBar.close, + iPivot.values // + ); + Add( + p2Bar.close, + iPivot.values // + ); + + // + iPivot.reserve = GetMax(iPivot.values); + + // + AddPivot( + iPivot, + cciCrossedOverOSPivots, + maxAllowedPivots // + ); + + // + iPivot.Clean(); + } + } + + // + // CCI Crossed Under OS ... + if (detectCCICrossedUnderOBPivot) + { + // + if (isCCIBearishVPattern) + { + // + XCAPivot iPivot; + + // + iPivot.to = cBar.time; + iPivot.from = p2Bar.time; + iPivot.value = pBar.high; + iPivot.type = XCA_CCI_CUOB; + iPivot.symbol = cBar.symbol; + iPivot.period = cBar.period; + + // + Add( + cBar.high, + iPivot.values // + ); + Add( + pBar.high, + iPivot.values // + ); + Add( + p2Bar.high, + iPivot.values // + ); + Add( + cBar.close, + iPivot.values // + ); + Add( + pBar.close, + iPivot.values // + ); + Add( + p2Bar.close, + iPivot.values // + ); + + // + iPivot.reserve = GetMin(iPivot.values); + + // + AddPivot( + iPivot, + cciCrossedUnderOBPivots, + maxAllowedPivots // + ); + + // + iPivot.Clean(); + } + } + + // + start++; + + // + zBar.Clean(); + cBar.Clean(); + pBar.Clean(); + p2Bar.Clean(); + fvgBox.Clean(); + iConditions.Clean(); + } + + // + } + + // + void Validate( + XBoxZone &unAvailableBoxes[], + int barIndex = 0 // + ) + { + // + // Do All Pivots Validation ... + + // + if (barIndex < 0) + { + barIndex = 0; + } + + // + XCAPivot tmp[]; + bool has = false; + + // + int zIDX = 0; + int cIDX = zIDX + 1; + int pIDX = cIDX + 1; + int p2IDX = pIDX + 1; + + // + // Implement Validation Senarios ... + + // + // PEAKS ... + + // + has = HasPeakPivots(); + if (has) + { + // + Copy( + peakPivots, + tmp // + ); + Clean(peakPivots); + while (HasChild(tmp)) + { + // + XCAPivot iPivot = tmp[0]; + ArrayRemove( + tmp, + 0, + 1 // + ); + + // + has = IsPivotBreaked( + iPivot, + unAvailableBoxes, + barIndex // + ); + if (!has) + { + // + AddRef( + iPivot, + peakPivots // + ); + } + } + Clean(tmp); + } + + // + // VALES ... + + // + has = HasValePivots(); + if (has) + { + // + Copy( + valePivots, + tmp // + ); + Clean(valePivots); + while (HasChild(tmp)) + { + // + XCAPivot iPivot = tmp[0]; + ArrayRemove( + tmp, + 0, + 1 // + ); + + // + has = IsPivotBreaked( + iPivot, + unAvailableBoxes, + barIndex // + ); + if (!has) + { + // + AddRef( + iPivot, + valePivots // + ); + } + } + Clean(tmp); + } + + // + // PEAK SWH RES ... + + // + has = HasPeakSWHResPivots(); + if (has) + { + // + Copy( + peakSWHResPivots, + tmp // + ); + Clean(peakSWHResPivots); + while (HasChild(tmp)) + { + // + XCAPivot iPivot = tmp[0]; + ArrayRemove( + tmp, + 0, + 1 // + ); + + // + has = IsPivotBreaked( + iPivot, + unAvailableBoxes, + barIndex // + ); + if (!has) + { + // + AddRef( + iPivot, + peakSWHResPivots // + ); + } + } + Clean(tmp); + } + + // + // VALE SWL SUP ... + + // + has = HasValeSWLSupPivots(); + if (has) + { + // + Copy( + valeSWLSupPivots, + tmp // + ); + Clean(valeSWLSupPivots); + while (HasChild(tmp)) + { + // + XCAPivot iPivot = tmp[0]; + ArrayRemove( + tmp, + 0, + 1 // + ); + + // + has = IsPivotBreaked( + iPivot, + unAvailableBoxes, + barIndex // + ); + if (!has) + { + // + AddRef( + iPivot, + valeSWLSupPivots // + ); + } + } + Clean(tmp); + } + + // + // SWING HIGH ... + + // + has = HasSWHPivots(); + if (has) + { + // + Copy( + swhPivots, + tmp // + ); + Clean(swhPivots); + while (HasChild(tmp)) + { + // + XCAPivot iPivot = tmp[0]; + ArrayRemove( + tmp, + 0, + 1 // + ); + + // + has = IsPivotBreaked( + iPivot, + unAvailableBoxes, + barIndex // + ); + if (!has) + { + // + AddRef( + iPivot, + swhPivots // + ); + } + } + Clean(tmp); + } + + // + // SWING LOW ... + + // + has = HasSWLPivots(); + if (has) + { + // + Copy( + swlPivots, + tmp // + ); + Clean(swlPivots); + while (HasChild(tmp)) + { + // + XCAPivot iPivot = tmp[0]; + ArrayRemove( + tmp, + 0, + 1 // + ); + + // + has = IsPivotBreaked( + iPivot, + unAvailableBoxes, + barIndex // + ); + if (!has) + { + // + AddRef( + iPivot, + swlPivots // + ); + } + } + Clean(tmp); + } + + // + // KI ... + + // + has = HasKIBullishPivots(); + if (has) + { + // + Copy( + kiBullishPivots, + tmp // + ); + Clean(kiBullishPivots); + while (HasChild(tmp)) + { + // + XCAPivot iPivot = tmp[0]; + ArrayRemove( + tmp, + 0, + 1 // + ); + + // + has = IsPivotBreaked( + iPivot, + unAvailableBoxes, + barIndex // + ); + if (!has) + { + // + AddRef( + iPivot, + kiBullishPivots // + ); + } + } + Clean(tmp); + } + + // + has = HasKIBearishPivots(); + if (has) + { + // + Copy( + kiBearishPivots, + tmp // + ); + Clean(kiBearishPivots); + while (HasChild(tmp)) + { + // + XCAPivot iPivot = tmp[0]; + ArrayRemove( + tmp, + 0, + 1 // + ); + + // + has = IsPivotBreaked( + iPivot, + unAvailableBoxes, + barIndex // + ); + if (!has) + { + // + AddRef( + iPivot, + kiBearishPivots // + ); + } + } + Clean(tmp); + } + + // + // TKI ... + + // + has = HasTKIBullishPivots(); + if (has) + { + // + Copy( + tkiBullishPivots, + tmp // + ); + Clean(tkiBullishPivots); + while (HasChild(tmp)) + { + // + XCAPivot iPivot = tmp[0]; + ArrayRemove( + tmp, + 0, + 1 // + ); + + // + has = IsPivotBreaked( + iPivot, + unAvailableBoxes, + barIndex // + ); + if (!has) + { + // + AddRef( + iPivot, + tkiBullishPivots // + ); + } + } + Clean(tmp); + } + + // + has = HasTKIBearishPivots(); + if (has) + { + // + Copy( + tkiBearishPivots, + tmp // + ); + Clean(tkiBearishPivots); + while (HasChild(tmp)) + { + // + XCAPivot iPivot = tmp[0]; + ArrayRemove( + tmp, + 0, + 1 // + ); + + // + has = IsPivotBreaked( + iPivot, + unAvailableBoxes, + barIndex // + ); + if (!has) + { + // + AddRef( + iPivot, + tkiBearishPivots // + ); + } + } + Clean(tmp); + } + + // + // FVG ... + + // + has = HasFVGBullishPivots(); + if (has) + { + // + Copy( + fvgBullishPivots, + tmp // + ); + Clean(fvgBullishPivots); + while (HasChild(tmp)) + { + // + XCAPivot iPivot = tmp[0]; + ArrayRemove( + tmp, + 0, + 1 // + ); + + // + has = IsPivotBreaked( + iPivot, + unAvailableBoxes, + barIndex // + ); + if (!has) + { + // + AddRef( + iPivot, + fvgBullishPivots // + ); + } + } + Clean(tmp); + } + + // + has = HasFVGBearishPivots(); + if (has) + { + // + Copy( + fvgBearishPivots, + tmp // + ); + Clean(fvgBearishPivots); + while (HasChild(tmp)) + { + // + XCAPivot iPivot = tmp[0]; + ArrayRemove( + tmp, + 0, + 1 // + ); + + // + has = IsPivotBreaked( + iPivot, + unAvailableBoxes, + barIndex // + ); + if (!has) + { + // + AddRef( + iPivot, + fvgBearishPivots // + ); + } + } + Clean(tmp); + } + + // + // PVFVG ... + XCAPVPivot tmpPVFVG[]; + + // + has = HasPVFVGBullishPivots(); + if (has) + { + // + Copy( + pvFVGBullishPivots, + tmpPVFVG // + ); + Clean(pvFVGBullishPivots); + while (HasChild(tmpPVFVG)) + { + // + XCAPVPivot iPVFVG = tmpPVFVG[0]; + ArrayRemove( + tmpPVFVG, + 0, + 1 // + ); + + // + XCAPivot tmpFVGs[]; + Copy( + iPVFVG.pivots, + tmpFVGs // + ); + Clean(iPVFVG.pivots); + while (HasChild(tmpFVGs)) + { + // + XCAPivot iPivot = tmpFVGs[0]; + ArrayRemove( + tmpFVGs, + 0, + 1 // + ); + + // + has = IsPivotBreaked( + iPivot, + unAvailableBoxes, + barIndex // + ); + if (!has) + { + // + AddRef( + iPivot, + iPVFVG.pivots // + ); + } + } + Clean(tmpFVGs); + + // + if (HasChild(iPVFVG.pivots)) + { + // + AddRef( + iPVFVG, + pvFVGBullishPivots // + ); + } + } + Clean(tmp); + Clean(tmpPVFVG); + } + + // + has = HasPVFVGBearishPivots(); + if (has) + { + // + Copy( + pvFVGBearishPivots, + tmpPVFVG // + ); + Clean(pvFVGBearishPivots); + while (HasChild(tmpPVFVG)) + { + // + XCAPVPivot iPVFVG = tmpPVFVG[0]; + ArrayRemove( + tmpPVFVG, + 0, + 1 // + ); + + // + XCAPivot tmpFVGs[]; + Copy( + iPVFVG.pivots, + tmpFVGs // + ); + Clean(iPVFVG.pivots); + while (HasChild(tmpFVGs)) + { + // + XCAPivot iPivot = tmpFVGs[0]; + ArrayRemove( + tmpFVGs, + 0, + 1 // + ); + + // + has = IsPivotBreaked( + iPivot, + unAvailableBoxes, + barIndex // + ); + if (!has) + { + // + AddRef( + iPivot, + iPVFVG.pivots // + ); + } + } + Clean(tmpFVGs); + + // + if (HasChild(iPVFVG.pivots)) + { + // + AddRef( + iPVFVG, + pvFVGBearishPivots // + ); + } + } + Clean(tmp); + Clean(tmpPVFVG); + } + + // + // TREND ... + + // + has = HasTrendBullishPivots(); + if (has) + { + // + Copy( + trendBullishPivots, + tmp // + ); + Clean(trendBullishPivots); + while (HasChild(tmp)) + { + // + XCAPivot iPivot = tmp[0]; + ArrayRemove( + tmp, + 0, + 1 // + ); + + // + has = IsPivotBreaked( + iPivot, + unAvailableBoxes, + barIndex // + ); + if (!has) + { + // + AddRef( + iPivot, + trendBullishPivots // + ); + } + } + Clean(tmp); + } + + // + has = HasTrendBearishPivots(); + if (has) + { + // + Copy( + trendBearishPivots, + tmp // + ); + Clean(trendBearishPivots); + while (HasChild(tmp)) + { + // + XCAPivot iPivot = tmp[0]; + ArrayRemove( + tmp, + 0, + 1 // + ); + + // + has = IsPivotBreaked( + iPivot, + unAvailableBoxes, + barIndex // + ); + if (!has) + { + // + AddRef( + iPivot, + trendBearishPivots // + ); + } + } + Clean(tmp); + } + + // + // TKITRND ... + + // + has = HasTKITRNDBullishPivots(); + if (has) + { + // + Copy( + tkitrndBullishPivots, + tmp // + ); + Clean(tkitrndBullishPivots); + while (HasChild(tmp)) + { + // + XCAPivot iPivot = tmp[0]; + ArrayRemove( + tmp, + 0, + 1 // + ); + + // + has = IsPivotBreaked( + iPivot, + unAvailableBoxes, + barIndex // + ); + if (!has) + { + // + AddRef( + iPivot, + tkitrndBullishPivots // + ); + } + } + Clean(tmp); + } + + // + has = HasTKITRNDBearishPivots(); + if (has) + { + // + Copy( + tkitrndBearishPivots, + tmp // + ); + Clean(tkitrndBearishPivots); + while (HasChild(tmp)) + { + // + XCAPivot iPivot = tmp[0]; + ArrayRemove( + tmp, + 0, + 1 // + ); + + // + has = IsPivotBreaked( + iPivot, + unAvailableBoxes, + barIndex // + ); + if (!has) + { + // + AddRef( + iPivot, + tkitrndBearishPivots // + ); + } + } + Clean(tmp); + } + + // + // SAME CYCLES HH / LL ... + + // + has = HasSSameLLPivots(); + if (has) + { + // + Copy( + sSameLLPivots, + tmp // + ); + Clean(sSameLLPivots); + while (HasChild(tmp)) + { + // + XCAPivot iPivot = tmp[0]; + ArrayRemove( + tmp, + 0, + 1 // + ); + + // + has = IsPivotBreaked( + iPivot, + unAvailableBoxes, + barIndex // + ); + if (!has) + { + // + AddRef( + iPivot, + sSameLLPivots // + ); + } + } + Clean(tmp); + } + + // + has = HasSSameHHPivots(); + if (has) + { + // + Copy( + sSameHHPivots, + tmp // + ); + Clean(sSameHHPivots); + while (HasChild(tmp)) + { + // + XCAPivot iPivot = tmp[0]; + ArrayRemove( + tmp, + 0, + 1 // + ); + + // + has = IsPivotBreaked( + iPivot, + unAvailableBoxes, + barIndex // + ); + if (!has) + { + // + AddRef( + iPivot, + sSameHHPivots // + ); + } + } + Clean(tmp); + } + + // + has = HasMSameLLPivots(); + if (has) + { + // + Copy( + mSameLLPivots, + tmp // + ); + Clean(mSameLLPivots); + while (HasChild(tmp)) + { + // + XCAPivot iPivot = tmp[0]; + ArrayRemove( + tmp, + 0, + 1 // + ); + + // + has = IsPivotBreaked( + iPivot, + unAvailableBoxes, + barIndex // + ); + if (!has) + { + // + AddRef( + iPivot, + mSameLLPivots // + ); + } + } + Clean(tmp); + } + + // + has = HasMSameHHPivots(); + if (has) + { + // + Copy( + mSameHHPivots, + tmp // + ); + Clean(mSameHHPivots); + while (HasChild(tmp)) + { + // + XCAPivot iPivot = tmp[0]; + ArrayRemove( + tmp, + 0, + 1 // + ); + + // + has = IsPivotBreaked( + iPivot, + unAvailableBoxes, + barIndex // + ); + if (!has) + { + // + AddRef( + iPivot, + mSameHHPivots // + ); + } + } + Clean(tmp); + } + + // + has = HasLSameLLPivots(); + if (has) + { + // + Copy( + lSameLLPivots, + tmp // + ); + Clean(lSameLLPivots); + while (HasChild(tmp)) + { + // + XCAPivot iPivot = tmp[0]; + ArrayRemove( + tmp, + 0, + 1 // + ); + + // + has = IsPivotBreaked( + iPivot, + unAvailableBoxes, + barIndex // + ); + if (!has) + { + // + AddRef( + iPivot, + lSameLLPivots // + ); + } + } + Clean(tmp); + } + + // + has = HasLSameHHPivots(); + if (has) + { + // + Copy( + lSameHHPivots, + tmp // + ); + Clean(lSameHHPivots); + while (HasChild(tmp)) + { + // + XCAPivot iPivot = tmp[0]; + ArrayRemove( + tmp, + 0, + 1 // + ); + + // + has = IsPivotBreaked( + iPivot, + unAvailableBoxes, + barIndex // + ); + if (!has) + { + // + AddRef( + iPivot, + lSameHHPivots // + ); + } + } + Clean(tmp); + } + + // + has = HasHSameLLPivots(); + if (has) + { + // + Copy( + hSameLLPivots, + tmp // + ); + Clean(hSameLLPivots); + while (HasChild(tmp)) + { + // + XCAPivot iPivot = tmp[0]; + ArrayRemove( + tmp, + 0, + 1 // + ); + + // + has = IsPivotBreaked( + iPivot, + unAvailableBoxes, + barIndex // + ); + if (!has) + { + // + AddRef( + iPivot, + hSameLLPivots // + ); + } + } + Clean(tmp); + } + + // + has = HasHSameHHPivots(); + if (has) + { + // + Copy( + hSameHHPivots, + tmp // + ); + Clean(hSameHHPivots); + while (HasChild(tmp)) + { + // + XCAPivot iPivot = tmp[0]; + ArrayRemove( + tmp, + 0, + 1 // + ); + + // + has = IsPivotBreaked( + iPivot, + unAvailableBoxes, + barIndex // + ); + if (!has) + { + // + AddRef( + iPivot, + hSameHHPivots // + ); + } + } + Clean(tmp); + } + + // + // OSCS ... + + // + // RSI ... + + // + has = HasRSIPeakPivots(); + if (has) + { + // + Copy( + rsiPeakPivots, + tmp // + ); + Clean(rsiPeakPivots); + while (HasChild(tmp)) + { + // + XCAPivot iPivot = tmp[0]; + ArrayRemove( + tmp, + 0, + 1 // + ); + + // + has = IsPivotBreaked( + iPivot, + unAvailableBoxes, + barIndex // + ); + if (!has) + { + // + AddRef( + iPivot, + rsiPeakPivots // + ); + } + } + Clean(tmp); + } + + // + has = HasRSIValePivots(); + if (has) + { + // + Copy( + rsiValePivots, + tmp // + ); + Clean(rsiValePivots); + while (HasChild(tmp)) + { + // + XCAPivot iPivot = tmp[0]; + ArrayRemove( + tmp, + 0, + 1 // + ); + + // + has = IsPivotBreaked( + iPivot, + unAvailableBoxes, + barIndex // + ); + if (!has) + { + // + AddRef( + iPivot, + rsiValePivots // + ); + } + } + Clean(tmp); + } + + // + has = HasRSICrossedOverOSPivots(); + if (has) + { + // + Copy( + rsiCrossedOverOSPivots, + tmp // + ); + Clean(rsiCrossedOverOSPivots); + while (HasChild(tmp)) + { + // + XCAPivot iPivot = tmp[0]; + ArrayRemove( + tmp, + 0, + 1 // + ); + + // + has = IsPivotBreaked( + iPivot, + unAvailableBoxes, + barIndex // + ); + if (!has) + { + // + AddRef( + iPivot, + rsiCrossedOverOSPivots // + ); + } + } + Clean(tmp); + } + + // + has = HasRSICrossedUnderOBPivots(); + if (has) + { + // + Copy( + rsiCrossedUnderOBPivots, + tmp // + ); + Clean(rsiCrossedUnderOBPivots); + while (HasChild(tmp)) + { + // + XCAPivot iPivot = tmp[0]; + ArrayRemove( + tmp, + 0, + 1 // + ); + + // + has = IsPivotBreaked( + iPivot, + unAvailableBoxes, + barIndex // + ); + if (!has) + { + // + AddRef( + iPivot, + rsiCrossedUnderOBPivots // + ); + } + } + Clean(tmp); + } + + // + // CCI ... + + // + has = HasCCIPeakPivots(); + if (has) + { + // + Copy( + cciPeakPivots, + tmp // + ); + Clean(cciPeakPivots); + while (HasChild(tmp)) + { + // + XCAPivot iPivot = tmp[0]; + ArrayRemove( + tmp, + 0, + 1 // + ); + + // + has = IsPivotBreaked( + iPivot, + unAvailableBoxes, + barIndex // + ); + if (!has) + { + // + AddRef( + iPivot, + cciPeakPivots // + ); + } + } + Clean(tmp); + } + + // + has = HasCCIValePivots(); + if (has) + { + // + Copy( + cciValePivots, + tmp // + ); + Clean(cciValePivots); + while (HasChild(tmp)) + { + // + XCAPivot iPivot = tmp[0]; + ArrayRemove( + tmp, + 0, + 1 // + ); + + // + has = IsPivotBreaked( + iPivot, + unAvailableBoxes, + barIndex // + ); + if (!has) + { + // + AddRef( + iPivot, + cciValePivots // + ); + } + } + Clean(tmp); + } + + // + has = HasCCICrossedOverOSPivots(); + if (has) + { + // + Copy( + cciCrossedOverOSPivots, + tmp // + ); + Clean(cciCrossedOverOSPivots); + while (HasChild(tmp)) + { + // + XCAPivot iPivot = tmp[0]; + ArrayRemove( + tmp, + 0, + 1 // + ); + + // + has = IsPivotBreaked( + iPivot, + unAvailableBoxes, + barIndex // + ); + if (!has) + { + // + AddRef( + iPivot, + cciCrossedOverOSPivots // + ); + } + } + Clean(tmp); + } + + // + has = HasCCICrossedUnderOBPivots(); + if (has) + { + // + Copy( + cciCrossedUnderOBPivots, + tmp // + ); + Clean(cciCrossedUnderOBPivots); + while (HasChild(tmp)) + { + // + XCAPivot iPivot = tmp[0]; + ArrayRemove( + tmp, + 0, + 1 // + ); + + // + has = IsPivotBreaked( + iPivot, + unAvailableBoxes, + barIndex // + ); + if (!has) + { + // + AddRef( + iPivot, + cciCrossedUnderOBPivots // + ); + } + } + Clean(tmp); + } + + // + // PVTICKS ... + + // + XCAPVTick tmpTicks[]; + + // + has = HasPeakTicks(); + if (has) + { + // + Copy( + peakTicks, + tmpTicks // + ); + Clean(peakTicks); + while (HasChild(tmpTicks)) + { + // + XCAPVTick iPVTick = tmpTicks[0]; + ArrayRemove( + tmpTicks, + 0, + 1 // + ); + + // + XBoxZone iBox; + bool isBoxBreaked = false; + has = iPVTick.GetMaxVolumeBox(iBox); + if (has) + { + // + isBoxBreaked = IsBoxBreaked( + iBox, + unAvailableBoxes, + barIndex // + ); + } + + // + has = IsPivotBreaked( + iPVTick.pivot, + unAvailableBoxes, + barIndex // + ); + if (!has && !isBoxBreaked) + { + // + AddRef( + iPVTick, + peakTicks // + ); + } + } + Clean(tmpTicks); + } + + // + has = HasValeTicks(); + if (has) + { + // + Copy( + valeTicks, + tmpTicks // + ); + Clean(valeTicks); + while (HasChild(tmpTicks)) + { + // + XCAPVTick iPVTick = tmpTicks[0]; + ArrayRemove( + tmpTicks, + 0, + 1 // + ); + + // + XBoxZone iBox; + bool isBoxBreaked = false; + has = iPVTick.GetMaxVolumeBox(iBox); + if (has) + { + // + isBoxBreaked = IsBoxBreaked( + iBox, + unAvailableBoxes, + barIndex // + ); + } + + // + has = IsPivotBreaked( + iPVTick.pivot, + unAvailableBoxes, + barIndex // + ); + if (!has && !isBoxBreaked) + { + // + AddRef( + iPVTick, + valeTicks // + ); + } + } + Clean(tmpTicks); + } + + // + Clean(tmp); + Clean(tmpPVFVG); + Clean(tmpTicks); + } + + // + int FillBullishBoxes( + XBoxZone &boxes[] // + ) + { + // + int result = 0; + + // + int count = 0; + bool has = false; + + // + Clean(boxes); + + // + has = HasSWLPivots(); + if (has) + { + // + count = CountSWLPivots(); + for (int i = 0; i < count; i++) + { + // + XBoxZone iBox; + has = swlPivots[i].AsBox(iBox); + if (has) + { + // + AddRef( + iBox, + boxes // + ); + } + + // + iBox.Clean(); + } + } + + // + has = HasValePivots(); + if (has) + { + // + count = CountValePivots(); + for (int i = 0; i < count; i++) + { + // + XBoxZone iBox; + has = valePivots[i].AsBox(iBox); + if (has) + { + // + AddRef( + iBox, + boxes // + ); + } + + // + iBox.Clean(); + } + } + + // + has = HasSSameLLPivots(); + if (has) + { + // + count = CountSSameLLPivots(); + for (int i = 0; i < count; i++) + { + // + XBoxZone iBox; + has = sSameLLPivots[i].AsBox(iBox); + if (has) + { + // + AddRef( + iBox, + boxes // + ); + } + + // + iBox.Clean(); + } + } + + // + has = HasMSameLLPivots(); + if (has) + { + // + count = CountMSameLLPivots(); + for (int i = 0; i < count; i++) + { + // + XBoxZone iBox; + has = mSameLLPivots[i].AsBox(iBox); + if (has) + { + // + AddRef( + iBox, + boxes // + ); + } + + // + iBox.Clean(); + } + } + + // + has = HasLSameLLPivots(); + if (has) + { + // + count = CountLSameLLPivots(); + for (int i = 0; i < count; i++) + { + // + XBoxZone iBox; + has = lSameLLPivots[i].AsBox(iBox); + if (has) + { + // + AddRef( + iBox, + boxes // + ); + } + + // + iBox.Clean(); + } + } + + // + has = HasHSameLLPivots(); + if (has) + { + // + count = CountHSameLLPivots(); + for (int i = 0; i < count; i++) + { + // + XBoxZone iBox; + has = hSameLLPivots[i].AsBox(iBox); + if (has) + { + // + AddRef( + iBox, + boxes // + ); + } + + // + iBox.Clean(); + } + } + + // + has = HasKIBullishPivots(); + if (has) + { + // + count = CountKIBullishPivots(); + for (int i = 0; i < count; i++) + { + // + XBoxZone iBox; + has = kiBullishPivots[i].AsBox(iBox); + if (has) + { + // + AddRef( + iBox, + boxes // + ); + } + + // + iBox.Clean(); + } + } + + // + has = HasFVGBullishPivots(); + if (has) + { + // + count = CountFVGBullishPivots(); + for (int i = 0; i < count; i++) + { + // + XBoxZone iBox; + has = fvgBullishPivots[i].AsBox(iBox); + if (has) + { + // + AddRef( + iBox, + boxes // + ); + } + + // + iBox.Clean(); + } + } + + // + has = HasValeSWLSupPivots(); + if (has) + { + // + count = CountValeSWLSupPivots(); + for (int i = 0; i < count; i++) + { + // + XBoxZone iBox; + has = valeSWLSupPivots[i].AsBox(iBox); + if (has) + { + // + AddRef( + iBox, + boxes // + ); + } + + // + iBox.Clean(); + } + } + + // + has = HasTKIBullishPivots(); + if (has) + { + // + count = CountTKIBullishPivots(); + for (int i = 0; i < count; i++) + { + // + XBoxZone iBox; + has = tkiBullishPivots[i].AsBox(iBox); + if (has) + { + // + AddRef( + iBox, + boxes // + ); + } + + // + iBox.Clean(); + } + } + + // + has = HasTrendBullishPivots(); + if (has) + { + // + count = CountTrendBullishPivots(); + for (int i = 0; i < count; i++) + { + // + XBoxZone iBox; + has = trendBullishPivots[i].AsBox(iBox); + if (has) + { + // + AddRef( + iBox, + boxes // + ); + } + + // + iBox.Clean(); + } + } + + // + has = HasTKITRNDBullishPivots(); + if (has) + { + // + count = CountTKITRNDBullishPivots(); + for (int i = 0; i < count; i++) + { + // + XBoxZone iBox; + has = tkitrndBullishPivots[i].AsBox(iBox); + if (has) + { + // + AddRef( + iBox, + boxes // + ); + } + + // + iBox.Clean(); + } + } + + // + has = HasRSIValePivots(); + if (has) + { + // + count = CountRSIValePivots(); + for (int i = 0; i < count; i++) + { + // + XBoxZone iBox; + has = rsiValePivots[i].AsBox(iBox); + if (has) + { + // + AddRef( + iBox, + boxes // + ); + } + + // + iBox.Clean(); + } + } + + // + has = HasRSICrossedOverOSPivots(); + if (has) + { + // + count = CountRSICrossedOverOSPivots(); + for (int i = 0; i < count; i++) + { + // + XBoxZone iBox; + has = rsiCrossedOverOSPivots[i].AsBox(iBox); + if (has) + { + // + AddRef( + iBox, + boxes // + ); + } + + // + iBox.Clean(); + } + } + + // + has = HasCCIValePivots(); + if (has) + { + // + count = CountCCIValePivots(); + for (int i = 0; i < count; i++) + { + // + XBoxZone iBox; + has = cciValePivots[i].AsBox(iBox); + if (has) + { + // + AddRef( + iBox, + boxes // + ); + } + + // + iBox.Clean(); + } + } + + // + has = HasCCICrossedOverOSPivots(); + if (has) + { + // + count = CountCCICrossedOverOSPivots(); + for (int i = 0; i < count; i++) + { + // + XBoxZone iBox; + has = cciCrossedOverOSPivots[i].AsBox(iBox); + if (has) + { + // + AddRef( + iBox, + boxes // + ); + } + + // + iBox.Clean(); + } + } + + // + result = ArraySize(boxes); + + // + return result; + } + + // + int FillBearishBoxes( + XBoxZone &boxes[] // + ) + { + // + int result = 0; + + // + int count = 0; + bool has = false; + + // + Clean(boxes); + + // + has = HasSWHPivots(); + if (has) + { + // + count = CountSWHPivots(); + for (int i = 0; i < count; i++) + { + // + XBoxZone iBox; + has = swhPivots[i].AsBox(iBox); + if (has) + { + // + AddRef( + iBox, + boxes // + ); + } + + // + iBox.Clean(); + } + } + + // + has = HasPeakPivots(); + if (has) + { + // + count = CountPeakPivots(); + for (int i = 0; i < count; i++) + { + // + XBoxZone iBox; + has = peakPivots[i].AsBox(iBox); + if (has) + { + // + AddRef( + iBox, + boxes // + ); + } + + // + iBox.Clean(); + } + } + + // + has = HasSSameHHPivots(); + if (has) + { + // + count = CountSSameHHPivots(); + for (int i = 0; i < count; i++) + { + // + XBoxZone iBox; + has = sSameHHPivots[i].AsBox(iBox); + if (has) + { + // + AddRef( + iBox, + boxes // + ); + } + + // + iBox.Clean(); + } + } + + // + has = HasMSameHHPivots(); + if (has) + { + // + count = CountMSameHHPivots(); + for (int i = 0; i < count; i++) + { + // + XBoxZone iBox; + has = mSameHHPivots[i].AsBox(iBox); + if (has) + { + // + AddRef( + iBox, + boxes // + ); + } + + // + iBox.Clean(); + } + } + + // + has = HasLSameHHPivots(); + if (has) + { + // + count = CountLSameHHPivots(); + for (int i = 0; i < count; i++) + { + // + XBoxZone iBox; + has = lSameHHPivots[i].AsBox(iBox); + if (has) + { + // + AddRef( + iBox, + boxes // + ); + } + + // + iBox.Clean(); + } + } + + // + has = HasHSameHHPivots(); + if (has) + { + // + count = CountHSameHHPivots(); + for (int i = 0; i < count; i++) + { + // + XBoxZone iBox; + has = hSameHHPivots[i].AsBox(iBox); + if (has) + { + // + AddRef( + iBox, + boxes // + ); + } + + // + iBox.Clean(); + } + } + + // + has = HasKIBearishPivots(); + if (has) + { + // + count = CountKIBearishPivots(); + for (int i = 0; i < count; i++) + { + // + XBoxZone iBox; + has = kiBearishPivots[i].AsBox(iBox); + if (has) + { + // + AddRef( + iBox, + boxes // + ); + } + + // + iBox.Clean(); + } + } + + // + has = HasFVGBearishPivots(); + if (has) + { + // + count = CountFVGBearishPivots(); + for (int i = 0; i < count; i++) + { + // + XBoxZone iBox; + has = fvgBearishPivots[i].AsBox(iBox); + if (has) + { + // + AddRef( + iBox, + boxes // + ); + } + + // + iBox.Clean(); + } + } + + // + has = HasPeakSWHResPivots(); + if (has) + { + // + count = CountPeakSWHResPivots(); + for (int i = 0; i < count; i++) + { + // + XBoxZone iBox; + has = peakSWHResPivots[i].AsBox(iBox); + if (has) + { + // + AddRef( + iBox, + boxes // + ); + } + + // + iBox.Clean(); + } + } + + // + has = HasTKIBearishPivots(); + if (has) + { + // + count = CountTKIBearishPivots(); + for (int i = 0; i < count; i++) + { + // + XBoxZone iBox; + has = tkiBearishPivots[i].AsBox(iBox); + if (has) + { + // + AddRef( + iBox, + boxes // + ); + } + + // + iBox.Clean(); + } + } + + // + has = HasTrendBearishPivots(); + if (has) + { + // + count = CountTrendBearishPivots(); + for (int i = 0; i < count; i++) + { + // + XBoxZone iBox; + has = trendBearishPivots[i].AsBox(iBox); + if (has) + { + // + AddRef( + iBox, + boxes // + ); + } + + // + iBox.Clean(); + } + } + + // + has = HasTKITRNDBearishPivots(); + if (has) + { + // + count = CountTKITRNDBearishPivots(); + for (int i = 0; i < count; i++) + { + // + XBoxZone iBox; + has = tkitrndBearishPivots[i].AsBox(iBox); + if (has) + { + // + AddRef( + iBox, + boxes // + ); + } + + // + iBox.Clean(); + } + } + + // + has = HasRSIPeakPivots(); + if (has) + { + // + count = CountRSIPeakPivots(); + for (int i = 0; i < count; i++) + { + // + XBoxZone iBox; + has = rsiPeakPivots[i].AsBox(iBox); + if (has) + { + // + AddRef( + iBox, + boxes // + ); + } + + // + iBox.Clean(); + } + } + + // + has = HasRSICrossedUnderOBPivots(); + if (has) + { + // + count = CountRSICrossedUnderOBPivots(); + for (int i = 0; i < count; i++) + { + // + XBoxZone iBox; + has = rsiCrossedUnderOBPivots[i].AsBox(iBox); + if (has) + { + // + AddRef( + iBox, + boxes // + ); + } + + // + iBox.Clean(); + } + } + + // + has = HasCCIPeakPivots(); + if (has) + { + // + count = CountCCIPeakPivots(); + for (int i = 0; i < count; i++) + { + // + XBoxZone iBox; + has = cciPeakPivots[i].AsBox(iBox); + if (has) + { + // + AddRef( + iBox, + boxes // + ); + } + + // + iBox.Clean(); + } + } + + // + has = HasCCICrossedUnderOBPivots(); + if (has) + { + // + count = CountCCICrossedUnderOBPivots(); + for (int i = 0; i < count; i++) + { + // + XBoxZone iBox; + has = cciCrossedUnderOBPivots[i].AsBox(iBox); + if (has) + { + // + AddRef( + iBox, + boxes // + ); + } + + // + iBox.Clean(); + } + } + + // + result = ArraySize(boxes); + + // + return result; + } + + // + // POI Handlers ... + + // + // PEAK ... + + // + bool HasPeakPivots() + { + return HasChild(peakPivots); + } + + // + int CountPeakPivots() + { + return ArraySize(peakPivots); + } + + // + // VALE ... + + // + bool HasValePivots() + { + return HasChild(valePivots); + } + + // + int CountValePivots() + { + return ArraySize(valePivots); + } + + // + // PEAK SWH Res ... + + // + bool HasPeakSWHResPivots() + { + return HasChild(peakSWHResPivots); + } + + // + int CountPeakSWHResPivots() + { + return ArraySize(peakSWHResPivots); + } + + // + // VALE SWL Sup ... + + // + bool HasValeSWLSupPivots() + { + return HasChild(valeSWLSupPivots); + } + + // + int CountValeSWLSupPivots() + { + return ArraySize(valeSWLSupPivots); + } + + // + // SWING High ... + + // + bool HasSWHPivots() + { + return HasChild(swhPivots); + } + + // + int CountSWHPivots() + { + return ArraySize(swhPivots); + } + + // + // SWING Low ... + + // + bool HasSWLPivots() + { + return HasChild(swlPivots); + } + + // + int CountSWLPivots() + { + return ArraySize(swlPivots); + } + + // + // KI ... + + // + bool HasKIBullishPivots() + { + return HasChild(kiBullishPivots); + } + + // + int CountKIBullishPivots() + { + return ArraySize(kiBullishPivots); + } + + // + bool HasKIBearishPivots() + { + return HasChild(kiBearishPivots); + } + + // + int CountKIBearishPivots() + { + return ArraySize(kiBearishPivots); + } + + // + // TKI ... + + // + bool HasTKIBullishPivots() + { + return HasChild(tkiBullishPivots); + } + + // + int CountTKIBullishPivots() + { + return ArraySize(tkiBullishPivots); + } + + // + bool HasTKIBearishPivots() + { + return HasChild(tkiBearishPivots); + } + + // + int CountTKIBearishPivots() + { + return ArraySize(tkiBearishPivots); + } + + // + // FVG ... + + // + bool HasFVGBullishPivots() + { + return HasChild(fvgBullishPivots); + } + + // + int CountFVGBullishPivots() + { + return ArraySize(fvgBullishPivots); + } + + // + bool HasFVGBearishPivots() + { + return HasChild(fvgBearishPivots); + } + + // + int CountFVGBearishPivots() + { + return ArraySize(fvgBearishPivots); + } + + // + // PVFVG ... + + // + bool HasPVFVGBullishPivots() + { + return HasChild(pvFVGBullishPivots); + } + + // + int CountPVFVGBullishPivots() + { + return ArraySize(pvFVGBullishPivots); + } + + // + bool HasPVFVGBearishPivots() + { + return HasChild(pvFVGBearishPivots); + } + + // + int CountPVFVGBearishPivots() + { + return ArraySize(pvFVGBearishPivots); + } + + // + // TREND ... + + // + bool HasTrendBullishPivots() + { + return HasChild(trendBullishPivots); + } + + // + int CountTrendBullishPivots() + { + return ArraySize(trendBullishPivots); + } + + // + bool HasTrendBearishPivots() + { + return HasChild(trendBearishPivots); + } + + // + int CountTrendBearishPivots() + { + return ArraySize(trendBearishPivots); + } + + // + // TKITRND ... + + // + bool HasTKITRNDBullishPivots() + { + return HasChild(tkitrndBullishPivots); + } + + // + int CountTKITRNDBullishPivots() + { + return ArraySize(tkitrndBullishPivots); + } + + // + bool HasTKITRNDBearishPivots() + { + return HasChild(tkitrndBearishPivots); + } + + // + int CountTKITRNDBearishPivots() + { + return ArraySize(tkitrndBearishPivots); + } + + // + // SAME CYCLES HH / LL ... + + // + bool HasSSameLLPivots() + { + return HasChild(sSameLLPivots); + } + + // + int CountSSameLLPivots() + { + return ArraySize(sSameLLPivots); + } + + // + bool HasMSameLLPivots() + { + return HasChild(mSameLLPivots); + } + + // + int CountMSameLLPivots() + { + return ArraySize(mSameLLPivots); + } + + // + bool HasLSameLLPivots() + { + return HasChild(lSameLLPivots); + } + + // + int CountLSameLLPivots() + { + return ArraySize(lSameLLPivots); + } + + // + bool HasHSameLLPivots() + { + return HasChild(hSameLLPivots); + } + + // + int CountHSameLLPivots() + { + return ArraySize(hSameLLPivots); + } + + // + bool HasSSameHHPivots() + { + return HasChild(sSameHHPivots); + } + + // + int CountSSameHHPivots() + { + return ArraySize(sSameHHPivots); + } + + // + bool HasMSameHHPivots() + { + return HasChild(mSameHHPivots); + } + + // + int CountMSameHHPivots() + { + return ArraySize(mSameHHPivots); + } + + // + bool HasLSameHHPivots() + { + return HasChild(lSameHHPivots); + } + + // + int CountLSameHHPivots() + { + return ArraySize(lSameHHPivots); + } + + // + bool HasHSameHHPivots() + { + return HasChild(hSameHHPivots); + } + + // + int CountHSameHHPivots() + { + return ArraySize(hSameHHPivots); + } + + // + // OSCS ... + + // + // RSI ... + + // + bool HasRSIPeakPivots() + { + return HasChild(rsiPeakPivots); + } + + // + int CountRSIPeakPivots() + { + return ArraySize(rsiPeakPivots); + } + + // + bool HasRSIValePivots() + { + return HasChild(rsiValePivots); + } + + // + int CountRSIValePivots() + { + return ArraySize(rsiValePivots); + } + + // + bool HasRSICrossedOverOSPivots() + { + return HasChild(rsiCrossedOverOSPivots); + } + + // + int CountRSICrossedOverOSPivots() + { + return ArraySize(rsiCrossedOverOSPivots); + } + + // + bool HasRSICrossedUnderOBPivots() + { + return HasChild(rsiCrossedUnderOBPivots); + } + + // + int CountRSICrossedUnderOBPivots() + { + return ArraySize(rsiCrossedUnderOBPivots); + } + + // + // CCI ... + + // + bool HasCCIPeakPivots() + { + return HasChild(cciPeakPivots); + } + + // + int CountCCIPeakPivots() + { + return ArraySize(cciPeakPivots); + } + + // + bool HasCCIValePivots() + { + return HasChild(cciValePivots); + } + + // + int CountCCIValePivots() + { + return ArraySize(cciValePivots); + } + + // + bool HasCCICrossedOverOSPivots() + { + return HasChild(cciCrossedOverOSPivots); + } + + // + int CountCCICrossedOverOSPivots() + { + return ArraySize(cciCrossedOverOSPivots); + } + + // + bool HasCCICrossedUnderOBPivots() + { + return HasChild(cciCrossedUnderOBPivots); + } + + // + int CountCCICrossedUnderOBPivots() + { + return ArraySize(cciCrossedUnderOBPivots); + } + + // + // PVTICKS ... + + // + bool HasPeakTicks() + { + return HasChild(peakTicks); + } + + // + int CountPeakTicks() + { + return ArraySize(peakTicks); + } + + // + bool HasValeTicks() + { + return HasChild(valeTicks); + } + + // + int CountValeTicks() + { + return ArraySize(valeTicks); + } + + // + // Protected ... + protected: + // + // Props ... + + // + // Prrivate ... + private: + // + // Props ... + + // + XCPOIDrawer *drawer; + XCXCAEAHelper *helper; + XCBarAnalyser *barAnalyser; + + // + bool CheckPivotCommons( + XCAPivot &pivot, + XBoxZone &box, + XBoxZone &unAvailableBoxes[], + int barIndex = 0 // + ) + { + // + bool result = false; + + // + box.Clean(); + + // + barIndex = NormalizeInt(barIndex, 0); + + // + result = pivot.IsValid(); + if (!result) + { + return result; + } + + // + int pivotToIDX = pivot.ToIndex(); + + // + result = pivotToIDX > barIndex; + if (!result) + { + return result; + } + + // + result = pivot.AsBox(box); + if (!result) + { + // + box.Clean(); + return result; + } + + // + return result; + } + + // + bool CheckPivotIsAvailable( + XBoxZone &pivotBox, + XBoxZone &unAvailableBoxes[] // + ) + { + // + bool result = false; + + // + result = pivotBox.IsValid(); + if (!result) + { + return result; + } + + // + int idx = -1; + bool isExists = FindBoxIndex( + idx, + pivotBox, + unAvailableBoxes // + ); + result = !isExists; + + // + return result; + } + + // + bool IsPivotBreaked( + XCAPivot &pivot, + XBoxZone &unAvailableBoxes[], + int barIndex = 0 // + ) + { + // + bool result = false; + + // + XBoxZone iBox; + result = CheckPivotCommons( + pivot, + iBox, + unAvailableBoxes, + barIndex // + ); + if (!result) + { + // + iBox.Clean(); + return result; + } + + // + // Check Box is Available Or Not ... + bool isAvailable = CheckPivotIsAvailable( + iBox, + unAvailableBoxes // + ); + if (!isAvailable) + { + // + iBox.Clean(); + + // + // Assume UnAvailable Boes as Breaked ... + result = true; + return result; + } + + // + bool isBullish = iBox.IsBullish(); + double boundary = + isBullish + ? iBox.lower + : iBox.upper; + + // + int toIDX = iBox.ToIndex(); + + // + // for validating Box Break we have to wait At Least 3 Bars Close + // out of Box Boundary ... + int barsLength = 3; + + // + int startCheckBreaktionBarIndex = toIDX - barsLength; + result = startCheckBreaktionBarIndex > 0 && + barIndex < startCheckBreaktionBarIndex; + if (!result) + { + // + iBox.Clean(); + return result; + } + + // + XOHCL cBar; + XOHCL pBar; + XOHCL p2Bar; + for (int i = barIndex; i < startCheckBreaktionBarIndex; i++) + { + // + result = cBar.Init( + iBox.symbol, + iBox.period, + i + 1 // + ); + result = + result && + cBar.GetPreviousBar(pBar); + result = + result && + pBar.GetPreviousBar(p2Bar); + if (!result) + { + // + iBox.Clean(); + cBar.Clean(); + pBar.Clean(); + p2Bar.Clean(); + + // + break; + } + + // + bool isBullishBreaked = + isBullish && + cBar.close < boundary && + pBar.close < boundary && + p2Bar.close < boundary; + + // + bool isBearishBreaked = + !isBullish && + cBar.close > boundary && + pBar.close > boundary && + p2Bar.close > boundary; + + // + result = isBullishBreaked || + isBearishBreaked; + if (result) + { + break; + } + + // + cBar.Clean(); + pBar.Clean(); + p2Bar.Clean(); + } + + // + iBox.Clean(); + cBar.Clean(); + pBar.Clean(); + p2Bar.Clean(); + + // + return result; + } + + // + bool IsBoxBreaked( + XBoxZone &box, + XBoxZone &unAvailableBoxes[], + int barIndex = 0 // + ) + { + // + bool result = false; + + // + barIndex = NormalizeInt(barIndex, 0); + + // + result = box.IsValid(); + if (!result) + { + // + // Assume Invalid Boxes as Broken ... + return true; + } + + // + int idx = -1; + result = FindBoxIndex( + idx, + box, + unAvailableBoxes // + ); + if (result) + { + // + // Assume UnAvailable Boxes as Broken ... + return result; + } + + // + int toIDX = box.ToIndex(); + result = toIDX > barIndex; + if (!result) + { + return result; + } + + // + bool isBullish = box.IsBullish(); + double boundary = + isBullish + ? box.lower + : box.upper; + + // + // for validating Box Break we have to wait At Least 3 Bars Close + // out of Box Boundary ... + int barsLength = 3; + + // + int startCheckBreaktionBarIndex = toIDX - barsLength; + result = startCheckBreaktionBarIndex > 0 && + barIndex < startCheckBreaktionBarIndex; + if (!result) + { + return result; + } + + // + XOHCL cBar; + XOHCL pBar; + XOHCL p2Bar; + for (int i = barIndex; i < startCheckBreaktionBarIndex; i++) + { + // + result = cBar.Init( + box.symbol, + box.period, + i + 1 // + ); + result = + result && + cBar.GetPreviousBar(pBar); + result = + result && + pBar.GetPreviousBar(p2Bar); + if (!result) + { + // + cBar.Clean(); + pBar.Clean(); + p2Bar.Clean(); + + // + break; + } + + // + bool isBullishBreaked = + isBullish && + cBar.close < boundary && + pBar.close < boundary && + p2Bar.close < boundary; + + // + bool isBearishBreaked = + !isBullish && + cBar.close > boundary && + pBar.close > boundary && + p2Bar.close > boundary; + + // + result = isBullishBreaked || + isBearishBreaked; + if (result) + { + break; + } + + // + cBar.Clean(); + pBar.Clean(); + p2Bar.Clean(); + } + + // + cBar.Clean(); + pBar.Clean(); + p2Bar.Clean(); + + // + return result; + } + + // +}; + +// \ No newline at end of file diff --git a/BKPS/14040203/XCAEA/Classes/xcaea.x-poi.drawer.class.mq5 b/BKPS/14040203/XCAEA/Classes/xcaea.x-poi.drawer.class.mq5 new file mode 100644 index 0000000..14d0bfd --- /dev/null +++ b/BKPS/14040203/XCAEA/Classes/xcaea.x-poi.drawer.class.mq5 @@ -0,0 +1,2424 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Indicator +// ------------------------------------------------- +// Name: XCXCAEAPOIDrawer ... +// Description: Class for XCAEA POI Drawer ... +// +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +////////////////////////////////////////////////////// +// +// Global Properties ... +#property library +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://saherelm.ir" +#property version "1.00" +#property description "SaherElm Class for XCAEA POI Drawer" +#property strict + +// +// Imports ... +#include "../../Classes/x-saherelm.x-poi.drawer.class.mq5" +#include "../Classes/xcaea.x-poi.detector.class.mq5" + +// +// Definitions ... + +// +// Implementations ... +class XCXCAEAPOIDrawer : public XCBase +{ + // + // Public ... + public: + // + // Props ... + bool drawSWHPivots; + bool drawSWLPivots; + bool drawPeakPivots; + bool drawValePivots; + bool drawRSIPeakPivots; + bool drawRSIValePivots; + bool drawCCIPeakPivots; + bool drawCCIValePivots; + bool drawKIBullishPivots; + bool drawKIBearishPivots; + bool drawFVGBullishPivots; + bool drawFVGBearishPivots; + bool drawPeakSWHResPivots; + bool drawValeSWLSupPivots; + bool drawTKIBullishPivots; + bool drawTKIBearishPivots; + bool drawCycleSameLLPivots; + bool drawCycleSameHHPivots; + bool drawTrendBullishPivots; + bool drawTrendBearishPivots; + bool drawPVFVGBullishPivots; + bool drawPVFVGBearishPivots; + bool drawTKITRNDBullishPivots; + bool drawTKITRNDBearishPivots; + bool drawRSICrossedOverOSPivots; + bool drawRSICrossedUnderOBPivots; + bool drawCCICrossedOverOSPivots; + bool drawCCICrossedUnderOBPivots; + + // + bool drawTicks; + + // + // Colorize Props ... + + // + color peakPivotColor; + color valePivotColor; + color sameHHPivotColor; + color sameLLPivotColor; + color ticksBullishColor; + color ticksBearishColor; + color kiBullishPivotColor; + color kiBearishPivotColor; + color fvgBullishPivotColor; + color fvgBearishPivotColor; + color defBullishPivotColor; + color defBearishPivotColor; + color oscsBullishPivotColor; + color oscsBearishPivotColor; + color trendBullishPivotColor; + color trendBearishPivotColor; + + // + // Width Props ... + + // + int peakPivotWidth; + int valePivotWidth; + int sameHHPivotWidth; + int sameLLPivotWidth; + int ticksBullishWidth; + int ticksBearishWidth; + int kiBullishPivotWidth; + int kiBearishPivotWidth; + int fvgBullishPivotWidth; + int fvgBearishPivotWidth; + int defBullishPivotWidth; + int defBearishPivotWidth; + int oscsBullishPivotWidth; + int oscsBearishPivotWidth; + int trendBullishPivotWidth; + int trendBearishPivotWidth; + + // + // Style Props ... + + // + ENUM_LINE_STYLE peakPivotStyle; + ENUM_LINE_STYLE valePivotStyle; + ENUM_LINE_STYLE sameHHPivotStyle; + ENUM_LINE_STYLE sameLLPivotStyle; + ENUM_LINE_STYLE ticksBullishStyle; + ENUM_LINE_STYLE ticksBearishStyle; + ENUM_LINE_STYLE kiBullishPivotStyle; + ENUM_LINE_STYLE kiBearishPivotStyle; + ENUM_LINE_STYLE fvgBullishPivotStyle; + ENUM_LINE_STYLE fvgBearishPivotStyle; + ENUM_LINE_STYLE defBullishPivotStyle; + ENUM_LINE_STYLE defBearishPivotStyle; + ENUM_LINE_STYLE oscsBullishPivotStyle; + ENUM_LINE_STYLE oscsBearishPivotStyle; + ENUM_LINE_STYLE trendBullishPivotStyle; + ENUM_LINE_STYLE trendBearishPivotStyle; + // + // Constructors ... + XCXCAEAPOIDrawer( + XCXCAEAPOIDetector *_detector // + ) + { + // + detector = _detector; + drawer = new XCPOIDrawer(); + + // + Default(); + } + + // + // De Constructors ... + ~XCXCAEAPOIDrawer() + { + // + mSWHPivotObjects.Clear(); + mSWLPivotObjects.Clear(); + mPeakPivotObjects.Clear(); + mValePivotObjects.Clear(); + mRSIPeakPivotObjects.Clear(); + mRSIValePivotObjects.Clear(); + mCCIPeakPivotObjects.Clear(); + mCCIValePivotObjects.Clear(); + mKIBullishPivotObjects.Clear(); + mKIBearishPivotObjects.Clear(); + mFVGBullishPivotObjects.Clear(); + mFVGBearishPivotObjects.Clear(); + mPeakSWHResPivotObjects.Clear(); + mValeSWLSupPivotObjects.Clear(); + mTKIBullishPivotObjects.Clear(); + mTKIBearishPivotObjects.Clear(); + mTrendBullishPivotObjects.Clear(); + mTrendBearishPivotObjects.Clear(); + mCycleSameLLPivotObjects.Clear(); + mCycleSameHHPivotObjects.Clear(); + mTKITRNDBullishPivotObjects.Clear(); + mTKITRNDBearishPivotObjects.Clear(); + mRSICrossedOverOSPivotObjects.Clear(); + mRSICrossedUnderOBPivotObjects.Clear(); + mCCICrossedOverOSPivotObjects.Clear(); + mCCICrossedUnderOBPivotObjects.Clear(); + + // + ZeroMemory(drawer); + ZeroMemory(detector); + } + + // + // Properties ... + + // + // Tools ... + + // + virtual void Default() + { + // + drawSWHPivots = false; + drawSWLPivots = false; + drawPeakPivots = false; + drawValePivots = false; + drawRSIPeakPivots = false; + drawRSIValePivots = false; + drawCCIPeakPivots = false; + drawCCIValePivots = false; + drawKIBullishPivots = false; + drawKIBearishPivots = false; + drawFVGBullishPivots = false; + drawFVGBearishPivots = false; + drawPeakSWHResPivots = false; + drawValeSWLSupPivots = false; + drawTKIBullishPivots = false; + drawTKIBearishPivots = false; + drawCycleSameLLPivots = false; + drawCycleSameHHPivots = false; + drawPVFVGBullishPivots = false; + drawPVFVGBearishPivots = false; + drawTrendBullishPivots = false; + drawTrendBearishPivots = false; + drawTKITRNDBullishPivots = false; + drawTKITRNDBearishPivots = false; + drawRSICrossedOverOSPivots = false; + drawRSICrossedUnderOBPivots = false; + drawCCICrossedOverOSPivots = false; + drawCCICrossedUnderOBPivots = false; + + // + drawTicks = false; + + // + // Color ... + defBullishPivotColor = clrLime; + defBearishPivotColor = clrRed; + + // + peakPivotColor = defBearishPivotColor; + valePivotColor = defBullishPivotColor; + sameHHPivotColor = defBearishPivotColor; + sameLLPivotColor = defBullishPivotColor; + ticksBullishColor = defBearishPivotColor; + ticksBearishColor = defBullishPivotColor; + kiBullishPivotColor = defBullishPivotColor; + kiBearishPivotColor = defBearishPivotColor; + fvgBullishPivotColor = defBullishPivotColor; + fvgBearishPivotColor = defBearishPivotColor; + oscsBullishPivotColor = defBullishPivotColor; + oscsBearishPivotColor = defBearishPivotColor; + trendBullishPivotColor = defBullishPivotColor; + trendBearishPivotColor = defBearishPivotColor; + + // + // Width ... + defBullishPivotWidth = 1; + defBearishPivotWidth = 1; + + // + peakPivotWidth = defBearishPivotWidth; + valePivotWidth = defBullishPivotWidth; + sameHHPivotWidth = defBearishPivotWidth; + sameLLPivotWidth = defBullishPivotWidth; + ticksBullishWidth = defBearishPivotWidth; + ticksBearishWidth = defBullishPivotWidth; + kiBullishPivotWidth = defBullishPivotWidth; + kiBearishPivotWidth = defBearishPivotWidth; + fvgBullishPivotWidth = defBullishPivotWidth; + fvgBearishPivotWidth = defBearishPivotWidth; + oscsBullishPivotWidth = defBullishPivotWidth; + oscsBearishPivotWidth = defBearishPivotWidth; + trendBullishPivotWidth = defBullishPivotWidth; + trendBearishPivotWidth = defBearishPivotWidth; + + // + // Style ... + defBullishPivotStyle = STYLE_DOT; + defBearishPivotStyle = STYLE_DOT; + + // + peakPivotStyle = defBearishPivotStyle; + valePivotStyle = defBullishPivotStyle; + sameHHPivotStyle = defBearishPivotStyle; + sameLLPivotStyle = defBullishPivotStyle; + ticksBullishStyle = defBearishPivotStyle; + ticksBearishStyle = defBullishPivotStyle; + kiBullishPivotStyle = defBullishPivotStyle; + kiBearishPivotStyle = defBearishPivotStyle; + fvgBullishPivotStyle = defBullishPivotStyle; + fvgBearishPivotStyle = defBearishPivotStyle; + oscsBullishPivotStyle = defBullishPivotStyle; + oscsBearishPivotStyle = defBearishPivotStyle; + trendBullishPivotStyle = defBullishPivotStyle; + trendBearishPivotStyle = defBearishPivotStyle; + } + + // + void Draw(datetime to = NULL) + { + // + DrawTicks(to); + DrawSWHPivots(to); + DrawSWLPivots(to); + DrawPeakPivots(to); + DrawValePivots(to); + DrawRSIPeakPivots(to); + DrawRSIValePivots(to); + DrawCCIPeakPivots(to); + DrawCCIValePivots(to); + DrawKIBullishPivots(to); + DrawKIBearishPivots(to); + DrawFVGBullishPivots(to); + DrawFVGBearishPivots(to); + DrawPeakSWHResPivots(to); + DrawValeSWLSupPivots(to); + DrawTKIBullishPivots(to); + DrawTKIBearishPivots(to); + DrawCycleSameLLPivots(to); + DrawCycleSameHHPivots(to); + DrawTrendBullishPivots(to); + DrawTrendBearishPivots(to); + DrawTKITRNDBullishPivots(to); + DrawTKITRNDBearishPivots(to); + DrawRSICrossedOverOSPivots(to); + DrawRSICrossedUnderOBPivots(to); + DrawCCICrossedOverOSPivots(to); + DrawCCICrossedUnderOBPivots(to); + } + + // + // + // + + // + void DrawTicks(datetime to = NULL) + { + // + if (!drawTicks) + { + return; + } + + // + bool canUpdateTo = IsValid(to); + + // + // PEAK TICKS ... + bool has = detector.HasPeakTicks(); + if (has) + { + // + int count = detector.CountPeakTicks(); + for (int i = 0; i < count; i++) + { + // + XCAPVTick iPVTick = detector.peakTicks[i]; + + // + // Converts Zone to Box ... + XBoxZone iBox; + has = iPVTick.GetMaxVolumeBox(iBox); + if (!has) + { + // + iBox.Clean(); + iPVTick.Clean(); + + // + continue; + } + if (canUpdateTo) + { + iBox.to = to; + } + + // + XCBoxObject *iObj; + has = drawer.DrawBox( + iBox, + iObj // + ); + if (has) + { + // + iObj.BoxColor(ticksBearishColor); + iObj.BoxWidth(ticksBearishWidth); + iObj.BoxStyle(ticksBearishStyle); + + // + mPeakSWHResPivotObjects.Add(iObj); + } + + // + iBox.Clean(); + iPVTick.Clean(); + ZeroMemory(iObj); + } + } + + // + // VALE TICKS ... + has = detector.HasValeTicks(); + if (has) + { + // + int count = detector.CountValeTicks(); + for (int i = 0; i < count; i++) + { + // + XCAPVTick iPVTick = detector.valeTicks[i]; + + // + // Converts Zone to Box ... + XBoxZone iBox; + has = iPVTick.GetMaxVolumeBox(iBox); + if (!has) + { + // + iBox.Clean(); + iPVTick.Clean(); + + // + continue; + } + if (canUpdateTo) + { + iBox.to = to; + } + + // + XCBoxObject *iObj; + has = drawer.DrawBox( + iBox, + iObj // + ); + if (has) + { + // + iObj.BoxColor(ticksBullishColor); + iObj.BoxWidth(ticksBullishWidth); + iObj.BoxStyle(ticksBullishStyle); + + // + mValeSWLSupPivotObjects.Add(iObj); + } + + // + iBox.Clean(); + iPVTick.Clean(); + ZeroMemory(iObj); + } + } + } + + // + void DrawSWHPivots(datetime to = NULL) + { + // + if (!drawSWHPivots) + { + return; + } + + // + bool canUpdateTo = IsValid(to); + + // + bool has = detector.HasSWHPivots(); + if (!has) + { + return; + } + + // + int count = detector.CountSWHPivots(); + for (int i = 0; i < count; i++) + { + // + XBoxZone iBox; + has = detector.swhPivots[i].AsBox(iBox); + if (!has) + { + continue; + } + + // + if (canUpdateTo) + { + iBox.to = to; + } + + // + XCBoxObject *iObj; + has = drawer.DrawBox( + iBox, + iObj // + ); + if (has) + { + // + iObj.BoxColor(peakPivotColor); + iObj.BoxWidth(peakPivotWidth); + iObj.BoxStyle(peakPivotStyle); + + // + mSWHPivotObjects.Add(iObj); + } + + // + iBox.Clean(); + } + } + + // + void DrawSWLPivots(datetime to = NULL) + { + // + if (!drawSWLPivots) + { + return; + } + + // + bool canUpdateTo = IsValid(to); + + // + bool has = detector.HasSWLPivots(); + if (!has) + { + return; + } + + // + int count = detector.CountSWLPivots(); + for (int i = 0; i < count; i++) + { + // + XBoxZone iBox; + has = detector.swlPivots[i].AsBox(iBox); + if (!has) + { + continue; + } + + // + if (canUpdateTo) + { + iBox.to = to; + } + + // + XCBoxObject *iObj; + has = drawer.DrawBox( + iBox, + iObj // + ); + if (has) + { + // + iObj.BoxColor(valePivotColor); + iObj.BoxWidth(valePivotWidth); + iObj.BoxStyle(valePivotStyle); + + // + mSWLPivotObjects.Add(iObj); + } + + // + iBox.Clean(); + } + } + + // + void DrawPeakPivots(datetime to = NULL) + { + // + if (!drawPeakPivots) + { + return; + } + + // + bool canUpdateTo = IsValid(to); + + // + bool has = detector.HasPeakPivots(); + if (!has) + { + return; + } + + // + int count = detector.CountPeakPivots(); + for (int i = 0; i < count; i++) + { + // + XBoxZone iBox; + has = detector.peakPivots[i].AsBox(iBox); + if (!has) + { + continue; + } + + // + if (canUpdateTo) + { + iBox.to = to; + } + + // + XCBoxObject *iObj; + has = drawer.DrawBox( + iBox, + iObj // + ); + if (has) + { + // + iObj.BoxColor(peakPivotColor); + iObj.BoxWidth(peakPivotWidth); + iObj.BoxStyle(peakPivotStyle); + + // + mPeakPivotObjects.Add(iObj); + } + + // + iBox.Clean(); + } + } + + // + void DrawValePivots(datetime to = NULL) + { + // + if (!drawValePivots) + { + return; + } + + // + bool canUpdateTo = IsValid(to); + + // + bool has = detector.HasValePivots(); + if (!has) + { + return; + } + + // + int count = detector.CountValePivots(); + for (int i = 0; i < count; i++) + { + // + XBoxZone iBox; + has = detector.valePivots[i].AsBox(iBox); + if (!has) + { + continue; + } + + // + if (canUpdateTo) + { + iBox.to = to; + } + + // + XCBoxObject *iObj; + has = drawer.DrawBox( + iBox, + iObj // + ); + if (has) + { + // + iObj.BoxColor(valePivotColor); + iObj.BoxWidth(valePivotWidth); + iObj.BoxStyle(valePivotStyle); + + // + mValePivotObjects.Add(iObj); + } + + // + iBox.Clean(); + } + } + + // + void DrawKIBullishPivots(datetime to = NULL) + { + // + if (!drawKIBullishPivots) + { + return; + } + + // + bool canUpdateTo = IsValid(to); + + // + bool has = detector.HasKIBullishPivots(); + if (!has) + { + return; + } + + // + int count = detector.CountKIBullishPivots(); + for (int i = 0; i < count; i++) + { + // + XBoxZone iBox; + has = detector.kiBullishPivots[i].AsBox(iBox); + if (!has) + { + continue; + } + + // + if (canUpdateTo) + { + iBox.to = to; + } + + // + XCBoxObject *iObj; + has = drawer.DrawBox( + iBox, + iObj // + ); + if (has) + { + // + iObj.BoxColor(kiBullishPivotColor); + iObj.BoxWidth(kiBullishPivotWidth); + iObj.BoxStyle(kiBullishPivotStyle); + + // + mKIBullishPivotObjects.Add(iObj); + } + + // + iBox.Clean(); + } + } + + // + void DrawKIBearishPivots(datetime to = NULL) + { + // + if (!drawKIBearishPivots) + { + return; + } + + // + bool canUpdateTo = IsValid(to); + + // + bool has = detector.HasKIBearishPivots(); + if (!has) + { + return; + } + + // + int count = detector.CountKIBearishPivots(); + for (int i = 0; i < count; i++) + { + // + XBoxZone iBox; + has = detector.kiBearishPivots[i].AsBox(iBox); + if (!has) + { + continue; + } + + // + if (canUpdateTo) + { + iBox.to = to; + } + + // + XCBoxObject *iObj; + has = drawer.DrawBox( + iBox, + iObj // + ); + if (has) + { + // + iObj.BoxColor(kiBearishPivotColor); + iObj.BoxWidth(kiBearishPivotWidth); + iObj.BoxStyle(kiBearishPivotStyle); + + // + mKIBearishPivotObjects.Add(iObj); + } + + // + iBox.Clean(); + } + } + + // + void DrawFVGBullishPivots(datetime to = NULL) + { + // + bool canUpdateTo = IsValid(to); + + // + if (drawFVGBullishPivots) + { + // + bool has = detector.HasFVGBullishPivots(); + if (has) + { + // + int count = detector.CountFVGBullishPivots(); + for (int i = 0; i < count; i++) + { + // + XBoxZone iBox; + has = detector.fvgBullishPivots[i].AsBox(iBox); + if (!has) + { + // + iBox.Clean(); + continue; + } + + // + if (canUpdateTo) + { + iBox.to = to; + } + + // + XCBoxObject *iObj; + has = drawer.DrawBox( + iBox, + iObj // + ); + if (has) + { + // + iObj.BoxColor(fvgBullishPivotColor); + iObj.BoxWidth(fvgBullishPivotWidth); + iObj.BoxStyle(fvgBullishPivotStyle); + + // + mFVGBullishPivotObjects.Add(iObj); + } + } + } + } + + // + if (drawPVFVGBullishPivots) + { + // + bool has = detector.HasPVFVGBullishPivots(); + if (has) + { + // + int count = detector.CountPVFVGBullishPivots(); + for (int i = 0; i < count; i++) + { + // + XCAPVPivot iPVFVG = detector.pvFVGBullishPivots[i]; + + // + XBoxZone fvgBoxes[]; + int fvgBoxesCount = iPVFVG.GetPivots(fvgBoxes); + has = IsValidSize(fvgBoxesCount); + if (has) + { + // + int idx = GetLowest(fvgBoxes); + if (IsValidIndex(idx)) + { + // + XBoxZone iBox = fvgBoxes[idx]; + + // + if (canUpdateTo) + { + iBox.to = to; + } + + // + XCBoxObject *iObj; + + // + has = drawer.DrawBox( + iBox, + iObj // + ); + if (has) + { + // + iObj.BoxColor(fvgBullishPivotColor); + iObj.BoxWidth(fvgBullishPivotWidth); + iObj.BoxStyle(fvgBullishPivotStyle); + + // + mFVGBullishPivotObjects.Add(iObj); + } + + // + iBox.Clean(); + ZeroMemory(iObj); + } + } + } + } + } + } + + // + void DrawFVGBearishPivots(datetime to = NULL) + { + // + bool canUpdateTo = IsValid(to); + + // + if (drawFVGBearishPivots) + { + // + bool has = detector.HasFVGBearishPivots(); + if (has) + { + // + int count = detector.CountFVGBearishPivots(); + for (int i = 0; i < count; i++) + { + // + XBoxZone iBox; + has = detector.fvgBearishPivots[i].AsBox(iBox); + if (!has) + { + // + iBox.Clean(); + continue; + } + + // + if (canUpdateTo) + { + iBox.to = to; + } + + // + XCBoxObject *iObj; + has = drawer.DrawBox( + iBox, + iObj // + ); + if (has) + { + // + iObj.BoxColor(fvgBearishPivotColor); + iObj.BoxWidth(fvgBearishPivotWidth); + iObj.BoxStyle(fvgBearishPivotStyle); + + // + mFVGBearishPivotObjects.Add(iObj); + } + } + } + } + + // + if (drawPVFVGBullishPivots) + { + // + bool has = detector.HasPVFVGBearishPivots(); + if (has) + { + // + int count = detector.CountPVFVGBearishPivots(); + for (int i = 0; i < count; i++) + { + // + XCAPVPivot iPVFVG = detector.pvFVGBearishPivots[i]; + + // + XBoxZone fvgBoxes[]; + int fvgBoxesCount = iPVFVG.GetPivots(fvgBoxes); + has = IsValidSize(fvgBoxesCount); + if (has) + { + // + int idx = GetHighest(fvgBoxes); + if (IsValidIndex(idx)) + { + // + XBoxZone iBox = fvgBoxes[idx]; + + // + if (canUpdateTo) + { + iBox.to = to; + } + + // + XCBoxObject *iObj; + + // + has = drawer.DrawBox( + iBox, + iObj // + ); + if (has) + { + // + iObj.BoxColor(fvgBearishPivotColor); + iObj.BoxWidth(fvgBearishPivotWidth); + iObj.BoxStyle(fvgBearishPivotStyle); + + // + mFVGBearishPivotObjects.Add(iObj); + } + + // + iBox.Clean(); + ZeroMemory(iObj); + } + } + } + } + } + } + + // + void DrawPeakSWHResPivots(datetime to = NULL) + { + // + if (!drawPeakSWHResPivots) + { + return; + } + + // + bool canUpdateTo = IsValid(to); + + // + bool has = detector.HasPeakSWHResPivots(); + if (!has) + { + return; + } + + // + int count = detector.CountPeakSWHResPivots(); + for (int i = 0; i < count; i++) + { + // + XBoxZone iBox; + has = detector.peakSWHResPivots[i].AsBox(iBox); + if (!has) + { + continue; + } + + // + if (canUpdateTo) + { + iBox.to = to; + } + + // + XCBoxObject *iObj; + has = drawer.DrawBox( + iBox, + iObj // + ); + if (has) + { + // + iObj.BoxColor(peakPivotColor); + iObj.BoxWidth(peakPivotWidth); + iObj.BoxStyle(peakPivotStyle); + + // + mPeakSWHResPivotObjects.Add(iObj); + } + + // + iBox.Clean(); + } + } + + // + void DrawValeSWLSupPivots(datetime to = NULL) + { + // + if (!drawValeSWLSupPivots) + { + return; + } + + // + bool canUpdateTo = IsValid(to); + + // + bool has = detector.HasValeSWLSupPivots(); + if (!has) + { + return; + } + + // + int count = detector.CountValeSWLSupPivots(); + for (int i = 0; i < count; i++) + { + // + XBoxZone iBox; + has = detector.valeSWLSupPivots[i].AsBox(iBox); + if (!has) + { + continue; + } + + // + if (canUpdateTo) + { + iBox.to = to; + } + + // + XCBoxObject *iObj; + has = drawer.DrawBox( + iBox, + iObj // + ); + if (has) + { + // + iObj.BoxColor(valePivotColor); + iObj.BoxWidth(valePivotWidth); + iObj.BoxStyle(valePivotStyle); + + // + mValeSWLSupPivotObjects.Add(iObj); + } + + // + iBox.Clean(); + } + } + + // + void DrawTKIBullishPivots(datetime to = NULL) + { + // + if (!drawTKIBullishPivots) + { + return; + } + + // + bool canUpdateTo = IsValid(to); + + // + bool has = detector.HasTKIBullishPivots(); + if (!has) + { + return; + } + + // + int count = detector.CountTKIBullishPivots(); + for (int i = 0; i < count; i++) + { + // + XBoxZone iBox; + has = detector.tkiBullishPivots[i].AsBox(iBox); + if (!has) + { + continue; + } + + // + if (canUpdateTo) + { + iBox.to = to; + } + + // + XCBoxObject *iObj; + has = drawer.DrawBox( + iBox, + iObj // + ); + if (has) + { + // + iObj.BoxColor(kiBullishPivotColor); + iObj.BoxWidth(kiBullishPivotWidth); + iObj.BoxStyle(kiBullishPivotStyle); + + // + mTKIBullishPivotObjects.Add(iObj); + } + + // + iBox.Clean(); + } + } + + // + void DrawTKIBearishPivots(datetime to = NULL) + { + // + if (!drawTKIBearishPivots) + { + return; + } + + // + bool canUpdateTo = IsValid(to); + + // + bool has = detector.HasTKIBearishPivots(); + if (!has) + { + return; + } + + // + int count = detector.CountTKIBearishPivots(); + for (int i = 0; i < count; i++) + { + // + XBoxZone iBox; + has = detector.tkiBearishPivots[i].AsBox(iBox); + if (!has) + { + continue; + } + + // + if (canUpdateTo) + { + iBox.to = to; + } + + // + XCBoxObject *iObj; + has = drawer.DrawBox( + iBox, + iObj // + ); + if (has) + { + // + iObj.BoxColor(kiBearishPivotColor); + iObj.BoxWidth(kiBearishPivotWidth); + iObj.BoxStyle(kiBearishPivotStyle); + + // + mTKIBearishPivotObjects.Add(iObj); + } + + // + iBox.Clean(); + } + } + + // + void DrawTrendBullishPivots(datetime to = NULL) + { + // + if (!drawTrendBullishPivots) + { + return; + } + + // + bool canUpdateTo = IsValid(to); + + // + bool has = detector.HasTrendBullishPivots(); + if (!has) + { + return; + } + + // + int count = detector.CountTrendBullishPivots(); + for (int i = 0; i < count; i++) + { + // + XBoxZone iBox; + has = detector.trendBullishPivots[i].AsBox(iBox); + if (!has) + { + continue; + } + + // + if (canUpdateTo) + { + iBox.to = to; + } + + // + XCBoxObject *iObj; + has = drawer.DrawBox( + iBox, + iObj // + ); + if (has) + { + // + iObj.BoxColor(trendBullishPivotColor); + iObj.BoxWidth(trendBullishPivotWidth); + iObj.BoxStyle(trendBullishPivotStyle); + + // + mTrendBullishPivotObjects.Add(iObj); + } + + // + iBox.Clean(); + } + } + + // + void DrawTrendBearishPivots(datetime to = NULL) + { + // + if (!drawTrendBearishPivots) + { + return; + } + + // + bool canUpdateTo = IsValid(to); + + // + bool has = detector.HasTrendBearishPivots(); + if (!has) + { + return; + } + + // + int count = detector.CountTrendBearishPivots(); + for (int i = 0; i < count; i++) + { + // + XBoxZone iBox; + has = detector.trendBearishPivots[i].AsBox(iBox); + if (!has) + { + continue; + } + + // + if (canUpdateTo) + { + iBox.to = to; + } + + // + XCBoxObject *iObj; + has = drawer.DrawBox( + iBox, + iObj // + ); + if (has) + { + // + iObj.BoxColor(trendBearishPivotColor); + iObj.BoxWidth(trendBearishPivotWidth); + iObj.BoxStyle(trendBearishPivotStyle); + + // + mTrendBearishPivotObjects.Add(iObj); + } + + // + iBox.Clean(); + } + } + + // + void DrawTKITRNDBullishPivots(datetime to = NULL) + { + // + if (!drawTKITRNDBullishPivots) + { + return; + } + + // + bool canUpdateTo = IsValid(to); + + // + bool has = detector.HasTKITRNDBullishPivots(); + if (!has) + { + return; + } + + // + int count = detector.CountTKITRNDBullishPivots(); + for (int i = 0; i < count; i++) + { + // + XBoxZone iBox; + has = detector.tkitrndBullishPivots[i].AsBox(iBox); + if (!has) + { + continue; + } + + // + if (canUpdateTo) + { + iBox.to = to; + } + + // + XCBoxObject *iObj; + has = drawer.DrawBox( + iBox, + iObj // + ); + if (has) + { + // + iObj.BoxColor(trendBullishPivotColor); + iObj.BoxWidth(trendBullishPivotWidth); + iObj.BoxStyle(trendBullishPivotStyle); + + // + mTKITRNDBullishPivotObjects.Add(iObj); + } + + // + iBox.Clean(); + } + } + + // + void DrawTKITRNDBearishPivots(datetime to = NULL) + { + // + if (!drawTKITRNDBearishPivots) + { + return; + } + + // + bool canUpdateTo = IsValid(to); + + // + bool has = detector.HasTKITRNDBearishPivots(); + if (!has) + { + return; + } + + // + int count = detector.CountTKITRNDBearishPivots(); + for (int i = 0; i < count; i++) + { + // + XBoxZone iBox; + has = detector.tkitrndBearishPivots[i].AsBox(iBox); + if (!has) + { + continue; + } + + // + if (canUpdateTo) + { + iBox.to = to; + } + + // + XCBoxObject *iObj; + has = drawer.DrawBox( + iBox, + iObj // + ); + if (has) + { + // + iObj.BoxColor(trendBearishPivotColor); + iObj.BoxWidth(trendBearishPivotWidth); + iObj.BoxStyle(trendBearishPivotStyle); + + // + mTKITRNDBearishPivotObjects.Add(iObj); + } + + // + iBox.Clean(); + } + } + + // + void DrawCycleSameLLPivots(datetime to = NULL) + { + // + if (!drawCycleSameLLPivots) + { + return; + } + + // + bool canUpdateTo = IsValid(to); + + // + int count = 0; + + // + // SHORT ... + bool has = detector.HasSSameLLPivots(); + if (has) + { + // + count = detector.CountSSameLLPivots(); + for (int i = 0; i < count; i++) + { + // + XBoxZone iBox; + has = detector.sSameLLPivots[i].AsBox(iBox); + if (!has) + { + continue; + } + + // + if (canUpdateTo) + { + iBox.to = to; + } + + // + XCBoxObject *iObj; + has = drawer.DrawBox( + iBox, + iObj // + ); + if (has) + { + // + iObj.BoxColor(sameLLPivotColor); + iObj.BoxWidth(sameLLPivotWidth); + iObj.BoxStyle(sameLLPivotStyle); + + // + mCycleSameLLPivotObjects.Add(iObj); + } + + // + iBox.Clean(); + } + } + + // + // MEDIUM ... + has = detector.HasMSameLLPivots(); + if (has) + { + // + count = detector.CountMSameLLPivots(); + for (int i = 0; i < count; i++) + { + // + XBoxZone iBox; + has = detector.mSameLLPivots[i].AsBox(iBox); + if (!has) + { + continue; + } + + // + if (canUpdateTo) + { + iBox.to = to; + } + + // + XCBoxObject *iObj; + has = drawer.DrawBox( + iBox, + iObj // + ); + if (has) + { + // + iObj.BoxColor(sameLLPivotColor); + iObj.BoxWidth(sameLLPivotWidth); + iObj.BoxStyle(sameLLPivotStyle); + + // + mCycleSameLLPivotObjects.Add(iObj); + } + + // + iBox.Clean(); + } + } + + // + // LONG ... + has = detector.HasLSameLLPivots(); + if (has) + { + // + count = detector.CountLSameLLPivots(); + for (int i = 0; i < count; i++) + { + // + XBoxZone iBox; + has = detector.lSameLLPivots[i].AsBox(iBox); + if (!has) + { + continue; + } + + // + if (canUpdateTo) + { + iBox.to = to; + } + + // + XCBoxObject *iObj; + has = drawer.DrawBox( + iBox, + iObj // + ); + if (has) + { + // + iObj.BoxColor(sameLLPivotColor); + iObj.BoxWidth(sameLLPivotWidth); + iObj.BoxStyle(sameLLPivotStyle); + + // + mCycleSameLLPivotObjects.Add(iObj); + } + + // + iBox.Clean(); + } + } + + // + // HIND ... + has = detector.HasHSameLLPivots(); + if (has) + { + // + count = detector.CountHSameLLPivots(); + for (int i = 0; i < count; i++) + { + // + XBoxZone iBox; + has = detector.hSameLLPivots[i].AsBox(iBox); + if (!has) + { + continue; + } + + // + if (canUpdateTo) + { + iBox.to = to; + } + + // + XCBoxObject *iObj; + has = drawer.DrawBox( + iBox, + iObj // + ); + if (has) + { + // + iObj.BoxColor(sameLLPivotColor); + iObj.BoxWidth(sameLLPivotWidth); + iObj.BoxStyle(sameLLPivotStyle); + + // + mCycleSameLLPivotObjects.Add(iObj); + } + + // + iBox.Clean(); + } + } + } + + // + void DrawCycleSameHHPivots(datetime to = NULL) + { + // + if (!drawCycleSameHHPivots) + { + return; + } + + // + bool canUpdateTo = IsValid(to); + + // + int count = 0; + + // + // SHORT ... + bool has = detector.HasSSameHHPivots(); + if (has) + { + // + count = detector.CountSSameHHPivots(); + for (int i = 0; i < count; i++) + { + // + XBoxZone iBox; + has = detector.sSameHHPivots[i].AsBox(iBox); + if (!has) + { + continue; + } + + // + if (canUpdateTo) + { + iBox.to = to; + } + + // + XCBoxObject *iObj; + has = drawer.DrawBox( + iBox, + iObj // + ); + if (has) + { + // + iObj.BoxColor(sameHHPivotColor); + iObj.BoxWidth(sameHHPivotWidth); + iObj.BoxStyle(sameHHPivotStyle); + + // + mCycleSameHHPivotObjects.Add(iObj); + } + + // + iBox.Clean(); + } + } + + // + // MEDIUM ... + has = detector.HasMSameHHPivots(); + if (has) + { + // + count = detector.CountMSameHHPivots(); + for (int i = 0; i < count; i++) + { + // + XBoxZone iBox; + has = detector.mSameHHPivots[i].AsBox(iBox); + if (!has) + { + continue; + } + + // + if (canUpdateTo) + { + iBox.to = to; + } + + // + XCBoxObject *iObj; + has = drawer.DrawBox( + iBox, + iObj // + ); + if (has) + { + // + iObj.BoxColor(sameHHPivotColor); + iObj.BoxWidth(sameHHPivotWidth); + iObj.BoxStyle(sameHHPivotStyle); + + // + mCycleSameHHPivotObjects.Add(iObj); + } + + // + iBox.Clean(); + } + } + + // + // LONG ... + has = detector.HasLSameHHPivots(); + if (has) + { + // + count = detector.CountLSameHHPivots(); + for (int i = 0; i < count; i++) + { + // + XBoxZone iBox; + has = detector.lSameHHPivots[i].AsBox(iBox); + if (!has) + { + continue; + } + + // + if (canUpdateTo) + { + iBox.to = to; + } + + // + XCBoxObject *iObj; + has = drawer.DrawBox( + iBox, + iObj // + ); + if (has) + { + // + iObj.BoxColor(sameHHPivotColor); + iObj.BoxWidth(sameHHPivotWidth); + iObj.BoxStyle(sameHHPivotStyle); + + // + mCycleSameHHPivotObjects.Add(iObj); + } + + // + iBox.Clean(); + } + } + + // + // HIND ... + has = detector.HasHSameHHPivots(); + if (has) + { + // + count = detector.CountHSameHHPivots(); + for (int i = 0; i < count; i++) + { + // + XBoxZone iBox; + has = detector.hSameHHPivots[i].AsBox(iBox); + if (!has) + { + continue; + } + + // + if (canUpdateTo) + { + iBox.to = to; + } + + // + XCBoxObject *iObj; + has = drawer.DrawBox( + iBox, + iObj // + ); + if (has) + { + // + iObj.BoxColor(sameHHPivotColor); + iObj.BoxWidth(sameHHPivotWidth); + iObj.BoxStyle(sameHHPivotStyle); + + // + mCycleSameHHPivotObjects.Add(iObj); + } + + // + iBox.Clean(); + } + } + } + + // + void DrawRSIPeakPivots(datetime to = NULL) + { + // + if (!drawRSIPeakPivots) + { + return; + } + + // + to = NULL; + bool canUpdateTo = IsValid(to); + + // + int count = 0; + bool has = detector.HasRSIPeakPivots(); + if (has) + { + // + count = detector.CountRSIPeakPivots(); + for (int i = 0; i < count; i++) + { + // + XBoxZone iBox; + has = detector.rsiPeakPivots[i].AsBox(iBox); + if (!has) + { + // + iBox.Clean(); + continue; + } + + // + if (canUpdateTo) + { + iBox.to = to; + } + + // + XCBoxObject *iObj; + has = drawer.DrawBox( + iBox, + iObj // + ); + if (has) + { + // + iObj.BoxColor(oscsBearishPivotColor); + iObj.BoxWidth(oscsBearishPivotWidth); + iObj.BoxStyle(oscsBearishPivotStyle); + + // + mRSIPeakPivotObjects.Add(iObj); + } + + // + iBox.Clean(); + } + } + } + + // + void DrawRSIValePivots(datetime to = NULL) + { + // + if (!drawRSIValePivots) + { + return; + } + + // + to = NULL; + bool canUpdateTo = IsValid(to); + + // + int count = 0; + bool has = detector.HasRSIValePivots(); + if (has) + { + // + count = detector.CountRSIValePivots(); + for (int i = 0; i < count; i++) + { + // + XBoxZone iBox; + has = detector.rsiValePivots[i].AsBox(iBox); + if (!has) + { + // + iBox.Clean(); + continue; + } + + // + if (canUpdateTo) + { + iBox.to = to; + } + + // + XCBoxObject *iObj; + has = drawer.DrawBox( + iBox, + iObj // + ); + if (has) + { + // + iObj.BoxColor(oscsBullishPivotColor); + iObj.BoxWidth(oscsBullishPivotWidth); + iObj.BoxStyle(oscsBullishPivotStyle); + + // + mRSIValePivotObjects.Add(iObj); + } + + // + iBox.Clean(); + } + } + } + + // + void DrawRSICrossedOverOSPivots(datetime to = NULL) + { + // + if (!drawRSICrossedOverOSPivots) + { + return; + } + + // + to = NULL; + bool canUpdateTo = IsValid(to); + + // + int count = 0; + bool has = detector.HasRSICrossedOverOSPivots(); + if (has) + { + // + count = detector.CountRSICrossedOverOSPivots(); + for (int i = 0; i < count; i++) + { + // + XBoxZone iBox; + has = detector.rsiCrossedOverOSPivots[i].AsBox(iBox); + if (!has) + { + continue; + } + + // + if (canUpdateTo) + { + iBox.to = to; + } + + // + XCBoxObject *iObj; + has = drawer.DrawBox( + iBox, + iObj // + ); + if (has) + { + // + iObj.BoxColor(oscsBullishPivotColor); + iObj.BoxWidth(oscsBullishPivotWidth); + iObj.BoxStyle(oscsBullishPivotStyle); + + // + mRSICrossedOverOSPivotObjects.Add(iObj); + } + + // + iBox.Clean(); + } + } + } + + // + void DrawRSICrossedUnderOBPivots(datetime to = NULL) + { + // + if (!drawRSICrossedUnderOBPivots) + { + return; + } + + // + to = NULL; + bool canUpdateTo = IsValid(to); + + // + int count = 0; + bool has = detector.HasRSICrossedUnderOBPivots(); + if (has) + { + // + count = detector.CountRSICrossedUnderOBPivots(); + for (int i = 0; i < count; i++) + { + // + XBoxZone iBox; + has = detector.rsiCrossedUnderOBPivots[i].AsBox(iBox); + if (!has) + { + continue; + } + + // + if (canUpdateTo) + { + iBox.to = to; + } + + // + XCBoxObject *iObj; + has = drawer.DrawBox( + iBox, + iObj // + ); + if (has) + { + // + iObj.BoxColor(oscsBearishPivotColor); + iObj.BoxWidth(oscsBearishPivotWidth); + iObj.BoxStyle(oscsBearishPivotStyle); + + // + mRSICrossedUnderOBPivotObjects.Add(iObj); + } + + // + iBox.Clean(); + } + } + } + + // + void DrawCCIPeakPivots(datetime to = NULL) + { + // + if (!drawCCIPeakPivots) + { + return; + } + + // + to = NULL; + bool canUpdateTo = IsValid(to); + + // + int count = 0; + bool has = detector.HasCCIPeakPivots(); + if (has) + { + // + count = detector.CountCCIPeakPivots(); + for (int i = 0; i < count; i++) + { + // + XBoxZone iBox; + has = detector.cciPeakPivots[i].AsBox(iBox); + if (!has) + { + // + iBox.Clean(); + continue; + } + + // + if (canUpdateTo) + { + iBox.to = to; + } + + // + XCBoxObject *iObj; + has = drawer.DrawBox( + iBox, + iObj // + ); + if (has) + { + // + iObj.BoxColor(oscsBearishPivotColor); + iObj.BoxWidth(oscsBearishPivotWidth); + iObj.BoxStyle(oscsBearishPivotStyle); + + // + mCCIPeakPivotObjects.Add(iObj); + } + + // + iBox.Clean(); + } + } + } + + // + void DrawCCIValePivots(datetime to = NULL) + { + // + if (!drawCCIValePivots) + { + return; + } + + // + to = NULL; + bool canUpdateTo = IsValid(to); + + // + int count = 0; + bool has = detector.HasCCIValePivots(); + if (has) + { + // + count = detector.CountCCIValePivots(); + for (int i = 0; i < count; i++) + { + // + XBoxZone iBox; + has = detector.cciValePivots[i].AsBox(iBox); + if (!has) + { + // + iBox.Clean(); + continue; + } + + // + if (canUpdateTo) + { + iBox.to = to; + } + + // + XCBoxObject *iObj; + has = drawer.DrawBox( + iBox, + iObj // + ); + if (has) + { + // + iObj.BoxColor(oscsBullishPivotColor); + iObj.BoxWidth(oscsBullishPivotWidth); + iObj.BoxStyle(oscsBullishPivotStyle); + + // + mCCIValePivotObjects.Add(iObj); + } + + // + iBox.Clean(); + } + } + } + + // + void DrawCCICrossedOverOSPivots(datetime to = NULL) + { + // + if (!drawCCICrossedOverOSPivots) + { + return; + } + + // + to = NULL; + bool canUpdateTo = IsValid(to); + + // + int count = 0; + bool has = detector.HasCCICrossedOverOSPivots(); + if (has) + { + // + count = detector.CountCCICrossedOverOSPivots(); + for (int i = 0; i < count; i++) + { + // + XBoxZone iBox; + has = detector.cciCrossedOverOSPivots[i].AsBox(iBox); + if (!has) + { + continue; + } + + // + if (canUpdateTo) + { + iBox.to = to; + } + + // + XCBoxObject *iObj; + has = drawer.DrawBox( + iBox, + iObj // + ); + if (has) + { + // + iObj.BoxColor(oscsBullishPivotColor); + iObj.BoxWidth(oscsBullishPivotWidth); + iObj.BoxStyle(oscsBullishPivotStyle); + + // + mCCICrossedOverOSPivotObjects.Add(iObj); + } + + // + iBox.Clean(); + } + } + } + + // + void DrawCCICrossedUnderOBPivots(datetime to = NULL) + { + // + if (!drawCCICrossedUnderOBPivots) + { + return; + } + + // + to = NULL; + bool canUpdateTo = IsValid(to); + + // + int count = 0; + bool has = detector.HasCCICrossedUnderOBPivots(); + if (has) + { + // + count = detector.CountCCICrossedUnderOBPivots(); + for (int i = 0; i < count; i++) + { + // + XBoxZone iBox; + has = detector.cciCrossedUnderOBPivots[i].AsBox(iBox); + if (!has) + { + continue; + } + + // + if (canUpdateTo) + { + iBox.to = to; + } + + // + XCBoxObject *iObj; + has = drawer.DrawBox( + iBox, + iObj // + ); + if (has) + { + // + iObj.BoxColor(oscsBearishPivotColor); + iObj.BoxWidth(oscsBearishPivotWidth); + iObj.BoxStyle(oscsBearishPivotStyle); + + // + mCCICrossedUnderOBPivotObjects.Add(iObj); + } + + // + iBox.Clean(); + } + } + } + + // + // Protected ... + protected: + // + // Props ... + + // + // Prrivate ... + private: + // + // Props ... + + // + XCPOIDrawer *drawer; + XCXCAEAPOIDetector *detector; + + // + CArrayObj mSWHPivotObjects; + CArrayObj mSWLPivotObjects; + CArrayObj mPeakPivotObjects; + CArrayObj mValePivotObjects; + CArrayObj mRSIPeakPivotObjects; + CArrayObj mRSIValePivotObjects; + CArrayObj mCCIPeakPivotObjects; + CArrayObj mCCIValePivotObjects; + CArrayObj mKIBullishPivotObjects; + CArrayObj mKIBearishPivotObjects; + CArrayObj mFVGBullishPivotObjects; + CArrayObj mFVGBearishPivotObjects; + CArrayObj mPeakSWHResPivotObjects; + CArrayObj mValeSWLSupPivotObjects; + CArrayObj mTKIBullishPivotObjects; + CArrayObj mTKIBearishPivotObjects; + CArrayObj mCycleSameLLPivotObjects; + CArrayObj mCycleSameHHPivotObjects; + CArrayObj mTrendBullishPivotObjects; + CArrayObj mTrendBearishPivotObjects; + CArrayObj mTKITRNDBullishPivotObjects; + CArrayObj mTKITRNDBearishPivotObjects; + CArrayObj mRSICrossedOverOSPivotObjects; + CArrayObj mRSICrossedUnderOBPivotObjects; + CArrayObj mCCICrossedOverOSPivotObjects; + CArrayObj mCCICrossedUnderOBPivotObjects; + + // +}; + +// \ No newline at end of file diff --git a/BKPS/14040203/XCAEA/Classes/xcaea.x-trade.manager.class.mq5 b/BKPS/14040203/XCAEA/Classes/xcaea.x-trade.manager.class.mq5 new file mode 100644 index 0000000..e8628b9 --- /dev/null +++ b/BKPS/14040203/XCAEA/Classes/xcaea.x-trade.manager.class.mq5 @@ -0,0 +1,782 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Class Library +// -------------------------------------- +// Name: XCXCAEATradeManager +// Description: provides all Requirements for Managing Trades ... +// +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +////////////////////////////////////////////////////// +// +// Global Properties ... +#property library +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://www.saherelm.ir" +#property version "1.00" +#property strict + +// +// Imports ... +#include "../../Classes/x-saherelm.x-alert.class.mq5" +#include "../../Classes/x-saherelm.x-poi.drawer.class.mq5" +#include "../../Classes/x-saherelm.x-trade.class.mq5" +#include "../Libraries/xcaea.signaller.lib.mq5" + +// +// Definitions ... + +// +enum ENUM_XCAEA_TRADE_FINALIZATION +{ + XCAEA_TRADE_FINAL_NONE, + XCAEA_TRADE_FINAL_TP, + XCAEA_TRADE_FINAL_SL, + XCAEA_TRADE_FINAL_CLOSE_IN_PROFIT, + XCAEA_TRADE_FINAL_CLOSE_IN_LOSE, +}; + +// +struct XCAEATrade +{ + // + // Props ... + double swap; + double profit; + XSignal signal; + ulong positionID; + double commission; + XCAEAStrategyConditions conditions; + ENUM_XCAEA_TRADE_FINALIZATION finalize; + + // + // Constructor ... + XCAEATrade() + { + Clean(); + } + + // + // Tools ... + + /** + * Cleanup Model ... + */ + void Clean() + { + // + swap = 0; + profit = 0; + signal.Clean(); + commission = 0; + positionID = 0; + conditions.Clean(); + finalize = XCAEA_TRADE_FINAL_NONE; + + // + ZeroMemory(this); + } + + /** + * Check Has Signal ... + * + * @return ( bool ) + */ + bool HasSignal() + { + // + bool result = false; + + // + result = signal.IsValid(); + + // + return result; + } + + /** + * Check Signal Executed or Not ... + * + * @return ( bool ) + */ + bool IsExecuted() + { + // + bool result = false; + + // + result = positionID > 0; + + // + return result; + } + + /** + * Check a Trade is Finalized or not ... + * + * @return ( bool ) + */ + bool IsFinalized() + { + // + bool result = false; + + // + result = HasSignal() && + IsExecuted() && + finalize != XCAEA_TRADE_FINAL_NONE; + + // + return result; + } +}; + +// +// Implementations ... +class XCXCAEATradeManager : public XCBaseAlert +{ + // + // Public ... + public: + // + // Props ... + XCTrade *trader; + bool drawSignal; + XCPOIDrawer *drawer; + + // + // Constructors ... + XCXCAEATradeManager(XCTrade *&_trader) + { + // + trader = _trader; + drawSignal = true; + drawer = new XCPOIDrawer(); + } + + // + // De Constructors ... + ~XCXCAEATradeManager() + { + // + ZeroMemory(trader); + ZeroMemory(drawer); + } + + // + // Tools ... + + /** + * Do All Position Managing Senaros ... + */ + void Manage() + { + // + bool has = HasChild(trades); + if (!has) + { + return; + } + + // + int count = ArraySize(trades); + for (int i = 0; i < count; i++) + { + // + has = trades[i].IsExecuted() && + !trades[i].IsFinalized(); + if (!has) + { + continue; + } + + // + XPosition iPosition; + has = trader.GetPosition( + trades[i].positionID, + iPosition // + ); + if (!has) + { + continue; + } + + // + // Update Trade Data ... + trades[i].swap = iPosition.swap; + trades[i].profit = iPosition.profit; + } + + // + // After Update All Trades we can Do Protection ... + Protect(); + } + + /** + * Do All Position Protection Here ... + */ + void Protect() + { + // + string prefix = "Protector: "; + int targetDistance = 5; + + // + bool has = HasChild(trades); + if (!has) + { + return; + } + + // + XPosition ownPosition[]; + XPosition ownLongPosition[]; + XPosition ownShortPosition[]; + + // + int count = ArraySize(trades); + for (int i = 0; i < count; i++) + { + // + has = + trades[i].IsExecuted() && + !trades[i].IsFinalized(); + if (!has) + { + continue; + } + + // + XPosition iPosition; + has = trader.GetPosition( + trades[i].positionID, + iPosition // + ); + if (!has) + { + continue; + } + + // + AddRef( + iPosition, + ownPosition // + ); + + // + if (IsLong(iPosition.type)) + { + // + AddRef( + iPosition, + ownLongPosition // + ); + } + else + { + // + AddRef( + iPosition, + ownShortPosition // + ); + } + } + + // + has = HasChild(ownPosition); + if (!has) + { + // + Clean(ownPosition); + Clean(ownLongPosition); + Clean(ownShortPosition); + + // + return; + } + + // + double swapSum = 0; + double profitSum = 0; + double commissionSum = 0; + + // + // Calculate Required Data On Collection ... + count = ArraySize(ownPosition); + for (int i = 0; i < count; i++) + { + // + XPosition iPosition = ownPosition[i]; + + // + swapSum += iPosition.swap; + profitSum += iPosition.profit; + commissionSum += iPosition.commission; + } + + // + // Do Collection Protectiong ... + // TODO: Implement this ... + + // + // Do Signle Protections ... + for (int i = 0; i < count; i++) + { + // + // Select Position ... + XPosition iPosition = ownPosition[i]; + int idx = -1; + has = HasTrade( + idx, + iPosition.ticket // + ); + if (!has) + { + continue; + } + + // + bool isLong = IsLong(iPosition.type); + double points = GetPoints(iPosition.symbol); + + // + // Handle RF On Targets ... + if (iPosition.profit > 0) + { + // + double targets[]; + Copy( + trades[idx].signal.targets, + targets // + ); + int targetsCount = ArraySize(targets); + has = IsValidSize(targetsCount); + if (has) + { + // + for (int j = 0; j < targetsCount; j++) + { + // + double jTarget = targets[j]; + + // + // Check Traget Validation ... + has = + iPosition.sl == 0 + ? true + : isLong + ? iPosition.sl < jTarget + : iPosition.sl > jTarget; + if (!has) + { + continue; + } + + // + double targetDelta = isLong + ? jTarget + (targetDistance * points) + : jTarget - (targetDistance * points); + + // + // Can Risk Free ... + bool canRF = jTarget > 0 && + (isLong + ? jTarget > iPosition.entry + : jTarget < iPosition.entry) && + (isLong + ? iPosition.price > targetDelta + : iPosition.price < targetDelta); + if (canRF) + { + // + double sl = jTarget; + double tp = iPosition.tp; + string comment = "RF On Target ..."; + bool isModified = trader.Modify( + iPosition.ticket, + sl, + tp, + comment // + ); + if (isModified) + { + // + string message = prefix + + ToString(iPosition.type) + + " Position: " + + ToString(iPosition.ticket) + + " RF On Traget: " + ToString(jTarget) + + " Successfully ..."; + Alert(message); + } + } + } + } + } + } + } + + /** + * Execute Specified Signal ... + * + * @param signal: XSignal instance reference ... + * @param conditions: XCAEAStrategyConditions instance reference ... + * + * @return ( bool ) + */ + bool Execute( + XSignal &signal, + XCAEAStrategyConditions &conditions // + ) + { + // + bool result = false; + + // + result = signal.IsValid(); + if (!result) + { + return result; + } + + // + int idx = -1; + bool isExists = HasTrade( + idx, + signal // + ); + result = !isExists; + if (!result) + { + return result; + } + + // + ENUM_X_SIGNAL_EXECUTION_RESULT executionResult; + result = trader.ExecuteSignal( + signal, + executionResult // + ); + + // + // Alert Signal Execution ... + string executionMessage = ToString(executionResult); + Alert(executionMessage); + + // + if (result) + { + // + if (drawSignal) + { + // + XCSignalObject *iObj; + isExists = drawer.DrawSignal( + signal, + iObj // + ); + + // + if (isExists) + { + // + mObjects.Add(iObj); + ZeroMemory(iObj); + } + } + + // + XCAEATrade iTrade; + + // + ulong positionID = trader.GetLastOpenPositionTicket(); + double commission = trader.GetPositionCommission(positionID); + + // + iTrade.signal = signal; + iTrade.conditions = conditions; + iTrade.positionID = positionID; + iTrade.commission = commission; + + // + AddRef( + iTrade, + trades // + ); + } + + // + return result; + } + + /** + * Handle Position Take Profit ... + * + * @param deal: XDeal instance reference ... + */ + void HandleTP(const XDeal &deal) + { + // + // Check Ticket Exists or not ... + int idx = -1; + bool isExists = HasTrade( + idx, + deal.positionId // + ); + if (!isExists) + { + return; + } + + // + // Apply Required Data ... + trades[idx].swap = deal.swap; + trades[idx].profit = deal.profit; + trades[idx].commission = deal.commission; + trades[idx].finalize = XCAEA_TRADE_FINAL_TP; + + // + tpCount++; + managedTPCount++; + + // + } + + /** + * Handle Position Stop Loss ... + * + * @param deal: XDeal instance reference ... + */ + void HandleSL(const XDeal &deal) + { + // + // Check Ticket Exists or not ... + int idx = -1; + bool isExists = HasTrade( + idx, + deal.positionId // + ); + if (!isExists) + { + return; + } + + // + // Apply Required Data ... + trades[idx].swap = deal.swap; + trades[idx].profit = deal.profit; + trades[idx].commission = deal.commission; + trades[idx].finalize = XCAEA_TRADE_FINAL_SL; + + // + slCount++; + managedSLCount++; + + // + } + + /** + * Handle Position Force Close ... + * + * @param deal: XDeal instance reference ... + */ + void HandleForceClose(const XPosition &position) + { + // + // Check Ticket Exists or not ... + int idx = -1; + bool isExists = HasTrade( + idx, + position.ticket // + ); + if (!isExists) + { + return; + } + + // + bool isInProfit = position.profit > 0; + + // + // Apply Required Data ... + trades[idx].swap = position.swap; + trades[idx].profit = position.profit; + trades[idx].commission = position.commission; + trades[idx].finalize = isInProfit + ? XCAEA_TRADE_FINAL_CLOSE_IN_PROFIT + : XCAEA_TRADE_FINAL_CLOSE_IN_LOSE; + + // + if (isInProfit) + { + // + tpCount++; + managedTPCount++; + } + else + { + // + slCount++; + managedSLCount++; + } + + // + } + + // + // TODO: Complete this ... + void HandleGuard() + { + } + + /** + * Find Executed Trade by Providing Position Ticket ... + * + * @param index: int reference, holding founded item index ... + * @param ticket: ulong, Specified Position Ticket ... + * + * @return ( bool ) + */ + bool HasTrade( + int &index, + ulong ticket // + ) + { + // + bool result = false; + + // + index = -1; + + // + result = + ticket > 0 && + HasChild(trades); + if (!result) + { + return result; + } + + // + int count = ArraySize(trades); + for (int i = 0; i < count; i++) + { + // + XCAEATrade iTrade = trades[i]; + + // + result = + iTrade.HasSignal() && + iTrade.IsExecuted() && + iTrade.positionID == ticket; + if (result) + { + // + index = i; + + // + iTrade.Clean(); + break; + } + + // + iTrade.Clean(); + } + + // + result = IsValidIndex(index); + + // + return result; + } + + /** + * Find Trade Item By Signal ... + * + * @param index: int reference, holding founded item index ... + * + * @return ( bool ) + */ + bool HasTrade( + int &index, + XSignal &signal // + ) + { + // + bool result = false; + + // + index = -1; + + // + result = + signal.IsValid() && + HasChild(trades); + if (!result) + { + return result; + } + + // + int count = ArraySize(trades); + for (int i = 0; i < count; i++) + { + // + XCAEATrade iTrade = trades[i]; + + // + result = + iTrade.HasSignal() && + iTrade.signal.IsSameAs(signal); + if (result) + { + // + index = i; + + // + iTrade.Clean(); + break; + } + + // + iTrade.Clean(); + } + + // + result = IsValidIndex(index); + + // + return result; + } + + // + // Protected ... + protected: + // + // Tools ... + + // + // Private ... + private: + // + // Props ... + + // + int slCount; + int tpCount; + + // + int managedSLCount; + int managedTPCount; + + // + CArrayObj mObjects; + + // + XCAEATrade trades[]; +}; + +// diff --git a/BKPS/14040203/XCAEA/Helpers/xcaea.helper.mq5 b/BKPS/14040203/XCAEA/Helpers/xcaea.helper.mq5 new file mode 100644 index 0000000..c329c1a --- /dev/null +++ b/BKPS/14040203/XCAEA/Helpers/xcaea.helper.mq5 @@ -0,0 +1,3099 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Helper Class Library +// ---------------------------------------------- +// Name: XCXCAEAHelper +// Description: provides all Indicator +// Helper requirements ... +// +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +////////////////////////////////////////////////////// +// +// Global Properties ... +#property library +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://www.saherelm.ir" +#property version "1.00" +#property strict + +// +// Imports ... +#include "../../Classes/x-saherelm.x-bar.analyser.class.mq5" +#include "../../Classes/x-saherelm.x-poi.class.mq5" +#include "../../Classes/x-saherelm.x-poi.drawer.class.mq5" +#include "../../Helpers/x-saherelm.x121.xca.helper.mq5" +#include "../../Helpers/x-saherelm.x121.xcc.helper.mq5" +#include "../../Helpers/x-saherelm.x121.xct.helper.mq5" +#include "../../Helpers/x-saherelm.x121.xoscs.helper.mq5" + +// +// Input Structure ... +struct XCAEAInputs +{ + // + bool showAC; + bool showAD; + bool showADX; + bool showATR; + bool showCCI; + bool showRSI; + bool showMFI; + bool showRVI; + bool showMACD; + bool showMomentum; + bool showStochastic; + + // + X121XCTInputs ctInputs; + X121XCCInputs ccInputs; + X121XCAInputs caInputs; + X121XOCSInputs oscsInputs; + + // + // Constructor ... + XCAEAInputs() + { + Clean(); + } + + // + // Tools ... + + /** + * Cleaning Up ... + */ + void Clean() + { + // + showAC = false; + showAD = false; + showADX = false; + showATR = false; + showCCI = false; + showRSI = false; + showMFI = false; + showRVI = false; + showMACD = false; + showMomentum = false; + showStochastic = false; + + // + ctInputs.Clean(); + ccInputs.Clean(); + caInputs.Clean(); + oscsInputs.Clean(); + + // + ZeroMemory(this); + } + + /** + * Set Default Values ... + */ + void Default() + { + // + ctInputs.Default(); + ccInputs.Default(); + caInputs.Default(); + oscsInputs.Default(); + } + + /** + * Validate ... + * + * @return ( bool ) + */ + bool IsValid() + { + // + bool result = false; + + // + result = + // + ctInputs.IsValid() && + ccInputs.IsValid() && + caInputs.IsValid() && + oscsInputs.IsValid() + // + ; + + // + return result; + } + + /** + * Extract Max Input Length ... + * + * @return ( int ) + */ + int Max() + { + // + int result = 0; + + // + int ctMax = ctInputs.Max(); + int ccMax = ccInputs.Max(); + int caMax = caInputs.Max(); + int ocsMax = oscsInputs.Max(); + + // + result = MathMax(ctMax, ccMax); + result = MathMax(result, caMax); + result = MathMax(result, ocsMax); + + // + return result; + } +}; + +// +// Conditions Structure ... +struct XCAEAConditions +{ + // + // Common ... + string symbol; + ENUM_TIMEFRAMES period; + datetime time; + + // + datetime to; + datetime from; + + // + // XCA ... + + // + // Buffers ... + + // + double kiBuffer[]; + double tkiBuffer[]; + double sHHBuffer[]; + double sLLBuffer[]; + double mHHBuffer[]; + double mLLBuffer[]; + double lHHBuffer[]; + double lLLBuffer[]; + double hHHBuffer[]; + double hLLBuffer[]; + double sarBuffer[]; + double peakBuffer[]; + double valeBuffer[]; + double trendBuffer[]; + double kiStateBuffer[]; + double supportBuffer[]; + double tkiStateBuffer[]; + double swingLowBuffer[]; + double swingHighBuffer[]; + double resistanceBuffer[]; + double peakGoldenBuffer[]; + double valeGoldenBuffer[]; + double fiboLevel1Buffer[]; + double fiboLevel2Buffer[]; + double fiboLevel3Buffer[]; + double trendStateBuffer[]; + + // + // Conditions ... + + // + // KI ... + + // + bool isKIRejectUp; + bool isKIRejectDown; + + // + bool isKIBullish; + bool isKIBearish; + + // + bool isKISwitchedToBullish; + bool isKISwitchedToBearish; + + // + // TKI ... + + // + bool isTKIRejectUp; + bool isTKIRejectDown; + + // + bool isTKIBullish; + bool isTKIBearish; + + // + bool isTKISwitchedToBullish; + bool isTKISwitchedToBearish; + + // + // SAR ... + + // + bool isSarBullish; + bool isSarBearish; + + // + bool isSarSwitchedToBullish; + bool isSarSwitchedToBearish; + + // + // PEAK ... + + // + bool isPeakSameLast; + bool isPeakOverLast; + bool isPeakUnderLast; + + // + // VALE ... + + // + bool isValeSameLast; + bool isValeOverLast; + bool isValeUnderLast; + + // + // TREND ... + + // + bool isTrendRejectUp; + bool isTrendRejectDown; + + // + bool isTrendBullish; + bool isTrendBearish; + + // + bool isTrendSwitchedToBullish; + bool isTrendSwitchedToBearish; + + // + // SUPPORT ... + + // + bool isSupportSameLast; + bool isSupportOverLast; + bool isSupportUnderLast; + + // + bool isLastSupportBreaked; + bool isLastSupportRejected; + + // + // RESISTANCE ... + + // + bool isResistanceSameLast; + bool isResistanceOverLast; + bool isResistanceUnderLast; + + // + bool isLastResistanceBreaked; + bool isLastResistanceRejected; + + // + // SWING Low ... + + // + bool isSwingLowSameLast; + bool isSwingLowOverLast; + bool isSwingLowUnderLast; + + // + bool isLastSwingLowBreaked; + bool isLastSwingLowRejected; + + // + // SWING High ... + + // + bool isSwingHighSameLast; + bool isSwingHighOverLast; + bool isSwingHighUnderLast; + + // + bool isLastSwingHighBreaked; + bool isLastSwingHighRejected; + + // + // COMPLEX Conditions ... + + // + bool isPeakIsPivot; + bool isValeIsPivot; + + // + bool isSwingLowSameAsVale; + bool isSwingHighSameAsPeak; + + // + bool isSupportSameAsVale; + bool isResistanceSameAsPeak; + + // + bool isSupportSameAsSwingLow; + bool isResistanceSameAsSwingHigh; + + // + // XOSCS ... + + // + // Buffers ... + + // + double acBuffer[]; + double adBuffer[]; + double atrBuffer[]; + double cciBuffer[]; + double rsiBuffer[]; + double mfiBuffer[]; + double rviBuffer[]; + double adxBuffer[]; + double adxpBuffer[]; + double adxnBuffer[]; + double macdBuffer[]; + double momentumBuffer[]; + double rviSignalBuffer[]; + double macdSignalBuffer[]; + double stochasticBuffer[]; + double stochasticSignalBuffer[]; + + // + // Values ... + + // + double adxThreshold; + double cciOBLevel; + double cciOSLevel; + double cciReversalLevel; + double rsiOBLevel; + double rsiOSLevel; + double rsiReversalLevel; + double mfiOBLevel; + double mfiOSLevel; + double mfiReversalLevel; + double rviBullishLevel; + double rviBearishLevel; + double macdBullishLevel; + double macdBearishLevel; + double momentumBullishLevel; + double momentumBearishLevel; + double stochasticOBLevel; + double stochasticOSLevel; + double stochasticReversalLevel; + + + // + // Conditions ... + + // + // AC ... + + // + bool isACBullish; + bool isACBearish; + + // + bool isACSwitchedToBullish; + bool isACSwitchedToBearish; + + // + bool isACOverMax; + bool isACUnderMin; + + // + // AD ... + + // + bool isADBiggerLast; + bool isADLesserLast; + + // + bool isADOverMax; + bool isADUnderMin; + + // + // ADX ... + + // + bool isADXBiggerLast; + bool isADXLesserLast; + + // + bool isADXOverThreshold; + bool isADXUnderThreshold; + + // + bool isDXPBiggerThanDXN; + bool isDXNBiggerThanDXP; + + // + bool isADXBullish; + bool isADXBearish; + + // + bool isADXSwitchedToBullish; + bool isADXSwitchedToBearish; + + // + // ATR ... + + bool isATROverLast; + bool isATRUnderLast; + + // + // CCI ... + + // + bool isCCIBullish; + bool isCCIBearish; + + // + bool isCCISwitchedToBullish; + bool isCCISwitchedToBearish; + + // + bool isCCIOB; + bool isCCIOS; + + // + bool isCCICrossedOverOB; + bool isCCICrossedOverOS; + + // + bool isCCICrossedUnderOB; + bool isCCICrossedUnderOS; + + // + // RSI ... + + // + bool isRSIBullish; + bool isRSIBearish; + + // + bool isRSISwitchedToBullish; + bool isRSISwitchedToBearish; + + // + bool isRSIOB; + bool isRSIOS; + + // + bool isRSICrossedOverOB; + bool isRSICrossedOverOS; + + // + bool isRSICrossedUnderOB; + bool isRSICrossedUnderOS; + + // + // MFI ... + + // + bool isMFIBullish; + bool isMFIBearish; + + // + bool isMFISwitchedToBullish; + bool isMFISwitchedToBearish; + + // + bool isMFIOB; + bool isMFIOS; + + // + bool isMFICrossedOverOB; + bool isMFICrossedOverOS; + + // + bool isMFICrossedUnderOB; + bool isMFICrossedUnderOS; + + // + // RVI ... + + // + bool isRVIBullish; + bool isRVIBearish; + + // + bool isRVISwitchedToBullish; + bool isRVISwitchedToBearish; + + // + bool isRVIOverSignal; + bool isRVIUnderSignal; + + // + bool isRVICrossedOverSignal; + bool isRVICrossedUnderSignal; + + // + // MACD ... + + // + bool isMACDBullish; + bool isMACDBearish; + + // + bool isMACDSwitchedToBullish; + bool isMACDSwitchedToBearish; + + // + bool isMACDOverSignal; + bool isMACDUnderSignal; + + // + bool isMACDCrossedOverSignal; + bool isMACDCrossedUnderSignal; + + // + // MOMENTUM ... + + // + bool isMomentumBullish; + bool isMomentumBearish; + + // + bool isMomentumSwitchedToBullish; + bool isMomentumSwitchedToBearish; + + // + // STOCHASTIC ... + + // + bool isStochasticBullish; + bool isStochasticBearish; + + // + bool isStochasticSwitchedToBullish; + bool isStochasticSwitchedToBearish; + + // + bool isStochasticOverSignal; + bool isStochasticUnderSignal; + + // + bool isStochasticCrossedOverSignal; + bool isStochasticCrossedUnderSignal; + + // + bool isStochasticOB; + bool isStochasticOS; + + // + bool isStochasticCrossedOverOB; + bool isStochasticCrossedOverOS; + + // + bool isStochasticCrossedUnderOB; + bool isStochasticCrossedUnderOS; + + // + // Specified Conditions ... + + // + + // + // Constructor ... + XCAEAConditions() + { + Clean(); + } + + // + // Tools ... + + /** + * Cleaning Up ... + */ + void Clean() + { + // + // Commons ... + symbol = NULL; + period = NULL; + + // + to = NULL; + from = NULL; + time = NULL; + + // + // XCA ... + + // + // Buffers ... + + // + Clean(kiBuffer); + Clean(tkiBuffer); + Clean(sHHBuffer); + Clean(sLLBuffer); + Clean(mHHBuffer); + Clean(mLLBuffer); + Clean(lHHBuffer); + Clean(lLLBuffer); + Clean(hHHBuffer); + Clean(hLLBuffer); + Clean(sarBuffer); + Clean(peakBuffer); + Clean(valeBuffer); + Clean(trendBuffer); + Clean(kiStateBuffer); + Clean(supportBuffer); + Clean(tkiStateBuffer); + Clean(swingLowBuffer); + Clean(swingHighBuffer); + Clean(resistanceBuffer); + Clean(peakGoldenBuffer); + Clean(valeGoldenBuffer); + Clean(fiboLevel1Buffer); + Clean(fiboLevel2Buffer); + Clean(fiboLevel3Buffer); + Clean(trendStateBuffer); + + // + ArraySetAsSeries(kiBuffer, true); + ArraySetAsSeries(tkiBuffer, true); + ArraySetAsSeries(sHHBuffer, true); + ArraySetAsSeries(sLLBuffer, true); + ArraySetAsSeries(mHHBuffer, true); + ArraySetAsSeries(mLLBuffer, true); + ArraySetAsSeries(lHHBuffer, true); + ArraySetAsSeries(lLLBuffer, true); + ArraySetAsSeries(hHHBuffer, true); + ArraySetAsSeries(hLLBuffer, true); + ArraySetAsSeries(sarBuffer, true); + ArraySetAsSeries(peakBuffer, true); + ArraySetAsSeries(valeBuffer, true); + ArraySetAsSeries(trendBuffer, true); + ArraySetAsSeries(kiStateBuffer, true); + ArraySetAsSeries(supportBuffer, true); + ArraySetAsSeries(tkiStateBuffer, true); + ArraySetAsSeries(swingLowBuffer, true); + ArraySetAsSeries(swingHighBuffer, true); + ArraySetAsSeries(resistanceBuffer, true); + ArraySetAsSeries(peakGoldenBuffer, true); + ArraySetAsSeries(valeGoldenBuffer, true); + ArraySetAsSeries(fiboLevel1Buffer, true); + ArraySetAsSeries(fiboLevel2Buffer, true); + ArraySetAsSeries(fiboLevel3Buffer, true); + ArraySetAsSeries(trendStateBuffer, true); + + // + // Conditions ... + + // + // KI ... + + // + isKIRejectUp = false; + isKIRejectDown = false; + + // + isKIBullish = false; + isKIBearish = false; + + // + isKISwitchedToBullish = false; + isKISwitchedToBearish = false; + + // + // TKI ... + + // + isTKIRejectUp = false; + isTKIRejectDown = false; + + // + isTKIBullish = false; + isTKIBearish = false; + + // + isTKISwitchedToBullish = false; + isTKISwitchedToBearish = false; + + // + // SAR ... + + // + isSarBullish = false; + isSarBearish = false; + + // + isSarSwitchedToBullish = false; + isSarSwitchedToBearish = false; + + // + // PEAK ... + + // + isPeakSameLast = false; + isPeakOverLast = false; + isPeakUnderLast = false; + + // + // VALE ... + + // + isValeSameLast = false; + isValeOverLast = false; + isValeUnderLast = false; + + // + // TREND ... + + // + isTrendRejectUp = false; + isTrendRejectDown = false; + + // + isTrendBullish = false; + isTrendBearish = false; + + // + isTrendSwitchedToBullish = false; + isTrendSwitchedToBearish = false; + + // + // SUPPORT ... + + // + isSupportSameLast = false; + isSupportOverLast = false; + isSupportUnderLast = false; + + // + isLastSupportBreaked = false; + isLastSupportRejected = false; + + // + // RESISTANCE ... + + // + isResistanceSameLast = false; + isResistanceOverLast = false; + isResistanceUnderLast = false; + + // + isLastResistanceBreaked = false; + isLastResistanceRejected = false; + + // + // SWING Low ... + + // + isSwingLowSameLast = false; + isSwingLowOverLast = false; + isSwingLowUnderLast = false; + + // + isLastSwingLowBreaked = false; + isLastSwingLowRejected = false; + + // + // SWING High ... + + // + isSwingHighSameLast = false; + isSwingHighOverLast = false; + isSwingHighUnderLast = false; + + // + isLastSwingHighBreaked = false; + isLastSwingHighRejected = false; + + // + // COMPLEX Conditions ... + + // + isPeakIsPivot = false; + isValeIsPivot = false; + + // + isSwingLowSameAsVale = false; + isSwingHighSameAsPeak = false; + + // + isSupportSameAsVale = false; + isResistanceSameAsPeak = false; + + // + isSupportSameAsSwingLow = false; + isResistanceSameAsSwingHigh = false; + + // + // XOSCS ... + + // + // Buffers ... + + // + Clean(acBuffer); + Clean(adBuffer); + Clean(atrBuffer); + Clean(cciBuffer); + Clean(rsiBuffer); + Clean(mfiBuffer); + Clean(rviBuffer); + Clean(adxBuffer); + Clean(adxpBuffer); + Clean(adxnBuffer); + Clean(macdBuffer); + Clean(momentumBuffer); + Clean(rviSignalBuffer); + Clean(macdSignalBuffer); + Clean(stochasticBuffer); + Clean(stochasticSignalBuffer); + + // + ArraySetAsSeries(acBuffer, true); + ArraySetAsSeries(adBuffer, true); + ArraySetAsSeries(atrBuffer, true); + ArraySetAsSeries(cciBuffer, true); + ArraySetAsSeries(rsiBuffer, true); + ArraySetAsSeries(mfiBuffer, true); + ArraySetAsSeries(rviBuffer, true); + ArraySetAsSeries(adxBuffer, true); + ArraySetAsSeries(adxpBuffer, true); + ArraySetAsSeries(adxnBuffer, true); + ArraySetAsSeries(macdBuffer, true); + ArraySetAsSeries(momentumBuffer, true); + ArraySetAsSeries(rviSignalBuffer, true); + ArraySetAsSeries(macdSignalBuffer, true); + ArraySetAsSeries(stochasticBuffer, true); + ArraySetAsSeries(stochasticSignalBuffer, true); + + // + // Values ... + + // + adxThreshold = 0.0; + cciOBLevel = 0.0; + cciOSLevel = 0.0; + cciReversalLevel = 0.0; + rsiOBLevel = 0.0; + rsiOSLevel = 0.0; + rsiReversalLevel = 0.0; + mfiOBLevel = 0.0; + mfiOSLevel = 0.0; + mfiReversalLevel = 0.0; + rviBullishLevel = 0.0; + rviBearishLevel = 0.0; + macdBullishLevel = 0.0; + macdBearishLevel = 0.0; + momentumBullishLevel = 0.0; + momentumBearishLevel = 0.0; + stochasticOBLevel = 0.0; + stochasticOSLevel = 0.0; + stochasticReversalLevel = 0.0; + + // + // Conditions ... + + // + // AC ... + + // + isACBullish = false; + isACBearish = false; + isACSwitchedToBullish = false; + isACSwitchedToBearish = false; + isACOverMax = false; + isACUnderMin = false; + + // + // AD ... + + // + isADBiggerLast = false; + isADLesserLast = false; + isADOverMax = false; + isADUnderMin = false; + + // + // ADX ... + + // + isADXBiggerLast = false; + isADXLesserLast = false; + isADXOverThreshold = false; + isADXUnderThreshold = false; + isDXPBiggerThanDXN = false; + isDXNBiggerThanDXP = false; + isADXBullish = false; + isADXBearish = false; + isADXSwitchedToBullish = false; + isADXSwitchedToBearish = false; + + // + // ATR ... + + // + isATROverLast = false; + isATRUnderLast = false; + + // + // CCI ... + + // + isCCIBullish = false; + isCCIBearish = false; + isCCISwitchedToBullish = false; + isCCISwitchedToBearish = false; + isCCIOB = false; + isCCIOS = false; + isCCICrossedOverOB = false; + isCCICrossedOverOS = false; + isCCICrossedUnderOB = false; + isCCICrossedUnderOS = false; + + // + // RSI ... + + // + isRSIBullish = false; + isRSIBearish = false; + isRSISwitchedToBullish = false; + isRSISwitchedToBearish = false; + isRSIOB = false; + isRSIOS = false; + isRSICrossedOverOB = false; + isRSICrossedOverOS = false; + isRSICrossedUnderOB = false; + isRSICrossedUnderOS = false; + + // + // MFI ... + + // + isMFIBullish = false; + isMFIBearish = false; + isMFISwitchedToBullish = false; + isMFISwitchedToBearish = false; + isMFIOB = false; + isMFIOS = false; + isMFICrossedOverOB = false; + isMFICrossedOverOS = false; + isMFICrossedUnderOB = false; + isMFICrossedUnderOS = false; + + // + // RVI ... + + // + isRVIBullish = false; + isRVIBearish = false; + isRVISwitchedToBullish = false; + isRVISwitchedToBearish = false; + isRVIOverSignal = false; + isRVIUnderSignal = false; + isRVICrossedOverSignal = false; + isRVICrossedUnderSignal = false; + + // + // MACD ... + + // + isMACDBullish = false; + isMACDBearish = false; + isMACDSwitchedToBullish = false; + isMACDSwitchedToBearish = false; + isMACDOverSignal = false; + isMACDUnderSignal = false; + isMACDCrossedOverSignal = false; + isMACDCrossedUnderSignal = false; + + // + // MOMENTUM ... + + // + isMomentumBullish = false; + isMomentumBearish = false; + isMomentumSwitchedToBullish = false; + isMomentumSwitchedToBearish = false; + + // + // STOCHASTIC ... + + // + isStochasticBullish = false; + isStochasticBearish = false; + isStochasticSwitchedToBullish = false; + isStochasticSwitchedToBearish = false; + isStochasticOverSignal = false; + isStochasticUnderSignal = false; + isStochasticCrossedOverSignal = false; + isStochasticCrossedUnderSignal = false; + isStochasticOB = false; + isStochasticOS = false; + isStochasticCrossedOverOB = false; + isStochasticCrossedOverOS = false; + isStochasticCrossedUnderOB = false; + isStochasticCrossedUnderOS = false; + + // + ZeroMemory(this); + } + + /** + * Generate Conditions Scores ... + * + * @param bullishScore: Double, Directional Scores Reference ... + * @param bearishScore: Double, Directional Scores Reference ... + */ + void GenerateScore( + double &bullishScore, + double &bearishScore // + ) + { + // + bullishScore = 0; + bearishScore = 0; + + // + double score = 1; + double minScore = 0.5; + double highScore = 1.5; + + // + // XCA ... + + // + // KI ... + + // + if (isKIBullish) + { + bullishScore += minScore; + } + if (isKIRejectUp) + { + bullishScore += minScore; + } + if (isKISwitchedToBullish) + { + bullishScore += minScore; + } + + // + if (isKIBearish) + { + bearishScore += minScore; + } + if (isKIRejectDown) + { + bearishScore += minScore; + } + if (isKISwitchedToBearish) + { + bearishScore += minScore; + } + + // + // TKI ... + + // + if (isTKIBullish) + { + bullishScore += minScore; + } + if (isTKIRejectUp) + { + bullishScore += minScore; + } + if (isTKISwitchedToBullish) + { + bullishScore += minScore; + } + + // + if (isTKIBearish) + { + bearishScore += minScore; + } + if (isTKIRejectDown) + { + bearishScore += minScore; + } + if (isTKISwitchedToBearish) + { + bearishScore += minScore; + } + + // + // SAR ... + + // + if (isSarBullish) + { + bullishScore += minScore; + } + if (isSarSwitchedToBullish) + { + bullishScore += minScore; + } + + // + if (isSarBearish) + { + bearishScore += minScore; + } + if (isSarSwitchedToBearish) + { + bearishScore += minScore; + } + + // + // TREND ... + + // + if (isTrendBullish) + { + bullishScore += minScore; + } + if (isTrendRejectUp) + { + bullishScore += minScore; + } + if (isTrendSwitchedToBullish) + { + bullishScore += minScore; + } + + // + if (isTrendBearish) + { + bearishScore += minScore; + } + if (isTrendRejectDown) + { + bearishScore += minScore; + } + if (isTrendSwitchedToBearish) + { + bearishScore += minScore; + } + + // + // SUPPORT ... + + // + if (isSupportSameLast) + { + bullishScore += minScore; + } + if (isSupportOverLast) + { + bullishScore += minScore; + } + if (isLastSupportRejected) + { + bullishScore += minScore; + } + + // + if (isSupportUnderLast) + { + bearishScore += minScore; + } + if (isLastSupportBreaked) + { + bearishScore += minScore; + } + + // + // RESISTANCE ... + + // + if (isResistanceOverLast) + { + bullishScore += minScore; + } + if (isLastResistanceBreaked) + { + bullishScore += minScore; + } + + // + if (isResistanceSameLast) + { + bearishScore += minScore; + } + if (isResistanceUnderLast) + { + bearishScore += minScore; + } + if (isLastResistanceRejected) + { + bearishScore += minScore; + } + + // + // SWING Low ... + + // + if (isSwingLowSameLast) + { + bullishScore += minScore; + } + if (isSwingLowOverLast) + { + bullishScore += minScore; + } + if (isLastSwingLowRejected) + { + bullishScore += minScore; + } + + // + if (isSwingLowUnderLast) + { + bearishScore += minScore; + } + if (isLastSwingLowBreaked) + { + bearishScore += minScore; + } + + // + // SWING High ... + + // + if (isSwingHighOverLast) + { + bullishScore += minScore; + } + if (isLastSwingHighBreaked) + { + bullishScore += minScore; + } + + // + if (isSwingHighSameLast) + { + bearishScore += minScore; + } + if (isSwingHighUnderLast) + { + bearishScore += minScore; + } + if (isLastSwingHighRejected) + { + bearishScore += minScore; + } + + // + // COMPLEX Conditions ... + + // + if (isValeIsPivot) + { + bullishScore += score; + } + if (isSupportSameAsVale) + { + bullishScore += score; + } + if (isSwingLowSameAsVale) + { + bullishScore += score; + } + if (isSupportSameAsSwingLow) + { + bullishScore += score; + } + + // + if (isPeakIsPivot) + { + bearishScore += score; + } + if (isSwingHighSameAsPeak) + { + bearishScore += score; + } + if (isResistanceSameAsPeak) + { + bearishScore += score; + } + if (isResistanceSameAsSwingHigh) + { + bearishScore += score; + } + + // + // XOCS ... + + // + // AC ... + + // + if (isACBullish) + { + bullishScore += minScore; + } + if (isACOverMax) + { + bullishScore += minScore; + } + if (isACSwitchedToBullish) + { + bullishScore += minScore; + } + + // + if (isACBearish) + { + bearishScore += minScore; + } + if (isACUnderMin) + { + bearishScore += minScore; + } + if (isACSwitchedToBearish) + { + bearishScore += minScore; + } + + // + // AD ... + + // + if (isADOverMax) + { + bullishScore += minScore; + } + if (isADBiggerLast) + { + bullishScore += minScore; + } + + // + if (isADUnderMin) + { + bearishScore += minScore; + } + if (isADLesserLast) + { + bearishScore += minScore; + } + + // + // ADX ... + + // + if (isADXBullish) + { + bullishScore += minScore; + } + if (isADXBiggerLast) + { + bullishScore += minScore; + } + if (isADXOverThreshold) + { + bullishScore += minScore; + } + if (isDXPBiggerThanDXN) + { + bullishScore += minScore; + } + if (isADXSwitchedToBullish) + { + bullishScore += minScore; + } + + // + if (isADXBearish) + { + bearishScore += minScore; + } + if (isADXLesserLast) + { + bearishScore += minScore; + } + if (isDXNBiggerThanDXP) + { + bearishScore += minScore; + } + if (isADXUnderThreshold) + { + bearishScore += minScore; + } + if (isADXSwitchedToBearish) + { + bearishScore += minScore; + } + + // + // ATR ... + + // + if (isATROverLast) + { + bullishScore += minScore; + } + + // + if (isATRUnderLast) + { + bearishScore += minScore; + } + + // + // CCI ... + + // + if (isCCIOS) + { + bullishScore += minScore; + } + if (isCCIBullish) + { + bullishScore += minScore; + } + if (isCCICrossedOverOS) + { + bullishScore += minScore; + } + if (isCCICrossedOverOB) + { + bullishScore += minScore; + } + if (isCCISwitchedToBullish) + { + bullishScore += minScore; + } + + // + if (isCCIOB) + { + bearishScore += minScore; + } + if (isCCIBearish) + { + bearishScore += minScore; + } + if (isCCICrossedUnderOS) + { + bearishScore += minScore; + } + if (isCCICrossedUnderOB) + { + bearishScore += minScore; + } + if (isCCISwitchedToBearish) + { + bearishScore += minScore; + } + + // + // RSI ... + + // + if (isRSIOS) + { + bullishScore += minScore; + } + if (isRSIBullish) + { + bullishScore += minScore; + } + if (isRSICrossedOverOB) + { + bullishScore += minScore; + } + if (isRSICrossedOverOS) + { + bullishScore += minScore; + } + if (isRSISwitchedToBullish) + { + bullishScore += minScore; + } + + // + if (isRSIOB) + { + bearishScore += minScore; + } + if (isRSIBearish) + { + bearishScore += minScore; + } + if (isRSICrossedUnderOB) + { + bearishScore += minScore; + } + if (isRSICrossedUnderOS) + { + bearishScore += minScore; + } + if (isRSISwitchedToBearish) + { + bearishScore += minScore; + } + + // + // MFI ... + + // + if (isMFIOS) + { + bullishScore += minScore; + } + if (isMFIBullish) + { + bullishScore += minScore; + } + if (isMFICrossedOverOB) + { + bullishScore += minScore; + } + if (isMFICrossedOverOS) + { + bullishScore += minScore; + } + if (isMFISwitchedToBullish) + { + bullishScore += minScore; + } + + // + if (isMFIOB) + { + bearishScore += minScore; + } + if (isMFIBearish) + { + bearishScore += minScore; + } + if (isMFICrossedUnderOB) + { + bearishScore += minScore; + } + if (isMFICrossedUnderOS) + { + bearishScore += minScore; + } + if (isMFISwitchedToBearish) + { + bearishScore += minScore; + } + + // + // RVI ... + + // + if (isRVIBullish) + { + bullishScore += minScore; + } + if (isRVIOverSignal) + { + bullishScore += minScore; + } + if (isRVISwitchedToBullish) + { + bullishScore += minScore; + } + if (isRVICrossedOverSignal) + { + bullishScore += minScore; + } + + // + if (isRVIBearish) + { + bearishScore += minScore; + } + if (isRVIUnderSignal) + { + bearishScore += minScore; + } + if (isRVISwitchedToBearish) + { + bearishScore += minScore; + } + if (isRVICrossedUnderSignal) + { + bearishScore += minScore; + } + + // + // MACD ... + + // + if (isMACDBullish) + { + bullishScore += minScore; + } + if (isMACDOverSignal) + { + bullishScore += minScore; + } + if (isMACDSwitchedToBullish) + { + bullishScore += minScore; + } + if (isMACDCrossedOverSignal) + { + bullishScore += minScore; + } + + // + if (isMACDBearish) + { + bearishScore += minScore; + } + if (isMACDUnderSignal) + { + bearishScore += minScore; + } + if (isMACDSwitchedToBearish) + { + bearishScore += minScore; + } + if (isMACDCrossedUnderSignal) + { + bearishScore += minScore; + } + + // + // MOMENTUM ... + + // + if (isMomentumBullish) + { + bullishScore += minScore; + } + if (isMomentumSwitchedToBullish) + { + bullishScore += minScore; + } + + // + if (isMomentumBearish) + { + bearishScore += minScore; + } + if (isMomentumSwitchedToBearish) + { + bearishScore += minScore; + } + + // + // STOCHASTIC ... + + // + if (isStochasticOS) + { + bullishScore += minScore; + } + if (isStochasticOverSignal) + { + bullishScore += minScore; + } + if (isStochasticBullish) + { + bullishScore += minScore; + } + if (isStochasticCrossedOverSignal) + { + bullishScore += minScore; + } + if (isStochasticCrossedOverOB) + { + bullishScore += minScore; + } + if (isStochasticCrossedOverOS) + { + bullishScore += minScore; + } + if (isStochasticSwitchedToBullish) + { + bullishScore += minScore; + } + + // + if (isStochasticOB) + { + bearishScore += minScore; + } + if (isStochasticUnderSignal) + { + bearishScore += minScore; + } + if (isStochasticBearish) + { + bearishScore += minScore; + } + if (isStochasticCrossedUnderSignal) + { + bearishScore += minScore; + } + if (isStochasticCrossedUnderOB) + { + bearishScore += minScore; + } + if (isStochasticCrossedUnderOS) + { + bearishScore += minScore; + } + if (isStochasticSwitchedToBearish) + { + bearishScore += minScore; + } + } + + /** + * Generate Summary String for Represent Conditions State ... + * + * @param onlyCommons: Boolean, Just Generate Only Commons Conditions ... + * @param onlyConditions: Boolean, Just Generate Only Conditions ... + * @param includeScores: Boolean, Attach Scores Representations on Result ... + * @param ignoreFalseConditions: Boolean, Ignore False Conditions on Result ... + * @param separator: String, Separate Lines ... + * + * @return ( string ) + */ + string GenerateSummary( + bool onlyCommons = false, + bool onlyConditions = false, + bool includeScores = true, + bool ignoreFalseConditions = true, + string separator = "\n" // + ) + { + // + string result = NULL; + + // + double bullishScore = 0; + double bearishScore = 0; + GenerateScore( + bullishScore, + bearishScore // + ); + + // + string scoresStr = + // + "Scores: " + separator + + "---------------" + separator + + "Bullish: " + ToString(bullishScore) + separator + + "Bearish: " + ToString(bearishScore) + separator + + "" + // + ; + + // + string commonStr = GenerateSpecifiedCommonSummary( + this, + separator, + includeScores // + ); + + // + string conditionsStr = + // + // + "-----------------------" + separator + + "XCA: " + separator + + "-----------------------" + separator + + ToString("isKIRejectUp", isKIRejectUp, ignoreFalseConditions, separator) + + ToString("isKIRejectDown", isKIRejectDown, ignoreFalseConditions, separator) + + ToString("isKIBullish", isKIBullish, ignoreFalseConditions, separator) + + ToString("isKIBearish", isKIBearish, ignoreFalseConditions, separator) + + ToString("isKISwitchedToBullish", isKISwitchedToBullish, ignoreFalseConditions, separator) + + ToString("isKISwitchedToBearish", isKISwitchedToBearish, ignoreFalseConditions, separator) + + ToString("isTKIRejectUp", isTKIRejectUp, ignoreFalseConditions, separator) + + ToString("isTKIRejectDown", isTKIRejectDown, ignoreFalseConditions, separator) + + ToString("isTKIBullish", isTKIBullish, ignoreFalseConditions, separator) + + ToString("isTKIBearish", isTKIBearish, ignoreFalseConditions, separator) + + ToString("isTKISwitchedToBullish", isTKISwitchedToBullish, ignoreFalseConditions, separator) + + ToString("isTKISwitchedToBearish", isTKISwitchedToBearish, ignoreFalseConditions, separator) + + ToString("isSarBullish", isSarBullish, ignoreFalseConditions, separator) + + ToString("isSarBearish", isSarBearish, ignoreFalseConditions, separator) + + ToString("isSarSwitchedToBullish", isSarSwitchedToBullish, ignoreFalseConditions, separator) + + ToString("isSarSwitchedToBearish", isSarSwitchedToBearish, ignoreFalseConditions, separator) + + ToString("isPeakSameLast", isPeakSameLast, ignoreFalseConditions, separator) + + ToString("isPeakOverLast", isPeakOverLast, ignoreFalseConditions, separator) + + ToString("isPeakUnderLast", isPeakUnderLast, ignoreFalseConditions, separator) + + ToString("isValeSameLast", isValeSameLast, ignoreFalseConditions, separator) + + ToString("isValeOverLast", isValeOverLast, ignoreFalseConditions, separator) + + ToString("isValeUnderLast", isValeUnderLast, ignoreFalseConditions, separator) + + ToString("isTrendRejectUp", isTrendRejectUp, ignoreFalseConditions, separator) + + ToString("isTrendRejectDown", isTrendRejectDown, ignoreFalseConditions, separator) + + ToString("isTrendBullish", isTrendBullish, ignoreFalseConditions, separator) + + ToString("isTrendBearish", isTrendBearish, ignoreFalseConditions, separator) + + ToString("isTrendSwitchedToBullish", isTrendSwitchedToBullish, ignoreFalseConditions, separator) + + ToString("isTrendSwitchedToBearish", isTrendSwitchedToBearish, ignoreFalseConditions, separator) + + ToString("isSupportSameLast", isSupportSameLast, ignoreFalseConditions, separator) + + ToString("isSupportOverLast", isSupportOverLast, ignoreFalseConditions, separator) + + ToString("isSupportUnderLast", isSupportUnderLast, ignoreFalseConditions, separator) + + ToString("isLastSupportBreaked", isLastSupportBreaked, ignoreFalseConditions, separator) + + ToString("isLastSupportRejected", isLastSupportRejected, ignoreFalseConditions, separator) + + ToString("isResistanceSameLast", isResistanceSameLast, ignoreFalseConditions, separator) + + ToString("isResistanceOverLast", isResistanceOverLast, ignoreFalseConditions, separator) + + ToString("isResistanceUnderLast", isResistanceUnderLast, ignoreFalseConditions, separator) + + ToString("isLastResistanceBreaked", isLastResistanceBreaked, ignoreFalseConditions, separator) + + ToString("isLastResistanceRejected", isLastResistanceRejected, ignoreFalseConditions, separator) + + ToString("isSwingLowSameLast", isSwingLowSameLast, ignoreFalseConditions, separator) + + ToString("isSwingLowOverLast", isSwingLowOverLast, ignoreFalseConditions, separator) + + ToString("isSwingLowUnderLast", isSwingLowUnderLast, ignoreFalseConditions, separator) + + ToString("isLastSwingLowBreaked", isLastSwingLowBreaked, ignoreFalseConditions, separator) + + ToString("isLastSwingLowRejected", isLastSwingLowRejected, ignoreFalseConditions, separator) + + ToString("isSwingHighSameLast", isSwingHighSameLast, ignoreFalseConditions, separator) + + ToString("isSwingHighOverLast", isSwingHighOverLast, ignoreFalseConditions, separator) + + ToString("isSwingHighUnderLast", isSwingHighUnderLast, ignoreFalseConditions, separator) + + ToString("isLastSwingHighBreaked", isLastSwingHighBreaked, ignoreFalseConditions, separator) + + ToString("isLastSwingHighRejected", isLastSwingHighRejected, ignoreFalseConditions, separator) + + ToString("isPeakIsPivot", isPeakIsPivot, ignoreFalseConditions, separator) + + ToString("isValeIsPivot", isValeIsPivot, ignoreFalseConditions, separator) + + ToString("isSwingLowSameAsVale", isSwingLowSameAsVale, ignoreFalseConditions, separator) + + ToString("isSwingHighSameAsPeak", isSwingHighSameAsPeak, ignoreFalseConditions, separator) + + ToString("isSupportSameAsVale", isSupportSameAsVale, ignoreFalseConditions, separator) + + ToString("isResistanceSameAsPeak", isResistanceSameAsPeak, ignoreFalseConditions, separator) + + ToString("isSupportSameAsSwingLow", isSupportSameAsSwingLow, ignoreFalseConditions, separator) + + ToString("isResistanceSameAsSwingHigh", isResistanceSameAsSwingHigh, ignoreFalseConditions, separator) + + "-----------------------" + separator + + "XOCS: " + separator + + "-----------------------" + separator + + ToString("isACBullish", isACBullish, ignoreFalseConditions, separator) + + ToString("isACBearish", isACBearish, ignoreFalseConditions, separator) + + ToString("isACSwitchedToBullish", isACSwitchedToBullish, ignoreFalseConditions, separator) + + ToString("isACSwitchedToBearish", isACSwitchedToBearish, ignoreFalseConditions, separator) + + ToString("isACOverMax", isACOverMax, ignoreFalseConditions, separator) + + ToString("isACUnderMin", isACUnderMin, ignoreFalseConditions, separator) + + ToString("isADBiggerLast", isADBiggerLast, ignoreFalseConditions, separator) + + ToString("isADLesserLast", isADLesserLast, ignoreFalseConditions, separator) + + ToString("isADOverMax", isADOverMax, ignoreFalseConditions, separator) + + ToString("isADUnderMin", isADUnderMin, ignoreFalseConditions, separator) + + ToString("isADXBiggerLast", isADXBiggerLast, ignoreFalseConditions, separator) + + ToString("isADXLesserLast", isADXLesserLast, ignoreFalseConditions, separator) + + ToString("isADXOverThreshold", isADXOverThreshold, ignoreFalseConditions, separator) + + ToString("isADXUnderThreshold", isADXUnderThreshold, ignoreFalseConditions, separator) + + ToString("isDXPBiggerThanDXN", isDXPBiggerThanDXN, ignoreFalseConditions, separator) + + ToString("isDXNBiggerThanDXP", isDXNBiggerThanDXP, ignoreFalseConditions, separator) + + ToString("isADXBullish", isADXBullish, ignoreFalseConditions, separator) + + ToString("isADXBearish", isADXBearish, ignoreFalseConditions, separator) + + ToString("isADXSwitchedToBullish", isADXSwitchedToBullish, ignoreFalseConditions, separator) + + ToString("isADXSwitchedToBearish", isADXSwitchedToBearish, ignoreFalseConditions, separator) + + ToString("isATROverLast", isATROverLast, ignoreFalseConditions, separator) + + ToString("isATRUnderLast", isATRUnderLast, ignoreFalseConditions, separator) + + ToString("isCCIBullish", isCCIBullish, ignoreFalseConditions, separator) + + ToString("isCCIBearish", isCCIBearish, ignoreFalseConditions, separator) + + ToString("isCCISwitchedToBullish", isCCISwitchedToBullish, ignoreFalseConditions, separator) + + ToString("isCCISwitchedToBearish", isCCISwitchedToBearish, ignoreFalseConditions, separator) + + ToString("isCCIOB", isCCIOB, ignoreFalseConditions, separator) + + ToString("isCCIOS", isCCIOS, ignoreFalseConditions, separator) + + ToString("isCCICrossedOverOB", isCCICrossedOverOB, ignoreFalseConditions, separator) + + ToString("isCCICrossedOverOS", isCCICrossedOverOS, ignoreFalseConditions, separator) + + ToString("isCCICrossedUnderOB", isCCICrossedUnderOB, ignoreFalseConditions, separator) + + ToString("isCCICrossedUnderOS", isCCICrossedUnderOS, ignoreFalseConditions, separator) + + ToString("isRSIBullish", isRSIBullish, ignoreFalseConditions, separator) + + ToString("isRSIBearish", isRSIBearish, ignoreFalseConditions, separator) + + ToString("isRSISwitchedToBullish", isRSISwitchedToBullish, ignoreFalseConditions, separator) + + ToString("isRSISwitchedToBearish", isRSISwitchedToBearish, ignoreFalseConditions, separator) + + ToString("isRSIOB", isRSIOB, ignoreFalseConditions, separator) + + ToString("isRSIOS", isRSIOS, ignoreFalseConditions, separator) + + ToString("isRSICrossedOverOB", isRSICrossedOverOB, ignoreFalseConditions, separator) + + ToString("isRSICrossedOverOS", isRSICrossedOverOS, ignoreFalseConditions, separator) + + ToString("isRSICrossedUnderOB", isRSICrossedUnderOB, ignoreFalseConditions, separator) + + ToString("isRSICrossedUnderOS", isRSICrossedUnderOS, ignoreFalseConditions, separator) + + ToString("isMFIBullish", isMFIBullish, ignoreFalseConditions, separator) + + ToString("isMFIBearish", isMFIBearish, ignoreFalseConditions, separator) + + ToString("isMFISwitchedToBullish", isMFISwitchedToBullish, ignoreFalseConditions, separator) + + ToString("isMFISwitchedToBearish", isMFISwitchedToBearish, ignoreFalseConditions, separator) + + ToString("isMFIOB", isMFIOB, ignoreFalseConditions, separator) + + ToString("isMFIOS", isMFIOS, ignoreFalseConditions, separator) + + ToString("isMFICrossedOverOB", isMFICrossedOverOB, ignoreFalseConditions, separator) + + ToString("isMFICrossedOverOS", isMFICrossedOverOS, ignoreFalseConditions, separator) + + ToString("isMFICrossedUnderOB", isMFICrossedUnderOB, ignoreFalseConditions, separator) + + ToString("isMFICrossedUnderOS", isMFICrossedUnderOS, ignoreFalseConditions, separator) + + ToString("isRVIBullish", isRVIBullish, ignoreFalseConditions, separator) + + ToString("isRVIBearish", isRVIBearish, ignoreFalseConditions, separator) + + ToString("isRVISwitchedToBullish", isRVISwitchedToBullish, ignoreFalseConditions, separator) + + ToString("isRVISwitchedToBearish", isRVISwitchedToBearish, ignoreFalseConditions, separator) + + ToString("isRVIOverSignal", isRVIOverSignal, ignoreFalseConditions, separator) + + ToString("isRVIUnderSignal", isRVIUnderSignal, ignoreFalseConditions, separator) + + ToString("isRVICrossedOverSignal", isRVICrossedOverSignal, ignoreFalseConditions, separator) + + ToString("isRVICrossedUnderSignal", isRVICrossedUnderSignal, ignoreFalseConditions, separator) + + ToString("isMACDBullish", isMACDBullish, ignoreFalseConditions, separator) + + ToString("isMACDBearish", isMACDBearish, ignoreFalseConditions, separator) + + ToString("isMACDSwitchedToBullish", isMACDSwitchedToBullish, ignoreFalseConditions, separator) + + ToString("isMACDSwitchedToBearish", isMACDSwitchedToBearish, ignoreFalseConditions, separator) + + ToString("isMACDOverSignal", isMACDOverSignal, ignoreFalseConditions, separator) + + ToString("isMACDUnderSignal", isMACDUnderSignal, ignoreFalseConditions, separator) + + ToString("isMACDCrossedOverSignal", isMACDCrossedOverSignal, ignoreFalseConditions, separator) + + ToString("isMACDCrossedUnderSignal", isMACDCrossedUnderSignal, ignoreFalseConditions, separator) + + ToString("isMomentumBullish", isMomentumBullish, ignoreFalseConditions, separator) + + ToString("isMomentumBearish", isMomentumBearish, ignoreFalseConditions, separator) + + ToString("isMomentumSwitchedToBullish", isMomentumSwitchedToBullish, ignoreFalseConditions, separator) + + ToString("isMomentumSwitchedToBearish", isMomentumSwitchedToBearish, ignoreFalseConditions, separator) + + ToString("isStochasticBullish", isStochasticBullish, ignoreFalseConditions, separator) + + ToString("isStochasticBearish", isStochasticBearish, ignoreFalseConditions, separator) + + ToString("isStochasticSwitchedToBullish", isStochasticSwitchedToBullish, ignoreFalseConditions, separator) + + ToString("isStochasticSwitchedToBearish", isStochasticSwitchedToBearish, ignoreFalseConditions, separator) + + ToString("isStochasticOverSignal", isStochasticOverSignal, ignoreFalseConditions, separator) + + ToString("isStochasticUnderSignal", isStochasticUnderSignal, ignoreFalseConditions, separator) + + ToString("isStochasticCrossedOverSignal", isStochasticCrossedOverSignal, ignoreFalseConditions, separator) + + ToString("isStochasticCrossedUnderSignal", isStochasticCrossedUnderSignal, ignoreFalseConditions, separator) + + ToString("isStochasticOB", isStochasticOB, ignoreFalseConditions, separator) + + ToString("isStochasticOS", isStochasticOS, ignoreFalseConditions, separator) + + ToString("isStochasticCrossedOverOB", isStochasticCrossedOverOB, ignoreFalseConditions, separator) + + ToString("isStochasticCrossedOverOS", isStochasticCrossedOverOS, ignoreFalseConditions, separator) + + ToString("isStochasticCrossedUnderOB", isStochasticCrossedUnderOB, ignoreFalseConditions, separator) + + ToString("isStochasticCrossedUnderOS", isStochasticCrossedUnderOS, ignoreFalseConditions, separator) + + // + "" + // + ; + + // + result = + // + "[" + GetTag() + "]" + separator + + (onlyConditions + ? "" + : commonStr) + + (!includeScores + ? "" + : scoresStr) + + " " + separator + + (onlyCommons + ? "" + : conditionsStr) + + "" + // + ; + + // + return result; + } + + /** + * Retrieve nique Tag Identifier ... + * + * @return ( string ) + */ + string GetTag() + { + return GetTypeName(this); + } +}; + +// +// Helper Class Implementation ... +class XCXCAEAHelper : XCBase +{ + // + // Public ... + public: + // + // Props ... + + // + XCPOIDrawer *poiDrawer; + XCPOIDetector *poiDetector; + + // + XCBarAnalyser *barAnalyser; + + // + XCX121XCCHelper *ccHelper; + XCX121XCTHelper *ctHelper; + XCX121XCAHelper *caHelper; + XCX121XOCSHelper *ocsHelper; + + // + // Constructor ... + XCXCAEAHelper() + { + // + barAnalyser = new XCBarAnalyser(); + } + + // + // Deconstructor ... + ~XCXCAEAHelper() + { + // + mInputs.Clean(); + + // + ZeroMemory(ccHelper); + ZeroMemory(ctHelper); + ZeroMemory(caHelper); + ZeroMemory(ocsHelper); + + // + ZeroMemory(poiDrawer); + ZeroMemory(poiDetector); + ZeroMemory(barAnalyser); + + // + IndicatorRelease(acHandler); + IndicatorRelease(adHandler); + IndicatorRelease(adxHandler); + IndicatorRelease(atrHandler); + IndicatorRelease(cciHandler); + IndicatorRelease(rsiHandler); + IndicatorRelease(mfiHandler); + IndicatorRelease(rviHandler); + IndicatorRelease(macdHandler); + IndicatorRelease(momentumHandler); + IndicatorRelease(stochasticHandler); + } + + // + string GetSymbol() + { + return mSymbol; + } + + // + ENUM_TIMEFRAMES GetPeriod() + { + return mPeriod; + } + + // + // Tools ... + + /** + * Initialize Indicator Helper ... + * + * @param symbol: String, Symbol ... + * @param period: ENUM_TIMEFRAMES member, Period ... + * @param inputs: XCAEAInputs instance, Indicator Inputs ... + * + * @return ( bool ) + */ + bool Init( + string symbol, // Trading Symbol + ENUM_TIMEFRAMES period, // Trading Period + XCAEAInputs &inputs // Inputs + ) + { + // + bool result = false; + + // + result = + IsValid(symbol) && + IsValid(period) && + inputs.IsValid(); + if (!result) + { + return result; + } + + // + mSymbol = symbol; + mPeriod = period; + + // + poiDetector = new XCPOIDetector( + symbol, + period // + ); + poiDetector.Init(); + + // + poiDrawer = new XCPOIDrawer(); + + // + // Setting Inputs ... + + // + mInputs = inputs; + + // + // Initial Helpers ... + + // + // XCT ... + ctHelper = new XCX121XCTHelper(); + result = + result && + ctHelper.Init( + symbol, + period, + mInputs.ctInputs // + ); + + // + // XCC ... + ccHelper = new XCX121XCCHelper(); + result = + result && + ccHelper.Init( + symbol, + period, + mInputs.ccInputs // + ); + + // + // XCA ... + caHelper = new XCX121XCAHelper(); + result = + result && + caHelper.Init( + symbol, + period, + mInputs.caInputs // + ); + + // + // XOSC ... + ocsHelper = new XCX121XOCSHelper(); + result = + result && + ocsHelper.Init( + symbol, + period, + mInputs.oscsInputs // + ); + + // + if (!result) + { + // + ZeroMemory(ccHelper); + ZeroMemory(ctHelper); + ZeroMemory(caHelper); + ZeroMemory(ocsHelper); + + // + ZeroMemory(poiDrawer); + ZeroMemory(poiDetector); + + // + return result; + } + + // + // OSCILLATORS Viewers ... + + // + // AC ... + if (mInputs.showAC) + { + // + acHandler = iAC( + symbol, + period // + ); + + // + result = + result && + acHandler != INVALID_HANDLE; + } + + // + // AD ... + if (mInputs.showAD) + { + // + adHandler = iAD( + symbol, + period, + mInputs.oscsInputs.adAppliedTo // + ); + + // + result = + result && + adHandler != INVALID_HANDLE; + } + + // + // ADX ... + if (mInputs.showADX) + { + // + adxHandler = iADX( + symbol, + period, + mInputs.oscsInputs.adxLength // + ); + + // + result = + result && + adxHandler != INVALID_HANDLE; + } + + // + // ATR ... + if (mInputs.showATR) + { + // + atrHandler = iATR( + symbol, + period, + mInputs.oscsInputs.atrLength // + ); + + // + result = + result && + atrHandler != INVALID_HANDLE; + } + + // + // CCI ... + if (mInputs.showCCI) + { + // + cciHandler = iCCI( + symbol, + period, + mInputs.oscsInputs.cciLength, + mInputs.oscsInputs.cciAppliedTo // + ); + + // + result = + result && + cciHandler != INVALID_HANDLE; + } + + // + // RSI ... + if (mInputs.showRSI) + { + // + rsiHandler = iRSI( + symbol, + period, + mInputs.oscsInputs.rsiLength, + mInputs.oscsInputs.rsiAppliedTo // + ); + + // + result = + result && + rsiHandler != INVALID_HANDLE; + } + + // + // MFI ... + if (mInputs.showMFI) + { + // + mfiHandler = iMFI( + symbol, + period, + mInputs.oscsInputs.mfiLength, + mInputs.oscsInputs.mfiAppliedTo // + ); + + // + result = + result && + mfiHandler != INVALID_HANDLE; + } + + // + // RVI ... + if (mInputs.showRVI) + { + // + rviHandler = iRVI( + symbol, + period, + mInputs.oscsInputs.rviLength // + ); + + // + result = + result && + rviHandler != INVALID_HANDLE; + } + + // + // MACD ... + if (mInputs.showMACD) + { + // + macdHandler = iMACD( + symbol, + period, + mInputs.oscsInputs.macdFastLength, + mInputs.oscsInputs.macdSlowLength, + mInputs.oscsInputs.macdSignalLength, + mInputs.oscsInputs.macdAppliedTo // + ); + + // + result = + result && + macdHandler != INVALID_HANDLE; + } + + // + // Momentum ... + if (mInputs.showMomentum) + { + // + momentumHandler = iMomentum( + symbol, + period, + mInputs.oscsInputs.momentumLength, + mInputs.oscsInputs.momentumAppliedTo // + ); + + // + result = + result && + momentumHandler != INVALID_HANDLE; + } + + // + // Stochastic ... + if (mInputs.showStochastic) + { + // + stochasticHandler = iStochastic( + symbol, + period, + mInputs.oscsInputs.stochasticKLength, + mInputs.oscsInputs.stochasticDLength, + mInputs.oscsInputs.stochasticSmoothingLength, + mInputs.oscsInputs.stochasticSmoothingMethod, + mInputs.oscsInputs.stochasticAppliedTo // + ); + + // + result = + result && + stochasticHandler != INVALID_HANDLE; + } + + // + // If Result is False, Cleanup Resources ... + if (!result) + { + // + mInputs.Clean(); + + // + ZeroMemory(ccHelper); + ZeroMemory(ctHelper); + ZeroMemory(caHelper); + ZeroMemory(ocsHelper); + + // + IndicatorRelease(acHandler); + IndicatorRelease(adHandler); + IndicatorRelease(adxHandler); + IndicatorRelease(atrHandler); + IndicatorRelease(cciHandler); + IndicatorRelease(rsiHandler); + IndicatorRelease(mfiHandler); + IndicatorRelease(rviHandler); + IndicatorRelease(macdHandler); + IndicatorRelease(momentumHandler); + IndicatorRelease(stochasticHandler); + + // + return result; + } + + // + return result; + } + + // + // Conditions Readers ... + + /** + * Retrieve Conditions ... + * + * @param conditions: Argument 1 + * @param barIndex: int, Specified Bar Index ... + * @param loopback: int, Loopback looking for others ... + * + * @return ( bool ) + */ + bool GetCAConditions( + X121XCAConditions &conditions, // + int barIndex = 0, // + int loopback = 5 // + ) + { + // + bool result = false; + + // + result = caHelper.GetConditions( + conditions, + barIndex, + loopback // + ); + + // + return result; + } + + /** + * Retrieve Conditions ... + * + * @param conditions: Argument 1 + * @param barIndex: int, Specified Bar Index ... + * @param loopback: int, Loopback looking for others ... + * + * @return ( bool ) + */ + bool GetOSCSConditions( + X121XOCSConditions &conditions, // + int barIndex = 0, // + int loopback = 5 // + ) + { + // + bool result = false; + + // + result = ocsHelper.GetConditions( + conditions, + barIndex, + loopback // + ); + + // + return result; + } + + // + // Others ... + + // + void Free() + { + // + caHelper.Free(); + ocsHelper.Free(); + } + + // + bool GetConditions( + XCAEAConditions &conditions, // + int barIndex = 0, // + int loopback = 5 // + ) + { + // + bool result = true; + + // + if (loopback < 5) + { + loopback = 5; + } + + // + conditions.Clean(); + + // + conditions.symbol = mSymbol; + conditions.period = mPeriod; + conditions.time = TimeCurrent(); + + // + int zIndex = barIndex; + int cIndex = zIndex + 1; + int pIndex = cIndex + 1; + int ppIndex = pIndex + 1; + + // + XOHCL zBar; + XOHCL cBar; + XOHCL pBar; + XOHCL fromBar; + + // + X121XCAConditions xcaConditions; + X121XOCSConditions xocsConditions; + + // + result = zBar.Init( + mSymbol, + mPeriod, + zIndex // + ); + result = + result && + zBar.GetPreviousBar(cBar); + result = + result && + cBar.GetPreviousBar(pBar); + result = + result && + fromBar.Init( + zBar.symbol, + zBar.period, + zIndex + loopback); + + // + // Conditions Retriever ... + + // + // XCA ... + result = + result && + GetCAConditions( + xcaConditions, + barIndex, + loopback // + ); + + // + // XOSCS ... + result = + result && + GetOSCSConditions( + xocsConditions, + barIndex, + loopback // + ); + + // + // Check Result ... + if (!result) + { + // + zBar.Clean(); + cBar.Clean(); + pBar.Clean(); + fromBar.Clean(); + + // + xcaConditions.Clean(); + xocsConditions.Clean(); + + // + return result; + } + + // + conditions.to = zBar.time; + conditions.from = fromBar.time; + + // + // Fill X121 Conditions Reference by Using + // Retrieved Conditions ... + + // + int cIDX = 1; + int pIDX = cIDX + 1; + + // + // XCA ... + + // + // Buffers ... + + // + Copy( + xcaConditions.kiBuffer, + conditions.kiBuffer // + ); + + // + Copy( + xcaConditions.tkiBuffer, + conditions.tkiBuffer // + ); + + // + Copy( + xcaConditions.sHHBuffer, + conditions.sHHBuffer // + ); + + // + Copy( + xcaConditions.sLLBuffer, + conditions.sLLBuffer // + ); + + // + Copy( + xcaConditions.mHHBuffer, + conditions.mHHBuffer // + ); + + // + Copy( + xcaConditions.mLLBuffer, + conditions.mLLBuffer // + ); + + // + Copy( + xcaConditions.lHHBuffer, + conditions.lHHBuffer // + ); + + // + Copy( + xcaConditions.lLLBuffer, + conditions.lLLBuffer // + ); + + // + Copy( + xcaConditions.hHHBuffer, + conditions.hHHBuffer // + ); + + // + Copy( + xcaConditions.hLLBuffer, + conditions.hLLBuffer // + ); + + // + Copy( + xcaConditions.sarBuffer, + conditions.sarBuffer // + ); + + // + Copy( + xcaConditions.peakBuffer, + conditions.peakBuffer // + ); + + // + Copy( + xcaConditions.valeBuffer, + conditions.valeBuffer // + ); + + // + Copy( + xcaConditions.trendBuffer, + conditions.trendBuffer // + ); + + // + Copy( + xcaConditions.kiStateBuffer, + conditions.kiStateBuffer // + ); + + // + Copy( + xcaConditions.tkiStateBuffer, + conditions.tkiStateBuffer // + ); + + // + Copy( + xcaConditions.supportBuffer, + conditions.supportBuffer // + ); + + // + Copy( + xcaConditions.swingLowBuffer, + conditions.swingLowBuffer // + ); + + // + Copy( + xcaConditions.swingHighBuffer, + conditions.swingHighBuffer // + ); + + // + Copy( + xcaConditions.resistanceBuffer, + conditions.resistanceBuffer // + ); + + // + Copy( + xcaConditions.peakGoldenBuffer, + conditions.peakGoldenBuffer // + ); + + // + Copy( + xcaConditions.valeGoldenBuffer, + conditions.valeGoldenBuffer // + ); + + // + Copy( + xcaConditions.fiboLevel1Buffer, + conditions.fiboLevel1Buffer // + ); + + // + Copy( + xcaConditions.fiboLevel2Buffer, + conditions.fiboLevel2Buffer // + ); + + // + Copy( + xcaConditions.fiboLevel3Buffer, + conditions.fiboLevel3Buffer // + ); + + // + Copy( + xcaConditions.trendStateBuffer, + conditions.trendStateBuffer // + ); + + // + // Conditions ... + + // + conditions.isKIBullish = xcaConditions.isKIBullish; + conditions.isKIBearish = xcaConditions.isKIBearish; + conditions.isKIRejectUp = xcaConditions.isKIRejectUp; + conditions.isTKIBullish = xcaConditions.isTKIBullish; + conditions.isTKIBearish = xcaConditions.isTKIBearish; + conditions.isSarBullish = xcaConditions.isSarBullish; + conditions.isSarBearish = xcaConditions.isSarBearish; + conditions.isTKIRejectUp = xcaConditions.isTKIRejectUp; + conditions.isPeakIsPivot = xcaConditions.isPeakIsPivot; + conditions.isValeIsPivot = xcaConditions.isValeIsPivot; + conditions.isKIRejectDown = xcaConditions.isKIRejectDown; + conditions.isPeakSameLast = xcaConditions.isPeakSameLast; + conditions.isPeakOverLast = xcaConditions.isPeakOverLast; + conditions.isValeSameLast = xcaConditions.isValeSameLast; + conditions.isValeOverLast = xcaConditions.isValeOverLast; + conditions.isTrendBullish = xcaConditions.isTrendBullish; + conditions.isTrendBearish = xcaConditions.isTrendBearish; + conditions.isTKIRejectDown = xcaConditions.isTKIRejectDown; + conditions.isPeakUnderLast = xcaConditions.isPeakUnderLast; + conditions.isValeUnderLast = xcaConditions.isValeUnderLast; + conditions.isTrendRejectUp = xcaConditions.isTrendRejectUp; + conditions.isTrendRejectDown = xcaConditions.isTrendRejectDown; + conditions.isSupportSameLast = xcaConditions.isSupportSameLast; + conditions.isSupportOverLast = xcaConditions.isSupportOverLast; + conditions.isSupportUnderLast = xcaConditions.isSupportUnderLast; + conditions.isSwingLowSameLast = xcaConditions.isSwingLowSameLast; + conditions.isSwingLowOverLast = xcaConditions.isSwingLowOverLast; + conditions.isSwingLowUnderLast = xcaConditions.isSwingLowUnderLast; + conditions.isSwingHighSameLast = xcaConditions.isSwingHighSameLast; + conditions.isSwingHighOverLast = xcaConditions.isSwingHighOverLast; + conditions.isSupportSameAsVale = xcaConditions.isSupportSameAsVale; + conditions.isLastSupportBreaked = xcaConditions.isLastSupportBreaked; + conditions.isResistanceSameLast = xcaConditions.isResistanceSameLast; + conditions.isResistanceOverLast = xcaConditions.isResistanceOverLast; + conditions.isSwingHighUnderLast = xcaConditions.isSwingHighUnderLast; + conditions.isSwingLowSameAsVale = xcaConditions.isSwingLowSameAsVale; + conditions.isLastSupportRejected = xcaConditions.isLastSupportRejected; + conditions.isResistanceUnderLast = xcaConditions.isResistanceUnderLast; + conditions.isKISwitchedToBullish = xcaConditions.isKISwitchedToBullish; + conditions.isKISwitchedToBearish = xcaConditions.isKISwitchedToBearish; + conditions.isLastSwingLowBreaked = xcaConditions.isLastSwingLowBreaked; + conditions.isSwingHighSameAsPeak = xcaConditions.isSwingHighSameAsPeak; + conditions.isTKISwitchedToBullish = xcaConditions.isTKISwitchedToBullish; + conditions.isTKISwitchedToBearish = xcaConditions.isTKISwitchedToBearish; + conditions.isLastSwingLowRejected = xcaConditions.isLastSwingLowRejected; + conditions.isSarSwitchedToBullish = xcaConditions.isSarSwitchedToBullish; + conditions.isSarSwitchedToBearish = xcaConditions.isSarSwitchedToBearish; + conditions.isLastSwingHighBreaked = xcaConditions.isLastSwingHighBreaked; + conditions.isResistanceSameAsPeak = xcaConditions.isResistanceSameAsPeak; + conditions.isLastSwingHighRejected = xcaConditions.isLastSwingHighRejected; + conditions.isLastResistanceBreaked = xcaConditions.isLastResistanceBreaked; + conditions.isSupportSameAsSwingLow = xcaConditions.isSupportSameAsSwingLow; + conditions.isLastResistanceRejected = xcaConditions.isLastResistanceRejected; + conditions.isTrendSwitchedToBullish = xcaConditions.isTrendSwitchedToBullish; + conditions.isTrendSwitchedToBearish = xcaConditions.isTrendSwitchedToBearish; + conditions.isResistanceSameAsSwingHigh = xcaConditions.isResistanceSameAsSwingHigh; + + // + // XOSCS ... + + // + // Buffers ... + + // + Copy( + xocsConditions.acBuffer, + conditions.acBuffer // + ); + + // + Copy( + xocsConditions.adBuffer, + conditions.adBuffer // + ); + + // + Copy( + xocsConditions.atrBuffer, + conditions.atrBuffer // + ); + + // + Copy( + xocsConditions.cciBuffer, + conditions.cciBuffer // + ); + + // + Copy( + xocsConditions.rsiBuffer, + conditions.rsiBuffer // + ); + + // + Copy( + xocsConditions.mfiBuffer, + conditions.mfiBuffer // + ); + + // + Copy( + xocsConditions.rviBuffer, + conditions.rviBuffer // + ); + + // + Copy( + xocsConditions.adxBuffer, + conditions.adxBuffer // + ); + + // + Copy( + xocsConditions.adxpBuffer, + conditions.adxpBuffer // + ); + + // + Copy( + xocsConditions.adxnBuffer, + conditions.adxnBuffer // + ); + + // + Copy( + xocsConditions.macdBuffer, + conditions.macdBuffer // + ); + + // + Copy( + xocsConditions.momentumBuffer, + conditions.momentumBuffer // + ); + + // + Copy( + xocsConditions.rviSignalBuffer, + conditions.rviSignalBuffer // + ); + + // + Copy( + xocsConditions.macdSignalBuffer, + conditions.macdSignalBuffer // + ); + + // + Copy( + xocsConditions.stochasticBuffer, + conditions.stochasticBuffer // + ); + + // + Copy( + xocsConditions.stochasticSignalBuffer, + conditions.stochasticSignalBuffer // + ); + + // + // Values ... + + // + conditions.adxThreshold = xocsConditions.adxThreshold; + conditions.cciOBLevel = xocsConditions.cciOBLevel; + conditions.cciOSLevel = xocsConditions.cciOSLevel; + conditions.cciReversalLevel = xocsConditions.cciReversalLevel; + conditions.rsiOBLevel = xocsConditions.rsiOBLevel; + conditions.rsiOSLevel = xocsConditions.rsiOSLevel; + conditions.rsiReversalLevel = xocsConditions.rsiReversalLevel; + conditions.mfiOBLevel = xocsConditions.mfiOBLevel; + conditions.mfiOSLevel = xocsConditions.mfiOSLevel; + conditions.mfiReversalLevel = xocsConditions.mfiReversalLevel; + conditions.rviBullishLevel = xocsConditions.rviBullishLevel; + conditions.rviBearishLevel = xocsConditions.rviBearishLevel; + conditions.macdBullishLevel = xocsConditions.macdBullishLevel; + conditions.macdBearishLevel = xocsConditions.macdBearishLevel; + conditions.momentumBullishLevel = xocsConditions.momentumBullishLevel; + conditions.momentumBearishLevel = xocsConditions.momentumBearishLevel; + conditions.stochasticOBLevel = xocsConditions.stochasticOBLevel; + conditions.stochasticOSLevel = xocsConditions.stochasticOSLevel; + conditions.stochasticReversalLevel = xocsConditions.stochasticReversalLevel; + + // + // Conditions ... + + // + conditions.isCCIOB = xocsConditions.isCCIOB; + conditions.isCCIOS = xocsConditions.isCCIOS; + conditions.isRSIOB = xocsConditions.isRSIOB; + conditions.isRSIOS = xocsConditions.isRSIOS; + conditions.isMFIOB = xocsConditions.isMFIOB; + conditions.isMFIOS = xocsConditions.isMFIOS; + conditions.isACBullish = xocsConditions.isACBullish; + conditions.isACBearish = xocsConditions.isACBearish; + conditions.isACOverMax = xocsConditions.isACOverMax; + conditions.isADOverMax = xocsConditions.isADOverMax; + conditions.isACUnderMin = xocsConditions.isACUnderMin; + conditions.isADUnderMin = xocsConditions.isADUnderMin; + conditions.isADXBullish = xocsConditions.isADXBullish; + conditions.isADXBearish = xocsConditions.isADXBearish; + conditions.isCCIBullish = xocsConditions.isCCIBullish; + conditions.isCCIBearish = xocsConditions.isCCIBearish; + conditions.isRSIBullish = xocsConditions.isRSIBullish; + conditions.isRSIBearish = xocsConditions.isRSIBearish; + conditions.isMFIBullish = xocsConditions.isMFIBullish; + conditions.isMFIBearish = xocsConditions.isMFIBearish; + conditions.isRVIBullish = xocsConditions.isRVIBullish; + conditions.isRVIBearish = xocsConditions.isRVIBearish; + conditions.isATROverLast = xocsConditions.isATROverLast; + conditions.isMACDBullish = xocsConditions.isMACDBullish; + conditions.isMACDBearish = xocsConditions.isMACDBearish; + conditions.isATRUnderLast = xocsConditions.isATRUnderLast; + conditions.isADBiggerLast = xocsConditions.isADBiggerLast; + conditions.isADLesserLast = xocsConditions.isADLesserLast; + conditions.isStochasticOB = xocsConditions.isStochasticOB; + conditions.isStochasticOS = xocsConditions.isStochasticOS; + conditions.isADXBiggerLast = xocsConditions.isADXBiggerLast; + conditions.isADXLesserLast = xocsConditions.isADXLesserLast; + conditions.isRVIOverSignal = xocsConditions.isRVIOverSignal; + conditions.isRVIUnderSignal = xocsConditions.isRVIUnderSignal; + conditions.isMACDOverSignal = xocsConditions.isMACDOverSignal; + conditions.isMACDUnderSignal = xocsConditions.isMACDUnderSignal; + conditions.isMomentumBullish = xocsConditions.isMomentumBullish; + conditions.isMomentumBearish = xocsConditions.isMomentumBearish; + conditions.isADXOverThreshold = xocsConditions.isADXOverThreshold; + conditions.isDXPBiggerThanDXN = xocsConditions.isDXPBiggerThanDXN; + conditions.isDXNBiggerThanDXP = xocsConditions.isDXNBiggerThanDXP; + conditions.isCCICrossedOverOB = xocsConditions.isCCICrossedOverOB; + conditions.isCCICrossedOverOS = xocsConditions.isCCICrossedOverOS; + conditions.isRSICrossedOverOB = xocsConditions.isRSICrossedOverOB; + conditions.isRSICrossedOverOS = xocsConditions.isRSICrossedOverOS; + conditions.isMFICrossedOverOB = xocsConditions.isMFICrossedOverOB; + conditions.isMFICrossedOverOS = xocsConditions.isMFICrossedOverOS; + conditions.isADXUnderThreshold = xocsConditions.isADXUnderThreshold; + conditions.isCCICrossedUnderOB = xocsConditions.isCCICrossedUnderOB; + conditions.isCCICrossedUnderOS = xocsConditions.isCCICrossedUnderOS; + conditions.isRSICrossedUnderOB = xocsConditions.isRSICrossedUnderOB; + conditions.isRSICrossedUnderOS = xocsConditions.isRSICrossedUnderOS; + conditions.isMFICrossedUnderOB = xocsConditions.isMFICrossedUnderOB; + conditions.isMFICrossedUnderOS = xocsConditions.isMFICrossedUnderOS; + conditions.isStochasticBullish = xocsConditions.isStochasticBullish; + conditions.isStochasticBearish = xocsConditions.isStochasticBearish; + conditions.isACSwitchedToBullish = xocsConditions.isACSwitchedToBullish; + conditions.isACSwitchedToBearish = xocsConditions.isACSwitchedToBearish; + conditions.isADXSwitchedToBullish = xocsConditions.isADXSwitchedToBullish; + conditions.isADXSwitchedToBearish = xocsConditions.isADXSwitchedToBearish; + conditions.isCCISwitchedToBullish = xocsConditions.isCCISwitchedToBullish; + conditions.isCCISwitchedToBearish = xocsConditions.isCCISwitchedToBearish; + conditions.isRSISwitchedToBullish = xocsConditions.isRSISwitchedToBullish; + conditions.isRSISwitchedToBearish = xocsConditions.isRSISwitchedToBearish; + conditions.isMFISwitchedToBullish = xocsConditions.isMFISwitchedToBullish; + conditions.isMFISwitchedToBearish = xocsConditions.isMFISwitchedToBearish; + conditions.isRVISwitchedToBullish = xocsConditions.isRVISwitchedToBullish; + conditions.isRVISwitchedToBearish = xocsConditions.isRVISwitchedToBearish; + conditions.isRVICrossedOverSignal = xocsConditions.isRVICrossedOverSignal; + conditions.isStochasticOverSignal = xocsConditions.isStochasticOverSignal; + conditions.isStochasticUnderSignal = xocsConditions.isStochasticUnderSignal; + conditions.isRVICrossedUnderSignal = xocsConditions.isRVICrossedUnderSignal; + conditions.isMACDSwitchedToBullish = xocsConditions.isMACDSwitchedToBullish; + conditions.isMACDSwitchedToBearish = xocsConditions.isMACDSwitchedToBearish; + conditions.isMACDCrossedOverSignal = xocsConditions.isMACDCrossedOverSignal; + conditions.isMACDCrossedUnderSignal = xocsConditions.isMACDCrossedUnderSignal; + conditions.isStochasticCrossedOverOB = xocsConditions.isStochasticCrossedOverOB; + conditions.isStochasticCrossedOverOS = xocsConditions.isStochasticCrossedOverOS; + conditions.isStochasticCrossedUnderOB = xocsConditions.isStochasticCrossedUnderOB; + conditions.isStochasticCrossedUnderOS = xocsConditions.isStochasticCrossedUnderOS; + conditions.isMomentumSwitchedToBullish = xocsConditions.isMomentumSwitchedToBullish; + conditions.isMomentumSwitchedToBearish = xocsConditions.isMomentumSwitchedToBearish; + conditions.isStochasticSwitchedToBullish = xocsConditions.isStochasticSwitchedToBullish; + conditions.isStochasticSwitchedToBearish = xocsConditions.isStochasticSwitchedToBearish; + conditions.isStochasticCrossedOverSignal = xocsConditions.isStochasticCrossedOverSignal; + conditions.isStochasticCrossedUnderSignal = xocsConditions.isStochasticCrossedUnderSignal; + + // + // Cleanup Resource ... + + // + zBar.Clean(); + cBar.Clean(); + pBar.Clean(); + fromBar.Clean(); + + // + xcaConditions.Clean(); + xocsConditions.Clean(); + + // + Free(); + + // + return result; + } + + // + // Protected ... + protected: + // + // Private ... + private: + // + // Props ... + + // + string mSymbol; // Trading Symbol + ENUM_TIMEFRAMES mPeriod; // Trading Period + + // + // Inputs ... + XCAEAInputs mInputs; + + // + // Handlers ... + int acHandler; + int adHandler; + int adxHandler; + int atrHandler; + int cciHandler; + int rsiHandler; + int mfiHandler; + int rviHandler; + int macdHandler; + int momentumHandler; + int stochasticHandler; +}; + +// \ No newline at end of file diff --git a/BKPS/14040203/XCAEA/Libraries/xcaea.signaller.lib.mq5 b/BKPS/14040203/XCAEA/Libraries/xcaea.signaller.lib.mq5 new file mode 100644 index 0000000..1230ed7 --- /dev/null +++ b/BKPS/14040203/XCAEA/Libraries/xcaea.signaller.lib.mq5 @@ -0,0 +1,1177 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Indicator +// ------------------------------------------------- +// Name: XCAEASignaller Lib +// Description: Library for XCAEA Signaller ... +// +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +////////////////////////////////////////////////////// +// +// Global Properties ... +#property library +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://saherelm.ir" +#property version "1.00" +#property description "SaherElm Library for XCAEA Signaller" +#property strict + +// +// Imports ... +#include "../../Libraries/x-saherelm.common.lib.mq5" +#include "../../Libraries/x-saherelm.x-poi.lib.mq5" +#include "../../Libraries/x-saherelm.x-trade.lib.mq5" +#include "../Classes/xcaea.x-poi.detector.class.mq5" +#include "../Helpers/xcaea.helper.mq5" + +// +// Enumeration ... + +// +// Guard Actions ... +enum ENUM_GUARD_ACTIONS +{ + X_GUARD_ACTION_NONE, // Nothing to Do + X_GUARD_ACTION_CLOSE, // Close Specified Position + X_GUARD_ACTION_CLOSE_ALL, // Close All Positions + X_GUARD_ACTION_CLOSE_LONGS, // Close All Long Positions + X_GUARD_ACTION_CLOSE_SHORTS, // Close All Short Position + X_GUARD_ACTION_PARTIAL_CLOSE, // Partial Close Specified Position + X_GUARD_ACTION_TRAIL_STOP, // Trail Stop of Specified Position + X_GUARD_ACTION_TRAIL_TARGET, // Trail Target of Specified Position + X_GUARD_ACTION_HEDGE, // Hedge Specified Positions +}; + +// +// Definitions ... + +// +// Conditions Struct ... +struct XCAEAStrategyConditions +{ + // + // Props ... + + // + string symbol; + ENUM_TIMEFRAMES period; + + // + // Setup Props ... + + // + double sl; + double tp; + double pivot; + double point; + string provider; + double targets[]; + + // + datetime time; + datetime setupTime; + datetime triggerTime; + + // + XBoxZone signalBox; + ENUM_X_DIRECTION dir; + ENUM_X_POSITION_TYPES type; + XCAEAConditions conditions; + + // + // Constructor ... + XCAEAStrategyConditions() + { + Clean(); + } + + // + // Tools ... + + /** + * Cleaning Up ... + */ + void Clean() + { + // + sl = 0; + tp = 0; + pivot = 0; + point = 0; + + // + symbol = NULL; + period = NULL; + provider = NULL; + + // + time = NULL; + setupTime = NULL; + triggerTime = NULL; + + // + Clean(targets); + + // + signalBox.Clean(); + conditions.Clean(); + + // + dir = X_DIRECTION_NONE; + type = X_POSITION_TYPE_NONE; + + // + } + + // + // Signalling ... + + /** + * Validate ... + * + * @return ( bool ) + */ + bool IsValid() + { + // + bool result = false; + + // + result = IsSpecifiedValid(symbol) && + IsSpecifiedValid(period) && + IsSpecifiedValid(time); + + // + return result; + } + + /** + * Check Conditions Has Valid Bullish Signal ... + * + * @return ( bool ) + */ + bool HasBullishSignal() + { + // + bool result = false; + + // + result = + (sl > 0 || + tp > 0) && + IsValid() && + HasDirection(dir); + if (!result) + { + return result; + } + + // + result = + IsBullish(dir); + + // + return result; + } + + /** + * Check Conditions Has Valid Bearish Signal ... + * + * @return ( bool ) + */ + bool HasBearishSignal() + { + // + bool result = false; + + // + result = + (sl > 0 || + tp > 0) && + IsValid() && + HasDirection(dir); + if (!result) + { + return result; + } + + // + result = + IsBearish(dir); + + // + return result; + } + + // + // Setting Up and Triggering Up ... + + /** + * Check Condition is Setting Up ... + * + * @param dir: ENUM_X_DIRECTION member, Setting Up Direction ... + * + * @return ( bool ) + */ + bool IsSetuped() + { + // + bool result = false; + + // + result = IsValid(setupTime) && + HasDirection(dir); + if (!result) + { + return result; + } + + // + return result; + } + + /** + * Calculate Setup Age ... + * + * @return ( int ) + */ + int GetSetupAge() + { + // + int result = 0; + + // + if (!IsSetuped()) + { + return result; + } + + // + result = (int)(TimeCurrent() - setupTime) / PeriodSeconds(period); + + // + return result; + } + + /** + * Detect How we Can Trigger Signal ... + * + * @return ( bool ) + */ + bool CanTrigger() + { + // + bool result = false; + + // + result = + // + sl > 0 && + IsValid(symbol) && + IsValid(period) && + IsValid(triggerTime) && + type != X_POSITION_TYPE_ALL && + type != X_POSITION_TYPE_NONE + // + ; + + // + return result; + } + + // +}; + +// +// Model a Guard Action ... +struct XCAEAGuard +{ + // + // Props ... + ENUM_GUARD_ACTIONS action; + datetime time; + + // + string symbol; + string provider; + + // + // Specified Position ... + ulong ticket; + + // + // Partial Close ... + double volumeMultiplier; + + // + // SL Trial ... + double sl; + + // + // TP Trial ... + double tp; + + // + // Constructor ... + XCAEAGuard() + { + Clean(); + } + + // + // Tools ... + + /** + * Cleanup ... + */ + void Clean() + { + // + time = NULL; + action = X_GUARD_ACTION_NONE; + + // + symbol = NULL; + provider = NULL; + + // + ticket = 0; + + // + volumeMultiplier = 0; + + // + sl = 0; + tp = 0; + + // + ZeroMemory(this); + } + + /** + * Validate ... + * + * @return ( bool ) + */ + bool IsValid() + { + // + bool result = false; + + // + result = + // + IsValid(time) && + IsValid(symbol) && + IsValid(provider) && + action != X_GUARD_ACTION_NONE + // + ; + if (!result) + { + return result; + } + + // + // Validate Model Based On Specified Guard Actions ... + + // + return result; + } +}; + +/** + * Add Guard to Collection ... + * + * @param guard: XCAEAGuard instance ... + * @param guards: XCAEAGuard instance Collection ... + * + * @return ( int ) + */ +int AddGuard( + XCAEAGuard &guard, + XCAEAGuard &guards[] // +) +{ + // + int result = 0; + + // + if (!guard.IsValid()) + { + return result; + } + + // + AddRef( + guard, + guards // + ); + + // + result = ArraySize(guards); + + // + return result; +} + +// +bool DetectXCAEAConditions( + XBoxZone &boxes[], + XCAEAConditions &conditions, + XBoxZone &pivotBox, + XBoxZone &box, + double &additionalSL, + ENUM_X_DIRECTION &dir, + XCXCAEAHelper *helper, + int barIndex = 0, + int loopback = 10 // +) +{ + // + bool result = false; + + // + int idx = -1; + int count = 0; + bool has = false; + + // + box.Clean(); + additionalSL = 0; + conditions.Clean(); + dir = X_DIRECTION_NONE; + + // + if (barIndex < 0) + { + barIndex = 0; + } + loopback = NormalizeInt(loopback, 5); + + // + string symbol = helper.GetSymbol(); + ENUM_TIMEFRAMES period = helper.GetPeriod(); + double points = GetPoints(symbol); + + // + XCAEAConditions pConditions; + result = helper.GetConditions( + conditions, + barIndex, + loopback // + ); + result = result && + helper.GetConditions( + pConditions, + barIndex + 1, + loopback // + ); + if (!result) + { + // + conditions.Clean(); + pConditions.Clean(); + + // + return result; + } + + // + int zIDX = barIndex; + int cIDX = zIDX + 1; + int pIDX = cIDX + 1; + int p2IDX = pIDX + 1; + int p3IDX = p2IDX + 1; + int p4IDX = p3IDX + 1; + + // + // Reading Parameters ... + + // + // KI ... + + // + double cKI = conditions.kiBuffer[cIDX]; + double pKI = conditions.kiBuffer[pIDX]; + double p2KI = conditions.kiBuffer[p2IDX]; + + // + double cKIState = conditions.kiStateBuffer[cIDX]; + double pKIState = conditions.kiStateBuffer[pIDX]; + double p2KIState = conditions.kiStateBuffer[p2IDX]; + + // + // TKI ... + + // + double cTKI = conditions.tkiBuffer[cIDX]; + double pTKI = conditions.tkiBuffer[pIDX]; + double p2TKI = conditions.tkiBuffer[p2IDX]; + + // + double cTKIState = conditions.tkiStateBuffer[cIDX]; + double pTKIState = conditions.tkiStateBuffer[pIDX]; + double p2TKIState = conditions.tkiStateBuffer[p2IDX]; + + // + // TREND ... + + // + double cTrend = conditions.trendBuffer[cIDX]; + double pTrend = conditions.trendBuffer[pIDX]; + double p2Trend = conditions.trendBuffer[p2IDX]; + + // + double ctrendState = conditions.trendStateBuffer[cIDX]; + double ptrendState = conditions.trendStateBuffer[pIDX]; + double p2trendState = conditions.trendStateBuffer[p2IDX]; + + // + // SWING Low ... + double cSWL = conditions.swingLowBuffer[cIDX]; + double pSWL = conditions.swingLowBuffer[pIDX]; + double p2SWL = conditions.swingLowBuffer[p2IDX]; + + // + // SWING High ... + double cSWH = conditions.swingHighBuffer[cIDX]; + double pSWH = conditions.swingHighBuffer[pIDX]; + double p2SWH = conditions.swingHighBuffer[p2IDX]; + + // + // PEAK ... + double zPeak = conditions.peakBuffer[zIDX]; + double cPeak = conditions.peakBuffer[cIDX]; + double pPeak = conditions.peakBuffer[pIDX]; + double p2Peak = conditions.peakBuffer[p2IDX]; + double p3Peak = conditions.peakBuffer[p3IDX]; + + // + // VALE ... + double zVale = conditions.valeBuffer[zIDX]; + double cVale = conditions.valeBuffer[cIDX]; + double pVale = conditions.valeBuffer[pIDX]; + double p2Vale = conditions.valeBuffer[p2IDX]; + double p3Vale = conditions.valeBuffer[p3IDX]; + + // + // RSI ... + double zRSI = conditions.rsiBuffer[zIDX]; + double cRSI = conditions.rsiBuffer[cIDX]; + double pRSI = conditions.rsiBuffer[pIDX]; + double p2RSI = conditions.rsiBuffer[p2IDX]; + double p3RSI = conditions.rsiBuffer[p3IDX]; + + // + // CCI ... + double zCCI = conditions.cciBuffer[zIDX]; + double cCCI = conditions.cciBuffer[cIDX]; + double pCCI = conditions.cciBuffer[pIDX]; + double p2CCI = conditions.cciBuffer[p2IDX]; + double p3CCI = conditions.cciBuffer[p3IDX]; + + // + // RVI ... + + // + double zRVI = conditions.rviBuffer[zIDX]; + double cRVI = conditions.rviBuffer[cIDX]; + double pRVI = conditions.rviBuffer[pIDX]; + double p2RVI = conditions.rviBuffer[p2IDX]; + double p3RVI = conditions.rviBuffer[p3IDX]; + + // + double zRVISignal = conditions.rviSignalBuffer[zIDX]; + double cRVISignal = conditions.rviSignalBuffer[cIDX]; + double pRVISignal = conditions.rviSignalBuffer[pIDX]; + double p2RVISignal = conditions.rviSignalBuffer[p2IDX]; + double p3RVISignal = conditions.rviSignalBuffer[p3IDX]; + + // + // Reading Bars ... + + // + XOHCL zBar; + XOHCL cBar; + XOHCL pBar; + XOHCL p2Bar; + XOHCL p3Bar; + XOHCL p4Bar; + result = zBar.Init( + symbol, + period, + zIDX // + ); + result = + result && + zBar.GetPreviousBar(cBar); + result = + result && + cBar.GetPreviousBar(pBar); + result = + result && + pBar.GetPreviousBar(p2Bar); + result = + result && + p2Bar.GetPreviousBar(p3Bar); + result = + result && + p3Bar.GetPreviousBar(p4Bar); + if (!result) + { + // + zBar.Clean(); + cBar.Clean(); + pBar.Clean(); + p2Bar.Clean(); + p3Bar.Clean(); + p4Bar.Clean(); + + // + box.Clean(); + conditions.Clean(); + pConditions.Clean(); + + // + return result; + } + + // + // Bars Conditions ... + + // + ENUM_X_DIRECTION cBarDir; + + // + // Hammer ... + bool isCBarHammer = helper + .barAnalyser + .IsHammer( + cBar, + cBarDir // + ); + bool isCBarBullishHammer = + isCBarHammer && + IsBullish(cBarDir); + bool isCBarBearishHammer = + isCBarHammer && + IsBearish(cBarDir); + + // + // Rejected ... + bool isCBarRejected = helper + .barAnalyser + .IsRejected( + cBar, + cBarDir, + false, // Force Type ... + true // Force Fibo Pressure ... + ); + bool isCBarBullishRejected = + isCBarRejected && + IsBullish(cBarDir); + bool isCBarBearishRejected = + isCBarRejected && + IsBearish(cBarDir); + + // + // Engulfed ... + bool isCBarEngulfed = helper + .barAnalyser + .IsEngulfed( + cBar, + cBarDir // + ); + bool isCBarBullishEngulfed = + isCBarEngulfed && + IsBullish(cBarDir); + bool isCBarBearishEngulfed = + isCBarEngulfed && + IsBearish(cBarDir); + + // + // Momentum ... + bool isCBarMomentum = helper + .barAnalyser + .IsMomentum( + cBar, + cBarDir, + 1 // + ); + bool isCBarBullishMomentum = + isCBarMomentum && + IsBullish(cBarDir); + bool isCBarBearishMomentum = + isCBarMomentum && + IsBearish(cBarDir); + + // + // Bar Sumarise ... + + // + bool isCBarValidForBullish = + (isCBarBullishHammer || + isCBarBullishRejected || + isCBarBullishMomentum || + isCBarBullishEngulfed); + + // + bool isCBarValidForBearish = + (isCBarBearishHammer || + isCBarBearishRejected || + isCBarBearishMomentum || + isCBarBearishEngulfed); + + // + // Score ... + + // + double bullishScore = 0; + double bearishScore = 0; + conditions.GenerateScore( + bullishScore, + bearishScore // + ); + + // + bool isScoreBullish = + bullishScore > bearishScore; + + // + bool isScoreBearish = + bearishScore > bullishScore; + + // + string summary = + conditions + .GenerateSummary(); + + // + // Conditions ... + + // + bool isRSIBullish = + zRSI >= cRSI && + cRSI > pRSI; + bool isRSIBearish = + zRSI <= cRSI && + cRSI < pRSI; + + // + bool isCCIBullish = + zCCI >= cCCI && + cCCI > pCCI && + (zCCI > conditions.cciOSLevel || + cCCI > conditions.cciOSLevel); + bool isCCIBearish = + zCCI >= cCCI && + cCCI > pCCI && + (zCCI < conditions.cciOBLevel || + cCCI < conditions.cciOBLevel); + + // + // Detect Selected Box ... + double providedSL = 0; + bool isBoxFVG = false; + bool hasPivotBox = false; + bool isBoxPeakVale = false; + bool isBoxRejected = false; + bool isBoxActivated = false; + bool isBoxFullSifeRejected = false; + bool hasBoxes = HasChild(boxes); + if (hasBoxes) + { + // + // Detect Selected Boxes ... + XBoxZone tmp[]; + Copy( + boxes, + tmp // + ); + while (HasChild(tmp)) + { + // + idx = GetYoungest(tmp); + has = IsValidIndex(idx); + if (!has) + { + break; + } + + // + XBoxZone iBox; + iBox = tmp[idx]; + ArrayRemove( + tmp, + idx, + 1 // + ); + + // + // Check Selected Box not RSI or CCI ... + isBoxFVG = Contains( + "XCA_FVG", + iBox.type // + ); + isBoxPeakVale = + Contains( + "XCA_PEAKSWHRES", + iBox.type // + ) || + Contains( + "XCA_VALESWLSUP", + iBox.type // + ); + has = isBoxFVG || + isBoxPeakVale; + if (!has) + { + // + iBox.Clean(); + + // + continue; + } + + // + bool isBullish = iBox.IsBullish(); + bool isBearish = iBox.IsBearish(); + + // + double rejectedCheckPrice = + isBullish + ? iBox.upper + : iBox.lower; + double rejectedFullCheckPrice = + isBullish + ? iBox.lower + : iBox.upper; + + // + // Check Box Selecting Senarios ... + + // + // Selecting Rejected Boxes ... + isBoxRejected = cBar.IsRejected( + rejectedCheckPrice, + iBox.dir, + false, + false // + ); + + // + // Selecting Rejected Boxes ... + isBoxFullSifeRejected = cBar.IsRejected( + rejectedFullCheckPrice, + iBox.dir, + false, + false // + ); + + // + // Selecting Activation Boxes ... + + // + bool isBullishActivated = + isBullish && + cBar.IsBullish() && + cBar.GetUp() > rejectedCheckPrice && + cBar.GetDown() < rejectedCheckPrice; + + // + bool isBearishActivated = + isBearish && + cBar.IsBearish() && + cBar.GetUp() > rejectedCheckPrice && + cBar.GetDown() < rejectedCheckPrice; + + // + isBoxActivated = isBullishActivated || + isBearishActivated; + + // + // Detect Box is Selected or not ... + has = + isBoxRejected || + isBoxActivated || + isBoxFullSifeRejected; + if (has) + { + // + pivotBox = iBox; + + // + iBox.Clean(); + break; + } + + // + iBox.Clean(); + } + + // + Clean(tmp); + } + + // + // Force Conditions to Have Selected Box ... + hasPivotBox = hasBoxes && + pivotBox.IsValid(); + if (hasPivotBox) + { + // + pivotBox.to = TimeCurrent(); + + // + // Draw Pivot Box Here ... + if (isBoxPeakVale) + { + // + XCBoxObject *iObj; + has = helper.poiDrawer.DrawBox( + pivotBox, + iObj // + ); + if (has) + { + // + iObj.BoxWidth(5); + iObj.BoxColor(clrDodgerBlue); + Print("Draw Pivot Box ..."); + } + } + } + + // + // If all Conditions required Boxes ... + // if (!result) + // { + // // + // zBar.Clean(); + // cBar.Clean(); + // pBar.Clean(); + // p2Bar.Clean(); + // p3Bar.Clean(); + // p4Bar.Clean(); + + // // + // box.Clean(); + // pivotBox.Clean(); + // conditions.Clean(); + + // // + // return result; + // } + + // + // Signaller Summarization ... + + // + // Cond1 Act Using PEAK VALE Box Activation or Rejection ... + + // + bool isCond1Bullish = + // + hasPivotBox && + isBoxPeakVale && + isScoreBullish && + pivotBox.IsBullish() && + (conditions.isValeUnderLast || + (conditions.isValeSameLast && + pConditions.isValeUnderLast)) && + conditions.isRSICrossedOverOS && + conditions.isCCICrossedOverOS + // + ; + + // + bool isCond1Bearish = + // + hasPivotBox && + isBoxPeakVale && + isScoreBearish && + pivotBox.IsBearish() && + (conditions.isPeakOverLast || + (conditions.isPeakSameLast && + pConditions.isPeakOverLast)) && + conditions.isRSICrossedUnderOB && + conditions.isCCICrossedUnderOB + // + ; + + // + bool isCond1 = isCond1Bullish || + isCond1Bearish; + if (isCond1) + { + // + providedSL = + isCond1Bullish + ? MathMin(pBar.low, pivotBox.lower) + : MathMax(pBar.high, pivotBox.upper); + + // + additionalSL = 0.5 * conditions.atrBuffer[cIDX]; + + // + Print("Cond1"); + } + + // + // Cond2 Act Using Box Rejection ... + + // + bool isCond2Bullish = + // + false + // + ; + + // + bool isCond2Bearish = + // + false + // + ; + + // + bool isCond2 = isCond2Bullish || + isCond2Bearish; + if (isCond2) + { + // + providedSL = + isCond1Bullish + ? MathMin(pBar.low, pivotBox.lower) + : MathMax(pBar.high, pivotBox.upper); + + // + Print("Cond2"); + } + + // + // Cond3 Act Using CCi Peaks and Vales ... + + // + bool isCond3Bullish = false; + + // + bool isCond3Bearish = false; + + // + bool isCond3 = isCond3Bullish || + isCond3Bearish; + if (isCond3) + { + // + + // + Print("Cond3"); + } + + // + // Summarise Conditions ... + + // + bool isBullish = + // + isCond1Bullish || + isCond2Bullish || + isCond3Bullish; + // + ; + + // + bool isBearish = + // + isCond1Bearish || + isCond2Bearish || + isCond3Bearish + // + ; + + // + result = isBullish || + isBearish; + if (result) + { + // + dir = + isBullish + ? X_DIRECTION_BULLISH + : X_DIRECTION_BEARISH; + + // + double entry = GetEntry( + conditions.symbol, + dir // + ); + + // + double sl = + providedSL > 0 + ? providedSL + : isBullish + ? pivotBox.lower + : pivotBox.upper; + + // + box.dir = dir; + box.symbol = conditions.symbol; + box.period = conditions.period; + + // + box.upper = + isBullish + ? entry + : sl; + + // + box.lower = + isBullish + ? sl + : entry; + + // + box.to = zBar.time; + box.from = p4Bar.time; + + // + box.type = "XCASignal"; + } + + // + result = box.IsValid() && + HasDirection(dir); + + // + // Cleanup Resources ... + + // + if (!result) + { + // + box.Clean(); + pivotBox.Clean(); + conditions.Clean(); + } + + // + zBar.Clean(); + cBar.Clean(); + pBar.Clean(); + p2Bar.Clean(); + p3Bar.Clean(); + p4Bar.Clean(); + pConditions.Clean(); + + // + return result; +} + +// \ No newline at end of file diff --git a/BKPS/14040203/XCAEA/Signals/xcaea.signaller.class.mq5 b/BKPS/14040203/XCAEA/Signals/xcaea.signaller.class.mq5 new file mode 100644 index 0000000..c0bce11 --- /dev/null +++ b/BKPS/14040203/XCAEA/Signals/xcaea.signaller.class.mq5 @@ -0,0 +1,876 @@ +/////////////////////////////////////////////////////// +// +// SaherElm IT Center MQL5 Indicator +// ------------------------------------------------- +// Name: XCXCAEASignaller ... +// Description: Class for XCAEA Signaller ... +// +// +// Maintainer: +// ------------ +// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com) +// +////////////////////////////////////////////////////// +// +// Global Properties ... +#property library +#property copyright "Copyright 2023, SaherElm IT Center" +#property link "https://saherelm.ir" +#property version "1.00" +#property description "SaherElm Class for XCAEA Signaller" +#property strict + +// +// Imports ... +#include "../../Classes/x-saherelm.base.class.mq5" +#include "../../Classes/x-saherelm.x-cobject.class.mq5" +#include "../Classes/xcaea.x-poi.detector.class.mq5" +#include "../Classes/xcaea.x-poi.drawer.class.mq5" +#include "../Helpers/xcaea.helper.mq5" +#include "../Libraries/xcaea.signaller.lib.mq5" + +// +// Definitions ... + +class XCXCAEASignaller : XCBase +{ + // + // Public ... + public: + // + // Props ... + bool useGuards; + XCAEAInputs inputs; + XBarTracker barTraker; + XCXCAEAHelper *helper; + XCXCAEAPOIDrawer *drawer; + bool continuesRFTillTarget; + XBoxZone unAvailableBoxes[]; + XCXCAEAPOIDetector *detector; + XCAEAStrategyConditions mConditions; + XCAEAStrategyConditions mConditionsCollection[]; + + // + // Constructor ... + XCXCAEASignaller( + string _symbol, + ENUM_TIMEFRAMES _period // + ) + { + // + symbol = _symbol; + period = _period; + + // + Init(); + } + + // + // Deconstructor ... + ~XCXCAEASignaller() + { + DeInit(); + } + + // + // Properties ... + + string GetSymbol() + { + return symbol; + } + + ENUM_TIMEFRAMES GetPeriod() + { + return period; + } + + // + // Signaller Tools ... + + /** + * Detect Setup Conditions based on Signalling ... + * + * @param maxAllowedSLDistanceInPoint: int, Max Allowed SL Distance in Points (if Bigger thn Zero Provided) ... + * + * @return ( bool ) + */ + bool DetectSignalSetup( + double tpReward = 3, + double maxAllowedSLDistanceInPoint = 100 // + ) + { + // + bool result = false; + + // + // Check Bar Processing ... + if (!barTraker.CanProcessBar()) + { + return result; + } + + // + bool isBullish = false; + bool isBearish = false; + + // + int zIndex = 0; + int cIndex = zIndex + 1; + int pIndex = cIndex + 1; + int ppIndex = pIndex + 1; + + // + int loopback = 10; + + // + int idx = -1; + int count = 0; + bool has = false; + + // + double ask = GetAsk(symbol); + double bid = GetBid(symbol); + datetime cTime = TimeCurrent(); + double points = GetPoints(symbol); + + // + XOHCL zBar; + XOHCL cBar; + XOHCL pBar; + XOHCL pPBar; + result = zBar.Init( + symbol, + period, + zIndex // + ); + result = + result && + zBar.GetPreviousBar(cBar); + result = + result && + cBar.GetPreviousBar(pBar); + result = + result && + pBar.GetPreviousBar(pPBar); + if (!result) + { + // + zBar.Clean(); + cBar.Clean(); + pBar.Clean(); + pPBar.Clean(); + + // + return result; + } + + // + // Setup Conditions ... + XBoxZone boxes[]; + XBoxZone pivotBox; + XBoxZone signalBox; + double additionalSL = 0; + XBoxZone bullishBoxes[]; + XBoxZone bearishBoxes[]; + bool hasSignalBox = false; + XCAEAConditions conditions; + ENUM_X_DIRECTION signalBoxDir = X_DIRECTION_NONE; + + // + // Detecting Pivots ... + detector.Update( + zIndex // + ); + + // + // Validate Pivots ... + detector.Validate( + unAvailableBoxes, + zIndex // + ); + + // + // Draw Founded Pivots ... + drawer.Draw(cTime); + + // + // Retrieve Valid Boxes ... + + // + // Bullish ... + int bullishBoxesCount = + detector + .FillBullishBoxes(bullishBoxes); + + // + // Bearish ... + int bearishBoxesCount = + detector + .FillBearishBoxes(bearishBoxes); + + // + Copy( + bullishBoxes, + boxes, + false // + ); + Copy( + bearishBoxes, + boxes, + false // + ); + int boxesCount = ArraySize(boxes); + bool hasBoxes = IsValidSize(boxesCount); + + // + // Filter UnAvailable Boxes ... + if (hasBoxes) + { + // + // Remove UnAvailable Boxes ... + has = HasChild(unAvailableBoxes); + if (has) + { + // + count = ArraySize(unAvailableBoxes); + for (int i = 0; i < count; i++) + { + // + XBoxZone iBox = unAvailableBoxes[i]; + + // + has = FindBoxIndex( + idx, + iBox, + boxes // + ); + if (has) + { + // + ArrayRemove( + boxes, + idx, + 1 // + ); + } + } + } + + // + hasBoxes = HasChild(boxes); + boxesCount = ArraySize(boxes); + } + + // + // + // + + // + if (hasBoxes) + { + // + // Detect Sinal Box ... + hasSignalBox = DetectXCAEAConditions( + boxes, + conditions, + pivotBox, + signalBox, + additionalSL, + signalBoxDir, + helper, + zIndex, + loopback // + ); + + // + // Make Pivot Box UnAvailable ... + if (pivotBox.IsValid()) + { + // + AddRef( + pivotBox, + unAvailableBoxes // + ); + } + } + + // + isBullish = hasSignalBox && + IsBullish(signalBoxDir); + + // + isBearish = hasSignalBox && + IsBearish(signalBoxDir); + + // + result = isBullish || + isBearish; + if (result) + { + // + // Do What we Want ... + barTraker.Waits(); + + // + // Draw Signal Box ... + XCBoxObject *iObj; + bool isCreated = helper.poiDrawer.DrawBox( + signalBox, + iObj // + ); + if (isCreated) + { + // + mObjects.Add(iObj); + ZeroMemory(iObj); + + // + Print("Signal Box ..."); + } + + // + // Prepare Conditions ... + mConditions.symbol = symbol; + mConditions.period = period; + + // + double spread = GetSpread(symbol); + + // + double entry = + isBullish + ? signalBox.upper + : signalBox.lower; + + // + double sl = + isBullish + ? signalBox.lower + : signalBox.upper; + if (additionalSL > 0) + { + // + sl = + isBullish + ? sl - additionalSL + : sl + additionalSL; + } + + // + double risk = + isBullish + ? entry - sl + : sl - entry; + risk += spread; + if (risk >= maxAllowedSLDistanceInPoint * points) + { + // + // Fix Risk in Big Distances ... + double hh5 = zBar.FindHighest(5, MODE_HIGH); + double ll5 = zBar.FindLowest(5, MODE_LOW); + + // + double hhll5Delta = hh5 - ll5; + double riskDelta = hhll5Delta / 2; + risk = riskDelta; + } + + // + double rewardTP = risk * tpReward; + + // + double tp = + isBullish + ? entry + rewardTP + : entry - rewardTP; + + // + // Filling ... + mConditions.sl = sl; + mConditions.tp = tp; + mConditions.pivot = + isBullish + ? sl + : entry; + mConditions.point = + isBullish + ? entry + : sl; + mConditions.dir = signalBoxDir; + mConditions.provider = "XCAEA"; + mConditions.signalBox = signalBox; + mConditions.setupTime = zBar.time; + mConditions.conditions = conditions; + + // + // Select RF Rewards ... + if (continuesRFTillTarget) + { + // + double rfReward = 1; + while (rfReward < tpReward) + { + // + double rewardRF = risk * rfReward; + double rfTP = + isBullish + ? entry + rewardRF + : entry - rewardRF; + + // + Add( + rfTP, + mConditions.targets // + ); + + // + rfReward++; + } + } + else + { + // + double rfReward = 1; + + // + double rewardRF = risk * rfReward; + double rfTP = + isBullish + ? entry + rewardRF + : entry - rewardRF; + + // + Add( + rfTP, + mConditions.targets // + ); + } + } + + // + // Cleanup Resource ... + + // + Clean(boxes); + Clean(bullishBoxes); + Clean(bearishBoxes); + + // + zBar.Clean(); + cBar.Clean(); + pBar.Clean(); + pPBar.Clean(); + + // + pivotBox.Clean(); + signalBox.Clean(); + conditions.Clean(); + + // + return result; + } + + /** + * Detect Trigger Conditions for Specified Signal ... + * + * @param conditions: XCAEAStrategyConditions instance Reference, Specified Signal Conditions ... + * @param maxAllowedSetupAge: specified Setup Age for Expiration (if bigger than Zero) ... + * + * @return ( bool ) + */ + bool DetectSignalTrigger( + XCAEAStrategyConditions &conditions, + int maxAllowedSetupAge = 60 // + ) + { + // + bool result = false; + + // + result = conditions.IsSetuped(); + if (!result) + { + return result; + } + + // + datetime setupTime = conditions.setupTime; + ENUM_X_DIRECTION setupDir = conditions.dir; + + // + bool isBullish = IsBullish(setupDir); + bool isBearish = IsBearish(setupDir); + + // + int zIndex = 0; + int cIndex = zIndex + 1; + int pIndex = cIndex + 1; + int ppIndex = pIndex + 1; + + // + int loopback = 10; + + // + double ask = GetAsk(symbol); + double bid = GetBid(symbol); + datetime cTime = TimeCurrent(); + double points = GetPoints(symbol); + + // + // Check Signal Validation ... + // IMPORTANT: since all Validations done in SetUp Process ... + // here we only Execute Signal ... + + // + result = isBullish || + isBearish; + + // + if (result) + { + // + conditions.triggerTime = cTime; + conditions.type = isBullish + ? X_POSITION_TYPE_LONG + : X_POSITION_TYPE_SHORT; + + // + } + + // + // Cleanup ... + + // + return result; + } + + /** + * Detect Guards bsed on Signalling Class ... + * + * @param guards: XCAEAGuard instance Collection, Holds Provided Guards ... + * @param positions: XPosition instance Collection, Provides Signalling Based Positions for Apply Guards on them ... + * @param provider: X121SMCStrategySignalProviderData instance Reference, Specified Data for Cycles ... + * + * @return ( bool ) + */ + bool DetectGuards( + XCAEAGuard &guards[], + const XPosition &positions[] // + ) + { + // + bool result = false; + + // + return result; + } + + /** + * Add Conditions to Conditions Collection if not Exists ... + * + * @param maxAllowed: int, Specified Max Allowed Holding Conditions ... + * + * @return ( int ) + */ + int AddConditionsIfNotExists( + int maxAllowed = 10 // + ) + { + // + int result = 0; + + // + bool isSetuped = IsValid(mConditions.setupTime) && + HasDirection(mConditions.dir); + if (!isSetuped) + { + return result; + } + + // + int count = ArraySize(mConditionsCollection); + if (IsValidSize(count)) + { + // + // Copy Original Items ... + XCAEAStrategyConditions tmpItems[]; + Copy( + mConditionsCollection, + tmpItems // + ); + + // + // Prese Item Data ... + bool isBullish = IsBullish(mConditions.dir); + + // + for (int i = 0; i < count; i++) + { + // + XCAEAStrategyConditions iItem = tmpItems[i]; + + // + bool canRemove = mConditions.dir == iItem.dir && + mConditions.pivot == iItem.pivot; + if (canRemove) + { + // + ArrayRemove( + mConditionsCollection, + i, + 1 // + ); + } + } + + // + Clean(tmpItems); + } + + // + AddRef( + mConditions, + mConditionsCollection // + ); + + // + // Remove Olds ... + CleanupArray( + mConditionsCollection, + maxAllowed // + ); + + // + result = ArraySize(mConditionsCollection); + + // + return result; + } + + // + // Protected ... + protected: + // + + // + // Private ... + private: + // + // Props ... + string symbol; + ENUM_TIMEFRAMES period; + CArrayObj mObjects; + CArrayObj mBarObjects; + + /** + * Initialize ... + */ + void Init() + { + // + useGuards = false; + continuesRFTillTarget = true; + + // + barTraker.Init( + symbol, + period // + ); + + // + inputs.Default(); + + // + // Configure Indicators ... + + // + // XCC ... + inputs.ccInputs.showCandles = true; + + // + // XCT ... + inputs.ctInputs.showCandleTime = true; + + // + // XCA ... + + // + inputs.caInputs.supResSmoothingLength = 7; + inputs.caInputs.supResSmoothingMode = X_MA_MODE_NONE; + + // + inputs.caInputs.showKI = true; + inputs.caInputs.showTKI = true; + inputs.caInputs.showSar = true; + inputs.caInputs.showTrend = true; + inputs.caInputs.showSwings = false; + inputs.caInputs.showLongCycle = false; + inputs.caInputs.showHindCycle = false; + inputs.caInputs.showFiboLevel1 = false; + inputs.caInputs.showFiboLevel2 = false; + inputs.caInputs.showFiboLevel3 = false; + inputs.caInputs.showShortCycle = false; + inputs.caInputs.showMediumCycle = false; + inputs.caInputs.showPeaksAndVales = true; + inputs.caInputs.showPeakAndValeGolden = false; + inputs.caInputs.showSupportAndResistance = false; + + // + // XOSCS ... + // inputs.oscsInputs.rsiLength = 5; + // inputs.oscsInputs.cciLength = 5; + // inputs.oscsInputs.mfiLength = 5; + // inputs.oscsInputs.rviLength = 5; + + // + // Oscillators Views ... + inputs.showCCI = false; + inputs.showRSI = false; + inputs.showMFI = false; + inputs.showRVI = false; + inputs.showADX = false; + inputs.showMACD = false; + + // + // XCAEA Helper ... + helper = new XCXCAEAHelper(); + helper.Init( + symbol, + period, + inputs // + ); + + // + // Initialize and Configure Detector ... + detector = new XCXCAEAPOIDetector(helper); + + // + detector.detectSWHPivot = false; + detector.detectSWLPivot = false; + detector.detectPeakPivot = false; + detector.detectValePivot = false; + detector.detectRSIPeakPivot = true; + detector.detectRSIValePivot = true; + detector.detectCCIPeakPivot = true; + detector.detectCCIValePivot = true; + detector.detectKIBullishPivot = false; + detector.detectKIBearishPivot = false; + detector.detectFVGBullishPivot = true; + detector.detectFVGBearishPivot = true; + detector.detectPeakSWHResPivot = true; + detector.detectValeSWLSupPivot = true; + detector.detectTKIBullishPivot = false; + detector.detectCycleSameLLPivot = false; + detector.detectCycleSameHHPivot = false; + detector.detectTKIBearishPivot = false; + detector.detectTrendBullishPivot = true; + detector.detectTrendBearishPivot = true; + detector.detectTKITRNDBullishPivot = false; + detector.detectTKITRNDBearishPivot = false; + detector.detectRSICrossedOverOSPivot = false; + detector.detectRSICrossedUnderOBPivot = false; + detector.detectCCICrossedOverOSPivot = false; + detector.detectCCICrossedUnderOBPivot = false; + + // + // Initialize and Configure Drawer ... + drawer = new XCXCAEAPOIDrawer(detector); + + // + // UnActive Pivots ... + drawer.drawSWHPivots = false; + drawer.drawSWLPivots = false; + drawer.drawPeakPivots = false; + drawer.drawValePivots = false; + drawer.drawRSIPeakPivots = true; // true; + drawer.drawRSIValePivots = true; // true; + drawer.drawCCIPeakPivots = false; // true; + drawer.drawCCIValePivots = false; // true; + drawer.drawKIBullishPivots = false; + drawer.drawKIBearishPivots = false; + drawer.drawFVGBullishPivots = false; + drawer.drawFVGBearishPivots = false; + drawer.drawPeakSWHResPivots = false; // true; + drawer.drawValeSWLSupPivots = false; // true; + drawer.drawTKIBullishPivots = false; + drawer.drawTKIBearishPivots = false; + drawer.drawPVFVGBullishPivots = false; // true; + drawer.drawPVFVGBearishPivots = false; // true; + drawer.drawCycleSameLLPivots = false; + drawer.drawCycleSameHHPivots = false; + drawer.drawTrendBullishPivots = false; + drawer.drawTrendBearishPivots = false; + drawer.drawTKITRNDBullishPivots = false; + drawer.drawTKITRNDBearishPivots = false; + drawer.drawRSICrossedOverOSPivots = true; + drawer.drawRSICrossedUnderOBPivots = true; + drawer.drawCCICrossedOverOSPivots = false; + drawer.drawCCICrossedUnderOBPivots = false; + + // + drawer.drawTicks = true; + + // + // Configure Width ... + drawer.peakPivotWidth = 1; + drawer.valePivotWidth = 1; + drawer.ticksBullishWidth = 2; + drawer.ticksBearishWidth = 2; + drawer.fvgBullishPivotWidth = 1; + drawer.fvgBearishPivotWidth = 1; + drawer.oscsBullishPivotWidth = 2; + drawer.oscsBearishPivotWidth = 2; + + // + // Configure Colors ... + drawer.peakPivotColor = clrMagenta; + drawer.valePivotColor = clrAqua; + drawer.ticksBullishColor = clrYellow; + drawer.ticksBearishColor = clrOrange; + drawer.fvgBullishPivotColor = clrLime; + drawer.fvgBearishPivotColor = clrRed; + drawer.oscsBullishPivotColor = clrYellow; + drawer.oscsBearishPivotColor = clrOrange; + + // + // Configure Style ... + drawer.peakPivotStyle = STYLE_SOLID; + drawer.valePivotStyle = STYLE_SOLID; + drawer.ticksBullishStyle = STYLE_DOT; + drawer.ticksBearishStyle = STYLE_DOT; + drawer.fvgBullishPivotStyle = STYLE_DASH; + drawer.fvgBearishPivotStyle = STYLE_DASH; + drawer.oscsBullishPivotStyle = STYLE_SOLID; + drawer.oscsBearishPivotStyle = STYLE_SOLID; + } + + /** + * DeInitialize ... + */ + void DeInit() + { + // + inputs.Clean(); + + // + ZeroMemory(drawer); + ZeroMemory(helper); + ZeroMemory(detector); + + // + mConditions.Clean(); + Clean(mConditionsCollection); + + // + mObjects.Clear(); + mBarObjects.Clear(); + + // + barTraker.Clean(); + } + + // +}; + +// \ No newline at end of file