Opening-gap continuation: trade the main session
openinggap buys a continuation of an upward opening gap, or sells a downward one. It waits for an opening range, places a stop beyond that range, attaches a stop loss, and exits near the regular session close.
bin/algo run \
--adapter bin/marketfeed-adapter --data-protocol pb \
--strategy bin/openinggap --symbols fut:XCME:ES \
--bar-interval 1m --session rth \
--inputs Session=rth,RangeMinutes=5,History=1000 \
--date-from 2025-01-02 --date-to 2025-03-31 \
--commission-per-share 2.50 --slippage-ticks 1 \
--results-dir results/learning/openinggapThis requires one-minute RTH history and an exchange calendar. History=1000 keeps more than two ordinary US equity-length sessions for the prior-session lookup; confirm coverage on the actual instrument. The run’s --session and the strategy’s Session input must agree.
The current marketfeed pin changes an important convention: ES, NQ, YM, RTY and the affected micro roots use 08:30-15:00 America/Chicago for rth, the US cash session, rather than the previous Globex day portion ending at 16:00. ETH still supplies the Globex trading-day close. Inspect each root’s calendar; not every equity-index contract follows this rule. Re-running an older RTH study can therefore change its close, opening-gap baseline and pre-close orders even when the strategy code is identical. Preserve the old adapter and calendar provenance for a comparison, and refresh cached reads when deliberately adopting the new definition.
Just after the open
The strategy asks NeedsCalendar() bool { return true }. On each primary bar it resolves the trade date and the calendar’s session window. It builds the range from bars opening before session.Open + RangeMinutes. When that range is complete, it compares the session’s opening price with the prior session’s close and places the stop in the gap’s direction.
On one-minute bars with a five-minute range, the signal is decided five minutes after the open and the new stop first participates in subsequent data. With RangeMinutes=1, it can act after the first minute. With 15-minute bars, a five-minute range is not actually observable at five minutes: the first available decision is the completed 15-minute bar. Choose resolution to match the question.
Use the calendar’s trade date, not CloseTime.Day() and a fixed UTC hour. Futures sessions can begin the preceding evening; daylight saving and early closes change the mapping to UTC. The demo uses the instant just before the bar close to attribute the bar to its session, then kit.PriorSession to recover the previous one from buffered bars.
Just before the close
The demo calls kit.CloseOutAt. Under lifetime v2 it makes the close-out decision on a bar at least five minutes before RTH close. It cancels the entry or protective stop as appropriate and returns MarketOnCloseBuy or MarketOnCloseSell for the actual position. It stops taking new entries after that cutoff. On 15-minute bars the last suitable decision is generally 15 minutes before close, not an invented five-minute observation.
Algolang’s v2 MOC is a scheduled market-style execution shortly before the calendar’s RTH close. It selects a deterministic send instant in its configured pre-close window and uses the first supported observation at or after that instant, plus slippage. A coarse bar without a finer path can supply its close as the proxy; inspect the fill-path notes. This is not a claim to model an exchange closing auction. A late decision may target the following session. Do not use legacy v1 same-bar-close behavior to obtain a convenient fill.
If the expected close-out bar is missing, this example cleans up at the next session’s first bar. That can leave overnight exposure and allow a resting order to fill before cleanup. The next chapter shows how a timer can make a decision without requiring that final bar.
Inspect an early-close day and a missing-bar fixture as carefully as a normal day. Confirm that an entry which never filled does not cause an unwanted “exit” to open an opposite position, and that no stale protective order is left after flattening. Source to study: strategies/demo/go/openinggap/main.go.
Complete source: openinggap
The numbered reading notes below explain the complete program; the inline comments describe individual steps. Keep all the listed files together. MODULE means the module path printed by go list -m in this checkout.
Session facts identify the main-session opening range and gap. The strategy does not substitute midnight or a hard-coded UTC time for an exchange session.
The range and session state limit entry opportunities. Follow the daily reset and the one-entry conditions before the order construction.
kit.CloseOutAtimplements the chosen close-out convention. Compare its execution time with the served session and data resolution; a scheduled exit is not a simulated auction.
Build the supplied files directly:
go build -o bin/openinggap ./strategies/demo/go/openinggap
bin/openinggap --algolang-selftestopeninggap/main.go
// Command openinggap is Bruce Babcock's opening-gap continuation on intraday bars: after an open that gaps from the
// prior session's close, it enters on a stop a few points beyond the opening range in the gap's direction, with a stop
// loss, and exits on the close.
//
// # Source
//
// Babcock in Le Beau and Lucas, Day Trading Systems & Methods, chapter 8: "wait for an opening price that gaps
// noticeably from the previous day's close ... Tack on a few points above or below the opening price range and enter
// the market on a buy stop or sell stop as the market begins to trend in the direction of the gap ... Use a stop loss
// of about $500 and exit the trade on the close." His "75 points" and "25 points" are hundredths of an S&P index point
// of 1992, about 0.19% and 0.06% of the index; the defaults GapMin 10 and FollowThrough 3 are those fractions of an
// E-mini near 5,300. The $500 stop is StopDollars / point value price units: 10 points on ES at 50 a point.
//
// # The rules as built
//
// On each primary bar the strategy advances the position lifecycle and looks up the symbol's exchange calendar, the
// bar's trade date (that of its close less one nanosecond) and the window that Session names on the calendar for the
// date; a bar without them changes nothing. It keeps the bar's 1-based ordinal in its session, the session's first
// open and the opening range: the high and low of the bars that open before the window's open plus RangeMinutes,
// complete at the close of the first bar that closes at or after that instant. The gap is the session's open less the
// prior session's close, which comes from the grid buffer resampled by trade date (kit.PriorSession). Once the range
// is complete, flat, with the session's entry not yet placed and the prior session known, a gap up of GapMin or more
// places a buy stop FollowThrough above the range's high and a gap down of GapMin or more a sell stop FollowThrough
// below its low; an open at the prior close never trades. The entry is GTC and carries an attached GTC stop loss
// StopDollars / point value from its level, a sell stop below a buy and a buy stop above a sell, which activates when
// the entry fills. On the session's close-out bar (kit.CloseOutAt) the strategy cancels by name the stop loss of a
// filled entry while a position is open, else the entry while it is still working, and closes a position with a
// market-on-close (MOC) order. Under lifetime v1 the close-out bar is the session's last, whose close is at or after
// the window's close, and the MOC settles at that close. Under v2 an MOC decided there would go out at the next
// session's close (GLE-1375), so the close-out bar is the last one closing at least 5 minutes before the RTH close, the
// 14:45 bar on the E-mini's 15-minute bars (its research RTH closes at 15:00 Chicago time), and the MOC goes out
// shortly before the close; the stop loss stops working one bar earlier than under v1, and the session takes no more
// orders after it. When a session's close-out bar is missing,
// the next session's first bar does the same: it cancels the stop loss of a position, or the entry if it is still working, and
// flattens a position by a market order at the next open (an order resting from the last session can fill in that
// first bar before the strategy sees it). One trade a session: no re-entry after a stop.
//
// # The order of touches inside a bar
//
// Scoping row 30: when one bar reaches the entry and then the stop loss, the bar-resolution simulator enters and
// stops out in that bar. A run with --path-heuristic midpoint takes the extreme nearer the open first; a run with
// both --include-path and --path-interval 1m decides from the minute bars. No engine change.
//
// # Departures
//
// The opening range is the first RangeMinutes of the grid: Babcock's "opening price range" is a pit-era term he does
// not define. With StopDollars 0 the stop loss rests at the entry level. With a buffer shorter than two sessions the
// prior session can first become known after the range bar, and the entry is then placed late: keep History at two
// sessions or more. The gap is inclusive: a gap of exactly GapMin trades. The entry rests until the session's last
// bar. A level at or through the last price rests as a first-touch stop.
//
// # Why the grid and not a custom window
//
// Session windows of the form custom:HHMM-HHMM refuse continuous symbols; the rth grid with the calendar's window
// serves dated and continuous symbols alike. The strategy declares no series: it reads the prior session from the
// grid buffer.
//
// # Lifetime
//
// The strategy supports lifetime-v2 and runs under either order-lifetime profile with one code path, the close-out bar
// aside: a GTC entry and its GTC stop loss, cancelled by name, and MOC exits; no Day order rests across bars. The
// fills are the same under both but on a day the stop loss or the entry would fill in the session's last bar, which
// v2 has already cancelled. It needs the exchange calendar (pb wire); with none, as on an adapter that serves none, it
// logs once and places no order. This is a backtest example: a first-touch stop is backtest-only.
package main
import (
"fmt"
"math"
"os"
"time"
_ "time/tzdata"
algolang "MODULE/sdk/strategy"
"MODULE/strategies/kit"
)
// OpeningGap is Babcock's opening-gap continuation: its exported fields are the run's inputs, the unexported ones the
// running state.
type OpeningGap struct {
Session string `algolang:"default=rth,values=[rth,eth,session],desc=The run's grid boundary (the --session of the run)"`
RangeMinutes int `algolang:"default=5,min=1,max=1440,desc=Minutes from the session's open that make the opening range"`
GapMin float64 `algolang:"default=10,min=0,desc=Smallest gap from the prior session's close to the open in price units"`
FollowThrough float64 `algolang:"default=3,min=0,desc=Price units beyond the opening range at which the stop entry rests"`
StopDollars float64 `algolang:"default=500,min=0,desc=Stop loss per contract in the account currency"`
History int `algolang:"default=400,min=2,max=100000,desc=Grid bars of history kept (at least two sessions)"`
Qty int `algolang:"default=1,min=1,max=1000000,desc=Contracts per entry"`
// ids stamps the orders' client IDs (Prefix "openinggap").
ids kit.IDStamper
// state is the running session: its date, ordinal, first open, opening range and entry flag.
state ogSession
// logged records that the missing calendar has been logged.
logged bool
// entryID is the ClientID of the session's entry, "" when none.
entryID string
}
// Name returns the strategy's name.
func (g *OpeningGap) Name() string { return "openinggap" }
// Description returns one sentence on what the strategy does.
func (g *OpeningGap) Description() string {
return "Bruce Babcock's opening-gap continuation, with a stop entry a few points beyond the opening range in the direction of a gap from the prior session's close, a dollar stop loss and an exit on the session's close."
}
// SupportedCapabilities reports that the strategy supports order lifetime v2; it requires nothing, so it runs under
// v1 as well.
func (g *OpeningGap) SupportedCapabilities() []string {
return []string{algolang.CapabilityLifetimeV2}
}
// Lookback returns the grid bars of history kept, History, from which the prior session is resampled.
func (g *OpeningGap) Lookback() int { return g.History }
// NeedsCalendar reports that the strategy reads the exchange calendar, so that the engine pushes it.
func (g *OpeningGap) NeedsCalendar() bool { return true }
// OnInit resets the client-ID stamper, the session, the logged flag and the session's entry. It reads nothing from
// ctx and always succeeds.
func (g *OpeningGap) OnInit(ctx *algolang.Context, cfg algolang.InitConfig) error {
g.ids = kit.IDStamper{Prefix: "openinggap"}
g.state = ogSession{}
g.logged = false
g.entryID = ""
return nil
}
// OnBar runs the opening-gap rules at the close of each primary bar: on the session's close-out bar (kit.CloseOutAt)
// it cancels the entry or its stop loss by name and exits with an MOC, and after it (v2) it does nothing; on a session's first bar it does the same for the last session's
// entry and flattens a position met there;
// otherwise it places the session's one stop entry, with its stop loss, once the opening range is complete and the
// open gaps from the prior session's close. It never returns an error.
func (g *OpeningGap) OnBar(ctx *algolang.Context, bar algolang.Bar) ([]algolang.Order, error) {
if !ctx.IsPrimary(bar) {
return nil, nil
}
ctx.Trade(bar)
sym := bar.Symbol
cal, ok := ctx.Calendar(sym)
if !ok {
if !g.logged {
g.logged = true
ctx.Logf("openinggap: no exchange calendar for %s: no orders", sym)
}
return nil, nil
}
date, ok := cal.TradeDate(bar.CloseTime.Add(-time.Nanosecond))
if !ok {
return nil, nil
}
win, ok := kit.SessionWindow(cal, date, g.Session)
if !ok {
return nil, nil
}
g.state = ogAdvance(g.state, date, bar, win.Open.Add(time.Duration(g.RangeMinutes)*time.Minute))
pos := ctx.Position(sym).Quantity
rthClose := win.Close
if rth, ok := kit.SessionWindow(cal, date, "rth"); ok {
rthClose = rth.Close
}
switch kit.CloseOutAt(bar, win.Close, rthClose, ctx.LifetimeV2()) {
case kit.CloseOutNow:
g.closeOut(ctx, pos)
switch {
case pos > 0:
return []algolang.Order{g.ids.Stamp(algolang.MarketOnCloseSell(sym, pos).Named("EOD exit"), bar)}, nil
case pos < 0:
return []algolang.Order{g.ids.Stamp(algolang.MarketOnCloseBuy(sym, -pos).Named("EOD exit"), bar)}, nil
}
return nil, nil
case kit.CloseOutDone:
return nil, nil
}
// A session's first bar with the last session's entry still named (its last bar was missing): cancel what is left
// of it, the stop loss of a position or the unfilled entry, before a new entry can take the name, and flatten a
// position at the next open.
if g.state.Ordinal == 1 && (pos != 0 || g.entryID != "") {
g.closeOut(ctx, pos)
if pos != 0 {
return []algolang.Order{g.ids.Stamp(algolang.Flatten(sym, pos).Named("EOD exit"), bar)}, nil
}
}
pc, pok := kit.PriorSession(kit.Series(ctx, bar), cal)
o, place := ogEntry(g.state, pc.Close, pok, g.GapMin, g.FollowThrough, g.StopDollars/kit.PointValue(ctx, sym), int64(g.Qty), pos, bar.Close, sym)
if !place {
return nil, nil
}
o = g.ids.Stamp(o, bar)
o.AttachedOrders[0].ClientID = o.ClientID + "_sl"
g.state.Entered = true
g.entryID = o.ClientID
side := "sell"
if o.Side == algolang.Buy {
side = "buy"
}
ctx.Logf("openinggap: %s gap %.2f entry %s at %v stop loss %v", date, g.state.Open-pc.Close, side, o.StopPrice, o.AttachedOrders[0].StopPrice)
return []algolang.Order{o}, nil
}
// closeOut cancels by name what ogCloseOut names for the session's entry and forgets the entry.
func (g *OpeningGap) closeOut(ctx *algolang.Context, pos int64) {
for _, id := range ogCloseOut(g.entryID, pos, ctx.WorkingOrders()) {
ctx.Cancel(id)
}
g.entryID = ""
}
// ogSession is the running state of the current trade date: its date, the 1-based ordinal of the newest bar, the
// session's first open, the opening range so far, whether the range is complete and whether this session's entry has
// been placed.
type ogSession struct {
Date string
Ordinal int
Open float64
RangeHigh, RangeLow float64
RangeDone bool
Entered bool
}
// ogAdvance folds a bar of trade date date into the session state; rangeEnd is the session window's open plus
// RangeMinutes. A bar of another date, or the first bar of all, starts the session afresh at that bar's open with an
// empty range. A bar that opens before rangeEnd widens the range, and the range is complete from the first bar that
// closes at or after rangeEnd on.
func ogAdvance(s ogSession, date string, bar algolang.Bar, rangeEnd time.Time) ogSession {
if s.Date != date || s.Ordinal == 0 {
s = ogSession{Date: date, Open: bar.Open, RangeHigh: math.Inf(-1), RangeLow: math.Inf(1)}
}
s.Ordinal++
if bar.OpenTime.Before(rangeEnd) {
s.RangeHigh = math.Max(s.RangeHigh, bar.High)
s.RangeLow = math.Min(s.RangeLow, bar.Low)
}
if !bar.CloseTime.Before(rangeEnd) {
s.RangeDone = true
}
return s
}
// ogEntry returns the session's stop entry, with its attached stop loss, and true when it is to be placed now. That
// is when the range is complete and has a bar, the entry is not yet placed, the position is flat and the prior
// session is known, and the open gaps from priorClose by gapMin or more: up, a buy follow above the range's high with
// a sell stop stopPoints below that level; down, a sell follow below the range's low with a buy stop stopPoints above
// it. A level at or through last gives the first-touch form. Both orders are GTC, of qty, and carry no ClientID;
// otherwise it returns the zero Order and false.
func ogEntry(s ogSession, priorClose float64, priorOK bool, gapMin, follow, stopPoints float64, qty, pos int64, last float64, sym string) (algolang.Order, bool) {
if !s.RangeDone || s.Entered || pos != 0 || !priorOK || math.IsInf(s.RangeHigh, 0) {
return algolang.Order{}, false
}
gap := s.Open - priorClose
var entry, stopLoss algolang.Order
switch {
case gap > 0 && gap >= gapMin:
level := s.RangeHigh + follow
entry = kit.StopEntry(sym, +1, qty, level, last).Named("LE")
stopLoss = algolang.StopSell(sym, qty, level-stopPoints).Named("LX Stop")
case gap < 0 && -gap >= gapMin:
level := s.RangeLow - follow
entry = kit.StopEntry(sym, -1, qty, level, last).Named("SE")
stopLoss = algolang.StopBuy(sym, qty, level+stopPoints).Named("SX Stop")
default:
return algolang.Order{}, false
}
entry.TIF = algolang.GTC
stopLoss.TIF = algolang.GTC
entry.AttachedOrders = []algolang.Order{stopLoss}
return entry, true
}
// ogCloseOut returns the client IDs to cancel when the session ends: the stop loss of a filled entry while a position
// is open, else the entry itself while it is still working. The stop loss is named, not looked up, as a v1 working
// view does not list an activated child; with no entry, or a flat position whose entry no longer works, it returns
// nil.
func ogCloseOut(entryID string, pos int64, working []algolang.WorkingOrder) []string {
if entryID == "" {
return nil
}
if pos != 0 {
return []string{entryID + "_sl"}
}
for _, w := range working {
if w.Order.ClientID == entryID && w.Status != algolang.OrderStatusPendingCancel {
return []string{entryID}
}
}
return nil
}
// main runs the strategy and exits with status 1 when the run fails.
func main() {
if err := algolang.Run(&OpeningGap{}); err != nil {
fmt.Fprintf(os.Stderr, "openinggap: %v\n", err)
os.Exit(1)
}
}Previous: A channel breakout with an attached bracket · Next: A session-timed limit strategy