order

package
v1.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 17, 2026 License: MIT Imports: 22 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrBotStopped = errors.New("bot is stopped")

ErrBotStopped is returned by CreateOrder* when the controller has been stopped. Cancel is intentionally not gated, so open orders can still be cleaned up, nor are the protections of the positions: they are refused, ErrBotStopped too, only once the controller is closed, see Close.

View Source
var ErrEntriesBlocked = errors.New("the entries of the bot are blocked")

ErrEntriesBlocked is returned by the orders that would open a position, or add to one, while the entries of the bot are blocked (see BlockEntries) or held (see HoldEntries): the bot only reduces what it holds then.

View Source
var ErrNoPosition = errors.New("no position held")

ErrNoPosition is the error of a stop loss set on a position not held.

Functions

func StopLevel

func StopLevel(leg model.Order) float64

StopLevel returns the level of a stop loss leg: its stop, else its price.

Types

type Controller

type Controller struct {
	Results map[string]*summary // under mtx while the bot runs, see Summaries
	// contains filtered or unexported fields
}

Controller creates the orders of the strategies on the exchange, stores them and follows them until they fill or are canceled, settling the positions and the results of their pairs.

The orders of a pair are serialized, each one from its call to the exchange to its recording (see lockPair), but nothing else waits for the exchange: a slow call, eg: an MT5 trade request whose answer was lost, looked for in the account, holds the orders of its pair only, while UpdateOrders, the reads and the orders of the other pairs go on.

The states of an order are recorded under mtx, never one older than the one recorded: an end (filled, canceled, rejected, expired) is never undone by a move or a cancel answered after it (see record), nor a move by a state UpdateOrders read before it (see updateOrders); the order feed takes them in the order they are recorded (see publish).

func NewController

func NewController(ctx context.Context, exchange service.Exchange, storage storage.Storage,
	orderFeed *Feed) *Controller

func (*Controller) Account

func (c *Controller) Account() (model.Account, error)

func (*Controller) AccountSummary

func (c *Controller) AccountSummary() (service.AccountSummary, bool)

AccountSummary returns the account as the broker reports it, in its currency, when it does (see service.AccountReporter): for the display.

func (*Controller) AllowEntries

func (c *Controller) AllowEntries(revision int64) bool

AllowEntries allows the entries blocked by BlockEntries again, at revision, unless it is older than the one of the last change (false); the holds of HoldEntries stay.

func (*Controller) BlockEntries

func (c *Controller) BlockEntries(revision int64, reason string) bool

BlockEntries blocks the entries of the bot, for reason, at revision, until AllowEntries: the orders that would open a position or add to one are refused (ErrEntriesBlocked), a market order against a position is sent as one that only reduces it (see service.ReduceOnlyBroker), and the protections of the positions, their cancels and the following of the orders go on. A revision older than the one of the last change is ignored, eg: a runtime read before a newer one applied, and reported false.

func (*Controller) Cancel

func (c *Controller) Cancel(order model.Order) error

Cancel cancels an order, on a stopped bot too, not once the controller is closed (see Close): pending cancel until the exchange tells it canceled, unless it ended meanwhile, see record.

func (*Controller) Close

func (c *Controller) Close()

Close stops the controller for good, as the bot exits (see XTrader.Run): it stops (see Stop), then nothing reaches the exchange any more, the protections of the positions, their moves and the cancels refused too (ErrBotStopped), once the calls begun are recorded; the pending orders are updated a last time, and never after. What the exchange did is then all handed to the storage, eg: an outbox about to be closed. Start never starts it again.

func (*Controller) ClosePosition

func (c *Controller) ClosePosition(pair string) (model.Order, error)

ClosePosition closes the whole position the bot holds on pair at the market, never opening the other side (see service.ReduceOnlyBroker), its stop loss and take profit going with it, on a stopped bot too, not once the controller is closed (see Close): the way the supervisor of the agents closes a position, whatever the entries, see ui.Chart. It returns an error wrapping exchange.ErrNothingToReduce when the bot holds none.

func (*Controller) ClosesProtected

func (c *Controller) ClosesProtected() bool

ClosesProtected reports whether a market order of the exchange closes a protected position with its legs in place, see service.ProtectedCloser.

func (*Controller) CreateOrderLimit

func (c *Controller) CreateOrderLimit(side model.SideType, pair string, size, limit float64) (model.Order, error)

func (*Controller) CreateOrderLimitProtected

func (c *Controller) CreateOrderLimitProtected(side model.SideType, pair string, size, limit, stop,
	profit float64) ([]model.Order, error)

CreateOrderLimitProtected places a limit order opening a position with its stop loss and take profit, see CreateOrderMarketProtected.

func (*Controller) CreateOrderMarket

func (c *Controller) CreateOrderMarket(side model.SideType, pair string, size float64) (model.Order, error)

func (*Controller) CreateOrderMarketProtected

func (c *Controller) CreateOrderMarketProtected(side model.SideType, pair string, size, stop,
	profit float64) ([]model.Order, error)

CreateOrderMarketProtected opens a position at the market with its stop loss and take profit, placed with the order when the exchange supports it, see service.ProtectionBroker. The entry and the legs are stored and followed as any other order.

func (*Controller) CreateOrderMarketQuote

func (c *Controller) CreateOrderMarketQuote(side model.SideType, pair string, amount float64) (model.Order, error)

func (*Controller) CreateOrderOCO

func (c *Controller) CreateOrderOCO(side model.SideType, pair string, size, price, stop,
	stopLimit float64) ([]model.Order, error)

func (*Controller) CreateOrderStop

func (c *Controller) CreateOrderStop(pair string, size float64, limit float64) (model.Order, error)

func (*Controller) CreateOrderStopProtected

func (c *Controller) CreateOrderStopProtected(side model.SideType, pair string, size, level, stop,
	profit float64) ([]model.Order, error)

CreateOrderStopProtected places a stop order opening a position with its stop loss and take profit, see CreateOrderMarketProtected.

func (*Controller) EntriesBlocked

func (c *Controller) EntriesBlocked() (blocked bool, reason string, revision int64)

EntriesBlocked reports whether the entries are refused, blocked or held, why, and the revision of their last block or allowance.

func (*Controller) HeldLegs

func (c *Controller) HeldLegs(pair string, side model.SideType) ([]model.Order, time.Time, error)

HeldLegs returns the open legs of the position held on side of pair, and when it opened, zero when unknown, see service.PositionLegs: from the orders the controller stores, in the state it follows them, a restart included (the positions replayed from the stored fills, see restore). A leg is an open order of a group on the other side, protecting the entry of the position: as the exchange tells it, when it knows both (see fillPositions), else placed after it, never one of an older entry, eg: of a position closed by its stop loss whose exit isn't booked yet. Any, with the entry unknown.

func (*Controller) HeldPosition

func (c *Controller) HeldPosition(pair string) (Position, bool)

HeldPosition returns the position held on pair as the controller follows it, false when flat.

func (*Controller) HoldEntries

func (c *Controller) HoldEntries(reason string) (release func())

HoldEntries refuses the entries as BlockEntries does until release, eg: as the positions are closed, so that none opens meanwhile, whatever the blocks; release may be called more than once.

func (*Controller) LastQuote

func (c *Controller) LastQuote(pair string) (float64, error)

func (*Controller) OnCandle

func (c *Controller) OnCandle(candle model.Candle)

func (*Controller) Order

func (c *Controller) Order(pair string, id int64) (model.Order, error)

func (*Controller) PointValue

func (c *Controller) PointValue(pair string) (float64, error)

PointValue returns the value in the currency of the cash of the exchange of a move of 1 of the price of pair for 1 unit, see service.PointValuer: 1 for an exchange valuing the pairs in their quote.

func (*Controller) Position

func (c *Controller) Position(pair string) (asset, quote float64, err error)

func (*Controller) PositionStop

func (c *Controller) PositionStop(pair string) (Position, model.Order, bool)

PositionStop returns the position held on pair and its stop loss leg as it is now (see service.ProtectionReader), from the legs the controller follows, false for the leg when it has none, eg: removed by hand, or never placed. It doesn't read the storage: it may be called on every price.

func (*Controller) PositionValue

func (c *Controller) PositionValue(pair string) (float64, error)

func (*Controller) PositionsOpened

func (c *Controller) PositionsOpened(pair string, since time.Time) int

PositionsOpened returns how many fills of pair opened a position, or reversed one, at or after since: from the fills the controller settled, the ones of the storage replayed at the start (see restore) included, whatever placed them (a strategy, the trade panel, Telegram).

func (*Controller) PositionsReplayed

func (c *Controller) PositionsReplayed(pair string, since time.Time) int

PositionsReplayed is PositionsOpened of the fills of the storage replayed at the start only (see restore): the positions opened by the previous runs, see service.PositionOpenings.

func (*Controller) Protect

func (c *Controller) Protect(side model.SideType, pair string, size, stop, profit float64) ([]model.Order, error)

Protect protects the position held on side of pair with a stop loss and a take profit, see service.PositionProtector, and stores the legs, followed as any other order. Like UpdateProtection, it works on a stopped bot too: it only protects a position; not once the controller is closed (see Close).

func (*Controller) SetNotifier

func (c *Controller) SetNotifier(notifier service.Notifier)

func (*Controller) SetPositionStop

func (c *Controller) SetPositionStop(pair string, side model.SideType, level float64) ([]model.Order, error)

SetPositionStop puts a stop loss at level on the position held on side of pair, which has none, see service.StopSetter, and stores the legs placed, followed as any other order. Like UpdateProtection, it works on a stopped bot too; not once the controller is closed.

func (*Controller) SetStopGuard

func (c *Controller) SetStopGuard(guarded func(pair string) bool)

SetStopGuard sets the stop guard: guarded reports whether the stop losses of the open positions of a pair only tighten (see UpdateProtection), nil for none. It is called under the lock of the pair, so it must not wait: an atomic flag, not a lock.

func (*Controller) Start

func (c *Controller) Start()

func (*Controller) Status

func (c *Controller) Status() Status

func (*Controller) Stop

func (c *Controller) Stop()

Stop stops the controller: no order begins any more (ErrBotStopped), and once the calls begun are recorded, the pending orders are updated a last time.

func (*Controller) StopGuarded

func (c *Controller) StopGuarded(pair string) bool

StopGuarded reports whether the stop guard of pair is on, see SetStopGuard.

func (*Controller) Summaries

func (c *Controller) Summaries() map[string]string

Summaries returns the results of each pair, as their table, read under c.mtx: Results is written as the orders fill, so read it directly only once the bot stopped, eg: at the end of a backtest. The exclusive lock, as the table may write the spare capacity of the slices of a summary (see rebuildCache).

func (*Controller) Tick

func (c *Controller) Tick(pair string) float64

Tick returns the step of the prices of pair at the exchange, 0 when unknown.

func (*Controller) TightenProtection

func (c *Controller) TightenProtection(leg model.Order, level float64) (model.Order, error)

TightenProtection is UpdateProtection always guarded: a stop loss of an open position moves only to a level protecting it more than the one it is at now (see service.ProtectionReader), by more than half a tick; as much is no move, the leg returned as it is; less is a *service.StopNotTighterError with the leg as it is. The level is read again under the lock of the pair, so that two movers never loosen what the other tightened. The legs of a pending entry, and the take profits, move as UpdateProtection moves them.

func (*Controller) UpdateLimit

func (c *Controller) UpdateLimit(order model.Order, limit float64) (model.Order, error)

UpdateLimit moves a pending limit order to limit, see service.ProtectionBroker, and stores it moved; an order that ended meanwhile, eg: filled as it was moved, is returned as it ended, see record. Unlike UpdateProtection, it needs the bot running: it changes when a position opens.

func (*Controller) UpdateOrders

func (c *Controller) UpdateOrders()

UpdateOrders fetches the status of the pending orders from the exchange, persists the ones that changed and settles their fills: the position, the profit of the trade and the order feed are updated here.

A started controller runs it every second on its own. Backtests replay years of candles in a few seconds, so they must call it after every candle to account the fills in the order they happen; it is cheap when nothing is pending.

func (*Controller) UpdateProtection

func (c *Controller) UpdateProtection(leg model.Order, level float64) (model.Order, error)

UpdateProtection moves a stop loss or take profit leg to level, see service.ProtectionBroker, and stores it moved; a leg that ended meanwhile, eg: filled as it was moved, is returned as it ended, see record. Like Cancel, it works on a stopped bot too: it only protects a position; not once the controller is closed (see Close). While the stop guard of its pair is on (see SetStopGuard), a stop loss of an open position only tightens, see TightenProtection.

func (*Controller) UpdateProtectionManual

func (c *Controller) UpdateProtectionManual(leg model.Order, level float64) (model.Order, error)

UpdateProtectionManual is UpdateProtection for a move by a user, eg: from the trade panel: never guarded, it may loosen a stop loss.

func (*Controller) WaitIdle

func (c *Controller) WaitIdle(d time.Duration) bool

WaitIdle waits for the orders being sent (see begin) to end, d at most: eg: once the entries are blocked, before the pending entries are canceled, so that none sent just before the block is left. false when some are still being sent after d.

type DataFeed

type DataFeed struct {
	Data chan model.Order
	Err  chan error
}

type Feed

type Feed struct {
	OrderFeeds            map[string]*DataFeed
	SubscriptionsBySymbol map[string][]Subscription
}

func NewOrderFeed

func NewOrderFeed() *Feed

func (*Feed) Publish

func (d *Feed) Publish(order model.Order, _ bool)

func (*Feed) Start

func (d *Feed) Start()

func (*Feed) Subscribe

func (d *Feed) Subscribe(pair string, consumer FeedConsumer, onlyNewOrder bool)

type FeedConsumer

type FeedConsumer func(order model.Order)

type Position

type Position struct {
	Side model.SideType
	// AvgPrice is the average price of the position, 0 when unknown: a fill
	// of it had no price, see Position.Update.
	AvgPrice float64
	Quantity float64
	// Fee paid to open the position, in quote currency. It is settled against
	// the profit as the position is closed.
	Fee       float64
	CreatedAt time.Time
	// Entry is the fill that opened the position, for the profit the broker
	// books when it closes, see service.AccountReporter.
	Entry model.Order
}

func (*Position) String

func (p *Position) String() string

String describes the position, eg: BUY 0.1 at 4250.5.

func (*Position) Update

func (p *Position) Update(order *model.Order) (result *Result, finished bool)

type Result

type Result struct {
	Pair          string
	ProfitPercent float64
	ProfitValue   float64
	Side          model.SideType
	Duration      time.Duration
	CreatedAt     time.Time
	// contains filtered or unexported fields
}

type Status

type Status string
const (
	StatusRunning Status = "running"
	StatusStopped Status = "stopped"
	StatusError   Status = "error"
)

type Subscription

type Subscription struct {
	// contains filtered or unexported fields
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL