update workspace ...

This commit is contained in:
2024-05-17 04:54:01 +03:30
parent 3fa288c92c
commit 642713072e
429 changed files with 111729 additions and 9330 deletions
@@ -0,0 +1,385 @@
///////////////////////////////////////////////////////
//
// SaherElm IT Center MQL5 Class Library
// ----------------------------------------------
// Name: XSCHttp
// Description: provides all HTTP requirements ...
//
//
// Maintainer:
// ------------
// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com)
//
//////////////////////////////////////////////////////
//
// Global Properties ...
#property library
#property copyright "Copyright 2023, SaherElm IT Center"
#property link "https://www.saherelm.ir"
#property version "1.00"
#property strict
//
// START Definitions ...
//
//
enum X_HTTP_METHOD
{
X_HTTP_GET,
X_HTTP_POST
};
//
// Convert enum to String ...
string ToString(X_HTTP_METHOD method)
{
//
string result = "";
//
switch (method)
{
//
case X_HTTP_GET:
result = "GET";
break;
//
case X_HTTP_POST:
result = "POST";
break;
}
//
return result;
}
//
// END Definitions ...
//
//
// START Import and Inclused requirements ...
//
//
// Includes ...
#include "../Libraries/x-saherelm.common.lib.mq5"
//
// END Import and Inclused requirements ...
//
//
// START Overrides ...
//
//
// END Overrides ...
//
//
// a Class for Manage Account ...
class XSCHttp
{
//
// Public ...
public:
//
// Constructor ...
void XSCHttp()
{
XSCHttp("", 10000);
}
void XSCHttp(
string path, // Base Folder to Store Data
int timeout // base timeout for Requests
)
{
//
Path(path);
Timeout(timeout);
}
//
// Deconstructor ...
void ~XSCHttp()
{
}
//
// START Getter(s)/Setter(s) ...
//
//
// Path ...
void Path(string value)
{
mPath = value;
}
string Path()
{
return mPath;
}
//
// Timeout ...
void Timeout(int value)
{
mTimeout = value;
}
//
int Timeout()
{
return mTimeout;
}
//
// Error ...
int Error()
{
return mError;
}
//
// Response ...
string Response()
{
return mResponse;
}
//
// END Getter(s)/Setter(s) ...
//
//
// START Provided Functions ...
//
//
// Send Global Request ...
int SendRequest(
X_HTTP_METHOD method, // Httm Request Method
const string url, // Server Address
const string headers, // Headers providing
const char &payload[], // the Data which needs to Send
char &response[], // Response of request
string responseHeaders, // Response Headers
int timeout = 500 // Timeout for response default is 500
)
{
//
int result = -1;
//
string strMethod = ToString(method);
if (StringLen(strMethod) == 0)
{
return result;
}
//
// Reset State ...
ResetState();
//
result = WebRequest(
strMethod,
url,
headers,
timeout,
payload,
response,
responseHeaders);
//
if (result < 0)
{
mError = GetLastError();
}
else
{
mResponse = CharArrayToString(response);
}
//
return result;
}
//
// Get Request ...
int GetRequest(
const string url, // Server Address
const string headers, // Headers providing
const char &payload[], // the Data which needs to Send
char &response[], // Response of request
string responseHeaders, // Response Headers
int timeout = 500 // Timeout for response default is 500
)
{
//
int result = SendRequest(
X_HTTP_GET,
url,
headers,
payload,
response,
responseHeaders,
timeout);
//
return result;
}
//
// Post Request ...
int PostRequest(
const string url, // Server Address
const string headers, // Headers providing
const char &payload[], // the Data which needs to Send
char &response[], // Response of request
string responseHeaders, // Response Headers
int timeout = 500 // Timeout for response default is 500
)
{
//
int result = SendRequest(
X_HTTP_POST,
url,
headers,
payload,
response,
responseHeaders,
timeout);
//
return result;
}
//
// Handle Download Specific URL Content to Specific Path and File Name ...
bool Download(
string url, // the URL address which going to download
string fileName // Specify Destination file name to Store Response
)
{
//
bool result = false;
//
string filePath = GetFilePath(fileName);
string cookie = NULL;
string referer = NULL;
int timeout = Timeout();
//
char payload[];
string headers;
char response[];
string responseHeaders;
//
// Send Request ...
int requestResult = GetRequest(
url,
headers,
payload,
response,
responseHeaders,
timeout);
//
// Define File Handler ...
int mFileHandler = FileOpen(
filePath,
FILE_WRITE | FILE_BIN);
if (mFileHandler == INVALID_HANDLE)
{
//
mError = GetLastError();
return result;
}
//
// Write Response to File ...
uint writed = FileWriteArray(
mFileHandler,
response,
0,
ArraySize(response));
FileFlush(mFileHandler);
FileClose(mFileHandler);
//
result = writed > 0;
//
return result;
}
//
// END Provided Functions ...
//
//
// Protected ...
protected:
//
// Destintion Folder Path ...
string mPath;
//
// WEB Request Timeout Value ...
int mTimeout;
//
// WEB Request's Response ...
string mResponse;
//
// Error Value ...
int mError;
//
// Private ...
private:
//
// Reset Errors State ...
void ResetState()
{
//
// Reset Errors ...
mError = -1;
mResponse = "";
ResetLastError();
}
//
// Generate Full File Path ...
string GetFilePath(string fileName)
{
//
string result = "";
//
result =
//
Path() + "\\" + fileName
//
;
//
return result;
}
};
//
// START Usefull Functions ...
//
//
// END Usefull Functions ...
//
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -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 <Trade/AccountInfo.mqh>
#include "../Libraries/x-saherelm.common.lib.mq5"
//
// END Import and Inclused requirements ...
//
//
// START Overrides ...
//
//
// END Overrides ...
//
//
// a Class for Manage Account ...
class XSCAccount
{
//
// Public ...
public:
//
// Constructor ...
void XSCAccount()
{
//
mAccountInfo = new CAccountInfo();
}
//
// Deconstructor ...
void ~XSCAccount()
{
}
//
// START Provided Functions ...
//
//
// User Account ...
long GetUserAccount()
{
return mAccountInfo.Login();
}
//
// Account Leverage ...
long GetLeverage()
{
return mAccountInfo.Leverage();
}
//
// Get Trade Expert State ...
bool CanExpertTrade()
{
return mAccountInfo.TradeExpert();
}
//
// User Account Trade Mopde (ENUM_ACCOUNT_TRADE_MODE) ...
// --------------------------
// ACCOUNT_TRADE_MODE_DEMO
// ACCOUNT_TRADE_MODE_CONTEST
// ACCOUNT_TRADE_MODE_REAL
ENUM_ACCOUNT_TRADE_MODE GetTradeMode()
{
return mAccountInfo.TradeMode();
}
//
// Get Account Balance ...
double GetBalance()
{
return mAccountInfo.Balance();
}
//
// Get the amount of give Credit ...
double GetCredit()
{
return mAccountInfo.Credit();
}
//
// Get the amount of current Profit on account ...
double GetProfit()
{
return mAccountInfo.Profit();
}
//
// Get the amount of current Equity on account ...
double GetEquity()
{
return mAccountInfo.Equity();
}
//
// Get the amount of reserved Margin ...
double GetMargin()
{
return mAccountInfo.Margin();
}
//
// Get the amount of free Margin ...
double GetFreeMargin()
{
return mAccountInfo.FreeMargin();
}
//
// Get the Level of Margin ...
double GetMarginLevel()
{
return mAccountInfo.MarginLevel();
}
//
// Get the Level Of Margin for a Deposit ...
double GetMarginCall()
{
return mAccountInfo.MarginCall();
}
//
// Get the Level of Margin for Stop out ...
double GetMarginStopOut()
{
return mAccountInfo.MarginStopOut();
}
//
// Get the Client Name ...
string GetName()
{
return mAccountInfo.Name();
}
//
// Get the Trade Server Name ...
string GetServerName()
{
return mAccountInfo.Server();
}
//
// Get deposit Currency Name ...
string GetCurrency()
{
return mAccountInfo.Currency();
}
//
// Get the Company Name that serves an Account ...
string GetCompany()
{
return mAccountInfo.Company();
}
//
// Calculate Profits for the current account based on passed parameters ...
double CalculateTradeProfit(
const string symbol, // trading symbol
ENUM_ORDER_TYPE type, // order type
double volume, // volume
double entry, // open price
double exit // close price
)
{
//
double result = mAccountInfo.OrderProfitCheck(
symbol,
type,
volume,
entry,
exit);
//
return result;
}
//
// Calculate amount of margin which required for trade operation ...
double CalculateMarging(
const string symbol, // trading symbol
ENUM_ORDER_TYPE type, // order type
double volume, // volume
double entry // open price
)
{
//
double result = mAccountInfo.MarginCheck(
symbol,
type,
volume,
entry);
//
return result;
}
//
// Calculate amount of free margin left after trade operation ...
double CalculateFreeMarging(
const string symbol, // trading symbol
ENUM_ORDER_TYPE type, // order type
double volume, // volume
double entry // open price
)
{
//
double result = mAccountInfo.FreeMarginCheck(
symbol,
type,
volume,
entry);
//
return result;
}
//
// Calculate the Maximum possible volume of trade operation ...
double CalculateMaxVolume(
const string symbol, // trading symbol
ENUM_ORDER_TYPE type, // order type
double entry, // open price
double percent = 100 // percent of available margin
)
{
//
double result = mAccountInfo.MaxLotCheck(
symbol,
type,
entry,
percent);
//
return result;
}
//
// Calculate Point Value for Given Symbol based on Account ...
double GetPointValue(
string symbol // trading symbol
)
{
//
double result = 0;
//
double tickSize = SymbolInfoDouble(symbol, SYMBOL_TRADE_TICK_SIZE);
double tickValue = SymbolInfoDouble(symbol, SYMBOL_TRADE_TICK_VALUE);
double point = SymbolInfoDouble(symbol, SYMBOL_POINT);
//
double ticksPerPoint = tickSize / point;
//
result = tickValue / ticksPerPoint;
//
return result;
}
//
// Calculate Risk Amount based on account Currency by Providing:
// Points and Volume ...
double CalculateRiskAmount(
string symbol, // trading symbol
double points, // amount of Risk Points
double volume // position Volume
)
{
//
double result = 0;
//
double pointValue = GetPointValue(symbol);
//
result = pointValue * volume * points;
//
return result;
}
//
// Calculate Risk Points based on account Currency by Providing:
// Volume and Amount ...
double CalculateRiskPoints(
string symbol, // trading symbol
double volume, // position Volume
double amount // amount of Risk based on Account Currency
)
{
//
double result = 0;
//
double pointValue = GetPointValue(symbol);
//
result = amount / (pointValue * volume);
//
return result;
}
//
// Calculate Volume based on account Currency by Providing:
// Amount and Risk Points ...
double CalculateVolume(
string symbol, // trading symbol
double amount, // amount of Risk based on Account Currency
double points // amount of Risk Points
)
{
//
double result = 0;
//
points =
points <= 0
? 10
: points;
//
double pointValue = GetPointValue(symbol);
//
result = amount / (pointValue * points);
//
return result;
}
//
// END Provided Functions ...
//
//
// Protected ...
protected:
//
// Private ...
private:
//
// Account Info ...
CAccountInfo mAccountInfo;
};
//
// START Usefull Functions ...
//
//
// END Usefull Functions ...
//
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,209 @@
///////////////////////////////////////////////////////
//
// SaherElm IT Center MQL5 Class Library
// ----------------------------------------------
// Name: XSCBaseHelper
// Description: provides all Base Indicator
// Helper requirements ...
//
//
// Maintainer:
// ------------
// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com)
//
//////////////////////////////////////////////////////
//
// Global Properties ...
#property library
#property copyright "Copyright 2023, SaherElm IT Center"
#property link "https://www.saherelm.ir"
#property version "1.00"
#property strict
//
// START Definitions ...
//
//
// END Definitions ...
//
//
// START Import and Inclused requirements ...
//
//
// Includes ...
#include "../Libraries/x-saherelm.common.lib.mq5"
//
// END Import and Inclused requirements ...
//
//
// START Overrides ...
//
//
// END Overrides ...
//
//
// a Class for Handle base requirements ...
// for indicators ...
class XSCBaseHelper
{
//
// Public ...
public:
//
// Constructor ...
void XSCBaseHelper(
string symbol, // Trading Symbol
ENUM_TIMEFRAMES period // Trading Time Frame
)
{
//
mSymbol = symbol;
mPeriod = period;
//
LoopBack(52);
}
//
// Deconstructor ...
void ~XSCBaseHelper()
{
IndicatorRelease(mHandler);
}
//
// START Properties ...
//
//
// Loopback Bars ...
void LoopBack(int value)
{
mLoopbackBars = value;
}
int Loopback()
{
return mLoopbackBars;
}
//
// Symbol ...
string GetSymbol()
{
return mSymbol;
}
//
// Period ...
ENUM_TIMEFRAMES GetPeriod()
{
return mPeriod;
}
//
// Tag ...
string GetTag()
{
return mTag;
}
//
// Retrieve Bars ...
int GetBars()
{
//
int result =
Bars(
mSymbol,
mPeriod);
//
return result;
}
//
int GetCalculatedBars()
{
return BarsCalculated(mHandler);
}
//
// END Properties ...
//
//
// START Provided Functions ...
//
//
// Prepare Tag ...
virtual void PrepareTag() {}
//
// Reading Buffers based on Given Bar Index ...
virtual void Calculate(
int barIndex // Given Bar Index
);
//
// Retrieve MAx Required Length for Calculations ...
virtual int GetMaxLength();
//
// END Provided Functions ...
//
//
// Protected ...
protected:
//
string GetTagPrefix()
{
//
string result = "(" + mSymbol + ")(" + ToString(mPeriod) + ")";
//
return result;
}
//
// Symbol ...
string mSymbol;
//
// Period ...
ENUM_TIMEFRAMES mPeriod;
//
// Indicator Handler ...
int mHandler;
//
// Number Of Items Read Per Tick ...
int mLoopbackBars;
//
// Tag Identifier ...
string mTag;
//
// Private ...
private:
//
};
//
// START Usefull Functions ...
//
//
// END Usefull Functions ...
//
@@ -0,0 +1,304 @@
///////////////////////////////////////////////////////
//
// SaherElm IT Center MQL5 Class Library
// ----------------------------------------------
// Name: XSCEABaseProvider
// Description: provides base requirements for
// Specific Sgnal Provider ...
//
//
// Maintainer:
// ------------
// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com)
//
//////////////////////////////////////////////////////
//
// Global Properties ...
#property library
#property copyright "Copyright 2023, SaherElm IT Center"
#property link "https://www.saherelm.ir"
#property version "1.00"
#property strict
//
// START Import and Inclused requirements ...
//
//
// Includes ...
#include "../Libraries/x-saherelm.log.lib.mq5"
#include "../Libraries/x-saherelm.draw.lib.mq5"
#include "../Libraries/x-saherelm.models.lib.mq5"
#include "../Libraries/x-saherelm.common.lib.mq5"
//
// END Import and Inclused requirements ...
//
//
// START Definitions ...
//
//
// Notified a Signal was Appears ...
typedef void (*OnSignal)(
XSignal &signal);
//
// Notified a Guard Appears ...
typedef void (*OnGuard)(XGuard &guard);
//
// END Definitions ...
//
//
// START Overrides ...
//
//
// END Overrides ...
//
//
// a Base Class for All of our EA's ...
class XSCEABaseProvider
{
//
// Public ...
public:
//
// Constructor ...
void XSCEABaseProvider()
{
mSymbol = _Symbol;
mPeriod = _Period;
}
void XSCEABaseProvider(
string symbol,
ENUM_TIMEFRAMES period)
{
//
mSymbol = symbol;
mPeriod = period;
//
mTag = mSymbol + "," + ToString(mPeriod);
//
mIsInTestMode = IsRunningOnTestMode();
}
//
// Deconstructor ...
void ~XSCEABaseProvider()
{
}
//
bool CanIgnoreTick() {
//
mIsNewCandle = IsNewCandle(
mSymbol,
mPeriod);
bool result = mIsInTestMode
? !mIsNewCandle
: !mIsNewCandle && mWaitUntilNewCandle;
//
return result;
}
//
// Prepare State ...
void OnTick()
{
//
mIsNewCandle = IsNewCandle(
mSymbol,
mPeriod);
mCanIgnoreTick = mIsInTestMode
? !mIsNewCandle
: !mIsNewCandle && mWaitUntilNewCandle;
//
ProcessBuffers();
//
if (mCanIgnoreTick)
{
return;
}
//
mWaitUntilNewCandle = false;
//
ProcessTick();
}
//
virtual void PrepareTag();
//
// Initialize Indicators and Requirements ...
virtual bool Init();
//
virtual int GetMaxLength();
//
virtual int GetCalculatedBars();
//
// Handle Update Buffers ...
virtual void ProcessBuffers()
{
return;
}
//
// Handle On Tick Event ...
virtual void ProcessTick()
{
return;
}
//
// Check for Guards ...
virtual bool GuardCheck(XGuard &guards[]);
//
// Add Specific On Signal Event Handler ...
int AddOnSignalEventHandler(OnSignal handler)
{
//
ArrayResize(
mSignalEventHandlers,
ArraySize(mSignalEventHandlers) + 1);
//
int result = ArraySize(mSignalEventHandlers) - 1;
mSignalEventHandlers[result] = handler;
//
return result;
}
//
// Remove All On Signal Event Handler ...
void ReoveOnSignalEventHandlers()
{
//
ArrayFree(mSignalEventHandlers);
}
//
// Notify a Signal Found on all Event Listeners ...
void NotifyOnSignalEvent(XSignal &info)
{
//
int listenerCount = ArraySize(mSignalEventHandlers);
if (listenerCount <= 0)
{
return;
}
//
// Loop Through Listeners ...
for (int i = 0; i < listenerCount; i++)
{
//
OnSignal listener = mSignalEventHandlers[i];
//
listener(info);
}
}
//
// Protected ...
protected:
//
string mSymbol;
//
ENUM_TIMEFRAMES mPeriod;
//
string mTag;
//
bool mIsNewCandle;
bool mIsInTestMode;
bool mCanIgnoreTick;
bool mWaitUntilNewCandle;
//
// Private ...
private:
//
// Signal Event Handlers ...
OnSignal mSignalEventHandlers[];
};
//
// START Definitions ...
//
//
// Model Signal Providers Definitions ...
struct XBaseSignalProvider
{
//
// Provider use Which Symbol ...
string symbol;
//
// Provider use Which Time Frame ...
ENUM_TIMEFRAMES period;
//
// Risk Amount Per Trades Related to Time Frames ...
// Percent of Available Balance ...
double riskAmount;
//
// Desired Magic Number ...
ulong magicNumber;
};
//
struct XLastSignal
{
datetime at;
string provider;
};
//
// END Definitions ...
//
//
// START Usefull Functions ...
//
//
// Add Specific Provider to List ...
void Add(
XBaseSignalProvider &item, // item want to add
XBaseSignalProvider &buffer[] // Destination buffer
)
{
//
ArrayResize(
buffer,
ArraySize(buffer) + 1);
//
buffer[ArraySize(buffer) - 1] = item;
}
//
// END Usefull Functions ...
//
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,506 @@
/**
* XColor Tools Module ...
* a module for handle colorify text contents in node js ...
*
* Maintainer
*
* Hadi Khazaee Asl <https://saherelm.ir> (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
@@ -0,0 +1,830 @@
/**
* XFile Tools Module ...
* a module for handle all file/folder manipulating task in node js ...
*
* Maintainer
*
* Hadi Khazaee Asl <https://saherelm.ir> (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<boolean>} 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<boolean>} 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<string>} 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<boolean>} 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<boolean>} 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<string[]>}
*/
async function getRecursiveFilesList(
path = "",
extensions = []
) {
//
let result = [];
//
// Validate Args ...
if (
!XValueTools.isValidArg(path)
|| !isDirectoryExists(path)
) {
return result;
}
//
const contents = await getDirectoryContents(path);
for(const item of contents) {
//
const itemPath = joinPath(
path,
item
);
//
const isItemFile = isFileExists(itemPath);
if (isItemFile) {
//
const itemFileExtension = getFileExtension(itemPath);
const isFileInSupportedExtensions =
extensions === undefined || extensions.length === 0
? true
: extensions.includes(itemFileExtension)
;
if (isFileInSupportedExtensions) {
result.push(itemPath);
}
} else if (isDirectoryExists(itemPath)) {
//
const itemPathFiles = await getRecursiveFilesList(itemPath, extensions);
result.push(...itemPathFiles);
}
}
//
return result;
}
//#endregion
//
//#region Directory ...
/**
* create a directory ...
*
* @param {string} path destination path including dir name ...
* @param {boolean} recursive create directories recursively ...
* @returns action done or not ...
*/
function createDirectory(
path = '',
recursive = true
) {
//
let result = false;
//
if (
isDirectoryExists(path) ||
!XValueTools.isValidArg(path)
) {
return false;
}
//
try {
//
fs.mkdirSync(path, { recursive: recursive });
result = true;
return result;
} catch {
return false;
}
}
/**
* remove a directory ...
*
* @param {string} path destination path including dir name ...
* @param {boolean} recursive removes directories recursively ...
* @returns {Promise<boolean>} 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<string[]>} 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<string[]>} 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<string[]>} 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<boolean>} 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<boolean>}
*/
async function writeJSON(
path = "",
content = undefined
) {
//
let result = false;
//
// Validate Args ...
if (!XValueTools.isValidArg(path)) {
return result;
}
//
// Normallize Content ...
if (content === undefined) {
content = {};
}
//
const contentString = XValueTools.beautifyJSON(content);
//
result = await writeFile(
path,
contentString,
true
);
//
return result;
}
//#endregion
//#endregion
//
//#region Module Exports ...
module.exports = {
//
CurrentDir,
PathSeparator,
//
getStatus,
getHomePath,
//
basename,
joinPath,
resolvePath,
//
download,
//
readJSON,
writeJSON,
//
copyFile,
readFile,
writeFile,
createFile,
removeFile,
isFileExists,
getFileExtension,
removeFileExtension,
getRecursiveFilesList,
//
copyFolder,
createDirectory,
removeDirectory,
createDirectory,
removeDirectory,
isDirectoryExists,
isDirectoryExists,
getDirectoryFiles,
getDirectoryFolders,
getDirectoryContents,
}
//#endregion
@@ -0,0 +1,219 @@
/**
* XShell Tools Module ...
* a module for handling shell actions and retrieve OS Info in node js ...
*
* Maintainer
*
* Hadi Khazaee Asl <https://saherelm.ir> (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<any, errr> 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
@@ -0,0 +1,268 @@
/**
* DataType Tools Module ...
* a module for manipulate and detect supported data types in node js ...
*
* Maintainer
*
* Hadi Khazaee Asl <https://saherelm.ir> (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
File diff suppressed because it is too large Load Diff
@@ -0,0 +1 @@
EURUSDb,GBPUSDb,USDJPYb,USDCHFb,XAUUSDb|M5,M15|0.01|X786|true
@@ -0,0 +1,366 @@
///////////////////////////////////////////////////////
//
// SaherElm IT Center MQL5 Expert Advisor
// ----------------------------------------
// Name: X121EA
// Description: this is an expert controller
// advisors which provides a mechanism for use them ...
//
// NOTE: about provider instancing in multi asset state:
// you can provide configurations using this:
//
// EURUSDb,GBPUSDb,USDJPYb,USDCHFb,XAUUSDb|M5,M15|0.01|X786|true
// EURUSDb,GBPUSDb,USDJPYb,USDCHFb,XAUUSDb|M5,M15|0.01|X786|true
//
// or make the instance use this:
//
// XPV(EURUSDb|M15|0.01|X92|true)XPV(GBPUSDb|M5|0.02|X786|false)
//
// if leave Configuration string blank this will used default config
// and One asset mode enabled ...
//
// Maintainer:
// ------------
// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com)
//
//////////////////////////////////////////////////////
//
// Global Properties ...
#property copyright "Copyright 2023, SaherElm IT Center"
#property link "https://saherelm.ir"
#property version "1.00"
#property description "SaherElm X121EA"
#property strict
//
// START Definitions ...
//
//
#define ShortName "X121EA"
//
// END Definitions ...
//
//
// START Inputs ...
//
//
// EA ...
input group "Common";
input bool xEAEnable = true; // Enable EA
input int xEASlippage = 10; // Slippgae
input ulong xEAMagicNumber = 1604056; // Magic Number
//
// Providers ...
input group "Providers";
input string xEAProvidersConfiguration = ""; // Providers Configuration
input string xEADefaultSignalProviders = "X786"; // Default Allowed Signal Providers
//
// Signals ...
input group "Signals";
input bool xEAEnableLongs = true; // Enable Long Trades
input bool xEAEnableShorts = true; // Enable Short Trades
//
// Risk Management ...
input group "Risk Management";
input int xEAMaxOpenPositions = 15; // Max Allowed Open Trades
input double xEAMinRiskAmountPerTrade = 0.001; // Min Risk Amount Per Trade
input double xEAMaxAllowedDrawDownFactor = 0.01; // Max Allowed Drawdown Factor
input double xEAMinProfitPerTrade = 0.1; // Min Acceptable Profit Per Trade
input double xEAMinProfitPerVolumeFactor = 0.01; // Min Acceptable Profit Volume Factor Per Trade
input bool xEAUseRiskAmountAsStaticVolume = true; // Use Provided Risk Amount as Static Volume
//
// Alerts ...
input group "Alerts";
input bool xEAEnableAlerts = true; // Enable Events Alert
input bool xEAEnableHourlyAlerts = false; // Send Alert on each new Hour
input bool xEAEnableDailyAlerts = false; // Send Alert on each new Day
input bool xEAEnableWeeklyAlerts = false; // Send Alert on each new Week
input bool xEAEnableMonthlyAlerts = false; // Send Alert on each new Month
//
// END Inputs ...
//
//
// START Including Providers ...
//
//
// Logger Library ...
#include "../Libraries/x-saherelm.log.lib.mq5"
#include "../Classes/x-saherelm.x121.xea.class.mq5"
#include "../Libraries/x-saherelm.seriallizer.lib.mq5"
//
// END Including Providers ...
//
//
// START Global Definitions: Variables, Properties and etc ...
//
//
XSCX121EA *mX121EA;
//
// END Global Definitions: Variables, Properties and etc ...
//
//
// START Event Handlers ...
//
//
// Initialization ...
int OnInit()
{
//
logTag = ShortName;
drawPrefix = logTag;
alertPrefix = logTag;
//
// Validate Inputs ...
if (!ValidateInputs())
{
return INIT_PARAMETERS_INCORRECT;
}
//
bool isInit = InitEAInstance();
if (!isInit)
{
return INIT_FAILED;
}
//
// Init Succeed ...
return INIT_SUCCEEDED;
}
//
// DeInitialization ...
void OnDeinit(const int reason)
{
//
// REASON_PROGRAM 0 The EA has stopped working calling the ExpertRemove() function
// REASON_REMOVE 1 Program removed from a chart
// REASON_RECOMPILE 2 Program recompiled
// REASON_CHARTCHANGE 3 A symbol or a chart period is changed
// REASON_CHARTCLOSE 4 Chart closed
// REASON_PARAMETERS 5 Inputs changed by a user
// REASON_ACCOUNT 6 Another account has been activated or reconnection to the trade server has occurred due to changes in the account settings
// REASON_TEMPLATE 7 Another chart template applied
// REASON_INITFAILED 8 The OnInit() handler returned a non-zero value
// REASON_CLOSE 9 Terminal closed
//
// De Initialize XEA Providers ...
delete mX121EA;
}
//
// On Tick Handler ...
void OnTick()
{
//
// Prevent Going Forward if user Disable it ...
if (xEAEnable)
{
mX121EA.OnTick();
}
}
//
// Handle Trade Events ...
void OnTrade()
{
mX121EA.OnTrade();
}
//
// Handle Signal Event ...
void OnSignalConditionsRecieved(X121MarketConditions &info)
{
}
//
// Handle StopLoss Event ...
void OnStopLossTriggered(const XDeal &deal)
{
}
//
// Handle TakeProfit Event ...
void OnTakeProfitTriggered(const XDeal &deal)
{
}
//
// Handle Deals Changed Event ...
void OnDealsChangedHandler(int count)
{
}
//
// Handle Order Changed Event ...
void OnOrdersChangedHandler(int count)
{
}
//
// Handle Position Changed Event ...
void OnPositionsChangedHandler(int count)
{
}
//
// Handle Trade State Changed ...
void OnTradeStateChangedHandler(const XOnTradeHandlerState &state)
{
}
//
// END Event Handlers ...
//
//
// START Functions ...
//
//
// Validate Input Args for Initialization ...
bool ValidateInputs()
{
//
bool result = true;
//
// Validate Args ...
result =
//
xEASlippage > 0 &&
xEAMagicNumber > 0 &&
xEAMinRiskAmountPerTrade > 0 &&
StringLen(xEADefaultSignalProviders) > 0
//
// TODO: add new validations here ...
//
;
//
// Validate Providers ...
if (result)
{
//
string providers[];
SplitContent(
providers,
xEADefaultSignalProviders);
//
int providersCount = ArraySize(providers);
if (providersCount <= 0)
{
//
result = false;
return result;
}
//
string allProviders[];
GetAllProviders(allProviders);
//
bool hasError = false;
for (int i = 0; i < providersCount; i++)
{
//
string iProvider = providers[i];
if (!Contains(iProvider, allProviders))
{
//
hasError = true;
break;
}
}
//
if (hasError)
{
//
result = false;
return result;
}
}
//
// Logging State ...
string message = "Validation of (" + logTag + ") Inputs " + (result ? "Succeeded" : "Failed") + " ...";
LogMessage(message);
//
return result;
}
//
// Initialize X121EA Class Instances ...
bool InitEAInstance()
{
//
bool result = false;
//
X121SignalProvider providers[];
//
// Try to Extract Configs ...
int configsCount = ExtractProviderConfigurations(
providers,
xEAProvidersConfiguration,
xEADefaultSignalProviders,
xEAMinRiskAmountPerTrade,
xEAUseRiskAmountAsStaticVolume);
//
mX121EA = new XSCX121EA(
_Symbol,
_Period,
xEAMagicNumber,
xEASlippage,
xEAMinProfitPerTrade,
xEAMinProfitPerVolumeFactor,
OnStopLossTriggered,
OnTakeProfitTriggered,
OnDealsChangedHandler,
OnOrdersChangedHandler,
OnPositionsChangedHandler,
OnTradeStateChangedHandler,
OnSignalConditionsRecieved);
//
mX121EA.EnableLongs(xEAEnableLongs);
mX121EA.EnableShorts(xEAEnableShorts);
mX121EA.MaxAllowedPositions(xEAMaxOpenPositions);
mX121EA.MaxAllowedDrawDownFactor(xEAMaxAllowedDrawDownFactor);
//
// Attach Providers to EA Instance ...
int providersCount = ArraySize(providers);
int addedProviders = mX121EA.AddProviders(providers);
result = addedProviders == providersCount;
//
return result;
}
//
// END Functions ...
//
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,187 @@
///////////////////////////////////////////////////////
//
// SaherElm IT Center MQL5 Alert Library
// --------------------------------------
// Name: XAlert
// Description: provides Alerts abilities ...
//
//
// Maintainer:
// ------------
// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com)
//
//////////////////////////////////////////////////////
//
// Global Properties ...
#property library
#property copyright "Copyright 2023, SaherElm IT Center"
#property link "https://www.saherelm.ir"
#property version "1.00"
#property strict
//
// START Inputs ...
//
input group "Alerts";
input bool enableAlerts = true; // Enable Alerts
input bool logAlerts = true; // Log Alerts
input bool terminalAlerts = false; // Terminal Alerts
input bool mailAlerts = false; // Mail Alerts
input bool pushAlerts = false; // Push Alerts
//
// END Inputs ...
//
//
#include "x-saherelm.log.lib.mq5"
//
// START Global Definitions: Variables, Properties and etc ...
//
string alertPrefix = "X-Alert";
//
// END Global Definitions: Variables, Properties and etc ...
//
//
// START Provided Functions ...
//
//
// Initial Library if required ...
bool OnInInitAlertLibrary()
{
return false;
}
//
// DeInitial Library if required ...
void OnDeinitAlertLibrary()
{
}
//
// Attach Alert Prefix to Message ...
string PrepareAlertMessage(string message)
{
//
StringReplace(message, "\n", " | ");
//
StringConcatenate(message, alertPrefix, " > ", message);
//
return message;
}
//
// Logging an Alert ...
void LogAlert(string message)
{
//
// Validate Args ...
if (!enableAlerts || !logAlerts)
{
return;
}
//
LogMessage(alertPrefix, message);
}
//
// Terminal Alert ...
void TerminalAlert(string message)
{
//
// Validate Args ...
if (!enableAlerts || !terminalAlerts)
{
return;
}
//
// Prepare Message ...
message = PrepareAlertMessage(message);
// Send Terminal Alert ...
Alert(message);
}
//
// Mail Alert ...
void MailAlert(string message)
{
//
// Validate Args ...
if (!enableAlerts || !mailAlerts)
{
return;
}
//
// Send Mail Alert ...
SendMail(alertPrefix, message);
}
//
// Send Push Notification ...
void PushAlert(string message)
{
//
// Validate Args ...
if (!enableAlerts || !pushAlerts)
{
return;
}
//
// Prepare Message ...
message = PrepareAlertMessage(message);
//
// Send Push Notification Alert ...
SendNotification(message);
}
//
// Alert Sending ...
void SendAlert(string message)
{
//
// Validate Args ...
if (!enableAlerts)
{
return;
}
//
// Log ...
if (logAlerts)
{
LogAlert(message);
}
//
// Terminal ...
if (terminalAlerts)
{
TerminalAlert(message);
}
//
// Mail ...
if (mailAlerts)
{
MailAlert(message);
}
//
// Push ...
if (pushAlerts)
{
PushAlert(message);
}
}
//
// END Provided Functions ...
//
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,177 @@
///////////////////////////////////////////////////////
//
// SaherElm IT Center MQL5 Http Library
// ------------------------------------------
// Name: XHttp
// Description: provide http communication
// abilities ...
//
//
// Maintainer:
// ------------
// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com)
//
//////////////////////////////////////////////////////
//
// Global Properties ...
#property library
#property copyright "Copyright 2023, SaherElm IT Center"
#property link "https://www.saherelm.ir"
#property version "1.00"
#property strict
//
// START Model Definition ...
//
enum X_HTTP_METHOD
{
X_HTTP_GET,
X_HTTP_POST
};
//
// END Model Definition ...
//
//
// START Inputs ...
//
//
// END Inputs ...
//
//
// START Global Definitions: Variables, Properties and etc ...
//
//
// END Global Definitions: Variables, Properties and etc ...
//
//
// START Provided Functions ...
//
//
// Initial Library if required ...
bool OnInInitHttpLibrary()
{
return false;
}
//
// DeInitial Library if required ...
void OnDeinitHttpLibrary()
{
}
//
// Convert enum to String ...
string ToString(X_HTTP_METHOD method)
{
//
string result = "";
//
switch (method)
{
//
case X_HTTP_GET:
result = "GET";
break;
//
case X_HTTP_POST:
result = "POST";
break;
}
//
return result;
}
//
// Send Global Request ...
int SendRequest(
X_HTTP_METHOD method, // Httm Request Method
const string url, // Server Address
const string headers, // Headers providing
const char &payload[], // the Data which needs to Send
char &response[], // Response of request
string responseHeaders, // Response Headers
int timeout = 500 // Timeout for response default is 500
)
{
//
int result = -1;
//
string strMethod = ToString(method);
if (StringLen(strMethod) == 0) {
return result;
}
//
result = WebRequest(
strMethod,
url,
headers,
timeout,
payload,
response,
responseHeaders
);
//
return result;
}
//
// Get Request ...
int GetRequest(
const string url, // Server Address
const string headers, // Headers providing
const char &payload[], // the Data which needs to Send
char &response[], // Response of request
string responseHeaders, // Response Headers
int timeout = 500 // Timeout for response default is 500
) {
//
int result = SendRequest(
X_HTTP_GET,
url,
headers,
payload,
response,
responseHeaders,
timeout
);
//
return result;
}
//
// Post Request ...
int PostRequest(
const string url, // Server Address
const string headers, // Headers providing
const char &payload[], // the Data which needs to Send
char &response[], // Response of request
string responseHeaders, // Response Headers
int timeout = 500 // Timeout for response default is 500
) {
//
int result = SendRequest(
X_HTTP_POST,
url,
headers,
payload,
response,
responseHeaders,
timeout
);
//
return result;
}
//
// END Provided Functions ...
//
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,303 @@
///////////////////////////////////////////////////////
//
// SaherElm IT Center MQL5 Models Library
// ---------------------------------------
// Name: XModels
// Description: provides all required models ...
//
//
// Maintainer:
// ------------
// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com)
//
//////////////////////////////////////////////////////
//
// Global Properties ...
#property library
#property copyright "Copyright 2023, SaherElm IT Center"
#property link "https://www.saherelm.ir"
#property version "1.00"
#property strict
//
// START Inputs ...
//
//
// END Inputs ...
//
//
// START Global Definitions: Variables, Properties and etc ...
//
//
// END Global Definitions: Variables, Properties and etc ...
//
//
// START Provided Functions ...
//
//
// How To Calculate Static Volume ...
enum ENUM_STATIC_VOLUME_METHODS
{
//
// Based On Deposit ...
X_STATIC_VOLUME_BASED_ON_DEPOSIT,
//
// Based On Balance ...
X_STATIC_VOLUME_BASED_ON_BALANCE,
};
//
// START Model Definitions ...
//
//
// OHCL Candel Model ...
enum ENUM_X_PRICE
{
X_PRICE_HIGH,
X_PRICE_OPEN,
X_PRICE_CLOSE,
X_PRICE_LOW
};
//
// Swing Types Enum ...
enum ENUM_X_SWING_TYPE
{
X_NO_SWING = 0,
X_SWING_HIGH = 1,
X_SWING_LOW = -1,
};
//
// Select Positions Type ...
enum ENUM_X_POSITION_SELECT_METHODS
{
X_POSITION_SELECT_NONE, // None
X_POSITION_SELECT_MAX, // Max
X_POSITION_SELECT_MIN, // Min
X_POSITION_SELECT_ALL, // Min
};
//
// Available Guard Action ...
enum ENUM_X_GUARD_ACTIONS
{
X_GUARD_ACTION_NOTHING, // Nothing
X_GUARD_ACTION_HEDGE, // Hedge
X_GUARD_PARTIAL_CLOSE, // Partial Close
X_GUARD_ACTION_TRAIL_STOP, // Trail StopLoss
X_GUARD_ACTION_FORCE_CLOSE, // Force Close
X_GUARD_ACTION_ADD_SUPPORT_SIGNAL, // Add Support Signal
X_GUARD_ACTION_CANCEL_PENDING_ORDERS, // Cancel Pending Orders
};
//
// Model Guard Info ...
struct XGuard
{
string symbol;
string provider;
ENUM_TIMEFRAMES period;
ENUM_POSITION_TYPE type;
ENUM_X_GUARD_ACTIONS action;
//
double dblPayLoad;
string strPayload;
};
//
// Describe an Specific Candle ...
struct XOHCL
{
double high;
double open;
double close;
double low;
};
//
// Model Support and Resistance
// for Specific Bar ...
struct XOHCLSupRes
{
//
double res[];
//
double sup[];
};
//
// Available Order Modes ...
enum ENUM_X_ORDER_MODES
{
X_ORDER_MODE_MARKET = 0, // Market Order
X_ORDER_MODE_STOP = 1, // Pending Stop Order
X_ORDER_MODE_LIMIT = 2, // Pending Limit Order
X_ORDER_MODE_STOP_LIMIT = 3, // Pending Stop Limit Order
};
//
// Model a Signal ...
struct XSignal
{
//
string providers[];
//
string symbol;
//
ENUM_TIMEFRAMES period;
//
ENUM_POSITION_TYPE type;
//
ENUM_X_ORDER_MODES mode;
//
double entry;
//
double riskAmount;
//
double tp;
//
double sl;
//
double r2r;
//
double volume;
//
bool calculateTP;
//
bool ignoreSL;
bool ignoreTP;
//
bool useSupportAndResistance;
//
bool useRiskAmountAsVolume;
//
// Support Signals ...
XSignal supports[];
//
XOHCLSupRes supportAndResistance;
};
//
// EXTENSION Methods ...
//
// Clear an Specific Signal Item ...
void Clean(XSignal &item)
{
//
Clean(item.providers);
//
Clean(item.supports);
//
Clean(item.supportAndResistance);
//
item.symbol = "";
item.type = NULL;
item.mode = NULL;
item.period = NULL;
//
item.tp = 0;
item.sl = 0;
item.r2r = 0;
item.entry = 0;
item.volume = 0;
item.riskAmount = 0;
//
item.ignoreSL = false;
item.ignoreTP = false;
item.calculateTP = false;
item.useRiskAmountAsVolume = false;
item.useSupportAndResistance = false;
}
//
void Clean(XOHCLSupRes &item)
{
Clean(item.sup);
Clean(item.res);
}
template <typename T>
void Add(
T &item,
T &buffer[])
{
//
ArrayResize(
buffer,
ArraySize(buffer) + 1);
//
buffer[ArraySize(buffer) - 1] = item;
}
template <typename T>
void Clean(T &buffer[])
{
//
ArrayFree(buffer);
ArrayResize(buffer, 0);
}
template <typename T>
void Copy(
T &source[], // Source Buffer ...
T &dest[], // Dest Buffer ...
bool cleanDest = true // Force Clen Dest Buffer ...
)
{
//
if (cleanDest)
{
Clean(dest);
}
//
int sourceCount = ArraySize(source);
if (sourceCount <= 0)
{
return;
}
//
for (int i = 0; i < sourceCount; i++)
{
//
T iSource = source[i];
//
Add(
iSource,
dest);
}
}
//
// END Provided Functions ...
//
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,276 @@
///////////////////////////////////////////////////////
//
// SaherElm IT Center MQL5 X12 Draw Library
// ------------------------------------------
// Name: X121Draw
// Description: provides Draw Requirements ...
//
//
// Maintainer:
// ------------
// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com)
//
//////////////////////////////////////////////////////
//
// Global Properties ...
#property library
#property copyright "Copyright 2023, SaherElm IT Center"
#property link "https://www.saherelm.ir"
#property version "1.00"
#property strict
//
#include "../Libraries/x-saherelm.draw.lib.mq5"
#include "../Libraries/x-saherelm.common.lib.mq5"
#include "../Libraries/x-saherelm.models.lib.mq5"
//
// START Draw Functions ...
//
//
// Draw Signal ...
void DrawSignal(const ulong ticket, XSignal &signal)
{
//
bool isLong = IsLong(signal.type);
//
string prefix = (string)ticket + "_" + ToString(signal.period);
//
// Retrieve Time ...
datetime time = iTime(
signal.symbol,
signal.period,
0);
//
// Retrieve 3 Time ...
datetime time3 = iTime(
signal.symbol,
signal.period,
3);
//
color posColor = isLong
? clrSpringGreen
: clrTomato;
color tpColor = clrSpringGreen;
color slColor = clrTomato;
color entryColor = clrGold;
//
ENUM_LINE_STYLE vLineStyle = STYLE_DOT;
ENUM_LINE_STYLE tpLineStyle = STYLE_SOLID;
ENUM_LINE_STYLE slLineStyle = STYLE_SOLID;
ENUM_LINE_STYLE entryLineStyle = STYLE_SOLID;
//
int lineWidth = 2;
//
long chartID = ChartID();
//
// Vertical Line ...
string vlName = prefix + "_" + (string)time;
//
DrawVerticalLine(
chartID,
vlName,
0,
time,
posColor,
vLineStyle,
lineWidth);
//
// TP ...
double profit = (MathAbs(signal.tp - signal.entry)) * signal.volume;
string tpName = prefix + "_TP_" + (string)profit;
//
DrawTrendLine(
chartID,
tpName,
0,
time3,
signal.tp,
time,
signal.tp,
tpColor,
tpLineStyle,
lineWidth);
//
// SL ...
double lost = (MathAbs(signal.sl - signal.entry)) * signal.volume;
string slName = prefix + "_SL_" + (string)lost;
//
DrawTrendLine(
chartID,
slName,
0,
time3,
signal.sl,
time,
signal.sl,
slColor,
slLineStyle,
lineWidth);
//
// ENTRY ...
string entryName = prefix + "_ENTRY_" + (string)lost;
//
DrawTrendLine(
chartID,
entryName,
0,
time3,
signal.entry,
time,
signal.entry,
entryColor,
entryLineStyle,
lineWidth);
}
//
void DrawSignals(
XSignal &signals[], // Signals To Draw
bool drawSupportAndResistances = false // Draw Signal Support and Resistance
)
{
//
int signalsCount = ArraySize(signals);
if (signalsCount <= 0)
{
return;
}
//
for (int i = 0; i < signalsCount; i++)
{
//
XSignal iSignal = signals[i];
//
ulong iTicket = MathRand() * 10000;
//
DrawSignal(iTicket, iSignal);
//
// Check For Draw Support and Resistances ...
bool isValidSupRes = ArraySize(iSignal.supportAndResistance.sup) > 0 || ArraySize(iSignal.supportAndResistance.res) > 0;
if (drawSupportAndResistances && isValidSupRes)
{
DrawSupportResistance(0, iSignal.supportAndResistance);
}
}
}
//
// Draw Support and Resistance ...
void DrawSupportResistance(
int bar_index,
XOHCLSupRes &data,
string prefix = "",
color supportColor = clrOrange,
color resistanceColor = clrOrange)
{
//
datetime barTime = GetCandleTime(
_Symbol,
_Period,
bar_index);
//
datetime prevBarTime = GetCandleTime(
_Symbol,
_Period,
bar_index + 5);
//
long chID = ChartID();
int subWindiw = 0;
int lineWidth = 1;
//
string mPrefix = prefix + "_" + (string)barTime + "_";
//
// SUPPORTS ...
//
int supCount = ArraySize(data.sup);
if (supCount > 0)
{
//
for (int i = 0; i < supCount; i++)
{
//
double iSup = data.sup[i];
//
string supTlName = mPrefix + "SUP[" + (string)(i + 1) + "]_(" + (string)iSup + ")";
//
// Draw Support ...
DrawTrendLine(
chID,
supTlName,
subWindiw,
prevBarTime,
iSup,
barTime,
iSup,
supportColor,
STYLE_DOT,
lineWidth,
true);
}
}
//
// RESISTANCES ...
//
int resCount = ArraySize(data.res);
if (resCount > 0)
{
//
for (int i = 0; i < resCount; i++)
{
//
double iRes = data.res[i];
//
string resTlName = mPrefix + "RES[" + (string)(i + 1) + "]_(" + (string)iRes + ")";
//
// Draw Support ...
DrawTrendLine(
chID,
resTlName,
subWindiw,
prevBarTime,
iRes,
barTime,
iRes,
resistanceColor,
STYLE_DOT,
lineWidth,
true);
}
}
}
//
// END Draw Functions ...
//
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,385 @@
///////////////////////////////////////////////////////
//
// SaherElm IT Center MQL5 Class Library
// ----------------------------------------------
// Name: XSCHttp
// Description: provides all HTTP requirements ...
//
//
// Maintainer:
// ------------
// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com)
//
//////////////////////////////////////////////////////
//
// Global Properties ...
#property library
#property copyright "Copyright 2023, SaherElm IT Center"
#property link "https://www.saherelm.ir"
#property version "1.00"
#property strict
//
// START Definitions ...
//
//
enum X_HTTP_METHOD
{
X_HTTP_GET,
X_HTTP_POST
};
//
// Convert enum to String ...
string ToString(X_HTTP_METHOD method)
{
//
string result = "";
//
switch (method)
{
//
case X_HTTP_GET:
result = "GET";
break;
//
case X_HTTP_POST:
result = "POST";
break;
}
//
return result;
}
//
// END Definitions ...
//
//
// START Import and Inclused requirements ...
//
//
// Includes ...
#include "../Libraries/x-saherelm.common.lib.mq5"
//
// END Import and Inclused requirements ...
//
//
// START Overrides ...
//
//
// END Overrides ...
//
//
// a Class for Manage Account ...
class XSCHttp
{
//
// Public ...
public:
//
// Constructor ...
void XSCHttp()
{
XSCHttp("", 10000);
}
void XSCHttp(
string path, // Base Folder to Store Data
int timeout // base timeout for Requests
)
{
//
Path(path);
Timeout(timeout);
}
//
// Deconstructor ...
void ~XSCHttp()
{
}
//
// START Getter(s)/Setter(s) ...
//
//
// Path ...
void Path(string value)
{
mPath = value;
}
string Path()
{
return mPath;
}
//
// Timeout ...
void Timeout(int value)
{
mTimeout = value;
}
//
int Timeout()
{
return mTimeout;
}
//
// Error ...
int Error()
{
return mError;
}
//
// Response ...
string Response()
{
return mResponse;
}
//
// END Getter(s)/Setter(s) ...
//
//
// START Provided Functions ...
//
//
// Send Global Request ...
int SendRequest(
X_HTTP_METHOD method, // Httm Request Method
const string url, // Server Address
const string headers, // Headers providing
const char &payload[], // the Data which needs to Send
char &response[], // Response of request
string responseHeaders, // Response Headers
int timeout = 500 // Timeout for response default is 500
)
{
//
int result = -1;
//
string strMethod = ToString(method);
if (StringLen(strMethod) == 0)
{
return result;
}
//
// Reset State ...
ResetState();
//
result = WebRequest(
strMethod,
url,
headers,
timeout,
payload,
response,
responseHeaders);
//
if (result < 0)
{
mError = GetLastError();
}
else
{
mResponse = CharArrayToString(response);
}
//
return result;
}
//
// Get Request ...
int GetRequest(
const string url, // Server Address
const string headers, // Headers providing
const char &payload[], // the Data which needs to Send
char &response[], // Response of request
string responseHeaders, // Response Headers
int timeout = 500 // Timeout for response default is 500
)
{
//
int result = SendRequest(
X_HTTP_GET,
url,
headers,
payload,
response,
responseHeaders,
timeout);
//
return result;
}
//
// Post Request ...
int PostRequest(
const string url, // Server Address
const string headers, // Headers providing
const char &payload[], // the Data which needs to Send
char &response[], // Response of request
string responseHeaders, // Response Headers
int timeout = 500 // Timeout for response default is 500
)
{
//
int result = SendRequest(
X_HTTP_POST,
url,
headers,
payload,
response,
responseHeaders,
timeout);
//
return result;
}
//
// Handle Download Specific URL Content to Specific Path and File Name ...
bool Download(
string url, // the URL address which going to download
string fileName // Specify Destination file name to Store Response
)
{
//
bool result = false;
//
string filePath = GetFilePath(fileName);
string cookie = NULL;
string referer = NULL;
int timeout = Timeout();
//
char payload[];
string headers;
char response[];
string responseHeaders;
//
// Send Request ...
int requestResult = GetRequest(
url,
headers,
payload,
response,
responseHeaders,
timeout);
//
// Define File Handler ...
int mFileHandler = FileOpen(
filePath,
FILE_WRITE | FILE_BIN);
if (mFileHandler == INVALID_HANDLE)
{
//
mError = GetLastError();
return result;
}
//
// Write Response to File ...
uint writed = FileWriteArray(
mFileHandler,
response,
0,
ArraySize(response));
FileFlush(mFileHandler);
FileClose(mFileHandler);
//
result = writed > 0;
//
return result;
}
//
// END Provided Functions ...
//
//
// Protected ...
protected:
//
// Destintion Folder Path ...
string mPath;
//
// WEB Request Timeout Value ...
int mTimeout;
//
// WEB Request's Response ...
string mResponse;
//
// Error Value ...
int mError;
//
// Private ...
private:
//
// Reset Errors State ...
void ResetState()
{
//
// Reset Errors ...
mError = -1;
mResponse = "";
ResetLastError();
}
//
// Generate Full File Path ...
string GetFilePath(string fileName)
{
//
string result = "";
//
result =
//
Path() + "\\" + fileName
//
;
//
return result;
}
};
//
// START Usefull Functions ...
//
//
// END Usefull Functions ...
//
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -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 <Trade/AccountInfo.mqh>
#include "../Libraries/x-saherelm.common.lib.mq5"
//
// END Import and Inclused requirements ...
//
//
// START Overrides ...
//
//
// END Overrides ...
//
//
// a Class for Manage Account ...
class XSCAccount
{
//
// Public ...
public:
//
// Constructor ...
void XSCAccount()
{
//
mAccountInfo = new CAccountInfo();
}
//
// Deconstructor ...
void ~XSCAccount()
{
}
//
// START Provided Functions ...
//
//
// User Account ...
long GetUserAccount()
{
return mAccountInfo.Login();
}
//
// Account Leverage ...
long GetLeverage()
{
return mAccountInfo.Leverage();
}
//
// Get Trade Expert State ...
bool CanExpertTrade()
{
return mAccountInfo.TradeExpert();
}
//
// User Account Trade Mopde (ENUM_ACCOUNT_TRADE_MODE) ...
// --------------------------
// ACCOUNT_TRADE_MODE_DEMO
// ACCOUNT_TRADE_MODE_CONTEST
// ACCOUNT_TRADE_MODE_REAL
ENUM_ACCOUNT_TRADE_MODE GetTradeMode()
{
return mAccountInfo.TradeMode();
}
//
// Get Account Balance ...
double GetBalance()
{
return mAccountInfo.Balance();
}
//
// Get the amount of give Credit ...
double GetCredit()
{
return mAccountInfo.Credit();
}
//
// Get the amount of current Profit on account ...
double GetProfit()
{
return mAccountInfo.Profit();
}
//
// Get the amount of current Equity on account ...
double GetEquity()
{
return mAccountInfo.Equity();
}
//
// Get the amount of reserved Margin ...
double GetMargin()
{
return mAccountInfo.Margin();
}
//
// Get the amount of free Margin ...
double GetFreeMargin()
{
return mAccountInfo.FreeMargin();
}
//
// Get the Level of Margin ...
double GetMarginLevel()
{
return mAccountInfo.MarginLevel();
}
//
// Get the Level Of Margin for a Deposit ...
double GetMarginCall()
{
return mAccountInfo.MarginCall();
}
//
// Get the Level of Margin for Stop out ...
double GetMarginStopOut()
{
return mAccountInfo.MarginStopOut();
}
//
// Get the Client Name ...
string GetName()
{
return mAccountInfo.Name();
}
//
// Get the Trade Server Name ...
string GetServerName()
{
return mAccountInfo.Server();
}
//
// Get deposit Currency Name ...
string GetCurrency()
{
return mAccountInfo.Currency();
}
//
// Get the Company Name that serves an Account ...
string GetCompany()
{
return mAccountInfo.Company();
}
//
// Calculate Profits for the current account based on passed parameters ...
double CalculateTradeProfit(
const string symbol, // trading symbol
ENUM_ORDER_TYPE type, // order type
double volume, // volume
double entry, // open price
double exit // close price
)
{
//
double result = mAccountInfo.OrderProfitCheck(
symbol,
type,
volume,
entry,
exit);
//
return result;
}
//
// Calculate amount of margin which required for trade operation ...
double CalculateMarging(
const string symbol, // trading symbol
ENUM_ORDER_TYPE type, // order type
double volume, // volume
double entry // open price
)
{
//
double result = mAccountInfo.MarginCheck(
symbol,
type,
volume,
entry);
//
return result;
}
//
// Calculate amount of free margin left after trade operation ...
double CalculateFreeMarging(
const string symbol, // trading symbol
ENUM_ORDER_TYPE type, // order type
double volume, // volume
double entry // open price
)
{
//
double result = mAccountInfo.FreeMarginCheck(
symbol,
type,
volume,
entry);
//
return result;
}
//
// Calculate the Maximum possible volume of trade operation ...
double CalculateMaxVolume(
const string symbol, // trading symbol
ENUM_ORDER_TYPE type, // order type
double entry, // open price
double percent = 100 // percent of available margin
)
{
//
double result = mAccountInfo.MaxLotCheck(
symbol,
type,
entry,
percent);
//
return result;
}
//
// Calculate Point Value for Given Symbol based on Account ...
double GetPointValue(
string symbol // trading symbol
)
{
//
double result = 0;
//
double tickSize = SymbolInfoDouble(symbol, SYMBOL_TRADE_TICK_SIZE);
double tickValue = SymbolInfoDouble(symbol, SYMBOL_TRADE_TICK_VALUE);
double point = SymbolInfoDouble(symbol, SYMBOL_POINT);
//
double ticksPerPoint = tickSize / point;
//
result = tickValue / ticksPerPoint;
//
return result;
}
//
// Calculate Risk Amount based on account Currency by Providing:
// Points and Volume ...
double CalculateRiskAmount(
string symbol, // trading symbol
double points, // amount of Risk Points
double volume // position Volume
)
{
//
double result = 0;
//
double pointValue = GetPointValue(symbol);
//
result = pointValue * volume * points;
//
return result;
}
//
// Calculate Risk Points based on account Currency by Providing:
// Volume and Amount ...
double CalculateRiskPoints(
string symbol, // trading symbol
double volume, // position Volume
double amount // amount of Risk based on Account Currency
)
{
//
double result = 0;
//
double pointValue = GetPointValue(symbol);
//
result = amount / (pointValue * volume);
//
return result;
}
//
// Calculate Volume based on account Currency by Providing:
// Amount and Risk Points ...
double CalculateVolume(
string symbol, // trading symbol
double amount, // amount of Risk based on Account Currency
double points // amount of Risk Points
)
{
//
double result = 0;
//
points =
points <= 0
? 10
: points;
//
double pointValue = GetPointValue(symbol);
//
result = amount / (pointValue * points);
//
return result;
}
//
// END Provided Functions ...
//
//
// Protected ...
protected:
//
// Private ...
private:
//
// Account Info ...
CAccountInfo mAccountInfo;
};
//
// START Usefull Functions ...
//
//
// END Usefull Functions ...
//
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,209 @@
///////////////////////////////////////////////////////
//
// SaherElm IT Center MQL5 Class Library
// ----------------------------------------------
// Name: XSCBaseHelper
// Description: provides all Base Indicator
// Helper requirements ...
//
//
// Maintainer:
// ------------
// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com)
//
//////////////////////////////////////////////////////
//
// Global Properties ...
#property library
#property copyright "Copyright 2023, SaherElm IT Center"
#property link "https://www.saherelm.ir"
#property version "1.00"
#property strict
//
// START Definitions ...
//
//
// END Definitions ...
//
//
// START Import and Inclused requirements ...
//
//
// Includes ...
#include "../Libraries/x-saherelm.common.lib.mq5"
//
// END Import and Inclused requirements ...
//
//
// START Overrides ...
//
//
// END Overrides ...
//
//
// a Class for Handle base requirements ...
// for indicators ...
class XSCBaseHelper
{
//
// Public ...
public:
//
// Constructor ...
void XSCBaseHelper(
string symbol, // Trading Symbol
ENUM_TIMEFRAMES period // Trading Time Frame
)
{
//
mSymbol = symbol;
mPeriod = period;
//
LoopBack(52);
}
//
// Deconstructor ...
void ~XSCBaseHelper()
{
IndicatorRelease(mHandler);
}
//
// START Properties ...
//
//
// Loopback Bars ...
void LoopBack(int value)
{
mLoopbackBars = value;
}
int Loopback()
{
return mLoopbackBars;
}
//
// Symbol ...
string GetSymbol()
{
return mSymbol;
}
//
// Period ...
ENUM_TIMEFRAMES GetPeriod()
{
return mPeriod;
}
//
// Tag ...
string GetTag()
{
return mTag;
}
//
// Retrieve Bars ...
int GetBars()
{
//
int result =
Bars(
mSymbol,
mPeriod);
//
return result;
}
//
int GetCalculatedBars()
{
return BarsCalculated(mHandler);
}
//
// END Properties ...
//
//
// START Provided Functions ...
//
//
// Prepare Tag ...
virtual void PrepareTag() {}
//
// Reading Buffers based on Given Bar Index ...
virtual void Calculate(
int barIndex // Given Bar Index
);
//
// Retrieve MAx Required Length for Calculations ...
virtual int GetMaxLength();
//
// END Provided Functions ...
//
//
// Protected ...
protected:
//
string GetTagPrefix()
{
//
string result = "(" + mSymbol + ")(" + ToString(mPeriod) + ")";
//
return result;
}
//
// Symbol ...
string mSymbol;
//
// Period ...
ENUM_TIMEFRAMES mPeriod;
//
// Indicator Handler ...
int mHandler;
//
// Number Of Items Read Per Tick ...
int mLoopbackBars;
//
// Tag Identifier ...
string mTag;
//
// Private ...
private:
//
};
//
// START Usefull Functions ...
//
//
// END Usefull Functions ...
//
@@ -0,0 +1,304 @@
///////////////////////////////////////////////////////
//
// SaherElm IT Center MQL5 Class Library
// ----------------------------------------------
// Name: XSCEABaseProvider
// Description: provides base requirements for
// Specific Sgnal Provider ...
//
//
// Maintainer:
// ------------
// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com)
//
//////////////////////////////////////////////////////
//
// Global Properties ...
#property library
#property copyright "Copyright 2023, SaherElm IT Center"
#property link "https://www.saherelm.ir"
#property version "1.00"
#property strict
//
// START Import and Inclused requirements ...
//
//
// Includes ...
#include "../Libraries/x-saherelm.log.lib.mq5"
#include "../Libraries/x-saherelm.draw.lib.mq5"
#include "../Libraries/x-saherelm.models.lib.mq5"
#include "../Libraries/x-saherelm.common.lib.mq5"
//
// END Import and Inclused requirements ...
//
//
// START Definitions ...
//
//
// Notified a Signal was Appears ...
typedef void (*OnSignal)(
XSignal &signal);
//
// Notified a Guard Appears ...
typedef void (*OnGuard)(XGuard &guard);
//
// END Definitions ...
//
//
// START Overrides ...
//
//
// END Overrides ...
//
//
// a Base Class for All of our EA's ...
class XSCEABaseProvider
{
//
// Public ...
public:
//
// Constructor ...
void XSCEABaseProvider()
{
mSymbol = _Symbol;
mPeriod = _Period;
}
void XSCEABaseProvider(
string symbol,
ENUM_TIMEFRAMES period)
{
//
mSymbol = symbol;
mPeriod = period;
//
mTag = mSymbol + "," + ToString(mPeriod);
//
mIsInTestMode = IsRunningOnTestMode();
}
//
// Deconstructor ...
void ~XSCEABaseProvider()
{
}
//
bool CanIgnoreTick() {
//
mIsNewCandle = IsNewCandle(
mSymbol,
mPeriod);
bool result = mIsInTestMode
? !mIsNewCandle
: !mIsNewCandle && mWaitUntilNewCandle;
//
return result;
}
//
// Prepare State ...
void OnTick()
{
//
mIsNewCandle = IsNewCandle(
mSymbol,
mPeriod);
mCanIgnoreTick = mIsInTestMode
? !mIsNewCandle
: !mIsNewCandle && mWaitUntilNewCandle;
//
ProcessBuffers();
//
if (mCanIgnoreTick)
{
return;
}
//
mWaitUntilNewCandle = false;
//
ProcessTick();
}
//
virtual void PrepareTag();
//
// Initialize Indicators and Requirements ...
virtual bool Init();
//
virtual int GetMaxLength();
//
virtual int GetCalculatedBars();
//
// Handle Update Buffers ...
virtual void ProcessBuffers()
{
return;
}
//
// Handle On Tick Event ...
virtual void ProcessTick()
{
return;
}
//
// Check for Guards ...
virtual bool GuardCheck(XGuard &guards[]);
//
// Add Specific On Signal Event Handler ...
int AddOnSignalEventHandler(OnSignal handler)
{
//
ArrayResize(
mSignalEventHandlers,
ArraySize(mSignalEventHandlers) + 1);
//
int result = ArraySize(mSignalEventHandlers) - 1;
mSignalEventHandlers[result] = handler;
//
return result;
}
//
// Remove All On Signal Event Handler ...
void ReoveOnSignalEventHandlers()
{
//
ArrayFree(mSignalEventHandlers);
}
//
// Notify a Signal Found on all Event Listeners ...
void NotifyOnSignalEvent(XSignal &info)
{
//
int listenerCount = ArraySize(mSignalEventHandlers);
if (listenerCount <= 0)
{
return;
}
//
// Loop Through Listeners ...
for (int i = 0; i < listenerCount; i++)
{
//
OnSignal listener = mSignalEventHandlers[i];
//
listener(info);
}
}
//
// Protected ...
protected:
//
string mSymbol;
//
ENUM_TIMEFRAMES mPeriod;
//
string mTag;
//
bool mIsNewCandle;
bool mIsInTestMode;
bool mCanIgnoreTick;
bool mWaitUntilNewCandle;
//
// Private ...
private:
//
// Signal Event Handlers ...
OnSignal mSignalEventHandlers[];
};
//
// START Definitions ...
//
//
// Model Signal Providers Definitions ...
struct XBaseSignalProvider
{
//
// Provider use Which Symbol ...
string symbol;
//
// Provider use Which Time Frame ...
ENUM_TIMEFRAMES period;
//
// Risk Amount Per Trades Related to Time Frames ...
// Percent of Available Balance ...
double riskAmount;
//
// Desired Magic Number ...
ulong magicNumber;
};
//
struct XLastSignal
{
datetime at;
string provider;
};
//
// END Definitions ...
//
//
// START Usefull Functions ...
//
//
// Add Specific Provider to List ...
void Add(
XBaseSignalProvider &item, // item want to add
XBaseSignalProvider &buffer[] // Destination buffer
)
{
//
ArrayResize(
buffer,
ArraySize(buffer) + 1);
//
buffer[ArraySize(buffer) - 1] = item;
}
//
// END Usefull Functions ...
//
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,378 @@
///////////////////////////////////////////////////////
//
// SaherElm IT Center MQL5 Expert Advisor
// ----------------------------------------
// Name: X121EA
// Description: this is an expert controller
// advisors which provides a mechanism for use them ...
//
//
// Maintainer:
// ------------
// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com)
//
//////////////////////////////////////////////////////
//
// Global Properties ...
#property copyright "Copyright 2023, SaherElm IT Center"
#property link "https://saherelm.ir"
#property version "1.00"
#property description "SaherElm X121EA"
#property strict
//
// START Definitions ...
//
//
#define ShortName "X121EA"
//
// END Definitions ...
//
//
// START Inputs ...
//
//
// EA ...
input group "Common";
input bool xEAEnable = true; // Enable EA
input int xEASlippage = 10; // Slippgae
input ulong xEAMagicNumber = 1604056; // Magic Number
//
// Providers ...
input group "Providers";
input bool xEAUseCurrentConfig = true; // Use Only Current Config
input string xEAProvidersConfiguration = ""; // Providers Configuration
input string xEADefaultSignalProviders = "X786,X92,X110,X121,X128"; // Default Allowed Signal Providers
//
// Signals ...
input group "Signals";
input bool xEAEnableLongs = true; // Enable Long Trades
input bool xEAEnableShorts = true; // Enable Short Trades
//
// Risk Management ...
input group "Risk Management";
input int xEAMaxOpenPositions = 15; // Max Allowed Open Trades
input double xEAMinRiskAmountPerTrade = 0.001; // Min Risk Amount Per Trade
input double xEAMaxAllowedDrawDownFactor = 0.001; // Max Allowed Drawdown Factor
//
// Alerts ...
input group "Alerts";
input bool xEAEnableAlerts = true; // Enable Events Alert
input bool xEAEnableHourlyAlerts = false; // Send Alert on each new Hour
input bool xEAEnableDailyAlerts = false; // Send Alert on each new Day
input bool xEAEnableWeeklyAlerts = false; // Send Alert on each new Week
input bool xEAEnableMonthlyAlerts = false; // Send Alert on each new Month
//
// END Inputs ...
//
//
// START Including Providers ...
//
//
// Logger Library ...
#include "../Libraries/x-saherelm.log.lib.mq5"
#include "../Classes/x-saherelm.x121.xea.class.mq5"
//
// END Including Providers ...
//
//
// START Global Definitions: Variables, Properties and etc ...
//
//
XSCX121EA *mX121EA;
//
// END Global Definitions: Variables, Properties and etc ...
//
//
// START Event Handlers ...
//
//
// Initialization ...
int OnInit()
{
//
logTag = ShortName;
drawPrefix = logTag;
alertPrefix = logTag;
//
// Validate Inputs ...
if (!ValidateInputs())
{
return INIT_PARAMETERS_INCORRECT;
}
//
bool isInit = InitEAInstance();
if (!isInit)
{
return INIT_FAILED;
}
//
// Init Succeed ...
return INIT_SUCCEEDED;
}
//
// DeInitialization ...
void OnDeinit(const int reason)
{
//
// REASON_PROGRAM 0 The EA has stopped working calling the ExpertRemove() function
// REASON_REMOVE 1 Program removed from a chart
// REASON_RECOMPILE 2 Program recompiled
// REASON_CHARTCHANGE 3 A symbol or a chart period is changed
// REASON_CHARTCLOSE 4 Chart closed
// REASON_PARAMETERS 5 Inputs changed by a user
// REASON_ACCOUNT 6 Another account has been activated or reconnection to the trade server has occurred due to changes in the account settings
// REASON_TEMPLATE 7 Another chart template applied
// REASON_INITFAILED 8 The OnInit() handler returned a non-zero value
// REASON_CLOSE 9 Terminal closed
//
// De Initialize XEA Providers ...
delete mX121EA;
}
//
// On Tick Handler ...
void OnTick()
{
//
// Prevent Going Forward if user Disable it ...
if (xEAEnable)
{
mX121EA.OnTick();
}
}
//
// Handle Trade Events ...
void OnTrade()
{
mX121EA.OnTrade();
}
//
// Handle Signal Event ...
void OnSignalConditionsRecieved(X121MarketConditions &info)
{
}
//
// Handle StopLoss Event ...
void OnStopLossTriggered(const XDeal &deal)
{
}
//
// Handle TakeProfit Event ...
void OnTakeProfitTriggered(const XDeal &deal)
{
}
//
// Handle Deals Changed Event ...
void OnDealsChangedHandler(int count)
{
}
//
// Handle Order Changed Event ...
void OnOrdersChangedHandler(int count)
{
}
//
// Handle Position Changed Event ...
void OnPositionsChangedHandler(int count)
{
}
//
// Handle Trade State Changed ...
void OnTradeStateChangedHandler(const XOnTradeHandlerState &state)
{
}
//
// END Event Handlers ...
//
//
// START Functions ...
//
//
// Validate Input Args for Initialization ...
bool ValidateInputs()
{
//
bool result = true;
//
// Validate Args ...
result =
//
xEASlippage > 0 &&
xEAMagicNumber > 0 &&
xEAMinRiskAmountPerTrade > 0 &&
StringLen(xEADefaultSignalProviders) > 0
//
// TODO: add new validations here ...
//
;
//
// Validate Providers ...
if (result)
{
//
string providers[];
SplitContent(
providers,
xEADefaultSignalProviders);
//
int providersCount = ArraySize(providers);
if (providersCount <= 0)
{
//
result = false;
return result;
}
//
string allProviders[];
GetAllProviders(allProviders);
//
bool hasError = false;
for (int i = 0; i < providersCount; i++)
{
//
string iProvider = providers[i];
if (!Contains(iProvider, allProviders))
{
//
hasError = true;
break;
}
}
//
if (hasError)
{
//
result = false;
return result;
}
}
//
// Logging State ...
string message = "Validation of (" + logTag + ") Inputs " + (result ? "Succeeded" : "Failed") + " ...";
LogMessage(message);
//
return result;
}
//
// Initialize X121EA Class Instances ...
bool InitEAInstance()
{
//
bool result = false;
//
X121SignalProvider providers[];
//
// Validatie Providers Configuration ...
if (xEAUseCurrentConfig)
{
//
// Here we Ignore xEAProvidersConfiguration ...
// Have to Create a Default Provider Structure and Attached it to X121EA Instance ...
X121SignalProvider provider;
//
provider.symbol = _Symbol;
provider.period = _Period;
provider.riskAmount = xEAMinRiskAmountPerTrade;
//
string signalProviders[];
SplitContent(
signalProviders,
xEADefaultSignalProviders);
//
Copy(
signalProviders,
provider.providers);
//
// Now add Default Provider to Providers Array ...
Add(
provider,
providers);
}
else
{
//
// TODO: Here we must Implement all mechanism to Extract Provider Configurations and
// Add them one by one to XEA Instance ...
}
//
mX121EA = new XSCX121EA(
_Symbol,
_Period,
xEAMagicNumber,
xEASlippage,
OnStopLossTriggered,
OnTakeProfitTriggered,
OnDealsChangedHandler,
OnOrdersChangedHandler,
OnPositionsChangedHandler,
OnTradeStateChangedHandler,
OnSignalConditionsRecieved);
//
mX121EA.EnableLongs(xEAEnableLongs);
mX121EA.EnableShorts(xEAEnableShorts);
mX121EA.MaxAllowedPositions(xEAMaxOpenPositions);
mX121EA.MaxAllowedDrawDownFactor(xEAMaxAllowedDrawDownFactor);
//
// Attach Providers to EA Instance ...
int providersCount = ArraySize(providers);
int addedProviders = mX121EA.AddProviders(providers);
result = addedProviders == providersCount;
//
return result;
}
//
// END Functions ...
//
@@ -0,0 +1,446 @@
///////////////////////////////////////////////////////
//
// SaherElm IT Center MQL5 Helper Class Library
// ----------------------------------------------
// Name: XSCXAMAHelper
// Description: provides all Indicator
// Helper requirements ...
//
//
// Maintainer:
// ------------
// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com)
//
//////////////////////////////////////////////////////
//
// Global Properties ...
#property library
#property copyright "Copyright 2023, SaherElm IT Center"
#property link "https://www.saherelm.ir"
#property version "1.00"
#property strict
//
// START Definitions ...
//
//
// Inputs ...
struct XAMAInputs
{
//
// Makret ...
int length; // Length
int fastEMA; // Fast EMA Length
int slowEMA; // Slow EMA Length
int maShift; // Shift
ENUM_APPLIED_PRICE appliedTo; // Applied To
//
// Presentation ...
bool showLine; // Show Line
};
//
// Index of Lines ...
enum ENUM_XAMA_BUFFERS
{
//
// Main Requirements ...
XAMA_LINE = 0,
XAMA_STATE_LINE = 1,
};
//
// XAMA Indicator States ...
enum ENUM_XAMA_STATES
{
X_XAMA_BULLISH = 0,
X_XAMA_BEARISH = 2,
X_XAMA_NEUTURAL = 1,
};
//
// Retrieve Info Model ...
struct XAMAInfo
{
//
// Symbol ...
string symbol;
//
// Period ...
ENUM_TIMEFRAMES period;
//
// Bar Time ...
datetime barTime;
//
// Bar Index ...
int barIndex;
//
// Values ...
double value;
//
double values[];
double states[];
//
// State ...
ENUM_XAMA_STATES state;
//
// Conditions ...
//
// Detect Trend is Bullish or not ...
bool isBullish;
//
// Detect Trend is Switched to Bullish Or not ...
bool isSwitchedBullish;
//
// Detect Trend is Bearish or not ...
bool isBearish;
//
// Detect Trend is Switched to Bearish Or not ...
bool isSwitchedBearish;
//
// Detect Trend is Neutural or not ...
bool isNeutural;
//
// Detect Trend is Switched to Neutural Or not ...
bool isSwitchedNeutural;
};
//
// END Definitions ...
//
//
// START Import and Inclused requirements ...
//
//
// Includes ...
#include "../Libraries/x-saherelm.common.lib.mq5"
#include "../Classes/x-saherelm.xhelper.class.mq5"
//
// END Import and Inclused requirements ...
//
//
// START Overrides ...
//
//
// END Overrides ...
//
//
// a Class for Helping Indicators Requirements ...
class XSCXAMAHelper : public XSCBaseHelper
{
//
// Public ...
public:
//
// Buffers ...
double valueBuffer[];
double stateBuffer[];
//
// Constructor ...
void XSCXAMAHelper(
string symbol, // Trading Symbol
ENUM_TIMEFRAMES period // Trading Time Frame
) : XSCBaseHelper(symbol, period)
{
PrepareTag();
}
//
// Deconstructor ...
void ~XSCXAMAHelper()
{
}
//
// START Properties ...
//
//
// END Properties ...
//
//
// START Provided Functions ...
//
//
// Prepare Tag ...
virtual void PrepareTag()
{
mTag = "XAMA" + GetTagPrefix();
}
//
virtual int GetMaxLength()
{
//
int result = -1;
//
result = mLength;
//
return result;
}
//
// Initial Indicator Handler ...
bool Init()
{
//
bool result = false;
//
// Validate Args ...
result =
//
(mLength >= 2)
//
;
if (!result)
{
return false;
}
//
// Initialize Handler ...
mHandler = iCustom(
//
mSymbol,
mPeriod,
"x-saherelm.x121.xama",
//
// Inputs ...
//
// Makret ...
"",
//
// Length ...
mLength,
//
// Fast EMA Length ...
mFastEMA,
//
// Slow EMA Length ...
mSlowEMA,
//
// Shift ...
mMaShift,
//
// Applied To ...
mAppliedTo,
//
// Presentation ...
"",
//
// Show Line ...
mShowLine
//
);
result = mHandler != INVALID_HANDLE;
//
return result;
}
//
// Retrieve Current Config ...
XAMAInputs GetConfig()
{
//
XAMAInputs result;
//
result.length = mLength;
result.fastEMA = mFastEMA;
result.slowEMA = mSlowEMA;
result.maShift = mMaShift;
result.appliedTo = mAppliedTo;
result.showLine = mShowLine;
//
return result;
}
//
// Set Config ...
bool SetConfig(XAMAInputs &config)
{
//
bool result = false;
//
mLength = config.length;
mFastEMA = config.fastEMA;
mSlowEMA = config.slowEMA;
mMaShift = config.maShift;
mAppliedTo = config.appliedTo;
mShowLine = config.showLine;
//
result = Init();
//
return result;
}
//
// Reading Buffers based on Given Bar Index ...
virtual void Calculate(
int barIndex // Given Bar Index
)
{
//
// VALUE ...
ArraySetAsSeries(valueBuffer, true);
CopyBuffer(
mHandler,
XAMA_LINE,
barIndex,
mLoopbackBars,
valueBuffer);
//
// STATE ...
ArraySetAsSeries(stateBuffer, true);
CopyBuffer(
mHandler,
XAMA_STATE_LINE,
barIndex,
mLoopbackBars,
stateBuffer);
}
//
// Retrieve Info at Specific Bar Index ...
XAMAInfo GetInfo(
int barIndex // Given Bar Index
)
{
//
XAMAInfo result;
//
if (barIndex < 0)
{
barIndex = 0;
}
//
// Do Calculations ...
Calculate(barIndex);
//
// Generate Candle Time ...
datetime barTime = GetCandleTime(
mSymbol,
mPeriod,
barIndex);
//
// Fill Result ...
result.symbol = mSymbol;
result.period = mPeriod;
result.barTime = barTime;
result.barIndex = barIndex;
//
result.value = valueBuffer[barIndex];
//
Copy(
valueBuffer,
result.values);
//
Copy(
stateBuffer,
result.states);
//
ENUM_XAMA_STATES state = (ENUM_XAMA_STATES)stateBuffer[barIndex];
ENUM_XAMA_STATES prevState = (ENUM_XAMA_STATES)stateBuffer[barIndex + 1];
result.state = state;
//
result.isBullish = state == X_XAMA_BULLISH;
result.isBearish = state == X_XAMA_BEARISH;
result.isNeutural = state == X_XAMA_NEUTURAL;
//
result.isSwitchedBullish =
state == X_XAMA_BULLISH && prevState != X_XAMA_BULLISH;
result.isSwitchedBearish =
state == X_XAMA_BEARISH && prevState != X_XAMA_BEARISH;
result.isSwitchedNeutural =
state == X_XAMA_NEUTURAL && prevState != X_XAMA_NEUTURAL;
//
return result;
}
//
// END Provided Functions ...
//
//
// Protected ...
protected:
//
// Private ...
private:
//
// Indicator Properties ...
//
// Market ...
//
// Length ...
int mLength;
//
// Fast EMA Length ...
int mFastEMA;
//
// Slow EMA Length ...
int mSlowEMA;
//
// Shift ...
int mMaShift;
//
// Applied To ...
ENUM_APPLIED_PRICE mAppliedTo;
//
// Presentation ...
//
// Show Line ...
bool mShowLine;
};
//
// START Usefull Functions ...
//
//
// END Usefull Functions ...
//
@@ -0,0 +1,293 @@
///////////////////////////////////////////////////////
//
// SaherElm IT Center MQL5 Helper Class Library
// ----------------------------------------------
// Name: XSCXCCHelper
// Description: provides all Indicator
// Helper requirements ...
//
//
// Maintainer:
// ------------
// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com)
//
//////////////////////////////////////////////////////
//
// Global Properties ...
#property library
#property copyright "Copyright 2023, SaherElm IT Center"
#property link "https://www.saherelm.ir"
#property version "1.00"
#property strict
//
// START Definitions ...
//
//
struct XCCInputs
{
//
// Chart Style ...
color upColor; // Up Color
color downColor; // Down Color
color lineColor; // Line mode and Doji candlestick Color
color bearishColor; // Bullish Color
color bullishColor; // Bearish Color
color volumesColor; // Volumes Color
//
// Presentation ...
bool showCandles; // Show Candles
};
//
// END Definitions ...
//
//
// START Import and Inclused requirements ...
//
//
// Includes ...
#include "../Libraries/x-saherelm.common.lib.mq5"
#include "../Classes/x-saherelm.xhelper.class.mq5"
//
// END Import and Inclused requirements ...
//
//
// START Overrides ...
//
//
// END Overrides ...
//
//
// a Class for Helping Indicators Requirements ...
class XSCXCCHelper : public XSCBaseHelper
{
//
// Public ...
public:
//
// Constructor ...
void XSCXCCHelper(
string symbol, // Trading Symbol
ENUM_TIMEFRAMES period // Trading Time Frame
) : XSCBaseHelper(symbol, period)
{
PrepareTag();
}
//
// Deconstructor ...
void ~XSCXCCHelper()
{
}
//
// START Properties ...
//
//
// Show Candles ...
bool ShowCandles(
bool show // Show or Hide
)
{
//
bool result = false;
//
if (mShowCandles == show)
{
return true;
}
//
mShowCandles = show;
result = Init();
//
return result;
}
//
// END Properties ...
//
//
// START Provided Functions ...
//
//
// Prepare Tag ...
virtual void PrepareTag()
{
mTag = "XCC" + GetTagPrefix();
}
//
// Reading Buffers based on Given Bar Index ...
virtual void Calculate(
int barIndex // Given Bar Index
) {}
//
virtual int GetMaxLength()
{
//
int result = -1;
//
result = 2;
//
return result;
}
//
// Initial Indicator Handler ...
bool Init()
{
//
bool result = false;
//
// Initialize Handler ...
mHandler = iCustom(
//
mSymbol,
mPeriod,
"x-saherelm.x121.xcc",
//
// Inputs ...
//
// Chart Style ...
"",
//
// Up Color ...
mUpColor,
//
// Down Color ...
mDownColor,
//
// Line mode and Doji candlestick Color ...
mLineColor,
//
// Bullish Color ...
mBearishColor,
//
// Bearish Color ...
mBullishColor,
//
// Volumes Color ...
mVolumesColor,
//
// Presentation ...
"",
//
// Show Candles ...
mShowCandles
//
);
result = mHandler != INVALID_HANDLE;
//
return result;
}
//
// Retrieve Current Config ...
XCCInputs GetConfig()
{
//
XCCInputs result;
//
result.upColor = mUpColor;
result.downColor = mDownColor;
result.lineColor = mLineColor;
result.bearishColor = mBearishColor;
result.bullishColor = mBullishColor;
result.volumesColor = mVolumesColor;
result.showCandles = mShowCandles;
//
return result;
}
//
// Set Config ...
bool SetConfig(XCCInputs &config)
{
//
bool result = false;
//
mUpColor = config.upColor;
mDownColor = config.downColor;
mLineColor = config.lineColor;
mBearishColor = config.bearishColor;
mBullishColor = config.bullishColor;
mVolumesColor = config.volumesColor;
mShowCandles = config.showCandles;
//
result = Init();
//
return result;
}
//
// END Provided Functions ...
//
//
// Protected ...
protected:
//
// Private ...
private:
//
// Indicator Properties ...
//
// Chart Style ...
//
// Up Color ...
color mUpColor;
//
// Down Color ...
color mDownColor;
//
// Line mode and Doji candlestick Color ...
color mLineColor;
//
// Bullish Color ...
color mBearishColor;
//
// Bearish Color ...
color mBullishColor;
//
// Volumes Color ...
color mVolumesColor;
//
// Presentation ...
//
// Show Candles ...
bool mShowCandles;
};
//
// START Usefull Functions ...
//
//
// END Usefull Functions ...
//
@@ -0,0 +1,612 @@
///////////////////////////////////////////////////////
//
// SaherElm IT Center MQL5 Helper Class Library
// ----------------------------------------------
// Name: XSCXCHEHelper
// Description: provides all Indicator
// Helper requirements ...
//
//
// Maintainer:
// ------------
// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com)
//
//////////////////////////////////////////////////////
//
// Global Properties ...
#property library
#property copyright "Copyright 2023, SaherElm IT Center"
#property link "https://www.saherelm.ir"
#property version "1.00"
#property strict
//
// START Definitions ...
//
//
// Inputs ...
struct XCHEInputs
{
//
// Market ...
int length; // Length
int loopback; // Loopback
double multiplier1; // 1st Multiplier
double multiplier2; // 2nd Multiplier
//
// Calculation ...
ENUM_APPLIED_PRICE upAppliedTo; // Up Zone Applied to
ENUM_APPLIED_PRICE downAppliedTo; // Down Zone Applied to
//
// Presentation ...
bool showLongExit1Line; // Show 1st Long Exit
bool showShortExit1Line; // Show 1st Short Exit
bool showLongExit2Line; // Show 2st Long Exit
bool showShortExit2Line; // Show 2st Short Exit
};
//
// Index of Lines ...
enum ENUM_XCHE_BUFFERS
{
//
// Main Requirements ...
XCHE_1ST_LONG_EXIT_LINE = 0,
XCHE_1ST_SHORT_EXIT_LINE = 1,
XCHE_2ND_LONG_EXIT_LINE = 2,
XCHE_2ND_SHORT_EXIT_LINE = 3,
};
//
// Retrieve Info Model ...
struct XCHEInfo
{
//
// Symbol ...
string symbol;
//
// Period ...
ENUM_TIMEFRAMES period;
//
// Bar Time ...
datetime barTime;
//
// Bar Index ...
int barIndex;
//
// Values ...
double longExit1;
double longExit2;
double shortExit1;
double shortExit2;
//
double le1[];
double le2[];
//
double se1[];
double se2[];
//
// Conditions ...
//
bool isLongExit1Start;
bool isShortExit1Start;
//
bool isLongExit2Start;
bool isShortExit2Start;
};
//
// END Definitions ...
//
//
// START Import and Inclused requirements ...
//
//
// Includes ...
#include "../Libraries/x-saherelm.common.lib.mq5"
#include "../Classes/x-saherelm.xhelper.class.mq5"
//
// END Import and Inclused requirements ...
//
//
// START Overrides ...
//
//
// END Overrides ...
//
//
// a Class for Helping Indicators Requirements ...
class XSCXCHEHelper : public XSCBaseHelper
{
//
// Public ...
public:
//
// Buffers ...
double longExit1Buffer[];
double shortExit1Buffer[];
double longExit2Buffer[];
double shortExit2Buffer[];
//
// Constructor ...
void XSCXCHEHelper(
string symbol, // Trading Symbol
ENUM_TIMEFRAMES period // Trading Time Frame
) : XSCBaseHelper(symbol, period)
{
PrepareTag();
}
//
// Deconstructor ...
void ~XSCXCHEHelper()
{
}
//
// START Properties ...
//
//
// Show 1st Long Exit ...
bool ShowLongExit1Line(
bool show // Show or Hide
)
{
//
bool result = false;
//
if (mShowLongExit1Line == show)
{
return true;
}
//
mShowLongExit1Line = show;
result = Init();
//
return result;
}
//
// Show 1st Short Exit ...
bool ShowShortExit1Line(
bool show // Show or Hide
)
{
//
bool result = false;
//
if (mShowShortExit1Line == show)
{
return true;
}
//
mShowShortExit1Line = show;
result = Init();
//
return result;
}
//
// Show 2st Long Exit ...
bool ShowLongExit2Line(
bool show // Show or Hide
)
{
//
bool result = false;
//
if (mShowLongExit2Line == show)
{
return true;
}
//
mShowLongExit2Line = show;
result = Init();
//
return result;
}
//
// Show 2st Short Exit ...
bool ShowShortExit2Line(
bool show // Show or Hide
)
{
//
bool result = false;
//
if (mShowShortExit1Line == show)
{
return true;
}
//
mShowShortExit1Line = show;
result = Init();
//
return result;
}
//
// END Properties ...
//
//
// START Provided Functions ...
//
//
// Prepare Tag ...
virtual void PrepareTag()
{
mTag = "XCHE" + GetTagPrefix();
}
//
virtual int GetMaxLength()
{
//
int result = -1;
//
result = MathMax(mLength, mLoopback);
//
return result;
}
//
// Initial Indicator Handler ...
bool Init()
{
//
bool result = false;
//
// Validate Inputs ...
//
//
result =
mLength >= 9 &&
mLoopback >= 0;
if (!result)
{
return result;
}
//
// Initialize Handler ...
mHandler = iCustom(
//
mSymbol,
mPeriod,
"x-saherelm.x121.xche",
//
// Inputs ...
//
// Market ...
"",
//
// Length ...
mLength,
//
// Loopback ...
mLoopback,
//
// 1st Multiplier ...
mMultiplier1,
//
// 2nd Multiplier ...
mMultiplier2,
//
// Calculation ...
"",
//
// Up Zone Applied to ...
mUpAppliedTo,
//
// Down Zone Applied to ...
mDownAppliedTo,
//
// Presentation ...
"",
//
// Show 1st Long Exit ...
mShowLongExit1Line,
//
// Show 1st Short Exit ...
mShowShortExit1Line,
//
// Show 2st Long Exit ...
mShowLongExit2Line,
//
// Show 2st Short Exit ...
mShowShortExit2Line
//
);
result = mHandler != INVALID_HANDLE;
//
return result;
}
//
// Retrieve Current Config ...
XCHEInputs GetConfig()
{
//
XCHEInputs result;
//
result.length = mLength;
result.loopback = mLoopback;
result.multiplier1 = mMultiplier1;
result.multiplier2 = mMultiplier2;
result.upAppliedTo = mUpAppliedTo;
result.downAppliedTo = mDownAppliedTo;
result.showLongExit1Line = mShowLongExit1Line;
result.showShortExit1Line = mShowShortExit1Line;
result.showLongExit2Line = mShowLongExit2Line;
result.showShortExit2Line = mShowShortExit2Line;
//
return result;
}
//
// Set Config ...
bool SetConfig(XCHEInputs &config)
{
//
bool result = false;
//
mLength = config.length;
mLoopback = config.loopback;
mMultiplier1 = config.multiplier1;
mMultiplier2 = config.multiplier2;
mUpAppliedTo = config.upAppliedTo;
mDownAppliedTo = config.downAppliedTo;
mShowLongExit1Line = config.showLongExit1Line;
mShowShortExit1Line = config.showShortExit1Line;
mShowLongExit2Line = config.showLongExit2Line;
mShowShortExit2Line = config.showShortExit2Line;
//
result = Init();
//
return result;
}
//
// Reading Buffers based on Given Bar Index ...
virtual void Calculate(
int barIndex // Given Bar Index
)
{
//
// LEVEL 1 ..
//
// LONG Exit ...
ArraySetAsSeries(longExit1Buffer, true);
CopyBuffer(
mHandler,
XCHE_1ST_LONG_EXIT_LINE,
barIndex,
mLoopbackBars,
longExit1Buffer);
//
// SHORT Exit ...
ArraySetAsSeries(shortExit1Buffer, true);
CopyBuffer(
mHandler,
XCHE_1ST_SHORT_EXIT_LINE,
barIndex,
mLoopbackBars,
shortExit1Buffer);
//
// LEVEL 2 ..
//
// LONG Exit ...
ArraySetAsSeries(longExit2Buffer, true);
CopyBuffer(
mHandler,
XCHE_2ND_LONG_EXIT_LINE,
barIndex,
mLoopbackBars,
longExit2Buffer);
//
// SHORT Exit ...
ArraySetAsSeries(shortExit2Buffer, true);
CopyBuffer(
mHandler,
XCHE_2ND_SHORT_EXIT_LINE,
barIndex,
mLoopbackBars,
shortExit2Buffer);
}
//
// Retrieve Info at Specific Bar Index ...
XCHEInfo GetInfo(
int barIndex // Given Bar Index
)
{
//
XCHEInfo result;
//
if (barIndex < 0)
{
barIndex = 0;
}
//
// Do Calculations ...
Calculate(barIndex);
//
// Generate Candle Time ...
datetime barTime = GetCandleTime(
mSymbol,
mPeriod,
barIndex);
//
// Fill Result ...
result.symbol = mSymbol;
result.period = mPeriod;
result.barTime = barTime;
result.barIndex = barIndex;
//
double longExit1 = longExit1Buffer[barIndex];
double longExit1Prev = longExit1Buffer[barIndex + 1];
double shortExit1 = shortExit1Buffer[barIndex];
double shortExit1Prev = shortExit1Buffer[barIndex + 1];
//
double longExit2 = longExit2Buffer[barIndex];
double longExit2Prev = longExit2Buffer[barIndex + 1];
double shortExit2 = shortExit2Buffer[barIndex];
double shortExit2Prev = shortExit2Buffer[barIndex + 1];
//
Copy(
longExit1Buffer,
result.le1);
Copy(
longExit2Buffer,
result.le2);
//
Copy(
shortExit1Buffer,
result.se1);
Copy(
shortExit2Buffer,
result.se2);
//
result.longExit1 = longExit1;
result.shortExit1 = shortExit1;
result.longExit2 = longExit2;
result.shortExit2 = shortExit2;
//
result.isLongExit1Start =
longExit1 != EMPTY_VALUE &&
longExit1Prev == EMPTY_VALUE;
//
result.isShortExit1Start =
shortExit1 != EMPTY_VALUE &&
shortExit1Prev == EMPTY_VALUE;
//
result.isLongExit2Start =
longExit2 != EMPTY_VALUE &&
longExit2Prev == EMPTY_VALUE;
//
result.isShortExit2Start =
shortExit2 != EMPTY_VALUE &&
shortExit2Prev == EMPTY_VALUE;
//
return result;
}
//
// END Provided Functions ...
//
//
// Protected ...
protected:
//
// Private ...
private:
//
// Indicator Properties ...
//
// Market ...
//
// Length ...
int mLength;
//
// Loopback ...
int mLoopback;
//
// 1st Multiplier ...
double mMultiplier1;
//
// 2nd Multiplier ...
double mMultiplier2;
//
// Calculation ...
//
// Up Zone Applied to ...
ENUM_APPLIED_PRICE mUpAppliedTo;
//
// Down Zone Applied to ...
ENUM_APPLIED_PRICE mDownAppliedTo;
//
// Presentation ...
//
// Show 1st Long Exit ...
bool mShowLongExit1Line;
//
// Show 1st Short Exit ...
bool mShowShortExit1Line;
//
// Show 2st Long Exit ...
bool mShowLongExit2Line;
//
// Show 2st Short Exit ...
bool mShowShortExit2Line;
};
//
// START Usefull Functions ...
//
//
// END Usefull Functions ...
//
@@ -0,0 +1,248 @@
///////////////////////////////////////////////////////
//
// SaherElm IT Center MQL5 Helper Class Library
// ----------------------------------------------
// Name: XSCXCTHelper
// Description: provides all Indicator
// Helper requirements ...
//
//
// Maintainer:
// ------------
// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com)
//
//////////////////////////////////////////////////////
//
// Global Properties ...
#property library
#property copyright "Copyright 2023, SaherElm IT Center"
#property link "https://www.saherelm.ir"
#property version "1.00"
#property strict
//
// START Definitions ...
//
//
struct XCTInputs
{
//
color clr;
ENUM_BASE_CORNER corner;
//
// Presentation ...
bool showCandleTime; // Show Candle Time
};
//
// END Definitions ...
//
//
// START Import and Inclused requirements ...
//
//
// Includes ...
#include "../Libraries/x-saherelm.common.lib.mq5"
#include "../Classes/x-saherelm.xhelper.class.mq5"
//
// END Import and Inclused requirements ...
//
//
// START Overrides ...
//
//
// END Overrides ...
//
//
// a Class for Helping Indicators Requirements ...
class XSCXCTHelper : public XSCBaseHelper
{
//
// Public ...
public:
//
// Constructor ...
void XSCXCTHelper(
string symbol, // Trading Symbol
ENUM_TIMEFRAMES period // Trading Time Frame
) : XSCBaseHelper(symbol, period)
{
PrepareTag();
}
//
// Deconstructor ...
void ~XSCXCTHelper()
{
}
//
// START Properties ...
//
//
// Show Candles ...
bool ShowCandleTime(
bool show // Show or Hide
)
{
//
bool result = false;
//
if (mShowCandleTime == show)
{
return true;
}
//
mShowCandleTime = show;
result = Init();
//
return result;
}
//
// END Properties ...
//
//
// START Provided Functions ...
//
//
// Prepare Tag ...
virtual void PrepareTag()
{
mTag = "XCT" + GetTagPrefix();
}
//
// Reading Buffers based on Given Bar Index ...
virtual void Calculate(
int barIndex // Given Bar Index
)
{
}
//
virtual int GetMaxLength()
{
//
int result = -1;
//
result = 1;
//
return result;
}
//
// Initial Indicator Handler ...
bool Init()
{
//
bool result = false;
//
// Initialize Handler ...
mHandler = iCustom(
//
mSymbol,
mPeriod,
"x-saherelm.x121.xct",
//
// Inputs ...
mClr,
mCorner,
//
// Presentation ...
"",
mShowCandleTime
//
);
result = mHandler != INVALID_HANDLE;
//
return result;
}
//
// Retrieve Current Config ...
XCTInputs GetConfig()
{
//
XCTInputs result;
//
result.clr = mClr;
result.corner = mCorner;
result.showCandleTime = mShowCandleTime;
//
return result;
}
//
// Set Config ...
bool SetConfig(XCTInputs &config)
{
//
bool result = false;
//
mClr = config.clr;
mCorner = config.corner;
mShowCandleTime = config.showCandleTime;
//
result = Init();
//
return result;
}
//
// END Provided Functions ...
//
//
// Protected ...
protected:
//
// Private ...
private:
//
// Indicator Properties ...
//
// Text Color ...
color mClr;
//
// Text Position ...
ENUM_BASE_CORNER mCorner;
//
// Presentation ...
//
// Show Candles ...
bool mShowCandleTime;
};
//
// START Usefull Functions ...
//
//
// END Usefull Functions ...
//
@@ -0,0 +1,470 @@
///////////////////////////////////////////////////////
//
// SaherElm IT Center MQL5 Helper Class Library
// ----------------------------------------------
// Name: XSCXDEMAHelper
// Description: provides all Indicator
// Helper requirements ...
//
//
// Maintainer:
// ------------
// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com)
//
//////////////////////////////////////////////////////
//
// Global Properties ...
#property library
#property copyright "Copyright 2023, SaherElm IT Center"
#property link "https://www.saherelm.ir"
#property version "1.00"
#property strict
//
// START Definitions ...
//
//
// Inputs ...
struct XDEMAInputs
{
//
// Makret ...
int length; // Length
int shift; // Shift
//
// Presentation ...
bool showDema; // Show Dema
bool showEMA; // Show EMA
bool showEMAOfEMA; // Show EMA of EMA
};
//
// Index of Lines ...
enum ENUM_XDEMA_BUFFERS
{
//
// Main Requirements ...
XDEMA_LINE = 0,
XDEMA_EMA_LINE = 2,
XDEMA_EMA_OF_EMA_LINE = 4,
};
//
// Retrieve Info Model ...
struct XDEMAInfo
{
//
// Symbol ...
string symbol;
//
// Period ...
ENUM_TIMEFRAMES period;
//
// Bar Time ...
datetime barTime;
//
// Bar Index ...
int barIndex;
//
// Values ...
double dema;
double ema;
double emaOfEma;
//
double demas[];
double emas[];
double emaOfEMAs[];
//
// Conditions ...
};
//
// END Definitions ...
//
//
// START Import and Inclused requirements ...
//
//
// Includes ...
#include "../Libraries/x-saherelm.common.lib.mq5"
#include "../Classes/x-saherelm.xhelper.class.mq5"
//
// END Import and Inclused requirements ...
//
//
// START Overrides ...
//
//
// END Overrides ...
//
//
// a Class for Helping Indicators Requirements ...
class XSCXDEMAHelper : public XSCBaseHelper
{
//
// Public ...
public:
//
// Buffers ...
double demaBuffer[];
double emaBuffer[];
double emaOfEMABuffer[];
//
// Constructor ...
void XSCXDEMAHelper(
string symbol, // Trading Symbol
ENUM_TIMEFRAMES period // Trading Time Frame
) : XSCBaseHelper(symbol, period)
{
PrepareTag();
}
//
// Deconstructor ...
void ~XSCXDEMAHelper()
{
}
//
// START Properties ...
//
//
// END Properties ...
//
//
// START Provided Functions ...
//
//
// Prepare Tag ...
virtual void PrepareTag()
{
mTag = "XDEMA" + GetTagPrefix();
}
//
virtual int GetMaxLength()
{
//
int result = -1;
//
result = mLength;
//
return result;
}
//
// Initial Indicator Handler ...
bool Init()
{
//
bool result = false;
//
// Validate Args ...
result =
//
(mLength >= 2 &&
mShift >= 0)
//
;
if (!result)
{
return false;
}
//
// Initialize Handler ...
mHandler = iCustom(
//
mSymbol,
mPeriod,
"x-saherelm.x121.xdema",
//
// Inputs ...
//
// Makret ...
"",
//
// Length ...
mLength,
//
// Shift ...
mShift,
//
// Presentation ...
"",
//
// Show Dema ...
mShowDema,
//
// Show EMA ...
mShowEMA,
//
// Show EMA of EMA ...
mShowEMAOfEMA
//
);
result = mHandler != INVALID_HANDLE;
//
return result;
}
//
// Retrieve Current Config ...
XDEMAInputs GetConfig()
{
//
XDEMAInputs result;
//
result.length = mLength;
result.shift = mShift;
result.showDema = mShowDema;
result.showEMA = mShowEMA;
result.showEMAOfEMA = mShowEMAOfEMA;
//
return result;
}
//
// Set Config ...
bool SetConfig(XDEMAInputs &config)
{
//
bool result = false;
//
mLength = config.length;
mShift = config.shift;
mShowDema = config.showDema;
mShowEMA = config.showEMA;
mShowEMAOfEMA = config.showEMAOfEMA;
//
result = Init();
//
return result;
}
//
// Show Dema ...
bool ShowDema(
bool show // Show or Hide
)
{
//
bool result = false;
//
if (mShowDema == show)
{
return true;
}
//
mShowDema = show;
result = Init();
//
return result;
}
//
// Show EMA ...
bool ShowEMA(
bool show // Show or Hide
)
{
//
bool result = false;
//
if (mShowEMA == show)
{
return true;
}
//
mShowEMA = show;
result = Init();
//
return result;
}
//
// Show EMA of EMA ...
bool ShowEMAOfEMA(
bool show // Show or Hide
)
{
//
bool result = false;
//
if (mShowEMAOfEMA == show)
{
return true;
}
//
mShowEMAOfEMA = show;
result = Init();
//
return result;
}
//
// Reading Buffers based on Given Bar Index ...
virtual void Calculate(
int barIndex // Given Bar Index
)
{
//
// DEMA ...
ArraySetAsSeries(demaBuffer, true);
CopyBuffer(
mHandler,
XDEMA_LINE,
barIndex,
mLoopbackBars,
demaBuffer);
//
// EMA ...
ArraySetAsSeries(emaBuffer, true);
CopyBuffer(
mHandler,
XDEMA_EMA_LINE,
barIndex,
mLoopbackBars,
emaBuffer);
//
// EMAOFEMA ...
ArraySetAsSeries(emaOfEMABuffer, true);
CopyBuffer(
mHandler,
XDEMA_EMA_OF_EMA_LINE,
barIndex,
mLoopbackBars,
emaOfEMABuffer);
}
//
// Retrieve Info at Specific Bar Index ...
XDEMAInfo GetInfo(
int barIndex // Given Bar Index
)
{
//
XDEMAInfo result;
//
if (barIndex < 0)
{
barIndex = 0;
}
//
// Do Calculations ...
Calculate(barIndex);
//
// Generate Candle Time ...
datetime barTime = GetCandleTime(
mSymbol,
mPeriod,
barIndex);
//
// Fill Result ...
result.symbol = mSymbol;
result.period = mPeriod;
result.barTime = barTime;
result.barIndex = barIndex;
//
result.ema = emaBuffer[barIndex];
result.dema = demaBuffer[barIndex];
result.emaOfEma = emaOfEMABuffer[barIndex];
//
Copy(
emaBuffer,
result.demas);
Copy(
demaBuffer,
result.emas);
Copy(
emaOfEMABuffer,
result.emaOfEMAs);
//
return result;
}
//
// END Provided Functions ...
//
//
// Protected ...
protected:
//
// Private ...
private:
//
// Indicator Properties ...
//
// Market ...
//
// Length ...
int mLength;
//
// Shift ...
int mShift;
//
// Presentation ...
//
// Show Dema ...
bool mShowDema;
//
// Show EMA ...
bool mShowEMA;
//
// Show EMA of EMA ...
bool mShowEMAOfEMA;
};
//
// START Usefull Functions ...
//
//
// END Usefull Functions ...
//
@@ -0,0 +1,733 @@
///////////////////////////////////////////////////////
//
// SaherElm IT Center MQL5 Helper Class Library
// ----------------------------------------------
// Name: XSCXFBBHelper
// Description: provides all Indicator
// Helper requirements ...
//
//
// Maintainer:
// ------------
// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com)
//
//////////////////////////////////////////////////////
//
// Global Properties ...
#property library
#property copyright "Copyright 2023, SaherElm IT Center"
#property link "https://www.saherelm.ir"
#property version "1.00"
#property strict
//
// START Definitions ...
//
//
// Inputs ...
struct XFBBInputs
{
//
// Market ...
//
// Length ...
int length;
//
// Multiplier ...
double multiplier;
//
// Applied To ...
ENUM_APPLIED_PRICE appliedTo;
//
// Presentation ...
//
// Show Base ...
bool showBase;
//
// Show Band ...
bool showBand;
//
// Show Golden Area ...
bool showGoldenArea;
//
// Show Other Levels ...
bool showOthers;
};
//
// Index of Lines ...
enum ENUM_XFBB_BUFFERS
{
//
// Main Requirements ...
XFBB_BASE_LINE = 0,
XFBB_BASE_STATE_LINE = 1,
XFBB_UP_BAND_LINE = 13,
XFBB_DOWN_BAND_LINE = 24,
//
XFBB_UP_1_LINE = 2,
XFBB_UP_2_LINE = 4,
XFBB_UP_3_LINE = 6,
XFBB_UP_4_LINE = 8,
XFBB_UP_5_LINE = 10,
//
XFBB_DOWN_1_LINE = 14,
XFBB_DOWN_2_LINE = 16,
XFBB_DOWN_3_LINE = 18,
XFBB_DOWN_4_LINE = 20,
XFBB_DOWN_5_LINE = 22,
};
//
// Retrieve Info Model ...
struct XFBBInfo
{
//
// Symbol ...
string symbol;
//
// Period ...
ENUM_TIMEFRAMES period;
//
// Bar Time ...
datetime barTime;
//
// Bar Index ...
int barIndex;
//
// Values ...
double base;
double baseState;
//
double upBand;
double downBand;
//
double up1;
double up2;
double up3;
double up4;
double up5;
//
double down1;
double down2;
double down3;
double down4;
double down5;
//
double bases[];
double baseStates[];
double upBands[];
double downBands[];
double up1s[];
double up2s[];
double up3s[];
double up4s[];
double up5s[];
double down1s[];
double down2s[];
double down3s[];
double down4s[];
double down5s[];
//
// Conditions ...
};
//
// END Definitions ...
//
//
// START Import and Inclused requirements ...
//
//
// Includes ...
#include "../Libraries/x-saherelm.common.lib.mq5"
#include "../Classes/x-saherelm.xhelper.class.mq5"
//
// END Import and Inclused requirements ...
//
//
// START Overrides ...
//
//
// END Overrides ...
//
//
// a Class for Helping Indicators Requirements ...
class XSCXFBBHelper : public XSCBaseHelper
{
//
// Public ...
public:
//
// Buffers ...
double baseBuffer[];
double baseStateBuffer[];
double upBandBuffer[];
double downBandBuffer[];
double up1Buffer[];
double up2Buffer[];
double up3Buffer[];
double up4Buffer[];
double up5Buffer[];
double down1Buffer[];
double down2Buffer[];
double down3Buffer[];
double down4Buffer[];
double down5Buffer[];
//
// Constructor ...
void XSCXFBBHelper(
string symbol, // Trading Symbol
ENUM_TIMEFRAMES period // Trading Time Frame
) : XSCBaseHelper(symbol, period)
{
PrepareTag();
}
//
// Deconstructor ...
void ~XSCXFBBHelper()
{
}
//
// START Properties ...
//
//
// END Properties ...
//
//
// START Provided Functions ...
//
//
// Prepare Tag ...
virtual void PrepareTag()
{
mTag = "XFBB" + GetTagPrefix();
}
//
virtual int GetMaxLength()
{
//
int result = -1;
//
result = mLength;
//
return result;
}
//
// Initial Indicator Handler ...
bool Init()
{
//
bool result = false;
//
// Validate Args ...
result =
//
(mLength >= 2 &&
mMultiplier >= 0)
//
;
if (!result)
{
return false;
}
//
// Initialize Handler ...
mHandler = iCustom(
//
mSymbol,
mPeriod,
"x-saherelm.x121.xfbb",
//
// Inputs ...
//
// Market ...
"",
//
// Length ...
mLength,
//
// Multiplier ...
mMultiplier,
//
// Applied To ...
mApliedTo,
//
// Presentation ...
"",
//
// Show Base ...
mShowBase,
//
// Show Band ...
mShowBand,
//
// Show Golden Area ...
mShowGoldenArea,
//
// Show Other Levels ...
mShowOthers
//
);
result = mHandler != INVALID_HANDLE;
//
return result;
}
//
// Retrieve Current Config ...
XFBBInputs GetConfig()
{
//
XFBBInputs result;
//
result.length = mLength;
result.multiplier = mMultiplier;
result.appliedTo = mApliedTo;
result.showBase = mShowBase;
result.showBand = mShowBand;
result.showGoldenArea = mShowGoldenArea;
result.showOthers = mShowOthers;
//
return result;
}
//
// Set Config ...
bool SetConfig(XFBBInputs &config)
{
//
bool result = false;
//
mLength = config.length;
mMultiplier = config.multiplier;
mApliedTo = config.appliedTo;
mShowBase = config.showBase;
mShowBand = config.showBand;
mShowGoldenArea = config.showGoldenArea;
mShowOthers = config.showOthers;
//
result = Init();
//
return result;
}
//
// Show Base ...
bool ShowBase(
bool show // Show or Hide
)
{
//
bool result = false;
//
if (mShowBase == show)
{
return true;
}
//
mShowBase = show;
result = Init();
//
return result;
}
//
// Show Band ...
bool ShowBand(
bool show // Show or Hide
)
{
//
bool result = false;
//
if (mShowBand == show)
{
return true;
}
//
mShowBand = show;
result = Init();
//
return result;
}
//
// Show Golden Area ...
bool ShowGoldenArea(
bool show // Show or Hide
)
{
//
bool result = false;
//
if (mShowGoldenArea == show)
{
return true;
}
//
mShowGoldenArea = show;
result = Init();
//
return result;
}
//
// Show Other Levels ...
bool ShowOthers(
bool show // Show or Hide
)
{
//
bool result = false;
//
if (mShowOthers == show)
{
return true;
}
//
mShowOthers = show;
result = Init();
//
return result;
}
//
// Reading Buffers based on Given Bar Index ...
virtual void Calculate(
int barIndex // Given Bar Index
)
{
//
// BASE ...
ArraySetAsSeries(baseBuffer, true);
CopyBuffer(
mHandler,
XFBB_BASE_LINE,
barIndex,
mLoopbackBars,
baseBuffer);
//
// BASE STATE ...
ArraySetAsSeries(baseStateBuffer, true);
CopyBuffer(
mHandler,
XFBB_BASE_STATE_LINE,
barIndex,
mLoopbackBars,
baseStateBuffer);
//
// UPBAND ...
ArraySetAsSeries(upBandBuffer, true);
CopyBuffer(
mHandler,
XFBB_UP_BAND_LINE,
barIndex,
mLoopbackBars,
upBandBuffer);
//
// DOWNBAND ...
ArraySetAsSeries(downBandBuffer, true);
CopyBuffer(
mHandler,
XFBB_DOWN_BAND_LINE,
barIndex,
mLoopbackBars,
downBandBuffer);
//
// UP 1 ...
ArraySetAsSeries(up1Buffer, true);
CopyBuffer(
mHandler,
XFBB_UP_1_LINE,
barIndex,
mLoopbackBars,
up1Buffer);
//
// UP 2 ...
ArraySetAsSeries(up2Buffer, true);
CopyBuffer(
mHandler,
XFBB_UP_2_LINE,
barIndex,
mLoopbackBars,
up2Buffer);
//
// UP 3 ...
ArraySetAsSeries(up3Buffer, true);
CopyBuffer(
mHandler,
XFBB_UP_3_LINE,
barIndex,
mLoopbackBars,
up3Buffer);
//
// UP 4 ...
ArraySetAsSeries(up4Buffer, true);
CopyBuffer(
mHandler,
XFBB_UP_4_LINE,
barIndex,
mLoopbackBars,
up4Buffer);
//
// UP 5 ...
ArraySetAsSeries(up5Buffer, true);
CopyBuffer(
mHandler,
XFBB_UP_5_LINE,
barIndex,
mLoopbackBars,
up5Buffer);
//
// DOWN 1 ...
ArraySetAsSeries(down1Buffer, true);
CopyBuffer(
mHandler,
XFBB_DOWN_1_LINE,
barIndex,
mLoopbackBars,
down1Buffer);
//
// DOWN 2 ...
ArraySetAsSeries(down2Buffer, true);
CopyBuffer(
mHandler,
XFBB_DOWN_2_LINE,
barIndex,
mLoopbackBars,
down2Buffer);
//
// DOWN 3 ...
ArraySetAsSeries(down3Buffer, true);
CopyBuffer(
mHandler,
XFBB_DOWN_3_LINE,
barIndex,
mLoopbackBars,
down3Buffer);
//
// DOWN 4 ...
ArraySetAsSeries(down4Buffer, true);
CopyBuffer(
mHandler,
XFBB_DOWN_4_LINE,
barIndex,
mLoopbackBars,
down4Buffer);
//
// DOWN 5 ...
ArraySetAsSeries(down5Buffer, true);
CopyBuffer(
mHandler,
XFBB_DOWN_5_LINE,
barIndex,
mLoopbackBars,
down5Buffer);
}
//
// Retrieve Info at Specific Bar Index ...
XFBBInfo GetInfo(
int barIndex // Given Bar Index
)
{
//
XFBBInfo result;
//
if (barIndex < 0)
{
barIndex = 0;
}
//
// Do Calculations ...
Calculate(barIndex);
//
// Generate Candle Time ...
datetime barTime = GetCandleTime(
mSymbol,
mPeriod,
barIndex);
//
// Fill Result ...
result.symbol = mSymbol;
result.period = mPeriod;
result.barTime = barTime;
result.barIndex = barIndex;
//
// values ...
result.base = baseBuffer[barIndex];
result.baseState = baseStateBuffer[barIndex];
result.upBand = upBandBuffer[barIndex];
result.downBand = downBandBuffer[barIndex];
result.up1 = up1Buffer[barIndex];
result.up2 = up2Buffer[barIndex];
result.up3 = up3Buffer[barIndex];
result.up4 = up4Buffer[barIndex];
result.up5 = up5Buffer[barIndex];
result.down1 = down1Buffer[barIndex];
result.down2 = down2Buffer[barIndex];
result.down3 = down3Buffer[barIndex];
result.down4 = down4Buffer[barIndex];
result.down5 = down5Buffer[barIndex];
//
Copy(
baseBuffer,
result.bases);
Copy(
baseStateBuffer,
result.baseStates);
Copy(
upBandBuffer,
result.upBands);
Copy(
downBandBuffer,
result.downBands);
Copy(
up1Buffer,
result.up1s);
Copy(
up2Buffer,
result.up2s);
Copy(
up3Buffer,
result.up3s);
Copy(
up4Buffer,
result.up4s);
Copy(
up5Buffer,
result.up5s);
Copy(
down1Buffer,
result.down1s);
Copy(
down2Buffer,
result.down2s);
Copy(
down3Buffer,
result.down3s);
Copy(
down4Buffer,
result.down4s);
Copy(
down5Buffer,
result.down5s);
//
return result;
}
//
// END Provided Functions ...
//
//
// Protected ...
protected:
//
// Private ...
private:
//
// Indicator Properties ...
//
// Market ...
//
// Length ...
int mLength;
//
// Multiplier ...
double mMultiplier;
//
// Applied To ...
ENUM_APPLIED_PRICE mApliedTo;
//
// Presentation ...
//
// Show Base ...
bool mShowBase;
//
// Show Band ...
bool mShowBand;
//
// Show Golden Area ...
bool mShowGoldenArea;
//
// Show Other Levels ...
bool mShowOthers;
};
//
// START Usefull Functions ...
//
//
// END Usefull Functions ...
//
@@ -0,0 +1,441 @@
///////////////////////////////////////////////////////
//
// SaherElm IT Center MQL5 Helper Class Library
// ----------------------------------------------
// Name: XSCXHKHelper
// Description: provides all Indicator
// Helper requirements ...
//
//
// Maintainer:
// ------------
// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com)
//
//////////////////////////////////////////////////////
//
// Global Properties ...
#property library
#property copyright "Copyright 2023, SaherElm IT Center"
#property link "https://www.saherelm.ir"
#property version "1.00"
#property strict
//
// START Definitions ...
//
//
// Inputs ...
struct XHKInputs
{
//
// Presentation ...
bool drawCandles; // Draw Hiken Ashi Candle
bool drawCandleLines; // Show HikenAshi Lines
};
//
// Index of Lines ...
enum ENUM_XHK_BUFFERS
{
//
// Main Requirements ...
XHK_OPEN_LINE = 0,
XHK_HIGH_LINE = 1,
XHK_LOW_LINE = 2,
XHK_CLOSE_LINE = 3,
};
//
// Retrieve Info Model ...
struct XHKInfo
{
//
// Symbol ...
string symbol;
//
// Period ...
ENUM_TIMEFRAMES period;
//
// Bar Time ...
datetime barTime;
//
// Bar Index ...
int barIndex;
//
// Values ...
double open;
double high;
double low;
double close;
//
double opens[];
double highs[];
double lows[];
double closes[];
//
// Conditions ...
//
// Detect Candle is Bullish or not ...
bool isBullish;
//
// Detect Candle is Bearish or not ...
bool isBearish;
};
//
// END Definitions ...
//
//
// START Import and Inclused requirements ...
//
//
// Includes ...
#include "../Libraries/x-saherelm.common.lib.mq5"
#include "../Classes/x-saherelm.xhelper.class.mq5"
//
// END Import and Inclused requirements ...
//
//
// START Overrides ...
//
//
// END Overrides ...
//
//
// a Class for Helping Indicators Requirements ...
class XSCXHKHelper : public XSCBaseHelper
{
//
// Public ...
public:
//
// Buffers ...
double openBuffer[];
double highBuffer[];
double lowBuffer[];
double closeBuffer[];
//
// Constructor ...
void XSCXHKHelper(
string symbol, // Trading Symbol
ENUM_TIMEFRAMES period // Trading Time Frame
//
// Indicator Properties ...
//
// Presentation ...
//
// Draw Hiken Ashi Candle ...
) : XSCBaseHelper(symbol, period)
{
PrepareTag();
}
//
// Deconstructor ...
void ~XSCXHKHelper()
{
}
//
// START Properties ...
//
//
// Draw Candles ...
bool DrawCandles(
bool show // Show or Hide
)
{
//
bool result = false;
//
if (mDrawCandles == show)
{
return true;
}
//
mDrawCandles = show;
result = Init();
//
return result;
}
//
// Show HikenAshi Lines ...
bool DrawCandleLines(
bool show // Show or Hide
)
{
//
bool result = false;
//
if (mDrawCandleLines == show)
{
return true;
}
//
mDrawCandleLines = show;
result = Init();
//
return result;
}
//
// END Properties ...
//
//
// START Provided Functions ...
//
//
// Prepare Tag ...
virtual void PrepareTag()
{
mTag = "XHK" + GetTagPrefix();
}
//
virtual int GetMaxLength()
{
//
int result = -1;
//
result = 2;
//
return result;
}
//
// Initial Indicator Handler ...
bool Init()
{
//
bool result = false;
//
// Initialize Handler ...
mHandler = iCustom(
//
mSymbol,
mPeriod,
"x-saherelm.x121.xhk",
//
// Inputs ...
//
// Presentation ...
"",
//
// Draw Hiken Ashi Candle ...
mDrawCandles,
//
// Show HikenAshi Lines ...
mDrawCandleLines
//
);
result = mHandler != INVALID_HANDLE;
//
return result;
}
//
// Retrieve Current Config ...
XHKInputs GetConfig()
{
//
XHKInputs result;
//
result.drawCandles = mDrawCandles;
result.drawCandleLines = mDrawCandleLines;
//
return result;
}
//
// Set Config ...
bool SetConfig(XHKInputs &config)
{
//
bool result = false;
//
mDrawCandles = config.drawCandles;
mDrawCandleLines = config.drawCandleLines;
//
result = Init();
//
return result;
}
//
// Reading Buffers based on Given Bar Index ...
virtual void Calculate(
int barIndex // Given Bar Index
)
{
//
// OPEN ...
ArraySetAsSeries(openBuffer, true);
CopyBuffer(
mHandler,
XHK_OPEN_LINE,
barIndex,
mLoopbackBars,
openBuffer);
//
// HIGH ...
ArraySetAsSeries(highBuffer, true);
CopyBuffer(
mHandler,
XHK_HIGH_LINE,
barIndex,
mLoopbackBars,
highBuffer);
//
// LOW ...
ArraySetAsSeries(lowBuffer, true);
CopyBuffer(
mHandler,
XHK_LOW_LINE,
barIndex,
mLoopbackBars,
lowBuffer);
//
// CLOSE ...
ArraySetAsSeries(closeBuffer, true);
CopyBuffer(
mHandler,
XHK_CLOSE_LINE,
barIndex,
mLoopbackBars,
closeBuffer);
}
//
// Retrieve Info at Specific Bar Index ...
XHKInfo GetInfo(
int barIndex // Given Bar Index
)
{
//
XHKInfo result;
//
if (barIndex < 0)
{
barIndex = 0;
}
//
// Do Calculations ...
Calculate(barIndex);
//
// Generate Candle Time ...
datetime barTime = GetCandleTime(
mSymbol,
mPeriod,
barIndex);
//
// Fill Result ...
result.symbol = mSymbol;
result.period = mPeriod;
result.barTime = barTime;
result.barIndex = barIndex;
//
double open = openBuffer[barIndex];
double high = highBuffer[barIndex];
double low = lowBuffer[barIndex];
double close = closeBuffer[barIndex];
//
result.open = open;
result.high = high;
result.low = low;
result.close = close;
//
Copy(
openBuffer,
result.opens);
Copy(
highBuffer,
result.highs);
Copy(
lowBuffer,
result.lows);
Copy(
closeBuffer,
result.closes);
//
result.isBullish = open < close;
result.isBearish = open >= close;
//
return result;
}
//
// END Provided Functions ...
//
//
// Protected ...
protected:
//
// Private ...
private:
//
// Indicator Properties ...
//
// Presentation ...
//
// Draw Hiken Ashi Candle ...
bool mDrawCandles;
//
// Show HikenAshi Lines ...
bool mDrawCandleLines;
};
//
// START Usefull Functions ...
//
//
// END Usefull Functions ...
//
@@ -0,0 +1,544 @@
///////////////////////////////////////////////////////
//
// SaherElm IT Center MQL5 Helper Class Library
// ----------------------------------------------
// Name: XSCXHULLHelper
// Description: provides all Indicator
// Helper requirements ...
//
//
// Maintainer:
// ------------
// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com)
//
//////////////////////////////////////////////////////
//
// Global Properties ...
#property library
#property copyright "Copyright 2023, SaherElm IT Center"
#property link "https://www.saherelm.ir"
#property version "1.00"
#property strict
//
// START Definitions ...
//
//
// Inputs ...
struct XHULLInputs
{
//
// Market ...
int length; // Length
double divisor; // Divisor (Speed)
//
// Calculation ...
ENUM_APPLIED_PRICE upAppliedTo; // Up Zone Applied to
ENUM_APPLIED_PRICE downAppliedTo; // Down Zone Applied to
//
// Presentation ...
bool showUpZone; // Show Up Zone
bool showDownZone; // Show Down Zone
};
//
// Index of Lines ...
enum ENUM_XHULL_BUFFERS
{
//
// Main Requirements ...
XHULL_UP_ZONE_LINE = 0,
XHULL_UP_ZONE_STATE_LINE = 1,
XHULL_DOWN_ZONE_LINE = 2,
XHULL_DOWN_ZONE_STATE_LINE = 3,
};
//
// Hull States ...
enum XHULL_ZONE_STATES
{
XHULL_STATE_NEUTURAL = 0,
XHULL_STATE_BULLISH = 1,
XHULL_STATE_BEARISH = 2
};
//
// Retrieve Info Model ...
struct XHULLInfo
{
//
// Symbol ...
string symbol;
//
// Period ...
ENUM_TIMEFRAMES period;
//
// Bar Time ...
datetime barTime;
//
// Bar Index ...
int barIndex;
//
// Values ...
double up;
XHULL_ZONE_STATES upState;
double down;
XHULL_ZONE_STATES downState;
//
double ups[];
double upStates[];
double downs[];
double downStates[];
//
// Conditions ...
//
bool isUpBullish;
bool isUpNeutural;
bool isUpBearish;
//
bool isUpSwitchedToBullish;
bool isUpSwitchedToBearish;
bool isUpSwitchedToNeutural;
//
bool isDownBullish;
bool isDownBearish;
bool isDownNeutural;
//
bool isDownSwitchedToBullish;
bool isDownSwitchedToBearish;
bool isDownSwitchedToNeutural;
};
//
// END Definitions ...
//
//
// START Import and Inclused requirements ...
//
//
// Includes ...
#include "../Libraries/x-saherelm.common.lib.mq5"
#include "../Classes/x-saherelm.xhelper.class.mq5"
//
// END Import and Inclused requirements ...
//
//
// START Overrides ...
//
//
// END Overrides ...
//
//
// a Class for Helping Indicators Requirements ...
class XSCXHULLHelper : public XSCBaseHelper
{
//
// Public ...
public:
//
// Buffers ...
double upBuffer[];
double upStateBuffer[];
double downBuffer[];
double downStateBuffer[];
//
// Constructor ...
void XSCXHULLHelper(
string symbol, // Trading Symbol
ENUM_TIMEFRAMES period // Trading Time Frame
) : XSCBaseHelper(symbol, period)
{
PrepareTag();
}
//
// Deconstructor ...
void ~XSCXHULLHelper()
{
}
//
// START Properties ...
//
//
// Show Up Zone ...
bool ShowUpZone(
bool show // Show or Hide
)
{
//
bool result = false;
//
if (mShowUpZone == show)
{
return true;
}
//
mShowUpZone = show;
result = Init();
//
return result;
}
//
// Show Down Zone ...
bool ShowDownZone(
bool show // Show or Hide
)
{
//
bool result = false;
//
if (mShowDownZone == show)
{
return true;
}
//
mShowDownZone = show;
result = Init();
//
return result;
}
//
// END Properties ...
//
//
// START Provided Functions ...
//
//
// Prepare Tag ...
virtual void PrepareTag()
{
mTag = "XHULL" + GetTagPrefix();
}
//
virtual int GetMaxLength()
{
//
int result = -1;
//
result = mLength;
//
return result;
}
//
// Initial Indicator Handler ...
bool Init()
{
//
bool result = false;
//
// Validate Inputs ...
//
result =
mLength >= 9 &&
mDivisor >= 0.5;
if (!result)
{
return result;
}
//
// Initialize Handler ...
mHandler = iCustom(
//
mSymbol,
mPeriod,
"x-saherelm.x121.xhull",
//
// Inputs ...
//
// Market ...
"",
//
// Length ...
mLength,
//
// Divisor (Speed) ...
mDivisor,
//
// Calculation ...
"",
//
// Up Zone Applied to ...
mUpAppliedTo,
//
// Down Zone Applied to ...
mDownAppliedTo,
//
// Presentation ...
"",
//
// Show Up Zone ...
mShowUpZone,
//
// Show Down Zone ...
mShowDownZone
//
);
result = mHandler != INVALID_HANDLE;
//
return result;
}
//
// Retrieve Current Config ...
XHULLInputs GetConfig()
{
//
XHULLInputs result;
//
result.length = mLength;
result.divisor = mDivisor;
result.upAppliedTo = mUpAppliedTo;
result.downAppliedTo = mDownAppliedTo;
result.showUpZone = mShowUpZone;
result.showDownZone = mShowDownZone;
//
return result;
}
//
// Set Config ...
bool SetConfig(XHULLInputs &config)
{
//
bool result = false;
//
mLength = config.length;
mDivisor = config.divisor;
mUpAppliedTo = config.upAppliedTo;
mDownAppliedTo = config.downAppliedTo;
mShowUpZone = config.showUpZone;
mShowDownZone = config.showDownZone;
//
result = Init();
//
return result;
}
//
// Reading Buffers based on Given Bar Index ...
virtual void Calculate(
int barIndex // Given Bar Index
)
{
//
// UP ...
ArraySetAsSeries(upBuffer, true);
CopyBuffer(
mHandler,
XHULL_UP_ZONE_LINE,
barIndex,
mLoopbackBars,
upBuffer);
//
// UP State ...
ArraySetAsSeries(upStateBuffer, true);
CopyBuffer(
mHandler,
XHULL_UP_ZONE_STATE_LINE,
barIndex,
mLoopbackBars,
upStateBuffer);
//
// DOWN ...
ArraySetAsSeries(downBuffer, true);
CopyBuffer(
mHandler,
XHULL_DOWN_ZONE_LINE,
barIndex,
mLoopbackBars,
downBuffer);
//
// DOWN State ...
ArraySetAsSeries(downStateBuffer, true);
CopyBuffer(
mHandler,
XHULL_DOWN_ZONE_STATE_LINE,
barIndex,
mLoopbackBars,
downStateBuffer);
}
//
// Retrieve Info at Specific Bar Index ...
XHULLInfo GetInfo(
int barIndex // Given Bar Index
)
{
//
XHULLInfo result;
//
if (barIndex < 0)
{
barIndex = 0;
}
//
// Do Calculations ...
Calculate(barIndex);
//
// Generate Candle Time ...
datetime barTime = GetCandleTime(
mSymbol,
mPeriod,
barIndex);
//
// Fill Result ...
result.symbol = mSymbol;
result.period = mPeriod;
result.barTime = barTime;
result.barIndex = barIndex;
//
double up = upBuffer[barIndex];
XHULL_ZONE_STATES upState = (XHULL_ZONE_STATES)upStateBuffer[barIndex];
XHULL_ZONE_STATES upStatePrev = (XHULL_ZONE_STATES)upStateBuffer[barIndex + 1];
//
double down = downBuffer[barIndex];
XHULL_ZONE_STATES downState = (XHULL_ZONE_STATES)downStateBuffer[barIndex];
XHULL_ZONE_STATES downStatePrev = (XHULL_ZONE_STATES)downStateBuffer[barIndex + 1];
//
result.up = up;
result.upState = upState;
result.down = down;
result.downState = downState;
//
Copy(
upBuffer,
result.ups);
Copy(
upStateBuffer,
result.upStates);
Copy(
downBuffer,
result.downs);
Copy(
downStateBuffer,
result.downStates);
//
result.isUpBullish = upState = XHULL_STATE_BULLISH;
result.isUpBearish = upState = XHULL_STATE_BEARISH;
result.isUpNeutural = upState = XHULL_STATE_NEUTURAL;
//
result.isUpSwitchedToBullish = upState == XHULL_STATE_BULLISH &&
upStatePrev != XHULL_STATE_BULLISH;
result.isUpSwitchedToBearish = upState == XHULL_STATE_BEARISH &&
upStatePrev != XHULL_STATE_BEARISH;
result.isUpSwitchedToNeutural = upState == XHULL_STATE_NEUTURAL &&
upStatePrev != XHULL_STATE_NEUTURAL;
//
result.isDownBullish = downState = XHULL_STATE_BULLISH;
result.isDownBearish = downState = XHULL_STATE_BEARISH;
result.isDownNeutural = downState = XHULL_STATE_NEUTURAL;
//
result.isDownSwitchedToBullish = downState == XHULL_STATE_BULLISH &&
downStatePrev != XHULL_STATE_BULLISH;
result.isDownSwitchedToBearish = downState == XHULL_STATE_BEARISH &&
downStatePrev != XHULL_STATE_BEARISH;
result.isDownSwitchedToNeutural = downState == XHULL_STATE_NEUTURAL &&
downStatePrev != XHULL_STATE_NEUTURAL;
//
return result;
}
//
// END Provided Functions ...
//
//
// Protected ...
protected:
//
// Private ...
private:
//
// Indicator Properties ...
//
// Market ...
//
// Length ...
int mLength;
//
// Divisor (Speed) ...
double mDivisor;
//
// Calculation ...
//
// Up Zone Applied to ...
ENUM_APPLIED_PRICE mUpAppliedTo;
//
// Down Zone Applied to ...
ENUM_APPLIED_PRICE mDownAppliedTo;
//
// Presentation ...
//
// Show Up Zone ...
bool mShowUpZone;
//
// Show Down Zone ...
bool mShowDownZone;
};
//
// START Usefull Functions ...
//
//
// END Usefull Functions ...
//
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,895 @@
///////////////////////////////////////////////////////
//
// SaherElm IT Center MQL5 Helper Class Library
// ----------------------------------------------
// Name: XSCXMRBHelper
// Description: provides all Indicator
// Helper requirements ...
//
//
// Maintainer:
// ------------
// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com)
//
//////////////////////////////////////////////////////
//
// Global Properties ...
#property library
#property copyright "Copyright 2023, SaherElm IT Center"
#property link "https://www.saherelm.ir"
#property version "1.00"
#property strict
//
// START Definitions ...
//
//
// Inputs ...
struct XMRBInputs
{
//
// Ribbon 1 ...
int fast1Length; // Fast
int slow1Length; // Slow
//
// Ribbon 2 ...
int fast2Length; // Fast
int slow2Length; // Slow
//
// Ribbon 3 ...
int fast3Length; // Fast
int slow3Length; // Slow
//
// Ribbon 4 ...
int fast4Length; // Fast
int slow4Length; // Slow
//
// Ribbon 5 ...
int fast5Length; // Fast
int slow5Length; // Slow
//
// Calculation ...
ENUM_MA_METHOD ribbonMode; // Mode
ENUM_APPLIED_PRICE ribbonAppliedTo; // Applied To
//
// Presentation ...
bool showFastMa; // Show Fast
bool showSlowMa; // Show Slow
bool showRibbon; // Show Ribbon
};
//
// Index of Lines ...
enum ENUM_XMRB_BUFFERS
{
//
// Main Requirements ...
XMRB_FAST_LINE = 0,
XMRB_SLOW_LINE = 1,
//
// RIBBON 1 ...
XMRB_R1_FAST_LINE = 2,
XMRB_R1_SLOW_LINE = 3,
//
// RIBBON 2 ...
XMRB_R2_FAST_LINE = 4,
XMRB_R2_SLOW_LINE = 5,
//
// RIBBON 3 ...
XMRB_R3_FAST_LINE = 6,
XMRB_R3_SLOW_LINE = 7,
//
// RIBBON 4 ...
XMRB_R4_FAST_LINE = 8,
XMRB_R4_SLOW_LINE = 9,
//
// RIBBON 5 ...
XMRB_R5_FAST_LINE = 10,
XMRB_R5_SLOW_LINE = 11,
};
//
// Retrieve Info Model ...
struct XMRBInfo
{
//
// Symbol ...
string symbol;
//
// Period ...
ENUM_TIMEFRAMES period;
//
// Bar Time ...
datetime barTime;
//
// Bar Index ...
int barIndex;
//
// Values ...
double fast;
double slow;
double fastR1;
double slowR1;
double fastR2;
double slowR2;
double fastR3;
double slowR3;
double fastR4;
double slowR4;
double fastR5;
double slowR5;
//
double fasts[];
double slows[];
double fastR1s[];
double slowR1s[];
double fastR2s[];
double slowR2s[];
double fastR3s[];
double slowR3s[];
double fastR4s[];
double slowR4s[];
double fastR5s[];
double slowR5s[];
//
// Conditions ...
//
bool isFastOverSlow;
bool isFastCrossedOverSlow;
bool isFastUnderSlow;
bool isFastCrossedUnderSlow;
//
bool isR1FastOverSlow;
bool isR1FastCrossedOverSlow;
bool isR1FastUnderSlow;
bool isR1FastCrossedUnderSlow;
//
bool isR2FastOverSlow;
bool isR2FastCrossedOverSlow;
bool isR2FastUnderSlow;
bool isR2FastCrossedUnderSlow;
//
bool isR3FastOverSlow;
bool isR3FastCrossedOverSlow;
bool isR3FastUnderSlow;
bool isR3FastCrossedUnderSlow;
//
bool isR4FastOverSlow;
bool isR4FastCrossedOverSlow;
bool isR4FastUnderSlow;
bool isR4FastCrossedUnderSlow;
//
bool isR5FastOverSlow;
bool isR5FastCrossedOverSlow;
bool isR5FastUnderSlow;
bool isR5FastCrossedUnderSlow;
};
//
// END Definitions ...
//
//
// START Import and Inclused requirements ...
//
//
// Includes ...
#include "../Libraries/x-saherelm.common.lib.mq5"
#include "../Classes/x-saherelm.xhelper.class.mq5"
//
// END Import and Inclused requirements ...
//
//
// START Overrides ...
//
//
// END Overrides ...
//
//
// a Class for Helping Indicators Requirements ...
class XSCXMRBHelper : public XSCBaseHelper
{
//
// Public ...
public:
//
// Buffers ...
double fastBuffer[];
double slowBuffer[];
double fastR1Buffer[];
double slowR1Buffer[];
double fastR2Buffer[];
double slowR2Buffer[];
double fastR3Buffer[];
double slowR3Buffer[];
double fastR4Buffer[];
double slowR4Buffer[];
double fastR5Buffer[];
double slowR5Buffer[];
//
// Constructor ...
void XSCXMRBHelper(
string symbol, // Trading Symbol
ENUM_TIMEFRAMES period // Trading Time Frame
) : XSCBaseHelper(symbol, period)
{
PrepareTag();
}
//
// Deconstructor ...
void ~XSCXMRBHelper()
{
}
//
// START Properties ...
//
//
// Show Fast ...
bool ShowFast(
bool show // Show or Hide
)
{
//
bool result = false;
//
if (mShowFastMa == show)
{
return true;
}
//
mShowFastMa = show;
result = Init();
//
return result;
}
//
// Show Slow ...
bool ShowSlow(
bool show // Show or Hide
)
{
//
bool result = false;
//
if (mShowSlowMa == show)
{
return true;
}
//
mShowSlowMa = show;
result = Init();
//
return result;
}
//
// Show Ribbon ...
bool ShowRibbon(
bool show // Show or Hide
)
{
//
bool result = false;
//
if (mShowRibbon == show)
{
return true;
}
//
mShowRibbon = show;
result = Init();
//
return result;
}
//
// END Properties ...
//
//
// START Provided Functions ...
//
//
// Prepare Tag ...
virtual void PrepareTag()
{
mTag = "XMRB" + GetTagPrefix();
}
//
virtual int GetMaxLength()
{
//
int result = -1;
//
result = MathMax(mFast1Length, mFast2Length);
result = MathMax(result, mFast3Length);
result = MathMax(result, mFast4Length);
result = MathMax(result, mFast5Length);
//
result = MathMax(result, mSlow1Length);
result = MathMax(result, mSlow2Length);
result = MathMax(result, mSlow3Length);
result = MathMax(result, mSlow4Length);
result = MathMax(result, mSlow5Length);
//
return result;
}
//
// Initial Indicator Handler ...
bool Init()
{
//
bool result = false;
//
// Validate Inputs ...
result =
//
(mFast1Length > 2 &&
mFast2Length > mFast1Length &&
mFast3Length > mFast2Length &&
mFast4Length > mFast3Length &&
mFast5Length > mFast4Length &&
mSlow1Length > mFast1Length &&
mSlow2Length > mFast2Length &&
mSlow3Length > mFast3Length &&
mSlow4Length > mFast4Length &&
mSlow5Length > mFast5Length &&
mSlow2Length > mSlow1Length &&
mSlow3Length > mSlow2Length &&
mSlow4Length > mSlow3Length &&
mSlow5Length > mSlow4Length
//
)
//
;
if (!result)
{
return result;
}
//
// Initialize Handler ...
mHandler = iCustom(
//
mSymbol,
mPeriod,
"x-saherelm.x121.xmrb",
//
// Inputs ...
//
// Ribbon 1 ...
"",
mFast1Length,
mSlow1Length,
//
// Ribbon 2 ...
"",
mFast2Length,
mSlow2Length,
//
// Ribbon 3 ...
"",
mFast3Length,
mSlow3Length,
//
// Ribbon 4 ...
"",
mFast4Length,
mSlow4Length,
//
// Ribbon 5 ...
"",
mFast5Length,
mSlow5Length,
//
// Calculation ...
"",
//
// Mode ...
mRibbonMode,
//
// Applied To ...
mRibbonAppliedTo,
//
// Presentation ...
"",
//
// Show Fast ...
mShowFastMa,
//
// Show Slow ...
mShowSlowMa,
//
// Show Ribbon ...
mShowRibbon
//
);
result = mHandler != INVALID_HANDLE;
//
return result;
}
//
// Retrieve Current Config ...
XMRBInputs GetConfig()
{
//
XMRBInputs result;
//
result.fast1Length = mFast1Length;
result.slow1Length = mSlow1Length;
result.fast2Length = mFast2Length;
result.slow2Length = mSlow2Length;
result.fast3Length = mFast3Length;
result.slow3Length = mSlow3Length;
result.fast4Length = mFast4Length;
result.slow4Length = mSlow4Length;
result.fast5Length = mFast5Length;
result.slow5Length = mSlow5Length;
result.ribbonMode = mRibbonMode;
result.ribbonAppliedTo = mRibbonAppliedTo;
result.showFastMa = mShowFastMa;
result.showSlowMa = mShowSlowMa;
result.showRibbon = mShowRibbon;
//
return result;
}
//
// Set Config ...
bool SetConfig(XMRBInputs &config)
{
//
bool result = false;
//
mFast1Length = config.fast1Length;
mSlow1Length = config.slow1Length;
mFast2Length = config.fast2Length;
mSlow2Length = config.slow2Length;
mFast3Length = config.fast3Length;
mSlow3Length = config.slow3Length;
mFast4Length = config.fast4Length;
mSlow4Length = config.slow4Length;
mFast5Length = config.fast5Length;
mSlow5Length = config.slow5Length;
mRibbonMode = config.ribbonMode;
mRibbonAppliedTo = config.ribbonAppliedTo;
mShowFastMa = config.showFastMa;
mShowSlowMa = config.showSlowMa;
mShowRibbon = config.showRibbon;
//
result = Init();
//
return result;
}
//
// Reading Buffers based on Given Bar Index ...
virtual void Calculate(
int barIndex // Given Bar Index
)
{
//
// FAST ...
ArraySetAsSeries(fastBuffer, true);
CopyBuffer(
mHandler,
XMRB_FAST_LINE,
barIndex,
mLoopbackBars,
fastBuffer);
//
// SLOW ...
ArraySetAsSeries(slowBuffer, true);
CopyBuffer(
mHandler,
XMRB_SLOW_LINE,
barIndex,
mLoopbackBars,
slowBuffer);
//
// RIBBON 1 ...
//
// FAST ...
ArraySetAsSeries(fastR1Buffer, true);
CopyBuffer(
mHandler,
XMRB_R1_FAST_LINE,
barIndex,
mLoopbackBars,
fastR1Buffer);
//
// SLOW ...
ArraySetAsSeries(slowR1Buffer, true);
CopyBuffer(
mHandler,
XMRB_R1_SLOW_LINE,
barIndex,
mLoopbackBars,
slowR1Buffer);
//
// RIBBON 2 ...
//
// FAST ...
ArraySetAsSeries(fastR2Buffer, true);
CopyBuffer(
mHandler,
XMRB_R2_FAST_LINE,
barIndex,
mLoopbackBars,
fastR2Buffer);
//
// SLOW ...
ArraySetAsSeries(slowR2Buffer, true);
CopyBuffer(
mHandler,
XMRB_R2_SLOW_LINE,
barIndex,
mLoopbackBars,
slowR2Buffer);
//
// RIBBON 3 ...
//
// FAST ...
ArraySetAsSeries(fastR3Buffer, true);
CopyBuffer(
mHandler,
XMRB_R3_FAST_LINE,
barIndex,
mLoopbackBars,
fastR3Buffer);
//
// SLOW ...
ArraySetAsSeries(slowR3Buffer, true);
CopyBuffer(
mHandler,
XMRB_R3_SLOW_LINE,
barIndex,
mLoopbackBars,
slowR3Buffer);
//
// RIBBON 4 ...
//
// FAST ...
ArraySetAsSeries(fastR4Buffer, true);
CopyBuffer(
mHandler,
XMRB_R4_FAST_LINE,
barIndex,
mLoopbackBars,
fastR4Buffer);
//
// SLOW ...
ArraySetAsSeries(slowR4Buffer, true);
CopyBuffer(
mHandler,
XMRB_R4_SLOW_LINE,
barIndex,
mLoopbackBars,
slowR4Buffer);
//
// RIBBON 5 ...
//
// FAST ...
ArraySetAsSeries(fastR5Buffer, true);
CopyBuffer(
mHandler,
XMRB_R5_FAST_LINE,
barIndex,
mLoopbackBars,
fastR5Buffer);
//
// SLOW ...
ArraySetAsSeries(slowR5Buffer, true);
CopyBuffer(
mHandler,
XMRB_R5_SLOW_LINE,
barIndex,
mLoopbackBars,
slowR5Buffer);
}
//
// Retrieve Info at Specific Bar Index ...
XMRBInfo GetInfo(
int barIndex // Given Bar Index
)
{
//
XMRBInfo result;
//
if (barIndex < 0)
{
barIndex = 0;
}
//
// Do Calculations ...
Calculate(barIndex);
//
// Generate Candle Time ...
datetime barTime = GetCandleTime(
mSymbol,
mPeriod,
barIndex);
//
// Fill Result ...
result.symbol = mSymbol;
result.period = mPeriod;
result.barTime = barTime;
result.barIndex = barIndex;
//
double fast = fastBuffer[barIndex];
double fastPrev = fastBuffer[barIndex + 1];
double slow = slowBuffer[barIndex];
double slowPrev = slowBuffer[barIndex + 1];
double fastR1 = fastR1Buffer[barIndex];
double fastR1Prev = fastR1Buffer[barIndex + 1];
double slowR1 = slowR1Buffer[barIndex];
double slowR1Prev = slowR1Buffer[barIndex + 1];
double fastR2 = fastR2Buffer[barIndex];
double fastR2Prev = fastR2Buffer[barIndex + 1];
double slowR2 = slowR2Buffer[barIndex];
double slowR2Prev = slowR2Buffer[barIndex + 1];
double fastR3 = fastR3Buffer[barIndex];
double fastR3Prev = fastR3Buffer[barIndex + 1];
double slowR3 = slowR3Buffer[barIndex];
double slowR3Prev = slowR3Buffer[barIndex + 1];
double fastR4 = fastR4Buffer[barIndex];
double fastR4Prev = fastR4Buffer[barIndex + 1];
double slowR4 = slowR4Buffer[barIndex];
double slowR4Prev = slowR4Buffer[barIndex + 1];
double fastR5 = fastR5Buffer[barIndex];
double fastR5Prev = fastR5Buffer[barIndex + 1];
double slowR5 = slowR5Buffer[barIndex];
double slowR5Prev = slowR5Buffer[barIndex + 1];
//
Copy(
fastBuffer,
result.fasts);
Copy(
slowBuffer,
result.slows);
Copy(
fastR1Buffer,
result.fastR1s);
Copy(
slowR1Buffer,
result.slowR1s);
Copy(
fastR2Buffer,
result.fastR2s);
Copy(
slowR2Buffer,
result.slowR2s);
Copy(
fastR3Buffer,
result.fastR3s);
Copy(
slowR3Buffer,
result.slowR3s);
Copy(
fastR4Buffer,
result.fastR4s);
Copy(
slowR4Buffer,
result.slowR4s);
Copy(
fastR5Buffer,
result.fastR5s);
Copy(
slowR5Buffer,
result.slowR5s);
//
result.fast = fast;
result.slow = slow;
result.fastR1 = fastR1;
result.slowR1 = slowR1;
result.fastR2 = fastR2;
result.slowR2 = slowR2;
result.fastR3 = fastR3;
result.slowR3 = slowR3;
result.fastR4 = fastR4;
result.slowR4 = slowR4;
result.fastR5 = fastR5;
result.slowR5 = slowR5;
//
result.isFastOverSlow =
fast > slow;
result.isFastCrossedOverSlow =
fast > slow && fastPrev <= slowPrev;
result.isFastUnderSlow =
fast < slow;
result.isFastCrossedUnderSlow =
fast < slow && fastPrev >= slowPrev;
//
result.isR1FastOverSlow =
fastR1 > slowR1;
result.isR1FastCrossedOverSlow =
fastR1 > slowR1 && fastR1Prev <= slowR1Prev;
result.isR1FastUnderSlow =
fastR1 < slowR1;
result.isR1FastCrossedUnderSlow =
fastR1 < slowR1 && fastR1Prev >= slowR1Prev;
//
result.isR2FastOverSlow =
fastR2 > slowR2;
result.isR2FastCrossedOverSlow =
fastR2 > slowR2 && fastR2Prev <= slowR2Prev;
result.isR2FastUnderSlow =
fastR2 < slowR2;
result.isR2FastCrossedUnderSlow =
fastR2 < slowR2 && fastR2Prev >= slowR2Prev;
//
result.isR3FastOverSlow =
fastR3 > slowR3;
result.isR3FastCrossedOverSlow =
fastR3 > slowR3 && fastR3Prev <= slowR3Prev;
result.isR3FastUnderSlow =
fastR3 < slowR3;
result.isR3FastCrossedUnderSlow =
fastR3 < slowR3 && fastR3Prev >= slowR3Prev;
//
result.isR4FastOverSlow =
fastR4 > slowR4;
result.isR4FastCrossedOverSlow =
fastR4 > slowR4 && fastR4Prev <= slowR4Prev;
result.isR4FastUnderSlow =
fastR4 < slowR4;
result.isR4FastCrossedUnderSlow =
fastR4 < slowR4 && fastR4Prev >= slowR4Prev;
//
result.isR5FastOverSlow =
fastR5 > slowR5;
result.isR5FastCrossedOverSlow =
fastR5 > slowR5 && fastR5Prev <= slowR5Prev;
result.isR5FastUnderSlow =
fastR5 < slowR5;
result.isR5FastCrossedUnderSlow =
fastR5 < slowR5 && fastR5Prev >= slowR5Prev;
//
return result;
}
//
// END Provided Functions ...
//
//
// Protected ...
protected:
//
// Private ...
private:
//
// Indicator Properties ...
//
// Market ...
//
// Ribbon 1 ...
int mFast1Length;
int mSlow1Length;
//
// Ribbon 2 ...
int mFast2Length;
int mSlow2Length;
//
// Ribbon 3 ...
int mFast3Length;
int mSlow3Length;
//
// Ribbon 4 ...
int mFast4Length;
int mSlow4Length;
//
// Ribbon 5 ...
int mFast5Length;
int mSlow5Length;
//
// Calculation ...
//
// Mode ...
ENUM_MA_METHOD mRibbonMode;
//
// Applied To ...
ENUM_APPLIED_PRICE mRibbonAppliedTo;
//
// Presentation ...
//
// Show Fast ...
bool mShowFastMa;
//
// Show Slow ...
bool mShowSlowMa;
//
// Show Ribbon ...
bool mShowRibbon;
};
//
// START Usefull Functions ...
//
//
// END Usefull Functions ...
//
@@ -0,0 +1,830 @@
///////////////////////////////////////////////////////
//
// SaherElm IT Center MQL5 Helper Class Library
// ----------------------------------------------
// Name: XSCXOSCHelper
// Description: provides all Indicator
// Helper requirements ...
//
//
// Maintainer:
// ------------
// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com)
//
//////////////////////////////////////////////////////
//
// Global Properties ...
#property library
#property copyright "Copyright 2023, SaherElm IT Center"
#property link "https://www.saherelm.ir"
#property version "1.00"
#property strict
//
// START Definitions ...
//
//
// Inputs ...
struct XOSCInputs
{
//
// ATR ...
int atrLength;
//
// RVI ...
int rviLength;
//
// BULLPOWER ...
int bullpLength;
//
// BEARPOWER ...
int bearpLength;
//
// VOLUME ...
ENUM_APPLIED_VOLUME volumeAppliedTo;
//
// RSI ...
int rsiLength;
ENUM_APPLIED_PRICE rsiAppliedTo;
//
// CCI ...
int cciLength;
ENUM_APPLIED_PRICE cciAppliedTo;
//
// MOMENTUM ...
int momentumLength;
ENUM_APPLIED_PRICE momentumAppliedTo;
//
// SAR ...
double sarStep;
double sarMaximum;
//
// MACD ...
int macdFastLength;
int macdSlowLength;
int macdSignaLength;
ENUM_APPLIED_PRICE macdAppliedTo;
//
// STOCHASTIC ...
int stochKLength;
int stochDLength;
int stochSlowing;
ENUM_MA_METHOD stochMaMethod;
ENUM_STO_PRICE stochMode;
//
// STANDARDDEVIATION ...
int stddevLength;
int stddevShift;
ENUM_MA_METHOD stddevMethod;
ENUM_APPLIED_PRICE stddevAppliedTo;
};
//
// Index of Lines ...
enum ENUM_XOSC_BUFFERS
{
//
// Main Requirements ...
XOSC_ATR_LINE = 0,
XOSC_RVI_MAIN_LINE = 1,
XOSC_RVI_SIGNAL_LINE = 2,
XOSC_BULLP_LINE = 3,
XOSC_BEARP_LINE = 4,
XOSC_VOLUME_LINE = 5,
XOSC_RSI_LINE = 6,
XOSC_CCI_LINE = 7,
XOSC_MOMENTUM_LINE = 8,
XOSC_SAR_LINE = 9,
XOSC_MACD_MAIN_LINE = 10,
XOSC_MACD_SIGNAL_LINE = 11,
XOSC_STOCH_MAIN_LINE = 12,
XOSC_STOCH_SIGNAL_LINE = 13,
XOSC_STDDEV_LINE = 14,
};
//
// Retrieve Info Model ...
struct XOSCInfo
{
//
// Symbol ...
string symbol;
//
// Period ...
ENUM_TIMEFRAMES period;
//
// Bar Time ...
datetime barTime;
//
// Bar Index ...
int barIndex;
//
// Values ...
double atr;
double rviMain;
double rviSignal;
double bullPower;
double bearPower;
double volume;
double rsi;
double cci;
double momentum;
double sar;
double macdMain;
double macdSignal;
double stochMain;
double stochSignal;
double stddev;
//
double atrs[];
double rviMains[];
double rviSignals[];
double bullPs[];
double bearPs[];
double volumes[];
double rsis[];
double ccis[];
double momentums[];
double sars[];
double macdMains[];
double macdSignals[];
double stochMains[];
double stochSignals[];
double stddevs[];
//
// Conditions ...
// TODO: Implement it Later ...
};
//
// END Definitions ...
//
//
// START Import and Inclused requirements ...
//
//
// Includes ...
#include "../Libraries/x-saherelm.common.lib.mq5"
#include "../Classes/x-saherelm.xhelper.class.mq5"
//
// END Import and Inclused requirements ...
//
//
// START Overrides ...
//
//
// END Overrides ...
//
//
// a Class for Helping Indicators Requirements ...
class XSCXOSCHelper : public XSCBaseHelper
{
//
// Public ...
public:
//
// Buffers ...
double atrBuffer[];
double rviMainBuffer[];
double rviSignalBuffer[];
double bullPBuffer[];
double bearPBuffer[];
double volumeBuffer[];
double rsiBuffer[];
double cciBuffer[];
double momentumBuffer[];
double sarBuffer[];
double macdMainBuffer[];
double macdSignalBuffer[];
double stochMainBuffer[];
double stochSignalBuffer[];
double stddevBuffer[];
//
// Constructor ...
void XSCXOSCHelper(
string symbol, // Trading Symbol
ENUM_TIMEFRAMES period // Trading Time Frame
) : XSCBaseHelper(symbol, period)
{
PrepareTag();
}
//
// Deconstructor ...
void ~XSCXOSCHelper()
{
}
//
// START Properties ...
//
//
// END Properties ...
//
//
// START Provided Functions ...
//
//
// Prepare Tag ...
virtual void PrepareTag()
{
mTag = "XOSC" + GetTagPrefix();
}
//
virtual int GetMaxLength()
{
//
int result = -1;
//
result = MathMax(mAtrLength, mRviLength);
result = MathMax(result, mBullpLength);
result = MathMax(result, mBearpLength);
result = MathMax(result, mRsiLength);
result = MathMax(result, mCciLength);
result = MathMax(result, mMomentumLength);
result = MathMax(result, mMacdFastLength);
result = MathMax(result, mMacdSlowLength);
result = MathMax(result, mMacdSignaLength);
result = MathMax(result, mStochKLength);
result = MathMax(result, mStochDLength);
result = MathMax(result, mStochSlowing);
result = MathMax(result, mStddevLength);
//
return result;
}
//
// Initial Indicator Handler ...
bool Init()
{
//
bool result = false;
//
// Validate Args ...
result =
//
mAtrLength >= 2 &&
mRviLength >= 2 &&
mBullpLength >= 2 &&
mBearpLength >= 2 &&
mRsiLength >= 2 &&
mCciLength >= 2 &&
mMomentumLength >= 2 &&
mSarStep > 0 &&
mSarStep < mSarMaximum &&
mMacdFastLength >= 2 &&
mMacdSlowLength > mMacdFastLength &&
mMacdSignaLength >= 2 &&
mStochKLength >= 2 &&
mStochDLength >= 2 &&
mStochSlowing >= 2 &&
mStddevLength >= 2 &&
mStddevShift >= 0
//
;
if (!result)
{
return false;
}
//
// Initialize Handler ...
mHandler = iCustom(
//
mSymbol,
mPeriod,
"x-saherelm.x121.xosc",
//
// Inputs ...
//
// ATR ...
"",
mAtrLength,
//
// RVI ...
"",
mRviLength,
//
// BULLPOWER ...
"",
mBullpLength,
//
// BEARPOWER ...
"",
mBearpLength,
//
// VOLUME ...
"",
mVolumeAppliedTo,
//
// RSI ...
"",
mRsiLength,
mRsiAppliedTo,
//
// CCI ...
"",
mCciLength,
mCciAppliedTo,
//
// STANDARDDEVIATION ...
"",
mStddevLength,
mStddevShift,
mStddevMethod,
mStddevAppliedTo,
//
// MOMENTUM ...
"",
mMomentumLength,
mMomentumAppliedTo,
//
// SAR ...
"",
mSarStep,
mSarMaximum,
//
// MACD ...
"",
mMacdFastLength,
mMacdSlowLength,
mMacdSignaLength,
mMacdAppliedTo,
//
// STOCHASTIC ...
"",
mStochKLength,
mStochDLength,
mStochSlowing,
mStochMaMethod,
mStochMode
//
);
result = mHandler != INVALID_HANDLE;
//
return result;
}
//
// Retrieve Current Config ...
XOSCInputs GetConfig()
{
//
XOSCInputs result;
//
result.atrLength = mAtrLength;
result.rviLength = mRviLength;
result.bullpLength = mBullpLength;
result.bearpLength = mBearpLength;
result.volumeAppliedTo = mVolumeAppliedTo;
result.rsiLength = mRsiLength;
result.rsiAppliedTo = mRsiAppliedTo;
result.cciLength = mCciLength;
result.cciAppliedTo = mCciAppliedTo;
result.momentumLength = mMomentumLength;
result.momentumAppliedTo = mMomentumAppliedTo;
result.sarStep = mSarStep;
result.sarMaximum = mSarMaximum;
result.macdFastLength = mMacdFastLength;
result.macdSlowLength = mMacdSlowLength;
result.macdSignaLength = mMacdSignaLength;
result.macdAppliedTo = mMacdAppliedTo;
result.stochKLength = mStochKLength;
result.stochDLength = mStochDLength;
result.stochSlowing = mStochSlowing;
result.stochMaMethod = mStochMaMethod;
result.stochMode = mStochMode;
result.stddevLength = mStddevLength;
result.stddevShift = mStddevShift;
result.stddevMethod = mStddevMethod;
result.stddevAppliedTo = mStddevAppliedTo;
//
return result;
}
//
// Set Config ...
bool SetConfig(XOSCInputs &config)
{
//
bool result = false;
//
mAtrLength = config.atrLength;
mRviLength = config.rviLength;
mBullpLength = config.bullpLength;
mBearpLength = config.bearpLength;
mVolumeAppliedTo = config.volumeAppliedTo;
mRsiLength = config.rsiLength;
mRsiAppliedTo = config.rsiAppliedTo;
mCciLength = config.cciLength;
mCciAppliedTo = config.cciAppliedTo;
mMomentumLength = config.momentumLength;
mMomentumAppliedTo = config.momentumAppliedTo;
mSarStep = config.sarStep;
mSarMaximum = config.sarMaximum;
mMacdFastLength = config.macdFastLength;
mMacdSlowLength = config.macdSlowLength;
mMacdSignaLength = config.macdSignaLength;
mMacdAppliedTo = config.macdAppliedTo;
mStochKLength = config.stochKLength;
mStochDLength = config.stochDLength;
mStochSlowing = config.stochSlowing;
mStochMaMethod = config.stochMaMethod;
mStochMode = config.stochMode;
mStddevLength = config.stddevLength;
mStddevShift = config.stddevShift;
mStddevMethod = config.stddevMethod;
mStddevAppliedTo = config.stddevAppliedTo;
//
result = Init();
//
return result;
}
//
// Reading Buffers based on Given Bar Index ...
virtual void Calculate(
int barIndex // Given Bar Index
)
{
//
// ATR ...
ArraySetAsSeries(atrBuffer, true);
CopyBuffer(
mHandler,
XOSC_ATR_LINE,
barIndex,
mLoopbackBars,
atrBuffer);
//
// RVI ...
//
// MAIN ...
ArraySetAsSeries(rviMainBuffer, true);
CopyBuffer(
mHandler,
XOSC_RVI_MAIN_LINE,
barIndex,
mLoopbackBars,
rviMainBuffer);
//
// SIGNAL ...
ArraySetAsSeries(rviSignalBuffer, true);
CopyBuffer(
mHandler,
XOSC_RVI_SIGNAL_LINE,
barIndex,
mLoopbackBars,
rviSignalBuffer);
//
// BULLPOWER ...
ArraySetAsSeries(bullPBuffer, true);
CopyBuffer(
mHandler,
XOSC_BULLP_LINE,
barIndex,
mLoopbackBars,
bullPBuffer);
//
// BEARPOWER ...
ArraySetAsSeries(bearPBuffer, true);
CopyBuffer(
mHandler,
XOSC_BEARP_LINE,
barIndex,
mLoopbackBars,
bearPBuffer);
//
// VOLUME ...
ArraySetAsSeries(volumeBuffer, true);
CopyBuffer(
mHandler,
XOSC_BEARP_LINE,
barIndex,
mLoopbackBars,
volumeBuffer);
//
// RSI ...
ArraySetAsSeries(rsiBuffer, true);
CopyBuffer(
mHandler,
XOSC_VOLUME_LINE,
barIndex,
mLoopbackBars,
rsiBuffer);
//
// CCI ...
ArraySetAsSeries(cciBuffer, true);
CopyBuffer(
mHandler,
XOSC_CCI_LINE,
barIndex,
mLoopbackBars,
cciBuffer);
//
// MOMENTUM ...
ArraySetAsSeries(momentumBuffer, true);
CopyBuffer(
mHandler,
XOSC_MOMENTUM_LINE,
barIndex,
mLoopbackBars,
momentumBuffer);
//
// SAR ...
ArraySetAsSeries(sarBuffer, true);
CopyBuffer(
mHandler,
XOSC_SAR_LINE,
barIndex,
mLoopbackBars,
sarBuffer);
//
// MACD ...
//
// MAIN ...
ArraySetAsSeries(macdMainBuffer, true);
CopyBuffer(
mHandler,
XOSC_MACD_MAIN_LINE,
barIndex,
mLoopbackBars,
macdMainBuffer);
//
// SIGNAL ...
ArraySetAsSeries(macdSignalBuffer, true);
CopyBuffer(
mHandler,
XOSC_MACD_SIGNAL_LINE,
barIndex,
mLoopbackBars,
macdSignalBuffer);
//
// STOCHASTIC ...
//
// MAIN ...
ArraySetAsSeries(stochMainBuffer, true);
CopyBuffer(
mHandler,
XOSC_STOCH_MAIN_LINE,
barIndex,
mLoopbackBars,
stochMainBuffer);
//
// SIGNAL ...
ArraySetAsSeries(stochSignalBuffer, true);
CopyBuffer(
mHandler,
XOSC_STOCH_SIGNAL_LINE,
barIndex,
mLoopbackBars,
stochSignalBuffer);
//
// STANDARDDEVIATION ...
ArraySetAsSeries(stddevBuffer, true);
CopyBuffer(
mHandler,
XOSC_STDDEV_LINE,
barIndex,
mLoopbackBars,
stddevBuffer);
}
//
// Retrieve Info at Specific Bar Index ...
XOSCInfo GetInfo(
int barIndex // Given Bar Index
)
{
//
XOSCInfo result;
//
if (barIndex < 0)
{
barIndex = 0;
}
//
// Do Calculations ...
Calculate(barIndex);
//
// Generate Candle Time ...
datetime barTime = GetCandleTime(
mSymbol,
mPeriod,
barIndex);
//
// Fill Result ...
result.symbol = mSymbol;
result.period = mPeriod;
result.barTime = barTime;
result.barIndex = barIndex;
//
result.atr = atrBuffer[barIndex];
result.rviMain = rviMainBuffer[barIndex];
result.rviSignal = rviSignalBuffer[barIndex];
result.bullPower = bullPBuffer[barIndex];
result.bearPower = bearPBuffer[barIndex];
result.volume = volumeBuffer[barIndex];
result.rsi = rsiBuffer[barIndex];
result.cci = cciBuffer[barIndex];
result.momentum = momentumBuffer[barIndex];
result.sar = sarBuffer[barIndex];
result.macdMain = macdMainBuffer[barIndex];
result.macdSignal = macdMainBuffer[barIndex];
result.stochMain = stochMainBuffer[barIndex];
result.stochSignal = stochSignalBuffer[barIndex];
result.stddev = stddevBuffer[barIndex];
//
Copy(
atrBuffer,
result.atrs);
Copy(
rviMainBuffer,
result.rviMains);
Copy(
rviSignalBuffer,
result.rviSignals);
Copy(
bullPBuffer,
result.bullPs);
Copy(
bearPBuffer,
result.bearPs);
Copy(
volumeBuffer,
result.volumes);
Copy(
rsiBuffer,
result.rsis);
Copy(
cciBuffer,
result.ccis);
Copy(
momentumBuffer,
result.momentums);
Copy(
sarBuffer,
result.sars);
Copy(
macdMainBuffer,
result.macdMains);
Copy(
macdSignalBuffer,
result.macdSignals);
Copy(
stochMainBuffer,
result.stochMains);
Copy(
stochSignalBuffer,
result.stochSignals);
Copy(
stddevBuffer,
result.stddevs);
//
return result;
}
//
// END Provided Functions ...
//
//
// Protected ...
protected:
//
// Private ...
private:
//
// Indicator Properties ...
//
// ATR ...
int mAtrLength;
//
// RVI ...
int mRviLength;
//
// BULLPOWER ...
int mBullpLength;
//
// BEARPOWER ...
int mBearpLength;
//
// VOLUME ...
ENUM_APPLIED_VOLUME mVolumeAppliedTo;
//
// RSI ...
int mRsiLength;
ENUM_APPLIED_PRICE mRsiAppliedTo;
//
// CCI ...
int mCciLength;
ENUM_APPLIED_PRICE mCciAppliedTo;
//
// MOMENTUM ...
int mMomentumLength;
ENUM_APPLIED_PRICE mMomentumAppliedTo;
//
// SAR ...
double mSarStep;
double mSarMaximum;
//
// MACD ...
int mMacdFastLength;
int mMacdSlowLength;
int mMacdSignaLength;
ENUM_APPLIED_PRICE mMacdAppliedTo;
//
// STOCHASTIC ...
int mStochKLength;
int mStochDLength;
int mStochSlowing;
ENUM_MA_METHOD mStochMaMethod;
ENUM_STO_PRICE mStochMode;
//
// STANDARDDEVIATION ...
int mStddevLength;
int mStddevShift;
ENUM_MA_METHOD mStddevMethod;
ENUM_APPLIED_PRICE mStddevAppliedTo;
};
//
// START Usefull Functions ...
//
//
// END Usefull Functions ...
//
@@ -0,0 +1,946 @@
///////////////////////////////////////////////////////
//
// SaherElm IT Center MQL5 Helper Class Library
// ----------------------------------------------
// Name: XSCXPVHelper
// Description: provides all Indicator
// Helper requirements ...
//
//
// Maintainer:
// ------------
// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com)
//
//////////////////////////////////////////////////////
//
// Global Properties ...
#property library
#property copyright "Copyright 2023, SaherElm IT Center"
#property link "https://www.saherelm.ir"
#property version "1.00"
#property strict
//
// START Definitions ...
//
//
// Inputs ...
struct XPVInputs
{
//
// Makret Cycles ...
int shortLength; // Short Length
int mediumLength; // Medium Length
int longLength; // Long Length
int hindLength; // Hind Length
double fiboLevel1; // Fibio 1st Level
double fiboLevel2; // Fibio 2st Level
double fiboLevel3; // Fibio 3rd Level
//
// Detection Modes ...
ENUM_SERIESMODE hhMode; // Highest High Calculation Method
ENUM_SERIESMODE llMode; // Lowest Low Calculation Method
//
// Presentation ...
bool showPeaksAndVales; // Show Peaks and Vales
bool showLevels; // Show Levels
bool showFibo1Levels; // Show Fibo 1st Level
bool showFibo2Levels; // Show Fibo 2nd Level
bool showFibo3Levels; // Show Fibo 3rd Level
};
//
// Index of Lines ...
enum ENUM_XPV_BUFFERS
{
//
// Main Requirements ...
XPV_PEAKS_LINE = 0,
XPV_VALES_LINE = 1,
//
XPV_RESISTANCE_LINE = 2,
XPV_RESISTANCE_STATE_LINE = 3,
//
XPV_SUPPORT_LINE = 4,
XPV_SUPPORT_STATE_LINE = 5,
//
XPV_FL1_LINE = 6,
XPV_FL2_LINE = 8,
XPV_FL3_LINE = 10,
//
// SHORT ...
XPV_SHORT_HIGH_LINE = 12,
XPV_SHORT_LOW_LINE = 13,
//
// MEDIUM ...
XPV_MEDIUM_HIGH_LINE = 14,
XPV_MEDIUM_LOW_LINE = 15,
//
// LONG ...
XPV_LONG_HIGH_LINE = 16,
XPV_LONG_LOW_LINE = 17,
//
// HIND ...
XPV_HIND_HIGH_LINE = 18,
XPV_HIND_LOW_LINE = 19,
};
//
// Retrieve Info Model ...
struct XPVInfo
{
//
// Symbol ...
string symbol;
//
// Period ...
ENUM_TIMEFRAMES period;
//
// Bar Time ...
datetime barTime;
//
// Bar Index ...
int barIndex;
//
// Values ...
double peak;
double vale;
double fl1;
double fl2;
double fl3;
//
double r;
double rState;
double s;
double sSate;
//
// SHORT ...
double sl;
double sh;
//
// MEDIUM ...
double ml;
double mh;
//
// LONG ...
double ll;
double lh;
//
// HIND ...
double hl;
double hh;
//
double peakss[];
double valess[];
double fl1s[];
double fl2s[];
double fl3s[];
double rs[];
double rStates[];
double ss[];
double sStates[];
double sls[];
double shs[];
double mls[];
double mhs[];
double lls[];
double lhs[];
double hls[];
double hhs[];
//
// Conditions ...
//
// Determines New Peaks Happens ...
bool isNewPeak;
//
// Determines New Vales Happens ...
bool isNewVale;
};
//
// END Definitions ...
//
//
// START Import and Inclused requirements ...
//
//
// Includes ...
#include "../Libraries/x-saherelm.common.lib.mq5"
#include "../Classes/x-saherelm.xhelper.class.mq5"
//
// END Import and Inclused requirements ...
//
//
// START Overrides ...
//
//
// END Overrides ...
//
//
// a Class for Helping Indicators Requirements ...
class XSCXPVHelper : public XSCBaseHelper
{
//
// Public ...
public:
//
// Buffers ...
double peaksBuffer[];
double valesBuffer[];
double fl1Buffer[];
double fl2Buffer[];
double fl3Buffer[];
//
// Support and Resistance ...
double rBuffer[];
double rStateBuffer[];
//
double sBuffer[];
double sStateBuffer[];
//
// SHORT ...
double slBuffer[];
double shBuffer[];
//
// MEDIUM ...
double mlBuffer[];
double mhBuffer[];
//
// LONG ...
double llBuffer[];
double lhBuffer[];
//
// HIND ...
double hlBuffer[];
double hhBuffer[];
//
// Constructor ...
void XSCXPVHelper(
string symbol, // Trading Symbol
ENUM_TIMEFRAMES period // Trading Time Frame
) : XSCBaseHelper(symbol, period)
{
PrepareTag();
}
//
// Deconstructor ...
void ~XSCXPVHelper()
{
}
//
// START Properties ...
//
//
// Show Levels ...
bool ShowLevels(
bool show // Show or Hide Levels
)
{
//
bool result = false;
//
if (mShowLevels == show)
{
return true;
}
//
mShowLevels = show;
result = Init();
//
return result;
}
//
// Show Peaks and Vales ...
bool ShowPeaksAnVales(
bool show // Show or Hide Levels
)
{
//
bool result = false;
//
if (mShowPeaksAndVales == show)
{
return true;
}
//
mShowPeaksAndVales = show;
result = Init();
//
return result;
}
//
// Show Fibo 1st Level ...
bool ShowFibo1Levels(
bool show // Show or Hide Levels
)
{
//
bool result = false;
//
if (mShowFibo1Levels == show)
{
return true;
}
//
mShowFibo1Levels = show;
result = Init();
//
return result;
}
//
// Show Fibo 2nd Level ...
bool ShowFibo2Levels(
bool show // Show or Hide Levels
)
{
//
bool result = false;
//
if (mShowFibo2Levels == show)
{
return true;
}
//
mShowFibo2Levels = show;
result = Init();
//
return result;
}
//
// Show Fibo 3rd Level ...
bool ShowFibo3Levels(
bool show // Show or Hide Levels
)
{
//
bool result = false;
//
if (mShowFibo3Levels == show)
{
return true;
}
//
mShowFibo3Levels = show;
result = Init();
//
return result;
}
//
// END Properties ...
//
//
// START Provided Functions ...
//
//
// Prepare Tag ...
virtual void PrepareTag()
{
mTag = "XPV" + GetTagPrefix();
}
//
virtual int GetMaxLength()
{
//
int result = -1;
//
result = MathMax(mShortLength, mMediumLength);
result = MathMax(result, mLongLength);
result = MathMax(result, mHindLength);
//
return result;
}
//
// Initial Indicator Handler ...
bool Init()
{
//
bool result = false;
//
// Validate Args ...
result =
//
(mShortLength > 2 &&
mMediumLength > mShortLength &&
mLongLength > mMediumLength &&
mHindLength > mLongLength)
//
;
if (!result)
{
return false;
}
//
// Initialize Handler ...
mHandler = iCustom(
//
mSymbol,
mPeriod,
"x-saherelm.x121.xpv",
//
// Inputs ...
//
// Market ...
"",
//
// Short Length ...
mShortLength,
//
// Medium Length
mMediumLength,
//
// Long Length ...
mLongLength,
//
// Hind Length ...
mHindLength,
//
// Fibio 1st Level ...
mFiboLevel1,
//
// Fibio 2st Level ...
mFiboLevel2,
//
// Fibio 3rd Level ...
mFiboLevel3,
//
// Detection Mode ...
"",
//
// Highest High Calculation Method ...
mHHMode,
//
// Lowest Low Calculation Method ...
mLLMode,
//
// Presentations ...
"",
//
// Show Peaks and Vales ...
mShowPeaksAndVales,
//
// Show Levels ...
mShowLevels,
//
// Show Fibo 1st Level ...
mShowFibo1Levels,
//
// Show Fibo 2nd Level ...
mShowFibo2Levels,
//
// Show Fibo 3rd Level ...
mShowFibo3Levels
//
);
result = mHandler != INVALID_HANDLE;
//
return result;
}
//
// Retrieve Current Config ...
XPVInputs GetConfig()
{
//
XPVInputs result;
//
result.shortLength = mShortLength;
result.mediumLength = mMediumLength;
result.longLength = mLongLength;
result.hindLength = mHindLength;
result.fiboLevel1 = mFiboLevel1;
result.fiboLevel2 = mFiboLevel2;
result.fiboLevel3 = mFiboLevel3;
result.hhMode = mHHMode;
result.llMode = mLLMode;
result.showPeaksAndVales = mShowPeaksAndVales;
result.showLevels = mShowLevels;
result.showFibo1Levels = mShowFibo1Levels;
result.showFibo2Levels = mShowFibo2Levels;
result.showFibo3Levels = mShowFibo3Levels;
//
return result;
}
//
// Set Config ...
bool SetConfig(XPVInputs &config)
{
//
bool result = false;
//
mShortLength = config.shortLength;
mMediumLength = config.mediumLength;
mLongLength = config.longLength;
mHindLength = config.hindLength;
mFiboLevel1 = config.fiboLevel1;
mFiboLevel2 = config.fiboLevel2;
mFiboLevel3 = config.fiboLevel3;
mHHMode = config.hhMode;
mLLMode = config.llMode;
mShowPeaksAndVales = config.showPeaksAndVales;
mShowLevels = config.showLevels;
mShowFibo1Levels = config.showFibo1Levels;
mShowFibo2Levels = config.showFibo2Levels;
mShowFibo3Levels = config.showFibo3Levels;
//
result = Init();
//
return result;
}
//
// Reading Buffers based on Given Bar Index ...
virtual void Calculate(
int barIndex // Given Bar Index
)
{
//
// PEAKS ...
ArraySetAsSeries(peaksBuffer, true);
CopyBuffer(
mHandler,
XPV_PEAKS_LINE,
barIndex,
mLoopbackBars,
peaksBuffer);
//
// VALES ...
ArraySetAsSeries(valesBuffer, true);
CopyBuffer(
mHandler,
XPV_VALES_LINE,
barIndex,
mLoopbackBars,
valesBuffer);
//
// FIBBO LEVELS ...
//
// LEVEL 1 ...
ArraySetAsSeries(fl1Buffer, true);
CopyBuffer(
mHandler,
XPV_FL1_LINE,
barIndex,
mLoopbackBars,
fl1Buffer);
//
// LEVEL 2 ...
ArraySetAsSeries(fl2Buffer, true);
CopyBuffer(
mHandler,
XPV_FL2_LINE,
barIndex,
mLoopbackBars,
fl2Buffer);
//
// LEVEL 3 ...
ArraySetAsSeries(fl3Buffer, true);
CopyBuffer(
mHandler,
XPV_FL3_LINE,
barIndex,
mLoopbackBars,
fl3Buffer);
//
// Support and Resistance ...
//
// Resistance ...
ArraySetAsSeries(rBuffer, true);
ArraySetAsSeries(rStateBuffer, true);
CopyBuffer(
mHandler,
XPV_RESISTANCE_LINE,
barIndex,
mLoopbackBars,
rBuffer);
CopyBuffer(
mHandler,
XPV_RESISTANCE_STATE_LINE,
barIndex,
mLoopbackBars,
rStateBuffer);
//
// Support ...
ArraySetAsSeries(sBuffer, true);
ArraySetAsSeries(sStateBuffer, true);
CopyBuffer(
mHandler,
XPV_SUPPORT_LINE,
barIndex,
mLoopbackBars,
sBuffer);
CopyBuffer(
mHandler,
XPV_SUPPORT_STATE_LINE,
barIndex,
mLoopbackBars,
sStateBuffer);
//
// CYCLES ...
//
// SHORT ...
//
// HIGH ...
ArraySetAsSeries(shBuffer, true);
CopyBuffer(
mHandler,
XPV_SHORT_HIGH_LINE,
barIndex,
mLoopbackBars,
shBuffer);
//
// LOW ...
ArraySetAsSeries(slBuffer, true);
CopyBuffer(
mHandler,
XPV_SHORT_LOW_LINE,
barIndex,
mLoopbackBars,
slBuffer);
//
// MEDIUM ...
//
// HIGH ...
ArraySetAsSeries(mhBuffer, true);
CopyBuffer(
mHandler,
XPV_MEDIUM_HIGH_LINE,
barIndex,
mLoopbackBars,
mhBuffer);
//
// LOW ...
ArraySetAsSeries(mlBuffer, true);
CopyBuffer(
mHandler,
XPV_MEDIUM_LOW_LINE,
barIndex,
mLoopbackBars,
mlBuffer);
//
// LONG ...
//
// HIGH ...
ArraySetAsSeries(lhBuffer, true);
CopyBuffer(
mHandler,
XPV_LONG_HIGH_LINE,
barIndex,
mLoopbackBars,
lhBuffer);
//
// LOW ...
ArraySetAsSeries(llBuffer, true);
CopyBuffer(
mHandler,
XPV_LONG_LOW_LINE,
barIndex,
mLoopbackBars,
llBuffer);
//
// HIND ...
//
// HIGH ...
ArraySetAsSeries(hhBuffer, true);
CopyBuffer(
mHandler,
XPV_HIND_HIGH_LINE,
barIndex,
mLoopbackBars,
hhBuffer);
//
// LOW ...
ArraySetAsSeries(hlBuffer, true);
CopyBuffer(
mHandler,
XPV_HIND_LOW_LINE,
barIndex,
mLoopbackBars,
hlBuffer);
}
//
// Retrieve Info at Specific Bar Index ...
XPVInfo GetInfo(
int barIndex // Given Bar Index
)
{
//
XPVInfo result;
//
if (barIndex < 0)
{
barIndex = 0;
}
//
// Do Calculations ...
Calculate(barIndex);
//
// Generate Candle Time ...
datetime barTime = GetCandleTime(
mSymbol,
mPeriod,
barIndex);
//
// Fill Result ...
result.symbol = mSymbol;
result.period = mPeriod;
result.barTime = barTime;
result.barIndex = barIndex;
//
result.peak = peaksBuffer[barIndex];
result.vale = valesBuffer[barIndex];
result.fl1 = fl1Buffer[barIndex];
result.fl2 = fl2Buffer[barIndex];
result.fl3 = fl3Buffer[barIndex];
//
result.r = rBuffer[barIndex];
result.rState = rStateBuffer[barIndex];
result.s = sBuffer[barIndex];
result.sSate = sStateBuffer[barIndex];
//
// SHORT ...
result.sl = slBuffer[barIndex];
result.sh = shBuffer[barIndex];
//
// MEDIUM ...
result.ml = mlBuffer[barIndex];
result.mh = mhBuffer[barIndex];
//
// LONG ...
result.ll = llBuffer[barIndex];
result.lh = lhBuffer[barIndex];
//
// HIND ...
result.hl = hlBuffer[barIndex];
result.hh = hhBuffer[barIndex];
//
Copy(
peaksBuffer,
result.peakss);
Copy(
valesBuffer,
result.valess);
Copy(
fl1Buffer,
result.fl1s);
Copy(
fl2Buffer,
result.fl2s);
Copy(
fl3Buffer,
result.fl3s);
Copy(
rBuffer,
result.rs);
Copy(
rStateBuffer,
result.rStates);
Copy(
sBuffer,
result.ss);
Copy(
sStateBuffer,
result.sStates);
Copy(
slBuffer,
result.sls);
Copy(
shBuffer,
result.shs);
Copy(
mlBuffer,
result.mls);
Copy(
mhBuffer,
result.mhs);
Copy(
llBuffer,
result.lls);
Copy(
lhBuffer,
result.lhs);
Copy(
hlBuffer,
result.hls);
Copy(
hhBuffer,
result.hhs);
//
result.isNewPeak =
peaksBuffer[barIndex] != peaksBuffer[barIndex + 1];
result.isNewVale =
valesBuffer[barIndex] != valesBuffer[barIndex + 1];
//
return result;
}
//
// END Provided Functions ...
//
//
// Protected ...
protected:
//
// Private ...
private:
//
// Indicator Properties ...
//
// Market ...
//
// Short Length ...
int mShortLength;
//
// Medium Length
int mMediumLength;
//
// Long Length ...
int mLongLength;
//
// Hind Length ...
int mHindLength;
//
// Fibio 1st Level ...
double mFiboLevel1;
//
// Fibio 2st Level ...
double mFiboLevel2;
//
// Fibio 3rd Level ...
double mFiboLevel3;
//
// Detection Mode ...
//
// Highest High Calculation Method ...
ENUM_SERIESMODE mHHMode;
//
// Lowest Low Calculation Method ...
ENUM_SERIESMODE mLLMode;
//
// Presentations ...
//
// Show Peaks and Vales ...
bool mShowPeaksAndVales;
//
// Show Levels ...
bool mShowLevels;
//
// Show Fibo 1st Level ...
bool mShowFibo1Levels;
//
// Show Fibo 2nd Level ...
bool mShowFibo2Levels;
//
// Show Fibo 3rd Level ...
bool mShowFibo3Levels;
};
//
// START Usefull Functions ...
//
//
// END Usefull Functions ...
//
@@ -0,0 +1,481 @@
///////////////////////////////////////////////////////
//
// SaherElm IT Center MQL5 Helper Class Library
// ----------------------------------------------
// Name: XSCXSSLCHelper
// Description: provides all Indicator
// Helper requirements ...
//
//
// Maintainer:
// ------------
// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com)
//
//////////////////////////////////////////////////////
//
// Global Properties ...
#property library
#property copyright "Copyright 2023, SaherElm IT Center"
#property link "https://www.saherelm.ir"
#property version "1.00"
#property strict
//
// START Definitions ...
//
//
// Inputs ...
struct XSSLCInputs
{
//
// Market ...
int length; // Length
//
// Calculation ...
ENUM_MA_METHOD method; // Method
ENUM_APPLIED_PRICE upAppliedTo; // Up Applied To
ENUM_APPLIED_PRICE downAppliedTo; // Down Applied To
//
// Presentation ...
bool showUp; // Show Up
bool showDown; // Show Down
};
//
// Index of Lines ...
enum ENUM_XSSLC_BUFFERS
{
//
// Main Requirements ...
XSSLC_UP_LINE = 0,
XSSLC_DOWN_LINE = 1,
};
//
// Retrieve Info Model ...
struct XSSLCInfo
{
//
// Symbol ...
string symbol;
//
// Period ...
ENUM_TIMEFRAMES period;
//
// Bar Time ...
datetime barTime;
//
// Bar Index ...
int barIndex;
//
// Values ...
double up;
double down;
//
double ups[];
double downs[];
//
// Conditions ...
//
// Detect Trend is Bullish or not ...
bool isBullish;
//
// Detect Trend is Switched to Bullish Or not ...
bool isSwitchedBullish;
//
// Detect Trend is Bearish or not ...
bool isBearish;
//
// Detect Trend is Switched to Bearish Or not ...
bool isSwitchedBearish;
};
//
// END Definitions ...
//
//
// START Import and Inclused requirements ...
//
//
// Includes ...
#include "../Libraries/x-saherelm.common.lib.mq5"
#include "../Classes/x-saherelm.xhelper.class.mq5"
//
// END Import and Inclused requirements ...
//
//
// START Overrides ...
//
//
// END Overrides ...
//
//
// a Class for Helping Indicators Requirements ...
class XSCXSSLCHelper : public XSCBaseHelper
{
//
// Public ...
public:
//
// Buffers ...
double upBuffer[];
double downBuffer[];
//
// Constructor ...
void XSCXSSLCHelper(
string symbol, // Trading Symbol
ENUM_TIMEFRAMES period // Trading Time Frame
) : XSCBaseHelper(symbol, period)
{
PrepareTag();
}
//
// Deconstructor ...
void ~XSCXSSLCHelper()
{
}
//
// START Properties ...
//
//
// Show Up ...
bool ShowUp(
bool show // Show or Hide Line
)
{
//
bool result = false;
//
if (mShowUp == show)
{
return true;
}
//
mShowUp = show;
result = Init();
//
return result;
}
//
// Show Down ...
bool ShowDown(
bool show // Show or Hide Line
)
{
//
bool result = false;
//
if (mShowDown == show)
{
return true;
}
//
mShowDown = show;
result = Init();
//
return result;
}
//
// END Properties ...
//
//
// START Provided Functions ...
//
//
// Prepare Tag ...
virtual void PrepareTag()
{
mTag = "XSSLC" + GetTagPrefix();
}
//
virtual int GetMaxLength()
{
//
int result = -1;
//
result = mLength;
//
return result;
}
//
// Initial Indicator Handler ...
bool Init()
{
//
bool result = false;
//
// Validate Args ...
result =
//
(mLength >= 2)
//
;
if (!result)
{
return false;
}
//
// Initialize Handler ...
mHandler = iCustom(
//
mSymbol,
mPeriod,
"x-saherelm.x121.xsslc",
//
// Inputs ...
//
// Market ...
"",
//
// Length ...
mLength,
//
// Calculation ...
"",
//
// Method ...
mMethod,
//
// Up Applied To ...
mUpAppliedTo,
//
// Down Applied To ...
mDownAppliedTo,
//
// Presentation ...
"",
//
// Show Up ...
mShowUp,
//
// Show Down ...
mShowDown
//
);
result = mHandler != INVALID_HANDLE;
//
return result;
}
//
// Retrieve Current Config ...
XSSLCInputs GetConfig()
{
//
XSSLCInputs result;
//
result.length = mLength;
result.method = mMethod;
result.upAppliedTo = mUpAppliedTo;
result.downAppliedTo = mDownAppliedTo;
result.showUp = mShowUp;
result.showDown = mShowDown;
//
return result;
}
//
// Set Config ...
bool SetConfig(XSSLCInputs &config)
{
//
bool result = false;
//
mLength = config.length;
mMethod = config.method;
mUpAppliedTo = config.upAppliedTo;
mDownAppliedTo = config.downAppliedTo;
mShowUp = config.showUp;
mShowDown = config.showDown;
//
result = Init();
//
return result;
}
//
// Reading Buffers based on Given Bar Index ...
virtual void Calculate(
int barIndex // Given Bar Index
)
{
//
// UP ...
ArraySetAsSeries(upBuffer, true);
CopyBuffer(
mHandler,
XSSLC_UP_LINE,
barIndex,
mLoopbackBars,
upBuffer);
//
// DOWN ...
ArraySetAsSeries(downBuffer, true);
CopyBuffer(
mHandler,
XSSLC_DOWN_LINE,
barIndex,
mLoopbackBars,
downBuffer);
}
//
// Retrieve Info at Specific Bar Index ...
XSSLCInfo GetInfo(
int barIndex // Given Bar Index
)
{
//
XSSLCInfo result;
//
if (barIndex < 0)
{
barIndex = 0;
}
//
// Do Calculations ...
Calculate(barIndex);
//
// Generate Candle Time ...
datetime barTime = GetCandleTime(
mSymbol,
mPeriod,
barIndex);
//
// Fill Result ...
result.symbol = mSymbol;
result.period = mPeriod;
result.barTime = barTime;
result.barIndex = barIndex;
//
double up = upBuffer[barIndex];
double upPrev = upBuffer[barIndex + 1];
double down = downBuffer[barIndex];
double downPrev = downBuffer[barIndex + 1];
//
Copy(
upBuffer,
result.ups
);
Copy(
downBuffer,
result.downs
);
//
result.up = up;
result.down = down;
//
result.isBullish = up > down;
result.isBearish = up < down;
//
result.isSwitchedBullish =
up > down &&
upPrev <= downPrev;
result.isSwitchedBearish =
up < down &&
upPrev >= downPrev;
//
return result;
}
//
// END Provided Functions ...
//
//
// Protected ...
protected:
//
// Private ...
private:
//
// Indicator Properties ...
//
// Market ...
//
// Length ...
int mLength;
//
// Calculation ...
//
// Method ...
ENUM_MA_METHOD mMethod;
//
// Up Applied To ...
ENUM_APPLIED_PRICE mUpAppliedTo;
//
// Down Applied To ...
ENUM_APPLIED_PRICE mDownAppliedTo;
//
// Presentation ...
//
// Show Up ...
bool mShowUp;
//
// Show Down ...
bool mShowDown;
};
//
// START Usefull Functions ...
//
//
// END Usefull Functions ...
//
@@ -0,0 +1,473 @@
///////////////////////////////////////////////////////
//
// SaherElm IT Center MQL5 Helper Class Library
// ----------------------------------------------
// Name: XSCXSTRHelper
// Description: provides all Indicator
// Helper requirements ...
//
//
// Maintainer:
// ------------
// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com)
//
//////////////////////////////////////////////////////
//
// Global Properties ...
#property library
#property copyright "Copyright 2023, SaherElm IT Center"
#property link "https://www.saherelm.ir"
#property version "1.00"
#property strict
//
// START Definitions ...
//
//
// Inputs ...
struct XSTRInputs
{
//
// Market ...
//
// Length ...
int atrLength;
//
// Multiplier ...
double atrMultiplier;
//
// Applied To ...
ENUM_APPLIED_PRICE atrAppliedTo;
//
// Presentation ...
//
// Show Trends ...
bool showTrends;
//
// Fill Trends ...
bool fillTrends;
};
//
// Index of Lines ...
enum ENUM_XSTR_BUFFERS
{
//
// Main Requirements ...
XSTR_LINE = 2,
XSTR_TREND_LINE = 5
};
//
// Trend State ...
enum ENUM_XSTR_TREND
{
XSTR_BULLISH = 1,
XSTR_BEARISH = -1
};
//
// Retrieve Info Model ...
struct XSTRInfo
{
//
// Symbol ...
string symbol;
//
// Period ...
ENUM_TIMEFRAMES period;
//
// Bar Time ...
datetime barTime;
//
// Bar Index ...
int barIndex;
//
// Values ...
double main;
ENUM_XSTR_TREND trend;
//
double mains[];
double trends[];
//
// Conditions ...
bool isTrendBullish;
bool isTrendBearish;
bool isTrendSwitchedToBullish;
bool isTrendSwitchedToBearish;
};
//
// END Definitions ...
//
//
// START Import and Inclused requirements ...
//
//
// Includes ...
#include "../Libraries/x-saherelm.common.lib.mq5"
#include "../Classes/x-saherelm.xhelper.class.mq5"
//
// END Import and Inclused requirements ...
//
//
// START Overrides ...
//
//
// END Overrides ...
//
//
// a Class for Helping Indicators Requirements ...
class XSCXSTRHelper : public XSCBaseHelper
{
//
// Public ...
public:
//
// Buffers ...
double mainBuffer[];
double trendBuffer[];
//
// Constructor ...
void XSCXSTRHelper(
string symbol, // Trading Symbol
ENUM_TIMEFRAMES period // Trading Time Frame
) : XSCBaseHelper(symbol, period)
{
PrepareTag();
}
//
// Deconstructor ...
void ~XSCXSTRHelper()
{
}
//
// START Properties ...
//
//
// END Properties ...
//
//
// START Provided Functions ...
//
//
// Prepare Tag ...
virtual void PrepareTag()
{
mTag = "XSTR" + GetTagPrefix();
}
//
virtual int GetMaxLength()
{
//
int result = -1;
//
result = mAtrLength;
//
return result;
}
//
// Initial Indicator Handler ...
bool Init()
{
//
bool result = false;
//
// Validate Args ...
result =
//
(mAtrLength >= 2 &&
mAtrMultiplier >= 0)
//
;
if (!result)
{
return false;
}
//
// Initialize Handler ...
mHandler = iCustom(
//
mSymbol,
mPeriod,
"x-saherelm.x121.xstr",
//
// Inputs ...
//
// Makret ...
"",
//
// Length ...
mAtrLength,
//
// Multiplier ...
mAtrMultiplier,
//
// Applied To ...
mAtrAppliedTo,
//
// Presentation ...
"",
//
// Show Trends ...
mShowTrends,
//
// Fill Trends ...
mFillTrends);
result = mHandler != INVALID_HANDLE;
//
return result;
}
//
// Retrieve Current Config ...
XSTRInputs GetConfig()
{
//
XSTRInputs result;
//
result.atrLength = mAtrLength;
result.atrMultiplier = mAtrMultiplier;
result.atrAppliedTo = mAtrAppliedTo;
result.showTrends = mShowTrends;
result.fillTrends = mFillTrends;
//
return result;
}
//
// Set Config ...
bool SetConfig(XSTRInputs &config)
{
//
bool result = false;
//
mAtrLength = config.atrLength;
mAtrMultiplier = config.atrMultiplier;
mAtrAppliedTo = config.atrAppliedTo;
mShowTrends = config.showTrends;
mFillTrends = config.fillTrends;
//
result = Init();
//
return result;
}
//
// Show Trends ...
bool ShowTrends(
bool show // Show or Hide
)
{
//
bool result = false;
//
if (mShowTrends == show)
{
return true;
}
//
mShowTrends = show;
result = Init();
//
return result;
}
//
// Fill Trends ...
bool FillTrends(
bool show // Show or Hide
)
{
//
bool result = false;
//
if (mFillTrends == show)
{
return true;
}
//
mFillTrends = show;
result = Init();
//
return result;
}
//
// Reading Buffers based on Given Bar Index ...
virtual void Calculate(
int barIndex // Given Bar Index
)
{
//
// MAIN ...
ArraySetAsSeries(mainBuffer, true);
CopyBuffer(
mHandler,
XSTR_LINE,
barIndex,
mLoopbackBars,
mainBuffer);
//
// TREND ...
ArraySetAsSeries(trendBuffer, true);
CopyBuffer(
mHandler,
XSTR_TREND_LINE,
barIndex,
mLoopbackBars,
trendBuffer);
}
//
// Retrieve Info at Specific Bar Index ...
XSTRInfo GetInfo(
int barIndex // Given Bar Index
)
{
//
XSTRInfo result;
//
if (barIndex < 0)
{
barIndex = 0;
}
//
// Do Calculations ...
Calculate(barIndex);
//
// Generate Candle Time ...
datetime barTime = GetCandleTime(
mSymbol,
mPeriod,
barIndex);
//
// Fill Result ...
result.symbol = mSymbol;
result.period = mPeriod;
result.barTime = barTime;
result.barIndex = barIndex;
//
double main = mainBuffer[barIndex];
ENUM_XSTR_TREND trend = (ENUM_XSTR_TREND)trendBuffer[barIndex];
ENUM_XSTR_TREND trendPrev = (ENUM_XSTR_TREND)trendBuffer[barIndex + 1];
//
Copy(
mainBuffer,
result.mains);
Copy(
trendBuffer,
result.trends);
//
result.main = main;
result.trend = trend;
//
result.isTrendBullish =
trend == XSTR_BULLISH;
//
result.isTrendBearish =
trend == XSTR_BEARISH;
//
result.isTrendSwitchedToBullish =
trend == XSTR_BULLISH &&
trendPrev != XSTR_BULLISH;
//
result.isTrendSwitchedToBearish =
trend == XSTR_BEARISH &&
trendPrev != XSTR_BEARISH;
//
return result;
}
//
// END Provided Functions ...
//
//
// Protected ...
protected:
//
// Private ...
private:
//
// Indicator Properties ...
//
// Market ...
//
// Length ...
int mAtrLength;
//
// Multiplier ...
double mAtrMultiplier;
//
// Applied To ...
ENUM_APPLIED_PRICE mAtrAppliedTo;
//
// Presentation ...
//
// Show Trends ...
bool mShowTrends;
//
// Fill Trends ...
bool mFillTrends;
};
//
// START Usefull Functions ...
//
//
// END Usefull Functions ...
//

Some files were not shown because too many files have changed in this diff Show More