diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6004a50..8e4a44e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -29,6 +29,17 @@ jobs: run: bun run build - name: Tests (unit + skills contract) + # Presence, not identity. src/common/Env.ts resolves PRIVY_APP_ID as + # `process.env.PRIVY_APP_ID ?? (IS_PRODUCTION ? : ensureString(...))`, + # so ANY non-empty value short-circuits the `??` and is returned unvalidated. + # Under vitest NODE_ENV is 'test', so IS_PRODUCTION is false and the + # ensureString branch threw at MODULE-IMPORT time, failing five suites during + # collection — before any in-test vi.stubEnv could run. Nothing here talks to + # Privy; the suites that do exercise it already stub their own fake ids. Plain + # env, deliberately NOT a secret: a real app id would be both unnecessary and + # a credential in CI. + env: + PRIVY_APP_ID: test-placeholder run: bunx vitest run - name: Skills release digest verification diff --git a/AGENTS.md b/AGENTS.md index de4777b..521c1cb 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -400,6 +400,7 @@ When you show an ETH or SOL address for a token, liquidity pool, or Hyperliquid - Hyperliquid perp: `[coin](https://tribes.xyz/perps/)` — e.g. `BTC`, `ETH`, `SOL`. + ## Shared-resource etiquette - This machine may share its host with other agents. Keep concurrency conservative and leave capacity for neighboring work. diff --git a/scalping-playbook.md b/scalping-playbook.md index 4d9afbd..4049538 100644 --- a/scalping-playbook.md +++ b/scalping-playbook.md @@ -31,9 +31,10 @@ tribes-cli ta indicators --candles-file /tmp/-5m.json --set ema,atr ``` **Indicator params:** + - **RSI(14)** — 1m candles -- **Bollinger Bands(20,2)** — 1m candles -- **VWAP** — 1m candles +- **Bollinger Bands(20,2)** — 1m candles +- **VWAP** — 1m candles - **ATR(14)** — 5m candles (volatility filter + stop sizing) - **EMA stack** — 5m candles (9, 21, 50). Note: `ta indicators` surfaces EMA20/50 natively; treat EMA9 as the short-term trend proxy by eyeballing the 1m EMA alignment or computing locally if needed. @@ -50,7 +51,7 @@ A long fires when **ALL** of the following are true simultaneously: 5. **5m EMA context:** the 5m EMA stack is either **bullish** (EMA9 > EMA21 > EMA50) OR **flat-bullish** (all three within 0.3% of each other). Dead-cross (9 < 21 < 50) = veto. 6. **ATR volatility gate:** 5m ATR(14) expressed as % of price is **between 0.10% and 0.50%**. Below 0.10% = dead market; above 0.50% = too choppy. -> **Plain-English trigger:** *"Price tags lower Bollinger + RSI < 35 while trading below VWAP, then reclaims VWAP on a volume spike, with the 5m EMA stack flat or up."* +> **Plain-English trigger:** _"Price tags lower Bollinger + RSI < 35 while trading below VWAP, then reclaims VWAP on a volume spike, with the 5m EMA stack flat or up."_ ### 1.3 Exact Short-Entry Formula @@ -63,7 +64,7 @@ A short fires when **ALL** of the following are true simultaneously: 5. **5m EMA context:** the 5m EMA stack is either **bearish** (EMA9 < EMA21 < EMA50) OR **flat-bearish** (all three within 0.3% of each other). Golden-cross (9 > 21 > 50) = veto. 6. **ATR volatility gate:** same as long: 5m ATR(14) % of price must be **0.10%–0.50%**. -> **Plain-English trigger:** *"Price tags upper Bollinger + RSI > 65 while trading above VWAP, then breaks back below VWAP on a volume spike, with the 5m EMA stack flat or down."* +> **Plain-English trigger:** _"Price tags upper Bollinger + RSI > 65 while trading above VWAP, then breaks back below VWAP on a volume spike, with the 5m EMA stack flat or down."_ ### 1.4 ATR-Based Stop Sizing @@ -88,14 +89,14 @@ A short fires when **ALL** of the following are true simultaneously: Before any trigger, scan the Hyperliquid perp with `list-assets --all-dexes` and verify: -| Filter | Threshold | Why | -|--------|-----------|-----| -| `dayNtlVlm` | ≥ **$5,000,000** | Enough two-sided flow to fill tight stops | -| `openInterest` | ≥ **$1,000,000** | Confirms active positioning | -| `impactPxs` spread | < **0.15%** for intended size | Slippage on entry/exit must not eat edge | -| `referencePx` vs `oraclePx` vs `midPx` | All within **0.10%** | Rejects stale or manipulated prints | -| `isDelisted` | `false` | Non-negotiable | -| `maxLeverage` offered | ≥ **10×** | Scalping regime needs magnification | +| Filter | Threshold | Why | +| -------------------------------------- | ----------------------------- | ----------------------------------------- | +| `dayNtlVlm` | ≥ **$5,000,000** | Enough two-sided flow to fill tight stops | +| `openInterest` | ≥ **$1,000,000** | Confirms active positioning | +| `impactPxs` spread | < **0.15%** for intended size | Slippage on entry/exit must not eat edge | +| `referencePx` vs `oraclePx` vs `midPx` | All within **0.10%** | Rejects stale or manipulated prints | +| `isDelisted` | `false` | Non-negotiable | +| `maxLeverage` offered | ≥ **10×** | Scalping regime needs magnification | **Actionable preference:** candidates with `dayNtlVlm` > $20M and impact spread < 0.08% rank above everything else. If no candidate clears the table, do not trade — flat is a position. @@ -127,14 +128,14 @@ tribes-cli hyperliquid entry-gate override --coin BTC --actor exec-lead --reason ### 3.1 Notional & Target -| Variable | Value | -|----------|-------| -| Posted margin | $500 | -| Leverage | 20× | -| Notional size | **$10,000** | +| Variable | Value | +| ------------------ | ------------------------- | +| Posted margin | $500 | +| Leverage | 20× | +| Notional size | **$10,000** | | Gross daily target | **+$50** (+10% of margin) | -| Hard stop-loss | **−$25** (−5% of margin) | -| R:R ratio | **2:1** | +| Hard stop-loss | **−$25** (−5% of margin) | +| R:R ratio | **2:1** | ### 3.2 Price-Distance Math at 20× @@ -142,17 +143,18 @@ A 0.25% price move on $10,000 notional = $25 P&L = 5% of margin. A 0.50% price move = $50 P&L = 10% of margin. Therefore: + - **SL distance:** **−0.25%** from entry (hard; may be adjusted by ATR within 0.20%–0.30% bounds). - **TP distances:** ladder below sums to **+0.50%** equivalent on the blended position. ### 3.3 Three-Rung Scaled TP -| Rung | % of Position Closed | Price % from Entry | P&L on That Slice | % of Margin Captured | -|------|----------------------|--------------------|-------------------|----------------------| -| **TP1** | 50% | **+0.30%** | $5,000 × 0.003 = **$15** | **3.0%** | -| **TP2** | 30% | **+0.50%** | $3,000 × 0.005 = **$15** | **3.0%** | -| **TP3** | 20% | **+1.00%** | $2,000 × 0.010 = **$20** | **4.0%** | -| **Total** | **100%** | — | **$50** | **10.0%** | +| Rung | % of Position Closed | Price % from Entry | P&L on That Slice | % of Margin Captured | +| --------- | -------------------- | ------------------ | ------------------------ | -------------------- | +| **TP1** | 50% | **+0.30%** | $5,000 × 0.003 = **$15** | **3.0%** | +| **TP2** | 30% | **+0.50%** | $3,000 × 0.005 = **$15** | **3.0%** | +| **TP3** | 20% | **+1.00%** | $2,000 × 0.010 = **$20** | **4.0%** | +| **Total** | **100%** | — | **$50** | **10.0%** | ### 3.4 SL Management @@ -183,14 +185,14 @@ tribes-cli trade-perp --coin --side sell --sz --reduce-only --l ### 4.1 The Numbers -| Item | Value | -|------|-------| -| Margin per trade | $500 | -| SL per full stop | −$25 (5% of margin) | -| Max full stops allowed | **2** | -| Max entries allowed | **4** (hard ceiling, regardless of outcome) | -| Fee budget | ~$10/day (2 round-trips × ~$3.50 + overhead) | -| Net daily target after fees | **~$40** | +| Item | Value | +| --------------------------- | -------------------------------------------- | +| Margin per trade | $500 | +| SL per full stop | −$25 (5% of margin) | +| Max full stops allowed | **2** | +| Max entries allowed | **4** (hard ceiling, regardless of outcome) | +| Fee budget | ~$10/day (2 round-trips × ~$3.50 + overhead) | +| Net daily target after fees | **~$40** | ### 4.2 Accounting Rules @@ -214,12 +216,12 @@ Before every entry, journal: coin, entry px, SL px, TP ladder pxs, which criteri ### 5.1 Per-Market Max Leverage -| Hyperliquid `maxLeverage` | Playbook Leverage | Rationale | -|---------------------------|-------------------|-----------| -| ≥ 25× | **20×** (hard cap) | Maximum magnification within regime | -| 15× – 24× | **15×** | Room below max for buffer | -| 10× – 14× | **10×** | Default floor; still viable | -| 5× – 9× | **Skip** | Insufficient for $50/day target on $500 margin | +| Hyperliquid `maxLeverage` | Playbook Leverage | Rationale | +| ------------------------- | ------------------ | ---------------------------------------------- | +| ≥ 25× | **20×** (hard cap) | Maximum magnification within regime | +| 15× – 24× | **15×** | Room below max for buffer | +| 10× – 14× | **10×** | Default floor; still viable | +| 5× – 9× | **Skip** | Insufficient for $50/day target on $500 margin | **Global ceiling:** never exceed **20×**, even if the venue offers 50×. @@ -234,9 +236,9 @@ Before every entry, journal: coin, entry px, SL px, TP ladder pxs, which criteri ### 5.3 Position Sizing with Concurrency | Concurrent Positions | Margin per Position | Notional per Position (20×) | -|----------------------|---------------------|------------------------------| -| 1 | $500 | $10,000 | -| 2 | $250 each | $5,000 each | +| -------------------- | ------------------- | --------------------------- | +| 1 | $500 | $10,000 | +| 2 | $250 each | $5,000 each | When splitting, recalculate the TP/SL price levels for the smaller notional. The R:R stays 2:1; the absolute dollar target per trade drops proportionally. The daily loss cap remains $50 across both positions combined. diff --git a/skills/trade-execution/SKILL.md b/skills/trade-execution/SKILL.md index 191455b..1f702a4 100644 --- a/skills/trade-execution/SKILL.md +++ b/skills/trade-execution/SKILL.md @@ -146,8 +146,9 @@ tribes-cli hyperliquid trade-perp \ Assign ONE `cloid` (`0x` + 32 hex) per ticket BEFORE any order command and keep it for the whole ticket life — the entry and every retry of THAT ticket reuse the SAME cloid, so a retry-on-ambiguous-ack is deduped by the venue instead of double-filling. + - Generate once per ticket: `cloid=$(cat /dev/urandom | od -An -N16 -tx1 | tr -d ' \n' | - sed 's/^\(..\).*/0x &/'` — or reuse the ticket's existing cloid when re-sending. +sed 's/^\(..\).*/0x &/'` — or reuse the ticket's existing cloid when re-sending. - NEVER mint a fresh cloid on a retry of the same ticket — that defeats the dedupe. - `trade-spot` accepts the same `--cloid`; add it identically. - A re-fire that REUSES the same cloid is ignored by the venue (dedupe); a distinct cloid is a @@ -187,14 +188,14 @@ TP/SL line only if the user explicitly waived exits. ## Error recovery -| Symptom | Action | -| ---------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- | -| Auth error (unauthorized, expired token) | Run `tribes-cli login`, retry the original command once, then stop and report. | -| Insufficient balance/margin | Run the `hyperliquid` skill funding flow (`references/funding-paths.md`) with user confirmation, then retry the order once. | -| Order/leg/sub-order below $10 minimum | Raise the size, or reduce `--orders` (ladder) / `--duration-minutes` (TWAP), then retry. | -| Size or price rejected | Re-check the `szDecimals` rounding from step 4 against step 1 data, then retry once. | +| Symptom | Action | +| ---------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Auth error (unauthorized, expired token) | Run `tribes-cli login`, retry the original command once, then stop and report. | +| Insufficient balance/margin | Run the `hyperliquid` skill funding flow (`references/funding-paths.md`) with user confirmation, then retry the order once. | +| Order/leg/sub-order below $10 minimum | Raise the size, or reduce `--orders` (ladder) / `--duration-minutes` (TWAP), then retry. | +| Size or price rejected | Re-check the `szDecimals` rounding from step 4 against step 1 data, then retry once. | | **Entry refused: `entry trigger gate`** | The coin's gate is not `trigger_fired` within TTL — NO entry may open until the trigger stack fires (or an authority override is granted). Inspect with `hyperliquid entry-gate status --coin `; do NOT retry a refused entry. Reduce-only exits and cancels are never blocked by the gate. | -| Any other API failure | Retry the same command once; if it fails again, stop and report the error. | +| Any other API failure | Retry the same command once; if it fails again, stop and report the error. | ## Related skills diff --git a/skills/trailing-stop/SKILL.md b/skills/trailing-stop/SKILL.md index c4e739b..aa4d4c4 100644 --- a/skills/trailing-stop/SKILL.md +++ b/skills/trailing-stop/SKILL.md @@ -14,13 +14,14 @@ allowed-tools: bash read # Trailing Stop Autonomous profit protection for an open Hyperliquid perp position: `arm` captures the position -+ trail config, a detached `monitor` loop follows the price (streaming via the SDK's -`SubscriptionClient`/`WebSocketTransport`, 10s poll fallback) and tightens the stop as the -position moves in favor, and on trigger it fires a reduce-only market close at the LIVE position -size. The trailing stop sits ALONGSIDE the position's hard SL/TP bracket — never a naked -position, never a flip, never over-close. Requires: auth token (`tribes-cli login` once) and -`evmWalletId` + EVM address from `zipbox-wallet` — the address is `--from`, the id is -`--wallet-id`. + +- trail config, a detached `monitor` loop follows the price (streaming via the SDK's + `SubscriptionClient`/`WebSocketTransport`, 10s poll fallback) and tightens the stop as the + position moves in favor, and on trigger it fires a reduce-only market close at the LIVE position + size. The trailing stop sits ALONGSIDE the position's hard SL/TP bracket — never a naked + position, never a flip, never over-close. Requires: auth token (`tribes-cli login` once) and + `evmWalletId` + EVM address from `zipbox-wallet` — the address is `--from`, the id is + `--wallet-id`. ## When to use @@ -105,4 +106,4 @@ heartbeat so a crashed loop is visible in `list` as a stale heartbeat rather tha - [ ] Trail is `--trail-pct` (default) or `--trail-px`, exactly one, no-lose guard passed. - [ ] Confirm `list` shows the stop armed with a fresh heartbeat before walking away. - [ ] On trigger: `list-positions` shows the position GONE (or correctly reduced) and - `list-fills` shows the reduce-only fill. \ No newline at end of file + `list-fills` shows the reduce-only fill. diff --git a/tests/helpers/AsyncControl.test.ts b/tests/helpers/AsyncControl.test.ts index 650c92e..fc449df 100644 --- a/tests/helpers/AsyncControl.test.ts +++ b/tests/helpers/AsyncControl.test.ts @@ -74,4 +74,4 @@ describe('retryProviderAware', () => { await expect(retryProviderAware({ fn, maxRetries: 2 })).rejects.toThrow('provider_error') expect(calls).toBe(3) // initial + 2 retries }) -}) \ No newline at end of file +}) diff --git a/tests/services/EntryGateService.test.ts b/tests/services/EntryGateService.test.ts index 89cd064..b7de65e 100644 --- a/tests/services/EntryGateService.test.ts +++ b/tests/services/EntryGateService.test.ts @@ -128,13 +128,31 @@ describe('EntryGateService override (authority-gated, journaled)', () => { test('re-grant MRNA after an ETH re-invoke — both survive (no clobber)', async () => { const { service: a, stateDir } = await freshService(['exec-lead', 'chief']) - await a.override({ dex: 'main', coin: 'ETH', actor: 'exec-lead', reason: 'eth-1', ttlMs: 60_000 }) + await a.override({ + dex: 'main', + coin: 'ETH', + actor: 'exec-lead', + reason: 'eth-1', + ttlMs: 60_000 + }) const b = new EntryGateService({ stateDir, overrideActors: ['exec-lead', 'chief'] }) - await b.override({ dex: 'main', coin: 'MRNA', actor: 'exec-lead', reason: 'mrna', ttlMs: 60_000 }) + await b.override({ + dex: 'main', + coin: 'MRNA', + actor: 'exec-lead', + reason: 'mrna', + ttlMs: 60_000 + }) // Another re-invoke of ETH (the exact flap: last ETH write wiped MRNA). const c = new EntryGateService({ stateDir, overrideActors: ['exec-lead', 'chief'] }) - await c.override({ dex: 'main', coin: 'ETH', actor: 'exec-lead', reason: 'eth-2', ttlMs: 60_000 }) + await c.override({ + dex: 'main', + coin: 'ETH', + actor: 'exec-lead', + reason: 'eth-2', + ttlMs: 60_000 + }) const eth = await c.isEntryAllowed('main', 'ETH') const mrna = await c.isEntryAllowed('main', 'MRNA') @@ -194,4 +212,4 @@ describe('EntryGateService — anchored state dir (cwd-independent)', () => { await rm(foreign, { recursive: true, force: true }) } }) -}) \ No newline at end of file +}) diff --git a/tests/services/HyperliquidService.test.ts b/tests/services/HyperliquidService.test.ts index 162edb3..ad2e209 100644 --- a/tests/services/HyperliquidService.test.ts +++ b/tests/services/HyperliquidService.test.ts @@ -193,9 +193,9 @@ describe('cloid pass-through (venue dedupe)', () => { walletId: 'w' }) expect(parsed.cloid).toBe(VALID_CLOID) - expect(HyperliquidPerpTradeCommandOptionsSchema.safeParse({ ...parsed, cloid: 'bad' }).success).toBe( - false - ) + expect( + HyperliquidPerpTradeCommandOptionsSchema.safeParse({ ...parsed, cloid: 'bad' }).success + ).toBe(false) }) test('trade-spot options thread a caller cloid through unchanged', () => { @@ -557,9 +557,11 @@ describe('HyperliquidService candles', () => { }) }) - describe('HyperliquidService entry-trigger gate enforcement', () => { - async function gateService(): Promise<{ entryGate: import('@/services/EntryGateService').EntryGateService; stateDir: string }> { + async function gateService(): Promise<{ + entryGate: import('@/services/EntryGateService').EntryGateService + stateDir: string + }> { const { mkdtemp, rm } = await import('node:fs/promises') const { tmpdir } = await import('node:os') const { join } = await import('node:path') @@ -735,7 +737,9 @@ describe('HyperliquidService account-read rate-limit resilience', () => { return err } - function balancesService(infoClient: Pick) { + function balancesService( + infoClient: Pick + ) { const params: HyperliquidServiceParams = { transaction: {} as HyperliquidServiceParams['transaction'], infoClient: infoClient as InfoClient @@ -744,8 +748,18 @@ describe('HyperliquidService account-read rate-limit resilience', () => { } const PERP_STATE = { - marginSummary: { accountValue: '10000', totalNtlPos: '5000', totalRawUsd: '10000', totalMarginUsed: '100' }, - crossMarginSummary: { accountValue: '10000', totalNtlPos: '5000', totalRawUsd: '10000', totalMarginUsed: '100' }, + marginSummary: { + accountValue: '10000', + totalNtlPos: '5000', + totalRawUsd: '10000', + totalMarginUsed: '100' + }, + crossMarginSummary: { + accountValue: '10000', + totalNtlPos: '5000', + totalRawUsd: '10000', + totalMarginUsed: '100' + }, withdrawable: '9000', assetPositions: [], crossMaintenanceMarginUsed: '0', @@ -773,7 +787,10 @@ describe('HyperliquidService account-read rate-limit resilience', () => { }) describe('HyperliquidService bracket side-guard (inverted-stop prevention)', () => { - async function bracketService(): Promise<{ gated: HyperliquidService; cleanup: () => Promise }> { + async function bracketService(): Promise<{ + gated: HyperliquidService + cleanup: () => Promise + }> { const { mkdtemp, rm } = await import('node:fs/promises') const { tmpdir } = await import('node:os') const { join } = await import('node:path') @@ -1006,7 +1023,10 @@ describe('HyperliquidService ghost-fill pair detector + post-fill read-guard', ( ], clearinghouseState: { assetPositions: [], crossMarginSummary: {} } }) - const guard = await service.verifyPostFillPosition({ address: ADDR as `0x${string}`, coin: 'ETH' }) + const guard = await service.verifyPostFillPosition({ + address: ADDR as `0x${string}`, + coin: 'ETH' + }) expect(guard.verdict).toBe('fills-without-position') expect(guard.warning).toContain('FILL_WITHOUT_POSITION') expect(guard.pairs).toHaveLength(1) @@ -1037,7 +1057,10 @@ describe('HyperliquidService ghost-fill pair detector + post-fill read-guard', ( crossMarginSummary: {} } }) - const guard = await service.verifyPostFillPosition({ address: ADDR as `0x${string}`, coin: 'ETH' }) + const guard = await service.verifyPostFillPosition({ + address: ADDR as `0x${string}`, + coin: 'ETH' + }) expect(guard.verdict).toBe('position-exists') expect(guard.position?.coin).toBe('ETH') expect(guard.warning).toBeUndefined() @@ -1120,7 +1143,10 @@ describe('HyperliquidService ghost-fill pair detector + post-fill read-guard', ( userFills: [], clearinghouseState: { assetPositions: [], crossMarginSummary: {} } }) - const guard = await service.verifyPostFillPosition({ address: ADDR as `0x${string}`, coin: 'ETH' }) + const guard = await service.verifyPostFillPosition({ + address: ADDR as `0x${string}`, + coin: 'ETH' + }) expect(guard.verdict).toBe('no-recent-fills') }) @@ -1132,7 +1158,10 @@ describe('HyperliquidService ghost-fill pair detector + post-fill read-guard', ( // The service has no cancel path at all: verifyPostFillPosition only calls // listPositions + listFills (reads). It resolves without throwing even when // the position is flat. - const guard = await service.verifyPostFillPosition({ address: ADDR as `0x${string}`, coin: 'ETH' }) + const guard = await service.verifyPostFillPosition({ + address: ADDR as `0x${string}`, + coin: 'ETH' + }) expect(guard.verdict).toBe('fills-without-position') }) @@ -1227,8 +1256,30 @@ describe('HyperliquidService order-path flatten guard (COIN rule)', () => { meta, [ MAIN_CONTEXT, - { prevDayPx: '178', dayNtlVlm: '2', markPx: '180.09', midPx: '180.09', funding: '0', openInterest: '1', premium: '0', oraclePx: '180.09', impactPxs: ['180.1', '180.08'], dayBaseVlm: '2' }, - { prevDayPx: '10.9', dayNtlVlm: '2', markPx: '11.5', midPx: '11.5', funding: '0', openInterest: '1', premium: '0', oraclePx: '11.5', impactPxs: ['11.51', '11.49'], dayBaseVlm: '2' } + { + prevDayPx: '178', + dayNtlVlm: '2', + markPx: '180.09', + midPx: '180.09', + funding: '0', + openInterest: '1', + premium: '0', + oraclePx: '180.09', + impactPxs: ['180.1', '180.08'], + dayBaseVlm: '2' + }, + { + prevDayPx: '10.9', + dayNtlVlm: '2', + markPx: '11.5', + midPx: '11.5', + funding: '0', + openInterest: '1', + premium: '0', + oraclePx: '11.5', + impactPxs: ['11.51', '11.49'], + dayBaseVlm: '2' + } ] ]) const infoClient = { @@ -1277,7 +1328,11 @@ describe('HyperliquidService order-path flatten guard (COIN rule)', () => { }) test('the same close PASSES when a chief journaled user directive exists', async () => { - const { svc, cleanup } = await flattenService({ coin: 'COUN', liveSide: 'long', directive: true }) + const { svc, cleanup } = await flattenService({ + coin: 'COUN', + liveSide: 'long', + directive: true + }) const Big = await import('bignumber.js').then((m) => m.default) try { const error = await svc diff --git a/tests/services/SigningCause.test.ts b/tests/services/SigningCause.test.ts index 4d22f43..ec37dca 100644 --- a/tests/services/SigningCause.test.ts +++ b/tests/services/SigningCause.test.ts @@ -11,7 +11,9 @@ describe('unwrapCause', () => { // The SDK wraps ANY wallet.signTypedData rejection into AbstractWalletError // with {cause}. A plain .message hid the real 403 (the bug that froze the // desk's close). unwrapCause must walk to the true reason. - const terminalError = new Error('Failed to sign Ethereum typed data: 403 Forbidden{"error":"Agent wallet does not belong to caller"}') + const terminalError = new Error( + 'Failed to sign Ethereum typed data: 403 Forbidden{"error":"Agent wallet does not belong to caller"}' + ) const sdkWrapper = new Error('Failed to sign typed data with viem wallet', { cause: terminalError }) @@ -80,8 +82,9 @@ describe('HyperliquidSignReplayResultSchema', () => { nonce: 1, timestamp: 2, ok: false, - error: 'AbstractWalletError: Failed to sign typed data with viem wallet → caused by: 403 Forbidden' + error: + 'AbstractWalletError: Failed to sign typed data with viem wallet → caused by: 403 Forbidden' }) expect(parsed.ok).toBe(false) }) -}) \ No newline at end of file +}) diff --git a/tests/services/SizingLockService.test.ts b/tests/services/SizingLockService.test.ts index 826f0c6..cebafa1 100644 --- a/tests/services/SizingLockService.test.ts +++ b/tests/services/SizingLockService.test.ts @@ -181,7 +181,13 @@ describe('SizingLockService — authority-gated journaled override', () => { // Fresh process = the second CLI command; must see ETH before writing MRNA. const b = new SizingLockService({ stateDir, overrideActors: ['exec-lead', 'chief'] }) await b.arm({ packageId: 'A-212', version: 'v3', perCoin: [V3_BTC_ENTRY] }) - await b.override({ dex: 'main', coin: 'MRNA', actor: 'exec-lead', reason: 'mrna', ttlMs: 60_000 }) + await b.override({ + dex: 'main', + coin: 'MRNA', + actor: 'exec-lead', + reason: 'mrna', + ttlMs: 60_000 + }) // Both override gates must be consumed. const eth = await b.isEntrySizeAllowed({ @@ -343,7 +349,9 @@ describe('SizingLockService arm-collision guard (COIN ghost-flatten class)', () const ADDR = '0xbb64c24a6b2ee1185621490d2a1ae06522f15f57' // A service whose armCollisionCheck returns a programmable verdict per coin. - async function collisionService(verdicts: Record): Promise<{ + async function collisionService( + verdicts: Record + ): Promise<{ service: SizingLockService stateDir: string }> { @@ -360,7 +368,14 @@ describe('SizingLockService arm-collision guard (COIN ghost-flatten class)', () return { service, stateDir } } - const COIN_ENTRY = { coin: 'COIN', dex: 'main', notionalUsd: 95, marginUsd: 95, leverage: 20, szDecimals: 4 } + const COIN_ENTRY = { + coin: 'COIN', + dex: 'main', + notionalUsd: 95, + marginUsd: 95, + leverage: 20, + szDecimals: 4 + } const COIN_ENTRY_60 = { ...COIN_ENTRY, notionalUsd: 60, marginUsd: 60 } test('re-arm a coin with a LIVE position is REFUSED', async () => { @@ -437,13 +452,19 @@ describe('SizingLockService arm-collision — resting entry + reduce-only', () = const service = new SizingLockService({ stateDir, overrideActors: ['exec-lead', 'chief'], - armCollisionCheck: async () => ({ livePosition: false, inFlightFill: false, restingEntry: true }) + armCollisionCheck: async () => ({ + livePosition: false, + inFlightFill: false, + restingEntry: true + }) }) await service.load() const armed = await service.arm({ packageId: 'A-1', version: 'v14', - perCoin: [{ coin: 'COIN', dex: 'main', notionalUsd: 95, marginUsd: 95, leverage: 20, szDecimals: 4 }], + perCoin: [ + { coin: 'COIN', dex: 'main', notionalUsd: 95, marginUsd: 95, leverage: 20, szDecimals: 4 } + ], address: '0xbb64c24a6b2ee1185621490d2a1ae06522f15f57' }) expect(armed.version).toBe('v14') @@ -462,7 +483,9 @@ describe('SizingLockService arm-collision — resting entry + reduce-only', () = const armed = await service.arm({ packageId: 'A-1', version: 'v1', - perCoin: [{ coin: 'COIN', dex: 'main', notionalUsd: 95, marginUsd: 95, leverage: 20, szDecimals: 4 }] + perCoin: [ + { coin: 'COIN', dex: 'main', notionalUsd: 95, marginUsd: 95, leverage: 20, szDecimals: 4 } + ] }) expect(armed.armed).toBe(true) await rm(stateDir, { recursive: true, force: true }) @@ -506,7 +529,9 @@ describe('SizingLockService arm-journaling + order-path flatten guard', () => { await service.arm({ packageId: 'A-1', version: 'v14-COIN60', - perCoin: [{ coin: 'COIN', dex: 'main', notionalUsd: 60, marginUsd: 60, leverage: 20, szDecimals: 4 }], + perCoin: [ + { coin: 'COIN', dex: 'main', notionalUsd: 60, marginUsd: 60, leverage: 20, szDecimals: 4 } + ], address: '0xbb64c24a6b2ee1185621490d2a1ae06522f15f57' as `0x${string}` }) const journal = await readFile(join(stateDir, 'sizing-lock-journal.jsonl'), 'utf8') @@ -529,13 +554,17 @@ describe('SizingLockService arm-journaling + order-path flatten guard', () => { await service.arm({ packageId: 'A-1', version: 'v13', - perCoin: [{ coin: 'COIN', dex: 'main', notionalUsd: 95, marginUsd: 95, leverage: 20, szDecimals: 4 }], + perCoin: [ + { coin: 'COIN', dex: 'main', notionalUsd: 95, marginUsd: 95, leverage: 20, szDecimals: 4 } + ], address: '0xbb64c24a6b2ee1185621490d2a1ae06522f26f57' as `0x${string}` }) await service.arm({ packageId: 'A-1', version: 'v14', - perCoin: [{ coin: 'COIN', dex: 'main', notionalUsd: 60, marginUsd: 60, leverage: 20, szDecimals: 4 }], + perCoin: [ + { coin: 'COIN', dex: 'main', notionalUsd: 60, marginUsd: 60, leverage: 20, szDecimals: 4 } + ], address: '0xbb64c24a6b2ee1185621490d2a1ae06522f26f57' as `0x${string}` }) const journal = await readFile(join(stateDir, 'sizing-lock-journal.jsonl'), 'utf8') @@ -571,11 +600,19 @@ describe('SizingLockService arm-journaling + order-path flatten guard', () => { armCollisionCheck: async () => ({ livePosition: true, inFlightFill: false }) }) await service.load() - await service.arm({ packageId: 'A-1', version: 'v1', perCoin: [{ coin: 'COIN', dex: 'main', notionalUsd: 95, marginUsd: 95, leverage: 20, szDecimals: 4 }] }) + await service.arm({ + packageId: 'A-1', + version: 'v1', + perCoin: [ + { coin: 'COIN', dex: 'main', notionalUsd: 95, marginUsd: 95, leverage: 20, szDecimals: 4 } + ] + }) const armed = await service.arm({ packageId: 'A-1', version: 'v14', - perCoin: [{ coin: 'COIN', dex: 'main', notionalUsd: 60, marginUsd: 60, leverage: 20, szDecimals: 4 }], + perCoin: [ + { coin: 'COIN', dex: 'main', notionalUsd: 60, marginUsd: 60, leverage: 20, szDecimals: 4 } + ], address: '0xbb64c24a6b2ee1185621490d2a1ae06522f26f57' as `0x${string}`, overrideActor: 'chief', overrideReason: 'user directive: deliberate close + re-place COIN at new spec' @@ -661,7 +698,10 @@ describe('SizingLockService TWAP-in-flight + slot-cap guard (CXMT over-cap class }) test('within-cap TWAP passes (no refusal when open legs fit the slot cap)', async () => { - const { service, stateDir } = await twapService({ COIN: { livePosition: false, openTwapLegs: 1 } }, 4) + const { service, stateDir } = await twapService( + { COIN: { livePosition: false, openTwapLegs: 1 } }, + 4 + ) await service.arm({ packageId: 'A-1', version: 'v1', perCoin: [COIN_ENTRY] }) const armed = await service.arm({ packageId: 'A-1', @@ -691,4 +731,3 @@ describe('SizingLockService TWAP-in-flight + slot-cap guard (CXMT over-cap class await rm(stateDir, { recursive: true, force: true }) }) }) - diff --git a/tests/services/TrailingStopService.test.ts b/tests/services/TrailingStopService.test.ts index 989ac6b..fba21f8 100644 --- a/tests/services/TrailingStopService.test.ts +++ b/tests/services/TrailingStopService.test.ts @@ -26,7 +26,13 @@ interface FakeHyperliquid { size: string entryPx: string }> - closeCalls: Array<{ coin: string; amount: string; side: string; reduceOnly: boolean; dex: string | null }> + closeCalls: Array<{ + coin: string + amount: string + side: string + reduceOnly: boolean + dex: string | null + }> listPositionsCalls: number } @@ -71,25 +77,35 @@ async function freshService( twapOrders: [] } }), - tradePerp: vi.fn(async (params: { request: { coin: string; amount: BigNumber; side: string; reduceOnly: boolean; dex: string | null } }) => { - fake.closeCalls.push({ - coin: params.request.coin, - amount: params.request.amount.toFixed(), - side: params.request.side, - reduceOnly: params.request.reduceOnly, - dex: params.request.dex - }) - // Simulate a full close: remove the position. - const coin = params.request.coin.toUpperCase() - fake.positions = fake.positions.filter((p) => p.coin.toUpperCase() !== coin) - return { - status: 'ok', - response: { - type: 'order', - data: { statuses: [{ filled: { totalSz: '1', avgPx: '100', oid: 12345 } }] } + tradePerp: vi.fn( + async (params: { + request: { + coin: string + amount: BigNumber + side: string + reduceOnly: boolean + dex: string | null + } + }) => { + fake.closeCalls.push({ + coin: params.request.coin, + amount: params.request.amount.toFixed(), + side: params.request.side, + reduceOnly: params.request.reduceOnly, + dex: params.request.dex + }) + // Simulate a full close: remove the position. + const coin = params.request.coin.toUpperCase() + fake.positions = fake.positions.filter((p) => p.coin.toUpperCase() !== coin) + return { + status: 'ok', + response: { + type: 'order', + data: { statuses: [{ filled: { totalSz: '1', avgPx: '100', oid: 12345 } }] } + } } } - }) + ) } as unknown as HyperliquidService const infoClient = { @@ -105,8 +121,26 @@ async function freshService( collateralToken: 0 }, [ - { prevDayPx: '69000', dayNtlVlm: '0', markPx: mark, midPx: mark, funding: '0', openInterest: '0', premium: null, oraclePx: mark }, - { prevDayPx: '10.9', dayNtlVlm: '0', markPx: mark, midPx: mark, funding: '0', openInterest: '0', premium: null, oraclePx: mark } + { + prevDayPx: '69000', + dayNtlVlm: '0', + markPx: mark, + midPx: mark, + funding: '0', + openInterest: '0', + premium: null, + oraclePx: mark + }, + { + prevDayPx: '10.9', + dayNtlVlm: '0', + markPx: mark, + midPx: mark, + funding: '0', + openInterest: '0', + premium: null, + oraclePx: mark + } ] ] }) @@ -135,8 +169,12 @@ describe('computeTrailingStop (pure trail math)', () => { }) test('px trail: long subtracts, short adds the absolute distance', () => { - expect(computeTrailingStop('long', new BigNumber(70000), { kind: 'px', value: 120 }).toNumber()).toBe(69880) - expect(computeTrailingStop('short', new BigNumber(68000), { kind: 'px', value: 120 }).toNumber()).toBe(68120) + expect( + computeTrailingStop('long', new BigNumber(70000), { kind: 'px', value: 120 }).toNumber() + ).toBe(69880) + expect( + computeTrailingStop('short', new BigNumber(68000), { kind: 'px', value: 120 }).toNumber() + ).toBe(68120) }) }) @@ -180,7 +218,11 @@ describe('TRAIL-PEAK FEED verify example — live-book tickers (LINK/AAPL/HOOD)' // most 30%. stop(long) = entry + 0.7 x (peak - entry); short mirrored. These // pin the EXACT exit the verify feed computes for the current book — no // scaled-TP legs, so the monitor derives the exit from the high-water mark. - const mkProfit = (pct: number, usd: number) => ({ kind: 'profit' as const, trailProfitPct: pct, engageProfitUsd: usd }) + const mkProfit = (pct: number, usd: number) => ({ + kind: 'profit' as const, + trailProfitPct: pct, + engageProfitUsd: usd + }) test('LINK long: entry 15.40, session peak 19.20 -> banked stop = 18.06 (keep 70%)', () => { const stop = computeProfitTrailStop('long', new BigNumber('15.40'), new BigNumber('19.20'), 0.7) @@ -189,7 +231,12 @@ describe('TRAIL-PEAK FEED verify example — live-book tickers (LINK/AAPL/HOOD)' }) test('AAPL short: entry 227.50, session trough 219.00 -> stop = 221.55 (bank 70%)', () => { - const stop = computeProfitTrailStop('short', new BigNumber('227.50'), new BigNumber('219.00'), 0.7) + const stop = computeProfitTrailStop( + 'short', + new BigNumber('227.50'), + new BigNumber('219.00'), + 0.7 + ) expect(stop.toNumber()).toBeCloseTo(227.5 - 0.7 * (227.5 - 219.0), 4) expect(stop.toNumber()).toBeCloseTo(221.55, 4) }) @@ -240,7 +287,9 @@ describe('TrailingStopService arm (no-lose guard + seeding)', () => { test('refuses to arm when the initial stop already crosses the current mark (short)', async () => { const fake = fakeHyperliquid() - fake.positions = [{ dex: 'main', coin: 'BTC', side: 'short', size: '0.02166', entryPx: '69178' }] + fake.positions = [ + { dex: 'main', coin: 'BTC', side: 'short', size: '0.02166', entryPx: '69178' } + ] const { service } = await freshService(fake, { mark: '71000' }) // mark above initial stop await expect( service.arm({ @@ -275,7 +324,12 @@ describe('TrailingStopService arm (no-lose guard + seeding)', () => { }) describe('TrailingStopService monitor loop (runMonitor)', () => { - async function armedState(service: TrailingStopService, side: 'long' | 'short', entry: string, peak: string): Promise { + async function armedState( + service: TrailingStopService, + side: 'long' | 'short', + entry: string, + peak: string + ): Promise { const fake = fakeHyperliquid() fake.positions = [{ dex: 'main', coin: 'BTC', side, size: '0.02166', entryPx: entry }] const { service: svc } = await freshService(fake, { mark: peak }) diff --git a/tests/utils/RoundTripPairs.test.ts b/tests/utils/RoundTripPairs.test.ts index 87ed933..0757b08 100644 --- a/tests/utils/RoundTripPairs.test.ts +++ b/tests/utils/RoundTripPairs.test.ts @@ -89,4 +89,4 @@ describe('findRoundTripPairs (ghost-fill pair detector)', () => { ] expect(findRoundTripPairs(fills, 1000)).toHaveLength(0) }) -}) \ No newline at end of file +})