Skip to content

Mopati123/nvidia_chat

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

66 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

ApexQuantumICT — Quantum-Physics Algorithmic Trading System

A production-grade trading bot that models financial markets as curved physical space and finds optimal trades using Feynman's path integral — the same mathematics that governs how particles move through quantum fields.

Every trade decision is authorized by a cryptographic governance protocol and stored in a SHA-256 runtime evidence hash chain. Optional evidence bundles support Merkle roots and Ed25519 signatures where that path is used.


What It Does

Instead of simple indicators (RSI, MACD), this system:

  1. Models price movement as geodesics through curved spacetime — the liquidity field ϕ(p,t) encodes order blocks, fair value gaps, and session timing as curvature; price follows the path of least resistance
  2. Generates N candidate trajectories via RK4 path integration — each seeded with geodesic curvature corrections, integrated with live Christoffel symbol acceleration
  3. Scores every trajectory against 18 ICT/SMC quantum operators — order blocks, FVGs, liquidity sweeps, OTE fibonacci, Judas swings, Wyckoff accumulation, and 12 more
  4. Selects the minimum-action path — the trajectory with lowest S[γ] = w_L·S_L + w_T·S_T + w_E·S_E + w_R·S_R
  5. Requires cryptographic authorization to execute — the scheduler issues a signed ExecutionToken or refuses; no token = no trade
  6. Learns from every outcome — PPO reinforcement learning agent + backward weight adaptation continuously improve trajectory selection

Current Software State

ApexQuantumICT currently stands as a rootfile-governed lawful-collapse trading runtime. Its core invariant is:

Possibility cannot execute itself.

The system can analyze market data, generate candidate futures, score and filter trade proposals, request scheduler authority, execute only after token validation, reconcile realized outcomes, emit hash-linked evidence, and feed settlement results back into learning.

Current capabilities include:

  1. Full 20-stage runtime kernel - PipelineOrchestrator carries a market observation from raw data through state construction, ICT extraction, geometry, trajectory generation, Ramanujan compression, action scoring, path selection, proposal generation, risk, entropy, scheduler collapse, execution, reconciliation, evidence, and weight update.
  2. Stage operator contracts - every canonical pipeline stage is mapped to an H1-H13 rootfile law through trading/pipeline/stage_contracts.py.
  3. Deterministic stage proofs - each stage records redacted input/output hashes, previous proof hash, operator id, canonical law, checkpoint hash, and refusal code through trading/pipeline/stage_proof.py.
  4. Refusal-first execution safety - proposals must pass admissibility, entropy, scheduler authority, kill-switch checks, and broker token validation before any paper, Deriv demo, or MT5 demo side effect.
  5. Broker execution boundaries - Deriv and MT5 integrations support demo-account workflows, secure credential resolution, token-validated execution calls, settlement, and audit. The system does not require secrets to be committed to Git.
  6. Evidence and reconciliation loop - runtime events, refusals, broker outcomes, settlements, and learning feedback can be written into SHA-256 hash-chained evidence logs and checked for integrity.
  7. Learning feedback - PPO/backward-weight update hooks can consume reconciled paper, MT5 demo, and Deriv demo settlement outcomes.
  8. Operational surfaces - CLI runners, broker setup scripts, preflight checks, settlement commands, a FastAPI dashboard, Telegram integration, and rootfile validators support operating and observing the runtime.
  9. Architecture intelligence - .understand-anything/ contains the generated knowledge graph, rootfile architecture analysis, and the superposition/evolution model used to understand the repo as a coherent software system.

The current trusted local proof path is the offline paper-mode E2E test in tests/rootfile/test_pipeline_paper_e2e.py. Live-demo Deriv and MT5 runs remain intentionally gated: a no-trade refusal can be valid behavior when risk, entropy, scheduler, broker, or preflight gates reject the setup.


Documentation

Guide Description
Architecture Guide System design — physics core, canonical pipeline, manifold geometry
Rootfile Hamiltonian Canon One-to-one map from the lawful-collapse canon to the current rootfile runtime
API Reference Complete class and method reference for all modules
Tutorials Step-by-step guides: paper trading, dashboard, Telegram bot, brokers
Examples Working Python code snippets
Deployment Deployment notes and platform process commands
Roadmap Strategic roadmap beyond T3-A

Architecture

RAW MARKET DATA (MT5 / Deriv / TradingView)
        ↓
┌─────────────────────────────────────────┐
│         CANONICAL PIPELINE              │
│  1. Data Ingestion                      │
│  2. State Construction (microstructure) │
│  3. ICT Extraction (OB, FVG, BOS)       │
│  4. Geometry (ϕ → Γ → curvature K)      │
│  5. Trajectory Generation (RK4)         │
│  6. Ramanujan Compression               │
│  7. Admissibility Filtering             │
│  8. Action Evaluation (S[γ])            │
│  9. Path Integral Weighting             │
│ 10. Interference Selection              │
│ 11. Path Selection (γ* = argmin S)      │
│ 12. Proposal Generation                 │
│ 13. Admissibility Check (risk gate)     │
│ 14. Entropy Gate (ΔS < threshold)       │
│ 15. Scheduler Collapse ← CIRCUIT BREAKER│
│ 16. Execution (paper / live)            │
│ 17. Reconciliation ← PnL DIVERGENCE    │
│ 18. Evidence Emission (SHA-256 chain)   │
│ 19. Weight Update (PPO + backward law)  │
│ 20. Completed                           │
└─────────────────────────────────────────┘
        ↓
CRYPTOGRAPHIC AUDIT CHAIN

Rootfile-First Overlay

The repository now includes a non-breaking rootfile overlay that makes the architecture explicit without moving the current working engine. Existing imports under trading.*, taep.*, and apps.* remain valid, while new canonical imports expose the same runtime through governance-oriented layers:

Canonical layer Responsibility Current implementation mapped underneath
data_core Ingest, normalize, and prepare market state trading.brokers.market_data, broker feeds, storage/ML adapters
core.simulation Generate proposals only: geometry, path integrals, strategy logic trading.geometry, trading.path_integral, trading.operators, trading.rl
core.orchestration Select admissible paths and mint execution authority trading.kernel.scheduler, trading.kernel.apex_engine, constraints
core.authority Canonical ExecutionToken facade and token validation TAEP scheduler tokens plus trading scheduler token compatibility
core.execution Shadow/live/broker execution boundaries trading.shadow, apps.telegram.trading_live, broker adapters
tachyonic_chain Runtime SHA-256 audit-chain exports; optional bundle adapters tachyonic_chain.audit_log, trading.evidence.evidence_chain
backend_api Telegram, dashboard, and read/control surfaces apps.telegram, trading.dashboard

The law of motion is: data prepares state, simulation proposes, orchestration authorizes, execution acts, and evidence records. Shadow and live execution boundaries now validate scheduler-issued authority through core.authority.validate_token(...); proposal modules remain token-free so analysis stays cheap and safe.

The microstructure layer also exposes read-only order-book feed adapters. Binance public depth streams, IB/TWS market-depth callbacks, and fake/replay fixtures all normalize into OrderBookSnapshot objects with feed-health metadata. These feeds do not place orders or import broker execution surfaces.

Sandbox HFT execution uses a separate hft_execution token scope. The scheduler must mint a narrow token for broker, symbol, side, notional, slippage, order count, TTL, strategy id, and sandbox-only mode before the fake HFT gateway can accept an order. Real broker routing remains disabled.

Code-gated HFT canary routing is present but off by default. It refuses unless ALLOW_REAL_TRADING=1, HFT_CANARY_ENABLED=1, sandbox certification, non-sandbox HFT token scope, fresh feed health, hard risk limits, and kill-switch checks all pass. Rollback writes evidence and activates the HFT kill switch.

The overlay also adds registry/ and config/ artifacts that describe module placement, metadata requirements, system invariants, and the design tensor. Validators in tools/ check metadata, import direction, scheduler-only token minting, and token validation at execution boundaries. The core/self_healing package is intentionally inert for now: it provides the skeleton for future perception, violation detection, repair planning, repair execution, and revalidation once the validators are trusted.


Repository Structure

nvidia_chat/
├── core/                              ← Rootfile overlay: authority, orchestration, execution, simulation
├── data_core/                         ← Canonical data ingestion/storage/ML namespace
├── backend_api/                       ← Canonical bot/dashboard API namespace
├── tachyonic_chain/                   ← Canonical evidence/audit-chain namespace
├── registry/                          ← Design tensor, invariants, module map
├── tools/                             ← Rootfile validators and structural checks
├── trading/
│   ├── pipeline/orchestrator.py      ← 20-stage pipeline master
│   ├── kernel/
│   │   ├── apex_engine.py            ← Wavefunction collapse engine
│   │   ├── scheduler.py              ← Collapse authority + HMAC tokens
│   │   └── H_constraints.py          ← Constraint projectors
│   ├── geometry/                     ← Riemannian market manifold
│   │   ├── liquidity_field.py        ← ϕ(p,t) field computation
│   │   ├── connection.py             ← Christoffel symbols Γ^i_jk
│   │   ├── curvature.py              ← Gaussian curvature K
│   │   ├── metric.py                 ← Conformal metric g_ij
│   │   └── geodesic.py               ← Geodesic path corrections
│   ├── path_integral/
│   │   └── trajectory_generator.py  ← RK4 integration + ESS calibration
│   ├── operators/
│   │   └── operator_registry.py     ← All 18 ICT operators (exact math)
│   ├── risk/
│   │   ├── risk_manager.py           ← Hard stops, kill switch, regime limits
│   │   └── pnl_tracker.py           ← Daily PnL + execution error histogram
│   ├── resilience/
│   │   ├── circuit_breaker.py        ← CLOSED→OPEN→HALF_OPEN state machine
│   │   └── state_recovery.py         ← Crash recovery + snapshot persistence
│   ├── evidence/
│   │   └── evidence_chain.py         ← Ed25519 signatures + Merkle tree
│   ├── memory/
│   │   └── vector_store.py           ← FAISS 128-dim cosine similarity
│   ├── rl/
│   │   ├── scheduler_agent.py        ← PPO agent (166-dim state space)
│   │   └── ppo_paper_hook.py         ← Paper trade → RL reward feedback
│   ├── brokers/
│   │   ├── mt5_broker.py             ← MetaTrader 5
│   │   ├── deriv_broker.py           ← Deriv WebSocket
│   │   ├── tradingview_connector.py  ← TradingView webhooks
│   │   └── async_tick_loop.py        ← Asyncio producer-consumer tick ingestion
│   ├── dashboard/
│   │   └── app.py                    ← FastAPI live dashboard (/metrics, /kill)
│   ├── core/
│   │   └── market_regime_detector.py ← TRENDING/RANGING/HIGH_VOL/CRISIS
│   ├── shadow/                        ← Paper trading (zero capital)
│   ├── microstructure/                ← OFI, microprice, flow field
│   ├── agents/                        ← Multi-agent voting system
│   └── accelerated/                   ← Mojo / Cython / Numba speed tiers
│       ├── _path_integral.pyx
│       ├── _operators.pyx
│       └── mojo/core/trajectory_engine.mojo
├── taep/                              ← Physics core
│   ├── hamiltonians/                  ← H_geo, H_3body, H_total
│   ├── chaos/three_body.py            ← Lyapunov entropy source
│   ├── core/master_equation.py        ← Lindbladian dρ/dt
│   ├── scheduler/scheduler.py         ← ExecutionToken authority
│   └── constraints/                   ← Admissibility projectors Π
├── apps/telegram/                     ← Telegram bot + deployment wrapper
├── scripts/                           ← Broker, trading, and validation commands
├── tests/                             ← Maintained pytest suites
├── validation/                        ← Legacy and manual validation scripts
├── docs/deployment/                   ← Deployment guides
├── docs/reports/                      ← Historical implementation reports
├── docs/roadmaps/                     ← Strategic roadmaps
└── requirements.txt

Quick Start

git clone https://github.com/Mopati123/nvidia_chat.git
cd nvidia_chat
pip install -r requirements.txt

Run Paper Trading

python -m scripts.trading.start_paper_trading

Run the Dashboard

uvicorn trading.dashboard.app:app --host 0.0.0.0 --port 8080

Open http://localhost:8080 — live PnL, regime, circuit breaker state, kill switch.

Run Integration Tests

# T2 enhancements (geodesic, FAISS, PPO, async, dashboard, Mojo)
python -m pytest validation/legacy/test_t2_integration.py -v

# T3-A production hardening (circuit breaker, PnL divergence)
python -m pytest validation/legacy/test_t3a_integration.py -v

# Full test suite
python -m pytest tests/ -v

Environment Variables

# Signing key (Ed25519 private key PEM — never commit this)
export APEX_SIGNING_KEY="-----BEGIN PRIVATE KEY-----..."

# Broker credentials
export MT5_LOGIN="your_login"
export MT5_PASSWORD="your_password"
export MT5_SERVER="your_broker_server"

export DERIV_APP_ID="your_app_id"
export DERIV_API_TOKEN="your_token"

# NVIDIA API (for Telegram bot AI models)
export NVIDIA_API_KEY="your_nvidia_key"

# Telegram
export TELEGRAM_BOT_TOKEN="your_bot_token"

# Risk limits
export MAX_RISK_PER_TRADE="0.02"
export DAILY_LOSS_LIMIT="500"

The 18 ICT Operators

# Operator Physics Role ICT Concept
O1 T(p;σ) Kinetic energy Momentum
O2 V_LP(x) Volume-weighted attraction Liquidity pools
O3 V_OB(x) Institutional footprint Order blocks
O4 V_FVG(x) Imbalance potential Fair value gaps
O5 V_macro(t) Session time-decay Kill zones
O6 V_PD(x) Price delivery Premium/discount
O7 V_regime BOS/CHOCH continuous score Market regime
O8 Π_session Trading hours gate Session filter
O9 Π_risk Exposure limit gate Risk management
O10 L(n) Sailing lane decay Multi-leg alpha
O11 S_liq Sweep + reversal speed Liquidity sweeps
O12 D(x,t) Displacement score Impulsive moves
O13 BB(x) Phase transition proximity Breaker blocks
O14 MB(x) Mitigation 1-dist/ATR Mitigation blocks
O15 OTE(x) Fibonacci 0.62–0.79 from BOS Optimal trade entry
O16 J(x,t) Judas reversal speed Judas swings
O17 A(x,t) Wyckoff range compression Accumulation/distribution
O18 ⟨ψ|H|ψ⟩ Quadratic expectation value Full quantum readout

Runtime Safety And Proof Governance

Circuit Breaker — Stage 15 (Scheduler Collapse):

  • 10 consecutive failures → circuit opens → risk_manager.trigger_kill_switch() fires automatically
  • OPEN circuit rejects all collapse attempts immediately
  • HALF_OPEN state: 3 successes required to recover

PnL Divergence Detection — Stage 17 (Reconciliation):

  • Tracks |predicted_pnl - realized_pnl| / max(|predicted_pnl|, 1.0) per execution
  • 15% divergence → weight penalty applied via scheduler.update_action_weights()

  • Rolling 100-trade histogram with mean/std/p95 stats

Stage Proof Chain - All canonical stages:

  • Each StageResult carries operator metadata, canonical law, input hash, output hash, previous hash, proof hash, and refusal code.
  • Terminal COMPLETED and FAILED records close the proof chain so offline paper runs are auditable end to end.
  • Secret-like keys such as tokens, passwords, credentials, API keys, and signatures are redacted before hashing.

Enhancement Roadmap

See T3_ROADMAP.md for the full strategic plan.

Phase What Status
T1 (A/B/C) Security, legacy O1-O18 operators, regime wiring COMPLETE
T2 (A–H) Geodesic trajectories, FAISS, PPO, async, dashboard, Mojo COMPLETE
T3-A Circuit breaker + PnL divergence COMPLETE
Rootfile stage proofs Operator contracts + deterministic stage proof chain COMPLETE
T3-C Prometheus metrics + Grafana Planned
T3-D Slippage model + partial fill Planned
T3-B GPU trajectory batching (50–200×) Planned
T3-E Distributed backtester Planned
T3-F Ensemble RL + curiosity exploration Planned

Test Coverage

Suite Tests Status
T2 Integration 6 PASSED
T3-A Integration 20 PASSED
Geometry unit tests 15 PASSED
TAEP unit tests 8 PASSED
Full pipeline integration 1 PASSED

License

MIT License — See LICENSE file.


Version: 2.1.0 (rootfile stage-proof runtime) Last Updated: 2026-05-22

About

No description, website, or topics provided.

Resources

Contributing

Security policy

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages