How Primex Decentralizes Trade Execution for Spot Margin Trades

primex.finance
primex.finance
Published in
16 min readJul 1, 2023

--

By reading our website, blog, or social channels, you have likely come across the phrase “decentralized trade execution.”

And for a valid reason. We are building a prime brokerage protocol that enables trustless margin trading with decentralized trade execution for users. This is not only a huge benefit for the community, but it is also something that helps Primex in standing out from the crowd in the decentralized finance (DeFi) market.

But what is decentralized trade execution anyways, why is it important for traders, and how can they benefit from it on Primex?

Let’s find out by exploring the following topics:

  • The basics of trade execution and how it works in general
  • Centralized trade execution and its caveats for traders
  • The state and problems of trade execution in DeFi
  • How decentralized trade execution works on Primex, and how can you start realizing its benefits as a Trader

What Is Trade Execution?

In traditional finance (TradFi) and centralized exchanges (CEXs), traders don’t have a direct connection to the markets they trade assets in. Instead, their trades go through a financial intermediary like a stock broker or a CEX before they execute.

Simply put, trade execution refers to when a buy or sell order for an asset (e.g., stocks, crypto, futures contracts) gets filled. Unless you choose to fill it at the current market price and there’s enough liquidity on the platform, your order will execute when someone fills it, not when you place it.

Let’s see an example to understand the above.

Suppose you have placed a new order on a centralized exchange to buy 1 BTC at the current market price. Despite creating a market order — that executes as quickly as possible at the best available price –, it has to be processed by a CEX before it gets filled (thus, gets executed) at $28,000.

The above process is centralized since a single provider (the CEX in this case) has the authority to decide on the fate of your order. This conventional form of trade execution also requires trust, as the provider holds your funds in its custody on an exchange wallet until you finish trading and withdraw them to a non-custodial wallet.

On the other hand, trade execution can be decentralized and trustless. But we’ll talk about this later; let’s get back to the conventional process for now.

Centralized Trade Execution and Order Books

Like TradFi brokerages and exchanges, CEXs utilize a mechanism called a central limit order book (CLOB) to facilitate trading between users on the platform. To achieve this goal, the CLOB acts as a central hub that collects buyers’ and sellers’ orders to match and execute them.

Think about an order book as an electronic ledger that continuously collects and matches all the buy and sell orders on the exchange’s platform at different price levels. It includes the size of the trade (the amount of assets to buy or sell), the highest price a buyer is willing to pay (bid), and the lowest price a seller is willing to accept (ask).

Let’s see an example to explain the above process. The top-listed sell orders (ask) are the following on a CEX:

  1. 0.1 BTC for 28,000 USDT per 1 BTC
  2. 0.2 BTC for 29,000 USDT per 1 BTC
  3. 0.3 BTC for 30,000 USDT per 1 BTC
  4. 0.4 BTC for 31,000 USDT per 1 BTC

Suppose you place a market order to buy 1 BTC. In this case, your order will get filled at the current market price. Based on the above four sell orders, your order will execute at 30,000 USDT (0.1 x 28,000 + 0.2 x 29,000 + 0.3 x 30,000 + 0.4 x 31,000), which is currently the best price it can get filled at the moment.

On the other hand, you would get different results with limit orders. Contrary to market orders that get filled as soon as possible at the best available price, you can specify a price at which your limit order will execute.

Based on our example, let’s place a limit order to buy BTC for 28,000 USDT. Consequently, it becomes either partially filled (purchasing only 0.1 BTC for 2,800 USDT) or is put on a temporary hold until the order book can find a seller who is willing to sell the remaining 0.9 BTC to you for the price of 28,000 USDT per 1 BTC or less.

Please note that the above example is a basic one, displaying only four sell orders in the whole order book. In practice, CEXs feature significantly more of these, offering you better prices and greater chances that your order gets completely filled. However, these advantages can come at a high cost.

What Is the Problem With Centralized Trade Execution?

Currently, order books are the most widespread way to execute trades on centralized platforms like CEXs and stock brokerages. However, the problem is not mainly with the order book mechanism but with centralized trade execution itself.

A CEX’s order book may display the top buy and sell orders for the same asset pair. However, we don’t know what’s going on behind the scenes, as most exchanges implement order books as an off-chain mechanism.

This means that everything that happens there is not recorded on a public blockchain (e.g., Ethereum, Bitcoin), where everyone can transparently audit all transactions. Instead, trade execution takes place in the provider’s servers in a closed, internal network only the exchange can access.

For that reason, you have to trust the exchange that it honors the agreement and executes your trade at the best possible price (or the one you have set for your order). Unfortunately, this has not always been the case with CEXs, as multiple providers have manipulated their order books via insider trading, wash trading, fake volumes, and price manipulation.

In fact, an August 2022 Forbes report revealed that 51% of the daily Bitcoin trading volume is likely fake based on the analysis of 157 crypto exchanges. In March 2019, Bitwise told the US Securities and Exchange Commission (SEC) that 95% of digital asset trading volume on unregulated exchange platforms appeared to be either fake or non-economic wash trading in nature.

Co-founded by former FTX CEO Sam Bankman-Fried, crypto trading firm Alameda Research had a secret exemption from FTX’s liquidation protocols. This means that the ties between the two collapsed companies enabled Alameda to maintain its risky positions on the exchange without facing liquidation. And let’s not forget the series of insider trading allegations against popular CEXs and NFT marketplaces.

While illicit schemes like insider trading and wash trading may provide financial benefits for perpetrators, they could significantly hurt traders’ ability to execute their orders with optimal conditions.

For example, you may think twice before placing a buy order for a cryptocurrency with a small market cap that was traded for only $100 in the last 24 hours. However, you may find this opportunity more enticing if the exchange fakes the volume and increases it to $1 million in 24 hours.

Besides centralized trade execution, CEXs also keep your funds in their custody until you withdraw them to an external wallet you fully control. This significantly increases the risks of traders and often leads to a loss of customers’ funds due to fraud, bankruptcy, hacks, and other events. FTX, Mt.Gox, and Quadriga CX are only a few examples of high-profile cases in this field. We recommend reading this article on our blog to learn more about this issue.

The State of Trade Execution in DeFi

As one of the largest sectors of the crypto market, DeFi aims to democratize finance by building decentralized, trustless, and non-custodial protocols.

On these platforms, users are the ones governing the ecosystem, not centralized companies like CEX providers. Also, you don’t have to submit documents to apply for a loan — you can borrow funds on your crypto assets instantly and without using an intermediary.

Regarding our topic, DeFi has provided an alternative to CEXs in the form of decentralized exchanges (DEXs) and automated market maker (AMM) protocols. In this section, we will take a look at how these change trade execution for crypto traders and why existing solutions are not ideal for margin trading.

Automated Market Maker (AMM) Protocols

Automated Market Makers (AMMs) may seem like a tough topic to understand at first, but it is important to discuss it to understand how trade execution works in DeFi. Implemented first by Uniswap, an AMM is a mechanism that replaces order books with liquidity pools to make trade execution decentralized and trustless.

A liquidity pool is a smart contract that facilitates trading by including a crowdsourced collection of crypto assets. It serves as a decentralized trading venue where users can trade with the pooled liquidity. Anyone can create new liquidity pools and supply cryptocurrencies into them in exchange for a share of trading fees and other liquidity provider (LP) rewards.

Most AMM liquidity pools include two digital assets at a 50/50 ratio. In practice, this means that if Wrapped Bitcoin (wBTC) trades at the current market price of 28,000 DAI, the wBTC/DAI pool should maintain this ratio by holding 28,000 DAI for every 1 wBTC. For example, this means the liquidity pool should maintain 28,000 DAI and 1 wBTC, 56,000 DAI and 2 wBTC, 14,000 DAI and 0.5 wBTC, and so on.

When you buy a crypto asset on an AMM like Uniswap, you don’t trade with sellers of the same asset but with the liquidity pool itself, where a collection of this asset has been pooled together with a collection of another cryptocurrency. This way, there is no need for an order book or another centralized mechanism to match your orders. Consequently, trade execution remains decentralized on DeFi AMMs.

Now, let’s see how an example trade would take place on an AMM.

Suppose you are trading 1 wBTC for 28,000 DAI in the wBTC/DAI pool, where 28 million DAI and 1,000 wBTC are held as liquidity. The process should look like this:

  1. You connect your wallet to the AMM.
  2. After selecting the amount of assets to exchange (1 wBTC to sell at the current price of 28,000 DAI), you set up the trade and confirm the transaction via your wallet. Unlike on CEXs, all transactions on AMMs are on-chain. This means that you can view them via a block explorer, and you must also cover their gas fees.
  3. The liquidity pool’s smart contract adds 1 wBTC and removes 28,000 DAI from the pool.
  4. The contract transfers 28,000 DAI minus trading fees (liquidity provider fees) and other costs (e.g., protocol fees) to your wallet.

As you can see, you didn’t have to trust any intermediary to match your buy order of 1 wBTC with a seller offering it for 28,000 DAI. Instead, the trade was executed in a completely decentralized manner.

DeFi’s Struggle With Leveraged Trades

Automated market makers protocols are excellent for swapping two digital assets on the spot market. However, they do not provide leveraged trading in their current forms.

But wait, what is the difference between trading with your own funds and leveraged trading?

When you are trading without leverage, you are using your own assets exclusively without borrowing funds from others. So, the coins you have bought are yours to keep without owing money to anyone.

On the other hand, leveraged trading (also called margin trading) refers to the practice when you borrow funds to amplify your position. As the leverage is often multiple times higher than your deposit, it comes with more risks and increased potential gains than non-leveraged trading.

DeFi AMMs are designed to facilitate spot swaps without any leverage. For this very reason, you can’t use them for margin trading without relying on another protocol that would enable this feature.

It’s challenging to conveniently borrow funds for leveraged trading with favorable terms from most DeFi lending protocols, either. On these platforms, lenders supply assets in exchange for earning yield into single or multiple liquidity pools. Borrowers borrow funds from these pools by depositing and locking their collateral in smart contracts and paying interest to lenders. They can unlock their assets once they settle their debt.

The main caveat with DeFi lending protocols is over-collateralization, a mechanism that protects lenders’ funds by requiring borrowers to deposit more value in collateral than the assets they can borrow. This means that you must lock roughly $1,000 of wBTC in a smart contract to get a loan of $700 of DAI.

Since traders must borrow more value than their initial deposit to trade with leverage, lending protocols’ over-collateralized loans are not suitable for margin trading.

Consequently, while CEXs continue to hold the lead on the margin trading front, DeFi protocols have created alternative solutions to enable leveraged trades in the decentralized finance space. However, these come with their own set of disadvantages.

Probably the biggest downside of current DeFi margin trading solutions is the centralization of trade execution. In practice, this means that some of the existing protocols replaced the AMM mechanism with order books to enable leveraged trading for their users. Even if all other parts of their ecosystems remain fully decentralized, centralized trade execution on DeFi protocols poses similar risks to traders as on CEXs.

In addition to CEXs, most of the above protocols offer margin trading for users through derivatives (that’s why we call them decentralized derivatives platforms).

As its name suggests, a crypto derivative is a financial instrument that derives its value from an underlying digital asset. Instead of trading Bitcoin (BTC), Ether (ETH), or another cryptocurrency, you trade a contract between you and one or more other parties.

You don’t own the underlying asset, as the derivative only follows its price. This presents multiple challenges for traders. First, you don’t have real ownership over the cryptocurrency you trade, which increases counterparty risks (the probability that the other party in the transaction doesn’t fulfill its part of the deal).

Second, it’s not unusual to spot a noticeable difference in the price of the derivative and the spot price of the crypto asset it is tracking. This is often the case with crypto perpetual futures, a common type of derivative on the market. That’s why trading platforms have introduced a mechanism called the funding rate that distributes periodic payments between buyers and sellers.

The funding rate turns positive when the demand for futures increases, so the price of a contract becomes higher than the price of the crypto asset. In this case, buyers make payments to sellers to bring the derivative’s value closer to the spot value. On the other hand, a negative funding rate signals a lower futures price than the crypto asset’s price, requiring sellers to compensate buyers in order to increase the value of contracts.

In some jurisdictions, crypto derivatives are also subject to much stricter regulations than spot assets, making it more challenging for traders to access them.

In summary, decentralized trade execution is not well established for spot leveraged trades in DeFi. And the few platforms with margin trading capabilities offer this feature for traders through derivatives and with centralized trade execution via order books. As they are competing with each other, liquidity remains fragmented on decentralized derivatives trading platforms.

The Primex Solution: Decentralized Trade Execution for Spot Margin Trades

While trade execution remains centralized on CEXs and most DeFi derivatives platforms, Primex Finance enables spot margin trading with decentralized trade execution. But how does the prime brokerage protocol achieve this for Traders?

The answer is rather straightforward: Primex doesn’t rely on order books or other centralized backends to execute trades.

Instead, a network of community-hosted bots called Keepers is responsible for the execution of all automated trades. Examples of the latter include Limit, Stop Loss, and Take Profit orders. Besides these, Keepers also have another important duty: to liquidate the positions of Traders that are below the maintenance margin.

With margin trading, you borrow more funds than your initial deposit to amplify your gains. While the initial deposit (also called the initial margin) is the amount of funds required to buy an asset with leverage, the maintenance margin is the sum you need to keep it open.

If this position falls below the maintenance margin, it poses a risk to Lenders whose funds Traders are borrowing to open leveraged trades via Primex. To protect their assets and ensure the stability of the protocol, Keepers automatically liquidate unprofitable positions.

Keepers allow trade execution to remain completely decentralized for both non-leveraged and margin trades on the protocol. At the same time, Primex doesn’t use any derivatives to facilitate leveraged trading. Instead, every trade takes place on the spot market.

Primex is also a non-custodial protocol where all ecosystem participants (e.g., Traders, Lenders, Keepers) have full control over their funds while utilizing the platform. Instead of an intermediary like a CEX provider, smart contracts connect Lenders directly with Traders without any third parties.

Furthermore, Primex is not competing with decentralized exchanges. Instead, it works on top of them across multiple blockchains to enable margin trading for users. This way, the protocol unifies liquidity in the DeFi market.

In a similar sense, Primex is not a direct competitor to decentralized derivatives platforms either. This is because spot leverage is more like a complementary tool for traders than something that is set to challenge the massive crypto derivatives market, where $223 billion of contracts were traded in the last 24 hours (June 6, 2023 data). For example, you may trade BTC futures on a decentralized derivatives platform while maintaining open leveraged spot positions on Primex for wBTC or other assets.

Example Margin Trade

Considering the above, how does decentralized trade execution work on Primex?

Let’s say you are a Trader seeking to set up a buy Limit order of 1 wBTC for 28,000 USDC on Primex with 5x leverage.

So, you connect your wallet to Primex and create the Limit order. As the last step, you sign the transaction in your wallet.

Since wBTC is trading at 29,000 USDC, your order won’t be executed until the wBTC price falls down to 28,000 USDC or below. When the latter happens, Keepers will execute your order with the following conditions:

  1. Your initial deposit is 5,600 USDC, which is transferred from your wallet to a Primex smart contract and becomes locked when you create the order.
  2. The remaining amount (22,400 USDC) is borrowed from Lenders at a 10% Borrowing Annual Rate (BAR). Automatically recalculated after each change to the supply and demand, this rate determines the interest you have to pay to Lenders on borrowed funds.
  3. You will also pay a small protocol fee for utilizing the Primex infrastructure (e.g., 20 USDC), depending on the size of your position. This fee is locked when you create the Limit order, and it’s taken by the protocol after execution.

After your position is opened, it can be closed in three possible ways:

  1. Manual closing: You close the position manually, either completely or partially. After repaying the debt to Lenders, the assets held in the smart contract are returned to your wallet. You can either realize a profit or minimize your losses with manual closing.
  2. Conditional closing: On Primex, you can optionally set up a Stop Loss (SL) and a Take Profit (TP) order for your position to manage your risks. When the price of the asset reaches the SL’s or the TP’s level, Keepers will automatically execute the trade, closing your position, compensating Lenders, and returning your funds to your wallet.
  3. Liquidation: In case your position falls below the maintenance margin, it will trigger an automatic liquidation by Keepers, who will sell the assets in your initial deposit to cover fees and repay the debt to Lenders.

As you can see, you remained in full control over your funds throughout the process without any counterparty risks. Simultaneously, trade execution was completely decentralized through Primex’s network of Keepers. Also, you traded crypto assets with leverage on the spot market without relying on derivatives.

Yes to Transparency, No to Manipulation

To ensure the transparency of digital asset trading and protect traders from market manipulation, trade execution must remain decentralized. While this is something that has already been achieved for non-leveraged trades by DeFi protocols, margin trades are executed in a centralized manner through order books on both CEXs and DEXs.

Meanwhile, market players are relying on derivatives that come with increased regulatory complexity and a difference between the spot and the contract price. Also, they don’t offer traders full control and ownership over the underlying assets during the trading process.

As a pioneer in this field, Primex enables non-custodial margin trading on its protocol on the spot market. This means that you have full control over the funds in your wallet, and you are trading real digital assets, not derivatives tracking their prices.

Most importantly, Primex’s network of Keepers ensures that trade execution remains completely decentralized on the protocol. Primex doesn’t host any order books or other centralized backends. Instead, everything is recorded on the blockchain without anyone having the authority to manipulate Primex trades.

How to Start Trading on Primex?

With decentralized trade execution, spot margin trades, no custody over users’ funds, and compatibility with several DEXs and blockchains, Primex is a no-brainer for many Traders.

But how can you start trading on the protocol?

Let’s get started by opening the Primex app and connecting your wallet to the protocol.

After connecting your wallet, the next step is to mint testnet tokens via the faucet. Without offering any financial value, testnet coins serve testing purposes on Primex, enabling Traders to experiment with the platform and try out their strategies before the mainnet launch.

Please note that you have to be an Early User to mint testnet ETH via Primex’s built-in faucet. You can submit your application by heading to this link (it only takes a few minutes to complete). Otherwise, you will have to utilize a third-party solution to acquire testnet tokens.

When you have testnet tokens in your wallet, it’s time to navigate to the trading page.

You will find the trading widget on the right side of the page. Use it to choose whether to make a Margin, Spot 1X, or a Swap trade (you can learn more about them here) and also whether to place a Market or a Limit order.

Select the assets to trade, the decentralized exchange, and the leverage. Optionally, you can set a Take Profit and a Stop Loss to minimize your risks by automatically closing your position after the asset you bought reaches a certain price.

Choose the balance (wallet balance or protocol balance) to utilize for the trade and choose whether to turn on Expert Mode (we don’t recommend this setting for beginners, only for advanced Traders).

When you are ready, click the blue “Open Position” button (or “Swap” for Swap trades) near the bottom of the widget to initiate the trade. As the last step, confirm the action in your wallet.

Unless you have set a Stop Loss or a Take Profit for your order — or it has already been liquidated by a Keeper due to falling below the maintenance margin – you may want to close your position to realize profits or minimize your losses.

You can do that by clicking the “Close Position” button next to an open position, tapping “Close Position” again in the next window, and confirming the transaction via your wallet.

--

--