Skip to content
Risk and Margin Calculations in Trading Systems 5 min

Risk and Margin Calculations in Trading Systems

ScaleDojo
ScaleDojo
May 11, 2026
5 min read
1,094 words
Risk and Margin Calculations in Trading Systems

The $6 Billion Lesson: Archegos Capital

In March 2021, Archegos Capital collapsed, wiping out $10 billion in losses across multiple banks. Credit Suisse alone lost $5.5 billion. The root cause wasn't some exotic market event, it was inadequate margin calculations that failed to catch a dangerously leveraged book in time. Archegos had built massive leveraged positions through swaps that hid concentration risk from the very banks financing them. Those banks' risk engines did not flag the danger until positions were already deep underwater, and by then there was nothing left to do but sell into a falling market.

Here's the uncomfortable part: none of this required a black-swan event. If the margin calculations had been real-time and comprehensive (recalculated on every price tick rather than at end of day, and aggregated across the total exposure rather than siloed by bank) the losses would have been a fraction of what they were. That's really the whole argument for building a proper risk engine, so it's worth walking through what that math and that pipeline actually look like.

Margin Basics: The Leverage Game

Before getting into engine architecture, it helps to be precise about what "margin" even means, because the math is unforgiving. Leverage amplifies gains and losses symmetrically, but liquidation only happens on one side of that trade.

Margin and Leverage Explained:

  Your cash: $10,000
  Leverage:  10x
  Position:  $100,000 (you control 10x your cash)

  Example: Buy $100,000 of ETH at $4,000 (25 ETH)

  Scenario 1: ETH rises to $4,400 (+10%)
  Position value: $110,000
  Your P&L: +$10,000 (100% return on YOUR $10,000)

  Scenario 2: ETH drops to $3,600 (-10%)
  Position value: $90,000
  Your P&L: -$10,000 (100% LOSS - your entire balance)

  Margin Levels:
  +------------------+---------+-------------------------+
  | Type             | Amount  | Purpose                 |
  +------------------+---------+-------------------------+
  | Initial Margin   | $10,000 | Required to open        |
  | Maintenance      | $5,000  | Minimum to keep open    |
  | Margin Call      | $5,000  | Warning: deposit more   |
  | Liquidation      | $3,000  | Force-close positions   |
  +------------------+---------+-------------------------+

  If ETH drops 7%: account = $3,000 -> LIQUIDATION

Notice how thin that margin is. A 7% move against a 10x leveraged position wipes out enough equity to trigger a forced close. Now multiply that fragility across thousands of accounts and dozens of correlated positions, and you start to see why Archegos's banks needed a system that never blinked. That's the job of the risk engine.

Real-Time Risk Engine Architecture

A margin engine is only useful if it's fast enough to act before the account goes negative. The pipeline below targets sub-10ms from price tick to risk decision, which sounds aggressive until you remember that Archegos-style blowups happen in minutes, not days. If you're new to breaking systems down into these kinds of pipeline stages, the building blocks of low-level design are a good place to build that muscle.

Risk Engine Pipeline (sub-10ms target):

  [Exchange Price Feeds]
  WebSocket: ETH=$4,000.12 at 14:30:01.003
       |
  [Price Ingestion Service]    <- 1M+ price ticks/second
  Normalize, validate, deduplicate
       |
  [Position Engine]            <- In-memory (Redis/custom)
  For each user with open positions:
    unrealized_pnl = (current_price - entry_price) * quantity
    account_equity = cash_balance + unrealized_pnl
       |
  [Margin Calculator]
  margin_ratio = account_equity / total_position_value
       |
  [Risk Decision Engine]
       |
  margin_ratio > 20%:  ALL CLEAR
  margin_ratio < 20%:  WARNING (email/push notification)
  margin_ratio < 10%:  MARGIN CALL (must deposit in 24h)
  margin_ratio < 5%:   LIQUIDATION (force-close positions)
       |
  [Order Execution]  <- liquidation orders are highest priority

  Latency budget:
  Price tick to risk decision: < 10ms
  Risk decision to liquidation order: < 5ms
  Total: < 15ms or losses exceed collateral

Two design decisions matter most here. First, the position state lives entirely in memory, because a database round-trip on every tick would blow the latency budget before the math even starts. Second, liquidation orders jump the queue ahead of everything else, since a delayed liquidation is exactly the failure mode that turned Archegos from a bad trade into a systemic loss. If you're thinking through how price feeds get distributed to consumers like this at scale, the ideas in event sourcing and async messaging apply directly, since a risk engine is essentially a very latency-sensitive event stream consumer.

Mark-to-Market: Continuous Revaluation

The pipeline above is only correct if the underlying numbers are correct, and that means marking every position to the current market price rather than trusting a stale valuation. Here's what that looks like for a single account holding three positions.

Mark-to-Market Example (3 positions):

  User: trader_alice
  Cash balance: $50,000

  Position     Entry    Current  Qty    Unrealized P&L
  ----------   ------   -------  -----  --------------
  ETH/USD      $4,000   $4,200   10     +$2,000
  BTC/USD      $65,000  $64,000  0.5    -$500
  SOL/USD      $120     $135     100    +$1,500
                                        ----------
                                Total:  +$3,000

  Account equity = $50,000 + $3,000 = $53,000
  Total position value = $42,000 + $32,000 + $13,500 = $87,500
  Margin ratio = $53,000 / $87,500 = 60.6%  -> ALL CLEAR

  If ETH crashes to $3,200 (-20%):
  ETH P&L: -$8,000 (was +$2,000, now -$8,000)
  Account equity = $50,000 + (-$8,000) + (-$500) + $1,500 = $43,000
  Still safe, but deteriorating.

Alice's account is fine at 60.6%, and even after a sharp 20% drop in ETH it's still above the maintenance threshold. That's the whole point of continuous mark-to-market: it gives you the early warning that Archegos's counterparties never got, because the deterioration shows up immediately instead of at the next reporting cycle. If your engine is only recalculating equity once an hour, you've built a system that's structurally blind between updates, which is basically what happened in 2021.

Interview Tip

When designing a trading platform, say: "The risk engine is an in-memory system that recalculates every user's margin ratio on every price tick, under 10ms latency. Positions are marked-to-market continuously: account_equity = cash + sum(unrealized_pnl). When margin_ratio drops below the maintenance threshold, the system sends margin calls. Below the liquidation threshold, it force-closes positions automatically with highest priority. The engine uses WebSocket price feeds, in-memory position state, and circuit breakers to prevent cascading liquidations."

Risk and Margin Calculations in Trading Systems - Architecture Diagram

Architecture overview

That last line about circuit breakers is worth dwelling on for a second, because it's easy to design a system that liquidates correctly for one account but forgets that mass liquidations move the market and trigger more liquidations. Pairing this kind of risk engine design with solid intuition around caching and state placement trade-offs tends to come up in interviews too, since where you keep hot position data (in-process cache versus a shared in-memory store) directly affects both latency and consistency guarantees.

Key Takeaway

Trading risk systems must continuously mark positions to market as prices change, comparing account equity to margin requirements in real time. The engine must be fast (sub-10ms), consistent (no position mismatch), and reliable (margin calls must fire before losses exceed collateral). In-memory databases and low-latency price feeds are essential.

Enjoyed this article?

Share it with your network to help others level up their system design skills.

Discussion0

Join the Discussion

Sign in to leave comments, reply to others, or like insights.

Sign In to ScaleDojo

No comments yet. Be the first to start the thread!

Related Articles

Enjoyed this content?

Your support keeps us creating free resources

We put a lot of hours into researching and writing these guides. If it helped you, consider buying us a coffee. Every bit goes toward keeping ScaleDojo's content free and growing.

$

One-time payment via Stripe. ScaleDojo account required.