A random exit in the final five minutes of RTH

A random exit in the final five minutes of RTH

The previous strategy withdrew an entry order. randomexit closes an actual position. It enters once per trade date, then submits a market exit at a random whole second in the symbol’s final five minutes of regular trading hours (RTH). The exchange calendar determines that window, including early closes and daylight-saving changes. There is no hard-coded closing hour.

The entry is deliberately simple: buy Qty units at the first eligible bar close at or after RTH.Open + EntryDelay. The defaults are one unit and five minutes after the open. Short=true sells instead. This isolates the exit mechanism; it is not evidence of an entry edge. Replace the entry rule with your own signal once you understand the timing and execution trace.

Choose one second, once per trade date

For an RTH close on a whole second, there are 300 possible exit instants:

RTH close - 300 seconds                    RTH close - 1 second
         |-----------------------------------------|     |
         <------ choose one of these 300 seconds ------> close

Example: 16:00:00 close -> 15:55:00 through 15:59:59
Example: 13:15:00 close -> 13:10:00 through 13:14:59

The interval includes its start and excludes the close. exitSecond draws uniformly from those seconds using a private pseudorandom generator. Its key combines the Seed input (default 42), canonical symbol and trade date. The same inputs reproduce the same scheduled second. Removing earlier days from a backtest, changing entry direction or receiving fewer bars does not advance a shared random stream and change the date’s draw. Different dates can still happen to choose the same offset; that is legitimate randomness.

Record the seed with the result and choose it before evaluation. Compare predeclared seeds to study sensitivity; selecting the best seed after looking at profits turns randomization into another optimized parameter. Do not seed from time.Now() or keep redrawing until a convenient deadline appears.

The strategy obtains the calendar with ctx.Calendar(symbol), uses cal.TradeDate(bar.CloseTime.Add(-time.Nanosecond)) to identify the owning trade date, and reads that day’s RTH.Open and RTH.Close. Subtracting a nanosecond assigns a bar ending at a half-open session boundary to the session it just observed. It checks calendar completeness through the close and arms a one-shot ArmSessionTimer against BoundaryRTHClose with the chosen negative offset. The returned instant must match the selected deadline before it submits an entry. A missing RTH or incomplete calendar is an error. A run starting in the last five minutes, or ending before that day’s RTH close, skips the entry.

Run five-minute bars with second-resolution exits

Prerequisite: the intrabar replay behavior in this section requires GLE-1934 to be implemented in the engine you use.

The strategy uses five-minute bars for ordinary decisions and schedules its exit independently, to the second. A one-second execution path supplies the historical observations used to simulate fills. These are separate clocks:

ClockPurpose
Five-minute signal barsDeliver completed observations to OnBar
Session timerCall OnTimer at the chosen random exit second
One-second execution pathResolve orders against observations available after submission

For example, a timer at 15:57:23 fires while the 15:55–16:00 signal bar is still forming. OnTimer sees the last completed signal bar, not the eventual high, low or close of the unfinished bar. The engine processes execution observations and timer deadlines in time order. An exit submitted at 15:57:23 cannot trade at that signal bar’s earlier 15:55 opening price.

Build the example and run it with the served RTH calendar and lifetime v2. Marketfeed must cover the dated contract at the requested execution resolution. The ordinary CSV file adapter supplies no exchange calendar and cannot run this example as written.

go build -o bin/randomexit ./strategies/demo/go/randomexit
bin/randomexit --algolang-describe

bin/algo run --run-id random-exit \
  --adapter bin/marketfeed-adapter --data-protocol pb \
  --strategy bin/randomexit --lifetime v2 \
  --symbols fut:XCME:ES:M26 --bar-interval 5m --session rth \
  --path-interval 1s \
  --date-from 2026-03-06 --date-to 2026-03-09 \
  --inputs Qty=1,Seed=42,EntryDelay=5m \
  --commission-per-share 2.50 --slippage-ticks 1 \
  --plate full --color never --chart lines \
  --lifecycle-json results/learning/random-exit-life.json \
  --fills-json results/learning/random-exit-fills.json \
  --results-dir results/learning/random-exit

The finer execution path does not add one-second OnBar callbacks or change the strategy’s lookback clock. It supplies execution evidence between the five-minute decisions. Missing execution observations can delay a fill; a timer still provides the scheduled decision. With only coarse OHLC data, inspect the engine’s reported execution policy and ambiguity rather than claiming a precise fill second that the data cannot establish.

Live streaming uses the same timer pattern. With --mode live --feed stream, the engine wakes at an armed deadline without waiting for another signal bar, then submits the orders returned by OnTimer to the venue. No strategy-owned clock goroutine is needed. Feed observations, timer decisions and account changes pass through the engine’s serialized event loop, so callbacks do not concurrently mutate strategy state. Scheduling to the second does not guarantee a broker fill at that second; feed ordering, processing and venue latency still matter.

To inspect a shortened RTH and a short position, run:

bin/algo run --run-id random-exit-halfday \
  --adapter bin/marketfeed-adapter --data-protocol pb \
  --strategy bin/randomexit --lifetime v2 \
  --symbols fut:XCME:ES:Z25 --bar-interval 5m --session rth \
  --path-interval 1s \
  --date-from 2025-11-28 --date-to 2025-11-28 \
  --inputs Qty=1,Seed=42,EntryDelay=5m,Short=true \
  --commission-per-share 2.50 --slippage-ticks 1 \
  --plate full --color never --chart lines \
  --lifecycle-json results/learning/random-exit-halfday-life.json \
  --fills-json results/learning/random-exit-halfday-fills.json \
  --results-dir results/learning/random-exit-halfday

With Seed=42 and these served closes, the draw produces the following scheduled deadlines, displayed in America/New_York. The March rows use ESM26; the November row uses ESZ25. The March 6 session is UTC−05:00; March 9 is UTC−04:00. The November close is the served ES RTH close.

Trade dateRTH closeScheduled exit
2026-03-0616:00:0015:55:13
2026-03-0916:00:0015:58:50
2025-11-2813:15:0013:11:34

These are reproducible deadlines, not guaranteed fill timestamps. Inspect the lifecycle trace for timer delivery and order submission, then the fills and final exposure for completed liquidation. Retain the calendar revision, seed and data settings with the result.

Distinguish the exit decision from its fill

OnTimer runs at the selected second. It receives no new bar, and the SDK’s history and account are not freshly updated just because the timer fired. The example logs DataAge alongside the planned and actual timer instants. When a bar closes at the timer instant, that bar is processed first; an order created by the subsequent timer cannot trade retrospectively in it.

flatten reads the actual signed position and returns the opposite market order: a long three needs a sell of three; a short three needs a buy of three. If an entry is still working, it requests cancellation first and waits for confirmation before calculating the remaining exit quantity. Lifecycle turns allow that reconciliation without waiting for another ordinary bar. An exit already working prevents duplicate exit orders.

The market order fills only from eligible execution data after submission. Even with a one-second execution path, sparse observations can delay it. The timer does not supply a fresh price, and the fill timestamp follows the execution model and observation actually used. A deadline at close - 1s can produce a fill stamped at the close, or leave an unfilled order if there is no eligible observation. The example randomizes the exit submission second, not a guaranteed exchange fill second. MarketOnClose does not promise the chosen second either: its supported held-order implementation uses a separate send-time policy. Backtests and the direct IBKR path can accept such an order at a timer; the desk-member path currently refuses it there with moc_at_timer. This recipe uses a plain market order to make its own submission deadline explicit.

If the engine refuses the timer, OnTimerRefused logs the reason and marks the position for flattening at the next decision. Later bars also recover after a missed deadline or incomplete fill; they may occur outside the intended window. A cancellation refusal needs investigation, and shutdown explicitly reports unresolved exposure. Neither a scheduled timer nor an exit intent proves that the account is flat. This small backtest example has no restart-state adoption policy; design and test one before using it live.

The draw tests are included in make strategy-guide-smoke and can be run alone with go test ./strategies/demo/go/randomexit. They check whole-second bounds, both window endpoints, reproducibility and early-close shifts. With the prerequisite engine implementation, the archive commands above exercise the calendar, intrabar timer, order and fill path together.

Complete source: randomexit

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.

  1. OnInit records the single traded instrument and run end. NeedsCalendar and RequiredCapabilities declare the calendar and timer requirements before data arrives.

  2. OnBar identifies the served RTH and checks the entry window. It draws and arms one deadline per trade date before returning the daily entry; the timer is independent of the signal-bar interval.

  3. draw.go contains the complete deterministic draw. A SHA-256 digest of seed, symbol and trade date initializes a private PCG generator; IntN(300) selects a whole second strictly before the served close.

  4. OnTimer requests flattening from actual filled exposure. Working entries are cancelled first; OnLifecycleTurn rechecks the position when cancellation grants a new decision.

  5. OnTimerRefused records failure without returning orders. Later decisions recover when possible, and the shutdown log exposes a position or working order that remains unresolved.

Build the supplied files directly:

go build -o bin/randomexit ./strategies/demo/go/randomexit
bin/randomexit --algolang-describe

This program requires engine capabilities. The current standalone --algolang-selftest offers none, so it intentionally refuses this program during negotiation. Inspect its inputs with --algolang-describe and use the chapter’s engine run to exercise it; do not remove the capability requirement to make a standalone probe pass.

randomexit/main.go

// Command randomexit enters once during RTH, then uses a session-anchored
// timer to request liquidation at a seeded random second in the final five
// minutes. Intrabar backtests require GLE-1934; session scheduling needs
// a served calendar. Signal bars and execution observations use separate clocks.
package main

import (
    "fmt"
    "os"
    "time"

    algolang "MODULE/sdk/strategy"
)

var buildID string

type RandomExit struct {
    Qty        int           `algolang:"default=1,min=1,max=1000,desc=Units in the one daily entry"`
    Seed       int           `algolang:"default=42,desc=Reproducible random-exit seed; record with the run"`
    EntryDelay time.Duration `algolang:"default=5m,min=0s,desc=Wait this long after the served RTH open before entering"`
    Short      bool          `algolang:"default=false,desc=Enter short instead of long; the exit always targets flat"`

    symbol, day, timer string
    end, at            time.Time
    lastExitAttempt    time.Time
    exiting            bool
    cancelRequested    bool
    planned, fired     int
}

var (
    _ algolang.CalendarRequirer    = (*RandomExit)(nil)
    _ algolang.CapabilityRequirer  = (*RandomExit)(nil)
    _ algolang.TimerHandler        = (*RandomExit)(nil)
    _ algolang.TimerRefusalHandler = (*RandomExit)(nil)
    _ algolang.TurnHandler         = (*RandomExit)(nil)
)

func (s *RandomExit) Name() string { return "Random RTH exit" }
func (s *RandomExit) Description() string {
    return "Enter once in RTH and request an exit at a reproducible random second in its last five minutes."
}
func (s *RandomExit) RequiredCapabilities() []string {
    return []string{algolang.CapabilityLifetimeV2}
}

// OneBarRule lets the engine end eligible resting orders after the next bar.
func (s *RandomExit) OneBarRule() bool    { return true }
func (s *RandomExit) NeedsCalendar() bool { return true }
func (s *RandomExit) Lookback() int       { return 1 }

func (s *RandomExit) OnInit(_ *algolang.Context, cfg algolang.InitConfig) error {
    if len(cfg.Instruments) != 1 || s.Qty < 1 || s.EntryDelay < 0 {
        return fmt.Errorf("randomexit needs exactly one instrument, positive Qty and nonnegative EntryDelay")
    }
    s.symbol, s.end = cfg.Instruments[0].Symbol, cfg.EndTime
    s.day, s.timer, s.at, s.lastExitAttempt = "", "", time.Time{}, time.Time{}
    s.exiting, s.cancelRequested, s.planned, s.fired = false, false, 0, 0
    return nil
}

func (s *RandomExit) OnBar(ctx *algolang.Context, bar algolang.Bar) ([]algolang.Order, error) {
    if bar.Symbol != s.symbol {
        return nil, nil
    }
    cal, ok := ctx.Calendar(s.symbol)
    if !ok {
        return nil, fmt.Errorf("no exchange calendar serves %s", s.symbol)
    }
    date, ok := cal.TradeDate(bar.CloseTime.Add(-time.Nanosecond))
    day, exists := cal.Day(date)
    if !ok || !exists || day.RTH == nil {
        return nil, fmt.Errorf("no served RTH window for %s at %s", s.symbol, bar.CloseTime)
    }

    // Timers normally provide the exit decision. Later bars are a recovery
    // opportunity after refusal, missing execution data, or partial fills.
    if !s.at.IsZero() && ctx.Now().After(s.at) {
        s.exiting = true
    }
    if s.exiting {
        orders := s.flatten(ctx)
        if len(orders) > 0 || ctx.Position(s.symbol).Quantity != 0 || len(ctx.Exposure(s.symbol).WorkingOrders) != 0 {
            return orders, nil
        }
        if date == s.day {
            return nil, nil // Never re-enter after this date's exit.
        }
        s.exiting = false
    }
    if date == s.day || bar.CloseTime.Before(day.RTH.Open.Add(s.EntryDelay)) {
        return nil, nil
    }
    // Starting a run in the exit window is not permission to redraw until a
    // convenient deadline appears. Skip that date without an entry.
    s.day = date
    if !bar.CloseTime.Before(day.RTH.Close.Add(-5*time.Minute)) ||
        (!s.end.IsZero() && s.end.Before(day.RTH.Close)) {
        ctx.Logf("skip date=%s: no full entry/exit window remains in this run", date)
        return nil, nil
    }
    if err := cal.Complete(ctx.Now(), day.RTH.Close, false); err != nil {
        return nil, fmt.Errorf("randomexit calendar: %w", err)
    }
    if ctx.Position(s.symbol).Quantity != 0 || len(ctx.Exposure(s.symbol).WorkingOrders) != 0 {
        return nil, fmt.Errorf("randomexit requires a flat account with no working order before its entry")
    }
    s.at = exitSecond(s.Seed, s.symbol, date, day.RTH.Close)
    s.timer = "random-exit:" + date
    s.cancelRequested = false
    s.lastExitAttempt = time.Time{}
    at, err := ctx.ArmSessionTimer(s.timer, s.symbol, algolang.BoundaryRTHClose, s.at.Sub(day.RTH.Close))
    if err != nil {
        return nil, fmt.Errorf("arm random exit before entry: %w", err)
    }
    if !at.Equal(s.at) {
        return nil, fmt.Errorf("session timer selected %s instead of this date's exit %s", at, s.at)
    }
    s.planned++
    ctx.Logf("randomexit plan date=%s symbol=%s seed=%d rth_close=%s exit_at=%s seconds_before_close=%g",
        date, s.symbol, s.Seed, day.RTH.Close.UTC().Format(time.RFC3339),
        s.at.UTC().Format(time.RFC3339), day.RTH.Close.Sub(s.at).Seconds())
    o := algolang.MarketBuy(s.symbol, int64(s.Qty)).Named("daily entry")
    if s.Short {
        o = algolang.MarketSell(s.symbol, int64(s.Qty)).Named("daily entry")
    }
    o.ClientID = "random-entry:" + date
    return []algolang.Order{o}, nil
}

func (s *RandomExit) OnTimer(ctx *algolang.Context, timer algolang.TimerFired) ([]algolang.Order, error) {
    if timer.ID != s.timer {
        return nil, nil
    }
    s.exiting = true
    s.fired++
    age, _ := ctx.DataAge(s.symbol)
    ctx.Logf("randomexit fired at=%s planned=%s data_age=%s position=%d",
        timer.FiredAt.UTC().Format(time.RFC3339), s.at.UTC().Format(time.RFC3339), age, ctx.Position(s.symbol).Quantity)
    return s.flatten(ctx), nil
}

func (s *RandomExit) OnTimerRefused(ctx *algolang.Context, refusal algolang.TimerRefused) {
    if refusal.ID == s.timer {
        s.exiting = true
        ctx.Logf("RANDOM EXIT REFUSED code=%s reason=%s; recover at the next decision", refusal.Code, refusal.Reason)
    }
}

// A confirmed entry cancellation can grant another decision at the same
// instant. Read the actual position there before submitting the closing order.
func (s *RandomExit) OnLifecycleTurn(ctx *algolang.Context, _ algolang.LifecycleTurn) ([]algolang.Order, error) {
    if s.exiting {
        return s.flatten(ctx), nil
    }
    return nil, nil
}

func (s *RandomExit) flatten(ctx *algolang.Context) []algolang.Order {
    exposure := ctx.Exposure(s.symbol)
    if len(exposure.WorkingOrders) != 0 {
        for _, w := range exposure.WorkingOrders {
            if w.Order.Name != "random exit" && w.Status != algolang.OrderStatusPendingCancel && !s.cancelRequested {
                ctx.Cancel(w.Order.ClientID)
                s.cancelRequested = true // A refused cancel needs investigation, not a same-instant retry loop.
            }
        }
        return nil
    }
    q := exposure.Position.Quantity
    if q == 0 || s.lastExitAttempt.Equal(ctx.Now()) {
        return nil
    }
    s.lastExitAttempt = ctx.Now()
    o := algolang.MarketSell(s.symbol, q).Named("random exit")
    if q < 0 {
        o = algolang.MarketBuy(s.symbol, -q).Named("random exit")
    }
    o.ClientID = fmt.Sprintf("random-flat:%s:%d", s.day, ctx.Now().UnixNano())
    return []algolang.Order{o}
}

func (s *RandomExit) OnFill(ctx *algolang.Context, fill algolang.Fill) {
    ctx.Logf("randomexit fill name=%s at=%s quantity=%d raw_price=%g position=%d",
        fill.Name, fill.Timestamp.UTC().Format(time.RFC3339), fill.Quantity, fill.RawPrice(), ctx.Position(s.symbol).Quantity)
}

func (s *RandomExit) OnShutdown(ctx *algolang.Context) {
    ctx.Logf("randomexit planned=%d fired=%d final_position=%d working=%d",
        s.planned, s.fired, ctx.Position(s.symbol).Quantity, len(ctx.Exposure(s.symbol).WorkingOrders))
    if ctx.Position(s.symbol).Quantity != 0 || len(ctx.Exposure(s.symbol).WorkingOrders) != 0 {
        ctx.Logf("UNRESOLVED EXPOSURE: the scheduled exit is not evidence of a completed liquidation")
    }
}

func main() {
    if err := algolang.Run(&RandomExit{}); err != nil {
        fmt.Fprintln(os.Stderr, "randomexit:", err)
        os.Exit(1)
    }
}

randomexit/draw.go

package main

import (
    "crypto/sha256"
    "encoding/binary"
    "fmt"
    "math/rand/v2"
    "time"
)

// exitSecond draws one of the 300 whole-second instants in [RTH close-5m,
// RTH close). A private generator keyed by seed, symbol and trade date makes
// the date's choice independent of earlier dates, missing bars or run order.
// It is simulation randomness, not a source of cryptographic randomness.
func exitSecond(seed int, symbol, date string, close time.Time) time.Time {
    digest := sha256.Sum256([]byte(fmt.Sprintf("%d\x00%s\x00%s", seed, symbol, date)))
    rng := rand.New(rand.NewPCG(binary.BigEndian.Uint64(digest[:8]), binary.BigEndian.Uint64(digest[8:16])))
    last := close.Add(-time.Nanosecond).Truncate(time.Second)
    return last.Add(-time.Duration(rng.IntN(300)) * time.Second)
}

Previous: A session-timed limit strategy · Next: A continuous futures trend: contracts and rolls