Article contents
- Evidence and scope
- Illustration
- Process
- A rolling boundary is not a confirmed swing
- Create the reference before classifying the event
- One boundary can produce different valid outcomes
- Order timing, invalidation and expiration
- Volume can select stronger moves and more expensive fills
- Test the reference calculation before the strategy
- Common pitfalls
- Practical checklist
- Frequently asked questions
- Research sources
Evidence and scope
The sources support channel formulas, data shifting and simulated order timing. No historical trend-following claim is treated as evidence that the particular entry, volume threshold and exit proposed here are profitable.
Practical workflow
- Collect N barsUse completed observations preceding the current bar.
- Freeze U and DStore prices and the age of each extreme.
- Classify the eventA closing breakout differs from an excursion and reclaim.
- Apply volumeUse only features available when the order is submitted.
- Simulate executionApply the registered entry, stop and expiration policy.
A rolling boundary is not a confirmed swing
Donchian takes the extremes of N observations; TradingView describes upper and lower bands and their midpoint [1]. Unlike a two-sided pivot, it does not require a subsequent reversal. The completed prior window is already known when the next bar begins. During a trend, its upper boundary can keep rising without functioning as resistance that holds.
The proposed causal definition is U[t]=max(H[t−N:t]), D[t]=min(L[t−N:t]), M[t]=(U[t]+D[t])/2, with the upper endpoint of the slice excluded. Thus the window ends at t−1. If H[t] is included in U[t], the condition H[t]>U[t] becomes impossible by construction.
This simple distinction affects the entire experiment. A charting indicator may display a band including the active bar for visual purposes; the strategy must still specify which historical snapshot it uses. Store the underlying extreme's timestamp as well as its price so later diagnostics can distinguish fresh boundaries from old extremes about to expire.
Create the reference before classifying the event
In pandas, shifting values separates the reference window from the row being evaluated [2]. One implementation is high.shift(1).rolling(N).max(). Shifting an index with freq is not a substitute for moving the observed values relative to the decision row. Require a full valid window instead of silently allowing a changing number of observations.
The baseline classifies a completed close beyond a band with b=max(2 ticks,0.1×ATR[t−1]); N=20 and 0.1 are proposed research settings. For immediate one-bar classifications, calculate a new prior-window reference each bar. For a multi-bar sweep and reclaim candidate, freeze the original level when the candidate starts.
Otherwise, the excursion bar enters the next rolling window and moves the boundary being reclaimed. Returning below an updated boundary can be a different event from returning below the level actually breached. Keep candidate_id, frozen_level, reference timestamp and expiry so the intended question remains stable throughout the setup.
U = max(H[t-N:t]); D = min(L[t-N:t])
b = max(2*tick, 0.1*ATR[t-1])
if no_active_setup and C[t] > U+b:
emit('up_breakout', signal_at=t, frozen_level=U)
if no_active_setup and H[t] > U+b and C[t] < U:
emit('upper_reclaim', signal_at=t, frozen_level=U)
# These labels represent different hypotheses.
# A close-confirmed order can be processed only after close t.
One boundary can produce different valid outcomes
Synthetic example: the previous 20 bars have U=105, D=99 and ATR=1. With tick=0.01, b=0.10. A current bar with H=106 and C=105.4 creates an upward close breakout. A proposed next-open purchase at 105.5, stop at 103.9 and target at 108.7 has 1.6 points of initial price risk and a 2R target before costs.
Failure path: after opening at 105.5, price falls to 103.8. The stop can be reached even though the triggering close met every detector condition. If instead the original trigger bar had H=106 and C=104.7, it would not be a close breakout. It could be an upper reclaim for a separately specified short strategy. Do not relabel a losing breakout as a sweep after seeing the loss.
A subtler case occurs when the old high of 105 leaves the N-bar window and U falls to 104. Price at 104.5 can now exceed the channel without making a new recent traded high. That is a legitimate rolling-window event. Excluding it requires an additional registered condition on the origin or movement of the reference level.
Test equality deliberately. A close exactly at U+b is rejected by the strict greater-than condition in this baseline. Tick rounding should occur under a fixed convention before order submission; otherwise floating-point noise can decide whether an observation lies just above or exactly on a boundary.
Order timing, invalidation and expiration
TradingView distinguishes order creation after a close from a fill at the next available tick in its emulator [3]. The proposed close-confirmed baseline therefore needs a subsequent executable price, spread and slippage. A buy-stop resting above U is a different model: it may fill intrabar and reverse before the close. An unfavorable close cannot retroactively erase that fill.
Exit choices include a fixed structural stop, a shorter lower-channel trail or a time exit. Select a simple configuration before evaluation. For a retest entry, define how far price may return, which reaction qualifies and how many bars the order remains valid. A breakout that never retests is a recorded missed opportunity, not an automatic switch to chasing price.
A bar touching both stop and target needs finer data or a declared conservative ordering convention. Gap tests should alter the realized fill and risk without changing the original signal timestamp or frozen reference. An execution rejection before submission and a losing filled order are different outcomes.
A rolling trailing stop also needs a timing rule. If yesterday's lower band updates after today's close, the new stop cannot protect earlier intrabar movement. Save every stop revision and its activation time rather than applying the final trail backward across the bar.
Volume can select stronger moves and more expensive fills
A proposed breakout filter requires RVOL≥1.5 against comparable session-time history. At a completed-close decision, the trigger bar's full volume is available. For a resting stop submitted earlier, only volume already observed at submission can determine whether the order exists. Full-bar volume measured after its fill cannot become a retrospective entry permission.
Separate a price-only branch, a minimum-liquidity branch and an abnormal-volume branch. These answer different questions: basic tradability versus incremental information. A high-RVOL subset may move farther while also experiencing larger gaps and spreads, so gross price response is insufficient.
Compare net expectancy, exposure and the number of discarded opportunities. Match risk budgets across branches and report results by liquidity or time of day using group definitions established on past data. A higher win rate on a small subset does not automatically improve the portfolio's return or drawdown.
For multi-bar reclaims, store excursion volume and reclaim volume separately. Their ratio can be studied, but unequal interval lengths need normalization. Aggregate OHLCV cannot determine whether the activity occurred precisely at the Donchian level or elsewhere inside a wide bar.
Test the reference calculation before the strategy
Register a small development grid such as N=10,20,40. Log band prices, extreme timestamps and level age at every signal, including whether the level moved because an old extreme expired. This separates economic behavior from mechanical window effects and makes sensitivity easier to interpret.
A direct causality test changes H[t] while holding the prefix fixed: U[t] must remain unchanged. Changing H[t−1] may change U[t]. Add missing-bar, holiday, opening-gap and stale-data fixtures. Compare batch calculations with a streaming implementation so off-by-one errors cannot hide inside a visually plausible chart.
Only then evaluate a locked out-of-sample period with turnover, fees, exposure, drawdown and fill sensitivity. If selecting special news, opening or closing-session subsets, count those as research trials. Report failed candidates and retests that never happened, not merely completed trades from favorable boundaries.
Common pitfalls
Letting the level chase the excursion
A reclaim against a newly updated band can differ from reclaiming the original breached boundary.
Confusing a touch with a crossing
Equality at U is not automatically a breakout; fix tick rounding and comparison rules.
Short windows hide their turnover cost
A smaller N can create frequent signals whose execution costs dominate their gross edge.
Checklist before using this method
Check each item after verifying it on your data. Progress is saved in this browser; it does not certify a profitable strategy.
Frequently asked questions
Should an upper-band touch be sold?
There is no general conclusion. Fading the boundary and buying a breakout are opposing hypotheses requiring separate definitions and tests.
Can Donchian replace pivots?
It can supply a breakout reference, but it does not provide the right-side reversal confirmation or swing ordering of a pivot detector.
Research sources
Each source supports the definition or evidence described beside it. The pseudocode, synthetic examples and proposed parameters require separate validation.
- Donchian ChannelsTradingView. Read channel formulas and descriptive uses. Checked: .
- pandas.Series.shiftpandas. Read the API to verify value shifting. Checked: .
- Pine Script: StrategiesTradingView. Read order creation, next-available-tick and stop-order behavior. Checked: .
Related methods
Risk note
This content supports education and research design, not financial advice. Backtest is historical simulation, does not guarantee future performance and does not place real trades. Methods in this library are not automatically features available in the app. See methodology and learning center.
Validate rules before risking real capital
Check app support, data and individual simulated trades; advanced detectors may require a separate implementation.
Download Backtest on the App Store