-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.go
More file actions
195 lines (160 loc) · 4.07 KB
/
main.go
File metadata and controls
195 lines (160 loc) · 4.07 KB
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
package main
import (
"encoding/json"
"fmt"
"net/http"
"strconv"
"github.com/cloakscn/crypto-exchange/orderbook"
"github.com/labstack/echo"
)
func main() {
fmt.Println("Hello Crypto Exchange!")
e := echo.New()
e.HTTPErrorHandler = httpErrorHandler
ex := NewExchange()
e.GET("/book/:market", ex.handleGetBook)
e.POST("/order", ex.handlePlaceOrder)
e.DELETE("/order/:id", ex.cancelOrder)
e.Start(":3000")
}
type OrderType string
func httpErrorHandler(err error, c echo.Context) {
fmt.Println(err)
}
const (
MarketOrder OrderType = "MARKET"
LimitOrder OrderType = "LIMIT"
)
type Market string
const (
MarketETH Market = "ETH"
)
type Exchange struct {
orderbooks map[Market]*orderbook.Orderbook
}
func NewExchange() *Exchange {
orderbooks := make(map[Market]*orderbook.Orderbook)
orderbooks[MarketETH] = orderbook.NewOrderbook()
return &Exchange{
orderbooks: orderbooks,
}
}
type PlaceOrderReq struct {
Type OrderType `json:"type"` // limit or market
Bid bool `json:"bid"`
Size float64 `json:"size"`
Price float64 `json:"price"`
Market Market `json:"market"`
}
type MatchedOrder struct {
Id int64 `json:"id"`
Price float64 `json:"price"`
Size float64 `json:"size"`
}
func (ex *Exchange) handlePlaceOrder(c echo.Context) error {
var placeOrderReq PlaceOrderReq
if err := json.NewDecoder(c.Request().Body).Decode(&placeOrderReq); err != nil {
return c.JSON(http.StatusExpectationFailed, nil)
}
market := Market(placeOrderReq.Market)
ob := ex.orderbooks[market]
order := orderbook.NewOrder(placeOrderReq.Bid, placeOrderReq.Size)
switch placeOrderReq.Type {
case LimitOrder:
ob.PlaceLimitOrder(placeOrderReq.Price, order)
return c.JSON(200, map[string]any{
"msg": "limit order placed",
})
case MarketOrder:
matches := ob.PlaceMarketOrder(order)
matchOrders := make([]*MatchedOrder, len(matches))
isBid := false
if order.Bid {
isBid = true
}
for i := 0; i < len(matchOrders); i++ {
id := matches[i].Bid.Id
if isBid {
id = matches[i].Ask.Id
}
matchOrders[i] = &MatchedOrder{
Id: id,
Price: matches[i].Price,
Size: matches[i].SizeFilled,
}
}
return c.JSON(200, map[string]any{
"matches": matchOrders,
})
default:
return c.JSON(http.StatusExpectationFailed, map[string]any{
"msg": "invalid order type",
})
}
}
type Order struct {
Id int64 `json:"id"`
Price float64 `json:"price"`
Size float64 `json:"size"`
Bid bool `json:"bid"`
Timestamp int64 `json:"timestamp"`
}
type OrderbookRep struct {
TotalBidVolume float64 `json:"totalBidVolume"`
TotalAskVolume float64 `json:"totalAskVolume"`
Asks []*Order `json:"asks"`
Bids []*Order `json:"bids"`
}
func (ex *Exchange) handleGetBook(c echo.Context) error {
market := Market(c.Param("market"))
ob, ok := ex.orderbooks[market]
if !ok {
return c.JSON(http.StatusBadRequest, map[string]any{
"msg": "market not found",
})
}
orderbookRep := OrderbookRep{
TotalBidVolume: ob.BitTotalVolume(),
TotalAskVolume: ob.AskTotalVolume(),
Asks: []*Order{},
Bids: []*Order{},
}
for _, limit := range ob.Asks() {
for _, order := range limit.Orders {
orderbookRep.Asks = append(orderbookRep.Asks, &Order{
Id: order.Id,
Price: limit.Price,
Size: order.Size,
Bid: order.Bid,
Timestamp: order.Timestamp,
})
}
}
for _, limit := range ob.Bids() {
for _, order := range limit.Orders {
orderbookRep.Bids = append(orderbookRep.Bids, &Order{
Id: order.Id,
Price: limit.Price,
Size: order.Size,
Bid: order.Bid,
Timestamp: order.Timestamp,
})
}
}
return c.JSON(http.StatusOK, orderbookRep)
}
func (ex *Exchange) cancelOrder(c echo.Context) error {
idStr := c.Param("id")
id, _ := strconv.Atoi(idStr)
ob := ex.orderbooks[MarketETH]
order, ok := ob.Orders[int64(id)]
if !ok {
return c.JSON(http.StatusBadRequest, map[string]any{
"msg": "order not found",
})
}
ob.CancelOrder(order)
return c.JSON(http.StatusOK, map[string]any{
"msg": "order cancelled",
})
}