/
order.go
executable file
·98 lines (84 loc) · 2.71 KB
/
order.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
96
97
98
package orderbook
import (
"bytes"
"fmt"
"math/big"
"strconv"
)
// OrderItem : info that will be store in database
type OrderItem struct {
Timestamp uint64 `json:"timestamp"`
Quantity *big.Int `json:"quantity"`
Price *big.Int `json:"price"`
// OrderID string `json:"orderID"`
TradeID string `json:"tradeID"`
// these following fields can lead to recursive problem
// NextOrder *Order `json:"-"`
// PrevOrder *Order `json:"-"`
// OrderList *OrderList `json:"-"`
// *OrderMeta
NextOrder []byte `json:"-"`
PrevOrder []byte `json:"-"`
OrderList []byte `json:"-"`
}
// OrderMeta to help building linked list, there would be a consecutive order meta for each linkedlist
// and slot offset is slot of linkedlist
// type OrderMeta struct {
// NextOrder []byte `json:"-"`
// PrevOrder []byte `json:"-"`
// OrderList []byte `json:"-"`
// }
type Order struct {
Item *OrderItem
Key []byte `json:"orderID"`
}
func (order *Order) String() string {
return fmt.Sprintf("orderID : %s, price: %s, quantity :%s, tradeID: %s",
new(big.Int).SetBytes(order.Key), order.Item.Price, order.Item.Quantity, order.Item.TradeID)
}
func (order *Order) GetNextOrder(orderList *OrderList) *Order {
nextOrder := orderList.GetOrder(order.Item.NextOrder)
return nextOrder
}
func (order *Order) GetPrevOrder(orderList *OrderList) *Order {
prevOrder := orderList.GetOrder(order.Item.PrevOrder)
return prevOrder
}
// NewOrder : create new order with quote ( can be ethereum address )
func NewOrder(quote map[string]string, orderList []byte) *Order {
timestamp, _ := strconv.ParseUint(quote["timestamp"], 10, 64)
quantity := ToBigInt(quote["quantity"])
price := ToBigInt(quote["price"])
orderID := ToBigInt(quote["order_id"])
key := GetKeyFromBig(orderID)
tradeID := quote["trade_id"]
orderItem := &OrderItem{
Timestamp: timestamp,
Quantity: quantity,
Price: price,
// OrderID: orderID,
TradeID: tradeID,
NextOrder: EmptyKey(),
PrevOrder: EmptyKey(),
OrderList: orderList,
}
// key should be Hash for compatible with smart contract
order := &Order{
Key: key,
Item: orderItem,
}
return order
}
// UpdateQuantity : update quantity of the order
func (order *Order) UpdateQuantity(orderList *OrderList, newQuantity *big.Int, newTimestamp uint64) {
if newQuantity.Cmp(order.Item.Quantity) > 0 && !bytes.Equal(orderList.Item.TailOrder, order.Key) {
orderList.MoveToTail(order)
}
// update volume and modified timestamp
orderList.Item.Volume = Sub(orderList.Item.Volume, Sub(order.Item.Quantity, newQuantity))
order.Item.Timestamp = newTimestamp
order.Item.Quantity = CloneBigInt(newQuantity)
fmt.Println("QUANTITY", order.Item.Quantity.String())
orderList.SaveOrder(order)
orderList.Save()
}