riskAmount = input.float(100, title="Risk Amount ($)", minval=1, tooltip="The fixed dollar amount you want to risk per trade.")
fibSL = input.float(-0.27, title="Fibonacci Stop Loss Level", tooltip="Fib level for Stop Loss.")
fibTP = input.float(1.5, title="Fibonacci Take Profit Level", tooltip="Fib level for Take Profit.")
tradeDirection = input.string("Both", title="Trade Direction", options=["Long", "Short", "Both"], tooltip="Choose to trade Long only, Short only, or both directions.")
// EMA Settings
emaLength = input.int(21, title="EMA Length", minval=1, tooltip="Length of the EMA filter.")
useEMAFilter = input.bool(true, title="Use EMA Filter", tooltip="Enable/disable EMA filter for entries.")
// =========================================================================
// 3) State Variables (For tracking pending orders)
// =========================================================================
var float pendingEntry = na
var float pendingSL = na
var float pendingTP = na
var bool tradeCancelled = false
// LONG SIGNAL: Bullish candle with no lower wick (open == low) AND price above EMA
isWicklessBullish = (close > open) and (open == low)
longEMACondition = not useEMAFilter or (close > ema21)
validLongSignal = isWicklessBullish and longEMACondition
// SHORT SIGNAL: Bearish candle with no upper wick (open == high) AND price below EMA
isWicklessBearish = (close < open) and (open == high)
shortEMACondition = not useEMAFilter or (close < ema21)
validShortSignal = isWicklessBearish and shortEMACondition
// =========================================================================
// 5) Cancellation Logic (Requirement: TP hit before Entry)
// =========================================================================
// Reset cancellation flag at the start of each bar calculation if we are flat
if strategy.position_size == 0
tradeCancelled := false
// Identify pending orders based on signals from the previous bar [1]
pendingLongOrder = (strategy.position_size == 0) and validLongSignal[1] and (tradeDirection == "Long" or tradeDirection == "Both")
pendingShortOrder = (strategy.position_size == 0) and validShortSignal[1] and (tradeDirection == "Short" or tradeDirection == "Both")
// --- Check for LONG cancellation ---
if (pendingLongOrder)
// If the current bar's high reached the pending TP level before entry
if (high >= pendingTP[1])
strategy.cancel("Long")
tradeCancelled := true
// --- Check for SHORT cancellation ---
if (pendingShortOrder)
// If the current bar's low reached the pending TP level before entry
if (low <= pendingTP[1])
strategy.cancel("Short")
tradeCancelled := true
// Only calculate and enter new trades if we are flat and no trade was cancelled on this bar
if (strategy.position_size == 0 and not tradeCancelled)
code
// Reset previous pending levels if a new signal hasn't formed yet
if not validLongSignal and not validShortSignal
pendingEntry := na
pendingSL := na
pendingTP := na
// --- LONG ENTRY LOGIC ---
if ((tradeDirection == "Long" or tradeDirection == "Both") and validLongSignal)
// Fib levels are drawn from Low (0) to High (1)
fibRange = high - low
// 1. Entry (Fib 0): Low of the candle
longEntryPrice = low
// 2. Stop Loss (Fib -0.27)
longStopLossPrice = low + fibRange * fibSL
// 3. Take Profit (Fib 1.5)
longTakeProfitPrice = low + fibRange * fibTP
// Store levels for plotting and cancellation checks on the next bar
pendingEntry := longEntryPrice
pendingSL := longStopLossPrice
pendingTP := longTakeProfitPrice
// 4. Calculate Position Size
riskPerUnit = longEntryPrice - longStopLossPrice
if (riskPerUnit > 0)
longPositionSize = riskAmount / riskPerUnit
// Place a LIMIT order at the calculated entry price
strategy.entry("Long", strategy.long, qty=longPositionSize, limit=longEntryPrice)
strategy.exit("Exit Long", from_entry="Long", stop=longStopLossPrice, limit=longTakeProfitPrice)
// --- SHORT ENTRY LOGIC ---
if ((tradeDirection == "Short" or tradeDirection == "Both") and validShortSignal)
// Fib levels are drawn from High (0) to Low (1)
fibRange = low - high // Note: low - high for short fib range
// 1. Entry (Fib 0): High of the candle
shortEntryPrice = high
// 2. Stop Loss (Fib -0.27)
shortStopLossPrice = high + fibRange * fibSL
// 3. Take Profit (Fib 1.5)
shortTakeProfitPrice = high + fibRange * fibTP
// Store levels for plotting and cancellation checks on the next bar
pendingEntry := shortEntryPrice
pendingSL := shortStopLossPrice
pendingTP := shortTakeProfitPrice
// 4. Calculate Position Size
riskPerUnit = shortStopLossPrice - shortEntryPrice
if (riskPerUnit > 0)
shortPositionSize = riskAmount / riskPerUnit
// Place a LIMIT order at the calculated entry price
strategy.entry("Short", strategy.short, qty=shortPositionSize, limit=shortEntryPrice)
strategy.exit("Exit Short", from_entry="Short", stop=shortStopLossPrice, limit=shortTakeProfitPrice)
// =========================================================================
// 7) Resetting State Variables
// =========================================================================
// If a trade is filled (position_size != 0) OR if a trade was cancelled, reset the pending visualization levels.
if (strategy.position_size != 0 or tradeCancelled)
pendingEntry := na
pendingSL := na
pendingTP := na
// Plot EMA
plot(ema21, title="EMA 21", color=color.new(color.orange, 0), linewidth=2)
// Highlight the signal candles (only when valid with EMA filter)
bgcolor(validLongSignal and strategy.position_size == 0 ? color.new(color.green, 80) :
validShortSignal and strategy.position_size == 0 ? color.new(color.red, 80) : na)
CONNVERT THIS SAME CODE FOR MT5 .... Copy each and every lof
Assistant
Sure! Below is the converted script for MetaTrader 5 (MT5) using MQL5. Note that MQL5 has a different syntax and structure compared to Pine Script, so some adaptations are necessary.
mql5
//+------------------------------------------------------------------+
//| WicklessFib.mq5 |
//| Copyright 2023, MetaQuotes Software Corp. |
//| |
//+------------------------------------------------------------------+
#property strict
input double riskAmount = 100; // Risk Amount ($)
input double fibSL = -0.27; // Fibonacci Stop Loss Level
input double fibTP = 1.5; // Fibonacci Take Profit Level
input ENUM_ORDER_TYPE tradeDirection = MODE_BOTH; // Trade Direction (Long, Short, Both)
input int emaLength = 21; // EMA Length
input bool useEMAFilter = true; // Use EMA Filter
enum ENUM_ORDER_TYPE {MODE_LONG, MODE_SHORT, MODE_BOTH};
// Global variables
double pendingEntry = EMPTY_VALUE;
double pendingSL = EMPTY_VALUE;
double pendingTP = EMPTY_VALUE;
bool tradeCancelled = false;
double ema21[];
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
ArraySetAsSeries(ema21, true); // Set the array to be sorted as a series
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
// Calculate EMA
ArrayResize(ema21, emaLength);
ArrayCopy(ema21, 0, iMA(_Symbol, _Period, emaLength, 0, MODE_EMA, PRICE_CLOSE, 0), 0, emaLength);
// Reset cancellation flag if no position
if (PositionsTotal() == 0)
tradeCancelled = false;
// Check for pending orders from the previous tick
bool pendingLongOrder = (PositionsTotal() == 0) && IsWicklessBullish(1) && (tradeDirection == MODE_BOTH || tradeDirection == MODE_LONG);
bool pendingShortOrder = (PositionsTotal() == 0) && IsWicklessBearish(1) && (tradeDirection == MODE_BOTH || tradeDirection == MODE_SHORT);
// Cancellation Logic
if (pendingLongOrder && High[0] >= pendingTP)
{
tradeCancelled = true;
}
if (pendingShortOrder && Low[0] <= pendingTP)
{
tradeCancelled = true;
}
// Trade Execution Logic
if (PositionsTotal() == 0 && !tradeCancelled)
{
// Reset pending levels if no new signal
if (!IsWicklessBullish(0) && !IsWicklessBearish(0))
{
pendingEntry = EMPTY_VALUE;
pendingSL = EMPTY_VALUE;
pendingTP = EMPTY_VALUE;
}
// Long Entry Logic
if ((tradeDirection == MODE_LONG || tradeDirection == MODE_BOTH) && IsWicklessBullish(0))
{
double fibRange = High[0] - Low[0];
double longEntryPrice = Low[0];
double longStopLossPrice = longEntryPrice + fibRange * fibSL;
double longTakeProfitPrice = longEntryPrice + fibRange * fibTP;
pendingEntry = longEntryPrice;
pendingSL = longStopLossPrice;
pendingTP = longTakeProfitPrice;
double riskPerUnit = longEntryPrice - longStopLossPrice;
if (riskPerUnit > 0)
{
double lotSize = riskAmount / riskPerUnit;
OrderSend(_Symbol, OP_BUYLIMIT, lotSize, longEntryPrice, 3, longStopLossPrice, longTakeProfitPrice, "Long Order", 0, 0, clrGreen);
}
}
// Short Entry Logic
if ((tradeDirection == MODE_SHORT || tradeDirection == MODE_BOTH) && IsWicklessBearish(0))
{
double fibRange = Low[0] - High[0];
double shortEntryPrice = High[0];
double shortStopLossPrice = shortEntryPrice + fibRange * fibSL;
double shortTakeProfitPrice = shortEntryPrice + fibRange * fibTP;
pendingEntry = shortEntryPrice;
pendingSL = shortStopLossPrice;
pendingTP = shortTakeProfitPrice;
double riskPerUnit = shortStopLossPrice - shortEntryPrice;
if (riskPerUnit > 0)
{
double lotSize = riskAmount / riskPerUnit;
OrderSend(_Symbol, OP_SELLLIMIT, lotSize, shortEntryPrice, 3, shortStopLossPrice, shortTakeProfitPrice, "Short Order", 0, 0, clrRed);
}
}
}
// Reset state variables if a trade is filled or cancelled
if (PositionsTotal() > 0 || tradeCancelled)
{
pendingEntry = EMPTY_VALUE;
pendingSL = EMPTY_VALUE;
pendingTP = EMPTY_VALUE;
}
}
// Function to check for a wickless bullish candle
bool IsWicklessBullish(int shift)
{
return (Close[shift] > Open[shift]) && (Open[shift] == Low[shift]) && (!useEMAFilter || Close[shift] > ema21[shift]);
}
// Function to check for a wickless bearish candle
bool IsWicklessBearish(int shift)
{
return (Close[shift] < Open[shift]) && (Open[shift] == High[shift]) && (!useEMAFilter || Close[shift] < ema21[shift]);
}
Explanation:
Inputs and Configuration:
The inputs are defined using input keywords.
An enumeration ENUM_ORDER_TYPE is created for trade direction.
EMA Calculation:
The EMA is calculated and stored in the ema21 array. The array is set to be sorted as a series for easier access to the most recent values.
State Variables:
Variables to track pending orders and trade cancellation status are declared.
OnTick Function:
This function is called on every tick.
The EMA is recalculated on every tick.
The cancellation flag is reset if there are no open positions.
Pending orders are checked, and trades are cancelled if the take profit level is hit before the entry.
New trades are calculated and executed if there are no open positions and no trades were cancelled on the current tick.
State variables are reset if a trade is filled or cancelled.
Entry Logic:
For long entries, the script checks for a wickless bullish candle and, if the EMA filter is enabled, ensures the close is above the EMA.
For short entries, the script checks for a wickless bearish candle and, if the EMA filter is enabled, ensures the close is below the EMA.
Fibonacci levels are calculated based on the candle's high and low.
The position size is calculated based on the risk amount and the distance between the entry and stop loss.
Limit orders are placed for both long and short entries with the calculated stop loss and take profit levels.
Helper Functions:
IsWicklessBullish and IsWicklessBearish functions check for wickless candles and, if the EMA filter is enabled, ensure the close is on the correct side of the EMA.