Live Settings Management Flow
Legend
- Blue nodes → API calls and data operations
- Green nodes → Database operations and success states
- Orange nodes → Real-time connection management
- Red nodes → Error states
Loading Settings Flow
1. User Opens Settings Panel
When the user opens the Trading Settings section, loadTradingSettings() is called automatically.
2. Fetch Settings from API
Endpoint: GET /api/trading-settings
Location: server.js:9355
Process:
- Authenticate user via
getUserId(req) - Query
trading_settingstable for user-specific settings - If no settings exist, create default settings:
risk_strategy:{ enabled: false, type: 'martingale', ... }live_trading:{ enabled: false, autoPlaceOrders: false }
- Return settings object with
valueandupdatedAtfor each setting
3. Parse and Populate UI
Location: index.html:9968
Settings Loaded:
-
Risk Strategy (legacy):
enabledcheckboxportfolioBalanceriskPercentmaxContracts
-
Live Trading:
enabledcheckboxautoPlaceOrderscheckbox
4. Fetch Risk Engine Config
Endpoint: GET /api/risk-engine/config
Purpose: Loads the new risk engine configuration (separate from legacy settings)
Config Includes:
- Starting balance
- Trailing drawdown limit
- Daily loss limit
- Max risk per trade percentage
- Max open trades
- Safety buffer percentage
- Risk mode (fixed_fraction, anti_martingale_pyramiding, etc.)
- Consistency rule settings
- Payout security settings
- Verification settings
5. Check Live Trading Status
Endpoint: GET /api/live-trading-status
Location: server.js:9888
Returns:
{
"success": true,
"status": {
"liveTradingEnabled": boolean,
"autoPlaceOrdersEnabled": boolean,
"hasCredentials": boolean,
"isFullyConfigured": boolean,
"liveTradesCount": number,
"accountId": string | null,
"credentialsUpdatedAt": timestamp | null
},
"settings": { ... },
"credentials": { ... }
}
Status Display:
- ✅ Fully Configured: Green indicator - Live trading enabled, auto-place enabled, credentials configured
- 🟡 Partially Configured: Yellow indicator - Live trading enabled but auto-place disabled
- 🔴 Missing Credentials: Red indicator - Live trading enabled but no TopStepX credentials
- ⚪ Inactive: Gray indicator - Live trading disabled
Saving Settings Flow
1. User Clicks "Save Settings"
Location: index.html:9996 - saveTradingSettings()
2. Collect Form Data
The function collects all settings from the UI:
Risk Engine Config:
- Starting balance
- Drawdown limits
- Risk percentages
- Anti-martingale settings (if applicable)
- Consistency rule settings
- Payout security settings
- Verification settings
Legacy Risk Strategy:
- Enabled state
- Portfolio balance
- Risk percent
- Max contracts
Live Trading:
- Enabled checkbox
- Auto-place orders checkbox
3. Multiple API Calls
The save process makes three separate API calls:
A. Save Risk Engine Config
Endpoint: POST /api/risk-engine/config
Body: Complete risk engine configuration object
B. Save Legacy Risk Strategy
Endpoint: POST /api/trading-settings
Body:
{
"settingKey": "risk_strategy",
"settingValue": {
"enabled": boolean,
"type": "legacy",
"portfolioBalance": number,
"riskPercent": number,
"maxContracts": number | null
}
}
C. Save Live Trading
Endpoint: POST /api/trading-settings
Body:
{
"settingKey": "live_trading",
"settingValue": {
"enabled": boolean,
"autoPlaceOrders": boolean
}
}
4. Server-Side Processing
Location: server.js:9450 - POST /api/trading-settings
Process:
- Authenticate user
- Validate
settingKey(must berisk_strategyorlive_trading) - Upsert to database:
INSERT INTO trading_settings (user_id, setting_key, setting_value, updated_at)
VALUES ($1, $2, $3, CURRENT_TIMESTAMP)
ON CONFLICT (user_id, setting_key)
DO UPDATE SET setting_value = $3, updated_at = CURRENT_TIMESTAMP
5. Real-Time Connection Management
If settingKey === 'live_trading':
When Enabled:
- Get TopStepX credentials from
topstepx_credentialstable - Start real-time connection via
topstepxRealtimeService.startConnection() - This enables real-time order updates and position monitoring
When Disabled:
- Stop real-time connection via
topstepxRealtimeService.stopConnection() - This disconnects from TopStepX real-time feed
6. Response Handling
Success:
- Show green success message: "Settings saved successfully!"
- Refresh live trading status display
- If live trading is enabled, show warning after 2 seconds: "⚠️ Live trading is ENABLED. Orders will be placed automatically when signals are received."
Error:
- Show red error message with error details
- Settings are not saved
Database Schema
trading_settings Table
CREATE TABLE trading_settings (
user_id INTEGER NOT NULL,
setting_key VARCHAR(50) NOT NULL,
setting_value JSONB NOT NULL,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (user_id, setting_key),
FOREIGN KEY (user_id) REFERENCES users(id)
);
Setting Keys:
risk_strategy: Legacy risk strategy configurationlive_trading: Live trading enable/disable and auto-place settings
API Endpoints Summary
GET /api/trading-settings
- Purpose: Load user-specific trading settings
- Auth: Required
- Returns: Settings object with
risk_strategyandlive_trading - Default: Creates default settings if none exist
POST /api/trading-settings
- Purpose: Save user-specific trading settings
- Auth: Required
- Body:
{ settingKey, settingValue } - Valid Keys:
risk_strategy,live_trading - Side Effects: Manages TopStepX real-time connection if
live_trading
GET /api/live-trading-status
- Purpose: Get comprehensive live trading status
- Auth: Required
- Returns: Status object with settings, credentials, and trade counts
- Used For: Status indicator display in UI
GET /api/risk-engine/config
- Purpose: Load risk engine configuration
- Auth: Required
- Returns: Complete risk engine config object
POST /api/risk-engine/config
- Purpose: Save risk engine configuration
- Auth: Required
- Body: Complete risk engine config object
Integration Points
TopStepX Real-Time Service
When live trading is enabled:
- Real-time connection is automatically started
- Connection uses credentials from
topstepx_credentialstable - Enables real-time order updates and position monitoring
- Connection is stopped when live trading is disabled
Risk Engine Integration
Settings saved via /api/trading-settings are used by:
- Trade entry flow (checks if live trading is enabled)
- Position sizing calculations
- Risk management rules
- Consistency rule enforcement
Error Handling
Authentication Errors
- 401 Unauthorized: User not authenticated
- Response:
{ success: false, error: 'Authentication required' }
Validation Errors
- 400 Bad Request: Invalid
settingKeyor missing parameters - Response:
{ success: false, error: 'Invalid setting key...' }
Server Errors
- 500 Internal Server Error: Database or processing error
- Response:
{ success: false, error: error.message }
User Experience
Loading Settings
- Settings are automatically loaded when settings panel opens
- Default values are created if no settings exist
- Status indicator shows current configuration state
Saving Settings
- All three API calls must succeed for save to be considered successful
- Success message is shown immediately
- Warning is shown if live trading is enabled
- Status display is refreshed after save
Status Display
- Real-time status indicator shows:
- Configuration completeness
- Credential status
- Number of open live trades
- Account ID (if configured)