Skill: prblmsolvrx/agentqskills (version 1.0.0)

--- name: moon-dev-trading-agents description: Master Moon Dev's AI Agents GitHub with 48+ specialized agents, multi-exchange support, LLM abstraction, and autonomous trading capabilities across crypto markets --- # Moon Dev's AI Trading Agents System A complete skillset reference for working with Moon Dev's experimental AI trading architecture — featuring 48+ specialized agents orchestrated across Hyperliquid, Solana (BirdEye), Asterdex, and Extended Exchange. --- ## Instructions When working with Moon Dev's trading system, use this skill to: 1. **Understand the system architecture**: Reference the core components, agent structure, and data flow patterns described in this skill 2. **Run agents**: Use the quick start commands and workflow examples to execute agents individually or via the orchestrator 3. **Configure exchanges**: Follow the exchange switching patterns to work with Hyperliquid, BirdEye, or Extended Exchange 4. **Switch AI models**: Use ModelFactory patterns to select appropriate LLM providers for different tasks 5. **Develop new agents**: Follow the agent template and development rules when creating new agents 6. **Run backtests**: Use the RBI agent workflow to generate and execute backtests from videos, PDFs, or text descriptions 7. **Debug issues**: Reference the architecture documentation and common workflows to troubleshoot problems When users ask about agents, trading workflows, exchange configuration, or system architecture, provide guidance based on the comprehensive information in this skill and referenced files (AGENTS.md, WORKFLOWS.md, ARCHITECTURE.md). --- ## 📌 When to Use This Skill Use this doc when you need to: - Understand the multi-agent architecture - Run, modify, or build new agents - Configure exchanges or LLM providers - Debug agent interactions - Run backtests using the RBI agent - Add new strategies or integrate new exchanges --- ## 🧪 Environment Setup Uses **Python 3.10.9**. - Conda, venv, or plain pip — all fine - README uses `tflow` as env name, but you can name your env anything --- ## 🚀 Quick Start ```bash # Activate environment conda activate tflow # or source venv/bin/activate # Run main orchestrator python src/main.py # Run an individual agent python src/agents/trading_agent.py python src/agents/risk_agent.py python src/agents/rbi_agent.py # After installing new packages pip freeze > requirements.txt ``` --- ## 🏗️ Core Architecture ### Directory Tree ``` src/ ├── agents/ # 48+ specialized AI agents (<800 lines each) ├── models/ # LLM provider abstraction (ModelFactory) ├── strategies/ # User-defined trading logic ├── scripts/ # Utility scripts ├── data/ # Saved results, memory, logs ├── config.py # Global configuration ├── main.py # Main orchestrator ├── nice_funcs.py # Solana/BirdEye utilities ├── nice_funcs_hl.py # Hyperliquid utilities ├── nice_funcs_extended.py # Extended Exchange utilities └── ezbot.py # Legacy bot ``` ### Key Components #### Agents Standalone executables with ModelFactory support. Output saved into `src/data/<agent_name>/`. #### LLM Providers Supports: Claude, GPT-4, DeepSeek, Groq, Gemini, Ollama. ```python from src.models.model_factory import ModelFactory model = ModelFactory.create_model('anthropic') ``` #### Trading Utilities * **nice_funcs.py** — Solana/BirdEye * **nice_funcs_hl.py** — Hyperliquid perps * **nice_funcs_extended.py** — X10 StarkNet perps #### Config * Trading settings * Risk limits * Active agents * AI model configs --- ## 🤖 Agent Categories ### Trading Agents `trading_agent`, `strategy_agent`, `risk_agent`, `copybot_agent` ### Market Analytics `sentiment_agent`, `whale_agent`, `funding_agent`, `liquidation_agent`, `chartanalysis_agent` ### Content Bots `chat_agent`, `tweet_agent`, `clips_agent`, `phone_agent`, `video_agent` ### Research / Backtesting `rbi_agent`, `research_agent`, `websearch_agent` ### Specialized `sniper_agent`, `million_agent`, `solana_agent`, `tx_agent`, `polymarket_agent`, `swarm_agent` --- ## 🔄 Common Workflows ### 1. Run any agent ```bash python src/agents/[agent_name].py ``` ### 2. Run orchestrator ```bash python src/main.py ``` Controlled by `ACTIVE_AGENTS` in `main.py`. ### 3. Switch Exchange ```python EXCHANGE = "hyperliquid" # or "birdeye", "extended" if EXCHANGE == "hyperliquid": from src import nice_funcs_hl as nf elif EXCHANGE == "extended": from src import nice_funcs_extended as nf ``` ### 4. Switch AI Model ```python AI_MODEL = "claude-3-haiku-20240307" ``` Or per-agent: ```python model = ModelFactory.create_model('deepseek') ``` ### 5. Backtesting (RBI Agent) ```bash python src/agents/rbi_agent.py ``` Supports: * YouTube videos * PDFs * Plain text trading ideas Outputs fully executable Backtesting.py code. --- ## 🧩 Development Rules (Critical) 1. **Files under 800 lines max** 2. **Don't move files** — only create new ones 3. **Use existing virtual environment** 4. Run `pip freeze > requirements.txt` after installs 5. Use **real data only** 6. Minimal try/except — let errors show 7. Never expose API keys ### New Agent Template ```python from src.models.model_factory import ModelFactory model = ModelFactory.create_model('anthropic') output_dir = "src/data/my_agent/" if __name__ == "__main__": # main logic ``` --- ## 📊 Backtesting Rules * Use `backtesting.py` (official library) * Use `pandas_ta` or `talib` for indicators * Example dataset: `src/data/rbi/BTC-USD-15m.csv` --- ## ⚙️ Config Files ### `config.py` * Tokens, whitelists/blacklists * Position sizing * Risk settings * Active agents * AI model / temperature / max tokens ### `.env` Contains: * BirdEye, MoonDev, Coingecko * Anthropic, OpenAI, DeepSeek, Groq, Gemini * Solana private keys * Hyperliquid EVM PK * X10 API keys (These must **never** be shown publicly.) --- ## 🏦 Exchange Support ### Hyperliquid (Perps DEX, 50× leverage) Functions: * `market_buy()` * `market_sell()` * `get_position()` * `close_position()` ### BirdEye / Solana 15k+ tokens * `token_overview()` * `token_price()` * `get_ohlcv_data()` ### Extended Exchange (X10) StarkNet perps Auto symbol mapping (e.g., BTC → BTC-USD). --- ## 🔁 Data Flow ``` Input + Config → Agent Init → API Calls → Data Parsing → LLM Reasoning → Decision Output → Save to data/ → (optional) Execute Trade ``` --- ## 🧪 Common Tasks ### Install new package ```bash pip install package-name pip freeze > requirements.txt ``` ### Read market data ```python from src.nice_funcs import token_overview, get_ohlcv_data, token_price ``` ### Hyperliquid trade ```python from src import nice_funcs_hl as nf nf.market_buy("BTC", usd_amount=100, leverage=10) ``` ### X10 trade ```python from src import nice_funcs_extended as nf nf.market_buy("BTC", usd_amount=100, leverage=15) ``` --- ## 🧵 Git Information * **Branch:** main Recent commits: * `dc55e90`: websearch agent * `921ead6`: rbi update * `6bb55c2`: backtest dashboard --- ## 📚 Documentation Located in `docs/`: * hyperliquid.md * extended_exchange.md * rbi_agent.md * swarm_agent.md * claude.md * websearch_agent.md * etc. --- ## 🛡️ Risk Management * Risk Agent runs **first** * Circuit breakers: * MAX_LOSS_USD * MINIMUM_BALANCE_USD * AI-confirmation optional for closing trades * Default loop: every **15 min** --- ## 🧠 Philosophy This project is experimental, community-driven, educational, and open-source. No token. No promises. No nonsense. > "Never over-engineer. Always ship real trading systems." --- **Built with 🌙 by Moon Dev**

path: WORKFLOWS.md
content: # Common Development Workflows

Practical examples for working with Moon Dev's trading system.

---

## Environment Setup

### Initial Setup

```bash
# Activate conda environment (NEVER create new venv!)
# Activate your environment (e.g., conda activate your_env_name)

# Install dependencies
pip install -r requirements.txt

# Configure environment variables
cp .env_example .env
# Edit .env with your API keys
```

### Adding New Package

```bash
# Activate your environment (e.g., conda activate your_env_name)
pip install package-name
pip freeze > requirements.txt  # CRITICAL: Always update!
```

---

## Running Agents

### Run Single Agent

```bash
# Activate environment
# Activate your environment (e.g., conda activate your_env_name)

# Run any agent standalone
python src/agents/trading_agent.py
python src/agents/risk_agent.py
python src/agents/sentiment_agent.py
python src/agents/rbi_agent.py
```

### Run Main Orchestrator

```bash
# Run multiple agents in loop
python src/main.py
```

Configure which agents run in `main.py`:
```python
ACTIVE_AGENTS = {
    "risk_agent": True,        # Always first
    "trading_agent": True,
    "sentiment_agent": False,  # Disabled
    "whale_agent": True,
}
```

---

## Exchange Configuration

### Switch Exchange in Trading Agent

Edit `src/agents/trading_agent.py`:

```python
# Exchange Configuration - Line ~20
EXCHANGE = "hyperliquid"  # Options: "hyperliquid", "birdeye", "extended"

# Import corresponding functions
if EXCHANGE == "hyperliquid":
    from src import nice_funcs_hl as nf
elif EXCHANGE == "extended":
    from src import nice_funcs_extended as nf
elif EXCHANGE == "birdeye":
    from src import nice_funcs as nf
```

### Test Exchange Connection

**Hyperliquid:**
```python
from src import nice_funcs_hl as hl

# Get balance
balance = hl.get_account_balance()
print(f"Balance: {balance['equity']}")

# Get position
position = hl.get_position("BTC")
if position:
    print(f"Position: {position['position_amount']}")
```

**Extended Exchange:**
```bash
# Run comprehensive test
python src/scripts/test_extended.py

# Debug position issues
python src/scripts/debug_extended_position.py
```

**BirdEye (Solana):**
```python
from src import nice_funcs as nf

# Get token data
token_addr = "your_token_address"
overview = nf.token_overview(token_addr)
price = nf.token_price(token_addr)
```

---

## AI Model Configuration

### Switch Default Model

Edit `src/config.py`:

```python
# AI Configuration
AI_MODEL = "claude-3-haiku-20240307"    # Fast, cheap
# AI_MODEL = "claude-3-sonnet-20240229"  # Balanced (recommended)
# AI_MODEL = "claude-3-opus-20240229"    # Most powerful, expensive

AI_MAX_TOKENS = 4000
AI_TEMPERATURE = 0.3
```

### Use Different Model Per Agent

```python
from src.models.model_factory import ModelFactory

# Use Claude for reasoning
claude = ModelFactory.create_model('anthropic')
response = claude.generate_response(
    system_prompt="You are a trading analyst",
    user_content="Analyze BTC",
    temperature=0.3,
    max_tokens=2000
)

# Use DeepSeek for cheap inference
deepseek = ModelFactory.create_model('deepseek')
response = deepseek.generate_response(system_prompt, user_content)

# Use Groq for speed
groq = ModelFactory.create_model('groq')
response = groq.generate_response(system_prompt, user_content)
```

### Available Providers

```python
ModelFactory.create_model('anthropic')  # Claude (default)
ModelFactory.create_model('openai')     # GPT-4
ModelFactory.create_model('deepseek')   # DeepSeek-R1, V3
ModelFactory.create_model('groq')       # Fast inference
ModelFactory.create_model('gemini')     # Google Gemini
ModelFactory.create_model('ollama')     # Local models
```

---

## Backtesting Strategies

### Using RBI Agent (Recommended)

```bash
# Activate your environment (e.g., conda activate your_env_name)
python src/agents/rbi_agent.py
```

**Workflow:**
1. Agent prompts: "Provide YouTube URL, PDF path, or describe strategy"
2. You provide input (e.g., YouTube link to trading tutorial)
3. DeepSeek-R1 extracts strategy logic
4. Generates backtesting.py compatible code
5. Executes backtest with sample data
6. Returns performance metrics

**Sample Input:**
- YouTube: `https://youtube.com/watch?v=...` (trading strategy video)
- PDF: `/path/to/strategy.pdf`
- Text: "RSI oversold strategy with 30/70 thresholds on 1H timeframe"

**Output:** Backtest results with Sharpe ratio, max drawdown, win rate, etc.

### Manual Backtesting

```python
from backtesting import Backtest, Strategy
import pandas_ta as ta
import pandas as pd

# Load sample data
df = pd.read_csv("src/data/rbi/BTC-USD-15m.csv")
df['Date'] = pd.to_datetime(df['Date'])
df.set_index('Date', inplace=True)

# Define strategy
class MyStrategy(Strategy):
    def init(self):
        # Calculate indicators using pandas_ta
        self.rsi = self.I(ta.rsi, pd.Series(self.data.Close), length=14)

    def next(self):
        if self.rsi[-1] < 30:  # Oversold
            self.buy()
        elif self.rsi[-1] > 70:  # Overbought
            self.sell()

# Run backtest
bt = Backtest(df, MyStrategy, cash=10000, commission=.002)
stats = bt.run()
print(stats)
bt.plot()
```

**IMPORTANT:**
- Use `pandas_ta` or `talib` for indicators (NOT backtesting.py built-ins)
- Sample data available: `src/data/rbi/BTC-USD-15m.csv`

---

## Trading Workflows

### Execute Manual Trade (Hyperliquid)

```python
from src import nice_funcs_hl as nf

# Market buy $100 BTC with 10x leverage
nf.market_buy("BTC", usd_amount=100, leverage=10)

# Check position
position = nf.get_position("BTC")
print(f"Entry: ${position['entry_price']:,.2f}")
print(f"PnL: {position['pnl_percentage']:.2f}%")

# Close position
nf.close_position("BTC")
```

### Execute Manual Trade (Extended)

```python
from src import nice_funcs_extended as nf

# Market buy $100 BTC with 15x leverage
nf.market_buy("BTC", usd_amount=100, leverage=15)

# Check position (auto-converts BTC to BTC-USD)
position = nf.get_position("BTC")
print(f"Size: {position['position_amount']}")
print(f"PnL: {position['pnl_percentage']:.2f}%")

# Close with maker orders (chunk_kill)
nf.chunk_kill("BTC")
```

### Monitor Positions

```python
from src import nice_funcs_hl as nf

# Get all positions
symbols = ["BTC", "ETH", "SOL"]
for symbol in symbols:
    position = nf.get_position(symbol)
    if position and position['position_amount'] != 0:
        print(f"{symbol}: {position['position_amount']} @ ${position['entry_price']:,.2f}")
        print(f"  PnL: {position['pnl_percentage']:.2f}%")
```

---

## Creating Custom Strategy

### Method 1: Strategy Class

Create `src/strategies/my_strategy.py`:

```python
"""
🌙 Moon Dev's Custom Strategy
"""

from src.strategies.base_strategy import BaseStrategy

class MyStrategy(BaseStrategy):
    name = "my_strategy"
    description = "My custom trading strategy"

    def generate_signals(self, token_address, market_data):
        """
        Generate trading signals

        Returns:
            {
                "action": "BUY" | "SELL" | "NOTHING",
                "confidence": 0-100,
                "reasoning": "Explanation"
            }
        """
        # Your logic here
        if market_data['price'] < market_data['support']:
            return {
                "action": "BUY",
                "confidence": 85,
                "reasoning": "Price below support level"
            }

        return {
            "action": "NOTHING",
            "confidence": 0,
            "reasoning": "No signal"
        }
```

Use with strategy_agent:
```python
python src/agents/strategy_agent.py
```

### Method 2: Custom Agent

Create `src/agents/my_custom_agent.py`:

```python
"""
🌙 Moon Dev's Custom Trading Agent
"""

from src.models.model_factory import ModelFactory
from src import nice_funcs_hl as nf
from termcolor import cprint
import os

OUTPUT_DIR = "src/data/my_custom_agent/"
os.makedirs(OUTPUT_DIR, exist_ok=True)

def main():
    cprint("🌙 Moon Dev's Custom Agent starting...", "cyan")

    # Initialize AI model
    model = ModelFactory.create_model('anthropic')

    # Get market data
    position = nf.get_position("BTC")

    # Prepare prompt
    system_prompt = "You are a trading analyst"
    user_content = f"Current BTC position: {position}"

    # Get AI analysis
    response = model.generate_response(
        system_prompt,
        user_content,
        temperature=0.3,
        max_tokens=1000
    )

    cprint(f"Analysis: {response}", "white")

    # Execute trade if needed
    # nf.market_buy("BTC", 100, leverage=10)

    # Save results
    with open(f"{OUTPUT_DIR}/analysis.txt", "w") as f:
        f.write(response)

    cprint("✅ Agent complete!", "green")

if __name__ == "__main__":
    main()
```

Run:
```bash
python src/agents/my_custom_agent.py
```

---

## Data Collection

### Get OHLCV Data (BirdEye)

```python
from src.nice_funcs import get_ohlcv_data

# Get 3 days of 1H candles
token_addr = "your_token_address"
ohlcv = get_ohlcv_data(token_addr, timeframe='1H', days_back=3)

# Returns DataFrame with: open, high, low, close, volume
print(ohlcv.head())
```

### Get Token Overview (BirdEye)

```python
from src.nice_funcs import token_overview

overview = token_overview(token_addr)
print(f"Price: ${overview['price']}")
print(f"Volume 24h: ${overview['volume24h']}")
print(f"Liquidity: ${overview['liquidity']}")
```

### Get Liquidation Data (Moon Dev API)

```python
from src.agents.api import MoonDevAPI

api = MoonDevAPI()

# Get liquidations for BTC
liq_data = api.get_liquidation_data("BTC")
print(f"Total liquidations: ${liq_data['total']:,.0f}")
```

---

## Risk Management

### Check Risk Before Trading

```bash
# Run risk agent first
python src/agents/risk_agent.py
```

Risk agent checks:
- Current P&L vs MAX_LOSS_USD
- Account balance vs MINIMUM_BALANCE_USD
- Position size vs MAX_POSITION_PERCENTAGE
- Daily/weekly loss limits

### Configure Risk Limits

Edit `src/config.py`:

```python
# Risk Management
MAX_LOSS_USD = 500          # Stop trading if loss exceeds
MAX_GAIN_USD = 2000         # Take profit if gain exceeds
MINIMUM_BALANCE_USD = 100   # Stop trading if balance below
MAX_POSITION_PERCENTAGE = 50 # Max % of account per position
CASH_PERCENTAGE = 10        # Keep % in cash
```

### Force Close All Positions

```python
from src import nice_funcs_hl as nf

# Emergency close all
symbols = ["BTC", "ETH", "SOL"]
for symbol in symbols:
    position = nf.get_position(symbol)
    if position and position['position_amount'] != 0:
        nf.close_position(symbol)
        print(f"✅ Closed {symbol}")
```

---

## Debugging

### Check Agent Output

Agents save outputs to `src/data/[agent_name]/`:

```bash
# View latest risk report
cat src/data/risk_agent/latest_report.txt

# View trading decisions
cat src/data/trading_agent/decisions.csv

# View RBI backtest results
ls src/data/rbi_agent/
```

### Test Exchange Connectivity

```python
# Hyperliquid
from src import nice_funcs_hl as hl
balance = hl.get_account_balance()
print(f"Connected! Balance: ${balance['equity']:,.2f}")

# Extended
from src import nice_funcs_extended as ex
balance = ex.get_account_balance()
print(f"Connected! Balance: ${balance['equity']:,.2f}")
```

### View Logs

Agents use colored terminal output (termcolor):
- Green: Success
- Yellow: Warnings
- Red: Errors
- Cyan: Info

---

## Git Workflow

### Commit Changes

```bash
# Check status
git status

# Stage changes
git add src/agents/my_new_agent.py

# Commit
git commit -m "Added my new agent"

# Push to main
git push origin main
```

### Revert File to Last Commit

```bash
# Revert specific file
git checkout HEAD -- src/agents/trading_agent.py

# Verify
git status
```

---

## Production Deployment

### Run Main Loop in Background

```bash
# Activate your environment (e.g., conda activate your_env_name)

# Run with nohup
nohup python src/main.py > trading.log 2>&1 &

# View logs
tail -f trading.log

# Stop
pkill -f main.py
```

### Monitor Active Agents

```bash
# Check running processes
ps aux | grep python | grep agents

# Monitor system resources
htop
```

---

## Common Issues

**"Module not found":**
```bash
# Activate your environment (e.g., conda activate your_env_name)
pip install missing-module
pip freeze > requirements.txt
```

**"API key not found":**
- Check `.env` file has required keys
- Verify key names match (ANTHROPIC_KEY, OPENAI_KEY, etc.)

**"Invalid quantity":**
- Position size too small for asset
- Increase USD amount or check minimum sizes

**"Position not found":**
- Verify symbol format (use "BTC" not "BTCUSD")
- Check exchange is correct (Hyperliquid vs Extended)

---

**Built with 🌙 by Moon Dev**

*Workflows for shipping real trading systems.*


path: ARCHITECTURE.md
content: # System Architecture

Deep dive into Moon Dev's AI trading system architecture.

---

## High-Level Overview

```
┌─────────────────────────────────────────────────────────┐
│                    Main Orchestrator                     │
│                    (src/main.py)                        │
└───────────┬─────────────────────────────────┬───────────┘
            │                                 │
            ▼                                 ▼
    ┌──────────────┐                 ┌──────────────┐
    │ Risk Agent   │ ◄───────────────┤ Active Agents │
    │ (runs first) │                 │  Trading      │
    └──────┬───────┘                 │  Sentiment    │
           │                         │  Whale        │
           │                         │  RBI          │
           ▼                         │  etc...       │
    ┌──────────────┐                └───────┬───────┘
    │ Risk OK?     │                        │
    │ Circuit      │                        │
    │ Breakers     │                        ▼
    └──────┬───────┘              ┌─────────────────┐
           │                      │  ModelFactory   │
           │                      │  (LLM Provider) │
           │                      └────────┬────────┘
           │                               │
           ▼                               │
    ┌─────────────────────────────────────┴────────┐
    │           Exchange Layer                      │
    │  ┌──────────┐  ┌──────────┐  ┌─────────┐   │
    │  │Hyperliquid│  │ BirdEye  │  │Extended │   │
    │  │  (HL)     │  │ (Solana) │  │  (X10)  │   │
    │  └──────────┘  └──────────┘  └─────────┘   │
    └───────────────────────────────────────────────┘
```

---

## Core Components

### 1. Main Orchestrator (main.py)

**Purpose**: Coordinates multiple agents in infinite loop

**Flow**:
1. Load configuration from config.py
2. Check ACTIVE_AGENTS dict
3. Run risk_agent first (always)
4. If risk checks pass, run active agents
5. Sleep SLEEP_BETWEEN_RUNS_MINUTES
6. Repeat

**Key Features**:
- Graceful shutdown on Ctrl+C
- Error handling per agent
- Agent independence (one failure doesn't stop others)
- Configurable agent activation

**Code Pattern**:
```python
while True:
    try:
        # Risk checks first
        if ACTIVE_AGENTS.get("risk_agent"):
            risk_result = run_risk_agent()
            if not risk_result['ok']:
                continue  # Skip trading if risk violated

        # Run other active agents
        for agent_name, is_active in ACTIVE_AGENTS.items():
            if is_active and agent_name != "risk_agent":
                run_agent(agent_name)

        time.sleep(SLEEP_BETWEEN_RUNS_MINUTES * 60)
    except KeyboardInterrupt:
        break
```

---

### 2. Agent Architecture

**Agent Types**:
- **Autonomous**: Run independently, make decisions
- **Data Collectors**: Fetch and store market data
- **Analyzers**: Process data, generate insights
- **Executors**: Execute trades based on signals

**Agent Lifecycle**:
```
Initialize → Load Config → Fetch Data → AI Analysis →
Generate Output → Store Results → (Optional) Execute Trade
```

**Common Agent Structure**:
```python
# 1. Imports
from src.models.model_factory import ModelFactory
from termcolor import cprint
import os

# 2. Configuration
OUTPUT_DIR = "src/data/agent_name/"
os.makedirs(OUTPUT_DIR, exist_ok=True)

# 3. Main function
def main():
    # Initialize model
    model = ModelFactory.create_model('anthropic')

    # Fetch data
    data = fetch_market_data()

    # AI analysis
    analysis = model.generate_response(system_prompt, user_content)

    # Store results
    save_results(OUTPUT_DIR, analysis)

    # Optional: Execute trade
    execute_trade_if_needed()

# 4. Entry point
if __name__ == "__main__":
    main()
```

**Agent Independence**:
- Each agent is self-contained
- Can run standalone or via orchestrator
- Shared utilities via nice_funcs.py
- No inter-agent dependencies (except risk_agent)

---

### 3. LLM Provider Abstraction (ModelFactory)

**Location**: `src/models/`

**Purpose**: Unified interface for multiple LLM providers

**Architecture**:
```
ModelFactory
├── BaseModel (abstract class)
│   ├── generate_response()
│   ├── generate_structured_output()
│   └── get_model_info()
│
├── AnthropicModel (Claude)
├── OpenAIModel (GPT-4)
├── DeepSeekModel (DeepSeek-R1, V3)
├── GroqModel (Fast inference)
├── GeminiModel (Google)
└── OllamaModel (Local models)
```

**Usage Pattern**:
```python
# Create model instance
model = ModelFactory.create_model('anthropic')  # or any provider

# Generate response (unified interface)
response = model.generate_response(
    system_prompt="You are a trading analyst",
    user_content="Analyze BTC market",
    temperature=0.3,
    max_tokens=2000
)

# All providers implement same interface
# Switch providers by changing one line
```

**Benefits**:
- Provider-agnostic code
- Easy A/B testing
- Cost optimization (use cheap models for simple tasks)
- Fallback options if one provider is down

**Provider Selection Strategy**:
- **Claude Sonnet**: Default, balanced quality/cost
- **Claude Haiku**: Fast, cheap, simple tasks
- **Claude Opus**: Complex reasoning, expensive
- **DeepSeek-R1**: Deep reasoning, very cheap
- **Groq**: Ultra-fast inference
- **Ollama**: Local, no API costs

---

### 4. Exchange Layer

**Three Exchange Integrations**:

#### Hyperliquid (nice_funcs_hl.py)
- **Type**: EVM-compatible perpetuals DEX
- **Blockchain**: Custom L1
- **Assets**: BTC, ETH, SOL, 50+ pairs
- **Leverage**: Up to 50x
- **API**: REST + WebSocket
- **Key Functions**:
  - `market_buy()`, `market_sell()`
  - `get_position()`, `close_position()`
  - `chunk_kill()` (maker orders)
  - `get_account_balance()`

#### BirdEye (nice_funcs.py)
- **Type**: Solana token data + spot trading
- **Blockchain**: Solana
- **Assets**: 15,000+ Solana tokens
- **Leverage**: None (spot only)
- **API**: REST
- **Key Functions**:
  - `token_overview()`, `token_price()`
  - `get_ohlcv_data()` (historical)
  - `get_token_security()` (rug check)

#### Extended Exchange (nice_funcs_extended.py)
- **Type**: StarkNet perpetuals DEX
- **Blockchain**: StarkNet L2
- **Assets**: BTC-USD, ETH-USD, SOL-USD
- **Leverage**: Up to 20x
- **API**: REST + SDK (async)
- **Key Functions**:
  - Same as Hyperliquid (API compatibility)
  - Auto symbol conversion (BTC → BTC-USD)
  - `format_symbol_for_extended()`

**Unified Trading Interface**:
All three exchanges implement same function signatures:
```python
# Works with all exchanges
nf.market_buy(symbol, usd_amount, leverage)
nf.get_position(symbol)
nf.close_position(symbol)
nf.get_account_balance()
```

**Exchange Selection**:
```python
# In agent code
EXCHANGE = "hyperliquid"  # or "birdeye", "extended"

if EXCHANGE == "hyperliquid":
    from src import nice_funcs_hl as nf
elif EXCHANGE == "extended":
    from src import nice_funcs_extended as nf
elif EXCHANGE == "birdeye":
    from src import nice_funcs as nf
```

---

### 5. Configuration Management

**Two-Layer Config**:

#### Layer 1: config.py (Trading Settings)
```python
# Monitored assets
MONITORED_TOKENS = ["BTC", "ETH", "SOL"]
EXCLUDED_TOKENS = ["SCAM", "RUG"]

# Position sizing
usd_size = 100
max_usd_order_size = 500

# Risk limits
CASH_PERCENTAGE = 10
MAX_POSITION_PERCENTAGE = 50
MAX_LOSS_USD = 500
MAX_GAIN_USD = 2000
MINIMUM_BALANCE_USD = 100

# Agent behavior
SLEEP_BETWEEN_RUNS_MINUTES = 15

# AI settings
AI_MODEL = "claude-3-sonnet-20240229"
AI_MAX_TOKENS = 4000
AI_TEMPERATURE = 0.3
```

#### Layer 2: .env (Secrets)
```bash
# AI Providers
ANTHROPIC_KEY=sk-ant-...
OPENAI_KEY=sk-...
DEEPSEEK_KEY=...
GROQ_API_KEY=...

# Trading APIs
BIRDEYE_API_KEY=...
MOONDEV_API_KEY=...

# Exchanges
HYPER_LIQUID_ETH_PRIVATE_KEY=0x...
X10_API_KEY=...
X10_PRIVATE_KEY=0x...

# Blockchain
SOLANA_PRIVATE_KEY=...
RPC_ENDPOINT=https://...
```

**Loading Pattern**:
```python
import os
from dotenv import load_dotenv

load_dotenv()

[REDACTED_SECRET]"BIRDEYE_API_KEY")
```

---

### 6. Data Flow Architecture

**Request Flow**:
```
User/Scheduler
    ↓
Main Orchestrator (main.py)
    ↓
Risk Agent (circuit breaker check)
    ↓
Active Agents (parallel execution possible)
    ↓
ModelFactory → LLM Provider
    ↓
Exchange API (Hyperliquid/BirdEye/Extended)
    ↓
Blockchain/Market
```

**Response Flow**:
```
Market Data (OHLCV, positions, balance)
    ↓
Exchange API Response
    ↓
Agent Processing (nice_funcs.py)
    ↓
LLM Analysis (ModelFactory)
    ↓
Decision Output
    ↓
Result Storage (src/data/agent_name/)
    ↓
Optional: Trade Execution
```

**Data Storage Pattern**:
```
src/data/
├── agent_name/
│   ├── latest_analysis.json
│   ├── decisions.csv
│   └── historical_trades.csv
└── shared/
    └── market_cache/
```

---

### 7. Risk Management Layer

**Risk-First Architecture**:

Risk agent ALWAYS runs before trading:
```python
# In main.py
risk_result = run_risk_agent()

if not risk_result['ok']:
    cprint("⚠️  Risk checks failed, skipping trading", "yellow")
    continue  # Skip this loop iteration
```

**Risk Checks**:
1. **Account Balance Check**:
   - Current balance > MINIMUM_BALANCE_USD?
   - If not: Stop all trading

2. **Loss Limit Check**:
   - Total loss today > MAX_LOSS_USD?
   - If yes: Close positions, stop trading

3. **Gain Target Check**:
   - Total gain today > MAX_GAIN_USD?
   - If yes: Close positions, take profit

4. **Position Size Check**:
   - Position size < MAX_POSITION_PERCENTAGE of account?
   - If not: Reduce position

5. **Exposure Check**:
   - Total exposure across all positions reasonable?
   - Cash percentage maintained?

**Circuit Breaker Pattern**:
```python
if current_balance < MINIMUM_BALANCE_USD:
    close_all_positions()
    send_alert("CRITICAL: Balance too low")
    sys.exit(1)

if daily_loss > MAX_LOSS_USD:
    close_all_positions()
    send_alert("WARNING: Max loss exceeded")
    pause_trading_for_today()
```

---

### 8. Backtesting Infrastructure

**RBI Agent Architecture** (Research-Based Inference):

```
User Input (YouTube/PDF/Text)
    ↓
DeepSeek-R1 (strategy extraction)
    ↓
Strategy Code Generation (backtesting.py format)
    ↓
Code Runner Agent (sandboxed execution)
    ↓
Backtest Execution (historical data)
    ↓
Performance Metrics (Sharpe, drawdown, etc.)
    ↓
Results Output (CSV + visualization)
```

**Backtesting Stack**:
- **Library**: backtesting.py (Python backtesting framework)
- **Indicators**: pandas_ta, talib (NOT backtesting.py built-ins)
- **Data**: Historical OHLCV from BirdEye API
- **Sample Data**: `src/data/rbi/BTC-USD-15m.csv`

**Strategy Format**:
```python
from backtesting import Strategy
import pandas_ta as ta

class MyStrategy(Strategy):
    def init(self):
        # Calculate indicators
        self.rsi = self.I(ta.rsi, pd.Series(self.data.Close), 14)

    def next(self):
        # Trading logic
        if self.rsi[-1] < 30:
            self.buy()
        elif self.rsi[-1] > 70:
            self.sell()
```

---

### 9. Agent Communication

**Current Architecture**: No direct inter-agent communication

**Data Sharing**:
- Agents write to `src/data/[agent_name]/`
- Other agents can read from those directories
- No shared memory or message passing

**Future Architecture** (via swarm_agent.py):
- Agent coordination layer
- Task distribution
- Result aggregation
- Shared context management

---

### 10. Error Handling Philosophy

**Moon Dev's Approach**: Minimal error handling

**Rationale**:
- See errors immediately
- Avoid hiding bugs
- Fail fast, fix fast
- No over-engineering

**Pattern**:
```python
# ❌ NOT THIS (over-engineered)
try:
    result = api_call()
except Exception as e:
    log.error(f"Error: {e}")
    return None

# ✅ DO THIS (fail fast)
result = api_call()  # Let it crash if it fails
```

**Exceptions**:
- Network calls (retries acceptable)
- User input (validation acceptable)
- Critical operations (position closing)

---

### 11. Scalability Considerations

**Current Scale**:
- 48+ agents
- 3 exchanges
- 6 LLM providers
- 15,000+ tokens tracked
- ~1,200 lines of shared utilities

**Performance Optimizations**:
- Agent independence (parallel execution possible)
- Lazy loading (only load what's needed)
- Result caching (avoid redundant API calls)
- ModelFactory (cheap models for simple tasks)

**Future Scaling**:
- Message queue for inter-agent communication
- Database for historical data (vs CSV)
- Load balancing across multiple instances
- Rate limit management per exchange

---

### 12. Security Architecture

**API Key Management**:
- All keys in `.env` (never committed)
- `load_dotenv()` at startup
- No hardcoded secrets

**Private Key Storage**:
- Ethereum private keys for Hyperliquid
- StarkNet keys for Extended
- Solana keys for on-chain operations
- Encrypted at rest (user's responsibility)

**Network Security**:
- HTTPS for all API calls
- WebSocket over WSS
- No credentials in logs
- No credentials shown in terminal output

**Agent Security**:
- Code execution sandboxed (RBI agent)
- No eval() of user input
- Input validation where needed

---

## System Characteristics

**Strengths**:
- Modular agent architecture
- Multi-exchange support
- Provider-agnostic LLM layer
- Risk-first approach
- Standalone agent execution

**Trade-offs**:
- No inter-agent communication (intentional)
- Minimal error handling (by design)
- CSV-based storage (simple, not scalable)
- No built-in backtesting UI

**Design Philosophy**:
> "Never over-engineer, always ship real trading systems."
>
> — Moon Dev

---

**Built with 🌙 by Moon Dev**

*Architecture for experimental AI trading at scale.*


path: AGENTS.md
content: # Complete Agent Reference

Comprehensive list of all 48+ specialized AI agents in Moon Dev's trading system.

---

## Trading Agents

**trading_agent.py**
- Primary trading execution agent
- Supports Hyperliquid, BirdEye, Extended Exchange
- Makes buy/sell decisions based on market analysis
- Configurable exchange selection via EXCHANGE variable

**strategy_agent.py**
- Executes user-defined strategies from src/strategies/
- Generates signals: BUY, SELL, NOTHING with confidence scores
- Loads strategies dynamically from strategy classes

**risk_agent.py**
- **RUNS FIRST** before any trading decisions
- Monitors portfolio risk, P&L, and exposure
- Circuit breakers: MAX_LOSS_USD, MAX_GAIN_USD, MINIMUM_BALANCE_USD
- Can force-close positions on risk violations

**copybot_agent.py**
- Copies trades from successful wallets/traders
- Uses Moon Dev API for copybot follow list
- Analyzes wallet activity and replicates positions

---

## Market Analysis Agents

**sentiment_agent.py**
- Analyzes market sentiment from social media, news
- Aggregates sentiment scores for tokens
- Helps inform trading decisions

**whale_agent.py**
- Tracks large wallet movements ("whale watching")
- Identifies significant buy/sell pressure
- Alerts on whale accumulation/distribution

**funding_agent.py**
- Monitors perpetual funding rates across exchanges
- Identifies funding rate arbitrage opportunities
- Tracks basis between spot and perps

**liquidation_agent.py**
- Tracks liquidation data from exchanges
- Identifies liquidation clusters and cascades
- Helps predict volatility and support/resistance

**chartanalysis_agent.py**
- Technical analysis using AI vision models
- Analyzes price charts for patterns
- Generates trading signals from chart patterns

**coingecko_agent.py**
- Fetches token metadata from CoinGecko API
- 15,000+ token market caps, volumes, sentiment
- Enriches token data for analysis

---

## Research & Strategy Development

**rbi_agent.py** (Research-Based Inference)
- **PRIMARY VERSION**: Codes backtests from videos/PDFs/text
- Uses DeepSeek-R1 for strategy extraction
- Generates backtesting.py compatible code
- Executes backtest and returns metrics
- Cost: ~$0.027 per backtest (~6 minutes)

**rbi_agent_v2.py**
- Alternative RBI implementation
- Enhanced strategy parsing

**rbi_agent_v3.py**
- Latest RBI version with improvements

**rbi_agent_pp.py**
- PowerPoint presentation integration for RBI

**rbi_agent_pp_multi.py**
- Multi-slide PowerPoint analysis

**rbi_batch_backtester.py**
- Batch backtest multiple strategies
- Compares strategy performance

**research_agent.py**
- General market research and analysis
- Compiles research reports
- Identifies trading opportunities

**websearch_agent.py**
- Web search capabilities for market research
- Fetches real-time news and data
- Enriches analysis with current information

---

## Content Creation Agents

**chat_agent.py**
- **PRIMARY VERSION**: Conversational AI for trading questions
- Answers user queries about markets, agents, strategies
- Provides explanations and guidance

**chat_agent_og.py**
- Original chat agent implementation

**chat_agent_ad.py**
- Ad-supported chat variant

**chat_question_generator.py**
- Generates questions for user engagement
- Creates content ideas

**clips_agent.py**
- Creates short video clips for social media
- Highlights key market moments

**realtime_clips_agent.py**
- Real-time clip generation
- Captures live market events

**tweet_agent.py**
- Generates tweets about market activity
- Automates social media posting
- Creates engagement content

**video_agent.py**
- Full-length video content creation
- Market analysis videos
- Educational content

**shortvid_agent.py**
- Short-form video content (TikTok, Reels)
- Vertical video format

**tiktok_agent.py**
- TikTok-specific content generation
- Trends and viral content

**phone_agent.py**
- Voice/phone interaction capabilities
- Audio-based market updates

---

## Specialized Trading Agents

**sniper_agent.py**
- Fast execution for new token launches
- Front-running strategies
- Quick entry/exit on opportunities

**solana_agent.py**
- Solana-specific trading operations
- On-chain transaction execution
- Solana DEX interactions

**tx_agent.py**
- Transaction monitoring and analysis
- On-chain activity tracking
- Wallet transaction parsing

**million_agent.py**
- High-volume trading strategies
- Aims for million-dollar targets
- Aggressive position sizing

**polymarket_agent.py**
- Polymarket prediction market integration
- Binary options trading
- Event-driven betting strategies

**housecoin_agent.py**
- Custom token (housecoin) specific agent
- Project-specific operations

**compliance_agent.py**
- Regulatory compliance monitoring
- Risk mitigation for legal requirements
- Trade logging and reporting

**focus_agent.py**
- Focuses on specific market segments
- Concentrated analysis on selected tokens

---

## Arbitrage Agents

**fundingarb_agent.py**
- Funding rate arbitrage strategies
- Exploits funding rate differentials
- Spot-perp arbitrage

**listingarb_agent.py**
- New listing arbitrage opportunities
- Cross-exchange price differences
- Launch price discrepancies

---

## Multi-Agent Coordination

**swarm_agent.py**
- Coordinates multiple agents simultaneously
- Orchestrates agent collaboration
- Distributes tasks across agent swarm
- Advanced multi-agent workflows

**base_agent.py**
- Base class for all agents
- Common agent functionality
- Inheritance pattern for new agents

**example_unified_agent.py**
- Example implementation of unified agent pattern
- Template for creating new agents

---

## Infrastructure & Utilities

**api.py**
- MoonDevAPI class for custom API endpoints
- Liquidation data, funding data, OI data
- Copybot follow list management

**backtest_runner.py**
- Executes backtests programmatically
- Integrates with backtesting.py library
- Strategy testing infrastructure

**code_runner_agent.py**
- Executes generated code safely
- Sandboxed code execution
- Used by RBI agent

**clean_ideas.py**
- Cleans and organizes trading ideas
- Data preprocessing utility

**new_or_top_agent.py**
- Identifies new or trending tokens
- Top mover detection
- Market scanning

**stream_agent.py**
- Real-time data streaming
- Live market updates
- WebSocket connections

**demo_countdown.py**
- Demo countdown timer
- Presentation utility

---

## Agent Categories Summary

| Category | Count | Examples |
|----------|-------|----------|
| **Trading** | 4 | trading_agent, strategy_agent, risk_agent, copybot_agent |
| **Market Analysis** | 6 | sentiment_agent, whale_agent, funding_agent, liquidation_agent |
| **Research** | 7 | rbi_agent (+ variants), research_agent, websearch_agent |
| **Content Creation** | 8 | chat_agent, clips_agent, tweet_agent, video_agent |
| **Specialized Trading** | 8 | sniper_agent, solana_agent, polymarket_agent, million_agent |
| **Arbitrage** | 2 | fundingarb_agent, listingarb_agent |
| **Coordination** | 2 | swarm_agent, base_agent |
| **Infrastructure** | 7 | api, backtest_runner, code_runner_agent, stream_agent |

---

## Running Agents

### Standalone Execution

Any agent can run independently:
```bash
# Activate your environment (e.g., conda activate your_env_name)
python src/agents/[agent_name].py
```

### Orchestrator Execution

Run multiple agents via main.py:
```bash
python src/main.py
```

Configure active agents in `main.py`:
```python
ACTIVE_AGENTS = {
    "risk_agent": True,      # Always runs first
    "trading_agent": True,
    "sentiment_agent": True,
    # ... etc
}
```

---

## Agent Output Storage

Each agent stores outputs in dedicated folder:
```
src/data/
├── risk_agent/          # Risk reports, circuit breaker logs
├── trading_agent/       # Trade logs, decisions
├── sentiment_agent/     # Sentiment scores
├── rbi_agent/           # Generated backtests
├── whale_agent/         # Whale activity logs
└── [agent_name]/        # Agent-specific outputs
```

Output formats: CSV, JSON, TXT

---

## Agent Selection Guide

**Want to trade?** → `trading_agent.py`

**Need risk management?** → `risk_agent.py` (runs first!)

**Test a strategy?** → `rbi_agent.py` (backtest from video/PDF)

**Custom strategy?** → `strategy_agent.py` (load from src/strategies/)

**Market sentiment?** → `sentiment_agent.py`, `whale_agent.py`

**Find opportunities?** → `funding_agent.py`, `liquidation_agent.py`, `listingarb_agent.py`

**Prediction markets?** → `polymarket_agent.py`

**Copy traders?** → `copybot_agent.py`

**Create content?** → `chat_agent.py`, `tweet_agent.py`, `video_agent.py`

**On-chain analysis?** → `tx_agent.py`, `solana_agent.py`

**Coordinate multiple agents?** → `swarm_agent.py`

---

## Creating New Agents

Follow the agent development pattern:

```python
"""
🌙 Moon Dev's [Agent Name]
[Brief description]
"""

from src.models.model_factory import ModelFactory
from termcolor import cprint
import os

# Configuration
OUTPUT_DIR = "src/data/my_agent/"
os.makedirs(OUTPUT_DIR, exist_ok=True)

def main():
    """Main agent logic"""
    cprint("🌙 Moon Dev's [Agent Name] starting...", "cyan")

    # Initialize LLM
    model = ModelFactory.create_model('anthropic')

    # Agent logic here
    # ...

    # Store results
    # Save to OUTPUT_DIR

    cprint("✅ Agent complete!", "green")

if __name__ == "__main__":
    main()
```

**Requirements:**
- Under 800 lines (split if longer)
- Use ModelFactory for LLM access
- Store outputs in src/data/[agent_name]/
- Make independently executable
- Follow naming: `[purpose]_agent.py`

---

**Built with 🌙 by Moon Dev**

*48+ agents, each a specialist in its domain.*


path: README-claude.md
content: # Moon Dev Trading Agents - Claude Skill

**Claude skill for mastering Moon Dev's AI trading system.**

---

## What This Skill Does

Provides Claude with expert knowledge about Moon Dev's trading system:
- 48+ specialized AI agents
- Multi-exchange support (Hyperliquid, BirdEye, Extended)
- LLM provider abstraction (6 providers)
- Backtesting with RBI agent
- Trading workflows and development patterns

---

## Skill Structure

**SKILL.md** (10KB)
- Main skill file with YAML frontmatter
- Quick start commands
- Core architecture overview
- Common tasks and patterns

**AGENTS.md** (10KB)
- Complete list of all 48+ agents
- Agent descriptions by category
- When to use which agent
- Agent selection guide

**WORKFLOWS.md** (12KB)
- Practical development workflows
- Exchange configuration
- AI model switching
- Backtesting strategies
- Trading execution examples
- Debugging tips

**ARCHITECTURE.md** (15KB)
- Deep system architecture
- Component breakdown
- Data flow patterns
- Risk management layer
- Security architecture
- Scalability considerations

---

## How It Works

Uses Claude's 3-level skill loading:

**Level 1** (Always loaded): Skill name + description (~100 tokens)

**Level 2** (When triggered): SKILL.md full content (~2,000 tokens)

**Level 3** (As needed): AGENTS.md, WORKFLOWS.md, ARCHITECTURE.md

Claude automatically loads this skill when working with the trading system.

---

## Installation

This skill is already installed in this project at:
```
.claude/skills/moon-dev-trading-agents/
```

To install in your global Claude config:
```bash
cp -r .claude/skills/moon-dev-trading-agents ~/.claude/skills/
```

---

## Usage

Just start working with the repository! Claude will automatically detect when to use this skill based on the description:

- "How do I run the trading agent?"
- "What agents are available?"
- "How do I switch exchanges?"
- "How does the RBI agent work?"

Claude loads the skill and provides expert guidance.

---

## Benefits

✅ **Instant Expertise**: Any Claude instance can master this repo

✅ **Comprehensive**: Covers all 48+ agents, exchanges, workflows

✅ **Progressive Loading**: Only loads what's needed (token efficient)

✅ **Always Updated**: Skill lives in repo, stays current

✅ **Portable**: Works in Claude Code, Claude.ai, API

---

## Maintenance

Update skill files as the system evolves:
- Add new agents to AGENTS.md
- Add new workflows to WORKFLOWS.md
- Update architecture in ARCHITECTURE.md
- Keep SKILL.md in sync with major changes

---

**Built with 🌙 by Moon Dev**

*Skills enable Claude to master complex systems instantly.*


path: CLAUDE.md
content: # CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

## Project Overview

This is an experimental AI trading system that orchestrates 48+ specialized AI agents to analyze markets, execute strategies, and manage risk across cryptocurrency markets (primarily Solana). The project uses a modular agent architecture with unified LLM provider abstraction supporting Claude, GPT-4, DeepSeek, Groq, Gemini, and local Ollama models.

## Key Development Commands

### Environment Setup
```bash
# Use existing conda environment (DO NOT create new virtual environments)
conda activate tflow

# Install/update dependencies
pip install -r requirements.txt

# IMPORTANT: Update requirements.txt every time you add a new package
pip freeze > requirements.txt
```

### Running the System
```bash
# Run main orchestrator (controls multiple agents)
python src/main.py

# Run individual agents standalone
python src/agents/trading_agent.py
python src/agents/risk_agent.py
python src/agents/rbi_agent.py
python src/agents/chat_agent.py
# ... any agent in src/agents/ can run independently
```

### Backtesting
```bash
# Use backtesting.py library with pandas_ta or talib for indicators
# Sample OHLCV data available at:
# /Users/md/Dropbox/dev/github/moon-dev-ai-agents-for-trading/src/data/rbi/BTC-USD-15m.csv
```

## Architecture Overview

### Core Structure
```
src/
├── agents/              # 48+ specialized AI agents (each <800 lines)
├── models/              # LLM provider abstraction (ModelFactory pattern)
├── strategies/          # User-defined trading strategies
├── scripts/             # Standalone utility scripts
├── data/                # Agent outputs, memory, analysis results
├── config.py            # Global configuration (positions, risk limits, API settings)
├── main.py              # Main orchestrator for multi-agent loop
├── nice_funcs.py        # ~1,200 lines of shared trading utilities
├── nice_funcs_hl.py     # Hyperliquid-specific utilities
└── ezbot.py             # Legacy trading controller
```

### Agent Ecosystem

**Trading Agents**: `trading_agent`, `strategy_agent`, `risk_agent`, `copybot_agent`
**Market Analysis**: `sentiment_agent`, `whale_agent`, `funding_agent`, `liquidation_agent`, `chartanalysis_agent`
**Content Creation**: `chat_agent`, `clips_agent`, `tweet_agent`, `video_agent`, `phone_agent`
**Strategy Development**: `rbi_agent` (Research-Based Inference - codes backtests from videos/PDFs), `research_agent`
**Specialized**: `sniper_agent`, `solana_agent`, `tx_agent`, `million_agent`, `tiktok_agent`, `compliance_agent`

Each agent can run independently or as part of the main orchestrator loop.

### LLM Integration (Model Factory)

Located at `src/models/model_factory.py` and `src/models/README.md`

**Unified Interface**: All agents use `ModelFactory.create_model()` for consistent LLM access
**Supported Providers**: Anthropic Claude (default), OpenAI, DeepSeek, Groq, Google Gemini, Ollama (local)
**Key Pattern**:
```python
from src.models.model_factory import ModelFactory

model = ModelFactory.create_model('anthropic')  # or 'openai', 'deepseek', 'groq', etc.
response = model.generate_response(system_prompt, user_content, temperature, max_tokens)
```

### Configuration Management

**Primary Config**: `src/config.py`
- Trading settings: `MONITORED_TOKENS`, `EXCLUDED_TOKENS`, position sizing (`usd_size`, `max_usd_order_size`)
- Risk management: `CASH_PERCENTAGE`, `MAX_POSITION_PERCENTAGE`, `MAX_LOSS_USD`, `MAX_GAIN_USD`, `MINIMUM_BALANCE_USD`
- Agent behavior: `SLEEP_BETWEEN_RUNS_MINUTES`, `ACTIVE_AGENTS` dict in `main.py`
- AI settings: `AI_MODEL`, `AI_MAX_TOKENS`, `AI_TEMPERATURE`

**Environment Variables**: `.env` (see `.env_example`)
- Trading APIs: `BIRDEYE_API_KEY`, `MOONDEV_API_KEY`, `COINGECKO_API_KEY`
- AI Services: `ANTHROPIC_KEY`, `OPENAI_KEY`, `DEEPSEEK_KEY`, `GROQ_API_KEY`, `GEMINI_KEY`
- Blockchain: `SOLANA_PRIVATE_KEY`, `HYPER_LIQUID_ETH_PRIVATE_KEY`, `RPC_ENDPOINT`

### Shared Utilities

**`src/nice_funcs.py`** (~1,200 lines): Core trading functions
- Data: `token_overview()`, `token_price()`, `get_position()`, `get_ohlcv_data()`
- Trading: `market_buy()`, `market_sell()`, `chunk_kill()`, `open_position()`
- Analysis: Technical indicators, PnL calculations, rug pull detection

**`src/agents/api.py`**: `MoonDevAPI` class for custom Moon Dev API endpoints
- `get_liquidation_data()`, `get_funding_data()`, `get_oi_data()`, `get_copybot_follow_list()`

### Data Flow Pattern

```
Config/Input → Agent Init → API Data Fetch → Data Parsing →
LLM Analysis (via ModelFactory) → Decision Output →
Result Storage (CSV/JSON in src/data/) → Optional Trade Execution
```

## Development Rules

### File Management
- **Keep files under 800 lines** - if longer, split into new files and update README
- **DO NOT move files without asking** - you can create new files but no moving
- **NEVER create new virtual environments** - use existing `conda activate tflow`
- **Update requirements.txt** after adding any new package

### Backtesting
- Use `backtesting.py` library (NOT their built-in indicators)
- Use `pandas_ta` or `talib` for technical indicators instead
- Sample data available at `/Users/md/Dropbox/dev/github/moon-dev-ai-agents-for-trading/src/data/rbi/BTC-USD-15m.csv`

### Code Style
- **No fake/synthetic data** - always use real data or fail the script
- **Minimal error handling** - user wants to see errors, not over-engineered try/except blocks
- **No API key exposure** - never show keys from `.env` in output

### Agent Development Pattern

When creating new agents:
1. Inherit from base patterns in existing agents
2. Use `ModelFactory` for LLM access
3. Store outputs in `src/data/[agent_name]/`
4. Make agent independently executable (standalone script)
5. Add configuration to `config.py` if needed
6. Follow naming: `[purpose]_agent.py`

### Testing Strategies

Place strategy definitions in `src/strategies/` folder:
```python
class YourStrategy(BaseStrategy):
    name = "strategy_name"
    description = "what it does"

    def generate_signals(self, token_address, market_data):
        return {
            "action": "BUY"|"SELL"|"NOTHING",
            "confidence": 0-100,
            "reasoning": "explanation"
        }
```

## Important Context

### Risk-First Philosophy
- Risk Agent runs first in main loop before any trading decisions
- Configurable circuit breakers (`MAX_LOSS_USD`, `MINIMUM_BALANCE_USD`)
- AI confirmation for position-closing decisions (configurable via `USE_AI_CONFIRMATION`)

### Data Sources
1. **BirdEye API** - Solana token data (price, volume, liquidity, OHLCV)
2. **Moon Dev API** - Custom signals (liquidations, funding rates, OI, copybot data)
3. **CoinGecko API** - 15,000+ token metadata, market caps, sentiment
4. **Helius RPC** - Solana blockchain interaction

### Autonomous Execution
- Main loop runs every 15 minutes by default (`SLEEP_BETWEEN_RUNS_MINUTES`)
- Agents handle errors gracefully and continue execution
- Keyboard interrupt for graceful shutdown
- All agents log to console with color-coded output (termcolor)

### AI-Driven Strategy Generation (RBI Agent)
1. User provides: YouTube video URL / PDF / trading idea text
2. DeepSeek-R1 analyzes and extracts strategy logic
3. Generates backtesting.py compatible code
4. Executes backtest and returns performance metrics
5. Cost: ~$0.027 per backtest execution (~6 minutes)

## Common Patterns

### Adding New Agent
1. Create `src/agents/your_agent.py`
2. Implement standalone execution logic
3. Add to `ACTIVE_AGENTS` in `main.py` if needed for orchestration
4. Use `ModelFactory` for LLM calls
5. Store results in `src/data/your_agent/`

### Switching AI Models
Edit `config.py`:
```python
AI_MODEL = "claude-3-haiku-20240307"  # Fast, cheap
# AI_MODEL = "claude-3-sonnet-20240229"  # Balanced
# AI_MODEL = "claude-3-opus-20240229"  # Most powerful
```

Or use different models per agent via ModelFactory:
```python
model = ModelFactory.create_model('deepseek')  # Reasoning tasks
model = ModelFactory.create_model('groq')      # Fast inference
```

### Reading Market Data
```python
from src.nice_funcs import token_overview, get_ohlcv_data, token_price

# Get comprehensive token data
overview = token_overview(token_address)

# Get price history
ohlcv = get_ohlcv_data(token_address, timeframe='1H', days_back=3)

# Get current price
price = token_price(token_address)
```

## Project Philosophy

This is an **experimental, educational project** demonstrating AI agent patterns through algorithmic trading:
- No guarantees of profitability (substantial risk of loss)
- Open source and free for learning
- YouTube-driven development with weekly updates
- Community-supported via Discord
- No token associated with project (avoid scams)

The goal is to democratize AI agent development and show practical multi-agent orchestration patterns that can be applied beyond trading.


Security scan verdicts — ClawScan: suspicious | static analysis: clean | VirusTotal: clean | SkillSpector: suspicious (CRITICAL)