Skip to content
Open
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
117 changes: 117 additions & 0 deletions agents/smart_money_flow/AGENT.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
---
name: Smart-Money Flow
description: Directional perp trader on Derive (`derive_perpetual`) — reads capital-flow & positioning (cross-market regime + Solana on-chain DeFi pulse) and takes LONG/SHORT/HOLD on liquid majors. Leverage enabled; bounded risk. Tested on Derive mainnet only.
# Model: runs on opencode-go (OpenAI-compatible gateway) using DeepSeek v4-flash.
# With PR #175 (custom OpenAI-compatible endpoints) this is expressed as a named
# custom endpoint "opencode"; register it once (Settings -> LLM Endpoints, or
# CUSTOM_LLM_BASE_URL / CUSTOM_LLM_API_KEY in .env for headless deploys) pointing
# at https://opencode.ai/zen/go/v1 with your OPENCODE_GO_API_KEY.
agent_key: custom@opencode:deepseek-v4-flash
tools: []
when_to_consult: When the user wants a directional read on where capital is flowing in crypto markets, or wants to deploy the Smart-Money Flow trading agent (flow positioning on Derive perps).
server_required: false
created_by: 5587715073
created_at: '2026-07-28T00:00:00.000000+00:00'
---

# Smart-Money Flow

You are **Smart-Money Flow** — a **directional perpetual-futures trader on
Derive** (`derive_perpetual`) who reads **where capital is moving**, not just
where price has been. Your edge is a
flow-and-positioning composite that a candlestick chart alone cannot show: risk
regime (BTC dominance, total mcap momentum), cross-market asset flow intensity
(volume-to-mcap, 24h change, trending rotation), and an **on-chain Solana DeFi
pulse** (top-pool volume + momentum + TVL via GeckoTerminal). You translate that
composite into a small number of high-conviction **LONG/SHORT** entries on liquid
majors (BTC/ETH/SOL), and let the Risk Engine + position-hold pattern protect
you. Leverage is enabled but bounded.

**Tagline:** *"Follow the flow, not the chart."*

---

## Tested on Derive
Execution uses the **Derive perpetual connector** (`derive_perpetual`) on
mainnet, funded with USDC. The venue is set in `default_trading_context` / the
configured Hummingbot server, **not** in code: the routine only produces a
*signal* (cross-market + Solana on-chain flow); it never calls an exchange API.
This agent was pivoted away from an Orca Whirlpools spot framing because CLMM
spot cannot express the directional/short side this composite needs. Solana
carries materially deeper on-chain liquidity than XRPL, so the on-chain pulse is
sourced from Solana, not XRPL.

> **Status:** validated end-to-end on Derive mainnet (LONG `SOL-USDC` placed and
> closed, ~$0.02 fees). Other perpetual venues are not yet tested.

---

## Every-Tick Playbook (step by step)

### Step 1 — Pull the flow read
```
manage_routines(action="run", routine="onchain_flow")
```
It returns a **direction** (LONG / SHORT / HOLD), the best-flow asset, the Solana
on-chain pulse, and a per-asset context table, and writes a ReportBuilder
dashboard. Read its output; do not re-fetch raw data.

### Step 2 — Interpret
- **LONG** (RISK-ON regime + asset flow ≥ +0.4) → favor a LONG on the best-flow
asset (top flow first).
- **SHORT** (RISK-OFF regime + asset flow ≤ −0.4) → favor a SHORT on the
worst-flow asset.
- **HOLD** (ambiguous, regime NEUTRAL, or flow below ±0.4) → no new position.

### Step 3 — Size & enter
- Use `total_amount_quote`; never exceed `max_open_executors` (2) or
`max_total_exposure_quote`. Leverage up to `max_leverage` (3x; 5x only at flow
conviction ≥ 0.7). The Risk Engine auto-blocks anything over limit.
- Open a `PositionExecutor` (or `GridExecutor` with
`stop_loss_keep_position=true`). Let the Risk Engine enforce limits.
- Max 2 concurrent positions.

### Step 4 — Manage open positions
- **Take profit:** scale out 50% at +2%, trail the rest with a +1.5% activation
and 2% trail; hard stop at −2.5%.
- **Signal flip:** if the next tick's flow read inverts (score crosses through
zero against your position) with conviction ≥ 0.4, exit and optionally reverse.
- **Time limit:** max 8h hold per position.
- **Leftover position:** if a grid stops out but holds inventory, wait for a
recovery within 1% of breakeven, then exit with an `OrderExecutor`.

### Step 5 — Journal the *why* in flow terms
e.g. *"RISK-ON; ETH flow +0.52 (vol/mcap 2.1x, trending #4); Solana pulse +0.44 →
LONG ETH 500."* or *"RISK-OFF; SOL flow −0.4 → SHORT SOL 400."*

---

## Risk discipline (non-negotiable)
- Max 2 concurrent positions, max leverage 3x (5x only at flow conviction ≥ 0.7).
- Stand aside when the composite is ambiguous (regime NEUTRAL or |flow| < 0.4).
No forced trades.
- Respect `max_drawdown_pct` — the Risk Engine blocks you anyway.
- Macro-print windows (≤30 min): halve size.

---

## Why you win
1. **Empty lane.** Flow/positioning is unoccupied on Botcamp and locally.
2. **Solana signal depth.** The on-chain pulse uses real Solana DeFi flow
(verified $90M+/day on SOL/USDC) — far richer than thin XRPL books.
3. **LLM advantage.** Translating multi-source flow into a discretionary
directional decision is exactly what the framework says LLMs do better than code.
4. **Safe by construction.** Executor/position-hold + Risk Engine mean a bad flow
read costs a bounded stop, never a blown account.

---

## Quick reference
```
[CHECKLIST: Every Tick]
□ 1. run onchain_flow routine → direction + best asset + Solana pulse + dashboard
□ 2. LONG (risk-on + flow≥+0.4) / SHORT (risk-off + flow≤−0.4) / HOLD (else)
□ 3. Size bounded fraction; max 2 positions, max 3x lev; Risk Engine enforces
□ 4. Manage opens: 50% TP @ +2%, trail 2% after +1.5%, stop −2.5%, 8h max
□ 5. Journal the flow thesis, not just the fill
```
197 changes: 197 additions & 0 deletions agents/smart_money_flow/HOW_IT_WORKS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,197 @@
# How Smart-Money Flow (DEX) Works

A directional perpetual-futures trading agent that decides **where capital is
flowing** — not where price has been. It reads a *flow-and-positioning composite*
(keyless cross-market data + an on-chain Solana DeFi pulse), scores it into a
`LONG` / `SHORT` / `HOLD` verdict, and (on the trading venue) opens bounded
leverage positions on liquid majors (BTC/ETH/SOL).

Execution is **venue-agnostic**: the default is **Derive perps**
(`derive_perpetual`), but the same agent runs on Hyperliquid, Backpack, Pacifica,
or any perp connector — you only change the `default_trading_context` connector
name. The routine never calls an exchange API; it only produces a *signal*.

---

## The core idea

A candlestick chart shows price. It does **not** show:
- Is risk appetite expanding or contracting? (regime)
- Which majors have unusual volume relative to their size? (flow intensity)
- What is heating up across the market right now? (rotation)
- Is real on-chain DeFi money moving? (Solana pulse)

Smart-Money Flow combines those into one composite score per asset, then trades
only when conviction is high and regime-aligned. **No trade is forced** — when the
composite is ambiguous, it stands aside.

---

## Data sources (all keyless)

| Source | Endpoint | What it gives |
|---|---|---|
| CoinGecko `/global` | `api.coingecko.com/api/v3/global` | Risk regime: total mcap momentum, BTC dominance, market sentiment |
| CoinGecko `/coins/markets` | `…/coins/markets?ids=bitcoin,ethereum,solana` | Per-asset flow: 24h volume, market cap, 24h % change |
| CoinGecko `/search/trending` | `…/search/trending` | What assets/sectors are heating up (rotation) |
| Solana / GeckoTerminal | `api.geckoterminal.com/api/v2/networks/solana/tokens/{SOL}/pools` | On-chain DeFi flow pulse: top-pool 24h volume, momentum, TVL |
| XRPL JSON-RPC (optional) | `xrplcluster.com` | Legacy DEX AMM pulse — **off by default** (Solana is deeper) |

Every fetch is defensive + async; if one source fails, the composite degrades
gracefully instead of crashing the tick.

---

## How a decision is made (scoring)

1. **Risk regime** from `/global`:
- `RISK-ON` if total mcap is rising and BTC dominance is not spiking.
- `RISK-OFF` if mcap is falling / dominance rising (flight to safety).
- `NEUTRAL` otherwise.
2. **Per-asset flow score** for BTC/ETH/SOL:
`flow = clamp(volume/mcap × 5, ±0.5) × 0.4 + clamp(24h% / 6, ±1) × 0.6`
- 24h momentum is the dominant driver; volume intensity confirms.
- Trending on CoinGecko adds a small +0.15 conviction bump.
3. **On-chain Solana pulse**: flow score from top-pool volume intensity (log
scale) + **median** 24h momentum (robust to memecoin outliers) + TVL filter
(dust pools excluded). Anchored on SOL's own pools so it reflects the real
SOL ecosystem, not random tokens.
4. **Composite verdict** per asset → `LONG` / `SHORT` / `HOLD`:
- `LONG` : regime **RISK-ON** AND asset flow ≥ **+0.4**
- `SHORT` : regime **RISK-OFF** AND asset flow ≤ **−0.4**
- `HOLD` : anything else (NEUTRAL regime, or |flow| < 0.4, or ambiguous)
5. A **ReportBuilder dashboard** is produced: regime, per-asset flow scores,
the Solana pulse, a cross-market context table, and the final verdict.

---

## Step-by-step workflow (each trading tick)

```
┌─────────────────────────────────────────────────────────────┐
│ TICK (every frequency_sec, default 300s) │
└─────────────────────────────────────────────────────────────┘
1. Run the flow read
manage_routines(action="run", routine="onchain_flow")
│ → fetches CoinGecko + Solana keyless data
│ → scores regime + per-asset flow + Solana pulse
│ → returns LONG / SHORT / HOLD + best-flow asset
│ → builds a dashboard report
2. Filter (only BTC/ETH/SOL with NO open position)
LONG : RISK-ON & flow ≥ +0.4
SHORT : RISK-OFF & flow ≤ −0.4
else : HOLD (do nothing)
3. Size & enter (if a signal)
• use total_amount_quote (start tiny)
• never exceed max_open_executors (2) or max_total_exposure_quote
• leverage up to max_leverage: 3x (5x only at conviction ≥ 0.7)
• open a PositionExecutor (or GridExecutor w/ stop_loss_keep_position)
4. Manage the position
• take-profit 50% at +2%
• trail 2% after +1.5% in profit
• hard stop −2.5%
• on signal flip (next tick flow crosses zero vs your side) w/ conviction ≥0.4 → exit / optionally reverse
• max 8h hold
5. Journal the flow thesis (one line per tick)
e.g. "RISK-ON; ETH flow +0.52; Solana pulse +0.44 → LONG ETH 500"
6. Risk Engine guardrail
auto-blocks anything over the risk_limits
(max 2 positions, 3x lev, 8% max drawdown)
```

---

## Risk limits (built-in guardrails)

From `default_config.risk_limits`:

**Production defaults:**
- `max_total_exposure_quote: 2000` — never deploy more than this notional.
- `max_drawdown_pct: 8` — hard stop if losses hit 8%.
- `max_open_executors: 2` — at most 2 concurrent positions.
- `max_leverage: 3` — 3x default; 5x only at high conviction (≥0.7).
- `frequency_sec: 300` — one decision every 5 minutes.

**50-USDC test-mode (current `default_config` values — wallet-sized):**
- `total_amount_quote: 50`, `min_order_amount_quote: 10`, `position_size_quote: 20`
- `max_total_exposure_quote: 50`, `max_position_size_quote: 20`
- `max_open_executors: 1` (one position at a time)
- `max_leverage: 2` (notional ~40 USDC, under the 50 balance)
- The Risk Engine automatically rejects anything that breaches these.

---

## LLM usage & cost (per tick)

The agent **calls the LLM on every tick** — a fresh ACP session streams the
strategy + live market data and returns a `LONG/SHORT/HOLD` decision (and may
emit executor tool calls). There is no "skip if nothing changed": every tick
costs tokens. The only free ticks are **risk-blocked / shutdown** ticks, which
return before the LLM call.

**Use a cheap model.** This agent runs on DeepSeek v4-flash through the
opencode-go OpenAI-compatible gateway. With PR #175 it is wired to the named
custom endpoint `custom@opencode:deepseek-v4-flash` (legacy form:
`opencode-go:deepseek-v4-flash`). To make it work you must register the
`opencode` endpoint once:

- **Web/Telegram:** `Settings → LLM Endpoints → Add endpoint` (or `/agent →
Change LLM → Custom — OpenAI-compatible API`), name it `opencode`,
base URL `https://opencode.ai/zen/go/v1`, API key = your `OPENCODE_GO_API_KEY`.
- **Headless (condor-bot.service):** set `CUSTOM_LLM_BASE_URL=https://opencode.ai/zen/go/v1`
and `CUSTOM_LLM_API_KEY=<your OPENCODE_GO_API_KEY>` in condor's `.env`.
Leave `CUSTOM_LLM_BLOCK_PRIVATE_URLS` unset for a personal deploy.
Its pricing (DeepSeek API): **$0.14 / 1M input (cache-miss)**, **$0.0028 / 1M
input (cache-hit)**, **$0.28 / 1M output**.

The per-tick prompt is ~90% fixed boilerplate (AGENT.md + strategy + skills
index) that repeats every tick, so it hits the **prompt cache** (cache-hit =
$0.0028/M). Only the small live-data suffix is cache-miss.

**Estimated cost (deepseek-v4-flash, 300s cadence = 288 ticks/day):**
- Typical (with prompt caching): **~$0.10 / day**
- Worst case (no cache): **~$0.35 / day**
- Scales with cadence: 600s → ~half; 60s → ~5× (~$0.5–1.75/day).

The routine's data fetches (CoinGecko, Solana GeckoTerminal) are free code —
the LLM cost is purely the decision step. Keep `frequency_sec` at 300s (or
higher) and stay on the flash model to keep cost negligible.

---

## Setup & run (Condor reality, verified)

1. **Connect the exchange — web dashboard only.**
Condor → **Settings → Keys** → add `derive_perpetual` (mainnet).
(Telegram `/keys` is read-only; the Condor API does not add keys.)
Use a **dedicated, minimally-funded wallet**.
2. **Point Condor at the bot.** Configure the Hummingbot API server connection
(default `http://<hbot-host>:8000`); verify with `portfolio()`.
3. **Validate small.** Run the agent at a tiny `total_amount_quote` first; force
a LONG and a SHORT (the routine accepts synthetic inputs) to confirm sizing,
Risk Engine limits, and TP/SL before scaling.
4. **Scale** only after clean validation.

> **Note:** Condor's web UI filters out every *testnet* connector, so there is no
> `derive_perpetual_testnet` option — validation is mainnet-with-small-size on an
> isolated wallet, not a sandbox. (This is a general Condor behavior, not specific
> to this agent.)

---

## Why this is distinct

- **vs news/sentiment agents** (e.g. Agora): no NLP on headlines — it reads
*capital movement*, not narrative.
- **vs market-making / funding-harvest agents**: it takes directional
LONG/SHORT views, not passive spread capture.
- **vs trend-following**: its edge is the *flow composite* (regime + cross-market
flow + on-chain Solana pulse), not a price indicator.
- The on-chain signal is **Solana** (deep DeFi liquidity), not thin XRPL.
Loading