Skip to content

btcdecky-cmd/agent-learning-machsolana

Repository files navigation

Agent Learning Machine

A complete autonomous Solana trading agent system with 4 layers: Observation, Decision, Execution, and Learning. Built with React, Express, tRPC, and MySQL.

🏗️ Architecture

4-Layer Agent System

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

Database Schema

12 Tables:

  • users - User authentication
  • market_snapshots - Historical token data
  • wallet_activity - Whale wallet movements
  • agent_config - Agent configuration and weights
  • agent_decisions - All agent decisions with scores
  • agent_signals - Market signals and research data
  • trade_executions - Executed trades
  • positions - Open and closed positions
  • performance_metrics - Trading performance data
  • decision_feedback - Decision outcomes
  • weight_history - Weight adjustments over time
  • telegram_config - Telegram bot integration

🚀 Getting Started

Prerequisites

  • Node.js 22+
  • MySQL/TiDB database
  • Helius API key (optional, for real Solana data)
  • Telegram bot token (optional, for notifications)

Installation

# 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 dev

Environment Variables

DATABASE_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-token

📊 API Endpoints

Agent Configuration

  • GET /api/trpc/agent.getConfigs - Get all agent configs
  • POST /api/trpc/agent.createConfig - Create new config
  • GET /api/trpc/agent.getConfig - Get specific config
  • POST /api/trpc/agent.updateConfig - Update weights/thresholds

Data Collection

  • POST /api/trpc/data.collectToken - Collect data for single token
  • POST /api/trpc/data.collectMultiple - Collect data for multiple tokens
  • GET /api/trpc/data.getTrend - Get market trend

Strategy Analysis

  • GET /api/trpc/strategy.analyzeToken - Analyze single token
  • GET /api/trpc/strategy.analyzeMultiple - Analyze multiple tokens
  • GET /api/trpc/strategy.getRecommendations - Get portfolio recommendations
  • GET /api/trpc/strategy.getDecisions - Get recent decisions
  • GET /api/trpc/strategy.getSignals - Get active signals

Execution

  • GET /api/trpc/execution.getPortfolio - Get portfolio summary
  • GET /api/trpc/execution.getPositions - Get open positions
  • GET /api/trpc/execution.getTradeHistory - Get trade history
  • POST /api/trpc/execution.updatePrices - Update position prices

Learning

  • GET /api/trpc/learning.getMetrics - Get performance metrics
  • GET /api/trpc/learning.getHistory - Get performance history
  • GET /api/trpc/learning.getLatest - Get latest metrics
  • POST /api/trpc/learning.runCycle - Run learning cycle

Dashboard

  • GET /api/trpc/dashboard.getSummary - Get complete dashboard data

🎯 Scoring System

Liquidity Score

  • Evaluates pool depth and stability
  • Ideal ratio: 10-30% of market cap
  • High liquidity = easier entries/exits

Volume Score

  • Analyzes trading activity
  • Ideal ratio: 10-50% of market cap
  • High volume = healthy market activity

Wallet Score

  • Detects whale accumulation
  • Tracks large wallet movements
  • Positive signal: Whales accumulating
  • Negative signal: Whales dumping

Technical Score

  • RSI (30 = oversold, 70 = overbought)
  • MACD (positive = bullish)
  • Sentiment (0-1 scale)
  • Buy/sell pressure ratio

🔧 Configuration

Adjust Scoring Weights

// 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
}

Set Decision Thresholds

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 = HOLD

Risk Management

maxPositionSize: 1000       // Max $ per position
stopLossPercent: 5          // Stop loss at 5% below entry
takeProfitPercent: 15       // Take profit at 15% above entry

📈 Performance Metrics

  • 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

🔔 Telegram Integration

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);

🧠 Learning Cycle

The agent continuously learns from outcomes:

  1. Record Feedback: Track actual prices vs predicted scores
  2. Analyze Signals: Identify which signals were effective
  3. Calculate Metrics: Compute performance statistics
  4. Optimize Weights: Adjust scoring weights based on success rates
  5. Store History: Maintain audit trail of all changes

📊 Dashboard Features

  • 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

🔐 Security

  • JWT-based authentication
  • Protected procedures for sensitive operations
  • Database encryption for sensitive data
  • Rate limiting on API endpoints
  • Input validation on all endpoints

📝 Development

Project Structure

/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

Running Tests

pnpm test

Building for Production

pnpm build
pnpm start

🚀 Deployment

The project is ready for deployment on Manus hosting:

  1. Create a checkpoint: webdev_save_checkpoint
  2. Click the Publish button in the Management UI
  3. Configure custom domain if desired

📚 Documentation

  • 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

🤝 Contributing

This is an autonomous agent system. Contributions should focus on:

  • Improving scoring algorithms
  • Adding new signal types
  • Enhancing risk management
  • Optimizing performance

📄 License

MIT License - See LICENSE file for details

🎓 Learning Resources

🆘 Support

For issues and questions:

  1. Check the dashboard for real-time status
  2. Review performance metrics and decision history
  3. Adjust configuration based on market conditions
  4. Run learning cycles to optimize weights

Built with ❤️ for autonomous trading on Solana

About

A full-stack Solana agent learning machine with 4 layers: Observation (Helius), Decision (Scoring), Execution, and Learning. Includes a dashboard for monitoring and strategy adjustment. · Built with Manus

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors