A session-timed limit strategy
closetimer rests a buy limit below the market during RTH and withdraws it at a calendar-derived instant. Unlike a bar-only strategy, it can cancel even if no bar closes near the deadline.
bin/algo run \
--adapter bin/marketfeed-adapter --data-protocol pb \
--strategy bin/closetimer --symbols fut:XCME:ES:M26 \
--bar-interval 1m --session rth --lifetime v2 \
--inputs Lead=5m,Distance=2,Withdraw=true \
--date-from 2026-03-09 --date-to 2026-03-13 \
--commission-per-share 2.50 --slippage-ticks 1 \
--lifecycle-json results/learning/timer-life.json \
--results-dir results/learning/timerIt requires lifetime v2, the protobuf strategy protocol and a served exchange calendar. The CSV file adapter does not supply the calendar needed here. This is an order-lifetime demonstration: it withdraws the limit, not a filled position. A filled buy can remain open. Do not mistake cancellation of an order for liquidation of a holding. The next trade date can place another entry even while that holding remains, so filled positions can accumulate. A one-position version needs a position gate and a separate exit policy.
Schedule a decision, not a fabricated bar
The key call in the executable is:
at, err := ctx.ArmSessionTimer("close", s.symbol,
algolang.BoundaryRTHClose, -s.Lead)
if err != nil {
ctx.Logf("cannot schedule withdrawal: %v", err)
return nil, nil
}The strategy arms the timer before relying on that withdrawal, returns the GTC limit, and implements OnTimer. At the timer it reads WorkingOrders, skips already-pending cancellations, and calls ctx.Cancel(clientID). OnTimerRefused also withdraws the order: a deadline that cannot be honoured must not silently leave it working.
Adapt the pattern to timed entries and exits
The same API can schedule a decision one minute after the open:
at, err := ctx.ArmSessionTimer("enter", symbol,
algolang.BoundaryRTHOpen, time.Minute)This is an adaptation fragment, not an input supported by closetimer. Arm it from an earlier eligible decision, such as the prior session or pre-open data; an RTH-only run cannot observe its first day’s open in advance merely by asking for a timer. Check the returned at against the intended trade date and remember that timers are one-shot. Re-arm for each desired session and avoid replacing an already-armed timer on every bar.
In the corresponding OnTimer, check ctx.DataAge(seriesID), the signal last established from completed data, and ctx.Flat(symbol) before returning a market entry. For a pre-close exit, arm sufficiently early for the intended execution policy, read actual signed position, cancel conflicting exits and return the required reducing order. A returned market order trades on later data; a timer provides a decision instant, not a guaranteed fill price.
No bar accompanies OnTimer: ctx.Now() is FiredAt, history does not advance, and the account is not freshly marked merely because time passed. A stale quote remains stale. In historical replay, the engine refuses a timer inside an unresolved coarse bar with timer_coarse. A finer execution path currently does not remove that check. Real-time streaming can fire inside a coarse bar; the random-exit chapter explains the distinction and the required engine support for intrabar backtests. Handle refusals deliberately. The calendar must be complete through the requested instant and the instant must be inside the run’s effective end.
Use an expiry when cancellation needs no decision
If a deadline only cancels an order, use an expiry. This GTC entry fragment expires 15 minutes after the decision:
order := algolang.Order{
Symbol: symbol, Side: algolang.Buy, Quantity: 1,
Type: algolang.Limit, LimitPrice: entryPrice,
TIF: algolang.GTC, CancelAfter: 15 * time.Minute,
}CancelAt sets an absolute instant; CancelAfter adds a duration to the decision instant; OneBar uses the next close of the deciding series. Choose one explicit field: combining them is an expiry_conflict. The relative duration is elapsed time, not trading minutes. These fields need lifetime v2; CancelAfter and OneBar also need the protobuf strategy wire. They are not supported on combos or attached children.
Live v2 enforces these expiries too. A fill observed first wins. One-bar expiry precedes the next strategy decision and produces a cancel without a CancelResponse; instant expiry produces the response and eventual cancel. Expiry precedes a timer at the same instant. A pending cancellation remains pending until the venue confirms it. Use a timer when the deadline requires checking data, choosing an exit quantity or another decision.
Compare Withdraw=true with Withdraw=false in the lifecycle trace: check the timer, cancellation response and any later fills. Source to study: strategies/demo/go/closetimer/main.go and sdk/strategy/timers.go.
Complete source: closetimer
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.
The strategy requires the lifetime capability and a calendar. It validates calendar coverage before relying on a session-relative deadline.
A timer is armed from a real decision using the main-session boundary. Its callback is a decision with no new bar, so the latest price can be stale.
OnTimerplaces or withdraws the working limit according to the inputs.OnTimerRefusedexposes refusal; withdrawing an entry does not liquidate an already filled position.
Build the supplied files directly:
go build -o bin/closetimer ./strategies/demo/go/closetimer
bin/closetimer --algolang-describeThis 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.
closetimer/main.go
// Command closetimer is a runnable example of a strategy that decides at an instant of its own
// choosing rather than at a bar: it rests a limit order below the market during a contract's
// regular trading hours (RTH) and withdraws it at the session's close, whether or not a bar of
// the contract closes then.
//
// On the first bar of a trade date that closes inside the date's RTH window (and, when Lead is
// set, at least Lead before its close), it buys Qty contracts with a GTC limit Distance below the
// bar's close, client id entry-<trade date>, and arms the session timer "close" for the RTH
// close less Lead on the contract's exchange calendar, with ctx.ArmSessionTimer. The engine
// admits the timer only when the calendar is complete up to that instant. When the timer fires,
// OnTimer cancels the order if it is still working and logs how old the contract's newest bar
// is (ctx.DataAge): no bar travels with a timer. If the engine refuses the timer, the order
// cannot be withdrawn on time, so OnTimerRefused cancels it at once. With Withdraw false the
// order is left working, for comparison.
//
// It needs order lifetime v2 and the exchange calendar of the contract's root, so it runs on
// the pb wire under an engine run with --lifetime v2.
package main
import (
"errors"
"fmt"
"os"
"time"
algolang "MODULE/sdk/strategy"
)
// buildID is stamped by the Makefile via -ldflags.
var buildID string
// ctCloseTimer is the id of the session timer that withdraws the order.
const ctCloseTimer = "close"
// CloseTimer rests one limit order per trade date during the regular session and withdraws it
// at the RTH close on a session timer.
type CloseTimer struct {
Qty int `algolang:"default=1,min=1,max=1000,desc=Contracts per order"`
Distance float64 `algolang:"default=2,min=0,desc=How far below the bar's close the limit rests (price units)"`
Lead time.Duration `algolang:"default=0s,desc=How long before the RTH close the order is withdrawn"`
Withdraw bool `algolang:"default=true,desc=Arm the close timer; false leaves the order working (for comparison)"`
symbol string // the traded contract, recorded by OnInit
series string // the contract's series id, recorded at its first bar
entered string // the trade date of the latest order
}
var (
_ algolang.CapabilityRequirer = (*CloseTimer)(nil)
_ algolang.CalendarRequirer = (*CloseTimer)(nil)
_ algolang.TimerHandler = (*CloseTimer)(nil)
_ algolang.TimerRefusalHandler = (*CloseTimer)(nil)
)
// Name returns the strategy's display name.
func (s *CloseTimer) Name() string { return "closetimer" }
// Description returns a one-sentence summary of the strategy.
func (s *CloseTimer) Description() string {
return "Rests a limit order below the market during the regular session and withdraws it at the RTH close on a session timer, whether or not a bar closes then (order lifetime v2)."
}
// RequiredCapabilities asks for order lifetime v2, which timers need.
func (s *CloseTimer) RequiredCapabilities() []string {
return []string{algolang.CapabilityLifetimeV2}
}
// NeedsCalendar asks for the exchange calendars: the session timer is computed from one.
func (s *CloseTimer) NeedsCalendar() bool { return true }
// OnInit records the traded contract, the run's first instrument.
func (s *CloseTimer) OnInit(_ *algolang.Context, cfg algolang.InitConfig) error {
if len(cfg.Instruments) == 0 {
return errors.New("closetimer: the run configures no instrument")
}
s.symbol = cfg.Instruments[0].Symbol
return nil
}
// OnBar submits the trade date's order at its first bar inside the RTH window and arms the
// timer that withdraws it.
func (s *CloseTimer) OnBar(ctx *algolang.Context, bar algolang.Bar) ([]algolang.Order, error) {
if bar.Symbol != s.symbol {
return nil, nil
}
if s.series == "" {
s.series = bar.SeriesID
if s.series == "" {
s.series = bar.Symbol
}
}
cal, ok := ctx.Calendar(s.symbol)
if !ok {
return nil, fmt.Errorf("closetimer: no exchange calendar serves %s", s.symbol)
}
date, ok := ctRTHDate(cal, bar.CloseTime, s.Lead)
if !ok || date == s.entered {
return nil, nil
}
o := algolang.LimitBuy(s.symbol, int64(s.Qty), bar.Close-s.Distance).Named("LE")
o.TIF = algolang.GTC
o.ClientID = "entry-" + date
if !s.Withdraw {
s.entered = date
ctx.Logf("entry %s: buy %d at %g, left working", o.ClientID, s.Qty, o.Price)
return []algolang.Order{o}, nil
}
at, err := ctx.ArmSessionTimer(ctCloseTimer, s.symbol, algolang.BoundaryRTHClose, -s.Lead)
if err != nil {
// No timer, no order: an order that cannot be withdrawn on time is not placed.
ctx.Logf("no entry on %s: %v", date, err)
return nil, nil
}
s.entered = date
ctx.Logf("entry %s: buy %d at %g, withdrawn at %s", o.ClientID, s.Qty, o.Price, ctTime(at))
return []algolang.Order{o}, nil
}
// OnTimer withdraws the order at the close timer's instant.
func (s *CloseTimer) OnTimer(ctx *algolang.Context, t algolang.TimerFired) ([]algolang.Order, error) {
if t.ID != ctCloseTimer {
return nil, nil
}
age, _ := ctx.DataAge(s.series)
if n := s.withdraw(ctx); n == 0 {
ctx.Logf("timer %s at %s: nothing to withdraw; the newest %s bar closed %s earlier", t.ID, ctTime(t.FiredAt), s.symbol, age)
} else {
ctx.Logf("timer %s at %s: withdrew %d order(s); the newest %s bar closed %s earlier", t.ID, ctTime(t.FiredAt), n, s.symbol, age)
}
return nil, nil
}
// OnTimerRefused withdraws the order at once: the engine will not decide at the close.
func (s *CloseTimer) OnTimerRefused(ctx *algolang.Context, r algolang.TimerRefused) {
ctx.Logf("timer %s refused (%s): %s", r.ID, r.Code, r.Reason)
s.withdraw(ctx)
}
// OnCancelResponse logs the engine's answer to each withdrawal.
func (s *CloseTimer) OnCancelResponse(ctx *algolang.Context, c algolang.CancelResponse) {
ctx.Logf("cancel %s: %s at %s", c.ClientID, c.Outcome, ctTime(c.Timestamp))
}
// OnFill logs each fill.
func (s *CloseTimer) OnFill(ctx *algolang.Context, f algolang.Fill) {
ctx.Logf("fill %s: %d at %g at %s", f.ClientID, f.Quantity, f.Price, ctTime(f.Timestamp))
}
// withdraw cancels every order of the contract that is working and not already being
// cancelled, and returns how many it cancelled. The cancel requests go out with the reply to
// the current decision, or to the next one when it runs outside a decision.
func (s *CloseTimer) withdraw(ctx *algolang.Context) int {
n := 0
for _, w := range ctx.WorkingOrders() {
if w.Order.Symbol != s.symbol || w.Status == algolang.OrderStatusPendingCancel {
continue
}
ctx.Cancel(w.Order.ClientID)
ctx.Logf("withdrawing %s", w.Order.ClientID)
n++
}
return n
}
// ctRTHDate returns the trade date of the bar closing at closeAt and true when it closes inside
// its date's RTH window and at least lead before the window's close, so a timer at the close
// less lead is still ahead of the decision; otherwise false.
func ctRTHDate(cal algolang.Calendar, closeAt time.Time, lead time.Duration) (string, bool) {
date, ok := cal.TradeDate(closeAt.Add(-time.Nanosecond))
if !ok {
return "", false
}
day, ok := cal.Day(date)
if !ok || day.RTH == nil {
return "", false
}
if !closeAt.After(day.RTH.Open) || !closeAt.Before(day.RTH.Close.Add(-lead)) {
return "", false
}
return date, true
}
// ctTime renders an instant in UTC for the log.
func ctTime(t time.Time) string { return t.UTC().Format(time.RFC3339) }
func main() {
if err := algolang.Run(&CloseTimer{}); err != nil {
fmt.Fprintln(os.Stderr, "closetimer:", err)
os.Exit(1)
}
}Previous: Opening-gap continuation: trade the main session · Next: A random exit in the final five minutes of RTH