Skip to main content

Architecture Diagram Index

Purpose

This document provides an index of all architecture diagrams and explains what to look for when auditing the platform's security and design.

Diagram Levels

Level 0: System Context

File: 01-context.md

Shows the platform in relation to external systems and users. Identifies:

  • External actors (TradingView, Traders, Admins)
  • External systems (TopstepX API, PostgreSQL)
  • Trust boundaries
  • High-level data flows

What to look for:

  • Clear separation between external and internal systems
  • Proper authentication boundaries
  • No direct access from untrusted sources to sensitive systems

Level 1: Container Diagram

File: 02-container.md

Shows the major containers (applications/services) within the platform. Identifies:

  • Frontend (Static HTML/JS)
  • Backend API (Express/Node.js)
  • Database (PostgreSQL)
  • External APIs (TopstepX Gateway)
  • Trust boundaries between containers

What to look for:

  • Frontend never directly accesses database
  • Frontend never directly calls TopstepX API
  • All sensitive operations go through backend
  • Clear separation of concerns

Level 2: Detailed Flows

1. Live Entry Flow

File: flows/01-live-entry.md

Shows the complete flow from TradingView alert to live order placement. Includes:

  • Webhook reception
  • TopstepX state fetching (source of truth)
  • Risk engine calculation
  • Safety gates (fail-closed, verification, staleness)
  • Order placement

What to look for:

  • FORBIDDEN: UI to TopstepX direct (red dashed line)
  • FORBIDDEN: Live trading using DB state without TopstepX verification
  • REQUIRED: TopstepX state always fetched in live mode
  • REQUIRED: Fail-closed gates block trading on invalid/stale state
  • REQUIRED: Verification mismatch blocks if fail_closed=true

2. Exit/Reduce Flow

File: flows/02-exit-reduce.md

Shows how exit and reduce-only orders are processed. Includes:

  • Order intent determination (order_intent="exit" or "reduce_only")
  • Payout mode checks (allow_manage_only, block_new_entries)
  • Risk engine validation
  • Order execution

What to look for:

  • Payout processing modes correctly differentiate entry vs exit
  • Exit orders bypass entry restrictions when appropriate
  • Risk engine still validates exit orders

3. Pyramiding Flow

File: flows/03-pyramiding.md

Shows the pyramiding decision logic. Includes:

  • Consistency rule checks (best day cap)
  • Payout security checks
  • Risk engine canPyramid() function
  • Position size calculation for adds

What to look for:

  • Pyramiding blocked when consistency cap reached
  • Pyramiding blocked during payout processing
  • Pyramiding respects soft threshold

4. Payout Security Flow

File: flows/04-payout.md

Shows payout request and completion flows. Includes:

  • Payout request initiation
  • Trading lock activation
  • Funded account MLL=0 floor logic
  • Payout completion and unlock

What to look for:

  • Trading locked immediately on payout request
  • Floor source priority: TopstepX > config > assumed
  • Funded accounts use hard floor instead of trailing drawdown
  • Floor source clearly marked in details

5. Consistency Rule Flow

File: flows/05-consistency-rule.md

Shows Topstep consistency rule enforcement (best day less than or equal to 50% profit target). Includes:

  • Daily P&L calculation (trading session boundary)
  • Cap calculation (best day % of target)
  • Soft threshold logic
  • Mode differentiation (hard_block, no_new_entries, disable_pyramiding)

What to look for:

  • Trading session boundary correctly applied (5pm ET)
  • Soft threshold restricts pyramiding before hard cap
  • Mode correctly differentiates behavior

6. Simulation Flow

File: flows/06-simulation.md

Shows simulation/backtesting flow. Includes:

  • Trade data loading
  • Risk engine simulation
  • Consistency rule application
  • Results aggregation

What to look for:

  • FORBIDDEN: Simulation to Live executor (red dashed line)
  • Simulation uses internal state (not TopstepX)
  • Consistency rule applied in simulation
  • Results never affect live trading

7. Settings & Verification Flow

File: flows/07-settings-verification-refresh.md

Shows settings management and state verification. Includes:

  • Settings save/load
  • TopstepX state refresh
  • Verification mismatch detection
  • Warning badge display

What to look for:

  • Settings validated before save
  • State refresh respects max age
  • Mismatch warnings displayed
  • No secrets exposed in UI

8. Trade List Display Flow

File: flows/08-trade-list-display.md

Shows how trades are fetched and displayed in the UI. Includes:

  • Trade list pagination
  • Database querying and filtering
  • UI table rendering
  • Auto-refresh behavior

What to look for:

  • Proper filtering (excludes failed/rejected/cancelled trades)
  • Live trades must have TopstepX order ID
  • Pagination controls work correctly
  • Auto-refresh only on page 1 to avoid blinking

9. Statistics Display Flow

File: flows/09-statistics-display.md

Shows how statistics are calculated and displayed. Includes:

  • Trade count calculations
  • Win/loss streaks
  • PnL metrics (total, average, best)
  • Live vs simulation stats priority

What to look for:

  • Stats prioritize live trades over simulation
  • Color coding for positive/negative values
  • Auto-refresh prevents rapid blinking
  • Admin users can see simulation stats

10. Balance & Metrics Display Flow

File: flows/10-balance-metrics-display.md

Shows how balances, metrics, and risk state are displayed. Includes:

  • Balance graph (equity curve)
  • TopstepX account metrics
  • Risk state display
  • Warning badges

What to look for:

  • Balance graph shows accurate equity curve
  • TopstepX metrics update frequently (5s)
  • Risk state warnings displayed when stale/mismatched
  • Floor source warnings for funded accounts

11. Manual Trade Entry Flow

File: flows/11-manual-trade-entry.md

Shows how users manually enter trades from the UI. Includes:

  • Form validation (client and server)
  • Database storage
  • Live trading integration
  • Post-submission updates

What to look for:

  • Direction logic validation (Long: SL < Entry < TP)
  • Manual trades can trigger live orders
  • Proper error handling and user feedback
  • Trade appears in trade list after submission

12. Live Settings Management Flow

File: flows/12-live-settings-management.md

Shows how live trading settings are loaded, saved, and integrated with the API. Includes:

  • Settings loading from database (with defaults)
  • Settings saving to database (upsert)
  • Risk engine config management
  • Live trading enable/disable
  • TopStepX real-time connection management
  • Status checking and display

What to look for:

  • Settings are user-specific (isolated by user_id)
  • Default settings created if none exist
  • Real-time connection started/stopped based on live trading state
  • Multiple API calls must all succeed for save to be successful
  • Status display shows comprehensive configuration state

13. Authentication Flow

File: flows/13-authentication.md

Shows Google OAuth authentication, user approval, and session management. Includes:

  • Google OAuth login flow
  • User registration on first login
  • Banned email checking
  • User approval workflow
  • Session creation and validation
  • Admin role checking

What to look for:

  • Banned emails are blocked before user creation
  • Admin users (info@fyrster.dk) are auto-approved
  • New users require admin approval
  • Sessions are validated on every API request
  • User approval status checked before access

14. Webhook Reception Flow

File: flows/14-webhook-reception.md

Shows how TradingView alerts are received and parsed. Includes:

  • Webhook endpoint handling
  • Multiple format parsing (JSON, query params, headers)
  • Alert data normalization
  • User ID extraction
  • Flux Charts detection
  • Result alert processing

What to look for:

  • Handles multiple TradingView alert formats
  • Extracts user_id from payload
  • Routes Flux Charts premium indicators to test handler
  • Validates alert data before processing
  • Stores raw data for debugging

15. Real-Time SignalR Connection Flow

File: flows/15-signalr-realtime.md

Shows WebSocket connection management for real-time TopStepX updates. Includes:

  • Connection establishment
  • Authentication token generation
  • SignalR hub subscription
  • Event handlers (Account, Order, Position, Trade)
  • Automatic reconnection
  • Connection lifecycle management

What to look for:

  • Connection starts when live trading enabled
  • Subscribes to all relevant events
  • Handles account closure automatically
  • Updates PnL in real-time
  • Reconnects automatically on failure

16. TopStepX Credentials Management Flow

File: flows/16-topstepx-credentials.md

Shows how TopStepX API credentials are stored and validated. Includes:

  • Credential input and validation
  • Account ID resolution (name → numeric ID)
  • Credential storage (encrypted)
  • Credential retrieval
  • Admin credential checking

What to look for:

  • Account names are resolved to numeric IDs via API
  • Credentials are stored securely (never returned)
  • Only account ID is displayed after saving
  • Admin can check other users' credentials

17. Manual Trade Exit Flow

File: flows/17-manual-trade-exit.md

Shows how users manually exit trades from the UI. Includes:

  • Exit form submission
  • Price validation (range checking)
  • PnL calculation
  • Exit type normalization
  • Trade status update

What to look for:

  • Validates exit price against entry price
  • Suggests corrections for common errors
  • Calculates PnL correctly for Buy/Sell
  • Normalizes exit types (TP/SL/Session End)

18. Risk Engine Testing Flow

File: flows/18-risk-engine-testing.md

Shows how the risk engine is tested and validated. Includes:

  • Test position size calculation
  • Risk summary generation
  • Multi-symbol tests (admin)
  • Edge case testing

What to look for:

  • Tests use actual risk engine logic
  • Multi-symbol tests verify independent streaks
  • Risk summary shows current limits
  • Admin-only test suite

19. Push Notifications Flow

File: flows/19-push-notifications.md

Shows browser push notification subscription and sending. Includes:

  • VAPID key generation
  • Browser permission request
  • Subscription management
  • Notification sending
  • Global notification settings

What to look for:

  • Subscriptions stored per user
  • Global enable/disable setting
  • Notifications sent on trade events
  • Expired subscriptions are cleaned up

20. Trade Export Flow

File: flows/20-trade-export.md

Shows how trades are exported for analysis. Includes:

  • Export request (admin only)
  • Data filtering (live trades only)
  • Format conversion (JSON/CSV)
  • File generation and download

What to look for:

  • Only exports live trades with TopStepX order IDs
  • Filters match trade list display
  • Includes all trade details and position sizing data
  • Admin-only access

21. Admin Operations Flow

File: flows/21-admin-operations.md

Shows all admin-specific operations. Includes:

  • Trade management (view, close, fix)
  • Trade cleanup operations
  • User management
  • System status checks
  • Push notification settings

What to look for:

  • All operations require admin authentication
  • Trade fixes update database correctly
  • Cleanup operations are logged
  • User deletions cascade properly

22. User Management Flow

File: flows/22-user-management.md

Shows admin user management operations. Includes:

  • User list viewing
  • User approval/rejection
  • User deletion
  • Banned email management
  • Credential checking

What to look for:

  • User approval required before access
  • Deletions cascade to related data
  • Banned emails prevent login
  • Credentials checked without exposing secrets

23. Trade Cleanup Flow

File: flows/23-trade-cleanup.md

Shows admin trade cleanup operations. Includes:

  • Stale trade detection and cleanup
  • Bad PnL detection and fixing
  • Clear all trades
  • Clear old trades

What to look for:

  • Stale trades are cancelled (not deleted)
  • Bad PnL is recalculated, not deleted
  • Clear operations require confirmation
  • All cleanup operations are logged

Legend

All flow diagrams use the following conventions:

  • Solid arrows to Allowed data flow
  • Red dashed arrows to Forbidden/should never happen paths
  • Gate nodes to Fail-closed/verification checkpoints
  • Source-of-truth labels to Indicates where data originates
  • Security-critical decisions to Highlighted nodes (payout lock, consistency rule, MLL floor, etc.)

Potential Issues Spotted from Structure

✅ Good Practices Identified

  1. Clear Source of Truth: TopstepX is always the source of truth in live mode
  2. Fail-Closed Design: Invalid/stale state blocks trading by default
  3. Trust Boundaries: Frontend never directly accesses database or TopstepX
  4. Verification Gates: Multiple verification checkpoints prevent stale data usage
  5. Mode Differentiation: Payout modes correctly handle entry vs exit

⚠️ Areas Requiring Attention

  1. Simulation Isolation: Ensure simulation never accidentally calls live executor
  2. State Freshness: UI warnings help but operators must monitor state age
  3. Floor Source: Assumed floor in funded accounts requires manual verification
  4. Verification Mismatch: Even with fail_closed=false, warnings are shown but trading continues

🔒 Security-Critical Decisions

The following decisions are security-critical and must be audited:

  1. TopstepX State Fetch: Always fetched in live mode, overwrites DB state
  2. Fail-Closed Gates: Block trading on invalid/stale state (default: ON)
  3. Payout Lock: Immediately locks trading on payout request
  4. Consistency Rule: Prevents best day from exceeding 50% of profit target
  5. Funded Floor: Hard floor replaces trailing drawdown when MLL=0
  6. Order Intent: Determines if payout modes allow/block orders