perp-cli 0.4.8 → 0.4.10

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 (45) hide show
  1. package/README.md +44 -5
  2. package/dist/arb/reconcile.d.ts +28 -0
  3. package/dist/arb/reconcile.js +162 -0
  4. package/dist/commands/account.d.ts +1 -1
  5. package/dist/commands/account.js +366 -62
  6. package/dist/commands/agent.js +9 -5
  7. package/dist/commands/arb/index.js +243 -49
  8. package/dist/commands/arb-auto.js +67 -19
  9. package/dist/commands/arb.d.ts +2 -1
  10. package/dist/commands/arb.js +535 -131
  11. package/dist/commands/bot.js +207 -0
  12. package/dist/commands/funds.d.ts +4 -0
  13. package/dist/commands/funds.js +741 -0
  14. package/dist/commands/history.d.ts +2 -1
  15. package/dist/commands/history.js +508 -5
  16. package/dist/commands/manage.js +5 -3
  17. package/dist/commands/market.js +34 -1
  18. package/dist/commands/pnl.js +1 -1
  19. package/dist/commands/risk.d.ts +2 -0
  20. package/dist/commands/risk.js +56 -0
  21. package/dist/commands/settings.js +147 -0
  22. package/dist/commands/trade.d.ts +1 -1
  23. package/dist/commands/trade.js +241 -259
  24. package/dist/commands/wallet.d.ts +4 -0
  25. package/dist/commands/wallet.js +10 -0
  26. package/dist/config.d.ts +2 -2
  27. package/dist/config.js +11 -3
  28. package/dist/exchanges/hyperliquid-spot.d.ts +1 -0
  29. package/dist/exchanges/hyperliquid-spot.js +13 -21
  30. package/dist/exchanges/lighter-spot.js +13 -15
  31. package/dist/exchanges/lighter.js +82 -21
  32. package/dist/exchanges/pacifica.js +12 -0
  33. package/dist/execution-log.d.ts +1 -1
  34. package/dist/index.js +39 -123
  35. package/dist/mcp-server.js +43 -96
  36. package/dist/strategies/split-order.d.ts +49 -0
  37. package/dist/strategies/split-order.js +138 -0
  38. package/package.json +1 -1
  39. package/skills/perp-cli/SKILL.md +13 -26
  40. package/skills/perp-cli/references/agent-operations.md +19 -9
  41. package/skills/perp-cli/references/commands.md +38 -31
  42. package/skills/perp-cli/references/strategies.md +26 -16
  43. package/skills/perp-cli/scripts/funding-analysis.sh +2 -2
  44. package/skills/perp-cli/scripts/preflight.sh +1 -1
  45. package/skills/perp-cli/scripts/spot-perp-scan.sh +1 -1
package/README.md CHANGED
@@ -13,9 +13,10 @@ npx -y perp-cli --json portfolio
13
13
  ## Features
14
14
 
15
15
  - **3 Exchanges** — trade, bridge, arbitrage across Pacifica, Hyperliquid, Lighter
16
- - **Funding Rate Arb** — scan spreads + one-command dual-leg execution (`arb exec`)
16
+ - **Funding Rate Arb** — perp-perp + spot-perp scan & one-command dual-leg execution
17
17
  - **Portfolio** — single call returns balances, positions, risk level across all exchanges
18
- - **CCTP V2 Bridge** — $0 fee USDC bridging (Solana, Arbitrum, Base)
18
+ - **Funds** — deposit, withdraw, CCTP bridge, internal transfer in one group
19
+ - **Bots** — TWAP, grid, DCA, trailing-stop with background job management
19
20
  - **Agent-First Design** — `--json`, `--fields`, `--ndjson`, `--dry-run`, runtime schema introspection
20
21
  - **Safety** — pre-trade validation, response sanitization, client-id deduplication
21
22
 
@@ -35,6 +36,30 @@ Same EVM key works for both Hyperliquid and Lighter.
35
36
 
36
37
  > **Lighter API Key Index:** Indexes 0–3 are reserved by Lighter's frontend (web/mobile). perp-cli defaults to index `4`. Override with `LIGHTER_API_KEY_INDEX` env var or `--key-index` flag on `manage setup-api-key`. Valid range: 4–254.
37
38
 
39
+ ## Command Groups
40
+
41
+ | Group | Description |
42
+ |-------|-------------|
43
+ | `market` | Prices, orderbook, funding, klines, HIP-3 dexes |
44
+ | `account` | Balance, positions, orders, margin |
45
+ | `trade` | Market/limit/stop orders, close, scale, split execution |
46
+ | `arb` | Funding rate arb — scan, exec, close, monitor (perp-perp & spot-perp) |
47
+ | `bot` | TWAP, grid, DCA, trailing-stop bots |
48
+ | `funds` | Deposit, withdraw, transfer, CCTP bridge |
49
+ | `bridge` | Cross-chain USDC bridge (deBridge DLN) |
50
+ | `risk` | Risk limits, liquidation distance, guardrails |
51
+ | `wallet` | Multi-wallet management & on-chain balances |
52
+ | `history` | Execution log, PnL, performance breakdown |
53
+ | `manage` | Margin mode, subaccount, API keys, builder |
54
+ | `portfolio` | Cross-exchange unified overview |
55
+ | `dashboard` | Live web dashboard |
56
+ | `settings` | CLI settings (referrals, defaults) |
57
+ | `backtest` | Strategy backtesting |
58
+ | `plan` | Multi-step composite execution plans |
59
+ | `rebalance` | Cross-exchange balance management |
60
+ | `jobs` | Background job management (tmux) |
61
+ | `agent` | Schema introspection, capabilities, health check |
62
+
38
63
  ## Core Commands
39
64
 
40
65
  ```bash
@@ -48,18 +73,32 @@ perp --json -e <EX> market funding <SYM>
48
73
 
49
74
  # Trading
50
75
  perp --json -e <EX> trade market <SYM> buy <SIZE>
76
+ perp --json -e <EX> trade market <SYM> buy <SIZE> --smart # IOC limit at best bid/ask (less slippage)
77
+ perp --json -e <EX> trade split <SYM> buy 5000 # orderbook-aware split (large orders)
51
78
  perp --json -e <EX> trade close <SYM>
52
79
  perp --json -e <EX> trade leverage <SYM> <N>
53
80
 
54
81
  # Funding rate arbitrage
55
- perp --json arb scan --min 5 # find opportunities
82
+ perp --json arb scan --min 5 # perp-perp opportunities
83
+ perp --json arb scan --mode spot-perp # spot+perp opportunities
56
84
  perp --json arb exec <SYM> <longEx> <shortEx> <$> --leverage 2 --isolated # execute both legs
85
+ perp --json arb spot-exec <SYM> <spotEx> <perpEx> <$> # spot+perp entry
86
+
87
+ # Funds (deposit, withdraw, transfer)
88
+ perp --json funds deposit hyperliquid 100
89
+ perp --json funds withdraw pacifica 50
90
+ perp --json funds transfer 100 <ADDRESS> # HL internal transfer
91
+ perp --json funds info # all routes & limits
57
92
 
58
93
  # Risk
59
94
  perp --json risk limits --max-leverage 5
60
95
  perp --json risk liquidation-distance
61
96
 
62
- # Bridge
97
+ # Bots
98
+ perp --json bot twap <SYM> buy <SIZE> 30m
99
+ perp --json bot grid <SYM> --range 5 --grids 10 --size 100
100
+
101
+ # Bridge (cross-chain USDC)
63
102
  perp --json bridge quote --from solana --to arbitrum --amount 100
64
103
  perp --json bridge send --from solana --to arbitrum --amount 100
65
104
  ```
@@ -92,7 +131,7 @@ perp --json portfolio
92
131
  # Runtime schema introspection (don't guess commands — query this)
93
132
  perp --json agent schema
94
133
 
95
- # Filter output to save tokens
134
+ # Filter output to specific fields (saves tokens)
96
135
  perp --json --fields totalEquity,risk portfolio
97
136
 
98
137
  # Stream large lists as NDJSON (one JSON per line)
@@ -0,0 +1,28 @@
1
+ import type { ExchangeAdapter } from "../exchanges/interface.js";
2
+ export interface ReconciliationIssue {
3
+ type: "orphan" | "phantom" | "size_mismatch";
4
+ symbol: string;
5
+ exchange: string;
6
+ side: "long" | "short";
7
+ localSize: number | null;
8
+ exchangeSize: number | null;
9
+ severity: "warning" | "critical";
10
+ suggestion: string;
11
+ }
12
+ export interface ReconciliationResult {
13
+ issues: ReconciliationIssue[];
14
+ healthy: number;
15
+ fixesApplied?: string[];
16
+ }
17
+ /**
18
+ * Reconcile local arb state with actual exchange positions.
19
+ *
20
+ * Detects three types of issues:
21
+ * - **Orphan**: Position exists on exchange but not in local arb state (manual entry?)
22
+ * - **Phantom**: Position exists in local state but not on exchange (liquidated? manually closed?)
23
+ * - **Size mismatch**: Both exist but sizes differ beyond tolerance
24
+ */
25
+ export declare function reconcileArbPositions(adapters: Map<string, ExchangeAdapter>, opts?: {
26
+ fix?: boolean;
27
+ tolerancePct?: number;
28
+ }): Promise<ReconciliationResult>;
@@ -0,0 +1,162 @@
1
+ import { getPositions, removePosition, updatePosition } from "./state.js";
2
+ /** Normalize symbol for comparison (strip -PERP suffix, uppercase) */
3
+ function normalizeSymbol(symbol) {
4
+ return symbol.toUpperCase().replace(/-PERP$/, "");
5
+ }
6
+ /** Find a matching exchange position by symbol */
7
+ function findExchangePosition(positions, symbol, side) {
8
+ const norm = normalizeSymbol(symbol);
9
+ return positions.find(p => normalizeSymbol(p.symbol) === norm && p.side === side);
10
+ }
11
+ /**
12
+ * Reconcile local arb state with actual exchange positions.
13
+ *
14
+ * Detects three types of issues:
15
+ * - **Orphan**: Position exists on exchange but not in local arb state (manual entry?)
16
+ * - **Phantom**: Position exists in local state but not on exchange (liquidated? manually closed?)
17
+ * - **Size mismatch**: Both exist but sizes differ beyond tolerance
18
+ */
19
+ export async function reconcileArbPositions(adapters, opts) {
20
+ const tolerancePct = opts?.tolerancePct ?? 1;
21
+ const shouldFix = opts?.fix ?? false;
22
+ const issues = [];
23
+ const fixesApplied = [];
24
+ let healthy = 0;
25
+ const localPositions = getPositions();
26
+ // Fetch all exchange positions
27
+ const exchangePositions = new Map();
28
+ for (const [name, adapter] of adapters) {
29
+ try {
30
+ const pos = await adapter.getPositions();
31
+ exchangePositions.set(name, pos);
32
+ }
33
+ catch {
34
+ exchangePositions.set(name, []);
35
+ }
36
+ }
37
+ // Track which exchange positions are accounted for
38
+ const accountedFor = new Set(); // "exchange:symbol:side"
39
+ // Check each local arb position against exchange
40
+ for (const arb of localPositions) {
41
+ // Check long leg
42
+ const longPositions = exchangePositions.get(arb.longExchange) ?? [];
43
+ const longMatch = findExchangePosition(longPositions, arb.symbol, "long");
44
+ if (!longMatch) {
45
+ issues.push({
46
+ type: "phantom",
47
+ symbol: arb.symbol,
48
+ exchange: arb.longExchange,
49
+ side: "long",
50
+ localSize: arb.longSize,
51
+ exchangeSize: null,
52
+ severity: "critical",
53
+ suggestion: `Local state has long ${arb.symbol} on ${arb.longExchange} but exchange has no position. May have been liquidated or manually closed.`,
54
+ });
55
+ if (shouldFix) {
56
+ removePosition(arb.symbol);
57
+ fixesApplied.push(`Removed phantom position ${arb.symbol} (long leg missing on ${arb.longExchange})`);
58
+ continue; // Skip short leg check since we removed the position
59
+ }
60
+ }
61
+ else {
62
+ accountedFor.add(`${arb.longExchange}:${normalizeSymbol(arb.symbol)}:long`);
63
+ const exchangeSize = Math.abs(Number(longMatch.size));
64
+ const localSize = Math.abs(arb.longSize);
65
+ const diffPct = localSize > 0 ? (Math.abs(exchangeSize - localSize) / localSize) * 100 : 0;
66
+ if (diffPct > tolerancePct) {
67
+ issues.push({
68
+ type: "size_mismatch",
69
+ symbol: arb.symbol,
70
+ exchange: arb.longExchange,
71
+ side: "long",
72
+ localSize,
73
+ exchangeSize,
74
+ severity: "warning",
75
+ suggestion: `Long size mismatch: local ${localSize} vs exchange ${exchangeSize} (${diffPct.toFixed(1)}% diff). Partial fill or manual adjustment?`,
76
+ });
77
+ if (shouldFix) {
78
+ updatePosition(arb.symbol, { longSize: exchangeSize });
79
+ fixesApplied.push(`Updated ${arb.symbol} long size: ${localSize} → ${exchangeSize}`);
80
+ }
81
+ }
82
+ else {
83
+ healthy++;
84
+ }
85
+ }
86
+ // Check short leg
87
+ const shortPositions = exchangePositions.get(arb.shortExchange) ?? [];
88
+ const shortMatch = findExchangePosition(shortPositions, arb.symbol, "short");
89
+ if (!shortMatch) {
90
+ // Don't double-report if we already removed via fix
91
+ if (shouldFix && !getPositions().find(p => p.symbol === arb.symbol))
92
+ continue;
93
+ issues.push({
94
+ type: "phantom",
95
+ symbol: arb.symbol,
96
+ exchange: arb.shortExchange,
97
+ side: "short",
98
+ localSize: arb.shortSize,
99
+ exchangeSize: null,
100
+ severity: "critical",
101
+ suggestion: `Local state has short ${arb.symbol} on ${arb.shortExchange} but exchange has no position. May have been liquidated or manually closed.`,
102
+ });
103
+ if (shouldFix) {
104
+ removePosition(arb.symbol);
105
+ fixesApplied.push(`Removed phantom position ${arb.symbol} (short leg missing on ${arb.shortExchange})`);
106
+ }
107
+ }
108
+ else {
109
+ accountedFor.add(`${arb.shortExchange}:${normalizeSymbol(arb.symbol)}:short`);
110
+ const exchangeSize = Math.abs(Number(shortMatch.size));
111
+ const localSize = Math.abs(arb.shortSize);
112
+ const diffPct = localSize > 0 ? (Math.abs(exchangeSize - localSize) / localSize) * 100 : 0;
113
+ if (diffPct > tolerancePct) {
114
+ issues.push({
115
+ type: "size_mismatch",
116
+ symbol: arb.symbol,
117
+ exchange: arb.shortExchange,
118
+ side: "short",
119
+ localSize,
120
+ exchangeSize,
121
+ severity: "warning",
122
+ suggestion: `Short size mismatch: local ${localSize} vs exchange ${exchangeSize} (${diffPct.toFixed(1)}% diff). Partial fill or manual adjustment?`,
123
+ });
124
+ if (shouldFix) {
125
+ updatePosition(arb.symbol, { shortSize: exchangeSize });
126
+ fixesApplied.push(`Updated ${arb.symbol} short size: ${localSize} → ${exchangeSize}`);
127
+ }
128
+ }
129
+ else {
130
+ healthy++;
131
+ }
132
+ }
133
+ }
134
+ // Check for orphan positions (on exchange but not in local state)
135
+ for (const [exchangeName, positions] of exchangePositions) {
136
+ for (const pos of positions) {
137
+ const key = `${exchangeName}:${normalizeSymbol(pos.symbol)}:${pos.side}`;
138
+ if (!accountedFor.has(key)) {
139
+ // Check if this exchange is used in any arb position
140
+ const isArbExchange = localPositions.some(p => p.longExchange === exchangeName || p.shortExchange === exchangeName);
141
+ // Only report orphans on exchanges that are part of arb state
142
+ if (isArbExchange || localPositions.length > 0) {
143
+ issues.push({
144
+ type: "orphan",
145
+ symbol: pos.symbol,
146
+ exchange: exchangeName,
147
+ side: pos.side,
148
+ localSize: null,
149
+ exchangeSize: Math.abs(Number(pos.size)),
150
+ severity: "warning",
151
+ suggestion: `Position on ${exchangeName} not tracked in arb state. Manual entry or untracked strategy?`,
152
+ });
153
+ }
154
+ }
155
+ }
156
+ }
157
+ return {
158
+ issues,
159
+ healthy,
160
+ ...(fixesApplied.length > 0 ? { fixesApplied } : {}),
161
+ };
162
+ }
@@ -1,3 +1,3 @@
1
1
  import { Command } from "commander";
2
2
  import type { ExchangeAdapter } from "../exchanges/interface.js";
3
- export declare function registerAccountCommands(program: Command, getAdapter: () => Promise<ExchangeAdapter>, isJson: () => boolean): void;
3
+ export declare function registerAccountCommands(program: Command, getAdapter: () => Promise<ExchangeAdapter>, isJson: () => boolean, getAdapterForExchange?: (exchange: string) => Promise<ExchangeAdapter>): void;