mkt

package module
v0.3.8 Latest Latest
Warning

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

Go to latest
Published: Sep 2, 2024 License: MIT Imports: 10 Imported by: 6

README

mkt

Documentation

Overview

Package mkt defines some market concepts.

Index

Constants

View Source
const (
	FIXUTCMillis = "20060102-15:04:05.000"    // FIXUTCMillis is the conventional timestamp format.
	FIXUTCMicros = "20060102-15:04:05.000000" // FIXUTCMicros is used by Binance SPOT.
)

FIX timestamp formats. Timestamps are always UTC.

Variables

View Source
var DecimalOne = decimal.New(1, 0)

DecimalOne is the number 1 as a decimal.

Functions

func CumQtyAvgPx

func CumQtyAvgPx(cumQty, avgPx, lastQty, lastPx decimal.Decimal, n int32) (decimal.Decimal, decimal.Decimal)

CumQtyAvgPx returns the cumulative quantity and average price, the latter rounded to 'n' places.

func NewOrderID added in v0.3.0

func NewOrderID() string

NewOrderID is a convenience function to generate a unique OrderID.

func Precision

func Precision(number decimal.Decimal) int32

Precision returns the number of decimals in the number.

func QuoteKey added in v0.3.1

func QuoteKey(quote *Quote) string

QuoteKey is a convenience function to use when constructing a utl.ConflatingQueue for Quote.

func SortImmediateFirst

func SortImmediateFirst[T HavingTimeInForce](items []T)

SortImmediateFirst sorts such that IOC items will be first in the slice.

func SortRecentFirst

func SortRecentFirst[T HavingTransactTime](items []T)

SortRecentFirst sorts the items in ascending time priority, with the most recent TransactTime first.

func TradeKey added in v0.3.1

func TradeKey(trade *Trade) string

TradeKey is a convenience function to use when constructing a utl.ConflatingQueue for Trade.

func Units

func Units(x, unit, min decimal.Decimal) decimal.Decimal

Units returns x as an integer number of units greater than or equal to the minimum. This function is used for both prices (to be round ticks) and quantities (to be round lots).

Types

type AnyListing added in v0.3.0

type AnyListing interface {
	Definition() *Listing
}

AnyListing defines all types which can embed, or derive from, Listing.

type AnyOrder added in v0.3.0

type AnyOrder interface {
	Definition() *Order
}

AnyOrder defines all types which can embed, or derive from, Order.

type Book added in v0.3.0

type Book[T AnyListing] struct {
	// contains filtered or unexported fields
}

Book is a set of *Position. A book may only hold a position in a Listing that is included in the associated WhiteList.

func NewBook added in v0.3.0

func NewBook[T AnyListing](name string, whitelist *WhiteList[T], options ...BookOption[T]) *Book[T]

NewBook returns a *Book ready to use.

func (*Book[T]) ForEachPosition added in v0.3.0

func (x *Book[T]) ForEachPosition(visitor func(*Position[T]))

ForEachPosition visits every position in the book.

func (*Book[T]) Name added in v0.3.0

func (x *Book[T]) Name() string

Name returns the name of the book.

func (*Book[T]) Traded added in v0.3.0

func (x *Book[T]) Traded(symbol string, side Side, lastQty decimal.Decimal, lastPx decimal.Decimal) error

Traded applies the trade to the book. If the symbol is not recognised this function will return an error.

type BookOption added in v0.3.0

type BookOption[T AnyListing] func(*Book[T])

BookOption is any option that can be applied when constructing the book.

func WithBookChannel added in v0.3.0

func WithBookChannel[T AnyListing](c chan *PositionMemo) BookOption[T]

WithBookChannel writes a *PositionMemo to the channel after any trade in the book.

type HavingTimeInForce

type HavingTimeInForce interface {
	TimeInForce() TimeInForce
}

HavingTimeInForce is the interface required for SortImmediateFirst.

type HavingTransactTime

type HavingTransactTime interface {
	TransactTime() time.Time
}

HavingTransactTime is the interface required for SortRecentFirst. TransactTime is FIX field 60.

type Listing added in v0.2.0

type Listing struct {
	Symbol             string          // FIX field 55
	TickIncrement      decimal.Decimal // FIX field 1208
	RoundLot           decimal.Decimal // FIX field 561
	MinTradeVol        decimal.Decimal // FIX field 562
	ContractMultiplier decimal.Decimal // FIX field 231
}

A Listing which can be traded with counterparties. These are the essential details required for trading.

Listing is principally a data object and stateless, so its fields are exported for convenience.

func (*Listing) Definition added in v0.2.0

func (x *Listing) Definition() *Listing

Definition returns the *Listing.

type MsgType added in v0.3.3

type MsgType int64

The MsgType for an order, FIX field 35.

const (
	OrderNew MsgType = iota + 13

	OrderCancel
	OrderReplace
)

Recognised MsgType values.

func MsgTypeFromString added in v0.3.3

func MsgTypeFromString(s string) MsgType

MsgTypeFromString returns a recognised MsgType or zero.

func (MsgType) AsQuickFIX added in v0.3.3

func (x MsgType) AsQuickFIX() field.MsgTypeField

AsQuickFIX returns this MsgType as a QuickFIX field. If the value is not one of those recognised, this function returns a valid value that will likely be rejected by the counterparty, rather than panicking.

func (MsgType) MarshalJSON added in v0.3.3

func (x MsgType) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

func (MsgType) String added in v0.3.3

func (x MsgType) String() string

String returns a short mnemonic for the MsgType, since the FIX values are unfamiliar to many. If the FIX values are required, use MsgType.AsQuickFIX instead.

func (*MsgType) UnmarshalJSON added in v0.3.3

func (x *MsgType) UnmarshalJSON(b []byte) error

UnmarshalJSON implements json.Unmarshaler.

type OrdStatus added in v0.3.6

type OrdStatus int64

The OrdStatus is the execution status of an order, FIX field 39

const (
	OrdStatusNew OrdStatus = iota + 1
	OrdStatusPartiallyFilled
	OrdStatusFilled
	OrdStatusCanceled
	OrdStatusPendingCancel
	OrdStatusRejected
	OrdStatusPendingNew
	OrdStatusExpired
	OrdStatusPendingReplace
)

Recognised OrdStatus values, a subset from FIX 4.4. The zero value is reserved for representing 'no value'.

func OrdStatusFromFIX added in v0.3.8

func OrdStatusFromFIX(ordStatus field.OrdStatusField) OrdStatus

OrdStatusFromFIX returns the equivalent OrdStatus from the QuickFIX field, or zero if there is no equivalence.

func OrdStatusFromString added in v0.3.6

func OrdStatusFromString(s string) OrdStatus

OrdStatusFromString returns a recognised OrdStatus or zero.

func (OrdStatus) AsQuickFIX added in v0.3.6

func (x OrdStatus) AsQuickFIX() field.OrdStatusField

AsQuickFIX returns the OrdStatus as a QuickFIX field. If the value is not one of those recognised, this function returns a valid value that will likely be rejected by the counterparty, rather than panicking.

func (OrdStatus) MarshalJSON added in v0.3.6

func (x OrdStatus) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

func (OrdStatus) String added in v0.3.6

func (x OrdStatus) String() string

String returns a mnemonic of the OrdStatus.

func (*OrdStatus) UnmarshalJSON added in v0.3.6

func (x *OrdStatus) UnmarshalJSON(b []byte) error

UnmarshalJSON implements json.Unmarshaler.

type Order added in v0.3.0

type Order struct {
	MsgType MsgType `json:"msgType"` // FIX field 35
	OrderID string  `json:"orderID"` // FIX field 37
	Side    Side    `json:"side"`    // FIX field 54
	Symbol  string  `json:"symbol"`  // FIX field 55
}

Order is the prototype for an order sent to a counterparty.

func (*Order) Definition added in v0.3.0

func (x *Order) Definition() *Order

Definition returns the *Order.

type Position added in v0.3.0

type Position[T AnyListing] struct {
	// contains filtered or unexported fields
}

A Position as a result of one or more trades in a Listing.

func NewPosition added in v0.3.0

func NewPosition[T AnyListing](symbol string, whitelist *WhiteList[T], options ...PositionOption[T]) *Position[T]

NewPosition returns a flat position for the given symbol.

func (*Position[T]) Cash added in v0.3.0

func (x *Position[T]) Cash(cash decimal.Decimal)

Cash adds cash to the realised profit/loss, representing a cash only movement such as a dividend. The cash may be negative.

func (*Position[T]) Mark added in v0.3.0

func (x *Position[T]) Mark(price decimal.Decimal) (valuation, unrealised decimal.Decimal)

Mark returns the valuation of the position at the given price and the unrealised profit/loss at that price.

func (*Position[T]) Memo added in v0.3.0

func (x *Position[T]) Memo() *PositionMemo

Memo returns a *PositionMemo for the current position.

func (*Position[T]) Reset added in v0.3.0

func (x *Position[T]) Reset()

Reset the realised profit/loss. Typically this would be done at the end of an accounting period.

func (*Position[T]) Traded added in v0.3.0

func (x *Position[T]) Traded(side Side, lastQty decimal.Decimal, lastPx decimal.Decimal)

Traded adjusts this position for the given trade.

type PositionMemo added in v0.3.0

type PositionMemo struct {
	Symbol   string          `json:"symbol"`
	Quantity decimal.Decimal `json:"quantity"`
	AvgPx    decimal.Decimal `json:"avgPx"`
	Realised decimal.Decimal `json:"realised"`
}

PositionMemo is the key information for each position.

type PositionOption added in v0.3.0

type PositionOption[T AnyListing] func(*Position[T])

PositionOption is any option which can be applied when constructing the position.

func WithPositionChannel added in v0.3.0

func WithPositionChannel[T AnyListing](c chan *PositionMemo) PositionOption[T]

WithPositionChannel writes a *PositionMemo to the channel at every trade.

type Quote

type Quote struct {
	Symbol  string          // FIX field 55
	BidPx   decimal.Decimal // FIX field 132
	BidSize decimal.Decimal // FIX field 134
	AskPx   decimal.Decimal // FIX field 133, renamed from OfferPx
	AskSize decimal.Decimal // FIX field 135, renamed from OfferSize
}

Quote is the best bid and ask for a symbol.

Quote is principally a data object and stateless, so its fields are exported for convenience.

func ZeroQuote

func ZeroQuote(quote *Quote) *Quote

ZeroQuote will 'zero' all the fields in the *Quote, never returning nil. This is a convenience for using quotes in a utl.Pool.

func (*Quote) Far

func (x *Quote) Far(side Side) (decimal.Decimal, decimal.Decimal)

Far returns the aggressive price and size for the given Side.

func (*Quote) MidPrice

func (x *Quote) MidPrice() decimal.Decimal

MidPrice returns the mean of the bid and ask. The mean is not expected to be tick aligned.

func (*Quote) Near

func (x *Quote) Near(side Side) (decimal.Decimal, decimal.Decimal)

Near returns the passive price and size for the given Side.

func (*Quote) Spread

func (x *Quote) Spread() decimal.Decimal

Spread returns the difference between the ask and the bid. This will be an integral number of ticks.

type Report added in v0.3.6

type Report struct {
	OrderID          string          `json:"orderID"`                    // FIX field 37
	Symbol           string          `json:"symbol,omitempty"`           // FIX field 55
	Side             Side            `json:"side,omitempty"`             // FIX field 54
	SecondaryOrderID string          `json:"secondaryOrderID,omitempty"` // FIX field 198
	ClOrdID          string          `json:"clOrdID,omitempty"`          // FIX field 11
	OrdStatus        OrdStatus       `json:"ordStatus,omitempty"`        // FIX field 39
	Account          string          `json:"account,omitempty"`          // FIX field 1
	TimeInForce      TimeInForce     `json:"timeInForce,omitempty"`      // FIX field 59
	LastQty          decimal.Decimal `json:"lastQty"`                    // FIX field 32
	LastPx           decimal.Decimal `json:"lastPx"`                     // FIX field 31
	TransactTime     time.Time       `json:"transactTime"`               // FIX field 60
	ExecInst         string          `json:"execInst,omitempty"`         // FIX field 18
}

Report is an augmented execution report from the counterparty.

[Report.OrderID] is that known by the originator of the order, whereas [Report.SecondaryOrderID] is that assigned by the counterparty.

[Report.ExecInst] values are ignored except for 'e', meaning 'work to target strategy'. If that is returned to the originator then it signals that the originator may resume sending requests to the counterparty.

func (*Report) WorkToTarget added in v0.3.6

func (x *Report) WorkToTarget() bool

WorkToTarget returns true if the report indicates the originator may continue sending requests.

type Side

type Side int64

The Side of an order, FIX field 54.

const (
	Buy  Side = 1
	Sell Side = 2
)

Recognised Side values.

func SideFromString

func SideFromString(x string) Side

SideFromString returns a recognised Side or zero.

func (Side) AsQuickFIX

func (x Side) AsQuickFIX() field.SideField

AsQuickFIX returns this side as a QuickFIX field. If the value is not one of those recognised, this function returns a valid value that will likely be rejected by the counterparty, rather than panicking.

func (Side) Improve

func (x Side) Improve(price, increment decimal.Decimal) decimal.Decimal

Improve returns the price improved by the increment. When buying, the price is improved (for the seller) by adding the increment; when selling the price is improved (for the buyer) by subtracting the increment.

func (Side) MarshalJSON

func (x Side) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

func (Side) Opposite

func (x Side) Opposite() Side

Opposite returns the opposite Side.

func (Side) String

func (x Side) String() string

func (*Side) UnmarshalJSON

func (x *Side) UnmarshalJSON(b []byte) error

UnmarshalJSON implements json.Unmarshaler.

func (Side) Within

func (x Side) Within(price, limit decimal.Decimal) bool

Within returns true if the price is within the limit. It also returns true if the limit is zero.

type TimeInForce

type TimeInForce int64

The TimeInForce of an order, FIX field 59.

const (
	GTC TimeInForce = 1
	IOC TimeInForce = 3
)

Recognised TimeInForce values.

func TimeInForceFromString

func TimeInForceFromString(s string) TimeInForce

TimeInForceFromString returns a recognised TimeInForce or zero.

func (TimeInForce) AsQuickFIX

func (x TimeInForce) AsQuickFIX() field.TimeInForceField

AsQuickFIX returns this TimeInForce as a QuickFIX field. If the value is not one of those recognised, this function returns a valid value that will likely be rejected by the counterparty, rather than panicking.

func (TimeInForce) MarshalJSON

func (x TimeInForce) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

func (TimeInForce) String

func (x TimeInForce) String() string

func (*TimeInForce) UnmarshalJSON

func (x *TimeInForce) UnmarshalJSON(b []byte) error

UnmarshalJSON implements json.Unmarshaler.

type Trade

type Trade struct {
	Symbol      string          // FIX field 55
	LastQty     decimal.Decimal // FIX field 32
	LastPx      decimal.Decimal // FIX field 31
	TradeVolume decimal.Decimal // FIX field 1020
	AvgPx       decimal.Decimal // FIX field 6
}

A Trade in a market.

Trade is principally a data object and has little state, so its fields are exported for convenience.

Trades may be aggregated, for example in a utl.ConflatingQueue. When inspecting a Trade the [Trade.LastQty] and [Trade.LastPx] fields will always refer to the last trade that was included. However, if non zero, [Trade.TradeVolume] and [Trade.AvgPx] reflect all the trades aggregated in the struct: if simply counting volume and VWAP use those fields.

func (*Trade) Aggregate added in v0.3.2

func (x *Trade) Aggregate(trade *Trade, precision int32)

Aggregate the given trade with this. The LastQty and LastPx are copied from the given trade and used to update total volume and average price.

type WhiteList added in v0.2.0

type WhiteList[T AnyListing] struct {
	// contains filtered or unexported fields
}

A WhiteList has one or more T which can be traded.

func NewWhiteList added in v0.3.0

func NewWhiteList[T AnyListing](options ...WhiteListOption[T]) *WhiteList[T]

NewWhiteList returns a new *WhiteList ready to use.

func (*WhiteList[T]) Add added in v0.3.0

func (x *WhiteList[T]) Add(listing T)

Add the listing to this white list. If the cache option was specified then this is a no-op - the cache governs what is in the whitelist.

func (*WhiteList[T]) Lookup added in v0.2.0

func (x *WhiteList[T]) Lookup(symbol string) (T, bool)

Lookup returns the T for the given symbol, or if not present, the zero value and false.

type WhiteListOption added in v0.3.0

type WhiteListOption[T AnyListing] func(*WhiteList[T])

WhiteListOption is any option that be applied when the *WhiteList is manufactured.

func WithWhiteListCacheOption added in v0.3.0

func WithWhiteListCacheOption[T AnyListing](cache *utl.Cache[string, T]) WhiteListOption[T]

WithWhiteListCacheOption is an option to use a utl.Cache instead of a simple map.

Jump to

Keyboard shortcuts

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