/
brocker.go
259 lines (212 loc) · 5.34 KB
/
brocker.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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
package services
import (
"context"
"fmt"
"golang.org/x/sync/errgroup"
"github.com/marksartdev/trading/internal/broker"
"github.com/marksartdev/trading/internal/log"
)
const (
mainAction log.Action = "main"
statAction log.Action = "statistic"
dealsAction log.Action = "deals"
statGrpcAction log.Action = "statistic - gRPC"
dealsGrpcAction log.Action = "deals - gRPC"
)
// Broker service.
type brokerService struct {
logger log.Logger
clientRepo broker.ClientRepo
dealRepo broker.DealRepo
posRepo broker.PositionRepo
statRepo broker.StatisticRepo
exchange broker.ExchangeService
cancel context.CancelFunc
}
// NewBrokerService creates new broker.
func NewBrokerService(
logger log.Logger,
clientRepo broker.ClientRepo,
dealRepo broker.DealRepo,
posRepo broker.PositionRepo,
statRepo broker.StatisticRepo,
exchange broker.ExchangeService,
) broker.BrokerService {
return &brokerService{
logger: logger,
clientRepo: clientRepo,
dealRepo: dealRepo,
posRepo: posRepo,
statRepo: statRepo,
exchange: exchange,
}
}
// Start runs service.
func (b *brokerService) Start() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
b.cancel = cancel
g := &errgroup.Group{}
g.Go(func() error {
b.consumeStatistic(ctx)
return nil
})
g.Go(func() error {
b.consumeResults(ctx)
return nil
})
b.logger.Info(mainAction, "started")
if err := g.Wait(); err != nil {
b.logger.Error(mainAction, err)
}
b.logger.Info(mainAction, "stopped")
}
// Stop stops service.
func (b *brokerService) Stop() {
if b.cancel != nil {
b.cancel()
return
}
b.logger.Error(mainAction, fmt.Errorf("cancel func dose not initialized"))
}
// GetClient returns client. Create client if it is not exist.
func (b *brokerService) GetClient(login string) (broker.Client, error) {
client, ok, err := b.clientRepo.Get(login)
if err != nil {
return broker.Client{}, err
}
if !ok {
client.Login = login
client.Balance = 100000000
if err := b.clientRepo.Add(&client); err != nil {
return broker.Client{}, err
}
}
return client, nil
}
// GetProfile returns profile.
func (b *brokerService) GetProfile(login string) (broker.Profile, error) {
client, err := b.GetClient(login)
if err != nil {
return broker.Profile{}, err
}
positions, err := b.posRepo.Get(client.ID)
if err != nil {
return broker.Profile{}, err
}
deals, err := b.dealRepo.GetOpened(client.ID)
if err != nil {
return broker.Profile{}, err
}
return broker.Profile{
ClientID: client.ID,
Balance: client.Balance,
Positions: positions,
OpenDeals: deals,
}, nil
}
// Create creates deal and send it to exchange service.
func (b *brokerService) Create(deal broker.Deal) (broker.Deal, error) {
dealID, err := b.exchange.Create(deal)
if err != nil {
return broker.Deal{}, err
}
deal.ID = dealID
deal.Status = broker.DealStatusNew
if err := b.dealRepo.Add(deal); err != nil {
return broker.Deal{}, err
}
return deal, nil
}
// Cancel canceled deal.
func (b *brokerService) Cancel(dealID int64) (bool, error) {
ok, err := b.exchange.Cancel(dealID)
if err != nil {
return false, err
}
if ok {
if err := b.dealRepo.UpdateStatus(dealID, broker.DealStatusCanceled); err != nil {
return false, err
}
}
return ok, nil
}
// History returns ticker history.
func (b *brokerService) History(ticker string) ([]broker.OHLCV, error) {
history, err := b.statRepo.Get(ticker)
if err != nil {
return nil, err
}
return history, nil
}
// Consumes statistic.
func (b *brokerService) consumeStatistic(ctx context.Context) {
in := make(chan broker.OHLCV, 100)
g := &errgroup.Group{}
g.Go(func() error {
b.logger.Info(statGrpcAction, "started")
defer b.logger.Info(statGrpcAction, "stopped")
if err := b.exchange.Statistic(ctx, in); err != nil {
b.logger.Error(statGrpcAction, err)
}
return nil
})
b.logger.Info(statAction, "started")
defer b.logger.Info(statAction, "stopped")
for ohlcv := range in {
if err := b.statRepo.Add(ohlcv); err != nil {
b.logger.Error(statAction, err)
}
}
if err := g.Wait(); err != nil {
b.logger.Error(statAction, err)
}
}
// Consumes results of deals.
func (b *brokerService) consumeResults(ctx context.Context) {
in := make(chan broker.Deal, 100)
g := &errgroup.Group{}
g.Go(func() error {
b.logger.Info(dealsGrpcAction, "started")
defer b.logger.Info(dealsGrpcAction, "stopped")
if err := b.exchange.Results(ctx, in); err != nil {
b.logger.Error(dealsGrpcAction, err)
}
return nil
})
b.logger.Info(dealsAction, "started")
defer b.logger.Info(dealsAction, "stopped")
for deal := range in {
if err := b.dealRepo.Update(deal); err != nil {
b.logger.Error(dealsAction, err)
continue
}
position := broker.Position{
ClientID: deal.ClientID,
Ticker: deal.Ticker,
Amount: deal.Amount,
}
var err error
if deal.Type == broker.Buy {
err = b.posRepo.Add(position)
} else {
err = b.posRepo.Remove(position)
}
if err != nil {
b.logger.Error(dealsAction, err)
continue
}
if deal.Type == broker.Buy {
err = b.clientRepo.SubBalance(deal.ClientID, deal.Price*float64(deal.Amount))
} else {
err = b.clientRepo.SumBalance(deal.ClientID, deal.Price*float64(deal.Amount))
}
if err != nil {
b.logger.Error(dealsAction, err)
continue
}
}
if err := g.Wait(); err != nil {
b.logger.Error(dealsAction, err)
}
}