-
Notifications
You must be signed in to change notification settings - Fork 40
/
Copy pathhost_gen_helpers.js.html
486 lines (402 loc) · 30.3 KB
/
host_gen_helpers.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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>host/gen_helpers.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#~cancelOrder">cancelOrder</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#~emitSelf">emitSelf</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#~subscribeDataChannels">subscribeDataChannels</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">host/gen_helpers.js</h1>
<section>
<article>
<pre class="prettyprint source linenums"><code>'use strict'
const Promise = require('bluebird')
const Debug = require('debug')
const flatPromise = require('flat-promise')
const MAX_SUBMIT_ATTEMPTS = 10
/**
* Generates a set of helpers to be used during algo order execution; these
* helpers are saved on the AO instance and provided to all event handlers.
*
* @param {object} state - algo order instance state
* @param {object} adapter - exchange adapter
* @returns {object} helpers
* @private
*/
const genHelpers = (state = {}, adapter) => {
const { id, gid } = state
const debug = Debug(`bfx:hf:algo:${id}:${gid}`)
const logHelperCall = (fmt, ...data) => {
const { DEBUG_TRACE } = process.env
if (DEBUG_TRACE) {
const { stack } = new Error()
debug(`${fmt} [%s]`, ...data, stack.split('\n')[3].trim())
} else {
debug(fmt, ...data)
}
}
const pendingSubscriptionResponses = {}
adapter.m.on('ws2:event:subscribed', (event) => {
const subscription = Object.values(pendingSubscriptionResponses)
.find(({ channel, payload }) =>
channel === event.channel &&
Object.entries(payload).every(([key, value]) => {
return value === event[key]
})
)
if (!subscription) {
return
}
const { eid, resolve, timeout } = subscription
if (timeout) {
clearTimeout(timeout)
}
delete pendingSubscriptionResponses[eid]
resolve()
})
/**
* @module Helpers
*
* @description
* ### AO Event Handlers & Helpers
* All event handlers receive the same arguments: `(instance = {}, ...args)`.
* The instance contains two objects, `{ state = {}, h = {} }` with `state`
* being the current AO state, and `h` being a helper object.
*
* The provided helpers are:
* * `clearAllTimeouts()` - clears all pending order submit/cancel timeouts
*
* * `debug(str, ...args)` - for logging information to the console, tagged
* by AO GID
*
* * `emitSelf(eventName, ...args)` - triggers an event on the 'self' section
*
* * `emit(eventName, ...args)` - raw event emitter, i.e. `emit('life:start')`
*
* * `notifyUI(level, message)` - generates and sends a notification which
* appears on the Bitfinex UI
*
* * `cancelOrder(state, order)` - takes current algo state and cancels the
* provided order
*
* * `submitOrderWithDelay(state, delay, order)` - takes current algo state,
* submits a new order, delay in ms
*
* * `declareEvent(instance, host, eventName, path)` - declares an internal
* AO event, see section below
*
* * `declareChannel(instance, host, channel, filter)` - declares a required
* data channel, see section below
*
* * `updateState(instance, update)` - update the current state for an AO
* instance
*/
return {
/**
* Clear all timeouts for pending subscriptions, called
* automatically by the algo host on teardown.
*/
clearAllTimeouts: () => {
for (const [eid, pendingSubscription] of Object.entries(pendingSubscriptionResponses)) {
if (pendingSubscription.timeout) {
clearTimeout(pendingSubscription.timeout)
}
delete pendingSubscriptionResponses[eid]
pendingSubscription.resolve()
}
},
timeout: (ms) => {
let id = null
const p = new Promise((resolve) => {
id = setTimeout(resolve, ms)
})
return [id, () => p]
},
/**
* Logs a string to the console, tagged by AO id/gid
*
* @param {string} str - format string
* @param {...any} args - passed to debug()
* @example
* debug('submitting order %s in %dms', order.toString(), delay)
*/
debug: (str, ...args) => {
debug(str, ...args)
},
/**
* Triggeres an event on the 'self' section
*
* @param {string} eventName - name of event to emit
* @param {...any} eventArgs - args passed to all handlers
* @returns {Promise} p - resolves when all handlers complete
* @example
* await emitSelf('submit_orders')
*/
emitSelf: async (eventName, ...eventArgs) => {
logHelperCall('emitSelf: %s', eventName)
return state.ev.emit(`self:${eventName}`, ...eventArgs)
},
/**
* Triggers a generic event
*
* @param {string} eventName - name of event to emit
* @param {...any} eventArgs - args passed to all handlers
* @returns {Promise} p - resolves when all handlers complete
* @example
* await emit('exec:order:submit:all', gid, [order], submitDelay)
*/
emit: async (eventName, ...eventArgs) => {
logHelperCall('emit %s', eventName)
return state.ev.emit(eventName, ...eventArgs)
},
/**
* Triggers an UI notification, sent out via the active websocket connection
*
* @param {string} level - 'info', 'success', 'error', 'warning'
* @param {string} message - notification content
* @returns {Promise} p - resolves when all handlers complete
* @example
* await notifyUI('info', `Scheduled tick in ${delay}s`)
*/
notifyUI: async (level, message) => {
logHelperCall('notify %s: %s', level, message)
await state.ev.emit('notify', gid, level, message)
},
/**
*
* @param {Object} state
* @param {Object} options
* @param {boolean} [options.fireAndForget]
* @param {number} [options.timeout]
* @returns Promise
*/
subscribeDataChannels: (state = {}, options = {}) => {
const { channels = [], gid, connection } = state
return Promise.all(
channels.map(({ channel, filter: payload }) => {
debug('subscribing to channel %j (filter: %) [AO gid %d]', channel, payload, gid)
adapter.subscribe(connection, channel, payload)
if (options.fireAndForget) {
return Promise.resolve()
}
const { promise, resolve, reject } = flatPromise()
const eid = Math.random()
const timeout = options.timeout &&
setTimeout(
() => {
delete pendingSubscriptionResponses[eid]
reject(new Error(`Subscription to channel '${channel}' timed out`))
},
options.timeout
)
pendingSubscriptionResponses[eid] = {
eid,
channel,
payload,
resolve,
timeout
}
return promise
})
)
},
/**
* Cancels the provided order instantly, and removes it from the active
* order set.
*
* @param {object} state - current AO instance state
* @param {object} order - order model or array
* @returns {object} nextState
* @example
* await cancelOrder(state, order)
*/
cancelOrder: async (state = {}, order) => {
logHelperCall('cancelOrder: %s', order.toString())
const { connection, orders = {} } = state
const {
[order.cid + '']: knownOrder, // eslint-disable-line
...otherOrders
} = orders
// NOTE: No await, in order to update cancelled order set immediately
adapter.cancelOrder(connection, order).then((order) => { // eslint-disable-line
debug(
'order successfully cancelled (id: %s, cid: %s): %s %f @ %f',
order.id, order.cid, order.type, order.amountOrig, order.price
)
}).catch((notification) => {
debug(
'received error while canceling order(id: %s, cid: %s): %s %f @ %f [ERROR: %O]',
order.id, order.cid, order.type, order.amountOrig, order.price, notification
)
})
return {
...state,
orders: otherOrders,
cancelledOrders: {
...state.cancelledOrders,
[order.cid + '']: order
}
}
},
sendPing: async (state = {}) => {
const { connection } = state
logHelperCall(
'sending ping to get server time'
)
const data = await adapter.sendPing(connection)
return data
},
/**
* Submits an order after a delay, and adds it to the active order set on
* the AO state. Emits errors if the order fails to submit; retries up to
* MAX_SUBMIT_ATTEMPTS in the case of balance evaluation errors.
*
* @param {object} state - current AO instance state
* @param {number} delay - delay in milliseconds
* @param {object} order - order model
* @param {number} attempt - attempt count, max is 10 (set as a constant)
* @returns {object} nextState
* @example
* await submitOrderWithDelay(state, 100, order)
*/
submitOrderWithDelay: async (state = {}, delay, order, attempt = 1) => {
logHelperCall(
'submitOrderWithDelay (%dms, attempt %d): %s',
delay, attempt, order.toString()
)
if (attempt > MAX_SUBMIT_ATTEMPTS) { // note state assumed already patched
return state
}
const { connection } = state
const orderPatch = {
[order.cid + '']: order
}
// Note that we don't wait for the order to submit here, since it might
// fill immediately triggering a fill event before we patch the state
// orders/allOrders objects
adapter.submitOrderWithDelay(connection, delay, order).then((order) => { // eslint-disable-line
debug(
'order successfully submitted: %s %f @ %f %s',
order.type, order.amountOrig, order.price, order.status
)
}).catch(async (notification) => {
const text = notification.text || notification
debug('%s', text)
if (/minimum size/.test(text)) {
await state.ev.emit('error:minimum_size', gid, order, { text })
} else if (/balance/.test(text)) {
await state.ev.emit('error:insufficient_balance', gid, order, { text })
} else if (/evaluate/.test(text)) {
if (attempt === MAX_SUBMIT_ATTEMPTS) {
await state.ev.emit('error:evaluate_balance', gid, order, { text })
} else {
const retryDelay = Math.max(500, delay + 250) // min 0.5s, increasing
await adapter.submitOrderWithDelay(connection, retryDelay, order)
}
} else {
await state.ev.emit('error:unknown_error', gid, order, { text })
}
})
return {
...state,
allOrders: { // track beyond close
...state.allOrders,
...orderPatch
},
orders: {
...state.orders,
...orderPatch
}
}
},
/**
* Hooks up the listener for a new event on the 'self' section
*
* @param {object} instance - full AO instance, with state/h
* @param {object} aoHost - algo host instance
* @param {string} eventName - name of event to declare
* @param {string} path - on the 'self' section
* @example
* declareEvent(instance, host, 'self:interval_tick', 'interval_tick')
*/
declareEvent: (instance = {}, aoHost, eventName, path) => {
const { state = {} } = instance
const { ev } = state
const handler = aoHost.onAOSelfEvent.bind(aoHost, instance, path)
logHelperCall('declareEvent: %s target %s', eventName, path)
ev.on(eventName, handler)
},
/**
* Assigns a data channel to the provided AO instance
*
* @param {object} instance - full AO instance, with state/h
* @param {object} aoHost - unused, here for common signature
* @param {string} channel - channel name, i.e. 'ticker'
* @param {object} filter - channel spec, i.e. { symbol: 'tBTCUSD' }
* @returns {object} nextState
* @example
* await declareChannel(instance, host, 'trades', { symbol })
*/
declareChannel: async (instance = {}, aoHost, channel, filter) => {
const { h = {}, state = {} } = instance
const { gid } = state
const { emit } = h
logHelperCall(
'declareChannel: %s filter %s', channel,
Object.keys(filter).map(k => `${k}=${filter[k]}`).join(', ')
)
await emit('channel:assign', gid, channel, filter)
return instance.state // updated ref
},
/**
* Updates the state for the provided AO instance
*
* @param {object} instance - full AO instance, with state/h
* @param {object} update - new state
* @returns {object} nextState
* @example
* await updateState(instance, { remainingAmount })
*/
updateState: async (instance = {}, update = {}) => {
const { h = {}, state = {} } = instance
const { gid } = state
const { emit } = h
logHelperCall('updateState')
await emit('state:update', gid, update)
return instance.state // updated ref
}
}
}
module.exports = genHelpers
</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 Mon Apr 26 2021 08:47:50 GMT-0300 (Brasilia Standard 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>