TradingView strategy research

Range trading strategy: boundaries, entries and breakout failure

A range trading strategy buys near a defined lower boundary or sells near an upper boundary, expecting price to return toward the middle or opposite side. The testable part is deciding those boundaries before entry, specifying a rejection signal, and exiting when the range fails. A sideways-looking chart alone is insufficient: a rolling window always has a high and low, even during a trend.

See the decision guide

What counts as a range?

Support and resistance describe areas where falling or rising prices have previously stalled. Fidelity explains that a broken level can change role. That possibility is the main failure condition for fading a boundary. A range strategy tests continued containment; a breakout strategy tests escape from it. Neither outcome is established by drawing two horizontal lines.

  • A channel indicator can supply reference levels. TradingView defines Donchian boundaries from the highest high and lowest low over a chosen period, with their average as the midpoint.
  • The protocol below adds qualification, expiry and execution rules. These are illustrative research choices, not the Donchian indicator definition or recommended settings.
  • Range trading is one form of a return-to-level hypothesis. Other mean-reversion strategies use moving averages, spreads or statistical deviations without a fixed horizontal box.

Qualify a rolling window without hindsight

Use standard candles on one fixed symbol, session and timeframe. At each close t, while flat and without an active candidate, inspect exactly the preceding 20 completed bars, t-20 through t-1. Exclude bar t from the reference window. Require complete OHLC data. The following deliberately simple screen identifies candidates; it does not prove that the next bounce will occur.

  • Equality passes the stated thresholds. Each side has its own visit counter; a wide bar may visit both sides. The screen can therefore admit noisy ranges and must be evaluated as written.
  • Twenty bars means twenty bars of the chosen chart, not twenty days on every timeframe. Record session and adjustment settings with the test.
  • A fresh candidate is calculated from the then-current preceding window. Do not choose the start and end of the box after seeing which boundaries produced winning trades.
DecisionFixed rule for this example
Reference levelsH is the highest high and L the lowest low in the 20-bar window. Width W = H - L; midpoint M = (H + L) / 2.
Minimum widthRequire W to be at least 20 minimum ticks. Reject zero-width windows. Separately account for costs; 20 ticks is not a profitability threshold.
Lower visitsA low at or below L + 0.10W counts as a lower-zone visit. Require at least two visits.
Upper visitsA high at or above H - 0.10W counts as an upper-zone visit. Require at least two visits.
Visit separationFor each side independently, scan oldest to newest. Accept the first visit, then accept the next only if its bar index is at least three greater than the last accepted visit.
Displacement checkRequire the absolute difference between the newest and oldest window closes to be no more than 0.25W.
Activation closeRequire bar t high to be at most H and its low to be at least L. Freeze H, L and W after t closes. The earliest entry signal is on t+1.

Freeze the box until it expires or fails

Once a candidate is active, do not slide its boundaries with each new candle. The rolling calculation is used to discover the next candidate; the active box remains fixed. This separates a changing observation window from the prices against which an actual trade is judged.

  • Retire a traded box at the close of the bar on which the exit is observed. For an invalidated box with an open position, begin the waiting period only after that position closes.
  • If a candidate was merely unused and expired, the next rolling window may overlap it. That is permitted by this protocol and must remain consistent across tests.
  • Changing the frozen low after a downside break would change the question being tested and can conceal the original failure.
State or eventRequired action
Active and flatInspect t+1 through t+10 for an entry signal. Ignore other candidate windows while this box is active.
Close strictly below L or above HInvalidate the box before evaluating any new entry. If a position remains open, request a market exit at that close while leaving its protective stop active until the position closes.
Wick outside the box, close insideKeep the box active. A long entry still fails if its signal low is below L. An existing stop order may already have executed during that wick.
No entry by the close of t+10Expire the box after evaluating that final eligible bar. Resume scanning on the next bar.
Entry pending or position openIgnore new entry signals. A box permits only one trade; its entry-window expiry does not move the open trade stop or target.
Trade closed or box invalidatedRetire this box. Resume scanning at the close of the 21st bar after retirement; its reference window contains 20 complete bars strictly after retirement.

A complete long-side rejection rule

This baseline trades only the lower boundary. Shorting the upper boundary is a separate variant with reversed comparisons and its own borrow, margin and cost assumptions. Defining one direction fully makes the entry and failure cases easier to inspect.

  • Cancel residual orders once flat. If entry gaps beyond the target or stop, record the actual fill and close at the first executable opportunity; do not remove the trade or assume the signal-close price was available.
  • A resting stop is distinct from a close-based range failure. The stop can fill before the closing decision, while a gap or delayed market exit can produce a larger loss than the planned distance.
  • This rule waits for a close back above the lower zone. Buying the first touch with a limit order is a different strategy and needs a separate test.
ComponentLong-only baseline
Closing confirmationOn an eligible bar, require L ≤ low ≤ L + 0.10W, close > L + 0.10W, and close < the target. The box must still be valid at that close.
EntrySubmit a market buy after the signal close. Under default TradingView strategy timing, the earliest fill is the next available tick, normally the next bar open in a historical bar-close test.
Stop and targetStop = L - 0.10W, rounded down to the minimum tick. Limit target = M, also rounded down to the minimum tick. Submit protective exit orders with the entry; keep both prices fixed.
Time exitCount the fill bar as bar one. If still open at the close of bar ten, request a market exit. A range-invalidating close can request an earlier exit.
QuantityUse 100 shares in the arithmetic example with sufficient simulated capital. No pyramiding or averaging down. Other instruments require their own lot size, point value and margin model.

Worked example: bounce profit versus breakout loss

These fictional dollar prices are arithmetic, not historical trades. Assume the window qualifies with L = 100, H = 110, W = 10 and a 0.01 tick. The lower zone ends at 101, the target is 105 and the stop is 99. An eligible signal bar has low 100.50 and close 101.10. Assume 100 shares fill at 101.20, with commission of 0.10 per share on each side.

  • The outcomes are alternatives, not an observed sequence. The 0.30 adverse difference in the gap branch is already in the exit fill; do not deduct it twice. These calculations include the stated commissions only, with no additional spread or financing charge.
  • With only exact-target and exact-stop outcomes, break-even win rate is 2.40 / (3.60 + 2.40) = 40%. Replacing every stop loss with the illustrated gap loss raises it to 2.70 / (3.60 + 2.70), about 42.9%. Neither is an estimated success rate.
  • If the confirmation close is already at 105, skip the entry: the midpoint reward is gone. If the signal low is 99.80, skip it even if the candle recovers; this baseline does not trade a sweep below support.
  • A narrower box can leave little reward after costs. Calculate target distance from the executable entry, not from L, and test the actual fee schedule and fill assumptions.
Alternative outcomePer-share arithmeticNet for 100 shares
Target fills at 105105 - 101.20 - 0.20 commission = +3.60+$360
Stop fills exactly at 9999 - 101.20 - 0.20 = -2.40-$240
Breakout gaps through stop; fill is 98.7098.70 - 101.20 - 0.20 = -2.70-$270
Four target wins and six gap losses4 × $360 - 6 × $270-$180 across ten hypothetical trades

Audit the losses that a tidy chart can hide

TradingView strategy results depend on simulated fills. Use standard candles and inspect bars that reach both exits with the available lower-timeframe detail. A fixed slippage setting is a scenario, not a precise forecast of live execution. Keep a record of failed boxes as well as completed trades.

  • The midpoint target trades less distance for an earlier exit than the opposite boundary. Compare the alternatives with identical entries and costs; do not assume either has better expectancy.
  • The screen may accept a pause within a trend or miss a discretionary range. Keep that limitation visible instead of manually deleting unattractive candidates after the test.
RecordWhat to compare
Candidate logActivation timestamp, frozen levels, visits, displacement, expiry or failure reason, and whether a trade occurred.
Trade logSignal timestamp, order activation, actual fill, fixed exits, costs, and exit reason: target, stop, invalidation or time.
Development and later evaluationFreeze lookback, zone width, visit separation and holding limit before running the reserved later dates. Preserve rejected parameter choices.
Cost sensitivityCompare a stated base-cost case with a higher-cost case. Report net average trade, drawdown and trade count alongside win rate.
Breakout dependenceCompare ordinary stop losses with gap losses and invalidation exits. Report how much of the total loss comes from these failed boxes.

Turn the rulebook into a Pine Script draft

Give Pine Script AI Coding Agent the window definition, visit-counting rule, frozen-box lifecycle, confirmation conditions and exit table. Ask for plotted frozen levels and separate candidate, signal and fill markers. Review the generated source and request a syntax check before comparing its behavior with the example.

  • Check a passing lower-zone rejection, a close beyond the box, an expired candidate, a wick through the stop, and an entry gap. A script that compiles can still implement the wrong timing.
  • Run the reviewed strategy in TradingView and save the full settings and results. Pineify can help write and revise the code; this page supplies no preset, live execution service or verified return estimate.
Where Pineify fits

Pine Script AI Coding Agent

Draft the frozen-range rules in Pine Script, then review the state transitions, request syntax validation and test the strategy in TradingView.

Draft my range strategy

Frequently asked questions

Educational strategy research, not investment advice. The rules and prices are hypothetical and have not been performance-tested. Backtests do not guarantee future results, and trading losses can exceed a planned stop distance.

Sources and verification

Published by Pineify. Pineify is an independent product and is not affiliated with TradingView. Sources support the technical explanations; examples do not establish trading performance.