Okay, I've refined the MT5 Expert Advisor code based on your detailed requirements.
The good news is that most of your requests were already aligned with the previous Pine Script logic and my initial MT5 conversion, but I've ensured every point is explicitly addressed and the code structure is robust for MT5's execution model.
Here's a summary of how each point is handled:
- Risk in Dollars: Implemented via
input double InpRiskAmount = 100.0;. The volume calculation uses this fixed dollar amount directly.
- Entry, Stop Loss, Take Profit Criteria (Fibonacci):
- Bullish Candle (Long): Fibonacci is drawn from
Low (0) to High (1).
- Entry:
Low (Fib 0).
- Stop Loss:
Low + FibRange * FibSL (Fib -0.27).
- Take Profit:
Low + FibRange * FibTP (Fib 1.5).
- Bearish Candle (Short): Fibonacci is drawn from
High (0) to Low (1).
- Entry:
High (Fib 0).
- Stop Loss:
High + FibRange * FibSL (Fib -0.27).
- Take Profit:
High + FibRange * FibTP (Fib 1.5).
This logic exactly matches the Pine Script and is correctly implemented.
- Trade will either close at Stop Loss or at TP: This is the default behavior of setting
request.sl and request.tp when placing an order in MT5. No other exit conditions are specified, ensuring closure only at these levels.
- If market touches TP without hitting entry cancel that trade: The
CheckAndCancelPending() function handles this. It's called at the start of each new bar to check if the current market price (high for long, low for short) reached the pending TP level before the limit entry was filled. If so, it cancels the pending order.
- Option of Choosing LONG only, SHORT only, or Both direction trading: This is controlled by the
input string InpTradeDirection with options "Long", "Short", and "Both".
- Option to change Fib Values of Stop Loss and Take Profit: This is provided by
input double InpFibSL and input double InpFibTP.
Key Improvements in the MT5 Code:
- Robust
OnTick Logic: The OnTick function now explicitly manages the tradeCancelled flag and the state of pending orders (pendingOrderTicket) to precisely mimic the Pine Script's execution flow, ensuring trades are only placed when no position is open, no pending order is active, and no prior pending order was cancelled on the current bar.
- Clearer Volume Calculation Comments: Added more detailed comments to
CalculateVolume regarding the conversion from dollar risk to lots, emphasizing the need to consider symbol-specific parameters (tick size, tick value) for real-world trading.
- Wickless Detection Tolerance: Continues to use a small tolerance (
tol) for float comparisons to accurately detect wickless candles.
Here is the full MQL5 code:
//+------------------------------------------------------------------+
//| WicklessCandleFib.mq5 |
//| Converted from TradingView Pine‑Script “Wickless Candle Fib Strategy v2” |
//| |
//| This EA places pending limit orders based on a wickless candle and |
//| Fibonacci-derived levels and cancels orders if the take-profit |
//| level is touched before order entry. It uses an EMA filter and a |
//| fixed-risk amount per trade. |
//+------------------------------------------------------------------+
#include <Trade\Trade.mqh>
CTrade trade;
#define MAGIC_NUMBER 123456
//===== Input parameters
input double InpRiskAmount = 100.0; // Risk Amount ($) per trade (fixed dollar risk)
input double InpFibSL = -0.27; // Fibonacci Stop Loss Level
input double InpFibTP = 1.5; // Fibonacci Take Profit Level
input string InpTradeDirection = "Both"; // Allowed trade directions: "Long", "Short", "Both"
input int InpEmaLength = 21; // EMA period length
input bool InpUseEMAFilter = true; // Enable/disable EMA filter for entries
//===== Global variables for pending order tracking and new-bar detection
ulong pendingOrderTicket = 0; // Ticket of the pending order (if any)
double pendingEntry = 0.0; // Price at which the pending order is created
double pendingSL = 0.0; // Stop loss price for the pending order
double pendingTP = 0.0; // Take profit price for the pending order
bool tradeCancelled = false; // Flag to indicate if pending order was cancelled on current bar
// For detecting new bars (the logic uses data from the previous bar)
datetime lastBarTime = 0;
//----- Tolerance for float comparisons (for wickless candle detection)
double tol = 1e-6; // A small value for floating point comparisons
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
// Initialize lastBarTime to the currently forming bar’s time
lastBarTime = iTime(_Symbol, _Period, 0);
Print("Wickless Candle Fib EA initialized.");
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Check for New Bar (comparing the current bar’s start time) |
//+------------------------------------------------------------------+
bool IsNewBar()
{
datetime currentBarTime = iTime(_Symbol, _Period, 0);
if(currentBarTime != lastBarTime)
{
lastBarTime = currentBarTime;
return(true);
}
return(false);
}
//+------------------------------------------------------------------+
//| Delete Pending Order if conditions are met (cancellation logic) |
//+------------------------------------------------------------------+
void CheckAndCancelPending()
{
// Only proceed if we are currently tracking a pending order
if(pendingOrderTicket == 0)
return;
// Attempt to select the pending order by its ticket to get its type and levels
if(OrderSelect(pendingOrderTicket, SELECT_BY_TICKET))
{
int orderType = (int)OrderGetInteger(ORDER_TYPE);
// Get current (forming) bar’s high and low prices to check for TP touch
double currHigh = iHigh(_Symbol, _Period, 0);
double currLow = iLow(_Symbol, _Period, 0);
// Cancellation logic: if price reached pending TP before entry
if(orderType == ORDER_TYPE_BUY_LIMIT) // For a pending Long (BUY_LIMIT)
{
// If current high reached or exceeded the pending TP price
if(currHigh >= pendingTP)
{
if(trade.OrderDelete(pendingOrderTicket))
{
Print("Cancelled pending LONG order (Ticket: ", pendingOrderTicket, ") because current high (",
DoubleToString(currHigh, _Digits), ") >= pendingTP (", DoubleToString(pendingTP, _Digits), ").");
tradeCancelled = true; // Mark that a trade was cancelled on this bar
// Clear tracking variables for this cancelled order
pendingOrderTicket = 0;
pendingEntry = pendingSL = pendingTP = 0.0;
}
else
{
Print("Failed to cancel pending LONG order (Ticket: ", pendingOrderTicket, "). Error: ", GetLastError());
}
}
}
else if(orderType == ORDER_TYPE_SELL_LIMIT) // For a pending Short (SELL_LIMIT)
{
// If current low reached or went below the pending TP price
if(currLow <= pendingTP)
{
if(trade.OrderDelete(pendingOrderTicket))
{
Print("Cancelled pending SHORT order (Ticket: ", pendingOrderTicket, ") because current low (",
DoubleToString(currLow, _Digits), ") <= pendingTP (", DoubleToString(pendingTP, _Digits), ").");
tradeCancelled = true; // Mark that a trade was cancelled on this bar
// Clear tracking variables for this cancelled order
pendingOrderTicket = 0;
pendingEntry = pendingSL = pendingTP = 0.0;
}
else
{
Print("Failed to cancel pending SHORT order (Ticket: ", pendingOrderTicket, "). Error: ", GetLastError());
}
}
}
}
else
{
// If OrderSelect failed, it means the order we were tracking is no longer there (e.g., it got filled)
// So, reset our tracking variables.
pendingOrderTicket = 0;
pendingEntry = pendingSL = pendingTP = 0.0;
}
}
//+------------------------------------------------------------------+
//| Calculate proper lot volume based on fixed dollar risk |
//+------------------------------------------------------------------+
double CalculateVolume(double riskPerUnit)
{
if (riskPerUnit <= 0)
{
Print("Error: Risk per unit is zero or negative. Cannot calculate volume.");
return 0.0;
}
// Get account currency information
string accountCurrency = AccountInfoString(ACCOUNT_CURRENCY);
// Get symbol contract size and tick value
double contractSize = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_CONTRACT_SIZE);
double tickValue = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_VALUE);
double tickSize = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE);
// Determine if account currency is the base or quote currency for the symbol
// For simplicity, we assume that riskPerUnit is expressed in the quote currency
// If the symbol's quote currency matches the account currency, this is straightforward.
// If not, a conversion rate (e.g., via iRates) would be needed here.
// For now, assuming direct conversion or FX pair where quote is the account currency.
// Calculate initial volume based on risk amount
double volume = InpRiskAmount / riskPerUnit; // This is the 'units' or 'base currency' volume
// Convert to lots, considering contract size
if (contractSize > 0)
{
volume /= contractSize; // For FX, contract size is usually 100,000 for standard lot
}
// --- Adjust volume to market specifications ---
double minVol = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN);
double maxVol = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX);
double volStep = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP);
// Round down to the nearest step and ensure it's within min/max limits
volume = MathFloor(volume / volStep) * volStep;
volume = MathMax(minVol, volume);
volume = MathMin(maxVol, volume);
// If after rounding, volume is too small (e.g., less than minVol and was rounded to 0),
// or if any calculation resulted in an invalid number, return 0.
if (volume < minVol)
return 0.0;
return(volume);
}
//+------------------------------------------------------------------+
//| Place a pending order (Buy Limit or Sell Limit) |
//+------------------------------------------------------------------+
void PlacePendingOrder(bool isLong, double entryPrice, double slPrice, double tpPrice)
{
MqlTradeRequest request;
MqlTradeResult result;
ZeroMemory(request);
ZeroMemory(result);
// Calculate risk per unit for volume calculation
double riskPerUnit;
if (isLong)
{
riskPerUnit = entryPrice - slPrice;
}
else // Short
{
riskPerUnit = slPrice - entryPrice;
}
request.action = TRADE_ACTION_PENDING;
request.symbol = _Symbol;
request.volume = CalculateVolume(riskPerUnit); // Use calculated volume
request.price = entryPrice;
request.sl = slPrice;
request.tp = tpPrice;
request.deviation = 10; // Max allowed deviation from the specified price
request.magic = MAGIC_NUMBER;
request.type_filling= ORDER_FILLING_FOK; // Fill or Kill: Order must be filled completely or cancelled
if (request.volume <= 0)
{
Print("Calculated volume is zero or negative. Order not placed.");
return;
}
if(isLong)
{
request.type = ORDER_TYPE_BUY_LIMIT;
Print("Attempting to place pending BUY LIMIT order. Entry: ", DoubleToString(entryPrice, _Digits),
", SL: ", DoubleToString(slPrice, _Digits), ", TP: ", DoubleToString(tpPrice, _Digits),
", Volume: ", DoubleToString(request.volume, 2));
}
else
{
request.type = ORDER_TYPE_SELL_LIMIT;
Print("Attempting to place pending SELL LIMIT order. Entry: ", DoubleToString(entryPrice, _Digits),
", SL: ", DoubleToString(slPrice, _Digits), ", TP: ", DoubleToString(tpPrice, _Digits),
", Volume: ", DoubleToString(request.volume, 2));
}
if(!OrderSend(request, result))
{
Print("OrderSend failed. Error: ", GetLastError());
return;
}
if(result.retcode == TRADE_RETCODE_DONE)
{
// Store the ticket and levels for tracking on subsequent ticks/bars
pendingOrderTicket = result.order;
pendingEntry = entryPrice;
pendingSL = slPrice;
pendingTP = tpPrice;
Print("Pending order placed successfully. Ticket: ", pendingOrderTicket);
}
else
{
Print("OrderSend failed, retcode=", result.retcode, ". Deal: ", result.deal, ", Order: ", result.order,
", Comment: ", result.comment);
}
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
// Process only at the start of a new bar
if(!IsNewBar())
return;
// --- State Reset at start of new bar if flat ---
// If there are no open positions and no pending order tracked by this EA,
// reset the cancellation flag for the new bar.
if (PositionsTotal() == 0 && pendingOrderTicket == 0)
{
tradeCancelled = false;
}
// --- Cancellation Logic for Pending Orders ---
// Check if the TP level of a previously placed pending order was hit BEFORE its entry price.
// This function will update 'tradeCancelled' flag if a cancellation occurs.
CheckAndCancelPending();
// --- Main Trading Logic (Entry) ---
// Only attempt to place a new trade if:
// 1. There are no open positions
// 2. There is no pending order from a previous bar
// 3. No trade was cancelled on *this* bar (which means the conditions for the previous pending trade were invalidated)
if (PositionsTotal() == 0 && pendingOrderTicket == 0 && !tradeCancelled)
{
// Retrieve data from the previous completed bar (index 1) for signal generation
double open1 = iOpen(_Symbol, _Period, 1);
double high1 = iHigh(_Symbol, _Period, 1);
double low1 = iLow(_Symbol, _Period, 1);
double close1 = iClose(_Symbol, _Period, 1);
double ema1 = iMA(_Symbol, _Period, InpEmaLength, 0, MODE_EMA, PRICE_CLOSE, 1);
//--- Define signal conditions based on the previous bar
// Bullish wickless candle: close > open AND open == low (with tolerance)
bool isWicklessBullish = (close1 > open1) && (MathAbs(open1 - low1) < tol);
// Long EMA filter: close of previous bar is above EMA OR filter is disabled
bool longEMACondition = !InpUseEMAFilter || (close1 > ema1);
bool validLongSignal = isWicklessBullish && longEMACondition;
// Bearish wickless candle: close < open AND open == high (with tolerance)
bool isWicklessBearish = (close1 < open1) && (MathAbs(open1 - high1) < tol);
// Short EMA filter: close of previous bar is below EMA OR filter is disabled
bool shortEMACondition = !InpUseEMAFilter || (close1 < ema1);
bool validShortSignal = isWicklessBearish && shortEMACondition;
//--- Check trade direction settings
bool allowLong = (InpTradeDirection == "Long" || InpTradeDirection == "Both");
bool allowShort = (InpTradeDirection == "Short" || InpTradeDirection == "Both");
//--- LONG ENTRY LOGIC ---
if(allowLong && validLongSignal)
{
// Fib levels are drawn from Low (0) to High (1) of the signal candle
double fibRange = high1 - low1;
// 1. Entry (Fib 0): Low of the candle
double longEntryPrice = low1;
// 2. Stop Loss (Fib -0.27): below the low
double longStopLossPrice = low1 + fibRange * InpFibSL;
// 3. Take Profit (Fib 1.5): above the high
double longTakeProfitPrice = low1 + fibRange * InpFibTP;
// Ensure valid SL (SL must be below entry for long)
if (longStopLossPrice < longEntryPrice)
{
PlacePendingOrder(true, longEntryPrice, longStopLossPrice, longTakeProfitPrice);
}
else
{
Print("Invalid Long SL calculated. SL (", DoubleToString(longStopLossPrice, _Digits), ") is not below Entry (",
DoubleToString(longEntryPrice, _Digits), "). Order not placed.");
}
// Only one signal per bar
return;
}
//--- SHORT ENTRY LOGIC ---
if(allowShort && validShortSignal)
{
// Fib levels are drawn from High (0) to Low (1) of the signal candle
// fibRange will be a negative value (e.g., low - high = 10 - 12 = -2)
double fibRange = low1 - high1;
// 1. Entry (Fib 0): High of the candle
double shortEntryPrice = high1;
// 2. Stop Loss (Fib -0.27): above the high
// Since fibRange is negative and InpFibSL is negative, fibRange * InpFibSL will be positive,
// thus shortStopLossPrice = high + positive_value (SL above entry)
double shortStopLossPrice = high1 + fibRange * InpFibSL;
// 3. Take Profit (Fib 1.5): below the low
// Since fibRange is negative and InpFibTP is positive, fibRange * InpFibTP will be negative,
// thus shortTakeProfitPrice = high + negative_value (TP below entry)
double shortTakeProfitPrice = high1 + fibRange * InpFibTP;
// Ensure valid SL (SL must be above entry for short)
if (shortStopLossPrice > shortEntryPrice)
{
PlacePendingOrder(false, shortEntryPrice, shortStopLossPrice, shortTakeProfitPrice);
}
else
{
Print("Invalid Short SL calculated. SL (", DoubleToString(shortStopLossPrice, _Digits), ") is not above Entry (",
DoubleToString(shortEntryPrice, _Digits), "). Order not placed.");
}
// Only one signal per bar
return;
}
}
// ELSE (if a trade is open, or pending, or was just cancelled on this bar)
// Do nothing, wait for next bar/transaction or a new signal on a future bar.
}
//+------------------------------------------------------------------+
//| Optional: Handle trade transactions to reset pending order state |
//+------------------------------------------------------------------+
void OnTradeTransaction(const MqlTradeTransaction &trans, const MqlTradeRequest &request, const MqlTradeResult &result)
{
// This function is called on every trade-related event.
// We use it to detect when our pending order is no longer pending (e.g., filled or cancelled by broker).
// Check if the transaction is a deal being added (i.e., an order was filled)
if(trans.type == TRADE_TRANSACTION_DEAL_ADD)
{
// Check if the deal belongs to our EA's magic number
if(trans.magic == MAGIC_NUMBER)
{
// If we were tracking a pending order, and it's no longer 'pending',
// it means it was either filled or otherwise removed from pending state.
if(pendingOrderTicket != 0)
{
// Try to select the order. If it fails, the order might be gone.
if(!OrderSelect(pendingOrderTicket, SELECT_BY_TICKET))
{
// The pending order we were tracking is no longer found.
// This implies it was filled or cancelled. Reset our tracking variables.
pendingOrderTicket = 0;
pendingEntry = pendingSL = pendingTP = 0.0;
Print("Pending order (Ticket: ", trans.order, ") was processed (filled/cancelled by broker). Resetting tracking variables.");
}
}
}
}
// If a pending order is explicitly cancelled (e.g. manually, or by CheckAndCancelPending)
// and the transaction type is TRADE_TRANSACTION_ORDER_DELETE, we could also handle it here,
// but CheckAndCancelPending already clears the ticket directly.
}
//+------------------------------------------------------------------+