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
Binary file not shown.
@@ -0,0 +1,169 @@
///////////////////////////////////////////////////////
//
// SaherElm IT Center MQL5 Expert Advisor
// ----------------------------------------
// Name: XEA
// Description: this is an expert controller
// advisors which provides a mechanism for use them ...
//
//
// Maintainer:
// ------------
// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com)
//
//////////////////////////////////////////////////////
//
// Global Properties ...
#property copyright "Copyright 2023, SaherElm IT Center"
#property link "https://saherelm.ir"
#property version "1.00"
#property description "SaherElm XEA"
#property strict
//
// START Inputs ...
//
input group "Commons";
//
// END Inputs ...
//
//
// START Including Providers ...
//
//
// Logger Library ...
#include "..\Libraries\x-saherelm.log.lib.mq5";
//
// Common Library ...
#include "..\Libraries\x-saherelm.common.lib.mq5";
//
// Alert Library ...
#include "..\Libraries\x-saherelm.alert.lib.mq5";
//
// Draw Library ...
#include "..\Libraries\x-saherelm.draw.lib.mq5";
//
// XTM Signal Provider ...
#include "..\Libraries\x-saherelm.xtm.provider.lib.mq5";
//
// END Including Providers ...
//
//
// START Global Definitions: Variables, Properties and etc ...
//
//
// END Global Definitions: Variables, Properties and etc ...
//
//
// START Event Handlers ...
//
//
// Initialization ...
int OnInit()
{
//
logTag = "XEA";
drawPrefix = logTag;
alertPrefix = logTag;
//
// Validate Inputs ...
if (!ValidateInputs())
{
return INIT_PARAMETERS_INCORRECT;
}
//
// Initialize XTM Provider ...
if (!XTMInitSignalProviderLibrary())
{
return INIT_PARAMETERS_INCORRECT;
}
//
// Apply default Chart Style for EA ...
ApplyChartStyle();
//
// Init Succeed ...
return INIT_SUCCEEDED;
}
//
// DeInitialization ...
void OnDeinit(const int reason)
{
//
// REASON_PROGRAM 0 The EA has stopped working calling the ExpertRemove() function
// REASON_REMOVE 1 Program removed from a chart
// REASON_RECOMPILE 2 Program recompiled
// REASON_CHARTCHANGE 3 A symbol or a chart period is changed
// REASON_CHARTCLOSE 4 Chart closed
// REASON_PARAMETERS 5 Inputs changed by a user
// REASON_ACCOUNT 6 Another account has been activated or reconnection to the trade server has occurred due to changes in the account settings
// REASON_TEMPLATE 7 Another chart template applied
// REASON_INITFAILED 8 The OnInit() handler returned a non-zero value
// REASON_CLOSE 9 Terminal closed
//
// Here we can handle De Initialization Reasons ...
//
// De Initialize XTM Provider ...
XTMDeinitSignalProviderLibrary(reason);
//
// De Init XDraw Library ...
OnDeinitDrawLibrary();
}
//
// On Tick Handler ...
void OnTick()
{
//
if (!IsNewCandle())
{
return;
}
//
// Handle Processing on XTM Signal Provider ...
XTMSignalProviderHandleTick();
}
//
// END Event Handlers ...
//
//
// START Functions ...
//
//
// Validate Input Args for Initialization ...
bool ValidateInputs()
{
//
bool result = false;
//
// Validate Args ...
result = XTMValidateInputs();
//
// Logging State ...
string message = "Validation of (" + "XEA" + ") Inputs " + (result ? "Succeeded" : "Failed") + " ...";
LogMessage(message);
//
return result;
}
//
// END Functions ...
//
@@ -0,0 +1,349 @@
///////////////////////////////////////////////////////
//
// SaherElm IT Center MQL5 Candle Indicator
// ---------------------------------------------
// Name: XTM
// Description: Trend Magic Indicator ...
//
//
// Maintainer:
// ------------
// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com)
//
//////////////////////////////////////////////////////
//
// Global Properties ...
#property copyright "Copyright 2023, SaherElm IT Center"
#property link "https://saherelm.ir"
#property version "1.00"
#property description "SaherElm XTM Indicator"
#property strict
//
// START Constants ...
//
#define ShortName "XTM"
//
// XTM Indicator States ...
enum ENUM_X_XTM_STATES
{
X_XTM_BULLISH = 1,
X_XTM_BEARISH = -1,
X_XTM_NEUTURAL = 0,
};
//
// END Constants ...
//
//
// START Inputs ...
//
input int maPeriod = 14; // Period
input int maShift = 0; // Shift
input ENUM_MA_METHOD maMethod = MODE_SMA; // Method
input ENUM_APPLIED_PRICE maAppliedTo = PRICE_CLOSE; // Applied To
//
// END Inputs ...
//
//
// Includes Logging Library ...
#include "../Libraries/x-saherelm.log.lib.mq5";
//
// Includes Common Library ...
#include "../Libraries/x-saherelm.common.lib.mq5";
//
// START Buffers ...
//
#property indicator_chart_window
//
#property indicator_buffers 3
#property indicator_plots 1
//
// maBuffer ...
#define maBufferIndex 0
#define maColorBufferIndex 1
#define stateBufferIndex 2
double maBuffer[];
double maColorBuffer[];
double stateBuffer[];
#property indicator_label1 "XTM"
#property indicator_type1 DRAW_COLOR_LINE
#property indicator_color1 clrLime, clrGray, clrRed
#property indicator_style1 STYLE_SOLID
#property indicator_width1 1
//
// END Buffers ...
//
//
// START Global Definitions: Variables, Properties and etc ...
//
int maHandler = INVALID_HANDLE;
//
// END Global Definitions: Variables, Properties and etc ...
//
//
// START Event Handlers ...
//
//
// Initialization ...
int OnInit()
{
//
// Validate Inputs ...
if (!ValidateInputs())
{
return INIT_PARAMETERS_INCORRECT;
}
//
logTag = ShortName;
//
// Initializing MA Handler ...
maHandler = iMA(
_Symbol,
_Period,
maPeriod,
maShift,
maMethod,
maAppliedTo);
if (maHandler == INVALID_HANDLE)
{
//
string message = "Error Initializing Ma Handler ...";
LogMessage(message);
//
return INIT_FAILED;
}
//
// Define Index Buffers ...
DefineBuffers();
//
// Set Indicator ShortName ...
SetIndicatorName();
//
// Init Succeed ...
return INIT_SUCCEEDED;
}
//
// DeInitialization ...
void OnDeinit(const int reason)
{
//
// REASON_PROGRAM 0 The EA has stopped working calling the ExpertRemove() function
// REASON_REMOVE 1 Program removed from a chart
// REASON_RECOMPILE 2 Program recompiled
// REASON_CHARTCHANGE 3 A symbol or a chart period is changed
// REASON_CHARTCLOSE 4 Chart closed
// REASON_PARAMETERS 5 Inputs changed by a user
// REASON_ACCOUNT 6 Another account has been activated or reconnection to the trade server has occurred due to changes in the account settings
// REASON_TEMPLATE 7 Another chart template applied
// REASON_INITFAILED 8 The OnInit() handler returned a non-zero value
// REASON_CLOSE 9 Terminal closed
//
// Here we can handle De Initialization Reasons ...
}
//
// Calculations ...
//
// Calculating what we want ...
int OnCalculate(
//
// total Candles on chart ...
const int rates_total,
//
// total calculated Candles on charts ...
const int prev_calculated,
//
// history of Candles Open Time ...
const datetime &time[],
//
// history of Candles Open Price ...
const double &open[],
//
// history of Candles High Price ...
const double &high[],
//
// history of Candles Low Price ...
const double &low[],
//
// history of Candles Close Price ...
const double &close[],
//
// history of Tick Volumes on Candle ...
const long &tick_volume[],
//
// history of Trade Volumes ...
const long &volume[],
//
// history of Candles Spread Price ...
const int &spread[])
{
//
// Prepare Buffers ...
ArraySetAsSeries(time, true);
ArraySetAsSeries(open, true);
ArraySetAsSeries(high, true);
ArraySetAsSeries(low, true);
ArraySetAsSeries(close, true);
ArraySetAsSeries(tick_volume, true);
ArraySetAsSeries(volume, true);
ArraySetAsSeries(spread, true);
//
// this counts Available Bars ...
int limit;
//
// because in some cases we may have more than one input for
// calculation and we must prevent any calculation
// untill we pass the biggest input length, here we get max Input length
// and then wait until pass it ...
int maxLength = MathMax(0, maPeriod);
//
// Check Calculated Bars ...
int maCalculatedBars = BarsCalculated(maHandler);
if (maCalculatedBars < maxLength)
{
return prev_calculated;
}
//
limit = (prev_calculated > rates_total || prev_calculated <= 0) ? rates_total : (rates_total - prev_calculated) + 1;
//
// Buffers Copy ...
int copiedMas = CopyBuffer(maHandler, 0, 0, limit, maBuffer);
if (copiedMas <= 0)
{
return prev_calculated;
}
//
// Main Loop ...
for (int i = limit - 1; i >= 0 && !IsStopped(); i--)
{
//
// Do Buffers Calculation ...
CalculateBuffers(i);
}
//
return rates_total;
}
//
// END Event Handlers ...
//
//
// START Functions ...
//
//
// Validate Input Args for Initialization ...
bool ValidateInputs()
{
//
bool result = false;
//
// Validate Args ...
if (maPeriod >= 2)
{
result = true;
}
//
return result;
}
//
// Define Indexes and Styles ...
void DefineBuffers()
{
//
string maBufferLabel = "XTM " + "(" + (string)maPeriod + ")";
//
// Ma Buffer ...
ArraySetAsSeries(maBuffer, true);
SetIndexBuffer(maBufferIndex, maBuffer, INDICATOR_DATA);
PlotIndexSetString(maBufferIndex, PLOT_LABEL, maBufferLabel);
//
// Ma Color Buffer ...
ArraySetAsSeries(maColorBuffer, true);
SetIndexBuffer(maColorBufferIndex, maColorBuffer, INDICATOR_COLOR_INDEX);
//
// State Buffer ...
ArraySetAsSeries(stateBuffer, true);
SetIndexBuffer(stateBufferIndex, stateBuffer, INDICATOR_CALCULATIONS);
}
//
// Set Indicator Short Name and also we can define Buffers Labels ...
void SetIndicatorName()
{
//
string indicatorShortName = "";
StringConcatenate(indicatorShortName, ShortName, " ", "(", maPeriod, ")");
//
IndicatorSetString(INDICATOR_SHORTNAME, indicatorShortName);
}
//
// Calculate Buffers ...
void CalculateBuffers(int bar_index)
{
//
// Requirements ...
XOHCL candle = GetCandle(bar_index);
//
double maValue = maBuffer[bar_index];
//
double lineColorIndex =
maValue < candle.low ? 0 : maValue > candle.high ? 2
: 1;
//
// Define State Value ...
// lineColorIndex == 0 => Bullish => 1;
// lineColorIndex == 1 => Neutural => 0;
// lineColorIndex == 2 => Bearish => -1;
double stateValue =
lineColorIndex == 0 ? X_XTM_BULLISH : lineColorIndex == 2 ? X_XTM_BEARISH
: X_XTM_NEUTURAL;
//
// Set Ma Buffer Color Index ...
maColorBuffer[bar_index] = lineColorIndex;
//
// Set State Buffer Value ...
stateBuffer[bar_index] = stateValue;
}
//
// END Functions ...
//
@@ -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
@@ -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 ...
//
@@ -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 ...
//
@@ -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 ...
//
@@ -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,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;
}
@@ -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 ...
//