@gbozee/ultimate 0.0.2-191 → 0.0.2-193

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.
@@ -64163,7 +64163,8 @@ function determineOptimumReward(payload) {
64163
64163
  low_range = 1,
64164
64164
  high_range = 199,
64165
64165
  target_loss,
64166
- distribution
64166
+ distribution,
64167
+ max_size
64167
64168
  } = payload;
64168
64169
  const criterion = app_config.strategy || "quantity";
64169
64170
  const risk_rewards = createArray(low_range, high_range, 1);
@@ -64185,6 +64186,7 @@ function determineOptimumReward(payload) {
64185
64186
  let min = Infinity;
64186
64187
  let neg_pnl = trades[0]?.neg_pnl || 0;
64187
64188
  let entry = trades.at(-1)?.entry;
64189
+ let avg_size = trades[0]?.avg_size || 0;
64188
64190
  if (!entry) {
64189
64191
  return null;
64190
64192
  }
@@ -64201,11 +64203,15 @@ function determineOptimumReward(payload) {
64201
64203
  risk_per_trade: app_config.risk_per_trade,
64202
64204
  max,
64203
64205
  min,
64206
+ avg_size,
64204
64207
  neg_pnl,
64205
64208
  entry
64206
64209
  };
64207
64210
  });
64208
64211
  func = func.filter((r2) => Boolean(r2));
64212
+ if (max_size !== undefined && max_size > 0) {
64213
+ func = func.filter((r2) => r2.avg_size <= max_size);
64214
+ }
64209
64215
  if (target_loss === undefined) {
64210
64216
  func = func.filter((r2) => {
64211
64217
  let foundIndex = r2?.result.findIndex((e2) => e2.quantity === r2.max);
@@ -64343,7 +64349,15 @@ function determineOptimumRisk(config2, payload, params) {
64343
64349
  };
64344
64350
  }
64345
64351
  function computeRiskReward(payload) {
64346
- const { app_config, entry, stop, risk_per_trade, target_loss, distribution } = payload;
64352
+ const {
64353
+ app_config,
64354
+ entry,
64355
+ stop,
64356
+ risk_per_trade,
64357
+ target_loss,
64358
+ distribution,
64359
+ max_size
64360
+ } = payload;
64347
64361
  const kind = entry > stop ? "long" : "short";
64348
64362
  app_config.kind = kind;
64349
64363
  app_config.entry = entry;
@@ -64352,12 +64366,14 @@ function computeRiskReward(payload) {
64352
64366
  const result = determineOptimumReward({
64353
64367
  app_config,
64354
64368
  target_loss,
64355
- distribution
64369
+ distribution,
64370
+ max_size
64356
64371
  });
64357
64372
  return result;
64358
64373
  }
64359
64374
  function getRiskReward(payload) {
64360
64375
  const {
64376
+ max_size,
64361
64377
  entry,
64362
64378
  stop,
64363
64379
  risk,
@@ -64380,7 +64396,8 @@ function getRiskReward(payload) {
64380
64396
  stop,
64381
64397
  risk_per_trade: risk,
64382
64398
  target_loss,
64383
- distribution
64399
+ distribution,
64400
+ max_size
64384
64401
  });
64385
64402
  if (force_exact_risk) {
64386
64403
  const new_risk_per_trade = determineOptimumRisk(global_config, {
@@ -66610,6 +66627,171 @@ class BinanceExchange extends BaseExchange {
66610
66627
  async forceClosePosition(symbol, options) {
66611
66628
  return await forceClosePosition(this.client, symbol, options);
66612
66629
  }
66630
+ async getTransferableAmount(options) {
66631
+ const { asset, maxTransferLimit } = options;
66632
+ try {
66633
+ const futuresBalance = await getWalletBalance(this.client, asset);
66634
+ const allPositions = await this.client.getPositionsV3();
66635
+ const activePositions = allPositions.filter((pos) => Math.abs(pos.positionAmt) > 0);
66636
+ let totalMarginUsed = 0;
66637
+ let totalUnrealizedPnl = 0;
66638
+ for (const position2 of activePositions) {
66639
+ const positionValue = Math.abs(position2.positionAmt) * position2.markPrice;
66640
+ const leverage = await getLeverage(this.client, position2.symbol);
66641
+ const marginForPosition = positionValue / (leverage || 1);
66642
+ console.log({ leverage });
66643
+ totalMarginUsed += marginForPosition;
66644
+ totalUnrealizedPnl += position2.unRealizedProfit || 0;
66645
+ }
66646
+ const safetyMarginPercent = 0.2;
66647
+ const requiredMargin = totalMarginUsed * (1 + safetyMarginPercent);
66648
+ const adjustedBalance = futuresBalance + totalUnrealizedPnl;
66649
+ const availableForTransfer = Math.max(0, adjustedBalance - requiredMargin);
66650
+ let maxTransferableAmount = availableForTransfer;
66651
+ let appliedLimit;
66652
+ if (maxTransferLimit && maxTransferLimit > 0) {
66653
+ maxTransferableAmount = Math.min(availableForTransfer, maxTransferLimit);
66654
+ appliedLimit = maxTransferLimit;
66655
+ }
66656
+ const recommendedTransferAmount = maxTransferableAmount * 0.8;
66657
+ const marginUtilization = adjustedBalance > 0 ? requiredMargin / adjustedBalance * 100 : 0;
66658
+ return {
66659
+ asset,
66660
+ totalBalance: futuresBalance,
66661
+ availableForTransfer,
66662
+ reservedForMargin: requiredMargin,
66663
+ maxTransferableAmount,
66664
+ appliedLimit,
66665
+ recommendedTransferAmount,
66666
+ marginUtilization,
66667
+ safetyMargin: safetyMarginPercent * 100
66668
+ };
66669
+ } catch (error) {
66670
+ console.error(`Error analyzing transferable amount for ${asset}:`, error);
66671
+ throw new Error(`Failed to analyze transferable funds: ${error instanceof Error ? error.message : error}`);
66672
+ }
66673
+ }
66674
+ async previewTransfer(options) {
66675
+ const { asset, amount } = options;
66676
+ const warnings = [];
66677
+ const errors = [];
66678
+ try {
66679
+ const analysis = await this.getTransferableAmount({ asset });
66680
+ let isValid3 = true;
66681
+ if (amount <= 0) {
66682
+ errors.push("Transfer amount must be greater than zero");
66683
+ isValid3 = false;
66684
+ }
66685
+ if (amount > analysis.maxTransferableAmount) {
66686
+ errors.push(`Transfer amount (${amount}) exceeds maximum transferable amount (${analysis.maxTransferableAmount})`);
66687
+ isValid3 = false;
66688
+ }
66689
+ if (amount > analysis.recommendedTransferAmount) {
66690
+ warnings.push(`Transfer amount exceeds recommended amount (${analysis.recommendedTransferAmount.toFixed(4)}). Consider transferring a smaller amount for safety.`);
66691
+ }
66692
+ if (analysis.marginUtilization > 70) {
66693
+ warnings.push(`High margin utilization (${analysis.marginUtilization.toFixed(1)}%). Transferring funds may increase liquidation risk.`);
66694
+ }
66695
+ const balanceAfterTransfer = analysis.totalBalance - amount;
66696
+ const marginRequirementAfterTransfer = analysis.reservedForMargin;
66697
+ if (isValid3 && balanceAfterTransfer < marginRequirementAfterTransfer) {
66698
+ errors.push("Transfer would result in insufficient margin for existing positions");
66699
+ isValid3 = false;
66700
+ }
66701
+ return {
66702
+ asset,
66703
+ requestedAmount: amount,
66704
+ isValid: isValid3,
66705
+ balanceAfterTransfer,
66706
+ marginRequirementAfterTransfer,
66707
+ warnings,
66708
+ errors
66709
+ };
66710
+ } catch (error) {
66711
+ console.error(`Error previewing transfer for ${asset}:`, error);
66712
+ return {
66713
+ asset,
66714
+ requestedAmount: amount,
66715
+ isValid: false,
66716
+ balanceAfterTransfer: 0,
66717
+ marginRequirementAfterTransfer: 0,
66718
+ warnings,
66719
+ errors: [`Failed to preview transfer: ${error instanceof Error ? error.message : error}`]
66720
+ };
66721
+ }
66722
+ }
66723
+ async executeFutureToSpotTransfer(options) {
66724
+ const { asset, amount, confirm, symbol = "BTCUSDT" } = options;
66725
+ try {
66726
+ if (!confirm) {
66727
+ return {
66728
+ success: false,
66729
+ asset,
66730
+ amount,
66731
+ fromWallet: "futures",
66732
+ toWallet: "spot",
66733
+ balanceAfterTransfer: 0,
66734
+ timestamp: new Date().toISOString(),
66735
+ error: "Transfer not confirmed. Set confirm: true to execute transfer."
66736
+ };
66737
+ }
66738
+ const preview = await this.previewTransfer({ asset, amount });
66739
+ if (!preview.isValid) {
66740
+ return {
66741
+ success: false,
66742
+ asset,
66743
+ amount,
66744
+ fromWallet: "futures",
66745
+ toWallet: "spot",
66746
+ balanceAfterTransfer: 0,
66747
+ timestamp: new Date().toISOString(),
66748
+ error: `Transfer validation failed: ${preview.errors.join("; ")}`
66749
+ };
66750
+ }
66751
+ const is_coin = !["USDT", "USDC", "BUSD"].includes(asset.toUpperCase());
66752
+ const transferType = is_coin ? CONSTANTS.COIN_FUTURE_TO_SPOT : CONSTANTS.USDT_FUTURE_TO_SPOT;
66753
+ if (!this.main_client) {
66754
+ throw new Error("Main client not available for transfers");
66755
+ }
66756
+ const transferClient = this.main_client;
66757
+ const transferResult = await transferClient.submitUniversalTransfer({
66758
+ asset: asset.toUpperCase(),
66759
+ amount,
66760
+ type: transferType,
66761
+ fromSymbol: symbol,
66762
+ toSymbol: symbol
66763
+ });
66764
+ const balanceAfterTransfer = await getWalletBalance(this.client, asset);
66765
+ return {
66766
+ success: true,
66767
+ transactionId: transferResult.tranId?.toString(),
66768
+ asset,
66769
+ amount,
66770
+ fromWallet: "futures",
66771
+ toWallet: "spot",
66772
+ balanceAfterTransfer,
66773
+ timestamp: new Date().toISOString()
66774
+ };
66775
+ } catch (error) {
66776
+ console.error(`Error executing transfer for ${asset}:`, error);
66777
+ let currentBalance = 0;
66778
+ try {
66779
+ currentBalance = await getWalletBalance(this.client, asset);
66780
+ } catch (balanceError) {
66781
+ console.warn("Could not fetch balance for error response:", balanceError);
66782
+ }
66783
+ return {
66784
+ success: false,
66785
+ asset,
66786
+ amount,
66787
+ fromWallet: "futures",
66788
+ toWallet: "spot",
66789
+ balanceAfterTransfer: currentBalance,
66790
+ timestamp: new Date().toISOString(),
66791
+ error: `Transfer execution failed: ${error instanceof Error ? error.message : error}`
66792
+ };
66793
+ }
66794
+ }
66613
66795
  }
66614
66796
  function getPricePlaces(target) {
66615
66797
  const numStr = target.toString();
@@ -66935,6 +67117,11 @@ async function placeStopOrder2(client, payload) {
66935
67117
  stop: payload.final_stop,
66936
67118
  is_market: !payload.is_limit
66937
67119
  };
67120
+ if (payload.hedge) {
67121
+ let reverse_kind = payload.kind === "long" ? "short" : "long";
67122
+ order.kind = reverse_kind;
67123
+ order.is_market = false;
67124
+ }
66938
67125
  return createLimitPurchaseOrders(client, symbol, price_places, decimal_places, [order]);
66939
67126
  }
66940
67127
  async function getOpenOrders2(client, symbol, type) {
@@ -67331,6 +67518,168 @@ class BybitExchange extends BaseExchange {
67331
67518
  return getOpenOrders2(this.client, payload.symbol);
67332
67519
  }
67333
67520
  async placeBadStopEntry(payload) {}
67521
+ async getTransferableAmount(options) {
67522
+ const { asset, maxTransferLimit } = options;
67523
+ try {
67524
+ const unifiedBalance = await getWalletBalance2(this.client, asset);
67525
+ const allPositions = await this.client.getPositionInfo({
67526
+ category: "linear",
67527
+ settleCoin: asset
67528
+ });
67529
+ const activePositions = (allPositions.result.list || []).filter((pos) => Math.abs(parseFloat(pos.size || "0")) > 0);
67530
+ let totalMarginUsed = 0;
67531
+ let totalUnrealizedPnl = 0;
67532
+ for (const position2 of activePositions) {
67533
+ const positionSize = Math.abs(parseFloat(position2.size || "0"));
67534
+ const markPrice = parseFloat(position2.markPrice || "0");
67535
+ const leverage = parseFloat(position2.leverage || "1");
67536
+ const positionValue = positionSize * markPrice;
67537
+ const marginForPosition = positionValue / leverage;
67538
+ totalMarginUsed += marginForPosition;
67539
+ totalUnrealizedPnl += parseFloat(position2.unrealisedPnl || "0");
67540
+ }
67541
+ const safetyMarginPercent = 0.2;
67542
+ const requiredMargin = totalMarginUsed * (1 + safetyMarginPercent);
67543
+ const adjustedBalance = unifiedBalance + totalUnrealizedPnl;
67544
+ const availableForTransfer = Math.max(0, adjustedBalance - requiredMargin);
67545
+ let maxTransferableAmount = availableForTransfer;
67546
+ let appliedLimit;
67547
+ if (maxTransferLimit && maxTransferLimit > 0) {
67548
+ maxTransferableAmount = Math.min(availableForTransfer, maxTransferLimit);
67549
+ appliedLimit = maxTransferLimit;
67550
+ }
67551
+ const recommendedTransferAmount = maxTransferableAmount * 0.8;
67552
+ const marginUtilization = adjustedBalance > 0 ? requiredMargin / adjustedBalance * 100 : 0;
67553
+ return {
67554
+ asset,
67555
+ totalBalance: unifiedBalance,
67556
+ availableForTransfer,
67557
+ reservedForMargin: requiredMargin,
67558
+ maxTransferableAmount,
67559
+ appliedLimit,
67560
+ recommendedTransferAmount,
67561
+ marginUtilization,
67562
+ safetyMargin: safetyMarginPercent * 100
67563
+ };
67564
+ } catch (error) {
67565
+ console.error(`Error analyzing transferable amount for ${asset}:`, error);
67566
+ throw new Error(`Failed to analyze transferable funds: ${error instanceof Error ? error.message : error}`);
67567
+ }
67568
+ }
67569
+ async previewTransfer(options) {
67570
+ const { asset, amount } = options;
67571
+ const warnings = [];
67572
+ const errors = [];
67573
+ try {
67574
+ const analysis = await this.getTransferableAmount({ asset });
67575
+ let isValid3 = true;
67576
+ if (amount <= 0) {
67577
+ errors.push("Transfer amount must be greater than zero");
67578
+ isValid3 = false;
67579
+ }
67580
+ if (amount > analysis.maxTransferableAmount) {
67581
+ errors.push(`Transfer amount (${amount}) exceeds maximum transferable amount (${analysis.maxTransferableAmount})`);
67582
+ isValid3 = false;
67583
+ }
67584
+ if (amount > analysis.recommendedTransferAmount) {
67585
+ warnings.push(`Transfer amount exceeds recommended amount (${analysis.recommendedTransferAmount.toFixed(4)}). Consider transferring a smaller amount for safety.`);
67586
+ }
67587
+ if (analysis.marginUtilization > 70) {
67588
+ warnings.push(`High margin utilization (${analysis.marginUtilization.toFixed(1)}%). Transferring funds may increase liquidation risk.`);
67589
+ }
67590
+ const balanceAfterTransfer = analysis.totalBalance - amount;
67591
+ const marginRequirementAfterTransfer = analysis.reservedForMargin;
67592
+ if (isValid3 && balanceAfterTransfer < marginRequirementAfterTransfer) {
67593
+ errors.push("Transfer would result in insufficient margin for existing positions");
67594
+ isValid3 = false;
67595
+ }
67596
+ return {
67597
+ asset,
67598
+ requestedAmount: amount,
67599
+ isValid: isValid3,
67600
+ balanceAfterTransfer,
67601
+ marginRequirementAfterTransfer,
67602
+ warnings,
67603
+ errors
67604
+ };
67605
+ } catch (error) {
67606
+ console.error(`Error previewing transfer for ${asset}:`, error);
67607
+ return {
67608
+ asset,
67609
+ requestedAmount: amount,
67610
+ isValid: false,
67611
+ balanceAfterTransfer: 0,
67612
+ marginRequirementAfterTransfer: 0,
67613
+ warnings,
67614
+ errors: [
67615
+ `Failed to preview transfer: ${error instanceof Error ? error.message : error}`
67616
+ ]
67617
+ };
67618
+ }
67619
+ }
67620
+ async executeUnifiedToFundingTransfer(options) {
67621
+ const { asset, amount, confirm } = options;
67622
+ try {
67623
+ if (!confirm) {
67624
+ return {
67625
+ success: false,
67626
+ asset,
67627
+ amount,
67628
+ fromWallet: "unified",
67629
+ toWallet: "funding",
67630
+ balanceAfterTransfer: 0,
67631
+ timestamp: new Date().toISOString(),
67632
+ error: "Transfer not confirmed. Set confirm: true to execute transfer."
67633
+ };
67634
+ }
67635
+ const preview = await this.previewTransfer({ asset, amount });
67636
+ if (!preview.isValid) {
67637
+ return {
67638
+ success: false,
67639
+ asset,
67640
+ amount,
67641
+ fromWallet: "unified",
67642
+ toWallet: "funding",
67643
+ balanceAfterTransfer: 0,
67644
+ timestamp: new Date().toISOString(),
67645
+ error: `Transfer validation failed: ${preview.errors.join("; ")}`
67646
+ };
67647
+ }
67648
+ const transferResult = await this.client.createInternalTransfer(`bybit_transfer_${Date.now()}`, asset.toUpperCase(), amount.toString(), "UNIFIED", "FUND");
67649
+ if (transferResult.retCode !== 0) {
67650
+ throw new Error(`Bybit transfer failed: ${transferResult.retMsg} (code: ${transferResult.retCode})`);
67651
+ }
67652
+ const balanceAfterTransfer = await getWalletBalance2(this.client, asset);
67653
+ return {
67654
+ success: true,
67655
+ transactionId: transferResult.result?.transferId,
67656
+ asset,
67657
+ amount,
67658
+ fromWallet: "unified",
67659
+ toWallet: "funding",
67660
+ balanceAfterTransfer,
67661
+ timestamp: new Date().toISOString()
67662
+ };
67663
+ } catch (error) {
67664
+ console.error(`Error executing transfer for ${asset}:`, error);
67665
+ let currentBalance = 0;
67666
+ try {
67667
+ currentBalance = await getWalletBalance2(this.client, asset);
67668
+ } catch (balanceError) {
67669
+ console.warn("Could not fetch balance for error response:", balanceError);
67670
+ }
67671
+ return {
67672
+ success: false,
67673
+ asset,
67674
+ amount,
67675
+ fromWallet: "unified",
67676
+ toWallet: "funding",
67677
+ balanceAfterTransfer: currentBalance,
67678
+ timestamp: new Date().toISOString(),
67679
+ error: `Transfer execution failed: ${error instanceof Error ? error.message : error}`
67680
+ };
67681
+ }
67682
+ }
67334
67683
  }
67335
67684
 
67336
67685
  // src/helpers/accounts.ts