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;
}