@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.
@@ -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(object2, value2) {
26185
+ module2.exports = function setToStringTag(object2, 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(object2, toStringTag, {
26194
26194
  configurable: !nonConfigurable,
26195
26195
  enumerable: false,
26196
- value: value2,
26196
+ value,
26197
26197
  writable: false
26198
26198
  });
26199
26199
  } else {
26200
- object2[toStringTag] = value2;
26200
+ object2[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);
@@ -59303,267 +59303,8 @@ class AppDatabase {
59303
59303
  }
59304
59304
  }
59305
59305
 
59306
- // src/helpers/pnl.ts
59307
- function determine_position_size(entry, stop, budget) {
59308
- let stop_percent = Math.abs(entry - stop) / entry;
59309
- let size = budget / stop_percent / entry;
59310
- return size;
59311
- }
59312
- function determine_risk(entry, stop, quantity) {
59313
- let stop_percent = Math.abs(entry - stop) / entry;
59314
- let risk = quantity * stop_percent * entry;
59315
- return risk;
59316
- }
59317
- function determine_close_price(entry, pnl, quantity, kind, single = false, leverage = 1) {
59318
- const dollar_value = entry / leverage;
59319
- const position = dollar_value * quantity;
59320
- if (position) {
59321
- let percent = pnl / position;
59322
- let difference = position * percent / quantity;
59323
- let result;
59324
- if (kind === "long") {
59325
- result = difference + entry;
59326
- } else {
59327
- result = entry - difference;
59328
- }
59329
- if (single) {
59330
- return result;
59331
- }
59332
- return result;
59333
- }
59334
- return 0;
59335
- }
59336
- function determine_amount_to_sell(entry, quantity, sell_price, pnl, kind, places = "%.3f") {
59337
- const _pnl = determine_pnl(entry, sell_price, quantity, kind);
59338
- const ratio = pnl / to_f(Math.abs(_pnl), places);
59339
- quantity = quantity * ratio;
59340
- return to_f(quantity, places);
59341
- }
59342
- function determine_pnl(entry, close_price, quantity, kind, contract_size, places = "%.2f") {
59343
- if (contract_size) {
59344
- const direction = kind === "long" ? 1 : -1;
59345
- return quantity * contract_size * direction * (1 / entry - 1 / close_price);
59346
- }
59347
- let difference = entry - close_price;
59348
- if (kind === "long") {
59349
- difference = close_price - entry;
59350
- }
59351
- return to_f(difference * quantity, places);
59352
- }
59353
- function position(entry, quantity, kind, leverage = 1) {
59354
- const direction = { long: 1, short: -1 };
59355
- return parseFloat((direction[kind] * quantity * (entry / leverage)).toFixed(3));
59356
- }
59357
- function to_f(value, places) {
59358
- if (value) {
59359
- let pp = parseInt(places.replace("%.", "").replace("f", ""));
59360
- return parseFloat(value.toFixed(pp));
59361
- }
59362
- return value;
59363
- }
59364
- var value = {
59365
- determine_risk,
59366
- determine_position_size,
59367
- determine_close_price,
59368
- determine_pnl,
59369
- position,
59370
- determine_amount_to_sell,
59371
- to_f
59372
- };
59373
- var pnl_default = value;
59374
-
59375
- // src/helpers/trade_utils.ts
59376
- function to_f2(value2, places = "%.1f") {
59377
- let v = typeof value2 === "string" ? parseFloat(value2) : value2;
59378
- const formattedValue = places.replace("%.", "").replace("f", "");
59379
- return parseFloat(v.toFixed(parseInt(formattedValue)));
59380
- }
59381
- function determine_amount_to_sell2(entry, quantity, sell_price, pnl, kind, places = "%.3f") {
59382
- const _pnl = determine_pnl2(entry, sell_price, quantity, kind);
59383
- const ratio = pnl / to_f2(Math.abs(_pnl), places);
59384
- quantity = quantity * ratio;
59385
- return to_f2(quantity, places);
59386
- }
59387
- function determine_position_size2({
59388
- entry,
59389
- stop,
59390
- budget,
59391
- percent,
59392
- min_size,
59393
- notional_value,
59394
- as_coin = true,
59395
- places = "%.3f"
59396
- }) {
59397
- let stop_percent = stop ? Math.abs(entry - stop) / entry : percent;
59398
- if (stop_percent && budget) {
59399
- let size = budget / stop_percent;
59400
- let notion_value = size * entry;
59401
- if (notional_value && notional_value > notion_value) {
59402
- size = notional_value / entry;
59403
- }
59404
- if (as_coin) {
59405
- size = size / entry;
59406
- if (min_size && min_size === 1) {
59407
- return to_f2(Math.round(size), places);
59408
- }
59409
- }
59410
- return to_f2(size, places);
59411
- }
59412
- return;
59413
- }
59414
- function determine_average_entry_and_size(orders, places = "%.3f", price_places = "%.1f") {
59415
- const sum_values = orders.reduce((sum, order) => sum + order.price * order.quantity, 0);
59416
- const total_quantity = orders.reduce((sum, order) => sum + order.quantity, 0);
59417
- const avg_price = total_quantity ? to_f2(sum_values / total_quantity, price_places) : 0;
59418
- return {
59419
- entry: avg_price,
59420
- price: avg_price,
59421
- quantity: to_f2(total_quantity, places)
59422
- };
59423
- }
59424
- var createArray = (start, stop, step) => {
59425
- const result = [];
59426
- let current = start;
59427
- while (current <= stop) {
59428
- result.push(current);
59429
- current += step;
59430
- }
59431
- return result;
59432
- };
59433
- var groupIntoPairsWithSumLessThan = (arr, targetSum, key = "quantity", firstSize = 0) => {
59434
- if (firstSize) {
59435
- const totalSize = arr.reduce((sum, order) => sum + order[key], 0);
59436
- const remainingSize = totalSize - firstSize;
59437
- let newSum = 0;
59438
- let newArray = [];
59439
- let lastIndex = 0;
59440
- for (let i2 = 0;i2 < arr.length; i2++) {
59441
- if (newSum < remainingSize) {
59442
- newSum += arr[i2][key];
59443
- newArray.push(arr[i2]);
59444
- lastIndex = i2;
59445
- }
59446
- }
59447
- const lastGroup = arr.slice(lastIndex + 1);
59448
- const previousPair = groupInPairs(newArray, key, targetSum);
59449
- if (lastGroup.length > 0) {
59450
- previousPair.push(lastGroup);
59451
- }
59452
- return previousPair;
59453
- }
59454
- return groupInPairs(arr, key, targetSum);
59455
- };
59456
- function groupInPairs(_arr, key, targetSum) {
59457
- const result = [];
59458
- let currentSum = 0;
59459
- let currentGroup = [];
59460
- for (let i2 = 0;i2 < _arr.length; i2++) {
59461
- currentSum += _arr[i2][key];
59462
- currentGroup.push(_arr[i2]);
59463
- if (currentSum >= targetSum) {
59464
- result.push(currentGroup);
59465
- currentGroup = [];
59466
- currentSum = 0;
59467
- }
59468
- }
59469
- return result;
59470
- }
59471
- var computeTotalAverageForEachTrade = (trades, config2) => {
59472
- let _take_profit = config2.take_profit;
59473
- let kind = config2.kind;
59474
- let entryToUse = kind === "short" ? Math.min(config2.entry, config2.stop) : Math.max(config2.entry, config2.stop);
59475
- let _currentEntry = config2.currentEntry || entryToUse;
59476
- let less = trades.filter((p) => kind === "long" ? p.entry <= _currentEntry : p.entry >= _currentEntry);
59477
- let rrr = trades.map((r2, i2) => {
59478
- let considered = [];
59479
- if (kind === "long") {
59480
- considered = trades.filter((p) => p.entry > _currentEntry);
59481
- } else {
59482
- considered = trades.filter((p) => p.entry < _currentEntry);
59483
- }
59484
- const x_pnl = 0;
59485
- const remaining = less.filter((o) => {
59486
- if (kind === "long") {
59487
- return o.entry >= r2.entry;
59488
- }
59489
- return o.entry <= r2.entry;
59490
- });
59491
- if (remaining.length === 0) {
59492
- return { ...r2, pnl: x_pnl };
59493
- }
59494
- const start = kind === "long" ? Math.max(...remaining.map((o) => o.entry)) : Math.min(...remaining.map((o) => o.entry));
59495
- considered = considered.map((o) => ({ ...o, entry: start }));
59496
- considered = considered.concat(remaining);
59497
- let avg_entry = determine_average_entry_and_size([
59498
- ...considered.map((o) => ({
59499
- price: o.entry,
59500
- quantity: o.quantity
59501
- })),
59502
- {
59503
- price: _currentEntry,
59504
- quantity: config2.currentQty || 0
59505
- }
59506
- ], config2.decimal_places, config2.price_places);
59507
- let _pnl = r2.pnl;
59508
- let sell_price = r2.sell_price;
59509
- let entry_pnl = r2.pnl;
59510
- if (_take_profit) {
59511
- _pnl = pnl_default.determine_pnl(avg_entry.price, _take_profit, avg_entry.quantity, kind);
59512
- sell_price = _take_profit;
59513
- entry_pnl = pnl_default.determine_pnl(r2.entry, _take_profit, avg_entry.quantity, kind);
59514
- }
59515
- const loss = pnl_default.determine_pnl(avg_entry.price, r2.stop, avg_entry.quantity, kind);
59516
- let new_stop = r2.new_stop;
59517
- const entry_loss = pnl_default.determine_pnl(r2.entry, new_stop, avg_entry.quantity, kind);
59518
- let min_profit = 0;
59519
- let min_entry_profit = 0;
59520
- if (config2.min_profit) {
59521
- min_profit = pnl_default.determine_close_price(avg_entry.price, config2.min_profit, avg_entry.quantity, kind);
59522
- min_entry_profit = pnl_default.determine_close_price(r2.entry, config2.min_profit, avg_entry.quantity, kind);
59523
- }
59524
- let x_fee = r2.fee;
59525
- if (config2.fee) {
59526
- x_fee = config2.fee * r2.stop * avg_entry.quantity;
59527
- }
59528
- let tp_close = pnl_default.determine_close_price(r2.entry, Math.abs(entry_loss) * (config2.rr || 1) + x_fee, avg_entry.quantity, kind);
59529
- return {
59530
- ...r2,
59531
- x_fee: to_f2(x_fee, "%.2f"),
59532
- avg_entry: avg_entry.price,
59533
- avg_size: avg_entry.quantity,
59534
- entry_pnl: to_f2(entry_pnl, "%.2f"),
59535
- entry_loss: to_f2(entry_loss, "%.2f"),
59536
- min_entry_pnl: to_f2(min_entry_profit, "%.2f"),
59537
- pnl: _pnl,
59538
- neg_pnl: to_f2(loss, "%.2f"),
59539
- sell_price,
59540
- close_p: to_f2(tp_close, "%.2f"),
59541
- min_pnl: to_f2(min_profit, "%.2f"),
59542
- new_stop
59543
- };
59544
- });
59545
- return rrr;
59546
- };
59547
- function createGapPairs(arr, gap, item) {
59548
- if (arr.length === 0) {
59549
- return [];
59550
- }
59551
- const result = [];
59552
- const firstElement = arr[0];
59553
- for (let i2 = arr.length - 1;i2 >= 0; i2--) {
59554
- const current = arr[i2];
59555
- const gapIndex = i2 - gap;
59556
- const pairedElement = gapIndex < 0 ? firstElement : arr[gapIndex];
59557
- if (current !== pairedElement) {
59558
- result.push([current, pairedElement]);
59559
- }
59560
- }
59561
- if (item) {
59562
- let r2 = result.find((o) => o[0] === item);
59563
- return r2 ? [r2] : [];
59564
- }
59565
- return result;
59566
- }
59306
+ // src/exchanges/binance/index.ts
59307
+ var import_binance = __toESM(require_lib2());
59567
59308
 
59568
59309
  // src/helpers/optimizations.ts
59569
59310
  function calculateTheoreticalKelly({
@@ -59600,7 +59341,7 @@ function calculateTheoreticalKelly({
59600
59341
  kelly_fraction *= vol_adjustment;
59601
59342
  }
59602
59343
  kelly_fraction = Math.max(0.005, Math.min(kelly_fraction, 0.5));
59603
- return to_f2(kelly_fraction, "%.4f");
59344
+ return to_f(kelly_fraction, "%.4f");
59604
59345
  }
59605
59346
  function calculateZoneProbabilities({
59606
59347
  current_entry,
@@ -59709,7 +59450,7 @@ function calculateTheoreticalKellyFixed({
59709
59450
  kelly_fraction *= vol_adjustment;
59710
59451
  }
59711
59452
  kelly_fraction = Math.max(0.005, Math.min(kelly_fraction, 0.5));
59712
- return to_f2(kelly_fraction, "%.4f");
59453
+ return to_f(kelly_fraction, "%.4f");
59713
59454
  }
59714
59455
  function calculatePositionBasedKelly({
59715
59456
  current_entry,
@@ -59743,11 +59484,11 @@ function calculatePositionBasedKelly({
59743
59484
  const base_kelly = 0.02;
59744
59485
  const max_kelly = 0.2;
59745
59486
  const kelly_fraction = base_kelly + adjusted_score * (max_kelly - base_kelly);
59746
- return to_f2(kelly_fraction, "%.4f");
59487
+ return to_f(kelly_fraction, "%.4f");
59747
59488
  }
59748
59489
 
59749
59490
  // src/helpers/trade_signal.ts
59750
- function determine_close_price2({
59491
+ function determine_close_price({
59751
59492
  entry,
59752
59493
  pnl,
59753
59494
  quantity,
@@ -59755,16 +59496,16 @@ function determine_close_price2({
59755
59496
  kind = "long"
59756
59497
  }) {
59757
59498
  const dollar_value = entry / leverage;
59758
- const position2 = dollar_value * quantity;
59759
- if (position2) {
59760
- const percent = pnl / position2;
59761
- const difference = position2 * percent / quantity;
59499
+ const position = dollar_value * quantity;
59500
+ if (position) {
59501
+ const percent = pnl / position;
59502
+ const difference = position * percent / quantity;
59762
59503
  const result = kind === "long" ? difference + entry : entry - difference;
59763
59504
  return result;
59764
59505
  }
59765
59506
  return 0;
59766
59507
  }
59767
- function determine_pnl2(entry, close_price, quantity, kind = "long", contract_size) {
59508
+ function determine_pnl(entry, close_price, quantity, kind = "long", contract_size) {
59768
59509
  if (contract_size) {
59769
59510
  const direction = kind === "long" ? 1 : -1;
59770
59511
  return quantity * contract_size * direction * (1 / entry - 1 / close_price);
@@ -59783,7 +59524,7 @@ function* _get_zones({
59783
59524
  let focus_low = last * Math.pow(1 + percent_change, -1);
59784
59525
  if (focus_high > current_price) {
59785
59526
  while (focus_high > current_price) {
59786
- yield to_f2(last, places);
59527
+ yield to_f(last, places);
59787
59528
  focus_high = last;
59788
59529
  last = focus_high * Math.pow(1 + percent_change, -1);
59789
59530
  focus_low = last * Math.pow(1 + percent_change, -1);
@@ -59791,14 +59532,14 @@ function* _get_zones({
59791
59532
  } else {
59792
59533
  if (focus_high <= current_price) {
59793
59534
  while (focus_high <= current_price) {
59794
- yield to_f2(focus_high, places);
59535
+ yield to_f(focus_high, places);
59795
59536
  focus_low = focus_high;
59796
59537
  last = focus_low * (1 + percent_change);
59797
59538
  focus_high = last * (1 + percent_change);
59798
59539
  }
59799
59540
  } else {
59800
59541
  while (focus_low <= current_price) {
59801
- yield to_f2(focus_high, places);
59542
+ yield to_f(focus_high, places);
59802
59543
  focus_low = focus_high;
59803
59544
  last = focus_low * (1 + percent_change);
59804
59545
  focus_high = last * (1 + percent_change);
@@ -60077,7 +59818,7 @@ class Signal {
60077
59818
  } else {
60078
59819
  i2["risk_sell"] = Math.min(...potentials.slice(0, max_index));
60079
59820
  }
60080
- i2["pnl"] = this.to_df(determine_pnl2(i2["entry"], i2["risk_sell"], i2["quantity"], kind));
59821
+ i2["pnl"] = this.to_df(determine_pnl(i2["entry"], i2["risk_sell"], i2["quantity"], kind));
60081
59822
  }
60082
59823
  }
60083
59824
  }
@@ -60141,13 +59882,13 @@ class Signal {
60141
59882
  let remaining_zones = margin_zones.filter((x) => JSON.stringify(x) != JSON.stringify(margin_range));
60142
59883
  if (margin_range) {
60143
59884
  const difference = Math.abs(margin_range[0] - margin_range[1]);
60144
- const spread = to_f2(difference / this.risk_reward, this.price_places);
59885
+ const spread = to_f(difference / this.risk_reward, this.price_places);
60145
59886
  let entries;
60146
59887
  const percent_change = this.percent_change / this.risk_reward;
60147
59888
  if (kind === "long") {
60148
- entries = Array.from({ length: Math.floor(this.risk_reward) + 1 }, (_, x) => to_f2(margin_range[1] - spread * x, this.price_places));
59889
+ entries = Array.from({ length: Math.floor(this.risk_reward) + 1 }, (_, x) => to_f(margin_range[1] - spread * x, this.price_places));
60149
59890
  } else {
60150
- 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));
59891
+ 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));
60151
59892
  }
60152
59893
  if (Math.min(...entries) < this.to_f(current_price) && this.to_f(current_price) < Math.max(...entries)) {
60153
59894
  return entries.sort((a, b) => a - b);
@@ -60159,14 +59900,14 @@ class Signal {
60159
59900
  if (new_range) {
60160
59901
  while (entries2.length < this.risk_reward + 1) {
60161
59902
  if (kind === "long") {
60162
- let value2 = this.to_f(new_range[1] - spread * x);
60163
- if (value2 <= current_price) {
60164
- entries2.push(value2);
59903
+ let value = this.to_f(new_range[1] - spread * x);
59904
+ if (value <= current_price) {
59905
+ entries2.push(value);
60165
59906
  }
60166
59907
  } else {
60167
- let value2 = this.to_f(new_range[1] * Math.pow(1 + percent_change, x));
60168
- if (value2 >= current_price) {
60169
- entries2.push(value2);
59908
+ let value = this.to_f(new_range[1] * Math.pow(1 + percent_change, x));
59909
+ if (value >= current_price) {
59910
+ entries2.push(value);
60170
59911
  }
60171
59912
  }
60172
59913
  x += 1;
@@ -60180,14 +59921,14 @@ class Signal {
60180
59921
  let x = 0;
60181
59922
  while (entries2.length < this.risk_reward + 1) {
60182
59923
  if (kind === "long") {
60183
- let value2 = this.to_f(next_focus - spread * x);
60184
- if (value2 <= this.to_f(current_price)) {
60185
- entries2.push(value2);
59924
+ let value = this.to_f(next_focus - spread * x);
59925
+ if (value <= this.to_f(current_price)) {
59926
+ entries2.push(value);
60186
59927
  }
60187
59928
  } else {
60188
- let value2 = this.to_f(next_focus * Math.pow(1 + percent_change, x));
60189
- if (value2 >= this.to_f(current_price)) {
60190
- entries2.push(value2);
59929
+ let value = this.to_f(next_focus * Math.pow(1 + percent_change, x));
59930
+ if (value >= this.to_f(current_price)) {
59931
+ entries2.push(value);
60191
59932
  }
60192
59933
  }
60193
59934
  x += 1;
@@ -60198,8 +59939,8 @@ class Signal {
60198
59939
  }
60199
59940
  return [];
60200
59941
  }
60201
- to_f(value2, places) {
60202
- return to_f2(value2, places || this.price_places);
59942
+ to_f(value, places) {
59943
+ return to_f(value, places || this.price_places);
60203
59944
  }
60204
59945
  get_margin_zones({
60205
59946
  current_price,
@@ -60417,7 +60158,7 @@ class Signal {
60417
60158
  }) {
60418
60159
  const considered = arr.map((x, i2) => i2).filter((i2) => i2 > index);
60419
60160
  const with_quantity = considered.map((x) => {
60420
- const q = determine_position_size2({
60161
+ const q = determine_position_size({
60421
60162
  entry: arr[x],
60422
60163
  stop: arr[x - 1],
60423
60164
  budget: risk,
@@ -60451,7 +60192,7 @@ class Signal {
60451
60192
  const incurred_fees = fees.reduce((a, b) => a + b, 0) + previous_risks.reduce((a, b) => a + b, 0);
60452
60193
  if (index === 0) {
60453
60194
  }
60454
- let quantity = determine_position_size2({
60195
+ let quantity = determine_position_size({
60455
60196
  entry,
60456
60197
  stop,
60457
60198
  budget: risk,
@@ -60463,7 +60204,7 @@ class Signal {
60463
60204
  }
60464
60205
  if (this.increase_size) {
60465
60206
  quantity = quantity * multiplier;
60466
- const new_risk = determine_pnl2(entry, stop, quantity, kind);
60207
+ const new_risk = determine_pnl(entry, stop, quantity, kind);
60467
60208
  risk = Math.abs(new_risk);
60468
60209
  }
60469
60210
  const fee = this.to_df(this.fee * quantity * entry);
@@ -60472,12 +60213,12 @@ class Signal {
60472
60213
  if (this.minimum_pnl) {
60473
60214
  pnl = this.minimum_pnl + fee;
60474
60215
  }
60475
- let sell_price = determine_close_price2({ entry, pnl, quantity, kind });
60216
+ let sell_price = determine_close_price({ entry, pnl, quantity, kind });
60476
60217
  if (take_profit && !this.minimum_pnl) {
60477
60218
  sell_price = take_profit;
60478
- pnl = this.to_df(determine_pnl2(entry, sell_price, quantity, kind));
60219
+ pnl = this.to_df(determine_pnl(entry, sell_price, quantity, kind));
60479
60220
  pnl = pnl + fee;
60480
- sell_price = determine_close_price2({ entry, pnl, quantity, kind });
60221
+ sell_price = determine_close_price({ entry, pnl, quantity, kind });
60481
60222
  }
60482
60223
  let risk_sell = sell_price;
60483
60224
  return {
@@ -60495,10 +60236,271 @@ class Signal {
60495
60236
  };
60496
60237
  }
60497
60238
  to_df(currentPrice, places = "%.3f") {
60498
- return to_f2(currentPrice, places);
60239
+ return to_f(currentPrice, places);
60240
+ }
60241
+ }
60242
+
60243
+ // src/helpers/pnl.ts
60244
+ function determine_position_size2(entry, stop, budget) {
60245
+ let stop_percent = Math.abs(entry - stop) / entry;
60246
+ let size = budget / stop_percent / entry;
60247
+ return size;
60248
+ }
60249
+ function determine_risk(entry, stop, quantity) {
60250
+ let stop_percent = Math.abs(entry - stop) / entry;
60251
+ let risk = quantity * stop_percent * entry;
60252
+ return risk;
60253
+ }
60254
+ function determine_close_price2(entry, pnl, quantity, kind, single = false, leverage = 1) {
60255
+ const dollar_value = entry / leverage;
60256
+ const position = dollar_value * quantity;
60257
+ if (position) {
60258
+ let percent = pnl / position;
60259
+ let difference = position * percent / quantity;
60260
+ let result;
60261
+ if (kind === "long") {
60262
+ result = difference + entry;
60263
+ } else {
60264
+ result = entry - difference;
60265
+ }
60266
+ if (single) {
60267
+ return result;
60268
+ }
60269
+ return result;
60270
+ }
60271
+ return 0;
60272
+ }
60273
+ function determine_amount_to_sell(entry, quantity, sell_price, pnl, kind, places = "%.3f") {
60274
+ const _pnl = determine_pnl2(entry, sell_price, quantity, kind);
60275
+ const ratio = pnl / to_f2(Math.abs(_pnl), places);
60276
+ quantity = quantity * ratio;
60277
+ return to_f2(quantity, places);
60278
+ }
60279
+ function determine_pnl2(entry, close_price, quantity, kind, contract_size, places = "%.2f") {
60280
+ if (contract_size) {
60281
+ const direction = kind === "long" ? 1 : -1;
60282
+ return quantity * contract_size * direction * (1 / entry - 1 / close_price);
60283
+ }
60284
+ let difference = entry - close_price;
60285
+ if (kind === "long") {
60286
+ difference = close_price - entry;
60287
+ }
60288
+ return to_f2(difference * quantity, places);
60289
+ }
60290
+ function position(entry, quantity, kind, leverage = 1) {
60291
+ const direction = { long: 1, short: -1 };
60292
+ return parseFloat((direction[kind] * quantity * (entry / leverage)).toFixed(3));
60293
+ }
60294
+ function to_f2(value, places) {
60295
+ if (value) {
60296
+ let pp = parseInt(places.replace("%.", "").replace("f", ""));
60297
+ return parseFloat(value.toFixed(pp));
60499
60298
  }
60299
+ return value;
60500
60300
  }
60301
+ var value = {
60302
+ determine_risk,
60303
+ determine_position_size: determine_position_size2,
60304
+ determine_close_price: determine_close_price2,
60305
+ determine_pnl: determine_pnl2,
60306
+ position,
60307
+ determine_amount_to_sell,
60308
+ to_f: to_f2
60309
+ };
60310
+ var pnl_default = value;
60501
60311
 
60312
+ // src/helpers/trade_utils.ts
60313
+ function to_f(value2, places = "%.1f") {
60314
+ let v = typeof value2 === "string" ? parseFloat(value2) : value2;
60315
+ const formattedValue = places.replace("%.", "").replace("f", "");
60316
+ return parseFloat(v.toFixed(parseInt(formattedValue)));
60317
+ }
60318
+ function determine_amount_to_sell2(entry, quantity, sell_price, pnl, kind, places = "%.3f") {
60319
+ const _pnl = determine_pnl(entry, sell_price, quantity, kind);
60320
+ const ratio = pnl / to_f(Math.abs(_pnl), places);
60321
+ quantity = quantity * ratio;
60322
+ return to_f(quantity, places);
60323
+ }
60324
+ function determine_position_size({
60325
+ entry,
60326
+ stop,
60327
+ budget,
60328
+ percent,
60329
+ min_size,
60330
+ notional_value,
60331
+ as_coin = true,
60332
+ places = "%.3f"
60333
+ }) {
60334
+ let stop_percent = stop ? Math.abs(entry - stop) / entry : percent;
60335
+ if (stop_percent && budget) {
60336
+ let size = budget / stop_percent;
60337
+ let notion_value = size * entry;
60338
+ if (notional_value && notional_value > notion_value) {
60339
+ size = notional_value / entry;
60340
+ }
60341
+ if (as_coin) {
60342
+ size = size / entry;
60343
+ if (min_size && min_size === 1) {
60344
+ return to_f(Math.round(size), places);
60345
+ }
60346
+ }
60347
+ return to_f(size, places);
60348
+ }
60349
+ return;
60350
+ }
60351
+ function determine_average_entry_and_size(orders, places = "%.3f", price_places = "%.1f") {
60352
+ const sum_values = orders.reduce((sum, order) => sum + order.price * order.quantity, 0);
60353
+ const total_quantity = orders.reduce((sum, order) => sum + order.quantity, 0);
60354
+ const avg_price = total_quantity ? to_f(sum_values / total_quantity, price_places) : 0;
60355
+ return {
60356
+ entry: avg_price,
60357
+ price: avg_price,
60358
+ quantity: to_f(total_quantity, places)
60359
+ };
60360
+ }
60361
+ var createArray = (start, stop, step) => {
60362
+ const result = [];
60363
+ let current = start;
60364
+ while (current <= stop) {
60365
+ result.push(current);
60366
+ current += step;
60367
+ }
60368
+ return result;
60369
+ };
60370
+ var groupIntoPairsWithSumLessThan = (arr, targetSum, key = "quantity", firstSize = 0) => {
60371
+ if (firstSize) {
60372
+ const totalSize = arr.reduce((sum, order) => sum + order[key], 0);
60373
+ const remainingSize = totalSize - firstSize;
60374
+ let newSum = 0;
60375
+ let newArray = [];
60376
+ let lastIndex = 0;
60377
+ for (let i2 = 0;i2 < arr.length; i2++) {
60378
+ if (newSum < remainingSize) {
60379
+ newSum += arr[i2][key];
60380
+ newArray.push(arr[i2]);
60381
+ lastIndex = i2;
60382
+ }
60383
+ }
60384
+ const lastGroup = arr.slice(lastIndex + 1);
60385
+ const previousPair = groupInPairs(newArray, key, targetSum);
60386
+ if (lastGroup.length > 0) {
60387
+ previousPair.push(lastGroup);
60388
+ }
60389
+ return previousPair;
60390
+ }
60391
+ return groupInPairs(arr, key, targetSum);
60392
+ };
60393
+ function groupInPairs(_arr, key, targetSum) {
60394
+ const result = [];
60395
+ let currentSum = 0;
60396
+ let currentGroup = [];
60397
+ for (let i2 = 0;i2 < _arr.length; i2++) {
60398
+ currentSum += _arr[i2][key];
60399
+ currentGroup.push(_arr[i2]);
60400
+ if (currentSum >= targetSum) {
60401
+ result.push(currentGroup);
60402
+ currentGroup = [];
60403
+ currentSum = 0;
60404
+ }
60405
+ }
60406
+ return result;
60407
+ }
60408
+ var computeTotalAverageForEachTrade = (trades, config2) => {
60409
+ let _take_profit = config2.take_profit;
60410
+ let kind = config2.kind;
60411
+ let entryToUse = kind === "short" ? Math.min(config2.entry, config2.stop) : Math.max(config2.entry, config2.stop);
60412
+ let _currentEntry = config2.currentEntry || entryToUse;
60413
+ let less = trades.filter((p) => kind === "long" ? p.entry <= _currentEntry : p.entry >= _currentEntry);
60414
+ let rrr = trades.map((r2, i2) => {
60415
+ let considered = [];
60416
+ if (kind === "long") {
60417
+ considered = trades.filter((p) => p.entry > _currentEntry);
60418
+ } else {
60419
+ considered = trades.filter((p) => p.entry < _currentEntry);
60420
+ }
60421
+ const x_pnl = 0;
60422
+ const remaining = less.filter((o) => {
60423
+ if (kind === "long") {
60424
+ return o.entry >= r2.entry;
60425
+ }
60426
+ return o.entry <= r2.entry;
60427
+ });
60428
+ if (remaining.length === 0) {
60429
+ return { ...r2, pnl: x_pnl };
60430
+ }
60431
+ const start = kind === "long" ? Math.max(...remaining.map((o) => o.entry)) : Math.min(...remaining.map((o) => o.entry));
60432
+ considered = considered.map((o) => ({ ...o, entry: start }));
60433
+ considered = considered.concat(remaining);
60434
+ let avg_entry = determine_average_entry_and_size([
60435
+ ...considered.map((o) => ({
60436
+ price: o.entry,
60437
+ quantity: o.quantity
60438
+ })),
60439
+ {
60440
+ price: _currentEntry,
60441
+ quantity: config2.currentQty || 0
60442
+ }
60443
+ ], config2.decimal_places, config2.price_places);
60444
+ let _pnl = r2.pnl;
60445
+ let sell_price = r2.sell_price;
60446
+ let entry_pnl = r2.pnl;
60447
+ if (_take_profit) {
60448
+ _pnl = pnl_default.determine_pnl(avg_entry.price, _take_profit, avg_entry.quantity, kind);
60449
+ sell_price = _take_profit;
60450
+ entry_pnl = pnl_default.determine_pnl(r2.entry, _take_profit, avg_entry.quantity, kind);
60451
+ }
60452
+ const loss = pnl_default.determine_pnl(avg_entry.price, r2.stop, avg_entry.quantity, kind);
60453
+ let new_stop = r2.new_stop;
60454
+ const entry_loss = pnl_default.determine_pnl(r2.entry, new_stop, avg_entry.quantity, kind);
60455
+ let min_profit = 0;
60456
+ let min_entry_profit = 0;
60457
+ if (config2.min_profit) {
60458
+ min_profit = pnl_default.determine_close_price(avg_entry.price, config2.min_profit, avg_entry.quantity, kind);
60459
+ min_entry_profit = pnl_default.determine_close_price(r2.entry, config2.min_profit, avg_entry.quantity, kind);
60460
+ }
60461
+ let x_fee = r2.fee;
60462
+ if (config2.fee) {
60463
+ x_fee = config2.fee * r2.stop * avg_entry.quantity;
60464
+ }
60465
+ let tp_close = pnl_default.determine_close_price(r2.entry, Math.abs(entry_loss) * (config2.rr || 1) + x_fee, avg_entry.quantity, kind);
60466
+ return {
60467
+ ...r2,
60468
+ x_fee: to_f(x_fee, "%.2f"),
60469
+ avg_entry: avg_entry.price,
60470
+ avg_size: avg_entry.quantity,
60471
+ entry_pnl: to_f(entry_pnl, "%.2f"),
60472
+ entry_loss: to_f(entry_loss, "%.2f"),
60473
+ min_entry_pnl: to_f(min_entry_profit, "%.2f"),
60474
+ pnl: _pnl,
60475
+ neg_pnl: to_f(loss, "%.2f"),
60476
+ sell_price,
60477
+ close_p: to_f(tp_close, "%.2f"),
60478
+ min_pnl: to_f(min_profit, "%.2f"),
60479
+ new_stop
60480
+ };
60481
+ });
60482
+ return rrr;
60483
+ };
60484
+ function createGapPairs(arr, gap, item) {
60485
+ if (arr.length === 0) {
60486
+ return [];
60487
+ }
60488
+ const result = [];
60489
+ const firstElement = arr[0];
60490
+ for (let i2 = arr.length - 1;i2 >= 0; i2--) {
60491
+ const current = arr[i2];
60492
+ const gapIndex = i2 - gap;
60493
+ const pairedElement = gapIndex < 0 ? firstElement : arr[gapIndex];
60494
+ if (current !== pairedElement) {
60495
+ result.push([current, pairedElement]);
60496
+ }
60497
+ }
60498
+ if (item) {
60499
+ let r2 = result.find((o) => o[0] === item);
60500
+ return r2 ? [r2] : [];
60501
+ }
60502
+ return result;
60503
+ }
60502
60504
  // src/helpers/shared.ts
60503
60505
  function getMaxQuantity(x, app_config) {
60504
60506
  let max_quantity = app_config.max_quantity;
@@ -60607,8 +60609,8 @@ function get_app_config_and_max_size(config2, payload) {
60607
60609
  stop: payload.stop,
60608
60610
  risk_per_trade: config2.risk,
60609
60611
  risk_reward: config2.risk_reward || 199,
60610
- support: to_f2(config2.support, config2.price_places),
60611
- resistance: to_f2(config2.resistance, config2.price_places),
60612
+ support: to_f(config2.support, config2.price_places),
60613
+ resistance: to_f(config2.resistance, config2.price_places),
60612
60614
  focus: payload.entry,
60613
60615
  fee: 0,
60614
60616
  percent_change: config2.stop_percent / 100,
@@ -60827,8 +60829,8 @@ function getOptimumStopAndRisk(app_config, params) {
60827
60829
  }
60828
60830
  }
60829
60831
  return {
60830
- optimal_stop: to_f2(optimal_stop, app_config.price_places),
60831
- optimal_risk: to_f2(final_risk, app_config.price_places),
60832
+ optimal_stop: to_f(optimal_stop, app_config.price_places),
60833
+ optimal_risk: to_f(final_risk, app_config.price_places),
60832
60834
  avg_size: final_result?.[0]?.avg_size || 0,
60833
60835
  avg_entry: final_result?.[0]?.avg_entry || 0,
60834
60836
  result: final_result,
@@ -60876,7 +60878,7 @@ function determine_amount_to_buy(payload) {
60876
60878
  existingOrders
60877
60879
  } = payload;
60878
60880
  const totalQuantity = orders.reduce((sum, order) => sum + (order.quantity || 0), 0);
60879
- let runningTotal = to_f2(totalQuantity, decimal_places);
60881
+ let runningTotal = to_f(totalQuantity, decimal_places);
60880
60882
  let sortedOrders = [...orders].sort((a, b) => (a.entry || 0) - (b.entry || 0));
60881
60883
  if (kind === "short") {
60882
60884
  sortedOrders.reverse();
@@ -60888,7 +60890,7 @@ function determine_amount_to_buy(payload) {
60888
60890
  cumulative_quantity: runningTotal
60889
60891
  });
60890
60892
  runningTotal -= order.quantity;
60891
- runningTotal = to_f2(runningTotal, decimal_places);
60893
+ runningTotal = to_f(runningTotal, decimal_places);
60892
60894
  }
60893
60895
  let filteredOrders = withCumulative.filter((order) => (order.cumulative_quantity || 0) > position2?.quantity).map((order) => ({
60894
60896
  ...order,
@@ -61151,10 +61153,10 @@ function determineOptimumRisk(config2, payload, params) {
61151
61153
  };
61152
61154
  const final_result = buildAppConfig(config2, final_payload);
61153
61155
  return {
61154
- optimal_risk: to_f2(best_risk, "%.2f"),
61155
- achieved_neg_pnl: to_f2(best_neg_pnl, "%.2f"),
61156
- target_neg_pnl: to_f2(highest_risk, "%.2f"),
61157
- difference: to_f2(best_diff, "%.2f"),
61156
+ optimal_risk: to_f(best_risk, "%.2f"),
61157
+ achieved_neg_pnl: to_f(best_neg_pnl, "%.2f"),
61158
+ target_neg_pnl: to_f(highest_risk, "%.2f"),
61159
+ difference: to_f(best_diff, "%.2f"),
61158
61160
  iterations,
61159
61161
  converged: best_diff <= tolerance,
61160
61162
  last_value: final_result.last_value,
@@ -61219,9 +61221,9 @@ function computeProfitDetail(payload) {
61219
61221
  full_ratio = 1
61220
61222
  } = payload;
61221
61223
  let reward_factor = strategy?.reward_factor || 1;
61222
- const profit_percent = to_f2(pnl * 100 / (focus_position.avg_price * focus_position.avg_qty), "%.4f");
61224
+ const profit_percent = to_f(pnl * 100 / (focus_position.avg_price * focus_position.avg_qty), "%.4f");
61223
61225
  const diff = pnl / focus_position.quantity;
61224
- const sell_price = to_f2(focus_position.kind === "long" ? focus_position.entry + diff : focus_position.entry - diff, price_places);
61226
+ const sell_price = to_f(focus_position.kind === "long" ? focus_position.entry + diff : focus_position.entry - diff, price_places);
61225
61227
  let loss = 0;
61226
61228
  let full_loss = 0;
61227
61229
  let expected_loss = 0;
@@ -61230,23 +61232,23 @@ function computeProfitDetail(payload) {
61230
61232
  if (reduce_position) {
61231
61233
  loss = Math.abs(reduce_position.entry - sell_price) * reduce_position.quantity;
61232
61234
  const ratio = pnl / loss;
61233
- quantity = to_f2(reduce_position.quantity * ratio, decimal_places);
61234
- expected_loss = to_f2(Math.abs(reduce_position.entry - sell_price) * quantity, "%.2f");
61235
+ quantity = to_f(reduce_position.quantity * ratio, decimal_places);
61236
+ expected_loss = to_f(Math.abs(reduce_position.entry - sell_price) * quantity, "%.2f");
61235
61237
  full_loss = Math.abs(reduce_position.avg_price - sell_price) * reduce_position.avg_qty * full_ratio;
61236
61238
  }
61237
61239
  if (reverse_position) {
61238
61240
  expected_loss = Math.abs(reverse_position.avg_price - sell_price) * reverse_position.avg_qty;
61239
- new_pnl = to_f2(pnl - expected_loss, "%.2f");
61241
+ new_pnl = to_f(pnl - expected_loss, "%.2f");
61240
61242
  }
61241
61243
  return {
61242
61244
  pnl: new_pnl,
61243
- loss: to_f2(expected_loss, "%.2f"),
61244
- full_loss: to_f2(full_loss, "%.2f"),
61245
+ loss: to_f(expected_loss, "%.2f"),
61246
+ full_loss: to_f(full_loss, "%.2f"),
61245
61247
  original_pnl: pnl,
61246
61248
  reward_factor,
61247
61249
  profit_percent,
61248
61250
  kind: focus_position.kind,
61249
- sell_price: to_f2(sell_price, price_places),
61251
+ sell_price: to_f(sell_price, price_places),
61250
61252
  quantity: quantity * full_ratio,
61251
61253
  price_places,
61252
61254
  decimal_places
@@ -61281,18 +61283,18 @@ function generateGapTp(payload) {
61281
61283
  const gapLoss = gap * max_quantity;
61282
61284
  const longPercent = gapLoss * factor / (short.entry * short.quantity);
61283
61285
  const shortPercent = gapLoss * factor / (long.entry * long.quantity);
61284
- const longTp = to_f2((1 + longPercent) * long.entry, price_places);
61285
- const shortTp = to_f2((1 + shortPercent) ** -1 * short.entry, price_places);
61286
- const shortToReduce = to_f2(Math.abs(longTp - long.entry) * long.quantity, "%.1f");
61287
- const longToReduce = to_f2(Math.abs(shortTp - short.entry) * short.quantity, "%.1f");
61288
- const actualShortReduce = to_f2(shortToReduce * sell_factor, "%.1f");
61289
- const actualLongReduce = to_f2(longToReduce * sell_factor, "%.1f");
61286
+ const longTp = to_f((1 + longPercent) * long.entry, price_places);
61287
+ const shortTp = to_f((1 + shortPercent) ** -1 * short.entry, price_places);
61288
+ const shortToReduce = to_f(Math.abs(longTp - long.entry) * long.quantity, "%.1f");
61289
+ const longToReduce = to_f(Math.abs(shortTp - short.entry) * short.quantity, "%.1f");
61290
+ const actualShortReduce = to_f(shortToReduce * sell_factor, "%.1f");
61291
+ const actualLongReduce = to_f(longToReduce * sell_factor, "%.1f");
61290
61292
  const short_quantity_to_sell = determine_amount_to_sell2(short.entry, short.quantity, longTp, actualShortReduce, "short", decimal_places);
61291
61293
  const long_quantity_to_sell = determine_amount_to_sell2(long.entry, long.quantity, shortTp, actualLongReduce, "long", decimal_places);
61292
- const risk_amount_short = to_f2(shortToReduce - actualShortReduce, "%.2f");
61293
- const risk_amount_long = to_f2(longToReduce - actualLongReduce, "%.2f");
61294
- const profit_percent_long = to_f2(shortToReduce * 100 / (long.entry * long.quantity), "%.4f");
61295
- const profit_percent_short = to_f2(longToReduce * 100 / (short.entry * short.quantity), "%.4f");
61294
+ const risk_amount_short = to_f(shortToReduce - actualShortReduce, "%.2f");
61295
+ const risk_amount_long = to_f(longToReduce - actualLongReduce, "%.2f");
61296
+ const profit_percent_long = to_f(shortToReduce * 100 / (long.entry * long.quantity), "%.4f");
61297
+ const profit_percent_short = to_f(longToReduce * 100 / (short.entry * short.quantity), "%.4f");
61296
61298
  return {
61297
61299
  profit_percent: {
61298
61300
  long: profit_percent_long,
@@ -61318,8 +61320,8 @@ function generateGapTp(payload) {
61318
61320
  short: short_quantity_to_sell,
61319
61321
  long: long_quantity_to_sell
61320
61322
  },
61321
- gap: to_f2(gap, price_places),
61322
- gap_loss: to_f2(gapLoss, "%.2f")
61323
+ gap: to_f(gap, price_places),
61324
+ gap_loss: to_f(gapLoss, "%.2f")
61323
61325
  };
61324
61326
  }
61325
61327
  function calculate_factor(payload) {
@@ -61345,7 +61347,7 @@ function calculate_factor(payload) {
61345
61347
  const calculated_shortPercent = target_to_reduce / (short_notional - target_to_reduce);
61346
61348
  calculated_factor = calculated_shortPercent * long_notional / gapLoss;
61347
61349
  }
61348
- calculated_factor = to_f2(calculated_factor, places);
61350
+ calculated_factor = to_f(calculated_factor, places);
61349
61351
  return calculated_factor;
61350
61352
  }
61351
61353
  function getHedgeZone(payload) {
@@ -61372,19 +61374,19 @@ function getHedgeZone(payload) {
61372
61374
  const tp_diff = Math.abs(take_profit - position2.entry);
61373
61375
  const quantity = position2.quantity;
61374
61376
  const diff = risk / quantity;
61375
- let new_take_profit = kind === "long" ? to_f2(position2.entry + diff, symbol_config.price_places) : to_f2(position2.entry - diff, symbol_config.price_places);
61376
- let base_factor = to_f2(Math.max(tp_diff, diff) / (Math.min(tp_diff, diff) || 1), "%.3f");
61377
+ let new_take_profit = kind === "long" ? to_f(position2.entry + diff, symbol_config.price_places) : to_f(position2.entry - diff, symbol_config.price_places);
61378
+ let base_factor = to_f(Math.max(tp_diff, diff) / (Math.min(tp_diff, diff) || 1), "%.3f");
61377
61379
  let factor = reward_factor || base_factor;
61378
61380
  const new_risk = risk * factor * risk_factor;
61379
61381
  const stop_loss_diff = new_risk / quantity;
61380
- 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);
61381
- 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);
61382
+ 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);
61383
+ 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);
61382
61384
  const profit_percent = new_risk * 100 / (position2.entry * position2.quantity);
61383
61385
  return {
61384
61386
  support: Math.min(new_take_profit, stop_loss),
61385
61387
  resistance: Math.max(new_take_profit, stop_loss),
61386
- risk: to_f2(new_risk, "%.2f"),
61387
- profit_percent: to_f2(profit_percent, "%.2f")
61388
+ risk: to_f(new_risk, "%.2f"),
61389
+ profit_percent: to_f(profit_percent, "%.2f")
61388
61390
  };
61389
61391
  }
61390
61392
  function getOptimumHedgeFactor(payload) {
@@ -61419,10 +61421,10 @@ function getOptimumHedgeFactor(payload) {
61419
61421
  }
61420
61422
  if (diff <= tolerance) {
61421
61423
  return {
61422
- reward_factor: to_f2(mid_factor, "%.4f"),
61423
- achieved_support: to_f2(current_support, symbol_config.price_places),
61424
- target_support: to_f2(target_support, symbol_config.price_places),
61425
- difference: to_f2(diff, symbol_config.price_places),
61424
+ reward_factor: to_f(mid_factor, "%.4f"),
61425
+ achieved_support: to_f(current_support, symbol_config.price_places),
61426
+ target_support: to_f(target_support, symbol_config.price_places),
61427
+ difference: to_f(diff, symbol_config.price_places),
61426
61428
  iterations: iteration + 1
61427
61429
  };
61428
61430
  }
@@ -61442,10 +61444,10 @@ function getOptimumHedgeFactor(payload) {
61442
61444
  reward_factor: best_factor
61443
61445
  });
61444
61446
  return {
61445
- reward_factor: to_f2(best_factor, "%.4f"),
61446
- achieved_support: to_f2(final_hedge_zone.support, symbol_config.price_places),
61447
- target_support: to_f2(target_support, symbol_config.price_places),
61448
- difference: to_f2(best_diff, symbol_config.price_places),
61447
+ reward_factor: to_f(best_factor, "%.4f"),
61448
+ achieved_support: to_f(final_hedge_zone.support, symbol_config.price_places),
61449
+ target_support: to_f(target_support, symbol_config.price_places),
61450
+ difference: to_f(best_diff, symbol_config.price_places),
61449
61451
  iterations: max_iterations,
61450
61452
  converged: best_diff <= tolerance
61451
61453
  };
@@ -61490,15 +61492,14 @@ function determineCompoundLongTrade(payload) {
61490
61492
  return {
61491
61493
  start_risk,
61492
61494
  short_profit,
61493
- support: to_f2(support, global_config.price_places),
61494
- resistance: to_f2(resistance, global_config.price_places),
61495
+ support: to_f(support, global_config.price_places),
61496
+ resistance: to_f(resistance, global_config.price_places),
61495
61497
  long_v: long_app_config.last_value,
61496
- profit_percent: to_f2(long_profit_percent, "%.3f"),
61498
+ profit_percent: to_f(long_profit_percent, "%.3f"),
61497
61499
  result,
61498
61500
  short_max_size
61499
61501
  };
61500
61502
  }
61501
-
61502
61503
  // src/helpers/strategy.ts
61503
61504
  class Strategy {
61504
61505
  position;
@@ -61522,10 +61523,10 @@ class Strategy {
61522
61523
  return this.config.global_config.decimal_places;
61523
61524
  }
61524
61525
  to_f(price) {
61525
- return to_f2(price, this.price_places);
61526
+ return to_f(price, this.price_places);
61526
61527
  }
61527
61528
  to_df(quantity) {
61528
- return to_f2(quantity, this.decimal_places);
61529
+ return to_f(quantity, this.decimal_places);
61529
61530
  }
61530
61531
  pnl(kind, _position) {
61531
61532
  const position2 = _position || this.position[kind];
@@ -61726,7 +61727,7 @@ class Strategy {
61726
61727
  remaining_quantity: this.to_df(reverse_avg.quantity - sell_quantity)
61727
61728
  },
61728
61729
  spread: Math.abs(avg.entry - reverse_avg.entry),
61729
- gap_loss: to_f2(Math.abs(avg.entry - reverse_avg.entry) * reverse_avg.quantity, "%.2f"),
61730
+ gap_loss: to_f(Math.abs(avg.entry - reverse_avg.entry) * reverse_avg.quantity, "%.2f"),
61730
61731
  net_profit: incurred_loss + reverse_pnl
61731
61732
  };
61732
61733
  }
@@ -61894,8 +61895,8 @@ class Strategy {
61894
61895
  quantity: this.position[app_config.kind].quantity
61895
61896
  }
61896
61897
  ]), app_config.decimal_places, app_config.price_places);
61897
- const expected_loss = to_f2(Math.abs(avg.price - stop) * avg.quantity, "%.2f");
61898
- const profit_percent = to_f2(this.pnl(kind) * 100 / (avg.price * avg.quantity), "%.3f");
61898
+ const expected_loss = to_f(Math.abs(avg.price - stop) * avg.quantity, "%.2f");
61899
+ const profit_percent = to_f(this.pnl(kind) * 100 / (avg.price * avg.quantity), "%.3f");
61899
61900
  app_config.entry = this.to_f(app_config.entry);
61900
61901
  app_config.stop = this.to_f(app_config.stop);
61901
61902
  return { ...app_config, avg, loss: -expected_loss, profit_percent };
@@ -61998,9 +61999,6 @@ class Strategy {
61998
61999
  };
61999
62000
  }
62000
62001
  }
62001
-
62002
- // src/exchanges/binance/index.ts
62003
- var import_binance = __toESM(require_lib2());
62004
62002
  // src/types/index.ts
62005
62003
  class BaseExchange {
62006
62004
  client;
@@ -62045,7 +62043,7 @@ class BaseExchange {
62045
62043
  place = false
62046
62044
  } = payload;
62047
62045
  const totalQuantity = orders.reduce((sum, order) => sum + (order.quantity || 0), 0);
62048
- let runningTotal = to_f2(totalQuantity, decimal_places);
62046
+ let runningTotal = to_f(totalQuantity, decimal_places);
62049
62047
  let sortedOrders = [...orders].sort((a, b) => (a.entry || 0) - (b.entry || 0));
62050
62048
  if (kind === "short") {
62051
62049
  sortedOrders.reverse();
@@ -62057,7 +62055,7 @@ class BaseExchange {
62057
62055
  cumulative_quantity: runningTotal
62058
62056
  });
62059
62057
  runningTotal -= order.quantity;
62060
- runningTotal = to_f2(runningTotal, decimal_places);
62058
+ runningTotal = to_f(runningTotal, decimal_places);
62061
62059
  }
62062
62060
  const positions = await this.getPositionInfo(symbol);
62063
62061
  const position2 = positions[kind] || {
@@ -62586,8 +62584,8 @@ async function createLimitPurchaseOrdersParallel(client, symbol, priceFormat, qu
62586
62584
  const createOrder = (x) => {
62587
62585
  const v = {
62588
62586
  symbol: symbol.toUpperCase(),
62589
- price: x.price ? to_f2(x.price, priceFormat) : 0,
62590
- quantity: x.quantity ? to_f2(x.quantity, quantityFormat) : 0,
62587
+ price: x.price ? to_f(x.price, priceFormat) : 0,
62588
+ quantity: x.quantity ? to_f(x.quantity, quantityFormat) : 0,
62591
62589
  side: x.side?.toUpperCase() || "",
62592
62590
  type: "LIMIT",
62593
62591
  positionSide: x.kind.toUpperCase(),
@@ -62602,7 +62600,7 @@ async function createLimitPurchaseOrdersParallel(client, symbol, priceFormat, qu
62602
62600
  delete v.timeInForce;
62603
62601
  v.type = `${v.type}_MARKET`.toUpperCase();
62604
62602
  } else if (typeof x.stop === "number") {
62605
- v.stopPrice = to_f2(x.stop, priceFormat);
62603
+ v.stopPrice = to_f(x.stop, priceFormat);
62606
62604
  }
62607
62605
  }
62608
62606
  if (x.force_market) {
@@ -62875,14 +62873,14 @@ async function getOpenOrders(client, symbol, type) {
62875
62873
  async function getWalletBalance(client, asset = "USDT") {
62876
62874
  const response = await client.getBalanceV3();
62877
62875
  const balance = response.find((x) => x.asset.toLowerCase() === asset.toLowerCase())?.balance;
62878
- return balance ? to_f2(balance, "%.2f") : 0;
62876
+ return balance ? to_f(balance, "%.2f") : 0;
62879
62877
  }
62880
62878
  async function allWalletBalances(client) {
62881
62879
  const response = await client.getBalanceV3();
62882
62880
  return response.map((x) => ({
62883
62881
  type: "future",
62884
62882
  asset: x.asset,
62885
- balance: to_f2(x.balance, "%.8f")
62883
+ balance: to_f(x.balance, "%.8f")
62886
62884
  }));
62887
62885
  }
62888
62886
  function buildPosition(position2, orders, options) {
@@ -62919,7 +62917,7 @@ function buildPosition(position2, orders, options) {
62919
62917
  take_profit,
62920
62918
  tp_quantity,
62921
62919
  stop_quantity,
62922
- liquidation: position2.liquidationPrice ? to_f2(position2.liquidationPrice, price_places) : 0
62920
+ liquidation: position2.liquidationPrice ? to_f(position2.liquidationPrice, price_places) : 0
62923
62921
  };
62924
62922
  }
62925
62923
  var emptyPosition = {
@@ -62940,7 +62938,7 @@ async function getLeverage(client, symbol) {
62940
62938
  symbol
62941
62939
  });
62942
62940
  const leverage = response[0]?.leverage;
62943
- return leverage ? to_f2(leverage, "%0f") : 0;
62941
+ return leverage ? to_f(leverage, "%0f") : 0;
62944
62942
  }
62945
62943
  async function fetchBinanceAccount(client, json, options) {
62946
62944
  const [position2, balance, orders, current_price, all_balances, leverage] = await Promise.all([
@@ -63238,7 +63236,7 @@ class BinanceExchange extends BaseExchange {
63238
63236
  const currentPrice = await getCurrentPrice(this.client, symbol);
63239
63237
  const price_places = isBTC ? "%.1f" : `%.${getPricePlaces(currentPrice)}f`;
63240
63238
  const decimal_places = `%.${target.quantityPrecision}f`;
63241
- const min_size = to_f2((minNotional || 0) / support, decimal_places);
63239
+ const min_size = to_f((minNotional || 0) / support, decimal_places);
63242
63240
  const configObj = {
63243
63241
  support,
63244
63242
  resistance,
@@ -63482,8 +63480,8 @@ async function createLimitPurchaseOrders(client, symbol, priceFormat, quantityFo
63482
63480
  const createOrder = (x) => {
63483
63481
  const v = {
63484
63482
  symbol: symbol.toUpperCase(),
63485
- price: (x.price ? to_f2(x.price, priceFormat) : 0).toString(),
63486
- qty: (x.quantity ? to_f2(x.quantity, quantityFormat) : 0).toString(),
63483
+ price: (x.price ? to_f(x.price, priceFormat) : 0).toString(),
63484
+ qty: (x.quantity ? to_f(x.quantity, quantityFormat) : 0).toString(),
63487
63485
  side: titleCase(x.side || ""),
63488
63486
  orderType: "LIMIT",
63489
63487
  positionIdx: x.kind === "long" ? 1 : 2,
@@ -63500,12 +63498,12 @@ async function createLimitPurchaseOrders(client, symbol, priceFormat, quantityFo
63500
63498
  delete v.timeInForce;
63501
63499
  v.orderType = `MARKET`;
63502
63500
  } else if (typeof x.stop === "number") {
63503
- v.triggerPrice = to_f2(x.stop, priceFormat).toString();
63501
+ v.triggerPrice = to_f(x.stop, priceFormat).toString();
63504
63502
  }
63505
63503
  if (x.kind === "long" && x.side === "sell" || x.kind === "short" && x.side === "buy") {
63506
63504
  v.tpslMode = "Partial";
63507
63505
  v.slOrderType = "Limit";
63508
- v.slLimitPrice = to_f2(v.triggerPrice, priceFormat).toString();
63506
+ v.slLimitPrice = to_f(v.triggerPrice, priceFormat).toString();
63509
63507
  if (x.is_market) {
63510
63508
  v.slOrderType = "Market";
63511
63509
  v.tpslMode = "Full";
@@ -63738,7 +63736,7 @@ async function getWalletBalance2(client, asset = "USDT") {
63738
63736
  accountType: "UNIFIED",
63739
63737
  coin: asset
63740
63738
  });
63741
- return to_f2(response.result.list[0].totalWalletBalance, "%.2f");
63739
+ return to_f(response.result.list[0].totalWalletBalance, "%.2f");
63742
63740
  }
63743
63741
  async function allWalletBalances2(client) {
63744
63742
  const response = await client.getWalletBalance({
@@ -63748,7 +63746,7 @@ async function allWalletBalances2(client) {
63748
63746
  return response.result.list[0].coin.map((x) => ({
63749
63747
  type: "future",
63750
63748
  asset: x.coin,
63751
- balance: to_f2(x.walletBalance, "%.8f")
63749
+ balance: to_f(x.walletBalance, "%.8f")
63752
63750
  }));
63753
63751
  }
63754
63752
  function buildPosition2(position2, orders, options) {
@@ -64045,7 +64043,7 @@ class BybitExchange extends BaseExchange {
64045
64043
  function determine_liquidation(balance_diff, position2) {
64046
64044
  const long_liquidation = position2.price - balance_diff / position2.quantity;
64047
64045
  const short_liquidation = position2.price + balance_diff / position2.quantity;
64048
- return position2.kind === "long" ? to_f2(long_liquidation, "%.2f") : to_f2(short_liquidation, "%.2f");
64046
+ return position2.kind === "long" ? to_f(long_liquidation, "%.2f") : to_f(short_liquidation, "%.2f");
64049
64047
  }
64050
64048
  function calculate_avg_entry(kind, {
64051
64049
  orders: _orders,
@@ -64210,13 +64208,13 @@ function calculateHedge(payload) {
64210
64208
  const stopLossQuantity = Math.min(stopLossAmount / priceDifference, oppositePosition.quantity);
64211
64209
  return {
64212
64210
  [kind]: {
64213
- price: to_f2(takeProfitPrice, active_account.price_places),
64214
- quantity: to_f2(position_quantity || 0, active_account.decimal_places),
64211
+ price: to_f(takeProfitPrice, active_account.price_places),
64212
+ quantity: to_f(position_quantity || 0, active_account.decimal_places),
64215
64213
  type: "TAKE_PROFIT"
64216
64214
  },
64217
64215
  [oppositeKind]: {
64218
- stop_price: to_f2(stopLossPrice, active_account.price_places),
64219
- quantity: to_f2(stopLossQuantity || 0, active_account.decimal_places),
64216
+ stop_price: to_f(stopLossPrice, active_account.price_places),
64217
+ quantity: to_f(stopLossQuantity || 0, active_account.decimal_places),
64220
64218
  type: "STOP_LOSS"
64221
64219
  }
64222
64220
  };
@@ -64281,7 +64279,7 @@ function processPosition(codeNode, input, kind) {
64281
64279
  side: reverse_kind === "long" ? "buy" : "sell"
64282
64280
  },
64283
64281
  orders_to_cancel,
64284
- stop: to_f2(vv[kind].price, active_account.price_places),
64282
+ stop: to_f(vv[kind].price, active_account.price_places),
64285
64283
  quantity: vv[kind].quantity,
64286
64284
  kind,
64287
64285
  type: JSON.stringify("TAKE_PROFIT"),
@@ -64300,7 +64298,7 @@ function processPosition(codeNode, input, kind) {
64300
64298
  }
64301
64299
  async function reduceMajorPositionCalculation(input, exchange_instance) {
64302
64300
  try {
64303
- let conditionsCheck = input.position.tp_quantity !== input.quantity || input.position.take_profit !== to_f2(input.stop, input.price_places);
64301
+ let conditionsCheck = input.position.tp_quantity !== input.quantity || input.position.take_profit !== to_f(input.stop, input.price_places);
64304
64302
  if (!isNaN(input.opposite_position.stop_quantity) && input.opposite_position.stop_quantity > -1) {
64305
64303
  conditionsCheck = conditionsCheck || input.opposite_position.stop_quantity !== input.to_place.quantity;
64306
64304
  }
@@ -64425,15 +64423,20 @@ async function reduceMajorPositionEntry(input, accountInfo, trigger2, exchange_i
64425
64423
  // src/position.ts
64426
64424
  class ExchangePosition {
64427
64425
  exchange;
64426
+ symbol_config;
64428
64427
  exchange_account;
64429
64428
  app_db;
64430
64429
  instance;
64431
64430
  constructor(payload) {
64431
+ this.symbol_config = payload.symbol_config;
64432
64432
  this.exchange = payload.exchange;
64433
64433
  this.app_db = payload.app_db;
64434
64434
  this.instance = payload.instance;
64435
64435
  this.exchange_account = payload.exchange_account;
64436
64436
  }
64437
+ getInstance() {
64438
+ return this.instance;
64439
+ }
64437
64440
  get symbol() {
64438
64441
  return this.instance.symbol;
64439
64442
  }
@@ -64441,16 +64444,18 @@ class ExchangePosition {
64441
64444
  return this.instance.kind;
64442
64445
  }
64443
64446
  get account() {
64444
- return this.instance.account;
64447
+ const { p_account } = this.instance.expand;
64448
+ return p_account;
64445
64449
  }
64446
64450
  async cancelOrders(payload) {
64447
- const { limit, price: _price } = payload;
64451
+ const { limit, price: _price, raw } = payload;
64448
64452
  if (limit) {
64449
64453
  return await this.app_db.cancelLimitOrders({
64450
64454
  symbol: this.symbol,
64451
64455
  kind: this.kind,
64452
64456
  account: this.account,
64453
- cancelExchangeOrders: (p) => this.exchange.cancelOrders(p)
64457
+ cancelExchangeOrders: (p) => this.exchange.cancelOrders(p),
64458
+ raw
64454
64459
  });
64455
64460
  }
64456
64461
  let price = _price || 0;
@@ -64483,6 +64488,9 @@ class ExchangePosition {
64483
64488
  return await this.app_db.createOrUpdatePositionConfig(this.instance, params);
64484
64489
  }
64485
64490
  }
64491
+ if (this.instance.expand?.b_config) {
64492
+ return this.instance.expand.b_config;
64493
+ }
64486
64494
  return await this.app_db.getPositionConfig({
64487
64495
  symbol: this.symbol,
64488
64496
  kind: this.kind,
@@ -64491,15 +64499,19 @@ class ExchangePosition {
64491
64499
  }
64492
64500
  async updateTargetPnl() {
64493
64501
  const position2 = this.instance;
64494
- if (position2?.expand?.config) {
64495
- const config2 = position2.expand.config;
64502
+ const config2 = await this.getConfig();
64503
+ if (config2) {
64496
64504
  let _profit = config2.profit;
64505
+ let risk = config2.risk;
64506
+ let next_risk = position2.next_risk;
64497
64507
  let _profit_percent = config2?.profit_percent;
64498
64508
  if (_profit_percent && (position2?.quantity || 0) > 0) {
64499
- _profit = to_f2(position2.quantity * _profit_percent * position2.entry / 100);
64509
+ _profit = to_f(position2.quantity * _profit_percent * position2.entry / 100);
64510
+ next_risk = risk + _profit;
64500
64511
  }
64501
64512
  await this.app_db.update_db_position(position2, {
64502
- target_pnl: _profit
64513
+ target_pnl: _profit,
64514
+ next_risk
64503
64515
  });
64504
64516
  return _profit;
64505
64517
  }
@@ -64519,13 +64531,13 @@ class ExchangePosition {
64519
64531
  }
64520
64532
  }
64521
64533
  async triggerTradeFromConfig(payload) {
64522
- const { place = true, stop, use_current, ignore_config } = payload;
64534
+ const { place = true, stop, use_current, ignore_config, risky } = payload;
64523
64535
  const position2 = this.instance;
64524
64536
  const config2 = await this.getConfig();
64525
64537
  let condition = ignore_config ? true : position2?.config;
64526
64538
  if (condition) {
64527
64539
  let entry = payload.tp ? position2.entry || config2.entry : config2.entry;
64528
- const v = stop ? "place_stop_orders" : "place_limit_orders";
64540
+ const v = stop ? "place_stop_orders" : risky ? "dangerous_entry_orders" : "place_limit_orders";
64529
64541
  return await this.placeSharedOrder(v, {
64530
64542
  entry,
64531
64543
  stop: config2.stop,
@@ -64533,18 +64545,26 @@ class ExchangePosition {
64533
64545
  risk: config2.risk,
64534
64546
  place,
64535
64547
  raw: payload.raw,
64536
- use_current
64548
+ use_current,
64549
+ stop_percent: config2.stop_percent || 100
64537
64550
  });
64538
64551
  }
64539
64552
  }
64540
64553
  async placeSharedOrder(action, payload) {
64554
+ const { stop_percent = 100 } = payload;
64555
+ const config2 = await this.getConfig();
64541
64556
  const app_config = await this.buildAppConfig({
64542
64557
  entry: payload.entry,
64543
64558
  stop: payload.stop,
64544
64559
  risk_reward: payload.risk_reward,
64545
64560
  risk: payload.risk,
64546
64561
  profit: 0,
64547
- update_db: payload.update_db
64562
+ update_db: payload.update_db,
64563
+ use_kelly: config2.kelly?.use_kelly,
64564
+ kelly_confidence_factor: config2.kelly?.kelly_confidence_factor,
64565
+ kelly_minimum_risk: config2.kelly?.kelly_minimum_risk,
64566
+ kelly_prediction_model: config2.kelly?.kelly_prediction_model,
64567
+ kelly_func: config2.kelly?.kelly_func
64548
64568
  });
64549
64569
  const { entry_orders, stop_orders, trades } = await this.placeConfigOrders(app_config, {
64550
64570
  risk_reward: payload.risk_reward,
@@ -64554,7 +64574,13 @@ class ExchangePosition {
64554
64574
  avg_size: 0,
64555
64575
  neg_pnl: 0,
64556
64576
  min_size: app_config.min_size,
64557
- symbol: this.symbol
64577
+ symbol: this.symbol,
64578
+ stop_percent,
64579
+ use_kelly: config2.kelly?.use_kelly,
64580
+ kelly_confidence_factor: config2.kelly?.kelly_confidence_factor,
64581
+ kelly_minimum_risk: config2.kelly?.kelly_minimum_risk,
64582
+ kelly_prediction_model: config2.kelly?.kelly_prediction_model,
64583
+ kelly_func: config2.kelly?.kelly_func
64558
64584
  }, false);
64559
64585
  if (payload.raw) {
64560
64586
  let actual_orders_to_buy = await this.determineAmountToBuy({
@@ -64590,12 +64616,23 @@ class ExchangePosition {
64590
64616
  symbol: this.symbol,
64591
64617
  place: payload.place
64592
64618
  });
64593
- await this.exchange_account.getLiveExchangeInstance({
64594
- symbol: this.symbol,
64595
- refresh: true
64596
- });
64597
64619
  return result;
64598
64620
  }
64621
+ if (action == "dangerous_entry_orders" && payload.place) {
64622
+ return await this.exchange.createLimitPurchaseOrders({
64623
+ orders: trades.map((x) => ({
64624
+ ...x,
64625
+ price: x.entry,
64626
+ quantity: x.quantity,
64627
+ side: app_config.kind === "long" ? "buy" : "sell",
64628
+ kind: app_config.kind
64629
+ })),
64630
+ kind: app_config.kind,
64631
+ decimal_places: app_config.decimal_places,
64632
+ price_places: app_config.price_places,
64633
+ symbol: this.symbol
64634
+ });
64635
+ }
64599
64636
  if (action === "place_stop_orders" && payload.place) {
64600
64637
  const instance = this.instance;
64601
64638
  let result = await this.exchange.placeStopOrders({
@@ -64607,10 +64644,6 @@ class ExchangePosition {
64607
64644
  decimal_places: app_config.decimal_places,
64608
64645
  place: true
64609
64646
  });
64610
- await this.exchange_account.getLiveExchangeInstance({
64611
- symbol: this.symbol,
64612
- refresh: true
64613
- });
64614
64647
  return result;
64615
64648
  }
64616
64649
  return {
@@ -64639,11 +64672,19 @@ class ExchangePosition {
64639
64672
  return app_config;
64640
64673
  }
64641
64674
  async placeConfigOrders(app_config, solution, place, skip_stop) {
64675
+ const { stop_percent = 100 } = solution;
64642
64676
  app_config.entry = solution.entry;
64643
64677
  app_config.stop = solution.stop;
64644
64678
  app_config.risk_per_trade = solution.risk_per_trade;
64645
64679
  app_config.min_size = solution.min_size;
64646
64680
  app_config.risk_reward = solution.risk_reward;
64681
+ app_config.kelly = {
64682
+ use_kelly: solution.use_kelly,
64683
+ kelly_confidence_factor: solution.kelly_confidence_factor,
64684
+ kelly_minimum_risk: solution.kelly_minimum_risk,
64685
+ kelly_prediction_model: solution.kelly_prediction_model,
64686
+ kelly_func: solution.kelly_func
64687
+ };
64647
64688
  const options = {
64648
64689
  take_profit: null,
64649
64690
  entry: app_config.entry,
@@ -64657,7 +64698,12 @@ class ExchangePosition {
64657
64698
  gap: app_config.gap,
64658
64699
  rr: app_config.rr,
64659
64700
  price_places: app_config.price_places,
64660
- decimal_places: app_config.decimal_places
64701
+ decimal_places: app_config.decimal_places,
64702
+ use_kelly: solution.use_kelly,
64703
+ kelly_confidence_factor: solution.kelly_confidence_factor,
64704
+ kelly_minimum_risk: solution.kelly_minimum_risk,
64705
+ kelly_prediction_model: solution.kelly_prediction_model,
64706
+ kelly_func: solution.kelly_func
64661
64707
  };
64662
64708
  const trades = sortedBuildConfig(app_config, options);
64663
64709
  const entry_orders = {
@@ -64671,9 +64717,13 @@ class ExchangePosition {
64671
64717
  })),
64672
64718
  kind: app_config.kind
64673
64719
  };
64720
+ const last_order = trades[0]?.entry;
64721
+ const stop_spread = stop_percent / 100;
64722
+ const _stop = app_config.kind === "short" ? last_order * (1 + stop_spread) : last_order * (1 - stop_spread);
64723
+ const stop_to_user = stop_percent === 100 ? solution.stop : _stop;
64674
64724
  const stop_orders = {
64675
- stop: solution.stop,
64676
- final_stop: solution.stop,
64725
+ stop: stop_to_user,
64726
+ final_stop: stop_to_user,
64677
64727
  kind: app_config.kind,
64678
64728
  quantity: trades[0]?.avg_size,
64679
64729
  is_limit: true,
@@ -64715,7 +64765,7 @@ class ExchangePosition {
64715
64765
  async determineAmountToBuy(payload) {
64716
64766
  const { orders, kind, decimal_places = "%.3f", refresh, cancel } = payload;
64717
64767
  const totalQuantity = orders.reduce((sum, order) => sum + (order.quantity || 0), 0);
64718
- let runningTotal = to_f2(totalQuantity, decimal_places);
64768
+ let runningTotal = to_f(totalQuantity, decimal_places);
64719
64769
  let sortedOrders = [...orders].sort((a, b) => (a.entry || 0) - (b.entry || 0));
64720
64770
  if (kind === "short") {
64721
64771
  sortedOrders.reverse();
@@ -64727,7 +64777,7 @@ class ExchangePosition {
64727
64777
  cumulative_quantity: runningTotal
64728
64778
  });
64729
64779
  runningTotal -= order.quantity;
64730
- runningTotal = to_f2(runningTotal, decimal_places);
64780
+ runningTotal = to_f(runningTotal, decimal_places);
64731
64781
  }
64732
64782
  const { instance: position2, existingOrders } = await this.refresh(refresh);
64733
64783
  let filteredOrders = withCumulative.filter((order) => (order.cumulative_quantity || 0) > position2?.quantity).map((order) => ({
@@ -64749,14 +64799,11 @@ class ExchangePosition {
64749
64799
  return filteredOrders;
64750
64800
  }
64751
64801
  async refresh(live_refresh) {
64752
- await this.exchange_account.refreshAccount({
64753
- symbol: this.symbol,
64754
- live_refresh
64755
- });
64756
64802
  const instance = await this.exchange_account.syncAccount({
64757
64803
  symbol: this.symbol,
64758
64804
  kind: this.kind,
64759
- update: true
64805
+ update: true,
64806
+ live_refresh
64760
64807
  });
64761
64808
  let existingOrders = await this.exchange_account.syncOrders({
64762
64809
  symbol: this.symbol,
@@ -64765,29 +64812,467 @@ class ExchangePosition {
64765
64812
  return { instance, existingOrders };
64766
64813
  }
64767
64814
  async placeTrade(payload) {
64768
- const { place, tp, raw: _raw, cancel, stop, ignore_config } = payload;
64815
+ const {
64816
+ place,
64817
+ tp,
64818
+ raw: _raw,
64819
+ cancel,
64820
+ stop,
64821
+ ignore_config,
64822
+ risky,
64823
+ limit = true,
64824
+ target_pnl
64825
+ } = payload;
64769
64826
  if (cancel) {
64770
64827
  await this.cancelOrders({
64771
64828
  limit: true
64772
64829
  });
64773
64830
  }
64774
- if (place) {
64831
+ if (limit) {
64775
64832
  return await this.triggerTradeFromConfig({
64776
- raw: payload.raw,
64833
+ raw: _raw,
64777
64834
  stop,
64778
- ignore_config
64835
+ ignore_config,
64836
+ risky,
64837
+ place
64779
64838
  });
64780
64839
  }
64781
64840
  const rr = await this.refresh(true);
64782
- await this.updateTargetPnl();
64841
+ await this.updateConfigPnl();
64783
64842
  if (tp) {
64784
64843
  await this.exchange_account.placeProfitAndStop({
64785
64844
  symbol: this.symbol,
64786
- trigger: true
64845
+ trigger: true,
64846
+ target_pnl
64787
64847
  });
64788
64848
  }
64849
+ return [];
64789
64850
  return rr.existingOrders;
64790
64851
  }
64852
+ async placeStopLimit(payload) {
64853
+ const { place, stop, quantity: _quantity } = payload;
64854
+ const kind = this.kind;
64855
+ const symbol = this.symbol;
64856
+ const position2 = this.instance;
64857
+ if (position2.avg_qty && position2.avg_qty > 0) {
64858
+ const spread = 1.00005;
64859
+ const qty = _quantity || position2.avg_qty - position2.quantity;
64860
+ const symbol_config = this.symbol_config;
64861
+ const orders = [
64862
+ {
64863
+ kind,
64864
+ stop,
64865
+ quantity: to_f(qty, symbol_config.decimal_places),
64866
+ side: kind === "long" ? "buy" : "sell",
64867
+ price: to_f(kind === "short" ? stop * spread ** -1 : stop * spread, symbol_config.price_places)
64868
+ }
64869
+ ];
64870
+ if (place) {
64871
+ return this.exchange.placeBadStopEntry({
64872
+ symbol,
64873
+ orders,
64874
+ price_places: symbol_config.price_places,
64875
+ decimal_places: symbol_config.decimal_places
64876
+ });
64877
+ }
64878
+ return orders;
64879
+ }
64880
+ return [];
64881
+ }
64882
+ async computeTargetPnl(payload) {
64883
+ const { secondary } = payload;
64884
+ const root_position = this.instance;
64885
+ const reverse_position = secondary.instance;
64886
+ if (reverse_position?.expand?.b_config && root_position.quantity > 0) {
64887
+ const reverse_config = reverse_position.expand.b_config;
64888
+ const diff = Math.abs(reverse_config.stop - root_position.entry);
64889
+ const result = to_f(diff * root_position.quantity);
64890
+ if (root_position.target_pnl !== result) {
64891
+ await this.app_db.update_db_position(root_position, {
64892
+ target_pnl: result
64893
+ });
64894
+ await secondary.getConfig({
64895
+ params: {
64896
+ ...reverse_config,
64897
+ risk: result
64898
+ }
64899
+ });
64900
+ }
64901
+ return result;
64902
+ }
64903
+ return 0;
64904
+ }
64905
+ async runSimulation(payload) {
64906
+ const { iterations = 2, raw = false } = payload;
64907
+ const kind = this.kind;
64908
+ const symbol_config = this.symbol_config;
64909
+ const long_position = payload.long_position.instance;
64910
+ const short_position = payload.short_position.instance;
64911
+ const long_config = await payload.long_position.getConfig();
64912
+ const short_config = await payload.short_position.getConfig();
64913
+ const focus_config = kind === "long" ? long_config : short_config;
64914
+ const short_tp_factor = short_config.profit_percent / long_config.profit_percent;
64915
+ const reduce_ratio = focus_config.reduce_ratio;
64916
+ const budget = focus_config.risk;
64917
+ const risk_reward = focus_config.risk_reward;
64918
+ const tp_percent = long_config.profit_percent;
64919
+ const fee_percent = symbol_config.fee_percent;
64920
+ const strategy_config = {
64921
+ tp_percent,
64922
+ short_tp_factor,
64923
+ fee_percent,
64924
+ budget,
64925
+ risk_reward,
64926
+ reduce_ratio,
64927
+ global_config: symbol_config
64928
+ };
64929
+ const strategy2 = new Strategy({
64930
+ long: {
64931
+ entry: long_position.entry,
64932
+ quantity: long_position.quantity,
64933
+ avg_price: long_position.avg_price,
64934
+ avg_qty: long_position.avg_qty
64935
+ },
64936
+ short: {
64937
+ entry: short_position.entry,
64938
+ quantity: short_position.quantity,
64939
+ avg_price: short_position.avg_price,
64940
+ avg_qty: short_position.avg_qty
64941
+ },
64942
+ config: strategy_config
64943
+ });
64944
+ if (raw) {
64945
+ return strategy2;
64946
+ }
64947
+ return strategy2.runIterations({
64948
+ iterations,
64949
+ kind
64950
+ });
64951
+ }
64952
+ async placeOppositeTradeAction(payload) {
64953
+ const { data } = payload;
64954
+ const position2 = this.instance;
64955
+ if (position2.avg_qty !== data.avg.quantity) {
64956
+ const config2 = await this.getConfig();
64957
+ await this.app_db.updateScheduledTrade(config2.id, {
64958
+ entry: data.entry,
64959
+ stop: data.stop,
64960
+ risk: data.risk_per_trade,
64961
+ profit_percent: data.profit_percent,
64962
+ risk_reward: data.risk_reward
64963
+ });
64964
+ await this.placeTrade({
64965
+ place: true,
64966
+ ignore_config: true
64967
+ });
64968
+ await this.placeTrade({
64969
+ place: true,
64970
+ stop: true,
64971
+ ignore_config: true
64972
+ });
64973
+ }
64974
+ }
64975
+ async updateRiskOnEmpty() {
64976
+ const position2 = this.instance;
64977
+ if (position2 && position2.quantity === 0) {
64978
+ if (position2.next_risk && position2.next_risk > 0) {
64979
+ await this.getConfig({
64980
+ params: {
64981
+ risk: position2.next_risk
64982
+ }
64983
+ });
64984
+ console.log(`Updated ${this.kind} position config for ${this.symbol}: risk = ${position2.next_risk}`);
64985
+ return {
64986
+ updated: true,
64987
+ symbol: this.symbol,
64988
+ kind: this.kind,
64989
+ old_risk: position2.expand?.b_config?.risk,
64990
+ new_risk: position2.next_risk
64991
+ };
64992
+ }
64993
+ }
64994
+ return {
64995
+ updated: false,
64996
+ symbol: this.symbol,
64997
+ kind: this.kind,
64998
+ reason: position2 ? position2.quantity > 0 ? "Position not empty" : "No next_risk available" : "Position not found"
64999
+ };
65000
+ }
65001
+ async increasePositionAtStop(payload) {
65002
+ const { place = false, increase = true } = payload;
65003
+ const position2 = this.instance;
65004
+ console.log(position2);
65005
+ let price_params = {
65006
+ price: payload.price,
65007
+ quantity: payload.quantity
65008
+ };
65009
+ if (!payload.price && position2 && position2.stop_loss) {
65010
+ price_params.price = position2.stop_loss.price;
65011
+ }
65012
+ if (!payload.quantity && position2 && position2.stop_loss) {
65013
+ price_params.quantity = position2.stop_loss.quantity;
65014
+ }
65015
+ if (price_params.price && price_params.quantity) {
65016
+ const { price, quantity } = price_params;
65017
+ const symbol_config = this.symbol_config;
65018
+ const price_places = symbol_config.price_places;
65019
+ const decimal_places = symbol_config.decimal_places;
65020
+ if (place) {
65021
+ await this.cancelOrders({
65022
+ limit: true
65023
+ });
65024
+ }
65025
+ return await this.exchange.customStopLoss({
65026
+ symbol: this.symbol,
65027
+ kind: this.kind,
65028
+ stop: price,
65029
+ quantity,
65030
+ price_places,
65031
+ decimal_places,
65032
+ increase,
65033
+ place
65034
+ });
65035
+ }
65036
+ }
65037
+ async placeSingleOrder(payload) {
65038
+ const { long_position, short_position } = payload;
65039
+ const kind = this.kind;
65040
+ const long_config = await long_position.getConfig();
65041
+ const short_config = await short_position.getConfig();
65042
+ const focus_config = kind === "long" ? long_config : short_config;
65043
+ const focus_position = kind === "long" ? long_position.instance : short_position.instance;
65044
+ const track_position = kind === "long" ? short_position.instance : long_position.instance;
65045
+ const follow = focus_config.follow || focus_position.follow;
65046
+ const threshold_qty = focus_config.threshold_qty || focus_position.threshold_qty;
65047
+ if (!follow) {
65048
+ return "No follow set";
65049
+ }
65050
+ let should_place_order = false;
65051
+ if (threshold_qty === 0) {
65052
+ should_place_order = true;
65053
+ }
65054
+ if (threshold_qty > 0 && track_position.quantity >= threshold_qty) {
65055
+ should_place_order = true;
65056
+ }
65057
+ if (focus_position.quantity === 0) {
65058
+ should_place_order = true;
65059
+ }
65060
+ if (track_position.quantity !== focus_position.quantity && focus_position.quantity < track_position.quantity && should_place_order) {
65061
+ const remaining_quantity = Math.abs(track_position.quantity - focus_position.quantity);
65062
+ await this.placeMarketOrder({
65063
+ quantity: remaining_quantity
65064
+ });
65065
+ }
65066
+ }
65067
+ async placeMarketOrder(payload) {
65068
+ const { quantity } = payload;
65069
+ const symbol_config = this.symbol_config;
65070
+ await this.exchange.placeMarketOrder({
65071
+ symbol: this.symbol,
65072
+ kind: this.kind,
65073
+ quantity,
65074
+ price_places: symbol_config.price_places,
65075
+ decimal_places: symbol_config.decimal_places
65076
+ });
65077
+ }
65078
+ async generate_config_params(payload) {
65079
+ const { entry, stop, risk_reward, risk, with_trades = false } = payload;
65080
+ const symbol = this.symbol;
65081
+ const app_config = await this.buildAppConfig({
65082
+ entry,
65083
+ stop,
65084
+ risk_reward,
65085
+ risk
65086
+ });
65087
+ let config2 = generate_config_params(app_config, {
65088
+ entry,
65089
+ stop,
65090
+ risk_reward,
65091
+ risk,
65092
+ symbol
65093
+ });
65094
+ if (with_trades) {
65095
+ const app_config2 = await this.buildAppConfig({
65096
+ entry: config2.entry,
65097
+ stop: config2.stop,
65098
+ risk_reward: config2.risk_reward,
65099
+ risk: config2.risk,
65100
+ profit: 0,
65101
+ update_db: false
65102
+ });
65103
+ const { trades } = await this.placeConfigOrders(app_config2, {
65104
+ risk_reward: config2.risk_reward,
65105
+ entry: config2.entry,
65106
+ stop: config2.stop,
65107
+ risk_per_trade: config2.risk,
65108
+ avg_size: 0,
65109
+ neg_pnl: 0,
65110
+ min_size: app_config2.min_size,
65111
+ symbol
65112
+ }, false);
65113
+ config2.trades = trades;
65114
+ }
65115
+ return { ...config2, place_stop: false, profit_percent: 0 };
65116
+ }
65117
+ async extrapolateConfig(payload) {
65118
+ const { risk_reward = 199, risk, kind } = payload;
65119
+ const position2 = this.instance;
65120
+ if (position2) {
65121
+ let entry = position2.next_order || position2.avg_liquidation;
65122
+ if (kind == "short" && entry < 0) {
65123
+ const symbol_config = this.symbol_config;
65124
+ entry = symbol_config?.support;
65125
+ }
65126
+ return await this.generate_config_params({
65127
+ entry,
65128
+ stop: position2.take_profit,
65129
+ risk_reward,
65130
+ risk: risk || position2.target_pnl
65131
+ });
65132
+ }
65133
+ return null;
65134
+ }
65135
+ async build_short_order() {
65136
+ const kind = this.kind;
65137
+ const position2 = this.instance;
65138
+ const position_config = await this.getConfig();
65139
+ if (position2 && position_config && position2.entry > 0) {
65140
+ let next_order = position2.next_order;
65141
+ let take_profit = position2.take_profit;
65142
+ if (next_order && take_profit) {
65143
+ let config2 = await this.buildConfigForSymbol({
65144
+ risk: position_config.risk,
65145
+ risk_reward: position_config.risk_reward,
65146
+ as_config: true
65147
+ });
65148
+ const focus = config2.entries.filter((x) => {
65149
+ if (kind == "long") {
65150
+ return x.entry <= next_order;
65151
+ } else {
65152
+ return x.entry >= next_order;
65153
+ }
65154
+ });
65155
+ const focus_entry = focus.at(-1);
65156
+ if (focus_entry) {
65157
+ let entry = focus_entry.entry;
65158
+ let risk = Math.abs(focus_entry.neg_pnl);
65159
+ return await this.generate_config_params({
65160
+ entry,
65161
+ stop: take_profit,
65162
+ risk_reward: position_config.risk_reward,
65163
+ risk
65164
+ });
65165
+ }
65166
+ }
65167
+ }
65168
+ }
65169
+ async buildConfigForSymbol(payload) {
65170
+ const kind = this.kind;
65171
+ const { risk, risk_reward = 199, as_config = false } = payload;
65172
+ const symbol_config = this.symbol_config;
65173
+ const long_config = await this.generate_config_params({
65174
+ entry: kind === "long" ? symbol_config.resistance : symbol_config.support,
65175
+ stop: kind === "long" ? symbol_config.support : symbol_config.resistance,
65176
+ risk_reward,
65177
+ risk
65178
+ });
65179
+ if (as_config) {
65180
+ const app_config = buildAppConfig(symbol_config, {
65181
+ entry: long_config.entry,
65182
+ stop: long_config.stop,
65183
+ risk_reward,
65184
+ risk: long_config.risk,
65185
+ symbol: this.symbol
65186
+ });
65187
+ return app_config;
65188
+ }
65189
+ return long_config;
65190
+ }
65191
+ async buildTrades(payload) {
65192
+ const { risk } = payload;
65193
+ const config2 = await this.getConfig();
65194
+ const app_config = await this.buildAppConfig({
65195
+ entry: config2.entry,
65196
+ stop: config2.stop,
65197
+ risk_reward: config2.risk_reward,
65198
+ risk: risk || config2.risk
65199
+ });
65200
+ const { trades } = await this.placeConfigOrders(app_config, {
65201
+ risk_reward: config2.risk_reward,
65202
+ entry: config2.entry,
65203
+ stop: config2.stop,
65204
+ risk_per_trade: risk || config2.risk,
65205
+ avg_size: 0,
65206
+ neg_pnl: 0,
65207
+ min_size: app_config.min_size,
65208
+ symbol: this.symbol,
65209
+ kelly_confidence_factor: config2.kelly?.kelly_confidence_factor,
65210
+ kelly_minimum_risk: config2.kelly?.kelly_minimum_risk,
65211
+ kelly_prediction_model: config2.kelly?.kelly_prediction_model,
65212
+ kelly_func: config2.kelly?.kelly_func
65213
+ });
65214
+ const position2 = this.instance;
65215
+ const orders_to_place = await this.determineAmountToBuy({
65216
+ orders: trades.map((x) => ({
65217
+ entry: x.entry,
65218
+ quantity: x.quantity
65219
+ })),
65220
+ kind: this.kind,
65221
+ decimal_places: app_config.decimal_places,
65222
+ price_places: app_config.price_places
65223
+ });
65224
+ const avg_values = determine_average_entry_and_size(orders_to_place.map((u) => ({
65225
+ price: u.entry,
65226
+ quantity: u.quantity
65227
+ })).concat({
65228
+ price: position2.entry,
65229
+ quantity: position2.quantity
65230
+ }), app_config.decimal_places, app_config.price_places);
65231
+ return {
65232
+ trades: orders_to_place,
65233
+ max_size: trades[0].avg_size,
65234
+ last_price: trades[0].entry,
65235
+ total_size: avg_values.quantity,
65236
+ avg_entry: avg_values.price
65237
+ };
65238
+ }
65239
+ async tradeConfig(payload) {
65240
+ const { override = {} } = payload;
65241
+ const config2 = await this.getConfig();
65242
+ const app_config = await this.buildAppConfig({
65243
+ entry: config2.entry,
65244
+ stop: config2.stop,
65245
+ risk_reward: config2.risk_reward,
65246
+ risk: config2.risk,
65247
+ symbol: this.symbol,
65248
+ use_kelly: config2.kelly?.use_kelly,
65249
+ kelly_confidence_factor: config2.kelly?.kelly_confidence_factor,
65250
+ kelly_minimum_risk: config2.kelly?.kelly_minimum_risk,
65251
+ kelly_prediction_model: config2.kelly?.kelly_prediction_model,
65252
+ kelly_func: config2.kelly?.kelly_func,
65253
+ ...override
65254
+ });
65255
+ return app_config;
65256
+ }
65257
+ async getOrCreatePositionConfig(payload) {
65258
+ const { risk = 50, risk_reward = 199 } = payload;
65259
+ const config2 = await this.getConfig();
65260
+ if (!config2) {
65261
+ const long_c = await this.buildConfigForSymbol({
65262
+ risk,
65263
+ risk_reward
65264
+ });
65265
+ return this.getConfig({
65266
+ params: {
65267
+ entry: config2.entry,
65268
+ stop: config2.stop,
65269
+ risk_reward: long_c.risk_reward,
65270
+ risk: long_c.risk
65271
+ }
65272
+ });
65273
+ }
65274
+ return config2;
65275
+ }
64791
65276
  }
64792
65277
 
64793
65278
  // src/exchange-account.ts
@@ -64838,16 +65323,22 @@ class ExchangeAccount {
64838
65323
  return result;
64839
65324
  }
64840
65325
  async initializePositions(payload) {
65326
+ const raw_positions = await this.syncAccount({
65327
+ update: payload.update,
65328
+ symbol: payload.symbol,
65329
+ live_refresh: payload.update
65330
+ });
64841
65331
  const positions = await this.syncAccount({
64842
65332
  symbol: payload.symbol,
64843
- as_view: payload.as_view
65333
+ as_view: true
64844
65334
  });
64845
- const raw_positions = await this.syncAccount({
65335
+ const symbol_config = await this.recomputeSymbolConfig({
64846
65336
  symbol: payload.symbol
64847
65337
  });
64848
65338
  const long_position = positions.find((x) => x.kind === "long");
64849
65339
  const short_position = positions.find((x) => x.kind === "short");
64850
65340
  this.long_position = new ExchangePosition({
65341
+ symbol_config,
64851
65342
  exchange: this.exchange,
64852
65343
  exchange_account: this,
64853
65344
  instance: long_position,
@@ -64855,6 +65346,7 @@ class ExchangeAccount {
64855
65346
  without_view: raw_positions.find((x) => x.kind === "long")
64856
65347
  });
64857
65348
  this.short_position = new ExchangePosition({
65349
+ symbol_config,
64858
65350
  exchange: this.exchange,
64859
65351
  exchange_account: this,
64860
65352
  instance: short_position,
@@ -64976,44 +65468,26 @@ class ExchangeAccount {
64976
65468
  }
64977
65469
  }
64978
65470
  }
64979
- async cancelOrders(payload) {
64980
- const { symbol, kind, price: _price, all, stop, limit, raw } = payload;
64981
- let price = _price || 0;
64982
- await this.syncAccount({
64983
- symbol,
64984
- kind,
64985
- update: true
64986
- });
64987
- if (limit) {
64988
- return await this.app_db.cancelLimitOrders({
64989
- raw,
65471
+ async getFocusPosition(payload) {
65472
+ const { symbol, kind, update = false } = payload;
65473
+ let focus_position = kind === "long" ? this.long_position : this.short_position;
65474
+ if (!focus_position) {
65475
+ focus_position = await this.initializePositions({
64990
65476
  symbol,
64991
65477
  kind,
64992
- account: this.instance,
64993
- cancelExchangeOrders: this.cancelExchangeOrders.bind(this)
65478
+ update
64994
65479
  });
64995
65480
  }
64996
- if (all) {
64997
- } else {
64998
- if (!price) {
64999
- const position2 = await this.syncAccount({
65000
- symbol,
65001
- kind: kind === "short" ? "long" : "short",
65002
- as_view: true
65003
- });
65004
- price = position2?.take_profit || 0;
65005
- }
65006
- }
65007
- let result = await this.app_db.cancelOrders({
65008
- cancelExchangeOrders: this.cancelExchangeOrders.bind(this),
65009
- all,
65010
- kind,
65011
- account: this.instance,
65481
+ return focus_position;
65482
+ }
65483
+ async cancelOrders(payload) {
65484
+ const { symbol, kind } = payload;
65485
+ const focus_position = await this.getFocusPosition({
65012
65486
  symbol,
65013
- price,
65014
- stop
65487
+ kind,
65488
+ update: true
65015
65489
  });
65016
- return result;
65490
+ return await focus_position.cancelOrders(payload);
65017
65491
  }
65018
65492
  async cancelExchangeOrders(payload) {
65019
65493
  return this.exchange.cancelOrders(payload);
@@ -65030,46 +65504,13 @@ class ExchangeAccount {
65030
65504
  });
65031
65505
  return break_even_price;
65032
65506
  }
65033
- async buildAppConfig(payload) {
65034
- let config2 = await this.app_db.getSymbolConfigFromDB(payload.symbol);
65035
- const app_config = buildAppConfig(config2, payload);
65036
- if (payload.update_db) {
65037
- const db_position = await this.syncAccount({
65038
- symbol: payload.symbol,
65039
- kind: app_config.kind
65040
- });
65041
- if (db_position) {
65042
- await this.app_db.createOrUpdatePositionConfig(db_position, {
65043
- entry: payload.entry,
65044
- stop: payload.stop,
65045
- risk_reward: payload.risk_reward,
65046
- risk: payload.risk,
65047
- profit_percent: payload.profit_percent
65048
- });
65049
- }
65050
- }
65051
- return app_config;
65052
- }
65053
65507
  async tradeConfig(payload) {
65054
65508
  const { symbol, kind, override = {} } = payload;
65055
- const config2 = await this.getPositionConfig({
65509
+ const focus_position = await this.getFocusPosition({
65056
65510
  symbol,
65057
65511
  kind
65058
65512
  });
65059
- const app_config = await this.buildAppConfig({
65060
- entry: config2.entry,
65061
- stop: config2.stop,
65062
- risk_reward: config2.risk_reward,
65063
- risk: config2.risk,
65064
- symbol,
65065
- use_kelly: config2.kelly?.use_kelly,
65066
- kelly_confidence_factor: config2.kelly?.kelly_confidence_factor,
65067
- kelly_minimum_risk: config2.kelly?.kelly_minimum_risk,
65068
- kelly_prediction_model: config2.kelly?.kelly_prediction_model,
65069
- kelly_func: config2.kelly?.kelly_func,
65070
- ...override
65071
- });
65072
- return app_config;
65513
+ return await focus_position.tradeConfig({ override });
65073
65514
  }
65074
65515
  async justInTimeProfit(payload) {
65075
65516
  const { symbol, target_pnl, kind, refresh, place, take_profit, pause_tp } = payload;
@@ -65087,7 +65528,7 @@ class ExchangeAccount {
65087
65528
  });
65088
65529
  const current_price = take_profit || position2.current_price;
65089
65530
  const notional_value = position2.quantity * position2.entry;
65090
- const current_pnl = to_f2(Math.abs(current_price - position2.entry) * position2.quantity, "%.2f");
65531
+ const current_pnl = to_f(Math.abs(current_price - position2.entry) * position2.quantity, "%.2f");
65091
65532
  const profit_percent = current_pnl * 100 / notional_value;
65092
65533
  const sell_ratio = target_pnl / current_pnl;
65093
65534
  if (place) {
@@ -65131,370 +65572,33 @@ class ExchangeAccount {
65131
65572
  }
65132
65573
  async buildTrades(payload) {
65133
65574
  const { symbol, kind, risk } = payload;
65134
- const config2 = await this.getPositionConfig({
65575
+ const focus_position = await this.getFocusPosition({
65135
65576
  symbol,
65136
65577
  kind
65137
65578
  });
65138
- const app_config = await this.buildAppConfig({
65139
- entry: config2.entry,
65140
- stop: config2.stop,
65141
- risk_reward: config2.risk_reward,
65142
- risk: risk || config2.risk,
65143
- symbol
65579
+ return await focus_position.buildTrades({ risk });
65580
+ }
65581
+ async placeSharedOrder(action, payload) {
65582
+ const kind = payload.entry > payload.stop ? "long" : "short";
65583
+ const focus_position = await this.getFocusPosition({
65584
+ symbol: payload.symbol,
65585
+ kind
65144
65586
  });
65145
- const { trades } = await this.placeConfigOrders(app_config, {
65146
- risk_reward: config2.risk_reward,
65147
- entry: config2.entry,
65148
- stop: config2.stop,
65149
- risk_per_trade: risk || config2.risk,
65150
- avg_size: 0,
65151
- neg_pnl: 0,
65152
- min_size: app_config.min_size,
65153
- symbol
65154
- });
65155
- const position2 = await this.syncAccount({
65156
- symbol,
65157
- kind
65158
- });
65159
- const orders_to_place = await this.determineAmountToBuy({
65160
- orders: trades.map((x) => ({
65161
- entry: x.entry,
65162
- quantity: x.quantity
65163
- })),
65164
- kind,
65165
- decimal_places: app_config.decimal_places,
65166
- price_places: app_config.price_places,
65167
- symbol
65168
- });
65169
- const avg_values = determine_average_entry_and_size(orders_to_place.map((u) => ({
65170
- price: u.entry,
65171
- quantity: u.quantity
65172
- })).concat({
65173
- price: position2.entry,
65174
- quantity: position2.quantity
65175
- }), app_config.decimal_places, app_config.price_places);
65176
- return {
65177
- trades: orders_to_place,
65178
- max_size: trades[0].avg_size,
65179
- last_price: trades[0].entry,
65180
- total_size: avg_values.quantity,
65181
- avg_entry: avg_values.price
65182
- };
65183
- }
65184
- async placeConfigOrders(app_config, solution, place, skip_stop) {
65185
- const { stop_percent = 100 } = solution;
65186
- app_config.entry = solution.entry;
65187
- app_config.stop = solution.stop;
65188
- app_config.risk_per_trade = solution.risk_per_trade;
65189
- app_config.min_size = solution.min_size;
65190
- app_config.risk_reward = solution.risk_reward;
65191
- app_config.kelly = {
65192
- use_kelly: solution.use_kelly,
65193
- kelly_confidence_factor: solution.kelly_confidence_factor,
65194
- kelly_minimum_risk: solution.kelly_minimum_risk,
65195
- kelly_prediction_model: solution.kelly_prediction_model,
65196
- kelly_func: solution.kelly_func
65197
- };
65198
- const options = {
65199
- take_profit: null,
65200
- entry: app_config.entry,
65201
- stop: app_config.stop,
65202
- raw_instance: null,
65203
- risk: app_config.risk_per_trade,
65204
- no_of_trades: undefined,
65205
- risk_reward: app_config.risk_reward,
65206
- kind: app_config.kind,
65207
- increase: true,
65208
- gap: app_config.gap,
65209
- rr: app_config.rr,
65210
- price_places: app_config.price_places,
65211
- decimal_places: app_config.decimal_places,
65212
- use_kelly: solution.use_kelly,
65213
- kelly_confidence_factor: solution.kelly_confidence_factor,
65214
- kelly_minimum_risk: solution.kelly_minimum_risk,
65215
- kelly_prediction_model: solution.kelly_prediction_model,
65216
- kelly_func: solution.kelly_func
65217
- };
65218
- const trades = sortedBuildConfig(app_config, options);
65219
- const entry_orders = {
65220
- orders: trades.map((x) => ({
65221
- entry: x.entry,
65222
- quantity: x.quantity,
65223
- reverse_avg_entry: x.reverse_avg_entry,
65224
- reverse_avg_quantity: x.reverse_avg_quantity,
65225
- avg_entry: x.avg_entry,
65226
- avg_size: x.avg_size
65227
- })),
65228
- kind: app_config.kind
65229
- };
65230
- const last_order = trades[0]?.entry;
65231
- const stop_spread = stop_percent / 100;
65232
- const _stop = app_config.kind === "short" ? last_order * (1 + stop_spread) : last_order * (1 - stop_spread);
65233
- const stop_to_user = stop_percent === 100 ? solution.stop : _stop;
65234
- const stop_orders = {
65235
- stop: stop_to_user,
65236
- final_stop: stop_to_user,
65237
- kind: app_config.kind,
65238
- quantity: trades[0]?.avg_size,
65239
- is_limit: true,
65240
- neg_pnl: trades[0]?.neg_pnl,
65241
- original_stop: solution.stop,
65242
- last_entry: last_order
65243
- };
65244
- if (place) {
65245
- let arr = [
65246
- this.exchange.bulkPlaceLimitOrders({
65247
- orders: trades.map((x) => ({
65248
- entry: x.entry,
65249
- quantity: x.quantity
65250
- })),
65251
- kind: app_config.kind,
65252
- decimal_places: app_config.decimal_places,
65253
- price_places: app_config.price_places,
65254
- symbol: solution.symbol,
65255
- place
65256
- })
65257
- ];
65258
- if (!skip_stop) {
65259
- arr.push(this.exchange.placeStopOrders({
65260
- symbol: solution.symbol,
65261
- quantity: trades[0].avg_size,
65262
- kind: app_config.kind,
65263
- stop: solution.stop,
65264
- price_places: app_config.price_places,
65265
- decimal_places: app_config.decimal_places,
65266
- place
65267
- }));
65268
- }
65269
- await Promise.all(arr);
65270
- }
65271
- return {
65272
- entry_orders,
65273
- stop_orders,
65274
- trades
65275
- };
65276
- }
65277
- async determineAmountToBuy(payload) {
65278
- const {
65279
- orders,
65280
- kind,
65281
- decimal_places = "%.3f",
65282
- symbol,
65283
- refresh,
65284
- cancel
65285
- } = payload;
65286
- const totalQuantity = orders.reduce((sum, order) => sum + (order.quantity || 0), 0);
65287
- let runningTotal = to_f2(totalQuantity, decimal_places);
65288
- let sortedOrders = [...orders].sort((a, b) => (a.entry || 0) - (b.entry || 0));
65289
- if (kind === "short") {
65290
- sortedOrders.reverse();
65291
- }
65292
- const withCumulative = [];
65293
- for (const order of sortedOrders) {
65294
- withCumulative.push({
65295
- ...order,
65296
- cumulative_quantity: runningTotal
65297
- });
65298
- runningTotal -= order.quantity;
65299
- runningTotal = to_f2(runningTotal, decimal_places);
65300
- }
65301
- const position2 = await this.syncAccount({
65302
- symbol,
65303
- kind,
65304
- live_refresh: refresh,
65305
- update: true
65306
- });
65307
- let existingOrders = await this.syncOrders({
65308
- symbol,
65309
- kind
65310
- });
65311
- let filteredOrders = withCumulative.filter((order) => (order.cumulative_quantity || 0) > position2?.quantity).map((order) => ({
65312
- ...order,
65313
- price: order.entry,
65314
- kind,
65315
- side: kind.toLowerCase() === "long" ? "buy" : "sell"
65316
- }));
65317
- filteredOrders = filteredOrders.filter((k) => !existingOrders.map((j) => j.price).includes(k.price));
65318
- const side = kind.toLowerCase() === "long" ? "buy" : "sell";
65319
- const shouldCancel = existingOrders.filter((k) => !orders.map((j) => j.entry).includes(k.price) && k.side === side).map((u) => u.price);
65320
- if (shouldCancel.length > 0 && cancel) {
65321
- const pp = kind === "long" ? Math.max(...shouldCancel) : Math.min(...shouldCancel);
65322
- const cancel_orders = await this.cancelOrders({
65323
- symbol,
65324
- kind,
65325
- price: pp
65326
- });
65327
- console.log("cancel_orders", cancel_orders);
65328
- }
65329
- return filteredOrders;
65330
- }
65331
- async placeSharedOrder(action, payload) {
65332
- const { stop_percent = 100 } = payload;
65333
- const kind = payload.entry > payload.stop ? "long" : "short";
65334
- const config2 = await this.getPositionConfig({
65335
- symbol: payload.symbol,
65336
- kind
65337
- });
65338
- const app_config = await this.buildAppConfig({
65339
- entry: payload.entry,
65340
- stop: payload.stop,
65341
- risk_reward: payload.risk_reward,
65342
- risk: payload.risk,
65587
+ const result = await focus_position.placeSharedOrder(action, payload);
65588
+ await this.getLiveExchangeInstance({
65343
65589
  symbol: payload.symbol,
65344
- profit: 0,
65345
- update_db: payload.update_db,
65346
- use_kelly: config2.kelly?.use_kelly,
65347
- kelly_confidence_factor: config2.kelly?.kelly_confidence_factor,
65348
- kelly_minimum_risk: config2.kelly?.kelly_minimum_risk,
65349
- kelly_prediction_model: config2.kelly?.kelly_prediction_model,
65350
- kelly_func: config2.kelly?.kelly_func
65590
+ refresh: true
65351
65591
  });
65352
- const { entry_orders, stop_orders, trades } = await this.placeConfigOrders(app_config, {
65353
- risk_reward: payload.risk_reward,
65354
- entry: payload.entry,
65355
- stop: payload.stop,
65356
- risk_per_trade: payload.risk,
65357
- avg_size: 0,
65358
- neg_pnl: 0,
65359
- min_size: app_config.min_size,
65360
- symbol: payload.symbol,
65361
- stop_percent,
65362
- use_kelly: config2.kelly?.use_kelly,
65363
- kelly_confidence_factor: config2.kelly?.kelly_confidence_factor,
65364
- kelly_minimum_risk: config2.kelly?.kelly_minimum_risk,
65365
- kelly_prediction_model: config2.kelly?.kelly_prediction_model,
65366
- kelly_func: config2.kelly?.kelly_func
65367
- }, false);
65368
- if (payload.raw) {
65369
- let actual_orders_to_buy = await this.determineAmountToBuy({
65370
- orders: trades,
65371
- kind: app_config.kind,
65372
- decimal_places: app_config.decimal_places,
65373
- price_places: app_config.price_places,
65374
- symbol: payload.symbol,
65375
- place: payload.place
65376
- });
65377
- if (action === "place_limit_orders" && payload.place) {
65378
- return await this.exchange.createLimitPurchaseOrders({
65379
- orders: actual_orders_to_buy.map((x) => ({
65380
- entry: x.entry,
65381
- quantity: x.quantity
65382
- })),
65383
- kind: app_config.kind,
65384
- decimal_places: app_config.decimal_places,
65385
- price_places: app_config.price_places,
65386
- symbol: payload.symbol
65387
- });
65388
- }
65389
- return actual_orders_to_buy;
65390
- }
65391
- if (action === "place_limit_orders" && payload.place) {
65392
- let result = await this.exchange.bulkPlaceLimitOrders({
65393
- orders: trades.map((x) => ({
65394
- entry: x.entry,
65395
- quantity: x.quantity
65396
- })),
65397
- kind: app_config.kind,
65398
- price_places: app_config.price_places,
65399
- decimal_places: app_config.decimal_places,
65400
- symbol: payload.symbol,
65401
- place: payload.place
65402
- });
65403
- await this.getLiveExchangeInstance({
65404
- symbol: payload.symbol,
65405
- refresh: true
65406
- });
65407
- return result;
65408
- }
65409
- if (action == "dangerous_entry_orders" && payload.place) {
65410
- return await this.exchange.createLimitPurchaseOrders({
65411
- orders: trades.map((x) => ({
65412
- ...x,
65413
- price: x.entry,
65414
- quantity: x.quantity,
65415
- side: app_config.kind === "long" ? "buy" : "sell",
65416
- kind: app_config.kind
65417
- })),
65418
- kind: app_config.kind,
65419
- decimal_places: app_config.decimal_places,
65420
- price_places: app_config.price_places,
65421
- symbol: payload.symbol
65422
- });
65423
- }
65424
- if (action === "place_stop_orders" && payload.place) {
65425
- const instance = await this.syncAccount({
65426
- symbol: payload.symbol,
65427
- kind: app_config.kind
65428
- });
65429
- let result = await this.exchange.placeStopOrders({
65430
- symbol: payload.symbol,
65431
- quantity: payload.use_current ? instance.quantity : trades[0].avg_size,
65432
- kind: app_config.kind,
65433
- stop: stop_orders.stop,
65434
- price_places: app_config.price_places,
65435
- decimal_places: app_config.decimal_places,
65436
- place: true
65437
- });
65438
- await this.getLiveExchangeInstance({
65439
- symbol: payload.symbol,
65440
- refresh: true
65441
- });
65442
- return result;
65443
- }
65444
- return {
65445
- entry_orders,
65446
- stop_orders
65447
- };
65592
+ return result;
65448
65593
  }
65449
65594
  async getOrCreatePositionConfig(payload) {
65450
- const { symbol, kind, risk = 50, risk_reward = 199 } = payload;
65451
- const config2 = await this.getPositionConfig({
65452
- symbol: payload.symbol,
65453
- kind: payload.kind
65454
- });
65455
- if (!config2) {
65456
- const long_c = await this.buildConfigForSymbol({
65457
- symbol,
65458
- risk,
65459
- risk_reward
65460
- });
65461
- return this.getPositionConfig({
65462
- symbol,
65463
- kind,
65464
- params: {
65465
- entry: kind === "long" ? long_c.entry : long_c.stop,
65466
- stop: kind === "long" ? long_c.stop : long_c.entry,
65467
- risk_reward: long_c.risk_reward,
65468
- risk: long_c.risk
65469
- }
65470
- });
65471
- }
65472
- return config2;
65595
+ const focus_position = await this.getFocusPosition(payload);
65596
+ return await focus_position.getOrCreatePositionConfig(payload);
65473
65597
  }
65474
65598
  async getPositionConfig(payload) {
65475
- if (payload.params) {
65476
- const db_position = await this.syncAccount({
65477
- symbol: payload.symbol,
65478
- kind: payload.kind
65479
- });
65480
- if (db_position) {
65481
- const config2 = db_position.expand?.config;
65482
- const params = {
65483
- entry: payload.params.entry !== undefined ? payload.params.entry : config2?.entry,
65484
- stop: payload.params.stop !== undefined ? payload.params.stop : config2?.stop,
65485
- risk_reward: payload.params.risk_reward !== undefined ? payload.params.risk_reward : config2?.risk_reward,
65486
- risk: payload.params.risk !== undefined ? payload.params.risk : config2?.risk,
65487
- profit_percent: payload.params.profit_percent !== undefined ? payload.params.profit_percent : config2?.profit_percent,
65488
- place_tp: payload.params.place_tp !== undefined ? payload.params.place_tp : true,
65489
- profit: payload.params.profit !== undefined ? payload.params.profit : config2?.profit
65490
- };
65491
- return await this.app_db.createOrUpdatePositionConfig(db_position, params);
65492
- }
65493
- }
65494
- return await this.app_db.getPositionConfig({
65495
- symbol: payload.symbol,
65496
- kind: payload.kind,
65497
- account: this.instance
65599
+ const focus_position = await this.getFocusPosition(payload);
65600
+ return await focus_position.getConfig({
65601
+ params: payload.params
65498
65602
  });
65499
65603
  }
65500
65604
  async getCurrentPrice(symbol) {
@@ -65507,23 +65611,23 @@ class ExchangeAccount {
65507
65611
  });
65508
65612
  }
65509
65613
  async buildReduceConfig(payload) {
65510
- const positions = await this.syncAccount({
65511
- symbol: payload.symbol
65512
- });
65513
- const long_position = positions.find((x) => x.kind === "long");
65514
- const short_position = positions.find((x) => x.kind === "short");
65515
- const long_config = await this.getPositionConfig({
65614
+ const long_position = await this.getFocusPosition({
65516
65615
  symbol: payload.symbol,
65517
65616
  kind: "long"
65518
65617
  });
65519
- const short_config = await this.getPositionConfig({
65618
+ const short_position = await this.getFocusPosition({
65520
65619
  symbol: payload.symbol,
65521
65620
  kind: "short"
65522
65621
  });
65622
+ const long_config = await long_position.getConfig();
65623
+ const short_config = await short_position.getConfig();
65523
65624
  const config2 = build_reduce_config({
65524
65625
  account: this.instance,
65525
65626
  symbol: payload.symbol,
65526
- _positions: positions,
65627
+ _positions: [
65628
+ long_position.getInstance(),
65629
+ short_position.getInstance()
65630
+ ],
65527
65631
  long_config,
65528
65632
  short_config
65529
65633
  });
@@ -65532,8 +65636,8 @@ class ExchangeAccount {
65532
65636
  }
65533
65637
  let long_target_pnl = payload.kind == "long" ? payload.target_pnl : 0;
65534
65638
  let short_target_pnl = payload.kind == "short" ? payload.target_pnl : 0;
65535
- const long_sell_ratio = long_config.sell_ratio || long_position?.sell_ratio;
65536
- const short_sell_ratio = short_config.sell_ratio || short_position?.sell_ratio;
65639
+ const long_sell_ratio = long_config.sell_ratio || long_position.getInstance()?.sell_ratio;
65640
+ const short_sell_ratio = short_config.sell_ratio || short_position.getInstance()?.sell_ratio;
65537
65641
  if (payload.as_dict) {
65538
65642
  return {
65539
65643
  long: {
@@ -65613,9 +65717,9 @@ class ExchangeAccount {
65613
65717
  async placeProfitAndStop(payload) {
65614
65718
  const { symbol, trigger: trigger2, refresh, kind, target_pnl } = payload;
65615
65719
  if (refresh) {
65616
- await this.syncAccount({
65720
+ await this.initializePositions({
65617
65721
  symbol,
65618
- live_refresh: true,
65722
+ kind,
65619
65723
  update: true
65620
65724
  });
65621
65725
  }
@@ -65648,14 +65752,16 @@ class ExchangeAccount {
65648
65752
  kind
65649
65753
  });
65650
65754
  }
65651
- const long_config = await this.getPositionConfig({
65755
+ const long_position = await this.getFocusPosition({
65652
65756
  symbol,
65653
65757
  kind: "long"
65654
65758
  });
65655
- const short_config = await this.getPositionConfig({
65759
+ const short_position = await this.getFocusPosition({
65656
65760
  symbol,
65657
65761
  kind: "short"
65658
65762
  });
65763
+ const long_config = await long_position.getConfig();
65764
+ const short_config = await short_position.getConfig();
65659
65765
  const long_pause_tp = long_config?.pause_tp;
65660
65766
  const short_pause_tp = short_config?.pause_tp;
65661
65767
  if (payload.trigger && !long_pause_tp && !short_pause_tp && config2) {
@@ -65669,299 +65775,75 @@ class ExchangeAccount {
65669
65775
  return config2;
65670
65776
  }
65671
65777
  async reEnterPositionOnEmpty(symbol) {
65672
- await this.getLiveExchangeInstance({
65778
+ const long_position = await this.getFocusPosition({
65673
65779
  symbol,
65674
- refresh: true
65780
+ kind: "long"
65675
65781
  });
65676
- const db_positions = await this.syncAccount({
65782
+ const short_position = await this.getFocusPosition({
65677
65783
  symbol,
65678
- update: true
65784
+ kind: "short"
65679
65785
  });
65680
- const long_position = db_positions.find((x) => x.kind === "long");
65681
- const short_position = db_positions.find((x) => x.kind === "short");
65682
- if (long_position && long_position.quantity === 0) {
65683
- await this.triggerTradeFromConfig({
65684
- symbol,
65685
- kind: "long"
65686
- });
65786
+ if (long_position && long_position.getInstance().quantity === 0) {
65787
+ await long_position.triggerTradeFromConfig({});
65687
65788
  }
65688
- if (short_position && short_position.quantity === 0) {
65689
- await this.triggerTradeFromConfig({
65690
- symbol,
65691
- kind: "short"
65692
- });
65789
+ if (short_position && short_position.getInstance().quantity === 0) {
65790
+ await short_position.triggerTradeFromConfig({});
65693
65791
  }
65694
- if (long_position.target_pnl > 0 || short_position.target_pnl > 0) {
65792
+ if (long_position.getInstance().target_pnl > 0 || short_position.getInstance().target_pnl > 0) {
65695
65793
  await Promise.all([
65696
- this.updateTargetPnl({
65697
- symbol,
65698
- kind: "long"
65699
- }),
65700
- this.updateTargetPnl({
65701
- symbol,
65702
- kind: "short"
65703
- })
65794
+ long_position.updateTargetPnl(),
65795
+ short_position.updateTargetPnl()
65704
65796
  ]);
65705
65797
  }
65706
65798
  }
65707
- async generate_config_params(payload) {
65708
- const {
65709
- entry,
65710
- stop,
65711
- risk_reward,
65712
- risk,
65713
- symbol,
65714
- with_trades = false
65715
- } = payload;
65716
- const app_config = await this.buildAppConfig({
65717
- entry,
65718
- stop,
65719
- risk_reward,
65720
- risk,
65721
- symbol
65722
- });
65723
- let config2 = generate_config_params(app_config, {
65724
- entry,
65725
- stop,
65726
- risk_reward,
65727
- risk,
65728
- symbol
65729
- });
65730
- if (with_trades) {
65731
- const app_config2 = await this.buildAppConfig({
65732
- entry: config2.entry,
65733
- stop: config2.stop,
65734
- risk_reward: config2.risk_reward,
65735
- risk: config2.risk,
65736
- symbol,
65737
- profit: 0,
65738
- update_db: false
65739
- });
65740
- const { trades } = await this.placeConfigOrders(app_config2, {
65741
- risk_reward: config2.risk_reward,
65742
- entry: config2.entry,
65743
- stop: config2.stop,
65744
- risk_per_trade: config2.risk,
65745
- avg_size: 0,
65746
- neg_pnl: 0,
65747
- min_size: app_config2.min_size,
65748
- symbol
65749
- }, false);
65750
- config2.trades = trades;
65751
- }
65752
- return { ...config2, place_stop: false, profit_percent: 0 };
65753
- }
65754
65799
  async build_short_order(payload) {
65755
- const { symbol, kind } = payload;
65756
- const position2 = await this.syncAccount({
65757
- symbol,
65758
- kind,
65759
- as_view: true
65760
- });
65761
- const position_config = await this.getPositionConfig({
65762
- symbol,
65763
- kind
65764
- });
65765
- if (position2 && position_config && position2.entry > 0) {
65766
- let next_order = position2.next_order;
65767
- let take_profit = position2.take_profit;
65768
- if (next_order && take_profit) {
65769
- let config2 = await this.buildConfigForSymbol({
65770
- symbol,
65771
- risk: position_config.risk,
65772
- risk_reward: position_config.risk_reward,
65773
- kind,
65774
- as_config: true
65775
- });
65776
- const focus = config2.entries.filter((x) => {
65777
- if (kind == "long") {
65778
- return x.entry <= next_order;
65779
- } else {
65780
- return x.entry >= next_order;
65781
- }
65782
- });
65783
- const focus_entry = focus.at(-1);
65784
- if (focus_entry) {
65785
- let entry = focus_entry.entry;
65786
- let risk = Math.abs(focus_entry.neg_pnl);
65787
- return await this.generate_config_params({
65788
- entry,
65789
- stop: take_profit,
65790
- risk_reward: position_config.risk_reward,
65791
- risk,
65792
- symbol
65793
- });
65794
- }
65795
- }
65796
- }
65800
+ const focus_position = await this.getFocusPosition(payload);
65801
+ return await focus_position.build_short_order();
65797
65802
  }
65798
65803
  async extrapolateShortConfig(payload) {
65799
- const { symbol, risk_reward = 199, kind, risk } = payload;
65804
+ const { symbol, kind } = payload;
65800
65805
  let reverse_kind = kind === "long" ? "short" : "long";
65801
- const position2 = await this.syncAccount({
65806
+ const focus_position = await this.getFocusPosition({
65802
65807
  symbol,
65803
- kind: reverse_kind,
65804
- as_view: true
65808
+ kind: reverse_kind
65809
+ });
65810
+ return await focus_position.extrapolateConfig({
65811
+ kind
65805
65812
  });
65806
- if (position2) {
65807
- let entry = position2.next_order || position2.avg_liquidation;
65808
- if (kind == "short" && entry < 0) {
65809
- const symbol_config = await this.recomputeSymbolConfig({
65810
- symbol
65811
- });
65812
- entry = symbol_config?.support;
65813
- }
65814
- return await this.generate_config_params({
65815
- entry,
65816
- stop: position2.take_profit,
65817
- risk_reward,
65818
- risk: risk || position2.target_pnl,
65819
- symbol
65820
- });
65821
- }
65822
- return null;
65823
65813
  }
65824
65814
  async placeMarketOrder(payload) {
65825
- const { symbol, kind, quantity } = payload;
65826
- const symbol_config = await this.recomputeSymbolConfig({
65827
- symbol
65828
- });
65829
- await this.exchange.placeMarketOrder({
65815
+ const { symbol, kind } = payload;
65816
+ const focus_position = await this.getFocusPosition(payload);
65817
+ await focus_position.placeMarketOrder(payload);
65818
+ await this.initializePositions({
65830
65819
  symbol,
65831
65820
  kind,
65832
- quantity,
65833
- price_places: symbol_config.price_places,
65834
- decimal_places: symbol_config.decimal_places
65835
- });
65836
- await this.syncAccount({
65837
- symbol,
65838
- update: true,
65839
- live_refresh: true
65821
+ update: true
65840
65822
  });
65841
65823
  }
65842
65824
  async placeSingleOrder(payload) {
65843
65825
  const { symbol, kind } = payload;
65844
- const positions = await this.syncAccount({
65845
- live_refresh: true,
65846
- update: true,
65847
- symbol
65848
- });
65849
- const long_position = positions.find((x) => x.kind === "long");
65850
- const short_position = positions.find((x) => x.kind === "short");
65851
- const long_config = await this.getPositionConfig({
65826
+ const long_position = await this.getFocusPosition({
65852
65827
  symbol,
65853
65828
  kind: "long"
65854
65829
  });
65855
- const short_config = await this.getPositionConfig({
65830
+ const short_position = await this.getFocusPosition({
65856
65831
  symbol,
65857
65832
  kind: "short"
65858
65833
  });
65859
- const focus_config = kind === "long" ? long_config : short_config;
65860
65834
  const focus_position = kind === "long" ? long_position : short_position;
65861
- const track_position = kind === "long" ? short_position : long_position;
65862
- const follow = focus_config.follow || focus_position.follow;
65863
- const threshold_qty = focus_config.threshold_qty || focus_position.threshold_qty;
65864
- if (!follow) {
65865
- return "No follow set";
65866
- }
65867
- let should_place_order = false;
65868
- if (threshold_qty === 0) {
65869
- should_place_order = true;
65870
- }
65871
- if (threshold_qty > 0 && track_position.quantity >= threshold_qty) {
65872
- should_place_order = true;
65873
- }
65874
- if (focus_position.quantity === 0) {
65875
- should_place_order = true;
65876
- }
65877
- if (track_position.quantity !== focus_position.quantity && focus_position.quantity < track_position.quantity && should_place_order) {
65878
- const remaining_quantity = Math.abs(track_position.quantity - focus_position.quantity);
65879
- await this.placeMarketOrder({
65880
- symbol,
65881
- kind,
65882
- quantity: remaining_quantity
65883
- });
65884
- }
65835
+ return await focus_position.placeSingleOrder({
65836
+ long_position,
65837
+ short_position
65838
+ });
65885
65839
  }
65886
65840
  async increasePositionAtStop(payload) {
65887
- const { symbol, kind, place = false, increase = true } = payload;
65888
- const position2 = await this.syncAccount({
65889
- symbol,
65890
- kind,
65891
- as_view: true
65892
- });
65893
- console.log(position2);
65894
- let price_params = {
65895
- price: payload.price,
65896
- quantity: payload.quantity
65897
- };
65898
- if (!payload.price && position2 && position2.stop_loss) {
65899
- price_params.price = position2.stop_loss.price;
65900
- }
65901
- if (!payload.quantity && position2 && position2.stop_loss) {
65902
- price_params.quantity = position2.stop_loss.quantity;
65903
- }
65904
- if (price_params.price && price_params.quantity) {
65905
- const { price, quantity } = price_params;
65906
- const symbol_config = await this.recomputeSymbolConfig({
65907
- symbol
65908
- });
65909
- const price_places = symbol_config.price_places;
65910
- const decimal_places = symbol_config.decimal_places;
65911
- if (place) {
65912
- await this.cancelOrders({
65913
- symbol,
65914
- kind,
65915
- limit: true
65916
- });
65917
- }
65918
- return await this.exchange.customStopLoss({
65919
- symbol,
65920
- kind,
65921
- stop: price,
65922
- quantity,
65923
- price_places,
65924
- decimal_places,
65925
- increase,
65926
- place
65927
- });
65928
- }
65841
+ const focus_position = await this.getFocusPosition(payload);
65842
+ return await focus_position.increasePositionAtStop(payload);
65929
65843
  }
65930
65844
  async triggerTradeFromConfig(payload) {
65931
- const {
65932
- symbol,
65933
- kind,
65934
- place = true,
65935
- stop,
65936
- use_current,
65937
- ignore_config,
65938
- risky
65939
- } = payload;
65940
- const position2 = await this.syncAccount({
65941
- symbol,
65942
- kind,
65943
- as_view: true
65944
- });
65945
- const config2 = await this.getPositionConfig({
65946
- symbol,
65947
- kind
65948
- });
65949
- let condition = ignore_config ? true : position2?.config;
65950
- if (condition) {
65951
- let entry = payload.tp ? position2.entry || config2.entry : config2.entry;
65952
- const v = stop ? "place_stop_orders" : risky ? "dangerous_entry_orders" : "place_limit_orders";
65953
- return await this.placeSharedOrder(v, {
65954
- symbol,
65955
- entry,
65956
- stop: config2.stop,
65957
- risk_reward: config2.risk_reward,
65958
- risk: config2.risk,
65959
- place,
65960
- raw: payload.raw,
65961
- use_current,
65962
- stop_percent: config2.stop_percent || 100
65963
- });
65964
- }
65845
+ const focus_position = await this.getFocusPosition(payload);
65846
+ return await focus_position.triggerTradeFromConfig(payload);
65965
65847
  }
65966
65848
  async verifyStopLoss(payload) {
65967
65849
  const { symbol, kind, revert } = payload;
@@ -66143,59 +66025,19 @@ class ExchangeAccount {
66143
66025
  }
66144
66026
  async updateTargetPnl(payload) {
66145
66027
  const { symbol, kind } = payload;
66146
- const position2 = await this.syncAccount({
66028
+ const focus_position = await this.getFocusPosition({
66147
66029
  symbol,
66148
66030
  kind
66149
66031
  });
66150
- if (position2?.expand?.config) {
66151
- const config2 = position2.expand.config;
66152
- let _profit = config2.profit;
66153
- let risk = config2.risk;
66154
- let next_risk = position2.next_risk;
66155
- let _profit_percent = config2?.profit_percent;
66156
- if (_profit_percent && (position2?.quantity || 0) > 0) {
66157
- _profit = to_f2(position2.quantity * _profit_percent * position2.entry / 100);
66158
- next_risk = risk + _profit;
66159
- }
66160
- await this.app_db.update_db_position(position2, {
66161
- target_pnl: _profit,
66162
- next_risk
66163
- });
66164
- return _profit;
66165
- }
66166
- return 0;
66032
+ return await focus_position.updateTargetPnl();
66167
66033
  }
66168
66034
  async updateRiskOnEmpty(payload) {
66169
66035
  const { symbol, kind } = payload;
66170
- const position2 = await this.syncAccount({
66036
+ const focus_position = await this.getFocusPosition({
66171
66037
  symbol,
66172
66038
  kind
66173
66039
  });
66174
- if (position2 && position2.quantity === 0) {
66175
- if (position2.next_risk && position2.next_risk > 0) {
66176
- await this.getPositionConfig({
66177
- symbol,
66178
- kind,
66179
- params: {
66180
- risk: position2.next_risk
66181
- }
66182
- });
66183
- console.log(`Updated ${kind} position config for ${symbol}: risk = ${position2.next_risk}`);
66184
- return {
66185
- updated: true,
66186
- symbol,
66187
- kind,
66188
- old_risk: position2.expand?.config?.risk,
66189
- new_risk: position2.next_risk
66190
- };
66191
- }
66192
- }
66193
- return {
66194
- updated: false,
66195
- symbol,
66196
- kind,
66197
- reason: position2 ? position2.quantity > 0 ? "Position not empty" : "No next_risk available" : "Position not found"
66198
- };
66040
+ return await focus_position.updateRiskOnEmpty();
66199
66041
  }
66200
66042
  async updateGoodHedgeConfig(payload) {
66201
66043
  const {
@@ -66207,19 +66049,20 @@ class ExchangeAccount {
66207
66049
  update = true
66208
66050
  } = payload;
66209
66051
  let _params = params;
66052
+ const long_position = await this.getFocusPosition({
66053
+ symbol,
66054
+ kind: "long"
66055
+ });
66056
+ const short_position = await this.getFocusPosition({
66057
+ symbol,
66058
+ kind: "short"
66059
+ });
66210
66060
  if (!params) {
66211
66061
  const result = await this.exchange.analyzeCandlesticks({ symbol });
66212
66062
  const support_price = Math.min(...Object.keys(result.support).map(Number));
66213
- const symbol_config = await this.recomputeSymbolConfig({ symbol });
66214
- const config2 = await this.getPositionConfig({
66215
- symbol,
66216
- kind: "long"
66217
- });
66218
- const position2 = await this.syncAccount({
66219
- symbol,
66220
- kind: "long",
66221
- as_view: true
66222
- });
66063
+ const symbol_config = long_position.symbol_config;
66064
+ const config2 = await long_position.getConfig();
66065
+ const position2 = long_position.getInstance();
66223
66066
  const bot_position = {
66224
66067
  kind: "long",
66225
66068
  entry: position2.entry,
@@ -66236,9 +66079,7 @@ class ExchangeAccount {
66236
66079
  });
66237
66080
  }
66238
66081
  if (update) {
66239
- await this.getPositionConfig({
66240
- symbol,
66241
- kind: "short",
66082
+ await short_position.getConfig({
66242
66083
  params: {
66243
66084
  entry: _params.support,
66244
66085
  stop: _params.resistance,
@@ -66247,22 +66088,15 @@ class ExchangeAccount {
66247
66088
  });
66248
66089
  }
66249
66090
  if (update_tp) {
66250
- await this.getPositionConfig({
66251
- symbol,
66252
- kind: "long",
66091
+ await long_position.getConfig({
66253
66092
  params: {
66254
66093
  profit_percent: _params.profit_percent
66255
66094
  }
66256
66095
  });
66257
- await this.updateTargetPnl({
66258
- symbol,
66259
- kind: "long"
66260
- });
66096
+ await long_position.updateTargetPnl();
66261
66097
  }
66262
66098
  if (place) {
66263
- await this.placeTrade({
66264
- symbol,
66265
- kind: "short",
66099
+ await short_position.placeTrade({
66266
66100
  limit: true,
66267
66101
  ignore_config: true
66268
66102
  });
@@ -66271,37 +66105,13 @@ class ExchangeAccount {
66271
66105
  }
66272
66106
  async placeOppositeTradeAction(payload) {
66273
66107
  const { symbol, kind, data } = payload;
66274
- const position2 = await this.syncAccount({
66108
+ const focus_position = await this.getFocusPosition({
66275
66109
  symbol,
66276
- kind,
66277
- as_view: true
66110
+ kind
66111
+ });
66112
+ return await focus_position.placeOppositeTradeAction({
66113
+ data
66278
66114
  });
66279
- if (position2.avg_qty !== data.avg.quantity) {
66280
- const config2 = await this.getPositionConfig({
66281
- symbol,
66282
- kind
66283
- });
66284
- await this.app_db.updateScheduledTrade(config2.id, {
66285
- entry: data.entry,
66286
- stop: data.stop,
66287
- risk: data.risk_per_trade,
66288
- profit_percent: data.profit_percent,
66289
- risk_reward: data.risk_reward
66290
- });
66291
- await this.placeTrade({
66292
- symbol,
66293
- kind,
66294
- place: true,
66295
- ignore_config: true
66296
- });
66297
- await this.placeTrade({
66298
- symbol,
66299
- kind,
66300
- place: true,
66301
- stop: true,
66302
- ignore_config: true
66303
- });
66304
- }
66305
66115
  }
66306
66116
  async buildOppositeTrades(payload) {
66307
66117
  const { symbol, kind, place, place_symbol } = payload;
@@ -66331,60 +66141,20 @@ class ExchangeAccount {
66331
66141
  }
66332
66142
  async runSimulation(payload) {
66333
66143
  const { symbol, kind, iterations = 2, raw = false } = payload;
66334
- const positions = await this.syncAccount({
66335
- symbol,
66336
- as_view: true
66337
- });
66338
- const symbol_config = await this.recomputeSymbolConfig({
66339
- symbol
66340
- });
66341
- const long_position = positions.find((x) => x.kind === "long");
66342
- const short_position = positions.find((x) => x.kind === "short");
66343
- const long_config = await this.getPositionConfig({
66144
+ const long_position = await this.getFocusPosition({
66344
66145
  symbol,
66345
66146
  kind: "long"
66346
66147
  });
66347
- const short_config = await this.getPositionConfig({
66148
+ const short_position = await this.getFocusPosition({
66348
66149
  symbol,
66349
66150
  kind: "short"
66350
66151
  });
66351
- const focus_config = kind === "long" ? long_config : short_config;
66352
- const short_tp_factor = short_config.profit_percent / long_config.profit_percent;
66353
- const reduce_ratio = focus_config.reduce_ratio;
66354
- const budget = focus_config.risk;
66355
- const risk_reward = focus_config.risk_reward;
66356
- const tp_percent = long_config.profit_percent;
66357
- const fee_percent = symbol_config.fee_percent;
66358
- const strategy_config = {
66359
- tp_percent,
66360
- short_tp_factor,
66361
- fee_percent,
66362
- budget,
66363
- risk_reward,
66364
- reduce_ratio,
66365
- global_config: symbol_config
66366
- };
66367
- const strategy2 = new Strategy({
66368
- long: {
66369
- entry: long_position.entry,
66370
- quantity: long_position.quantity,
66371
- avg_price: long_position.avg_price,
66372
- avg_qty: long_position.avg_qty
66373
- },
66374
- short: {
66375
- entry: short_position.entry,
66376
- quantity: short_position.quantity,
66377
- avg_price: short_position.avg_price,
66378
- avg_qty: short_position.avg_qty
66379
- },
66380
- config: strategy_config
66381
- });
66382
- if (raw) {
66383
- return strategy2;
66384
- }
66385
- return strategy2.runIterations({
66152
+ const focus_position = kind === "long" ? long_position : short_position;
66153
+ return focus_position.runSimulation({
66386
66154
  iterations,
66387
- kind
66155
+ raw,
66156
+ long_position,
66157
+ short_position
66388
66158
  });
66389
66159
  }
66390
66160
  async getCurrentRun(payload) {
@@ -66446,34 +66216,12 @@ class ExchangeAccount {
66446
66216
  return this.app_db.getSymbolConfigFromDB(symbol);
66447
66217
  }
66448
66218
  async buildConfigForSymbol(payload) {
66449
- const {
66219
+ const { symbol, kind = "long" } = payload;
66220
+ const focus_position = await this.getFocusPosition({
66450
66221
  symbol,
66451
- risk,
66452
- risk_reward = 199,
66453
- as_config = false,
66454
- kind = "long"
66455
- } = payload;
66456
- const symbol_config = await this.recomputeSymbolConfig({
66457
- symbol
66458
- });
66459
- const long_config = await this.generate_config_params({
66460
- entry: kind === "long" ? symbol_config.resistance : symbol_config.support,
66461
- stop: kind === "long" ? symbol_config.support : symbol_config.resistance,
66462
- risk_reward,
66463
- risk,
66464
- symbol
66222
+ kind
66465
66223
  });
66466
- if (as_config) {
66467
- const app_config = buildAppConfig(symbol_config, {
66468
- entry: long_config.entry,
66469
- stop: long_config.stop,
66470
- risk_reward,
66471
- risk: long_config.risk,
66472
- symbol
66473
- });
66474
- return app_config;
66475
- }
66476
- return long_config;
66224
+ return await focus_position.buildConfigForSymbol(payload);
66477
66225
  }
66478
66226
  async triggerBullishMarket(payload) {
66479
66227
  let { symbol, profit_percent = 10, risk_reward = 199 } = payload;
@@ -66579,15 +66327,9 @@ class ExchangeAccount {
66579
66327
  const all_open_symbols = await this.exchange.getOpenPositions();
66580
66328
  await new Promise((resolve) => setTimeout(resolve, interval * 1000));
66581
66329
  for (const symbol of Array.from(new Set(symbols.concat(all_open_symbols)))) {
66582
- await this.getLiveExchangeInstance({ symbol, refresh: true });
66330
+ await this.initializePositions({ symbol, kind: "long", update: true });
66583
66331
  await new Promise((resolve) => setTimeout(resolve, 1000));
66584
66332
  }
66585
- for (const symbol of all_open_symbols) {
66586
- await this.syncAccount({
66587
- symbol,
66588
- update: true
66589
- });
66590
- }
66591
66333
  }
66592
66334
  async updateAllPositionsWithNoConfig(payload) {
66593
66335
  const { kind } = payload;
@@ -66899,139 +66641,32 @@ class ExchangeAccount {
66899
66641
  }
66900
66642
  async computeTargetPnl(payload) {
66901
66643
  const { symbol, kind } = payload;
66902
- const reverse_kind = kind === "long" ? "short" : "long";
66903
- const root_position = await this.syncAccount({
66644
+ const focus_position = await this.getFocusPosition({
66904
66645
  symbol,
66905
66646
  kind
66906
66647
  });
66907
- const reverse_position = await this.syncAccount({
66648
+ const secondary_position = await this.getFocusPosition({
66908
66649
  symbol,
66909
- kind: reverse_kind
66650
+ kind: kind === "long" ? "short" : "long"
66651
+ });
66652
+ return await focus_position.computeTargetPnl({
66653
+ secondary: secondary_position
66910
66654
  });
66911
- if (reverse_position?.expand?.config && root_position.quantity > 0) {
66912
- const reverse_config = reverse_position.expand.config;
66913
- const diff = Math.abs(reverse_config.stop - root_position.entry);
66914
- const result = to_f2(diff * root_position.quantity);
66915
- if (root_position.target_pnl !== result) {
66916
- await this.app_db.update_db_position(root_position, {
66917
- target_pnl: result
66918
- });
66919
- await this.getPositionConfig({
66920
- kind: reverse_kind,
66921
- symbol,
66922
- params: {
66923
- ...reverse_config,
66924
- risk: result
66925
- }
66926
- });
66927
- }
66928
- return result;
66929
- }
66930
- return 0;
66931
66655
  }
66932
66656
  async placeStopLimit(payload) {
66933
- const { symbol, kind, place, stop, quantity: _quantity } = payload;
66934
- const position2 = await this.syncAccount({
66935
- symbol,
66936
- kind,
66937
- as_view: true
66938
- });
66939
- if (position2.avg_qty && position2.avg_qty > 0) {
66940
- const spread = 1.00005;
66941
- const qty = _quantity || position2.avg_qty - position2.quantity;
66942
- const symbol_config = await this.recomputeSymbolConfig({ symbol });
66943
- const orders = [
66944
- {
66945
- kind,
66946
- stop,
66947
- quantity: to_f2(qty, symbol_config.decimal_places),
66948
- side: kind === "long" ? "buy" : "sell",
66949
- price: to_f2(kind === "short" ? stop * spread ** -1 : stop * spread, symbol_config.price_places)
66950
- }
66951
- ];
66952
- if (place) {
66953
- return this.exchange.placeBadStopEntry({
66954
- symbol,
66955
- orders,
66956
- price_places: symbol_config.price_places,
66957
- decimal_places: symbol_config.decimal_places
66958
- });
66959
- }
66960
- return orders;
66961
- }
66962
- return [];
66657
+ const focus_position = await this.getFocusPosition(payload);
66658
+ return await focus_position.placeStopLimit(payload);
66963
66659
  }
66964
66660
  async placeTrade(payload) {
66965
- const {
66966
- symbol,
66967
- kind,
66968
- place,
66969
- tp,
66970
- limit = true,
66971
- raw: _raw,
66972
- cancel,
66973
- stop,
66974
- ignore_config,
66975
- target_pnl,
66976
- risky
66977
- } = payload;
66978
- if (cancel) {
66979
- await this.cancelOrders({
66980
- symbol,
66981
- kind
66982
- });
66983
- }
66984
- if (limit) {
66985
- return await this.triggerTradeFromConfig({
66986
- symbol,
66987
- kind,
66988
- raw: payload.raw,
66989
- stop,
66990
- ignore_config,
66991
- place,
66992
- risky
66993
- });
66994
- }
66995
- await this.syncAccount({
66996
- symbol,
66997
- live_refresh: true,
66998
- update: true
66999
- });
67000
- await this.updateConfigPnl({
67001
- symbol,
67002
- kind
66661
+ const focus_position = await this.getFocusPosition({
66662
+ symbol: payload.symbol,
66663
+ kind: payload.kind
67003
66664
  });
67004
- if (tp) {
67005
- await this.placeProfitAndStop({
67006
- symbol,
67007
- trigger: true,
67008
- target_pnl
67009
- });
67010
- }
67011
- return [];
66665
+ return await focus_position.placeTrade(payload);
67012
66666
  }
67013
66667
  async updateConfigPnl(payload) {
67014
- const { symbol, kind } = payload;
67015
- const position2 = await this.syncAccount({
67016
- symbol,
67017
- kind
67018
- });
67019
- if (!position2?.config) {
67020
- const config2 = await this.getPositionConfig({ symbol, kind });
67021
- if (config2) {
67022
- await this.app_db.update_db_position(position2, { config: config2.id });
67023
- await this.updateTargetPnl({
67024
- symbol,
67025
- kind
67026
- });
67027
- await this.app_db.update_db_position(position2, { config: null });
67028
- }
67029
- } else {
67030
- await this.updateTargetPnl({
67031
- symbol,
67032
- kind
67033
- });
67034
- }
66668
+ const focus_position = await this.getFocusPosition(payload);
66669
+ return await focus_position.updateConfigPnl();
67035
66670
  }
67036
66671
  async determineReduceTp(payload) {
67037
66672
  const { symbol, factor } = payload;
@@ -67046,10 +66681,10 @@ class ExchangeAccount {
67046
66681
  const gap_cost = gap * long_position.quantity * factor;
67047
66682
  const long_diff = gap_cost / (short_position.entry * short_position.quantity);
67048
66683
  const short_diff = gap_cost / (long_position.entry * long_position.quantity);
67049
- const long_tp = to_f2((long_diff + 1) * short_position.entry, symbol_config.price_places);
67050
- const short_tp = to_f2((short_diff + 1) ** -1 * long_position.entry, symbol_config.price_places);
67051
- const long_percent = to_f2(Math.abs(long_tp - long_position.entry) * 100 / long_position.entry, "%.4f");
67052
- const short_percent = to_f2(Math.abs(short_tp - short_position.entry) * 100 / short_position.entry, "%.4f");
66684
+ const long_tp = to_f((long_diff + 1) * short_position.entry, symbol_config.price_places);
66685
+ const short_tp = to_f((short_diff + 1) ** -1 * long_position.entry, symbol_config.price_places);
66686
+ const long_percent = to_f(Math.abs(long_tp - long_position.entry) * 100 / long_position.entry, "%.4f");
66687
+ const short_percent = to_f(Math.abs(short_tp - short_position.entry) * 100 / short_position.entry, "%.4f");
67053
66688
  return {
67054
66689
  long_diff,
67055
66690
  short_diff,
@@ -67063,7 +66698,6 @@ class ExchangeAccount {
67063
66698
  }
67064
66699
  async profitWithinGapStrategy(payload) {
67065
66700
  const { symbol } = payload;
67066
- let reward_factor = 1;
67067
66701
  console.log("Fetching positions for ", symbol);
67068
66702
  const positions = await this.syncAccount({
67069
66703
  symbol,
@@ -67077,70 +66711,11 @@ class ExchangeAccount {
67077
66711
  if (!strategy2) {
67078
66712
  return;
67079
66713
  }
67080
- const risk = strategy2.risk;
67081
66714
  const kind = strategy2.kind;
67082
- const support = strategy2.support;
67083
- const resistance = strategy2.resistance;
67084
- console.log("Getting long and short positions for ", symbol);
67085
- const long_position = positions.find((k) => k.kind === "long");
67086
- const short_position = positions.find((k) => k.kind === "short");
67087
- console.log("Getting focus position for ", symbol, kind);
67088
- if (strategy2.max_reward_factor === 0) {
67089
- reward_factor = strategy2.reward_factor;
67090
- }
67091
- if (focus_position.avg_qty >= focus_position.quantity && strategy2.max_reward_factor) {
67092
- if (strategy2.dynamic) {
67093
- const quantity_ratio = focus_position.quantity / focus_position.avg_qty;
67094
- reward_factor = to_f2(quantity_ratio ** 2 * strategy2.max_reward_factor, "%.2f");
67095
- } else {
67096
- reward_factor = to_f2(focus_position.quantity * strategy2.max_reward_factor / focus_position.avg_qty, "%.4f");
67097
- }
67098
- } else {
67099
- reward_factor = strategy2.reward_factor;
67100
- }
67101
- console.log("Getting entry and stop for ", symbol, kind);
67102
- const entry = kind === "long" ? resistance : support;
67103
- const stop = kind === "long" ? support : resistance;
67104
- console.log("Building app config for ", symbol, kind);
67105
- const initial_app_config = await this.buildAppConfig({
67106
- entry,
67107
- stop,
67108
- risk_reward: 199,
67109
- risk,
67110
- symbol
67111
- });
67112
- console.log("Computing risk reward for ", symbol, kind);
67113
- const risk_reward = strategy2.risk_reward || computeRiskReward({
67114
- app_config: initial_app_config,
67115
- entry: initial_app_config.entry,
67116
- stop: initial_app_config.stop,
67117
- risk_per_trade: initial_app_config.risk_per_trade
67118
- });
67119
- console.log("Re-computing app config for ", symbol, kind);
67120
- const { entries, last_value, ...app_config } = await this.buildAppConfig({
67121
- entry: initial_app_config.entry,
67122
- stop: initial_app_config.stop,
67123
- risk_reward,
67124
- risk,
67125
- symbol
67126
- });
67127
- console.log("Computing profit percent for ", symbol, kind);
67128
- const pnl = reward_factor * risk;
67129
- const profit_percent = to_f2(pnl * 100 / (last_value.avg_entry * last_value.avg_size), "%.4f");
67130
- let config2 = {
67131
- entry,
67132
- stop,
67133
- risk,
67134
- risk_reward,
67135
- profit_percent
67136
- };
67137
- console.log("Saving new config for ", symbol, kind);
67138
- const data = await this.getPositionConfig({
66715
+ const { entries, last_value, ...app_config } = await this.tradeConfig({
67139
66716
  symbol,
67140
- kind,
67141
- params: config2
66717
+ kind
67142
66718
  });
67143
- console.log("Checking orders to place for ", symbol, kind);
67144
66719
  await this.placeTrade({
67145
66720
  symbol,
67146
66721
  kind,
@@ -67148,10 +66723,6 @@ class ExchangeAccount {
67148
66723
  ignore_config: true,
67149
66724
  tp: true
67150
66725
  });
67151
- config2 = {
67152
- ...config2,
67153
- ...data
67154
- };
67155
66726
  if (focus_position.avg_qty < last_value.avg_size) {
67156
66727
  console.log("Placing trade for ", symbol, kind);
67157
66728
  await this.placeTrade({
@@ -67163,15 +66734,9 @@ class ExchangeAccount {
67163
66734
  }
67164
66735
  console.log("Checking if focus position has quantity for ", symbol, kind);
67165
66736
  return {
67166
- positions: {
67167
- long: long_position,
67168
- short: short_position
67169
- },
67170
66737
  config_details: {
67171
66738
  app_config,
67172
- last_value,
67173
- config: config2,
67174
- pnl
66739
+ last_value
67175
66740
  }
67176
66741
  };
67177
66742
  }