Initial Commit ...

This commit is contained in:
2024-01-25 04:05:58 +03:30
commit dac3101466
520 changed files with 186332 additions and 0 deletions
+839
View File
@@ -0,0 +1,839 @@
///////////////////////////////////////////////////////
//
// SaherElm IT Center XST Strategy Expert Advisor
// ---------------------------------------------
// saherelm implementation of strategy expert advisor ...
// in this EA, we try to combine multiple tools, to ashive best
// results ...
//
// ShortName: XST
//
// Maintainer:
// ------------
// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com)
// +989121694056
//
//////////////////////////////////////////////////////
//
// Global Properties ...
#property copyright "Copyright 2023, SaherElm IT Center"
#property link "https://saherelm.ir"
#property version "1.00"
#property description "SaherElm XST Strategy Expert Advisor"
#property strict
//
// START Inputs ...
//
//
// Signal Prefixe ...
input string signalPrefix = "XST"; // Signal Prefix
//
// Signal Draw Specifications ...
input string bullishSignalLabel = "X_BUY"; // Bullish Signal Label
input color bullishSignalColor = clrAqua; // Bullish Signal Color
//
input string bearishSignalLabel = "X_SELL"; // Bearish Signal Label
input color bearishSignalColor = clrFuchsia; // Bearish Signal Color
//
input color signalEntryColor = clrAquamarine; // Signal Entry Ptice Color
input color signalSLColor = clrRed; // Signal SL Color
input color signalTPColor = clrGreen; // Signal TP Color
//
// Trade ...
input bool allowTrade = true; // Allow Trade Based on given Signals
input bool allowLongTrades = true; // Allow Long Trades
input bool allowShortTrades = false; // Allow Short Trades
//
// Market Specification Inpouts ...
input int marketLength = 7; // Market Length
input double riskToRewardRatio = 2; // Risk to Reward Ratio
// input double maxTPMultiplier = 1000; // Max Allowed TP
//
// Alerts ...
input bool alertEvents = true; // Alert Events
input bool alertPositions = true; // Alert Positions
input bool longPositionAlerts = true; // Alert Long Positions
input bool shortPositionAlerts = true; // Alert Short Positions
//
// Alert Types ...
input bool terminalAlert = false; // Terminal Alert
input bool pushAlert = false; // Push Notification Alerts
//
// Balance and Finanical Specifications ...
input double lotsPerTradePercent = 0.00001; // Lots Per Trade Percent
input int maxOpenTrades = 4; // Maximum Open Trade
input double maxDrawdownPercentPerPTrade = 0.03; // Maximum DrawDown Per Trade
input double minBalancePercent = 0.5; // Minimum Balance for Trading
input double maxEquityPercent = 0.1; // Maximum Trade Equity
input int closeAllOpenTradesAfterCandle = 252; // Close All Open Trades After Passed Candles
input bool closeAllInProfitOpenTradesWhenMaxOpenTradesReached = false; // Close All In Profit Open Trades When Max Open Trades Reached and New Signal Income
//
// Indicators ...
//
// CCI Inputs ...
input double step = 0.01; // SAR Step
input double maximum = 0.1; // SAR Maximum
//
// XMA Inputs ...
//
input int shortCycleMultiplier = 2; // Short Cycle Fast Multiplier
input int mediumCycleMultiplier = 6; // Medium Cycle Fast Multiplier
input int longCycleMultiplier = 36; // Long Cycle Fast Multiplier
//
// START Global Definitions: Variables, Properties and etc ...
//
int lastSignalledBar = 0;
//
bool waitForLongSignals = true;
bool closeLongTrades = false;
//
bool waitForShortSignals = true;
bool closeShortTrades = false;
//
// Includes our shared library ...
#include "../Libraries/x-saherelm.lib.mq4"
//
// Includes our shared library ...
#include "../Libraries/x-saherelm.signal.lib.mq4"
//
// END Global Definitions: Variables, Properties and etc ...
//
//
// Start Event Handlers ...
//
//
// Initialization ...
int OnInit() {
//
// Validate Inputs ...
bool inputsNotValiid =
//
// MARKET ...
marketLength < 0
|| riskToRewardRatio < 0
//
// EA ...
|| lotsPerTradePercent < 0
|| maxOpenTrades <= 0
|| maxDrawdownPercentPerPTrade < 0
|| minBalancePercent < 0
|| maxEquityPercent < 0
|| marketLength < 0
//
// XMA ...
//
// Validate Short Cycle ...
|| shortCycleMultiplier <= 0
//
// Validate Medium Cycle ...
|| mediumCycleMultiplier <= 0
//
// Validate Long Cycle ...
|| longCycleMultiplier <= 0
//
// Validate Series of Multipliers ...
|| shortCycleMultiplier >= mediumCycleMultiplier
|| mediumCycleMultiplier >= longCycleMultiplier
;
//
if (inputsNotValiid) {
return INIT_PARAMETERS_INCORRECT;
}
//
totalSignals = 0;
totalLongSignals = 0;
totalShortSignals = 0;
//
initialBalance = 0;
//
// START Define Array Series ...
//
//
// END Define Array Series ...
//
//
// here we specify logging enabled or not ...
enableLogging = true;
//
// this is a Tag which attached to our Logger ...
logTag = "XST";
// //
// // Set Event Timer on One Seccond ...
// bool isEventSet = EventSetTimer(1);
// if (!isEventSet) {
// LogMessage("Error: " + GetLastError());
// return INIT_FAILED;
// }
//
ClearSignalConditions();
//
return INIT_SUCCEEDED;
}
//
// DeInitialization ...
void OnDeinit(const int reason) {
//
// Killing Event Timer ...
EventKillTimer();
}
//
// Ticker Event Handler ...
void OnTick() {
//
isNewDay = IsNewDay();
if (isNewDay) {
//
LogMessage(
StringConcatenate(
"New Day ..."
)
);
}
//
// Process Signals to Open Positions ...
ProcessSignals();
//
// Checking State for Signal Handling ...
CheckState();
//
// Process Open Positions for Trailing Stop Loss or Close ...
ProcessOpenPositions();
}
//
// Timer Event Handler ...
void OnTimer() {
//
CheckState();
//
ProcessOpenPositions();
}
//
// END Event Handlers ...
//
//
// START Functions ...
//
//
// Check State for Signal Handling ...
void CheckState() {
//
// Here we Must to Check Market State for enable or disable
// Signal Handlers and also make dection to close all long/short
// trades ...
}
//
// Calculate Signals and Process Based on Exists Signals ...
void ProcessSignals() {
//
XSignalRequest request = {};
request.type = X_SIGNAL_NONE;
request.hasSignal = false;
//
// Prevent Multiple Calculating on Same Bars ...
isNewBar = IsNewBar();
if (isNewBar) {
countedBars++;
}
//
if (countedBars < longCycleMultiplier * marketLength) {
return;
}
//
bool allowDoTrade = true;
//
// Check Balance ...
if (initialBalance > 0) {
//
// Retrieve Account Balance ...
double balance = AccountInfoDouble(ACCOUNT_BALANCE);
double minimumBalanceForTrade =
balance > initialBalance
?
minBalancePercent * balance
:
minBalancePercent * initialBalance;
//
// Retrieve Account Equity ...
double equity = AccountInfoDouble(ACCOUNT_EQUITY);
double maxAllowedEquity = balance - (balance * maxEquityPercent);
//
// Retrieve Free Marigin ...
double freeMargin = AccountFreeMargin();
double maximumMariginRisk = balance - (balance * maxEquityPercent);
//
if (
//
// Do not Open Positions if equity not passed ...
equity < maxAllowedEquity ||
//
// Do not Open Positions if free margin not passed ...
freeMargin <= maximumMariginRisk ||
//
// Do not open positions if balance less than minimum ...
balance <= minimumBalanceForTrade
) {
//
allowDoTrade = false;
// //
// string message = StringConcatenate(
// "Trading Pause => ",
// "Balance: ", balance,
// ", Equity: ", equity,
// ", FreeMargin: ", freeMargin
// );
// //
// LogMessage(message);
// SendAlert(message);
}
}
//
// Retrieve Signal Exists ...
request = GenerateSignal(0);
//
// Prevent doing anything else, if there is no signals ...
if (
!allowDoTrade ||
!request.hasSignal ||
request.type == X_SIGNAL_NONE
) {
return;
}
//
bool hasLongSignal = request.type == X_SIGNAL_LONG;
//
// Check For Bot State ...
if (
(hasLongSignal && !waitForLongSignals)
|| (!hasLongSignal && !waitForShortSignals)
) {
//
// Clear Signal Conditions ...
if (hasLongSignal) {
ClearLongSignalConditions();
} else {
ClearShortSignalConditions();
}
//
return;
}
//
// Check last Signalled Bar with Counted Bars ...
// Prevent Multiple Signalling on Same Bar ...
bool isInLastSignalledBars = false;
for (int i=0; i < marketLength; i++) {
//
isInLastSignalledBars =
isInLastSignalledBars
|| lastSignalledBar == countedBars - i
;
}
if (isInLastSignalledBars) {
//
// Clear Signal Conditions ...
if (hasLongSignal) {
ClearLongSignalConditions();
} else {
ClearShortSignalConditions();
}
//
return;
}
//
// increase last signalled bar ...
lastSignalledBar = countedBars;
//
// Calculate Can Trade or not ...
allowDoTrade = allowTrade
&& (
hasLongSignal ?
allowLongTrades :
allowShortTrades
);
//
// Chack Maximum Open Positions ...
int openTrades = CountOpenTrades();
if (maxOpenTrades > 0) {
//
if (openTrades >= maxOpenTrades) {
//
allowDoTrade = false;
//
if (closeAllInProfitOpenTradesWhenMaxOpenTradesReached) {
//
// Close All In Profit Trades ...
bool hasClosedInProfitTrade = CloseAllInProfitTrades();
if (hasClosedInProfitTrade) {
//
openTrades = CountOpenTrades();
//
allowDoTrade = !(openTrades >= maxOpenTrades);
}
}
//
if (!allowDoTrade) {
//
string message = StringConcatenate(
"Trading Pause => ",
"Max Open Trades (",
maxOpenTrades,
") reached ..."
);
//
LogMessage(message);
SendAlert(message);
}
}
}
//
// Check Trading is Enable or not ...
// nothing to do if trading is disabled ...
if (!allowDoTrade) {
//
// Clear Signal Conditions ...
if (hasLongSignal) {
ClearLongSignalConditions();
} else {
ClearShortSignalConditions();
}
// //
// string message = StringConcatenate(
// "Trading Not Allowed ..."
// );
// //
// LogMessage(message);
// SendAlert(message);
return;
}
//
bool isPositionOpened = TradeSignal(
request.signal,
lotsPerTradePercent,
//
bullishSignalLabel,
bullishSignalColor,
bearishSignalLabel,
bearishSignalColor
);
//
totalSignals++;
if (hasLongSignal) {
//
totalLongSignals++;
ClearLongSignalConditions();
} else {
//
totalShortSignals++;
ClearShortSignalConditions();
}
// //
// if (isPositionOpened) {
// //
// int rangeMarketLength = marketLength * longCycleMultiplier;
// XRange range = GetMarketRange(
// 0,
// rangeMarketLength,
// marketLength
// );
// //
// DrawRange(
// range,
// 0,
// 0,
// signalPrefix
// );
// }
// //
// double fibLevel = 1.618;
// double fibLevelPrice = GetFibonacciLevel(
// request.signal.tp,
// request.signal.entry,
// fibLevel,
// 1
// );
// string lbl = StringConcatenate(
// request.signal.tag,
// "_FIB_",
// fibLevel,
// "_",
// fibLevelPrice
// );
// //
// datetime time1 = iTime(
// _Symbol,
// _Period,
// 1
// );
// //
// datetime time2 = iTime(
// _Symbol,
// _Period,
// 0
// );
// //
// DrawTrendLine(
// 0,
// lbl,
// 0,
// time1,
// fibLevelPrice,
// time2,
// fibLevelPrice,
// clrYellow,
// STYLE_DOT
// );
//
if (isPositionOpened) {
//
bool canAlert =
alertPositions
&& (
hasLongSignal ?
longPositionAlerts
:
shortPositionAlerts
);
//
if (canAlert) {
//
// Alert Message ...
string message = StringConcatenate(
"Trade on Signal ID: ", request.signal.id,
", Entry: ", request.signal.entry,
", TP: ", request.signal.tp
);
//
// Terminal Alert ...
if (terminalAlert) {
Alert(message);
}
//
// Push Alert ...
if (pushAlert) {
SendNotification(message);
}
}
}
}
//
// Process All Open Positions ...
void ProcessOpenPositions() {
//
// this comes from check state ...
if (closeLongTrades) {
//
closeLongTrades = false;
//
bool isAllLongTradesClosed = CloseAllLongTrades();
if (isAllLongTradesClosed) {
}
}
//
// this comes from check state ...
if (closeShortTrades) {
//
closeShortTrades = false;
//
bool isAllShortTradesClosed = CloseAllShortTrades();
if (isAllShortTradesClosed) {
}
}
//
// Close All XXX Provided Signals on it's Specific Condition ...
if (xCloseLongTrades) {
//
CloseAllProviderLongTrades(X_XXX_PROVIDER);
//
xCloseLongTrades = false;
}
//
bool hasClosedLongTimeTrade = CloseAllLongTimeTrades(
closeAllOpenTradesAfterCandle
);
//
// Close Maximum DrawDown Passed Trades ...
bool hasClosedInDrawDownLongTrade = CloseAllMaximumDrawDownPassedTrades(
maxDrawdownPercentPerPTrade
);
//
if (
hasClosedLongTimeTrade
|| hasClosedInDrawDownLongTrade
) {
//
// waitForLongSignals = false;
}
}
//
// Send Special Type of Alerts ...
void SendAlert(string message) {
//
if (!alertEvents) {
return;
}
//
// Terminal Alert ...
if (terminalAlert) {
Alert(message);
}
//
// Push Alert ...
if (pushAlert) {
SendNotification(message);
}
}
//
// END Functions ...
//
//
//
// Calculate Signal ...
// in this function we calculate a signal exists in
// specific bar or not ...
XSignalRequest GenerateSignal(
const int bar_index // Bar Index ...
) {
//
// create temp result ...
XSignalRequest result = {};
result.hasSignal = false;
result.type = X_SIGNAL_NONE;
result.provider = X_UNKNOWN_PROVIDER;
//
bool hasSignal = false;
bool hasLongSignal = false;
bool hasShortSignal = false;
//
XSignal signal = {};
//
// Retrieve XMA States ...
// based on medium cycle slow ...
XState states[];
ArrayFree(states);
ArrayResize(
states,
marketLength
);
//
int index = 0;
for (int i = bar_index; i < bar_index + marketLength; i++) {
//
states[index] = GetXState(
i,
marketLength,
//
step,
maximum,
//
shortCycleMultiplier,
mediumCycleMultiplier,
longCycleMultiplier
);
//
index++;
}
//
CheckSignalHandler(
bar_index,
marketLength,
states
);
//
CheckXLongSignalConditions(
bar_index,
marketLength,
states
);
//
XSignalRequest xLongSignalRequest = GenerateXSignal(
X_SIGNAL_LONG,
signalPrefix,
bar_index,
marketLength,
longCycleMultiplier,
riskToRewardRatio,
states
);
// //
// CheckXShortSignalConditions(
// bar_index,
// marketLength,
// states
// );
// //
// XSignalRequest xShortSignalRequest = GenerateXSignal(
// X_SIGNAL_SHORT,
// signalPrefix,
// bar_index,
// marketLength,
// longCycleMultiplier,
// riskToRewardRatio,
// states
// );
//
if (xLongSignalRequest.hasSignal) {
//
// Here we can Check and Filter Signals Based On State ...
bool isReady = IsReadyForXSignals(
xLongSignalRequest.signal,
states,
marketLength,
//
shortCycleMultiplier,
mediumCycleMultiplier,
longCycleMultiplier
);
//
if (isReady && xWaitForLongSignals) {
//
hasLongSignal = true;
signal = xLongSignalRequest.signal;
} else {
ClearXLongSignalConditions();
}
// } else if (xShortSignalRequest.hasSignal) {
// //
// // Here we can Check and Filter Signals Based On State ...
// bool isReady = IsReadyForXSignals(
// xShortSignalRequest.signal,
// states,
// marketLength,
// //
// shortCycleMultiplier,
// mediumCycleMultiplier,
// longCycleMultiplier
// );
// //
// if (isReady) {
// //
// hasShortSignal = true;
// signal = xShortSignalRequest.signal;
// } else {
// ClearXShortSignalConditions();
// }
}
//
hasSignal = hasLongSignal || hasShortSignal;
//
if (!hasSignal) {
//
signal.type = X_SIGNAL_NONE;
result.type = X_SIGNAL_NONE;
}
//
// Normalize TP, SL and Entry Price ...
signal.tp = NormalizeDouble(signal.tp, _Digits);
signal.sl = NormalizeDouble(signal.sl, _Digits);
signal.entry = NormalizeDouble(signal.entry, _Digits);
//
result.signal = signal;
result.type = signal.type;
result.hasSignal = hasSignal;
result.provider = signal.provider;
//
// Return Result ...
return result;
}
@@ -0,0 +1,720 @@
///////////////////////////////////////////////////////
//
// SaherElm IT Center XST Strategy Expert Advisor
// ---------------------------------------------
// saherelm implementation of strategy expert advisor ...
// in this EA, we try to combine multiple tools, to ashive best
// results ...
//
// ShortName: XST
//
// Maintainer:
// ------------
// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com)
// +989121694056
//
//////////////////////////////////////////////////////
//
// Global Properties ...
#property copyright "Copyright 2023, SaherElm IT Center"
#property link "https://saherelm.ir"
#property version "1.00"
#property description "SaherElm XST Strategy Expert Advisor"
#property strict
//
// START Inputs ...
//
//
// Signal Prefixe ...
input string signalPrefix = "XST"; // Signal Prefix
//
// Signal Draw Specifications ...
input string bullishSignalLabel = "X_BUY"; // Bullish Signal Label
input color bullishSignalColor = clrAqua; // Bullish Signal Color
//
input string bearishSignalLabel = "X_SELL"; // Bearish Signal Label
input color bearishSignalColor = clrFuchsia; // Bearish Signal Color
//
input color signalEntryColor = clrAquamarine; // Signal Entry Ptice Color
input color signalSLColor = clrRed; // Signal SL Color
input color signalTPColor = clrGreen; // Signal TP Color
//
input int candleGapBetweenSignals = 6; // How many Candle waits to new Signal from last one
//
// Trade ...
input bool allowTrade = true; // Allow Trade Based on given Signals
input bool allowLongTrades = true; // Allow Long Trades
input bool allowShortTrades = false; // Allow Short Trades
//
// Alerts ...
input bool alertEvents = true; // Alert Events
input bool alertPositions = true; // Alert Positions
input bool longPositionAlerts = true; // Alert Long Positions
input bool shortPositionAlerts = true; // Alert Short Positions
//
// Alert Types ...
input bool terminalAlert = false; // Terminal Alert
input bool pushAlert = false; // Push Notification Alerts
//
// Balance and Finanical Specifications ...
input double lotsPerTradePercent = 0.0003; // Lots Per Trade Percent
input int maxOpenTrades = 4; // Maximum Open Trade
input double maxDrawdownPercentPerPTrade = 0.3; // Maximum DrawDown Per Trade
input double minBalancePercent = 0.5; // Minimum Balance for Trading
input double maxEquityPercent = 0.1; // Maximum Trade Equity
input int closeAllOpenTradesAfterCandle = 252; // Close All Open Trades After Passed Candles
input bool closeAllInProfitOpenTradesWhenMaxOpenTradesReached = false; // Close All In Profit Open Trades When Max Open Trades Reached and New Signal Income
//
// START Global Definitions: Variables, Properties and etc ...
//
int lastSignalledBar = 0;
//
bool waitForLongSignals = true;
bool closeLongTrades = false;
//
bool waitForShortSignals = true;
bool closeShortTrades = false;
//
// Includes our shared library ...
#include "../Libraries/x-saherelm.lib.mq4"
//
// Includes our shared library ...
#include "../Libraries/x-saherelm.signal.lib.mq4"
//
int maxMarketLength = 0;
//
// END Global Definitions: Variables, Properties and etc ...
//
//
// Start Event Handlers ...
//
//
// Initialization ...
int OnInit() {
//
// Validate Inputs ...
bool inputsNotValiid =
//
// EA ...
lotsPerTradePercent < 0
|| maxOpenTrades <= 0
|| maxDrawdownPercentPerPTrade < 0
|| minBalancePercent < 0
|| maxEquityPercent < 0
;
//
if (inputsNotValiid) {
return INIT_PARAMETERS_INCORRECT;
}
//
totalSignals = 0;
totalLongSignals = 0;
totalShortSignals = 0;
//
initialBalance = 0;
//
// START Define Array Series ...
//
//
// END Define Array Series ...
//
//
// here we specify logging enabled or not ...
enableLogging = true;
//
// this is a Tag which attached to our Logger ...
logTag = "XST";
//
ClearSignalConditions();
//
maxMarketLength = MathMax(0, GetDailyCandleCount());
//
return INIT_SUCCEEDED;
}
//
// DeInitialization ...
void OnDeinit(const int reason) {
}
//
// Ticker Event Handler ...
void OnTick() {
//
isNewDay = IsNewDay();
if (isNewDay) {
//
LogMessage(
StringConcatenate(
"New Day ..."
)
);
}
//
// Process Signals to Open Positions ...
ProcessSignals();
//
// Checking State for Signal Handling ...
CheckState();
//
// Process Open Positions for Trailing Stop Loss or Close ...
ProcessOpenPositions();
}
//
// END Event Handlers ...
//
//
// START Functions ...
//
//
// Check State for Signal Handling ...
void CheckState() {
//
// Here we Must to Check Market State for enable or disable
// Signal Handlers and also make dection to close all long/short
// trades ...
}
//
// Calculate Signals and Process Based on Exists Signals ...
void ProcessSignals() {
//
XSignalRequest request = {};
request.type = X_SIGNAL_NONE;
request.hasSignal = false;
//
// Prevent Multiple Calculating on Same Bars ...
isNewBar = IsNewBar();
if (isNewBar) {
countedBars++;
}
//
if (countedBars < maxMarketLength) {
return;
}
//
bool allowDoTrade = true;
//
// Check Balance ...
if (initialBalance > 0) {
//
// Retrieve Account Balance ...
double balance = AccountInfoDouble(ACCOUNT_BALANCE);
double minimumBalanceForTrade =
balance > initialBalance
?
minBalancePercent * balance
:
minBalancePercent * initialBalance;
//
// Retrieve Account Equity ...
double equity = AccountInfoDouble(ACCOUNT_EQUITY);
double maxAllowedEquity = balance - (balance * maxEquityPercent);
//
// Retrieve Free Marigin ...
double freeMargin = AccountFreeMargin();
double maximumMariginRisk = balance - (balance * maxEquityPercent);
//
if (
//
// Do not Open Positions if equity not passed ...
equity < maxAllowedEquity ||
//
// Do not Open Positions if free margin not passed ...
freeMargin <= maximumMariginRisk ||
//
// Do not open positions if balance less than minimum ...
balance <= minimumBalanceForTrade
) {
//
allowDoTrade = false;
// //
// string message = StringConcatenate(
// "Trading Pause => ",
// "Balance: ", balance,
// ", Equity: ", equity,
// ", FreeMargin: ", freeMargin
// );
// //
// LogMessage(message);
// SendAlert(message);
}
}
//
// Retrieve Signal Exists ...
request = GenerateSignal(0);
//
// Prevent doing anything else, if there is no signals ...
if (
!allowDoTrade ||
!request.hasSignal ||
request.type == X_SIGNAL_NONE
) {
return;
}
//
bool hasLongSignal = request.type == X_SIGNAL_LONG;
//
// Check For Bot State ...
if (
(hasLongSignal && !waitForLongSignals)
|| (!hasLongSignal && !waitForShortSignals)
) {
//
// Clear Signal Conditions ...
if (hasLongSignal) {
ClearLongSignalConditions();
} else {
ClearShortSignalConditions();
}
//
return;
}
//
// Check last Signalled Bar with Counted Bars ...
// Prevent Multiple Signalling on Same Bar ...
bool isInLastSignalledBars = false;
for (int i=0; i < candleGapBetweenSignals; i++) {
//
isInLastSignalledBars =
isInLastSignalledBars
|| lastSignalledBar == countedBars - i
;
}
if (isInLastSignalledBars) {
//
// Clear Signal Conditions ...
if (hasLongSignal) {
ClearLongSignalConditions();
} else {
ClearShortSignalConditions();
}
//
return;
}
//
// increase last signalled bar ...
lastSignalledBar = countedBars;
//
// Calculate Can Trade or not ...
allowDoTrade = allowTrade
&& (
hasLongSignal ?
allowLongTrades :
allowShortTrades
);
//
// Chack Maximum Open Positions ...
int openTrades = CountOpenTrades();
if (maxOpenTrades > 0) {
//
if (openTrades >= maxOpenTrades) {
//
allowDoTrade = false;
//
if (closeAllInProfitOpenTradesWhenMaxOpenTradesReached) {
//
// Close All In Profit Trades ...
bool hasClosedInProfitTrade = CloseAllInProfitTrades();
if (hasClosedInProfitTrade) {
//
openTrades = CountOpenTrades();
//
allowDoTrade = !(openTrades >= maxOpenTrades);
}
}
//
if (!allowDoTrade) {
//
string message = StringConcatenate(
"Trading Pause => ",
"Max Open Trades (",
maxOpenTrades,
") reached ..."
);
//
LogMessage(message);
SendAlert(message);
}
}
}
//
// Check Trading is Enable or not ...
// nothing to do if trading is disabled ...
if (!allowDoTrade) {
//
// Clear Signal Conditions ...
if (hasLongSignal) {
ClearLongSignalConditions();
} else {
ClearShortSignalConditions();
}
// //
// string message = StringConcatenate(
// "Trading Not Allowed ..."
// );
// //
// LogMessage(message);
// SendAlert(message);
return;
}
//
bool isPositionOpened = TradeSignal(
request.signal,
lotsPerTradePercent,
//
bullishSignalLabel,
bullishSignalColor,
bearishSignalLabel,
bearishSignalColor
);
//
totalSignals++;
if (hasLongSignal) {
//
totalLongSignals++;
ClearLongSignalConditions();
} else {
//
totalShortSignals++;
ClearShortSignalConditions();
}
//
// Draw XRState ...
if (isPositionOpened) {
//
XRState state = GetXRange(
0
);
//
string lblXRHH = StringConcatenate(
request.signal.tag,
"_XR_HH_", state.hh
);
//
// HH ...
DrawTrendLine(
0,
lblXRHH,
0,
state.start,
state.hh,
request.signal.time,
state.hh,
clrLime,
STYLE_DASH
);
//
string lblXRMID = StringConcatenate(
request.signal.tag,
"_XR_MID_", state.mid
);
//
// MID ...
DrawTrendLine(
0,
lblXRMID,
0,
state.start,
state.mid,
request.signal.time,
state.mid,
clrYellow,
STYLE_DASHDOT
);
//
string lblXRLL = StringConcatenate(
request.signal.tag,
"_XR_LL_", state.ll
);
//
// HH ...
DrawTrendLine(
0,
lblXRLL,
0,
state.start,
state.ll,
request.signal.time,
state.ll,
clrRed,
STYLE_DASH
);
}
//
if (isPositionOpened) {
//
bool canAlert =
alertPositions
&& (
hasLongSignal ?
longPositionAlerts
:
shortPositionAlerts
);
//
if (canAlert) {
//
// Alert Message ...
string message = StringConcatenate(
"Trade on Signal ID: ", request.signal.id,
", Entry: ", request.signal.entry,
", TP: ", request.signal.tp
);
//
// Terminal Alert ...
if (terminalAlert) {
Alert(message);
}
//
// Push Alert ...
if (pushAlert) {
SendNotification(message);
}
}
}
}
//
// Process All Open Positions ...
void ProcessOpenPositions() {
//
// this comes from check state ...
if (closeLongTrades) {
//
closeLongTrades = false;
//
bool isAllLongTradesClosed = CloseAllLongTrades();
if (isAllLongTradesClosed) {
}
}
//
// this comes from check state ...
if (closeShortTrades) {
//
closeShortTrades = false;
//
bool isAllShortTradesClosed = CloseAllShortTrades();
if (isAllShortTradesClosed) {
}
}
//
// Close All XXX Provided Signals on it's Specific Condition ...
if (xCloseLongTrades) {
//
CloseAllProviderLongTrades(X_XXX_PROVIDER);
//
xCloseLongTrades = false;
}
//
if (xrCloseLongTrades) {
//
CloseAllProviderLongTrades(X_XR_PROVIDER);
//
xrCloseLongTrades = false;
}
//
bool hasClosedLongTimeTrade = CloseAllLongTimeTrades(
closeAllOpenTradesAfterCandle
);
//
// Close Maximum DrawDown Passed Trades ...
bool hasClosedInDrawDownLongTrade = CloseAllMaximumDrawDownPassedTrades(
maxDrawdownPercentPerPTrade
);
//
if (
hasClosedLongTimeTrade
|| hasClosedInDrawDownLongTrade
) {
//
// waitForLongSignals = false;
}
}
//
// Send Special Type of Alerts ...
void SendAlert(string message) {
//
if (!alertEvents) {
return;
}
//
// Terminal Alert ...
if (terminalAlert) {
Alert(message);
}
//
// Push Alert ...
if (pushAlert) {
SendNotification(message);
}
}
//
// END Functions ...
//
//
//
// Calculate Signal ...
// in this function we calculate a signal exists in
// specific bar or not ...
XSignalRequest GenerateSignal(
const int bar_index // Bar Index ...
) {
//
// create temp result ...
XSignalRequest result = {};
result.hasSignal = false;
result.type = X_SIGNAL_NONE;
result.provider = X_UNKNOWN_PROVIDER;
//
bool hasSignal = false;
bool hasLongSignal = false;
bool hasShortSignal = false;
//
XSignal signal = {};
//
CheckXRSignalHandler(
bar_index
);
//
CheckXRLongSignalConditions(
bar_index
);
//
XSignalRequest xrLongSignalRequest = GenerateXRSignal(
X_SIGNAL_LONG,
signalPrefix,
bar_index
);
//
if (xrLongSignalRequest.hasSignal) {
//
// Here we can Check and Filter Signals Based On State ...
bool isReady = IsReadyForXRSignals(
xrLongSignalRequest.signal
);
//
if (isReady && xWaitForLongSignals) {
//
hasLongSignal = true;
signal = xrLongSignalRequest.signal;
} else {
ClearXRLongSignalConditions();
}
}
//
hasSignal = hasLongSignal || hasShortSignal;
//
if (!hasSignal) {
//
signal.type = X_SIGNAL_NONE;
result.type = X_SIGNAL_NONE;
}
//
// Normalize TP, SL and Entry Price ...
signal.tp = NormalizeDouble(signal.tp, _Digits);
signal.sl = NormalizeDouble(signal.sl, _Digits);
signal.entry = NormalizeDouble(signal.entry, _Digits);
//
result.signal = signal;
result.type = signal.type;
result.hasSignal = hasSignal;
result.provider = signal.provider;
//
// Return Result ...
return result;
}
@@ -0,0 +1,173 @@
///////////////////////////////////////////////////////
//
// SaherElm IT Center MA Indicator
// ---------------------------------------------
// saherelm implementation of above indicator ...
// this indicator uses two ma line:
// - fast ma;
// - slow ma;
//
// 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 MA Indicator"
#property strict
//
// START Inputs ...
//
//
// Fast MA ...
input int maLength = 20; // MA Length
input int maShift = 0; // MA Shift
input ENUM_MA_METHOD maMethod = MODE_EMA; // MA Method
input ENUM_APPLIED_PRICE maAppliedPrice = PRICE_CLOSE; // MA Applied Price
//
// START Global Definitions: Variables, Properties and etc ...
//
#property indicator_chart_window
//
#property indicator_buffers 1
//
#property indicator_plots 1
//
// Start Define Indicator Buffer Styles ...
//
//
// Fast Ma Buffer ...
#property indicator_label1 "Ma"
#property indicator_type1 DRAW_LINE
#property indicator_color1 clrYellow
#property indicator_style1 STYLE_DOT
#property indicator_width1 2
//
// End Define Indicator Buffer Styles ...
//
//
// Buffers ...
#define maBufferIndex 0
double maBuffer[];
//
// END Global Definitions: Variables, Properties and etc ...
//
//
// Start Event Handlers ...
//
//
// Initialization ...
int OnInit() {
//
// Initialize what we want ...
if (maLength <= 0) {
return INIT_PARAMETERS_INCORRECT;
}
//
// Start Set Index Buffers ...
//
//
// Ma ...
SetIndexBuffer(maBufferIndex, maBuffer);
SetIndexDrawBegin(maBufferIndex, maLength + 1);
//
// End Set Index Buffers ...
//
//
return INIT_SUCCEEDED;
}
//
// Calculating what we want ...
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[]
) {
//
// this counts Available Bars ...
int limit;
//
// because in some cases we may have more than one input for
// calculation and we must prevent any calculation
// untill we pass the biggest input length, here we get max Input length
// and then wait until pass it ...
int maxLength = MathMax(0, maLength);
//
// input variable, we return 0 means nothing passed ...
if (rates_total < maxLength) {
return 0;
}
//
// found which candles calculated before ...
limit = (prev_calculated == 0) ? rates_total - maxLength - 1 : rates_total - prev_calculated + 1;
//
// this is the main loop of calculations, for each bar index ...
for (int i = limit - 1; i >= 0; i--) {
//
// Start Calculation here ...
// i is bar_index ...
//
// Calculate Ma ...
CalculateMa(i);
}
//
return rates_total;
}
//
// END Event Handlers ...
//
//
// START Functions ...
//
//
// Calculating Ma ...
void CalculateMa(
const int &bar_index
) {
//
// Calculating Fast Ma ...
double ma = iMA(
_Symbol,
_Period,
maLength,
maShift,
maMethod,
maAppliedPrice,
bar_index
);
//
maBuffer[bar_index] = ma;
}
//
// END Functions ...
//
@@ -0,0 +1,412 @@
///////////////////////////////////////////////////////
//
// SaherElm IT Center X Indicator
// ---------------------------------------------
// saherelm implementation of above indicator ...
//
// Maintainer:
// ------------
// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com)
//
//////////////////////////////////////////////////////
//
// Global Properties ...
#property copyright "Copyright 2023, SaherElm IT Center"
#property link "https://saherelm.ir"
#property version "1.00"
#property description "SaherElm X Indicator"
#property strict
//
// START Inputs ...
//
//
input int marketLength = 7; // Market Length
//
input int shortCycleMultiplier = 2; // Market Short Cycle Multiplier
input int mediumCycleMultiplier = 6; // Market Medium Cycle Multiplier
input int longCycleMultiplier = 36; // Market Medium Cycle Multiplier
//
input ENUM_MA_METHOD maMethod = MODE_SMA; // Ma Method
//
// END Inputs ...
//
//
// START Global Definitions: Variables, Properties and etc ...
//
#property indicator_chart_window
//
#property indicator_buffers 6
//
#property indicator_plots 6
//
// Start Define Indicator Buffer Styles ...
//
//
// Short Cycle Highest High Buffer ...
#property indicator_type1 DRAW_LINE
#property indicator_color1 clrGreen
#property indicator_style1 STYLE_DOT
#property indicator_width1 1
//
// Short Cycle Lowest Low Buffer ...
#property indicator_type2 DRAW_LINE
#property indicator_color2 clrRed
#property indicator_style2 STYLE_DOT
#property indicator_width2 1
//
// Medium Cycle Highest High Buffer ...
#property indicator_type3 DRAW_LINE
#property indicator_color3 clrAqua
#property indicator_style3 STYLE_DOT
#property indicator_width3 1
//
// Medium Cycle Lowest Low Buffer ...
#property indicator_type4 DRAW_LINE
#property indicator_color4 clrFuchsia
#property indicator_style4 STYLE_DOT
#property indicator_width4 1
//
// Long Cycle Highest High Buffer ...
#property indicator_type5 DRAW_LINE
#property indicator_color5 C'62,82,6'
#property indicator_style5 STYLE_DOT
#property indicator_width5 1
//
// Long Cycle Lowest Low Buffer ...
#property indicator_type6 DRAW_LINE
#property indicator_color6 C'255,81,0'
#property indicator_style6 STYLE_DOT
#property indicator_width6 1
//
// End Define Indicator Buffer Styles ...
//
//
// Buffers ...
//
// HH Buffers ...
#define scHHBufferIndex 0
#define scLLBufferIndex 1
#define mcHHBufferIndex 2
#define mcLLBufferIndex 3
#define lcHHBufferIndex 4
#define lcLLBufferIndex 5
double scHHBuffer[];
double scLLBuffer[];
double mcHHBuffer[];
double mcLLBuffer[];
double lcHHBuffer[];
double lcLLBuffer[];
//
// Variables ...
int shortCycleLength;
int mediumCycleLength;
int longCycleLength;
//
// END Global Definitions: Variables, Properties and etc ...
//
//
// Start Event Handlers ...
//
//
// Initialization ...
int OnInit() {
//
// Initialize what we want ...
if (
marketLength <= 0 ||
shortCycleMultiplier <= 0 ||
mediumCycleMultiplier <= 0 ||
shortCycleMultiplier > mediumCycleMultiplier
) {
return INIT_PARAMETERS_INCORRECT;
}
//
// Start Set Index Buffers ...
//
shortCycleLength = shortCycleMultiplier * marketLength;
mediumCycleLength = mediumCycleMultiplier * marketLength;
longCycleLength = longCycleMultiplier * marketLength;
//
// Highest High and Lowest Low Buffers ...
//
// Short Cycle Highest High ...
string scHHLbl = StringConcatenate(
"SC HH(", shortCycleLength, ")"
);
SetIndexBuffer(scHHBufferIndex, scHHBuffer);
SetIndexLabel(scHHBufferIndex, scHHLbl);
//
// Short Cycle Lowest Low ...
string scLLLbl = StringConcatenate(
"SC LL(", shortCycleLength, ")"
);
SetIndexBuffer(scLLBufferIndex, scLLBuffer);
SetIndexLabel(scLLBufferIndex, scLLLbl);
//
// Medium Cycle Highest High ...
string mcHHLbl = StringConcatenate(
"MC HH(", mediumCycleLength, ")"
);
SetIndexBuffer(mcHHBufferIndex, mcHHBuffer);
SetIndexLabel(mcHHBufferIndex, mcHHLbl);
//
// Medium Cycle Lowest Low ...
string mcLLLbl = StringConcatenate(
"MC LL(", mediumCycleLength, ")"
);
SetIndexBuffer(mcLLBufferIndex, mcLLBuffer);
SetIndexLabel(mcLLBufferIndex, mcLLLbl);
//
// Long Cycle Highest High ...
string lcHHLbl = StringConcatenate(
"LC HH(", longCycleLength, ")"
);
SetIndexBuffer(lcHHBufferIndex, lcHHBuffer);
SetIndexLabel(lcHHBufferIndex, lcHHLbl);
//
// Long Cycle Lowest Low ...
string lcLLLbl = StringConcatenate(
"LC LL(", longCycleLength, ")"
);
SetIndexBuffer(lcLLBufferIndex, lcLLBuffer);
SetIndexLabel(lcLLBufferIndex, lcLLLbl);
//
// End Set Index Buffers ...
//
//
return INIT_SUCCEEDED;
}
//
// Calculating what we want ...
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[]
) {
//
// this counts Available Bars ...
int limit;
//
// because in some cases we may have more than one input for
// calculation and we must prevent any calculation
// untill we pass the biggest input length, here we get max Input length
// and then wait until pass it ...
int maxLength = MathMax(0, marketLength);
//
// input variable, we return 0 means nothing passed ...
if (rates_total < maxLength) {
return 0;
}
//
// found which candles calculated before ...
limit = (prev_calculated == 0) ? rates_total - maxLength - 1 : rates_total - prev_calculated + 1;
//
// this is the main loop of calculations, for each bar index ...
for (int i = limit - 1; i >= 0; i--) {
//
// Start Calculation here ...
// i is bar_index ...
//
// Calculat Ma's ...
//
CalculateShortCycle(i);
//
CalculateMediumCycle(i);
//
CalculateLongCycle(i);
}
//
return rates_total;
}
//
// END Event Handlers ...
//
//
// START Functions ...
//
//
// Calculating Short Cycle ...
void CalculateShortCycle(
const int &bar_index
) {
//
// Short Cycle Highest High ...
//
int scHHIdx = iHighest(
_Symbol,
_Period,
MODE_HIGH,
shortCycleLength,
bar_index
);
//
double scHH = iHigh(
_Symbol,
_Period,
scHHIdx
);
//
scHHBuffer[bar_index] = scHH;
//
// Short Cycle Lowest Low ...
//
int scLLIdx = iLowest(
_Symbol,
_Period,
MODE_LOW,
shortCycleLength,
bar_index
);
//
double scLL = iLow(
_Symbol,
_Period,
scLLIdx
);
//
scLLBuffer[bar_index] = scLL;
}
//
// Calculating Medium Cycle ...
void CalculateMediumCycle(
const int &bar_index
) {
//
// Medium Cycle Highest High ...
//
int mcHHIdx = iHighest(
_Symbol,
_Period,
MODE_HIGH,
mediumCycleLength,
bar_index
);
//
double mcHH = iHigh(
_Symbol,
_Period,
mcHHIdx
);
//
mcHHBuffer[bar_index] = mcHH;
//
// Medium Cycle Lowest Low ...
//
int mcLLIdx = iLowest(
_Symbol,
_Period,
MODE_LOW,
mediumCycleLength,
bar_index
);
//
double mcLL = iLow(
_Symbol,
_Period,
mcLLIdx
);
//
mcLLBuffer[bar_index] = mcLL;
}
//
// Calculating Long Cycle ...
void CalculateLongCycle(
const int &bar_index
) {
//
// Long Cycle Highest High ...
//
int lcHHIdx = iHighest(
_Symbol,
_Period,
MODE_HIGH,
longCycleLength,
bar_index
);
//
double lcHH = iHigh(
_Symbol,
_Period,
lcHHIdx
);
//
lcHHBuffer[bar_index] = lcHH;
//
// Long Cycle Lowest Low ...
//
int lcLLIdx = iLowest(
_Symbol,
_Period,
MODE_LOW,
longCycleLength,
bar_index
);
//
double lcLL = iLow(
_Symbol,
_Period,
lcLLIdx
);
//
lcLLBuffer[bar_index] = lcLL;
}
//
// END Functions ...
//
@@ -0,0 +1,294 @@
///////////////////////////////////////////////////////
//
// SaherElm IT Center XRange Indicator
// ---------------------------------------------
// saherelm implementation of above indicator ...
//
// Maintainer:
// ------------
// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com)
//
//////////////////////////////////////////////////////
//
// Global Properties ...
#property copyright "Copyright 2023, SaherElm IT Center"
#property link "https://saherelm.ir"
#property version "1.00"
#property description "SaherElm XRange Indicator"
#property strict
//
// START Inputs ...
//
input int marketLength = 14;
//
// END Inputs ...
//
//
// START Global Definitions: Variables, Properties and etc ...
//
#property indicator_chart_window
//
#property indicator_buffers 3
//
#property indicator_plots 3
//
// Start Define Indicator Buffer Styles ...
//
//
// Highest High Buffer ...
#property indicator_type1 DRAW_LINE
#property indicator_color1 clrGreen
#property indicator_style1 STYLE_DOT
#property indicator_width1 1
//
// Lowest Low Buffer ...
#property indicator_type2 DRAW_LINE
#property indicator_color2 clrRed
#property indicator_style2 STYLE_DOT
#property indicator_width2 1
//
// Middle Buffer ...
#property indicator_type3 DRAW_LINE
#property indicator_color3 clrYellow
#property indicator_style3 STYLE_DASH
#property indicator_width3 1
//
// End Define Indicator Buffer Styles ...
//
//
// Buffers ...
//
#define highestHighBufferIndex 0
#define lowestLowBufferIndex 1
#define middleBufferIndex 2
//
double highestHighBuffer[];
double lowestLowBuffer[];
double middleBuffer[];
//
datetime startTime;
//
// END Global Definitions: Variables, Properties and etc ...
//
//
// Start Event Handlers ...
//
//
// Initialization ...
int OnInit() {
//
// Initialize what we want ...
if (
marketLength <= 0
) {
return INIT_PARAMETERS_INCORRECT;
}
//
string hhLbl = StringConcatenate(
"XR HH(", marketLength, ")"
);
SetIndexBuffer(highestHighBufferIndex, highestHighBuffer);
SetIndexLabel(highestHighBufferIndex, hhLbl);
//
string llLbl = StringConcatenate(
"XR LL(", marketLength, ")"
);
SetIndexBuffer(lowestLowBufferIndex, lowestLowBuffer);
SetIndexLabel(lowestLowBufferIndex, llLbl);
//
string midLbl = StringConcatenate(
"XR Mid(", marketLength, ")"
);
SetIndexBuffer(middleBufferIndex, middleBuffer);
SetIndexLabel(middleBufferIndex, midLbl);
//
return INIT_SUCCEEDED;
}
//
// Calculating what we want ...
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[]
) {
//
// this counts Available Bars ...
int limit;
//
// because in some cases we may have more than one input for
// calculation and we must prevent any calculation
// untill we pass the biggest input length, here we get max Input length
// and then wait until pass it ...
int maxLength = MathMax(0, marketLength);
//
// input variable, we return 0 means nothing passed ...
if (rates_total < maxLength) {
return 0;
}
//
// found which candles calculated before ...
limit = (prev_calculated == 0) ? rates_total - maxLength - 1 : rates_total - prev_calculated + 1;
//
// this is the main loop of calculations, for each bar index ...
for (int i = limit - 1; i >= 0; i--) {
//
// Start Calculation here ...
// i is bar_index ...
//
// Calculations ...
CalculateBuffers(i);
}
//
return rates_total;
}
//
// END Event Handlers ...
//
//
// START Functions ...
//
//
// Calculations ...
void CalculateBuffers(
const int &bar_index
) {
//
// Retrieve Bar Time ...
datetime barTime = iTime(
_Symbol,
_Period,
bar_index
);
//
if (startTime == 0) {
//
startTime = barTime;
SetIndicatorBuffersNone(bar_index);
return;
}
//
int startBarIndex = iBarShift(
_Symbol,
_Period,
startTime
);
//
int startDistance = startBarIndex - bar_index;
if (startDistance < marketLength) {
//
SetIndicatorBuffersNone(bar_index);
return;
}
//
// Highest High ...
int hhIdx = iHighest(
_Symbol,
_Period,
MODE_HIGH,
marketLength,
bar_index
);
double hh = iHigh(
_Symbol,
_Period,
hhIdx
);
highestHighBuffer[bar_index] = hh;
//
// Lowest Low ...
int llIdx = iLowest(
_Symbol,
_Period,
MODE_LOW,
marketLength,
bar_index
);
double ll = iLow(
_Symbol,
_Period,
llIdx
);
lowestLowBuffer[bar_index] = ll;
//
// Middle Buffer ...
double mid = (hh + ll) / 2;
middleBuffer[bar_index] = mid;
//
// Reset Start Time ...
startTime = 0;
}
//
void SetIndicatorBuffersNone(
const int bar_index
) {
//
int lastBarIndex = bar_index + 1;
//
double lastHighestHigh;
double lastLowestLow;
//
// Highest High ...
if (ArraySize(highestHighBuffer) > lastBarIndex) {
lastHighestHigh = highestHighBuffer[lastBarIndex];
} else {
lastHighestHigh = 0;
}
//
// Lowest Low ...
if (ArraySize(lowestLowBuffer) > lastBarIndex) {
lastLowestLow = lowestLowBuffer[lastBarIndex];
} else {
lastLowestLow = 0;
}
//
highestHighBuffer[bar_index] = lastHighestHigh;
lowestLowBuffer[bar_index] = lastLowestLow;
//
double mid = (lastHighestHigh + lastLowestLow) / 2;
middleBuffer[bar_index] = mid;
}
//
// END Functions ...
//
@@ -0,0 +1,395 @@
///////////////////////////////////////////////////////
//
// SaherElm IT Center X Indicator
// ---------------------------------------------
// saherelm implementation of above indicator ...
//
// Maintainer:
// ------------
// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com)
//
//////////////////////////////////////////////////////
//
// Global Properties ...
#property copyright "Copyright 2023, SaherElm IT Center"
#property link "https://saherelm.ir"
#property version "1.00"
#property description "SaherElm X Indicator"
#property strict
//
// START Inputs ...
//
//
input int marketLength = 7; // Market Length
//
input double step = 0.02; // P SAR Step
input double maximum = 0.2; // P SAR Maximum
//
input int shortCycleMultiplier = 2; // Market Short Cycle Multiplier
input int mediumCycleMultiplier = 6; // Market Medium Cycle Multiplier
input int longCycleMultiplier = 36; // Market Medium Cycle Multiplier
//
input ENUM_MA_METHOD maMethod = MODE_SMA; // Ma Method
//
// END Inputs ...
//
//
// START Global Definitions: Variables, Properties and etc ...
//
#property indicator_chart_window
//
#property indicator_buffers 7
//
#property indicator_plots 7
//
// Start Define Indicator Buffer Styles ...
//
//
// Short Cycle Fast Buffer ...
#property indicator_type1 DRAW_LINE
#property indicator_color1 clrGreen
#property indicator_style1 STYLE_DOT
#property indicator_width1 1
//
// Short Cycle Slow Buffer ...
#property indicator_type2 DRAW_LINE
#property indicator_color2 clrRed
#property indicator_style2 STYLE_DOT
#property indicator_width2 1
//
// Medium Cycle Fast Buffer ...
#property indicator_type3 DRAW_LINE
#property indicator_color3 clrAqua
#property indicator_style3 STYLE_DOT
#property indicator_width3 1
//
// Medium Cycle Slow Buffer ...
#property indicator_type4 DRAW_LINE
#property indicator_color4 clrFuchsia
#property indicator_style4 STYLE_DOT
#property indicator_width4 1
//
// Long Cycle Fast Buffer ...
#property indicator_type5 DRAW_LINE
#property indicator_color5 C'62,82,6'
#property indicator_style5 STYLE_DOT
#property indicator_width5 1
//
// Long Cycle Slow Buffer ...
#property indicator_type6 DRAW_LINE
#property indicator_color6 C'255,81,0'
#property indicator_style6 STYLE_DOT
#property indicator_width6 1
//
// Parabolic SAR ...
#property indicator_type7 DRAW_LINE
#property indicator_color7 C'0,174,255'
#property indicator_style7 STYLE_DASHDOT
#property indicator_width7 1
//
// End Define Indicator Buffer Styles ...
//
//
// Buffers ...
//
// Ma Buffers ...
#define scFastBufferIndex 0
#define scSlowBufferIndex 1
#define mcFastBufferIndex 2
#define mcSlowBufferIndex 3
#define lcFastBufferIndex 4
#define lcSlowBufferIndex 5
#define psarBufferIndex 6
double scFastBuffer[];
double scSlowBuffer[];
double mcFastBuffer[];
double mcSlowBuffer[];
double lcFastBuffer[];
double lcSlowBuffer[];
double psarBuffer[];
//
// Variables ...
int shortCycleLength;
int mediumCycleLength;
int longCycleLength;
//
// END Global Definitions: Variables, Properties and etc ...
//
//
// Start Event Handlers ...
//
//
// Initialization ...
int OnInit() {
//
// Initialize what we want ...
if (
marketLength <= 0 ||
shortCycleMultiplier <= 0 ||
mediumCycleMultiplier <= 0 ||
shortCycleMultiplier > mediumCycleMultiplier
) {
return INIT_PARAMETERS_INCORRECT;
}
//
// Start Set Index Buffers ...
//
shortCycleLength = shortCycleMultiplier * marketLength;
mediumCycleLength = mediumCycleMultiplier * marketLength;
longCycleLength = longCycleMultiplier * marketLength;
//
// Ma Buffers ...
//
// Short Cycle ...
string scFLbl = StringConcatenate(
"SC F(", shortCycleLength, ")"
);
SetIndexBuffer(scFastBufferIndex, scFastBuffer);
SetIndexLabel(scFastBufferIndex, scFLbl);
//
string scSLbl = StringConcatenate(
"SC S(", shortCycleLength, ")"
);
SetIndexBuffer(scSlowBufferIndex, scSlowBuffer);
SetIndexLabel(scSlowBufferIndex, scSLbl);
//
// Medium Cycle ...
string mcFLbl = StringConcatenate(
"MC F(", mediumCycleLength, ")"
);
SetIndexBuffer(mcFastBufferIndex, mcFastBuffer);
SetIndexLabel(mcFastBufferIndex, mcFLbl);
//
string mcSLbl = StringConcatenate(
"MC S(", mediumCycleLength, ")"
);
SetIndexBuffer(mcSlowBufferIndex, mcSlowBuffer);
SetIndexLabel(mcSlowBufferIndex, mcSLbl);
//
// Long Cycle ...
string lcFLbl = StringConcatenate(
"LC F(", longCycleLength, ")"
);
SetIndexBuffer(lcFastBufferIndex, lcFastBuffer);
SetIndexLabel(lcFastBufferIndex, lcFLbl);
//
string lcSLbl = StringConcatenate(
"LC S(", longCycleLength, ")"
);
SetIndexBuffer(lcSlowBufferIndex, lcSlowBuffer);
SetIndexLabel(lcSlowBufferIndex, lcSLbl);
//
// End Set Index Buffers ...
//
//
// Parabolic Sar ...
SetIndexBuffer(psarBufferIndex, psarBuffer);
SetIndexLabel(psarBufferIndex, "P Sar");
//
return INIT_SUCCEEDED;
}
//
// Calculating what we want ...
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[]
) {
//
// this counts Available Bars ...
int limit;
//
// because in some cases we may have more than one input for
// calculation and we must prevent any calculation
// untill we pass the biggest input length, here we get max Input length
// and then wait until pass it ...
int maxLength = MathMax(0, marketLength);
//
// input variable, we return 0 means nothing passed ...
if (rates_total < maxLength) {
return 0;
}
//
// found which candles calculated before ...
limit = (prev_calculated == 0) ? rates_total - maxLength - 1 : rates_total - prev_calculated + 1;
//
// this is the main loop of calculations, for each bar index ...
for (int i = limit - 1; i >= 0; i--) {
//
// Start Calculation here ...
// i is bar_index ...
//
// Calculat Ma's ...
//
CalculateShortCycle(i);
//
CalculateMediumCycle(i);
//
CalculateLongCycle(i);
//
// Parabolic SAR ...
CalculateParabolicSAR(i);
}
//
return rates_total;
}
//
// END Event Handlers ...
//
//
// START Functions ...
//
//
// Calculating Short Cycle ...
void CalculateShortCycle(
const int &bar_index
) {
//
double scFast = iMA(
_Symbol,
_Period,
shortCycleLength,
0,
maMethod,
PRICE_OPEN,
bar_index
);
scFastBuffer[bar_index] = scFast;
//
double scSlow = iMA(
_Symbol,
_Period,
shortCycleLength,
0,
maMethod,
PRICE_CLOSE,
bar_index
);
scSlowBuffer[bar_index] = scSlow;
}
//
// Calculating Medium Cycle ...
void CalculateMediumCycle(
const int &bar_index
) {
//
double mcFast = iMA(
_Symbol,
_Period,
mediumCycleLength,
0,
maMethod,
PRICE_OPEN,
bar_index
);
mcFastBuffer[bar_index] = mcFast;
//
double mcSlow = iMA(
_Symbol,
_Period,
mediumCycleLength,
0,
maMethod,
PRICE_CLOSE,
bar_index
);
mcSlowBuffer[bar_index] = mcSlow;
}
//
// Calculating Long Cycle ...
void CalculateLongCycle(
const int &bar_index
) {
//
double lcFast = iMA(
_Symbol,
_Period,
longCycleLength,
0,
maMethod,
PRICE_OPEN,
bar_index
);
lcFastBuffer[bar_index] = lcFast;
//
double lcSlow = iMA(
_Symbol,
_Period,
longCycleLength,
0,
maMethod,
PRICE_CLOSE,
bar_index
);
lcSlowBuffer[bar_index] = lcSlow;
}
//
// Calculate Parabolic SAR ...
void CalculateParabolicSAR(
const int &bar_index
) {
//
double pSar = iSAR(
_Symbol,
_Period,
step,
maximum,
bar_index
);
//
psarBuffer[bar_index] = pSar;
}
//
// END Functions ...
//
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,535 @@
///////////////////////////////////////////////////////
//
// SaherElm IT Center MQL4 Indicator Global Library
// ---------------------------------------------------
// saherelm useful tools and definitions ...
//
//
// Maintainer:
// ------------
// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com)
//
//////////////////////////////////////////////////////
#property library
#property copyright "Copyright 2023, SaherElm IT Center"
#property link "https://www.saherelm.ir"
#property version "1.00"
#property strict
//
// Includes library ...
#include "../Libraries/x-saherelm.lib.mq4"
//
// Includes Models library ...
#include "../Libraries/x-saherelm.models.lib.mq4"
//
// START Global Requirement Functions ...
//
//
double GetMaxRangeAllowedTP(
const ENUM_X_SIGNAL_TYPE type,
const XRange &range
) {
//
bool isLongSignal =
type != X_SIGNAL_NONE
&& type == X_SIGNAL_LONG
;
//
double maxAllowedTPRange = ((range.levels - 0.5) * range.rate);
//
double result =
isLongSignal ?
range.lowestLow + maxAllowedTPRange
:
range.highestHigh - maxAllowedTPRange
;
//
return result;
}
//
double GetMaxRangeAllowedEntry(
const ENUM_X_SIGNAL_TYPE type,
const XRange &range
) {
//
bool isLongSignal =
type != X_SIGNAL_NONE
&& type == X_SIGNAL_LONG
;
//
double maxAllowedEntryRange = (range.levels - 1.5) * range.rate;
//
double result =
isLongSignal ?
range.lowestLow + maxAllowedEntryRange
:
range.highestHigh - maxAllowedEntryRange
;
//
return result;
}
//
// Range Verification ...
bool IsRangeVerified(
const int bar_index,
const int marketLen,
const int levels,
const ENUM_X_SIGNAL_TYPE type,
const double entry,
const double tp,
const XRange &range
) {
//
bool isLongSignal =
type == X_SIGNAL_LONG
&& type != X_SIGNAL_NONE
;
//
double maxAllowedTP =
GetMaxRangeAllowedTP(
type,
range
)
;
//
double maxAllowedEntry =
GetMaxRangeAllowedEntry(
type,
range
)
;
//
bool result =
isLongSignal
?
//
entry < maxAllowedEntry
&& tp < maxAllowedTP
:
//
entry > maxAllowedEntry
&& tp > maxAllowedTP
;
//
return result;
}
//
// START Global Requirement Functions ...
//
//
// Signal Range Verification ...
bool IsSignalRangeVerified(
const int bar_index,
const int marketLen,
const int levels,
const XSignal &signal,
const XRange &range
) {
//
bool result =
IsRangeVerified(
bar_index,
marketLen,
levels,
signal.type,
signal.entry,
signal.tp,
range
);
//
return result;
}
//
double ReadXMABuffer(
const int bar_index,
const int buffer_index,
//
const int marketLen,
//
const double stp,
const double mxm,
//
const int shortCycleMult,
const int mediumCycleMult,
const int longCycleMult
) {
//
string xmaIndicatorName = "x-saherelm.x.xma";
//
double result = iCustom(
_Symbol,
_Period,
xmaIndicatorName,
//
// Inputs ...
marketLen,
stp,
mxm,
shortCycleMult,
mediumCycleMult,
longCycleMult,
MODE_SMA,
//
buffer_index,
bar_index
);
//
return result;
}
//
double ReadXHLBuffer(
const int bar_index,
const int buffer_index,
//
const int marketLen,
//
const int shortCycleMult,
const int mediumCycleMult,
const int longCycleMult
) {
//
string xhlIndicatorName = "x-saherelm.x.hl";
//
double result = iCustom(
_Symbol,
_Period,
xhlIndicatorName,
//
// Inputs ...
marketLen,
shortCycleMult,
mediumCycleMult,
longCycleMult,
MODE_SMA,
//
buffer_index,
bar_index
);
//
return result;
}
//
double ReadADX(
const int bar_index,
const int marketLen,
const int mult
) {
//
double result;
//
int period = marketLen * mult;
//
result = iADX(
_Symbol,
_Period,
period,
PRICE_CLOSE,
MODE_MAIN,
bar_index
);
//
return result;
}
//
XState GetXState(
const int bar_index,
//
const int marketLen,
//
const double stp,
const double mxm,
//
const int shortCycleMult,
const int mediumCycleMult,
const int longCycleMult
) {
//
XState result = {};
//
// Cycle Buffer Indexes ...
int scFastBufferIndex = 0;
int scSlowBufferIndex = 1;
int mcFastBufferIndex = 2;
int mcSlowBufferIndex = 3;
int lcFastBufferIndex = 4;
int lcSlowBufferIndex = 5;
int psarBufferIndex = 6;
//
// HH and LL Buffer Indexes ...
int scHHBufferIndex = 0;
int scLLBufferIndex = 1;
int mcHHBufferIndex = 2;
int mcLLBufferIndex = 3;
int lcHHBufferIndex = 4;
int lcLLBufferIndex = 5;
//
// Short Cycle ...
//
// Fast ...
double scFast = ReadXMABuffer(
bar_index,
scFastBufferIndex,
//
marketLen,
stp,
mxm,
shortCycleMult,
mediumCycleMult,
longCycleMult
);
//
// Slow ...
double scSlow = ReadXMABuffer(
bar_index,
scSlowBufferIndex,
//
marketLen,
stp,
mxm,
shortCycleMult,
mediumCycleMult,
longCycleMult
);
//
// Highest High ...
double scHH = ReadXHLBuffer(
bar_index,
scHHBufferIndex,
//
marketLen,
//
shortCycleMult,
mediumCycleMult,
longCycleMult
);
//
// Lowest Low ...
double scLL = ReadXHLBuffer(
bar_index,
scLLBufferIndex,
//
marketLen,
//
shortCycleMult,
mediumCycleMult,
longCycleMult
);
//
// Integrate Result ...
XCycleState sc = {};
sc.fast = scFast;
sc.slow = scSlow;
sc.hh = scHH;
sc.ll = scLL;
//
// Attach Result ...
result.sc = sc;
//
// Medium Cycle ...
//
// Fast ...
double mcFast = ReadXMABuffer(
bar_index,
mcFastBufferIndex,
//
marketLen,
stp,
mxm,
shortCycleMult,
mediumCycleMult,
longCycleMult
);
//
// Slow ...
double mcSlow = ReadXMABuffer(
bar_index,
mcSlowBufferIndex,
//
marketLen,
stp,
mxm,
shortCycleMult,
mediumCycleMult,
longCycleMult
);
//
// Highest High ...
double mcHH = ReadXHLBuffer(
bar_index,
mcHHBufferIndex,
//
marketLen,
//
shortCycleMult,
mediumCycleMult,
longCycleMult
);
//
// Lowest Low ...
double mcLL = ReadXHLBuffer(
bar_index,
mcLLBufferIndex,
//
marketLen,
//
shortCycleMult,
mediumCycleMult,
longCycleMult
);
//
double di = GetMA(
bar_index,
(mediumCycleMult + 1) * marketLen,
0,
MODE_SMA,
PRICE_CLOSE
);
result.di = di;
//
// Integrate Result ...
XCycleState mc = {};
mc.fast = mcFast;
mc.slow = mcSlow;
mc.hh = mcHH;
mc.ll = mcLL;
//
// Attach Result ...
result.mc = mc;
//
// Long Cycle ...
//
// Fast ...
double lcFast = ReadXMABuffer(
bar_index,
lcFastBufferIndex,
//
marketLen,
stp,
mxm,
shortCycleMult,
mediumCycleMult,
longCycleMult
);
//
// Slow ...
double lcSlow = ReadXMABuffer(
bar_index,
lcSlowBufferIndex,
//
marketLen,
stp,
mxm,
shortCycleMult,
mediumCycleMult,
longCycleMult
);
//
// Highest High ...
double lcHH = ReadXHLBuffer(
bar_index,
lcHHBufferIndex,
//
marketLen,
//
shortCycleMult,
mediumCycleMult,
longCycleMult
);
//
// Lowest Low ...
double lcLL = ReadXHLBuffer(
bar_index,
lcLLBufferIndex,
//
marketLen,
//
shortCycleMult,
mediumCycleMult,
longCycleMult
);
//
// Integrate Result ...
XCycleState lc = {};
lc.fast = lcFast;
lc.slow = lcSlow;
lc.hh = lcHH;
lc.ll = lcLL;
//
// Attach Result ...
result.lc = lc;
//
// Parabolic SAR ...
double psar = ReadXMABuffer(
bar_index,
psarBufferIndex,
//
marketLen,
stp,
mxm,
shortCycleMult,
mediumCycleMult,
longCycleMult
);
//
result.parabolicSAR = psar;
//
return result;
}
//
// END XMA Data ...
//
//
// END Indicator Reading Data ...
//
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,91 @@
///////////////////////////////////////////////////////
//
// SaherElm IT Center MQL4 Draw Global Library
// ---------------------------------------------
// saherelm useful tools and definitions ...
//
//
// Maintainer:
// ------------
// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com)
//
//////////////////////////////////////////////////////
#property library
#property copyright "Copyright 2023, SaherElm IT Center"
#property link "https://www.saherelm.ir"
#property version "1.00"
#property strict
//
// Log Tag ...
static string logTag = "";
//
// Enable or Disable Logging ...
static bool enableLogging = false;
//
// Start Log Messages ...
//
//
// Logging a Message, specified for this EA ...
// using provided LogTag ...
void LogMessage(string message) {
//
if (!enableLogging) {
return;
}
//
Print(logTag, " > ", message);
}
//
// this used for logging series ...
void LogSeries(
double &series[], // which series to Log ...
int length = 0, // number of items to Log, 0 means all ...
int skip = 0 // number of items which skip before logging ...
) {
//
string msg = "";
//
int seriesSize = ArraySize(series);
if (
skip < 0
|| length < 0
|| seriesSize == 0
|| skip > seriesSize
|| skip + length > seriesSize
) {
return;
}
//
length = length == 0 ?
seriesSize :
length;
int start = skip > 1 ?
skip - 1 :
skip == 1 ?
1 :
0;
//
// Loop through series items ...
for (int i = start; i < start + length; i++) {
//
msg += StringConcatenate(
"i[", i, "]: ", series[i], ", "
);
}
//
LogMessage(msg);
}
//
// End Log Messages ...
//
@@ -0,0 +1,152 @@
///////////////////////////////////////////////////////
//
// SaherElm IT Center MQL4 Models Global Library
// ---------------------------------------------
// saherelm useful tools and definitions ...
//
//
// Maintainer:
// ------------
// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com)
//
//////////////////////////////////////////////////////
#property library
#property copyright "Copyright 2023, SaherElm IT Center"
#property link "https://www.saherelm.ir"
#property version "1.00"
#property strict
//
// START STATIC Variables ...
//
//
static int totalSignals = 0;
static int totalLongSignals = 0;
static int totalShortSignals = 0;
//
static double initialBalance = 0;
//
static int countedBars = 0;
static bool isNewBar = false;
static bool isNewDay = false;
//
// END STATIC Variables ...
//
//
// Start Models ...
//
//
// Signal Providers ...
enum ENUM_X_SIGNAL_PROVIDER {
X_UNKNOWN_PROVIDER,
X_XXX_PROVIDER,
X_XR_PROVIDER
};
//
// these are different signal types ...
enum ENUM_X_SIGNAL_TYPE {
X_SIGNAL_NONE,
X_SIGNAL_LONG,
X_SIGNAL_SHORT,
};
//
// we Model each signals as this type ...
struct XSignal {
//
// Signal Symbol ...
string symbol;
//
// Signal Type ...
ENUM_X_SIGNAL_TYPE type;
//
// Signal ID ...
int id;
//
// Signal Ticket Number, when Opening Trade ...
int ticket;
//
// Signal Provider ...
ENUM_X_SIGNAL_PROVIDER provider;
//
// Target Point ...
double tp;
//
// Stop Loss ...
double sl;
//
// Signal Entry Price ...
double entry;
//
// Signalling Time ...
datetime time;
//
// Signal Comments ...
string comment;
//
// Signal TAG ...
string tag;
};
//
// this is Signal Request Response model ...
struct XSignalRequest {
bool hasSignal;
XSignal signal;
ENUM_X_SIGNAL_TYPE type;
ENUM_X_SIGNAL_PROVIDER provider;
};
//
struct XCycleState {
//
double fast;
double slow;
//
double hh;
double ll;
//
double power;
};
//
// Define a Model to Represent Snapshot of XMA Indicator ...
struct XState {
//
// SC ...
XCycleState sc;
//
// MC ...
XCycleState mc;
//
double di;
//
// LC ...
XCycleState lc;
//
// PARABOLIC-SAR ...
double parabolicSAR;
};
//
// End Models ...
//
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,778 @@
///////////////////////////////////////////////////////
//
// SaherElm IT Center MQL4 X Signal Global Library
// ---------------------------------------------------
// saherelm useful tools and definitions ...
//
//
// Maintainer:
// ------------
// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com)
//
//////////////////////////////////////////////////////
#property library
#property copyright "Copyright 2023, SaherElm IT Center"
#property link "https://www.saherelm.ir"
#property version "1.00"
#property strict
//
// Includes library ...
#include "../Libraries/x-saherelm.lib.mq4"
//
// Includes Indicator library ...
#include "../Libraries/x-saherelm.indicator.lib.mq4"
//
// Includes Models library ...
#include "../Libraries/x-saherelm.models.lib.mq4"
//
// START Global Requirement Functions ...
//
//
// X Based Signal Conditions ...
struct XSignalConditions {
datetime startTime;
datetime signalTime;
datetime entryTime;
};
//
static XSignalConditions xLongConds;
static bool xCloseLongTrades = false;
static bool xWaitForLongSignals = true;
static datetime lastLCFCrossOverSCLLTime;
static datetime xWaitForLongSignalChangeTime;
//
static XSignalConditions xShortConds;
static bool xWaitForShortSignals = true;
static bool xCloseShortTrades = false;
//
// END Global Requirement Functions ...
//
//
// START Functions ...
//
//
// Check and Fill Long and Short Signal Handlers ...
void CheckSignalHandler(
const int bar_index,
const int marketLen,
const XState &states[],
//
const double smoother = 10
) {
//
// Check Market For Enable/Disable Signal Handlers ...
// Checking Market for Long Signals ...
if (xWaitForLongSignals) {
// //
// bool isLCFastOnTrendingUpTouchLowestLow =
// //
// // LC Trending Up ...
// states[1].lc.fast > states[1].lc.slow
// && states[2].lc.fast > states[2].lc.slow
// //
// // LC Fast Touch Market Lowest Low ...
// && states[1].lc.fast > states[1].mkt.lowestLow
// && !(states[2].lc.fast > states[2].mkt.lowestLow)
// ;
// //
// bool isMCSlowCrossOverBNDHigh =
// states[1].mc.fast > states[1].mc.slow
// && states[1].mc.slow > states[1].bnd.high
// && !(states[2].mc.slow > states[2].bnd.high)
// ;
//
// Disable Long Trade Handlers ...
// if (
// isMCSlowCrossOverBNDHigh
// || isLCFastOnTrendingUpTouchLowestLow
// ) {
// //
// xWaitForLongSignals = false;
// xWaitForLongSignalChangeTime = TimeCurrent();
// LogMessage("Disable Long ...");
// }
} else {
//
bool isAllTrendingUp =
//
// SC ...
states[1].sc.fast > states[1].sc.slow
//
// MC ...
&& states[1].mc.fast > states[1].mc.slow
&& !(states[2].mc.fast > states[2].mc.slow)
//
// LC ...
&& states[1].lc.fast > states[1].lc.slow
;
//
int lastWaitChangeBarIndex = iBarShift(
_Symbol,
_Period,
xWaitForLongSignalChangeTime
);
//
// Enable Long Trade Handlers ...
if (
isAllTrendingUp
&& lastWaitChangeBarIndex - bar_index >= marketLen
) {
xWaitForLongSignals = true;
LogMessage("Enable Long ...");
}
}
}
//
// Check and Fill Long Signal Conditions ...
void CheckXLongSignalConditions(
const int bar_index,
const int marketLen,
const XState &states[],
//
const double smoother = 10
) {
//
datetime barTime = iTime(
_Symbol,
_Period,
bar_index
);
//
// for Long Signals it happens when sc fast cross over slow ...
bool isCrossUnder =
states[0].sc.fast > states[0].sc.slow
&& states[1].sc.fast > states[1].sc.slow
&& !(states[2].sc.fast > states[2].sc.slow)
;
//
// for Long Signals it happens when sc fast cross under slow ...
bool isCrossOver =
states[0].sc.fast < states[0].sc.slow
&& states[1].sc.fast < states[1].sc.slow
&& !(states[2].sc.fast < states[2].sc.slow)
;
//
// Check Special Conditions ...
// XOHCL pCandle = GetCandleModel(bar_index + 1);
// XOHCL ppCandle = GetCandleModel(bar_index + 2);
// XOHCL mCandle = GetCandleModel(bar_index + marketLen);
// bool isLCGoingDownPrice =
// //
// pCandle.low > states[1].lc.slow
// && ppCandle.low > states[2].lc.slow
// && mCandle.low < states[marketLen - 1].lc.slow
// ;
// if ()
//
if (
isCrossUnder
&& xLongConds.startTime == 0
) {
//
xLongConds.startTime = barTime;
return;
}
//
if (
isCrossOver
&& xLongConds.startTime > 0
&& xLongConds.signalTime == 0
) {
//
xLongConds.signalTime = barTime;
xLongConds.entryTime = barTime;
//
// if (states[0].parabolicSAR < states[0].sc.slow) {
// }
return;
}
// //
// if (
// xLongConds.startTime > 0
// && xLongConds.signalTime > 0
// && xLongConds.entryTime == 0
// && states[0].parabolicSAR < states[0].sc.slow
// ) {
// //
// xLongConds.entryTime = barTime;
// return;
// }
}
//
// Check and Fill Short Signal Conditions ...
void CheckXShortSignalConditions(
const int bar_index,
const int marketLen,
const XState &states[],
//
const double smoother = 10
) {
//
datetime barTime = iTime(
_Symbol,
_Period,
bar_index
);
//
bool isCrossUnder =
false;
//
bool isCrossOver =
false;
//
if (
isCrossOver
&& xShortConds.startTime == 0
) {
//
xShortConds.startTime = barTime;
return;
}
//
if (
isCrossUnder
&& xShortConds.startTime > 0
&& xShortConds.signalTime == 0
) {
//
xShortConds.signalTime = barTime;
return;
}
}
//
// Convert Long Signal Conditions to XSignal ...
XSignalRequest GenerateXSignal(
const ENUM_X_SIGNAL_TYPE type, // Signal Type ...
const string signalTag , // Signal Tag ...
const int bar_index, // Bar Index ...
const int marketLen, // MarketLength for TP and SL ...
const int longCycleMult, // Long Cycle Multiplier for XRange Calculations ...
const double r2r, // Risk to Reward ratio ...
const XState &states[],
//
const double smoother = 10
) {
//
XSignalRequest result = {};
//
result.hasSignal = false;
result.type = X_SIGNAL_NONE;
result.provider = X_UNKNOWN_PROVIDER;
//
bool requestLong = type == X_SIGNAL_LONG;
//
if (requestLong) {
//
if (
!ValidateXLongConditions(
marketLen,
states,
smoother
)
) {
return result;
}
} else {
//
if (
!ValidateXShortConditions(
marketLen,
states,
smoother
)
) {
return result;
}
}
//
// Price Calculations ...
//
RefreshRates();
//
double askPrice = SymbolInfoDouble(
_Symbol,
SYMBOL_ASK
);
//
double bidPrice = SymbolInfoDouble(
_Symbol,
SYMBOL_BID
);
//
double entryPrice = requestLong ?
askPrice :
bidPrice;
//
double exitPrice = requestLong ?
bidPrice :
askPrice;
//
double priceGap = MathAbs(entryPrice - exitPrice);
//
double ll =
//
GetMarketLowestLow(
bar_index,
marketLen
)
;
//
double hh =
//
GetMarketHighestHigh(
bar_index,
marketLen
)
;
//
double openPrice = iOpen(
_Symbol,
_Period,
bar_index
);
//
double closePrice = iClose(
_Symbol,
_Period,
bar_index
);
//
double risk = requestLong ?
MathMin(openPrice, closePrice) - ll :
hh - MathMax(openPrice, closePrice);
double reward = risk * r2r; // risk * r2r; // 300 * _Point;
// if (risk > (500 * _Point)) {
// reward = 300 * _Point;
// }
//
double sl = requestLong ?
0 : // ll :
0; // ll;
double tp = requestLong ?
entryPrice + reward :
entryPrice - reward;
// //
// double fibLevel = 1.618;
// double fibLevelPrice = GetFibonacciLevel(
// tp,
// entryPrice,
// fibLevel,
// 1
// );
// //
// if (requestLong) {
// sl = fibLevelPrice;
// }
//
if (
//
// Condition 1 ...
(
tp > states[0].lc.hh
&& ll == states[0].sc.ll
&& states[0].sc.ll == states[0].mc.ll
)
||
//
// Condition 2 ...
(
states[0].sc.hh == states[0].mc.hh
&& states[0].lc.hh == states[0].mc.hh
&& states[0].sc.ll == states[0].mc.ll
)
) {
//
reward = risk * 1;
tp = requestLong ?
entryPrice + reward :
entryPrice - reward;
}
// //
// int rangeMarketLength = marketLen * longCycleMult;
// //
// XRange range = GetMarketRange(
// bar_index,
// rangeMarketLength,
// marketLen
// );
// //
// bool isRangeVerified = IsRangeVerified(
// bar_index,
// rangeMarketLength,
// marketLen,
// type,
// entryPrice,
// tp,
// range
// );
// //
// if (!isRangeVerified) {
// //
// // sl = requestLong ?
// // states[0].mc.ll :
// // states[0].mc.hh
// // ;
// }
//
datetime barTime = iTime(
_Symbol,
_Period,
bar_index
);
//
result.signal.tp = tp;
result.signal.sl = sl;
result.signal.type = type;
result.signal.time = barTime;
result.signal.tag = signalTag;
result.signal.symbol = _Symbol;
result.signal.entry = entryPrice;
result.signal.id = totalSignals + 1;
result.signal.provider = X_XXX_PROVIDER;
//
result.hasSignal = true;
result.type = type;
result.provider = X_XXX_PROVIDER;
//
return result;
}
//
// Validate Signal Conditions ...
bool ValidateXLongConditions(
const int marketLen,
const XState &states[],
//
const double smoother = 10
) {
//
bool isConditionsFilled =
xLongConds.startTime > 0
&& xLongConds.signalTime > 0
&& xLongConds.entryTime > 0
;
//
bool isBLFilled = false;
if (isConditionsFilled) {
//
int startBarIndex = iBarShift(
_Symbol,
_Period,
xLongConds.startTime
);
//
int signalBarIndex = iBarShift(
_Symbol,
_Period,
xLongConds.signalTime
);
//
isBLFilled =
//
xLongConds.signalTime > xLongConds.startTime
&& xLongConds.entryTime >= xLongConds.signalTime
&& MathAbs(signalBarIndex - startBarIndex) > 2
;
}
//
bool result =
isBLFilled
&& isConditionsFilled
&& xWaitForLongSignals
;
//
// Since maybe Conditions Filled but
// Slope is Negative, for Handling Next Signals and
// Prevent from infinity loop, here we Clear Signal Conditions ...
if (
!result
&& isConditionsFilled
) {
ClearXLongSignalConditions();
}
//
return result;
}
bool ValidateXShortConditions(
const int marketLen,
const XState &states[],
//
const double smoother = 10
) {
//
bool isConditionsFilled =
xShortConds.startTime > 0
&& xShortConds.signalTime > 0
&& xShortConds.entryTime > 0
;
//
bool isBLFilled = false;
if (isConditionsFilled) {
//
int startBarIndex = iBarShift(
_Symbol,
_Period,
xShortConds.startTime
);
//
int signalBarIndex = iBarShift(
_Symbol,
_Period,
xShortConds.signalTime
);
//
isBLFilled =
//
xShortConds.signalTime > xShortConds.startTime
&& xShortConds.entryTime >= xShortConds.signalTime
&& MathAbs(signalBarIndex - startBarIndex) > marketLen
;
}
//
bool result =
isBLFilled
&& isConditionsFilled
&& xWaitForLongSignals
;
//
// Since maybe Conditions Filled but
// Slope is Negative, for Handling Next Signals and
// Prevent from infinity loop, here we Clear Signal Conditions ...
if (
!result
&& isConditionsFilled
) {
ClearXShortSignalConditions();
}
//
return result;
}
//
// Clear Long Signal Conditions for New One ...
void ClearXLongSignalConditions() {
//
xLongConds.startTime = 0;
xLongConds.signalTime = 0;
}
//
// Clear Short Signal Conditions for New One ...
void ClearXShortSignalConditions() {
//
xShortConds.startTime = 0;
xShortConds.signalTime = 0;
}
//
// Check State for Long Signals ...
bool IsReadyForXSignals(
const XSignal &signal,
const XState &states[],
const int marketLen,
//
const int shortCycleMult,
const int mediumCycleMult,
const int longCycleMult,
//
double smoother = 10
) {
//
bool result = false;
//
bool isSCTrendUp = false;
bool isSCTrendDown = false;
//
bool isMCTrendUp = false;
bool isMCTrendDown = false;
//
bool isLCTrendUp = false;
bool isLCTrendDown = false;
//
XOHCL candle = GetCandleModel(0);
XOHCL pCandle = GetCandleModel(1);
// //
// bool isRange = false;
// int rangeMarketLength = 5 * marketLen;
// for (int i = 1; i < rangeMarketLength; i++) {
// //
// XState iState = GetXState(
// i,
// marketLen,
// 0.01,
// 0.1,
// shortCycleMult,
// mediumCycleMult,
// longCycleMult
// );
// //
// isRange =
// iState.mc.hh == iState.lc.hh
// && iState.mc.hh == states[0].mc.hh
// ;
// }
// //
// int statesLast = ArraySize(states) - 1;
// double scSlope =
// GetSlope(
// statesLast,
// states[statesLast].sc.slow,
// 0,
// states[0].sc.slow
// );
// double mcSlope =
// GetSlope(
// statesLast,
// states[statesLast].mc.slow,
// 0,
// states[0].mc.slow
// );
// double lcSlope =
// GetSlope(
// statesLast,
// states[statesLast].lc.slow,
// 0,
// states[0].lc.slow
// );
//
// Verify Long Signals ...
if (signal.type == X_SIGNAL_LONG) {
//
isSCTrendUp =
states[0].sc.fast < states[0].sc.slow
&& states[1].sc.fast < states[1].sc.slow
// && states[2].sc.fast < states[2].sc.slow
;
//
isMCTrendUp =
states[0].mc.fast < states[0].mc.slow
&& states[1].mc.fast < states[1].mc.slow
// && states[2].mc.fast < states[2].mc.slow
;
//
isLCTrendUp =
states[0].lc.fast < states[0].lc.slow
&& states[1].lc.fast < states[1].lc.slow
// && states[2].lc.fast < states[2].lc.slow
;
//
result =
//
// Starter ...
true
//
// Trending State ...
&& isSCTrendUp
&& isMCTrendUp
&& isLCTrendUp
//
// && !isRange
//
// Condition 1 ...
&& states[0].mc.fast > states[0].sc.slow
//
&& states[0].lc.slow < states[0].sc.ll
;
} else
//
// Verify Short Signals ...
if (signal.type == X_SIGNAL_SHORT) {
//
result =
false
;
}
// //
// if (result) {
// //
// LogMessage(
// StringConcatenate(
// "scSlope: ", scSlope,
// ", mcSlope: ", mcSlope,
// ", lcSlope: ", lcSlope
// )
// );
// }
//
return result;
}
//
// END Functions ...
//
@@ -0,0 +1,732 @@
///////////////////////////////////////////////////////
//
// SaherElm IT Center MQL4 X Signal Global Library
// ---------------------------------------------------
// saherelm useful tools and definitions ...
//
//
// Maintainer:
// ------------
// Hadi Khazaee Asl (hadi_khazaee_asl@yahoo.com)
//
//////////////////////////////////////////////////////
#property library
#property copyright "Copyright 2023, SaherElm IT Center"
#property link "https://www.saherelm.ir"
#property version "1.00"
#property strict
//
// Includes library ...
#include "../Libraries/x-saherelm.lib.mq4"
//
// Includes Indicator library ...
#include "../Libraries/x-saherelm.indicator.lib.mq4"
//
// Includes Models library ...
#include "../Libraries/x-saherelm.models.lib.mq4"
//
// START Inputs ...
//
input double xrR2R = 2; // XR Risk To Reward Ratio
//
input int xrOscillatorLength = 7; // XR Oscillator Length
input int xrFastLength = 20; // XR Fast Length
input int xrSlowLength = 50; // XR Slow Length
input int xrMarketRangeLength = 50; // XR Range Detector Length
//
input int xrSwingLength = 7; // Swing Length
//
// END Inputs ...
//
//
// START Global Requirement Functions ...
//
//
// XR Market State ...
struct XRMarketState {
//
double fast;
double slow;
//
double prevFast;
double prevSlow;
//
double oscillator;
double prevOscillator;
//
double verifier;
};
//
struct XRState {
//
datetime start;
int length;
//
double hh;
double ll;
double mid;
};
//
// XR Based Signal Conditions ...
struct XRSignalConditions {
//
datetime startTime;
datetime signalTime;
datetime entryTime;
//
double value;
XRState state;
};
//
static XRSignalConditions xrLongConds;
static bool xrCloseLongTrades = false;
static bool xrWaitForLongSignals = true;
//
static double xrMaximumDrawDown = 0;
//
// END Global Requirement Functions ...
//
//
// START Functions ...
//
//
// Check and Fill Long and Short Signal Handlers ...
void CheckXRSignalHandler(
const int bar_index
) {
//
// Check Market For Enable/Disable Signal Handlers ...
// Checking Market for Long Signals ...
//
XOHCL candle = GetCandleModel(bar_index);
//
XRMarketState state = GetXRMarketState(
bar_index
);
//
if (xrWaitForLongSignals) {
//
if (
state.oscillator < state.fast
&& state.oscillator < state.slow
&& state.prevOscillator < state.prevFast
&& state.prevOscillator < state.prevSlow
&& candle.low < xrMaximumDrawDown
) {
//
xrMaximumDrawDown = 0;
xrCloseLongTrades = true;
}
} else {
}
}
//
// Check and Fill Long Signal Conditions ...
void CheckXRLongSignalConditions(
const int bar_index
) {
//
datetime barTime = iTime(
_Symbol,
_Period,
bar_index
);
//
XOHCL candle = GetCandleModel(bar_index + 1);
//
XRState xrState = GetXRange(
bar_index
);
//
double affectedValue = xrState.mid;
//
XRMarketState state = GetXRMarketState(
bar_index
);
//
bool isCrossOver =
state.fast > state.slow
&& !(state.prevFast > state.prevSlow)
;
//
bool isCrossUnder =
state.fast < state.slow
&& !(state.prevFast < state.prevSlow)
;
//
if (
isCrossUnder
&& xrLongConds.startTime == 0
) {
//
xrLongConds.startTime = barTime;
return;
}
//
if (
isCrossOver
&& xrLongConds.startTime > 0
&& xrLongConds.signalTime == 0
) {
//
xrLongConds.value = affectedValue;
xrLongConds.state = xrState;
//
xrLongConds.signalTime = barTime;
xrLongConds.entryTime = barTime;
return;
}
}
//
// Convert Long Signal Conditions to XSignal ...
XSignalRequest GenerateXRSignal(
const ENUM_X_SIGNAL_TYPE type, // Signal Type ...
const string signalTag , // Signal Tag ...
const int bar_index
) {
//
XSignalRequest result = {};
//
result.hasSignal = false;
result.type = X_SIGNAL_NONE;
result.provider = X_UNKNOWN_PROVIDER;
//
bool requestLong = type == X_SIGNAL_LONG;
//
if (requestLong) {
//
if (
!ValidateXLongConditions()
) {
return result;
}
} else {
}
//
// Price Calculations ...
//
RefreshRates();
//
double askPrice = SymbolInfoDouble(
_Symbol,
SYMBOL_ASK
);
//
double bidPrice = SymbolInfoDouble(
_Symbol,
SYMBOL_BID
);
//
double entryPrice = requestLong ?
askPrice :
bidPrice;
//
double exitPrice = requestLong ?
bidPrice :
askPrice;
//
double priceGap = MathAbs(entryPrice - exitPrice);
//
double ll =
//
GetMarketLowestLow(
bar_index,
xrSwingLength
)
;
//
double hh =
//
GetMarketHighestHigh(
bar_index,
xrSwingLength
)
;
//
double openPrice = iOpen(
_Symbol,
_Period,
bar_index
);
//
double closePrice = iClose(
_Symbol,
_Period,
bar_index
);
//
double risk = requestLong ?
MathMin(openPrice, closePrice) - ll :
hh - MathMax(openPrice, closePrice);
double reward = risk * xrR2R;
//
double sl = requestLong ?
0 :
ll;
double tp = requestLong ?
entryPrice + reward :
entryPrice - reward
;
//
xrMaximumDrawDown =
xrMaximumDrawDown == 0 ?
xrLongConds.state.mid :
xrMaximumDrawDown > xrLongConds.state.mid ?
xrMaximumDrawDown :
xrLongConds.state.mid;
//
datetime barTime = iTime(
_Symbol,
_Period,
bar_index
);
//
result.signal.tp = tp;
result.signal.sl = sl;
result.signal.type = type;
result.signal.time = barTime;
result.signal.tag = signalTag;
result.signal.symbol = _Symbol;
result.signal.entry = entryPrice;
result.signal.id = totalSignals + 1;
result.signal.provider = X_XR_PROVIDER;
//
result.hasSignal = true;
result.type = type;
result.provider = X_XR_PROVIDER;
//
return result;
}
//
// Validate Signal Conditions ...
bool ValidateXLongConditions() {
//
bool isConditionsFilled =
xrLongConds.startTime > 0
&& xrLongConds.signalTime > 0
&& xrLongConds.entryTime > 0
//
&& xrLongConds.value > 0
;
//
bool isBLFilled = false;
if (isConditionsFilled) {
//
int startBarIndex = iBarShift(
_Symbol,
_Period,
xrLongConds.startTime
);
//
int signalBarIndex = iBarShift(
_Symbol,
_Period,
xrLongConds.signalTime
);
//
// Count Affected Value Touches ...
int cStartBarIndex = iBarShift(
_Symbol,
_Period,
xrLongConds.state.start
);
//
int cEndBarIndex = cStartBarIndex + xrLongConds.state.length;
//
int highTouched = 0;
int valueTouched = 0;
for (int i = cStartBarIndex; i <= cStartBarIndex + cEndBarIndex; i++) {
//
XOHCL iCandle = GetCandleModel(i);
//
if (
iCandle.low < xrLongConds.value
&& iCandle.high > xrLongConds.value
) {
valueTouched++;
}
//
if (
iCandle.low < xrLongConds.state.hh
&& iCandle.high > xrLongConds.state.hh
) {
highTouched++;
}
}
//
isBLFilled =
//
xrLongConds.signalTime > xrLongConds.startTime
&& xrLongConds.entryTime >= xrLongConds.signalTime
//
&& highTouched < 2
&& valueTouched > (cEndBarIndex - cStartBarIndex) / 6
;
}
//
bool result =
isBLFilled
&& isConditionsFilled
&& xrWaitForLongSignals
;
//
// Since maybe Conditions Filled but
// Slope is Negative, for Handling Next Signals and
// Prevent from infinity loop, here we Clear Signal Conditions ...
if (
!result
&& isConditionsFilled
) {
ClearXRLongSignalConditions();
}
//
return result;
}
//
// Clear Long Signal Conditions for New One ...
void ClearXRLongSignalConditions() {
//
xrLongConds.startTime = 0;
xrLongConds.signalTime = 0;
xrLongConds.entryTime = 0;
//
xrLongConds.value = 0;
//
XRState e = {};
xrLongConds.state = e;
}
//
// Check State for Long Signals ...
bool IsReadyForXRSignals(
const XSignal &signal
) {
//
bool result = false;
//
XRMarketState state = GetXRMarketState(0);
//
double fSDif = MathAbs(state.fast - state.slow);
double fSDifP = MathAbs(state.prevFast - state.prevSlow);
//
double emaSlope = GetSlope(
1,
state.prevOscillator,
2,
state.oscillator
);
//
XOHCL pCandle = GetCandleModel(1);
//
// Verify Long Signals ...
if (signal.type == X_SIGNAL_LONG) {
//
result =
//
// Starter ...
true
//
&& state.oscillator > state.fast
&& emaSlope > 0
&& signal.entry > state.verifier
//
&& fSDif > fSDifP
//
&& signal.entry < xrLongConds.state.hh
&& signal.entry > xrLongConds.state.mid
;
} else
//
// Verify Short Signals ...
if (signal.type == X_SIGNAL_SHORT) {
//
result =
false
;
}
//
return result;
}
//
// END Functions ...
//
//
// START Data Providers ...
//
//
static XRState lastXRState;
XRState GetXRange(
const int bar_index
) {
//
XRState result = {};
//
datetime barTime = iTime(
_Symbol,
_Period,
bar_index
);
//
int marketBarIndex = bar_index + xrMarketRangeLength;
//
// Highest High ...
//
int hhIdx = iHighest(
_Symbol,
_Period,
MODE_HIGH,
marketBarIndex,
bar_index
);
//
double hh = iHigh(
_Symbol,
_Period,
hhIdx
);
//
// Lowest Low ...
//
int llIdx = iLowest(
_Symbol,
_Period,
MODE_LOW,
marketBarIndex,
bar_index
);
//
double ll = iLow(
_Symbol,
_Period,
llIdx
);
//
if (lastXRState.start == 0) {
//
lastXRState.start = barTime;
lastXRState.length = xrMarketRangeLength;
//
lastXRState.hh = hh;
lastXRState.ll = ll;
//
// Middle ...
double mid = (hh + ll) / 2;
lastXRState.mid = mid;
} else {
//
int startBarIndex = iBarShift(
_Symbol,
_Period,
lastXRState.start
);
//
if (startBarIndex - bar_index >= xrMarketRangeLength) {
//
lastXRState.start = barTime;
lastXRState.length = xrMarketRangeLength;
//
lastXRState.hh = hh;
lastXRState.ll = ll;
//
// Middle ...
double mid = (hh + ll) / 2;
lastXRState.mid = mid;
}
}
//
result = lastXRState;
//
return result;
}
//
XRMarketState GetXRMarketState(
const int bar_index
) {
//
XRMarketState result = {};
//
// Prepare Market Length ...
int xrVerifierMarketLength = GetDailyCandleCount();
//
// Calculate Fast and Prev Fast ...
//
// Fast ...
double fast = GetMA(
bar_index + 1,
xrFastLength,
0,
MODE_SMA,
PRICE_CLOSE
);
//
// Prev Fast ...
double prevFast = GetMA(
bar_index + 2,
xrFastLength,
0,
MODE_SMA,
PRICE_CLOSE
);
//
// Calculate Slow and Prev Slow ...
//
// Slow ...
double slow = GetMA(
bar_index + 1,
xrSlowLength,
0,
MODE_SMA,
PRICE_CLOSE
);
//
// Prev Slow ...
double prevSlow = GetMA(
bar_index + 2,
xrSlowLength,
0,
MODE_SMA,
PRICE_CLOSE
);
//
// Calculate Oscillator and Prev Oscillator ...
//
// Oscillator ...
double oscillator = GetMA(
bar_index,
xrOscillatorLength,
0,
MODE_EMA,
PRICE_CLOSE
);
//
// Prev Oscillator ...
double prevOscillator = GetMA(
bar_index + 1,
xrOscillatorLength,
0,
MODE_EMA,
PRICE_CLOSE
);
//
// Calculate Verifier ...
double verifier = GetMA(
bar_index,
xrVerifierMarketLength,
0,
MODE_EMA,
PRICE_CLOSE
);
//
result.fast = fast;
result.slow = slow;
result.verifier = verifier;
result.prevFast = prevFast;
result.prevSlow = prevSlow;
result.oscillator = oscillator;
result.prevOscillator = prevOscillator;
//
return result;
}
//
// END Data Providers ...
//