跳到正文
DEV Community· CoinPopBit·· 2 小時前AI 評分44

三間交易所、三套強平公式:一個供建置時及瀏覽器使用的 JavaScript 函數

Three exchanges, three liquidation formulas, one JavaScript function for the build and the browser

AI 導讀

這組靜態計算器頁面統一 OKX、Bybit 和 MEXC 的 USDT 永續合約逐倉倉位強平價格計算,並以同一 JavaScript 函數生成建置時 HTML 數值及瀏覽器中的計算結果。由於首頁小工具曾把 OKX 公式套用於所有交易所,同一組 Bybit 輸入數據曾得出 66,971.69,與專用計算器的 66,934.67 不同。

正文

This is a write-up of how a set of static calculator pages computes the liquidation price of an isolated-margin USDT perpetual position for three exchanges (OKX, Bybit and MEXC), and how one function now produces both the numbers baked into the HTML at build time and the numbers the page script shows after a user types. The formulas are short. The bugs came from copying them.

The problem: "liquidation price" is not one formula

Every exchange documents roughly the same idea: a position is liquidated when its remaining margin falls to the maintenance margin. The details differ, and they move the result by a few dollars on a large price:

  • OKX includes the taker fee for closing the position in the denominator.
  • Bybit leaves the fee out of the price formula, but counts margin added later as slightly less (divided by 1 - taker).
  • MEXC uses a linear form: the entry price shifted by the maintenance rate and 1/leverage, then by any extra margin per unit.

With entry price E, quantity q (notional / entry), leverage L, maintenance margin rate mmr, taker fee taker and extra margin extra, the long and short cases are:

export function levLiq(ex, long, E, q, L, mmr, taker, extra) {
  if (ex === 'mexc') return long ? E * (1 + mmr - 1 / L) - extra / q : E * (1 - mmr + 1 / L) + extra / q;
  if (ex === 'bybit') return long ? (E * q - E * q / L - extra / (1 - taker)) / (q - q * mmr) : (E * q + E * q / L + extra / (1 + taker)) / (q + q * mmr);
  return long ? (E * q - E * q / L - extra) / (q * (1 - mmr - taker)) : (E * q + E * q / L + extra) / (q * (1 + mmr + taker));
}

For a 10,000 USDT position at 74,000 with 10x leverage, a 0.5% maintenance rate and each venue's regular taker rate (0.05%, 0.055%, 0.04%), this gives:

Formula style Long Short
Fee in denominator (OKX) 66,968.33 80,954.75
Maintenance only (Bybit) 66,934.67 80,995.02
Linear (MEXC) 66,970.00 81,030.00

The spread is small, which is exactly why it went unnoticed.

The bug: several copies of the same math

The site grew one page at a time. A liquidation calculator, a leverage calculator, an all-in-one futures calculator and a small widget on the home page each got their own copy of the formula. The home widget's copy implemented only the OKX version and used it for every venue.

The result: the home page showed 66,971.69 for a Bybit long (the OKX formula with Bybit's 0.055% taker fee), while the dedicated calculator showed 66,934.67 for the same inputs. Nobody computes these by hand, so nothing looked wrong until a review compared the pages side by side.

A second problem sat next to it: the widget's HTML contained numbers written in by hand for the first render. Before the script ran, every domain showed figures calculated for one venue, including domains that do not cover that venue at all.

The fix: one function, serialized into the page

The home widget now has a single function that returns display strings. The build script calls it to write the initial HTML, and the same function is injected into the inline page script with Function.prototype.toString():

function homeFutCalc(v, entry, margin, levRaw, F) {
  F = F || { loc: 'en-US', sfx: false, fee: 'Fee' };
  var isShort = levRaw < 0;
  var lev = Math.abs(levRaw);
  var mmr = 0.005;
  var notional = margin * lev;
  var liqPrice;
  if (v.liqStyle === 'add') liqPrice = isShort ? entry * (1 - mmr + 1 / lev) : entry * (1 + mmr - 1 / lev);
  else if (v.liqStyle === 'mmr') liqPrice = isShort ? entry * (1 + 1 / lev) / (1 + mmr) : entry * (1 - 1 / lev) / (1 - mmr);
  else liqPrice = isShort ? entry * (1 + 1 / lev) / (1 + mmr + v.perpT) : entry * (1 - 1 / lev) / (1 - mmr - v.perpT);
  // ... fee, breakeven and formatting lines omitted
}
// build time: initial HTML for this domain's default venue
const homeFutInit = homeFutCalc(homeVenues[allowedVenues[0]], 74000, 1000, 10, homeFmt);

// page script template
const script = `
  var VENUES = ${JSON.stringify(homeVenues).replace(/</g, '\\u003c')};
  var homeFutCalc = ${homeFutCalc.toString()};
`;

With no extra margin, the general formulas reduce to these forms (q cancels out), so the widget and the full calculators agree to the cent. After the change, all 15 combinations (three venues, five leverage and side presets) were checked against the dedicated calculators, and on each of the five domains the 29 output elements had the same content before and after the page script ran.

toString() has rules that are easy to break:

  1. The function must be self-contained. No imports, no closures over module variables, no helpers defined elsewhere. Everything it needs comes in as arguments: the venue data v and the number format F.
  2. Write it in syntax every target browser runs. The body is pasted into the page as-is; it is not transpiled. That is why it uses var and plain functions.
  3. Keep data out of the function body. The source text is copied into every domain's page. An earlier version branched on venue names, so the page for a domain that covers one exchange still carried the names and rules of the other two in its source. Now the formula style is data (liqStyle: 'fee' | 'mmr' | 'add'), and the build serializes only the venues that domain covers into VENUES.
  4. Escape what you inline. JSON.stringify does not escape <, so a string containing </script> would end the script block. Replacing < with < keeps the JSON valid and the HTML safe.

What is still duplicated

Not every page uses the serialized function yet. The full futures calculator has a build-time fcCompute() (used for its example table) and a page script that repeats the same three formulas, now also selected by a style field instead of venue names:

var st = (RATES[ex] && RATES[ex].liq) || 'fee';
if (st === 'add') return long ? E * (1 + mmr - 1 / L) - extra / q : E * (1 - mmr + 1 / L) + extra / q;
if (st === 'mmr') return long ? (E * q - E * q / L - extra / (1 - taker)) / (q - q * mmr) : (E * q + E * q / L + extra / (1 + taker)) / (q + q * mmr);

Those copies are kept in step by a comment in each file and by a reference value: 100,000 entry, 10x, 0.5% maintenance and 0.05% taker must give 90,497.74 on every page that uses the fee-in-denominator style. Moving the remaining pages to the serialized-function pattern is the obvious next step.

The other way a formula drifts: the wrong venue

A copy can also drift by venue rather than by math. One localized page computed a cross-versus-isolated comparison with the fee-in-denominator formula and cited that venue's help page, while every other calculator on the same domain used the linear formula of the venue that domain actually covers. The two pages disagreed on the same trade. The fix was the same idea: pick the formula from the domain's venue data, never from a hard-coded default.

Takeaways

  • If a number appears on more than one page, compute it with one function and serialize that function, rather than keeping parallel implementations.
  • Render the initial HTML with the same function the script uses. Hand-written "first paint" numbers go stale silently.
  • Keep a few reference values (inputs plus expected output) and check every page against them after any change to the math.
  • Encode per-provider differences as data the function reads, not as branches on provider names, especially when the function's source is shipped to the client.

This post was written by an AI assistant (Claude) from the project's source code and deployment notes, and published without manual editing. The code and the figures are from the running project.

來源:DEV Community · dev.to