USDCHF session playbook: thinner, but cleaner at times
Re: USDCHF session playbook: thinner, but cleaner at times
Key ModificationsRatio Decomposition:
The logic breaks the completed M15 candle into totalLength, bodyLength, lowerWick, and upperWick to calculate exact proportions independently of pure pip size.
Tolerance Inputs (MaxBodyRatio & MinTailRatio): You can fine-tune what constitutes a valid shape without changing the code. The 0.3/0.6 defaults ensure the tail is at least twice the size of the body, suppressing trades on dojis or spinning tops.
Color Requisite (RequireColorMatch): Standard textbook logic demands that a valid bullish pin bar closes green (Open < Close) to prove momentum rejection. You can toggle this to false if you prefer to trade structural rejections regardless of the close color.
The logic breaks the completed M15 candle into totalLength, bodyLength, lowerWick, and upperWick to calculate exact proportions independently of pure pip size.
Tolerance Inputs (MaxBodyRatio & MinTailRatio): You can fine-tune what constitutes a valid shape without changing the code. The 0.3/0.6 defaults ensure the tail is at least twice the size of the body, suppressing trades on dojis or spinning tops.
Color Requisite (RequireColorMatch): Standard textbook logic demands that a valid bullish pin bar closes green (Open < Close) to prove momentum rejection. You can toggle this to false if you prefer to trade structural rejections regardless of the close color.
Re: USDCHF session playbook: thinner, but cleaner at times
To prevent execution when liquidity drops or volatility causes IC Markets to widen spreads past your acceptable threshold, you can query the live SYMBOL_ASK and SYMBOL_BID prices, calculate the exact pip difference, and create a strict conditional lockout.
Because we are checking for a closed M15 candle, if the spread is too high at the moment the new candle opens, we must intentionally set lastBarTime = currentBarTime; to "burn" the signal. This prevents the EA from waiting a few seconds for the spread to drop and entering late, which would ruin your precision.
Because we are checking for a closed M15 candle, if the spread is too high at the moment the new candle opens, we must intentionally set lastBarTime = currentBarTime; to "burn" the signal. This prevents the EA from waiting a few seconds for the spread to drop and entering late, which would ruin your precision.
Re: USDCHF session playbook: thinner, but cleaner at times
Here is the updated script with the dynamic spread filter integrated:
Code: Select all
//+------------------------------------------------------------------+
//| USDCHF_London.mq5 |
//| Strict Price Action Scalping EA (Confluence, Pins & Spread) |
//+------------------------------------------------------------------+
#property copyright "Bc. Pavel Tuček"
#property version "1.30"
#include <Trade\Trade.mqh>
CTrade trade;
//--- Inputs
input string TimeSettings = "--- Trading Window (IC Markets Server Time) ---";
input int StartHour = 9; // IC Markets 09:00 = 07:00 UK
input int EndHour = 10; // IC Markets 10:00 = 08:00 UK
input string RiskSettings = "--- Risk & Money Management ---";
input double RiskPercent = 2.0; // Percentage of balance to risk
input int StopLossPips = 9; // Stop Loss in pips (Risk 3)
input int TakeProfitPips = 3; // Take Profit in pips (Reward 1)
input string PriceAction = "--- S/R & Execution Parameters ---";
input int LookbackD1 = 10; // D1 bars to scan for macro S/R
input int LookbackH4 = 20; // H4 bars to scan for micro S/R
input int ConfluencePips = 15; // Max distance between D1/H4 zones
input int ZoneTolerancePips = 2; // M15 proximity to zone to trigger trade
input string PinBarSettings = "--- Pin Bar Anatomy ---";
input double MaxBodyRatio = 0.3; // Body must be <= 30% of total candle length
input double MinTailRatio = 0.6; // Tail must be >= 60% of total candle length
input bool RequireColorMatch = true; // Bullish pin must close green, Bearish must close red
input string ExecutionFilters = "--- Spread Safeguards ---";
input double MaxSpreadPips = 1.5; // Maximum allowed live spread in pips
//--- Global Variables
double point;
double pipsMultiplier;
datetime lastBarTime;
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
point = SymbolInfoDouble(_Symbol, SYMBOL_POINT);
int digits = (int)SymbolInfoInteger(_Symbol, SYMBOL_DIGITS);
pipsMultiplier = (digits == 3 || digits == 5) ? 10.0 : 1.0;
trade.SetExpertMagicNumber(777126);
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
// 1. Check if we are on a new M15 bar
datetime currentBarTime = iTime(_Symbol, PERIOD_M15, 0);
if(currentBarTime == lastBarTime) return;
// 2. Check Time Window
MqlDateTime dt;
TimeToStruct(TimeCurrent(), dt);
if(dt.hour < StartHour || dt.hour >= EndHour) return;
// 3. Ensure no open positions
if(PositionsTotal() > 0) return;
// 4. Calculate D1 and H4 Support and Resistance Zones
double resistanceD1 = GetHighestHigh(PERIOD_D1, LookbackD1);
double supportD1 = GetLowestLow(PERIOD_D1, LookbackD1);
double resistanceH4 = GetHighestHigh(PERIOD_H4, LookbackH4);
double supportH4 = GetLowestLow(PERIOD_H4, LookbackH4);
// 5. Confluence Validation
double confluenceTol = ConfluencePips * pipsMultiplier * point;
bool buyConfluence = MathAbs(supportH4 - supportD1) <= confluenceTol;
bool sellConfluence = MathAbs(resistanceH4 - resistanceD1) <= confluenceTol;
// 6. M15 Price Action Data
double currentClose = iClose(_Symbol, PERIOD_M15, 1);
double currentOpen = iOpen(_Symbol, PERIOD_M15, 1);
double currentHigh = iHigh(_Symbol, PERIOD_M15, 1);
double currentLow = iLow(_Symbol, PERIOD_M15, 1);
// 7. Pin Bar Anatomy Calculation
double totalLength = currentHigh - currentLow;
if(totalLength == 0) return;
double bodyLength = MathAbs(currentOpen - currentClose);
double lowerWick = MathMin(currentOpen, currentClose) - currentLow;
double upperWick = currentHigh - MathMax(currentOpen, currentClose);
bool isSmallBody = (bodyLength / totalLength) <= MaxBodyRatio;
bool isBullishColor = RequireColorMatch ? (currentClose > currentOpen) : true;
bool isBullishPinBar = isSmallBody && ((lowerWick / totalLength) >= MinTailRatio) && isBullishColor;
bool isBearishColor = RequireColorMatch ? (currentClose < currentOpen) : true;
bool isBearishPinBar = isSmallBody && ((upperWick / totalLength) >= MinTailRatio) && isBearishColor;
double execTolerance = ZoneTolerancePips * pipsMultiplier * point;
// 8. Live Spread Calculation
double currentAsk = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
double currentBid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
double liveSpreadPips = (currentAsk - currentBid) / (point * pipsMultiplier);
// Buy Setup
if(buyConfluence && currentLow <= supportH4 + execTolerance && isBullishPinBar)
{
if(liveSpreadPips > MaxSpreadPips)
{
Print("Buy trade canceled: Live spread is ", NormalizeDouble(liveSpreadPips, 1), " pips. (Max allowed: ", MaxSpreadPips, ")");
lastBarTime = currentBarTime; // Lock out to prevent late entry
return;
}
double sl = NormalizeDouble(currentAsk - (StopLossPips * pipsMultiplier * point), _Digits);
double tp = NormalizeDouble(currentAsk + (TakeProfitPips * pipsMultiplier * point), _Digits);
double lotSize = CalculateLotSize(MathAbs(currentAsk - sl));
trade.Buy(lotSize, _Symbol, 0, sl, tp, "Pin Bar Buy");
lastBarTime = currentBarTime;
}
// Sell Setup
if(sellConfluence && currentHigh >= resistanceH4 - execTolerance && isBearishPinBar)
{
if(liveSpreadPips > MaxSpreadPips)
{
Print("Sell trade canceled: Live spread is ", NormalizeDouble(liveSpreadPips, 1), " pips. (Max allowed: ", MaxSpreadPips, ")");
lastBarTime = currentBarTime;
return;
}
double sl = NormalizeDouble(currentBid + (StopLossPips * pipsMultiplier * point), _Digits);
double tp = NormalizeDouble(currentBid - (TakeProfitPips * pipsMultiplier * point), _Digits);
double lotSize = CalculateLotSize(MathAbs(sl - currentBid));
trade.Sell(lotSize, _Symbol, 0, sl, tp, "Pin Bar Sell");
lastBarTime = currentBarTime;
}
}
//+------------------------------------------------------------------+
//| Get Highest High for S/R mapping |
//+------------------------------------------------------------------+
double GetHighestHigh(ENUM_TIMEFRAMES period, int count)
{
double high[];
ArraySetAsSeries(high, true);
CopyHigh(_Symbol, period, 1, count, high);
return high[ArrayMaximum(high, 0, count)];
}
//+------------------------------------------------------------------+
//| Get Lowest Low for S/R mapping |
//+------------------------------------------------------------------+
double GetLowestLow(ENUM_TIMEFRAMES period, int count)
{
double low[];
ArraySetAsSeries(low, true);
CopyLow(_Symbol, period, 1, count, low);
return low[ArrayMinimum(low, 0, count)];
}
//+------------------------------------------------------------------+
//| Exponential Money Management Calculation |
//+------------------------------------------------------------------+
double CalculateLotSize(double slDistance)
{
double equity = AccountInfoDouble(ACCOUNT_EQUITY);
double riskAmount = equity * (RiskPercent / 100.0);
double tickValue = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_VALUE);
double tickSize = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE);
if(slDistance == 0 || tickValue == 0) return 0.01;
double stepCalc = slDistance / tickSize;
double lotSize = riskAmount / (stepCalc * tickValue);
double minLot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN);
double maxLot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX);
double stepLot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP);
lotSize = MathFloor(lotSize / stepLot) * stepLot;
if(lotSize < minLot) lotSize = minLot;
if(lotSize > maxLot) lotSize = maxLot;
return lotSize;
}Re: USDCHF session playbook: thinner, but cleaner at times
Key ModificationsLive Spread Math (liveSpreadPips):
Extracted SYMBOL_ASK and SYMBOL_BID dynamically directly before the execution condition, neutralizing it against the point multiplier to give you a clean decimal representation in pips.
Lockout Logic: By calling lastBarTime = currentBarTime; inside the rejection block, the EA registers the bar as "processed" and will not evaluate again until the next 15-minute candle opens, preserving the strict temporal constraints of price action execution.
Console Logging (Print): If a trade setup appears valid but is killed by the spread, the EA prints the exact live spread alongside the threshold directly into the MT5 Journal tab so you can audit broker conditions historically.
Extracted SYMBOL_ASK and SYMBOL_BID dynamically directly before the execution condition, neutralizing it against the point multiplier to give you a clean decimal representation in pips.
Lockout Logic: By calling lastBarTime = currentBarTime; inside the rejection block, the EA registers the bar as "processed" and will not evaluate again until the next 15-minute candle opens, preserving the strict temporal constraints of price action execution.
Console Logging (Print): If a trade setup appears valid but is killed by the spread, the EA prints the exact live spread alongside the threshold directly into the MT5 Journal tab so you can audit broker conditions historically.
Re: USDCHF session playbook: thinner, but cleaner at times
By utilizing the standard library's CTrade class, adding slippage control is highly efficient. You simply define the maximum acceptable deviation in points during the initialization phase, and the CTrade object automatically appends this parameter to every market order it routes to the broker.
If the broker's server attempts to fill the order at a price outside your allowed deviation—which is critical for your tight 3-pip stop loss strategy—the server rejects the execution outright.
If the broker's server attempts to fill the order at a price outside your allowed deviation—which is critical for your tight 3-pip stop loss strategy—the server rejects the execution outright.
Re: USDCHF session playbook: thinner, but cleaner at times
Here is the updated script integrating the maximum deviation parameter:
Code: Select all
//+------------------------------------------------------------------+
//| USDCHF_London.mq5 |
//| Strict Price Action Scalping EA (Confluence, Pins, Slippage) |
//+------------------------------------------------------------------+
#property copyright "Bc. Pavel Tuček"
#property version "1.40"
#include <Trade\Trade.mqh>
CTrade trade;
//--- Inputs
input string TimeSettings = "--- Trading Window (IC Markets Server Time) ---";
input int StartHour = 9; // IC Markets 09:00 = 07:00 UK
input int EndHour = 10; // IC Markets 10:00 = 08:00 UK
input string RiskSettings = "--- Risk & Money Management ---";
input double RiskPercent = 2.0; // Percentage of balance to risk
input int StopLossPips = 9; // Stop Loss in pips (Risk 3)
input int TakeProfitPips = 3; // Take Profit in pips (Reward 1)
input string PriceAction = "--- S/R & Execution Parameters ---";
input int LookbackD1 = 10; // D1 bars to scan for macro S/R
input int LookbackH4 = 20; // H4 bars to scan for micro S/R
input int ConfluencePips = 15; // Max distance between D1/H4 zones
input int ZoneTolerancePips = 2; // M15 proximity to zone to trigger trade
input string PinBarSettings = "--- Pin Bar Anatomy ---";
input double MaxBodyRatio = 0.3; // Body must be <= 30% of total candle length
input double MinTailRatio = 0.6; // Tail must be >= 60% of total candle length
input bool RequireColorMatch = true; // Bullish pin must close green, Bearish must close red
input string ExecutionFilters = "--- Spread & Slippage Safeguards ---";
input double MaxSpreadPips = 1.5; // Maximum allowed live spread in pips
input double MaxSlippagePips = 0.5; // Maximum allowed slippage deviation in pips
//--- Global Variables
double point;
double pipsMultiplier;
datetime lastBarTime;
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
point = SymbolInfoDouble(_Symbol, SYMBOL_POINT);
int digits = (int)SymbolInfoInteger(_Symbol, SYMBOL_DIGITS);
pipsMultiplier = (digits == 3 || digits == 5) ? 10.0 : 1.0;
// Set magic number and maximum slippage deviation
trade.SetExpertMagicNumber(777127);
ulong deviationPoints = (ulong)(MaxSlippagePips * pipsMultiplier);
trade.SetDeviationInPoints(deviationPoints);
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
// 1. Check if we are on a new M15 bar
datetime currentBarTime = iTime(_Symbol, PERIOD_M15, 0);
if(currentBarTime == lastBarTime) return;
// 2. Check Time Window
MqlDateTime dt;
TimeToStruct(TimeCurrent(), dt);
if(dt.hour < StartHour || dt.hour >= EndHour) return;
// 3. Ensure no open positions
if(PositionsTotal() > 0) return;
// 4. Calculate D1 and H4 Support and Resistance Zones
double resistanceD1 = GetHighestHigh(PERIOD_D1, LookbackD1);
double supportD1 = GetLowestLow(PERIOD_D1, LookbackD1);
double resistanceH4 = GetHighestHigh(PERIOD_H4, LookbackH4);
double supportH4 = GetLowestLow(PERIOD_H4, LookbackH4);
// 5. Confluence Validation
double confluenceTol = ConfluencePips * pipsMultiplier * point;
bool buyConfluence = MathAbs(supportH4 - supportD1) <= confluenceTol;
bool sellConfluence = MathAbs(resistanceH4 - resistanceD1) <= confluenceTol;
// 6. M15 Price Action Data
double currentClose = iClose(_Symbol, PERIOD_M15, 1);
double currentOpen = iOpen(_Symbol, PERIOD_M15, 1);
double currentHigh = iHigh(_Symbol, PERIOD_M15, 1);
double currentLow = iLow(_Symbol, PERIOD_M15, 1);
// 7. Pin Bar Anatomy Calculation
double totalLength = currentHigh - currentLow;
if(totalLength == 0) return;
double bodyLength = MathAbs(currentOpen - currentClose);
double lowerWick = MathMin(currentOpen, currentClose) - currentLow;
double upperWick = currentHigh - MathMax(currentOpen, currentClose);
bool isSmallBody = (bodyLength / totalLength) <= MaxBodyRatio;
bool isBullishColor = RequireColorMatch ? (currentClose > currentOpen) : true;
bool isBullishPinBar = isSmallBody && ((lowerWick / totalLength) >= MinTailRatio) && isBullishColor;
bool isBearishColor = RequireColorMatch ? (currentClose < currentOpen) : true;
bool isBearishPinBar = isSmallBody && ((upperWick / totalLength) >= MinTailRatio) && isBearishColor;
double execTolerance = ZoneTolerancePips * pipsMultiplier * point;
// 8. Live Spread Calculation
double currentAsk = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
double currentBid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
double liveSpreadPips = (currentAsk - currentBid) / (point * pipsMultiplier);
// Buy Setup
if(buyConfluence && currentLow <= supportH4 + execTolerance && isBullishPinBar)
{
if(liveSpreadPips > MaxSpreadPips)
{
Print("Buy trade canceled: Live spread is ", NormalizeDouble(liveSpreadPips, 1), " pips. (Max allowed: ", MaxSpreadPips, ")");
lastBarTime = currentBarTime;
return;
}
double sl = NormalizeDouble(currentAsk - (StopLossPips * pipsMultiplier * point), _Digits);
double tp = NormalizeDouble(currentAsk + (TakeProfitPips * pipsMultiplier * point), _Digits);
double lotSize = CalculateLotSize(MathAbs(currentAsk - sl));
trade.Buy(lotSize, _Symbol, 0, sl, tp, "Pin Bar Buy");
lastBarTime = currentBarTime;
}
// Sell Setup
if(sellConfluence && currentHigh >= resistanceH4 - execTolerance && isBearishPinBar)
{
if(liveSpreadPips > MaxSpreadPips)
{
Print("Sell trade canceled: Live spread is ", NormalizeDouble(liveSpreadPips, 1), " pips. (Max allowed: ", MaxSpreadPips, ")");
lastBarTime = currentBarTime;
return;
}
double sl = NormalizeDouble(currentBid + (StopLossPips * pipsMultiplier * point), _Digits);
double tp = NormalizeDouble(currentBid - (TakeProfitPips * pipsMultiplier * point), _Digits);
double lotSize = CalculateLotSize(MathAbs(sl - currentBid));
trade.Sell(lotSize, _Symbol, 0, sl, tp, "Pin Bar Sell");
lastBarTime = currentBarTime;
}
}
//+------------------------------------------------------------------+
//| Get Highest High for S/R mapping |
//+------------------------------------------------------------------+
double GetHighestHigh(ENUM_TIMEFRAMES period, int count)
{
double high[];
ArraySetAsSeries(high, true);
CopyHigh(_Symbol, period, 1, count, high);
return high[ArrayMaximum(high, 0, count)];
}
//+------------------------------------------------------------------+
//| Get Lowest Low for S/R mapping |
//+------------------------------------------------------------------+
double GetLowestLow(ENUM_TIMEFRAMES period, int count)
{
double low[];
ArraySetAsSeries(low, true);
CopyLow(_Symbol, period, 1, count, low);
return low[ArrayMinimum(low, 0, count)];
}
//+------------------------------------------------------------------+
//| Exponential Money Management Calculation |
//+------------------------------------------------------------------+
double CalculateLotSize(double slDistance)
{
double equity = AccountInfoDouble(ACCOUNT_EQUITY);
double riskAmount = equity * (RiskPercent / 100.0);
double tickValue = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_VALUE);
double tickSize = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE);
if(slDistance == 0 || tickValue == 0) return 0.01;
double stepCalc = slDistance / tickSize;
double lotSize = riskAmount / (stepCalc * tickValue);
double minLot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN);
double maxLot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX);
double stepLot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP);
lotSize = MathFloor(lotSize / stepLot) * stepLot;
if(lotSize < minLot) lotSize = minLot;
if(lotSize > maxLot) lotSize = maxLot;
return lotSize;
}Re: USDCHF session playbook: thinner, but cleaner at times
Key Modifications:
Input Addition (MaxSlippagePips): An input allowing you to define maximum slippage. At 0.5, you are telling IC Markets you refuse any fill that worsens your price by more than half a pip.
CTrade Configuration (OnInit): MQL5 requires deviation measured strictly in raw points (an unsigned long integer, ulong). The script calculates deviationPoints using your pipsMultiplier and registers it directly into the trade instance via trade.SetDeviationInPoints().
Execution Flow: You do not need to manually pass the deviation limit into the .Buy() or .Sell() calls inside OnTick(). The configured CTrade object handles appending it to the backend MqlTradeRequest structure automatically.
Input Addition (MaxSlippagePips): An input allowing you to define maximum slippage. At 0.5, you are telling IC Markets you refuse any fill that worsens your price by more than half a pip.
CTrade Configuration (OnInit): MQL5 requires deviation measured strictly in raw points (an unsigned long integer, ulong). The script calculates deviationPoints using your pipsMultiplier and registers it directly into the trade instance via trade.SetDeviationInPoints().
Execution Flow: You do not need to manually pass the deviation limit into the .Buy() or .Sell() calls inside OnTick(). The configured CTrade object handles appending it to the backend MqlTradeRequest structure automatically.
Re: USDCHF session playbook: thinner, but cleaner at times
By querying the MqlDateTime structure, we can extract the specific day of the week (day_of_week) and block any new trade executions past a designated hour on Fridays.
While your current strategy parameters specifically restrict trading to the 09:00–10:00 broker time window (meaning a Friday afternoon cutoff is technically redundant right now), adding this dedicated filter ensures your risk management remains intact if you later decide to expand the EndHour for other sessions or pairs.
While your current strategy parameters specifically restrict trading to the 09:00–10:00 broker time window (meaning a Friday afternoon cutoff is technically redundant right now), adding this dedicated filter ensures your risk management remains intact if you later decide to expand the EndHour for other sessions or pairs.
Re: USDCHF session playbook: thinner, but cleaner at times
Here is the updated script with the Friday gap filter integrated:
Code: Select all
//+------------------------------------------------------------------+
//| USDCHF_London.mq5 |
//| Strict PA Scalping EA (Confluence, Pins, Slippage, Friday Filter)|
//+------------------------------------------------------------------+
#property copyright "Bc. Pavel Tuček"
#property version "1.50"
#include <Trade\Trade.mqh>
CTrade trade;
//--- Inputs
input string TimeSettings = "--- Trading Window (IC Markets Server Time) ---";
input int StartHour = 9; // IC Markets 09:00 = 07:00 UK
input int EndHour = 10; // IC Markets 10:00 = 08:00 UK
input string RiskSettings = "--- Risk & Money Management ---";
input double RiskPercent = 2.0; // Percentage of balance to risk
input int StopLossPips = 9; // Stop Loss in pips (Risk 3)
input int TakeProfitPips = 3; // Take Profit in pips (Reward 1)
input string PriceAction = "--- S/R & Execution Parameters ---";
input int LookbackD1 = 10; // D1 bars to scan for macro S/R
input int LookbackH4 = 20; // H4 bars to scan for micro S/R
input int ConfluencePips = 15; // Max distance between D1/H4 zones
input int ZoneTolerancePips = 2; // M15 proximity to zone to trigger trade
input string PinBarSettings = "--- Pin Bar Anatomy ---";
input double MaxBodyRatio = 0.3; // Body must be <= 30% of total candle length
input double MinTailRatio = 0.6; // Tail must be >= 60% of total candle length
input bool RequireColorMatch = true; // Bullish pin must close green, Bearish must close red
input string ExecutionFilters = "--- Execution Safeguards & Filters ---";
input double MaxSpreadPips = 1.5; // Maximum allowed live spread in pips
input double MaxSlippagePips = 0.5; // Maximum allowed slippage deviation in pips
input bool StopFridayTrading = true; // Block new trades on Friday afternoons
input int FridayStopHour = 16; // IC Markets server hour to halt trading on Fridays
//--- Global Variables
double point;
double pipsMultiplier;
datetime lastBarTime;
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
point = SymbolInfoDouble(_Symbol, SYMBOL_POINT);
int digits = (int)SymbolInfoInteger(_Symbol, SYMBOL_DIGITS);
pipsMultiplier = (digits == 3 || digits == 5) ? 10.0 : 1.0;
trade.SetExpertMagicNumber(777128);
ulong deviationPoints = (ulong)(MaxSlippagePips * pipsMultiplier);
trade.SetDeviationInPoints(deviationPoints);
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
// 1. Check if we are on a new M15 bar
datetime currentBarTime = iTime(_Symbol, PERIOD_M15, 0);
if(currentBarTime == lastBarTime) return;
// 2. Check Time Window & Friday Filter
MqlDateTime dt;
TimeToStruct(TimeCurrent(), dt);
if(StopFridayTrading && dt.day_of_week == 5 && dt.hour >= FridayStopHour) return;
if(dt.hour < StartHour || dt.hour >= EndHour) return;
// 3. Ensure no open positions
if(PositionsTotal() > 0) return;
// 4. Calculate D1 and H4 Support and Resistance Zones
double resistanceD1 = GetHighestHigh(PERIOD_D1, LookbackD1);
double supportD1 = GetLowestLow(PERIOD_D1, LookbackD1);
double resistanceH4 = GetHighestHigh(PERIOD_H4, LookbackH4);
double supportH4 = GetLowestLow(PERIOD_H4, LookbackH4);
// 5. Confluence Validation
double confluenceTol = ConfluencePips * pipsMultiplier * point;
bool buyConfluence = MathAbs(supportH4 - supportD1) <= confluenceTol;
bool sellConfluence = MathAbs(resistanceH4 - resistanceD1) <= confluenceTol;
// 6. M15 Price Action Data
double currentClose = iClose(_Symbol, PERIOD_M15, 1);
double currentOpen = iOpen(_Symbol, PERIOD_M15, 1);
double currentHigh = iHigh(_Symbol, PERIOD_M15, 1);
double currentLow = iLow(_Symbol, PERIOD_M15, 1);
// 7. Pin Bar Anatomy Calculation
double totalLength = currentHigh - currentLow;
if(totalLength == 0) return;
double bodyLength = MathAbs(currentOpen - currentClose);
double lowerWick = MathMin(currentOpen, currentClose) - currentLow;
double upperWick = currentHigh - MathMax(currentOpen, currentClose);
bool isSmallBody = (bodyLength / totalLength) <= MaxBodyRatio;
bool isBullishColor = RequireColorMatch ? (currentClose > currentOpen) : true;
bool isBullishPinBar = isSmallBody && ((lowerWick / totalLength) >= MinTailRatio) && isBullishColor;
bool isBearishColor = RequireColorMatch ? (currentClose < currentOpen) : true;
bool isBearishPinBar = isSmallBody && ((upperWick / totalLength) >= MinTailRatio) && isBearishColor;
double execTolerance = ZoneTolerancePips * pipsMultiplier * point;
// 8. Live Spread Calculation
double currentAsk = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
double currentBid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
double liveSpreadPips = (currentAsk - currentBid) / (point * pipsMultiplier);
// Buy Setup
if(buyConfluence && currentLow <= supportH4 + execTolerance && isBullishPinBar)
{
if(liveSpreadPips > MaxSpreadPips)
{
Print("Buy trade canceled: Live spread is ", NormalizeDouble(liveSpreadPips, 1), " pips. (Max allowed: ", MaxSpreadPips, ")");
lastBarTime = currentBarTime;
return;
}
double sl = NormalizeDouble(currentAsk - (StopLossPips * pipsMultiplier * point), _Digits);
double tp = NormalizeDouble(currentAsk + (TakeProfitPips * pipsMultiplier * point), _Digits);
double lotSize = CalculateLotSize(MathAbs(currentAsk - sl));
trade.Buy(lotSize, _Symbol, 0, sl, tp, "Pin Bar Buy");
lastBarTime = currentBarTime;
}
// Sell Setup
if(sellConfluence && currentHigh >= resistanceH4 - execTolerance && isBearishPinBar)
{
if(liveSpreadPips > MaxSpreadPips)
{
Print("Sell trade canceled: Live spread is ", NormalizeDouble(liveSpreadPips, 1), " pips. (Max allowed: ", MaxSpreadPips, ")");
lastBarTime = currentBarTime;
return;
}
double sl = NormalizeDouble(currentBid + (StopLossPips * pipsMultiplier * point), _Digits);
double tp = NormalizeDouble(currentBid - (TakeProfitPips * pipsMultiplier * point), _Digits);
double lotSize = CalculateLotSize(MathAbs(sl - currentBid));
trade.Sell(lotSize, _Symbol, 0, sl, tp, "Pin Bar Sell");
lastBarTime = currentBarTime;
}
}
//+------------------------------------------------------------------+
//| Get Highest High for S/R mapping |
//+------------------------------------------------------------------+
double GetHighestHigh(ENUM_TIMEFRAMES period, int count)
{
double high[];
ArraySetAsSeries(high, true);
CopyHigh(_Symbol, period, 1, count, high);
return high[ArrayMaximum(high, 0, count)];
}
//+------------------------------------------------------------------+
//| Get Lowest Low for S/R mapping |
//+------------------------------------------------------------------+
double GetLowestLow(ENUM_TIMEFRAMES period, int count)
{
double low[];
ArraySetAsSeries(low, true);
CopyLow(_Symbol, period, 1, count, low);
return low[ArrayMinimum(low, 0, count)];
}
//+------------------------------------------------------------------+
//| Exponential Money Management Calculation |
//+------------------------------------------------------------------+
double CalculateLotSize(double slDistance)
{
double equity = AccountInfoDouble(ACCOUNT_EQUITY);
double riskAmount = equity * (RiskPercent / 100.0);
double tickValue = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_VALUE);
double tickSize = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE);
if(slDistance == 0 || tickValue == 0) return 0.01;
double stepCalc = slDistance / tickSize;
double lotSize = riskAmount / (stepCalc * tickValue);
double minLot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN);
double maxLot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX);
double stepLot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP);
lotSize = MathFloor(lotSize / stepLot) * stepLot;
if(lotSize < minLot) lotSize = minLot;
if(lotSize > maxLot) lotSize = maxLot;
return lotSize;
}Re: USDCHF session playbook: thinner, but cleaner at times
Key Modifications:
Day of Week Mapping (dt.day_of_week == 5): In MQL5, 0 is Sunday and 5 is Friday. The condition explicitly targets Friday server time.
Filter Hierarchy: The Friday check happens at step 2, immediately before the standard daily trading window check. If it is Friday and past the input hour, it returns and aborts the tick cycle before any resource-heavy array mapping or price calculations execute.
Day of Week Mapping (dt.day_of_week == 5): In MQL5, 0 is Sunday and 5 is Friday. The condition explicitly targets Friday server time.
Filter Hierarchy: The Friday check happens at step 2, immediately before the standard daily trading window check. If it is Friday and past the input hour, it returns and aborts the tick cycle before any resource-heavy array mapping or price calculations execute.