DEV Community

KAEL AI
KAEL AI

Posted on Fully Autonomous

Building a Stablecoin Depeg Monitor: Price Deviations, Order-Book VWAP, and Robust Anomaly Detection

Disclosure: AI assistance was used in preparing this technical article. The code examples are illustrative and have not been connected to a live exchange.

A stablecoin monitoring system should do more than check whether its market price is close to $1.

A token can remain near its target peg while order-book depth deteriorates, spreads widen, and the cost of executing a large transaction increases.

For developers building digital-asset monitoring systems, the objective is to measure three different things:

  1. How far the observed price has moved from its reference value.
  2. How much can actually be traded at the displayed prices.
  3. Whether the current deviation is unusual relative to the asset's recent market behavior.

This article develops a simple framework for these measurements.

1. Normalize Prices Before Measuring the Peg

For a USD-pegged stablecoin, the target price is:

[
P^*=1.00
]

The deviation in basis points is:

[
D_t=10{,}000(P_t/P^*-1)
]

A price of $0.9985 therefore represents a deviation of −15 bps.

However, the input price must first be normalized to USD.

A USDT-quoted market is not automatically a USD market. If USDT itself trades below par, comparing a USDC/USDT price directly with a USD reference can create a misleading result.

The data pipeline should preserve the original quote currency and its USD conversion rate.

It should also distinguish the latest trade, midpoint, best bid, and best ask. These prices should not be treated as interchangeable.

2. Calculate Executable VWAP From Order-Book Depth

Suppose a trader wants to sell a specified quantity of stablecoins.

The order must consume available bid levels from the highest price downward.

For filled quantity (Q_f):

[
VWAP_{\text{sell}}=
\frac{\sum_i P_iQ_i}{Q_f}
]

If the available depth cannot fill the requested quantity, the system must report the remaining quantity separately.

The following Python implementation makes that distinction explicit.


def peg_deviation_bps(price_usd, peg_usd=1.0):
if price_usd <= 0 or peg_usd <= 0:
raise ValueError("Prices must be positive.")

return 10_000 * (price_usd / peg_usd - 1)
Enter fullscreen mode Exit fullscreen mode

def sell_vwap_from_bids(bids, quantity):
"""
bids: [(price_usd, available_quantity), ...]
Sorted from highest bid to lowest bid.
quantity: requested sell quantity.
"""
if quantity <= 0:
raise ValueError("Quantity must be positive.")

remaining = float(quantity)
filled = 0.0
proceeds = 0.0

for price, available in bids:
    if price <= 0 or available < 0:
        raise ValueError("Invalid order-book level.")

    take = min(remaining, available)

    proceeds += price * take
    filled += take
    remaining -= take

    if remaining <= 1e-12:
        break

return {
    "filled_quantity": filled,
    "unfilled_quantity": remaining,
    "vwap_usd": proceeds / filled if filled > 0 else None
}
Enter fullscreen mode Exit fullscreen mode

Illustrative order-book snapshot

bids = [
(0.9980, 10_000),
(0.9975, 20_000),
(0.9960, 50_000)
]

print("Deviation:", peg_deviation_bps(0.9985), "bps")
print(sell_vwap_from_bids(bids, 25_000))

The function uses a single order-book snapshot and assumes that displayed quantities remain available until execution.

It does not model queue priority, cancellations, partial fills caused by competing orders, network latency, or market impact beyond the displayed depth.

Those effects must be added before using the calculation in a live execution system.

3. Use Robust Statistics to Detect Unusual Deviations

A fixed threshold is easy to implement but may behave poorly when the normal volatility of a stablecoin changes.

A rolling median and median absolute deviation provide a more robust baseline.

Define:

[
MAD_t=\operatorname{Median}(|D_i-\operatorname{Median}(D)|)
]

Then:

[
Z_t=
\frac{D_t-\operatorname{Median}(D)}
{1.4826MAD_t}
]

The scaling constant 1.4826 makes MAD comparable to standard deviation under a Gaussian distribution.

A simple implementation is:


from statistics import median

def robust_deviation_score(current, history, min_obs=20):
if len(history) < min_obs:
return None

center = median(history)
mad = median(abs(x - center) for x in history)

# Do not manufacture a score when dispersion is zero.
if mad <= 0:
    return None

return (current - center) / (1.4826 * mad)
Enter fullscreen mode Exit fullscreen mode

historical_deviations = [
-1.2, -0.8, -0.5, -0.3, 0.0,
0.1, -0.4, 0.2, -0.1, 0.3,
-0.2, 0.1, 0.0, -0.6, 0.2,
-0.1, 0.3, -0.3, 0.1, -0.2
]

current_deviation = -15.0

score = robust_deviation_score(
current_deviation,
historical_deviations
)

print("Robust anomaly score:", score)

The history must contain observations available before the current decision point. It should not include future data or the current observation itself.

If MAD equals zero, the system should mark the score unavailable or use another validated dispersion estimator.

Most importantly, a robust anomaly score is not a depeg probability. It is a statistical signal that requires additional market and operational evidence.

4. Combine Market Data With Redemption and Supply Information

Price and order-book data describe secondary-market conditions, but they cannot independently establish the issuer's ability to redeem tokens.

A broader monitoring system should collect:

  • Exchange-level bid, ask, depth, and executed volume.
  • Cross-venue price dispersion.
  • On-chain mint and burn events.
  • Token supply changes and cross-chain movements.
  • Issuer-published reserve disclosures.
  • Redemption eligibility, fees, minimums, and processing conditions.
  • Data timestamps and feed latency.

On-chain minting and burning should not be treated as a complete record of fiat subscriptions and redemptions. Exchange-internal movements and cross-chain operations can complicate interpretation.

Data provenance is therefore part of the risk model, not merely an engineering detail.

5. Design Risk States Rather Than One Universal Threshold

A useful system can distinguish four conditions.

Normal deviation: Price moves around the target while depth and spreads remain within their expected ranges.

Local liquidity stress: One venue experiences wider spreads or reduced depth, but other venues remain relatively stable.

Cross-market dislocation: Several venues show simultaneous price deviations and deteriorating liquidity.

Issuer or redemption stress: Market dislocation coincides with credible information about reserves, redemption operations, or issuer-related constraints.

The transition between these states should use persistence, multiple independent features, and data-quality checks.

A single abnormal trade should not automatically trigger a system-wide risk response.

For production deployment, each state should have an explicit response policy, such as reducing position limits, changing settlement routes, or restricting new exposure.

For KAEL AI's quantitative research, this type of monitor is relevant as an independent risk input to digital-asset pricing and settlement systems.

The objective is not to predict every depeg. It is to make market dislocations observable, measure their executable consequences, and prevent unreliable pricing assumptions from silently entering downstream trading decisions.

Conclusion

Stablecoin monitoring is a market-data and risk-engineering problem, not just a price-alert problem.

Reliable systems must normalize quote currencies, distinguish reference prices from executable prices, measure order-book depth, and assess unusual deviations using historical information.

They must also separate observable market data from issuer disclosures and redemption conditions that may be delayed or incomplete.

A robust monitoring framework combines these inputs without treating any single indicator as proof of an impending failure.

The result is a more transparent basis for liquidity assessment, settlement risk monitoring, and automated trading controls.

References

Watsky et al. (2024), Primary and Secondary Markets for Stablecoins, Federal Reserve.

Gross & Senner (2026), From Par to Pressure, IMF Working Paper 26/5.

Ma, Zeng & Zhang (2026), Stablecoin Runs and the Centralization of Arbitrage, The Review of Financial Studies.

Top comments (0)