Intermediate Trading Tutorial — Confirmed Compression-to-Expansion Scan in Thinkorswim
Volatility is not constant. A narrow candle followed by a broad candle can mark a change in the scale of price movement, but an absolute range threshold is difficult to apply across symbols with different price levels. This tutorial develops a thinkScript Stock Hacker filter that identifies a completed narrow setup candle followed immediately by a completed expansion candle, using one shared historical baseline. The scanner identifies a descriptive two-bar event rather than forecasting a breakout or recommending a trade. Its central design choice is to freeze the reference before either event candle enters the calculation.
Define compression and expansion
Define range as high minus low. Let N be a positive integer specifying the number of reference candles, and let R be their arithmetic mean range. The setup candle must have a range no greater than a compression multiplier times R. The immediately following signal candle must have a range no smaller than an expansion multiplier times R. The default multipliers are 0.6 and 1.5. Both comparisons use the same R, computed entirely before the setup candle. Consequently a very narrow setup cannot reduce the expansion threshold, and the expansion candle cannot inflate its own threshold.
This is not a Bollinger Band squeeze or a true range measure. It describes the relative sizes of two adjacent candle ranges, without incorporating interbar gaps, closing direction, or traded volume. A broad candle may close near its midpoint or reverse an earlier move. The scanner deliberately does not distinguish these possibilities. That separation makes the volatility event easier to test before introducing additional filters.

Worked examples
Set length to three. Suppose the three baseline ranges are four, four and four price units. The next candle has high 102 and low 100, producing a range of two. The following candle has high 106 and low 99, producing a range of seven. The compression limit is 0.6 × 4 = 2.4. The expansion requirement is 1.5 × 4 = 6. The setup qualifies because two is no greater than 2.4, and the signal qualifies because seven is no smaller than six. Once both candles are completed, the scan returns true.
If the signal range were five instead, its ratio would be 1.25 and the scan would return false. If the setup range were three while the signal remained seven, the setup ratio would be 0.75 and the scan would again return false. These are independent hypothetical comparisons against the same baseline. Exact equality at either threshold is accepted. A zero reference mean is rejected rather than interpreted as a valid expansion. These rules make the treatment of boundaries explicit.
Complete Stock Hacker thinkScript source
# PatternSmart: confirmed compression-to-expansion scan
input length = 20;
input compressionRatio = 0.6;
input expansionRatio = 1.5;
# [1] is the latest completed bar; [2] is the setup.
def barRange = high - low;
# Freeze the baseline before BOTH event bars.
def reference = Average(barRange, length)[3];
def setupRange = barRange[2];
def signalRange = barRange[1];
def ready = !IsNaN(reference) and
!IsNaN(setupRange) and !IsNaN(signalRange) and
reference > 0 and setupRange >= 0 and signalRange >= 0;
def validSettings = compressionRatio > 0 and
compressionRatio < 1 and expansionRatio > 1;
# Stock Hacker requires exactly one Boolean plot.
plot scan = if ready and validSettings then
setupRange <= compressionRatio * reference and
signalRange >= expansionRatio * reference
else no;
Understanding historical offsets
In thinkScript, the unshifted high and low refer to the current aggregation bar. During a live session this bar may still be forming. The expression barRange[1] reads the preceding bar, while barRange[2] reads the bar immediately before it. The setup and signal are therefore separated from the active candle. Average(barRange, length)[3] reads the moving average as of three bars ago, covering the reference candles before the setup. With length three, these are offsets three, four and five. The event candles at offsets two and one never participate in that mean.
The reference is recomputed for each evaluation bar, not stored indefinitely. When the next aggregation bar appears, the entire five-bar structure in the worked example advances. The scan no longer necessarily matches the previously identified event because the two designated event offsets have changed. That is expected behavior for an event scanner rather than a persistent watchlist state. The reference uses a simple average, and an exceptionally large earlier candle can raise both thresholds. Users interested in robust estimates may investigate other reference definitions separately.
The ready expression checks that the required values are available and that the baseline is positive. The settings expression rejects compression multipliers outside the intended interval and expansion multipliers no greater than one. The length input should always be a positive integer; invalid lengths can generate an editor error before logical guards are evaluated. The script contains exactly one Boolean plot, named scan. Intermediate quantities are definitions rather than additional plots, which is important for a custom Stock Hacker study filter.
Installation in Stock Hacker
Open the Scan tab in Thinkorswim and select Stock Hacker. Choose a suitable symbol universe and add a Study filter. Select the custom study editor and switch to its thinkScript editing interface. Replace the existing expression with the complete source above. Choose the desired aggregation period in the study filter and apply the scan. Keep the length and multipliers consistent when comparing scan results with independent chart calculations. The example requires no secondary aggregation or external symbol lookup. The code has not been compiled or executed in Thinkorswim here; verify editor acceptance and behavior in your installed environment.
Closed-bar behavior and repainting
The active candle contributes neither to the event nor to its reference. In normal live operation, the result for the last completed two-bar pattern does not change simply because the current candle's high or low changes. When a new candle appears, the previously active bar becomes eligible and the result may change. A daily aggregation may therefore report the previous completed session's event during the current session. Around a market closure the latest candle can remain at offset zero until the next bar is recognized. Scanner refresh cadence can also delay when a new match becomes visible. No future price is referenced, but historical data corrections and session changes can alter the input history.
Testing and limitations
Build a spreadsheet containing consecutive highs and lows, compute the prior average, and compare the two threshold conditions independently. Test the worked example, both failure cases, equality at thresholds, a flat baseline and insufficient history. Use the same aggregation and extended-hours settings in the scan and chart. Compare results before and after the current candle completes. A high expansion ratio may reflect news, a thinly traded instrument or a data anomaly; it does not establish directional conviction. Range normalization does not eliminate spread, liquidity or gap risk. Test downstream hypotheses on independent data and account for realistic transaction costs. Avoid selecting thresholds solely because they performed well on a small historical sample.
For directional extensions, configurable persistence conditions or custom watchlist versions, contact our Custom Thinkorswim indicator Development Services.
Risk disclosure: educational material only. Trading involves risk of loss; hypothetical examples do not establish profitability.