@gbozee/ultimate 0.0.2-16 → 0.0.2-161

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