@gbozee/ultimate 0.0.2-21 → 0.0.2-211

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