/
orderbook_api.go
95 lines (84 loc) · 2.4 KB
/
orderbook_api.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package protocol
import (
"math/big"
"strconv"
"github.com/tomochain/orderbook/orderbook"
)
// remember that API structs to be offered MUST be exported
type OrderbookAPI struct {
V int
Engine *orderbook.Engine
}
// Version : return version
func (api *OrderbookAPI) Version() (int, error) {
return api.V, nil
}
func NewOrderbookAPI(v int, orderbookEngine *orderbook.Engine) *OrderbookAPI {
return &OrderbookAPI{
V: v,
Engine: orderbookEngine,
}
}
func (api *OrderbookAPI) getRecordFromOrder(order *orderbook.Order, ob *orderbook.OrderBook) map[string]string {
record := make(map[string]string)
record["timestamp"] = strconv.FormatUint(order.Item.Timestamp, 10)
record["price"] = order.Item.Price.String()
record["quantity"] = order.Item.Quantity.String()
// retrieve the input order_id, by default it is set when retrieving from orderbook
record["order_id"] = new(big.Int).SetBytes(order.Key).String()
record["trade_id"] = order.Item.TradeID
return record
}
func (api *OrderbookAPI) GetBestAskList(pairName string) []map[string]string {
ob, _ := api.Engine.GetOrderBook(pairName)
if ob == nil {
return nil
}
orderList := ob.Asks.MaxPriceList()
if orderList == nil {
return nil
}
// t.Logf("Best ask List : %s", orderList.String(0))
cursor := orderList.Head()
// we have length
results := make([]map[string]string, orderList.Item.Length)
for cursor != nil {
record := api.getRecordFromOrder(cursor, ob)
results = append(results, record)
cursor = cursor.GetNextOrder(orderList)
}
return results
}
func (api *OrderbookAPI) GetBestBidList(pairName string) []map[string]string {
ob, _ := api.Engine.GetOrderBook(pairName)
if ob == nil {
return nil
}
orderList := ob.Bids.MinPriceList()
// t.Logf("Best ask List : %s", orderList.String(0))
if orderList == nil {
return nil
}
cursor := orderList.Tail()
// we have length
results := make([]map[string]string, orderList.Item.Length)
for cursor != nil {
record := api.getRecordFromOrder(cursor, ob)
results = append(results, record)
cursor = cursor.GetPrevOrder(orderList)
}
return results
}
func (api *OrderbookAPI) GetOrder(pairName, orderID string) map[string]string {
var result map[string]string
ob, _ := api.Engine.GetOrderBook(pairName)
if ob == nil {
return nil
}
key := orderbook.GetKeyFromString(orderID)
order := ob.GetOrder(key)
if order != nil {
result = api.getRecordFromOrder(order, ob)
}
return result
}