perp-cli 0.4.2 → 0.4.8

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 (68) hide show
  1. package/README.md +2 -0
  2. package/dist/arb/sizing.d.ts +12 -1
  3. package/dist/arb/sizing.js +38 -5
  4. package/dist/arb/state.d.ts +6 -0
  5. package/dist/cli-spec.d.ts +0 -4
  6. package/dist/cli-spec.js +8 -1
  7. package/dist/commands/agent.js +7 -4
  8. package/dist/commands/arb-auto.js +643 -4
  9. package/dist/commands/dex.js +7 -1
  10. package/dist/commands/funding.d.ts +2 -1
  11. package/dist/commands/funding.js +211 -4
  12. package/dist/commands/manage.js +1 -1
  13. package/dist/commands/market.js +1 -1
  14. package/dist/commands/multileg.d.ts +16 -0
  15. package/dist/commands/multileg.js +174 -0
  16. package/dist/commands/pnl.d.ts +12 -0
  17. package/dist/commands/pnl.js +243 -0
  18. package/dist/commands/stream.js +132 -55
  19. package/dist/commands/trade.js +29 -8
  20. package/dist/commands/wallet.js +1 -1
  21. package/dist/config.d.ts +5 -0
  22. package/dist/config.js +12 -0
  23. package/dist/dashboard/ws-feeds.js +1 -1
  24. package/dist/equity-tracker.d.ts +57 -0
  25. package/dist/equity-tracker.js +209 -0
  26. package/dist/exchanges/hyperliquid-spot.d.ts +68 -0
  27. package/dist/exchanges/hyperliquid-spot.js +317 -0
  28. package/dist/exchanges/hyperliquid.d.ts +26 -5
  29. package/dist/exchanges/hyperliquid.js +171 -73
  30. package/dist/exchanges/interface.d.ts +1 -1
  31. package/dist/exchanges/lighter-spot.d.ts +55 -0
  32. package/dist/exchanges/lighter-spot.js +417 -0
  33. package/dist/exchanges/lighter.d.ts +10 -2
  34. package/dist/exchanges/lighter.js +128 -35
  35. package/dist/exchanges/pacifica.d.ts +11 -4
  36. package/dist/exchanges/pacifica.js +52 -37
  37. package/dist/exchanges/spot-interface.d.ts +45 -0
  38. package/dist/exchanges/spot-interface.js +22 -0
  39. package/dist/execution-log.d.ts +2 -2
  40. package/dist/funding/rates.d.ts +36 -0
  41. package/dist/funding/rates.js +146 -0
  42. package/dist/index.js +147 -98
  43. package/dist/liquidity.d.ts +12 -0
  44. package/dist/liquidity.js +43 -0
  45. package/dist/signer/evm-local.d.ts +12 -0
  46. package/dist/signer/evm-local.js +19 -0
  47. package/dist/signer/index.d.ts +3 -0
  48. package/dist/signer/index.js +2 -0
  49. package/dist/signer/interface.d.ts +31 -0
  50. package/dist/signer/interface.js +7 -0
  51. package/dist/signer/solana-local.d.ts +13 -0
  52. package/dist/signer/solana-local.js +19 -0
  53. package/dist/smart-order.js +14 -3
  54. package/dist/utils.js +7 -1
  55. package/dist/ws/market-feed.d.ts +74 -0
  56. package/dist/ws/market-feed.js +227 -0
  57. package/package.json +1 -1
  58. package/skills/perp-cli/SKILL.md +93 -4
  59. package/skills/perp-cli/references/commands.md +16 -1
  60. package/skills/perp-cli/references/strategies.md +1 -1
  61. package/skills/perp-cli/scripts/arb-monitor.sh +74 -0
  62. package/skills/perp-cli/scripts/funding-analysis.sh +85 -0
  63. package/skills/perp-cli/scripts/preflight.sh +98 -0
  64. package/skills/perp-cli/scripts/spot-perp-scan.sh +83 -0
  65. package/skills/perp-cli/scripts/validate-arb.sh +112 -0
  66. package/skills/perp-cli/templates/arb-scan.sh +0 -15
  67. package/skills/perp-cli/templates/open-position.sh +0 -38
  68. package/skills/perp-cli/templates/wallet-setup.sh +0 -17
@@ -898,7 +898,8 @@ export function registerArbAutoCommands(program, getAdapterForExchange, isJson,
898
898
  // ── arb scan ── (one-shot spread scan)
899
899
  arb
900
900
  .command("scan")
901
- .description("Scan current funding rate spreads")
901
+ .description("Scan current funding rate spreads (perp-perp or spot-perp)")
902
+ .option("--mode <mode>", "Scan mode: perp-perp, spot-perp, all", "perp-perp")
902
903
  .option("--min <pct>", "Min annual spread to show", "10")
903
904
  .option("--top <n>", "Return only top N results (for JSON output)")
904
905
  .option("--hold-days <days>", "Expected hold period for cost calc", "7")
@@ -909,8 +910,50 @@ export function registerArbAutoCommands(program, getAdapterForExchange, isJson,
909
910
  const holdDays = parseFloat(opts.holdDays);
910
911
  const bridgeCostUsd = parseFloat(opts.bridgeCost);
911
912
  const sizeUsd = parseFloat(opts.size);
913
+ // ── spot-perp mode ──
914
+ if (opts.mode === "spot-perp" || opts.mode === "all") {
915
+ if (!isJson())
916
+ console.log(chalk.cyan("\n Scanning spot+perp funding opportunities...\n"));
917
+ const { fetchSpotPerpSpreads } = await import("../funding/rates.js");
918
+ const { spreads: spotSpreads } = await fetchSpotPerpSpreads({ minSpread });
919
+ if (isJson() && opts.mode === "spot-perp") {
920
+ let result = spotSpreads.map(s => ({
921
+ mode: "spot-perp", symbol: s.symbol, perpExchange: s.perpExchange,
922
+ spotExchanges: s.spotExchanges, annualSpreadPct: s.annualSpreadPct,
923
+ perpFundingRate: s.perpFundingRate, direction: s.direction,
924
+ markPrice: s.bestMarkPrice, estHourlyIncomeUsd: s.estHourlyIncomeUsd,
925
+ }));
926
+ if (opts.top)
927
+ result = result.slice(0, parseInt(opts.top));
928
+ return printJson(jsonOk(result));
929
+ }
930
+ if (!isJson()) {
931
+ if (spotSpreads.length === 0) {
932
+ console.log(chalk.gray(` No spot+perp opportunities above ${minSpread}%\n`));
933
+ }
934
+ else {
935
+ console.log(chalk.gray(` ${"SYMBOL".padEnd(8)} ${"SPREAD".padEnd(8)} ${"PERP EX".padEnd(9)} ${"SPOT EX".padEnd(12)} ${"FUND".padEnd(12)} DIRECTION`));
936
+ for (const s of spotSpreads.slice(0, parseInt(opts.top ?? "30"))) {
937
+ const spreadColor = s.annualSpreadPct >= 30 ? chalk.green : chalk.yellow;
938
+ const dir = s.direction === "long-spot-short-perp" ? "Spot+Short" : "Sell+Long";
939
+ console.log(` ${chalk.white.bold(s.symbol.padEnd(8))} ` +
940
+ `${spreadColor(`${s.annualSpreadPct.toFixed(1)}%`.padEnd(8))} ` +
941
+ `${s.perpExchange.slice(0, 8).padEnd(9)} ` +
942
+ `${s.spotExchanges.join(",").slice(0, 11).padEnd(12)} ` +
943
+ `${(s.perpFundingRate * 100).toFixed(4).padEnd(12)}% ` +
944
+ dir);
945
+ }
946
+ console.log(chalk.gray(`\n ${spotSpreads.length} spot+perp opportunities (spot funding = 0%)`));
947
+ }
948
+ }
949
+ if (opts.mode === "spot-perp")
950
+ return;
951
+ if (!isJson())
952
+ console.log(""); // separator
953
+ }
954
+ // ── perp-perp mode (default) ──
912
955
  if (!isJson())
913
- console.log(chalk.cyan("\n Scanning funding rate spreads...\n"));
956
+ console.log(chalk.cyan(" Scanning perp-perp funding rate spreads...\n"));
914
957
  const spreads = await fetchFundingSpreads();
915
958
  const filtered = spreads.filter(s => Math.abs(s.spread) >= minSpread);
916
959
  if (isJson()) {
@@ -918,14 +961,14 @@ export function registerArbAutoCommands(program, getAdapterForExchange, isJson,
918
961
  const grossSpread = Math.abs(s.spread);
919
962
  const rtCost = computeRoundTripCostPct(s.longExch, s.shortExch);
920
963
  const net = computeNetSpread(grossSpread, holdDays, rtCost, bridgeCostUsd, sizeUsd);
921
- return { symbol: s.symbol, longExch: s.longExch, shortExch: s.shortExch, markPrice: s.markPrice, grossSpread, netSpread: net, estFeesPct: rtCost };
964
+ return { mode: "perp-perp", symbol: s.symbol, longExch: s.longExch, shortExch: s.shortExch, markPrice: s.markPrice, grossSpread, netSpread: net, estFeesPct: rtCost };
922
965
  }).sort((a, b) => b.netSpread - a.netSpread);
923
966
  if (opts.top)
924
967
  enriched = enriched.slice(0, parseInt(opts.top));
925
968
  return printJson(jsonOk(enriched));
926
969
  }
927
970
  if (filtered.length === 0) {
928
- console.log(chalk.gray(` No spreads above ${minSpread}%\n`));
971
+ console.log(chalk.gray(` No perp-perp spreads above ${minSpread}%\n`));
929
972
  return;
930
973
  }
931
974
  // Header
@@ -1181,6 +1224,602 @@ export function registerArbAutoCommands(program, getAdapterForExchange, isJson,
1181
1224
  console.log(chalk.red(` SHORT: ${result.shortError}\n`));
1182
1225
  }
1183
1226
  });
1227
+ // ── arb spot-exec ── (spot+perp arb execution)
1228
+ arb
1229
+ .command("spot-exec")
1230
+ .description("Execute spot+perp arb: buy spot + short perp simultaneously")
1231
+ .argument("<symbol>", "Symbol (e.g. ETH, BTC)")
1232
+ .argument("<spotExch>", "Spot exchange: hl (Hyperliquid) or lt (Lighter)")
1233
+ .argument("<perpExch>", "Perp exchange: hl, lt, pac")
1234
+ .argument("<sizeUsd>", "Position size per leg in USD")
1235
+ .option("--max-slippage <pct>", "Max slippage % per leg", "0.5")
1236
+ .option("--leverage <n>", "Set leverage on perp side before entry")
1237
+ .option("--isolated", "Use isolated margin mode on perp side")
1238
+ .option("--dry-run", "Simulate without executing trades")
1239
+ .action(async (symbol, spotExch, perpExch, sizeUsdStr, opts) => {
1240
+ const sym = symbol.toUpperCase();
1241
+ const sizeUsd = parseFloat(sizeUsdStr);
1242
+ const maxSlippage = parseFloat(opts.maxSlippage);
1243
+ const dryRun = !!opts.dryRun || process.argv.includes("--dry-run");
1244
+ // Resolve exchange aliases
1245
+ const aliasMap = { hl: "hyperliquid", pac: "pacifica", lt: "lighter" };
1246
+ spotExch = aliasMap[spotExch.toLowerCase()] || spotExch.toLowerCase();
1247
+ perpExch = aliasMap[perpExch.toLowerCase()] || perpExch.toLowerCase();
1248
+ // Validate spot exchange
1249
+ if (!["hyperliquid", "lighter"].includes(spotExch)) {
1250
+ const msg = `Spot exchange must be hl or lt (got ${spotExch}). Pacifica is perp-only.`;
1251
+ if (isJson())
1252
+ return printJson(jsonOk({ error: msg }));
1253
+ console.log(chalk.red(` ${msg}`));
1254
+ return;
1255
+ }
1256
+ // Load spot adapter
1257
+ const { HyperliquidSpotAdapter } = await import("../exchanges/hyperliquid-spot.js");
1258
+ const { LighterSpotAdapter } = await import("../exchanges/lighter-spot.js");
1259
+ let spotAdapter;
1260
+ if (spotExch === "hyperliquid") {
1261
+ const hlAdapter = await getAdapterForExchange("hyperliquid");
1262
+ const hlSpot = new HyperliquidSpotAdapter(hlAdapter);
1263
+ await hlSpot.init();
1264
+ spotAdapter = hlSpot;
1265
+ }
1266
+ else {
1267
+ const ltAdapter = await getAdapterForExchange("lighter");
1268
+ const ltSpot = new LighterSpotAdapter(ltAdapter);
1269
+ await ltSpot.init();
1270
+ spotAdapter = ltSpot;
1271
+ }
1272
+ const perpAdapter = await getAdapterForExchange(perpExch);
1273
+ // 1. Set perp leverage if requested
1274
+ if (opts.leverage) {
1275
+ const lev = parseInt(opts.leverage);
1276
+ const mode = opts.isolated ? "isolated" : "cross";
1277
+ if (!isJson())
1278
+ console.log(chalk.gray(` Setting perp leverage ${lev}x ${mode} on ${perpExch}...`));
1279
+ try {
1280
+ await perpAdapter.setLeverage(sym, lev, mode);
1281
+ }
1282
+ catch (e) {
1283
+ const msg = `Failed to set leverage: ${e instanceof Error ? e.message : e}`;
1284
+ if (isJson())
1285
+ return printJson(jsonOk({ error: msg }));
1286
+ console.log(chalk.red(` ${msg}`));
1287
+ return;
1288
+ }
1289
+ }
1290
+ // 2. Auto-transfer USDC to spot account if needed
1291
+ if (spotExch === "hyperliquid") {
1292
+ const hlSpot = spotAdapter;
1293
+ const transferAmt = Math.ceil(sizeUsd * 1.1);
1294
+ try {
1295
+ const xferResult = await hlSpot.transferUsdcToSpot(transferAmt);
1296
+ if (xferResult?.status === "err" && xferResult.response?.includes("unified")) {
1297
+ if (!isJson())
1298
+ console.log(chalk.gray(` Unified account — no USDC transfer needed`));
1299
+ }
1300
+ else if (xferResult?.status !== "err") {
1301
+ if (!isJson())
1302
+ console.log(chalk.gray(` Transferred $${transferAmt} USDC perp→spot`));
1303
+ await new Promise(r => setTimeout(r, 500));
1304
+ }
1305
+ }
1306
+ catch {
1307
+ // Non-critical — may be unified account or already have balance
1308
+ }
1309
+ }
1310
+ else if (spotExch === "lighter") {
1311
+ // Lighter requires explicit USDC transfer from perp → spot account
1312
+ const ltSpot = spotAdapter;
1313
+ const transferAmt = Math.ceil(sizeUsd * 1.1);
1314
+ try {
1315
+ const xferResult = await ltSpot.transferUsdcToSpot(transferAmt);
1316
+ if (!isJson())
1317
+ console.log(chalk.gray(` Transferred $${transferAmt} USDC perp→spot on Lighter`));
1318
+ await new Promise(r => setTimeout(r, 300));
1319
+ }
1320
+ catch (e) {
1321
+ const msg = e instanceof Error ? e.message : String(e);
1322
+ if (!isJson())
1323
+ console.log(chalk.yellow(` USDC transfer warning: ${msg}`));
1324
+ // Continue — spot order may still work if spot balance already exists
1325
+ }
1326
+ }
1327
+ // 2b. Verify spot USDC balance is sufficient after transfer
1328
+ try {
1329
+ const spotBalances = await spotAdapter.getSpotBalances();
1330
+ const spotUsdc = spotBalances.find(b => b.token === "USDC_SPOT" || b.token === "USDC");
1331
+ const spotUsdcAvail = Number(spotUsdc?.available ?? 0);
1332
+ // Also check perp balance for the perp leg
1333
+ const perpBalance = await perpAdapter.getBalance();
1334
+ const perpAvail = Number(perpBalance?.available ?? 0);
1335
+ if (spotUsdcAvail < sizeUsd * 0.9) {
1336
+ const msg = `Insufficient spot USDC: have $${spotUsdcAvail.toFixed(2)}, need ~$${sizeUsd}. Transfer may have failed.`;
1337
+ if (isJson())
1338
+ return printJson(jsonOk({ error: msg, spotUsdcAvail, required: sizeUsd }));
1339
+ console.log(chalk.red(` ${msg}`));
1340
+ return;
1341
+ }
1342
+ if (perpAvail < sizeUsd * 0.5) {
1343
+ const msg = `Insufficient perp balance: have $${perpAvail.toFixed(2)} available on ${perpExch}, need margin for ~$${sizeUsd}`;
1344
+ if (isJson())
1345
+ return printJson(jsonOk({ error: msg, perpAvail, required: sizeUsd }));
1346
+ console.log(chalk.red(` ${msg}`));
1347
+ return;
1348
+ }
1349
+ }
1350
+ catch {
1351
+ // Balance check failed — continue with execution, let order placement catch errors
1352
+ }
1353
+ // 3. Fetch orderbooks simultaneously
1354
+ const spotSymbol = `${sym}/USDC`;
1355
+ if (!isJson())
1356
+ console.log(chalk.gray(` Checking orderbook depth (spot ${spotExch} + perp ${perpExch})...`));
1357
+ const [spotBook, perpBook] = await Promise.all([
1358
+ spotAdapter.getSpotOrderbook(spotSymbol),
1359
+ perpAdapter.getOrderbook(sym),
1360
+ ]);
1361
+ // 3a. Price cross-validation: verify spot and perp are the same underlying
1362
+ // Prevents wrong-token trades if index mapping is incorrect
1363
+ const spotMid = spotBook.bids.length > 0 && spotBook.asks.length > 0
1364
+ ? (Number(spotBook.bids[0][0]) + Number(spotBook.asks[0][0])) / 2 : 0;
1365
+ const perpMid = perpBook.bids.length > 0 && perpBook.asks.length > 0
1366
+ ? (Number(perpBook.bids[0][0]) + Number(perpBook.asks[0][0])) / 2 : 0;
1367
+ if (spotMid > 0 && perpMid > 0) {
1368
+ const priceDeviation = Math.abs(spotMid - perpMid) / perpMid * 100;
1369
+ if (priceDeviation > 5) {
1370
+ const msg = `Price mismatch: spot mid $${spotMid.toFixed(4)} vs perp mid $${perpMid.toFixed(4)} (${priceDeviation.toFixed(1)}% deviation). Possible wrong token index — aborting.`;
1371
+ if (isJson())
1372
+ return printJson(jsonOk({ error: msg, spotMid, perpMid, deviationPct: priceDeviation }));
1373
+ console.log(chalk.red(`\n ${msg}`));
1374
+ return;
1375
+ }
1376
+ }
1377
+ else if (spotMid === 0) {
1378
+ const msg = `Empty spot orderbook for ${sym} — cannot verify token identity`;
1379
+ if (isJson())
1380
+ return printJson(jsonOk({ error: msg }));
1381
+ console.log(chalk.red(`\n ${msg}`));
1382
+ return;
1383
+ }
1384
+ // 3b. Validate depth
1385
+ const spotCheck = computeExecutableSize(spotBook.asks, sizeUsd, maxSlippage);
1386
+ const perpCheck = computeExecutableSize(perpBook.bids, sizeUsd, maxSlippage);
1387
+ if (!spotCheck.canFillFull || !perpCheck.canFillFull) {
1388
+ const fillableUsd = Math.min(spotCheck.maxSize * spotCheck.avgFillPrice, perpCheck.maxSize * perpCheck.avgFillPrice);
1389
+ if (isJson())
1390
+ return printJson(jsonOk({
1391
+ error: "Insufficient orderbook depth",
1392
+ requestedUsd: sizeUsd, fillableUsd: Math.round(fillableUsd * 100) / 100,
1393
+ spot: { exchange: spotExch, depthUsd: spotCheck.depthUsd, canFill: spotCheck.canFillFull },
1394
+ perp: { exchange: perpExch, depthUsd: perpCheck.depthUsd, canFill: perpCheck.canFillFull },
1395
+ }));
1396
+ console.log(chalk.red(`\n Insufficient depth for $${sizeUsd}:`));
1397
+ console.log(chalk.gray(` ${spotExch} spot asks: $${spotCheck.depthUsd.toFixed(0)}`));
1398
+ console.log(chalk.gray(` ${perpExch} perp bids: $${perpCheck.depthUsd.toFixed(0)}`));
1399
+ return;
1400
+ }
1401
+ // 4. Compute matched size
1402
+ const inferDecimals = (levels) => {
1403
+ for (const [, s] of levels) {
1404
+ const dot = s.indexOf(".");
1405
+ if (dot >= 0)
1406
+ return s.length - dot - 1;
1407
+ }
1408
+ return 0;
1409
+ };
1410
+ const spotDecimals = inferDecimals(spotBook.asks);
1411
+ const perpDecimals = inferDecimals(perpBook.bids);
1412
+ const decimals = Math.min(spotDecimals, perpDecimals);
1413
+ const matchedBase = Math.min(spotCheck.recommendedSize, perpCheck.recommendedSize);
1414
+ const matchedSize = (Math.floor(matchedBase * 10 ** decimals) / 10 ** decimals).toFixed(decimals);
1415
+ const avgPrice = (spotCheck.avgFillPrice + perpCheck.avgFillPrice) / 2;
1416
+ const matchedUsd = matchedBase * avgPrice;
1417
+ if (!isJson()) {
1418
+ console.log(chalk.cyan(`\n Spot+Perp Arb: ${sym}`));
1419
+ console.log(chalk.gray(` SPOT ${spotExch}: buy ${matchedSize} (~$${(matchedBase * spotCheck.avgFillPrice).toFixed(2)})`));
1420
+ console.log(chalk.gray(` PERP ${perpExch}: sell ${matchedSize} (~$${(matchedBase * perpCheck.avgFillPrice).toFixed(2)})`));
1421
+ console.log(chalk.gray(` Executing both legs simultaneously...\n`));
1422
+ }
1423
+ // 5. Execute both legs (or return dry-run result)
1424
+ if (dryRun) {
1425
+ const result = {
1426
+ status: "filled", mode: "spot-perp", symbol: sym, dryRun: true,
1427
+ size: matchedSize, notionalUsd: Math.round(matchedUsd * 100) / 100,
1428
+ spot: { exchange: spotExch, side: "buy", size: matchedSize },
1429
+ perp: { exchange: perpExch, side: "sell", size: matchedSize },
1430
+ };
1431
+ if (isJson())
1432
+ return printJson(jsonOk(result));
1433
+ console.log(chalk.cyan(` [DRY-RUN] Would execute: spot buy ${matchedSize} on ${spotExch} + perp sell ${matchedSize} on ${perpExch}`));
1434
+ return;
1435
+ }
1436
+ // Same exchange (e.g. Lighter) shares nonce → must execute sequentially
1437
+ // Different exchanges → execute simultaneously for speed
1438
+ const validatePerpFill = (r) => {
1439
+ const res = r;
1440
+ const statuses = res?.response?.data?.statuses;
1441
+ if (statuses && statuses.length > 0) {
1442
+ const st = statuses[0];
1443
+ if (st.error)
1444
+ throw new Error(`Perp sell ${sym}: ${st.error}`);
1445
+ const filled = st.filled;
1446
+ if (filled && Number(filled.totalSz ?? 0) === 0) {
1447
+ throw new Error(`Perp sell ${sym}: 0 fill`);
1448
+ }
1449
+ }
1450
+ return r;
1451
+ };
1452
+ let spotResult;
1453
+ let perpResult;
1454
+ if (spotExch === perpExch) {
1455
+ // Sequential: spot first, then perp (avoids nonce collision on same exchange)
1456
+ spotResult = await spotAdapter.spotMarketOrder(spotSymbol, "buy", matchedSize)
1457
+ .then(r => ({ status: "fulfilled", value: r }))
1458
+ .catch(e => ({ status: "rejected", reason: e }));
1459
+ if (spotResult.status === "fulfilled") {
1460
+ perpResult = await perpAdapter.marketOrder(sym, "sell", matchedSize)
1461
+ .then(validatePerpFill)
1462
+ .then(r => ({ status: "fulfilled", value: r }))
1463
+ .catch(e => ({ status: "rejected", reason: e }));
1464
+ }
1465
+ else {
1466
+ perpResult = { status: "rejected", reason: new Error("Skipped: spot failed") };
1467
+ }
1468
+ }
1469
+ else {
1470
+ // Parallel: different exchanges, no nonce conflict
1471
+ [spotResult, perpResult] = await Promise.allSettled([
1472
+ spotAdapter.spotMarketOrder(spotSymbol, "buy", matchedSize),
1473
+ perpAdapter.marketOrder(sym, "sell", matchedSize).then(validatePerpFill),
1474
+ ]);
1475
+ }
1476
+ const spotOk = spotResult.status === "fulfilled";
1477
+ const perpOk = perpResult.status === "fulfilled";
1478
+ if (spotOk && perpOk) {
1479
+ // ── Post-execution fill verification ──
1480
+ // Wait for exchange state to settle, then verify both legs actually filled
1481
+ let fillVerified = true;
1482
+ let verifyWarnings = [];
1483
+ try {
1484
+ await new Promise(r => setTimeout(r, 800));
1485
+ // Verify spot: check base token balance appeared
1486
+ const spotBals = await spotAdapter.getSpotBalances();
1487
+ const baseToken = sym; // e.g. "ETH"
1488
+ const spotTokenBal = spotBals.find(b => b.token.toUpperCase().startsWith(baseToken));
1489
+ const spotTokenAmt = Number(spotTokenBal?.total ?? 0);
1490
+ const expectedSize = parseFloat(matchedSize);
1491
+ if (spotTokenAmt < expectedSize * 0.5) {
1492
+ fillVerified = false;
1493
+ verifyWarnings.push(`Spot buy may not have filled: expected ~${matchedSize} ${baseToken}, found ${spotTokenAmt.toFixed(6)}`);
1494
+ }
1495
+ // Verify perp: check short position exists
1496
+ const perpPositions = await perpAdapter.getPositions();
1497
+ const perpPos = perpPositions.find(p => p.symbol.replace("-PERP", "").toUpperCase() === sym && p.side === "short");
1498
+ if (!perpPos) {
1499
+ fillVerified = false;
1500
+ verifyWarnings.push(`Perp short position not found for ${sym} on ${perpExch} — fill may not have executed`);
1501
+ }
1502
+ else if (Number(perpPos.size) < expectedSize * 0.5) {
1503
+ verifyWarnings.push(`Perp short size ${perpPos.size} < expected ${matchedSize} — partial fill?`);
1504
+ }
1505
+ }
1506
+ catch (verifyErr) {
1507
+ // Verification check itself failed — log but don't block
1508
+ verifyWarnings.push(`Fill verification check failed: ${verifyErr instanceof Error ? verifyErr.message : String(verifyErr)}`);
1509
+ }
1510
+ if (verifyWarnings.length > 0 && !isJson()) {
1511
+ for (const w of verifyWarnings) {
1512
+ console.log(chalk.yellow(` ⚠ ${w}`));
1513
+ }
1514
+ }
1515
+ if (!fillVerified) {
1516
+ // Fills couldn't be confirmed — log as unverified but still persist
1517
+ // (rolling back based on uncertain data is worse than persisting)
1518
+ logExecution({
1519
+ type: "arb_entry", exchange: `spot:${spotExch}+${perpExch}`,
1520
+ symbol: sym, side: "entry", size: matchedSize,
1521
+ status: "unverified", dryRun: false,
1522
+ meta: { mode: "spot-perp", spotExch, perpExch, matchedUsd, warnings: verifyWarnings },
1523
+ });
1524
+ }
1525
+ else {
1526
+ // Log execution — verified
1527
+ logExecution({
1528
+ type: "arb_entry", exchange: `spot:${spotExch}+${perpExch}`,
1529
+ symbol: sym, side: "entry", size: matchedSize,
1530
+ status: "success", dryRun: false,
1531
+ meta: { mode: "spot-perp", spotExch, perpExch, matchedUsd },
1532
+ });
1533
+ }
1534
+ // Persist position state
1535
+ persistAddPosition({
1536
+ id: `${sym}-spot-${Date.now()}`,
1537
+ symbol: sym,
1538
+ longExchange: spotExch,
1539
+ shortExchange: perpExch,
1540
+ longSize: parseFloat(matchedSize),
1541
+ shortSize: parseFloat(matchedSize),
1542
+ entryTime: new Date().toISOString(),
1543
+ entrySpread: 0, // Will be updated on next scan
1544
+ entryLongPrice: spotCheck.avgFillPrice,
1545
+ entryShortPrice: perpCheck.avgFillPrice,
1546
+ accumulatedFunding: 0,
1547
+ lastCheckTime: new Date().toISOString(),
1548
+ mode: "spot-perp",
1549
+ spotExchange: spotExch,
1550
+ spotSymbol: spotSymbol,
1551
+ });
1552
+ // Return leftover USDC from spot back to perp (non-unified HL accounts)
1553
+ if (spotExch === "hyperliquid") {
1554
+ try {
1555
+ const hlSpot = spotAdapter;
1556
+ const bals = await hlSpot.getSpotBalances();
1557
+ const usdcBal = bals.find(b => b.token.startsWith("USDC"));
1558
+ const leftover = Number(usdcBal?.available ?? 0);
1559
+ if (leftover > 1) {
1560
+ const xfer = await hlSpot.transferUsdcToPerp(Math.floor(leftover));
1561
+ if (xfer?.status !== "err") {
1562
+ if (!isJson())
1563
+ console.log(chalk.gray(` Returned ~$${Math.floor(leftover)} USDC to perp account`));
1564
+ }
1565
+ }
1566
+ }
1567
+ catch { /* non-critical — unified accounts don't need transfer */ }
1568
+ }
1569
+ const result = {
1570
+ status: fillVerified ? "filled" : "filled_unverified",
1571
+ mode: "spot-perp", symbol: sym,
1572
+ size: matchedSize, notionalUsd: Math.round(matchedUsd * 100) / 100,
1573
+ spot: { exchange: spotExch, side: "buy", size: matchedSize },
1574
+ perp: { exchange: perpExch, side: "sell", size: matchedSize },
1575
+ ...(verifyWarnings.length > 0 && { warnings: verifyWarnings }),
1576
+ };
1577
+ if (isJson())
1578
+ return printJson(jsonOk(result));
1579
+ if (fillVerified) {
1580
+ console.log(chalk.green(` FILLED (verified): ${sym} ${matchedSize} units (~$${matchedUsd.toFixed(2)})`));
1581
+ }
1582
+ else {
1583
+ console.log(chalk.yellow(` FILLED (unverified): ${sym} ${matchedSize} units (~$${matchedUsd.toFixed(2)})`));
1584
+ }
1585
+ console.log(chalk.green(` SPOT ${spotExch} ✓ (bought ${matchedSize})`));
1586
+ console.log(chalk.green(` PERP ${perpExch} ✓ (shorted ${matchedSize})\n`));
1587
+ }
1588
+ else if (spotOk !== perpOk) {
1589
+ // One leg failed — rollback
1590
+ const filledSide = spotOk ? "spot" : "perp";
1591
+ const failedSide = spotOk ? "perp" : "spot";
1592
+ const failedErr = spotOk
1593
+ ? perpResult.reason
1594
+ : spotResult.reason;
1595
+ const failedErrMsg = failedErr instanceof Error ? failedErr.message : String(failedErr);
1596
+ if (!isJson()) {
1597
+ console.log(chalk.yellow(` PARTIAL: ${filledSide} OK, ${failedSide} FAILED — rolling back...`));
1598
+ console.log(chalk.red(` Reason: ${failedErrMsg}`));
1599
+ }
1600
+ let rollbackOk = false;
1601
+ for (let attempt = 1; attempt <= 2; attempt++) {
1602
+ try {
1603
+ if (spotOk) {
1604
+ await spotAdapter.spotMarketOrder(spotSymbol, "sell", matchedSize);
1605
+ }
1606
+ else {
1607
+ await perpAdapter.marketOrder(sym, "buy", matchedSize);
1608
+ }
1609
+ rollbackOk = true;
1610
+ break;
1611
+ }
1612
+ catch { /* retry */ }
1613
+ }
1614
+ logExecution({
1615
+ type: "arb_entry", exchange: `spot:${spotExch}+${perpExch}`,
1616
+ symbol: sym, side: "entry", size: matchedSize,
1617
+ status: "failed", dryRun: false,
1618
+ error: `Partial: ${failedSide} failed (${failedErrMsg}). Rollback: ${rollbackOk ? "ok" : "FAILED"}`,
1619
+ });
1620
+ const result = {
1621
+ status: "partial_fill", mode: "spot-perp", symbol: sym,
1622
+ filledSide, failedSide,
1623
+ failedError: failedErrMsg,
1624
+ rollback: rollbackOk ? "success" : "FAILED — MANUAL CLOSE REQUIRED",
1625
+ };
1626
+ if (isJson())
1627
+ return printJson(jsonOk(result));
1628
+ console.log(rollbackOk
1629
+ ? chalk.yellow(` Rollback OK — no open exposure.\n`)
1630
+ : chalk.red.bold(` ROLLBACK FAILED — ${filledSide} leg still open. Close manually!\n`));
1631
+ }
1632
+ else {
1633
+ // Both failed
1634
+ const spotErr = spotResult.reason;
1635
+ const perpErr = perpResult.reason;
1636
+ const result = {
1637
+ status: "both_failed", mode: "spot-perp", symbol: sym,
1638
+ spotError: spotErr instanceof Error ? spotErr.message : String(spotErr),
1639
+ perpError: perpErr instanceof Error ? perpErr.message : String(perpErr),
1640
+ };
1641
+ if (isJson())
1642
+ return printJson(jsonOk(result));
1643
+ console.log(chalk.red(` Both legs failed:`));
1644
+ console.log(chalk.red(` SPOT: ${result.spotError}`));
1645
+ console.log(chalk.red(` PERP: ${result.perpError}\n`));
1646
+ }
1647
+ });
1648
+ // ── arb spot-close ── (close spot+perp arb position)
1649
+ arb
1650
+ .command("spot-close")
1651
+ .description("Close a spot+perp arb position: sell spot + buy back perp")
1652
+ .argument("<symbol>", "Symbol (e.g. ETH)")
1653
+ .option("--spot-exch <exchange>", "Spot exchange (hl or lt)")
1654
+ .option("--perp-exch <exchange>", "Perp exchange (hl, lt, pac)")
1655
+ .action(async (symbol, opts) => {
1656
+ const sym = symbol.toUpperCase();
1657
+ // Try to find the position from state
1658
+ const state = loadArbState();
1659
+ const pos = state?.positions.find(p => p.symbol.toUpperCase() === sym && p.mode === "spot-perp");
1660
+ const aliasMap = { hl: "hyperliquid", pac: "pacifica", lt: "lighter" };
1661
+ const spotExch = aliasMap[opts.spotExch?.toLowerCase() ?? ""] || opts.spotExch?.toLowerCase() || pos?.spotExchange || pos?.longExchange;
1662
+ const perpExch = aliasMap[opts.perpExch?.toLowerCase() ?? ""] || opts.perpExch?.toLowerCase() || pos?.shortExchange;
1663
+ if (!spotExch || !perpExch) {
1664
+ const msg = "Cannot determine exchanges. Specify --spot-exch and --perp-exch, or ensure the position is tracked in state.";
1665
+ if (isJson())
1666
+ return printJson(jsonOk({ error: msg }));
1667
+ console.log(chalk.red(` ${msg}`));
1668
+ return;
1669
+ }
1670
+ // Load adapters
1671
+ const { HyperliquidSpotAdapter } = await import("../exchanges/hyperliquid-spot.js");
1672
+ const { LighterSpotAdapter } = await import("../exchanges/lighter-spot.js");
1673
+ let spotAdapter;
1674
+ if (spotExch === "hyperliquid") {
1675
+ const hlAdapter = await getAdapterForExchange("hyperliquid");
1676
+ const hlSpot = new HyperliquidSpotAdapter(hlAdapter);
1677
+ await hlSpot.init();
1678
+ spotAdapter = hlSpot;
1679
+ }
1680
+ else {
1681
+ const ltAdapter = await getAdapterForExchange("lighter");
1682
+ const ltSpot = new LighterSpotAdapter(ltAdapter);
1683
+ await ltSpot.init();
1684
+ spotAdapter = ltSpot;
1685
+ }
1686
+ const perpAdapter = await getAdapterForExchange(perpExch);
1687
+ const spotSymbol = `${sym}/USDC`;
1688
+ // Find how much to close
1689
+ const perpPositions = await perpAdapter.getPositions();
1690
+ const perpPos = perpPositions.find(p => p.symbol.replace("-PERP", "").toUpperCase() === sym && p.side === "short");
1691
+ if (!perpPos) {
1692
+ const msg = `No short perp position found for ${sym} on ${perpExch}`;
1693
+ if (isJson())
1694
+ return printJson(jsonOk({ error: msg }));
1695
+ console.log(chalk.red(` ${msg}`));
1696
+ return;
1697
+ }
1698
+ const closeSize = perpPos.size;
1699
+ if (!isJson()) {
1700
+ console.log(chalk.cyan(`\n Closing Spot+Perp Arb: ${sym}`));
1701
+ console.log(chalk.gray(` SPOT ${spotExch}: sell ${closeSize}`));
1702
+ console.log(chalk.gray(` PERP ${perpExch}: buy ${closeSize} (close short)`));
1703
+ console.log(chalk.gray(` Executing...\n`));
1704
+ }
1705
+ // Same exchange → sequential (nonce collision), different → parallel
1706
+ let spotResult;
1707
+ let perpResult;
1708
+ if (spotExch === perpExch) {
1709
+ // Sequential: sell spot first, then close perp
1710
+ spotResult = await spotAdapter.spotMarketOrder(spotSymbol, "sell", closeSize)
1711
+ .then(r => ({ status: "fulfilled", value: r }))
1712
+ .catch(e => ({ status: "rejected", reason: e }));
1713
+ perpResult = await perpAdapter.marketOrder(sym, "buy", closeSize)
1714
+ .then(r => ({ status: "fulfilled", value: r }))
1715
+ .catch(e => ({ status: "rejected", reason: e }));
1716
+ }
1717
+ else {
1718
+ [spotResult, perpResult] = await Promise.allSettled([
1719
+ spotAdapter.spotMarketOrder(spotSymbol, "sell", closeSize),
1720
+ perpAdapter.marketOrder(sym, "buy", closeSize),
1721
+ ]);
1722
+ }
1723
+ const spotOk = spotResult.status === "fulfilled";
1724
+ const perpOk = perpResult.status === "fulfilled";
1725
+ if (spotOk && perpOk) {
1726
+ // ── Post-close fill verification ──
1727
+ let closeVerified = true;
1728
+ let closeWarnings = [];
1729
+ try {
1730
+ await new Promise(r => setTimeout(r, 800));
1731
+ // Verify spot token was sold (balance should be near zero or gone)
1732
+ const spotBals = await spotAdapter.getSpotBalances();
1733
+ const baseToken = sym;
1734
+ const spotTokenBal = spotBals.find(b => b.token.toUpperCase().startsWith(baseToken));
1735
+ const remainingSpotAmt = Number(spotTokenBal?.total ?? 0);
1736
+ const closedSize = parseFloat(closeSize);
1737
+ if (remainingSpotAmt > closedSize * 0.5) {
1738
+ closeVerified = false;
1739
+ closeWarnings.push(`Spot sell may not have filled: still have ${remainingSpotAmt.toFixed(6)} ${baseToken} (expected ~0)`);
1740
+ }
1741
+ // Verify perp short was closed (position should be gone or reduced)
1742
+ const perpPositionsAfter = await perpAdapter.getPositions();
1743
+ const remainingPerpPos = perpPositionsAfter.find(p => p.symbol.replace("-PERP", "").toUpperCase() === sym && p.side === "short");
1744
+ if (remainingPerpPos && Number(remainingPerpPos.size) > closedSize * 0.5) {
1745
+ closeVerified = false;
1746
+ closeWarnings.push(`Perp short still open: ${remainingPerpPos.size} ${sym} on ${perpExch} (expected closed)`);
1747
+ }
1748
+ }
1749
+ catch (verifyErr) {
1750
+ closeWarnings.push(`Close verification failed: ${verifyErr instanceof Error ? verifyErr.message : String(verifyErr)}`);
1751
+ }
1752
+ if (closeWarnings.length > 0 && !isJson()) {
1753
+ for (const w of closeWarnings) {
1754
+ console.log(chalk.yellow(` ⚠ ${w}`));
1755
+ }
1756
+ }
1757
+ // Remove from state
1758
+ persistRemovePosition(sym);
1759
+ logExecution({
1760
+ type: "arb_close", exchange: `spot:${spotExch}+${perpExch}`,
1761
+ symbol: sym, side: "exit", size: closeSize,
1762
+ status: closeVerified ? "success" : "unverified", dryRun: false,
1763
+ meta: { mode: "spot-perp", ...(closeWarnings.length > 0 && { warnings: closeWarnings }) },
1764
+ });
1765
+ // Return spot USDC proceeds back to perp account
1766
+ if (spotExch === "lighter") {
1767
+ try {
1768
+ const ltSpot = spotAdapter;
1769
+ const bals = await ltSpot.getSpotBalances();
1770
+ const usdcBal = bals.find(b => b.token === "USDC");
1771
+ const leftover = Number(usdcBal?.available ?? 0);
1772
+ if (leftover > 0.01) {
1773
+ await ltSpot.transferUsdcToPerp(leftover);
1774
+ if (!isJson())
1775
+ console.log(chalk.gray(` Returned ~$${leftover.toFixed(2)} USDC spot→perp on Lighter`));
1776
+ }
1777
+ }
1778
+ catch { /* non-critical */ }
1779
+ }
1780
+ else if (spotExch === "hyperliquid") {
1781
+ try {
1782
+ const hlSpot = spotAdapter;
1783
+ const bals = await hlSpot.getSpotBalances();
1784
+ const usdcBal = bals.find(b => b.token.startsWith("USDC"));
1785
+ const leftover = Number(usdcBal?.available ?? 0);
1786
+ if (leftover > 1) {
1787
+ await hlSpot.transferUsdcToPerp(Math.floor(leftover));
1788
+ }
1789
+ }
1790
+ catch { /* non-critical */ }
1791
+ }
1792
+ const closeResult = {
1793
+ status: closeVerified ? "closed" : "closed_unverified",
1794
+ mode: "spot-perp", symbol: sym, size: closeSize,
1795
+ ...(closeWarnings.length > 0 && { warnings: closeWarnings }),
1796
+ };
1797
+ if (isJson())
1798
+ return printJson(jsonOk(closeResult));
1799
+ if (closeVerified) {
1800
+ console.log(chalk.green(` CLOSED (verified): ${sym} ${closeSize} units`));
1801
+ }
1802
+ else {
1803
+ console.log(chalk.yellow(` CLOSED (unverified): ${sym} ${closeSize} units — check positions manually`));
1804
+ }
1805
+ console.log(chalk.green(` SPOT ${spotExch}: sold ✓`));
1806
+ console.log(chalk.green(` PERP ${perpExch}: bought (closed short) ✓\n`));
1807
+ }
1808
+ else {
1809
+ const errors = [];
1810
+ if (!spotOk)
1811
+ errors.push(`Spot sell failed: ${spotResult.reason}`);
1812
+ if (!perpOk)
1813
+ errors.push(`Perp buy failed: ${perpResult.reason}`);
1814
+ const result = { status: "partial_close", symbol: sym, spotOk, perpOk, errors };
1815
+ if (isJson())
1816
+ return printJson(jsonOk(result));
1817
+ console.log(chalk.red(` Close partially failed:`));
1818
+ for (const e of errors)
1819
+ console.log(chalk.red(` ${e}`));
1820
+ console.log(chalk.yellow(` Manual intervention may be needed.\n`));
1821
+ }
1822
+ });
1184
1823
  // ── arb pnl ── (check arb position PnL)
1185
1824
  arb
1186
1825
  .command("pnl")