-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
helper.js
1135 lines (964 loc) · 28.8 KB
/
helper.js
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
const moment = require('moment');
const _ = require('lodash');
const config = require('config');
const { binance, slack, cache, mongo } = require('../../helpers');
const getGlobalConfiguration = async logger => {
const configValue = await mongo.findOne(logger, 'simple-stop-chaser-common', {
key: 'configuration'
});
if (_.isEmpty(configValue)) {
logger.info('Could not find global configuration.');
return {};
}
logger.info('Found global configuration.');
// To avoid undefined, little housekeeping here.
if (!configValue.buy) {
configValue.buy = {
enabled: true
};
}
if (!configValue.sell) {
configValue.sell = {
enabled: true
};
}
return configValue;
};
const getSymbolConfiguration = async (logger, symbol = null) => {
if (symbol === null) {
// If symbol is not provided, then return empty.
return {};
}
const configValue = await mongo.findOne(
logger,
'simple-stop-chaser-symbols',
{
key: `${symbol}-configuration`
}
);
if (_.isEmpty(configValue)) {
logger.info('Could not find symbol configuration.');
return {};
}
logger.info({ configValue }, 'Found symbol configuration.');
return configValue;
};
const saveGlobalConfiguration = async (logger, configuration) =>
mongo.upsertOne(
logger,
'simple-stop-chaser-common',
{
key: 'configuration'
},
{
key: 'configuration',
...configuration
}
);
const saveSymbolConfiguration = async (
logger,
symbol = null,
configuration = {}
) => {
if (symbol === null) {
// If symbol is not provided, then return empty.
return {};
}
return mongo.upsertOne(
logger,
'simple-stop-chaser-symbols',
{
key: `${symbol}-configuration`
},
{
key: `${symbol}-configuration`,
...configuration
}
);
};
const getConfiguration = async (logger, symbol = null) => {
// If symbol is not provided, then it only looks up global configuration
const globalConfigValue = await getGlobalConfiguration(logger);
const symbolConfigValue = await getSymbolConfiguration(logger, symbol);
// Merge global and symbol configuration
const configValue = { ...globalConfigValue, ...symbolConfigValue };
let simpleStopChaserConfig = {};
if (_.isEmpty(configValue) === false) {
logger.info('Found configuration from MongoDB');
simpleStopChaserConfig = configValue;
} else {
logger.info(
'Could not find configuration from MongoDB, retrieve from initial configuration.'
);
// If it is empty, then global configuration is not stored in the
simpleStopChaserConfig = config.get('jobs.simpleStopChaser');
await saveGlobalConfiguration(logger, simpleStopChaserConfig);
}
logger.info({ simpleStopChaserConfig }, 'Get configuration result');
return simpleStopChaserConfig;
};
/**
* Calculate round down
*
* @param {*} number
* @param {*} decimals
*/
const roundDown = (number, decimals) =>
// eslint-disable-next-line no-restricted-properties
Math.floor(number * Math.pow(10, decimals)) / Math.pow(10, decimals);
/**
* Cancel any open orders to get available balance
*
* @param {*} logger
* @param {*} symbol
*/
const cancelOpenOrders = async (logger, symbol) => {
logger.info('Cancelling open orders');
// Cancel open orders first to make sure it does not have unsettled orders.
try {
const result = await binance.client.cancelOpenOrders({ symbol });
logger.info({ result }, 'Cancelled open orders');
} catch (e) {
logger.info({ e }, 'Cancel result failed, but it is ok. Do not worry.');
}
};
/**
* Get symbol information
*
* @param {*} logger
* @param {*} symbol
*/
const getSymbolInfo = async (logger, symbol) => {
const cachedSymbolInfo = await cache.hget(
'simple-stop-chaser-symbols',
`${symbol}-symbol-info`
);
if (cachedSymbolInfo) {
logger.info({ cachedSymbolInfo }, 'Retrieved symbol info from the cache.');
return JSON.parse(cachedSymbolInfo);
}
logger.info({}, 'Request exchange info from Binance.');
const exchangeInfo = await binance.client.exchangeInfo();
logger.info({}, 'Retrieved exchange info from Binance.');
const symbolInfo =
_.filter(exchangeInfo.symbols, s => s.symbol === symbol)[0] || {};
symbolInfo.filterLotSize =
_.filter(symbolInfo.filters, f => f.filterType === 'LOT_SIZE')[0] || {};
symbolInfo.filterPrice =
_.filter(symbolInfo.filters, f => f.filterType === 'PRICE_FILTER')[0] || {};
symbolInfo.filterPercent =
_.filter(symbolInfo.filters, f => f.filterType === 'PERCENT_PRICE')[0] ||
{};
symbolInfo.filterMinNotional =
_.filter(symbolInfo.filters, f => f.filterType === 'MIN_NOTIONAL')[0] || {};
const success = await cache.hset(
'simple-stop-chaser-symbols',
`${symbol}-symbol-info`,
JSON.stringify(symbolInfo)
);
logger.info({ success, symbolInfo }, 'Retrieved symbol info from Binance.');
return symbolInfo;
};
/**
* Retrieve balance for buy trade asset based on the trade action
*
* @param {*} logger
* @param {*} indicators
* @param {*} options
*/
const getBuyBalance = async (logger, indicators, options) => {
const { symbolInfo, lastCandle } = indicators;
logger.info({ lastCandle }, 'Retrieve last candle');
// 1. Get account info
const accountInfo = await binance.client.accountInfo({ recvWindow: 10000 });
logger.info('Retrieved Account info');
const { quoteAsset, baseAsset } = symbolInfo;
logger.info({ quoteAsset, baseAsset }, 'Retrieve assets');
// 2. Get quote asset balance
const quoteAssetBalance =
_.filter(accountInfo.balances, b => b.asset === quoteAsset)[0] || {};
const baseAssetBalance =
_.filter(accountInfo.balances, b => b.asset === baseAsset)[0] || {};
if (_.isEmpty(quoteAssetBalance) || _.isEmpty(baseAssetBalance)) {
return {
result: false,
message: 'Balance is not found. Do not place an order.',
quoteAssetBalance,
baseAssetBalance
};
}
const baseAssetTotalBalance =
+baseAssetBalance.free + +baseAssetBalance.locked;
logger.info({ quoteAssetBalance, baseAssetBalance }, 'Balance found');
// 3. Make sure we don't have base asset balance which assume already purchased.
const lastCandleClose = +lastCandle.close;
if (
baseAssetTotalBalance * lastCandleClose >
+symbolInfo.filterMinNotional.minNotional
) {
return {
result: false,
message:
'The base asset has enough balance to place a stop-loss limit order. Do not place a buy order.',
baseAsset,
baseAssetTotalBalance,
lastCandleClose,
currentBalanceInQuoteAsset: baseAssetTotalBalance * lastCandleClose,
minNotional: symbolInfo.filterMinNotional.minNotional
};
}
// 4. Calculate free balance with precision
const lotPrecision = symbolInfo.filterLotSize.stepSize.indexOf(1) - 1;
let freeBalance = parseFloat(_.floor(+quoteAssetBalance.free, lotPrecision));
logger.info({ freeBalance }, 'Current free balance');
// 5. Check if free balance is more than maximum purchase amount (USDT),
if (freeBalance > options.maxPurchaseAmount) {
freeBalance = options.maxPurchaseAmount;
logger.info({ freeBalance }, 'Adjusted free balance');
}
// 6. Validate free balance for buy action
if (freeBalance < +symbolInfo.filterMinNotional.minNotional) {
return {
result: false,
message:
'Balance is less than the minimum notional. Do not place an order.',
freeBalance
};
}
return {
result: true,
message: 'Balance found.',
freeBalance
};
};
/**
* Retrieve balance for buy trade asset based on the trade action
*
* @param {*} logger
* @param {*} symbolInfo
* @param {*} indicators
* @param {*} stopLossLimitConfig
*/
const getSellBalance = async (
logger,
symbolInfo,
indicators,
stopLossLimitConfig
) => {
// 1. Get account info
const accountInfo = await binance.client.accountInfo({ recvWindow: 10000 });
logger.info('Retrieved Account info');
const { baseAsset, symbol } = symbolInfo;
logger.info({ baseAsset }, 'Retrieved base asset');
// 2. Get trade asset balance
const baseAssetBalance =
_.filter(accountInfo.balances, b => b.asset === baseAsset)[0] || {};
if (_.isEmpty(baseAssetBalance)) {
return {
result: false,
message: 'Balance is not found. Do not place an order.',
baseAssetBalance
};
}
logger.info({ baseAssetBalance }, 'Balance found');
// 3. Calculate free balance with precision
const lotPrecision = symbolInfo.filterLotSize.stepSize.indexOf(1) - 1;
const freeBalance = parseFloat(_.floor(+baseAssetBalance.free, lotPrecision));
const lockedBalance = parseFloat(
_.floor(+baseAssetBalance.locked, lotPrecision)
);
// 4. If total balance is not enough to sell, then the last buy price is meaningless.
const totalBalance = freeBalance + lockedBalance;
// Calculate quantity - commission
const quantity = parseFloat(
_.floor(totalBalance - totalBalance * (0.1 / 100), lotPrecision)
);
if (quantity <= +symbolInfo.filterLotSize.minQty) {
await mongo.deleteOne(logger, 'simple-stop-chaser-symbols', {
key: `${symbol}-last-buy-price`
});
return {
result: false,
message: 'Balance found, but not enough to sell. Delete last buy price.',
freeBalance,
lockedBalance
};
}
const lastCandleClose = +indicators.lastCandle.close;
const orderPrecision = symbolInfo.filterPrice.tickSize.indexOf(1) - 1;
const price = roundDown(
lastCandleClose * +stopLossLimitConfig.limitPercentage,
orderPrecision
);
// Notional value = contract size (order quantity) * underlying price (order price)
if (quantity * price < +symbolInfo.filterMinNotional.minNotional) {
await mongo.deleteOne(logger, 'simple-stop-chaser-symbols', {
key: `${symbol}-last-buy-price`
});
return {
result: false,
message:
'Balance found, but the notional value is less than the minimum notional value. Delete last buy price.',
freeBalance,
lockedBalance
};
}
return {
result: true,
message: 'Balance found.',
freeBalance,
lockedBalance
};
};
/**
* Calculate order quantity
*
* @param {*} logger
* @param {*} symbolInfo
* @param {*} balanceInfo
* @param {*} indicators
*/
const getBuyOrderQuantity = (logger, symbolInfo, balanceInfo, indicators) => {
const baseAssetPrice = +indicators.lastCandle.close;
logger.info({ baseAssetPrice }, 'Retrieved latest asset price');
const lotPrecision = symbolInfo.filterLotSize.stepSize.indexOf(1) - 1;
const { freeBalance } = balanceInfo;
const orderQuantityBeforeCommission = 1 / (+baseAssetPrice / freeBalance);
const orderQuantity = parseFloat(
_.floor(
orderQuantityBeforeCommission -
orderQuantityBeforeCommission * (0.1 / 100),
lotPrecision
)
);
if (orderQuantity <= 0) {
return {
result: false,
message: 'Order quantity is less or equal to 0. Do not place an order.',
baseAssetPrice,
orderQuantity,
freeBalance
};
}
return {
result: true,
message: 'Calculated order quantity to buy.',
baseAssetPrice,
orderQuantity,
freeBalance
};
};
/**
* Calculate order price
*
* @param {*} logger
* @param {*} symbolInfo
* @param {*} orderQuantityInfo
*/
const getBuyOrderPrice = (logger, symbolInfo, orderQuantityInfo) => {
const orderPrecision = symbolInfo.filterPrice.tickSize.indexOf(1) - 1;
const orderPrice = parseFloat(
_.floor(+orderQuantityInfo.baseAssetPrice, orderPrecision)
);
logger.info({ orderPrecision, orderPrice }, 'Calculated order price');
// Notional value = contract size (order quantity) * underlying price (order price)
if (
orderQuantityInfo.orderQuantity * orderPrice <
symbolInfo.filterMinNotional.minNotional
) {
return {
result: false,
message: `Notional value is less than the minimum notional value. Do not place an order.`,
orderPrice
};
}
return {
result: true,
message: 'Calculated order price for buy.',
orderPrice
};
};
/**
* Get open orders
*
* @param {*} logger
* @param {*} symbol
*/
const getOpenOrders = async (logger, symbol) => {
const openOrders = await binance.client.openOrders({
symbol,
recvWindow: 10000
});
logger.info({ openOrders }, 'Get open orders');
return openOrders;
};
/**
* Place stop loss limit order
*
* @param {*} logger
* @param {*} symbolInfo
* @param {*} balanceInfo
* @param {*} indicators
* @param {*} stopLossLimitInfo
*/
const placeStopLossLimitOrder = async (
logger,
symbolInfo,
balanceInfo,
indicators,
stopLossLimitInfo
) => {
logger.info('Started place stop loss limit order');
const basePrice = +indicators.lastCandle.close;
const balance = balanceInfo.freeBalance;
const lotPrecision = symbolInfo.filterLotSize.stepSize.indexOf(1) - 1;
const orderPrecision = symbolInfo.filterPrice.tickSize.indexOf(1) - 1;
logger.info(
{ basePrice, balance, orderPrecision, stopLossLimitInfo },
'Prepare params'
);
const stopPrice = roundDown(
basePrice * +stopLossLimitInfo.stopPercentage,
orderPrecision
);
const price = roundDown(
basePrice * +stopLossLimitInfo.limitPercentage,
orderPrecision
);
// Calculate quantity - commission
const quantity = parseFloat(
_.floor(balance - balance * (0.1 / 100), lotPrecision)
);
if (quantity <= +symbolInfo.filterLotSize.minQty) {
return {
result: false,
message:
`Order quantity is less or equal than the minimum quantity - ${symbolInfo.filterLotSize.minQty}. ` +
`Do not place an order.`,
quantity
};
}
// Notional value = contract size (order quantity) * underlying price (order price)
if (quantity * price < +symbolInfo.filterMinNotional.minNotional) {
return {
result: false,
message: `Notional value is less than the minimum notional value. Do not place an order.`,
quantity,
price,
notionValue: quantity * price,
minNotional: +symbolInfo.filterMinNotional.minNotional
};
}
const orderParams = {
symbol: symbolInfo.symbol,
side: 'sell',
type: 'STOP_LOSS_LIMIT',
quantity,
price,
timeInForce: 'GTC',
stopPrice
};
logger.info({ orderParams }, 'Order params');
slack.sendMessage(`Action: *STOP_LOSS_LIMIT*
- Order Params: \`\`\`${JSON.stringify(orderParams, undefined, 2)}\`\`\`
`);
const orderResult = await binance.client.order(orderParams);
logger.info({ orderResult }, 'Order result');
cache.hset(
'simple-stop-chaser-symbols',
`${symbolInfo.symbol}-last-placed-stop-loss-order`,
JSON.stringify(orderParams)
);
await slack.sendMessage(
`Action Result: *STOP_LOSS_LIMIT*
- Order Result: \`\`\`${JSON.stringify(orderResult, undefined, 2)}\`\`\``
);
return {
result: true,
message: `Placed stop loss order.`,
orderParams,
orderResult
};
};
/**
* Get balance from Binance
*
* @param {*} logger
*/
const getAccountInfo = async logger => {
const accountInfo = await binance.client.accountInfo();
accountInfo.balances = accountInfo.balances.reduce((acc, b) => {
const balance = b;
if (+balance.free > 0 || +balance.locked > 0) {
acc.push(balance);
}
return acc;
}, []);
logger.info({ accountInfo }, 'Retrieved account information');
return accountInfo;
};
/**
* Get exchange info from Binance
*
* @param {*} logger
*/
const getExchangeSymbols = async logger => {
const simpleStopChaserConfig = await getConfiguration(logger);
const cachedExchangeInfo = await cache.hget(
'simple-stop-chaser-common',
'exchange-symbols'
);
if (_.isEmpty(cachedExchangeInfo) === false) {
logger.info(
{ cachedExchangeInfo },
'Retrieved exchange information from cache'
);
return JSON.parse(cachedExchangeInfo);
}
const exchangeInfo = await binance.client.exchangeInfo();
let { supportFIATs } = simpleStopChaserConfig;
if (!supportFIATs) {
supportFIATs = config.get('jobs.simpleStopChaser.supportFIATs');
}
logger.info({ supportFIATs }, 'Support FIATs');
const { symbols } = exchangeInfo;
const exchangeSymbols = symbols.reduce((acc, symbol) => {
if (new RegExp(supportFIATs.join('|')).test(symbol.symbol)) {
acc.push(symbol.symbol);
}
return acc;
}, []);
await cache.hset(
'simple-stop-chaser-common',
'exchange-symbols',
JSON.stringify(exchangeSymbols)
);
logger.info({ exchangeSymbols }, 'Retrieved exchange symbols');
return exchangeSymbols;
};
/**
* Flatten candle data
*
* @param {*} candles
*/
const flattenCandlesData = candles => {
const openTime = [];
const low = [];
candles.forEach(candle => {
openTime.push(+candle.openTime);
low.push(+candle.low);
});
return {
openTime,
low
};
};
/**
* Get candles from Binance and determine buy signal with lowest price
*
* @param {*} logger
*/
const getIndicators = async (symbol, logger) => {
const simpleStopChaserConfig = await getConfiguration(logger, symbol);
const candles = await binance.client.candles({
symbol,
interval: simpleStopChaserConfig.candles.interval,
limit: simpleStopChaserConfig.candles.limit
});
const [lastCandle] = candles.slice(-1);
logger.info({ lastCandle }, 'Retrieved candles');
const candlesData = flattenCandlesData(candles);
// MIN
const lowestClosed = _.min(candlesData.low);
logger.info({ lowestClosed }, 'Retrieved lowest closed value result');
// Cast string to number
lastCandle.close = +lastCandle.close;
const symbolInfo = await getSymbolInfo(logger, symbol);
return {
symbol,
lowestClosed,
lastCandle,
symbolInfo
};
};
/**
* Determine action based on indicator
*
* @param {*} logger
* @param {*} indicators
*/
const determineAction = async (logger, indicators) => {
let action = 'wait';
const { symbol, lowestClosed, lastCandle } = indicators;
if (lastCandle.close <= lowestClosed) {
action = 'buy';
logger.info(
{ symbol, lowestClosed, close: lastCandle.close },
"Current price is less than the lowest minimum price. Let's buy it."
);
} else {
logger.warn(
{ symbol, lowestClosed, close: lastCandle.close },
'Current price is higher than the lowest minimum price. Do not buy.'
);
}
// Store last action
const returnValue = {
symbol,
action,
lastCandleClose: lastCandle.close,
lowestClosed,
timeUTC: moment().utc()
};
cache.hset(
'simple-stop-chaser-symbols',
`${symbol}-determine-action`,
JSON.stringify(returnValue)
);
return returnValue;
};
/**
* Place buy order based on signal
* Note: This method is optimised for USDT only.
*
* @param {*} logger
* @param {*} indicators
*/
const placeBuyOrder = async (logger, indicators) => {
logger.info('Start placing buy order');
const { symbol, symbolInfo } = indicators;
const simpleStopChaserConfig = await getConfiguration(logger, symbol);
let returnValue;
// 1. Cancel all orders
await cancelOpenOrders(logger, symbol);
// 2. Get balance for trade asset
const { maxPurchaseAmount } = simpleStopChaserConfig;
const balanceInfo = await getBuyBalance(logger, indicators, {
maxPurchaseAmount
});
if (balanceInfo.result === false) {
logger.warn({ balanceInfo }, 'getBuyBalance result');
cache.hset(
'simple-stop-chaser-symbols',
`${symbol}-place-buy-order-result`,
JSON.stringify(balanceInfo)
);
return balanceInfo;
}
logger.info({ balanceInfo }, 'getBuyBalance result');
// 3. Get order quantity
const orderQuantityInfo = getBuyOrderQuantity(
logger,
symbolInfo,
balanceInfo,
indicators
);
if (orderQuantityInfo.result === false) {
logger.warn({ orderQuantityInfo }, 'getBuyOrderQuantity result');
cache.hset(
'simple-stop-chaser-symbols',
`${symbol}-place-buy-order-result`,
JSON.stringify(orderQuantityInfo)
);
return orderQuantityInfo;
}
logger.info({ orderQuantityInfo }, 'getBuyOrderQuantity result');
// 4. Get order price
const orderPriceInfo = getBuyOrderPrice(
logger,
symbolInfo,
orderQuantityInfo
);
if (orderPriceInfo.result === false) {
logger.warn({ orderPriceInfo }, 'getBuyOrderPrice result');
cache.hset(
'simple-stop-chaser-symbols',
`${symbol}-place-buy-order-result`,
JSON.stringify(orderPriceInfo)
);
return orderPriceInfo;
}
logger.info({ orderPriceInfo }, 'getBuyOrderPrice result');
// 5. Check trading enabled
if (simpleStopChaserConfig.buy.enabled === false) {
// Trading is disabled. So do not place an order.
returnValue = {
result: false,
message: 'Trading for this symbol is disabled. Do not place an order.'
};
logger.warn(returnValue);
cache.hset(
'simple-stop-chaser-symbols',
`${symbol}-place-buy-order-result`,
JSON.stringify(returnValue)
);
return returnValue;
}
// 6. Place order
const orderParams = {
symbol,
side: 'buy',
type: 'LIMIT',
quantity: orderQuantityInfo.orderQuantity,
price: orderPriceInfo.orderPrice,
timeInForce: 'GTC'
};
slack.sendMessage(`${symbol} Action: *Buy*
- Free Balance: ${orderQuantityInfo.freeBalance}
- Order Quantity: ${orderQuantityInfo.orderQuantity}
- Order Params: \`\`\`${JSON.stringify(orderParams, undefined, 2)}\`\`\`
`);
logger.info({ orderParams }, 'Buy order params');
const orderResult = await binance.client.order(orderParams);
logger.info({ orderResult }, 'Buy order result');
cache.hset(
'simple-stop-chaser-symbols',
`${symbol}-place-buy-order-result`,
JSON.stringify({
result: true,
message: `Placed buy order at the price of ${orderPriceInfo.orderPrice}.`
})
);
await mongo.upsertOne(
logger,
'simple-stop-chaser-symbols',
{
key: `${symbol}-last-buy-price`
},
{
key: `${symbol}-last-buy-price`,
lastBuyPrice: orderPriceInfo.orderPrice
}
);
await slack.sendMessage(
`${symbol} Action Result: *Buy*
- Order Result: \`\`\`${JSON.stringify(orderResult, undefined, 2)}\`\`\``
);
return orderResult;
};
/**
* Chase stop loss order
* Keep chasing dream
*
* @param {*} logger
* @param {*} indicators
*/
const chaseStopLossLimitOrder = async (logger, indicators) => {
logger.info('Start chaseStopLossLimitOrder');
const { symbol, symbolInfo } = indicators;
const simpleStopChaserConfig = await getConfiguration(logger, symbol);
let returnValue;
const { stopLossLimit: stopLossLimitConfig } = simpleStopChaserConfig;
// 1. Get open orders
const openOrders = await getOpenOrders(logger, symbol);
cache.hset(
'simple-stop-chaser-symbols',
`${symbol}-open-orders`,
JSON.stringify(openOrders)
);
// 1-1. Get last buy price and make sure it is within minimum profit range.
const lastBuyPriceDoc = await mongo.findOne(
logger,
'simple-stop-chaser-symbols',
{
key: `${symbol}-last-buy-price`
}
);
const cachedLastBuyPrice =
lastBuyPriceDoc && lastBuyPriceDoc.lastBuyPrice
? lastBuyPriceDoc.lastBuyPrice
: null;
logger.debug({ cachedLastBuyPrice }, 'Last buy price');
if (
_.isEmpty(openOrders) &&
(!cachedLastBuyPrice || +cachedLastBuyPrice <= 0)
) {
returnValue = {
result: false,
message:
'Open order cannot be found and cannot get last buy price from the cache. Wait.'
};
// Delete sell signal
cache.hdel(
'simple-stop-chaser-symbols',
`${symbol}-chase-stop-loss-limit-order-sell-signal`
);
cache.hdel(
'simple-stop-chaser-symbols',
`${symbol}-chase-stop-loss-limit-order-sell-signal-result`
);
return returnValue;
}
const lastBuyPrice = +cachedLastBuyPrice;
logger.info({ lastBuyPrice }, 'Retrieved last buy price');
const lastCandleClose = +indicators.lastCandle.close;
logger.info({ lastCandleClose }, 'Retrieved last closed price');
const calculatedLastBuyPrice =
lastBuyPrice * +stopLossLimitConfig.lastBuyPercentage;
const sellSignalInfo = {
lastBuyPrice,
lastCandleClose,
calculatedLastBuyPrice
};
cache.hset(
'simple-stop-chaser-symbols',
`${symbol}-chase-stop-loss-limit-order-sell-signal`,
JSON.stringify({
...sellSignalInfo,
timeUTC: moment().utc()
})
);
// 2. If there is no open orders
if (openOrders.length === 0) {
logger.info(
{ openOrders, lastBuyPrice },
'There is no open orders but found the last buy price. Try to get a selling signal.'
);
// 2-1. Get current balance of symbol.
// If there is not enough balance, then remove last buy price and return.
const balanceInfo = await getSellBalance(
logger,
symbolInfo,
indicators,
stopLossLimitConfig
);
if (balanceInfo.result === false) {
logger.warn({ balanceInfo }, 'getSellBalance result');
cache.hset(
'simple-stop-chaser-symbols',
`${symbol}-chase-stop-loss-limit-order-sell-signal-result`,
JSON.stringify({
...sellSignalInfo,
...balanceInfo,
timeUTC: moment().utc()
})
);
return balanceInfo;
}
logger.info({ balanceInfo }, 'getSellBalance result');
// 2-2. Compare last buy price is within minimum profit range.
// If not cached for some reason, it will just place stop-loss-limit order.
if (lastCandleClose < calculatedLastBuyPrice) {
returnValue = {
result: false,
message: 'Current price is lower than the minimum selling price. Wait.',