Initial Commit ...

This commit is contained in:
2024-01-25 04:09:42 +03:30
commit b2037e07eb
1991 changed files with 668083 additions and 0 deletions
View File
+197
View File
@@ -0,0 +1,197 @@
///////////////////////////////////////////////////////
//
// 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 = true; // Terminal Alerts
input bool mailAlerts = true; // Mail Alerts
input bool pushAlerts = true; // 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)
{
//
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);
}
}
void SendAlert(
XSignal &signal, // the Signal Object which requred to Alert
bool asExecuted = true // determines Alert Signal as Executed Signal or not
)
{
//
// Prepare Message ...
string message = asExecuted ? ExecutedSignalToString(signal) : SignalToString(signal);
//
// Do Alerting ...
SendAlert(message);
}
//
// END Provided Functions ...
//
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+177
View File
@@ -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 ...
//
+161
View File
@@ -0,0 +1,161 @@
///////////////////////////////////////////////////////
//
// SaherElm IT Center MQL5 Logger Library
// ---------------------------------------
// Name: XLogger
// Description: provides Logging abilities ...
//
//
// Maintainer:
// ------------
// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com)
//
//////////////////////////////////////////////////////
//
// Global Properties ...
#property library
#property copyright "Copyright 2023, SaherElm IT Center"
#property link "https://www.saherelm.ir"
#property version "1.00"
#property strict
//
// START Inputs ...
//
input group "Logging";
input bool enableLogging = true; // Enable Logging
//
// END Inputs ...
//
//
// Including Models ...
#include "x-saherelm.models.lib.mq5"
//
// START Global Definitions: Variables, Properties and etc ...
//
string logTag = "X-Logger"; // LogTag
//
// END Global Definitions: Variables, Properties and etc ...
//
//
// START Provided Functions ...
//
//
// Logging a Message ...
void LogMessage(string message)
{
//
if (!enableLogging)
{
return;
}
//
Print(logTag, " > ", message);
}
void LogMessage(string tag, string message)
{
//
if (!enableLogging)
{
return;
}
//
Print(tag, " > ", message);
}
//
// Logging an Array ...
void LogArray(int &array[])
{
//
if (!enableLogging)
{
return;
}
//
Print(logTag, ">");
ArrayPrint(array);
}
void LogArray(double &array[])
{
//
if (!enableLogging)
{
return;
}
//
Print(logTag, ">");
ArrayPrint(array);
}
void LogArray(string &array[])
{
//
if (!enableLogging)
{
return;
}
//
Print(logTag, ">");
ArrayPrint(array);
}
//
// Convert a Signal to String Message ...
string SignalToString(XSignal &signal)
{
//
string result = "";
//
result += (signal.type == X_SIGNAL_LONG ? "Buy" : "Sell") + " Signal provided on (" + signal.symbol + " _ " + EnumToString(_Period) + ") by this comment: " + signal.comment;
//
return result;
}
//
// Convert an Executed Signal to String Message ...
string ExecutedSignalToString(XSignal &signal)
{
//
string result = "";
//
result += (signal.type == X_SIGNAL_LONG ? "Buy" : "Sell") + " Signal Executed provided on (" + signal.symbol + " _ " + EnumToString(_Period) + ") by this comment: " + signal.comment;
//
return result;
}
//
// Logging Signal ...
void LogSignal(XSignal &signal)
{
//
string message = SignalToString(signal);
//
LogMessage(message);
}
//
// Log Signal Execution ...
void LogExecutedSignal(XSignal &signal)
{
//
string message = ExecutedSignalToString(signal);
//
LogMessage(message);
}
//
// END Provided Functions ...
//
+146
View File
@@ -0,0 +1,146 @@
///////////////////////////////////////////////////////
//
// 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 ...
//
//
// START Model Definitions ...
//
//
// OHCL Candel Model ...
enum ENUM_X_PRICE
{
X_PRICE_HIGH,
X_PRICE_OPEN,
X_PRICE_CLOSE,
X_PRICE_LOW
};
//
// Describe an Specific Candle ...
struct XOHCL
{
double high;
double open;
double close;
double low;
};
//
// Swing Types Enum ...
enum ENUM_X_SWING_TYPE
{
X_NO_SWING = 0,
X_SWING_HIGH = 1,
X_SWING_LOW = -1,
};
//
// Signal Types ...
enum ENUM_X_SIGNAL_TYPE
{
X_SIGNAL_LONG,
X_SIGNAL_SHORT,
X_SIGNAL_UNKNOWN,
};
//
// Signal Structure ...
struct XSignal
{
//
// Identifier ...
ulong id;
//
// Which Symbol used for Signal ...
string symbol;
//
// Which Type of operations ...
ENUM_X_SIGNAL_TYPE type;
//
// Magic Number ...
ulong magicNumber;
//
// Ticket ...
ulong ticket;
//
// Entry/Open Price ...
double entry;
//
// TP ...
double tp;
//
// SL ...
double sl;
//
// Trade Profit ...
double profit;
//
// Time of Operation ...
datetime time;
//
// Volume ...
double volume;
//
// Comment ...
string comment;
};
//
// TP/SL Struct ...
struct XTPSL
{
ENUM_X_SIGNAL_TYPE type;
double tp;
double sl;
double entry;
double r2r;
};
//
// END Provided Functions ...
//
+258
View File
@@ -0,0 +1,258 @@
///////////////////////////////////////////////////////
//
// SaherElm IT Center MQL5 NN Class Library
// ----------------------------------------
// Name: XNNClass
// Description: provides all classes for implementing
// Neural Network ...
//
//
// 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 Global Definitions: Variables, Properties and etc ...
//
class XCNNBase
{
//
// Public Definitions ...
public:
//
// Constructor ...
void XCNNBase(
int nodes = 10, // Number of Input Nodes
double starterWeight = 0.5, // start weight for each input
double coEfficient = 0.1, // COEfficient Multiplier
double upperRange = 1, // Upper Normal Range Value
double lowerRange = -1, // Lower Normal Range Value
double learningRates = 0.1 // Back Propagation Learning Rate
) {
//
mNodes = nodes;
mUpperRange = upperRange;
mLowerRange = lowerRange;
mCoEfficient = coEfficient;
mLearningRates = learningRates;
mStarterWeight = starterWeight;
//
ReConstructWeights();
}
//
// Deconstructor ...
void ~XCNNBase() {}
//
// Protected Definitions ...
void NormalizeInputs(double &inputs[], double &result[])
{
//
ArrayFree(result);
ArrayResize(result, 1);
//
// Validate inputs ...
if (ArraySize(inputs) != mNodes)
{
return;
}
//
// Prepare Result ...
ArrayResize(result, mNodes);
//
// Calculating min and max range value ...
double minRangeValue = inputs[ArrayMinimum(inputs)];
double maxRangeValue = inputs[ArrayMaximum(inputs)];
//
// Loop through Inputs nd Normalize them ...
for (int i = 0; i < mNodes; i++)
{
//
double normalValue = (((inputs[i] - minRangeValue) * (mUpperRange - mLowerRange)) / (maxRangeValue - minRangeValue)) + mLowerRange;
result[i] = normalValue;
}
}
//
// Hyperbolic Tangent Activation Function ...
double TanHActivationFunction(double weightedInputs)
{
//
double result = (exp(weightedInputs) - exp(-weightedInputs)) / (exp(weightedInputs) + exp(-weightedInputs));
return result;
}
//
// Calculate Weighted Inputs ...
double CalculateWeightedInputs(
double &inputs[],
bool applyCOEfficient = true)
{
//
double result = 0;
//
// Validate Inputs ...
if (ArraySize(inputs) != mNodes)
{
//
result = -1;
return result;
}
//
for (int i = 0; i < mNodes; i++)
{
result += inputs[i] * mWeights[i];
}
//
// Multiply if required ...
if (applyCOEfficient)
{
result *= mCoEfficient;
}
//
return result;
}
//
// Calculate Hidden Layers ...
virtual double CalculateHiddenLayer(double &inputs[])
{
//
// this is Default Activation Function which used ...
// you can override this by writing your own ...
double totalWeightedInputs = CalculateWeightedInputs(inputs);
double result = TanHActivationFunction(totalWeightedInputs);
//
return result;
}
//
// Calculate Output Layers ...
double CalculateOutputLayer(double &inputs[])
{
//
double result = -1;
//
// Validate Inputs ...
if (ArraySize(inputs) != mNodes) {
return result;
}
//
double normalizedInputs[];
NormalizeInputs(inputs, normalizedInputs);
if (ArraySize(normalizedInputs) != mNodes) {
return result;
}
//
double hiddenLayerResult = CalculateHiddenLayer(normalizedInputs);
//
result = 1 * hiddenLayerResult;
//
return result;
}
//
// Basck Propaggation Learning ...
void BackPropagation(
double &inputs[],
double &outputs,
double targetOutput
) {
//
// Validate Inputs ...
if (ArraySize(inputs) != mNodes) {
return;
}
//
double normalizedInputs[];
NormalizeInputs(inputs, normalizedInputs);
if (ArraySize(normalizedInputs) != mNodes) {
return;
}
//
double error = targetOutput - outputs;
double derivative = 1 - MathPow(outputs, 2);
//
for (int i = 0; i < mNodes; i++) {
//
double gradient = error * derivative * inputs[i];
mWeights[i] = mLearningRates * gradient;
}
}
protected:
//
// Private Definitions ...
private:
//
// Number of Input Nodes ...
int mNodes;
//
// Specify Upper range of Normal Values ...
double mUpperRange;
//
// Specify Lower range of Normal Values ...
double mLowerRange;
//
// Starter Weight for each input node ...
double mStarterWeight;
//
// double Input Node Weights ...
double mWeights[];
//
// CoEfficient is a multiplyer for weighted inputs ...
double mCoEfficient;
//
// Back Propagation Learning Rates ...
double mLearningRates;
//
// ReConstruct Weights ...
void ReConstructWeights() {
//
ArrayFree(mWeights);
ArrayResize(mWeights, mNodes);
//
for (int i = 0; i< mNodes; i++) {
mWeights[i] = mStarterWeight;
}
}
}
//
// END Global Definitions: Variables, Properties and etc ...
//
@@ -0,0 +1,126 @@
/////////////////////////////////////////////////////////////////////////////
//
// SaherElm IT Center MQL5 _INDICATOR_ Indicator Helper for Signal Providers
// --------------------------------------------------------------------------
//
//
// Maintainer:
// ------------
// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com)
//
/////////////////////////////////////////////////////////////////////////////
//
// Global Properties ...
#property library
#property copyright "Copyright 2023, SaherElm IT Center"
#property link "https://www.saherelm.ir"
#property version "1.00"
#property strict
//
// Includes ...
#include "..\Libraries\x-saherelm.log.lib.mq5"
#include "..\Libraries\x-saherelm.common.lib.mq5"
//
// TODO: Include Main Provider Inputs ...
// #include "x-saherelm.xmap.provider.inputs.lib.mq5"
//
// START Inputs ...
//
input group "_INDICATOR_ Indicator/Oscillator";
// TODO: Implement Named Indicator/Oscillator Specific Inputs here ...
//
// END Inputs ...
//
//
// START Definitions ...
int _iNDICATOR_Handler = INVALID_HANDLE;
//
// TODO: Define Specific Buffers here ...
// double _iNDICATOR_Buffer[];
//
// END Definitions ...
//
//
// START Handler Functions ...
//
//
// Init Indicators ...
bool _INDICATOR_InitHandlers()
{
//
bool result = false;
//
// Initialize Indicator/Oscillator Handlers ...
ResetLastError();
//
// _INDICATOR_ Handler ...
// TODO: Set As Buffer Series ...
// ArraySetAsSeries(_iNDICATOR_Buffer, true);
_iNDICATOR_Handler = iCustom(
_Symbol,
_Period,
// TODO: Set Indicator Name ...
""
//
// Inputs ...
// TODO: Attach Inputs here ...
//
);
if (_iNDICATOR_Handler == INVALID_HANDLE)
{
//
// TODO: Edit Error Message ...
LogMessage("failed to Initialize _INDICATOR_ Indicator: " + (string)GetLastError());
return result;
}
//
result = true;
//
return result;
}
//
// Release Indicators ...
void _INDICATOR_ReleaseHandlers()
{
IndicatorRelease(_iNDICATOR_Handler);
}
//
// Handle Reading Buffers ...
void _INDICATOR_ReadBuffers()
{
//
// TODO: Fix Copy Buffer ...
// CopyBuffer(
// _iNDICATOR_Handler,
// 0,
// 0,
// //
// // TODO: Use Global Number Of Items Per Tick ...
// 0
// //
// // TODO Define Which buffer to save results ...
// // _iNDICATOR_Buffer
// //
// );
}
//
// END Handler Funcions ...
//
//
// START _INDICATOR_ Custom Functions ...
//
// TODO: Attach all Aditional Helper Functions for Specific Indicator/Oscillator here ...
//
// END _INDICATOR_ Custom Functions ...
//
@@ -0,0 +1,758 @@
////////////////////////////////////////////////////////////
//
// SaherElm IT Center MQL5 _XPROVIDER_ Signal Provider Library
// --------------------------------------------------------
// Name: _XPROVIDER_SignalProvider
// Description: _XPROVIDER_ based signal provider ...
//
//
// Maintainer:
// ------------
// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com)
//
//////////////////////////////////////////////////////
//
// Global Properties ...
#property library
#property copyright "Copyright 2023, SaherElm IT Center"
#property link "https://www.saherelm.ir"
#property version "1.00"
#property strict
//
// START Inputs ...
//
input group "_XPROVIDER_ Provider";
//
input group "_XPROVIDER_ Common";
input bool enable_XPROVIDER_Provider = true; // Enable Provider
input bool _xPROVIDER_EnableAlerts = true; // Enable Events Alert
//
input group "_XPROVIDER_ Indicator";
//
input group "_XPROVIDER_ Trader";
input int _xPROVIDER_MagicNumber = 16940562; // Trader MagicNumber
input int _xPROVIDER_Slippage = 10; // Trader Slippage
//
input group "_XPROVIDER_ Trade Management";
input bool _xPROVIDER_AllowLongTrades = true; // Allow Long Trades
input bool _xPROVIDER_AllowShortTrades = true; // Allow Short Trades
input bool _xPROVIDER_UseGridTrades = true; // Enable Grid Trades
input double _xPROVIDER_GridVolumeMultiplier = 2; // Grid Volume Multiplier
input double _xPROVIDER_GridDistancePips = 10; // Grid Position Distance in Pips
//
input group "_XPROVIDER_ Risk Management";
input bool _xPROVIDER_UseDynamicVolume = true; // Enable Dynamic Volume
input double _xPROVIDER_StaticVolume = 0.01; // Static Volume
input double _xPROVIDER_BalanceIncreased = 500; // Balance Increase
input double _xPROVIDER_VolumeIncreased = 0.01; // Volume Increase
//
// END Inputs ...
//
//
// Include Common Library ...
#include "x-saherelm.common.lib.mq5"
//
// Include Logger Library ...
#include "x-saherelm.log.lib.mq5"
//
// Include Alert Library ...
#include "x-saherelm.alert.lib.mq5"
//
// Include Draw Library ...
#include "x-saherelm.draw.lib.mq5"
//
// Include Class Libraries ...
#include "x-saherelm.class.lib.mq5"
//
// START Global Definitions: Variables, Properties and etc ...
//
//
XCTrade *_xPROVIDER_Trader;
XCAccountInfo _xPROVIDER_AccountInfo;
//
double _xPROVIDER_GridLongPrice = 0;
double _xPROVIDER_GridLongVolume = 0;
//
double _xPROVIDER_GridShortPrice = 0;
double _xPROVIDER_GridShortVolume = 0;
//
// END Global Definitions: Variables, Properties and etc ...
//
//
// START Provided Functions ...
//
//
// Initial Library if required ...
bool OnInInit_XPROVIDER_SignalProviderLibrary()
{
//
bool result = false;
//
// Error Message ...
string message = "";
//
// Check Risk Management ...
if (_xPROVIDER_UseDynamicVolume)
{
//
if (_xPROVIDER_BalanceIncreased <= 0 || _xPROVIDER_VolumeIncreased <= 0)
{
//
message = "invalid volume increased factors ...";
LogMessage(message);
//
return result;
}
}
else
{
//
double maxAvailableVolume = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX);
double minAvailableVolume = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN);
//
if (_xPROVIDER_StaticVolume > maxAvailableVolume || _xPROVIDER_StaticVolume < minAvailableVolume)
{
//
message = "invalid static volume ...";
LogMessage(message);
//
return result;
}
}
//
// Make XCTrader instance ...
_xPROVIDER_Trader = new XCTrade(
_Symbol,
_xPROVIDER_Slippage,
_xPROVIDER_MagicNumber);
//
result = true;
//
// Logging State ...
message = "Initializion of (" + "_XPROVIDER_ Provider" + " _ " + _Symbol + " _ " + EnumToString(_Period) + ") Succeeded ...";
LogMessage(message);
//
return result;
}
//
// DeInitial Library if required ...
void OnDeinit_XPROVIDER_SignalProviderLibrary()
{
//
// Logging State ...
string message = "De Initializion of (" + "_XPROVIDER_ Provider" + ") Succeeded ...";
LogMessage(message);
}
//
// this is a Globally Function which do all of
// checkings and positions handling ...
void Handle_XPROVIDER_SignalProviderTick()
{
//
// Handle Open Trades ...
_XPROVIDER_HandleOpenTrades();
//
// Handle Close Trades ...
_XPROVIDER_HandleCloseTrades();
}
//
// Check Market Conditions to find Long Primary Signals ...
bool _XPROVIDER_HasPrimaryLongSignal()
{
//
bool result = false;
//
// Check Buy/Long Conditions ...
//
return result;
}
//
// Check Market Conditions to find Short Primary Signals ...
bool _XPROVIDER_HasPrimaryShortSignal()
{
//
bool result = false;
//
// Check Sell/Short Conditions ...
//
return result;
}
//
// Check Market Conditions to find Long Grid Signals ...
bool _XPROVIDER_HasGridLongSignal()
{
//
bool result = false;
//
// Check Buy/Long Conditions ...
//
return result;
}
//
// Check Market Conditions to find Short Grid Signals ...
bool _XPROVIDER_HasGridShortSignal()
{
//
bool result = false;
//
// Check Sell/Short Conditions ...
//
return result;
}
//
// Check Market Conditions for closing Long Trades ...
bool _XPROVIDER_CanCloseLongTrades()
{
//
bool result = false;
//
return result;
}
//
// Check Market Conditions for closing Short Trades ...
bool _XPROVIDER_CanCloseShortTrades()
{
//
bool result = false;
//
return result;
}
//
// Handle Long/Buy for Primary Trades...
bool _XPROVIDER_HandlePrimaryLong(
XSignal &signal, // return structure if signal founded
bool doTrade = true // do trade on signal
)
{
//
bool result = false;
//
ResetLastError();
//
if (_XPROVIDER_HasPrimaryLongSignal() && _xPROVIDER_Trader.CountLongs() == 0)
{
//
double entry = GetAsk();
double volume = _XPROVIDER_CalculateVolume();
//
double canDoTrade = _XPROVIDER_CanDoTrade();
//
signal.entry = entry;
signal.volume = volume;
signal.symbol = _Symbol;
signal.type = X_SIGNAL_LONG;
signal.magicNumber = _xPROVIDER_MagicNumber;
signal.time = iTime(_Symbol, _Period, 0);
signal.comment = "Primary _XPROVIDER_ Long";
//
if (enable_XPROVIDER_Provider && _xPROVIDER_AllowLongTrades && doTrade && canDoTrade)
{
//
// Execute Signal ...
result = _xPROVIDER_Trader.ExecuteSignal(signal);
//
// Since this means an error happens, we have to log this error ...
if (!result)
{
string errMessage = "failed to execute Long signal: " + (string)GetLastError();
LogMessage(errMessage);
}
}
else
{
result = false;
}
}
//
// Handle Alerts ...
if (result)
{
//
if (_xPROVIDER_EnableAlerts)
{
SendAlert(signal, true);
}
else
{
LogExecutedSignal(signal);
}
}
//
return result;
}
//
// Handle Short/Sell for Primary Trades...
bool _XPROVIDER_HandlePrimaryShort(
XSignal &signal, // return structure if signal founded
bool doTrade = true // do trade on signal
)
{
//
bool result = false;
//
ResetLastError();
//
if (_XPROVIDER_HasPrimaryShortSignal() && _xPROVIDER_Trader.CountShorts() == 0)
{
//
double entry = GetBid();
double volume = _XPROVIDER_CalculateVolume();
//
double canDoTrade = _XPROVIDER_CanDoTrade();
//
signal.entry = entry;
signal.volume = volume;
signal.symbol = _Symbol;
signal.type = X_SIGNAL_SHORT;
signal.magicNumber = _xPROVIDER_MagicNumber;
signal.time = iTime(_Symbol, _Period, 0);
signal.comment = "Primary _XPROVIDER_ Short";
//
if (enable_XPROVIDER_Provider && _xPROVIDER_AllowShortTrades && doTrade && canDoTrade)
{
//
// Execute Signal ...
result = _xPROVIDER_Trader.ExecuteSignal(signal);
//
// Since this means an error happens, we have to log this error ...
if (!result)
{
string errMessage = "failed to execute Short signal: " + (string)GetLastError();
LogMessage(errMessage);
}
}
else
{
result = false;
}
}
//
// Handle Alerts ...
if (result)
{
//
if (_xPROVIDER_EnableAlerts)
{
SendAlert(signal, true);
}
else
{
LogExecutedSignal(signal);
}
}
//
return result;
}
//
// Handle Long/Buy for Grid Trades...
bool _XPROVIDER_HandleGridLong(
XSignal &signal, // return structure if signal founded
bool doTrade = true // do trade on signal
)
{
//
bool result = false;
//
ResetLastError();
//
double ask = GetAsk();
bool canDoGridTrade = ask <= _xPROVIDER_GridLongPrice;
if (_XPROVIDER_HasGridLongSignal() && _xPROVIDER_Trader.CountLongs() > 0 && canDoGridTrade)
{
//
double entry = ask;
double volume = _xPROVIDER_GridLongVolume;
//
double canDoTrade = _XPROVIDER_CanDoTrade();
//
signal.entry = entry;
signal.volume = volume;
signal.symbol = _Symbol;
signal.type = X_SIGNAL_LONG;
signal.magicNumber = _xPROVIDER_MagicNumber;
signal.time = iTime(_Symbol, _Period, 0);
signal.comment = "Grid _XPROVIDER_ Long";
//
if (enable_XPROVIDER_Provider && _xPROVIDER_AllowLongTrades && _xPROVIDER_UseGridTrades && doTrade && canDoTrade)
{
//
// Execute Signal ...
result = _xPROVIDER_Trader.ExecuteSignal(signal);
//
// Since this means an error happens, we have to log this error ...
if (!result)
{
string errMessage = "failed to execute Long signal: " + (string)GetLastError();
LogMessage(errMessage);
}
}
else
{
result = false;
}
}
//
// Handle Alerts ...
if (result)
{
//
if (_xPROVIDER_EnableAlerts)
{
SendAlert(signal, true);
}
else
{
LogExecutedSignal(signal);
}
}
//
return result;
}
//
// Handle Short/Sell for Grid Trades...
bool _XPROVIDER_HandleGridShort(
XSignal &signal, // return structure if signal founded
bool doTrade = true // do trade on signal
)
{
//
bool result = false;
//
ResetLastError();
//
double bid = GetBid();
bool canDoGridTrade = bid >= _xPROVIDER_GridShortPrice;
if (_XPROVIDER_HasGridShortSignal() && _xPROVIDER_Trader.CountShorts() > 0 && canDoGridTrade)
{
//
double entry = bid;
double volume = _xPROVIDER_GridShortVolume;
//
double canDoTrade = _XPROVIDER_CanDoTrade();
//
signal.entry = entry;
signal.volume = volume;
signal.symbol = _Symbol;
signal.type = X_SIGNAL_SHORT;
signal.magicNumber = _xPROVIDER_MagicNumber;
signal.time = iTime(_Symbol, _Period, 0);
signal.comment = "Grid _XPROVIDER_ Short";
//
if (enable_XPROVIDER_Provider && _xPROVIDER_AllowShortTrades && _xPROVIDER_UseGridTrades && doTrade && canDoTrade)
{
//
// Execute Signal ...
result = _xPROVIDER_Trader.ExecuteSignal(signal);
//
// Since this means an error happens, we have to log this error ...
if (!result)
{
string errMessage = "failed to execute Short signal: " + (string)GetLastError();
LogMessage(errMessage);
}
}
else
{
result = false;
}
}
//
// Handle Alerts ...
if (result)
{
//
if (_xPROVIDER_EnableAlerts)
{
SendAlert(signal, true);
}
else
{
LogExecutedSignal(signal);
}
}
//
return result;
}
//
// Handle Open Trades ...
void _XPROVIDER_HandleOpenTrades()
{
//
// Primary Long Trade ...
XSignal primaryLongSignal = {};
bool isPrimaryLongSignalExecuted = _XPROVIDER_HandlePrimaryLong(primaryLongSignal);
if (isPrimaryLongSignalExecuted)
{
//
// Calculate Grid Long Conditions ...
_XPROVIDER_CalculateGridLongConditions(primaryLongSignal);
}
//
// Primary Short Trade ...
XSignal primaryShortSignal = {};
bool isPrimaryShortSignalExecuted = _XPROVIDER_HandlePrimaryShort(primaryShortSignal);
if (isPrimaryShortSignalExecuted)
{
//
// Calculate Grid Short Conditions ...
_XPROVIDER_CalculateGridShortConditions(primaryShortSignal);
}
//
// Check Grid Trades ...
if (_xPROVIDER_UseGridTrades)
{
//
// Grid Long Trade ...
XSignal gridLongSignal = {};
bool isGridLongSignalExecuted = _XPROVIDER_HandleGridLong(gridLongSignal);
if (isGridLongSignalExecuted)
{
//
// Calculate Grid Long Conditions ...
_XPROVIDER_CalculateGridLongConditions(gridLongSignal);
}
//
// Grid Short Trade ...
XSignal gridShortSignal = {};
bool isGridShortSignalExecuted = _XPROVIDER_HandleGridShort(gridShortSignal);
if (isGridShortSignalExecuted)
{
//
// Calculate Grid Short Conditions ...
_XPROVIDER_CalculateGridShortConditions(gridShortSignal);
}
}
}
//
// Handle Close Trades ...
void _XPROVIDER_HandleCloseTrades()
{
//
// Handle Long/Buy Close ...
if (_xPROVIDER_Trader.CountLongs() > 0 && _XPROVIDER_CanCloseLongTrades())
{
//
_xPROVIDER_Trader.CloseLongPositions();
//
// Reset Grid Long Conditions ...
_xPROVIDER_GridLongPrice = 0;
_xPROVIDER_GridLongVolume = 0;
//
string message = "_XPROVIDER_ Closing Long Trades ...";
//
if (_xPROVIDER_EnableAlerts)
{
SendAlert(message);
}
else
{
LogMessage(message);
}
}
//
// Handle Short/Sell Close ...
if (_xPROVIDER_Trader.CountShorts() > 0 && _XPROVIDER_CanCloseShortTrades())
{
//
_xPROVIDER_Trader.CloseShortPositions();
//
// Reset Grid Short Conditions ...
_xPROVIDER_GridShortPrice = 0;
_xPROVIDER_GridShortVolume = 0;
//
string message = "_XPROVIDER_ Closing Short Trades ...";
//
if (_xPROVIDER_EnableAlerts)
{
SendAlert(message);
}
else
{
LogMessage(message);
}
}
}
//
// Calculating Volume for Tradings ...
double _XPROVIDER_CalculateVolume()
{
//
double result = _xPROVIDER_StaticVolume;
if (!_xPROVIDER_UseDynamicVolume)
{
return result;
}
//
double accountBalance = _xPROVIDER_AccountInfo.GetBalance();
double balanceIncreased = _xPROVIDER_BalanceIncreased;
double volumeIncreased = _xPROVIDER_VolumeIncreased;
//
result = (volumeIncreased * accountBalance) / balanceIncreased;
//
// Normalize Volume ...
result = NormalizeDouble(result, 2);
//
double maxAvailableVolume = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX);
double minAvailableVolume = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN);
//
// Validate Result ...
if (result > maxAvailableVolume)
{
result = maxAvailableVolume;
}
else if (result < minAvailableVolume)
{
result = minAvailableVolume;
}
//
return result;
}
//
// Calculate Grid Long Trades Price and Volume ...
void _XPROVIDER_CalculateGridLongConditions(XSignal &signal)
{
//
// Check Grid Trades Enable ...
if (!_xPROVIDER_UseGridTrades)
{
return;
}
//
// Calculate GridLongPrice and GridLongVolume ...
_xPROVIDER_GridLongVolume = NormalizeDouble(signal.volume * _xPROVIDER_GridVolumeMultiplier, 2);
_xPROVIDER_GridLongPrice = NormalizeDouble(signal.entry - (_xPROVIDER_GridDistancePips * 10 * _Point), _Digits);
}
//
// Calculate Grid Short Trades Price and Volume ...
void _XPROVIDER_CalculateGridShortConditions(XSignal &signal)
{
//
// Check Grid Trades Enable ...
if (!_xPROVIDER_UseGridTrades)
{
return;
}
//
// Calculate GridShortPrice and GridShortVolume ...
_xPROVIDER_GridShortVolume = NormalizeDouble(signal.volume * _xPROVIDER_GridVolumeMultiplier, 2);
_xPROVIDER_GridShortPrice = NormalizeDouble(signal.entry + (_xPROVIDER_GridDistancePips * 10 * _Point), _Digits);
}
//
// Determine based on current account state
bool _XPROVIDER_CanDoTrade()
{
//
bool result = true;
//
// TODO: Complete this ...
//
return true;
}
//
// END Provided Functions ...
//
@@ -0,0 +1,834 @@
/////////////////////////////////////////////////////////////////////////////
//
// SaherElm IT Center MQL5 XCHMA Oscillator Helper for Signal Providers
// --------------------------------------------------------------------------
//
// Maintainer:
// ------------
// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com)
//
/////////////////////////////////////////////////////////////////////////////
//
// Global Properties ...
#property library
#property copyright "Copyright 2023, SaherElm IT Center"
#property link "https://www.saherelm.ir"
#property version "1.00"
#property strict
//
// Includes ...
#include "..\Libraries\x-saherelm.log.lib.mq5"
#include "..\Libraries\x-saherelm.common.lib.mq5"
//
// START Enum Definitions ...
//
//
// XCHMA Oscillator Hot State Presentation ...
enum ENUM_XCHMA_HOT_STATES
{
X_XCHMA_HOT_BULLISH = 1,
X_XCHMA_HOT_NEUTURAL = 0,
X_XCHMA_HOT_BEARISH = -1,
};
//
// XCHMA Oscillator Cycles State Presentation ...
enum ENUM_XCHMA_CYCLE_STATES
{
X_XCHMA_FAST_CROSSED_OVER_SLOW = 2,
X_XCHMA_FAST_OVER_SLOW = 1,
X_XCHMA_NEUTURAL = 0,
X_XCHMA_FAST_UNDER_SLOW = -1,
X_XCHMA_FAST_CROSSED_UNDER_SLOW = -2,
};
//
// XCHMA Oscillator Buffer Lines ...
enum ENUM_X_XCHMA_BUFFER_LINES
{
X_XCHMA_LC_FAST_LINE = 0,
X_XCHMA_LC_SLOW_LINE = 1,
X_XCHMA_LC_STATE_LINE = 6,
X_XCHMA_MC_FAST_LINE = 2,
X_XCHMA_MC_SLOW_LINE = 3,
X_XCHMA_MC_STATE_LINE = 7,
X_XCHMA_SC_FAST_LINE = 4,
X_XCHMA_SC_SLOW_LINE = 5,
X_XCHMA_SC_STATE_LINE = 8,
X_XCHMA_HOT_STATE_LINE = 9,
};
//
// END Enum Definitions ...
//
//
// START Inputs ...
//
input group "XCHMA Oscillator";
//
// Commons ...
input group "XCHMA Hot Areas";
input bool xCHMADrawHotAreas = false; // Draw Hot Areas Symbol;
input uchar xCHMAHotBullishArrowCode = 228; // Hot Bullish Arrow Code;
input color xCHMAHotBullishArrowColor = clrAqua; // Hot Bullish Arrow Color;
input uchar xCHMAHotBearishArrowCode = 230; // Hot Bearish Arrow Code;
input color xCHMAHotBearishArrowColor = clrFuchsia; // Hot Bearish Arrow Color;
//
// LC Inputs ...
input group "XCHMA Long Cycle";
input group "XCHMA LC Market";
input int xCHMALcFastLength = 288; // Fast Length
input int xCHMALcSlowLength = 576; // Slow Length
input ENUM_MA_METHOD xCHMALcMethod = MODE_EMA; // Calculation Method
input ENUM_APPLIED_PRICE xCHMALcAppliedTo = PRICE_CLOSE; // Applied To
input group "XCHMA LC Style";
input int xCHMALcDrawWidth = 1; // Draw Width
input ENUM_DRAW_TYPE xCHMALcDrawType = DRAW_LINE; // Draw Type
input ENUM_LINE_STYLE xCHMALcDrawStyle = STYLE_DOT; // Draw Style
input color xCHMALcFastColor = clrAqua; // Fast Color
input color xCHMALcSlowColor = clrFuchsia; // Slow Color
input group "XCHMA LC Drawings";
input bool xCHMALcDrawFast = true; // Draw Fast
input bool xCHMALcDrawSlow = true; // Draw Slow
input bool xCHMALcDrawCrosses = false; // Draw Cross Lines
//
// MC Inputs ...
input group "XCHMA Medium Cycle";
input group "XCHMA MC Market";
input int xCHMAMcFastLength = 72; // Fast Length
input int xCHMAMcSlowLength = 144; // Slow Length
input ENUM_MA_METHOD xCHMAMcMethod = MODE_EMA; // Calculation Method
input ENUM_APPLIED_PRICE xCHMAMcAppliedTo = PRICE_CLOSE; // Applied To
input group "XCHMA MC Style";
input int xCHMAMcDrawWidth = 1; // Draw Width
input ENUM_DRAW_TYPE xCHMAMcDrawType = DRAW_LINE; // Draw Type
input ENUM_LINE_STYLE xCHMAMcDrawStyle = STYLE_DOT; // Draw Style
input color xCHMAMcFastColor = clrLime; // Fast Color
input color xCHMAMcSlowColor = clrRed; // Slow Color
input group "XCHMA MC Drawings";
input bool xCHMAMcDrawFast = true; // Draw Fast
input bool xCHMAMcDrawSlow = true; // Draw Slow
input bool xCHMAMcDrawCrosses = false; // Draw Cross Lines
//
// SC Inputs ...
input group "XCHMA Short Cycle";
input group "XCHMA SC Market";
input int xCHMAScFastLength = 7; // Fast Length
input int xCHMAScSlowLength = 14; // Slow Length
input ENUM_MA_METHOD xCHMAScMethod = MODE_EMA; // Calculation Method
input ENUM_APPLIED_PRICE xCHMAScAppliedTo = PRICE_CLOSE; // Applied To
input group "XCHMA SC Style";
input int xCHMAScDrawWidth = 1; // Draw Width
input ENUM_DRAW_TYPE xCHMAScDrawType = DRAW_LINE; // Draw Type
input ENUM_LINE_STYLE xCHMAScDrawStyle = STYLE_SOLID; // Draw Style
input color xCHMAScFastColor = clrLightBlue; // Fast Color
input color xCHMAScSlowColor = clrLightSalmon; // Slow Color
input group "XCHMA SC Drawings";
input bool xCHMAScDrawFast = true; // Draw Fast
input bool xCHMAScDrawSlow = true; // Draw Slow
input bool xCHMAScDrawCrosses = false; // Draw Cross Lines
//
// END Inputs ...
//
//
// START Definitions ...
//
int xCHMAHandler = INVALID_HANDLE;
double xCHMALcFastBuffer[];
double xCHMALcSlowBuffer[];
double xCHMAMcFastBuffer[];
double xCHMAMcSlowBuffer[];
double xCHMAScFastBuffer[];
double xCHMAScSlowBuffer[];
//
// END Definitions ...
//
//
// START Handler Functions ...
//
//
// Init Oscillators ...
bool XCHMAInitHandlers()
{
//
bool result = false;
//
// Initialize Indicator/Oscillator Handlers ...
ResetLastError();
//
// XCHMA Handler ...
ArraySetAsSeries(xCHMALcFastBuffer, true);
ArraySetAsSeries(xCHMALcSlowBuffer, true);
ArraySetAsSeries(xCHMAMcFastBuffer, true);
ArraySetAsSeries(xCHMAMcSlowBuffer, true);
ArraySetAsSeries(xCHMAScFastBuffer, true);
ArraySetAsSeries(xCHMAScSlowBuffer, true);
xCHMAHandler = iCustom(
_Symbol,
_Period,
"x-saherelm.xchma.oscillator",
//
// Inputs ...
"",
xCHMADrawHotAreas,
xCHMAHotBullishArrowCode,
xCHMAHotBullishArrowColor,
xCHMAHotBearishArrowCode,
xCHMAHotBearishArrowColor,
//
// Long Cycle ...
"",
"",
xCHMALcFastLength,
xCHMALcSlowLength,
xCHMALcMethod,
xCHMALcAppliedTo,
"",
xCHMALcDrawWidth,
xCHMALcDrawType,
xCHMALcDrawStyle,
xCHMALcFastColor,
xCHMALcSlowColor,
"",
xCHMALcDrawFast,
xCHMALcDrawSlow,
xCHMALcDrawCrosses,
//
// Medium Cycle ...
"",
"",
xCHMAMcFastLength,
xCHMAMcSlowLength,
xCHMAMcMethod,
xCHMAMcAppliedTo,
"",
xCHMAMcDrawWidth,
xCHMAMcDrawType,
xCHMAMcDrawStyle,
xCHMAMcFastColor,
xCHMAMcSlowColor,
"",
xCHMAMcDrawFast,
xCHMAMcDrawSlow,
xCHMAMcDrawCrosses,
//
// Short Cycle ...
"",
"",
xCHMAScFastLength,
xCHMAScSlowLength,
xCHMAScMethod,
xCHMAScAppliedTo,
"",
xCHMAScDrawWidth,
xCHMAScDrawType,
xCHMAScDrawStyle,
xCHMAScFastColor,
xCHMAScSlowColor,
"",
xCHMAScDrawFast,
xCHMAScDrawSlow,
xCHMAScDrawCrosses);
if (xCHMAHandler == INVALID_HANDLE)
{
//
LogMessage("failed to Initialize XCHMA Oscillator: " + (string)GetLastError());
return result;
}
//
result = true;
//
return result;
}
//
// Release Oscillators ...
void XCHMAReleaseHandlers()
{
IndicatorRelease(xCHMAHandler);
}
//
// Handle Reading Buffers ...
void XCHMAReadBuffers(
int xCHMAItemsPerTick // Number Of Reading Buffer Items Per Tick
)
{
//
// XCHMA Long Cycle ...
//
// XCHMA Fast ...
CopyBuffer(
xCHMAHandler,
X_XCHMA_LC_FAST_LINE,
0,
xCHMAItemsPerTick,
xCHMALcFastBuffer);
//
// XCHMA Slow ...
CopyBuffer(
xCHMAHandler,
X_XCHMA_LC_SLOW_LINE,
0,
xCHMAItemsPerTick,
xCHMALcSlowBuffer);
//
// XCHMA Medium Cycle ...
//
// XCHMA Fast ...
CopyBuffer(
xCHMAHandler,
X_XCHMA_MC_FAST_LINE,
0,
xCHMAItemsPerTick,
xCHMAMcFastBuffer);
//
// XCHMA Slow ...
CopyBuffer(
xCHMAHandler,
X_XCHMA_MC_SLOW_LINE,
0,
xCHMAItemsPerTick,
xCHMAMcSlowBuffer);
//
// XCHMA Short Cycle ...
//
// XCHMA Fast ...
CopyBuffer(
xCHMAHandler,
X_XCHMA_SC_FAST_LINE,
0,
xCHMAItemsPerTick,
xCHMAScFastBuffer);
//
// XCHMA Slow ...
CopyBuffer(
xCHMAHandler,
X_XCHMA_SC_SLOW_LINE,
0,
xCHMAItemsPerTick,
xCHMAScSlowBuffer);
}
//
// END Handler Funcions ...
//
//
// START Signal Related Conditions ...
//
//
// XCHMA Long Conditions ...
bool XCHMAHasLongConditions(
int xCHMAItemsPerTick // Number Of Reading Buffer Items Per Tick
)
{
//
bool result = false;
//
return result;
}
//
// XCHMA Short Conditions ...
bool XCHMAHasShortConditions(
int xCHMAItemsPerTick // Number Of Reading Buffer Items Per Tick
)
{
//
bool result = false;
//
return result;
}
//
// END Signal Related Conditions ...
//
//
// START XCHMA Custom Functions ...
//
//
// Long Cycle ...
//
//
// Check LC is Peak ...
bool XCHMAIsLCPeak() {
//
bool result = false;
//
// TODO: Complete this ...
//
return result;
}
//
// Check LC is Vale ...
bool XCHMAIsLCVale() {
//
bool result = false;
//
// TODO: Complete this ...
//
return result;
}
//
// Check LC Fast Crossed Over Slow ...
bool XCHMAIsLCFastCrossedOverSlow(
int bar_index // Specified Index ...
)
{
//
bool result = false;
//
if (
bar_index <= 0 ||
!XCHMAIsValidBuffersSize(bar_index + 1))
{
return result;
}
//
result = IsCrossOver(
xCHMALcFastBuffer,
xCHMALcSlowBuffer,
bar_index);
//
return result;
}
//
// Check LC Fast Over Slow ...
bool XCHMAIsLCFastOverSlow(
int bar_index // Specified Index ...
)
{
//
bool result = false;
//
if (
bar_index <= 0 ||
!XCHMAIsValidBuffersSize(bar_index + 1))
{
return result;
}
//
result = IsOver(
xCHMALcFastBuffer,
xCHMALcSlowBuffer,
bar_index);
//
return result;
}
//
// Check LC Fast Crossed Under Slow ...
bool XCHMAIsLCFastCrossedUnderSlow(
int bar_index // Specified Index ...
)
{
//
bool result = false;
//
if (
bar_index <= 0 ||
!XCHMAIsValidBuffersSize(bar_index + 1))
{
return result;
}
//
result = IsCrossUnder(
xCHMALcFastBuffer,
xCHMALcSlowBuffer,
bar_index);
//
return result;
}
//
// Check LC Fast Under Slow ...
bool XCHMAIsLCFastUnderSlow(
int bar_index // Specified Index ...
)
{
//
bool result = false;
//
if (
bar_index <= 0 ||
!XCHMAIsValidBuffersSize(bar_index + 1))
{
return result;
}
//
result = IsUnder(
xCHMALcFastBuffer,
xCHMALcSlowBuffer,
bar_index);
//
return result;
}
//
// Medium Cycle ...
//
//
// Check MC is Peak ...
bool XCHMAIsMCPeak() {
//
bool result = false;
//
// TODO: Complete this ...
//
return result;
}
//
// Check MC is Vale ...
bool XCHMAIsMCVale() {
//
bool result = false;
//
// TODO: Complete this ...
//
return result;
}
//
// Check MC Fast Crossed Over Slow ...
bool XCHMAIsMCFastCrossedOverSlow(
int bar_index // Specified Index ...
)
{
//
bool result = false;
//
if (
bar_index <= 0 ||
!XCHMAIsValidBuffersSize(bar_index + 1))
{
return result;
}
//
result = IsCrossOver(
xCHMAMcFastBuffer,
xCHMAMcSlowBuffer,
bar_index);
//
return result;
}
//
// Check MC Fast Over Slow ...
bool XCHMAIsMCFastOverSlow(
int bar_index // Specified Index ...
)
{
//
bool result = false;
//
if (
bar_index <= 0 ||
!XCHMAIsValidBuffersSize(bar_index + 1))
{
return result;
}
//
result = IsOver(
xCHMAMcFastBuffer,
xCHMAMcSlowBuffer,
bar_index);
//
return result;
}
//
// Check MC Fast Crossed Under Slow ...
bool XCHMAIsMCFastCrossedUnderSlow(
int bar_index // Specified Index ...
)
{
//
bool result = false;
//
if (
bar_index <= 0 ||
!XCHMAIsValidBuffersSize(bar_index + 1))
{
return result;
}
//
result = IsCrossUnder(
xCHMAMcFastBuffer,
xCHMAMcSlowBuffer,
bar_index);
//
return result;
}
//
// Check MC Fast Under Slow ...
bool XCHMAIsMCFastUnderSlow(
int bar_index // Specified Index ...
)
{
//
bool result = false;
//
if (
bar_index <= 0 ||
!XCHMAIsValidBuffersSize(bar_index + 1))
{
return result;
}
//
result = IsUnder(
xCHMAMcFastBuffer,
xCHMAMcSlowBuffer,
bar_index);
//
return result;
}
//
// Short Cycle ...
//
//
// Check SC is Peak ...
bool XCHMAIsSCPeak() {
//
bool result = false;
//
// TODO: Complete this ...
//
return result;
}
//
// Check SC is Vale ...
bool XCHMAIsSCVale() {
//
bool result = false;
//
// TODO: Complete this ...
//
return result;
}
//
// Check SC Fast Crossed Over Slow ...
bool XCHMAIsSCFastCrossedOverSlow(
int bar_index // Specified Index ...
)
{
//
bool result = false;
//
if (
bar_index <= 0 ||
!XCHMAIsValidBuffersSize(bar_index + 1))
{
return result;
}
//
result = IsCrossOver(
xCHMAScFastBuffer,
xCHMAScSlowBuffer,
bar_index);
//
return result;
}
//
// Check SC Fast Over Slow ...
bool XCHMAIsSCFastOverSlow(
int bar_index // Specified Index ...
)
{
//
bool result = false;
//
if (
bar_index <= 0 ||
!XCHMAIsValidBuffersSize(bar_index + 1))
{
return result;
}
//
result = IsOver(
xCHMAScFastBuffer,
xCHMAScSlowBuffer,
bar_index);
//
return result;
}
//
// Check SC Fast Crossed Under Slow ...
bool XCHMAIsSCFastCrossedUnderSlow(
int bar_index // Specified Index ...
)
{
//
bool result = false;
//
if (
bar_index <= 0 ||
!XCHMAIsValidBuffersSize(bar_index + 1))
{
return result;
}
//
result = IsCrossUnder(
xCHMAScFastBuffer,
xCHMAScSlowBuffer,
bar_index);
//
return result;
}
//
// Check SC Fast Under Slow ...
bool XCHMAIsSCFastUnderSlow(
int bar_index // Specified Index ...
)
{
//
bool result = false;
//
if (
bar_index <= 0 ||
!XCHMAIsValidBuffersSize(bar_index + 1))
{
return result;
}
//
result = IsUnder(
xCHMAScFastBuffer,
xCHMAScSlowBuffer,
bar_index);
//
return result;
}
//
// Utility Functions ...
//
//
// Check all Buffers has valid Size ...
bool XCHMAIsValidBuffersSize(
int size // the size of buffers which min size for requirements
)
{
//
bool result = false;
//
if (
size <= 0 ||
//
ArraySize(xCHMALcFastBuffer) < size ||
ArraySize(xCHMALcSlowBuffer) < size ||
//
ArraySize(xCHMAMcFastBuffer) < size ||
ArraySize(xCHMAMcSlowBuffer) < size ||
//
ArraySize(xCHMAScFastBuffer) < size ||
ArraySize(xCHMAScSlowBuffer) < size
//
)
{
result = false;
}
else
{
result = true;
}
//
return result;
}
//
// END XCHMA Custom Functions ...
//
@@ -0,0 +1,162 @@
///////////////////////////////////////////////////////////////////
//
// SaherElm IT Center MQL5 XCHMA Signal Provider Indicators Library
// ----------------------------------------------------------------
//
// 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 Provider Inputs ...
#include "x-saherelm.xchma.provider.inputs.lib.mq5";
//
// Imports all Indicators Helper here ...
input group "XCHMA Provider Indicators";
#include "x-saherelm.xchma.oscillator.helper.lib.mq5";
//
int xCHMAMaxLengthOfInputs = 0;
int xCHMACalculatedBars = 0;
//
// Init Indicators ...
bool XCHMAInitIndicators()
{
//
bool result = false;
//
// Check and Calculate Max Length in Inputs ...
xCHMAMaxLengthOfInputs = MathMax(
xCHMAScFastLength,
xCHMAScSlowLength);
xCHMAMaxLengthOfInputs = MathMax(
xCHMAMcFastLength,
xCHMAMaxLengthOfInputs);
xCHMAMaxLengthOfInputs = MathMax(
xCHMAMcSlowLength,
xCHMAMaxLengthOfInputs);
xCHMAMaxLengthOfInputs = MathMax(
xCHMALcFastLength,
xCHMAMaxLengthOfInputs);
xCHMAMaxLengthOfInputs = MathMax(
xCHMALcSlowLength,
xCHMAMaxLengthOfInputs);
//
// Initialize Indicator/Oscillator Handlers ...
ResetLastError();
//
// XCHMA Init ...
result = XCHMAInitHandlers();
if (!result)
{
return result;
}
//
result = true;
//
return result;
}
//
// Release Indicators ...
void XCHMAReleaseIndicators()
{
//
// Release Handlers ...
XCHMAReleaseHandlers();
}
//
// Handle Reading Buffers ...
void XCHMAHandleReadingBuffers()
{
//
// Reading Calculated Bars for a Simple Handler ...
xCHMACalculatedBars = BarsCalculated(xCHMAHandler);
//
// Read Indicators Buffers ...
XCHMAReadBuffers(xCHMANumberOfItemsPerTick);
}
//
//
// START Combination Functions ...
//
//
//
// Can Open Long Trade ...
// this is a Function will Check all market Conditions and get all
// Strategy requirement Verifications for Long Signals ...
bool XCHMACanOpenLongTrade() {
//
bool result = false;
//
result = XCHMAHasLongConditions(xCHMANumberOfItemsPerTick);
//
return result;
}
//
// Can Close Long Trade ...
// this is a Function will Check all market Conditions and get all
// Strategy requirement Verifications for Long Signals ...
bool XCHMACanCloseLongTrade() {
//
bool result = false;
//
return result;
}
//
// Can Open Short Trade ...
// this is a Function will Check all market Conditions and get all
// Strategy requirement Verifications for Short Signals ...
bool XCHMACanOpenShortTrade() {
//
bool result = false;
//
result = XCHMAHasShortConditions(xCHMANumberOfItemsPerTick);
//
return result;
}
//
// Can Close Short Trade ...
// this is a Function will Check all market Conditions and get all
// Strategy requirement Verifications for Short Signals ...
bool XCHMACanCloseShortTrade() {
//
bool result = false;
//
return result;
}
//
//
// END Combination Functions ...
//
//
@@ -0,0 +1,63 @@
///////////////////////////////////////////////////////////////
//
// SaherElm IT Center MQL5 XCHMA Signal Provider Library Inputs
// -----------------------------------------------------------
//
// 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
//
input group "XCHMA Provider";
//
input group "XCHMA Common";
input bool enableXCHMAPProvider = true; // Enable Provider
input bool xCHMAEnableAlerts = false; // Enable Events Alert
input int xCHMANumberOfItemsPerTick = 110; // Number Of items Readed In Each Tick
//
input group "XCHMA Trader";
input int xCHMAMagicNumber = 16940561; // Trader MagicNumber
input int xCHMASlippage = 10; // Trader Slippage
//
input group "XCHMA Trade Management";
input bool xCHMAAllowLongTrades = true; // Allow Long Trades
input bool xCHMAAllowShortTrades = true; // Allow Short Trades
//
input group "XCHMA Risk Management";
input int xCHMAMaxAllowedTrades = 5; // Max Allowed Trades at Same Time
input int xCHMAMaxInProfitTradeAge = 0; // Max In Profit Trades Age
input int xCHMAMaxInDrawDownTradeAge = 576; // Max In DrawDown Trades Age
input double xCHMAStaticVolume = 0.02; // Static Volume
input double xCHMAVolumeMultiplier = 2; // Volume Multiplier
input double xCHMAMinRewardPerTradeInPips = 2; // Min Reward Per Trade In Pips
input double xCHMAFreeMarginFactorForOpenTrades = 0.5; // Minimum Free Marging for Open Trades
input double xCHMABalanceFactorForOpenTrades = 0.5; // Minimum Balance for Open Trades
input bool xCHMAEnableSupportTrades = false; // Enable Support Trade
//
// Validate Inputs before Initialization ...
bool XCHMAValidateInputs()
{
//
bool result = false;
//
// TODO: Fix this ...
result = true;
//
return result;
}
+855
View File
@@ -0,0 +1,855 @@
////////////////////////////////////////////////////////////
//
// SaherElm IT Center MQL5 XCHMA Signal Provider Library
// --------------------------------------------------------
// Name: XCHMASignalProvider
// Description: XCHMA based signal provider ...
//
//
// Maintainer:
// ------------
// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com)
//
//////////////////////////////////////////////////////
//
// Global Properties ...
#property library
#property copyright "Copyright 2023, SaherElm IT Center"
#property link "https://www.saherelm.ir"
#property version "1.00"
#property strict
#define XCHMAProviderName "XCHMA"
//
// START Inputs ...
//
#include "x-saherelm.xchma.provider.inputs.lib.mq5";
//
// END Inputs ...
//
//
// Include Common Library ...
#include "x-saherelm.common.lib.mq5"
//
// Include Logger Library ...
#include "x-saherelm.log.lib.mq5"
//
// Include Alert Library ...
#include "x-saherelm.alert.lib.mq5"
//
// Include Draw Library ...
#include "x-saherelm.draw.lib.mq5"
//
// Include Class Libraries ...
#include "x-saherelm.class.lib.mq5"
//
// START Global Definitions: Variables, Properties and etc ...
//
//
XCTrade *xCHMATrader;
XCAccountInfo xCHMAAccountInfo;
//
#include "x-saherelm.xchma.provider.indicators.lib.mq5"
//
double xCHMADeposit = 0;
double xCHMABalance = 0;
double xCHMAFreeMargin = 0;
double xCHMAFreeMarginForOpenTrades = 0;
double xCHMABalanceForOpenTrades = 0;
//
// END Global Definitions: Variables, Properties and etc ...
//
//
// START Provided Functions ...
//
//
// Initial Library if required ...
bool XCHMAInitSignalProviderLibrary()
{
//
bool result = false;
//
// Validate Inputs ...
result = XCHMAValidateInputs();
if (!result)
{
return result;
}
//
// Init Indicators ...
result = XCHMAInitIndicators();
if (!result)
{
return result;
}
//
// Calculate Account Deposit ...
xCHMADeposit = xCHMAAccountInfo.GetInitialBalance();
//
// Calculate Min Balance for Trades ...
if (xCHMABalanceFactorForOpenTrades > 0)
{
xCHMABalanceForOpenTrades = xCHMABalanceFactorForOpenTrades * xCHMADeposit;
}
//
// Claculate Min Free Marging for Trades ...
if (xCHMAFreeMarginFactorForOpenTrades > 0)
{
xCHMAFreeMarginForOpenTrades = xCHMAFreeMarginFactorForOpenTrades * xCHMADeposit;
}
//
// Make XCTrader instance ...
xCHMATrader = new XCTrade(
_Symbol,
xCHMASlippage,
xCHMAMagicNumber);
//
result = true;
//
// Logging State ...
XCHMAIssueInitializationSucceedAlert();
//
return result;
}
//
// DeInitial Library if required ...
void XCHMADeinitSignalProviderLibrary(
const int reason)
{
//
// Release Handlers ...
XCHMAReleaseIndicators();
//
// Logging State ...
XCHMAIssueDeinitializationSucceedAlert();
}
//
// this is a Globally Function which do all of
// checkings and positions handling ...
void XCHMASignalProviderHandleTick()
{
//
// Update account Balance ...
xCHMABalance = xCHMAAccountInfo.GetBalance();
xCHMAFreeMargin = xCHMAAccountInfo.GetFreeMargin();
//
// Reading Indicator Buffers ...
XCHMAHandleReadingBuffers();
if (xCHMACalculatedBars < xCHMAMaxLengthOfInputs)
{
return;
}
//
// Handle Open Trades ...
XCHMAHandleOpenTrades();
//
// Handle Close Trades ...
XCHMAHandleCloseTrades();
}
//
// Handle Open Trades ...
void XCHMAHandleOpenTrades()
{
//
// Check Can Trade ...
bool canTrade = xCHMAAllowLongTrades || xCHMAAllowShortTrades;
if (!canTrade)
{
return;
}
//
// First Check Signal Exists or NOt ...
bool xCHMAHasLongSignal = XCHMACanOpenLongTrade();
bool xCHMAHasShortSignal = XCHMACanOpenShortTrade();
if (!xCHMAHasLongSignal && !xCHMAHasShortSignal)
{
return;
}
//
// Count Max Open Trades ...
if (xCHMAMaxAllowedTrades > 0)
{
//
int count = xCHMATrader.Count();
bool canOpenTrade = count < xCHMAMaxAllowedTrades;
if (!canOpenTrade)
{
//
XCHMAIssueMaxAllowedTradesReachedAlert();
//
return;
}
}
//
// Check Free Margin ...
if (xCHMAFreeMargin <= xCHMAFreeMarginForOpenTrades)
{
//
XCHMAIssueMaxAllowedFreeMarginReachedAlert();
//
return;
}
//
// Check Account Balance ...
if (xCHMABalance <= xCHMABalanceForOpenTrades)
{
//
XCHMAIssueMinAllowedBalanceReachedAlert();
//
return;
}
//
// Primary Long Trade ...
if (
xCHMAHasLongSignal &&
xCHMAAllowLongTrades)
{
//
bool isLongSignalExecuted = XCHMAOpenLongPosition();
if (isLongSignalExecuted)
{
}
}
//
// Primary Short Trade ...
if (
xCHMAHasShortSignal &&
xCHMAAllowShortTrades)
{
//
bool isShortSignalExecuted = XCHMAOpenShortPosition();
if (isShortSignalExecuted)
{
}
}
}
//
// Handle Close Trades ...
void XCHMAHandleCloseTrades()
{
//
// Handle Long/Buy Close ...
if (xCHMATrader.CountLongs() > 0 && XCHMACanCloseLongTrade())
{
//
XSignal closed[];
xCHMATrader.CloseLongPositions(closed);
bool hasClosed = ArraySize(closed) > 0;
if (hasClosed)
{
XCHMAIssueForceCloseTradesAlert(X_SIGNAL_LONG);
}
}
//
// Handle Short/Sell Close ...
if (xCHMATrader.CountShorts() > 0 && XCHMACanCloseShortTrade())
{
//
XSignal closed[];
xCHMATrader.CloseShortPositions(closed);
bool hasClosed = ArraySize(closed) > 0;
if (hasClosed)
{
XCHMAIssueForceCloseTradesAlert(X_SIGNAL_SHORT);
}
}
//
// Handle Close In Profit Teades ...
if (xCHMAMaxInProfitTradeAge > 0)
{
//
XSignal closed[];
XSignal longTimeTrades[];
xCHMATrader.GetLongTimeTrades(
xCHMAMaxInProfitTradeAge,
_Period,
longTimeTrades);
int count = ArraySize(longTimeTrades);
if (count > 0)
{
//
// Loop ...
for (int i = 0; i < count; i++)
{
//
XSignal trade = longTimeTrades[i];
if (trade.profit < 0)
{
continue;
}
//
bool isClosed = xCHMATrader.Close(trade.ticket);
if (isClosed)
{
Add(
trade,
closed);
}
}
}
//
if (ArraySize(closed) > 0)
{
XCHMAIssueLongInProfitTradeClosed();
}
}
//
// Handle Close In DrawDown Trades ...
if (xCHMAMaxInDrawDownTradeAge > 0)
{
//
XSignal closed[];
XSignal longTimeTrades[];
xCHMATrader.GetLongTimeTrades(
xCHMAMaxInDrawDownTradeAge,
_Period,
longTimeTrades);
int count = ArraySize(longTimeTrades);
if (count > 0)
{
//
// Loop ...
for (int i = 0; i < count; i++)
{
//
XSignal trade = longTimeTrades[i];
if (trade.profit > 0)
{
continue;
}
//
// Open Grid Trades ...
XCHMAOpenSuppurtTrade(trade);
// //
// bool isClosed = xCHMATrader.Close(trade.ticket);
// if (isClosed)
// {
// //
// Add(
// trade,
// closed);
// }
}
}
//
if (ArraySize(closed) > 0)
{
XCHMAIssueLongInDrawdownTradeClosed();
}
}
}
//
// Open Long Position ...
bool XCHMAOpenLongPosition()
{
//
bool result = false;
//
// Generate Position Signal and Validate it ...
XSignal position = XCHMAGeneratePositionSignal(X_SIGNAL_LONG);
if (!IsValid(
position,
xCHMAMagicNumber))
{
return result;
}
//
// Try to Open Position ...
result = xCHMATrader.ExecuteSignal(position);
if (result)
{
XCHMAIssueSignalExecutionAlert(position);
}
//
return result;
}
//
// Open Short Position ...
bool XCHMAOpenShortPosition()
{
//
bool result = false;
//
// Generate Position Signal and Validate it ...
XSignal position = XCHMAGeneratePositionSignal(X_SIGNAL_SHORT);
if (!IsValid(
position,
xCHMAMagicNumber))
{
return result;
}
//
// Try to Open Position ...
result = xCHMATrader.ExecuteSignal(position);
if (result)
{
XCHMAIssueSignalExecutionAlert(position);
}
//
return result;
}
//
// Open a Support Signal ...
bool XCHMAOpenSuppurtTrade(
XSignal &signal // Parent Signal
)
{
//
bool result = false;
//
if (!xCHMAEnableSupportTrades) {
return result;
}
//
// Validate Signal ...
if (!IsValid(signal, xCHMAMagicNumber))
{
return result;
}
//
// Market Conditions ...
bool hasLongSignal = XCHMACanOpenLongTrade();
bool hasShortSignal = XCHMACanOpenShortTrade();
//
ENUM_X_SIGNAL_TYPE type = X_SIGNAL_UNKNOWN;
//
// Detect Support Signal Direction ...
XSignal support = {};
switch (signal.type)
{
//
case X_SIGNAL_LONG:
//
// First Check Long Support ...
// Then Look for Short Support ...
if (hasLongSignal)
{
type = X_SIGNAL_LONG;
}
else if (hasShortSignal)
{
type = X_SIGNAL_SHORT;
}
else
{
type = signal.type;
}
break;
//
case X_SIGNAL_SHORT:
// First Check Short Support ...
// Then Look for Long Support ...
if (hasShortSignal)
{
type = X_SIGNAL_SHORT;
}
else if (hasLongSignal)
{
type = X_SIGNAL_LONG;
}
else
{
type = signal.type;
}
break;
}
//
if (type == X_SIGNAL_UNKNOWN)
{
return result;
}
bool isLong = type == X_SIGNAL_LONG;
//
// Find Common Used ...
double entry = GetEntry(type);
double volumeMultiplier = 2;
if (xCHMAVolumeMultiplier > 2)
{
volumeMultiplier = xCHMAVolumeMultiplier;
}
//
// Check Signal is Support ot nor ...
int titlePosition = StringFind(
signal.comment,
"Support");
bool isSupport = titlePosition >= 0;
double priceDistance = MathAbs(signal.entry - entry);
//
if (isSupport || priceDistance < PipsToPrice(5)) {
return result;
}
//
datetime time = iTime(
_Symbol,
_Period,
0);
double volume = NormalizeVolume(isSupport ? signal.volume : signal.volume * volumeMultiplier);
string comment = "Support_" + GetSignalType(type) + "_For_" + (string)signal.ticket + "_" + (string)volume + "_" + (string)time;
//
XTPSL tpSL = XCHMACalculateTPSL(type);
if (!IsValid(tpSL))
{
return result;
}
//
// Calculate reward of signal ...
double reward = MathAbs(signal.entry - signal.tp) / 2;
double tp = tpSL.sl; // isLong ? entry + reward : entry - reward;
double sl = tpSL.sl;
//
// Filling Support Signal ...
support.tp = tp;
support.sl = sl;
support.type = type;
support.time = time;
support.entry = entry;
support.volume = volume;
support.symbol = _Symbol;
support.comment = comment;
support.magicNumber = xCHMAMagicNumber;
//
// Validate Generated Support ...
if (!IsValid(support, xCHMAMagicNumber))
{
return result;
}
//
result = xCHMATrader.ExecuteSignal(support);
if (result)
{
XCHMAIssueSignalExecutionAlert(support);
}
//
return result;
}
//
// Generate Specific type of Signals for Trading ...
XSignal XCHMAGeneratePositionSignal(
ENUM_X_SIGNAL_TYPE type // direction of position
)
{
//
XSignal result = {};
//
if (type != X_SIGNAL_LONG &&
type != X_SIGNAL_SHORT)
{
return result;
}
//
double ask = GetAsk();
double bid = GetBid();
double entry = GetEntry(type);
//
double volume = XCHMACalculateVolume();
//
datetime time = iTime(
_Symbol,
_Period,
0);
//
string typeString = GetSignalType(type);
string comment = XCHMAProviderName + "_" + typeString + "_" + (string)volume + "_" + (string)time;
//
XTPSL tpSL = XCHMACalculateTPSL(type);
if (IsValid(tpSL))
{
//
// Apply TP ...
if (tpSL.tp > 0)
{
result.tp = tpSL.tp;
}
//
// Apply SL ...
if (tpSL.sl > 0)
{
result.sl = tpSL.sl;
}
}
//
result.type = type;
result.time = time;
result.entry = entry;
result.volume = volume;
result.symbol = _Symbol;
result.comment = comment;
result.magicNumber = xCHMAMagicNumber;
//
return result;
}
//
// END Provided Functions ...
//
//
// START Private Functions ...
//
//
// Calculating Volume for Tradings ...
double XCHMACalculateVolume()
{
//
// Assign default Value ...
double result = xCHMAStaticVolume;
//
// we can count open trades and in draw down trades
// then do check volume based on it for gridding ...
int openTrades = xCHMATrader.Count();
if (openTrades == 0)
{
openTrades = 1;
}
//
// Calculate Normalized Multiplier ...
double multiplier = xCHMAVolumeMultiplier <= 0 ? 1 : xCHMAVolumeMultiplier;
//
result = multiplier * openTrades * xCHMAStaticVolume;
//
// Normalize Volume ...
result = NormalizeVolume(result);
//
return result;
}
//
// Calculate Signal TP and SL ...
XTPSL XCHMACalculateTPSL(
ENUM_X_SIGNAL_TYPE type // Position Type
)
{
//
XTPSL result = {};
//
// Validate Args ...
if (
type != X_SIGNAL_LONG &&
type != X_SIGNAL_SHORT)
{
return result;
}
//
bool isLong = type == X_SIGNAL_LONG;
//
double ask = GetAsk();
double bid = GetBid();
double spread = GetSpread();
double entry = isLong ? ask : bid;
//
// TODO: Find Risk ..
double risk = 0;
//
// Calculate Reward ...
double reward = PipsToPrice(xCHMAMinRewardPerTradeInPips) + spread;
//
// Calculate TP and SL ...
double tp = isLong ? entry + reward : entry - reward;
double sl = 0;
//
result.type = type;
result.tp = tp;
result.sl = sl;
result.entry = entry;
//
// TODO: Calculate R2R ...
result.r2r = 0;
//
return result;
}
void XCHMAIssueInitializationSucceedAlert()
{
//
string message = "Initializion of (" + XCHMAProviderName + " Provider" + " _ " + _Symbol + " _ " + EnumToString(_Period) + ") Succeeded ...";
XCHMAIssueAlert(message);
}
void XCHMAIssueDeinitializationSucceedAlert()
{
//
string message = "De Initializion of (" + XCHMAProviderName + " Provider" + ") Succeeded ...";
XCHMAIssueAlert(message);
}
void XCHMAIssueForceCloseTradesAlert(ENUM_X_SIGNAL_TYPE type) {
//
string typeStr = GetSignalType(type);
if (StringLen(typeStr) == 0) {
return;
}
//
string message = "Force Close " + typeStr + " Trades ...";
XCHMAIssueAlert(message);
}
void XCHMAIssueMaxAllowedTradesReachedAlert()
{
//
string message = "reached Max Allowed Same Time Trades ...";
XCHMAIssueAlert(message);
}
void XCHMAIssueMaxAllowedFreeMarginReachedAlert()
{
//
string message = "reached FreeMarigin For Open Trades ...";
XCHMAIssueAlert(message);
}
void XCHMAIssueMinAllowedBalanceReachedAlert()
{
//
string message = "doesn't have Minimum Balance For Open Trades ...";
XCHMAIssueAlert(message);
}
void XCHMAIssueSignalExecutionAlert(
XSignal &signal // Executed Signal
)
{
//
XCHMAIssueAlert(signal);
}
void XCHMAIssueLongInProfitTradeClosed()
{
//
string message = "Closed Long Time in Profit Trades ...";
XCHMAIssueAlert(message);
}
void XCHMAIssueLongInDrawdownTradeClosed()
{
//
string message = "Closed Long Time in Profit Trades ...";
XCHMAIssueAlert(message);
}
void XCHMAIssueAlert(string message)
{
//
if (xCHMAEnableAlerts)
{
SendAlert(message);
}
else
{
LogMessage(message);
}
}
void XCHMAIssueAlert(XSignal &signal)
{
//
if (xCHMAEnableAlerts)
{
SendAlert(signal);
}
else
{
LogSignal(signal);
}
}
//
// END Private Functions ...
//
@@ -0,0 +1,917 @@
/////////////////////////////////////////////////////////////////////////////
//
// SaherElm IT Center MQL5 XTD Oscillator Helper for Signal Providers
// --------------------------------------------------------------------------
//
// Maintainer:
// ------------
// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com)
//
/////////////////////////////////////////////////////////////////////////////
//
// Global Properties ...
#property library
#property copyright "Copyright 2023, SaherElm IT Center"
#property link "https://www.saherelm.ir"
#property version "1.00"
#property strict
//
// Includes ...
#include "..\Libraries\x-saherelm.log.lib.mq5"
#include "..\Libraries\x-saherelm.common.lib.mq5"
//
// START Enum Definitions ...
//
//
// XTD Oscillator States ...
enum ENUM_X_XTD_STATES
{
X_XTD_BULLISH_CROSSED_OVER_BEARISH = 2,
X_XTD_BULLISH_OVER_BEARISH = 1,
X_XTD_NEUTURAL = 0,
X_XTD_BULLISH_UNDER_BEARISH = -1,
X_XTD_BULLISH_CROSSED_UNDER_BEARISH = -2
};
//
// XTD Oscillator Buffer Lines ...
enum ENUM_X_XTD_BUFFER_LINES
{
X_XTD_BULLISH_POWER_LINE = 0,
X_XTD_BEARISH_POWER_LINE = 1,
X_XTD_SIGNAL_LINE = 2,
};
//
// END Enum Definitions ...
//
//
// START Inputs ...
//
input group "XTD Oscillator";
input int xTDLength = 14; // Market Length
input bool xTDDrawCrosses = false; // Draw Cross Arrows
input uchar xTDBullishArrowCode = 228; // Cross Over Arrow Code
input color xTDBullishArrowColor = clrAqua; // Cross Over Arrow Color
input uchar xTDBearishArrowCode = 230; // Cross Under Arrow Code
input color xTDBearishArrowColor = clrMagenta; // Cross Under Arrow Color
//
// END Inputs ...
//
//
// START Definitions ...
//
int xTDHandler = INVALID_HANDLE;
double xTDBullishBuffer[];
double xTDBearishBuffer[];
double xTDSignalBuffer[];
//
// END Definitions ...
//
//
// START Handler Functions ...
//
//
// Init Oscillators ...
bool XTDInitHandlers()
{
//
bool result = false;
//
// Initialize Indicator/Oscillator Handlers ...
ResetLastError();
//
// XTD Handler ...
ArraySetAsSeries(xTDBullishBuffer, true);
ArraySetAsSeries(xTDBearishBuffer, true);
ArraySetAsSeries(xTDSignalBuffer, true);
xTDHandler = iCustom(
_Symbol,
_Period,
"x-saherelm.xtd.oscillator",
//
// Inputs ...
xTDLength,
xTDDrawCrosses,
xTDBullishArrowCode,
xTDBullishArrowColor,
xTDBearishArrowCode,
xTDBearishArrowColor);
if (xTDHandler == INVALID_HANDLE)
{
//
LogMessage("failed to Initialize XTD Oscillator: " + (string)GetLastError());
return result;
}
//
result = true;
//
return result;
}
//
// Release Oscillators ...
void XTDReleaseHandlers()
{
IndicatorRelease(xTDHandler);
}
//
// Handle Reading Buffers ...
void XTDReadBuffers(
int xTDItemsPerTick // Number Of Reading Buffer Items Per Tick
)
{
//
// XTD Bullish Buffer ...
CopyBuffer(
xTDHandler,
X_XTD_BULLISH_POWER_LINE,
0,
xTDItemsPerTick,
xTDBullishBuffer);
//
// XTD Bullish Buffer ...
CopyBuffer(
xTDHandler,
X_XTD_BEARISH_POWER_LINE,
0,
xTDItemsPerTick,
xTDBearishBuffer);
//
// XTD Signal Buffer ...
CopyBuffer(
xTDHandler,
X_XTD_SIGNAL_LINE,
0,
xTDItemsPerTick,
xTDSignalBuffer);
}
//
// END Handler Funcions ...
//
//
// START Signal Related Conditions ...
//
//
// XTD Long Conditions ...
bool XTDHasLongConditions(
int xTDItemsPerTick // Number Of Reading Buffer Items Per Tick
)
{
//
bool result = false;
//
bool isVale = XTDIsSignalVale();
//
bool isInPeak = IsInPeak(
15,
xTDSignalBuffer);
//
bool isSharpChanged = IsSharpChanged(
15,
1,
xTDSignalBuffer);
//
double entry = GetEntry(X_SIGNAL_LONG);
double maxPrice = GetHighestHigh(
7,
0);
double minPrice = GetLowestLow(
7,
0);
double priceDelta = maxPrice - minPrice;
double priceStep = priceDelta / 7;
//
bool isPricePassed =
entry < maxPrice &&
maxPrice - entry < (priceDelta / 4) * 3;
//
result =
//
isVale
//
&&
//
!isInPeak
//
&&
//
!isSharpChanged
//
&&
//
isPricePassed
//
;
//
return result;
}
//
// XTD Short Conditions ...
bool XTDHasShortConditions(
int xTDItemsPerTick // Number Of Reading Buffer Items Per Tick
)
{
//
bool result = false;
//
bool isPeak = XTDIsSignalPeak();
//
bool isInVale = IsInVale(
15,
xTDSignalBuffer);
//
bool isSharpChanged = IsSharpChanged(
15,
1,
xTDSignalBuffer);
//
double entry = GetEntry(X_SIGNAL_SHORT);
double maxPrice = GetHighestHigh(
7,
0);
double minPrice = GetLowestLow(
7,
0);
double priceDelta = maxPrice - minPrice;
double priceStep = priceDelta / 7;
//
bool isPricePassed =
entry > minPrice &&
minPrice + entry > (priceDelta / 4);
//
result =
//
isPeak
//
&&
//
!isInVale
//
&&
//
!isSharpChanged
//
&&
//
isPricePassed
//
;
//
return result;
}
//
// END Signal Related Conditions ...
//
//
// START XTD Custom Functions ...
//
//
// Check Signal Vale ...
bool XTDIsSignalVale()
{
//
bool result = false;
//
// Must Decreasing ...
bool isIncreasing = IsIncreasing(
3,
1,
xTDSignalBuffer);
//
// Must Increasing ...
bool isDecreasing = IsDecreasing(
15,
3,
xTDSignalBuffer);
//
// Generating Result ...
result =
//
isIncreasing
//
&&
//
isDecreasing
//
;
//
return result;
}
//
// Check Signal Peak ...
bool XTDIsSignalPeak()
{
//
bool result = false;
//
// Must Decreasing ...
bool isIncreasing = IsIncreasing(
15,
3,
xTDSignalBuffer);
//
// Must Increasing ...
bool isDecreasing = IsDecreasing(
3,
1,
xTDSignalBuffer);
//
// Generating Result ...
result =
//
isIncreasing
//
&&
//
isDecreasing
//
;
//
return result;
}
//
// Check Signal Peak ...
//
// Check Bullish Crossed Over Bearish ...
bool XTDIsBullCrossedOverBear(
int bar_index // Specified Bar Index
)
{
//
bool result = false;
//
if (
bar_index <= 0 ||
!XTDIsValidBuffersSize(bar_index + 1))
{
return result;
}
//
result = IsCrossOver(
xTDBullishBuffer,
xTDBearishBuffer,
1);
//
return result;
}
//
// Check Bullish Over Bearish ...
bool XTDIsBullOverBear(
int bar_index // Specified Bar Index
)
{
//
bool result = false;
//
if (
bar_index <= 0 ||
!XTDIsValidBuffersSize(bar_index + 1))
{
return result;
}
//
result = IsOver(
xTDBullishBuffer,
xTDBearishBuffer,
1);
//
return result;
}
//
// Check Bullish Crossed Under Bearish ...
bool XTDIsBullCrossedUnderBear(
int bar_index // Specified Bar Index
)
{
//
bool result = false;
//
if (
bar_index <= 0 ||
!XTDIsValidBuffersSize(bar_index + 1))
{
return result;
}
//
result = IsCrossUnder(
xTDBullishBuffer,
xTDBearishBuffer,
1);
//
return result;
}
//
// Check Bullish Under Bearish ...
bool XTDIsBullUnderBear(
int bar_index // Specified Bar Index
)
{
//
bool result = false;
//
if (
bar_index <= 0 ||
!XTDIsValidBuffersSize(bar_index + 1))
{
return result;
}
//
result = IsUnder(
xTDBullishBuffer,
xTDBearishBuffer,
1);
//
return result;
}
//
// Check Signal Crossed Over Bearish ...
bool XTDIsSignalCrossedOverBear(
int bar_index // Specified Bar Index
)
{
//
bool result = false;
//
if (
bar_index <= 0 ||
!XTDIsValidBuffersSize(bar_index + 1))
{
return result;
}
//
result = IsCrossOver(
xTDSignalBuffer,
xTDBearishBuffer,
1);
//
return result;
}
//
// Check Signal Over Bearish ...
bool XTDIsSignalOverBear(
int bar_index // Specified Bar Index
)
{
//
bool result = false;
//
if (
bar_index <= 0 ||
!XTDIsValidBuffersSize(bar_index + 1))
{
return result;
}
//
result = IsOver(
xTDSignalBuffer,
xTDBearishBuffer,
1);
//
return result;
}
//
// Check Signal Crossed Under Bearish ...
bool XTDIsSignalCrossedUnderBear(
int bar_index // Specified Bar Index
)
{
//
bool result = false;
//
if (
bar_index <= 0 ||
!XTDIsValidBuffersSize(bar_index + 1))
{
return result;
}
//
result = IsCrossUnder(
xTDSignalBuffer,
xTDBearishBuffer,
1);
//
return result;
}
//
// Check Signal Under Bearish ...
bool XTDIsSignalUnderBear(
int bar_index // Specified Bar Index
)
{
//
bool result = false;
//
if (
bar_index <= 0 ||
!XTDIsValidBuffersSize(bar_index + 1))
{
return result;
}
//
result = IsUnder(
xTDSignalBuffer,
xTDBearishBuffer,
1);
//
return result;
}
//
// Check all Buffers has valid Size ...
bool XTDIsValidBuffersSize(
int size // the size of buffers which min size for requirements
)
{
//
bool result = false;
//
if (
size <= 0 ||
ArraySize(xTDBullishBuffer) < size ||
ArraySize(xTDBullishBuffer) < size ||
ArraySize(xTDSignalBuffer) < size)
{
result = false;
}
else
{
result = true;
}
//
return result;
}
//
// Count Signal Crossed Over Bear ...
int XTDCountSignalCrossedOverBearIndex(
int bar_index // Specified Bar Index
)
{
//
int result = 0;
//
int count = ArraySize(xTDSignalBuffer) - 1;
if (
bar_index <= 0 ||
count <= bar_index + 1)
{
return result;
}
//
// Loop Through ...
for (int i = bar_index + 1; i < count && result == -1; i++)
{
//
// Check Cross On i Point ...
bool isCrossedOnI = XTDIsSignalCrossedOverBear(i);
if (isCrossedOnI)
{
result++;
}
}
//
return result;
}
//
// Count Signal Crossed Under Bear ...
int XTDCountSignalCrossedUnderBearIndex(
int bar_index // Specified Bar Index
)
{
//
int result = 0;
//
int count = ArraySize(xTDSignalBuffer) - 1;
if (
bar_index <= 0 ||
count <= bar_index + 1)
{
return result;
}
//
// Loop Through ...
for (int i = bar_index + 1; i < count && result == -1; i++)
{
//
// Check Cross On i Point ...
bool isCrossedOnI = XTDIsSignalCrossedUnderBear(i);
if (isCrossedOnI)
{
result++;
}
}
//
return result;
}
//
// Count Bull Crossed Over Bear ...
int XTDCountBullCrossedOverBearIndex(
int bar_index // Specified Bar Index
)
{
//
int result = 0;
//
int count = ArraySize(xTDSignalBuffer) - 1;
if (
bar_index <= 0 ||
count <= bar_index + 1)
{
return result;
}
//
// Loop Through ...
for (int i = bar_index + 1; i < count && result == -1; i++)
{
//
// Check Cross On i Point ...
bool isCrossedOnI = XTDIsBullCrossedOverBear(i);
if (isCrossedOnI)
{
result++;
}
}
//
return result;
}
//
// Count Bull Crossed Under Bear ...
int XTDCountBullCrossedUnderBearIndex(
int bar_index // Specified Bar Index
)
{
//
int result = 0;
//
int count = ArraySize(xTDSignalBuffer) - 1;
if (
bar_index <= 0 ||
count <= bar_index + 1)
{
return result;
}
//
// Loop Through ...
for (int i = bar_index + 1; i < count && result == -1; i++)
{
//
// Check Cross On i Point ...
bool isCrossedOnI = XTDIsBullCrossedUnderBear(i);
if (isCrossedOnI)
{
result++;
}
}
//
return result;
}
//
// Find Last Signal Crossed Over Bear ...
int XTDFindLastSignalCrossedOverBearIndex(
int bar_index // Specified Bar Index
)
{
//
int result = -1;
//
int count = ArraySize(xTDSignalBuffer) - 1;
if (
bar_index <= 0 ||
count <= bar_index + 1)
{
return result;
}
//
// Loop Through ...
for (int i = bar_index + 1; i < count && result == -1; i++)
{
//
// Check Cross On i Point ...
bool isCrossedOnI = XTDIsSignalCrossedOverBear(i);
if (isCrossedOnI)
{
//
result = i;
break;
}
}
//
return result;
}
//
// Find Last Signal Crossed Onder Bear ...
int XTDFindLastSignalCrossedUnderBearIndex(
int bar_index // Specified Bar Index
)
{
//
int result = -1;
//
int count = ArraySize(xTDSignalBuffer) - 1;
if (
bar_index <= 0 ||
count <= bar_index + 1)
{
return result;
}
//
// Loop Through ...
for (int i = bar_index + 1; i < count && result == -1; i++)
{
//
// Check Cross On i Point ...
bool isCrossedOnI = XTDIsSignalCrossedUnderBear(i);
if (isCrossedOnI)
{
//
result = i;
break;
}
}
//
return result;
}
//
// Find Last Bull Crossed Over Bear ...
int XTDFindLastBullCrossedOverBearIndex(
int bar_index // Specified Bar Index
)
{
//
int result = -1;
//
int count = ArraySize(xTDSignalBuffer) - 1;
if (
bar_index <= 0 ||
count <= bar_index + 1)
{
return result;
}
//
// Loop Through ...
for (int i = bar_index + 1; i < count && result == -1; i++)
{
//
// Check Cross On i Point ...
bool isCrossedOnI = XTDIsBullCrossedOverBear(i);
if (isCrossedOnI)
{
//
result = i;
break;
}
}
//
return result;
}
//
// Find Last Bull Crossed Under Bear ...
int XTDFindLastBullCrossedUnderBearIndex(
int bar_index // Specified Bar Index
)
{
//
int result = -1;
//
int count = ArraySize(xTDSignalBuffer) - 1;
if (
bar_index <= 0 ||
count <= bar_index + 1)
{
return result;
}
//
// Loop Through ...
for (int i = bar_index + 1; i < count && result == -1; i++)
{
//
// Check Cross On i Point ...
bool isCrossedOnI = XTDIsBullCrossedUnderBear(i);
if (isCrossedOnI)
{
//
result = i;
break;
}
}
//
return result;
}
//
// END XTD Custom Functions ...
//
@@ -0,0 +1,155 @@
///////////////////////////////////////////////////////////////////
//
// SaherElm IT Center MQL5 XTD Signal Provider Indicators Library
// ----------------------------------------------------------------
//
// 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 Provider Inputs ...
#include "x-saherelm.xtd.provider.inputs.lib.mq5";
//
// Imports all Indicators Helper here ...
input group "XTD Provider Indicators";
#include "x-saherelm.xtd.oscillator.helper.lib.mq5";
//
int xTDMaxLengthOfInputs = 0;
int xTDCalculatedBars = 0;
//
// Init Indicators ...
bool XTDInitIndicators()
{
//
bool result = false;
//
// Check and Calculate Max Length in Inputs ...
xTDMaxLengthOfInputs = MathMax(
xTDLength,
xTDMaxLengthOfInputs);
//
// Initialize Indicator/Oscillator Handlers ...
ResetLastError();
//
// XTD Init ...
result = XTDInitHandlers();
if (!result)
{
return result;
}
//
result = true;
//
return result;
}
//
// Release Indicators ...
void XTDReleaseIndicators()
{
//
// Release Handlers ...
XTDReleaseHandlers();
}
//
// Handle Reading Buffers ...
void XTDHandleReadingBuffers()
{
//
// Reading Calculated Bars for a Simple Handler ...
xTDCalculatedBars = BarsCalculated(xTDHandler);
//
// Read Indicators Buffers ...
XTDReadBuffers(xTDNumberOfItemsPerTick);
}
//
//
// START Combination Functions ...
//
//
//
// Can Open Long Trade ...
// this is a Function will Check all market Conditions and get all
// Strategy requirement Verifications for Long Signals ...
bool XTDCanOpenLongTrade() {
//
bool result = false;
//
result = XTDHasLongConditions(xTDNumberOfItemsPerTick);
//
// if (result) {
// LogMessage("Salam");
// }
//
return result;
}
//
// Can Close Long Trade ...
// this is a Function will Check all market Conditions and get all
// Strategy requirement Verifications for Long Signals ...
bool XTDCanCloseLongTrade() {
//
bool result = false;
//
return result;
}
//
// Can Open Short Trade ...
// this is a Function will Check all market Conditions and get all
// Strategy requirement Verifications for Short Signals ...
bool XTDCanOpenShortTrade() {
//
bool result = false;
//
result = XTDHasShortConditions(xTDNumberOfItemsPerTick);
//
return result;
}
//
// Can Close Short Trade ...
// this is a Function will Check all market Conditions and get all
// Strategy requirement Verifications for Short Signals ...
bool XTDCanCloseShortTrade() {
//
bool result = false;
//
return result;
}
//
//
// END Combination Functions ...
//
//
@@ -0,0 +1,63 @@
///////////////////////////////////////////////////////////////
//
// SaherElm IT Center MQL5 XTD Signal Provider Library Inputs
// -----------------------------------------------------------
//
// 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
//
input group "XTD Provider";
//
input group "XTD Common";
input bool enableXTDPProvider = true; // Enable Provider
input bool xTDEnableAlerts = false; // Enable Events Alert
input int xTDNumberOfItemsPerTick = 110; // Number Of items Readed In Each Tick
//
input group "XTD Trader";
input int xTDMagicNumber = 16940561; // Trader MagicNumber
input int xTDSlippage = 10; // Trader Slippage
//
input group "XTD Trade Management";
input bool xTDAllowLongTrades = true; // Allow Long Trades
input bool xTDAllowShortTrades = true; // Allow Short Trades
//
input group "XTD Risk Management";
input int xTDMaxAllowedTrades = 5; // Max Allowed Trades at Same Time
input int xTDMaxInProfitTradeAge = 0; // Max In Profit Trades Age
input int xTDMaxInDrawDownTradeAge = 576; // Max In DrawDown Trades Age
input double xTDStaticVolume = 0.02; // Static Volume
input double xTDVolumeMultiplier = 2; // Volume Multiplier
input double xTDMinRewardPerTradeInPips = 2; // Min Reward Per Trade In Pips
input double xTDFreeMarginFactorForOpenTrades = 0.5; // Minimum Free Marging for Open Trades
input double xTDBalanceFactorForOpenTrades = 0.5; // Minimum Balance for Open Trades
input bool xTDEnableSupportTrades = false; // Enable Support Trade
//
// Validate Inputs before Initialization ...
bool XTDValidateInputs()
{
//
bool result = false;
//
// TODO: Fix this ...
result = true;
//
return result;
}
+855
View File
@@ -0,0 +1,855 @@
////////////////////////////////////////////////////////////
//
// SaherElm IT Center MQL5 XTD Signal Provider Library
// --------------------------------------------------------
// Name: XTDSignalProvider
// Description: XTD based signal provider ...
//
//
// Maintainer:
// ------------
// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com)
//
//////////////////////////////////////////////////////
//
// Global Properties ...
#property library
#property copyright "Copyright 2023, SaherElm IT Center"
#property link "https://www.saherelm.ir"
#property version "1.00"
#property strict
#define XTDProviderName "XTD"
//
// START Inputs ...
//
#include "x-saherelm.xtd.provider.inputs.lib.mq5";
//
// END Inputs ...
//
//
// Include Common Library ...
#include "x-saherelm.common.lib.mq5"
//
// Include Logger Library ...
#include "x-saherelm.log.lib.mq5"
//
// Include Alert Library ...
#include "x-saherelm.alert.lib.mq5"
//
// Include Draw Library ...
#include "x-saherelm.draw.lib.mq5"
//
// Include Class Libraries ...
#include "x-saherelm.class.lib.mq5"
//
// START Global Definitions: Variables, Properties and etc ...
//
//
XCTrade *xTDTrader;
XCAccountInfo xTDAccountInfo;
//
#include "x-saherelm.xtd.provider.indicators.lib.mq5"
//
double xTDDeposit = 0;
double xTDBalance = 0;
double xTDFreeMargin = 0;
double xTDFreeMarginForOpenTrades = 0;
double xTDBalanceForOpenTrades = 0;
//
// END Global Definitions: Variables, Properties and etc ...
//
//
// START Provided Functions ...
//
//
// Initial Library if required ...
bool XTDInitSignalProviderLibrary()
{
//
bool result = false;
//
// Validate Inputs ...
result = XTDValidateInputs();
if (!result)
{
return result;
}
//
// Init Indicators ...
result = XTDInitIndicators();
if (!result)
{
return result;
}
//
// Calculate Account Deposit ...
xTDDeposit = xTDAccountInfo.GetInitialBalance();
//
// Calculate Min Balance for Trades ...
if (xTDBalanceFactorForOpenTrades > 0)
{
xTDBalanceForOpenTrades = xTDBalanceFactorForOpenTrades * xTDDeposit;
}
//
// Claculate Min Free Marging for Trades ...
if (xTDFreeMarginFactorForOpenTrades > 0)
{
xTDFreeMarginForOpenTrades = xTDFreeMarginFactorForOpenTrades * xTDDeposit;
}
//
// Make XCTrader instance ...
xTDTrader = new XCTrade(
_Symbol,
xTDSlippage,
xTDMagicNumber);
//
result = true;
//
// Logging State ...
XTDIssueInitializationSucceedAlert();
//
return result;
}
//
// DeInitial Library if required ...
void XTDDeinitSignalProviderLibrary(
const int reason)
{
//
// Release Handlers ...
XTDReleaseIndicators();
//
// Logging State ...
XTDIssueDeinitializationSucceedAlert();
}
//
// this is a Globally Function which do all of
// checkings and positions handling ...
void XTDSignalProviderHandleTick()
{
//
// Update account Balance ...
xTDBalance = xTDAccountInfo.GetBalance();
xTDFreeMargin = xTDAccountInfo.GetFreeMargin();
//
// Reading Indicator Buffers ...
XTDHandleReadingBuffers();
if (xTDCalculatedBars < xTDMaxLengthOfInputs)
{
return;
}
//
// Handle Open Trades ...
XTDHandleOpenTrades();
//
// Handle Close Trades ...
XTDHandleCloseTrades();
}
//
// Handle Open Trades ...
void XTDHandleOpenTrades()
{
//
// Check Can Trade ...
bool canTrade = xTDAllowLongTrades || xTDAllowShortTrades;
if (!canTrade)
{
return;
}
//
// First Check Signal Exists or NOt ...
bool xTDHasLongSignal = XTDCanOpenLongTrade();
bool xTDHasShortSignal = XTDCanOpenShortTrade();
if (!xTDHasLongSignal && !xTDHasShortSignal)
{
return;
}
//
// Count Max Open Trades ...
if (xTDMaxAllowedTrades > 0)
{
//
int count = xTDTrader.Count();
bool canOpenTrade = count < xTDMaxAllowedTrades;
if (!canOpenTrade)
{
//
XTDIssueMaxAllowedTradesReachedAlert();
//
return;
}
}
//
// Check Free Margin ...
if (xTDFreeMargin <= xTDFreeMarginForOpenTrades)
{
//
XTDIssueMaxAllowedFreeMarginReachedAlert();
//
return;
}
//
// Check Account Balance ...
if (xTDBalance <= xTDBalanceForOpenTrades)
{
//
XTDIssueMinAllowedBalanceReachedAlert();
//
return;
}
//
// Primary Long Trade ...
if (
xTDHasLongSignal &&
xTDAllowLongTrades)
{
//
bool isLongSignalExecuted = XTDOpenLongPosition();
if (isLongSignalExecuted)
{
}
}
//
// Primary Short Trade ...
if (
xTDHasShortSignal &&
xTDAllowShortTrades)
{
//
bool isShortSignalExecuted = XTDOpenShortPosition();
if (isShortSignalExecuted)
{
}
}
}
//
// Handle Close Trades ...
void XTDHandleCloseTrades()
{
//
// Handle Long/Buy Close ...
if (xTDTrader.CountLongs() > 0 && XTDCanCloseLongTrade())
{
//
XSignal closed[];
xTDTrader.CloseLongPositions(closed);
bool hasClosed = ArraySize(closed) > 0;
if (hasClosed)
{
XTDIssueForceCloseTradesAlert(X_SIGNAL_LONG);
}
}
//
// Handle Short/Sell Close ...
if (xTDTrader.CountShorts() > 0 && XTDCanCloseShortTrade())
{
//
XSignal closed[];
xTDTrader.CloseShortPositions(closed);
bool hasClosed = ArraySize(closed) > 0;
if (hasClosed)
{
XTDIssueForceCloseTradesAlert(X_SIGNAL_SHORT);
}
}
//
// Handle Close In Profit Teades ...
if (xTDMaxInProfitTradeAge > 0)
{
//
XSignal closed[];
XSignal longTimeTrades[];
xTDTrader.GetLongTimeTrades(
xTDMaxInProfitTradeAge,
_Period,
longTimeTrades);
int count = ArraySize(longTimeTrades);
if (count > 0)
{
//
// Loop ...
for (int i = 0; i < count; i++)
{
//
XSignal trade = longTimeTrades[i];
if (trade.profit < 0)
{
continue;
}
//
bool isClosed = xTDTrader.Close(trade.ticket);
if (isClosed)
{
Add(
trade,
closed);
}
}
}
//
if (ArraySize(closed) > 0)
{
XTDIssueLongInProfitTradeClosed();
}
}
//
// Handle Close In DrawDown Trades ...
if (xTDMaxInDrawDownTradeAge > 0)
{
//
XSignal closed[];
XSignal longTimeTrades[];
xTDTrader.GetLongTimeTrades(
xTDMaxInDrawDownTradeAge,
_Period,
longTimeTrades);
int count = ArraySize(longTimeTrades);
if (count > 0)
{
//
// Loop ...
for (int i = 0; i < count; i++)
{
//
XSignal trade = longTimeTrades[i];
if (trade.profit > 0)
{
continue;
}
//
// Open Grid Trades ...
XTDOpenSuppurtTrade(trade);
// //
// bool isClosed = xTDTrader.Close(trade.ticket);
// if (isClosed)
// {
// //
// Add(
// trade,
// closed);
// }
}
}
//
if (ArraySize(closed) > 0)
{
XTDIssueLongInDrawdownTradeClosed();
}
}
}
//
// Open Long Position ...
bool XTDOpenLongPosition()
{
//
bool result = false;
//
// Generate Position Signal and Validate it ...
XSignal position = XTDGeneratePositionSignal(X_SIGNAL_LONG);
if (!IsValid(
position,
xTDMagicNumber))
{
return result;
}
//
// Try to Open Position ...
result = xTDTrader.ExecuteSignal(position);
if (result)
{
XTDIssueSignalExecutionAlert(position);
}
//
return result;
}
//
// Open Short Position ...
bool XTDOpenShortPosition()
{
//
bool result = false;
//
// Generate Position Signal and Validate it ...
XSignal position = XTDGeneratePositionSignal(X_SIGNAL_SHORT);
if (!IsValid(
position,
xTDMagicNumber))
{
return result;
}
//
// Try to Open Position ...
result = xTDTrader.ExecuteSignal(position);
if (result)
{
XTDIssueSignalExecutionAlert(position);
}
//
return result;
}
//
// Open a Support Signal ...
bool XTDOpenSuppurtTrade(
XSignal &signal // Parent Signal
)
{
//
bool result = false;
//
if (!xTDEnableSupportTrades) {
return result;
}
//
// Validate Signal ...
if (!IsValid(signal, xTDMagicNumber))
{
return result;
}
//
// Market Conditions ...
bool hasLongSignal = XTDCanOpenLongTrade();
bool hasShortSignal = XTDCanOpenShortTrade();
//
ENUM_X_SIGNAL_TYPE type = X_SIGNAL_UNKNOWN;
//
// Detect Support Signal Direction ...
XSignal support = {};
switch (signal.type)
{
//
case X_SIGNAL_LONG:
//
// First Check Long Support ...
// Then Look for Short Support ...
if (hasLongSignal)
{
type = X_SIGNAL_LONG;
}
else if (hasShortSignal)
{
type = X_SIGNAL_SHORT;
}
else
{
type = signal.type;
}
break;
//
case X_SIGNAL_SHORT:
// First Check Short Support ...
// Then Look for Long Support ...
if (hasShortSignal)
{
type = X_SIGNAL_SHORT;
}
else if (hasLongSignal)
{
type = X_SIGNAL_LONG;
}
else
{
type = signal.type;
}
break;
}
//
if (type == X_SIGNAL_UNKNOWN)
{
return result;
}
bool isLong = type == X_SIGNAL_LONG;
//
// Find Common Used ...
double entry = GetEntry(type);
double volumeMultiplier = 2;
if (xTDVolumeMultiplier > 2)
{
volumeMultiplier = xTDVolumeMultiplier;
}
//
// Check Signal is Support ot nor ...
int titlePosition = StringFind(
signal.comment,
"Support");
bool isSupport = titlePosition >= 0;
double priceDistance = MathAbs(signal.entry - entry);
//
if (isSupport || priceDistance < PipsToPrice(5)) {
return result;
}
//
datetime time = iTime(
_Symbol,
_Period,
0);
double volume = NormalizeVolume(isSupport ? signal.volume : signal.volume * volumeMultiplier);
string comment = "Support_" + GetSignalType(type) + "_For_" + (string)signal.ticket + "_" + (string)volume + "_" + (string)time;
//
XTPSL tpSL = XTDCalculateTPSL(type);
if (!IsValid(tpSL))
{
return result;
}
//
// Calculate reward of signal ...
double reward = MathAbs(signal.entry - signal.tp) / 2;
double tp = tpSL.sl; // isLong ? entry + reward : entry - reward;
double sl = tpSL.sl;
//
// Filling Support Signal ...
support.tp = tp;
support.sl = sl;
support.type = type;
support.time = time;
support.entry = entry;
support.volume = volume;
support.symbol = _Symbol;
support.comment = comment;
support.magicNumber = xTDMagicNumber;
//
// Validate Generated Support ...
if (!IsValid(support, xTDMagicNumber))
{
return result;
}
//
result = xTDTrader.ExecuteSignal(support);
if (result)
{
XTDIssueSignalExecutionAlert(support);
}
//
return result;
}
//
// Generate Specific type of Signals for Trading ...
XSignal XTDGeneratePositionSignal(
ENUM_X_SIGNAL_TYPE type // direction of position
)
{
//
XSignal result = {};
//
if (type != X_SIGNAL_LONG &&
type != X_SIGNAL_SHORT)
{
return result;
}
//
double ask = GetAsk();
double bid = GetBid();
double entry = GetEntry(type);
//
double volume = XTDCalculateVolume();
//
datetime time = iTime(
_Symbol,
_Period,
0);
//
string typeString = GetSignalType(type);
string comment = XTDProviderName + "_" + typeString + "_" + (string)volume + "_" + (string)time;
//
XTPSL tpSL = XTDCalculateTPSL(type);
if (IsValid(tpSL))
{
//
// Apply TP ...
if (tpSL.tp > 0)
{
result.tp = tpSL.tp;
}
//
// Apply SL ...
if (tpSL.sl > 0)
{
result.sl = tpSL.sl;
}
}
//
result.type = type;
result.time = time;
result.entry = entry;
result.volume = volume;
result.symbol = _Symbol;
result.comment = comment;
result.magicNumber = xTDMagicNumber;
//
return result;
}
//
// END Provided Functions ...
//
//
// START Private Functions ...
//
//
// Calculating Volume for Tradings ...
double XTDCalculateVolume()
{
//
// Assign default Value ...
double result = xTDStaticVolume;
//
// we can count open trades and in draw down trades
// then do check volume based on it for gridding ...
int openTrades = xTDTrader.Count();
if (openTrades == 0)
{
openTrades = 1;
}
//
// Calculate Normalized Multiplier ...
double multiplier = xTDVolumeMultiplier <= 0 ? 1 : xTDVolumeMultiplier;
//
result = multiplier * openTrades * xTDStaticVolume;
//
// Normalize Volume ...
result = NormalizeVolume(result);
//
return result;
}
//
// Calculate Signal TP and SL ...
XTPSL XTDCalculateTPSL(
ENUM_X_SIGNAL_TYPE type // Position Type
)
{
//
XTPSL result = {};
//
// Validate Args ...
if (
type != X_SIGNAL_LONG &&
type != X_SIGNAL_SHORT)
{
return result;
}
//
bool isLong = type == X_SIGNAL_LONG;
//
double ask = GetAsk();
double bid = GetBid();
double spread = GetSpread();
double entry = isLong ? ask : bid;
//
// TODO: Find Risk ..
double risk = 0;
//
// Calculate Reward ...
double reward = PipsToPrice(xTDMinRewardPerTradeInPips) + spread;
//
// Calculate TP and SL ...
double tp = isLong ? entry + reward : entry - reward;
double sl = 0;
//
result.type = type;
result.tp = tp;
result.sl = sl;
result.entry = entry;
//
// TODO: Calculate R2R ...
result.r2r = 0;
//
return result;
}
void XTDIssueInitializationSucceedAlert()
{
//
string message = "Initializion of (" + XTDProviderName + " Provider" + " _ " + _Symbol + " _ " + EnumToString(_Period) + ") Succeeded ...";
XTDIssueAlert(message);
}
void XTDIssueDeinitializationSucceedAlert()
{
//
string message = "De Initializion of (" + XTDProviderName + " Provider" + ") Succeeded ...";
XTDIssueAlert(message);
}
void XTDIssueForceCloseTradesAlert(ENUM_X_SIGNAL_TYPE type) {
//
string typeStr = GetSignalType(type);
if (StringLen(typeStr) == 0) {
return;
}
//
string message = "Force Close " + typeStr + " Trades ...";
XTDIssueAlert(message);
}
void XTDIssueMaxAllowedTradesReachedAlert()
{
//
string message = "reached Max Allowed Same Time Trades ...";
XTDIssueAlert(message);
}
void XTDIssueMaxAllowedFreeMarginReachedAlert()
{
//
string message = "reached FreeMarigin For Open Trades ...";
XTDIssueAlert(message);
}
void XTDIssueMinAllowedBalanceReachedAlert()
{
//
string message = "doesn't have Minimum Balance For Open Trades ...";
XTDIssueAlert(message);
}
void XTDIssueSignalExecutionAlert(
XSignal &signal // Executed Signal
)
{
//
XTDIssueAlert(signal);
}
void XTDIssueLongInProfitTradeClosed()
{
//
string message = "Closed Long Time in Profit Trades ...";
XTDIssueAlert(message);
}
void XTDIssueLongInDrawdownTradeClosed()
{
//
string message = "Closed Long Time in Profit Trades ...";
XTDIssueAlert(message);
}
void XTDIssueAlert(string message)
{
//
if (xTDEnableAlerts)
{
SendAlert(message);
}
else
{
LogMessage(message);
}
}
void XTDIssueAlert(XSignal &signal)
{
//
if (xTDEnableAlerts)
{
SendAlert(signal);
}
else
{
LogSignal(signal);
}
}
//
// END Private Functions ...
//
@@ -0,0 +1,475 @@
/////////////////////////////////////////////////////////////////////////////
//
// SaherElm IT Center MQL5 XTM Indicator Helper for Signal Providers
// --------------------------------------------------------------------------
//
// Maintainer:
// ------------
// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com)
//
/////////////////////////////////////////////////////////////////////////////
//
// Global Properties ...
#property library
#property copyright "Copyright 2023, SaherElm IT Center"
#property link "https://www.saherelm.ir"
#property version "1.00"
#property strict
//
// Includes ...
#include "..\Libraries\x-saherelm.log.lib.mq5"
#include "..\Libraries\x-saherelm.common.lib.mq5"
//
// START Enum Definitions ...
//
//
// XTM Indicator States ...
enum ENUM_X_XTM_STATES
{
X_XTM_BULLISH = 1,
X_XTM_BEARISH = -1,
X_XTM_NEUTURAL = 0,
};
//
// XTM Indicator Buffer Lines ...
enum ENUM_X_XTM_BUFFER_LINES
{
X_XTM_MA_LINE = 0,
X_XTM_MC_COLOR_LINE = 1,
X_XTM_STATE_LINE = 2,
};
//
// END Enum Definitions ...
//
//
// START Inputs ...
//
input group "XTM Indicator";
input int xTMMaPeriod = 14; // Period
input int xTMMaShift = 0; // Shift
input ENUM_MA_METHOD xTMMaMethod = MODE_SMA; // Method
input ENUM_APPLIED_PRICE xTMMaAppliedTo = PRICE_WEIGHTED; // Applied To
//
// END Inputs ...
//
//
// START Definitions ...
//
int xTMHandler = INVALID_HANDLE;
double xTMMaBuffer[];
double xTMStateBuffer[];
//
// END Definitions ...
//
//
// START Handler Functions ...
//
//
// Init Indicators ...
bool XTMInitHandlers()
{
//
bool result = false;
//
// Initialize Indicator/Oscillator Handlers ...
ResetLastError();
//
// XTM Handler ...
ArraySetAsSeries(xTMMaBuffer, true);
ArraySetAsSeries(xTMStateBuffer, true);
xTMHandler = iCustom(
_Symbol,
_Period,
"x-saherelm.xtm.indicator",
//
// Inputs ...
xTMMaPeriod,
xTMMaShift,
xTMMaMethod,
xTMMaAppliedTo);
if (xTMHandler == INVALID_HANDLE)
{
//
LogMessage("failed to Initialize XTM Indicator: " + (string)GetLastError());
return result;
}
//
// xTMOHandler ...
// ArraySetAsSeries(xTMOBuffer, true);
// xTMOHandler = iCustom(
// _Symbol,
// _Period,
// "x-saherelm.xma.indicator",
// //
// // Inputs ...
// xTMMaPeriod,
// xTMMaShift,
// MODE_SMA,
// PRICE_OPEN);
// if (xTMOHandler == INVALID_HANDLE)
// {
// //
// LogMessage("failed to Initialize XMA Indicator: " + (string)GetLastError());
// return result;
// }
//
result = true;
//
return result;
}
//
// Release Indicators ...
void XTMReleaseHandlers()
{
IndicatorRelease(xTMHandler);
// IndicatorRelease(xTMOHandler);
}
//
// Handle Reading Buffers ...
void XTMReadBuffers(
int xTMItemsPerTick // Number Of Reading Buffer Items Per Tick
)
{
//
// Ma Buffer ...
CopyBuffer(
xTMHandler,
X_XTM_MA_LINE,
0,
xTMItemsPerTick,
xTMMaBuffer);
//
// State Buffer ...
CopyBuffer(
xTMHandler,
X_XTM_STATE_LINE,
0,
xTMItemsPerTick,
xTMStateBuffer);
//
// XTMO Buffer ...
// CopyBuffer(
// xTMOHandler,
// 0,
// 0,
// xTMItemsPerTick,
// xTMOBuffer);
}
//
// END Handler Funcions ...
//
//
// START Signal Related Conditions ...
//
//
// XTM Long Conditions ...
bool XTMHasLongConditions(
int xTMItemsPerTick // Number Of Reading Buffer Items Per Tick
)
{
//
bool result = false;
//
bool isPeak = XTMIsPeak();
bool isVale = XTMIsVale();
//
double minValue = GetMinValue(
xTMItemsPerTick,
xTMMaBuffer);
double maxValue = GetMaxValue(
xTMItemsPerTick,
xTMMaBuffer);
double currentValue = xTMMaBuffer[1];
bool isTMMinMaxPassed =
currentValue < maxValue && currentValue > minValue;
//
bool isInPeak = IsInPeak(
15,
xTMMaBuffer);
//
bool isSharpChanged = IsSharpChanged(
15,
1,
xTMMaBuffer);
bool isCandleSharpChanged = IsSharpChanged(
15,
1,
PRICE_CLOSE);
//
double entry = GetEntry(X_SIGNAL_LONG);
double maxPrice = GetHighestHigh(
7,
0);
double minPrice = GetLowestLow(
7,
0);
double priceDelta = maxPrice - minPrice;
double priceStep = priceDelta / 7;
//
bool isPricePassed =
entry < maxPrice &&
maxPrice - entry < (priceDelta / 4) * 3;
//
result =
//
isVale
//
&&
//
!isInPeak
//
&&
//
!isSharpChanged
//
&&
//
isPricePassed
//
&&
//
!isCandleSharpChanged
//
;
//
return result;
}
//
// XTM Short Conditions ...
bool XTMHasShortConditions(
int xTMItemsPerTick // Number Of Reading Buffer Items Per Tick
)
{
//
bool result = false;
//
bool isPeak = XTMIsPeak();
bool isValue = XTMIsVale();
//
double minValue = GetMinValue(
xTMItemsPerTick,
xTMMaBuffer);
double maxValue = GetMaxValue(
xTMItemsPerTick,
xTMMaBuffer);
double currentValue = xTMMaBuffer[1];
bool isTMMinMaxPassed =
currentValue < maxValue && currentValue > minValue;
//
bool isInPeak = IsInPeak(
15,
xTMMaBuffer);
bool isInVale = IsInVale(
15,
xTMMaBuffer);
//
bool isSharpChanged = IsSharpChanged(
15,
1,
xTMMaBuffer);
bool isCandleSharpChanged = IsSharpChanged(
15,
1,
PRICE_CLOSE);
//
double entry = GetEntry(X_SIGNAL_SHORT);
double maxPrice = GetHighestHigh(
7,
0);
double minPrice = GetLowestLow(
7,
0);
double priceDelta = maxPrice - minPrice;
double priceStep = priceDelta / 7;
//
bool isPricePassed =
entry > minPrice &&
minPrice + entry > (priceDelta / 4);
//
result =
//
isPeak
//
&&
//
!isInVale
//
&&
//
!isSharpChanged
//
&&
//
isPricePassed
//
&&
//
!isCandleSharpChanged
;
//
return result;
}
//
// END Signal Related Conditions ...
//
//
// START XTM Custom Functions ...
//
//
// Find Peak based On this Indicator ...
bool XTMIsPeak()
{
//
bool result = false;
//
// Check Is Vale ...
//
double currentValue = xTMMaBuffer[1];
//
// Must Decreasing ...
bool isIncreasing = IsIncreasing(
15,
3,
xTMMaBuffer);
//
// Must Increasing ...
bool isDecreasing = IsDecreasing(
3,
1,
xTMMaBuffer);
//
// Find State of First and Last ...
double stateValue1 = xTMStateBuffer[1];
double stateValue2 = xTMStateBuffer[2];
bool isStatePassed =
stateValue2 == X_XTM_NEUTURAL &&
stateValue1 == X_XTM_BEARISH;
//
// Calculate Result ...
result =
//
isIncreasing
//
&&
//
isDecreasing
//
&&
//
isStatePassed
//
;
//
return result;
}
//
// Find Vale based On this Indicator ...
bool XTMIsVale()
{
//
bool result = false;
//
// Check Is Vale ...
//
double currentValue = xTMMaBuffer[1];
//
// Must Decreasing ...
bool isIncreasing = IsIncreasing(
3,
1,
xTMMaBuffer);
//
// Must Increasing ...
bool isDecreasing = IsDecreasing(
15,
3,
xTMMaBuffer);
//
// Find State of First and Last ...
double stateValue1 = xTMStateBuffer[1];
double stateValue2 = xTMStateBuffer[2];
bool isStatePassed =
stateValue2 == X_XTM_NEUTURAL &&
stateValue1 == X_XTM_BULLISH;
//
// Calculate Result ...
result =
//
isIncreasing
//
&&
//
isDecreasing
//
&&
//
isStatePassed
//
;
//
return result;
}
//
// END XTM Custom Functions ...
//
@@ -0,0 +1,150 @@
///////////////////////////////////////////////////////////////////
//
// SaherElm IT Center MQL5 XTM Signal Provider Indicators Library
// ----------------------------------------------------------------
//
// 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 Provider Inputs ...
#include "x-saherelm.xtm.provider.inputs.lib.mq5";
//
// Imports all Indicators Helper here ...
input group "XTM Provider Indicators";
#include "x-saherelm.xtm.indicator.helper.lib.mq5";
//
int xTMMaxLengthOfInputs = 0;
int xTMCalculatedBars = 0;
//
// Init Indicators ...
bool XTMInitIndicators()
{
//
bool result = false;
//
// Check and Calculate Max Length in Inputs ...
xTMMaxLengthOfInputs = MathMax(
xTMMaPeriod,
xTMMaxLengthOfInputs);
//
// Initialize Indicator/Oscillator Handlers ...
ResetLastError();
//
// XTM Init ...
result = XTMInitHandlers();
if (!result)
{
return result;
}
//
result = true;
//
return result;
}
//
// Release Indicators ...
void XTMReleaseIndicators()
{
//
// Release Handlers ...
XTMReleaseHandlers();
}
//
// Handle Reading Buffers ...
void XTMHandleReadingBuffers()
{
//
// Reading Calculated Bars for a Simple Handler ...
xTMCalculatedBars = BarsCalculated(xTMHandler);
//
// Read Indicators Buffers ...
XTMReadBuffers(xTMNumberOfItemsPerTick);
}
//
//
// START Combination Functions ...
//
//
//
// Can Open Long Trade ...
// this is a Function will Check all market Conditions and get all
// Strategy requirement Verifications for Long Signals ...
bool XTMCanOpenLongTrade() {
//
bool result = false;
//
result = XTMHasLongConditions(xTMNumberOfItemsPerTick);
//
return result;
}
//
// Can Close Long Trade ...
// this is a Function will Check all market Conditions and get all
// Strategy requirement Verifications for Long Signals ...
bool XTMCanCloseLongTrade() {
//
bool result = false;
//
return result;
}
//
// Can Open Short Trade ...
// this is a Function will Check all market Conditions and get all
// Strategy requirement Verifications for Short Signals ...
bool XTMCanOpenShortTrade() {
//
bool result = false;
//
result = XTMHasShortConditions(xTMNumberOfItemsPerTick);
//
return result;
}
//
// Can Close Short Trade ...
// this is a Function will Check all market Conditions and get all
// Strategy requirement Verifications for Short Signals ...
bool XTMCanCloseShortTrade() {
//
bool result = false;
//
return result;
}
//
//
// END Combination Functions ...
//
//
@@ -0,0 +1,63 @@
///////////////////////////////////////////////////////////////
//
// SaherElm IT Center MQL5 XTM Signal Provider Library Inputs
// -----------------------------------------------------------
//
// 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
//
input group "XTM Provider";
//
input group "XTM Common";
input bool enableXTMPProvider = true; // Enable Provider
input bool xTMEnableAlerts = false; // Enable Events Alert
input int xTMNumberOfItemsPerTick = 72; // Number Of items Readed In Each Tick
//
input group "XTM Trader";
input int xTMMagicNumber = 16940560; // Trader MagicNumber
input int xTMSlippage = 10; // Trader Slippage
//
input group "XTM Trade Management";
input bool xTMAllowLongTrades = true; // Allow Long Trades
input bool xTMAllowShortTrades = true; // Allow Short Trades
//
input group "XTM Risk Management";
input int xTMMaxAllowedTrades = 5; // Max Allowed Trades at Same Time
input int xTMMaxInProfitTradeAge = 0; // Max In Profit Trades Age
input int xTMMaxInDrawDownTradeAge = 576; // Max In DrawDown Trades Age
input double xTMStaticVolume = 0.02; // Static Volume
input double xTMVolumeMultiplier = 2; // Volume Multiplier
input double xTMMinRewardPerTradeInPips = 1; // Min Reward Per Trade In Pips
input double xTMFreeMarginFactorForOpenTrades = 0.5; // Minimum Free Marging for Open Trades
input double xTMBalanceFactorForOpenTrades = 0.5; // Minimum Balance for Open Trades
input bool xTMEnableSupportTrades = false; // Enable Support Trade
//
// Validate Inputs before Initialization ...
bool XTMValidateInputs()
{
//
bool result = false;
//
// TODO: Fix this ...
result = true;
//
return result;
}
+853
View File
@@ -0,0 +1,853 @@
////////////////////////////////////////////////////////////
//
// SaherElm IT Center MQL5 XTM Signal Provider Library
// --------------------------------------------------------
// Name: XTMSignalProvider
// Description: XTM based signal provider ...
//
//
// Maintainer:
// ------------
// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com)
//
//////////////////////////////////////////////////////
//
// Global Properties ...
#property library
#property copyright "Copyright 2023, SaherElm IT Center"
#property link "https://www.saherelm.ir"
#property version "1.00"
#property strict
#define XTMProviderName "XTM"
//
// START Inputs ...
//
#include "x-saherelm.xtm.provider.inputs.lib.mq5";
//
// END Inputs ...
//
//
// Include Common Library ...
#include "x-saherelm.common.lib.mq5"
//
// Include Logger Library ...
#include "x-saherelm.log.lib.mq5"
//
// Include Alert Library ...
#include "x-saherelm.alert.lib.mq5"
//
// Include Draw Library ...
#include "x-saherelm.draw.lib.mq5"
//
// Include Class Libraries ...
#include "x-saherelm.class.lib.mq5"
//
// START Global Definitions: Variables, Properties and etc ...
//
//
XCTrade *xTMTrader;
XCAccountInfo xTMAccountInfo;
//
#include "x-saherelm.xtm.provider.indicators.lib.mq5"
//
double xTMDeposit = 0;
double xTMBalance = 0;
double xTMFreeMargin = 0;
double xTMFreeMarginForOpenTrades = 0;
double xTMBalanceForOpenTrades = 0;
//
// END Global Definitions: Variables, Properties and etc ...
//
//
// START Provided Functions ...
//
//
// Initial Library if required ...
bool XTMInitSignalProviderLibrary()
{
//
bool result = false;
//
// Validate Inputs ...
result = XTMValidateInputs();
if (!result)
{
return result;
}
//
// Init Indicators ...
result = XTMInitIndicators();
if (!result)
{
return result;
}
//
// Calculate Account Deposit ...
xTMDeposit = xTMAccountInfo.GetInitialBalance();
//
// Calculate Min Balance for Trades ...
if (xTMBalanceFactorForOpenTrades > 0)
{
xTMBalanceForOpenTrades = xTMBalanceFactorForOpenTrades * xTMDeposit;
}
//
// Claculate Min Free Marging for Trades ...
if (xTMFreeMarginFactorForOpenTrades > 0)
{
xTMFreeMarginForOpenTrades = xTMFreeMarginFactorForOpenTrades * xTMDeposit;
}
//
// Make XCTrader instance ...
xTMTrader = new XCTrade(
_Symbol,
xTMSlippage,
xTMMagicNumber);
//
result = true;
//
// Logging State ...
XTMIssueInitializationSucceedAlert();
//
return result;
}
//
// DeInitial Library if required ...
void XTMDeinitSignalProviderLibrary(
const int reason)
{
//
// Release Handlers ...
XTMReleaseIndicators();
//
// Logging State ...
XTMIssueDeinitializationSucceedAlert();
}
//
// this is a Globally Function which do all of
// checkings and positions handling ...
void XTMSignalProviderHandleTick()
{
//
// Update account Balance ...
xTMBalance = xTMAccountInfo.GetBalance();
xTMFreeMargin = xTMAccountInfo.GetFreeMargin();
//
// Reading Indicator Buffers ...
XTMHandleReadingBuffers();
if (xTMCalculatedBars < xTMMaxLengthOfInputs)
{
return;
}
//
// Handle Open Trades ...
XTMHandleOpenTrades();
//
// Handle Close Trades ...
XTMHandleCloseTrades();
}
//
// Handle Open Trades ...
void XTMHandleOpenTrades()
{
//
// Check Can Trade ...
bool canTrade = xTMAllowLongTrades || xTMAllowShortTrades;
if (!canTrade)
{
return;
}
//
// First Check Signal Exists or NOt ...
bool xTMHasLongSignal = XTMCanOpenLongTrade();
bool xTMHasShortSignal = XTMCanOpenShortTrade();
if (!xTMHasLongSignal && !xTMHasShortSignal)
{
return;
}
//
// Count Max Open Trades ...
if (xTMMaxAllowedTrades > 0)
{
//
int count = xTMTrader.Count();
bool canOpenTrade = count < xTMMaxAllowedTrades;
if (!canOpenTrade)
{
//
XTMIssueMaxAllowedTradesReachedAlert();
//
return;
}
}
//
// Check Free Margin ...
if (xTMFreeMargin <= xTMFreeMarginForOpenTrades)
{
//
XTMIssueMaxAllowedFreeMarginReachedAlert();
//
return;
}
//
// Check Account Balance ...
if (xTMBalance <= xTMBalanceForOpenTrades)
{
//
XTMIssueMinAllowedBalanceReachedAlert();
//
return;
}
//
// Primary Long Trade ...
if (
xTMHasLongSignal &&
xTMAllowLongTrades)
{
//
bool isLongSignalExecuted = XTMOpenLongPosition();
if (isLongSignalExecuted)
{
}
}
//
// Primary Short Trade ...
if (
xTMHasShortSignal &&
xTMAllowShortTrades)
{
//
bool isShortSignalExecuted = XTMOpenShortPosition();
if (isShortSignalExecuted)
{
}
}
}
//
// Handle Close Trades ...
void XTMHandleCloseTrades()
{
//
// Handle Long/Buy Close ...
if (xTMTrader.CountLongs() > 0 && XTMCanCloseLongTrade())
{
//
XSignal closed[];
xTMTrader.CloseLongPositions(closed);
bool hasClosed = ArraySize(closed) > 0;
if (hasClosed)
{
XTMIssueForceCloseTradesAlert(X_SIGNAL_LONG);
}
}
//
// Handle Short/Sell Close ...
if (xTMTrader.CountShorts() > 0 && XTMCanCloseShortTrade())
{
//
XSignal closed[];
xTMTrader.CloseShortPositions(closed);
bool hasClosed = ArraySize(closed) > 0;
if (hasClosed)
{
XTMIssueForceCloseTradesAlert(X_SIGNAL_SHORT);
}
}
//
// Handle Close In Profit Teades ...
if (xTMMaxInProfitTradeAge > 0)
{
//
XSignal closed[];
XSignal longTimeTrades[];
xTMTrader.GetLongTimeTrades(
xTMMaxInProfitTradeAge,
_Period,
longTimeTrades);
int count = ArraySize(longTimeTrades);
if (count > 0)
{
//
// Loop ...
for (int i = 0; i < count; i++)
{
//
XSignal trade = longTimeTrades[i];
if (trade.profit < 0)
{
continue;
}
//
bool isClosed = xTMTrader.Close(trade.ticket);
if (isClosed)
{
Add(
trade,
closed);
}
}
}
//
if (ArraySize(closed) > 0)
{
XTMIssueLongInProfitTradeClosed();
}
}
//
// Handle Close In DrawDown Trades ...
if (xTMMaxInDrawDownTradeAge > 0)
{
//
XSignal closed[];
XSignal longTimeTrades[];
xTMTrader.GetLongTimeTrades(
xTMMaxInDrawDownTradeAge,
_Period,
longTimeTrades);
int count = ArraySize(longTimeTrades);
if (count > 0)
{
//
// Loop ...
for (int i = 0; i < count; i++)
{
//
XSignal trade = longTimeTrades[i];
if (trade.profit > 0)
{
continue;
}
//
// Open Grid Trades ...
XTMOpenSuppurtTrade(trade);
// //
// bool isClosed = xTMTrader.Close(trade.ticket);
// if (isClosed)
// {
// //
// Add(
// trade,
// closed);
// }
}
}
//
if (ArraySize(closed) > 0)
{
XTMIssueLongInDrawdownTradeClosed();
}
}
}
//
// Open Long Position ...
bool XTMOpenLongPosition()
{
//
bool result = false;
//
// Generate Position Signal and Validate it ...
XSignal position = XTMGeneratePositionSignal(X_SIGNAL_LONG);
if (!IsValid(
position,
xTMMagicNumber))
{
return result;
}
//
// Try to Open Position ...
result = xTMTrader.ExecuteSignal(position);
if (result)
{
XTMIssueSignalExecutionAlert(position);
}
//
return result;
}
//
// Open Short Position ...
bool XTMOpenShortPosition()
{
//
bool result = false;
//
// Generate Position Signal and Validate it ...
XSignal position = XTMGeneratePositionSignal(X_SIGNAL_SHORT);
if (!IsValid(
position,
xTMMagicNumber))
{
return result;
}
//
// Try to Open Position ...
result = xTMTrader.ExecuteSignal(position);
if (result)
{
XTMIssueSignalExecutionAlert(position);
}
//
return result;
}
//
// Open a Support Signal ...
bool XTMOpenSuppurtTrade(
XSignal &signal // Parent Signal
)
{
//
bool result = false;
//
if (!xTMEnableSupportTrades) {
return result;
}
//
// Validate Signal ...
if (!IsValid(signal, xTMMagicNumber))
{
return result;
}
//
// Market Conditions ...
bool hasLongSignal = XTMCanOpenLongTrade();
bool hasShortSignal = XTMCanOpenShortTrade();
//
ENUM_X_SIGNAL_TYPE type = X_SIGNAL_UNKNOWN;
//
// Detect Support Signal Direction ...
XSignal support = {};
switch (signal.type)
{
//
case X_SIGNAL_LONG:
//
// First Check Long Support ...
// Then Look for Short Support ...
if (hasLongSignal)
{
type = X_SIGNAL_LONG;
}
else if (hasShortSignal)
{
type = X_SIGNAL_SHORT;
}
else
{
type = signal.type;
}
break;
//
case X_SIGNAL_SHORT:
// First Check Short Support ...
// Then Look for Long Support ...
if (hasShortSignal)
{
type = X_SIGNAL_SHORT;
}
else if (hasLongSignal)
{
type = X_SIGNAL_LONG;
}
else
{
type = signal.type;
}
break;
}
//
if (type == X_SIGNAL_UNKNOWN)
{
return result;
}
bool isLong = type == X_SIGNAL_LONG;
//
// Find Common Used ...
double entry = GetEntry(type);
double volumeMultiplier = 2;
if (xTMVolumeMultiplier > 2)
{
volumeMultiplier = xTMVolumeMultiplier;
}
//
// Check Signal is Support ot nor ...
int titlePosition = StringFind(
signal.comment,
"Support");
bool isSupport = titlePosition >= 0;
double priceDistance = MathAbs(signal.entry - entry);
//
if (isSupport || priceDistance < PipsToPrice(5)) {
return result;
}
//
datetime time = iTime(
_Symbol,
_Period,
0);
double volume = NormalizeVolume(isSupport ? signal.volume : signal.volume * volumeMultiplier);
string comment = "Support_" + GetSignalType(type) + "_For_" + (string)signal.ticket + "_" + (string)volume + "_" + (string)time;
//
XTPSL tpSL = XTMCalculateTPSL(type);
if (!IsValid(tpSL))
{
return result;
}
//
// Calculate reward of signal ...
double reward = MathAbs(signal.entry - signal.tp) / 2;
double tp = tpSL.sl; // isLong ? entry + reward : entry - reward;
double sl = tpSL.sl;
//
// Filling Support Signal ...
support.tp = tp;
support.sl = sl;
support.type = type;
support.time = time;
support.entry = entry;
support.volume = volume;
support.symbol = _Symbol;
support.comment = comment;
support.magicNumber = xTMMagicNumber;
//
// Validate Generated Support ...
if (!IsValid(support, xTMMagicNumber))
{
return result;
}
//
result = xTMTrader.ExecuteSignal(support);
if (result)
{
XTMIssueSignalExecutionAlert(support);
}
//
return result;
}
//
// Generate Specific type of Signals for Trading ...
XSignal XTMGeneratePositionSignal(
ENUM_X_SIGNAL_TYPE type // direction of position
)
{
//
XSignal result = {};
//
if (type != X_SIGNAL_LONG &&
type != X_SIGNAL_SHORT)
{
return result;
}
//
double ask = GetAsk();
double bid = GetBid();
double entry = GetEntry(type);
//
double volume = XTMCalculateVolume();
//
datetime time = iTime(
_Symbol,
_Period,
0);
//
string typeString = GetSignalType(type);
string comment = XTMProviderName + "_" + typeString + "_" + (string)volume + "_" + (string)time;
//
XTPSL tpSL = XTMCalculateTPSL(type);
if (IsValid(tpSL))
{
//
// Apply TP ...
if (tpSL.tp > 0)
{
result.tp = tpSL.tp;
}
//
// Apply SL ...
if (tpSL.sl > 0)
{
result.sl = tpSL.sl;
}
}
//
result.type = type;
result.time = time;
result.entry = entry;
result.volume = volume;
result.symbol = _Symbol;
result.comment = comment;
result.magicNumber = xTMMagicNumber;
//
return result;
}
//
// END Provided Functions ...
//
//
// START Private Functions ...
//
//
// Calculating Volume for Tradings ...
double XTMCalculateVolume()
{
//
// Assign default Value ...
double result = xTMStaticVolume;
//
// we can count open trades and in draw down trades
// then do check volume based on it for gridding ...
int openTrades = xTMTrader.Count();
if (openTrades == 0)
{
openTrades = 1;
}
//
// Calculate Normalized Multiplier ...
double multiplier = xTMVolumeMultiplier <= 0 ? 1 : xTMVolumeMultiplier;
//
result = multiplier * openTrades * xTMStaticVolume;
//
// Normalize Volume ...
result = NormalizeVolume(result);
//
return result;
}
//
// Calculate Signal TP and SL ...
XTPSL XTMCalculateTPSL(
ENUM_X_SIGNAL_TYPE type // Position Type
)
{
//
XTPSL result = {};
//
// Validate Args ...
if (
type != X_SIGNAL_LONG &&
type != X_SIGNAL_SHORT)
{
return result;
}
//
bool isLong = type == X_SIGNAL_LONG;
//
double ask = GetAsk();
double bid = GetBid();
double spread = GetSpread();
double entry = isLong ? ask : bid;
//
// TODO: Find Risk ..
double risk = 0;
//
// Calculate Reward ...
double reward = PipsToPrice(xTMMinRewardPerTradeInPips) + spread;
//
// Calculate TP and SL ...
double tp = isLong ? entry + reward : entry - reward;
double sl = 0;
//
result.type = type;
result.tp = tp;
result.sl = sl;
result.entry = entry;
//
// TODO: Calculate R2R ...
result.r2r = 0;
//
return result;
}
void XTMIssueInitializationSucceedAlert()
{
//
string message = "Initializion of (" + XTMProviderName + " Provider" + " _ " + _Symbol + " _ " + EnumToString(_Period) + ") Succeeded ...";
XTMIssueAlert(message);
}
void XTMIssueDeinitializationSucceedAlert()
{
//
string message = "De Initializion of (" + XTMProviderName + " Provider" + ") Succeeded ...";
XTMIssueAlert(message);
}
void XTMIssueForceCloseTradesAlert(ENUM_X_SIGNAL_TYPE type) {
//
string typeStr = GetSignalType(type);
if (StringLen(typeStr) == 0) {
return;
}
//
string message = "Force Close " + typeStr + " Trades ...";
XTMIssueAlert(message);
}
void XTMIssueMaxAllowedTradesReachedAlert()
{
//
string message = "reached Max Allowed Same Time Trades ...";
XTMIssueAlert(message);
}
void XTMIssueMaxAllowedFreeMarginReachedAlert()
{
//
string message = "reached FreeMarigin For Open Trades ...";
XTMIssueAlert(message);
}
void XTMIssueMinAllowedBalanceReachedAlert()
{
//
string message = "doesn't have Minimum Balance For Open Trades ...";
XTMIssueAlert(message);
}
void XTMIssueSignalExecutionAlert(
XSignal &signal // Executed Signal
)
{
//
XTMIssueAlert(signal);
}
void XTMIssueLongInProfitTradeClosed()
{
//
string message = "Closed Long Time in Profit Trades ...";
XTMIssueAlert(message);
}
void XTMIssueLongInDrawdownTradeClosed()
{
//
string message = "Closed Long Time in Profit Trades ...";
XTMIssueAlert(message);
}
void XTMIssueAlert(string message)
{
//
if (xTMEnableAlerts)
{
SendAlert(message);
}
else
{
LogMessage(message);
}
}
void XTMIssueAlert(XSignal &signal)
{
//
if (xTMEnableAlerts)
{
SendAlert(signal);
}
else
{
LogSignal(signal);
}
}
//
// END Private Functions ...
//