Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 10 additions & 5 deletions backtest_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ func (s *scriptStrategy) onBar(_ context.Context, b marketdata.Bar) *order {
return nil
}

func (s *scriptStrategy) onBars(ctx context.Context, bars []marketdata.Bar) []*order {
func (s *scriptStrategy) onBars(ctx context.Context, bars []marketdata.Bar) ([]*order, error) {
return eachBar(ctx, bars, s.onBar)
}

Expand Down Expand Up @@ -204,7 +204,7 @@ func (s *cancelStrategy) onBar(ctx context.Context, b marketdata.Bar) *order {
return s.scriptStrategy.onBar(ctx, b)
}

func (s *cancelStrategy) onBars(ctx context.Context, bars []marketdata.Bar) []*order {
func (s *cancelStrategy) onBars(ctx context.Context, bars []marketdata.Bar) ([]*order, error) {
return eachBar(ctx, bars, s.onBar)
}

Expand Down Expand Up @@ -323,7 +323,7 @@ func (s *rejectFirstOpen) onBar(ctx context.Context, b marketdata.Bar) *order {
return o
}

func (s *rejectFirstOpen) onBars(ctx context.Context, bars []marketdata.Bar) []*order {
func (s *rejectFirstOpen) onBars(ctx context.Context, bars []marketdata.Bar) ([]*order, error) {
return eachBar(ctx, bars, s.onBar)
}

Expand Down Expand Up @@ -397,7 +397,7 @@ func (s *seenStrategy) onBar(_ context.Context, b marketdata.Bar) *order {
return nil
}

func (s *seenStrategy) onBars(ctx context.Context, bars []marketdata.Bar) []*order {
func (s *seenStrategy) onBars(ctx context.Context, bars []marketdata.Bar) ([]*order, error) {
return eachBar(ctx, bars, s.onBar)
}

Expand Down Expand Up @@ -519,7 +519,12 @@ func TestBacktestRunSeries_SingleInstrumentMatchesThePerBarRun(t *testing.T) {
}

// first is the first of orders, or nil.
func first(orders []*order) *order {
// first is the first order a strategy's onBars returned, or nil. The strategies it
// wraps cannot fail, so an error is a bug in the test.
func first(orders []*order, err error) *order {
if err != nil {
panic(err)
}
if len(orders) == 0 {
return nil
}
Expand Down
2 changes: 1 addition & 1 deletion emax_backtest_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -645,7 +645,7 @@ func (w *positionWatcher) onBar(ctx context.Context, b marketdata.Bar) *order {
return first(w.strategy.onBars(ctx, []marketdata.Bar{b}))
}

func (w *positionWatcher) onBars(ctx context.Context, bars []marketdata.Bar) []*order {
func (w *positionWatcher) onBars(ctx context.Context, bars []marketdata.Bar) ([]*order, error) {
return eachBar(ctx, bars, w.onBar)
}

Expand Down
42 changes: 42 additions & 0 deletions examples/remote-strategy/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
// Command remote-strategy is a minimal external strategy for Trader: it listens
// on a loopback port, takes each group of bars Trader sends and always answers
// with no orders.
//
// Run it, then point a Trader backtest at the address it prints:
//
// go run ./examples/remote-strategy -addr 127.0.0.1:9100
//
// It serves one connection and exits when Trader closes it. The wire protocol is
// described in package strategy.
package main

import (
"flag"
"fmt"
"log"
"net"
"os"

"github.com/rustyeddy/trader/marketdata"
"github.com/rustyeddy/trader/strategy"
)

func main() {
addr := flag.String("addr", "127.0.0.1:0", "loopback address to listen on")
flag.Parse()

groups := 0
err := strategy.ListenAndServe(*addr,
func(a net.Addr) {
fmt.Println("listening on", a)
}, // for whoever started us
func([]marketdata.Bar) error {
// A real strategy decides here. This one only counts.
groups++
return nil
})
if err != nil {
log.Fatal(err)
}
fmt.Fprintf(os.Stderr, "done: %d groups\n", groups)
}
4 changes: 2 additions & 2 deletions historical_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -406,7 +406,7 @@ type recordingStrategy struct{ calls [][]marketdata.Bar }

func (*recordingStrategy) name() string { return "recording" }
func (*recordingStrategy) init() error { return nil }
func (r *recordingStrategy) onBars(_ context.Context, bars []marketdata.Bar) []*order {
func (r *recordingStrategy) onBars(_ context.Context, bars []marketdata.Bar) ([]*order, error) {
r.calls = append(r.calls, slices.Clone(bars))
return nil
return nil, nil
}
16 changes: 9 additions & 7 deletions strategy.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,14 @@ import (
// strategy decides what to trade. It is called once per availability instant with
// every bar that became available then (the bars are fresh and in instrument
// order; an instrument with no bar at that instant is absent) and returns the
// orders it wants, in the order they should be submitted, or none. It sees the
// orders it wants, in the order they should be submitted, or none, or an error,
// which stops the run before any order is used. It sees the
// whole group before any of its orders is submitted. A single-instrument run is
// the same call with a one-bar group. bars is only valid for the call.
type strategy interface {
name() string
init() error
onBars(ctx context.Context, bars []marketdata.Bar) []*order
onBars(ctx context.Context, bars []marketdata.Bar) ([]*order, error)
}

// warmer is implemented by a strategy that can prefill its indicators. The bars
Expand All @@ -30,15 +31,16 @@ type warmer interface {
}

// eachBar adapts a decision made one bar at a time: it asks decide about every bar
// of the group in order and returns the orders it gave, in that order.
func eachBar(ctx context.Context, bars []marketdata.Bar, decide func(context.Context, marketdata.Bar) *order) []*order {
// of the group in order and returns the orders it gave, in that order. A decision
// that is only a bar-by-bar rule cannot fail, so the error is always nil.
func eachBar(ctx context.Context, bars []marketdata.Bar, decide func(context.Context, marketdata.Bar) *order) ([]*order, error) {
var orders []*order
for _, b := range bars {
if o := decide(ctx, b); o != nil {
orders = append(orders, o)
}
}
return orders
return orders, nil
}

// emax is the EMA crossover strategy: long while the short EMA is above the long
Expand Down Expand Up @@ -77,7 +79,7 @@ func (e *emax) warm(_ context.Context, bars []marketdata.Bar) {
}

// onBars is onBar for each bar of the group.
func (e *emax) onBars(ctx context.Context, bars []marketdata.Bar) []*order {
func (e *emax) onBars(ctx context.Context, bars []marketdata.Bar) ([]*order, error) {
return eachBar(ctx, bars, e.onBar)
}

Expand Down Expand Up @@ -257,7 +259,7 @@ func (s *emaxEach) warm(ctx context.Context, bars []marketdata.Bar) {

// onBars hands each bar to its instrument's emax; the group's orders come back in
// the group's instrument order.
func (s *emaxEach) onBars(ctx context.Context, bars []marketdata.Bar) []*order {
func (s *emaxEach) onBars(ctx context.Context, bars []marketdata.Bar) ([]*order, error) {
return eachBar(ctx, bars, s.onBar)
}

Expand Down
89 changes: 89 additions & 0 deletions strategy/client.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
package strategy

import (
"context"
"errors"
"fmt"
"net"
"os"
"time"

"github.com/rustyeddy/trader/marketdata"
)

// DefaultTimeout is how long Client waits for the worker to answer one group.
const DefaultTimeout = 30 * time.Second

// Client is the trader's end of a connection to a worker.
type Client struct {
// Timeout is how long OnBars waits for an answer; zero means DefaultTimeout.
Timeout time.Duration

conn net.Conn
}

// Dial connects to a worker listening at addr, which must be a loopback address:
// nothing here is authenticated or encrypted.
func Dial(addr string) (*Client, error) {
if err := requireLoopback(addr); err != nil {
return nil, err
}
conn, err := net.DialTimeout("tcp", addr, 5*time.Second)
if err != nil {
return nil, err
}
return &Client{conn: conn}, nil
}

// Close ends the session; the worker sees the connection close and stops.
func (r *Client) Close() error { return r.conn.Close() }

// OnBars sends one group of bars and waits for the answer. It returns an error if
// the worker does not answer within the timeout or ctx ends first, if the
// connection fails, or if the answer holds any orders. After an error the
// connection should be closed.
func (r *Client) OnBars(ctx context.Context, bars []marketdata.Bar) error {
timeout := r.Timeout
if timeout == 0 {
timeout = DefaultTimeout
}
deadline := time.Now().Add(timeout)
if d, ok := ctx.Deadline(); ok && d.Before(deadline) {
deadline = d
}
if err := r.conn.SetDeadline(deadline); err != nil {
return err
}
// Cancelling ctx expires the deadline at once, which wakes a blocked read.
stop := context.AfterFunc(ctx, func() { _ = r.conn.SetDeadline(time.Unix(1, 0)) })
defer stop()

err := r.exchange(bars)
switch {
case err == nil:
return nil
case ctx.Err() != nil:
return ctx.Err()
case errors.Is(err, os.ErrDeadlineExceeded):
// The socket's timer can fire a moment before ctx notices its own deadline.
if d, ok := ctx.Deadline(); ok && !time.Now().Before(d) {
return context.DeadlineExceeded
}
return fmt.Errorf("worker did not answer within %s: %w", timeout, err)
}
return err
}

func (r *Client) exchange(bars []marketdata.Bar) error {
if err := writeMessage(r.conn, barsMessage{Bars: bars}); err != nil {
return fmt.Errorf("sending bars: %w", err)
}
var reply ordersMessage
if err := readMessage(r.conn, &reply); err != nil {
return fmt.Errorf("reading orders: %w", err)
}
if len(reply.Orders) > 0 {
return fmt.Errorf("worker returned %d orders; orders over the wire are not supported yet", len(reply.Orders))
}
return nil
}
Loading
Loading