last backup ...

This commit is contained in:
2026-01-08 11:39:42 +03:30
parent afafeca00a
commit 963e045e65
249 changed files with 328192 additions and 0 deletions
@@ -0,0 +1,414 @@
///////////////////////////////////////////////////////
//
// SaherElm IT Center XTest MQL5 Expert Advisor
// -------------------------------------------------
// Name: XBackTester
// Description: a Backtest Tools Strategy Tester
//
// Maintainer:
// ------------
// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com)
//
//////////////////////////////////////////////////////x
//
// Global Properties ...
#property copyright "Copyright 2023, SaherElm IT Center"
#property link "https://saherelm.ir"
#property version "1.00"
#property icon "../Images/SaherElm_Logo_Color.ico"
#property description "SaherElm XBackTester"
#property strict
//
#define ShortName "XBackTester"
//
// Imports ...
#include "../Classes/x-saherelm.x-backtester.expert.class.mq5"
//
// Definitions ...
//
// Inputs ...
//
// Common ...
input group "Common";
input long eaMagicNumber = 78692110; // Magic Number
input int eaSlippage = 10; // Slippgae
input string eaLogSuffix = ""; // Log Suffix
//
// Alert ...
// Here we Provider All Requirements for
// Configuring Alert Provider ...
input group "Alert";
input bool eaEnableAlerts = true; // Enable Alerts
input bool eaLogAlerts = true; // Log Alerts
input bool eaMailAlerts = false; // Mail Alerts
input bool eaPushAlerts = false; // Push Alerts
input bool eaTerminalAlerts = false; // Terminal Alerts
//
// Define Local Variables ...
//
string eaLogTag; // EA Log Prefix ...
XCBackTesterEA *eaExpert; // EA Expert ...
//
// Event Handlers ...
//
// Initialization ...
int OnInit()
{
//
// Preparing Tags ...
string eaTag =
(IsValid(eaLogSuffix)
? eaLogSuffix + "_"
: "") +
ShortName;
//
// Validate Inputs and Required Parameters
// for EA to Works fine ...
if (!ValidateInputs())
{
return INIT_PARAMETERS_INCORRECT;
}
//
// Initialize Timer ...
if (!InitTimer())
{
return INIT_FAILED;
}
//
// Configure EA Expert Class ...
eaExpert = new XCBackTesterEA();
//
// Symbol / Period ...
eaExpert.symbol = _Symbol;
eaExpert.period = _Period;
//
// Common ...
eaExpert.eaMagicNumber = eaMagicNumber;
eaExpert.eaSlippage = eaSlippage;
eaExpert.eaLogSuffix = eaTag;
//
// Alert ...
eaExpert.eaEnableAlerts = eaEnableAlerts;
eaExpert.eaLogAlerts = eaLogAlerts;
eaExpert.eaMailAlerts = eaMailAlerts;
eaExpert.eaPushAlerts = eaPushAlerts;
eaExpert.eaTerminalAlerts = eaTerminalAlerts;
//
// Attach Event Handlers ...
eaExpert.AddOnDealsChangedEventHandler(OnDealsChanged);
eaExpert.AddOnStopLossEventHandler(OnStopLossTriggered);
eaExpert.AddOnOrdersChangedEventHandler(OnOrdersChanged);
eaExpert.AddOnTakeProfitEventHandler(OnTakeProfitTriggered);
eaExpert.AddOnModifyPositionEventHandler(OnPositionModified);
eaExpert.AddOnPositionsChangedEventHandler(OnPositionsChanged);
eaExpert.AddOnTradeStateChangedEventHandler(OnTradeStateChanged);
eaExpert.AddOnForceClosePositionEventHandler(OnPositionForceClosed);
eaExpert.AddOnPartialClosePositionEventHandler(OnPositionPartialClosed);
//
// Configure Other Requirements ...
// eaExpert.volume = 0;
// eaExpert.riskInPoint = 0;
// eaExpert.allowedTPSLStep = 0;
// eaExpert.riskToRewardRatio = 0;
// eaExpert.minAllowedRiskInPoint = 0;
//
// Try to Initialize eaExpert ...
bool isInited = eaExpert.HandleOnInit();
if (!isInited)
{
//
Print(ShortName, ": Initialization Failed ...");
return INIT_FAILED;
}
//
Print(ShortName, ": Initialized Successfully ...");
return INIT_SUCCEEDED;
}
//
// DeInitialization ...
void OnDeinit(const int reason)
{
//
// REASON_PROGRAM 0 The EA has stopped working calling the ExpertRemove() function
// REASON_REMOVE 1 Program removed from a chart
// REASON_RECOMPILE 2 Program recompiled
// REASON_CHARTCHANGE 3 A symbol or a chart period is changed
// REASON_CHARTCLOSE 4 Chart closed
// REASON_PARAMETERS 5 Inputs changed by a user
// REASON_ACCOUNT 6 Another account has been activated or reconnection to the trade server has occurred due to changes in the account settings
// REASON_TEMPLATE 7 Another chart template applied
// REASON_INITFAILED 8 The OnInit() handler returned a non-zero value
// REASON_CLOSE 9 Terminal closed
//
// Destroy Timer ...
eaExpert.HandleOnDeInit();
//
delete eaExpert;
ZeroMemory(eaExpert);
}
//
// On Tick Handler ...
void OnTick()
{
eaExpert.HandleOnTick();
}
//
// Handle On Trade Event ...
void OnTrade()
{
eaExpert.HandleOnTrade();
}
//
// On Timer ...
void OnTimer()
{
eaExpert.HandleOnTimer();
}
//
// Chart Event Handler ...
void OnChartEvent(
const int id,
const long &lparam,
const double &dparam,
const string &sparam //
)
{
eaExpert.HandleOnChartEvent(id, lparam, dparam, sparam);
}
//
// Custom Functions ...
/**
* Validate all Inputs of Expert Adviser ...
*
* @return ( bool )
*/
bool ValidateInputs()
{
//
bool result = false;
//
string errMessage = "";
//
bool isCommonValid = (
//
eaSlippage > 0 &&
eaMagicNumber > 0
//
);
if (!isCommonValid)
{
//
errMessage += "common configurations error;" + "\n";
}
//
result =
//
// Common ...
isCommonValid &&
//
// Otere ...
true
//
;
//
if (!result)
{
//
// Since here Logger not Initiallized, we Use Raw Print Command ...
Print(ShortName + " Errors: \n", errMessage);
}
//
return result;
}
/**
* Initialize Timer ...
*
* @return ( bool )
*/
bool InitTimer()
{
//
bool result = false;
//
// TODO: Initialize Timer if necessary ...
// result = EventSetTimer(1);
// result = EventSetMillisecondTimer(100);
result = true;
//
return result;
}
/**
* Destroy Timer ...
*/
void DestroyTimer()
{
//
// TODO: Use This ...
// EventKillTimer();
}
//
// Trade Event Handlers ...
/**
* Handle StopLoss Triggered Positions ...
*
* @param deal: XDeal instance ...
*/
void OnStopLossTriggered(const XDeal &deal)
{
eaExpert.HandleOnStopLossTriggered(deal);
}
/**
* Handle Take Profit Triggered Positions ...
*
* @param deal: XDeal instance ...
*/
void OnTakeProfitTriggered(const XDeal &deal)
{
eaExpert.HandleOnTakeProfitTriggered(deal);
}
/**
* Handle Force Close a Position ...
*
* @param ticket: ULONG ...
* @param position: XPosition instance ...
* @param comment: String ...
*/
void OnPositionForceClosed(
const ulong ticket,
const XPosition &position,
const string comment //
)
{
//
eaExpert.HandleOnPositionForceClosed(
ticket,
position,
comment //
);
}
/**
* Handle Deals Changes ...
*
* @param count: Integer, Number of Changes ...
*/
void OnDealsChanged(int count)
{
eaExpert.HandleOnDealsChanged(count);
}
/**
* Handle Orders Changes ...
*
* @param count: Integer, Number of Changes ...
*/
void OnOrdersChanged(int count)
{
eaExpert.HandleOnOrdersChanged(count);
}
/**
* Handle Positions Changes ...
*
* @param count: Integer, Number of Changes ...
*/
void OnPositionsChanged(int count)
{
eaExpert.HandleOnPositionsChanged(count);
}
/**
* Handle Position Modified ...
*
* @param ticket: ulong, Position Ticket ...
* @param profit: double, Position Profit ...
* @param comment: string, Comment ...
*/
void OnPositionModified(
const ulong ticket,
const double profit,
const string comment //
)
{
//
eaExpert.HandleOnPositionModified(
ticket,
profit,
comment //
);
}
/**
* Handle Position Partial Closed ...
*
* @param ticket: ulong, Position Ticket ...
* @param profit: double, Position Profit ...
* @param comment: string, Comment ...
*/
void OnPositionPartialClosed(
const ulong ticket,
const double profit,
const string comment //
)
{
//
eaExpert.HandleOnPositionPartialClosed(
ticket,
profit,
comment //
);
}
/**
* Handle Trade State Changed ...
*
* @param state: XOnTradeHandlerState instance ...
*/
void OnTradeStateChanged(const XOnTradeHandlerState &state)
{
eaExpert.HandleOnTradeStateChanged(state);
}
//
@@ -0,0 +1,432 @@
///////////////////////////////////////////////////////
//
// SaherElm IT Center XTest MQL5 Expert Advisor
// -------------------------------------------------
// Name: XRRToolsEA
// Description: a Template For Exper Advisors
//
// Maintainer:
// ------------
// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com)
//
//////////////////////////////////////////////////////x
//
// Global Properties ...
#property copyright "Copyright 2023, SaherElm IT Center"
#property link "https://saherelm.ir"
#property version "1.00"
#property icon "../Images/SaherElm_Logo_Color.ico"
#property description "SaherElm XRRToolsEA"
#property strict
//
#define ShortName "XRRTools"
//
// Imports ...
#include "../Classes/x-saherelm.x-alert.class.mq5"
#include "../Classes/x-saherelm.x-rm.panel.class.mq5"
#include "../Classes/x-saherelm.x-trade.class.mq5"
#include "../Helpers/x-saherelm.x121.xcc.helper.mq5"
#include "../Helpers/x-saherelm.x121.xct.helper.mq5"
//
// Inputs ...
//
// Common ...
input group "Common";
input long eaMagicNumber = 78692110; // Magic Number
input int eaSlippage = 10; // Slippgae
input string eaLogSuffix = ""; // Log Suffix
//
// Alert ...
// Here we Provider All Requirements for
// Configuring Alert Provider ...
input group "Alert";
input bool eAEnableAlerts = true; // Enable Alerts
input bool eALogAlerts = true; // Log Alerts
input bool eAMailAlerts = false; // Mail Alerts
input bool eAPushAlerts = false; // Push Alerts
input bool eATerminalAlerts = false; // Terminal Alerts
//
// Define Local Variables ...
//
string eaLogTag; // EA Log Prefix ...
XCAlert *eaAlert; // Alert Provider for Expert Adviser ...
XCTrade *eaTrader; // Trader of Expert Adviser ...
XCRMPanel eaMainWindow; // Main Window ...
XCX121XCTHelper *eaCTHelper; // Bar Timer Indicator Helper class ...
XCX121XCCHelper *eaCCHelper; // Chart Styler Indicator Helper Class ...
//
// Event Handlers ...
//
// Initialization ...
int OnInit()
{
//
// Validate Inputs and Required Parameters
// for EA to Works fine ...
if (!ValidateInputs())
{
return INIT_PARAMETERS_INCORRECT;
}
//
// Initialize Timer ...
if (!InitTimer())
{
return INIT_FAILED;
}
//
// Initialize all Requirements ...
if (!InitEA())
{
return INIT_FAILED;
}
//
// Initialize all GUI Objects and Classes ...
if (!InitGUI())
{
return INIT_FAILED;
}
//
// Alert Initialization ...
string msg = "Initialized Successfully ...";
eaAlert.SendAlert(msg);
//
// Init Succeed ...
return INIT_SUCCEEDED;
}
//
// DeInitialization ...
void OnDeinit(const int reason)
{
//
// REASON_PROGRAM 0 The EA has stopped working calling the ExpertRemove() function
// REASON_REMOVE 1 Program removed from a chart
// REASON_RECOMPILE 2 Program recompiled
// REASON_CHARTCHANGE 3 A symbol or a chart period is changed
// REASON_CHARTCLOSE 4 Chart closed
// REASON_PARAMETERS 5 Inputs changed by a user
// REASON_ACCOUNT 6 Another account has been activated or reconnection to the trade server has occurred due to changes in the account settings
// REASON_TEMPLATE 7 Another chart template applied
// REASON_INITFAILED 8 The OnInit() handler returned a non-zero value
// REASON_CLOSE 9 Terminal closed
//
// Destroy Timer ...
DestroyTimer();
//
// Destroy all GUI Requirements ...
DestroyGUI();
//
// Alert De Initialization Succeeded ...
string msg = "De Initialized Successfully ...";
eaAlert.SendAlert(msg);
//
// Destroy all EA Requirements ...
DestroyEA();
}
//
// On Tick Handler ...
void OnTick()
{
//
UpdateGUI();
}
//
// Handle On Trade Event ...
void OnTrade()
{
eaTrader.HandleOnTrade();
}
//
// On Timer ...
void OnTimer()
{
//
// TODO: Implement Time Based Functionalities ...
}
//
// Chart Event Handler ...
void OnChartEvent(
const int id,
const long &lparam,
const double &dparam,
const string &sparam //
)
{
//
// Apply Chart Event on Main Window ...
eaMainWindow.ChartEvent(id, lparam, dparam, sparam);
}
//
// Custom Event Handlers ...
/**
* Handle StopLoss Triggered Positions ...
*
* @param deal: XDeal ...
*/
void OnStopLossTriggered(const XDeal &deal)
{
}
/**
* Handle Take Profit Triggered Positions ...
*
* @param deal: XDeal ...
*/
void OnTakeProfitTriggered(const XDeal &deal)
{
}
/**
* Handle Force Close a Position ...
*
* @param ticket: Position Ticket ...
* @param position: XPosition ...
* @param comment: Closing Comment ...
*/
void OnPositionForceClosed(
const ulong ticket,
const XPosition &position,
const string comment //
)
{
}
//
// Custom Functions ...
/**
* Validate all Inputs of Expert Adviser ...
*
* @return ( bool )
*/
bool ValidateInputs()
{
//
bool result = false;
//
string errMessage = "";
//
bool isCommonValid = (
//
eaSlippage > 0 &&
eaMagicNumber > 0
//
);
if (!isCommonValid)
{
//
errMessage += "common configurations error;" + "\n";
}
//
result =
//
// Common ...
isCommonValid &&
//
// Otere ...
true
//
;
//
if (!result)
{
//
// Since here Logger not Initiallized, we Use Raw Print Command ...
Print(ShortName + " Errors: \n", errMessage);
}
//
return result;
}
/**
* Initialize Timer ...
*
* @return ( bool )
*/
bool InitTimer()
{
//
bool result = false;
//
// TODO: Initialize Timer if necessary ...
// result = EventSetTimer(1);
// result = EventSetMillisecondTimer(100);
result = true;
//
return result;
}
/**
* Destroy Timer ...
*/
void DestroyTimer()
{
//
// TODO: Use This ...
// EventKillTimer();
}
/**
* Initialize all Requirements for Working Fine ...
*
* @return ( bool )
*/
bool InitEA()
{
//
bool result = false;
//
// Locally Apply Changes on Prefix ...
eaLogTag = ShortName + ">" + eaLogSuffix;
//
// Bar Timer ...
X121XCTInputs ctInputs;
ctInputs.Default(); // Default Configurations ...
eaCTHelper = new XCX121XCTHelper();
result = eaCTHelper.Init(
_Symbol,
_Period,
ctInputs //
);
if (!result)
{
return result;
}
//
// Bar Styles ...
X121XCCInputs ccInputs;
ccInputs.Default(); // Default Configurations ...
eaCCHelper = new XCX121XCCHelper();
result = eaCCHelper.Init(
_Symbol,
_Period,
ccInputs //
);
if (!result)
{
return result;
}
//
// Create Instance of Alert Class and Configure it ...
eaAlert = new XCAlert();
eaAlert.SetPrefix(eaLogTag);
eaAlert.SetLogAlerts(eALogAlerts);
eaAlert.SetMailAlerts(eAMailAlerts);
eaAlert.SetPushAlerts(eAPushAlerts);
eaAlert.SetEnableAlerts(eAEnableAlerts);
eaAlert.SetTerminalAlerts(eATerminalAlerts);
//
// Create Trader Instance and Configure it ...
eaTrader = new XCTrade(
eaSlippage,
eaMagicNumber //
);
eaTrader.AddOnStopLossEventHandler(OnStopLossTriggered);
eaTrader.AddOnTakeProfitEventHandler(OnTakeProfitTriggered);
eaTrader.AddOnForceClosePositionEventHandler(OnPositionForceClosed);
//
return result;
}
/**
* Destroy all Initialized EA Requirements ...
*/
void DestroyEA()
{
//
delete eaCTHelper;
delete eaCCHelper;
//
delete eaAlert;
}
/**
* Initialize all GUI Requirements for EA ...
*
* @return ( bool )
*/
bool InitGUI()
{
//
bool result = false;
//
// Initialize Application Main Window ...
result = eaMainWindow.Create(
ChartID(),
ShortName, // Dialog Name ...
0, // SubWindow ...
10, // X1 ...
35, // Y1 ...
300, // X2 ...
200 // Y2 ...
);
//
// Try To Run Main Window ...
if (result)
{
eaMainWindow.Run();
}
//
return result;
}
/**
* Update GUI based on Each Ticks ...
*/
void UpdateGUI()
{
//
eaMainWindow.UpdateState();
}
/**
* Destroy all Initialized GUi Requirements ...
*/
void DestroyGUI()
{
//
eaMainWindow.Destroy();
}
//
@@ -0,0 +1,631 @@
///////////////////////////////////////////////////////
//
// SaherElm IT Center MQL5 Expert Advisor
// -------------------------------------------------
// Name: XBaseEA
// Description: Base Expert Advisor as Template ...
//
// 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 icon "../Images/SaherElm_Logo_Color.ico"
#property description "SaherElm Based Expert Advisor"
#property strict
//
#define ShortName "XBaseEA"
//
// Importts ...
#include "../Classes/x-saherelm.x-expert.class.mq5"
//
// Inputs ...
//
// Common ...
input group "Common";
input long eaMagicNumber = 1694056; // Magic Number
input int eaSlippage = 10; // Slippgae
input string eaLogSuffix = ""; // Log Suffix
//
// Symbols
// [
// Name|
// Symbol|
// period|
// (ST_04:00_08:30),(TL_10:30_12:00),(NY_16:00_20:00)|
// maxAllowedSpread|
// maxAllowedPosition|
// (
// restrictionsPeriod,
// restrictionsMultiplier,
// maxAllowedTPs,
// maxAllowedSLs,
// maxAllowedTrades,
// closeAllOpenTradesAt
// )
// ]
//
//
// [XNAME|XAUUSDb|M5|(ST_04:00_08:30),(TL_10:30_12:00),(NY_16:00_20:00)|25.0|5|(XTRADE_RESTRICATION_DAILY,1,0,2,0)]
input string eaSymbolConfiguration = "[XNAME|XAUUSDb|M5|(ST_04:00_08:30),(TL_10:30_12:00),(NY_16:00_20:00)|25.0|5|(XTRADE_RESTRICATION_DAILY,3,0,2,0)]"; // Symbol Configurations
//
// Management ...
input group "Management";
input bool eaAllowGuards = false; // Allow Guards
input bool eaAllowTrade = true; // Allow Trade on Signals
input bool eaAllowLongs = true; // Allow Long Trades
input bool eaAllowShorts = true; // Allow Short Trades
input double eaMaxAllowedDrawdownFactor = 0.3; // Max Allowed DrawDown for Trade
//
// Volume ...
input group "Volume";
input ENUM_X_VOLUME_SELECT_TYPE eaVolumeSelect = X_VOLUME_CONSTANT; // Volume Applying Type
input double eaStaticVoluem = 0.0; // Static Volume
input double eaDynamicVolumeStepBalance = 0.0; // Step of Balance for Increase Volume
input double eaDynamicVolumeStepVolume = X_MIN_VOLUME; // Step of Volume Increasing
input double eaConstantRiskBalance = 0.0; // Constant Risk Balance per Trade
input double eaConstantPercent = 1; // Constant Percent of Balance Per Trade
input double eaConstantBalance = 1000.0; // Constant Balance for Calculations
//
// Alert ...
input group "Alert";
input bool eaEnableAlerts = true; // Enable Alerts
input bool eaSaveAlerts = true; // Save Alerts
input bool eaLogAlerts = true; // Log Alerts
input bool eaMailAlerts = false; // Mail Alerts
input bool eaPushAlerts = true; // Push Alerts
input bool eaTerminalAlerts = false; // Terminal Alerts
//
// Reports ...
input group "Reports";
input bool eaReportNewMonths = false; // Report New Month
input bool eaReportNewWeeks = false; // Report New Weeks
input bool eaReportNewDays = true; // Report New Days
input bool eaReportNewHours = false; // Report New Hours
input bool eaReportTrades = true; // Report Trades
input bool eaReportSignals = true; // Report Signals
input bool eaReportRestrictions = true; // Report Restrictions
input bool eaReportProtector = true; // Report Protector Actions
input bool eaReportAfterTradesBalance = true; // Report Balance after a Trade Finished
//
// Collector ...
input group "Collector";
input bool eaSaveTrades = true; // Save Trades
input bool eaSaveSignals = true; // Save Signals
input bool eaSaveWins = true; // Save Winning Conditions
input bool eaSaveLosts = true; // Save Lost Conditions
input bool eaSaveRestrictions = true; // Save Restriction Reports
//
// Management Panel ...
input group "Management Panel";
input bool eaShowPanel = false; // Show Management Panel
double eaPanelAllowedTPSLStep = 10; // Value for Change TP/SL in Each Step
double eaPanelMinAllowedRiskInPoint = 20; // Min Allowed Risk in Point
double eaPanelRiskInPoint = 50; // Risk in Point per Trades
double eaPanelRiskToRewardRatio = 2.0; // Risk To Reward per Trades
double eaPanelVolume = X_MIN_VOLUME; // Default volume Per Trade
//
// Variables ...
//
XCBaseExpert *eaExpert;
//
// Event Handlers ...
/**
* Initialize EA Process ...
*
* @return ( int )
*/
int OnInit()
{
//
// Preparing Tags ...
string eaTag =
(IsValid(eaLogSuffix)
? eaLogSuffix + "_"
: "") +
ShortName;
//
// Validate Inputs and Required Parameters ...
// for EA to Works fine ...
if (!ValidateInputs())
{
return INIT_PARAMETERS_INCORRECT;
}
//
// Initialize Timer ...
if (!InitTimer())
{
return INIT_FAILED;
}
//
// Configure EA Expert Class ...
eaExpert = new XCBaseExpert();
//
// Setting All Inputs to Expert Adviser Class ...
//
// Common ...
eaExpert.eaMagicNumber = eaMagicNumber;
eaExpert.eaSlippage = eaSlippage;
eaExpert.eaLogSuffix = eaTag;
//
// Symbols ...
eaExpert.eaSymbolConfiguration = eaSymbolConfiguration;
//
// Management ...
eaExpert.eaAllowGuards = eaAllowGuards;
eaExpert.eaAllowTrade = eaAllowTrade;
eaExpert.eaAllowLongs = eaAllowLongs;
eaExpert.eaAllowShorts = eaAllowShorts;
eaExpert.eaMaxAllowedDrawdownFactor = eaMaxAllowedDrawdownFactor;
//
// Volume ...
eaExpert.eaVolumeSelect = eaVolumeSelect;
eaExpert.eaStaticVoluem = eaStaticVoluem;
eaExpert.eaDynamicVolumeStepBalance = eaDynamicVolumeStepBalance;
eaExpert.eaDynamicVolumeStepVolume = eaDynamicVolumeStepVolume;
eaExpert.eaConstantRiskBalance = eaConstantRiskBalance;
eaExpert.eaConstantPercent = eaConstantPercent;
eaExpert.eaConstantBalance = eaConstantBalance;
//
// Alert ...
eaExpert.eaEnableAlerts = eaEnableAlerts;
eaExpert.eaSaveAlerts = eaSaveAlerts;
eaExpert.eaLogAlerts = eaLogAlerts;
eaExpert.eaMailAlerts = eaMailAlerts;
eaExpert.eaPushAlerts = eaPushAlerts;
eaExpert.eaTerminalAlerts = eaTerminalAlerts;
//
// Reports ...
eaExpert.eaReportNewMonths = eaReportNewMonths;
eaExpert.eaReportNewWeeks = eaReportNewWeeks;
eaExpert.eaReportNewDays = eaReportNewDays;
eaExpert.eaReportNewHours = eaReportNewHours;
eaExpert.eaReportTrades = eaReportTrades;
eaExpert.eaReportSignals = eaReportSignals;
eaExpert.eaReportRestrictions = eaReportRestrictions;
eaExpert.eaReportProtector = eaReportProtector;
eaExpert.eaReportAfterTradesBalance = eaReportAfterTradesBalance;
//
// Collector ...
eaExpert.eaSaveTrades = eaSaveTrades;
eaExpert.eaSaveSignals = eaSaveSignals;
eaExpert.eaSaveWins = eaSaveWins;
eaExpert.eaSaveLosts = eaSaveLosts;
eaExpert.eaSaveRestrictions = eaSaveRestrictions;
//
// Management Panel ...
eaExpert.eaShowPanel = eaShowPanel;
eaExpert.eaPanelAllowedTPSLStep = eaPanelAllowedTPSLStep;
eaExpert.eaPanelMinAllowedRiskInPoint = eaPanelMinAllowedRiskInPoint;
eaExpert.eaPanelRiskInPoint = eaPanelRiskInPoint;
eaExpert.eaPanelRiskToRewardRatio = eaPanelRiskToRewardRatio;
eaExpert.eaPanelVolume = eaPanelVolume;
//
// Attach Event Handlers ...
eaExpert.AddOnSignalEventHandler(OnSignalTriggered);
eaExpert.onGuardedEventHandler = OnGuardedTriggered;
eaExpert.AddOnDealsChangedEventHandler(OnDealsChanged);
eaExpert.AddOnStopLossEventHandler(OnStopLossTriggered);
eaExpert.AddOnOrdersChangedEventHandler(OnOrdersChanged);
eaExpert.AddOnSignalExecutedEventHandler(OnSignalExecuted);
eaExpert.canAnalyseEventHandler = CanAnalyseEventTriggered;
eaExpert.AddOnTakeProfitEventHandler(OnTakeProfitTriggered);
eaExpert.checkForGuardEventHandler = CheckForGuardTriggered;
eaExpert.AddOnModifyPositionEventHandler(OnPositionModified);
eaExpert.AddOnPositionsChangedEventHandler(OnPositionsChanged);
eaExpert.AddOnTradeStateChangedEventHandler(OnTradeStateChanged);
eaExpert.AddOnForceClosePositionEventHandler(OnPositionForceClosed);
eaExpert.AddOnPartialClosePositionEventHandler(OnPositionPartialClosed);
//
// Try to Initialize eaExpert ...
bool isInited = eaExpert.HandleOnInit();
if (!isInited)
{
//
Print(ShortName, ": Initialization Failed ...");
return INIT_FAILED;
}
//
Print(ShortName, ": Initialized Successfully ...");
return INIT_SUCCEEDED;
}
/**
* De Initialize Expert ...
*
* @param reason: int, DeInitialization 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
*
*/
void OnDeinit(const int reason)
{
//
// Destroy Timer ...
// If Initialized ...
//
// De Init Expert Class Instance ...
eaExpert.HandleOnDeInit();
//
// Cleanup Resources ...
delete eaExpert;
ZeroMemory(eaExpert);
}
/**
* Handle Tick for Processing ...
*/
void OnTick()
{
eaExpert.HandleOnTick();
}
/**
* Handle On Trade Processing ...
*/
void OnTrade()
{
eaExpert.HandleOnTrade();
}
/**
* Handle On Timer Processing ...
*/
void OnTimer()
{
eaExpert.HandleOnTimer();
}
/**
* Handle On Chart Event Processing ...
* @param id: int, Specified Event ID ...
* @param lparam: long, type event parameter
* @param dparam: double, type event parameter
* @param sparam: string, type event parameter
*/
void OnChartEvent(
const int id,
const long &lparam,
const double &dparam,
const string &sparam //
)
{
eaExpert.HandleOnChartEvent(id, lparam, dparam, sparam);
}
//
// Event Listeners ...
/**
* Handle CanAnalyse Event Triggered ...
*
* @param symbol: Symbol ...
* @param period: Period ...
* @param time: Analysing Time ...
*
* @return ( bool )
*/
bool CanAnalyseEventTriggered(
string symbol,
ENUM_TIMEFRAMES period,
datetime time //
)
{
return eaExpert.HandleCanAnalyseEventTriggered(
symbol,
period,
time //
);
}
/**
* Check For Guard ...
*
* @param guards: XGuard, reference Collection to holds result ...
* @param positions: XPosition, refrence collection to Provides Positions ...
* @param barIndex: int, Specified Bar index ...
*
* @return ( int )
*/
int CheckForGuardTriggered(
XGuard &guards[],
XPosition &positions[],
int barIndex = 0 //
)
{
//
return eaExpert.CheckForGuardTriggered(
guards,
positions,
barIndex //
);
}
/**
* Handle Guard Events ...
*
* @param action: ENUM_X_GUARD_ACTIONS
* @param positions: XPosition[]
*/
void OnGuardedTriggered(
ENUM_X_GUARD_ACTIONS action,
XPosition &positions[] //
)
{
eaExpert.OnGuardedTriggered(action, positions);
}
/**
* Trigger OnSignal Event ...
*
* @param signal: XSignal
*/
void OnSignalTriggered(XSignal &signal)
{
eaExpert.HandleOnSignalTriggered(signal);
}
/**
* Trigger OnSignal Executed Event ...
*
* @param signal: XSignal
*/
void OnSignalExecuted(XSignal &signal)
{
eaExpert.HandleOnSignalExecuted(signal);
}
/**
* Handle StopLoss Triggered Positions ...
*
* @param deal: XDeal instance ...
*/
void OnStopLossTriggered(const XDeal &deal)
{
eaExpert.HandleOnStopLossTriggered(deal);
}
/**
* Handle Take Profit Triggered Positions ...
*
* @param deal: XDeal instance ...
*/
void OnTakeProfitTriggered(const XDeal &deal)
{
eaExpert.HandleOnTakeProfitTriggered(deal);
}
/**
* Handle Force Close a Position ...
*
* @param ticket: ULONG ...
* @param position: XPosition instance ...
* @param comment: String ...
*/
void OnPositionForceClosed(
const ulong ticket,
const XPosition &position,
const string comment //
)
{
//
eaExpert.HandleOnPositionForceClosed(
ticket,
position,
comment //
);
}
/**
* Handle Deals Changes ...
*
* @param count: Integer, Number of Changes ...
*/
void OnDealsChanged(int count)
{
eaExpert.HandleOnDealsChanged(count);
}
/**
* Handle Orders Changes ...
*
* @param count: Integer, Number of Changes ...
*/
void OnOrdersChanged(int count)
{
eaExpert.HandleOnOrdersChanged(count);
}
/**
* Handle Positions Changes ...
*
* @param count: Integer, Number of Changes ...
*/
void OnPositionsChanged(int count)
{
eaExpert.HandleOnPositionsChanged(count);
}
/**
* Handle Position Modified ...
*
* @param ticket: ulong, Position Ticket ...
* @param profit: double, Position Profit ...
* @param comment: string, Comment ...
*/
void OnPositionModified(
const ulong ticket,
const double profit,
const string comment //
)
{
//
eaExpert.HandleOnPositionModified(
ticket,
profit,
comment //
);
}
/**
* Handle Position Partial Closed ...
*
* @param ticket: ulong, Position Ticket ...
* @param profit: double, Position Profit ...
* @param comment: string, Comment ...
*/
void OnPositionPartialClosed(
const ulong ticket,
const double profit,
const string comment //
)
{
//
eaExpert.HandleOnPositionPartialClosed(
ticket,
profit,
comment //
);
}
/**
* Handle Trade State Changed ...
*
* @param state: XOnTradeHandlerState instance ...
*/
void OnTradeStateChanged(const XOnTradeHandlerState &state)
{
eaExpert.HandleOnTradeStateChanged(state);
}
//
// Custom Functions ...
/**
* Validate all Inputs of Expert Adviser ...
*
* @return ( bool )
*/
bool ValidateInputs()
{
//
bool result = false;
//
string errMessage = "";
//
bool isCommonValid = (
//
eaSlippage > 0 &&
eaMagicNumber > 0
//
);
if (!isCommonValid)
{
//
errMessage += "common configurations error;" + "\n";
}
//
result =
//
// Common ...
isCommonValid &&
//
// Otere ...
true
//
;
//
if (!result)
{
//
// Since here Logger not Initiallized, we Use Raw Print Command ...
Print(ShortName + " Errors: \n", errMessage);
}
//
return result;
}
/**
* Initialize Timer ...
*
* @return ( bool )
*/
bool InitTimer()
{
//
bool result = false;
//
// TODO: Initialize Timer if necessary ...
// result = EventSetTimer(1);
// result = EventSetMillisecondTimer(100);
result = true;
//
return result;
}
/**
* Destroy Timer ...
*/
void DestroyTimer()
{
//
// TODO: Use This ...
// EventKillTimer();
}
//
@@ -0,0 +1,636 @@
///////////////////////////////////////////////////////
//
// SaherElm IT Center MQL5 Expert Advisor
// -------------------------------------------------
// Name: X121XCATB
// Description: X121XCATB base Expert Advisor ...
//
// 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 icon "../Images/SaherElm_Logo_Color.ico"
#property description "SaherElm X121XCATB based Expert Advisor"
#property strict
//
#define ShortName "X121XCATBEA"
//
// Importts ...
#include "../XCATBEA/Classes/xcatbea.expert.class.mq5"
//
// Inputs ...
//
// Common ...
input group "Common";
input long eaMagicNumber = 1694056; // Magic Number
input int eaSlippage = 10; // Slippgae
input string eaLogSuffix = ""; // Log Suffix
//
// Detector ...
input group "Detector";
//
// Validating ...
input group "Validations";
input bool eaForceHasSwing = false; // Force Block to Has Propper Swing
input bool eaForceOBBarType = false; // Force Order Block to Has InDirectional Bars
input int eaMinRequiredOBBar = 0; // Min Required OB Bar
input bool eaForceFVGBarType = false; // Force Fair Value Gaps Bars Type
input int eaLiquidityLoopback = 0; // Liquidity Detection Loopback
input double eaMaxAllowedRange = 0.0; // Max Allowed Order Block Range
input double eaMinAllowedRange = 0.0; // Min Allowed Order Block Range
input bool eaForceHasFLiquidity = false; // Force Order Block To Has Reversal Liquidity
input bool eaForceHasRLiquidity = false; // Force Order Block to Has Following Liquidity
input bool eaValidateGapSequence = false; // Validate Fair Value Gaps Bar Sequences
input int eaMinAllowedBlockLength = 0; // Min Allowed Block Length
input bool eaValidateBlockEdgeBreakout = false; // Validate Order Block Edge Breakeout
//
// Filtering ...
input group "Filters";
input bool eaFilterBasedOnKI = false; // Filter Based On KI Flats
input bool eaFilterBasedOnPV = false; // Filter Based On PV
input int eaBosLoopback = 0; // PV Based Filtering BOS Lookup
input bool eaFilterBasedOnSar = false; // Filter Based On SAR
input bool eaForceSarSwitched = false; // SAR Switched on Sides for Filtering
input bool eaForceSarOnBothSide = false; // SAR Check on Both Sides for Filtering
input bool eaForceSarHasBreakout = false; // SAR Must Breakout
input bool eaForceSarHasReversalSide = false; // SAR Must Has Reversal Direction
input bool eaFilterBasedOnRSI = false; // Filter Based On RSI
input bool eaForceHasRSITrending = false; // RSI Must Has Trending
input bool eaForceHasRSIVPattern = false; // RSI Must Has V Pattern
input bool eaForceHasRSICrossing = false; // RSI Must Has Crossing Levels
input bool eaFilterBasedOnADX = false; // Filter Based On ADX
input bool eaForceHasADXTrending = false; // ADX Must Has Trending
input bool eaForceHasADXCrossing = false; // ADX Must Has Crossing +DI/-DI
input bool eaFilterBasedOnATR = false; // Filter Based On ATR
input bool eaForceHasATRTrending = false; // ATR Must Has Trending
input bool eaForceHasATRBreakout = false; // ATR Must Has Breakout
input bool eaFilterBasedOnTrend = false; // Filter Based On Trend
input bool eaForceHasTrendDir = false; // TREND Must Has Following Direction
input bool eaForceHasTrendPlace = false; // TREND Place Based Filtering
input bool eaForceHasTrendChange = false; // TREND Change Filtering
input bool eaForceHasTrendTrending = false; // TREND Must Has Trending
input bool eaForceHasTrendRejection = false; // TREND Line Must Rejected
input bool eaForceHasTrendLineInside = false; // TREND Line has Inside
input bool eaForceHasTrendDirOnBothSide = false; // TREND Must Has Following Direction in Both Side
input bool eaFilterBasedOnDelta = false; // Filter Based On Delta
input bool eaFilterBasedOnVolume = false; // Filter Based On Volume
input bool eaFilterBasedOnSignalBar = false; // Filter Based on Signal Bar
input bool eaFilterBasedOnHKSignalBar = false; // Filter Based On HK Signal Bar
//
// Signal ...
input group "Signal";
input int eaSignalR2R = 2; // Risk Reward Ratio
input double eaSLATRMultiplier = 0; // ATR Multiplier for SL
input bool eaAllowSignallingBasedOnConditions = false; // Signalling Based on Market Conditions
input bool eaAllowSignallingBasedOnTriggerBlocks = false; // Signalling Based on Trigger Blocks
input bool eaAllowSignallingBasedOnTriggerBlocksInsideOther = false; // Signalling Based on Trigger Blocks Seccond inputs
input bool eaSecondsTriggersSLUsingFirstTriggerBlock = true; // Use First Trigger Block for SL of Seconds Trigger Block Signalss
input bool eaApplyValidateAndFilterOnSelectInsideOthers = false; // Select Trigger Blocks by Applying Validations and Filterss
input bool eaAllowSignallingConditions1 = true; // Allow Market Conditions Signaller to Using Sar Signals
input bool eaAllowSignallingConditions2 = true; // Allow Market Conditions Signaller to Using Trend Signals
input bool eaAllowSignallingConditions3 = true; // Allow Market Conditions Signaller to Using Delta Signals
input bool eaAllowSignallingConditions4 = true; // Allow Market Conditions Signaller to Using Volume Signals
input bool eaAllowSignallingConditions5 = true; // Allow Market Conditions Signaller to Using Signal Bar Signals
input bool eaAllowSignallingConditions6 = true; // Allow Market Conditions Signaller to Using HK Signal Bar Signals
//
// Volume ...
input group "Volume";
input ENUM_X_VOLUME_SELECT_TYPE eaVolumeSelect = X_VOLUME_EQUITY; // Volume Applying Type
input double eaStaticVoluem = 0.0; // Static Volume
input double eaDynamicVolumeStepBalance = 0.0; // Step of Balance for Increase Volume
input double eaDynamicVolumeStepVolume = X_MIN_VOLUME; // Step of Volume Increasing
input double eaConstantRiskBalance = 0.0; // Constant Risk Balance per Trade
input double eaConstantPercent = 0.5; // Constant Percent of Balance Per Trade
input double eaConstantBalance = 0.0; // Constant Balance for Calculations
//
// Management ...
// eaSymbols => comma separated Symbols for Trading, use Default if not Provided ...
// eaSessions => (ST_04:00_08:30),(TL_10:30_12:00),(NY_16:00_20:00)
input group "Management";
input string eaSymbols = "XAUUSDb,XAGUSDb,EURUSDb,GBPUSDb,USDCHFb,USDJPYb,USDCADb,NZDUSDb,DowJones30"; // Allowed Trading Symbols
input bool eaAllowGuards = false; // Allow Guards
input bool eaAllowTrade = true; // Allow Trade on Signals
input bool eaAllowLongs = true; // Allow Long Trades
input bool eaAllowShorts = true; // Allow Short Trades
input string eaSessions = ""; // Active Sessions
input ENUM_XCATBEA_TRADE_RESTRICTION_PERIOD eaRestrictionsPeriod = XCATBEA_TRADE_RESTRICATION_NONE; // Restrictions Period
input int eaMaxAllowedTPs = 0; // Max Allowed TP(s) in Restrictions Period
input int eaMaxAllowedSLs = 0; // Max Allowed SL(s) in Restrictions Period
input int eaMaxAllowedTrades = 0; // Max Allowed Trades in Restrictions Period
input int eaMaxAllowedPositions = 5; // Max Allowed Same Time Trades
input double eaMaxAllowedSpread = 25; // Max Allowed Spread For Trade
input double eaMaxAllowedDrawdownFactor = 0.3; // Max Allowed DrawDown for Trade
input string eaCloseAllOpenTradesAt = ""; // Close All Open Trades per Day At Specified Time
//
// Alert ...
// Here we Provider All Requirements for
// Configuring Alert Provider ...
input group "Alert";
input bool eaEnableAlerts = true; // Enable Alerts
input bool eaSaveAlerts = true; // Save Alerts
input bool eaLogAlerts = true; // Log Alerts
input bool eaMailAlerts = false; // Mail Alerts
input bool eaPushAlerts = true; // Push Alerts
input bool eaTerminalAlerts = false; // Terminal Alerts
//
// Time Report ...
input group "Reports";
input bool eaReportNewMonths = false; // Report New Month
input bool eaReportNewWeeks = false; // Report New Weeks
input bool eaReportNewDays = true; // Report New Days
input bool eaReportNewHours = false; // Report New Hours
input bool eaReportTrades = true; // Report Trades
input bool eaReportSignals = true; // Report Signals
input bool eaReportRestrictions = true; // Report Restrictions
input bool eaReportProtector = true; // Report Protector Actions
input bool eaReportAfterTradesBalance = true; // Report Balance after a Trade Finished
//
// Collector ...
input group "Collector";
input bool eaSaveTrades = true; // Save Trades
input bool eaSaveSignals = true; // Save Signals
input bool eaSaveWins = true; // Save Winning Conditions
input bool eaSaveLosts = true; // Save Lost Conditions
input bool eaSaveRestrictions = true; // Save Restriction Reports
//
// Variables ...
//
XCXCATBEAExpert *eaExpert;
//
// Event Handlers ...
//
// Initialization ...
int OnInit()
{
//
// Preparing Tags ...
string eaTag =
(IsValid(eaLogSuffix)
? eaLogSuffix + "_"
: "") +
ShortName;
//
// Validate Inputs and Required Parameters
// for EA to Works fine ...
if (!ValidateInputs())
{
return INIT_PARAMETERS_INCORRECT;
}
//
// Initialize Timer ...
if (!InitTimer())
{
return INIT_FAILED;
}
//
// Configure EA Expert Class ...
eaExpert = new XCXCATBEAExpert();
//
// Setting All Inputs to Expert Adviser Class ...
//
// Common ...
eaExpert.eaLogSuffix = eaTag;
eaExpert.eaSlippage = eaSlippage;
eaExpert.eaMagicNumber = eaMagicNumber;
//
// Detector ...
//
// Validations ...
eaExpert.eaForceHasSwing = eaForceHasSwing;
eaExpert.eaForceOBBarType = eaForceOBBarType;
eaExpert.eaForceFVGBarType = eaForceFVGBarType;
eaExpert.eaMaxAllowedRange = eaMaxAllowedRange;
eaExpert.eaMinAllowedRange = eaMinAllowedRange;
eaExpert.eaMinRequiredOBBar = eaMinRequiredOBBar;
eaExpert.eaLiquidityLoopback = eaLiquidityLoopback;
eaExpert.eaForceHasFLiquidity = eaForceHasFLiquidity;
eaExpert.eaForceHasRLiquidity = eaForceHasRLiquidity;
eaExpert.eaValidateGapSequence = eaValidateGapSequence;
eaExpert.eaMinAllowedBlockLength = eaMinAllowedBlockLength;
eaExpert.eaValidateBlockEdgeBreakout = eaValidateBlockEdgeBreakout;
//
// Filters ...
eaExpert.eaBosLoopback = eaBosLoopback;
eaExpert.eaFilterBasedOnKI = eaFilterBasedOnKI;
eaExpert.eaFilterBasedOnPV = eaFilterBasedOnPV;
eaExpert.eaFilterBasedOnSar = eaFilterBasedOnSar;
eaExpert.eaFilterBasedOnRSI = eaFilterBasedOnRSI;
eaExpert.eaForceSarSwitched = eaForceSarSwitched;
eaExpert.eaFilterBasedOnADX = eaFilterBasedOnADX;
eaExpert.eaFilterBasedOnATR = eaFilterBasedOnATR;
eaExpert.eaForceHasTrendDir = eaForceHasTrendDir;
eaExpert.eaForceSarOnBothSide = eaForceSarOnBothSide;
eaExpert.eaFilterBasedOnTrend = eaFilterBasedOnTrend;
eaExpert.eaForceHasTrendPlace = eaForceHasTrendPlace;
eaExpert.eaFilterBasedOnDelta = eaFilterBasedOnDelta;
eaExpert.eaForceSarHasBreakout = eaForceSarHasBreakout;
eaExpert.eaForceHasRSITrending = eaForceHasRSITrending;
eaExpert.eaForceHasRSIVPattern = eaForceHasRSIVPattern;
eaExpert.eaForceHasRSICrossing = eaForceHasRSICrossing;
eaExpert.eaForceHasADXTrending = eaForceHasADXTrending;
eaExpert.eaForceHasADXCrossing = eaForceHasADXCrossing;
eaExpert.eaForceHasATRTrending = eaForceHasATRTrending;
eaExpert.eaForceHasATRBreakout = eaForceHasATRBreakout;
eaExpert.eaForceHasTrendChange = eaForceHasTrendChange;
eaExpert.eaFilterBasedOnVolume = eaFilterBasedOnVolume;
eaExpert.eaForceHasTrendTrending = eaForceHasTrendTrending;
eaExpert.eaForceHasTrendRejection = eaForceHasTrendRejection;
eaExpert.eaFilterBasedOnSignalBar = eaFilterBasedOnSignalBar;
eaExpert.eaForceSarHasReversalSide = eaForceSarHasReversalSide;
eaExpert.eaForceHasTrendLineInside = eaForceHasTrendLineInside;
eaExpert.eaFilterBasedOnHKSignalBar = eaFilterBasedOnHKSignalBar;
eaExpert.eaForceHasTrendDirOnBothSide = eaForceHasTrendDirOnBothSide;
//
// Signal ...
eaExpert.eaSignalR2R = eaSignalR2R;
eaExpert.eaSLATRMultiplier = eaSLATRMultiplier;
eaExpert.eaAllowSignallingBasedOnConditions = eaAllowSignallingBasedOnConditions;
eaExpert.eaAllowSignallingBasedOnTriggerBlocks = eaAllowSignallingBasedOnTriggerBlocks;
eaExpert.eaSecondsTriggersSLUsingFirstTriggerBlock = eaSecondsTriggersSLUsingFirstTriggerBlock;
eaExpert.eaApplyValidateAndFilterOnSelectInsideOthers = eaApplyValidateAndFilterOnSelectInsideOthers;
eaExpert.eaAllowSignallingBasedOnTriggerBlocksInsideOther = eaAllowSignallingBasedOnTriggerBlocksInsideOther;
eaExpert.eaAllowSignallingConditions1 = eaAllowSignallingConditions1;
eaExpert.eaAllowSignallingConditions2 = eaAllowSignallingConditions2;
eaExpert.eaAllowSignallingConditions3 = eaAllowSignallingConditions3;
eaExpert.eaAllowSignallingConditions4 = eaAllowSignallingConditions4;
eaExpert.eaAllowSignallingConditions5 = eaAllowSignallingConditions5;
eaExpert.eaAllowSignallingConditions6 = eaAllowSignallingConditions6;
//
// Volume ...
eaExpert.eaVolumeSelect = eaVolumeSelect;
eaExpert.eaStaticVoluem = eaStaticVoluem;
eaExpert.eaConstantPercent = eaConstantPercent;
eaExpert.eaConstantBalance = eaConstantBalance;
eaExpert.eaConstantRiskBalance = eaConstantRiskBalance;
eaExpert.eaDynamicVolumeStepVolume = eaDynamicVolumeStepVolume;
eaExpert.eaDynamicVolumeStepBalance = eaDynamicVolumeStepBalance;
//
// Management ...
eaExpert.eaSymbols = eaSymbols;
eaExpert.eaSessions = eaSessions;
eaExpert.eaAllowTrade = eaAllowTrade;
eaExpert.eaAllowLongs = eaAllowLongs;
eaExpert.eaAllowGuards = eaAllowGuards;
eaExpert.eaAllowShorts = eaAllowShorts;
eaExpert.eaMaxAllowedTPs = eaMaxAllowedTPs;
eaExpert.eaMaxAllowedSLs = eaMaxAllowedSLs;
eaExpert.eaMaxAllowedTrades = eaMaxAllowedTrades;
eaExpert.eaMaxAllowedSpread = eaMaxAllowedSpread;
eaExpert.eaRestrictionsPeriod = eaRestrictionsPeriod;
eaExpert.eaMaxAllowedPositions = eaMaxAllowedPositions;
eaExpert.eaCloseAllOpenTradesAt = eaCloseAllOpenTradesAt;
eaExpert.eaMaxAllowedDrawdownFactor = eaMaxAllowedDrawdownFactor;
//
// Alert ...
eaExpert.eaLogAlerts = eaLogAlerts;
eaExpert.eaMailAlerts = eaMailAlerts;
eaExpert.eaPushAlerts = eaPushAlerts;
eaExpert.eaSaveAlerts = eaSaveAlerts;
eaExpert.eaEnableAlerts = eaEnableAlerts;
eaExpert.eaTerminalAlerts = eaTerminalAlerts;
//
// Reports ...
eaExpert.eaReportTrades = eaReportTrades;
eaExpert.eaReportNewDays = eaReportNewDays;
eaExpert.eaReportSignals = eaReportSignals;
eaExpert.eaReportNewWeeks = eaReportNewWeeks;
eaExpert.eaReportNewHours = eaReportNewHours;
eaExpert.eaReportProtector = eaReportProtector;
eaExpert.eaReportNewMonths = eaReportNewMonths;
eaExpert.eaReportRestrictions = eaReportRestrictions;
eaExpert.eaReportAfterTradesBalance = eaReportAfterTradesBalance;
//
// Collector ...
eaExpert.eaSaveWins = eaSaveWins;
eaExpert.eaSaveLosts = eaSaveLosts;
eaExpert.eaSaveTrades = eaSaveTrades;
eaExpert.eaSaveSignals = eaSaveSignals;
eaExpert.eaSaveRestrictions = eaSaveRestrictions;
//
// Attach Event Handlers ...
eaExpert.AddOnDealsChangedEventHandler(OnDealsChanged);
eaExpert.AddOnStopLossEventHandler(OnStopLossTriggered);
eaExpert.AddOnOrdersChangedEventHandler(OnOrdersChanged);
eaExpert.AddOnTakeProfitEventHandler(OnTakeProfitTriggered);
eaExpert.AddOnModifyPositionEventHandler(OnPositionModified);
eaExpert.AddOnPositionsChangedEventHandler(OnPositionsChanged);
eaExpert.AddOnTradeStateChangedEventHandler(OnTradeStateChanged);
eaExpert.AddOnForceClosePositionEventHandler(OnPositionForceClosed);
eaExpert.AddOnPartialClosePositionEventHandler(OnPositionPartialClosed);
//
bool isInited = eaExpert.HandleOnInit();
if (!isInited)
{
return INIT_FAILED;
}
//
return INIT_SUCCEEDED;
}
//
// DeInitialization ...
void OnDeinit(const int reason)
{
//
// REASON_PROGRAM 0 The EA has stopped working calling the ExpertRemove() function
// REASON_REMOVE 1 Program removed from a chart
// REASON_RECOMPILE 2 Program recompiled
// REASON_CHARTCHANGE 3 A symbol or a chart period is changed
// REASON_CHARTCLOSE 4 Chart closed
// REASON_PARAMETERS 5 Inputs changed by a user
// REASON_ACCOUNT 6 Another account has been activated or reconnection to the trade server has occurred due to changes in the account settings
// REASON_TEMPLATE 7 Another chart template applied
// REASON_INITFAILED 8 The OnInit() handler returned a non-zero value
// REASON_CLOSE 9 Terminal closed
//
// Destroy Timer ...
eaExpert.HandleOnDeInit();
//
delete eaExpert;
ZeroMemory(eaExpert);
}
//
// On Tick Handler ...
void OnTick()
{
eaExpert.HandleOnTick();
}
//
// Handle On Trade Event ...
void OnTrade()
{
eaExpert.HandleOnTrade();
}
//
// On Timer ...
void OnTimer()
{
eaExpert.HandleOnTimer();
}
//
// Chart Event Handler ...
void OnChartEvent(
const int id,
const long &lparam,
const double &dparam,
const string &sparam //
)
{
eaExpert.HandleOnChartEvent(id, lparam, dparam, sparam);
}
//
// Event Listeners ...
/**
* Handle StopLoss Triggered Positions ...
*
* @param deal: XDeal instance ...
*/
void OnStopLossTriggered(const XDeal &deal)
{
eaExpert.HandleOnStopLossTriggered(deal);
}
/**
* Handle Take Profit Triggered Positions ...
*
* @param deal: XDeal instance ...
*/
void OnTakeProfitTriggered(const XDeal &deal)
{
eaExpert.HandleOnTakeProfitTriggered(deal);
}
/**
* Handle Force Close a Position ...
*
* @param ticket: ULONG ...
* @param position: XPosition instance ...
* @param comment: String ...
*/
void OnPositionForceClosed(
const ulong ticket,
const XPosition &position,
const string comment //
)
{
//
eaExpert.HandleOnPositionForceClosed(
ticket,
position,
comment //
);
}
/**
* Handle Deals Changes ...
*
* @param count: Integer, Number of Changes ...
*/
void OnDealsChanged(int count)
{
eaExpert.HandleOnDealsChanged(count);
}
/**
* Handle Orders Changes ...
*
* @param count: Integer, Number of Changes ...
*/
void OnOrdersChanged(int count)
{
eaExpert.HandleOnOrdersChanged(count);
}
/**
* Handle Positions Changes ...
*
* @param count: Integer, Number of Changes ...
*/
void OnPositionsChanged(int count)
{
eaExpert.HandleOnPositionsChanged(count);
}
/**
* Handle Position Modified ...
*
* @param ticket: ulong, Position Ticket ...
* @param profit: double, Position Profit ...
* @param comment: string, Comment ...
*/
void OnPositionModified(
const ulong ticket,
const double profit,
const string comment //
)
{
//
eaExpert.HandleOnPositionModified(
ticket,
profit,
comment //
);
}
/**
* Handle Position Partial Closed ...
*
* @param ticket: ulong, Position Ticket ...
* @param profit: double, Position Profit ...
* @param comment: string, Comment ...
*/
void OnPositionPartialClosed(
const ulong ticket,
const double profit,
const string comment //
)
{
//
eaExpert.HandleOnPositionPartialClosed(
ticket,
profit,
comment //
);
}
/**
* Handle Trade State Changed ...
*
* @param state: XOnTradeHandlerState instance ...
*/
void OnTradeStateChanged(const XOnTradeHandlerState &state)
{
eaExpert.HandleOnTradeStateChanged(state);
}
//
// Custom Functions ...
/**
* Validate all Inputs of Expert Adviser ...
*
* @return ( bool )
*/
bool ValidateInputs()
{
//
bool result = false;
//
string errMessage = "";
//
bool isCommonValid = (
//
eaSlippage > 0 &&
eaMagicNumber > 0
//
);
if (!isCommonValid)
{
//
errMessage += "common configurations error;" + "\n";
}
//
result =
//
// Common ...
isCommonValid &&
//
// Otere ...
true
//
;
//
if (!result)
{
//
// Since here Logger not Initiallized, we Use Raw Print Command ...
Print(ShortName + " Errors: \n", errMessage);
}
//
return result;
}
/**
* Initialize Timer ...
*
* @return ( bool )
*/
bool InitTimer()
{
//
bool result = false;
//
// TODO: Initialize Timer if necessary ...
// result = EventSetTimer(1);
// result = EventSetMillisecondTimer(100);
result = true;
//
return result;
}
/**
* Destroy Timer ...
*/
void DestroyTimer()
{
//
// TODO: Use This ...
// EventKillTimer();
}
//
@@ -0,0 +1,881 @@
///////////////////////////////////////////////////////
//
// SaherElm IT Center MQL5 Expert Advisor
// -------------------------------------------------
// Name: X121XKIEABackTester
// Description: Base Expert Advisor as Template ...
//
// 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 icon "../Images/SaherElm_Logo_Color.ico"
#property description "SaherElm XFIMA Expert Advisor"
#property strict
//
#define ShortName "X121XKIEABackTester"
//
// Importts ...
#include "../Classes/x-saherelm.x-backtester.expert.class.mq5"
#include "../X121XKIEA/Classes/x-saherelm.x121.xki.signaller.class.mq5"
// #region Inputs ...
// #region Commons ...
input group "Common";
input long eaMagicNumber = 78692110; // Magic Number
input int eaSlippage = 10; // Slippgae
input string eaLogSuffix = ""; // Log Suffix
// #endregion
// #region Volume ...
input group "Volume";
input ENUM_X_VOLUME_SELECT_TYPE eaVolumeSelect = X_VOLUME_CONSTANT; // Volume Applying Type
input double eaStaticVoluem = 0.0; // Static Volume
input double eaDynamicVolumeStepBalance = 0.0; // Step of Balance for Increase Volume
input double eaDynamicVolumeStepVolume = X_MIN_VOLUME; // Step of Volume Increasing
input double eaConstantRiskBalance = 0.0; // Constant Risk Balance per Trade
input double eaConstantPercent = 1; // Constant Percent of Balance Per Trade
input double eaConstantBalance = 1000.0; // Constant Balance for Calculations
// #endregion
// #region Alert ...
input group "Alert";
input bool eaEnableAlerts = true; // Enable Alerts
input bool eaLogAlerts = true; // Log Alerts
input bool eaMailAlerts = false; // Mail Alerts
input bool eaPushAlerts = false; // Push Alerts
input bool eaTerminalAlerts = false; // Terminal Alerts
// #endregion
// #region Configurations ...
input group "Configuration";
input bool eaProcessAllTicks = false; // Process All Ticks
input double eaSignallerR2R = 2.0; // Risk To Reward Ratio
input double eaSignallerVolume = 0.01; // Default Volume
input double eaSignallerRiskInPoint = 50; // Default Risk In Point
// #endregion
// #region Bar Time ...
input group "Bar Timer";
input int barTimeFontSize = 10; // Font Size
input string barTimeFont = "Arial"; // Font
input color barTimeColor = clrYellow; // Text Color
input ENUM_BASE_CORNER barTimeCorner = CORNER_RIGHT_LOWER; // Text Position
input bool showBars = true; // Show Bars
input bool showBarTime = true; // Show Bar Time
// #endregion
// #region Indicator Inputs ...
//
input group "Calculation";
input int kiFastLength = 26; // KI Fast Length
input int kiSlowLength = 104; // KI Slow Length
input int kiSuperSlowLength = 208; // KI Super Slow Length
input int maFastLength = 26; // MA Fast Length
input int maSlowLength = 104; // MA Slow Length
input int maSuperSlowLength = 208; // MA Super Slow Length
input ENUM_MA_METHOD maMethod = MODE_EMA; // MA Mode
input ENUM_APPLIED_PRICE maAppliedTo = PRICE_CLOSE; // MA Applied To
input int rsiLength = 14; // RSI Length
input ENUM_APPLIED_PRICE rsiAppliedTo = PRICE_CLOSE; // RSI Applied To
input int kiWaveSmoothingLength = 14; // RSI KI Wave Smoothing Length
input ENUM_X_MA_METHOD kiWaveSmoothingMode = X_MA_MODE_EMA; // RSI KI Wave Smoothing Method
input double rsiMultiplier = 0.5; // RSI Multiplier
input int atrLength = 14; // ATR Length
input double atrMultiplier = 2; // ATR Multiplier
input int atrSmoothingLength = 14; // ATR Smoothing Length
input ENUM_X_MA_METHOD atrSmoothingMode = X_MA_MODE_EMA; // ATR Smoothing Method
input ENUM_X_PRICE atrUpperPriceType = X_PRICE_HIGH; // ATR Upper Price Type
input ENUM_X_PRICE atrLowerPriceType = X_PRICE_LOW; // ATR Lower Price Type
//
// Presentation ...
input group "Presentation";
input bool showPV = true; // Show PV
input bool showKIFast = true; // Show KI Fast
input bool showKISlow = true; // Show KI Slow
input bool showKISuperSlow = true; // Show KI Super Slow
input bool showMaFast = true; // Show Ma Fast
input bool showMaSlow = true; // Show MA Slow
input bool showMaSuperSlow = true; // Show MA Super Slow
input bool showKIWave = true; // Show KI Wave
input bool showKIUpper = true; // Show KI Upper
input bool showKILower = true; // Show KI Lower
//
input int startCalculationForLastBars = 1500; // Calculate Last n Bars
// #endregion
// #endregion
// #region Local Variables ...
//
// Requirements ...
string eaLogTag; // EA Log Prefix ...
XCBackTesterEA *eaExpert; // EA Expert ...
//
// Registered Signallers ...
XCX121XKIStrategy1Signaller *signaller1; // XFIMA1 Signaller ...
//
XBarTracker eaBarTracker; // EA Bar Traker ...
//
// Registered Handlers ...
int eaCTHandler = INVALID_HANDLE; // Candle Timer Handler ...
int eaCCHandler = INVALID_HANDLE; // Candle Cleaner Handler ...
//
bool eaIsNewBar; // Check New Bar ...
//
ENUM_CHART_MODE eaBarMode = CHART_CANDLES;
//
color eaBarUpColor = clrLime;
color eaBarDownColor = clrRed;
color eaBarLineColor = clrLime;
color eaBarBearishColor = clrRed;
color eaBarBullishColor = clrLime;
color eaBarVolumesColor = clrGreen;
// #endregion
// #region Event Handlers ...
//
// Initialization ...
int OnInit()
{
//
// Preparing Tags ...
string eaTag =
(IsValid(eaLogSuffix)
? eaLogSuffix + "_"
: "") +
ShortName;
//
// Validate Inputs and Required Parameters
// for EA to Works fine ...
if (!ValidateInputs())
{
return INIT_PARAMETERS_INCORRECT;
}
//
// Initialize Timer ...
if (!InitTimer())
{
return INIT_FAILED;
}
//
// Configure EA Expert Class ...
eaExpert = new XCBackTesterEA();
//
// Symbol / Period ...
eaExpert.symbol = _Symbol;
eaExpert.period = _Period;
//
// Common ...
eaExpert.eaMagicNumber = eaMagicNumber;
eaExpert.eaSlippage = eaSlippage;
eaExpert.eaLogSuffix = eaTag;
//
// Volume ...
eaExpert.eaVolumeSelect = eaVolumeSelect;
eaExpert.eaStaticVoluem = eaStaticVoluem;
eaExpert.eaDynamicVolumeStepBalance = eaDynamicVolumeStepBalance;
eaExpert.eaDynamicVolumeStepVolume = eaDynamicVolumeStepVolume;
eaExpert.eaConstantRiskBalance = eaConstantRiskBalance;
eaExpert.eaConstantPercent = eaConstantPercent;
eaExpert.eaConstantBalance = eaConstantBalance;
//
// Alert ...
eaExpert.eaEnableAlerts = eaEnableAlerts;
eaExpert.eaLogAlerts = eaLogAlerts;
eaExpert.eaMailAlerts = eaMailAlerts;
eaExpert.eaPushAlerts = eaPushAlerts;
eaExpert.eaTerminalAlerts = eaTerminalAlerts;
//
// Attach Event Handlers ...
eaExpert.AddOnDealsChangedEventHandler(OnDealsChanged);
eaExpert.AddOnStopLossEventHandler(OnStopLossTriggered);
eaExpert.AddOnOrdersChangedEventHandler(OnOrdersChanged);
eaExpert.AddOnSignalExecutedEventHandler(OnSignalExecuted);
eaExpert.AddOnTakeProfitEventHandler(OnTakeProfitTriggered);
eaExpert.AddOnModifyPositionEventHandler(OnPositionModified);
eaExpert.AddOnPositionsChangedEventHandler(OnPositionsChanged);
eaExpert.AddOnTradeStateChangedEventHandler(OnTradeStateChanged);
eaExpert.AddOnForceClosePositionEventHandler(OnPositionForceClosed);
eaExpert.AddOnPartialClosePositionEventHandler(OnPositionPartialClosed);
//
// Configure Other Requirements ...
eaExpert.allowedTPSLStep = 10;
eaExpert.minAllowedRiskInPoint = 20;
eaExpert.volume = eaSignallerVolume;
eaExpert.riskToRewardRatio = eaSignallerR2R;
eaExpert.riskInPoint = eaSignallerRiskInPoint;
//
// Try to Initialize eaExpert ...
bool isInited = eaExpert.HandleOnInit();
if (!isInited)
{
//
Print(ShortName, ": Initialization Failed ...");
return INIT_FAILED;
}
//
// Here Instantiate Signaller Class ...
//
// Preparing Indicator Inputs ...
X121XKIInputs kiInputs;
//
// This is Default Configuration ...
kiInputs.Default();
kiInputs.Hide();
//
// Here we Attach Inputs to Indicator ...
kiInputs.kiFastLength = kiFastLength;
kiInputs.kiSlowLength = kiSlowLength;
kiInputs.kiSuperSlowLength = kiSuperSlowLength;
kiInputs.maFastLength = maFastLength;
kiInputs.maSlowLength = maSlowLength;
kiInputs.maSuperSlowLength = maSuperSlowLength;
kiInputs.maMethod = maMethod;
kiInputs.maAppliedTo = maAppliedTo;
kiInputs.rsiLength = rsiLength;
kiInputs.rsiAppliedTo = rsiAppliedTo;
kiInputs.kiWaveSmoothingLength = kiWaveSmoothingLength;
kiInputs.kiWaveSmoothingMode = kiWaveSmoothingMode;
kiInputs.rsiMultiplier = rsiMultiplier;
kiInputs.atrLength = atrLength;
kiInputs.atrMultiplier = atrMultiplier;
kiInputs.atrSmoothingLength = atrSmoothingLength;
kiInputs.atrSmoothingMode = atrSmoothingMode;
kiInputs.atrUpperPriceType = atrUpperPriceType;
kiInputs.atrLowerPriceType = atrLowerPriceType;
kiInputs.showPV = showPV;
kiInputs.showKIFast = showKIFast;
kiInputs.showKISlow = showKISlow;
kiInputs.showKISuperSlow = showKISuperSlow;
kiInputs.showMaFast = showMaFast;
kiInputs.showMaSlow = showMaSlow;
kiInputs.showMaSuperSlow = showMaSuperSlow;
kiInputs.showKIWave = showKIWave;
kiInputs.showKIUpper = showKIUpper;
kiInputs.showKILower = showKILower;
kiInputs.startCalculationForLastBars = startCalculationForLastBars;
//
// Instantiate Signaller ...
//
// X121XKI1 Signaller ...
signaller1 = new XCX121XKIStrategy1Signaller(
_Symbol,
_Period,
kiInputs,
eaProcessAllTicks, // Process All Ticks ...
eaSignallerR2R, // Signaller Risk to Reward Ratio ...
eaSignallerRiskInPoint, // Default Risk In Points ...
eaSignallerVolume // Defaul Volume ...
);
//
// Configure Signaller ...
signaller1.ignoreTargets = false;
signaller1.slAdditionDistance = 30;
signaller1.maxAllowedRiskDistance = 350;
signaller1.AddOnSignalEventHandler(OnSignalTriggered);
//
isInited =
signaller1.IsValid();
if (!isInited)
{
//
Print(ShortName, ": Initialization Failed ...");
return INIT_FAILED;
}
//
// Initialize Candle Timer Handler ...
eaCTHandler = iCustom(
_Symbol,
_Period,
"x-saherelm.x121.xct",
//
// Inputs ...
barTimeFontSize, // Font Size ...
barTimeFont, // Font ...
barTimeColor, // Text Color ...
barTimeCorner, // Text Position ...
//
// Presentation ...
"",
showBarTime // Show Candle Time
//
);
isInited = eaCTHandler != INVALID_HANDLE;
if (!isInited)
{
//
Print(ShortName, ": Initialization Failed ...");
return INIT_FAILED;
}
//
// Initialize Candle Cleaner Handler ...
eaCCHandler = iCustom(
_Symbol,
_Period,
"x-saherelm.x121.xcc",
//
// Inputs ...
//
// Chart Style ...
"",
eaBarMode, // Mode
eaBarUpColor, // Up Color
eaBarDownColor, // Down Color
eaBarLineColor, // Line mode and Doji candlestick Color
eaBarBullishColor, // Bearish Color
eaBarBearishColor, // Bullish Color
eaBarVolumesColor, // Volumes Color
//
// Presentation ...
"",
showBars // Show Candles
//
);
isInited = eaCCHandler != INVALID_HANDLE;
if (!isInited)
{
//
Print(ShortName, ": Initialization Failed ...");
return INIT_FAILED;
}
//
// Initialize Bar Tracker ...
isInited = eaBarTracker.Init(
_Symbol,
_Period //
);
if (!isInited)
{
//
Print(ShortName, ": Initialization Failed ...");
return INIT_FAILED;
}
//
// Configure XFIMA POI Detector / Drawer ...
// detectorConfig.Default();
// detectorConfig.FullDetect();
// marketStructureDrawerConfig.FullDraw();
//
// Ignoring Position Drawer ...
delete eaExpert.eaPositionDrawer;
ZeroMemory(eaExpert.eaPositionDrawer);
eaExpert.eaPositionDrawer = NULL;
//
Print(ShortName, ": Initialized Successfully ...");
return INIT_SUCCEEDED;
}
//
// DeInitialization ...
void OnDeinit(const int reason)
{
//
// REASON_PROGRAM 0 The EA has stopped working calling the ExpertRemove() function
// REASON_REMOVE 1 Program removed from a chart
// REASON_RECOMPILE 2 Program recompiled
// REASON_CHARTCHANGE 3 A symbol or a chart period is changed
// REASON_CHARTCLOSE 4 Chart closed
// REASON_PARAMETERS 5 Inputs changed by a user
// REASON_ACCOUNT 6 Another account has been activated or reconnection to the trade server has occurred due to changes in the account settings
// REASON_TEMPLATE 7 Another chart template applied
// REASON_INITFAILED 8 The OnInit() handler returned a non-zero value
// REASON_CLOSE 9 Terminal closed
//
// Destroy Timer ...
eaExpert.HandleOnDeInit();
//
// De Init Indicator ...
IndicatorRelease(eaCTHandler);
//
eaBarTracker.Clean();
//
delete signaller1;
ZeroMemory(signaller1);
//
delete eaExpert;
ZeroMemory(eaExpert);
}
//
// On Tick Handler ...
void OnTick()
{
//
eaIsNewBar = eaBarTracker.IsNewBar();
bool canProcess = eaProcessAllTicks
? true
: eaIsNewBar;
//
eaExpert.HandleOnTick();
//
if (!canProcess)
{
return;
}
//
// Bar Index ...
int barIndex = 0;
//
// Signallers Calling OnTick ...
signaller1.OnTick(barIndex);
//
// Checking For Guard only When has Position ...
XPosition positions[];
int positionsCount = eaExpert.eaTrader.GetPositions(
positions,
signaller1.symbol,
signaller1.name,
signaller1.period,
NULL, // All Types ...
true, // Filter By Magic ...
true // Force Clean ...
);
if (IsValidSize(positionsCount))
{
//
XGuard guards[];
int guardsCount = signaller1.CheckForGuard(
guards,
positions,
barIndex //
);
if (IsValidSize(guardsCount))
{
//
// Handling Guards ...
eaExpert.eaGuard.DoGuards(guards);
}
}
}
//
// Handle On Trade Event ...
void OnTrade()
{
eaExpert.HandleOnTrade();
}
//
// On Timer ...
void OnTimer()
{
eaExpert.HandleOnTimer();
}
//
// Chart Event Handler ...
void OnChartEvent(
const int id,
const long &lparam,
const double &dparam,
const string &sparam //
)
{
eaExpert.HandleOnChartEvent(id, lparam, dparam, sparam);
}
// #endregion
// #region Custom Event Handlers ...
/**
* Validate all Inputs of Expert Adviser ...
*
* @return ( bool )
*/
bool ValidateInputs()
{
//
bool result = false;
//
string errMessage = "";
//
bool isCommonValid = (
//
eaSlippage > 0 &&
eaMagicNumber > 0 &&
//
// Indicator Inputs ...
//
// KI ...
kiFastLength >= 5 &&
kiSlowLength > kiFastLength &&
//
// ATR ...
atrLength >= 5 &&
//
// RSI ...
rsiLength >= 5
//
//
);
if (!isCommonValid)
{
//
errMessage += "common configurations error;" + "\n";
}
//
result =
//
// Common ...
isCommonValid &&
//
// Otere ...
true
//
;
//
if (!result)
{
//
// Since here Logger not Initiallized, we Use Raw Print Command ...
Print(ShortName + " Errors: \n", errMessage);
}
//
return result;
}
/**
* Initialize Timer ...
*
* @return ( bool )
*/
bool InitTimer()
{
//
bool result = false;
//
// TODO: Initialize Timer if necessary ...
// result = EventSetTimer(1);
// result = EventSetMillisecondTimer(100);
result = true;
//
return result;
}
/**
* Destroy Timer ...
*/
void DestroyTimer()
{
//
// TODO: Use This ...
// EventKillTimer();
}
/**
* Trigger OnSignal Event ...
*
* @param signal: XSignal
*/
void OnSignalTriggered(XSignal &signal)
{
// //
// // Draw Signal on Chart ...
// XCSignalObject *iSignalObj;
// bool has = signaller1.poiDrawer.DrawSignal(
// signal,
// iSignalObj,
// 7 //
// );
//
eaExpert.HandleOnSignalTriggered(signal);
}
/**
* Trigger OnSignal Executed Event ...
*
* @param signal: XSignal
*/
void OnSignalExecuted(XSignal &signal)
{
eaExpert.HandleOnSignalExecuted(signal);
}
/**
* Check For Guard ...
*
* @param guards: XGuard, reference Collection to holds result ...
* @param positions: XPosition, refrence collection to Provides Positions ...
* @param barIndex: int, Specified Bar index ...
*
* @return ( int )
*/
int CheckForGuard(
XGuard &guards[],
XPosition &positions[],
int barIndex = 0 //
)
{
//
int result = signaller1.CheckForGuard(
guards,
positions,
barIndex //
);
//
return result;
}
//
// Trade Event Handlers ...
/**
* Handle StopLoss Triggered Positions ...
*
* @param deal: XDeal instance ...
*/
void OnStopLossTriggered(const XDeal &deal)
{
//
eaExpert.HandleOnStopLossTriggered(deal);
//
HandleBalanceReport();
HandleWinTrade(deal.positionId, deal.profit);
HandleLoseTrade(deal.positionId, deal.profit);
}
/**
* Handle Take Profit Triggered Positions ...
*
* @param deal: XDeal instance ...
*/
void OnTakeProfitTriggered(const XDeal &deal)
{
//
eaExpert.HandleOnTakeProfitTriggered(deal);
//
HandleBalanceReport();
HandleWinTrade(deal.positionId, deal.profit);
}
/**
* Handle Force Close a Position ...
*
* @param ticket: ULONG ...
* @param position: XPosition instance ...
* @param comment: String ...
*/
void OnPositionForceClosed(
const ulong ticket,
const XPosition &position,
const string comment //
)
{
//
eaExpert.HandleOnPositionForceClosed(
ticket,
position,
comment //
);
//
HandleBalanceReport();
HandleWinTrade(ticket, position.profit);
HandleLoseTrade(ticket, position.profit);
}
/**
* Handle Deals Changes ...
*
* @param count: Integer, Number of Changes ...
*/
void OnDealsChanged(int count)
{
eaExpert.HandleOnDealsChanged(count);
}
/**
* Handle Orders Changes ...
*
* @param count: Integer, Number of Changes ...
*/
void OnOrdersChanged(int count)
{
eaExpert.HandleOnOrdersChanged(count);
}
/**
* Handle Positions Changes ...
*
* @param count: Integer, Number of Changes ...
*/
void OnPositionsChanged(int count)
{
eaExpert.HandleOnPositionsChanged(count);
}
/**
* Handle Position Modified ...
*
* @param ticket: ulong, Position Ticket ...
* @param profit: double, Position Profit ...
* @param comment: string, Comment ...
*/
void OnPositionModified(
const ulong ticket,
const double profit,
const string comment //
)
{
//
eaExpert.HandleOnPositionModified(
ticket,
profit,
comment //
);
}
/**
* Handle Position Partial Closed ...
*
* @param ticket: ulong, Position Ticket ...
* @param profit: double, Position Profit ...
* @param comment: string, Comment ...
*/
void OnPositionPartialClosed(
const ulong ticket,
const double profit,
const string comment //
)
{
//
eaExpert.HandleOnPositionPartialClosed(
ticket,
profit,
comment //
);
}
/**
* Handle Trade State Changed ...
*
* @param state: XOnTradeHandlerState instance ...
*/
void OnTradeStateChanged(const XOnTradeHandlerState &state)
{
eaExpert.HandleOnTradeStateChanged(state);
}
/**
* Test Resting Signals ...
*
* @param ticket: ulong, Position Ticket ...
* @param profit: double, Position Profit ...
*/
void HandleLoseTrade(
ulong ticket = 0,
double profit = 0 //
)
{
//
// Check Position Loose ...
bool has = ticket > 0 &&
profit < 0;
if (!has)
{
return;
}
//
// NOTE: Here we Can Add Restrictions on Signaller based on our Requirements ...
// restingSignals: Specified Number of Signals which must to Ignore ...
// restUntil: Specified DateTime to Ignore all Signals before it Expiration ...
// restingDelay: Specified Bars Delay to Ignore all Signals before it passed ...
//
// Increase Resting Signals of Signallers ...
signaller1.LoseTrade();
}
/**
* Handle Win Trade ...
*
* @param ticket: ulong, Position Ticket ...
* @param profit: double, Position Profit ...
*/
void HandleWinTrade(
ulong ticket = 0,
double profit = 0 //
)
{
//
bool has = ticket > 0 &&
profit > 0;
if (!has)
{
return;
}
//
signaller1.WinTrade();
}
/**
* Handle Balance Report ...
*/
void HandleBalanceReport()
{
//
string message = eaExpert.eaTrader.mAccount.GetBalanceReportMessage();
eaExpert.eaAlert.SendAlert(message);
}
// #endregion
@@ -0,0 +1,965 @@
///////////////////////////////////////////////////////
//
// SaherElm IT Center XTest MQL5 Expert Advisor
// -------------------------------------------------
// Name: XBackTester
// Description: a Backtest Tools Strategy Tester
//
// Maintainer:
// ------------
// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com)
//
//////////////////////////////////////////////////////x
//
// Global Properties ...
#property copyright "Copyright 2023, SaherElm IT Center"
#property link "https://saherelm.ir"
#property version "1.00"
#property description "SaherElm XBackTester"
#property icon "../Images/SaherElm_Logo_Color.ico"
#property strict
//
#define ShortName "XBackTester"
//
// Imports ...
#include "../Classes/x-saherelm.x-backtester.expert.class.mq5"
#include "../XFIMAEA/Classes/x-saherelm.xfima.signaller.class.mq5"
//
// Definitions ...
//
// Inputs ...
//
// Common ...
input group "Common";
input long eaMagicNumber = 78692110; // Magic Number
input int eaSlippage = 10; // Slippgae
input string eaLogSuffix = ""; // Log Suffix
//
// Volume ...
input group "Volume";
input ENUM_X_VOLUME_SELECT_TYPE eaVolumeSelect = X_VOLUME_CONSTANT; // Volume Applying Type
input double eaStaticVoluem = 0.0; // Static Volume
input double eaDynamicVolumeStepBalance = 0.0; // Step of Balance for Increase Volume
input double eaDynamicVolumeStepVolume = X_MIN_VOLUME; // Step of Volume Increasing
input double eaConstantRiskBalance = 0.0; // Constant Risk Balance per Trade
input double eaConstantPercent = 1; // Constant Percent of Balance Per Trade
input double eaConstantBalance = 1000.0; // Constant Balance for Calculations
//
// Alert ...
// Here we Provider All Requirements for
// Configuring Alert Provider ...
input group "Alert";
input bool eaEnableAlerts = true; // Enable Alerts
input bool eaLogAlerts = true; // Log Alerts
input bool eaMailAlerts = false; // Mail Alerts
input bool eaPushAlerts = false; // Push Alerts
input bool eaTerminalAlerts = false; // Terminal Alerts
//
// Configurations ...
input group "Configuration";
input bool eaProcessAllTicks = false; // Process All Ticks
input double eaSignallerR2R = 2.0; // Risk To Reward Ratio
input double eaSignallerVolume = 0.01; // Default Volume
input double eaSignallerRiskInPoint = 50; // Default Risk In Point
//
// Indicator Inputs ...
//
input group "Calculation";
//
// Short ...
input ENUM_X_PERIOD_METHOD scMethod = X_PERIOD_AUTO; // How to Find Short Period
input ENUM_TIMEFRAMES scPeriod = NULL; // Short Period
//
// Medium ...
input ENUM_X_PERIOD_METHOD mcMethod = X_PERIOD_AUTO; // How to Find Medium Period
input ENUM_TIMEFRAMES mcPeriod = NULL; // Medium Period
//
// Long ...
input ENUM_X_PERIOD_METHOD lcMethod = X_PERIOD_AUTO; // How to Find Long Period
input ENUM_TIMEFRAMES lcPeriod = NULL; // Long Period
//
// Hind ...
input ENUM_X_PERIOD_METHOD hcMethod = X_PERIOD_AUTO; // How to Find Hind Period
input ENUM_TIMEFRAMES hcPeriod = NULL; // Hind Period
//
// PV ...
input ENUM_SERIESMODE upperMode = MODE_HIGH; // Peak Method
input ENUM_SERIESMODE lowerMode = MODE_LOW; // Vale Method
//
// Others ...
input ENUM_X_FIBO_LEVELS fiboUpperZoneLevel = X_FIBO_LEVEL_382; // Upper Zone Level
input ENUM_X_FIBO_LEVELS fiboMiddleZoneLevel = X_FIBO_LEVEL_500; // Middle Zone Level
input ENUM_X_FIBO_LEVELS fiboLowerZoneLevel = X_FIBO_LEVEL_618; // Lower Zone Level
input double sarStep = 0.02; // SAR Step
input double sarMax = 0.2; // SAR Maximum
input ENUM_MA_METHOD maMethod = MODE_EMA; // MA Method
input ENUM_APPLIED_PRICE maAppliedTo = PRICE_CLOSE; // MA Applied To
input int maFastLength = 7; // Fast MA Length
input int maSlowLength = 20; // Slow MA Length
input int maBandLength = 7; // MA Band Length
input int zigzagDepth = 12; // ZigZag Depth
input int zigzagDeviation = 5; // ZigZag Deviation
input int zigzagBackStep = 3; // ZigZag Back Step
input ENUM_X_PRICE zigzagUppersMode = X_PRICE_HIGH; // ZigZag High Detect Mode
input ENUM_X_PRICE zigzagLowersMode = X_PRICE_LOW; // ZigZag Low Detect Mode
input bool hkIgnoreShadows = true; // HK Remove noises
input int hkSmoothingLength = 21; // HK Smoothing Length
input ENUM_X_MA_METHOD hkSmoothingMode = X_MA_MODE_EMA; // HK Smoothing Method
input int atrLength = 14; // ATR Length
input double atrMultiplier = 1.5; // ATR Band Multiplier
input int atrSmoothingLength = 21; // ATR Smoothing Length
input ENUM_X_PRICE atrUpperPriceType = X_PRICE_HIGH; // ATR Upper Zone Applied To
input ENUM_X_PRICE atrLowerPriceType = X_PRICE_LOW; // ATR Lower Zone Applied To
input ENUM_X_MA_METHOD atrSmoothingMode = X_MA_MODE_EMA; // ATR Smoothing Method
//
input group "Bar Timer";
input int barTimeFontSize = 10; // Font Size
input string barTimeFont = "Arial"; // Font
input color barTimeColor = clrYellow; // Text Color
input ENUM_BASE_CORNER barTimeCorner = CORNER_RIGHT_LOWER; // Text Position
//
// Presentation ...
input group "Presentation";
input bool showPV = false; // Show PV
input bool showHK = false; // Show HK
input bool showSAR = false; // Show Sar
input bool showBars = true; // Show Bars
input bool showMAFast = false; // Show MA Fast
input bool showMASlow = false; // Show MA Slow
input bool showMABand = false; // Show MA Band
input bool showHKBand = false; // Show HK Band
input bool showATRBand = false; // Show ATR Band
input bool showBarTime = true; // Show Bar Time
input bool showZigZag = false; // Show ZigZag
input bool showCyclesMa = false; // Show Cycles MA
input bool showFiboZone = false; // Show Fibo Zone
//
input int startCalculationForLastBars = 1500; // Calculate Last n Bars
//
input int sarArrowCode = 159; // Parabolic Sar Arrow Code
input int peakArrowCode = 159; // Peaks Arrow Code
input int valeArrowCode = 159; // Vales Arrow Code
//
// Define Local Variables ...
//
// Requirements ...
string eaLogTag; // EA Log Prefix ...
XCBackTesterEA *eaExpert; // EA Expert ...
//
// Registered Signallers ...
XCXFIMAStrategy1Signaller *fima1Signaller; // XFIMA1 Signaller ...
//
XBarTracker eaBarTracker; // EA Bar Traker ...
//
// Registered Handlers ...
int eaCTHandler = INVALID_HANDLE; // Candle Timer Handler ...
int eaCCHandler = INVALID_HANDLE; // Candle Cleaner Handler ...
//
bool eaIsNewBar; // Check New Bar ...
//
ENUM_CHART_MODE eaBarMode = CHART_CANDLES;
//
color eaBarUpColor = clrLime;
color eaBarDownColor = clrRed;
color eaBarLineColor = clrLime;
color eaBarBearishColor = clrRed;
color eaBarBullishColor = clrLime;
color eaBarVolumesColor = clrGreen;
//
// Event Handlers ...
//
// Initialization ...
int OnInit()
{
//
// Preparing Tags ...
string eaTag =
(IsValid(eaLogSuffix)
? eaLogSuffix + "_"
: "") +
ShortName;
//
// Validate Inputs and Required Parameters
// for EA to Works fine ...
if (!ValidateInputs())
{
return INIT_PARAMETERS_INCORRECT;
}
//
// Initialize Timer ...
if (!InitTimer())
{
return INIT_FAILED;
}
//
// Configure EA Expert Class ...
eaExpert = new XCBackTesterEA();
//
// Symbol / Period ...
eaExpert.symbol = _Symbol;
eaExpert.period = _Period;
//
// Common ...
eaExpert.eaMagicNumber = eaMagicNumber;
eaExpert.eaSlippage = eaSlippage;
eaExpert.eaLogSuffix = eaTag;
//
// Volume ...
eaExpert.eaVolumeSelect = eaVolumeSelect;
eaExpert.eaStaticVoluem = eaStaticVoluem;
eaExpert.eaDynamicVolumeStepBalance = eaDynamicVolumeStepBalance;
eaExpert.eaDynamicVolumeStepVolume = eaDynamicVolumeStepVolume;
eaExpert.eaConstantRiskBalance = eaConstantRiskBalance;
eaExpert.eaConstantPercent = eaConstantPercent;
eaExpert.eaConstantBalance = eaConstantBalance;
//
// Alert ...
eaExpert.eaEnableAlerts = eaEnableAlerts;
eaExpert.eaLogAlerts = eaLogAlerts;
eaExpert.eaMailAlerts = eaMailAlerts;
eaExpert.eaPushAlerts = eaPushAlerts;
eaExpert.eaTerminalAlerts = eaTerminalAlerts;
//
// Attach Event Handlers ...
eaExpert.AddOnDealsChangedEventHandler(OnDealsChanged);
eaExpert.AddOnStopLossEventHandler(OnStopLossTriggered);
eaExpert.AddOnOrdersChangedEventHandler(OnOrdersChanged);
eaExpert.AddOnSignalExecutedEventHandler(OnSignalExecuted);
eaExpert.AddOnTakeProfitEventHandler(OnTakeProfitTriggered);
eaExpert.AddOnModifyPositionEventHandler(OnPositionModified);
eaExpert.AddOnPositionsChangedEventHandler(OnPositionsChanged);
eaExpert.AddOnTradeStateChangedEventHandler(OnTradeStateChanged);
eaExpert.AddOnForceClosePositionEventHandler(OnPositionForceClosed);
eaExpert.AddOnPartialClosePositionEventHandler(OnPositionPartialClosed);
//
// Configure Other Requirements ...
eaExpert.allowedTPSLStep = 10;
eaExpert.minAllowedRiskInPoint = 20;
eaExpert.volume = eaSignallerVolume;
eaExpert.riskToRewardRatio = eaSignallerR2R;
eaExpert.riskInPoint = eaSignallerRiskInPoint;
//
// Try to Initialize eaExpert ...
bool isInited = eaExpert.HandleOnInit();
if (!isInited)
{
//
Print(ShortName, ": Initialization Failed ...");
return INIT_FAILED;
}
//
// Here Instantiate Signaller Class ...
//
// Preparing Indicator Inputs ...
XFIMAInputs fimaInputs;
//
// This is Default Configuration ...
fimaInputs.Default();
fimaInputs.Hide();
//
// Here we Attach Inputs to Indicator ...
fimaInputs.scMethod = scMethod;
fimaInputs.scPeriod = scPeriod;
fimaInputs.mcMethod = mcMethod;
fimaInputs.mcPeriod = mcPeriod;
fimaInputs.lcMethod = lcMethod;
fimaInputs.lcPeriod = lcPeriod;
fimaInputs.hcMethod = hcMethod;
fimaInputs.hcPeriod = hcPeriod;
fimaInputs.upperMode = upperMode;
fimaInputs.lowerMode = lowerMode;
fimaInputs.fiboUpperZoneLevel = fiboUpperZoneLevel;
fimaInputs.fiboMiddleZoneLevel = fiboMiddleZoneLevel;
fimaInputs.fiboLowerZoneLevel = fiboLowerZoneLevel;
fimaInputs.sarStep = sarStep;
fimaInputs.sarMax = sarMax;
fimaInputs.maMethod = maMethod;
fimaInputs.maAppliedTo = maAppliedTo;
fimaInputs.maFastLength = maFastLength;
fimaInputs.maSlowLength = maSlowLength;
fimaInputs.maBandLength = maBandLength;
fimaInputs.zigzagDepth = zigzagDepth;
fimaInputs.zigzagDeviation = zigzagDeviation;
fimaInputs.zigzagBackStep = zigzagBackStep;
fimaInputs.zigzagUppersMode = zigzagUppersMode;
fimaInputs.zigzagLowersMode = zigzagLowersMode;
fimaInputs.hkIgnoreShadows = hkIgnoreShadows;
fimaInputs.hkSmoothingLength = hkSmoothingLength;
fimaInputs.hkSmoothingMode = hkSmoothingMode;
fimaInputs.atrLength = atrLength;
fimaInputs.atrMultiplier = atrMultiplier;
fimaInputs.atrSmoothingLength = atrSmoothingLength;
fimaInputs.atrUpperPriceType = atrUpperPriceType;
fimaInputs.atrLowerPriceType = atrLowerPriceType;
fimaInputs.atrSmoothingMode = atrSmoothingMode;
fimaInputs.showPV = showPV;
fimaInputs.showHK = showHK;
fimaInputs.showSAR = showSAR;
fimaInputs.showMAFast = showMAFast;
fimaInputs.showMASlow = showMASlow;
fimaInputs.showMABand = showMABand;
fimaInputs.showHKBand = showHKBand;
fimaInputs.showATRBand = showATRBand;
fimaInputs.showZigZag = showZigZag;
fimaInputs.showCyclesMa = showCyclesMa;
fimaInputs.showFiboZone = showFiboZone;
fimaInputs.startCalculationForLastBars = startCalculationForLastBars;
fimaInputs.sarArrowCode = sarArrowCode;
fimaInputs.peakArrowCode = peakArrowCode;
fimaInputs.valeArrowCode = valeArrowCode;
//
// Instantiate Signaller ...
//
// XFIMA1 Signaller ...
fima1Signaller = new XCXFIMAStrategy1Signaller(
_Symbol,
_Period,
fimaInputs,
eaProcessAllTicks, // Process All Ticks ...
eaSignallerR2R, // Signaller Risk to Reward Ratio ...
eaSignallerRiskInPoint, // Default Risk In Points ...
eaSignallerVolume // Defaul Volume ...
);
//
// Configure Signaller ...
fima1Signaller.ignoreTargets = false;
fima1Signaller.slAdditionDistance = 30;
fima1Signaller.maxAllowedRiskDistance = 350;
fima1Signaller.AddOnSignalEventHandler(OnSignalTriggered);
//
isInited =
fima1Signaller.IsValid();
if (!isInited)
{
//
Print(ShortName, ": Initialization Failed ...");
return INIT_FAILED;
}
//
// Initialize Candle Timer Handler ...
eaCTHandler = iCustom(
_Symbol,
_Period,
"x-saherelm.x121.xct",
//
// Inputs ...
barTimeFontSize, // Font Size ...
barTimeFont, // Font ...
barTimeColor, // Text Color ...
barTimeCorner, // Text Position ...
//
// Presentation ...
"",
showBarTime // Show Candle Time
//
);
isInited = eaCTHandler != INVALID_HANDLE;
if (!isInited)
{
//
Print(ShortName, ": Initialization Failed ...");
return INIT_FAILED;
}
//
// Initialize Candle Cleaner Handler ...
eaCCHandler = iCustom(
_Symbol,
_Period,
"x-saherelm.x121.xcc",
//
// Inputs ...
//
// Chart Style ...
"",
eaBarMode, // Mode
eaBarUpColor, // Up Color
eaBarDownColor, // Down Color
eaBarLineColor, // Line mode and Doji candlestick Color
eaBarBullishColor, // Bearish Color
eaBarBearishColor, // Bullish Color
eaBarVolumesColor, // Volumes Color
//
// Presentation ...
"",
showBars // Show Candles
//
);
isInited = eaCCHandler != INVALID_HANDLE;
if (!isInited)
{
//
Print(ShortName, ": Initialization Failed ...");
return INIT_FAILED;
}
//
// Initialize Bar Tracker ...
isInited = eaBarTracker.Init(
_Symbol,
_Period //
);
if (!isInited)
{
//
Print(ShortName, ": Initialization Failed ...");
return INIT_FAILED;
}
//
// Configure XFIMA POI Detector / Drawer ...
// detectorConfig.Default();
// detectorConfig.FullDetect();
// marketStructureDrawerConfig.FullDraw();
//
// Ignoring Position Drawer ...
delete eaExpert.eaPositionDrawer;
ZeroMemory(eaExpert.eaPositionDrawer);
eaExpert.eaPositionDrawer = NULL;
//
Print(ShortName, ": Initialized Successfully ...");
return INIT_SUCCEEDED;
}
//
// DeInitialization ...
void OnDeinit(const int reason)
{
//
// REASON_PROGRAM 0 The EA has stopped working calling the ExpertRemove() function
// REASON_REMOVE 1 Program removed from a chart
// REASON_RECOMPILE 2 Program recompiled
// REASON_CHARTCHANGE 3 A symbol or a chart period is changed
// REASON_CHARTCLOSE 4 Chart closed
// REASON_PARAMETERS 5 Inputs changed by a user
// REASON_ACCOUNT 6 Another account has been activated or reconnection to the trade server has occurred due to changes in the account settings
// REASON_TEMPLATE 7 Another chart template applied
// REASON_INITFAILED 8 The OnInit() handler returned a non-zero value
// REASON_CLOSE 9 Terminal closed
//
// Destroy Timer ...
eaExpert.HandleOnDeInit();
//
// De Init Indicator ...
IndicatorRelease(eaCTHandler);
//
eaBarTracker.Clean();
//
delete fima1Signaller;
ZeroMemory(fima1Signaller);
//
delete eaExpert;
ZeroMemory(eaExpert);
}
//
// On Tick Handler ...
void OnTick()
{
//
eaIsNewBar = eaBarTracker.IsNewBar();
bool canProcess = eaProcessAllTicks
? true
: eaIsNewBar;
//
eaExpert.HandleOnTick();
//
if (!canProcess)
{
return;
}
//
// Bar Index ...
int barIndex = 0;
//
// Signallers Calling OnTick ...
fima1Signaller.OnTick(barIndex);
//
// Checking For Guard only When has Position ...
XPosition positions[];
int positionsCount = eaExpert.eaTrader.GetPositions(
positions,
fima1Signaller.symbol,
fima1Signaller.name,
fima1Signaller.period,
NULL, // All Types ...
true, // Filter By Magic ...
true // Force Clean ...
);
if (IsValidSize(positionsCount))
{
//
XGuard guards[];
int guardsCount = fima1Signaller.CheckForGuard(
guards,
positions,
barIndex //
);
if (IsValidSize(guardsCount))
{
//
// Handling Guards ...
eaExpert.eaGuard.DoGuards(guards);
}
}
}
//
// Handle On Trade Event ...
void OnTrade()
{
eaExpert.HandleOnTrade();
}
//
// On Timer ...
void OnTimer()
{
eaExpert.HandleOnTimer();
}
//
// Chart Event Handler ...
void OnChartEvent(
const int id,
const long &lparam,
const double &dparam,
const string &sparam //
)
{
eaExpert.HandleOnChartEvent(id, lparam, dparam, sparam);
}
//
// Custom Functions ...
/**
* Validate all Inputs of Expert Adviser ...
*
* @return ( bool )
*/
bool ValidateInputs()
{
//
bool result = false;
//
string errMessage = "";
//
bool isCommonValid = (
//
eaSlippage > 0 &&
eaMagicNumber > 0 &&
//
// Indicator Inputs ...
//
// MA ...
maFastLength >= 2 &&
maSlowLength >= 2 &&
maSlowLength > maFastLength &&
//
// SAR ...
sarMax > 0 &&
sarStep > 0 &&
sarMax > sarStep &&
//
// CYCLES ...
(IsValid(scMethod, scPeriod) &&
IsValid(mcMethod, mcPeriod) &&
IsValid(lcMethod, lcPeriod) &&
IsValid(hcMethod, hcPeriod)) &&
//
// ZIGZAG ...
zigzagDepth > 0 &&
zigzagDeviation > 0 &&
zigzagBackStep > 0 &&
//
// Validate Upper Mode Detection ...
IsXValid(zigzagUppersMode) &&
//
// Validate Lower Mode Detection ...
IsXValid(zigzagLowersMode)
//
);
if (!isCommonValid)
{
//
errMessage += "common configurations error;" + "\n";
}
//
result =
//
// Common ...
isCommonValid &&
//
// Otere ...
true
//
;
//
if (!result)
{
//
// Since here Logger not Initiallized, we Use Raw Print Command ...
Print(ShortName + " Errors: \n", errMessage);
}
//
return result;
}
/**
* Initialize Timer ...
*
* @return ( bool )
*/
bool InitTimer()
{
//
bool result = false;
//
// TODO: Initialize Timer if necessary ...
// result = EventSetTimer(1);
// result = EventSetMillisecondTimer(100);
result = true;
//
return result;
}
/**
* Destroy Timer ...
*/
void DestroyTimer()
{
//
// TODO: Use This ...
// EventKillTimer();
}
/**
* Trigger OnSignal Event ...
*
* @param signal: XSignal
*/
void OnSignalTriggered(XSignal &signal)
{
// //
// // Draw Signal on Chart ...
// XCSignalObject *iSignalObj;
// bool has = fima1Signaller.poiDrawer.DrawSignal(
// signal,
// iSignalObj,
// 7 //
// );
//
eaExpert.HandleOnSignalTriggered(signal);
}
/**
* Trigger OnSignal Executed Event ...
*
* @param signal: XSignal
*/
void OnSignalExecuted(XSignal &signal)
{
eaExpert.HandleOnSignalExecuted(signal);
}
/**
* Check For Guard ...
*
* @param guards: XGuard, reference Collection to holds result ...
* @param positions: XPosition, refrence collection to Provides Positions ...
* @param barIndex: int, Specified Bar index ...
*
* @return ( int )
*/
int CheckForGuard(
XGuard &guards[],
XPosition &positions[],
int barIndex = 0 //
)
{
//
int result = fima1Signaller.CheckForGuard(
guards,
positions,
barIndex //
);
//
return result;
}
//
// Trade Event Handlers ...
/**
* Handle StopLoss Triggered Positions ...
*
* @param deal: XDeal instance ...
*/
void OnStopLossTriggered(const XDeal &deal)
{
//
eaExpert.HandleOnStopLossTriggered(deal);
//
HandleBalanceReport();
HandleWinTrade(deal.positionId, deal.profit);
HandleLoseTrade(deal.positionId, deal.profit);
}
/**
* Handle Take Profit Triggered Positions ...
*
* @param deal: XDeal instance ...
*/
void OnTakeProfitTriggered(const XDeal &deal)
{
//
eaExpert.HandleOnTakeProfitTriggered(deal);
//
HandleBalanceReport();
HandleWinTrade(deal.positionId, deal.profit);
}
/**
* Handle Force Close a Position ...
*
* @param ticket: ULONG ...
* @param position: XPosition instance ...
* @param comment: String ...
*/
void OnPositionForceClosed(
const ulong ticket,
const XPosition &position,
const string comment //
)
{
//
eaExpert.HandleOnPositionForceClosed(
ticket,
position,
comment //
);
//
HandleBalanceReport();
HandleWinTrade(ticket, position.profit);
HandleLoseTrade(ticket, position.profit);
}
/**
* Handle Deals Changes ...
*
* @param count: Integer, Number of Changes ...
*/
void OnDealsChanged(int count)
{
eaExpert.HandleOnDealsChanged(count);
}
/**
* Handle Orders Changes ...
*
* @param count: Integer, Number of Changes ...
*/
void OnOrdersChanged(int count)
{
eaExpert.HandleOnOrdersChanged(count);
}
/**
* Handle Positions Changes ...
*
* @param count: Integer, Number of Changes ...
*/
void OnPositionsChanged(int count)
{
eaExpert.HandleOnPositionsChanged(count);
}
/**
* Handle Position Modified ...
*
* @param ticket: ulong, Position Ticket ...
* @param profit: double, Position Profit ...
* @param comment: string, Comment ...
*/
void OnPositionModified(
const ulong ticket,
const double profit,
const string comment //
)
{
//
eaExpert.HandleOnPositionModified(
ticket,
profit,
comment //
);
}
/**
* Handle Position Partial Closed ...
*
* @param ticket: ulong, Position Ticket ...
* @param profit: double, Position Profit ...
* @param comment: string, Comment ...
*/
void OnPositionPartialClosed(
const ulong ticket,
const double profit,
const string comment //
)
{
//
eaExpert.HandleOnPositionPartialClosed(
ticket,
profit,
comment //
);
}
/**
* Handle Trade State Changed ...
*
* @param state: XOnTradeHandlerState instance ...
*/
void OnTradeStateChanged(const XOnTradeHandlerState &state)
{
eaExpert.HandleOnTradeStateChanged(state);
}
/**
* Test Resting Signals ...
*
* @param ticket: ulong, Position Ticket ...
* @param profit: double, Position Profit ...
*/
void HandleLoseTrade(
ulong ticket = 0,
double profit = 0 //
)
{
//
// Check Position Loose ...
bool has = ticket > 0 &&
profit < 0;
if (!has)
{
return;
}
//
// NOTE: Here we Can Add Restrictions on Signaller based on our Requirements ...
// restingSignals: Specified Number of Signals which must to Ignore ...
// restUntil: Specified DateTime to Ignore all Signals before it Expiration ...
// restingDelay: Specified Bars Delay to Ignore all Signals before it passed ...
//
// Increase Resting Signals of Signallers ...
fima1Signaller.LoseTrade();
}
/**
* Handle Win Trade ...
*
* @param ticket: ulong, Position Ticket ...
* @param profit: double, Position Profit ...
*/
void HandleWinTrade(
ulong ticket = 0,
double profit = 0 //
)
{
//
bool has = ticket > 0 &&
profit > 0;
if (!has)
{
return;
}
//
fima1Signaller.WinTrade();
}
/**
* Handle Balance Report ...
*/
void HandleBalanceReport()
{
//
string message = eaExpert.eaTrader.mAccount.GetBalanceReportMessage();
eaExpert.eaAlert.SendAlert(message);
}
//
@@ -0,0 +1,636 @@
///////////////////////////////////////////////////////
//
// SaherElm IT Center MQL5 Expert Advisor
// -------------------------------------------------
// Name: XFIMAEA
// Description: Base Expert Advisor as Template ...
//
// 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 icon "../Images/SaherElm_Logo_Color.ico"
#property description "SaherElm XFIMA Expert Advisor"
#property strict
//
#define ShortName "XFIMAEA"
//
// Importts ...
#include "../XFIMAEA/Classes/x-saherelm.xfima.expert.class.mq5"
//
// Inputs ...
//
// Common ...
input group "Common";
input long eaMagicNumber = 1694056; // Magic Number
input int eaSlippage = 10; // Slippgae
input string eaLogSuffix = ""; // Log Suffix
//
// Symbols
// [
// Name|
// Symbol|
// period|
// (ST_04:00_08:30),(TL_10:30_12:00),(NY_16:00_20:00)|
// maxAllowedSpread|
// maxAllowedPosition|
// (
// restrictionsPeriod,
// restrictionsMultiplier,
// maxAllowedTPs,
// maxAllowedSLs,
// maxAllowedTrades,
// closeAllOpenTradesAt
// )
// ]
//
//
// [XFIMA1|EURUSDb|M5||25.0|5|]
// [XFIMA1|XAUUSDb|M5|(ST_04:00_08:30),(TL_10:30_12:00),(NY_16:00_20:00)|25.0|5|(XTRADE_RESTRICATION_DAILY,1,0,2,0)]
// [XFIMA1|XAUUSDb|M5|(ST_04:00_08:30),(TL_10:30_12:00),(NY_16:00_20:00)|25.0|5|(XTRADE_RESTRICATION_DAILY,3,0,2,0)]
input string eaSymbolConfiguration = "[XFIMA1|EURUSDb|M15||25.0|5|]"; // Symbol Configurations
//
// Management ...
input group "Management";
input bool eaAllowGuards = false; // Allow Guards
input bool eaAllowTrade = true; // Allow Trade on Signals
input bool eaAllowLongs = true; // Allow Long Trades
input bool eaAllowShorts = true; // Allow Short Trades
input double eaMaxAllowedDrawdownFactor = 0.3; // Max Allowed DrawDown for Trade
//
// Volume ...
input group "Volume";
input ENUM_X_VOLUME_SELECT_TYPE eaVolumeSelect = X_VOLUME_CONSTANT; // Volume Applying Type
input double eaStaticVoluem = 0.0; // Static Volume
input double eaDynamicVolumeStepBalance = 0.0; // Step of Balance for Increase Volume
input double eaDynamicVolumeStepVolume = X_MIN_VOLUME; // Step of Volume Increasing
input double eaConstantRiskBalance = 0.0; // Constant Risk Balance per Trade
input double eaConstantPercent = 1; // Constant Percent of Balance Per Trade
input double eaConstantBalance = 1000.0; // Constant Balance for Calculations
//
// Alert ...
input group "Alert";
input bool eaEnableAlerts = true; // Enable Alerts
input bool eaSaveAlerts = true; // Save Alerts
input bool eaLogAlerts = true; // Log Alerts
input bool eaMailAlerts = false; // Mail Alerts
input bool eaPushAlerts = true; // Push Alerts
input bool eaTerminalAlerts = false; // Terminal Alerts
//
// Reports ...
input group "Reports";
input bool eaReportNewMonths = false; // Report New Month
input bool eaReportNewWeeks = false; // Report New Weeks
input bool eaReportNewDays = true; // Report New Days
input bool eaReportNewHours = false; // Report New Hours
input bool eaReportTrades = true; // Report Trades
input bool eaReportSignals = true; // Report Signals
input bool eaReportRestrictions = true; // Report Restrictions
input bool eaReportProtector = true; // Report Protector Actions
input bool eaReportAfterTradesBalance = true; // Report Balance after a Trade Finished
//
// Collector ...
input group "Collector";
input bool eaSaveTrades = true; // Save Trades
input bool eaSaveSignals = true; // Save Signals
input bool eaSaveWins = true; // Save Winning Conditions
input bool eaSaveLosts = true; // Save Lost Conditions
input bool eaSaveRestrictions = true; // Save Restriction Reports
//
// Management Panel ...
input group "Management Panel";
input bool eaShowPanel = false; // Show Management Panel
double eaPanelAllowedTPSLStep = 10; // Value for Change TP/SL in Each Step
double eaPanelMinAllowedRiskInPoint = 20; // Min Allowed Risk in Point
double eaPanelRiskInPoint = 50; // Risk in Point per Trades
double eaPanelRiskToRewardRatio = 2.0; // Risk To Reward per Trades
double eaPanelVolume = X_MIN_VOLUME; // Default volume Per Trade
//
// Variables ...
//
XCXFIMAExpret *eaExpert;
//
// Event Handlers ...
/**
* Initialize EA Process ...
*
* @return ( int )
*/
int OnInit()
{
//
// Preparing Tags ...
string eaTag =
(IsValid(eaLogSuffix)
? eaLogSuffix + "_"
: "") +
ShortName;
//
// Validate Inputs and Required Parameters ...
// for EA to Works fine ...
if (!ValidateInputs())
{
return INIT_PARAMETERS_INCORRECT;
}
//
// Initialize Timer ...
if (!InitTimer())
{
return INIT_FAILED;
}
//
// Configure EA Expert Class ...
eaExpert = new XCXFIMAExpret();
//
// Setting All Inputs to Expert Adviser Class ...
//
// Common ...
eaExpert.eaMagicNumber = eaMagicNumber;
eaExpert.eaSlippage = eaSlippage;
eaExpert.eaLogSuffix = eaTag;
//
// Symbols ...
eaExpert.eaSymbolConfiguration = eaSymbolConfiguration;
//
// Management ...
eaExpert.eaAllowGuards = eaAllowGuards;
eaExpert.eaAllowTrade = eaAllowTrade;
eaExpert.eaAllowLongs = eaAllowLongs;
eaExpert.eaAllowShorts = eaAllowShorts;
eaExpert.eaMaxAllowedDrawdownFactor = eaMaxAllowedDrawdownFactor;
//
// Volume ...
eaExpert.eaVolumeSelect = eaVolumeSelect;
eaExpert.eaStaticVoluem = eaStaticVoluem;
eaExpert.eaDynamicVolumeStepBalance = eaDynamicVolumeStepBalance;
eaExpert.eaDynamicVolumeStepVolume = eaDynamicVolumeStepVolume;
eaExpert.eaConstantRiskBalance = eaConstantRiskBalance;
eaExpert.eaConstantPercent = eaConstantPercent;
eaExpert.eaConstantBalance = eaConstantBalance;
//
// Alert ...
eaExpert.eaEnableAlerts = eaEnableAlerts;
eaExpert.eaSaveAlerts = eaSaveAlerts;
eaExpert.eaLogAlerts = eaLogAlerts;
eaExpert.eaMailAlerts = eaMailAlerts;
eaExpert.eaPushAlerts = eaPushAlerts;
eaExpert.eaTerminalAlerts = eaTerminalAlerts;
//
// Reports ...
eaExpert.eaReportNewMonths = eaReportNewMonths;
eaExpert.eaReportNewWeeks = eaReportNewWeeks;
eaExpert.eaReportNewDays = eaReportNewDays;
eaExpert.eaReportNewHours = eaReportNewHours;
eaExpert.eaReportTrades = eaReportTrades;
eaExpert.eaReportSignals = eaReportSignals;
eaExpert.eaReportRestrictions = eaReportRestrictions;
eaExpert.eaReportProtector = eaReportProtector;
eaExpert.eaReportAfterTradesBalance = eaReportAfterTradesBalance;
//
// Collector ...
eaExpert.eaSaveTrades = eaSaveTrades;
eaExpert.eaSaveSignals = eaSaveSignals;
eaExpert.eaSaveWins = eaSaveWins;
eaExpert.eaSaveLosts = eaSaveLosts;
eaExpert.eaSaveRestrictions = eaSaveRestrictions;
//
// Management Panel ...
eaExpert.eaShowPanel = eaShowPanel;
eaExpert.eaPanelAllowedTPSLStep = eaPanelAllowedTPSLStep;
eaExpert.eaPanelMinAllowedRiskInPoint = eaPanelMinAllowedRiskInPoint;
eaExpert.eaPanelRiskInPoint = eaPanelRiskInPoint;
eaExpert.eaPanelRiskToRewardRatio = eaPanelRiskToRewardRatio;
eaExpert.eaPanelVolume = eaPanelVolume;
//
// Attach Event Handlers ...
eaExpert.AddOnSignalEventHandler(OnSignalTriggered);
eaExpert.onGuardedEventHandler = OnGuardedTriggered;
eaExpert.AddOnDealsChangedEventHandler(OnDealsChanged);
eaExpert.AddOnStopLossEventHandler(OnStopLossTriggered);
eaExpert.AddOnOrdersChangedEventHandler(OnOrdersChanged);
eaExpert.canAnalyseEventHandler = CanAnalyseEventTriggered;
eaExpert.AddOnTakeProfitEventHandler(OnTakeProfitTriggered);
eaExpert.checkForGuardEventHandler = CheckForGuardTriggered;
eaExpert.AddOnModifyPositionEventHandler(OnPositionModified);
eaExpert.AddOnPositionsChangedEventHandler(OnPositionsChanged);
eaExpert.AddOnTradeStateChangedEventHandler(OnTradeStateChanged);
eaExpert.AddOnForceClosePositionEventHandler(OnPositionForceClosed);
eaExpert.AddOnPartialClosePositionEventHandler(OnPositionPartialClosed);
//
// TODO: Attach other Requirements if necessary ...
//
// Try to Initialize eaExpert ...
bool isInited = eaExpert.HandleOnInit();
if (!isInited)
{
//
Print(ShortName, ": Initialization Failed ...");
return INIT_FAILED;
}
//
Print(ShortName, ": Initialized Successfully ...");
return INIT_SUCCEEDED;
}
/**
* De Initialize Expert ...
*
* @param reason: int, DeInitialization 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
*
*/
void OnDeinit(const int reason)
{
//
// Destroy Timer ...
// If Initialized ...
//
// De Init Expert Class Instance ...
eaExpert.HandleOnDeInit();
//
// Cleanup Resources ...
delete eaExpert;
ZeroMemory(eaExpert);
}
/**
* Handle Tick for Processing ...
*/
void OnTick()
{
eaExpert.HandleOnTick();
}
/**
* Handle On Trade Processing ...
*/
void OnTrade()
{
eaExpert.HandleOnTrade();
}
/**
* Handle On Timer Processing ...
*/
void OnTimer()
{
eaExpert.HandleOnTimer();
}
/**
* Handle On Chart Event Processing ...
* @param id: int, Specified Event ID ...
* @param lparam: long, type event parameter
* @param dparam: double, type event parameter
* @param sparam: string, type event parameter
*/
void OnChartEvent(
const int id,
const long &lparam,
const double &dparam,
const string &sparam //
)
{
eaExpert.HandleOnChartEvent(id, lparam, dparam, sparam);
}
//
// Event Listeners ...
/**
* Handle CanAnalyse Event Triggered ...
*
* @param symbol: Symbol ...
* @param period: Period ...
* @param time: Analysing Time ...
*
* @return ( bool )
*/
bool CanAnalyseEventTriggered(
string symbol,
ENUM_TIMEFRAMES period,
datetime time //
)
{
//
return eaExpert.HandleCanAnalyseEventTriggered(
symbol,
period,
time //
);
}
/**
* Check For Guard ...
*
* @param guards: XGuard, reference Collection to holds result ...
* @param positions: XPosition, refrence collection to Provides Positions ...
* @param barIndex: int, Specified Bar index ...
*
* @return ( int )
*/
int CheckForGuardTriggered(
XGuard &guards[],
XPosition &positions[],
int barIndex = 0 //
)
{
//
return eaExpert.CheckForGuardTriggered(
guards,
positions,
barIndex //
);
}
/**
* Handle Guard Events ...
*
* @param action: ENUM_X_GUARD_ACTIONS
* @param positions: XPosition[]
*/
void OnGuardedTriggered(
ENUM_X_GUARD_ACTIONS action,
XPosition &positions[] //
)
{
eaExpert.OnGuardedTriggered(action, positions);
}
/**
* Trigger OnSignal Event ...
*
* @param signal: XSignal
*/
void OnSignalTriggered(XSignal &signal)
{
eaExpert.HandleOnSignalTriggered(signal);
}
/**
* Trigger OnSignal Executed Event ...
*
* @param signal: XSignal
*/
void OnSignalExecuted(XSignal &signal)
{
eaExpert.HandleOnSignalExecuted(signal);
}
/**
* Handle StopLoss Triggered Positions ...
*
* @param deal: XDeal instance ...
*/
void OnStopLossTriggered(const XDeal &deal)
{
eaExpert.HandleOnStopLossTriggered(deal);
}
/**
* Handle Take Profit Triggered Positions ...
*
* @param deal: XDeal instance ...
*/
void OnTakeProfitTriggered(const XDeal &deal)
{
eaExpert.HandleOnTakeProfitTriggered(deal);
}
/**
* Handle Force Close a Position ...
*
* @param ticket: ULONG ...
* @param position: XPosition instance ...
* @param comment: String ...
*/
void OnPositionForceClosed(
const ulong ticket,
const XPosition &position,
const string comment //
)
{
//
eaExpert.HandleOnPositionForceClosed(
ticket,
position,
comment //
);
}
/**
* Handle Deals Changes ...
*
* @param count: Integer, Number of Changes ...
*/
void OnDealsChanged(int count)
{
eaExpert.HandleOnDealsChanged(count);
}
/**
* Handle Orders Changes ...
*
* @param count: Integer, Number of Changes ...
*/
void OnOrdersChanged(int count)
{
eaExpert.HandleOnOrdersChanged(count);
}
/**
* Handle Positions Changes ...
*
* @param count: Integer, Number of Changes ...
*/
void OnPositionsChanged(int count)
{
eaExpert.HandleOnPositionsChanged(count);
}
/**
* Handle Position Modified ...
*
* @param ticket: ulong, Position Ticket ...
* @param profit: double, Position Profit ...
* @param comment: string, Comment ...
*/
void OnPositionModified(
const ulong ticket,
const double profit,
const string comment //
)
{
//
eaExpert.HandleOnPositionModified(
ticket,
profit,
comment //
);
}
/**
* Handle Position Partial Closed ...
*
* @param ticket: ulong, Position Ticket ...
* @param profit: double, Position Profit ...
* @param comment: string, Comment ...
*/
void OnPositionPartialClosed(
const ulong ticket,
const double profit,
const string comment //
)
{
//
eaExpert.HandleOnPositionPartialClosed(
ticket,
profit,
comment //
);
}
/**
* Handle Trade State Changed ...
*
* @param state: XOnTradeHandlerState instance ...
*/
void OnTradeStateChanged(const XOnTradeHandlerState &state)
{
eaExpert.HandleOnTradeStateChanged(state);
}
//
// Custom Functions ...
/**
* Validate all Inputs of Expert Adviser ...
*
* @return ( bool )
*/
bool ValidateInputs()
{
//
bool result = false;
//
string errMessage = "";
//
bool isCommonValid = (
//
eaSlippage > 0 &&
eaMagicNumber > 0
//
);
if (!isCommonValid)
{
//
errMessage += "common configurations error;" + "\n";
}
//
result =
//
// Common ...
isCommonValid &&
//
// Otere ...
true
//
;
//
if (!result)
{
//
// Since here Logger not Initiallized, we Use Raw Print Command ...
Print(ShortName + " Errors: \n", errMessage);
}
//
return result;
}
/**
* Initialize Timer ...
*
* @return ( bool )
*/
bool InitTimer()
{
//
bool result = false;
//
// TODO: Initialize Timer if necessary ...
// result = EventSetTimer(1);
// result = EventSetMillisecondTimer(100);
result = true;
//
return result;
}
/**
* Destroy Timer ...
*/
void DestroyTimer()
{
//
// TODO: Use This ...
// EventKillTimer();
}
//
@@ -0,0 +1,571 @@
///////////////////////////////////////////////////////
//
// SaherElm IT Center MQL5 Expert Advisor
// -------------------------------------------------
// Name: XOM1
// Description: XOM1 base Expert Advisor ...
//
// 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 icon "../Images/SaherElm_Logo_Color.ico"
#property description "SaherElm XOM1 based Expert Advisor"
#property strict
//
#define ShortName "XOM1EA"
//
// Importts ...
#include "../XOM1EA/Classes/xom1ea.expert.class.mq5"
//
// Inputs ...
//
// Common ...
input group "Common";
input long eaMagicNumber = 1694056; // Magic Number
input int eaSlippage = 10; // Slippgae
input string eaLogSuffix = ""; // Log Suffix
//
// Symbols
// [
// Symbol|
// period|
// (ST_04:00_08:30),(TL_10:30_12:00),(NY_16:00_20:00)|
// maxAllowedSpread|
// maxAllowedPosition|
// (
// restrictionsPeriod,
// restrictionsMultiplier,
// maxAllowedTPs,
// maxAllowedSLs,
// maxAllowedTrades,
// closeAllOpenTradesAt
// )
// ]
//
//
// [XAUUSDb|M5|(ST_04:00_08:30),(TL_10:30_12:00),(NY_16:00_20:00)|25.0|5|(XTRADE_RESTRICATION_DAILY,1,0,2,0)]
input string eaSymbolConfiguration = "[XAUUSDb|M5|(ST_04:00_08:30),(TL_10:30_12:00),(NY_16:00_20:00)|25.0|5|(XTRADE_RESTRICATION_DAILY,3,0,2,0)]"; // Symbol Configurations
//
// Management ...
input group "Management";
input bool eaAllowGuards = false; // Allow Guards
input bool eaAllowTrade = true; // Allow Trade on Signals
input bool eaAllowLongs = true; // Allow Long Trades
input bool eaAllowShorts = true; // Allow Short Trades
input double eaMaxAllowedDrawdownFactor = 0.3; // Max Allowed DrawDown for Trade
//
// Volume ...
input group "Volume";
input ENUM_X_VOLUME_SELECT_TYPE eaVolumeSelect = X_VOLUME_CONSTANT; // Volume Applying Type
input double eaStaticVoluem = 0.0; // Static Volume
input double eaDynamicVolumeStepBalance = 0.0; // Step of Balance for Increase Volume
input double eaDynamicVolumeStepVolume = X_MIN_VOLUME; // Step of Volume Increasing
input double eaConstantRiskBalance = 0.0; // Constant Risk Balance per Trade
input double eaConstantPercent = 1; // Constant Percent of Balance Per Trade
input double eaConstantBalance = 1000.0; // Constant Balance for Calculations
//
// Alert ...
input group "Alert";
input bool eaEnableAlerts = true; // Enable Alerts
input bool eaSaveAlerts = true; // Save Alerts
input bool eaLogAlerts = true; // Log Alerts
input bool eaMailAlerts = false; // Mail Alerts
input bool eaPushAlerts = true; // Push Alerts
input bool eaTerminalAlerts = false; // Terminal Alerts
//
// Reports ...
input group "Reports";
input bool eaReportNewMonths = false; // Report New Month
input bool eaReportNewWeeks = false; // Report New Weeks
input bool eaReportNewDays = true; // Report New Days
input bool eaReportNewHours = false; // Report New Hours
input bool eaReportTrades = true; // Report Trades
input bool eaReportSignals = true; // Report Signals
input bool eaReportRestrictions = true; // Report Restrictions
input bool eaReportProtector = true; // Report Protector Actions
input bool eaReportAfterTradesBalance = true; // Report Balance after a Trade Finished
//
// Collector ...
input group "Collector";
input bool eaSaveTrades = true; // Save Trades
input bool eaSaveSignals = true; // Save Signals
input bool eaSaveWins = true; // Save Winning Conditions
input bool eaSaveLosts = true; // Save Lost Conditions
input bool eaSaveRestrictions = true; // Save Restriction Reports
//
// Variables ...
//
XCXOM1EAExpert *eaExpert;
//
// Event Handlers ...
//
// Initialization ...
int OnInit()
{
//
// Preparing Tags ...
string eaTag =
(IsValid(eaLogSuffix)
? eaLogSuffix + "_"
: "") +
ShortName;
//
// Validate Inputs and Required Parameters ...
// for EA to Works fine ...
if (!ValidateInputs())
{
return INIT_PARAMETERS_INCORRECT;
}
//
// Initialize Timer ...
if (!InitTimer())
{
return INIT_FAILED;
}
//
// Configure EA Expert Class ...
eaExpert = new XCXOM1EAExpert();
//
// Setting All Inputs to Expert Adviser Class ...
//
// Common ...
eaExpert.eaMagicNumber = eaMagicNumber;
eaExpert.eaSlippage = eaSlippage;
eaExpert.eaLogSuffix = eaTag;
//
// Symbols ...
eaExpert.eaSymbolConfiguration = eaSymbolConfiguration;
//
// Management ...
eaExpert.eaAllowGuards = eaAllowGuards;
eaExpert.eaAllowTrade = eaAllowTrade;
eaExpert.eaAllowLongs = eaAllowLongs;
eaExpert.eaAllowShorts = eaAllowShorts;
eaExpert.eaMaxAllowedDrawdownFactor = eaMaxAllowedDrawdownFactor;
//
// Volume ...
eaExpert.eaVolumeSelect = eaVolumeSelect;
eaExpert.eaStaticVoluem = eaStaticVoluem;
eaExpert.eaDynamicVolumeStepBalance = eaDynamicVolumeStepBalance;
eaExpert.eaDynamicVolumeStepVolume = eaDynamicVolumeStepVolume;
eaExpert.eaConstantRiskBalance = eaConstantRiskBalance;
eaExpert.eaConstantPercent = eaConstantPercent;
eaExpert.eaConstantBalance = eaConstantBalance;
//
// Alert ...
eaExpert.eaEnableAlerts = eaEnableAlerts;
eaExpert.eaSaveAlerts = eaSaveAlerts;
eaExpert.eaLogAlerts = eaLogAlerts;
eaExpert.eaMailAlerts = eaMailAlerts;
eaExpert.eaPushAlerts = eaPushAlerts;
eaExpert.eaTerminalAlerts = eaTerminalAlerts;
//
// Reports ...
eaExpert.eaReportNewMonths = eaReportNewMonths;
eaExpert.eaReportNewWeeks = eaReportNewWeeks;
eaExpert.eaReportNewDays = eaReportNewDays;
eaExpert.eaReportNewHours = eaReportNewHours;
eaExpert.eaReportTrades = eaReportTrades;
eaExpert.eaReportSignals = eaReportSignals;
eaExpert.eaReportRestrictions = eaReportRestrictions;
eaExpert.eaReportProtector = eaReportProtector;
eaExpert.eaReportAfterTradesBalance = eaReportAfterTradesBalance;
//
// Collector ...
eaExpert.eaSaveTrades = eaSaveTrades;
eaExpert.eaSaveSignals = eaSaveSignals;
eaExpert.eaSaveWins = eaSaveWins;
eaExpert.eaSaveLosts = eaSaveLosts;
eaExpert.eaSaveRestrictions = eaSaveRestrictions;
//
// Attach Event Handlers ...
eaExpert.AddOnSignalEventHandler(OnSignalTriggered);
eaExpert.onGuardedEventHandler = OnGuardedTriggered;
eaExpert.AddOnDealsChangedEventHandler(OnDealsChanged);
eaExpert.AddOnStopLossEventHandler(OnStopLossTriggered);
eaExpert.AddOnOrdersChangedEventHandler(OnOrdersChanged);
eaExpert.canAnalyseEventHandler = CanAnalyseEventTriggered;
eaExpert.AddOnTakeProfitEventHandler(OnTakeProfitTriggered);
eaExpert.checkForGuardEventHandler = CheckForGuardTriggered;
eaExpert.AddOnModifyPositionEventHandler(OnPositionModified);
eaExpert.AddOnPositionsChangedEventHandler(OnPositionsChanged);
eaExpert.AddOnTradeStateChangedEventHandler(OnTradeStateChanged);
eaExpert.AddOnForceClosePositionEventHandler(OnPositionForceClosed);
eaExpert.AddOnPartialClosePositionEventHandler(OnPositionPartialClosed);
//
// Try to Initialize eaExpert ...
bool isInited = eaExpert.HandleOnInit();
if (!isInited)
{
//
Print(ShortName, ": Initialization Failed ...");
return INIT_FAILED;
}
//
Print(ShortName, ": Initialized Successfully ...");
return INIT_SUCCEEDED;
}
//
// DeInitialization ...
void OnDeinit(const int reason)
{
//
// REASON_PROGRAM 0 The EA has stopped working calling the ExpertRemove() function
// REASON_REMOVE 1 Program removed from a chart
// REASON_RECOMPILE 2 Program recompiled
// REASON_CHARTCHANGE 3 A symbol or a chart period is changed
// REASON_CHARTCLOSE 4 Chart closed
// REASON_PARAMETERS 5 Inputs changed by a user
// REASON_ACCOUNT 6 Another account has been activated or reconnection to the trade server has occurred due to changes in the account settings
// REASON_TEMPLATE 7 Another chart template applied
// REASON_INITFAILED 8 The OnInit() handler returned a non-zero value
// REASON_CLOSE 9 Terminal closed
//
// Destroy Timer ...
eaExpert.HandleOnDeInit();
//
delete eaExpert;
ZeroMemory(eaExpert);
}
//
// On Tick Handler ...
void OnTick()
{
eaExpert.HandleOnTick();
}
//
// Handle On Trade Event ...
void OnTrade()
{
eaExpert.HandleOnTrade();
}
//
// On Timer ...
void OnTimer()
{
eaExpert.HandleOnTimer();
}
//
// Chart Event Handler ...
void OnChartEvent(
const int id,
const long &lparam,
const double &dparam,
const string &sparam //
)
{
eaExpert.HandleOnChartEvent(id, lparam, dparam, sparam);
}
//
// Event Listeners ...
/**
* Handle CanAnalyse Event Triggered ...
*
* @param symbol: Symbol ...
* @param period: Period ...
* @param time: Analysing Time ...
*
* @return ( bool )
*/
bool CanAnalyseEventTriggered(
string symbol,
ENUM_TIMEFRAMES period,
datetime time //
)
{
return eaExpert.HandleCanAnalyseEventTriggered(
symbol,
period,
time //
);
}
/**
* Check For Guard Event Handler ...
*
* @param guards: XGuard[]
*
* @return ( int )
*/
int CheckForGuardTriggered(
XGuard &guards[],
XPosition &positions[],
int barIndex = 0 //
)
{
return eaExpert.CheckForGuardTriggered(guards);
}
/**
* Handle Guard Events ...
*
* @param action: ENUM_X_GUARD_ACTIONS
* @param positions: XPosition[]
*/
void OnGuardedTriggered(
ENUM_X_GUARD_ACTIONS action,
XPosition &positions[] //
)
{
eaExpert.OnGuardedTriggered(action, positions);
}
/**
* Trigger OnSignal Event ...
*
* @param signal: XSignal
*/
void OnSignalTriggered(XSignal &signal)
{
eaExpert.HandleOnSignalTriggered(signal);
}
/**
* Handle StopLoss Triggered Positions ...
*
* @param deal: XDeal instance ...
*/
void OnStopLossTriggered(const XDeal &deal)
{
eaExpert.HandleOnStopLossTriggered(deal);
}
/**
* Handle Take Profit Triggered Positions ...
*
* @param deal: XDeal instance ...
*/
void OnTakeProfitTriggered(const XDeal &deal)
{
eaExpert.HandleOnTakeProfitTriggered(deal);
}
/**
* Handle Force Close a Position ...
*
* @param ticket: ULONG ...
* @param position: XPosition instance ...
* @param comment: String ...
*/
void OnPositionForceClosed(
const ulong ticket,
const XPosition &position,
const string comment //
)
{
//
eaExpert.HandleOnPositionForceClosed(
ticket,
position,
comment //
);
}
/**
* Handle Deals Changes ...
*
* @param count: Integer, Number of Changes ...
*/
void OnDealsChanged(int count)
{
eaExpert.HandleOnDealsChanged(count);
}
/**
* Handle Orders Changes ...
*
* @param count: Integer, Number of Changes ...
*/
void OnOrdersChanged(int count)
{
eaExpert.HandleOnOrdersChanged(count);
}
/**
* Handle Positions Changes ...
*
* @param count: Integer, Number of Changes ...
*/
void OnPositionsChanged(int count)
{
eaExpert.HandleOnPositionsChanged(count);
}
/**
* Handle Position Modified ...
*
* @param ticket: ulong, Position Ticket ...
* @param profit: double, Position Profit ...
* @param comment: string, Comment ...
*/
void OnPositionModified(
const ulong ticket,
const double profit,
const string comment //
)
{
//
eaExpert.HandleOnPositionModified(
ticket,
profit,
comment //
);
}
/**
* Handle Position Partial Closed ...
*
* @param ticket: ulong, Position Ticket ...
* @param profit: double, Position Profit ...
* @param comment: string, Comment ...
*/
void OnPositionPartialClosed(
const ulong ticket,
const double profit,
const string comment //
)
{
//
eaExpert.HandleOnPositionPartialClosed(
ticket,
profit,
comment //
);
}
/**
* Handle Trade State Changed ...
*
* @param state: XOnTradeHandlerState instance ...
*/
void OnTradeStateChanged(const XOnTradeHandlerState &state)
{
eaExpert.HandleOnTradeStateChanged(state);
}
//
// Custom Functions ...
/**
* Validate all Inputs of Expert Adviser ...
*
* @return ( bool )
*/
bool ValidateInputs()
{
//
bool result = false;
//
string errMessage = "";
//
bool isCommonValid = (
//
eaSlippage > 0 &&
eaMagicNumber > 0
//
);
if (!isCommonValid)
{
//
errMessage += "common configurations error;" + "\n";
}
//
result =
//
// Common ...
isCommonValid &&
//
// Otere ...
true
//
;
//
if (!result)
{
//
// Since here Logger not Initiallized, we Use Raw Print Command ...
Print(ShortName + " Errors: \n", errMessage);
}
//
return result;
}
/**
* Initialize Timer ...
*
* @return ( bool )
*/
bool InitTimer()
{
//
bool result = false;
//
// TODO: Initialize Timer if necessary ...
// result = EventSetTimer(1);
// result = EventSetMillisecondTimer(100);
result = true;
//
return result;
}
/**
* Destroy Timer ...
*/
void DestroyTimer()
{
//
// TODO: Use This ...
// EventKillTimer();
}