A cross-exchange trend: New York and London clocks
clocktrend buys one US unit while its own trend and a recent London reference’s trend both rise; otherwise it wants to be flat. Its new concept: different timestamp representations can describe the same instant; different session closes usually describe different instants.
Run the committed, entirely synthetic two-exchange fixture:
bin/algo run \
--adapter bin/file-csv-adapter \
--adapter-inputs Path=docs/examples/cross-exchange.csv,TickSize=0.01,PointValue=1 \
--data-protocol pb --strategy bin/clocktrend --symbols eq:XNAS:MSFT \
--bar-interval 1h \
--date-from 2026-03-06T12:00:00Z --date-to 2026-03-13T19:00:00Z \
--commission-per-share 0.005 --slippage-ticks 1 --cache off \
--fills-json results/learning/clocks-fills.json \
--results-dir results/learning/clocksmake build includes this strategy. It declares eq:XLON:VOD as a data-only reference. The invented hourly sequences are not complete regular sessions; some US observations precede its regular open. Only MSFT receives orders. Separate trend comparisons need no currency conversion; a price-ratio or two-leg spread model would require different assumptions.
Compare instants, preserve local meaning
The CSV writes each exchange’s timestamps with its own offset. Consider these closes, with seconds omitted for readability:
| Date | New York representation | London representation | Common UTC instant |
|---|---|---|---|
| 6 March 2026 | 10:00-05:00 | 15:00+00:00 | 15:00Z |
| 13 March 2026 | 11:00-04:00 | 15:00+00:00 | 15:00Z |
Parse offsets and compare absolute instants with Go’s Time.Equal, Before and After. Use UTC or UnixNano() for timestamp keys. Comparing formatted strings, stripping offsets, or using == on time.Time values with different locations can give the wrong answer.
New York has changed to daylight time in the second row; London has not. Each pair closes simultaneously. A fixed five-hour subtraction would fail. For local display, use IANA locations: America/New_York and Europe/London. The executable embeds time/tzdata; its PrimaryZone and ReferenceZone inputs change display only. In(location) preserves the instant. Offset-free local timestamps can be ambiguous around a daylight-saving fold; resolve that ambiguity at ingestion.
Sample the reference at each US decision
Declare a reference and an aligned view, as in the economic panel:
func (s *ClockTrend) DataRequirements() []algolang.DataRequirement {
return []algolang.DataRequirement{{
SeriesID: "reference", Symbol: s.Reference,
Lookback: s.Window + 1,
Schema: algolang.DataSchemaSpec{
Kind: algolang.Bars, BarKind: algolang.BarsTime,
Interval: s.Interval,
},
}}
}
func (s *ClockTrend) AlignedSeries() []algolang.AlignedSeries {
return []algolang.AlignedSeries{{
SeriesID: "reference_on_primary", Source: "reference",
}}
}It decides only when ctx.IsPrimary(bar) is true. For these ordinary price bars, a reference closing at the same instant is available before the primary decision. This is distinct from the release-stamped tie rule discussed earlier. The aligned view also carries the last known reference across gaps.
After checking that the view contains a sample, check its clocks:
sample := view.Bar(0)
if !sample.CloseTime.Equal(bar.CloseTime) ||
sample.SourceCloseTime.After(bar.CloseTime) {
return nil, fmt.Errorf("reference view is not causal at %s", bar.CloseTime)
}
age := bar.CloseTime.Sub(sample.SourceCloseTime)CloseTime is the aligned grid timestamp. SourceCloseTime is the close of the London observation carried into that grid row. Measuring age from the grid timestamp would always produce zero and would disguise stale data. The default MaxAge=90m permits a one-hour carry and refuses a two-hour carry. Missing data also requests a flat target; the strategy does not leave an existing holding unmanaged simply because a reference disappeared.
The trend compares each latest close with its close two native bars earlier (Window=2), requiring three actual bars per source. A three-row aligned trend could repeat one London close three times. Orders reconcile a target of one or zero against the actual primary position, waiting for unresolved orders before submitting another.
Inspect the gap and the unseen future
On 6 March at 16:00Z, both trends are ready and rising: the strategy submits a buy. At 17:00Z, London’s latest close is still 16:00Z, one hour old, so it holds. At 18:00Z, that observation is two hours old and it submits an exit. The fill records show four one-unit fills over the two dates:
| Decision, UTC | Following primary bar, UTC | Action | Fill price |
|---|---|---|---|
| 6 March, 16:00 | 6 March, 17:00 | Buy | 102.51 |
| 6 March, 18:00 | 6 March, 19:00 | Sell | 104.49 |
| 13 March, 14:00 | 13 March, 15:00 | Buy | 110.51 |
| 13 March, 16:00 | 13 March, 17:00 | Sell | 112.49 |
The following bar’s open supplies the market fill price; the bar timestamp in the fill record is its close. Each fill includes one tick of adverse slippage and 0.005 commission. These numbers verify mechanics on invented prices, not an investment result.
On 13 March the London price falls from 62 to 10 at 16:00Z. At the preceding 15:00Z US decision, the log must still say reference_close=62 target=1. At 16:00Z, it says reference_close=10 target=0. Seeing 10 at 15:00Z would expose lookahead. make strategy-guide-smoke checks these decisions, staleness and fills, then rewrites every input timestamp in UTC and verifies that the results are unchanged.
Move from the fixture to real exchanges
With marketfeed, verify both instruments’ coverage; this fixture does not establish their availability. Request appropriate sessions and calendars for each series. Let the feed supply timestamped bars, and use calendars for session boundaries, holidays and early closes, as later chapters demonstrate.
Two exchanges’ daily closing bars need not represent the same instant even when their local trade dates match. At the earlier close, the later market’s final daily bar is still unavailable. Choose an explicit decision clock and use the latest completed observation known then, with a stated age limit, or wait until both have closed. Timezone conversion cannot make genuinely different closes simultaneous. Joining by local date or row number cannot establish causality.
The 90-minute cutoff counts elapsed time across closures. A calendar-aware policy could distinguish expected holidays from missing data. To trade both legs, also define currency conversion, tick and point values, session order eligibility, and a response when only one leg fills. The ES/NQ spread introduces that order problem. On a live feed, co-closing peers are waited for up to two seconds; a late peer can arrive after the primary decision. Its later arrival cannot repair the earlier decision. Log the actual source timestamp and keep the age rule. Source to study: strategies/demo/go/clocktrend/main.go and docs/examples/cross-exchange.csv.
Complete source: clocktrend
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.
OnInitvalidates the clocks and inputs.OnBarkeeps the reference and primary roles separate even when both arrive at the same instant.The decision compares absolute close times and enforces a maximum reference age. New York and London display times are for the audit log, not the ordering test.
The target becomes flat when the reference is stale. The fixture includes unequal UTC offsets, a daylight-saving transition and an unavailable future observation.
Build the supplied files directly:
go build -o bin/clocktrend ./strategies/demo/go/clocktrend
bin/clocktrend --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.
clocktrend/main.go
// Command clocktrend demonstrates cross-exchange timestamp alignment. It trades
// the primary instrument when both its trend and a reference instrument's trend
// are up, provided the reference's latest completed bar is recent enough.
//
// The aligned view samples the reference as known at each primary decision;
// SourceCloseTime, not the view's grid timestamp, measures staleness. Each trend
// uses bars on its own native clock, avoiding repeated carried samples. IANA
// locations affect logging only: all comparisons use absolute time instants.
package main
import (
"fmt"
"os"
"time"
_ "time/tzdata"
algolang "MODULE/sdk/strategy"
)
var buildID string
type ClockTrend struct {
Reference string `algolang:"default=eq:XLON:VOD,desc=Data-only reference instrument"`
Interval string `algolang:"default=1h,desc=Reference bar interval"`
Window int `algolang:"default=2,min=1,max=500,desc=Native bars back for each trend"`
MaxAge time.Duration `algolang:"default=90m,min=0s,desc=Maximum age of the reference bar at a decision"`
PrimaryZone string `algolang:"default=America/New_York,desc=Primary display timezone"`
ReferenceZone string `algolang:"default=Europe/London,desc=Reference display timezone"`
primaryLocation, referenceLocation *time.Location
}
func (s *ClockTrend) Name() string { return "Cross-exchange clock trend" }
func (s *ClockTrend) Description() string {
return "Long one primary unit while both native trends rise and the as-of reference is recent; flat otherwise."
}
func (s *ClockTrend) RequiredCapabilities() []string {
return []string{algolang.CapabilityLifetimeV2}
}
// OneBarRule lets the engine end eligible resting orders after the next bar.
func (s *ClockTrend) OneBarRule() bool { return true }
func (s *ClockTrend) Lookback() int { return s.Window + 1 }
func (s *ClockTrend) OnInit(_ *algolang.Context, _ algolang.InitConfig) error {
var err error
if s.primaryLocation, err = time.LoadLocation(s.PrimaryZone); err != nil {
return fmt.Errorf("primary display timezone: %w", err)
}
if s.referenceLocation, err = time.LoadLocation(s.ReferenceZone); err != nil {
return fmt.Errorf("reference display timezone: %w", err)
}
return nil
}
func (s *ClockTrend) DataRequirements() []algolang.DataRequirement {
return []algolang.DataRequirement{{
SeriesID: "reference", Symbol: s.Reference, Lookback: s.Window + 1,
Schema: algolang.DataSchemaSpec{
Kind: algolang.Bars, BarKind: algolang.BarsTime, Interval: s.Interval,
},
}}
}
func (s *ClockTrend) AlignedSeries() []algolang.AlignedSeries {
return []algolang.AlignedSeries{{SeriesID: "reference_on_primary", Source: "reference"}}
}
func (s *ClockTrend) OnBar(ctx *algolang.Context, bar algolang.Bar) ([]algolang.Order, error) {
if !ctx.IsPrimary(bar) {
return nil, nil
}
primary := ctx.Series(ctx.PrimarySymbol())
reference := ctx.Series("reference")
view := ctx.Series("reference_on_primary")
var target int64
if view.Len() > 0 {
sample := view.Bar(0)
if !sample.CloseTime.Equal(bar.CloseTime) || sample.SourceCloseTime.After(bar.CloseTime) {
return nil, fmt.Errorf("reference view is not causal at %s", bar.CloseTime)
}
age := bar.CloseTime.Sub(sample.SourceCloseTime)
ready := primary.Len() > s.Window && reference.Len() > s.Window
if ready && age <= s.MaxAge && primary.Close(0) > primary.Close(s.Window) &&
reference.Close(0) > reference.Close(s.Window) {
target = 1
}
ctx.Logf("clocktrend at=%s primary_local=%s reference_local=%s source=%s age=%s reference_close=%g target=%d",
bar.CloseTime.UTC().Format(time.RFC3339),
bar.CloseTime.In(s.primaryLocation).Format(time.RFC3339),
sample.SourceCloseTime.In(s.referenceLocation).Format(time.RFC3339),
sample.SourceCloseTime.UTC().Format(time.RFC3339), age, sample.Close, target)
} else {
ctx.Logf("clocktrend at=%s source=missing target=0", bar.CloseTime.UTC().Format(time.RFC3339))
}
// A missing/stale reference wants flat, including when a holding already
// exists. Let any unresolved market order settle before sending another.
exposure := ctx.Exposure(bar.Symbol)
if len(exposure.WorkingOrders) != 0 {
return nil, nil
}
delta := target - ctx.Position(bar.Symbol).Quantity
if delta == 0 {
return nil, nil
}
o := algolang.MarketBuy(bar.Symbol, delta).Named("LE")
if delta < 0 {
o = algolang.MarketSell(bar.Symbol, -delta).Named("LX")
}
o.ClientID = fmt.Sprintf("clocktrend_%d", bar.CloseTime.UnixNano())
return []algolang.Order{o}, nil
}
func main() {
if err := algolang.Run(&ClockTrend{}); err != nil {
fmt.Fprintln(os.Stderr, "clocktrend:", err)
os.Exit(1)
}
}Previous: A trend using an aligned economic panel · Next: Triple Screen: completed weeks and resting stops