A channel breakout with an attached bracket

A channel breakout with an attached bracket

bracket enters above a channel high and attaches a profit target and a protective stop to that entry. Once the parent fills, its exits work as an OCO pair: one exit filling cancels the other. This closes the entry-bar protection gap in the preceding recipe.

Start with six synthetic minute bars whose third bar reaches both exits:

bin/algo run \
  --adapter bin/file-csv-adapter \
  --adapter-inputs Path=docs/examples/bracket.csv,TickSize=0.01,PointValue=1 \
  --data-protocol pb --strategy bin/bracket --symbols TEST \
  --bar-interval 1m --lifetime v2 --inputs Channel=1,ATR=1,Expire=2 \
  --commission-per-share 0.005 --slippage-ticks 1 \
  --bracket-ambiguity conservative --cache off \
  --fills-json results/learning/bracket-fills.json \
  --lifecycle-json results/learning/bracket-life.json \
  --results-dir results/learning/bracket

Channel=1,ATR=1 makes the arithmetic inspectable, not a proposed trading setting. The defaults use a 10-bar channel and 14-bar ATR. Flat with nothing working, the strategy places its buy stop one tick above the channel, with a target two ATRs above the entry and a stop one ATR below it. The essential construction, after calculating and rounding those levels, is:

parent := algolang.Order{
    Symbol: sym, Side: algolang.Buy, Quantity: int64(s.Lots),
    Type: algolang.Stop, StopPrice: entry,
    TIF: algolang.GTC, ClientID: name,
}
return []algolang.Order{
    algolang.Bracket(parent.Named("Breakout LE"), target, stop),
}, nil

The demo reads actual positions and working orders rather than remembering that it intended to enter. It waits while a bracket exists. If still flat after Expire bars, it cancels the unfilled parent; its held children end with it. After an entry, the attached orders manage the exit. The parent is GTC: enabling the engine’s Day one-bar rule alone would not alter this policy. For a one-bar variant, give the parent TIF: algolang.Day, OneBar: true and let the engine own that expiry instead of the demo’s manual timeout. The children remain exempt from the one-bar rule once active.

Trace protection and ambiguity

At 14:32Z the fixture produces an entry stop at 102.01, target at 106.01 and protective stop at 100.01. The following bar reaches both exits. Under conservative, the entry fills at 102.02 including slippage and the stop fills at 100.00. Each fill charges 0.005 commission. The target’s cancellation names the filled stop as its trigger. The next parent remains unfilled and is cancelled after two bars, taking its held children with it.

Repeat with --bracket-ambiguity optimistic and a different output directory: the same bar takes the 106.01 target. That difference is a modeling assumption, not evidence about the actual path. Compare path_direction too, or use a supported finer path when the archive has it. The smoke check verifies the two outcomes, child-to-parent fill identity and OCO cancellations.

Use Fill.ParentClientID to connect an exit to its entry, and OrderCancel.TriggeredBy to identify the OCO winner. Do not count the cancelled sibling as an additional trade. Nor does cancelling an unfilled entry mean that an existing holding has been flattened.

Carry the bracket to a desk deliberately

A live member can now send supported brackets to a desk using protocol 9 or later. Its broker port must accept them. Children must be one level deep, on the parent’s symbol and opposite side, and no larger than the parent. Supported children are limit, stop, stop-limit or trailing-stop orders with Day or GTC lifetime and no independent expiry fields. Live MOC orders cannot carry children. The direct IBKR Web API and emulator paths still refuse brackets; desk support does not remove that distinction.

An important live case cannot be inferred from this whole-fill simulation: a parent may fill partly, and a child may execute for that part before the parent finishes. If the parent then cancels or expires, its children remain working for the filled quantity, reduced by their own fills. They do not receive PARENT_CANCELLED merely because the parent ended. If the parent filled nothing, its held children end with it. Read the resulting working quantities instead of deleting all child state on any parent cancellation. The demo’s Expire branch runs only while the position is flat; it is not a general timeout for a partially filled live parent.

To withdraw a held bracket, cancel the parent; cancelling its inactive child is refused. Modifying a child uses cancellation and replacement rather than an in-place change. Test partial fills, still-pending cancels and restart adoption before extending this recipe to a live account. The existing desk tests cover these mechanics; the small fixture above covers the backtest. Source to study: strategies/demo/go/bracket/main.go, engine/gle1609_bracket_demo_e2e_test.go and the technical manual’s desk chapter.

Complete source: bracket

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. The channel and ATR inputs determine a breakout parent and its attached profit and stop children. Their parent link and OCO relationship are execution instructions.

  2. The unfilled parent has an explicit age policy. Cancelling it before any fill removes its dependent children; a partially filled live parent needs protection for the filled quantity.

  3. OnFill and OnCancel report the outcome. Use the chapter’s conservative and optimistic runs to see why an OHLC bar alone cannot establish which child was touched first.

Build the supplied files directly:

go build -o bin/bracket ./strategies/demo/go/bracket
bin/bracket --algolang-selftest

bracket/main.go

// Command bracket is the demo of a bracket order (GLE-1609): one order that
// opens a position, its parent, with two attached orders that close it, a
// target and a stop. The venue holds the attached orders until the parent
// fills, then works them as one OCO pair: the first to fill cancels the
// other. IBKR places the same bracket: a parent and two attached children in
// one OCA group. The demo trades one symbol, long only:
//
//   - flat with nothing working, it places a bracket: a buy stop one tick
//     above the highest high of the last Channel bars, a limit sell
//     TargetATR average true ranges above that entry and a stop sell StopATR
//     below it;
//   - a parent that has not filled after Expire bars is cancelled by name,
//     and its attached orders end with it (cancel reason PARENT_CANCELLED);
//   - once the parent fills, the target or the stop closes the position.
//     A bar that reaches both is settled by the run's bracket-ambiguity.
//
// Every fill and cancel is logged with the parent of an attached order and,
// for the order an OCO fill cancelled, the order that filled. A backtest and
// a member on a desk's SIM clock log the same lines. Under lifetime v2 or v1
// alike; the demo places no stop of its own beyond the bracket's.
package main

import (
    "fmt"
    "math"
    "os"
    "time"

    "MODULE/indicators"
    algolang "MODULE/sdk/strategy"
)

// buildID is stamped by the Makefile via -ldflags.
var buildID string

// Bracket is the strategy: its inputs. It keeps no state of its own: what
// it decides comes from the bars, its position and its working orders, so a
// restart resumes it.
type Bracket struct {
    Lots      int     `algolang:"default=1,min=1,desc=Contracts or shares to buy"`
    Channel   int     `algolang:"default=10,min=1,max=400,desc=The bars whose highest high the entry stop is placed above"`
    ATR       int     `algolang:"default=14,min=1,max=400,desc=The average true range's period in bars"`
    TargetATR float64 `algolang:"default=2,min=0.1,desc=The target's distance above the entry, in average true ranges"`
    StopATR   float64 `algolang:"default=1,min=0.1,desc=The stop's distance below the entry, in average true ranges"`
    Expire    int     `algolang:"default=5,min=1,max=400,desc=Bars after which a parent that has not filled is cancelled"`
    Tick      float64 `algolang:"default=0,min=0,desc=The price increment; 0 takes the instrument's tick size, and 0.01 when it has none"`
}

func (s *Bracket) Name() string { return "Bracket" }

func (s *Bracket) Description() string {
    return "Buys a channel breakout with a bracket: a stop entry with an attached target and stop that work as one OCO pair once it fills."
}

// SupportedCapabilities declares order lifetime v2: the decisions read the
// position and the working orders alone, the same under either profile.
func (s *Bracket) SupportedCapabilities() []string {
    return []string{algolang.CapabilityLifetimeV2}
}

// Lookback keeps the channel, the average true range and the bars a parent
// may wait.
func (s *Bracket) Lookback() int { return max(s.Channel, s.ATR+1, s.Expire+1) + 1 }

// OnBar decides on each bar of the primary symbol.
func (s *Bracket) OnBar(ctx *algolang.Context, bar algolang.Bar) ([]algolang.Order, error) {
    if !ctx.IsPrimary(bar) {
        return nil, nil
    }
    sym := bar.Symbol
    id := bar.SeriesID
    if id == "" {
        id = sym
    }
    series := ctx.Series(id)
    if series.Len() < max(s.Channel, s.ATR+1) {
        return nil, nil
    }
    exposure := ctx.Exposure(sym)
    if exposure.Position.Quantity != 0 {
        return nil, nil // the bracket's target or stop closes it
    }
    if p, ok := parentOf(exposure.WorkingOrders); ok {
        if waited := barsSince(series, p.SubmittedAt); waited >= s.Expire {
            ctx.Logf("bracket: %s parent %s unfilled after %d bars: cancelling it", stamp(bar.CloseTime), p.Order.ClientID, waited)
            ctx.Cancel(p.Order.ClientID)
        }
        return nil, nil
    }
    if len(exposure.WorkingOrders) > 0 {
        return nil, nil // the last bracket's children are still ending
    }

    tick := s.Tick
    if tick == 0 {
        tick = ctx.Instrument(sym).TickSize
    }
    if tick == 0 {
        tick = 0.01
    }
    ohlc := indicators.FromSeries(series)
    atr := ohlc.Close.ATR(ohlc.High, ohlc.Low, ohlc.Close, s.ATR).Value()
    high := series.High(0)
    for i := 1; i < s.Channel; i++ {
        high = max(high, series.High(i))
    }
    entry := onTick(high+tick, tick)
    target, stop := onTick(entry+s.TargetATR*atr, tick), onTick(entry-s.StopATR*atr, tick)
    if !(stop < entry && entry < target) {
        return nil, nil // a range too narrow for the ticks
    }
    name := "b-" + bar.CloseTime.UTC().Format("20060102T150405")
    ctx.Logf("bracket: %s buy %d %s above %v: entry stop %v, target %v, stop %v", stamp(bar.CloseTime), s.Lots, sym, high, entry, target, stop)
    parent := algolang.Order{Symbol: sym, Side: algolang.Buy, Quantity: int64(s.Lots), Type: algolang.Stop, StopPrice: entry,
        TIF: algolang.GTC, ClientID: name}
    return []algolang.Order{algolang.Bracket(parent.Named("Breakout LE"), target, stop)}, nil
}

// OnFill logs a fill, an attached order's with its parent.
func (s *Bracket) OnFill(ctx *algolang.Context, f algolang.Fill) {
    line := fmt.Sprintf("bracket: %s fill %s %s %d @ %v", stamp(f.Timestamp), f.ClientID, side(f.Side), f.Quantity, f.Price)
    if f.ParentClientID != "" {
        line += " (parent " + f.ParentClientID + ")"
    }
    ctx.Logf("%s", line)
}

// OnCancel logs a cancel with its reason and, for an OCO cancel, the order
// whose fill made it.
func (s *Bracket) OnCancel(ctx *algolang.Context, c algolang.OrderCancel) {
    line := fmt.Sprintf("bracket: %s cancel %s %s", stamp(c.Timestamp), c.ClientID, reason(c.Reason))
    if c.TriggeredBy != "" {
        line += " (by " + c.TriggeredBy + ")"
    }
    ctx.Logf("%s", line)
}

// parentOf is the bracket's parent among the working orders: the buy stop
// with no parent of its own.
func parentOf(working []algolang.WorkingOrder) (algolang.WorkingOrder, bool) {
    for _, w := range working {
        if w.Order.Side == algolang.Buy && w.Order.Type == algolang.Stop && w.ParentClientID == "" {
            return w, true
        }
    }
    return algolang.WorkingOrder{}, false
}

// barsSince is how many of the series' bars closed after at, its newest
// first; every bar the series holds when at is zero (an adopted order with
// no submit time).
func barsSince(series algolang.Series, at time.Time) int {
    n := 0
    for i := 0; i < series.Len() && series.Bar(i).CloseTime.After(at); i++ {
        n++
    }
    return n
}

// onTick is price on the tick grid, nearest.
func onTick(price, tick float64) float64 {
    return math.Round(math.Round(price/tick)*tick*1e9) / 1e9
}

func stamp(t time.Time) string { return t.UTC().Format(time.RFC3339) }

func side(s algolang.Side) string {
    if s == algolang.Sell {
        return "sell"
    }
    return "buy"
}

// reason names a cancel reason.
func reason(r algolang.CancelReason) string {
    switch r {
    case algolang.CancelReasonOCOTriggered:
        return "oco"
    case algolang.CancelReasonTIFExpired:
        return "tif-expired"
    case algolang.CancelReasonExplicit:
        return "explicit"
    case algolang.CancelReasonRejected:
        return "rejected"
    case algolang.CancelReasonShutdown:
        return "shutdown"
    case algolang.CancelReasonParentCancelled:
        return "parent-cancelled"
    case algolang.CancelReasonGTCExpired:
        return "gtc-expired"
    case algolang.CancelReasonVenue:
        return "venue"
    }
    return fmt.Sprintf("reason-%d", r)
}

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

Previous: Triple Screen: completed weeks and resting stops · Next: Opening-gap continuation: trade the main session