How pedramhatef/neuro works
1. What this repo is
- NeuroTrade is a two-part system: a React/Vite trading dashboard in the browser and a Node/Express execution backend. It analyzes dYdX v4 perpetual markets, optimizes strategy parameters, stores state in Firestore, and can launch live trading scripts.
2. User-facing UI layer
- App.tsx is the main client orchestrator.
- components/ is presentation-only UI: asset selection, signal feed, optimizer panel, charting, stats, execution controls, and header.
- The browser talks to the backend through Vite’s /api proxy and also reads/writes Firestore directly through the Firebase client SDK.
3. Client-side market analysis pipeline
- services/marketData.ts pulls 1-minute candles from the dYdX v4 Indexer API and caches them.
- services/technicalAnalysis.ts computes indicators such as RSI, EMA, ADX, and Bollinger Bands.
- services/marketRegime.ts classifies the current regime so optimization and Q-learning can choose different parameters.
- services/marketSimulator.ts provides a fallback when live market data is unavailable.
4. Strategy optimization engine
- services/backtesting.ts is the deterministic evaluation core and is leverage-aware.
- services/optimizer.ts runs the genetic algorithm that searches TP/SL and strategy parameters.
- services/qLearning.ts persists best parameters per symbol_regime in Firestore and reuses them when the asset/regime combination has prior history.
- services/executionScorer.ts and services/signalDiagnostics.ts are supporting evaluation layers for ranking and explaining signals.
5. AI analysis boundary
- services/geminiService.ts performs LLM-driven market analysis.
- Primary path is Google Gemini; fallback is OpenRouter/GPT-4o-mini, with Anthropic available as an additional integration point.
- This AI output feeds the signal/strategy decision layer, but it is separated from execution so the system can still trade using deterministic rules if needed.
6. Persistent state and Firestore model
- services/persistence.ts batches writes to Firestore.
- assetStates stores per-asset live state: signals, cached candles, strategy, regime, and AI analysis.
- qTable stores the regime-specific learned strategy parameters.
- tradeJournal records every trade lifecycle and outcome.
- The repo uses both Firebase Client SDK in the browser and Firebase Admin SDK on the server, so Firestore is a shared state boundary across runtimes.
7. Execution backend
- server.js is the Express control plane on port 3001.
- It exposes endpoints for logs, position status, running a command, closing all positions, OCO state, and releasing an in-flight guard.
- The backend launches trading scripts as child processes, staggers them to avoid sequence conflicts, and parses stdout to determine TP/SL/MANUAL outcomes.
- Server-side guards prevent duplicate entries and enforce cooldown/circuit-breaker behavior after repeated stop losses.
8. Live trading scripts and dYdX order flow
- The actual order execution lives in v4-clients/v4-client-js/examples/short_term_order_composite_open_{ASSET}.ts for the six supported assets.
- These scripts fetch oracle prices, place IOC entry orders, then create TAKE_PROFIT_LIMIT and STOP_LIMIT legs as an OCO pair.
- They monitor fills, cancel the opposite leg on exit, and handle manual closure or expiry.
- This is the main boundary where strategy output becomes on-chain trading activity.
9. dYdX client SDK layer
- src/dydxClient.ts and src/dydxClientContext.tsx set up the browser-side dYdX client.
- The v4-clients/ directory vendors the generated dYdX protocol client libraries and higher-level JS client packages, including Cosmos/IBC/dYdX proto support.
- These packages are infrastructure, not app logic, but they are essential because they define how the repo speaks to dYdX.
10. Shared domain model
- types.ts is the authoritative shared TypeScript schema for assets, regimes, strategy params, signals, and outcomes.
- constants.ts and related service constants define leverage, fees, and strategy bounds used consistently by both backtesting and execution.
- This shared model keeps the UI, optimizer, persistence layer, and trading scripts aligned.
11. Background automation
- cron.ts and cron-bootstrap.ts indicate a periodic job runner used to keep optimization or signal processing moving without manual interaction.
- launch-engine.sh and ecosystem.config.cjs suggest the backend can also be run as a managed process in production.
12. Deployment and runtime topology
- Frontend is built with Vite and deployed through Firebase Hosting.
- Backend can also run on Fly.io, with supporting configs in fly.toml, Dockerfile, and server.js.
- Development runs with the UI on one port and the Express backend on another, with the frontend proxying API requests to the server.
13. Overall data flow
- Market data comes from dYdX Indexer → analysis/TA/regime detection → backtest + GA + Q-learning → Firestore persistence.
- When a signal is confirmed, the browser/backend control plane invokes a trading script → dYdX orders are placed → fill/exit status is observed → results are written back to Firestore and surfaced in the UI via SSE logs and live state updates.
Main entry points: optimizer.ts Optimizer · App.tsx App · short_term_order_composite_open_BTC.ts Order scripts · components UI panels
Components 21
Browser app
React/Vite UI, client-side analysis, and direct Firebase usage.
- App · Main browser orchestrator for the dashboard.
App.tsx - UI panels · Presentation layer for selection, signals, optimization, charts, stats, and controls.
components - dYdX client · Browser-side dYdX client/context wiring.
src/dydxClient.ts - Firebase client · Browser-side Firestore access and app config.
src/firebaseConfig.ts - Market data · Pulls and caches 1m dYdX indexer candles.
services/marketData.ts - Technical analysis · Computes RSI, EMA, ADX, Bollinger Bands, and related indicators.
services/technicalAnalysis.ts - Regime model · Classifies market regime for parameter selection and optimization.
services/marketRegime.ts - Simulator · Synthetic or fallback market source when live data is unavailable.
services/marketSimulator.ts - Backtesting · Deterministic leverage-aware strategy evaluation.
services/backtesting.ts - Optimizer · Searches TP/SL and strategy parameters.
services/optimizer.ts - Q-learning · Persists and reuses best parameters per symbol/regime.
services/qLearning.ts - Diagnostics · Ranks signals and explains why a setup is strong or weak.
services/executionScorer.ts - AI analysis · Gemini-first market analysis with fallback providers.
services/geminiService.ts - Persistence · Batched writes and shared state persistence.
services/persistence.ts
Control plane
Express server, cron automation, and execution orchestration.
Shared model
Types and constants used across UI, optimizer, persistence, and scripts.
- Shared types · Authoritative shared schema for assets, regimes, strategy params, signals, and outcomes.
types.ts - Constants · Shared leverage, fee, and strategy bound constants.
constants.ts
Trading scripts
Live order-entry scripts and dYdX client libraries that place and manage orders.
- Order scripts · Asset-specific short-term composite entry scripts that turn signals into trades.
v4-clients/v4-client-js/examples/short_term_order_composite_open_BTC.ts - Composite client · Higher-level dYdX client package used by execution scripts.
v4-clients/v4-client-js/src/clients/composite-client.ts
Vendored SDKs
Generated dYdX protocol and client packages vendored into the repo.
- Protocol SDK · Vendored protocol, Cosmos, IBC, and Slinky generated client libraries.
v4-clients/dydxjs/packages/dydxjs/src/dydxprotocol/client.ts
Connections 26
- App → UI panels: renders · App composes the dashboard panels.
- App → Market data: drives · UI triggers market analysis refresh.
- App → AI analysis: requests analysis · App can surface LLM-driven analysis results.
- UI panels → Firebase client: reads/writes · Panels interact with Firestore-backed live state.
- UI panels → dYdX client: reads state · UI can query dYdX client context.
- Market data → Technical analysis: feeds · Candles are transformed into indicators.
- Technical analysis → Regime model: informs · Indicators contribute to regime classification.
- Market data → Simulator: falls back to · Fallback source when live market data is unavailable.
- Technical analysis → Backtesting: evaluates · Indicator-derived features are used in deterministic evaluation.
- Regime model → Optimizer: selects params · Regime guides search space and parameter choices.
- Backtesting → Optimizer: scores · Optimizer searches using backtest results.
- Diagnostics → Optimizer: ranks · Scoring and explanation layer helps prioritize candidates.
- Q-learning → Firebase client: persists · Learned parameters are stored in Firestore.
- Optimizer → Q-learning: updates · Best-performing parameters are reused by regime.
- AI analysis → Persistence: stores analysis · AI analysis is written into shared state.
- Optimizer → Persistence: stores results · Optimization outputs are batched to Firestore.
- Server → Order scripts: launches · Express server starts trading scripts as child processes.
- Cron jobs → Server: automates · Scheduler keeps control-plane work moving.
- Order scripts → Composite client: uses · Execution scripts rely on the higher-level client.
- Composite client → Protocol SDK: depends on · Composite client is built on vendored protocol libraries.
- Order scripts → Shared types: uses schema · Scripts consume the shared domain model.
- Order scripts → Constants: uses bounds · Scripts use shared leverage and strategy limits.
- Server → Persistence: writes results · Control plane reflects execution outcomes in shared state.
- dYdX client → Protocol SDK: uses · Browser-side dYdX integration is backed by vendored SDKs.
- App → Shared types: uses schema · UI is aligned with the shared domain model.
- Optimizer → Constants: uses bounds · Optimization respects shared strategy limits.