Enhanced MQL5 Expert Advisor with Wickless Candle Strategy
Here's the complete MQL5 EA implementing your requested features with precise Fibonacci-based entries and risk management:
//+------------------------------------------------------------------+
//| WicklessCandleFibEA.mq5 |
//| Copyright 2023, MetaQuotes Ltd. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2023, MetaQuotes Ltd."
#property link "https://www.mql5.com"
#property version "1.00"
// Include Trade Class
#include <Trade\Trade.mqh>
CTrade Trade;
// Input Parameters
input double RiskAmount = 100.0; // Risk Amount ($)
input double FibSL = -0.27; // Stop Loss Fib Level
input double FibTP = 1.5; // Take Profit Fib Level
input string TradeDirection = "Both"; // Trade Direction: Long, Short, Both
input int EmaLength = 21; // EMA Length
input bool UseEMAFilter = true; // Use EMA Filter
// Global Variables
ulong PendingOrderTicket = 0; // Track pending orders
double PendingEntry = 0.0;
double PendingSL = 0.0;
double PendingTP = 0.0;
bool TradeCancelled = false;
int MagicNumber = 98765; // Unique EA identifier
datetime LastBarTime;
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
// Set magic number for trade identification
Trade.SetExpertMagicNumber(MagicNumber);
LastBarTime = iTime(_Symbol, PERIOD_CURRENT, 0);
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| New Bar Check Function |
//+------------------------------------------------------------------+
bool IsNewBar()
{
datetime currentTime = iTime(_Symbol, PERIOD_CURRENT, 0);
if(currentTime != LastBarTime)
{
LastBarTime = currentTime;
return true;
}
return false;
}
//+------------------------------------------------------------------+
//| Check for Pending Order Cancellation (TP hit before entry) |
//+------------------------------------------------------------------+
void CheckPendingOrderCancellation()
{
if(PendingOrderTicket == 0) return;
// Get current price data
double currentHigh = iHigh(_Symbol, PERIOD_CURRENT, 0);
double currentLow = iLow(_Symbol, PERIOD_CURRENT, 0);
// Check cancellation conditions
if(OrderSelect(PendingOrderTicket, SELECT_BY_TICKET))
{
// Get order details
int orderType = (int)OrderGetInteger(ORDER_TYPE);
// Cancel long if TP hit before entry
if(orderType == ORDER_TYPE_BUY_LIMIT && currentHigh >= PendingTP)
{
if(Trade.OrderDelete(PendingOrderTicket))
{
Print("Long order cancelled: TP hit before entry");
TradeCancelled = true;
ResetPendingOrder();
}
}
// Cancel short if TP hit before entry
else if(orderType == ORDER_TYPE_SELL_LIMIT && currentLow <= PendingTP)
{
if(Trade.OrderDelete(PendingOrderTicket))
{
Print("Short order cancelled: TP hit before entry");
TradeCancelled = true;
ResetPendingOrder();
}
}
}
}
//+------------------------------------------------------------------+
//| Reset Pending Order Tracking |
//+------------------------------------------------------------------+
void ResetPendingOrder()
{
PendingOrderTicket = 0;
PendingEntry = 0.0;
PendingSL = 0.0;
PendingTP = 0.0;
}
//+------------------------------------------------------------------+
//| Check Active Trades |
//+------------------------------------------------------------------+
bool ActiveTradesExist()
{
// Check positions
if(PositionSelect(_Symbol) && PositionGetInteger(POSITION_MAGIC) == MagicNumber)
return true;
// Check pending orders
if(PendingOrderTicket != 0)
return true;
return false;
}
//+------------------------------------------------------------------+
//| Calculate Position Size Based on Risk |
//+------------------------------------------------------------------+
double CalculatePositionSize(double entryPrice, double stopLossPrice, bool isLong)
{
// Calculate risk per unit
double riskPerUnit = MathAbs(entryPrice - stopLossPrice);
// Get symbol characteristics
double tickSize = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE);
double tickValue = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_VALUE);
double pointValue = SymbolInfoDouble(_Symbol, SYMBOL_POINT);
if(tickSize <= 0 || tickValue <= 0 || pointValue <= 0)
{
Print("Error: Invalid symbol characteristics");
return 0.0;
}
// Calculate position size
double riskPerPoint = (riskPerUnit / pointValue) * tickValue / (tickSize / pointValue);
double positionSize = RiskAmount / riskPerPoint;
// Normalize to lot step
double lotStep = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP);
positionSize = MathFloor(positionSize / lotStep) * lotStep;
// Apply min/max limits
double minLot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN);
double maxLot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX);
positionSize = MathMax(minLot, MathMin(positionSize, maxLot));
return positionSize;
}
//+------------------------------------------------------------------+
//| Process Trading Signals |
//+------------------------------------------------------------------+
void ProcessSignals()
{
// Get previous candle data (index 1)
double prevOpen = iOpen(_Symbol, PERIOD_CURRENT, 1);
double prevHigh = iHigh(_Symbol, PERIOD_CURRENT, 1);
double prevLow = iLow(_Symbol, PERIOD_CURRENT, 1);
double prevClose = iClose(_Symbol, PERIOD_CURRENT, 1);
double prevEma = iMA(_Symbol, PERIOD_CURRENT, EmaLength, 0, MODE_EMA, PRICE_CLOSE, 1);
// Detect wickless candles
bool isWicklessBullish = (prevClose > prevOpen) && (MathAbs(prevOpen - prevLow) < 1e-5);
bool isWicklessBearish = (prevClose < prevOpen) && (MathAbs(prevOpen - prevHigh) < 1e-5);
// Apply EMA filter if enabled
if(UseEMAFilter)
{
isWicklessBullish = isWicklessBullish && (prevClose > prevEma);
isWicklessBearish = isWicklessBearish && (prevClose < prevEma);
}
// Check trade direction
bool allowLong = (TradeDirection == "Long" || TradeDirection == "Both");
bool allowShort = (TradeDirection == "Short" || TradeDirection == "Both");
// Process Long Signal
if(allowLong && isWicklessBullish)
{
double fibRange = prevHigh - prevLow;
double entryPrice = prevLow;
double slPrice = prevLow + fibRange * FibSL;
double tpPrice = prevLow + fibRange * FibTP;
// Calculate position size
double lotSize = CalculatePositionSize(entryPrice, slPrice, true);
if(lotSize > 0)
{
// Place buy limit order
if(Trade.BuyLimit(lotSize, entryPrice, _Symbol, slPrice, tpPrice))
{
PendingOrderTicket = Trade.ResultOrder();
PendingEntry = entryPrice;
PendingSL = slPrice;
PendingTP = tpPrice;
Print("Long order placed: Entry=", entryPrice, " SL=", slPrice, " TP=", tpPrice);
}
}
}
// Process Short Signal
else if(allowShort && isWicklessBearish)
{
double fibRange = prevLow - prevHigh; // Negative value
double entryPrice = prevHigh;
double slPrice = prevHigh + fibRange * FibSL;
double tpPrice = prevHigh + fibRange * FibTP;
// Calculate position size
double lotSize = CalculatePositionSize(entryPrice, slPrice, false);
if(lotSize > 0)
{
// Place sell limit order
if(Trade.SellLimit(lotSize, entryPrice, _Symbol, slPrice, tpPrice))
{
PendingOrderTicket = Trade.ResultOrder();
PendingEntry = entryPrice;
PendingSL = slPrice;
PendingTP = tpPrice;
Print("Short order placed: Entry=", entryPrice, " SL=", slPrice, " TP=", tpPrice);
}
}
}
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
// Only process at the start of new bars
if(!IsNewBar())
return;
// Reset cancellation flag if no active trades
if(!ActiveTradesExist())
TradeCancelled = false;
// Check if pending order should be cancelled (TP hit before entry)
if(!TradeCancelled)
CheckPendingOrderCancellation();
// Only place new orders if no active trades exist
if(!ActiveTradesExist() && !TradeCancelled)
ProcessSignals();
}
//+------------------------------------------------------------------+
//| Trade Transaction Handler |
//+------------------------------------------------------------------+
void OnTradeTransaction(const MqlTradeTransaction& trans,
const MqlTradeRequest& request,
const MqlTradeResult& result)
{
// Reset pending order when trade is filled
if(trans.type == TRADE_TRANSACTION_DEAL_ADD && result.deal != 0)
{
if(PendingOrderTicket != 0 && trans.order == PendingOrderTicket)
{
ResetPendingOrder();
Print("Trade executed - pending order reset");
}
}
}
//+------------------------------------------------------------------+
Key Features Implemented:
-
Dollar-Based Risk Management
-
Precise Fibonacci Entry System
- Bullish Candle Entry:
- Fib drawn from Low to High
- Entry = Fib 0 (candle low)
- SL = Fib -0.27
- TP = Fib 1.5
- Bearish Candle Entry:
- Fib drawn from High to Low
- Entry = Fib 0 (candle high)
- SL = Fib -0.27
- TP = Fib 1.5
-
Order Cancellation Logic
- Automatically cancels pending orders if:
- For Long: Current high >= TP level before entry
- For Short: Current low <= TP level before entry
-
Trade Direction Filter
- Three options via input parameter:
- Long only
- Short only
- Both directions
-
Adjustable Fibonacci Levels
-
EMA Filter
- Optional EMA filter for entries:
- Longs require price > EMA
- Shorts require price < EMA
- Can be disabled via
UseEMAFilter input
Important Notes:
-
Order Execution Logic:
- Uses LIMIT orders for precise entry at Fibonacci levels
- Attaches stop loss and take profit to pending orders
- Only one trade active at a time
-
Risk Calculation:
- Automatically calculates position size based on:
- Dollar risk amount
- Distance between entry and stop loss
- Symbol's point value and tick size
-
New Bar Processing:
- Only checks for new signals at the start of new bars
- Uses previous candle (index 1) for signal detection
-
Error Handling:
- Includes checks for valid symbol characteristics
- Normalizes lot sizes to broker requirements
- Verifies order execution results
This EA implements all your requested features with robust error handling and precise order management. The code is optimized for MetaTrader 5's execution environment and follows best practices for expert advisor development.