Git Product home page Git Product logo

orderbook's Introduction

Go orderbook

Improved matching engine written in Go (Golang)

Go Report Card GoDoc gocover.run Stability: Active Build Status

Features

  • Standard price-time priority
  • Supports both market and limit orders
  • Supports order cancelling
  • High performance (above 300k trades per second)
  • Optimal memory usage
  • JSON Marshalling and Unmarsalling
  • Calculating market price for definite quantity

Usage

To start using order book you need to create object:

import (
  "fmt" 
  ob "github.com/muzykantov/orderbook"
)

func main() {
  orderBook := ob.NewOrderBook()
  fmt.Println(orderBook)
}

Then you be able to use next primary functions:

func (ob *OrderBook) ProcessLimitOrder(side Side, orderID string, quantity, price decimal.Decimal) (done []*Order, partial *Order, err error) { ... }

func (ob *OrderBook) ProcessMarketOrder(side Side, quantity decimal.Decimal) (done []*Order, partial *Order, quantityLeft decimal.Decimal, err error) { .. }

func (ob *OrderBook) CancelOrder(orderID string) *Order { ... }

About primary functions

ProcessLimitOrder

// ProcessLimitOrder places new order to the OrderBook
// Arguments:
//      side     - what do you want to do (ob.Sell or ob.Buy)
//      orderID  - unique order ID in depth
//      quantity - how much quantity you want to sell or buy
//      price    - no more expensive (or cheaper) this price
//      * to create new decimal number you should use decimal.New() func
//        read more at https://github.com/shopspring/decimal
// Return:
//      error   - not nil if quantity (or price) is less or equal 0. Or if order with given ID is exists
//      done    - not nil if your order produces ends of anoter order, this order will add to
//                the "done" slice. If your order have done too, it will be places to this array too
//      partial - not nil if your order has done but top order is not fully done. Or if your order is
//                partial done and placed to the orderbook without full quantity - partial will contain
//                your order with quantity to left
//      partialQuantityProcessed - if partial order is not nil this result contains processed quatity from partial order
func (ob *OrderBook) ProcessLimitOrder(side Side, orderID string, quantity, price decimal.Decimal) (done []*Order, partial *Order, err error) { ... }

For example:

ProcessLimitOrder(ob.Sell, "uinqueID", decimal.New(55, 0), decimal.New(100, 0))

asks: 110 -> 5      110 -> 5
      100 -> 1      100 -> 56
--------------  ->  --------------
bids: 90  -> 5      90  -> 5
      80  -> 1      80  -> 1

done    - nil
partial - nil

ProcessLimitOrder(ob.Buy, "uinqueID", decimal.New(7, 0), decimal.New(120, 0))

asks: 110 -> 5
      100 -> 1
--------------  ->  --------------
bids: 90  -> 5      120 -> 1
      80  -> 1      90  -> 5
                    80  -> 1

done    - 2 (or more orders)
partial - uinqueID order

ProcessLimitOrder(ob.Buy, "uinqueID", decimal.New(3, 0), decimal.New(120, 0))

asks: 110 -> 5
      100 -> 1      110 -> 3
--------------  ->  --------------
bids: 90  -> 5      90  -> 5
      80  -> 1      90  -> 5

done    - 1 order with 100 price, (may be also few orders with 110 price) + uinqueID order
partial - 1 order with price 110

ProcessMarketOrder

// ProcessMarketOrder immediately gets definite quantity from the order book with market price
// Arguments:
//      side     - what do you want to do (ob.Sell or ob.Buy)
//      quantity - how much quantity you want to sell or buy
//      * to create new decimal number you should use decimal.New() func
//        read more at https://github.com/shopspring/decimal
// Return:
//      error        - not nil if price is less or equal 0
//      done         - not nil if your market order produces ends of anoter orders, this order will add to
//                     the "done" slice
//      partial      - not nil if your order has done but top order is not fully done
//      partialQuantityProcessed - if partial order is not nil this result contains processed quatity from partial order
//      quantityLeft - more than zero if it is not enought orders to process all quantity
func (ob *OrderBook) ProcessMarketOrder(side Side, quantity decimal.Decimal) (done []*Order, partial *Order, quantityLeft decimal.Decimal, err error) { .. }

For example:

ProcessMarketOrder(ob.Sell, decimal.New(6, 0))

asks: 110 -> 5      110 -> 5
      100 -> 1      100 -> 1
--------------  ->  --------------
bids: 90  -> 5      80 -> 1
      80  -> 2

done         - 2 (or more orders)
partial      - 1 order with price 80
quantityLeft - 0

ProcessMarketOrder(ob.Buy, decimal.New(10, 0))

asks: 110 -> 5
      100 -> 1
--------------  ->  --------------
bids: 90  -> 5      90  -> 5
      80  -> 1      80  -> 1
                    
done         - 2 (or more orders)
partial      - nil
quantityLeft - 4

CancelOrder

// CancelOrder removes order with given ID from the order book
func (ob *OrderBook) CancelOrder(orderID string) *Order { ... }
CancelOrder("myUinqueID-Sell-1-with-100")

asks: 110 -> 5
      100 -> 1      110 -> 5
--------------  ->  --------------
bids: 90  -> 5      90  -> 5
      80  -> 1      80  -> 1
                    
done         - 2 (or more orders)
partial      - nil
quantityLeft - 4

License

The MIT License (MIT)

See LICENSE and AUTHORS files

orderbook's People

Contributors

d-fal avatar i25959341 avatar joshelb avatar muzykantov avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

orderbook's Issues

Renaming Len?

Is it a bad idea to rename the Len function?
Users who are trying to combine this package with others may be confused on using the len function.

OrderSide top level does not add up

adding new orders in the same level does not add up the amount

I have unit tests that are failing to show the case

t.Run("test adding multiple bid quantities to the same level ", func(t *testing.T) {
		var err error
		engine := NewLocalMatchingEngine("BTCUSD")
		updatesChan, _, ob, err := engine.SubscribeToOrderBook(ctx, "USDEGP")
		if err != nil {
			t.Fatal(err)
		}
		// check that the subscription channel receives a snapshot
		snapshot := <-updatesChan
		assert.NotNil(t, snapshot)

		// add levels to local matching engine
		var price float64 = 112.32
		res1, err := engine.CreateOrder(ctx, types.CreateOrderRequest{
			ExternalAccountId: "test-1234",
			Side:              types.BUY,
			Price:             &price,
			Quantity:          2.14,
		})
		if err != nil {
			t.Fatal(err)
		}
		assert.NotNil(t, <-updatesChan)
		assert.Equal(t, "OPEN", res1.Status)

		res2, err := engine.CreateOrder(ctx, types.CreateOrderRequest{
			ExternalAccountId: "test-1235",
			Side:              types.BUY,
			Price:             &price,
			Quantity:          1.24,
		})
		if err != nil {
			t.Fatal(err)
		}
		assert.NotNil(t, <-updatesChan)
		assert.Equal(t, "OPEN", res2.Status)

		
		assert.Equal(t, fpdecimal.FromFloat[float64](10000), ob.GetBestBid())
		assert.Equal(t, 1, ob.GetDepth(orderbook.Bid))
		assert.Equal(t, fpdecimal.FromFloat[float64](3.38), ob.GetBestVolume(orderbook.Bid))
		assert.Equal(t, decimal.NewFromFloat32(3.38), engine.orderbook.Depth().Bids()[0].Amount())
	})

ProcessMarketOrder do not have UniqID argument

Hi,

Limit order function contain UniqID argument but not ProcessMarketOrder ?

Generating order ID and pass it to the function is better and let you backup it before returning the final result after matching.

equal to buy doesn't work

i changed the comperator to equal, but it doesn't work.
i need to match equal price tx only

comparator = price.Equal

Trying to implement it to a real project

Hi

I wanted to implement it to a real project, but it's a bit complicated.

Is there a way that for each rotation, I will get this rows:
-> Complete result for each BUY orders processed
-> Complete result for each SELL orders processed

Returning both of them no matter it is a BID or ASK.

SO I can for example update users balance, send notifications via websocket to update orderbook, update database order history etc...

Your help will be appreciated !

If matching server crash, orders will be lost ?

Hi,

Is there a way to recover orders in case of server crashed for some reasons ?

300k orders processed per second is this right ? What are the characteristics of the server used for that (RAM, Processor etc.) ?

Thank you

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.