JSPM

  • Created
  • Published
  • Downloads 429
  • Score
    100M100P100Q111512F
  • License MIT OR Apache-2.0

Complete AI-powered algorithmic trading platform with neural networks, backtesting, live trading, and MCP integration - all features included (meta package)

Package Exports

  • neural-trader
  • neural-trader/index.js

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (neural-trader) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

npm version Downloads License NAPI-RS Rust CI Website GitHub Stars PRs Welcome

๐Ÿค– The First Self-Learning AI Trading Platform Built for Claude Code, Cursor, GitHub Copilot & OpenAI Codex

20 Modular Packages โ€ข 78.75x Faster โ€ข 60+ MCP Tools โ€ข Zero-Overhead NAPI โ€ข Production-Ready

๐Ÿ“ฆ Quick Start โ€ข ๐ŸŽฏ Features โ€ข ๐Ÿ“š Docs โ€ข ๐Ÿ’ฌ Community


๐ŸŒ Live API: https://neural-trader.ruv.io | ๐Ÿ“š Documentation: https://neural-trader.ruv.io/docs | ๐Ÿ“ฆ NPM: 20 packages with 27 neural models & 78.75x speedup


โœจ Key Features

๐Ÿง  Neural Trading Strategies

  • 8 Advanced Strategies: Mirror Trader, Momentum Trader, Enhanced Momentum, Neural Sentiment, Neural Arbitrage, Neural Trend, Mean Reversion, Pairs Trading
  • 27 Neural Models: LSTM, Transformer, NHITS, NBEATS, TFT, DeepAR, and 21+ more with GPU acceleration
  • 78.75x Performance Boost: Combined SIMD, parallelization, and Flash Attention optimizations
  • GPU Acceleration Ready: Automatic detection and utilization when available
  • Real-Time Execution: Sub-second decision making and order placement
  • Multi-Symbol Support: Trade multiple assets simultaneously

๐Ÿ“ฆ NPM Packages (20 Published)

Complete modular trading system available on npm with high-performance Rust bindings:

Core Packages:

Trading Components:

Specialized:

Tools:

๐Ÿ“š Installation: npm install @neural-trader/backend or npm install neural-trader ๐Ÿ“– Full Package List: docs/ALL_PACKAGES_PUBLISHED.md

๐Ÿ“Š Comprehensive Trading Operations

  • Live Trading: Start/stop trading with advanced configuration
  • Backtesting: Historical performance analysis with Sharpe ratio calculations
  • Strategy Optimization: Parameter tuning with up to 100 iterations
  • Risk Management: Stop-loss, take-profit, and position sizing controls
  • Multi-Exchange Support: CCXT integration for 100+ cryptocurrency exchanges
  • E2B Sandbox Execution: Isolated code execution environments for strategy testing
  • Real-Time WebSocket Streaming: Live market data and order updates
  • Cross-Asset Correlation: Multi-asset portfolio optimization and rebalancing

๐Ÿ” Enterprise Security (NEW!)

  • JWT Authentication: Optional Bearer token authentication
  • API Key Support: Alternative authentication method
  • Environment-Based Config: Secure secrets management
  • Bcrypt Password Hashing: Industry-standard security

๐Ÿ“ˆ Advanced Analytics

  • AI News Sentiment: Real-time news analysis from multiple sources (NewsAPI, Finnhub, Alpha Vantage)
  • Portfolio Analytics: Sharpe ratio, max drawdown, win rate, alpha, beta metrics
  • Risk Analysis: VaR, CVaR, Monte Carlo simulations (100k+ scenarios)
  • Performance Monitoring: Real-time tracking and Prometheus metrics
  • Prediction Markets: Expected value calculations and probability calibration
  • Correlation Matrix: Cross-asset correlation analysis for diversification
  • Reinforcement Learning: Q-Learning, SARSA, Actor-Critic for strategy optimization

๐Ÿš€ Production Ready

  • FastAPI Framework: High-performance async API
  • Docker Deployment: Containerized for easy deployment
  • Fly.io Integration: One-command cloud deployment
  • Health Monitoring: Built-in health checks and status endpoints

๐Ÿ”ฅ Quick Start

1. Clone the Repository

git clone https://github.com/ruvnet/neural-trader.git
cd neural-trader

2. Install Dependencies

Python (FastAPI Backend):

pip install -r requirements.txt

Node.js (NPM Packages):

npm install @neural-trader/backend
# Or install the complete metapackage
npm install neural-trader

3. Configure Environment

cp .env.example .env
# Edit .env with your API keys and settings

4. Run Locally

python -m uvicorn src.main:app --reload --port 8080

5. Deploy to Production

# Using the deployment script
./scripts/deploy-to-fly.sh

# Or deploy with Docker (see Docker section below)

๐Ÿ“ก API Endpoints

Core Endpoints

Method Endpoint Description
GET / Platform info and status
GET /health Health check with strategy status
GET /gpu-status GPU availability check
GET /metrics Prometheus metrics

Authentication (Optional)

Method Endpoint Description
POST /auth/login Get JWT token
GET /auth/status Check auth status
POST /auth/verify Verify JWT token

Trading Operations

Method Endpoint Description
POST /trading/start Start trading with configuration
POST /trading/stop Stop trading strategies
GET /trading/status Current trading status
POST /trading/backtest Run historical backtest
POST /trading/optimize Optimize strategy parameters
POST /trading/analyze-news AI news sentiment analysis
POST /trading/execute-trade Execute individual trade

Portfolio & Risk

Method Endpoint Description
GET /portfolio/status Portfolio overview with analytics
POST /risk/analysis Comprehensive risk analysis

๐Ÿ”ง Configuration

Environment Variables

# Authentication (Optional)
AUTH_ENABLED=false              # Enable/disable JWT auth
JWT_SECRET_KEY=your-secret-key  # JWT signing key
AUTH_USERNAME=admin             # Default username
AUTH_PASSWORD=changeme          # Default password

# Trading APIs
ALPACA_API_KEY=your-key
ALPACA_SECRET_KEY=your-secret
NEWS_API_KEY=your-key
FINNHUB_API_KEY=your-key

# Application
PORT=8080
LOG_LEVEL=info

Trading Configuration

{
  "strategies": ["momentum_trader", "neural_sentiment"],
  "symbols": ["SPY", "QQQ", "AAPL"],
  "risk_level": "medium",
  "max_position_size": 10000,
  "stop_loss_percentage": 2.0,
  "take_profit_percentage": 5.0,
  "time_frame": "5m",
  "use_gpu": false,
  "enable_news_trading": true,
  "enable_sentiment_analysis": true
}

๐Ÿ” Authentication

The platform includes optional JWT authentication that can be enabled for production:

Enable Authentication

# For cloud deployments
fly secrets set AUTH_ENABLED=true --app your-app-name

# For Docker deployments
export AUTH_ENABLED=true

Obtain Token

curl -X POST https://neural-trader.ruv.io/auth/login \
  -H "Content-Type: application/json" \
  -d '{"username":"admin","password":"your-password"}'

Use Token

curl -H "Authorization: Bearer YOUR_TOKEN" \
  https://neural-trader.ruv.io/trading/status

See Authentication Guide for detailed documentation.

๐Ÿงช Testing

Run Tests

# Test all endpoints
./scripts/test-api-endpoints.sh

# Test authentication
./scripts/test-auth.sh

# Validate core features
./scripts/validate-core-features.sh

# Comprehensive capability test
./scripts/test-all-capabilities.sh

API Testing with cURL

# Start trading
curl -X POST https://neural-trader.ruv.io/trading/start \
  -H "Content-Type: application/json" \
  -d '{"strategies":["momentum_trader"],"symbols":["SPY"]}'

# Check status
curl https://neural-trader.ruv.io/trading/status

# Run backtest
curl -X POST https://neural-trader.ruv.io/trading/backtest \
  -H "Content-Type: application/json" \
  -d '{
    "strategy": "momentum_trader",
    "symbols": ["SPY"],
    "start_date": "2024-01-01",
    "end_date": "2024-06-30"
  }'

๐Ÿ“Š Performance Metrics

  • Response Time: Average 121ms
  • Success Rate: 87.76% in comprehensive tests
  • Neural Models: 27 models with 78.75x speedup
  • Deployment Size: 327 MB Docker image
  • Memory Usage: ~500MB typical
  • CPU Usage: <10% idle, 20-40% active trading

๐Ÿ—๏ธ Architecture

neural-trader/
โ”œโ”€โ”€ src/                      # Python FastAPI backend
โ”‚   โ”œโ”€โ”€ auth/                 # JWT authentication
โ”‚   โ”œโ”€โ”€ trading/
โ”‚   โ”‚   โ””โ”€โ”€ strategies/       # Trading strategies
โ”‚   โ”œโ”€โ”€ optimization/         # Strategy optimization
โ”‚   โ””โ”€โ”€ main.py              # FastAPI application
โ”œโ”€โ”€ neural-trader-rust/       # Rust performance layer
โ”‚   โ”œโ”€โ”€ crates/
โ”‚   โ”‚   โ”œโ”€โ”€ napi-bindings/   # NAPI bindings
โ”‚   โ”‚   โ””โ”€โ”€ neuro-divergent/ # 27 neural models
โ”‚   โ””โ”€โ”€ packages/            # 20 NPM packages
โ”œโ”€โ”€ scripts/                  # Deployment & testing
โ”œโ”€โ”€ docs/                     # Documentation
โ””โ”€โ”€ requirements.txt          # Dependencies

๐Ÿš€ Deployment

Docker Deployment

Build the Image

# Build from Dockerfile
docker build -t neural-trader:latest .

# Or build with specific Dockerfile
docker build -f Dockerfile.fly -t neural-trader:latest .

Run the Container

# Run with environment file
docker run -d \
  --name neural-trader \
  -p 8080:8080 \
  --env-file .env \
  neural-trader:latest

# Or run with individual environment variables
docker run -d \
  --name neural-trader \
  -p 8080:8080 \
  -e AUTH_ENABLED=false \
  -e JWT_SECRET_KEY="$(openssl rand -hex 32)" \
  -e ALPACA_API_KEY="your-key" \
  neural-trader:latest

Docker Compose

# docker-compose.yml
version: '3.8'
services:
  neural-trader:
    build: .
    ports:
      - "8080:8080"
    environment:
      - AUTH_ENABLED=false
      - JWT_SECRET_KEY=${JWT_SECRET_KEY}
      - ALPACA_API_KEY=${ALPACA_API_KEY}
    volumes:
      - ./logs:/app/logs
    restart: unless-stopped

Cloud Deployment (Fly.io)

# Deploy with the provided script
./scripts/deploy-to-fly.sh

# Or manually with fly CLI
fly deploy

# Configure secrets
fly secrets set JWT_SECRET_KEY="$(openssl rand -hex 32)"
fly secrets set ALPACA_API_KEY="your-key"
fly secrets set AUTH_ENABLED=true

Manual Deployment

  1. Set up environment variables
  2. Install dependencies: pip install -r requirements.txt
  3. Run with production server: gunicorn -k uvicorn.workers.UvicornWorker src.main:app

๐Ÿ“š Documentation

๐Ÿ› ๏ธ Available Strategies

Strategy Description Risk Level
Mirror Trader Mirrors successful market patterns Medium
Momentum Trader Follows strong price movements Medium-High
Enhanced Momentum Advanced momentum with multiple indicators High
Neural Sentiment AI-powered news sentiment analysis Medium
Neural Arbitrage Statistical arbitrage opportunities Low-Medium
Neural Trend Deep learning trend prediction Medium
Mean Reversion Exploits price mean reversion Medium
Pairs Trading Market-neutral statistical arbitrage Low

๐Ÿ”ง Advanced Features

Model Context Protocol (MCP)

Neural Trader supports MCP integration for AI-assisted trading with 60+ tools:

# Add Neural Trader as MCP server
claude mcp add neural-trader npx @neural-trader/mcp

# Use in Claude Desktop for AI-powered trading analysis
# Available tools: executeTrade, neuralForecast, getSportsOdds, createSyndicate, etc.

GPU Acceleration

Automatic GPU detection and utilization for neural models with CUDA support:

# Check GPU availability
GET /gpu-status

# Enable GPU in trading config
{
  "use_gpu": true,
  "strategies": ["neural_sentiment", "neural_trend"],
  "gpu_memory_limit": 4096  # MB
}

E2B Sandbox Execution

Isolated code execution environments for safe strategy testing:

const {
  createE2bSandbox,
  runE2bAgent,
  executeE2bProcess
} = require('@neural-trader/backend');

// Create sandbox
const sandbox = await createE2bSandbox({
  name: 'strategy-test',
  template: 'node',
  timeout: 300
});

// Run trading agent in sandbox
await runE2bAgent({
  sandbox_id: sandbox.id,
  agent_type: 'momentum_trader',
  symbols: ['SPY', 'QQQ'],
  use_gpu: false
});

Cryptocurrency Trading (CCXT)

Support for 100+ cryptocurrency exchanges via CCXT integration:

const { executeTrade } = require('@neural-trader/backend');

// Trade on Binance, Coinbase, Kraken, etc.
await executeTrade({
  strategy: 'momentum_trader',
  symbol: 'BTC/USDT',
  exchange: 'binance',
  action: 'buy',
  quantity: 0.1
});

Prediction Markets

Polymarket integration with expected value calculations:

const {
  getPredictionMarkets,
  analyzeMarketSentiment,
  calculateExpectedValue
} = require('@neural-trader/backend');

// Get available markets
const markets = await getPredictionMarkets({ category: 'politics', limit: 10 });

// Calculate expected value
const ev = await calculateExpectedValue({
  market_id: 'market_123',
  investment_amount: 1000,
  confidence_adjustment: 1.0
});

Sports Betting Integration

Built-in sports betting arbitrage detection and Kelly Criterion position sizing:

const {
  getSportsOdds,
  findSportsArbitrage,
  calculateKellyCriterion,
  getSportsEvents,
  analyzeBettingMarketDepth
} = require('@neural-trader/sports-betting');

// Get upcoming events
const events = await getSportsEvents('basketball_nba', { days_ahead: 7 });

// Find arbitrage opportunities
const arbs = await findSportsArbitrage('basketball_nba', { min_profit_margin: 0.01 });

// Calculate Kelly sizing
const stake = calculateKellyCriterion({
  probability: 0.55,
  odds: 2.1,
  bankroll: 10000
});

// Analyze market depth
const depth = await analyzeBettingMarketDepth('market_123', 'basketball_nba');

Investment Syndicates

Collaborative investment pools with profit sharing and governance:

const {
  createSyndicate,
  addSyndicateMember,
  allocateSyndicateFunds,
  distributeSyndicateProfits,
  createSyndicateVote
} = require('@neural-trader/syndicate');

// Create syndicate
await createSyndicate({
  syndicate_id: 'tech-growth-fund',
  name: 'Tech Growth Fund',
  description: 'Tech sector growth investments'
});

// Add members
await addSyndicateMember({
  syndicate_id: 'tech-growth-fund',
  name: 'Alice',
  email: 'alice@example.com',
  role: 'member',
  initial_contribution: 5000
});

// Allocate funds with Kelly Criterion
await allocateSyndicateFunds({
  syndicate_id: 'tech-growth-fund',
  opportunities: [...],
  strategy: 'kelly_criterion'
});

// Distribute profits
await distributeSyndicateProfits({
  syndicate_id: 'tech-growth-fund',
  total_profit: 1250,
  model: 'hybrid' // Contribution + performance based
});

// Create governance vote
await createSyndicateVote({
  syndicate_id: 'tech-growth-fund',
  vote_type: 'strategy_change',
  proposal: 'Switch to more conservative allocation',
  options: ['Approve', 'Reject', 'Modify']
});

๐Ÿค Contributing

Contributions are welcome! Please read our Contributing Guide for details.

๐Ÿ“ License

This project is licensed under the MIT License - see the LICENSE file for details.

๐Ÿ™ Acknowledgments

  • FastAPI - Modern, fast web framework
  • Alpaca - Commission-free trading API
  • Rust & NAPI-RS - High-performance neural model bindings
  • Model Context Protocol - AI integration framework

๐Ÿ“ž Support


Built with โค๏ธ by rUv