-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathorder_trade_listener.go
193 lines (166 loc) · 4.72 KB
/
order_trade_listener.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
package fnmbroker
import (
"context"
"errors"
"fmt"
"sync"
"time"
finamclient "github.com/evsamsonov/FinamTradeGo/v2"
"github.com/evsamsonov/FinamTradeGo/v2/tradeapi"
"github.com/google/uuid"
"go.uber.org/zap"
"golang.org/x/sync/errgroup"
)
const (
orderTradeSendTimeout = 5 * time.Second
orderTradeKeepAliveTimeout = 1 * time.Minute
orderTradeSubscriptionRetryTimeout = 5 * time.Second
)
type orderTradeListener struct {
clientID string
token string
logger *zap.Logger
mu sync.RWMutex
orderChans []chan *tradeapi.OrderEvent
tradeChans []chan *tradeapi.TradeEvent
}
func newOrderTradeListener(clientID, token string, logger *zap.Logger) *orderTradeListener {
return &orderTradeListener{
clientID: clientID,
token: token,
logger: logger,
}
}
func (o *orderTradeListener) Run(ctx context.Context) error {
ctx, cancel := context.WithCancel(ctx)
g, ctx := errgroup.WithContext(ctx)
g.Go(func() error {
defer cancel()
o.logger.Debug("Start main subscription")
return o.run(ctx)
})
// Connection resets after 10 minutes and events may be lost.
// Redundant subscription is needed to receive events consistently.
// See https://github.com/FinamWeb/trade-api-docs/discussions/21#discussioncomment-8374024
g.Go(func() error {
defer cancel()
<-time.After(5 * time.Minute)
o.logger.Debug("Start redundant subscription")
return o.run(ctx)
})
return g.Wait()
}
// Subscribe subscribes to order and trade events.
// Unsubscribe function is third argument
func (o *orderTradeListener) Subscribe() (<-chan *tradeapi.OrderEvent, <-chan *tradeapi.TradeEvent, func()) {
orderChan := make(chan *tradeapi.OrderEvent)
tradeChan := make(chan *tradeapi.TradeEvent)
o.mu.Lock()
defer o.mu.Unlock()
o.orderChans = append(o.orderChans, orderChan)
o.tradeChans = append(o.tradeChans, tradeChan)
return orderChan, tradeChan, func() {
o.unsubscribe(orderChan)
}
}
func (o *orderTradeListener) run(ctx context.Context) error {
for {
client, err := finamclient.NewFinamClient(o.clientID, o.token, ctx)
if err != nil {
o.logger.Error("Failed to create finam client", zap.Error(err))
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(orderTradeSubscriptionRetryTimeout):
}
continue
}
if err := o.readOrderTrade(ctx, client); err != nil {
if errors.Is(err, context.Canceled) {
return err
}
o.logger.Warn(
"Failed to read order trade. Retry",
zap.Error(err),
)
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(orderTradeSubscriptionRetryTimeout):
}
}
}
}
func (o *orderTradeListener) readOrderTrade(ctx context.Context, client finamclient.IFinamClient) error {
requestID := uuid.New().String()[:16]
go client.SubscribeOrderTrade(&tradeapi.OrderTradeSubscribeRequest{
RequestId: requestID,
IncludeTrades: true,
IncludeOrders: true,
ClientIds: []string{o.clientID},
})
errChan := client.GetErrorChan()
orderChan := client.GetOrderChan()
orderTradeChan := client.GetOrderTradeChan()
for {
select {
case <-ctx.Done():
return ctx.Err()
case err := <-errChan:
return fmt.Errorf("read order trade: %w", err)
case <-time.After(orderTradeKeepAliveTimeout):
resp := client.SubscribeKeepAlive(&tradeapi.KeepAliveRequest{
RequestId: uuid.New().String()[:16],
})
if !resp.Success {
o.logger.Error("Failed to send keep alive", zap.Any("resp", resp))
continue
}
o.logger.Debug("Keep alive response", zap.Any("resp", resp))
case order := <-orderChan:
o.logger.Debug("Order received", zap.Any("orders", order))
o.sendOrders(ctx, order)
case trade := <-orderTradeChan:
o.logger.Debug("Trade received", zap.Any("orderTrade", trade))
o.sendTrades(ctx, trade)
}
}
}
func (o *orderTradeListener) sendOrders(ctx context.Context, order *tradeapi.OrderEvent) {
o.mu.RLock()
defer o.mu.RUnlock()
for _, ch := range o.orderChans {
select {
case <-ctx.Done():
return
case ch <- order:
case <-time.After(orderTradeSendTimeout):
o.logger.Error("Send order timeout", zap.Any("order", order))
}
}
}
func (o *orderTradeListener) sendTrades(ctx context.Context, trade *tradeapi.TradeEvent) {
o.mu.RLock()
defer o.mu.RUnlock()
for _, ch := range o.tradeChans {
select {
case <-ctx.Done():
return
case ch <- trade:
case <-time.After(orderTradeSendTimeout):
o.logger.Error("Send trade timeout", zap.Any("trade", trade))
}
}
}
func (o *orderTradeListener) unsubscribe(orderChan <-chan *tradeapi.OrderEvent) {
o.mu.Lock()
defer o.mu.Unlock()
for i, ch := range o.orderChans {
if orderChan != ch {
continue
}
o.orderChans = append(o.orderChans[:i], o.orderChans[i+1:]...)
o.tradeChans = append(o.tradeChans[:i], o.tradeChans[i+1:]...)
break
}
}