Skill: zedit42/solana-funding-arb (version 2.1.0)

--- name: solana-funding-arb description: Solana perpetual DEX funding rate arbitrage - scanner and auto-trader. Compares funding rates across Drift and Flash Trade to find and execute cross-DEX arbitrage opportunities. Use when analyzing Solana perp funding rates, finding funding arbitrage, setting up delta-neutral strategies, or running automated funding collection. Includes Monte Carlo simulation, backtesting, and full auto-trading capabilities. --- # Solana Funding Rate Arbitrage (v2.0) Automated funding rate arbitrage bot for Solana perpetual DEXes. ## 🔥 What's New in v2.0 - **Auto-Trading**: Fully automated position management - **Multi-DEX Support**: Drift Protocol + Flash Trade - **Position Manager**: Track PnL and funding collected - **Risk Management**: Stop-loss, max DD, auto-rebalancing - **Cron Integration**: Scheduled rate checks ## Supported DEXes | DEX | Markets | Trading | Data Source | |-----|---------|---------|-------------| | Drift Protocol | 64 | ✅ Full | Direct API | | Flash Trade | 19 | 🔶 DRY_RUN | CoinGecko | ## Strategy Options | Strategy | Leverage | Win Rate | APY | Max Drawdown | |----------|----------|----------|-----|--------------| | Ultra Safe | 1x | 96% | 126% | 2% | | Conservative | 1.5x | 89% | 203% | 4% | | Moderate | 2.5x | 85% | 411% | 9% | ## Quick Start ```bash cd scripts && npm install # 1. Scan funding rates (no trading) npm run trade:scan # 2. Check position status npm run trade:status # 3. Run in DRY_RUN mode (simulated) npm run trade:dry # 4. Run live trading (requires wallet) npm run trade # Other commands npm run scan # Basic rate scanner npm run dashboard # Web dashboard (:3456) npm run monte-carlo # Risk simulations ``` ## Configuration **Config file:** `~/.secrets/funding-arb-config.json` ```json { "strategy": "ultra_safe", "max_position_pct": 50, "min_spread": 0.5, "max_dd_pct": 2, "auto_execute": true, "dry_run": true, "leverage": 1, "check_interval_hours": 4, "min_apy_threshold": 100, "max_position_usd": 100, "notification": { "telegram": true, "on_open": true, "on_close": true, "on_funding": true }, "risk": { "max_positions": 2, "stop_loss_pct": 2, "take_profit_pct": null, "auto_rebalance": true, "rebalance_threshold": 0.3 } } ``` ## Environment Variables Create `.env` in scripts directory or `~/.secrets/.env`: ```env # Required for live trading SOLANA_PRIVATE_KEY=[1,2,3,...] # Or use wallet file SOLANA_WALLET_PATH=/path/to/wallet.json # Optional SOLANA_RPC_URL=https://mainnet.helius-rpc.com/?[REDACTED_SECRET] DEBUG=true # Verbose logging ``` ## Cron Setup Run every 4 hours: ```bash # Add to crontab -e 0 */4 * * * ~/clawd/skills/solana-funding-arb/scripts/cron-runner.sh ``` ## How It Works 1. **Scan**: Compare funding rates on Drift vs Flash Trade 2. **Identify**: Find pairs where one is paying and other is receiving 3. **Execute**: - Go LONG on exchange with negative rate (receive funding) - Go SHORT on exchange with positive rate (receive funding) 4. **Collect**: Delta-neutral = collect funding from both sides 5. **Rebalance**: Close when spread reverses or DD exceeded ### Example Trade ``` SOL Funding Rates: - Drift: -500% APY (longs receive) - Flash: +800% APY (shorts receive) - Spread: 1300% APY Action: → LONG $50 SOL on Drift (receive 500% APY) → SHORT $50 SOL on Flash (receive 800% APY) → Net: Delta-neutral, collecting ~1300% APY in funding ``` ## Files ``` scripts/ ├── src/trading/ │ ├── auto-trader.ts # Main trading logic │ ├── drift-client.ts # Drift Protocol integration │ ├── flash-client.ts # Flash Trade integration │ └── position-manager.ts # Position tracking ├── cron-runner.sh # Cron wrapper script └── ... ~/.clawd/funding-arb/ ├── positions.json # Current positions ├── history.json # Trade history ├── trader-state.json # Bot state └── logs/ # Cron logs ``` ## Risks ⚠️ **Smart Contract Risk**: DEX bugs, hacks ⚠️ **Rate Reversal**: 15-18% daily probability ⚠️ **Execution Slippage**: 0.2-0.4% ⚠️ **Liquidation**: Only with leverage >1x ## Yield Comparison | Platform | APY | vs Ultra Safe | |----------|-----|---------------| | Ultra Safe (1x) | 126% | — | | US Bank (FDIC) | 4.5% | 28x less | | Aave V3 | 2.5% | 50x less | | Marginfi | 8.5% | 15x less | ## Testing 1. Start with `dry_run: true` (default) 2. Run `npm run trade:scan` to verify opportunities 3. Run `npm run trade:dry` to test execution flow 4. When ready, set `dry_run: false` and `max_position_usd: 10` 5. Monitor logs at `~/.clawd/funding-arb/logs/` ## References - [Drift Protocol Docs](https://docs.drift.trade) - [Flash Trade](https://flash.trade) - [API Reference](references/api.md)

path: USER_GUIDE.md
content: # 🚀 Solana Funding Rate Arbitrage Scanner

## Put Your Idle Coins to Work!

This tool scans funding rates across Solana perpetual DEXes to find **delta-neutral arbitrage opportunities**.

## 💡 How It Works

Perpetual futures have a "funding rate" mechanism:
- **Positive rate**: Longs pay Shorts
- **Negative rate**: Shorts pay Longs

Different DEXes can have different funding rates for the same asset. By exploiting this difference:

```
DEX A: SOL Funding = -500% APY (Longs earn)
DEX B: SOL Funding = +800% APY (Shorts earn)

Strategy:
→ Open Long on DEX A (receive funding)
→ Open Short on DEX B (receive funding)
→ Zero price risk (hedged)
→ Collect funding from both sides!
```

## 📊 Supported DEXes

| DEX | Markets | Features |
|-----|---------|----------|
| Drift Protocol | 64 | Largest Solana perp DEX |
| Flash Trade | 19 | Low fees |
| GMTrade | 37 | GMX on Solana |
| Zeta Markets | 24 | Options + Perps |

## 🛠️ Installation

### 1. Requirements
- Node.js 18 or higher
- npm or pnpm

### 2. Setup
```bash
cd scripts
npm install
```

### 3. Configuration (Optional)

Create a `.env` file:
```bash
cp .env.example .env
```

**Recommended:** Get a free Helius RPC key:
1. Go to https://helius.xyz
2. Create a free account
3. Copy your API key
4. Add to `.env`:
```env
SOLANA_RPC_URL=https://mainnet.helius-rpc.com/?[REDACTED_SECRET]
```

## 🚀 Usage

### CLI Scanner
```bash
npm run scan
```

Output:
```
═══════════════════════════════════════════════════════════════
⚡ SOLANA DEX FUNDING RATE COMPARISON
═══════════════════════════════════════════════════════════════

Symbol  | Drift APY    | Flash APY    | Spread   | Arbitrage
────────────────────────────────────────────────────────────────
SOL     | 🟢 -3037%   | 🔴 +3626%   | 6663%   | Long Drift, Short Flash
BTC     | 🟢 -617%    | 🔴 +2330%   | 2947%   | Long Drift, Short Flash
```

### Web Dashboard
```bash
npm run start
```
Open in browser: http://localhost:3456

## 📈 Implementing the Strategy

### Step 1: Find Opportunity
Use the dashboard or CLI to find high-spread assets.

### Step 2: Open Hedged Position
Example: SOL with 1300% spread

| DEX | Position | Size | Funding |
|-----|----------|------|---------|
| Drift | Long | 10 SOL | Receiving |
| Flash | Short | 10 SOL | Receiving |

### Step 3: Collect Funding
Receive funding payments every 8 hours (varies by DEX).

### Step 4: Close When Done
Close positions when spread narrows or reverses.

## ⚠️ Risks

1. **Spread Reversal**: Rates can flip direction quickly
2. **Execution Risk**: Slippage when opening/closing
3. **Liquidity**: Large positions may face issues
4. **Liquidation**: Be careful with leverage!
5. **Platform Risk**: Smart contract risks exist

## 💰 Expected Returns

- High spreads (>500% APY diff): ~1-2% daily
- Medium spreads (>100% APY diff): ~0.1-0.5% daily
- Subtract fees and slippage from estimates

## 🔐 Security

- **Never share your private key!**
- Add `.env` to `.gitignore`
- Start with small amounts
- DYOR (Do Your Own Research)

## 🔧 Advanced Configuration

### Custom RPC Providers
```env
# Helius (recommended)
SOLANA_RPC_URL=https://mainnet.helius-rpc.com/?[REDACTED_SECRET]

# Alchemy
SOLANA_RPC_URL=https://solana-mainnet.g.alchemy.com/v2/YOUR_KEY

# QuickNode
SOLANA_RPC_URL=https://your-quicknode-endpoint.com
```

### Wallet Setup (For Future Execution)
```env
# Base58 private key (KEEP SECRET!)
SOLANA_PRIVATE_KEY=your_private_key

# Or keypair file path
SOLANA_KEYPAIR_PATH=/path/to/keypair.json
```

## 🤝 Support

- Discord: [Clawdbot Community](https://discord.com/invite/clawd)
- Issues: Open on GitHub

---

*This tool is for informational purposes only. Not financial advice. Do your own research and only trade with funds you can afford to lose.*


path: references/setup.md
content: # Setup Guide

## Requirements

- Node.js 18+ (Node 20 recommended for most features)
- npm or pnpm

## Installation

```bash
# Clone or copy the scripts folder
cd solana-funding-arb/scripts

# Install dependencies
npm install
```

## Configuration

### 1. Create Environment File

```bash
cp .env.example .env
```

### 2. Configure RPC (Optional but Recommended)

For Zeta Markets support and faster scanning, use a dedicated RPC:

```env
# Helius (recommended - 100k free requests/day)
SOLANA_RPC_URL=https://mainnet.helius-rpc.com/?[REDACTED_SECRET]

# Or Alchemy
SOLANA_RPC_URL=https://solana-mainnet.g.alchemy.com/v2/YOUR_ALCHEMY_KEY
```

Get free API keys:
- Helius: https://helius.xyz
- Alchemy: https://alchemy.com/solana

### 3. Wallet Setup (For Execution Only)

⚠️ **SECURITY WARNING**: Never share your private key!

For paper trading (simulation), no wallet is needed.

For live execution:
```env
# Base58 encoded private key
SOLANA_PRIVATE_KEY=your_private_key_here

# Or path to keypair file
SOLANA_KEYPAIR_PATH=/path/to/keypair.json
```

## Running

### CLI Scanner
```bash
npm run scan
```

### Web Dashboard
```bash
npm run start
# Open http://localhost:3456
```

### Zeta-Only Scanner (requires RPC)
```bash
npm run scan:zeta
```

## Troubleshooting

### Rate Limiting (429 errors)
Use a dedicated RPC instead of public endpoint.

### WebSocket Errors
Ensure Node.js 18+ is installed. The `rpc-websockets` package has compatibility issues with older versions.

### Missing Dependencies
```bash
rm -rf node_modules package-lock.json
npm install
```

## Architecture

```
scripts/
├── src/
│   ├── core/           # Aggregators for each DEX
│   ├── dashboard/      # Web UI
│   └── execution/      # Trade execution (future)
├── package.json
└── .env
```


path: scripts/src/dex/index.ts
content: export { JupiterDex } from './jupiter';
export { RaydiumDex } from './raydium';
export { OrcaDex } from './orca';
export { MeteoraDex } from './meteora';


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