Crypto Never Sleeps — Neither Should Your Risk Management | by DolphinDB | MediumSitemapOpen in appSign up<br>Sign in
Medium Logo
Get app<br>Write
Search
Sign up<br>Sign in
Crypto Never Sleeps — Neither Should Your Risk Management
DolphinDB
6 min read·<br>Mar 6, 2026
Listen
Share
Press enter or click to view image in full size
Cryptocurrency markets never sleep — and neither do the risks that come with them. Price swings of 10% or more within a single hour are not unusual, and for traders managing multi-asset portfolios across spot and futures accounts, staying on top of exposure in real time is not just good practice — it’s essential.<br>Traditional risk management approaches that rely on end-of-day batch calculations simply don’t cut it in this environment. What’s needed is a system that continuously monitors account balances, positions, and market prices, computes key risk metrics on the fly, and alerts you the moment thresholds are breached.<br>This post walks through how to build exactly that using DolphinDB. By integrating directly with Binance and OKX exchange APIs, the solution provides real-time computation of portfolio net value, unrealized P&L, leverage ratios, and more — all persisted to a time-series database and wired to instant notifications.<br>Solution Overview<br>The system is built around three core capabilities:<br>Exchange data retrieval: Periodically polls wallet balances, futures positions, and market quotes from exchanges via REST APIs, and writes them into DolphinDB stream tables for downstream computation.<br>Real-time risk computation: Computes risk metrics for spot and futures accounts separately, then combines them into unified portfolio-level indicators — updated every minute.<br>Real-time data persistence and alerting: Persists all account information and risk metrics to the DolphinDB database in real time, and triggers notifications when defined risk thresholds are exceeded.<br>Risk Metric Computation<br>The solution computes risk metrics at three levels: spot account, futures account, and overall portfolio. Variable names and formulas follow Binance’s conventions.<br>Spot account risk metrics<br>Free value (freeValue) : The sum of each asset’s free quantity multiplied by its corresponding market price (midPrice).<br>Locked value (lockedValue) : The sum of each asset’s locked quantity multiplied by its corresponding market price (midPrice).<br>Spot total value (spotTotalValue) : The sum of free value and locked value.<br>Futures account risk metrics<br>Live unrealized P&L (liveUnrealizedProfit): The sum of potential profits across all futures positions based on the difference between the current market price and the break-even price.<br>Futures net value (futuresNetValue): The sum of the total futures account value and unrealized profit.<br>Total futures position value (principleAmt): The sum of each futures position multiplied by its corresponding market price (midPrice).<br>Futures leverage ratio (futuresLeverageRatio): The total futures position value divided by the total futures account balance.<br>In the leverage computation, the discountRatio parameter is introduced as a conservative adjustment factor to prevent excessive leverage. In this solution, the discount ratio is set to 0.95.<br>Overall risk metrics<br>Total value (totalValue): The sum of spot total value and futures net value.<br>Total leverage ratio (totalLeverageRatio): The ratio of (spot free value plus the total futures position value) to the total account value.<br>Building the Risk Model<br>The following steps walk through building the real-time risk model using Binance as the example exchange.<br>Create data tables<br>In DolphinDB, create in-memory tables to store exchange data. Use latestKeyedTable to create key-value in-memory tables for account information (asset and position data) and price data, and share them across all sessions on the current node using share. Key-value in-memory tables make it easy to store the latest data and can be directly used for risk metric computation. The following example shows how to create a spot position table:<br>// Spot position<br>colNames = `asset`free`locked`updateTime<br>colTypes = [SYMBOL, DOUBLE, DOUBLE, TIMESTAMP]<br>share latestKeyedTable(`asset, `updateTime, 1000:0, colNames, colTypes) as spotBalanceKT<br>goFor risk metrics, use streamTable to create stream tables, and enable enableTableShareAndPersistence to allow both sharing and persistence.<br>// Risk metrics<br>colNames = `freeValue`lockedValue`spotTotalValue`baseCurrency`free`locked`balance`crossWalletBalance`crossUnPnl`availableBalance`maxWithdrawAmount`updateTime`principleAmt`liveUnrealizedProfit`unrealizedProfit`futuresNetValue`futuresLeverageRatio`totalValue`totalLeverageRatio<br>colTypes = [DOUBLE,DOUBLE,DOUBLE,STRING,DOUBLE,DOUBLE,<br>DOUBLE,DOUBLE,DOUBLE,DOUBLE,DOUBLE,TIMESTAMP,DOUBLE,<br>DOUBLE,DOUBLE,DOUBLE,DOUBLE,DOUBLE,DOUBLE]<br>enableTableShareAndPersistence(<br>table=streamTable(10000:0, colNames, colTypes),<br>tableName="portfolioRiskIndicatorST",<br>cacheSize=100000,<br>preCache=10000<br>goRetrieve exchange...