07 - Sandbox Architecture (Analyzer Mode)
Overview
OpenAlgo's Sandbox/Analyzer mode provides a local walk-forward execution environment with ₹1 Crore default sandbox capital, margin/leverage simulation, auto square-off, and T+1 settlement behavior. It stores trading state separately from live broker state in db/sandbox.db.
Analyzer mode implements GTT place, modify, cancel and orderbook through sandbox/gtt_manager.py, backed by the sandbox_gtt and sandbox_gtt_legs tables. The 501 responses on those four endpoints belong to live mode instead: import_broker_gtt_module(broker) returns None for any broker without an api/gtt_api.py, which today means every broker except Dhan and Zerodha.
Architecture Diagram

Core Components
1. Database Models
Location: database/sandbox_db.py
SandboxOrders Table
Stores all sandbox orders with complete state tracking.
Why margin_blocked is critical:
Stores exact margin calculated at order placement
Prevents over/under-release when execution price ≠ order price
Ensures margin consistency across async execution
SandboxTrades Table
Records executed trades linked to orders.
SandboxPositions Table
Tracks open positions with comprehensive P&L tracking.
P&L Field Semantics:
pnl: Display field for unrealized P&L (varies by context)accumulated_realized_pnl: All-time realized, never decrementstoday_realized_pnl: Daily realized, resets at session boundary (03:00 IST)
SandboxHoldings Table
T+1 settled CNC positions (delivery holdings).
SandboxFunds Table
Sandbox capital management per user.
Fund Balance Equation:
SandboxDailyPnL Table
EOD snapshots for historical P&L reporting.
SandboxConfig Table
Global configuration for all sandbox settings.
Default Configuration Values:
starting_capital
10000000
₹1 Crore sandbox capital
reset_day
Never
Weekly reset day (Never/Monday-Sunday)
reset_time
00:00
Reset time in IST
equity_mis_leverage
5
5x leverage for equity intraday
equity_cnc_leverage
1
1x for equity delivery
futures_leverage
10
10x for futures
option_buy_leverage
1
Full premium for option buy
option_sell_leverage
1
Full premium for option sell
nse_bse_square_off_time
15:15
NSE/BSE MIS square-off
cds_bcd_square_off_time
16:45
Currency MIS square-off
mcx_square_off_time
23:30
MCX MIS square-off
ncdex_square_off_time
17:00
NCDEX MIS square-off
order_check_interval
5
Execution engine polling (seconds)
mtm_update_interval
5
Position MTM update (seconds)
2. Fund Manager
Location: sandbox/fund_manager.py
Manages sandbox capital with thread-safe operations and realistic margin calculations.
Margin Calculation
Margin Block/Release Flow
Margin Reconciliation
Detects and fixes margin inconsistencies.
Auto-Reset Feature
3. Execution Engine
Location: sandbox/execution_engine.py
Background worker that monitors pending orders and executes them based on live market data.
Main Execution Loop
Order Execution Logic by Price Type
Trade Execution and Position Update
Execution Flow Diagram

4. Position Manager
Location: sandbox/position_manager.py
Handles position tracking, MTM updates, session filtering, and expired contract handling.
MTM (Mark-to-Market) Updates
Session Filtering
Expired Contract Handling
5. Square-Off Manager
Location: sandbox/squareoff_manager.py
Automatically closes MIS positions at exchange-specific timings.
Main Square-Off Logic
APScheduler Jobs
6. Holdings Manager
Location: sandbox/holdings_manager.py
Handles T+1 settlement and holdings MTM.
T+1 Settlement Process
7. Order Manager
Location: sandbox/order_manager.py
Handles order placement, modification, and cancellation.
Order Placement
Order Modification
Order Cancellation
8. API Integration
Location: restx_api/analyzer.py, services/sandbox_service.py
All major API endpoints check sandbox mode and route accordingly.
Analyzer Toggle Endpoint
Complete Order Flow Diagram

Session and Settlement Flow

Key Files Reference
database/sandbox_db.py
All database models and initialization
sandbox/fund_manager.py
Capital and margin management
sandbox/execution_engine.py
Order execution background worker
sandbox/position_manager.py
Position tracking and MTM
sandbox/squareoff_manager.py
Auto square-off scheduling
sandbox/holdings_manager.py
T+1 settlement logic
sandbox/order_manager.py
Order CRUD operations
sandbox/gtt_manager.py
GTTManager analyzer GTT lifecycle and OCO leg handling
sandbox/catch_up_processor.py
Startup catch-up for missed events
sandbox/execution_thread.py
Execution engine thread management
sandbox/websocket_execution_engine.py
WebSocket-based order execution
sandbox/squareoff_thread.py
APScheduler management
services/sandbox_service.py
API integration layer
services/analyzer_service.py
Analyzer mode toggle
restx_api/analyzer.py
REST API endpoints
blueprints/analyzer.py
Web UI routes
blueprints/sandbox.py
Configuration UI routes
Configuration Blueprint
Location: /sandbox web routes
/sandbox/
GET
Configuration page
/sandbox/api/configs
GET
Get all config values
/sandbox/update
POST
Update config value
/sandbox/reset
POST
Reset all sandbox data
/sandbox/reload-squareoff
POST
Reload square-off schedule
/sandbox/squareoff-status
GET
Current square-off status
/sandbox/mypnl
GET
P&L history page
/sandbox/mypnl/api/data
GET
P&L history data (JSON)
/sandbox/mypnl/export/daily
GET
Daily P&L export
/sandbox/mypnl/export/positions
GET
Positions export
/sandbox/mypnl/export/holdings
GET
Holdings export
/sandbox/mypnl/export/trades
GET
Trades export
Analyzer GTT
sandbox/gtt_manager.py implements the analyzer side of GTT. services/sandbox_service.py exposes sandbox_place_gtt_order, sandbox_modify_gtt_order, sandbox_cancel_gtt_order and sandbox_gtt_orderbook, each of which constructs a GTTManager(user_id) and calls the matching method:
Service function
GTTManager method
sandbox_place_gtt_order
place_gtt(gtt_data, last_price)
sandbox_modify_gtt_order
modify_gtt(trigger_id, gtt_data)
sandbox_cancel_gtt_order
cancel_gtt(trigger_id)
sandbox_gtt_orderbook
list_gtts(status_filter)
State lives in the sandbox_gtt and sandbox_gtt_legs tables. Each of the four GTT services checks get_analyze_mode() first and routes here; only the live branch can return 501, and only when the selected broker has no api/gtt_api.py.
Last updated
Was this helpful?