Risk Server
Contents
Risk Server
The Risk Server monitors account profit and loss, enforces risk limits, and manages account state transitions based on trading activity. It tracks each account's net position, buying power consumption, and realized/unrealized profit and loss. When an account exceeds its configured loss threshold, the server automatically transitions the account through risk states—from active trading to closed orders mode, and ultimately to disabled or liquidation if losses continue. By centralizing risk monitoring and enforcement, the server protects both individual accounts and the overall system from excessive exposure.
The Risk Server integrates with the Service Locator for authentication, the Order Execution service to monitor trades, and a MySQL database to persist risk parameters and inventory snapshots.
Configuration
The Risk Server is configured via a YAML file that defines network interfaces, database connection, and Service Locator integration. Below is the structure of the configuration file with example values:
--- server: # Primary network interface and port the Risk Server binds to. interface: "0.0.0.0:20600" # List of addresses the server is reachable at (for registration with Service Locator). # Typically includes both public-facing and local addresses. addresses: ["198.51.100.5:20600", "10.0.0.5:20600"] data_store: # The address of the MySQL server (host:port). address: "127.0.0.1:3306" # The username for authenticating with MySQL. username: spireadmin # The password for the MySQL user. password: 1234 # The name of the database schema where data is stored. schema: spire service_locator: # The address of the Service Locator (host:port). address: "10.0.0.5:20000" # The account username used by the Risk Server to authenticate with the Service Locator. username: risk_service # The password for the Risk Server's Service Locator account. password: admin_password ...
Risk Parameters
Each account is assigned risk parameters that govern its trading limits and risk enforcement behavior:
- Currency - The currency used for risk calculations and loss limits
- Buying Power - Maximum amount of capital available for trading
- Allowed State - The risk state the account is permitted to operate in
- Net Loss Threshold - Maximum net loss before transitioning to closed orders mode
- Transition Time - Duration allowed in closed orders mode before automatic liquidation
Risk States
Accounts progress through the following risk states based on their profit and loss:
- Active - Normal trading with full permissions
- Closed Orders - No new orders allowed; existing positions may be reduced
- Disabled - Trading prohibited; positions must be manually managed
- Liquidation - Account positions are automatically liquidated
Functionality
Real-Time Risk Monitoring
The Risk Server continuously tracks:
- Net position by security and currency
- Realized and unrealized profit and loss
- Buying power consumption
- Order and execution activity
When an account's net loss exceeds its configured threshold, the server automatically transitions the account to closed orders mode and starts a timer. If the account does not return to profitability within the transition time, the server escalates to disabled or liquidation state.
Inventory Management
The server maintains real-time inventory snapshots for each account, tracking:
- Open positions by security
- Average cost basis
- Current market value
- Unrealized profit and loss
Inventory updates occur on every execution report, ensuring accurate position tracking across all trading venues.
Regional Risk Control
Risk parameters and state transitions can be scoped by region (country, venue, or security). This enables fine-grained control over risk exposure in specific markets or asset classes.
Utility Scripts
positions.py
Reports current positions for accounts in CSV format:
python positions.py --config config.yml # Configuration file --account trader1 # Specific account (optional; reports all if omitted)
Output format:
Account,Security,Currency,Side,Open Quantity,Cost Basis trader1,AAPL.NASDAQ,USD,Long,100,15000.00 trader1,TSLA.NASDAQ,USD,Short,50,12500.00
moe.py
Manual Order Entry (MOE) utility for opening or closing positions without market execution. These orders are synthetic and do not interact with external venues:
python moe.py --config config.yml # Configuration file --positions positions.csv # CSV file with positions to MOE --account trader1 # Specific account (optional) --region CA # Region filter (country/venue/security) --open # Open positions --close # Close positions
The positions CSV file must have the format:
Account,Security,Currency,Side,Open Quantity,Cost Basis
Use cases:
- Opening initial positions for testing
- Closing positions during liquidation
- Adjusting positions after system recovery
reset.py
Resets risk state for a specific region, clearing accumulated profit/loss tracking:
python reset.py --config config.yml # Configuration file --region CA # Region to reset (country code, venue, or security)
This utility is typically used at the start of a trading day or after maintenance periods to reset risk calculations.
Installation & Setup
A setup.py script is provided to generate the final config.yml from the config.default.yml template.
The script supports the following arguments:
python setup.py --local 0.0.0.0 # Local interface (default: auto-detected IP) --world 198.51.100.5 # Global/public interface (optional) --address 10.0.0.5:20000 # Service Locator address (default: local_interface:20000) --password [REQUIRED] # Service password for authentication --mysql_address 127.0.0.1:3306 # MySQL server address --mysql_username spireadmin # MySQL username --mysql_password secretpw # MySQL password (default: --password if omitted) --mysql_schema spire # MySQL schema
Operations
The Risk Server is controlled using three operational scripts: start.sh, stop.sh, and check.sh.
Log files are generated in the format:
srv_YYYYMMDD_HH_MM_SS.log
Upon startup, older log files are moved into the logs/ directory.
check.sh
The check.sh script verifies whether the server is currently running by inspecting the PID recorded in pid.lock and testing whether the associated process exists.
If the server is not running, it prints:
RiskServer is not running.
start.sh
The start.sh script:
- Exits immediately if the server is already running
- Creates a
logs/directory if necessary - Moves any existing
srv_*.logfiles intologs/ - Starts the
RiskServerprocess in the background - Writes the PID to
pid.lock - Reads network interfaces from
config.ymland waits until the server is listening on at least one configured address
This ensures the server is fully initialized before the script exits.
stop.sh
The stop.sh script:
- Reads the PID from
pid.lock - Sends
SIGINTto request a graceful shutdown - Waits for termination using exponential backoff (up to 300 seconds)
- Sends
SIGKILLif the server fails to stop cleanly - Appends a forced-termination message to the most recent log file (if applicable)
- Removes the
pid.lockfile
This guarantees consistent shutdown behavior across normal and exceptional conditions.
