-
Notifications
You must be signed in to change notification settings - Fork 0
/
xapi.go
219 lines (199 loc) · 5.13 KB
/
xapi.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
package xapi
import (
"encoding/json"
"fmt"
"sync"
"time"
"github.com/MateoGreil/xapi-go/internal/protocols/socket"
"github.com/MateoGreil/xapi-go/internal/protocols/stream"
"github.com/gorilla/websocket"
)
type client struct {
conn *websocket.Conn
streamConn *websocket.Conn
streamSessionId string
streamMessageChannel chan interface{}
CandlesChannel chan stream.Candle
mutexSendMessage sync.Mutex
}
const (
websocketBaseURL = "wss://ws.xtb.com"
pingInterval = 5 * time.Minute
)
func NewClient(userId string, password string, connectionType string) (*client, error) {
var websocketURL string
var websocketStreamURL string
switch connectionType {
case "demo":
websocketURL = websocketBaseURL + "/demo"
websocketStreamURL = websocketBaseURL + "/demoStream"
case "real":
websocketURL = websocketBaseURL + "/real"
websocketStreamURL = websocketBaseURL + "/realStream"
}
conn, _, err := websocket.DefaultDialer.Dial(websocketURL, nil)
if err != nil {
return nil, err
}
streamSessionId, err := login(conn, userId, password)
if err != nil {
return nil, err
}
streamConn, _, err := websocket.DefaultDialer.Dial(websocketStreamURL, nil)
if err != nil {
return nil, err
}
getKeepAlive(streamConn, streamSessionId)
var m sync.Mutex
c := &client{
conn: conn,
streamConn: streamConn,
streamSessionId: streamSessionId,
streamMessageChannel: make(chan interface{}),
CandlesChannel: make(chan stream.Candle),
mutexSendMessage: m,
}
go c.pingSocket()
go c.pingStream()
go c.listenStream()
go c.streamWriteJSON()
return c, nil
}
func (c *client) SubscribeCandles(symbol string) {
request := stream.GetCandlesRequest{
Command: "getCandles",
StreamSessionId: c.streamSessionId,
Symbol: symbol,
}
c.streamMessageChannel <- request
}
func (c *client) GetCandles(end int, period int, start int, symbol string, ticks int) ([]socket.Candle, error) {
request := socket.Request{
Command: "getChartRangeRequest",
Arguments: socket.InfoArguments{
Info: socket.GetCandlesInfo{
End: end,
Period: period,
Start: start,
Symbol: symbol,
Ticks: ticks,
},
},
}
response := socket.Response{}
c.mutexSendMessage.Lock()
c.conn.WriteJSON(request)
err := c.conn.ReadJSON(&response)
c.mutexSendMessage.Unlock()
if err != nil {
return nil, err
}
if response.Status != true {
return nil, fmt.Errorf("Error on sending getChartRangeRequest: %+v, response:, %+v", request, response)
}
return response.ReturnData.RateInfos, nil
}
func (c *client) listenStream() {
for {
_, message, err := c.streamConn.ReadMessage()
if err != nil {
fmt.Println(err.Error())
}
response := stream.Response{}
err = json.Unmarshal(message, &response)
if err != nil {
fmt.Printf("message: %s\n", message)
fmt.Println(err.Error())
}
switch response.Command {
case "candle":
responseCandle := stream.ResponseCandle{}
err = json.Unmarshal(message, &responseCandle)
if err != nil {
fmt.Println(err.Error())
}
c.CandlesChannel <- responseCandle.Data
case "keepAlive":
fmt.Printf("keepAlive received\n")
default:
fmt.Printf("Unknown stream message: %s\n", message)
}
}
}
func (c *client) pingSocket() {
for {
request := struct {
Command string `json:"command"`
}{Command: "ping"}
response := socket.Response{}
c.mutexSendMessage.Lock()
c.conn.WriteJSON(request)
err := c.conn.ReadJSON(&response)
c.mutexSendMessage.Unlock()
if err != nil {
//TODO: Handle error
fmt.Printf("Ping socket failed: %s", err.Error())
} else if response.Status != true {
fmt.Errorf("Error on sending request: %+v, response:, %+v", request, response)
}
time.Sleep(pingInterval)
}
}
func (c *client) pingStream() {
for {
request := stream.Request{
Command: "ping",
StreamSessionId: c.streamSessionId,
}
c.streamMessageChannel <- request
time.Sleep(pingInterval)
}
}
func (c *client) streamWriteJSON() {
for {
message := <-c.streamMessageChannel
c.streamConn.WriteJSON(message)
fmt.Printf("messageStream: %+v\n", message)
}
}
func login(conn *websocket.Conn, userId string, password string) (string, error) {
request := socket.Request{
Command: "login",
Arguments: socket.LoginRequestArguments{
UserId: userId,
Password: password,
},
}
conn.WriteJSON(request)
response := socket.LoginResponse{}
err := conn.ReadJSON(&response)
if err != nil {
return "", err
}
if response.Status == false {
return "", fmt.Errorf("%+v", response.ErrorDescr)
}
return response.StreamSessionId, nil
}
func getKeepAlive(conn *websocket.Conn, streamSessionId string) {
keepAliveReq := stream.Request{
Command: "getKeepAlive",
StreamSessionId: streamSessionId,
}
conn.WriteJSON(keepAliveReq)
_, message, err := conn.ReadMessage()
if err != nil {
// TODO: Handle errors
fmt.Println(err.Error())
}
response := stream.KeepAliveResponse{}
err = json.Unmarshal(message, &response)
if err != nil {
// TODO: Handle errors
fmt.Println(err.Error())
}
if response.Command != "keepAlive" {
// TODO: Handle errors
fmt.Println(err.Error())
}
}