Skip to content

fix: correct calculateLiquidationPrice (current-notional margin ratio)#64

Open
koko1123 wants to merge 2 commits into
mainfrom
koko/fix-liquidation-price
Open

fix: correct calculateLiquidationPrice (current-notional margin ratio)#64
koko1123 wants to merge 2 commits into
mainfrom
koko/fix-liquidation-price

Conversation

@koko1123

@koko1123 koko1123 commented Jul 13, 2026

Copy link
Copy Markdown
Contributor

What

calculateLiquidationPrice used the wrong formula. IMarginRatios defines the margin ratio as equity / position value, where value is the current notional (size * price), not the entry notional. The old code computed entryPrice ∓ (margin - liqRatio * entryNotional) / size.

Solving equity == liqRatio * size * liqPrice at the liquidation price gives:

  • long: (entry - margin/size) / (1 - liqRatio)
  • short: (entry + margin/size) / (1 + liqRatio)

Also returns null for a long when liqRatio >= 100% (no positive liquidation price exists).

Example (entry 50, size 1, margin 100, liqRatio 0.05)

old (buggy) new (correct)
long 0 (clamped from -47.5) 0 (clamped from -52.6)
short 147.5 142.857

The old short value (147.5) overstated the liquidation price by ~3%, which for a bot reads as "safe" when the position is actually closer to liquidation.

Tests

Updated the unit tests with the corrected formula and added exact-value locks (short = 142.857, high-leverage long = 42.105). Full pnpm run ci green: build, 267 unit tests, tsc --noEmit, biome lint.

Context

Found while porting these helpers to perpcity-zig-sdk (verified against the deployed contract's IMarginRatios). This mirrors the fix landing there so both SDKs report identical liquidation prices.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes

    • Refined liquidation price calculations for both long and short positions.
    • Long-position liquidation price now clamps to exactly 0 when applicable.
    • More accurate liquidation price results for short and high-leverage long scenarios.
    • Added correct handling when the liquidation margin ratio is too high (returns no liquidation price).
  • Tests

    • Updated unit tests with precise expected values for representative long/short cases.
    • Added a new unit test covering the “returns null” edge case.

@coderabbitai

coderabbitai Bot commented Jul 13, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 9f8ac76f-c80c-4d84-8520-51c02d228332

📥 Commits

Reviewing files that changed from the base of the PR and between 222068d and 2e515d9.

📒 Files selected for processing (2)
  • src/__tests__/unit/position-calculations.test.ts
  • src/functions/position.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/tests/unit/position-calculations.test.ts
  • src/functions/position.ts

📝 Walkthrough

Walkthrough

calculateLiquidationPrice now derives long and short liquidation prices directly from the liquidation margin ratio, clamps valid long results to zero, returns null for invalid long denominators, and updates scenario tests with specific expected values.

Changes

Liquidation Price Calculation

Layer / File(s) Summary
Direct liquidation price formulas
src/functions/position.ts
Long positions validate the denominator and clamp results to zero; short positions use a direct margin-adjusted formula.
Scenario expectation updates
src/__tests__/unit/position-calculations.test.ts
Long and short scenarios assert 0, approximately 142.857, and approximately 42.105; an added case expects null when the liquidation margin ratio is at least 100%.

Estimated code review effort: 2 (Simple) | ~10 minutes

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main change by naming calculateLiquidationPrice and the current-notional margin ratio fix.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch koko/fix-liquidation-price

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
src/functions/position.ts (1)

110-112: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Add a regression test for the liqMarginRatio >= 1 boundary.

This branch is explicitly introduced by the PR, but the updated tests cover only ratios below 100%. Add a long-position case with liq: 1_000_000 and assert that the result is null.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/functions/position.ts` around lines 110 - 112, Add a regression test for
the long-position calculation covering liqMarginRatio equal to 1, using liq:
1_000_000 and asserting the result is null. Place it alongside the existing
position tests and preserve the current expectations for ratios below 100%.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@src/functions/position.ts`:
- Around line 110-112: Add a regression test for the long-position calculation
covering liqMarginRatio equal to 1, using liq: 1_000_000 and asserting the
result is null. Place it alongside the existing position tests and preserve the
current expectations for ratios below 100%.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: fd70ab87-efc8-46d1-a3b2-084ee83a5121

📥 Commits

Reviewing files that changed from the base of the PR and between b1b05ee and 3476002.

📒 Files selected for processing (2)
  • src/__tests__/unit/position-calculations.test.ts
  • src/functions/position.ts

@koko1123

Copy link
Copy Markdown
Contributor Author

Addressed the CodeRabbit nitpick: added a regression test covering the liqMarginRatio >= 100% long boundary (liq: 1_000_000), asserting calculateLiquidationPrice returns null for the denom <= 0 branch introduced by this fix (222068d).

Local pnpm run ci is green: build success, 268 unit tests pass, tsc --noEmit clean, biome lint clean. All CI checks (build-and-test, lint, CodeQL, integration-tests) were already passing.

koko1123 added 2 commits July 13, 2026 17:20
… ratio

The margin ratio is defined by IMarginRatios as equity / position value, where
value is the *current* notional (size * price) -- not the entry notional. The
old formula subtracted `(margin - liqRatio * entryNotional) / size` from the
entry price, which is wrong. Solving `equity == liqRatio * size * liqPrice`
gives:
  long:  (entry - margin/size) / (1 - liqRatio)
  short: (entry + margin/size) / (1 + liqRatio)

Also returns null for a long when liqRatio >= 100% (no positive liq price).

Updated the unit tests with the corrected formula and exact-value locks
(short = 142.857, high-lev long = 42.105). Full CI green (267 unit tests, tsc,
biome).

Mirrors the same fix in perpcity-zig-sdk so both SDKs report identical
liquidation prices.
The denom <= 0 branch (liq ratio >= 100% -> null) introduced by this fix
was untested. Adds a long-position case with liq: 1_000_000 asserting null,
addressing the CodeRabbit nitpick.
@koko1123
koko1123 force-pushed the koko/fix-liquidation-price branch from 222068d to 2e515d9 Compare July 13, 2026 21:21
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant