Skip to content

Repository files navigation

Axiom Logo

Axiom: Agentic Trading Engine

Axiom Banner

AI-Powered Cryptocurrency Trading Platform using Agentic AI, LangGraph, Bayesian Forecasting, and Explainable Intelligence.

License: MIT Version Python Version Node Version Docker Build Status Coverage Documentation Discord Stars Forks

Documentation β€’ Live Demo β€’ Report Bug β€’ Request Feature β€’ Website


Table of Contents

πŸ“‘ Table of Contents


πŸ“– Project Overview

The Problem

Current algorithmic trading bots rely on rigid, hardcoded rules, simple lagging indicators (like moving average crossovers), and naive binary classifiers. They fail spectacularly during regime changes, black swan events, or high-volatility shifts. Furthermore, they lack the ability to adapt, reason about macroeconomic news, or provide human-readable explanations for their catastrophic drawdowns.

Why Axiom? Why Agentic AI?

Axiom solves this by moving away from hardcoded logic and replacing it with an Agentic AI Workflow powered by LangGraph. Instead of running a single if/else script, Axiom spins up specialized, autonomous LLM agents (e.g., News Agent, Whale Agent, Macro Agent). These agents gather data in parallel, debate market conditions, and converge on a single mathematically sound trading decision.

Why Bayesian Forecasting (Orbit DLT)?

Traditional machine learning in trading (like XGBoost or LSTMs) is highly prone to overfitting on noise. Axiom utilizes Uber's Orbit DLT (Damped Local Trend) model, which employs Bayesian Structural Time Series forecasting via CmdStanPy and MCMC (Markov Chain Monte Carlo). This allows Axiom to predict continuous price ranges and inherently measure uncertainty (confidence intervals), rather than blindly guessing UP or DOWN.

Business & Technical Value

  • Institutional-Grade Reasoning: Provides Explainable AI (XAI) reports detailing exactly why a trade was taken, bridging the gap between black-box AI and quantitative transparency.
  • Massive Parallelism: Evaluates on-chain data, global news, social sentiment, and Bayesian forecasts simultaneously in under 400ms.
  • Future Vision: Evolving from a single-user portfolio manager to a decentralized swarm of specialized trading agents optimizing yield across DeFi and CeFi simultaneously.

πŸ“Έ Screenshots

Dashboard & Portfolio Agent Strategy Monitor
Dashboard Agent Monitor
Real-time Risk Metrics & PnL Live LangGraph DAG Execution Trace
Dark Mode Trading View Explainable AI (XAI) Signals
Dark Mode Signals
Integrated Chart.js Financial Visualization Human-Readable Rationale for Trades

πŸ› Complete System Architecture

Axiom operates on a highly decoupled, microservice-inspired architecture separating state management, AI inference, and execution.

flowchart LR
    %% Entities
    U([User / Trader])
    
    %% Presentation
    subgraph Frontend [Presentation Layer - Next.js]
        UI[React / Tailwind UI]
        State[React Query / Framer]
    end

    %% Gateway
    subgraph Gateway [API Gateway]
        Auth[JWT / OAuth]
        REST[FastAPI REST API]
        WSS[WebSocket Server]
    end

    %% Core Application
    subgraph Backend [Core Application - Python]
        Orchestrator[LangGraph Orchestrator]
        Risk[Risk Management Service]
        Exec[Execution Engine]
    end

    %% AI Layer
    subgraph AI [AI & Machine Learning]
        LLM[LiteLLM / OpenAI]
        Orbit[Orbit DLT / CmdStan]
        NLP[FinBERT Sentiment]
    end

    %% Data & Persistence
    subgraph Persistence [Data Layer]
        PG[(PostgreSQL)]
        Redis[(Redis Memory & Cache)]
    end

    %% External
    subgraph External [External Integrations]
        CCXT[Exchange APIs]
        News[News / Social APIs]
        Notify[Sentry / Prometheus]
    end

    %% Connections
    U <-->|HTTP / WSS| Frontend
    Frontend <--> Gateway
    Gateway <--> Backend
    Backend <--> AI
    Backend <--> Persistence
    Backend <--> External
Loading

πŸ“ Folder Structure

Axiom utilizes a strict enterprise Monorepo architecture, optimizing code sharing between the frontend client and the AI backend.

Axiom/
β”‚
β”œβ”€β”€ apps/
β”‚   β”œβ”€β”€ web/                 # Next.js 14 Frontend Application
β”‚   └── api/                 # FastAPI Backend Application
β”‚
β”œβ”€β”€ packages/
β”‚   β”œβ”€β”€ ui/                  # Shared React components and Tailwind configs
β”‚   β”œβ”€β”€ types/               # Shared TypeScript / Pydantic types
β”‚   β”œβ”€β”€ config/              # ESLint, Prettier, and TS configs
β”‚   β”œβ”€β”€ shared/              # Shared utility functions (formatting, math)
β”‚   └── sdk/                 # Client SDK for interacting with the Axiom API
β”‚
β”œβ”€β”€ infrastructure/          # Terraform / Pulumi definitions for cloud deployment
β”œβ”€β”€ docker/                  # Dockerfiles and Docker Compose orchestrations
β”œβ”€β”€ nginx/                   # Reverse proxy and load balancing configurations
β”œβ”€β”€ monitoring/              # Prometheus, Grafana, and OpenTelemetry configs
β”œβ”€β”€ scripts/                 # Bash/Python scripts for DB migrations and seeding
β”œβ”€β”€ docs/                    # Extensive markdown documentation (Architecture, API, ML)
β”œβ”€β”€ examples/                # Example API requests and strategy JSONs
β”œβ”€β”€ datasets/                # Sample OHLCV data for local ML training
β”œβ”€β”€ notebooks/               # Jupyter Notebooks for EDA and Model Prototyping
β”œβ”€β”€ tests/                   # Pytest (Backend) and Jest/Cypress (Frontend)
β”œβ”€β”€ .github/                 # CI/CD Workflows, Issue Templates, CODEOWNERS
β”‚
β”œβ”€β”€ README.md                # This document
β”œβ”€β”€ CONTRIBUTING.md          # Guidelines for open source contributors
β”œβ”€β”€ SECURITY.md              # Vulnerability reporting and RBAC details
β”œβ”€β”€ ROADMAP.md               # Future milestones and features
β”œβ”€β”€ CHANGELOG.md             # Semantic versioning history
β”œβ”€β”€ LICENSE                  # MIT License
└── CODE_OF_CONDUCT.md       # Community standards

πŸ— Architecture Layers

Axiom is built upon Domain-Driven Design (DDD) principles, enforcing strict separation of concerns:

  1. Presentation Layer: Next.js (SSR/CSR) handling UI rendering, optimistic updates (React Query), and complex charting (Chart.js).
  2. Application Layer: FastAPI routing, JWT authorization validation, and WebSocket multiplexing.
  3. Domain Layer: Business logic handling strategy creation, portfolio validation, and risk parameters.
  4. AI Layer: LangGraph orchestrating agent state transitions, LLM tool calling (LiteLLM), and prompt compilation.
  5. ML Layer: Statistical inference environments running Pandas, Scikit-learn, and the Orbit Bayesian model via CmdStan.
  6. Infrastructure Layer: Docker containers, Redis Pub/Sub, and Nginx reverse proxies.
  7. Persistence Layer: PostgreSQL (via SQLAlchemy/Alembic) for ACID transactions, Redis for ephemeral state (Checkpoints).
  8. Notification Layer: Decoupled service pushing events to Webhooks, Discord, or Email.
  9. Monitoring Layer: Prometheus metrics exposing latency and LLM token usage, visualized in Grafana.
  10. Security Layer: JWT validation, SQL injection prevention, and Redis-backed rate limiting.

πŸ•Έ LangGraph Workflow

At the core of Axiom is a deterministic State Machine powered by LangGraph. It utilizes Parallel Fan-Out to gather intelligence with zero latency bottlenecks, followed by a Fan-In for reasoning.

stateDiagram-v2
    [*] --> Initialize_TickState
    Initialize_TickState --> Fetch_Price_OHLCV
    Fetch_Price_OHLCV --> Compute_Indicators
    
    state Parallel_Fan_Out {
        Compute_Indicators --> Fetch_News_Sentiment
        Compute_Indicators --> Fetch_Social_Sentiment
        Compute_Indicators --> Fetch_Fear_Greed
        Compute_Indicators --> Fetch_Whale_Activity
        Compute_Indicators --> Fetch_ML_Prediction
        Compute_Indicators --> Load_Historical_Memory
    }

    Fetch_News_Sentiment --> Fan_In_Reasoning
    Fetch_Social_Sentiment --> Fan_In_Reasoning
    Fetch_Fear_Greed --> Fan_In_Reasoning
    Fetch_Whale_Activity --> Fan_In_Reasoning
    Fetch_ML_Prediction --> Fan_In_Reasoning
    Load_Historical_Memory --> Fan_In_Reasoning

    Fan_In_Reasoning --> Risk_Guard
    Risk_Guard --> Persist_and_Notify
    Persist_and_Notify --> [*]
Loading

Key Mechanisms:

  • Conditional Edges: If the configuration disables social sentiment, the edge is pruned at runtime, saving compute.
  • Checkpointing: The TickState is saved to PostgreSQL after every node execution. If the LLM rate-limits, the graph resumes exactly where it failed.
  • Human Approval (Optional): An edge can be configured to pause the graph before Persist_and_Notify, requiring human approval via the UI for trades exceeding a specific capital threshold.

πŸ€– Agent Architecture

Axiom relies on specialized sub-agents, preventing context-window exhaustion and hallucination in the primary LLM.

  • Market Agent: Ingests live OHLCV data to detect micro-structure patterns.
  • Indicator Agent: Analyzes RSI, MACD, and Bollinger Bands to identify oversold/overbought extremes.
  • News Agent: Scrapes global financial news, summarizes events, and assigns a FinBERT impact score.
  • Social Agent: Monitors Twitter/Reddit for retail frenzy or capitulation markers.
  • Whale Agent: Analyzes on-chain movements (e.g., large Exchange Inflows indicating a dump).
  • Macro Agent: Assesses Fed interest rates, CPI data, and global liquidity indexes.
  • ML Agent: Interfaces with the Orbit Bayesian model to extract quantitative price forecasts.
  • Memory Agent: Retrieves the last 10 actions taken by the system to maintain logical continuity.
  • Risk Agent: Enforces hardcoded boundaries (e.g., max 5% drawdown per day).
  • Reasoning Agent: The Master LLM node. Synthesizes all inputs and outputs the final JSON decision.
  • Execution Agent: Handles API routing, slippage calculation, and TWAP/VWAP order chunking.
  • Notification Agent: Formats complex JSON objects into human-readable Slack/Discord alerts.
  • Audit Agent: Runs asynchronously to verify trade execution matched the intended strategy logic.

⚑ AI Decision Flow

sequenceDiagram
    participant User
    participant API as API Gateway
    participant LG as LangGraph
    participant ML as Orbit DLT
    participant LLM as Reasoning LLM
    participant Risk as Risk Engine
    participant DB as PostgreSQL
    participant Exch as Exchange (CCXT)

    User->>API: Activate Strategy (ETH/USD)
    API->>LG: Initialize TickState
    LG->>ML: Fetch Bayesian Forecast
    ML-->>LG: {price: 3450, conf: 82%}
    LG->>LLM: Compile Inputs (News, Tech, ML)
    LLM-->>LG: JSON Output: {action: BUY, size: 2}
    LG->>Risk: Validate against Drawdown limits
    Risk-->>LG: Approved
    LG->>Exch: Execute Market Order
    Exch-->>LG: Fill: 2 ETH @ $3451
    LG->>DB: Persist Checkpoint & Audit Log
    LG-->>User: WSS Push Notification
Loading

πŸ“Š Data Pipeline

Data integrity is critical for ML and AI reasoning. Axiom's pipeline is strictly typed:

  1. Ingestion: Exchange WebSockets and REST APIs pull raw data.
  2. Cleaning: Pandas removes NaN values, handles missing candles via interpolation, and normalizes timestamps to UTC.
  3. Feature Engineering: Calculation of momentum, volatility, and volume indicators.
  4. Prediction: Transformed data is fed into the Orbit .pkl model.
  5. Decision: Outputs enter the LangGraph state.
  6. Execution: Standardized via CCXT.
  7. Persistence: Raw inputs and LLM outputs are logged for MLOps retraining.
  8. Analytics: Portfolio tracking updates total equity curves.

🧠 Machine Learning (Orbit DLT)

Axiom uses Uber's Orbit (Bayesian Structural Time Series) rather than XGBoost or LSTMs.

The Mechanics

  • Bayesian Inference: Instead of a single point prediction, Orbit calculates a probability distribution of future prices.
  • CmdStan & MCMC: Orbit uses Markov Chain Monte Carlo (MCMC) sampling via CmdStanPy. It runs 4 chains in parallel across 8 CPU cores to guarantee mathematical convergence on the optimal weights.
  • Structural Components: The model equation combines Trend (Damped Local Trend), Seasonality (Day of week cycles), and Regressors (RSI, MACD, Volume).

Evaluation Metrics

Axiom tracks strict financial ML metrics during validation:

  • Directional Accuracy: Did the model correctly guess UP or DOWN? (Target > 55%).
  • MAE / MAPE: Mean Absolute Error and Percentage Error to measure exact dollar deviations.
  • RMSE: Heavily penalizes large prediction errors.

πŸ’‘ Explainable AI (XAI)

Black-box trading algorithms are uninvestable. Axiom enforces Explainable Intelligence.

Every trade executed by Axiom generates an XAI Report. The Reasoning LLM is prompted to output a strict JSON schema containing:

  • Evidence: The exact data points (e.g., "RSI is 22, Whale Inflow decreased by 40%").
  • Confidence: A 0-100 score based on signal convergence.
  • Rationale: A human-readable paragraph explaining Why Buy, Why Sell, or Why Hold.

πŸ—„ Database Design

Axiom relies on a highly normalized PostgreSQL database.

erDiagram
    USERS ||--o{ STRATEGIES : creates
    USERS ||--o{ PORTFOLIOS : owns
    USERS ||--o{ WALLETS : manages
    
    STRATEGIES ||--o{ SIGNALS : generates
    STRATEGIES ||--o{ ORDERS : executes
    
    PORTFOLIOS ||--o{ POSITIONS : contains
    
    ORDERS ||--o{ AUDIT_LOGS : tracked_by
    SIGNALS ||--o{ MODEL_PREDICTIONS : informed_by
    
    USERS {
        uuid id PK
        string email
        string hashed_password
        string role
    }
    
    STRATEGIES {
        uuid id PK
        uuid user_id FK
        jsonb configuration
        boolean is_active
    }
    
    ORDERS {
        uuid id PK
        string symbol
        string side
        float amount
        float fill_price
        string status
    }
Loading

πŸ”Œ API Documentation

Detailed API documentation is auto-generated via FastAPI's Swagger UI (/docs).

Key Endpoints:

  • POST /api/v1/auth/token - OAuth2 JWT Generation
  • GET /api/v1/portfolio/balances - Fetch aggregated exchange balances
  • POST /api/v1/strategies/{id}/start - Initialize a LangGraph worker
  • GET /api/v1/signals/history - Retrieve XAI trade reasoning logs

πŸ” Authentication Flow & Security

Auth Flow

Axiom uses JWT (JSON Web Tokens).

  1. Client sends credentials.
  2. Server validates Argon2id hash and issues a short-lived access_token and an HttpOnly refresh_token.
  3. Client attaches Bearer token to headers for protected routes.
  4. Role-Based Access Control (RBAC) ensures users cannot access other users' portfolios.

Security Posture (OWASP Compliant)

  • Secrets: API keys are encrypted at rest using AES-256-GCM.
  • SQL Injection: Mitigated entirely via SQLAlchemy ORM parameterized queries.
  • Rate Limiting: Redis-backed sliding window prevents brute-force API attacks.
  • Input Validation: Pydantic models reject malformed JSON payloads instantly.

☁️ Deployment Architecture

Axiom is cloud-agnostic, ready for Kubernetes, AWS ECS, or Docker Swarm.

flowchart TD
    Internet((Internet)) --> CF[Cloudflare WAF]
    CF --> Nginx[Nginx Reverse Proxy]
    Nginx --> Frontend[Next.js Containers]
    Nginx --> API[FastAPI Containers]
    
    API --> Redis[(Redis Cluster)]
    API --> PG[(PostgreSQL RDS)]
    
    API --> Worker1[LangGraph Worker Node]
    API --> Worker2[LangGraph Worker Node]
    
    Worker1 --> Orbit[ML Inference Service]
    Worker2 --> Orbit
Loading

πŸ›  DevOps & Monitoring

CI/CD Pipeline (GitHub Actions)

  1. Linting: Flake8, Black, ESLint, Prettier.
  2. Testing: Pytest & Jest run on every Push. Coverage must exceed 80%.
  3. Build: Docker images are built and pushed to GitHub Container Registry (GHCR).
  4. Release Automation: Semantic Release bumps versions and updates the Changelog automatically.

Observability

  • Prometheus / Grafana: Tracks system memory, CPU, and API latency.
  • OpenTelemetry: Traces the execution path of a single tick through the LangGraph DAG.
  • Sentry: Catches unhandled Python/Node exceptions instantly.

βš™οΈ Configuration

Axiom uses a hierarchical configuration system (Environment Variables > .env > Defaults).

  • DATABASE_URL: PostgreSQL connection string.
  • REDIS_URL: Redis broker URL.
  • OPENAI_API_KEY: Required for LangGraph reasoning.
  • BINANCE_API_KEY: Required for execution.

πŸš€ Installation & Usage

1. Docker (Recommended for Production)

git clone https://github.com/axiom-trading/axiom.git
cd axiom
docker-compose -f docker-compose.prod.yml up -d --build

Access the Dashboard at http://localhost:3000 and API at http://localhost:8000.

2. Local Development (macOS / Linux)

Backend:

cd apps/api
python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
uvicorn main:app --reload

Frontend:

cd apps/web
pnpm install
pnpm dev

πŸ§ͺ Testing

Axiom enforces rigorous testing standards:

  • Unit Tests: Testing individual technical indicators and ML data loaders. (pytest tests/unit)
  • Integration Tests: Validating the interaction between LangGraph and the SQLite test database.
  • E2E Tests: Cypress tests verifying the frontend dashboard renders correctly.

πŸ“š Documentation

For deep-dive technical reading, view the docs/ folder:

  • ARCHITECTURE.md - System Design
  • AI.md - LangGraph & Agent logic
  • ML.md - Orbit DLT and Bayesian math
  • API.md - REST specifications
  • DEPLOYMENT.md - K8s and Cloud architectures
  • DEVELOPMENT.md - Contributing guide

πŸ—Ί Roadmap

  • Near Term: Live trading on Binance, Advanced Paper Trading.
  • Medium Term: Decentralized Swarm Intelligence, Deep Reinforcement Learning integration.
  • Long Term: Protocol-level DeFi yield farming via smart contract execution.

🀝 Contribution Guide

We operate on strict open-source enterprise standards. Please read CONTRIBUTING.md before opening a PR.

  • Branch Naming: feat/add-rsi, fix/db-timeout.
  • Commit Conventions: Conventional Commits required (feat: ..., fix: ...).

πŸ“„ License & Acknowledgements

License: Distributed under the MIT License. See LICENSE for more information.

Acknowledgements: Axiom is built on the shoulders of giants. We deeply thank the maintainers of:


**Built with 🀍 by the Axiom Engineering Team.**

πŸ› Complete System Architecture

This document provides a highly detailed, enterprise-grade overview of the Axiom Agentic Trading Engine. Every architectural decision is explained with its engineering rationale, scalability considerations, and trade-offs.

1. The Monolithic Microservice Dilemma (Engineering Rationale)

Axiom utilizes a modular monolith approach on the backend. While a true microservice architecture (where ML inference, LangGraph orchestration, and API routing exist in separate repositories) offers horizontal scalability, it introduces unacceptable network latency and serialization overhead for high-frequency algorithmic trading.

By containing the core logic within a single Python FastAPI backend (while offloading heavy Bayesian inference to background Celery/Ray workers), Axiom achieves the perfect balance:

  • Low Latency: State transitions within LangGraph occur in-memory without HTTP hops.
  • Scalability: The FastAPI workers are stateless. We can spin up N Docker containers behind an Nginx load balancer to handle thousands of concurrent trading strategies.

2. High-Level Architecture Diagram

flowchart TD
    subgraph Client [Client / Trader Layer]
        Browser[Web Browser]
        Mobile[Mobile Application]
    end

    subgraph Edge [Edge & Ingress]
        WAF[Cloudflare WAF]
        Nginx[Nginx Reverse Proxy / Load Balancer]
    end

    subgraph Presentation [Presentation Layer - Next.js]
        SSR[Next.js SSR Server]
        Static[CDN Delivered Assets]
    end

    subgraph Application [Application Layer - FastAPI]
        Gateway[API Gateway / Router]
        Auth[JWT Authorization middleware]
        WS[WebSocket Multiplexer]
    end

    subgraph Domain [Domain & Execution Layer]
        Portfolio[Portfolio Manager]
        Risk[Risk Management Firewall]
        Exec[CCXT Execution Engine]
    end

    subgraph Intelligence [AI & Machine Learning Layer]
        LangGraph[LangGraph Orchestrator]
        LLM[Reasoning Node - LiteLLM]
        Orbit[Orbit DLT Inference Service]
        NLP[FinBERT Sentiment Analyzer]
    end

    subgraph Data [Persistence & State]
        PG[(PostgreSQL Primary)]
        Redis[(Redis Cache / PubSub)]
    end

    subgraph External [External Integrations]
        Binance[Exchange APIs]
        NewsAPI[Global News Feeds]
    end

    %% Routing
    Browser --> WAF
    Mobile --> WAF
    WAF --> Nginx
    
    Nginx --> SSR
    Nginx --> Gateway
    
    Gateway --> Auth
    Auth --> Domain
    Auth --> WS
    
    Domain --> Intelligence
    Intelligence --> Data
    Domain --> External
Loading

3. Architecture Layers (Deep Dive)

3.1 Presentation Layer

  • Technology: Next.js 14, React 18, Tailwind CSS, React Query.
  • Responsibility: Delivering a sub-100ms TTI (Time to Interactive) dashboard.
  • Rationale: We chose Next.js for its Server-Side Rendering (SSR) capabilities, which allows us to securely pre-fetch sensitive portfolio data before the page reaches the client. React Query is heavily utilized to cache API responses and manage optimistic UI updates when placing manual trades.
  • Trade-off: Next.js introduces Node.js into our stack. We mitigated the complexity by using a strict Monorepo structure, sharing TypeScript types between the Next.js frontend and the Pydantic models (via OpenAPI generators).

3.2 Application Layer

  • Technology: FastAPI (Python), Uvicorn.
  • Responsibility: HTTP routing, WebSocket multiplexing, and input validation.
  • Rationale: FastAPI, built on Starlette and Pydantic, is currently the highest-performing asynchronous Python framework. It natively supports Python 3.10+ async/await, allowing a single worker to handle thousands of concurrent WebSocket connections (vital for streaming real-time candlestick data to the client).
  • Scalability: Completely stateless. Session state is relegated entirely to Redis.

3.3 Domain Layer

  • Technology: Pure Python, specialized design patterns (Strategy, Factory).
  • Responsibility: The core business rules of Axiom. It defines what a "Portfolio" is, what constitutes a "Risk Violation," and how an "Order" is constructed.
  • Rationale: By isolating Domain logic from the Application and AI layers, we can rigorously unit test the Risk Management Firewall without needing to mock complex LLM responses.

3.4 AI Layer (Agentic Orchestration)

  • Technology: LangGraph, LangChain, LiteLLM.
  • Responsibility: Managing the Directed Acyclic Graph (DAG) state machine.
  • Rationale: Standard LLM chains (like AgentExecutor) are linear and brittle. LangGraph allows Axiom to define cyclic graphs (loops) with Conditional Edges. For example, if the LLM's decision is rejected by the Risk Firewall, LangGraph cycles the state back to the LLM with an error message: "Decision rejected due to 5% drawdown limit. Propose new allocation."
  • Trade-off: LangGraph adds slight orchestration overhead compared to raw OpenAI API calls. However, the robustness gained through native checkpointing (saving the graph state to PostgreSQL) is critical for financial applications.

3.5 ML Layer (Quantitative Forecasting)

  • Technology: Uber Orbit, CmdStanPy, Scikit-learn, Pandas.
  • Responsibility: Time-series forecasting and feature engineering.
  • Rationale: We decoupled the ML inference from the main FastAPI thread. Bayesian inference via MCMC (Markov Chain Monte Carlo) is highly CPU-intensive. When the LangGraph state machine requires a price prediction, it fires an async RPC call to a dedicated ML worker pool.
  • Scalability: The .pkl model artifacts are loaded into memory once during worker initialization.

3.6 Infrastructure Layer

  • Technology: Docker, Docker Compose, Nginx.
  • Responsibility: Environment consistency and reverse proxying.
  • Rationale: Nginx sits at the edge, terminating SSL/TLS and stripping away malformed headers. It routes /api/* traffic to the FastAPI backend and / traffic to the Next.js frontend.

3.7 Persistence Layer

  • Technology: PostgreSQL, Redis.
  • Responsibility: ACID transactions for trades and ephemeral caching.
  • Rationale: PostgreSQL handles the highly relational data (Users -> Portfolios -> Trades -> Audit Logs). Redis acts as a high-speed cache for OHLCV data (reducing CCXT API calls to the exchange) and manages the Celery/Message Queue for background ML tasks.

3.8 Notification Layer

  • Responsibility: Async pushing of events (Trade executed, Stop Loss hit, System Error) to Discord Webhooks or Email via SendGrid.
  • Design: Completely non-blocking. Notifications are pushed to a Redis queue and consumed by a lightweight worker.

3.9 Monitoring Layer

  • Technology: Prometheus, Grafana, OpenTelemetry.
  • Responsibility: Tracking the health of the engine.
  • Metrics Tracked: llm_token_usage, api_latency_ms, exchange_api_rate_limit_remaining, orbit_inference_time.

3.10 Security Layer

  • Responsibility: Enforcing RBAC (Role-Based Access Control) and mitigating OWASP Top 10 vulnerabilities.
  • Implementation: All database queries use SQLAlchemy's parameterized queries to prevent SQL Injection. Passwords are hashed using Argon2id (resistant to GPU cracking). API keys are AES-256 encrypted at rest.

πŸ€– Agentic AI & LangGraph Architecture

This document explores the core intelligence of Axiom. Unlike legacy trading bots that execute rigid if-then statements, Axiom utilizes an Agentic Workflow orchestrated by LangGraph, enabling dynamic reasoning, error recovery, and robust decision-making.

1. Why LangGraph? (Engineering Rationale)

In building Axiom, we evaluated raw OpenAI API calls, standard LangChain AgentExecutor chains, and AutoGPT-style autonomous loops.

  • The Chain Problem: Standard chains are linear. If a sub-agent fails or an API times out, the entire sequence crashes.
  • The AutoGPT Problem: Fully autonomous agents often get stuck in infinite hallucination loops, consuming massive amounts of API tokens without producing a valid trading decision.

The LangGraph Solution: LangGraph allows us to model the trading execution as a State Machine represented by a Directed Acyclic Graph (DAG). It provides:

  1. Cycles (Loops): We can explicitly route a failed LLM output back to itself for correction.
  2. State Persistence (Checkpoints): LangGraph natively saves the TickState to PostgreSQL after every node. If the server reboots mid-trade, the graph resumes exactly where it left off.
  3. Human-in-the-Loop: We can inject "breakpoints" into the graph, requiring human authorization for high-risk trades before proceeding to the execution node.

2. The LangGraph DAG Workflow

Axiom's primary execution cycle is called a "Tick." A Tick is instantiated every minute (or configured timeframe) for active strategies.

stateDiagram-v2
    [*] --> Initialize_TickState
    Initialize_TickState --> Fetch_Price_OHLCV
    Fetch_Price_OHLCV --> Compute_Indicators
    
    state Parallel_Fan_Out {
        Compute_Indicators --> Fetch_News_Sentiment
        Compute_Indicators --> Fetch_Social_Sentiment
        Compute_Indicators --> Fetch_Fear_Greed
        Compute_Indicators --> Fetch_Whale_Activity
        Compute_Indicators --> Fetch_ML_Prediction
        Compute_Indicators --> Load_Historical_Memory
    }

    Fetch_News_Sentiment --> Fan_In_Reasoning
    Fetch_Social_Sentiment --> Fan_In_Reasoning
    Fetch_Fear_Greed --> Fan_In_Reasoning
    Fetch_Whale_Activity --> Fan_In_Reasoning
    Fetch_ML_Prediction --> Fan_In_Reasoning
    Load_Historical_Memory --> Fan_In_Reasoning

    Fan_In_Reasoning --> Risk_Guard
    Risk_Guard --> Persist_and_Notify
    Persist_and_Notify --> [*]
Loading

2.1 Parallel Fan-Out

To minimize latency, Axiom utilizes asyncio.gather within LangGraph to execute data-fetching nodes concurrently. Instead of waiting 100ms for news, then 150ms for ML predictions, then 200ms for on-chain data, all external API calls occur simultaneously.

2.2 Fan-In (The Convergence)

The Fan_In_Reasoning node receives the populated TickState dictionary. It compiles this massive payload into a highly structured prompt injected into the LLM.

3. Agent Architecture (Sub-Agents)

To prevent context-window exhaustion and hallucination, Axiom utilizes a Swarm of specialized sub-agents.

Data Gathering Agents

  • Market Agent: Ingests OHLCV and calculates order book depth imbalances.
  • Indicator Agent: Flags extreme conditions (RSI > 80, MACD bearish crosses).
  • News Agent: Scrapes headlines and utilizes FinBERT to output a normalized Sentiment Score (-1 to 1).
  • Social Agent: Monitors Twitter/Reddit cashtags ($BTC, $ETH) for retail frenzy markers.
  • Whale Agent: Tracks on-chain metrics via Etherscan/Glassnode (e.g., Large Exchange Inflows).
  • Macro Agent: Queries traditional finance APIs for DXY (US Dollar Index) and Treasury Yields, which heavily impact crypto liquidity.

Operational Agents

  • Memory Agent: Retrieves the last 10 LLM decisions from the PostgreSQL database. This prevents "flip-flopping" (e.g., buying, immediately selling, then buying again) by giving the LLM context of its own previous reasoning.
  • ML Agent: A specialized bridge to the Orbit DLT Bayesian model.
  • Risk Agent: The "Adult in the Room." This agent ignores all AI reasoning and mathematically checks the proposed trade against the user's hard limits (e.g., "Max 2% capital allocation per trade"). If limits are breached, it overrides the decision.
  • Reasoning Agent: The Master Node. It synthesizes the data and must return a strictly typed JSON response conforming to our Pydantic schema.

4. Explainable AI (XAI)

One of the most critical features of Axiom is Explainable Intelligence. Institutional capital cannot be managed by a "black box" that simply says "BUY."

When the Reasoning Agent makes a decision, it is forced by its System Prompt to output a JSON object containing its rationale.

The JSON Output Schema

{
  "action": "BUY",
  "confidence": 85,
  "allocation_percentage": 5,
  "reasoning": {
    "evidence": [
      "Orbit ML model forecasts a 3% price increase over the next 24 hours.",
      "RSI is currently 28, indicating an oversold condition.",
      "Whale exchange outflows increased by 15% in the last hour, signaling accumulation."
    ],
    "rationale_summary": "The confluence of deeply oversold technicals, strong on-chain accumulation, and positive Bayesian forecasting provides a high-probability mean-reversion setup. Executing a 5% allocation."
  },
  "suggested_sl": 3200.50,
  "suggested_tp": 3550.00
}

This output is saved to the database and displayed in the frontend UI, allowing human traders to audit the AI's logic historically.

πŸ“ˆ Machine Learning: Orbit DLT & Bayesian Forecasting

Axiom relies on Uber's Orbit (Bayesian Structural Time Series) for its core quantitative price forecasting. This document explains the engineering rationale behind abandoning XGBoost in favor of Orbit, and details the rigorous MLOps pipeline utilized by the system.

1. The Flaws of Legacy Models (XGBoost & LSTMs)

Historically, algorithmic trading bots utilize binary classifiers (like Random Forest or XGBoost) to guess whether a candle will close UP or DOWN.

  • The Overfitting Problem: Financial time series data is overwhelmingly noisy. Decision trees aggressively memorize this noise.
  • The Lag Problem: Features fed into these models (MACD, RSI) are lagging indicators. By the time XGBoost recognizes a trend, the alpha has evaporated.
  • Lack of Confidence Intervals: A standard Neural Network outputs a deterministic float. It cannot accurately express its own statistical uncertainty.

2. Why Orbit DLT? (Bayesian Structural Time Series)

Orbit solves these problems by treating the price not as a classification problem, but as a continuous structural equation.

Orbit decomposes the time series into three latent variables:

  1. Trend ($T_t$): Axiom uses the Damped Local Trend (DLT) model. Unlike linear trends that extrapolate to infinity, DLT mathematically forces the trend to "flatten out" over time, perfectly mirroring the mean-reverting nature of crypto markets.
  2. Seasonality ($S_t$): Captures recurring cycles (e.g., lower weekend volume, funding rate epochs).
  3. Regressors ($R_t$): Exogenous variables. This is where we inject our Feature Engineering (Volume profiles, RSI, etc.).

By utilizing Bayesian inference, Orbit outputs a Posterior Distribution. It doesn't just predict the price will be $64,000; it predicts the price will be $64,000 with a 95% confidence interval between $63,200 and $65,100.

3. The MCMC Training Process

Training an Orbit model is computationally expensive. It relies on Markov Chain Monte Carlo (MCMC) sampling via the CmdStanPy engine.

When Axiom's MLOps pipeline triggers a retrain (python train.py model=orbit):

  1. Chains (4): CmdStan launches 4 completely independent simulations simultaneously.
  2. Cores (8): These chains run in parallel across CPU cores.
  3. Warmups (225): The MCMC algorithm takes 225 random "burn-in" steps to explore the probability landscape and find the global minimum. These steps are discarded.
  4. Samples (25): The algorithm takes 25 highly accurate samples per chain (100 total).

If all 4 chains converge on the exact same structural weights (measured by the $\hat{R}$ statistic approaching 1.0), the model is compiled into a .pkl artifact.

4. Feature Engineering

Axiom's data loaders (data_loader/creator.py) automatically prepare the tensors for Orbit.

  • Look-back Window (Lag): Time series models require temporal context. Axiom uses a rolling window (default $t=3$). To predict day $T_4$, the model receives the vectors from $T_1$, $T_2$, and $T_3$.
  • Scaling: Raw price data (e.g., $65,000 BTC vs $0.50 ADA) breaks gradient descent. All data is passed through a MaxAbsScaler before inference.

5. Evaluation Metrics

Axiom strictly evaluates models on an unseen Validation dataset before deploying them to the LangGraph execution engine.

  • Directional Accuracy: The percentage of time the model correctly forecasted the sign of the return (+ or -). A score $&gt; 55%$ in crypto is considered highly profitable.
  • MAE (Mean Absolute Error): The average absolute dollar amount the prediction was wrong.
  • MAPE (Mean Absolute Percentage Error): The MAE divided by the true price. A MAPE of 2.5% means the model's predictions are, on average, 97.5% accurate to the true price.
  • RMSE (Root Mean Square Error): Heavily penalizes "tail risk" or catastrophic prediction failures during black swan events.

6. Live Inference Architecture

In production, the .pkl models are loaded into memory by the FastAPI/Celery workers. When the LangGraph Fetch_ML_Prediction node executes:

  1. It queries the database for the last 3 days of OHLCV data.
  2. It applies the exact same MaxAbsScaler used during training.
  3. It appends a NaN future row to the dataframe.
  4. Orbit runs .predict() on the dataframe.
  5. The predicted absolute price is compared against the current baseline to derive the final output: { direction: "UP", confidence: 82.5 }.

πŸ—„ Database Design & Schema Architecture

Axiom requires a robust, ACID-compliant database to handle high-throughput financial transactions, store complex LLM reasoning payloads, and maintain user portfolios. We utilize PostgreSQL as the primary datastore, interfaced via SQLAlchemy and managed by Alembic migrations.

1. Schema Design Rationale

Trading systems produce three very different types of data:

  1. Relational/Transactional Data: Users, Portfolios, Wallets, and Orders. These require strict foreign keys, cascading deletes, and ACID compliance to prevent double-spending or orphaned trades.
  2. Time-Series Data: OHLCV (Open, High, Low, Close, Volume) data. While PostgreSQL is not a dedicated time-series DB (like InfluxDB), using compound indices on (symbol, timestamp) provides sufficient read performance for our ML data loaders.
  3. Document Data: The LLM's Explainable AI (XAI) output and agent checkpoints are highly nested JSON structures. We utilize PostgreSQL's JSONB column type, allowing us to store dynamic schemas while retaining the ability to query specific keys (e.g., finding all trades where confidence > 80).

2. Entity Relationship Diagram (ERD)

erDiagram
    USERS ||--o{ WALLETS : manages
    USERS ||--o{ PORTFOLIOS : owns
    USERS ||--o{ STRATEGIES : creates
    USERS ||--o{ WATCHLISTS : maintains
    USERS ||--o{ NOTIFICATIONS : receives

    PORTFOLIOS ||--o{ POSITIONS : contains
    
    STRATEGIES ||--o{ SIGNALS : generates
    STRATEGIES ||--o{ ORDERS : executes

    SIGNALS ||--o{ MODEL_PREDICTIONS : informed_by
    ORDERS ||--o{ AUDIT_LOGS : tracked_by
    STRATEGIES ||--o{ AGENT_LOGS : produces

    USERS {
        uuid id PK
        string email UK
        string hashed_password
        string role
        boolean is_active
        timestamp created_at
    }

    WALLETS {
        uuid id PK
        uuid user_id FK
        string exchange
        string encrypted_api_key
        string encrypted_api_secret
    }

    PORTFOLIOS {
        uuid id PK
        uuid user_id FK
        string name
        float total_equity
    }

    STRATEGIES {
        uuid id PK
        uuid user_id FK
        string name
        jsonb configuration
        boolean is_active
        boolean paper_trading
    }

    ORDERS {
        uuid id PK
        uuid strategy_id FK
        string symbol
        string order_type
        string side
        float amount
        float fill_price
        string status
        timestamp executed_at
    }

    SIGNALS {
        uuid id PK
        uuid strategy_id FK
        jsonb xai_reasoning
        float confidence_score
        timestamp created_at
    }

    MARKET_DATA {
        string symbol PK
        timestamp timestamp PK
        float open
        float high
        float low
        float close
        float volume
    }
Loading

3. Table Breakdown

3.1 Core User Entities

  • users: Manages authentication. Passwords use Argon2id hashing. role dictates RBAC (e.g., admin, trader).
  • wallets: Stores exchange API keys. Security Note: Keys are encrypted at the application layer (AES-256-GCM) before being written to the database.

3.2 Trading Entities

  • strategies: The configuration object passed into the LangGraph state machine. The configuration JSONB column stores specific indicator thresholds and risk limits.
  • orders: Represents a single execution attempt on an exchange.
  • positions: Represents current aggregated holdings across a portfolio.

3.3 Intelligence Entities

  • signals: The master output of the LangGraph Reasoning Agent. The xai_reasoning JSONB column stores the exact prompts, inputs, and natural language rationale for the trade.
  • agent_logs: Ephemeral storage of LangGraph state checkpoints. Used to resume a DAG if a node fails.
  • model_predictions: Stores the Orbit Bayesian forecast outputs for later MLOps accuracy auditing.

4. Indexing Strategy & Performance

To maintain $&lt; 50ms$ query times, Axiom employs strict indexing:

  1. B-Tree Indices: Applied to all UUID Primary Keys and Foreign Keys (user_id, strategy_id).
  2. Compound Indices: The market_data table relies heavily on a composite index on (symbol, timestamp) sorted in DESC order. This optimizes the ML data loader's frequent queries for "the last 100 candles of BTC/USD".
  3. GIN Indices: Applied to the configuration JSONB column in the strategies table and xai_reasoning in signals, enabling ultra-fast full-text search and key-value lookups within the JSON structures.

5. Connection Pooling

FastAPI runs asynchronously, which can rapidly exhaust PostgreSQL's max connection limit. We utilize PgBouncer (in production) or SQLAlchemy's AsyncSession with an AsyncEngine pool size of 20 (and max overflow of 10) to efficiently multiplex database connections across thousands of LangGraph ticks.

πŸ”Œ REST API Documentation

Axiom exposes a strictly typed, OpenAPI-compliant REST API via FastAPI. This document outlines the core architectural principles of the API, authentication flows, and common endpoints.

1. Architectural Principles

  1. Strict Pydantic Validation: Every request and response body is mapped to a Pydantic BaseModel. This ensures malformed JSON is rejected at the edge with a 422 Unprocessable Entity before ever reaching the business logic.
  2. Statelessness: The FastAPI backend holds zero session state. All state is either derived from the JWT or loaded from Redis/PostgreSQL.
  3. Idempotency: Core trading endpoints (like POST /api/v1/trade/cancel) are idempotent. Sending the same cancel request multiple times will not result in multiple exchange API calls if the order is already cancelled.

2. Authentication & Authorization Flow

Axiom uses JSON Web Tokens (JWT) for stateless authentication.

The OAuth2 Flow

  1. Login: Client sends POST /api/v1/auth/token with username and password as application/x-www-form-urlencoded.
  2. Verification: Server hashes the password with Argon2id and verifies against PostgreSQL.
  3. Token Issuance:
    • Server issues a short-lived access_token (expires in 15 minutes) returned in the JSON body.
    • Server issues a long-lived refresh_token (expires in 7 days) set as a secure, HttpOnly cookie.
  4. Authorized Requests: Client includes Authorization: Bearer <access_token> in the header for all subsequent requests.

Role-Based Access Control (RBAC)

FastAPI Depends() dependency injection is used to enforce RBAC.

  • get_current_user: Ensures the token is valid.
  • get_current_active_user: Ensures the user account is not suspended.
  • get_current_admin_user: Requires the role claim in the JWT to be admin.

3. Core API Endpoints

Full interactive documentation is automatically generated by FastAPI and available at http://localhost:8000/docs (Swagger UI) or /redoc (ReDoc).

3.1 Authentication

  • POST /api/v1/auth/register - Create a new user account.
  • POST /api/v1/auth/token - Login and generate JWTs.
  • POST /api/v1/auth/refresh - Use the HttpOnly refresh token to mint a new access token.

3.2 Portfolio & Wallets

  • GET /api/v1/portfolio/balances - Fetch real-time aggregated balances across all linked exchanges (CCXT).
  • POST /api/v1/wallets - Securely encrypt and store exchange API keys.

3.3 Strategies & Agent Control

  • POST /api/v1/strategies - Create a new trading strategy (saves configuration JSON).
  • POST /api/v1/strategies/{strategy_id}/start - Instantiates the LangGraph worker and begins the execution loop.
  • POST /api/v1/strategies/{strategy_id}/stop - Issues a halt command to the active worker via Redis PubSub.

3.4 Signals & Explainable AI (XAI)

  • GET /api/v1/signals - Retrieve the history of all trading signals generated by the LLM.
    • Response Example:
      {
        "id": "uuid-1234",
        "symbol": "BTC/USD",
        "action": "BUY",
        "confidence_score": 88.5,
        "xai_reasoning": {
           "evidence": ["Orbit DLT forecast +2%", "Whale inflows dropped"],
           "rationale_summary": "High conviction mean reversion."
        }
      }

3.5 Predictions (ML Inference)

  • GET /api/v1/predict/{symbol} - Triggers a synchronous inference run of the Orbit DLT model.

4. Rate Limiting & Security

To protect both our infrastructure and the user's exchange API limits, Axiom implements strict rate limiting via Redis.

  • Global Limits: 100 requests per minute per IP.
  • Exchange-Specific Limits: If the system detects CCXT rate limit headers, it automatically back-offs and applies a 429 Too Many Requests to the client.

☁️ Deployment Architecture & DevOps

This document outlines the production deployment topology, CI/CD pipeline, and observability standards for Axiom.

1. Cloud-Agnostic Infrastructure

Axiom is built on Docker and is entirely cloud-agnostic. While our reference architecture utilizes AWS (ECS, RDS, ElastiCache), the system can be deployed equally well to GCP, Azure, or bare-metal Kubernetes clusters.

Production Topology

flowchart TD
    Internet((Internet)) --> WAF[Cloudflare WAF / CDN]
    WAF --> LB[AWS ALB / Nginx]
    
    subgraph VPC [Private VPC]
        subgraph Frontend_Cluster [Next.js Cluster]
            FE1[Web Node 1]
            FE2[Web Node 2]
        end
        
        subgraph Backend_Cluster [FastAPI Cluster]
            API1[API Node 1]
            API2[API Node 2]
        end
        
        subgraph Worker_Cluster [ML & LangGraph Workers]
            W1[Worker Node 1]
            W2[Worker Node 2]
        end
        
        subgraph Data_Tier [State & Persistence]
            Redis[(Redis ElastiCache)]
            PG[(PostgreSQL RDS Multi-AZ)]
        end
    end
    
    LB --> FE1 & FE2
    LB --> API1 & API2
    
    FE1 & FE2 --> API1 & API2
    
    API1 & API2 --> Redis
    API1 & API2 --> PG
    
    Worker1 & Worker2 --> Redis
    Worker1 & Worker2 --> PG
Loading

2. Containerization Strategy

Axiom uses multi-stage Docker builds to dramatically reduce image sizes and attack surfaces.

  • Next.js (Web): Uses node:18-alpine. Builds the static .next bundle and runs purely in production mode.
  • FastAPI (API): Uses python:3.10-slim. We compile requirements.txt via pip-tools to ensure deterministic builds.

3. CI/CD Pipeline (GitHub Actions)

We practice Continuous Integration and Continuous Deployment via GitHub Actions (.github/workflows/).

Pipeline Stages

  1. Code Quality: Runs flake8, black, eslint, and prettier. Fails the PR if standards are not met.
  2. Security Scanning: Runs bandit (Python) and npm audit to check for CVEs in dependencies.
  3. Testing: Spins up a localized PostgreSQL container (via Service Containers) and runs pytest and jest.
  4. Build & Publish: If tests pass on the main branch, Docker images are built and pushed to the GitHub Container Registry (GHCR), tagged with the git commit SHA.
  5. Release (Semantic Release): Automatically bumps the package.json version and generates a Changelog based on Conventional Commits.

4. Observability & Monitoring

You cannot fix what you cannot measure. Axiom utilizes a robust "three-pillar" observability stack:

4.1 Metrics (Prometheus & Grafana)

FastAPI middleware exposes a /metrics endpoint. Prometheus scrapes this every 10 seconds. Key Dashboards:

  • API Latency: p95 and p99 response times.
  • LangGraph Execution Time: How long a full tick takes. If it exceeds 1000ms, alerts trigger.
  • LLM Token Usage: Cost tracking per strategy.

4.2 Distributed Tracing (OpenTelemetry)

Axiom uses OpenTelemetry to trace a request from the Next.js frontend, through the FastAPI gateway, down into the LangGraph state machine, and into the PostgreSQL database. This allows us to pinpoint exactly which micro-step is causing lag.

4.3 Error Tracking (Sentry)

Any unhandled exception (e.g., CCXT exchange timeout, LLM JSON parse failure) is caught and sent to Sentry with the full stack trace and request context.

5. Disaster Recovery & Backups

  • Database Backups: PostgreSQL uses continuous WAL (Write-Ahead Logging) archiving to S3, allowing for Point-In-Time-Recovery (PITR) up to 35 days.
  • Stateless Recovery: Because the workers and API nodes are entirely stateless, if a node crashes, the orchestrator (Kubernetes/ECS) simply provisions a new one. LangGraph will resume the exact state of the trade from PostgreSQL.

πŸ’» Development Guide

This document is the definitive guide for developing, testing, and debugging Axiom locally.

1. Prerequisites

Before cloning, ensure you have the following installed:

  • Docker & Docker Compose: For running the local Redis and PostgreSQL instances.
  • Node.js (v18.x+) & pnpm (v8.x+): For the Next.js frontend.
  • Python (3.10+): For the FastAPI backend and ML Inference.

2. Local Environment Setup

2.1 Database & Redis

Axiom requires state. Do not run the backend without the databases online.

docker-compose -f docker-compose.dev.yml up -d db redis

2.2 Backend (FastAPI) Setup

Navigate to the API app, create a virtual environment, and install dependencies via pip-tools (to ensure hash-checking and deterministic builds).

cd apps/api
python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt

Generate the initial database tables using Alembic:

alembic upgrade head

Run the API server with Uvicorn (hot-reloading enabled):

uvicorn main:app --reload --port 8000

2.3 Frontend (Next.js) Setup

Navigate to the Web app and use pnpm:

cd apps/web
pnpm install
pnpm dev

The dashboard is now available at http://localhost:3000.

3. Configuration Hierarchy

Axiom uses strict Pydantic BaseSettings to manage configuration. The hierarchy of overrides is:

  1. Environment Variables: Take highest precedence (e.g., export OPENAI_API_KEY=sk-...).
  2. .env Files: Read at startup. Do NOT commit these.
  3. Default Values: Hardcoded fallbacks in apps/api/core/config.py.

Required .env Variables (Backend)

DATABASE_URL=postgresql://user:pass@localhost:5432/axiom_db
REDIS_URL=redis://localhost:6379/0
JWT_SECRET=generate_a_secure_random_string_here
OPENAI_API_KEY=sk-...

4. Testing Strategy

We enforce a strict TDD (Test-Driven Development) culture. Coverage must exceed 80%.

Unit Tests

Run standard Python unit tests, mocking out database and API calls.

cd apps/api
pytest tests/unit/

Integration Tests

Integration tests actually hit a test SQLite database.

pytest tests/integration/

Frontend Tests

Next.js components are tested via Jest and React Testing Library.

cd apps/web
pnpm test

5. Working with LangGraph

Debugging the LLM DAG state machine locally can be difficult.

  • Enable Debug Logging: Set LOG_LEVEL=DEBUG in your .env. This will print the raw prompts sent to the LLM and the raw JSON received.
  • LangSmith (Optional): We highly recommend connecting LangSmith for local development to visually trace the nodes.
    LANGCHAIN_TRACING_V2=true
    LANGCHAIN_API_KEY=ls__...

6. MLOps: Training the Model Locally

You can run a local MCMC training session for the Orbit model. Note: this requires significant CPU resources.

cd packages/ml
python train.py dataset_loader=Binance dataset_loader.symbol=XBTUSD model=orbit

The resulting .pkl file will be saved in packages/ml/models/ and automatically picked up by the API upon reboot.

πŸ”§ Troubleshooting Guide

This guide covers common errors encountered when deploying or developing Axiom, along with their diagnostic steps and resolutions.

1. LangGraph & LLM Errors

Error: openai.error.RateLimitError: 429 Too Many Requests

Symptom: The LangGraph execution pauses and the UI shows "Agent Halted". Cause: The OpenAI (or alternative LLM) API key has exhausted its tokens-per-minute (TPM) or tier limits. Resolution:

  1. Axiom's state machine automatically saves a checkpoint to PostgreSQL before the crash.
  2. Upgrade your LLM tier or implement a fallback model (e.g., fallback to claude-3-haiku in .env).
  3. Once limits are restored, click "Resume Strategy" in the UI. LangGraph will hydrate the state from PostgreSQL and continue.

Error: ValueError: Output did not match JSON schema

Symptom: The Reasoning Node fails to parse the LLM output. Cause: The LLM hallucinated outside the strict Pydantic JSON schema required by Axiom. Resolution:

  1. Axiom automatically catches this via a Conditional Edge and prompts the LLM to fix the formatting (up to 3 retries).
  2. If it fails 3 times, check the agent_logs table to see the raw output. You may need to use a smarter model (e.g., GPT-4o instead of GPT-3.5) for complex reasoning tasks.

2. Database & Connection Errors

Error: sqlalchemy.exc.TimeoutError: QueuePool limit of size 20 overflow 10 reached

Symptom: 500 Internal Server Error during high API load. Cause: FastAPI workers are exhausting the PostgreSQL connection pool. Resolution:

  1. Ensure you are using PgBouncer in production.
  2. Increase DB_POOL_SIZE in the environment variables (but ensure it doesn't exceed PostgreSQL's max_connections).

Error: redis.exceptions.ConnectionError

Symptom: WebSockets disconnect; ML tasks remain in "Pending". Cause: The API cannot communicate with the Redis broker. Resolution:

  1. Ensure Redis is running: docker ps | grep redis.
  2. Check the REDIS_URL format. It must be redis://<host>:<port>/<db>.

3. Exchange API (CCXT) Errors

Error: ccxt.NetworkError: Request timeout

Symptom: The Execute node fails to place a trade. Cause: The exchange API is unresponsive or Cloudflare is blocking the IP. Resolution:

  1. Axiom uses an Exponential Backoff retry strategy for network errors.
  2. If persistent, verify your server's IP is allowlisted on the Exchange's API settings.

Error: ccxt.InsufficientFunds

Symptom: Trade execution rejected. Cause: The Risk Guard approved an allocation percentage, but the wallet lacks the exact quote currency needed after fees. Resolution: Ensure the portfolio has sufficient base currency for gas/fees. Adjust the max_allocation parameter in the Strategy Builder UI down by 1% to account for slippage.

4. Machine Learning Errors

Error: ValueError: Found array with 0 sample(s)

Symptom: The Orbit ML node fails during inference. Cause: The CCXT data loader returned an empty Pandas DataFrame, likely due to a delisted symbol or a downtime on the exchange's OHLCV endpoint. Resolution: Verify the symbol exists on the specified exchange (e.g., XBT/USD vs BTC/USDT).

Error: CmdStanPy RuntimeError: Stan model failed to compile

Symptom: The train.py script crashes immediately. Cause: C++ compiler toolchain is missing on your host machine. Resolution: Ensure gcc and g++ are installed. If using Docker, ensure the build-essential package is included in your Dockerfile.

❓ Frequently Asked Questions

This document answers the most common technical and operational questions regarding Axiom.

1. General & Architecture

Q: Is Axiom a High-Frequency Trading (HFT) bot? A: No. True HFT requires co-location at exchange data centers, FPGA hardware, and microsecond latencies (written in C++ or Rust). Axiom is a statistical arbitrage and swing-trading engine. It evaluates trades on minute, hourly, or daily timeframes. Its edge comes from superior reasoning (LangGraph + Bayesian math), not sheer speed.

Q: Why Python for the backend instead of Rust/Go? A: The entire ML ecosystem (PyTorch, CmdStanPy, XGBoost) and the Agentic AI ecosystem (LangChain, LangGraph) are heavily centralized around Python. Rebuilding these libraries in Rust would delay the project by years. However, critical performance bottlenecks (like CCXT exchange mapping) utilize C-bindings where possible.

2. AI & Machine Learning

Q: Which LLM is best for the Reasoning Agent? A: Axiom requires models with massive context windows, strict JSON adherence, and high logical reasoning capabilities.

  • Recommended: GPT-4o or Claude 3.5 Sonnet.
  • Not Recommended: GPT-3.5 or open-source models < 70B parameters (they struggle with the complex JSON schemas).

Q: What is the "Orbit DLT" model? A: Orbit is a Bayesian Time Series library open-sourced by Uber. We use it instead of XGBoost because it provides a probabilistic distribution (e.g., "70% chance price is between $X and $Y") rather than a deterministic guess. See ML.md for a deep dive.

3. Exchanges & Execution

Q: Which exchanges are supported? A: Axiom utilizes the CCXT library, which technically supports over 100+ cryptocurrency exchanges. However, we officially test and support Binance, Kraken, and Coinbase Advanced Trade.

Q: How does Axiom handle API rate limits? A: Axiom's execution nodes have an exponential backoff built-in. If an exchange returns a HTTP 429, the agent will pause, wait the required header time, and retry.

4. Operations & Cost

Q: How much does it cost to run the LLM? A: This depends entirely on your Tick Rate (how often the agent evaluates the market). Running a complex strategy on a 1-minute tick with GPT-4o can cost over $50/day in API fees. We recommend running strategies on 15-minute or 1-hour ticks to manage costs while maintaining alpha.

Q: Do I need a GPU to run this? A: No. The LLM reasoning happens via external APIs (OpenAI/Anthropic). The Orbit ML training does not use GPUs (MCMC sampling relies heavily on CPU cores). You can run the entire stack on a standard VPS.

🎨 Engineering Style Guide

To maintain a pristine, FAANG-level codebase, all contributors to Axiom must adhere to the following stylistic conventions. This ensures readability, maintainability, and prevents semantic drift across a large monorepo.

1. Python Backend (apps/api/)

We strictly enforce PEP 8, extended by our aggressive use of Black and Ruff.

1.1 Type Hinting

Every function, method, and variable (where ambiguous) must be type-hinted. We use mypy in strict mode.

❌ Bad:

def calculate_risk(portfolio_value, risk_pct):
    return portfolio_value * risk_pct

βœ… Good:

def calculate_risk(portfolio_value: float, risk_pct: float) -> float:
    """Calculates the absolute dollar amount to risk based on a percentage."""
    return portfolio_value * risk_pct

1.2 Pydantic Models vs Dicts

Never pass raw dictionaries around the business logic layer. Always cast inputs and outputs to Pydantic models.

❌ Bad:

def process_trade(trade_data: dict):
    if trade_data.get("side") == "BUY":
        ...

βœ… Good:

from pydantic import BaseModel
from typing import Literal

class TradeIntent(BaseModel):
    side: Literal["BUY", "SELL"]
    amount: float

def process_trade(intent: TradeIntent):
    if intent.side == "BUY":
        ...

1.3 Asynchronous Programming

Because we use FastAPI, avoid blocking the event loop at all costs.

  • Always use await for I/O operations (database calls, Redis, HTTP requests).
  • If you must run a synchronous, CPU-bound library (like pandas or Orbit), offload it to a thread pool via run_in_threadpool() or use Celery.

2. TypeScript Frontend (apps/web/)

We enforce standard Next.js 14 (App Router) conventions.

2.1 Component Structure

  • Use functional components with hooks. Do not use class components.
  • Separate complex logic into custom hooks (useStrategy.ts) to keep the UI components clean.

2.2 Server vs Client Components

  • Default to Server Components (no "use client" directive).
  • Only use "use client" when you need useState, useEffect, or onClick event listeners.

2.3 TailwindCSS Sorting

We use the prettier-plugin-tailwindcss to automatically sort classes. Always group utility classes logically: Layout -> Spacing -> Typography -> Colors -> Effects.

3. Database & SQL

When writing raw SQL or SQLAlchemy models:

  • Table names must be plural and snake_case (e.g., user_strategies, not UserStrategy).
  • Always use UUIDv4 for primary keys to prevent enumeration attacks and simplify distributed merging.
  • Boolean columns should generally be prefixed with is_ or has_ (e.g., is_active, has_notifications).

4. Git & Commit Messages

Follow the Conventional Commits specification.

  • Write messages in the imperative mood: "fix bug" not "fixed bug".
  • Keep the subject line under 50 characters.

Changelog

All notable changes to this project will be documented in this file.

The format is based on Keep a Changelog, and this project adheres to Semantic Versioning.

[Unreleased]

Added

  • Multi-exchange routing capabilities for arbitrage strategies.
  • Dynamic fee calculation in the Risk_Guard agent.
  • Optional fallback LLM routing in .env if primary OpenAI key rate-limits.

Changed

  • Migrated primary database driver from psycopg2 to async asyncpg.
  • Updated LangGraph dependency to v0.1.x for improved checkpointing speed.

Fixed

  • Memory leak in Next.js dashboard when WebSockets are left open for > 24 hours.
  • Edge case where ccxt.InsufficientFunds was improperly parsed by the Sentry logger.

[1.0.0] - 2024-05-01

Added

  • Initial Open Source Release!
  • Fully functional Next.js 14 Dashboard with React Query and TailwindCSS.
  • FastAPI backend with strict Pydantic schemas.
  • LangGraph integration with 6 specialized Data Gathering Agents.
  • Orbit DLT Machine Learning pipeline for Bayesian forecasting.
  • CCXT integration for Binance and Kraken.
  • Comprehensive documentation suite.

Security

  • Implemented AES-256-GCM encryption for all Exchange API keys at rest.
  • Implemented Argon2id for user password hashing.

🀝 Contributing to Axiom

First, thank you for your interest in contributing to Axiom! Our goal is to build the most robust, open-source Agentic Trading Engine in the world.

Whether you are fixing a bug, adding a new Technical Indicator, or refining our Orbit ML models, your help is appreciated. We operate under strict enterprise standards, so please read this guide carefully.

1. Code of Conduct

By participating in this project, you agree to abide by our Code of Conduct.

2. Getting Started

  1. Fork the repository on GitHub.
  2. Clone your fork locally: git clone https://github.com/YOUR_USERNAME/axiom.git
  3. Set up your development environment: Follow the Development Guide.

3. Branching Strategy

We follow a simplified GitHub Flow model. Do not commit directly to main.

Branch Naming Convention:

  • feat/ - For new features (e.g., feat/add-ichimoku-cloud)
  • fix/ - For bug fixes (e.g., fix/ccxt-timeout-retry)
  • docs/ - For documentation changes (e.g., docs/update-api-spec)
  • chore/ - For maintenance tasks (e.g., chore/update-dependencies)
  • refactor/ - For code restructuring without logic changes.

4. Conventional Commits

Axiom uses Semantic Release to automatically version the software and generate the Changelog. Therefore, all commit messages must follow the Conventional Commits specification.

Format:

<type>(<scope>): <subject>

Examples:

  • feat(ml): integrate orbit dlt model
  • fix(api): resolve memory leak in websocket multiplexer
  • docs(readme): add langgraph architecture diagram

5. Development Standards

Python (Backend)

  • We use Black for code formatting and Flake8 for linting.
  • Type hinting is strictly required for all new functions. We use mypy to enforce this.
  • Run formatting before committing: black . && flake8 .

TypeScript (Frontend)

  • We use ESLint and Prettier.
  • Do not use any. Define proper interfaces for all API responses.
  • Run linting: pnpm lint

6. Pull Request Process

  1. Ensure your branch is up to date with main.
  2. Ensure all tests pass: pytest (backend) and pnpm test (frontend).
  3. Push your branch to your fork.
  4. Open a Pull Request against the main branch of the official Axiom repository.
  5. Fill out the Pull Request Template completely.
  6. Code Review: At least one core maintainer must approve your PR.
  7. CI/CD: GitHub Actions will automatically run linting, security scans, and tests. Your PR cannot be merged if any pipeline fails.

7. Reporting Bugs

If you find a bug, please use the Bug Report Issue Template on GitHub. Include:

  • Your operating system and Python/Node versions.
  • Steps to reproduce the bug.
  • The expected vs actual behavior.
  • Any relevant logs or tracebacks (use formatting).

8. Requesting Features

For new features, use the Feature Request Issue Template. Be prepared to discuss the engineering trade-offs of your proposal. We prioritize features that benefit the Agentic AI reasoning or execution robustness.

🀝 Contributor Covenant Code of Conduct

Our Pledge

We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, caste, color, religion, or sexual identity and orientation.

We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.

Our Standards

Examples of behavior that contributes to a positive environment for our community include:

  • Demonstrating empathy and kindness toward other people
  • Being respectful of differing opinions, viewpoints, and experiences
  • Giving and gracefully accepting constructive feedback
  • Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
  • Focusing on what is best not just for us as individuals, but for the overall community

Examples of unacceptable behavior include:

  • The use of sexualized language or imagery, and sexual attention or advances of any kind
  • Trolling, insulting or derogatory comments, and personal or political attacks
  • Public or private harassment
  • Publishing others' private information, such as a physical or email address, without their explicit permission
  • Other conduct which could reasonably be considered inappropriate in a professional setting

Enforcement Responsibilities

Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.

Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.

Scope

This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.

Enforcement

Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at conduct@axiom-trading.io. All complaints will be reviewed and investigated promptly and fairly.

All community leaders are obligated to respect the privacy and security of the reporter of any incident.

Enforcement Guidelines

Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:

1. Correction

Community Impact: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community. Consequence: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.

2. Warning

Community Impact: A violation through a single incident or series of actions. Consequence: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media.

3. Temporary Ban

Community Impact: A serious violation of community standards, including sustained inappropriate behavior. Consequence: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period.

4. Permanent Ban

Community Impact: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals. Consequence: A permanent ban from any sort of public interaction within the community.

Attribution

This Code of Conduct is adapted from the Contributor Covenant, version 2.1, available at https://www.contributor-covenant.org/version/2/1/code_of_conduct.html.

πŸ—ΊοΈ Axiom Roadmap

This document outlines the strategic vision and upcoming milestones for the Axiom Agentic Trading Engine.

Disclaimer: This roadmap is a living document. Priorities may shift based on community feedback and market conditions.

πŸ“Œ Phase 1: Foundation & Stability (Current)

Target: Q3 2024

Our immediate focus is on ensuring the core orchestration engine is flawless.

  • LangGraph Orchestrator: Reliable DAG execution with PostgreSQL checkpointing.
  • Orbit DLT Integration: Replace legacy XGBoost models with Bayesian time-series forecasting.
  • Next.js Dashboard: V1 of the user interface for strategy management.
  • Comprehensive Test Coverage: Achieve 85%+ coverage on apps/api.
  • Docker Swarm / K8s Manifests: Provide official Helm charts for easier enterprise deployments.

πŸš€ Phase 2: Advanced Intelligence & DeFi

Target: Q4 2024

Expanding the swarm's capabilities beyond centralized exchanges (CEXs).

  • DEX Aggregation: Integrate 1inch or Uniswap V3 routers directly into the execution agent, enabling purely on-chain execution.
  • Reinforcement Learning (RLHF): Implement a feedback loop where the LLM's confidence_score is continuously graded against the actual trade PnL, fine-tuning its prompt weights over time.
  • Alternative Data Agents: Build specialized sub-agents to ingest alternative data (e.g., scraping SEC EDGAR filings for ETF news, parsing GitHub commits of target protocols).

🧠 Phase 3: Multi-Agent Collaboration

Target: Q1 2025

Moving from a single orchestrator to a consensus-based multi-agent architecture.

  • Agent Debate: Instead of one Reasoning Agent, deploy three specialized models (e.g., GPT-4 for macro, Claude 3 for technicals, Llama 3 for sentiment). The final trade is only executed if 2/3 achieve consensus.
  • Dynamic Portfolio Rebalancing: Allow agents to control cross-asset allocations (e.g., dynamically shifting portfolio weight from BTC to ETH based on ETH/BTC dominance metrics).
  • Options & Derivatives: Expand the Risk Guard to handle complex Greeks (Delta, Gamma) for options trading on Deribit or Bybit.

🌐 Phase 4: Decentralized Protocol

Target: Q3 2025

  • Zero-Knowledge Proofs (ZKPs): Implement ZK-SNARKs so traders can prove their strategy's historical ROI to investors without revealing the proprietary LangGraph logic or indicator parameters.
  • Axiom Strategy Marketplace: A decentralized repository where users can publish and monetize their custom Agent configurations.

πŸ›‘οΈ Security Policy

Because Axiom manages financial assets and exchange API keys, security is our highest priority. We treat every vulnerability as a critical incident.

Supported Versions

Only the latest major release of Axiom receives active security patches.

Version Supported
v1.x.x βœ…
< v1.0 ❌

Reporting a Vulnerability

DO NOT create a public GitHub issue for a security vulnerability.

If you discover a potential vulnerability in Axiom, please email the core security team directly at: security@axiom-trading.io

We will acknowledge your email within 24 hours and provide a timeline for the patch.

What to include in your report:

  • Description of the vulnerability.
  • Steps to reproduce the exploit.
  • Potential impact (e.g., "Allows an attacker to extract encrypted API keys").
  • Proposed mitigation (if any).

API Key Security Architecture

Axiom handles exchange API keys (Binance, Coinbase, Kraken) with extreme prejudice.

  1. Encryption at Rest: All API keys and secrets are encrypted in the PostgreSQL database using AES-256-GCM.
  2. Symmetric Key Isolation: The symmetric encryption key (FERNET_KEY) is never stored in the database. It must be provided via the environment variable during the FastAPI container boot sequence.
  3. No Plaintext Logging: The application is strictly configured to scrub any string matching an API key or JWT format before it hits stdout or Sentry logs.

Dependency Security

We rely heavily on open-source dependencies (FastAPI, React, LangChain).

  • Dependabot is enabled on this repository and automatically opens PRs for CVEs.
  • Our CI/CD pipeline runs bandit to statically analyze the Python code for common vulnerabilities (e.g., SQL injection, hardcoded passwords).
  • Our Next.js frontend runs npm audit during the build phase.

Bug Bounty Program

At this time, Axiom does not have a formalized, paid bug bounty program. However, researchers who responsibly disclose critical vulnerabilities (Remote Code Execution, Data Exfiltration) will be publicly acknowledged in our Hall of Fame and Release Notes.

About

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages