AI-Powered Cryptocurrency Trading Platform using Agentic AI, LangGraph, Bayesian Forecasting, and Explainable Intelligence.
Documentation β’ Live Demo β’ Report Bug β’ Request Feature β’ Website
- π Table of Contents
- π Project Overview
- πΈ Screenshots
- π Complete System Architecture
- π Folder Structure
- π Architecture Layers
- πΈ LangGraph Workflow
- π€ Agent Architecture
- β‘ AI Decision Flow
- π Data Pipeline
- π§ Machine Learning (Orbit DLT)
- π‘ Explainable AI (XAI)
- π Database Design
- π API Documentation
- π Authentication Flow & Security
- βοΈ Deployment Architecture
- π DevOps & Monitoring
- βοΈ Configuration
- π Installation & Usage
- π§ͺ Testing
- π Documentation
- πΊ Roadmap
- π€ Contribution Guide
- π License & Acknowledgements
- π Complete System Architecture
- π€ Agentic AI & LangGraph Architecture
- π Machine Learning: Orbit DLT & Bayesian Forecasting
- π Database Design & Schema Architecture
- π REST API Documentation
- βοΈ Deployment Architecture & DevOps
- π» Development Guide
- π§ Troubleshooting Guide
- β Frequently Asked Questions
- π¨ Engineering Style Guide
- Changelog
- π€ Contributor Covenant Code of Conduct
- π‘οΈ Security Policy
- Project Overview
- Screenshots
- Complete System Architecture
- Folder Structure
- Architecture Layers
- LangGraph Workflow
- Agent Architecture
- AI Decision Flow
- Data Pipeline
- Machine Learning
- Explainable AI (XAI)
- Database Design
- API Documentation
- Authentication Flow
- Security
- Deployment Architecture
- DevOps
- Monitoring
- Configuration
- Installation
- Usage
- Testing
- Documentation
- Roadmap
- Contribution Guide
- License
- Acknowledgements
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.
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.
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.
- 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.
| Dashboard & Portfolio | Agent Strategy Monitor |
|---|---|
![]() |
![]() |
| Real-time Risk Metrics & PnL | Live LangGraph DAG Execution Trace |
| Dark Mode Trading View | Explainable AI (XAI) Signals |
|---|---|
![]() |
![]() |
| Integrated Chart.js Financial Visualization | Human-Readable Rationale for Trades |
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
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
Axiom is built upon Domain-Driven Design (DDD) principles, enforcing strict separation of concerns:
- Presentation Layer: Next.js (SSR/CSR) handling UI rendering, optimistic updates (React Query), and complex charting (Chart.js).
- Application Layer: FastAPI routing, JWT authorization validation, and WebSocket multiplexing.
- Domain Layer: Business logic handling strategy creation, portfolio validation, and risk parameters.
- AI Layer: LangGraph orchestrating agent state transitions, LLM tool calling (LiteLLM), and prompt compilation.
- ML Layer: Statistical inference environments running Pandas, Scikit-learn, and the Orbit Bayesian model via CmdStan.
- Infrastructure Layer: Docker containers, Redis Pub/Sub, and Nginx reverse proxies.
- Persistence Layer: PostgreSQL (via SQLAlchemy/Alembic) for ACID transactions, Redis for ephemeral state (Checkpoints).
- Notification Layer: Decoupled service pushing events to Webhooks, Discord, or Email.
- Monitoring Layer: Prometheus metrics exposing latency and LLM token usage, visualized in Grafana.
- Security Layer: JWT validation, SQL injection prevention, and Redis-backed rate limiting.
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 --> [*]
- Conditional Edges: If the configuration disables social sentiment, the edge is pruned at runtime, saving compute.
- Checkpointing: The
TickStateis 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.
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.
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
Data integrity is critical for ML and AI reasoning. Axiom's pipeline is strictly typed:
- Ingestion: Exchange WebSockets and REST APIs pull raw data.
- Cleaning: Pandas removes NaN values, handles missing candles via interpolation, and normalizes timestamps to UTC.
- Feature Engineering: Calculation of momentum, volatility, and volume indicators.
- Prediction: Transformed data is fed into the Orbit
.pklmodel. - Decision: Outputs enter the LangGraph state.
- Execution: Standardized via CCXT.
- Persistence: Raw inputs and LLM outputs are logged for MLOps retraining.
- Analytics: Portfolio tracking updates total equity curves.
Axiom uses Uber's Orbit (Bayesian Structural Time Series) rather than XGBoost or LSTMs.
- 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).
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.
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.
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
}
Detailed API documentation is auto-generated via FastAPI's Swagger UI (/docs).
Key Endpoints:
POST /api/v1/auth/token- OAuth2 JWT GenerationGET /api/v1/portfolio/balances- Fetch aggregated exchange balancesPOST /api/v1/strategies/{id}/start- Initialize a LangGraph workerGET /api/v1/signals/history- Retrieve XAI trade reasoning logs
Axiom uses JWT (JSON Web Tokens).
- Client sends credentials.
- Server validates Argon2id hash and issues a short-lived
access_tokenand an HttpOnlyrefresh_token. - Client attaches
Bearertoken to headers for protected routes. - Role-Based Access Control (RBAC) ensures users cannot access other users' portfolios.
- 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.
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
- Linting: Flake8, Black, ESLint, Prettier.
- Testing: Pytest & Jest run on every Push. Coverage must exceed 80%.
- Build: Docker images are built and pushed to GitHub Container Registry (GHCR).
- Release Automation: Semantic Release bumps versions and updates the Changelog automatically.
- 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.
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.
git clone https://github.com/axiom-trading/axiom.git
cd axiom
docker-compose -f docker-compose.prod.yml up -d --buildAccess the Dashboard at http://localhost:3000 and API at http://localhost:8000.
Backend:
cd apps/api
python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
uvicorn main:app --reloadFrontend:
cd apps/web
pnpm install
pnpm devAxiom 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.
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
- 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.
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: 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:
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.
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.
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
- 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).
- 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.
- 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.
- 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.
- 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
.pklmodel artifacts are loaded into memory once during worker initialization.
- 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.
- 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.
- 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.
- 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.
- 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.
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.
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:
- Cycles (Loops): We can explicitly route a failed LLM output back to itself for correction.
- State Persistence (Checkpoints): LangGraph natively saves the
TickStateto PostgreSQL after every node. If the server reboots mid-trade, the graph resumes exactly where it left off. - Human-in-the-Loop: We can inject "breakpoints" into the graph, requiring human authorization for high-risk trades before proceeding to the execution node.
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 --> [*]
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.
The Fan_In_Reasoning node receives the populated TickState dictionary. It compiles this massive payload into a highly structured prompt injected into the LLM.
To prevent context-window exhaustion and hallucination, Axiom utilizes a Swarm of specialized sub-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.
- 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.
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.
{
"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.
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.
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.
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:
-
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. -
Seasonality (
$S_t$ ): Captures recurring cycles (e.g., lower weekend volume, funding rate epochs). -
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.
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):
- Chains (4): CmdStan launches 4 completely independent simulations simultaneously.
- Cores (8): These chains run in parallel across CPU cores.
- 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.
- 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 .pkl artifact.
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
MaxAbsScalerbefore inference.
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
$> 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.
In production, the .pkl models are loaded into memory by the FastAPI/Celery workers.
When the LangGraph Fetch_ML_Prediction node executes:
- It queries the database for the last 3 days of OHLCV data.
- It applies the exact same
MaxAbsScalerused during training. - It appends a
NaNfuture row to the dataframe. - Orbit runs
.predict()on the dataframe. - The predicted absolute price is compared against the current baseline to derive the final output:
{ direction: "UP", confidence: 82.5 }.
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.
Trading systems produce three very different types of data:
- 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.
- 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. - Document Data: The LLM's Explainable AI (XAI) output and agent checkpoints are highly nested JSON structures. We utilize PostgreSQL's
JSONBcolumn type, allowing us to store dynamic schemas while retaining the ability to query specific keys (e.g., finding all trades whereconfidence > 80).
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
}
users: Manages authentication. Passwords use Argon2id hashing.roledictates 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.
strategies: The configuration object passed into the LangGraph state machine. TheconfigurationJSONB 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.
signals: The master output of the LangGraph Reasoning Agent. Thexai_reasoningJSONB 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.
To maintain
- B-Tree Indices: Applied to all UUID Primary Keys and Foreign Keys (
user_id,strategy_id). - Compound Indices: The
market_datatable relies heavily on a composite index on(symbol, timestamp)sorted inDESCorder. This optimizes the ML data loader's frequent queries for "the last 100 candles of BTC/USD". - GIN Indices: Applied to the
configurationJSONB column in thestrategiestable andxai_reasoninginsignals, enabling ultra-fast full-text search and key-value lookups within the JSON structures.
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.
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.
- Strict Pydantic Validation: Every request and response body is mapped to a Pydantic
BaseModel. This ensures malformed JSON is rejected at the edge with a422 Unprocessable Entitybefore ever reaching the business logic. - Statelessness: The FastAPI backend holds zero session state. All state is either derived from the JWT or loaded from Redis/PostgreSQL.
- 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.
Axiom uses JSON Web Tokens (JWT) for stateless authentication.
- Login: Client sends
POST /api/v1/auth/tokenwithusernameandpasswordasapplication/x-www-form-urlencoded. - Verification: Server hashes the password with Argon2id and verifies against PostgreSQL.
- 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,HttpOnlycookie.
- Server issues a short-lived
- Authorized Requests: Client includes
Authorization: Bearer <access_token>in the header for all subsequent requests.
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 theroleclaim in the JWT to beadmin.
Full interactive documentation is automatically generated by FastAPI and available at http://localhost:8000/docs (Swagger UI) or /redoc (ReDoc).
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 theHttpOnlyrefresh token to mint a new access token.
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.
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.
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." } }
- Response Example:
GET /api/v1/predict/{symbol}- Triggers a synchronous inference run of the Orbit DLT model.
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 Requeststo the client.
This document outlines the production deployment topology, CI/CD pipeline, and observability standards for Axiom.
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.
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
Axiom uses multi-stage Docker builds to dramatically reduce image sizes and attack surfaces.
- Next.js (Web): Uses
node:18-alpine. Builds the static.nextbundle and runs purely in production mode. - FastAPI (API): Uses
python:3.10-slim. We compilerequirements.txtviapip-toolsto ensure deterministic builds.
We practice Continuous Integration and Continuous Deployment via GitHub Actions (.github/workflows/).
- Code Quality: Runs
flake8,black,eslint, andprettier. Fails the PR if standards are not met. - Security Scanning: Runs
bandit(Python) andnpm auditto check for CVEs in dependencies. - Testing: Spins up a localized PostgreSQL container (via Service Containers) and runs
pytestandjest. - Build & Publish: If tests pass on the
mainbranch, Docker images are built and pushed to the GitHub Container Registry (GHCR), tagged with the git commit SHA. - Release (Semantic Release): Automatically bumps the
package.jsonversion and generates a Changelog based on Conventional Commits.
You cannot fix what you cannot measure. Axiom utilizes a robust "three-pillar" observability stack:
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.
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.
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.
- 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.
This document is the definitive guide for developing, testing, and debugging Axiom locally.
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.
Axiom requires state. Do not run the backend without the databases online.
docker-compose -f docker-compose.dev.yml up -d db redisNavigate 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.txtGenerate the initial database tables using Alembic:
alembic upgrade headRun the API server with Uvicorn (hot-reloading enabled):
uvicorn main:app --reload --port 8000Navigate to the Web app and use pnpm:
cd apps/web
pnpm install
pnpm devThe dashboard is now available at http://localhost:3000.
Axiom uses strict Pydantic BaseSettings to manage configuration.
The hierarchy of overrides is:
- Environment Variables: Take highest precedence (e.g.,
export OPENAI_API_KEY=sk-...). .envFiles: Read at startup. Do NOT commit these.- Default Values: Hardcoded fallbacks in
apps/api/core/config.py.
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-...We enforce a strict TDD (Test-Driven Development) culture. Coverage must exceed 80%.
Run standard Python unit tests, mocking out database and API calls.
cd apps/api
pytest tests/unit/Integration tests actually hit a test SQLite database.
pytest tests/integration/Next.js components are tested via Jest and React Testing Library.
cd apps/web
pnpm testDebugging the LLM DAG state machine locally can be difficult.
- Enable Debug Logging: Set
LOG_LEVEL=DEBUGin 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__...
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=orbitThe resulting .pkl file will be saved in packages/ml/models/ and automatically picked up by the API upon reboot.
This guide covers common errors encountered when deploying or developing Axiom, along with their diagnostic steps and resolutions.
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:
- Axiom's state machine automatically saves a checkpoint to PostgreSQL before the crash.
- Upgrade your LLM tier or implement a fallback model (e.g., fallback to
claude-3-haikuin.env). - Once limits are restored, click "Resume Strategy" in the UI. LangGraph will hydrate the state from PostgreSQL and continue.
Symptom: The Reasoning Node fails to parse the LLM output. Cause: The LLM hallucinated outside the strict Pydantic JSON schema required by Axiom. Resolution:
- Axiom automatically catches this via a Conditional Edge and prompts the LLM to fix the formatting (up to 3 retries).
- If it fails 3 times, check the
agent_logstable 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.
Symptom: 500 Internal Server Error during high API load. Cause: FastAPI workers are exhausting the PostgreSQL connection pool. Resolution:
- Ensure you are using
PgBouncerin production. - Increase
DB_POOL_SIZEin the environment variables (but ensure it doesn't exceed PostgreSQL'smax_connections).
Symptom: WebSockets disconnect; ML tasks remain in "Pending". Cause: The API cannot communicate with the Redis broker. Resolution:
- Ensure Redis is running:
docker ps | grep redis. - Check the
REDIS_URLformat. It must beredis://<host>:<port>/<db>.
Symptom: The Execute node fails to place a trade.
Cause: The exchange API is unresponsive or Cloudflare is blocking the IP.
Resolution:
- Axiom uses an Exponential Backoff retry strategy for network errors.
- If persistent, verify your server's IP is allowlisted on the Exchange's API settings.
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.
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).
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.
This document answers the most common technical and operational questions regarding Axiom.
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.
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.
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.
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.
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.
We strictly enforce PEP 8, extended by our aggressive use of Black and Ruff.
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_pctNever 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":
...Because we use FastAPI, avoid blocking the event loop at all costs.
- Always use
awaitfor 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.
We enforce standard Next.js 14 (App Router) conventions.
- Use functional components with hooks. Do not use class components.
- Separate complex logic into custom hooks (
useStrategy.ts) to keep the UI components clean.
- Default to Server Components (no
"use client"directive). - Only use
"use client"when you needuseState,useEffect, oronClickevent listeners.
We use the prettier-plugin-tailwindcss to automatically sort classes.
Always group utility classes logically: Layout -> Spacing -> Typography -> Colors -> Effects.
When writing raw SQL or SQLAlchemy models:
- Table names must be plural and
snake_case(e.g.,user_strategies, notUserStrategy). - Always use UUIDv4 for primary keys to prevent enumeration attacks and simplify distributed merging.
- Boolean columns should generally be prefixed with
is_orhas_(e.g.,is_active,has_notifications).
Follow the Conventional Commits specification.
- Write messages in the imperative mood: "fix bug" not "fixed bug".
- Keep the subject line under 50 characters.
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.
- Multi-exchange routing capabilities for arbitrage strategies.
- Dynamic fee calculation in the
Risk_Guardagent. - Optional fallback LLM routing in
.envif primary OpenAI key rate-limits.
- Migrated primary database driver from
psycopg2to asyncasyncpg. - Updated LangGraph dependency to
v0.1.xfor improved checkpointing speed.
- Memory leak in Next.js dashboard when WebSockets are left open for > 24 hours.
- Edge case where
ccxt.InsufficientFundswas improperly parsed by the Sentry logger.
- 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.
- Implemented AES-256-GCM encryption for all Exchange API keys at rest.
- Implemented Argon2id for user password hashing.
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.
By participating in this project, you agree to abide by our Code of Conduct.
- Fork the repository on GitHub.
- Clone your fork locally:
git clone https://github.com/YOUR_USERNAME/axiom.git - Set up your development environment: Follow the Development Guide.
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.
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 modelfix(api): resolve memory leak in websocket multiplexerdocs(readme): add langgraph architecture diagram
- We use Black for code formatting and Flake8 for linting.
- Type hinting is strictly required for all new functions. We use
mypyto enforce this. - Run formatting before committing:
black . && flake8 .
- We use ESLint and Prettier.
- Do not use
any. Define proper interfaces for all API responses. - Run linting:
pnpm lint
- Ensure your branch is up to date with
main. - Ensure all tests pass:
pytest(backend) andpnpm test(frontend). - Push your branch to your fork.
- Open a Pull Request against the
mainbranch of the official Axiom repository. - Fill out the Pull Request Template completely.
- Code Review: At least one core maintainer must approve your PR.
- CI/CD: GitHub Actions will automatically run linting, security scans, and tests. Your PR cannot be merged if any pipeline fails.
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).
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.
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.
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
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.
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.
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.
Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
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.
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.
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.
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.
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.
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.
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.
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_scoreis 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).
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.
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.
Because Axiom manages financial assets and exchange API keys, security is our highest priority. We treat every vulnerability as a critical incident.
Only the latest major release of Axiom receives active security patches.
| Version | Supported |
|---|---|
| v1.x.x | β |
| < v1.0 | β |
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.
- 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).
Axiom handles exchange API keys (Binance, Coinbase, Kraken) with extreme prejudice.
- Encryption at Rest: All API keys and secrets are encrypted in the PostgreSQL database using AES-256-GCM.
- 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. - No Plaintext Logging: The application is strictly configured to scrub any string matching an API key or JWT format before it hits
stdoutor Sentry logs.
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
banditto statically analyze the Python code for common vulnerabilities (e.g., SQL injection, hardcoded passwords). - Our Next.js frontend runs
npm auditduring the build phase.
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.



