//@version=4 strategy(title="GBPUSD LONG 15 MIN TWIN RANGE", shorttitle = "GBPUSD LONG 15 MIN TWIN", overlay=true, calc_on_order_fills=true, default_qty_value=10, default_qty_type=strategy.percent_of_equity) source = input(defval=low, title="Source") // Day Filter var g_days = "Days to Trade" d_monday = input(true, title="Monday", group=g_days, tooltip="Take trades on this day?", inline="day") d_tuesday = input(true, title="Tuesday", group=g_days, tooltip="Take trades on this day?", inline="day") d_wednesday = input(true, title="Wednesday", group=g_days, tooltip="Take trades on this day?", inline="day") d_thursday = input(true, title="Thursday", group=g_days, tooltip="Take trades on this day?", inline="day") d_friday = input(true, title="Friday", group=g_days, tooltip="Take trades on this day?", inline="day") // Check if the current day falls within the selected days day_filter = (dayofweek == dayofweek.monday and d_monday) or (dayofweek == dayofweek.tuesday and d_tuesday) or (dayofweek == dayofweek.wednesday and d_wednesday) or (dayofweek == dayofweek.thursday and d_thursday) or (dayofweek == dayofweek.friday and d_friday) // Time Range Filter var1 = input(0, title="Period Start Time", minval=0, maxval=24) var2 = input(23, title="Period End Time", minval=0, maxval=24) var3 = input(0, title="Time Zone Offset", minval=0, maxval=13) milTime = var3 == 0 ? hour : var3 < 0 ? hour > 3 ? hour + var3 : hour + 24 + var3 : hour >= 22 ? hour - 24 + var3 : hour + var3 if milTime > 23 milTime -= 24 time_filter = milTime >= var1 and milTime <= var2 // Combine Day and Time Filters daytime_filter = day_filter and time_filter // RSI Indicator use_rsi = input(true, title="Use RSI", group="Indicators") rsi_length = input(10, title="RSI Length", group="Indicators") rsi_overbought = input(2, title="RSI Overbought Level", group="Indicators") rsi_oversold = input(75, title="RSI Oversold Level", group="Indicators") rsi_value = use_rsi ? rsi(close, rsi_length) : na // Skip Trades Consecutive Losses skipAfterLosses = input(defval=true, title="Consecutive Loss Trade Disabler", type=input.bool) // Add an input variable to specify the number of consecutive losses required to skip trades consecutiveLossesLimit = input(defval=2, title="Consecutive Losses Limit", type=input.integer) // Initialize variables to keep track of trade results var consecutiveLosses = 0 var canTrade = true // Calculate Supertrend useSupertrendFilter = input(false, title="Use Supertrend Filter") var atrLength = input(14, "ATR Length", minval=60, tooltip="This determines the ATR Length for Supertrend") var factor = input(50, "Factor", step = 3.0,tooltip="This determines the ATR Length Factor for Supertrend") [supertrend, direction] = supertrend(factor, atrLength) ema200 = ema(close, 200) plot(ema200, title="EMA 200", color=color.yellow, linewidth=2) supColor = direction == -1 ? color.green : color.red plot(supertrend, title="Supertrend", color=useSupertrendFilter ? supColor : na, linewidth=2) // Track trade results and skip trades if needed if (strategy.position_size != 0) // Calculate the result of the current trade tradeResult = strategy.position_size > 0 ? close - strategy.position_avg_price : strategy.position_avg_price - close // If it's a loss, increment the consecutiveLosses count if (tradeResult < 0) consecutiveLosses := consecutiveLosses + 1 else // If it's a win or breakeven, reset the consecutiveLosses count consecutiveLosses := 0 // Check if we should skip new trades based on consecutive losses if (skipAfterLosses) canTrade := consecutiveLosses < consecutiveLossesLimit // Calculate True Range (TR) tr = max(max(high - low, abs(high - close[1])), abs(low - close[1])) // Smooth Average Range per1 = input(defval=60, minval=1, title="Fast period", group ="Twin Range Filter") mult1 = input(defval=5.0, minval=0.1, title="Fast range", group ="Twin Range Filter") per2 = input(defval=4, minval=1, title="Slow period", group ="Twin Range Filter") mult2 = input(defval=2.0, minval=0.1, title="Slow range", group ="Twin Range Filter") smoothrng(x, t, m) => wper = t * 2 - 1 avrng = ema(abs(x - x[1]), t) smoothrng = ema(avrng, wper) * m smoothrng smrng1 = smoothrng(source, per1, mult1) smrng2 = smoothrng(source, per2, mult2) smrng = (smrng1 + smrng2) / 2 // Range Filter rngfilt(x, r) => rngfilt = x rngfilt := x > nz(rngfilt[1]) ? x - r < nz(rngfilt[1]) ? nz(rngfilt[1]) : x - r : x + r > nz(rngfilt[1]) ? nz(rngfilt[1]) : x + r rngfilt filt = rngfilt(source, smrng) upward = 0.0 upward := filt > filt[1] ? nz(upward[1]) + 1 : filt < filt[1] ? 0 : nz(upward[1]) downward = 0.0 downward := filt < filt[1] ? nz(downward[1]) + 1 : filt > filt[1] ? 0 : nz(downward[1]) hband = filt + smrng lband = filt - smrng longCond = bool(na) shortCond = bool(na) // Define the minimum distance in pips minDistancePips = input(title="Min Entry - Take Profit Distance", defval=5, minval=1) // Calculate the minimum price change required for the specified pips minPriceChange = minDistancePips * syminfo.mintick // Long entry condition longCond := canTrade and daytime_filter and (source > filt and source > source[1] and upward > 0 or source > filt and source < source[1] and upward > 0) and (rsi_value > rsi_overbought or not use_rsi) // Short entry condition shortCond := canTrade and daytime_filter and (source < filt and source < source[1] and downward > 0 or source < filt and source > source[1] and downward > 0) and (rsi_value < rsi_oversold or not use_rsi) CondIni = 0 CondIni := longCond ? 1 : shortCond ? -1 : CondIni[1] long = longCond and CondIni[1] == -1 short = shortCond and CondIni[1] == 1 // Plotting // Strategy disabler = input(title="Disable ATR conditions", type=input.bool, defval=false, group = "ATR condition") //second l2 = input(title="ATR1", defval=80, minval=1, group = "ATR condition", tooltip = "C: Short-range volatility must be low than long-term volatility measurement for the entry.") s2 = input(title="Smoothing", defval="EMA", options=["RMA", "SMA", "EMA", "WMA"], tooltip = "C: Short-range volatility must be low than long-term volatility measurement for the entry.", group = "ATR condition") atr2(source, l2) => if s2 == "SMA" sma(source, l2) else if s2 == "RMA" rma(source, l2) else if s2 == "EMA" ema(source, l2) else wma(source, l2) //third l3 = input(title="ATR2", defval=20, minval=1, group = "ATR condition", tooltip = "C: Short-range volatility must be low than long-term volatility measurement for the entry.") s3 = input(title="Smoothing", defval="EMA", options=["RMA", "SMA", "EMA", "WMA"], tooltip = "C: Short-range volatility must be low than long-term volatility measurement for the entry.", group = "ATR condition") atr3(source, l3) => if s3 == "RMA" rma(source, l3) else if s3 == "SMA" sma(source, l3) else if s3 == "EMA" ema(source, l3) else wma(source, l3) atr20=atr2(tr(true), l2) atr30=atr3(tr(true), l3) var tradeLoss = 0.0 // Variable to keep track of the current trade's losses // Risk Management riskPerTrade = input(5.0, title="Risk Per Trade (%)", type=input.float, group = "Risk Management") // Set your desired risk percentage acc_leverage = input(500.0, title="Trading Account Leverage", type=input.float, group = "Risk Management") ordersize = floor((riskPerTrade / 100) * strategy.equity * acc_leverage) i_time = input(true, "Enable Time Base Close", group = "Risk Management") maxcandles_till_close = input(2, title="Time-based Close", type=input.integer, defval=30, group = "Risk Management") mintick = input(defval=0.00001, title="Tick Decimals", group = "Risk Management", type=input.float) slippage = input(defval=0.00002, title="Add/Minus Slippage for TP-Entry Distance", group = "Risk Management", tooltip="Dynamically add/deduct slippage based on higher timeframe trend", type=input.float) // Calculate 1-hour moving average useMA = input(true, title="Use Moving Average", group = "Moving Average Trend") MAlength = input(2, title="Alternate Timeline Trend Confirmation", type=input.integer, defval=2, group = "Moving Average Trend") ma_1hour = sma(close, MAlength) // Determine the 15-minute trend based on the 1-hour moving average trend = close > ma_1hour ? 1 : close < ma_1hour ? -1 : 0 //stop var stop_long = 0.0, var entry = 0.0, var stop_short = 0.0 i_sl_type = input("Close - abs(Close - Lowest Low[len]) * %", options = ["Low - (ATR[len] * %)", "Low - (close - lowest low[len]) * %", "Low - (close - average low[len]) * %", "Close - (ATR[len] * %)", "Low - TicksNumber", "Close - abs(Close - Lowest Low[len]) * %"], title ="Calculation (Long)", group = "Stop-loss", tooltip = "This is a stop-loss calculation for long positions. Reversed logic is used for short stop-loss. *Calculation Low - TicksNumber doesn't use Percentage-based multiplier. **Number of ticks are always subtracted (added) after the initial calculation. ") i_sl_atr = input(1, "Calculation Length", group = "Stop-loss") i_sl_perc = input(50, "Percentage", group = "Stop-loss", type = input.float) / 100 i_sl_ticks = input(defval = 10, minval = 1, title = "Number of ticks", group = "Stop-loss") * mintick i_stoploss = input(true, "Enable Stop-loss", group = "Stop-loss") f_stop_long (calculation, length, mult, ticks) => stop_0 = calculation == "Low - (ATR[len] * %)" ? low - (atr(length) * mult) - ticks : calculation == "Low - (close - lowest low[len]) * %" ? low - abs(close - lowest(low, length)) * mult - ticks : calculation == "Low - (close - average low[len]) * %" ? low - abs(close - sma(low, length)) * mult - ticks : calculation == "Close - (ATR[len] * %)" ? close - (atr(length) * mult) - ticks : calculation == "Close - abs(Close - Lowest Low[len]) * %" ? close - abs(close - lowest(low, length)) * mult - ticks : low - ticks f_stop_short (calculation, length, mult, ticks) => stop_0 = calculation == "Low - (ATR[len] * %)" ? high + (atr(length) * mult) + ticks : calculation == "Low - (close - lowest low[len]) * %" ? high + abs(close - lowest(high, length)) * mult + ticks : calculation == "Low - (close - average low[len]) * %" ? high + abs(close - sma(high, length)) * mult + ticks : calculation == "Close - (ATR[len] * %)" ? close + (atr(length) * mult) + ticks : calculation == "Close - abs(Close - Lowest Low[len]) * %" ? close + (atr(length) * mult) + ticks : high + ticks //target var target_long = 0.0, var target_short = 0.0 i_tr_type = input("Close + abs(close - highest high[len]) * %", options = ["High + (ATR[len] * %)", "Close + (ATR[len] * %)", "Close + abs(close - highest high[len]) * %", "Close + abs(close - average high[len]) * %", "High + TicksNumber", "Close + TicksNumber"], title="Calculation (Long)", group = "Target", tooltip = "Raw number of ticks is always added to the target.") i_tr_atr = input(1, "Calculation Length", group = "Target") i_tr_perc = input(90, "Percentage", group = "Target", type = input.float) / 100 i_tr_ticks = input(defval = 1, minval = 1, title = "Number of ticks", group = "Target") * mintick i_target = input(true, "Enable Target", group = "Target") f_target_long (calculation, length, mult, ticks) => stop_0 = calculation == "High + (ATR[len] * %)" ? high + (atr(length) * mult) + ticks : calculation == "Close + (ATR[len] * %)" ? close + (atr(length) * mult) + ticks : calculation == "Close + abs(close - highest high[len]) * %" ? close + abs(close - (highest(high, length))) * mult + ticks : calculation == "Close + abs(close - average high[len]) * %" ? close + abs(close - sma(high, length)) * mult + ticks : calculation == "High + TicksNumber" ? high + ticks : close + ticks f_target_short (calculation, length, mult, ticks) => stop_0 = calculation == "High + (ATR[len] * %)" ? low - (atr(length) * mult) - ticks : calculation == "Close + (ATR[len] * %)" ? close - (atr(length) * mult) - ticks : calculation == "Close + abs(close - highest high[len]) * %" ? close - abs(close - (lowest(low, length))) * mult - ticks : calculation == "Close + abs(close - average high[len]) * %" ? close - abs(close - sma(low, length)) * mult - ticks : calculation == "High + TicksNumber" ? low - ticks : close - ticks // Calculate stop loss and take profit in market price stop_long := i_stoploss ? f_stop_long(i_sl_type, i_sl_atr, i_sl_perc, i_sl_ticks) : na target_long := i_target ? f_target_long(i_tr_type, i_tr_atr, i_tr_perc, i_tr_ticks) : na stop_short := i_stoploss ? f_stop_short(i_sl_type, i_sl_atr, i_sl_perc, i_sl_ticks) : na target_short := i_target ? f_target_short(i_tr_type, i_tr_atr, i_tr_perc, i_tr_ticks) : na if (strategy.position_size >= 0 or strategy.position_size[1] != strategy.position_size) stop_short := i_stoploss ? f_stop_short(i_sl_type, i_sl_atr, i_sl_perc, i_sl_ticks) : na target_short := i_target ? f_target_short(i_tr_type, i_tr_atr, i_tr_perc, i_tr_ticks) : na if (strategy.position_size <= 0 or strategy.position_size[1] != strategy.position_size) stop_long := i_stoploss ? f_stop_long(i_sl_type, i_sl_atr, i_sl_perc, i_sl_ticks) : na target_long := i_target ? f_target_long(i_tr_type, i_tr_atr, i_tr_perc, i_tr_ticks) : na if (strategy.position_size == 0 or strategy.position_size[1] != strategy.position_size) entry := open // PineConnector Settings var g_pc = "PineConnector Settings" pc_id = input(title="License ID", defval="", group=g_pc, tooltip="This is your PineConnector license ID") pc_risk = riskPerTrade pc_prefix = input(title="MetaTrader Prefix", defval="", group=g_pc, tooltip="This is your broker's MetaTrader symbol prefix") pc_suffix = input(title="MetaTrader Suffix", defval="", group=g_pc, tooltip="This is your broker's MetaTrader symbol suffix") pc_spread = input(title="Spread", defval=0.5, group=g_pc, tooltip="Enter your average spread for this pair (used for offsetting limit order)") pc_limit = input(title="PC Limit", defval=false, group=g_pc, tooltip="If true a limit order will be used, if false a market order will be used") // Generate PineConnector alert string var symbol = pc_prefix + syminfo.ticker + pc_suffix var limit = pc_limit ? "limit" : "" pc_entry_alert(direction, sl, tp) => pc_id + "," + direction + "," + symbol + ",sl=" + tostring(sl) + ",tp=" + tostring(tp) + ",risk=" + tostring(pc_risk) pc_close_alert(direction) => pc_id + "," + direction + "," + symbol pc_cancel_alert(direction) => pc_id + "," + direction + "," + symbol enable_long = input(true, title="Enable Long Trade") enable_short = input(false, title="Enable Short Trade") bull = enable_long and long and (atr20 < atr30 or disabler) and (not useSupertrendFilter or direction == 1) and (useMA ? trend == 1 : true) bear = enable_short and short and (atr20 < atr30 or disabler) and (not useSupertrendFilter or direction == -1) and (useMA ? trend == -1 : true) bullclock = barssince(bull) bearclock = barssince(bear) // Initialize custom counter variables var int longEntryBar = 0 var int shortEntryBar = 0 if (bull) strategy.entry("Twin Long", strategy.long, qty=ordersize) adjustedTP = target_long + slippage alertStringLong = pc_entry_alert("buy", stop_long, adjustedTP) alert(alertStringLong, alert.freq_once_per_bar_close) strategy.exit("Exit", from_entry = "Twin Long", limit = target_long, stop = stop_long) if (bear) strategy.entry("Twin Short", strategy.short, qty=ordersize) adjustedTP = target_short - slippage alertStringShort = pc_entry_alert("sell", stop_short, adjustedTP) alert(alertStringShort, alert.freq_once_per_bar_close) strategy.exit("Exit", from_entry = "Twin Short", limit = target_short, stop = stop_short) // Exit Conditions for Long Trades if (strategy.position_size > 0 and i_time and bullclock == maxcandles_till_close) alert(pc_close_alert("closelong")) strategy.close("Twin Long") // Exit Conditions for Short Trades if (strategy.position_size < 0 and i_time and bearclock == maxcandles_till_close) alert(pc_close_alert("closeshort")) strategy.close("Twin Short") // Update custom counter variables on entry if (bull and strategy.position_size[1] == 0) longEntryBar := bar_index if (bear and strategy.position_size[1] == 0) shortEntryBar := bar_index // Plotting longTarget = f_target_long(i_tr_type, i_tr_atr, i_tr_perc, i_tr_ticks) shortTarget = f_target_short(i_tr_type, i_tr_atr, i_tr_perc, i_tr_ticks) c_fill_stop = color.new(color.red, 90) c_fill_target = color.new(color.green, 90) p_longstop = plot(strategy.position_size > 0 and i_stoploss ? stop_long : na, linewidth = 2, color = color.red, style = plot.style_linebr) p_shortstop = plot(strategy.position_size < 0 and i_stoploss ? stop_short : na, linewidth = 2, color = color.red, style = plot.style_linebr) p_entry = plot(strategy.position_size != 0 ? entry : na, linewidth = 2, color = color.blue, style = plot.style_linebr) p_longtarget = plot(strategy.position_size > 0 and i_target ? target_long : na, linewidth = 2, color = color.green, style = plot.style_linebr) p_shorttarget = plot(strategy.position_size < 0 and i_target ? target_short : na, linewidth = 2, color = color.green, style = plot.style_linebr) fill(p_entry, p_longstop, c_fill_stop) fill(p_entry, p_shortstop, c_fill_stop) fill(p_entry, p_longtarget, c_fill_target) fill(p_entry, p_shorttarget, c_fill_target)