# dantelrharrell-debug/nija architecture

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

- Interactive diagram: https://gitdiagram.com/dantelrharrell-debug/nija
- Repository: https://github.com/dantelrharrell-debug/nija

## Overview

1. **What this repo is**
   - A Python-based multi-broker trading platform with a large `bot/` runtime, supporting live trading, paper trading, backtesting, education/demo mode, dashboards, and mobile/backend integrations.
   - The codebase is organized as a trading system plus an app/platform shell, not just a single strategy engine.

2. **Primary runtime entry points**
   - The main execution surfaces are `main.py`, `bot/bot_main.py`, `run_live.py`, `run_paper_mode.sh`, `run_dry_run.sh`, `api_server.py`, `gateway.py`, `fastapi_backend.py`, and `web_server.py`.
   - These launch different slices of the system: trading runtime, API layer, gateway/API aggregation, and browser-facing UI.

3. **Core trading brain**
   - The core decision logic lives in `bot/`, `core/`, and `execution/`.
   - `bot/control/`, `core/strategy_orchestrator.py`, `core/nija_brain.py`, `bot/strategy_manager.py`, and the strategy modules in `bot/strategies/` form the signal-generation and orchestration layer.
   - Strategies include momentum, mean reversion, liquidity reversal, apex/NIJA variants, and AI/meta-learning components.

4. **Market data → signal → trade flow**
   - Market inputs come through the market/regime/liquidity stack (`bot/market_data_engine.py`, `bot/market_regime_*`, `bot/liquidity_*`, `bot/indicators*`).
   - Signals are filtered and scored by layers such as `bot/smart_filters.py`, `bot/ai_trade_quality_filter.py`, `bot/enhanced_entry_scoring.py`, and `bot/trade_quality_gate.py`.
   - Approved trades then move into the execution pipeline, where routing, sizing, and broker selection are resolved.

5. **Execution and broker boundary**
   - Execution is split into abstractions and venue-specific adapters: `bot/execution_*`, `bot/execution_router.py`, `bot/execution_pipeline.py`, `bot/broker_*`, `bot/live_broker_adapters.py`, `bot/broker_adapters.py`, and `execution/broker_adapter.py`.
   - Supported broker/venue configs include Kraken, Coinbase, Binance, Alpaca, and OKX under `bot/broker_configs/` and `config/brokers/`.
   - The repo has many “patch” modules that harden or repair execution paths, indicating a defensive execution layer with runtime hooks and fail-closed behavior.

6. **Risk, safety, and kill-switch architecture**
   - Risk is not a single module; it is a layered boundary spanning `bot/risk/`, `bot/risk_engine.py`, `bot/global_risk_engine.py`, `bot/risk_management.py`, `bot/pre_trade_risk_engine.py`, and many guardrails.
   - Safety controls include drawdown protection, position caps, volatility filters, exchange kill switches, emergency liquidation/reset, symbol freezing, and broker/venue cash guards.
   - The README’s live-trading rules are enforced by this stack: live mode is gated by consent, broker readiness, balance verification, and audit logging.

7. **Capital, portfolio, and account isolation**
   - Capital allocation and scaling are handled by `bot/capital/`, `bot/capital_*`, `bot/portfolio_*`, `bot/position_*`, and tier-aware modules like `bot/tier_config.py` and `bot/tier_aware_position_manager.py`.
   - There is explicit support for multi-account and user isolation: `bot/account_isolation_manager.py`, `bot/user_*`, `bot/multi_account_*`, and `config/users/*`.
   - This means capital is treated as a routed resource with hierarchy, reservation, and per-user/per-account boundaries.

8. **Persistence and runtime state**
   - Persistent state is split across PostgreSQL-style schema migration support (`alembic/`, `database/models.py`), Redis/cache (`cache/redis_client.py`, `bot/redis_runtime.py`), and file-based operational state in `data/`.
   - The `data/` directory stores audit logs, nonce state, profit confirmations, risk analyses, trade attribution, and recovery snapshots.
   - This mix suggests a system that keeps both durable business records and fast runtime coordination state.

9. **APIs, dashboards, and user-facing surfaces**
   - The platform exposes multiple API and UI surfaces: `api/`, `api_server.py`, `api_gateway.py`, `mobile_api.py`, `realtime_dashboard_api.py`, `control_center_api.py`, `central_dashboard_api.py`, and numerous dashboard modules in `bot/`.
   - Browser UI lives in `frontend/`, `bot/templates/`, and standalone HTML dashboards such as `owner_dashboard.html` and `NIJA_OPERATOR_DASHBOARD.html`.
   - The dashboard flow includes trade panels, execution previews, KPI/performance views, and operational control surfaces.

10. **Mobile app boundary**
   - The mobile app is designed as an education-first client, with demo mode default and live mode locked behind consent, broker readiness, and server-side secret handling.
   - Mobile assets and wrappers live under `mobile/`, `mobile_backend_server.py`, `unified_mobile_api.py`, and `frontend/static/js/` for app-store-style UI logic.
   - The mobile frontend is explicitly not the broker boundary; it calls secure backend APIs only.

11. **Ops, deployment, and environment model**
   - Deployment targets include Docker, Compose, Kubernetes (`k8s/`), Render (`render.yaml`), Railway (`railway.json`), and systemd/supervisor configs under `deploy/` and `deployment/`.
   - Environment is configuration-heavy: `.env.*`, `config/environment.py`, feature flags, broker configs, and user YAML/JSON definitions drive runtime behavior.
   - CI/security automation is extensive via GitHub Actions, pre-commit hooks, secret scanning, CodeQL, and threat-modeling workflows.

12. **Observability and auditability**
   - Monitoring is a first-class subsystem: `monitoring/` contains Grafana/Prometheus assets, while runtime modules emit logs, audits, and performance reports.
   - The system tracks execution journal entries, trade ledger data, profit confirmations, health checks, and compliance logs.
   - Architecture-wise, this supports post-trade reconciliation, operator visibility, and safety verification rather than only live execution.

13. **How to draw the main boundaries**
   - A good diagram should separate: external brokers/venues, the execution/risk core, the capital/account layer, the API/dashboard/mobile layer, and persistence/observability.
   - The most important cross-cutting constraint is that every trade must pass through readiness, risk, authority, and venue-validation gates before reaching a broker.
   - The mobile app and dashboards are control/visibility surfaces; they do not directly own broker secrets or execution authority.

Main entry points: [`bot/bot_main.py`](https://github.com/dantelrharrell-debug/nija/blob/main/bot/bot_main.py) (Bot runtime), [`api_server.py`](https://github.com/dantelrharrell-debug/nija/blob/main/api_server.py) (API server), [`bot/control/control_compiler.py`](https://github.com/dantelrharrell-debug/nija/blob/main/bot/control/control_compiler.py) (Control pipe), [`bot/strategies/apex_strategy.py`](https://github.com/dantelrharrell-debug/nija/blob/main/bot/strategies/apex_strategy.py) (Strategies)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_runtime["Runtimes"]
  node_main_py["Main<br/>entrypoint<br/>[main.py]"]
  node_bot_main["Bot runtime<br/>trading runtime<br/>[bot_main.py]"]
end

subgraph group_brain["Decision Core"]
  node_core_orchestrator["Orchestrator<br/>strategy control"]
  node_nija_brain{{"NIJA brain<br/>decision engine<br/>[nija_brain.py]"}}
  node_control_pipeline["Control pipe<br/>signal pipeline"]
  node_market_data["Market data<br/>market ingestion"]
  node_trade_quality["Trade gate<br/>signal filter"]
  node_strategy_core["Strategies<br/>strategy modules<br/>[apex_strategy.py]"]
end

subgraph group_safety["Capital & Safety"]
  node_capital_orchestration["Capital flow<br/>capital routing"]
  node_account_isolation["Account isolation<br/>account boundary"]
  node_global_risk["Global risk<br/>risk boundary"]
  node_risk_engine["Risk engine<br/>risk controls<br/>[risk_engine.py]"]
end

subgraph group_execution["Execution"]
  node_execution_pipeline["Exec pipeline<br/>execution pipeline"]
  node_execution_router["Exec router<br/>routing"]
  node_broker_adapter["Broker adapter<br/>venue adapter<br/>[broker_adapter.py]"]
end

subgraph group_surface["Interfaces"]
  node_api_server["API server<br/>api surface<br/>[api_server.py]"]
  node_gateway["Gateway<br/>api aggregator<br/>[gateway.py]"]
  node_mobile_backend["Mobile backend<br/>mobile api"]
  node_web_server["Web server<br/>ui server<br/>[web_server.py]"]
end

subgraph group_state["State & Storage"]
  node_trade_ledger[("Trade ledger<br/>persistent state<br/>[trade_ledger_db.py]")]
  node_redis_client[("Redis<br/>runtime cache<br/>[redis_client.py]")]
  node_db_models[("DB models<br/>schema<br/>[models.py]")]
end

subgraph group_external["External Venues"]
  node_broker_configs["Broker configs<br/>venue config<br/>[default_config.py]"]
end

node_main_py -->|"starts"| node_bot_main
node_bot_main -->|"drives"| node_core_orchestrator
node_core_orchestrator -->|"compiles"| node_control_pipeline
node_control_pipeline -->|"ingests"| node_market_data
node_control_pipeline -->|"selects"| node_strategy_core
node_strategy_core -->|"coordinates"| node_nija_brain
node_strategy_core -->|"filters"| node_trade_quality
node_trade_quality -->|"vetoes"| node_risk_engine
node_risk_engine -->|"escalates"| node_global_risk
node_global_risk -->|"allocates"| node_capital_orchestration
node_capital_orchestration -->|"scopes"| node_account_isolation
node_risk_engine -->|"authorizes"| node_execution_pipeline
node_execution_pipeline -->|"routes"| node_execution_router
node_execution_router -->|"adapts"| node_broker_adapter
node_broker_adapter -->|"constrains"| node_broker_configs
node_execution_pipeline -->|"records"| node_trade_ledger
node_bot_main -->|"coordinates"| node_redis_client
node_bot_main -->|"persists"| node_db_models
node_api_server -->|"controls"| node_bot_main
node_gateway -->|"fronts"| node_api_server
node_mobile_backend -->|"calls"| node_api_server
node_web_server -->|"renders"| node_api_server
node_web_server -->|"views"| node_trade_ledger

click node_main_py "https://github.com/dantelrharrell-debug/nija/blob/main/main.py"
click node_bot_main "https://github.com/dantelrharrell-debug/nija/blob/main/bot/bot_main.py"
click node_api_server "https://github.com/dantelrharrell-debug/nija/blob/main/api_server.py"
click node_gateway "https://github.com/dantelrharrell-debug/nija/blob/main/gateway.py"
click node_mobile_backend "https://github.com/dantelrharrell-debug/nija/blob/main/mobile_backend_server.py"
click node_web_server "https://github.com/dantelrharrell-debug/nija/blob/main/web_server.py"
click node_core_orchestrator "https://github.com/dantelrharrell-debug/nija/blob/main/core/strategy_orchestrator.py"
click node_nija_brain "https://github.com/dantelrharrell-debug/nija/blob/main/core/nija_brain.py"
click node_control_pipeline "https://github.com/dantelrharrell-debug/nija/blob/main/bot/control/control_compiler.py"
click node_market_data "https://github.com/dantelrharrell-debug/nija/blob/main/bot/market_data_engine.py"
click node_trade_quality "https://github.com/dantelrharrell-debug/nija/blob/main/bot/trade_quality_gate.py"
click node_strategy_core "https://github.com/dantelrharrell-debug/nija/blob/main/bot/strategies/apex_strategy.py"
click node_capital_orchestration "https://github.com/dantelrharrell-debug/nija/blob/main/bot/capital_orchestration_engine.py"
click node_account_isolation "https://github.com/dantelrharrell-debug/nija/blob/main/bot/account_isolation_manager.py"
click node_global_risk "https://github.com/dantelrharrell-debug/nija/blob/main/bot/global_risk_engine.py"
click node_risk_engine "https://github.com/dantelrharrell-debug/nija/blob/main/bot/risk_engine.py"
click node_execution_pipeline "https://github.com/dantelrharrell-debug/nija/blob/main/bot/execution_pipeline.py"
click node_execution_router "https://github.com/dantelrharrell-debug/nija/blob/main/bot/execution_router.py"
click node_broker_adapter "https://github.com/dantelrharrell-debug/nija/blob/main/execution/broker_adapter.py"
click node_broker_configs "https://github.com/dantelrharrell-debug/nija/blob/main/bot/broker_configs/default_config.py"
click node_trade_ledger "https://github.com/dantelrharrell-debug/nija/blob/main/bot/trade_ledger_db.py"
click node_redis_client "https://github.com/dantelrharrell-debug/nija/blob/main/cache/redis_client.py"
click node_db_models "https://github.com/dantelrharrell-debug/nija/blob/main/database/models.py"

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_main_py,node_bot_main,node_broker_configs toneBlue
class node_core_orchestrator,node_nija_brain,node_control_pipeline,node_market_data,node_trade_quality,node_strategy_core toneAmber
class node_capital_orchestration,node_account_isolation,node_global_risk,node_risk_engine toneMint
class node_execution_pipeline,node_execution_router,node_broker_adapter toneRose
class node_api_server,node_gateway,node_mobile_backend,node_web_server toneIndigo
class node_trade_ledger,node_redis_client,node_db_models toneTeal
```

## Components

### Runtimes

Process entrypoints and mode launchers.

- [Main](https://github.com/dantelrharrell-debug/nija/blob/main/main.py): entrypoint · Top-level bootstrap and mode selection. · `main.py`
- [Bot runtime](https://github.com/dantelrharrell-debug/nija/blob/main/bot/bot_main.py): trading runtime · Primary trading process orchestrator. · `bot/bot_main.py`

### Decision Core

Strategy orchestration, signal generation, and market interpretation.

- [Orchestrator](https://github.com/dantelrharrell-debug/nija/blob/main/core/strategy_orchestrator.py): strategy control · Coordinates strategy selection and trade lifecycle. · `core/strategy_orchestrator.py`
- [NIJA brain](https://github.com/dantelrharrell-debug/nija/blob/main/core/nija_brain.py): decision engine · Higher-level trading intelligence and synthesis. · `core/nija_brain.py`
- [Control pipe](https://github.com/dantelrharrell-debug/nija/blob/main/bot/control/control_compiler.py): signal pipeline · Compiles control, regime, and signal flow. · `bot/control/control_compiler.py`
- [Market data](https://github.com/dantelrharrell-debug/nija/blob/main/bot/market_data_engine.py): market ingestion · Market, regime, and liquidity input layer. · `bot/market_data_engine.py`
- [Trade gate](https://github.com/dantelrharrell-debug/nija/blob/main/bot/trade_quality_gate.py): signal filter · Entry scoring and trade quality gating. · `bot/trade_quality_gate.py`
- [Strategies](https://github.com/dantelrharrell-debug/nija/blob/main/bot/strategies/apex_strategy.py): strategy modules · Representative strategy implementations and variants. · `bot/strategies/apex_strategy.py`

### Capital & Safety

Capital routing, account boundaries, and layered risk controls.

- [Capital flow](https://github.com/dantelrharrell-debug/nija/blob/main/bot/capital_orchestration_engine.py): capital routing · Capital allocation, reservation, and scaling. · `bot/capital_orchestration_engine.py`
- [Account isolation](https://github.com/dantelrharrell-debug/nija/blob/main/bot/account_isolation_manager.py): account boundary · Separates users, accounts, and authority scopes. · `bot/account_isolation_manager.py`
- [Global risk](https://github.com/dantelrharrell-debug/nija/blob/main/bot/global_risk_engine.py): risk boundary · Portfolio-level risk, drawdown, and kill-switch logic. · `bot/global_risk_engine.py`
- [Risk engine](https://github.com/dantelrharrell-debug/nija/blob/main/bot/risk_engine.py): risk controls · Pre-trade and per-trade risk evaluation layer. · `bot/risk_engine.py`

### Execution

Order compilation, routing, and broker/venue adapters.

- [Exec pipeline](https://github.com/dantelrharrell-debug/nija/blob/main/bot/execution_pipeline.py): execution pipeline · Validates, compiles, and submits orders. · `bot/execution_pipeline.py`
- [Exec router](https://github.com/dantelrharrell-debug/nija/blob/main/bot/execution_router.py): routing · Selects venue, route, and execution path. · `bot/execution_router.py`
- [Broker adapter](https://github.com/dantelrharrell-debug/nija/blob/main/execution/broker_adapter.py): venue adapter · Abstract broker boundary used by execution. · `execution/broker_adapter.py`

### Interfaces

API, dashboard, web, and mobile control surfaces.

- [API server](https://github.com/dantelrharrell-debug/nija/blob/main/api_server.py): api surface · Primary backend API entrypoint. · `api_server.py`
- [Gateway](https://github.com/dantelrharrell-debug/nija/blob/main/gateway.py): api aggregator · Fronts and aggregates platform APIs. · `gateway.py`
- [Mobile backend](https://github.com/dantelrharrell-debug/nija/blob/main/mobile_backend_server.py): mobile api · Secure backend for the mobile client. · `mobile_backend_server.py`
- [Web server](https://github.com/dantelrharrell-debug/nija/blob/main/web_server.py): ui server · Browser-facing UI host. · `web_server.py`

### State & Storage

Durable records and fast runtime coordination state.

- [Trade ledger](https://github.com/dantelrharrell-debug/nija/blob/main/bot/trade_ledger_db.py): persistent state · Trade journals, ledgers, and audit records. · `bot/trade_ledger_db.py`
- [Redis](https://github.com/dantelrharrell-debug/nija/blob/main/cache/redis_client.py): runtime cache · Fast coordination and shared runtime state. · `cache/redis_client.py`
- [DB models](https://github.com/dantelrharrell-debug/nija/blob/main/database/models.py): schema · Durable business records and migration-backed schema. · `database/models.py`

### External Venues

Broker and venue boundary.

- [Broker configs](https://github.com/dantelrharrell-debug/nija/blob/main/bot/broker_configs/default_config.py): venue config · Broker-specific parameters and constraints. · `bot/broker_configs/default_config.py`

## Connections

- Main → Bot runtime: starts · Bootstraps the trading runtime and mode handlers.
- Bot runtime → Orchestrator: drives · Hands off runtime cycles to the strategy orchestrator.
- Orchestrator → Control pipe: compiles · Builds the control and signal flow.
- Control pipe → Market data: ingests · Consumes market, regime, and liquidity inputs.
- Control pipe → Strategies: selects · Routes decisions into representative strategy modules.
- Strategies → NIJA brain: coordinates · Shares higher-level intelligence and strategy synthesis.
- Strategies → Trade gate: filters · Scores and gates candidate trades.
- Trade gate → Risk engine: vetoes · Fails closed before orders reach execution.
- Risk engine → Global risk: escalates · Promotes local checks into portfolio-level safety.
- Global risk → Capital flow: allocates · Constrains and routes capital through hierarchy.
- Capital flow → Account isolation: scopes · Applies per-user and per-account boundaries.
- Risk engine → Exec pipeline: authorizes · Only approved trades may enter execution.
- Exec pipeline → Exec router: routes · Chooses venue and order path.
- Exec router → Broker adapter: adapts · Uses broker abstraction for venue-specific calls.
- Broker adapter → Broker configs: constrains · Applies broker and venue configuration limits.
- Exec pipeline → Trade ledger: records · Persists order and trade lifecycle events.
- Bot runtime → Redis: coordinates · Shares runtime state, locks, and caches.
- Bot runtime → DB models: persists · Writes durable platform state and records.
- API server → Bot runtime: controls · Operator/API actions influence the trading runtime.
- Gateway → API server: fronts · Aggregates backend API capabilities.
- Mobile backend → API server: calls · Mobile client uses secure backend APIs.
- Web server → API server: renders · Browser UI surfaces platform state and controls.
- Web server → Trade ledger: views · Displays execution and performance history.
