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
59 changes: 42 additions & 17 deletions examples/remote-strategy/main.go
Original file line number Diff line number Diff line change
@@ -1,16 +1,18 @@
// Command remote-strategy is a tiny external strategy for Trader. It listens on a
// loopback port and, for every group of bars Trader sends, applies one fixed
// rule: open a long position in the first bar's instrument on the third group,
// with a stop a fixed distance below the close, and close it on the sixth. It
// asks only; Trader sizes the order, applies the account's risk rules and fills
// it.
// with a stop a fixed distance below the close, and close it on the sixth, but
// only if Trader has told it the entry filled and the stop has not already taken
// it out. It asks only; Trader sizes the order, applies the account's risk rules
// and fills it, and reports what it did with the next group.
//
// 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.
// It prints each event Trader reports to standard error. It serves one
// connection and exits when Trader closes it. The wire protocol is described in
// package strategy.
package main

import (
Expand All @@ -27,47 +29,70 @@ import (

const (
openAt = 3 // open on this group...
closeAt = 6 // ...and close on this one
closeAt = 6 // ...and close on this one, if still in
)

// entryRef labels the opening order, so its events can be recognised.
const entryRef = "entry"

// stopDistance is how far below the entry the stop goes.
var stopDistance = num.MustParsePrice("0.015")

// worker is the strategy's memory: how many groups it has seen and whether it is
// in a position, as far as Trader has said.
type worker struct {
groups int
inPosition bool
}

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

groups := 0
w := &worker{}
err := strategy.ListenAndServe(*addr,
func(a net.Addr) { fmt.Println("listening on", a) }, // for whoever started us
func(bars []marketdata.Bar) ([]strategy.Order, error) {
groups++
return decide(groups, bars)
func(bars []marketdata.Bar, events []strategy.Event) ([]strategy.Order, error) {
for _, e := range events {
fmt.Fprintf(os.Stderr, "event: %s %s %s %s %s ref=%q id=%q reason=%q\n",
e.Time.Format("2006-01-02"), e.Kind, e.Action, e.Instrument, e.Cause, e.Ref, e.ID, e.Reason)
}
return w.decide(bars, events)
})
if err != nil {
log.Fatal(err)
}
fmt.Fprintf(os.Stderr, "done: %d groups\n", groups)
fmt.Fprintf(os.Stderr, "done: %d groups\n", w.groups)
}

// decide is the whole strategy: the orders to request on the n-th group of bars.
func decide(n int, bars []marketdata.Bar) ([]strategy.Order, error) {
// decide is the whole strategy: what Trader reported, then the orders to request
// on the next group of bars.
func (w *worker) decide(bars []marketdata.Bar, events []strategy.Event) ([]strategy.Order, error) {
for _, e := range events {
switch {
case e.Ref == entryRef && e.Kind == strategy.Filled:
w.inPosition = true
case e.Kind == strategy.Filled && e.Cause == "stop loss":
w.inPosition = false // the protective stop took us out
}
}
w.groups++
if len(bars) == 0 {
return nil, nil
}
b := bars[0]
closePrice := b.OHLC().Close
switch n {
case openAt:
switch {
case w.groups == openAt:
stop, err := closePrice.Sub(stopDistance)
if err != nil {
return nil, err
}
return []strategy.Order{{
Instrument: b.Instrument, Action: "open", Direction: "long",
Price: closePrice, StopLoss: stop,
Price: closePrice, StopLoss: stop, Ref: entryRef,
}}, nil
case closeAt:
case w.groups == closeAt && w.inPosition:
return []strategy.Order{{Instrument: b.Instrument, Action: "close", Price: closePrice}}, nil
}
return nil, nil
Expand Down
122 changes: 122 additions & 0 deletions feedback.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
package trader

import (
"slices"

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

// feedbackEvent is one entry of an order's history, with the order it belongs to.
type feedbackEvent struct {
order *order
orderEvent
}

// feedbacker is implemented by a strategy that wants to be told what the trader
// did with its orders. The trader calls feedback once per frame, just before
// onBars, with the events that happened since the last call, in the order they
// happened. They are the broker's work on the frame about to be shown to the
// strategy and the outcome of the orders it asked for in the previous call; never
// the outcome of the orders it is about to return. A strategy that does not
// implement it is simply not told.
type feedbacker interface {
feedback(events []feedbackEvent)
}

// feedbackLog remembers what has been told to a feedbacker, so that each event is
// delivered once.
type feedbackLog struct {
watched []*order // the strategy's orders whose history is not all delivered
sent map[*order]int // how many history entries of each were delivered
exitsSeen int // how much of broker.completed was looked at for the broker's own exits
}

// watch starts following a strategy's order.
func (tr *trader) watch(o *order) {
if _, ok := tr.strategy.(feedbacker); ok {
tr.feedbackLog.watched = append(tr.feedbackLog.watched, o)
}
}

// reported says whether a state is one the strategy is told about. Requested and
// sized are the trader's own steps on the way to accepted.
func reported(s orderState) bool {
switch s {
case stateSubmitted, stateFilled, stateRejected, stateCancelled:
return true
}
return false
}

// collectEvents returns what the strategy has not yet been told, in the order it
// happened (by time; on a tie the strategy's own orders come before the broker's
// exits, which is how they happen on one bar), and marks it told. It reports:
//
// - the submitted, filled, rejected and cancelled steps of the strategy's orders;
// - the broker's own exits (protective stop, take profit, margin closeout) when
// they fill. Their other steps are the broker's housekeeping and are not
// reported.
func (tr *trader) collectEvents() []feedbackEvent {
log := &tr.feedbackLog
if log.sent == nil {
log.sent = make(map[*order]int)
}
var events []feedbackEvent
for _, o := range log.watched {
for _, e := range o.history[log.sent[o]:] {
if reported(e.state) {
events = append(events, feedbackEvent{o, e})
}
}
log.sent[o] = len(o.history)
}
log.watched = slices.DeleteFunc(log.watched, func(o *order) bool {
done := o.state == stateFilled || o.state == stateRejected || o.state == stateCancelled
if done {
delete(log.sent, o)
}
return done
})

for _, o := range tr.broker.completed[log.exitsSeen:] {
if o.accountID == tr.account.id && o.reason != reasonStrategy && o.state == stateFilled {
events = append(events, feedbackEvent{o, o.history[len(o.history)-1]})
}
}
log.exitsSeen = len(tr.broker.completed)

slices.SortStableFunc(events, func(a, b feedbackEvent) int { return a.time.Compare(b.time) })
return events
}

// toWireEvent maps an event onto the public form. ref is the worker's label for
// the order, empty for the broker's own orders.
func toWireEvent(e feedbackEvent, ref string) remotestrat.Event {
o := e.order
w := remotestrat.Event{
Time: e.time,
ID: o.id,
Ref: ref,
Instrument: o.instrument,
Action: o.action.String(),
Units: o.units,
Cause: o.reason.String(),
}
if o.direction != noDirection {
w.Direction = o.direction.String()
}
switch e.state {
case stateSubmitted:
w.Kind = remotestrat.Accepted
case stateFilled:
w.Kind = remotestrat.Filled
w.Price = o.fillPrice
case stateRejected:
w.Kind = remotestrat.Rejected
w.Reason = e.reason
case stateCancelled:
w.Kind = remotestrat.Cancelled
w.Reason = e.reason
}
return w
}
Loading
Loading