An intelligent multi-chain DeFi trading bot powered by SpoonOS Agent Framework, featuring AI-driven market analysis, risk assessment, and automated trade execution.
π₯ Project Demo: An intelligent multi-chain DeFi trading bot β Live Demo
- π§ AI Market Intelligence: Real-time multi-chain opportunity scanning
- π‘οΈ Deterministic Firewall: Rigid checks on Solvency, Slippage, and Whitelists (Zero AI Hallucinations)
- β Confirmation Manager: Preventing "Ghost Trades" by waiting for block finality
β οΈ Risk Assessment: Advanced AI-powered risk analysis and portfolio optimization- π Smart Execution: Optimal DEX aggregation and MEV-protected trading
- π Position Management: Automated stop-loss, take-profit, and portfolio tracking
- β½ Gas Optimization: Intelligent gas pricing and transaction timing
- π Multi-Chain Support: Ethereum, Polygon, BSC, Arbitrum
The bot uses a novel Dual-Layer "Hybrid Intelligence" Architecture powered by SpoonOS. This design solves the "hallucination problem" by separating AI decision-making from high-stakes execution.
- Role: Strategy, Intent, and Adaptation.
- Components:
Market Intelligence Agent,Risk Assessment Agent,Execution Manager Agent. - Function: Consumes market data, news, and graphs to form an intent (e.g., "Accumulate ETH"). It hands off structured requests to the Body.
- Role: Validation, Routing, Execution, and Finality.
- Components:
OrderManager: The central nervous system that orchestrates the workflow.SafeExecutionEngine(The Firewall): A rigid Python/Rust sandbox that validates every trade againstconfig.jsonwhitelists, solvency checks, and risk caps. If the AI requests a dangerous trade, the Firewall kills it.ConfirmationManager: Tracks transaction finality (block confirmations) to ensure trades are irreversible before updating state.
graph TD
subgraph Brain ["π§ Cognitive Layer (SpoonOS Agents)"]
A[Market Intelligence] --> B[Execution Agent]
R[Risk Agent] --> B
end
subgraph Body ["π‘οΈ Deterministic Layer (Python/Rust)"]
B -- "Intent (OrderRequest)" --> OM[OrderManager]
OM --> DA[DEX Aggregator]
DA -- "Route" --> OM
OM --> FW{Firewall <br/> SafeExecutionEngine}
FW -- "Reject" --> B
FW -- "Approve" --> EX[Execution]
EX --> CM[Confirmation Manager]
CM -- "Finalized" --> OM
end
The rust-engine/ directory contains a prototype of the execution layer rewritten in Rust for microsecond latency and type-safe financial operations.
- Python 3.10+
- Node.js 16+ (for some MCP tools)
- Git
- Clone the repository
git clone https://github.com/CodeKage25/defi-ai-trading-bot.git
cd defi-ai-trading-bot- Set up virtual environment
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate- Install dependencies
pip install -r requirements.txt- Configure environment variables
cp config/.env.example .env
# Edit .env with your API keys and wallet details- Install the package
pip install -e .- Set up API keys in
.env:
# LLM APIs
OPENAI_API_KEY=sk-your-openai-key
ANTHROPIC_API_KEY=sk-your-anthropic-key
# Blockchain
PRIVATE_KEY=0x1234567890abcdef...
ETHEREUM_RPC_URL=https://eth-mainnet.alchemyapi.io/v2/your-key
# Data providers
CHAINBASE_API_KEY=your-chainbase-key
COINGECKO_API_KEY=your-coingecko-key- Review configuration in
config/config.json:
defi-bot config# Scan all supported chains
defi-bot scan
# Scan specific chains and tokens
defi-bot scan -c ethereum -c polygon -t ETH -t USDC# Assess risk for a strategy
defi-bot risk "ETH/USDC arbitrage" 1000
# Risk assessment with specific tokens
defi-bot risk "Yield farming" 5000 -t ETH -t USDC# Execute a simple trade
defi-bot trade ETH USDC 1.5 --chain ethereum
# Trade with custom slippage
defi-bot trade BTC ETH 0.1 --chain ethereum --slippage 0.005# Monitor active positions
defi-bot positions
# View portfolio dashboard
defi-bot dashboard# Run arbitrage strategy
defi-bot strategy arbitrage --amount 1000 -c ethereum -c polygon
# Run yield farming strategy
defi-bot strategy yield_farming --amount 5000 -c ethereum
# Run with custom config
defi-bot strategy dca --config strategies/conservative_dca.json# Check system status
defi-bot status
# View configuration
defi-bot configLaunch the real-time dashboard:
defi-bot dashboard --refresh 30Features:
- Real-time portfolio tracking
- Active position monitoring
- Strategy performance metrics
- Market opportunity alerts
Create a strategy configuration file:
{
"strategy": "arbitrage",
"parameters": {
"chains": ["ethereum", "polygon"],
"tokens": ["ETH", "USDC", "WBTC"],
"min_profit_threshold": 0.005,
"max_position_size": 0.1,
"risk_tolerance": "moderate"
},
"risk_management": {
"stop_loss": 0.05,
"take_profit": 0.15,
"max_drawdown": 0.1
}
}Run with custom config:
defi-bot strategy arbitrage --config my_strategy.jsonimport asyncio
from src.cli.main import TradingBotOrchestrator
async def main():
bot = TradingBotOrchestrator()
# Scan markets
opportunities = await bot.scan_markets(
chains=["ethereum", "polygon"],
tokens=["ETH", "USDC"]
)
# Assess risk
risk_analysis = await bot.assess_risk("arbitrage", 1000)
# Execute trade if conditions are met
if risk_analysis.get("risk_score", 10) < 7:
result = await bot.execute_trade("ETH", "USDC", 1.0)
# Monitor positions
await bot.monitor_positions()
if __name__ == "__main__":
asyncio.run(main())defi-ai-trading-bot/
βββ src/
β βββ agents/ # AI agents
β β βββ market_intelligence.py
β β βββ risk_assessment.py
β β βββ execution_manager.py
β βββ strategies/ # Trading strategies
β βββ data/ # Data sources and APIs
β βββ execution/ # Trade execution logic
β βββ risk/ # Risk management
β βββ interfaces/ # Web dashboard, APIs
βββ config/
β βββ config.json # Main configuration
β βββ .env.example # Environment template
βββ tests/ # Test suite
βββ docs/ # Documentation
βββ requirements.txt # Dependencies
# Run all tests
pytest
# Run with coverage
pytest --cov=src --cov-report=html
# Run specific test category
pytest tests/test_agents.py# Install development dependencies
pip install -e ".[dev]"
# Set up pre-commit hooks
pre-commit install
# Run linting
black src/
flake8 src/
mypy src/- Position Limits: Automatic position sizing based on portfolio risk
- Stop-Loss Protection: Automated stop-loss and take-profit orders
- Smart Contract Analysis: AI-powered contract security assessment
- Gas Optimization: MEV protection and gas cost minimization
- Multi-signature Support: Enterprise-grade wallet security
- Never commit private keys to version control
- Use hardware wallets for production deployments
- Implement position limits to control risk exposure
- Monitor gas prices to avoid MEV attacks
- Regular security audits of smart contract interactions
# Use environment variables for sensitive data
export PRIVATE_KEY="0x..."
# Or use mnemonic phrases
export MNEMONIC="your twelve word mnemonic phrase here"
# For production, consider using a hardware wallet or multi-sig
export MULTISIG_WALLET_ADDRESS="0x..."The bot tracks:
- Total P&L and ROI
- Win rate and average trade duration
- Gas optimization savings
- Risk-adjusted returns (Sharpe ratio)
- Maximum drawdown
Configure notifications via:
- Telegram: Real-time trade and position updates
- Discord: Strategy performance alerts
- Email: Daily/weekly performance reports
# Set up Telegram notifications
export TELEGRAM_BOT_TOKEN="your-bot-token"
export TELEGRAM_CHAT_ID="your-chat-id"- β Core agent architecture (SpoonOS)
- β Dual-Layer "Brain/Body" Separation
- β
Deterministic Firewall (
SafeExecutionEngine) - β
Transaction Finality Tracking (
ConfirmationManager) - β Basic market scanning
- β Risk assessment framework
- β Trade execution engine
- Advanced yield farming strategies
- Cross-chain bridge integration
- Options trading support
- Web dashboard UI
- Machine learning strategy optimization
- Social trading features
- Institutional-grade reporting
- Mobile app
- Decentralized governance token
- Strategy marketplace
- Advanced derivatives trading
- Global regulatory compliance
We welcome contributions! Please see our Contributing Guide for details.
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
This project is licensed under the MIT License - see the LICENSE file for details.
- Documentation: docs/
- Issues: GitHub Issues
- Discord: DeFi Intelligence Community
- Email: babzchizzy27@gmail.com
This software is for educational and experimental purposes only. Trading cryptocurrencies and DeFi protocols involves substantial risk of loss. The authors are not responsible for any financial losses incurred through the use of this software.
Always:
- Test thoroughly on testnets first
- Start with small amounts
- Understand the risks involved
- Never invest more than you can afford to lose
- Built with SpoonOS Agent Framework
- Powered by OpenAI GPT-4 and Anthropic Claude
- Market data from Chainbase, CoinGecko, and DEX APIs
- Special thanks to the DeFi and Web3 community
Happy Trading! π