@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.
package/dist/index.js CHANGED
@@ -57427,7 +57427,8 @@ function determineOptimumReward(payload) {
57427
57427
  low_range = 1,
57428
57428
  high_range = 199,
57429
57429
  target_loss,
57430
- distribution
57430
+ distribution,
57431
+ max_size
57431
57432
  } = payload;
57432
57433
  const criterion = app_config.strategy || "quantity";
57433
57434
  const risk_rewards = createArray(low_range, high_range, 1);
@@ -57449,6 +57450,7 @@ function determineOptimumReward(payload) {
57449
57450
  let min = Infinity;
57450
57451
  let neg_pnl = trades[0]?.neg_pnl || 0;
57451
57452
  let entry = trades.at(-1)?.entry;
57453
+ let avg_size = trades[0]?.avg_size || 0;
57452
57454
  if (!entry) {
57453
57455
  return null;
57454
57456
  }
@@ -57465,11 +57467,15 @@ function determineOptimumReward(payload) {
57465
57467
  risk_per_trade: app_config.risk_per_trade,
57466
57468
  max,
57467
57469
  min,
57470
+ avg_size,
57468
57471
  neg_pnl,
57469
57472
  entry
57470
57473
  };
57471
57474
  });
57472
57475
  func = func.filter((r2) => Boolean(r2));
57476
+ if (max_size !== undefined && max_size > 0) {
57477
+ func = func.filter((r2) => r2.avg_size <= max_size);
57478
+ }
57473
57479
  if (target_loss === undefined) {
57474
57480
  func = func.filter((r2) => {
57475
57481
  let foundIndex = r2?.result.findIndex((e2) => e2.quantity === r2.max);
@@ -57607,7 +57613,15 @@ function determineOptimumRisk(config2, payload, params) {
57607
57613
  };
57608
57614
  }
57609
57615
  function computeRiskReward(payload) {
57610
- const { app_config, entry, stop, risk_per_trade, target_loss, distribution } = payload;
57616
+ const {
57617
+ app_config,
57618
+ entry,
57619
+ stop,
57620
+ risk_per_trade,
57621
+ target_loss,
57622
+ distribution,
57623
+ max_size
57624
+ } = payload;
57611
57625
  const kind = entry > stop ? "long" : "short";
57612
57626
  app_config.kind = kind;
57613
57627
  app_config.entry = entry;
@@ -57616,12 +57630,14 @@ function computeRiskReward(payload) {
57616
57630
  const result = determineOptimumReward({
57617
57631
  app_config,
57618
57632
  target_loss,
57619
- distribution
57633
+ distribution,
57634
+ max_size
57620
57635
  });
57621
57636
  return result;
57622
57637
  }
57623
57638
  function getRiskReward(payload) {
57624
57639
  const {
57640
+ max_size,
57625
57641
  entry,
57626
57642
  stop,
57627
57643
  risk,
@@ -57644,7 +57660,8 @@ function getRiskReward(payload) {
57644
57660
  stop,
57645
57661
  risk_per_trade: risk,
57646
57662
  target_loss,
57647
- distribution
57663
+ distribution,
57664
+ max_size
57648
57665
  });
57649
57666
  if (force_exact_risk) {
57650
57667
  const new_risk_per_trade = determineOptimumRisk(global_config, {
@@ -59972,6 +59989,171 @@ class BinanceExchange extends BaseExchange {
59972
59989
  async forceClosePosition(symbol, options) {
59973
59990
  return await forceClosePosition(this.client, symbol, options);
59974
59991
  }
59992
+ async getTransferableAmount(options) {
59993
+ const { asset, maxTransferLimit } = options;
59994
+ try {
59995
+ const futuresBalance = await getWalletBalance(this.client, asset);
59996
+ const allPositions = await this.client.getPositionsV3();
59997
+ const activePositions = allPositions.filter((pos) => Math.abs(pos.positionAmt) > 0);
59998
+ let totalMarginUsed = 0;
59999
+ let totalUnrealizedPnl = 0;
60000
+ for (const position2 of activePositions) {
60001
+ const positionValue = Math.abs(position2.positionAmt) * position2.markPrice;
60002
+ const leverage = await getLeverage(this.client, position2.symbol);
60003
+ const marginForPosition = positionValue / (leverage || 1);
60004
+ console.log({ leverage });
60005
+ totalMarginUsed += marginForPosition;
60006
+ totalUnrealizedPnl += position2.unRealizedProfit || 0;
60007
+ }
60008
+ const safetyMarginPercent = 0.2;
60009
+ const requiredMargin = totalMarginUsed * (1 + safetyMarginPercent);
60010
+ const adjustedBalance = futuresBalance + totalUnrealizedPnl;
60011
+ const availableForTransfer = Math.max(0, adjustedBalance - requiredMargin);
60012
+ let maxTransferableAmount = availableForTransfer;
60013
+ let appliedLimit;
60014
+ if (maxTransferLimit && maxTransferLimit > 0) {
60015
+ maxTransferableAmount = Math.min(availableForTransfer, maxTransferLimit);
60016
+ appliedLimit = maxTransferLimit;
60017
+ }
60018
+ const recommendedTransferAmount = maxTransferableAmount * 0.8;
60019
+ const marginUtilization = adjustedBalance > 0 ? requiredMargin / adjustedBalance * 100 : 0;
60020
+ return {
60021
+ asset,
60022
+ totalBalance: futuresBalance,
60023
+ availableForTransfer,
60024
+ reservedForMargin: requiredMargin,
60025
+ maxTransferableAmount,
60026
+ appliedLimit,
60027
+ recommendedTransferAmount,
60028
+ marginUtilization,
60029
+ safetyMargin: safetyMarginPercent * 100
60030
+ };
60031
+ } catch (error) {
60032
+ console.error(`Error analyzing transferable amount for ${asset}:`, error);
60033
+ throw new Error(`Failed to analyze transferable funds: ${error instanceof Error ? error.message : error}`);
60034
+ }
60035
+ }
60036
+ async previewTransfer(options) {
60037
+ const { asset, amount } = options;
60038
+ const warnings = [];
60039
+ const errors = [];
60040
+ try {
60041
+ const analysis = await this.getTransferableAmount({ asset });
60042
+ let isValid2 = true;
60043
+ if (amount <= 0) {
60044
+ errors.push("Transfer amount must be greater than zero");
60045
+ isValid2 = false;
60046
+ }
60047
+ if (amount > analysis.maxTransferableAmount) {
60048
+ errors.push(`Transfer amount (${amount}) exceeds maximum transferable amount (${analysis.maxTransferableAmount})`);
60049
+ isValid2 = false;
60050
+ }
60051
+ if (amount > analysis.recommendedTransferAmount) {
60052
+ warnings.push(`Transfer amount exceeds recommended amount (${analysis.recommendedTransferAmount.toFixed(4)}). Consider transferring a smaller amount for safety.`);
60053
+ }
60054
+ if (analysis.marginUtilization > 70) {
60055
+ warnings.push(`High margin utilization (${analysis.marginUtilization.toFixed(1)}%). Transferring funds may increase liquidation risk.`);
60056
+ }
60057
+ const balanceAfterTransfer = analysis.totalBalance - amount;
60058
+ const marginRequirementAfterTransfer = analysis.reservedForMargin;
60059
+ if (isValid2 && balanceAfterTransfer < marginRequirementAfterTransfer) {
60060
+ errors.push("Transfer would result in insufficient margin for existing positions");
60061
+ isValid2 = false;
60062
+ }
60063
+ return {
60064
+ asset,
60065
+ requestedAmount: amount,
60066
+ isValid: isValid2,
60067
+ balanceAfterTransfer,
60068
+ marginRequirementAfterTransfer,
60069
+ warnings,
60070
+ errors
60071
+ };
60072
+ } catch (error) {
60073
+ console.error(`Error previewing transfer for ${asset}:`, error);
60074
+ return {
60075
+ asset,
60076
+ requestedAmount: amount,
60077
+ isValid: false,
60078
+ balanceAfterTransfer: 0,
60079
+ marginRequirementAfterTransfer: 0,
60080
+ warnings,
60081
+ errors: [`Failed to preview transfer: ${error instanceof Error ? error.message : error}`]
60082
+ };
60083
+ }
60084
+ }
60085
+ async executeFutureToSpotTransfer(options) {
60086
+ const { asset, amount, confirm, symbol = "BTCUSDT" } = options;
60087
+ try {
60088
+ if (!confirm) {
60089
+ return {
60090
+ success: false,
60091
+ asset,
60092
+ amount,
60093
+ fromWallet: "futures",
60094
+ toWallet: "spot",
60095
+ balanceAfterTransfer: 0,
60096
+ timestamp: new Date().toISOString(),
60097
+ error: "Transfer not confirmed. Set confirm: true to execute transfer."
60098
+ };
60099
+ }
60100
+ const preview = await this.previewTransfer({ asset, amount });
60101
+ if (!preview.isValid) {
60102
+ return {
60103
+ success: false,
60104
+ asset,
60105
+ amount,
60106
+ fromWallet: "futures",
60107
+ toWallet: "spot",
60108
+ balanceAfterTransfer: 0,
60109
+ timestamp: new Date().toISOString(),
60110
+ error: `Transfer validation failed: ${preview.errors.join("; ")}`
60111
+ };
60112
+ }
60113
+ const is_coin = !["USDT", "USDC", "BUSD"].includes(asset.toUpperCase());
60114
+ const transferType = is_coin ? CONSTANTS.COIN_FUTURE_TO_SPOT : CONSTANTS.USDT_FUTURE_TO_SPOT;
60115
+ if (!this.main_client) {
60116
+ throw new Error("Main client not available for transfers");
60117
+ }
60118
+ const transferClient = this.main_client;
60119
+ const transferResult = await transferClient.submitUniversalTransfer({
60120
+ asset: asset.toUpperCase(),
60121
+ amount,
60122
+ type: transferType,
60123
+ fromSymbol: symbol,
60124
+ toSymbol: symbol
60125
+ });
60126
+ const balanceAfterTransfer = await getWalletBalance(this.client, asset);
60127
+ return {
60128
+ success: true,
60129
+ transactionId: transferResult.tranId?.toString(),
60130
+ asset,
60131
+ amount,
60132
+ fromWallet: "futures",
60133
+ toWallet: "spot",
60134
+ balanceAfterTransfer,
60135
+ timestamp: new Date().toISOString()
60136
+ };
60137
+ } catch (error) {
60138
+ console.error(`Error executing transfer for ${asset}:`, error);
60139
+ let currentBalance = 0;
60140
+ try {
60141
+ currentBalance = await getWalletBalance(this.client, asset);
60142
+ } catch (balanceError) {
60143
+ console.warn("Could not fetch balance for error response:", balanceError);
60144
+ }
60145
+ return {
60146
+ success: false,
60147
+ asset,
60148
+ amount,
60149
+ fromWallet: "futures",
60150
+ toWallet: "spot",
60151
+ balanceAfterTransfer: currentBalance,
60152
+ timestamp: new Date().toISOString(),
60153
+ error: `Transfer execution failed: ${error instanceof Error ? error.message : error}`
60154
+ };
60155
+ }
60156
+ }
59975
60157
  }
59976
60158
  function getPricePlaces(target) {
59977
60159
  const numStr = target.toString();
@@ -60297,6 +60479,11 @@ async function placeStopOrder2(client, payload) {
60297
60479
  stop: payload.final_stop,
60298
60480
  is_market: !payload.is_limit
60299
60481
  };
60482
+ if (payload.hedge) {
60483
+ let reverse_kind = payload.kind === "long" ? "short" : "long";
60484
+ order.kind = reverse_kind;
60485
+ order.is_market = false;
60486
+ }
60300
60487
  return createLimitPurchaseOrders(client, symbol, price_places, decimal_places, [order]);
60301
60488
  }
60302
60489
  async function getOpenOrders2(client, symbol, type) {
@@ -60693,6 +60880,168 @@ class BybitExchange extends BaseExchange {
60693
60880
  return getOpenOrders2(this.client, payload.symbol);
60694
60881
  }
60695
60882
  async placeBadStopEntry(payload) {}
60883
+ async getTransferableAmount(options) {
60884
+ const { asset, maxTransferLimit } = options;
60885
+ try {
60886
+ const unifiedBalance = await getWalletBalance2(this.client, asset);
60887
+ const allPositions = await this.client.getPositionInfo({
60888
+ category: "linear",
60889
+ settleCoin: asset
60890
+ });
60891
+ const activePositions = (allPositions.result.list || []).filter((pos) => Math.abs(parseFloat(pos.size || "0")) > 0);
60892
+ let totalMarginUsed = 0;
60893
+ let totalUnrealizedPnl = 0;
60894
+ for (const position2 of activePositions) {
60895
+ const positionSize = Math.abs(parseFloat(position2.size || "0"));
60896
+ const markPrice = parseFloat(position2.markPrice || "0");
60897
+ const leverage = parseFloat(position2.leverage || "1");
60898
+ const positionValue = positionSize * markPrice;
60899
+ const marginForPosition = positionValue / leverage;
60900
+ totalMarginUsed += marginForPosition;
60901
+ totalUnrealizedPnl += parseFloat(position2.unrealisedPnl || "0");
60902
+ }
60903
+ const safetyMarginPercent = 0.2;
60904
+ const requiredMargin = totalMarginUsed * (1 + safetyMarginPercent);
60905
+ const adjustedBalance = unifiedBalance + totalUnrealizedPnl;
60906
+ const availableForTransfer = Math.max(0, adjustedBalance - requiredMargin);
60907
+ let maxTransferableAmount = availableForTransfer;
60908
+ let appliedLimit;
60909
+ if (maxTransferLimit && maxTransferLimit > 0) {
60910
+ maxTransferableAmount = Math.min(availableForTransfer, maxTransferLimit);
60911
+ appliedLimit = maxTransferLimit;
60912
+ }
60913
+ const recommendedTransferAmount = maxTransferableAmount * 0.8;
60914
+ const marginUtilization = adjustedBalance > 0 ? requiredMargin / adjustedBalance * 100 : 0;
60915
+ return {
60916
+ asset,
60917
+ totalBalance: unifiedBalance,
60918
+ availableForTransfer,
60919
+ reservedForMargin: requiredMargin,
60920
+ maxTransferableAmount,
60921
+ appliedLimit,
60922
+ recommendedTransferAmount,
60923
+ marginUtilization,
60924
+ safetyMargin: safetyMarginPercent * 100
60925
+ };
60926
+ } catch (error) {
60927
+ console.error(`Error analyzing transferable amount for ${asset}:`, error);
60928
+ throw new Error(`Failed to analyze transferable funds: ${error instanceof Error ? error.message : error}`);
60929
+ }
60930
+ }
60931
+ async previewTransfer(options) {
60932
+ const { asset, amount } = options;
60933
+ const warnings = [];
60934
+ const errors = [];
60935
+ try {
60936
+ const analysis = await this.getTransferableAmount({ asset });
60937
+ let isValid2 = true;
60938
+ if (amount <= 0) {
60939
+ errors.push("Transfer amount must be greater than zero");
60940
+ isValid2 = false;
60941
+ }
60942
+ if (amount > analysis.maxTransferableAmount) {
60943
+ errors.push(`Transfer amount (${amount}) exceeds maximum transferable amount (${analysis.maxTransferableAmount})`);
60944
+ isValid2 = false;
60945
+ }
60946
+ if (amount > analysis.recommendedTransferAmount) {
60947
+ warnings.push(`Transfer amount exceeds recommended amount (${analysis.recommendedTransferAmount.toFixed(4)}). Consider transferring a smaller amount for safety.`);
60948
+ }
60949
+ if (analysis.marginUtilization > 70) {
60950
+ warnings.push(`High margin utilization (${analysis.marginUtilization.toFixed(1)}%). Transferring funds may increase liquidation risk.`);
60951
+ }
60952
+ const balanceAfterTransfer = analysis.totalBalance - amount;
60953
+ const marginRequirementAfterTransfer = analysis.reservedForMargin;
60954
+ if (isValid2 && balanceAfterTransfer < marginRequirementAfterTransfer) {
60955
+ errors.push("Transfer would result in insufficient margin for existing positions");
60956
+ isValid2 = false;
60957
+ }
60958
+ return {
60959
+ asset,
60960
+ requestedAmount: amount,
60961
+ isValid: isValid2,
60962
+ balanceAfterTransfer,
60963
+ marginRequirementAfterTransfer,
60964
+ warnings,
60965
+ errors
60966
+ };
60967
+ } catch (error) {
60968
+ console.error(`Error previewing transfer for ${asset}:`, error);
60969
+ return {
60970
+ asset,
60971
+ requestedAmount: amount,
60972
+ isValid: false,
60973
+ balanceAfterTransfer: 0,
60974
+ marginRequirementAfterTransfer: 0,
60975
+ warnings,
60976
+ errors: [
60977
+ `Failed to preview transfer: ${error instanceof Error ? error.message : error}`
60978
+ ]
60979
+ };
60980
+ }
60981
+ }
60982
+ async executeUnifiedToFundingTransfer(options) {
60983
+ const { asset, amount, confirm } = options;
60984
+ try {
60985
+ if (!confirm) {
60986
+ return {
60987
+ success: false,
60988
+ asset,
60989
+ amount,
60990
+ fromWallet: "unified",
60991
+ toWallet: "funding",
60992
+ balanceAfterTransfer: 0,
60993
+ timestamp: new Date().toISOString(),
60994
+ error: "Transfer not confirmed. Set confirm: true to execute transfer."
60995
+ };
60996
+ }
60997
+ const preview = await this.previewTransfer({ asset, amount });
60998
+ if (!preview.isValid) {
60999
+ return {
61000
+ success: false,
61001
+ asset,
61002
+ amount,
61003
+ fromWallet: "unified",
61004
+ toWallet: "funding",
61005
+ balanceAfterTransfer: 0,
61006
+ timestamp: new Date().toISOString(),
61007
+ error: `Transfer validation failed: ${preview.errors.join("; ")}`
61008
+ };
61009
+ }
61010
+ const transferResult = await this.client.createInternalTransfer(`bybit_transfer_${Date.now()}`, asset.toUpperCase(), amount.toString(), "UNIFIED", "FUND");
61011
+ if (transferResult.retCode !== 0) {
61012
+ throw new Error(`Bybit transfer failed: ${transferResult.retMsg} (code: ${transferResult.retCode})`);
61013
+ }
61014
+ const balanceAfterTransfer = await getWalletBalance2(this.client, asset);
61015
+ return {
61016
+ success: true,
61017
+ transactionId: transferResult.result?.transferId,
61018
+ asset,
61019
+ amount,
61020
+ fromWallet: "unified",
61021
+ toWallet: "funding",
61022
+ balanceAfterTransfer,
61023
+ timestamp: new Date().toISOString()
61024
+ };
61025
+ } catch (error) {
61026
+ console.error(`Error executing transfer for ${asset}:`, error);
61027
+ let currentBalance = 0;
61028
+ try {
61029
+ currentBalance = await getWalletBalance2(this.client, asset);
61030
+ } catch (balanceError) {
61031
+ console.warn("Could not fetch balance for error response:", balanceError);
61032
+ }
61033
+ return {
61034
+ success: false,
61035
+ asset,
61036
+ amount,
61037
+ fromWallet: "unified",
61038
+ toWallet: "funding",
61039
+ balanceAfterTransfer: currentBalance,
61040
+ timestamp: new Date().toISOString(),
61041
+ error: `Transfer execution failed: ${error instanceof Error ? error.message : error}`
61042
+ };
61043
+ }
61044
+ }
60696
61045
  }
60697
61046
 
60698
61047
  // src/helpers/accounts.ts