@tradejs/connectors 3.1.29-beta.284 → 3.1.29-beta.286

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.
Files changed (3) hide show
  1. package/dist/index.js +417 -120
  2. package/dist/index.mjs +417 -120
  3. package/package.json +3 -3
package/dist/index.js CHANGED
@@ -141,7 +141,8 @@ var parseKlineItem = (item) => ({
141
141
  turnover: parseFloat(item[6])
142
142
  });
143
143
  var mapKlineToChartData = (data) => data.map(parseKlineItem);
144
- var symbolMetaCache = /* @__PURE__ */ new Map();
144
+ var SYMBOL_META_TTL_MS = 6e4;
145
+ var symbolMetaCache = /* @__PURE__ */ new WeakMap();
145
146
  var roundByStep = (value, step, mode = "floor") => {
146
147
  if (!step || !Number.isFinite(value)) return value;
147
148
  const ratio = value / step;
@@ -153,15 +154,20 @@ var stepToPrecision = (raw) => {
153
154
  const [, decimals = ""] = raw.split(".");
154
155
  return decimals.length;
155
156
  };
156
- var getSymbolMeta = async (client, symbol) => {
157
- const cached = symbolMetaCache.get(symbol);
158
- if (cached) return cached;
157
+ var getSymbolMeta = async (client, symbol, refresh = false) => {
158
+ let cache = symbolMetaCache.get(client);
159
+ if (!cache) {
160
+ cache = /* @__PURE__ */ new Map();
161
+ symbolMetaCache.set(client, cache);
162
+ }
163
+ const cached = cache.get(symbol);
164
+ if (!refresh && cached && cached.expiresAt > Date.now()) return cached.value;
159
165
  const res = await client.getInstrumentsInfo({
160
166
  category: BYBIT_CATEGORY,
161
167
  symbol
162
168
  });
163
169
  const item = res?.result?.list?.[0];
164
- if (!item) {
170
+ if (res.retCode !== 0 || !item || item.symbol !== symbol) {
165
171
  throw new Error(`No instrument info for symbol ${symbol}`);
166
172
  }
167
173
  const tickSizeStr = item.priceFilter?.tickSize ?? "0.01";
@@ -171,13 +177,18 @@ var getSymbolMeta = async (client, symbol) => {
171
177
  tickSize: Number(tickSizeStr),
172
178
  qtyStep: Number(qtyStepStr),
173
179
  minOrderQty: Number(minOrderQtyStr),
180
+ maxMarketOrderQty: "maxMktOrderQty" in item.lotSizeFilter ? Number(item.lotSizeFilter.maxMktOrderQty) : null,
181
+ maxLimitOrderQty: Number(item.lotSizeFilter.maxOrderQty),
174
182
  pricePrecision: stepToPrecision(tickSizeStr),
175
183
  qtyPrecision: stepToPrecision(qtyStepStr),
176
- maxLeverage: Number.isFinite(
177
- Number(item.leverageFilter?.maxLeverage)
178
- ) ? Number(item.leverageFilter.maxLeverage) : null
184
+ minLeverage: "leverageFilter" in item ? Number(item.leverageFilter.minLeverage) : null,
185
+ maxLeverage: "leverageFilter" in item ? Number(item.leverageFilter.maxLeverage) : null,
186
+ leverageStep: "leverageFilter" in item ? Number(item.leverageFilter.leverageStep) : null
179
187
  };
180
- symbolMetaCache.set(symbol, meta);
188
+ cache.set(symbol, {
189
+ value: meta,
190
+ expiresAt: Date.now() + SYMBOL_META_TTL_MS
191
+ });
181
192
  return meta;
182
193
  };
183
194
  var normalizeQty = (rawQty, meta) => {
@@ -185,6 +196,19 @@ var normalizeQty = (rawQty, meta) => {
185
196
  const qtyStr = qtyNum.toFixed(meta.qtyPrecision);
186
197
  return { qtyNum, qtyStr };
187
198
  };
199
+ var normalizeEntryQty = (rawQty, meta, isLimit) => {
200
+ const maxQty = isLimit ? meta.maxLimitOrderQty : meta.maxMarketOrderQty;
201
+ if (typeof maxQty !== "number" || !Number.isFinite(maxQty) || maxQty <= 0)
202
+ throw new Error("BYBIT_INVALID_ORDER_QTY_LIMIT");
203
+ if (!Number.isFinite(rawQty) || rawQty <= 0)
204
+ throw new Error("BYBIT_INVALID_ORDER_QTY");
205
+ if (!Number.isFinite(meta.qtyStep) || meta.qtyStep <= 0)
206
+ throw new Error("BYBIT_INVALID_QTY_STEP");
207
+ const normalized = normalizeQty(Math.min(rawQty, maxQty), meta);
208
+ if (!Number.isFinite(normalized.qtyNum) || normalized.qtyNum > rawQty || normalized.qtyNum > maxQty)
209
+ throw new Error("BYBIT_INVALID_NORMALIZED_ORDER_QTY");
210
+ return normalized;
211
+ };
188
212
  var normalizePrice = (rawPrice, role, meta) => {
189
213
  let mode = "floor";
190
214
  switch (role) {
@@ -222,6 +246,199 @@ var mapPositionData = (data) => {
222
246
  }));
223
247
  };
224
248
 
249
+ // src/ByBit/leverage.ts
250
+ var CATEGORY = "linear";
251
+ var REFRESH_CODES = /* @__PURE__ */ new Set([110013, 110085, 110086, 110089, 110090]);
252
+ var orderQueues = /* @__PURE__ */ new Map();
253
+ var withBybitOrderLock = async (key, action) => {
254
+ const previous = orderQueues.get(key) ?? Promise.resolve();
255
+ let release;
256
+ const pending = new Promise((resolve) => {
257
+ release = resolve;
258
+ });
259
+ orderQueues.set(key, pending);
260
+ await previous;
261
+ try {
262
+ return await action();
263
+ } finally {
264
+ release();
265
+ if (orderQueues.get(key) === pending) orderQueues.delete(key);
266
+ }
267
+ };
268
+ var positive = (value, label) => {
269
+ const parsed = Number(value);
270
+ if (!["string", "number"].includes(typeof value) || value === "" || !Number.isFinite(parsed) || parsed <= 0) {
271
+ throw new Error(`BYBIT_INVALID_${label}`);
272
+ }
273
+ return parsed;
274
+ };
275
+ var nonNegative = (value, label) => {
276
+ if (value === "0" || value === 0) return 0;
277
+ return positive(value, label);
278
+ };
279
+ var loadPositions = async (client, symbol) => {
280
+ const response = await client.getPositionInfo({ category: CATEGORY, symbol });
281
+ if (response.retCode !== 0 || !Array.isArray(response.result?.list) || !response.result.list.length) {
282
+ throw new Error("BYBIT_LEVERAGE_POSITION_UNAVAILABLE");
283
+ }
284
+ const rows = response.result.list;
285
+ if (rows.some((row) => row.symbol !== symbol || row.positionIdx !== 0)) {
286
+ throw new Error("BYBIT_LEVERAGE_POSITION_MODE_UNSUPPORTED");
287
+ }
288
+ return rows;
289
+ };
290
+ var loadRiskMaximum = async (client, symbol, positionValue, riskIds) => {
291
+ let cursor;
292
+ const tiers = [];
293
+ for (let page = 0; page < 20; page += 1) {
294
+ const response = await client.getRiskLimit({
295
+ category: CATEGORY,
296
+ symbol,
297
+ ...cursor ? { cursor } : {}
298
+ });
299
+ if (response.retCode !== 0 || !Array.isArray(response.result?.list)) {
300
+ throw new Error("BYBIT_LEVERAGE_RISK_LIMIT_UNAVAILABLE");
301
+ }
302
+ for (const row of response.result.list) {
303
+ if (row.symbol !== symbol) continue;
304
+ tiers.push({
305
+ id: row.id,
306
+ value: positive(row.riskLimitValue, "RISK_LIMIT"),
307
+ leverage: positive(row.maxLeverage, "RISK_LEVERAGE")
308
+ });
309
+ }
310
+ const nextCursor = "nextPageCursor" in response.result ? response.result.nextPageCursor : void 0;
311
+ if (nextCursor != null && typeof nextCursor !== "string")
312
+ throw new Error("BYBIT_LEVERAGE_INVALID_CURSOR");
313
+ cursor = nextCursor ?? void 0;
314
+ if (!cursor) break;
315
+ if (page === 19) throw new Error("BYBIT_LEVERAGE_RISK_LIMIT_INCOMPLETE");
316
+ }
317
+ const tier = tiers.sort((left, right) => left.value - right.value).find((row) => row.value >= positionValue);
318
+ if (!tier) throw new Error("BYBIT_LEVERAGE_RISK_LIMIT_EXCEEDED");
319
+ const currentTiers = riskIds.map((id) => {
320
+ const current = tiers.find((row) => row.id === id);
321
+ if (!current) throw new Error("BYBIT_LEVERAGE_RISK_TIER_UNKNOWN");
322
+ return current;
323
+ });
324
+ return Math.min(tier.leverage, ...currentTiers.map((row) => row.leverage));
325
+ };
326
+ var loadPendingValue = async (client, symbol, price) => {
327
+ const total = { Buy: 0, Sell: 0 };
328
+ let cursor;
329
+ for (let page = 0; page < 20; page += 1) {
330
+ const response = await client.getActiveOrders({
331
+ category: CATEGORY,
332
+ symbol,
333
+ openOnly: 0,
334
+ orderFilter: "Order",
335
+ limit: 50,
336
+ ...cursor ? { cursor } : {}
337
+ });
338
+ if (response.retCode !== 0 || !Array.isArray(response.result?.list))
339
+ throw new Error("BYBIT_LEVERAGE_OPEN_ORDERS_UNAVAILABLE");
340
+ for (const order of response.result.list) {
341
+ if (order.symbol !== symbol || order.reduceOnly) continue;
342
+ if (order.side !== "Buy" && order.side !== "Sell")
343
+ throw new Error("BYBIT_INVALID_OPEN_ORDER_SIDE");
344
+ const qty = nonNegative(order.leavesQty, "OPEN_ORDER_QTY");
345
+ const orderPrice = nonNegative(order.price, "OPEN_ORDER_PRICE");
346
+ total[order.side] += qty * Math.max(price, orderPrice);
347
+ }
348
+ cursor = response.result.nextPageCursor;
349
+ if (!cursor) return total;
350
+ }
351
+ throw new Error("BYBIT_LEVERAGE_OPEN_ORDERS_INCOMPLETE");
352
+ };
353
+ var normalizeLeverage = (requested, max, min, step) => {
354
+ const cap = Math.min(requested, max);
355
+ const result = Number(
356
+ (min + Math.floor((cap - min + step * 1e-9) / step) * step).toFixed(12)
357
+ );
358
+ if (result < min || result > cap + 1e-9)
359
+ throw new Error("BYBIT_LEVERAGE_NOT_AVAILABLE");
360
+ return result;
361
+ };
362
+ var prepareBybitLeverage = async ({
363
+ client,
364
+ marketClient,
365
+ symbol,
366
+ requested,
367
+ direction,
368
+ qty,
369
+ price
370
+ }) => {
371
+ positive(requested, "REQUESTED_LEVERAGE");
372
+ positive(qty, "ORDER_QTY");
373
+ positive(price, "ORDER_PRICE");
374
+ for (let attempt = 0; attempt < 2; attempt += 1) {
375
+ const meta = await getSymbolMeta(marketClient, symbol, attempt > 0);
376
+ const min = positive(meta.minLeverage, "MIN_LEVERAGE");
377
+ const max = positive(meta.maxLeverage, "MAX_LEVERAGE");
378
+ const step = positive(meta.leverageStep, "LEVERAGE_STEP");
379
+ if (max < min) throw new Error("BYBIT_INVALID_LEVERAGE_RANGE");
380
+ const positions = await loadPositions(client, symbol);
381
+ const exposure = {
382
+ Buy: direction === "LONG" ? qty * price : 0,
383
+ Sell: direction === "SHORT" ? qty * price : 0
384
+ };
385
+ const riskIds = [];
386
+ for (const position of positions) {
387
+ positive(position.leverage, "POSITION_LEVERAGE");
388
+ const size = nonNegative(position.size, "POSITION_SIZE");
389
+ if (size > 0) {
390
+ if (position.side !== "Buy" && position.side !== "Sell")
391
+ throw new Error("BYBIT_INVALID_POSITION_SIDE");
392
+ exposure[position.side] += Math.max(
393
+ nonNegative(position.positionValue, "POSITION_VALUE"),
394
+ size * price
395
+ );
396
+ riskIds.push(positive(position.riskId, "POSITION_RISK_ID"));
397
+ }
398
+ }
399
+ const pending = await loadPendingValue(client, symbol, price);
400
+ const positionValue = Math.max(
401
+ exposure.Buy + pending.Buy,
402
+ exposure.Sell + pending.Sell
403
+ );
404
+ const riskMax = await loadRiskMaximum(
405
+ client,
406
+ symbol,
407
+ positionValue,
408
+ riskIds
409
+ );
410
+ const effective = normalizeLeverage(
411
+ requested,
412
+ Math.min(max, riskMax),
413
+ min,
414
+ step
415
+ );
416
+ const response = await client.setLeverage({
417
+ category: CATEGORY,
418
+ symbol,
419
+ buyLeverage: String(effective),
420
+ sellLeverage: String(effective)
421
+ });
422
+ if (response.retCode !== 0 && response.retCode !== 110043) {
423
+ if (attempt === 0 && REFRESH_CODES.has(response.retCode)) continue;
424
+ throw new Error(
425
+ `BYBIT_SET_LEVERAGE_${response.retCode ?? "INVALID_RESPONSE"}`
426
+ );
427
+ }
428
+ const confirmed = await loadPositions(client, symbol);
429
+ if (confirmed.some((row) => Number(row.leverage) !== effective))
430
+ throw new Error("BYBIT_LEVERAGE_NOT_CONFIRMED");
431
+ return {
432
+ requested,
433
+ effective,
434
+ maxAllowed: Math.min(max, riskMax),
435
+ reductionReason: effective === requested ? null : riskMax < Math.min(requested, max) ? "risk_limit" : max < requested ? "instrument_limit" : "leverage_step",
436
+ verifiedAt: Date.now()
437
+ };
438
+ }
439
+ throw new Error("BYBIT_LEVERAGE_NOT_CONFIRMED");
440
+ };
441
+
225
442
  // src/ByBit/index.ts
226
443
  var import_types = require("@tradejs/types");
227
444
  var LIMIT = 1e3;
@@ -264,6 +481,7 @@ var INTERVAL_TO_MINUTES = {
264
481
  var getLogLevel = (res) => res.retCode === 0 ? "info" : "error";
265
482
  var isTradingStopNotModified = (res) => res?.retCode === BYBIT_TRADING_STOP_NOT_MODIFIED_RETCODE;
266
483
  var isTradingStopAccepted = (res) => res?.retCode === 0 || isTradingStopNotModified(res);
484
+ var isMaxOrderQuantityRejected = (response) => response.retCode === 10001 && typeof response.retMsg === "string" && /number of contracts exceeds maximum limit allowed/i.test(response.retMsg);
267
485
  var isKlineRateLimited = (res) => res?.retCode === BYBIT_RATE_LIMIT_RETCODE;
268
486
  var mapBybitAssetClass = (symbolType) => {
269
487
  if (symbolType === "stock") return "equity";
@@ -1237,119 +1455,198 @@ var ByBitConnectorCreator = async (config, runtime) => {
1237
1455
  signal,
1238
1456
  leverage
1239
1457
  }) => {
1240
- invalidatePositionSnapshot(symbol);
1241
- const client = await getPrivateClient();
1242
- const marketDataClient = await getPublicClient();
1243
- if (!client || !marketDataClient) {
1244
- if (signal) {
1245
- signal.orderFailureReason = "BYBIT_CLIENT_UNAVAILABLE";
1246
- }
1247
- return false;
1248
- }
1249
- const isLong = direction === "LONG";
1250
- if (positionIntent === "increase") {
1251
- const currentPosition = await getPositionSnapshot(symbol);
1252
- if (!currentPosition || currentPosition.direction !== direction) {
1253
- const failureReason = currentPosition ? "POSITION_DIRECTION_MISMATCH" : "POSITION_NOT_FOUND";
1254
- if (signal) {
1255
- signal.orderFailureReason = failureReason;
1458
+ return withBybitOrderLock(
1459
+ JSON.stringify([
1460
+ config.userName,
1461
+ config.accountId ?? "default",
1462
+ symbol
1463
+ ]),
1464
+ async () => {
1465
+ if (signal) signal.orderLeverage = void 0;
1466
+ invalidatePositionSnapshot(symbol);
1467
+ const client = await getPrivateClient();
1468
+ const marketDataClient = await getPublicClient();
1469
+ if (!client || !marketDataClient) {
1470
+ if (signal) {
1471
+ signal.orderFailureReason = "BYBIT_CLIENT_UNAVAILABLE";
1472
+ }
1473
+ return false;
1256
1474
  }
1257
- logger.log(
1258
- "warn",
1259
- "placeOrder: rejected position increase: %s",
1260
- (0, import_data.toJson)(
1261
- {
1475
+ const isLong = direction === "LONG";
1476
+ if (positionIntent === "increase") {
1477
+ const currentPosition = await getPositionSnapshot(symbol);
1478
+ if (!currentPosition || currentPosition.direction !== direction) {
1479
+ const failureReason = currentPosition ? "POSITION_DIRECTION_MISMATCH" : "POSITION_NOT_FOUND";
1480
+ if (signal) {
1481
+ signal.orderFailureReason = failureReason;
1482
+ }
1483
+ logger.log(
1484
+ "warn",
1485
+ "placeOrder: rejected position increase: %s",
1486
+ (0, import_data.toJson)(
1487
+ {
1488
+ symbol,
1489
+ direction,
1490
+ currentDirection: currentPosition?.direction ?? null,
1491
+ failureReason
1492
+ },
1493
+ true
1494
+ )
1495
+ );
1496
+ return false;
1497
+ }
1498
+ }
1499
+ let quantityCeiling = qty;
1500
+ let quantityRejection = "";
1501
+ for (let attempt = 0; attempt < 2; attempt += 1) {
1502
+ if (signal) signal.orderLeverage = void 0;
1503
+ const meta = await getSymbolMeta(
1504
+ marketDataClient,
1505
+ symbol,
1506
+ attempt > 0
1507
+ );
1508
+ let normalizedQty;
1509
+ try {
1510
+ normalizedQty = normalizeEntryQty(
1511
+ quantityCeiling,
1512
+ meta,
1513
+ isLimit === true
1514
+ );
1515
+ } catch (error) {
1516
+ const reason = error instanceof Error ? error.message : "BYBIT_ORDER_QTY_UNAVAILABLE";
1517
+ if (signal) signal.orderFailureReason = reason;
1518
+ logger.log(
1519
+ "warn",
1520
+ "placeOrder: quantity preparation failed: %s %s",
1262
1521
  symbol,
1522
+ reason
1523
+ );
1524
+ return false;
1525
+ }
1526
+ if (attempt > 0 && normalizedQty.qtyNum >= quantityCeiling) {
1527
+ if (signal) signal.orderFailureReason = quantityRejection;
1528
+ return false;
1529
+ }
1530
+ const isQtyBelowMin = normalizedQty.qtyNum < meta.minOrderQty;
1531
+ if (isQtyBelowMin) {
1532
+ if (signal) {
1533
+ signal.orderQty = normalizedQty.qtyNum;
1534
+ signal.orderValue = normalizedQty.qtyNum * price;
1535
+ signal.orderFailureReason = "QTY_BELOW_MIN_ORDER";
1536
+ }
1537
+ logger.log(
1538
+ "warn",
1539
+ "placeOrder: rejected qty below minOrderQty: %s",
1540
+ (0, import_data.toJson)(
1541
+ {
1542
+ symbol,
1543
+ qty,
1544
+ normalizedOrderQty: normalizedQty.qtyNum,
1545
+ minOrderQty: meta.minOrderQty
1546
+ },
1547
+ true
1548
+ )
1549
+ );
1550
+ return false;
1551
+ }
1552
+ if (normalizedQty.qtyNum < qty) {
1553
+ logger.log(
1554
+ "info",
1555
+ "placeOrder: quantity reduced: %s",
1556
+ (0, import_data.toJson)({
1557
+ symbol,
1558
+ requestedQty: qty,
1559
+ orderQty: normalizedQty.qtyNum,
1560
+ maxOrderQty: isLimit ? meta.maxLimitOrderQty : meta.maxMarketOrderQty,
1561
+ orderType: isLimit ? "Limit" : "Market"
1562
+ })
1563
+ );
1564
+ }
1565
+ const orderQty = normalizedQty.qtyNum;
1566
+ const orderQtyStr = normalizedQty.qtyStr;
1567
+ if (signal) {
1568
+ signal.orderQty = orderQty;
1569
+ signal.orderValue = orderQty * price;
1570
+ }
1571
+ const entryNormalized = isLimit ? normalizePrice(price, "ENTRY", meta) : void 0;
1572
+ logger.log(
1573
+ "info",
1574
+ "placeOrder: %s",
1575
+ (0, import_data.toJson)(
1576
+ {
1577
+ symbol,
1578
+ price,
1579
+ qty,
1580
+ direction,
1581
+ orderQty,
1582
+ orderQtyStr
1583
+ },
1584
+ true
1585
+ )
1586
+ );
1587
+ try {
1588
+ const orderLeverage = await prepareBybitLeverage({
1589
+ client,
1590
+ marketClient: marketDataClient,
1591
+ symbol,
1592
+ requested: leverage ?? 10,
1263
1593
  direction,
1264
- currentDirection: currentPosition?.direction ?? null,
1265
- failureReason
1266
- },
1267
- true
1268
- )
1269
- );
1594
+ qty: orderQty,
1595
+ price
1596
+ });
1597
+ if (signal) signal.orderLeverage = orderLeverage;
1598
+ logger.log(
1599
+ "info",
1600
+ "placeOrder:leverage %s %s",
1601
+ symbol,
1602
+ (0, import_data.toJson)(orderLeverage)
1603
+ );
1604
+ } catch (error) {
1605
+ const reason = error instanceof Error && error.message.startsWith("BYBIT_") ? error.message : "BYBIT_LEVERAGE_UNAVAILABLE";
1606
+ if (signal) signal.orderFailureReason = reason;
1607
+ logger.log(
1608
+ "warn",
1609
+ "placeOrder: leverage preparation failed: %s %s",
1610
+ symbol,
1611
+ reason
1612
+ );
1613
+ return false;
1614
+ }
1615
+ const orderRes = await client.submitOrder({
1616
+ category: BYBIT_CATEGORY2,
1617
+ symbol,
1618
+ price: entryNormalized?.priceStr || void 0,
1619
+ side: isLong ? "Buy" : "Sell",
1620
+ orderType: isLimit ? "Limit" : "Market",
1621
+ qty: orderQtyStr,
1622
+ orderFilter: "Order",
1623
+ orderLinkId: typeof orderId === "string" && orderId.trim() ? orderId : void 0
1624
+ });
1625
+ logger.log(
1626
+ getLogLevel(orderRes),
1627
+ "placeOrder:response: %s",
1628
+ (0, import_data.toJson)(orderRes, true)
1629
+ );
1630
+ if (orderRes.retCode !== 0) {
1631
+ if (attempt === 0 && isMaxOrderQuantityRejected(orderRes)) {
1632
+ quantityCeiling = orderQty;
1633
+ quantityRejection = orderRes.retMsg;
1634
+ continue;
1635
+ }
1636
+ if (signal) {
1637
+ signal.orderFailureReason = typeof orderRes.retMsg === "string" && orderRes.retMsg.trim() ? orderRes.retMsg.trim() : `BYBIT_RETCODE_${orderRes.retCode}`;
1638
+ }
1639
+ return false;
1640
+ }
1641
+ if (signal) {
1642
+ signal.orderFailureReason = void 0;
1643
+ }
1644
+ invalidatePositionSnapshot(symbol);
1645
+ return true;
1646
+ }
1270
1647
  return false;
1271
1648
  }
1272
- }
1273
- const meta = await getSymbolMeta(marketDataClient, symbol);
1274
- const normalizedQty = normalizeQty(qty, meta);
1275
- const isQtyBelowMin = normalizedQty.qtyNum < meta.minOrderQty;
1276
- if (isQtyBelowMin) {
1277
- if (signal) {
1278
- signal.orderQty = normalizedQty.qtyNum;
1279
- signal.orderValue = normalizedQty.qtyNum * price;
1280
- signal.orderFailureReason = "QTY_BELOW_MIN_ORDER";
1281
- }
1282
- logger.log(
1283
- "warn",
1284
- "placeOrder: rejected qty below minOrderQty: %s",
1285
- (0, import_data.toJson)(
1286
- {
1287
- symbol,
1288
- qty,
1289
- normalizedOrderQty: normalizedQty.qtyNum,
1290
- minOrderQty: meta.minOrderQty
1291
- },
1292
- true
1293
- )
1294
- );
1295
- return false;
1296
- }
1297
- const orderQty = normalizedQty.qtyNum;
1298
- const orderQtyStr = normalizedQty.qtyStr;
1299
- if (signal) {
1300
- signal.orderQty = orderQty;
1301
- signal.orderValue = orderQty * price;
1302
- }
1303
- const entryNormalized = isLimit ? normalizePrice(price, "ENTRY", meta) : void 0;
1304
- logger.log(
1305
- "info",
1306
- "placeOrder: %s",
1307
- (0, import_data.toJson)(
1308
- {
1309
- symbol,
1310
- price,
1311
- qty,
1312
- direction,
1313
- orderQty,
1314
- orderQtyStr
1315
- },
1316
- true
1317
- )
1318
- );
1319
- const requestedLeverage = typeof leverage === "number" && Number.isFinite(leverage) ? Math.max(1, leverage) : 10;
1320
- const effectiveLeverage = meta.maxLeverage != null ? Math.min(requestedLeverage, meta.maxLeverage) : requestedLeverage;
1321
- await client.setLeverage({
1322
- category: BYBIT_CATEGORY2,
1323
- symbol,
1324
- buyLeverage: String(effectiveLeverage),
1325
- sellLeverage: String(effectiveLeverage)
1326
- });
1327
- const orderRes = await client.submitOrder({
1328
- category: BYBIT_CATEGORY2,
1329
- symbol,
1330
- price: entryNormalized?.priceStr || void 0,
1331
- side: isLong ? "Buy" : "Sell",
1332
- orderType: isLimit ? "Limit" : "Market",
1333
- qty: orderQtyStr,
1334
- orderFilter: "Order",
1335
- orderLinkId: typeof orderId === "string" && orderId.trim() ? orderId : void 0
1336
- });
1337
- logger.log(
1338
- getLogLevel(orderRes),
1339
- "placeOrder:response: %s",
1340
- (0, import_data.toJson)(orderRes, true)
1341
1649
  );
1342
- if (orderRes.retCode !== 0) {
1343
- if (signal) {
1344
- signal.orderFailureReason = typeof orderRes.retMsg === "string" && orderRes.retMsg.trim() ? orderRes.retMsg.trim() : `BYBIT_RETCODE_${orderRes.retCode}`;
1345
- }
1346
- return false;
1347
- }
1348
- if (signal) {
1349
- signal.orderFailureReason = void 0;
1350
- }
1351
- invalidatePositionSnapshot(symbol);
1352
- return true;
1353
1650
  },
1354
1651
  setPositionProtection,
1355
1652
  setTakeProfits,
@@ -2105,7 +2402,7 @@ var spotKlineProviders = {
2105
2402
  // src/ByBit/klineStream.ts
2106
2403
  var import_bybit_api2 = require("bybit-api");
2107
2404
  var import_time3 = require("@tradejs/core/time");
2108
- var CATEGORY = "linear";
2405
+ var CATEGORY2 = "linear";
2109
2406
  var SUBSCRIPTION_BATCH_SIZE = 100;
2110
2407
  var KLINE_TOPIC_PATTERN = /^kline\.([^.]+)\.(.+)$/;
2111
2408
  var chunk = (items, size) => {
@@ -2190,12 +2487,12 @@ var createBybitKlineStreamWithClient = ({
2190
2487
  const added = [...nextTopics].filter((topic) => !topics.has(topic));
2191
2488
  const removed = [...topics].filter((topic) => !nextTopics.has(topic));
2192
2489
  for (const batch of chunk(removed, SUBSCRIPTION_BATCH_SIZE)) {
2193
- void Promise.all(client.unsubscribeV5(batch, CATEGORY)).catch(
2490
+ void Promise.all(client.unsubscribeV5(batch, CATEGORY2)).catch(
2194
2491
  (error) => logger.error("Bybit kline unsubscribe failed: %s", String(error))
2195
2492
  );
2196
2493
  }
2197
2494
  for (const batch of chunk(added, SUBSCRIPTION_BATCH_SIZE)) {
2198
- void Promise.all(client.subscribeV5(batch, CATEGORY)).catch(
2495
+ void Promise.all(client.subscribeV5(batch, CATEGORY2)).catch(
2199
2496
  (error) => logger.error("Bybit kline subscribe failed: %s", String(error))
2200
2497
  );
2201
2498
  }
@@ -2213,7 +2510,7 @@ var createBybitKlineStreamWithClient = ({
2213
2510
  const currentTopics = [...topics];
2214
2511
  topics.clear();
2215
2512
  for (const batch of chunk(currentTopics, SUBSCRIPTION_BATCH_SIZE)) {
2216
- await Promise.allSettled(client.unsubscribeV5(batch, CATEGORY));
2513
+ await Promise.allSettled(client.unsubscribeV5(batch, CATEGORY2));
2217
2514
  }
2218
2515
  client.closeAll();
2219
2516
  }
package/dist/index.mjs CHANGED
@@ -91,7 +91,8 @@ var parseKlineItem = (item) => ({
91
91
  turnover: parseFloat(item[6])
92
92
  });
93
93
  var mapKlineToChartData = (data) => data.map(parseKlineItem);
94
- var symbolMetaCache = /* @__PURE__ */ new Map();
94
+ var SYMBOL_META_TTL_MS = 6e4;
95
+ var symbolMetaCache = /* @__PURE__ */ new WeakMap();
95
96
  var roundByStep = (value, step, mode = "floor") => {
96
97
  if (!step || !Number.isFinite(value)) return value;
97
98
  const ratio = value / step;
@@ -103,15 +104,20 @@ var stepToPrecision = (raw) => {
103
104
  const [, decimals = ""] = raw.split(".");
104
105
  return decimals.length;
105
106
  };
106
- var getSymbolMeta = async (client, symbol) => {
107
- const cached = symbolMetaCache.get(symbol);
108
- if (cached) return cached;
107
+ var getSymbolMeta = async (client, symbol, refresh = false) => {
108
+ let cache = symbolMetaCache.get(client);
109
+ if (!cache) {
110
+ cache = /* @__PURE__ */ new Map();
111
+ symbolMetaCache.set(client, cache);
112
+ }
113
+ const cached = cache.get(symbol);
114
+ if (!refresh && cached && cached.expiresAt > Date.now()) return cached.value;
109
115
  const res = await client.getInstrumentsInfo({
110
116
  category: BYBIT_CATEGORY,
111
117
  symbol
112
118
  });
113
119
  const item = res?.result?.list?.[0];
114
- if (!item) {
120
+ if (res.retCode !== 0 || !item || item.symbol !== symbol) {
115
121
  throw new Error(`No instrument info for symbol ${symbol}`);
116
122
  }
117
123
  const tickSizeStr = item.priceFilter?.tickSize ?? "0.01";
@@ -121,13 +127,18 @@ var getSymbolMeta = async (client, symbol) => {
121
127
  tickSize: Number(tickSizeStr),
122
128
  qtyStep: Number(qtyStepStr),
123
129
  minOrderQty: Number(minOrderQtyStr),
130
+ maxMarketOrderQty: "maxMktOrderQty" in item.lotSizeFilter ? Number(item.lotSizeFilter.maxMktOrderQty) : null,
131
+ maxLimitOrderQty: Number(item.lotSizeFilter.maxOrderQty),
124
132
  pricePrecision: stepToPrecision(tickSizeStr),
125
133
  qtyPrecision: stepToPrecision(qtyStepStr),
126
- maxLeverage: Number.isFinite(
127
- Number(item.leverageFilter?.maxLeverage)
128
- ) ? Number(item.leverageFilter.maxLeverage) : null
134
+ minLeverage: "leverageFilter" in item ? Number(item.leverageFilter.minLeverage) : null,
135
+ maxLeverage: "leverageFilter" in item ? Number(item.leverageFilter.maxLeverage) : null,
136
+ leverageStep: "leverageFilter" in item ? Number(item.leverageFilter.leverageStep) : null
129
137
  };
130
- symbolMetaCache.set(symbol, meta);
138
+ cache.set(symbol, {
139
+ value: meta,
140
+ expiresAt: Date.now() + SYMBOL_META_TTL_MS
141
+ });
131
142
  return meta;
132
143
  };
133
144
  var normalizeQty = (rawQty, meta) => {
@@ -135,6 +146,19 @@ var normalizeQty = (rawQty, meta) => {
135
146
  const qtyStr = qtyNum.toFixed(meta.qtyPrecision);
136
147
  return { qtyNum, qtyStr };
137
148
  };
149
+ var normalizeEntryQty = (rawQty, meta, isLimit) => {
150
+ const maxQty = isLimit ? meta.maxLimitOrderQty : meta.maxMarketOrderQty;
151
+ if (typeof maxQty !== "number" || !Number.isFinite(maxQty) || maxQty <= 0)
152
+ throw new Error("BYBIT_INVALID_ORDER_QTY_LIMIT");
153
+ if (!Number.isFinite(rawQty) || rawQty <= 0)
154
+ throw new Error("BYBIT_INVALID_ORDER_QTY");
155
+ if (!Number.isFinite(meta.qtyStep) || meta.qtyStep <= 0)
156
+ throw new Error("BYBIT_INVALID_QTY_STEP");
157
+ const normalized = normalizeQty(Math.min(rawQty, maxQty), meta);
158
+ if (!Number.isFinite(normalized.qtyNum) || normalized.qtyNum > rawQty || normalized.qtyNum > maxQty)
159
+ throw new Error("BYBIT_INVALID_NORMALIZED_ORDER_QTY");
160
+ return normalized;
161
+ };
138
162
  var normalizePrice = (rawPrice, role, meta) => {
139
163
  let mode = "floor";
140
164
  switch (role) {
@@ -172,6 +196,199 @@ var mapPositionData = (data) => {
172
196
  }));
173
197
  };
174
198
 
199
+ // src/ByBit/leverage.ts
200
+ var CATEGORY = "linear";
201
+ var REFRESH_CODES = /* @__PURE__ */ new Set([110013, 110085, 110086, 110089, 110090]);
202
+ var orderQueues = /* @__PURE__ */ new Map();
203
+ var withBybitOrderLock = async (key, action) => {
204
+ const previous = orderQueues.get(key) ?? Promise.resolve();
205
+ let release;
206
+ const pending = new Promise((resolve) => {
207
+ release = resolve;
208
+ });
209
+ orderQueues.set(key, pending);
210
+ await previous;
211
+ try {
212
+ return await action();
213
+ } finally {
214
+ release();
215
+ if (orderQueues.get(key) === pending) orderQueues.delete(key);
216
+ }
217
+ };
218
+ var positive = (value, label) => {
219
+ const parsed = Number(value);
220
+ if (!["string", "number"].includes(typeof value) || value === "" || !Number.isFinite(parsed) || parsed <= 0) {
221
+ throw new Error(`BYBIT_INVALID_${label}`);
222
+ }
223
+ return parsed;
224
+ };
225
+ var nonNegative = (value, label) => {
226
+ if (value === "0" || value === 0) return 0;
227
+ return positive(value, label);
228
+ };
229
+ var loadPositions = async (client, symbol) => {
230
+ const response = await client.getPositionInfo({ category: CATEGORY, symbol });
231
+ if (response.retCode !== 0 || !Array.isArray(response.result?.list) || !response.result.list.length) {
232
+ throw new Error("BYBIT_LEVERAGE_POSITION_UNAVAILABLE");
233
+ }
234
+ const rows = response.result.list;
235
+ if (rows.some((row) => row.symbol !== symbol || row.positionIdx !== 0)) {
236
+ throw new Error("BYBIT_LEVERAGE_POSITION_MODE_UNSUPPORTED");
237
+ }
238
+ return rows;
239
+ };
240
+ var loadRiskMaximum = async (client, symbol, positionValue, riskIds) => {
241
+ let cursor;
242
+ const tiers = [];
243
+ for (let page = 0; page < 20; page += 1) {
244
+ const response = await client.getRiskLimit({
245
+ category: CATEGORY,
246
+ symbol,
247
+ ...cursor ? { cursor } : {}
248
+ });
249
+ if (response.retCode !== 0 || !Array.isArray(response.result?.list)) {
250
+ throw new Error("BYBIT_LEVERAGE_RISK_LIMIT_UNAVAILABLE");
251
+ }
252
+ for (const row of response.result.list) {
253
+ if (row.symbol !== symbol) continue;
254
+ tiers.push({
255
+ id: row.id,
256
+ value: positive(row.riskLimitValue, "RISK_LIMIT"),
257
+ leverage: positive(row.maxLeverage, "RISK_LEVERAGE")
258
+ });
259
+ }
260
+ const nextCursor = "nextPageCursor" in response.result ? response.result.nextPageCursor : void 0;
261
+ if (nextCursor != null && typeof nextCursor !== "string")
262
+ throw new Error("BYBIT_LEVERAGE_INVALID_CURSOR");
263
+ cursor = nextCursor ?? void 0;
264
+ if (!cursor) break;
265
+ if (page === 19) throw new Error("BYBIT_LEVERAGE_RISK_LIMIT_INCOMPLETE");
266
+ }
267
+ const tier = tiers.sort((left, right) => left.value - right.value).find((row) => row.value >= positionValue);
268
+ if (!tier) throw new Error("BYBIT_LEVERAGE_RISK_LIMIT_EXCEEDED");
269
+ const currentTiers = riskIds.map((id) => {
270
+ const current = tiers.find((row) => row.id === id);
271
+ if (!current) throw new Error("BYBIT_LEVERAGE_RISK_TIER_UNKNOWN");
272
+ return current;
273
+ });
274
+ return Math.min(tier.leverage, ...currentTiers.map((row) => row.leverage));
275
+ };
276
+ var loadPendingValue = async (client, symbol, price) => {
277
+ const total = { Buy: 0, Sell: 0 };
278
+ let cursor;
279
+ for (let page = 0; page < 20; page += 1) {
280
+ const response = await client.getActiveOrders({
281
+ category: CATEGORY,
282
+ symbol,
283
+ openOnly: 0,
284
+ orderFilter: "Order",
285
+ limit: 50,
286
+ ...cursor ? { cursor } : {}
287
+ });
288
+ if (response.retCode !== 0 || !Array.isArray(response.result?.list))
289
+ throw new Error("BYBIT_LEVERAGE_OPEN_ORDERS_UNAVAILABLE");
290
+ for (const order of response.result.list) {
291
+ if (order.symbol !== symbol || order.reduceOnly) continue;
292
+ if (order.side !== "Buy" && order.side !== "Sell")
293
+ throw new Error("BYBIT_INVALID_OPEN_ORDER_SIDE");
294
+ const qty = nonNegative(order.leavesQty, "OPEN_ORDER_QTY");
295
+ const orderPrice = nonNegative(order.price, "OPEN_ORDER_PRICE");
296
+ total[order.side] += qty * Math.max(price, orderPrice);
297
+ }
298
+ cursor = response.result.nextPageCursor;
299
+ if (!cursor) return total;
300
+ }
301
+ throw new Error("BYBIT_LEVERAGE_OPEN_ORDERS_INCOMPLETE");
302
+ };
303
+ var normalizeLeverage = (requested, max, min, step) => {
304
+ const cap = Math.min(requested, max);
305
+ const result = Number(
306
+ (min + Math.floor((cap - min + step * 1e-9) / step) * step).toFixed(12)
307
+ );
308
+ if (result < min || result > cap + 1e-9)
309
+ throw new Error("BYBIT_LEVERAGE_NOT_AVAILABLE");
310
+ return result;
311
+ };
312
+ var prepareBybitLeverage = async ({
313
+ client,
314
+ marketClient,
315
+ symbol,
316
+ requested,
317
+ direction,
318
+ qty,
319
+ price
320
+ }) => {
321
+ positive(requested, "REQUESTED_LEVERAGE");
322
+ positive(qty, "ORDER_QTY");
323
+ positive(price, "ORDER_PRICE");
324
+ for (let attempt = 0; attempt < 2; attempt += 1) {
325
+ const meta = await getSymbolMeta(marketClient, symbol, attempt > 0);
326
+ const min = positive(meta.minLeverage, "MIN_LEVERAGE");
327
+ const max = positive(meta.maxLeverage, "MAX_LEVERAGE");
328
+ const step = positive(meta.leverageStep, "LEVERAGE_STEP");
329
+ if (max < min) throw new Error("BYBIT_INVALID_LEVERAGE_RANGE");
330
+ const positions = await loadPositions(client, symbol);
331
+ const exposure = {
332
+ Buy: direction === "LONG" ? qty * price : 0,
333
+ Sell: direction === "SHORT" ? qty * price : 0
334
+ };
335
+ const riskIds = [];
336
+ for (const position of positions) {
337
+ positive(position.leverage, "POSITION_LEVERAGE");
338
+ const size = nonNegative(position.size, "POSITION_SIZE");
339
+ if (size > 0) {
340
+ if (position.side !== "Buy" && position.side !== "Sell")
341
+ throw new Error("BYBIT_INVALID_POSITION_SIDE");
342
+ exposure[position.side] += Math.max(
343
+ nonNegative(position.positionValue, "POSITION_VALUE"),
344
+ size * price
345
+ );
346
+ riskIds.push(positive(position.riskId, "POSITION_RISK_ID"));
347
+ }
348
+ }
349
+ const pending = await loadPendingValue(client, symbol, price);
350
+ const positionValue = Math.max(
351
+ exposure.Buy + pending.Buy,
352
+ exposure.Sell + pending.Sell
353
+ );
354
+ const riskMax = await loadRiskMaximum(
355
+ client,
356
+ symbol,
357
+ positionValue,
358
+ riskIds
359
+ );
360
+ const effective = normalizeLeverage(
361
+ requested,
362
+ Math.min(max, riskMax),
363
+ min,
364
+ step
365
+ );
366
+ const response = await client.setLeverage({
367
+ category: CATEGORY,
368
+ symbol,
369
+ buyLeverage: String(effective),
370
+ sellLeverage: String(effective)
371
+ });
372
+ if (response.retCode !== 0 && response.retCode !== 110043) {
373
+ if (attempt === 0 && REFRESH_CODES.has(response.retCode)) continue;
374
+ throw new Error(
375
+ `BYBIT_SET_LEVERAGE_${response.retCode ?? "INVALID_RESPONSE"}`
376
+ );
377
+ }
378
+ const confirmed = await loadPositions(client, symbol);
379
+ if (confirmed.some((row) => Number(row.leverage) !== effective))
380
+ throw new Error("BYBIT_LEVERAGE_NOT_CONFIRMED");
381
+ return {
382
+ requested,
383
+ effective,
384
+ maxAllowed: Math.min(max, riskMax),
385
+ reductionReason: effective === requested ? null : riskMax < Math.min(requested, max) ? "risk_limit" : max < requested ? "instrument_limit" : "leverage_step",
386
+ verifiedAt: Date.now()
387
+ };
388
+ }
389
+ throw new Error("BYBIT_LEVERAGE_NOT_CONFIRMED");
390
+ };
391
+
175
392
  // src/ByBit/index.ts
176
393
  import {
177
394
  resolveConnectorUniverse
@@ -216,6 +433,7 @@ var INTERVAL_TO_MINUTES = {
216
433
  var getLogLevel = (res) => res.retCode === 0 ? "info" : "error";
217
434
  var isTradingStopNotModified = (res) => res?.retCode === BYBIT_TRADING_STOP_NOT_MODIFIED_RETCODE;
218
435
  var isTradingStopAccepted = (res) => res?.retCode === 0 || isTradingStopNotModified(res);
436
+ var isMaxOrderQuantityRejected = (response) => response.retCode === 10001 && typeof response.retMsg === "string" && /number of contracts exceeds maximum limit allowed/i.test(response.retMsg);
219
437
  var isKlineRateLimited = (res) => res?.retCode === BYBIT_RATE_LIMIT_RETCODE;
220
438
  var mapBybitAssetClass = (symbolType) => {
221
439
  if (symbolType === "stock") return "equity";
@@ -1189,119 +1407,198 @@ var ByBitConnectorCreator = async (config, runtime) => {
1189
1407
  signal,
1190
1408
  leverage
1191
1409
  }) => {
1192
- invalidatePositionSnapshot(symbol);
1193
- const client = await getPrivateClient();
1194
- const marketDataClient = await getPublicClient();
1195
- if (!client || !marketDataClient) {
1196
- if (signal) {
1197
- signal.orderFailureReason = "BYBIT_CLIENT_UNAVAILABLE";
1198
- }
1199
- return false;
1200
- }
1201
- const isLong = direction === "LONG";
1202
- if (positionIntent === "increase") {
1203
- const currentPosition = await getPositionSnapshot(symbol);
1204
- if (!currentPosition || currentPosition.direction !== direction) {
1205
- const failureReason = currentPosition ? "POSITION_DIRECTION_MISMATCH" : "POSITION_NOT_FOUND";
1206
- if (signal) {
1207
- signal.orderFailureReason = failureReason;
1410
+ return withBybitOrderLock(
1411
+ JSON.stringify([
1412
+ config.userName,
1413
+ config.accountId ?? "default",
1414
+ symbol
1415
+ ]),
1416
+ async () => {
1417
+ if (signal) signal.orderLeverage = void 0;
1418
+ invalidatePositionSnapshot(symbol);
1419
+ const client = await getPrivateClient();
1420
+ const marketDataClient = await getPublicClient();
1421
+ if (!client || !marketDataClient) {
1422
+ if (signal) {
1423
+ signal.orderFailureReason = "BYBIT_CLIENT_UNAVAILABLE";
1424
+ }
1425
+ return false;
1208
1426
  }
1209
- logger.log(
1210
- "warn",
1211
- "placeOrder: rejected position increase: %s",
1212
- toJson(
1213
- {
1427
+ const isLong = direction === "LONG";
1428
+ if (positionIntent === "increase") {
1429
+ const currentPosition = await getPositionSnapshot(symbol);
1430
+ if (!currentPosition || currentPosition.direction !== direction) {
1431
+ const failureReason = currentPosition ? "POSITION_DIRECTION_MISMATCH" : "POSITION_NOT_FOUND";
1432
+ if (signal) {
1433
+ signal.orderFailureReason = failureReason;
1434
+ }
1435
+ logger.log(
1436
+ "warn",
1437
+ "placeOrder: rejected position increase: %s",
1438
+ toJson(
1439
+ {
1440
+ symbol,
1441
+ direction,
1442
+ currentDirection: currentPosition?.direction ?? null,
1443
+ failureReason
1444
+ },
1445
+ true
1446
+ )
1447
+ );
1448
+ return false;
1449
+ }
1450
+ }
1451
+ let quantityCeiling = qty;
1452
+ let quantityRejection = "";
1453
+ for (let attempt = 0; attempt < 2; attempt += 1) {
1454
+ if (signal) signal.orderLeverage = void 0;
1455
+ const meta = await getSymbolMeta(
1456
+ marketDataClient,
1457
+ symbol,
1458
+ attempt > 0
1459
+ );
1460
+ let normalizedQty;
1461
+ try {
1462
+ normalizedQty = normalizeEntryQty(
1463
+ quantityCeiling,
1464
+ meta,
1465
+ isLimit === true
1466
+ );
1467
+ } catch (error) {
1468
+ const reason = error instanceof Error ? error.message : "BYBIT_ORDER_QTY_UNAVAILABLE";
1469
+ if (signal) signal.orderFailureReason = reason;
1470
+ logger.log(
1471
+ "warn",
1472
+ "placeOrder: quantity preparation failed: %s %s",
1214
1473
  symbol,
1474
+ reason
1475
+ );
1476
+ return false;
1477
+ }
1478
+ if (attempt > 0 && normalizedQty.qtyNum >= quantityCeiling) {
1479
+ if (signal) signal.orderFailureReason = quantityRejection;
1480
+ return false;
1481
+ }
1482
+ const isQtyBelowMin = normalizedQty.qtyNum < meta.minOrderQty;
1483
+ if (isQtyBelowMin) {
1484
+ if (signal) {
1485
+ signal.orderQty = normalizedQty.qtyNum;
1486
+ signal.orderValue = normalizedQty.qtyNum * price;
1487
+ signal.orderFailureReason = "QTY_BELOW_MIN_ORDER";
1488
+ }
1489
+ logger.log(
1490
+ "warn",
1491
+ "placeOrder: rejected qty below minOrderQty: %s",
1492
+ toJson(
1493
+ {
1494
+ symbol,
1495
+ qty,
1496
+ normalizedOrderQty: normalizedQty.qtyNum,
1497
+ minOrderQty: meta.minOrderQty
1498
+ },
1499
+ true
1500
+ )
1501
+ );
1502
+ return false;
1503
+ }
1504
+ if (normalizedQty.qtyNum < qty) {
1505
+ logger.log(
1506
+ "info",
1507
+ "placeOrder: quantity reduced: %s",
1508
+ toJson({
1509
+ symbol,
1510
+ requestedQty: qty,
1511
+ orderQty: normalizedQty.qtyNum,
1512
+ maxOrderQty: isLimit ? meta.maxLimitOrderQty : meta.maxMarketOrderQty,
1513
+ orderType: isLimit ? "Limit" : "Market"
1514
+ })
1515
+ );
1516
+ }
1517
+ const orderQty = normalizedQty.qtyNum;
1518
+ const orderQtyStr = normalizedQty.qtyStr;
1519
+ if (signal) {
1520
+ signal.orderQty = orderQty;
1521
+ signal.orderValue = orderQty * price;
1522
+ }
1523
+ const entryNormalized = isLimit ? normalizePrice(price, "ENTRY", meta) : void 0;
1524
+ logger.log(
1525
+ "info",
1526
+ "placeOrder: %s",
1527
+ toJson(
1528
+ {
1529
+ symbol,
1530
+ price,
1531
+ qty,
1532
+ direction,
1533
+ orderQty,
1534
+ orderQtyStr
1535
+ },
1536
+ true
1537
+ )
1538
+ );
1539
+ try {
1540
+ const orderLeverage = await prepareBybitLeverage({
1541
+ client,
1542
+ marketClient: marketDataClient,
1543
+ symbol,
1544
+ requested: leverage ?? 10,
1215
1545
  direction,
1216
- currentDirection: currentPosition?.direction ?? null,
1217
- failureReason
1218
- },
1219
- true
1220
- )
1221
- );
1546
+ qty: orderQty,
1547
+ price
1548
+ });
1549
+ if (signal) signal.orderLeverage = orderLeverage;
1550
+ logger.log(
1551
+ "info",
1552
+ "placeOrder:leverage %s %s",
1553
+ symbol,
1554
+ toJson(orderLeverage)
1555
+ );
1556
+ } catch (error) {
1557
+ const reason = error instanceof Error && error.message.startsWith("BYBIT_") ? error.message : "BYBIT_LEVERAGE_UNAVAILABLE";
1558
+ if (signal) signal.orderFailureReason = reason;
1559
+ logger.log(
1560
+ "warn",
1561
+ "placeOrder: leverage preparation failed: %s %s",
1562
+ symbol,
1563
+ reason
1564
+ );
1565
+ return false;
1566
+ }
1567
+ const orderRes = await client.submitOrder({
1568
+ category: BYBIT_CATEGORY2,
1569
+ symbol,
1570
+ price: entryNormalized?.priceStr || void 0,
1571
+ side: isLong ? "Buy" : "Sell",
1572
+ orderType: isLimit ? "Limit" : "Market",
1573
+ qty: orderQtyStr,
1574
+ orderFilter: "Order",
1575
+ orderLinkId: typeof orderId === "string" && orderId.trim() ? orderId : void 0
1576
+ });
1577
+ logger.log(
1578
+ getLogLevel(orderRes),
1579
+ "placeOrder:response: %s",
1580
+ toJson(orderRes, true)
1581
+ );
1582
+ if (orderRes.retCode !== 0) {
1583
+ if (attempt === 0 && isMaxOrderQuantityRejected(orderRes)) {
1584
+ quantityCeiling = orderQty;
1585
+ quantityRejection = orderRes.retMsg;
1586
+ continue;
1587
+ }
1588
+ if (signal) {
1589
+ signal.orderFailureReason = typeof orderRes.retMsg === "string" && orderRes.retMsg.trim() ? orderRes.retMsg.trim() : `BYBIT_RETCODE_${orderRes.retCode}`;
1590
+ }
1591
+ return false;
1592
+ }
1593
+ if (signal) {
1594
+ signal.orderFailureReason = void 0;
1595
+ }
1596
+ invalidatePositionSnapshot(symbol);
1597
+ return true;
1598
+ }
1222
1599
  return false;
1223
1600
  }
1224
- }
1225
- const meta = await getSymbolMeta(marketDataClient, symbol);
1226
- const normalizedQty = normalizeQty(qty, meta);
1227
- const isQtyBelowMin = normalizedQty.qtyNum < meta.minOrderQty;
1228
- if (isQtyBelowMin) {
1229
- if (signal) {
1230
- signal.orderQty = normalizedQty.qtyNum;
1231
- signal.orderValue = normalizedQty.qtyNum * price;
1232
- signal.orderFailureReason = "QTY_BELOW_MIN_ORDER";
1233
- }
1234
- logger.log(
1235
- "warn",
1236
- "placeOrder: rejected qty below minOrderQty: %s",
1237
- toJson(
1238
- {
1239
- symbol,
1240
- qty,
1241
- normalizedOrderQty: normalizedQty.qtyNum,
1242
- minOrderQty: meta.minOrderQty
1243
- },
1244
- true
1245
- )
1246
- );
1247
- return false;
1248
- }
1249
- const orderQty = normalizedQty.qtyNum;
1250
- const orderQtyStr = normalizedQty.qtyStr;
1251
- if (signal) {
1252
- signal.orderQty = orderQty;
1253
- signal.orderValue = orderQty * price;
1254
- }
1255
- const entryNormalized = isLimit ? normalizePrice(price, "ENTRY", meta) : void 0;
1256
- logger.log(
1257
- "info",
1258
- "placeOrder: %s",
1259
- toJson(
1260
- {
1261
- symbol,
1262
- price,
1263
- qty,
1264
- direction,
1265
- orderQty,
1266
- orderQtyStr
1267
- },
1268
- true
1269
- )
1270
- );
1271
- const requestedLeverage = typeof leverage === "number" && Number.isFinite(leverage) ? Math.max(1, leverage) : 10;
1272
- const effectiveLeverage = meta.maxLeverage != null ? Math.min(requestedLeverage, meta.maxLeverage) : requestedLeverage;
1273
- await client.setLeverage({
1274
- category: BYBIT_CATEGORY2,
1275
- symbol,
1276
- buyLeverage: String(effectiveLeverage),
1277
- sellLeverage: String(effectiveLeverage)
1278
- });
1279
- const orderRes = await client.submitOrder({
1280
- category: BYBIT_CATEGORY2,
1281
- symbol,
1282
- price: entryNormalized?.priceStr || void 0,
1283
- side: isLong ? "Buy" : "Sell",
1284
- orderType: isLimit ? "Limit" : "Market",
1285
- qty: orderQtyStr,
1286
- orderFilter: "Order",
1287
- orderLinkId: typeof orderId === "string" && orderId.trim() ? orderId : void 0
1288
- });
1289
- logger.log(
1290
- getLogLevel(orderRes),
1291
- "placeOrder:response: %s",
1292
- toJson(orderRes, true)
1293
1601
  );
1294
- if (orderRes.retCode !== 0) {
1295
- if (signal) {
1296
- signal.orderFailureReason = typeof orderRes.retMsg === "string" && orderRes.retMsg.trim() ? orderRes.retMsg.trim() : `BYBIT_RETCODE_${orderRes.retCode}`;
1297
- }
1298
- return false;
1299
- }
1300
- if (signal) {
1301
- signal.orderFailureReason = void 0;
1302
- }
1303
- invalidatePositionSnapshot(symbol);
1304
- return true;
1305
1602
  },
1306
1603
  setPositionProtection,
1307
1604
  setTakeProfits,
@@ -2061,7 +2358,7 @@ var spotKlineProviders = {
2061
2358
  // src/ByBit/klineStream.ts
2062
2359
  import { WebsocketClient } from "bybit-api";
2063
2360
  import { formatUnix as formatUnix3 } from "@tradejs/core/time";
2064
- var CATEGORY = "linear";
2361
+ var CATEGORY2 = "linear";
2065
2362
  var SUBSCRIPTION_BATCH_SIZE = 100;
2066
2363
  var KLINE_TOPIC_PATTERN = /^kline\.([^.]+)\.(.+)$/;
2067
2364
  var chunk = (items, size) => {
@@ -2146,12 +2443,12 @@ var createBybitKlineStreamWithClient = ({
2146
2443
  const added = [...nextTopics].filter((topic) => !topics.has(topic));
2147
2444
  const removed = [...topics].filter((topic) => !nextTopics.has(topic));
2148
2445
  for (const batch of chunk(removed, SUBSCRIPTION_BATCH_SIZE)) {
2149
- void Promise.all(client.unsubscribeV5(batch, CATEGORY)).catch(
2446
+ void Promise.all(client.unsubscribeV5(batch, CATEGORY2)).catch(
2150
2447
  (error) => logger.error("Bybit kline unsubscribe failed: %s", String(error))
2151
2448
  );
2152
2449
  }
2153
2450
  for (const batch of chunk(added, SUBSCRIPTION_BATCH_SIZE)) {
2154
- void Promise.all(client.subscribeV5(batch, CATEGORY)).catch(
2451
+ void Promise.all(client.subscribeV5(batch, CATEGORY2)).catch(
2155
2452
  (error) => logger.error("Bybit kline subscribe failed: %s", String(error))
2156
2453
  );
2157
2454
  }
@@ -2169,7 +2466,7 @@ var createBybitKlineStreamWithClient = ({
2169
2466
  const currentTopics = [...topics];
2170
2467
  topics.clear();
2171
2468
  for (const batch of chunk(currentTopics, SUBSCRIPTION_BATCH_SIZE)) {
2172
- await Promise.allSettled(client.unsubscribeV5(batch, CATEGORY));
2469
+ await Promise.allSettled(client.unsubscribeV5(batch, CATEGORY2));
2173
2470
  }
2174
2471
  client.closeAll();
2175
2472
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tradejs/connectors",
3
- "version": "3.1.29-beta.284",
3
+ "version": "3.1.29-beta.286",
4
4
  "description": "MIT-licensed exchange connectors and market data providers for the TradeJS framework.",
5
5
  "keywords": [
6
6
  "tradejs",
@@ -39,8 +39,8 @@
39
39
  }
40
40
  },
41
41
  "dependencies": {
42
- "@tradejs/core": "^3.1.29-beta.284",
43
- "@tradejs/types": "^3.1.29-beta.284",
42
+ "@tradejs/core": "^3.1.29-beta.286",
43
+ "@tradejs/types": "^3.1.29-beta.286",
44
44
  "bybit-api": "^4.7.1",
45
45
  "chalk": "4.1.2",
46
46
  "lodash": "^4.18.1"