-
Notifications
You must be signed in to change notification settings - Fork 40
/
Copy pathao_host.js.html
835 lines (707 loc) · 40.2 KB
/
ao_host.js.html
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>ao_host.js - Documentation</title>
<script src="scripts/prettify/prettify.js"></script>
<script src="scripts/prettify/lang-css.js"></script>
<!--[if lt IE 9]>
<script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link type="text/css" rel="stylesheet" href="styles/prettify.css">
<link type="text/css" rel="stylesheet" href="styles/jsdoc.css">
<script src="scripts/nav.js" defer></script>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<input type="checkbox" id="nav-trigger" class="nav-trigger" />
<label for="nav-trigger" class="navicon-button x">
<div class="navicon"></div>
</label>
<label for="nav-trigger" class="overlay"></label>
<nav >
<input type="text" id="nav-search" placeholder="Search" />
<h2><a href="index.html">Home</a></h2><h2><a href="https://honey.bitfinex.com/" target="_blank" class="menu-item" id="hfui_link" >HF UI</a></h2><h2><a href="/tutorial-Architecture.html" target="" class="menu-item" id="architecture_link" >Getting Started</a></h2><h2><a href="/class-AOHost.html" target="" class="menu-item" id="algo_host_link" >Algo Host</a></h2><h2><a href="/module-AccumulateDistribute.html" target="" class="menu-item" id="ad_link" >Accumulate/Distribute</a></h2><h2><a href="/module-Iceberg.html" target="" class="menu-item" id="iceberg_link" >Iceberg</a></h2><h2><a href="/module-MACrossover.html" target="" class="menu-item" id="mac_link" >MA Crossover</a></h2><h2><a href="/module-OCOCO.html" target="" class="menu-item" id="ococo_link" >Order Creates OCO</a></h2><h2><a href="/module-PingPong.html" target="" class="menu-item" id="pingpong_link" >Ping/Pong</a></h2><h2><a href="/module-TWAP.html" target="" class="menu-item" id="twap_link" >TWAP</a></h2><h3>Classes</h3><ul><li><a href="AOHost.html">AOHost</a><ul class='members'><li data-type='member'><a href="AOHost.html#.TEARDOWN_GRACE_PERIOD_MS">TEARDOWN_GRACE_PERIOD_MS</a></li></ul><ul class='methods'><li data-type='method'><a href="AOHost.html#aosRunning">aosRunning</a></li><li data-type='method'><a href="AOHost.html#close">close</a></li><li data-type='method'><a href="AOHost.html#connect">connect</a></li><li data-type='method'><a href="AOHost.html#getAdapter">getAdapter</a></li><li data-type='method'><a href="AOHost.html#getAO">getAO</a></li><li data-type='method'><a href="AOHost.html#getAOInstance">getAOInstance</a></li><li data-type='method'><a href="AOHost.html#getAOInstances">getAOInstances</a></li><li data-type='method'><a href="AOHost.html#getAOs">getAOs</a></li><li data-type='method'><a href="AOHost.html#reconnect">reconnect</a></li><li data-type='method'><a href="AOHost.html#startAO">startAO</a></li><li data-type='method'><a href="AOHost.html#stopAO">stopAO</a></li></ul></li><li><a href="AsyncEventEmitter.html">AsyncEventEmitter</a><ul class='methods'><li data-type='method'><a href="AsyncEventEmitter.html#emit">emit</a></li><li data-type='method'><a href="AsyncEventEmitter.html#off">off</a></li><li data-type='method'><a href="AsyncEventEmitter.html#on">on</a></li><li data-type='method'><a href="AsyncEventEmitter.html#onAll">onAll</a></li><li data-type='method'><a href="AsyncEventEmitter.html#onAllOnce">onAllOnce</a></li><li data-type='method'><a href="AsyncEventEmitter.html#once">once</a></li><li data-type='method'><a href="AsyncEventEmitter.html#removeAllListeners">removeAllListeners</a></li></ul></li></ul><h3>Modules</h3><ul><li><a href="module-AccumulateDistribute.html">AccumulateDistribute</a><ul class='methods'><li data-type='method'><a href="module-AccumulateDistribute.html#.declareChannels">declareChannels</a></li><li data-type='method'><a href="module-AccumulateDistribute.html#.declareEvents">declareEvents</a></li><li data-type='method'><a href="module-AccumulateDistribute.html#.generateOrderAmounts">generateOrderAmounts</a></li><li data-type='method'><a href="module-AccumulateDistribute.html#.genOrderLabel">genOrderLabel</a></li><li data-type='method'><a href="module-AccumulateDistribute.html#.genPreview">genPreview</a></li><li data-type='method'><a href="module-AccumulateDistribute.html#.getUIDef">getUIDef</a></li><li data-type='method'><a href="module-AccumulateDistribute.html#.hasIndicatorCap">hasIndicatorCap</a></li><li data-type='method'><a href="module-AccumulateDistribute.html#.hasIndicatorOffset">hasIndicatorOffset</a></li><li data-type='method'><a href="module-AccumulateDistribute.html#.hasOBRequirement">hasOBRequirement</a></li><li data-type='method'><a href="module-AccumulateDistribute.html#.hasTradeRequirement">hasTradeRequirement</a></li><li data-type='method'><a href="module-AccumulateDistribute.html#.initState">initState</a></li><li data-type='method'><a href="module-AccumulateDistribute.html#.onDataManagedBook">onDataManagedBook</a></li><li data-type='method'><a href="module-AccumulateDistribute.html#.onDataManagedCandles">onDataManagedCandles</a></li><li data-type='method'><a href="module-AccumulateDistribute.html#.onDataTrades">onDataTrades</a></li><li data-type='method'><a href="module-AccumulateDistribute.html#.onLifeStart">onLifeStart</a></li><li data-type='method'><a href="module-AccumulateDistribute.html#.onLifeStop">onLifeStop</a></li><li data-type='method'><a href="module-AccumulateDistribute.html#.onOrdersOrderCancel">onOrdersOrderCancel</a></li><li data-type='method'><a href="module-AccumulateDistribute.html#.onOrdersOrderFill">onOrdersOrderFill</a></li><li data-type='method'><a href="module-AccumulateDistribute.html#.onSelfIntervalTick">onSelfIntervalTick</a></li><li data-type='method'><a href="module-AccumulateDistribute.html#.onSelfSubmitOrder">onSelfSubmitOrder</a></li><li data-type='method'><a href="module-AccumulateDistribute.html#.processParams">processParams</a></li><li data-type='method'><a href="module-AccumulateDistribute.html#.scheduleTick">scheduleTick</a></li><li data-type='method'><a href="module-AccumulateDistribute.html#.serialize">serialize</a></li><li data-type='method'><a href="module-AccumulateDistribute.html#.unserialize">unserialize</a></li><li data-type='method'><a href="module-AccumulateDistribute.html#.validateParams">validateParams</a></li></ul></li><li><a href="module-DefaultErrorHandlers.html">DefaultErrorHandlers</a><ul class='methods'><li data-type='method'><a href="module-DefaultErrorHandlers.html#.onErrorInsufficientBalance">onErrorInsufficientBalance</a></li><li data-type='method'><a href="module-DefaultErrorHandlers.html#.onErrorMinimumSize">onErrorMinimumSize</a></li><li data-type='method'><a href="module-DefaultErrorHandlers.html#.onOrdersOrderError">onOrdersOrderError</a></li></ul></li><li><a href="module-Helpers.html">Helpers</a><ul class='methods'><li data-type='method'><a href="module-Helpers.html#~cancelAllOrdersWithDelay">cancelAllOrdersWithDelay</a></li><li data-type='method'><a href="module-Helpers.html#~cancelOrderWithDelay">cancelOrderWithDelay</a></li><li data-type='method'><a href="module-Helpers.html#~clearAllTimeouts">clearAllTimeouts</a></li><li data-type='method'><a href="module-Helpers.html#~debug">debug</a></li><li data-type='method'><a href="module-Helpers.html#~declareChannel">declareChannel</a></li><li data-type='method'><a href="module-Helpers.html#~declareEvent">declareEvent</a></li><li data-type='method'><a href="module-Helpers.html#~emit">emit</a></li><li data-type='method'><a href="module-Helpers.html#~emitAsync">emitAsync</a></li><li data-type='method'><a href="module-Helpers.html#~emitSelf">emitSelf</a></li><li data-type='method'><a href="module-Helpers.html#~emitSelfAsync">emitSelfAsync</a></li><li data-type='method'><a href="module-Helpers.html#~notifyUI">notifyUI</a></li><li data-type='method'><a href="module-Helpers.html#~submitOrderWithDelay">submitOrderWithDelay</a></li><li data-type='method'><a href="module-Helpers.html#~updateState">updateState</a></li></ul></li><li><a href="module-Iceberg.html">Iceberg</a><ul class='members'><li data-type='member'><a href="module-Iceberg.html#.generateOrders">generateOrders</a></li></ul><ul class='methods'><li data-type='method'><a href="module-Iceberg.html#.declareEvents">declareEvents</a></li><li data-type='method'><a href="module-Iceberg.html#.genOrderLabel">genOrderLabel</a></li><li data-type='method'><a href="module-Iceberg.html#.genOrderLabel">genOrderLabel</a></li><li data-type='method'><a href="module-Iceberg.html#.genPreview">genPreview</a></li><li data-type='method'><a href="module-Iceberg.html#.getUIDef">getUIDef</a></li><li data-type='method'><a href="module-Iceberg.html#.initState">initState</a></li><li data-type='method'><a href="module-Iceberg.html#.onLifeStart">onLifeStart</a></li><li data-type='method'><a href="module-Iceberg.html#.onLifeStop">onLifeStop</a></li><li data-type='method'><a href="module-Iceberg.html#.onOrdersOrderCancel">onOrdersOrderCancel</a></li><li data-type='method'><a href="module-Iceberg.html#.onOrdersOrderFill">onOrdersOrderFill</a></li><li data-type='method'><a href="module-Iceberg.html#.onSelfSubmitOrders">onSelfSubmitOrders</a></li><li data-type='method'><a href="module-Iceberg.html#.processParams">processParams</a></li><li data-type='method'><a href="module-Iceberg.html#.serialize">serialize</a></li><li data-type='method'><a href="module-Iceberg.html#.unserialize">unserialize</a></li><li data-type='method'><a href="module-Iceberg.html#.validateParams">validateParams</a></li></ul></li><li><a href="module-MACrossover.html">MACrossover</a><ul class='members'><li data-type='member'><a href="module-MACrossover.html#.generateOrder">generateOrder</a></li></ul><ul class='methods'><li data-type='method'><a href="module-MACrossover.html#.declareChannels">declareChannels</a></li><li data-type='method'><a href="module-MACrossover.html#.declareEvents">declareEvents</a></li><li data-type='method'><a href="module-MACrossover.html#.genPreview">genPreview</a></li><li data-type='method'><a href="module-MACrossover.html#.initState">initState</a></li><li data-type='method'><a href="module-MACrossover.html#.onDataManagedCandles">onDataManagedCandles</a></li><li data-type='method'><a href="module-MACrossover.html#.onLifeStop">onLifeStop</a></li><li data-type='method'><a href="module-MACrossover.html#.onOrdersOrderCancel">onOrdersOrderCancel</a></li><li data-type='method'><a href="module-MACrossover.html#.onSelfSubmitOrder">onSelfSubmitOrder</a></li><li data-type='method'><a href="module-MACrossover.html#.processParams">processParams</a></li><li data-type='method'><a href="module-MACrossover.html#.serialize">serialize</a></li><li data-type='method'><a href="module-MACrossover.html#.unserialize">unserialize</a></li><li data-type='method'><a href="module-MACrossover.html#.validateParams">validateParams</a></li></ul></li><li><a href="module-OCOCO.html">OCOCO</a><ul class='members'><li data-type='member'><a href="module-OCOCO.html#.generateInitialOrder">generateInitialOrder</a></li><li data-type='member'><a href="module-OCOCO.html#.generateOCOOrder">generateOCOOrder</a></li></ul><ul class='methods'><li data-type='method'><a href="module-OCOCO.html#.genOrderLabel">genOrderLabel</a></li><li data-type='method'><a href="module-OCOCO.html#.genPreview">genPreview</a></li><li data-type='method'><a href="module-OCOCO.html#.getUIDef">getUIDef</a></li><li data-type='method'><a href="module-OCOCO.html#.initState">initState</a></li><li data-type='method'><a href="module-OCOCO.html#.module.exports">module.exports</a></li><li data-type='method'><a href="module-OCOCO.html#.onLifeStart">onLifeStart</a></li><li data-type='method'><a href="module-OCOCO.html#.onLifeStop">onLifeStop</a></li><li data-type='method'><a href="module-OCOCO.html#.onOrdersOrderCancel">onOrdersOrderCancel</a></li><li data-type='method'><a href="module-OCOCO.html#.onOrdersOrderFill">onOrdersOrderFill</a></li><li data-type='method'><a href="module-OCOCO.html#.onSelfSubmitInitialOrder">onSelfSubmitInitialOrder</a></li><li data-type='method'><a href="module-OCOCO.html#.onSelfSubmitOCOOrder">onSelfSubmitOCOOrder</a></li><li data-type='method'><a href="module-OCOCO.html#.processParams">processParams</a></li><li data-type='method'><a href="module-OCOCO.html#.serialize">serialize</a></li><li data-type='method'><a href="module-OCOCO.html#.unserialize">unserialize</a></li><li data-type='method'><a href="module-OCOCO.html#.validateParams">validateParams</a></li></ul></li><li><a href="module-PingPong.html">PingPong</a><ul class='members'><li data-type='member'><a href="module-PingPong.html#.genPingPongTable">genPingPongTable</a></li></ul><ul class='methods'><li data-type='method'><a href="module-PingPong.html#.genOrderLabel">genOrderLabel</a></li><li data-type='method'><a href="module-PingPong.html#.genPreview">genPreview</a></li><li data-type='method'><a href="module-PingPong.html#.getUIDef">getUIDef</a></li><li data-type='method'><a href="module-PingPong.html#.initState">initState</a></li><li data-type='method'><a href="module-PingPong.html#.onLifeStart">onLifeStart</a></li><li data-type='method'><a href="module-PingPong.html#.onLifeStop">onLifeStop</a></li><li data-type='method'><a href="module-PingPong.html#.onOrdersOrderCancel">onOrdersOrderCancel</a></li><li data-type='method'><a href="module-PingPong.html#.onOrdersOrderFill">onOrdersOrderFill</a></li><li data-type='method'><a href="module-PingPong.html#.processParams">processParams</a></li><li data-type='method'><a href="module-PingPong.html#.serialize">serialize</a></li><li data-type='method'><a href="module-PingPong.html#.unserialize">unserialize</a></li><li data-type='method'><a href="module-PingPong.html#.validateParams">validateParams</a></li></ul></li><li><a href="module-TWAP.html">TWAP</a><ul class='members'><li data-type='member'><a href="module-TWAP.html#.generateOrder">generateOrder</a></li><li data-type='member'><a href="module-TWAP.html#.getOBPrice">getOBPrice</a></li><li data-type='member'><a href="module-TWAP.html#.getTradePrice">getTradePrice</a></li><li data-type='member'><a href="module-TWAP.html#.hasOBTarget">hasOBTarget</a></li><li data-type='member'><a href="module-TWAP.html#.hasTradeTarget">hasTradeTarget</a></li><li data-type='member'><a href="module-TWAP.html#.isTargetMet">isTargetMet</a></li></ul><ul class='methods'><li data-type='method'><a href="module-TWAP.html#.declareChannels">declareChannels</a></li><li data-type='method'><a href="module-TWAP.html#.declareEvents">declareEvents</a></li><li data-type='method'><a href="module-TWAP.html#.genOrderLabel">genOrderLabel</a></li><li data-type='method'><a href="module-TWAP.html#.genPreview">genPreview</a></li><li data-type='method'><a href="module-TWAP.html#.getUIDef">getUIDef</a></li><li data-type='method'><a href="module-TWAP.html#.initState">initState</a></li><li data-type='method'><a href="module-TWAP.html#.onDataManagedBook">onDataManagedBook</a></li><li data-type='method'><a href="module-TWAP.html#.onDataTrades">onDataTrades</a></li><li data-type='method'><a href="module-TWAP.html#.onLifeStart">onLifeStart</a></li><li data-type='method'><a href="module-TWAP.html#.onLifeStop">onLifeStop</a></li><li data-type='method'><a href="module-TWAP.html#.onOrdersOrderCancel">onOrdersOrderCancel</a></li><li data-type='method'><a href="module-TWAP.html#.onOrdersOrderFill">onOrdersOrderFill</a></li><li data-type='method'><a href="module-TWAP.html#.onSelfIntervalTick">onSelfIntervalTick</a></li><li data-type='method'><a href="module-TWAP.html#.processParams">processParams</a></li><li data-type='method'><a href="module-TWAP.html#.serialize">serialize</a></li><li data-type='method'><a href="module-TWAP.html#.unserialize">unserialize</a></li><li data-type='method'><a href="module-TWAP.html#.validateParams">validateParams</a></li></ul></li></ul><h3>Events</h3><ul><li><a href="AOHost.html#~event:dataBook">dataBook</a></li><li><a href="AOHost.html#~event:dataCandles">dataCandles</a></li><li><a href="AOHost.html#~event:dataManagedBook">dataManagedBook</a></li><li><a href="AOHost.html#~event:dataManagedCandles">dataManagedCandles</a></li><li><a href="AOHost.html#~event:dataNotification">dataNotification</a></li><li><a href="AOHost.html#~event:dataTicker">dataTicker</a></li><li><a href="AOHost.html#~event:dataTrades">dataTrades</a></li><li><a href="AOHost.html#~event:errorsInsufficientBalance">errorsInsufficientBalance</a></li><li><a href="AOHost.html#~event:errorsMinimumSize">errorsMinimumSize</a></li><li><a href="AOHost.html#~event:lifeStart">lifeStart</a></li><li><a href="AOHost.html#~event:lifeStop">lifeStop</a></li><li><a href="AOHost.html#~event:ordersOrderCancel">ordersOrderCancel</a></li><li><a href="AOHost.html#~event:ordersOrderError">ordersOrderError</a></li><li><a href="AOHost.html#~event:ordersOrderFill">ordersOrderFill</a></li><li><a href="module-AccumulateDistribute.html#~event:selfIntervalTick">selfIntervalTick</a></li><li><a href="module-AccumulateDistribute.html#~event:selfSubmitOrder">selfSubmitOrder</a></li><li><a href="module-Iceberg.html#~event:event:selfSubmitOrders">selfSubmitOrders</a></li><li><a href="module-MACrossover.html#~event:selfSubmitOrder">selfSubmitOrder</a></li><li><a href="module-OCOCO.html#~event:selfSubmitInitialOrder">selfSubmitInitialOrder</a></li><li><a href="module-OCOCO.html#~event:selfSubmitOCOOrder">selfSubmitOCOOrder</a></li><li><a href="module-TWAP.html#~event:selfIntervalTick">selfIntervalTick</a></li></ul><h3>Tutorials</h3><ul><li><a href="tutorial-Architecture.html">Architecture</a></li></ul><h3>Global</h3><ul><li><a href="global.html#defineAlgoOrder">defineAlgoOrder</a></li></ul>
</nav>
<div id="main">
<h1 class="page-title">ao_host.js</h1>
<section>
<article>
<pre class="prettyprint source linenums"><code>'use strict'
const PI = require('p-iteration')
const _isFunction = require('lodash/isFunction')
const _isEmpty = require('lodash/isEmpty')
const _includes = require('lodash/includes')
const _get = require('lodash/get')
const debug = require('debug')('bfx:hf:algo:ao-host')
const WsAdapter = require('./ws_adapter')
const AsyncEventEmitter = require('./async_event_emitter')
const onMinimumSizeError = require('./host/events/minimum_size_error')
const onInsufficientBalanceError = require('./host/events/insufficient_balance')
const onSubmitAllOrders = require('./host/events/submit_all_orders')
const onCancelAllOrders = require('./host/events/cancel_all_orders')
const onUpdateState = require('./host/events/update_state')
const onAssignChannel = require('./host/events/assign_channel')
const onNotify = require('./host/events/notify')
const onStop = require('./host/events/stop')
const withAOUpdate = require('./host/with_ao_update')
const bindWS2Bus = require('./host/ws2/bind_bus')
const initAO = require('./host/init_ao')
const genHelpers = require('./host/gen_helpers')
/**
* @typedef {object} EventMetaInformation
* @property {object} chanFilter - source channel filter
* @property {string} chanFilter.symbol - source channel symbol
*/
/**
* @typedef {object} AOUIDefinition
* @property {string} label - name of the order to be shown to the user
* @property {string} id - internal algorithmic order ID
* @property {string} [uiIcon] - CSS classname of the icon to show
* @property {string} [customHelp] - documentation
* @property {number} connectionTimeout - how long to wait before considering
* the HF disconnected
* @property {number} actionTimeout - how long to wait for action confirmatio
* before considering the HF disconnected
* @property {object} [header] - rendered at the top of the form
* @property {string} [header.component] - component to use for the header
* @property {string[]} [header.fields] - array of field names to render in
* header
* @property {object[]} sections - the layout definition itself
* @property {string} sections[].title - rendered above the section
* @property {string} sections[].name - unique internal ID for the section
* @property {string[][]} sections[].rows - array of rows of field IDs to
* render in the section, two per row.
* @property {object} fields - field definitions, key'd by ID
* @property {string[]} actions - array of action names, maximum 2
*/
/**
* The AOHost class provides a wrapper around the algo order system, and
* manages lifetime events/order execution. Internally it hosts a Manager
* instance from bfx-api-node-core for communication with the Bitfinex API, and
* listens for websocket stream events in order to update order state/trigger
* algo order events.
*
* Execution is handled by an event system, with events being triggered by
* Bitfinex API websocket stream payloads, and the algo orders themselves.
*
* To start/stop algo orders, `gid = startAO(id, args)` and `stopAO(gid)`
* methods are provided, with the generated group ID (`gid`) being the same as
* that used for all atomic orders created by the individual algo orders.
*/
class AOHost extends AsyncEventEmitter {
/**
* @param {object} [args] - arguments
* @param {object} [args.db] - optional
* @param {string} [args.wsURL] - wss://api.bitfinex.com/ws/2
* @param {string} [args.restURL] - https://api.bitfinex.com
* @param {object} [args.agent] - optional proxy agent
* @param {object[]} [args.aos] - algo orders to manage
* @param {number} [args.dms] - dead man switch, active 4 (default)
*/
constructor (args = {}) {
super()
const { aos, wsSettings } = args
this.aos = aos
this.adapter = new WsAdapter(wsSettings)
this.instances = {}
this.onAOStart = this.onAOStart.bind(this)
this.onAOStop = this.onAOStop.bind(this)
this.onAOPersist = this.onAOPersist.bind(this)
this.loadAO = this.loadAO.bind(this)
this.triggerAOEvent = this.triggerAOEvent.bind(this)
this.triggerGlobalEvent = this.triggerGlobalEvent.bind(this)
this.triggerOrderEvent = this.triggerOrderEvent.bind(this)
this.adapter.on('meta:error', this.onMetaError.bind(this))
this.adapter.on('data:ticker', this.onDataTicker.bind(this))
this.adapter.on('data:trades', this.onDataTrades.bind(this))
this.adapter.on('data:candles', this.onDataCandles.bind(this))
this.adapter.on('data:book', this.onDataBook.bind(this))
this.adapter.on('data:managed:book', this.onDataManagedBook.bind(this))
this.adapter.on('data:managed:candles', this.onDataManagedCandles.bind(this))
this.adapter.on('data:notification', this.onDataNotification.bind(this))
this.adapter.on('meta:reload', this.onMetaReload.bind(this))
this.adapter.on('meta:connection:update', this.onMetaConnectionUpdate.bind(this))
this.on('ao:start', this.onAOStart)
this.on('ao:stop', this.onAOStop)
this.on('ao:persist', this.onAOPersist)
bindWS2Bus(this)
this.adapter.once('order:snapshot', (snapshot) => {
this.orderSnapshot = snapshot
this.emit('ready')
})
}
/**
* Get configured exchange adapter
*
* @returns {object} adapter
*/
getAdapter () {
return this.adapter
}
/**
* Disconnect & reconnect the exchange adapter
*/
reconnect () {
this.adapter.reconnect()
}
/**
* Close the exchange adapter connection.
*
* @returns {Promise} p - resolves on connection close
*/
close () {
return this.adapter.disconnect()
}
/**
* @param {Error} error - error from incoming event
* @private
*/
onMetaError (error) {
this.emit('error', error)
}
/**
* Update internal connection when the adpater applies an update
*
* @param {number} i - connection ID
* @param {object} c - new connection object
* @private
*/
onMetaConnectionUpdate (i, c) {
Object.values(this.instances).forEach((instance = {}) => {
const { connection } = instance.state
const { id } = connection
if (id === i) {
connection.c = c
}
})
}
onMetaReload () {
Object.values(this.instances).forEach((instance = {}) => {
const { state = {} } = instance
state.ev.removeAllListeners()
})
this.instances = {}
this.emit('meta:reload')
}
/**
* Opens a new socket connection on the internal adapter
*/
connect () {
this.adapter.connect()
}
/**
* Fetch configured algorithmic orders
*
* @returns {Array} aos
*/
getAOs () {
return Object.values(this.aos)
}
/**
* Returns the algo order definition identified by the provided ID
*
* @param {string} id - i.e. bfx-iceberg
* @returns {object} aoDef
*/
getAO (id) {
return Object.values(this.aos).find(ao => ao.id === id)
}
/**
* Returns the active AO instance state identified by the provided GID
*
* @param {string} gid - algo order group ID
* @returns {object} state - algo order state
*/
getAOInstance (gid) {
return this.instances[gid]
}
/**
* Returns an array of all running algo order instances
*
* @returns {object[]} aoInstances
*/
getAOInstances () {
return Object.values(this.instances)
}
/**
* Propagates notifications
*
* @param {object} notification - model
* @param {object} meta - routing information
* @private
*/
onDataNotification (notification, meta = {}) {
/**
* Triggered when a notification is received.
*
* @event AOHost~dataNotification
* @param {Array[]} notification - incoming notification data
* @param {EventMetaInformation} meta - source channel information
*/
this.triggerGlobalEvent('data', 'notification', notification, meta)
this.emit('notification', notification)
}
/**
* Propagates tickers
*
* @param {object} ticker - model
* @param {object} meta - routing information
* @private
*/
onDataTicker (ticker, meta = {}) {
/**
* Triggered when a ticker is received.
*
* @event AOHost~dataTicker
* @param {Array[]} ticker - incoming ticker data
* @param {EventMetaInformation} meta - source channel information
*/
this.triggerGlobalEvent('data', 'ticker', ticker, meta)
}
/**
* Propagates trades
*
* @param {object[]} trades - models
* @param {object} meta - routing information
* @private
*/
onDataTrades (trades, meta = {}) {
/**
* Triggered when a trade snapshot or single trade is received
*
* @event AOHost~dataTrades
* @param {Array[]} update - incoming snapshot or single trade
* @param {EventMetaInformation} meta - source channel information
*/
this.triggerGlobalEvent('data', 'trades', trades, meta)
}
/**
* Propagates candles
*
* @param {object[]} candles - models
* @param {object} meta - routing information
* @private
*/
onDataCandles (candles, meta = {}) {
/**
* Triggered when a candle snapshot or individual candle is received.
*
* @event AOHost~dataCandles
* @param {Array[]} update - incoming snapshot or single candle
* @param {EventMetaInformation} meta - source channel information
*/
this.triggerGlobalEvent('data', 'candles', candles, meta)
}
/**
* Propagates order books
*
* @param {object} update - partial or full order book snapshot
* @param {object} meta - routing information
* @private
*/
onDataBook (update, meta = {}) {
/**
* Triggered when an order book update is received.
*
* @event AOHost~dataBook
* @param {Array[]} update - incoming snapshot or price level
* @param {EventMetaInformation} meta - source channel information
*/
this.triggerGlobalEvent('data', 'book', update, meta)
}
/**
* Propagates full managed order books
*
* @param {object} book - full managed order book
* @param {object} meta - routing information
* @private
* @fires AOHost~dataManagedBook
*/
onDataManagedBook (book, meta = {}) {
/**
* Triggered when an order book update is received, and an internally
* managed order book instance is updated. The entire order book is passed
* to the event listeners.
*
* @event AOHost~dataManagedBook
* @param {object} book - full order boook
* @param {EventMetaInformation} meta - source channel information
*/
this.triggerGlobalEvent('data', 'managedBook', book, meta)
}
/**
* Propagates full candle sets
*
* @param {object[]} candles - full candle set
* @param {object} meta - routing information
* @private
*/
onDataManagedCandles (candles, meta = {}) {
/**
* Triggered when a candle update is received, and an internally managed
* candle dataset is updated. The entire dataset is passed to the event
* listeners.
*
* @event AOHost~dataManagedCandles
* @param {object[]} candles - full dataset
* @param {EventMetaInformation} meta - source channel information
*/
this.triggerGlobalEvent('data', 'managedCandles', candles, meta)
}
/**
* Loads and starts a single algo order, with the provided serialized state
*
* @param {string} id - algo order definition ID
* @param {string} gid - algo order instance group ID
* @param {object} loadedState - algo order instance state
* @returns {string} gid
* @private
*/
async loadAO (id, gid, loadedState = {}) {
const ao = this.getAO(id)
if (!ao) {
throw new Error(`unknown algo order: ${id}`)
}
const { meta = {} } = ao
const { unserialize } = meta
const state = _isFunction(unserialize)
? unserialize(loadedState)
: { ...loadedState }
state.id = id
state.gid = gid
state.channels = []
state.orders = {}
state.cancelledOrders = {}
state.allOrders = {}
state.ev = new AsyncEventEmitter()
const h = genHelpers(state, this.adapter)
/**
* @typedef {object} AOInstance
* @property {object} state - instance state used during execution
* @property {number} state.id - ID of the instance
* @property {number} state.gid - ID of the order group, attached to all
* orders
* @property {Array} state.channels - subscribed channels and their filters
* @property {object} state.orders - map of open orders key'd by client ID
* @property {object} state.cancelledOrders - map of cancelled orders key'd
* by client ID
* @property {object} state.allOrders - map of all orders ever created by
* the instance key'd by client ID
* @property {AsyncEventEmitter} state.ev - internal event emitter
* @property {module:Helpers} h - helpers bound to the instance
*/
const inst = { state, h }
await this.bootstrapAO(ao, inst)
return this.emit('ao:loaded', gid)
}
/**
* Creates and starts a new algo order instance, based on the AO def
* identified by the supplied ID
*
* @param {string} id - algo order definition ID, i.e. bfx-iceberg
* @param {object} args - algo order arguments/parameters
* @param {Function} [gidCB] - callback to acquire GID prior to ao:start
* @returns {string} gid - instance GID
*/
async startAO (id, args = {}, gidCB) {
const ao = this.getAO(id)
if (!ao) {
throw new Error(`unknown algo order: ${id}`)
}
const inst = initAO(this.adapter, ao, args)
return this.bootstrapAO(ao, inst, gidCB)
}
/**
* Prepares the provided algo order instance for execution, saves it
* internally for execution tracking, and starts it. Hooks up event listeners
* and executes `declareEvents` and `declareChannels` on the instance. Emits
* the 'ao:start' event.
*
* @param {object} ao - base algo order definition
* @param {object} instance - new algo order to be started
* @param {Function} [gidCB] - callback to acquire GID prior to ao:start
* @returns {string} gid - new instance GID
* @private
*/
async bootstrapAO (ao, instance = {}, gidCB) {
const { state } = instance
const { gid } = state
state.connection = this.adapter.getConnection()
this.instances[gid] = instance
state.ev.on('channel:assign', onAssignChannel.bind(null, this))
state.ev.on('state:update', onUpdateState.bind(null, this))
state.ev.on('notify', onNotify.bind(null, this))
state.ev.on('error:minimum_size', onMinimumSizeError.bind(null, this))
state.ev.on('error:insufficient_balance', onInsufficientBalanceError.bind(null, this))
state.ev.on('exec:order:submit:all', onSubmitAllOrders.bind(null, this))
state.ev.on('exec:order:cancel:all', onCancelAllOrders.bind(null, this))
state.ev.on('exec:stop', onStop.bind(null, this, gid))
const { declareEvents, declareChannels } = ao.meta || {}
if (_isFunction(declareEvents)) {
await declareEvents(this.instances[gid], this)
}
if (_isFunction(declareChannels)) {
await declareChannels(this.instances[gid], this)
}
// Cancel existing orders
for (let i = 0; i < this.orderSnapshot.length; i += 1) {
if (this.orderSnapshot[i].gid === +gid) {
await this.adapter.cancelOrderWithDelay(
state.connection, 0, this.orderSnapshot[i]
)
}
}
if (_isFunction(gidCB)) {
await gidCB(gid)
}
await this.emit('ao:start', this.instances[gid])
return gid
}
/**
* Stops an algo order instance by GID
*
* @param {string} gid - algo order instance GID
*/
async stopAO (gid) {
const instance = this.instances[gid]
if (!instance) {
throw new Error(`unknown AO: ${gid}`)
}
await this.emit('ao:stop', instance)
}
/**
* Triggers a 'self' event on an algo order instance with the provided
* arguments
*
* @param {object} instance - algo order instance to operate on
* @param {string} eventName - name of event to trigger
* @param {...any} args - event arguments
* @returns {Promise} p - resolves when all handlers complete
* @private
*/
onAOSelfEvent (instance, eventName, ...args) {
return this.triggerAOEvent(instance, 'self', eventName, ...args)
}
/**
* @returns {boolean} aosRunning - true if any algo order is currently running
*/
aosRunning () {
return Object.values(this.instances).find((instance) => {
const { state } = instance
const { active } = state
return active
})
}
/**
* Handles init for an algo order instance; sets the 'active' flag, subscribes
* to required channels, and triggers the life.start event.
*
* @param {object} instance - algo order instance that has started
* @private
*/
async onAOStart (instance = {}) {
const { channels = [], gid, connection } = instance.state
await withAOUpdate(this, gid, (instance = {}) => {
const { state = {} } = instance
return {
...state,
active: true
}
})
if (!_isEmpty(channels)) {
channels.forEach(ch => {
debug('subscribing to channel %j [AO gid %d]', ch, gid)
this.adapter.subscribe(connection, ch.channel, ch.filter)
})
}
/**
* Triggered when an algorithmic order begins execution.
*
* @event AOHost~lifeStart
*/
await this.triggerAOEvent(instance, 'life', 'start')
await this.emit('ao:persist', gid)
}
/**
* Handles algo order teardown; disables the 'active' state flag, unsubscribes
* from channels, emits the life.stop event, and saves the AO instance.
*
* @param {object} instance - algo order instance to operate on
* @private
*/
async onAOStop (instance = {}) {
const { h } = instance
const { channels = [], gid, connection } = instance.state
h.clearAllTimeouts()
await withAOUpdate(this, gid, (instance = {}) => {
const { state = {} } = instance
return {
...state,
active: false
}
})
if (!_isEmpty(channels)) {
channels.forEach(ch => {
debug('unsubscribing from channel %s [AO gid %d]', ch.channel, gid)
this.adapter.unsubscribe(connection, ch.channel, ch.filter)
})
}
/**
* Triggered when an algorithmic order ends execution.
*
* @event AOHost~lifeStop
*/
await this.triggerAOEvent(instance, 'life', 'stop')
await this.emit('ao:persist', gid)
}
/**
* Serializes & saves an algo order instance state to the DB
*
* @param {string} gid - GID of algo order instance to persist
* @private
*/
async onAOPersist (gid) {
const instance = this.instances[gid]
if (!instance) {
return
}
const { state = {} } = instance
const { id } = state
const ao = this.getAO(id)
if (!ao) {
throw new Error(`can\t persist unknown ao: ${id}`)
}
const { meta = {} } = ao
const { serialize } = meta
if (!serialize) {
debug('can\t save AO %s [%s] due to missing serialize method', gid, id)
return
}
await this.emit('ao:persist:db:update', {
gid,
algoID: id,
state: JSON.stringify(serialize(state)),
active: state.active
})
debug('saved AO %s', gid)
}
/**
* Passes event to the AO instances that know the order
*
* @param {string} section - name of section to trigger event on
* @param {string} eventName - name of event to trigger
* @param {object} order - order instance to pass to event handler
* @private
*/
async triggerOrderEvent (section, eventName, order) {
if (!this.adapter.orderEventsValid()) {
return
}
const instances = Object.values(this.instances)
await PI.forEach(instances, async (instance) => {
const { state = {} } = instance
const { orders = {}, allOrders = {}, cancelledOrders = {}, id, gid } = state
const cids = Object.keys(allOrders)
const cancelledCIds = Object.keys(cancelledOrders)
const ocid = order.cid + ''
// Note that we avoid triggering order_cancel for orders cancelled by us.
// order_cancel is meant to trigger after a user UI interaction
if (
_includes(cids, ocid) && // tracked (known) order
(
(eventName !== 'order_cancel' && eventName !== 'order_error') ||
!_includes(cancelledCIds, ocid) // or not canceled by us
)
) {
debug(
'triggering order event %s:%s for AO %s [gid %s, o cid %s, %f @ %f %s]',
section, eventName, id, gid, order.cid, order.amountOrig, order.price,
order.status
)
if (orders[ocid]) {
orders[ocid].updateFrom(order)
}
if (allOrders[ocid]) {
allOrders[ocid].updateFrom(order)
}
if (cancelledOrders[ocid]) {
cancelledOrders[ocid].updateFrom(order)
}
await this.triggerAOEvent(
instance,
section,
eventName,
allOrders[ocid]
)
}
})
}
/**
* Triggers an event with the supplied arguments on all active algo order
* instances.
*
* @param {string} section - name of section to trigger event on
* @param {string} eventName - name of event to trigger
* @param {...any} args - event arguments
* @returns {Promise} p - resolves when all handlers complete
* @private
*/
async triggerGlobalEvent (section, eventName, ...args) {
const instances = Object.values(this.instances)
return PI.forEach(instances, async (instance) => (
this.triggerAOEvent(instance, section, eventName, ...args)
))
}
/**
* Triggers an event on an algo order instance
*
* @param {object} instance - algo order instance to operate on
* @param {string} section - name of section to trigger event on
* @param {string} eventName - name of event to trigger
* @param {...any} args - event arguments
* @returns {Promise} p - resolves when all handlers complete
* @private
*/
async triggerAOEvent (instance, section, eventName, ...args) {
const { state } = instance
const { id, gid, ev } = state
const ao = this.getAO(id)
const sectionHandlers = (ao.events || {})[section]
const handler = _get((sectionHandlers || {}), eventName)
if (!_isFunction(handler)) {
if (section === 'self') {
debug('error: unknown handler %s:%s', section, eventName)
}
return
}
debug(
'triggering %s:%s for AO %s [gid %s]',
section, eventName, id, gid
)
await handler(instance, ...args)
return ev.emit(`internal:${section}:${eventName}`, ...args)
}
}
/**
* How long orders are allowed to settle for before teardown in ms.
*
* @type {number}
* @default 10000
*/
AOHost.TEARDOWN_GRACE_PERIOD_MS = 1 * 1000
module.exports = AOHost
</code></pre>
</article>
</section>
</div>
<br class="clear">
<footer>
Documentation generated by <a href="https://github.com/jsdoc3/jsdoc">JSDoc 3.6.6</a> on Tue Feb 09 2021 18:02:23 GMT+0545 (Nepal Time) using the <a href="https://github.com/clenemt/docdash">docdash</a> theme.
</footer>
<script>prettyPrint();</script>
<script src="scripts/polyfill.js"></script>
<script src="scripts/linenumber.js"></script>
<script src="scripts/search.js" defer></script>
</body>
</html>