---
title: "1.2.6 Crypto: spot, perpetuals and the funding rate"
description: "Spot, futures and perpetuals in crypto: how funding works, what a leveraged long costs, where it gets liquidated and what custody risk it carries."
url: "https://pythonparatrading.com/en/python-trading-course/level-1/crypto-spot-perpetuals-and-funding/"
lang: "en"
image: "https://pythonparatrading.com/og/en/python-trading-course/level-1/crypto-spot-perpetuals-and-funding.png"
---

# 1.2.6 · Crypto: spot, perpetuals, funding and custody

> In crypto the most traded product is not spot but a future that never expires, tied to its price by a payment every eight hours. The lesson takes it apart with two years of hourly data for a fictitious token, XSN: the perpetual's premium, the funding it receives or pays, the liquidation price of a leveraged long and the risks of leaving funds on an exchange.

- Course: [Level 1: Financial data, markets and analysis](https://pythonparatrading.com/en/python-trading-course/level-1/)
- Module: 1.2 · Asset classes
- Duration: 60 min
- Prerequisites: [1.1.5 · Costs, settlement, leverage and margin](https://pythonparatrading.com/en/python-trading-course/level-1/trading-costs-settlement-leverage-and-margin/), [1.2.3 · Futures: specifications, margin, roll and contango](https://pythonparatrading.com/en/python-trading-course/level-1/futures-contract-specs-margin-and-roll/)

## By the end of this lesson

- Distinguish spot, dated future and perpetual, and the role of the composite index in funding and liquidation.
- Rebuild a perpetual's funding rate from its premium over the index with pandas.
- Compute how much funding a leveraged long pays in a year and at what price a position with isolated margin is liquidated.
- Explain the custody differences between a centralized exchange (CEX) and a decentralized one (DEX), and what a stablecoin is and what risks it carries.

## Three ways to get exposure to a token

In crypto markets three products on the same asset coexist, and the data from each tell different things:

| Product | What you buy | Expiry | How it is tied to spot | Leverage |
|---|---|---|---|---|
| Spot | The token, with delivery | None | It is spot | No (except exchange margin) |
| Dated future | A contract that settles on a date | Quarterly, monthly… | Converges at expiry, as in lesson 1.2.3 | Yes, with margin |
| Perpetual | A contract with no expiry date | None | Periodic **funding** payments | Yes, with margin |

The **perpetual** is crypto's signature product. It is a future that never expires: there is no convergence at expiry
to tie it to the token's price, so something else ties it, a periodic payment between longs and shorts. If the
perpetual trades above the reference price, longs pay shorts; if it trades below, the other way around. The payment
makes the position of the side pushing the price out of line more expensive and rewards the side bringing it back.

The reference price is not the spot price of a particular exchange but an **index** made up of the spot prices of
several exchanges. That index is used to compute funding and, above all, to decide when a position is liquidated: if
it depended on the last price of a single order book, sweeping it for an instant would be enough to liquidate other
people's positions.

```mermaid
flowchart TB
  P[Positive premium] --> F[Positive funding]
  F --> L[Longs pay]
  L --> A[Arbitrage]
  A --> V[Sells perpetual]
  A --> C[Buys spot]
  V --> I[Premium closes]
  C --> I
```

The diagram is the return mechanism: when the premium rises, an arbitrageur sells the perpetual and buys the token (a
position with no directional risk) and collects the funding. Their sale pushes the perpetual down and their purchase
pushes spot up. This strategy is called *cash and carry* or *basis trade*.

## Two years of XSN, hour by hour

The data are for **XSN**, a fictitious token, every hour of 2024 and 2025: the `spot` price on one exchange, the linear
`perpetuo` (perpetual, settled in USD) and the composite `indice` (index) the exchange uses for funding and
liquidation. They are synthetic, with crypto-like volatility (around 75% a year), fat tails and a sharp drop in early
October 2025.

```python
import numpy as np
import pandas as pd

xsn = pd.read_parquet("xsn_1h.parquet").set_index("ts")
print(len(xsn), "hours;", xsn.index.min(), "→", xsn.index.max())
horas_por_dia = xsn.groupby(xsn.index.date).size()
print("hours per day:", horas_por_dia.unique())
xsn.head(3)
```
```output
17544 hours; 2024-01-01 00:00:00+00:00 → 2025-12-31 23:00:00+00:00
hours per day: [24]
                              spot  perpetuo   indice
ts
2024-01-01 00:00:00+00:00  24.0855   24.0727  24.0727
2024-01-01 01:00:00+00:00  24.0662   24.0609  24.0635
2024-01-01 02:00:00+00:00  24.0721   24.0629  24.0622
```

24 hours on each of the 731 days, weekends included: in crypto there are no sessions, holidays or auctions, and the
timestamps come in UTC. The first thing you lose when moving from stocks to crypto is the calendar (lesson 1.1.2); the
second, the idea of a “closing price”, which here is a convention (often the daily candle that starts at 00:00 UTC).

The three prices almost match. The relative difference between the perpetual and the index is the perpetual's
**premium**; that of an exchange's spot over the index, the **basis** of that exchange. Measured in basis points
(0.01%):

```python
xsn["prima_pb"] = 1e4 * (xsn["perpetuo"] / xsn["indice"] - 1)
xsn["base_spot_pb"] = 1e4 * (xsn["spot"] / xsn["indice"] - 1)
xsn[["prima_pb", "base_spot_pb"]].describe().round(2)
```
```output
       prima_pb  base_spot_pb
count  17544.00      17544.00
mean       1.01         -0.07
std        5.54          4.00
min      -17.98        -15.62
25%       -2.72         -2.77
50%        0.99         -0.07
75%        4.75          2.57
max       19.64         14.80
```

The exchange's spot moves around the index with an almost zero mean and a standard deviation of 4 basis points: it
tracks it closely. The perpetual's premium is positive on average, one basis point, and swings more, with extremes of
about ±20 basis points. What does it depend on? On the pressure from leveraged traders: when the market rises, longs
are opened on the perpetual and its price runs ahead of spot; when it falls, the reverse.

```python
xsn["ret_30d"] = xsn["indice"].pct_change(30 * 24)
tramo = pd.qcut(xsn["ret_30d"], 5, labels=["strong drop", "drop",
                                           "flat", "rise",
                                           "strong rise"])
xsn.groupby(tramo, observed=True)["prima_pb"].mean().round(2)
```
```output
ret_30d
strong drop   -1.54
drop          -1.19
flat           1.85
rise           2.09
strong rise    3.27
Name: prima_pb, dtype: float64
```

In the fifth of hours with the most bullish 30-day trend, the average premium is 3.27 basis points; in the most bearish
fifth, −1.54. Hour by hour the relation is weak, but over a horizon of weeks it is clear: the perpetual captures the
sentiment of leveraged traders, and funding makes whoever is pushing pay for it.

## Funding, payment by payment

XSN funding settles every eight hours, at 00:00, 08:00 and 16:00 UTC, like Binance's standard perpetual, whose formula
it follows[^1]. Each period's rate is computed from the average premium over the previous eight hours, $P$, plus an
interest term of 0.01% per period clipped to ±0.05%:

$$
F = P + \operatorname{clamp}(0.01\,\% - P,\ -0.05\,\%,\ 0.05\,\%)
$$

with an additional cap of ±0.75% per period in this data. If $F$ is positive, each long pays $F$ times the **notional
value** of its position (quantity times the index price) to the shorts; if it is negative, it receives.

[^1]: Binance, “Introduction to Binance Futures Funding Rates”: default interval of eight hours at 00:00, 08:00 and
16:00 UTC, an interest rate of 0.01% per period and the formula with the ±0.05% `clamp` (link in the resources).
Other exchanges use different intervals and caps.

```python
funding = pd.read_csv("xsn_funding_8h.csv",
                      parse_dates=["ts"]).set_index("ts")
tasa = funding["tasa_funding"]
print(len(tasa), "8 h periods")
print(f"Exactly 0.01%: {(tasa.round(6) == 0.0001).mean():.1%}")
print(f"Negative (shorts pay): {(tasa < 0).mean():.1%}")
print(f"Maximum: {tasa.max():.4%}  minimum: {tasa.min():.4%}")
por_año = tasa.groupby(tasa.index.year).sum()
print("Sum by year:", (100 * por_año).round(2).to_dict())
```
```output
2192 8 h periods
Exactly 0.01%: 64.2%
Negative (shorts pay): 12.9%
Maximum: 0.1240%  minimum: -0.1104%
Sum by year: {2024: 11.4, 2025: 10.67}
```

In 64% of periods funding is exactly 0.01%: as long as the average premium is between −0.04% and +0.06%, the `clamp`
does not clip and $P + (0.01\,\% - P)$ is exactly 0.01%. That base rate, three times a day, amounts to 0.03% a day and
almost 11% a year: it is what a long pays in a calm market. In periods of euphoria funding is multiplied by more than
ten, and in 13% of periods it is negative and longs receive.

The rule can be checked: each published rate can be rebuilt from the hourly premium. It is the kind of verification
worth doing with real data before using it in a backtest, because the exact moment of calculation (which hours go into
the average) changes the result.

```python
prima = xsn["perpetuo"] / xsn["indice"] - 1
# average of the PREVIOUS 8 hours: [t-8h, t), labeled at t
p_media = prima.resample("8h", closed="left", label="left").mean()
p_media.index = p_media.index + pd.Timedelta("8h")
calc = (p_media + (0.0001 - p_media).clip(-0.0005, 0.0005)
        ).clip(-0.0075, 0.0075)
comp = pd.concat([tasa, calc.rename("calculada")], axis=1,
                 join="inner")
dif = (comp["tasa_funding"] - comp["calculada"]).abs()
print(f"{len(comp)} periods; maximum difference: {dif.max():.1e}")
```
```output
2192 periods; maximum difference: 5.0e-07
```

All 2,192 rates match the reconstruction except for the file's rounding to six decimals. If the wrong window is used
(for example, the average of the eight hours that **follow** the timestamp) the reconstruction no longer matches, and a
backtest that used that average to anticipate funding would be looking into the future.

*Fig. — Average premium of the XSN perpetual over the index in each 8-hour period (top) and the resulting funding (bottom), September to November 2025, in basis points.* Two panels sharing the time axis. Top, the average premium moves between -10.94 and 14.84 basis points, with two lines marking the −4 to +6 band where funding is not clamped. Bottom, funding stays at 1 basis point most of the time and only moves when the premium leaves the band; the minimum, highlighted, is -5.94 basis points.

The figure shows the relation in the three months around the October 2025 crash: at the top, the average premium of
each eight-hour period; at the bottom, the funding that comes out of it. The two dotted lines in the top panel mark the
band from −4 to +6 basis points in which the `clamp` does not clip: as long as the average premium is inside it,
funding stays pinned at 1 basis point. When it leaves, funding follows it: up to 9.84 basis points on September 11, in
the middle of the rally, and below zero several times after the October crash, with a minimum of −5.94 on October 24.

## What a leveraged long costs

Funding is paid on the notional, not on the margin. With leverage, a rate that looks small becomes a large part of the
capital committed. A 10,000 USD long in XSN opened on the first day of 2025 and held all year, with the same quantity
of tokens:

```python
t25 = tasa.loc["2025"]
precio_funding = xsn["indice"].reindex(t25.index)
cantidad = 10_000 / xsn["indice"].loc["2025-01-01 00:00"]
pagos = cantidad * precio_funding * t25  # > 0: the long pays
acumulado = pagos.cumsum()
print(f"Quantity: {cantidad:.2f} XSN; payments: {len(pagos)}")
print(f"Funding paid in 2025: {acumulado.iloc[-1]:,.2f} USD")
for apal in (1, 3, 5, 10):
    margen = 10_000 / apal
    print(f"  {apal:>2}x: margin {margen:>8,.0f} USD, funding = "
          f"{acumulado.iloc[-1] / margen:.1%} of margin")
```
```output
Quantity: 158.81 XSN; payments: 1095
Funding paid in 2025: 1,060.01 USD
   1x: margin   10,000 USD, funding = 10.6% of margin
   3x: margin    3,333 USD, funding = 31.8% of margin
   5x: margin    2,000 USD, funding = 53.0% of margin
  10x: margin    1,000 USD, funding = 106.0% of margin
```

*Fig. — Cumulative funding paid in 2025 by a long of 10,000 USD notional in the XSN perpetual at 3x leverage, as a percentage of its margin (3,333 USD).* Line of the cumulative funding in 2025: it barely moves from January to March, with negative stretches in which the long gets paid; it climbs fast from April to September, with the market rising, and flattens in the last quarter to 31.8% of the margin on 31 December, highlighted. A dashed straight line marks what the 0.01% base rate every 8 hours alone would cost, which ends at a similar value.

Funding is not paid at a constant pace: from January to March, with XSN falling from 63 to 39, the account barely
moves and even receives; from April to September, with XSN rising, it shoots up. At the end of the year, the total ends
up close to what the base rate alone would have cost (the dashed line). Without leverage, a year of funding costs 10.6%
of the amount invested: more than a bank loan. At 3x, a third of the margin; at 10x, more than the entire margin. For
comparison, buying the token on spot pays no funding (although custody and tied-up capital do have a cost). That is
why leveraged longs on perpetuals are a poor way to hold a position for months, and why *cash and carry* (buying spot
and selling the perpetual, collecting funding) is one of the most popular strategies in the industry, with its own
risk: the failure of the exchange holding the short leg or the liquidation of that leg in a violent rally.

<aside class="callout" data-kind="aviso">

In a perpetuals backtest, ignoring funding is like ignoring dividends and interest in stocks: the result of a trend
strategy that holds longs in bull markets can change sign. The correct calculation uses the published rates at their
exact times and the position's notional at each payment.

</aside>

## Where a position gets liquidated

A perpetual is traded on margin: the exchange requires an **initial margin** (1/L of the notional with leverage L) and
a **maintenance margin** (a smaller percentage, $m$). If losses push the margin below the maintenance level, the
exchange's risk engine closes the position: **liquidation**. With isolated margin (only that position's margin is at
stake), without fees or funding, a long opened at $P_0$ is liquidated when the index reaches:

$$
P_{liq} = P_0 \left(1 - \frac{1}{L} + m\right)
$$

and a short, at $P_0 (1 + 1/L - m)$. The formula is a simplification: each exchange applies its own margin tiers by
position size, liquidation fees and an insurance fund. But it gives the order of magnitude: at 10x, a drop of a little
less than 10% wipes out the whole margin.

```python
def precio_liquidacion(entrada, apal, mant=0.005, lado="largo"):
    """Isolated margin, without fees or funding."""
    if lado == "largo":
        return entrada * (1 - 1 / apal + mant)
    return entrada * (1 + 1 / apal - mant)

camino = xsn.loc["2025-10-05":"2025-10-15", "indice"]
entrada = camino.iloc[0]
print(f"Entry: {entrada:.4f} on {camino.index[0]:%Y-%m-%d %H:%M} UTC")
filas = []
for apal in (2, 3, 5, 7, 10, 20):
    p_liq = precio_liquidacion(entrada, apal)
    tocado = camino[camino <= p_liq]
    filas.append({"apal": apal, "p_liq": round(p_liq, 2),
                  "caida_pct": round(100 * (p_liq / entrada - 1), 1),
                  "liquidado": (tocado.index[0].strftime("%m-%d %H:%M")
                                if len(tocado) else "no")})
pd.DataFrame(filas).set_index("apal")
```
```output
Entry: 85.4608 on 2025-10-05 00:00 UTC
      p_liq  caida_pct    liquidado
apal
2     43.16      -49.5           no
3     57.40      -32.8           no
5     68.80      -19.5           no
7     73.68      -13.8  10-10 22:00
10    77.34       -9.5  10-07 10:00
20    81.62       -4.5  10-05 17:00
```

The figure at the top draws the same episode: the XSN index from October 1 to 15, 2025 and the liquidation price at
each leverage for a long opened on the 5th at 00:00. The index falls almost 15% in six days, to 72.86 on October 11.
The 20x long lasts 17 hours; the 10x, a little over two days; the 7x, almost six. The 5x, 3x and 2x survive, and by
October 13 the index has already recovered a good part of the drop. The lesson is the usual one about leverage
(lessons 0.1.2 and 1.1.5), with a twist specific to crypto: the market never closes, so liquidation can arrive on a
Sunday at four in the morning.

```python
salida = camino.iloc[-1]
for apal in (2, 3, 5):
    margen = 1 / apal  # per unit of notional
    pnl = salida / entrada - 1
    print(f"{apal}x: margin {pnl / margen:+.1%} "
          f"(index {pnl:+.1%})")
```
```output
2x: margin -14.9% (index -7.4%)
3x: margin -22.3% (index -7.4%)
5x: margin -37.1% (index -7.4%)
```

The positions that survive end the period with a loss equal to their leverage times the index's drop. And those that
were liquidated recover nothing even if the price comes back: liquidation locks in the loss at the worst moment. In a
backtest, a leveraged crypto strategy has to simulate liquidation against the index hour by hour (or minute by
minute); using only daily closes hides the intraday lows that liquidate positions.

## Dated futures and basis

Crypto exchanges also list **dated futures** (monthly or quarterly), which work like those in lesson 1.2.3: they pay no
funding and their price converges to the index on the expiry date. The difference from spot, the **basis**, reflects
the funding the market expects to pay until that date. Annualized:

$$
\text{annualized basis} = \left(\frac{F}{S}\right)^{365/d} - 1
$$

with $d$ the days to expiry. A quarterly XSN future pricing in the average 2025 funding would trade at an annualized
basis of around 11%. Buying spot and selling that future locks in the basis when the trade is opened, regardless of how
funding evolves: it is *cash and carry* with a date.

```python
funding_anual = t25.mean() * 3 * 365
S0 = xsn.loc["2025-12-31 23:00", "indice"]
d = 90
F_teorico = S0 * (1 + funding_anual) ** (d / 365)
print(f"Average 2025 funding, annualized: {funding_anual:.2%}")
print(f"Spot {S0:.2f} → {d}-day future {F_teorico:.2f} "
      f"(basis {100 * (F_teorico / S0 - 1):.2f}% over the period)")
```
```output
Average 2025 funding, annualized: 10.67%
Spot 48.26 → 90-day future 49.49 (basis 2.53% over the period)
```

## Custody: CEX, DEX and stablecoins

In stocks, the securities sit at a central depository and the broker registers them in the client's name (lesson
1.1.1). In crypto, custody depends on where you trade:

```mermaid
flowchart TB
  U[User] -- deposits --> X[CEX exchange]
  X --> CX[CEX custody]
  X --> LI[Internal order book]
  U -- signs --> W[Own wallet]
  W --> SC[DEX contract]
  SC --> PL[Liquidity pool]
```

- **Centralized exchange (CEX).** The user deposits their tokens or dollars and the exchange holds them in its own
  wallets. Trades are matched in an internal order book, as on a stock exchange, and are only recorded in its books:
  they do not go on-chain. It is fast and cheap, but the user's balance is a claim against the exchange. If the
  exchange goes bankrupt, is hacked or freezes withdrawals, the user is just another creditor.
- **Decentralized exchange (DEX).** The user trades from their own wallet, signing each transaction, against a smart
  contract. In the most common ones there is no order book but a **liquidity pool** that sets the price with a formula.
  There is no custodial intermediary, but there are other risks: bugs in the contract, network fees, third-party trades
  that front-run your own and, above all, custody of the keys: whoever loses them loses the funds.

A **stablecoin** is a token designed to keep a fixed price against a currency, almost always the dollar. The most used
are backed by reserves (cash, Treasury bills) held by their issuer, and they are the “currency” of almost all crypto
pairs: XSN/USDT or XSN/USDC, not XSN/USD. Their risk is that of their issuer and its reserves: if the market doubts it
can redeem, the stablecoin trades below 1 (it loses its peg, a *depeg*), and every price quoted in it is distorted.

<aside class="callout" data-kind="nota">

In the EU, the Markets in Crypto-Assets Regulation (MiCA) entered into force in June 2023 and has applied in full since
December 30, 2024. It regulates crypto-asset service providers (CASPs) and stablecoin issuers (asset-referenced tokens
and e-money tokens). Providers that were already operating under national law can continue to do so, depending on the
country, until July 1, 2026 or until they obtain or are refused authorization. ESMA publishes a register of authorized
providers and another of entities operating without authorization. The regulatory and tax details are in lessons
3.7.5, 7.4.4 and 7.4.6.

</aside>

## Crypto data: what to watch for

- **Each exchange has its own price.** XSN's spot on one exchange deviates from the index by a few basis points on
  average, and much more at times of stress. A backtest with one exchange's prices and execution on another mixes two
  slightly different assets.
- **Mark price, index and last price.** For funding and liquidation what counts is the index or the *mark price*, not
  the perpetual's last price. Many APIs return the last price by default.
- **24/7 and UTC.** Daily candles at 00:00 UTC, weekends with little liquidity and funding payments at fixed times. A
  resample in the local time zone shifts everything (lesson 0.4.4).
- **Reported volume.** Some exchanges inflate volume with trades against themselves. To compare liquidity, order book
  depth and the bid-ask spread say more than volume (lessons 1.1.3 and 1.3.5).
- **Symbols and contracts.** In ccxt, spot is `XSN/USDT` and the linear perpetual `XSN/USDT:USDT`; an inverse perpetual
  (settled in the token itself) has a different P&L formula. You have to know which one you are downloading.

With ccxt, the same API works for almost any exchange. This code downloads candles and the funding history of a real
perpetual; it is not run here because it needs a network connection (downloading with pagination and retries is
lesson 1.4.1):

```python skip
import ccxt

ex = ccxt.binanceusdm()          # USDT-margined futures
simbolo = "BTC/USDT:USDT"        # linear perpetual
velas = ex.fetch_ohlcv(simbolo, timeframe="1h", limit=500)
historial = ex.fetch_funding_rate_history(simbolo, limit=500)
funding_real = pd.DataFrame(historial)[["datetime",
                                        "fundingRate"]]
```

`fetch_ohlcv` returns a list of candles `[ms, open, high, low, close, volume]` (the same format as
`xsn_ccxt_ohlcv.json`, the example in the level's data) and `fetch_funding_rate_history`, a list of dictionaries with
the timestamp and the rate of each period.

## Exercises

1. Compute the result of a *cash and carry* with XSN in 2025: buy 10,000 USD of spot on January 1 and sell the same
   quantity of tokens on the perpetual, collecting the funding. How much does the position make from funding and how
   much from price? (Ignore fees and assume both legs are closed on December 31 at 23:00.)

**Solution.**

```python
ini, fin = "2025-01-01 00:00", "2025-12-31 23:00"
spot_pnl = cantidad * (xsn.loc[fin, "spot"] - xsn.loc[ini, "spot"])
perp_pnl = -cantidad * (xsn.loc[fin, "perpetuo"]
                        - xsn.loc[ini, "perpetuo"])
cobrado = pagos.sum()  # the short receives what the longs pay
print(f"Price, spot: {spot_pnl:+,.2f}  perpetual: {perp_pnl:+,.2f}")
print(f"Funding received: {cobrado:+,.2f} USD")
total = spot_pnl + perp_pnl + cobrado
print(f"Total: {total:+,.2f} USD ({total / 10_000:+.2%})")
```
```output
Price, spot: -2,333.66  perpetual: +2,337.33
Funding received: +1,060.01 USD
Total: +1,063.68 USD (+10.64%)
```

The two price legs almost cancel out: −2,333.66 USD on spot and +2,337.33 on the perpetual, a net 3.67 USD that comes
from the small difference between the two prices at the open and at the close. Of the result, +1,063.68 USD (10.64%),
almost all is funding received. It is a return without directional risk, but not without risk: the capital sits on an
exchange (counterparty risk) and the short leg can be liquidated in a sharp rally if enough margin is not maintained.

2. Repeat the liquidation table for **shorts** opened at 00:00 on October 11, 2025, near the low of the drop, and check
   which ones are liquidated before October 15.

**Solution.**

```python
tramo = xsn.loc["2025-10-11":"2025-10-15", "indice"]
p0 = tramo.iloc[0]
print(f"Short entry: {p0:.4f}")
for apal in (3, 5, 10, 20):
    p_liq = precio_liquidacion(p0, apal, lado="corto")
    toca = tramo[tramo >= p_liq]
    cuando = (toca.index[0].strftime("%m-%d %H:%M") if len(toca)
              else "no")
    print(f"{apal:>2}x: liquidation at {p_liq:.2f} → {cuando}")
```
```output
Short entry: 72.8819
 3x: liquidation at 96.81 → no
 5x: liquidation at 87.09 → 10-13 12:00
10x: liquidation at 79.81 → 10-12 02:00
20x: liquidation at 76.16 → 10-11 16:00
```

A short opened after the drop suffers the rebound: the index rises from 72.88 to above 87 in a little over two days,
and shorts at 5x or more are liquidated on the way up; the 20x, 16 hours after opening. Liquidation risk is
symmetric: crypto volatility punishes leverage in both directions.

3. A friend keeps their stablecoins on a CEX because “a stablecoin can't go down”. List the risks they are taking.

**Solution.**

Two layers of risk. The stablecoin's: its price depends on the issuer having sufficient, liquid reserves and being able
to redeem them; if the market doubts it, it loses its peg, and in the EU it is worth checking whether the issuer is
authorized under MiCA. The exchange's: the balance is a claim against the CEX, which can go bankrupt, be hacked or
freeze withdrawals; and if the exchange is not authorized to operate in their country, the protection is weaker.
Spreading holdings across issuers and exchanges, or keeping them in your own wallet (with the risk of losing the keys),
reduces the risk, but does not eliminate it.

## Self-assessment

1. A perpetual's funding rate is +0.03% for an eight-hour period. What happens at settlement?

   - A. Shorts pay longs 0.03% of their position
   - B. Longs pay shorts 0.03% of the notional value of their position
   - C. The exchange charges everyone 0.03%
   - D. Nothing: funding is only applied when the position is closed

   *Answer B: Longs pay shorts 0.03% of the notional value of their position.* Positive funding means the perpetual trades above the index and longs pay shorts, in proportion to the position's notional value, not its margin. The payment goes from one side to the other; the exchange only intermediates it.

2. Why is XSN's funding exactly 0.01% in 64% of periods?

   - A. Because the rule adds a `clamp(0.01% − P, ±0.05%)` term to the premium: as long as the average premium is between −0.04% and +0.06%, the result is exactly 0.01%
   - B. Because the exchange sets it by hand
   - C. Because the perpetual's premium is always 0.01%
   - D. By chance

   *Answer A: Because the rule adds a `clamp(0.01% − P, ±0.05%)` term to the premium: as long as the average premium is between −0.04% and +0.06%, the result is exactly 0.01%.* With `P` between −0.04% and +0.06%, the term `clamp(0.01% − P, …)` equals `0.01% − P` without clipping, and `P + (0.01% − P) = 0.01%`. Only when the premium leaves that band does funding move away from the base rate.

3. A 10x long on a perpetual, with isolated margin and a 0.5% maintenance margin, enters at 100. Roughly where is it liquidated?

   - A. At 90
   - B. At 99.5
   - C. At 90.5
   - D. At 50

   *Answer C: At 90.5.* Liquidation comes when the loss leaves the margin at the maintenance level: `100 × (1 − 1/10 + 0.005) = 90.5`. A 9.5% drop wipes out the margin of a 10x position; with fees and the insurance fund, somewhat earlier.

4. What is the custody difference between a CEX and a DEX?

   - A. None: in both the user controls their keys
   - B. In a DEX the exchange holds the funds in a clearing house
   - C. In a CEX trades settle on-chain one by one
   - D. In a CEX the exchange holds the funds and the user has a balance against it; in a DEX the user trades from their own wallet against a smart contract

   *Answer D: In a CEX the exchange holds the funds and the user has a balance against it; in a DEX the user trades from their own wallet against a smart contract.* Depositing on a CEX means lending the assets to the exchange: what the user sees is an entry in its internal ledger. If the exchange goes bankrupt or freezes withdrawals, that balance is a claim against it. In a DEX there is no custodial intermediary, but the risk shifts to the contract and to managing your own keys.

5. Why is the index an exchange uses for funding and liquidation a composite price from several markets?

   - A. To make it more volatile
   - B. So that an isolated trade or a thin order book in a single market does not trigger liquidations or extreme funding
   - C. Because MiCA requires it
   - D. Because spot does not exist in crypto

   *Answer B: So that an isolated trade or a thin order book in a single market does not trigger liquidations or extreme funding.* If liquidation depended on the perpetual's own last price, sweeping its order book for an instant would be enough to liquidate other people's positions. An index from several exchanges is harder to move. That is why, in a backtest, liquidation is checked against the index (or the mark price), not against the last price.

## Key points

- Spot is buying the token; a dated future converges to spot on a date; a perpetual never expires and stays close to the index through periodic funding payments.
- Positive funding: the perpetual trades at a premium and longs pay shorts. It is computed on the notional, so with leverage it weighs heavily on the margin.
- In XSN, 2025 funding adds up to 10.7% of the notional: a 3x long held all year pays close to a third of its margin in funding.
- With isolated margin, a long at L times leverage is liquidated after a drop of a little less than 1/L. In the October 2025 crash, the 7x to 20x longs opened on the 5th were liquidated; those at 5x and below were not.
- In a CEX the exchange holds the funds; in a DEX the user holds them and the risk shifts to the smart contract and to their keys. A stablecoin is only worth what its reserves and its issuer are worth.
- Crypto data are 24/7 and in UTC, each exchange has its own price and reported volume is not always reliable: the index and the source matter.

## Resources

### Research

- [Stochastic Processes - Random Walks](https://pythonparatrading.com/en/stochastic-processes/) · Research-0005 · 11 min

### Documentation

- [Binance: introduction to perpetual futures funding rates (formula, schedule and base rate)](https://www.binance.com/en/support/faq/introduction-to-binance-futures-funding-rates-360033525031) · binance.com
- [ESMA: Markets in Crypto-Assets Regulation (MiCA), implementing measures and register](https://www.esma.europa.eu/esmas-activities/digital-finance-and-innovation/markets-crypto-assets-regulation-mica) · esma.europa.eu
- [ccxt: manual of the unified crypto exchange API](https://docs.ccxt.com/) · docs.ccxt.com

### Data

- [Level 1 data: hourly XSN, 2024-2025 (Parquet)](https://pythonparatrading.com/curso/datos/nivel-1/xsn_1h.parquet) · Download · xsn_1h.parquet
- [Level 1 data: XSN funding every 8 hours (CSV)](https://pythonparatrading.com/curso/datos/nivel-1/xsn_funding_8h.csv) · Download · xsn_funding_8h.csv

Previous lesson: [1.2.5 · Options: calls, puts, intrinsic value and time value](https://pythonparatrading.com/en/python-trading-course/level-1/options-calls-puts-and-time-value/)

Next lesson: [1.2.7 · Fixed income and interest rates; CFDs and leveraged products](https://pythonparatrading.com/en/python-trading-course/level-1/fixed-income-rates-and-leveraged-products/)
