the0 Algorithmic Trading Platform

repository·dev·Indexed 43 days ago

https://github.com/alexanderwanyoike/the0

An open-source, production-grade algorithmic trading execution engine for building and deploying trading bots in Python, Rust, and TypeScript. Features a NestJS-based API with a Model Context Protocol (MCP) server for AI integration, a CLI for bot and backtest management, and a scalable microservices infrastructure for real-time monitoring.

Tokens
120.5K
Snippets
415
Records
601
Agent score
56%

What's inside the0

  1. Overview of Kubernetes Mode

    dev

    Kubernetes mode provides a controller-based deployment for running bots at scale. It is recommended when running more than ~1000 bots per host, when high availability is required, or when K8s-native observability and management is needed.

    The system uses a Controller Manager that runs two reconciliation controllers:

    1. Bot Controller: Manages Pods for live (realtime) trading bots.
    2. Schedule Controller: Manages CronJobs for scheduled bots.

    Both controllers watch MongoDB for the desired state and use NATS events to react to changes.

  2. Overview of Theo API

    dev

    Theo API is the backend service for the0 automated trading platform, built using the NestJS framework. It provides core functionality for managing bots, including bot configuration validation against external schemas, centralized configuration management, and integration with external services via Axios.

    A key feature is its built-in Model Context Protocol (MCP) server, which allows AI assistants like Claude Code to interact directly with the platform to manage bots, view logs, and check status.

  3. Understand the Price Alerts Bot

    dev

    The Price Alerts Bot is a real-time bot example designed to demonstrate structured metric emission using pino logging and a custom React frontend using the the0-react SDK.

    It performs the following continuous tasks:

    1. Simulates price movements using a random walk.
    2. Emits price snapshots at configurable intervals.
    3. Triggers alerts when price changes exceed a specified threshold.
    4. Emits buy/sell signals based on price trends.
  4. Manage the platform using the the0 CLI

    dev

    The the0 CLI is the primary interface for interacting with the platform. Use it to perform the following tasks:

    • Installation: Set up the CLI on your local machine.
    • Authentication: Configure your API credentials to authorize commands.
    • Bot Management: Use bot commands to manage existing bot instances.
    • Custom Bot Deployment: Deploy your own custom bot logic to the platform.
    • Secrets Management: Configure private dependencies and sensitive information required by your bots.
  5. Understand the Docker Mode architecture

    dev

    Docker mode uses a unified execute architecture where each bot container is self-managing. Instead of the runtime services managing code or state, they only handle the container lifecycle (starting, stopping, and restarting).

    All operational complexity—including code downloading, state persistence, and log streaming—is delegated to the runtime execute command running inside each container. This architecture is recommended for local development and small-to-medium deployments.

  6. How Kubernetes Controller Mode works

    dev

    In Kubernetes deployments, the0 can run in Controller Mode by default. Instead of running bots within a single container, the runtime controller manages bots as native Kubernetes objects:

    • Bot Isolation: Each bot runs in its own dedicated Kubernetes Pod.
    • Scheduled Bots: Scheduled tasks are managed using native Kubernetes CronJobs via a Schedule Controller.
    • Lifecycle: The Bot Controller reads enabled bots from MongoDB and ensures a matching Pod exists. Configuration changes trigger Pod recreation, and deleting a bot removes its corresponding Pod.
    • Security: Uses the configured runtime image and does not require privileged containers.
    • Scaling: Kubernetes handles scheduling and resource limits via ResourceQuota.

    To use this mode, ensure botController.enabled is set to true in your Helm values.

    # Enable controller mode in values.yaml
    botRunner:
      enabled: false
    botScheduler:
      enabled: false
    
    botController:
      enabled: true
      imageBuilder:
        enabled: true
        registry: "localhost:5000"  # Example for Minikube registry
  7. Manage named API environments in the0 CLI

    dev
    The the0 CLI supports named environments, allowing you to switch between different API endpoints (e.g., local Docker Compose stacks and prod clusters) without manually updating environment variables or API keys. Each environment stores its own URL and API key. Environments are persisted in ~/.the0/environments.json.
  8. How Query Handlers work for Realtime vs Scheduled bots

    dev

    Query handlers allow you to expose read-only data from your bots via HTTP endpoints without affecting the bot's execution or state. The execution model depends on the bot type:

    Realtime Bots

    Realtime bots run a dedicated HTTP server on port 9476. Queries are proxied directly to the running container, resulting in low latency (~10-50ms).

    Scheduled Bots

    Scheduled bots handle queries by spawning ephemeral containers. When a query arrives, the runtime starts a container with the QUERY_PATH environment variable set. The SDK detects this variable and runs in query mode instead of normal execution. This incurs higher latency (~1-3s) due to container startup and state downloading.

  9. Understand the0 Service Architecture

    dev

    The platform is composed of Infrastructure and Application services working together.

    Infrastructure Services

    • PostgreSQL (port 5432): Stores user accounts, bot definitions, and configuration.
    • MongoDB (port 27017): Stores runtime state, job queues, and execution logs. Used by the bot runner and scheduler for coordination.
    • NATS (port 4222): Provides event streaming. JetStream is enabled for durable delivery.
    • MinIO (ports 9000, 9001): S3-compatible object storage for bot code, logs, and artifacts.

    Application Services

    • the0-api (port 3000): Handles REST API, authentication, and bot management. Publishes events to NATS.
    • the0-frontend (port 3001): Web dashboard.
    • the0-docs (port 3002): Platform documentation.
    • bot-runner: Executes real-time bots in isolated Docker containers using a reconciliation loop against MongoDB state.
    • bot-scheduler: Manages scheduled execution by monitoring cron schedules in MongoDB and triggering events via NATS.
  10. How Query Execution works for Realtime and Scheduled bots

    dev

    The query-server (port 9477) handles requests differently depending on the bot type:

    Realtime Bot Queries

    For bots that are already running, the query-server proxies the request to the specific container's internal query server.

    1. query-server (port 9477) receives the HTTP request.
    2. It finds the target bot and its container.
    3. It proxies the request to the container's IP on port 9476.
    4. Latency: ~10-50ms.

    Scheduled Bot Queries

    For bots that are not currently running, the system spawns an ephemeral container to run the query.

    1. query-server receives the request.
    2. It identifies the bot configuration.
    3. It starts an ephemeral container using QUERY_PATH and QUERY_PARAMS environment variables.
    4. The container runs in query mode, returns a JSON result, and terminates.
    5. Latency: ~1-3s.
  11. Understand State Persistence and Syncing

    dev

    Bot state is automatically synchronized to MinIO to ensure continuity across container restarts.

    • Mechanism: The daemon sync process runs periodically (every 60 seconds).
    • Logic: It computes a hash of the state directory and uploads changes to MinIO when changes are detected.
    • Recovery: On container restart, the existing state is automatically downloaded from MinIO before the bot starts.
    • Scheduled Bots: For scheduled tasks, the daemon performs a final sync upon bot completion to ensure all logs and state are captured before the container terminates.