do backup ...

This commit is contained in:
2025-04-23 05:10:52 +03:30
parent eedd7beaab
commit 91cc004c55
131 changed files with 172974 additions and 0 deletions
@@ -0,0 +1,431 @@
///////////////////////////////////////////////////////
//
// SaherElm IT Center XTest MQL5 Expert Advisor
// -------------------------------------------------
// Name: XRRToolsEA
// Description: a Template For Exper Advisors
//
// Maintainer:
// ------------
// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com)
//
//////////////////////////////////////////////////////x
//
// Global Properties ...
#property copyright "Copyright 2023, SaherElm IT Center"
#property link "https://saherelm.ir"
#property version "1.00"
#property description "SaherElm XRRToolsEA"
#property strict
//
#define ShortName "XRRTools"
//
// Imports ...
#include "../Classes/x-saherelm.x-alert.class.mq5"
#include "../Classes/x-saherelm.x-rm.panel.class.mq5"
#include "../Classes/x-saherelm.x-trade.class.mq5"
#include "../Helpers/x-saherelm.x121.xcc.helper.mq5"
#include "../Helpers/x-saherelm.x121.xct.helper.mq5"
//
// Inputs ...
//
// Common ...
input group "Common";
input long eaMagicNumber = 78692110; // Magic Number
input int eaSlippage = 10; // Slippgae
input string eaLogSuffix = ""; // Log Suffix
//
// Alert ...
// Here we Provider All Requirements for
// Configuring Alert Provider ...
input group "Alert";
input bool eAEnableAlerts = true; // Enable Alerts
input bool eALogAlerts = true; // Log Alerts
input bool eAMailAlerts = false; // Mail Alerts
input bool eAPushAlerts = false; // Push Alerts
input bool eATerminalAlerts = false; // Terminal Alerts
//
// Define Local Variables ...
//
string eaLogTag; // EA Log Prefix ...
XCAlert *eaAlert; // Alert Provider for Expert Adviser ...
XCTrade *eaTrader; // Trader of Expert Adviser ...
XCRMPanel eaMainWindow; // Main Window ...
XCX121XCTHelper *eaCTHelper; // Bar Timer Indicator Helper class ...
XCX121XCCHelper *eaCCHelper; // Chart Styler Indicator Helper Class ...
//
// Event Handlers ...
//
// Initialization ...
int OnInit()
{
//
// Validate Inputs and Required Parameters
// for EA to Works fine ...
if (!ValidateInputs())
{
return INIT_PARAMETERS_INCORRECT;
}
//
// Initialize Timer ...
if (!InitTimer())
{
return INIT_FAILED;
}
//
// Initialize all Requirements ...
if (!InitEA())
{
return INIT_FAILED;
}
//
// Initialize all GUI Objects and Classes ...
if (!InitGUI())
{
return INIT_FAILED;
}
//
// Alert Initialization ...
string msg = "Initialized Successfully ...";
eaAlert.Alert(msg);
//
// Init Succeed ...
return INIT_SUCCEEDED;
}
//
// DeInitialization ...
void OnDeinit(const int reason)
{
//
// REASON_PROGRAM 0 The EA has stopped working calling the ExpertRemove() function
// REASON_REMOVE 1 Program removed from a chart
// REASON_RECOMPILE 2 Program recompiled
// REASON_CHARTCHANGE 3 A symbol or a chart period is changed
// REASON_CHARTCLOSE 4 Chart closed
// REASON_PARAMETERS 5 Inputs changed by a user
// REASON_ACCOUNT 6 Another account has been activated or reconnection to the trade server has occurred due to changes in the account settings
// REASON_TEMPLATE 7 Another chart template applied
// REASON_INITFAILED 8 The OnInit() handler returned a non-zero value
// REASON_CLOSE 9 Terminal closed
//
// Destroy Timer ...
DestroyTimer();
//
// Destroy all GUI Requirements ...
DestroyGUI();
//
// Alert De Initialization Succeeded ...
string msg = "De Initialized Successfully ...";
eaAlert.Alert(msg);
//
// Destroy all EA Requirements ...
DestroyEA();
}
//
// On Tick Handler ...
void OnTick()
{
//
UpdateGUI();
}
//
// Handle On Trade Event ...
void OnTrade()
{
eaTrader.HandleOnTrade();
}
//
// On Timer ...
void OnTimer()
{
//
// TODO: Implement Time Based Functionalities ...
}
//
// Chart Event Handler ...
void OnChartEvent(
const int id,
const long &lparam,
const double &dparam,
const string &sparam //
)
{
//
// Apply Chart Event on Main Window ...
eaMainWindow.ChartEvent(id, lparam, dparam, sparam);
}
//
// Custom Event Handlers ...
/**
* Handle StopLoss Triggered Positions ...
*
* @param deal: XDeal ...
*/
void OnStopLossTriggered(const XDeal &deal)
{
}
/**
* Handle Take Profit Triggered Positions ...
*
* @param deal: XDeal ...
*/
void OnTakeProfitTriggered(const XDeal &deal)
{
}
/**
* Handle Force Close a Position ...
*
* @param ticket: Position Ticket ...
* @param position: XPosition ...
* @param comment: Closing Comment ...
*/
void OnPositionForceClosed(
const ulong ticket,
const XPosition &position,
const string comment //
)
{
}
//
// Custom Functions ...
/**
* Validate all Inputs of Expert Adviser ...
*
* @return ( bool )
*/
bool ValidateInputs()
{
//
bool result = false;
//
string errMessage = "";
//
bool isCommonValid = (
//
eaSlippage > 0 &&
eaMagicNumber > 0
//
);
if (!isCommonValid)
{
//
errMessage += "common configurations error;" + "\n";
}
//
result =
//
// Common ...
isCommonValid &&
//
// Otere ...
true
//
;
//
if (!result)
{
//
// Since here Logger not Initiallized, we Use Raw Print Command ...
Print(ShortName + " Errors: \n", errMessage);
}
//
return result;
}
/**
* Initialize Timer ...
*
* @return ( bool )
*/
bool InitTimer()
{
//
bool result = false;
//
// TODO: Initialize Timer if necessary ...
// result = EventSetTimer(1);
// result = EventSetMillisecondTimer(100);
result = true;
//
return result;
}
/**
* Destroy Timer ...
*/
void DestroyTimer()
{
//
// TODO: Use This ...
// EventKillTimer();
}
/**
* Initialize all Requirements for Working Fine ...
*
* @return ( bool )
*/
bool InitEA()
{
//
bool result = false;
//
// Locally Apply Changes on Prefix ...
eaLogTag = ShortName + ">" + eaLogSuffix;
//
// Bar Timer ...
X121XCTInputs ctInputs;
ctInputs.Default(); // Default Configurations ...
eaCTHelper = new XCX121XCTHelper();
result = eaCTHelper.Init(
_Symbol,
_Period,
ctInputs //
);
if (!result)
{
return result;
}
//
// Bar Styles ...
X121XCCInputs ccInputs;
ccInputs.Default(); // Default Configurations ...
eaCCHelper = new XCX121XCCHelper();
result = eaCCHelper.Init(
_Symbol,
_Period,
ccInputs //
);
if (!result)
{
return result;
}
//
// Create Instance of Alert Class and Configure it ...
eaAlert = new XCAlert();
eaAlert.SetPrefix(eaLogTag);
eaAlert.SetLogAlerts(eALogAlerts);
eaAlert.SetMailAlerts(eAMailAlerts);
eaAlert.SetPushAlerts(eAPushAlerts);
eaAlert.SetEnableAlerts(eAEnableAlerts);
eaAlert.SetTerminalAlerts(eATerminalAlerts);
//
// Create Trader Instance and Configure it ...
eaTrader = new XCTrade(
eaSlippage,
eaMagicNumber //
);
eaTrader.AddOnStopLossEventHandler(OnStopLossTriggered);
eaTrader.AddOnTakeProfitEventHandler(OnTakeProfitTriggered);
eaTrader.AddOnForceClosePositionEventHandler(OnPositionForceClosed);
//
return result;
}
/**
* Destroy all Initialized EA Requirements ...
*/
void DestroyEA()
{
//
delete eaCTHelper;
delete eaCCHelper;
//
delete eaAlert;
}
/**
* Initialize all GUI Requirements for EA ...
*
* @return ( bool )
*/
bool InitGUI()
{
//
bool result = false;
//
// Initialize Application Main Window ...
result = eaMainWindow.Create(
ChartID(),
ShortName, // Dialog Name ...
0, // SubWindow ...
10, // X1 ...
35, // Y1 ...
300, // X2 ...
200 // Y2 ...
);
//
// Try To Run Main Window ...
if (result)
{
eaMainWindow.Run();
}
//
return result;
}
/**
* Update GUI based on Each Ticks ...
*/
void UpdateGUI()
{
//
eaMainWindow.UpdateState();
}
/**
* Destroy all Initialized GUi Requirements ...
*/
void DestroyGUI()
{
//
eaMainWindow.Destroy();
}
//
@@ -0,0 +1,462 @@
///////////////////////////////////////////////////////
//
// SaherElm IT Center XTest MQL5 Expert Advisor
// -------------------------------------------------
// Name: X121SMCEA
// Description: an Exper Advisor which used Panels
//
// Maintainer:
// ------------
// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com)
//
//////////////////////////////////////////////////////
//
// Global Properties ...
#property copyright "Copyright 2023, SaherElm IT Center"
#property link "https://saherelm.ir"
#property version "1.00"
#property description "SaherElm X121SMCEA"
#property strict
//
#define ShortName "X121SMCEA"
//
// Imports ...
#include "../X121SMCEA/Experts/x-121.smc.expert.class.mq5"
//
// Inputs ...
//
// Common ...
input group "Common";
input long eaMagicNumber = 78692110; // Magic Number
input int eaSlippage = 10; // Slippgae
input string eaLogSuffix = ""; // Log Suffix
//
// Symbols ...
input group "Symbols";
input bool eaMultiSymbol = false; // Use Multi Symbol
input string eaSymbols = "EURUSDb,GBPUSDb,USDCHFb,USDJPYb"; // Trading Symbols
//
// Signalling ...
input group "Signalling";
input bool eaAllowLong = true; // Allow Long Signals
input bool eaAllowShort = true; // Allow Short Signals
input int eaMaxAllowedLongs = 5; // Max Allowed Long Signals
input int eaMaxAllowedShorts = 5; // Max Allowed Short Signals
input bool eaUseMaxAllowedSignalsPerSymbol = true; // Use Max Allowed Signal Types Per Symbol
input double eaLastPositionProfitForAcceptNextInPoint = 0; // Last Position Profit In Points for Accept new Signal
input int eaDelaysBetweenTwoSignalsInBar = 0; // Delay between two Signals in Bars
input double eaMaxAllowedSpread = 0; // Max Allowed Spread for Signalling
//
// Trade ...
input group "Trade";
input bool eaAllowTrade = true; // Allow Open Trade On Signals
input string eaStartTradeAt = ""; // Enable Trade on Signals on Time
input string eaStopTradeAt = ""; // Enable Trade on Signals on Time
input string eaCloseAllTradesAt = ""; // Enable Close All Trades on Signals on Time
//
// Risk Management ...
input group "Risk Management";
input double eaR2R = 6; // Signallers Risk to Reward Ratio
input double eaVolume = 0; // Static Volume
input double eaStaticBalance = 1000; // Static Balance
input double eaBalancePerTrade = 5; // Balance Used in Each Trade
input double eaRiskPercentPerBalance = 0; // Risk Percent Per Balance in Each Trade
input bool eaDynamicRiskManagement = false; // Dynamic Risk Management
input bool eaUseDynamicVolume = false; // Use Dynamic Volume
input double eaDynamicVolumeStep = 0.01; // Increase Volume Step
input double eaDynamicVolumeBalanceFactor = 200; // Balance Factor for Generate Dynamic Volume
input double eaMaxAllowedDrawdownToOpenTrades = 3; // Max Allowed Drawdown for Open Trades
input int eaMaxAllowedSLToPauseSignallingPerSymbol = 0; // Max Allowed SL for Pause Signalling Per Symbol
input int eaPauseSignallingAfterReachesMaxAllowedSLInSecconds = 0; // Pause Signalling Per Symbol afte Max Allowed SL Reached In Seconds
//
// Protection ...
input group "Protection";
input bool eaAllowHedging = false; // Allow Hedge Positions
input int eaMinOpenTradesFroHedging = 4; // Minimum Open Positions for Hedging
input double eaHedgingMinVolumeStep = 0.01; // Minimum Volume Step for Hedging
input double eaHedgeingMinRequiredProfitPerVolumeStep = 1.0; // Minimum Required Profit Per Volume Step for Hedging
//
// Alert ...
// Here we Provider All Requirements for
// Configuring Alert Provider ...
input group "Alert";
input bool eaEnableAlerts = true; // Enable Alerts
input bool eaLogAlerts = true; // Log Alerts
input bool eaMailAlerts = false; // Mail Alerts
input bool eaPushAlerts = false; // Push Alerts
input bool eaTerminalAlerts = false; // Terminal Alerts
//
// Time Report ...
input group "Reports";
input bool eaReportNewMonths = false; // Report New Month
input bool eaReportNewWeeks = false; // Report New Weeks
input bool eaReportNewDays = true; // Report New Days
input bool eaReportNewHours = false; // Report New Hours
//
// Define Local Variables ...
XC121SMCExpert *eaExpert;
//
// Event Handlers ...
//
// Initialization ...
int OnInit()
{
//
// Validate Inputs and Required Parameters
// for EA to Works fine ...
if (!ValidateInputs())
{
return INIT_PARAMETERS_INCORRECT;
}
//
// Initialize Timer ...
if (!InitTimer())
{
return INIT_FAILED;
}
//
// Configure EA Expert Class ...
eaExpert = new XC121SMCExpert();
//
// Event Handlers ...
eaExpert.OnSignalEventListener = OnSignalRecieved;
eaExpert.OnDealsChangedEventListener = OnDealsChanged;
eaExpert.OnOrdersChangedEventListener = OnOrdersChanged;
eaExpert.OnPositionSLEventListener = OnStopLossTriggered;
eaExpert.OnPositionTPEventListener = OnTakeProfitTriggered;
eaExpert.OnPositionsChangedEventListener = OnPositionsChanged;
eaExpert.OnPositionForceCloseEventListener = OnPositionForceClosed;
//
// Common ...
eaExpert.MagicNumber(eaMagicNumber);
eaExpert.Slippage(eaSlippage);
eaExpert.TagPrefix(eaLogSuffix);
//
// Symbol ...
eaExpert.SetSymbol(_Symbol);
eaExpert.SetPeriod(_Period);
eaExpert.Symbols(eaSymbols);
eaExpert.MultiSymbol(eaMultiSymbol);
//
// Signalling ...
eaExpert.AllowLong(eaAllowLong);
eaExpert.AllowShort(eaAllowShort);
eaExpert.MaxAllowedLongs(eaMaxAllowedLongs);
eaExpert.MaxAllowedShorts(eaMaxAllowedShorts);
eaExpert.UseMaxAllowedSignalsPerSymbol(eaUseMaxAllowedSignalsPerSymbol);
eaExpert.LastPositionProfitForAcceptNextInPoint(eaLastPositionProfitForAcceptNextInPoint);
eaExpert.DelaysBetweenTwoSignalsInBar(eaDelaysBetweenTwoSignalsInBar);
eaExpert.MaxAllowedSpread(eaMaxAllowedSpread);
//
// Trade ...
eaExpert.AllowTrade(eaAllowTrade);
eaExpert.StartTradeAt(eaStartTradeAt);
eaExpert.StopTradeAt(eaStopTradeAt);
eaExpert.CloseAllTradesAt(eaCloseAllTradesAt);
//
// Risk Management ...
eaExpert.R2R(eaR2R);
eaExpert.Volume(eaVolume);
eaExpert.StaticBalance(eaStaticBalance);
eaExpert.BalancePerTrade(eaBalancePerTrade);
eaExpert.RiskPercentPerBalance(eaRiskPercentPerBalance);
eaExpert.DynamicRiskManagement(eaDynamicRiskManagement);
eaExpert.UseDynamicVolume(eaUseDynamicVolume);
eaExpert.DynamicVolumeStep(eaDynamicVolumeStep);
eaExpert.DynamicVolumeBalanceFactor(eaDynamicVolumeBalanceFactor);
eaExpert.MaxAllowedDrawdownToOpenTrades(eaMaxAllowedDrawdownToOpenTrades);
eaExpert.MaxAllowedSLToPauseSignallingPerSymbol(eaMaxAllowedSLToPauseSignallingPerSymbol);
eaExpert.PauseSignallingAfterReachesMaxAllowedSLInSecconds(eaPauseSignallingAfterReachesMaxAllowedSLInSecconds);
//
// Protection ...
eaExpert.AllowHedging(eaAllowHedging);
eaExpert.MinOpenTradesFroHedging(eaMinOpenTradesFroHedging);
eaExpert.HedgingMinVolumeStep(eaHedgingMinVolumeStep);
eaExpert.HedgeingMinRequiredProfitPerVolumeStep(eaHedgeingMinRequiredProfitPerVolumeStep);
//
// Alert ...
eaExpert.SetAlertEnableAlerts(eaEnableAlerts);
eaExpert.SetAlertLogAlerts(eaLogAlerts);
eaExpert.SetAlertMailAlerts(eaMailAlerts);
eaExpert.SetAlertPushAlerts(eaPushAlerts);
eaExpert.SetAlertTerminalAlerts(eaTerminalAlerts);
//
// Reports ...
eaExpert.ReportNewMonths(eaReportNewMonths);
eaExpert.ReportNewWeeks(eaReportNewWeeks);
eaExpert.ReportNewDays(eaReportNewDays);
eaExpert.ReportNewHours(eaReportNewHours);
//
bool isInited = eaExpert.HandleOnInit();
if (!isInited)
{
return INIT_FAILED;
}
//
// Init Succeed ...
return INIT_SUCCEEDED;
}
//
// DeInitialization ...
void OnDeinit(const int reason)
{
//
// REASON_PROGRAM 0 The EA has stopped working calling the ExpertRemove() function
// REASON_REMOVE 1 Program removed from a chart
// REASON_RECOMPILE 2 Program recompiled
// REASON_CHARTCHANGE 3 A symbol or a chart period is changed
// REASON_CHARTCLOSE 4 Chart closed
// REASON_PARAMETERS 5 Inputs changed by a user
// REASON_ACCOUNT 6 Another account has been activated or reconnection to the trade server has occurred due to changes in the account settings
// REASON_TEMPLATE 7 Another chart template applied
// REASON_INITFAILED 8 The OnInit() handler returned a non-zero value
// REASON_CLOSE 9 Terminal closed
//
// Destroy Timer ...
eaExpert.HandleOnDeInit();
//
delete eaExpert;
//
ZeroMemory(eaExpert);
}
//
// On Tick Handler ...
void OnTick()
{
eaExpert.HandleOnTick();
}
//
// Handle On Trade Event ...
void OnTrade()
{
eaExpert.HandleOnTrade();
}
//
// On Timer ...
void OnTimer()
{
eaExpert.HandleOnTimer();
}
//
// Chart Event Handler ...
void OnChartEvent(
const int id,
const long &lparam,
const double &dparam,
const string &sparam //
)
{
eaExpert.HandleOnChartEvent(id, lparam, dparam, sparam);
}
//
// Event Listeners ...
/**
* Do What we Want by Specific Signal ...
*
* @param signal: XSignal instance ...
* @param conditions: XStrategyConditions instance ...
*/
void OnSignalRecieved(
XSignal &signal,
X121SMCStrategyConditions &conditions //
)
{
//
eaExpert.HandleOnSignalRecieved(
signal,
conditions //
);
}
/**
* Handle StopLoss Triggered Positions ...
*
* @param deal: XDeal instance ...
*/
void OnStopLossTriggered(const XDeal &deal)
{
eaExpert.HandleOnStopLossTriggered(deal);
}
/**
* Handle Take Profit Triggered Positions ...
*
* @param deal: XDeal instance ...
*/
void OnTakeProfitTriggered(const XDeal &deal)
{
eaExpert.HandleOnTakeProfitTriggered(deal);
}
/**
* Handle Force Close a Position ...
*
* @param ticket: ULONG ...
* @param position: XPosition instance ...
* @param comment: String ...
*/
void OnPositionForceClosed(
const ulong ticket,
const XPosition &position,
const string comment //
)
{
//
eaExpert.HandleOnPositionForceClosed(
ticket,
position,
comment //
);
}
/**
* Handle Deals Changes ...
*
* @param count: Integer, Number of Changes ...
*/
void OnDealsChanged(int count)
{
eaExpert.HandleOnDealsChanged(count);
}
/**
* Handle Orders Changes ...
*
* @param count: Integer, Number of Changes ...
*/
void OnOrdersChanged(int count)
{
eaExpert.HandleOnOrdersChanged(count);
}
/**
* Handle Positions Changes ...
*
* @param count: Integer, Number of Changes ...
*/
void OnPositionsChanged(int count)
{
eaExpert.HandleOnPositionsChanged(count);
}
//
// Custom Functions ...
/**
* Validate all Inputs of Expert Adviser ...
*
* @return ( bool )
*/
bool ValidateInputs()
{
//
bool result = false;
//
string errMessage = "";
//
bool isCommonValid = (
//
eaSlippage > 0 &&
eaMagicNumber > 0
//
);
if (!isCommonValid)
{
//
errMessage += "common configurations error;" + "\n";
}
//
result =
//
// Common ...
isCommonValid &&
//
// Otere ...
true
//
;
//
if (!result)
{
//
// Since here Logger not Initiallized, we Use Raw Print Command ...
Print(ShortName + " Errors: \n", errMessage);
}
//
return result;
}
/**
* Initialize Timer ...
*
* @return ( bool )
*/
bool InitTimer()
{
//
bool result = false;
//
// TODO: Initialize Timer if necessary ...
// result = EventSetTimer(1);
// result = EventSetMillisecondTimer(100);
result = true;
//
return result;
}
/**
* Destroy Timer ...
*/
void DestroyTimer()
{
//
// TODO: Use This ...
// EventKillTimer();
}
//
@@ -0,0 +1,624 @@
///////////////////////////////////////////////////////
//
// SaherElm IT Center XTest MQL5 Expert Advisor
// -------------------------------------------------
// Name: XCAEA
// Description: an Exper Advisor which used Panels
//
// Maintainer:
// ------------
// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com)
//
//////////////////////////////////////////////////////
//
// Global Properties ...
#property copyright "Copyright 2023, SaherElm IT Center"
#property link "https://saherelm.ir"
#property version "1.00"
#property description "SaherElm XCAEA EA"
#property strict
//
// Imports ...
#include "../Classes/x-saherelm.x-alert.class.mq5"
#include "../Classes/x-saherelm.x-trade.class.mq5"
#include "../Classes/x-saherelm.x-volume.class.mq5"
#include "../XCAEA/Classes/xcaea.x-trade.manager.class.mq5"
#include "../XCAEA/Signals/xcaea.signaller.class.mq5"
//
#define ShortName "XCAEAEA"
//
// Inputs ...
//
// Common ...
input group "Common";
input long eaMagicNumber = 78692110; // Magic Number
input int eaSlippage = 10; // Slippgae
input string eaLogSuffix = ""; // Log Suffix
//
// Volume ...
input group "Volume";
input ENUM_X_VOLUME_SELECT_TYPE eaVolumeSelect = X_VOLUME_EQUITY; // Volume Applying Type
input double eaStaticVoluem = 0.0; // Static Volume
input double eaDynamicVolumeStepBalance = 0.0; // Step of Balance for Increase Volume
input double eaDynamicVolumeStepVolume = X_MIN_VOLUME; // Step of Volume Increasing
input double eaConstantRiskBalance = 0.0; // Constant Risk Balance per Trade
input double eaConstantPercent = 0.5; // Constant Percent of Balance Per Trade
input double eaConstantBalance = 0.0; // Constant Balance for Calculations
//
// Alert ...
// Here we Provider All Requirements for
// Configuring Alert Provider ...
input group "Alert";
input bool eaEnableAlerts = true; // Enable Alerts
input bool eaLogAlerts = true; // Log Alerts
input bool eaMailAlerts = false; // Mail Alerts
input bool eaPushAlerts = false; // Push Alerts
input bool eaTerminalAlerts = false; // Terminal Alerts
//
// Time Report ...
input group "Reports";
input bool eaReportNewMonths = false; // Report New Month
input bool eaReportNewWeeks = false; // Report New Weeks
input bool eaReportNewDays = true; // Report New Days
input bool eaReportNewHours = false; // Report New Hours
//
// Variables, Instances ...
XCAlert *eaAlert;
XCTrade *eaTrade;
XSignal eaSignal;
XCVolume *eaVolume;
XCXCAEASignaller *eaSignaller;
XCXCAEATradeManager *eaTradeManager;
XCAEAStrategyConditions eaConditions;
//
int eaMaxAllowedPositions = 5;
double eaMaxAllowedSpread = 25;
double eaMaxAllowedDrawdownFactor = 0.3;
//
string eaTag = "";
//
// Event Handlers ...
//
// Initialization ...
int OnInit()
{
//
// Validate Inputs and Required Parameters
// for EA to Works fine ...
if (!ValidateInputs())
{
return INIT_PARAMETERS_INCORRECT;
}
//
// Initialize Timer ...
if (!InitTimer())
{
return INIT_FAILED;
}
//
// Initial Requirements ...
InitRequirements();
//
// Initialize Volume Manger ...
if (!InitVolume())
{
return INIT_FAILED;
}
//
// Init Succeed ...
return INIT_SUCCEEDED;
}
//
// DeInitialization ...
void OnDeinit(const int reason)
{
//
// REASON_PROGRAM 0 The EA has stopped working calling the ExpertRemove() function
// REASON_REMOVE 1 Program removed from a chart
// REASON_RECOMPILE 2 Program recompiled
// REASON_CHARTCHANGE 3 A symbol or a chart period is changed
// REASON_CHARTCLOSE 4 Chart closed
// REASON_PARAMETERS 5 Inputs changed by a user
// REASON_ACCOUNT 6 Another account has been activated or reconnection to the trade server has occurred due to changes in the account settings
// REASON_TEMPLATE 7 Another chart template applied
// REASON_INITFAILED 8 The OnInit() handler returned a non-zero value
// REASON_CLOSE 9 Terminal closed
//
ZeroMemory(eaAlert);
ZeroMemory(eaTrade);
ZeroMemory(eaVolume);
ZeroMemory(eaSignaller);
//
eaSignal.Clean();
eaConditions.Clean();
//
DestroyTimer();
}
//
// On Tick Handler ...
void OnTick()
{
//
int idx = -1;
int count = 0;
bool has = false;
//
// Handle Position Management / Protections ...
eaTradeManager.Manage();
//
eaSignal.Clean();
eaConditions.Clean();
//
double r2r = 5;
string provider = "XCAEA";
ENUM_POSITION_TYPE type = POSITION_TYPE_BUY;
ENUM_X_ORDER_MODES mode = X_ORDER_MODE_MARKET;
//
bool hasLong = false;
bool hasShort = false;
//
// Start Calculations ...
//
// Retrieve Common Data ...
string symbol = eaSignaller.GetSymbol();
ENUM_TIMEFRAMES period = eaSignaller.GetPeriod();
//
datetime cTime = TimeCurrent();
//
// Required Value For SL/TP Calculations ...
double points = GetPoints(symbol);
double pip = GetPipPrice(symbol);
double pip2 = 2 * pip;
//
has = eaSignaller.DetectSignalSetup(
r2r,
300 // Max Allowed SL Distance ...
);
if (has)
{
//
count = eaSignaller
.AddConditionsIfNotExists();
//
eaSignaller.mConditions.Clean();
}
//
// Check Setuped Conditions Exists ...
count = ArraySize(eaSignaller.mConditionsCollection);
has = IsValidSize(count);
if (!has)
{
return;
}
//
for (int i = 0; i < count; i++)
{
//
has = eaSignaller
.DetectSignalTrigger(eaSignaller
.mConditionsCollection[i]);
//
if (has)
{
//
idx = i;
eaConditions = eaSignaller.mConditionsCollection[i];
break;
}
}
//
has = IsValidIndex(idx);
if (has)
{
//
ArrayRemove(
eaSignaller.mConditionsCollection,
idx,
1 //
);
}
//
// Check EA Conditions is Valid or not ...
has = eaConditions.IsSetuped() &&
eaConditions.CanTrigger();
if (!has)
{
//
eaConditions.Clean();
return;
}
//
// Setting Time to Conditions ...
eaConditions.time = cTime;
has = ToPositionType(
type,
eaConditions.type //
);
if (!has)
{
//
eaSignal.Clean();
eaConditions.Clean();
//
return;
}
//
// Checking Trigger Direction ...
hasLong = eaConditions.HasBullishSignal();
hasShort = eaConditions.HasBearishSignal();
has = hasLong ||
hasShort;
if (!has)
{
//
eaSignal.Clean();
eaConditions.Clean();
//
return;
}
//
// Preparing Signal ...
//
eaSignal.mode = mode;
eaSignal.type = type;
eaSignal.entry = GetEntry(
eaConditions.symbol,
eaConditions.dir //
);
eaSignal.provider = provider;
eaSignal.sl = eaConditions.sl;
eaSignal.tp = eaConditions.tp;
eaSignal.volume = X_MIN_VOLUME;
eaSignal.time = eaConditions.time;
eaSignal.symbol = eaConditions.symbol;
eaSignal.period = eaConditions.period;
//
Copy(
eaConditions.targets,
eaSignal.targets //
);
//
has = eaSignal.IsValid();
if (!has)
{
//
eaSignal.Clean();
eaConditions.Clean();
return;
}
//
// Handle Volume Management ...
double iVolume = eaVolume.CalculateVolume(eaSignal);
if (iVolume > X_MIN_VOLUME &&
iVolume != eaSignal.volume)
{
eaSignal.volume = iVolume;
}
//
// Draw Signal ...
//
// Execute Signal ...
//
has = eaTradeManager.Execute(
eaSignal,
eaConditions //
);
if (has)
{
//
// Do What we Want on Successfully Execution Signal ...
Print("Signal Executed ...");
}
//
eaSignal.Clean();
eaConditions.Clean();
}
//
// Handle On Trade Event ...
void OnTrade()
{
}
//
// On Timer ...
void OnTimer()
{
}
//
// Chart Event Handler ...
void OnChartEvent(
const int id,
const long &lparam,
const double &dparam,
const string &sparam //
)
{
}
//
// Event Listeners ...
/**
* Handle StopLoss Triggered Positions ...
*
* @param deal: XDeal instance ...
*/
void OnStopLossTriggered(const XDeal &deal)
{
eaTradeManager.HandleSL(deal);
}
/**
* Handle Take Profit Triggered Positions ...
*
* @param deal: XDeal instance ...
*/
void OnTakeProfitTriggered(const XDeal &deal)
{
eaTradeManager.HandleTP(deal);
}
/**
* Handle Force Close a Position ...
*
* @param ticket: ULONG ...
* @param position: XPosition instance ...
* @param comment: String ...
*/
void OnPositionForceClosed(
const ulong ticket,
const XPosition &position,
const string comment //
)
{
eaTradeManager.HandleForceClose(position);
}
/**
* Handle Deals Changes ...
*
* @param count: Integer, Number of Changes ...
*/
void OnDealsChanged(int count)
{
}
/**
* Handle Orders Changes ...
*
* @param count: Integer, Number of Changes ...
*/
void OnOrdersChanged(int count)
{
}
/**
* Handle Positions Changes ...
*
* @param count: Integer, Number of Changes ...
*/
void OnPositionsChanged(int count)
{
}
//
// Custom Functions ...
/**
* Validate all Inputs of Expert Adviser ...
*
* @return ( bool )
*/
bool ValidateInputs()
{
//
bool result = false;
//
string errMessage = "";
//
bool isCommonValid = (
//
eaSlippage > 0 &&
eaMagicNumber > 0
//
);
if (!isCommonValid)
{
//
errMessage += "common configurations error;" + "\n";
}
//
result =
//
// Common ...
isCommonValid &&
//
// Otere ...
true
//
;
//
if (!result)
{
//
// Since here Logger not Initiallized, we Use Raw Print Command ...
Print(ShortName + " Errors: \n", errMessage);
}
//
return result;
}
/**
* Initialize Timer ...
*
* @return ( bool )
*/
bool InitTimer()
{
//
bool result = false;
//
// TODO: Initialize Timer if necessary ...
// result = EventSetTimer(1);
// result = EventSetMillisecondTimer(100);
result = true;
//
return result;
}
/**
* Destroy Timer ...
*/
void DestroyTimer()
{
//
// TODO: Use This ...
// EventKillTimer();
}
/**
* Initial Volume Manager Class Based on Given Configuration ...
*
* @return ( bool )
*/
bool InitVolume()
{
//
bool result = false;
//
eaVolume = new XCVolume();
//
result = eaVolume.Init(
eaVolumeSelect,
eaStaticVoluem,
eaDynamicVolumeStepBalance,
eaDynamicVolumeStepVolume,
eaConstantRiskBalance,
eaConstantPercent,
eaConstantBalance //
);
//
return result;
}
/**
* Initial Requirements of EA ...
*
*/
void InitRequirements()
{
//
// Preparing Tags ...
eaTag =
(IsValid(eaLogSuffix)
? eaLogSuffix + "_"
: "") +
ShortName;
//
// EA Alert ...
eaAlert = new XCAlert(
eaTag,
eaEnableAlerts,
eaLogAlerts,
eaTerminalAlerts,
eaMailAlerts,
eaPushAlerts //
);
//
// EA Trade ...
eaTrade = new XCTrade(
eaSlippage,
eaMagicNumber,
eaMaxAllowedSpread,
eaMaxAllowedPositions,
eaMaxAllowedDrawdownFactor //
);
eaTrade.AddOnStopLossEventHandler(OnStopLossTriggered);
eaTrade.AddOnTakeProfitEventHandler(OnTakeProfitTriggered);
eaTrade.AddOnForceClosePositionEventHandler(OnPositionForceClosed);
//
// EA Trae Manager ...
eaTradeManager = new XCXCAEATradeManager(
eaTrade //
);
eaTradeManager.SetAlertEnableAlerts(eaEnableAlerts);
eaTradeManager.SetAlertPrefix(eaTag);
eaTradeManager.SetAlertLogAlerts(eaLogAlerts);
eaTradeManager.SetAlertMailAlerts(eaMailAlerts);
eaTradeManager.SetAlertPushAlerts(eaPushAlerts);
eaTradeManager.SetAlertTerminalAlerts(eaTerminalAlerts);
//
// EA Signaller ...
eaSignaller = new XCXCAEASignaller(
_Symbol,
_Period //
);
//
}
//