@gbozee/ultimate 0.0.2-192 → 0.0.2-194

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
@@ -38652,20 +38652,20 @@ var require_axios2 = __commonJS((exports, module) => {
38652
38652
  var reduceDescriptors = (obj, reducer) => {
38653
38653
  const descriptors2 = Object.getOwnPropertyDescriptors(obj);
38654
38654
  const reducedDescriptors = {};
38655
- forEach2(descriptors2, (descriptor, name2) => {
38655
+ forEach2(descriptors2, (descriptor, name3) => {
38656
38656
  let ret;
38657
- if ((ret = reducer(descriptor, name2, obj)) !== false) {
38658
- reducedDescriptors[name2] = ret || descriptor;
38657
+ if ((ret = reducer(descriptor, name3, obj)) !== false) {
38658
+ reducedDescriptors[name3] = ret || descriptor;
38659
38659
  }
38660
38660
  });
38661
38661
  Object.defineProperties(obj, reducedDescriptors);
38662
38662
  };
38663
38663
  var freezeMethods = (obj) => {
38664
- reduceDescriptors(obj, (descriptor, name2) => {
38665
- if (isFunction(obj) && ["arguments", "caller", "callee"].indexOf(name2) !== -1) {
38664
+ reduceDescriptors(obj, (descriptor, name3) => {
38665
+ if (isFunction(obj) && ["arguments", "caller", "callee"].indexOf(name3) !== -1) {
38666
38666
  return false;
38667
38667
  }
38668
- const value2 = obj[name2];
38668
+ const value2 = obj[name3];
38669
38669
  if (!isFunction(value2))
38670
38670
  return;
38671
38671
  descriptor.enumerable = false;
@@ -38675,7 +38675,7 @@ var require_axios2 = __commonJS((exports, module) => {
38675
38675
  }
38676
38676
  if (!descriptor.set) {
38677
38677
  descriptor.set = () => {
38678
- throw Error("Can not rewrite read-only method '" + name2 + "'");
38678
+ throw Error("Can not rewrite read-only method '" + name3 + "'");
38679
38679
  };
38680
38680
  }
38681
38681
  });
@@ -38983,8 +38983,8 @@ var require_axios2 = __commonJS((exports, module) => {
38983
38983
  params && toFormData(params, this, options);
38984
38984
  }
38985
38985
  var prototype = AxiosURLSearchParams.prototype;
38986
- prototype.append = function append(name2, value2) {
38987
- this._pairs.push([name2, value2]);
38986
+ prototype.append = function append(name3, value2) {
38987
+ this._pairs.push([name3, value2]);
38988
38988
  };
38989
38989
  prototype.toString = function toString(encoder2) {
38990
38990
  const _encode = encoder2 ? function(value2) {
@@ -39120,8 +39120,8 @@ var require_axios2 = __commonJS((exports, module) => {
39120
39120
  }
39121
39121
  }, options));
39122
39122
  }
39123
- function parsePropPath(name2) {
39124
- return utils$1.matchAll(/\w+|\[(\w*)]/g, name2).map((match) => {
39123
+ function parsePropPath(name3) {
39124
+ return utils$1.matchAll(/\w+|\[(\w*)]/g, name3).map((match) => {
39125
39125
  return match[0] === "[]" ? "" : match[1] || match[0];
39126
39126
  });
39127
39127
  }
@@ -39139,33 +39139,33 @@ var require_axios2 = __commonJS((exports, module) => {
39139
39139
  }
39140
39140
  function formDataToJSON(formData) {
39141
39141
  function buildPath(path, value2, target, index) {
39142
- let name2 = path[index++];
39143
- if (name2 === "__proto__")
39142
+ let name3 = path[index++];
39143
+ if (name3 === "__proto__")
39144
39144
  return true;
39145
- const isNumericKey = Number.isFinite(+name2);
39145
+ const isNumericKey = Number.isFinite(+name3);
39146
39146
  const isLast = index >= path.length;
39147
- name2 = !name2 && utils$1.isArray(target) ? target.length : name2;
39147
+ name3 = !name3 && utils$1.isArray(target) ? target.length : name3;
39148
39148
  if (isLast) {
39149
- if (utils$1.hasOwnProp(target, name2)) {
39150
- target[name2] = [target[name2], value2];
39149
+ if (utils$1.hasOwnProp(target, name3)) {
39150
+ target[name3] = [target[name3], value2];
39151
39151
  } else {
39152
- target[name2] = value2;
39152
+ target[name3] = value2;
39153
39153
  }
39154
39154
  return !isNumericKey;
39155
39155
  }
39156
- if (!target[name2] || !utils$1.isObject(target[name2])) {
39157
- target[name2] = [];
39156
+ if (!target[name3] || !utils$1.isObject(target[name3])) {
39157
+ target[name3] = [];
39158
39158
  }
39159
- const result = buildPath(path, value2, target[name2], index);
39160
- if (result && utils$1.isArray(target[name2])) {
39161
- target[name2] = arrayToObject(target[name2]);
39159
+ const result = buildPath(path, value2, target[name3], index);
39160
+ if (result && utils$1.isArray(target[name3])) {
39161
+ target[name3] = arrayToObject(target[name3]);
39162
39162
  }
39163
39163
  return !isNumericKey;
39164
39164
  }
39165
39165
  if (utils$1.isFormData(formData) && utils$1.isFunction(formData.entries)) {
39166
39166
  const obj = {};
39167
- utils$1.forEachEntry(formData, (name2, value2) => {
39168
- buildPath(parsePropPath(name2), value2, obj, 0);
39167
+ utils$1.forEachEntry(formData, (name3, value2) => {
39168
+ buildPath(parsePropPath(name3), value2, obj, 0);
39169
39169
  });
39170
39170
  return obj;
39171
39171
  }
@@ -39744,10 +39744,10 @@ var require_axios2 = __commonJS((exports, module) => {
39744
39744
  var CRLF_BYTES_COUNT = 2;
39745
39745
 
39746
39746
  class FormDataPart {
39747
- constructor(name2, value2) {
39747
+ constructor(name3, value2) {
39748
39748
  const { escapeName } = this.constructor;
39749
39749
  const isStringValue = utils$1.isString(value2);
39750
- let headers = `Content-Disposition: form-data; name="${escapeName(name2)}"${!isStringValue && value2.name ? `; filename="${escapeName(value2.name)}"` : ""}${CRLF}`;
39750
+ let headers = `Content-Disposition: form-data; name="${escapeName(name3)}"${!isStringValue && value2.name ? `; filename="${escapeName(value2.name)}"` : ""}${CRLF}`;
39751
39751
  if (isStringValue) {
39752
39752
  value2 = textEncoder.encode(String(value2).replace(/\r?\n|\r\n?/g, CRLF));
39753
39753
  } else {
@@ -39756,7 +39756,7 @@ var require_axios2 = __commonJS((exports, module) => {
39756
39756
  this.headers = textEncoder.encode(headers + CRLF);
39757
39757
  this.contentLength = isStringValue ? value2.byteLength : value2.size;
39758
39758
  this.size = this.headers.byteLength + this.contentLength + CRLF_BYTES_COUNT;
39759
- this.name = name2;
39759
+ this.name = name3;
39760
39760
  this.value = value2;
39761
39761
  }
39762
39762
  async* encode() {
@@ -39769,8 +39769,8 @@ var require_axios2 = __commonJS((exports, module) => {
39769
39769
  }
39770
39770
  yield CRLF_BYTES;
39771
39771
  }
39772
- static escapeName(name2) {
39773
- return String(name2).replace(/[\r\n"]/g, (match) => ({
39772
+ static escapeName(name3) {
39773
+ return String(name3).replace(/[\r\n"]/g, (match) => ({
39774
39774
  "\r": "%0D",
39775
39775
  "\n": "%0A",
39776
39776
  '"': "%22"
@@ -39792,8 +39792,8 @@ var require_axios2 = __commonJS((exports, module) => {
39792
39792
  const boundaryBytes = textEncoder.encode("--" + boundary + CRLF);
39793
39793
  const footerBytes = textEncoder.encode("--" + boundary + "--" + CRLF + CRLF);
39794
39794
  let contentLength = footerBytes.byteLength;
39795
- const parts = Array.from(form.entries()).map(([name2, value2]) => {
39796
- const part = new FormDataPart(name2, value2);
39795
+ const parts = Array.from(form.entries()).map(([name3, value2]) => {
39796
+ const part = new FormDataPart(name3, value2);
39797
39797
  contentLength += part.size;
39798
39798
  return part;
39799
39799
  });
@@ -40401,20 +40401,20 @@ var require_axios2 = __commonJS((exports, module) => {
40401
40401
  return origin2.protocol === url2.protocol && origin2.host === url2.host && (isMSIE || origin2.port === url2.port);
40402
40402
  })(new URL(platform.origin), platform.navigator && /(msie|trident)/i.test(platform.navigator.userAgent)) : () => true;
40403
40403
  var cookies = platform.hasStandardBrowserEnv ? {
40404
- write(name2, value2, expires, path, domain, secure) {
40405
- const cookie = [name2 + "=" + encodeURIComponent(value2)];
40404
+ write(name3, value2, expires, path, domain, secure) {
40405
+ const cookie = [name3 + "=" + encodeURIComponent(value2)];
40406
40406
  utils$1.isNumber(expires) && cookie.push("expires=" + new Date(expires).toGMTString());
40407
40407
  utils$1.isString(path) && cookie.push("path=" + path);
40408
40408
  utils$1.isString(domain) && cookie.push("domain=" + domain);
40409
40409
  secure === true && cookie.push("secure");
40410
40410
  document.cookie = cookie.join("; ");
40411
40411
  },
40412
- read(name2) {
40413
- const match = document.cookie.match(new RegExp("(^|;\\s*)(" + name2 + ")=([^;]*)"));
40412
+ read(name3) {
40413
+ const match = document.cookie.match(new RegExp("(^|;\\s*)(" + name3 + ")=([^;]*)"));
40414
40414
  return match ? decodeURIComponent(match[3]) : null;
40415
40415
  },
40416
- remove(name2) {
40417
- this.write(name2, "", Date.now() - 86400000);
40416
+ remove(name3) {
40417
+ this.write(name3, "", Date.now() - 86400000);
40418
40418
  }
40419
40419
  } : {
40420
40420
  write() {},
@@ -54739,35 +54739,6 @@ class AppDatabase {
54739
54739
  }
54740
54740
  return null;
54741
54741
  }
54742
- async getRunningInstanceFromDB(account, symbol, options) {
54743
- const { delay = 60 * 1000 } = options || {
54744
- delay: 60 * 1000
54745
- };
54746
- const running_instance = await this.pb.collection("trade_block_tracking").getFirstListItem(`account.owner = "${account.owner}" && account.exchange = "${account.exchange}" && symbol = "${symbol}"`, {
54747
- expand: "account"
54748
- });
54749
- if (!running_instance) {
54750
- let account_instance = await this.pb.collection("exchange_accounts").getFirstListItem(`owner = "${account.owner}" && exchange = "${account.exchange}"`);
54751
- return await this.pb.collection("trade_block_tracking").create({
54752
- account: account_instance.id,
54753
- symbol,
54754
- running: false
54755
- });
54756
- }
54757
- const updatedAt = new Date(running_instance.updated);
54758
- const now = new Date;
54759
- const diffInMinutes = (now.getTime() - updatedAt.getTime()) / delay;
54760
- if (diffInMinutes >= 1) {
54761
- await this.updateRunningInstance(running_instance.id, false);
54762
- running_instance.running = false;
54763
- }
54764
- return running_instance;
54765
- }
54766
- async updateRunningInstance(id, running) {
54767
- return await this.pb.collection("trade_block_tracking").update(id, {
54768
- running
54769
- });
54770
- }
54771
54742
  async getOrders(account, options) {
54772
54743
  const { symbol, kind } = options;
54773
54744
  const db_orders = await this.pb.collection("orders").getFullList({
@@ -55078,110 +55049,6 @@ class AppDatabase {
55078
55049
  }
55079
55050
  return null;
55080
55051
  }
55081
- async getBotViewInstance(payload) {
55082
- const { asset, main_account } = payload;
55083
- const bot_instances = await this.pb.collection("bot_view").getFullList({
55084
- filter: `asset:lower="${asset.toLowerCase()}" && main_account.owner:lower="${main_account.owner.toLowerCase()}" && main_account.exchange:lower="${main_account.exchange.toLowerCase()}"`,
55085
- expand: "main_account,secondary_account,main_long_strategy,main_short_strategy,secondary_long_strategy,secondary_short_strategy"
55086
- });
55087
- if (bot_instances.length > 0) {
55088
- const instance = bot_instances[0];
55089
- const {
55090
- main_account: main_account2,
55091
- secondary_account,
55092
- main_long_strategy,
55093
- main_short_strategy,
55094
- secondary_long_strategy,
55095
- secondary_short_strategy
55096
- } = instance.expand;
55097
- const update_boolean = (value) => {
55098
- if (!value) {
55099
- return value;
55100
- }
55101
- return {
55102
- ...value,
55103
- follow: Boolean(value.follow),
55104
- place_tp: Boolean(value.place_tp),
55105
- pause_tp: Boolean(value.pause_tp)
55106
- };
55107
- };
55108
- return {
55109
- ...instance,
55110
- main: {
55111
- account: main_account2,
55112
- symbol: instance.main_symbol,
55113
- strategy: {
55114
- long: main_long_strategy,
55115
- short: main_short_strategy
55116
- },
55117
- position: {
55118
- long: instance.main_long_position,
55119
- short: instance.main_short_position
55120
- },
55121
- config: {
55122
- long: update_boolean(instance.main_long_config),
55123
- short: update_boolean(instance.main_short_config)
55124
- }
55125
- },
55126
- secondary: {
55127
- account: secondary_account,
55128
- symbol: instance.secondary_symbol,
55129
- strategy: {
55130
- long: secondary_long_strategy,
55131
- short: secondary_short_strategy
55132
- },
55133
- position: {
55134
- long: instance.secondary_long_position,
55135
- short: instance.secondary_short_position
55136
- },
55137
- config: {
55138
- long: update_boolean(instance.secondary_long_config),
55139
- short: update_boolean(instance.secondary_short_config)
55140
- }
55141
- }
55142
- };
55143
- }
55144
- return null;
55145
- }
55146
- async getBotInstance(payload) {
55147
- const { asset, main_account } = payload;
55148
- const bot_instances = await this.pb.collection("bot_instances").getFullList({
55149
- filter: `asset:lower="${asset.toLowerCase()}" && main_account.owner:lower="${main_account.owner.toLowerCase()}" && main_account.exchange:lower="${main_account.exchange.toLowerCase()}"`
55150
- });
55151
- if (bot_instances.length > 0) {
55152
- return bot_instances[0];
55153
- }
55154
- return null;
55155
- }
55156
- async getBotState(payload) {
55157
- const { asset, main_account, running } = payload;
55158
- let filter = `bot.asset:lower="${asset.toLowerCase()}" && bot.main_account.owner:lower="${main_account.owner.toLowerCase()}" && bot.main_account.exchange:lower="${main_account.exchange.toLowerCase()}"`;
55159
- if (running !== undefined) {
55160
- filter += ` && running=${running}`;
55161
- }
55162
- const bot_states = await this.pb.collection("bot_states").getFullList({
55163
- filter
55164
- });
55165
- return bot_states;
55166
- }
55167
- async getBotOrderHistories(payload) {
55168
- const { asset, main_account, symbol, kind, type } = payload;
55169
- let filter = `field.bot.asset:lower="${asset.toLowerCase()}" && field.bot.main_account.owner:lower="${main_account.owner.toLowerCase()}" && field.bot.main_account.exchange:lower="${main_account.exchange.toLowerCase()}"`;
55170
- if (symbol) {
55171
- filter += ` && symbol:lower="${symbol.toLowerCase()}"`;
55172
- }
55173
- if (kind) {
55174
- filter += ` && kind="${kind}"`;
55175
- }
55176
- if (type) {
55177
- filter += ` && type="${type}"`;
55178
- }
55179
- const bot_order_histories = await this.pb.collection("bot_order_history").getFullList({
55180
- filter,
55181
- sort: "-created"
55182
- });
55183
- return bot_order_histories;
55184
- }
55185
55052
  async createOrUpdateWindingDownMarket(payload) {
55186
55053
  const { symbol, risk_reward = 30 } = payload;
55187
55054
  const existing_winding_down_market = await this.pb.collection("winding_down_markets").getFullList({
@@ -58652,6 +58519,8 @@ class Strategy {
58652
58519
  };
58653
58520
  }
58654
58521
  }
58522
+ // src/helpers/compound.ts
58523
+ var name2 = "";
58655
58524
  // src/types/index.ts
58656
58525
  class BaseExchange {
58657
58526
  client;
@@ -59989,6 +59858,171 @@ class BinanceExchange extends BaseExchange {
59989
59858
  async forceClosePosition(symbol, options) {
59990
59859
  return await forceClosePosition(this.client, symbol, options);
59991
59860
  }
59861
+ async getTransferableAmount(options) {
59862
+ const { asset, maxTransferLimit } = options;
59863
+ try {
59864
+ const futuresBalance = await getWalletBalance(this.client, asset);
59865
+ const allPositions = await this.client.getPositionsV3();
59866
+ const activePositions = allPositions.filter((pos) => Math.abs(pos.positionAmt) > 0);
59867
+ let totalMarginUsed = 0;
59868
+ let totalUnrealizedPnl = 0;
59869
+ for (const position2 of activePositions) {
59870
+ const positionValue = Math.abs(position2.positionAmt) * position2.markPrice;
59871
+ const leverage = await getLeverage(this.client, position2.symbol);
59872
+ const marginForPosition = positionValue / (leverage || 1);
59873
+ console.log({ leverage });
59874
+ totalMarginUsed += marginForPosition;
59875
+ totalUnrealizedPnl += position2.unRealizedProfit || 0;
59876
+ }
59877
+ const safetyMarginPercent = 0.2;
59878
+ const requiredMargin = totalMarginUsed * (1 + safetyMarginPercent);
59879
+ const adjustedBalance = futuresBalance + totalUnrealizedPnl;
59880
+ const availableForTransfer = Math.max(0, adjustedBalance - requiredMargin);
59881
+ let maxTransferableAmount = availableForTransfer;
59882
+ let appliedLimit;
59883
+ if (maxTransferLimit && maxTransferLimit > 0) {
59884
+ maxTransferableAmount = Math.min(availableForTransfer, maxTransferLimit);
59885
+ appliedLimit = maxTransferLimit;
59886
+ }
59887
+ const recommendedTransferAmount = maxTransferableAmount * 0.8;
59888
+ const marginUtilization = adjustedBalance > 0 ? requiredMargin / adjustedBalance * 100 : 0;
59889
+ return {
59890
+ asset,
59891
+ totalBalance: futuresBalance,
59892
+ availableForTransfer,
59893
+ reservedForMargin: requiredMargin,
59894
+ maxTransferableAmount,
59895
+ appliedLimit,
59896
+ recommendedTransferAmount,
59897
+ marginUtilization,
59898
+ safetyMargin: safetyMarginPercent * 100
59899
+ };
59900
+ } catch (error) {
59901
+ console.error(`Error analyzing transferable amount for ${asset}:`, error);
59902
+ throw new Error(`Failed to analyze transferable funds: ${error instanceof Error ? error.message : error}`);
59903
+ }
59904
+ }
59905
+ async previewTransfer(options) {
59906
+ const { asset, amount } = options;
59907
+ const warnings = [];
59908
+ const errors = [];
59909
+ try {
59910
+ const analysis = await this.getTransferableAmount({ asset });
59911
+ let isValid2 = true;
59912
+ if (amount <= 0) {
59913
+ errors.push("Transfer amount must be greater than zero");
59914
+ isValid2 = false;
59915
+ }
59916
+ if (amount > analysis.maxTransferableAmount) {
59917
+ errors.push(`Transfer amount (${amount}) exceeds maximum transferable amount (${analysis.maxTransferableAmount})`);
59918
+ isValid2 = false;
59919
+ }
59920
+ if (amount > analysis.recommendedTransferAmount) {
59921
+ warnings.push(`Transfer amount exceeds recommended amount (${analysis.recommendedTransferAmount.toFixed(4)}). Consider transferring a smaller amount for safety.`);
59922
+ }
59923
+ if (analysis.marginUtilization > 70) {
59924
+ warnings.push(`High margin utilization (${analysis.marginUtilization.toFixed(1)}%). Transferring funds may increase liquidation risk.`);
59925
+ }
59926
+ const balanceAfterTransfer = analysis.totalBalance - amount;
59927
+ const marginRequirementAfterTransfer = analysis.reservedForMargin;
59928
+ if (isValid2 && balanceAfterTransfer < marginRequirementAfterTransfer) {
59929
+ errors.push("Transfer would result in insufficient margin for existing positions");
59930
+ isValid2 = false;
59931
+ }
59932
+ return {
59933
+ asset,
59934
+ requestedAmount: amount,
59935
+ isValid: isValid2,
59936
+ balanceAfterTransfer,
59937
+ marginRequirementAfterTransfer,
59938
+ warnings,
59939
+ errors
59940
+ };
59941
+ } catch (error) {
59942
+ console.error(`Error previewing transfer for ${asset}:`, error);
59943
+ return {
59944
+ asset,
59945
+ requestedAmount: amount,
59946
+ isValid: false,
59947
+ balanceAfterTransfer: 0,
59948
+ marginRequirementAfterTransfer: 0,
59949
+ warnings,
59950
+ errors: [`Failed to preview transfer: ${error instanceof Error ? error.message : error}`]
59951
+ };
59952
+ }
59953
+ }
59954
+ async executeFutureToSpotTransfer(options) {
59955
+ const { asset, amount, confirm, symbol = "BTCUSDT" } = options;
59956
+ try {
59957
+ if (!confirm) {
59958
+ return {
59959
+ success: false,
59960
+ asset,
59961
+ amount,
59962
+ fromWallet: "futures",
59963
+ toWallet: "spot",
59964
+ balanceAfterTransfer: 0,
59965
+ timestamp: new Date().toISOString(),
59966
+ error: "Transfer not confirmed. Set confirm: true to execute transfer."
59967
+ };
59968
+ }
59969
+ const preview = await this.previewTransfer({ asset, amount });
59970
+ if (!preview.isValid) {
59971
+ return {
59972
+ success: false,
59973
+ asset,
59974
+ amount,
59975
+ fromWallet: "futures",
59976
+ toWallet: "spot",
59977
+ balanceAfterTransfer: 0,
59978
+ timestamp: new Date().toISOString(),
59979
+ error: `Transfer validation failed: ${preview.errors.join("; ")}`
59980
+ };
59981
+ }
59982
+ const is_coin = !["USDT", "USDC", "BUSD"].includes(asset.toUpperCase());
59983
+ const transferType = is_coin ? CONSTANTS.COIN_FUTURE_TO_SPOT : CONSTANTS.USDT_FUTURE_TO_SPOT;
59984
+ if (!this.main_client) {
59985
+ throw new Error("Main client not available for transfers");
59986
+ }
59987
+ const transferClient = this.main_client;
59988
+ const transferResult = await transferClient.submitUniversalTransfer({
59989
+ asset: asset.toUpperCase(),
59990
+ amount,
59991
+ type: transferType,
59992
+ fromSymbol: symbol,
59993
+ toSymbol: symbol
59994
+ });
59995
+ const balanceAfterTransfer = await getWalletBalance(this.client, asset);
59996
+ return {
59997
+ success: true,
59998
+ transactionId: transferResult.tranId?.toString(),
59999
+ asset,
60000
+ amount,
60001
+ fromWallet: "futures",
60002
+ toWallet: "spot",
60003
+ balanceAfterTransfer,
60004
+ timestamp: new Date().toISOString()
60005
+ };
60006
+ } catch (error) {
60007
+ console.error(`Error executing transfer for ${asset}:`, error);
60008
+ let currentBalance = 0;
60009
+ try {
60010
+ currentBalance = await getWalletBalance(this.client, asset);
60011
+ } catch (balanceError) {
60012
+ console.warn("Could not fetch balance for error response:", balanceError);
60013
+ }
60014
+ return {
60015
+ success: false,
60016
+ asset,
60017
+ amount,
60018
+ fromWallet: "futures",
60019
+ toWallet: "spot",
60020
+ balanceAfterTransfer: currentBalance,
60021
+ timestamp: new Date().toISOString(),
60022
+ error: `Transfer execution failed: ${error instanceof Error ? error.message : error}`
60023
+ };
60024
+ }
60025
+ }
59992
60026
  }
59993
60027
  function getPricePlaces(target) {
59994
60028
  const numStr = target.toString();
@@ -60314,6 +60348,11 @@ async function placeStopOrder2(client, payload) {
60314
60348
  stop: payload.final_stop,
60315
60349
  is_market: !payload.is_limit
60316
60350
  };
60351
+ if (payload.hedge) {
60352
+ let reverse_kind = payload.kind === "long" ? "short" : "long";
60353
+ order.kind = reverse_kind;
60354
+ order.is_market = false;
60355
+ }
60317
60356
  return createLimitPurchaseOrders(client, symbol, price_places, decimal_places, [order]);
60318
60357
  }
60319
60358
  async function getOpenOrders2(client, symbol, type) {
@@ -60710,6 +60749,168 @@ class BybitExchange extends BaseExchange {
60710
60749
  return getOpenOrders2(this.client, payload.symbol);
60711
60750
  }
60712
60751
  async placeBadStopEntry(payload) {}
60752
+ async getTransferableAmount(options) {
60753
+ const { asset, maxTransferLimit } = options;
60754
+ try {
60755
+ const unifiedBalance = await getWalletBalance2(this.client, asset);
60756
+ const allPositions = await this.client.getPositionInfo({
60757
+ category: "linear",
60758
+ settleCoin: asset
60759
+ });
60760
+ const activePositions = (allPositions.result.list || []).filter((pos) => Math.abs(parseFloat(pos.size || "0")) > 0);
60761
+ let totalMarginUsed = 0;
60762
+ let totalUnrealizedPnl = 0;
60763
+ for (const position2 of activePositions) {
60764
+ const positionSize = Math.abs(parseFloat(position2.size || "0"));
60765
+ const markPrice = parseFloat(position2.markPrice || "0");
60766
+ const leverage = parseFloat(position2.leverage || "1");
60767
+ const positionValue = positionSize * markPrice;
60768
+ const marginForPosition = positionValue / leverage;
60769
+ totalMarginUsed += marginForPosition;
60770
+ totalUnrealizedPnl += parseFloat(position2.unrealisedPnl || "0");
60771
+ }
60772
+ const safetyMarginPercent = 0.2;
60773
+ const requiredMargin = totalMarginUsed * (1 + safetyMarginPercent);
60774
+ const adjustedBalance = unifiedBalance + totalUnrealizedPnl;
60775
+ const availableForTransfer = Math.max(0, adjustedBalance - requiredMargin);
60776
+ let maxTransferableAmount = availableForTransfer;
60777
+ let appliedLimit;
60778
+ if (maxTransferLimit && maxTransferLimit > 0) {
60779
+ maxTransferableAmount = Math.min(availableForTransfer, maxTransferLimit);
60780
+ appliedLimit = maxTransferLimit;
60781
+ }
60782
+ const recommendedTransferAmount = maxTransferableAmount * 0.8;
60783
+ const marginUtilization = adjustedBalance > 0 ? requiredMargin / adjustedBalance * 100 : 0;
60784
+ return {
60785
+ asset,
60786
+ totalBalance: unifiedBalance,
60787
+ availableForTransfer,
60788
+ reservedForMargin: requiredMargin,
60789
+ maxTransferableAmount,
60790
+ appliedLimit,
60791
+ recommendedTransferAmount,
60792
+ marginUtilization,
60793
+ safetyMargin: safetyMarginPercent * 100
60794
+ };
60795
+ } catch (error) {
60796
+ console.error(`Error analyzing transferable amount for ${asset}:`, error);
60797
+ throw new Error(`Failed to analyze transferable funds: ${error instanceof Error ? error.message : error}`);
60798
+ }
60799
+ }
60800
+ async previewTransfer(options) {
60801
+ const { asset, amount } = options;
60802
+ const warnings = [];
60803
+ const errors = [];
60804
+ try {
60805
+ const analysis = await this.getTransferableAmount({ asset });
60806
+ let isValid2 = true;
60807
+ if (amount <= 0) {
60808
+ errors.push("Transfer amount must be greater than zero");
60809
+ isValid2 = false;
60810
+ }
60811
+ if (amount > analysis.maxTransferableAmount) {
60812
+ errors.push(`Transfer amount (${amount}) exceeds maximum transferable amount (${analysis.maxTransferableAmount})`);
60813
+ isValid2 = false;
60814
+ }
60815
+ if (amount > analysis.recommendedTransferAmount) {
60816
+ warnings.push(`Transfer amount exceeds recommended amount (${analysis.recommendedTransferAmount.toFixed(4)}). Consider transferring a smaller amount for safety.`);
60817
+ }
60818
+ if (analysis.marginUtilization > 70) {
60819
+ warnings.push(`High margin utilization (${analysis.marginUtilization.toFixed(1)}%). Transferring funds may increase liquidation risk.`);
60820
+ }
60821
+ const balanceAfterTransfer = analysis.totalBalance - amount;
60822
+ const marginRequirementAfterTransfer = analysis.reservedForMargin;
60823
+ if (isValid2 && balanceAfterTransfer < marginRequirementAfterTransfer) {
60824
+ errors.push("Transfer would result in insufficient margin for existing positions");
60825
+ isValid2 = false;
60826
+ }
60827
+ return {
60828
+ asset,
60829
+ requestedAmount: amount,
60830
+ isValid: isValid2,
60831
+ balanceAfterTransfer,
60832
+ marginRequirementAfterTransfer,
60833
+ warnings,
60834
+ errors
60835
+ };
60836
+ } catch (error) {
60837
+ console.error(`Error previewing transfer for ${asset}:`, error);
60838
+ return {
60839
+ asset,
60840
+ requestedAmount: amount,
60841
+ isValid: false,
60842
+ balanceAfterTransfer: 0,
60843
+ marginRequirementAfterTransfer: 0,
60844
+ warnings,
60845
+ errors: [
60846
+ `Failed to preview transfer: ${error instanceof Error ? error.message : error}`
60847
+ ]
60848
+ };
60849
+ }
60850
+ }
60851
+ async executeUnifiedToFundingTransfer(options) {
60852
+ const { asset, amount, confirm } = options;
60853
+ try {
60854
+ if (!confirm) {
60855
+ return {
60856
+ success: false,
60857
+ asset,
60858
+ amount,
60859
+ fromWallet: "unified",
60860
+ toWallet: "funding",
60861
+ balanceAfterTransfer: 0,
60862
+ timestamp: new Date().toISOString(),
60863
+ error: "Transfer not confirmed. Set confirm: true to execute transfer."
60864
+ };
60865
+ }
60866
+ const preview = await this.previewTransfer({ asset, amount });
60867
+ if (!preview.isValid) {
60868
+ return {
60869
+ success: false,
60870
+ asset,
60871
+ amount,
60872
+ fromWallet: "unified",
60873
+ toWallet: "funding",
60874
+ balanceAfterTransfer: 0,
60875
+ timestamp: new Date().toISOString(),
60876
+ error: `Transfer validation failed: ${preview.errors.join("; ")}`
60877
+ };
60878
+ }
60879
+ const transferResult = await this.client.createInternalTransfer(`bybit_transfer_${Date.now()}`, asset.toUpperCase(), amount.toString(), "UNIFIED", "FUND");
60880
+ if (transferResult.retCode !== 0) {
60881
+ throw new Error(`Bybit transfer failed: ${transferResult.retMsg} (code: ${transferResult.retCode})`);
60882
+ }
60883
+ const balanceAfterTransfer = await getWalletBalance2(this.client, asset);
60884
+ return {
60885
+ success: true,
60886
+ transactionId: transferResult.result?.transferId,
60887
+ asset,
60888
+ amount,
60889
+ fromWallet: "unified",
60890
+ toWallet: "funding",
60891
+ balanceAfterTransfer,
60892
+ timestamp: new Date().toISOString()
60893
+ };
60894
+ } catch (error) {
60895
+ console.error(`Error executing transfer for ${asset}:`, error);
60896
+ let currentBalance = 0;
60897
+ try {
60898
+ currentBalance = await getWalletBalance2(this.client, asset);
60899
+ } catch (balanceError) {
60900
+ console.warn("Could not fetch balance for error response:", balanceError);
60901
+ }
60902
+ return {
60903
+ success: false,
60904
+ asset,
60905
+ amount,
60906
+ fromWallet: "unified",
60907
+ toWallet: "funding",
60908
+ balanceAfterTransfer: currentBalance,
60909
+ timestamp: new Date().toISOString(),
60910
+ error: `Transfer execution failed: ${error instanceof Error ? error.message : error}`
60911
+ };
60912
+ }
60913
+ }
60713
60914
  }
60714
60915
 
60715
60916
  // src/helpers/accounts.ts
@@ -62418,9 +62619,6 @@ class ExchangeAccount {
62418
62619
  }
62419
62620
  return db_positions;
62420
62621
  }
62421
- async getRunningInstanceFromDB(symbol) {
62422
- return await this.app_db.getRunningInstanceFromDB(this.instance, symbol);
62423
- }
62424
62622
  async syncOrders(options) {
62425
62623
  const { symbol, update = false, kind } = options;
62426
62624
  if (!update && kind) {
@@ -64069,22 +64267,11 @@ class App {
64069
64267
  }
64070
64268
  async syncOrders(payload) {
64071
64269
  const exchange_account = await this.getExchangeAccount(payload.account);
64072
- const db_running_instance = await exchange_account.getRunningInstanceFromDB(payload.symbol);
64073
- if (db_running_instance.running) {
64074
- return {
64075
- new_config: null,
64076
- position: null,
64077
- config: null,
64078
- error: "Already running"
64079
- };
64080
- }
64081
- await this.app_db.updateRunningInstance(db_running_instance.id, true);
64082
64270
  await exchange_account.syncAccount({
64083
64271
  symbol: payload.symbol,
64084
64272
  kind: payload.kind,
64085
64273
  update: true
64086
64274
  });
64087
- await this.app_db.updateRunningInstance(db_running_instance.id, false);
64088
64275
  return true;
64089
64276
  }
64090
64277
  async cancelOrders(payload) {
@@ -64513,6 +64700,7 @@ async function initialize(payload) {
64513
64700
  }
64514
64701
  export {
64515
64702
  sortedBuildConfig,
64703
+ name2 as name,
64516
64704
  initialize,
64517
64705
  initApp,
64518
64706
  get_app_config_and_max_size,