本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
// ╔══════════════════════════════════════════════════════════════════════════╗
// ║ LIQUIDITY SCALPING V1.0 — built from BOX_ENGINE V2.1 (1M) ║
// ║ Entries: same as BOX_ENGINE V2.1 (1M) - 1-minute chart, box 09:30-10:00 ║
// ║ NY, 1m close beyond the level + volume / delta filters, one entry per ║
// ║ 30-minute cycle, previous 30m candle break after a trade, back inside ║
// ║ the box = fresh box break. ║
// ║ Removed: ATR filter, daily ATR zones, ATR gears, RC (manual only). ║
// ║ Exits (FLOWLOCK style): take profit, stop loss, stop steps 1 / 2, ║
// ║ break-even (overrides trailing), trailing activation / offset, ║
// ║ scale-in (add to winner) with the stop at least the new average, ║
// ║ stop lock (the stop never moves back). ║
// ║ Decided at each 1-minute close (live = chart). Stop and target rest as ║
// ║ orders and fill on the tick price hits them. If at the close price is ║
// ║ already beyond the new stop, the position is closed at that close. ║
// ╚══════════════════════════════════════════════════════════════════════════╝
// ╔══════════════════════════════════════════════════════════════════════════╗
// ║ BOX_ENGINE V2.1 (1M) RUNS ON THE 1-MINUTE CHART ║
// ║ - Box 09:30-10:00 NY. A 1m candle CLOSES beyond box +/- buffer AND the ║
// ║ 1m filters (volume / delta) pass -> enter at that close. ║
// ║ - ONE entry per 30-minute cycle. After an entry: locked until the ║
// ║ 30m cycle closes. ║
// ║ - Next cycles: level = previous 30m candle high + buffer / low - buffer ║
// ║ (after a trade, or when the previous 30m candle closed beyond the ║
// ║ box). A later 30m candle back inside the box = fresh box break. ║
// ╚══════════════════════════════════════════════════════════════════════════╝
// ╔══════════════════════════════════════════════════════════════════════════╗
// ║ V2.0 SIMPLE BREAK: box break +buffer; after a trade, previous-candle ║
// ║ break +buffer; back inside the box = reset. No retracement modes. ║
// ║ V1.9 LIVE = CHART (the alert copy and the chart take the SAME trades) ║
// ║ 1. The script decides ONCE per candle, at its close (calc_on_every_tick ║
// ║ off). Orders are resting stop/limit orders, so they still FILL and ║
// ║ the ALERT fires on the tick price hits them - no candle-close wait. ║
// ║ 2. No tick memory (varip): live and the recalculated chart see exactly ║
// ║ the same closed-candle data, so they can not decide differently. ║
// ║ 3. ATRs from closed candles only. Daily ATR = yesterday's value. ║
// ║ 4. The order for the NEXT candle is never blocked by an entry on the ║
// ║ candle that just closed (the big breakout candle had no order). ║
// ║ 5. Bar Magnifier on: the chart fills entries/exits inside the candle ║
// ║ with lower-timeframe data, like live (TradingView Premium). ║
// ╚══════════════════════════════════════════════════════════════════════════╝
// ╔══════════════════════════════════════════════════════════════════════════╗
// ║ BOX_ENGINE V1.7 (MEMORY LOCKED) — Pine Script v6 ║
// ║ FIX 1: Restored native stable box tracking logic. ║
// ║ FIX 2: Hardcoded all exact user gear parameters and window restrictions. ║
// ║ NEW 1: Memory Lock enforces Max Trades Per Bar. ║
// ║ V6: Migrated to Pine v6. margin_long/short pinned to 0 (v5 behaviour). ║
// ║ CLEANUP: Removed Strict 1/Day, VXN filter, Order Flow Radar, RB Midline. ║
// ║ FIX 3: Orders pre-armed at close of last box candle (backtest = live). ║
// ║ V1.5 FIX 4: Time Stop now measured from the real fill (was bar-open ║
// ║ based -> killed live trades seconds after entry). ║
// ║ V1.5 FIX 5: Long/Short entries linked in an OCA group (no reversal). ║
// ║ V1.5 FIX 6: Closed-trade counter no longer re-counts on every tick. ║
// ║ V1.6 NEW: Every entry must BREAK the previous candle: long only above ║
// ║ its high, short only below its low (then the retracement ║
// ║ limit applies). Inside bar = no break = no trade. ║
// ║ V1.7 NEW: BOX RETURN RESET — after a trade, if price comes back inside ║
// ║ the box, the next entry (buy or sell) only needs to break the ║
// ║ box again (no previous-candle break, no retracement). Normal ║
// ║ rule resumes once that entry fills. ║
// ╚══════════════════════════════════════════════════════════════════════════╝
strategy("LIQUIDITY SCALPING V1.0", overlay=true, calc_on_every_tick=false, process_orders_on_close=true, use_bar_magnifier=false, calc_on_order_fills=false, max_labels_count=500, max_lines_count=500, initial_capital=10000, currency=currency.USD, default_qty_type=strategy.fixed, default_qty_value=1, commission_type=strategy.commission.cash_per_contract, commission_value=1.0, slippage=4, pyramiding=3, margin_long=0, margin_short=0)
// ============================================================================
// 1. POSITION SIZING & ACCOUNT RISK
// ============================================================================
g_risk = "━━━━━ ⚙️ 1. POSITION SIZING & ACCOUNT RISK ━━━━━"
trade_qty = input.int(1, "Trade Quantity", group=g_risk)
global_sync = input.string("Strict Flat (1 Trade Max)", "Global Overlap Mode", options=["Strict Flat (1 Trade Max)", "Directional Pyramid (Same Dir Only)", "Independent (Allow Hedge)"], group=g_risk)
use_max_loss = input.bool(false, "Enable Daily Max Loss?", group=g_risk)
max_loss_usd = input.float(170.0, "Max Loss Limit ($)", group=g_risk)
use_max_profit = input.bool(false, "Enable Daily Max Profit?", group=g_risk)
max_profit_usd = input.float(300.0, "Max Profit Target ($)", group=g_risk)
// ============================================================================
// 2. ENGINE FILTERS & SAFETY GATES
// ============================================================================
g_safe = "━━━━━ 🛡️ 2. ENGINE FILTERS & SAFETY GATES ━━━━━"
use_time_stop = input.bool(false, "Enable Time Stop?", group=g_safe)
time_stop_mins = input.int(3, "Kill Trade After X Mins", group=g_safe)
use_news_block = input.bool(false, "Enable News Blackout?", group=g_safe)
news_dates = input.string("2026-05-06", "News Dates (YYYY-MM-DD, comma sep)", group=g_safe)
news_time = input.session("0959-1030", "Blackout Time Window", group=g_safe)
block_dates = input.string("2026-01-20, 2026-02-17", "Holiday Block Dates (YYYY-MM-DD)", group=g_safe)
// ============================================================================
// 3. ENGINE: CORE LOGIC & EXITS
// ============================================================================
g_main = "━━━━━ 🔴 3. ENGINE: CORE LOGIC & EXITS ━━━━━"
u5 = input.bool(true, "Enable Engine", group=g_main)
orb_time = input.session("0930-1000", "RB Box Window", group=g_main)
block_first = input.bool(false, "Block 1st Candle?", group=g_main)
limit_one_per_bar = input.bool(false, "Limit to One Entry Per Bar?", group=g_main)
max_entries_per_bar = input.int(1, "Max Entries Per Bar", minval=1, maxval=10, group=g_main)
brk_buf = input.float(2.0, "Break Buffer (points)", step=0.25, minval=0, group=g_main, tooltip="Long: price breaks the box high + buffer. Short: price breaks the box low - buffer. After a trade, every new entry must break the previous candle high + buffer (long) or low - buffer (short). If price comes back inside the box, the rule resets to a fresh box break.")
use_max_t_5 = input.bool(false, "Enable Max Total Trades?", group=g_main)
max_tot_5 = input.int(4, "Max Total Trades", minval=1, group=g_main)
use_max_d_5 = input.bool(false, "Enable Max Direction Limit?", group=g_main)
max_dir_5 = input.int(4, "Max Per Direction", minval=1, group=g_main)
// ============================================================================
// 4. RISK MANAGEMENT (POINTS) - FLOWLOCK STYLE
// ============================================================================
g_rm = "━━━━━ 🎯 4. RISK MANAGEMENT (POINTS) ━━━━━"
tp_pts = input.float(60.0, "Take Profit", minval=0.25, step=0.25, group=g_rm)
sl_pts = input.float(40.0, "Stop Loss", minval=0.25, step=0.25, group=g_rm)
use_be = input.bool(false, "Enable Break-Even (Overrides Trailing)", tooltip="Once price reaches the activation, the stop goes to the average price + 1 point. When ON, the trailing is not used.", group=g_rm)
be_on = input.float(20.0, "Break-Even Activation", minval=0.0, step=0.25, group=g_rm)
use_trail = input.bool(true, "Enable Trailing", group=g_rm)
trail_on = input.float(20.0, "Trailing Activation", minval=0.0, step=0.25, tooltip="Points in profit (best price vs average) before the trailing starts.", group=g_rm)
trail_off = input.float(20.0, "Trailing Offset", minval=0.25, step=0.25, tooltip="The stop follows the best price at this distance.", group=g_rm)
scale_on = input.bool(false, "Enable Scale-In (Add to Winner)", tooltip="Once, when a 1-minute candle closes this many points in profit (vs the average), add contracts. After the add, the stop is at least the new average price (whole position break-even or better). TP, steps, break-even and trailing are then measured from the new average.", group=g_rm)
scale_pts = input.float(20.0, "Scale-In Distance", minval=0.25, step=0.25, group=g_rm)
scale_qty = input.int(1, "Scale-In Qty", minval=1, group=g_rm)
use_steps = input.bool(false, "Enable Stop Steps", tooltip="Tightens the stop in stages as the trade moves your way, before the trailing takes over. A step is ignored whenever it is not tighter than the stop already held.", group=g_rm)
s1_on = input.float(10.0, "Step 1: Activate at (Points in Profit)", minval=0.0, step=0.25, group=g_rm)
s1_sl = input.float(24.0, "Step 1: New Stop Distance (From Average)", minval=0.0, step=0.25, group=g_rm)
use_s2 = input.bool(false, "Enable Step 2", group=g_rm)
s2_on = input.float(18.0, "Step 2: Activate at (Points in Profit)", minval=0.0, step=0.25, group=g_rm)
s2_sl = input.float(16.0, "Step 2: New Stop Distance (From Average)", minval=0.0, step=0.25, group=g_rm)
// ============================================================================
// 5. SCHEDULE & MACRO TIME
// ============================================================================
g_time = "━━━━━ 📅 5. SCHEDULE & MACRO TIME ━━━━━"
tz = input.string("America/New_York", "Time Zone", options=["America/New_York", "America/Chicago", "Europe/London", "Europe/Berlin", "Europe/Bucharest", "Asia/Tokyo"], group=g_time)
close_eod = input.bool(true, "Close all trades at EOD?", group=g_time)
eod_time = input.session("1530-1545", "EOD Time", group=g_time)
act_tz = tz
g_mon = "📅 MONDAY"
mon_w1_on = input.bool(true, "Mon W1", group=g_mon)
mon_w1_tm = input.session("0930-1530", "Mon W1 Time", group=g_mon)
mon_w2_on = input.bool(false, "Mon W2 ", group=g_mon)
mon_w2_tm = input.session("1200-1400", "Mon W2 Time", group=g_mon)
g_tue = "📅 TUESDAY"
tue_w1_on = input.bool(true, "Tue W1", group=g_tue)
tue_w1_tm = input.session("0930-1530", "Tue W1 Time", group=g_tue)
tue_w2_on = input.bool(false, "Tue W2 ", group=g_tue)
tue_w2_tm = input.session("1200-1400", "Tue W2 Time", group=g_tue)
g_wed = "📅 WEDNESDAY"
wed_w1_on = input.bool(true, "Wed W1", group=g_wed)
wed_w1_tm = input.session("0930-1530", "Wed W1 Time", group=g_wed)
wed_w2_on = input.bool(false, "Wed W2 ", group=g_wed)
wed_w2_tm = input.session("1200-1400", "Wed W2 Time", group=g_wed)
g_thu = "📅 THURSDAY"
thu_w1_on = input.bool(true, "Thu W1", group=g_thu)
thu_w1_tm = input.session("0930-1530", "Thu W1 Time", group=g_thu)
thu_w2_on = input.bool(false, "Thu W2 ", group=g_thu)
thu_w2_tm = input.session("1200-1400", "Thu W2 Time", group=g_thu)
g_fri = "📅 FRIDAY"
fri_w1_on = input.bool(true, "Fri W1", group=g_fri)
fri_w1_tm = input.session("0930-1530", "Fri W1 Time", group=g_fri)
fri_w2_on = input.bool(false, "Fri W2 ", group=g_fri)
fri_w2_tm = input.session("1200-1400", "Fri W2 Time", group=g_fri)
// ============================================================================
// 1-MINUTE ENTRY FILTERS (checked on the breakout minute)
// ============================================================================
g_f1 = "━━━━━ ⏱️ 1-MINUTE ENTRY ━━━━━"
cyc_min = input.int(30, "Cycle Length (Minutes)", minval=5, maxval=240, tooltip="One entry per cycle. 30 = the 30-minute candles. The previous-candle levels also use this length.", group=g_f1)
cross_mode = input.string("Close Crosses The Level", "Entry Trigger", options=["Close Crosses The Level", "Any Close Beyond The Level"], tooltip="Close Crosses = the 1m candle that closes across the level (previous 1m close was not beyond it). Any Close Beyond = the first 1m close beyond the level that passes the filters, inside the cycle.", group=g_f1)
f_len = input.int(20, "Average Length (1m Candles)", minval=2, maxval=200, group=g_f1)
f_vol_on = input.bool(true, "Volume Filter", inline="fv", group=g_f1)
f_vol_x = input.float(1.5, "At Least (x Average)", minval=0.1, step=0.1, inline="fv", tooltip="Volume of the breakout minute vs the average volume of the last X closed minutes.", group=g_f1)
f_dlt_on = input.bool(true, "Delta Filter", inline="fd", group=g_f1)
f_dlt_x = input.float(1.5, "At Least (x Average)", minval=0.1, step=0.1, inline="fd", tooltip="Delta of the breakout minute in the trade direction (long = buyers, short = sellers) vs the average delta size of the last X minutes. Built from 1-second data: TradingView keeps it only for recent days, so older days in the backtest get no trades with this filter on.", group=g_f1)
show_lvls = input.bool(true, "Show Entry Levels", group=g_f1)
// ============================================================================
// LOGIC EXECUTION
// ============================================================================
y_str = str.tostring(year(time, syminfo.timezone))
m_str = str.tostring(month(time, syminfo.timezone))
d_str = str.tostring(dayofmonth(time, syminfo.timezone))
m_str := str.length(m_str) == 1 ? "0" + m_str : m_str
d_str := str.length(d_str) == 1 ? "0" + d_str : d_str
today_str = y_str + "-" + m_str + "-" + d_str
is_blocked = str.contains(block_dates, today_str)
int today_key = year(time, "America/New_York") * 10000 + month(time, "America/New_York") * 100 + dayofmonth(time, "America/New_York")
var int current_day_key = na
bool new_day = na(current_day_key) or today_key != current_day_key
var float start_of_day_profit = 0.0
if new_day
current_day_key := today_key
start_of_day_profit := strategy.netprofit
float daily_pnl = strategy.netprofit - start_of_day_profit + strategy.openprofit
bool daily_loss_hit = use_max_loss and (daily_pnl <= -max_loss_usd)
bool daily_profit_hit = use_max_profit and (daily_pnl >= max_profit_usd)
if (daily_loss_hit or daily_profit_hit) and strategy.opentrades > 0
strategy.close_all(comment="DAILY LIMIT: FLAT")
if timeframe.period != "1"
runtime.error("LIQUIDITY SCALPING V1.0 must run on the 1-minute chart.")
is_mon = dayofweek == dayofweek.monday
is_tue = dayofweek == dayofweek.tuesday
is_wed = dayofweek == dayofweek.wednesday
is_thu = dayofweek == dayofweek.thursday
is_fri = dayofweek == dayofweek.friday
mon_active = is_mon and ((mon_w1_on and not na(time(timeframe.period, mon_w1_tm, act_tz))) or (mon_w2_on and not na(time(timeframe.period, mon_w2_tm, act_tz))))
tue_active = is_tue and ((tue_w1_on and not na(time(timeframe.period, tue_w1_tm, act_tz))) or (tue_w2_on and not na(time(timeframe.period, tue_w2_tm, act_tz))))
wed_active = is_wed and ((wed_w1_on and not na(time(timeframe.period, wed_w1_tm, act_tz))) or (wed_w2_on and not na(time(timeframe.period, wed_w2_tm, act_tz))))
thu_active = is_thu and ((thu_w1_on and not na(time(timeframe.period, thu_w1_tm, act_tz))) or (thu_w2_on and not na(time(timeframe.period, thu_w2_tm, act_tz))))
fri_active = is_fri and ((fri_w1_on and not na(time(timeframe.period, fri_w1_tm, act_tz))) or (fri_w2_on and not na(time(timeframe.period, fri_w2_tm, act_tz))))
bool in_trade_window = mon_active or tue_active or wed_active or thu_active or fri_active
// DAILY COUNTERS
var int closed_L = 0
var int closed_S = 0
var bool arm5L = true
var bool arm5S = true
if new_day
closed_L := 0
closed_S := 0
arm5L := true
arm5S := true
var int entries_this_bar = 0
var int last_bar_index_seen = -1
if bar_index != last_bar_index_seen
entries_this_bar := 0
last_bar_index_seen := bar_index
var int last_total_entries = 0
int current_total_entries = strategy.opentrades + strategy.closedtrades
if current_total_entries > last_total_entries
entries_this_bar := entries_this_bar + (current_total_entries - last_total_entries)
last_total_entries := current_total_entries
int effective_limit = limit_one_per_bar ? 1 : max_entries_per_bar
// V1.8 FIX: at the candle CLOSE the orders are placed for the NEXT candle, which has
// 0 entries yet. Before, an entry on this candle blocked the orders for the next one,
// so the next candle got no order (on the chart that cost a whole candle).
bool bar_gated_ok = barstate.isconfirmed ? true : entries_this_bar < effective_limit
// V1.5 FIX 6: count each closed trade exactly once (tick-safe)
var int last_closed_seen = 0
if strategy.closedtrades > last_closed_seen
int new_closes = strategy.closedtrades - last_closed_seen
for i = 1 to new_closes
string cid = strategy.closedtrades.entry_id(strategy.closedtrades - i)
if cid == "En_L"
closed_L := closed_L + 1
arm5L := false
else if cid == "En_S"
closed_S := closed_S + 1
arm5S := false
last_closed_seen := strategy.closedtrades
int open_L = 0
int open_S = 0
if strategy.opentrades > 0
for i = 0 to strategy.opentrades - 1
string oid = strategy.opentrades.entry_id(i)
if oid == "En_L"
open_L := open_L + 1
else if oid == "En_S"
open_S := open_S + 1
int longs5 = closed_L + open_L
int shorts5 = closed_S + open_S
int trades5 = longs5 + shorts5
bool inL = open_L > 0
bool inS = open_S > 0
if inL and not inL[1]
arm5L := false
if inS and not inS[1]
arm5S := false
// time stop clock: set when the position opens from flat (an add does not restart it)
var int entry_clock = na
var int prev_open = 0
int now_clock = time_close // same clock live and on the chart
if strategy.opentrades > 0 and prev_open == 0
entry_clock := now_clock
if strategy.opentrades == 0
entry_clock := na
prev_open := strategy.opentrades
// ═══════════════════════════════════════════════════════════════════════════
// NATIVE STABLE BOX ENGINE BOUNDS
// ═══════════════════════════════════════════════════════════════════════════
var float h5 = na
var float l5 = na
if new_day
strategy.cancel_all()
h5 := na
l5 := na
in5 = time(timeframe.period, orb_time, act_tz)
if not na(in5)
h5 := na(in5[1]) ? high : math.max(h5, high)
l5 := na(in5[1]) ? low : math.min(l5, low)
// ═══════════════════════════════════════════════════════════════════════════
// ═══════════════════════════════════════════════════════════════════════════
// V2.1 30-MINUTE CYCLES ON THE 1-MINUTE CHART
// ═══════════════════════════════════════════════════════════════════════════
int cyc = int(math.floor(time / (cyc_min * 60000.0)))
bool new_cyc = cyc != cyc[1]
var float c_hi = na
var float c_lo = na
var float c_cl = na
var float p_hi = na // previous 30m candle
var float p_lo = na
var float p_cl = na
var int p_cyc = na
if new_cyc
p_hi := c_hi
p_lo := c_lo
p_cl := c_cl
p_cyc := cyc[1]
c_hi := high
c_lo := low
else
c_hi := math.max(nz(c_hi, high), high)
c_lo := math.min(nz(c_lo, low), low)
c_cl := close
bool box_done = not na(h5) and na(in5)
var int first_cyc = na // first cycle after the box
if new_day
first_cyc := na
if box_done and na(first_cyc)
first_cyc := cyc
bool box_cleared = block_first ? cyc != first_cyc : true
// ═══════════════════════════════════════════════════════════════════════════
// V2.1 BREAK RULE + ONE ENTRY PER CYCLE
// - No trade yet: level = box high + buffer / box low - buffer.
// - After an entry, or when the previous 30m candle CLOSED beyond the box
// level: level = previous 30m candle high + buffer / low - buffer.
// - A LATER 30m candle trades back inside the box: fresh box break.
// - After an entry: no new entry until the 30m cycle closes.
// ═══════════════════════════════════════════════════════════════════════════
var bool need_prev_brk = false
var int lock_cyc = na
if new_day
need_prev_brk := false
lock_cyc := na
if new_cyc and not na(h5) and not na(lock_cyc) and not na(p_cyc) and p_cyc > lock_cyc and p_hi >= l5 and p_lo <= h5
need_prev_brk := false // back in the box -> fresh box break
float boxL = h5 + brk_buf
float boxS = l5 - brk_buf
bool usePL = need_prev_brk or (not na(p_cl) and p_cl >= boxL)
bool usePS = need_prev_brk or (not na(p_cl) and p_cl <= boxS)
float lvlL = usePL and not na(p_hi) ? math.max(p_hi, h5) + brk_buf : boxL
float lvlS = usePS and not na(p_lo) ? math.min(p_lo, l5) - brk_buf : boxS
bool brkL = cross_mode == "Close Crosses The Level" ? (close > lvlL and close[1] <= lvlL) : close > lvlL
bool brkS = cross_mode == "Close Crosses The Level" ? (close < lvlS and close[1] >= lvlS) : close < lvlS
bool cyc_free = na(lock_cyc) or cyc != lock_cyc
// ---- 1m filters on the breakout minute ----
float vol_avg = ta.sma(volume, f_len)[1]
bool vol_ok = not f_vol_on or (not na(vol_avg) and volume >= f_vol_x * vol_avg)
[o_1s, c_1s, v_1s] = request.security_lower_tf(syminfo.tickerid, "1S", [open, close, volume])
var float pc_1s = na
float d_1m = 0.0
int n_1s = array.size(v_1s)
if n_1s > 0
for i = 0 to n_1s - 1
float o_ = array.get(o_1s, i)
float c_ = array.get(c_1s, i)
float v_ = array.get(v_1s, i)
float pc = i == 0 ? nz(pc_1s, o_) : array.get(c_1s, i - 1)
d_1m += c_ > o_ ? v_ : c_ < o_ ? -v_ : (c_ > pc ? v_ : c_ < pc ? -v_ : 0.0)
pc_1s := array.get(c_1s, n_1s - 1)
bool has_d = n_1s > 0
float dlt_avg = ta.sma(has_d ? math.abs(d_1m) : na, f_len)[1]
bool dltL_ok = not f_dlt_on or (has_d and not na(dlt_avg) and d_1m > 0 and d_1m >= f_dlt_x * dlt_avg)
bool dltS_ok = not f_dlt_on or (has_d and not na(dlt_avg) and d_1m < 0 and -d_1m >= f_dlt_x * dlt_avg)
// ═══════════════════════════════════════════════════════════════════════════
if not na(h5)
if strategy.position_size == 0
arm5L := true
arm5S := true
bool ok_global_L = global_sync == "Strict Flat (1 Trade Max)" ? (not inL and not inS) : global_sync == "Directional Pyramid (Same Dir Only)" ? (not inS) : true
bool ok_global_S = global_sync == "Strict Flat (1 Trade Max)" ? (not inL and not inS) : global_sync == "Directional Pyramid (Same Dir Only)" ? (not inL) : true
// V1.5 FIX 5: link Long/Short entries — when one fills, the other is cancelled instantly
oca_t = global_sync == "Independent (Allow Hedge)" ? strategy.oca.none : strategy.oca.cancel
bool is_news_day = str.contains(news_dates, today_str)
bool is_news_blackout = use_news_block and is_news_day and not na(time(timeframe.period, news_time, act_tz))
bool is_eod_window = close_eod and not na(time(timeframe.period, eod_time, act_tz))
if u5
bool limL5 = (not use_max_t_5 or trades5 < max_tot_5) and (not use_max_d_5 or longs5 < max_dir_5)
bool limS5 = (not use_max_t_5 or trades5 < max_tot_5) and (not use_max_d_5 or shorts5 < max_dir_5)
bool trigger_L = box_done and box_cleared and cyc_free and brkL and vol_ok and dltL_ok and in_trade_window and not is_eod_window and not na(h5) and limL5 and ok_global_L and not is_blocked and not is_news_blackout and not daily_loss_hit and not daily_profit_hit and arm5L
bool trigger_S = box_done and box_cleared and cyc_free and brkS and vol_ok and dltS_ok and in_trade_window and not is_eod_window and not na(h5) and limS5 and ok_global_S and not is_blocked and not is_news_blackout and not daily_loss_hit and not daily_profit_hit and arm5S
// the entry fills at this close: its first stop / target are set relative to the fill
if trigger_L
strategy.entry("En_L", strategy.long, qty=trade_qty, comment="L")
strategy.exit("Ex_L", "En_L", loss=math.max(sl_pts / syminfo.mintick, 1), profit=tp_pts / syminfo.mintick, comment_loss="SL", comment_profit="TP")
lock_cyc := cyc
need_prev_brk := true
if trigger_S and not trigger_L
strategy.entry("En_S", strategy.short, qty=trade_qty, comment="S")
strategy.exit("Ex_S", "En_S", loss=math.max(sl_pts / syminfo.mintick, 1), profit=tp_pts / syminfo.mintick, comment_loss="SL", comment_profit="TP")
lock_cyc := cyc
need_prev_brk := true
// Time Stop measured from the fill
if use_time_stop and strategy.opentrades > 0 and not na(entry_clock)
if (now_clock - entry_clock) / 60000 >= time_stop_mins
strategy.close_all(comment="Time Stop")
// ============================================================================
// EXIT ENGINE (FLOWLOCK STYLE) - decided at each 1-minute close
// 1. stop loss 1b. stop steps 2. break-even 3. trailing
// 4. scale-in: stop at least the new average 5. stop lock 6. take profit
// ============================================================================
float pos_sz = strategy.position_size
float avg_px = strategy.position_avg_price
var float x_run_L = na
var float x_run_S = na
var bool x_be = false
var float x_lock_L = na
var float x_lock_S = na
var string x_lrs_L = "SL"
var string x_lrs_S = "SL"
var bool x_scaled = false
if pos_sz == 0
x_run_L := na
x_run_S := na
x_be := false
x_lock_L := na
x_lock_S := na
x_scaled := false
float x_sl_now = na
float x_tp_now = na
bool x_closing = false
if u5 and pos_sz > 0 and avg_px > 0
// every candle seen in the position started after the entry close -> best = candle HIGH
x_run_L := na(x_run_L) ? high : math.max(x_run_L, high)
// 1. base stop
float l_sl = avg_px - sl_pts
string l_rs = "SL"
// 1b. stop steps
if use_steps
if x_run_L >= avg_px + s1_on and avg_px - s1_sl > l_sl
l_sl := avg_px - s1_sl
l_rs := "S1"
if use_s2 and x_run_L >= avg_px + s2_on and avg_px - s2_sl > l_sl
l_sl := avg_px - s2_sl
l_rs := "S2"
// 2. break-even (overrides trailing)
if use_be and x_run_L >= avg_px + be_on
x_be := true
if x_be
if avg_px + 1.0 > l_sl
l_rs := "BE"
l_sl := math.max(l_sl, avg_px + 1.0)
// 3. trailing
if use_trail and not use_be and x_run_L >= avg_px + trail_on
float l_tr = x_run_L - trail_off
if l_tr > l_sl
l_rs := "TRAIL"
l_sl := math.max(l_sl, l_tr)
// 4. scale-in: once the add has filled, the stop is at least the new average
if strategy.opentrades > 1
if avg_px > l_sl
l_rs := "BE"
l_sl := math.max(l_sl, avg_px)
// 5. stop lock: never let the stop move back down
if not na(x_lock_L) and x_lock_L > l_sl
l_sl := x_lock_L
l_rs := x_lrs_L
x_lock_L := l_sl
x_lrs_L := l_rs
// 6. target
float l_tp = avg_px + tp_pts
x_sl_now := l_sl
x_tp_now := l_tp
if close <= l_sl
strategy.close_all(comment=l_rs) // price already through the new stop at this close
x_closing := true
else
strategy.exit("Ex_L", "En_L", stop=l_sl, limit=l_tp, profit=na, loss=na, comment_loss=l_rs, comment_profit="TP")
strategy.exit("Ex_L Add", "En_L_Add", stop=l_sl, limit=l_tp, profit=na, loss=na, comment_loss=l_rs + " ADD", comment_profit="TP ADD")
if u5 and pos_sz < 0 and avg_px > 0
x_run_S := na(x_run_S) ? low : math.min(x_run_S, low)
float s_sl = avg_px + sl_pts
string s_rs = "SL"
if use_steps
if x_run_S <= avg_px - s1_on and avg_px + s1_sl < s_sl
s_sl := avg_px + s1_sl
s_rs := "S1"
if use_s2 and x_run_S <= avg_px - s2_on and avg_px + s2_sl < s_sl
s_sl := avg_px + s2_sl
s_rs := "S2"
if use_be and x_run_S <= avg_px - be_on
x_be := true
if x_be
if avg_px - 1.0 < s_sl
s_rs := "BE"
s_sl := math.min(s_sl, avg_px - 1.0)
if use_trail and not use_be and x_run_S <= avg_px - trail_on
float s_tr = x_run_S + trail_off
if s_tr < s_sl
s_rs := "TRAIL"
s_sl := math.min(s_sl, s_tr)
if strategy.opentrades > 1
if avg_px < s_sl
s_rs := "BE"
s_sl := math.min(s_sl, avg_px)
if not na(x_lock_S) and x_lock_S < s_sl
s_sl := x_lock_S
s_rs := x_lrs_S
x_lock_S := s_sl
x_lrs_S := s_rs
float s_tp = avg_px - tp_pts
x_sl_now := s_sl
x_tp_now := s_tp
if close >= s_sl
strategy.close_all(comment=s_rs)
x_closing := true
else
strategy.exit("Ex_S", "En_S", stop=s_sl, limit=s_tp, profit=na, loss=na, comment_loss=s_rs, comment_profit="TP")
strategy.exit("Ex_S Add", "En_S_Add", stop=s_sl, limit=s_tp, profit=na, loss=na, comment_loss=s_rs + " ADD", comment_profit="TP ADD")
// ---- scale-in (add to winner): once, at a 1-minute close this many points in profit ----
if u5 and scale_on and not x_scaled and not x_closing and strategy.opentrades == 1 and not is_eod_window and not is_blocked and not daily_loss_hit and not daily_profit_hit
if pos_sz > 0 and close >= avg_px + scale_pts
strategy.entry("En_L_Add", strategy.long, qty=scale_qty, comment="L ADD")
strategy.exit("Ex_L Add", "En_L_Add", stop=x_sl_now, limit=x_tp_now, profit=na, loss=na, comment_loss=x_lrs_L + " ADD", comment_profit="TP ADD")
x_scaled := true
else if pos_sz < 0 and close <= avg_px - scale_pts
strategy.entry("En_S_Add", strategy.short, qty=scale_qty, comment="S ADD")
strategy.exit("Ex_S Add", "En_S_Add", stop=x_sl_now, limit=x_tp_now, profit=na, loss=na, comment_loss=x_lrs_S + " ADD", comment_profit="TP ADD")
x_scaled := true
if is_eod_window
strategy.close_all(comment="EOD Flat")
plot(u5 and show_lvls and box_done ? lvlL : na, "Long Level", color.new(#2962ff, 30), 1, plot.style_stepline)
plot(u5 and show_lvls and box_done ? lvlS : na, "Short Level", color.new(#ff6d00, 30), 1, plot.style_stepline)
plot(u5 and na(in5) ? h5 : na, "RB High", color.new(#1e6e09, 12), 1, plot.style_linebr)
plot(u5 and na(in5) ? l5 : na, "RB Low", color.new(#e00707, 23), 1, plot.style_linebr)
plot(u5 and pos_sz != 0 ? x_sl_now : na, "Stop", color.new(color.red, 0), 1, plot.style_linebr)
plot(u5 and pos_sz != 0 ? x_tp_now : na, "Target", color.new(color.green, 0), 1, plot.style_linebr)