Metadata-Version: 2.4
Name: coinpopbit-futures-math
Version: 1.0.0
Summary: Deterministic zero-dependency math estimates for isolated futures liquidation price, breakeven, risk-based position sizing, average entry price, and risk-reward ratio.
Author-email: CoinPopBit <contact@coinpopbit.com>
License: MIT
Project-URL: Homepage, https://coinpopbit.com/
Project-URL: Repository, https://github.com/wlwli1/coinpopbit-futures-math
Project-URL: Issues, https://github.com/wlwli1/coinpopbit-futures-math/issues
Keywords: crypto,futures,perpetual,liquidation-price,breakeven,position-sizing,risk-reward,average-entry-price,trading-math,finance
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Financial and Insurance Industry
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Office/Business :: Financial
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Dynamic: license-file

# coinpopbit-futures-math

Deterministic, zero-dependency math formulas for cryptocurrency perpetual futures planning — available in both **JavaScript/TypeScript (ESM)** and **Python 3.9+**.

- **Pure math only:** No network calls, no market or funding API data, no exchange fee presets, no regional leverage caps, and no affiliate links. You pass every rate and margin parameter explicitly.
- **Cross-language parity:** Both implementations share the same test vectors (`tests/vectors.json`) and match the interactive calculators on [CoinPopBit](https://coinpopbit.com/).
- **Estimates only:** Every result is a mathematical estimate for planning and education. Actual liquidation prices, fees, and funding depend on each exchange's live mark price, maintenance margin tiers, contract rules, and account mode — always check the exchange screen before placing an order.

## Functions & Interactive Calculators

| Function (JS / Python) | What it estimates | Interactive calculator |
|---|---|---|
| `isolatedLiquidationPrice` / `isolated_liquidation_price` | Isolated-margin liquidation price (`style: 'fee' \| 'mmr' \| 'add'`), bankruptcy price, distance %, margin, and max isolated loss | [Liquidation Price Calculator](https://coinpopbit.com/liquidation-price-calculator/) |
| `breakevenPrice` / `breakeven_price` | Fee- and funding-inclusive breakeven exit price (long or short) | [Futures Breakeven Calculator](https://coinpopbit.com/futures-breakeven-calculator/) |
| `roundTripFee` / `round_trip_fee` | Entry + exit trading fee using entry notional and exit price | [Crypto Futures Calculator](https://coinpopbit.com/crypto-futures-calculator/) |
| `positionSizeByRisk` / `position_size_by_risk` | Risk-based position size, coin quantity, margin, and liquidation-before-stop check | [Crypto Position Size Calculator](https://coinpopbit.com/crypto-position-size-calculator/) |
| `averageEntryPrice` / `average_entry_price` | Weighted average entry price across buys plus quantity needed to reach a target average | [Crypto Average Price Calculator](https://coinpopbit.com/crypto-average-price-calculator/) |
| `riskRewardRatio` / `risk_reward_ratio` | Raw and fee-adjusted risk-to-reward ratio and breakeven win rate | [Risk-Reward Ratio Calculator](https://coinpopbit.com/risk-reward-ratio-calculator/) |

## Installation

### JavaScript / TypeScript (Node 18+ / Browser ESM)

```bash
npm install coinpopbit-futures-math
```

```js
import {
  isolatedLiquidationPrice,
  breakevenPrice,
  roundTripFee,
  positionSizeByRisk,
  averageEntryPrice,
  riskRewardRatio,
} from 'coinpopbit-futures-math';

const liq = isolatedLiquidationPrice({
  side: 'long',
  entryPrice: 100000,
  leverage: 10,
  notional: 10000,
  mmr: 0.005,
  feeRate: 0.0005,
  style: 'fee',
});
console.log(liq.liquidationPrice); // ~90497.7376 (estimate)
```

### Python (3.9+, standard library only)

```bash
pip install coinpopbit-futures-math
```

```python
from coinpopbit_futures_math import (
    isolated_liquidation_price,
    breakeven_price,
    round_trip_fee,
    position_size_by_risk,
    average_entry_price,
    risk_reward_ratio,
)

liq = isolated_liquidation_price(
    side="long",
    entry_price=100000,
    leverage=10,
    notional=10000,
    mmr=0.005,
    fee_rate=0.0005,
    style="fee",
)
print(liq["liquidation_price"])  # ~90497.7376 (estimate)
```

## Formulas & Reference Documentation

Let $q = N / E$ be position quantity, $E$ entry price, $N$ entry notional, $L$ leverage ($\ge 1$), $X$ extra isolated margin ($\ge 0$), $\text{mmr}$ maintenance margin rate ($\ge 0$), and $f$ fee rate ($0 \le f < 1$).

### 1. Isolated Liquidation Price (`style: 'fee' | 'mmr' | 'add'`)

Exchanges differ in how liquidation fees and extra margin enter the isolated-margin equation. Pass `style` explicitly to select the formula family:

- **`fee`** (maintenance margin ratio includes closing fee in denominator; see [OKX liquidation calculation help](https://www.okx.com/en-gb/help/how-to-calculate-the-price-what-are-the-conditions-for-strong-flat)):
  - Long: $P = (E \cdot q - E \cdot q / L - X) / (q \cdot (1 - \text{mmr} - f))$
  - Short: $P = (E \cdot q + E \cdot q / L + X) / (q \cdot (1 + \text{mmr} + f))$
  - Requires $\text{mmr} + f < 1$.
- **`mmr`** (extra margin adjusted by $(1 \mp f)$, denominator uses $\text{mmr}$ only; see [Bybit UTA liquidation process](https://www.bybit.com/en/help-center/article/UTA-Trading-Rules-Liquidation-Process)):
  - Long: $P = (E \cdot q - E \cdot q / L - X / (1 - f)) / (q \cdot (1 - \text{mmr}))$
  - Short: $P = (E \cdot q + E \cdot q / L + X / (1 + f)) / (q \cdot (1 + \text{mmr}))$
  - Requires $\text{mmr} < 1$.
- **`add`** (linearized offset with additive extra margin; see [MEXC margin calculation guide](https://www.mexc.com/support/article/mexc-margin-calculation-guide-312054740132052992)):
  - Long: $P = E \cdot (1 + \text{mmr} - 1 / L) - X / q$
  - Short: $P = E \cdot (1 - \text{mmr} + 1 / L) + X / q$
  - Requires $\text{mmr} < 1$.

Validation & outputs:
- Throws if any input is out of range, if the resulting price is non-finite, or if liquidation sits on the wrong side of entry (`P >= E` for long, `P <= E` for short).
- Long liquidation prices $\le 0$ (such as 1x long) are clamped to `0`.
- Bankruptcy price: long $\max(0,\; E(1 - 1/L) - X/q)$, short $E(1 + 1/L) + X/q$.
- Max isolated loss equals full committed isolated margin: $N / L + X$ (not just the price move to liquidation).

### 2. Breakeven Price & Round-Trip Fee

- Funding paid (positive = paid, negative = received; see [OKX funding fee mechanism](https://www.okx.com/help/perps-funding-fee-mechanism)):
  $$\text{fundingPaid} = N \cdot r_{\text{funding}} \cdot n_{\text{settlements}} \cdot (\text{long} ? +1 : -1), \quad F = \text{fundingPaid} / N$$
- Breakeven price (requires $0 \le f_{\text{open}}$, $0 \le f_{\text{close}} < 1$):
  - Long: $E \cdot (1 + f_{\text{open}} + F) / (1 - f_{\text{close}})$
  - Short: $E \cdot (1 - f_{\text{open}} - F) / (1 + f_{\text{close}})$
- Round-trip fee at `exitPrice`: $N \cdot f_{\text{open}} + (N / E) \cdot P_{\text{exit}} \cdot f_{\text{close}}$.

### 3. Risk-Based Position Size

- Risk amount: $R = \text{balance} \times (\text{riskPct} / 100)$
- Loss per unit at stop $S$ (stop assumed filled at $S$ with `closeFeeRate`):
  $$\text{perUnit} = (\text{long} ? E - S : S - E) + E \cdot f_{\text{open}} + S \cdot f_{\text{close}}$$
- Quantity $Q = R / \text{perUnit}$, notional $N = Q \cdot E$, margin $M = N / L$. Leverage sets margin and liquidation proximity without changing risk-based quantity.
- Includes `liqBeforeStop` flag comparing estimated liquidation against $S$ using the chosen `style`.

### 4. Average Entry Price & Target Averaging

- Weighted average over positive `(price, quantity)` entries: $A = \sum(p_i q_i) / \sum q_i$.
- Optional target average $T$ at new price $P$ (valid whenever $P < T < A$ or $P > T > A$):
  $$Q_{\text{add}} = Q \cdot (A - T) / (T - P)$$

### 5. Risk-Reward Ratio & Breakeven Win Rate

- Raw: $\text{risk} = |E - S|$, $\text{reward} = |T - E|$, $R = \text{reward} / \text{risk}$, $\text{winRate} = 1 / (1 + R)$.
- Fee-adjusted (single per-side fee rate $f \ge 0$):
  $$R_f = \frac{\text{reward} - (E \cdot f + T \cdot f)}{\text{risk} + (E \cdot f + S \cdot f)}$$
  If $R_f \le 0$, `feeAdjustedRatio` is `null` (`None` in Python) and `feeAdjustedBreakevenWinRate` is `1.0`.

## Running Tests

```bash
# JavaScript (Node 18+)
node packages/js/test/run.mjs

# Python (3.9+)
python -m unittest discover -s packages/python/tests -v
```

## Disclaimer & License

MIT License — Copyright (c) 2026 CoinPopBit (`contact@coinpopbit.com`). All outputs are deterministic mathematical estimates for educational and planning use only, not financial or trading advice.
