A complete autonomous Solana trading agent system with 4 layers: Observation, Decision, Execution, and Learning. Built with React, Express, tRPC, and MySQL.
1. 👁 Observation Layer (Data Engine)
- Real-time token data ingestion from Helius API
- Market snapshot collection (price, volume, liquidity, RSI, MACD, sentiment)
- Wallet activity tracking and whale detection
- Buy/sell pressure analysis
- Technical indicator calculation
2. 🧠 Decision Layer (Strategy Agent)
- Weighted scoring system with configurable parameters
- Liquidity score: Evaluates pool depth and market stability
- Volume score: Analyzes trading activity relative to market cap
- Wallet score: Tracks whale accumulation patterns
- Composite score:
liquidity_score * 0.3 + volume_score * 0.3 + wallet_score * 0.4 - Decision logic: BUY (score > 0.75), SELL (score < 0.25), HOLD (0.25-0.75), SKIP
3. ⚡ Execution Layer (Execution Engine)
- Automated trade execution based on agent decisions
- Position tracking with entry/exit prices
- Risk management: Stop loss and take profit levels
- Position sizing based on max position limits
- Transaction history and execution validation
- Real-time PnL calculation
4. 📈 Learning Layer (Learning Engine)
- Performance metrics calculation (win rate, Sharpe ratio, max drawdown)
- Decision feedback tracking
- Weight optimization based on historical success rates
- Continuous improvement through feedback loops
- Performance history and trend analysis
12 Tables:
users- User authenticationmarket_snapshots- Historical token datawallet_activity- Whale wallet movementsagent_config- Agent configuration and weightsagent_decisions- All agent decisions with scoresagent_signals- Market signals and research datatrade_executions- Executed tradespositions- Open and closed positionsperformance_metrics- Trading performance datadecision_feedback- Decision outcomesweight_history- Weight adjustments over timetelegram_config- Telegram bot integration
- Node.js 22+
- MySQL/TiDB database
- Helius API key (optional, for real Solana data)
- Telegram bot token (optional, for notifications)
# Install dependencies
pnpm install
# Set up environment variables
cp .env.example .env
# Run database migrations
pnpm drizzle-kit generate
pnpm drizzle-kit migrate
# Start development server
pnpm devDATABASE_URL=mysql://user:password@localhost/agent_learning_machine
JWT_SECRET=your-secret-key
HELIUS_API_KEY=your-helius-api-key
TELEGRAM_BOT_TOKEN=your-telegram-bot-tokenGET /api/trpc/agent.getConfigs- Get all agent configsPOST /api/trpc/agent.createConfig- Create new configGET /api/trpc/agent.getConfig- Get specific configPOST /api/trpc/agent.updateConfig- Update weights/thresholds
POST /api/trpc/data.collectToken- Collect data for single tokenPOST /api/trpc/data.collectMultiple- Collect data for multiple tokensGET /api/trpc/data.getTrend- Get market trend
GET /api/trpc/strategy.analyzeToken- Analyze single tokenGET /api/trpc/strategy.analyzeMultiple- Analyze multiple tokensGET /api/trpc/strategy.getRecommendations- Get portfolio recommendationsGET /api/trpc/strategy.getDecisions- Get recent decisionsGET /api/trpc/strategy.getSignals- Get active signals
GET /api/trpc/execution.getPortfolio- Get portfolio summaryGET /api/trpc/execution.getPositions- Get open positionsGET /api/trpc/execution.getTradeHistory- Get trade historyPOST /api/trpc/execution.updatePrices- Update position prices
GET /api/trpc/learning.getMetrics- Get performance metricsGET /api/trpc/learning.getHistory- Get performance historyGET /api/trpc/learning.getLatest- Get latest metricsPOST /api/trpc/learning.runCycle- Run learning cycle
GET /api/trpc/dashboard.getSummary- Get complete dashboard data
- Evaluates pool depth and stability
- Ideal ratio: 10-30% of market cap
- High liquidity = easier entries/exits
- Analyzes trading activity
- Ideal ratio: 10-50% of market cap
- High volume = healthy market activity
- Detects whale accumulation
- Tracks large wallet movements
- Positive signal: Whales accumulating
- Negative signal: Whales dumping
- RSI (30 = oversold, 70 = overbought)
- MACD (positive = bullish)
- Sentiment (0-1 scale)
- Buy/sell pressure ratio
// Default weights
liquidityWeight: 0.30
volumeWeight: 0.30
walletWeight: 0.40
// Customize via API
POST /api/trpc/agent.updateConfig
{
configId: 1,
liquidityWeight: 0.25,
volumeWeight: 0.35,
walletWeight: 0.40
}buyThreshold: 0.75 // Score must exceed this to BUY
sellThreshold: 0.25 // Score must fall below this to SELL
holdThreshold: 0.50 // Between sell and buy = HOLDmaxPositionSize: 1000 // Max $ per position
stopLossPercent: 5 // Stop loss at 5% below entry
takeProfitPercent: 15 // Take profit at 15% above entry- Win Rate: Percentage of profitable trades
- Profit Factor: Gross profit / Gross loss
- Sharpe Ratio: Risk-adjusted returns
- Max Drawdown: Largest peak-to-trough decline
- Decision Accuracy: Percentage of correct decisions
- Average Confidence: Mean confidence of all decisions
Send market snapshots and trading decisions to Telegram:
// Send market snapshot
await sendMarketSnapshot(configId, tokenSymbol, snapshot);
// Send trading decision
await sendTradingDecision(configId, tokenSymbol, decision);
// Send position update
await sendPositionUpdate(configId, tokenSymbol, update);
// Send performance report
await sendPerformanceReport(configId, metrics);The agent continuously learns from outcomes:
- Record Feedback: Track actual prices vs predicted scores
- Analyze Signals: Identify which signals were effective
- Calculate Metrics: Compute performance statistics
- Optimize Weights: Adjust scoring weights based on success rates
- Store History: Maintain audit trail of all changes
- Real-time Metrics: Live PnL, win rate, Sharpe ratio
- Position Tracking: Open positions with unrealized PnL
- Decision History: Recent agent decisions with confidence scores
- Active Signals: Current market signals and their strength
- Performance Charts: Historical performance visualization
- Configuration UI: Adjust weights and thresholds in real-time
- JWT-based authentication
- Protected procedures for sensitive operations
- Database encryption for sensitive data
- Rate limiting on API endpoints
- Input validation on all endpoints
/agent-learning-machine
├── client/ # React frontend
│ ├── src/
│ │ ├── pages/ # Page components
│ │ ├── components/ # Reusable components
│ │ └── lib/ # Utilities
├── server/ # Express backend
│ ├── engines/ # Agent engines
│ │ ├── dataEngine.ts
│ │ ├── strategyAgent.ts
│ │ ├── executionEngine.ts
│ │ ├── learningEngine.ts
│ │ └── telegramEngine.ts
│ ├── routers.ts # tRPC routes
│ └── db.ts # Database helpers
├── drizzle/ # Database schema
│ └── schema.ts
└── shared/ # Shared types
pnpm testpnpm build
pnpm startThe project is ready for deployment on Manus hosting:
- Create a checkpoint:
webdev_save_checkpoint - Click the Publish button in the Management UI
- Configure custom domain if desired
- Data Engine: Helius API integration, technical indicators
- Strategy Agent: Scoring system, decision logic
- Execution Engine: Trade execution, position management
- Learning Engine: Performance tracking, weight optimization
- Telegram Integration: Notifications and alerts
This is an autonomous agent system. Contributions should focus on:
- Improving scoring algorithms
- Adding new signal types
- Enhancing risk management
- Optimizing performance
MIT License - See LICENSE file for details
- Solana Development: https://docs.solana.com
- Helius API: https://docs.helius.xyz
- tRPC: https://trpc.io
- Drizzle ORM: https://orm.drizzle.team
For issues and questions:
- Check the dashboard for real-time status
- Review performance metrics and decision history
- Adjust configuration based on market conditions
- Run learning cycles to optimize weights
Built with ❤️ for autonomous trading on Solana