@gbozee/ultimate 0.0.2-10 → 0.0.2-101

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2392 @@
1
+ // src/helpers/trade_signal.ts
2
+ function determine_close_price({
3
+ entry,
4
+ pnl,
5
+ quantity,
6
+ leverage = 1,
7
+ kind = "long"
8
+ }) {
9
+ const dollar_value = entry / leverage;
10
+ const position = dollar_value * quantity;
11
+ if (position) {
12
+ const percent = pnl / position;
13
+ const difference = position * percent / quantity;
14
+ const result = kind === "long" ? difference + entry : entry - difference;
15
+ return result;
16
+ }
17
+ return 0;
18
+ }
19
+ function determine_pnl(entry, close_price, quantity, kind = "long", contract_size) {
20
+ if (contract_size) {
21
+ const direction = kind === "long" ? 1 : -1;
22
+ return quantity * contract_size * direction * (1 / entry - 1 / close_price);
23
+ }
24
+ const difference = kind === "long" ? close_price - entry : entry - close_price;
25
+ return difference * quantity;
26
+ }
27
+ function* _get_zones({
28
+ current_price,
29
+ focus,
30
+ percent_change,
31
+ places = "%.5f"
32
+ }) {
33
+ let last = focus;
34
+ let focus_high = last * (1 + percent_change);
35
+ let focus_low = last * Math.pow(1 + percent_change, -1);
36
+ if (focus_high > current_price) {
37
+ while (focus_high > current_price) {
38
+ yield to_f(last, places);
39
+ focus_high = last;
40
+ last = focus_high * Math.pow(1 + percent_change, -1);
41
+ focus_low = last * Math.pow(1 + percent_change, -1);
42
+ }
43
+ } else {
44
+ if (focus_high <= current_price) {
45
+ while (focus_high <= current_price) {
46
+ yield to_f(focus_high, places);
47
+ focus_low = focus_high;
48
+ last = focus_low * (1 + percent_change);
49
+ focus_high = last * (1 + percent_change);
50
+ }
51
+ } else {
52
+ while (focus_low <= current_price) {
53
+ yield to_f(focus_high, places);
54
+ focus_low = focus_high;
55
+ last = focus_low * (1 + percent_change);
56
+ focus_high = last * (1 + percent_change);
57
+ }
58
+ }
59
+ }
60
+ }
61
+
62
+ class Signal {
63
+ focus;
64
+ budget;
65
+ percent_change = 0.02;
66
+ price_places = "%.5f";
67
+ decimal_places = "%.0f";
68
+ zone_risk = 1;
69
+ fee = 0.08 / 100;
70
+ support;
71
+ risk_reward = 4;
72
+ resistance;
73
+ risk_per_trade;
74
+ increase_size = false;
75
+ additional_increase = 0;
76
+ minimum_pnl = 0;
77
+ take_profit;
78
+ increase_position = false;
79
+ minimum_size;
80
+ first_order_size;
81
+ gap = 10;
82
+ max_size = 0;
83
+ constructor({
84
+ focus,
85
+ budget,
86
+ percent_change = 0.02,
87
+ price_places = "%.5f",
88
+ decimal_places = "%.0f",
89
+ zone_risk = 1,
90
+ fee = 0.06 / 100,
91
+ support,
92
+ risk_reward = 4,
93
+ resistance,
94
+ risk_per_trade,
95
+ increase_size = false,
96
+ additional_increase = 0,
97
+ minimum_pnl = 0,
98
+ take_profit,
99
+ increase_position = false,
100
+ minimum_size = 0,
101
+ first_order_size = 0,
102
+ gap = 10,
103
+ max_size = 0
104
+ }) {
105
+ this.minimum_size = minimum_size;
106
+ this.first_order_size = first_order_size;
107
+ this.focus = focus;
108
+ this.budget = budget;
109
+ this.percent_change = percent_change;
110
+ this.price_places = price_places;
111
+ this.decimal_places = decimal_places;
112
+ this.zone_risk = zone_risk;
113
+ this.fee = fee;
114
+ this.support = support;
115
+ this.risk_reward = risk_reward;
116
+ this.resistance = resistance;
117
+ this.risk_per_trade = risk_per_trade;
118
+ this.increase_size = increase_size;
119
+ this.additional_increase = additional_increase;
120
+ this.minimum_pnl = minimum_pnl;
121
+ this.take_profit = take_profit;
122
+ this.increase_position = increase_position;
123
+ this.gap = gap;
124
+ this.max_size = max_size;
125
+ }
126
+ build_entry({
127
+ current_price,
128
+ stop_loss,
129
+ pnl,
130
+ stop_percent,
131
+ kind = "long",
132
+ risk,
133
+ no_of_trades = 1,
134
+ take_profit
135
+ }) {
136
+ let _stop_loss = stop_loss;
137
+ if (!_stop_loss && stop_percent) {
138
+ _stop_loss = kind === "long" ? current_price * Math.pow(1 + stop_percent, -1) : current_price * Math.pow(1 + stop_percent, 1);
139
+ }
140
+ const percent_change = _stop_loss ? Math.max(current_price, _stop_loss) / Math.min(current_price, _stop_loss) - 1 : this.percent_change;
141
+ const _no_of_trades = no_of_trades || this.risk_reward;
142
+ let _resistance = current_price * Math.pow(1 + percent_change, 1);
143
+ const derivedConfig = {
144
+ ...this,
145
+ percent_change,
146
+ focus: current_price,
147
+ resistance: _resistance,
148
+ risk_per_trade: risk / this.risk_reward,
149
+ minimum_pnl: pnl,
150
+ risk_reward: _no_of_trades,
151
+ take_profit: take_profit || this.take_profit,
152
+ support: kind === "long" ? _stop_loss : this.support
153
+ };
154
+ const instance = new Signal(derivedConfig);
155
+ if (kind === "short") {}
156
+ let result = instance.get_bulk_trade_zones({ current_price, kind });
157
+ return result;
158
+ return result?.filter((x) => {
159
+ let pp = parseFloat(this.decimal_places.replace("%.", "").replace("f", ""));
160
+ if (pp < 3) {
161
+ return true;
162
+ }
163
+ if (kind === "long") {
164
+ return x.entry > x.stop + 0.5;
165
+ }
166
+ return x.entry + 0.5 < x.stop;
167
+ });
168
+ }
169
+ get risk() {
170
+ return this.budget * this.percent_change;
171
+ }
172
+ get min_trades() {
173
+ return parseInt(this.risk.toString());
174
+ }
175
+ get min_price() {
176
+ const number = this.price_places.replace("%.", "").replace("f", "");
177
+ return 1 * Math.pow(10, -parseInt(number));
178
+ }
179
+ build_opposite_order({
180
+ current_price,
181
+ kind = "long"
182
+ }) {
183
+ let _current_price = current_price;
184
+ if (kind === "long") {
185
+ _current_price = current_price * Math.pow(1 + this.percent_change, -1);
186
+ }
187
+ const result = this.special_build_orders({
188
+ current_price: _current_price,
189
+ kind
190
+ });
191
+ const first_price = result[result.length - 1].entry;
192
+ const stop = result[0].stop;
193
+ const instance = new Signal({ ...this, take_profit: stop });
194
+ const new_kind = kind === "long" ? "short" : "long";
195
+ return instance.build_orders({
196
+ current_price: first_price,
197
+ kind: new_kind
198
+ });
199
+ }
200
+ special_build_orders({
201
+ current_price,
202
+ kind = "long"
203
+ }) {
204
+ let orders = this.build_orders({ current_price, kind });
205
+ if (orders?.length > 1) {
206
+ orders = this.build_orders({ current_price: orders[1].entry, kind });
207
+ }
208
+ if (orders.length > 0) {
209
+ const new_kind = kind === "long" ? "short" : "long";
210
+ let opposite_order = this.build_orders({
211
+ current_price: orders[orders.length - 1].entry,
212
+ kind: new_kind
213
+ });
214
+ this.take_profit = opposite_order[0].stop;
215
+ orders = this.build_orders({
216
+ current_price: orders[orders.length - 1].entry,
217
+ kind
218
+ });
219
+ }
220
+ return orders;
221
+ }
222
+ build_orders({
223
+ current_price,
224
+ kind = "long",
225
+ limit = false,
226
+ replace_focus = false,
227
+ max_index = 0,
228
+ min_index = 2
229
+ }) {
230
+ const focus = this.focus;
231
+ if (replace_focus) {
232
+ this.focus = current_price;
233
+ }
234
+ const new_kind = kind === "long" ? "short" : "long";
235
+ const take_profit = this.take_profit;
236
+ this.take_profit = undefined;
237
+ let result = this.get_bulk_trade_zones({
238
+ current_price,
239
+ kind: new_kind,
240
+ limit
241
+ });
242
+ if (result?.length) {
243
+ let oppositeStop = result[0]["sell_price"];
244
+ let oppositeEntry = result[result.length - 1]["entry"];
245
+ let tradeLength = this.risk_reward + 1;
246
+ let percentChange = Math.abs(1 - Math.max(oppositeEntry, oppositeStop) / Math.min(oppositeEntry, oppositeStop)) / tradeLength;
247
+ let newTrades = [];
248
+ for (let x = 0;x < tradeLength; x++) {
249
+ newTrades.push(oppositeStop * Math.pow(1 + percentChange, x));
250
+ }
251
+ if (kind === "short") {
252
+ newTrades = [];
253
+ for (let x = 0;x < tradeLength; x++) {
254
+ newTrades.push(oppositeStop * Math.pow(1 + percentChange, x * -1));
255
+ }
256
+ }
257
+ this.take_profit = take_profit;
258
+ newTrades = newTrades.map((r) => this.to_f(r));
259
+ if (kind === "long") {
260
+ if (newTrades[1] > current_price) {
261
+ const start = newTrades[0];
262
+ newTrades = [];
263
+ for (let x = 0;x < tradeLength; x++) {
264
+ newTrades.push(start * Math.pow(1 + percentChange, x * -1));
265
+ }
266
+ newTrades.sort();
267
+ }
268
+ }
269
+ const newR = this.process_orders({
270
+ current_price,
271
+ stop_loss: newTrades[0],
272
+ trade_zones: newTrades,
273
+ kind
274
+ });
275
+ return newR;
276
+ }
277
+ this.focus = focus;
278
+ return result;
279
+ }
280
+ build_orders_old({
281
+ current_price,
282
+ kind = "long",
283
+ limit = false,
284
+ replace_focus = false,
285
+ max_index = 0,
286
+ min_index = 2
287
+ }) {
288
+ const focus = this.focus;
289
+ if (replace_focus) {
290
+ this.focus = current_price;
291
+ }
292
+ const result = this.get_bulk_trade_zones({ current_price, kind, limit });
293
+ if (result?.length) {
294
+ let next_focus;
295
+ if (kind == "long") {
296
+ next_focus = current_price * (1 + this.percent_change);
297
+ } else {
298
+ next_focus = current_price * Math.pow(1 + this.percent_change, -1);
299
+ }
300
+ let new_result = this.get_bulk_trade_zones({
301
+ current_price: next_focus,
302
+ kind,
303
+ limit
304
+ });
305
+ if (new_result?.length) {
306
+ for (let i of result) {
307
+ let condition = kind === "long" ? (a, b) => a >= b : (a, b) => a <= b;
308
+ let potentials = new_result.filter((x) => condition(x["entry"], i["risk_sell"])).map((x) => x["entry"]);
309
+ if (potentials.length && max_index) {
310
+ if (kind === "long") {
311
+ console.log("slice: ", potentials.slice(0, max_index));
312
+ i["risk_sell"] = Math.max(...potentials.slice(0, max_index));
313
+ } else {
314
+ i["risk_sell"] = Math.min(...potentials.slice(0, max_index));
315
+ }
316
+ i["pnl"] = this.to_df(determine_pnl(i["entry"], i["risk_sell"], i["quantity"], kind));
317
+ }
318
+ }
319
+ }
320
+ }
321
+ this.focus = focus;
322
+ return result;
323
+ }
324
+ get_bulk_trade_zones({
325
+ current_price,
326
+ kind = "long",
327
+ limit = false
328
+ }) {
329
+ const futures = this.get_future_zones({ current_price, kind });
330
+ const original = this.zone_risk;
331
+ if (futures) {
332
+ const values = futures;
333
+ if (values) {
334
+ let trade_zones = values.sort();
335
+ if (this.resistance) {
336
+ trade_zones = trade_zones.filter((x) => this.resistance ? x <= this.resistance : true);
337
+ if (kind === "short") {
338
+ trade_zones = trade_zones.sort((a, b) => b - a);
339
+ }
340
+ }
341
+ if (trade_zones.length > 0) {
342
+ const stop_loss = trade_zones[0];
343
+ const result = this.process_orders({
344
+ current_price,
345
+ stop_loss,
346
+ trade_zones,
347
+ kind
348
+ });
349
+ if (!result.length) {
350
+ if (kind === "long") {
351
+ let m_z = this.get_margin_range(futures[0]);
352
+ if (m_z && m_z[0] < current_price && current_price !== m_z[1]) {
353
+ return this.get_bulk_trade_zones({
354
+ current_price: m_z[1],
355
+ kind,
356
+ limit
357
+ });
358
+ }
359
+ }
360
+ }
361
+ this.zone_risk = original;
362
+ return result;
363
+ }
364
+ }
365
+ }
366
+ this.zone_risk = original;
367
+ }
368
+ get_future_zones({
369
+ current_price,
370
+ kind = "long",
371
+ raw
372
+ }) {
373
+ if (raw) {}
374
+ const margin_range = this.get_margin_range(current_price, kind);
375
+ let margin_zones = this.get_margin_zones({ current_price });
376
+ let remaining_zones = margin_zones.filter((x) => JSON.stringify(x) != JSON.stringify(margin_range));
377
+ if (margin_range) {
378
+ const difference = Math.abs(margin_range[0] - margin_range[1]);
379
+ const spread = to_f(difference / this.risk_reward, this.price_places);
380
+ let entries;
381
+ const percent_change = this.percent_change / this.risk_reward;
382
+ if (kind === "long") {
383
+ entries = Array.from({ length: Math.floor(this.risk_reward) + 1 }, (_, x) => to_f(margin_range[1] - spread * x, this.price_places));
384
+ } else {
385
+ entries = Array.from({ length: Math.floor(this.risk_reward) + 1 }, (_, x) => to_f(margin_range[1] * Math.pow(1 + percent_change, x), this.price_places));
386
+ }
387
+ if (Math.min(...entries) < this.to_f(current_price) && this.to_f(current_price) < Math.max(...entries)) {
388
+ return entries.sort((a, b) => a - b);
389
+ }
390
+ if (remaining_zones.length > 0) {
391
+ let new_range = remaining_zones[0];
392
+ let entries2 = [];
393
+ let x = 0;
394
+ if (new_range) {
395
+ while (entries2.length < this.risk_reward + 1) {
396
+ if (kind === "long") {
397
+ let value = this.to_f(new_range[1] - spread * x);
398
+ if (value <= current_price) {
399
+ entries2.push(value);
400
+ }
401
+ } else {
402
+ let value = this.to_f(new_range[1] * Math.pow(1 + percent_change, x));
403
+ if (value >= current_price) {
404
+ entries2.push(value);
405
+ }
406
+ }
407
+ x += 1;
408
+ }
409
+ }
410
+ return entries2.sort((a, b) => a - b);
411
+ }
412
+ if (remaining_zones.length === 0 && this.to_f(current_price) <= Math.min(...entries)) {
413
+ const next_focus = margin_range[0] * Math.pow(1 + this.percent_change, -1);
414
+ let entries2 = [];
415
+ let x = 0;
416
+ while (entries2.length < this.risk_reward + 1) {
417
+ if (kind === "long") {
418
+ let value = this.to_f(next_focus - spread * x);
419
+ if (value <= this.to_f(current_price)) {
420
+ entries2.push(value);
421
+ }
422
+ } else {
423
+ let value = this.to_f(next_focus * Math.pow(1 + percent_change, x));
424
+ if (value >= this.to_f(current_price)) {
425
+ entries2.push(value);
426
+ }
427
+ }
428
+ x += 1;
429
+ }
430
+ return entries2.sort((a, b) => a - b);
431
+ }
432
+ return entries.sort((a, b) => a - b);
433
+ }
434
+ return [];
435
+ }
436
+ to_f(value, places) {
437
+ return to_f(value, places || this.price_places);
438
+ }
439
+ get_margin_zones({
440
+ current_price,
441
+ kind = "long"
442
+ }) {
443
+ if (this.support && kind === "long") {
444
+ let result = [];
445
+ let start = current_price;
446
+ let counter = 0;
447
+ while (start > this.support) {
448
+ let v = this.get_margin_range(start);
449
+ if (v) {
450
+ result.push(v);
451
+ start = v[0] - this.min_price;
452
+ counter += 1;
453
+ }
454
+ if (counter > 10) {
455
+ break;
456
+ }
457
+ }
458
+ return result;
459
+ }
460
+ if (this.resistance) {
461
+ let result = [];
462
+ let start = current_price;
463
+ let counter = 0;
464
+ while (start < this.resistance) {
465
+ let v = this.get_margin_range(start);
466
+ if (v) {
467
+ result.push(v);
468
+ start = v[1] + this.min_price;
469
+ }
470
+ if (counter > 10) {
471
+ break;
472
+ }
473
+ }
474
+ return result;
475
+ }
476
+ return [this.get_margin_range(current_price)];
477
+ }
478
+ get_margin_range(current_price, kind = "long") {
479
+ const diff = -this.min_price;
480
+ const zones = _get_zones({
481
+ current_price: current_price + diff,
482
+ focus: this.focus,
483
+ percent_change: this.percent_change,
484
+ places: this.price_places
485
+ }) || [];
486
+ const top_zones = [];
487
+ for (const i of zones) {
488
+ if (i < 0.00000001) {
489
+ break;
490
+ }
491
+ top_zones.push(this.to_f(i));
492
+ }
493
+ if (top_zones.length > 0) {
494
+ const result = top_zones[top_zones.length - 1];
495
+ return [this.to_f(result), this.to_f(result * (1 + this.percent_change))];
496
+ }
497
+ return null;
498
+ }
499
+ process_orders({
500
+ current_price,
501
+ stop_loss,
502
+ trade_zones,
503
+ kind = "long"
504
+ }) {
505
+ const number_of_orders = trade_zones.slice(1).length;
506
+ let take_profit = stop_loss * (1 + 2 * this.percent_change);
507
+ if (kind === "short") {
508
+ take_profit = stop_loss * Math.pow(1 + 2 * this.percent_change, -1);
509
+ }
510
+ if (this.take_profit) {
511
+ take_profit = this.take_profit;
512
+ }
513
+ if (number_of_orders > 0) {
514
+ const risk_per_trade = this.get_risk_per_trade(number_of_orders);
515
+ let limit_orders = trade_zones.slice(1).filter((x) => x <= this.to_f(current_price));
516
+ let market_orders = trade_zones.slice(1).filter((x) => x > this.to_f(current_price));
517
+ if (kind === "short") {
518
+ limit_orders = trade_zones.slice(1).filter((x) => x >= this.to_f(current_price));
519
+ market_orders = trade_zones.slice(1).filter((x) => x < this.to_f(current_price));
520
+ }
521
+ if (market_orders.length === 1) {
522
+ limit_orders = limit_orders.concat(market_orders);
523
+ market_orders = [];
524
+ }
525
+ const increase_position = Boolean(this.support) && this.increase_position;
526
+ const market_trades = limit_orders.length > 0 ? market_orders.map((x, i) => {
527
+ const defaultStopLoss = i === 0 ? limit_orders[limit_orders.length - 1] : market_orders[i - 1];
528
+ const y = this.build_trade_dict({
529
+ entry: x,
530
+ stop: increase_position ? this.support : defaultStopLoss,
531
+ risk: risk_per_trade,
532
+ arr: market_orders,
533
+ index: i,
534
+ kind,
535
+ start: market_orders.length + limit_orders.length,
536
+ take_profit
537
+ });
538
+ return y;
539
+ }).filter((y) => y) : [];
540
+ let total_incurred_market_fees = 0;
541
+ if (market_trades.length > 0) {
542
+ let first = market_trades[0];
543
+ if (first) {
544
+ total_incurred_market_fees += first.incurred;
545
+ total_incurred_market_fees += first.fee;
546
+ }
547
+ }
548
+ const default_gap = this.gap;
549
+ const gap_pairs = createGapPairs(limit_orders, default_gap);
550
+ const limit_trades = (limit_orders.map((x, i) => {
551
+ let _base = limit_orders[i - 1];
552
+ let _stops = gap_pairs.find((o) => o[0] === x);
553
+ if (!_stops) {
554
+ return;
555
+ }
556
+ if (_stops) {
557
+ _base = _stops[1];
558
+ }
559
+ const defaultStopLoss = i === 0 ? stop_loss : _base;
560
+ const new_stop = kind === "long" ? this.support : stop_loss;
561
+ const y = this.build_trade_dict({
562
+ entry: x,
563
+ stop: (this.increase_position ? new_stop : defaultStopLoss) || defaultStopLoss,
564
+ risk: risk_per_trade,
565
+ arr: limit_orders,
566
+ index: i,
567
+ new_fees: total_incurred_market_fees,
568
+ kind,
569
+ start: market_orders.length + limit_orders.length,
570
+ take_profit
571
+ });
572
+ if (y) {
573
+ y.new_stop = defaultStopLoss;
574
+ }
575
+ return y !== null ? y : undefined;
576
+ }) || []).filter((y) => y !== undefined).filter((y) => {
577
+ const min_options = [0.001, 0.002, 0.003];
578
+ if (min_options.includes(this.minimum_size)) {
579
+ return y.quantity <= 0.03;
580
+ }
581
+ return true;
582
+ });
583
+ let total_orders = limit_trades.concat(market_trades);
584
+ if (kind === "short") {}
585
+ if (this.minimum_size && total_orders.length > 0) {
586
+ let payload = total_orders;
587
+ let greater_than_min_size = total_orders.filter((o) => o ? o.quantity >= this.minimum_size : true);
588
+ let less_than_min_size = total_orders.filter((o) => o ? o.quantity < this.minimum_size : true) || total_orders;
589
+ less_than_min_size = groupIntoPairsWithSumLessThan(less_than_min_size, this.minimum_size, "quantity", this.first_order_size);
590
+ less_than_min_size = less_than_min_size.map((q, i) => {
591
+ let avg_entry = determine_average_entry_and_size(q.map((o) => ({
592
+ price: o.entry,
593
+ quantity: o.quantity
594
+ })), this.decimal_places, this.price_places);
595
+ let candidate = q[0];
596
+ candidate.entry = avg_entry.price;
597
+ candidate.quantity = avg_entry.quantity;
598
+ return candidate;
599
+ });
600
+ less_than_min_size = less_than_min_size.map((q, i) => {
601
+ let new_stop = q.new_stop;
602
+ if (i > 0) {
603
+ new_stop = less_than_min_size[i - 1].entry;
604
+ }
605
+ return {
606
+ ...q,
607
+ new_stop
608
+ };
609
+ });
610
+ if (greater_than_min_size.length !== total_orders.length) {
611
+ payload = greater_than_min_size.concat(less_than_min_size);
612
+ }
613
+ return payload;
614
+ }
615
+ return total_orders;
616
+ }
617
+ return [];
618
+ }
619
+ get_risk_per_trade(number_of_orders) {
620
+ if (this.risk_per_trade) {
621
+ return this.risk_per_trade;
622
+ }
623
+ return this.zone_risk / number_of_orders;
624
+ }
625
+ build_trade_dict({
626
+ entry,
627
+ stop,
628
+ risk,
629
+ arr,
630
+ index,
631
+ new_fees = 0,
632
+ kind = "long",
633
+ start = 0,
634
+ take_profit
635
+ }) {
636
+ const considered = arr.map((x, i) => i).filter((i) => i > index);
637
+ const with_quantity = considered.map((x) => {
638
+ const q = determine_position_size({
639
+ entry: arr[x],
640
+ stop: arr[x - 1],
641
+ budget: risk,
642
+ places: this.decimal_places
643
+ });
644
+ if (!q) {
645
+ return;
646
+ }
647
+ if (this.minimum_size) {
648
+ if (q < this.minimum_size) {
649
+ return;
650
+ }
651
+ }
652
+ return { quantity: q, entry: arr[x] };
653
+ }).filter((x) => x);
654
+ if (this.increase_size) {
655
+ const arr_length = with_quantity.length;
656
+ with_quantity.forEach((x, i) => {
657
+ if (x) {
658
+ x.quantity = x.quantity * (arr_length - i);
659
+ }
660
+ });
661
+ }
662
+ const fees = with_quantity.map((x) => {
663
+ return this.to_df(this.fee * x.quantity * x.entry);
664
+ });
665
+ const previous_risks = with_quantity.map((x) => {
666
+ return this.to_df(risk);
667
+ });
668
+ const multiplier = start - index;
669
+ const incurred_fees = fees.reduce((a, b) => a + b, 0) + previous_risks.reduce((a, b) => a + b, 0);
670
+ if (index === 0) {}
671
+ let quantity = determine_position_size({
672
+ entry,
673
+ stop,
674
+ budget: risk,
675
+ places: this.decimal_places,
676
+ min_size: this.minimum_size
677
+ });
678
+ if (!quantity) {
679
+ return;
680
+ }
681
+ if (this.increase_size) {
682
+ quantity = quantity * multiplier;
683
+ const new_risk = determine_pnl(entry, stop, quantity, kind);
684
+ risk = Math.abs(new_risk);
685
+ }
686
+ const fee = this.to_df(this.fee * quantity * entry);
687
+ const increment = Math.abs(arr.length - (index + 1));
688
+ let pnl = this.to_df(risk) * (this.risk_reward + increment);
689
+ if (this.minimum_pnl) {
690
+ pnl = this.minimum_pnl + fee;
691
+ }
692
+ let sell_price = determine_close_price({ entry, pnl, quantity, kind });
693
+ if (take_profit && !this.minimum_pnl) {
694
+ sell_price = take_profit;
695
+ pnl = this.to_df(determine_pnl(entry, sell_price, quantity, kind));
696
+ pnl = pnl + fee;
697
+ sell_price = determine_close_price({ entry, pnl, quantity, kind });
698
+ }
699
+ let risk_sell = sell_price;
700
+ return {
701
+ entry,
702
+ risk: this.to_df(risk),
703
+ quantity,
704
+ sell_price: this.to_f(sell_price),
705
+ risk_sell: this.to_f(risk_sell),
706
+ stop,
707
+ pnl,
708
+ fee,
709
+ net: this.to_df(pnl - fee),
710
+ incurred: this.to_df(incurred_fees + new_fees),
711
+ stop_percent: this.to_df(Math.abs(entry - stop) / entry)
712
+ };
713
+ }
714
+ to_df(currentPrice, places = "%.3f") {
715
+ return to_f(currentPrice, places);
716
+ }
717
+ }
718
+
719
+ // src/helpers/pnl.ts
720
+ function determine_position_size2(entry, stop, budget) {
721
+ let stop_percent = Math.abs(entry - stop) / entry;
722
+ let size = budget / stop_percent / entry;
723
+ return size;
724
+ }
725
+ function determine_risk(entry, stop, quantity) {
726
+ let stop_percent = Math.abs(entry - stop) / entry;
727
+ let risk = quantity * stop_percent * entry;
728
+ return risk;
729
+ }
730
+ function determine_close_price2(entry, pnl, quantity, kind, single = false, leverage = 1) {
731
+ const dollar_value = entry / leverage;
732
+ const position = dollar_value * quantity;
733
+ if (position) {
734
+ let percent = pnl / position;
735
+ let difference = position * percent / quantity;
736
+ let result;
737
+ if (kind === "long") {
738
+ result = difference + entry;
739
+ } else {
740
+ result = entry - difference;
741
+ }
742
+ if (single) {
743
+ return result;
744
+ }
745
+ return result;
746
+ }
747
+ return 0;
748
+ }
749
+ function determine_amount_to_sell(entry, quantity, sell_price, pnl, kind, places = "%.3f") {
750
+ const _pnl = determine_pnl2(entry, sell_price, quantity, kind);
751
+ const ratio = pnl / to_f2(Math.abs(_pnl), places);
752
+ quantity = quantity * ratio;
753
+ return to_f2(quantity, places);
754
+ }
755
+ function determine_pnl2(entry, close_price, quantity, kind, contract_size, places = "%.2f") {
756
+ if (contract_size) {
757
+ const direction = kind === "long" ? 1 : -1;
758
+ return quantity * contract_size * direction * (1 / entry - 1 / close_price);
759
+ }
760
+ let difference = entry - close_price;
761
+ if (kind === "long") {
762
+ difference = close_price - entry;
763
+ }
764
+ return to_f2(difference * quantity, places);
765
+ }
766
+ function position(entry, quantity, kind, leverage = 1) {
767
+ const direction = { long: 1, short: -1 };
768
+ return parseFloat((direction[kind] * quantity * (entry / leverage)).toFixed(3));
769
+ }
770
+ function to_f2(value, places) {
771
+ if (value) {
772
+ let pp = parseInt(places.replace("%.", "").replace("f", ""));
773
+ return parseFloat(value.toFixed(pp));
774
+ }
775
+ return value;
776
+ }
777
+ var value = {
778
+ determine_risk,
779
+ determine_position_size: determine_position_size2,
780
+ determine_close_price: determine_close_price2,
781
+ determine_pnl: determine_pnl2,
782
+ position,
783
+ determine_amount_to_sell,
784
+ to_f: to_f2
785
+ };
786
+ var pnl_default = value;
787
+
788
+ // src/helpers/trade_utils.ts
789
+ function profitHelper(longPosition, shortPosition, config, contract_size, balance = 0) {
790
+ let long = { takeProfit: 0, quantity: 0, pnl: 0 };
791
+ let short = { takeProfit: 0, quantity: 0, pnl: 0 };
792
+ if (longPosition) {
793
+ long = config?.getSize2(longPosition, contract_size, balance) || null;
794
+ }
795
+ if (shortPosition) {
796
+ short = config?.getSize2(shortPosition, contract_size, balance) || null;
797
+ }
798
+ return { long, short };
799
+ }
800
+ function getParamForField(self, configs, field, isGroup) {
801
+ if (isGroup === "group" && field === "checkbox") {
802
+ return configs.filter((o) => o.kind === field && o.group === true).map((o) => {
803
+ let _self = self;
804
+ let value2 = _self[o.name];
805
+ return { ...o, value: value2 };
806
+ });
807
+ }
808
+ let r = configs.find((o) => o.name == field);
809
+ if (r) {
810
+ let oo = self;
811
+ let tt = oo[r.name] || "";
812
+ r.value = tt;
813
+ }
814
+ return r;
815
+ }
816
+ function getTradeEntries(entry, min_size, kind, size, spread = 0) {
817
+ let result = [];
818
+ let index = 0;
819
+ let no_of_trades = size > min_size ? Math.round(size / min_size) : 1;
820
+ while (index < no_of_trades) {
821
+ if (kind === "long") {
822
+ result.push({ entry: entry - index * spread, size: min_size });
823
+ } else {
824
+ result.push({ entry: entry + index * spread, size: min_size });
825
+ }
826
+ index = index + 1;
827
+ }
828
+ return result;
829
+ }
830
+ function extractValue(_param, condition) {
831
+ let param;
832
+ if (condition) {
833
+ try {
834
+ let value2 = JSON.parse(_param || "[]");
835
+ param = value2.map((o) => parseFloat(o));
836
+ } catch (error) {}
837
+ } else {
838
+ param = parseFloat(_param);
839
+ }
840
+ return param;
841
+ }
842
+ function asCoins(symbol) {
843
+ let _type = symbol.toLowerCase().includes("usdt") ? "usdt" : "coin";
844
+ if (symbol.toLowerCase() == "btcusdt") {
845
+ _type = "usdt";
846
+ }
847
+ let result = _type === "usdt" ? symbol.toLowerCase().includes("usdt") ? "USDT" : "BUSD" : symbol.toUpperCase().split("USD_")[0];
848
+ if (symbol.toLowerCase().includes("-")) {
849
+ result = result.split("-")[0];
850
+ }
851
+ if (symbol.toLowerCase() == "usdt-usd") {}
852
+ let result2 = _type == "usdt" ? symbol.split(result)[0] : result;
853
+ if (result.includes("-")) {
854
+ result2 = result;
855
+ }
856
+ return result2;
857
+ }
858
+ var SpecialCoins = ["NGN", "USDT", "BUSD", "PAX", "USDC", "EUR"];
859
+ function allCoins(symbols) {
860
+ let r = symbols.map((o, i) => asCoins(o));
861
+ return [...new Set(r), ...SpecialCoins];
862
+ }
863
+ function formatPrice(value2, opts = {}) {
864
+ const { locale = "en-US", currency = "USD" } = opts;
865
+ const formatter = new Intl.NumberFormat(locale, {
866
+ currency,
867
+ style: "currency",
868
+ maximumFractionDigits: 2
869
+ });
870
+ return formatter.format(value2);
871
+ }
872
+ function to_f(value2, places = "%.1f") {
873
+ let v = typeof value2 === "string" ? parseFloat(value2) : value2;
874
+ const formattedValue = places.replace("%.", "").replace("f", "");
875
+ return parseFloat(v.toFixed(parseInt(formattedValue)));
876
+ }
877
+ function determine_stop_and_size(entry, pnl, take_profit, kind = "long") {
878
+ const difference = kind === "long" ? take_profit - entry : entry - take_profit;
879
+ const quantity = pnl / difference;
880
+ return Math.abs(quantity);
881
+ }
882
+ var range = (start, stop, step = 1) => Array.from({ length: (stop - start) / step + 1 }, (_, i) => start + i * step);
883
+ function determine_amount_to_sell2(entry, quantity, sell_price, pnl, kind, places = "%.3f") {
884
+ const _pnl = determine_pnl(entry, sell_price, quantity, kind);
885
+ const ratio = pnl / to_f(Math.abs(_pnl), places);
886
+ quantity = quantity * ratio;
887
+ return to_f(quantity, places);
888
+ }
889
+ function determine_position_size({
890
+ entry,
891
+ stop,
892
+ budget,
893
+ percent,
894
+ min_size,
895
+ notional_value,
896
+ as_coin = true,
897
+ places = "%.3f"
898
+ }) {
899
+ let stop_percent = stop ? Math.abs(entry - stop) / entry : percent;
900
+ if (stop_percent && budget) {
901
+ let size = budget / stop_percent;
902
+ let notion_value = size * entry;
903
+ if (notional_value && notional_value > notion_value) {
904
+ size = notional_value / entry;
905
+ }
906
+ if (as_coin) {
907
+ size = size / entry;
908
+ if (min_size && min_size === 1) {
909
+ return to_f(Math.round(size), places);
910
+ }
911
+ }
912
+ return to_f(size, places);
913
+ }
914
+ return;
915
+ }
916
+ function determine_remaining_entry({
917
+ risk,
918
+ max_size,
919
+ stop_loss,
920
+ kind,
921
+ position: position2
922
+ }) {
923
+ const avg_entry = determine_avg_entry_based_on_max_size({
924
+ risk,
925
+ max_size,
926
+ stop_loss,
927
+ kind
928
+ });
929
+ const result = avg_entry * max_size - position2.quantity * position2.entry;
930
+ return result / (max_size - position2.quantity);
931
+ }
932
+ function determine_avg_entry_based_on_max_size({
933
+ risk,
934
+ max_size,
935
+ stop_loss,
936
+ kind = "long"
937
+ }) {
938
+ const diff = max_size * stop_loss;
939
+ if (kind === "long") {
940
+ return (risk + diff) / max_size;
941
+ }
942
+ return (risk - diff) / max_size;
943
+ }
944
+ function determine_average_entry_and_size(orders, places = "%.3f", price_places = "%.1f") {
945
+ const sum_values = orders.reduce((sum, order) => sum + order.price * order.quantity, 0);
946
+ const total_quantity = orders.reduce((sum, order) => sum + order.quantity, 0);
947
+ const avg_price = total_quantity ? to_f(sum_values / total_quantity, price_places) : 0;
948
+ return {
949
+ entry: avg_price,
950
+ price: avg_price,
951
+ quantity: to_f(total_quantity, places)
952
+ };
953
+ }
954
+ var createArray = (start, stop, step) => {
955
+ const result = [];
956
+ let current = start;
957
+ while (current <= stop) {
958
+ result.push(current);
959
+ current += step;
960
+ }
961
+ return result;
962
+ };
963
+ var groupBy = (xs, key) => {
964
+ return xs.reduce((rv, x) => {
965
+ (rv[x[key]] = rv[x[key]] || []).push(x);
966
+ return rv;
967
+ }, {});
968
+ };
969
+ function fibonacci_analysis({
970
+ support,
971
+ resistance,
972
+ kind = "long",
973
+ trend = "long",
974
+ places = "%.1f"
975
+ }) {
976
+ const swing_high = trend === "long" ? resistance : support;
977
+ const swing_low = trend === "long" ? support : resistance;
978
+ const ranges = [0, 0.236, 0.382, 0.5, 0.618, 0.789, 1, 1.272, 1.414, 1.618];
979
+ const fib_calc = (p, h, l) => p * (h - l) + l;
980
+ const fib_values = ranges.map((x) => fib_calc(x, swing_high, swing_low)).map((x) => to_f(x, places));
981
+ if (kind === "short") {
982
+ return trend === "long" ? fib_values.reverse() : fib_values;
983
+ } else {
984
+ return trend === "short" ? fib_values.reverse() : fib_values;
985
+ }
986
+ return fib_values;
987
+ }
988
+ var groupIntoPairs = (arr, size) => {
989
+ const result = [];
990
+ for (let i = 0;i < arr.length; i += size) {
991
+ result.push(arr.slice(i, i + size));
992
+ }
993
+ return result;
994
+ };
995
+ var groupIntoPairsWithSumLessThan = (arr, targetSum, key = "quantity", firstSize = 0) => {
996
+ if (firstSize) {
997
+ const totalSize = arr.reduce((sum, order) => sum + order[key], 0);
998
+ const remainingSize = totalSize - firstSize;
999
+ let newSum = 0;
1000
+ let newArray = [];
1001
+ let lastIndex = 0;
1002
+ for (let i = 0;i < arr.length; i++) {
1003
+ if (newSum < remainingSize) {
1004
+ newSum += arr[i][key];
1005
+ newArray.push(arr[i]);
1006
+ lastIndex = i;
1007
+ }
1008
+ }
1009
+ const lastGroup = arr.slice(lastIndex + 1);
1010
+ const previousPair = groupInPairs(newArray, key, targetSum);
1011
+ if (lastGroup.length > 0) {
1012
+ previousPair.push(lastGroup);
1013
+ }
1014
+ return previousPair;
1015
+ }
1016
+ return groupInPairs(arr, key, targetSum);
1017
+ };
1018
+ function groupInPairs(_arr, key, targetSum) {
1019
+ const result = [];
1020
+ let currentSum = 0;
1021
+ let currentGroup = [];
1022
+ for (let i = 0;i < _arr.length; i++) {
1023
+ currentSum += _arr[i][key];
1024
+ currentGroup.push(_arr[i]);
1025
+ if (currentSum >= targetSum) {
1026
+ result.push(currentGroup);
1027
+ currentGroup = [];
1028
+ currentSum = 0;
1029
+ }
1030
+ }
1031
+ return result;
1032
+ }
1033
+ var computeTotalAverageForEachTrade = (trades, config) => {
1034
+ let _take_profit = config.take_profit;
1035
+ let kind = config.kind;
1036
+ let entryToUse = kind === "short" ? Math.min(config.entry, config.stop) : Math.max(config.entry, config.stop);
1037
+ let _currentEntry = config.currentEntry || entryToUse;
1038
+ let less = trades.filter((p) => kind === "long" ? p.entry <= _currentEntry : p.entry >= _currentEntry);
1039
+ let rrr = trades.map((r, i) => {
1040
+ let considered = [];
1041
+ if (kind === "long") {
1042
+ considered = trades.filter((p) => p.entry > _currentEntry);
1043
+ } else {
1044
+ considered = trades.filter((p) => p.entry < _currentEntry);
1045
+ }
1046
+ const x_pnl = 0;
1047
+ const remaining = less.filter((o) => {
1048
+ if (kind === "long") {
1049
+ return o.entry >= r.entry;
1050
+ }
1051
+ return o.entry <= r.entry;
1052
+ });
1053
+ if (remaining.length === 0) {
1054
+ return { ...r, pnl: x_pnl };
1055
+ }
1056
+ const start = kind === "long" ? Math.max(...remaining.map((o) => o.entry)) : Math.min(...remaining.map((o) => o.entry));
1057
+ considered = considered.map((o) => ({ ...o, entry: start }));
1058
+ considered = considered.concat(remaining);
1059
+ let avg_entry = determine_average_entry_and_size([
1060
+ ...considered.map((o) => ({
1061
+ price: o.entry,
1062
+ quantity: o.quantity
1063
+ })),
1064
+ {
1065
+ price: _currentEntry,
1066
+ quantity: config.currentQty || 0
1067
+ }
1068
+ ], config.decimal_places, config.price_places);
1069
+ let _pnl = r.pnl;
1070
+ let sell_price = r.sell_price;
1071
+ let entry_pnl = r.pnl;
1072
+ if (_take_profit) {
1073
+ _pnl = pnl_default.determine_pnl(avg_entry.price, _take_profit, avg_entry.quantity, kind);
1074
+ sell_price = _take_profit;
1075
+ entry_pnl = pnl_default.determine_pnl(r.entry, _take_profit, avg_entry.quantity, kind);
1076
+ }
1077
+ const loss = pnl_default.determine_pnl(avg_entry.price, r.stop, avg_entry.quantity, kind);
1078
+ let new_stop = r.new_stop;
1079
+ const entry_loss = pnl_default.determine_pnl(r.entry, new_stop, avg_entry.quantity, kind);
1080
+ let min_profit = 0;
1081
+ let min_entry_profit = 0;
1082
+ if (config.min_profit) {
1083
+ min_profit = pnl_default.determine_close_price(avg_entry.price, config.min_profit, avg_entry.quantity, kind);
1084
+ min_entry_profit = pnl_default.determine_close_price(r.entry, config.min_profit, avg_entry.quantity, kind);
1085
+ }
1086
+ let x_fee = r.fee;
1087
+ if (config.fee) {
1088
+ x_fee = config.fee * r.stop * avg_entry.quantity;
1089
+ }
1090
+ let tp_close = pnl_default.determine_close_price(r.entry, Math.abs(entry_loss) * (config.rr || 1) + x_fee, avg_entry.quantity, kind);
1091
+ return {
1092
+ ...r,
1093
+ x_fee: to_f(x_fee, "%.2f"),
1094
+ avg_entry: avg_entry.price,
1095
+ avg_size: avg_entry.quantity,
1096
+ entry_pnl: to_f(entry_pnl, "%.2f"),
1097
+ entry_loss: to_f(entry_loss, "%.2f"),
1098
+ min_entry_pnl: to_f(min_entry_profit, "%.2f"),
1099
+ pnl: _pnl,
1100
+ neg_pnl: to_f(loss, "%.2f"),
1101
+ sell_price,
1102
+ close_p: to_f(tp_close, "%.2f"),
1103
+ min_pnl: to_f(min_profit, "%.2f"),
1104
+ new_stop
1105
+ };
1106
+ });
1107
+ return rrr;
1108
+ };
1109
+ function getDecimalPlaces(numberString) {
1110
+ let parts = numberString.toString().split(".");
1111
+ if (parts.length == 2) {
1112
+ return parts[1].length;
1113
+ }
1114
+ return 0;
1115
+ }
1116
+ function createGapPairs(arr, gap, item) {
1117
+ if (arr.length === 0) {
1118
+ return [];
1119
+ }
1120
+ const result = [];
1121
+ const firstElement = arr[0];
1122
+ for (let i = arr.length - 1;i >= 0; i--) {
1123
+ const current = arr[i];
1124
+ const gapIndex = i - gap;
1125
+ const pairedElement = gapIndex < 0 ? firstElement : arr[gapIndex];
1126
+ if (current !== pairedElement) {
1127
+ result.push([current, pairedElement]);
1128
+ }
1129
+ }
1130
+ if (item) {
1131
+ let r = result.find((o) => o[0] === item);
1132
+ return r ? [r] : [];
1133
+ }
1134
+ return result;
1135
+ }
1136
+ function logWithLineNumber(...args) {
1137
+ const stack = new Error().stack;
1138
+ const lines = stack?.split(`
1139
+ `).slice(2).map((line) => line.trim());
1140
+ const lineNumber = lines?.[0]?.split(":").pop();
1141
+ console.log(`${lineNumber}:`, ...args);
1142
+ }
1143
+ function computeSellZones(payload) {
1144
+ const { entry, exit, zones = 10 } = payload;
1145
+ const gap = exit / entry;
1146
+ const factor = Math.pow(gap, 1 / zones);
1147
+ const spread = factor - 1;
1148
+ return Array.from({ length: zones }, (_, i) => entry * Math.pow(1 + spread, i));
1149
+ }
1150
+ // src/helpers/shared.ts
1151
+ function buildConfig(app_config, {
1152
+ take_profit,
1153
+ entry,
1154
+ stop,
1155
+ raw_instance,
1156
+ risk,
1157
+ no_of_trades,
1158
+ min_profit = 0,
1159
+ risk_reward,
1160
+ kind,
1161
+ increase,
1162
+ gap,
1163
+ rr = 1,
1164
+ price_places = "%.1f",
1165
+ decimal_places = "%.3f"
1166
+ }) {
1167
+ let fee = app_config.fee / 100;
1168
+ let working_risk = risk || app_config.risk_per_trade;
1169
+ let trade_no = no_of_trades || app_config.risk_reward;
1170
+ const config = {
1171
+ focus: app_config.focus,
1172
+ fee,
1173
+ budget: app_config.budget,
1174
+ risk_reward: risk_reward || trade_no,
1175
+ support: app_config.support,
1176
+ resistance: app_config.resistance,
1177
+ price_places: app_config.price_places || price_places,
1178
+ decimal_places,
1179
+ percent_change: app_config.percent_change / app_config.tradeSplit,
1180
+ risk_per_trade: working_risk,
1181
+ take_profit: take_profit || app_config.take_profit,
1182
+ increase_position: increase,
1183
+ minimum_size: app_config.min_size,
1184
+ entry,
1185
+ stop,
1186
+ kind: app_config.kind,
1187
+ gap,
1188
+ min_profit: min_profit || app_config.min_profit,
1189
+ rr: rr || 1
1190
+ };
1191
+ const instance = new Signal(config);
1192
+ if (raw_instance) {
1193
+ return instance;
1194
+ }
1195
+ if (!stop) {
1196
+ return [];
1197
+ }
1198
+ const condition = (kind === "long" ? entry > app_config.support : entry >= app_config.support) && stop >= app_config.support * 0.999;
1199
+ if (kind === "short") {}
1200
+ const result = entry === stop ? [] : condition ? instance.build_entry({
1201
+ current_price: entry,
1202
+ stop_loss: stop,
1203
+ risk: working_risk,
1204
+ kind: kind || app_config.kind,
1205
+ no_of_trades: trade_no
1206
+ }) || [] : [];
1207
+ return computeTotalAverageForEachTrade(result, config);
1208
+ }
1209
+ function buildAvg({
1210
+ _trades,
1211
+ kind
1212
+ }) {
1213
+ let avg = determine_average_entry_and_size(_trades?.map((r) => ({
1214
+ price: r.entry,
1215
+ quantity: r.quantity
1216
+ })) || []);
1217
+ const stop_prices = _trades.map((o) => o.stop);
1218
+ const stop_loss = kind === "long" ? Math.min(...stop_prices) : Math.max(...stop_prices);
1219
+ avg.pnl = pnl_default.determine_pnl(avg.price, stop_loss, avg.quantity, kind);
1220
+ return avg;
1221
+ }
1222
+ function sortedBuildConfig(app_config, options) {
1223
+ const sorted = buildConfig(app_config, options).sort((a, b) => app_config.kind === "long" ? a.entry - b.entry : b.entry - b.entry).filter((x) => {
1224
+ if (app_config.symbol === "BTCUSDT") {
1225
+ return x.quantity <= 0.03;
1226
+ }
1227
+ if (app_config.symbol?.toLowerCase().startsWith("sol")) {
1228
+ return x.quantity <= 2;
1229
+ }
1230
+ return true;
1231
+ });
1232
+ return sorted.map((k, i) => {
1233
+ const arrSet = sorted.slice(0, i + 1);
1234
+ const avg_values = determine_average_entry_and_size(arrSet.map((u) => ({ price: u.entry, quantity: u.quantity })), app_config.decimal_places, app_config.price_places);
1235
+ return {
1236
+ ...k,
1237
+ reverse_avg_entry: avg_values.price,
1238
+ reverse_avg_quantity: avg_values.quantity
1239
+ };
1240
+ });
1241
+ }
1242
+ function get_app_config_and_max_size(config, payload) {
1243
+ const app_config = {
1244
+ kind: payload.kind,
1245
+ entry: payload.entry,
1246
+ stop: payload.stop,
1247
+ risk_per_trade: config.risk,
1248
+ risk_reward: config.risk_reward || 199,
1249
+ support: to_f(config.support, config.price_places),
1250
+ resistance: to_f(config.resistance, config.price_places),
1251
+ focus: payload.entry,
1252
+ fee: 0,
1253
+ percent_change: config.stop_percent / 100,
1254
+ tradeSplit: 1,
1255
+ gap: 1,
1256
+ min_size: config.min_size,
1257
+ budget: 0,
1258
+ price_places: config.price_places,
1259
+ decimal_places: config.decimal_places,
1260
+ min_profit: config.profit_percent * config.profit / 100,
1261
+ symbol: config.symbol
1262
+ };
1263
+ const initialResult = sortedBuildConfig(app_config, {
1264
+ entry: app_config.entry,
1265
+ stop: app_config.stop,
1266
+ kind: app_config.kind,
1267
+ risk: app_config.risk_per_trade,
1268
+ risk_reward: app_config.risk_reward,
1269
+ increase: true,
1270
+ gap: app_config.gap,
1271
+ price_places: app_config.price_places,
1272
+ decimal_places: app_config.decimal_places
1273
+ });
1274
+ const max_size = initialResult[0]?.avg_size;
1275
+ const last_value = initialResult[0];
1276
+ const entries = initialResult.map((x) => ({
1277
+ entry: x.entry,
1278
+ avg_entry: x.avg_entry,
1279
+ avg_size: x.avg_size,
1280
+ neg_pnl: x.neg_pnl,
1281
+ quantity: x.quantity
1282
+ }));
1283
+ return {
1284
+ app_config,
1285
+ max_size,
1286
+ last_value,
1287
+ entries
1288
+ };
1289
+ }
1290
+ function buildAppConfig(config, payload) {
1291
+ const { app_config, max_size, last_value, entries } = get_app_config_and_max_size({
1292
+ ...config,
1293
+ risk: payload.risk,
1294
+ profit: payload.profit || 500,
1295
+ risk_reward: payload.risk_reward,
1296
+ accounts: [],
1297
+ reduce_percent: 90,
1298
+ reverse_factor: 1,
1299
+ profit_percent: 0,
1300
+ kind: payload.entry > payload.stop ? "long" : "short",
1301
+ symbol: payload.symbol
1302
+ }, {
1303
+ entry: payload.entry,
1304
+ stop: payload.stop,
1305
+ kind: payload.entry > payload.stop ? "long" : "short"
1306
+ });
1307
+ app_config.max_size = max_size;
1308
+ app_config.entry = payload.entry || app_config.entry;
1309
+ app_config.stop = payload.stop || app_config.stop;
1310
+ app_config.last_value = last_value;
1311
+ app_config.entries = entries;
1312
+ return app_config;
1313
+ }
1314
+ function getOptimumStopAndRisk(app_config, params) {
1315
+ const { max_size, target_stop } = params;
1316
+ const isLong = app_config.kind === "long";
1317
+ const stopRange = Math.abs(app_config.entry - target_stop) * 0.5;
1318
+ let low_stop = isLong ? target_stop - stopRange : Math.max(target_stop - stopRange, app_config.entry);
1319
+ let high_stop = isLong ? Math.min(target_stop + stopRange, app_config.entry) : target_stop + stopRange;
1320
+ let optimal_stop = target_stop;
1321
+ let best_stop_result = null;
1322
+ let best_entry_diff = Infinity;
1323
+ console.log(`Finding optimal stop for ${isLong ? "LONG" : "SHORT"} position. Target: ${target_stop}, Search range: ${low_stop} to ${high_stop}`);
1324
+ let iterations = 0;
1325
+ const MAX_ITERATIONS = 50;
1326
+ while (Math.abs(high_stop - low_stop) > 0.1 && iterations < MAX_ITERATIONS) {
1327
+ iterations++;
1328
+ const mid_stop = (low_stop + high_stop) / 2;
1329
+ const result = sortedBuildConfig(app_config, {
1330
+ entry: app_config.entry,
1331
+ stop: mid_stop,
1332
+ kind: app_config.kind,
1333
+ risk: app_config.risk_per_trade,
1334
+ risk_reward: app_config.risk_reward,
1335
+ increase: true,
1336
+ gap: app_config.gap,
1337
+ price_places: app_config.price_places,
1338
+ decimal_places: app_config.decimal_places
1339
+ });
1340
+ if (result.length === 0) {
1341
+ if (isLong) {
1342
+ low_stop = mid_stop;
1343
+ } else {
1344
+ high_stop = mid_stop;
1345
+ }
1346
+ continue;
1347
+ }
1348
+ const first_entry = result[0].entry;
1349
+ const entry_diff = Math.abs(first_entry - target_stop);
1350
+ console.log(`Stop: ${mid_stop.toFixed(2)}, First Entry: ${first_entry.toFixed(2)}, Diff: ${entry_diff.toFixed(2)}`);
1351
+ if (entry_diff < best_entry_diff) {
1352
+ best_entry_diff = entry_diff;
1353
+ optimal_stop = mid_stop;
1354
+ best_stop_result = result;
1355
+ }
1356
+ if (first_entry < target_stop) {
1357
+ if (isLong) {
1358
+ low_stop = mid_stop;
1359
+ } else {
1360
+ low_stop = mid_stop;
1361
+ }
1362
+ } else {
1363
+ if (isLong) {
1364
+ high_stop = mid_stop;
1365
+ } else {
1366
+ high_stop = mid_stop;
1367
+ }
1368
+ }
1369
+ if (entry_diff < 1)
1370
+ break;
1371
+ }
1372
+ console.log(`Found optimal stop: ${optimal_stop.toFixed(2)} that gives first_entry: ${best_stop_result?.[0]?.entry?.toFixed(2)}, difference: ${best_entry_diff.toFixed(2)} after ${iterations} iterations`);
1373
+ let low_risk = 10;
1374
+ let high_risk = params.highest_risk || 2000;
1375
+ let optimal_risk = app_config.risk_per_trade;
1376
+ let best_size_result = best_stop_result;
1377
+ let best_size_diff = Infinity;
1378
+ console.log(`Finding optimal risk_per_trade for size target: ${max_size} (never exceeding it)`);
1379
+ iterations = 0;
1380
+ while (Math.abs(high_risk - low_risk) > 0.1 && iterations < MAX_ITERATIONS) {
1381
+ iterations++;
1382
+ const mid_risk = (low_risk + high_risk) / 2;
1383
+ const result = sortedBuildConfig(app_config, {
1384
+ entry: app_config.entry,
1385
+ stop: optimal_stop,
1386
+ kind: app_config.kind,
1387
+ risk: mid_risk,
1388
+ risk_reward: app_config.risk_reward,
1389
+ increase: true,
1390
+ gap: app_config.gap,
1391
+ price_places: app_config.price_places,
1392
+ decimal_places: app_config.decimal_places
1393
+ });
1394
+ if (result.length === 0) {
1395
+ high_risk = mid_risk;
1396
+ continue;
1397
+ }
1398
+ const first_entry = result[0];
1399
+ const avg_size = first_entry.avg_size;
1400
+ console.log(`Risk: ${mid_risk.toFixed(2)}, Avg Size: ${avg_size.toFixed(4)}, Target: ${max_size}`);
1401
+ if (avg_size <= max_size) {
1402
+ const size_diff = max_size - avg_size;
1403
+ if (size_diff < best_size_diff) {
1404
+ best_size_diff = size_diff;
1405
+ optimal_risk = mid_risk;
1406
+ best_size_result = result;
1407
+ }
1408
+ low_risk = mid_risk;
1409
+ } else {
1410
+ high_risk = mid_risk;
1411
+ }
1412
+ if (best_size_diff < 0.001)
1413
+ break;
1414
+ }
1415
+ console.log(`Found optimal risk_per_trade: ${optimal_risk.toFixed(2)} that gives avg_size: ${best_size_result?.[0]?.avg_size?.toFixed(4)}, difference: ${best_size_diff.toFixed(4)} after ${iterations} iterations`);
1416
+ let final_risk = optimal_risk;
1417
+ let final_result = best_size_result;
1418
+ if (best_size_result?.[0]?.avg_size < max_size) {
1419
+ console.log(`Current avg_size (${best_size_result?.[0].avg_size.toFixed(4)}) is less than target (${max_size}). Increasing risk to reach target...`);
1420
+ let current_risk = optimal_risk;
1421
+ const risk_increment = 5;
1422
+ iterations = 0;
1423
+ while (iterations < MAX_ITERATIONS) {
1424
+ iterations++;
1425
+ current_risk += risk_increment;
1426
+ if (current_risk > 5000)
1427
+ break;
1428
+ const result = sortedBuildConfig(app_config, {
1429
+ entry: app_config.entry,
1430
+ stop: optimal_stop,
1431
+ kind: app_config.kind,
1432
+ risk: current_risk,
1433
+ risk_reward: app_config.risk_reward,
1434
+ increase: true,
1435
+ gap: app_config.gap,
1436
+ price_places: app_config.price_places,
1437
+ decimal_places: app_config.decimal_places
1438
+ });
1439
+ if (result.length === 0)
1440
+ continue;
1441
+ const avg_size = result[0].avg_size;
1442
+ console.log(`Increased Risk: ${current_risk.toFixed(2)}, New Avg Size: ${avg_size.toFixed(4)}`);
1443
+ if (avg_size >= max_size) {
1444
+ final_risk = current_risk;
1445
+ final_result = result;
1446
+ console.log(`Target size reached! Final risk: ${final_risk.toFixed(2)}, Final avg_size: ${avg_size.toFixed(4)}`);
1447
+ break;
1448
+ }
1449
+ }
1450
+ }
1451
+ return {
1452
+ optimal_stop: to_f(optimal_stop, app_config.price_places),
1453
+ optimal_risk: to_f(final_risk, app_config.price_places),
1454
+ avg_size: final_result?.[0]?.avg_size || 0,
1455
+ avg_entry: final_result?.[0]?.avg_entry || 0,
1456
+ result: final_result,
1457
+ first_entry: final_result?.[0]?.entry || 0,
1458
+ neg_pnl: final_result?.[0]?.neg_pnl || 0,
1459
+ risk_reward: app_config.risk_reward,
1460
+ size_diff: Math.abs((final_result?.[0]?.avg_size || 0) - max_size),
1461
+ entry_diff: best_entry_diff
1462
+ };
1463
+ }
1464
+ function generate_config_params(app_config, payload) {
1465
+ const { result, ...optimum } = getOptimumStopAndRisk(app_config, {
1466
+ max_size: app_config.max_size,
1467
+ highest_risk: payload.risk * 2,
1468
+ target_stop: app_config.stop
1469
+ });
1470
+ return {
1471
+ entry: payload.entry,
1472
+ stop: optimum.optimal_stop,
1473
+ avg_size: optimum.avg_size,
1474
+ avg_entry: optimum.avg_entry,
1475
+ risk_reward: payload.risk_reward,
1476
+ neg_pnl: optimum.neg_pnl,
1477
+ risk: payload.risk
1478
+ };
1479
+ }
1480
+ function determine_break_even_price(payload) {
1481
+ const { long_position, short_position, fee_percent = 0.05 / 100 } = payload;
1482
+ const long_notional = long_position.entry * long_position.quantity;
1483
+ const short_notional = short_position.entry * short_position.quantity;
1484
+ const net_quantity = long_position.quantity - short_position.quantity;
1485
+ const net_capital = Math.abs(long_notional - short_notional);
1486
+ const break_even_price = net_capital / (Math.abs(net_quantity) + fee_percent * Math.abs(net_quantity));
1487
+ return {
1488
+ price: break_even_price,
1489
+ direction: net_quantity > 0 ? "long" : "short"
1490
+ };
1491
+ }
1492
+ function determine_amount_to_buy(payload) {
1493
+ const {
1494
+ orders,
1495
+ kind,
1496
+ decimal_places = "%.3f",
1497
+ position: position2,
1498
+ existingOrders
1499
+ } = payload;
1500
+ const totalQuantity = orders.reduce((sum, order) => sum + (order.quantity || 0), 0);
1501
+ let runningTotal = to_f(totalQuantity, decimal_places);
1502
+ let sortedOrders = [...orders].sort((a, b) => (a.entry || 0) - (b.entry || 0));
1503
+ if (kind === "short") {
1504
+ sortedOrders.reverse();
1505
+ }
1506
+ const withCumulative = [];
1507
+ for (const order of sortedOrders) {
1508
+ withCumulative.push({
1509
+ ...order,
1510
+ cumulative_quantity: runningTotal
1511
+ });
1512
+ runningTotal -= order.quantity;
1513
+ runningTotal = to_f(runningTotal, decimal_places);
1514
+ }
1515
+ let filteredOrders = withCumulative.filter((order) => (order.cumulative_quantity || 0) > position2?.quantity).map((order) => ({
1516
+ ...order,
1517
+ price: order.entry,
1518
+ kind,
1519
+ side: kind.toLowerCase() === "long" ? "buy" : "sell"
1520
+ }));
1521
+ filteredOrders = filteredOrders.filter((k) => !existingOrders.map((j) => j.price).includes(k.price));
1522
+ return filteredOrders;
1523
+ }
1524
+ function generateOptimumAppConfig(config, payload, position2) {
1525
+ let low_risk = payload.start_risk;
1526
+ let high_risk = payload.max_risk || 50000;
1527
+ let best_risk = null;
1528
+ let best_app_config = null;
1529
+ const tolerance = 0.1;
1530
+ const max_iterations = 150;
1531
+ let iterations = 0;
1532
+ while (high_risk - low_risk > tolerance && iterations < max_iterations) {
1533
+ iterations++;
1534
+ const mid_risk = (low_risk + high_risk) / 2;
1535
+ const {
1536
+ app_config: current_app_config,
1537
+ max_size,
1538
+ last_value,
1539
+ entries
1540
+ } = get_app_config_and_max_size({
1541
+ ...config,
1542
+ risk: mid_risk,
1543
+ profit_percent: config.profit_percent || 0,
1544
+ profit: config.profit || 500,
1545
+ risk_reward: payload.risk_reward,
1546
+ kind: position2.kind,
1547
+ price_places: config.price_places,
1548
+ decimal_places: config.decimal_places,
1549
+ accounts: config.accounts || [],
1550
+ reduce_percent: config.reduce_percent || 90,
1551
+ reverse_factor: config.reverse_factor || 1,
1552
+ symbol: config.symbol || "",
1553
+ support: config.support || 0,
1554
+ resistance: config.resistance || 0,
1555
+ min_size: config.min_size || 0,
1556
+ stop_percent: config.stop_percent || 0
1557
+ }, {
1558
+ entry: payload.entry,
1559
+ stop: payload.stop,
1560
+ kind: position2.kind
1561
+ });
1562
+ current_app_config.max_size = max_size;
1563
+ current_app_config.last_value = last_value;
1564
+ current_app_config.entries = entries;
1565
+ current_app_config.risk_reward = payload.risk_reward;
1566
+ const full_trades = sortedBuildConfig(current_app_config, {
1567
+ entry: current_app_config.entry,
1568
+ stop: current_app_config.stop,
1569
+ kind: current_app_config.kind,
1570
+ risk: current_app_config.risk_per_trade,
1571
+ risk_reward: current_app_config.risk_reward,
1572
+ increase: true,
1573
+ gap: current_app_config.gap,
1574
+ price_places: current_app_config.price_places,
1575
+ decimal_places: current_app_config.decimal_places
1576
+ });
1577
+ if (full_trades.length === 0) {
1578
+ high_risk = mid_risk;
1579
+ continue;
1580
+ }
1581
+ const trades = determine_amount_to_buy({
1582
+ orders: full_trades,
1583
+ kind: position2.kind,
1584
+ decimal_places: current_app_config.decimal_places,
1585
+ price_places: current_app_config.price_places,
1586
+ position: position2,
1587
+ existingOrders: []
1588
+ });
1589
+ if (trades.length === 0) {
1590
+ low_risk = mid_risk;
1591
+ continue;
1592
+ }
1593
+ const last_trade = trades[trades.length - 1];
1594
+ const last_entry = last_trade.entry;
1595
+ if (position2.kind === "long") {
1596
+ if (last_entry > position2.entry) {
1597
+ high_risk = mid_risk;
1598
+ } else {
1599
+ best_risk = mid_risk;
1600
+ best_app_config = current_app_config;
1601
+ low_risk = mid_risk;
1602
+ }
1603
+ } else {
1604
+ if (last_entry < position2.entry) {
1605
+ high_risk = mid_risk;
1606
+ } else {
1607
+ best_risk = mid_risk;
1608
+ best_app_config = current_app_config;
1609
+ low_risk = mid_risk;
1610
+ }
1611
+ }
1612
+ }
1613
+ if (iterations >= max_iterations) {
1614
+ console.warn(`generateAppConfig: Reached max iterations (${max_iterations}) without converging. Returning best found result.`);
1615
+ } else if (best_app_config) {
1616
+ console.log(`Search finished. Best Risk: ${best_risk?.toFixed(2)}, Final Last Entry: ${best_app_config.last_value?.entry?.toFixed(4)}`);
1617
+ } else {
1618
+ console.warn(`generateAppConfig: Could not find a valid risk configuration.`);
1619
+ }
1620
+ if (!best_app_config) {
1621
+ return null;
1622
+ }
1623
+ best_app_config.entries = determine_amount_to_buy({
1624
+ orders: best_app_config.entries,
1625
+ kind: position2.kind,
1626
+ decimal_places: best_app_config.decimal_places,
1627
+ price_places: best_app_config.price_places,
1628
+ position: position2,
1629
+ existingOrders: []
1630
+ });
1631
+ return best_app_config;
1632
+ }
1633
+ function determineOptimumReward(app_config, increase = true, low_range = 30, high_range = 199) {
1634
+ const criterion = app_config.strategy || "quantity";
1635
+ const risk_rewards = createArray(low_range, high_range, 1);
1636
+ let func = risk_rewards.map((trade_no) => {
1637
+ let trades = sortedBuildConfig(app_config, {
1638
+ take_profit: app_config.take_profit,
1639
+ entry: app_config.entry,
1640
+ stop: app_config.stop,
1641
+ no_of_trades: trade_no,
1642
+ risk_reward: trade_no,
1643
+ increase,
1644
+ kind: app_config.kind,
1645
+ gap: app_config.gap,
1646
+ decimal_places: app_config.decimal_places
1647
+ });
1648
+ let total = 0;
1649
+ let max = -Infinity;
1650
+ let min = Infinity;
1651
+ let neg_pnl = trades[0]?.neg_pnl || 0;
1652
+ let entry = trades.at(-1)?.entry;
1653
+ if (!entry) {
1654
+ return null;
1655
+ }
1656
+ for (let trade of trades) {
1657
+ total += trade.quantity;
1658
+ max = Math.max(max, trade.quantity);
1659
+ min = Math.min(min, trade.quantity);
1660
+ entry = app_config.kind === "long" ? Math.max(entry, trade.entry) : Math.min(entry, trade.entry);
1661
+ }
1662
+ return {
1663
+ result: trades,
1664
+ value: trade_no,
1665
+ total,
1666
+ risk_per_trade: app_config.risk_per_trade,
1667
+ max,
1668
+ min,
1669
+ neg_pnl,
1670
+ entry
1671
+ };
1672
+ });
1673
+ func = func.filter((r) => Boolean(r)).filter((r) => {
1674
+ let foundIndex = r?.result.findIndex((e) => e.quantity === r.max);
1675
+ return criterion === "quantity" ? foundIndex === 0 : true;
1676
+ });
1677
+ const highest = criterion === "quantity" ? Math.max(...func.map((o) => o.max)) : Math.min(...func.map((o) => o.entry));
1678
+ const key = criterion === "quantity" ? "max" : "entry";
1679
+ const index = findIndexByCondition(func, app_config.kind, (x) => x[key] == highest, criterion);
1680
+ if (app_config.raw) {
1681
+ return func[index];
1682
+ }
1683
+ return func[index]?.value;
1684
+ }
1685
+ function findIndexByCondition(lst, kind, condition, defaultKey = "neg_pnl") {
1686
+ const found = [];
1687
+ let max_new_diff = 0;
1688
+ let new_lst = lst.map((i, j) => ({
1689
+ ...i,
1690
+ net_diff: lst[j].neg_pnl + lst[j].risk_per_trade
1691
+ }));
1692
+ new_lst.forEach((item, index) => {
1693
+ if (item.net_diff > 0) {
1694
+ found.push(index);
1695
+ }
1696
+ });
1697
+ if (found.length === 0) {
1698
+ max_new_diff = Math.max(...new_lst.map((e) => e.net_diff));
1699
+ found.push(new_lst.findIndex((e) => e.net_diff === max_new_diff));
1700
+ }
1701
+ const sortedFound = found.map((o, index) => ({ ...new_lst[o], index: o })).filter((j) => max_new_diff === 0 ? j.net_diff > 0 : j.net_diff >= max_new_diff).sort((a, b) => {
1702
+ if (a.total !== b.total) {
1703
+ return b.total - a.total;
1704
+ return b.net_diff - a.net_diff;
1705
+ return a.net_diff - b.net_diff;
1706
+ } else {
1707
+ return b.net_diff - a.net_diff;
1708
+ }
1709
+ });
1710
+ console.log("found", sortedFound);
1711
+ if (defaultKey === "quantity") {
1712
+ return sortedFound[0].index;
1713
+ }
1714
+ if (found.length === 1) {
1715
+ return found[0];
1716
+ }
1717
+ if (found.length === 0) {
1718
+ return -1;
1719
+ }
1720
+ const entryCondition = (a, b) => {
1721
+ if (kind == "long") {
1722
+ return a.entry > b.entry;
1723
+ }
1724
+ return a.entry < b.entry;
1725
+ };
1726
+ const maximum = found.reduce((maxIndex, currentIndex) => {
1727
+ return new_lst[currentIndex]["net_diff"] < new_lst[maxIndex]["net_diff"] && entryCondition(new_lst[currentIndex], new_lst[maxIndex]) ? currentIndex : maxIndex;
1728
+ }, found[0]);
1729
+ return maximum;
1730
+ }
1731
+ function computeRiskReward(payload) {
1732
+ const { app_config, entry, stop, risk_per_trade } = payload;
1733
+ const kind = entry > stop ? "long" : "short";
1734
+ app_config.kind = kind;
1735
+ app_config.entry = entry;
1736
+ app_config.stop = stop;
1737
+ app_config.risk_per_trade = risk_per_trade;
1738
+ const result = determineOptimumReward(app_config);
1739
+ return result;
1740
+ }
1741
+ function getRiskReward(payload) {
1742
+ const { entry, stop, risk, global_config } = payload;
1743
+ const { entries, last_value, ...app_config } = buildAppConfig(global_config, {
1744
+ entry,
1745
+ stop,
1746
+ risk_reward: 30,
1747
+ risk,
1748
+ symbol: global_config.symbol
1749
+ });
1750
+ const risk_reward = computeRiskReward({
1751
+ app_config,
1752
+ entry,
1753
+ stop,
1754
+ risk_per_trade: risk
1755
+ });
1756
+ return risk_reward;
1757
+ }
1758
+ function computeProfitDetail(payload) {
1759
+ const {
1760
+ focus_position,
1761
+ strategy,
1762
+ price_places = "%.1f",
1763
+ reduce_position,
1764
+ decimal_places,
1765
+ reverse_position
1766
+ } = payload;
1767
+ let reward_factor = strategy.reward_factor;
1768
+ let risk = strategy.risk;
1769
+ if (strategy.max_reward_factor === 0) {
1770
+ reward_factor = strategy.reward_factor;
1771
+ }
1772
+ if (focus_position.avg_qty >= focus_position.quantity && strategy.max_reward_factor) {
1773
+ reward_factor = to_f(focus_position.quantity * strategy.max_reward_factor / focus_position.avg_qty, "%.4f");
1774
+ } else {
1775
+ reward_factor = strategy.reward_factor;
1776
+ }
1777
+ const full_pnl = reward_factor * risk;
1778
+ const profit_percent = to_f(full_pnl * 100 / (focus_position.avg_price * focus_position.avg_qty), "%.4f");
1779
+ const pnl = to_f(focus_position.entry * focus_position.quantity * profit_percent / 100, "%.2f");
1780
+ const diff = pnl / focus_position.quantity;
1781
+ const sell_price = to_f(focus_position.kind === "long" ? focus_position.entry + diff : focus_position.entry - diff, price_places);
1782
+ let loss = 0;
1783
+ let expected_loss = 0;
1784
+ let quantity = 0;
1785
+ let new_pnl = pnl;
1786
+ if (reduce_position) {
1787
+ loss = Math.abs(reduce_position.entry - sell_price) * reduce_position.quantity;
1788
+ const ratio = pnl / loss;
1789
+ quantity = to_f(reduce_position.quantity * ratio, decimal_places);
1790
+ }
1791
+ if (reverse_position) {
1792
+ expected_loss = Math.abs(reverse_position.avg_price - sell_price) * reverse_position.avg_qty;
1793
+ new_pnl = to_f(pnl - expected_loss, "%.2f");
1794
+ }
1795
+ return {
1796
+ pnl: new_pnl,
1797
+ loss: to_f(expected_loss, "%.2f"),
1798
+ original_pnl: pnl,
1799
+ reward_factor,
1800
+ profit_percent,
1801
+ kind: focus_position.kind,
1802
+ sell_price: to_f(sell_price, price_places),
1803
+ quantity,
1804
+ price_places,
1805
+ decimal_places
1806
+ };
1807
+ }
1808
+ function generateGapTp(payload) {
1809
+ const {
1810
+ long,
1811
+ short,
1812
+ factor = 1,
1813
+ sell_factor = 1,
1814
+ price_places = "%.1f",
1815
+ decimal_places = "%.3f"
1816
+ } = payload;
1817
+ const gap = Math.abs(long.entry - short.entry);
1818
+ const max_quantity = Math.max(long.quantity, short.quantity);
1819
+ const gapLoss = gap * max_quantity;
1820
+ const longPercent = gapLoss * factor / (short.entry * short.quantity);
1821
+ const shortPercent = gapLoss * factor / (long.entry * long.quantity);
1822
+ const longTp = to_f((1 + longPercent) * long.entry, price_places);
1823
+ const shortTp = to_f((1 + shortPercent) ** -1 * short.entry, price_places);
1824
+ const shortToReduce = to_f(Math.abs(longTp - long.entry) * long.quantity, "%.1f");
1825
+ const longToReduce = to_f(Math.abs(shortTp - short.entry) * short.quantity, "%.1f");
1826
+ const actualShortReduce = to_f(shortToReduce * sell_factor, "%.1f");
1827
+ const actualLongReduce = to_f(longToReduce * sell_factor, "%.1f");
1828
+ const short_quantity_to_sell = determine_amount_to_sell2(short.entry, short.quantity, longTp, actualShortReduce, "short", decimal_places);
1829
+ const long_quantity_to_sell = determine_amount_to_sell2(long.entry, long.quantity, shortTp, longToReduce, "long", decimal_places);
1830
+ const risk_amount_short = to_f(shortToReduce - actualShortReduce, "%.2f");
1831
+ const risk_amount_long = to_f(longToReduce - actualLongReduce, "%.2f");
1832
+ const profit_percent_long = to_f(shortToReduce * 100 / (long.entry * long.quantity), "%.4f");
1833
+ const profit_percent_short = to_f(longToReduce * 100 / (short.entry * short.quantity), "%.4f");
1834
+ return {
1835
+ profit_percent: {
1836
+ long: profit_percent_long,
1837
+ short: profit_percent_short
1838
+ },
1839
+ risk: {
1840
+ short: risk_amount_short,
1841
+ long: risk_amount_long
1842
+ },
1843
+ take_profit: {
1844
+ long: longTp,
1845
+ short: shortTp
1846
+ },
1847
+ to_reduce: {
1848
+ short: actualShortReduce,
1849
+ long: actualLongReduce
1850
+ },
1851
+ full_reduce: {
1852
+ short: shortToReduce,
1853
+ long: longToReduce
1854
+ },
1855
+ sell_quantity: {
1856
+ short: short_quantity_to_sell,
1857
+ long: long_quantity_to_sell
1858
+ },
1859
+ gap: to_f(gap, price_places),
1860
+ gap_loss: to_f(gapLoss, "%.2f")
1861
+ };
1862
+ }
1863
+ // src/helpers/strategy.ts
1864
+ class Strategy {
1865
+ position;
1866
+ dominant_position = "long";
1867
+ config;
1868
+ constructor(payload) {
1869
+ this.position = {
1870
+ long: payload.long,
1871
+ short: payload.short
1872
+ };
1873
+ this.dominant_position = payload.dominant_position || "long";
1874
+ this.config = payload.config;
1875
+ if (!this.config.fee_percent) {
1876
+ this.config.fee_percent = 0.05;
1877
+ }
1878
+ }
1879
+ get price_places() {
1880
+ return this.config.global_config.price_places;
1881
+ }
1882
+ get decimal_places() {
1883
+ return this.config.global_config.decimal_places;
1884
+ }
1885
+ to_f(price) {
1886
+ return to_f(price, this.price_places);
1887
+ }
1888
+ to_df(quantity) {
1889
+ return to_f(quantity, this.decimal_places);
1890
+ }
1891
+ pnl(kind, _position) {
1892
+ const position2 = _position || this.position[kind];
1893
+ const { entry, quantity } = position2;
1894
+ const notional = entry * quantity;
1895
+ let tp_percent = this.config.tp_percent;
1896
+ if (kind == "short") {
1897
+ tp_percent = tp_percent * this.config.short_tp_factor;
1898
+ }
1899
+ const profit = notional * (tp_percent / 100);
1900
+ return this.to_f(profit);
1901
+ }
1902
+ tp(kind) {
1903
+ let position2 = this.position[kind];
1904
+ if (position2.quantity == 0) {
1905
+ const reverse_kind = kind == "long" ? "short" : "long";
1906
+ position2 = this.position[reverse_kind];
1907
+ }
1908
+ const { entry, quantity } = position2;
1909
+ const profit = this.pnl(kind, position2);
1910
+ const diff = profit / (quantity || 1);
1911
+ return this.to_f(kind == "long" ? entry + diff : entry - diff);
1912
+ }
1913
+ calculate_fee(position2) {
1914
+ const { price, quantity } = position2;
1915
+ const fee = price * quantity * this.config.fee_percent / 100;
1916
+ return this.to_f(fee);
1917
+ }
1918
+ get long_tp() {
1919
+ return this.tp("long");
1920
+ }
1921
+ get short_tp() {
1922
+ return this.tp("short");
1923
+ }
1924
+ generateGapClosingAlgorithm(payload) {
1925
+ const {
1926
+ kind,
1927
+ ignore_entries = false,
1928
+ reduce_ratio = 1,
1929
+ sell_factor = 1
1930
+ } = payload;
1931
+ const { entry, quantity } = this.position[kind];
1932
+ const focus_position = this.position[kind];
1933
+ const reverse_kind = kind == "long" ? "short" : "long";
1934
+ const reverse_position = this.position[reverse_kind];
1935
+ let _entry = this.tp(kind);
1936
+ let _stop = this.tp(reverse_kind);
1937
+ const second_payload = {
1938
+ entry: _entry,
1939
+ stop: _stop,
1940
+ risk_reward: this.config.risk_reward,
1941
+ start_risk: this.pnl(reverse_kind),
1942
+ max_risk: this.config.budget
1943
+ };
1944
+ const third_payload = {
1945
+ entry,
1946
+ quantity,
1947
+ kind
1948
+ };
1949
+ const app_config = generateOptimumAppConfig(this.config.global_config, second_payload, third_payload);
1950
+ let entries = [];
1951
+ let risk_per_trade = this.config.budget;
1952
+ let last_value = null;
1953
+ if (app_config) {
1954
+ let { entries: _entries, ...rest } = app_config;
1955
+ entries = _entries;
1956
+ risk_per_trade = rest.risk_per_trade;
1957
+ last_value = rest.last_value;
1958
+ if (ignore_entries) {
1959
+ entries = [];
1960
+ }
1961
+ console.log({ app_config });
1962
+ }
1963
+ const risk = this.to_f(risk_per_trade);
1964
+ let below_reverse_entries = kind === "long" ? entries.filter((u) => {
1965
+ return u.entry < (reverse_position.entry || focus_position.entry);
1966
+ }) : entries.filter((u) => {
1967
+ return u.entry > (reverse_position.entry || focus_position.entry);
1968
+ });
1969
+ const threshold = below_reverse_entries.at(-1);
1970
+ const result = this.gapCloserHelper({
1971
+ risk,
1972
+ entries,
1973
+ kind,
1974
+ sell_factor,
1975
+ reduce_ratio
1976
+ });
1977
+ return {
1978
+ ...result,
1979
+ last_entry: last_value?.entry,
1980
+ first_entry: entries.at(-1)?.entry,
1981
+ threshold
1982
+ };
1983
+ }
1984
+ gapCloserHelper(payload) {
1985
+ const {
1986
+ risk,
1987
+ entries = [],
1988
+ kind,
1989
+ sell_factor = 1,
1990
+ reduce_ratio = 1
1991
+ } = payload;
1992
+ const { entry, quantity } = this.position[kind];
1993
+ const focus_position = this.position[kind];
1994
+ const reverse_kind = kind == "long" ? "short" : "long";
1995
+ const reverse_position = this.position[reverse_kind];
1996
+ let _entry = this.tp(kind);
1997
+ let _stop = this.tp(reverse_kind);
1998
+ const second_payload = {
1999
+ entry: _entry,
2000
+ stop: _stop,
2001
+ risk_reward: this.config.risk_reward,
2002
+ start_risk: this.pnl(reverse_kind),
2003
+ max_risk: this.config.budget
2004
+ };
2005
+ const adjusted_focus_entries = entries.map((entry2) => {
2006
+ let adjusted_price = entry2.price;
2007
+ if (focus_position.quantity > 0) {
2008
+ if (kind === "long" && entry2.price >= focus_position.entry) {
2009
+ adjusted_price = focus_position.entry;
2010
+ } else if (kind === "short" && entry2.price <= focus_position.entry) {
2011
+ adjusted_price = focus_position.entry;
2012
+ }
2013
+ }
2014
+ return {
2015
+ price: adjusted_price,
2016
+ quantity: entry2.quantity
2017
+ };
2018
+ });
2019
+ const avg = determine_average_entry_and_size(adjusted_focus_entries.concat([
2020
+ {
2021
+ price: entry,
2022
+ quantity
2023
+ }
2024
+ ]), this.config.global_config.decimal_places, this.config.global_config.price_places);
2025
+ const focus_loss = this.to_f(Math.abs(avg.price - second_payload.stop) * avg.quantity);
2026
+ let below_reverse_entries = kind === "long" ? entries.filter((u) => {
2027
+ return u.entry < (reverse_position.entry || focus_position.entry);
2028
+ }) : entries.filter((u) => {
2029
+ return u.entry > (reverse_position.entry || focus_position.entry);
2030
+ });
2031
+ const threshold = below_reverse_entries.at(-1);
2032
+ let adjusted_reverse_entries = entries.map((entry2) => {
2033
+ let adjusted_price = entry2.price;
2034
+ if (threshold) {
2035
+ if (reverse_kind === "short" && entry2.price > threshold.entry) {
2036
+ adjusted_price = threshold.entry;
2037
+ } else if (reverse_kind === "long" && entry2.price < threshold.entry) {
2038
+ adjusted_price = threshold.entry;
2039
+ }
2040
+ }
2041
+ return {
2042
+ price: adjusted_price,
2043
+ quantity: entry2.quantity
2044
+ };
2045
+ });
2046
+ const reverse_avg = determine_average_entry_and_size(adjusted_reverse_entries.concat([
2047
+ {
2048
+ price: reverse_position.entry,
2049
+ quantity: reverse_position.quantity
2050
+ }
2051
+ ]), this.config.global_config.decimal_places, this.config.global_config.price_places);
2052
+ const sell_quantity = this.to_df(reverse_avg.quantity * sell_factor);
2053
+ const reverse_pnl = this.to_f(Math.abs(reverse_avg.price - second_payload.stop) * sell_quantity);
2054
+ const fee_to_pay = this.calculate_fee({
2055
+ price: avg.entry,
2056
+ quantity: avg.quantity
2057
+ }) + this.calculate_fee({
2058
+ price: reverse_avg.entry,
2059
+ quantity: sell_quantity
2060
+ });
2061
+ const net_reverse_pnl = reverse_pnl - fee_to_pay;
2062
+ const ratio = net_reverse_pnl * reduce_ratio / focus_loss;
2063
+ const quantity_to_sell = this.to_df(ratio * avg.quantity);
2064
+ const remaining_quantity = this.to_df(avg.quantity - quantity_to_sell);
2065
+ const incurred_loss = this.to_f((avg.price - second_payload.stop) * quantity_to_sell);
2066
+ return {
2067
+ risk,
2068
+ risk_reward: this.config.risk_reward,
2069
+ [kind]: {
2070
+ avg_entry: avg.entry,
2071
+ avg_size: avg.quantity,
2072
+ loss: focus_loss,
2073
+ stop: second_payload.stop,
2074
+ stop_quantity: quantity_to_sell,
2075
+ re_entry_quantity: remaining_quantity,
2076
+ initial_pnl: this.pnl(kind),
2077
+ tp: second_payload.entry,
2078
+ incurred_loss
2079
+ },
2080
+ [reverse_kind]: {
2081
+ avg_entry: reverse_avg.entry,
2082
+ avg_size: reverse_avg.quantity,
2083
+ pnl: reverse_pnl,
2084
+ tp: second_payload.stop,
2085
+ re_entry_quantity: remaining_quantity,
2086
+ initial_pnl: this.pnl(reverse_kind),
2087
+ remaining_quantity: this.to_df(reverse_avg.quantity - sell_quantity)
2088
+ },
2089
+ spread: Math.abs(avg.entry - reverse_avg.entry),
2090
+ gap_loss: to_f(Math.abs(avg.entry - reverse_avg.entry) * reverse_avg.quantity, "%.2f"),
2091
+ net_profit: incurred_loss + reverse_pnl
2092
+ };
2093
+ }
2094
+ runIterations(payload) {
2095
+ const {
2096
+ kind,
2097
+ iterations,
2098
+ ignore_entries = false,
2099
+ reduce_ratio = 1,
2100
+ sell_factor = 1
2101
+ } = payload;
2102
+ const reverse_kind = kind == "long" ? "short" : "long";
2103
+ const result = [];
2104
+ let position2 = {
2105
+ long: this.position.long,
2106
+ short: this.position.short
2107
+ };
2108
+ let tp_percent_multiplier = 1;
2109
+ let short_tp_factor_multiplier = 1;
2110
+ for (let i = 0;i < iterations; i++) {
2111
+ const instance = new Strategy({
2112
+ long: position2.long,
2113
+ short: position2.short,
2114
+ config: {
2115
+ ...this.config,
2116
+ tp_percent: this.config.tp_percent * tp_percent_multiplier,
2117
+ short_tp_factor: this.config.short_tp_factor * short_tp_factor_multiplier
2118
+ }
2119
+ });
2120
+ const algorithm = instance.generateGapClosingAlgorithm({
2121
+ kind,
2122
+ ignore_entries,
2123
+ reduce_ratio,
2124
+ sell_factor
2125
+ });
2126
+ if (!algorithm) {
2127
+ console.log("No algorithm found");
2128
+ return result;
2129
+ break;
2130
+ }
2131
+ result.push(algorithm);
2132
+ position2[kind] = {
2133
+ entry: algorithm[kind].avg_entry,
2134
+ quantity: algorithm[kind].re_entry_quantity
2135
+ };
2136
+ let reverse_entry = algorithm[reverse_kind].tp;
2137
+ let reverse_quantity = algorithm[reverse_kind].re_entry_quantity;
2138
+ if (algorithm[reverse_kind].remaining_quantity > 0) {
2139
+ const purchase_to_occur = {
2140
+ price: reverse_entry,
2141
+ quantity: algorithm[reverse_kind].remaining_quantity
2142
+ };
2143
+ const avg = determine_average_entry_and_size([
2144
+ purchase_to_occur,
2145
+ {
2146
+ price: algorithm[reverse_kind].avg_entry,
2147
+ quantity: reverse_quantity - algorithm[reverse_kind].remaining_quantity
2148
+ }
2149
+ ], this.config.global_config.decimal_places, this.config.global_config.price_places);
2150
+ reverse_entry = avg.entry;
2151
+ reverse_quantity = avg.quantity;
2152
+ if (reverse_kind === "short") {
2153
+ short_tp_factor_multiplier = 2;
2154
+ } else {
2155
+ tp_percent_multiplier = 2;
2156
+ }
2157
+ }
2158
+ position2[reverse_kind] = {
2159
+ entry: reverse_entry,
2160
+ quantity: reverse_quantity
2161
+ };
2162
+ }
2163
+ return result;
2164
+ }
2165
+ getPositionAfterTp(payload) {
2166
+ const { kind, include_fees = false } = payload;
2167
+ const focus_position = this.position[kind];
2168
+ const reverse_kind = kind == "long" ? "short" : "long";
2169
+ const reverse_position = this.position[reverse_kind];
2170
+ const focus_tp = this.tp(kind);
2171
+ const focus_pnl = this.pnl(kind);
2172
+ const fees = include_fees ? this.calculate_fee({
2173
+ price: focus_tp,
2174
+ quantity: focus_position.quantity
2175
+ }) * 2 : 0;
2176
+ const expected_loss = (focus_pnl - fees) * this.config.reduce_ratio;
2177
+ const actual_loss = Math.abs(focus_tp - reverse_position.entry) * reverse_position.quantity;
2178
+ const ratio = expected_loss / actual_loss;
2179
+ const loss_quantity = this.to_df(ratio * reverse_position.quantity);
2180
+ const remaining_quantity = this.to_df(reverse_position.quantity - loss_quantity);
2181
+ const diff = focus_pnl - expected_loss;
2182
+ return {
2183
+ [kind]: {
2184
+ entry: focus_tp,
2185
+ quantity: remaining_quantity
2186
+ },
2187
+ [reverse_kind]: {
2188
+ entry: reverse_position.entry,
2189
+ quantity: remaining_quantity
2190
+ },
2191
+ pnl: {
2192
+ [kind]: focus_pnl,
2193
+ [reverse_kind]: -expected_loss,
2194
+ diff
2195
+ },
2196
+ spread: this.to_f(Math.abs(focus_tp - reverse_position.entry) * remaining_quantity)
2197
+ };
2198
+ }
2199
+ getPositionAfterIteration(payload) {
2200
+ const { kind, iterations, with_fees = false } = payload;
2201
+ let _result = this.getPositionAfterTp({
2202
+ kind,
2203
+ include_fees: with_fees
2204
+ });
2205
+ const result = [_result];
2206
+ for (let i = 0;i < iterations - 1; i++) {
2207
+ const instance = new Strategy({
2208
+ long: _result.long,
2209
+ short: _result.short,
2210
+ config: {
2211
+ ...this.config,
2212
+ tp_percent: this.config.tp_percent + (i + 1) * 0.3
2213
+ }
2214
+ });
2215
+ _result = instance.getPositionAfterTp({
2216
+ kind,
2217
+ include_fees: with_fees
2218
+ });
2219
+ result.push(_result);
2220
+ }
2221
+ return result;
2222
+ }
2223
+ generateOppositeTrades(payload) {
2224
+ const { kind, risk_factor = 0.5, avg_entry } = payload;
2225
+ const entry = avg_entry || this.position[kind].entry;
2226
+ const stop = this.tp(kind);
2227
+ const risk = this.pnl(kind) * risk_factor;
2228
+ const risk_reward = getRiskReward({
2229
+ entry,
2230
+ stop,
2231
+ risk,
2232
+ global_config: this.config.global_config
2233
+ });
2234
+ const { entries, last_value, ...app_config } = buildAppConfig(this.config.global_config, {
2235
+ entry,
2236
+ stop,
2237
+ risk_reward,
2238
+ risk,
2239
+ symbol: this.config.global_config.symbol
2240
+ });
2241
+ const trades_to_place = determine_amount_to_buy({
2242
+ orders: entries,
2243
+ kind: app_config.kind,
2244
+ decimal_places: app_config.decimal_places,
2245
+ price_places: app_config.price_places,
2246
+ position: this.position[app_config.kind],
2247
+ existingOrders: []
2248
+ });
2249
+ const avg = determine_average_entry_and_size(trades_to_place.map((u) => ({
2250
+ price: u.entry,
2251
+ quantity: u.quantity
2252
+ })).concat([
2253
+ {
2254
+ price: this.position[app_config.kind].entry,
2255
+ quantity: this.position[app_config.kind].quantity
2256
+ }
2257
+ ]), app_config.decimal_places, app_config.price_places);
2258
+ const expected_loss = to_f(Math.abs(avg.price - stop) * avg.quantity, "%.2f");
2259
+ const profit_percent = to_f(this.pnl(kind) * 100 / (avg.price * avg.quantity), "%.3f");
2260
+ app_config.entry = this.to_f(app_config.entry);
2261
+ app_config.stop = this.to_f(app_config.stop);
2262
+ return { ...app_config, avg, loss: -expected_loss, profit_percent };
2263
+ }
2264
+ identifyGapConfig(payload) {
2265
+ const { factor = 1, sell_factor = 1 } = payload;
2266
+ return generateGapTp({
2267
+ long: this.position.long,
2268
+ short: this.position.short,
2269
+ factor,
2270
+ sell_factor,
2271
+ decimal_places: this.config.global_config.decimal_places,
2272
+ price_places: this.config.global_config.price_places
2273
+ });
2274
+ }
2275
+ analyzeProfit(payload) {
2276
+ const { reward_factor = 1, max_reward_factor, risk, kind } = payload;
2277
+ const focus_position = this.position[kind];
2278
+ const result = computeProfitDetail({
2279
+ focus_position: {
2280
+ kind,
2281
+ entry: focus_position.entry,
2282
+ quantity: focus_position.quantity,
2283
+ avg_price: focus_position.avg_price,
2284
+ avg_qty: focus_position.avg_qty
2285
+ },
2286
+ strategy: {
2287
+ reward_factor,
2288
+ max_reward_factor,
2289
+ risk
2290
+ }
2291
+ });
2292
+ return result;
2293
+ }
2294
+ simulateGapReduction(payload) {
2295
+ const { factor, kind, sell_factor = 1 } = payload;
2296
+ const results = [];
2297
+ let params = {
2298
+ long: this.position.long,
2299
+ short: this.position.short,
2300
+ config: this.config
2301
+ };
2302
+ let counter = 1;
2303
+ while (true) {
2304
+ const instance = new Strategy(params);
2305
+ const { profit_percent, risk, take_profit, sell_quantity, gap_loss } = instance.identifyGapConfig({
2306
+ factor,
2307
+ sell_factor
2308
+ });
2309
+ const to_add = {
2310
+ profit_percent,
2311
+ risk,
2312
+ take_profit,
2313
+ sell_quantity,
2314
+ gap_loss,
2315
+ position: {
2316
+ long: {
2317
+ entry: this.to_f(params.long.entry),
2318
+ quantity: this.to_df(params.long.quantity)
2319
+ },
2320
+ short: {
2321
+ entry: this.to_f(params.short.entry),
2322
+ quantity: this.to_df(params.short.quantity)
2323
+ }
2324
+ }
2325
+ };
2326
+ results.push(to_add);
2327
+ const sell_kind = kind == "long" ? "short" : "long";
2328
+ const remaining = this.to_df(params[sell_kind].quantity - sell_quantity[sell_kind]);
2329
+ if (remaining <= 0) {
2330
+ break;
2331
+ }
2332
+ params[sell_kind].quantity = remaining;
2333
+ params[kind] = {
2334
+ entry: take_profit[kind],
2335
+ quantity: remaining
2336
+ };
2337
+ counter++;
2338
+ }
2339
+ const last_gap_loss = results.at(-1)?.gap_loss;
2340
+ const last_tp = results.at(-1)?.take_profit[kind];
2341
+ const entry = this.position[kind].entry;
2342
+ const quantity = this.to_df(Math.abs(last_tp - entry) / last_gap_loss);
2343
+ return {
2344
+ results,
2345
+ quantity,
2346
+ counter
2347
+ };
2348
+ }
2349
+ }
2350
+ export {
2351
+ to_f,
2352
+ sortedBuildConfig,
2353
+ range,
2354
+ profitHelper,
2355
+ logWithLineNumber,
2356
+ groupIntoPairsWithSumLessThan,
2357
+ groupIntoPairs,
2358
+ groupBy,
2359
+ get_app_config_and_max_size,
2360
+ getTradeEntries,
2361
+ getRiskReward,
2362
+ getParamForField,
2363
+ getOptimumStopAndRisk,
2364
+ getDecimalPlaces,
2365
+ generate_config_params,
2366
+ generateOptimumAppConfig,
2367
+ generateGapTp,
2368
+ formatPrice,
2369
+ fibonacci_analysis,
2370
+ extractValue,
2371
+ determine_stop_and_size,
2372
+ determine_remaining_entry,
2373
+ determine_position_size,
2374
+ determine_break_even_price,
2375
+ determine_average_entry_and_size,
2376
+ determine_amount_to_sell2 as determine_amount_to_sell,
2377
+ determine_amount_to_buy,
2378
+ determineOptimumReward,
2379
+ createGapPairs,
2380
+ createArray,
2381
+ computeTotalAverageForEachTrade,
2382
+ computeSellZones,
2383
+ computeRiskReward,
2384
+ computeProfitDetail,
2385
+ buildConfig,
2386
+ buildAvg,
2387
+ buildAppConfig,
2388
+ asCoins,
2389
+ allCoins,
2390
+ Strategy,
2391
+ SpecialCoins
2392
+ };