execution

package
v0.2.4 Latest Latest
Warning

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

Go to latest
Published: Jul 10, 2026 License: BSD-2-Clause Imports: 7 Imported by: 0

Documentation

Index

Constants

View Source
const (
	LotNone lotState = iota
	LotOpenRequested
	LotOpen
	LotCloseRequested
	LotClosed
)

Variables

This section is empty.

Functions

func FillAdjust added in v0.2.4

func FillAdjust(isBuy bool, spread, slippage market.Price) market.Price

FillAdjust returns the price adjustment for spread and slippage when turning a bid-side OHLC price into an executed fill. Dukascopy OHLC prices are bid-side: when buying (long open, short close) we pay the ask, so the adjustment is +spread+slippage; when selling we only lose slippage.

func InstrumentPositions added in v0.2.4

func InstrumentPositions(lb *LotBook) map[string]Position

InstrumentPositions derives per-instrument Position from all open lots.

Types

type Account added in v0.2.4

type Account struct {
	ID           string
	Name         string
	Currency     string       // account denomination (e.g. "USD")
	Balance      market.Money // realised cash; updated on every close
	Equity       market.Money // Balance + sum of unrealised P/L across open lots
	MarginUsed   market.Money // sum of margin reserved by open lots
	FreeMargin   market.Money // Equity − MarginUsed
	MarginLevel  market.Money // Equity / MarginUsed × market.MoneyScale (0 when flat)
	RiskFraction market.Rate  // fraction of equity risked per trade (e.g. 0.005 = 0.5 %)

	Lots   LotBook
	Trades []*Trade // closed trades, appended by CloseLot
}

Account holds the financial state for a single trading account. All monetary values are scaled integers (market.Money = int64 × market.MoneyScale). Invariants that must hold after every operation:

  • Equity = Balance + UnrealizedPL
  • FreeMargin = Equity − MarginUsed

func NewAccount added in v0.2.4

func NewAccount(name string, deposit market.Money) *Account

NewAccount creates an Account with the given name and opening deposit. Currency defaults to "USD"; RiskFraction defaults to 0.5 %.

func (*Account) AddLot added in v0.2.4

func (acct *Account) AddLot(lot *Lot) error

AddLot registers a newly opened lot with the account and immediately revalues all open positions at the lot's entry price.

func (*Account) CloseLot added in v0.2.4

func (acct *Account) CloseLot(lot *Lot, trade *Trade) error

CloseLot realizes P/L for the lot, appends the trade to the account's Trades history, removes the lot from the LotBook, and revalues remaining open lots at the exit price.

func (*Account) ResolveWithMarks added in v0.2.4

func (acct *Account) ResolveWithMarks(marks map[string]market.Price) error

ResolveWithMarks recomputes all account-level derived fields (Equity, MarginUsed, FreeMargin, MarginLevel) using the provided mark prices. If a lot's instrument has no entry in marks, the lot's EntryPrice is used. Pass nil to revalue everything at entry.

func (*Account) SizePosition added in v0.2.4

func (acct *Account) SizePosition(req *OpenRequest) error

SizePosition computes and sets req.Units as the lesser of:

  • the units allowed by the risk budget (unitsByRisk)
  • the units allowed by available margin (unitsByMargin)

Returns an error if the computed size is below the instrument's minimum trade size or if any input is invalid.

type Broker added in v0.2.4

type Broker struct {
	Name    string
	Account *Account
	// contains filtered or unexported fields
}

func NewBroker added in v0.2.4

func NewBroker(name string) *Broker

func (*Broker) EnqueueEvent added in v0.2.4

func (b *Broker) EnqueueEvent(evt *Event) bool

EnqueueEvent places evt on the broker event queue without blocking, returning true if it was accepted. The queue is initialized on first use. Useful for injecting events from outside the normal Submit path (e.g. tests, replay).

func (*Broker) EventQueueCap added in v0.2.4

func (b *Broker) EventQueueCap() int

EventQueueCap returns the capacity of the broker event queue, or 0 if it has not been initialized.

func (*Broker) EventQueueLen added in v0.2.4

func (b *Broker) EventQueueLen() int

EventQueueLen returns the number of pending broker events, or 0 if the queue has not been initialized. Used by the engine to detect broker idleness.

func (*Broker) Events added in v0.2.4

func (b *Broker) Events() <-chan *Event

func (*Broker) SubmitClose added in v0.2.4

func (b *Broker) SubmitClose(ctx context.Context, req *CloseRequest) error

func (*Broker) SubmitOpen added in v0.2.4

func (b *Broker) SubmitOpen(ctx context.Context, req *OpenRequest) (*Lot, error)

type CloseCause added in v0.2.4

type CloseCause int

CloseCause represents a trader domain type.

const (
	CloseUnknown CloseCause = iota
	CloseManual
	CloseStopLoss
	CloseTakeProfit
	CloseBrokerLiquidation
)

func (CloseCause) String added in v0.2.4

func (c CloseCause) String() string

String is an internal helper for trader type processing.

type CloseMatcher added in v0.2.4

type CloseMatcher interface {
	Match(lots []*Lot, units market.Units) ([]LotMatch, error)
}

type CloseRequest added in v0.2.4

type CloseRequest struct {
	Request
	*Lot
	CloseCause CloseCause
}

CloseRequest represents a trader domain type.

func (*CloseRequest) Validate added in v0.2.4

func (r *CloseRequest) Validate() error

Validate is an internal helper for trader type processing.

type Event added in v0.2.4

type Event struct {
	Type  EventType
	Trade *Trade
	Lot   *Lot
}

type EventType added in v0.2.4

type EventType int
const (
	EventOrderFilled EventType = iota + 1
	EventPositionClosed
)

func (EventType) String added in v0.2.4

func (e EventType) String() string

type FIFOMatcher added in v0.2.4

type FIFOMatcher struct{}

FIFOMatcher closes the oldest open lots first.

func (FIFOMatcher) Match added in v0.2.4

func (FIFOMatcher) Match(lots []*Lot, units market.Units) ([]LotMatch, error)

type Lot added in v0.2.4

type Lot struct {
	*TradeCommon
	EntryPrice     market.Price
	EntryTime      market.Timestamp
	OriginalUnits  market.Units
	RemainingUnits market.Units
	State          lotState
	// ExtremePrice tracks the highest-high (long) or lowest-low (short) seen
	// since entry. Used by trailing/chandelier exit strategies.
	ExtremePrice market.Price
}

Lot represents a trader domain type.

func (*Lot) Clone added in v0.2.4

func (lot *Lot) Clone() *Lot

Clone is an internal helper for trader type processing.

func (*Lot) Validate added in v0.2.4

func (lot *Lot) Validate() error

Validate is an internal helper for trader type processing.

type LotBook added in v0.2.4

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

LotBook represents a trader domain type.

func (*LotBook) Add added in v0.2.4

func (lb *LotBook) Add(lot *Lot) error

Add is an internal helper for trader type processing.

func (*LotBook) All added in v0.2.4

func (lb *LotBook) All() map[string]*Lot

All is an internal helper for trader type processing.

func (*LotBook) Delete added in v0.2.4

func (lb *LotBook) Delete(id string) bool

Delete is an internal helper for trader type processing.

func (*LotBook) Get added in v0.2.4

func (lb *LotBook) Get(id string) *Lot

Get is an internal helper for trader type processing.

func (*LotBook) Has added in v0.2.4

func (lb *LotBook) Has(id string) bool

Has is an internal helper for trader type processing.

func (*LotBook) Len added in v0.2.4

func (lb *LotBook) Len() int

Len is an internal helper for trader type processing.

func (*LotBook) Range added in v0.2.4

func (lb *LotBook) Range(fn func(*Lot) error) error

Range is an internal helper for trader type processing.

func (*LotBook) Slice added in v0.2.4

func (lb *LotBook) Slice() []*Lot

Slice is an internal helper for trader type processing.

type LotMatch added in v0.2.4

type LotMatch struct {
	Lot   *Lot
	Units market.Units
}

type OpenRequest added in v0.2.4

type OpenRequest struct {
	Request
}

OpenRequest represents a trader domain type.

func NewOpenRequest added in v0.2.4

func NewOpenRequest(
	instr string,
	c *market.CandleTime,
	side market.Side,
	stop market.Price,
	take market.Price,
	reason string) *OpenRequest

NewOpenRequest is an internal helper for trader type processing.

func (*OpenRequest) Validate added in v0.2.4

func (r *OpenRequest) Validate() error

Validate is an internal helper for trader type processing.

type Position added in v0.2.4

type Position struct {
	Instrument         string
	LongUnits          market.Units
	LongAvgEntryPrice  market.Price
	ShortUnits         market.Units
	ShortAvgEntryPrice market.Price
	NetUnits           market.Units
}

Position is the computed aggregate view of all open lots for one instrument. Hedged books keep separate long/short exposure and entry prices.

type Request added in v0.2.4

type Request struct {
	*TradeCommon
	RequestType
	market.Price
	market.Timestamp
	Reason string
	Candle market.Candle
}

Request represents a trader domain type.

type RequestType added in v0.2.4

type RequestType uint8

RequestType represents a trader domain type.

const (
	RequestNone RequestType = iota
	RequestMarketOpen
	RequestLimitOpen
	RequestClose
)

func (RequestType) String added in v0.2.4

func (t RequestType) String() string

String is an internal helper for trader type processing.

type Trade added in v0.2.4

type Trade struct {
	*TradeCommon
	EntryPrice market.Price
	EntryTime  market.Timestamp
	ExitPrice  market.Price
	ExitTime   market.Timestamp
	PNL        market.Money // account currency (best-effort)
	CloseCause CloseCause
}

Trade represents a trader domain type.

func (*Trade) Clone added in v0.2.4

func (t *Trade) Clone() *Trade

Clone is an internal helper for trader type processing.

type TradeCommon added in v0.2.4

type TradeCommon struct {
	ID          string
	Instrument  string
	market.Side // Long or Short
	market.Units
	Stop market.Price
	Take market.Price
}

TradeCommon represents a trader domain type.

func (*TradeCommon) Clone added in v0.2.4

func (tc *TradeCommon) Clone() *TradeCommon

Clone is an internal helper for trader type processing.

type TradeHistory added in v0.2.4

type TradeHistory struct {
	*TradeCommon
	*OpenRequest
}

TradeHistory represents a trader domain type.

func NewTradeHistory added in v0.2.4

func NewTradeHistory(inst string) *TradeHistory

NewTradeHistory is an internal helper for trader type processing.

Jump to

Keyboard shortcuts

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