Back to Ruflo

ruflo-neural-trader

plugins/ruflo-neural-trader/README.md

3.6.307.6 KB
Original Source

ruflo-neural-trader

Neural trading strategies powered by neural-trader (v2.7+) — self-learning LSTM/Transformer/N-BEATS models, Rust/NAPI backtesting (8-19x faster), 112+ MCP tools, swarm coordination, and portfolio optimization.

Overview

Wraps the neural-trader npm package as a Ruflo plugin with 4 specialized agents, 6 skills, and comprehensive CLI commands. Adds AgentDB memory persistence, SONA trajectory learning, and swarm-coordinated execution on top of neural-trader's Rust/NAPI engine.

Prerequisites

bash
npm install neural-trader

Installation

bash
claude --plugin-dir plugins/ruflo-neural-trader

MCP Integration (112+ Tools)

neural-trader exposes 112+ MCP tools for direct Claude Desktop access:

bash
claude mcp add neural-trader -- npx neural-trader mcp start

Agents

AgentModelRole
trading-strategistopusStrategy design, LSTM/Transformer training, Z-score anomaly detection, backtest orchestration
risk-analystsonnetVaR/CVaR assessment, Kelly criterion sizing, circuit breakers, correlation monitoring
market-analystsonnetRegime detection, technical indicators (RSI/MACD/Bollinger), sector analysis, correlation
backtest-engineersonnetWalk-forward validation, Monte Carlo simulation, parameter optimization, benchmark comparison

Skills

SkillUsageDescription
trader-backtest/trader-backtest <strategy> --symbol SPYRust/NAPI backtest with walk-forward validation
trader-signal/trader-signal [--strategy NAME]Z-score anomaly detection signal generation
trader-portfolio/trader-portfolio [--risk-target 0.15]Mean-variance portfolio optimization
trader-regime/trader-regime [--symbol SPY]Market regime detection and classification
trader-train/trader-train lstm --symbol TSLATrain neural prediction models
trader-risk/trader-risk [--symbol AAPL]VaR, position sizing, circuit breaker status

Commands

bash
# Strategy management
trader strategy create <name> --type <momentum|mean-reversion|pairs|adaptive>
trader backtest <strategy> --symbol <TICKER> --period <range>

# Neural model training
trader train <lstm|transformer|nbeats> --symbol <TICKER>

# Signal generation
trader signal scan [--strategy <name>] [--symbols <TICKERS>]

# Market analysis
trader regime --symbol <TICKER>
trader indicators --symbol <TICKER> --indicators rsi,macd,bollinger
trader correlation --symbols <TICKERS> --window 30d

# Risk & portfolio
trader risk assess [--symbol <TICKER>]
trader portfolio optimize [--risk-target <number>]

# Live trading
trader live --broker <name> [--swarm enabled]

# History
trader history

Neural Models (via neural-trader)

ModelTypeUse Case
LSTMRecurrentSequence prediction, price forecasting
TransformerAttentionMulti-variate pattern recognition
N-BEATSDecompositionTrend/seasonality decomposition
bash
npx neural-trader --model lstm --symbol TSLA --confidence 0.95
npx neural-trader --model transformer --symbol BTC-USD --predict
npx neural-trader --model nbeats --symbol SPY --decompose

Strategy Types

StrategyCLI FlagEntry Logic
Momentum--strategy momentumRSI + MACD confirmation
Mean-reversion--strategy mean-reversionZ-score > 2.0, Bollinger extremes
Pairs trading--strategy pairsCointegration spread divergence
Multi-indicator--strategy multi-indicatorRSI + MACD + Bollinger combined
Adaptive--strategy adaptiveAuto-switches by regime

Market Regime Detection

RegimeIndicatorsRecommended Strategy
Bull trendingADX > 25, price > 200 SMAMomentum, trend-following
Bear trendingADX > 25, price < 200 SMAShort momentum, hedging
RangingADX < 20, Bollinger squeezeMean-reversion
High volatilityVIX > 25, ATR expandingReduce size, widen stops
TransitioningDivergences formingWait for confirmation

Anomaly Detection

neural-trader Z-score composite scoring on OHLCV: anomalyScore = min(1, meanZ / 3)

TypeDetectionMarket Interpretation
spikemaxZ > 5Breakout / gap
drift1-2 dims sustainedSustained trend
flatlineall near zeroConsolidation
oscillationalternatingRange-bound
pattern-breakmoderate Z, multi-dimRegime change
cluster-outlier>50% dims highMulti-factor dislocation

Circuit Breakers

BreakerTriggerAction
Daily lossDrawdown > 3%/dayHalt new entries
Weekly lossDrawdown > 5%/weekReduce sizes 50%
Correlation spikePortfolio corr > 0.85Reduce correlated positions
Volatility regimeVIX > 2x historicalMinimum position sizes
Max positionsOpen > limitBlock new entries
ConcentrationAny position > 10%Force trim

Backtesting Features

FeatureCommand
Walk-forward--walk-forward --train-window 6M --test-window 1M
Monte Carlo--monte-carlo --simulations 1000
Parameter optimization--optimize --param "entry_z:1.5:3.0:0.25"
Multi-symbol--symbols "AAPL,MSFT,GOOGL"
Benchmark comparison--benchmark SPY

Performance

neural-trader uses Rust/NAPI bindings for zero-overhead performance:

  • 8-19x faster than Python equivalents
  • Sub-200ms order execution and risk checks
  • WASM/SIMD acceleration available
  • 52,000+ inserts/sec for market data

Compatibility

  • CLI: pinned to @claude-flow/cli v3.6 major+minor.
  • Runtime: npx neural-trader (Rust/NAPI bindings — 112+ MCP tools).
  • Verification: bash plugins/ruflo-neural-trader/scripts/smoke.sh is the contract.

Namespace coordination

This plugin owns four AgentDB namespaces (kebab-case, follows the convention from ruflo-agentdb ADR-0001 §"Namespace convention"):

NamespacePurpose
trading-strategiesStrategy definitions (loaded by trader-backtest, trader-signal)
trading-backtestsBacktest results indexed by strategy + timestamp
trading-riskRisk metrics per portfolio
trading-analysisRegime detection + market analysis history

Note: the namespace prefix is trading- (the actual intent) rather than neural-trader- (the plugin stem). This is a deliberate ergonomic choice — trading is the load-bearing concern downstream consumers reason about. Reserved namespaces (pattern, claude-memories, default) MUST NOT be shadowed.

All access via memory_* (namespace-routed). No agentdb_hierarchical-* or agentdb_pattern-store with namespace arguments — the plugin uses the correct routing throughout.

Verification

bash
bash plugins/ruflo-neural-trader/scripts/smoke.sh
# Expected: "11 passed, 0 failed"

Architecture Decisions

  • ruflo-agentdb — namespace convention owner; backing store
  • ruflo-market-data — OHLCV data ingestion and candlestick pattern detection (feeds trading-strategies)
  • ruflo-ruvector — HNSW indexing for strategy pattern similarity search
  • ruflo-cost-tracker — PnL tracking and cost attribution
  • ruflo-observability — Strategy performance dashboards

License

MIT