-
Notifications
You must be signed in to change notification settings - Fork 0
/
orders.go
344 lines (303 loc) · 8.33 KB
/
orders.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
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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
package dvotcWS
import (
"encoding/json"
"errors"
"fmt"
"log"
"sync"
"time"
"github.com/fasthttp/websocket"
)
type Order struct {
QuoteID string `json:"quoteId,omitempty"`
OrderType string `json:"orderType,omitempty"`
Asset string `json:"asset,omitempty"`
CounterAsset string `json:"counterAsset,omitempty"`
Price float64 `json:"price,omitempty"`
LimitPrice *string `json:"limitPrice,omitempty"`
Qty float64 `json:"qty,omitempty"`
Side string `json:"side,omitempty"`
ClientTag string `json:"clientTag,omitempty"`
}
type OrderStatus struct {
ID string `json:"_id"`
ClientTag string `json:"clientTag"`
LimitPrice string `json:"limitPrice"`
Price float64 `json:"price"`
Quantity float64 `json:"quantity"`
Side string `json:"side"`
OrderType string `json:"orderType,omitempty"`
Asset string `json:"asset"`
CounterAsset string `json:"counterAsset"`
Status string `json:"status"`
User User `json:"user"`
CreatedAt time.Time `json:"createdAt"`
FilledAt *time.Time `json:"filledAt"`
CancelledAt *time.Time `json:"cancelledAt"`
}
type MarketOrderParams struct {
QuoteID string `json:"quoteId"`
Asset string `json:"asset"`
CounterAsset string `json:"counterAsset"`
Price float64 `json:"price"`
Qty float64 `json:"qty"`
Side string `json:"side"`
ClientTag string `json:"clientTag"`
}
type LimitOrderParams struct {
Asset string `json:"asset"`
CounterAsset string `json:"counterAsset"`
LimitPrice float64 `json:"limitPrice"`
Qty float64 `json:"qty"`
Side string `json:"side"`
ClientTag string `json:"clientTag"`
}
type OrderResponseData = Subscription[*OrderStatus]
func (dvotc *DVOTCClient) PlaceMarketOrder(marketOrder MarketOrderParams) (*OrderStatus, error) {
conn, err := dvotc.getConnOrReuse(connectionOrders)
if err != nil {
return nil, err
}
order := &Order{
QuoteID: marketOrder.QuoteID,
OrderType: "market",
Asset: marketOrder.Asset,
CounterAsset: marketOrder.CounterAsset,
Price: marketOrder.Price,
Qty: marketOrder.Qty,
Side: marketOrder.Side,
ClientTag: marketOrder.ClientTag,
}
data, err := json.Marshal(order)
if err != nil {
return nil, err
}
payload := Payload{
Type: MessageTypeRequestResponse,
Event: dvotc.getRequestID(),
Topic: "createorder",
Data: data,
}
sub := &OrderResponseData{
Data: make(chan *OrderStatus),
Error: make(chan error),
topic: payload.Topic,
event: payload.Event,
conn: conn,
}
storeTradeAndErrorChann(dvotc.orderChanStore, &dvotc.chanMutex, sub.event, sub.topic, sub.Data, sub.Error)
defer func() {
close(sub.Data)
close(sub.Error)
cleanupTradeAndErrorChan(dvotc.orderChanStore, &dvotc.chanMutex, sub.event, sub.topic)
}()
if err := dvotc.writeJSONMessage(conn, payload); err != nil {
return nil, err
}
select {
case res := <-sub.Data:
return res, nil
case err := <-sub.Error:
return nil, err
}
}
func (dvotc *DVOTCClient) PlaceLimitOrder(limitOrder LimitOrderParams) (*OrderStatus, error) {
conn, err := dvotc.getConnOrReuse(connectionOrders)
if err != nil {
return nil, err
}
sellPriceStr := fmt.Sprintf("%g", limitOrder.LimitPrice)
order := Order{
OrderType: "LIMIT",
Asset: limitOrder.Asset,
CounterAsset: limitOrder.CounterAsset,
LimitPrice: &sellPriceStr,
Qty: limitOrder.Qty,
Side: limitOrder.Side,
ClientTag: limitOrder.ClientTag,
}
data, err := json.Marshal(order)
if err != nil {
return nil, err
}
payload := Payload{
Type: MessageTypeRequestResponse,
Event: dvotc.getRequestID(),
Topic: "createorder",
Data: data,
}
sub := &OrderResponseData{
Data: make(chan *OrderStatus),
Error: make(chan error),
topic: payload.Topic,
event: payload.Event,
conn: conn,
}
storeTradeAndErrorChann(dvotc.orderChanStore, &dvotc.chanMutex, sub.event, sub.topic, sub.Data, sub.Error)
defer func() {
close(sub.Data)
close(sub.Error)
cleanupTradeAndErrorChan(dvotc.orderChanStore, &dvotc.chanMutex, sub.event, sub.topic)
}()
if err := dvotc.writeJSONMessage(conn, payload); err != nil {
return nil, err
}
select {
case res := <-sub.Data:
return res, nil
case err := <-sub.Error:
return nil, err
}
}
func (dvotc *DVOTCClient) CancelOrder(orderID string) error {
conn, err := dvotc.getConn()
if err != nil {
return err
}
defer conn.Close()
payload := Payload{
Type: MessageTypeRequestResponse,
Event: dvotc.getRequestID(),
Topic: fmt.Sprintf("cancelorder/%s", orderID),
Data: nil,
}
err = conn.WriteJSON(payload)
if err != nil {
return err
}
resp := &Payload{}
if err := conn.ReadJSON(resp); err != nil {
return err
}
if resp.Type == "error" {
return errors.New(string(resp.Data))
}
return nil
}
func (dvotc *DVOTCClient) SubscribeOrderChanges(status string) (*Subscription[OrderStatus], error) {
conn, err := dvotc.getConn()
if err != nil {
return nil, err
}
payload := Payload{
Type: MessageTypeSubscribe,
Event: "order-updates",
Topic: fmt.Sprintf("order/%s", status),
Data: nil,
}
err = conn.WriteJSON(payload)
if err != nil {
return nil, err
}
sub := &Subscription[OrderStatus]{
Data: make(chan OrderStatus, 100),
done: make(chan struct{}),
conn: conn,
topic: payload.Topic,
event: payload.Event,
}
go func() {
defer close(sub.Data)
for {
select {
case <-sub.done:
return
default:
resp := Payload{}
if err := sub.conn.ReadJSON(&resp); err != nil {
if !websocket.IsUnexpectedCloseError(err, websocket.CloseAbnormalClosure) {
// server closed connection
log.Default().Print("server closed connection")
}
continue
}
switch resp.Type {
case MessageTypeError:
return
case MessageTypeInfo:
if resp.Event == "reconnect" {
newConn, err := dvotc.retryConnWithPayload(payload)
if err != nil {
// can't do much after all retries fail
fmt.Println(err)
return
}
sub.conn = newConn
}
continue
}
orderStatus := OrderStatus{}
if err := json.Unmarshal(resp.Data, &orderStatus); err != nil {
return
}
sub.Data <- orderStatus
}
}
}()
return sub, nil
}
func (dvotc *DVOTCClient) readOrderMessageLoop(conn *websocket.Conn, cleanupFunc func()) {
for {
resp := Payload{}
if err := conn.ReadJSON(&resp); err != nil {
if !websocket.IsUnexpectedCloseError(err, websocket.CloseAbnormalClosure) {
// server closed connection
log.Default().Print("server closed connection")
}
if cleanupFunc != nil {
cleanupFunc()
}
return
}
// handle error
if resp.Type == "error" {
errResp := ErrorResponse{}
if err := json.Unmarshal(resp.Data, &errResp); err != nil {
dispatchTradeData(dvotc.orderChanStore, &dvotc.chanMutex, resp.Event, resp.Topic, nil, err)
continue
}
dispatchTradeData(dvotc.orderChanStore, &dvotc.chanMutex, resp.Event, resp.Topic, nil, errors.New(errResp.Message))
continue
}
orderStatus := OrderStatus{}
if err := json.Unmarshal(resp.Data, &orderStatus); err != nil {
return
}
dispatchTradeData(dvotc.orderChanStore, &dvotc.chanMutex, resp.Event, resp.Topic, &orderStatus, nil)
}
}
func dispatchTradeData(safeChanStore map[string]tradeData, mutex *sync.RWMutex, event, topic string, trade *OrderStatus, err error) {
mutex.Lock()
defer mutex.Unlock()
key := fmt.Sprintf("%s:%s", topic, event)
channels, ok := safeChanStore[key]
if !ok {
log.Panicf("key already exist for trade %s", key)
}
if err != nil {
channels.err <- err
} else {
channels.data <- trade
}
}
func storeTradeAndErrorChann(safeChanStore map[string]tradeData, mutex *sync.RWMutex, event, topic string, channel chan *OrderStatus, errChan chan error) {
mutex.Lock()
defer mutex.Unlock()
key := fmt.Sprintf("%s:%s", topic, event)
_, ok := safeChanStore[key]
if ok {
log.Panicf("key already exist for trade %s", key)
}
safeChanStore[key] = tradeData{
data: channel,
err: errChan,
}
}
// cleanupTradeAndErrorChan remove the tradeData channels for a key
// TODO: make this cleanup on a timer basis
func cleanupTradeAndErrorChan(safeChanStore map[string]tradeData, mutex *sync.RWMutex, event, topic string) {
mutex.Lock()
defer mutex.Unlock()
key := fmt.Sprintf("%s:%s", topic, event)
delete(safeChanStore, key)
}