Metadata-Version: 2.4
Name: useopentrade
Version: 0.1.1
Summary: OpenTrade: crypto research, agent bundles, and runtime control
Requires-Python: >=3.10
Description-Content-Type: text/markdown
Requires-Dist: langchain-core>=0.3.81
Requires-Dist: langchain-anthropic>=0.3.15
Requires-Dist: langchain-google-genai>=2.1.5
Requires-Dist: langchain-openai>=0.3.23
Requires-Dist: langgraph>=0.4.8
Requires-Dist: pandas>=2.3.0
Requires-Dist: httpx>=0.27.0
Requires-Dist: ta>=0.11.0
Requires-Dist: rank-bm25>=0.2.2
Requires-Dist: fastapi>=0.115.0
Requires-Dist: uvicorn>=0.32.0
Requires-Dist: sse-starlette>=2.1.0
Requires-Dist: pydantic>=2.9.0
Requires-Dist: tradingview-ta>=3.3.0
Requires-Dist: feedparser>=6.0.0
Requires-Dist: fastmcp>=2.0.0
Requires-Dist: redis>=5.0.0
Requires-Dist: asyncpg>=0.29
Requires-Dist: psycopg[binary,pool]>=3.1
Requires-Dist: docker>=7.1.0
Requires-Dist: python-dotenv>=1.0.0
Requires-Dist: rich>=14.0.0
Requires-Dist: typer>=0.9
Requires-Dist: typing-extensions>=4.14.0
Requires-Dist: open-wallet-standard
Requires-Dist: scipy>=1.15.3
Provides-Extra: dev
Requires-Dist: pytest>=8.0.0; extra == "dev"
Requires-Dist: pytest-asyncio>=0.24.0; extra == "dev"
Requires-Dist: pytest-rerunfailures>=14.0; extra == "dev"
Provides-Extra: test
Requires-Dist: testcontainers[postgres]>=4.8.0; extra == "test"
Provides-Extra: live
Requires-Dist: hyperliquid-python-sdk>=0.24.0; extra == "live"
Requires-Dist: eth-account>=0.13.0; extra == "live"
Provides-Extra: cli

# OpenTrade

Automated crypto research and market intelligence for traders and analysts.

OpenTrade helps you scan the market, run deep diligence on any token, and turn fragmented crypto data into portfolio-ready investment memos. Use it to research a single asset, build thesis-driven screens, compare relative-value trades, or construct custom portfolios.

## What You Can Do

- **Research any token** — generate an institutional-style memo with fundamentals, technicals, news, sentiment, risks, catalysts, and a trade plan.
- **Scan the market** — find deep value, cashflow yield, AI exposure, momentum breakouts, oversold quality, or unlock-short candidates.
- **Build custom portfolios** — create baskets by asset class, sector, theme, valuation, liquidity, or risk profile.
- **Compare relative value** — use category and competitor analysis to frame pair trades or long/short ideas.
- **Track thesis changes** — rerun research or add follow-up analysis when governance, tokenomics, news, or market structure changes.
- **Audit the reasoning** — inspect analyst reports, scoring, debate, risk review, and final portfolio-manager memo.

## How It Works

OpenTrade mirrors an institutional trading desk with specialized AI agents working in sequence:

```
ANALYST TEAM → RESEARCHER DEBATE → TRADER → RISK ANALYSIS → INVESTMENT MEMO
```

**Phase 1 — Analyst Team** (4 default agents, each with crypto-specific tools)
- **Fundamentals Analyst** — Market cap vs FDV, TVL, protocol revenue, on-chain valuation (MVRV, NVT), value accrual, fee switch/buyback/burn mechanics, token dilution, and competitive positioning
- **Technical Analyst** — Murphy-methodology top-down analysis: Dow Theory trend structure, MA crossovers (golden/death cross), swing-based S/R, Fibonacci retracements, RSI/MACD divergence detection, volume confirmation, plus standard indicators (RSI, MACD, Bollinger Bands, ATR, ADX, Stochastic RSI)
- **News Analyst** — Protocol upgrades, security incidents, hack history, governance proposals (full Discourse content)
- **Sentiment Analyst** — Crypto Twitter discourse, community metrics, developer activity (GitHub + Electric Capital)

**Phase 2 — Researcher Debate** (adversarial)
- **Bull Researcher** — Network effects, token utility, growth catalysts
- **Bear Researcher** — Smart contract risk, dilution, regulatory risk, centralization
- Debate runs 1-3 rounds, then **Research Manager** synthesizes

**Phase 3 — Trading Decision**
- **Trader Agent** — Synthesizes all inputs into a recommendation

**Phase 4 — Risk Analysis** (3-way debate)
- **Aggressive**, **Conservative**, and **Neutral** risk analysts debate the trader's recommendation

**Phase 5 — Investment Memo**
- **Portfolio Manager** — Final structured output modeled on institutional research standards (10 sections, conviction scoring, trade plan with entry/target/stop)

**Follow-Up Mode** — After generating a memo, ask follow-up questions via `graph.follow_up(question, url)` to produce targeted amendments without re-running the full pipeline.

**Scanner Mode** — Before running full memos, use YAML-defined screens in `screens/` via `scripts/run_screen.py` or the `opentrade-scanner` skill to find candidates such as deep value, oversold quality, cashflow yield, AI exposure, momentum breakouts, or unlock shorts. Scanner output includes ranked candidates and ready-to-run research commands.

## Data Sources

| Source | Data | Cost |
|--------|------|------|
| [CoinGecko](https://www.coingecko.com/) | Price, OHLCV, market cap, supply, community metrics | Free (30 req/min) |
| [DefiLlama](https://defillama.com/) | TVL, protocol revenue, fees, DEX volume, stablecoin TVL, hacks | Free (unlimited) |
| [CoinMetrics](https://coinmetrics.io/) | Network data, active addresses, transaction count, market cap, supply | Free community API by default |
| [Token Terminal](https://tokenterminal.com/) | Financial metrics, revenue, fees, users, statements | Paid API key |
| [Tokenomist](https://tokenomist.ai/) | Unlocks, emissions, allocations, buyback/burn | Optional paid API key |
| [Nansen](https://www.nansen.ai/) | Smart money signals (accumulation/distribution) | Optional API key |
| [Electric Capital](https://github.com/electric-capital/crypto-ecosystems) | Ecosystem developer metrics (open dataset) | Free |
| [ta](https://github.com/bukosabino/ta) | Technical indicators (computed locally) | Free |
| Governance Forums | Full Discourse topic content via JSON API (Aave, Uniswap, etc.) | Free |
| [Tavily](https://tavily.com/) | AI-optimized web search for news, security incidents, tokenomics | Free (1k/mo) |

## Quickstart

### Current beta setup

Paste this into Claude Code, Codex, or Cursor:

```text
Set up https://opentrade.money/setup.md
```

The setup prompt installs the `useopentrade` package and exposes the `opentrade`
CLI command. See **[SETUP.md](docs/SETUP.md)** for the full guide.

### Manual install (Python library)

```bash
git clone https://github.com/UseOpenTrade/opentrade.git
cd opentrade
python3 -m venv .venv
.venv/bin/pip install -e .
cp .env.example .env
# Add API keys — see docs/SETUP.md for which ones
```

### Run a research query

```python
from research.graph.research_graph import ResearchGraph

graph = ResearchGraph()
state, rating = graph.research("bitcoin")

print(f"Rating: {rating}")
print(state["final_trade_decision"])
```

You can also inject external reference data (e.g., Token Terminal reports) via supplementary context:

```python
state, rating = graph.research(
    "aave",
    investment_timeframe="medium",
    supplementary_context="DAO revenue is $142M TTM with a 15.11% take rate..."
)
```

**Follow-up questions** (without re-running the full pipeline):

```python
amendment = graph.follow_up(
    "What about the Aave Will Win governance proposal?",
    url="https://governance.aave.com/t/arfc-aave-will-win-framework/24352"
)
```

Or via CLI:

```bash
python scripts/follow_up.py results/aave_state.json "What about the fee switch?" --url https://...
```

### Run a screener before research

```bash
python scripts/run_screen.py --list
python scripts/run_screen.py deep_value --top-n 5
python scripts/run_screen.py --ad-hoc "AI tokens down >50% with active dev"
```

Screen definitions live in `screens/`. Each screen uses cheap CoinGecko filters first, then selectively enriches survivors with GitHub/GitLab and financial metrics to keep API calls bounded.

### 4. Run the API server

```bash
uvicorn api.main:app --reload --port 8000
```

Then call the API:

```bash
# Full memo (blocking)
curl -X POST http://localhost:8000/api/research \
  -H "Content-Type: application/json" \
  -d '{"query": "solana", "depth": "standard"}'

# Streaming (SSE)
curl -X POST http://localhost:8000/api/research/stream \
  -H "Content-Type: application/json" \
  -d '{"query": "ethereum", "depth": "quick"}'
```

## Database

The opentrade API has two backends selected at startup via environment variables:

- **Sqlite (default, zero setup).** If `OPENTRADE_DATABASE_URL` is unset, the API uses a local sqlite file at `OPENTRADE_DB_PATH` (default `./portfolio.db`). The file is created on first use. This is the zero-dependency path for local dev and CI.
- **OpenTrade Postgres (opt-in).** If `OPENTRADE_DATABASE_URL` is set, the API connects to the OpenTrade-owned Postgres/Timescale schema via asyncpg. The URL must point at a Postgres database with `db/migrations` applied.

**Selection rule:** `OPENTRADE_DATABASE_URL` set → postgres; unset → sqlite. Never both. Startup fails loudly if the postgres pool cannot connect — there is no silent fallback to sqlite.

**Local postgres stack** — spin up Postgres + OpenTrade migrations + the API together:

```bash
cd packages/opentrade
docker-compose up
# API at http://localhost:8000, timescaledb at localhost:5433
curl http://localhost:8000/api/leaderboard
```

The compose file runs a one-shot `opentrade-db-migrate` sidecar that applies the migrations in `db/migrations/` before the API starts. `OPENTRADE_DATABASE_URL` is wired into the API container automatically. `OPENTRADE_DATABASE_NAME` defaults to the OpenTrade-owned database name (`opentrade`).

## Next.js server env

The Next.js frontend proxies browser requests through App Router route handlers under `app/api/`. Those handlers read **server-only** env vars — they must never be prefixed `NEXT_PUBLIC_*` and must never reach the browser bundle:

- **`OPENTRADE_API_URL`** (required) — base URL the proxy routes use to reach the FastAPI opentrade-api.
  - Local dev: `http://localhost:8000`
  - Demo cluster: `http://internal.dingus.party/opentrade-api` — Traefik's `strip-opentrade-api` middleware strips the prefix before hitting the backend, so the proxy always appends the FastAPI path unchanged (e.g. `/api/leaderboard`).
- **`RACECONTROL_URL`** (required for onboarding flow) — base URL for `circuit-racecontrol` (trials, races, customization).
  - Local dev: `http://localhost:8080`
  - Demo cluster: `http://internal.dingus.party/racecontrol` — same strip-prefix pattern (`strip-racecontrol` middleware).
- **`EDGE_AUTH_PASSWORD`** (required for hosted runtime) — when set, proxy routes attach `Authorization: Basic base64("api:<pw>")` to upstream requests. Matches the Traefik BasicAuth htpasswd entry created by `infra/k8s/demo/deploy.sh` (username hardcoded to `api`).
- **`OPENTRADE_RUNTIME_ALLOW_ANONYMOUS`** (dev only) — runtime control routes fail closed by default: hosted deployments must set `EDGE_AUTH_PASSWORD` and resolve an owner per request. Set this to `1` only for a single-operator local dev box to run without auth.

All vars live only on the Next.js server side (Vercel server env, or `.env.local` for dev). See `.env.example` for the Next.js section.

**Proxy routes:**

| Next.js path | Upstream base | Upstream path |
|---|---|---|
| `GET /api/leaderboard` | `OPENTRADE_API_URL` | `/api/leaderboard` |
| `POST /api/agents` | `OPENTRADE_API_URL` | `/api/agents` |
| `POST /api/onboarding/construct-config` | `OPENTRADE_API_URL` | `/api/onboarding/construct-config` |
| `POST /api/trials` | `RACECONTROL_URL` | `/trials` (forwards `X-User-Id`) |

## Configuration

Edit `research/config.py` or pass a config dict to `ResearchGraph`:

```python
graph = ResearchGraph(config={
    "llm_provider": "anthropic",           # or openai, google, xai, openrouter, ollama
    "deep_think_llm": "claude-sonnet-4-6", # quality model for final memo
    "quick_think_llm": "claude-haiku-4-5-20251001",  # fast model for analysts
    "max_debate_rounds": 2,                # bull/bear debate rounds (1-3)
    "max_risk_discuss_rounds": 1,          # risk analysis rounds (1-3)
})
```

**Depth presets** (via API):
- `quick` — 1 debate round (~$0.10/query)
- `standard` — 2 debate rounds (~$0.25/query)
- `deep` — 3 debate rounds (~$0.50/query)

## LLM Providers

All providers are supported via LangChain integrations:

| Provider | Models | Env Variable |
|----------|--------|-------------|
| Anthropic | Claude Sonnet, Haiku | `ANTHROPIC_API_KEY` |
| OpenAI | GPT-4o, GPT-4o-mini | `OPENAI_API_KEY` |
| Google | Gemini | `GOOGLE_API_KEY` |
| xAI | Grok | `XAI_API_KEY` |
| OpenRouter | Any model | `OPENROUTER_API_KEY` |
| Ollama | Local models | (runs locally) |

## Project Structure

```
opentrade/
├── research/
│   ├── config.py                  # Default configuration
│   ├── dataflows/                 # Data clients (CoinGecko, DefiLlama, CoinMetrics, etc.)
│   ├── agents/
│   │   ├── analysts/              # 4 default analysts, plus optional specialist analysts
│   │   ├── researchers/           # Bull/Bear adversarial debate
│   │   ├── risk_mgmt/             # Aggressive/Conservative/Neutral debate
│   │   ├── managers/              # Research Manager + Portfolio Manager
│   │   └── trader/                # Trader agent
│   ├── chat/                      # Conversational Q&A layer (intent routing)
│   ├── graph/                     # LangGraph orchestration
│   │   ├── research_graph.py      # Main entry point (ResearchGraph class + follow_up)
│   │   ├── setup.py               # Graph construction
│   │   └── ...                    # Conditional logic, propagation, reflection
│   ├── reference_data/            # Stored reference data (Token Terminal reports, etc.)
│   └── llm_clients/               # Multi-provider LLM abstraction
├── api/
│   ├── main.py                    # FastAPI application
│   └── routes/                    # /api/research + /api/chat endpoints
├── scripts/
│   ├── run_research.py            # CLI for full pipeline runs
│   └── follow_up.py               # CLI for follow-up questions on existing memos
├── BACKLOG.md                     # Tracked improvements and feature roadmap
└── tests/
```

## License

This project is a fork of [TradingAgents](https://github.com/TauricResearch/TradingAgents), licensed under the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0).


## Next.js server env

The Next.js frontend proxies browser requests through App Router route handlers under `app/api/`. Those handlers read **server-only** env vars — they must never be prefixed `NEXT_PUBLIC_*` and must never reach the browser bundle:

- **`OPENTRADE_API_URL`** (required) — base URL the proxy routes use to reach the FastAPI opentrade-api.
  - Local dev: `http://localhost:8000`
  - Demo cluster: `http://internal.opentrade.money/opentrade-api` — Traefik's `strip-opentrade-api` middleware strips the prefix before hitting the backend, so the proxy always appends the FastAPI path unchanged (e.g. `/api/leaderboard`).
- **`RACECONTROL_URL`** (required for onboarding flow) — base URL for `circuit-racecontrol` (trials, races, customization).
  - Local dev: `http://localhost:8080`
  - Demo cluster: `http://internal.opentrade.money/racecontrol` — same strip-prefix pattern (`strip-racecontrol` middleware).
- **`EDGE_AUTH_PASSWORD`** (required for hosted runtime) — when set, proxy routes attach `Authorization: Basic base64("api:<pw>")` to upstream requests. Matches the Traefik BasicAuth htpasswd entry created by `infra/k8s/demo/deploy.sh` (username hardcoded to `api`).
- **`OPENTRADE_RUNTIME_ALLOW_ANONYMOUS`** (dev only) — runtime control routes fail closed by default: hosted deployments must set `EDGE_AUTH_PASSWORD` and resolve an owner per request. Set this to `1` only for a single-operator local dev box to run without auth.

All vars live only on the Next.js server side (Vercel server env, or `.env.local` for dev). See `.env.example` for the Next.js section.

**Proxy routes:**

| Next.js path | Upstream base | Upstream path |
|---|---|---|
| `GET /api/leaderboard` | `OPENTRADE_API_URL` | `/api/leaderboard` |
| `POST /api/agents` | `OPENTRADE_API_URL` | `/api/agents` |
| `POST /api/onboarding/construct-config` | `OPENTRADE_API_URL` | `/api/onboarding/construct-config` |
| `POST /api/trials` | `RACECONTROL_URL` | `/trials` (forwards `X-User-Id`) |


---

*This software is for research purposes only and does not constitute financial or investment advice.*
