Crypto-Stocks is an autonomous trading agent system designed to identify and capitalize on arbitrage opportunities across crypto exchanges and stock data providers. The system uses real-time price monitoring, leverage calculations, and AI-driven sentiment analysis to target 20-30% returns.
Core Strategies:
- Cross-Exchange Arbitrage: Price gaps between exchanges
- Leveraged Trading: 5x, 10x, 20x multipliers on high-probability opportunities
- Risk Management: Kill switch, margin monitoring, PDT compliance
- AI Sentiment: Long-term analysis using Gemini 2.0 Flash
Stack: TypeScript, Node.js, CCXT, Drizzle ORM, PostgreSQL (Railway), OpenRouter
/agent
βββ src/
β βββ agents/
β β βββ crypto/
β β β βββ arbitrage.ts # WebSocket listener (CCXT Pro)
β β β βββ leverage.ts # ROI calculator (5x, 10x, 20x)
β β β βββ index.ts # Crypto agents runner
β β βββ stocks/
β β βββ arbitrage.ts # Price gap scanner (Alpha Vantage/Polygon)
β β βββ leverage.ts # Margin/PDT rule tracker
β β βββ long-term.ts # AI sentiment analysis
β β βββ index.ts # Stock agents runner
β βββ database/
β β βββ migrations.sql # SQL schema for Railway
β βββ db/
β β βββ schema.ts # Drizzle ORM schema
β β βββ index.ts # Database connection
β βββ index.ts # Main entry point
βββ package.json
βββ drizzle.config.ts
The system uses 4 core tables on Railway PostgreSQL:
Real-time pricing data from exchanges and data providers
- Exchange name, symbol, best bid/ask, timestamp
- Indexes on symbol/timestamp for fast queries
Detected arbitrage opportunities with leverage calculations
- Asset type (crypto/stock), price gap %, leverage multiplier
- Projected ROI after fees, status tracking
Kill switch and performance tracking (singleton table)
- Consecutive losses counter
- Total P/L, win rate, kill switch status
- Auto-activates after 3 losses in 24 hours
History of all simulated/real trades
- Buy/sell actions, fees paid, profit/loss
- Links to opportunities for backtesting
- Node.js 18+ (or use Docker)
- Railway PostgreSQL database
- API Keys (optional but recommended):
- OpenRouter (for AI sentiment analysis)
- Alpha Vantage (for stock prices)
- Polygon.io (for stock prices)
cd agent
npm installCopy .env.example to .env and configure:
# Database (Railway)
DATABASE_URL="postgresql://user:pass@host:port/dbname"
# Optional: Stock Data APIs
ALPHA_VANTAGE_API_KEY="your_key_here"
POLYGON_API_KEY="your_key_here"
# Optional: AI Analysis
OPENROUTER_API_KEY="your_key_here"
# Agent Control (default: both enabled)
RUN_CRYPTO=true
RUN_STOCKS=trueRun the SQL migration on Railway:
npm run db:migrateOr manually run agent/src/database/migrations.sql in Railway's PostgreSQL console.
Run all agents:
npm run devRun crypto only:
npm run run:cryptoRun stocks only:
npm run run:stocksArbitrage Agent:
- Monitors BTC/USDT on Coinbase & Kraken via WebSocket
- Detects price gaps between exchanges
- Logs data to
market_depthtable every tick
Leverage Agent:
- Scans
market_depthevery 10 seconds - Calculates ROI with 5x, 10x, 20x leverage
- Logs opportunities hitting 20-30% target (after 0.2% fees)
- Respects kill switch (3 losses in 24h)
Arbitrage Agent:
- Polls Alpha Vantage & Polygon every 60 seconds
- Detects price gaps between data providers
- Logs data for top stocks (AAPL, MSFT, GOOGL, TSLA, NVDA)
Leverage Agent:
- Scans for stock arbitrage opportunities
- Enforces PDT rules (Pattern Day Trader)
- Accounts <$25k: Max 3 day trades per 5 days, 2x leverage
- Accounts β₯$25k: Unlimited day trades, 4x leverage
- Calculates ROI with available leverage
Long-Term Agent:
- AI-driven sentiment analysis (Gemini 2.0 Flash)
- Analyzes market trends, fundamentals, technical indicators
- Provides buy/sell/hold recommendations
- Runs every hour for configured symbols
Automatically triggered when:
- 3 consecutive losses within 24 hours
- Prevents further opportunity logging
- Must be manually reset after review
- Real-time liquidation price monitoring (planned)
- Slippage checks before execution
- Position sizing based on account balance
All trades are simulated by default for safety:
- Logs to
execution_logtable - No real money at risk
- Perfect for backtesting and validation
# Clone the repository
git clone git@github.com:ChrisForti/crypto-stocks.git
cd crypto-stocks/agent
# Install dependencies
npm install
# Configure environment
cp .env.example .env
nano .env # Add your DATABASE_URL and API keysnpm run db:migrate# Install PM2 globally
npm install -g pm2
# Start all agents
pm2 start npm --name "arbitrage-agent" -- run start
# Or use tsx for development
pm2 start tsx --name "arbitrage-agent" -- src/index.ts
# View logs
pm2 logs arbitrage-agent
# Monitor status
pm2 status
# Restart
pm2 restart arbitrage-agent# Save PM2 configuration
pm2 save
# Setup startup script
pm2 startup
# Follow the instructions printed| Variable | Description | Required | Default |
|---|---|---|---|
DATABASE_URL |
Railway PostgreSQL connection string | β Yes | - |
RUN_CRYPTO |
Enable crypto agents | β No | true |
RUN_STOCKS |
Enable stock agents | β No | true |
OPENROUTER_API_KEY |
OpenRouter API for AI analysis | β No | - |
ALPHA_VANTAGE_API_KEY |
Alpha Vantage for stock prices | β No | - |
POLYGON_API_KEY |
Polygon.io for stock prices | β No | - |
The agents log all opportunities to the database. Query them:
-- View recent opportunities
SELECT * FROM leverage_opportunities
WHERE projected_roi_pct >= 20
ORDER BY created_at DESC
LIMIT 20;
-- Check kill switch status
SELECT * FROM risk_management;
-- View win rate
SELECT
asset_type,
COUNT(*) as total_trades,
SUM(CASE WHEN profit_loss > 0 THEN 1 ELSE 0 END) as wins,
AVG(profit_loss) as avg_profit
FROM execution_log
GROUP BY asset_type;After 48 hours of simulation:
-- Export opportunities to CSV
COPY (
SELECT * FROM leverage_opportunities
WHERE created_at > NOW() - INTERVAL '48 hours'
) TO '/tmp/opportunities.csv' CSV HEADER;Feed this to Gemini 2.0:
"Which of these opportunities were actually executable during high-volatility periods?"
This software is for educational and research purposes only.
- Trading with leverage involves significant risk of total capital loss
- All trades are simulated by default - no real execution
- Always test thoroughly before considering live trading
- Past performance does not guarantee future results
- Consult a financial advisor before making investment decisions
MIT License - See LICENSE file for details
Contributions welcome! Please open an issue or submit a pull request.