orderbook

package module
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Sep 10, 2023 License: MIT Imports: 12 Imported by: 0

README

Go - Orderbook

Go Report Card License MIT Go Doc

The pkg go-orderbook implements a limit order book for high-frequency trading (HFT), as described by WK Selph.

Based on WK Selph's Blogpost: https://goo.gl/KF1SRm

Install

go get -u github.com/danielgatis/go-orderbook

And then import the package in your code:

import "github.com/danielgatis/go-orderbook"
Example

An example described below is one of the use cases.

package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"math/rand"
	"time"

	"github.com/danielgatis/go-orderbook"
	"github.com/google/uuid"
	"github.com/shopspring/decimal"
)

func main() {
	book := orderbook.NewOrderBook("BTC/BRL")

	for i := 0; i < 10; i++ {
		rand.Seed(time.Now().UnixNano())
		side := []orderbook.Side{orderbook.Buy, orderbook.Sell}[rand.Intn(2)]

		book.ProcessPostOnlyOrder(uuid.New().String(), uuid.New().String(), side, decimal.NewFromInt(rand.Int63n(1000)), decimal.NewFromInt(rand.Int63n(1000)))
	}

	depth, _ := json.Marshal(book.Depth())
	var buf bytes.Buffer
	json.Indent(&buf, depth, "", "  ")
	fmt.Println(buf.String())
}
❯ go run main.go
{
  "bids": [
    {
      "amount": "392",
      "price": "930"
    },
    {
      "amount": "872",
      "price": "907"
    },
    {
      "amount": "859",
      "price": "790"
    },
    {
      "amount": "643",
      "price": "424"
    },
    {
      "amount": "269",
      "price": "244"
    },
    {
      "amount": "160",
      "price": "83"
    },
    {
      "amount": "74",
      "price": "65"
    }
  ],
  "asks": [
    {
      "amount": "178",
      "price": "705"
    },
    {
      "amount": "253",
      "price": "343"
    },
    {
      "amount": "805",
      "price": "310"
    }
  ]
}

License

Copyright (c) 2020-present Daniel Gatis

Licensed under MIT License

Buy me a coffee

Liked some of my work? Buy me a coffee (or more likely a beer)

Buy Me A Coffee

Documentation

Overview

Package orderbook is a Limit Order Book for high-frequency trading.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrInvalidOrderID     = errors.New("Invalid order id")
	ErrInvalidTraderID    = errors.New("Invalid trader id")
	ErrInvalidAmount      = errors.New("Invalid amount")
	ErrInvalidPrice       = errors.New("Invalid price")
	ErrInvalidSide        = errors.New("Invalid side")
	ErrOrderAlreadyExists = errors.New("Order already exists")
)

Orderbook erros

Functions

This section is empty.

Types

type Depth

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

Depth represents a order book depth.

func NewDepth

func NewDepth(bids, asks []*PriceLevel) *Depth

NewDepth creates a new depth.

func (*Depth) Asks

func (d *Depth) Asks() []*PriceLevel

Asks returns a range of price leves.

func (*Depth) Bids

func (d *Depth) Bids() []*PriceLevel

Bids returns a range of price leves.

func (*Depth) MarshalJSON

func (d *Depth) MarshalJSON() ([]byte, error)

MarshalJSON implements json.MarshalJSON.

func (*Depth) UnmarshalJSON

func (d *Depth) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler.

type Order

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

Order represents a bid or an ask.

func NewOrder

func NewOrder(ID, traderID string, side Side, amount, price decimal.Decimal) *Order

NewOrder creates a new order.

func (*Order) Amount

func (o *Order) Amount() decimal.Decimal

Amount returns the amount.

func (*Order) ID

func (o *Order) ID() string

ID returns the order ID.

func (*Order) MarshalJSON

func (o *Order) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

func (*Order) Price

func (o *Order) Price() decimal.Decimal

Price returns the price.

func (*Order) Side

func (o *Order) Side() Side

Side returns the side.

func (*Order) TraderID

func (o *Order) TraderID() string

TraderID returns the trader ID.

func (*Order) UnmarshalJSON

func (o *Order) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler.

type OrderBook

type OrderBook struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

OrderBook represents a order book for a given market symbol.

func NewOrderBook

func NewOrderBook(symbol string) *OrderBook

NewOrderBook creates a new order book.

func Restore

func Restore(version uint64, raw [][][]string) *OrderBook

Restore restores a new order book from raw representation. Raw format is a nested arrays like: raw[ask[price][amount]][bid[price][amount]][symbol].

func (*OrderBook) CancelOrder

func (ob *OrderBook) CancelOrder(orderID string) *Order

CancelOrder canacels an order.

func (*OrderBook) Depth

func (ob *OrderBook) Depth() *Depth

Depth retruns the depth.

func (*OrderBook) MarshalJSON

func (ob *OrderBook) MarshalJSON() ([]byte, error)

MarshalJSON implements json.MarshalJSON.

func (*OrderBook) ProcessLimitOrder

func (ob *OrderBook) ProcessLimitOrder(orderID, traderID string, side Side, amount, price decimal.Decimal) ([]*Trade, error)

ProcessLimitOrder processes a limit order.

func (*OrderBook) ProcessMarketOrder

func (ob *OrderBook) ProcessMarketOrder(orderID, traderID string, side Side, amount, price decimal.Decimal) ([]*Trade, error)

ProcessMarketOrder processes a market order.

func (*OrderBook) ProcessPostOnlyOrder

func (ob *OrderBook) ProcessPostOnlyOrder(orderID, traderID string, side Side, amount, price decimal.Decimal) ([]*Trade, error)

ProcessPostOnlyOrder processes a post only order.

func (*OrderBook) ProcessPostOnlyOrderAppendAmount

func (ob *OrderBook) ProcessPostOnlyOrderAppendAmount(orderID, traderID string, side Side, amount, price decimal.Decimal) ([]*Trade, error)

ProcessPostOnlyOrder processes a post only order.

func (*OrderBook) Quote

func (ob *OrderBook) Quote(traderID string, side Side, amount decimal.Decimal) (*Quote, error)

Quote quotes a market order.

func (*OrderBook) Reset

func (ob *OrderBook) Reset(version uint64)

Reset resets the order book.

func (*OrderBook) Symbol

func (ob *OrderBook) Symbol() string

Symbol returns the symbol.

func (*OrderBook) UnmarshalJSON

func (ob *OrderBook) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler.

func (*OrderBook) Version

func (ob *OrderBook) Version() uint64

Version returns the version. The version is auto incremented by each change.

type OrderQueue

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

OrderQueue represents a queue of orders.

func NewOrderQueue

func NewOrderQueue(price decimal.Decimal) *OrderQueue

NewOrderQueue creates a new order queue.

func (*OrderQueue) Amount

func (oq *OrderQueue) Amount() decimal.Decimal

Amount returns the queue amout.

func (*OrderQueue) Append

func (oq *OrderQueue) Append(order *Order) *list.Element

Append appends an order.

func (*OrderQueue) Back

func (oq *OrderQueue) Back() *list.Element

Back returns the last order of the queue.

func (*OrderQueue) Front

func (oq *OrderQueue) Front() *list.Element

Front returns the first order of the queue.

func (*OrderQueue) Len

func (oq *OrderQueue) Len() int

Len returns the length.

func (*OrderQueue) Orders

func (oq *OrderQueue) Orders() *list.List

Orders returns the orders as a list.

func (*OrderQueue) Price

func (oq *OrderQueue) Price() decimal.Decimal

Price returns the queue price.

func (*OrderQueue) Remove

func (oq *OrderQueue) Remove(e *list.Element) *Order

Remove removes an order.

func (*OrderQueue) UpdateAmount

func (oq *OrderQueue) UpdateAmount(e *list.Element, amount decimal.Decimal) *Order

UpdateAmount updates an order amount.

type OrderSide

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

OrderSide represents all the prices about bids or asks.

func NewOrderSide

func NewOrderSide(side Side) *OrderSide

NewOrderSide creates a new order side.

func (*OrderSide) Append

func (os *OrderSide) Append(order *Order) *list.Element

Append appends an order.

func (*OrderSide) GreaterThan

func (os *OrderSide) GreaterThan(price decimal.Decimal) *OrderQueue

GreaterThan returns the order queue for the price greater than the given price.

func (*OrderSide) LessThan

func (os *OrderSide) LessThan(price decimal.Decimal) *OrderQueue

LessThan returns the order queue for the price less than the given price.

func (*OrderSide) MaxPriceQueue

func (os *OrderSide) MaxPriceQueue() *OrderQueue

MaxPriceQueue returns the order queue for the max price.

func (*OrderSide) MinPriceQueue

func (os *OrderSide) MinPriceQueue() *OrderQueue

MinPriceQueue returns the order queue for the min price.

func (*OrderSide) Orders

func (os *OrderSide) Orders() []*Order

Orders return all the orders sorted by price. Desc when side is buy. Asc when side is sell.

func (*OrderSide) Remove

func (os *OrderSide) Remove(e *list.Element) *Order

Remove removes an order.

func (*OrderSide) UpdateAmount

func (os *OrderSide) UpdateAmount(e *list.Element, amount decimal.Decimal) *Order

UpdateAmount updates an order amount.

type PriceLevel

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

PriceLevel takes a count of how many assets have that price.

func NewPriceLevel

func NewPriceLevel(price, amount decimal.Decimal) *PriceLevel

NewPriceLevel creates a new price level.

func (*PriceLevel) Amount

func (p *PriceLevel) Amount() decimal.Decimal

Amount returns the amount.

func (*PriceLevel) MarshalJSON

func (p *PriceLevel) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

func (*PriceLevel) Price

func (p *PriceLevel) Price() decimal.Decimal

Price returns the price.

func (*PriceLevel) UnmarshalJSON

func (p *PriceLevel) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler.

type Quote

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

Quote represents a quote.

func NewQuote

func NewQuote(price, remainingAmount decimal.Decimal) *Quote

NewQuote creates a new quote.

func (*Quote) MarshalJSON

func (m *Quote) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

func (*Quote) Price

func (m *Quote) Price() decimal.Decimal

Price returns the price.

func (*Quote) RemainingAmount

func (m *Quote) RemainingAmount() decimal.Decimal

RemainingAmount returns the remaining amount.

func (*Quote) UnmarshalJSON

func (m *Quote) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler.

type Side

type Side int

A Side of the order.

const (
	// Sell for asks
	Sell Side = 0

	// Buy for bids
	Buy Side = 1
)

func (Side) MarshalJSON

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

MarshalJSON implements json.Marshaler.

func (Side) String

func (s Side) String() string

String implements fmt.Stringer.

func (*Side) UnmarshalJSON

func (s *Side) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler.

type Trade

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

Trade represents a match between a maker order and a taker order.

func NewTrade

func NewTrade(takerOrderID, makerOrderID string, amount, price decimal.Decimal) *Trade

NewTrade creates a new trade.

func (*Trade) Amount

func (t *Trade) Amount() decimal.Decimal

Amount returns the amount.

func (*Trade) MakerOrderID

func (t *Trade) MakerOrderID() string

MakerOrderID returns the maker order id.

func (*Trade) MarshalJSON

func (t *Trade) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

func (*Trade) Price

func (t *Trade) Price() decimal.Decimal

Price returns the price.

func (*Trade) TakerOrderID

func (t *Trade) TakerOrderID() string

TakerOrderID returns the taker order id.

func (*Trade) UnmarshalJSON

func (t *Trade) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler.

Jump to

Keyboard shortcuts

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