Intermediate Trading Tutorial | thinkScript | Stock Hacker

An inside bar describes a candle whose high and low remain within the preceding candle. It can help identify a temporary contraction in price activity, but a geometric inside bar alone says little about whether the contraction is meaningful. A large mother candle may contain a second candle that is still unusually wide compared with the instrument's recent history. This tutorial builds a scanner that demands both strict containment and a measured reduction in range, using only completed candles. The result is a reproducible watchlist filter, not a prediction of the direction of the next move.

Two tests, two different jobs

The first test compares the last completed candle with the candle immediately before it. Both boundaries must be strictly inside: the candidate high must be lower than the mother's high, and the candidate low must be higher than the mother's low. Equal highs or equal lows fail by design. This convention is deliberately more restrictive than definitions that allow equal boundaries.

The second test calculates the candidate's high minus low, divided by the arithmetic mean of the preceding 20 high-minus-low ranges, then multiplied by 100. The baseline includes the mother candle but excludes the candidate and the currently developing candle. With the default limit of 60%, a valid candidate must have a range no greater than 60% of that prior average. The two tests measure different properties: containment is local geometry, while the percentage is relative compression. Neither substitutes for the other.

A numerical example

Imagine the mother candle has a high of 104 and low of 98, giving it a range of 6. The next completed candle reaches 102 and 100, giving it a range of 2. Assume the sum of the 20 preceding ranges, including the mother's 6, is 80. The baseline is 80 / 20 = 4 and the candidate percentage is 100 × 2 / 4 = 50%. Both containment and the 60% threshold are satisfied.

Build a Confirmed Inside Bar Compression Scanner with thinkScript
Figure 1. Hypothetical candles: strict containment plus a range of 2.0 against a prior mean of 4.0 gives 50%, which passes the 60% ceiling.

Now change the candidate high to 103 and low to 100. The candle remains strictly inside, but its range is 3 and the percentage is 75%. The scanner rejects it. Conversely, a narrow candle with a high of 105 and low of 104 has a 25% ratio but violates containment. That candle fails too. These examples make useful unit tests because each isolates a different part of the Boolean expression.

Complete thinkScript for Stock Hacker

# PatternSmart: confirmed inside-bar compression scanner
# Use a single aggregation in Stock Hacker.
input averageLength = 20;
input maxRangePercent = 60.0;

# Compare the last completed bar to its mother bar.
def candidateRange = high[1] - low[1];
def motherRange = high[2] - low[2];
def baseline = Average(high[2] - low[2], averageLength);

# Exclude missing or non-positive ranges and invalid thresholds.
def ready = !IsNaN(high[1]) and !IsNaN(low[1])
    and !IsNaN(high[2]) and !IsNaN(low[2])
    and !IsNaN(baseline) and baseline > 0
    and candidateRange > 0 and motherRange > 0
    and maxRangePercent > 0 and maxRangePercent <= 100;

# Strict containment: equal boundaries are not accepted.
def inside = high[1] < high[2] and low[1] > low[2];
def ratio = if baseline > 0
    then 100 * candidateRange / baseline
    else Double.NaN;

# Exactly one Boolean plot for Stock Hacker.
plot scan = ready and inside and ratio <= maxRangePercent;

In thinkScript, index [0] refers to the current bar, [1] to the previous bar, and [2] to the bar before that. The expression Average(high[2] – low[2], averageLength) therefore averages the ranges at offsets 2 through 21 with the default length. Using Average(high – low, averageLength) would mix the live bar and candidate into the reference series, which is not the intended rule. The only plot is a Boolean scan condition, as required for a standard custom Stock Hacker study. Set averageLength to a positive integer before applying the filter.

Install and configure

  1. Open the desktop thinkorswim Scan tab and select Stock Hacker.
  2. Choose the universe you want to evaluate, such as a personal watchlist of liquid stocks.
  3. Add a Study filter, choose Custom and switch to the thinkScript editor. Replace the existing expression with the complete source.
  4. Select the aggregation period for this filter. Start with daily or 30-minute bars. Decide whether to include extended-hours data on intraday scans.
  5. Save the filter, run Scan, and open several returned charts with the same aggregation and session settings.

The scanner evaluates the previous completed bar. On a daily aggregation, the result normally refers to the prior bar while a new daily bar is present. On an intraday aggregation, a qualifying candle becomes the candidate once the following bar exists. A quiet symbol may not immediately have a new bar, and the scanner's own update frequency can add further delay. This is an intentional confirmation cost, not a promise of instant alerts.

Parameter decisions and tradeoffs

Parameter Default Effect
averageLength 20 Short windows respond rapidly but are more sensitive to unusual candles; longer windows smooth the reference but adapt slowly.
maxRangePercent 60 A lower ceiling selects stronger compression and fewer candidates. Higher values broaden coverage.
Boundary comparison Strict Excludes equal highs and lows. A relaxed comparison would change the definition and should be evaluated separately.

A 20-bar average on a five-minute chart covers a very different period from 20 daily bars. Do not transfer thresholds across aggregations without checking the resulting distributions. A large mother candle also raises the prior average; this is consistent with the stated calculation but can make the compression test easier to pass after a volatility shock. If you want to measure compression against pre-mother conditions, that is a separate version with an offset of 3 and a different example.

Handling edge cases without future data

The readiness condition checks missing prices, a nonpositive baseline and zero-width candles. A flat bar may be a valid data observation, but treating it as meaningful compression can generate false positives in illiquid instruments. The script intentionally excludes it. A valid positive baseline is required before division, so a completely flat reference window cannot generate a result. The percentage input must be above zero and at most 100; values beyond this range are rejected by the readiness test. Invalid average lengths should be corrected in the editor rather than used as scan inputs.

The script uses no future offsets or secondary aggregation. It does not read the live candle's high or low, so ordinary intrabar movement of that candle cannot change the previously evaluated test. Historical corrections, session setting changes, or a different data feed may still alter results. Also, once a new bar begins, the previous bar changes identity; a qualifying symbol may disappear from the scan even if its older inside bar remains visible on the chart. That is expected for an event filter.

Validation before relying on results

  • Confirm the candidate and mother are offsets 1 and 2, not 0 and 1.
  • Manually add the 20 reference ranges for a small test sample and divide by 20.
  • Test an exact 60% case: the inclusive percentage comparison should pass if the strict boundaries also pass.
  • Test equal highs, equal lows, a range ratio of 75%, and zero-width candles: each should fail for the applicable reason.
  • Compare results with the same chart timeframe and extended-hours settings.
  • Observe results during the next bar and after the subsequent bar arrives to confirm the intended timing.

The syntax and filter restrictions were reviewed against the official thinkScript Stock Hacker Study Filters and Average documentation. The code has not been compiled or live-tested in the platform for this article. Validate it in the editor and a non-live workflow before incorporating it into your routine.

What this scanner cannot tell you

Compression does not guarantee expansion, a profitable breakout, or a favorable execution price. The scan does not consider news, volume, spread, overnight gaps, support and resistance, or direction. Its high-minus-low range is not true range and does not measure gaps between candles. A user may combine the output with independent liquidity and trend filters, but should evaluate any additional conditions separately. This tutorial provides educational code, not investment advice or a recommendation to trade. Trading can result in losses, and historical patterns do not guarantee future performance.

If this free scanner is useful and you would like a custom watchlist column, a different containment definition or additional conditions, contact us through our Custom Trading Software Development Services.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.