Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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 ? <baked id> : 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
Expand Down
1 change: 1 addition & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/<coin>)` — e.g. `BTC`, `ETH`, `SOL`.

<!-- BEGIN TRIBES RESOURCE ETIQUETTE -->

## Shared-resource etiquette

- This machine may share its host with other agents. Keep concurrency conservative and leave capacity for neighboring work.
Expand Down
86 changes: 44 additions & 42 deletions scalping-playbook.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,10 @@ tribes-cli ta indicators --candles-file /tmp/<coin>-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.

Expand All @@ -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

Expand All @@ -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

Expand All @@ -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.

Expand Down Expand Up @@ -127,32 +128,33 @@ 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×

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

Expand Down Expand Up @@ -183,14 +185,14 @@ tribes-cli trade-perp --coin <COIN> --side sell --sz <sz*0.20> --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

Expand All @@ -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×.

Expand All @@ -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.

Expand Down
17 changes: 9 additions & 8 deletions skills/trade-execution/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 <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

Expand Down
17 changes: 9 additions & 8 deletions skills/trailing-stop/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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.
`list-fills` shows the reduce-only fill.
2 changes: 1 addition & 1 deletion tests/helpers/AsyncControl.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,4 +74,4 @@ describe('retryProviderAware', () => {
await expect(retryProviderAware({ fn, maxRetries: 2 })).rejects.toThrow('provider_error')
expect(calls).toBe(3) // initial + 2 retries
})
})
})
26 changes: 22 additions & 4 deletions tests/services/EntryGateService.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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')
Expand Down Expand Up @@ -194,4 +212,4 @@ describe('EntryGateService — anchored state dir (cwd-independent)', () => {
await rm(foreign, { recursive: true, force: true })
}
})
})
})
Loading
Loading