Book: Gap Trading to Profit in 7 Days
Author: Peter L. McGrew
Difficulty: Intermediate
The Big Idea
A price gap is an observation. Turning it into a trading decision requires a definition, a hypothesis, an execution plan, and evidence. This workbook helps you work through the book’s four chapters while building those skills. Keep your copy beside you: reading assignments refer to the supplied 129-page PDF, counting its contents page as page 1. Pagination in other editions may differ.
The explanations, fictional market examples, exercises, answer keys, worksheets, and experimental code below are original CandleChasers teaching material. The seven sessions are a study schedule, not a timetable for becoming profitable. Take longer wherever the calculations or chart work need practice.
If you remember only one thing: define a setup before seeing its outcome, and evaluate the trade you could actually execute.
Quick Study Guide: Gap Trading at a Glance
Use this revision sheet after working through the lessons, or to find the explanation you need. These are the workbook’s working definitions; a gap label alone does not establish a profitable trade.
Know Which Gap You Are Measuring
| Concept | Working definition | Review |
|---|---|---|
| Opening gap | Today’s open differs from the previous session’s close. | Gap definitions and examples |
| Outside opening | The open is above the previous high or below the previous low. | Compare the price boundaries |
| Separated daily ranges | Today’s low exceeds yesterday’s high, or today’s high is below yesterday’s low. The completed daily range is known only after the session ends. | Avoid look-ahead |
| Full opening-gap fill | Price reaches the previous close within your specified observation window. | Define the fill reference |
| Candidate gap type | A provisional interpretation based on information available at the decision time. Preserve it when later prices disagree. | Classify without hindsight |
Keep These Calculations Handy
| Calculation | Formula |
|---|---|
| Signed opening gap | 100 × (current open − previous close) ÷ previous close |
| Initial price risk per share | Absolute difference between actual entry and initial stop |
| Simplified whole-share quantity | Round down: (cash risk budget − fixed estimated costs) ÷ (planned entry-to-stop distance + estimated variable round-trip cost per share). Require a positive numerator and denominator, then apply the exposure cap. |
| Price reward/risk | Entry-to-target distance ÷ entry-to-stop distance, with the target in the favorable direction |
| Realized net R | Actual net profit or loss ÷ frozen initial cash price-risk |
| Sample mean net R | Sum of all realized net R outcomes ÷ number of closed trades |
For example, a $50 previous close and $52 open give a +4% opening gap. A long filled at $52.20 with a $51.70 initial stop has $0.50 of price risk per share; a 2R price target is $53.20 before costs. These are hypothetical calculations. The quantity formula uses a planned entry, so worse fills can exceed the budget. Review sizing, costs, and execution stress tests before applying it.
Six Mistakes to Catch Before You Continue
- Calling every upward opening a gap between completed daily ranges.
- Using the day’s final low, volume, or later reversal to justify an earlier decision.
- Assuming every gap must fill, or that a fill automatically creates a profitable trade.
- Calculating reward/risk from the signal price while ignoring the actual fill.
- Treating a stop as a guaranteed maximum loss, or position exposure as cash risk.
- Judging a method by its win rate or best example while excluding costs and failed setups.
Before each paper trade: name the setup, write the trigger and order timing, define invalidation and exits, calculate quantity and exposure, and record what was known before entry. Then assess rule-following separately from profit or loss.
Choose your next step: write a complete setup, inspect the research experiment, use the worksheets, or complete the capstone. A strategy claim needs evidence beyond memorizing this sheet.
Seven Sessions, Seven Concrete Outputs
Read first, attempt the exercise with the answers closed, then compare your reasoning with the key. Use historical replay or paper observations for practical work. Do not treat completing an exercise as evidence that a strategy works.
| Session | Reading | Output |
|---|---|---|
| 1 | Introduction and Chapter 1, PDF pp. 2–35 | Gap calculations and a definition sheet |
| 2 | Chapter 2, pp. 36–63 | Five observations labeled before outcomes |
| 3 | Chapter 3, pp. 64–83 | A comparison of continuation and fade hypotheses |
| 4 | Chapter 3, pp. 84–104 | One complete setup specification |
| 5 | Chapter 4, pp. 105–116 | Position-size and execution stress tests |
| 6 | Chapter 4, pp. 117–129 | A journal review and a frozen research protocol |
| 7 | Revisit passages relevant to your experiment | A research report with limitations and next questions |
Chapter 1 Companion: Identify and Measure the Gap
Read: Chapter 1, pp. 6–35. Demonstrate: distinguish an opening jump from a gap between completed trading ranges, calculate the opening percentage, and choose a fill reference.
Two comparisons that should not share an undefined label
The chapter introduces gaps through changes between trading periods and visual spaces on charts. Those descriptions can refer to different measurements. An opening gap compares today’s open with the previous close. A gap between completed daily ranges compares today’s low with yesterday’s high, or today’s high with yesterday’s low.
| Measurement | Gap up | Gap down | When known |
|---|---|---|---|
| Opening gap | Open > previous close | Open < previous close | At the opening print |
| Opening outside the previous range | Open > previous high | Open < previous low | At the opening print |
| Non-overlapping completed daily ranges | Low > previous high | High < previous low | After the session ends |
An outside opening can later trade back into the prior range. You cannot know at 9:30 whether the entire completed daily candle will remain separated. A backtest that uses today’s final low to select an opening trade uses information from the future.
Opening gap % = 100 × (current open − previous close) ÷ previous close. The sign gives direction. Use the absolute value only when intentionally studying magnitude without direction.
Worked example: opening gap, overlapping ranges
Fictional Alder Labs closed at $40. Its previous high was $41 and low was $38. The next session opened at $42, traded between $40.50 and $43, and closed at $42.50. Its opening gap was 5%. It opened above the prior high, but the completed daily ranges overlap between $40.50 and $41.
For this workbook, a full opening-gap fill means reaching the previous close. Alder did not reach $40, so that event did not occur. It did reach yesterday’s range. These are separate outcomes.
Clarifications to write in your margin
A wick records an extreme beyond the candle’s body; it is not inherently a false gap. A closing-price line chart usually connects closes and cannot by itself establish the opening gap. Chart session settings also matter: a regular-session opening gap does not prove there were no overnight trades. FINRA’s extended-hours disclosure explains that trading outside regular hours can have lower liquidity, higher volatility, and wider spreads.
The book’s discussion sometimes shifts between gap boundaries and support/resistance. Record the exact price level under consideration. A previous close, previous high, and current open can all be different prices; calling each one “the gap” makes a plan ambiguous.
Exercises 1–4
- Calculate and classify. Previous close $80, high $82, low $77; current open $84, high $85, low $81. Find the opening gap percentage. Was the opening outside the previous range? Are completed ranges separate? Was the previous close reached?
- Reverse direction. Previous close $50, low $48; current open $47, high $49, low $45. Answer the same four questions for this gap down.
- Catch the look-ahead. A researcher buys at the open only when the day’s final low stays above yesterday’s high. What information is unavailable at entry? Rewrite the eligibility rule.
- Write a definition. Specify your market, session, timezone, gap formula, fill reference, and observation deadline. Explain how extended-hours settings could change what you see.
Answer key: exercises 1–4
- +5%; yes, $84 exceeds $82; no, today’s $81 low overlaps yesterday’s range; no, $80 was not reached.
- −6%; the open is below the previous $48 low; completed ranges overlap because today’s high reaches $49; no full fill to $50 occurred.
- The final session low is unknown at the open. Use open > previous high as an observable opening condition, then separately measure whether the completed ranges remain apart.
- One valid specification: ordinary US shares, regular session, America/New_York, signed open-to-previous-close percentage, fill at the previous regular-session close, deadline the same regular-session end. Explain whether extended-hours bars are included. Other consistent definitions are acceptable.
Reading reflection: Find two places in Chapter 1 where a price boundary needs a more precise name. Rewrite each in your own notes and explain how the clarification changes a calculation.
Chapter 2 Companion: Classify Without Hindsight
Read: Chapter 2, pp. 36–63. Demonstrate: separate what is visible now from what later price action reveals.
The chapter discusses common, breakaway, continuation/runaway, and exhaustion gaps, with additional classification dimensions. These labels mix observations with interpretations. Direction is immediately measurable. Whether a move marks the beginning, middle, or end of a lasting trend often becomes clearer later.
| Label | Useful idea from the reading | Question to ask before the outcome |
|---|---|---|
| Common | A gap within ordinary range activity | What defines the range and “small” size? |
| Breakaway candidate | A gap beyond a prior consolidation or boundary | Was that boundary recorded before the gap? |
| Continuation candidate | A gap aligned with an existing trend | How was the trend identified using past bars? |
| Exhaustion candidate | A late trend push that subsequently fails | What evidence of failure was available at decision time? |
| Island reversal candidate | A separated price cluster followed by a gap in the other direction | Has the second gap actually occurred yet? |
Use two labels, recorded at two times
Before revealing later bars, record candidate classification and the evidence supporting it. After a fixed observation window, record outcome classification. A candidate that fails remains in your sample. Otherwise “breakaway gaps work” can become circular: successful moves receive the name while failures disappear.
There is a wording inconsistency in Chapter 2’s exhaustion discussion: it describes gaps in the prevailing direction but also calls them opposite-direction moves. Later examples describe a trend-direction push followed by failure. For our worksheet, write the sequence explicitly: pre-existing uptrend, upward gap, then observed failure. An upward gap alone does not establish exhaustion.
Make context measurable
These are our possible research definitions, not the author’s universal thresholds: “range breakout” means opening above the highest high of the previous 20 completed sessions; “uptrend” means the previous close exceeds its 20-session moving average and that average exceeds its value five sessions earlier. “High opening volume” could mean first-five-minute volume divided by average first-five-minute volume over the previous 20 sessions exceeds 1.5.
Compare matching time intervals. The first five minutes of volume divided by an average full day’s volume answers a different question. Neither high volume nor a rising candle identifies particular traders’ intentions or guarantees follow-through.
Exercises 5–8
- Candidate versus conclusion. A stock opens above a 20-session range after an earnings announcement. It has not completed its first candle. What can you label now, and what remains unknown?
- Spot circular evidence. An analyst collects only gaps followed by ten rising days and calls them continuation gaps. Why can this not establish the chance of continuation at entry?
- Normalize volume. Today’s first five minutes trade 240,000 shares. The average of the previous 20 opening five-minute bars is 160,000. Calculate the ratio. Does it prove buying by institutions?
- Blind chart task. Hide future bars on five historical examples. Record your candidate label and two observable reasons. Reveal exactly five sessions and record what changed. Keep disagreements and failed candidates.
Answer key: exercises 5–8
- It is an opening gap and a breakout candidate, provided the recorded range boundary is exceeded. Persistence, the completed day’s volume, and eventual exhaustion remain unknown.
- The sample was selected using the successful future outcome. Include every setup satisfying rules available at entry, including those that reverse.
- 240,000 ÷ 160,000 = 1.5 times the comparison volume. It measures activity relative to that reference, not participant identity or future direction.
- There is no predetermined correct outcome. A good submission preserves the original labels, uses the same five-session horizon, and explains disagreements without rewriting the original record.
Chapter 3 Companion: Turn a Setup Into a Specification
Read: Chapter 3, pp. 64–104. Demonstrate: distinguish continuation from reversal trades and write rules another reader can apply.
The chapter moves among gap-and-go, gap-fill reversals, opening reversals, and inside-range openings. It also discusses catalysts, opening ranges, VWAP, volume, and supply/demand context. Treat each as a separate hypothesis before combining filters.
Three trades can begin with the same gap up
| Hypothesis | Direction after an upward gap | Event being sought |
|---|---|---|
| Continuation | Long | Price advances beyond a specified opening boundary |
| Fade toward the previous close | Short | Price moves against the opening jump toward a defined reference |
| Rebound after a fill | Long | Price returns to the previous close, then shows a specified recovery |
A fill occurring before your entry is not the same strategy as trading toward the fill. For short examples, define the protective stop above the entry or other chosen invalidation level; do not mechanically reuse a long trade’s stop placement.
Worked example · Fictional prices
From Signal to Actual Fill
Birch Systems opens higher. Our example waits for a completed candle above the opening-range high, then submits a market order. The actual fill determines the entry-to-stop risk.
| Step | Price or calculation | What it means |
|---|---|---|
| 1. Opening gap | $25 close → $26.50 open +6% | The stock opens above the previous close. |
| 2. Opening range | High: $26.80 Low: $26.20 | The first five-minute candle sets our reference levels. |
| 3. Confirmation | Later candle closes at $26.90 | The completed close is above $26.80; our example now submits a market order. |
| 4. Actual entry | Hypothetical fill: $27.05 | The fill is $0.15 above the signal close. |
| 5. Initial risk | $27.05 − $26.20 = $0.85 per share | The example uses the opening-range low as its stop. |
| 6. Target at 2R | $27.05 + (2 × $0.85) = $28.75 | The price target is twice the initial risk above the actual entry, before costs. |
Confirmation adds information and can change the entry price. Whether that tradeoff improves results requires testing. This manual example uses an opening-range stop; the workbook’s separate Pine experiment uses an ATR-based stop.
Resolve Ambiguous Instructions Before Testing
Record unresolved instructions instead of treating them as an executable order plan. The examples here use explicitly chosen invalidation prices.
Your Complete Setup Card
Complete these ten fields before testing. Another reader should be able to follow the specification without guessing.
- Market and universeWhich instruments qualify?
- Session and timezoneWhen do the rules apply?
- Gap definitionWhich prices are compared?
- Context ruleWhat must be true before the trigger?
- Entry triggerWhich observable event authorizes entry?
- Order and expiryWhat order is submitted, and when is it cancelled?
- Initial stopWhere is the trade invalidated?
- Target or other exitHow and when does the position close?
- Size and exposure capWhat quantity and maximum exposure are allowed?
- No-trade conditionsWhat disqualifies an otherwise valid setup?
Exercises 9–12
- Name the trade. A stock gaps up, falls to yesterday’s close, then rises above a completed recovery candle. You buy that recovery. Is this a fade, continuation breakout, or rebound-after-fill hypothesis?
- Recalculate after the fill. A long signal closes at $60. Actual fill is $60.40, stop $59.20. What is actual price risk? What is the 2R target from that fill?
- Audit a short. A short fills at $30 with proposed protective buy-stop at $29. Explain the problem. Suggest a hypothetical invalidation price above entry and calculate a 2R price target.
- Write a no-trade decision. A candidate meets the chart trigger, but no reliable opening price or previous close is available. What should the research record say? May you estimate convenient prices from the screenshot?
Answer key: exercises 9–12
- Rebound after fill. The fill happened before the long entry. It is not the short trade that would have attempted to profit from the descent.
- $1.20 per share; $60.40 + 2 × $1.20 = $62.80 before costs.
- A buy-stop below a current $30 short entry is not a conventional protective stop against rising prices. If the independently chosen invalidation is $30.60, initial risk is $0.60 and a 2R price target is $28.80. The $30.60 level is an example, not a rule from the author.
- Record missing data and exclude the case under a predeclared data-quality rule. Preserve the exclusion count. Do not manufacture inputs; investigate a reliable data source if the case matters.
Chapter 4 Companion: Size, Execute, and Review
Read: Chapter 4, pp. 105–129. Demonstrate: distinguish exposure from planned loss, account for costs, stress-test fills, and separate execution quality from outcome.
Size follows the price distance
For ordinary shares in a matching account currency, a simplified calculation is: quantity = floor((cash risk budget − fixed estimated costs) ÷ (entry-to-stop distance + estimated variable cost per share)). Apply an independent cash/exposure limit too. Futures, options, foreign currencies, and leveraged products need their own contract and conversion calculations.
Suppose a fictional account contains $20,000 and the teaching risk budget is $100. Planned entry is $40, stop $39.20, estimated round-trip variable costs are $0.04 per share, and fixed costs are zero. Quantity is floor($100 ÷ $0.84) = 119 shares. Exposure is $4,760; modeled loss including estimated costs is $99.96. The 0.5% budget is an illustration, not a sizing recommendation.
If the entry fills at $40.20 while the stop stays $39.20, estimated risk rises to $1.04 per share: 119 shares now imply $123.76. Recomputing the arithmetic does not retroactively change the filled order. Your execution plan must address price uncertainty and exposure before submission.
A stop is also not a guaranteed maximum loss. The SEC’s stop-order bulletin explains the difference between a stop trigger and its execution price, and why a stop-limit can remain unfilled.
A wider stop does not improve reward/risk by itself
Entry $40, stop $39.20, target $41.60 gives $0.80 price risk and $1.60 reward: 2R. Widen the stop to $38.80 with the target unchanged, and the reward becomes about 1.33R. Reducing quantity can restore a cash-risk budget, but it does not change this price ratio.
Expectancy needs more than the win rate
In a fictional ten-trade sample, four winners earn +2R each and six losers lose −1R each. Gross total is +2R, or +0.20R per trade. If average costs are 0.15R per trade, net expectancy is +0.05R. If costs rise to 0.25R, it becomes −0.05R. These are arithmetic demonstrations, not backtest results.
Record actual net profit/loss divided by initial cash price-risk to obtain realized net R. Freeze the denominator. If your plan includes costs in the risk budget, name that different denominator so your journal does not mix units.
Review behavior separately from money
The chapter emphasizes emotion management and trade review. Translate a vague goal such as “be disciplined” into an observable behavior: did you wait for the completed trigger candle, use the specified quantity, and leave the initial stop unchanged unless the plan allowed an adjustment?
A profitable violation is still a violation. A rule-following loss may be correct execution of an unproven or losing method. Record both dimensions. A useful pause rule for a paper-trading exercise is to stop submitting new simulated orders after a specified number of process errors, then review those errors. The threshold is your experimental operating rule, not proof of improved returns.
Exercises 13–18
- Size the trade. Cash budget $75, entry $30, stop $29.50, estimated variable round-trip cost $0.05 per share, no fixed cost. Calculate whole shares, exposure, and modeled loss.
- Apply an exposure cap. For exercise 13, maximum permitted exposure is $3,000. What quantity remains, and what modeled loss follows?
- Stress the stop. Buy 100 shares at $50 with intended stop $49. A trading halt is followed by an executable exit at $46. Calculate price loss before costs and compare with planned price risk.
- Expectancy. Win probability 35%, average win 2R, average loss 1R, average costs 0.10R. Calculate net expectancy. Assume no breakeven trades.
- Drawdown. A $10,000 account loses 20%. What percentage gain on the remaining balance restores $10,000?
- Process review. You doubled quantity without authorization and made money. Write a review entry that does not reward the violation.
Answer key: exercises 13–18
- floor(75 ÷ 0.55) = 136 shares. Exposure $4,080. Modeled loss 136 × $0.55 = $74.80.
- 100 shares, because $3,000 ÷ $30 = 100. Modeled loss is $55. A cap can reduce risk below the original budget.
- $400 loss against $100 initial price risk: −4R before costs. The stop level did not cap the realized loss.
- 0.35 × 2 − 0.65 × 1 − 0.10 = −0.05R per trade.
- The balance is $8,000; $2,000 ÷ $8,000 = 25%.
- Example: “Outcome profitable; sizing rule failed. Record planned and actual quantity, the reason for the override, and a pre-submission size check for the next paper session.” Do not relabel the trade compliant because it won.
Claims to Investigate While You Read
The supplied book includes examples and confident statements, but it does not supply a complete reproducible dataset and methodology establishing the following ideas for every instrument and period. Keep them as research questions.
| Idea in the reading | Evidence needed | Our testable version |
|---|---|---|
| Smaller gaps tend to fill | Defined sizes, horizon, universe, all qualifying events | Compare same-session previous-close touches across prespecified size bands |
| Large gaps can continue early in the session | Entry/exit rules, costs, failed setups, actual fill assumptions | The opening-range experiment below |
| High volume confirms the move | Matched-time volume benchmark and subsequent returns | Compare the same entry rule with and without a prespecified relative-volume filter |
| Gap boundaries can act as support/resistance | A fixed boundary, first-touch definition, invalidation, comparison cases | Measure first revisits to the previous close separately from revisits to the previous high |
Research Lab: Does an Early Breakout Follow an Upward Gap?
The book motivates continuation and opening-range trades. Our experiment asks a narrower question: after an opening gap of at least a chosen percentage, what happens when a later completed five-minute candle closes above the first five-minute high?
This code tests one objective interpretation of the source’s concept. Any mechanical definitions introduced here are ours and are not necessarily the creator’s exact rules.
| Layer | Rule |
|---|---|
| Source-derived idea | Investigate early continuation after an upward opening gap using an opening boundary |
| Our experimental definitions | Five-minute chart; default gap at least 4%; first regular-session bar defines the range; later completed close above its high; signal before 10:00 New York time; one long attempt per session |
| Our exit choice | Stop distance fixed at signal-time ATR(14) × input multiplier, rounded up to ticks; target distance is a chosen multiple; both measured from actual entry by relative-tick brackets; remaining position closed at the session’s final bar |
| Implementation shortcuts | Fixed share quantity; no catalyst, float, VWAP, or volume filter; one symbol per run; no short positions or discretionary zone analysis |
Choose a standard five-minute candlestick chart for a US stock with a 9:30 New York regular-session open, and switch off extended hours. The script rejects incompatible chart types/timeframes and observed extended-session bars. Start/end inputs select the research period. Leave enough earlier bars loaded for ATR and a prior session close. Use the same split/dividend-adjustment settings for comparisons and inspect corporate-action dates for mechanical gaps.
Market entries are submitted after the signal candle closes and normally become eligible for fill on the next bar’s opening tick. The stop/target instructions are submitted with the entry using relative tick distances, so their reference is the actual simulated fill. The fixed distance is frozen at submission; it is not recomputed from later ATR values. New setups cannot replace an active trade, and the attempt flag remains used even if a stop closes the trade immediately.
Defaults assume a $25,000 account, 10 shares, commission of 0.05% per executed side, and two ticks of simulated slippage. These are teaching assumptions; change commission, slippage, and capital in Strategy Properties to match the instrument and test. Fixed quantity is exposure sizing, not a fixed percentage risk model.
The final-session-bar exit uses an immediate simulated close to avoid intentionally carrying the position overnight. It assumes execution at that bar’s closing price, with the emulator’s applicable costs, rather than reproducing a real market-on-close submission process. Missing final bars, halts, or data gaps can defeat this intended flattening; inspect any overnight positions. Stop/target ordering within a candle remains emulator-dependent. Compare Bar Magnifier where data access permits it, and inspect large winners and losers manually. The broker-emulator mechanics are documented in TradingView’s strategy documentation (paid link).
Validation status: The script has received a static execution review but has not been compiled in TradingView or run against historical data here. No performance results are claimed.
View Pine Script Backtest Code
//@version=6
// CandleChasers original research baseline; not the author's complete strategy.
strategy("CC Gap Workbook - Early Continuation Experiment", overlay=true,
initial_capital=25000, pyramiding=0, margin_long=100,
commission_type=strategy.commission.percent, commission_value=0.05,
slippage=2, calc_on_every_tick=false, calc_on_order_fills=false,
process_orders_on_close=false)
gapMinimum = input.float(4.0, "Minimum upward opening gap (%)", minval=0.0, step=0.5)
shares = input.int(10, "Fixed shares (not fixed cash risk)", minval=1)
atrLength = input.int(14, "Signal ATR length", minval=1)
stopMultiple = input.float(1.0, "Stop distance / signal ATR", minval=0.1, step=0.25)
rewardMultiple = input.float(2.0, "Target distance / stop distance", minval=0.1, step=0.5)
startDate = input.time(timestamp("01 Jan 2020 00:00 +0000"), "First eligible date")
endDate = input.time(timestamp("31 Dec 2030 23:59 +0000"), "Last eligible date")
if barstate.isfirst
if not chart.is_standard or not timeframe.isminutes or timeframe.multiplier != 5
runtime.error("Use a standard five-minute candlestick chart.")
if syminfo.type != "stock"
runtime.error("This workbook baseline is for US stocks.")
if endDate < startDate
runtime.error("End date must be after start date.")
if session.ispremarket or session.ispostmarket
runtime.error("Switch the chart to regular trading hours only.")
// Previous session close is captured from the prior regular-session chart bar.
// No developing higher-timeframe values or future data are requested.
var float openingRangeHigh = na
var float openingRangeLow = na
var float gapPercent = na
var bool attempted = false
var int frozenStopTicks = na
var int frozenTargetTicks = na
signalATR = ta.atr(atrLength)
nyOpenMinute = hour(time, "America/New_York") * 60 + minute(time, "America/New_York")
nyCloseMinute = hour(time_close, "America/New_York") * 60 + minute(time_close, "America/New_York")
if session.isfirstbar_regular
if nyOpenMinute != 570
runtime.error("Use a US stock with a 09:30 New York regular-session open.")
openingRangeHigh := high
openingRangeLow := low
gapPercent := not na(close[1]) and close[1] > 0 ? 100 * (open - close[1]) / close[1] : na
attempted := false
// First five-minute bar is fully known before a later close can trigger.
// Signals at 10:00 or later are excluded; default first possible signal is 09:40.
eligibleTime = nyCloseMinute > 575 and nyCloseMinute < 600
eligibleDate = time >= startDate and time <= endDate
signal = barstate.isconfirmed and session.ismarket and not session.isfirstbar_regular and
not session.islastbar_regular and eligibleTime and eligibleDate and
not attempted and strategy.position_size == 0 and
not na(gapPercent) and gapPercent >= gapMinimum and
not na(signalATR) and close > openingRangeHigh
if signal
// Freeze distances now. Relative brackets anchor them to the actual entry fill.
frozenStopTicks := math.max(1, int(math.ceil(signalATR * stopMultiple / syminfo.mintick)))
frozenTargetTicks := math.max(1, int(math.round(frozenStopTicks * rewardMultiple)))
strategy.entry("GapLong", strategy.long, qty=shares)
strategy.exit("GapBracket", from_entry="GapLong", loss=frozenStopTicks, profit=frozenTargetTicks)
attempted := true
// Reissue the same fixed bracket; never move it with later ATR values.
if strategy.position_size > 0
strategy.exit("GapBracket", from_entry="GapLong", loss=frozenStopTicks, profit=frozenTargetTicks)
// Intentional closing-price simulation; not an actual MOC order model.
// A missing last bar or halt can prevent this intended flattening.
if barstate.isconfirmed and session.islastbar_regular
strategy.cancel_all()
strategy.close_all(comment="Modeled session close", immediately=true)
plot(session.ismarket ? openingRangeHigh : na, "Opening range high", color=color.teal, style=plot.style_linebr)
plot(session.ismarket ? openingRangeLow : na, "Opening range low", color=color.orange, style=plot.style_linebr)
plot(gapPercent, "Opening gap percent", display=display.data_window)
plotshape(signal, title="Entry submission", style=shape.triangleup, location=location.belowbar, color=color.teal, size=size.tiny)
What This Code Actually Tests
It tests one long-only early-session breakout model after an upward regular-session opening gap. Eligibility is fixed from the open and previous regular-session close. The opening-range high is fixed after the first bar. A qualifying later close submits one market entry and its relative-distance bracket. Exit occurs at stop, target, or the modeled session close.
What This Code Does Not Test
It does not reproduce the book’s complete discretionary method, premarket-high entries, a one-minute trigger, low-float selection, catalyst verification, volume confirmation, VWAP conditions, a stop at the opening-range low, or a gap-fill strategy. It cannot model queue priority, actual spreads, partial fills, market impact, halts, or a portfolio of simultaneous candidates. A positive result would support further work on this narrow model; a negative result would not refute every gap strategy.
Backtest Lab
| Experiment | Change | Keep constant | Record and interpret |
|---|---|---|---|
| Gap threshold | 2%, 4%, 6% | Chart, dates, exits, quantity, costs | Eligible sessions, trades, net expectancy, drawdown; a higher threshold may only shrink the sample |
| Target distance | 1R, 1.5R, 2R, 3R | Gap threshold, entries, stop multiplier, costs | Average win/loss, net R, time exits; inspect broad stability rather than selecting one isolated profit peak |
| Stop distance | 0.75, 1, 1.5 times signal ATR | Other rules and quantity | Cash risk, net R, drawdown; fixed quantity makes cash risk change across settings |
| Cost stress | Base, doubled commission, doubled slippage | Signals and other properties | Net profit per trade and expectancy; determine whether a thin apparent edge survives |
Freeze a baseline before running comparisons. Select development dates and a later untouched evaluation period in advance. If you repeatedly inspect and optimize the evaluation results, they become development data. Keep all attempted settings in your research log. A handful of trades, one strong ticker, or one favorable month cannot establish robustness.
Separate observation study: to investigate fill frequency, collect all eligible opening gaps, including days without a breakout entry. Prespecify bands such as 0.5–under 2%, 2–under 4%, and 4–under 8%, separately for up and down gaps. Mark a same-session fill only if price reaches the previous close. This requires a separate event log; the strategy’s winning-trade percentage is not a gap-fill rate.
Exercises 19–22
- Audit timing. The 9:35–9:40 candle closes above the opening-range high. Under this script, when is the order submitted, and what is the usual earliest simulated fill?
- Audit the bracket. Frozen stop distance is 50 ticks, tick size $0.01, target 2R, actual entry $20.30. Find the stop and target trigger levels before exit slippage and costs.
- Audit the sample. You run the script on three stocks selected because they were last year’s biggest winners. What selection problem arises? Propose a better universe rule.
- Audit the conclusion. A variant has four trades and the highest profit among 40 settings. Write a restrained conclusion and identify the next evidence you need.
Answer key: exercises 19–22
- Submission is at the 9:40 close calculation. Normally the next bar’s opening tick can fill the market order. A signal close is not a guaranteed execution price.
- Distance $0.50: stop $19.80, target $21.30. Actual exit prices and net reward/risk can differ.
- Winner-based universe selection and survivorship can favor the result. Specify the universe as it would have been known at each date, include failed/delisted names where available, and document missing historical coverage. A predeclared present-day list still does not remove historical survivorship.
- “This is an exploratory result from a small sample and many comparisons.” Check individual fills, costs, neighboring settings, additional periods, and fresh evaluation data before making an edge claim.
Reusable Research Worksheets
Copy these tables into a journal or print this page. Write your answers before revealing future prices. Blank cells are intentional spaces for your work. Paper entries are observations, not submitted brokerage orders.
Worksheet A: Opening observation
| Field | Your record |
|---|---|
| Symbol, date, data source, chart adjustment settings | ____________________________ |
| Session and timezone | ____________________________ |
| Previous close / high / low | ____________________________ |
| Current open / signed gap % | ____________________________ |
| Inside/outside prior range at open | ____________________________ |
| Candidate label and evidence available now | ____________________________ |
| Catalyst source and time known, or unknown | ____________________________ |
| Fill reference and fixed observation deadline | ____________________________ |
| Later outcome and first-touch time | ____________________________ |
| Missing data, ambiguity, or exclusion reason | ____________________________ |
Worksheet B: Setup and execution card
| Field | Your specification |
|---|---|
| Rule version / universe / timeframe | ____________________________ |
| Eligibility, context, trigger, and decision timestamp | ____________________________ |
| Order type, planned entry, expiry | ____________________________ |
| Stop, target, time exit, invalidation | ____________________________ |
| Risk budget / estimated costs / quantity / exposure cap | ____________________________ |
| Actual simulated fills / fees / slippage | ____________________________ |
| Initial price risk / realized net R | ____________________________ |
| Rules followed? Evidence, independent of result | ____________________________ |
Worksheet C: Experiment comparison
| Measure | Baseline | One-variable variant |
|---|---|---|
| Rule version and single changed variable | ________ | ________ |
| Dates, universe, chart session, costs | ________ | ________ |
| Eligible setups / triggered trades / exclusions | ________ | ________ |
| Winners / losers / breakevens / net win rate | ________ | ________ |
| Average gross win/loss in frozen R | ________ | ________ |
| Mean net R / net profit per trade | ________ | ________ |
| Profit factor / maximum drawdown and units | ________ | ________ |
| Ambiguous fills / overnight exceptions | ________ | ________ |
| Results by symbol and time period | ________ | ________ |
| Conclusion and evidence that would change it | ________ | ________ |
Net win rate is profitable trades after the chosen costs divided by all closed trades, with breakevens counted separately in the record. Profit factor is gross gains divided by the absolute gross losses under a stated cost convention; it is undefined if the loss denominator is zero. Maximum drawdown is the largest peak-to-trough decline in the measured equity series. Report whether it is cash, percentage, closed-trade, or intratrade drawdown.
Worksheet D: Weekly process review
- Which rule did I follow consistently? Cite a specific record.
- Which behavior failed most often? Count occurrences, including profitable violations.
- Were valid setups skipped? Record reasons separately from invalid setups.
- What single operational change will I practise next session?
- What evidence would show the change helped execution?
- Am I changing a strategy rule? If yes, create a new version and preserve the old results.
Capstone: Build a Small, Auditable Research Report
Your final assignment is an investigation, not an income target. Choose one hypothesis from Chapter 3. Use the supplied script for its specific hypothesis or write a separate manual protocol for a different setup. Do not describe one as a test of the other.
- Specify: complete Worksheet B, identify what comes from the reading, and label every added rule.
- Collect: work through a preselected period without skipping unattractive examples. Aim initially for 30 eligible observations as a workflow exercise; this count is not statistical validation. If fewer exist, report the shortfall rather than widening rules after the fact.
- Audit: inspect at least five individual cases, including a loss, a skipped setup, and any ambiguous fill. Check decision time against information availability.
- Compare: change one variable and complete Worksheet C. Preserve the baseline and all attempted variants.
- Evaluate: report findings on untouched later data when enough observations exist. If the sample remains sparse, label the conclusion inconclusive.
- Explain: submit a one-page report with the hypothesis, exact rules, sample/exclusions, costs, findings, limitations, and next experiment. State whether the code compiled and which data were actually tested.
Worked micro-review: profitable rule-breaking
Suppose a learner’s five fictional observations include two compliant losses of −1R, one compliant win of +2R, one +1R win entered before the trigger, and one qualifying setup skipped without a rule-based reason. The three compliant executed trades total 0R before costs. The early-entry winner does not establish the compliant method’s result, and the missed setup is a process record, not a zero-return executed trade. Keep the overall account record as well; separating groups must not hide actual losses or costs.
Final assessment: exercises 23–28
- Can an opening gap up coexist with overlapping completed daily candles? Explain.
- Why is a filled gap not automatically a profitable gap-fill trade?
- Does increasing share quantity change the price reward/risk ratio?
- Why can a high win rate coexist with negative expectancy?
- How can an “exhaustion” label accidentally leak future information into an entry rule?
- What is the strongest defensible conclusion after completing this workbook without running any historical tests?
Answer key: final assessment
- Yes. The open can exceed the previous close while later prices trade back into the earlier range.
- The trader may enter too late, stop out before the fill, pay excessive costs, lack a short borrow, or never receive an assumed fill. The price event alone supplies no complete executable trade.
- No. At unchanged prices it scales money gained/lost; it does not change the ratio of price reward to price risk.
- Average losses and costs can outweigh frequent smaller gains.
- If the name is assigned only after the reversal and then used to justify a trade before that reversal was known, the rule uses future information.
- You have practised definitions, calculations, specification, and research design. You have not established that any setup is profitable or suitable for live trading.
Completion rubric
| Skill | Ready to continue when… |
|---|---|
| Definitions | You can distinguish opening gaps, outside openings, range separation, and fill references |
| Classification | Your candidate labels preserve the information available at their timestamp |
| Specification | Another reader can apply your trigger, stop, exits, and exclusions without guessing |
| Risk arithmetic | You correctly calculate quantity, exposure, costs, realized R, and worse-fill scenarios |
| Research integrity | You preserve failures, exclusions, ambiguous fills, and all attempted settings |
| Interpretation | Your conclusion matches the evidence and acknowledges untested components |
If a skill is missing, return to its exercise and correct the reasoning. Completing every row supports further learning and investigation; it is not a readiness certificate for risking money.
Final Takeaway
The book introduces gaps, their possible interpretations, setup families, and risk management. This workbook turns those topics into definitions you can check, calculations you can reproduce, and hypotheses you can investigate. Your next useful step is to freeze one specification and collect honest evidence, including the cases that do not support it.
Risk Disclosure
This material is for education and research, not personalized financial advice or a recommendation to trade. Trading can cause substantial losses. Stops do not guarantee a maximum loss; liquidity, halts, gaps, spreads, fees, slippage, and leverage can materially change outcomes. Backtests and paper trades are hypothetical and cannot reproduce every aspect of live execution. Examples and research settings do not establish future profitability.
This is an independent educational companion to the book and is not affiliated with, sponsored by, endorsed by, or authorized by its author or publisher.