/
disorderBook_front.go
967 lines (769 loc) · 27.6 KB
/
disorderBook_front.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
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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
package main
import (
"bufio"
"bytes"
"encoding/json"
"errors"
"flag"
"fmt"
"github.com/gorilla/websocket" // go get github.com/gorilla/websocket
"io"
"io/ioutil"
"net/http"
"os"
"os/exec"
"strconv"
"strings"
"sync"
)
type PipesStruct struct {
stdin io.WriteCloser
stdout io.ReadCloser
stderr io.ReadCloser
}
type OrderStruct struct {
Symbol string `json:"symbol"`
Stock string `json:"stock"`
Venue string `json:"venue"`
Direction string `json:"direction"`
OrderType string `json:"orderType"`
Account string `json:"account"`
Qty int32 `json:"qty"`
Price int32 `json:"price"`
}
type OptionsStruct struct {
MaxBooks int
Port int
WsPort int
AccountFilename string
DefaultVenue string
DefaultSymbol string
Excess bool
}
type WsInfo struct {
Account string
Venue string
Symbol string
ConnType int
MessageChannel chan string
}
const (
HEARTBEAT_OK = `{"ok": true, "error": ""}`
UNKNOWN_PATH = `{"ok": false, "error": "Unknown path"}`
UNKNOWN_VENUE = `{"ok": false, "error": "Unknown venue"}`
UNKNOWN_SYMBOL = `{"ok": false, "error": "Venue is known but symbol is not"}`
BAD_JSON = `{"ok": false, "error": "Failed to parse incoming JSON"}`
URL_MISMATCH = `{"ok": false, "error": "Venue or symbol in URL did not match that in POST"}`
MISSING_FIELD = `{"ok": false, "error": "Missing key or unacceptable value in POST"}`
UNKNOWN_ORDER = `{"ok": false, "error": "Unknown order ID"}`
BAD_ORDER = `{"ok": false, "error": "Couldn't parse order ID"}`
AUTH_FAILURE = `{"ok": false, "error": "Unknown account or wrong API key"}`
NO_VENUE_HEART = `{"ok": false, "error": "Venue not up (create it by using it)"}`
CREATE_BOOK_FAIL = `{"ok": false, "error": "Couldn't create book! Either: bad name, or too many books exist"}`
NOT_IMPLEMENTED = `{"ok": false, "error": "Not implemented"}`
DISABLED = `{"ok": false, "error": "Disabled or not enabled. (See command line options)"}`
BAD_ACCOUNT_NAME = `{"ok": false, "error": "Bad account name (should be alpha_numeric and sane length)"}`
)
const (
BUY = 1
SELL = 2
)
const (
LIMIT = 1
MARKET = 2
FOK = 3
IOC = 4
)
const (
TICKER = 1
EXECUTION = 2
)
const FRONTPAGE = `<html>
<head><title>disorderBook</title></head>
<body><pre>
disorderBook: unofficial Stockfighter server
C+Go version
https://github.com/fohristiwhirl/disorderBook_Prime
By Amtiskaw (Fohristiwhirl on GitHub)
With help from cite-reader, Medecau and DanielVF
Mad props to patio11 for the elegant fundamental design!
Also inspired by eu90h's Mockfighter
"WOAH THATS FAST" -- DanielVF
</pre></body></html>`
// --------------------------------------------------------------------------------------------
var Books = make(map[string]map[string]*PipesStruct)
var Locks = make(map[string]map[string]*sync.Mutex)
var AccountInts = make(map[string]int)
var Auth = make(map[string]string)
var AuthMode = false
var BookCount = 0
var Options OptionsStruct
var WebSocketClients = make([]*WsInfo, 0)
var ClientListLock sync.Mutex
var Upgrader = websocket.Upgrader{ReadBufferSize: 1024, WriteBufferSize: 1024}
// --------------------------------------------------------------------------------------------
func bad_name(name string) bool {
if len(name) < 1 || len(name) > 20 {
return true
}
// Disallow all chars except alphanumeric and underscore...
for _, c := range(name) {
if c < 48 || (c > 57 && c < 65) || (c > 90 && c < 95) || c == 96 || c > 122 {
return true
}
}
return false
}
func create_book_if_needed(venue string, symbol string) error {
if bad_name(venue) || bad_name(symbol) {
return errors.New("Bad name for a book!")
}
if Books[venue] == nil {
if BookCount >= Options.MaxBooks {
return errors.New("Too many books!")
}
Books[venue] = make(map[string]*PipesStruct)
Locks[venue] = make(map[string]*sync.Mutex)
}
if Books[venue][symbol] == nil {
if BookCount >= Options.MaxBooks {
return errors.New("Too many books!")
}
command := exec.Command("./disorderBook.exe", venue, symbol)
i_pipe, _ := command.StdinPipe()
o_pipe, _ := command.StdoutPipe()
e_pipe, _ := command.StderrPipe()
// Should maybe handle errors from the above.
new_pipes_struct := PipesStruct{i_pipe, o_pipe, e_pipe}
Books[venue][symbol] = &new_pipes_struct
Locks[venue][symbol] = new(sync.Mutex) // new() returns a pointer
BookCount++
command.Start()
go ws_controller(venue, symbol)
}
return nil
}
func get_response_from_book(command string, venue string, symbol string) string {
v := Books[venue]
if v == nil {
return UNKNOWN_VENUE
}
s := Books[venue][symbol]
if s == nil {
return UNKNOWN_SYMBOL
}
if len(command) == 0 || command[len(command) - 1] != '\n' {
command = command + "\n"
}
Locks[venue][symbol].Lock()
fmt.Fprintf(Books[venue][symbol].stdin, command)
scanner := bufio.NewScanner(Books[venue][symbol].stdout)
var buffer bytes.Buffer
for {
scanner.Scan()
str_piece := scanner.Text()
if str_piece != "END" {
buffer.WriteString(str_piece)
buffer.WriteByte('\n')
} else {
break
}
}
Locks[venue][symbol].Unlock()
return buffer.String()
}
func get_binary_orderbook_to_json(venue string, symbol string) string {
// See comments in the C code for how the incoming data is formatted
v := Books[venue]
if v == nil {
return UNKNOWN_VENUE
}
s := Books[venue][symbol]
if s == nil {
return UNKNOWN_SYMBOL
}
Locks[venue][symbol].Lock()
reader := bufio.NewReader(Books[venue][symbol].stdout)
fmt.Fprintf(Books[venue][symbol].stdin, "ORDERBOOK_BINARY\n")
var nextbyte byte
var qty uint32
var price uint32
var commaflag bool
var buffer bytes.Buffer
buffer.WriteString("{\n \"ok\": true,\n \"venue\": \"")
buffer.WriteString(venue)
buffer.WriteString("\",\n \"symbol\": \"")
buffer.WriteString(symbol)
buffer.WriteString("\",\n \"bids\": [")
wrote_any_bids := false
wrote_any_asks := false
commaflag = false
for {
qty = 0
nextbyte, _ = reader.ReadByte()
qty += uint32(nextbyte) << 24
nextbyte, _ = reader.ReadByte()
qty += uint32(nextbyte) << 16
nextbyte, _ = reader.ReadByte()
qty += uint32(nextbyte) << 8
nextbyte, _ = reader.ReadByte()
qty += uint32(nextbyte)
price = 0
nextbyte, _ = reader.ReadByte()
price += uint32(nextbyte) << 24
nextbyte, _ = reader.ReadByte()
price += uint32(nextbyte) << 16
nextbyte, _ = reader.ReadByte()
price += uint32(nextbyte) << 8
nextbyte, _ = reader.ReadByte()
price += uint32(nextbyte)
if qty != 0 {
if commaflag {
buffer.WriteString(",")
}
buffer.WriteString("\n {\"price\": ")
buffer.WriteString(strconv.FormatUint(uint64(price), 10))
buffer.WriteString(", \"qty\": ")
buffer.WriteString(strconv.FormatUint(uint64(qty), 10))
buffer.WriteString(", \"isBuy\": true}")
commaflag = true
wrote_any_bids = true
} else {
break
}
}
if wrote_any_bids {
buffer.WriteString("\n ")
}
buffer.WriteString("],\n \"asks\": [")
commaflag = false
for {
qty = 0
nextbyte, _ = reader.ReadByte()
qty += uint32(nextbyte) << 24
nextbyte, _ = reader.ReadByte()
qty += uint32(nextbyte) << 16
nextbyte, _ = reader.ReadByte()
qty += uint32(nextbyte) << 8
nextbyte, _ = reader.ReadByte()
qty += uint32(nextbyte)
price = 0
nextbyte, _ = reader.ReadByte()
price += uint32(nextbyte) << 24
nextbyte, _ = reader.ReadByte()
price += uint32(nextbyte) << 16
nextbyte, _ = reader.ReadByte()
price += uint32(nextbyte) << 8
nextbyte, _ = reader.ReadByte()
price += uint32(nextbyte)
if qty != 0 {
if commaflag {
buffer.WriteString(",")
}
buffer.WriteString("\n {\"price\": ")
buffer.WriteString(strconv.FormatUint(uint64(price), 10))
buffer.WriteString(", \"qty\": ")
buffer.WriteString(strconv.FormatUint(uint64(qty), 10))
buffer.WriteString(", \"isBuy\": false}")
commaflag = true
wrote_any_asks = true
} else {
break
}
}
Locks[venue][symbol].Unlock()
// The above Unlock() has to happen before calling
// get_response_from_book() for the timestamp since it also locks.
ts := get_response_from_book("__TIMESTAMP__", venue, symbol)
ts = strings.Trim(ts, "\n\r\t ")
if wrote_any_asks {
buffer.WriteString("\n ")
}
buffer.WriteString("],\n \"ts\": \"")
buffer.WriteString(ts)
buffer.WriteString("\"\n}")
return buffer.String()
}
func main_handler(writer http.ResponseWriter, request * http.Request) {
writer.Header().Set("Content-Type", "application/json") // A few things change this later
request_api_key := request.Header.Get("X-Starfighter-Authorization")
if request_api_key == "" {
request_api_key = request.Header.Get("X-Stockfighter-Authorization")
}
path_clean := strings.Trim(request.URL.Path, "\n\r\t /")
pathlist := strings.Split(path_clean, "/")
// Welcome message for "/"
if len(pathlist) == 1 && pathlist[0] == "" { // The split behaviour means len is never 0
writer.Header().Set("Content-Type", "text/html")
fmt.Fprintf(writer, FRONTPAGE)
return
}
// Check for obvious path fails...
if len(pathlist) < 2 || pathlist[0] != "ob" || pathlist[1] != "api" {
fmt.Fprintf(writer, UNKNOWN_PATH)
return
}
// General heartbeat...
if len(pathlist) == 3 {
if pathlist[2] == "heartbeat" {
fmt.Fprintf(writer, HEARTBEAT_OK)
return
}
}
// Venues list...
if len(pathlist) == 3 {
if pathlist[2] == "venues" {
fmt.Fprintf(writer, `{"ok": true, "venues": [`)
name := ""
commaflag := false
for v := range Books {
name = v + " Exchange"
if commaflag {
fmt.Fprintf(writer, ", ")
}
fmt.Fprintf(writer, `{"name": "%s", "state": "open", "venue": "%s"}`, name, v)
commaflag = true
}
fmt.Fprintf(writer, "]}")
return
}
}
// Venue heartbeat...
if len(pathlist) == 5 {
if pathlist[2] == "venues" && pathlist[4] == "heartbeat" {
venue := pathlist[3]
if Books[venue] == nil {
fmt.Fprintf(writer, NO_VENUE_HEART)
} else {
fmt.Fprintf(writer, `{"ok": true, "venue": "%s"}`, venue)
}
return
}
}
// Stocks on an exchange...
list_stocks_flag := false
if len(pathlist) == 4 {
if pathlist[2] == "venues" {
list_stocks_flag = true
}
} else if len(pathlist) == 5 {
if pathlist[2] == "venues" && pathlist[4] == "stocks" {
list_stocks_flag = true
}
}
if list_stocks_flag {
venue := pathlist[3]
if Books[venue] == nil {
fmt.Fprintf(writer, NO_VENUE_HEART)
return
}
fmt.Fprintf(writer, `{"ok": true, "symbols": [`)
name := ""
commaflag := false
for s := range Books[venue] {
name = s + " Inc"
if commaflag {
fmt.Fprintf(writer, ", ")
}
fmt.Fprintf(writer, `{"name": "%s", "symbol": "%s"}`, name, s)
commaflag = true
}
fmt.Fprintf(writer, "]}")
return
}
// Quote...
if len(pathlist) == 7 {
if pathlist[2] == "venues" && pathlist[4] == "stocks" && pathlist[6] == "quote" {
venue := pathlist[3]
symbol := pathlist[5]
err := create_book_if_needed(venue, symbol)
if err != nil {
fmt.Fprintf(writer, CREATE_BOOK_FAIL)
return
}
res := get_response_from_book("QUOTE", venue, symbol)
fmt.Fprintf(writer, res)
return
}
}
// Orderbook...
if len(pathlist) == 6 {
if pathlist[2] == "venues" && pathlist[4] == "stocks" {
venue := pathlist[3]
symbol := pathlist[5]
err := create_book_if_needed(venue, symbol)
if err != nil {
fmt.Fprintf(writer, CREATE_BOOK_FAIL)
return
}
res := get_binary_orderbook_to_json(venue, symbol)
fmt.Fprintf(writer, res)
return
}
}
// All orders on a venue...
if len(pathlist) == 7 {
if pathlist[2] == "venues" && pathlist[4] == "accounts" && pathlist[6] == "orders" {
fmt.Fprintf(writer, NOT_IMPLEMENTED)
return
}
}
// All orders on a venue (specific stock)...
if len(pathlist) == 9 {
if pathlist[2] == "venues" && pathlist[4] == "accounts" && pathlist[6] == "stocks" && pathlist[8] == "orders" {
venue := pathlist[3]
account := pathlist[5]
symbol := pathlist[7]
if Options.Excess == false {
fmt.Fprintf(writer, DISABLED)
return
}
if AuthMode { // Do this before the acc_id int is generated
api_key, ok := Auth[account]
if api_key != request_api_key || ok == false {
fmt.Fprintf(writer, AUTH_FAILURE)
return
}
}
acc_id, ok := AccountInts[account]
if !ok {
acc_id = len(AccountInts)
AccountInts[account] = acc_id
}
res := get_response_from_book("STATUSALL " + strconv.Itoa(acc_id), venue, symbol)
fmt.Fprintf(writer, res)
return
}
}
// Status and cancel...
if len(pathlist) == 8 {
if pathlist[2] == "venues" && pathlist[4] == "stocks" && pathlist[6] == "orders" {
venue := pathlist[3]
symbol := pathlist[5]
id, err := strconv.Atoi(pathlist[7])
if err != nil {
fmt.Fprintf(writer, BAD_ORDER)
return
}
res1 := get_response_from_book("__ACC_FROM_ID__ " + strconv.Itoa(id), venue, symbol)
res1 = strings.Trim(res1, " \t\n\r")
reply_list := strings.Split(res1, " ")
err_string, account := reply_list[0], reply_list[1]
if err_string == "ERROR" {
fmt.Fprintf(writer, UNKNOWN_ORDER)
return
}
if AuthMode {
if Auth[account] != request_api_key || Auth[account] == "" {
fmt.Fprintf(writer, AUTH_FAILURE)
return
}
}
var command string
if request.Method == "DELETE" {
command = fmt.Sprintf("CANCEL %d", id)
} else {
command = fmt.Sprintf("STATUS %d", id)
}
res2 := get_response_from_book(command, venue, symbol)
fmt.Fprintf(writer, res2)
return
}
}
// Order placing...
if len(pathlist) == 7 {
if pathlist[2] == "venues" && pathlist[4] == "stocks" && pathlist[6] == "orders" && request.Method == "POST" {
venue := pathlist[3]
symbol := pathlist[5]
raw_order := OrderStruct{}
decoder := json.NewDecoder(request.Body)
err := decoder.Decode(&raw_order)
if err != nil {
fmt.Fprintf(writer, BAD_JSON)
return
}
// Accept missing fields that can be determined from URL...
if raw_order.Venue == "" {
raw_order.Venue = venue
}
if raw_order.Symbol == "" && raw_order.Stock == "" {
raw_order.Symbol = symbol
}
// Accept stock as an alias of symbol...
if raw_order.Stock != "" {
raw_order.Symbol = raw_order.Stock
}
if raw_order.Venue != venue || raw_order.Symbol != symbol {
fmt.Fprintf(writer, URL_MISMATCH)
return
}
if raw_order.Venue == "" || raw_order.Symbol == "" || raw_order.Account == "" || raw_order.Qty == 0 ||
raw_order.Direction == "" || raw_order.OrderType == "" {
fmt.Fprintf(writer, MISSING_FIELD)
return
}
if bad_name(raw_order.Account) {
fmt.Fprintf(writer, BAD_ACCOUNT_NAME)
return
}
int_ordertype := 0
switch raw_order.OrderType {
case "ioc":
int_ordertype = IOC
case "immediate-or-cancel":
int_ordertype = IOC
case "fok":
int_ordertype = FOK
case "fill-or-kill":
int_ordertype = FOK
case "limit":
int_ordertype = LIMIT
case "market":
int_ordertype = MARKET
}
int_direction := 0
switch raw_order.Direction {
case "sell":
int_direction = SELL
case "buy":
int_direction = BUY
}
if AuthMode { // Do this before the acc_id int is generated
api_key, ok := Auth[raw_order.Account]
if api_key != request_api_key || ok == false {
fmt.Fprintf(writer, AUTH_FAILURE)
return
}
}
acc_id, ok := AccountInts[raw_order.Account]
if !ok {
acc_id = len(AccountInts)
AccountInts[raw_order.Account] = acc_id
}
err = create_book_if_needed(venue, symbol)
if err != nil {
fmt.Fprintf(writer, CREATE_BOOK_FAIL)
return
}
command := fmt.Sprintf("ORDER %s %d %d %d %d %d", raw_order.Account, acc_id, raw_order.Qty, raw_order.Price, int_direction, int_ordertype)
res := get_response_from_book(command, venue, symbol)
fmt.Fprintf(writer, res)
return
}
}
// Scores...
if len(pathlist) == 7 {
if pathlist[2] == "venues" && pathlist[4] == "stocks" && pathlist[6] == "scores" {
venue := pathlist[3]
symbol := pathlist[5]
res := get_response_from_book("__SCORES__", venue, symbol)
writer.Header().Set("Content-Type", "text/html")
fmt.Fprintf(writer, res)
return
}
}
fmt.Fprintf(writer, UNKNOWN_PATH)
return
}
/*
WebSocket strategy:
For each incoming WS connection, the goroutine ws_handler() puts an entry
in a global struct, storing account, venue, and symbol (some of which
are optional). It also stores a channel used for communication.
Each C backend sends messages to stderr. There is one goroutine per
backend -- ws_controller() -- that reads these messages and passes them
on via the channel (only sending to the correct clients).
*/
func ws_handler(writer http.ResponseWriter, request * http.Request) {
// http://www.gorillatoolkit.org/pkg/websocket
conn, err := Upgrader.Upgrade(writer, request, nil)
if err != nil {
return
}
path_clean := strings.Trim(request.URL.Path, "\n\r\t /")
pathlist := strings.Split(path_clean, "/")
if len(pathlist) < 3 || pathlist[0] != "ob" || pathlist[1] != "api" || pathlist[2] != "ws" {
return
}
var account string
var venue string
var symbol string
var info WsInfo
message_channel := make(chan string, 128) // Dunno what buffer is appropriate
//ob/api/ws/:trading_account/venues/:venue/tickertape/stocks/:stock
if len(pathlist) == 9 && pathlist[4] == "venues" && pathlist[6] == "tickertape" && pathlist[7] == "stocks" {
account = ""
venue = pathlist[5]
symbol = pathlist[8]
info = WsInfo{account, venue, symbol, TICKER, message_channel}
ClientListLock.Lock()
WebSocketClients = append(WebSocketClients, &info)
ClientListLock.Unlock()
//ob/api/ws/:trading_account/venues/:venue/tickertape
} else if len(pathlist) == 7 && pathlist[4] == "venues" && pathlist[6] == "tickertape" {
account = ""
venue = pathlist[5]
symbol = ""
info = WsInfo{account, venue, symbol, TICKER, message_channel}
ClientListLock.Lock()
WebSocketClients = append(WebSocketClients, &info)
ClientListLock.Unlock()
//ob/api/ws/:trading_account/venues/:venue/executions/stocks/:symbol
} else if len(pathlist) == 9 && pathlist[4] == "venues" && pathlist[6] == "executions" && pathlist[7] == "stocks" {
account = pathlist[3]
venue = pathlist[5]
symbol = pathlist[8]
info = WsInfo{account, venue, symbol, EXECUTION, message_channel}
ClientListLock.Lock()
WebSocketClients = append(WebSocketClients, &info)
ClientListLock.Unlock()
//ob/api/ws/:trading_account/venues/:venue/executions
} else if len(pathlist) == 7 && pathlist[4] == "venues" && pathlist[6] == "executions" {
account = pathlist[3]
venue = pathlist[5]
symbol = ""
info = WsInfo{account, venue, symbol, EXECUTION, message_channel}
ClientListLock.Lock()
WebSocketClients = append(WebSocketClients, &info)
ClientListLock.Unlock()
// invalid URL
} else {
conn.Close()
return
}
fmt.Printf("WebSocket -OPEN- ... Active == %d\n", len(WebSocketClients))
go ws_null_reader(conn, &info) // This handles reading and discarding incoming messages
for {
msg := <- message_channel
err = conn.WriteMessage(websocket.TextMessage, []byte(msg))
if err != nil {
delete_client_from_global_list(&info)
return // The function ws_null_reader() will likely close the connection.
}
}
}
// See comments above for WebSocket strategy.
func ws_controller(venue string, symbol string) {
scanner := bufio.NewScanner(Books[venue][symbol].stderr)
for {
scanner.Scan()
headers := strings.Split(scanner.Text(), " ")
var msg_type int
// The backend sends a header line in format TYPE ACCOUNT VENUE SYMBOL
// (the last 2 pieces aren't needed as we know what they are already).
if headers[0] == "TICKER" {
msg_type = TICKER
} else if headers[0] == "EXECUTION" {
msg_type = EXECUTION
} else {
msg_type = 0
fmt.Println("Unknown WS message type received from backend!")
}
var buffer bytes.Buffer
for {
scanner.Scan()
str_piece := scanner.Text()
if str_piece != "END" {
buffer.WriteString(str_piece)
buffer.WriteByte('\n')
} else {
break
}
}
ClientListLock.Lock()
for _, client := range WebSocketClients {
if client.ConnType != msg_type {
continue
}
if client.Account != headers[1] && client.ConnType == EXECUTION {
continue
}
if client.Venue != venue {
continue
}
if client.Symbol != symbol && client.Symbol != "" {
continue
}
select {
case client.MessageChannel <- buffer.String() : // Send message unless buffer is full
default:
}
}
ClientListLock.Unlock()
}
}
func delete_client_from_global_list(info_ptr * WsInfo) {
// Does nothing if the client isn't in the list
ClientListLock.Lock()
for i, client_ptr := range WebSocketClients {
if client_ptr == info_ptr {
// Replace the pointer to this client by the final
// pointer in the list, then shorten the list by 1.
WebSocketClients[i] = WebSocketClients[len(WebSocketClients) - 1]
WebSocketClients = WebSocketClients[:len(WebSocketClients) - 1]
fmt.Printf("WebSocket CLOSED ... Active == %d\n", len(WebSocketClients))
break
}
}
ClientListLock.Unlock()
return
}
// Apparently reading WebSocket messages from clients is mandatory.
// This function also closes connections if needed.
func ws_null_reader(conn * websocket.Conn, info_ptr * WsInfo) {
for {
if _, _, err := conn.NextReader(); err != nil {
delete_client_from_global_list(info_ptr)
conn.Close()
return
}
}
}
func load_auth() {
file, err := ioutil.ReadFile(Options.AccountFilename)
if err != nil {
fmt.Printf("Couldn't load and parse accounts file.\n\n")
os.Exit(1)
}
var di interface{}
err = json.Unmarshal(file, &di)
if err != nil {
fmt.Printf("Couldn't load and parse accounts file.\n\n")
os.Exit(1)
}
m := di.(map[string]interface{})
for acc, apikey := range m {
switch apikey.(type) {
case string:
Auth[acc] = apikey.(string)
}
}
return
}
func main() {
maxbooksPtr := flag.Int("maxbooks", 100, "Maximum number of books")
portPtr := flag.Int("port", 8000, "Port for web API and WebSockets")
accountfilenamePtr := flag.String("accounts", "", "Accounts file for authentication")
defaultvenuePtr := flag.String("venue", "TESTEX", "Default venue")
defaultsymbolPtr := flag.String("symbol", "FOOBAR", "Default symbol")
excessPtr := flag.Bool("excess", false, "Enable commands that can return excessive responses")
flag.Parse()
Options = OptionsStruct{ MaxBooks : *maxbooksPtr,
Port : *portPtr,
AccountFilename : *accountfilenamePtr,
DefaultVenue : *defaultvenuePtr,
DefaultSymbol : *defaultsymbolPtr,
Excess : *excessPtr}
create_book_if_needed(Options.DefaultVenue, Options.DefaultSymbol)
fmt.Printf("\ndisorderBook (C+Go version) starting up on port %d\n", Options.Port)
if Options.AccountFilename != "" {
load_auth()
AuthMode = true
} else {
fmt.Printf("\n-----> Warning: running WITHOUT AUTHENTICATION! <-----\n\n")
}
server_string := fmt.Sprintf("127.0.0.1:%d", Options.Port)
http.HandleFunc("/", main_handler)
http.HandleFunc("/ob/api/ws/", ws_handler)
http.ListenAndServe(server_string, nil)
}