broker

package
v0.0.26 Latest Latest
Warning

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

Go to latest
Published: Jun 19, 2022 License: MIT Imports: 10 Imported by: 0

Documentation

Overview

Package broker provides an API for interacting with 3rd party exchanges, and a simulated dealer for backtesting in the child package backtest.

Index

Constants

View Source
const (
	// OrderPending represents an order that has not been processed by a dealer.
	OrderPending = iota

	// OrderOpen represents an order that has been opened by a dealer but not yet filled.
	OrderOpen

	// OrderFilled represents an order that has been filled by a dealer at a price level.
	OrderFilled

	// OrderClosed represents an order that has been closed by a dealer.
	OrderClosed
)
View Source
const (
	// PositionPending represents a position that has not been processed by a dealer.
	PositionPending = iota

	// PositionOpen represents a position that has been opened by a dealer.
	PositionOpen

	// PositionClosed represents a position that has been closed by a dealer.
	PositionClosed
)

Variables

This section is empty.

Functions

func SortMapValues

func SortMapValues[K constraints.Ordered, V any](m map[K]V) []V

SortMapValues sorts the values of the map.

Types

type AccountBalance

type AccountBalance struct {

	// Trade is the balance amount available for trading.
	Trade decimal.Decimal

	// Equity is the total notional account value including unrealized gains on open positions.
	Equity decimal.Decimal
}

AccountBalance is a representation of a broker's account balance.

type BracketOrder

type BracketOrder struct {
	Enter Order
	Stop  Order
}

BracketOrder groups together a set of dependent orders to open and manage a new position.

type DealID

type DealID string

DealID is a unique identifier for a dealer data entity.

func NewID

func NewID() DealID

NewID returns a new DealID seeded with the current time.

func NewIDWithTime

func NewIDWithTime(t time.Time) DealID

NewIDWithTime returns a new DealID seeded with the given time.

type Dealer

type Dealer interface {
	GetBalance(context.Context) (*AccountBalance, *web.Response, error)
	PlaceOrder(context.Context, Order) (*Order, *web.Response, error)
	CancelOrders(context.Context) (*web.Response, error)
	ListPositions(context.Context, *web.ListOpts) ([]Position, *web.Response, error)
	ListRoundTurns(context.Context, *web.ListOpts) ([]RoundTurn, *web.Response, error)
}

Dealer is an interface for interacting with a 3rd party exchange and placing orders in the market.

type EquitySeries

type EquitySeries TimeSeries[decimal.Decimal]

EquitySeries is a time series of equity values.

func (EquitySeries) SortKeys

func (es EquitySeries) SortKeys() []Timestamp

SortKeys returns a sorted slice of keys in ascending chronological order.

func (EquitySeries) SortValuesByTime

func (es EquitySeries) SortValuesByTime() []decimal.Decimal

SortValuesByTime returns a sorted slice of values in ascending chronological order.

type MakeSimulatedDealer

type MakeSimulatedDealer func() (SimulatedDealer, error)

MakeSimulatedDealer returns a new SimulatedDealer

type MockDealer

type MockDealer struct {
	mock.Mock
}

MockDealer is a mock implementation of the Dealer interface using testify/mock.

func (*MockDealer) CancelOrders

func (d *MockDealer) CancelOrders(ctx context.Context) (*web.Response, error)

CancelOrders cancels an order.

func (*MockDealer) GetBalance

func (d *MockDealer) GetBalance(ctx context.Context) (*AccountBalance, *web.Response, error)

GetBalance returns the balance of the account.

func (*MockDealer) ListPositions

func (d *MockDealer) ListPositions(ctx context.Context, opts *web.ListOpts) ([]Position, *web.Response, error)

ListPositions returns the positions of the account.

func (*MockDealer) ListRoundTurns added in v0.0.25

func (d *MockDealer) ListRoundTurns(ctx context.Context, opts *web.ListOpts) ([]RoundTurn, *web.Response, error)

ListRoundTurns returns the round-turns of the account.

func (*MockDealer) PlaceOrder

func (d *MockDealer) PlaceOrder(ctx context.Context, order Order) (*Order, *web.Response, error)

PlaceOrder places an order.

type Order

type Order struct {
	ID       DealID
	OpenedAt time.Time
	FilledAt time.Time
	ClosedAt time.Time

	Asset      market.Asset
	Side       OrderSide
	Type       OrderType
	LimitPrice decimal.Decimal
	Size       decimal.Decimal
	ReduceOnly bool

	FilledPrice decimal.Decimal
	FilledSize  decimal.Decimal

	Fee decimal.Decimal
}

Order represents an order to be placed using a dealer.

func NewOrder

func NewOrder(asset market.Asset, side OrderSide, size decimal.Decimal) Order

NewOrder creates a new order with the minimum required fields to be valid.

func (*Order) State

func (o *Order) State() OrderState

State returns the state of the order based on the order timestamps.

type OrderSide

type OrderSide int

OrderSide represents the side of an order: Buy (long) or Sell (short).

const (
	// Buy (long)
	Buy OrderSide = iota + 1

	// Sell (short)
	Sell
)

func (OrderSide) MarshalText added in v0.0.20

func (s OrderSide) MarshalText() ([]byte, error)

MarshalText is used to output as a string for CSV rendering.

func (OrderSide) Opposite

func (s OrderSide) Opposite() OrderSide

Opposite returns the opposite side of the order.

func (OrderSide) String

func (s OrderSide) String() string

type OrderState

type OrderState int

OrderState represents the state of an order as it is processed by a dealer.

func (OrderState) String

func (s OrderState) String() string

type OrderType

type OrderType int

OrderType represents an order type

const (
	// Market order type is executed at market price (taker).
	Market OrderType = iota + 1

	// Limit order type is executed at a specified price (maker).
	Limit
)

func (OrderType) MarshalText added in v0.0.20

func (t OrderType) MarshalText() ([]byte, error)

MarshalText is used to output as a string for CSV rendering.

func (OrderType) String

func (t OrderType) String() string

type Position

type Position struct {
	ID       DealID
	OpenedAt time.Time
	ClosedAt time.Time
	Asset    market.Asset
	Side     OrderSide

	// TradeCount is the number of trades (filled orders) applied
	TradeCount int

	// Cost is the net capital invested (inc fees) into the position
	Cost decimal.Decimal

	// Size is the number of units of the Asset controlled by the Position
	Size decimal.Decimal

	// EntryPrice is the average price paid per unit of the asset (inclusive of fees) i.e. Cost / Size
	EntryPrice decimal.Decimal

	// MarkPrice is the latest marked price for the asset
	MarkPrice decimal.Decimal

	// PNL is Size * (MarkPrice - EntryPrice)
	PNL decimal.Decimal

	// Exit price is the price at which the position was closed
	ExitPrice decimal.Decimal
}

Position represents a position in a market for a given asset.

func (*Position) State

func (p *Position) State() PositionState

State returns the state of the position based on the position timestamps.

type PositionState

type PositionState int

PositionState represents the state of a position as it is processed by a dealer.

func (PositionState) String

func (s PositionState) String() string

type RoundTurn added in v0.0.25

type RoundTurn struct {
	ID         DealID          `csv:"id"`
	CreatedAt  time.Time       `csv:"created_at"`
	Asset      market.Asset    `csv:",inline"`
	Side       OrderSide       `csv:"side"`
	Profit     decimal.Decimal `csv:"profit"`
	HoldPeriod time.Duration   `csv:"hold_period"`
	TradeCount int             `csv:"trade_count"`
}

RoundTurn is the result of opening and closing a position aka round-trip.

type SimulatedDealer

type SimulatedDealer interface {
	Dealer
	market.Receiver
	EquityHistory() EquitySeries
	SetInitialCapital(amount decimal.Decimal)
}

SimulatedDealer is a Dealer that can be used for backtesting.

type StubDealer

type StubDealer struct {
}

StubDealer is a test double for a simulated dealer that does nothing.

func (*StubDealer) CancelOrders

func (d *StubDealer) CancelOrders(ctx context.Context) (*web.Response, error)

CancelOrders not implemented.

func (*StubDealer) EquityHistory

func (d *StubDealer) EquityHistory() EquitySeries

EquityHistory not implemented.

func (*StubDealer) GetBalance

func (d *StubDealer) GetBalance(ctx context.Context) (*AccountBalance, *web.Response, error)

GetBalance not implemented.

func (*StubDealer) ListPositions

func (d *StubDealer) ListPositions(ctx context.Context, opts *web.ListOpts) ([]Position, *web.Response, error)

ListPositions not implemented.

func (*StubDealer) ListRoundTurns added in v0.0.25

func (d *StubDealer) ListRoundTurns(ctx context.Context, opts *web.ListOpts) ([]RoundTurn, *web.Response, error)

ListRoundTurns not implemented.

func (*StubDealer) PlaceOrder

func (d *StubDealer) PlaceOrder(ctx context.Context, order Order) (*Order, *web.Response, error)

PlaceOrder not implemented.

func (*StubDealer) ReceivePrice

func (d *StubDealer) ReceivePrice(ctx context.Context, price market.Kline) error

ReceivePrice not implemented.

func (*StubDealer) SetInitialCapital

func (d *StubDealer) SetInitialCapital(amount decimal.Decimal)

SetInitialCapital not implemented.

type TimeSeries

type TimeSeries[V any] map[Timestamp]V

TimeSeries represents a time series of values.

func (TimeSeries[V]) SortKeys

func (ts TimeSeries[V]) SortKeys() []Timestamp

SortKeys sorts the keys of the time series by time in ascending order.

func (TimeSeries[V]) SortValuesByTime

func (ts TimeSeries[V]) SortValuesByTime() []V

SortValuesByTime sorts the values of the time series by time in ascending order.

type Timestamp

type Timestamp int64

Timestamp represents a unix timestamp in milliseconds.

func (Timestamp) Time

func (t Timestamp) Time() time.Time

Time returns the time.Time representation of the Timestamp.

Directories

Path Synopsis
Package backtest provides a simultated dealer implementation for running backtests.
Package backtest provides a simultated dealer implementation for running backtests.

Jump to

Keyboard shortcuts

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