This repository has been archived by the owner on Jul 17, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 24
/
exchange.go
97 lines (85 loc) · 2.12 KB
/
exchange.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
package deribit
import (
"errors"
"sync"
"github.com/adampointer/go-deribit/client/operations"
"github.com/adampointer/go-deribit/models"
"github.com/gorilla/websocket"
)
const (
liveURL = "wss://www.deribit.com/ws/api/v2/"
testURL = "wss://test.deribit.com/ws/api/v2/"
)
// ErrTimeout - request timed out
var ErrTimeout = errors.New("timed out waiting for a response")
// Exchange is an API wrapper with the exchange
type Exchange struct {
OnDisconnect func(*Exchange) // triggers on a failed read from connection
url string
test bool
conn *websocket.Conn
mutex sync.Mutex
pending map[uint64]*RPCCall
subscriptions map[string]*RPCSubscription
counter uint64
errors chan error
stop chan bool
auth *models.PublicAuthResponseResult
client *operations.Client
isClosed bool
}
// NewExchange creates a new API wrapper
// key and secret can be ignored if you are only calling public endpoints
func NewExchange(test bool, errs chan error, stop chan bool) (*Exchange, error) {
exc := &Exchange{
pending: make(map[uint64]*RPCCall, 1),
subscriptions: make(map[string]*RPCSubscription),
counter: 1,
errors: errs,
stop: stop,
}
exc.url = liveURL
if test {
exc.test = true
exc.url = testURL
}
return exc, nil
}
// Connect to the websocket API
func (e *Exchange) Connect() error {
c, _, err := websocket.DefaultDialer.Dial(e.url, nil)
if err != nil {
return err
}
e.conn = c
// Start listening for responses
go e.read()
//go e.heartbeat()
return nil
}
// Close the websocket connection
func (e *Exchange) Close() error {
e.mutex.Lock()
e.isClosed = true
e.mutex.Unlock()
if err := e.conn.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, "")); err != nil {
return err
}
return e.conn.Close()
}
/*func (e *Exchange) heartbeat() {
ticker := time.NewTicker(10 * time.Second)
go func() {
for {
select {
case <-ticker.C:
if _, err := e.Ping(); err != nil {
e.stop <- true
}
case <-e.stop:
ticker.Stop()
return
}
}
}()
}*/