@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.cjs CHANGED
@@ -16595,8 +16595,8 @@ var require_combined_stream = __commonJS((exports2, module2) => {
16595
16595
  stream2.pipe(this, { end: false });
16596
16596
  return;
16597
16597
  }
16598
- var value2 = stream2;
16599
- this.write(value2);
16598
+ var value = stream2;
16599
+ this.write(value);
16600
16600
  this._getNext();
16601
16601
  };
16602
16602
  CombinedStream.prototype._handleErrors = function(stream2) {
@@ -25809,8 +25809,8 @@ var require_get = __commonJS((exports2, module2) => {
25809
25809
  var desc = !!hasProtoAccessor && gOPD && gOPD(Object.prototype, "__proto__");
25810
25810
  var $Object = Object;
25811
25811
  var $getPrototypeOf = $Object.getPrototypeOf;
25812
- module2.exports = desc && typeof desc.get === "function" ? callBind([desc.get]) : typeof $getPrototypeOf === "function" ? function getDunder(value2) {
25813
- return $getPrototypeOf(value2 == null ? value2 : $Object(value2));
25812
+ module2.exports = desc && typeof desc.get === "function" ? callBind([desc.get]) : typeof $getPrototypeOf === "function" ? function getDunder(value) {
25813
+ return $getPrototypeOf(value == null ? value : $Object(value));
25814
25814
  } : false;
25815
25815
  });
25816
25816
 
@@ -25982,26 +25982,26 @@ var require_get_intrinsic = __commonJS((exports2, module2) => {
25982
25982
  }
25983
25983
  var errorProto;
25984
25984
  var doEval = function doEval(name2) {
25985
- var value2;
25985
+ var value;
25986
25986
  if (name2 === "%AsyncFunction%") {
25987
- value2 = getEvalledConstructor("async function () {}");
25987
+ value = getEvalledConstructor("async function () {}");
25988
25988
  } else if (name2 === "%GeneratorFunction%") {
25989
- value2 = getEvalledConstructor("function* () {}");
25989
+ value = getEvalledConstructor("function* () {}");
25990
25990
  } else if (name2 === "%AsyncGeneratorFunction%") {
25991
- value2 = getEvalledConstructor("async function* () {}");
25991
+ value = getEvalledConstructor("async function* () {}");
25992
25992
  } else if (name2 === "%AsyncGenerator%") {
25993
25993
  var fn = doEval("%AsyncGeneratorFunction%");
25994
25994
  if (fn) {
25995
- value2 = fn.prototype;
25995
+ value = fn.prototype;
25996
25996
  }
25997
25997
  } else if (name2 === "%AsyncIteratorPrototype%") {
25998
25998
  var gen = doEval("%AsyncGenerator%");
25999
25999
  if (gen && getProto) {
26000
- value2 = getProto(gen.prototype);
26000
+ value = getProto(gen.prototype);
26001
26001
  }
26002
26002
  }
26003
- INTRINSICS[name2] = value2;
26004
- return value2;
26003
+ INTRINSICS[name2] = value;
26004
+ return value;
26005
26005
  };
26006
26006
  var LEGACY_ALIASES = {
26007
26007
  __proto__: null,
@@ -26088,17 +26088,17 @@ var require_get_intrinsic = __commonJS((exports2, module2) => {
26088
26088
  intrinsicName = "%" + alias[0] + "%";
26089
26089
  }
26090
26090
  if (hasOwn(INTRINSICS, intrinsicName)) {
26091
- var value2 = INTRINSICS[intrinsicName];
26092
- if (value2 === needsEval) {
26093
- value2 = doEval(intrinsicName);
26091
+ var value = INTRINSICS[intrinsicName];
26092
+ if (value === needsEval) {
26093
+ value = doEval(intrinsicName);
26094
26094
  }
26095
- if (typeof value2 === "undefined" && !allowMissing) {
26095
+ if (typeof value === "undefined" && !allowMissing) {
26096
26096
  throw new $TypeError("intrinsic " + name2 + " exists, but is not available. Please file an issue!");
26097
26097
  }
26098
26098
  return {
26099
26099
  alias,
26100
26100
  name: intrinsicName,
26101
- value: value2
26101
+ value
26102
26102
  };
26103
26103
  }
26104
26104
  throw new $SyntaxError("intrinsic " + name2 + " does not exist!");
@@ -26117,7 +26117,7 @@ var require_get_intrinsic = __commonJS((exports2, module2) => {
26117
26117
  var intrinsicBaseName = parts.length > 0 ? parts[0] : "";
26118
26118
  var intrinsic = getBaseIntrinsic("%" + intrinsicBaseName + "%", allowMissing);
26119
26119
  var intrinsicRealName = intrinsic.name;
26120
- var value2 = intrinsic.value;
26120
+ var value = intrinsic.value;
26121
26121
  var skipFurtherCaching = false;
26122
26122
  var alias = intrinsic.alias;
26123
26123
  if (alias) {
@@ -26137,32 +26137,32 @@ var require_get_intrinsic = __commonJS((exports2, module2) => {
26137
26137
  intrinsicBaseName += "." + part;
26138
26138
  intrinsicRealName = "%" + intrinsicBaseName + "%";
26139
26139
  if (hasOwn(INTRINSICS, intrinsicRealName)) {
26140
- value2 = INTRINSICS[intrinsicRealName];
26141
- } else if (value2 != null) {
26142
- if (!(part in value2)) {
26140
+ value = INTRINSICS[intrinsicRealName];
26141
+ } else if (value != null) {
26142
+ if (!(part in value)) {
26143
26143
  if (!allowMissing) {
26144
26144
  throw new $TypeError("base intrinsic for " + name2 + " exists, but the property is not available.");
26145
26145
  }
26146
26146
  return;
26147
26147
  }
26148
26148
  if ($gOPD && i2 + 1 >= parts.length) {
26149
- var desc = $gOPD(value2, part);
26149
+ var desc = $gOPD(value, part);
26150
26150
  isOwn = !!desc;
26151
26151
  if (isOwn && "get" in desc && !("originalValue" in desc.get)) {
26152
- value2 = desc.get;
26152
+ value = desc.get;
26153
26153
  } else {
26154
- value2 = value2[part];
26154
+ value = value[part];
26155
26155
  }
26156
26156
  } else {
26157
- isOwn = hasOwn(value2, part);
26158
- value2 = value2[part];
26157
+ isOwn = hasOwn(value, part);
26158
+ value = value[part];
26159
26159
  }
26160
26160
  if (isOwn && !skipFurtherCaching) {
26161
- INTRINSICS[intrinsicRealName] = value2;
26161
+ INTRINSICS[intrinsicRealName] = value;
26162
26162
  }
26163
26163
  }
26164
26164
  }
26165
- return value2;
26165
+ return value;
26166
26166
  };
26167
26167
  });
26168
26168
 
@@ -26182,7 +26182,7 @@ var require_es_set_tostringtag = __commonJS((exports2, module2) => {
26182
26182
  var hasOwn = require_hasown();
26183
26183
  var $TypeError = require_type();
26184
26184
  var toStringTag = hasToStringTag ? Symbol.toStringTag : null;
26185
- module2.exports = function setToStringTag(object, value2) {
26185
+ module2.exports = function setToStringTag(object, value) {
26186
26186
  var overrideIfSet = arguments.length > 2 && !!arguments[2] && arguments[2].force;
26187
26187
  var nonConfigurable = arguments.length > 2 && !!arguments[2] && arguments[2].nonConfigurable;
26188
26188
  if (typeof overrideIfSet !== "undefined" && typeof overrideIfSet !== "boolean" || typeof nonConfigurable !== "undefined" && typeof nonConfigurable !== "boolean") {
@@ -26193,11 +26193,11 @@ var require_es_set_tostringtag = __commonJS((exports2, module2) => {
26193
26193
  $defineProperty(object, toStringTag, {
26194
26194
  configurable: !nonConfigurable,
26195
26195
  enumerable: false,
26196
- value: value2,
26196
+ value,
26197
26197
  writable: false
26198
26198
  });
26199
26199
  } else {
26200
- object[toStringTag] = value2;
26200
+ object[toStringTag] = value;
26201
26201
  }
26202
26202
  }
26203
26203
  };
@@ -26245,77 +26245,77 @@ var require_form_data = __commonJS((exports2, module2) => {
26245
26245
  FormData2.LINE_BREAK = `\r
26246
26246
  `;
26247
26247
  FormData2.DEFAULT_CONTENT_TYPE = "application/octet-stream";
26248
- FormData2.prototype.append = function(field, value2, options) {
26248
+ FormData2.prototype.append = function(field, value, options) {
26249
26249
  options = options || {};
26250
26250
  if (typeof options == "string") {
26251
26251
  options = { filename: options };
26252
26252
  }
26253
26253
  var append = CombinedStream.prototype.append.bind(this);
26254
- if (typeof value2 == "number") {
26255
- value2 = "" + value2;
26254
+ if (typeof value == "number") {
26255
+ value = "" + value;
26256
26256
  }
26257
- if (Array.isArray(value2)) {
26257
+ if (Array.isArray(value)) {
26258
26258
  this._error(new Error("Arrays are not supported."));
26259
26259
  return;
26260
26260
  }
26261
- var header = this._multiPartHeader(field, value2, options);
26261
+ var header = this._multiPartHeader(field, value, options);
26262
26262
  var footer = this._multiPartFooter();
26263
26263
  append(header);
26264
- append(value2);
26264
+ append(value);
26265
26265
  append(footer);
26266
- this._trackLength(header, value2, options);
26266
+ this._trackLength(header, value, options);
26267
26267
  };
26268
- FormData2.prototype._trackLength = function(header, value2, options) {
26268
+ FormData2.prototype._trackLength = function(header, value, options) {
26269
26269
  var valueLength = 0;
26270
26270
  if (options.knownLength != null) {
26271
26271
  valueLength += +options.knownLength;
26272
- } else if (Buffer.isBuffer(value2)) {
26273
- valueLength = value2.length;
26274
- } else if (typeof value2 === "string") {
26275
- valueLength = Buffer.byteLength(value2);
26272
+ } else if (Buffer.isBuffer(value)) {
26273
+ valueLength = value.length;
26274
+ } else if (typeof value === "string") {
26275
+ valueLength = Buffer.byteLength(value);
26276
26276
  }
26277
26277
  this._valueLength += valueLength;
26278
26278
  this._overheadLength += Buffer.byteLength(header) + FormData2.LINE_BREAK.length;
26279
- if (!value2 || !value2.path && !(value2.readable && Object.prototype.hasOwnProperty.call(value2, "httpVersion")) && !(value2 instanceof Stream)) {
26279
+ if (!value || !value.path && !(value.readable && Object.prototype.hasOwnProperty.call(value, "httpVersion")) && !(value instanceof Stream)) {
26280
26280
  return;
26281
26281
  }
26282
26282
  if (!options.knownLength) {
26283
- this._valuesToMeasure.push(value2);
26283
+ this._valuesToMeasure.push(value);
26284
26284
  }
26285
26285
  };
26286
- FormData2.prototype._lengthRetriever = function(value2, callback) {
26287
- if (Object.prototype.hasOwnProperty.call(value2, "fd")) {
26288
- if (value2.end != null && value2.end != Infinity && value2.start != null) {
26289
- callback(null, value2.end + 1 - (value2.start ? value2.start : 0));
26286
+ FormData2.prototype._lengthRetriever = function(value, callback) {
26287
+ if (Object.prototype.hasOwnProperty.call(value, "fd")) {
26288
+ if (value.end != null && value.end != Infinity && value.start != null) {
26289
+ callback(null, value.end + 1 - (value.start ? value.start : 0));
26290
26290
  } else {
26291
- fs.stat(value2.path, function(err, stat) {
26291
+ fs.stat(value.path, function(err, stat) {
26292
26292
  var fileSize;
26293
26293
  if (err) {
26294
26294
  callback(err);
26295
26295
  return;
26296
26296
  }
26297
- fileSize = stat.size - (value2.start ? value2.start : 0);
26297
+ fileSize = stat.size - (value.start ? value.start : 0);
26298
26298
  callback(null, fileSize);
26299
26299
  });
26300
26300
  }
26301
- } else if (Object.prototype.hasOwnProperty.call(value2, "httpVersion")) {
26302
- callback(null, +value2.headers["content-length"]);
26303
- } else if (Object.prototype.hasOwnProperty.call(value2, "httpModule")) {
26304
- value2.on("response", function(response) {
26305
- value2.pause();
26301
+ } else if (Object.prototype.hasOwnProperty.call(value, "httpVersion")) {
26302
+ callback(null, +value.headers["content-length"]);
26303
+ } else if (Object.prototype.hasOwnProperty.call(value, "httpModule")) {
26304
+ value.on("response", function(response) {
26305
+ value.pause();
26306
26306
  callback(null, +response.headers["content-length"]);
26307
26307
  });
26308
- value2.resume();
26308
+ value.resume();
26309
26309
  } else {
26310
26310
  callback("Unknown stream");
26311
26311
  }
26312
26312
  };
26313
- FormData2.prototype._multiPartHeader = function(field, value2, options) {
26313
+ FormData2.prototype._multiPartHeader = function(field, value, options) {
26314
26314
  if (typeof options.header == "string") {
26315
26315
  return options.header;
26316
26316
  }
26317
- var contentDisposition = this._getContentDisposition(value2, options);
26318
- var contentType = this._getContentType(value2, options);
26317
+ var contentDisposition = this._getContentDisposition(value, options);
26318
+ var contentType = this._getContentType(value, options);
26319
26319
  var contents = "";
26320
26320
  var headers = {
26321
26321
  "Content-Disposition": ["form-data", 'name="' + field + '"'].concat(contentDisposition || []),
@@ -26341,35 +26341,35 @@ var require_form_data = __commonJS((exports2, module2) => {
26341
26341
  }
26342
26342
  return "--" + this.getBoundary() + FormData2.LINE_BREAK + contents + FormData2.LINE_BREAK;
26343
26343
  };
26344
- FormData2.prototype._getContentDisposition = function(value2, options) {
26344
+ FormData2.prototype._getContentDisposition = function(value, options) {
26345
26345
  var filename, contentDisposition;
26346
26346
  if (typeof options.filepath === "string") {
26347
26347
  filename = path.normalize(options.filepath).replace(/\\/g, "/");
26348
- } else if (options.filename || value2.name || value2.path) {
26349
- filename = path.basename(options.filename || value2.name || value2.path);
26350
- } else if (value2.readable && Object.prototype.hasOwnProperty.call(value2, "httpVersion")) {
26351
- filename = path.basename(value2.client._httpMessage.path || "");
26348
+ } else if (options.filename || value.name || value.path) {
26349
+ filename = path.basename(options.filename || value.name || value.path);
26350
+ } else if (value.readable && Object.prototype.hasOwnProperty.call(value, "httpVersion")) {
26351
+ filename = path.basename(value.client._httpMessage.path || "");
26352
26352
  }
26353
26353
  if (filename) {
26354
26354
  contentDisposition = 'filename="' + filename + '"';
26355
26355
  }
26356
26356
  return contentDisposition;
26357
26357
  };
26358
- FormData2.prototype._getContentType = function(value2, options) {
26358
+ FormData2.prototype._getContentType = function(value, options) {
26359
26359
  var contentType = options.contentType;
26360
- if (!contentType && value2.name) {
26361
- contentType = mime.lookup(value2.name);
26360
+ if (!contentType && value.name) {
26361
+ contentType = mime.lookup(value.name);
26362
26362
  }
26363
- if (!contentType && value2.path) {
26364
- contentType = mime.lookup(value2.path);
26363
+ if (!contentType && value.path) {
26364
+ contentType = mime.lookup(value.path);
26365
26365
  }
26366
- if (!contentType && value2.readable && Object.prototype.hasOwnProperty.call(value2, "httpVersion")) {
26367
- contentType = value2.headers["content-type"];
26366
+ if (!contentType && value.readable && Object.prototype.hasOwnProperty.call(value, "httpVersion")) {
26367
+ contentType = value.headers["content-type"];
26368
26368
  }
26369
26369
  if (!contentType && (options.filepath || options.filename)) {
26370
26370
  contentType = mime.lookup(options.filepath || options.filename);
26371
26371
  }
26372
- if (!contentType && typeof value2 == "object") {
26372
+ if (!contentType && typeof value == "object") {
26373
26373
  contentType = FormData2.DEFAULT_CONTENT_TYPE;
26374
26374
  }
26375
26375
  return contentType;
@@ -26742,9 +26742,9 @@ var require_follow_redirects = __commonJS((exports2, module2) => {
26742
26742
  this._ending = true;
26743
26743
  }
26744
26744
  };
26745
- RedirectableRequest.prototype.setHeader = function(name2, value2) {
26746
- this._options.headers[name2] = value2;
26747
- this._currentRequest.setHeader(name2, value2);
26745
+ RedirectableRequest.prototype.setHeader = function(name2, value) {
26746
+ this._options.headers[name2] = value;
26747
+ this._currentRequest.setHeader(name2, value);
26748
26748
  };
26749
26749
  RedirectableRequest.prototype.removeHeader = function(name2) {
26750
26750
  delete this._options.headers[name2];
@@ -27064,17 +27064,17 @@ var require_follow_redirects = __commonJS((exports2, module2) => {
27064
27064
  var dot = subdomain.length - domain.length - 1;
27065
27065
  return dot > 0 && subdomain[dot] === "." && subdomain.endsWith(domain);
27066
27066
  }
27067
- function isString2(value2) {
27068
- return typeof value2 === "string" || value2 instanceof String;
27067
+ function isString2(value) {
27068
+ return typeof value === "string" || value instanceof String;
27069
27069
  }
27070
- function isFunction(value2) {
27071
- return typeof value2 === "function";
27070
+ function isFunction(value) {
27071
+ return typeof value === "function";
27072
27072
  }
27073
- function isBuffer(value2) {
27074
- return typeof value2 === "object" && "length" in value2;
27073
+ function isBuffer(value) {
27074
+ return typeof value === "object" && "length" in value;
27075
27075
  }
27076
- function isURL2(value2) {
27077
- return URL2 && value2 instanceof URL2;
27076
+ function isURL2(value) {
27077
+ return URL2 && value instanceof URL2;
27078
27078
  }
27079
27079
  module2.exports = wrap3({ http: http2, https: https2 });
27080
27080
  module2.exports.wrap = wrap3;
@@ -27270,14 +27270,14 @@ var require_axios = __commonJS((exports2, module2) => {
27270
27270
  } while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype);
27271
27271
  return destObj;
27272
27272
  };
27273
- var endsWith = (str, searchString, position2) => {
27273
+ var endsWith = (str, searchString, position) => {
27274
27274
  str = String(str);
27275
- if (position2 === undefined || position2 > str.length) {
27276
- position2 = str.length;
27275
+ if (position === undefined || position > str.length) {
27276
+ position = str.length;
27277
27277
  }
27278
- position2 -= searchString.length;
27279
- const lastIndex = str.indexOf(searchString, position2);
27280
- return lastIndex !== -1 && lastIndex === position2;
27278
+ position -= searchString.length;
27279
+ const lastIndex = str.indexOf(searchString, position);
27280
+ return lastIndex !== -1 && lastIndex === position;
27281
27281
  };
27282
27282
  var toArray = (thing) => {
27283
27283
  if (!thing)
@@ -27339,8 +27339,8 @@ var require_axios = __commonJS((exports2, module2) => {
27339
27339
  if (isFunction(obj) && ["arguments", "caller", "callee"].indexOf(name2) !== -1) {
27340
27340
  return false;
27341
27341
  }
27342
- const value2 = obj[name2];
27343
- if (!isFunction(value2))
27342
+ const value = obj[name2];
27343
+ if (!isFunction(value))
27344
27344
  return;
27345
27345
  descriptor.enumerable = false;
27346
27346
  if ("writable" in descriptor) {
@@ -27357,8 +27357,8 @@ var require_axios = __commonJS((exports2, module2) => {
27357
27357
  var toObjectSet = (arrayOrString, delimiter) => {
27358
27358
  const obj = {};
27359
27359
  const define2 = (arr) => {
27360
- arr.forEach((value2) => {
27361
- obj[value2] = true;
27360
+ arr.forEach((value) => {
27361
+ obj[value] = true;
27362
27362
  });
27363
27363
  };
27364
27364
  isArray3(arrayOrString) ? define2(arrayOrString) : define2(String(arrayOrString).split(delimiter));
@@ -27366,8 +27366,8 @@ var require_axios = __commonJS((exports2, module2) => {
27366
27366
  };
27367
27367
  var noop2 = () => {
27368
27368
  };
27369
- var toFiniteNumber = (value2, defaultValue) => {
27370
- return value2 != null && Number.isFinite(value2 = +value2) ? value2 : defaultValue;
27369
+ var toFiniteNumber = (value, defaultValue) => {
27370
+ return value != null && Number.isFinite(value = +value) ? value : defaultValue;
27371
27371
  };
27372
27372
  function isSpecCompliantForm(thing) {
27373
27373
  return !!(thing && isFunction(thing.append) && thing[Symbol.toStringTag] === "FormData" && thing[Symbol.iterator]);
@@ -27382,8 +27382,8 @@ var require_axios = __commonJS((exports2, module2) => {
27382
27382
  if (!("toJSON" in source)) {
27383
27383
  stack[i2] = source;
27384
27384
  const target = isArray3(source) ? [] : {};
27385
- forEach2(source, (value2, key) => {
27386
- const reducedValue = visit(value2, i2 + 1);
27385
+ forEach2(source, (value, key) => {
27386
+ const reducedValue = visit(value, i2 + 1);
27387
27387
  !isUndefined3(reducedValue) && (target[key] = reducedValue);
27388
27388
  });
27389
27389
  stack[i2] = undefined;
@@ -27578,27 +27578,27 @@ var require_axios = __commonJS((exports2, module2) => {
27578
27578
  if (!utils$1.isFunction(visitor)) {
27579
27579
  throw new TypeError("visitor must be a function");
27580
27580
  }
27581
- function convertValue(value2) {
27582
- if (value2 === null)
27581
+ function convertValue(value) {
27582
+ if (value === null)
27583
27583
  return "";
27584
- if (utils$1.isDate(value2)) {
27585
- return value2.toISOString();
27584
+ if (utils$1.isDate(value)) {
27585
+ return value.toISOString();
27586
27586
  }
27587
- if (!useBlob && utils$1.isBlob(value2)) {
27587
+ if (!useBlob && utils$1.isBlob(value)) {
27588
27588
  throw new AxiosError("Blob is not supported. Use a Buffer instead.");
27589
27589
  }
27590
- if (utils$1.isArrayBuffer(value2) || utils$1.isTypedArray(value2)) {
27591
- return useBlob && typeof Blob === "function" ? new Blob([value2]) : Buffer.from(value2);
27590
+ if (utils$1.isArrayBuffer(value) || utils$1.isTypedArray(value)) {
27591
+ return useBlob && typeof Blob === "function" ? new Blob([value]) : Buffer.from(value);
27592
27592
  }
27593
- return value2;
27593
+ return value;
27594
27594
  }
27595
- function defaultVisitor(value2, key, path) {
27596
- let arr = value2;
27597
- if (value2 && !path && typeof value2 === "object") {
27595
+ function defaultVisitor(value, key, path) {
27596
+ let arr = value;
27597
+ if (value && !path && typeof value === "object") {
27598
27598
  if (utils$1.endsWith(key, "{}")) {
27599
27599
  key = metaTokens ? key : key.slice(0, -2);
27600
- value2 = JSON.stringify(value2);
27601
- } else if (utils$1.isArray(value2) && isFlatArray(value2) || (utils$1.isFileList(value2) || utils$1.endsWith(key, "[]")) && (arr = utils$1.toArray(value2))) {
27600
+ value = JSON.stringify(value);
27601
+ } else if (utils$1.isArray(value) && isFlatArray(value) || (utils$1.isFileList(value) || utils$1.endsWith(key, "[]")) && (arr = utils$1.toArray(value))) {
27602
27602
  key = removeBrackets(key);
27603
27603
  arr.forEach(function each(el, index) {
27604
27604
  !(utils$1.isUndefined(el) || el === null) && formData.append(indexes === true ? renderKey([key], index, dots) : indexes === null ? key : key + "[]", convertValue(el));
@@ -27606,10 +27606,10 @@ var require_axios = __commonJS((exports2, module2) => {
27606
27606
  return false;
27607
27607
  }
27608
27608
  }
27609
- if (isVisitable(value2)) {
27609
+ if (isVisitable(value)) {
27610
27610
  return true;
27611
27611
  }
27612
- formData.append(renderKey(path, key, dots), convertValue(value2));
27612
+ formData.append(renderKey(path, key, dots), convertValue(value));
27613
27613
  return false;
27614
27614
  }
27615
27615
  const stack = [];
@@ -27618,14 +27618,14 @@ var require_axios = __commonJS((exports2, module2) => {
27618
27618
  convertValue,
27619
27619
  isVisitable
27620
27620
  });
27621
- function build(value2, path) {
27622
- if (utils$1.isUndefined(value2))
27621
+ function build(value, path) {
27622
+ if (utils$1.isUndefined(value))
27623
27623
  return;
27624
- if (stack.indexOf(value2) !== -1) {
27624
+ if (stack.indexOf(value) !== -1) {
27625
27625
  throw Error("Circular reference detected in " + path.join("."));
27626
27626
  }
27627
- stack.push(value2);
27628
- utils$1.forEach(value2, function each(el, key) {
27627
+ stack.push(value);
27628
+ utils$1.forEach(value, function each(el, key) {
27629
27629
  const result = !(utils$1.isUndefined(el) || el === null) && visitor.call(formData, el, utils$1.isString(key) ? key.trim() : key, path, exposedHelpers);
27630
27630
  if (result === true) {
27631
27631
  build(el, path ? path.concat(key) : [key]);
@@ -27658,12 +27658,12 @@ var require_axios = __commonJS((exports2, module2) => {
27658
27658
  params && toFormData(params, this, options);
27659
27659
  }
27660
27660
  var prototype = AxiosURLSearchParams.prototype;
27661
- prototype.append = function append(name2, value2) {
27662
- this._pairs.push([name2, value2]);
27661
+ prototype.append = function append(name2, value) {
27662
+ this._pairs.push([name2, value]);
27663
27663
  };
27664
27664
  prototype.toString = function toString(encoder2) {
27665
- const _encode = encoder2 ? function(value2) {
27666
- return encoder2.call(this, value2, encode$1);
27665
+ const _encode = encoder2 ? function(value) {
27666
+ return encoder2.call(this, value, encode$1);
27667
27667
  } : encode$1;
27668
27668
  return this._pairs.map(function each(pair) {
27669
27669
  return _encode(pair[0]) + "=" + _encode(pair[1]);
@@ -27786,9 +27786,9 @@ var require_axios = __commonJS((exports2, module2) => {
27786
27786
  };
27787
27787
  function toURLEncodedForm(data, options) {
27788
27788
  return toFormData(data, new platform.classes.URLSearchParams, Object.assign({
27789
- visitor: function(value2, key, path, helpers) {
27790
- if (platform.isNode && utils$1.isBuffer(value2)) {
27791
- this.append(key, value2.toString("base64"));
27789
+ visitor: function(value, key, path, helpers) {
27790
+ if (platform.isNode && utils$1.isBuffer(value)) {
27791
+ this.append(key, value.toString("base64"));
27792
27792
  return false;
27793
27793
  }
27794
27794
  return helpers.defaultVisitor.apply(this, arguments);
@@ -27813,7 +27813,7 @@ var require_axios = __commonJS((exports2, module2) => {
27813
27813
  return obj;
27814
27814
  }
27815
27815
  function formDataToJSON(formData) {
27816
- function buildPath(path, value2, target, index) {
27816
+ function buildPath(path, value, target, index) {
27817
27817
  let name2 = path[index++];
27818
27818
  if (name2 === "__proto__")
27819
27819
  return true;
@@ -27822,16 +27822,16 @@ var require_axios = __commonJS((exports2, module2) => {
27822
27822
  name2 = !name2 && utils$1.isArray(target) ? target.length : name2;
27823
27823
  if (isLast) {
27824
27824
  if (utils$1.hasOwnProp(target, name2)) {
27825
- target[name2] = [target[name2], value2];
27825
+ target[name2] = [target[name2], value];
27826
27826
  } else {
27827
- target[name2] = value2;
27827
+ target[name2] = value;
27828
27828
  }
27829
27829
  return !isNumericKey;
27830
27830
  }
27831
27831
  if (!target[name2] || !utils$1.isObject(target[name2])) {
27832
27832
  target[name2] = [];
27833
27833
  }
27834
- const result = buildPath(path, value2, target[name2], index);
27834
+ const result = buildPath(path, value, target[name2], index);
27835
27835
  if (result && utils$1.isArray(target[name2])) {
27836
27836
  target[name2] = arrayToObject(target[name2]);
27837
27837
  }
@@ -27839,8 +27839,8 @@ var require_axios = __commonJS((exports2, module2) => {
27839
27839
  }
27840
27840
  if (utils$1.isFormData(formData) && utils$1.isFunction(formData.entries)) {
27841
27841
  const obj = {};
27842
- utils$1.forEachEntry(formData, (name2, value2) => {
27843
- buildPath(parsePropPath(name2), value2, obj, 0);
27842
+ utils$1.forEachEntry(formData, (name2, value) => {
27843
+ buildPath(parsePropPath(name2), value, obj, 0);
27844
27844
  });
27845
27845
  return obj;
27846
27846
  }
@@ -27993,11 +27993,11 @@ var require_axios = __commonJS((exports2, module2) => {
27993
27993
  function normalizeHeader(header) {
27994
27994
  return header && String(header).trim().toLowerCase();
27995
27995
  }
27996
- function normalizeValue(value2) {
27997
- if (value2 === false || value2 == null) {
27998
- return value2;
27996
+ function normalizeValue(value) {
27997
+ if (value === false || value == null) {
27998
+ return value;
27999
27999
  }
28000
- return utils$1.isArray(value2) ? value2.map(normalizeValue) : String(value2);
28000
+ return utils$1.isArray(value) ? value.map(normalizeValue) : String(value);
28001
28001
  }
28002
28002
  function parseTokens(str) {
28003
28003
  const tokens = Object.create(null);
@@ -28009,20 +28009,20 @@ var require_axios = __commonJS((exports2, module2) => {
28009
28009
  return tokens;
28010
28010
  }
28011
28011
  var isValidHeaderName = (str) => /^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(str.trim());
28012
- function matchHeaderValue(context3, value2, header, filter, isHeaderNameFilter) {
28012
+ function matchHeaderValue(context3, value, header, filter, isHeaderNameFilter) {
28013
28013
  if (utils$1.isFunction(filter)) {
28014
- return filter.call(this, value2, header);
28014
+ return filter.call(this, value, header);
28015
28015
  }
28016
28016
  if (isHeaderNameFilter) {
28017
- value2 = header;
28017
+ value = header;
28018
28018
  }
28019
- if (!utils$1.isString(value2))
28019
+ if (!utils$1.isString(value))
28020
28020
  return;
28021
28021
  if (utils$1.isString(filter)) {
28022
- return value2.indexOf(filter) !== -1;
28022
+ return value.indexOf(filter) !== -1;
28023
28023
  }
28024
28024
  if (utils$1.isRegExp(filter)) {
28025
- return filter.test(value2);
28025
+ return filter.test(value);
28026
28026
  }
28027
28027
  }
28028
28028
  function formatHeader(header) {
@@ -28064,8 +28064,8 @@ var require_axios = __commonJS((exports2, module2) => {
28064
28064
  } else if (utils$1.isString(header) && (header = header.trim()) && !isValidHeaderName(header)) {
28065
28065
  setHeaders(parseHeaders(header), valueOrRewrite);
28066
28066
  } else if (utils$1.isHeaders(header)) {
28067
- for (const [key, value2] of header.entries()) {
28068
- setHeader(value2, key, rewrite);
28067
+ for (const [key, value] of header.entries()) {
28068
+ setHeader(value, key, rewrite);
28069
28069
  }
28070
28070
  } else {
28071
28071
  header != null && setHeader(valueOrRewrite, header, rewrite);
@@ -28077,18 +28077,18 @@ var require_axios = __commonJS((exports2, module2) => {
28077
28077
  if (header) {
28078
28078
  const key = utils$1.findKey(this, header);
28079
28079
  if (key) {
28080
- const value2 = this[key];
28080
+ const value = this[key];
28081
28081
  if (!parser) {
28082
- return value2;
28082
+ return value;
28083
28083
  }
28084
28084
  if (parser === true) {
28085
- return parseTokens(value2);
28085
+ return parseTokens(value);
28086
28086
  }
28087
28087
  if (utils$1.isFunction(parser)) {
28088
- return parser.call(this, value2, key);
28088
+ return parser.call(this, value, key);
28089
28089
  }
28090
28090
  if (utils$1.isRegExp(parser)) {
28091
- return parser.exec(value2);
28091
+ return parser.exec(value);
28092
28092
  }
28093
28093
  throw new TypeError("parser must be boolean|regexp|function");
28094
28094
  }
@@ -28138,10 +28138,10 @@ var require_axios = __commonJS((exports2, module2) => {
28138
28138
  normalize(format) {
28139
28139
  const self2 = this;
28140
28140
  const headers = {};
28141
- utils$1.forEach(this, (value2, header) => {
28141
+ utils$1.forEach(this, (value, header) => {
28142
28142
  const key = utils$1.findKey(headers, header);
28143
28143
  if (key) {
28144
- self2[key] = normalizeValue(value2);
28144
+ self2[key] = normalizeValue(value);
28145
28145
  delete self2[header];
28146
28146
  return;
28147
28147
  }
@@ -28149,7 +28149,7 @@ var require_axios = __commonJS((exports2, module2) => {
28149
28149
  if (normalized !== header) {
28150
28150
  delete self2[header];
28151
28151
  }
28152
- self2[normalized] = normalizeValue(value2);
28152
+ self2[normalized] = normalizeValue(value);
28153
28153
  headers[normalized] = true;
28154
28154
  });
28155
28155
  return this;
@@ -28159,8 +28159,8 @@ var require_axios = __commonJS((exports2, module2) => {
28159
28159
  }
28160
28160
  toJSON(asStrings) {
28161
28161
  const obj = Object.create(null);
28162
- utils$1.forEach(this, (value2, header) => {
28163
- value2 != null && value2 !== false && (obj[header] = asStrings && utils$1.isArray(value2) ? value2.join(", ") : value2);
28162
+ utils$1.forEach(this, (value, header) => {
28163
+ value != null && value !== false && (obj[header] = asStrings && utils$1.isArray(value) ? value.join(", ") : value);
28164
28164
  });
28165
28165
  return obj;
28166
28166
  }
@@ -28168,7 +28168,7 @@ var require_axios = __commonJS((exports2, module2) => {
28168
28168
  return Object.entries(this.toJSON())[Symbol.iterator]();
28169
28169
  }
28170
28170
  toString() {
28171
- return Object.entries(this.toJSON()).map(([header, value2]) => header + ": " + value2).join(`
28171
+ return Object.entries(this.toJSON()).map(([header, value]) => header + ": " + value).join(`
28172
28172
  `);
28173
28173
  }
28174
28174
  get [Symbol.toStringTag]() {
@@ -28200,10 +28200,10 @@ var require_axios = __commonJS((exports2, module2) => {
28200
28200
  }
28201
28201
  }
28202
28202
  AxiosHeaders.accessor(["Content-Type", "Content-Length", "Accept", "Accept-Encoding", "User-Agent", "Authorization"]);
28203
- utils$1.reduceDescriptors(AxiosHeaders.prototype, ({ value: value2 }, key) => {
28203
+ utils$1.reduceDescriptors(AxiosHeaders.prototype, ({ value }, key) => {
28204
28204
  let mapped = key[0].toUpperCase() + key.slice(1);
28205
28205
  return {
28206
- get: () => value2,
28206
+ get: () => value,
28207
28207
  set(headerValue) {
28208
28208
  this[mapped] = headerValue;
28209
28209
  }
@@ -28222,8 +28222,8 @@ var require_axios = __commonJS((exports2, module2) => {
28222
28222
  headers.normalize();
28223
28223
  return data;
28224
28224
  }
28225
- function isCancel(value2) {
28226
- return !!(value2 && value2.__CANCEL__);
28225
+ function isCancel(value) {
28226
+ return !!(value && value.__CANCEL__);
28227
28227
  }
28228
28228
  function CanceledError(message2, config2, request) {
28229
28229
  AxiosError.call(this, message2 == null ? "canceled" : message2, AxiosError.ERR_CANCELED, config2, request);
@@ -28419,28 +28419,28 @@ var require_axios = __commonJS((exports2, module2) => {
28419
28419
  var CRLF_BYTES_COUNT = 2;
28420
28420
 
28421
28421
  class FormDataPart {
28422
- constructor(name2, value2) {
28422
+ constructor(name2, value) {
28423
28423
  const { escapeName } = this.constructor;
28424
- const isStringValue = utils$1.isString(value2);
28425
- let headers = `Content-Disposition: form-data; name="${escapeName(name2)}"${!isStringValue && value2.name ? `; filename="${escapeName(value2.name)}"` : ""}${CRLF}`;
28424
+ const isStringValue = utils$1.isString(value);
28425
+ let headers = `Content-Disposition: form-data; name="${escapeName(name2)}"${!isStringValue && value.name ? `; filename="${escapeName(value.name)}"` : ""}${CRLF}`;
28426
28426
  if (isStringValue) {
28427
- value2 = textEncoder.encode(String(value2).replace(/\r?\n|\r\n?/g, CRLF));
28427
+ value = textEncoder.encode(String(value).replace(/\r?\n|\r\n?/g, CRLF));
28428
28428
  } else {
28429
- headers += `Content-Type: ${value2.type || "application/octet-stream"}${CRLF}`;
28429
+ headers += `Content-Type: ${value.type || "application/octet-stream"}${CRLF}`;
28430
28430
  }
28431
28431
  this.headers = textEncoder.encode(headers + CRLF);
28432
- this.contentLength = isStringValue ? value2.byteLength : value2.size;
28432
+ this.contentLength = isStringValue ? value.byteLength : value.size;
28433
28433
  this.size = this.headers.byteLength + this.contentLength + CRLF_BYTES_COUNT;
28434
28434
  this.name = name2;
28435
- this.value = value2;
28435
+ this.value = value;
28436
28436
  }
28437
28437
  async* encode() {
28438
28438
  yield this.headers;
28439
- const { value: value2 } = this;
28440
- if (utils$1.isTypedArray(value2)) {
28441
- yield value2;
28439
+ const { value } = this;
28440
+ if (utils$1.isTypedArray(value)) {
28441
+ yield value;
28442
28442
  } else {
28443
- yield* readBlob$1(value2);
28443
+ yield* readBlob$1(value);
28444
28444
  }
28445
28445
  yield CRLF_BYTES;
28446
28446
  }
@@ -28467,8 +28467,8 @@ var require_axios = __commonJS((exports2, module2) => {
28467
28467
  const boundaryBytes = textEncoder.encode("--" + boundary + CRLF);
28468
28468
  const footerBytes = textEncoder.encode("--" + boundary + "--" + CRLF + CRLF);
28469
28469
  let contentLength = footerBytes.byteLength;
28470
- const parts = Array.from(form.entries()).map(([name2, value2]) => {
28471
- const part = new FormDataPart(name2, value2);
28470
+ const parts = Array.from(form.entries()).map(([name2, value]) => {
28471
+ const part = new FormDataPart(name2, value);
28472
28472
  contentLength += part.size;
28473
28473
  return part;
28474
28474
  });
@@ -28513,9 +28513,9 @@ var require_axios = __commonJS((exports2, module2) => {
28513
28513
  var callbackify = (fn, reducer) => {
28514
28514
  return utils$1.isAsyncFn(fn) ? function(...args) {
28515
28515
  const cb = args.pop();
28516
- fn.apply(this, args).then((value2) => {
28516
+ fn.apply(this, args).then((value) => {
28517
28517
  try {
28518
- reducer ? cb(null, ...reducer(value2)) : cb(null, value2);
28518
+ reducer ? cb(null, ...reducer(value)) : cb(null, value);
28519
28519
  } catch (err) {
28520
28520
  cb(err);
28521
28521
  }
@@ -28685,15 +28685,15 @@ var require_axios = __commonJS((exports2, module2) => {
28685
28685
  return new Promise((resolve, reject) => {
28686
28686
  let onDone;
28687
28687
  let isDone;
28688
- const done = (value2, isRejected) => {
28688
+ const done = (value, isRejected) => {
28689
28689
  if (isDone)
28690
28690
  return;
28691
28691
  isDone = true;
28692
- onDone && onDone(value2, isRejected);
28692
+ onDone && onDone(value, isRejected);
28693
28693
  };
28694
- const _resolve = (value2) => {
28695
- done(value2);
28696
- resolve(value2);
28694
+ const _resolve = (value) => {
28695
+ done(value);
28696
+ resolve(value);
28697
28697
  };
28698
28698
  const _reject = (reason) => {
28699
28699
  done(reason, true);
@@ -28721,7 +28721,7 @@ var require_axios = __commonJS((exports2, module2) => {
28721
28721
  let rejected = false;
28722
28722
  let req;
28723
28723
  if (lookup) {
28724
- const _lookup = callbackify$1(lookup, (value2) => utils$1.isArray(value2) ? value2 : [value2]);
28724
+ const _lookup = callbackify$1(lookup, (value) => utils$1.isArray(value) ? value : [value]);
28725
28725
  lookup = (hostname, opt, cb) => {
28726
28726
  _lookup(hostname, opt, (err, arg0, arg1) => {
28727
28727
  if (err) {
@@ -28742,7 +28742,7 @@ var require_axios = __commonJS((exports2, module2) => {
28742
28742
  }
28743
28743
  emitter.removeAllListeners();
28744
28744
  };
28745
- onDone((value2, isRejected) => {
28745
+ onDone((value, isRejected) => {
28746
28746
  isDone = true;
28747
28747
  if (isRejected) {
28748
28748
  rejected = true;
@@ -29077,8 +29077,8 @@ var require_axios = __commonJS((exports2, module2) => {
29077
29077
  return origin2.protocol === url2.protocol && origin2.host === url2.host && (isMSIE || origin2.port === url2.port);
29078
29078
  })(new URL(platform.origin), platform.navigator && /(msie|trident)/i.test(platform.navigator.userAgent)) : () => true;
29079
29079
  var cookies = platform.hasStandardBrowserEnv ? {
29080
- write(name2, value2, expires, path, domain, secure) {
29081
- const cookie = [name2 + "=" + encodeURIComponent(value2)];
29080
+ write(name2, value, expires, path, domain, secure) {
29081
+ const cookie = [name2 + "=" + encodeURIComponent(value)];
29082
29082
  utils$1.isNumber(expires) && cookie.push("expires=" + new Date(expires).toGMTString());
29083
29083
  utils$1.isString(path) && cookie.push("path=" + path);
29084
29084
  utils$1.isString(domain) && cookie.push("domain=" + domain);
@@ -29240,8 +29240,8 @@ var require_axios = __commonJS((exports2, module2) => {
29240
29240
  config: config2,
29241
29241
  request
29242
29242
  };
29243
- settle(function _resolve(value2) {
29244
- resolve(value2);
29243
+ settle(function _resolve(value) {
29244
+ resolve(value);
29245
29245
  done();
29246
29246
  }, function _reject(err) {
29247
29247
  reject(err);
@@ -29386,11 +29386,11 @@ var require_axios = __commonJS((exports2, module2) => {
29386
29386
  const reader = stream3.getReader();
29387
29387
  try {
29388
29388
  for (;; ) {
29389
- const { done, value: value2 } = await reader.read();
29389
+ const { done, value } = await reader.read();
29390
29390
  if (done) {
29391
29391
  break;
29392
29392
  }
29393
- yield value2;
29393
+ yield value;
29394
29394
  }
29395
29395
  } finally {
29396
29396
  await reader.cancel();
@@ -29409,18 +29409,18 @@ var require_axios = __commonJS((exports2, module2) => {
29409
29409
  return new ReadableStream({
29410
29410
  async pull(controller) {
29411
29411
  try {
29412
- const { done: done2, value: value2 } = await iterator.next();
29412
+ const { done: done2, value } = await iterator.next();
29413
29413
  if (done2) {
29414
29414
  _onFinish();
29415
29415
  controller.close();
29416
29416
  return;
29417
29417
  }
29418
- let len = value2.byteLength;
29418
+ let len = value.byteLength;
29419
29419
  if (onProgress) {
29420
29420
  let loadedBytes = bytes += len;
29421
29421
  onProgress(loadedBytes);
29422
29422
  }
29423
- controller.enqueue(new Uint8Array(value2));
29423
+ controller.enqueue(new Uint8Array(value));
29424
29424
  } catch (err) {
29425
29425
  _onFinish(err);
29426
29426
  throw err;
@@ -29589,13 +29589,13 @@ var require_axios = __commonJS((exports2, module2) => {
29589
29589
  xhr: xhrAdapter,
29590
29590
  fetch: fetchAdapter
29591
29591
  };
29592
- utils$1.forEach(knownAdapters, (fn, value2) => {
29592
+ utils$1.forEach(knownAdapters, (fn, value) => {
29593
29593
  if (fn) {
29594
29594
  try {
29595
- Object.defineProperty(fn, "name", { value: value2 });
29595
+ Object.defineProperty(fn, "name", { value });
29596
29596
  } catch (e2) {
29597
29597
  }
29598
- Object.defineProperty(fn, "adapterName", { value: value2 });
29598
+ Object.defineProperty(fn, "adapterName", { value });
29599
29599
  }
29600
29600
  });
29601
29601
  var renderReason = (reason) => `- ${reason}`;
@@ -29676,7 +29676,7 @@ var require_axios = __commonJS((exports2, module2) => {
29676
29676
  function formatMessage(opt, desc) {
29677
29677
  return "[Axios v" + VERSION3 + "] Transitional option '" + opt + "'" + desc + (message2 ? ". " + message2 : "");
29678
29678
  }
29679
- return (value2, opt, opts) => {
29679
+ return (value, opt, opts) => {
29680
29680
  if (validator2 === false) {
29681
29681
  throw new AxiosError(formatMessage(opt, " has been removed" + (version ? " in " + version : "")), AxiosError.ERR_DEPRECATED);
29682
29682
  }
@@ -29684,11 +29684,11 @@ var require_axios = __commonJS((exports2, module2) => {
29684
29684
  deprecatedWarnings[opt] = true;
29685
29685
  console.warn(formatMessage(opt, " has been deprecated since v" + version + " and will be removed in the near future"));
29686
29686
  }
29687
- return validator2 ? validator2(value2, opt, opts) : true;
29687
+ return validator2 ? validator2(value, opt, opts) : true;
29688
29688
  };
29689
29689
  };
29690
29690
  validators$1.spelling = function spelling(correctSpelling) {
29691
- return (value2, opt) => {
29691
+ return (value, opt) => {
29692
29692
  console.warn(`${opt} is likely a misspelling of ${correctSpelling}`);
29693
29693
  return true;
29694
29694
  };
@@ -29703,8 +29703,8 @@ var require_axios = __commonJS((exports2, module2) => {
29703
29703
  const opt = keys[i2];
29704
29704
  const validator2 = schema[opt];
29705
29705
  if (validator2) {
29706
- const value2 = options[opt];
29707
- const result = value2 === undefined || validator2(value2, opt, options);
29706
+ const value = options[opt];
29707
+ const result = value === undefined || validator2(value, opt, options);
29708
29708
  if (result !== true) {
29709
29709
  throw new AxiosError("option " + opt + " must be " + result, AxiosError.ERR_BAD_OPTION_VALUE);
29710
29710
  }
@@ -30037,8 +30037,8 @@ var require_axios = __commonJS((exports2, module2) => {
30037
30037
  NotExtended: 510,
30038
30038
  NetworkAuthenticationRequired: 511
30039
30039
  };
30040
- Object.entries(HttpStatusCode).forEach(([key, value2]) => {
30041
- HttpStatusCode[value2] = key;
30040
+ Object.entries(HttpStatusCode).forEach(([key, value]) => {
30041
+ HttpStatusCode[value] = key;
30042
30042
  });
30043
30043
  var HttpStatusCode$1 = HttpStatusCode;
30044
30044
  function createInstance(defaultConfig) {
@@ -30784,23 +30784,23 @@ var require_beautifier = __commonJS((exports2) => {
30784
30784
  }
30785
30785
  const newItem = {};
30786
30786
  for (const key2 in data) {
30787
- const value2 = data[key2];
30788
- const valueType = typeof value2;
30787
+ const value = data[key2];
30788
+ const valueType = typeof value;
30789
30789
  let newKey = knownBeautification[key2] || key2;
30790
30790
  if (Array.isArray(newKey)) {
30791
30791
  newKey = newKey[0];
30792
30792
  }
30793
- if (!Array.isArray(value2)) {
30794
- if (valueType === "object" && value2 !== null) {
30795
- newItem[newKey] = this.beautify(value2, knownBeautification[key2]);
30793
+ if (!Array.isArray(value)) {
30794
+ if (valueType === "object" && value !== null) {
30795
+ newItem[newKey] = this.beautify(value, knownBeautification[key2]);
30796
30796
  } else {
30797
- newItem[newKey] = this.beautifyValueWithKey(newKey, value2);
30797
+ newItem[newKey] = this.beautifyValueWithKey(newKey, value);
30798
30798
  }
30799
30799
  continue;
30800
30800
  }
30801
30801
  const newArray = [];
30802
30802
  if (Array.isArray(this.beautificationMap[newKey])) {
30803
- for (const elementValue of value2) {
30803
+ for (const elementValue of value) {
30804
30804
  const mappedBeautification = this.beautificationMap[knownBeautification[key2]];
30805
30805
  const childMapping = mappedBeautification[0];
30806
30806
  if (typeof childMapping === "object" && childMapping !== null) {
@@ -30897,22 +30897,22 @@ var require_nanoid = __commonJS((exports2, module2) => {
30897
30897
  // node_modules/binance/lib/util/browser-support.js
30898
30898
  var require_browser_support = __commonJS((exports2) => {
30899
30899
  var __awaiter = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) {
30900
- function adopt(value2) {
30901
- return value2 instanceof P ? value2 : new P(function(resolve) {
30902
- resolve(value2);
30900
+ function adopt(value) {
30901
+ return value instanceof P ? value : new P(function(resolve) {
30902
+ resolve(value);
30903
30903
  });
30904
30904
  }
30905
30905
  return new (P || (P = Promise))(function(resolve, reject) {
30906
- function fulfilled(value2) {
30906
+ function fulfilled(value) {
30907
30907
  try {
30908
- step(generator.next(value2));
30908
+ step(generator.next(value));
30909
30909
  } catch (e2) {
30910
30910
  reject(e2);
30911
30911
  }
30912
30912
  }
30913
- function rejected(value2) {
30913
+ function rejected(value) {
30914
30914
  try {
30915
- step(generator["throw"](value2));
30915
+ step(generator["throw"](value));
30916
30916
  } catch (e2) {
30917
30917
  reject(e2);
30918
30918
  }
@@ -30989,22 +30989,22 @@ var require_node_support = __commonJS((exports2) => {
30989
30989
  return result;
30990
30990
  };
30991
30991
  var __awaiter = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) {
30992
- function adopt(value2) {
30993
- return value2 instanceof P ? value2 : new P(function(resolve) {
30994
- resolve(value2);
30992
+ function adopt(value) {
30993
+ return value instanceof P ? value : new P(function(resolve) {
30994
+ resolve(value);
30995
30995
  });
30996
30996
  }
30997
30997
  return new (P || (P = Promise))(function(resolve, reject) {
30998
- function fulfilled(value2) {
30998
+ function fulfilled(value) {
30999
30999
  try {
31000
- step(generator.next(value2));
31000
+ step(generator.next(value));
31001
31001
  } catch (e2) {
31002
31002
  reject(e2);
31003
31003
  }
31004
31004
  }
31005
- function rejected(value2) {
31005
+ function rejected(value) {
31006
31006
  try {
31007
- step(generator["throw"](value2));
31007
+ step(generator["throw"](value));
31008
31008
  } catch (e2) {
31009
31009
  reject(e2);
31010
31010
  }
@@ -31036,22 +31036,22 @@ var require_node_support = __commonJS((exports2) => {
31036
31036
  // node_modules/binance/lib/util/requestUtils.js
31037
31037
  var require_requestUtils = __commonJS((exports2) => {
31038
31038
  var __awaiter = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) {
31039
- function adopt(value2) {
31040
- return value2 instanceof P ? value2 : new P(function(resolve) {
31041
- resolve(value2);
31039
+ function adopt(value) {
31040
+ return value instanceof P ? value : new P(function(resolve) {
31041
+ resolve(value);
31042
31042
  });
31043
31043
  }
31044
31044
  return new (P || (P = Promise))(function(resolve, reject) {
31045
- function fulfilled(value2) {
31045
+ function fulfilled(value) {
31046
31046
  try {
31047
- step(generator.next(value2));
31047
+ step(generator.next(value));
31048
31048
  } catch (e2) {
31049
31049
  reject(e2);
31050
31050
  }
31051
31051
  }
31052
- function rejected(value2) {
31052
+ function rejected(value) {
31053
31053
  try {
31054
- step(generator["throw"](value2));
31054
+ step(generator["throw"](value));
31055
31055
  } catch (e2) {
31056
31056
  reject(e2);
31057
31057
  }
@@ -31097,11 +31097,11 @@ var require_requestUtils = __commonJS((exports2) => {
31097
31097
  function serialiseParams(params = {}, strict_validation = false, encodeValues = false, filterUndefinedParams = false) {
31098
31098
  const paramKeys = !filterUndefinedParams ? Object.keys(params) : Object.keys(params).filter((key) => typeof params[key] !== "undefined");
31099
31099
  return paramKeys.map((key) => {
31100
- const value2 = params[key];
31101
- if (strict_validation === true && typeof value2 === "undefined") {
31100
+ const value = params[key];
31101
+ if (strict_validation === true && typeof value === "undefined") {
31102
31102
  throw new Error("Failed to sign API request due to undefined parameter");
31103
31103
  }
31104
- const encodedValue = encodeValues ? encodeURIComponent(value2) : value2;
31104
+ const encodedValue = encodeValues ? encodeURIComponent(value) : value;
31105
31105
  return `${key}=${encodedValue}`;
31106
31106
  }).join("&");
31107
31107
  }
@@ -31240,22 +31240,22 @@ var require_requestUtils = __commonJS((exports2) => {
31240
31240
  // node_modules/binance/lib/util/BaseRestClient.js
31241
31241
  var require_BaseRestClient = __commonJS((exports2) => {
31242
31242
  var __awaiter = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) {
31243
- function adopt(value2) {
31244
- return value2 instanceof P ? value2 : new P(function(resolve) {
31245
- resolve(value2);
31243
+ function adopt(value) {
31244
+ return value instanceof P ? value : new P(function(resolve) {
31245
+ resolve(value);
31246
31246
  });
31247
31247
  }
31248
31248
  return new (P || (P = Promise))(function(resolve, reject) {
31249
- function fulfilled(value2) {
31249
+ function fulfilled(value) {
31250
31250
  try {
31251
- step(generator.next(value2));
31251
+ step(generator.next(value));
31252
31252
  } catch (e2) {
31253
31253
  reject(e2);
31254
31254
  }
31255
31255
  }
31256
- function rejected(value2) {
31256
+ function rejected(value) {
31257
31257
  try {
31258
- step(generator["throw"](value2));
31258
+ step(generator["throw"](value));
31259
31259
  } catch (e2) {
31260
31260
  reject(e2);
31261
31261
  }
@@ -31327,8 +31327,8 @@ var require_BaseRestClient = __commonJS((exports2) => {
31327
31327
  getTimeOffset() {
31328
31328
  return this.timeOffset;
31329
31329
  }
31330
- setTimeOffset(value2) {
31331
- this.timeOffset = value2;
31330
+ setTimeOffset(value) {
31331
+ this.timeOffset = value;
31332
31332
  }
31333
31333
  get(endpoint, params) {
31334
31334
  return this._call("GET", endpoint, params);
@@ -31422,18 +31422,18 @@ var require_BaseRestClient = __commonJS((exports2) => {
31422
31422
  const delta = {};
31423
31423
  for (const headerKey in this.apiLimitTrackers) {
31424
31424
  const headerValue = responseHeaders[headerKey];
31425
- const value2 = parseInt(headerValue);
31426
- if (headerValue !== undefined && !isNaN(value2)) {
31427
- this.apiLimitTrackers[headerKey] = value2;
31425
+ const value = parseInt(headerValue);
31426
+ if (headerValue !== undefined && !isNaN(value)) {
31427
+ this.apiLimitTrackers[headerKey] = value;
31428
31428
  delta[headerKey] = {
31429
31429
  updated: true,
31430
- valueParsed: value2,
31430
+ valueParsed: value,
31431
31431
  valueRaw: headerValue
31432
31432
  };
31433
31433
  } else {
31434
31434
  delta[headerKey] = {
31435
31435
  updated: false,
31436
- valueParsed: value2,
31436
+ valueParsed: value,
31437
31437
  valueRaw: headerValue
31438
31438
  };
31439
31439
  }
@@ -31474,22 +31474,22 @@ var require_BaseRestClient = __commonJS((exports2) => {
31474
31474
  // node_modules/binance/lib/coinm-client.js
31475
31475
  var require_coinm_client = __commonJS((exports2) => {
31476
31476
  var __awaiter = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) {
31477
- function adopt(value2) {
31478
- return value2 instanceof P ? value2 : new P(function(resolve) {
31479
- resolve(value2);
31477
+ function adopt(value) {
31478
+ return value instanceof P ? value : new P(function(resolve) {
31479
+ resolve(value);
31480
31480
  });
31481
31481
  }
31482
31482
  return new (P || (P = Promise))(function(resolve, reject) {
31483
- function fulfilled(value2) {
31483
+ function fulfilled(value) {
31484
31484
  try {
31485
- step(generator.next(value2));
31485
+ step(generator.next(value));
31486
31486
  } catch (e2) {
31487
31487
  reject(e2);
31488
31488
  }
31489
31489
  }
31490
- function rejected(value2) {
31490
+ function rejected(value) {
31491
31491
  try {
31492
- step(generator["throw"](value2));
31492
+ step(generator["throw"](value));
31493
31493
  } catch (e2) {
31494
31494
  reject(e2);
31495
31495
  }
@@ -31841,22 +31841,22 @@ var require_logger = __commonJS((exports2) => {
31841
31841
  // node_modules/binance/lib/main-client.js
31842
31842
  var require_main_client = __commonJS((exports2) => {
31843
31843
  var __awaiter = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) {
31844
- function adopt(value2) {
31845
- return value2 instanceof P ? value2 : new P(function(resolve) {
31846
- resolve(value2);
31844
+ function adopt(value) {
31845
+ return value instanceof P ? value : new P(function(resolve) {
31846
+ resolve(value);
31847
31847
  });
31848
31848
  }
31849
31849
  return new (P || (P = Promise))(function(resolve, reject) {
31850
- function fulfilled(value2) {
31850
+ function fulfilled(value) {
31851
31851
  try {
31852
- step(generator.next(value2));
31852
+ step(generator.next(value));
31853
31853
  } catch (e2) {
31854
31854
  reject(e2);
31855
31855
  }
31856
31856
  }
31857
- function rejected(value2) {
31857
+ function rejected(value) {
31858
31858
  try {
31859
- step(generator["throw"](value2));
31859
+ step(generator["throw"](value));
31860
31860
  } catch (e2) {
31861
31861
  reject(e2);
31862
31862
  }
@@ -33387,22 +33387,22 @@ var require_main_client = __commonJS((exports2) => {
33387
33387
  // node_modules/binance/lib/portfolio-client.js
33388
33388
  var require_portfolio_client = __commonJS((exports2) => {
33389
33389
  var __awaiter = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) {
33390
- function adopt(value2) {
33391
- return value2 instanceof P ? value2 : new P(function(resolve) {
33392
- resolve(value2);
33390
+ function adopt(value) {
33391
+ return value instanceof P ? value : new P(function(resolve) {
33392
+ resolve(value);
33393
33393
  });
33394
33394
  }
33395
33395
  return new (P || (P = Promise))(function(resolve, reject) {
33396
- function fulfilled(value2) {
33396
+ function fulfilled(value) {
33397
33397
  try {
33398
- step(generator.next(value2));
33398
+ step(generator.next(value));
33399
33399
  } catch (e2) {
33400
33400
  reject(e2);
33401
33401
  }
33402
33402
  }
33403
- function rejected(value2) {
33403
+ function rejected(value) {
33404
33404
  try {
33405
- step(generator["throw"](value2));
33405
+ step(generator["throw"](value));
33406
33406
  } catch (e2) {
33407
33407
  reject(e2);
33408
33408
  }
@@ -33861,22 +33861,22 @@ var require_websockets = __commonJS((exports2) => {
33861
33861
  // node_modules/binance/lib/usdm-client.js
33862
33862
  var require_usdm_client = __commonJS((exports2) => {
33863
33863
  var __awaiter = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) {
33864
- function adopt(value2) {
33865
- return value2 instanceof P ? value2 : new P(function(resolve) {
33866
- resolve(value2);
33864
+ function adopt(value) {
33865
+ return value instanceof P ? value : new P(function(resolve) {
33866
+ resolve(value);
33867
33867
  });
33868
33868
  }
33869
33869
  return new (P || (P = Promise))(function(resolve, reject) {
33870
- function fulfilled(value2) {
33870
+ function fulfilled(value) {
33871
33871
  try {
33872
- step(generator.next(value2));
33872
+ step(generator.next(value));
33873
33873
  } catch (e2) {
33874
33874
  reject(e2);
33875
33875
  }
33876
33876
  }
33877
- function rejected(value2) {
33877
+ function rejected(value) {
33878
33878
  try {
33879
- step(generator["throw"](value2));
33879
+ step(generator["throw"](value));
33880
33880
  } catch (e2) {
33881
33881
  reject(e2);
33882
33882
  }
@@ -34791,35 +34791,35 @@ var require_permessage_deflate = __commonJS((exports2, module2) => {
34791
34791
  normalizeParams(configurations) {
34792
34792
  configurations.forEach((params) => {
34793
34793
  Object.keys(params).forEach((key) => {
34794
- let value2 = params[key];
34795
- if (value2.length > 1) {
34794
+ let value = params[key];
34795
+ if (value.length > 1) {
34796
34796
  throw new Error(`Parameter "${key}" must have only a single value`);
34797
34797
  }
34798
- value2 = value2[0];
34798
+ value = value[0];
34799
34799
  if (key === "client_max_window_bits") {
34800
- if (value2 !== true) {
34801
- const num = +value2;
34800
+ if (value !== true) {
34801
+ const num = +value;
34802
34802
  if (!Number.isInteger(num) || num < 8 || num > 15) {
34803
- throw new TypeError(`Invalid value for parameter "${key}": ${value2}`);
34803
+ throw new TypeError(`Invalid value for parameter "${key}": ${value}`);
34804
34804
  }
34805
- value2 = num;
34805
+ value = num;
34806
34806
  } else if (!this._isServer) {
34807
- throw new TypeError(`Invalid value for parameter "${key}": ${value2}`);
34807
+ throw new TypeError(`Invalid value for parameter "${key}": ${value}`);
34808
34808
  }
34809
34809
  } else if (key === "server_max_window_bits") {
34810
- const num = +value2;
34810
+ const num = +value;
34811
34811
  if (!Number.isInteger(num) || num < 8 || num > 15) {
34812
- throw new TypeError(`Invalid value for parameter "${key}": ${value2}`);
34812
+ throw new TypeError(`Invalid value for parameter "${key}": ${value}`);
34813
34813
  }
34814
- value2 = num;
34814
+ value = num;
34815
34815
  } else if (key === "client_no_context_takeover" || key === "server_no_context_takeover") {
34816
- if (value2 !== true) {
34817
- throw new TypeError(`Invalid value for parameter "${key}": ${value2}`);
34816
+ if (value !== true) {
34817
+ throw new TypeError(`Invalid value for parameter "${key}": ${value}`);
34818
34818
  }
34819
34819
  } else {
34820
34820
  throw new Error(`Unknown parameter "${key}"`);
34821
34821
  }
34822
- params[key] = value2;
34822
+ params[key] = value;
34823
34823
  });
34824
34824
  });
34825
34825
  return configurations;
@@ -35102,8 +35102,8 @@ var require_validation = __commonJS((exports2, module2) => {
35102
35102
  }
35103
35103
  return true;
35104
35104
  }
35105
- function isBlob(value2) {
35106
- 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");
35105
+ function isBlob(value) {
35106
+ 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");
35107
35107
  }
35108
35108
  module2.exports = {
35109
35109
  isBlob,
@@ -36121,12 +36121,12 @@ var require_extension = __commonJS((exports2, module2) => {
36121
36121
  }
36122
36122
  if (end === -1)
36123
36123
  end = i2;
36124
- let value2 = header.slice(start, end);
36124
+ let value = header.slice(start, end);
36125
36125
  if (mustUnescape) {
36126
- value2 = value2.replace(/\\/g, "");
36126
+ value = value.replace(/\\/g, "");
36127
36127
  mustUnescape = false;
36128
36128
  }
36129
- push(params, paramName, value2);
36129
+ push(params, paramName, value);
36130
36130
  if (code === 44) {
36131
36131
  push(offers, extensionName, params);
36132
36132
  params = Object.create(null);
@@ -36649,8 +36649,8 @@ var require_websocket = __commonJS((exports2, module2) => {
36649
36649
  const headers = options && options.headers;
36650
36650
  options = { ...options, headers: {} };
36651
36651
  if (headers) {
36652
- for (const [key2, value2] of Object.entries(headers)) {
36653
- options.headers[key2.toLowerCase()] = value2;
36652
+ for (const [key2, value] of Object.entries(headers)) {
36653
+ options.headers[key2.toLowerCase()] = value;
36654
36654
  }
36655
36655
  }
36656
36656
  } else if (websocket.listenerCount("redirect") === 0) {
@@ -37312,10 +37312,10 @@ var require_websocket_server = __commonJS((exports2, module2) => {
37312
37312
  }
37313
37313
  if (extensions[PerMessageDeflate.extensionName]) {
37314
37314
  const params = extensions[PerMessageDeflate.extensionName].params;
37315
- const value2 = extension.format({
37315
+ const value = extension.format({
37316
37316
  [PerMessageDeflate.extensionName]: [params]
37317
37317
  });
37318
- headers.push(`Sec-WebSocket-Extensions: ${value2}`);
37318
+ headers.push(`Sec-WebSocket-Extensions: ${value}`);
37319
37319
  ws._extensions = extensions;
37320
37320
  }
37321
37321
  this.emit("headers", headers, req);
@@ -37447,22 +37447,22 @@ var require_websocket_client = __commonJS((exports2) => {
37447
37447
  return result;
37448
37448
  };
37449
37449
  var __awaiter = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) {
37450
- function adopt(value2) {
37451
- return value2 instanceof P ? value2 : new P(function(resolve) {
37452
- resolve(value2);
37450
+ function adopt(value) {
37451
+ return value instanceof P ? value : new P(function(resolve) {
37452
+ resolve(value);
37453
37453
  });
37454
37454
  }
37455
37455
  return new (P || (P = Promise))(function(resolve, reject) {
37456
- function fulfilled(value2) {
37456
+ function fulfilled(value) {
37457
37457
  try {
37458
- step(generator.next(value2));
37458
+ step(generator.next(value));
37459
37459
  } catch (e2) {
37460
37460
  reject(e2);
37461
37461
  }
37462
37462
  }
37463
- function rejected(value2) {
37463
+ function rejected(value) {
37464
37464
  try {
37465
- step(generator["throw"](value2));
37465
+ step(generator["throw"](value));
37466
37466
  } catch (e2) {
37467
37467
  reject(e2);
37468
37468
  }
@@ -37954,10 +37954,10 @@ var require_websocket_client = __commonJS((exports2) => {
37954
37954
  });
37955
37955
  this.tryWsSend(wsKey, wsMessage);
37956
37956
  }
37957
- requestSetProperty(wsKey, property, value2, requestId) {
37957
+ requestSetProperty(wsKey, property, value, requestId) {
37958
37958
  const wsMessage = JSON.stringify({
37959
37959
  method: "SET_PROPERTY",
37960
- params: [property, value2],
37960
+ params: [property, value],
37961
37961
  id: requestId
37962
37962
  });
37963
37963
  this.tryWsSend(wsKey, wsMessage);
@@ -52608,267 +52608,8 @@ __export(exports_exchange_account, {
52608
52608
  ExchangeAccount: () => ExchangeAccount
52609
52609
  });
52610
52610
 
52611
- // src/helpers/pnl.ts
52612
- function determine_position_size(entry, stop, budget) {
52613
- let stop_percent = Math.abs(entry - stop) / entry;
52614
- let size = budget / stop_percent / entry;
52615
- return size;
52616
- }
52617
- function determine_risk(entry, stop, quantity) {
52618
- let stop_percent = Math.abs(entry - stop) / entry;
52619
- let risk = quantity * stop_percent * entry;
52620
- return risk;
52621
- }
52622
- function determine_close_price(entry, pnl, quantity, kind, single = false, leverage = 1) {
52623
- const dollar_value = entry / leverage;
52624
- const position = dollar_value * quantity;
52625
- if (position) {
52626
- let percent = pnl / position;
52627
- let difference = position * percent / quantity;
52628
- let result;
52629
- if (kind === "long") {
52630
- result = difference + entry;
52631
- } else {
52632
- result = entry - difference;
52633
- }
52634
- if (single) {
52635
- return result;
52636
- }
52637
- return result;
52638
- }
52639
- return 0;
52640
- }
52641
- function determine_amount_to_sell(entry, quantity, sell_price, pnl, kind, places = "%.3f") {
52642
- const _pnl = determine_pnl(entry, sell_price, quantity, kind);
52643
- const ratio = pnl / to_f(Math.abs(_pnl), places);
52644
- quantity = quantity * ratio;
52645
- return to_f(quantity, places);
52646
- }
52647
- function determine_pnl(entry, close_price, quantity, kind, contract_size, places = "%.2f") {
52648
- if (contract_size) {
52649
- const direction = kind === "long" ? 1 : -1;
52650
- return quantity * contract_size * direction * (1 / entry - 1 / close_price);
52651
- }
52652
- let difference = entry - close_price;
52653
- if (kind === "long") {
52654
- difference = close_price - entry;
52655
- }
52656
- return to_f(difference * quantity, places);
52657
- }
52658
- function position(entry, quantity, kind, leverage = 1) {
52659
- const direction = { long: 1, short: -1 };
52660
- return parseFloat((direction[kind] * quantity * (entry / leverage)).toFixed(3));
52661
- }
52662
- function to_f(value, places) {
52663
- if (value) {
52664
- let pp = parseInt(places.replace("%.", "").replace("f", ""));
52665
- return parseFloat(value.toFixed(pp));
52666
- }
52667
- return value;
52668
- }
52669
- var value = {
52670
- determine_risk,
52671
- determine_position_size,
52672
- determine_close_price,
52673
- determine_pnl,
52674
- position,
52675
- determine_amount_to_sell,
52676
- to_f
52677
- };
52678
- var pnl_default = value;
52679
-
52680
- // src/helpers/trade_utils.ts
52681
- function to_f2(value2, places = "%.1f") {
52682
- let v = typeof value2 === "string" ? parseFloat(value2) : value2;
52683
- const formattedValue = places.replace("%.", "").replace("f", "");
52684
- return parseFloat(v.toFixed(parseInt(formattedValue)));
52685
- }
52686
- function determine_amount_to_sell2(entry, quantity, sell_price, pnl, kind, places = "%.3f") {
52687
- const _pnl = determine_pnl2(entry, sell_price, quantity, kind);
52688
- const ratio = pnl / to_f2(Math.abs(_pnl), places);
52689
- quantity = quantity * ratio;
52690
- return to_f2(quantity, places);
52691
- }
52692
- function determine_position_size2({
52693
- entry,
52694
- stop,
52695
- budget,
52696
- percent,
52697
- min_size,
52698
- notional_value,
52699
- as_coin = true,
52700
- places = "%.3f"
52701
- }) {
52702
- let stop_percent = stop ? Math.abs(entry - stop) / entry : percent;
52703
- if (stop_percent && budget) {
52704
- let size = budget / stop_percent;
52705
- let notion_value = size * entry;
52706
- if (notional_value && notional_value > notion_value) {
52707
- size = notional_value / entry;
52708
- }
52709
- if (as_coin) {
52710
- size = size / entry;
52711
- if (min_size && min_size === 1) {
52712
- return to_f2(Math.round(size), places);
52713
- }
52714
- }
52715
- return to_f2(size, places);
52716
- }
52717
- return;
52718
- }
52719
- function determine_average_entry_and_size(orders, places = "%.3f", price_places = "%.1f") {
52720
- const sum_values = orders.reduce((sum, order) => sum + order.price * order.quantity, 0);
52721
- const total_quantity = orders.reduce((sum, order) => sum + order.quantity, 0);
52722
- const avg_price = total_quantity ? to_f2(sum_values / total_quantity, price_places) : 0;
52723
- return {
52724
- entry: avg_price,
52725
- price: avg_price,
52726
- quantity: to_f2(total_quantity, places)
52727
- };
52728
- }
52729
- var createArray = (start, stop, step) => {
52730
- const result = [];
52731
- let current = start;
52732
- while (current <= stop) {
52733
- result.push(current);
52734
- current += step;
52735
- }
52736
- return result;
52737
- };
52738
- var groupIntoPairsWithSumLessThan = (arr, targetSum, key = "quantity", firstSize = 0) => {
52739
- if (firstSize) {
52740
- const totalSize = arr.reduce((sum, order) => sum + order[key], 0);
52741
- const remainingSize = totalSize - firstSize;
52742
- let newSum = 0;
52743
- let newArray = [];
52744
- let lastIndex = 0;
52745
- for (let i2 = 0;i2 < arr.length; i2++) {
52746
- if (newSum < remainingSize) {
52747
- newSum += arr[i2][key];
52748
- newArray.push(arr[i2]);
52749
- lastIndex = i2;
52750
- }
52751
- }
52752
- const lastGroup = arr.slice(lastIndex + 1);
52753
- const previousPair = groupInPairs(newArray, key, targetSum);
52754
- if (lastGroup.length > 0) {
52755
- previousPair.push(lastGroup);
52756
- }
52757
- return previousPair;
52758
- }
52759
- return groupInPairs(arr, key, targetSum);
52760
- };
52761
- function groupInPairs(_arr, key, targetSum) {
52762
- const result = [];
52763
- let currentSum = 0;
52764
- let currentGroup = [];
52765
- for (let i2 = 0;i2 < _arr.length; i2++) {
52766
- currentSum += _arr[i2][key];
52767
- currentGroup.push(_arr[i2]);
52768
- if (currentSum >= targetSum) {
52769
- result.push(currentGroup);
52770
- currentGroup = [];
52771
- currentSum = 0;
52772
- }
52773
- }
52774
- return result;
52775
- }
52776
- var computeTotalAverageForEachTrade = (trades, config2) => {
52777
- let _take_profit = config2.take_profit;
52778
- let kind = config2.kind;
52779
- let entryToUse = kind === "short" ? Math.min(config2.entry, config2.stop) : Math.max(config2.entry, config2.stop);
52780
- let _currentEntry = config2.currentEntry || entryToUse;
52781
- let less = trades.filter((p) => kind === "long" ? p.entry <= _currentEntry : p.entry >= _currentEntry);
52782
- let rrr = trades.map((r2, i2) => {
52783
- let considered = [];
52784
- if (kind === "long") {
52785
- considered = trades.filter((p) => p.entry > _currentEntry);
52786
- } else {
52787
- considered = trades.filter((p) => p.entry < _currentEntry);
52788
- }
52789
- const x_pnl = 0;
52790
- const remaining = less.filter((o) => {
52791
- if (kind === "long") {
52792
- return o.entry >= r2.entry;
52793
- }
52794
- return o.entry <= r2.entry;
52795
- });
52796
- if (remaining.length === 0) {
52797
- return { ...r2, pnl: x_pnl };
52798
- }
52799
- const start = kind === "long" ? Math.max(...remaining.map((o) => o.entry)) : Math.min(...remaining.map((o) => o.entry));
52800
- considered = considered.map((o) => ({ ...o, entry: start }));
52801
- considered = considered.concat(remaining);
52802
- let avg_entry = determine_average_entry_and_size([
52803
- ...considered.map((o) => ({
52804
- price: o.entry,
52805
- quantity: o.quantity
52806
- })),
52807
- {
52808
- price: _currentEntry,
52809
- quantity: config2.currentQty || 0
52810
- }
52811
- ], config2.decimal_places, config2.price_places);
52812
- let _pnl = r2.pnl;
52813
- let sell_price = r2.sell_price;
52814
- let entry_pnl = r2.pnl;
52815
- if (_take_profit) {
52816
- _pnl = pnl_default.determine_pnl(avg_entry.price, _take_profit, avg_entry.quantity, kind);
52817
- sell_price = _take_profit;
52818
- entry_pnl = pnl_default.determine_pnl(r2.entry, _take_profit, avg_entry.quantity, kind);
52819
- }
52820
- const loss = pnl_default.determine_pnl(avg_entry.price, r2.stop, avg_entry.quantity, kind);
52821
- let new_stop = r2.new_stop;
52822
- const entry_loss = pnl_default.determine_pnl(r2.entry, new_stop, avg_entry.quantity, kind);
52823
- let min_profit = 0;
52824
- let min_entry_profit = 0;
52825
- if (config2.min_profit) {
52826
- min_profit = pnl_default.determine_close_price(avg_entry.price, config2.min_profit, avg_entry.quantity, kind);
52827
- min_entry_profit = pnl_default.determine_close_price(r2.entry, config2.min_profit, avg_entry.quantity, kind);
52828
- }
52829
- let x_fee = r2.fee;
52830
- if (config2.fee) {
52831
- x_fee = config2.fee * r2.stop * avg_entry.quantity;
52832
- }
52833
- let tp_close = pnl_default.determine_close_price(r2.entry, Math.abs(entry_loss) * (config2.rr || 1) + x_fee, avg_entry.quantity, kind);
52834
- return {
52835
- ...r2,
52836
- x_fee: to_f2(x_fee, "%.2f"),
52837
- avg_entry: avg_entry.price,
52838
- avg_size: avg_entry.quantity,
52839
- entry_pnl: to_f2(entry_pnl, "%.2f"),
52840
- entry_loss: to_f2(entry_loss, "%.2f"),
52841
- min_entry_pnl: to_f2(min_entry_profit, "%.2f"),
52842
- pnl: _pnl,
52843
- neg_pnl: to_f2(loss, "%.2f"),
52844
- sell_price,
52845
- close_p: to_f2(tp_close, "%.2f"),
52846
- min_pnl: to_f2(min_profit, "%.2f"),
52847
- new_stop
52848
- };
52849
- });
52850
- return rrr;
52851
- };
52852
- function createGapPairs(arr, gap, item) {
52853
- if (arr.length === 0) {
52854
- return [];
52855
- }
52856
- const result = [];
52857
- const firstElement = arr[0];
52858
- for (let i2 = arr.length - 1;i2 >= 0; i2--) {
52859
- const current = arr[i2];
52860
- const gapIndex = i2 - gap;
52861
- const pairedElement = gapIndex < 0 ? firstElement : arr[gapIndex];
52862
- if (current !== pairedElement) {
52863
- result.push([current, pairedElement]);
52864
- }
52865
- }
52866
- if (item) {
52867
- let r2 = result.find((o) => o[0] === item);
52868
- return r2 ? [r2] : [];
52869
- }
52870
- return result;
52871
- }
52611
+ // src/exchanges/binance/index.ts
52612
+ var import_binance = __toESM(require_lib2());
52872
52613
 
52873
52614
  // src/helpers/optimizations.ts
52874
52615
  function calculateTheoreticalKelly({
@@ -52905,7 +52646,7 @@ function calculateTheoreticalKelly({
52905
52646
  kelly_fraction *= vol_adjustment;
52906
52647
  }
52907
52648
  kelly_fraction = Math.max(0.005, Math.min(kelly_fraction, 0.5));
52908
- return to_f2(kelly_fraction, "%.4f");
52649
+ return to_f(kelly_fraction, "%.4f");
52909
52650
  }
52910
52651
  function calculateZoneProbabilities({
52911
52652
  current_entry,
@@ -53014,7 +52755,7 @@ function calculateTheoreticalKellyFixed({
53014
52755
  kelly_fraction *= vol_adjustment;
53015
52756
  }
53016
52757
  kelly_fraction = Math.max(0.005, Math.min(kelly_fraction, 0.5));
53017
- return to_f2(kelly_fraction, "%.4f");
52758
+ return to_f(kelly_fraction, "%.4f");
53018
52759
  }
53019
52760
  function calculatePositionBasedKelly({
53020
52761
  current_entry,
@@ -53048,11 +52789,11 @@ function calculatePositionBasedKelly({
53048
52789
  const base_kelly = 0.02;
53049
52790
  const max_kelly = 0.2;
53050
52791
  const kelly_fraction = base_kelly + adjusted_score * (max_kelly - base_kelly);
53051
- return to_f2(kelly_fraction, "%.4f");
52792
+ return to_f(kelly_fraction, "%.4f");
53052
52793
  }
53053
52794
 
53054
52795
  // src/helpers/trade_signal.ts
53055
- function determine_close_price2({
52796
+ function determine_close_price({
53056
52797
  entry,
53057
52798
  pnl,
53058
52799
  quantity,
@@ -53060,16 +52801,16 @@ function determine_close_price2({
53060
52801
  kind = "long"
53061
52802
  }) {
53062
52803
  const dollar_value = entry / leverage;
53063
- const position2 = dollar_value * quantity;
53064
- if (position2) {
53065
- const percent = pnl / position2;
53066
- const difference = position2 * percent / quantity;
52804
+ const position = dollar_value * quantity;
52805
+ if (position) {
52806
+ const percent = pnl / position;
52807
+ const difference = position * percent / quantity;
53067
52808
  const result = kind === "long" ? difference + entry : entry - difference;
53068
52809
  return result;
53069
52810
  }
53070
52811
  return 0;
53071
52812
  }
53072
- function determine_pnl2(entry, close_price, quantity, kind = "long", contract_size) {
52813
+ function determine_pnl(entry, close_price, quantity, kind = "long", contract_size) {
53073
52814
  if (contract_size) {
53074
52815
  const direction = kind === "long" ? 1 : -1;
53075
52816
  return quantity * contract_size * direction * (1 / entry - 1 / close_price);
@@ -53088,7 +52829,7 @@ function* _get_zones({
53088
52829
  let focus_low = last * Math.pow(1 + percent_change, -1);
53089
52830
  if (focus_high > current_price) {
53090
52831
  while (focus_high > current_price) {
53091
- yield to_f2(last, places);
52832
+ yield to_f(last, places);
53092
52833
  focus_high = last;
53093
52834
  last = focus_high * Math.pow(1 + percent_change, -1);
53094
52835
  focus_low = last * Math.pow(1 + percent_change, -1);
@@ -53096,14 +52837,14 @@ function* _get_zones({
53096
52837
  } else {
53097
52838
  if (focus_high <= current_price) {
53098
52839
  while (focus_high <= current_price) {
53099
- yield to_f2(focus_high, places);
52840
+ yield to_f(focus_high, places);
53100
52841
  focus_low = focus_high;
53101
52842
  last = focus_low * (1 + percent_change);
53102
52843
  focus_high = last * (1 + percent_change);
53103
52844
  }
53104
52845
  } else {
53105
52846
  while (focus_low <= current_price) {
53106
- yield to_f2(focus_high, places);
52847
+ yield to_f(focus_high, places);
53107
52848
  focus_low = focus_high;
53108
52849
  last = focus_low * (1 + percent_change);
53109
52850
  focus_high = last * (1 + percent_change);
@@ -53382,7 +53123,7 @@ class Signal {
53382
53123
  } else {
53383
53124
  i2["risk_sell"] = Math.min(...potentials.slice(0, max_index));
53384
53125
  }
53385
- i2["pnl"] = this.to_df(determine_pnl2(i2["entry"], i2["risk_sell"], i2["quantity"], kind));
53126
+ i2["pnl"] = this.to_df(determine_pnl(i2["entry"], i2["risk_sell"], i2["quantity"], kind));
53386
53127
  }
53387
53128
  }
53388
53129
  }
@@ -53446,13 +53187,13 @@ class Signal {
53446
53187
  let remaining_zones = margin_zones.filter((x) => JSON.stringify(x) != JSON.stringify(margin_range));
53447
53188
  if (margin_range) {
53448
53189
  const difference = Math.abs(margin_range[0] - margin_range[1]);
53449
- const spread = to_f2(difference / this.risk_reward, this.price_places);
53190
+ const spread = to_f(difference / this.risk_reward, this.price_places);
53450
53191
  let entries;
53451
53192
  const percent_change = this.percent_change / this.risk_reward;
53452
53193
  if (kind === "long") {
53453
- entries = Array.from({ length: Math.floor(this.risk_reward) + 1 }, (_, x) => to_f2(margin_range[1] - spread * x, this.price_places));
53194
+ entries = Array.from({ length: Math.floor(this.risk_reward) + 1 }, (_, x) => to_f(margin_range[1] - spread * x, this.price_places));
53454
53195
  } else {
53455
- 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));
53196
+ 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));
53456
53197
  }
53457
53198
  if (Math.min(...entries) < this.to_f(current_price) && this.to_f(current_price) < Math.max(...entries)) {
53458
53199
  return entries.sort((a, b) => a - b);
@@ -53464,14 +53205,14 @@ class Signal {
53464
53205
  if (new_range) {
53465
53206
  while (entries2.length < this.risk_reward + 1) {
53466
53207
  if (kind === "long") {
53467
- let value2 = this.to_f(new_range[1] - spread * x);
53468
- if (value2 <= current_price) {
53469
- entries2.push(value2);
53208
+ let value = this.to_f(new_range[1] - spread * x);
53209
+ if (value <= current_price) {
53210
+ entries2.push(value);
53470
53211
  }
53471
53212
  } else {
53472
- let value2 = this.to_f(new_range[1] * Math.pow(1 + percent_change, x));
53473
- if (value2 >= current_price) {
53474
- entries2.push(value2);
53213
+ let value = this.to_f(new_range[1] * Math.pow(1 + percent_change, x));
53214
+ if (value >= current_price) {
53215
+ entries2.push(value);
53475
53216
  }
53476
53217
  }
53477
53218
  x += 1;
@@ -53485,14 +53226,14 @@ class Signal {
53485
53226
  let x = 0;
53486
53227
  while (entries2.length < this.risk_reward + 1) {
53487
53228
  if (kind === "long") {
53488
- let value2 = this.to_f(next_focus - spread * x);
53489
- if (value2 <= this.to_f(current_price)) {
53490
- entries2.push(value2);
53229
+ let value = this.to_f(next_focus - spread * x);
53230
+ if (value <= this.to_f(current_price)) {
53231
+ entries2.push(value);
53491
53232
  }
53492
53233
  } else {
53493
- let value2 = this.to_f(next_focus * Math.pow(1 + percent_change, x));
53494
- if (value2 >= this.to_f(current_price)) {
53495
- entries2.push(value2);
53234
+ let value = this.to_f(next_focus * Math.pow(1 + percent_change, x));
53235
+ if (value >= this.to_f(current_price)) {
53236
+ entries2.push(value);
53496
53237
  }
53497
53238
  }
53498
53239
  x += 1;
@@ -53503,8 +53244,8 @@ class Signal {
53503
53244
  }
53504
53245
  return [];
53505
53246
  }
53506
- to_f(value2, places) {
53507
- return to_f2(value2, places || this.price_places);
53247
+ to_f(value, places) {
53248
+ return to_f(value, places || this.price_places);
53508
53249
  }
53509
53250
  get_margin_zones({
53510
53251
  current_price,
@@ -53722,7 +53463,7 @@ class Signal {
53722
53463
  }) {
53723
53464
  const considered = arr.map((x, i2) => i2).filter((i2) => i2 > index);
53724
53465
  const with_quantity = considered.map((x) => {
53725
- const q = determine_position_size2({
53466
+ const q = determine_position_size({
53726
53467
  entry: arr[x],
53727
53468
  stop: arr[x - 1],
53728
53469
  budget: risk,
@@ -53756,7 +53497,7 @@ class Signal {
53756
53497
  const incurred_fees = fees.reduce((a, b) => a + b, 0) + previous_risks.reduce((a, b) => a + b, 0);
53757
53498
  if (index === 0) {
53758
53499
  }
53759
- let quantity = determine_position_size2({
53500
+ let quantity = determine_position_size({
53760
53501
  entry,
53761
53502
  stop,
53762
53503
  budget: risk,
@@ -53768,7 +53509,7 @@ class Signal {
53768
53509
  }
53769
53510
  if (this.increase_size) {
53770
53511
  quantity = quantity * multiplier;
53771
- const new_risk = determine_pnl2(entry, stop, quantity, kind);
53512
+ const new_risk = determine_pnl(entry, stop, quantity, kind);
53772
53513
  risk = Math.abs(new_risk);
53773
53514
  }
53774
53515
  const fee = this.to_df(this.fee * quantity * entry);
@@ -53777,12 +53518,12 @@ class Signal {
53777
53518
  if (this.minimum_pnl) {
53778
53519
  pnl = this.minimum_pnl + fee;
53779
53520
  }
53780
- let sell_price = determine_close_price2({ entry, pnl, quantity, kind });
53521
+ let sell_price = determine_close_price({ entry, pnl, quantity, kind });
53781
53522
  if (take_profit && !this.minimum_pnl) {
53782
53523
  sell_price = take_profit;
53783
- pnl = this.to_df(determine_pnl2(entry, sell_price, quantity, kind));
53524
+ pnl = this.to_df(determine_pnl(entry, sell_price, quantity, kind));
53784
53525
  pnl = pnl + fee;
53785
- sell_price = determine_close_price2({ entry, pnl, quantity, kind });
53526
+ sell_price = determine_close_price({ entry, pnl, quantity, kind });
53786
53527
  }
53787
53528
  let risk_sell = sell_price;
53788
53529
  return {
@@ -53800,10 +53541,271 @@ class Signal {
53800
53541
  };
53801
53542
  }
53802
53543
  to_df(currentPrice, places = "%.3f") {
53803
- return to_f2(currentPrice, places);
53544
+ return to_f(currentPrice, places);
53545
+ }
53546
+ }
53547
+
53548
+ // src/helpers/pnl.ts
53549
+ function determine_position_size2(entry, stop, budget) {
53550
+ let stop_percent = Math.abs(entry - stop) / entry;
53551
+ let size = budget / stop_percent / entry;
53552
+ return size;
53553
+ }
53554
+ function determine_risk(entry, stop, quantity) {
53555
+ let stop_percent = Math.abs(entry - stop) / entry;
53556
+ let risk = quantity * stop_percent * entry;
53557
+ return risk;
53558
+ }
53559
+ function determine_close_price2(entry, pnl, quantity, kind, single = false, leverage = 1) {
53560
+ const dollar_value = entry / leverage;
53561
+ const position = dollar_value * quantity;
53562
+ if (position) {
53563
+ let percent = pnl / position;
53564
+ let difference = position * percent / quantity;
53565
+ let result;
53566
+ if (kind === "long") {
53567
+ result = difference + entry;
53568
+ } else {
53569
+ result = entry - difference;
53570
+ }
53571
+ if (single) {
53572
+ return result;
53573
+ }
53574
+ return result;
53575
+ }
53576
+ return 0;
53577
+ }
53578
+ function determine_amount_to_sell(entry, quantity, sell_price, pnl, kind, places = "%.3f") {
53579
+ const _pnl = determine_pnl2(entry, sell_price, quantity, kind);
53580
+ const ratio = pnl / to_f2(Math.abs(_pnl), places);
53581
+ quantity = quantity * ratio;
53582
+ return to_f2(quantity, places);
53583
+ }
53584
+ function determine_pnl2(entry, close_price, quantity, kind, contract_size, places = "%.2f") {
53585
+ if (contract_size) {
53586
+ const direction = kind === "long" ? 1 : -1;
53587
+ return quantity * contract_size * direction * (1 / entry - 1 / close_price);
53588
+ }
53589
+ let difference = entry - close_price;
53590
+ if (kind === "long") {
53591
+ difference = close_price - entry;
53592
+ }
53593
+ return to_f2(difference * quantity, places);
53594
+ }
53595
+ function position(entry, quantity, kind, leverage = 1) {
53596
+ const direction = { long: 1, short: -1 };
53597
+ return parseFloat((direction[kind] * quantity * (entry / leverage)).toFixed(3));
53598
+ }
53599
+ function to_f2(value, places) {
53600
+ if (value) {
53601
+ let pp = parseInt(places.replace("%.", "").replace("f", ""));
53602
+ return parseFloat(value.toFixed(pp));
53804
53603
  }
53604
+ return value;
53805
53605
  }
53606
+ var value = {
53607
+ determine_risk,
53608
+ determine_position_size: determine_position_size2,
53609
+ determine_close_price: determine_close_price2,
53610
+ determine_pnl: determine_pnl2,
53611
+ position,
53612
+ determine_amount_to_sell,
53613
+ to_f: to_f2
53614
+ };
53615
+ var pnl_default = value;
53806
53616
 
53617
+ // src/helpers/trade_utils.ts
53618
+ function to_f(value2, places = "%.1f") {
53619
+ let v = typeof value2 === "string" ? parseFloat(value2) : value2;
53620
+ const formattedValue = places.replace("%.", "").replace("f", "");
53621
+ return parseFloat(v.toFixed(parseInt(formattedValue)));
53622
+ }
53623
+ function determine_amount_to_sell2(entry, quantity, sell_price, pnl, kind, places = "%.3f") {
53624
+ const _pnl = determine_pnl(entry, sell_price, quantity, kind);
53625
+ const ratio = pnl / to_f(Math.abs(_pnl), places);
53626
+ quantity = quantity * ratio;
53627
+ return to_f(quantity, places);
53628
+ }
53629
+ function determine_position_size({
53630
+ entry,
53631
+ stop,
53632
+ budget,
53633
+ percent,
53634
+ min_size,
53635
+ notional_value,
53636
+ as_coin = true,
53637
+ places = "%.3f"
53638
+ }) {
53639
+ let stop_percent = stop ? Math.abs(entry - stop) / entry : percent;
53640
+ if (stop_percent && budget) {
53641
+ let size = budget / stop_percent;
53642
+ let notion_value = size * entry;
53643
+ if (notional_value && notional_value > notion_value) {
53644
+ size = notional_value / entry;
53645
+ }
53646
+ if (as_coin) {
53647
+ size = size / entry;
53648
+ if (min_size && min_size === 1) {
53649
+ return to_f(Math.round(size), places);
53650
+ }
53651
+ }
53652
+ return to_f(size, places);
53653
+ }
53654
+ return;
53655
+ }
53656
+ function determine_average_entry_and_size(orders, places = "%.3f", price_places = "%.1f") {
53657
+ const sum_values = orders.reduce((sum, order) => sum + order.price * order.quantity, 0);
53658
+ const total_quantity = orders.reduce((sum, order) => sum + order.quantity, 0);
53659
+ const avg_price = total_quantity ? to_f(sum_values / total_quantity, price_places) : 0;
53660
+ return {
53661
+ entry: avg_price,
53662
+ price: avg_price,
53663
+ quantity: to_f(total_quantity, places)
53664
+ };
53665
+ }
53666
+ var createArray = (start, stop, step) => {
53667
+ const result = [];
53668
+ let current = start;
53669
+ while (current <= stop) {
53670
+ result.push(current);
53671
+ current += step;
53672
+ }
53673
+ return result;
53674
+ };
53675
+ var groupIntoPairsWithSumLessThan = (arr, targetSum, key = "quantity", firstSize = 0) => {
53676
+ if (firstSize) {
53677
+ const totalSize = arr.reduce((sum, order) => sum + order[key], 0);
53678
+ const remainingSize = totalSize - firstSize;
53679
+ let newSum = 0;
53680
+ let newArray = [];
53681
+ let lastIndex = 0;
53682
+ for (let i2 = 0;i2 < arr.length; i2++) {
53683
+ if (newSum < remainingSize) {
53684
+ newSum += arr[i2][key];
53685
+ newArray.push(arr[i2]);
53686
+ lastIndex = i2;
53687
+ }
53688
+ }
53689
+ const lastGroup = arr.slice(lastIndex + 1);
53690
+ const previousPair = groupInPairs(newArray, key, targetSum);
53691
+ if (lastGroup.length > 0) {
53692
+ previousPair.push(lastGroup);
53693
+ }
53694
+ return previousPair;
53695
+ }
53696
+ return groupInPairs(arr, key, targetSum);
53697
+ };
53698
+ function groupInPairs(_arr, key, targetSum) {
53699
+ const result = [];
53700
+ let currentSum = 0;
53701
+ let currentGroup = [];
53702
+ for (let i2 = 0;i2 < _arr.length; i2++) {
53703
+ currentSum += _arr[i2][key];
53704
+ currentGroup.push(_arr[i2]);
53705
+ if (currentSum >= targetSum) {
53706
+ result.push(currentGroup);
53707
+ currentGroup = [];
53708
+ currentSum = 0;
53709
+ }
53710
+ }
53711
+ return result;
53712
+ }
53713
+ var computeTotalAverageForEachTrade = (trades, config2) => {
53714
+ let _take_profit = config2.take_profit;
53715
+ let kind = config2.kind;
53716
+ let entryToUse = kind === "short" ? Math.min(config2.entry, config2.stop) : Math.max(config2.entry, config2.stop);
53717
+ let _currentEntry = config2.currentEntry || entryToUse;
53718
+ let less = trades.filter((p) => kind === "long" ? p.entry <= _currentEntry : p.entry >= _currentEntry);
53719
+ let rrr = trades.map((r2, i2) => {
53720
+ let considered = [];
53721
+ if (kind === "long") {
53722
+ considered = trades.filter((p) => p.entry > _currentEntry);
53723
+ } else {
53724
+ considered = trades.filter((p) => p.entry < _currentEntry);
53725
+ }
53726
+ const x_pnl = 0;
53727
+ const remaining = less.filter((o) => {
53728
+ if (kind === "long") {
53729
+ return o.entry >= r2.entry;
53730
+ }
53731
+ return o.entry <= r2.entry;
53732
+ });
53733
+ if (remaining.length === 0) {
53734
+ return { ...r2, pnl: x_pnl };
53735
+ }
53736
+ const start = kind === "long" ? Math.max(...remaining.map((o) => o.entry)) : Math.min(...remaining.map((o) => o.entry));
53737
+ considered = considered.map((o) => ({ ...o, entry: start }));
53738
+ considered = considered.concat(remaining);
53739
+ let avg_entry = determine_average_entry_and_size([
53740
+ ...considered.map((o) => ({
53741
+ price: o.entry,
53742
+ quantity: o.quantity
53743
+ })),
53744
+ {
53745
+ price: _currentEntry,
53746
+ quantity: config2.currentQty || 0
53747
+ }
53748
+ ], config2.decimal_places, config2.price_places);
53749
+ let _pnl = r2.pnl;
53750
+ let sell_price = r2.sell_price;
53751
+ let entry_pnl = r2.pnl;
53752
+ if (_take_profit) {
53753
+ _pnl = pnl_default.determine_pnl(avg_entry.price, _take_profit, avg_entry.quantity, kind);
53754
+ sell_price = _take_profit;
53755
+ entry_pnl = pnl_default.determine_pnl(r2.entry, _take_profit, avg_entry.quantity, kind);
53756
+ }
53757
+ const loss = pnl_default.determine_pnl(avg_entry.price, r2.stop, avg_entry.quantity, kind);
53758
+ let new_stop = r2.new_stop;
53759
+ const entry_loss = pnl_default.determine_pnl(r2.entry, new_stop, avg_entry.quantity, kind);
53760
+ let min_profit = 0;
53761
+ let min_entry_profit = 0;
53762
+ if (config2.min_profit) {
53763
+ min_profit = pnl_default.determine_close_price(avg_entry.price, config2.min_profit, avg_entry.quantity, kind);
53764
+ min_entry_profit = pnl_default.determine_close_price(r2.entry, config2.min_profit, avg_entry.quantity, kind);
53765
+ }
53766
+ let x_fee = r2.fee;
53767
+ if (config2.fee) {
53768
+ x_fee = config2.fee * r2.stop * avg_entry.quantity;
53769
+ }
53770
+ let tp_close = pnl_default.determine_close_price(r2.entry, Math.abs(entry_loss) * (config2.rr || 1) + x_fee, avg_entry.quantity, kind);
53771
+ return {
53772
+ ...r2,
53773
+ x_fee: to_f(x_fee, "%.2f"),
53774
+ avg_entry: avg_entry.price,
53775
+ avg_size: avg_entry.quantity,
53776
+ entry_pnl: to_f(entry_pnl, "%.2f"),
53777
+ entry_loss: to_f(entry_loss, "%.2f"),
53778
+ min_entry_pnl: to_f(min_entry_profit, "%.2f"),
53779
+ pnl: _pnl,
53780
+ neg_pnl: to_f(loss, "%.2f"),
53781
+ sell_price,
53782
+ close_p: to_f(tp_close, "%.2f"),
53783
+ min_pnl: to_f(min_profit, "%.2f"),
53784
+ new_stop
53785
+ };
53786
+ });
53787
+ return rrr;
53788
+ };
53789
+ function createGapPairs(arr, gap, item) {
53790
+ if (arr.length === 0) {
53791
+ return [];
53792
+ }
53793
+ const result = [];
53794
+ const firstElement = arr[0];
53795
+ for (let i2 = arr.length - 1;i2 >= 0; i2--) {
53796
+ const current = arr[i2];
53797
+ const gapIndex = i2 - gap;
53798
+ const pairedElement = gapIndex < 0 ? firstElement : arr[gapIndex];
53799
+ if (current !== pairedElement) {
53800
+ result.push([current, pairedElement]);
53801
+ }
53802
+ }
53803
+ if (item) {
53804
+ let r2 = result.find((o) => o[0] === item);
53805
+ return r2 ? [r2] : [];
53806
+ }
53807
+ return result;
53808
+ }
53807
53809
  // src/helpers/shared.ts
53808
53810
  function getMaxQuantity(x, app_config) {
53809
53811
  let max_quantity = app_config.max_quantity;
@@ -53925,8 +53927,8 @@ function get_app_config_and_max_size(config2, payload) {
53925
53927
  stop: payload.stop,
53926
53928
  risk_per_trade: config2.risk,
53927
53929
  risk_reward: config2.risk_reward || 199,
53928
- support: to_f2(config2.support, config2.price_places),
53929
- resistance: to_f2(config2.resistance, config2.price_places),
53930
+ support: to_f(config2.support, config2.price_places),
53931
+ resistance: to_f(config2.resistance, config2.price_places),
53930
53932
  focus: payload.entry,
53931
53933
  fee: 0,
53932
53934
  percent_change: config2.stop_percent / 100,
@@ -54145,8 +54147,8 @@ function getOptimumStopAndRisk(app_config, params) {
54145
54147
  }
54146
54148
  }
54147
54149
  return {
54148
- optimal_stop: to_f2(optimal_stop, app_config.price_places),
54149
- optimal_risk: to_f2(final_risk, app_config.price_places),
54150
+ optimal_stop: to_f(optimal_stop, app_config.price_places),
54151
+ optimal_risk: to_f(final_risk, app_config.price_places),
54150
54152
  avg_size: final_result?.[0]?.avg_size || 0,
54151
54153
  avg_entry: final_result?.[0]?.avg_entry || 0,
54152
54154
  result: final_result,
@@ -54194,7 +54196,7 @@ function determine_amount_to_buy(payload) {
54194
54196
  existingOrders
54195
54197
  } = payload;
54196
54198
  const totalQuantity = orders.reduce((sum, order) => sum + (order.quantity || 0), 0);
54197
- let runningTotal = to_f2(totalQuantity, decimal_places);
54199
+ let runningTotal = to_f(totalQuantity, decimal_places);
54198
54200
  let sortedOrders = [...orders].sort((a, b) => (a.entry || 0) - (b.entry || 0));
54199
54201
  if (kind === "short") {
54200
54202
  sortedOrders.reverse();
@@ -54206,7 +54208,7 @@ function determine_amount_to_buy(payload) {
54206
54208
  cumulative_quantity: runningTotal
54207
54209
  });
54208
54210
  runningTotal -= order.quantity;
54209
- runningTotal = to_f2(runningTotal, decimal_places);
54211
+ runningTotal = to_f(runningTotal, decimal_places);
54210
54212
  }
54211
54213
  let filteredOrders = withCumulative.filter((order) => (order.cumulative_quantity || 0) > position2?.quantity).map((order) => ({
54212
54214
  ...order,
@@ -54469,10 +54471,10 @@ function determineOptimumRisk(config2, payload, params) {
54469
54471
  };
54470
54472
  const final_result = buildAppConfig(config2, final_payload);
54471
54473
  return {
54472
- optimal_risk: to_f2(best_risk, "%.2f"),
54473
- achieved_neg_pnl: to_f2(best_neg_pnl, "%.2f"),
54474
- target_neg_pnl: to_f2(highest_risk, "%.2f"),
54475
- difference: to_f2(best_diff, "%.2f"),
54474
+ optimal_risk: to_f(best_risk, "%.2f"),
54475
+ achieved_neg_pnl: to_f(best_neg_pnl, "%.2f"),
54476
+ target_neg_pnl: to_f(highest_risk, "%.2f"),
54477
+ difference: to_f(best_diff, "%.2f"),
54476
54478
  iterations,
54477
54479
  converged: best_diff <= tolerance,
54478
54480
  last_value: final_result.last_value,
@@ -54537,9 +54539,9 @@ function computeProfitDetail(payload) {
54537
54539
  full_ratio = 1
54538
54540
  } = payload;
54539
54541
  let reward_factor = strategy?.reward_factor || 1;
54540
- const profit_percent = to_f2(pnl * 100 / (focus_position.avg_price * focus_position.avg_qty), "%.4f");
54542
+ const profit_percent = to_f(pnl * 100 / (focus_position.avg_price * focus_position.avg_qty), "%.4f");
54541
54543
  const diff = pnl / focus_position.quantity;
54542
- const sell_price = to_f2(focus_position.kind === "long" ? focus_position.entry + diff : focus_position.entry - diff, price_places);
54544
+ const sell_price = to_f(focus_position.kind === "long" ? focus_position.entry + diff : focus_position.entry - diff, price_places);
54543
54545
  let loss = 0;
54544
54546
  let full_loss = 0;
54545
54547
  let expected_loss = 0;
@@ -54548,23 +54550,23 @@ function computeProfitDetail(payload) {
54548
54550
  if (reduce_position) {
54549
54551
  loss = Math.abs(reduce_position.entry - sell_price) * reduce_position.quantity;
54550
54552
  const ratio = pnl / loss;
54551
- quantity = to_f2(reduce_position.quantity * ratio, decimal_places);
54552
- expected_loss = to_f2(Math.abs(reduce_position.entry - sell_price) * quantity, "%.2f");
54553
+ quantity = to_f(reduce_position.quantity * ratio, decimal_places);
54554
+ expected_loss = to_f(Math.abs(reduce_position.entry - sell_price) * quantity, "%.2f");
54553
54555
  full_loss = Math.abs(reduce_position.avg_price - sell_price) * reduce_position.avg_qty * full_ratio;
54554
54556
  }
54555
54557
  if (reverse_position) {
54556
54558
  expected_loss = Math.abs(reverse_position.avg_price - sell_price) * reverse_position.avg_qty;
54557
- new_pnl = to_f2(pnl - expected_loss, "%.2f");
54559
+ new_pnl = to_f(pnl - expected_loss, "%.2f");
54558
54560
  }
54559
54561
  return {
54560
54562
  pnl: new_pnl,
54561
- loss: to_f2(expected_loss, "%.2f"),
54562
- full_loss: to_f2(full_loss, "%.2f"),
54563
+ loss: to_f(expected_loss, "%.2f"),
54564
+ full_loss: to_f(full_loss, "%.2f"),
54563
54565
  original_pnl: pnl,
54564
54566
  reward_factor,
54565
54567
  profit_percent,
54566
54568
  kind: focus_position.kind,
54567
- sell_price: to_f2(sell_price, price_places),
54569
+ sell_price: to_f(sell_price, price_places),
54568
54570
  quantity: quantity * full_ratio,
54569
54571
  price_places,
54570
54572
  decimal_places
@@ -54599,18 +54601,18 @@ function generateGapTp(payload) {
54599
54601
  const gapLoss = gap * max_quantity;
54600
54602
  const longPercent = gapLoss * factor / (short.entry * short.quantity);
54601
54603
  const shortPercent = gapLoss * factor / (long.entry * long.quantity);
54602
- const longTp = to_f2((1 + longPercent) * long.entry, price_places);
54603
- const shortTp = to_f2((1 + shortPercent) ** -1 * short.entry, price_places);
54604
- const shortToReduce = to_f2(Math.abs(longTp - long.entry) * long.quantity, "%.1f");
54605
- const longToReduce = to_f2(Math.abs(shortTp - short.entry) * short.quantity, "%.1f");
54606
- const actualShortReduce = to_f2(shortToReduce * sell_factor, "%.1f");
54607
- const actualLongReduce = to_f2(longToReduce * sell_factor, "%.1f");
54604
+ const longTp = to_f((1 + longPercent) * long.entry, price_places);
54605
+ const shortTp = to_f((1 + shortPercent) ** -1 * short.entry, price_places);
54606
+ const shortToReduce = to_f(Math.abs(longTp - long.entry) * long.quantity, "%.1f");
54607
+ const longToReduce = to_f(Math.abs(shortTp - short.entry) * short.quantity, "%.1f");
54608
+ const actualShortReduce = to_f(shortToReduce * sell_factor, "%.1f");
54609
+ const actualLongReduce = to_f(longToReduce * sell_factor, "%.1f");
54608
54610
  const short_quantity_to_sell = determine_amount_to_sell2(short.entry, short.quantity, longTp, actualShortReduce, "short", decimal_places);
54609
54611
  const long_quantity_to_sell = determine_amount_to_sell2(long.entry, long.quantity, shortTp, actualLongReduce, "long", decimal_places);
54610
- const risk_amount_short = to_f2(shortToReduce - actualShortReduce, "%.2f");
54611
- const risk_amount_long = to_f2(longToReduce - actualLongReduce, "%.2f");
54612
- const profit_percent_long = to_f2(shortToReduce * 100 / (long.entry * long.quantity), "%.4f");
54613
- const profit_percent_short = to_f2(longToReduce * 100 / (short.entry * short.quantity), "%.4f");
54612
+ const risk_amount_short = to_f(shortToReduce - actualShortReduce, "%.2f");
54613
+ const risk_amount_long = to_f(longToReduce - actualLongReduce, "%.2f");
54614
+ const profit_percent_long = to_f(shortToReduce * 100 / (long.entry * long.quantity), "%.4f");
54615
+ const profit_percent_short = to_f(longToReduce * 100 / (short.entry * short.quantity), "%.4f");
54614
54616
  return {
54615
54617
  profit_percent: {
54616
54618
  long: profit_percent_long,
@@ -54636,8 +54638,8 @@ function generateGapTp(payload) {
54636
54638
  short: short_quantity_to_sell,
54637
54639
  long: long_quantity_to_sell
54638
54640
  },
54639
- gap: to_f2(gap, price_places),
54640
- gap_loss: to_f2(gapLoss, "%.2f")
54641
+ gap: to_f(gap, price_places),
54642
+ gap_loss: to_f(gapLoss, "%.2f")
54641
54643
  };
54642
54644
  }
54643
54645
  function calculate_factor(payload) {
@@ -54663,14 +54665,14 @@ function calculate_factor(payload) {
54663
54665
  const calculated_shortPercent = target_to_reduce / (short_notional - target_to_reduce);
54664
54666
  calculated_factor = calculated_shortPercent * long_notional / gapLoss;
54665
54667
  }
54666
- calculated_factor = to_f2(calculated_factor, places);
54668
+ calculated_factor = to_f(calculated_factor, places);
54667
54669
  return calculated_factor;
54668
54670
  }
54669
54671
  function determineRewardFactor(payload) {
54670
54672
  const { quantity, avg_qty, minimum_pnl, risk } = payload;
54671
54673
  const reward_factor = minimum_pnl / risk;
54672
54674
  const quantity_ratio = quantity / avg_qty;
54673
- return to_f2(reward_factor / quantity_ratio, "%.4f");
54675
+ return to_f(reward_factor / quantity_ratio, "%.4f");
54674
54676
  }
54675
54677
  function getHedgeZone(payload) {
54676
54678
  const {
@@ -54696,19 +54698,19 @@ function getHedgeZone(payload) {
54696
54698
  const tp_diff = Math.abs(take_profit - position2.entry);
54697
54699
  const quantity = position2.quantity;
54698
54700
  const diff = risk / quantity;
54699
- let new_take_profit = kind === "long" ? to_f2(position2.entry + diff, symbol_config.price_places) : to_f2(position2.entry - diff, symbol_config.price_places);
54700
- let base_factor = to_f2(Math.max(tp_diff, diff) / (Math.min(tp_diff, diff) || 1), "%.3f");
54701
+ let new_take_profit = kind === "long" ? to_f(position2.entry + diff, symbol_config.price_places) : to_f(position2.entry - diff, symbol_config.price_places);
54702
+ let base_factor = to_f(Math.max(tp_diff, diff) / (Math.min(tp_diff, diff) || 1), "%.3f");
54701
54703
  let factor = reward_factor || base_factor;
54702
54704
  const new_risk = risk * factor * risk_factor;
54703
54705
  const stop_loss_diff = new_risk / quantity;
54704
- 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);
54705
- 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);
54706
+ 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);
54707
+ 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);
54706
54708
  const profit_percent = new_risk * 100 / (position2.entry * position2.quantity);
54707
54709
  return {
54708
54710
  support: Math.min(new_take_profit, stop_loss),
54709
54711
  resistance: Math.max(new_take_profit, stop_loss),
54710
- risk: to_f2(new_risk, "%.2f"),
54711
- profit_percent: to_f2(profit_percent, "%.2f")
54712
+ risk: to_f(new_risk, "%.2f"),
54713
+ profit_percent: to_f(profit_percent, "%.2f")
54712
54714
  };
54713
54715
  }
54714
54716
  function getOptimumHedgeFactor(payload) {
@@ -54743,10 +54745,10 @@ function getOptimumHedgeFactor(payload) {
54743
54745
  }
54744
54746
  if (diff <= tolerance) {
54745
54747
  return {
54746
- reward_factor: to_f2(mid_factor, "%.4f"),
54747
- achieved_support: to_f2(current_support, symbol_config.price_places),
54748
- target_support: to_f2(target_support, symbol_config.price_places),
54749
- difference: to_f2(diff, symbol_config.price_places),
54748
+ reward_factor: to_f(mid_factor, "%.4f"),
54749
+ achieved_support: to_f(current_support, symbol_config.price_places),
54750
+ target_support: to_f(target_support, symbol_config.price_places),
54751
+ difference: to_f(diff, symbol_config.price_places),
54750
54752
  iterations: iteration + 1
54751
54753
  };
54752
54754
  }
@@ -54766,10 +54768,10 @@ function getOptimumHedgeFactor(payload) {
54766
54768
  reward_factor: best_factor
54767
54769
  });
54768
54770
  return {
54769
- reward_factor: to_f2(best_factor, "%.4f"),
54770
- achieved_support: to_f2(final_hedge_zone.support, symbol_config.price_places),
54771
- target_support: to_f2(target_support, symbol_config.price_places),
54772
- difference: to_f2(best_diff, symbol_config.price_places),
54771
+ reward_factor: to_f(best_factor, "%.4f"),
54772
+ achieved_support: to_f(final_hedge_zone.support, symbol_config.price_places),
54773
+ target_support: to_f(target_support, symbol_config.price_places),
54774
+ difference: to_f(best_diff, symbol_config.price_places),
54773
54775
  iterations: max_iterations,
54774
54776
  converged: best_diff <= tolerance
54775
54777
  };
@@ -54814,15 +54816,14 @@ function determineCompoundLongTrade(payload) {
54814
54816
  return {
54815
54817
  start_risk,
54816
54818
  short_profit,
54817
- support: to_f2(support, global_config.price_places),
54818
- resistance: to_f2(resistance, global_config.price_places),
54819
+ support: to_f(support, global_config.price_places),
54820
+ resistance: to_f(resistance, global_config.price_places),
54819
54821
  long_v: long_app_config.last_value,
54820
- profit_percent: to_f2(long_profit_percent, "%.3f"),
54822
+ profit_percent: to_f(long_profit_percent, "%.3f"),
54821
54823
  result,
54822
54824
  short_max_size
54823
54825
  };
54824
54826
  }
54825
-
54826
54827
  // src/helpers/strategy.ts
54827
54828
  class Strategy {
54828
54829
  position;
@@ -54846,10 +54847,10 @@ class Strategy {
54846
54847
  return this.config.global_config.decimal_places;
54847
54848
  }
54848
54849
  to_f(price) {
54849
- return to_f2(price, this.price_places);
54850
+ return to_f(price, this.price_places);
54850
54851
  }
54851
54852
  to_df(quantity) {
54852
- return to_f2(quantity, this.decimal_places);
54853
+ return to_f(quantity, this.decimal_places);
54853
54854
  }
54854
54855
  pnl(kind, _position) {
54855
54856
  const position2 = _position || this.position[kind];
@@ -55050,7 +55051,7 @@ class Strategy {
55050
55051
  remaining_quantity: this.to_df(reverse_avg.quantity - sell_quantity)
55051
55052
  },
55052
55053
  spread: Math.abs(avg.entry - reverse_avg.entry),
55053
- gap_loss: to_f2(Math.abs(avg.entry - reverse_avg.entry) * reverse_avg.quantity, "%.2f"),
55054
+ gap_loss: to_f(Math.abs(avg.entry - reverse_avg.entry) * reverse_avg.quantity, "%.2f"),
55054
55055
  net_profit: incurred_loss + reverse_pnl
55055
55056
  };
55056
55057
  }
@@ -55218,8 +55219,8 @@ class Strategy {
55218
55219
  quantity: this.position[app_config.kind].quantity
55219
55220
  }
55220
55221
  ]), app_config.decimal_places, app_config.price_places);
55221
- const expected_loss = to_f2(Math.abs(avg.price - stop) * avg.quantity, "%.2f");
55222
- const profit_percent = to_f2(this.pnl(kind) * 100 / (avg.price * avg.quantity), "%.3f");
55222
+ const expected_loss = to_f(Math.abs(avg.price - stop) * avg.quantity, "%.2f");
55223
+ const profit_percent = to_f(this.pnl(kind) * 100 / (avg.price * avg.quantity), "%.3f");
55223
55224
  app_config.entry = this.to_f(app_config.entry);
55224
55225
  app_config.stop = this.to_f(app_config.stop);
55225
55226
  return { ...app_config, avg, loss: -expected_loss, profit_percent };
@@ -55322,9 +55323,6 @@ class Strategy {
55322
55323
  };
55323
55324
  }
55324
55325
  }
55325
-
55326
- // src/exchanges/binance/index.ts
55327
- var import_binance = __toESM(require_lib2());
55328
55326
  // src/types/index.ts
55329
55327
  class BaseExchange {
55330
55328
  client;
@@ -55369,7 +55367,7 @@ class BaseExchange {
55369
55367
  place = false
55370
55368
  } = payload;
55371
55369
  const totalQuantity = orders.reduce((sum, order) => sum + (order.quantity || 0), 0);
55372
- let runningTotal = to_f2(totalQuantity, decimal_places);
55370
+ let runningTotal = to_f(totalQuantity, decimal_places);
55373
55371
  let sortedOrders = [...orders].sort((a, b) => (a.entry || 0) - (b.entry || 0));
55374
55372
  if (kind === "short") {
55375
55373
  sortedOrders.reverse();
@@ -55381,7 +55379,7 @@ class BaseExchange {
55381
55379
  cumulative_quantity: runningTotal
55382
55380
  });
55383
55381
  runningTotal -= order.quantity;
55384
- runningTotal = to_f2(runningTotal, decimal_places);
55382
+ runningTotal = to_f(runningTotal, decimal_places);
55385
55383
  }
55386
55384
  const positions = await this.getPositionInfo(symbol);
55387
55385
  const position2 = positions[kind] || {
@@ -55910,8 +55908,8 @@ async function createLimitPurchaseOrdersParallel(client, symbol, priceFormat, qu
55910
55908
  const createOrder = (x) => {
55911
55909
  const v = {
55912
55910
  symbol: symbol.toUpperCase(),
55913
- price: x.price ? to_f2(x.price, priceFormat) : 0,
55914
- quantity: x.quantity ? to_f2(x.quantity, quantityFormat) : 0,
55911
+ price: x.price ? to_f(x.price, priceFormat) : 0,
55912
+ quantity: x.quantity ? to_f(x.quantity, quantityFormat) : 0,
55915
55913
  side: x.side?.toUpperCase() || "",
55916
55914
  type: "LIMIT",
55917
55915
  positionSide: x.kind.toUpperCase(),
@@ -55926,7 +55924,7 @@ async function createLimitPurchaseOrdersParallel(client, symbol, priceFormat, qu
55926
55924
  delete v.timeInForce;
55927
55925
  v.type = `${v.type}_MARKET`.toUpperCase();
55928
55926
  } else if (typeof x.stop === "number") {
55929
- v.stopPrice = to_f2(x.stop, priceFormat);
55927
+ v.stopPrice = to_f(x.stop, priceFormat);
55930
55928
  }
55931
55929
  }
55932
55930
  if (x.force_market) {
@@ -56199,14 +56197,14 @@ async function getOpenOrders(client, symbol, type) {
56199
56197
  async function getWalletBalance(client, asset = "USDT") {
56200
56198
  const response = await client.getBalanceV3();
56201
56199
  const balance = response.find((x) => x.asset.toLowerCase() === asset.toLowerCase())?.balance;
56202
- return balance ? to_f2(balance, "%.2f") : 0;
56200
+ return balance ? to_f(balance, "%.2f") : 0;
56203
56201
  }
56204
56202
  async function allWalletBalances(client) {
56205
56203
  const response = await client.getBalanceV3();
56206
56204
  return response.map((x) => ({
56207
56205
  type: "future",
56208
56206
  asset: x.asset,
56209
- balance: to_f2(x.balance, "%.8f")
56207
+ balance: to_f(x.balance, "%.8f")
56210
56208
  }));
56211
56209
  }
56212
56210
  function buildPosition(position2, orders, options) {
@@ -56243,7 +56241,7 @@ function buildPosition(position2, orders, options) {
56243
56241
  take_profit,
56244
56242
  tp_quantity,
56245
56243
  stop_quantity,
56246
- liquidation: position2.liquidationPrice ? to_f2(position2.liquidationPrice, price_places) : 0
56244
+ liquidation: position2.liquidationPrice ? to_f(position2.liquidationPrice, price_places) : 0
56247
56245
  };
56248
56246
  }
56249
56247
  var emptyPosition = {
@@ -56264,7 +56262,7 @@ async function getLeverage(client, symbol) {
56264
56262
  symbol
56265
56263
  });
56266
56264
  const leverage = response[0]?.leverage;
56267
- return leverage ? to_f2(leverage, "%0f") : 0;
56265
+ return leverage ? to_f(leverage, "%0f") : 0;
56268
56266
  }
56269
56267
  async function fetchBinanceAccount(client, json, options) {
56270
56268
  const [position2, balance, orders, current_price, all_balances, leverage] = await Promise.all([
@@ -56562,7 +56560,7 @@ class BinanceExchange extends BaseExchange {
56562
56560
  const currentPrice = await getCurrentPrice(this.client, symbol);
56563
56561
  const price_places = isBTC ? "%.1f" : `%.${getPricePlaces(currentPrice)}f`;
56564
56562
  const decimal_places = `%.${target.quantityPrecision}f`;
56565
- const min_size = to_f2((minNotional || 0) / support, decimal_places);
56563
+ const min_size = to_f((minNotional || 0) / support, decimal_places);
56566
56564
  const configObj = {
56567
56565
  support,
56568
56566
  resistance,
@@ -56806,8 +56804,8 @@ async function createLimitPurchaseOrders(client, symbol, priceFormat, quantityFo
56806
56804
  const createOrder = (x) => {
56807
56805
  const v = {
56808
56806
  symbol: symbol.toUpperCase(),
56809
- price: (x.price ? to_f2(x.price, priceFormat) : 0).toString(),
56810
- qty: (x.quantity ? to_f2(x.quantity, quantityFormat) : 0).toString(),
56807
+ price: (x.price ? to_f(x.price, priceFormat) : 0).toString(),
56808
+ qty: (x.quantity ? to_f(x.quantity, quantityFormat) : 0).toString(),
56811
56809
  side: titleCase(x.side || ""),
56812
56810
  orderType: "LIMIT",
56813
56811
  positionIdx: x.kind === "long" ? 1 : 2,
@@ -56824,12 +56822,12 @@ async function createLimitPurchaseOrders(client, symbol, priceFormat, quantityFo
56824
56822
  delete v.timeInForce;
56825
56823
  v.orderType = `MARKET`;
56826
56824
  } else if (typeof x.stop === "number") {
56827
- v.triggerPrice = to_f2(x.stop, priceFormat).toString();
56825
+ v.triggerPrice = to_f(x.stop, priceFormat).toString();
56828
56826
  }
56829
56827
  if (x.kind === "long" && x.side === "sell" || x.kind === "short" && x.side === "buy") {
56830
56828
  v.tpslMode = "Partial";
56831
56829
  v.slOrderType = "Limit";
56832
- v.slLimitPrice = to_f2(v.triggerPrice, priceFormat).toString();
56830
+ v.slLimitPrice = to_f(v.triggerPrice, priceFormat).toString();
56833
56831
  if (x.is_market) {
56834
56832
  v.slOrderType = "Market";
56835
56833
  v.tpslMode = "Full";
@@ -57062,7 +57060,7 @@ async function getWalletBalance2(client, asset = "USDT") {
57062
57060
  accountType: "UNIFIED",
57063
57061
  coin: asset
57064
57062
  });
57065
- return to_f2(response.result.list[0].totalWalletBalance, "%.2f");
57063
+ return to_f(response.result.list[0].totalWalletBalance, "%.2f");
57066
57064
  }
57067
57065
  async function allWalletBalances2(client) {
57068
57066
  const response = await client.getWalletBalance({
@@ -57072,7 +57070,7 @@ async function allWalletBalances2(client) {
57072
57070
  return response.result.list[0].coin.map((x) => ({
57073
57071
  type: "future",
57074
57072
  asset: x.coin,
57075
- balance: to_f2(x.walletBalance, "%.8f")
57073
+ balance: to_f(x.walletBalance, "%.8f")
57076
57074
  }));
57077
57075
  }
57078
57076
  function buildPosition2(position2, orders, options) {
@@ -57369,7 +57367,7 @@ class BybitExchange extends BaseExchange {
57369
57367
  function determine_liquidation(balance_diff, position2) {
57370
57368
  const long_liquidation = position2.price - balance_diff / position2.quantity;
57371
57369
  const short_liquidation = position2.price + balance_diff / position2.quantity;
57372
- return position2.kind === "long" ? to_f2(long_liquidation, "%.2f") : to_f2(short_liquidation, "%.2f");
57370
+ return position2.kind === "long" ? to_f(long_liquidation, "%.2f") : to_f(short_liquidation, "%.2f");
57373
57371
  }
57374
57372
  function calculate_avg_entry(kind, {
57375
57373
  orders: _orders,
@@ -57534,13 +57532,13 @@ function calculateHedge(payload) {
57534
57532
  const stopLossQuantity = Math.min(stopLossAmount / priceDifference, oppositePosition.quantity);
57535
57533
  return {
57536
57534
  [kind]: {
57537
- price: to_f2(takeProfitPrice, active_account.price_places),
57538
- quantity: to_f2(position_quantity || 0, active_account.decimal_places),
57535
+ price: to_f(takeProfitPrice, active_account.price_places),
57536
+ quantity: to_f(position_quantity || 0, active_account.decimal_places),
57539
57537
  type: "TAKE_PROFIT"
57540
57538
  },
57541
57539
  [oppositeKind]: {
57542
- stop_price: to_f2(stopLossPrice, active_account.price_places),
57543
- quantity: to_f2(stopLossQuantity || 0, active_account.decimal_places),
57540
+ stop_price: to_f(stopLossPrice, active_account.price_places),
57541
+ quantity: to_f(stopLossQuantity || 0, active_account.decimal_places),
57544
57542
  type: "STOP_LOSS"
57545
57543
  }
57546
57544
  };
@@ -57605,7 +57603,7 @@ function processPosition(codeNode, input, kind) {
57605
57603
  side: reverse_kind === "long" ? "buy" : "sell"
57606
57604
  },
57607
57605
  orders_to_cancel,
57608
- stop: to_f2(vv[kind].price, active_account.price_places),
57606
+ stop: to_f(vv[kind].price, active_account.price_places),
57609
57607
  quantity: vv[kind].quantity,
57610
57608
  kind,
57611
57609
  type: JSON.stringify("TAKE_PROFIT"),
@@ -57624,7 +57622,7 @@ function processPosition(codeNode, input, kind) {
57624
57622
  }
57625
57623
  async function reduceMajorPositionCalculation(input, exchange_instance) {
57626
57624
  try {
57627
- let conditionsCheck = input.position.tp_quantity !== input.quantity || input.position.take_profit !== to_f2(input.stop, input.price_places);
57625
+ let conditionsCheck = input.position.tp_quantity !== input.quantity || input.position.take_profit !== to_f(input.stop, input.price_places);
57628
57626
  if (!isNaN(input.opposite_position.stop_quantity) && input.opposite_position.stop_quantity > -1) {
57629
57627
  conditionsCheck = conditionsCheck || input.opposite_position.stop_quantity !== input.to_place.quantity;
57630
57628
  }
@@ -57749,15 +57747,20 @@ async function reduceMajorPositionEntry(input, accountInfo, trigger2, exchange_i
57749
57747
  // src/position.ts
57750
57748
  class ExchangePosition {
57751
57749
  exchange;
57750
+ symbol_config;
57752
57751
  exchange_account;
57753
57752
  app_db;
57754
57753
  instance;
57755
57754
  constructor(payload) {
57755
+ this.symbol_config = payload.symbol_config;
57756
57756
  this.exchange = payload.exchange;
57757
57757
  this.app_db = payload.app_db;
57758
57758
  this.instance = payload.instance;
57759
57759
  this.exchange_account = payload.exchange_account;
57760
57760
  }
57761
+ getInstance() {
57762
+ return this.instance;
57763
+ }
57761
57764
  get symbol() {
57762
57765
  return this.instance.symbol;
57763
57766
  }
@@ -57765,16 +57768,18 @@ class ExchangePosition {
57765
57768
  return this.instance.kind;
57766
57769
  }
57767
57770
  get account() {
57768
- return this.instance.account;
57771
+ const { p_account } = this.instance.expand;
57772
+ return p_account;
57769
57773
  }
57770
57774
  async cancelOrders(payload) {
57771
- const { limit, price: _price } = payload;
57775
+ const { limit, price: _price, raw } = payload;
57772
57776
  if (limit) {
57773
57777
  return await this.app_db.cancelLimitOrders({
57774
57778
  symbol: this.symbol,
57775
57779
  kind: this.kind,
57776
57780
  account: this.account,
57777
- cancelExchangeOrders: (p) => this.exchange.cancelOrders(p)
57781
+ cancelExchangeOrders: (p) => this.exchange.cancelOrders(p),
57782
+ raw
57778
57783
  });
57779
57784
  }
57780
57785
  let price = _price || 0;
@@ -57807,6 +57812,9 @@ class ExchangePosition {
57807
57812
  return await this.app_db.createOrUpdatePositionConfig(this.instance, params);
57808
57813
  }
57809
57814
  }
57815
+ if (this.instance.expand?.b_config) {
57816
+ return this.instance.expand.b_config;
57817
+ }
57810
57818
  return await this.app_db.getPositionConfig({
57811
57819
  symbol: this.symbol,
57812
57820
  kind: this.kind,
@@ -57815,15 +57823,19 @@ class ExchangePosition {
57815
57823
  }
57816
57824
  async updateTargetPnl() {
57817
57825
  const position2 = this.instance;
57818
- if (position2?.expand?.config) {
57819
- const config2 = position2.expand.config;
57826
+ const config2 = await this.getConfig();
57827
+ if (config2) {
57820
57828
  let _profit = config2.profit;
57829
+ let risk = config2.risk;
57830
+ let next_risk = position2.next_risk;
57821
57831
  let _profit_percent = config2?.profit_percent;
57822
57832
  if (_profit_percent && (position2?.quantity || 0) > 0) {
57823
- _profit = to_f2(position2.quantity * _profit_percent * position2.entry / 100);
57833
+ _profit = to_f(position2.quantity * _profit_percent * position2.entry / 100);
57834
+ next_risk = risk + _profit;
57824
57835
  }
57825
57836
  await this.app_db.update_db_position(position2, {
57826
- target_pnl: _profit
57837
+ target_pnl: _profit,
57838
+ next_risk
57827
57839
  });
57828
57840
  return _profit;
57829
57841
  }
@@ -57843,13 +57855,13 @@ class ExchangePosition {
57843
57855
  }
57844
57856
  }
57845
57857
  async triggerTradeFromConfig(payload) {
57846
- const { place = true, stop, use_current, ignore_config } = payload;
57858
+ const { place = true, stop, use_current, ignore_config, risky } = payload;
57847
57859
  const position2 = this.instance;
57848
57860
  const config2 = await this.getConfig();
57849
57861
  let condition = ignore_config ? true : position2?.config;
57850
57862
  if (condition) {
57851
57863
  let entry = payload.tp ? position2.entry || config2.entry : config2.entry;
57852
- const v = stop ? "place_stop_orders" : "place_limit_orders";
57864
+ const v = stop ? "place_stop_orders" : risky ? "dangerous_entry_orders" : "place_limit_orders";
57853
57865
  return await this.placeSharedOrder(v, {
57854
57866
  entry,
57855
57867
  stop: config2.stop,
@@ -57857,18 +57869,26 @@ class ExchangePosition {
57857
57869
  risk: config2.risk,
57858
57870
  place,
57859
57871
  raw: payload.raw,
57860
- use_current
57872
+ use_current,
57873
+ stop_percent: config2.stop_percent || 100
57861
57874
  });
57862
57875
  }
57863
57876
  }
57864
57877
  async placeSharedOrder(action, payload) {
57878
+ const { stop_percent = 100 } = payload;
57879
+ const config2 = await this.getConfig();
57865
57880
  const app_config = await this.buildAppConfig({
57866
57881
  entry: payload.entry,
57867
57882
  stop: payload.stop,
57868
57883
  risk_reward: payload.risk_reward,
57869
57884
  risk: payload.risk,
57870
57885
  profit: 0,
57871
- update_db: payload.update_db
57886
+ update_db: payload.update_db,
57887
+ use_kelly: config2.kelly?.use_kelly,
57888
+ kelly_confidence_factor: config2.kelly?.kelly_confidence_factor,
57889
+ kelly_minimum_risk: config2.kelly?.kelly_minimum_risk,
57890
+ kelly_prediction_model: config2.kelly?.kelly_prediction_model,
57891
+ kelly_func: config2.kelly?.kelly_func
57872
57892
  });
57873
57893
  const { entry_orders, stop_orders, trades } = await this.placeConfigOrders(app_config, {
57874
57894
  risk_reward: payload.risk_reward,
@@ -57878,7 +57898,13 @@ class ExchangePosition {
57878
57898
  avg_size: 0,
57879
57899
  neg_pnl: 0,
57880
57900
  min_size: app_config.min_size,
57881
- symbol: this.symbol
57901
+ symbol: this.symbol,
57902
+ stop_percent,
57903
+ use_kelly: config2.kelly?.use_kelly,
57904
+ kelly_confidence_factor: config2.kelly?.kelly_confidence_factor,
57905
+ kelly_minimum_risk: config2.kelly?.kelly_minimum_risk,
57906
+ kelly_prediction_model: config2.kelly?.kelly_prediction_model,
57907
+ kelly_func: config2.kelly?.kelly_func
57882
57908
  }, false);
57883
57909
  if (payload.raw) {
57884
57910
  let actual_orders_to_buy = await this.determineAmountToBuy({
@@ -57914,12 +57940,23 @@ class ExchangePosition {
57914
57940
  symbol: this.symbol,
57915
57941
  place: payload.place
57916
57942
  });
57917
- await this.exchange_account.getLiveExchangeInstance({
57918
- symbol: this.symbol,
57919
- refresh: true
57920
- });
57921
57943
  return result;
57922
57944
  }
57945
+ if (action == "dangerous_entry_orders" && payload.place) {
57946
+ return await this.exchange.createLimitPurchaseOrders({
57947
+ orders: trades.map((x) => ({
57948
+ ...x,
57949
+ price: x.entry,
57950
+ quantity: x.quantity,
57951
+ side: app_config.kind === "long" ? "buy" : "sell",
57952
+ kind: app_config.kind
57953
+ })),
57954
+ kind: app_config.kind,
57955
+ decimal_places: app_config.decimal_places,
57956
+ price_places: app_config.price_places,
57957
+ symbol: this.symbol
57958
+ });
57959
+ }
57923
57960
  if (action === "place_stop_orders" && payload.place) {
57924
57961
  const instance = this.instance;
57925
57962
  let result = await this.exchange.placeStopOrders({
@@ -57931,10 +57968,6 @@ class ExchangePosition {
57931
57968
  decimal_places: app_config.decimal_places,
57932
57969
  place: true
57933
57970
  });
57934
- await this.exchange_account.getLiveExchangeInstance({
57935
- symbol: this.symbol,
57936
- refresh: true
57937
- });
57938
57971
  return result;
57939
57972
  }
57940
57973
  return {
@@ -57963,11 +57996,19 @@ class ExchangePosition {
57963
57996
  return app_config;
57964
57997
  }
57965
57998
  async placeConfigOrders(app_config, solution, place, skip_stop) {
57999
+ const { stop_percent = 100 } = solution;
57966
58000
  app_config.entry = solution.entry;
57967
58001
  app_config.stop = solution.stop;
57968
58002
  app_config.risk_per_trade = solution.risk_per_trade;
57969
58003
  app_config.min_size = solution.min_size;
57970
58004
  app_config.risk_reward = solution.risk_reward;
58005
+ app_config.kelly = {
58006
+ use_kelly: solution.use_kelly,
58007
+ kelly_confidence_factor: solution.kelly_confidence_factor,
58008
+ kelly_minimum_risk: solution.kelly_minimum_risk,
58009
+ kelly_prediction_model: solution.kelly_prediction_model,
58010
+ kelly_func: solution.kelly_func
58011
+ };
57971
58012
  const options = {
57972
58013
  take_profit: null,
57973
58014
  entry: app_config.entry,
@@ -57981,7 +58022,12 @@ class ExchangePosition {
57981
58022
  gap: app_config.gap,
57982
58023
  rr: app_config.rr,
57983
58024
  price_places: app_config.price_places,
57984
- decimal_places: app_config.decimal_places
58025
+ decimal_places: app_config.decimal_places,
58026
+ use_kelly: solution.use_kelly,
58027
+ kelly_confidence_factor: solution.kelly_confidence_factor,
58028
+ kelly_minimum_risk: solution.kelly_minimum_risk,
58029
+ kelly_prediction_model: solution.kelly_prediction_model,
58030
+ kelly_func: solution.kelly_func
57985
58031
  };
57986
58032
  const trades = sortedBuildConfig(app_config, options);
57987
58033
  const entry_orders = {
@@ -57995,9 +58041,13 @@ class ExchangePosition {
57995
58041
  })),
57996
58042
  kind: app_config.kind
57997
58043
  };
58044
+ const last_order = trades[0]?.entry;
58045
+ const stop_spread = stop_percent / 100;
58046
+ const _stop = app_config.kind === "short" ? last_order * (1 + stop_spread) : last_order * (1 - stop_spread);
58047
+ const stop_to_user = stop_percent === 100 ? solution.stop : _stop;
57998
58048
  const stop_orders = {
57999
- stop: solution.stop,
58000
- final_stop: solution.stop,
58049
+ stop: stop_to_user,
58050
+ final_stop: stop_to_user,
58001
58051
  kind: app_config.kind,
58002
58052
  quantity: trades[0]?.avg_size,
58003
58053
  is_limit: true,
@@ -58039,7 +58089,7 @@ class ExchangePosition {
58039
58089
  async determineAmountToBuy(payload) {
58040
58090
  const { orders, kind, decimal_places = "%.3f", refresh, cancel } = payload;
58041
58091
  const totalQuantity = orders.reduce((sum, order) => sum + (order.quantity || 0), 0);
58042
- let runningTotal = to_f2(totalQuantity, decimal_places);
58092
+ let runningTotal = to_f(totalQuantity, decimal_places);
58043
58093
  let sortedOrders = [...orders].sort((a, b) => (a.entry || 0) - (b.entry || 0));
58044
58094
  if (kind === "short") {
58045
58095
  sortedOrders.reverse();
@@ -58051,7 +58101,7 @@ class ExchangePosition {
58051
58101
  cumulative_quantity: runningTotal
58052
58102
  });
58053
58103
  runningTotal -= order.quantity;
58054
- runningTotal = to_f2(runningTotal, decimal_places);
58104
+ runningTotal = to_f(runningTotal, decimal_places);
58055
58105
  }
58056
58106
  const { instance: position2, existingOrders } = await this.refresh(refresh);
58057
58107
  let filteredOrders = withCumulative.filter((order) => (order.cumulative_quantity || 0) > position2?.quantity).map((order) => ({
@@ -58073,14 +58123,11 @@ class ExchangePosition {
58073
58123
  return filteredOrders;
58074
58124
  }
58075
58125
  async refresh(live_refresh) {
58076
- await this.exchange_account.refreshAccount({
58077
- symbol: this.symbol,
58078
- live_refresh
58079
- });
58080
58126
  const instance = await this.exchange_account.syncAccount({
58081
58127
  symbol: this.symbol,
58082
58128
  kind: this.kind,
58083
- update: true
58129
+ update: true,
58130
+ live_refresh
58084
58131
  });
58085
58132
  let existingOrders = await this.exchange_account.syncOrders({
58086
58133
  symbol: this.symbol,
@@ -58089,29 +58136,467 @@ class ExchangePosition {
58089
58136
  return { instance, existingOrders };
58090
58137
  }
58091
58138
  async placeTrade(payload) {
58092
- const { place, tp, raw: _raw, cancel, stop, ignore_config } = payload;
58139
+ const {
58140
+ place,
58141
+ tp,
58142
+ raw: _raw,
58143
+ cancel,
58144
+ stop,
58145
+ ignore_config,
58146
+ risky,
58147
+ limit = true,
58148
+ target_pnl
58149
+ } = payload;
58093
58150
  if (cancel) {
58094
58151
  await this.cancelOrders({
58095
58152
  limit: true
58096
58153
  });
58097
58154
  }
58098
- if (place) {
58155
+ if (limit) {
58099
58156
  return await this.triggerTradeFromConfig({
58100
- raw: payload.raw,
58157
+ raw: _raw,
58101
58158
  stop,
58102
- ignore_config
58159
+ ignore_config,
58160
+ risky,
58161
+ place
58103
58162
  });
58104
58163
  }
58105
58164
  const rr = await this.refresh(true);
58106
- await this.updateTargetPnl();
58165
+ await this.updateConfigPnl();
58107
58166
  if (tp) {
58108
58167
  await this.exchange_account.placeProfitAndStop({
58109
58168
  symbol: this.symbol,
58110
- trigger: true
58169
+ trigger: true,
58170
+ target_pnl
58111
58171
  });
58112
58172
  }
58173
+ return [];
58113
58174
  return rr.existingOrders;
58114
58175
  }
58176
+ async placeStopLimit(payload) {
58177
+ const { place, stop, quantity: _quantity } = payload;
58178
+ const kind = this.kind;
58179
+ const symbol = this.symbol;
58180
+ const position2 = this.instance;
58181
+ if (position2.avg_qty && position2.avg_qty > 0) {
58182
+ const spread = 1.00005;
58183
+ const qty = _quantity || position2.avg_qty - position2.quantity;
58184
+ const symbol_config = this.symbol_config;
58185
+ const orders = [
58186
+ {
58187
+ kind,
58188
+ stop,
58189
+ quantity: to_f(qty, symbol_config.decimal_places),
58190
+ side: kind === "long" ? "buy" : "sell",
58191
+ price: to_f(kind === "short" ? stop * spread ** -1 : stop * spread, symbol_config.price_places)
58192
+ }
58193
+ ];
58194
+ if (place) {
58195
+ return this.exchange.placeBadStopEntry({
58196
+ symbol,
58197
+ orders,
58198
+ price_places: symbol_config.price_places,
58199
+ decimal_places: symbol_config.decimal_places
58200
+ });
58201
+ }
58202
+ return orders;
58203
+ }
58204
+ return [];
58205
+ }
58206
+ async computeTargetPnl(payload) {
58207
+ const { secondary } = payload;
58208
+ const root_position = this.instance;
58209
+ const reverse_position = secondary.instance;
58210
+ if (reverse_position?.expand?.b_config && root_position.quantity > 0) {
58211
+ const reverse_config = reverse_position.expand.b_config;
58212
+ const diff = Math.abs(reverse_config.stop - root_position.entry);
58213
+ const result = to_f(diff * root_position.quantity);
58214
+ if (root_position.target_pnl !== result) {
58215
+ await this.app_db.update_db_position(root_position, {
58216
+ target_pnl: result
58217
+ });
58218
+ await secondary.getConfig({
58219
+ params: {
58220
+ ...reverse_config,
58221
+ risk: result
58222
+ }
58223
+ });
58224
+ }
58225
+ return result;
58226
+ }
58227
+ return 0;
58228
+ }
58229
+ async runSimulation(payload) {
58230
+ const { iterations = 2, raw = false } = payload;
58231
+ const kind = this.kind;
58232
+ const symbol_config = this.symbol_config;
58233
+ const long_position = payload.long_position.instance;
58234
+ const short_position = payload.short_position.instance;
58235
+ const long_config = await payload.long_position.getConfig();
58236
+ const short_config = await payload.short_position.getConfig();
58237
+ const focus_config = kind === "long" ? long_config : short_config;
58238
+ const short_tp_factor = short_config.profit_percent / long_config.profit_percent;
58239
+ const reduce_ratio = focus_config.reduce_ratio;
58240
+ const budget = focus_config.risk;
58241
+ const risk_reward = focus_config.risk_reward;
58242
+ const tp_percent = long_config.profit_percent;
58243
+ const fee_percent = symbol_config.fee_percent;
58244
+ const strategy_config = {
58245
+ tp_percent,
58246
+ short_tp_factor,
58247
+ fee_percent,
58248
+ budget,
58249
+ risk_reward,
58250
+ reduce_ratio,
58251
+ global_config: symbol_config
58252
+ };
58253
+ const strategy2 = new Strategy({
58254
+ long: {
58255
+ entry: long_position.entry,
58256
+ quantity: long_position.quantity,
58257
+ avg_price: long_position.avg_price,
58258
+ avg_qty: long_position.avg_qty
58259
+ },
58260
+ short: {
58261
+ entry: short_position.entry,
58262
+ quantity: short_position.quantity,
58263
+ avg_price: short_position.avg_price,
58264
+ avg_qty: short_position.avg_qty
58265
+ },
58266
+ config: strategy_config
58267
+ });
58268
+ if (raw) {
58269
+ return strategy2;
58270
+ }
58271
+ return strategy2.runIterations({
58272
+ iterations,
58273
+ kind
58274
+ });
58275
+ }
58276
+ async placeOppositeTradeAction(payload) {
58277
+ const { data } = payload;
58278
+ const position2 = this.instance;
58279
+ if (position2.avg_qty !== data.avg.quantity) {
58280
+ const config2 = await this.getConfig();
58281
+ await this.app_db.updateScheduledTrade(config2.id, {
58282
+ entry: data.entry,
58283
+ stop: data.stop,
58284
+ risk: data.risk_per_trade,
58285
+ profit_percent: data.profit_percent,
58286
+ risk_reward: data.risk_reward
58287
+ });
58288
+ await this.placeTrade({
58289
+ place: true,
58290
+ ignore_config: true
58291
+ });
58292
+ await this.placeTrade({
58293
+ place: true,
58294
+ stop: true,
58295
+ ignore_config: true
58296
+ });
58297
+ }
58298
+ }
58299
+ async updateRiskOnEmpty() {
58300
+ const position2 = this.instance;
58301
+ if (position2 && position2.quantity === 0) {
58302
+ if (position2.next_risk && position2.next_risk > 0) {
58303
+ await this.getConfig({
58304
+ params: {
58305
+ risk: position2.next_risk
58306
+ }
58307
+ });
58308
+ console.log(`Updated ${this.kind} position config for ${this.symbol}: risk = ${position2.next_risk}`);
58309
+ return {
58310
+ updated: true,
58311
+ symbol: this.symbol,
58312
+ kind: this.kind,
58313
+ old_risk: position2.expand?.b_config?.risk,
58314
+ new_risk: position2.next_risk
58315
+ };
58316
+ }
58317
+ }
58318
+ return {
58319
+ updated: false,
58320
+ symbol: this.symbol,
58321
+ kind: this.kind,
58322
+ reason: position2 ? position2.quantity > 0 ? "Position not empty" : "No next_risk available" : "Position not found"
58323
+ };
58324
+ }
58325
+ async increasePositionAtStop(payload) {
58326
+ const { place = false, increase = true } = payload;
58327
+ const position2 = this.instance;
58328
+ console.log(position2);
58329
+ let price_params = {
58330
+ price: payload.price,
58331
+ quantity: payload.quantity
58332
+ };
58333
+ if (!payload.price && position2 && position2.stop_loss) {
58334
+ price_params.price = position2.stop_loss.price;
58335
+ }
58336
+ if (!payload.quantity && position2 && position2.stop_loss) {
58337
+ price_params.quantity = position2.stop_loss.quantity;
58338
+ }
58339
+ if (price_params.price && price_params.quantity) {
58340
+ const { price, quantity } = price_params;
58341
+ const symbol_config = this.symbol_config;
58342
+ const price_places = symbol_config.price_places;
58343
+ const decimal_places = symbol_config.decimal_places;
58344
+ if (place) {
58345
+ await this.cancelOrders({
58346
+ limit: true
58347
+ });
58348
+ }
58349
+ return await this.exchange.customStopLoss({
58350
+ symbol: this.symbol,
58351
+ kind: this.kind,
58352
+ stop: price,
58353
+ quantity,
58354
+ price_places,
58355
+ decimal_places,
58356
+ increase,
58357
+ place
58358
+ });
58359
+ }
58360
+ }
58361
+ async placeSingleOrder(payload) {
58362
+ const { long_position, short_position } = payload;
58363
+ const kind = this.kind;
58364
+ const long_config = await long_position.getConfig();
58365
+ const short_config = await short_position.getConfig();
58366
+ const focus_config = kind === "long" ? long_config : short_config;
58367
+ const focus_position = kind === "long" ? long_position.instance : short_position.instance;
58368
+ const track_position = kind === "long" ? short_position.instance : long_position.instance;
58369
+ const follow = focus_config.follow || focus_position.follow;
58370
+ const threshold_qty = focus_config.threshold_qty || focus_position.threshold_qty;
58371
+ if (!follow) {
58372
+ return "No follow set";
58373
+ }
58374
+ let should_place_order = false;
58375
+ if (threshold_qty === 0) {
58376
+ should_place_order = true;
58377
+ }
58378
+ if (threshold_qty > 0 && track_position.quantity >= threshold_qty) {
58379
+ should_place_order = true;
58380
+ }
58381
+ if (focus_position.quantity === 0) {
58382
+ should_place_order = true;
58383
+ }
58384
+ if (track_position.quantity !== focus_position.quantity && focus_position.quantity < track_position.quantity && should_place_order) {
58385
+ const remaining_quantity = Math.abs(track_position.quantity - focus_position.quantity);
58386
+ await this.placeMarketOrder({
58387
+ quantity: remaining_quantity
58388
+ });
58389
+ }
58390
+ }
58391
+ async placeMarketOrder(payload) {
58392
+ const { quantity } = payload;
58393
+ const symbol_config = this.symbol_config;
58394
+ await this.exchange.placeMarketOrder({
58395
+ symbol: this.symbol,
58396
+ kind: this.kind,
58397
+ quantity,
58398
+ price_places: symbol_config.price_places,
58399
+ decimal_places: symbol_config.decimal_places
58400
+ });
58401
+ }
58402
+ async generate_config_params(payload) {
58403
+ const { entry, stop, risk_reward, risk, with_trades = false } = payload;
58404
+ const symbol = this.symbol;
58405
+ const app_config = await this.buildAppConfig({
58406
+ entry,
58407
+ stop,
58408
+ risk_reward,
58409
+ risk
58410
+ });
58411
+ let config2 = generate_config_params(app_config, {
58412
+ entry,
58413
+ stop,
58414
+ risk_reward,
58415
+ risk,
58416
+ symbol
58417
+ });
58418
+ if (with_trades) {
58419
+ const app_config2 = await this.buildAppConfig({
58420
+ entry: config2.entry,
58421
+ stop: config2.stop,
58422
+ risk_reward: config2.risk_reward,
58423
+ risk: config2.risk,
58424
+ profit: 0,
58425
+ update_db: false
58426
+ });
58427
+ const { trades } = await this.placeConfigOrders(app_config2, {
58428
+ risk_reward: config2.risk_reward,
58429
+ entry: config2.entry,
58430
+ stop: config2.stop,
58431
+ risk_per_trade: config2.risk,
58432
+ avg_size: 0,
58433
+ neg_pnl: 0,
58434
+ min_size: app_config2.min_size,
58435
+ symbol
58436
+ }, false);
58437
+ config2.trades = trades;
58438
+ }
58439
+ return { ...config2, place_stop: false, profit_percent: 0 };
58440
+ }
58441
+ async extrapolateConfig(payload) {
58442
+ const { risk_reward = 199, risk, kind } = payload;
58443
+ const position2 = this.instance;
58444
+ if (position2) {
58445
+ let entry = position2.next_order || position2.avg_liquidation;
58446
+ if (kind == "short" && entry < 0) {
58447
+ const symbol_config = this.symbol_config;
58448
+ entry = symbol_config?.support;
58449
+ }
58450
+ return await this.generate_config_params({
58451
+ entry,
58452
+ stop: position2.take_profit,
58453
+ risk_reward,
58454
+ risk: risk || position2.target_pnl
58455
+ });
58456
+ }
58457
+ return null;
58458
+ }
58459
+ async build_short_order() {
58460
+ const kind = this.kind;
58461
+ const position2 = this.instance;
58462
+ const position_config = await this.getConfig();
58463
+ if (position2 && position_config && position2.entry > 0) {
58464
+ let next_order = position2.next_order;
58465
+ let take_profit = position2.take_profit;
58466
+ if (next_order && take_profit) {
58467
+ let config2 = await this.buildConfigForSymbol({
58468
+ risk: position_config.risk,
58469
+ risk_reward: position_config.risk_reward,
58470
+ as_config: true
58471
+ });
58472
+ const focus = config2.entries.filter((x) => {
58473
+ if (kind == "long") {
58474
+ return x.entry <= next_order;
58475
+ } else {
58476
+ return x.entry >= next_order;
58477
+ }
58478
+ });
58479
+ const focus_entry = focus.at(-1);
58480
+ if (focus_entry) {
58481
+ let entry = focus_entry.entry;
58482
+ let risk = Math.abs(focus_entry.neg_pnl);
58483
+ return await this.generate_config_params({
58484
+ entry,
58485
+ stop: take_profit,
58486
+ risk_reward: position_config.risk_reward,
58487
+ risk
58488
+ });
58489
+ }
58490
+ }
58491
+ }
58492
+ }
58493
+ async buildConfigForSymbol(payload) {
58494
+ const kind = this.kind;
58495
+ const { risk, risk_reward = 199, as_config = false } = payload;
58496
+ const symbol_config = this.symbol_config;
58497
+ const long_config = await this.generate_config_params({
58498
+ entry: kind === "long" ? symbol_config.resistance : symbol_config.support,
58499
+ stop: kind === "long" ? symbol_config.support : symbol_config.resistance,
58500
+ risk_reward,
58501
+ risk
58502
+ });
58503
+ if (as_config) {
58504
+ const app_config = buildAppConfig(symbol_config, {
58505
+ entry: long_config.entry,
58506
+ stop: long_config.stop,
58507
+ risk_reward,
58508
+ risk: long_config.risk,
58509
+ symbol: this.symbol
58510
+ });
58511
+ return app_config;
58512
+ }
58513
+ return long_config;
58514
+ }
58515
+ async buildTrades(payload) {
58516
+ const { risk } = payload;
58517
+ const config2 = await this.getConfig();
58518
+ const app_config = await this.buildAppConfig({
58519
+ entry: config2.entry,
58520
+ stop: config2.stop,
58521
+ risk_reward: config2.risk_reward,
58522
+ risk: risk || config2.risk
58523
+ });
58524
+ const { trades } = await this.placeConfigOrders(app_config, {
58525
+ risk_reward: config2.risk_reward,
58526
+ entry: config2.entry,
58527
+ stop: config2.stop,
58528
+ risk_per_trade: risk || config2.risk,
58529
+ avg_size: 0,
58530
+ neg_pnl: 0,
58531
+ min_size: app_config.min_size,
58532
+ symbol: this.symbol,
58533
+ kelly_confidence_factor: config2.kelly?.kelly_confidence_factor,
58534
+ kelly_minimum_risk: config2.kelly?.kelly_minimum_risk,
58535
+ kelly_prediction_model: config2.kelly?.kelly_prediction_model,
58536
+ kelly_func: config2.kelly?.kelly_func
58537
+ });
58538
+ const position2 = this.instance;
58539
+ const orders_to_place = await this.determineAmountToBuy({
58540
+ orders: trades.map((x) => ({
58541
+ entry: x.entry,
58542
+ quantity: x.quantity
58543
+ })),
58544
+ kind: this.kind,
58545
+ decimal_places: app_config.decimal_places,
58546
+ price_places: app_config.price_places
58547
+ });
58548
+ const avg_values = determine_average_entry_and_size(orders_to_place.map((u) => ({
58549
+ price: u.entry,
58550
+ quantity: u.quantity
58551
+ })).concat({
58552
+ price: position2.entry,
58553
+ quantity: position2.quantity
58554
+ }), app_config.decimal_places, app_config.price_places);
58555
+ return {
58556
+ trades: orders_to_place,
58557
+ max_size: trades[0].avg_size,
58558
+ last_price: trades[0].entry,
58559
+ total_size: avg_values.quantity,
58560
+ avg_entry: avg_values.price
58561
+ };
58562
+ }
58563
+ async tradeConfig(payload) {
58564
+ const { override = {} } = payload;
58565
+ const config2 = await this.getConfig();
58566
+ const app_config = await this.buildAppConfig({
58567
+ entry: config2.entry,
58568
+ stop: config2.stop,
58569
+ risk_reward: config2.risk_reward,
58570
+ risk: config2.risk,
58571
+ symbol: this.symbol,
58572
+ use_kelly: config2.kelly?.use_kelly,
58573
+ kelly_confidence_factor: config2.kelly?.kelly_confidence_factor,
58574
+ kelly_minimum_risk: config2.kelly?.kelly_minimum_risk,
58575
+ kelly_prediction_model: config2.kelly?.kelly_prediction_model,
58576
+ kelly_func: config2.kelly?.kelly_func,
58577
+ ...override
58578
+ });
58579
+ return app_config;
58580
+ }
58581
+ async getOrCreatePositionConfig(payload) {
58582
+ const { risk = 50, risk_reward = 199 } = payload;
58583
+ const config2 = await this.getConfig();
58584
+ if (!config2) {
58585
+ const long_c = await this.buildConfigForSymbol({
58586
+ risk,
58587
+ risk_reward
58588
+ });
58589
+ return this.getConfig({
58590
+ params: {
58591
+ entry: config2.entry,
58592
+ stop: config2.stop,
58593
+ risk_reward: long_c.risk_reward,
58594
+ risk: long_c.risk
58595
+ }
58596
+ });
58597
+ }
58598
+ return config2;
58599
+ }
58115
58600
  }
58116
58601
 
58117
58602
  // src/exchange-account.ts
@@ -58162,16 +58647,22 @@ class ExchangeAccount {
58162
58647
  return result;
58163
58648
  }
58164
58649
  async initializePositions(payload) {
58650
+ const raw_positions = await this.syncAccount({
58651
+ update: payload.update,
58652
+ symbol: payload.symbol,
58653
+ live_refresh: payload.update
58654
+ });
58165
58655
  const positions = await this.syncAccount({
58166
58656
  symbol: payload.symbol,
58167
- as_view: payload.as_view
58657
+ as_view: true
58168
58658
  });
58169
- const raw_positions = await this.syncAccount({
58659
+ const symbol_config = await this.recomputeSymbolConfig({
58170
58660
  symbol: payload.symbol
58171
58661
  });
58172
58662
  const long_position = positions.find((x) => x.kind === "long");
58173
58663
  const short_position = positions.find((x) => x.kind === "short");
58174
58664
  this.long_position = new ExchangePosition({
58665
+ symbol_config,
58175
58666
  exchange: this.exchange,
58176
58667
  exchange_account: this,
58177
58668
  instance: long_position,
@@ -58179,6 +58670,7 @@ class ExchangeAccount {
58179
58670
  without_view: raw_positions.find((x) => x.kind === "long")
58180
58671
  });
58181
58672
  this.short_position = new ExchangePosition({
58673
+ symbol_config,
58182
58674
  exchange: this.exchange,
58183
58675
  exchange_account: this,
58184
58676
  instance: short_position,
@@ -58300,44 +58792,26 @@ class ExchangeAccount {
58300
58792
  }
58301
58793
  }
58302
58794
  }
58303
- async cancelOrders(payload) {
58304
- const { symbol, kind, price: _price, all, stop, limit, raw } = payload;
58305
- let price = _price || 0;
58306
- await this.syncAccount({
58307
- symbol,
58308
- kind,
58309
- update: true
58310
- });
58311
- if (limit) {
58312
- return await this.app_db.cancelLimitOrders({
58313
- raw,
58795
+ async getFocusPosition(payload) {
58796
+ const { symbol, kind, update = false } = payload;
58797
+ let focus_position = kind === "long" ? this.long_position : this.short_position;
58798
+ if (!focus_position) {
58799
+ focus_position = await this.initializePositions({
58314
58800
  symbol,
58315
58801
  kind,
58316
- account: this.instance,
58317
- cancelExchangeOrders: this.cancelExchangeOrders.bind(this)
58802
+ update
58318
58803
  });
58319
58804
  }
58320
- if (all) {
58321
- } else {
58322
- if (!price) {
58323
- const position2 = await this.syncAccount({
58324
- symbol,
58325
- kind: kind === "short" ? "long" : "short",
58326
- as_view: true
58327
- });
58328
- price = position2?.take_profit || 0;
58329
- }
58330
- }
58331
- let result = await this.app_db.cancelOrders({
58332
- cancelExchangeOrders: this.cancelExchangeOrders.bind(this),
58333
- all,
58334
- kind,
58335
- account: this.instance,
58805
+ return focus_position;
58806
+ }
58807
+ async cancelOrders(payload) {
58808
+ const { symbol, kind } = payload;
58809
+ const focus_position = await this.getFocusPosition({
58336
58810
  symbol,
58337
- price,
58338
- stop
58811
+ kind,
58812
+ update: true
58339
58813
  });
58340
- return result;
58814
+ return await focus_position.cancelOrders(payload);
58341
58815
  }
58342
58816
  async cancelExchangeOrders(payload) {
58343
58817
  return this.exchange.cancelOrders(payload);
@@ -58354,46 +58828,13 @@ class ExchangeAccount {
58354
58828
  });
58355
58829
  return break_even_price;
58356
58830
  }
58357
- async buildAppConfig(payload) {
58358
- let config2 = await this.app_db.getSymbolConfigFromDB(payload.symbol);
58359
- const app_config = buildAppConfig(config2, payload);
58360
- if (payload.update_db) {
58361
- const db_position = await this.syncAccount({
58362
- symbol: payload.symbol,
58363
- kind: app_config.kind
58364
- });
58365
- if (db_position) {
58366
- await this.app_db.createOrUpdatePositionConfig(db_position, {
58367
- entry: payload.entry,
58368
- stop: payload.stop,
58369
- risk_reward: payload.risk_reward,
58370
- risk: payload.risk,
58371
- profit_percent: payload.profit_percent
58372
- });
58373
- }
58374
- }
58375
- return app_config;
58376
- }
58377
58831
  async tradeConfig(payload) {
58378
58832
  const { symbol, kind, override = {} } = payload;
58379
- const config2 = await this.getPositionConfig({
58833
+ const focus_position = await this.getFocusPosition({
58380
58834
  symbol,
58381
58835
  kind
58382
58836
  });
58383
- const app_config = await this.buildAppConfig({
58384
- entry: config2.entry,
58385
- stop: config2.stop,
58386
- risk_reward: config2.risk_reward,
58387
- risk: config2.risk,
58388
- symbol,
58389
- use_kelly: config2.kelly?.use_kelly,
58390
- kelly_confidence_factor: config2.kelly?.kelly_confidence_factor,
58391
- kelly_minimum_risk: config2.kelly?.kelly_minimum_risk,
58392
- kelly_prediction_model: config2.kelly?.kelly_prediction_model,
58393
- kelly_func: config2.kelly?.kelly_func,
58394
- ...override
58395
- });
58396
- return app_config;
58837
+ return await focus_position.tradeConfig({ override });
58397
58838
  }
58398
58839
  async justInTimeProfit(payload) {
58399
58840
  const { symbol, target_pnl, kind, refresh, place, take_profit, pause_tp } = payload;
@@ -58411,7 +58852,7 @@ class ExchangeAccount {
58411
58852
  });
58412
58853
  const current_price = take_profit || position2.current_price;
58413
58854
  const notional_value = position2.quantity * position2.entry;
58414
- const current_pnl = to_f2(Math.abs(current_price - position2.entry) * position2.quantity, "%.2f");
58855
+ const current_pnl = to_f(Math.abs(current_price - position2.entry) * position2.quantity, "%.2f");
58415
58856
  const profit_percent = current_pnl * 100 / notional_value;
58416
58857
  const sell_ratio = target_pnl / current_pnl;
58417
58858
  if (place) {
@@ -58455,370 +58896,33 @@ class ExchangeAccount {
58455
58896
  }
58456
58897
  async buildTrades(payload) {
58457
58898
  const { symbol, kind, risk } = payload;
58458
- const config2 = await this.getPositionConfig({
58899
+ const focus_position = await this.getFocusPosition({
58459
58900
  symbol,
58460
58901
  kind
58461
58902
  });
58462
- const app_config = await this.buildAppConfig({
58463
- entry: config2.entry,
58464
- stop: config2.stop,
58465
- risk_reward: config2.risk_reward,
58466
- risk: risk || config2.risk,
58467
- symbol
58903
+ return await focus_position.buildTrades({ risk });
58904
+ }
58905
+ async placeSharedOrder(action, payload) {
58906
+ const kind = payload.entry > payload.stop ? "long" : "short";
58907
+ const focus_position = await this.getFocusPosition({
58908
+ symbol: payload.symbol,
58909
+ kind
58468
58910
  });
58469
- const { trades } = await this.placeConfigOrders(app_config, {
58470
- risk_reward: config2.risk_reward,
58471
- entry: config2.entry,
58472
- stop: config2.stop,
58473
- risk_per_trade: risk || config2.risk,
58474
- avg_size: 0,
58475
- neg_pnl: 0,
58476
- min_size: app_config.min_size,
58477
- symbol
58478
- });
58479
- const position2 = await this.syncAccount({
58480
- symbol,
58481
- kind
58482
- });
58483
- const orders_to_place = await this.determineAmountToBuy({
58484
- orders: trades.map((x) => ({
58485
- entry: x.entry,
58486
- quantity: x.quantity
58487
- })),
58488
- kind,
58489
- decimal_places: app_config.decimal_places,
58490
- price_places: app_config.price_places,
58491
- symbol
58492
- });
58493
- const avg_values = determine_average_entry_and_size(orders_to_place.map((u) => ({
58494
- price: u.entry,
58495
- quantity: u.quantity
58496
- })).concat({
58497
- price: position2.entry,
58498
- quantity: position2.quantity
58499
- }), app_config.decimal_places, app_config.price_places);
58500
- return {
58501
- trades: orders_to_place,
58502
- max_size: trades[0].avg_size,
58503
- last_price: trades[0].entry,
58504
- total_size: avg_values.quantity,
58505
- avg_entry: avg_values.price
58506
- };
58507
- }
58508
- async placeConfigOrders(app_config, solution, place, skip_stop) {
58509
- const { stop_percent = 100 } = solution;
58510
- app_config.entry = solution.entry;
58511
- app_config.stop = solution.stop;
58512
- app_config.risk_per_trade = solution.risk_per_trade;
58513
- app_config.min_size = solution.min_size;
58514
- app_config.risk_reward = solution.risk_reward;
58515
- app_config.kelly = {
58516
- use_kelly: solution.use_kelly,
58517
- kelly_confidence_factor: solution.kelly_confidence_factor,
58518
- kelly_minimum_risk: solution.kelly_minimum_risk,
58519
- kelly_prediction_model: solution.kelly_prediction_model,
58520
- kelly_func: solution.kelly_func
58521
- };
58522
- const options = {
58523
- take_profit: null,
58524
- entry: app_config.entry,
58525
- stop: app_config.stop,
58526
- raw_instance: null,
58527
- risk: app_config.risk_per_trade,
58528
- no_of_trades: undefined,
58529
- risk_reward: app_config.risk_reward,
58530
- kind: app_config.kind,
58531
- increase: true,
58532
- gap: app_config.gap,
58533
- rr: app_config.rr,
58534
- price_places: app_config.price_places,
58535
- decimal_places: app_config.decimal_places,
58536
- use_kelly: solution.use_kelly,
58537
- kelly_confidence_factor: solution.kelly_confidence_factor,
58538
- kelly_minimum_risk: solution.kelly_minimum_risk,
58539
- kelly_prediction_model: solution.kelly_prediction_model,
58540
- kelly_func: solution.kelly_func
58541
- };
58542
- const trades = sortedBuildConfig(app_config, options);
58543
- const entry_orders = {
58544
- orders: trades.map((x) => ({
58545
- entry: x.entry,
58546
- quantity: x.quantity,
58547
- reverse_avg_entry: x.reverse_avg_entry,
58548
- reverse_avg_quantity: x.reverse_avg_quantity,
58549
- avg_entry: x.avg_entry,
58550
- avg_size: x.avg_size
58551
- })),
58552
- kind: app_config.kind
58553
- };
58554
- const last_order = trades[0]?.entry;
58555
- const stop_spread = stop_percent / 100;
58556
- const _stop = app_config.kind === "short" ? last_order * (1 + stop_spread) : last_order * (1 - stop_spread);
58557
- const stop_to_user = stop_percent === 100 ? solution.stop : _stop;
58558
- const stop_orders = {
58559
- stop: stop_to_user,
58560
- final_stop: stop_to_user,
58561
- kind: app_config.kind,
58562
- quantity: trades[0]?.avg_size,
58563
- is_limit: true,
58564
- neg_pnl: trades[0]?.neg_pnl,
58565
- original_stop: solution.stop,
58566
- last_entry: last_order
58567
- };
58568
- if (place) {
58569
- let arr = [
58570
- this.exchange.bulkPlaceLimitOrders({
58571
- orders: trades.map((x) => ({
58572
- entry: x.entry,
58573
- quantity: x.quantity
58574
- })),
58575
- kind: app_config.kind,
58576
- decimal_places: app_config.decimal_places,
58577
- price_places: app_config.price_places,
58578
- symbol: solution.symbol,
58579
- place
58580
- })
58581
- ];
58582
- if (!skip_stop) {
58583
- arr.push(this.exchange.placeStopOrders({
58584
- symbol: solution.symbol,
58585
- quantity: trades[0].avg_size,
58586
- kind: app_config.kind,
58587
- stop: solution.stop,
58588
- price_places: app_config.price_places,
58589
- decimal_places: app_config.decimal_places,
58590
- place
58591
- }));
58592
- }
58593
- await Promise.all(arr);
58594
- }
58595
- return {
58596
- entry_orders,
58597
- stop_orders,
58598
- trades
58599
- };
58600
- }
58601
- async determineAmountToBuy(payload) {
58602
- const {
58603
- orders,
58604
- kind,
58605
- decimal_places = "%.3f",
58606
- symbol,
58607
- refresh,
58608
- cancel
58609
- } = payload;
58610
- const totalQuantity = orders.reduce((sum, order) => sum + (order.quantity || 0), 0);
58611
- let runningTotal = to_f2(totalQuantity, decimal_places);
58612
- let sortedOrders = [...orders].sort((a, b) => (a.entry || 0) - (b.entry || 0));
58613
- if (kind === "short") {
58614
- sortedOrders.reverse();
58615
- }
58616
- const withCumulative = [];
58617
- for (const order of sortedOrders) {
58618
- withCumulative.push({
58619
- ...order,
58620
- cumulative_quantity: runningTotal
58621
- });
58622
- runningTotal -= order.quantity;
58623
- runningTotal = to_f2(runningTotal, decimal_places);
58624
- }
58625
- const position2 = await this.syncAccount({
58626
- symbol,
58627
- kind,
58628
- live_refresh: refresh,
58629
- update: true
58630
- });
58631
- let existingOrders = await this.syncOrders({
58632
- symbol,
58633
- kind
58634
- });
58635
- let filteredOrders = withCumulative.filter((order) => (order.cumulative_quantity || 0) > position2?.quantity).map((order) => ({
58636
- ...order,
58637
- price: order.entry,
58638
- kind,
58639
- side: kind.toLowerCase() === "long" ? "buy" : "sell"
58640
- }));
58641
- filteredOrders = filteredOrders.filter((k) => !existingOrders.map((j) => j.price).includes(k.price));
58642
- const side = kind.toLowerCase() === "long" ? "buy" : "sell";
58643
- const shouldCancel = existingOrders.filter((k) => !orders.map((j) => j.entry).includes(k.price) && k.side === side).map((u) => u.price);
58644
- if (shouldCancel.length > 0 && cancel) {
58645
- const pp = kind === "long" ? Math.max(...shouldCancel) : Math.min(...shouldCancel);
58646
- const cancel_orders = await this.cancelOrders({
58647
- symbol,
58648
- kind,
58649
- price: pp
58650
- });
58651
- console.log("cancel_orders", cancel_orders);
58652
- }
58653
- return filteredOrders;
58654
- }
58655
- async placeSharedOrder(action, payload) {
58656
- const { stop_percent = 100 } = payload;
58657
- const kind = payload.entry > payload.stop ? "long" : "short";
58658
- const config2 = await this.getPositionConfig({
58659
- symbol: payload.symbol,
58660
- kind
58661
- });
58662
- const app_config = await this.buildAppConfig({
58663
- entry: payload.entry,
58664
- stop: payload.stop,
58665
- risk_reward: payload.risk_reward,
58666
- risk: payload.risk,
58911
+ const result = await focus_position.placeSharedOrder(action, payload);
58912
+ await this.getLiveExchangeInstance({
58667
58913
  symbol: payload.symbol,
58668
- profit: 0,
58669
- update_db: payload.update_db,
58670
- use_kelly: config2.kelly?.use_kelly,
58671
- kelly_confidence_factor: config2.kelly?.kelly_confidence_factor,
58672
- kelly_minimum_risk: config2.kelly?.kelly_minimum_risk,
58673
- kelly_prediction_model: config2.kelly?.kelly_prediction_model,
58674
- kelly_func: config2.kelly?.kelly_func
58914
+ refresh: true
58675
58915
  });
58676
- const { entry_orders, stop_orders, trades } = await this.placeConfigOrders(app_config, {
58677
- risk_reward: payload.risk_reward,
58678
- entry: payload.entry,
58679
- stop: payload.stop,
58680
- risk_per_trade: payload.risk,
58681
- avg_size: 0,
58682
- neg_pnl: 0,
58683
- min_size: app_config.min_size,
58684
- symbol: payload.symbol,
58685
- stop_percent,
58686
- use_kelly: config2.kelly?.use_kelly,
58687
- kelly_confidence_factor: config2.kelly?.kelly_confidence_factor,
58688
- kelly_minimum_risk: config2.kelly?.kelly_minimum_risk,
58689
- kelly_prediction_model: config2.kelly?.kelly_prediction_model,
58690
- kelly_func: config2.kelly?.kelly_func
58691
- }, false);
58692
- if (payload.raw) {
58693
- let actual_orders_to_buy = await this.determineAmountToBuy({
58694
- orders: trades,
58695
- kind: app_config.kind,
58696
- decimal_places: app_config.decimal_places,
58697
- price_places: app_config.price_places,
58698
- symbol: payload.symbol,
58699
- place: payload.place
58700
- });
58701
- if (action === "place_limit_orders" && payload.place) {
58702
- return await this.exchange.createLimitPurchaseOrders({
58703
- orders: actual_orders_to_buy.map((x) => ({
58704
- entry: x.entry,
58705
- quantity: x.quantity
58706
- })),
58707
- kind: app_config.kind,
58708
- decimal_places: app_config.decimal_places,
58709
- price_places: app_config.price_places,
58710
- symbol: payload.symbol
58711
- });
58712
- }
58713
- return actual_orders_to_buy;
58714
- }
58715
- if (action === "place_limit_orders" && payload.place) {
58716
- let result = await this.exchange.bulkPlaceLimitOrders({
58717
- orders: trades.map((x) => ({
58718
- entry: x.entry,
58719
- quantity: x.quantity
58720
- })),
58721
- kind: app_config.kind,
58722
- price_places: app_config.price_places,
58723
- decimal_places: app_config.decimal_places,
58724
- symbol: payload.symbol,
58725
- place: payload.place
58726
- });
58727
- await this.getLiveExchangeInstance({
58728
- symbol: payload.symbol,
58729
- refresh: true
58730
- });
58731
- return result;
58732
- }
58733
- if (action == "dangerous_entry_orders" && payload.place) {
58734
- return await this.exchange.createLimitPurchaseOrders({
58735
- orders: trades.map((x) => ({
58736
- ...x,
58737
- price: x.entry,
58738
- quantity: x.quantity,
58739
- side: app_config.kind === "long" ? "buy" : "sell",
58740
- kind: app_config.kind
58741
- })),
58742
- kind: app_config.kind,
58743
- decimal_places: app_config.decimal_places,
58744
- price_places: app_config.price_places,
58745
- symbol: payload.symbol
58746
- });
58747
- }
58748
- if (action === "place_stop_orders" && payload.place) {
58749
- const instance = await this.syncAccount({
58750
- symbol: payload.symbol,
58751
- kind: app_config.kind
58752
- });
58753
- let result = await this.exchange.placeStopOrders({
58754
- symbol: payload.symbol,
58755
- quantity: payload.use_current ? instance.quantity : trades[0].avg_size,
58756
- kind: app_config.kind,
58757
- stop: stop_orders.stop,
58758
- price_places: app_config.price_places,
58759
- decimal_places: app_config.decimal_places,
58760
- place: true
58761
- });
58762
- await this.getLiveExchangeInstance({
58763
- symbol: payload.symbol,
58764
- refresh: true
58765
- });
58766
- return result;
58767
- }
58768
- return {
58769
- entry_orders,
58770
- stop_orders
58771
- };
58916
+ return result;
58772
58917
  }
58773
58918
  async getOrCreatePositionConfig(payload) {
58774
- const { symbol, kind, risk = 50, risk_reward = 199 } = payload;
58775
- const config2 = await this.getPositionConfig({
58776
- symbol: payload.symbol,
58777
- kind: payload.kind
58778
- });
58779
- if (!config2) {
58780
- const long_c = await this.buildConfigForSymbol({
58781
- symbol,
58782
- risk,
58783
- risk_reward
58784
- });
58785
- return this.getPositionConfig({
58786
- symbol,
58787
- kind,
58788
- params: {
58789
- entry: kind === "long" ? long_c.entry : long_c.stop,
58790
- stop: kind === "long" ? long_c.stop : long_c.entry,
58791
- risk_reward: long_c.risk_reward,
58792
- risk: long_c.risk
58793
- }
58794
- });
58795
- }
58796
- return config2;
58919
+ const focus_position = await this.getFocusPosition(payload);
58920
+ return await focus_position.getOrCreatePositionConfig(payload);
58797
58921
  }
58798
58922
  async getPositionConfig(payload) {
58799
- if (payload.params) {
58800
- const db_position = await this.syncAccount({
58801
- symbol: payload.symbol,
58802
- kind: payload.kind
58803
- });
58804
- if (db_position) {
58805
- const config2 = db_position.expand?.config;
58806
- const params = {
58807
- entry: payload.params.entry !== undefined ? payload.params.entry : config2?.entry,
58808
- stop: payload.params.stop !== undefined ? payload.params.stop : config2?.stop,
58809
- risk_reward: payload.params.risk_reward !== undefined ? payload.params.risk_reward : config2?.risk_reward,
58810
- risk: payload.params.risk !== undefined ? payload.params.risk : config2?.risk,
58811
- profit_percent: payload.params.profit_percent !== undefined ? payload.params.profit_percent : config2?.profit_percent,
58812
- place_tp: payload.params.place_tp !== undefined ? payload.params.place_tp : true,
58813
- profit: payload.params.profit !== undefined ? payload.params.profit : config2?.profit
58814
- };
58815
- return await this.app_db.createOrUpdatePositionConfig(db_position, params);
58816
- }
58817
- }
58818
- return await this.app_db.getPositionConfig({
58819
- symbol: payload.symbol,
58820
- kind: payload.kind,
58821
- account: this.instance
58923
+ const focus_position = await this.getFocusPosition(payload);
58924
+ return await focus_position.getConfig({
58925
+ params: payload.params
58822
58926
  });
58823
58927
  }
58824
58928
  async getCurrentPrice(symbol) {
@@ -58831,23 +58935,23 @@ class ExchangeAccount {
58831
58935
  });
58832
58936
  }
58833
58937
  async buildReduceConfig(payload) {
58834
- const positions = await this.syncAccount({
58835
- symbol: payload.symbol
58836
- });
58837
- const long_position = positions.find((x) => x.kind === "long");
58838
- const short_position = positions.find((x) => x.kind === "short");
58839
- const long_config = await this.getPositionConfig({
58938
+ const long_position = await this.getFocusPosition({
58840
58939
  symbol: payload.symbol,
58841
58940
  kind: "long"
58842
58941
  });
58843
- const short_config = await this.getPositionConfig({
58942
+ const short_position = await this.getFocusPosition({
58844
58943
  symbol: payload.symbol,
58845
58944
  kind: "short"
58846
58945
  });
58946
+ const long_config = await long_position.getConfig();
58947
+ const short_config = await short_position.getConfig();
58847
58948
  const config2 = build_reduce_config({
58848
58949
  account: this.instance,
58849
58950
  symbol: payload.symbol,
58850
- _positions: positions,
58951
+ _positions: [
58952
+ long_position.getInstance(),
58953
+ short_position.getInstance()
58954
+ ],
58851
58955
  long_config,
58852
58956
  short_config
58853
58957
  });
@@ -58856,8 +58960,8 @@ class ExchangeAccount {
58856
58960
  }
58857
58961
  let long_target_pnl = payload.kind == "long" ? payload.target_pnl : 0;
58858
58962
  let short_target_pnl = payload.kind == "short" ? payload.target_pnl : 0;
58859
- const long_sell_ratio = long_config.sell_ratio || long_position?.sell_ratio;
58860
- const short_sell_ratio = short_config.sell_ratio || short_position?.sell_ratio;
58963
+ const long_sell_ratio = long_config.sell_ratio || long_position.getInstance()?.sell_ratio;
58964
+ const short_sell_ratio = short_config.sell_ratio || short_position.getInstance()?.sell_ratio;
58861
58965
  if (payload.as_dict) {
58862
58966
  return {
58863
58967
  long: {
@@ -58937,9 +59041,9 @@ class ExchangeAccount {
58937
59041
  async placeProfitAndStop(payload) {
58938
59042
  const { symbol, trigger: trigger2, refresh, kind, target_pnl } = payload;
58939
59043
  if (refresh) {
58940
- await this.syncAccount({
59044
+ await this.initializePositions({
58941
59045
  symbol,
58942
- live_refresh: true,
59046
+ kind,
58943
59047
  update: true
58944
59048
  });
58945
59049
  }
@@ -58972,14 +59076,16 @@ class ExchangeAccount {
58972
59076
  kind
58973
59077
  });
58974
59078
  }
58975
- const long_config = await this.getPositionConfig({
59079
+ const long_position = await this.getFocusPosition({
58976
59080
  symbol,
58977
59081
  kind: "long"
58978
59082
  });
58979
- const short_config = await this.getPositionConfig({
59083
+ const short_position = await this.getFocusPosition({
58980
59084
  symbol,
58981
59085
  kind: "short"
58982
59086
  });
59087
+ const long_config = await long_position.getConfig();
59088
+ const short_config = await short_position.getConfig();
58983
59089
  const long_pause_tp = long_config?.pause_tp;
58984
59090
  const short_pause_tp = short_config?.pause_tp;
58985
59091
  if (payload.trigger && !long_pause_tp && !short_pause_tp && config2) {
@@ -58993,299 +59099,75 @@ class ExchangeAccount {
58993
59099
  return config2;
58994
59100
  }
58995
59101
  async reEnterPositionOnEmpty(symbol) {
58996
- await this.getLiveExchangeInstance({
59102
+ const long_position = await this.getFocusPosition({
58997
59103
  symbol,
58998
- refresh: true
59104
+ kind: "long"
58999
59105
  });
59000
- const db_positions = await this.syncAccount({
59106
+ const short_position = await this.getFocusPosition({
59001
59107
  symbol,
59002
- update: true
59108
+ kind: "short"
59003
59109
  });
59004
- const long_position = db_positions.find((x) => x.kind === "long");
59005
- const short_position = db_positions.find((x) => x.kind === "short");
59006
- if (long_position && long_position.quantity === 0) {
59007
- await this.triggerTradeFromConfig({
59008
- symbol,
59009
- kind: "long"
59010
- });
59110
+ if (long_position && long_position.getInstance().quantity === 0) {
59111
+ await long_position.triggerTradeFromConfig({});
59011
59112
  }
59012
- if (short_position && short_position.quantity === 0) {
59013
- await this.triggerTradeFromConfig({
59014
- symbol,
59015
- kind: "short"
59016
- });
59113
+ if (short_position && short_position.getInstance().quantity === 0) {
59114
+ await short_position.triggerTradeFromConfig({});
59017
59115
  }
59018
- if (long_position.target_pnl > 0 || short_position.target_pnl > 0) {
59116
+ if (long_position.getInstance().target_pnl > 0 || short_position.getInstance().target_pnl > 0) {
59019
59117
  await Promise.all([
59020
- this.updateTargetPnl({
59021
- symbol,
59022
- kind: "long"
59023
- }),
59024
- this.updateTargetPnl({
59025
- symbol,
59026
- kind: "short"
59027
- })
59118
+ long_position.updateTargetPnl(),
59119
+ short_position.updateTargetPnl()
59028
59120
  ]);
59029
59121
  }
59030
59122
  }
59031
- async generate_config_params(payload) {
59032
- const {
59033
- entry,
59034
- stop,
59035
- risk_reward,
59036
- risk,
59037
- symbol,
59038
- with_trades = false
59039
- } = payload;
59040
- const app_config = await this.buildAppConfig({
59041
- entry,
59042
- stop,
59043
- risk_reward,
59044
- risk,
59045
- symbol
59046
- });
59047
- let config2 = generate_config_params(app_config, {
59048
- entry,
59049
- stop,
59050
- risk_reward,
59051
- risk,
59052
- symbol
59053
- });
59054
- if (with_trades) {
59055
- const app_config2 = await this.buildAppConfig({
59056
- entry: config2.entry,
59057
- stop: config2.stop,
59058
- risk_reward: config2.risk_reward,
59059
- risk: config2.risk,
59060
- symbol,
59061
- profit: 0,
59062
- update_db: false
59063
- });
59064
- const { trades } = await this.placeConfigOrders(app_config2, {
59065
- risk_reward: config2.risk_reward,
59066
- entry: config2.entry,
59067
- stop: config2.stop,
59068
- risk_per_trade: config2.risk,
59069
- avg_size: 0,
59070
- neg_pnl: 0,
59071
- min_size: app_config2.min_size,
59072
- symbol
59073
- }, false);
59074
- config2.trades = trades;
59075
- }
59076
- return { ...config2, place_stop: false, profit_percent: 0 };
59077
- }
59078
59123
  async build_short_order(payload) {
59079
- const { symbol, kind } = payload;
59080
- const position2 = await this.syncAccount({
59081
- symbol,
59082
- kind,
59083
- as_view: true
59084
- });
59085
- const position_config = await this.getPositionConfig({
59086
- symbol,
59087
- kind
59088
- });
59089
- if (position2 && position_config && position2.entry > 0) {
59090
- let next_order = position2.next_order;
59091
- let take_profit = position2.take_profit;
59092
- if (next_order && take_profit) {
59093
- let config2 = await this.buildConfigForSymbol({
59094
- symbol,
59095
- risk: position_config.risk,
59096
- risk_reward: position_config.risk_reward,
59097
- kind,
59098
- as_config: true
59099
- });
59100
- const focus = config2.entries.filter((x) => {
59101
- if (kind == "long") {
59102
- return x.entry <= next_order;
59103
- } else {
59104
- return x.entry >= next_order;
59105
- }
59106
- });
59107
- const focus_entry = focus.at(-1);
59108
- if (focus_entry) {
59109
- let entry = focus_entry.entry;
59110
- let risk = Math.abs(focus_entry.neg_pnl);
59111
- return await this.generate_config_params({
59112
- entry,
59113
- stop: take_profit,
59114
- risk_reward: position_config.risk_reward,
59115
- risk,
59116
- symbol
59117
- });
59118
- }
59119
- }
59120
- }
59124
+ const focus_position = await this.getFocusPosition(payload);
59125
+ return await focus_position.build_short_order();
59121
59126
  }
59122
59127
  async extrapolateShortConfig(payload) {
59123
- const { symbol, risk_reward = 199, kind, risk } = payload;
59128
+ const { symbol, kind } = payload;
59124
59129
  let reverse_kind = kind === "long" ? "short" : "long";
59125
- const position2 = await this.syncAccount({
59130
+ const focus_position = await this.getFocusPosition({
59126
59131
  symbol,
59127
- kind: reverse_kind,
59128
- as_view: true
59132
+ kind: reverse_kind
59133
+ });
59134
+ return await focus_position.extrapolateConfig({
59135
+ kind
59129
59136
  });
59130
- if (position2) {
59131
- let entry = position2.next_order || position2.avg_liquidation;
59132
- if (kind == "short" && entry < 0) {
59133
- const symbol_config = await this.recomputeSymbolConfig({
59134
- symbol
59135
- });
59136
- entry = symbol_config?.support;
59137
- }
59138
- return await this.generate_config_params({
59139
- entry,
59140
- stop: position2.take_profit,
59141
- risk_reward,
59142
- risk: risk || position2.target_pnl,
59143
- symbol
59144
- });
59145
- }
59146
- return null;
59147
59137
  }
59148
59138
  async placeMarketOrder(payload) {
59149
- const { symbol, kind, quantity } = payload;
59150
- const symbol_config = await this.recomputeSymbolConfig({
59151
- symbol
59152
- });
59153
- await this.exchange.placeMarketOrder({
59139
+ const { symbol, kind } = payload;
59140
+ const focus_position = await this.getFocusPosition(payload);
59141
+ await focus_position.placeMarketOrder(payload);
59142
+ await this.initializePositions({
59154
59143
  symbol,
59155
59144
  kind,
59156
- quantity,
59157
- price_places: symbol_config.price_places,
59158
- decimal_places: symbol_config.decimal_places
59159
- });
59160
- await this.syncAccount({
59161
- symbol,
59162
- update: true,
59163
- live_refresh: true
59145
+ update: true
59164
59146
  });
59165
59147
  }
59166
59148
  async placeSingleOrder(payload) {
59167
59149
  const { symbol, kind } = payload;
59168
- const positions = await this.syncAccount({
59169
- live_refresh: true,
59170
- update: true,
59171
- symbol
59172
- });
59173
- const long_position = positions.find((x) => x.kind === "long");
59174
- const short_position = positions.find((x) => x.kind === "short");
59175
- const long_config = await this.getPositionConfig({
59150
+ const long_position = await this.getFocusPosition({
59176
59151
  symbol,
59177
59152
  kind: "long"
59178
59153
  });
59179
- const short_config = await this.getPositionConfig({
59154
+ const short_position = await this.getFocusPosition({
59180
59155
  symbol,
59181
59156
  kind: "short"
59182
59157
  });
59183
- const focus_config = kind === "long" ? long_config : short_config;
59184
59158
  const focus_position = kind === "long" ? long_position : short_position;
59185
- const track_position = kind === "long" ? short_position : long_position;
59186
- const follow = focus_config.follow || focus_position.follow;
59187
- const threshold_qty = focus_config.threshold_qty || focus_position.threshold_qty;
59188
- if (!follow) {
59189
- return "No follow set";
59190
- }
59191
- let should_place_order = false;
59192
- if (threshold_qty === 0) {
59193
- should_place_order = true;
59194
- }
59195
- if (threshold_qty > 0 && track_position.quantity >= threshold_qty) {
59196
- should_place_order = true;
59197
- }
59198
- if (focus_position.quantity === 0) {
59199
- should_place_order = true;
59200
- }
59201
- if (track_position.quantity !== focus_position.quantity && focus_position.quantity < track_position.quantity && should_place_order) {
59202
- const remaining_quantity = Math.abs(track_position.quantity - focus_position.quantity);
59203
- await this.placeMarketOrder({
59204
- symbol,
59205
- kind,
59206
- quantity: remaining_quantity
59207
- });
59208
- }
59159
+ return await focus_position.placeSingleOrder({
59160
+ long_position,
59161
+ short_position
59162
+ });
59209
59163
  }
59210
59164
  async increasePositionAtStop(payload) {
59211
- const { symbol, kind, place = false, increase = true } = payload;
59212
- const position2 = await this.syncAccount({
59213
- symbol,
59214
- kind,
59215
- as_view: true
59216
- });
59217
- console.log(position2);
59218
- let price_params = {
59219
- price: payload.price,
59220
- quantity: payload.quantity
59221
- };
59222
- if (!payload.price && position2 && position2.stop_loss) {
59223
- price_params.price = position2.stop_loss.price;
59224
- }
59225
- if (!payload.quantity && position2 && position2.stop_loss) {
59226
- price_params.quantity = position2.stop_loss.quantity;
59227
- }
59228
- if (price_params.price && price_params.quantity) {
59229
- const { price, quantity } = price_params;
59230
- const symbol_config = await this.recomputeSymbolConfig({
59231
- symbol
59232
- });
59233
- const price_places = symbol_config.price_places;
59234
- const decimal_places = symbol_config.decimal_places;
59235
- if (place) {
59236
- await this.cancelOrders({
59237
- symbol,
59238
- kind,
59239
- limit: true
59240
- });
59241
- }
59242
- return await this.exchange.customStopLoss({
59243
- symbol,
59244
- kind,
59245
- stop: price,
59246
- quantity,
59247
- price_places,
59248
- decimal_places,
59249
- increase,
59250
- place
59251
- });
59252
- }
59165
+ const focus_position = await this.getFocusPosition(payload);
59166
+ return await focus_position.increasePositionAtStop(payload);
59253
59167
  }
59254
59168
  async triggerTradeFromConfig(payload) {
59255
- const {
59256
- symbol,
59257
- kind,
59258
- place = true,
59259
- stop,
59260
- use_current,
59261
- ignore_config,
59262
- risky
59263
- } = payload;
59264
- const position2 = await this.syncAccount({
59265
- symbol,
59266
- kind,
59267
- as_view: true
59268
- });
59269
- const config2 = await this.getPositionConfig({
59270
- symbol,
59271
- kind
59272
- });
59273
- let condition = ignore_config ? true : position2?.config;
59274
- if (condition) {
59275
- let entry = payload.tp ? position2.entry || config2.entry : config2.entry;
59276
- const v = stop ? "place_stop_orders" : risky ? "dangerous_entry_orders" : "place_limit_orders";
59277
- return await this.placeSharedOrder(v, {
59278
- symbol,
59279
- entry,
59280
- stop: config2.stop,
59281
- risk_reward: config2.risk_reward,
59282
- risk: config2.risk,
59283
- place,
59284
- raw: payload.raw,
59285
- use_current,
59286
- stop_percent: config2.stop_percent || 100
59287
- });
59288
- }
59169
+ const focus_position = await this.getFocusPosition(payload);
59170
+ return await focus_position.triggerTradeFromConfig(payload);
59289
59171
  }
59290
59172
  async verifyStopLoss(payload) {
59291
59173
  const { symbol, kind, revert } = payload;
@@ -59467,59 +59349,19 @@ class ExchangeAccount {
59467
59349
  }
59468
59350
  async updateTargetPnl(payload) {
59469
59351
  const { symbol, kind } = payload;
59470
- const position2 = await this.syncAccount({
59352
+ const focus_position = await this.getFocusPosition({
59471
59353
  symbol,
59472
59354
  kind
59473
59355
  });
59474
- if (position2?.expand?.config) {
59475
- const config2 = position2.expand.config;
59476
- let _profit = config2.profit;
59477
- let risk = config2.risk;
59478
- let next_risk = position2.next_risk;
59479
- let _profit_percent = config2?.profit_percent;
59480
- if (_profit_percent && (position2?.quantity || 0) > 0) {
59481
- _profit = to_f2(position2.quantity * _profit_percent * position2.entry / 100);
59482
- next_risk = risk + _profit;
59483
- }
59484
- await this.app_db.update_db_position(position2, {
59485
- target_pnl: _profit,
59486
- next_risk
59487
- });
59488
- return _profit;
59489
- }
59490
- return 0;
59356
+ return await focus_position.updateTargetPnl();
59491
59357
  }
59492
59358
  async updateRiskOnEmpty(payload) {
59493
59359
  const { symbol, kind } = payload;
59494
- const position2 = await this.syncAccount({
59360
+ const focus_position = await this.getFocusPosition({
59495
59361
  symbol,
59496
59362
  kind
59497
59363
  });
59498
- if (position2 && position2.quantity === 0) {
59499
- if (position2.next_risk && position2.next_risk > 0) {
59500
- await this.getPositionConfig({
59501
- symbol,
59502
- kind,
59503
- params: {
59504
- risk: position2.next_risk
59505
- }
59506
- });
59507
- console.log(`Updated ${kind} position config for ${symbol}: risk = ${position2.next_risk}`);
59508
- return {
59509
- updated: true,
59510
- symbol,
59511
- kind,
59512
- old_risk: position2.expand?.config?.risk,
59513
- new_risk: position2.next_risk
59514
- };
59515
- }
59516
- }
59517
- return {
59518
- updated: false,
59519
- symbol,
59520
- kind,
59521
- reason: position2 ? position2.quantity > 0 ? "Position not empty" : "No next_risk available" : "Position not found"
59522
- };
59364
+ return await focus_position.updateRiskOnEmpty();
59523
59365
  }
59524
59366
  async updateGoodHedgeConfig(payload) {
59525
59367
  const {
@@ -59531,19 +59373,20 @@ class ExchangeAccount {
59531
59373
  update = true
59532
59374
  } = payload;
59533
59375
  let _params = params;
59376
+ const long_position = await this.getFocusPosition({
59377
+ symbol,
59378
+ kind: "long"
59379
+ });
59380
+ const short_position = await this.getFocusPosition({
59381
+ symbol,
59382
+ kind: "short"
59383
+ });
59534
59384
  if (!params) {
59535
59385
  const result = await this.exchange.analyzeCandlesticks({ symbol });
59536
59386
  const support_price = Math.min(...Object.keys(result.support).map(Number));
59537
- const symbol_config = await this.recomputeSymbolConfig({ symbol });
59538
- const config2 = await this.getPositionConfig({
59539
- symbol,
59540
- kind: "long"
59541
- });
59542
- const position2 = await this.syncAccount({
59543
- symbol,
59544
- kind: "long",
59545
- as_view: true
59546
- });
59387
+ const symbol_config = long_position.symbol_config;
59388
+ const config2 = await long_position.getConfig();
59389
+ const position2 = long_position.getInstance();
59547
59390
  const bot_position = {
59548
59391
  kind: "long",
59549
59392
  entry: position2.entry,
@@ -59560,9 +59403,7 @@ class ExchangeAccount {
59560
59403
  });
59561
59404
  }
59562
59405
  if (update) {
59563
- await this.getPositionConfig({
59564
- symbol,
59565
- kind: "short",
59406
+ await short_position.getConfig({
59566
59407
  params: {
59567
59408
  entry: _params.support,
59568
59409
  stop: _params.resistance,
@@ -59571,22 +59412,15 @@ class ExchangeAccount {
59571
59412
  });
59572
59413
  }
59573
59414
  if (update_tp) {
59574
- await this.getPositionConfig({
59575
- symbol,
59576
- kind: "long",
59415
+ await long_position.getConfig({
59577
59416
  params: {
59578
59417
  profit_percent: _params.profit_percent
59579
59418
  }
59580
59419
  });
59581
- await this.updateTargetPnl({
59582
- symbol,
59583
- kind: "long"
59584
- });
59420
+ await long_position.updateTargetPnl();
59585
59421
  }
59586
59422
  if (place) {
59587
- await this.placeTrade({
59588
- symbol,
59589
- kind: "short",
59423
+ await short_position.placeTrade({
59590
59424
  limit: true,
59591
59425
  ignore_config: true
59592
59426
  });
@@ -59595,37 +59429,13 @@ class ExchangeAccount {
59595
59429
  }
59596
59430
  async placeOppositeTradeAction(payload) {
59597
59431
  const { symbol, kind, data } = payload;
59598
- const position2 = await this.syncAccount({
59432
+ const focus_position = await this.getFocusPosition({
59599
59433
  symbol,
59600
- kind,
59601
- as_view: true
59434
+ kind
59435
+ });
59436
+ return await focus_position.placeOppositeTradeAction({
59437
+ data
59602
59438
  });
59603
- if (position2.avg_qty !== data.avg.quantity) {
59604
- const config2 = await this.getPositionConfig({
59605
- symbol,
59606
- kind
59607
- });
59608
- await this.app_db.updateScheduledTrade(config2.id, {
59609
- entry: data.entry,
59610
- stop: data.stop,
59611
- risk: data.risk_per_trade,
59612
- profit_percent: data.profit_percent,
59613
- risk_reward: data.risk_reward
59614
- });
59615
- await this.placeTrade({
59616
- symbol,
59617
- kind,
59618
- place: true,
59619
- ignore_config: true
59620
- });
59621
- await this.placeTrade({
59622
- symbol,
59623
- kind,
59624
- place: true,
59625
- stop: true,
59626
- ignore_config: true
59627
- });
59628
- }
59629
59439
  }
59630
59440
  async buildOppositeTrades(payload) {
59631
59441
  const { symbol, kind, place, place_symbol } = payload;
@@ -59655,60 +59465,20 @@ class ExchangeAccount {
59655
59465
  }
59656
59466
  async runSimulation(payload) {
59657
59467
  const { symbol, kind, iterations = 2, raw = false } = payload;
59658
- const positions = await this.syncAccount({
59659
- symbol,
59660
- as_view: true
59661
- });
59662
- const symbol_config = await this.recomputeSymbolConfig({
59663
- symbol
59664
- });
59665
- const long_position = positions.find((x) => x.kind === "long");
59666
- const short_position = positions.find((x) => x.kind === "short");
59667
- const long_config = await this.getPositionConfig({
59468
+ const long_position = await this.getFocusPosition({
59668
59469
  symbol,
59669
59470
  kind: "long"
59670
59471
  });
59671
- const short_config = await this.getPositionConfig({
59472
+ const short_position = await this.getFocusPosition({
59672
59473
  symbol,
59673
59474
  kind: "short"
59674
59475
  });
59675
- const focus_config = kind === "long" ? long_config : short_config;
59676
- const short_tp_factor = short_config.profit_percent / long_config.profit_percent;
59677
- const reduce_ratio = focus_config.reduce_ratio;
59678
- const budget = focus_config.risk;
59679
- const risk_reward = focus_config.risk_reward;
59680
- const tp_percent = long_config.profit_percent;
59681
- const fee_percent = symbol_config.fee_percent;
59682
- const strategy_config = {
59683
- tp_percent,
59684
- short_tp_factor,
59685
- fee_percent,
59686
- budget,
59687
- risk_reward,
59688
- reduce_ratio,
59689
- global_config: symbol_config
59690
- };
59691
- const strategy2 = new Strategy({
59692
- long: {
59693
- entry: long_position.entry,
59694
- quantity: long_position.quantity,
59695
- avg_price: long_position.avg_price,
59696
- avg_qty: long_position.avg_qty
59697
- },
59698
- short: {
59699
- entry: short_position.entry,
59700
- quantity: short_position.quantity,
59701
- avg_price: short_position.avg_price,
59702
- avg_qty: short_position.avg_qty
59703
- },
59704
- config: strategy_config
59705
- });
59706
- if (raw) {
59707
- return strategy2;
59708
- }
59709
- return strategy2.runIterations({
59476
+ const focus_position = kind === "long" ? long_position : short_position;
59477
+ return focus_position.runSimulation({
59710
59478
  iterations,
59711
- kind
59479
+ raw,
59480
+ long_position,
59481
+ short_position
59712
59482
  });
59713
59483
  }
59714
59484
  async getCurrentRun(payload) {
@@ -59770,34 +59540,12 @@ class ExchangeAccount {
59770
59540
  return this.app_db.getSymbolConfigFromDB(symbol);
59771
59541
  }
59772
59542
  async buildConfigForSymbol(payload) {
59773
- const {
59543
+ const { symbol, kind = "long" } = payload;
59544
+ const focus_position = await this.getFocusPosition({
59774
59545
  symbol,
59775
- risk,
59776
- risk_reward = 199,
59777
- as_config = false,
59778
- kind = "long"
59779
- } = payload;
59780
- const symbol_config = await this.recomputeSymbolConfig({
59781
- symbol
59782
- });
59783
- const long_config = await this.generate_config_params({
59784
- entry: kind === "long" ? symbol_config.resistance : symbol_config.support,
59785
- stop: kind === "long" ? symbol_config.support : symbol_config.resistance,
59786
- risk_reward,
59787
- risk,
59788
- symbol
59546
+ kind
59789
59547
  });
59790
- if (as_config) {
59791
- const app_config = buildAppConfig(symbol_config, {
59792
- entry: long_config.entry,
59793
- stop: long_config.stop,
59794
- risk_reward,
59795
- risk: long_config.risk,
59796
- symbol
59797
- });
59798
- return app_config;
59799
- }
59800
- return long_config;
59548
+ return await focus_position.buildConfigForSymbol(payload);
59801
59549
  }
59802
59550
  async triggerBullishMarket(payload) {
59803
59551
  let { symbol, profit_percent = 10, risk_reward = 199 } = payload;
@@ -59903,15 +59651,9 @@ class ExchangeAccount {
59903
59651
  const all_open_symbols = await this.exchange.getOpenPositions();
59904
59652
  await new Promise((resolve) => setTimeout(resolve, interval * 1000));
59905
59653
  for (const symbol of Array.from(new Set(symbols.concat(all_open_symbols)))) {
59906
- await this.getLiveExchangeInstance({ symbol, refresh: true });
59654
+ await this.initializePositions({ symbol, kind: "long", update: true });
59907
59655
  await new Promise((resolve) => setTimeout(resolve, 1000));
59908
59656
  }
59909
- for (const symbol of all_open_symbols) {
59910
- await this.syncAccount({
59911
- symbol,
59912
- update: true
59913
- });
59914
- }
59915
59657
  }
59916
59658
  async updateAllPositionsWithNoConfig(payload) {
59917
59659
  const { kind } = payload;
@@ -60223,139 +59965,32 @@ class ExchangeAccount {
60223
59965
  }
60224
59966
  async computeTargetPnl(payload) {
60225
59967
  const { symbol, kind } = payload;
60226
- const reverse_kind = kind === "long" ? "short" : "long";
60227
- const root_position = await this.syncAccount({
59968
+ const focus_position = await this.getFocusPosition({
60228
59969
  symbol,
60229
59970
  kind
60230
59971
  });
60231
- const reverse_position = await this.syncAccount({
59972
+ const secondary_position = await this.getFocusPosition({
60232
59973
  symbol,
60233
- kind: reverse_kind
59974
+ kind: kind === "long" ? "short" : "long"
59975
+ });
59976
+ return await focus_position.computeTargetPnl({
59977
+ secondary: secondary_position
60234
59978
  });
60235
- if (reverse_position?.expand?.config && root_position.quantity > 0) {
60236
- const reverse_config = reverse_position.expand.config;
60237
- const diff = Math.abs(reverse_config.stop - root_position.entry);
60238
- const result = to_f2(diff * root_position.quantity);
60239
- if (root_position.target_pnl !== result) {
60240
- await this.app_db.update_db_position(root_position, {
60241
- target_pnl: result
60242
- });
60243
- await this.getPositionConfig({
60244
- kind: reverse_kind,
60245
- symbol,
60246
- params: {
60247
- ...reverse_config,
60248
- risk: result
60249
- }
60250
- });
60251
- }
60252
- return result;
60253
- }
60254
- return 0;
60255
59979
  }
60256
59980
  async placeStopLimit(payload) {
60257
- const { symbol, kind, place, stop, quantity: _quantity } = payload;
60258
- const position2 = await this.syncAccount({
60259
- symbol,
60260
- kind,
60261
- as_view: true
60262
- });
60263
- if (position2.avg_qty && position2.avg_qty > 0) {
60264
- const spread = 1.00005;
60265
- const qty = _quantity || position2.avg_qty - position2.quantity;
60266
- const symbol_config = await this.recomputeSymbolConfig({ symbol });
60267
- const orders = [
60268
- {
60269
- kind,
60270
- stop,
60271
- quantity: to_f2(qty, symbol_config.decimal_places),
60272
- side: kind === "long" ? "buy" : "sell",
60273
- price: to_f2(kind === "short" ? stop * spread ** -1 : stop * spread, symbol_config.price_places)
60274
- }
60275
- ];
60276
- if (place) {
60277
- return this.exchange.placeBadStopEntry({
60278
- symbol,
60279
- orders,
60280
- price_places: symbol_config.price_places,
60281
- decimal_places: symbol_config.decimal_places
60282
- });
60283
- }
60284
- return orders;
60285
- }
60286
- return [];
59981
+ const focus_position = await this.getFocusPosition(payload);
59982
+ return await focus_position.placeStopLimit(payload);
60287
59983
  }
60288
59984
  async placeTrade(payload) {
60289
- const {
60290
- symbol,
60291
- kind,
60292
- place,
60293
- tp,
60294
- limit = true,
60295
- raw: _raw,
60296
- cancel,
60297
- stop,
60298
- ignore_config,
60299
- target_pnl,
60300
- risky
60301
- } = payload;
60302
- if (cancel) {
60303
- await this.cancelOrders({
60304
- symbol,
60305
- kind
60306
- });
60307
- }
60308
- if (limit) {
60309
- return await this.triggerTradeFromConfig({
60310
- symbol,
60311
- kind,
60312
- raw: payload.raw,
60313
- stop,
60314
- ignore_config,
60315
- place,
60316
- risky
60317
- });
60318
- }
60319
- await this.syncAccount({
60320
- symbol,
60321
- live_refresh: true,
60322
- update: true
60323
- });
60324
- await this.updateConfigPnl({
60325
- symbol,
60326
- kind
59985
+ const focus_position = await this.getFocusPosition({
59986
+ symbol: payload.symbol,
59987
+ kind: payload.kind
60327
59988
  });
60328
- if (tp) {
60329
- await this.placeProfitAndStop({
60330
- symbol,
60331
- trigger: true,
60332
- target_pnl
60333
- });
60334
- }
60335
- return [];
59989
+ return await focus_position.placeTrade(payload);
60336
59990
  }
60337
59991
  async updateConfigPnl(payload) {
60338
- const { symbol, kind } = payload;
60339
- const position2 = await this.syncAccount({
60340
- symbol,
60341
- kind
60342
- });
60343
- if (!position2?.config) {
60344
- const config2 = await this.getPositionConfig({ symbol, kind });
60345
- if (config2) {
60346
- await this.app_db.update_db_position(position2, { config: config2.id });
60347
- await this.updateTargetPnl({
60348
- symbol,
60349
- kind
60350
- });
60351
- await this.app_db.update_db_position(position2, { config: null });
60352
- }
60353
- } else {
60354
- await this.updateTargetPnl({
60355
- symbol,
60356
- kind
60357
- });
60358
- }
59992
+ const focus_position = await this.getFocusPosition(payload);
59993
+ return await focus_position.updateConfigPnl();
60359
59994
  }
60360
59995
  async determineReduceTp(payload) {
60361
59996
  const { symbol, factor } = payload;
@@ -60370,10 +60005,10 @@ class ExchangeAccount {
60370
60005
  const gap_cost = gap * long_position.quantity * factor;
60371
60006
  const long_diff = gap_cost / (short_position.entry * short_position.quantity);
60372
60007
  const short_diff = gap_cost / (long_position.entry * long_position.quantity);
60373
- const long_tp = to_f2((long_diff + 1) * short_position.entry, symbol_config.price_places);
60374
- const short_tp = to_f2((short_diff + 1) ** -1 * long_position.entry, symbol_config.price_places);
60375
- const long_percent = to_f2(Math.abs(long_tp - long_position.entry) * 100 / long_position.entry, "%.4f");
60376
- const short_percent = to_f2(Math.abs(short_tp - short_position.entry) * 100 / short_position.entry, "%.4f");
60008
+ const long_tp = to_f((long_diff + 1) * short_position.entry, symbol_config.price_places);
60009
+ const short_tp = to_f((short_diff + 1) ** -1 * long_position.entry, symbol_config.price_places);
60010
+ const long_percent = to_f(Math.abs(long_tp - long_position.entry) * 100 / long_position.entry, "%.4f");
60011
+ const short_percent = to_f(Math.abs(short_tp - short_position.entry) * 100 / short_position.entry, "%.4f");
60377
60012
  return {
60378
60013
  long_diff,
60379
60014
  short_diff,
@@ -60387,7 +60022,6 @@ class ExchangeAccount {
60387
60022
  }
60388
60023
  async profitWithinGapStrategy(payload) {
60389
60024
  const { symbol } = payload;
60390
- let reward_factor = 1;
60391
60025
  console.log("Fetching positions for ", symbol);
60392
60026
  const positions = await this.syncAccount({
60393
60027
  symbol,
@@ -60401,70 +60035,11 @@ class ExchangeAccount {
60401
60035
  if (!strategy2) {
60402
60036
  return;
60403
60037
  }
60404
- const risk = strategy2.risk;
60405
60038
  const kind = strategy2.kind;
60406
- const support = strategy2.support;
60407
- const resistance = strategy2.resistance;
60408
- console.log("Getting long and short positions for ", symbol);
60409
- const long_position = positions.find((k) => k.kind === "long");
60410
- const short_position = positions.find((k) => k.kind === "short");
60411
- console.log("Getting focus position for ", symbol, kind);
60412
- if (strategy2.max_reward_factor === 0) {
60413
- reward_factor = strategy2.reward_factor;
60414
- }
60415
- if (focus_position.avg_qty >= focus_position.quantity && strategy2.max_reward_factor) {
60416
- if (strategy2.dynamic) {
60417
- const quantity_ratio = focus_position.quantity / focus_position.avg_qty;
60418
- reward_factor = to_f2(quantity_ratio ** 2 * strategy2.max_reward_factor, "%.2f");
60419
- } else {
60420
- reward_factor = to_f2(focus_position.quantity * strategy2.max_reward_factor / focus_position.avg_qty, "%.4f");
60421
- }
60422
- } else {
60423
- reward_factor = strategy2.reward_factor;
60424
- }
60425
- console.log("Getting entry and stop for ", symbol, kind);
60426
- const entry = kind === "long" ? resistance : support;
60427
- const stop = kind === "long" ? support : resistance;
60428
- console.log("Building app config for ", symbol, kind);
60429
- const initial_app_config = await this.buildAppConfig({
60430
- entry,
60431
- stop,
60432
- risk_reward: 199,
60433
- risk,
60434
- symbol
60435
- });
60436
- console.log("Computing risk reward for ", symbol, kind);
60437
- const risk_reward = strategy2.risk_reward || computeRiskReward({
60438
- app_config: initial_app_config,
60439
- entry: initial_app_config.entry,
60440
- stop: initial_app_config.stop,
60441
- risk_per_trade: initial_app_config.risk_per_trade
60442
- });
60443
- console.log("Re-computing app config for ", symbol, kind);
60444
- const { entries, last_value, ...app_config } = await this.buildAppConfig({
60445
- entry: initial_app_config.entry,
60446
- stop: initial_app_config.stop,
60447
- risk_reward,
60448
- risk,
60449
- symbol
60450
- });
60451
- console.log("Computing profit percent for ", symbol, kind);
60452
- const pnl = reward_factor * risk;
60453
- const profit_percent = to_f2(pnl * 100 / (last_value.avg_entry * last_value.avg_size), "%.4f");
60454
- let config2 = {
60455
- entry,
60456
- stop,
60457
- risk,
60458
- risk_reward,
60459
- profit_percent
60460
- };
60461
- console.log("Saving new config for ", symbol, kind);
60462
- const data = await this.getPositionConfig({
60039
+ const { entries, last_value, ...app_config } = await this.tradeConfig({
60463
60040
  symbol,
60464
- kind,
60465
- params: config2
60041
+ kind
60466
60042
  });
60467
- console.log("Checking orders to place for ", symbol, kind);
60468
60043
  await this.placeTrade({
60469
60044
  symbol,
60470
60045
  kind,
@@ -60472,10 +60047,6 @@ class ExchangeAccount {
60472
60047
  ignore_config: true,
60473
60048
  tp: true
60474
60049
  });
60475
- config2 = {
60476
- ...config2,
60477
- ...data
60478
- };
60479
60050
  if (focus_position.avg_qty < last_value.avg_size) {
60480
60051
  console.log("Placing trade for ", symbol, kind);
60481
60052
  await this.placeTrade({
@@ -60487,15 +60058,9 @@ class ExchangeAccount {
60487
60058
  }
60488
60059
  console.log("Checking if focus position has quantity for ", symbol, kind);
60489
60060
  return {
60490
- positions: {
60491
- long: long_position,
60492
- short: short_position
60493
- },
60494
60061
  config_details: {
60495
60062
  app_config,
60496
- last_value,
60497
- config: config2,
60498
- pnl
60063
+ last_value
60499
60064
  }
60500
60065
  };
60501
60066
  }