cleanup and refocused workspace for using on XCATBEA Projects ...

This commit is contained in:
2025-05-28 15:20:54 +03:30
parent 4c6be67a2d
commit 72e8b34da5
32 changed files with 18021 additions and 6061 deletions
@@ -0,0 +1,167 @@
///////////////////////////////////////////////////////
//
// SaherElm IT Center MQL5 Indicator
// -------------------------------------------------
// Name: XCXCAEADataCollector ...
// Description: Class for XCAEA Data Collector ...
//
//
// Maintainer:
// ------------
// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com)
//
//////////////////////////////////////////////////////
//
// Global Properties ...
#property library
#property copyright "Copyright 2023, SaherElm IT Center"
#property link "https://saherelm.ir"
#property version "1.00"
#property description "SaherElm Class for XCAEA Data Collector"
#property strict
//
// Imports ...
#include "../../Classes/x-saherelm.base.class.mq5"
//
// Definitions ...
//
// Implementation ...
class XCXCAEADataCollector : public XCBase
{
//
// Public ...
public:
//
// Constructors ...
XCXCAEADataCollector()
{
}
//
// Deconstructor ...
~XCXCAEADataCollector()
{
}
//
// Properties ...
//
string Path()
{
return mPath;
}
//
void Path(string value)
{
//
// Normalizing Collector Path ...
if (IsValid(value))
{
mPath = value;
}
else
{
mPath = "XCXCAEADataCollector";
}
}
//
// Tools ...
//
string GetFilePath(string fileName)
{
//
string result = "";
//
result =
//
mPath + "\\" + fileName + ".x121.log"
//
;
//
return result;
}
//
int GetFileHandlerForWrite(string filePath)
{
//
int result = INVALID_HANDLE;
//
if (!IsValid(filePath))
{
return result;
}
//
result = FileOpen(
filePath,
FILE_READ | FILE_WRITE | FILE_TXT //
);
//
return result;
}
/**
* Save Specified Content into Specified File Name ...
*
* @param fileName: string, file name ...
* @param content: string, content ...
*
* @return ( bool )
*/
bool Save(
string fileName,
string content //
)
{
//
bool result = false;
//
result = IsValid(content);
if (!result)
{
return result;
}
//
//
int mHandler = GetFileHandlerForWrite(fileName);
result = mHandler != INVALID_HANDLE;
if (!result)
{
return result;
}
//
FileWrite(mHandler, content);
FileFlush(mHandler);
FileClose(mHandler);
//
return result;
}
//
// Protected ...
protected:
//
// Private ...
private:
//
// Props ...
//
string mPath; // Base Collector Path ...
};
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+955
View File
@@ -0,0 +1,955 @@
//
// Detect Trigger Block ...
bool DetectTriggerBlock(
//
string symbol,
ENUM_TIMEFRAMES period,
//
XTriggerBlock &tb,
//
XCBarAnalyser *barAnalyser,
//
// Required Buffers ...
const double &_atrBuffer[],
const double &_rsiBuffer[],
const double &_adxBuffer[],
const double &_adxpBuffer[],
const double &_adxnBuffer[],
const double &_peakBuffer[],
const double &_valeBuffer[],
const double &_deltaBuffer[],
const double &_sarBuffer[],
const double &_sarStateBuffer[],
const double &_trendBuffer[],
const double &_trendStateBuffer[],
const double &_atrUpperBuffer[],
const double &_atrLowerBuffer[],
const double &_sBarOpenSBuffer[],
const double &_sBarCloseBuffer[],
const double &_hkSBarOpenBuffer[],
const double &_hkSBarCloseBuffer[],
const double &_peakGoldenBuffer[],
const double &_valeGoldenBuffer[],
const double &_deltaSignalBuffer[],
const double &_bullishVolumeSignalBuffer[],
const double &_bearishVolumeSignalBuffer[],
//
int barIndex,
//
int _r2r,
double _slAtrMultiplier,
//
// Configs ...
double _rsiOBLevel,
double _rsiOSLevel,
double _adxThreshold,
//
// Validators ...
//
bool _forceOBBarType = false,
bool _forceFVGBarType = false,
bool _forceHasSwing = false,
bool _forceHasFLiquidity = false,
bool _forceHasRLiquidity = false,
bool _validateGapSequence = false,
bool _validateBlockEdgeBreakout = false,
//
// Filters ...
bool _filterBasedOnPV = false,
bool _filterBasedOnSar = false,
bool _filterBasedOnRSI = false,
bool _filterBasedOnADX = false,
bool _filterBasedOnATR = false,
bool _filterBasedOnTrend = false,
bool _filterBasedOnDelta = false,
bool _filterBasedOnVolume = false,
bool _filterBasedOnSignalBar = false,
bool _filterBasedOnHKSignalBar = false //
)
{
//
bool result = false;
//
// Custom Configs ...
// //
// _r2r = 2;
// _slAtrMultiplier = 1;
// //
// // Validators ...
// _forceHasSwing = true;
// _forceOBBarType = true;
// _forceFVGBarType = true;
// _validateGapSequence = true;
// //
// _forceHasFLiquidity = false;
// _forceHasRLiquidity = false;
// _validateBlockEdgeBreakout = true;
// //
// // Filters ...
// _filterBasedOnPV = true;
// _filterBasedOnATR = true;
// _filterBasedOnDelta = true;
// _filterBasedOnVolume = true;
// //
// _filterBasedOnSar = true;
// _filterBasedOnRSI = false;
// _filterBasedOnADX = false;
// _filterBasedOnTrend = false;
// _filterBasedOnSignalBar = true;
// _filterBasedOnHKSignalBar = true;
//
tb.Clean();
//
result = barAnalyser != NULL;
if (!result)
{
return result;
}
//
int zIDX = 0;
bool has = false;
bool isDone = false;
ENUM_X_DIRECTION iDir = X_DIRECTION_NONE;
//
// Retrieve Required Bars ...
//
XOHCL iBar;
XOHCL zBar; // Current Start Checking Bar (Usually Used for Triggering) ...
has = zBar.Init(
symbol,
period,
barIndex //
);
//
// Detect Based Order Block ...
has =
has &&
barAnalyser.IsOB(
zBar,
tb.ob,
_forceFVGBarType, // Force FVG Bar Type ...
_forceOBBarType // Force Block Two Bar Checking ...
);
//
// Detect Based Fair Value Gap ...
has =
has &&
barAnalyser.IsFVG(
zBar,
tb.fvg,
_forceFVGBarType // Force FVG Bar Type ...
);
//
// Clone Trigger Block ...
if (has)
{
//
tb.trigger = tb.ob;
tb.trigger.type = "XTRGB";
}
//
bool isBullish =
has &&
tb.IsBullish();
//
bool isBearish =
has &&
tb.IsBearish();
//
int toIDX = tb.ToIndex();
int fromIDX = tb.FromIndex();
//
// Verifications and Filters ...
//
int loopback = 144;
//
// Forces ...
//
// Force Has Proper Swing ...
if (has &&
_forceHasSwing)
{
//
XOHCL iPBar;
XOHCL iP2Bar;
toIDX = tb.ToIndex();
fromIDX = tb.FromIndex();
for (int i = toIDX; i <= fromIDX; i++)
{
//
// Initialize iBar ...
isDone = iBar.Init(
zBar.symbol,
zBar.period,
i //
);
isDone =
isDone &&
iBar.GetPreviousBar(iPBar);
isDone =
isDone &&
iPBar.GetPreviousBar(iP2Bar);
isDone =
isDone &&
barAnalyser.IsSimpleSwing(
iBar,
iDir //
) &&
iDir == tb.GetDirection();
if (isDone)
{
//
bool canSet =
!tb.swingBar.IsValid()
? true
: (isBullish
? tb.swingBar.low > iP2Bar.low
: tb.swingBar.high < iP2Bar.high);
if (canSet)
{
tb.swingBar = iP2Bar;
}
}
//
iBar.Clean();
iPBar.Clean();
iP2Bar.Clean();
}
//
has = tb.swingBar.IsValid();
}
//
// Force Has Liquidity ...
// TODO: Add Validation based on Liquidities
// if necessary ...
if (has &&
(_forceHasFLiquidity ||
_forceHasRLiquidity))
{
//
toIDX = tb.ToIndex();
fromIDX = tb.FromIndex();
for (int i = toIDX; i < fromIDX + loopback; i++)
{
//
// Initialize iBar ...
isDone = iBar.Init(
zBar.symbol,
zBar.period,
i //
);
//
bool isRejected =
isDone &&
barAnalyser.IsRejected(
iBar,
iDir,
false, // Force Bar Type ...
true // Force Fibo Pressure ...
);
//
// Following Liquidity ...
bool isFLiq =
isDone &&
isRejected &&
iDir == tb.GetDirection() &&
(isBullish
? iBar.low < tb.trigger.lower
: iBar.high > tb.trigger.upper);
if (isFLiq &&
_forceHasFLiquidity &&
!tb.fLiquidity.IsValid())
{
//
FillLiquidity(
iBar,
iDir,
tb.fLiquidity,
tb.trigger.to //
);
}
//
// Reversal Liquidity ...
bool isRLiq =
isDone &&
isRejected &&
Opposit(iDir) == tb.GetDirection() &&
(isBullish
? iBar.low > tb.trigger.upper
: iBar.high < tb.trigger.lower);
if (isRLiq &&
_forceHasRLiquidity &&
!tb.rLiquidity.IsValid())
{
//
FillLiquidity(
iBar,
iDir,
tb.rLiquidity,
tb.trigger.to //
);
}
//
// Checking Conditions ...
isDone =
(!_forceHasFLiquidity
? true
: tb.fLiquidity.IsValid()) &&
(!_forceHasRLiquidity
? true
: tb.rLiquidity.IsValid());
if (isDone)
{
//
iBar.Clean();
break;
}
//
iBar.Clean();
}
//
// Checking Conditions ...
has =
(!_forceHasFLiquidity
? true
: tb.fLiquidity.IsValid()) &&
(!_forceHasRLiquidity
? true
: tb.rLiquidity.IsValid());
}
//
// Validations ...
//
// Validating Gap Sequence means
// Gap Bars must Follow each Other ...
if (has &&
_validateGapSequence)
{
//
XOHCL iPBar;
toIDX = tb.fvg.ToIndex();
fromIDX = tb.fvg.FromIndex();
//
for (int i = toIDX; i < fromIDX - 1; i++)
{
//
// Initialize iBar ...
has = iBar.Init(
zBar.symbol,
zBar.period,
i //
);
has =
has &&
iBar.GetPreviousBar(iPBar);
has =
has &&
(isBullish
? iBar.low > iPBar.low
: iBar.high < iPBar.high);
if (!has)
{
break;
}
}
//
iBar.Clean();
iPBar.Clean();
}
//
// Validate Block Edge Breakout ...
if (has &&
_validateBlockEdgeBreakout)
{
//
has = tb.fvg.ToBar(iBar);
has =
has &&
(isBullish
? (iBar.GetDown() < tb.ob.upper &&
iBar.GetUp() > tb.ob.upper)
: (iBar.GetDown() < tb.ob.lower &&
iBar.GetUp() > tb.ob.lower));
//
iBar.Clean();
}
//
// Filters ...
//
// PV ...
if (has &&
_filterBasedOnPV)
{
//
double iPeak = _peakBuffer[barIndex];
double iPPeak = _peakBuffer[barIndex + 1];
double iP2Peak = _peakBuffer[barIndex + 2];
//
double iPeakGolden = _peakGoldenBuffer[barIndex];
double iPPeakGolden = _peakGoldenBuffer[barIndex + 1];
double iP2PeakGolden = _peakGoldenBuffer[barIndex + 2];
//
double iVale = _valeBuffer[barIndex];
double iPVale = _valeBuffer[barIndex + 1];
double iP2Vale = _valeBuffer[barIndex + 2];
//
double iValeGolden = _valeGoldenBuffer[barIndex];
double iPValeGolden = _valeGoldenBuffer[barIndex + 1];
double iP2ValeGolden = _valeGoldenBuffer[barIndex + 2];
//
// TODO: Fix this ...
has =
has &&
(isBullish
? (tb.trigger.lower <= iVale &&
tb.trigger.upper < iPeak
// || tb.trigger.lower <= iValeGolden
)
: (tb.trigger.upper >= iPeak &&
tb.trigger.lower > iVale
// || tb.trigger.upper >= iPeakGolden
));
}
//
// SAR ...
if (has &&
_filterBasedOnSar)
{
//
double iSarState = _sarStateBuffer[barIndex];
double iPSarState = _sarStateBuffer[barIndex + 1];
double iP2SarState = _sarStateBuffer[barIndex + 2];
//
bool isSarBullish = iSarState > 0;
bool isPSarBullish = iPSarState > 0;
bool isP2SarBullish = iP2SarState > 0;
//
bool isSarBearish = iSarState < 0;
bool isPSarBearish = iPSarState < 0;
bool isP2SarBearish = iP2SarState < 0;
//
bool isSarSwitchedToBullish =
isSarBullish &&
!isPSarBullish;
//
bool isSarSwitchedToBearish =
isSarBearish &&
!isPSarBearish;
//
bool isSarPSwitchedToBullish =
isPSarBullish &&
!isP2SarBullish;
//
bool isSarPSwitchedToBearish =
isPSarBearish &&
!isP2SarBearish;
//
has =
has &&
(isBullish
? (isSarSwitchedToBullish ||
isSarPSwitchedToBullish)
: (isSarSwitchedToBearish ||
isSarPSwitchedToBearish));
}
//
// RSI ...
if (has &&
_filterBasedOnRSI)
{
//
double rsiTrend = (_rsiOBLevel + _rsiOSLevel) / 2;
//
double iRSI = _rsiBuffer[barIndex];
double iPRSI = _rsiBuffer[barIndex + 1];
double iP2RSI = _rsiBuffer[barIndex + 2];
//
bool isRSICrossedOverOS =
iRSI > _rsiOSLevel &&
iPRSI <= _rsiOSLevel;
//
bool isRSICrossedUnderOB =
iRSI < _rsiOBLevel &&
iPRSI >= _rsiOBLevel;
//
bool isPRSICrossedOverOS =
iPRSI > _rsiOSLevel &&
iP2RSI <= _rsiOSLevel;
//
bool isPRSICrossedUnderOB =
iPRSI < _rsiOBLevel &&
iP2RSI >= _rsiOBLevel;
//
has =
has &&
(isBullish
? (isRSICrossedOverOS ||
isPRSICrossedOverOS)
: (isRSICrossedUnderOB ||
isPRSICrossedUnderOB));
}
//
// ADX ...
if (has &&
_filterBasedOnADX)
{
//
// ADX ...
double iADX = _adxBuffer[barIndex];
double iPADX = _adxBuffer[barIndex + 1];
double iP2ADX = _adxBuffer[barIndex + 2];
//
// ADX +DI ...
double iADXP = _adxpBuffer[barIndex];
double iPADXP = _adxpBuffer[barIndex + 1];
double iP2ADXP = _adxpBuffer[barIndex + 2];
//
// ADX -DI ...
double iADXN = _adxnBuffer[barIndex];
double iPADXN = _adxnBuffer[barIndex + 1];
double iP2ADXN = _adxnBuffer[barIndex + 2];
//
// Preparing Conditions ...
//
bool isADXBullish = iADX > _adxThreshold;
bool isADXBearish = iADX < _adxThreshold;
//
bool isPADXBullish = iPADX > _adxThreshold;
bool isPADXBearish = iPADX < _adxThreshold;
//
bool isP2ADXBullish = iP2ADX > _adxThreshold;
bool isP2ADXBearish = iP2ADX < _adxThreshold;
//
bool isADXSwitchedToBullish =
isADXBullish &&
!isPADXBullish;
//
bool isADXSwitchedToBearish =
isADXBearish &&
!isPADXBearish;
//
bool isPADXSwitchedToBullish =
isPADXBullish &&
!isP2ADXBullish;
//
bool isPADXSwitchedToBearish =
isPADXBearish &&
!isP2ADXBearish;
//
has =
has &&
(isBullish
? (isADXSwitchedToBullish ||
isPADXSwitchedToBullish)
: (isADXSwitchedToBearish ||
isPADXSwitchedToBearish));
}
//
// ATR ...
if (has &&
_filterBasedOnATR)
{
//
fromIDX = tb.FromIndex();
double iATRUpper = _atrUpperBuffer[fromIDX];
double iATRLower = _atrLowerBuffer[fromIDX];
//
has =
has &&
(isBullish
? tb.trigger.lower < iATRLower
: tb.trigger.upper > iATRUpper);
}
//
// TREND ...
if (has &&
_filterBasedOnTrend)
{
//
double iTrendState = _trendStateBuffer[barIndex];
double iPTrendState = _trendStateBuffer[barIndex + 1];
//
bool isTrendBullish = iTrendState > 0;
bool isPTrendBullish = iPTrendState > 0;
//
bool isTrendBearish = iTrendState < 0;
bool isPTrendBearish = iPTrendState < 0;
//
double trends[];
int toIDX = tb.ToIndex();
int fromIDX = tb.FromIndex();
double iTrend = _trendBuffer[toIDX];
for (int i = toIDX; i <= fromIDX; i++)
{
//
Add(
_trendBuffer[i],
trends //
);
}
double trendsMin = GetMin(trends);
double trendsMax = GetMax(trends);
double trendsAVG = GetAverage(trends);
//
bool isTrendUp =
iTrend > trendsMin &&
iTrend >= trendsAVG;
//
bool isTrendDown =
iTrend < trendsMax &&
iTrend <= trendsAVG;
//
bool isTrendSwitchedToBullish =
isTrendUp &&
isTrendBullish &&
!isPTrendBullish;
//
bool isTrendSwitchedToBearish =
isTrendDown &&
isTrendBearish &&
!isPTrendBearish;
//
has =
has &&
(isBullish
? isTrendSwitchedToBullish
: isTrendSwitchedToBearish);
}
//
// DELTA ...
if (has &&
_filterBasedOnDelta)
{
//
double iDelta = _deltaBuffer[barIndex];
double iPDelta = _deltaBuffer[barIndex + 1];
//
bool isDeltaUp = iDelta > iPDelta;
bool isDeltaDown = iDelta < iPDelta;
//
double iDeltaSignal = _deltaSignalBuffer[barIndex];
double iPDeltaSignal = _deltaSignalBuffer[barIndex + 1];
//
bool isDeltaSignalUp = iDeltaSignal > iPDeltaSignal;
bool isDeltaSignalDown = iDeltaSignal < iPDeltaSignal;
//
bool isDeltaSwitchedToBullish =
isDeltaUp &&
isDeltaSignalUp &&
iDelta > iDeltaSignal &&
iPDelta < iPDeltaSignal;
//
bool isDeltaSwitchedToBearish =
isDeltaDown &&
isDeltaSignalDown &&
iDelta < iDeltaSignal &&
iPDelta > iPDeltaSignal;
//
has =
has &&
(isBullish
? isDeltaSwitchedToBullish
: isDeltaSwitchedToBearish);
}
//
// VOLUME ...
if (has &&
_filterBasedOnVolume)
{
//
double iBullishVolumeSignal = _bullishVolumeSignalBuffer[barIndex];
double iPBullishVolumeSignal = _bullishVolumeSignalBuffer[barIndex + 1];
//
bool isBullishVolumeSignalUp = iBullishVolumeSignal > iPBullishVolumeSignal;
bool isBullishVolumeSignalDown = iBullishVolumeSignal < iPBullishVolumeSignal;
//
double iBearishVolumeSignal = _bearishVolumeSignalBuffer[barIndex];
double iPBearishVolumeSignal = _bearishVolumeSignalBuffer[barIndex + 1];
//
bool isBearishVolumeSignalUp = iBearishVolumeSignal > iPBearishVolumeSignal;
bool isBearishVolumeSignalDown = iBearishVolumeSignal < iPBearishVolumeSignal;
//
bool isVolumeSwitchdToBullish =
isBullishVolumeSignalUp &&
!isBearishVolumeSignalUp &&
iBullishVolumeSignal > iBearishVolumeSignal &&
iPBullishVolumeSignal < iPBearishVolumeSignal;
//
bool isVolumeSwitchdToBearish =
isBearishVolumeSignalUp &&
!isBullishVolumeSignalUp &&
iBearishVolumeSignal > iBullishVolumeSignal &&
iPBearishVolumeSignal < iPBullishVolumeSignal;
//
has =
has &&
(isBullish
? isVolumeSwitchdToBullish
: isVolumeSwitchdToBearish);
}
//
// SIGNAL Bar ...
if (has &&
_filterBasedOnSignalBar)
{
//
double iSignalOpen = _sBarOpenSBuffer[barIndex];
double iPSignalOpen = _sBarOpenSBuffer[barIndex + 1];
//
double iSignalClose = _sBarCloseBuffer[barIndex];
double iPSignalClose = _sBarCloseBuffer[barIndex + 1];
//
bool isSignalBarBullish = iSignalOpen < iSignalClose;
bool isPSignalBarBullish = iPSignalOpen < iPSignalClose;
//
bool isSignalBarBearish = iSignalOpen > iSignalClose;
bool isPSignalBarBearish = iPSignalOpen > iPSignalClose;
//
bool isSignalBarSwitchedToBullish =
isSignalBarBullish &&
!isPSignalBarBullish;
//
bool isSignalBarSwitchedToBearish =
isSignalBarBearish &&
!isPSignalBarBearish;
//
has =
has &&
(isBullish
? isSignalBarSwitchedToBullish
: isSignalBarSwitchedToBearish);
}
//
// HK SIGNAL Bar ...
if (has &&
_filterBasedOnHKSignalBar)
{
//
double iHKSignalOpen = _hkSBarOpenBuffer[barIndex];
double iPHKSignalOpen = _hkSBarOpenBuffer[barIndex + 1];
//
double iHKSignalClose = _hkSBarCloseBuffer[barIndex];
double iPHKSignalClose = _hkSBarCloseBuffer[barIndex + 1];
//
bool isHKSignalBarBullish = iHKSignalOpen < iHKSignalClose;
bool isPHKSignalBarBullish = iPHKSignalOpen < iPHKSignalClose;
//
bool isHKSignalBarBearish = iHKSignalOpen > iHKSignalClose;
bool isPHKSignalBarBearish = iPHKSignalOpen > iPHKSignalClose;
//
bool isHKSignalBarSwitchedToBullish =
isHKSignalBarBullish &&
!isPHKSignalBarBullish;
//
bool isHKSignalBarSwitchedToBearish =
isHKSignalBarBearish &&
!isPHKSignalBarBearish;
//
has =
has &&
(isBullish
? isHKSignalBarSwitchedToBullish
: isHKSignalBarSwitchedToBearish);
}
//
// Valdating Directional Trending ...
bool _filterBasedOnDirection = false;
if (has &&
_filterBasedOnDirection)
{
//
iBar.Clean();
fromIDX = tb.FromIndex();
int loopbackForValidating = 30;
for (int i = fromIDX; i < fromIDX + loopbackForValidating; i++)
{
//
// Initialize iBar ...
iBar.Clean();
has = iBar.Init(
symbol,
period,
i //
);
//
has =
has &&
(isBullish
? iBar.high < tb.trigger.upper
: iBar.low > tb.trigger.lower);
if (!has)
{
break;
}
}
//
// Update Trigger Block ...
if (has)
{
tb.trigger.from = iBar.time;
}
//
iBar.Clean();
}
//
// Preparing Signal ...
if (has)
{
//
// CArrayObj *tbObjects = new CArrayObj();
// DrawTriggerBlock(
// tb,
// drawer,
// tbObjects,
// NULL //
// );
//
double targets[];
for (int i = 1; i <= _r2r; i++)
{
//
Add(
(double)i,
targets //
);
}
//
double iATR = 0;
if (barIndex > 0 &&
barIndex < ArraySize(_atrBuffer))
{
iATR = _atrBuffer[barIndex];
}
double slAdditional = _slAtrMultiplier * iATR;
//
has = ToSignal(
tb.trigger,
tb.signal,
targets,
slAdditional //
);
}
//
result = has;
//
return result;
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,961 @@
///////////////////////////////////////////////////////
//
// SaherElm IT Center XCAEA 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
input ENUM_TIMEFRAMES eaAnalysisPeriod = PERIOD_H1; // Analysis Period
//
// Symbols ...
//
// -------------------------------------------------------
// ----------
// eaSymbols:
// ----------
// - if EMPTY use Current Symbol;
// - for Multi Symbol use Comma Separated Symbols:
// EURUSDb,XAUUSDb
//
// ------------------
// eaSymbolSessions:
// ------------------
// - if EMPTY use WHOLE Times;
// - for each Symbol use Comma Separated:
// (XEURS1_02:00_14:00),(XEURS2_19:00_23:00)|
// -------------------------------------------------------
input group "Symbols";
input string eaSymbols = ""; // Symbols Description
input string eaSymbolSessions = ""; // Symbols Sessions
//
// 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 ...
input group "Management";
input bool eaAllowTrade = true; // Allow Trade on Signals
input bool eaAllowLongs = true; // Allow Long Trades
input bool eaAllowShorts = true; // Allow Short Trades
input ENUM_XCAEA_TRADE_RESTRICTION_PERIOD eaRestrictionsPeriod = XCAEA_TRADE_RESTRICATION_DAILY; // Trade Restrictions Period
input int eaMaxAllowedTPs = 2; // Max Allowed TP(s) per Day
input int eaMaxAllowedSLs = 2; // Max Allowed SL(s) per Day
input int eaMaxAllowedTrades = 3; // Max Allowed Trades per Day
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 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
input bool eaReportTrades = true; // Report Trades
input bool eaReportSignals = true; // Report Signals
input bool eaReportProtector = true; // Report Protector Actions
input bool eaReportAfterTradesBalance = true; // Report Balance after a Trade Finished
//
// Variables, Instances ...
XCAlert *eaAlert;
XCTrade *eaTrade;
XSignal eaSignal;
XCVolume *eaVolume;
XTimeTracker eaTimeTracker;
XCXCAEASignaller *eaSignallers[];
XCXCAEATradeManager *eaTradeManager;
XCAEAStrategyConditions eaConditions;
//
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);
//
eaSignal.Clean();
eaConditions.Clean();
eaTimeTracker.Clean();
//
int count = ArraySize(eaSignallers);
for (int i = 0; i < count; i++)
{
//
eaSignallers[i].DeInit();
ZeroMemory(eaSignallers[i]);
}
Clean(eaSignallers);
//
DestroyTimer();
}
//
// On Tick Handler ...
void OnTick()
{
//
int idx = -1;
int count = 0;
bool has = false;
//
HandleTimeReport();
//
// Handle Position Management / Protections ...
eaTradeManager.Manage();
//
eaSignal.Clean();
eaConditions.Clean();
//
double r2r = 4;
string provider = "XCAEA";
datetime cTime = TimeCurrent();
ENUM_POSITION_TYPE type = POSITION_TYPE_BUY;
ENUM_X_ORDER_MODES mode = X_ORDER_MODE_MARKET;
//
bool hasLong = false;
bool hasShort = false;
//
// Checking Signallers ...
has = HasChild(eaSignallers);
if (!has)
{
return;
}
//
int signallersCount = ArraySize(eaSignallers);
for (int is = 0; is < signallersCount; is++)
{
//
// Start Calculations ...
//
// Retrieve Common Data ...
string symbol = eaSignallers[is].GetSymbol();
ENUM_TIMEFRAMES period = eaSignallers[is].GetPeriod();
//
// Required Value For SL/TP Calculations ...
double points = GetPoints(symbol);
double pip = GetPipPrice(symbol);
double pip2 = 2 * pip;
//
// Detect Signal Setups ...
has = eaSignallers[is].DetectSignalSetup(r2r);
if (has)
{
//
count = eaSignallers[is]
.AddConditionsIfNotExists();
//
eaSignallers[is].mConditions.Clean();
}
//
// Check Setuped Conditions Exists ...
count = ArraySize(eaSignallers[is].mConditionsCollection);
has = IsValidSize(count);
if (!has)
{
continue;
}
//
// Loop through Setuped Conditions for
// Validating or Looking up Triggers ...
for (int i = 0; i < count; i++)
{
//
// Check Signal Triggered or not ...
has = eaSignallers[is]
.DetectSignalTrigger(eaSignallers[is]
.mConditionsCollection[i]);
//
// If Triggered ...
if (has)
{
//
idx = i;
eaConditions = eaSignallers[is].mConditionsCollection[i];
break;
}
//
// Check Condition Validation ...
has = eaSignallers[is].mConditionsCollection[i].IsValid() &&
eaSignallers[is].mConditionsCollection[i].IsSetuped();
if (!has)
{
idx = i;
break;
}
}
//
// Remove Setuped Condition if provided IDX ...
has = IsValidIndex(idx);
if (has)
{
//
ArrayRemove(
eaSignallers[is].mConditionsCollection,
idx,
1 //
);
}
//
// Check EA Conditions is Valid or not ...
has = eaConditions.IsSetuped() &&
eaConditions.CanTrigger();
if (!has)
{
//
eaSignal.Clean();
eaConditions.Clean();
//
continue;
}
//
// Setting Time to Conditions ...
eaConditions.time = cTime;
has = ToPositionType(
type,
eaConditions.type //
);
if (!has)
{
//
eaSignal.Clean();
eaConditions.Clean();
//
continue;
}
//
// Checking Trigger Direction ...
hasLong = eaConditions.HasBullishSignal();
hasShort = eaConditions.HasBearishSignal();
has = hasLong ||
hasShort;
if (!has)
{
//
eaSignal.Clean();
eaConditions.Clean();
//
continue;
}
//
// 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;
//
// Handling Targets ...
ApplyTargetsOnSignal(
eaConditions.dir,
eaConditions.targets,
eaSignal //
);
//
// Validate Signal ...
has = eaSignal.IsValid();
if (!has)
{
//
eaSignal.Clean();
eaConditions.Clean();
//
continue;
}
//
// Handle Volume Management ...
double iVolume = eaVolume.CalculateVolume(eaSignal);
if (iVolume > X_MIN_VOLUME &&
iVolume != eaSignal.volume)
{
eaSignal.volume = iVolume;
}
//
// Execute Signal ...
has = eaTradeManager.Execute(
eaSignal,
eaConditions //
);
//
eaSignal.Clean();
eaConditions.Clean();
}
}
//
// Handle On Trade Event ...
void OnTrade()
{
eaTrade.HandleOnTrade();
}
//
// 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 Position Partially Closed Event ...
*
* @param ticket: ULONG ...
* @param profit: double ...
* @param comment: string ...
*/
void OnPositionPartiallyClosed(
const ulong ticket,
const double profit,
const string comment //
)
{
eaTradeManager.HandlePartiallyClosed(
ticket,
profit,
comment //
);
}
/**
* 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);
eaTrade.AddOnPartialClosePositionEventHandler(OnPositionPartiallyClosed);
//
// EA Trae Manager ...
eaTradeManager = new XCXCAEATradeManager(
eaTrade //
);
eaTradeManager.SaveTrades(true);
eaTradeManager.SetAlertEnableAlerts(eaEnableAlerts);
eaTradeManager.SetAlertPrefix(eaTag);
eaTradeManager.SetAlertLogAlerts(eaLogAlerts);
eaTradeManager.SetAlertMailAlerts(eaMailAlerts);
eaTradeManager.SetAlertPushAlerts(eaPushAlerts);
eaTradeManager.SetAlertTerminalAlerts(eaTerminalAlerts);
//
// Setting Trade Reports ...
eaTradeManager
.SetTradeReports(
eaReportTrades,
eaReportSignals,
eaReportProtector,
eaReportAfterTradesBalance //
);
//
// Setting Trade Permissions ...
eaTradeManager
.SetTradePermissions(
eaAllowTrade,
eaAllowLongs,
eaAllowShorts //
);
//
// Setting Trade Restrictions ...
eaTradeManager
.SetTradeRestrictions(
eaRestrictionsPeriod,
eaMaxAllowedTPs,
eaMaxAllowedSLs,
eaMaxAllowedTrades //
);
//
InitSymbolSessions();
//
}
/**
* Initial Symbols and Active Sessions of EA ...
*/
void InitSymbolSessions()
{
//
string symbols[];
string sessions[];
string iSymbol = NULL;
XCXCAEASignaller *iSignaller;
//
// Parse Symbols ...
int symbolsCount = 0;
bool isMultiSymbol = IsValid(eaSymbols);
if (isMultiSymbol)
{
//
symbolsCount = SplitContent(
symbols,
eaSymbols //
);
isMultiSymbol = IsValidSize(symbolsCount);
}
if (!isMultiSymbol)
{
//
Add(
_Symbol,
symbols //
);
//
symbolsCount = 1;
}
//
// Parse Sessions ...
int sessionsCount = 0;
bool hasSession = IsValid(eaSymbolSessions);
if (hasSession)
{
//
// Extract Per Symbol Sessions ...
sessionsCount = SplitContent(
sessions,
eaSymbolSessions,
"|" //
);
}
//
// Setting Up Symbols ...
bool has = false;
//
for (int i = 0; i < symbolsCount; i++)
{
//
iSymbol = symbols[i];
//
// EA Signaller ...
iSignaller = new XCXCAEASignaller(
iSymbol,
_Period,
eaAnalysisPeriod // Analysing Period ...
);
//
Add(
iSignaller,
eaSignallers //
);
//
ZeroMemory(iSignaller);
}
//
// Setting Up Sessions ...
if (hasSession)
{
//
for (int i = 0; i < symbolsCount; i++)
{
//
iSymbol = symbols[i];
//
if (i < sessionsCount)
{
//
// Extract Per Symbol Sessions ...
string iSymbolSessionsStr[];
int iSymbolSessionsCount = SplitContent(
iSymbolSessionsStr,
sessions[i],
"," //
);
//
has = IsValidSize(iSymbolSessionsCount);
if (has)
{
//
// Loop through Symbols Sessions ...
for (int j = 0; j < iSymbolSessionsCount; j++)
{
//
string iSessionDescriptorStr = ExtractString(iSymbolSessionsStr[j]);
has = IsValid(iSessionDescriptorStr);
if (has)
{
//
// Extract Session Descriptor Data ...
string parts[];
int partsCount = SplitContent(
parts,
iSessionDescriptorStr,
"_" //
);
has = IsValidSize(partsCount) && partsCount == 3;
if (has)
{
//
string iName = parts[0];
string iStart = parts[1];
string iEnd = parts[2];
has = IsValid(iName) &&
IsValid(iStart) &&
IsValid(iEnd);
if (has)
{
//
eaTradeManager
.SetTradeSession(
iSymbol,
iStart,
iEnd,
iName //
);
}
}
//
Clean(parts);
}
}
}
//
Clean(iSymbolSessionsStr);
}
}
}
//
Clean(symbols);
Clean(sessions);
ZeroMemory(iSignaller);
}
/**
* Handling Time Reporting ...
*/
void HandleTimeReport()
{
//
// Monthly Report ....
if (eaReportNewMonths &&
eaTimeTracker.IsNewMonth())
{
//
string msg = "New Month ...";
//
eaAlert.SendAlert(msg);
}
//
// Weekly Report ....
if (eaReportNewWeeks &&
eaTimeTracker.IsNewWeek())
{
//
string msg = "New Week ...";
//
eaAlert.SendAlert(msg);
}
//
// Daily Report ....
if (eaReportNewDays &&
eaTimeTracker.IsNewDay())
{
//
string msg = "New Day ...";
//
eaAlert.SendAlert(msg);
}
//
// Hourly Report ....
if (eaReportNewHours &&
eaTimeTracker.IsNewHour())
{
//
string msg = "New Hour ...";
//
eaAlert.SendAlert(msg);
}
}
//