forked from quickfixgo/examples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathordermatch.go
More file actions
321 lines (268 loc) · 7.69 KB
/
ordermatch.go
File metadata and controls
321 lines (268 loc) · 7.69 KB
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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
// Copyright (c) quickfixengine.org All rights reserved.
//
// This file may be distributed under the terms of the quickfixengine.org
// license as defined by quickfixengine.org and appearing in the file
// LICENSE included in the packaging of this file.
//
// This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING
// THE WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A
// PARTICULAR PURPOSE.
//
// See http://www.quickfixengine.org/LICENSE for licensing information.
//
// Contact ask@quickfixengine.org if any conditions of this licensing
// are not clear to you.
package ordermatch
import (
"bufio"
"bytes"
"fmt"
"io"
"os"
"os/signal"
"path"
"strconv"
"syscall"
"github.com/quickfixgo/enum"
"github.com/quickfixgo/examples/cmd/ordermatch/internal"
"github.com/quickfixgo/examples/cmd/utils"
"github.com/quickfixgo/field"
"github.com/quickfixgo/fix42/executionreport"
"github.com/quickfixgo/fix42/marketdatarequest"
"github.com/quickfixgo/fix42/newordersingle"
"github.com/quickfixgo/fix42/ordercancelrequest"
"github.com/spf13/cobra"
"github.com/quickfixgo/quickfix"
)
// Application implements the quickfix.Application interface
type Application struct {
*quickfix.MessageRouter
*internal.OrderMatcher
execID int
}
func newApplication() *Application {
app := &Application{
MessageRouter: quickfix.NewMessageRouter(),
OrderMatcher: internal.NewOrderMatcher(),
}
app.AddRoute(newordersingle.Route(app.onNewOrderSingle))
app.AddRoute(ordercancelrequest.Route(app.onOrderCancelRequest))
app.AddRoute(marketdatarequest.Route(app.onMarketDataRequest))
return app
}
// OnCreate implemented as part of Application interface
func (a Application) OnCreate(_ quickfix.SessionID) {}
// OnLogon implemented as part of Application interface
func (a Application) OnLogon(_ quickfix.SessionID) {}
// OnLogout implemented as part of Application interface
func (a Application) OnLogout(_ quickfix.SessionID) {}
// ToAdmin implemented as part of Application interface
func (a Application) ToAdmin(_ *quickfix.Message, _ quickfix.SessionID) {}
// ToApp implemented as part of Application interface
func (a Application) ToApp(_ *quickfix.Message, _ quickfix.SessionID) error {
return nil
}
// FromAdmin implemented as part of Application interface
func (a Application) FromAdmin(_ *quickfix.Message, _ quickfix.SessionID) quickfix.MessageRejectError {
return nil
}
// FromApp implemented as part of Application interface, uses Router on incoming application messages
func (a *Application) FromApp(msg *quickfix.Message, sessionID quickfix.SessionID) (reject quickfix.MessageRejectError) {
return a.Route(msg, sessionID)
}
func (a *Application) onNewOrderSingle(msg newordersingle.NewOrderSingle, _ quickfix.SessionID) quickfix.MessageRejectError {
clOrdID, err := msg.GetClOrdID()
if err != nil {
return err
}
symbol, err := msg.GetSymbol()
if err != nil {
return err
}
senderCompID, err := msg.Header.GetSenderCompID()
if err != nil {
return err
}
targetCompID, err := msg.Header.GetTargetCompID()
if err != nil {
return err
}
side, err := msg.GetSide()
if err != nil {
return err
}
ordType, err := msg.GetOrdType()
if err != nil {
return err
}
price, err := msg.GetPrice()
if err != nil {
return err
}
orderQty, err := msg.GetOrderQty()
if err != nil {
return err
}
order := internal.Order{
ClOrdID: clOrdID,
Symbol: symbol,
SenderCompID: senderCompID,
TargetCompID: targetCompID,
Side: side,
OrdType: ordType,
Price: price,
Quantity: orderQty,
}
a.Insert(order)
a.acceptOrder(order)
matches := a.Match(order.Symbol)
for len(matches) > 0 {
a.fillOrder(matches[0])
matches = matches[1:]
}
return nil
}
func (a *Application) onOrderCancelRequest(msg ordercancelrequest.OrderCancelRequest, _ quickfix.SessionID) quickfix.MessageRejectError {
origClOrdID, err := msg.GetOrigClOrdID()
if err != nil {
return err
}
symbol, err := msg.GetSymbol()
if err != nil {
return err
}
side, err := msg.GetSide()
if err != nil {
return err
}
order := a.Cancel(origClOrdID, symbol, side)
if order != nil {
a.cancelOrder(*order)
}
return nil
}
func (a *Application) onMarketDataRequest(msg marketdatarequest.MarketDataRequest, _ quickfix.SessionID) (err quickfix.MessageRejectError) {
fmt.Printf("%+v\n", msg)
return
}
func (a *Application) acceptOrder(order internal.Order) {
a.updateOrder(order, enum.OrdStatus_NEW)
}
func (a *Application) fillOrder(order internal.Order) {
status := enum.OrdStatus_FILLED
if !order.IsClosed() {
status = enum.OrdStatus_PARTIALLY_FILLED
}
a.updateOrder(order, status)
}
func (a *Application) cancelOrder(order internal.Order) {
a.updateOrder(order, enum.OrdStatus_CANCELED)
}
func (a *Application) genExecID() string {
a.execID++
return strconv.Itoa(a.execID)
}
func (a *Application) updateOrder(order internal.Order, status enum.OrdStatus) {
execReport := executionreport.New(
field.NewOrderID(order.ClOrdID),
field.NewExecID(a.genExecID()),
field.NewExecTransType(enum.ExecTransType_NEW),
field.NewExecType(enum.ExecType(status)),
field.NewOrdStatus(status),
field.NewSymbol(order.Symbol),
field.NewSide(order.Side),
field.NewLeavesQty(order.OpenQuantity(), 2),
field.NewCumQty(order.ExecutedQuantity, 2),
field.NewAvgPx(order.AvgPx, 2),
)
execReport.SetOrderQty(order.Quantity, 2)
execReport.SetClOrdID(order.ClOrdID)
switch status {
case enum.OrdStatus_FILLED, enum.OrdStatus_PARTIALLY_FILLED:
execReport.SetLastShares(order.LastExecutedQuantity, 2)
execReport.SetLastPx(order.LastExecutedPrice, 2)
}
execReport.Header.SetTargetCompID(order.SenderCompID)
execReport.Header.SetSenderCompID(order.TargetCompID)
sendErr := quickfix.Send(execReport)
if sendErr != nil {
fmt.Println(sendErr)
}
}
const (
usage = "ordermatch"
short = "Start an order matching (FIX acceptor) service"
long = "Start an order matching (FIX acceptor) service."
)
var (
// Cmd is the quote command.
Cmd = &cobra.Command{
Use: usage,
Short: short,
Long: long,
Aliases: []string{"oms"},
Example: "qf ordermatch [YOUR_FIX_CONFIG_FILE_HERE.cfg] (default is ./config/ordermatch.cfg)",
RunE: execute,
}
)
func execute(_ *cobra.Command, args []string) error {
var cfgFileName string
argLen := len(args)
switch argLen {
case 0:
{
utils.PrintInfo("FIX config file not provided...")
utils.PrintInfo("attempting to use default location './config/ordermatch.cfg' ...")
cfgFileName = path.Join("config", "ordermatch.cfg")
}
case 1:
{
cfgFileName = args[0]
}
default:
{
return fmt.Errorf("incorrect argument number")
}
}
cfg, err := os.Open(cfgFileName)
if err != nil {
return fmt.Errorf("error opening %v, %v", cfgFileName, err)
}
defer cfg.Close()
stringData, readErr := io.ReadAll(cfg)
if readErr != nil {
return fmt.Errorf("error reading cfg: %s,", readErr)
}
appSettings, err := quickfix.ParseSettings(bytes.NewReader(stringData))
if err != nil {
return fmt.Errorf("error reading cfg: %s,", err)
}
logger := utils.NewFancyLog()
app := newApplication()
utils.PrintConfig("acceptor", bytes.NewReader(stringData))
acceptor, err := quickfix.NewAcceptor(app, quickfix.NewMemoryStoreFactory(), appSettings, logger)
if err != nil {
return fmt.Errorf("unable to create acceptor: %s", err)
}
err = acceptor.Start()
if err != nil {
return fmt.Errorf("unable to start FIX acceptor: %s", err)
}
interrupt := make(chan os.Signal, 1)
signal.Notify(interrupt, os.Interrupt, syscall.SIGTERM)
go func() {
<-interrupt
acceptor.Stop()
os.Exit(0)
}()
scanner := bufio.NewScanner(os.Stdin)
for {
scanner.Scan()
switch value := scanner.Text(); value {
case "#symbols":
app.Display()
default:
app.DisplayMarket(value)
}
}
}