DEV Community

mattleeee
mattleeee

Posted on Originally published at hkcode.dpdns.org

Long-Hold Token Positions: Sizing and Liquidation Protection

Long-term holding is often framed as the opposite of active risk management: you pick an asset, size it, and wait. That framing breaks down for tokens that move 10–20% in a day. A "side position" that was supposed to sit quietly at 15% of the account can become 40% of it after a drawdown elsewhere, and if any leverage is involved, the liquidation price does not care about your holding horizon.

This post walks through the engineering side of a long-hold paper account starting at 100U: how to size the core position, how to compute and monitor liquidation distance for leveraged spot positions, and how to build a hard floor that de-risks without a human in the loop.

The account model

The setup is deliberately minimal:

  • Equity: 100U at start, marked to market every cycle.
  • Core hold: one long-term token position, no leverage. It can lose value, but it cannot be liquidated.
  • Side positions: leveraged longs, allowed only within a small, explicit budget.
  • Risk system: recomputes exposure and liquidation distance on every cycle, alerts early, and force-reduces when thresholds are breached.

The rule "no leverage on the core hold" is the single most important design decision. Leverage converts a volatility problem into a solvency problem, and solvency problems have deadlines. A 30% drawdown in an unlevered position is unpleasant; in a 3x position it is a 90% loss, and at 3.3x it is liquidation.

Position sizing math

The volatility-scaled cap

A fixed percentage cap ("no position above 25% of equity") is a floor, not a sizing method, because it ignores how much the asset actually moves. Scale the cap by realized volatility instead:

import numpy as np

def realized_vol(returns: np.ndarray, window: int = 30) -> float:
    """Daily realized volatility from log returns."""
    r = returns[-window:]
    return float(np.std(r, ddof=1))

def position_cap(equity: float, daily_vol: float,
                 target_daily_risk: float = 0.02,
                 hard_cap: float = 0.25) -> float:
    """
    Notional cap for one position, in quote currency.
    target_daily_risk: fraction of equity you accept as 1-sigma daily PnL.
    hard_cap: absolute share of equity a single position may occupy.
    """
    vol_cap = target_daily_risk / max(daily_vol, 1e-6)
    return equity * min(vol_cap, hard_cap)
Enter fullscreen mode Exit fullscreen mode

With target_daily_risk = 0.02, a token with 8% daily vol gets a cap of 25% of equity (2% / 8% = 0.25), which the hard cap also enforces. A token with 4% daily vol would be allowed up to 50% by the vol rule, but the hard cap cuts it to 25%. The hard cap is the binding constraint for most liquid majors; the vol rule matters most when you hold several positions and need their combined risk to stay bounded.

The leverage budget

Leverage is allowed only on side positions, and only out of a separate budget. Treat it as a loss budget rather than a notional budget:

def max_leveraged_notional(equity: float, leverage: float,
                           maintenance_margin: float = 0.005,
                           liq_buffer: float = 0.50,
                           budget: float = 0.10) -> float:
    """
    Largest leveraged notional such that liquidation sits at least
    `liq_buffer` (fraction of entry) below the current price,
    and total loss at liquidation stays within `budget` of equity.
    """
    # Distance from entry to liquidation, as a fraction of entry price,
    # ignoring fees and funding (add them as a haircut in production).
    liq_distance = 1.0 / leverage - maintenance_margin
    if liq_distance < liq_buffer:
        return 0.0
    # Loss if price falls to liquidation = notional * liq_distance.
    return equity * budget / liq_distance
Enter fullscreen mode Exit fullscreen mode

The check liq_distance < liq_buffer rejects configurations that are liquidatable too close to entry — for example, 50x with 0.5% maintenance margin puts liquidation about 1.5% below entry, which a single hourly candle can reach. The budget term means a full liquidation costs at most 10% of equity, not the whole account.

For a 100U account at 3x, liq_distance ≈ 0.328, so the notional cap is 100 * 0.10 / 0.328 ≈ 30.5U. That is roughly 10U of margin. Small, and intentionally so: leveraged positions on a 100U account are experiments, not core exposure.

Liquidation price for leveraged spot

On a leveraged spot (margin) long, the exchange liquidates when equity in the position falls to the maintenance margin requirement. Working from the maintenance-margin definition:

liq_price = entry * (1 - 1/L + mmr)
Enter fullscreen mode Exit fullscreen mode

where L is leverage and mmr is the maintenance margin rate. Derivation: at price P, position equity is N * (P/entry - 1) + N/L (unrealized PnL plus posted margin, with N the notional). Liquidation occurs when this equals N * mmr * P/entry. Solving for P gives the formula above.

def liquidation_price(entry: float, leverage: float,
                      mmr: float = 0.005) -> float:
    return entry * (1.0 - 1.0 / leverage + mmr)

def distance_to_liq(price: float, entry: float, leverage: float,
                    mmr: float = 0.005) -> float:
    """Fractional distance from current price down to liquidation."""
    liq = liquidation_price(entry, leverage, mmr)
    return (price - liq) / price
Enter fullscreen mode Exit fullscreen mode

Two practical points. First, mmr is tiered by notional on most venues — read it from the exchange's risk-limit table rather than hardcoding 0.5%. Second, funding payments and fees shift the effective liquidation price slightly; a 1–2% haircut on distance_to_liq is a cheap way to stay conservative.

The monitoring loop

The loop recomputes equity, exposure shares, and liquidation distance every cycle, then escalates through three levels: alert, warn, and de-risk.

from dataclasses import dataclass, field

@dataclass
class Position:
    symbol: str
    qty: float
    entry: float
    leverage: float = 1.0
    mmr: float = 0.005
    is_core: bool = False

@dataclass
class RiskConfig:
    max_share: float = 0.25          # max single-position share of equity
    alert_distance: float = 0.50     # alert at 50% distance to liq
    derisk_distance: float = 0.30    # cut at 30% distance to liq
    floor_equity: float = 70.0       # hard floor, in quote currency
    floor_reduce: float = 0.50       # fraction of position cut at the floor

@dataclass
class RiskState:
    alerts: list = field(default_factory=list)

def evaluate(positions: list[Position], prices: dict[str, float],
             cash: float, cfg: RiskConfig, state: RiskState) -> list[dict]:
    equity = cash + sum(p.qty * prices[p.symbol] for p in positions)
    actions = []

    for p in positions:
        price = prices[p.symbol]
        notional = p.qty * price

        # 1. Concentration check (core hold included).
        share = notional / equity if equity > 0 else 1.0
        if share > cfg.max_share:
            actions.append({"symbol": p.symbol, "type": "TRIM",
                            "reason": f"share {share:.1%} > {cfg.max_share:.0%}"})

        # 2. Liquidation distance (leveraged only).
        if p.leverage > 1.0:
            dist = distance_to_liq(price, p.entry, p.leverage, p.mmr)
            if dist < cfg.derisk_distance:
                actions.append({"symbol": p.symbol, "type": "CUT",
                                "reason": f"liq distance {dist:.1%}"})
            elif dist < cfg.alert_distance:
                actions.append({"symbol": p.symbol, "type": "ALERT",
                                "reason": f"liq distance {dist:.1%}",
                                "level": "warn"})

    # 3. Hard equity floor: de-risk regardless of why equity fell.
    if equity < cfg.floor_equity:
        for p in positions:
            if not p.is_core:
                actions.append({"symbol": p.symbol, "type": "CUT",
                                "reason": f"equity floor {equity:.1f}",
                                "fraction": cfg.floor_reduce})
        state.alerts.append(f"FLOOR BREACH: equity={equity:.2f}")

    return actions
Enter fullscreen mode Exit fullscreen mode

A few things this loop does that matter more than the code itself:

  • Equity is marked to market, not cost basis. A position that "hasn't been sold" still changes the account's risk profile every time the price moves.
  • The concentration check includes the core hold. If the token rallies and the core position grows past the cap, the system trims it. This is the opposite of instinct — you trim winners — but it keeps the account from becoming a single bet.
  • The floor is independent of position logic. It triggers on equity alone, so it catches correlated drawdowns across positions, funding bleed, and anything else the per-position checks miss.

Why "buy and hold" still needs an active risk system

An unlevered long-hold has no liquidation price, but it has three live risks that a passive posture does not address.

Concentration drift. A 25% position that doubles becomes 40% of a rebalanced account and more than 40% of one whose cash has been spent. Token volatility compounds this: a 3x rally in one holding can make the rest of the book irrelevant. The cap has to be re-evaluated on every mark, not set once at entry.

Volatility regime shifts. Sizing based on trailing 30-day vol is fine until vol triples. A position sized at 2% daily risk under 4% vol becomes 6% daily risk under 12% vol with no trade made. The loop should re-run position_cap on a schedule and trim when the cap falls below current notional.

Operational failure. The most common way a long-hold account dies is not a bad thesis; it is the holder not looking. A floor that cuts exposure at, say, 70% of starting equity converts a potential 100% loss into a bounded one, and it works on a timer rather than on attention.

None of this requires predicting price. It requires knowing, at every moment, what fraction of the account each position occupies and how far the leveraged ones are from liquidation — and having code that acts on those numbers without waiting for a human.

More notes like this ship every week on this site.

Top comments (0)