# Concepts
The exchange
module is to support exchange of tokens where it has two types of markets, Derivative Market
and Spot Market
.
Derivative Market
consists of Perpetual Swap Market
and Futures Market
.
# Derivative Market
# Definitions
In a derivative market using linear contracts (as opposed to inverse contracts), a contract with ticker AAA/BBB offers exposure to the underlying AAA using the quote currency BBB for margin and settlement. For each contract, the quotation unit is the BBB price of one unit of AAA, e.g. the USDT price of one unit of ETH.
Notional - the notional value of a position is: \mathrm
Refunds - In our clearing system, a refund refers to the action of incrementing the available balance of an account. This liberation of funds occurs as the result of an encumbrance being lifted from the account (e.g. cancelling a limit order, reducing an order's payable fee to a maker fee, using less margin to fund a market order, etc.).
# Perpetual Market Trading Lifecycle
# Perpetual Market Creation
- InitialMarginRatio
- MaintenanceMarginRatio
- CumulativeFunding
# Balance Management
# Depositing Funds into Exchange
A trader can deposit funds (e.g. USDT) into the exchange by sending a MsgDeposit which transfers coins from the Cosmos-SDK bank module to the trader's subaccount deposits on the exchange module.
Depositing a given Amount
of coin will increment both the trader's subaccount deposit AvailableBalance
and TotalBalance
by Amount
.
# Withdrawing Funds from Exchange
A trader can withdraw funds from the exchange by sending a MsgWithdraw which transfers coins from the trader's subaccount on the exchange module.
Withdrawal Requirement: Withdrawing a given Amount
of coin will decrement both the trader's subaccount
deposit AvailableBalance
and TotalBalance
by Amount
. Note: Amount
must be less than or equal
to AvailableBalance
.
# Transferring Funds between Subaccounts
A trader can transfer funds between his own subaccounts sending a MsgSubaccountTransfer which transfer coins from one of the trader's subaccount deposits to another subaccount also owned by the trader.
Subaccount transfers have the same Withdrawal Requirement as normal withdrawals.
# Transferring Funds to another Exchange Account
A trader can transfer funds to an external account by sending a MsgExternalTransfer which transfers funds from the trader's subaccount to another third-party account.
External Funds transfers have the same Withdrawal Requirement as normal withdrawals.
# Order Management
# Placing Limit Orders
A trader can post a limit buy or sell order by sending a MsgCreateDerivativeLimitOrder. Upon submission, the order can be:
- Immediately (fully or partially) matched against other opposing resting orders on the orderbook in the Endblocker batch auction, thus establishing a position for the user.
- Added to the orderbook.
Note that it is possible for an order to be partially matched and for the remaining unmatched portion to be added to the orderbook.
# Placing Market Orders
A trader can post a market buy or sell order by sending a MsgCreateDerivativeMarketOrder. Upon submission, the market order will be executed against other opposing resting orders on the orderbook in the Endblocker batch auction, thus establishing a position for the user.
# Cancelling Limit Orders
User cancels a limit buy or sell order by sending a MsgCancelDerivativeOrder which removes the user's limit order from the orderbook.
# Position Management
# Increasing Position Margin
A user can increase the margin of a position by sending a MsgIncreasePositionMargin.
# Liquidating Insolvent Positions
A third party can liquidate any user's position if the position's maintenance margin ratio is breached by sending a MsgLiquidatePosition.
Maintenance Margin Requirement
Throughout the lifecycle of an active position, if the following margin requirement is not met, the position is subject to liquidation. (Note: for simplicity of notation but without loss of generality, we assume the position considered does not have any funding).
For Longs: For Shorts: \mathrm
# Funding Payments
Funding exists only for perpetual markets as a mechanism to align trading prices with the mark price. It refers to the periodic payments exchanged between the traders that are long or short of a contract at the end of every funding epoch, e.g. every hour. When the funding rate is positive, longs pay shorts. When negative, shorts pay longs.
# Perpetual Market Trading Specification
# Positions
A trader's position records the conditions under which the trader has entered into the derivative contract and is defined as follows
- Position Definition
As an example, consider the following position in the ETH/USDT market:
- Quantity = -2
- EntryPrice = 2200
- Margin = 800
- HoldQuantity = 1
- CumulativeFundingEntry = 4838123
This position represents short exposure for 2 contracts of the ETH/USDT market collateralized with 800 USDT, with an entry price of 2200. The HoldQuantity represents the quantity of the position that the trader has opposing orders for. CumulativeFundingEntry represents the cumulative funding value that the position was last updated at.
- Position Netting
Position Delta: FillQuantity, FillMargin, ClearingPrice
- Applying Position Delta to a position in the same direction
- Entry Price' ← (Quantity * EntryPrice + FillQuantity * ClearingPrice) / (Quantity + FillQuantity)
- Quantity' ← Quantity + FillQuantity
- Margin' ← Margin + FillMargin
- Apply Position Delta to a position in the opposing direction:
- Entry Price - no change
- Quantity' ← Quantity - FillQuantity
- Margin' ← Margin * (Quantity - FillQuantity) / Quantity
# Limit Buy Order
A limit buy order seeks to purchase a specified Quantity of a derivative contract at a specified Price by providing a specified amount of margin as collateral.
# Limit Sell Order
A limit sell order seeks to sell a specified Quantity of a derivative contract at a specified Price by providing a specified amount of margin as collateral.
A matched position will have subtracted fees which depend on whether the limit order becomes executed as a maker order or a taker order.
# Market Buy Order
A market buy order seeks to purchase a specified Quantity of a derivative contract at a specified worst price using the subaccount's available balance as margin collateral.
Handler and EndBlocker Execution of the market order are conceptually identical to the Limit Buy Order (Immediately Matched case), since the trader passes the margin which implicitly sets a maximum price limit due to the initial min margin requirements.
# Market Sell Order
A market sell order seeks to sell a specified Quantity of a derivative contract at a specified worst price using the subaccount's available balance as margin collateral.
Handler and EndBlocker Execution of the market order are conceptually identical to the Limit Sell Order (Immediately Matched case), since the trader passes the margin which implicitly sets a maximum price limit due to the initial min margin requirements.
# Reduce-Only Orders (Selling Positions)
# Limit Buy Reduce-Only Order
A limit buy reduce-only order seeks to reduce existing long exposure by a specified Quantity
ETH (base currency).
A reduced position will have subtracted fees for closing.
# Limit Sell Reduce-Only Order
A limit sell reduce-only order seeks to reduce existing short exposure by a specified Quantity
ETH (base currency)
. A reduced position will have subtracted fees for closing.
- FuturesLimitOrderState Definition
- High Level
# Spot Market
# Definitions
In a Spot Market with ticker AAA/BBB, AAA is the base asset, BBB is the quote asset.
For example, in the ETH/USDT market
- ETH is base asset
- USDT is the quote asset
The spot market's price refers to the how much USDT (the quote asset) is required for one unit of ETH (the base asset). For all spot markets, fees are always paid in the quote asset (e.g. USDT).
Debit vs Credit
- Debit Amount refers to the amount of asset that is withdrawn from an account.
- Credit Amount refers to the amount of asset that is deposited to an account.
Refunds
In our system, a refund refers to the action of incrementing the available balance of an account. This liberation of funds occurs as the result of an encumbrance being lifted from the account (e.g. cancelling a limit order, reducing an order's payable fee to a maker fee, using less margin to fund a market order, etc.).
# Limit Buy Order
A limit buy order seeks to buy a specified Quantity
ETH (base asset) in exchange for Quantity * Price
amount of
USDT (quote asset) plus fees which depend on whether the limit order becomes executed as a maker order or a
taker order.
# Limit Sell Order
A limit sell order seeks to sell a specified Quantity
ETH (base asset) in exchange for Quantity * Price
amount
of USDT (quote asset) minus fees which depend on whether the limit order becomes executed as a maker order or a
taker order.
# Market Buy Order
A market buy order seeks to buy a specified Quantity
ETH (base asset) at a specified worst price which is at or near the current ask using the respective
account quote asset balance (USDT) as collateral (inclusive of fees).
As a result, each market buy order implicitly has a maximum acceptable price associated with it, as filling the market order beyond that price would simply fail due to a lack of funds.
# Market Sell Order
A market sell order seeks to sell a specified Quantity
ETH (base asset) at a specified worst price which is at or near the current bid in exchange for any amount of the quote
asset (USDT) available in the market.
As a result, each market sell order implicitly has a zero price associated with it.
# Market Data Requirements
Orderbook data aside, so long as our Chain supports the base capability to obtain Tick by Tick trading data, aggregations can be applied to obtain most of the necessary higher order data, including
- OHLCV data
- Account Trading History
- Market Statistics
# Concurrency-Friendly Market Order Clearing Price Algorithm (WIP)
We apply the split-apply-combine paradigm to leverage concurrency for efficient data processing.
Note: beyond just executing settlement, the design must also take into account market data dissemination requirements for off-chain consumption.
# Spot Market Lifecycle
# Governance based Spot Market Creation
Launch a new spot market through a SpotMarketLaunchProposal
governance proposal.
- should validate that the denominations exist
# Listing Fee based Spot Market Creation
Allow anyone to create an active spot market of their choice without requiring governance approval by burning a pre-set SpotMarketInstantListingFee of INJ.
We should still check that the denom is valid of course though.
# Spot Market Status Update
A Spot Market can exist in four different states:
- Active
- Paused
- Suspended
- Demolished
# Active State
If a spot market is an active state, it can accept orders and trades.
# Paused State
If a spot market is a paused state, it will no longer accept orders and trades and will also not allow any users to take actions on that market (no order cancellations).
# Suspended State
If a spot market is a suspended state, it will no longer accept orders and trades, and will only allow traders to cancel their orders.
# Demolished State
When a market becomes demolished, all outstanding orders are cancelled.
# Market Status State Transitions
There are three state transitions that correspond to the following status changes
- Activate Action - Paused or Suspended Status → Active Status
- Pause Action - Active or Suspended Status → Paused Status
- Suspend Action - Active or Paused Status → Suspended Status
- Demolish Action - Paused or Suspended Status → Demolished Status
# Spot Market Parameter Update
The following parameters exist for Spot Markets
- SpotMarketInstantListingFee
- DefaultSpotMakerFeeRate
- DefaultSpotTakerFeeRate