# Perpetuals

## <mark style="color:blue;">Overview</mark>

**Perpetual Trading Explained:**&#x20;

The Elys Network's perpetual trading is a system designed to facilitate leveraged trading on various assets within the blockchain.

<figure><img src="https://723411151-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FYSf8pZaRovewz0yJFl0a%2Fuploads%2FA4b0MJ6ULfkkZ8G4wrZa%2Fimage.png?alt=media&#x26;token=44696c6c-c5f1-445b-90fa-b15ac35cfe9e" alt=""><figcaption></figcaption></figure>

## <mark style="color:blue;">How it Works</mark>

This system integrates several components, including the **module** itself, the **keeper, specification**, and **types**, to ensure seamless operation and high-level security across all transactions.

The core integration point of the perpetual trading **module** is responsible for managing the state of the perpetual contracts, processing transactions, and interfacing with other modules in the network. It acts as the backbone of the perpetual trading system, ensuring that all actions taken by users are securely recorded and executed according to the defined logic.

The specific responsibility for initializing the perpetual trading logic is handled by the **BeginBlocker** function within the **Keeper**. This function is triggered at the beginning of each block and performs critical operations, such as

checking whether a new epoch has begun

* Computing borrow interest rates
* Updating the health of margin trading positions (MTPs)
* and processing funding fees.&#x20;

This ensures that the system remains up-to-date and responsive to changes in the market.

Transactions within the perpetual trading module follow a well-defined lifecycle, ensuring network protocol compliance and system integrity.&#x20;

* When a transaction is initiated, it undergoes validation to ensure that it meets all necessary conditions, such as having sufficient collateral and being authorized (if whitelisting is enabled).&#x20;
* Once validated, the Keeper executes the transaction, which updates the state of the involved positions and pools accordingly.
* Queries are handled by the Keeper as well, providing users and system administrators with real-time information about the status of their positions, system health, and other key metrics.

The business logic of the perpetual trading module is intricately designed to oversee risk management, risk assessments, and collateral tracking.&#x20;

The module ensures that all open positions are adequately collateralized through a margin system.&#x20;

It continuously monitors the health of each position and automatically triggers liquidations when necessary to protect the platform and its users. The module also implements a funding rate mechanism to maintain the alignment of perpetual contract prices with the underlying spot prices, balancing long and short exposures in the market.

The code specifications from the keeper, spec, and types define the blueprint for how the perpetual trading system operates. These include&#x20;

* The **Keeper**'s methods for managing positions, pools, and transactions
* The **Spec** that outlines the module's configuration and key parameters
* The **Types** that define the data structures used throughout the module.&#x20;

These components create a flexible and secure environment for perpetual trading, allowing users to leverage their positions, manage risks, and interact with the system efficiently.

In summary, the blueprint provided by the code specifications ensures that the module operates seamlessly, offering a reliable platform for users to engage in perpetual trading.

## <mark style="color:blue;">How is it the Same as Other Perpectual Platforms?</mark>

The Elys Perpectual Trading system shares several common features with other platforms:

* **Leverage Trading:** Users can increase their exposure to certain assets by borrowing funds.
* **Risk Management:** The system includes measures like margin requirements and automatic liquidation to protect users.

## <mark style="color:blue;">How is it Different from Other Perpetual Platforms?</mark>

Elys stands out due to its deep integration within the Cosmos ecosystem, which enables superior interoperability and scalability.&#x20;

By leveraging the Cosmos SDK and Tendermint, Elys ensures lower transaction costs and faster processing times while seamlessly connecting with other Cosmos-based networks. Elys places a strong emphasis on decentralized risk management, incorporating features like dynamic interest rate adjustments and real-time pool health monitoring. These tools provide traders with granular control over their positions, offering enhanced flexibility and security.&#x20;

This focus on dynamic, decentralized management tools makes Elys an optimal choice for traders looking to refine their strategies in a multi-chain environment.

## <mark style="color:blue;">Why Would I Want to Use the Elys Perpetual Trading System?</mark>

Choosing the Elys Perpetual Trading System offers several compelling advantages, particularly for experienced traders. The platform's foundation on the Cosmos SDK and Tendermint provides a robust security framework, ensuring that your trades are safeguarded within a highly secure network. Unlike traditional platforms, Elys leverages blockchain technology to deliver complete transparency, allowing you to trust in the fairness and security of every transaction. Furthermore, Elys offers unparalleled flexibility by allowing you to hold positions indefinitely, giving you the freedom to tailor your investment strategies without the pressure of expiration dates. The platform's advanced features, including decentralized oracles and smart contracts, integrate cutting-edge technology into your trading experience, offering a modern and efficient environment that enhances your trading capabilities.

## <mark style="color:blue;">Detailed Components Overview</mark>

#### <mark style="color:blue;">**Order Processing**</mark>

**Order Types Supported**: Limit orders, market orders, and stop-loss orders are processed differently, each with specific logic paths in the system. These orders are essential for flexible and strategic trading, allowing users to manage their positions effectively.

#### <mark style="color:blue;">**Price Calculation and Updates**</mark>

**Decentralized Oracles:** Prices are updated by fetching data from decentralized oracles, which aggregate price feeds from multiple sources to mitigate the risk of price manipulation. This ensures that the prices of perpetual contracts and spot assets remain aligned, maintaining fair and accurate market conditions.

#### <mark style="color:blue;">**Leverage and Margin Handling**</mark>

**Leverage Calculation:** Leverage is applied based on user account settings and the asset being traded. Users can select leverage levels, which determine the amount of borrowed capital relative to their own investment.

**Margin Requirements:** The system dynamically calculates margin requirements to prevent undercollateralization, ensuring users maintain sufficient collateral to cover potential losses. This calculation is crucial for protecting both the user and the platform from excessive risk.

#### <mark style="color:blue;">**Open Interest Management**</mark>

**Open Interest Management:** Open interest is managed by tracking the total number of outstanding contracts held by market participants. The system ensures that the net open interest is balanced to prevent excessive exposure in one direction, utilizing funding rates to incentivize traders to take opposing positions.

#### <mark style="color:blue;">**Funding Rate Calculation**</mark>

**Funding Calculation:** The primary purpose of the funding rate is to balance the open interest (OI) rather than to converge the prices of spot and perpetual contracts. Since we use oracle prices, the prices of perpetual contracts and spot assets are always aligned. If the net position of all traders is long on an asset, it means the pool is short on that asset. To encourage traders to take the opposite position and balance the pool, the funding rate incentivizes traders accordingly. For instance, if the net OI is long, long position holders will pay a funding rate to short position holders, and vice versa.

#### <mark style="color:blue;">**Scalability Beyond Pool Liquidity**</mark>

**Scalability Beyond Pool Liquidity:** The architecture scales beyond the pool liquidity by dynamically adjusting leverage and margin requirements based on pool health. This approach ensures that the system can handle large trading volumes without compromising liquidity. Additionally, the use of decentralized oracles ensures that the pricing mechanism remains robust even under high load.

#### <mark style="color:blue;">**Health Calculation**</mark>

**Health Calculation:** The health of a position is continuously monitored by the system, which evaluates the collateral against the required margin. The system uses real-time data to assess the risk and adjust the leverage and margin requirements accordingly. This ongoing assessment helps prevent undercollateralization and ensures the stability of the trading environment.

#### <mark style="color:blue;">**Stop Loss and Liquidation Triggers**</mark>

**Stop Loss Trigger:** A stop-loss order is triggered when the market price of an asset reaches a specified level, automatically closing the position to prevent further losses. This mechanism protects traders from significant downside risk.

**Liquidation Trigger:** Positions that fall below margin requirements are automatically liquidated to ensure the system remains solvent and users do not incur more losses than their collateral can cover. The system continuously monitors each position's collateral and required margin, triggering liquidation if the collateral is insufficient.

## <mark style="color:blue;">FAQ</mark>

#### <mark style="color:blue;">How is Open Interest Managed?</mark>

Open interest is managed through funding rates that incentivize traders to take opposing positions. If the net position of all traders is long, the pool is short, and funding rates are adjusted to encourage short positions, balancing the open interest.

#### <mark style="color:blue;">How is Funding Calculated?</mark>

Funding rates are calculated based on the net open interest. If the net position is long, long position holders pay a funding rate to short position holders, and vice versa. This is designed to balance the open interest and ensure the pool's neutrality.

#### <mark style="color:blue;">How Does This Architecture Scale Beyond Pool Liquidity While Using Pools?</mark>

The architecture scales by dynamically adjusting leverage and margin requirements based on the pool's liquidity. This ensures that the pool can handle larger positions without compromising stability. Additionally, decentralized oracles ensure accurate pricing and real-time adjustments.

#### <mark style="color:blue;">How is Health Calculated?</mark>

Pool health is calculated using a function H(X)H(X)H(X), which takes into account the pool's assets, liabilities, and overall liquidity. This ensures that the pool remains solvent and can cover all positions.

#### <mark style="color:blue;">How is Stop Loss Triggered?</mark>

Stop loss is triggered when the market price reaches a predefined level set by the trader. The system monitors the market in real-time and executes the stop-loss order to limit potential losses.

#### <mark style="color:blue;">How is Liquidation Triggered?</mark>

Liquidation is triggered when a position's collateral falls below the required margin. The system continuously monitors the position's health and automatically liquidates it if the collateral is insufficient to cover potential losses.

## <mark style="color:blue;">Flow Explanation</mark>

#### <mark style="color:blue;">Opening a Position</mark>

When a user wants to open a position on the Elys platform:

1. **Initiating a Trade:**
   1. The user navigates to the trading interface where they can select the asset they want to trade.
   2. They choose whether to go long (expecting the price to rise) or short (expecting the price to fall) and specify the leverage they want to use.
2. **Entering Trade Details:**
   1. The user inputs the amount of collateral they want to use for the trade. The system will automatically calculate the potential position size based on the chosen leverage.
   2. If the user is satisfied with the details, they can proceed to execute the trade.
3. **Trade Execution:**
   1. Once the trade is executed, the system performs all the necessary backend operations, such as calculating the required swap amounts, updating the pool balances, and setting up the MTP (Margin Trading Position).
   2. The system uses decentralized oracles to fetch the latest price data and ensure that the trade is executed at a fair market price.
4. **Monitoring the Position:**
   1. After the position is open, the user can monitor it through the dashboard. They can see all the critical information, such as the current value of the position, collateral, liabilities, and health metrics.
   2. The platform provides real-time updates, allowing the user to track how their position is performing relative to market movements.

#### <mark style="color:blue;">Managing an Open Position</mark>

1. **Adjusting or Closing a Position:**
   1. If the market conditions change or the user wants to take profits, they can easily adjust their position by adding more collateral, reducing leverage, or setting stop-loss and take-profit levels.
   2. To close a position, the user simply clicks on the "Close Position" button, which initiates the closing process. The system calculates the necessary swaps and updates the pool and MTP accordingly.
2. **Handling Liquidations:**
   1. If the position’s health falls below a certain threshold, the system will automatically initiate a liquidation process to protect the user and the platform from further losses. This is done seamlessly without requiring user intervention, but the user is notified and can monitor the liquidation process.

#### <mark style="color:blue;">Viewing Key Information</mark>

* Dashboard Overview:
  * The dashboard provides a comprehensive view of all open positions, showing real-time data on profits/losses, funding rates, and more.
  * Users can also view their whitelisted status and any system notifications that might affect their trading strategy.

#### <mark style="color:blue;">Closing Remarks</mark>

This flow ensures that users, especially those already familiar with perpetual trading platforms, can intuitively understand how to operate on Elys. The seamless integration of decentralized technologies, real-time data, and advanced trading tools provides a robust platform that meets the needs of sophisticated traders while maintaining ease of use.

\
