USDCHF session playbook: thinner, but cleaner at times
Re: USDCHF session playbook: thinner, but cleaner at times
Automating the data extraction directly into a CSV file completely eliminates the need to maintain a manual written journal. The data passively accumulates throughout your 2-to-6 week trading series, sitting locally on your machine for a batch review when you take your break.
Here is the updated script. It uses MQL5's native file handling to append a new row to a CSV file every time the broker successfully fills an order.
Here is the updated script. It uses MQL5's native file handling to append a new row to a CSV file every time the broker successfully fills an order.
Re: USDCHF session playbook: thinner, but cleaner at times
MQL5 code:
Code: Select all
//+------------------------------------------------------------------+
//| USDCHF_London.mq5 |
//| Strict PA Scalping EA (Confluence, Pins, Friday, CSV Log) |
//+------------------------------------------------------------------+
#property copyright "Bc. Pavel Tuček"
#property version "1.60"
#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
input string LoggingSettings = "--- CSV Journal Logging ---";
input string LogFileName = "USDCHF_Series_Log.csv"; // Saved in MQL5\Files\
//--- 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(777129);
ulong deviationPoints = (ulong)(MaxSlippagePips * pipsMultiplier);
trade.SetDeviationInPoints(deviationPoints);
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
datetime currentBarTime = iTime(_Symbol, PERIOD_M15, 0);
if(currentBarTime == lastBarTime) return;
MqlDateTime dt;
TimeToStruct(TimeCurrent(), dt);
if(StopFridayTrading && dt.day_of_week == 5 && dt.hour >= FridayStopHour) return;
if(dt.hour < StartHour || dt.hour >= EndHour) return;
if(PositionsTotal() > 0) return;
double resistanceD1 = GetHighestHigh(PERIOD_D1, LookbackD1);
double supportD1 = GetLowestLow(PERIOD_D1, LookbackD1);
double resistanceH4 = GetHighestHigh(PERIOD_H4, LookbackH4);
double supportH4 = GetLowestLow(PERIOD_H4, LookbackH4);
double confluenceTol = ConfluencePips * pipsMultiplier * point;
bool buyConfluence = MathAbs(supportH4 - supportD1) <= confluenceTol;
bool sellConfluence = MathAbs(resistanceH4 - resistanceD1) <= confluenceTol;
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);
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;
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.");
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));
// Execute and verify success before logging
if(trade.Buy(lotSize, _Symbol, 0, sl, tp, "Pin Bar Buy"))
{
LogTradeToCSV("BUY", currentAsk, sl, tp, liveSpreadPips, lotSize, "Bullish Pin + D1/H4 Confluence");
}
lastBarTime = currentBarTime;
}
// Sell Setup
if(sellConfluence && currentHigh >= resistanceH4 - execTolerance && isBearishPinBar)
{
if(liveSpreadPips > MaxSpreadPips)
{
Print("Sell trade canceled: Live spread is ", NormalizeDouble(liveSpreadPips, 1), " pips.");
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));
// Execute and verify success before logging
if(trade.Sell(lotSize, _Symbol, 0, sl, tp, "Pin Bar Sell"))
{
LogTradeToCSV("SELL", currentBid, sl, tp, liveSpreadPips, lotSize, "Bearish Pin + D1/H4 Confluence");
}
lastBarTime = currentBarTime;
}
}
//+------------------------------------------------------------------+
//| Log Executed Trade to CSV File |
//+------------------------------------------------------------------+
void LogTradeToCSV(string tradeType, double entryPrice, double sl, double tp, double spread, double lotSize, string conditions)
{
// Open file in append mode. FILE_COMMON saves to the shared Terminal folder if preferred.
int fileHandle = FileOpen(LogFileName, FILE_WRITE | FILE_CSV | FILE_READ | FILE_ANSI, ",");
if(fileHandle != INVALID_HANDLE)
{
// If the file is empty, write the header row first
if(FileSize(fileHandle) == 0)
{
FileWrite(fileHandle, "Time", "Symbol", "Type", "LotSize", "EntryPrice", "SL", "TP", "SpreadPips", "Conditions");
}
// Move the pointer to the end of the file so we don't overwrite previous logs
FileSeek(fileHandle, 0, SEEK_END);
// Write the trade data
FileWrite(fileHandle, TimeToString(TimeCurrent()), _Symbol, tradeType, lotSize, entryPrice, sl, tp, NormalizeDouble(spread, 1), conditions);
FileClose(fileHandle);
}
else
{
Print("Failed to open CSV for logging. Error: ", GetLastError());
}
}
//+------------------------------------------------------------------+
//| 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
The LogTradeToCSV Function: This dedicated function utilizes FileOpen with the FILE_CSV and FILE_WRITE | FILE_READ flags. It automatically injects column headers (Time, Symbol, Type...) the very first time the file is created.
Pointer Navigation (FileSeek): By executing FileSeek(fileHandle, 0, SEEK_END), the EA guarantees that each new order appends cleanly to the bottom row without overwriting your historical series data.
Execution Validation (if(trade.Buy(...))): The logging function only fires if the IC Markets server formally accepts and processes the trade request. If an order is rejected due to margin requirements or network latency, nothing is logged.
File Directory Location: You will find your raw log data by opening MT5 and navigating to File > Open Data Folder, then entering the MQL5\Files directory.
The LogTradeToCSV Function: This dedicated function utilizes FileOpen with the FILE_CSV and FILE_WRITE | FILE_READ flags. It automatically injects column headers (Time, Symbol, Type...) the very first time the file is created.
Pointer Navigation (FileSeek): By executing FileSeek(fileHandle, 0, SEEK_END), the EA guarantees that each new order appends cleanly to the bottom row without overwriting your historical series data.
Execution Validation (if(trade.Buy(...))): The logging function only fires if the IC Markets server formally accepts and processes the trade request. If an order is rejected due to margin requirements or network latency, nothing is logged.
File Directory Location: You will find your raw log data by opening MT5 and navigating to File > Open Data Folder, then entering the MQL5\Files directory.
Re: USDCHF session playbook: thinner, but cleaner at times
To restrict daily executions robustly, the EA should interrogate the terminal's actual trading history using HistorySelect() rather than relying on an internal memory counter. An internal counter resets to zero if your MT5 terminal restarts, your VPS reboots, or you change the chart timeframe, which could accidentally bypass your limit. By reading the actual history deals, the EA always knows exactly how many entries were executed that day.
Re: USDCHF session playbook: thinner, but cleaner at times
Here is the updated script. I have extracted the Magic Number into an input variable so the history-checking function can dynamically reference it to only count its own trades.
Code: Select all
//+------------------------------------------------------------------+
//| USDCHF_London.mq5 |
//| Strict PA Scalping EA (Confluence, Pins, Friday, Max/Day) |
//+------------------------------------------------------------------+
#property copyright "Bc. Pavel Tuček"
#property version "1.70"
#include <Trade\Trade.mqh>
CTrade trade;
//--- Inputs
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 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 ExecutionFilters = "--- Execution Safeguards & Filters ---";
input int MaxTradesPerDay = 3; // Maximum number of entries per day
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
input ulong EA_Magic = 777130; // Magic Number for trade identification
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 LoggingSettings = "--- CSV Journal Logging ---";
input string LogFileName = "USDCHF_Series_Log.csv"; // Saved in MQL5\Files\
//--- 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(EA_Magic);
ulong deviationPoints = (ulong)(MaxSlippagePips * pipsMultiplier);
trade.SetDeviationInPoints(deviationPoints);
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
datetime currentBarTime = iTime(_Symbol, PERIOD_M15, 0);
if(currentBarTime == lastBarTime) return;
MqlDateTime dt;
TimeToStruct(TimeCurrent(), dt);
if(StopFridayTrading && dt.day_of_week == 5 && dt.hour >= FridayStopHour) return;
if(dt.hour < StartHour || dt.hour >= EndHour) return;
// Block execution if the daily trade limit is reached
if(GetTradesToday() >= MaxTradesPerDay) return;
if(PositionsTotal() > 0) return;
double resistanceD1 = GetHighestHigh(PERIOD_D1, LookbackD1);
double supportD1 = GetLowestLow(PERIOD_D1, LookbackD1);
double resistanceH4 = GetHighestHigh(PERIOD_H4, LookbackH4);
double supportH4 = GetLowestLow(PERIOD_H4, LookbackH4);
double confluenceTol = ConfluencePips * pipsMultiplier * point;
bool buyConfluence = MathAbs(supportH4 - supportD1) <= confluenceTol;
bool sellConfluence = MathAbs(resistanceH4 - resistanceD1) <= confluenceTol;
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);
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;
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.");
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));
if(trade.Buy(lotSize, _Symbol, 0, sl, tp, "Pin Bar Buy"))
{
LogTradeToCSV("BUY", currentAsk, sl, tp, liveSpreadPips, lotSize, "Bullish Pin + D1/H4 Confluence");
}
lastBarTime = currentBarTime;
}
// Sell Setup
if(sellConfluence && currentHigh >= resistanceH4 - execTolerance && isBearishPinBar)
{
if(liveSpreadPips > MaxSpreadPips)
{
Print("Sell trade canceled: Live spread is ", NormalizeDouble(liveSpreadPips, 1), " pips.");
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));
if(trade.Sell(lotSize, _Symbol, 0, sl, tp, "Pin Bar Sell"))
{
LogTradeToCSV("SELL", currentBid, sl, tp, liveSpreadPips, lotSize, "Bearish Pin + D1/H4 Confluence");
}
lastBarTime = currentBarTime;
}
}
//+------------------------------------------------------------------+
//| Calculate Total Executed Deals Today |
//+------------------------------------------------------------------+
int GetTradesToday()
{
int tradesToday = 0;
// Map the precise start of the current server day (midnight)
MqlDateTime dt;
TimeToStruct(TimeCurrent(), dt);
dt.hour = 0; dt.min = 0; dt.sec = 0;
datetime startOfDay = StructToTime(dt);
// Pull the transaction history for today
HistorySelect(startOfDay, TimeCurrent());
int totalDeals = HistoryDealsTotal();
for(int i = 0; i < totalDeals; i++)
{
ulong ticket = HistoryDealGetTicket(i);
if(ticket > 0)
{
// Verify it is a market ENTRY belonging to this specific EA and Symbol
if(HistoryDealGetInteger(ticket, DEAL_MAGIC) == EA_Magic &&
HistoryDealGetString(ticket, DEAL_SYMBOL) == _Symbol &&
HistoryDealGetInteger(ticket, DEAL_ENTRY) == DEAL_ENTRY_IN)
{
tradesToday++;
}
}
}
return tradesToday;
}
//+------------------------------------------------------------------+
//| Log Executed Trade to CSV File |
//+------------------------------------------------------------------+
void LogTradeToCSV(string tradeType, double entryPrice, double sl, double tp, double spread, double lotSize, string conditions)
{
int fileHandle = FileOpen(LogFileName, FILE_WRITE | FILE_CSV | FILE_READ | FILE_ANSI, ",");
if(fileHandle != INVALID_HANDLE)
{
if(FileSize(fileHandle) == 0)
{
FileWrite(fileHandle, "Time", "Symbol", "Type", "LotSize", "EntryPrice", "SL", "TP", "SpreadPips", "Conditions");
}
FileSeek(fileHandle, 0, SEEK_END);
FileWrite(fileHandle, TimeToString(TimeCurrent()), _Symbol, tradeType, lotSize, entryPrice, sl, tp, NormalizeDouble(spread, 1), conditions);
FileClose(fileHandle);
}
}
//+------------------------------------------------------------------+
//| 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:
GetTradesToday() Function: It creates a timestamp precisely at 00:00:00 broker server time using StructToTime(), pulls all activity via HistorySelect(), and iterates through the history pool.
Deal Filtering: The DEAL_ENTRY_IN check is crucial. An MT5 "Deal" represents an actual fill. Entering a trade creates one deal, and hitting TP/SL creates another. Filtering exclusively for DEAL_ENTRY_IN guarantees the EA only counts market entries, avoiding double-counting the closures.
Persistent Enforcement: Because it polls the IC Markets server history directly instead of using a local variable, you can crash the terminal, change your M15 chart to H1, or restart your VPS, and the EA will still know exactly how many trades it executed that day.
GetTradesToday() Function: It creates a timestamp precisely at 00:00:00 broker server time using StructToTime(), pulls all activity via HistorySelect(), and iterates through the history pool.
Deal Filtering: The DEAL_ENTRY_IN check is crucial. An MT5 "Deal" represents an actual fill. Entering a trade creates one deal, and hitting TP/SL creates another. Filtering exclusively for DEAL_ENTRY_IN guarantees the EA only counts market entries, avoiding double-counting the closures.
Persistent Enforcement: Because it polls the IC Markets server history directly instead of using a local variable, you can crash the terminal, change your M15 chart to H1, or restart your VPS, and the EA will still know exactly how many trades it executed that day.
Re: USDCHF session playbook: thinner, but cleaner at times
To build a robust consecutive loss circuit breaker, the EA must iterate through the terminal's daily history in reverse. By scanning backwards from the most recently closed deal (DEAL_ENTRY_OUT), the logic can count sequential negative profits. If it encounters a winning trade, it breaks the loop; if it counts two consecutive losses, it locks the EA for the remainder of the server day.
Re: USDCHF session playbook: thinner, but cleaner at times
Here is the updated script integrating the circuit breaker directly into the execution flow:
Code: Select all
//+------------------------------------------------------------------+
//| USDCHF_London.mq5 |
//| Strict PA Scalping EA (Confluence, Pins, Friday, Circuit Break) |
//+------------------------------------------------------------------+
#property copyright "Bc. Pavel Tuček"
#property version "1.80"
#include <Trade\Trade.mqh>
CTrade trade;
//--- Inputs
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 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 ExecutionFilters = "--- Execution Safeguards & Filters ---";
input int MaxTradesPerDay = 3; // Maximum number of entries per day
input int MaxConsecutiveLosses = 2; // Circuit breaker: halt after X consecutive losses today
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
input ulong EA_Magic = 777130; // Magic Number for trade identification
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 LoggingSettings = "--- CSV Journal Logging ---";
input string LogFileName = "USDCHF_Series_Log.csv"; // Saved in MQL5\Files\
//--- 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(EA_Magic);
ulong deviationPoints = (ulong)(MaxSlippagePips * pipsMultiplier);
trade.SetDeviationInPoints(deviationPoints);
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
datetime currentBarTime = iTime(_Symbol, PERIOD_M15, 0);
if(currentBarTime == lastBarTime) return;
MqlDateTime dt;
TimeToStruct(TimeCurrent(), dt);
if(StopFridayTrading && dt.day_of_week == 5 && dt.hour >= FridayStopHour) return;
if(dt.hour < StartHour || dt.hour >= EndHour) return;
// Block execution if daily trade limit or consecutive loss limit is reached
if(GetTradesToday() >= MaxTradesPerDay) return;
if(IsCircuitBreakerActive()) return;
if(PositionsTotal() > 0) return;
double resistanceD1 = GetHighestHigh(PERIOD_D1, LookbackD1);
double supportD1 = GetLowestLow(PERIOD_D1, LookbackD1);
double resistanceH4 = GetHighestHigh(PERIOD_H4, LookbackH4);
double supportH4 = GetLowestLow(PERIOD_H4, LookbackH4);
double confluenceTol = ConfluencePips * pipsMultiplier * point;
bool buyConfluence = MathAbs(supportH4 - supportD1) <= confluenceTol;
bool sellConfluence = MathAbs(resistanceH4 - resistanceD1) <= confluenceTol;
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);
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;
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.");
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));
if(trade.Buy(lotSize, _Symbol, 0, sl, tp, "Pin Bar Buy"))
{
LogTradeToCSV("BUY", currentAsk, sl, tp, liveSpreadPips, lotSize, "Bullish Pin + D1/H4 Confluence");
}
lastBarTime = currentBarTime;
}
// Sell Setup
if(sellConfluence && currentHigh >= resistanceH4 - execTolerance && isBearishPinBar)
{
if(liveSpreadPips > MaxSpreadPips)
{
Print("Sell trade canceled: Live spread is ", NormalizeDouble(liveSpreadPips, 1), " pips.");
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));
if(trade.Sell(lotSize, _Symbol, 0, sl, tp, "Pin Bar Sell"))
{
LogTradeToCSV("SELL", currentBid, sl, tp, liveSpreadPips, lotSize, "Bearish Pin + D1/H4 Confluence");
}
lastBarTime = currentBarTime;
}
}
//+------------------------------------------------------------------+
//| Calculate Consecutive Losses Today (Circuit Breaker) |
//+------------------------------------------------------------------+
bool IsCircuitBreakerActive()
{
if(MaxConsecutiveLosses <= 0) return false;
MqlDateTime dt;
TimeToStruct(TimeCurrent(), dt);
dt.hour = 0; dt.min = 0; dt.sec = 0;
datetime startOfDay = StructToTime(dt);
HistorySelect(startOfDay, TimeCurrent());
int totalDeals = HistoryDealsTotal();
int consecutiveLosses = 0;
// Loop backwards through today's deals to check the most recent closures first
for(int i = totalDeals - 1; i >= 0; i--)
{
ulong ticket = HistoryDealGetTicket(i);
if(ticket > 0)
{
// Filter for closed positions matching this EA and symbol
if(HistoryDealGetInteger(ticket, DEAL_MAGIC) == EA_Magic &&
HistoryDealGetString(ticket, DEAL_SYMBOL) == _Symbol &&
HistoryDealGetInteger(ticket, DEAL_ENTRY) == DEAL_ENTRY_OUT)
{
double profit = HistoryDealGetDouble(ticket, DEAL_PROFIT);
if(profit < 0)
{
consecutiveLosses++;
if(consecutiveLosses >= MaxConsecutiveLosses)
{
Print("Circuit breaker triggered: ", MaxConsecutiveLosses, " consecutive losses reached.");
return true;
}
}
else if(profit > 0)
{
// A winning trade breaks the consecutive losing streak
break;
}
}
}
}
return false;
}
//+------------------------------------------------------------------+
//| Calculate Total Executed Deals Today |
//+------------------------------------------------------------------+
int GetTradesToday()
{
int tradesToday = 0;
MqlDateTime dt;
TimeToStruct(TimeCurrent(), dt);
dt.hour = 0; dt.min = 0; dt.sec = 0;
datetime startOfDay = StructToTime(dt);
HistorySelect(startOfDay, TimeCurrent());
int totalDeals = HistoryDealsTotal();
for(int i = 0; i < totalDeals; i++)
{
ulong ticket = HistoryDealGetTicket(i);
if(ticket > 0)
{
if(HistoryDealGetInteger(ticket, DEAL_MAGIC) == EA_Magic &&
HistoryDealGetString(ticket, DEAL_SYMBOL) == _Symbol &&
HistoryDealGetInteger(ticket, DEAL_ENTRY) == DEAL_ENTRY_IN)
{
tradesToday++;
}
}
}
return tradesToday;
}
//+------------------------------------------------------------------+
//| Log Executed Trade to CSV File |
//+------------------------------------------------------------------+
void LogTradeToCSV(string tradeType, double entryPrice, double sl, double tp, double spread, double lotSize, string conditions)
{
int fileHandle = FileOpen(LogFileName, FILE_WRITE | FILE_CSV | FILE_READ | FILE_ANSI, ",");
if(fileHandle != INVALID_HANDLE)
{
if(FileSize(fileHandle) == 0)
{
FileWrite(fileHandle, "Time", "Symbol", "Type", "LotSize", "EntryPrice", "SL", "TP", "SpreadPips", "Conditions");
}
FileSeek(fileHandle, 0, SEEK_END);
FileWrite(fileHandle, TimeToString(TimeCurrent()), _Symbol, tradeType, lotSize, entryPrice, sl, tp, NormalizeDouble(spread, 1), conditions);
FileClose(fileHandle);
}
}
//+------------------------------------------------------------------+
//| 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:
Reverse Iteration (for(int i = totalDeals - 1; i >= 0; i--)): To accurately assess the current streak without reading yesterday's performance, the loop reads today's executed deals backwards, processing the most recently closed position first.
Deal Out Filter (DEAL_ENTRY_OUT): While GetTradesToday() filters for DEAL_ENTRY_IN to count entries, the circuit breaker filters strictly for DEAL_ENTRY_OUT. This isolates the exact moment your Stop Loss or Take Profit executed and realized the final P&L.
Profit Evaluation (profit < 0): By reading HistoryDealGetDouble(ticket, DEAL_PROFIT), the EA checks if the exit generated a net loss. If it did, it increments the consecutiveLosses counter. If it hits a winning deal (profit > 0), it fires the break command, killing the loop entirely because the streak is broken.
Console Logging (Print): If the limit triggers, the EA logs a clear timestamped message to the MT5 Journal tab, ensuring you understand why it refused to execute any further setups that day.
Reverse Iteration (for(int i = totalDeals - 1; i >= 0; i--)): To accurately assess the current streak without reading yesterday's performance, the loop reads today's executed deals backwards, processing the most recently closed position first.
Deal Out Filter (DEAL_ENTRY_OUT): While GetTradesToday() filters for DEAL_ENTRY_IN to count entries, the circuit breaker filters strictly for DEAL_ENTRY_OUT. This isolates the exact moment your Stop Loss or Take Profit executed and realized the final P&L.
Profit Evaluation (profit < 0): By reading HistoryDealGetDouble(ticket, DEAL_PROFIT), the EA checks if the exit generated a net loss. If it did, it increments the consecutiveLosses counter. If it hits a winning deal (profit > 0), it fires the break command, killing the loop entirely because the streak is broken.
Console Logging (Print): If the limit triggers, the EA logs a clear timestamped message to the MT5 Journal tab, ensuring you understand why it refused to execute any further setups that day.
-
FXS Prop Desk
- Posts: 1693
- Joined: Wed Oct 07, 2026 9:52 am
Re: USDCHF session playbook: thinner, but cleaner at times
Mapping the UK window to broker server time is the detail that trips most people, so it helps to have it written down here. The risk 3, reward 1 structure deserves a caution, though. With a 9-pip stop and a 3-pip target, the break-even win rate is 75% before costs, and after a typical raw spread and commission on USDCHF it moves closer to 80%. That gives the setup a thin margin for error. Anyone testing it should log the spread at entry on each trade, since a few wider-spread entries at the session edge can quietly decide whether the whole playbook is positive.
FXS Official Team | The Idea Lab & Strategy