@gbozee/ultimate 0.0.2-150 → 0.0.2-152

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
@@ -16579,8 +16579,8 @@ var require_combined_stream = __commonJS((exports, module) => {
16579
16579
  stream2.pipe(this, { end: false });
16580
16580
  return;
16581
16581
  }
16582
- var value2 = stream2;
16583
- this.write(value2);
16582
+ var value = stream2;
16583
+ this.write(value);
16584
16584
  this._getNext();
16585
16585
  };
16586
16586
  CombinedStream.prototype._handleErrors = function(stream2) {
@@ -25793,8 +25793,8 @@ var require_get = __commonJS((exports, module) => {
25793
25793
  var desc = !!hasProtoAccessor && gOPD && gOPD(Object.prototype, "__proto__");
25794
25794
  var $Object = Object;
25795
25795
  var $getPrototypeOf = $Object.getPrototypeOf;
25796
- module.exports = desc && typeof desc.get === "function" ? callBind([desc.get]) : typeof $getPrototypeOf === "function" ? function getDunder(value2) {
25797
- return $getPrototypeOf(value2 == null ? value2 : $Object(value2));
25796
+ module.exports = desc && typeof desc.get === "function" ? callBind([desc.get]) : typeof $getPrototypeOf === "function" ? function getDunder(value) {
25797
+ return $getPrototypeOf(value == null ? value : $Object(value));
25798
25798
  } : false;
25799
25799
  });
25800
25800
 
@@ -25966,26 +25966,26 @@ var require_get_intrinsic = __commonJS((exports, module) => {
25966
25966
  }
25967
25967
  var errorProto;
25968
25968
  var doEval = function doEval(name2) {
25969
- var value2;
25969
+ var value;
25970
25970
  if (name2 === "%AsyncFunction%") {
25971
- value2 = getEvalledConstructor("async function () {}");
25971
+ value = getEvalledConstructor("async function () {}");
25972
25972
  } else if (name2 === "%GeneratorFunction%") {
25973
- value2 = getEvalledConstructor("function* () {}");
25973
+ value = getEvalledConstructor("function* () {}");
25974
25974
  } else if (name2 === "%AsyncGeneratorFunction%") {
25975
- value2 = getEvalledConstructor("async function* () {}");
25975
+ value = getEvalledConstructor("async function* () {}");
25976
25976
  } else if (name2 === "%AsyncGenerator%") {
25977
25977
  var fn = doEval("%AsyncGeneratorFunction%");
25978
25978
  if (fn) {
25979
- value2 = fn.prototype;
25979
+ value = fn.prototype;
25980
25980
  }
25981
25981
  } else if (name2 === "%AsyncIteratorPrototype%") {
25982
25982
  var gen = doEval("%AsyncGenerator%");
25983
25983
  if (gen && getProto) {
25984
- value2 = getProto(gen.prototype);
25984
+ value = getProto(gen.prototype);
25985
25985
  }
25986
25986
  }
25987
- INTRINSICS[name2] = value2;
25988
- return value2;
25987
+ INTRINSICS[name2] = value;
25988
+ return value;
25989
25989
  };
25990
25990
  var LEGACY_ALIASES = {
25991
25991
  __proto__: null,
@@ -26072,17 +26072,17 @@ var require_get_intrinsic = __commonJS((exports, module) => {
26072
26072
  intrinsicName = "%" + alias[0] + "%";
26073
26073
  }
26074
26074
  if (hasOwn(INTRINSICS, intrinsicName)) {
26075
- var value2 = INTRINSICS[intrinsicName];
26076
- if (value2 === needsEval) {
26077
- value2 = doEval(intrinsicName);
26075
+ var value = INTRINSICS[intrinsicName];
26076
+ if (value === needsEval) {
26077
+ value = doEval(intrinsicName);
26078
26078
  }
26079
- if (typeof value2 === "undefined" && !allowMissing) {
26079
+ if (typeof value === "undefined" && !allowMissing) {
26080
26080
  throw new $TypeError("intrinsic " + name2 + " exists, but is not available. Please file an issue!");
26081
26081
  }
26082
26082
  return {
26083
26083
  alias,
26084
26084
  name: intrinsicName,
26085
- value: value2
26085
+ value
26086
26086
  };
26087
26087
  }
26088
26088
  throw new $SyntaxError("intrinsic " + name2 + " does not exist!");
@@ -26101,7 +26101,7 @@ var require_get_intrinsic = __commonJS((exports, module) => {
26101
26101
  var intrinsicBaseName = parts.length > 0 ? parts[0] : "";
26102
26102
  var intrinsic = getBaseIntrinsic("%" + intrinsicBaseName + "%", allowMissing);
26103
26103
  var intrinsicRealName = intrinsic.name;
26104
- var value2 = intrinsic.value;
26104
+ var value = intrinsic.value;
26105
26105
  var skipFurtherCaching = false;
26106
26106
  var alias = intrinsic.alias;
26107
26107
  if (alias) {
@@ -26121,32 +26121,32 @@ var require_get_intrinsic = __commonJS((exports, module) => {
26121
26121
  intrinsicBaseName += "." + part;
26122
26122
  intrinsicRealName = "%" + intrinsicBaseName + "%";
26123
26123
  if (hasOwn(INTRINSICS, intrinsicRealName)) {
26124
- value2 = INTRINSICS[intrinsicRealName];
26125
- } else if (value2 != null) {
26126
- if (!(part in value2)) {
26124
+ value = INTRINSICS[intrinsicRealName];
26125
+ } else if (value != null) {
26126
+ if (!(part in value)) {
26127
26127
  if (!allowMissing) {
26128
26128
  throw new $TypeError("base intrinsic for " + name2 + " exists, but the property is not available.");
26129
26129
  }
26130
26130
  return;
26131
26131
  }
26132
26132
  if ($gOPD && i2 + 1 >= parts.length) {
26133
- var desc = $gOPD(value2, part);
26133
+ var desc = $gOPD(value, part);
26134
26134
  isOwn = !!desc;
26135
26135
  if (isOwn && "get" in desc && !("originalValue" in desc.get)) {
26136
- value2 = desc.get;
26136
+ value = desc.get;
26137
26137
  } else {
26138
- value2 = value2[part];
26138
+ value = value[part];
26139
26139
  }
26140
26140
  } else {
26141
- isOwn = hasOwn(value2, part);
26142
- value2 = value2[part];
26141
+ isOwn = hasOwn(value, part);
26142
+ value = value[part];
26143
26143
  }
26144
26144
  if (isOwn && !skipFurtherCaching) {
26145
- INTRINSICS[intrinsicRealName] = value2;
26145
+ INTRINSICS[intrinsicRealName] = value;
26146
26146
  }
26147
26147
  }
26148
26148
  }
26149
- return value2;
26149
+ return value;
26150
26150
  };
26151
26151
  });
26152
26152
 
@@ -26166,7 +26166,7 @@ var require_es_set_tostringtag = __commonJS((exports, module) => {
26166
26166
  var hasOwn = require_hasown();
26167
26167
  var $TypeError = require_type();
26168
26168
  var toStringTag = hasToStringTag ? Symbol.toStringTag : null;
26169
- module.exports = function setToStringTag(object, value2) {
26169
+ module.exports = function setToStringTag(object, value) {
26170
26170
  var overrideIfSet = arguments.length > 2 && !!arguments[2] && arguments[2].force;
26171
26171
  var nonConfigurable = arguments.length > 2 && !!arguments[2] && arguments[2].nonConfigurable;
26172
26172
  if (typeof overrideIfSet !== "undefined" && typeof overrideIfSet !== "boolean" || typeof nonConfigurable !== "undefined" && typeof nonConfigurable !== "boolean") {
@@ -26177,11 +26177,11 @@ var require_es_set_tostringtag = __commonJS((exports, module) => {
26177
26177
  $defineProperty(object, toStringTag, {
26178
26178
  configurable: !nonConfigurable,
26179
26179
  enumerable: false,
26180
- value: value2,
26180
+ value,
26181
26181
  writable: false
26182
26182
  });
26183
26183
  } else {
26184
- object[toStringTag] = value2;
26184
+ object[toStringTag] = value;
26185
26185
  }
26186
26186
  }
26187
26187
  };
@@ -26229,77 +26229,77 @@ var require_form_data = __commonJS((exports, module) => {
26229
26229
  FormData2.LINE_BREAK = `\r
26230
26230
  `;
26231
26231
  FormData2.DEFAULT_CONTENT_TYPE = "application/octet-stream";
26232
- FormData2.prototype.append = function(field, value2, options) {
26232
+ FormData2.prototype.append = function(field, value, options) {
26233
26233
  options = options || {};
26234
26234
  if (typeof options == "string") {
26235
26235
  options = { filename: options };
26236
26236
  }
26237
26237
  var append = CombinedStream.prototype.append.bind(this);
26238
- if (typeof value2 == "number") {
26239
- value2 = "" + value2;
26238
+ if (typeof value == "number") {
26239
+ value = "" + value;
26240
26240
  }
26241
- if (Array.isArray(value2)) {
26241
+ if (Array.isArray(value)) {
26242
26242
  this._error(new Error("Arrays are not supported."));
26243
26243
  return;
26244
26244
  }
26245
- var header = this._multiPartHeader(field, value2, options);
26245
+ var header = this._multiPartHeader(field, value, options);
26246
26246
  var footer = this._multiPartFooter();
26247
26247
  append(header);
26248
- append(value2);
26248
+ append(value);
26249
26249
  append(footer);
26250
- this._trackLength(header, value2, options);
26250
+ this._trackLength(header, value, options);
26251
26251
  };
26252
- FormData2.prototype._trackLength = function(header, value2, options) {
26252
+ FormData2.prototype._trackLength = function(header, value, options) {
26253
26253
  var valueLength = 0;
26254
26254
  if (options.knownLength != null) {
26255
26255
  valueLength += +options.knownLength;
26256
- } else if (Buffer.isBuffer(value2)) {
26257
- valueLength = value2.length;
26258
- } else if (typeof value2 === "string") {
26259
- valueLength = Buffer.byteLength(value2);
26256
+ } else if (Buffer.isBuffer(value)) {
26257
+ valueLength = value.length;
26258
+ } else if (typeof value === "string") {
26259
+ valueLength = Buffer.byteLength(value);
26260
26260
  }
26261
26261
  this._valueLength += valueLength;
26262
26262
  this._overheadLength += Buffer.byteLength(header) + FormData2.LINE_BREAK.length;
26263
- if (!value2 || !value2.path && !(value2.readable && Object.prototype.hasOwnProperty.call(value2, "httpVersion")) && !(value2 instanceof Stream)) {
26263
+ if (!value || !value.path && !(value.readable && Object.prototype.hasOwnProperty.call(value, "httpVersion")) && !(value instanceof Stream)) {
26264
26264
  return;
26265
26265
  }
26266
26266
  if (!options.knownLength) {
26267
- this._valuesToMeasure.push(value2);
26267
+ this._valuesToMeasure.push(value);
26268
26268
  }
26269
26269
  };
26270
- FormData2.prototype._lengthRetriever = function(value2, callback) {
26271
- if (Object.prototype.hasOwnProperty.call(value2, "fd")) {
26272
- if (value2.end != null && value2.end != Infinity && value2.start != null) {
26273
- callback(null, value2.end + 1 - (value2.start ? value2.start : 0));
26270
+ FormData2.prototype._lengthRetriever = function(value, callback) {
26271
+ if (Object.prototype.hasOwnProperty.call(value, "fd")) {
26272
+ if (value.end != null && value.end != Infinity && value.start != null) {
26273
+ callback(null, value.end + 1 - (value.start ? value.start : 0));
26274
26274
  } else {
26275
- fs.stat(value2.path, function(err, stat) {
26275
+ fs.stat(value.path, function(err, stat) {
26276
26276
  var fileSize;
26277
26277
  if (err) {
26278
26278
  callback(err);
26279
26279
  return;
26280
26280
  }
26281
- fileSize = stat.size - (value2.start ? value2.start : 0);
26281
+ fileSize = stat.size - (value.start ? value.start : 0);
26282
26282
  callback(null, fileSize);
26283
26283
  });
26284
26284
  }
26285
- } else if (Object.prototype.hasOwnProperty.call(value2, "httpVersion")) {
26286
- callback(null, +value2.headers["content-length"]);
26287
- } else if (Object.prototype.hasOwnProperty.call(value2, "httpModule")) {
26288
- value2.on("response", function(response) {
26289
- value2.pause();
26285
+ } else if (Object.prototype.hasOwnProperty.call(value, "httpVersion")) {
26286
+ callback(null, +value.headers["content-length"]);
26287
+ } else if (Object.prototype.hasOwnProperty.call(value, "httpModule")) {
26288
+ value.on("response", function(response) {
26289
+ value.pause();
26290
26290
  callback(null, +response.headers["content-length"]);
26291
26291
  });
26292
- value2.resume();
26292
+ value.resume();
26293
26293
  } else {
26294
26294
  callback("Unknown stream");
26295
26295
  }
26296
26296
  };
26297
- FormData2.prototype._multiPartHeader = function(field, value2, options) {
26297
+ FormData2.prototype._multiPartHeader = function(field, value, options) {
26298
26298
  if (typeof options.header == "string") {
26299
26299
  return options.header;
26300
26300
  }
26301
- var contentDisposition = this._getContentDisposition(value2, options);
26302
- var contentType = this._getContentType(value2, options);
26301
+ var contentDisposition = this._getContentDisposition(value, options);
26302
+ var contentType = this._getContentType(value, options);
26303
26303
  var contents = "";
26304
26304
  var headers = {
26305
26305
  "Content-Disposition": ["form-data", 'name="' + field + '"'].concat(contentDisposition || []),
@@ -26325,35 +26325,35 @@ var require_form_data = __commonJS((exports, module) => {
26325
26325
  }
26326
26326
  return "--" + this.getBoundary() + FormData2.LINE_BREAK + contents + FormData2.LINE_BREAK;
26327
26327
  };
26328
- FormData2.prototype._getContentDisposition = function(value2, options) {
26328
+ FormData2.prototype._getContentDisposition = function(value, options) {
26329
26329
  var filename, contentDisposition;
26330
26330
  if (typeof options.filepath === "string") {
26331
26331
  filename = path.normalize(options.filepath).replace(/\\/g, "/");
26332
- } else if (options.filename || value2.name || value2.path) {
26333
- filename = path.basename(options.filename || value2.name || value2.path);
26334
- } else if (value2.readable && Object.prototype.hasOwnProperty.call(value2, "httpVersion")) {
26335
- filename = path.basename(value2.client._httpMessage.path || "");
26332
+ } else if (options.filename || value.name || value.path) {
26333
+ filename = path.basename(options.filename || value.name || value.path);
26334
+ } else if (value.readable && Object.prototype.hasOwnProperty.call(value, "httpVersion")) {
26335
+ filename = path.basename(value.client._httpMessage.path || "");
26336
26336
  }
26337
26337
  if (filename) {
26338
26338
  contentDisposition = 'filename="' + filename + '"';
26339
26339
  }
26340
26340
  return contentDisposition;
26341
26341
  };
26342
- FormData2.prototype._getContentType = function(value2, options) {
26342
+ FormData2.prototype._getContentType = function(value, options) {
26343
26343
  var contentType = options.contentType;
26344
- if (!contentType && value2.name) {
26345
- contentType = mime.lookup(value2.name);
26344
+ if (!contentType && value.name) {
26345
+ contentType = mime.lookup(value.name);
26346
26346
  }
26347
- if (!contentType && value2.path) {
26348
- contentType = mime.lookup(value2.path);
26347
+ if (!contentType && value.path) {
26348
+ contentType = mime.lookup(value.path);
26349
26349
  }
26350
- if (!contentType && value2.readable && Object.prototype.hasOwnProperty.call(value2, "httpVersion")) {
26351
- contentType = value2.headers["content-type"];
26350
+ if (!contentType && value.readable && Object.prototype.hasOwnProperty.call(value, "httpVersion")) {
26351
+ contentType = value.headers["content-type"];
26352
26352
  }
26353
26353
  if (!contentType && (options.filepath || options.filename)) {
26354
26354
  contentType = mime.lookup(options.filepath || options.filename);
26355
26355
  }
26356
- if (!contentType && typeof value2 == "object") {
26356
+ if (!contentType && typeof value == "object") {
26357
26357
  contentType = FormData2.DEFAULT_CONTENT_TYPE;
26358
26358
  }
26359
26359
  return contentType;
@@ -26726,9 +26726,9 @@ var require_follow_redirects = __commonJS((exports, module) => {
26726
26726
  this._ending = true;
26727
26727
  }
26728
26728
  };
26729
- RedirectableRequest.prototype.setHeader = function(name2, value2) {
26730
- this._options.headers[name2] = value2;
26731
- this._currentRequest.setHeader(name2, value2);
26729
+ RedirectableRequest.prototype.setHeader = function(name2, value) {
26730
+ this._options.headers[name2] = value;
26731
+ this._currentRequest.setHeader(name2, value);
26732
26732
  };
26733
26733
  RedirectableRequest.prototype.removeHeader = function(name2) {
26734
26734
  delete this._options.headers[name2];
@@ -27048,17 +27048,17 @@ var require_follow_redirects = __commonJS((exports, module) => {
27048
27048
  var dot = subdomain.length - domain.length - 1;
27049
27049
  return dot > 0 && subdomain[dot] === "." && subdomain.endsWith(domain);
27050
27050
  }
27051
- function isString2(value2) {
27052
- return typeof value2 === "string" || value2 instanceof String;
27051
+ function isString2(value) {
27052
+ return typeof value === "string" || value instanceof String;
27053
27053
  }
27054
- function isFunction(value2) {
27055
- return typeof value2 === "function";
27054
+ function isFunction(value) {
27055
+ return typeof value === "function";
27056
27056
  }
27057
- function isBuffer(value2) {
27058
- return typeof value2 === "object" && "length" in value2;
27057
+ function isBuffer(value) {
27058
+ return typeof value === "object" && "length" in value;
27059
27059
  }
27060
- function isURL2(value2) {
27061
- return URL2 && value2 instanceof URL2;
27060
+ function isURL2(value) {
27061
+ return URL2 && value instanceof URL2;
27062
27062
  }
27063
27063
  module.exports = wrap3({ http: http2, https: https2 });
27064
27064
  module.exports.wrap = wrap3;
@@ -27254,14 +27254,14 @@ var require_axios = __commonJS((exports, module) => {
27254
27254
  } while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype);
27255
27255
  return destObj;
27256
27256
  };
27257
- var endsWith = (str, searchString, position2) => {
27257
+ var endsWith = (str, searchString, position) => {
27258
27258
  str = String(str);
27259
- if (position2 === undefined || position2 > str.length) {
27260
- position2 = str.length;
27259
+ if (position === undefined || position > str.length) {
27260
+ position = str.length;
27261
27261
  }
27262
- position2 -= searchString.length;
27263
- const lastIndex = str.indexOf(searchString, position2);
27264
- return lastIndex !== -1 && lastIndex === position2;
27262
+ position -= searchString.length;
27263
+ const lastIndex = str.indexOf(searchString, position);
27264
+ return lastIndex !== -1 && lastIndex === position;
27265
27265
  };
27266
27266
  var toArray = (thing) => {
27267
27267
  if (!thing)
@@ -27323,8 +27323,8 @@ var require_axios = __commonJS((exports, module) => {
27323
27323
  if (isFunction(obj) && ["arguments", "caller", "callee"].indexOf(name2) !== -1) {
27324
27324
  return false;
27325
27325
  }
27326
- const value2 = obj[name2];
27327
- if (!isFunction(value2))
27326
+ const value = obj[name2];
27327
+ if (!isFunction(value))
27328
27328
  return;
27329
27329
  descriptor.enumerable = false;
27330
27330
  if ("writable" in descriptor) {
@@ -27341,8 +27341,8 @@ var require_axios = __commonJS((exports, module) => {
27341
27341
  var toObjectSet = (arrayOrString, delimiter) => {
27342
27342
  const obj = {};
27343
27343
  const define2 = (arr) => {
27344
- arr.forEach((value2) => {
27345
- obj[value2] = true;
27344
+ arr.forEach((value) => {
27345
+ obj[value] = true;
27346
27346
  });
27347
27347
  };
27348
27348
  isArray3(arrayOrString) ? define2(arrayOrString) : define2(String(arrayOrString).split(delimiter));
@@ -27350,8 +27350,8 @@ var require_axios = __commonJS((exports, module) => {
27350
27350
  };
27351
27351
  var noop2 = () => {
27352
27352
  };
27353
- var toFiniteNumber = (value2, defaultValue) => {
27354
- return value2 != null && Number.isFinite(value2 = +value2) ? value2 : defaultValue;
27353
+ var toFiniteNumber = (value, defaultValue) => {
27354
+ return value != null && Number.isFinite(value = +value) ? value : defaultValue;
27355
27355
  };
27356
27356
  function isSpecCompliantForm(thing) {
27357
27357
  return !!(thing && isFunction(thing.append) && thing[Symbol.toStringTag] === "FormData" && thing[Symbol.iterator]);
@@ -27366,8 +27366,8 @@ var require_axios = __commonJS((exports, module) => {
27366
27366
  if (!("toJSON" in source)) {
27367
27367
  stack[i2] = source;
27368
27368
  const target = isArray3(source) ? [] : {};
27369
- forEach2(source, (value2, key) => {
27370
- const reducedValue = visit(value2, i2 + 1);
27369
+ forEach2(source, (value, key) => {
27370
+ const reducedValue = visit(value, i2 + 1);
27371
27371
  !isUndefined3(reducedValue) && (target[key] = reducedValue);
27372
27372
  });
27373
27373
  stack[i2] = undefined;
@@ -27562,27 +27562,27 @@ var require_axios = __commonJS((exports, module) => {
27562
27562
  if (!utils$1.isFunction(visitor)) {
27563
27563
  throw new TypeError("visitor must be a function");
27564
27564
  }
27565
- function convertValue(value2) {
27566
- if (value2 === null)
27565
+ function convertValue(value) {
27566
+ if (value === null)
27567
27567
  return "";
27568
- if (utils$1.isDate(value2)) {
27569
- return value2.toISOString();
27568
+ if (utils$1.isDate(value)) {
27569
+ return value.toISOString();
27570
27570
  }
27571
- if (!useBlob && utils$1.isBlob(value2)) {
27571
+ if (!useBlob && utils$1.isBlob(value)) {
27572
27572
  throw new AxiosError("Blob is not supported. Use a Buffer instead.");
27573
27573
  }
27574
- if (utils$1.isArrayBuffer(value2) || utils$1.isTypedArray(value2)) {
27575
- return useBlob && typeof Blob === "function" ? new Blob([value2]) : Buffer.from(value2);
27574
+ if (utils$1.isArrayBuffer(value) || utils$1.isTypedArray(value)) {
27575
+ return useBlob && typeof Blob === "function" ? new Blob([value]) : Buffer.from(value);
27576
27576
  }
27577
- return value2;
27577
+ return value;
27578
27578
  }
27579
- function defaultVisitor(value2, key, path) {
27580
- let arr = value2;
27581
- if (value2 && !path && typeof value2 === "object") {
27579
+ function defaultVisitor(value, key, path) {
27580
+ let arr = value;
27581
+ if (value && !path && typeof value === "object") {
27582
27582
  if (utils$1.endsWith(key, "{}")) {
27583
27583
  key = metaTokens ? key : key.slice(0, -2);
27584
- value2 = JSON.stringify(value2);
27585
- } else if (utils$1.isArray(value2) && isFlatArray(value2) || (utils$1.isFileList(value2) || utils$1.endsWith(key, "[]")) && (arr = utils$1.toArray(value2))) {
27584
+ value = JSON.stringify(value);
27585
+ } else if (utils$1.isArray(value) && isFlatArray(value) || (utils$1.isFileList(value) || utils$1.endsWith(key, "[]")) && (arr = utils$1.toArray(value))) {
27586
27586
  key = removeBrackets(key);
27587
27587
  arr.forEach(function each(el, index) {
27588
27588
  !(utils$1.isUndefined(el) || el === null) && formData.append(indexes === true ? renderKey([key], index, dots) : indexes === null ? key : key + "[]", convertValue(el));
@@ -27590,10 +27590,10 @@ var require_axios = __commonJS((exports, module) => {
27590
27590
  return false;
27591
27591
  }
27592
27592
  }
27593
- if (isVisitable(value2)) {
27593
+ if (isVisitable(value)) {
27594
27594
  return true;
27595
27595
  }
27596
- formData.append(renderKey(path, key, dots), convertValue(value2));
27596
+ formData.append(renderKey(path, key, dots), convertValue(value));
27597
27597
  return false;
27598
27598
  }
27599
27599
  const stack = [];
@@ -27602,14 +27602,14 @@ var require_axios = __commonJS((exports, module) => {
27602
27602
  convertValue,
27603
27603
  isVisitable
27604
27604
  });
27605
- function build(value2, path) {
27606
- if (utils$1.isUndefined(value2))
27605
+ function build(value, path) {
27606
+ if (utils$1.isUndefined(value))
27607
27607
  return;
27608
- if (stack.indexOf(value2) !== -1) {
27608
+ if (stack.indexOf(value) !== -1) {
27609
27609
  throw Error("Circular reference detected in " + path.join("."));
27610
27610
  }
27611
- stack.push(value2);
27612
- utils$1.forEach(value2, function each(el, key) {
27611
+ stack.push(value);
27612
+ utils$1.forEach(value, function each(el, key) {
27613
27613
  const result = !(utils$1.isUndefined(el) || el === null) && visitor.call(formData, el, utils$1.isString(key) ? key.trim() : key, path, exposedHelpers);
27614
27614
  if (result === true) {
27615
27615
  build(el, path ? path.concat(key) : [key]);
@@ -27642,12 +27642,12 @@ var require_axios = __commonJS((exports, module) => {
27642
27642
  params && toFormData(params, this, options);
27643
27643
  }
27644
27644
  var prototype = AxiosURLSearchParams.prototype;
27645
- prototype.append = function append(name2, value2) {
27646
- this._pairs.push([name2, value2]);
27645
+ prototype.append = function append(name2, value) {
27646
+ this._pairs.push([name2, value]);
27647
27647
  };
27648
27648
  prototype.toString = function toString(encoder2) {
27649
- const _encode = encoder2 ? function(value2) {
27650
- return encoder2.call(this, value2, encode$1);
27649
+ const _encode = encoder2 ? function(value) {
27650
+ return encoder2.call(this, value, encode$1);
27651
27651
  } : encode$1;
27652
27652
  return this._pairs.map(function each(pair) {
27653
27653
  return _encode(pair[0]) + "=" + _encode(pair[1]);
@@ -27770,9 +27770,9 @@ var require_axios = __commonJS((exports, module) => {
27770
27770
  };
27771
27771
  function toURLEncodedForm(data, options) {
27772
27772
  return toFormData(data, new platform.classes.URLSearchParams, Object.assign({
27773
- visitor: function(value2, key, path, helpers) {
27774
- if (platform.isNode && utils$1.isBuffer(value2)) {
27775
- this.append(key, value2.toString("base64"));
27773
+ visitor: function(value, key, path, helpers) {
27774
+ if (platform.isNode && utils$1.isBuffer(value)) {
27775
+ this.append(key, value.toString("base64"));
27776
27776
  return false;
27777
27777
  }
27778
27778
  return helpers.defaultVisitor.apply(this, arguments);
@@ -27797,7 +27797,7 @@ var require_axios = __commonJS((exports, module) => {
27797
27797
  return obj;
27798
27798
  }
27799
27799
  function formDataToJSON(formData) {
27800
- function buildPath(path, value2, target, index) {
27800
+ function buildPath(path, value, target, index) {
27801
27801
  let name2 = path[index++];
27802
27802
  if (name2 === "__proto__")
27803
27803
  return true;
@@ -27806,16 +27806,16 @@ var require_axios = __commonJS((exports, module) => {
27806
27806
  name2 = !name2 && utils$1.isArray(target) ? target.length : name2;
27807
27807
  if (isLast) {
27808
27808
  if (utils$1.hasOwnProp(target, name2)) {
27809
- target[name2] = [target[name2], value2];
27809
+ target[name2] = [target[name2], value];
27810
27810
  } else {
27811
- target[name2] = value2;
27811
+ target[name2] = value;
27812
27812
  }
27813
27813
  return !isNumericKey;
27814
27814
  }
27815
27815
  if (!target[name2] || !utils$1.isObject(target[name2])) {
27816
27816
  target[name2] = [];
27817
27817
  }
27818
- const result = buildPath(path, value2, target[name2], index);
27818
+ const result = buildPath(path, value, target[name2], index);
27819
27819
  if (result && utils$1.isArray(target[name2])) {
27820
27820
  target[name2] = arrayToObject(target[name2]);
27821
27821
  }
@@ -27823,8 +27823,8 @@ var require_axios = __commonJS((exports, module) => {
27823
27823
  }
27824
27824
  if (utils$1.isFormData(formData) && utils$1.isFunction(formData.entries)) {
27825
27825
  const obj = {};
27826
- utils$1.forEachEntry(formData, (name2, value2) => {
27827
- buildPath(parsePropPath(name2), value2, obj, 0);
27826
+ utils$1.forEachEntry(formData, (name2, value) => {
27827
+ buildPath(parsePropPath(name2), value, obj, 0);
27828
27828
  });
27829
27829
  return obj;
27830
27830
  }
@@ -27977,11 +27977,11 @@ var require_axios = __commonJS((exports, module) => {
27977
27977
  function normalizeHeader(header) {
27978
27978
  return header && String(header).trim().toLowerCase();
27979
27979
  }
27980
- function normalizeValue(value2) {
27981
- if (value2 === false || value2 == null) {
27982
- return value2;
27980
+ function normalizeValue(value) {
27981
+ if (value === false || value == null) {
27982
+ return value;
27983
27983
  }
27984
- return utils$1.isArray(value2) ? value2.map(normalizeValue) : String(value2);
27984
+ return utils$1.isArray(value) ? value.map(normalizeValue) : String(value);
27985
27985
  }
27986
27986
  function parseTokens(str) {
27987
27987
  const tokens = Object.create(null);
@@ -27993,20 +27993,20 @@ var require_axios = __commonJS((exports, module) => {
27993
27993
  return tokens;
27994
27994
  }
27995
27995
  var isValidHeaderName = (str) => /^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(str.trim());
27996
- function matchHeaderValue(context3, value2, header, filter, isHeaderNameFilter) {
27996
+ function matchHeaderValue(context3, value, header, filter, isHeaderNameFilter) {
27997
27997
  if (utils$1.isFunction(filter)) {
27998
- return filter.call(this, value2, header);
27998
+ return filter.call(this, value, header);
27999
27999
  }
28000
28000
  if (isHeaderNameFilter) {
28001
- value2 = header;
28001
+ value = header;
28002
28002
  }
28003
- if (!utils$1.isString(value2))
28003
+ if (!utils$1.isString(value))
28004
28004
  return;
28005
28005
  if (utils$1.isString(filter)) {
28006
- return value2.indexOf(filter) !== -1;
28006
+ return value.indexOf(filter) !== -1;
28007
28007
  }
28008
28008
  if (utils$1.isRegExp(filter)) {
28009
- return filter.test(value2);
28009
+ return filter.test(value);
28010
28010
  }
28011
28011
  }
28012
28012
  function formatHeader(header) {
@@ -28048,8 +28048,8 @@ var require_axios = __commonJS((exports, module) => {
28048
28048
  } else if (utils$1.isString(header) && (header = header.trim()) && !isValidHeaderName(header)) {
28049
28049
  setHeaders(parseHeaders(header), valueOrRewrite);
28050
28050
  } else if (utils$1.isHeaders(header)) {
28051
- for (const [key, value2] of header.entries()) {
28052
- setHeader(value2, key, rewrite);
28051
+ for (const [key, value] of header.entries()) {
28052
+ setHeader(value, key, rewrite);
28053
28053
  }
28054
28054
  } else {
28055
28055
  header != null && setHeader(valueOrRewrite, header, rewrite);
@@ -28061,18 +28061,18 @@ var require_axios = __commonJS((exports, module) => {
28061
28061
  if (header) {
28062
28062
  const key = utils$1.findKey(this, header);
28063
28063
  if (key) {
28064
- const value2 = this[key];
28064
+ const value = this[key];
28065
28065
  if (!parser) {
28066
- return value2;
28066
+ return value;
28067
28067
  }
28068
28068
  if (parser === true) {
28069
- return parseTokens(value2);
28069
+ return parseTokens(value);
28070
28070
  }
28071
28071
  if (utils$1.isFunction(parser)) {
28072
- return parser.call(this, value2, key);
28072
+ return parser.call(this, value, key);
28073
28073
  }
28074
28074
  if (utils$1.isRegExp(parser)) {
28075
- return parser.exec(value2);
28075
+ return parser.exec(value);
28076
28076
  }
28077
28077
  throw new TypeError("parser must be boolean|regexp|function");
28078
28078
  }
@@ -28122,10 +28122,10 @@ var require_axios = __commonJS((exports, module) => {
28122
28122
  normalize(format) {
28123
28123
  const self2 = this;
28124
28124
  const headers = {};
28125
- utils$1.forEach(this, (value2, header) => {
28125
+ utils$1.forEach(this, (value, header) => {
28126
28126
  const key = utils$1.findKey(headers, header);
28127
28127
  if (key) {
28128
- self2[key] = normalizeValue(value2);
28128
+ self2[key] = normalizeValue(value);
28129
28129
  delete self2[header];
28130
28130
  return;
28131
28131
  }
@@ -28133,7 +28133,7 @@ var require_axios = __commonJS((exports, module) => {
28133
28133
  if (normalized !== header) {
28134
28134
  delete self2[header];
28135
28135
  }
28136
- self2[normalized] = normalizeValue(value2);
28136
+ self2[normalized] = normalizeValue(value);
28137
28137
  headers[normalized] = true;
28138
28138
  });
28139
28139
  return this;
@@ -28143,8 +28143,8 @@ var require_axios = __commonJS((exports, module) => {
28143
28143
  }
28144
28144
  toJSON(asStrings) {
28145
28145
  const obj = Object.create(null);
28146
- utils$1.forEach(this, (value2, header) => {
28147
- value2 != null && value2 !== false && (obj[header] = asStrings && utils$1.isArray(value2) ? value2.join(", ") : value2);
28146
+ utils$1.forEach(this, (value, header) => {
28147
+ value != null && value !== false && (obj[header] = asStrings && utils$1.isArray(value) ? value.join(", ") : value);
28148
28148
  });
28149
28149
  return obj;
28150
28150
  }
@@ -28152,7 +28152,7 @@ var require_axios = __commonJS((exports, module) => {
28152
28152
  return Object.entries(this.toJSON())[Symbol.iterator]();
28153
28153
  }
28154
28154
  toString() {
28155
- return Object.entries(this.toJSON()).map(([header, value2]) => header + ": " + value2).join(`
28155
+ return Object.entries(this.toJSON()).map(([header, value]) => header + ": " + value).join(`
28156
28156
  `);
28157
28157
  }
28158
28158
  get [Symbol.toStringTag]() {
@@ -28184,10 +28184,10 @@ var require_axios = __commonJS((exports, module) => {
28184
28184
  }
28185
28185
  }
28186
28186
  AxiosHeaders.accessor(["Content-Type", "Content-Length", "Accept", "Accept-Encoding", "User-Agent", "Authorization"]);
28187
- utils$1.reduceDescriptors(AxiosHeaders.prototype, ({ value: value2 }, key) => {
28187
+ utils$1.reduceDescriptors(AxiosHeaders.prototype, ({ value }, key) => {
28188
28188
  let mapped = key[0].toUpperCase() + key.slice(1);
28189
28189
  return {
28190
- get: () => value2,
28190
+ get: () => value,
28191
28191
  set(headerValue) {
28192
28192
  this[mapped] = headerValue;
28193
28193
  }
@@ -28206,8 +28206,8 @@ var require_axios = __commonJS((exports, module) => {
28206
28206
  headers.normalize();
28207
28207
  return data;
28208
28208
  }
28209
- function isCancel(value2) {
28210
- return !!(value2 && value2.__CANCEL__);
28209
+ function isCancel(value) {
28210
+ return !!(value && value.__CANCEL__);
28211
28211
  }
28212
28212
  function CanceledError(message2, config2, request) {
28213
28213
  AxiosError.call(this, message2 == null ? "canceled" : message2, AxiosError.ERR_CANCELED, config2, request);
@@ -28403,28 +28403,28 @@ var require_axios = __commonJS((exports, module) => {
28403
28403
  var CRLF_BYTES_COUNT = 2;
28404
28404
 
28405
28405
  class FormDataPart {
28406
- constructor(name2, value2) {
28406
+ constructor(name2, value) {
28407
28407
  const { escapeName } = this.constructor;
28408
- const isStringValue = utils$1.isString(value2);
28409
- let headers = `Content-Disposition: form-data; name="${escapeName(name2)}"${!isStringValue && value2.name ? `; filename="${escapeName(value2.name)}"` : ""}${CRLF}`;
28408
+ const isStringValue = utils$1.isString(value);
28409
+ let headers = `Content-Disposition: form-data; name="${escapeName(name2)}"${!isStringValue && value.name ? `; filename="${escapeName(value.name)}"` : ""}${CRLF}`;
28410
28410
  if (isStringValue) {
28411
- value2 = textEncoder.encode(String(value2).replace(/\r?\n|\r\n?/g, CRLF));
28411
+ value = textEncoder.encode(String(value).replace(/\r?\n|\r\n?/g, CRLF));
28412
28412
  } else {
28413
- headers += `Content-Type: ${value2.type || "application/octet-stream"}${CRLF}`;
28413
+ headers += `Content-Type: ${value.type || "application/octet-stream"}${CRLF}`;
28414
28414
  }
28415
28415
  this.headers = textEncoder.encode(headers + CRLF);
28416
- this.contentLength = isStringValue ? value2.byteLength : value2.size;
28416
+ this.contentLength = isStringValue ? value.byteLength : value.size;
28417
28417
  this.size = this.headers.byteLength + this.contentLength + CRLF_BYTES_COUNT;
28418
28418
  this.name = name2;
28419
- this.value = value2;
28419
+ this.value = value;
28420
28420
  }
28421
28421
  async* encode() {
28422
28422
  yield this.headers;
28423
- const { value: value2 } = this;
28424
- if (utils$1.isTypedArray(value2)) {
28425
- yield value2;
28423
+ const { value } = this;
28424
+ if (utils$1.isTypedArray(value)) {
28425
+ yield value;
28426
28426
  } else {
28427
- yield* readBlob$1(value2);
28427
+ yield* readBlob$1(value);
28428
28428
  }
28429
28429
  yield CRLF_BYTES;
28430
28430
  }
@@ -28451,8 +28451,8 @@ var require_axios = __commonJS((exports, module) => {
28451
28451
  const boundaryBytes = textEncoder.encode("--" + boundary + CRLF);
28452
28452
  const footerBytes = textEncoder.encode("--" + boundary + "--" + CRLF + CRLF);
28453
28453
  let contentLength = footerBytes.byteLength;
28454
- const parts = Array.from(form.entries()).map(([name2, value2]) => {
28455
- const part = new FormDataPart(name2, value2);
28454
+ const parts = Array.from(form.entries()).map(([name2, value]) => {
28455
+ const part = new FormDataPart(name2, value);
28456
28456
  contentLength += part.size;
28457
28457
  return part;
28458
28458
  });
@@ -28497,9 +28497,9 @@ var require_axios = __commonJS((exports, module) => {
28497
28497
  var callbackify = (fn, reducer) => {
28498
28498
  return utils$1.isAsyncFn(fn) ? function(...args) {
28499
28499
  const cb = args.pop();
28500
- fn.apply(this, args).then((value2) => {
28500
+ fn.apply(this, args).then((value) => {
28501
28501
  try {
28502
- reducer ? cb(null, ...reducer(value2)) : cb(null, value2);
28502
+ reducer ? cb(null, ...reducer(value)) : cb(null, value);
28503
28503
  } catch (err) {
28504
28504
  cb(err);
28505
28505
  }
@@ -28669,15 +28669,15 @@ var require_axios = __commonJS((exports, module) => {
28669
28669
  return new Promise((resolve, reject) => {
28670
28670
  let onDone;
28671
28671
  let isDone;
28672
- const done = (value2, isRejected) => {
28672
+ const done = (value, isRejected) => {
28673
28673
  if (isDone)
28674
28674
  return;
28675
28675
  isDone = true;
28676
- onDone && onDone(value2, isRejected);
28676
+ onDone && onDone(value, isRejected);
28677
28677
  };
28678
- const _resolve = (value2) => {
28679
- done(value2);
28680
- resolve(value2);
28678
+ const _resolve = (value) => {
28679
+ done(value);
28680
+ resolve(value);
28681
28681
  };
28682
28682
  const _reject = (reason) => {
28683
28683
  done(reason, true);
@@ -28705,7 +28705,7 @@ var require_axios = __commonJS((exports, module) => {
28705
28705
  let rejected = false;
28706
28706
  let req;
28707
28707
  if (lookup) {
28708
- const _lookup = callbackify$1(lookup, (value2) => utils$1.isArray(value2) ? value2 : [value2]);
28708
+ const _lookup = callbackify$1(lookup, (value) => utils$1.isArray(value) ? value : [value]);
28709
28709
  lookup = (hostname, opt, cb) => {
28710
28710
  _lookup(hostname, opt, (err, arg0, arg1) => {
28711
28711
  if (err) {
@@ -28726,7 +28726,7 @@ var require_axios = __commonJS((exports, module) => {
28726
28726
  }
28727
28727
  emitter.removeAllListeners();
28728
28728
  };
28729
- onDone((value2, isRejected) => {
28729
+ onDone((value, isRejected) => {
28730
28730
  isDone = true;
28731
28731
  if (isRejected) {
28732
28732
  rejected = true;
@@ -29061,8 +29061,8 @@ var require_axios = __commonJS((exports, module) => {
29061
29061
  return origin2.protocol === url2.protocol && origin2.host === url2.host && (isMSIE || origin2.port === url2.port);
29062
29062
  })(new URL(platform.origin), platform.navigator && /(msie|trident)/i.test(platform.navigator.userAgent)) : () => true;
29063
29063
  var cookies = platform.hasStandardBrowserEnv ? {
29064
- write(name2, value2, expires, path, domain, secure) {
29065
- const cookie = [name2 + "=" + encodeURIComponent(value2)];
29064
+ write(name2, value, expires, path, domain, secure) {
29065
+ const cookie = [name2 + "=" + encodeURIComponent(value)];
29066
29066
  utils$1.isNumber(expires) && cookie.push("expires=" + new Date(expires).toGMTString());
29067
29067
  utils$1.isString(path) && cookie.push("path=" + path);
29068
29068
  utils$1.isString(domain) && cookie.push("domain=" + domain);
@@ -29224,8 +29224,8 @@ var require_axios = __commonJS((exports, module) => {
29224
29224
  config: config2,
29225
29225
  request
29226
29226
  };
29227
- settle(function _resolve(value2) {
29228
- resolve(value2);
29227
+ settle(function _resolve(value) {
29228
+ resolve(value);
29229
29229
  done();
29230
29230
  }, function _reject(err) {
29231
29231
  reject(err);
@@ -29370,11 +29370,11 @@ var require_axios = __commonJS((exports, module) => {
29370
29370
  const reader = stream3.getReader();
29371
29371
  try {
29372
29372
  for (;; ) {
29373
- const { done, value: value2 } = await reader.read();
29373
+ const { done, value } = await reader.read();
29374
29374
  if (done) {
29375
29375
  break;
29376
29376
  }
29377
- yield value2;
29377
+ yield value;
29378
29378
  }
29379
29379
  } finally {
29380
29380
  await reader.cancel();
@@ -29393,18 +29393,18 @@ var require_axios = __commonJS((exports, module) => {
29393
29393
  return new ReadableStream({
29394
29394
  async pull(controller) {
29395
29395
  try {
29396
- const { done: done2, value: value2 } = await iterator.next();
29396
+ const { done: done2, value } = await iterator.next();
29397
29397
  if (done2) {
29398
29398
  _onFinish();
29399
29399
  controller.close();
29400
29400
  return;
29401
29401
  }
29402
- let len = value2.byteLength;
29402
+ let len = value.byteLength;
29403
29403
  if (onProgress) {
29404
29404
  let loadedBytes = bytes += len;
29405
29405
  onProgress(loadedBytes);
29406
29406
  }
29407
- controller.enqueue(new Uint8Array(value2));
29407
+ controller.enqueue(new Uint8Array(value));
29408
29408
  } catch (err) {
29409
29409
  _onFinish(err);
29410
29410
  throw err;
@@ -29573,13 +29573,13 @@ var require_axios = __commonJS((exports, module) => {
29573
29573
  xhr: xhrAdapter,
29574
29574
  fetch: fetchAdapter
29575
29575
  };
29576
- utils$1.forEach(knownAdapters, (fn, value2) => {
29576
+ utils$1.forEach(knownAdapters, (fn, value) => {
29577
29577
  if (fn) {
29578
29578
  try {
29579
- Object.defineProperty(fn, "name", { value: value2 });
29579
+ Object.defineProperty(fn, "name", { value });
29580
29580
  } catch (e2) {
29581
29581
  }
29582
- Object.defineProperty(fn, "adapterName", { value: value2 });
29582
+ Object.defineProperty(fn, "adapterName", { value });
29583
29583
  }
29584
29584
  });
29585
29585
  var renderReason = (reason) => `- ${reason}`;
@@ -29660,7 +29660,7 @@ var require_axios = __commonJS((exports, module) => {
29660
29660
  function formatMessage(opt, desc) {
29661
29661
  return "[Axios v" + VERSION3 + "] Transitional option '" + opt + "'" + desc + (message2 ? ". " + message2 : "");
29662
29662
  }
29663
- return (value2, opt, opts) => {
29663
+ return (value, opt, opts) => {
29664
29664
  if (validator2 === false) {
29665
29665
  throw new AxiosError(formatMessage(opt, " has been removed" + (version ? " in " + version : "")), AxiosError.ERR_DEPRECATED);
29666
29666
  }
@@ -29668,11 +29668,11 @@ var require_axios = __commonJS((exports, module) => {
29668
29668
  deprecatedWarnings[opt] = true;
29669
29669
  console.warn(formatMessage(opt, " has been deprecated since v" + version + " and will be removed in the near future"));
29670
29670
  }
29671
- return validator2 ? validator2(value2, opt, opts) : true;
29671
+ return validator2 ? validator2(value, opt, opts) : true;
29672
29672
  };
29673
29673
  };
29674
29674
  validators$1.spelling = function spelling(correctSpelling) {
29675
- return (value2, opt) => {
29675
+ return (value, opt) => {
29676
29676
  console.warn(`${opt} is likely a misspelling of ${correctSpelling}`);
29677
29677
  return true;
29678
29678
  };
@@ -29687,8 +29687,8 @@ var require_axios = __commonJS((exports, module) => {
29687
29687
  const opt = keys[i2];
29688
29688
  const validator2 = schema[opt];
29689
29689
  if (validator2) {
29690
- const value2 = options[opt];
29691
- const result = value2 === undefined || validator2(value2, opt, options);
29690
+ const value = options[opt];
29691
+ const result = value === undefined || validator2(value, opt, options);
29692
29692
  if (result !== true) {
29693
29693
  throw new AxiosError("option " + opt + " must be " + result, AxiosError.ERR_BAD_OPTION_VALUE);
29694
29694
  }
@@ -30021,8 +30021,8 @@ var require_axios = __commonJS((exports, module) => {
30021
30021
  NotExtended: 510,
30022
30022
  NetworkAuthenticationRequired: 511
30023
30023
  };
30024
- Object.entries(HttpStatusCode).forEach(([key, value2]) => {
30025
- HttpStatusCode[value2] = key;
30024
+ Object.entries(HttpStatusCode).forEach(([key, value]) => {
30025
+ HttpStatusCode[value] = key;
30026
30026
  });
30027
30027
  var HttpStatusCode$1 = HttpStatusCode;
30028
30028
  function createInstance(defaultConfig) {
@@ -30768,23 +30768,23 @@ var require_beautifier = __commonJS((exports) => {
30768
30768
  }
30769
30769
  const newItem = {};
30770
30770
  for (const key2 in data) {
30771
- const value2 = data[key2];
30772
- const valueType = typeof value2;
30771
+ const value = data[key2];
30772
+ const valueType = typeof value;
30773
30773
  let newKey = knownBeautification[key2] || key2;
30774
30774
  if (Array.isArray(newKey)) {
30775
30775
  newKey = newKey[0];
30776
30776
  }
30777
- if (!Array.isArray(value2)) {
30778
- if (valueType === "object" && value2 !== null) {
30779
- newItem[newKey] = this.beautify(value2, knownBeautification[key2]);
30777
+ if (!Array.isArray(value)) {
30778
+ if (valueType === "object" && value !== null) {
30779
+ newItem[newKey] = this.beautify(value, knownBeautification[key2]);
30780
30780
  } else {
30781
- newItem[newKey] = this.beautifyValueWithKey(newKey, value2);
30781
+ newItem[newKey] = this.beautifyValueWithKey(newKey, value);
30782
30782
  }
30783
30783
  continue;
30784
30784
  }
30785
30785
  const newArray = [];
30786
30786
  if (Array.isArray(this.beautificationMap[newKey])) {
30787
- for (const elementValue of value2) {
30787
+ for (const elementValue of value) {
30788
30788
  const mappedBeautification = this.beautificationMap[knownBeautification[key2]];
30789
30789
  const childMapping = mappedBeautification[0];
30790
30790
  if (typeof childMapping === "object" && childMapping !== null) {
@@ -30881,22 +30881,22 @@ var require_nanoid = __commonJS((exports, module) => {
30881
30881
  // node_modules/binance/lib/util/browser-support.js
30882
30882
  var require_browser_support = __commonJS((exports) => {
30883
30883
  var __awaiter = exports && exports.__awaiter || function(thisArg, _arguments, P, generator) {
30884
- function adopt(value2) {
30885
- return value2 instanceof P ? value2 : new P(function(resolve) {
30886
- resolve(value2);
30884
+ function adopt(value) {
30885
+ return value instanceof P ? value : new P(function(resolve) {
30886
+ resolve(value);
30887
30887
  });
30888
30888
  }
30889
30889
  return new (P || (P = Promise))(function(resolve, reject) {
30890
- function fulfilled(value2) {
30890
+ function fulfilled(value) {
30891
30891
  try {
30892
- step(generator.next(value2));
30892
+ step(generator.next(value));
30893
30893
  } catch (e2) {
30894
30894
  reject(e2);
30895
30895
  }
30896
30896
  }
30897
- function rejected(value2) {
30897
+ function rejected(value) {
30898
30898
  try {
30899
- step(generator["throw"](value2));
30899
+ step(generator["throw"](value));
30900
30900
  } catch (e2) {
30901
30901
  reject(e2);
30902
30902
  }
@@ -30973,22 +30973,22 @@ var require_node_support = __commonJS((exports) => {
30973
30973
  return result;
30974
30974
  };
30975
30975
  var __awaiter = exports && exports.__awaiter || function(thisArg, _arguments, P, generator) {
30976
- function adopt(value2) {
30977
- return value2 instanceof P ? value2 : new P(function(resolve) {
30978
- resolve(value2);
30976
+ function adopt(value) {
30977
+ return value instanceof P ? value : new P(function(resolve) {
30978
+ resolve(value);
30979
30979
  });
30980
30980
  }
30981
30981
  return new (P || (P = Promise))(function(resolve, reject) {
30982
- function fulfilled(value2) {
30982
+ function fulfilled(value) {
30983
30983
  try {
30984
- step(generator.next(value2));
30984
+ step(generator.next(value));
30985
30985
  } catch (e2) {
30986
30986
  reject(e2);
30987
30987
  }
30988
30988
  }
30989
- function rejected(value2) {
30989
+ function rejected(value) {
30990
30990
  try {
30991
- step(generator["throw"](value2));
30991
+ step(generator["throw"](value));
30992
30992
  } catch (e2) {
30993
30993
  reject(e2);
30994
30994
  }
@@ -31020,22 +31020,22 @@ var require_node_support = __commonJS((exports) => {
31020
31020
  // node_modules/binance/lib/util/requestUtils.js
31021
31021
  var require_requestUtils = __commonJS((exports) => {
31022
31022
  var __awaiter = exports && exports.__awaiter || function(thisArg, _arguments, P, generator) {
31023
- function adopt(value2) {
31024
- return value2 instanceof P ? value2 : new P(function(resolve) {
31025
- resolve(value2);
31023
+ function adopt(value) {
31024
+ return value instanceof P ? value : new P(function(resolve) {
31025
+ resolve(value);
31026
31026
  });
31027
31027
  }
31028
31028
  return new (P || (P = Promise))(function(resolve, reject) {
31029
- function fulfilled(value2) {
31029
+ function fulfilled(value) {
31030
31030
  try {
31031
- step(generator.next(value2));
31031
+ step(generator.next(value));
31032
31032
  } catch (e2) {
31033
31033
  reject(e2);
31034
31034
  }
31035
31035
  }
31036
- function rejected(value2) {
31036
+ function rejected(value) {
31037
31037
  try {
31038
- step(generator["throw"](value2));
31038
+ step(generator["throw"](value));
31039
31039
  } catch (e2) {
31040
31040
  reject(e2);
31041
31041
  }
@@ -31081,11 +31081,11 @@ var require_requestUtils = __commonJS((exports) => {
31081
31081
  function serialiseParams(params = {}, strict_validation = false, encodeValues = false, filterUndefinedParams = false) {
31082
31082
  const paramKeys = !filterUndefinedParams ? Object.keys(params) : Object.keys(params).filter((key) => typeof params[key] !== "undefined");
31083
31083
  return paramKeys.map((key) => {
31084
- const value2 = params[key];
31085
- if (strict_validation === true && typeof value2 === "undefined") {
31084
+ const value = params[key];
31085
+ if (strict_validation === true && typeof value === "undefined") {
31086
31086
  throw new Error("Failed to sign API request due to undefined parameter");
31087
31087
  }
31088
- const encodedValue = encodeValues ? encodeURIComponent(value2) : value2;
31088
+ const encodedValue = encodeValues ? encodeURIComponent(value) : value;
31089
31089
  return `${key}=${encodedValue}`;
31090
31090
  }).join("&");
31091
31091
  }
@@ -31224,22 +31224,22 @@ var require_requestUtils = __commonJS((exports) => {
31224
31224
  // node_modules/binance/lib/util/BaseRestClient.js
31225
31225
  var require_BaseRestClient = __commonJS((exports) => {
31226
31226
  var __awaiter = exports && exports.__awaiter || function(thisArg, _arguments, P, generator) {
31227
- function adopt(value2) {
31228
- return value2 instanceof P ? value2 : new P(function(resolve) {
31229
- resolve(value2);
31227
+ function adopt(value) {
31228
+ return value instanceof P ? value : new P(function(resolve) {
31229
+ resolve(value);
31230
31230
  });
31231
31231
  }
31232
31232
  return new (P || (P = Promise))(function(resolve, reject) {
31233
- function fulfilled(value2) {
31233
+ function fulfilled(value) {
31234
31234
  try {
31235
- step(generator.next(value2));
31235
+ step(generator.next(value));
31236
31236
  } catch (e2) {
31237
31237
  reject(e2);
31238
31238
  }
31239
31239
  }
31240
- function rejected(value2) {
31240
+ function rejected(value) {
31241
31241
  try {
31242
- step(generator["throw"](value2));
31242
+ step(generator["throw"](value));
31243
31243
  } catch (e2) {
31244
31244
  reject(e2);
31245
31245
  }
@@ -31311,8 +31311,8 @@ var require_BaseRestClient = __commonJS((exports) => {
31311
31311
  getTimeOffset() {
31312
31312
  return this.timeOffset;
31313
31313
  }
31314
- setTimeOffset(value2) {
31315
- this.timeOffset = value2;
31314
+ setTimeOffset(value) {
31315
+ this.timeOffset = value;
31316
31316
  }
31317
31317
  get(endpoint, params) {
31318
31318
  return this._call("GET", endpoint, params);
@@ -31406,18 +31406,18 @@ var require_BaseRestClient = __commonJS((exports) => {
31406
31406
  const delta = {};
31407
31407
  for (const headerKey in this.apiLimitTrackers) {
31408
31408
  const headerValue = responseHeaders[headerKey];
31409
- const value2 = parseInt(headerValue);
31410
- if (headerValue !== undefined && !isNaN(value2)) {
31411
- this.apiLimitTrackers[headerKey] = value2;
31409
+ const value = parseInt(headerValue);
31410
+ if (headerValue !== undefined && !isNaN(value)) {
31411
+ this.apiLimitTrackers[headerKey] = value;
31412
31412
  delta[headerKey] = {
31413
31413
  updated: true,
31414
- valueParsed: value2,
31414
+ valueParsed: value,
31415
31415
  valueRaw: headerValue
31416
31416
  };
31417
31417
  } else {
31418
31418
  delta[headerKey] = {
31419
31419
  updated: false,
31420
- valueParsed: value2,
31420
+ valueParsed: value,
31421
31421
  valueRaw: headerValue
31422
31422
  };
31423
31423
  }
@@ -31458,22 +31458,22 @@ var require_BaseRestClient = __commonJS((exports) => {
31458
31458
  // node_modules/binance/lib/coinm-client.js
31459
31459
  var require_coinm_client = __commonJS((exports) => {
31460
31460
  var __awaiter = exports && exports.__awaiter || function(thisArg, _arguments, P, generator) {
31461
- function adopt(value2) {
31462
- return value2 instanceof P ? value2 : new P(function(resolve) {
31463
- resolve(value2);
31461
+ function adopt(value) {
31462
+ return value instanceof P ? value : new P(function(resolve) {
31463
+ resolve(value);
31464
31464
  });
31465
31465
  }
31466
31466
  return new (P || (P = Promise))(function(resolve, reject) {
31467
- function fulfilled(value2) {
31467
+ function fulfilled(value) {
31468
31468
  try {
31469
- step(generator.next(value2));
31469
+ step(generator.next(value));
31470
31470
  } catch (e2) {
31471
31471
  reject(e2);
31472
31472
  }
31473
31473
  }
31474
- function rejected(value2) {
31474
+ function rejected(value) {
31475
31475
  try {
31476
- step(generator["throw"](value2));
31476
+ step(generator["throw"](value));
31477
31477
  } catch (e2) {
31478
31478
  reject(e2);
31479
31479
  }
@@ -31825,22 +31825,22 @@ var require_logger = __commonJS((exports) => {
31825
31825
  // node_modules/binance/lib/main-client.js
31826
31826
  var require_main_client = __commonJS((exports) => {
31827
31827
  var __awaiter = exports && exports.__awaiter || function(thisArg, _arguments, P, generator) {
31828
- function adopt(value2) {
31829
- return value2 instanceof P ? value2 : new P(function(resolve) {
31830
- resolve(value2);
31828
+ function adopt(value) {
31829
+ return value instanceof P ? value : new P(function(resolve) {
31830
+ resolve(value);
31831
31831
  });
31832
31832
  }
31833
31833
  return new (P || (P = Promise))(function(resolve, reject) {
31834
- function fulfilled(value2) {
31834
+ function fulfilled(value) {
31835
31835
  try {
31836
- step(generator.next(value2));
31836
+ step(generator.next(value));
31837
31837
  } catch (e2) {
31838
31838
  reject(e2);
31839
31839
  }
31840
31840
  }
31841
- function rejected(value2) {
31841
+ function rejected(value) {
31842
31842
  try {
31843
- step(generator["throw"](value2));
31843
+ step(generator["throw"](value));
31844
31844
  } catch (e2) {
31845
31845
  reject(e2);
31846
31846
  }
@@ -33371,22 +33371,22 @@ var require_main_client = __commonJS((exports) => {
33371
33371
  // node_modules/binance/lib/portfolio-client.js
33372
33372
  var require_portfolio_client = __commonJS((exports) => {
33373
33373
  var __awaiter = exports && exports.__awaiter || function(thisArg, _arguments, P, generator) {
33374
- function adopt(value2) {
33375
- return value2 instanceof P ? value2 : new P(function(resolve) {
33376
- resolve(value2);
33374
+ function adopt(value) {
33375
+ return value instanceof P ? value : new P(function(resolve) {
33376
+ resolve(value);
33377
33377
  });
33378
33378
  }
33379
33379
  return new (P || (P = Promise))(function(resolve, reject) {
33380
- function fulfilled(value2) {
33380
+ function fulfilled(value) {
33381
33381
  try {
33382
- step(generator.next(value2));
33382
+ step(generator.next(value));
33383
33383
  } catch (e2) {
33384
33384
  reject(e2);
33385
33385
  }
33386
33386
  }
33387
- function rejected(value2) {
33387
+ function rejected(value) {
33388
33388
  try {
33389
- step(generator["throw"](value2));
33389
+ step(generator["throw"](value));
33390
33390
  } catch (e2) {
33391
33391
  reject(e2);
33392
33392
  }
@@ -33845,22 +33845,22 @@ var require_websockets = __commonJS((exports) => {
33845
33845
  // node_modules/binance/lib/usdm-client.js
33846
33846
  var require_usdm_client = __commonJS((exports) => {
33847
33847
  var __awaiter = exports && exports.__awaiter || function(thisArg, _arguments, P, generator) {
33848
- function adopt(value2) {
33849
- return value2 instanceof P ? value2 : new P(function(resolve) {
33850
- resolve(value2);
33848
+ function adopt(value) {
33849
+ return value instanceof P ? value : new P(function(resolve) {
33850
+ resolve(value);
33851
33851
  });
33852
33852
  }
33853
33853
  return new (P || (P = Promise))(function(resolve, reject) {
33854
- function fulfilled(value2) {
33854
+ function fulfilled(value) {
33855
33855
  try {
33856
- step(generator.next(value2));
33856
+ step(generator.next(value));
33857
33857
  } catch (e2) {
33858
33858
  reject(e2);
33859
33859
  }
33860
33860
  }
33861
- function rejected(value2) {
33861
+ function rejected(value) {
33862
33862
  try {
33863
- step(generator["throw"](value2));
33863
+ step(generator["throw"](value));
33864
33864
  } catch (e2) {
33865
33865
  reject(e2);
33866
33866
  }
@@ -34775,35 +34775,35 @@ var require_permessage_deflate = __commonJS((exports, module) => {
34775
34775
  normalizeParams(configurations) {
34776
34776
  configurations.forEach((params) => {
34777
34777
  Object.keys(params).forEach((key) => {
34778
- let value2 = params[key];
34779
- if (value2.length > 1) {
34778
+ let value = params[key];
34779
+ if (value.length > 1) {
34780
34780
  throw new Error(`Parameter "${key}" must have only a single value`);
34781
34781
  }
34782
- value2 = value2[0];
34782
+ value = value[0];
34783
34783
  if (key === "client_max_window_bits") {
34784
- if (value2 !== true) {
34785
- const num = +value2;
34784
+ if (value !== true) {
34785
+ const num = +value;
34786
34786
  if (!Number.isInteger(num) || num < 8 || num > 15) {
34787
- throw new TypeError(`Invalid value for parameter "${key}": ${value2}`);
34787
+ throw new TypeError(`Invalid value for parameter "${key}": ${value}`);
34788
34788
  }
34789
- value2 = num;
34789
+ value = num;
34790
34790
  } else if (!this._isServer) {
34791
- throw new TypeError(`Invalid value for parameter "${key}": ${value2}`);
34791
+ throw new TypeError(`Invalid value for parameter "${key}": ${value}`);
34792
34792
  }
34793
34793
  } else if (key === "server_max_window_bits") {
34794
- const num = +value2;
34794
+ const num = +value;
34795
34795
  if (!Number.isInteger(num) || num < 8 || num > 15) {
34796
- throw new TypeError(`Invalid value for parameter "${key}": ${value2}`);
34796
+ throw new TypeError(`Invalid value for parameter "${key}": ${value}`);
34797
34797
  }
34798
- value2 = num;
34798
+ value = num;
34799
34799
  } else if (key === "client_no_context_takeover" || key === "server_no_context_takeover") {
34800
- if (value2 !== true) {
34801
- throw new TypeError(`Invalid value for parameter "${key}": ${value2}`);
34800
+ if (value !== true) {
34801
+ throw new TypeError(`Invalid value for parameter "${key}": ${value}`);
34802
34802
  }
34803
34803
  } else {
34804
34804
  throw new Error(`Unknown parameter "${key}"`);
34805
34805
  }
34806
- params[key] = value2;
34806
+ params[key] = value;
34807
34807
  });
34808
34808
  });
34809
34809
  return configurations;
@@ -35086,8 +35086,8 @@ var require_validation = __commonJS((exports, module) => {
35086
35086
  }
35087
35087
  return true;
35088
35088
  }
35089
- function isBlob(value2) {
35090
- return hasBlob && typeof value2 === "object" && typeof value2.arrayBuffer === "function" && typeof value2.type === "string" && typeof value2.stream === "function" && (value2[Symbol.toStringTag] === "Blob" || value2[Symbol.toStringTag] === "File");
35089
+ function isBlob(value) {
35090
+ return hasBlob && typeof value === "object" && typeof value.arrayBuffer === "function" && typeof value.type === "string" && typeof value.stream === "function" && (value[Symbol.toStringTag] === "Blob" || value[Symbol.toStringTag] === "File");
35091
35091
  }
35092
35092
  module.exports = {
35093
35093
  isBlob,
@@ -36105,12 +36105,12 @@ var require_extension = __commonJS((exports, module) => {
36105
36105
  }
36106
36106
  if (end === -1)
36107
36107
  end = i2;
36108
- let value2 = header.slice(start, end);
36108
+ let value = header.slice(start, end);
36109
36109
  if (mustUnescape) {
36110
- value2 = value2.replace(/\\/g, "");
36110
+ value = value.replace(/\\/g, "");
36111
36111
  mustUnescape = false;
36112
36112
  }
36113
- push(params, paramName, value2);
36113
+ push(params, paramName, value);
36114
36114
  if (code === 44) {
36115
36115
  push(offers, extensionName, params);
36116
36116
  params = Object.create(null);
@@ -36633,8 +36633,8 @@ var require_websocket = __commonJS((exports, module) => {
36633
36633
  const headers = options && options.headers;
36634
36634
  options = { ...options, headers: {} };
36635
36635
  if (headers) {
36636
- for (const [key2, value2] of Object.entries(headers)) {
36637
- options.headers[key2.toLowerCase()] = value2;
36636
+ for (const [key2, value] of Object.entries(headers)) {
36637
+ options.headers[key2.toLowerCase()] = value;
36638
36638
  }
36639
36639
  }
36640
36640
  } else if (websocket.listenerCount("redirect") === 0) {
@@ -37296,10 +37296,10 @@ var require_websocket_server = __commonJS((exports, module) => {
37296
37296
  }
37297
37297
  if (extensions[PerMessageDeflate.extensionName]) {
37298
37298
  const params = extensions[PerMessageDeflate.extensionName].params;
37299
- const value2 = extension.format({
37299
+ const value = extension.format({
37300
37300
  [PerMessageDeflate.extensionName]: [params]
37301
37301
  });
37302
- headers.push(`Sec-WebSocket-Extensions: ${value2}`);
37302
+ headers.push(`Sec-WebSocket-Extensions: ${value}`);
37303
37303
  ws._extensions = extensions;
37304
37304
  }
37305
37305
  this.emit("headers", headers, req);
@@ -37426,22 +37426,22 @@ var require_websocket_client = __commonJS((exports) => {
37426
37426
  return result;
37427
37427
  };
37428
37428
  var __awaiter = exports && exports.__awaiter || function(thisArg, _arguments, P, generator) {
37429
- function adopt(value2) {
37430
- return value2 instanceof P ? value2 : new P(function(resolve) {
37431
- resolve(value2);
37429
+ function adopt(value) {
37430
+ return value instanceof P ? value : new P(function(resolve) {
37431
+ resolve(value);
37432
37432
  });
37433
37433
  }
37434
37434
  return new (P || (P = Promise))(function(resolve, reject) {
37435
- function fulfilled(value2) {
37435
+ function fulfilled(value) {
37436
37436
  try {
37437
- step(generator.next(value2));
37437
+ step(generator.next(value));
37438
37438
  } catch (e2) {
37439
37439
  reject(e2);
37440
37440
  }
37441
37441
  }
37442
- function rejected(value2) {
37442
+ function rejected(value) {
37443
37443
  try {
37444
- step(generator["throw"](value2));
37444
+ step(generator["throw"](value));
37445
37445
  } catch (e2) {
37446
37446
  reject(e2);
37447
37447
  }
@@ -37933,10 +37933,10 @@ var require_websocket_client = __commonJS((exports) => {
37933
37933
  });
37934
37934
  this.tryWsSend(wsKey, wsMessage);
37935
37935
  }
37936
- requestSetProperty(wsKey, property, value2, requestId) {
37936
+ requestSetProperty(wsKey, property, value, requestId) {
37937
37937
  const wsMessage = JSON.stringify({
37938
37938
  method: "SET_PROPERTY",
37939
- params: [property, value2],
37939
+ params: [property, value],
37940
37940
  id: requestId
37941
37941
  });
37942
37942
  this.tryWsSend(wsKey, wsMessage);
@@ -52556,267 +52556,8 @@ __export(exports_exchange_account, {
52556
52556
  ExchangeAccount: () => ExchangeAccount
52557
52557
  });
52558
52558
 
52559
- // src/helpers/pnl.ts
52560
- function determine_position_size(entry, stop, budget) {
52561
- let stop_percent = Math.abs(entry - stop) / entry;
52562
- let size = budget / stop_percent / entry;
52563
- return size;
52564
- }
52565
- function determine_risk(entry, stop, quantity) {
52566
- let stop_percent = Math.abs(entry - stop) / entry;
52567
- let risk = quantity * stop_percent * entry;
52568
- return risk;
52569
- }
52570
- function determine_close_price(entry, pnl, quantity, kind, single = false, leverage = 1) {
52571
- const dollar_value = entry / leverage;
52572
- const position = dollar_value * quantity;
52573
- if (position) {
52574
- let percent = pnl / position;
52575
- let difference = position * percent / quantity;
52576
- let result;
52577
- if (kind === "long") {
52578
- result = difference + entry;
52579
- } else {
52580
- result = entry - difference;
52581
- }
52582
- if (single) {
52583
- return result;
52584
- }
52585
- return result;
52586
- }
52587
- return 0;
52588
- }
52589
- function determine_amount_to_sell(entry, quantity, sell_price, pnl, kind, places = "%.3f") {
52590
- const _pnl = determine_pnl(entry, sell_price, quantity, kind);
52591
- const ratio = pnl / to_f(Math.abs(_pnl), places);
52592
- quantity = quantity * ratio;
52593
- return to_f(quantity, places);
52594
- }
52595
- function determine_pnl(entry, close_price, quantity, kind, contract_size, places = "%.2f") {
52596
- if (contract_size) {
52597
- const direction = kind === "long" ? 1 : -1;
52598
- return quantity * contract_size * direction * (1 / entry - 1 / close_price);
52599
- }
52600
- let difference = entry - close_price;
52601
- if (kind === "long") {
52602
- difference = close_price - entry;
52603
- }
52604
- return to_f(difference * quantity, places);
52605
- }
52606
- function position(entry, quantity, kind, leverage = 1) {
52607
- const direction = { long: 1, short: -1 };
52608
- return parseFloat((direction[kind] * quantity * (entry / leverage)).toFixed(3));
52609
- }
52610
- function to_f(value, places) {
52611
- if (value) {
52612
- let pp = parseInt(places.replace("%.", "").replace("f", ""));
52613
- return parseFloat(value.toFixed(pp));
52614
- }
52615
- return value;
52616
- }
52617
- var value = {
52618
- determine_risk,
52619
- determine_position_size,
52620
- determine_close_price,
52621
- determine_pnl,
52622
- position,
52623
- determine_amount_to_sell,
52624
- to_f
52625
- };
52626
- var pnl_default = value;
52627
-
52628
- // src/helpers/trade_utils.ts
52629
- function to_f2(value2, places = "%.1f") {
52630
- let v = typeof value2 === "string" ? parseFloat(value2) : value2;
52631
- const formattedValue = places.replace("%.", "").replace("f", "");
52632
- return parseFloat(v.toFixed(parseInt(formattedValue)));
52633
- }
52634
- function determine_amount_to_sell2(entry, quantity, sell_price, pnl, kind, places = "%.3f") {
52635
- const _pnl = determine_pnl2(entry, sell_price, quantity, kind);
52636
- const ratio = pnl / to_f2(Math.abs(_pnl), places);
52637
- quantity = quantity * ratio;
52638
- return to_f2(quantity, places);
52639
- }
52640
- function determine_position_size2({
52641
- entry,
52642
- stop,
52643
- budget,
52644
- percent,
52645
- min_size,
52646
- notional_value,
52647
- as_coin = true,
52648
- places = "%.3f"
52649
- }) {
52650
- let stop_percent = stop ? Math.abs(entry - stop) / entry : percent;
52651
- if (stop_percent && budget) {
52652
- let size = budget / stop_percent;
52653
- let notion_value = size * entry;
52654
- if (notional_value && notional_value > notion_value) {
52655
- size = notional_value / entry;
52656
- }
52657
- if (as_coin) {
52658
- size = size / entry;
52659
- if (min_size && min_size === 1) {
52660
- return to_f2(Math.round(size), places);
52661
- }
52662
- }
52663
- return to_f2(size, places);
52664
- }
52665
- return;
52666
- }
52667
- function determine_average_entry_and_size(orders, places = "%.3f", price_places = "%.1f") {
52668
- const sum_values = orders.reduce((sum, order) => sum + order.price * order.quantity, 0);
52669
- const total_quantity = orders.reduce((sum, order) => sum + order.quantity, 0);
52670
- const avg_price = total_quantity ? to_f2(sum_values / total_quantity, price_places) : 0;
52671
- return {
52672
- entry: avg_price,
52673
- price: avg_price,
52674
- quantity: to_f2(total_quantity, places)
52675
- };
52676
- }
52677
- var createArray = (start, stop, step) => {
52678
- const result = [];
52679
- let current = start;
52680
- while (current <= stop) {
52681
- result.push(current);
52682
- current += step;
52683
- }
52684
- return result;
52685
- };
52686
- var groupIntoPairsWithSumLessThan = (arr, targetSum, key = "quantity", firstSize = 0) => {
52687
- if (firstSize) {
52688
- const totalSize = arr.reduce((sum, order) => sum + order[key], 0);
52689
- const remainingSize = totalSize - firstSize;
52690
- let newSum = 0;
52691
- let newArray = [];
52692
- let lastIndex = 0;
52693
- for (let i2 = 0;i2 < arr.length; i2++) {
52694
- if (newSum < remainingSize) {
52695
- newSum += arr[i2][key];
52696
- newArray.push(arr[i2]);
52697
- lastIndex = i2;
52698
- }
52699
- }
52700
- const lastGroup = arr.slice(lastIndex + 1);
52701
- const previousPair = groupInPairs(newArray, key, targetSum);
52702
- if (lastGroup.length > 0) {
52703
- previousPair.push(lastGroup);
52704
- }
52705
- return previousPair;
52706
- }
52707
- return groupInPairs(arr, key, targetSum);
52708
- };
52709
- function groupInPairs(_arr, key, targetSum) {
52710
- const result = [];
52711
- let currentSum = 0;
52712
- let currentGroup = [];
52713
- for (let i2 = 0;i2 < _arr.length; i2++) {
52714
- currentSum += _arr[i2][key];
52715
- currentGroup.push(_arr[i2]);
52716
- if (currentSum >= targetSum) {
52717
- result.push(currentGroup);
52718
- currentGroup = [];
52719
- currentSum = 0;
52720
- }
52721
- }
52722
- return result;
52723
- }
52724
- var computeTotalAverageForEachTrade = (trades, config2) => {
52725
- let _take_profit = config2.take_profit;
52726
- let kind = config2.kind;
52727
- let entryToUse = kind === "short" ? Math.min(config2.entry, config2.stop) : Math.max(config2.entry, config2.stop);
52728
- let _currentEntry = config2.currentEntry || entryToUse;
52729
- let less = trades.filter((p) => kind === "long" ? p.entry <= _currentEntry : p.entry >= _currentEntry);
52730
- let rrr = trades.map((r2, i2) => {
52731
- let considered = [];
52732
- if (kind === "long") {
52733
- considered = trades.filter((p) => p.entry > _currentEntry);
52734
- } else {
52735
- considered = trades.filter((p) => p.entry < _currentEntry);
52736
- }
52737
- const x_pnl = 0;
52738
- const remaining = less.filter((o) => {
52739
- if (kind === "long") {
52740
- return o.entry >= r2.entry;
52741
- }
52742
- return o.entry <= r2.entry;
52743
- });
52744
- if (remaining.length === 0) {
52745
- return { ...r2, pnl: x_pnl };
52746
- }
52747
- const start = kind === "long" ? Math.max(...remaining.map((o) => o.entry)) : Math.min(...remaining.map((o) => o.entry));
52748
- considered = considered.map((o) => ({ ...o, entry: start }));
52749
- considered = considered.concat(remaining);
52750
- let avg_entry = determine_average_entry_and_size([
52751
- ...considered.map((o) => ({
52752
- price: o.entry,
52753
- quantity: o.quantity
52754
- })),
52755
- {
52756
- price: _currentEntry,
52757
- quantity: config2.currentQty || 0
52758
- }
52759
- ], config2.decimal_places, config2.price_places);
52760
- let _pnl = r2.pnl;
52761
- let sell_price = r2.sell_price;
52762
- let entry_pnl = r2.pnl;
52763
- if (_take_profit) {
52764
- _pnl = pnl_default.determine_pnl(avg_entry.price, _take_profit, avg_entry.quantity, kind);
52765
- sell_price = _take_profit;
52766
- entry_pnl = pnl_default.determine_pnl(r2.entry, _take_profit, avg_entry.quantity, kind);
52767
- }
52768
- const loss = pnl_default.determine_pnl(avg_entry.price, r2.stop, avg_entry.quantity, kind);
52769
- let new_stop = r2.new_stop;
52770
- const entry_loss = pnl_default.determine_pnl(r2.entry, new_stop, avg_entry.quantity, kind);
52771
- let min_profit = 0;
52772
- let min_entry_profit = 0;
52773
- if (config2.min_profit) {
52774
- min_profit = pnl_default.determine_close_price(avg_entry.price, config2.min_profit, avg_entry.quantity, kind);
52775
- min_entry_profit = pnl_default.determine_close_price(r2.entry, config2.min_profit, avg_entry.quantity, kind);
52776
- }
52777
- let x_fee = r2.fee;
52778
- if (config2.fee) {
52779
- x_fee = config2.fee * r2.stop * avg_entry.quantity;
52780
- }
52781
- let tp_close = pnl_default.determine_close_price(r2.entry, Math.abs(entry_loss) * (config2.rr || 1) + x_fee, avg_entry.quantity, kind);
52782
- return {
52783
- ...r2,
52784
- x_fee: to_f2(x_fee, "%.2f"),
52785
- avg_entry: avg_entry.price,
52786
- avg_size: avg_entry.quantity,
52787
- entry_pnl: to_f2(entry_pnl, "%.2f"),
52788
- entry_loss: to_f2(entry_loss, "%.2f"),
52789
- min_entry_pnl: to_f2(min_entry_profit, "%.2f"),
52790
- pnl: _pnl,
52791
- neg_pnl: to_f2(loss, "%.2f"),
52792
- sell_price,
52793
- close_p: to_f2(tp_close, "%.2f"),
52794
- min_pnl: to_f2(min_profit, "%.2f"),
52795
- new_stop
52796
- };
52797
- });
52798
- return rrr;
52799
- };
52800
- function createGapPairs(arr, gap, item) {
52801
- if (arr.length === 0) {
52802
- return [];
52803
- }
52804
- const result = [];
52805
- const firstElement = arr[0];
52806
- for (let i2 = arr.length - 1;i2 >= 0; i2--) {
52807
- const current = arr[i2];
52808
- const gapIndex = i2 - gap;
52809
- const pairedElement = gapIndex < 0 ? firstElement : arr[gapIndex];
52810
- if (current !== pairedElement) {
52811
- result.push([current, pairedElement]);
52812
- }
52813
- }
52814
- if (item) {
52815
- let r2 = result.find((o) => o[0] === item);
52816
- return r2 ? [r2] : [];
52817
- }
52818
- return result;
52819
- }
52559
+ // src/exchanges/binance/index.ts
52560
+ var import_binance = __toESM(require_lib2(), 1);
52820
52561
 
52821
52562
  // src/helpers/optimizations.ts
52822
52563
  function calculateTheoreticalKelly({
@@ -52853,7 +52594,7 @@ function calculateTheoreticalKelly({
52853
52594
  kelly_fraction *= vol_adjustment;
52854
52595
  }
52855
52596
  kelly_fraction = Math.max(0.005, Math.min(kelly_fraction, 0.5));
52856
- return to_f2(kelly_fraction, "%.4f");
52597
+ return to_f(kelly_fraction, "%.4f");
52857
52598
  }
52858
52599
  function calculateZoneProbabilities({
52859
52600
  current_entry,
@@ -52962,7 +52703,7 @@ function calculateTheoreticalKellyFixed({
52962
52703
  kelly_fraction *= vol_adjustment;
52963
52704
  }
52964
52705
  kelly_fraction = Math.max(0.005, Math.min(kelly_fraction, 0.5));
52965
- return to_f2(kelly_fraction, "%.4f");
52706
+ return to_f(kelly_fraction, "%.4f");
52966
52707
  }
52967
52708
  function calculatePositionBasedKelly({
52968
52709
  current_entry,
@@ -52996,11 +52737,11 @@ function calculatePositionBasedKelly({
52996
52737
  const base_kelly = 0.02;
52997
52738
  const max_kelly = 0.2;
52998
52739
  const kelly_fraction = base_kelly + adjusted_score * (max_kelly - base_kelly);
52999
- return to_f2(kelly_fraction, "%.4f");
52740
+ return to_f(kelly_fraction, "%.4f");
53000
52741
  }
53001
52742
 
53002
52743
  // src/helpers/trade_signal.ts
53003
- function determine_close_price2({
52744
+ function determine_close_price({
53004
52745
  entry,
53005
52746
  pnl,
53006
52747
  quantity,
@@ -53008,16 +52749,16 @@ function determine_close_price2({
53008
52749
  kind = "long"
53009
52750
  }) {
53010
52751
  const dollar_value = entry / leverage;
53011
- const position2 = dollar_value * quantity;
53012
- if (position2) {
53013
- const percent = pnl / position2;
53014
- const difference = position2 * percent / quantity;
52752
+ const position = dollar_value * quantity;
52753
+ if (position) {
52754
+ const percent = pnl / position;
52755
+ const difference = position * percent / quantity;
53015
52756
  const result = kind === "long" ? difference + entry : entry - difference;
53016
52757
  return result;
53017
52758
  }
53018
52759
  return 0;
53019
52760
  }
53020
- function determine_pnl2(entry, close_price, quantity, kind = "long", contract_size) {
52761
+ function determine_pnl(entry, close_price, quantity, kind = "long", contract_size) {
53021
52762
  if (contract_size) {
53022
52763
  const direction = kind === "long" ? 1 : -1;
53023
52764
  return quantity * contract_size * direction * (1 / entry - 1 / close_price);
@@ -53036,7 +52777,7 @@ function* _get_zones({
53036
52777
  let focus_low = last * Math.pow(1 + percent_change, -1);
53037
52778
  if (focus_high > current_price) {
53038
52779
  while (focus_high > current_price) {
53039
- yield to_f2(last, places);
52780
+ yield to_f(last, places);
53040
52781
  focus_high = last;
53041
52782
  last = focus_high * Math.pow(1 + percent_change, -1);
53042
52783
  focus_low = last * Math.pow(1 + percent_change, -1);
@@ -53044,14 +52785,14 @@ function* _get_zones({
53044
52785
  } else {
53045
52786
  if (focus_high <= current_price) {
53046
52787
  while (focus_high <= current_price) {
53047
- yield to_f2(focus_high, places);
52788
+ yield to_f(focus_high, places);
53048
52789
  focus_low = focus_high;
53049
52790
  last = focus_low * (1 + percent_change);
53050
52791
  focus_high = last * (1 + percent_change);
53051
52792
  }
53052
52793
  } else {
53053
52794
  while (focus_low <= current_price) {
53054
- yield to_f2(focus_high, places);
52795
+ yield to_f(focus_high, places);
53055
52796
  focus_low = focus_high;
53056
52797
  last = focus_low * (1 + percent_change);
53057
52798
  focus_high = last * (1 + percent_change);
@@ -53330,7 +53071,7 @@ class Signal {
53330
53071
  } else {
53331
53072
  i2["risk_sell"] = Math.min(...potentials.slice(0, max_index));
53332
53073
  }
53333
- i2["pnl"] = this.to_df(determine_pnl2(i2["entry"], i2["risk_sell"], i2["quantity"], kind));
53074
+ i2["pnl"] = this.to_df(determine_pnl(i2["entry"], i2["risk_sell"], i2["quantity"], kind));
53334
53075
  }
53335
53076
  }
53336
53077
  }
@@ -53394,13 +53135,13 @@ class Signal {
53394
53135
  let remaining_zones = margin_zones.filter((x) => JSON.stringify(x) != JSON.stringify(margin_range));
53395
53136
  if (margin_range) {
53396
53137
  const difference = Math.abs(margin_range[0] - margin_range[1]);
53397
- const spread = to_f2(difference / this.risk_reward, this.price_places);
53138
+ const spread = to_f(difference / this.risk_reward, this.price_places);
53398
53139
  let entries;
53399
53140
  const percent_change = this.percent_change / this.risk_reward;
53400
53141
  if (kind === "long") {
53401
- entries = Array.from({ length: Math.floor(this.risk_reward) + 1 }, (_, x) => to_f2(margin_range[1] - spread * x, this.price_places));
53142
+ entries = Array.from({ length: Math.floor(this.risk_reward) + 1 }, (_, x) => to_f(margin_range[1] - spread * x, this.price_places));
53402
53143
  } else {
53403
- entries = Array.from({ length: Math.floor(this.risk_reward) + 1 }, (_, x) => to_f2(margin_range[1] * Math.pow(1 + percent_change, x), this.price_places));
53144
+ 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));
53404
53145
  }
53405
53146
  if (Math.min(...entries) < this.to_f(current_price) && this.to_f(current_price) < Math.max(...entries)) {
53406
53147
  return entries.sort((a, b) => a - b);
@@ -53412,14 +53153,14 @@ class Signal {
53412
53153
  if (new_range) {
53413
53154
  while (entries2.length < this.risk_reward + 1) {
53414
53155
  if (kind === "long") {
53415
- let value2 = this.to_f(new_range[1] - spread * x);
53416
- if (value2 <= current_price) {
53417
- entries2.push(value2);
53156
+ let value = this.to_f(new_range[1] - spread * x);
53157
+ if (value <= current_price) {
53158
+ entries2.push(value);
53418
53159
  }
53419
53160
  } else {
53420
- let value2 = this.to_f(new_range[1] * Math.pow(1 + percent_change, x));
53421
- if (value2 >= current_price) {
53422
- entries2.push(value2);
53161
+ let value = this.to_f(new_range[1] * Math.pow(1 + percent_change, x));
53162
+ if (value >= current_price) {
53163
+ entries2.push(value);
53423
53164
  }
53424
53165
  }
53425
53166
  x += 1;
@@ -53433,14 +53174,14 @@ class Signal {
53433
53174
  let x = 0;
53434
53175
  while (entries2.length < this.risk_reward + 1) {
53435
53176
  if (kind === "long") {
53436
- let value2 = this.to_f(next_focus - spread * x);
53437
- if (value2 <= this.to_f(current_price)) {
53438
- entries2.push(value2);
53177
+ let value = this.to_f(next_focus - spread * x);
53178
+ if (value <= this.to_f(current_price)) {
53179
+ entries2.push(value);
53439
53180
  }
53440
53181
  } else {
53441
- let value2 = this.to_f(next_focus * Math.pow(1 + percent_change, x));
53442
- if (value2 >= this.to_f(current_price)) {
53443
- entries2.push(value2);
53182
+ let value = this.to_f(next_focus * Math.pow(1 + percent_change, x));
53183
+ if (value >= this.to_f(current_price)) {
53184
+ entries2.push(value);
53444
53185
  }
53445
53186
  }
53446
53187
  x += 1;
@@ -53451,8 +53192,8 @@ class Signal {
53451
53192
  }
53452
53193
  return [];
53453
53194
  }
53454
- to_f(value2, places) {
53455
- return to_f2(value2, places || this.price_places);
53195
+ to_f(value, places) {
53196
+ return to_f(value, places || this.price_places);
53456
53197
  }
53457
53198
  get_margin_zones({
53458
53199
  current_price,
@@ -53670,7 +53411,7 @@ class Signal {
53670
53411
  }) {
53671
53412
  const considered = arr.map((x, i2) => i2).filter((i2) => i2 > index);
53672
53413
  const with_quantity = considered.map((x) => {
53673
- const q = determine_position_size2({
53414
+ const q = determine_position_size({
53674
53415
  entry: arr[x],
53675
53416
  stop: arr[x - 1],
53676
53417
  budget: risk,
@@ -53704,7 +53445,7 @@ class Signal {
53704
53445
  const incurred_fees = fees.reduce((a, b) => a + b, 0) + previous_risks.reduce((a, b) => a + b, 0);
53705
53446
  if (index === 0) {
53706
53447
  }
53707
- let quantity = determine_position_size2({
53448
+ let quantity = determine_position_size({
53708
53449
  entry,
53709
53450
  stop,
53710
53451
  budget: risk,
@@ -53716,7 +53457,7 @@ class Signal {
53716
53457
  }
53717
53458
  if (this.increase_size) {
53718
53459
  quantity = quantity * multiplier;
53719
- const new_risk = determine_pnl2(entry, stop, quantity, kind);
53460
+ const new_risk = determine_pnl(entry, stop, quantity, kind);
53720
53461
  risk = Math.abs(new_risk);
53721
53462
  }
53722
53463
  const fee = this.to_df(this.fee * quantity * entry);
@@ -53725,12 +53466,12 @@ class Signal {
53725
53466
  if (this.minimum_pnl) {
53726
53467
  pnl = this.minimum_pnl + fee;
53727
53468
  }
53728
- let sell_price = determine_close_price2({ entry, pnl, quantity, kind });
53469
+ let sell_price = determine_close_price({ entry, pnl, quantity, kind });
53729
53470
  if (take_profit && !this.minimum_pnl) {
53730
53471
  sell_price = take_profit;
53731
- pnl = this.to_df(determine_pnl2(entry, sell_price, quantity, kind));
53472
+ pnl = this.to_df(determine_pnl(entry, sell_price, quantity, kind));
53732
53473
  pnl = pnl + fee;
53733
- sell_price = determine_close_price2({ entry, pnl, quantity, kind });
53474
+ sell_price = determine_close_price({ entry, pnl, quantity, kind });
53734
53475
  }
53735
53476
  let risk_sell = sell_price;
53736
53477
  return {
@@ -53748,10 +53489,271 @@ class Signal {
53748
53489
  };
53749
53490
  }
53750
53491
  to_df(currentPrice, places = "%.3f") {
53751
- return to_f2(currentPrice, places);
53492
+ return to_f(currentPrice, places);
53493
+ }
53494
+ }
53495
+
53496
+ // src/helpers/pnl.ts
53497
+ function determine_position_size2(entry, stop, budget) {
53498
+ let stop_percent = Math.abs(entry - stop) / entry;
53499
+ let size = budget / stop_percent / entry;
53500
+ return size;
53501
+ }
53502
+ function determine_risk(entry, stop, quantity) {
53503
+ let stop_percent = Math.abs(entry - stop) / entry;
53504
+ let risk = quantity * stop_percent * entry;
53505
+ return risk;
53506
+ }
53507
+ function determine_close_price2(entry, pnl, quantity, kind, single = false, leverage = 1) {
53508
+ const dollar_value = entry / leverage;
53509
+ const position = dollar_value * quantity;
53510
+ if (position) {
53511
+ let percent = pnl / position;
53512
+ let difference = position * percent / quantity;
53513
+ let result;
53514
+ if (kind === "long") {
53515
+ result = difference + entry;
53516
+ } else {
53517
+ result = entry - difference;
53518
+ }
53519
+ if (single) {
53520
+ return result;
53521
+ }
53522
+ return result;
53523
+ }
53524
+ return 0;
53525
+ }
53526
+ function determine_amount_to_sell(entry, quantity, sell_price, pnl, kind, places = "%.3f") {
53527
+ const _pnl = determine_pnl2(entry, sell_price, quantity, kind);
53528
+ const ratio = pnl / to_f2(Math.abs(_pnl), places);
53529
+ quantity = quantity * ratio;
53530
+ return to_f2(quantity, places);
53531
+ }
53532
+ function determine_pnl2(entry, close_price, quantity, kind, contract_size, places = "%.2f") {
53533
+ if (contract_size) {
53534
+ const direction = kind === "long" ? 1 : -1;
53535
+ return quantity * contract_size * direction * (1 / entry - 1 / close_price);
53536
+ }
53537
+ let difference = entry - close_price;
53538
+ if (kind === "long") {
53539
+ difference = close_price - entry;
53540
+ }
53541
+ return to_f2(difference * quantity, places);
53542
+ }
53543
+ function position(entry, quantity, kind, leverage = 1) {
53544
+ const direction = { long: 1, short: -1 };
53545
+ return parseFloat((direction[kind] * quantity * (entry / leverage)).toFixed(3));
53546
+ }
53547
+ function to_f2(value, places) {
53548
+ if (value) {
53549
+ let pp = parseInt(places.replace("%.", "").replace("f", ""));
53550
+ return parseFloat(value.toFixed(pp));
53752
53551
  }
53552
+ return value;
53753
53553
  }
53554
+ var value = {
53555
+ determine_risk,
53556
+ determine_position_size: determine_position_size2,
53557
+ determine_close_price: determine_close_price2,
53558
+ determine_pnl: determine_pnl2,
53559
+ position,
53560
+ determine_amount_to_sell,
53561
+ to_f: to_f2
53562
+ };
53563
+ var pnl_default = value;
53754
53564
 
53565
+ // src/helpers/trade_utils.ts
53566
+ function to_f(value2, places = "%.1f") {
53567
+ let v = typeof value2 === "string" ? parseFloat(value2) : value2;
53568
+ const formattedValue = places.replace("%.", "").replace("f", "");
53569
+ return parseFloat(v.toFixed(parseInt(formattedValue)));
53570
+ }
53571
+ function determine_amount_to_sell2(entry, quantity, sell_price, pnl, kind, places = "%.3f") {
53572
+ const _pnl = determine_pnl(entry, sell_price, quantity, kind);
53573
+ const ratio = pnl / to_f(Math.abs(_pnl), places);
53574
+ quantity = quantity * ratio;
53575
+ return to_f(quantity, places);
53576
+ }
53577
+ function determine_position_size({
53578
+ entry,
53579
+ stop,
53580
+ budget,
53581
+ percent,
53582
+ min_size,
53583
+ notional_value,
53584
+ as_coin = true,
53585
+ places = "%.3f"
53586
+ }) {
53587
+ let stop_percent = stop ? Math.abs(entry - stop) / entry : percent;
53588
+ if (stop_percent && budget) {
53589
+ let size = budget / stop_percent;
53590
+ let notion_value = size * entry;
53591
+ if (notional_value && notional_value > notion_value) {
53592
+ size = notional_value / entry;
53593
+ }
53594
+ if (as_coin) {
53595
+ size = size / entry;
53596
+ if (min_size && min_size === 1) {
53597
+ return to_f(Math.round(size), places);
53598
+ }
53599
+ }
53600
+ return to_f(size, places);
53601
+ }
53602
+ return;
53603
+ }
53604
+ function determine_average_entry_and_size(orders, places = "%.3f", price_places = "%.1f") {
53605
+ const sum_values = orders.reduce((sum, order) => sum + order.price * order.quantity, 0);
53606
+ const total_quantity = orders.reduce((sum, order) => sum + order.quantity, 0);
53607
+ const avg_price = total_quantity ? to_f(sum_values / total_quantity, price_places) : 0;
53608
+ return {
53609
+ entry: avg_price,
53610
+ price: avg_price,
53611
+ quantity: to_f(total_quantity, places)
53612
+ };
53613
+ }
53614
+ var createArray = (start, stop, step) => {
53615
+ const result = [];
53616
+ let current = start;
53617
+ while (current <= stop) {
53618
+ result.push(current);
53619
+ current += step;
53620
+ }
53621
+ return result;
53622
+ };
53623
+ var groupIntoPairsWithSumLessThan = (arr, targetSum, key = "quantity", firstSize = 0) => {
53624
+ if (firstSize) {
53625
+ const totalSize = arr.reduce((sum, order) => sum + order[key], 0);
53626
+ const remainingSize = totalSize - firstSize;
53627
+ let newSum = 0;
53628
+ let newArray = [];
53629
+ let lastIndex = 0;
53630
+ for (let i2 = 0;i2 < arr.length; i2++) {
53631
+ if (newSum < remainingSize) {
53632
+ newSum += arr[i2][key];
53633
+ newArray.push(arr[i2]);
53634
+ lastIndex = i2;
53635
+ }
53636
+ }
53637
+ const lastGroup = arr.slice(lastIndex + 1);
53638
+ const previousPair = groupInPairs(newArray, key, targetSum);
53639
+ if (lastGroup.length > 0) {
53640
+ previousPair.push(lastGroup);
53641
+ }
53642
+ return previousPair;
53643
+ }
53644
+ return groupInPairs(arr, key, targetSum);
53645
+ };
53646
+ function groupInPairs(_arr, key, targetSum) {
53647
+ const result = [];
53648
+ let currentSum = 0;
53649
+ let currentGroup = [];
53650
+ for (let i2 = 0;i2 < _arr.length; i2++) {
53651
+ currentSum += _arr[i2][key];
53652
+ currentGroup.push(_arr[i2]);
53653
+ if (currentSum >= targetSum) {
53654
+ result.push(currentGroup);
53655
+ currentGroup = [];
53656
+ currentSum = 0;
53657
+ }
53658
+ }
53659
+ return result;
53660
+ }
53661
+ var computeTotalAverageForEachTrade = (trades, config2) => {
53662
+ let _take_profit = config2.take_profit;
53663
+ let kind = config2.kind;
53664
+ let entryToUse = kind === "short" ? Math.min(config2.entry, config2.stop) : Math.max(config2.entry, config2.stop);
53665
+ let _currentEntry = config2.currentEntry || entryToUse;
53666
+ let less = trades.filter((p) => kind === "long" ? p.entry <= _currentEntry : p.entry >= _currentEntry);
53667
+ let rrr = trades.map((r2, i2) => {
53668
+ let considered = [];
53669
+ if (kind === "long") {
53670
+ considered = trades.filter((p) => p.entry > _currentEntry);
53671
+ } else {
53672
+ considered = trades.filter((p) => p.entry < _currentEntry);
53673
+ }
53674
+ const x_pnl = 0;
53675
+ const remaining = less.filter((o) => {
53676
+ if (kind === "long") {
53677
+ return o.entry >= r2.entry;
53678
+ }
53679
+ return o.entry <= r2.entry;
53680
+ });
53681
+ if (remaining.length === 0) {
53682
+ return { ...r2, pnl: x_pnl };
53683
+ }
53684
+ const start = kind === "long" ? Math.max(...remaining.map((o) => o.entry)) : Math.min(...remaining.map((o) => o.entry));
53685
+ considered = considered.map((o) => ({ ...o, entry: start }));
53686
+ considered = considered.concat(remaining);
53687
+ let avg_entry = determine_average_entry_and_size([
53688
+ ...considered.map((o) => ({
53689
+ price: o.entry,
53690
+ quantity: o.quantity
53691
+ })),
53692
+ {
53693
+ price: _currentEntry,
53694
+ quantity: config2.currentQty || 0
53695
+ }
53696
+ ], config2.decimal_places, config2.price_places);
53697
+ let _pnl = r2.pnl;
53698
+ let sell_price = r2.sell_price;
53699
+ let entry_pnl = r2.pnl;
53700
+ if (_take_profit) {
53701
+ _pnl = pnl_default.determine_pnl(avg_entry.price, _take_profit, avg_entry.quantity, kind);
53702
+ sell_price = _take_profit;
53703
+ entry_pnl = pnl_default.determine_pnl(r2.entry, _take_profit, avg_entry.quantity, kind);
53704
+ }
53705
+ const loss = pnl_default.determine_pnl(avg_entry.price, r2.stop, avg_entry.quantity, kind);
53706
+ let new_stop = r2.new_stop;
53707
+ const entry_loss = pnl_default.determine_pnl(r2.entry, new_stop, avg_entry.quantity, kind);
53708
+ let min_profit = 0;
53709
+ let min_entry_profit = 0;
53710
+ if (config2.min_profit) {
53711
+ min_profit = pnl_default.determine_close_price(avg_entry.price, config2.min_profit, avg_entry.quantity, kind);
53712
+ min_entry_profit = pnl_default.determine_close_price(r2.entry, config2.min_profit, avg_entry.quantity, kind);
53713
+ }
53714
+ let x_fee = r2.fee;
53715
+ if (config2.fee) {
53716
+ x_fee = config2.fee * r2.stop * avg_entry.quantity;
53717
+ }
53718
+ let tp_close = pnl_default.determine_close_price(r2.entry, Math.abs(entry_loss) * (config2.rr || 1) + x_fee, avg_entry.quantity, kind);
53719
+ return {
53720
+ ...r2,
53721
+ x_fee: to_f(x_fee, "%.2f"),
53722
+ avg_entry: avg_entry.price,
53723
+ avg_size: avg_entry.quantity,
53724
+ entry_pnl: to_f(entry_pnl, "%.2f"),
53725
+ entry_loss: to_f(entry_loss, "%.2f"),
53726
+ min_entry_pnl: to_f(min_entry_profit, "%.2f"),
53727
+ pnl: _pnl,
53728
+ neg_pnl: to_f(loss, "%.2f"),
53729
+ sell_price,
53730
+ close_p: to_f(tp_close, "%.2f"),
53731
+ min_pnl: to_f(min_profit, "%.2f"),
53732
+ new_stop
53733
+ };
53734
+ });
53735
+ return rrr;
53736
+ };
53737
+ function createGapPairs(arr, gap, item) {
53738
+ if (arr.length === 0) {
53739
+ return [];
53740
+ }
53741
+ const result = [];
53742
+ const firstElement = arr[0];
53743
+ for (let i2 = arr.length - 1;i2 >= 0; i2--) {
53744
+ const current = arr[i2];
53745
+ const gapIndex = i2 - gap;
53746
+ const pairedElement = gapIndex < 0 ? firstElement : arr[gapIndex];
53747
+ if (current !== pairedElement) {
53748
+ result.push([current, pairedElement]);
53749
+ }
53750
+ }
53751
+ if (item) {
53752
+ let r2 = result.find((o) => o[0] === item);
53753
+ return r2 ? [r2] : [];
53754
+ }
53755
+ return result;
53756
+ }
53755
53757
  // src/helpers/shared.ts
53756
53758
  function getMaxQuantity(x, app_config) {
53757
53759
  let max_quantity = app_config.max_quantity;
@@ -53873,8 +53875,8 @@ function get_app_config_and_max_size(config2, payload) {
53873
53875
  stop: payload.stop,
53874
53876
  risk_per_trade: config2.risk,
53875
53877
  risk_reward: config2.risk_reward || 199,
53876
- support: to_f2(config2.support, config2.price_places),
53877
- resistance: to_f2(config2.resistance, config2.price_places),
53878
+ support: to_f(config2.support, config2.price_places),
53879
+ resistance: to_f(config2.resistance, config2.price_places),
53878
53880
  focus: payload.entry,
53879
53881
  fee: 0,
53880
53882
  percent_change: config2.stop_percent / 100,
@@ -54093,8 +54095,8 @@ function getOptimumStopAndRisk(app_config, params) {
54093
54095
  }
54094
54096
  }
54095
54097
  return {
54096
- optimal_stop: to_f2(optimal_stop, app_config.price_places),
54097
- optimal_risk: to_f2(final_risk, app_config.price_places),
54098
+ optimal_stop: to_f(optimal_stop, app_config.price_places),
54099
+ optimal_risk: to_f(final_risk, app_config.price_places),
54098
54100
  avg_size: final_result?.[0]?.avg_size || 0,
54099
54101
  avg_entry: final_result?.[0]?.avg_entry || 0,
54100
54102
  result: final_result,
@@ -54142,7 +54144,7 @@ function determine_amount_to_buy(payload) {
54142
54144
  existingOrders
54143
54145
  } = payload;
54144
54146
  const totalQuantity = orders.reduce((sum, order) => sum + (order.quantity || 0), 0);
54145
- let runningTotal = to_f2(totalQuantity, decimal_places);
54147
+ let runningTotal = to_f(totalQuantity, decimal_places);
54146
54148
  let sortedOrders = [...orders].sort((a, b) => (a.entry || 0) - (b.entry || 0));
54147
54149
  if (kind === "short") {
54148
54150
  sortedOrders.reverse();
@@ -54154,7 +54156,7 @@ function determine_amount_to_buy(payload) {
54154
54156
  cumulative_quantity: runningTotal
54155
54157
  });
54156
54158
  runningTotal -= order.quantity;
54157
- runningTotal = to_f2(runningTotal, decimal_places);
54159
+ runningTotal = to_f(runningTotal, decimal_places);
54158
54160
  }
54159
54161
  let filteredOrders = withCumulative.filter((order) => (order.cumulative_quantity || 0) > position2?.quantity).map((order) => ({
54160
54162
  ...order,
@@ -54417,10 +54419,10 @@ function determineOptimumRisk(config2, payload, params) {
54417
54419
  };
54418
54420
  const final_result = buildAppConfig(config2, final_payload);
54419
54421
  return {
54420
- optimal_risk: to_f2(best_risk, "%.2f"),
54421
- achieved_neg_pnl: to_f2(best_neg_pnl, "%.2f"),
54422
- target_neg_pnl: to_f2(highest_risk, "%.2f"),
54423
- difference: to_f2(best_diff, "%.2f"),
54422
+ optimal_risk: to_f(best_risk, "%.2f"),
54423
+ achieved_neg_pnl: to_f(best_neg_pnl, "%.2f"),
54424
+ target_neg_pnl: to_f(highest_risk, "%.2f"),
54425
+ difference: to_f(best_diff, "%.2f"),
54424
54426
  iterations,
54425
54427
  converged: best_diff <= tolerance,
54426
54428
  last_value: final_result.last_value,
@@ -54485,9 +54487,9 @@ function computeProfitDetail(payload) {
54485
54487
  full_ratio = 1
54486
54488
  } = payload;
54487
54489
  let reward_factor = strategy?.reward_factor || 1;
54488
- const profit_percent = to_f2(pnl * 100 / (focus_position.avg_price * focus_position.avg_qty), "%.4f");
54490
+ const profit_percent = to_f(pnl * 100 / (focus_position.avg_price * focus_position.avg_qty), "%.4f");
54489
54491
  const diff = pnl / focus_position.quantity;
54490
- const sell_price = to_f2(focus_position.kind === "long" ? focus_position.entry + diff : focus_position.entry - diff, price_places);
54492
+ const sell_price = to_f(focus_position.kind === "long" ? focus_position.entry + diff : focus_position.entry - diff, price_places);
54491
54493
  let loss = 0;
54492
54494
  let full_loss = 0;
54493
54495
  let expected_loss = 0;
@@ -54496,23 +54498,23 @@ function computeProfitDetail(payload) {
54496
54498
  if (reduce_position) {
54497
54499
  loss = Math.abs(reduce_position.entry - sell_price) * reduce_position.quantity;
54498
54500
  const ratio = pnl / loss;
54499
- quantity = to_f2(reduce_position.quantity * ratio, decimal_places);
54500
- expected_loss = to_f2(Math.abs(reduce_position.entry - sell_price) * quantity, "%.2f");
54501
+ quantity = to_f(reduce_position.quantity * ratio, decimal_places);
54502
+ expected_loss = to_f(Math.abs(reduce_position.entry - sell_price) * quantity, "%.2f");
54501
54503
  full_loss = Math.abs(reduce_position.avg_price - sell_price) * reduce_position.avg_qty * full_ratio;
54502
54504
  }
54503
54505
  if (reverse_position) {
54504
54506
  expected_loss = Math.abs(reverse_position.avg_price - sell_price) * reverse_position.avg_qty;
54505
- new_pnl = to_f2(pnl - expected_loss, "%.2f");
54507
+ new_pnl = to_f(pnl - expected_loss, "%.2f");
54506
54508
  }
54507
54509
  return {
54508
54510
  pnl: new_pnl,
54509
- loss: to_f2(expected_loss, "%.2f"),
54510
- full_loss: to_f2(full_loss, "%.2f"),
54511
+ loss: to_f(expected_loss, "%.2f"),
54512
+ full_loss: to_f(full_loss, "%.2f"),
54511
54513
  original_pnl: pnl,
54512
54514
  reward_factor,
54513
54515
  profit_percent,
54514
54516
  kind: focus_position.kind,
54515
- sell_price: to_f2(sell_price, price_places),
54517
+ sell_price: to_f(sell_price, price_places),
54516
54518
  quantity: quantity * full_ratio,
54517
54519
  price_places,
54518
54520
  decimal_places
@@ -54547,18 +54549,18 @@ function generateGapTp(payload) {
54547
54549
  const gapLoss = gap * max_quantity;
54548
54550
  const longPercent = gapLoss * factor / (short.entry * short.quantity);
54549
54551
  const shortPercent = gapLoss * factor / (long.entry * long.quantity);
54550
- const longTp = to_f2((1 + longPercent) * long.entry, price_places);
54551
- const shortTp = to_f2((1 + shortPercent) ** -1 * short.entry, price_places);
54552
- const shortToReduce = to_f2(Math.abs(longTp - long.entry) * long.quantity, "%.1f");
54553
- const longToReduce = to_f2(Math.abs(shortTp - short.entry) * short.quantity, "%.1f");
54554
- const actualShortReduce = to_f2(shortToReduce * sell_factor, "%.1f");
54555
- const actualLongReduce = to_f2(longToReduce * sell_factor, "%.1f");
54552
+ const longTp = to_f((1 + longPercent) * long.entry, price_places);
54553
+ const shortTp = to_f((1 + shortPercent) ** -1 * short.entry, price_places);
54554
+ const shortToReduce = to_f(Math.abs(longTp - long.entry) * long.quantity, "%.1f");
54555
+ const longToReduce = to_f(Math.abs(shortTp - short.entry) * short.quantity, "%.1f");
54556
+ const actualShortReduce = to_f(shortToReduce * sell_factor, "%.1f");
54557
+ const actualLongReduce = to_f(longToReduce * sell_factor, "%.1f");
54556
54558
  const short_quantity_to_sell = determine_amount_to_sell2(short.entry, short.quantity, longTp, actualShortReduce, "short", decimal_places);
54557
54559
  const long_quantity_to_sell = determine_amount_to_sell2(long.entry, long.quantity, shortTp, actualLongReduce, "long", decimal_places);
54558
- const risk_amount_short = to_f2(shortToReduce - actualShortReduce, "%.2f");
54559
- const risk_amount_long = to_f2(longToReduce - actualLongReduce, "%.2f");
54560
- const profit_percent_long = to_f2(shortToReduce * 100 / (long.entry * long.quantity), "%.4f");
54561
- const profit_percent_short = to_f2(longToReduce * 100 / (short.entry * short.quantity), "%.4f");
54560
+ const risk_amount_short = to_f(shortToReduce - actualShortReduce, "%.2f");
54561
+ const risk_amount_long = to_f(longToReduce - actualLongReduce, "%.2f");
54562
+ const profit_percent_long = to_f(shortToReduce * 100 / (long.entry * long.quantity), "%.4f");
54563
+ const profit_percent_short = to_f(longToReduce * 100 / (short.entry * short.quantity), "%.4f");
54562
54564
  return {
54563
54565
  profit_percent: {
54564
54566
  long: profit_percent_long,
@@ -54584,8 +54586,8 @@ function generateGapTp(payload) {
54584
54586
  short: short_quantity_to_sell,
54585
54587
  long: long_quantity_to_sell
54586
54588
  },
54587
- gap: to_f2(gap, price_places),
54588
- gap_loss: to_f2(gapLoss, "%.2f")
54589
+ gap: to_f(gap, price_places),
54590
+ gap_loss: to_f(gapLoss, "%.2f")
54589
54591
  };
54590
54592
  }
54591
54593
  function calculate_factor(payload) {
@@ -54611,14 +54613,14 @@ function calculate_factor(payload) {
54611
54613
  const calculated_shortPercent = target_to_reduce / (short_notional - target_to_reduce);
54612
54614
  calculated_factor = calculated_shortPercent * long_notional / gapLoss;
54613
54615
  }
54614
- calculated_factor = to_f2(calculated_factor, places);
54616
+ calculated_factor = to_f(calculated_factor, places);
54615
54617
  return calculated_factor;
54616
54618
  }
54617
54619
  function determineRewardFactor(payload) {
54618
54620
  const { quantity, avg_qty, minimum_pnl, risk } = payload;
54619
54621
  const reward_factor = minimum_pnl / risk;
54620
54622
  const quantity_ratio = quantity / avg_qty;
54621
- return to_f2(reward_factor / quantity_ratio, "%.4f");
54623
+ return to_f(reward_factor / quantity_ratio, "%.4f");
54622
54624
  }
54623
54625
  function getHedgeZone(payload) {
54624
54626
  const {
@@ -54644,19 +54646,19 @@ function getHedgeZone(payload) {
54644
54646
  const tp_diff = Math.abs(take_profit - position2.entry);
54645
54647
  const quantity = position2.quantity;
54646
54648
  const diff = risk / quantity;
54647
- let new_take_profit = kind === "long" ? to_f2(position2.entry + diff, symbol_config.price_places) : to_f2(position2.entry - diff, symbol_config.price_places);
54648
- let base_factor = to_f2(Math.max(tp_diff, diff) / (Math.min(tp_diff, diff) || 1), "%.3f");
54649
+ let new_take_profit = kind === "long" ? to_f(position2.entry + diff, symbol_config.price_places) : to_f(position2.entry - diff, symbol_config.price_places);
54650
+ let base_factor = to_f(Math.max(tp_diff, diff) / (Math.min(tp_diff, diff) || 1), "%.3f");
54649
54651
  let factor = reward_factor || base_factor;
54650
54652
  const new_risk = risk * factor * risk_factor;
54651
54653
  const stop_loss_diff = new_risk / quantity;
54652
- new_take_profit = kind === "long" ? to_f2(position2.entry + stop_loss_diff, symbol_config.price_places) : to_f2(position2.entry - stop_loss_diff, symbol_config.price_places);
54653
- const stop_loss = kind === "long" ? to_f2(position2.entry - stop_loss_diff, symbol_config.price_places) : to_f2(position2.entry + stop_loss_diff, symbol_config.price_places);
54654
+ 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);
54655
+ 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);
54654
54656
  const profit_percent = new_risk * 100 / (position2.entry * position2.quantity);
54655
54657
  return {
54656
54658
  support: Math.min(new_take_profit, stop_loss),
54657
54659
  resistance: Math.max(new_take_profit, stop_loss),
54658
- risk: to_f2(new_risk, "%.2f"),
54659
- profit_percent: to_f2(profit_percent, "%.2f")
54660
+ risk: to_f(new_risk, "%.2f"),
54661
+ profit_percent: to_f(profit_percent, "%.2f")
54660
54662
  };
54661
54663
  }
54662
54664
  function getOptimumHedgeFactor(payload) {
@@ -54691,10 +54693,10 @@ function getOptimumHedgeFactor(payload) {
54691
54693
  }
54692
54694
  if (diff <= tolerance) {
54693
54695
  return {
54694
- reward_factor: to_f2(mid_factor, "%.4f"),
54695
- achieved_support: to_f2(current_support, symbol_config.price_places),
54696
- target_support: to_f2(target_support, symbol_config.price_places),
54697
- difference: to_f2(diff, symbol_config.price_places),
54696
+ reward_factor: to_f(mid_factor, "%.4f"),
54697
+ achieved_support: to_f(current_support, symbol_config.price_places),
54698
+ target_support: to_f(target_support, symbol_config.price_places),
54699
+ difference: to_f(diff, symbol_config.price_places),
54698
54700
  iterations: iteration + 1
54699
54701
  };
54700
54702
  }
@@ -54714,10 +54716,10 @@ function getOptimumHedgeFactor(payload) {
54714
54716
  reward_factor: best_factor
54715
54717
  });
54716
54718
  return {
54717
- reward_factor: to_f2(best_factor, "%.4f"),
54718
- achieved_support: to_f2(final_hedge_zone.support, symbol_config.price_places),
54719
- target_support: to_f2(target_support, symbol_config.price_places),
54720
- difference: to_f2(best_diff, symbol_config.price_places),
54719
+ reward_factor: to_f(best_factor, "%.4f"),
54720
+ achieved_support: to_f(final_hedge_zone.support, symbol_config.price_places),
54721
+ target_support: to_f(target_support, symbol_config.price_places),
54722
+ difference: to_f(best_diff, symbol_config.price_places),
54721
54723
  iterations: max_iterations,
54722
54724
  converged: best_diff <= tolerance
54723
54725
  };
@@ -54762,15 +54764,14 @@ function determineCompoundLongTrade(payload) {
54762
54764
  return {
54763
54765
  start_risk,
54764
54766
  short_profit,
54765
- support: to_f2(support, global_config.price_places),
54766
- resistance: to_f2(resistance, global_config.price_places),
54767
+ support: to_f(support, global_config.price_places),
54768
+ resistance: to_f(resistance, global_config.price_places),
54767
54769
  long_v: long_app_config.last_value,
54768
- profit_percent: to_f2(long_profit_percent, "%.3f"),
54770
+ profit_percent: to_f(long_profit_percent, "%.3f"),
54769
54771
  result,
54770
54772
  short_max_size
54771
54773
  };
54772
54774
  }
54773
-
54774
54775
  // src/helpers/strategy.ts
54775
54776
  class Strategy {
54776
54777
  position;
@@ -54794,10 +54795,10 @@ class Strategy {
54794
54795
  return this.config.global_config.decimal_places;
54795
54796
  }
54796
54797
  to_f(price) {
54797
- return to_f2(price, this.price_places);
54798
+ return to_f(price, this.price_places);
54798
54799
  }
54799
54800
  to_df(quantity) {
54800
- return to_f2(quantity, this.decimal_places);
54801
+ return to_f(quantity, this.decimal_places);
54801
54802
  }
54802
54803
  pnl(kind, _position) {
54803
54804
  const position2 = _position || this.position[kind];
@@ -54998,7 +54999,7 @@ class Strategy {
54998
54999
  remaining_quantity: this.to_df(reverse_avg.quantity - sell_quantity)
54999
55000
  },
55000
55001
  spread: Math.abs(avg.entry - reverse_avg.entry),
55001
- gap_loss: to_f2(Math.abs(avg.entry - reverse_avg.entry) * reverse_avg.quantity, "%.2f"),
55002
+ gap_loss: to_f(Math.abs(avg.entry - reverse_avg.entry) * reverse_avg.quantity, "%.2f"),
55002
55003
  net_profit: incurred_loss + reverse_pnl
55003
55004
  };
55004
55005
  }
@@ -55166,8 +55167,8 @@ class Strategy {
55166
55167
  quantity: this.position[app_config.kind].quantity
55167
55168
  }
55168
55169
  ]), app_config.decimal_places, app_config.price_places);
55169
- const expected_loss = to_f2(Math.abs(avg.price - stop) * avg.quantity, "%.2f");
55170
- const profit_percent = to_f2(this.pnl(kind) * 100 / (avg.price * avg.quantity), "%.3f");
55170
+ const expected_loss = to_f(Math.abs(avg.price - stop) * avg.quantity, "%.2f");
55171
+ const profit_percent = to_f(this.pnl(kind) * 100 / (avg.price * avg.quantity), "%.3f");
55171
55172
  app_config.entry = this.to_f(app_config.entry);
55172
55173
  app_config.stop = this.to_f(app_config.stop);
55173
55174
  return { ...app_config, avg, loss: -expected_loss, profit_percent };
@@ -55270,9 +55271,6 @@ class Strategy {
55270
55271
  };
55271
55272
  }
55272
55273
  }
55273
-
55274
- // src/exchanges/binance/index.ts
55275
- var import_binance = __toESM(require_lib2(), 1);
55276
55274
  // src/types/index.ts
55277
55275
  class BaseExchange {
55278
55276
  client;
@@ -55317,7 +55315,7 @@ class BaseExchange {
55317
55315
  place = false
55318
55316
  } = payload;
55319
55317
  const totalQuantity = orders.reduce((sum, order) => sum + (order.quantity || 0), 0);
55320
- let runningTotal = to_f2(totalQuantity, decimal_places);
55318
+ let runningTotal = to_f(totalQuantity, decimal_places);
55321
55319
  let sortedOrders = [...orders].sort((a, b) => (a.entry || 0) - (b.entry || 0));
55322
55320
  if (kind === "short") {
55323
55321
  sortedOrders.reverse();
@@ -55329,7 +55327,7 @@ class BaseExchange {
55329
55327
  cumulative_quantity: runningTotal
55330
55328
  });
55331
55329
  runningTotal -= order.quantity;
55332
- runningTotal = to_f2(runningTotal, decimal_places);
55330
+ runningTotal = to_f(runningTotal, decimal_places);
55333
55331
  }
55334
55332
  const positions = await this.getPositionInfo(symbol);
55335
55333
  const position2 = positions[kind] || {
@@ -55858,8 +55856,8 @@ async function createLimitPurchaseOrdersParallel(client, symbol, priceFormat, qu
55858
55856
  const createOrder = (x) => {
55859
55857
  const v = {
55860
55858
  symbol: symbol.toUpperCase(),
55861
- price: x.price ? to_f2(x.price, priceFormat) : 0,
55862
- quantity: x.quantity ? to_f2(x.quantity, quantityFormat) : 0,
55859
+ price: x.price ? to_f(x.price, priceFormat) : 0,
55860
+ quantity: x.quantity ? to_f(x.quantity, quantityFormat) : 0,
55863
55861
  side: x.side?.toUpperCase() || "",
55864
55862
  type: "LIMIT",
55865
55863
  positionSide: x.kind.toUpperCase(),
@@ -55874,7 +55872,7 @@ async function createLimitPurchaseOrdersParallel(client, symbol, priceFormat, qu
55874
55872
  delete v.timeInForce;
55875
55873
  v.type = `${v.type}_MARKET`.toUpperCase();
55876
55874
  } else if (typeof x.stop === "number") {
55877
- v.stopPrice = to_f2(x.stop, priceFormat);
55875
+ v.stopPrice = to_f(x.stop, priceFormat);
55878
55876
  }
55879
55877
  }
55880
55878
  if (x.force_market) {
@@ -56147,14 +56145,14 @@ async function getOpenOrders(client, symbol, type) {
56147
56145
  async function getWalletBalance(client, asset = "USDT") {
56148
56146
  const response = await client.getBalanceV3();
56149
56147
  const balance = response.find((x) => x.asset.toLowerCase() === asset.toLowerCase())?.balance;
56150
- return balance ? to_f2(balance, "%.2f") : 0;
56148
+ return balance ? to_f(balance, "%.2f") : 0;
56151
56149
  }
56152
56150
  async function allWalletBalances(client) {
56153
56151
  const response = await client.getBalanceV3();
56154
56152
  return response.map((x) => ({
56155
56153
  type: "future",
56156
56154
  asset: x.asset,
56157
- balance: to_f2(x.balance, "%.8f")
56155
+ balance: to_f(x.balance, "%.8f")
56158
56156
  }));
56159
56157
  }
56160
56158
  function buildPosition(position2, orders, options) {
@@ -56191,7 +56189,7 @@ function buildPosition(position2, orders, options) {
56191
56189
  take_profit,
56192
56190
  tp_quantity,
56193
56191
  stop_quantity,
56194
- liquidation: position2.liquidationPrice ? to_f2(position2.liquidationPrice, price_places) : 0
56192
+ liquidation: position2.liquidationPrice ? to_f(position2.liquidationPrice, price_places) : 0
56195
56193
  };
56196
56194
  }
56197
56195
  var emptyPosition = {
@@ -56212,7 +56210,7 @@ async function getLeverage(client, symbol) {
56212
56210
  symbol
56213
56211
  });
56214
56212
  const leverage = response[0]?.leverage;
56215
- return leverage ? to_f2(leverage, "%0f") : 0;
56213
+ return leverage ? to_f(leverage, "%0f") : 0;
56216
56214
  }
56217
56215
  async function fetchBinanceAccount(client, json, options) {
56218
56216
  const [position2, balance, orders, current_price, all_balances, leverage] = await Promise.all([
@@ -56510,7 +56508,7 @@ class BinanceExchange extends BaseExchange {
56510
56508
  const currentPrice = await getCurrentPrice(this.client, symbol);
56511
56509
  const price_places = isBTC ? "%.1f" : `%.${getPricePlaces(currentPrice)}f`;
56512
56510
  const decimal_places = `%.${target.quantityPrecision}f`;
56513
- const min_size = to_f2((minNotional || 0) / support, decimal_places);
56511
+ const min_size = to_f((minNotional || 0) / support, decimal_places);
56514
56512
  const configObj = {
56515
56513
  support,
56516
56514
  resistance,
@@ -56754,8 +56752,8 @@ async function createLimitPurchaseOrders(client, symbol, priceFormat, quantityFo
56754
56752
  const createOrder = (x) => {
56755
56753
  const v = {
56756
56754
  symbol: symbol.toUpperCase(),
56757
- price: (x.price ? to_f2(x.price, priceFormat) : 0).toString(),
56758
- qty: (x.quantity ? to_f2(x.quantity, quantityFormat) : 0).toString(),
56755
+ price: (x.price ? to_f(x.price, priceFormat) : 0).toString(),
56756
+ qty: (x.quantity ? to_f(x.quantity, quantityFormat) : 0).toString(),
56759
56757
  side: titleCase(x.side || ""),
56760
56758
  orderType: "LIMIT",
56761
56759
  positionIdx: x.kind === "long" ? 1 : 2,
@@ -56772,12 +56770,12 @@ async function createLimitPurchaseOrders(client, symbol, priceFormat, quantityFo
56772
56770
  delete v.timeInForce;
56773
56771
  v.orderType = `MARKET`;
56774
56772
  } else if (typeof x.stop === "number") {
56775
- v.triggerPrice = to_f2(x.stop, priceFormat).toString();
56773
+ v.triggerPrice = to_f(x.stop, priceFormat).toString();
56776
56774
  }
56777
56775
  if (x.kind === "long" && x.side === "sell" || x.kind === "short" && x.side === "buy") {
56778
56776
  v.tpslMode = "Partial";
56779
56777
  v.slOrderType = "Limit";
56780
- v.slLimitPrice = to_f2(v.triggerPrice, priceFormat).toString();
56778
+ v.slLimitPrice = to_f(v.triggerPrice, priceFormat).toString();
56781
56779
  if (x.is_market) {
56782
56780
  v.slOrderType = "Market";
56783
56781
  v.tpslMode = "Full";
@@ -57010,7 +57008,7 @@ async function getWalletBalance2(client, asset = "USDT") {
57010
57008
  accountType: "UNIFIED",
57011
57009
  coin: asset
57012
57010
  });
57013
- return to_f2(response.result.list[0].totalWalletBalance, "%.2f");
57011
+ return to_f(response.result.list[0].totalWalletBalance, "%.2f");
57014
57012
  }
57015
57013
  async function allWalletBalances2(client) {
57016
57014
  const response = await client.getWalletBalance({
@@ -57020,7 +57018,7 @@ async function allWalletBalances2(client) {
57020
57018
  return response.result.list[0].coin.map((x) => ({
57021
57019
  type: "future",
57022
57020
  asset: x.coin,
57023
- balance: to_f2(x.walletBalance, "%.8f")
57021
+ balance: to_f(x.walletBalance, "%.8f")
57024
57022
  }));
57025
57023
  }
57026
57024
  function buildPosition2(position2, orders, options) {
@@ -57317,7 +57315,7 @@ class BybitExchange extends BaseExchange {
57317
57315
  function determine_liquidation(balance_diff, position2) {
57318
57316
  const long_liquidation = position2.price - balance_diff / position2.quantity;
57319
57317
  const short_liquidation = position2.price + balance_diff / position2.quantity;
57320
- return position2.kind === "long" ? to_f2(long_liquidation, "%.2f") : to_f2(short_liquidation, "%.2f");
57318
+ return position2.kind === "long" ? to_f(long_liquidation, "%.2f") : to_f(short_liquidation, "%.2f");
57321
57319
  }
57322
57320
  function calculate_avg_entry(kind, {
57323
57321
  orders: _orders,
@@ -57482,13 +57480,13 @@ function calculateHedge(payload) {
57482
57480
  const stopLossQuantity = Math.min(stopLossAmount / priceDifference, oppositePosition.quantity);
57483
57481
  return {
57484
57482
  [kind]: {
57485
- price: to_f2(takeProfitPrice, active_account.price_places),
57486
- quantity: to_f2(position_quantity || 0, active_account.decimal_places),
57483
+ price: to_f(takeProfitPrice, active_account.price_places),
57484
+ quantity: to_f(position_quantity || 0, active_account.decimal_places),
57487
57485
  type: "TAKE_PROFIT"
57488
57486
  },
57489
57487
  [oppositeKind]: {
57490
- stop_price: to_f2(stopLossPrice, active_account.price_places),
57491
- quantity: to_f2(stopLossQuantity || 0, active_account.decimal_places),
57488
+ stop_price: to_f(stopLossPrice, active_account.price_places),
57489
+ quantity: to_f(stopLossQuantity || 0, active_account.decimal_places),
57492
57490
  type: "STOP_LOSS"
57493
57491
  }
57494
57492
  };
@@ -57553,7 +57551,7 @@ function processPosition(codeNode, input, kind) {
57553
57551
  side: reverse_kind === "long" ? "buy" : "sell"
57554
57552
  },
57555
57553
  orders_to_cancel,
57556
- stop: to_f2(vv[kind].price, active_account.price_places),
57554
+ stop: to_f(vv[kind].price, active_account.price_places),
57557
57555
  quantity: vv[kind].quantity,
57558
57556
  kind,
57559
57557
  type: JSON.stringify("TAKE_PROFIT"),
@@ -57572,7 +57570,7 @@ function processPosition(codeNode, input, kind) {
57572
57570
  }
57573
57571
  async function reduceMajorPositionCalculation(input, exchange_instance) {
57574
57572
  try {
57575
- let conditionsCheck = input.position.tp_quantity !== input.quantity || input.position.take_profit !== to_f2(input.stop, input.price_places);
57573
+ let conditionsCheck = input.position.tp_quantity !== input.quantity || input.position.take_profit !== to_f(input.stop, input.price_places);
57576
57574
  if (!isNaN(input.opposite_position.stop_quantity) && input.opposite_position.stop_quantity > -1) {
57577
57575
  conditionsCheck = conditionsCheck || input.opposite_position.stop_quantity !== input.to_place.quantity;
57578
57576
  }
@@ -57697,15 +57695,20 @@ async function reduceMajorPositionEntry(input, accountInfo, trigger2, exchange_i
57697
57695
  // src/position.ts
57698
57696
  class ExchangePosition {
57699
57697
  exchange;
57698
+ symbol_config;
57700
57699
  exchange_account;
57701
57700
  app_db;
57702
57701
  instance;
57703
57702
  constructor(payload) {
57703
+ this.symbol_config = payload.symbol_config;
57704
57704
  this.exchange = payload.exchange;
57705
57705
  this.app_db = payload.app_db;
57706
57706
  this.instance = payload.instance;
57707
57707
  this.exchange_account = payload.exchange_account;
57708
57708
  }
57709
+ getInstance() {
57710
+ return this.instance;
57711
+ }
57709
57712
  get symbol() {
57710
57713
  return this.instance.symbol;
57711
57714
  }
@@ -57713,16 +57716,18 @@ class ExchangePosition {
57713
57716
  return this.instance.kind;
57714
57717
  }
57715
57718
  get account() {
57716
- return this.instance.account;
57719
+ const { p_account } = this.instance.expand;
57720
+ return p_account;
57717
57721
  }
57718
57722
  async cancelOrders(payload) {
57719
- const { limit, price: _price } = payload;
57723
+ const { limit, price: _price, raw } = payload;
57720
57724
  if (limit) {
57721
57725
  return await this.app_db.cancelLimitOrders({
57722
57726
  symbol: this.symbol,
57723
57727
  kind: this.kind,
57724
57728
  account: this.account,
57725
- cancelExchangeOrders: (p) => this.exchange.cancelOrders(p)
57729
+ cancelExchangeOrders: (p) => this.exchange.cancelOrders(p),
57730
+ raw
57726
57731
  });
57727
57732
  }
57728
57733
  let price = _price || 0;
@@ -57755,6 +57760,9 @@ class ExchangePosition {
57755
57760
  return await this.app_db.createOrUpdatePositionConfig(this.instance, params);
57756
57761
  }
57757
57762
  }
57763
+ if (this.instance.expand?.b_config) {
57764
+ return this.instance.expand.b_config;
57765
+ }
57758
57766
  return await this.app_db.getPositionConfig({
57759
57767
  symbol: this.symbol,
57760
57768
  kind: this.kind,
@@ -57763,15 +57771,19 @@ class ExchangePosition {
57763
57771
  }
57764
57772
  async updateTargetPnl() {
57765
57773
  const position2 = this.instance;
57766
- if (position2?.expand?.config) {
57767
- const config2 = position2.expand.config;
57774
+ const config2 = await this.getConfig();
57775
+ if (config2) {
57768
57776
  let _profit = config2.profit;
57777
+ let risk = config2.risk;
57778
+ let next_risk = position2.next_risk;
57769
57779
  let _profit_percent = config2?.profit_percent;
57770
57780
  if (_profit_percent && (position2?.quantity || 0) > 0) {
57771
- _profit = to_f2(position2.quantity * _profit_percent * position2.entry / 100);
57781
+ _profit = to_f(position2.quantity * _profit_percent * position2.entry / 100);
57782
+ next_risk = risk + _profit;
57772
57783
  }
57773
57784
  await this.app_db.update_db_position(position2, {
57774
- target_pnl: _profit
57785
+ target_pnl: _profit,
57786
+ next_risk
57775
57787
  });
57776
57788
  return _profit;
57777
57789
  }
@@ -57791,13 +57803,13 @@ class ExchangePosition {
57791
57803
  }
57792
57804
  }
57793
57805
  async triggerTradeFromConfig(payload) {
57794
- const { place = true, stop, use_current, ignore_config } = payload;
57806
+ const { place = true, stop, use_current, ignore_config, risky } = payload;
57795
57807
  const position2 = this.instance;
57796
57808
  const config2 = await this.getConfig();
57797
57809
  let condition = ignore_config ? true : position2?.config;
57798
57810
  if (condition) {
57799
57811
  let entry = payload.tp ? position2.entry || config2.entry : config2.entry;
57800
- const v = stop ? "place_stop_orders" : "place_limit_orders";
57812
+ const v = stop ? "place_stop_orders" : risky ? "dangerous_entry_orders" : "place_limit_orders";
57801
57813
  return await this.placeSharedOrder(v, {
57802
57814
  entry,
57803
57815
  stop: config2.stop,
@@ -57805,18 +57817,26 @@ class ExchangePosition {
57805
57817
  risk: config2.risk,
57806
57818
  place,
57807
57819
  raw: payload.raw,
57808
- use_current
57820
+ use_current,
57821
+ stop_percent: config2.stop_percent || 100
57809
57822
  });
57810
57823
  }
57811
57824
  }
57812
57825
  async placeSharedOrder(action, payload) {
57826
+ const { stop_percent = 100 } = payload;
57827
+ const config2 = await this.getConfig();
57813
57828
  const app_config = await this.buildAppConfig({
57814
57829
  entry: payload.entry,
57815
57830
  stop: payload.stop,
57816
57831
  risk_reward: payload.risk_reward,
57817
57832
  risk: payload.risk,
57818
57833
  profit: 0,
57819
- update_db: payload.update_db
57834
+ update_db: payload.update_db,
57835
+ use_kelly: config2.kelly?.use_kelly,
57836
+ kelly_confidence_factor: config2.kelly?.kelly_confidence_factor,
57837
+ kelly_minimum_risk: config2.kelly?.kelly_minimum_risk,
57838
+ kelly_prediction_model: config2.kelly?.kelly_prediction_model,
57839
+ kelly_func: config2.kelly?.kelly_func
57820
57840
  });
57821
57841
  const { entry_orders, stop_orders, trades } = await this.placeConfigOrders(app_config, {
57822
57842
  risk_reward: payload.risk_reward,
@@ -57826,7 +57846,13 @@ class ExchangePosition {
57826
57846
  avg_size: 0,
57827
57847
  neg_pnl: 0,
57828
57848
  min_size: app_config.min_size,
57829
- symbol: this.symbol
57849
+ symbol: this.symbol,
57850
+ stop_percent,
57851
+ use_kelly: config2.kelly?.use_kelly,
57852
+ kelly_confidence_factor: config2.kelly?.kelly_confidence_factor,
57853
+ kelly_minimum_risk: config2.kelly?.kelly_minimum_risk,
57854
+ kelly_prediction_model: config2.kelly?.kelly_prediction_model,
57855
+ kelly_func: config2.kelly?.kelly_func
57830
57856
  }, false);
57831
57857
  if (payload.raw) {
57832
57858
  let actual_orders_to_buy = await this.determineAmountToBuy({
@@ -57862,12 +57888,23 @@ class ExchangePosition {
57862
57888
  symbol: this.symbol,
57863
57889
  place: payload.place
57864
57890
  });
57865
- await this.exchange_account.getLiveExchangeInstance({
57866
- symbol: this.symbol,
57867
- refresh: true
57868
- });
57869
57891
  return result;
57870
57892
  }
57893
+ if (action == "dangerous_entry_orders" && payload.place) {
57894
+ return await this.exchange.createLimitPurchaseOrders({
57895
+ orders: trades.map((x) => ({
57896
+ ...x,
57897
+ price: x.entry,
57898
+ quantity: x.quantity,
57899
+ side: app_config.kind === "long" ? "buy" : "sell",
57900
+ kind: app_config.kind
57901
+ })),
57902
+ kind: app_config.kind,
57903
+ decimal_places: app_config.decimal_places,
57904
+ price_places: app_config.price_places,
57905
+ symbol: this.symbol
57906
+ });
57907
+ }
57871
57908
  if (action === "place_stop_orders" && payload.place) {
57872
57909
  const instance = this.instance;
57873
57910
  let result = await this.exchange.placeStopOrders({
@@ -57879,10 +57916,6 @@ class ExchangePosition {
57879
57916
  decimal_places: app_config.decimal_places,
57880
57917
  place: true
57881
57918
  });
57882
- await this.exchange_account.getLiveExchangeInstance({
57883
- symbol: this.symbol,
57884
- refresh: true
57885
- });
57886
57919
  return result;
57887
57920
  }
57888
57921
  return {
@@ -57911,11 +57944,19 @@ class ExchangePosition {
57911
57944
  return app_config;
57912
57945
  }
57913
57946
  async placeConfigOrders(app_config, solution, place, skip_stop) {
57947
+ const { stop_percent = 100 } = solution;
57914
57948
  app_config.entry = solution.entry;
57915
57949
  app_config.stop = solution.stop;
57916
57950
  app_config.risk_per_trade = solution.risk_per_trade;
57917
57951
  app_config.min_size = solution.min_size;
57918
57952
  app_config.risk_reward = solution.risk_reward;
57953
+ app_config.kelly = {
57954
+ use_kelly: solution.use_kelly,
57955
+ kelly_confidence_factor: solution.kelly_confidence_factor,
57956
+ kelly_minimum_risk: solution.kelly_minimum_risk,
57957
+ kelly_prediction_model: solution.kelly_prediction_model,
57958
+ kelly_func: solution.kelly_func
57959
+ };
57919
57960
  const options = {
57920
57961
  take_profit: null,
57921
57962
  entry: app_config.entry,
@@ -57929,7 +57970,12 @@ class ExchangePosition {
57929
57970
  gap: app_config.gap,
57930
57971
  rr: app_config.rr,
57931
57972
  price_places: app_config.price_places,
57932
- decimal_places: app_config.decimal_places
57973
+ decimal_places: app_config.decimal_places,
57974
+ use_kelly: solution.use_kelly,
57975
+ kelly_confidence_factor: solution.kelly_confidence_factor,
57976
+ kelly_minimum_risk: solution.kelly_minimum_risk,
57977
+ kelly_prediction_model: solution.kelly_prediction_model,
57978
+ kelly_func: solution.kelly_func
57933
57979
  };
57934
57980
  const trades = sortedBuildConfig(app_config, options);
57935
57981
  const entry_orders = {
@@ -57943,9 +57989,13 @@ class ExchangePosition {
57943
57989
  })),
57944
57990
  kind: app_config.kind
57945
57991
  };
57992
+ const last_order = trades[0]?.entry;
57993
+ const stop_spread = stop_percent / 100;
57994
+ const _stop = app_config.kind === "short" ? last_order * (1 + stop_spread) : last_order * (1 - stop_spread);
57995
+ const stop_to_user = stop_percent === 100 ? solution.stop : _stop;
57946
57996
  const stop_orders = {
57947
- stop: solution.stop,
57948
- final_stop: solution.stop,
57997
+ stop: stop_to_user,
57998
+ final_stop: stop_to_user,
57949
57999
  kind: app_config.kind,
57950
58000
  quantity: trades[0]?.avg_size,
57951
58001
  is_limit: true,
@@ -57987,7 +58037,7 @@ class ExchangePosition {
57987
58037
  async determineAmountToBuy(payload) {
57988
58038
  const { orders, kind, decimal_places = "%.3f", refresh, cancel } = payload;
57989
58039
  const totalQuantity = orders.reduce((sum, order) => sum + (order.quantity || 0), 0);
57990
- let runningTotal = to_f2(totalQuantity, decimal_places);
58040
+ let runningTotal = to_f(totalQuantity, decimal_places);
57991
58041
  let sortedOrders = [...orders].sort((a, b) => (a.entry || 0) - (b.entry || 0));
57992
58042
  if (kind === "short") {
57993
58043
  sortedOrders.reverse();
@@ -57999,7 +58049,7 @@ class ExchangePosition {
57999
58049
  cumulative_quantity: runningTotal
58000
58050
  });
58001
58051
  runningTotal -= order.quantity;
58002
- runningTotal = to_f2(runningTotal, decimal_places);
58052
+ runningTotal = to_f(runningTotal, decimal_places);
58003
58053
  }
58004
58054
  const { instance: position2, existingOrders } = await this.refresh(refresh);
58005
58055
  let filteredOrders = withCumulative.filter((order) => (order.cumulative_quantity || 0) > position2?.quantity).map((order) => ({
@@ -58021,14 +58071,11 @@ class ExchangePosition {
58021
58071
  return filteredOrders;
58022
58072
  }
58023
58073
  async refresh(live_refresh) {
58024
- await this.exchange_account.refreshAccount({
58025
- symbol: this.symbol,
58026
- live_refresh
58027
- });
58028
58074
  const instance = await this.exchange_account.syncAccount({
58029
58075
  symbol: this.symbol,
58030
58076
  kind: this.kind,
58031
- update: true
58077
+ update: true,
58078
+ live_refresh
58032
58079
  });
58033
58080
  let existingOrders = await this.exchange_account.syncOrders({
58034
58081
  symbol: this.symbol,
@@ -58037,29 +58084,467 @@ class ExchangePosition {
58037
58084
  return { instance, existingOrders };
58038
58085
  }
58039
58086
  async placeTrade(payload) {
58040
- const { place, tp, raw: _raw, cancel, stop, ignore_config } = payload;
58087
+ const {
58088
+ place,
58089
+ tp,
58090
+ raw: _raw,
58091
+ cancel,
58092
+ stop,
58093
+ ignore_config,
58094
+ risky,
58095
+ limit = true,
58096
+ target_pnl
58097
+ } = payload;
58041
58098
  if (cancel) {
58042
58099
  await this.cancelOrders({
58043
58100
  limit: true
58044
58101
  });
58045
58102
  }
58046
- if (place) {
58103
+ if (limit) {
58047
58104
  return await this.triggerTradeFromConfig({
58048
- raw: payload.raw,
58105
+ raw: _raw,
58049
58106
  stop,
58050
- ignore_config
58107
+ ignore_config,
58108
+ risky,
58109
+ place
58051
58110
  });
58052
58111
  }
58053
58112
  const rr = await this.refresh(true);
58054
- await this.updateTargetPnl();
58113
+ await this.updateConfigPnl();
58055
58114
  if (tp) {
58056
58115
  await this.exchange_account.placeProfitAndStop({
58057
58116
  symbol: this.symbol,
58058
- trigger: true
58117
+ trigger: true,
58118
+ target_pnl
58059
58119
  });
58060
58120
  }
58121
+ return [];
58061
58122
  return rr.existingOrders;
58062
58123
  }
58124
+ async placeStopLimit(payload) {
58125
+ const { place, stop, quantity: _quantity } = payload;
58126
+ const kind = this.kind;
58127
+ const symbol = this.symbol;
58128
+ const position2 = this.instance;
58129
+ if (position2.avg_qty && position2.avg_qty > 0) {
58130
+ const spread = 1.00005;
58131
+ const qty = _quantity || position2.avg_qty - position2.quantity;
58132
+ const symbol_config = this.symbol_config;
58133
+ const orders = [
58134
+ {
58135
+ kind,
58136
+ stop,
58137
+ quantity: to_f(qty, symbol_config.decimal_places),
58138
+ side: kind === "long" ? "buy" : "sell",
58139
+ price: to_f(kind === "short" ? stop * spread ** -1 : stop * spread, symbol_config.price_places)
58140
+ }
58141
+ ];
58142
+ if (place) {
58143
+ return this.exchange.placeBadStopEntry({
58144
+ symbol,
58145
+ orders,
58146
+ price_places: symbol_config.price_places,
58147
+ decimal_places: symbol_config.decimal_places
58148
+ });
58149
+ }
58150
+ return orders;
58151
+ }
58152
+ return [];
58153
+ }
58154
+ async computeTargetPnl(payload) {
58155
+ const { secondary } = payload;
58156
+ const root_position = this.instance;
58157
+ const reverse_position = secondary.instance;
58158
+ if (reverse_position?.expand?.b_config && root_position.quantity > 0) {
58159
+ const reverse_config = reverse_position.expand.b_config;
58160
+ const diff = Math.abs(reverse_config.stop - root_position.entry);
58161
+ const result = to_f(diff * root_position.quantity);
58162
+ if (root_position.target_pnl !== result) {
58163
+ await this.app_db.update_db_position(root_position, {
58164
+ target_pnl: result
58165
+ });
58166
+ await secondary.getConfig({
58167
+ params: {
58168
+ ...reverse_config,
58169
+ risk: result
58170
+ }
58171
+ });
58172
+ }
58173
+ return result;
58174
+ }
58175
+ return 0;
58176
+ }
58177
+ async runSimulation(payload) {
58178
+ const { iterations = 2, raw = false } = payload;
58179
+ const kind = this.kind;
58180
+ const symbol_config = this.symbol_config;
58181
+ const long_position = payload.long_position.instance;
58182
+ const short_position = payload.short_position.instance;
58183
+ const long_config = await payload.long_position.getConfig();
58184
+ const short_config = await payload.short_position.getConfig();
58185
+ const focus_config = kind === "long" ? long_config : short_config;
58186
+ const short_tp_factor = short_config.profit_percent / long_config.profit_percent;
58187
+ const reduce_ratio = focus_config.reduce_ratio;
58188
+ const budget = focus_config.risk;
58189
+ const risk_reward = focus_config.risk_reward;
58190
+ const tp_percent = long_config.profit_percent;
58191
+ const fee_percent = symbol_config.fee_percent;
58192
+ const strategy_config = {
58193
+ tp_percent,
58194
+ short_tp_factor,
58195
+ fee_percent,
58196
+ budget,
58197
+ risk_reward,
58198
+ reduce_ratio,
58199
+ global_config: symbol_config
58200
+ };
58201
+ const strategy2 = new Strategy({
58202
+ long: {
58203
+ entry: long_position.entry,
58204
+ quantity: long_position.quantity,
58205
+ avg_price: long_position.avg_price,
58206
+ avg_qty: long_position.avg_qty
58207
+ },
58208
+ short: {
58209
+ entry: short_position.entry,
58210
+ quantity: short_position.quantity,
58211
+ avg_price: short_position.avg_price,
58212
+ avg_qty: short_position.avg_qty
58213
+ },
58214
+ config: strategy_config
58215
+ });
58216
+ if (raw) {
58217
+ return strategy2;
58218
+ }
58219
+ return strategy2.runIterations({
58220
+ iterations,
58221
+ kind
58222
+ });
58223
+ }
58224
+ async placeOppositeTradeAction(payload) {
58225
+ const { data } = payload;
58226
+ const position2 = this.instance;
58227
+ if (position2.avg_qty !== data.avg.quantity) {
58228
+ const config2 = await this.getConfig();
58229
+ await this.app_db.updateScheduledTrade(config2.id, {
58230
+ entry: data.entry,
58231
+ stop: data.stop,
58232
+ risk: data.risk_per_trade,
58233
+ profit_percent: data.profit_percent,
58234
+ risk_reward: data.risk_reward
58235
+ });
58236
+ await this.placeTrade({
58237
+ place: true,
58238
+ ignore_config: true
58239
+ });
58240
+ await this.placeTrade({
58241
+ place: true,
58242
+ stop: true,
58243
+ ignore_config: true
58244
+ });
58245
+ }
58246
+ }
58247
+ async updateRiskOnEmpty() {
58248
+ const position2 = this.instance;
58249
+ if (position2 && position2.quantity === 0) {
58250
+ if (position2.next_risk && position2.next_risk > 0) {
58251
+ await this.getConfig({
58252
+ params: {
58253
+ risk: position2.next_risk
58254
+ }
58255
+ });
58256
+ console.log(`Updated ${this.kind} position config for ${this.symbol}: risk = ${position2.next_risk}`);
58257
+ return {
58258
+ updated: true,
58259
+ symbol: this.symbol,
58260
+ kind: this.kind,
58261
+ old_risk: position2.expand?.b_config?.risk,
58262
+ new_risk: position2.next_risk
58263
+ };
58264
+ }
58265
+ }
58266
+ return {
58267
+ updated: false,
58268
+ symbol: this.symbol,
58269
+ kind: this.kind,
58270
+ reason: position2 ? position2.quantity > 0 ? "Position not empty" : "No next_risk available" : "Position not found"
58271
+ };
58272
+ }
58273
+ async increasePositionAtStop(payload) {
58274
+ const { place = false, increase = true } = payload;
58275
+ const position2 = this.instance;
58276
+ console.log(position2);
58277
+ let price_params = {
58278
+ price: payload.price,
58279
+ quantity: payload.quantity
58280
+ };
58281
+ if (!payload.price && position2 && position2.stop_loss) {
58282
+ price_params.price = position2.stop_loss.price;
58283
+ }
58284
+ if (!payload.quantity && position2 && position2.stop_loss) {
58285
+ price_params.quantity = position2.stop_loss.quantity;
58286
+ }
58287
+ if (price_params.price && price_params.quantity) {
58288
+ const { price, quantity } = price_params;
58289
+ const symbol_config = this.symbol_config;
58290
+ const price_places = symbol_config.price_places;
58291
+ const decimal_places = symbol_config.decimal_places;
58292
+ if (place) {
58293
+ await this.cancelOrders({
58294
+ limit: true
58295
+ });
58296
+ }
58297
+ return await this.exchange.customStopLoss({
58298
+ symbol: this.symbol,
58299
+ kind: this.kind,
58300
+ stop: price,
58301
+ quantity,
58302
+ price_places,
58303
+ decimal_places,
58304
+ increase,
58305
+ place
58306
+ });
58307
+ }
58308
+ }
58309
+ async placeSingleOrder(payload) {
58310
+ const { long_position, short_position } = payload;
58311
+ const kind = this.kind;
58312
+ const long_config = await long_position.getConfig();
58313
+ const short_config = await short_position.getConfig();
58314
+ const focus_config = kind === "long" ? long_config : short_config;
58315
+ const focus_position = kind === "long" ? long_position.instance : short_position.instance;
58316
+ const track_position = kind === "long" ? short_position.instance : long_position.instance;
58317
+ const follow = focus_config.follow || focus_position.follow;
58318
+ const threshold_qty = focus_config.threshold_qty || focus_position.threshold_qty;
58319
+ if (!follow) {
58320
+ return "No follow set";
58321
+ }
58322
+ let should_place_order = false;
58323
+ if (threshold_qty === 0) {
58324
+ should_place_order = true;
58325
+ }
58326
+ if (threshold_qty > 0 && track_position.quantity >= threshold_qty) {
58327
+ should_place_order = true;
58328
+ }
58329
+ if (focus_position.quantity === 0) {
58330
+ should_place_order = true;
58331
+ }
58332
+ if (track_position.quantity !== focus_position.quantity && focus_position.quantity < track_position.quantity && should_place_order) {
58333
+ const remaining_quantity = Math.abs(track_position.quantity - focus_position.quantity);
58334
+ await this.placeMarketOrder({
58335
+ quantity: remaining_quantity
58336
+ });
58337
+ }
58338
+ }
58339
+ async placeMarketOrder(payload) {
58340
+ const { quantity } = payload;
58341
+ const symbol_config = this.symbol_config;
58342
+ await this.exchange.placeMarketOrder({
58343
+ symbol: this.symbol,
58344
+ kind: this.kind,
58345
+ quantity,
58346
+ price_places: symbol_config.price_places,
58347
+ decimal_places: symbol_config.decimal_places
58348
+ });
58349
+ }
58350
+ async generate_config_params(payload) {
58351
+ const { entry, stop, risk_reward, risk, with_trades = false } = payload;
58352
+ const symbol = this.symbol;
58353
+ const app_config = await this.buildAppConfig({
58354
+ entry,
58355
+ stop,
58356
+ risk_reward,
58357
+ risk
58358
+ });
58359
+ let config2 = generate_config_params(app_config, {
58360
+ entry,
58361
+ stop,
58362
+ risk_reward,
58363
+ risk,
58364
+ symbol
58365
+ });
58366
+ if (with_trades) {
58367
+ const app_config2 = await this.buildAppConfig({
58368
+ entry: config2.entry,
58369
+ stop: config2.stop,
58370
+ risk_reward: config2.risk_reward,
58371
+ risk: config2.risk,
58372
+ profit: 0,
58373
+ update_db: false
58374
+ });
58375
+ const { trades } = await this.placeConfigOrders(app_config2, {
58376
+ risk_reward: config2.risk_reward,
58377
+ entry: config2.entry,
58378
+ stop: config2.stop,
58379
+ risk_per_trade: config2.risk,
58380
+ avg_size: 0,
58381
+ neg_pnl: 0,
58382
+ min_size: app_config2.min_size,
58383
+ symbol
58384
+ }, false);
58385
+ config2.trades = trades;
58386
+ }
58387
+ return { ...config2, place_stop: false, profit_percent: 0 };
58388
+ }
58389
+ async extrapolateConfig(payload) {
58390
+ const { risk_reward = 199, risk, kind } = payload;
58391
+ const position2 = this.instance;
58392
+ if (position2) {
58393
+ let entry = position2.next_order || position2.avg_liquidation;
58394
+ if (kind == "short" && entry < 0) {
58395
+ const symbol_config = this.symbol_config;
58396
+ entry = symbol_config?.support;
58397
+ }
58398
+ return await this.generate_config_params({
58399
+ entry,
58400
+ stop: position2.take_profit,
58401
+ risk_reward,
58402
+ risk: risk || position2.target_pnl
58403
+ });
58404
+ }
58405
+ return null;
58406
+ }
58407
+ async build_short_order() {
58408
+ const kind = this.kind;
58409
+ const position2 = this.instance;
58410
+ const position_config = await this.getConfig();
58411
+ if (position2 && position_config && position2.entry > 0) {
58412
+ let next_order = position2.next_order;
58413
+ let take_profit = position2.take_profit;
58414
+ if (next_order && take_profit) {
58415
+ let config2 = await this.buildConfigForSymbol({
58416
+ risk: position_config.risk,
58417
+ risk_reward: position_config.risk_reward,
58418
+ as_config: true
58419
+ });
58420
+ const focus = config2.entries.filter((x) => {
58421
+ if (kind == "long") {
58422
+ return x.entry <= next_order;
58423
+ } else {
58424
+ return x.entry >= next_order;
58425
+ }
58426
+ });
58427
+ const focus_entry = focus.at(-1);
58428
+ if (focus_entry) {
58429
+ let entry = focus_entry.entry;
58430
+ let risk = Math.abs(focus_entry.neg_pnl);
58431
+ return await this.generate_config_params({
58432
+ entry,
58433
+ stop: take_profit,
58434
+ risk_reward: position_config.risk_reward,
58435
+ risk
58436
+ });
58437
+ }
58438
+ }
58439
+ }
58440
+ }
58441
+ async buildConfigForSymbol(payload) {
58442
+ const kind = this.kind;
58443
+ const { risk, risk_reward = 199, as_config = false } = payload;
58444
+ const symbol_config = this.symbol_config;
58445
+ const long_config = await this.generate_config_params({
58446
+ entry: kind === "long" ? symbol_config.resistance : symbol_config.support,
58447
+ stop: kind === "long" ? symbol_config.support : symbol_config.resistance,
58448
+ risk_reward,
58449
+ risk
58450
+ });
58451
+ if (as_config) {
58452
+ const app_config = buildAppConfig(symbol_config, {
58453
+ entry: long_config.entry,
58454
+ stop: long_config.stop,
58455
+ risk_reward,
58456
+ risk: long_config.risk,
58457
+ symbol: this.symbol
58458
+ });
58459
+ return app_config;
58460
+ }
58461
+ return long_config;
58462
+ }
58463
+ async buildTrades(payload) {
58464
+ const { risk } = payload;
58465
+ const config2 = await this.getConfig();
58466
+ const app_config = await this.buildAppConfig({
58467
+ entry: config2.entry,
58468
+ stop: config2.stop,
58469
+ risk_reward: config2.risk_reward,
58470
+ risk: risk || config2.risk
58471
+ });
58472
+ const { trades } = await this.placeConfigOrders(app_config, {
58473
+ risk_reward: config2.risk_reward,
58474
+ entry: config2.entry,
58475
+ stop: config2.stop,
58476
+ risk_per_trade: risk || config2.risk,
58477
+ avg_size: 0,
58478
+ neg_pnl: 0,
58479
+ min_size: app_config.min_size,
58480
+ symbol: this.symbol,
58481
+ kelly_confidence_factor: config2.kelly?.kelly_confidence_factor,
58482
+ kelly_minimum_risk: config2.kelly?.kelly_minimum_risk,
58483
+ kelly_prediction_model: config2.kelly?.kelly_prediction_model,
58484
+ kelly_func: config2.kelly?.kelly_func
58485
+ });
58486
+ const position2 = this.instance;
58487
+ const orders_to_place = await this.determineAmountToBuy({
58488
+ orders: trades.map((x) => ({
58489
+ entry: x.entry,
58490
+ quantity: x.quantity
58491
+ })),
58492
+ kind: this.kind,
58493
+ decimal_places: app_config.decimal_places,
58494
+ price_places: app_config.price_places
58495
+ });
58496
+ const avg_values = determine_average_entry_and_size(orders_to_place.map((u) => ({
58497
+ price: u.entry,
58498
+ quantity: u.quantity
58499
+ })).concat({
58500
+ price: position2.entry,
58501
+ quantity: position2.quantity
58502
+ }), app_config.decimal_places, app_config.price_places);
58503
+ return {
58504
+ trades: orders_to_place,
58505
+ max_size: trades[0].avg_size,
58506
+ last_price: trades[0].entry,
58507
+ total_size: avg_values.quantity,
58508
+ avg_entry: avg_values.price
58509
+ };
58510
+ }
58511
+ async tradeConfig(payload) {
58512
+ const { override = {} } = payload;
58513
+ const config2 = await this.getConfig();
58514
+ const app_config = await this.buildAppConfig({
58515
+ entry: config2.entry,
58516
+ stop: config2.stop,
58517
+ risk_reward: config2.risk_reward,
58518
+ risk: config2.risk,
58519
+ symbol: this.symbol,
58520
+ use_kelly: config2.kelly?.use_kelly,
58521
+ kelly_confidence_factor: config2.kelly?.kelly_confidence_factor,
58522
+ kelly_minimum_risk: config2.kelly?.kelly_minimum_risk,
58523
+ kelly_prediction_model: config2.kelly?.kelly_prediction_model,
58524
+ kelly_func: config2.kelly?.kelly_func,
58525
+ ...override
58526
+ });
58527
+ return app_config;
58528
+ }
58529
+ async getOrCreatePositionConfig(payload) {
58530
+ const { risk = 50, risk_reward = 199 } = payload;
58531
+ const config2 = await this.getConfig();
58532
+ if (!config2) {
58533
+ const long_c = await this.buildConfigForSymbol({
58534
+ risk,
58535
+ risk_reward
58536
+ });
58537
+ return this.getConfig({
58538
+ params: {
58539
+ entry: config2.entry,
58540
+ stop: config2.stop,
58541
+ risk_reward: long_c.risk_reward,
58542
+ risk: long_c.risk
58543
+ }
58544
+ });
58545
+ }
58546
+ return config2;
58547
+ }
58063
58548
  }
58064
58549
 
58065
58550
  // src/exchange-account.ts
@@ -58110,16 +58595,22 @@ class ExchangeAccount {
58110
58595
  return result;
58111
58596
  }
58112
58597
  async initializePositions(payload) {
58598
+ const raw_positions = await this.syncAccount({
58599
+ update: payload.update,
58600
+ symbol: payload.symbol,
58601
+ live_refresh: payload.update
58602
+ });
58113
58603
  const positions = await this.syncAccount({
58114
58604
  symbol: payload.symbol,
58115
- as_view: payload.as_view
58605
+ as_view: true
58116
58606
  });
58117
- const raw_positions = await this.syncAccount({
58607
+ const symbol_config = await this.recomputeSymbolConfig({
58118
58608
  symbol: payload.symbol
58119
58609
  });
58120
58610
  const long_position = positions.find((x) => x.kind === "long");
58121
58611
  const short_position = positions.find((x) => x.kind === "short");
58122
58612
  this.long_position = new ExchangePosition({
58613
+ symbol_config,
58123
58614
  exchange: this.exchange,
58124
58615
  exchange_account: this,
58125
58616
  instance: long_position,
@@ -58127,6 +58618,7 @@ class ExchangeAccount {
58127
58618
  without_view: raw_positions.find((x) => x.kind === "long")
58128
58619
  });
58129
58620
  this.short_position = new ExchangePosition({
58621
+ symbol_config,
58130
58622
  exchange: this.exchange,
58131
58623
  exchange_account: this,
58132
58624
  instance: short_position,
@@ -58248,44 +58740,26 @@ class ExchangeAccount {
58248
58740
  }
58249
58741
  }
58250
58742
  }
58251
- async cancelOrders(payload) {
58252
- const { symbol, kind, price: _price, all, stop, limit, raw } = payload;
58253
- let price = _price || 0;
58254
- await this.syncAccount({
58255
- symbol,
58256
- kind,
58257
- update: true
58258
- });
58259
- if (limit) {
58260
- return await this.app_db.cancelLimitOrders({
58261
- raw,
58743
+ async getFocusPosition(payload) {
58744
+ const { symbol, kind, update = false } = payload;
58745
+ let focus_position = kind === "long" ? this.long_position : this.short_position;
58746
+ if (!focus_position) {
58747
+ focus_position = await this.initializePositions({
58262
58748
  symbol,
58263
58749
  kind,
58264
- account: this.instance,
58265
- cancelExchangeOrders: this.cancelExchangeOrders.bind(this)
58750
+ update
58266
58751
  });
58267
58752
  }
58268
- if (all) {
58269
- } else {
58270
- if (!price) {
58271
- const position2 = await this.syncAccount({
58272
- symbol,
58273
- kind: kind === "short" ? "long" : "short",
58274
- as_view: true
58275
- });
58276
- price = position2?.take_profit || 0;
58277
- }
58278
- }
58279
- let result = await this.app_db.cancelOrders({
58280
- cancelExchangeOrders: this.cancelExchangeOrders.bind(this),
58281
- all,
58282
- kind,
58283
- account: this.instance,
58753
+ return focus_position;
58754
+ }
58755
+ async cancelOrders(payload) {
58756
+ const { symbol, kind } = payload;
58757
+ const focus_position = await this.getFocusPosition({
58284
58758
  symbol,
58285
- price,
58286
- stop
58759
+ kind,
58760
+ update: true
58287
58761
  });
58288
- return result;
58762
+ return await focus_position.cancelOrders(payload);
58289
58763
  }
58290
58764
  async cancelExchangeOrders(payload) {
58291
58765
  return this.exchange.cancelOrders(payload);
@@ -58302,46 +58776,13 @@ class ExchangeAccount {
58302
58776
  });
58303
58777
  return break_even_price;
58304
58778
  }
58305
- async buildAppConfig(payload) {
58306
- let config2 = await this.app_db.getSymbolConfigFromDB(payload.symbol);
58307
- const app_config = buildAppConfig(config2, payload);
58308
- if (payload.update_db) {
58309
- const db_position = await this.syncAccount({
58310
- symbol: payload.symbol,
58311
- kind: app_config.kind
58312
- });
58313
- if (db_position) {
58314
- await this.app_db.createOrUpdatePositionConfig(db_position, {
58315
- entry: payload.entry,
58316
- stop: payload.stop,
58317
- risk_reward: payload.risk_reward,
58318
- risk: payload.risk,
58319
- profit_percent: payload.profit_percent
58320
- });
58321
- }
58322
- }
58323
- return app_config;
58324
- }
58325
58779
  async tradeConfig(payload) {
58326
58780
  const { symbol, kind, override = {} } = payload;
58327
- const config2 = await this.getPositionConfig({
58781
+ const focus_position = await this.getFocusPosition({
58328
58782
  symbol,
58329
58783
  kind
58330
58784
  });
58331
- const app_config = await this.buildAppConfig({
58332
- entry: config2.entry,
58333
- stop: config2.stop,
58334
- risk_reward: config2.risk_reward,
58335
- risk: config2.risk,
58336
- symbol,
58337
- use_kelly: config2.kelly?.use_kelly,
58338
- kelly_confidence_factor: config2.kelly?.kelly_confidence_factor,
58339
- kelly_minimum_risk: config2.kelly?.kelly_minimum_risk,
58340
- kelly_prediction_model: config2.kelly?.kelly_prediction_model,
58341
- kelly_func: config2.kelly?.kelly_func,
58342
- ...override
58343
- });
58344
- return app_config;
58785
+ return await focus_position.tradeConfig({ override });
58345
58786
  }
58346
58787
  async justInTimeProfit(payload) {
58347
58788
  const { symbol, target_pnl, kind, refresh, place, take_profit, pause_tp } = payload;
@@ -58359,7 +58800,7 @@ class ExchangeAccount {
58359
58800
  });
58360
58801
  const current_price = take_profit || position2.current_price;
58361
58802
  const notional_value = position2.quantity * position2.entry;
58362
- const current_pnl = to_f2(Math.abs(current_price - position2.entry) * position2.quantity, "%.2f");
58803
+ const current_pnl = to_f(Math.abs(current_price - position2.entry) * position2.quantity, "%.2f");
58363
58804
  const profit_percent = current_pnl * 100 / notional_value;
58364
58805
  const sell_ratio = target_pnl / current_pnl;
58365
58806
  if (place) {
@@ -58403,370 +58844,33 @@ class ExchangeAccount {
58403
58844
  }
58404
58845
  async buildTrades(payload) {
58405
58846
  const { symbol, kind, risk } = payload;
58406
- const config2 = await this.getPositionConfig({
58847
+ const focus_position = await this.getFocusPosition({
58407
58848
  symbol,
58408
58849
  kind
58409
58850
  });
58410
- const app_config = await this.buildAppConfig({
58411
- entry: config2.entry,
58412
- stop: config2.stop,
58413
- risk_reward: config2.risk_reward,
58414
- risk: risk || config2.risk,
58415
- symbol
58851
+ return await focus_position.buildTrades({ risk });
58852
+ }
58853
+ async placeSharedOrder(action, payload) {
58854
+ const kind = payload.entry > payload.stop ? "long" : "short";
58855
+ const focus_position = await this.getFocusPosition({
58856
+ symbol: payload.symbol,
58857
+ kind
58416
58858
  });
58417
- const { trades } = await this.placeConfigOrders(app_config, {
58418
- risk_reward: config2.risk_reward,
58419
- entry: config2.entry,
58420
- stop: config2.stop,
58421
- risk_per_trade: risk || config2.risk,
58422
- avg_size: 0,
58423
- neg_pnl: 0,
58424
- min_size: app_config.min_size,
58425
- symbol
58426
- });
58427
- const position2 = await this.syncAccount({
58428
- symbol,
58429
- kind
58430
- });
58431
- const orders_to_place = await this.determineAmountToBuy({
58432
- orders: trades.map((x) => ({
58433
- entry: x.entry,
58434
- quantity: x.quantity
58435
- })),
58436
- kind,
58437
- decimal_places: app_config.decimal_places,
58438
- price_places: app_config.price_places,
58439
- symbol
58440
- });
58441
- const avg_values = determine_average_entry_and_size(orders_to_place.map((u) => ({
58442
- price: u.entry,
58443
- quantity: u.quantity
58444
- })).concat({
58445
- price: position2.entry,
58446
- quantity: position2.quantity
58447
- }), app_config.decimal_places, app_config.price_places);
58448
- return {
58449
- trades: orders_to_place,
58450
- max_size: trades[0].avg_size,
58451
- last_price: trades[0].entry,
58452
- total_size: avg_values.quantity,
58453
- avg_entry: avg_values.price
58454
- };
58455
- }
58456
- async placeConfigOrders(app_config, solution, place, skip_stop) {
58457
- const { stop_percent = 100 } = solution;
58458
- app_config.entry = solution.entry;
58459
- app_config.stop = solution.stop;
58460
- app_config.risk_per_trade = solution.risk_per_trade;
58461
- app_config.min_size = solution.min_size;
58462
- app_config.risk_reward = solution.risk_reward;
58463
- app_config.kelly = {
58464
- use_kelly: solution.use_kelly,
58465
- kelly_confidence_factor: solution.kelly_confidence_factor,
58466
- kelly_minimum_risk: solution.kelly_minimum_risk,
58467
- kelly_prediction_model: solution.kelly_prediction_model,
58468
- kelly_func: solution.kelly_func
58469
- };
58470
- const options = {
58471
- take_profit: null,
58472
- entry: app_config.entry,
58473
- stop: app_config.stop,
58474
- raw_instance: null,
58475
- risk: app_config.risk_per_trade,
58476
- no_of_trades: undefined,
58477
- risk_reward: app_config.risk_reward,
58478
- kind: app_config.kind,
58479
- increase: true,
58480
- gap: app_config.gap,
58481
- rr: app_config.rr,
58482
- price_places: app_config.price_places,
58483
- decimal_places: app_config.decimal_places,
58484
- use_kelly: solution.use_kelly,
58485
- kelly_confidence_factor: solution.kelly_confidence_factor,
58486
- kelly_minimum_risk: solution.kelly_minimum_risk,
58487
- kelly_prediction_model: solution.kelly_prediction_model,
58488
- kelly_func: solution.kelly_func
58489
- };
58490
- const trades = sortedBuildConfig(app_config, options);
58491
- const entry_orders = {
58492
- orders: trades.map((x) => ({
58493
- entry: x.entry,
58494
- quantity: x.quantity,
58495
- reverse_avg_entry: x.reverse_avg_entry,
58496
- reverse_avg_quantity: x.reverse_avg_quantity,
58497
- avg_entry: x.avg_entry,
58498
- avg_size: x.avg_size
58499
- })),
58500
- kind: app_config.kind
58501
- };
58502
- const last_order = trades[0]?.entry;
58503
- const stop_spread = stop_percent / 100;
58504
- const _stop = app_config.kind === "short" ? last_order * (1 + stop_spread) : last_order * (1 - stop_spread);
58505
- const stop_to_user = stop_percent === 100 ? solution.stop : _stop;
58506
- const stop_orders = {
58507
- stop: stop_to_user,
58508
- final_stop: stop_to_user,
58509
- kind: app_config.kind,
58510
- quantity: trades[0]?.avg_size,
58511
- is_limit: true,
58512
- neg_pnl: trades[0]?.neg_pnl,
58513
- original_stop: solution.stop,
58514
- last_entry: last_order
58515
- };
58516
- if (place) {
58517
- let arr = [
58518
- this.exchange.bulkPlaceLimitOrders({
58519
- orders: trades.map((x) => ({
58520
- entry: x.entry,
58521
- quantity: x.quantity
58522
- })),
58523
- kind: app_config.kind,
58524
- decimal_places: app_config.decimal_places,
58525
- price_places: app_config.price_places,
58526
- symbol: solution.symbol,
58527
- place
58528
- })
58529
- ];
58530
- if (!skip_stop) {
58531
- arr.push(this.exchange.placeStopOrders({
58532
- symbol: solution.symbol,
58533
- quantity: trades[0].avg_size,
58534
- kind: app_config.kind,
58535
- stop: solution.stop,
58536
- price_places: app_config.price_places,
58537
- decimal_places: app_config.decimal_places,
58538
- place
58539
- }));
58540
- }
58541
- await Promise.all(arr);
58542
- }
58543
- return {
58544
- entry_orders,
58545
- stop_orders,
58546
- trades
58547
- };
58548
- }
58549
- async determineAmountToBuy(payload) {
58550
- const {
58551
- orders,
58552
- kind,
58553
- decimal_places = "%.3f",
58554
- symbol,
58555
- refresh,
58556
- cancel
58557
- } = payload;
58558
- const totalQuantity = orders.reduce((sum, order) => sum + (order.quantity || 0), 0);
58559
- let runningTotal = to_f2(totalQuantity, decimal_places);
58560
- let sortedOrders = [...orders].sort((a, b) => (a.entry || 0) - (b.entry || 0));
58561
- if (kind === "short") {
58562
- sortedOrders.reverse();
58563
- }
58564
- const withCumulative = [];
58565
- for (const order of sortedOrders) {
58566
- withCumulative.push({
58567
- ...order,
58568
- cumulative_quantity: runningTotal
58569
- });
58570
- runningTotal -= order.quantity;
58571
- runningTotal = to_f2(runningTotal, decimal_places);
58572
- }
58573
- const position2 = await this.syncAccount({
58574
- symbol,
58575
- kind,
58576
- live_refresh: refresh,
58577
- update: true
58578
- });
58579
- let existingOrders = await this.syncOrders({
58580
- symbol,
58581
- kind
58582
- });
58583
- let filteredOrders = withCumulative.filter((order) => (order.cumulative_quantity || 0) > position2?.quantity).map((order) => ({
58584
- ...order,
58585
- price: order.entry,
58586
- kind,
58587
- side: kind.toLowerCase() === "long" ? "buy" : "sell"
58588
- }));
58589
- filteredOrders = filteredOrders.filter((k) => !existingOrders.map((j) => j.price).includes(k.price));
58590
- const side = kind.toLowerCase() === "long" ? "buy" : "sell";
58591
- const shouldCancel = existingOrders.filter((k) => !orders.map((j) => j.entry).includes(k.price) && k.side === side).map((u) => u.price);
58592
- if (shouldCancel.length > 0 && cancel) {
58593
- const pp = kind === "long" ? Math.max(...shouldCancel) : Math.min(...shouldCancel);
58594
- const cancel_orders = await this.cancelOrders({
58595
- symbol,
58596
- kind,
58597
- price: pp
58598
- });
58599
- console.log("cancel_orders", cancel_orders);
58600
- }
58601
- return filteredOrders;
58602
- }
58603
- async placeSharedOrder(action, payload) {
58604
- const { stop_percent = 100 } = payload;
58605
- const kind = payload.entry > payload.stop ? "long" : "short";
58606
- const config2 = await this.getPositionConfig({
58607
- symbol: payload.symbol,
58608
- kind
58609
- });
58610
- const app_config = await this.buildAppConfig({
58611
- entry: payload.entry,
58612
- stop: payload.stop,
58613
- risk_reward: payload.risk_reward,
58614
- risk: payload.risk,
58859
+ const result = await focus_position.placeSharedOrder(action, payload);
58860
+ await this.getLiveExchangeInstance({
58615
58861
  symbol: payload.symbol,
58616
- profit: 0,
58617
- update_db: payload.update_db,
58618
- use_kelly: config2.kelly?.use_kelly,
58619
- kelly_confidence_factor: config2.kelly?.kelly_confidence_factor,
58620
- kelly_minimum_risk: config2.kelly?.kelly_minimum_risk,
58621
- kelly_prediction_model: config2.kelly?.kelly_prediction_model,
58622
- kelly_func: config2.kelly?.kelly_func
58862
+ refresh: true
58623
58863
  });
58624
- const { entry_orders, stop_orders, trades } = await this.placeConfigOrders(app_config, {
58625
- risk_reward: payload.risk_reward,
58626
- entry: payload.entry,
58627
- stop: payload.stop,
58628
- risk_per_trade: payload.risk,
58629
- avg_size: 0,
58630
- neg_pnl: 0,
58631
- min_size: app_config.min_size,
58632
- symbol: payload.symbol,
58633
- stop_percent,
58634
- use_kelly: config2.kelly?.use_kelly,
58635
- kelly_confidence_factor: config2.kelly?.kelly_confidence_factor,
58636
- kelly_minimum_risk: config2.kelly?.kelly_minimum_risk,
58637
- kelly_prediction_model: config2.kelly?.kelly_prediction_model,
58638
- kelly_func: config2.kelly?.kelly_func
58639
- }, false);
58640
- if (payload.raw) {
58641
- let actual_orders_to_buy = await this.determineAmountToBuy({
58642
- orders: trades,
58643
- kind: app_config.kind,
58644
- decimal_places: app_config.decimal_places,
58645
- price_places: app_config.price_places,
58646
- symbol: payload.symbol,
58647
- place: payload.place
58648
- });
58649
- if (action === "place_limit_orders" && payload.place) {
58650
- return await this.exchange.createLimitPurchaseOrders({
58651
- orders: actual_orders_to_buy.map((x) => ({
58652
- entry: x.entry,
58653
- quantity: x.quantity
58654
- })),
58655
- kind: app_config.kind,
58656
- decimal_places: app_config.decimal_places,
58657
- price_places: app_config.price_places,
58658
- symbol: payload.symbol
58659
- });
58660
- }
58661
- return actual_orders_to_buy;
58662
- }
58663
- if (action === "place_limit_orders" && payload.place) {
58664
- let result = await this.exchange.bulkPlaceLimitOrders({
58665
- orders: trades.map((x) => ({
58666
- entry: x.entry,
58667
- quantity: x.quantity
58668
- })),
58669
- kind: app_config.kind,
58670
- price_places: app_config.price_places,
58671
- decimal_places: app_config.decimal_places,
58672
- symbol: payload.symbol,
58673
- place: payload.place
58674
- });
58675
- await this.getLiveExchangeInstance({
58676
- symbol: payload.symbol,
58677
- refresh: true
58678
- });
58679
- return result;
58680
- }
58681
- if (action == "dangerous_entry_orders" && payload.place) {
58682
- return await this.exchange.createLimitPurchaseOrders({
58683
- orders: trades.map((x) => ({
58684
- ...x,
58685
- price: x.entry,
58686
- quantity: x.quantity,
58687
- side: app_config.kind === "long" ? "buy" : "sell",
58688
- kind: app_config.kind
58689
- })),
58690
- kind: app_config.kind,
58691
- decimal_places: app_config.decimal_places,
58692
- price_places: app_config.price_places,
58693
- symbol: payload.symbol
58694
- });
58695
- }
58696
- if (action === "place_stop_orders" && payload.place) {
58697
- const instance = await this.syncAccount({
58698
- symbol: payload.symbol,
58699
- kind: app_config.kind
58700
- });
58701
- let result = await this.exchange.placeStopOrders({
58702
- symbol: payload.symbol,
58703
- quantity: payload.use_current ? instance.quantity : trades[0].avg_size,
58704
- kind: app_config.kind,
58705
- stop: stop_orders.stop,
58706
- price_places: app_config.price_places,
58707
- decimal_places: app_config.decimal_places,
58708
- place: true
58709
- });
58710
- await this.getLiveExchangeInstance({
58711
- symbol: payload.symbol,
58712
- refresh: true
58713
- });
58714
- return result;
58715
- }
58716
- return {
58717
- entry_orders,
58718
- stop_orders
58719
- };
58864
+ return result;
58720
58865
  }
58721
58866
  async getOrCreatePositionConfig(payload) {
58722
- const { symbol, kind, risk = 50, risk_reward = 199 } = payload;
58723
- const config2 = await this.getPositionConfig({
58724
- symbol: payload.symbol,
58725
- kind: payload.kind
58726
- });
58727
- if (!config2) {
58728
- const long_c = await this.buildConfigForSymbol({
58729
- symbol,
58730
- risk,
58731
- risk_reward
58732
- });
58733
- return this.getPositionConfig({
58734
- symbol,
58735
- kind,
58736
- params: {
58737
- entry: kind === "long" ? long_c.entry : long_c.stop,
58738
- stop: kind === "long" ? long_c.stop : long_c.entry,
58739
- risk_reward: long_c.risk_reward,
58740
- risk: long_c.risk
58741
- }
58742
- });
58743
- }
58744
- return config2;
58867
+ const focus_position = await this.getFocusPosition(payload);
58868
+ return await focus_position.getOrCreatePositionConfig(payload);
58745
58869
  }
58746
58870
  async getPositionConfig(payload) {
58747
- if (payload.params) {
58748
- const db_position = await this.syncAccount({
58749
- symbol: payload.symbol,
58750
- kind: payload.kind
58751
- });
58752
- if (db_position) {
58753
- const config2 = db_position.expand?.config;
58754
- const params = {
58755
- entry: payload.params.entry !== undefined ? payload.params.entry : config2?.entry,
58756
- stop: payload.params.stop !== undefined ? payload.params.stop : config2?.stop,
58757
- risk_reward: payload.params.risk_reward !== undefined ? payload.params.risk_reward : config2?.risk_reward,
58758
- risk: payload.params.risk !== undefined ? payload.params.risk : config2?.risk,
58759
- profit_percent: payload.params.profit_percent !== undefined ? payload.params.profit_percent : config2?.profit_percent,
58760
- place_tp: payload.params.place_tp !== undefined ? payload.params.place_tp : true,
58761
- profit: payload.params.profit !== undefined ? payload.params.profit : config2?.profit
58762
- };
58763
- return await this.app_db.createOrUpdatePositionConfig(db_position, params);
58764
- }
58765
- }
58766
- return await this.app_db.getPositionConfig({
58767
- symbol: payload.symbol,
58768
- kind: payload.kind,
58769
- account: this.instance
58871
+ const focus_position = await this.getFocusPosition(payload);
58872
+ return await focus_position.getConfig({
58873
+ params: payload.params
58770
58874
  });
58771
58875
  }
58772
58876
  async getCurrentPrice(symbol) {
@@ -58779,23 +58883,23 @@ class ExchangeAccount {
58779
58883
  });
58780
58884
  }
58781
58885
  async buildReduceConfig(payload) {
58782
- const positions = await this.syncAccount({
58783
- symbol: payload.symbol
58784
- });
58785
- const long_position = positions.find((x) => x.kind === "long");
58786
- const short_position = positions.find((x) => x.kind === "short");
58787
- const long_config = await this.getPositionConfig({
58886
+ const long_position = await this.getFocusPosition({
58788
58887
  symbol: payload.symbol,
58789
58888
  kind: "long"
58790
58889
  });
58791
- const short_config = await this.getPositionConfig({
58890
+ const short_position = await this.getFocusPosition({
58792
58891
  symbol: payload.symbol,
58793
58892
  kind: "short"
58794
58893
  });
58894
+ const long_config = await long_position.getConfig();
58895
+ const short_config = await short_position.getConfig();
58795
58896
  const config2 = build_reduce_config({
58796
58897
  account: this.instance,
58797
58898
  symbol: payload.symbol,
58798
- _positions: positions,
58899
+ _positions: [
58900
+ long_position.getInstance(),
58901
+ short_position.getInstance()
58902
+ ],
58799
58903
  long_config,
58800
58904
  short_config
58801
58905
  });
@@ -58804,8 +58908,8 @@ class ExchangeAccount {
58804
58908
  }
58805
58909
  let long_target_pnl = payload.kind == "long" ? payload.target_pnl : 0;
58806
58910
  let short_target_pnl = payload.kind == "short" ? payload.target_pnl : 0;
58807
- const long_sell_ratio = long_config.sell_ratio || long_position?.sell_ratio;
58808
- const short_sell_ratio = short_config.sell_ratio || short_position?.sell_ratio;
58911
+ const long_sell_ratio = long_config.sell_ratio || long_position.getInstance()?.sell_ratio;
58912
+ const short_sell_ratio = short_config.sell_ratio || short_position.getInstance()?.sell_ratio;
58809
58913
  if (payload.as_dict) {
58810
58914
  return {
58811
58915
  long: {
@@ -58885,9 +58989,9 @@ class ExchangeAccount {
58885
58989
  async placeProfitAndStop(payload) {
58886
58990
  const { symbol, trigger: trigger2, refresh, kind, target_pnl } = payload;
58887
58991
  if (refresh) {
58888
- await this.syncAccount({
58992
+ await this.initializePositions({
58889
58993
  symbol,
58890
- live_refresh: true,
58994
+ kind,
58891
58995
  update: true
58892
58996
  });
58893
58997
  }
@@ -58920,14 +59024,16 @@ class ExchangeAccount {
58920
59024
  kind
58921
59025
  });
58922
59026
  }
58923
- const long_config = await this.getPositionConfig({
59027
+ const long_position = await this.getFocusPosition({
58924
59028
  symbol,
58925
59029
  kind: "long"
58926
59030
  });
58927
- const short_config = await this.getPositionConfig({
59031
+ const short_position = await this.getFocusPosition({
58928
59032
  symbol,
58929
59033
  kind: "short"
58930
59034
  });
59035
+ const long_config = await long_position.getConfig();
59036
+ const short_config = await short_position.getConfig();
58931
59037
  const long_pause_tp = long_config?.pause_tp;
58932
59038
  const short_pause_tp = short_config?.pause_tp;
58933
59039
  if (payload.trigger && !long_pause_tp && !short_pause_tp && config2) {
@@ -58941,299 +59047,75 @@ class ExchangeAccount {
58941
59047
  return config2;
58942
59048
  }
58943
59049
  async reEnterPositionOnEmpty(symbol) {
58944
- await this.getLiveExchangeInstance({
59050
+ const long_position = await this.getFocusPosition({
58945
59051
  symbol,
58946
- refresh: true
59052
+ kind: "long"
58947
59053
  });
58948
- const db_positions = await this.syncAccount({
59054
+ const short_position = await this.getFocusPosition({
58949
59055
  symbol,
58950
- update: true
59056
+ kind: "short"
58951
59057
  });
58952
- const long_position = db_positions.find((x) => x.kind === "long");
58953
- const short_position = db_positions.find((x) => x.kind === "short");
58954
- if (long_position && long_position.quantity === 0) {
58955
- await this.triggerTradeFromConfig({
58956
- symbol,
58957
- kind: "long"
58958
- });
59058
+ if (long_position && long_position.getInstance().quantity === 0) {
59059
+ await long_position.triggerTradeFromConfig({});
58959
59060
  }
58960
- if (short_position && short_position.quantity === 0) {
58961
- await this.triggerTradeFromConfig({
58962
- symbol,
58963
- kind: "short"
58964
- });
59061
+ if (short_position && short_position.getInstance().quantity === 0) {
59062
+ await short_position.triggerTradeFromConfig({});
58965
59063
  }
58966
- if (long_position.target_pnl > 0 || short_position.target_pnl > 0) {
59064
+ if (long_position.getInstance().target_pnl > 0 || short_position.getInstance().target_pnl > 0) {
58967
59065
  await Promise.all([
58968
- this.updateTargetPnl({
58969
- symbol,
58970
- kind: "long"
58971
- }),
58972
- this.updateTargetPnl({
58973
- symbol,
58974
- kind: "short"
58975
- })
59066
+ long_position.updateTargetPnl(),
59067
+ short_position.updateTargetPnl()
58976
59068
  ]);
58977
59069
  }
58978
59070
  }
58979
- async generate_config_params(payload) {
58980
- const {
58981
- entry,
58982
- stop,
58983
- risk_reward,
58984
- risk,
58985
- symbol,
58986
- with_trades = false
58987
- } = payload;
58988
- const app_config = await this.buildAppConfig({
58989
- entry,
58990
- stop,
58991
- risk_reward,
58992
- risk,
58993
- symbol
58994
- });
58995
- let config2 = generate_config_params(app_config, {
58996
- entry,
58997
- stop,
58998
- risk_reward,
58999
- risk,
59000
- symbol
59001
- });
59002
- if (with_trades) {
59003
- const app_config2 = await this.buildAppConfig({
59004
- entry: config2.entry,
59005
- stop: config2.stop,
59006
- risk_reward: config2.risk_reward,
59007
- risk: config2.risk,
59008
- symbol,
59009
- profit: 0,
59010
- update_db: false
59011
- });
59012
- const { trades } = await this.placeConfigOrders(app_config2, {
59013
- risk_reward: config2.risk_reward,
59014
- entry: config2.entry,
59015
- stop: config2.stop,
59016
- risk_per_trade: config2.risk,
59017
- avg_size: 0,
59018
- neg_pnl: 0,
59019
- min_size: app_config2.min_size,
59020
- symbol
59021
- }, false);
59022
- config2.trades = trades;
59023
- }
59024
- return { ...config2, place_stop: false, profit_percent: 0 };
59025
- }
59026
59071
  async build_short_order(payload) {
59027
- const { symbol, kind } = payload;
59028
- const position2 = await this.syncAccount({
59029
- symbol,
59030
- kind,
59031
- as_view: true
59032
- });
59033
- const position_config = await this.getPositionConfig({
59034
- symbol,
59035
- kind
59036
- });
59037
- if (position2 && position_config && position2.entry > 0) {
59038
- let next_order = position2.next_order;
59039
- let take_profit = position2.take_profit;
59040
- if (next_order && take_profit) {
59041
- let config2 = await this.buildConfigForSymbol({
59042
- symbol,
59043
- risk: position_config.risk,
59044
- risk_reward: position_config.risk_reward,
59045
- kind,
59046
- as_config: true
59047
- });
59048
- const focus = config2.entries.filter((x) => {
59049
- if (kind == "long") {
59050
- return x.entry <= next_order;
59051
- } else {
59052
- return x.entry >= next_order;
59053
- }
59054
- });
59055
- const focus_entry = focus.at(-1);
59056
- if (focus_entry) {
59057
- let entry = focus_entry.entry;
59058
- let risk = Math.abs(focus_entry.neg_pnl);
59059
- return await this.generate_config_params({
59060
- entry,
59061
- stop: take_profit,
59062
- risk_reward: position_config.risk_reward,
59063
- risk,
59064
- symbol
59065
- });
59066
- }
59067
- }
59068
- }
59072
+ const focus_position = await this.getFocusPosition(payload);
59073
+ return await focus_position.build_short_order();
59069
59074
  }
59070
59075
  async extrapolateShortConfig(payload) {
59071
- const { symbol, risk_reward = 199, kind, risk } = payload;
59076
+ const { symbol, kind } = payload;
59072
59077
  let reverse_kind = kind === "long" ? "short" : "long";
59073
- const position2 = await this.syncAccount({
59078
+ const focus_position = await this.getFocusPosition({
59074
59079
  symbol,
59075
- kind: reverse_kind,
59076
- as_view: true
59080
+ kind: reverse_kind
59081
+ });
59082
+ return await focus_position.extrapolateConfig({
59083
+ kind
59077
59084
  });
59078
- if (position2) {
59079
- let entry = position2.next_order || position2.avg_liquidation;
59080
- if (kind == "short" && entry < 0) {
59081
- const symbol_config = await this.recomputeSymbolConfig({
59082
- symbol
59083
- });
59084
- entry = symbol_config?.support;
59085
- }
59086
- return await this.generate_config_params({
59087
- entry,
59088
- stop: position2.take_profit,
59089
- risk_reward,
59090
- risk: risk || position2.target_pnl,
59091
- symbol
59092
- });
59093
- }
59094
- return null;
59095
59085
  }
59096
59086
  async placeMarketOrder(payload) {
59097
- const { symbol, kind, quantity } = payload;
59098
- const symbol_config = await this.recomputeSymbolConfig({
59099
- symbol
59100
- });
59101
- await this.exchange.placeMarketOrder({
59087
+ const { symbol, kind } = payload;
59088
+ const focus_position = await this.getFocusPosition(payload);
59089
+ await focus_position.placeMarketOrder(payload);
59090
+ await this.initializePositions({
59102
59091
  symbol,
59103
59092
  kind,
59104
- quantity,
59105
- price_places: symbol_config.price_places,
59106
- decimal_places: symbol_config.decimal_places
59107
- });
59108
- await this.syncAccount({
59109
- symbol,
59110
- update: true,
59111
- live_refresh: true
59093
+ update: true
59112
59094
  });
59113
59095
  }
59114
59096
  async placeSingleOrder(payload) {
59115
59097
  const { symbol, kind } = payload;
59116
- const positions = await this.syncAccount({
59117
- live_refresh: true,
59118
- update: true,
59119
- symbol
59120
- });
59121
- const long_position = positions.find((x) => x.kind === "long");
59122
- const short_position = positions.find((x) => x.kind === "short");
59123
- const long_config = await this.getPositionConfig({
59098
+ const long_position = await this.getFocusPosition({
59124
59099
  symbol,
59125
59100
  kind: "long"
59126
59101
  });
59127
- const short_config = await this.getPositionConfig({
59102
+ const short_position = await this.getFocusPosition({
59128
59103
  symbol,
59129
59104
  kind: "short"
59130
59105
  });
59131
- const focus_config = kind === "long" ? long_config : short_config;
59132
59106
  const focus_position = kind === "long" ? long_position : short_position;
59133
- const track_position = kind === "long" ? short_position : long_position;
59134
- const follow = focus_config.follow || focus_position.follow;
59135
- const threshold_qty = focus_config.threshold_qty || focus_position.threshold_qty;
59136
- if (!follow) {
59137
- return "No follow set";
59138
- }
59139
- let should_place_order = false;
59140
- if (threshold_qty === 0) {
59141
- should_place_order = true;
59142
- }
59143
- if (threshold_qty > 0 && track_position.quantity >= threshold_qty) {
59144
- should_place_order = true;
59145
- }
59146
- if (focus_position.quantity === 0) {
59147
- should_place_order = true;
59148
- }
59149
- if (track_position.quantity !== focus_position.quantity && focus_position.quantity < track_position.quantity && should_place_order) {
59150
- const remaining_quantity = Math.abs(track_position.quantity - focus_position.quantity);
59151
- await this.placeMarketOrder({
59152
- symbol,
59153
- kind,
59154
- quantity: remaining_quantity
59155
- });
59156
- }
59107
+ return await focus_position.placeSingleOrder({
59108
+ long_position,
59109
+ short_position
59110
+ });
59157
59111
  }
59158
59112
  async increasePositionAtStop(payload) {
59159
- const { symbol, kind, place = false, increase = true } = payload;
59160
- const position2 = await this.syncAccount({
59161
- symbol,
59162
- kind,
59163
- as_view: true
59164
- });
59165
- console.log(position2);
59166
- let price_params = {
59167
- price: payload.price,
59168
- quantity: payload.quantity
59169
- };
59170
- if (!payload.price && position2 && position2.stop_loss) {
59171
- price_params.price = position2.stop_loss.price;
59172
- }
59173
- if (!payload.quantity && position2 && position2.stop_loss) {
59174
- price_params.quantity = position2.stop_loss.quantity;
59175
- }
59176
- if (price_params.price && price_params.quantity) {
59177
- const { price, quantity } = price_params;
59178
- const symbol_config = await this.recomputeSymbolConfig({
59179
- symbol
59180
- });
59181
- const price_places = symbol_config.price_places;
59182
- const decimal_places = symbol_config.decimal_places;
59183
- if (place) {
59184
- await this.cancelOrders({
59185
- symbol,
59186
- kind,
59187
- limit: true
59188
- });
59189
- }
59190
- return await this.exchange.customStopLoss({
59191
- symbol,
59192
- kind,
59193
- stop: price,
59194
- quantity,
59195
- price_places,
59196
- decimal_places,
59197
- increase,
59198
- place
59199
- });
59200
- }
59113
+ const focus_position = await this.getFocusPosition(payload);
59114
+ return await focus_position.increasePositionAtStop(payload);
59201
59115
  }
59202
59116
  async triggerTradeFromConfig(payload) {
59203
- const {
59204
- symbol,
59205
- kind,
59206
- place = true,
59207
- stop,
59208
- use_current,
59209
- ignore_config,
59210
- risky
59211
- } = payload;
59212
- const position2 = await this.syncAccount({
59213
- symbol,
59214
- kind,
59215
- as_view: true
59216
- });
59217
- const config2 = await this.getPositionConfig({
59218
- symbol,
59219
- kind
59220
- });
59221
- let condition = ignore_config ? true : position2?.config;
59222
- if (condition) {
59223
- let entry = payload.tp ? position2.entry || config2.entry : config2.entry;
59224
- const v = stop ? "place_stop_orders" : risky ? "dangerous_entry_orders" : "place_limit_orders";
59225
- return await this.placeSharedOrder(v, {
59226
- symbol,
59227
- entry,
59228
- stop: config2.stop,
59229
- risk_reward: config2.risk_reward,
59230
- risk: config2.risk,
59231
- place,
59232
- raw: payload.raw,
59233
- use_current,
59234
- stop_percent: config2.stop_percent || 100
59235
- });
59236
- }
59117
+ const focus_position = await this.getFocusPosition(payload);
59118
+ return await focus_position.triggerTradeFromConfig(payload);
59237
59119
  }
59238
59120
  async verifyStopLoss(payload) {
59239
59121
  const { symbol, kind, revert } = payload;
@@ -59415,59 +59297,19 @@ class ExchangeAccount {
59415
59297
  }
59416
59298
  async updateTargetPnl(payload) {
59417
59299
  const { symbol, kind } = payload;
59418
- const position2 = await this.syncAccount({
59300
+ const focus_position = await this.getFocusPosition({
59419
59301
  symbol,
59420
59302
  kind
59421
59303
  });
59422
- if (position2?.expand?.config) {
59423
- const config2 = position2.expand.config;
59424
- let _profit = config2.profit;
59425
- let risk = config2.risk;
59426
- let next_risk = position2.next_risk;
59427
- let _profit_percent = config2?.profit_percent;
59428
- if (_profit_percent && (position2?.quantity || 0) > 0) {
59429
- _profit = to_f2(position2.quantity * _profit_percent * position2.entry / 100);
59430
- next_risk = risk + _profit;
59431
- }
59432
- await this.app_db.update_db_position(position2, {
59433
- target_pnl: _profit,
59434
- next_risk
59435
- });
59436
- return _profit;
59437
- }
59438
- return 0;
59304
+ return await focus_position.updateTargetPnl();
59439
59305
  }
59440
59306
  async updateRiskOnEmpty(payload) {
59441
59307
  const { symbol, kind } = payload;
59442
- const position2 = await this.syncAccount({
59308
+ const focus_position = await this.getFocusPosition({
59443
59309
  symbol,
59444
59310
  kind
59445
59311
  });
59446
- if (position2 && position2.quantity === 0) {
59447
- if (position2.next_risk && position2.next_risk > 0) {
59448
- await this.getPositionConfig({
59449
- symbol,
59450
- kind,
59451
- params: {
59452
- risk: position2.next_risk
59453
- }
59454
- });
59455
- console.log(`Updated ${kind} position config for ${symbol}: risk = ${position2.next_risk}`);
59456
- return {
59457
- updated: true,
59458
- symbol,
59459
- kind,
59460
- old_risk: position2.expand?.config?.risk,
59461
- new_risk: position2.next_risk
59462
- };
59463
- }
59464
- }
59465
- return {
59466
- updated: false,
59467
- symbol,
59468
- kind,
59469
- reason: position2 ? position2.quantity > 0 ? "Position not empty" : "No next_risk available" : "Position not found"
59470
- };
59312
+ return await focus_position.updateRiskOnEmpty();
59471
59313
  }
59472
59314
  async updateGoodHedgeConfig(payload) {
59473
59315
  const {
@@ -59479,19 +59321,20 @@ class ExchangeAccount {
59479
59321
  update = true
59480
59322
  } = payload;
59481
59323
  let _params = params;
59324
+ const long_position = await this.getFocusPosition({
59325
+ symbol,
59326
+ kind: "long"
59327
+ });
59328
+ const short_position = await this.getFocusPosition({
59329
+ symbol,
59330
+ kind: "short"
59331
+ });
59482
59332
  if (!params) {
59483
59333
  const result = await this.exchange.analyzeCandlesticks({ symbol });
59484
59334
  const support_price = Math.min(...Object.keys(result.support).map(Number));
59485
- const symbol_config = await this.recomputeSymbolConfig({ symbol });
59486
- const config2 = await this.getPositionConfig({
59487
- symbol,
59488
- kind: "long"
59489
- });
59490
- const position2 = await this.syncAccount({
59491
- symbol,
59492
- kind: "long",
59493
- as_view: true
59494
- });
59335
+ const symbol_config = long_position.symbol_config;
59336
+ const config2 = await long_position.getConfig();
59337
+ const position2 = long_position.getInstance();
59495
59338
  const bot_position = {
59496
59339
  kind: "long",
59497
59340
  entry: position2.entry,
@@ -59508,9 +59351,7 @@ class ExchangeAccount {
59508
59351
  });
59509
59352
  }
59510
59353
  if (update) {
59511
- await this.getPositionConfig({
59512
- symbol,
59513
- kind: "short",
59354
+ await short_position.getConfig({
59514
59355
  params: {
59515
59356
  entry: _params.support,
59516
59357
  stop: _params.resistance,
@@ -59519,22 +59360,15 @@ class ExchangeAccount {
59519
59360
  });
59520
59361
  }
59521
59362
  if (update_tp) {
59522
- await this.getPositionConfig({
59523
- symbol,
59524
- kind: "long",
59363
+ await long_position.getConfig({
59525
59364
  params: {
59526
59365
  profit_percent: _params.profit_percent
59527
59366
  }
59528
59367
  });
59529
- await this.updateTargetPnl({
59530
- symbol,
59531
- kind: "long"
59532
- });
59368
+ await long_position.updateTargetPnl();
59533
59369
  }
59534
59370
  if (place) {
59535
- await this.placeTrade({
59536
- symbol,
59537
- kind: "short",
59371
+ await short_position.placeTrade({
59538
59372
  limit: true,
59539
59373
  ignore_config: true
59540
59374
  });
@@ -59543,37 +59377,13 @@ class ExchangeAccount {
59543
59377
  }
59544
59378
  async placeOppositeTradeAction(payload) {
59545
59379
  const { symbol, kind, data } = payload;
59546
- const position2 = await this.syncAccount({
59380
+ const focus_position = await this.getFocusPosition({
59547
59381
  symbol,
59548
- kind,
59549
- as_view: true
59382
+ kind
59383
+ });
59384
+ return await focus_position.placeOppositeTradeAction({
59385
+ data
59550
59386
  });
59551
- if (position2.avg_qty !== data.avg.quantity) {
59552
- const config2 = await this.getPositionConfig({
59553
- symbol,
59554
- kind
59555
- });
59556
- await this.app_db.updateScheduledTrade(config2.id, {
59557
- entry: data.entry,
59558
- stop: data.stop,
59559
- risk: data.risk_per_trade,
59560
- profit_percent: data.profit_percent,
59561
- risk_reward: data.risk_reward
59562
- });
59563
- await this.placeTrade({
59564
- symbol,
59565
- kind,
59566
- place: true,
59567
- ignore_config: true
59568
- });
59569
- await this.placeTrade({
59570
- symbol,
59571
- kind,
59572
- place: true,
59573
- stop: true,
59574
- ignore_config: true
59575
- });
59576
- }
59577
59387
  }
59578
59388
  async buildOppositeTrades(payload) {
59579
59389
  const { symbol, kind, place, place_symbol } = payload;
@@ -59603,60 +59413,20 @@ class ExchangeAccount {
59603
59413
  }
59604
59414
  async runSimulation(payload) {
59605
59415
  const { symbol, kind, iterations = 2, raw = false } = payload;
59606
- const positions = await this.syncAccount({
59607
- symbol,
59608
- as_view: true
59609
- });
59610
- const symbol_config = await this.recomputeSymbolConfig({
59611
- symbol
59612
- });
59613
- const long_position = positions.find((x) => x.kind === "long");
59614
- const short_position = positions.find((x) => x.kind === "short");
59615
- const long_config = await this.getPositionConfig({
59416
+ const long_position = await this.getFocusPosition({
59616
59417
  symbol,
59617
59418
  kind: "long"
59618
59419
  });
59619
- const short_config = await this.getPositionConfig({
59420
+ const short_position = await this.getFocusPosition({
59620
59421
  symbol,
59621
59422
  kind: "short"
59622
59423
  });
59623
- const focus_config = kind === "long" ? long_config : short_config;
59624
- const short_tp_factor = short_config.profit_percent / long_config.profit_percent;
59625
- const reduce_ratio = focus_config.reduce_ratio;
59626
- const budget = focus_config.risk;
59627
- const risk_reward = focus_config.risk_reward;
59628
- const tp_percent = long_config.profit_percent;
59629
- const fee_percent = symbol_config.fee_percent;
59630
- const strategy_config = {
59631
- tp_percent,
59632
- short_tp_factor,
59633
- fee_percent,
59634
- budget,
59635
- risk_reward,
59636
- reduce_ratio,
59637
- global_config: symbol_config
59638
- };
59639
- const strategy2 = new Strategy({
59640
- long: {
59641
- entry: long_position.entry,
59642
- quantity: long_position.quantity,
59643
- avg_price: long_position.avg_price,
59644
- avg_qty: long_position.avg_qty
59645
- },
59646
- short: {
59647
- entry: short_position.entry,
59648
- quantity: short_position.quantity,
59649
- avg_price: short_position.avg_price,
59650
- avg_qty: short_position.avg_qty
59651
- },
59652
- config: strategy_config
59653
- });
59654
- if (raw) {
59655
- return strategy2;
59656
- }
59657
- return strategy2.runIterations({
59424
+ const focus_position = kind === "long" ? long_position : short_position;
59425
+ return focus_position.runSimulation({
59658
59426
  iterations,
59659
- kind
59427
+ raw,
59428
+ long_position,
59429
+ short_position
59660
59430
  });
59661
59431
  }
59662
59432
  async getCurrentRun(payload) {
@@ -59718,34 +59488,12 @@ class ExchangeAccount {
59718
59488
  return this.app_db.getSymbolConfigFromDB(symbol);
59719
59489
  }
59720
59490
  async buildConfigForSymbol(payload) {
59721
- const {
59491
+ const { symbol, kind = "long" } = payload;
59492
+ const focus_position = await this.getFocusPosition({
59722
59493
  symbol,
59723
- risk,
59724
- risk_reward = 199,
59725
- as_config = false,
59726
- kind = "long"
59727
- } = payload;
59728
- const symbol_config = await this.recomputeSymbolConfig({
59729
- symbol
59730
- });
59731
- const long_config = await this.generate_config_params({
59732
- entry: kind === "long" ? symbol_config.resistance : symbol_config.support,
59733
- stop: kind === "long" ? symbol_config.support : symbol_config.resistance,
59734
- risk_reward,
59735
- risk,
59736
- symbol
59494
+ kind
59737
59495
  });
59738
- if (as_config) {
59739
- const app_config = buildAppConfig(symbol_config, {
59740
- entry: long_config.entry,
59741
- stop: long_config.stop,
59742
- risk_reward,
59743
- risk: long_config.risk,
59744
- symbol
59745
- });
59746
- return app_config;
59747
- }
59748
- return long_config;
59496
+ return await focus_position.buildConfigForSymbol(payload);
59749
59497
  }
59750
59498
  async triggerBullishMarket(payload) {
59751
59499
  let { symbol, profit_percent = 10, risk_reward = 199 } = payload;
@@ -59851,15 +59599,9 @@ class ExchangeAccount {
59851
59599
  const all_open_symbols = await this.exchange.getOpenPositions();
59852
59600
  await new Promise((resolve) => setTimeout(resolve, interval * 1000));
59853
59601
  for (const symbol of Array.from(new Set(symbols.concat(all_open_symbols)))) {
59854
- await this.getLiveExchangeInstance({ symbol, refresh: true });
59602
+ await this.initializePositions({ symbol, kind: "long", update: true });
59855
59603
  await new Promise((resolve) => setTimeout(resolve, 1000));
59856
59604
  }
59857
- for (const symbol of all_open_symbols) {
59858
- await this.syncAccount({
59859
- symbol,
59860
- update: true
59861
- });
59862
- }
59863
59605
  }
59864
59606
  async updateAllPositionsWithNoConfig(payload) {
59865
59607
  const { kind } = payload;
@@ -60171,139 +59913,32 @@ class ExchangeAccount {
60171
59913
  }
60172
59914
  async computeTargetPnl(payload) {
60173
59915
  const { symbol, kind } = payload;
60174
- const reverse_kind = kind === "long" ? "short" : "long";
60175
- const root_position = await this.syncAccount({
59916
+ const focus_position = await this.getFocusPosition({
60176
59917
  symbol,
60177
59918
  kind
60178
59919
  });
60179
- const reverse_position = await this.syncAccount({
59920
+ const secondary_position = await this.getFocusPosition({
60180
59921
  symbol,
60181
- kind: reverse_kind
59922
+ kind: kind === "long" ? "short" : "long"
59923
+ });
59924
+ return await focus_position.computeTargetPnl({
59925
+ secondary: secondary_position
60182
59926
  });
60183
- if (reverse_position?.expand?.config && root_position.quantity > 0) {
60184
- const reverse_config = reverse_position.expand.config;
60185
- const diff = Math.abs(reverse_config.stop - root_position.entry);
60186
- const result = to_f2(diff * root_position.quantity);
60187
- if (root_position.target_pnl !== result) {
60188
- await this.app_db.update_db_position(root_position, {
60189
- target_pnl: result
60190
- });
60191
- await this.getPositionConfig({
60192
- kind: reverse_kind,
60193
- symbol,
60194
- params: {
60195
- ...reverse_config,
60196
- risk: result
60197
- }
60198
- });
60199
- }
60200
- return result;
60201
- }
60202
- return 0;
60203
59927
  }
60204
59928
  async placeStopLimit(payload) {
60205
- const { symbol, kind, place, stop, quantity: _quantity } = payload;
60206
- const position2 = await this.syncAccount({
60207
- symbol,
60208
- kind,
60209
- as_view: true
60210
- });
60211
- if (position2.avg_qty && position2.avg_qty > 0) {
60212
- const spread = 1.00005;
60213
- const qty = _quantity || position2.avg_qty - position2.quantity;
60214
- const symbol_config = await this.recomputeSymbolConfig({ symbol });
60215
- const orders = [
60216
- {
60217
- kind,
60218
- stop,
60219
- quantity: to_f2(qty, symbol_config.decimal_places),
60220
- side: kind === "long" ? "buy" : "sell",
60221
- price: to_f2(kind === "short" ? stop * spread ** -1 : stop * spread, symbol_config.price_places)
60222
- }
60223
- ];
60224
- if (place) {
60225
- return this.exchange.placeBadStopEntry({
60226
- symbol,
60227
- orders,
60228
- price_places: symbol_config.price_places,
60229
- decimal_places: symbol_config.decimal_places
60230
- });
60231
- }
60232
- return orders;
60233
- }
60234
- return [];
59929
+ const focus_position = await this.getFocusPosition(payload);
59930
+ return await focus_position.placeStopLimit(payload);
60235
59931
  }
60236
59932
  async placeTrade(payload) {
60237
- const {
60238
- symbol,
60239
- kind,
60240
- place,
60241
- tp,
60242
- limit = true,
60243
- raw: _raw,
60244
- cancel,
60245
- stop,
60246
- ignore_config,
60247
- target_pnl,
60248
- risky
60249
- } = payload;
60250
- if (cancel) {
60251
- await this.cancelOrders({
60252
- symbol,
60253
- kind
60254
- });
60255
- }
60256
- if (limit) {
60257
- return await this.triggerTradeFromConfig({
60258
- symbol,
60259
- kind,
60260
- raw: payload.raw,
60261
- stop,
60262
- ignore_config,
60263
- place,
60264
- risky
60265
- });
60266
- }
60267
- await this.syncAccount({
60268
- symbol,
60269
- live_refresh: true,
60270
- update: true
60271
- });
60272
- await this.updateConfigPnl({
60273
- symbol,
60274
- kind
59933
+ const focus_position = await this.getFocusPosition({
59934
+ symbol: payload.symbol,
59935
+ kind: payload.kind
60275
59936
  });
60276
- if (tp) {
60277
- await this.placeProfitAndStop({
60278
- symbol,
60279
- trigger: true,
60280
- target_pnl
60281
- });
60282
- }
60283
- return [];
59937
+ return await focus_position.placeTrade(payload);
60284
59938
  }
60285
59939
  async updateConfigPnl(payload) {
60286
- const { symbol, kind } = payload;
60287
- const position2 = await this.syncAccount({
60288
- symbol,
60289
- kind
60290
- });
60291
- if (!position2?.config) {
60292
- const config2 = await this.getPositionConfig({ symbol, kind });
60293
- if (config2) {
60294
- await this.app_db.update_db_position(position2, { config: config2.id });
60295
- await this.updateTargetPnl({
60296
- symbol,
60297
- kind
60298
- });
60299
- await this.app_db.update_db_position(position2, { config: null });
60300
- }
60301
- } else {
60302
- await this.updateTargetPnl({
60303
- symbol,
60304
- kind
60305
- });
60306
- }
59940
+ const focus_position = await this.getFocusPosition(payload);
59941
+ return await focus_position.updateConfigPnl();
60307
59942
  }
60308
59943
  async determineReduceTp(payload) {
60309
59944
  const { symbol, factor } = payload;
@@ -60318,10 +59953,10 @@ class ExchangeAccount {
60318
59953
  const gap_cost = gap * long_position.quantity * factor;
60319
59954
  const long_diff = gap_cost / (short_position.entry * short_position.quantity);
60320
59955
  const short_diff = gap_cost / (long_position.entry * long_position.quantity);
60321
- const long_tp = to_f2((long_diff + 1) * short_position.entry, symbol_config.price_places);
60322
- const short_tp = to_f2((short_diff + 1) ** -1 * long_position.entry, symbol_config.price_places);
60323
- const long_percent = to_f2(Math.abs(long_tp - long_position.entry) * 100 / long_position.entry, "%.4f");
60324
- const short_percent = to_f2(Math.abs(short_tp - short_position.entry) * 100 / short_position.entry, "%.4f");
59956
+ const long_tp = to_f((long_diff + 1) * short_position.entry, symbol_config.price_places);
59957
+ const short_tp = to_f((short_diff + 1) ** -1 * long_position.entry, symbol_config.price_places);
59958
+ const long_percent = to_f(Math.abs(long_tp - long_position.entry) * 100 / long_position.entry, "%.4f");
59959
+ const short_percent = to_f(Math.abs(short_tp - short_position.entry) * 100 / short_position.entry, "%.4f");
60325
59960
  return {
60326
59961
  long_diff,
60327
59962
  short_diff,
@@ -60335,7 +59970,6 @@ class ExchangeAccount {
60335
59970
  }
60336
59971
  async profitWithinGapStrategy(payload) {
60337
59972
  const { symbol } = payload;
60338
- let reward_factor = 1;
60339
59973
  console.log("Fetching positions for ", symbol);
60340
59974
  const positions = await this.syncAccount({
60341
59975
  symbol,
@@ -60349,70 +59983,11 @@ class ExchangeAccount {
60349
59983
  if (!strategy2) {
60350
59984
  return;
60351
59985
  }
60352
- const risk = strategy2.risk;
60353
59986
  const kind = strategy2.kind;
60354
- const support = strategy2.support;
60355
- const resistance = strategy2.resistance;
60356
- console.log("Getting long and short positions for ", symbol);
60357
- const long_position = positions.find((k) => k.kind === "long");
60358
- const short_position = positions.find((k) => k.kind === "short");
60359
- console.log("Getting focus position for ", symbol, kind);
60360
- if (strategy2.max_reward_factor === 0) {
60361
- reward_factor = strategy2.reward_factor;
60362
- }
60363
- if (focus_position.avg_qty >= focus_position.quantity && strategy2.max_reward_factor) {
60364
- if (strategy2.dynamic) {
60365
- const quantity_ratio = focus_position.quantity / focus_position.avg_qty;
60366
- reward_factor = to_f2(quantity_ratio ** 2 * strategy2.max_reward_factor, "%.2f");
60367
- } else {
60368
- reward_factor = to_f2(focus_position.quantity * strategy2.max_reward_factor / focus_position.avg_qty, "%.4f");
60369
- }
60370
- } else {
60371
- reward_factor = strategy2.reward_factor;
60372
- }
60373
- console.log("Getting entry and stop for ", symbol, kind);
60374
- const entry = kind === "long" ? resistance : support;
60375
- const stop = kind === "long" ? support : resistance;
60376
- console.log("Building app config for ", symbol, kind);
60377
- const initial_app_config = await this.buildAppConfig({
60378
- entry,
60379
- stop,
60380
- risk_reward: 199,
60381
- risk,
60382
- symbol
60383
- });
60384
- console.log("Computing risk reward for ", symbol, kind);
60385
- const risk_reward = strategy2.risk_reward || computeRiskReward({
60386
- app_config: initial_app_config,
60387
- entry: initial_app_config.entry,
60388
- stop: initial_app_config.stop,
60389
- risk_per_trade: initial_app_config.risk_per_trade
60390
- });
60391
- console.log("Re-computing app config for ", symbol, kind);
60392
- const { entries, last_value, ...app_config } = await this.buildAppConfig({
60393
- entry: initial_app_config.entry,
60394
- stop: initial_app_config.stop,
60395
- risk_reward,
60396
- risk,
60397
- symbol
60398
- });
60399
- console.log("Computing profit percent for ", symbol, kind);
60400
- const pnl = reward_factor * risk;
60401
- const profit_percent = to_f2(pnl * 100 / (last_value.avg_entry * last_value.avg_size), "%.4f");
60402
- let config2 = {
60403
- entry,
60404
- stop,
60405
- risk,
60406
- risk_reward,
60407
- profit_percent
60408
- };
60409
- console.log("Saving new config for ", symbol, kind);
60410
- const data = await this.getPositionConfig({
59987
+ const { entries, last_value, ...app_config } = await this.tradeConfig({
60411
59988
  symbol,
60412
- kind,
60413
- params: config2
59989
+ kind
60414
59990
  });
60415
- console.log("Checking orders to place for ", symbol, kind);
60416
59991
  await this.placeTrade({
60417
59992
  symbol,
60418
59993
  kind,
@@ -60420,10 +59995,6 @@ class ExchangeAccount {
60420
59995
  ignore_config: true,
60421
59996
  tp: true
60422
59997
  });
60423
- config2 = {
60424
- ...config2,
60425
- ...data
60426
- };
60427
59998
  if (focus_position.avg_qty < last_value.avg_size) {
60428
59999
  console.log("Placing trade for ", symbol, kind);
60429
60000
  await this.placeTrade({
@@ -60435,15 +60006,9 @@ class ExchangeAccount {
60435
60006
  }
60436
60007
  console.log("Checking if focus position has quantity for ", symbol, kind);
60437
60008
  return {
60438
- positions: {
60439
- long: long_position,
60440
- short: short_position
60441
- },
60442
60009
  config_details: {
60443
60010
  app_config,
60444
- last_value,
60445
- config: config2,
60446
- pnl
60011
+ last_value
60447
60012
  }
60448
60013
  };
60449
60014
  }