A complete, production-ready automated trading bot for Solana perpetuals with Phantom wallet integration, leveraging up to 10x on Drift Protocol.
LEVERAGED TRADING IS EXTREMELY RISKY
- You can lose your entire investment quickly
- Leverage amplifies both gains AND losses
- Only trade with funds you can afford to lose completely
- This bot executes real trades with real money
- No guarantees of profit - trading is inherently risky
- Past performance does not indicate future results
USE AT YOUR OWN RISK
- β Phantom Wallet Integration - Secure transaction signing (no private keys stored)
- β Drift Protocol - Primary perpetuals DEX on Solana
- β Symbol Allowlist - Hardcoded to BTC, ETH, SOL, HYPE, ZEC only
- β 10x Leverage - Configurable up to maximum of 10x
- β Fixed Strategy - 20% take-profit / 5% stop-loss (4:1 RR)
- β 60% Position Sizing - Uses 60% of available equity per trade
- β One Position at a Time - Prevents overexposure
- β Daily Loss Cap - Auto-stops at 3% daily loss (default)
- β Consecutive Loss Limit - 6-hour cooldown after 3 losses
- β Slippage Protection - Rejects trades exceeding 0.3% slippage
- β Order Timeout - Auto-cancels unfilled orders after 30s
- β TP/SL Enforcement - Immediate placement after entry
- β EMA Crossover - Fast (9) / Slow (21) exponential moving averages
- β
Pluggable Interface - Swap strategies easily via
IStrategy - β Signal Validation - Three-layer allowlist enforcement
- β Next.js Web App - Modern, responsive dashboard
- β Real-time Updates - WebSocket streaming for instant feedback
- β Paper Trading Mode - Test strategies risk-free
- β Live Logs - Streaming bot activity logs
- β Trade Export - Download CSV of all trades
- β SQLite Storage - Persistent trade/equity/log history
Autotrader/
βββ backend/ # Trading engine
β βββ src/
β β βββ exchanges/ # Exchange adapters (Drift, Paper)
β β βββ strategies/ # Signal generation (EMA crossover)
β β βββ risk/ # Risk management
β β βββ database/ # SQLite storage
β β βββ worker/ # Main trading bot
β β βββ server/ # API & WebSocket server
β β βββ utils/ # Logger, helpers
β βββ package.json
βββ frontend/ # Next.js web UI
β βββ src/
β β βββ app/ # Pages (Next.js 14 app router)
β β βββ components/ # React components
β β βββ contexts/ # Wallet context provider
β β βββ hooks/ # Custom hooks (API, WebSocket)
β β βββ styles/ # Global CSS
β βββ package.json
βββ shared/ # Shared types & constants
β βββ src/
β β βββ constants.ts # Allowlist, enums
β β βββ types.ts # TypeScript interfaces
β βββ package.json
βββ .env.example # Environment template
βββ package.json # Root workspace config
βββ README.md
- Node.js >= 18.0.0
- npm or yarn
- Phantom Wallet (browser extension)
- Solana RPC URL (Alchemy, QuickNode, or public RPC)
git clone <repository-url>
cd Autotradernpm run install:allThis installs dependencies for root, backend, frontend, and shared packages.
cp .env.example .envEdit .env with your settings:
# RPC URL (required)
SOLANA_RPC_URL=https://api.mainnet-beta.solana.com
# Exchange (drift | jupiter)
EXCHANGE=drift
# Active symbol (must be in allowlist)
ACTIVE_SYMBOL=SOL
SYMBOLS=BTC,ETH,SOL,HYPE,ZEC
# Position sizing
ALLOCATION_PCT=0.60
MAX_LEVERAGE=10
# Strategy (fixed)
TAKE_PROFIT_PCT=0.20
STOP_LOSS_PCT=0.05
# Risk guardrails
DAILY_LOSS_CAP_PCT=0.03
MAX_CONSECUTIVE_LOSSES=3
MAX_SLIPPAGE_PCT=0.003
# Trading mode
PAPER_TRADING=true # Set to false for live tradingnpm run build --workspace=sharedRun both backend and frontend in parallel:
npm run devThis starts:
- Backend API: http://localhost:3001
- Frontend UI: http://localhost:3000
Build and run in production:
npm run build
npm startNavigate to http://localhost:3000 in your browser.
Click "Connect Wallet" button in the top-right corner.
Note: Ensure Phantom is installed and you have USDC collateral deposited on Drift Protocol (for live trading).
- Trading Mode: Choose Paper (safe) or Live (real money)
- Active Symbol: Select from BTC, ETH, SOL, HYPE, or ZEC
- Unavailable markets will be marked (e.g., HYPE, ZEC on Drift)
Click "π Start Trading"
The bot will:
- Connect to exchange
- Validate market availability
- Initialize risk management
- Begin monitoring for signals
- Equity Card: Total equity, daily PnL, free collateral
- Risk Card: Consecutive losses, daily loss cap, cooldown status
- Position Card: Current open position with unrealized PnL
- Orders Table: Active TP/SL orders
- Live Logs: Real-time bot activity
Click "βΉοΈ Stop Trading" to gracefully shut down.
- Fast EMA: 9 periods
- Slow EMA: 21 periods
- Long Signal: Fast crosses above Slow (bullish)
- Short Signal: Fast crosses below Slow (bearish)
- Entry: Market order at signal price
- Size: 60% of free collateral Γ 10x leverage
- Immediate TP/SL: Placed as soon as entry fills
- Take Profit: +20% from entry
- Stop Loss: -5% from entry
- RR Ratio: 4:1 (risking 5% to gain 20%)
- Max Leverage: 10x (amplifies PnL by 10x)
- One Position: Never holds multiple positions per market
The bot REFUSES to trade any symbol not in the hardcoded allowlist:
const ALLOWED_SYMBOLS = ["BTC", "ETH", "SOL", "HYPE", "ZEC"];Enforcement at three layers:
- UI dropdown (only shows allowed symbols)
- Strategy validation (rejects signals for disallowed symbols)
- Exchange adapter (hard fails on disallowed symbol orders)
Bot stops trading when daily loss exceeds 3% (default):
Daily Loss = (Current Equity - Starting Equity) / Starting Equity
Resets at 00:00 UTC.
After 3 consecutive losing trades:
- Bot enters 6-hour cooldown
- No new trades allowed until cooldown expires
- Resets on next winning trade
Market orders rejected if estimated slippage > 0.3%:
- Protects against poor fills in low liquidity
- Calculated based on AMM depth
All data persists to ./backend/data/trades.db:
- Trades: Every executed trade
- Orders: Order history
- Positions: Position open/close records
- Equity Snapshots: Periodic equity tracking
- Logs: All bot logs
- Signals: Trading signals history
Click "π₯ Export" in the UI to download CSV:
id,order_id,symbol,side,size,price,fee,timestamp,position_id
trade-1,order-123,SOL,LONG,10.5,98.50,0.49,1704067200000,pos-1| Variable | Default | Description |
|---|---|---|
SOLANA_RPC_URL |
Required | Solana RPC endpoint |
ACTIVE_SYMBOL |
SOL | Symbol to trade (must be in allowlist) |
ALLOCATION_PCT |
0.60 | % of equity per trade (60%) |
MAX_LEVERAGE |
10 | Leverage (1-10x) |
PAPER_TRADING |
true | Paper mode (true) or live (false) |
| Variable | Default | Description |
|---|---|---|
TAKE_PROFIT_PCT |
0.20 | TP distance (20%) |
STOP_LOSS_PCT |
0.05 | SL distance (5%) |
TIMEFRAME |
5m | Candle timeframe |
EMA_FAST |
9 | Fast EMA period |
EMA_SLOW |
21 | Slow EMA period |
| Variable | Default | Description |
|---|---|---|
DAILY_LOSS_CAP_PCT |
0.03 | Daily loss limit (3%) |
MAX_CONSECUTIVE_LOSSES |
3 | Losses before cooldown |
CONSECUTIVE_LOSS_COOLDOWN_HOURS |
6 | Cooldown duration |
MAX_SLIPPAGE_PCT |
0.003 | Max slippage (0.3%) |
- Bot NEVER requests or stores seed phrases
- All transactions signed by Phantom wallet
- User maintains full custody of funds
- Bot generates unsigned transaction
- Transaction sent to Phantom for approval
- User reviews and signs in Phantom
- Signed transaction broadcast to Solana
Current implementation is read-only for Drift Protocol:
- Can fetch positions, orders, equity
- Cannot place orders without Phantom integration
- Order placement methods throw informative errors
TODO for Production: Integrate Phantom wallet adapter in backend for signing.
Error: "Symbol not in allowlist"
- Fix: Edit
.env, setACTIVE_SYMBOLto one of: BTC, ETH, SOL, HYPE, ZEC
Error: "Market not available on exchange"
- Fix: Choose a different symbol. HYPE and ZEC may not be on Drift.
Error: "WebSocket disconnected"
- Fix: Ensure backend is running on port 3001
- Check firewall/proxy settings
- Cause: Paper mode needs price feed integration
- Fix: Currently uses manual price updates. Integrate Pyth/Switchboard oracle for production.
- Info: Bot auto-pauses when daily loss exceeds limit
- Fix: Wait until next UTC day for reset, or adjust
DAILY_LOSS_CAP_PCT
-
Candle Data: No integrated data provider (Pyth/Switchboard)
- Strategy uses placeholder candle fetching
- Implement real-time OHLCV feed for production
-
Order Placement: Drift adapter is read-only
- Requires Phantom wallet integration for signing
- Paper mode fully functional
-
Symbol Support: HYPE and ZEC unavailable on Drift
- Use Jupiter Perps adapter (implement separately)
-
Single Market: Bot trades one symbol at a time
- Multi-symbol support requires architecture changes
- Pyth/Switchboard oracle integration
- Jupiter Perps adapter implementation
- Multi-symbol concurrent trading
- Advanced strategies (RSI, Bollinger Bands)
- Backtesting framework
- Mobile-responsive UI improvements
- Email/Telegram notifications
Base URL: http://localhost:3001/api
Get current bot status.
Response:
{
"success": true,
"data": {
"status": "RUNNING",
"mode": "PAPER",
"activeSymbol": "SOL",
"equity": { ... },
"position": { ... }
}
}Start the trading bot.
Body:
{
"walletAddress": "7xKXtg2CW87d97TXJSDpbD5jBkheTqA83TZRuJosgAsU"
}Stop the trading bot.
Get available markets.
Get trade history (query param: ?limit=100).
Download trades as CSV.
Connection: ws://localhost:3001
Incoming Events:
BOT_STATE: Full bot state updateLOG: Log messageTRADE: New trade executedPOSITION_UPDATE: Position changedORDER_UPDATE: Order status changed
- Set
PAPER_TRADING=truein.env - Start bot - simulates all trading
- No real money at risk
- $10,000 starting equity (simulated)
- Connect Phantom wallet
- Start bot in paper mode
- Verify equity card updates
- Check risk management triggers
- Test symbol switching
- Verify TP/SL placement (paper mode)
- Export trades to CSV
- Stop bot gracefully
This project is provided as-is for educational purposes.
No warranty or guarantees of profitability.
Contributions welcome! Areas for improvement:
- Data Providers: Integrate Pyth/Switchboard
- Jupiter Perps: Implement adapter
- Strategies: Add RSI, MACD, Bollinger Bands
- Testing: Add unit/integration tests
- Documentation: Improve inline code comments
For issues, questions, or feedback:
- Open a GitHub issue
- Check existing documentation
- Review code comments for implementation details
Built with β€οΈ for the Solana trading community
Remember: Trade responsibly. Never risk more than you can afford to lose.