
The problem
A trading platform must never pay out twice or let an account go below zero, even when a user closes a position at the same moment the risk engine liquidates it.
What I built
One audited function for every balance change. It locks the wallet, refuses negative balances, and appends entries to a per-wallet hash chain. Database triggers block edits and deletes.
Margin and P&L that use each contract's multiplier. After finding silver, crude and natural gas under-margined 100 to 1,000 times, I moved margin into one function shared by the order path, the risk worker and every close path, with a regression test.
A race-safe close: a conditional update claims the position only while it is still open, so a user close and a liquidation can't both pay out.
A risk worker that checks equity against maintenance margin every second from live prices, plus stop-loss and take-profit.
Options priced on the server with Black-Scholes.
Stack: TypeScript, Next.js, PostgreSQL, Drizzle, Redis, WebSockets
0 likes · 2 views · Oct 30, 2026
For a client's commodity trading platform: margin, liquidation and P&L on a hash-chained ledger, with race-safe closes so nothing pays out twice.