Perpetual DEX development: where position management breaks
Position management is where margin requirement, funding rate, and liquidation decision converge. On a flat market, it looks like simple arithmetic: recalculate margin, update position state, charge a fee.
The discrepancy shows up on the first sharp move. The risk engine calculates the requirement at one price, execution occurs at another, and liquidation triggers at a third — a gap forms between these circuits, and it falls entirely on the exchange.
The second source of problems is liquidation as a separate execution path. If it goes through the same pool as regular orders, with a thin order book the slippage exceeds the remaining margin of the position, and the insurance fund covers the difference.
Hence the typical failure chain: thin liquidity, wide spread, liquidation cascade on a downward move.
An insurance fund deficit is covered either by forced reduction of profitable positions or by a loss for liquidity providers — and both options damage trust more than the loss itself.
In perpetual DEX development, we lock in a unified risk model before the first line of code: one price for calculation, one for execution, transparent rounding rules, and a predefined source of deficit coverage. We break down how this is addressed.
What a controllable risk engine and margin modes provide
The risk engine calculates collateral not by the last trade but by the mark price — the average between the index and the order book. This eliminates a class of failures where a position is taken out by a wick on thin liquidity rather than a real market move.
Then tiered maintenance margin kicks in: the larger the position, the higher the requirements, and this is calculated separately for isolated and cross-margin modes.
Position recalculation is done in batches within the block, in a deterministic order. Recalculation time is predictable even during peak hours: the calculation queue takes a fixed interval, and the funding rate accrues without manual parameter edits. This is how volatility resilience appears without an engineer on duty at the monitor.
Liquidation works as a cascade: partial position closure, then the insurance fund, automatic reduction — last. The share of failed liquidations that leave negative collateral drops by a factor of several, and the loss is not shifted onto other market participants.
We keep settlements on Ethereum, where the execution environment is deterministic and the state is verifiable.
The risk engine's behavior becomes reproducible: the same set of positions always yields the same result, and disputed situations are resolved from logs, not from memory.
Margin modes and price calculation models: comparing approaches
Margin modes and the price source are two independent decisions, and together they determine how the system survives a sharp market move.
The mode defines exactly what the trader is liable with for the position; the price source defines the value from which collateral and the liquidation threshold are calculated. The choice is made not "to taste" but for the audience profile and liquidity depth.
| Option | When it fits | Limitations |
|---|---|---|
| Isolated margin | Traders limit risk to a single trade and want to see maximum losses in advance | Free collateral in the account does not save the position: capital is not reused |
| Cross margin | A portfolio with hedging legs, where profit from one holds the drawdown of another | An error in one position drags down the entire account — risk becomes shared rather than local |
| Oracle price | A value resistant to manipulation within a single pool is needed with a thin order book | Update delay creates a lag between the quote and actual trades |
| Index price | Liquid spot and many source venues that can be averaged | Dependence on the composition of sources and their availability at the moment |
| Partial liquidation | Large positions where full closure hits the order book and other participants | Requires careful configuration of step and thresholds; otherwise liquidation loops |
In practice, approaches are combined: index price as the base, oracle as insurance when venues diverge. Splitting liquidation into steps instead of a single closure reduces the cascade and removes peak drawdowns for those not at fault for the move.
Next, we break down how these modes connect to the risk calculation module and what we test under load.
Development and implementation: engineering stages
The sequence of work is the same both for a new perpetuals exchange and for a position management module on top of an already operating protocol.
The difference is in the depth of the audit: from scratch, we design margin and liquidation logic; on top of an existing system, we analyze the current one and do not break live positions.
- Audit of the current scheme. We analyze position accounting, margin calculation, and the liquidation queue, looking for desynchronization between contract state and the data in the front end. The output is a map of bottlenecks and a list of scenarios the system does not survive.
- Flow design. We describe the order path from wallet to calculation: where limits are checked, who supplies the price, how roles are distributed between contracts and services. The design is locked before the first line of code.
- Risk parameter configuration. We set leverage, maintenance margin tiers, liquidation thresholds, and funding rate calculation rules. Separately — safeguards: open interest limits per instrument and per participant, pause on sharp price moves.
- Assembly of the calculation core. We implement position accounting, margin mechanics, and liquidations, and connect the price source. Each module is covered by automated tests before integration.
- Scenario testing. We run the model on sharp price moves, liquidation cascades, oracle pauses, and load spikes, and compare calculations against a reference model. A margin error in testing is cheaper than in production.
- System handover. We deploy, hand over documentation on parameters and procedures for changing them, and train the client's team to respond to anomalies and change the risk profile without halting trading.
Handover artifacts: configurations, diagrams, and procedures
Project delivery is not an archive with source code but a package your team can use to operate the perpetual DEX without us. We hand it over along with a walkthrough: we go through each document, show where a parameter changes and what will happen to client positions after that. Below is what physically remains with the client.
- Risk configurations — files with maximum leverage, position and instrument limits, liquidation thresholds, funding rates, and margin ratios. Each parameter group includes a description: allowable value range, what the change affects, and which check catches an error before release.
- Access policies — roles and separation of powers among operator, risk manager, and administrator, rules for handling signer keys, the procedure for granting and revoking access, and scheduled rotation procedure.
- Data schema — structure of tables for positions, orders, trade history, and funding calculations: relationships between entities, history retention requirements, queries for balance reconciliation and discrepancy investigation.
- Flow diagrams — the order path from receipt to execution, the price acquisition point, the event queue, and system behavior when the connection to an external source breaks and when the price diverges.
- Response procedure — a list of scenarios by failure class: which metric triggers action, who makes the decision, how trading is restricted, and how the change is rolled back.
- Documentation — description of modules and their responsibilities, instructions for deployment, recovery from backup, and failover to the standby circuit.
- Limitations log and roadmap — what is deliberately left outside the current release, which areas require attention as load grows, and in what order to address them.
We accept the package together: we run a recovery from backup and one training incident according to the procedure. If a document does not allow the on-call shift to act without us, we rewrite it rather than sign off.
Case study: position management under volatility load
Position calculation lived in the same thread as the rest of the venue's logic: when the price jumped, the recalculation task queued behind fund debits, fee calculation, and accruals.
The queue grew, some liquidations triggered at an already outdated price, and engineers manually adjusted risk thresholds at night. This concerns a perpetual contract trading venue on Ethereum.
What was rebuilt
Position calculation was moved to a separate circuit that reads the quote stream and updates only positions that entered the risk zone — instead of a full pass over all open positions on every tick.
The "trading pair + side" index and state snapshots before and after each step provided idempotency: repeating a task after a node failure does not double the debit and does not create a second liquidation.
Risk thresholds became versioned parameters — a change is applied predictably and rolled back with a single action, without editing code in production.
Metrics before and after
| Metric | Before | After |
|---|---|---|
| Share of failed liquidations out of all triggers | about 7% | less than 0.5% |
| Position recalculation time after a price jump | 40–60 s | 2–3 s |
| Manual interventions in risk parameters per week | 12–15 | 0–1 |
| Recovery after node failure | manual reconciliation | snapshot reconciliation |
The window between a price change and the risk circuit's reaction shrank by an order of magnitude, so liquidation occurs at the current quote rather than the one from before the spike.
Manual threshold edits are no longer a standard operating mode: the client's team changes parameters itself, and engineers focus on development rather than on-call duty.
What to do if the risk engine is already deployed but liquidations are unprofitable?
Unprofitable liquidations rarely mean the engine is poorly written — more often it calculates correctly but from incorrect inputs.
A typical cause: margin is calculated by the last trade price rather than the index price, and a thin order book provides a price at which the position cannot be closed without slippage.
The second cause: maintenance margin is set too close to initial margin, and the position goes into liquidation on ordinary noise.
Diagnostics start with metrics, not with reading code: the share of liquidations that occur during short price spikes, the size of the insurance fund deficit after each forced sale, and the time gap between touching the threshold and actual closure.
These three numbers separate a parameter problem from an architecture problem — and determine what exactly to change.
Next is targeted module replacement. We do not rewrite the entire system: we change the price source, move it to a manipulation-resistant aggregator, such as Chainlink, recalculate the maintenance margin formula, and add open interest limits for thin pairs.
The position format and external interfaces remain the same, so existing positions are not forcibly recalculated or closed.
Rollout is phased. First, the new calculation runs in shadow mode: it calculates requirements, while closures are performed by the old one — this way, discrepancies are visible on the real flow before anything is affected.
Then new positions are moved to the new mode, and only after that — the accumulated portfolio, as positions close voluntarily or according to an announced schedule.
The migration plan records which positions are affected, where forced migration is possible, and by what criterion we roll back.
Technical concerns: margin, oracles, and calculation audit
Risk parameters — initial and maintenance margin, tiers for large positions, funding rates — are moved into managed settings rather than the contract body. Changing the liquidation mode then does not require reissuing contracts and migrating user positions.
Calculations live in a single module: the same formula calculates margin, liquidation price, and payout, so divergence between the interface and on-chain logic is excluded by design rather than caught by tests.
What happens when price sources diverge?
Divergence is a normal situation, not a failure. We calculate the median across several independent oracles, discard outliers, and monitor deviation from a stable value.
If the deviation exceeds a set threshold, the engine switches to risk reduction mode: new positions are not opened, liquidations proceed at a conservative price, and the funding rate is capped. After a set stabilization window, the system returns to normal mode without manual intervention.
How do you test calculations before launch?
We run the engine on historical series with stress scenarios: gaps, liquidation cascade, thin book, oracle delay. We compare the result with a reference model calculated independently — the discrepancy in margin and payouts must be zero on matching input data. We separately test edges: rounding, minimum price step, behavior at zero liquidity.
What is included in acceptance?
Scenarios with expected numbers that the client reproduces independently rather than taking on faith. Plus a report on test coverage of critical paths: margin calculation, liquidation, funding, withdrawal.
If a calculation does not match the reference, we investigate the cause before version lock — disputed points are documented in writing rather than "agreed later."
Let's discuss your task — we will show how these issues are addressed in your market configuration.Let's discuss the task: what to send for an estimate and work plan
For the work estimate and implementation plan to rely on your mechanics rather than averaged assumptions, we need context: how margin, calculations, and liquidations are structured and what exactly does not work. Below is the input data that resolves most questions at the start. If something is missing, we will record it as an open item and include it in the plan.
- Instruments and markets: perpetual futures, inverse or linear, whether multi-collateral is needed.
- Margin rules: isolated or cross, maximum leverage, maintenance margin rates by tier.
- Funding: accrual frequency, rate formula, who calculates it, and how it is distributed.
- Pricing: price sources, index averaging window, behavior when diverging from the last trade.
- Liquidations: position closing order, insurance fund, automatic reduction with a thin order book.
- Bottlenecks: order placement delay, drawdowns during volatility, manual operations in calculations.
- Expected result: calculation time, accuracy of matching the index, share of manual interventions.
Send the description in a convenient form — text, table, or diagram. We will discuss the task and come back with an estimate and a phased implementation plan.







