forked from aliukevicius/cexio-websocket-api
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathorder_book_subscrition.go
More file actions
101 lines (76 loc) · 2.04 KB
/
Copy pathorder_book_subscrition.go
File metadata and controls
101 lines (76 loc) · 2.04 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
package cexio
import (
"encoding/json"
"errors"
"fmt"
"time"
log "github.com/sirupsen/logrus"
)
func (a *API) handleOrderBookSubscriptions(bookSnapshot *responseOrderBookSubscribe, currencyPair string, handler SubscriptionHandler) {
quit := make(chan bool)
subscriptionIdentifier := fmt.Sprintf("md_update_%s", currencyPair)
a.subscribe(subscriptionIdentifier)
a.orderBookHandlers[subscriptionIdentifier] = quit
obData := OrderBookUpdateData{
ID: bookSnapshot.Data.ID,
Pair: bookSnapshot.Data.Pair,
Timestamp: bookSnapshot.Data.Timestamp,
Bids: bookSnapshot.Data.Bids,
Asks: bookSnapshot.Data.Asks,
}
// process order book snapshot items before order book updates
go handler(obData)
sub, err := a.subscriber(subscriptionIdentifier)
if err != nil {
log.Info(err)
return
}
for {
select {
case <-quit:
return
case m := <-sub:
resp := m.(*responseOrderBookUpdate)
obData := OrderBookUpdateData{
ID: resp.Data.ID,
Pair: resp.Data.Pair,
Timestamp: resp.Data.Timestamp,
Bids: resp.Data.Bids,
Asks: resp.Data.Asks,
}
go handler(obData)
}
}
}
//OrderBookUnsubscribe unsubscribes from order book updates
func (a *API) OrderBookUnsubscribe(cCode1 string, cCode2 string) error {
action := "order-book-unsubscribe"
sub := a.subscribe(action)
defer a.unsubscribe(action)
timestamp := time.Now().UnixNano()
req := requestOrderBookUnsubscribe{
E: action,
Oid: fmt.Sprintf("%d_%s:%s", timestamp, cCode1, cCode2),
Data: orderBookPair{
Pair: []string{cCode1, cCode2},
},
}
err := a.conn.WriteJSON(req)
if err != nil {
return err
}
msg := (<-sub).([]byte)
resp := &responseOrderBookUnsubscribe{}
err = json.Unmarshal(msg, resp)
if err != nil {
return err
}
if resp.OK != "ok" {
return errors.New(resp.Data.Error)
}
handlerIdentifier := fmt.Sprintf("md_update_%s:%s", cCode1, cCode2)
// stop processing book messages
a.orderBookHandlers[handlerIdentifier] <- true
delete(a.orderBookHandlers, handlerIdentifier)
return nil
}