@gbozee/ultimate 0.0.2-15 → 0.0.2-150

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,2974 @@
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
+ };
1544
+ const initialResult = sortedBuildConfig(app_config, {
1545
+ entry: app_config.entry,
1546
+ stop: app_config.stop,
1547
+ kind: app_config.kind,
1548
+ risk: app_config.risk_per_trade,
1549
+ risk_reward: app_config.risk_reward,
1550
+ increase: true,
1551
+ gap: app_config.gap,
1552
+ price_places: app_config.price_places,
1553
+ decimal_places: app_config.decimal_places,
1554
+ use_kelly: payload.use_kelly,
1555
+ kelly_confidence_factor: payload.kelly_confidence_factor,
1556
+ kelly_minimum_risk: payload.kelly_minimum_risk,
1557
+ kelly_prediction_model: payload.kelly_prediction_model,
1558
+ kelly_func: payload.kelly_func
1559
+ });
1560
+ const max_size = initialResult[0]?.avg_size;
1561
+ const last_value = initialResult[0];
1562
+ const entries = initialResult.map((x) => ({
1563
+ entry: x.entry,
1564
+ avg_entry: x.avg_entry,
1565
+ avg_size: x.avg_size,
1566
+ neg_pnl: x.neg_pnl,
1567
+ quantity: x.quantity
1568
+ }));
1569
+ return {
1570
+ app_config,
1571
+ max_size,
1572
+ last_value,
1573
+ entries
1574
+ };
1575
+ }
1576
+ function buildAppConfig(config, payload) {
1577
+ const { app_config, max_size, last_value, entries } = get_app_config_and_max_size({
1578
+ ...config,
1579
+ risk: payload.risk,
1580
+ profit: payload.profit || 500,
1581
+ risk_reward: payload.risk_reward,
1582
+ accounts: [],
1583
+ reduce_percent: 90,
1584
+ reverse_factor: 1,
1585
+ profit_percent: 0,
1586
+ kind: payload.entry > payload.stop ? "long" : "short",
1587
+ symbol: payload.symbol
1588
+ }, {
1589
+ entry: payload.entry,
1590
+ stop: payload.stop,
1591
+ kind: payload.entry > payload.stop ? "long" : "short",
1592
+ use_kelly: payload.use_kelly,
1593
+ kelly_confidence_factor: payload.kelly_confidence_factor,
1594
+ kelly_minimum_risk: payload.kelly_minimum_risk,
1595
+ kelly_prediction_model: payload.kelly_prediction_model,
1596
+ kelly_func: payload.kelly_func
1597
+ });
1598
+ app_config.max_size = max_size;
1599
+ app_config.entry = payload.entry || app_config.entry;
1600
+ app_config.stop = payload.stop || app_config.stop;
1601
+ app_config.last_value = last_value;
1602
+ app_config.entries = entries;
1603
+ app_config.kelly = {
1604
+ use_kelly: payload.use_kelly,
1605
+ kelly_confidence_factor: payload.kelly_confidence_factor,
1606
+ kelly_minimum_risk: payload.kelly_minimum_risk,
1607
+ kelly_prediction_model: payload.kelly_prediction_model,
1608
+ kelly_func: payload.kelly_func
1609
+ };
1610
+ return app_config;
1611
+ }
1612
+ function getOptimumStopAndRisk(app_config, params) {
1613
+ const { max_size, target_stop } = params;
1614
+ const isLong = app_config.kind === "long";
1615
+ const stopRange = Math.abs(app_config.entry - target_stop) * 0.5;
1616
+ let low_stop = isLong ? target_stop - stopRange : Math.max(target_stop - stopRange, app_config.entry);
1617
+ let high_stop = isLong ? Math.min(target_stop + stopRange, app_config.entry) : target_stop + stopRange;
1618
+ let optimal_stop = target_stop;
1619
+ let best_stop_result = null;
1620
+ let best_entry_diff = Infinity;
1621
+ console.log(`Finding optimal stop for ${isLong ? "LONG" : "SHORT"} position. Target: ${target_stop}, Search range: ${low_stop} to ${high_stop}`);
1622
+ let iterations = 0;
1623
+ const MAX_ITERATIONS = 50;
1624
+ while (Math.abs(high_stop - low_stop) > 0.1 && iterations < MAX_ITERATIONS) {
1625
+ iterations++;
1626
+ const mid_stop = (low_stop + high_stop) / 2;
1627
+ const result = sortedBuildConfig(app_config, {
1628
+ entry: app_config.entry,
1629
+ stop: mid_stop,
1630
+ kind: app_config.kind,
1631
+ risk: app_config.risk_per_trade,
1632
+ risk_reward: app_config.risk_reward,
1633
+ increase: true,
1634
+ gap: app_config.gap,
1635
+ price_places: app_config.price_places,
1636
+ decimal_places: app_config.decimal_places
1637
+ });
1638
+ if (result.length === 0) {
1639
+ if (isLong) {
1640
+ low_stop = mid_stop;
1641
+ } else {
1642
+ high_stop = mid_stop;
1643
+ }
1644
+ continue;
1645
+ }
1646
+ const first_entry = result[0].entry;
1647
+ const entry_diff = Math.abs(first_entry - target_stop);
1648
+ console.log(`Stop: ${mid_stop.toFixed(2)}, First Entry: ${first_entry.toFixed(2)}, Diff: ${entry_diff.toFixed(2)}`);
1649
+ if (entry_diff < best_entry_diff) {
1650
+ best_entry_diff = entry_diff;
1651
+ optimal_stop = mid_stop;
1652
+ best_stop_result = result;
1653
+ }
1654
+ if (first_entry < target_stop) {
1655
+ if (isLong) {
1656
+ low_stop = mid_stop;
1657
+ } else {
1658
+ low_stop = mid_stop;
1659
+ }
1660
+ } else {
1661
+ if (isLong) {
1662
+ high_stop = mid_stop;
1663
+ } else {
1664
+ high_stop = mid_stop;
1665
+ }
1666
+ }
1667
+ if (entry_diff < 1)
1668
+ break;
1669
+ }
1670
+ 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`);
1671
+ let low_risk = 10;
1672
+ let high_risk = params.highest_risk || 2000;
1673
+ let optimal_risk = app_config.risk_per_trade;
1674
+ let best_size_result = best_stop_result;
1675
+ let best_size_diff = Infinity;
1676
+ console.log(`Finding optimal risk_per_trade for size target: ${max_size} (never exceeding it)`);
1677
+ iterations = 0;
1678
+ while (Math.abs(high_risk - low_risk) > 0.1 && iterations < MAX_ITERATIONS) {
1679
+ iterations++;
1680
+ const mid_risk = (low_risk + high_risk) / 2;
1681
+ const result = sortedBuildConfig(app_config, {
1682
+ entry: app_config.entry,
1683
+ stop: optimal_stop,
1684
+ kind: app_config.kind,
1685
+ risk: mid_risk,
1686
+ risk_reward: app_config.risk_reward,
1687
+ increase: true,
1688
+ gap: app_config.gap,
1689
+ price_places: app_config.price_places,
1690
+ decimal_places: app_config.decimal_places
1691
+ });
1692
+ if (result.length === 0) {
1693
+ high_risk = mid_risk;
1694
+ continue;
1695
+ }
1696
+ const first_entry = result[0];
1697
+ const avg_size = first_entry.avg_size;
1698
+ console.log(`Risk: ${mid_risk.toFixed(2)}, Avg Size: ${avg_size.toFixed(4)}, Target: ${max_size}`);
1699
+ if (avg_size <= max_size) {
1700
+ const size_diff = max_size - avg_size;
1701
+ if (size_diff < best_size_diff) {
1702
+ best_size_diff = size_diff;
1703
+ optimal_risk = mid_risk;
1704
+ best_size_result = result;
1705
+ }
1706
+ low_risk = mid_risk;
1707
+ } else {
1708
+ high_risk = mid_risk;
1709
+ }
1710
+ if (best_size_diff < 0.001)
1711
+ break;
1712
+ }
1713
+ 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`);
1714
+ let final_risk = optimal_risk;
1715
+ let final_result = best_size_result;
1716
+ if (best_size_result?.[0]?.avg_size < max_size) {
1717
+ console.log(`Current avg_size (${best_size_result?.[0].avg_size.toFixed(4)}) is less than target (${max_size}). Increasing risk to reach target...`);
1718
+ let current_risk = optimal_risk;
1719
+ const risk_increment = 5;
1720
+ iterations = 0;
1721
+ while (iterations < MAX_ITERATIONS) {
1722
+ iterations++;
1723
+ current_risk += risk_increment;
1724
+ if (current_risk > 5000)
1725
+ break;
1726
+ const result = sortedBuildConfig(app_config, {
1727
+ entry: app_config.entry,
1728
+ stop: optimal_stop,
1729
+ kind: app_config.kind,
1730
+ risk: current_risk,
1731
+ risk_reward: app_config.risk_reward,
1732
+ increase: true,
1733
+ gap: app_config.gap,
1734
+ price_places: app_config.price_places,
1735
+ decimal_places: app_config.decimal_places
1736
+ });
1737
+ if (result.length === 0)
1738
+ continue;
1739
+ const avg_size = result[0].avg_size;
1740
+ console.log(`Increased Risk: ${current_risk.toFixed(2)}, New Avg Size: ${avg_size.toFixed(4)}`);
1741
+ if (avg_size >= max_size) {
1742
+ final_risk = current_risk;
1743
+ final_result = result;
1744
+ console.log(`Target size reached! Final risk: ${final_risk.toFixed(2)}, Final avg_size: ${avg_size.toFixed(4)}`);
1745
+ break;
1746
+ }
1747
+ }
1748
+ }
1749
+ return {
1750
+ optimal_stop: to_f(optimal_stop, app_config.price_places),
1751
+ optimal_risk: to_f(final_risk, app_config.price_places),
1752
+ avg_size: final_result?.[0]?.avg_size || 0,
1753
+ avg_entry: final_result?.[0]?.avg_entry || 0,
1754
+ result: final_result,
1755
+ first_entry: final_result?.[0]?.entry || 0,
1756
+ neg_pnl: final_result?.[0]?.neg_pnl || 0,
1757
+ risk_reward: app_config.risk_reward,
1758
+ size_diff: Math.abs((final_result?.[0]?.avg_size || 0) - max_size),
1759
+ entry_diff: best_entry_diff
1760
+ };
1761
+ }
1762
+ function generate_config_params(app_config, payload) {
1763
+ const { result, ...optimum } = getOptimumStopAndRisk(app_config, {
1764
+ max_size: app_config.max_size,
1765
+ highest_risk: payload.risk * 2,
1766
+ target_stop: app_config.stop
1767
+ });
1768
+ return {
1769
+ entry: payload.entry,
1770
+ stop: optimum.optimal_stop,
1771
+ avg_size: optimum.avg_size,
1772
+ avg_entry: optimum.avg_entry,
1773
+ risk_reward: payload.risk_reward,
1774
+ neg_pnl: optimum.neg_pnl,
1775
+ risk: payload.risk
1776
+ };
1777
+ }
1778
+ function determine_break_even_price(payload) {
1779
+ const { long_position, short_position, fee_percent = 0.05 / 100 } = payload;
1780
+ const long_notional = long_position.entry * long_position.quantity;
1781
+ const short_notional = short_position.entry * short_position.quantity;
1782
+ const net_quantity = long_position.quantity - short_position.quantity;
1783
+ const net_capital = Math.abs(long_notional - short_notional);
1784
+ const break_even_price = net_capital / (Math.abs(net_quantity) + fee_percent * Math.abs(net_quantity));
1785
+ return {
1786
+ price: break_even_price,
1787
+ direction: net_quantity > 0 ? "long" : "short"
1788
+ };
1789
+ }
1790
+ function determine_amount_to_buy(payload) {
1791
+ const {
1792
+ orders,
1793
+ kind,
1794
+ decimal_places = "%.3f",
1795
+ position: position2,
1796
+ existingOrders
1797
+ } = payload;
1798
+ const totalQuantity = orders.reduce((sum, order) => sum + (order.quantity || 0), 0);
1799
+ let runningTotal = to_f(totalQuantity, decimal_places);
1800
+ let sortedOrders = [...orders].sort((a, b) => (a.entry || 0) - (b.entry || 0));
1801
+ if (kind === "short") {
1802
+ sortedOrders.reverse();
1803
+ }
1804
+ const withCumulative = [];
1805
+ for (const order of sortedOrders) {
1806
+ withCumulative.push({
1807
+ ...order,
1808
+ cumulative_quantity: runningTotal
1809
+ });
1810
+ runningTotal -= order.quantity;
1811
+ runningTotal = to_f(runningTotal, decimal_places);
1812
+ }
1813
+ let filteredOrders = withCumulative.filter((order) => (order.cumulative_quantity || 0) > position2?.quantity).map((order) => ({
1814
+ ...order,
1815
+ price: order.entry,
1816
+ kind,
1817
+ side: kind.toLowerCase() === "long" ? "buy" : "sell"
1818
+ }));
1819
+ filteredOrders = filteredOrders.filter((k) => !existingOrders.map((j) => j.price).includes(k.price));
1820
+ return filteredOrders;
1821
+ }
1822
+ function generateOptimumAppConfig(config, payload, position2) {
1823
+ let low_risk = payload.start_risk;
1824
+ let high_risk = payload.max_risk || 50000;
1825
+ let best_risk = null;
1826
+ let best_app_config = null;
1827
+ const tolerance = 0.1;
1828
+ const max_iterations = 150;
1829
+ let iterations = 0;
1830
+ while (high_risk - low_risk > tolerance && iterations < max_iterations) {
1831
+ iterations++;
1832
+ const mid_risk = (low_risk + high_risk) / 2;
1833
+ const {
1834
+ app_config: current_app_config,
1835
+ max_size,
1836
+ last_value,
1837
+ entries
1838
+ } = get_app_config_and_max_size({
1839
+ ...config,
1840
+ risk: mid_risk,
1841
+ profit_percent: config.profit_percent || 0,
1842
+ profit: config.profit || 500,
1843
+ risk_reward: payload.risk_reward,
1844
+ kind: position2.kind,
1845
+ price_places: config.price_places,
1846
+ decimal_places: config.decimal_places,
1847
+ accounts: config.accounts || [],
1848
+ reduce_percent: config.reduce_percent || 90,
1849
+ reverse_factor: config.reverse_factor || 1,
1850
+ symbol: config.symbol || "",
1851
+ support: config.support || 0,
1852
+ resistance: config.resistance || 0,
1853
+ min_size: config.min_size || 0,
1854
+ stop_percent: config.stop_percent || 0
1855
+ }, {
1856
+ entry: payload.entry,
1857
+ stop: payload.stop,
1858
+ kind: position2.kind
1859
+ });
1860
+ current_app_config.max_size = max_size;
1861
+ current_app_config.last_value = last_value;
1862
+ current_app_config.entries = entries;
1863
+ current_app_config.risk_reward = payload.risk_reward;
1864
+ const full_trades = sortedBuildConfig(current_app_config, {
1865
+ entry: current_app_config.entry,
1866
+ stop: current_app_config.stop,
1867
+ kind: current_app_config.kind,
1868
+ risk: current_app_config.risk_per_trade,
1869
+ risk_reward: current_app_config.risk_reward,
1870
+ increase: true,
1871
+ gap: current_app_config.gap,
1872
+ price_places: current_app_config.price_places,
1873
+ decimal_places: current_app_config.decimal_places
1874
+ });
1875
+ if (full_trades.length === 0) {
1876
+ high_risk = mid_risk;
1877
+ continue;
1878
+ }
1879
+ const trades = determine_amount_to_buy({
1880
+ orders: full_trades,
1881
+ kind: position2.kind,
1882
+ decimal_places: current_app_config.decimal_places,
1883
+ price_places: current_app_config.price_places,
1884
+ position: position2,
1885
+ existingOrders: []
1886
+ });
1887
+ if (trades.length === 0) {
1888
+ low_risk = mid_risk;
1889
+ continue;
1890
+ }
1891
+ const last_trade = trades[trades.length - 1];
1892
+ const last_entry = last_trade.entry;
1893
+ if (position2.kind === "long") {
1894
+ if (last_entry > position2.entry) {
1895
+ high_risk = mid_risk;
1896
+ } else {
1897
+ best_risk = mid_risk;
1898
+ best_app_config = current_app_config;
1899
+ low_risk = mid_risk;
1900
+ }
1901
+ } else {
1902
+ if (last_entry < position2.entry) {
1903
+ high_risk = mid_risk;
1904
+ } else {
1905
+ best_risk = mid_risk;
1906
+ best_app_config = current_app_config;
1907
+ low_risk = mid_risk;
1908
+ }
1909
+ }
1910
+ }
1911
+ if (iterations >= max_iterations) {
1912
+ console.warn(`generateAppConfig: Reached max iterations (${max_iterations}) without converging. Returning best found result.`);
1913
+ } else if (best_app_config) {
1914
+ console.log(`Search finished. Best Risk: ${best_risk?.toFixed(2)}, Final Last Entry: ${best_app_config.last_value?.entry?.toFixed(4)}`);
1915
+ } else {
1916
+ console.warn(`generateAppConfig: Could not find a valid risk configuration.`);
1917
+ }
1918
+ if (!best_app_config) {
1919
+ return null;
1920
+ }
1921
+ best_app_config.entries = determine_amount_to_buy({
1922
+ orders: best_app_config.entries,
1923
+ kind: position2.kind,
1924
+ decimal_places: best_app_config.decimal_places,
1925
+ price_places: best_app_config.price_places,
1926
+ position: position2,
1927
+ existingOrders: []
1928
+ });
1929
+ return best_app_config;
1930
+ }
1931
+ function determineOptimumReward(app_config, increase = true, low_range = 30, high_range = 199) {
1932
+ const criterion = app_config.strategy || "quantity";
1933
+ const risk_rewards = createArray(low_range, high_range, 1);
1934
+ let func = risk_rewards.map((trade_no) => {
1935
+ let trades = sortedBuildConfig(app_config, {
1936
+ take_profit: app_config.take_profit,
1937
+ entry: app_config.entry,
1938
+ stop: app_config.stop,
1939
+ no_of_trades: trade_no,
1940
+ risk_reward: trade_no,
1941
+ increase,
1942
+ kind: app_config.kind,
1943
+ gap: app_config.gap,
1944
+ decimal_places: app_config.decimal_places
1945
+ });
1946
+ let total = 0;
1947
+ let max = -Infinity;
1948
+ let min = Infinity;
1949
+ let neg_pnl = trades[0]?.neg_pnl || 0;
1950
+ let entry = trades.at(-1)?.entry;
1951
+ if (!entry) {
1952
+ return null;
1953
+ }
1954
+ for (let trade of trades) {
1955
+ total += trade.quantity;
1956
+ max = Math.max(max, trade.quantity);
1957
+ min = Math.min(min, trade.quantity);
1958
+ entry = app_config.kind === "long" ? Math.max(entry, trade.entry) : Math.min(entry, trade.entry);
1959
+ }
1960
+ return {
1961
+ result: trades,
1962
+ value: trade_no,
1963
+ total,
1964
+ risk_per_trade: app_config.risk_per_trade,
1965
+ max,
1966
+ min,
1967
+ neg_pnl,
1968
+ entry
1969
+ };
1970
+ });
1971
+ func = func.filter((r) => Boolean(r)).filter((r) => {
1972
+ let foundIndex = r?.result.findIndex((e) => e.quantity === r.max);
1973
+ return criterion === "quantity" ? foundIndex === 0 : true;
1974
+ });
1975
+ const highest = criterion === "quantity" ? Math.max(...func.map((o) => o.max)) : Math.min(...func.map((o) => o.entry));
1976
+ const key = criterion === "quantity" ? "max" : "entry";
1977
+ const index = findIndexByCondition(func, app_config.kind, (x) => x[key] == highest, criterion);
1978
+ if (app_config.raw) {
1979
+ return func[index];
1980
+ }
1981
+ return func[index]?.value;
1982
+ }
1983
+ function findIndexByCondition(lst, kind, condition, defaultKey = "neg_pnl") {
1984
+ const found = [];
1985
+ let max_new_diff = 0;
1986
+ let new_lst = lst.map((i, j) => ({
1987
+ ...i,
1988
+ net_diff: lst[j].neg_pnl + lst[j].risk_per_trade
1989
+ }));
1990
+ new_lst.forEach((item, index) => {
1991
+ if (item.net_diff > 0) {
1992
+ found.push(index);
1993
+ }
1994
+ });
1995
+ if (found.length === 0) {
1996
+ max_new_diff = Math.max(...new_lst.map((e) => e.net_diff));
1997
+ found.push(new_lst.findIndex((e) => e.net_diff === max_new_diff));
1998
+ }
1999
+ 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) => {
2000
+ if (a.total !== b.total) {
2001
+ return b.total - a.total;
2002
+ return b.net_diff - a.net_diff;
2003
+ return a.net_diff - b.net_diff;
2004
+ } else {
2005
+ return b.net_diff - a.net_diff;
2006
+ }
2007
+ });
2008
+ console.log("found", sortedFound);
2009
+ if (defaultKey === "quantity") {
2010
+ return sortedFound[0].index;
2011
+ }
2012
+ if (found.length === 1) {
2013
+ return found[0];
2014
+ }
2015
+ if (found.length === 0) {
2016
+ return -1;
2017
+ }
2018
+ const entryCondition = (a, b) => {
2019
+ if (kind == "long") {
2020
+ return a.entry > b.entry;
2021
+ }
2022
+ return a.entry < b.entry;
2023
+ };
2024
+ const maximum = found.reduce((maxIndex, currentIndex) => {
2025
+ return new_lst[currentIndex]["net_diff"] < new_lst[maxIndex]["net_diff"] && entryCondition(new_lst[currentIndex], new_lst[maxIndex]) ? currentIndex : maxIndex;
2026
+ }, found[0]);
2027
+ return maximum;
2028
+ }
2029
+ function determineOptimumRisk(config, payload, params) {
2030
+ const { highest_risk, tolerance = 0.01, max_iterations = 200 } = params;
2031
+ let low_risk = 1;
2032
+ let high_risk = Math.max(highest_risk * 5, payload.risk * 10);
2033
+ let best_risk = payload.risk;
2034
+ let best_neg_pnl = 0;
2035
+ let best_diff = Infinity;
2036
+ console.log(`Finding optimal risk for target neg_pnl: ${highest_risk}`);
2037
+ let iterations = 0;
2038
+ while (iterations < max_iterations && high_risk - low_risk > tolerance) {
2039
+ iterations++;
2040
+ const mid_risk = (low_risk + high_risk) / 2;
2041
+ const test_payload = {
2042
+ ...payload,
2043
+ risk: mid_risk
2044
+ };
2045
+ const { last_value } = buildAppConfig(config, test_payload);
2046
+ if (!last_value || !last_value.neg_pnl) {
2047
+ high_risk = mid_risk;
2048
+ continue;
2049
+ }
2050
+ const current_neg_pnl = Math.abs(last_value.neg_pnl);
2051
+ const diff = Math.abs(current_neg_pnl - highest_risk);
2052
+ console.log(`Iteration ${iterations}: Risk=${mid_risk.toFixed(2)}, neg_pnl=${current_neg_pnl.toFixed(2)}, diff=${diff.toFixed(2)}`);
2053
+ if (diff < best_diff) {
2054
+ best_diff = diff;
2055
+ best_risk = mid_risk;
2056
+ best_neg_pnl = current_neg_pnl;
2057
+ }
2058
+ if (diff <= tolerance) {
2059
+ console.log(`Converged! Optimal risk: ${mid_risk.toFixed(2)}`);
2060
+ break;
2061
+ }
2062
+ if (current_neg_pnl < highest_risk) {
2063
+ low_risk = mid_risk;
2064
+ } else {
2065
+ high_risk = mid_risk;
2066
+ }
2067
+ }
2068
+ const final_payload = {
2069
+ ...payload,
2070
+ risk: best_risk
2071
+ };
2072
+ const final_result = buildAppConfig(config, final_payload);
2073
+ return {
2074
+ optimal_risk: to_f(best_risk, "%.2f"),
2075
+ achieved_neg_pnl: to_f(best_neg_pnl, "%.2f"),
2076
+ target_neg_pnl: to_f(highest_risk, "%.2f"),
2077
+ difference: to_f(best_diff, "%.2f"),
2078
+ iterations,
2079
+ converged: best_diff <= tolerance,
2080
+ last_value: final_result.last_value,
2081
+ entries: final_result.entries,
2082
+ app_config: final_result
2083
+ };
2084
+ }
2085
+ function computeRiskReward(payload) {
2086
+ const { app_config, entry, stop, risk_per_trade } = payload;
2087
+ const kind = entry > stop ? "long" : "short";
2088
+ app_config.kind = kind;
2089
+ app_config.entry = entry;
2090
+ app_config.stop = stop;
2091
+ app_config.risk_per_trade = risk_per_trade;
2092
+ const result = determineOptimumReward(app_config);
2093
+ return result;
2094
+ }
2095
+ function getRiskReward(payload) {
2096
+ const {
2097
+ entry,
2098
+ stop,
2099
+ risk,
2100
+ global_config,
2101
+ force_exact_risk = false
2102
+ } = payload;
2103
+ const { entries, last_value, ...app_config } = buildAppConfig(global_config, {
2104
+ entry,
2105
+ stop,
2106
+ risk_reward: 30,
2107
+ risk,
2108
+ symbol: global_config.symbol
2109
+ });
2110
+ const risk_reward = computeRiskReward({
2111
+ app_config,
2112
+ entry,
2113
+ stop,
2114
+ risk_per_trade: risk
2115
+ });
2116
+ if (force_exact_risk) {
2117
+ const new_risk_per_trade = determineOptimumRisk(global_config, {
2118
+ entry,
2119
+ stop,
2120
+ risk_reward,
2121
+ risk,
2122
+ symbol: global_config.symbol
2123
+ }, {
2124
+ highest_risk: risk
2125
+ }).optimal_risk;
2126
+ return { risk: new_risk_per_trade, risk_reward };
2127
+ }
2128
+ return risk_reward;
2129
+ }
2130
+ function computeProfitDetail(payload) {
2131
+ const {
2132
+ focus_position,
2133
+ strategy,
2134
+ pnl,
2135
+ price_places = "%.1f",
2136
+ reduce_position,
2137
+ decimal_places,
2138
+ reverse_position,
2139
+ full_ratio = 1
2140
+ } = payload;
2141
+ let reward_factor = strategy?.reward_factor || 1;
2142
+ const profit_percent = to_f(pnl * 100 / (focus_position.avg_price * focus_position.avg_qty), "%.4f");
2143
+ const diff = pnl / focus_position.quantity;
2144
+ const sell_price = to_f(focus_position.kind === "long" ? focus_position.entry + diff : focus_position.entry - diff, price_places);
2145
+ let loss = 0;
2146
+ let full_loss = 0;
2147
+ let expected_loss = 0;
2148
+ let quantity = 0;
2149
+ let new_pnl = pnl;
2150
+ if (reduce_position) {
2151
+ loss = Math.abs(reduce_position.entry - sell_price) * reduce_position.quantity;
2152
+ const ratio = pnl / loss;
2153
+ quantity = to_f(reduce_position.quantity * ratio, decimal_places);
2154
+ expected_loss = to_f(Math.abs(reduce_position.entry - sell_price) * quantity, "%.2f");
2155
+ full_loss = Math.abs(reduce_position.avg_price - sell_price) * reduce_position.avg_qty * full_ratio;
2156
+ }
2157
+ if (reverse_position) {
2158
+ expected_loss = Math.abs(reverse_position.avg_price - sell_price) * reverse_position.avg_qty;
2159
+ new_pnl = to_f(pnl - expected_loss, "%.2f");
2160
+ }
2161
+ return {
2162
+ pnl: new_pnl,
2163
+ loss: to_f(expected_loss, "%.2f"),
2164
+ full_loss: to_f(full_loss, "%.2f"),
2165
+ original_pnl: pnl,
2166
+ reward_factor,
2167
+ profit_percent,
2168
+ kind: focus_position.kind,
2169
+ sell_price: to_f(sell_price, price_places),
2170
+ quantity: quantity * full_ratio,
2171
+ price_places,
2172
+ decimal_places
2173
+ };
2174
+ }
2175
+ function generateGapTp(payload) {
2176
+ const {
2177
+ long,
2178
+ short,
2179
+ factor: factor_value = 0,
2180
+ risk: desired_risk,
2181
+ sell_factor = 1,
2182
+ kind,
2183
+ price_places = "%.1f",
2184
+ decimal_places = "%.3f"
2185
+ } = payload;
2186
+ if (!factor_value && !desired_risk) {
2187
+ throw new Error("Either factor or risk must be provided");
2188
+ }
2189
+ if (desired_risk && !kind) {
2190
+ throw new Error("Kind must be provided when risk is provided");
2191
+ }
2192
+ let factor = factor_value || calculate_factor({
2193
+ long,
2194
+ short,
2195
+ risk: desired_risk,
2196
+ kind,
2197
+ sell_factor
2198
+ });
2199
+ const gap = Math.abs(long.entry - short.entry);
2200
+ const max_quantity = Math.max(long.quantity, short.quantity);
2201
+ const gapLoss = gap * max_quantity;
2202
+ const longPercent = gapLoss * factor / (short.entry * short.quantity);
2203
+ const shortPercent = gapLoss * factor / (long.entry * long.quantity);
2204
+ const longTp = to_f((1 + longPercent) * long.entry, price_places);
2205
+ const shortTp = to_f((1 + shortPercent) ** -1 * short.entry, price_places);
2206
+ const shortToReduce = to_f(Math.abs(longTp - long.entry) * long.quantity, "%.1f");
2207
+ const longToReduce = to_f(Math.abs(shortTp - short.entry) * short.quantity, "%.1f");
2208
+ const actualShortReduce = to_f(shortToReduce * sell_factor, "%.1f");
2209
+ const actualLongReduce = to_f(longToReduce * sell_factor, "%.1f");
2210
+ const short_quantity_to_sell = determine_amount_to_sell2(short.entry, short.quantity, longTp, actualShortReduce, "short", decimal_places);
2211
+ const long_quantity_to_sell = determine_amount_to_sell2(long.entry, long.quantity, shortTp, actualLongReduce, "long", decimal_places);
2212
+ const risk_amount_short = to_f(shortToReduce - actualShortReduce, "%.2f");
2213
+ const risk_amount_long = to_f(longToReduce - actualLongReduce, "%.2f");
2214
+ const profit_percent_long = to_f(shortToReduce * 100 / (long.entry * long.quantity), "%.4f");
2215
+ const profit_percent_short = to_f(longToReduce * 100 / (short.entry * short.quantity), "%.4f");
2216
+ return {
2217
+ profit_percent: {
2218
+ long: profit_percent_long,
2219
+ short: profit_percent_short
2220
+ },
2221
+ risk: {
2222
+ short: risk_amount_short,
2223
+ long: risk_amount_long
2224
+ },
2225
+ take_profit: {
2226
+ long: longTp,
2227
+ short: shortTp
2228
+ },
2229
+ to_reduce: {
2230
+ short: actualShortReduce,
2231
+ long: actualLongReduce
2232
+ },
2233
+ full_reduce: {
2234
+ short: shortToReduce,
2235
+ long: longToReduce
2236
+ },
2237
+ sell_quantity: {
2238
+ short: short_quantity_to_sell,
2239
+ long: long_quantity_to_sell
2240
+ },
2241
+ gap: to_f(gap, price_places),
2242
+ gap_loss: to_f(gapLoss, "%.2f")
2243
+ };
2244
+ }
2245
+ function calculate_factor(payload) {
2246
+ const {
2247
+ long,
2248
+ short,
2249
+ risk: desired_risk,
2250
+ kind,
2251
+ sell_factor,
2252
+ places = "%.4f"
2253
+ } = payload;
2254
+ const gap = Math.abs(long.entry - short.entry);
2255
+ const max_quantity = Math.max(long.quantity, short.quantity);
2256
+ const gapLoss = gap * max_quantity;
2257
+ let calculated_factor;
2258
+ const long_notional = long.entry * long.quantity;
2259
+ const short_notional = short.entry * short.quantity;
2260
+ const target_to_reduce = desired_risk / (1 - sell_factor);
2261
+ if (kind === "short") {
2262
+ const calculate_longPercent = target_to_reduce / long_notional;
2263
+ calculated_factor = calculate_longPercent * short_notional / gapLoss;
2264
+ } else {
2265
+ const calculated_shortPercent = target_to_reduce / (short_notional - target_to_reduce);
2266
+ calculated_factor = calculated_shortPercent * long_notional / gapLoss;
2267
+ }
2268
+ calculated_factor = to_f(calculated_factor, places);
2269
+ return calculated_factor;
2270
+ }
2271
+ function determineRewardFactor(payload) {
2272
+ const { quantity, avg_qty, minimum_pnl, risk } = payload;
2273
+ const reward_factor = minimum_pnl / risk;
2274
+ const quantity_ratio = quantity / avg_qty;
2275
+ return to_f(reward_factor / quantity_ratio, "%.4f");
2276
+ }
2277
+ function getHedgeZone(payload) {
2278
+ const {
2279
+ reward_factor: _reward_factor,
2280
+ symbol_config,
2281
+ risk,
2282
+ position: position2,
2283
+ risk_factor = 1,
2284
+ support
2285
+ } = payload;
2286
+ const kind = position2.kind;
2287
+ let reward_factor = _reward_factor;
2288
+ if (support) {
2289
+ const _result = getOptimumHedgeFactor({
2290
+ target_support: support,
2291
+ symbol_config,
2292
+ risk,
2293
+ position: position2
2294
+ });
2295
+ reward_factor = Number(_result.reward_factor);
2296
+ }
2297
+ const take_profit = position2.tp?.price;
2298
+ const tp_diff = Math.abs(take_profit - position2.entry);
2299
+ const quantity = position2.quantity;
2300
+ const diff = risk / quantity;
2301
+ let new_take_profit = kind === "long" ? to_f(position2.entry + diff, symbol_config.price_places) : to_f(position2.entry - diff, symbol_config.price_places);
2302
+ let base_factor = to_f(Math.max(tp_diff, diff) / (Math.min(tp_diff, diff) || 1), "%.3f");
2303
+ let factor = reward_factor || base_factor;
2304
+ const new_risk = risk * factor * risk_factor;
2305
+ const stop_loss_diff = new_risk / quantity;
2306
+ 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);
2307
+ 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);
2308
+ const profit_percent = new_risk * 100 / (position2.entry * position2.quantity);
2309
+ return {
2310
+ support: Math.min(new_take_profit, stop_loss),
2311
+ resistance: Math.max(new_take_profit, stop_loss),
2312
+ risk: to_f(new_risk, "%.2f"),
2313
+ profit_percent: to_f(profit_percent, "%.2f")
2314
+ };
2315
+ }
2316
+ function getOptimumHedgeFactor(payload) {
2317
+ const {
2318
+ target_support,
2319
+ max_iterations = 50,
2320
+ min_factor = 0.1,
2321
+ max_factor = 20,
2322
+ symbol_config,
2323
+ risk,
2324
+ position: position2
2325
+ } = payload;
2326
+ const current_price = position2.entry;
2327
+ const tolerance = current_price > 100 ? 0.5 : current_price > 1 ? 0.01 : 0.001;
2328
+ let low = min_factor;
2329
+ let high = max_factor;
2330
+ let best_factor = low;
2331
+ let best_diff = Infinity;
2332
+ for (let iteration = 0;iteration < max_iterations; iteration++) {
2333
+ const mid_factor = (low + high) / 2;
2334
+ const hedge_zone = getHedgeZone({
2335
+ reward_factor: mid_factor,
2336
+ symbol_config,
2337
+ risk,
2338
+ position: position2
2339
+ });
2340
+ const current_support = hedge_zone.support;
2341
+ const diff = Math.abs(current_support - target_support);
2342
+ if (diff < best_diff) {
2343
+ best_diff = diff;
2344
+ best_factor = mid_factor;
2345
+ }
2346
+ if (diff <= tolerance) {
2347
+ return {
2348
+ reward_factor: to_f(mid_factor, "%.4f"),
2349
+ achieved_support: to_f(current_support, symbol_config.price_places),
2350
+ target_support: to_f(target_support, symbol_config.price_places),
2351
+ difference: to_f(diff, symbol_config.price_places),
2352
+ iterations: iteration + 1
2353
+ };
2354
+ }
2355
+ if (current_support > target_support) {
2356
+ low = mid_factor;
2357
+ } else {
2358
+ high = mid_factor;
2359
+ }
2360
+ if (Math.abs(high - low) < 0.0001) {
2361
+ break;
2362
+ }
2363
+ }
2364
+ const final_hedge_zone = getHedgeZone({
2365
+ symbol_config,
2366
+ risk,
2367
+ position: position2,
2368
+ reward_factor: best_factor
2369
+ });
2370
+ return {
2371
+ reward_factor: to_f(best_factor, "%.4f"),
2372
+ achieved_support: to_f(final_hedge_zone.support, symbol_config.price_places),
2373
+ target_support: to_f(target_support, symbol_config.price_places),
2374
+ difference: to_f(best_diff, symbol_config.price_places),
2375
+ iterations: max_iterations,
2376
+ converged: best_diff <= tolerance
2377
+ };
2378
+ }
2379
+ function determineCompoundLongTrade(payload) {
2380
+ const {
2381
+ focus_short_position,
2382
+ focus_long_position,
2383
+ shortConfig,
2384
+ global_config,
2385
+ rr = 1
2386
+ } = payload;
2387
+ const short_app_config = buildAppConfig(global_config, {
2388
+ entry: shortConfig.entry,
2389
+ stop: shortConfig.stop,
2390
+ risk_reward: shortConfig.risk_reward,
2391
+ risk: shortConfig.risk,
2392
+ symbol: shortConfig.symbol
2393
+ });
2394
+ const short_max_size = short_app_config.last_value.avg_size;
2395
+ const start_risk = Math.abs(short_app_config.last_value.neg_pnl) * rr;
2396
+ const short_profit = short_app_config.last_value.avg_size * short_app_config.last_value.avg_entry * shortConfig.profit_percent / 100;
2397
+ const diff = short_profit * rr / short_app_config.last_value.avg_size;
2398
+ const support = Math.abs(short_app_config.last_value.avg_entry - diff);
2399
+ const resistance = focus_short_position.next_order || focus_long_position.take_profit;
2400
+ console.log({ support, resistance, short_profit });
2401
+ const result = getRiskReward({
2402
+ entry: resistance,
2403
+ stop: support,
2404
+ risk: start_risk,
2405
+ global_config,
2406
+ force_exact_risk: true
2407
+ });
2408
+ const long_app_config = buildAppConfig(global_config, {
2409
+ entry: resistance,
2410
+ stop: support,
2411
+ risk_reward: result.risk_reward,
2412
+ risk: result.risk,
2413
+ symbol: shortConfig.symbol
2414
+ });
2415
+ const long_profit_percent = start_risk * 2 * 100 / (long_app_config.last_value.avg_size * long_app_config.last_value.avg_entry);
2416
+ return {
2417
+ start_risk,
2418
+ short_profit,
2419
+ support: to_f(support, global_config.price_places),
2420
+ resistance: to_f(resistance, global_config.price_places),
2421
+ long_v: long_app_config.last_value,
2422
+ profit_percent: to_f(long_profit_percent, "%.3f"),
2423
+ result,
2424
+ short_max_size
2425
+ };
2426
+ }
2427
+ // src/helpers/strategy.ts
2428
+ class Strategy {
2429
+ position;
2430
+ dominant_position = "long";
2431
+ config;
2432
+ constructor(payload) {
2433
+ this.position = {
2434
+ long: payload.long,
2435
+ short: payload.short
2436
+ };
2437
+ this.dominant_position = payload.dominant_position || "long";
2438
+ this.config = payload.config;
2439
+ if (!this.config.fee_percent) {
2440
+ this.config.fee_percent = 0.05;
2441
+ }
2442
+ }
2443
+ get price_places() {
2444
+ return this.config.global_config.price_places;
2445
+ }
2446
+ get decimal_places() {
2447
+ return this.config.global_config.decimal_places;
2448
+ }
2449
+ to_f(price) {
2450
+ return to_f(price, this.price_places);
2451
+ }
2452
+ to_df(quantity) {
2453
+ return to_f(quantity, this.decimal_places);
2454
+ }
2455
+ pnl(kind, _position) {
2456
+ const position2 = _position || this.position[kind];
2457
+ const { entry, quantity } = position2;
2458
+ const notional = entry * quantity;
2459
+ let tp_percent = this.config.tp_percent;
2460
+ if (kind == "short") {
2461
+ tp_percent = tp_percent * this.config.short_tp_factor;
2462
+ }
2463
+ const profit = notional * (tp_percent / 100);
2464
+ return this.to_f(profit);
2465
+ }
2466
+ tp(kind) {
2467
+ let position2 = this.position[kind];
2468
+ if (position2.quantity == 0) {
2469
+ const reverse_kind = kind == "long" ? "short" : "long";
2470
+ position2 = this.position[reverse_kind];
2471
+ }
2472
+ const { entry, quantity } = position2;
2473
+ const profit = this.pnl(kind, position2);
2474
+ const diff = profit / (quantity || 1);
2475
+ return this.to_f(kind == "long" ? entry + diff : entry - diff);
2476
+ }
2477
+ calculate_fee(position2) {
2478
+ const { price, quantity } = position2;
2479
+ const fee = price * quantity * this.config.fee_percent / 100;
2480
+ return this.to_f(fee);
2481
+ }
2482
+ get long_tp() {
2483
+ return this.tp("long");
2484
+ }
2485
+ get short_tp() {
2486
+ return this.tp("short");
2487
+ }
2488
+ generateGapClosingAlgorithm(payload) {
2489
+ const {
2490
+ kind,
2491
+ ignore_entries = false,
2492
+ reduce_ratio = 1,
2493
+ sell_factor = 1
2494
+ } = payload;
2495
+ const { entry, quantity } = this.position[kind];
2496
+ const focus_position = this.position[kind];
2497
+ const reverse_kind = kind == "long" ? "short" : "long";
2498
+ const reverse_position = this.position[reverse_kind];
2499
+ let _entry = this.tp(kind);
2500
+ let _stop = this.tp(reverse_kind);
2501
+ const second_payload = {
2502
+ entry: _entry,
2503
+ stop: _stop,
2504
+ risk_reward: this.config.risk_reward,
2505
+ start_risk: this.pnl(reverse_kind),
2506
+ max_risk: this.config.budget
2507
+ };
2508
+ const third_payload = {
2509
+ entry,
2510
+ quantity,
2511
+ kind
2512
+ };
2513
+ const app_config = generateOptimumAppConfig(this.config.global_config, second_payload, third_payload);
2514
+ let entries = [];
2515
+ let risk_per_trade = this.config.budget;
2516
+ let last_value = null;
2517
+ if (app_config) {
2518
+ let { entries: _entries, ...rest } = app_config;
2519
+ entries = _entries;
2520
+ risk_per_trade = rest.risk_per_trade;
2521
+ last_value = rest.last_value;
2522
+ if (ignore_entries) {
2523
+ entries = [];
2524
+ }
2525
+ console.log({ app_config });
2526
+ }
2527
+ const risk = this.to_f(risk_per_trade);
2528
+ let below_reverse_entries = kind === "long" ? entries.filter((u) => {
2529
+ return u.entry < (reverse_position.entry || focus_position.entry);
2530
+ }) : entries.filter((u) => {
2531
+ return u.entry > (reverse_position.entry || focus_position.entry);
2532
+ });
2533
+ const threshold = below_reverse_entries.at(-1);
2534
+ const result = this.gapCloserHelper({
2535
+ risk,
2536
+ entries,
2537
+ kind,
2538
+ sell_factor,
2539
+ reduce_ratio
2540
+ });
2541
+ return {
2542
+ ...result,
2543
+ last_entry: last_value?.entry,
2544
+ first_entry: entries.at(-1)?.entry,
2545
+ threshold
2546
+ };
2547
+ }
2548
+ gapCloserHelper(payload) {
2549
+ const {
2550
+ risk,
2551
+ entries = [],
2552
+ kind,
2553
+ sell_factor = 1,
2554
+ reduce_ratio = 1
2555
+ } = payload;
2556
+ const { entry, quantity } = this.position[kind];
2557
+ const focus_position = this.position[kind];
2558
+ const reverse_kind = kind == "long" ? "short" : "long";
2559
+ const reverse_position = this.position[reverse_kind];
2560
+ let _entry = this.tp(kind);
2561
+ let _stop = this.tp(reverse_kind);
2562
+ const second_payload = {
2563
+ entry: _entry,
2564
+ stop: _stop,
2565
+ risk_reward: this.config.risk_reward,
2566
+ start_risk: this.pnl(reverse_kind),
2567
+ max_risk: this.config.budget
2568
+ };
2569
+ const adjusted_focus_entries = entries.map((entry2) => {
2570
+ let adjusted_price = entry2.price;
2571
+ if (focus_position.quantity > 0) {
2572
+ if (kind === "long" && entry2.price >= focus_position.entry) {
2573
+ adjusted_price = focus_position.entry;
2574
+ } else if (kind === "short" && entry2.price <= focus_position.entry) {
2575
+ adjusted_price = focus_position.entry;
2576
+ }
2577
+ }
2578
+ return {
2579
+ price: adjusted_price,
2580
+ quantity: entry2.quantity
2581
+ };
2582
+ });
2583
+ const avg = determine_average_entry_and_size(adjusted_focus_entries.concat([
2584
+ {
2585
+ price: entry,
2586
+ quantity
2587
+ }
2588
+ ]), this.config.global_config.decimal_places, this.config.global_config.price_places);
2589
+ const focus_loss = this.to_f(Math.abs(avg.price - second_payload.stop) * avg.quantity);
2590
+ let below_reverse_entries = kind === "long" ? entries.filter((u) => {
2591
+ return u.entry < (reverse_position.entry || focus_position.entry);
2592
+ }) : entries.filter((u) => {
2593
+ return u.entry > (reverse_position.entry || focus_position.entry);
2594
+ });
2595
+ const threshold = below_reverse_entries.at(-1);
2596
+ let adjusted_reverse_entries = entries.map((entry2) => {
2597
+ let adjusted_price = entry2.price;
2598
+ if (threshold) {
2599
+ if (reverse_kind === "short" && entry2.price > threshold.entry) {
2600
+ adjusted_price = threshold.entry;
2601
+ } else if (reverse_kind === "long" && entry2.price < threshold.entry) {
2602
+ adjusted_price = threshold.entry;
2603
+ }
2604
+ }
2605
+ return {
2606
+ price: adjusted_price,
2607
+ quantity: entry2.quantity
2608
+ };
2609
+ });
2610
+ const reverse_avg = determine_average_entry_and_size(adjusted_reverse_entries.concat([
2611
+ {
2612
+ price: reverse_position.entry,
2613
+ quantity: reverse_position.quantity
2614
+ }
2615
+ ]), this.config.global_config.decimal_places, this.config.global_config.price_places);
2616
+ const sell_quantity = this.to_df(reverse_avg.quantity * sell_factor);
2617
+ const reverse_pnl = this.to_f(Math.abs(reverse_avg.price - second_payload.stop) * sell_quantity);
2618
+ const fee_to_pay = this.calculate_fee({
2619
+ price: avg.entry,
2620
+ quantity: avg.quantity
2621
+ }) + this.calculate_fee({
2622
+ price: reverse_avg.entry,
2623
+ quantity: sell_quantity
2624
+ });
2625
+ const net_reverse_pnl = reverse_pnl - fee_to_pay;
2626
+ const ratio = net_reverse_pnl * reduce_ratio / focus_loss;
2627
+ const quantity_to_sell = this.to_df(ratio * avg.quantity);
2628
+ const remaining_quantity = this.to_df(avg.quantity - quantity_to_sell);
2629
+ const incurred_loss = this.to_f((avg.price - second_payload.stop) * quantity_to_sell);
2630
+ return {
2631
+ risk,
2632
+ risk_reward: this.config.risk_reward,
2633
+ [kind]: {
2634
+ avg_entry: avg.entry,
2635
+ avg_size: avg.quantity,
2636
+ loss: focus_loss,
2637
+ stop: second_payload.stop,
2638
+ stop_quantity: quantity_to_sell,
2639
+ re_entry_quantity: remaining_quantity,
2640
+ initial_pnl: this.pnl(kind),
2641
+ tp: second_payload.entry,
2642
+ incurred_loss
2643
+ },
2644
+ [reverse_kind]: {
2645
+ avg_entry: reverse_avg.entry,
2646
+ avg_size: reverse_avg.quantity,
2647
+ pnl: reverse_pnl,
2648
+ tp: second_payload.stop,
2649
+ re_entry_quantity: remaining_quantity,
2650
+ initial_pnl: this.pnl(reverse_kind),
2651
+ remaining_quantity: this.to_df(reverse_avg.quantity - sell_quantity)
2652
+ },
2653
+ spread: Math.abs(avg.entry - reverse_avg.entry),
2654
+ gap_loss: to_f(Math.abs(avg.entry - reverse_avg.entry) * reverse_avg.quantity, "%.2f"),
2655
+ net_profit: incurred_loss + reverse_pnl
2656
+ };
2657
+ }
2658
+ runIterations(payload) {
2659
+ const {
2660
+ kind,
2661
+ iterations,
2662
+ ignore_entries = false,
2663
+ reduce_ratio = 1,
2664
+ sell_factor = 1
2665
+ } = payload;
2666
+ const reverse_kind = kind == "long" ? "short" : "long";
2667
+ const result = [];
2668
+ let position2 = {
2669
+ long: this.position.long,
2670
+ short: this.position.short
2671
+ };
2672
+ let tp_percent_multiplier = 1;
2673
+ let short_tp_factor_multiplier = 1;
2674
+ for (let i = 0;i < iterations; i++) {
2675
+ const instance = new Strategy({
2676
+ long: position2.long,
2677
+ short: position2.short,
2678
+ config: {
2679
+ ...this.config,
2680
+ tp_percent: this.config.tp_percent * tp_percent_multiplier,
2681
+ short_tp_factor: this.config.short_tp_factor * short_tp_factor_multiplier
2682
+ }
2683
+ });
2684
+ const algorithm = instance.generateGapClosingAlgorithm({
2685
+ kind,
2686
+ ignore_entries,
2687
+ reduce_ratio,
2688
+ sell_factor
2689
+ });
2690
+ if (!algorithm) {
2691
+ console.log("No algorithm found");
2692
+ return result;
2693
+ break;
2694
+ }
2695
+ result.push(algorithm);
2696
+ position2[kind] = {
2697
+ entry: algorithm[kind].avg_entry,
2698
+ quantity: algorithm[kind].re_entry_quantity
2699
+ };
2700
+ let reverse_entry = algorithm[reverse_kind].tp;
2701
+ let reverse_quantity = algorithm[reverse_kind].re_entry_quantity;
2702
+ if (algorithm[reverse_kind].remaining_quantity > 0) {
2703
+ const purchase_to_occur = {
2704
+ price: reverse_entry,
2705
+ quantity: algorithm[reverse_kind].remaining_quantity
2706
+ };
2707
+ const avg = determine_average_entry_and_size([
2708
+ purchase_to_occur,
2709
+ {
2710
+ price: algorithm[reverse_kind].avg_entry,
2711
+ quantity: reverse_quantity - algorithm[reverse_kind].remaining_quantity
2712
+ }
2713
+ ], this.config.global_config.decimal_places, this.config.global_config.price_places);
2714
+ reverse_entry = avg.entry;
2715
+ reverse_quantity = avg.quantity;
2716
+ if (reverse_kind === "short") {
2717
+ short_tp_factor_multiplier = 2;
2718
+ } else {
2719
+ tp_percent_multiplier = 2;
2720
+ }
2721
+ }
2722
+ position2[reverse_kind] = {
2723
+ entry: reverse_entry,
2724
+ quantity: reverse_quantity
2725
+ };
2726
+ }
2727
+ return result;
2728
+ }
2729
+ getPositionAfterTp(payload) {
2730
+ const { kind, include_fees = false } = payload;
2731
+ const focus_position = this.position[kind];
2732
+ const reverse_kind = kind == "long" ? "short" : "long";
2733
+ const reverse_position = this.position[reverse_kind];
2734
+ const focus_tp = this.tp(kind);
2735
+ const focus_pnl = this.pnl(kind);
2736
+ const fees = include_fees ? this.calculate_fee({
2737
+ price: focus_tp,
2738
+ quantity: focus_position.quantity
2739
+ }) * 2 : 0;
2740
+ const expected_loss = (focus_pnl - fees) * this.config.reduce_ratio;
2741
+ const actual_loss = Math.abs(focus_tp - reverse_position.entry) * reverse_position.quantity;
2742
+ const ratio = expected_loss / actual_loss;
2743
+ const loss_quantity = this.to_df(ratio * reverse_position.quantity);
2744
+ const remaining_quantity = this.to_df(reverse_position.quantity - loss_quantity);
2745
+ const diff = focus_pnl - expected_loss;
2746
+ return {
2747
+ [kind]: {
2748
+ entry: focus_tp,
2749
+ quantity: remaining_quantity
2750
+ },
2751
+ [reverse_kind]: {
2752
+ entry: reverse_position.entry,
2753
+ quantity: remaining_quantity
2754
+ },
2755
+ pnl: {
2756
+ [kind]: focus_pnl,
2757
+ [reverse_kind]: -expected_loss,
2758
+ diff
2759
+ },
2760
+ spread: this.to_f(Math.abs(focus_tp - reverse_position.entry) * remaining_quantity)
2761
+ };
2762
+ }
2763
+ getPositionAfterIteration(payload) {
2764
+ const { kind, iterations, with_fees = false } = payload;
2765
+ let _result = this.getPositionAfterTp({
2766
+ kind,
2767
+ include_fees: with_fees
2768
+ });
2769
+ const result = [_result];
2770
+ for (let i = 0;i < iterations - 1; i++) {
2771
+ const instance = new Strategy({
2772
+ long: _result.long,
2773
+ short: _result.short,
2774
+ config: {
2775
+ ...this.config,
2776
+ tp_percent: this.config.tp_percent + (i + 1) * 0.3
2777
+ }
2778
+ });
2779
+ _result = instance.getPositionAfterTp({
2780
+ kind,
2781
+ include_fees: with_fees
2782
+ });
2783
+ result.push(_result);
2784
+ }
2785
+ return result;
2786
+ }
2787
+ generateOppositeTrades(payload) {
2788
+ const { kind, risk_factor = 0.5, avg_entry } = payload;
2789
+ const entry = avg_entry || this.position[kind].entry;
2790
+ const stop = this.tp(kind);
2791
+ const risk = this.pnl(kind) * risk_factor;
2792
+ const risk_reward = getRiskReward({
2793
+ entry,
2794
+ stop,
2795
+ risk,
2796
+ global_config: this.config.global_config
2797
+ });
2798
+ const { entries, last_value, ...app_config } = buildAppConfig(this.config.global_config, {
2799
+ entry,
2800
+ stop,
2801
+ risk_reward,
2802
+ risk,
2803
+ symbol: this.config.global_config.symbol
2804
+ });
2805
+ const trades_to_place = determine_amount_to_buy({
2806
+ orders: entries,
2807
+ kind: app_config.kind,
2808
+ decimal_places: app_config.decimal_places,
2809
+ price_places: app_config.price_places,
2810
+ position: this.position[app_config.kind],
2811
+ existingOrders: []
2812
+ });
2813
+ const avg = determine_average_entry_and_size(trades_to_place.map((u) => ({
2814
+ price: u.entry,
2815
+ quantity: u.quantity
2816
+ })).concat([
2817
+ {
2818
+ price: this.position[app_config.kind].entry,
2819
+ quantity: this.position[app_config.kind].quantity
2820
+ }
2821
+ ]), app_config.decimal_places, app_config.price_places);
2822
+ const expected_loss = to_f(Math.abs(avg.price - stop) * avg.quantity, "%.2f");
2823
+ const profit_percent = to_f(this.pnl(kind) * 100 / (avg.price * avg.quantity), "%.3f");
2824
+ app_config.entry = this.to_f(app_config.entry);
2825
+ app_config.stop = this.to_f(app_config.stop);
2826
+ return { ...app_config, avg, loss: -expected_loss, profit_percent };
2827
+ }
2828
+ identifyGapConfig(payload) {
2829
+ const { factor, sell_factor = 1, kind, risk } = payload;
2830
+ return generateGapTp({
2831
+ long: this.position.long,
2832
+ short: this.position.short,
2833
+ factor,
2834
+ sell_factor,
2835
+ kind,
2836
+ risk,
2837
+ decimal_places: this.config.global_config.decimal_places,
2838
+ price_places: this.config.global_config.price_places
2839
+ });
2840
+ }
2841
+ analyzeProfit(payload) {
2842
+ const { reward_factor = 1, max_reward_factor, risk, kind } = payload;
2843
+ const focus_position = this.position[kind];
2844
+ const result = computeProfitDetail({
2845
+ focus_position: {
2846
+ kind,
2847
+ entry: focus_position.entry,
2848
+ quantity: focus_position.quantity,
2849
+ avg_price: focus_position.avg_price,
2850
+ avg_qty: focus_position.avg_qty
2851
+ },
2852
+ pnl: this.pnl(kind),
2853
+ strategy: {
2854
+ reward_factor,
2855
+ max_reward_factor,
2856
+ risk
2857
+ }
2858
+ });
2859
+ return result;
2860
+ }
2861
+ simulateGapReduction(payload) {
2862
+ const {
2863
+ factor,
2864
+ direction,
2865
+ sell_factor = 1,
2866
+ iterations = 10,
2867
+ risk: desired_risk,
2868
+ kind
2869
+ } = payload;
2870
+ const results = [];
2871
+ let params = {
2872
+ long: this.position.long,
2873
+ short: this.position.short,
2874
+ config: this.config
2875
+ };
2876
+ for (let i = 0;i < iterations; i++) {
2877
+ const instance = new Strategy(params);
2878
+ const { profit_percent, risk, take_profit, sell_quantity, gap_loss } = instance.identifyGapConfig({
2879
+ factor,
2880
+ sell_factor,
2881
+ kind,
2882
+ risk: desired_risk
2883
+ });
2884
+ const to_add = {
2885
+ profit_percent,
2886
+ risk,
2887
+ take_profit,
2888
+ sell_quantity,
2889
+ gap_loss,
2890
+ position: {
2891
+ long: {
2892
+ entry: this.to_f(params.long.entry),
2893
+ quantity: this.to_df(params.long.quantity)
2894
+ },
2895
+ short: {
2896
+ entry: this.to_f(params.short.entry),
2897
+ quantity: this.to_df(params.short.quantity)
2898
+ }
2899
+ }
2900
+ };
2901
+ const sell_kind = direction == "long" ? "short" : "long";
2902
+ if (sell_quantity[sell_kind] <= 0) {
2903
+ break;
2904
+ }
2905
+ results.push(to_add);
2906
+ const remaining = this.to_df(params[sell_kind].quantity - sell_quantity[sell_kind]);
2907
+ if (remaining <= 0) {
2908
+ break;
2909
+ }
2910
+ params[sell_kind].quantity = remaining;
2911
+ params[direction] = {
2912
+ entry: take_profit[direction],
2913
+ quantity: remaining
2914
+ };
2915
+ }
2916
+ const last_gap_loss = results.at(-1)?.gap_loss;
2917
+ const last_tp = results.at(-1)?.take_profit[direction];
2918
+ const entry = this.position[direction].entry;
2919
+ const quantity = this.to_df(Math.abs(last_tp - entry) / last_gap_loss);
2920
+ return {
2921
+ results,
2922
+ quantity
2923
+ };
2924
+ }
2925
+ }
2926
+ export {
2927
+ to_f,
2928
+ sortedBuildConfig,
2929
+ range,
2930
+ profitHelper,
2931
+ logWithLineNumber,
2932
+ groupIntoPairsWithSumLessThan,
2933
+ groupIntoPairs,
2934
+ groupBy,
2935
+ get_app_config_and_max_size,
2936
+ getTradeEntries,
2937
+ getRiskReward,
2938
+ getParamForField,
2939
+ getOptimumStopAndRisk,
2940
+ getOptimumHedgeFactor,
2941
+ getHedgeZone,
2942
+ getDecimalPlaces,
2943
+ generate_config_params,
2944
+ generateOptimumAppConfig,
2945
+ generateGapTp,
2946
+ formatPrice,
2947
+ fibonacci_analysis,
2948
+ extractValue,
2949
+ determine_stop_and_size,
2950
+ determine_remaining_entry,
2951
+ determine_position_size,
2952
+ determine_break_even_price,
2953
+ determine_average_entry_and_size,
2954
+ determine_amount_to_sell2 as determine_amount_to_sell,
2955
+ determine_amount_to_buy,
2956
+ determineTPSl,
2957
+ determineRewardFactor,
2958
+ determineOptimumRisk,
2959
+ determineOptimumReward,
2960
+ determineCompoundLongTrade,
2961
+ createGapPairs,
2962
+ createArray,
2963
+ computeTotalAverageForEachTrade,
2964
+ computeSellZones,
2965
+ computeRiskReward,
2966
+ computeProfitDetail,
2967
+ buildConfig,
2968
+ buildAvg,
2969
+ buildAppConfig,
2970
+ asCoins,
2971
+ allCoins,
2972
+ Strategy,
2973
+ SpecialCoins
2974
+ };