-
Notifications
You must be signed in to change notification settings - Fork 1
/
model.go
96 lines (81 loc) · 2.12 KB
/
model.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
package orderbook
import (
"github.com/google/btree"
"github.com/shopspring/decimal"
)
// Side of order, either "sell" or "buy".
type Side string
const (
// SideSell is representation of sell Side.
SideSell Side = "sell"
// SideBuy is representation of buy Side.
SideBuy Side = "buy"
)
// Kind of order, either "Market" or "Limit".
// New types of order can be added.
type Kind string
const (
// KindMarket is representation of Market order.
KindMarket Kind = "market"
// KindLimit is representation of Limit order.
KindLimit Kind = "limit"
)
// Order is simple representation of order for matching engine.
type Order struct {
ID uint64 `json:"id"`
Side Side `json:"side"`
Kind Kind `json:"kind"`
Price decimal.Decimal `json:"price"`
Volume decimal.Decimal `json:"volume"`
Locked decimal.Decimal `json:"locked"`
Received decimal.Decimal `json:"received"`
}
// Trade is result of two matched orders.
type Trade struct {
Buy Order `json:"buy"`
Sell Order `json:"sell"`
Amount decimal.Decimal `json:"amount"`
Price decimal.Decimal `json:"price"`
}
// NewTrade creates new trade.
func NewTrade(buy, sell *Order, amount, price decimal.Decimal) *Trade {
return &Trade{
Buy: *buy,
Sell: *sell,
Amount: amount,
Price: price,
}
}
// CalculateLocked calculates locked according to order side.
func CalculateLocked(amount, price decimal.Decimal, side Side) decimal.Decimal {
switch side {
case SideBuy:
return amount.Mul(price)
case SideSell:
return amount
default:
return decimal.Zero
}
}
// Less compares two orders by price & ID, respects order Side.
// Used in order-book for sorting btree of orders.
func (o *Order) Less(other btree.Item) bool {
operand := other.(*Order)
switch o.Side {
case SideBuy:
if o.Price.LessThan(operand.Price) {
return false
} else if o.Price.GreaterThan(operand.Price) {
return true
}
return o.ID < operand.ID
case SideSell:
if o.Price.LessThan(operand.Price) {
return true
} else if o.Price.GreaterThan(operand.Price) {
return false
}
return o.ID < operand.ID
}
return false
}