-
Notifications
You must be signed in to change notification settings - Fork 0
/
disorderBook_front.go
1148 lines (915 loc) · 35.4 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
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"bufio"
"bytes"
"encoding/binary"
"encoding/json"
"flag"
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"os/exec"
"strconv"
"strings"
"sync"
"time"
"github.com/gorilla/websocket" // go get github.com/gorilla/websocket
)
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"` // int32 is what the backend likes,
Price int32 `json:"price"` // official uses uint32 I think.
}
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
}
type Command struct {
Venue string
Symbol string
Command string
HubCommand int
CreateIfNeeded bool
ResponseChan chan []byte
}
type BookInfo struct {
Venue string
Symbol string
}
var HEARTBEAT_OK = []byte(`{"ok": true, "error": ""}`)
var UNKNOWN_PATH = []byte(`{"ok": false, "error": "Unknown path"}`)
var UNKNOWN_VENUE = []byte(`{"ok": false, "error": "Unknown venue"}`)
var UNKNOWN_SYMBOL = []byte(`{"ok": false, "error": "Venue is known but symbol is not"}`)
var BAD_JSON = []byte(`{"ok": false, "error": "Failed to parse incoming JSON"}`)
var URL_MISMATCH = []byte(`{"ok": false, "error": "Venue or symbol in URL did not match that in POST"}`)
var MISSING_FIELD = []byte(`{"ok": false, "error": "Missing key or unacceptable value in POST"}`)
var UNKNOWN_ORDER = []byte(`{"ok": false, "error": "Unknown order ID"}`)
var BAD_ORDER = []byte(`{"ok": false, "error": "Couldn't parse order ID"}`)
var AUTH_FAILURE = []byte(`{"ok": false, "error": "Unknown account or wrong API key"}`)
var NO_VENUE_HEART = []byte(`{"ok": false, "error": "Venue not up (create it by using it)"}`)
var BAD_BOOK_NAME = []byte(`{"ok": false, "error": "Couldn't create book! Bad name for a book!"}`)
var TOO_MANY_BOOKS = []byte(`{"ok": false, "error": "Couldn't create book! Too many books!"}`)
var NOT_IMPLEMENTED = []byte(`{"ok": false, "error": "Not implemented"}`)
var DISABLED = []byte(`{"ok": false, "error": "Disabled or not enabled. (See command line options)"}`)
var BAD_ACCOUNT_NAME = []byte(`{"ok": false, "error": "Bad account name (should be alpha_numeric and sane length)"}`)
var BAD_DIRECTION = []byte(`{"ok": false, "error": "Bad direction (should be buy or sell, lowercase)"}`)
var BAD_ORDERTYPE = []byte(`{"ok": false, "error": "Bad (unknown) orderType"}`)
var BAD_PRICE = []byte(`{"ok": false, "error": "Bad (negative) price"}`)
var BAD_QTY = []byte(`{"ok": false, "error": "Bad (non-positive) qty"}`)
var MYSTERY_HUB_CMD = []byte(`{"ok": false, "error": "Hub received unknown hub command"}`)
var STATUS_ON_UNKNOWN = []byte(`{"ok": false, "error": "Status/cancel on unknown book"}`)
var BAD_METHOD = []byte(`{"ok": false, "error": "Method not allowed, use GET, DELETE, POST only"}`)
var BAD_METHOD_HERE = []byte(`{"ok": false, "error": "Method not allowed at this URL"}`)
const (
VENUES_LIST = 1
VENUE_HEARTBEAT = 2
STOCK_LIST = 3
)
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>`
// -------------------------------------------------------------------------------------------------------
// The following globals are unsafe -- could be touched by multiple goroutines (e.g. web handlers):
var AccountInts = make(map[string]int)
var WebSocketClients = make([]*WsInfo, 0)
// The following are mutexes for the above:
var AccountInts_MUTEX sync.RWMutex
var WebSocketClients_MUTEX sync.RWMutex
// The following globals are safe because they are only written to before the various goroutines start:
var Options OptionsStruct
var AuthMode = false
var Auth = make(map[string]string)
// The following globals are safe because they are never "written" to as such:
var Upgrader = websocket.Upgrader{ReadBufferSize: 1024, WriteBufferSize: 1024, CheckOrigin: func(r *http.Request) bool {return true}}
var GlobalCommandChan = make(chan Command)
// -------------------------------------------------------------------------------------------------------
func main() {
flag.IntVar(&Options.MaxBooks, "maxbooks", 100, "Maximum number of books")
flag.IntVar(&Options.Port, "port", 8000, "Port for web API and WebSockets")
flag.StringVar(&Options.AccountFilename, "accounts", "", "Accounts file for authentication")
flag.StringVar(&Options.DefaultVenue, "venue", "TESTEX", "Default venue")
flag.StringVar(&Options.DefaultSymbol, "symbol", "FOOBAR", "Default symbol")
flag.BoolVar(&Options.Excess, "excess", false, "Enable commands that can return excessive responses")
flag.Parse()
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")
}
go hub()
// Create the default venue...
result_chan := make(chan []byte)
msg := Command{
ResponseChan: result_chan,
Venue: Options.DefaultVenue,
Symbol: Options.DefaultSymbol,
CreateIfNeeded: true,
Command: "THIS_DOES_NOT_MATTER",
}
GlobalCommandChan <- msg
<- result_chan // Need to read a result to prevent deadlock
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)
}
func main_handler(writer http.ResponseWriter, request * http.Request) {
// Each time a new web request comes in (not including
// WebSocket connections) this is called as a new goroutine.
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, "/")
// Disallow all methods except GET, DELETE, POST.............................................
if request.Method != "GET" && request.Method != "DELETE" && request.Method != "POST" {
writer.Write(BAD_METHOD)
return
}
// 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" {
writer.Write(UNKNOWN_PATH)
return
}
// General heartbeat.........................................................................
if len(pathlist) == 3 {
if pathlist[2] == "heartbeat" {
writer.Write(HEARTBEAT_OK)
return
}
}
// Venues list...............................................................................
if len(pathlist) == 3 {
if pathlist[2] == "venues" {
msg := Command{
HubCommand: VENUES_LIST,
}
relay(msg, writer)
return
}
}
// Venue heartbeat...........................................................................
if len(pathlist) == 5 {
if pathlist[2] == "venues" && pathlist[4] == "heartbeat" {
venue := pathlist[3]
msg := Command{
Venue: venue,
HubCommand: VENUE_HEARTBEAT,
}
relay(msg, writer)
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]
msg := Command{
Venue: venue,
HubCommand: STOCK_LIST,
}
relay(msg, writer)
return
}
// Quote.....................................................................................
if len(pathlist) == 7 {
if pathlist[2] == "venues" && pathlist[4] == "stocks" && pathlist[6] == "quote" {
venue := pathlist[3]
symbol := pathlist[5]
msg := Command{
Venue: venue,
Symbol: symbol,
Command: "QUOTE",
CreateIfNeeded: true,
}
relay(msg, writer)
return
}
}
// Orderbook.................................................................................
if len(pathlist) == 6 {
if pathlist[2] == "venues" && pathlist[4] == "stocks" {
venue := pathlist[3]
symbol := pathlist[5]
msg := Command{
Venue: venue,
Symbol: symbol,
Command: "ORDERBOOK_BINARY",
CreateIfNeeded: true,
}
relay(msg, writer)
return
}
}
// All orders on a venue.....................................................................
if len(pathlist) == 7 {
if pathlist[2] == "venues" && pathlist[4] == "accounts" && pathlist[6] == "orders" {
writer.Write(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 {
writer.Write(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 {
writer.Write(AUTH_FAILURE)
return
}
}
AccountInts_MUTEX.Lock()
acc_id, ok := AccountInts[account]
if !ok {
acc_id = len(AccountInts)
AccountInts[account] = acc_id
}
AccountInts_MUTEX.Unlock()
msg := Command{
Venue: venue,
Symbol: symbol,
Command: "STATUSALL " + strconv.Itoa(acc_id),
CreateIfNeeded: true,
}
relay(msg, writer)
return
}
}
// Status and cancel (including cancel at alternate URL).....................................
if (len(pathlist) == 8 && pathlist[2] == "venues" && pathlist[4] == "stocks" && pathlist[6] == "orders") ||
(len(pathlist) == 9 && pathlist[2] == "venues" && pathlist[4] == "stocks" && pathlist[6] == "orders" && pathlist[8] == "cancel") {
venue := pathlist[3]
symbol := pathlist[5]
id, err := strconv.Atoi(pathlist[7])
if err != nil {
writer.Write(BAD_ORDER)
return
}
// GET doesn't make sense at the alternate cancel URL... (we'll allow DELETE I guess)
if len(pathlist) == 9 && request.Method == "GET" {
writer.Write(BAD_METHOD_HERE)
return
}
// In this instance, the web-handler needs to contact the book for info and NOT
// send that on to the client. Once we have the info we can make the real request.
command := "__ACC_FROM_ID__ " + strconv.Itoa(id)
result_chan := make(chan []byte)
msg := Command{
ResponseChan: result_chan,
Venue: venue,
Symbol: symbol,
Command: command,
CreateIfNeeded: false,
}
GlobalCommandChan <- msg
res1 := <- result_chan
// If the book didn't exist we will receive one of these replies...
if bytes.Equal(res1, UNKNOWN_VENUE) || bytes.Equal(res1, UNKNOWN_SYMBOL) {
writer.Write(STATUS_ON_UNKNOWN)
return
}
res1 = bytes.Trim(res1, " \t\n\r")
reply_list := bytes.Split(res1, []byte(" "))
err_string, account := string(reply_list[0]), string(reply_list[1])
if err_string == "ERROR" {
writer.Write(UNKNOWN_ORDER)
return
}
if AuthMode {
if Auth[account] != request_api_key || Auth[account] == "" {
writer.Write(AUTH_FAILURE)
return
}
}
if request.Method == "DELETE" || len(pathlist) == 9 { // The longer path is the alternate cancel URL
command = fmt.Sprintf("CANCEL %d", id)
} else {
command = fmt.Sprintf("STATUS %d", id)
}
msg = Command{
Venue: venue,
Symbol: symbol,
Command: command,
CreateIfNeeded: false,
}
relay(msg, writer)
return
}
// Order placing.............................................................................
if len(pathlist) == 7 {
if pathlist[2] == "venues" && pathlist[4] == "stocks" && pathlist[6] == "orders" {
venue := pathlist[3]
symbol := pathlist[5]
if request.Method != "POST" {
writer.Write(BAD_METHOD_HERE)
return
}
raw_order := OrderStruct{}
decoder := json.NewDecoder(request.Body)
err := decoder.Decode(&raw_order)
if err != nil {
writer.Write(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 {
writer.Write(URL_MISMATCH)
return
}
if raw_order.Venue == "" || raw_order.Symbol == "" || raw_order.Account == "" || raw_order.Direction == "" || raw_order.OrderType == "" {
writer.Write(MISSING_FIELD)
return
}
if raw_order.Price < 0 {
writer.Write(BAD_PRICE)
return
}
if raw_order.Qty < 1 {
writer.Write(BAD_QTY)
return
}
if bad_name(raw_order.Account) {
writer.Write(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
default:
writer.Write(BAD_ORDERTYPE)
return
}
int_direction := 0
switch raw_order.Direction {
case "sell":
int_direction = SELL
case "buy":
int_direction = BUY
default:
writer.Write(BAD_DIRECTION)
return
}
if AuthMode {
api_key, ok := Auth[raw_order.Account]
if api_key != request_api_key || ok == false {
writer.Write(AUTH_FAILURE)
return
}
}
// Do the account-ID generation as late as possible so we don't get unused IDs if we return early
AccountInts_MUTEX.Lock()
acc_id, ok := AccountInts[raw_order.Account]
if !ok {
acc_id = len(AccountInts)
AccountInts[raw_order.Account] = acc_id
}
AccountInts_MUTEX.Unlock()
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)
msg := Command{
Venue: venue,
Symbol: symbol,
Command: command,
CreateIfNeeded: true,
}
relay(msg, writer)
return
}
}
// Scores....................................................................................
if len(pathlist) == 7 {
if pathlist[2] == "venues" && pathlist[4] == "stocks" && pathlist[6] == "scores" {
venue := pathlist[3]
symbol := pathlist[5]
writer.Header().Set("Content-Type", "text/html") // FIXME? If the book doesn't exist it will be a JSON response
msg := Command{
Venue: venue,
Symbol: symbol,
Command: "__SCORES__",
CreateIfNeeded: false,
}
relay(msg, writer)
return
}
}
// Unknown...................................................................................
writer.Write(UNKNOWN_PATH)
return
}
func relay(msg Command, writer http.ResponseWriter) {
// Send the message to the hub, read the response via a channel,
// and then send that response to the http client.
result_chan := make(chan []byte)
msg.ResponseChan = result_chan
GlobalCommandChan <- msg
res := <- result_chan
writer.Write(res)
return
}
func hub() {
// All web-handlers that need some sort of considered response send their commands to the hub.
// The real reason for this is that the books are behind a map; accessing which is not thread-safe.
// Earlier architecture ended up with a ton of mutex calls and a map of mutexes behind a mutex...
books := make(map[string]map[string]chan Command)
bookcount := 0
hub_command_chan := make(chan Command)
hub_update_chan := make(chan BookInfo)
go hub_command_handler(hub_command_chan, hub_update_chan)
for {
msg := <- GlobalCommandChan
// Check whether the command was to the hub or to the book...
if msg.HubCommand != 0 {
hub_command_chan <- msg
continue
}
// Command was a real command to a book...
// But maybe it doesn't exist and we can ignore it?
venue, symbol := msg.Venue, msg.Symbol
if msg.CreateIfNeeded == false {
if books[venue] == nil {
msg.ResponseChan <- UNKNOWN_VENUE
continue
}
if books[venue][symbol] == nil {
msg.ResponseChan <- UNKNOWN_SYMBOL
continue
}
}
// Either the book exists or we need to create it...
if books[venue] == nil || books[venue][symbol] == nil { // Short circuits if no venue
if bad_name(venue) || bad_name(symbol) {
msg.ResponseChan <- BAD_BOOK_NAME
continue
}
if bookcount >= Options.MaxBooks {
msg.ResponseChan <- TOO_MANY_BOOKS
continue
}
if books[venue] == nil {
books[venue] = make(map[string]chan Command)
}
new_command_chan := make(chan Command)
books[venue][symbol] = new_command_chan
bookcount += 1
hub_update_chan <- BookInfo{venue, symbol}
exec_command := exec.Command("./disorderBook.exe", venue, symbol)
i_pipe, _ := exec_command.StdinPipe()
o_pipe, _ := exec_command.StdoutPipe()
e_pipe, _ := exec_command.StderrPipe()
// Should maybe handle errors from the above.
new_pipes_struct := PipesStruct{i_pipe, o_pipe, e_pipe}
exec_command.Start()
go ws_controller(venue, symbol, e_pipe)
go controller(venue, symbol, new_pipes_struct, new_command_chan)
fmt.Printf("Creating %s %s\n", venue, symbol)
}
// The book exists...
books[venue][symbol] <- msg
}
}
func hub_command_handler(hub_command_chan chan Command, hub_update_chan chan BookInfo) {
// Some commands aren't dealt with by passing them to a book but rather are queries of global state.
// This goroutine keeps a copy of the relevant state up-to-date by receiving messages from the hub
// about new book creation. It thus is able to deal with the commands for such state.
venue_symbol_map := make(map[string]map[string]bool) // bool is adequate here
for {
select {
case cmd := <- hub_command_chan:
handle_hub_command(cmd, venue_symbol_map)
case update := <- hub_update_chan:
if venue_symbol_map[update.Venue] == nil {
venue_symbol_map[update.Venue] = make(map[string]bool)
}
venue_symbol_map[update.Venue][update.Symbol] = true
}
}
}
func handle_hub_command(msg Command, venue_symbol_map map[string]map[string]bool) {
var buffer bytes.Buffer
switch msg.HubCommand {
case VENUES_LIST:
commaflag := false
buffer.WriteString("{\n \"ok\": true,\n \"venues\": [")
for v := range venue_symbol_map {
name := v + " Exchange"
if commaflag {
buffer.WriteString(",")
}
line := fmt.Sprintf("\n {\"name\": \"%s\", \"state\": \"open\", \"venue\": \"%s\"}", name, v)
buffer.WriteString(line)
commaflag = true
}
buffer.WriteString("\n ]\n}")
case VENUE_HEARTBEAT:
if venue_symbol_map[msg.Venue] == nil {
buffer.Write(NO_VENUE_HEART)
} else {
line := fmt.Sprintf(`{"ok": true, "venue": "%s"}`, msg.Venue)
buffer.WriteString(line)
}
case STOCK_LIST:
if venue_symbol_map[msg.Venue] == nil {
buffer.Write(NO_VENUE_HEART)
} else {
commaflag := false
buffer.WriteString("{\n \"ok\": true,\n \"symbols\": [")
for s := range venue_symbol_map[msg.Venue] {
name := s + " Inc"
if commaflag {
buffer.WriteString(",")
}
line := fmt.Sprintf("\n {\"name\": \"%s\", \"symbol\": \"%s\"}", name, s)
buffer.WriteString(line)
commaflag = true
}
buffer.WriteString("\n ]\n}")
}
default:
buffer.Write(MYSTERY_HUB_CMD)
}
msg.ResponseChan <- buffer.Bytes()
return
}
func controller(venue string, symbol string, pipes PipesStruct, command_chan chan Command) {
// This goroutine controls the stdout and stdin for a single backend.
// (stderr (for WebSockets) is handled by a different goroutine.)
for {
msg := <- command_chan
command := msg.Command
if len(command) == 0 || command[len(command) - 1] != '\n' {
command = command + "\n"
}
fmt.Fprintf(pipes.Stdin, command)
if command == "ORDERBOOK_BINARY\n" { // This is a special case since the response is binary
handle_binary_orderbook_response(pipes.Stdout, msg.Venue, msg.Symbol, msg.ResponseChan)
continue
}
scanner := bufio.NewScanner(pipes.Stdout)
var buffer bytes.Buffer
for {
scanner.Scan()
str_piece := scanner.Bytes()
if bytes.Equal(str_piece, []byte("END")) {
break
} else {
buffer.Write(str_piece)
buffer.WriteByte('\n')
}
}
msg.ResponseChan <- buffer.Bytes()
}
}
func handle_binary_orderbook_response(backend_stdout io.ReadCloser, venue string, symbol string, result_chan chan []byte) {
// The orderbook is the only thing the C backend sends in a binary format (this is
// done for speed reasons, as it's potentially a large amount of data, frequently
// requested in normal usage). See comments in the C file for format info.
reader := bufio.NewReader(backend_stdout)
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 {
binary.Read(reader, binary.BigEndian, &qty)
binary.Read(reader, binary.BigEndian, &price)
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 {
binary.Read(reader, binary.BigEndian, &qty)
binary.Read(reader, binary.BigEndian, &price)
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
}
}
ts, _ := time.Now().UTC().MarshalJSON()
if wrote_any_asks {
buffer.WriteString("\n ")
}
buffer.WriteString("],\n \"ts\": ")
buffer.Write(ts) // Already has quotes around it
buffer.WriteString("\n}")
result_chan <- buffer.Bytes()
return
}
// WebSocket strategy: http://www.gorillatoolkit.org/pkg/websocket
//
// 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 channels (only sending to the correct clients).
func ws_handler(writer http.ResponseWriter, request * http.Request) {
// Each time the /ob/api/ws URL is hit, this is called as a new goroutine.
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}
append_to_ws_client_list(&info)
//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}
append_to_ws_client_list(&info)
//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}
append_to_ws_client_list(&info)
//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}
append_to_ws_client_list(&info)
// invalid URL
} else {
conn.Close()
return
}
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 {
remove_from_ws_client_list(&info)
return // The function ws_null_reader() will likely close the connection.
}
}
}
func ws_controller(venue string, symbol string, backend_stderr io.ReadCloser) {
// See comments above for WebSocket strategy. This goroutine is responsible
// for reading the stderr of a single C backend (i.e. a single book). It
// then passes WebSocket messages on to the relevant connections.
scanner := bufio.NewScanner(backend_stderr)
for {
scanner.Scan()
headers := strings.Split(scanner.Text(), " ")