@gbozee/ultimate 0.0.2-13 → 0.0.2-130

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