Files
MQL5Data/X121SMCEA/Experts/x-121.smc.expert.class.mq5
T
2024-12-31 21:50:07 +03:30

1640 lines
37 KiB
Plaintext

///////////////////////////////////////////////////////
//
// SaherElm IT Center MQL5 Class Library
// --------------------------------------
// Name: XC121SMCExpert
// Description: provides all based classes for use ...
//
//
// Maintainer:
// ------------
// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com)
//
//////////////////////////////////////////////////////
//
// Global Properties ...
#property library
#property copyright "Copyright 2023, SaherElm IT Center"
#property link "https://www.saherelm.ir"
#property version "1.00"
#property strict
//
// Imports ...
#include "../../Classes/x-saherelm.x-expert.class.mq5"
#include "../Classes/x-121.smc.x-tradehandler.class.mq5"
#include "../Libraries/x-121.smc.lib.mq5"
#include "../Strategy/x-121.smc.strategy.class.mq5"
//
// Definitions ...
string XC121SMCExpertToken = "XC121SMCEA";
//
// Implementation ...
class XC121SMCExpert : public XCBaseExpert
{
//
public:
//
//
// Signal Event Listener ...
TOnStopLoss OnPositionSLEventListener;
TOnTakeProfit OnPositionTPEventListener;
TOnPartialClose OnPositionPartialCloseEventListener;
TOnModify OnPositionModifiedEventListener;
TOnForceClose OnPositionForceCloseEventListener;
//
TOnDealsChanged OnDealsChangedEventListener;
TOnOrdersChanged OnOrdersChangedEventListener;
TOnPositionsChanged OnPositionsChangedEventListener;
//
TOnX121SMCSignal OnSignalEventListener;
//
// Getter(s) / Setter(s) ...
//
// Signalling Props ...
/**
* Get Allow Long Signals State ...
*
* @return ( bool )
*/
bool AllowLong()
{
return mAllowLong;
}
/**
* Set Allow Long Signals State ...
*
* @param value: Boolean ...
*/
void AllowLong(bool value)
{
//
mAllowLong = value;
ReConfigure();
}
/**
* Get Allow Short Signals State ...
*
* @return ( bool )
*/
bool AllowShort()
{
return mAllowShort;
}
/**
* Set Allow Short Signals State ...
*
* @param value: Boolean ...
*/
void AllowShort(bool value)
{
//
mAllowShort = value;
ReConfigure();
}
/**
* Get Max Allowed Long Signals ...
* 0 => Unlimited ...
*
* @return ( int )
*/
int MaxAllowedLongs()
{
return mMaxAllowedLongs;
}
/**
* Set Max Allowed Long Signals ...
*
* @param value: Integer ...
* 0 => Unlimited ...
*/
void MaxAllowedLongs(int value)
{
//
if (value < 0)
{
value = 0;
}
//
mMaxAllowedLongs = value;
ReConfigure();
}
/**
* Get Max Allowed Short Signals ...
* 0 => Unlimited ...
*
* @return ( int )
*/
int MaxAllowedShorts()
{
return mMaxAllowedShorts;
}
/**
* Set Max Allowed Short Signals ...
*
* @param value: Integer ...
* 0 => Unlimited ...
*/
void MaxAllowedShorts(int value)
{
//
if (value < 0)
{
value = 0;
}
//
mMaxAllowedShorts = value;
ReConfigure();
}
/**
* Get Use Max Allowed Signal Types Per Symbol State ...
*
* @return ( bool )
*/
bool UseMaxAllowedSignalsPerSymbol()
{
return mUseMaxAllowedSignalsPerSymbol;
}
/**
* Set Use Max Allowed Signal Types Per Symbol State ...
*
* @param value: Boolean ...
*/
void UseMaxAllowedSignalsPerSymbol(bool value)
{
//
mUseMaxAllowedSignalsPerSymbol = false;
ReConfigure();
}
/**
* Get Last Position Profit In Points for Accept new Signal ...
* 0 => Accept All ...
*
* @return ( double )
*/
double LastPositionProfitForAcceptNextInPoint()
{
return mLastPositionProfitForAcceptNextInPoint;
}
/**
* Set Last Position Profit In Points for Accept new Signal ...
*
* @param value: Double ...
* 0 => Accept All ...
*/
void LastPositionProfitForAcceptNextInPoint(double value)
{
//
if (value < 0)
{
value = 0;
}
//
mLastPositionProfitForAcceptNextInPoint = value;
ReConfigure();
}
/**
* Get Delay between two Signals in Bars ...
* 0 => Accept All ...
*
* @return ( int )
*/
int DelaysBetweenTwoSignalsInBar()
{
return mDelaysBetweenTwoSignalsInBar;
}
/**
* Set Delay between two Signals in Bars ...
*
* @param value: Integer ...
* 0 => Accept All ...
*/
void DelaysBetweenTwoSignalsInBar(int value)
{
//
if (value < 0)
{
value = 0;
}
//
mDelaysBetweenTwoSignalsInBar = value;
ReConfigure();
}
/**
* Get Max Allowed Spread for Signalling ...
* 0 => Accept All ...
*
* @return ( double )
*/
double MaxAllowedSpread()
{
return mMaxAllowedSpread;
}
/**
* Set Max Allowed Spread for Signalling ...
*
* @param value: Double ...
* 0 => Accept All ...
*/
void MaxAllowedSpread(double value)
{
//
if (value < 0)
{
value = 0;
}
//
mMaxAllowedSpread = value;
ReConfigure();
}
/**
* Get Minimum Spread Verification for Signalling ...
* 0 => Ignore ...
*
* @return ( int )
*/
int MinRequiredVerificationForSpreadPass()
{
return mMinRequiredVerificationForSpreadPass;
}
/**
* Set Minimum Spread Verification for Signalling ...
*
* @param value: Integer ...
* 0 => Ignore ...
*/
void MinRequiredVerificationForSpreadPass(int value)
{
//
if (value < 0)
{
value = 0;
}
//
mMinRequiredVerificationForSpreadPass = value;
ReConfigure();
}
//
// Risk Management Props ...
/**
* Get Risk to Reward Ratio ...
*
* @return ( double )
*/
double R2R()
{
return mR2R;
}
/**
* Set Risk to Reward Ratio ...
*
* @param value: Double ...
*/
void R2R(double value)
{
//
if (value < 1)
{
value = 1;
}
//
mR2R = value;
ReConfigure();
}
/**
* Get Static Volume ...
*
* @return ( double )
*/
double Volume()
{
return mVolume;
}
/**
* Set Static Volume ...
*
* @param value: Double ...
*/
void Volume(double value)
{
//
if (value < 0.01)
{
value = 0.01;
}
//
mVolume = value;
ReConfigure();
}
/**
* Get Risk Percent Per Balance in Each Trade ...
*
* @return ( double )
*/
double RiskPercentPerBalance()
{
return mRiskPercentPerBalance;
}
/**
* Set Risk Percent Per Balance in Each Trade ...
*
* @param value: Double
*/
void RiskPercentPerBalance(double value)
{
//
if (value < 0)
{
value = 0;
}
//
mRiskPercentPerBalance = value;
ReConfigure();
}
/**
* Get Dynamic Risk Management State ...
*
* @return ( bool )
*/
bool DynamicRiskManagement()
{
return mDynamicRiskManagement;
}
/**
* Set Dynamic Risk Management State ...
*
* @param value: Boolean ...
*/
void DynamicRiskManagement(bool value)
{
//
mDynamicRiskManagement = value;
ReConfigure();
}
/**
* Get Use Dynamic Volume State ...
*
* @return ( bool )
*/
bool UseDynamicVolume()
{
return mUseDynamicVolume;
}
/**
* Set Use Dynamic Volume State ...
*
* @param value: Boolean ...
*/
void UseDynamicVolume(bool value)
{
//
mUseDynamicVolume = value;
ReConfigure();
}
/**
* Get Increase Volume Step ...
*
* @return ( double )
*/
double DynamicVolumeStep()
{
return mDynamicVolumeStep;
}
/**
* Set Increase Volume Step ...
*
* @param value: Double ...
*/
void DynamicVolumeStep(double value)
{
//
if (value < 0.01)
{
value = 0.01;
}
//
mDynamicVolumeStep = value;
ReConfigure();
}
/**
* Get Balance Factor for Generate Dynamic Volume ...
*
* @return ( double )
*/
double DynamicVolumeBalanceFactor()
{
return mDynamicVolumeBalanceFactor;
}
/**
* Set Balance Factor for Generate Dynamic Volume ...
*
* @param value: Double ...
*/
void DynamicVolumeBalanceFactor(double value)
{
//
if (value < 0)
{
value = 0;
}
//
mDynamicVolumeBalanceFactor = value;
ReConfigure();
}
/**
* Get Max Allowed Drawdown Percent for Open Trades ...
* 0 => Ignore ...
* min => 0 ...
* max => 100 ...
*
* @return ( double )
*/
double MaxAllowedDrawdownToOpenTrades()
{
return mMaxAllowedDrawdownToOpenTrades;
}
/**
* Set Max Allowed Drawdown Percent for Open Trades ...
*
* @param value: Double ...
* 0 => Ignore ...
* min => 0 ...
* max => 100 ...
*/
void MaxAllowedDrawdownToOpenTrades(double value)
{
//
if (value < 0)
{
value = 0;
}
//
if (value > 50)
{
value = 50;
}
//
mMaxAllowedDrawdownToOpenTrades = value;
ReConfigure();
}
/**
* Get Max Allowed SL for Pause Signalling Per Symbol ...
* 0 => Unlimited ...
*
* @return ( int )
*/
int MaxAllowedSLToPauseSignallingPerSymbol()
{
return mMaxAllowedSLToPauseSignallingPerSymbol;
}
/**
* Set Max Allowed SL for Pause Signalling Per Symbol ...
*
* @param value: Integer ...
* 0 => Unlimited ...
*/
void MaxAllowedSLToPauseSignallingPerSymbol(int value)
{
//
if (value < 0)
{
value = 0;
}
//
mMaxAllowedSLToPauseSignallingPerSymbol = value;
ReConfigure();
}
/**
* Get Pause Signalling Per Symbol afte Max Allowed SL Reached In Seconds ...
* 0 => Ignore ...
*
* @return ( int )
*/
int PauseSignallingAfterReachesMaxAllowedSLInSecconds()
{
return mPauseSignallingAfterReachesMaxAllowedSLInSecconds;
}
/**
* Set Pause Signalling Per Symbol afte Max Allowed SL Reached In Seconds ...
*
* @param value: Integer ...
* 0 => Ignore ...
*/
void PauseSignallingAfterReachesMaxAllowedSLInSecconds(int value)
{
//
if (value < 0)
{
value = 0;
}
//
mPauseSignallingAfterReachesMaxAllowedSLInSecconds = value;
ReConfigure();
}
//
// Protection Props ...
/**
* Get Allow Hedge Positions State ...
*
* @return ( bool )
*/
bool AllowHedging()
{
return mAllowHedging;
}
/**
* Set Allow Hedge Positions State ...
*
* @param value: Boolean ...
*/
void AllowHedging(bool value)
{
//
mAllowHedging = value;
ReConfigure();
}
/**
* Get Minimum Open Positions for Hedging ...
* 0 => Ignore ...
*
* @return ( int )
*/
int MinOpenTradesFroHedging()
{
return mMinOpenTradesFroHedging;
}
/**
* Set Minimum Open Positions for Hedging ...
*
* @param value: Integer ...
* 0 => Ignore ...
*/
void MinOpenTradesFroHedging(int value)
{
//
if (value < 0)
{
value = 0;
}
//
mMinOpenTradesFroHedging = value;
ReConfigure();
}
/**
* Get Minimum Volume Step for Hedging ...
* 0 => Ignore ...
*
* @return ( double )
*/
double HedgingMinVolumeStep()
{
return mHedgingMinVolumeStep;
}
/**
* Set Minimum Volume Step for Hedging ...
*
* @param value: Double ...
* 0 => Ignore ...
*/
void HedgingMinVolumeStep(double value)
{
//
if (value < 0)
{
value = 0;
}
//
if (value > 0 && value < 0.01)
{
value = 0.01;
}
//
if (value > 0 && value > 0.1)
{
value = 0.1;
}
//
mHedgingMinVolumeStep = value;
ReConfigure();
}
/**
* Get Minimum Required Profit Per Volume Step for Hedging ...
* 0 => Ignore ...
*
* @return ( double )
*/
double HedgeingMinRequiredProfitPerVolumeStep()
{
return mHedgeingMinRequiredProfitPerVolumeStep;
}
/**
* Set Minimum Required Profit Per Volume Step for Hedging ...
*
* @param value: Double ...
* 0 => Ignore ...
*/
void HedgeingMinRequiredProfitPerVolumeStep(double value)
{
//
if (value < 0)
{
value = 0;
}
//
mHedgeingMinRequiredProfitPerVolumeStep = value;
ReConfigure();
}
//
// Actions ...
/**
* Handle OnSignalRecieved Event ...
*
* @param signal: XSignal instance ...
* @param conditions: X121SMCStrategyConditions instance ...
*/
void HandleOnSignalRecieved(
XSignal &signal,
X121SMCStrategyConditions &conditions //
)
{
//
// Check Signal and Conditions Validations ...
//
if (!signal.IsValid())
{
return;
}
//
if (!conditions.IsValid())
{
return;
}
//
bool isLong = IsLong(signal.type);
//
// Notify When a Raw (Unfiltered) Signal Recieved
// if it's Provided ...
bool mAlertRawSignals = false;
if (mAlertRawSignals)
{
//
string msg = "Raw " + (IsLong(signal.type) ? "Long" : "Short") + " Signal Recieved: (" + signal.provider + "," + signal.symbol + "," + ToString(signal.period) + ") ...";
Alert(msg);
}
//
// Apply Volume On Signal ...
ApplyVolumeOnSignal(signal);
//
// Chekc Signalling Enable or not ...
bool canContinue =
isLong
? AllowLong()
: AllowShort();
if (!canContinue)
{
return;
}
//
// TODO: Apply Filtering On Signal ...
bool isFiltered = false;
if (isFiltered)
{
//
mTradeHandler.Remove(signal);
return;
}
//
// Attach Conditions Summary to Signal ...
string conditionsSummary = conditions.GenerateSummary(
false,
false,
true,
false //
);
//
// TODO: Retrieve Conditions Summary based on Filter ...
signal.conditions = conditionsSummary;
//
datetime currentTime = TimeCurrent();
//
// Execute Signal Using Trade Handler ...
ENUM_X_SIGNAL_EXECUTION_RESULT state;
bool isExecuted = mTradeHandler.ExecuteSignal(
signal,
state,
false // ignore Policies ...
);
}
//
// Override Actions ...
/**
* Apply Default Configurations ...
*/
void DefaultConfigure() override
{
//
// Commons ...
Slippage(10);
TagPrefix("");
MagicNumber(1694056);
//
// Symbol ...
SetSymbol(_Symbol);
SetPeriod(_Period);
MultiSymbol(false);
Symbols("EURUSDb,GBPUSDb,USDJPYb,USDCHFb,DowJones30,XAUUSDb");
//
// Signalling ...
Disabled(false);
AllowLong(true);
AllowShort(true);
//
string tag = GetTag();
//
// Alert ...
SetAlertPrefix(tag);
SetAlertLogAlerts(true);
SetAlertPushAlerts(true);
SetAlertMailAlerts(false);
SetAlertEnableAlerts(true);
SetAlertTerminalAlerts(false);
//
// Reports ...
ReportNewDays(true);
ReportNewWeeks(false);
ReportNewHours(false);
ReportNewMonths(false);
//
R2R(1);
//
// Volume Default Configurations ...
Volume(0.01);
UseDynamicVolume(false);
DynamicVolumeStep(0.01);
DynamicVolumeBalanceFactor(200);
//
RiskPercentPerBalance(0);
DynamicRiskManagement(false);
}
/**
* Vaslidate Inputs ...
*
* @return ( bool )
*/
bool ValidateInputs() override
{
//
bool result = false;
//
string errMessage = "";
//
bool isCommonValid = (
//
Slippage() > 0 &&
MagicNumber() > 0
//
);
if (!isCommonValid)
{
//
errMessage += "common configurations error;" + "\n";
}
//
// Checking Volume ...
bool isVolumeValid = true;
if (UseDynamicVolume())
{
//
isVolumeValid =
DynamicVolumeStep() > 0 &&
DynamicVolumeBalanceFactor() > 0;
if (!isVolumeValid)
{
errMessage += "Dynamic Volume configurations error;" + "\n";
}
}
isVolumeValid = isVolumeValid &&
Volume() > 0;
if (!isVolumeValid)
{
errMessage += "Static Volume configurations error;" + "\n";
}
//
result =
//
// Common ...
isCommonValid &&
//
// Volume Coniguration ...
isVolumeValid &&
//
// Otere ...
true
//
;
//
if (!result)
{
//
// Since here Logger not Initiallized, we Use Raw Print Command ...
errMessage = " Errors: \n" + errMessage;
Alert(errMessage);
}
//
return result;
}
//
// Initializers and DeInitializers ...
/**
* Initial EA Requirements ...
*
* @return ( bool )
*/
bool InitEA() override
{
//
bool result = false;
//
// Initialize Indicator Helpers ...
//
// Bar Timer ...
XCTInputs ctInputs;
ctInputs.Default(); // Default Configurations ...
mCTHelper = new XCXCTHelper();
result = mCTHelper.Init(
GetSymbol(),
GetPeriod(),
ctInputs //
);
if (!result)
{
return result;
}
//
// Bar Styles ...
XCCInputs ccInputs;
ccInputs.Default(); // Default Configurations ...
mCCHelper = new XCXCCHelper();
result = mCCHelper.Init(
GetSymbol(),
GetPeriod(),
ccInputs //
);
if (!result)
{
return result;
}
//
// Configure Alerts ...
SetAlertPrefix(GetTag());
SetAlertEnableAlerts(GetAlertEnableAlerts());
SetAlertLogAlerts(GetAlertLogAlerts());
SetAlertMailAlerts(GetAlertMailAlerts());
SetAlertPushAlerts(GetAlertPushAlerts());
SetAlertTerminalAlerts(GetAlertTerminalAlerts());
//
// Create Trader Instance and Configure it ...
mTrader = new XCTrade(
Slippage(),
MagicNumber() //
);
mTrader.AddOnStopLossEventHandler(OnPositionSLEventListener);
mTrader.AddOnTakeProfitEventHandler(OnPositionTPEventListener);
mTrader.AddOnDealsChangedEventHandler(OnDealsChangedEventListener);
mTrader.AddOnOrdersChangedEventHandler(OnOrdersChangedEventListener);
mTrader.AddOnModifyPositionEventHandler(OnPositionModifiedEventListener);
mTrader.AddOnPositionsChangedEventHandler(OnPositionsChangedEventListener);
mTrader.AddOnForceClosePositionEventHandler(OnPositionForceCloseEventListener);
mTrader.AddOnPartialClosePositionEventHandler(OnPositionPartialCloseEventListener);
//
// Initialize Trade Handler ...
mTradeHandler = new XC121SMCTradeHandler(mTrader);
mTradeHandler.SaveTrades(false);
mTradeHandler.SaveSignals(false);
mTradeHandler.SaveConditions(false);
//
ReConfigureTradeHandler();
//
// Parsers ...
XSymbolParser _symbolParser;
XCPOIDrawer *poiDrawer = NULL;
//
// Single Symbol ...
if (!MultiSymbol())
{
//
// Register Strategy ...
//
// Create Class Instance ...
XCX121SMCBaseStrategy *iX121SMCStrategy;
iX121SMCStrategy = new XCX121SMCStrategy(
_Symbol,
_Period //
);
//
if (poiDrawer == NULL)
{
//
poiDrawer = iX121SMCStrategy
.GetDrawer();
}
//
iX121SMCStrategy.AddXSignalEventHandler(OnSignalEventListener);
//
ConfigureStrategy(iX121SMCStrategy);
RegisterStrategy(iX121SMCStrategy);
}
//
// Multi Symbol ...
else
{
//
// Parse Symbols ...
string symbols[];
int symbolsCount = SplitContent(
symbols,
Symbols() //
);
result = IsValidSize(symbolsCount);
if (!result)
{
return result;
}
//
for (int i = 0; i < symbolsCount; i++)
{
//
// Select Symbol ...
string iSymbol = symbols[i];
//
// Register Strategy Based On Symbol ...
//
// Parse Symbol ...
bool isEURUSD = _symbolParser.IsEURUSD(_Symbol);
bool isGBPUSD = _symbolParser.IsGBPUSD(_Symbol);
bool isEURGBP = _symbolParser.IsEURGBP(_Symbol);
bool isUSDCHF = _symbolParser.IsUSDCHF(_Symbol);
bool isEURCHF = _symbolParser.IsEURCHF(_Symbol);
bool isUSDJPY = _symbolParser.IsUSDJPY(_Symbol);
bool isEURJPY = _symbolParser.IsEURJPY(_Symbol);
bool isUSDCAD = _symbolParser.IsUSDCAD(_Symbol);
bool isEURCAD = _symbolParser.IsEURCAD(_Symbol);
bool isAUDUSD = _symbolParser.IsAUDUSD(_Symbol);
bool isEURAUD = _symbolParser.IsEURAUD(_Symbol);
bool isNZDUSD = _symbolParser.IsNZDUSD(_Symbol);
bool isEURNZD = _symbolParser.IsEURNZD(_Symbol);
//
// Check Symbol Can Register or not ...
bool canRegisterStrategy = true;
//
if (canRegisterStrategy)
{
//
// Create Class Instance ...
XCX121SMCBaseStrategy *iX121SMCStrategy;
iX121SMCStrategy = new XCX121SMCStrategy(
iSymbol,
_Period //
);
//
if (poiDrawer == NULL)
{
//
poiDrawer = iX121SMCStrategy
.GetDrawer();
}
//
iX121SMCStrategy.AddXSignalEventHandler(OnSignalEventListener);
//
// Register Strategy ...
ConfigureStrategy(iX121SMCStrategy);
RegisterStrategy(iX121SMCStrategy);
}
}
}
//
if (poiDrawer != NULL)
{
mTradeHandler.SetDrawer(poiDrawer);
}
//
return result;
}
/**
* Destroy all Initialized EA Requirements ...
*/
void DestroyEA() override
{
//
delete mCTHelper;
delete mCCHelper;
delete mTradeHandler;
//
Clean(mStrategies);
}
/**
* Call all Registered Strategies On Tick ...
*/
void HandleStrategiesOnTick() override
{
//
// Update Positions Data ...
mTradeHandler.UpdateData();
//
// Protect Positions ...
mTradeHandler.HandleProtection();
//
int count = ArraySize(mStrategies);
if (!IsValidSize(count))
{
return;
}
//
for (int i = 0; i < count; i++)
{
//
// Call Tick Handler Function ...
mStrategies[i].HandleTick();
}
}
//
// Event Handlers ...
/**
* Calls When a Deals Changed Triggered ...
*
* @param count: Integer, Number of Changes ...
*/
void HandleOnDealsChanged(int count) override
{
}
/**
* Calls When a Order Changed Triggered ...
*
* @param count: Integer, Number of Changes ...
*/
void HandleOnOrdersChanged(int count) override
{
}
/**
* Calls When a Positions Changed Triggered ...
*
* @param count: Integer, Number of Changes ...
*/
void HandleOnPositionsChanged(int count) override
{
//
if (IsValidSize(count))
{
mTradeHandler.HandleNewPosition();
}
}
/**
* Calls When a Position's SL Triggered ...
*
* @param deal: XDeal instance ...
*/
void HandleOnStopLossTriggered(const XDeal &deal) override
{
//
// Finish ...
mTradeHandler.Finish(deal);
//
HandleReportBalance();
}
/**
* Calls When a Position's TP Triggered ...
*
* @param deal: XDeal instance ...
*/
void HandleOnTakeProfitTriggered(const XDeal &deal) override
{
//
// Finish ...
mTradeHandler.Finish(deal);
//
bool useDynamicRiskManagement = DynamicRiskManagement();
if (useDynamicRiskManagement)
{
mTradeHandler.ResetSymbolInfo(deal.symbol);
}
//
HandleReportBalance();
}
/**
* Handle Force Close a Position ...
*
* @param ticket: Position Ticket ...
* @param position: XPosition ...
* @param comment: Closing Comment ...
*/
void HandleOnPositionForceClosed(
const ulong ticket,
const XPosition &position,
const string comment //
) override
{
//
// Finish ...
mTradeHandler.Finish(
ticket,
position,
comment //
);
//
HandleReportBalance();
}
/**
* Reset All Paused Symbols on Each New Days ...
*/
void HandleOnNewDay() override
{
mTradeHandler.ResumePausedSymbols();
}
/**
* Re Configure Materials on Properties Changed ...
*/
void ReConfigure() override
{
//
ReConfigureTradeHandler();
ReConfigureAllStrategies();
}
/**
* Generate Identifier Tag ...
*
* @return ( string )
*/
string GetTag() override
{
//
string result = NULL;
//
string tagPrefix = TagPrefix();
if (IsValid(tagPrefix))
{
result = tagPrefix;
}
else
{
result = "";
}
//
result =
XC121SMCExpertToken + result;
//
return result;
}
//
protected:
//
//
// Props ...
//
XC121SMCTradeHandler *mTradeHandler; // Trade Handler ...
XCX121SMCBaseStrategy *mStrategies[]; // Registere Strategies in EA ...
//
// Actions ...
/**
* Apply Volume Based On Configurations on Signal ...
*
* @param signal: XSignal instance
*/
void ApplyVolumeOnSignal(XSignal &signal)
{
//
// Prepare Signal Dynamic Volume
// if Provided ...
if (UseDynamicVolume() &&
DynamicVolumeStep() > 0 &&
DynamicVolumeBalanceFactor() > 0)
{
//
double dVolume = mTrader.GetDynamicVolume(
signal.symbol,
DynamicVolumeBalanceFactor(),
DynamicVolumeStep() //
);
//
if (dVolume > 0)
{
signal.volume = dVolume;
}
else
{
signal.volume = Volume();
}
}
else if (RiskPercentPerBalance() > 0)
{
//
double riskPercent = RiskPercentPerBalance();
//
double balance = mTrader.mAccount.GetBalance();
double riskAmountPerBalance = (riskPercent * balance) / 100;
//
double risk = signal.GetRisk();
double points = GetPoints(signal.symbol);
double riskInPoints = risk / points;
//
double volume = mTrader.mAccount.CalculateVolume(
signal.symbol,
riskAmountPerBalance,
riskInPoints //
);
//
// Check Dynamic Risk Management ...
bool allowDynamicRiskManagement = DynamicRiskManagement();
if (allowDynamicRiskManagement)
{
//
// Calculate Dynamic Additional Risk Management Volume Multiplier ...
double mAdditionalRiskMultiplier = CalculateAdditionalVolumeMultiplier(signal);
if (mAdditionalRiskMultiplier < 1)
{
mAdditionalRiskMultiplier = 1;
}
//
volume *= mAdditionalRiskMultiplier;
}
//
if (volume > 0)
{
volume = NormalizeVolume(volume, signal.symbol);
}
//
signal.volume = volume;
}
else
{
signal.volume = Volume();
}
}
/**
* Configure Startegy ...
*/
void ConfigureStrategy(XCX121SMCBaseStrategy *&strategy)
{
//
if (strategy == NULL)
{
return;
}
//
// Configure Alerts ...
strategy.SetAlertPrefix(GetTag());
strategy.SetAlertLogAlerts(GetAlertLogAlerts());
strategy.SetAlertMailAlerts(GetAlertMailAlerts());
strategy.SetAlertPushAlerts(GetAlertPushAlerts());
strategy.SetAlertEnableAlerts(GetAlertEnableAlerts());
strategy.SetAlertTerminalAlerts(GetAlertTerminalAlerts());
//
// Confiugre Signalling ...
//
strategy.R2R(R2R());
strategy.AllowLong(AllowLong());
strategy.AllowShort(AllowShort());
strategy.MaxAllowedSpread(20);
strategy.MaxAllowedSaveTicks(150);
strategy.MinRequiredTicksForSpreadPass(100);
//
if (Disabled())
{
strategy.Disable();
}
else
{
strategy.Enable();
}
//
}
/**
* Register an Strategy in EA ...
*
* @param strategy: XCX121SMCBaseStrategy instance ...
*/
void RegisterStrategy(XCX121SMCBaseStrategy *strategy)
{
//
if (strategy == NULL)
{
return;
}
//
ArrayResize(
mStrategies,
ArraySize(mStrategies) + 1 //
);
//
mStrategies[ArraySize(mStrategies) - 1] = strategy;
}
/**
* Re Configure All Registered Strategies ...
*/
void ReConfigureAllStrategies()
{
//
int count = ArraySize(mStrategies);
if (!IsValidSize(count))
{
return;
}
//
for (int i = 0; i < count; i++)
{
//
ConfigureStrategy(mStrategies[i]);
}
}
/**
* Re Configure Trade Handler ...
*/
void ReConfigureTradeHandler()
{
//
if (mTradeHandler == NULL)
{
return;
}
//
// Configure Alerts ...
mTradeHandler.SetAlertPrefix(GetTag());
mTradeHandler.SetAlertEnableAlerts(GetAlertEnableAlerts());
mTradeHandler.SetAlertLogAlerts(GetAlertLogAlerts());
mTradeHandler.SetAlertMailAlerts(GetAlertMailAlerts());
mTradeHandler.SetAlertPushAlerts(GetAlertPushAlerts());
mTradeHandler.SetAlertTerminalAlerts(GetAlertTerminalAlerts());
//
mTradeHandler.AllowLong(AllowLong());
mTradeHandler.AllowShort(AllowShort());
mTradeHandler.MaxAllowedLongs(MaxAllowedLongs());
mTradeHandler.MaxAllowedShorts(MaxAllowedShorts());
mTradeHandler.UseMaxAllowedSignalsPerSymbol(UseMaxAllowedSignalsPerSymbol());
mTradeHandler.LastPositionProfitForAcceptNextInPoint(LastPositionProfitForAcceptNextInPoint());
mTradeHandler.DelaysBetweenTwoSignalsInBar(DelaysBetweenTwoSignalsInBar());
mTradeHandler.MaxAllowedSpread(MaxAllowedSpread());
mTradeHandler.MaxAllowedDrawdownToOpenTrades(MaxAllowedDrawdownToOpenTrades());
mTradeHandler.MaxAllowedSLToPauseSignallingPerSymbol(MaxAllowedSLToPauseSignallingPerSymbol());
mTradeHandler.PauseSignallingAfterReachesMaxAllowedSLInSecconds(PauseSignallingAfterReachesMaxAllowedSLInSecconds());
mTradeHandler.AllowHedging(AllowHedging());
mTradeHandler.MinOpenTradesFroHedging(MinOpenTradesFroHedging());
mTradeHandler.HedgingMinVolumeStep(HedgingMinVolumeStep());
mTradeHandler.HedgeingMinRequiredProfitPerVolumeStep(HedgeingMinRequiredProfitPerVolumeStep());
}
//
private:
//
//
// Props ...
//
// Signalling Props ...
bool mAllowLong; // Allow Long Signals ...
bool mAllowShort; // Allow Short Signals ...
int mMaxAllowedLongs; // Max Allowed Long Signals ...
int mMaxAllowedShorts; // Max Allowed Short Signals ...
bool mUseMaxAllowedSignalsPerSymbol; // Use Max Allowed Signal Types Per Symbol ...
double mLastPositionProfitForAcceptNextInPoint; // Last Position Profit In Points for Accept new Signal ...
int mDelaysBetweenTwoSignalsInBar; // Delay between two Signals in Bars ...
double mMaxAllowedSpread; // Max Allowed Spread for Signalling ...
int mMinRequiredVerificationForSpreadPass; // Minimum Spread Verification for Signalling ...
//
// Risk Management Props ...
double mR2R; // Signallers Risk to Reward Ratio ...
double mVolume; // Static Volume ...
double mRiskPercentPerBalance; // Risk Percent Per Balance in Each Trade ...
bool mDynamicRiskManagement; // Dynamic Risk Management ...
bool mUseDynamicVolume; // Use Dynamic Volume ...
double mDynamicVolumeStep; // Increase Volume Step ...
double mDynamicVolumeBalanceFactor; // Balance Factor for Generate Dynamic Volume ...
double mMaxAllowedDrawdownToOpenTrades; // Max Allowed Drawdown for Open Trades ...
int mMaxAllowedSLToPauseSignallingPerSymbol; // Max Allowed SL for Pause Signalling Per Symbol ...
int mPauseSignallingAfterReachesMaxAllowedSLInSecconds; // Pause Signalling Per Symbol afte Max Allowed SL Reached In Seconds ...
//
// Protection Props ...
bool mAllowHedging; // Allow Hedge Positions ...
int mMinOpenTradesFroHedging; // Minimum Open Positions for Hedging ...
double mHedgingMinVolumeStep; // Minimum Volume Step for Hedging ...
double mHedgeingMinRequiredProfitPerVolumeStep; // Minimum Required Profit Per Volume Step for Hedging ...
//
double CalculateAdditionalVolumeMultiplier(XSignal &signal)
{
//
double result = 0;
//
if (!signal.IsValid())
{
return result;
}
//
X121SMCSymbolPositionInfo info;
bool hasInfo = mTradeHandler.GetSymbolInfo(
signal.symbol,
info //
);
if (!hasInfo)
{
return result;
}
//
if (info.countedSLs >= 2)
{
result = (info.countedSLs / 2) + 1;
}
//
return result;
}
//
};
//