-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathstreaming.go
165 lines (143 loc) · 4 KB
/
streaming.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
package goanda
import (
"bufio"
"context"
"encoding/json"
"fmt"
"net/http"
"strings"
)
type StreamingConnection struct {
*Connection
streamURL string
}
func NewStreamingConnection(c *Connection) *StreamingConnection {
streamURL := "https://stream-fxpractice.oanda.com/v3"
if strings.Contains(c.hostname, "fxtrade") {
streamURL = "https://stream-fxtrade.oanda.com/v3"
}
return &StreamingConnection{
Connection: c,
streamURL: streamURL,
}
}
func (c *Connection) NewStreamingConnection() *StreamingConnection {
return NewStreamingConnection(c)
}
func (sc *StreamingConnection) StreamPrices(instruments []string, callback func(PricingStreamResponse)) error {
endpoint := fmt.Sprintf("/accounts/%s/pricing/stream", sc.accountID)
url := sc.streamURL + endpoint + "?instruments=" + strings.Join(instruments, "%2C")
return sc.stream(url, func(data []byte) error {
var response PricingStreamResponse
err := json.Unmarshal(data, &response)
if err != nil {
return err
}
if response.Type == "" {
// This might be an error response
var errorResp struct {
ErrorMessage string `json:"errorMessage"`
}
if err := json.Unmarshal(data, &errorResp); err == nil && errorResp.ErrorMessage != "" {
return fmt.Errorf("API error: %s", errorResp.ErrorMessage)
}
}
callback(response)
return nil
})
}
func (sc *StreamingConnection) StreamTransactions(callback func(TransactionStreamResponse)) error {
endpoint := fmt.Sprintf("/accounts/%s/transactions/stream", sc.accountID)
url := sc.streamURL + endpoint
return sc.stream(url, func(data []byte) error {
var response TransactionStreamResponse
err := json.Unmarshal(data, &response)
if err != nil {
return err
}
callback(response)
return nil
})
}
func (sc *StreamingConnection) stream(url string, handler func([]byte) error) error {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
if err != nil {
return err
}
req.Header.Set("Authorization", sc.authHeader)
req.Header.Set("Accept-Datetime-Format", "RFC3339")
resp, err := sc.client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
done := make(chan struct{})
errChan := make(chan error, 1)
go func() {
scanner := bufio.NewScanner(resp.Body)
for scanner.Scan() {
line := scanner.Text()
if line == "" {
continue
}
// Handle heartbeats
if strings.HasPrefix(line, "{\"type\":\"HEARTBEAT\"") {
var heartbeat HeartbeatResponse
err := json.Unmarshal([]byte(line), &heartbeat)
if err == nil {
fmt.Printf("Received heartbeat at %s\n", heartbeat.Time)
}
continue
}
err := handler([]byte(line))
if err != nil {
errChan <- err
return
}
}
if err := scanner.Err(); err != nil {
errChan <- err
}
close(done)
}()
select {
case <-ctx.Done():
return ctx.Err()
case err := <-errChan:
return err
case <-done:
return nil
}
}
type PricingStreamResponse struct {
Type string `json:"type"`
Time string `json:"time"`
Instrument string `json:"instrument,omitempty"`
Bids []struct {
Price string `json:"price"`
Liquidity int `json:"liquidity"`
} `json:"bids,omitempty"`
Asks []struct {
Price string `json:"price"`
Liquidity int `json:"liquidity"`
} `json:"asks,omitempty"`
CloseoutBid string `json:"closeoutBid,omitempty"`
CloseoutAsk string `json:"closeoutAsk,omitempty"`
Status string `json:"status,omitempty"`
Tradeable bool `json:"tradeable,omitempty"`
}
type TransactionStreamResponse struct {
Type string `json:"type"`
Time string `json:"time"`
TransactionID string `json:"transactionID,omitempty"`
AccountID string `json:"accountID,omitempty"`
BatchID string `json:"batchID,omitempty"`
RequestID string `json:"requestID,omitempty"`
Transaction json.RawMessage `json:"transaction,omitempty"`
}
type HeartbeatResponse struct {
Type string `json:"type"`
Time string `json:"time"`
}