> For the complete documentation index, see [llms.txt](https://button-labs.gitbook.io/button/gKgg6YSLPuW40VjoL4W1/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://button-labs.gitbook.io/button/gKgg6YSLPuW40VjoL4W1/core/button-basis.md).

# Button Basis

### **What is a Basis Trade?**&#x20;

In a crypto *basis trade*, an investor goes long the spot asset and short an equivalent amount of perpetual futures on that asset. This locks in the price difference (or *basis*) between the futures and spot markets. For example, if the perpetual futures price is above the spot price (a positive basis), shorting the perp and buying spot effectively yields a fixed interest rate over time. The appeal is to earn funding payments or capture the basis spread while remaining delta-neutral – if the asset’s price moves, gains on one leg offset losses on the other.

### **Why Rebalance?**&#x20;

Despite the delta-neutral appearance, this trade is not a set-and-forget arbitrage. It’s better seen as a continuous hedge rather than a riskless arbitrage. The key to basis trading is maintaining the hedge alignment over time. Market movements, funding accruals, and other factors cause the initial 1-to-1 long vs short balance to drift. Rebalancing is the process of adjusting the spot or perp position (or both) periodically to realign the hedge. In practice, rebalancing a basis trade is complex and dynamic. It’s a balancing act between too frequent adjustments (trading cost) and too infrequent adjustments (liquidation risk).

The goals of rebalancing are threefold:

* Hedge Alignment: Keep the spot and perp positions in the right proportion so that price moves remain hedged&#x20;
* Risk Management: Mitigate risks like liquidation or extreme drawdowns by reducing exposure when needed.
* Cost Control: Minimize trading costs by avoiding unnecessary trades – each rebalance incurs fees and slippage. The trick is to trade *only* when the drift or risk becomes significant.

### How Rebalancing Works?

Mechanics of the Hedge: In a long-spot/short-perp basis trade, initially the spot and short positions are set equal. This gives a delta-neutral stance. Over time, several forces will create off balance:

* Price movements: Suppose the asset’s price jumps. The spot leg’s value increases, while the perp short’s notional exposure also increases. Although PnL could be 0 due to delta-neutral, the short position could toward its liquidation limit if the price surge is large and the short’s margin is limited. Conversely, if price drops, the short gains and the long loses value, meaning the short position may become oversized relative to the  spot leg.
* Funding payments: Perpetual futures have funding rates typically paid between longs and shorts to keep futures prices peg to spot. If the funding rate is positive (perp price > spot), shorts receive payments from longs; if negative, shorts pay. These payments accumulate over time. A positive funding means the short leg is profitable to hold, which might encourage letting the short position ride a bit longer before rebalancing. Negative funding means holding the short is costly, which pushes toward earlier rebalancing or reducing the short position to cut the bleeding.

Rather than continuously trading to keep the position exactly delta-neutral, most strategies use a ***band*** approach. The basis trade is allowed to drift within a band around the target hedge ratio, and only rebalanced when it breaches that band. This is analogous to how one might rebalance an investment portfolio only when allocations stray by a certain percentage. In this context, one can define a hedge ratio. Initially this ratio is 100% — fully hedged. For example, a band of 10% – meaning if the short exposure falls below 90% of the long or rises above 110%, the rebalance is triggered.&#x20;

Importantly, the band is not fixed forever – it can adapt based on market conditions and risk factors. For instance, if volatility spikes or funding rates change drastically, the effective threshold to rebalance might tighten or loosen. Our rebalance strategy compute a score or hazard level that combines all relevant factors to decide if a rebalance should happen. In essence, when the “hazard score” exceeds a certain threshold, the system triggers a rebalance trade. This way, the strategy might rebalance sooner in hazard conditions even if the ratio hasn’t moved as much or hold off longer in calm conditions or if trading costs are unusually high.

**Hazard Score:**&#x20;

All factors are combined in a scoring model that continuously evaluates the state of the trade. For example, the strategy might compute a hazard score H that increases with:

* the distance of the hedge ratio from 1
* the current volatility — higher vol = higher hazard
* the net funding cost if negative or decreases if funding is positive, since that’s a benefit
* the proximity to liquidation (if margin level is low, hazard jumps very high)
* the ADL indicator (higher ADL risk = higher hazard)
* the liquidation indicator (higher liquidation risk = higher hazard)

Meanwhile, it will factor in the estimated cost to rebalance right now. When hazard exceeds the cost threshold, a rebalance is triggered. This approach ensures the strategy is dynamic.

### How to implement the factors?

To make the above more concrete and actionable strategy. We’ll define the variables and assumptions along the way.At the heart of the strategy is the no-trade band for the hedge ratio.&#x20;

Let’s define:

$$Q\_{spot}$$ = quantity of spot asset we long&#x20;

$$Q\_{perp}$$ = quantity of the asset in the perpetual we short

$$R$$ = the hedge ratio&#x20;

$$
R = \frac{Q\_{spot} \* Price}{Q\_{perp} \* Price}
$$

Initially fully hedged R = 1. We set an upper and lower threshold around fully hedged R

$$
R\_{lower} = 1 - \delta \ R\_{upper} = 1 + \delta
$$

How do we choose the  $$\delta$$ ? A simple heuristic formula might be derived from setting the marginal risk cost equal to marginal trade cost at the boundary. The band formula reflects a cost–risk tradeoff. Intuitively, an investor/trader faces two opposing forces when deciding how often to rebalance a position

$$
B\_t = \sqrt{\frac{2 \cdot C\_{total,t}}{\lambda \cdot \sigma\_t^2 \cdot \tau}} \\
$$

$$
C\_{total,t} = C\_{trade} + h\_{ADL} \cdot C\_{ADL} + h\_{LIQ} \cdot C\_{LIQ}\\
\lambda = risk\space aversion\space parameter \\
\sigma\_t^2 = basis\space variance (hourly)\\
\tau = 1\space hour
$$

#### Factor — Trading cost

1. taker orders: taker fee + slippage
2. maker orders: maker fee
3. ratio between taker and maker

$$
C\_{trade} = w\_{taker} \cdot (f\_{taker} + \eta \cdot R) + (1 - w\_{taker}) \cdot f\_{maker} \\
Where:\w\_{taker} = taker\space weight (proportion\space of\space taker\space orders)\ f\_{taker}, f\_{maker} = taker/maker fees\ \eta = slippage\space multiplier\ R = \frac{H - L}{M} = bar\space range\space fraction\\
$$

#### Factor — ADL Hazard

&#x20;how likely the perp to get force delivered soon

the probability that looks at stress signals

1. down move in spot
2. unusually wide bars
3. perp trading cheap vs spot
4. bearish bar shape

$$
h\_{ADL} = \sigma(\beta\_0 + \beta\_1 D + \beta\_2 Z\_R + \beta\_3 Z\_P + \beta\_4 M) \ \sigma(x) = \frac{1}{1 + e^{-x}}\ Where:\ D = \max(0, -r\_{spot}) = downside shock\ Z\_R = robust\space z-score\space of range\ Z\_P = robust\space z-score\space of\space negative premium\ M = \frac{H - C}{H - L} = marubozu down\space indicator\\
$$

#### Factor — ADL Cost

what is expected loss if ADL happened

1. funding missing
2. slippage to get back the perp
3. directional follow-through right after shock

$$
C\_{ADL} = C\_F + C\_S + C\_J\C\_F = \lvert F\rvert \frac{\bar{k}}{60} \ C\_S = \eta\_{\mathrm{stress}} \cdot \mathbb{E}\left\[R\_{t+1},\middle|,r\_t^{S}\in\text{worst }q%\right] \ C\_J = \left\lvert\mathbb{E}\left\[r\_{t+1}^{S},\middle|,r\_t^{S}\in\text{worst }q%\right]\right\rvert
$$

#### Factor — robust z-score

this number shows how unusual today’s value is without being fooled by outliers

$$
Z(x) = \frac{x - \operatorname{median}(X)}{\operatorname{MAD}(X)} \\\operatorname{MAD}(X) = \operatorname{median}\bigl(\lvert X - \operatorname{median}(X)\rvert\bigr)
$$

#### Factor — Liquidation Hazard

chance the perp touch liquidation soon:

1. distance to liquidation
2. volatility

$$
h\_{\mathrm{LIQ}} = 2 \cdot \Bigl(1 - \Phi\bigl(\tfrac{d\_t}{\sigma\_t\sqrt{\tau}}\bigr)\Bigr) \ d\_t = \left\lvert\ln\left(\tfrac{P\_{\mathrm{liq}}}{P\_t}\right)\right\rvert \ d\_t \ge z^{} \cdot \sigma\_t\sqrt{\tau},\quad z^{} = 5,;\tau = 1\text{ hour}
$$

#### Factor — Liquidation Price

$$
(q < 0);:;P\_{\mathrm{liq}} = \frac{E + q \cdot P\_{\mathrm{entry}}}{q + m\lvert q\rvert}\\(q > 0);:;P\_{\mathrm{liq}} = \frac{q \cdot P\_{\mathrm{entry}} - E}{q(1 - m)} \ m = \frac{1}{2L\_{\max}}
$$

#### Factor — Liquidation Cost

what is the expected cost if liquidation happened

1. exchange penalty fee
2. slippage to get back the perp
3. directional follow-through right after shock
4. missing funding

$$
C\_{\mathrm{LIQ}} = C\_{\mathrm{pen}} + C\_{\mathrm{slip}} + C\_{\mathrm{cont}} + C\_{F,\mathrm{miss}} \ C\_{\mathrm{pen}} = \gamma\_{\mathrm{pen}}  \ C\_{\mathrm{slip}} = \eta\_{\mathrm{liq}} \cdot \mathbb{E}\left\[R\_{t+1},\middle|,r\_t^{S}\in\text{extreme}\right] \ C\_{\mathrm{cont}} = \left\lvert\mathbb{E}\left\[r\_{t+1}^{S},\middle|,r\_t^{S}\in\text{extreme}\right]\right\rvert \ C\_{F,\mathrm{miss}} = \lvert F\rvert \frac{\bar{k}\_{\mathrm{liq}}}{60}
$$

#### Factor — Basis Volatility (EWMA + Huber)

how noisy is the underlying we are hedging

1. slow updating average EWMA, the more recent data is more matter
2. Huber loss to filter outliers

Higher basis volatility —> hedge drift faster —> tighter band

$$
\sigma\_t^{2} = (1 - \alpha)\sigma\_{t-1}^{2} + \alpha,L\_c(r\_t^{b}) \ r\_t^{b} = r\_t^{\mathrm{perp}} - r\_t^{\mathrm{spot}}
$$

#### **Factor — Net Funding**

Divide by starting capital to get efficiency percentage

1. tighter band: better tracking but more cost
2. wider band: fewer trades but more drift/hazard

$$
Π\_{net} = Π\_{funding} - C\_{fees} - C\_{borrow}\Efficiency = (Π\_{net} / C₀) \* 100\C\_{borrow} = ∫₀ᵀ r\_{borrow} \* p\_{borrow} \* dt
$$

#### **What This Backtesting System Is Doing**

This system is testing a funding rate arbitrage strategy on Bitcoin:

1. Buy Bitcoin on the spot market
2. Sell Bitcoin futures
3. Collect funding payments - futures traders pay you every 1 hours just for holding this position

The profit comes not from price movement, but from collecting these regular funding payments - like earning interest.

#### **What The System Is Searching For**

Based on the configuration, it's trying to answer:

"How should I run this strategy to keep the most money?"

| Setting Being Tested  | What It Means                                                                          |
| --------------------- | -------------------------------------------------------------------------------------- |
| Leverage (8-15x)      | How much to amplify the position. Higher = more funding income, but riskier            |
| Rebalancing frequency | How often to adjust when positions drift. Too often = expensive fees. Too rare = risky |
| Borrowing (0-100%)    | Should I borrow money to make the position bigger? At what cost?                       |
| Risk tolerance        | How much drift to allow before rebalancing                                             |

***

#### **The Test Environment**

The system simulates trading with:

* $100,000 starting capital
* Historical BTC price data over \~6 months
* Realistic costs: trading fees, slippage, borrowing interest
* Random exchange outages (0.001% chance per hour) - simulating real-world disruptions

***

#### **What "Good" Looks Like**

The system scores each test based on:

| Priority               | Weight | What It Measures                    |
| ---------------------- | ------ | ----------------------------------- |
| Net profit             | 70%    | Money earned after ALL costs        |
| Rebalancing efficiency | 12%    | Did it avoid unnecessary trading?   |
| Trading activity       | 8%     | Not too many, not too few trades    |
| Risk-adjusted returns  | 7%     | Good returns relative to volatility |
| Drawdown control       | 3%     | Avoided big losses                  |
