Yesterday I wrote about Situational Awareness LP, the hedge fund that went from forty-five billion dollars to roughly ten in the space of a week, and I made a claim that a lot of readers pushed back on. I said the fund ran with four investment professionals and eight employees total, and that the software required to monitor a book that size is no longer difficult or expensive. I called it a weekend project. Enough people asked me to show my work that I am going to.
This article is written for two audiences at once, which is a thing you are told not to do. Engineers want the implementation. Everyone else wants to understand what actually happened and why a smart person with excellent instincts got wiped out anyway. I think you can serve both, because the finance in this story is genuinely simple once someone explains it without the jargon, and the engineering is genuinely simple once you understand the finance. There are a handful of code samples. If you are not a developer, skip them. Nothing after a code block depends on your having read it.
Everything a risk system needs to tell you reduces to four questions. How much of this is actually mine. How far can it fall before somebody else starts making my decisions. How many different things do I actually own. How long would it take me to get out and what would that cost me. Four numbers. That is the whole discipline. The rest is plumbing.
First, What a Margin Account Actually Is
If you already know this, skip ahead two sections. If you do not, nothing else in the article will land, so here it is in one page.
Say you have a hundred thousand dollars and you want to buy stock. You could buy a hundred thousand dollars of stock. Or you could go to a broker, put up your hundred thousand as collateral, borrow another hundred thousand, and buy two hundred thousand dollars of stock. You now control twice as much as you own. That is leverage, and the ratio — two hundred thousand of exposure against a hundred thousand of your own money — is called two times, or 2x.
Here is the part that matters. If the stock rises ten percent, your position is worth two hundred and twenty thousand. You still owe the broker a hundred thousand, so your money is now a hundred and twenty thousand. You made ten percent on the stock and twenty percent on yourself. That is the appeal, and it is real.
Now run it the other way. The stock falls ten percent. Your position is worth a hundred and eighty thousand, you still owe a hundred thousand, and your money is eighty thousand. You lost twenty percent. Fall thirty percent and you have lost sixty percent of everything you had. The leverage does not care which direction it multiplies.
The second thing that matters is that the broker is not a passive lender. The loan is secured by the stock itself, so the broker sets a floor: your own money must stay above a certain percentage of the position’s value. Under the standard American rules that floor is twenty-five percent for shares you own, and most brokers set their house floor higher than the legal minimum. When you fall through the floor you get a margin call, which is a demand for more cash by a deadline usually measured in hours. If you cannot meet it, the broker sells your positions. Not when you think the price is fair. Not when you have finished your analysis. Immediately, at whatever the market will pay.
That is the entire mechanism. Everything that happened to Situational Awareness in July 2026 is an elaboration of the previous paragraph.
One correction to a widely repeated claim, including one I made loosely in the last article. Under Regulation T, the standard American margin rule, a fund borrowing from its prime broker is capped at roughly two times leverage. Full stop. Getting to four times, which is where Situational Awareness reportedly sat, requires leaving that regime entirely. There are three doors. A portfolio margin account, where the broker replaces the flat percentage with a risk model that stress-tests your whole book and can be far more generous to a genuinely hedged portfolio. An enhanced prime brokerage arrangement, which routes the lending through a non-US entity that operates under looser law, and which buys you leverage in exchange for additional legal risk if things go wrong. Or synthetic exposure through total return swaps, where you never own the shares at all — the bank owns them and pays you their performance, and your leverage is embedded in the contract.
This matters for the software, because it means there is no universal margin formula. Which door you walked through determines your entire risk profile, and any system that assumes the textbook rules will be confidently wrong about the only number that counts.
Number One: How Much of This Is Mine
Your equity is what would be left if everything closed right now. Add up the market value of everything you own, subtract the market value of everything you have sold short, and add your cash — which is a negative number when you have borrowed. That is it.
The short piece confuses people, so briefly: selling short means borrowing shares you do not own, selling them, and hoping to buy them back cheaper. The sale proceeds land in your account as cash, and you carry an obligation to return the shares. When the stock rises, that obligation grows and your equity shrinks. This is why Situational Awareness was in genuine trouble rather than ordinary trouble — it was long AI infrastructure and short software companies, and in July the infrastructure names fell while the software names rallied. Both sides lost simultaneously. A portfolio built to have two independent legs discovered it had one leg pointed at both feet.
// Net liquidation value. Cash is negative when carrying a margin loan.
// Short proceeds are credited to cash; the buy-back obligation is SMV.
public static decimal Equity(Book b, IReadOnlyDictionary<string, decimal> marks)
{
decimal longMv = b.Longs.Sum(p => p.Quantity * marks[p.Symbol]);
decimal shortMv = b.Shorts.Sum(p => p.Quantity * marks[p.Symbol]);
return b.Cash + longMv - shortMv;
}
// Gross leverage: total exposure you control per dollar you own.
public static decimal GrossLeverage(decimal longMv, decimal shortMv, decimal equity)
=> (longMv + shortMv) / equity;
Use decimal, never double or float. I have been called into enough remediation work to have watched a floating-point rounding error in a position-keeping system turn into a six-figure reconciliation break that took three weeks to locate. Money is decimal all the way through, including in the database schema.
Number Two: How Far Can It Fall Before Someone Else Decides
Every risk dashboard in the world displays your equity and your margin requirement and the difference between them. Those dashboards are close to useless, and understanding why is the single most valuable idea in this article.
Knowing you have eleven million dollars of cushion tells you nothing, because you have no intuition for how quickly eleven million evaporates. What you want to know is how far the market has to move against you before the cushion is gone. Not in dollars. In percent.
A number that tells you where you are is a status. A number that tells you how far you can fall before someone else starts making your decisions is a warning. Build the second one.
Compute it two ways, and the second one is the one that would have mattered. Per position: holding everything else still, how far can this one name drop before you get the call. Across the whole book: what simultaneous move, applied to every position in the direction that hurts — longs down, shorts up — takes you to zero. That second number is the one that fires in a real crisis, because real crises are correlated. A system that stress-tests each holding in isolation will report that everything is fine right up until the morning everything is not.
You cannot solve this with algebra against a real broker agreement, because the requirement is not a straight line. Portfolio margin adds surcharges when any position exceeds a concentration threshold, and short positions get more expensive as they move against you, so the requirement steps upward exactly as your equity steps down. So you solve it numerically. Guess a shock, compute the resulting cushion, adjust, repeat. It converges in microseconds and you run it on every update.
// Bisect for the uniform adverse shock that drives excess equity to zero.
// Longs shocked down, shorts shocked up. Requirement recomputed at each
// step because concentration surcharges are non-linear in price.
decimal shockToCall = Bisect(lo: 0m, hi: 1m, tol: 0.0001m, f: pct =>
{
var stressed = marks.ApplyAdverse(book, pct);
return Equity(book, stressed) - _broker.MaintenanceRequirement(book, stressed);
});
Two things the first draft of this article left out, both of which I would rather you learn here than the expensive way.
A margin call is not the only way financing disappears. Prime brokerage agreements contain net asset value triggers — clauses that let the broker reduce or withdraw your leverage entirely if the fund’s value drops by some threshold in a month or a year, typically something like twenty percent and thirty-five percent respectively. These fire independently of your margin cushion. You can be comfortably above your maintenance requirement and still have your financing pulled because a calendar-month number crossed a line in a contract. Academic work on this describes the fund as effectively being short an option to its prime broker, which is exactly right and worth sitting with. Model your NAV triggers with the same seriousness as your margin, because they may well fire first.
And your brokers are not independent of each other. A fund typically uses two or three, and the comforting assumption is that they will not all tighten at once. They will. They are running similar risk models, watching the same volatility, and looking at heavily overlapping client books — so when the market moves they reach the same conclusion within hours of each other. Do not model your worst broker. Model all of them tightening simultaneously, because that is the observed behavior and it is what turns a bad week into a forced liquidation.
Number Three: How Many Things Do You Actually Own
The fund’s disclosed portfolio was roughly forty percent Nebius, twelve percent Bloom Energy, ten percent SanDisk, eight percent CoreWeave, six percent SharonAI, and a tail of former bitcoin miners. On a position report that is more than a dozen holdings across several industries. In reality it was one bet — that hyperscalers would keep spending enormous sums on AI infrastructure — expressed a dozen ways. Every one of those companies rises and falls on the same belief, so when the belief wobbled they all gapped down together on the same morning.
This is measurable, and the measure has a name: the effective number of bets, introduced by Attilio Meucci. The intuition is that if you hold twelve things that all move together, you own one thing, and a number should say so.
I want to be careful here, because there is a wrong version of this calculation that circulates widely and I nearly published it myself. The tempting shortcut is to take the correlation matrix of your holdings, extract its eigenvalues, and measure how lopsided they are. That is wrong, and the reason is instructive: it ignores your position sizes entirely. A book that is forty percent Nebius and a book that is equal-weighted across the same twelve names would score identically. The concentration you are trying to detect is invisible to it.
The correct calculation runs on the covariance matrix and it uses your weights. Decompose the covariance matrix into its principal components, which are a set of uncorrelated synthetic portfolios. Express your actual holdings in terms of those components. Compute how much of your portfolio’s total variance each component is responsible for, which gives you a set of proportions that sum to one. Then take the Shannon entropy of those proportions and exponentiate it. The result runs from one — everything is a single bet — up to the number of positions you hold, if they were genuinely independent.
// Meucci's Effective Number of Bets. Covariance, not correlation,
// and the portfolio weights must be in the calculation.
var cov = Statistics.Covariance(returnsMatrix); // n x n
var evd = cov.Evd(Symmetricity.Symmetric);
var E = evd.EigenVectors; // principal portfolios
var lam = evd.EigenValues.Real();
var wTilde = E.Transpose() * w; // weights in PC basis
var contrib = wTilde.PointwiseMultiply(wTilde)
.PointwiseMultiply(lam); // variance per component
var p = contrib / contrib.Sum(); // sums to 1
double entropy = -p.Where(x => x > 1e-12).Sum(x => x * Math.Log(x));
double enb = Math.Exp(entropy); // 1 .. n
Put that single integer in front of a human being every morning. Twelve positions with an effective bet count of one point three is not a diversified portfolio, it is a concentrated single-name position paying twelve sets of commissions, and one number says so in a way that a correlation heat map never will. Chart it over time. Set a floor on a calm day and alert when you breach it.
There is a refinement worth knowing about if you take this further. Raw principal components are mathematically clean but economically unstable — they can rotate meaningfully with small changes in the input window. The literature addresses this with a technique called minimal linear torsion, which produces uncorrelated factors that stay close to the original assets and are therefore interpretable. For a first implementation, plain principal components are fine. Just do not be surprised when the composition of your top component shifts.
Number Four: How Long to Get Out, and What Does It Cost
This is the simplest arithmetic in the article and it decided the outcome.
Take your position in shares. Divide by the stock’s average daily trading volume. Divide again by the share of that volume you can realistically take without pushing the price against yourself. The result is the number of trading days you need to exit in an orderly fashion.
That last input is where people fool themselves. Institutional practice puts a typical participation rate below ten percent, and stress testing is done at five percent or lower, because in a dislocation volume dries up at the same moment everyone wants out. Some frameworks will use twenty percent as a normal-conditions assumption, but running your stress case at twenty percent is the analytical equivalent of assuming the fire exit is unlocked. Use ten as your working number, five for stress, and compute the stressed case against the worst volume regime in your history rather than the current one.
For calibration, a widely used institutional scale treats anything under three days to liquidate as highly liquid, three to five as liquid, five to ten as less liquid, and ten or more as illiquid. Consider that Situational Awareness held forty percent of a forty-five billion dollar book in a single mid-cap name.
Days alone is only half the answer, and my first draft stopped there. You also want the cost. The standard approximation is the square-root law: expected market impact is roughly the stock’s daily volatility multiplied by the square root of your participation rate. A stock that moves two percent on a typical day, exited at ten percent of volume, costs you somewhere near two percent times the square root of one tenth, which is about sixty-three basis points — before spread, before the fact that everyone else is selling the same thing.
public sealed record LiquidityProfile(
decimal DaysToExit, decimal EstimatedImpactBps, VolumeRegime Regime);
public LiquidityProfile Evaluate(Position p, MarketStats s, decimal participation)
{
decimal adv = s.AverageDailyVolume(Regime); // stressed regime for the stress case
decimal days = p.Quantity / (adv * participation);
// square-root law: impact ~ daily vol * sqrt(participation rate)
double impact = (double)s.DailyVolatility * Math.Sqrt((double)participation);
return new LiquidityProfile(days, (decimal)(impact * 10_000), Regime);
}
Now multiply days-to-exit by distance-to-call and you have the only risk metric that ever really mattered. If it takes nine days to unwind a position and a six percent adverse move triggers your margin call, you do not own that position in any meaningful sense. You are holding it on someone else’s behalf until they decide otherwise. And the correct moment to discover this is when you are putting the trade on, not when your prime broker is on the phone.
A forced seller does not get to choose the price. That is the definition of the term. It is also knowable in advance, from one line of arithmetic, months before it happens.
The Machine Around the Four Numbers
Everything else is engineering, and it is the well-understood kind. Briefly, for those who want it.
Market data arrives over a streaming socket. Use a bounded channel that drops the oldest entry when full, because during a dislocation the data arrives faster than you can process it and a stale quote is worthless — you always want the newest. This is the opposite of most developers’ instinct, which is to buffer everything and fall progressively further behind reality at the exact moment reality matters.
Budget more engineering time for reconnection than for anything else in the data layer. You will lose the socket several times a day, always at the worst moment. Every serious feed carries a sequence number; detect the gap, backfill from the REST endpoint, and only then resume computing. A margin engine running on a book with a nine-minute hole in it is not a risk system, it is a liability with good typography. Write the tests that kill the connection deliberately, mid-stream, and use the TimeProvider abstraction rather than reading the clock directly so you can replay an entire trading day deterministically at a thousand times speed. That replay is how you prove your alerts would have fired when you claim they would have.
For storage, SQL Server system-versioned temporal tables solve a problem people usually solve badly with hand-rolled audit logs. When something goes wrong at 14:32 you need to know what the system believed at 14:32, not what it believes now about then. Temporal tables give you that at the storage engine level.
CREATE TABLE dbo.Position
(
PositionId UNIQUEIDENTIFIER NOT NULL PRIMARY KEY,
Symbol VARCHAR(24) NOT NULL,
Quantity DECIMAL(28,8) NOT NULL,
AverageCost DECIMAL(19,6) NOT NULL,
PrimeBrokerId INT NOT NULL,
ValidFrom DATETIME2(7) GENERATED ALWAYS AS ROW START NOT NULL,
ValidTo DATETIME2(7) GENERATED ALWAYS AS ROW END NOT NULL,
PERIOD FOR SYSTEM_TIME (ValidFrom, ValidTo)
)
WITH (SYSTEM_VERSIONING = ON (HISTORY_TABLE = dbo.PositionHistory));
SELECT * FROM dbo.Position
FOR SYSTEM_TIME AS OF '2026-07-29T14:32:07.000';
Tick history goes in its own table with a clustered columnstore index partitioned by trading date. Compression on financial time series routinely runs ten to one, and the aggregate queries the covariance calculation needs — a year of daily returns across a hundred symbols — run in batch mode and return in milliseconds.
The Agent Layer, and What It Is Honestly For
The reason funds historically needed analysts was document coverage. Somebody has to read the filing that drops at 4:05, sit through the earnings call, notice the ownership disclosure, catch the guidance revision buried on slide nineteen, and connect it back to why you own the thing in the first place. That does not scale, and it is why headcount grows with position count.
It is now largely automatable, and I want to be precise about why, because the reason is not that language models are clever. It is that this particular task is retrieval and comparison rather than judgment. You write down your thesis for each position — the actual reasons you own it, in plain sentences. You ingest filings, transcripts and news. And you ask, continuously, whether anything that just published contradicts anything you wrote down.
SQL Server 2025 handles the retrieval side without adding a separate vector database to your stack, which is a real operational win. One important caveat that I got wrong in my first draft and that will bite anyone copying from blog posts: the VECTOR type and the VECTOR_DISTANCE function are generally available, but vector indexes and approximate search are preview features. You must enable them explicitly, and — critically — creating a vector index does nothing for you unless you also switch your query to the approximate search syntax. An ordinary ORDER BY over VECTOR_DISTANCE performs an exact scan of every row and ignores the index entirely. People build the index, see no improvement, and conclude the feature is slow.
ALTER DATABASE SCOPED CONFIGURATION SET PREVIEW_FEATURES = ON;
CREATE TABLE dbo.DocumentChunk
(
ChunkId BIGINT IDENTITY PRIMARY KEY,
Symbol VARCHAR(24) NOT NULL,
SourceType VARCHAR(32) NOT NULL,
PublishedAt DATETIME2(0) NOT NULL,
Body NVARCHAR(MAX) NOT NULL,
Embedding VECTOR(1536) NOT NULL
);
CREATE VECTOR INDEX ixv_chunk ON dbo.DocumentChunk(Embedding)
WITH (METRIC = 'cosine', TYPE = 'DiskANN');
-- Approximate search. This engages the index. ORDER BY VECTOR_DISTANCE
-- would not: that is an exact scan over every row.
SELECT TOP (12) c.ChunkId, c.Symbol, c.SourceType, c.PublishedAt, c.Body
FROM VECTOR_SEARCH(
TABLE = dbo.DocumentChunk AS c,
COLUMN = Embedding,
SIMILAR_TO = @thesisVector,
METRIC = 'cosine',
TOP_N = 12) AS s
ORDER BY s.distance;
Above that sits an agent that wakes on a schedule, pulls what is new, retrieves the stored thesis, compares, and produces a divergence report citing the specific passage that triggered it. Expose the portfolio state through a Model Context Protocol server so the agent — or a human with a chat window — can ask questions about the book without someone building a bespoke endpoint for every question that gets asked once.
The design constraint that makes this safe is worth stating flatly, because it is where most people building these systems go wrong. The agent decides nothing. No write access to the book, no ability to place an order, no authority to dismiss an alert. It escalates, with a citation, to a person. It is a research analyst who reads everything, never sleeps, never gets bored on the ninth consecutive filing, and never quietly skips one because it is Friday afternoon. It is not a portfolio manager, and anyone selling you one is selling you a liability.
Alerting is tiered and the tiers must be genuinely different channels — dashboard, then chat, then SMS, then an actual phone call through a paging provider for anything threatening solvency. If every severity arrives in the same place, within two weeks all of them are being ignored at the rate of the least important. And build the dead man’s switch: the risk system emits a heartbeat, and something outside the risk system alerts when the heartbeat stops. The most dangerous state a monitoring system can be in is silent, and the second most dangerous is silent while everyone assumes silence means fine.
What It Costs, and What It Does Not Buy
A strong senior engineer builds the data, storage and margin layers in three to four weeks. Concentration and liquidity are a week, because the mathematics is two hundred lines and the rest is data hygiene. The agent layer is another three to four weeks depending on document sources. Hardening and alerting, a week. Call it two to three months for one person, six weeks for two, plus market data fees and a modest cloud bill. Less than one seat on a trading desk.
And now the part that would make this article dishonest if I left it out.
This system would not have saved Situational Awareness.
He was not flying blind. Reporting indicates at least one prime broker had already placed the fund on an internal watch list for being too concentrated and too volatile, and had demanded additional margin repeatedly over the preceding year, including in the final week. The information existed and was acted on by the lender. Someone close to the situation described him as having the illusion of control while not having control. That is not a monitoring failure. It is a leverage decision made months earlier that had quietly removed every option except one.
At four times leverage, on a book with an effective bet count near one and a nine-day exit profile, there is no dashboard that helps. By the time the numbers turn red the only remaining question is which distressed buyer gets your positions and at what discount. Software cannot return optionality you have already spent.
So what is it actually worth? It converts a feeling into a number, early, while choices still exist. It replaces I am a bit nervous about how large Nebius has gotten with I am eleven percent from a call, my book behaves as one point three independent positions, unwinding the largest takes nine days at a realistic participation rate, and it will cost me eighty basis points to do it. Those two sentences describe an identical situation. Only one of them changes what you do on a Tuesday in April, four months before the Tuesday in July when it stops being your decision.
That is what risk infrastructure is for, and the principle generalizes well past finance. It lets you set limits while you are calm and enforces them when you are not. Every system I have built in twenty-nine years that genuinely mattered did some version of that job.
If You Want One Built
I build production agentic systems on the .NET stack — Model Context Protocol servers, Microsoft Agent Framework orchestration, retrieval pipelines, SQL Server 2025 vector search, and the observability layer that determines whether any of it can be trusted with something that matters. The architecture above is not theoretical. It is the same pattern I ship for clients in commerce, logistics and regulated industries, aimed at a different domain.
If you run a book, a desk, a treasury function, or any operation where an unmonitored exposure could ruin your quarter, and you would rather own the system than rent a black box, get in touch through Inverted Software at invertedsoftware.com. I also do architecture reviews if you already have something and want an outside read on where it breaks.
Disclaimer: This article is technical and educational commentary. It is not investment advice, financial advice, or a recommendation regarding any security, strategy, or use of leverage. I am not a licensed financial advisor, broker, or investment professional. Nothing here should be construed as a suggestion to trade on margin or to replicate any portfolio or approach described. Margin rules, maintenance requirements and prime brokerage terms vary by jurisdiction, broker and account type, and the figures cited here are illustrative rather than authoritative — consult your own agreements and counsel. Risk monitoring software does not prevent losses, and leverage of the kind discussed can result in the total loss of invested capital and in losses exceeding the amount invested. Any implementation of the concepts described here is the responsibility of the implementer, including compliance with all applicable regulatory, licensing, market data and brokerage obligations.
About the Author
Gal Ratner is the founder and CTO of Inverted Software and WhiteStar Labs, and Chief Architect at Prana Entertainment. He has spent nearly thirty years shipping production software on the Microsoft and .NET stack for clients including Microsoft, Sony, Rockstar Games, 2K Games, Best Buy and Allegiant Air. He was employee number six at Break.com and a finalist for the Los Angeles Business Journal’s CTO of the Year.
His current work centers on production agentic AI — Model Context Protocol servers, the Microsoft Agent Framework, retrieval pipelines, SQL Server 2025 vector search, and the PLogger observability framework — the unglamorous engineering that determines whether an autonomous system can be trusted with anything that matters. He also builds and operates ShopSnap, a zero-transaction-fee e-commerce platform, along with several other production web properties.
He writes about what actually ships, as opposed to what gets announced. He co-hosts Edge Grip Podcast, trains Brazilian jiu-jitsu in Las Vegas, rides motorcycles, and is the author of the novel The Archive of Lost Suns.



