# pedramhatef/neuro architecture

> Architecture diagram of the GitHub repository pedramhatef/neuro, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-05-16). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/pedramhatef/neuro
- Repository: https://github.com/pedramhatef/neuro

## Overview

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: [`services/optimizer.ts`](https://github.com/pedramhatef/neuro/blob/new-development-branch/services/optimizer.ts) (Optimizer), [`App.tsx`](https://github.com/pedramhatef/neuro/blob/new-development-branch/App.tsx) (App), [`v4-clients/v4-client-js/examples/short_term_order_composite_open_BTC.ts`](https://github.com/pedramhatef/neuro/blob/new-development-branch/v4-clients/v4-client-js/examples/short_term_order_composite_open_BTC.ts) (Order scripts), [`components`](https://github.com/pedramhatef/neuro/tree/new-development-branch/components) (UI panels)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_frontend["Browser app"]
  node_app["App<br/>React entry<br/>[App.tsx]"]
  node_ui["UI panels<br/>React components"]
  node_browser_dydx["dYdX client<br/>Browser SDK<br/>[dydxClient.ts]"]
  node_browser_firebase[("Firebase client<br/>Firestore client<br/>[firebaseConfig.ts]")]
  node_market_data["Market data<br/>Candle fetcher<br/>[marketData.ts]"]
  node_ta["Technical analysis<br/>Indicator engine"]
  node_regime["Regime model<br/>Classifier<br/>[marketRegime.ts]"]
  node_simulator["Simulator<br/>Fallback market model<br/>[marketSimulator.ts]"]
  node_backtest["Backtesting<br/>Evaluation core<br/>[backtesting.ts]"]
  node_optimizer["Optimizer<br/>Genetic search<br/>[optimizer.ts]"]
  node_qlearn["Q-learning<br/>Firestore learner<br/>[qLearning.ts]"]
  node_diagnostics["Diagnostics<br/>Scoring/explain<br/>[executionScorer.ts]"]
  node_llm["AI analysis<br/>LLM boundary<br/>[geminiService.ts]"]
  node_persistence[("Persistence<br/>Firestore writer<br/>[persistence.ts]")]
end

subgraph group_backend["Control plane"]
  node_server["Server<br/>Express control plane<br/>[server.js]"]
  node_cron["Cron jobs<br/>Scheduler<br/>[cron.ts]"]
end

subgraph group_shared["Shared model"]
  node_shared_types["Shared types<br/>Domain schema<br/>[types.ts]"]
  node_shared_constants["Constants<br/>Strategy bounds<br/>[constants.ts]"]
end

subgraph group_execution["Trading scripts"]
  node_trade_scripts["Order scripts<br/>Live execution scripts"]
  node_composite_client["Composite client<br/>dYdX JS client"]
end

subgraph group_vendors["Vendored SDKs"]
  node_protocol_sdk["Protocol SDK<br/>Generated dYdX proto<br/>[client.ts]"]
end

node_app -->|"renders"| node_ui
node_app -->|"drives"| node_market_data
node_app -->|"requests analysis"| node_llm
node_ui -->|"reads/writes"| node_browser_firebase
node_ui -->|"reads state"| node_browser_dydx
node_market_data -->|"feeds"| node_ta
node_ta -->|"informs"| node_regime
node_market_data -.->|"falls back to"| node_simulator
node_ta -->|"evaluates"| node_backtest
node_regime -->|"selects params"| node_optimizer
node_backtest -->|"scores"| node_optimizer
node_diagnostics -->|"ranks"| node_optimizer
node_qlearn -->|"persists"| node_browser_firebase
node_optimizer -->|"updates"| node_qlearn
node_llm -->|"stores analysis"| node_persistence
node_optimizer -->|"stores results"| node_persistence
node_server -->|"launches"| node_trade_scripts
node_cron -.->|"automates"| node_server
node_trade_scripts -->|"uses"| node_composite_client
node_composite_client -->|"depends on"| node_protocol_sdk
node_trade_scripts -->|"uses schema"| node_shared_types
node_trade_scripts -->|"uses bounds"| node_shared_constants
node_server -->|"writes results"| node_persistence
node_browser_dydx -->|"uses"| node_protocol_sdk
node_app -->|"uses schema"| node_shared_types
node_optimizer -->|"uses bounds"| node_shared_constants

click node_app "https://github.com/pedramhatef/neuro/blob/new-development-branch/App.tsx"
click node_ui "https://github.com/pedramhatef/neuro/tree/new-development-branch/components"
click node_browser_dydx "https://github.com/pedramhatef/neuro/blob/new-development-branch/src/dydxClient.ts"
click node_browser_firebase "https://github.com/pedramhatef/neuro/blob/new-development-branch/src/firebaseConfig.ts"
click node_market_data "https://github.com/pedramhatef/neuro/blob/new-development-branch/services/marketData.ts"
click node_ta "https://github.com/pedramhatef/neuro/blob/new-development-branch/services/technicalAnalysis.ts"
click node_regime "https://github.com/pedramhatef/neuro/blob/new-development-branch/services/marketRegime.ts"
click node_simulator "https://github.com/pedramhatef/neuro/blob/new-development-branch/services/marketSimulator.ts"
click node_backtest "https://github.com/pedramhatef/neuro/blob/new-development-branch/services/backtesting.ts"
click node_optimizer "https://github.com/pedramhatef/neuro/blob/new-development-branch/services/optimizer.ts"
click node_qlearn "https://github.com/pedramhatef/neuro/blob/new-development-branch/services/qLearning.ts"
click node_diagnostics "https://github.com/pedramhatef/neuro/blob/new-development-branch/services/executionScorer.ts"
click node_llm "https://github.com/pedramhatef/neuro/blob/new-development-branch/services/geminiService.ts"
click node_persistence "https://github.com/pedramhatef/neuro/blob/new-development-branch/services/persistence.ts"
click node_server "https://github.com/pedramhatef/neuro/blob/new-development-branch/server.js"
click node_cron "https://github.com/pedramhatef/neuro/blob/new-development-branch/cron.ts"
click node_trade_scripts "https://github.com/pedramhatef/neuro/blob/new-development-branch/v4-clients/v4-client-js/examples/short_term_order_composite_open_BTC.ts"
click node_composite_client "https://github.com/pedramhatef/neuro/blob/new-development-branch/v4-clients/v4-client-js/src/clients/composite-client.ts"
click node_protocol_sdk "https://github.com/pedramhatef/neuro/blob/new-development-branch/v4-clients/dydxjs/packages/dydxjs/src/dydxprotocol/client.ts"
click node_shared_types "https://github.com/pedramhatef/neuro/blob/new-development-branch/types.ts"
click node_shared_constants "https://github.com/pedramhatef/neuro/blob/new-development-branch/constants.ts"

classDef toneNeutral fill:#f8fafc,stroke:#334155,stroke-width:1.5px,color:#0f172a
classDef toneBlue fill:#dbeafe,stroke:#2563eb,stroke-width:1.5px,color:#172554
classDef toneAmber fill:#fef3c7,stroke:#d97706,stroke-width:1.5px,color:#78350f
classDef toneMint fill:#dcfce7,stroke:#16a34a,stroke-width:1.5px,color:#14532d
classDef toneRose fill:#ffe4e6,stroke:#e11d48,stroke-width:1.5px,color:#881337
classDef toneIndigo fill:#e0e7ff,stroke:#4f46e5,stroke-width:1.5px,color:#312e81
classDef toneTeal fill:#ccfbf1,stroke:#0f766e,stroke-width:1.5px,color:#134e4a
class node_app,node_ui,node_browser_dydx,node_browser_firebase,node_market_data,node_ta,node_regime,node_simulator,node_backtest,node_optimizer,node_qlearn,node_diagnostics,node_llm,node_persistence toneBlue
class node_server,node_cron toneAmber
class node_shared_types,node_shared_constants toneMint
class node_trade_scripts,node_composite_client toneRose
class node_protocol_sdk toneIndigo
```

## Components

### Browser app

React/Vite UI, client-side analysis, and direct Firebase usage.

- [App](https://github.com/pedramhatef/neuro/blob/new-development-branch/App.tsx): React entry · Main browser orchestrator for the dashboard. · `App.tsx`
- [UI panels](https://github.com/pedramhatef/neuro/tree/new-development-branch/components): React components · Presentation layer for selection, signals, optimization, charts, stats, and controls. · `components`
- [dYdX client](https://github.com/pedramhatef/neuro/blob/new-development-branch/src/dydxClient.ts): Browser SDK · Browser-side dYdX client/context wiring. · `src/dydxClient.ts`
- [Firebase client](https://github.com/pedramhatef/neuro/blob/new-development-branch/src/firebaseConfig.ts): Firestore client · Browser-side Firestore access and app config. · `src/firebaseConfig.ts`
- [Market data](https://github.com/pedramhatef/neuro/blob/new-development-branch/services/marketData.ts): Candle fetcher · Pulls and caches 1m dYdX indexer candles. · `services/marketData.ts`
- [Technical analysis](https://github.com/pedramhatef/neuro/blob/new-development-branch/services/technicalAnalysis.ts): Indicator engine · Computes RSI, EMA, ADX, Bollinger Bands, and related indicators. · `services/technicalAnalysis.ts`
- [Regime model](https://github.com/pedramhatef/neuro/blob/new-development-branch/services/marketRegime.ts): Classifier · Classifies market regime for parameter selection and optimization. · `services/marketRegime.ts`
- [Simulator](https://github.com/pedramhatef/neuro/blob/new-development-branch/services/marketSimulator.ts): Fallback market model · Synthetic or fallback market source when live data is unavailable. · `services/marketSimulator.ts`
- [Backtesting](https://github.com/pedramhatef/neuro/blob/new-development-branch/services/backtesting.ts): Evaluation core · Deterministic leverage-aware strategy evaluation. · `services/backtesting.ts`
- [Optimizer](https://github.com/pedramhatef/neuro/blob/new-development-branch/services/optimizer.ts): Genetic search · Searches TP/SL and strategy parameters. · `services/optimizer.ts`
- [Q-learning](https://github.com/pedramhatef/neuro/blob/new-development-branch/services/qLearning.ts): Firestore learner · Persists and reuses best parameters per symbol/regime. · `services/qLearning.ts`
- [Diagnostics](https://github.com/pedramhatef/neuro/blob/new-development-branch/services/executionScorer.ts): Scoring/explain · Ranks signals and explains why a setup is strong or weak. · `services/executionScorer.ts`
- [AI analysis](https://github.com/pedramhatef/neuro/blob/new-development-branch/services/geminiService.ts): LLM boundary · Gemini-first market analysis with fallback providers. · `services/geminiService.ts`
- [Persistence](https://github.com/pedramhatef/neuro/blob/new-development-branch/services/persistence.ts): Firestore writer · Batched writes and shared state persistence. · `services/persistence.ts`

### Control plane

Express server, cron automation, and execution orchestration.

- [Server](https://github.com/pedramhatef/neuro/blob/new-development-branch/server.js): Express control plane · API server for logs, position status, command launch, and guard control. · `server.js`
- [Cron jobs](https://github.com/pedramhatef/neuro/blob/new-development-branch/cron.ts): Scheduler · Periodic automation bootstrap and job runner. · `cron.ts`

### Shared model

Types and constants used across UI, optimizer, persistence, and scripts.

- [Shared types](https://github.com/pedramhatef/neuro/blob/new-development-branch/types.ts): Domain schema · Authoritative shared schema for assets, regimes, strategy params, signals, and outcomes. · `types.ts`
- [Constants](https://github.com/pedramhatef/neuro/blob/new-development-branch/constants.ts): Strategy bounds · 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](https://github.com/pedramhatef/neuro/blob/new-development-branch/v4-clients/v4-client-js/examples/short_term_order_composite_open_BTC.ts): Live execution 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](https://github.com/pedramhatef/neuro/blob/new-development-branch/v4-clients/v4-client-js/src/clients/composite-client.ts): dYdX JS 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](https://github.com/pedramhatef/neuro/blob/new-development-branch/v4-clients/dydxjs/packages/dydxjs/src/dydxprotocol/client.ts): Generated dYdX proto · Vendored protocol, Cosmos, IBC, and Slinky generated client libraries. · `v4-clients/dydxjs/packages/dydxjs/src/dydxprotocol/client.ts`

## Connections

- 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.
