@gbozee/ultimate 0.0.2-20 → 0.0.2-201

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