Book a free call

How to Build a P2P Derivatives Exchange

A P2P derivatives exchange lets traders swap perpetuals directly, with a smart contract holding the collateral instead of a custodian. Here is how to build one.

Hertiv engineering teamReviewed by a senior engineer
8 min read
How to Build a P2P Derivatives Exchange
On this page

Short answer

A P2P derivatives exchange is a trading venue where two traders agree a derivatives contract directly and a smart contract holds the collateral, settles the outcome and releases the funds. No central operator takes custody of the money, so the trade settles by code rather than by trusting a company.

What is a P2P derivatives exchange?

A P2P derivatives exchange is a venue where traders agree derivatives contracts with each other directly, and a smart contract holds the collateral and settles the result. A derivative is a contract whose value follows something else, such as the price of bitcoin or ether, without the trader owning the asset itself.

Most derivatives exchanges are centralised: traders deposit funds with the company, the company matches orders, and the company pays out winnings. In a P2P design, the matching and the money are handled differently. Traders can find each other through an order book or a request-for-quote flow, but the collateral sits in a smart contract that neither side controls alone.

The contract only moves money when its rules are met. If a position closes in profit, the contract pays the winner from the loser's collateral. If a position must be liquidated, the contract sells enough collateral to cover the loss. This is what makes the trade trustless in the practical sense: neither trader needs to trust the other, or a custodian, to get paid.

The spot-market version of the same idea is covered in how to build a P2P crypto exchange, which handles escrow and disputes for ordinary coin trades rather than derivatives.

How does a P2P derivatives trade work?

A P2P derivatives trade starts when one trader posts an offer and another accepts it, or when two orders match in an order book. The offer states the market, the size, the direction and the price or the funding terms. Once both sides agree, each side locks collateral into the smart contract before the position opens.

For perpetual swaps, the most common crypto derivative, the position has no expiry date. Instead, the two sides exchange funding payments at set intervals. When the perpetual price sits above the spot price, long positions pay short positions, which pulls the price back towards the spot market. This mechanism keeps the contract price close to the real price without an expiry date forcing settlement.

Options work differently. The buyer pays a premium for the right, but not the obligation, to buy or sell at a set price before a set date. The seller locks collateral to cover the payout if the option ends in the money. The contract checks the price at expiry, usually from an oracle, and pays the winner. The basics of these products are covered in what crypto derivatives are and why they matter.

The full range of contract types, from futures to options, is listed in the types of crypto derivatives.

What makes the trade trustless?

Three pieces make a P2P derivatives trade trustless: collateral held by a contract, prices supplied by an oracle, and settlement that runs by code. Each piece removes one reason to trust a person or a company.

Collateral is the first piece. Both sides deposit margin into a smart contract before trading. The contract will not open a position until the collateral is there, and it will not release funds except according to its rules. A trader who loses cannot walk away with the winner's money, because the money was never in the loser's hands.

Oracles are the second piece. The contract cannot see market prices on its own, so it reads them from an oracle feed. The oracle reports the price of the underlying asset, and the contract uses it to work out profit, loss and liquidation. A good design uses more than one price source and pauses trading if the feeds disagree by too much.

Settlement by code is the third piece. When a position closes, the contract computes the result and moves the funds in the same step. There is no back office to approve the payout and no queue for withdrawals. If the contract is written correctly, the only trust left is trust in the code itself, which is why audits matter so much.

Which parts must you build first?

A P2P derivatives exchange has six parts, and the order you build them in matters. The collateral and settlement contracts come first, because everything else depends on them working correctly.

PartWhat it doesBuild first?
Collateral vaultsHold margin and pay out winnersYes
Matching enginePairs offers and ordersYes
Oracle feedsSupply prices for settlementYes
Liquidation engineCloses positions that run out of marginYes
Wallets and accountsLet traders sign and track positionsAfter core
Compliance checksScreen users and block restricted regionsBefore launch

The matching engine can run off-chain for speed, as long as the signed orders it produces are settled on-chain. The liquidation engine can also run off-chain, watching positions and calling the contract when one must close. But the collateral, the settlement rules and the price feeds must live in contracts that anyone can read, because those are the parts traders are trusting.

How do liquidations and funding rates work?

Liquidation protects the system when a losing position runs out of margin. Every position has a maintenance margin, which is the minimum collateral it must keep. When losses push the collateral below that line, the position is closed and the remaining collateral is used to cover the loss.

The liquidation engine watches every open position against the oracle price. When a position crosses the line, the engine calls the contract, which closes the position and sells enough collateral to repay the other side. A small part of the collateral is usually kept as a fee for the liquidator, which gives independent keepers a reason to watch the market and act quickly.

Funding rates keep perpetual prices close to spot prices. At set intervals, the side of the market that is more crowded pays the other side. When more traders are long than short, longs pay shorts, which makes holding a long position cost money and pulls the price down towards spot. The rate rises with the gap between the perpetual price and the spot price, so a large gap means a large payment.

Both mechanisms need careful limits. A liquidation that runs during a sharp price move can close positions at bad prices, and a funding rate that spikes can surprise traders. Caps on funding and partial liquidations, which close only part of a position, soften both problems.

How to build a P2P derivatives exchange in 6 steps

Build a P2P derivatives exchange in six steps: define the first market, write the contracts, connect the prices, build the matching, test the failures, then open with limits.

  1. Pick one market and one product. Start with a single perpetual market, such as bitcoin, where price feeds are deep and traders already understand the product.
  2. Write the collateral and settlement contracts. Cover deposits, withdrawals, position opening, closing, funding and liquidation. Keep the contracts small and easy to read.
  3. Connect two or more oracle feeds. Use independent price sources and a rule that pauses trading if they disagree by more than a set amount.
  4. Build matching and liquidation off-chain. A fast matching service and a liquidation watcher keep the exchange responsive while settlement stays on-chain.
  5. Test the failure cases. Simulate oracle outages, sharp price moves, liquidations during low liquidity and disputed settlements on a test network.
  6. Launch with caps. Limit position sizes, the number of markets and the total collateral at risk until the system has run through real market moves.

Each step should be finished and tested before the next begins. A derivatives exchange that opens with untested liquidation logic is a loss waiting for a volatile day. The exchange-side parts are covered in the components of a crypto derivatives exchange.

Example (hypothetical): a first month of P2P derivatives trading

Example (hypothetical): a small team opens a P2P perpetual exchange with one bitcoin market. In the first month, 200 traders open positions, and the total collateral locked in the contracts is 50 bitcoin. The team caps each position at 0.5 bitcoin and the total open interest at 100 bitcoin, so the system is never risking more than it can settle.

During the month, the bitcoin price falls by a tenth in a single day. Forty positions cross their maintenance margin, and the liquidation engine closes them. Thirty-eight close cleanly and the winners are paid from the losers' collateral. Two positions close at a loss to the system because the price moved between the oracle update and the liquidation call, and the insurance fund covers the gap of 0.2 bitcoin.

The team reviews the two bad liquidations and finds the oracle was updating every 60 seconds while the price was moving fast. It shortens the update interval and adds a second price source, and it raises the insurance fund from 1 bitcoin to 2 bitcoin.

The next sharp move closes all 30 liquidations cleanly, and the fund is untouched. The lesson is that the first month is a test of the failure paths, not of the trading volume.

What are the common mistakes?

The most common mistakes in P2P derivatives exchanges are trusting a single price feed, letting liquidations run untested, and opening too many markets at once.

  • One oracle, one point of failure. If the only price feed stops or is manipulated, every settlement is wrong. Use at least two feeds and a pause rule.
  • Untested liquidations. Liquidation logic that has never faced a sharp move will fail on the first volatile day. Simulate crashes on a test network.
  • Too many markets at launch. Each new market needs its own price feed, its own liquidity and its own liquidation watch. Start with one.
  • Hidden custody. If the team can move collateral by hand, the exchange is not trustless. Keep admin powers narrow and time-locked.
  • No insurance fund. Some liquidations will lose money. A fund paid for by trading fees covers the gap instead of passing it to winners.
  • Ignoring the rules. Derivatives are regulated in many places. Get legal advice on who may trade before opening, not after.

Key takeaways

  • A P2P derivatives exchange replaces a custodian with a smart contract that holds collateral and settles by code
  • Perpetuals stay near the spot price through funding payments, not through an expiry date
  • Liquidations protect winners, but only if the oracle feeds and the liquidation engine are tested under stress
  • Start with one market, two price feeds and capped positions, then expand once the failure paths are proven
  • An insurance fund paid for by fees covers the liquidations that close at a loss

Frequently asked questions

What is the difference between a P2P derivatives exchange and a centralised one?

In a centralised exchange, traders deposit funds with the company, which matches orders and pays out winnings. In a P2P exchange, traders lock collateral in a smart contract, and the contract settles the trade. The company that built the venue never holds the money, so traders do not need to trust it to get paid.

Do P2P derivatives exchanges need an order book?

Not always. Some use an order book where makers post prices and takers accept them, while others use request-for-quote, where a trader asks for a price and a counterparty answers. Both work as long as the agreed trade is settled by a contract. Order books suit liquid markets; request-for-quote suits larger or less liquid trades.

What collateral can traders use?

Most P2P derivatives exchanges accept stablecoins as collateral, because their value does not move with the market being traded. Some also accept the underlying asset or a major cryptocurrency, with a haircut that reflects how much its price could fall. The choice affects how much margin a trader must lock up for the same position size.

How are funding rates set?

Funding rates are set by the gap between the perpetual price and the spot price. When the perpetual trades above spot, long positions pay short positions, and the payment grows with the size of the gap. The exchange sets the formula and the payment interval in advance, so traders can see the cost before they open a position.

What happens if the oracle price is wrong?

A wrong oracle price can trigger false liquidations or pay the wrong side, so good designs use two or more independent feeds and pause trading when they disagree by more than a set amount. Some designs also use a time-weighted average price, which smooths out brief spikes. The pause rule matters more than the feed choice.

Can a P2P derivatives exchange offer options too?

Yes. Options fit the same model: the buyer pays a premium and the seller locks collateral, and the contract settles at expiry using the oracle price. Options need extra contract logic for expiry, strike prices and premium handling, so most teams launch perpetuals first and add options once the core settlement is proven.

Found this useful? Share it.
Hertiv engineering team

Written from projects we build for clients: blockchain systems in production. Every post is reviewed by a senior engineer before publishing and updated when practice changes.

About HertivHow we work

Building a P2P derivatives exchange? Talk to Hertiv.

A senior engineer replies within one business day. Or see our Crypto Exchange service.

Book a free call

Keep reading

All posts

Tell us what you want to build

A senior engineer reads every request and replies within one business day with questions, a rough range, or a call link.

  • NDA on request before any details
  • You own all code, models and IP
  • US, UK and EU time-zone overlap

Your email app should open with your message ready to send. If it does not, write to contact@hertiv.com.

Prefer email? Write to contact@hertiv.com
Estimate costBook a call