Backend Services Layer
Relevant source files
The following files were used as context for generating this wiki page:
The Backend Services Layer of OpenAlgo serves as the core orchestration engine, sitting between the Unified Broker API and the specific broker adapters. It provides a normalized interface for order management, portfolio tracking, and market data retrieval, ensuring that strategy logic remains decoupled from specific broker implementations. This layer is responsible for critical functions such as margin calculation, position reconciliation, and routing requests to either live broker environments or the internal API Analyzer Mode.
This layer facilitates high-level trading operations across 34 supported broker plugins and one crypto exchange. It handles the translation of standardized OpenAlgo symbols and constants into broker-specific formats, manages session persistence for single-user deployments, and broadcasts state changes over SocketIO to keep the React frontend updated in real-time.
Sources: CLAUDE.md:1-20, README.md:10-30, okf/sdk/services-documentation.md:1-15
Core Service Architecture
The backend services are organized into functional modules that manage the lifecycle of trading operations. The architecture follows a strict request pipeline where requests pass through security and traffic logging middleware before reaching the service layer.
System Flow Diagram
The following diagram illustrates how the backend services layer interacts with external requests and the underlying broker infrastructure.
The diagram shows the transition from external requests through security layers into the core service modules, which route tasks based on the active trading mode.
Sources: CLAUDE.md:144-155, test/sandbox/README.md:5-15
Order Management and Routing
The Order Router Service provides a unified contract for placing, modifying, and cancelling orders. It supports standard orders as well as advanced order types like basket orders and smart orders that automatically reconcile to a target position size.
Order Capabilities
| Order Type | Functionality | Supported Price Types |
|---|---|---|
| Place Order | Standard order execution with broker. | MARKET, LIMIT, SL, SL-M |
| Smart Order | Position-aware order that reconciles to target size. | MARKET, LIMIT, SL, SL-M |
| Basket Order | Simultaneous placement of multiple orders. | Standard broker types |
| Split Order | Chunks large orders to manage liquidity/impact. | MARKET, LIMIT |
Sources: README.md:88-105, test/test_flow_workflow_validator.py:465-485
Validation Logic
The service layer performs strict structural validation of orders before routing. For priced orders (LIMIT/SL/SL-M), it enforces the presence of price or triggerPrice to prevent broker-side defaults or zero-value errors.
Sources: test/test_flow_workflow_validator.py:490-510
Portfolio and Fund Services
The Portfolio Service manages the retrieval and normalization of account-level data. It aggregates information from the broker to provide a consistent view of the trader's financial status.
- Fund Management: Tracks available margin and account balances.
- Position Tracking: Reconciles open positions and calculated P&L.
- Holdings: Manages portfolio holdings for delivery-based products (CNC).
- Order/Trade Books: Provides an audit trail of executed trades and pending orders for the current day.
Sources: okf/viz.html:158-180, test/sandbox/README.md:20-35
Market Data and Streaming
The Market Data Service utilizes a three-layer pipeline to deliver real-time and historical data. It normalizes data from disparate broker feeds into the OpenAlgo standard.
Data Pipeline Sequence
This sequence shows the decoupling of broker feeds from client delivery using a ZMQ message bus for high-performance distribution.
Sources: CLAUDE.md:129-142, README.md:110-120
Supported Data Modes
- LTP (Mode 1): Last Traded Price and timestamp.
- Quote (Mode 2): Full OHLCV data and price change.
- Depth (Mode 3): Level 2 order book data (5, 20, 30, or 50 levels).
Sources: collections/openalgo/IN_stock/WEBSOCKET_README.md:15-35
Sandbox and Analyzer Mode
The Backend Services Layer includes a fully isolated Sandbox engine for testing strategies without financial risk. It utilizes a dedicated SQLite database (sandbox.db) and simulates broker responses.
- Capital Simulation: Provides a virtual ₹1 Crore sandbox capital.
- Margin Logic: Implements realistic margin blocking and release scenarios.
- Validation: Simulates product-specific rules, such as rejecting CNC (delivery) sell orders when no holdings exist.
- Rejection Audit: Stores rejection reasons in a sandbox order book for diagnostic purposes.
Sources: test/sandbox/README.md:5-50, CLAUDE.md:124-128
Technical Constraints and Invariants
- Execution Environment: Production services run under
eventletwithin a single Gunicorn worker. Standardasynciois prohibited as it conflicts with eventlet's monkey-patching. - Database Hygiene: All SQLite connections must use
NullPoolto ensure a fresh connection per operation, preventing cursor corruption during concurrent requests. - ZeroMQ Bus: The market-data bus uses a fan-in pattern where the Proxy SUB socket
bindsand adaptersconnect. - Security: API keys are hashed with a unique pepper before storage, and sensitive tokens are encrypted using Fernet symmetric encryption.
Sources: CLAUDE.md:94-122, CLAUDE.md:175-185
Summary
The Backend Services Layer is the functional heart of OpenAlgo, providing the necessary abstraction to support a diverse ecosystem of brokers and trading interfaces. By centralizing order routing, portfolio management, and market data normalization, it enables robust algorithmic execution while maintaining high standards for security and performance through its middleware and ZMQ-based distribution model.