orderbook

package
v0.0.0-...-83dca6d Latest Latest
Warning

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

Go to latest
Published: May 23, 2022 License: MIT Imports: 14 Imported by: 0

README

GoCryptoTrader package Orderbook

Build Status Software License GoDoc Coverage Status Go Report Card

This orderbook package is part of the GoCryptoTrader codebase.

This is still in active development

You can track ideas, planned features and what's in progress on this Trello board: https://trello.com/b/ZAhMhpOy/gocryptotrader.

Join our slack to discuss all things related to GoCryptoTrader! GoCryptoTrader Slack

Current Features for orderbook

  • This package facilitates orderbook generation.

  • Attaches methods to an orderbook

    • To Return total Bids
    • To Return total Asks
    • Update orderbooks
  • Gets a loaded orderbook by exchange, asset type and currency pair.

  • This package is primarily used in conjunction with but not limited to the exchange interface system set by exchange wrapper orderbook functions in "exchange"_wrapper.go.

Examples below:

ob, err := yobitExchange.FetchOrderbook()
if err != nil {
	// Handle error
}

// Find total asks which also returns total orderbook value
totalAsks, totalOrderbookVal := ob.CalculateTotalAsks()
  • or if you have a routine setting an exchange orderbook you can access it via the package itself.
ob, err := orderbook.Get(...)
if err != nil {
	// Handle error
}
Please click GoDocs chevron above to view current GoDoc information for this package

Contribution

Please feel free to submit any pull requests or suggest any desired features to be added.

When submitting a PR, please abide by our coding guidelines:

  • Code must adhere to the official Go formatting guidelines (i.e. uses gofmt).
  • Code must be documented adhering to the official Go commentary guidelines.
  • Code must adhere to our coding style.
  • Pull requests need to be based on and opened against the master branch.

Donations

If this framework helped you in any way, or you would like to support the developers working on it, please donate Bitcoin to:

bc1qk0jareu4jytc0cfrhr5wgshsq8282awpavfahc

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func SubscribeToExchangeOrderbooks

func SubscribeToExchangeOrderbooks(exchange string) (dispatch.Pipe, error)

SubscribeToExchangeOrderbooks returns a pipe to an exchange feed

Types

type Base

type Base struct {
	Bids Items
	Asks Items

	Exchange string
	Pair     currency.Pair
	Asset    asset.Item

	LastUpdated  time.Time
	LastUpdateID int64
	// PriceDuplication defines whether an orderbook can contain duplicate
	// prices in a payload
	PriceDuplication bool
	IsFundingRate    bool
	// VerifyOrderbook allows for a toggle between orderbook verification set by
	// user configuration, this allows for a potential processing boost but
	// a potential for orderbook integrity being deminished.
	VerifyOrderbook bool `json:"-"`
	// RestSnapshot defines if the depth was applied via the REST protocol thus
	// an update cannot be applied via websocket mechanics and a resubscription
	// would need to take place to maintain book integrity
	RestSnapshot bool
	// Checks if the orderbook needs ID alignment as well as price alignment
	IDAlignment bool
}

Base holds the fields for the orderbook base

func Get

func Get(exchange string, p currency.Pair, a asset.Item) (*Base, error)

Get checks and returns the orderbook given an exchange name and currency pair

func (*Base) GetAveragePrice

func (b *Base) GetAveragePrice(buy bool, amount float64) (float64, error)

GetAveragePrice finds the average buy or sell price of a specified amount. It finds the nominal amount spent on the total purchase or sell and uses it to find the average price for an individual unit bought or sold

func (*Base) Process

func (b *Base) Process() error

Process processes incoming orderbooks, creating or updating the orderbook list

func (*Base) SimulateOrder

func (b *Base) SimulateOrder(amount float64, buy bool) *OrderSimulationResult

SimulateOrder simulates an order

func (*Base) TotalAsksAmount

func (b *Base) TotalAsksAmount() (amountCollated, total float64)

TotalAsksAmount returns the total amount of asks and the total orderbook asks value

func (*Base) TotalBidsAmount

func (b *Base) TotalBidsAmount() (amountCollated, total float64)

TotalBidsAmount returns the total amount of bids and the total orderbook bids value

func (*Base) Verify

func (b *Base) Verify() error

Verify ensures that the orderbook items are correctly sorted prior to being set and will reject any book with incorrect values. Bids should always go from a high price to a low price and Asks should always go from a low price to a higher price

func (*Base) WhaleBomb

func (b *Base) WhaleBomb(priceTarget float64, buy bool) (*WhaleBombResult, error)

WhaleBomb finds the amount required to target a price

type ByPrice

type ByPrice orderSummary

ByPrice used for sorting orders by order date

func (ByPrice) Len

func (b ByPrice) Len() int

func (ByPrice) Less

func (b ByPrice) Less(i, j int) bool

func (ByPrice) Swap

func (b ByPrice) Swap(i, j int)

type Depth

type Depth struct {
	alert.Notice
	// contains filtered or unexported fields
}

Depth defines a linked list of orderbook items

func DeployDepth

func DeployDepth(exchange string, p currency.Pair, a asset.Item) (*Depth, error)

DeployDepth sets a depth struct and returns a depth pointer. This allows for the loading of a new orderbook snapshot and incremental updates via the streaming package.

func GetDepth

func GetDepth(exchange string, p currency.Pair, a asset.Item) (*Depth, error)

GetDepth returns a Depth pointer allowing the caller to stream orderbook changes

func (*Depth) AssignOptions

func (d *Depth) AssignOptions(b *Base)

AssignOptions assigns the initial options for the depth instance

func (*Depth) DeleteBidAskByID

func (d *Depth) DeleteBidAskByID(bidUpdts, askUpdts Items, bypassErr bool, lastUpdateID int64, lastUpdated time.Time) error

DeleteBidAskByID deletes a price level by ID

func (*Depth) Flush

func (d *Depth) Flush()

Flush flushes the bid and ask depths

func (*Depth) GetAskLength

func (d *Depth) GetAskLength() int

GetAskLength returns length of asks

func (*Depth) GetBidLength

func (d *Depth) GetBidLength() int

GetBidLength returns length of bids

func (*Depth) GetName

func (d *Depth) GetName() string

GetName returns name of exchange

func (*Depth) GetUnsafe

func (d *Depth) GetUnsafe() Unsafe

GetUnsafe returns an unsafe orderbook with pointers to the linked list heads.

func (*Depth) InsertBidAskByID

func (d *Depth) InsertBidAskByID(bidUpdts, askUpdts Items, lastUpdateID int64, lastUpdated time.Time) error

InsertBidAskByID inserts new updates

func (*Depth) IsFundingRate

func (d *Depth) IsFundingRate() bool

IsFundingRate returns if the depth is a funding rate

func (*Depth) IsRestSnapshot

func (d *Depth) IsRestSnapshot() bool

IsRestSnapshot returns if the depth item was updated via REST

func (*Depth) LastUpdateID

func (d *Depth) LastUpdateID() int64

LastUpdateID returns the last Update ID

func (*Depth) LoadSnapshot

func (d *Depth) LoadSnapshot(bids, asks []Item, lastUpdateID int64, lastUpdated time.Time, updateByREST bool)

LoadSnapshot flushes the bids and asks with a snapshot

func (*Depth) Publish

func (d *Depth) Publish()

Publish alerts any subscribed routines using a dispatch mux

func (*Depth) Retrieve

func (d *Depth) Retrieve() *Base

Retrieve returns the orderbook base a copy of the underlying linked list spread

func (*Depth) TotalAskAmounts

func (d *Depth) TotalAskAmounts() (liquidity, value float64)

TotalAskAmounts returns the total amount of asks and the total orderbook asks value

func (*Depth) TotalBidAmounts

func (d *Depth) TotalBidAmounts() (liquidity, value float64)

TotalBidAmounts returns the total amount of bids and the total orderbook bids value

func (*Depth) UpdateBidAskByID

func (d *Depth) UpdateBidAskByID(bidUpdts, askUpdts Items, lastUpdateID int64, lastUpdated time.Time) error

UpdateBidAskByID amends details by ID

func (*Depth) UpdateBidAskByPrice

func (d *Depth) UpdateBidAskByPrice(bidUpdts, askUpdts Items, maxDepth int, lastUpdateID int64, lastUpdated time.Time)

UpdateBidAskByPrice updates the bid and ask spread by supplied updates, this will trim total length of depth level to a specified supplied number

func (*Depth) UpdateInsertByID

func (d *Depth) UpdateInsertByID(bidUpdts, askUpdts Items, lastUpdateID int64, lastUpdated time.Time) error

UpdateInsertByID updates or inserts by ID at current price level.

type Exchange

type Exchange struct {
	ID uuid.UUID
	// contains filtered or unexported fields
}

Exchange defines a holder for the exchange specific depth items with a specific ID associated with that exchange

type Item

type Item struct {
	Amount float64
	Price  float64
	ID     int64

	// Funding rate field
	Period int64

	// Contract variables
	LiquidationOrders int64
	OrderCount        int64
}

Item stores the amount and price values

type Items

type Items []Item

Items defines a slice of orderbook items

func (Items) FindNominalAmount

func (elem Items) FindNominalAmount(amount float64) (aggNominalAmount, remainingAmount float64)

FindNominalAmount finds the nominal amount spent in terms of the quote If the orderbook doesn't have enough liquidity it returns a non zero remaining amount value

func (*Items) Reverse

func (elem *Items) Reverse()

Reverse reverses the order of orderbook items; some bid/asks are returned in either ascending or descending order. One bid or ask slice depending on whats received can be reversed. This is usually faster than using a sort algorithm as the algorithm could be impeded by a worst case time complexity when elements are shifted as opposed to just swapping element values.

func (*Items) SortAsks

func (elem *Items) SortAsks()

SortAsks sorts ask items to the correct ascending order if pricing values are scattered. If order from exchange is descending consider using the Reverse function.

func (*Items) SortBids

func (elem *Items) SortBids()

SortBids sorts bid items to the correct descending order if pricing values are scattered. If order from exchange is ascending consider using the Reverse function.

type Node

type Node struct {
	Value Item
	Next  *Node
	Prev  *Node
	// contains filtered or unexported fields
}

Node defines a linked list node for an orderbook item

type OrderSimulationResult

type OrderSimulationResult WhaleBombResult

OrderSimulationResult returns the order simulation result

type Service

type Service struct {
	*dispatch.Mux
	sync.Mutex
	// contains filtered or unexported fields
}

Service provides a store for difference exchange orderbooks

func (*Service) DeployDepth

func (s *Service) DeployDepth(exchange string, p currency.Pair, a asset.Item) (*Depth, error)

DeployDepth used for subsystem deployment creates a depth item in the struct then returns a ptr to that Depth item

func (*Service) GetDepth

func (s *Service) GetDepth(exchange string, p currency.Pair, a asset.Item) (*Depth, error)

GetDepth returns the actual depth struct for potential subsystems and strategies to interact with

func (*Service) Retrieve

func (s *Service) Retrieve(exchange string, p currency.Pair, a asset.Item) (*Base, error)

Retrieve gets orderbook depth data from the associated linked list and returns the base equivalent copy

func (*Service) Update

func (s *Service) Update(b *Base) error

Update stores orderbook data

type Unsafe

type Unsafe struct {
	BidHead **Node
	AskHead **Node

	// UpdatedViaREST defines if sync manager is updating this book via the REST
	// protocol then this book is not considered live and cannot be trusted.
	UpdatedViaREST *bool
	LastUpdated    *time.Time
	*alert.Notice
	// contains filtered or unexported fields
}

Unsafe is an exported linked list reference to the current bid/ask heads and a reference to the underlying depth mutex. This allows for the exposure of the internal list to an external strategy or subsystem. The bid and ask fields point to the actual head fields contained on both linked list structs, so that this struct can be reusable and not needed to be called on each inspection.

func (*Unsafe) Lock

func (src *Unsafe) Lock()

Lock locks down the underlying linked list which inhibits all pending updates for strategy inspection.

func (*Unsafe) LockWith

func (src *Unsafe) LockWith(dst sync.Locker)

LockWith locks both books for the context of cross orderbook inspection. WARNING: When inspecting diametrically opposed books a higher order mutex MUST be used or a dead lock will occur.

func (*Unsafe) Unlock

func (src *Unsafe) Unlock()

Unlock unlocks the underlying linked list after inspection by a strategy to resume normal operations

func (*Unsafe) UnlockWith

func (src *Unsafe) UnlockWith(dst sync.Locker)

UnlockWith unlocks both books for the context of cross orderbook inspection

type WhaleBombResult

type WhaleBombResult struct {
	Amount               float64
	MinimumPrice         float64
	MaximumPrice         float64
	PercentageGainOrLoss float64
	Orders               orderSummary
	Status               string
}

WhaleBombResult returns the whale bomb result

Jump to

Keyboard shortcuts

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