๐Ÿ’ปAPI

This document primarily contains guidelines and technical documentation for MYX smart contracts. You can utilize these documents to understand the MYX protocol smart contracts and develop on-chain integrations.

General API Information

Apis

  • List of Trading Pairs

GET /v2/quote/market/contracts

Retrieve all contract trading pairs

Parameters: None

Response:

{
  "code": 0,
  "msg": "Success",
  "data": [
    {
      "contract_index": 1,
      "ticker_id": "BTC-USDC", //Identifier of a ticker with delimiter to separate base/target, eg. BTC-PERP
      "base_currency": "BTC", //Symbol/currency code of base pair, eg. BTC
      "target_currency": "USDC", //Symbol/currency code of target pair, eg. ETH
      "last_price": 61681.74480976, //Last transacted price of base currency based on given target currency
      "base_volume": 1758.7498, //24 hour trading volume in base pair volume
      "target_volume": 108836479.78206, //24 hour trading volume in target pair volume
      "high": 62748.59803949, //Rolling 24-hours highest transaction price
      "low": 61133.51105089, //Rolling 24-hours lowest transaction price
      "product_type": "Perpetual", //What product is this? Futures, Perpetual, Options?
      "open_interest": 3.827820648391355e+51, //The open interest in the last 24 hours in contracts
      "index_price": 61681.74480976, //Underlying index price
      "index_name": "BTC", //Name of the underlying index if any
      "index_currency": "USDC", //Underlying currency for index
      "funding_rate": 0.00003708, //Current funding rate
      "next_funding_rate": 0.00002753, //Upcoming predicted funding rate
      "next_funding_rate_timestamp": 1715738400000 //Timestamp of the next funding rate change
    }
  ]
}
  • Description of Trading Pairs

GET /v2/quote/market/contract_specs

Retrieve all contract trading pair descriptions

Parameters:

Response:

{
  "code": 0,
  "msg": "Success",
  "data": {
    "contract_type": "Vanilla", //Describes the type of contract - Vanilla, Inverse or Quanto?
    "contract_price_currency": "USDC", //Describes the currency which the contract is priced in.
    "contract_price": 61829.72380263 //Describes the price per contract. (If not same as last price)
  }
}

Liquidity Management:

Users can manage liquidity by interacting with the Pool contract, enabling liquidity management through the Pool.

Add Liquidity

// Router.sol
function addLiquidity(
    address indexToken,
    address stableToken,
    uint256 indexAmount,
    uint256 stableAmount,
    address[] calldata tokens,
    bytes[] calldata updateData,
    uint64[] calldata publishTimes
) external payable returns (uint256 mintAmount, address slipToken, uint256 slipAmount)
  • When adding liquidity, the indexToken and stableToken need to be approved to the Router contract. The contract will then transfer the corresponding LP token quantity to the user based on their input.

  • The user adding liquidity is the process of the user purchasing MLP. The contract will allocate the corresponding MLP of the trading pair to the user based on the current balance of the pool and the set fee. MLP is an ERC20 token.

Adding liquidity for others:

// Router.sol
function addLiquidityForAccount(
    address indexToken,
    address stableToken,
    address receiver,
    uint256 indexAmount,
    uint256 stableAmount,
    address[] calldata tokens,
    bytes[] calldata updateData,
    uint64[] calldata publishTimes
) external payable returns (uint256 mintAmount, address slipToken, uint256 slipAmount)
  • A parameter called "receiver" is defined. After adding liquidity, the acquired MLP can be sent directly to the receiver.

Add liquidity, using ETH:

// Router.sol
function addLiquidityETH(
    address indexToken,
    address stableToken,
    uint256 indexAmount,
    uint256 stableAmount,
    address[] calldata tokens,
    bytes[] calldata updateData,
    uint64[] calldata publishTimes,
    uint256 updateFee
) external payable whenNotPaused nonReentrant returns (uint256 mintAmount, address slipToken, uint256 slipAmount)
Params: 
indexToken: indexToken, for example BTC, ETH
stableToken: Address of the stableToken, currently support USDT
indexAmount: Quantity of index Token
stableAmount: Quantity of the stable Token
tokens: Token address of the trading pair
updateData๏ผšPyth price update data
publishTimes๏ผšPyth price publication time
updateFee: Update Pyth price fee

Returns:
mintAmount: Quantity of minted LP tokens
slipToken: Collected slippage tokens
slipAmount: Quantity of the collected slippage tokens

Removing Liquidity

// Router.sol
function removeLiquidity(
    address indexToken,
    address stableToken,
    uint256 amount,
    bool useETH,
    address[] calldata tokens,
    bytes[] calldata updateData,
    uint64[] calldata publishTimes
) external payable returns (uint256 receivedIndexAmount, uint256 receivedStableAmount, uint256 feeAmount)
  • Removing liquidity is the process of users redeeming tokens. According to the pool's desired weight, more of the undisired tokens will be paid to users.

  • When a portion of tokens in the liquidity pool is locked, which results in an insufficient quantity of tokens, the redeeming operation will pay more of the available tokens. In case that the assets available for this operation are insufficient due to the reserve of assets, the transaction fails.

Removing Liquidity and Specifying Another Receiver

// Router.sol
function removeLiquidityForAccount(
    address indexToken,
    address stableToken,
    address receiver,
    uint256 amount,
    bool useETH,
    address[] calldata tokens,
    bytes[] calldata updateData,
    uint64[] calldata publishTimes
) external payable returns (uint256 receivedIndexAmount, uint256 receivedStableAmount, uint256 feeAmount)
  • A additional parameter called "receiver" is defined. After removing liquidity, the corresponding tokens will be sent to the receiver's address.

Params:
indexToken: indexToken, for example BTC, ETH
stableToken: Address of the stableToken, currently support USDT
amount: The amount of MLP the user wishes to remove
useETH: Whether to receive ETH, true for ETH, false for WETH
receiver: Receiver
tokens: Token address of the trading pair
updateData๏ผšPyth price update data
publishTimes๏ผšPyth price publication time

Returns:
receivedIndexAmount: Amount of indexToken received
receivedStableAmount๏ผšAmount of stableToken received
feeAmount๏ผšFee amount

Multicall Contract

Router inherits from the Multicall contract. Its main function is to allow calling multiple methods of a contract in a single transaction.

// Multicall.sol
function multicall(
    bytes[] calldata data
) external payable returns (bytes[] memory results);
// call in typescript
await multicallContract.multicall([multicall.interface.encodeFunctionData('method', ['param1', 'param2'])]);

Support for ETH

  • ETH support is implemented through Multicall. When adding liquidity, first call wrapETH, transfer the corresponding ETH to receive the corresponding WETH. addLiquidity is called simultaneously.

Position Management

Users can place orders through the Router, and the orders will be stored in the OrderManager contract. The Keeper will monitor placed orders and execute those that meet the conditions.

Retrieve Trading Pair Index

// Pool.sol
function getPairIndex(
    address indexToken, 
    address stableToken
) external view returns (uint256);
  • Retrieve the pairIndex using indexToken and stableToken. The pairIndex will be required for subsequent contract parameters.

Opening Positions or Managing Existing Positions

// Router.sol
function createIncreaseOrder(
    TradingTypes.IncreasePositionRequest memory request
) external returns (uint256 orderId)๏ผ›

// struct
struct IncreasePositionRequest {
    address account  // Will be automatically set to the address of the transaction sender
    uint256 pairIndex; // Trading pair ID
    TradeType tradeType;
    int256 collateral; // 1e18๏ผŒCollateral amount, a positive number indicates adding, and a negative number indicates reducing and withdrawing
    uint256 openPrice; // 1e30, Opening price
    bool isLong; // Open long/Open short
    uint256 sizeAmount; // Order size
    uint256 maxSlippage; // Maximum slippage allowed for the transaction to execute
    NetworkFeePaymentType paymentType; // Network fee payment method๏ผˆ0: eth 1: usdc๏ผ‰
    uint256 networkFeeAmount; // Amount of network fee
}

enum TradeType {
    MARKET,//Market order
    LIMIT,//Limit order
    TP,//Take profit order
    SL //Stop loss order
}
enum NetworkFeePaymentType {
    ETH,
    COLLATERAL

Open a position and set take-profit and stop-loss

// Router.sol
function createIncreaseOrderWithTpSl(
    TradingTypes.IncreasePositionWithTpSlRequest memory request
) external returns (uint256 orderId)

// struct
struct IncreasePositionWithTpSlRequest {
    address account; // Will be automatically set to the address of the transaction sender
    uint256 pairIndex; // Trading pair ID
    TradeType tradeType;
    int256 collateral; // 1e18๏ผŒCollateral amount, a positive number indicates adding, and a negative number indicates reducing and withdrawing
    uint256 openPrice; // 1e30, Opening price
    bool isLong; // Open long/Open short
    uint256 sizeAmount; // Order size
    uint256 tpPrice; // 1e30๏ผŒTake profit price
    uint256 tp; // Take profit amount
    uint256 slPrice; // 1e30, Stop loss price
    uint256 sl; // Stop loss amount
    uint256 maxSlippage; // Maximum slippage allowed for the transaction to execute
    NetworkFeePaymentType paymentType; // Network fee payment method๏ผˆ0: eth 1: usdc๏ผ‰
    uint256 networkFeeAmount; // Amount of network fee
    uint256 tpNetworkFeeAmount; // Amount of network fee for take profit orders
    uint256 slNetworkFeeAmount; // Amount of network fee for stop loss orders
}

Decreasing or Closing a Position

// Router.sol
function createDecreaseOrder(
    TradingTypes.DecreasePositionRequest memory request
) external returns (uint256);

// struct
struct DecreasePositionRequest {
    address account; // Will be automatically set o the account of the transaction sender
    uint256 pairIndex; // Trading pair ID
    TradeType tradeType;
    int256 collateral; // 1e18๏ผŒCollateral amount, a positive number indicates adding, and a negative number indicates reducing and withdrawing
    uint256 triggerPrice; // 1e30, Trigger price
    uint256 sizeAmount; // Order size
    bool isLong; // Open long/Open short
    uint256 maxSlippage; // Maximum slippage allowed for the transaction to execute
    NetworkFeePaymentType paymentType; // Network fee payment method๏ผˆ0: eth 1: usdc๏ผ‰
    uint256 networkFeeAmount; // Amount of network fee
}

Creating Multiple Decrease Orders

function createDecreaseOrders(
    TradingTypes.DecreasePositionRequest[] memory requests
) external returns (uint256[] memory orderIds)๏ผ›
  • The parameter is an array of DecreasePositionRequest.

Limit Orders

  • For limit orders, set the TradeType to LIMIT and specify the price. You can set limit orders for opening, adding, or reducing positions.

Cancel Order

// Router.sol
function cancelOrder(
    CancelOrderRequest memory request
) external;

// struct
struct CancelOrderRequest {
    uint256 orderId; // Order ID
    TradingTypes.TradeType tradeType;
    bool isIncrease; // Increase/Decrease
}

Order Execution

  • The keeper will monitor all orders and execute them when conditions are met. The keeper-related contract mechanism will be introduced in the keeper document.

Get Positions Info

The user's address, trading pair index, and whether the user is going long or short serve as keys to the user's position.

function getPositionKey(
    address _account, 
    uint256 _pairIndex, 
    bool _isLong
) internal pure returns (bytes32)

Get information on the user's position

function getPosition(
    address _account,
    uint256 _pairIndex,
    bool _isLong
) public view returns (Position.Info memory)๏ผ›

// Position.Info
struct Info {
    address account; // Account address
    uint256 pairIndex; // Trading pair ID
    bool isLong; // Open long/Open short
    uint256 collateral; // Total collateral amount of the position
    uint256 positionAmount; // Total position size
    uint256 averagePrice; // Average position price
    int256 fundingFeeTracker; // Funding rate tracker of the position
}

The Router provides an option to cancel all orders in its position.

function cancelPositionOrders(
    uint256 pairIndex,
    bool isLong,
    bool isIncrease
) external;

Transaction Fee

A transaction fee will be charged when trade is executed.

  • When there are more long open interest than short, and a user goes long: a taker fee is charged. When there are more long open interest than short, and a user goes short: a maker fee is charged. When there are more short open interest than long, and a user goes short: a taker fee is charged. When there are more short open interest than long, and a user goes long: a maker fee is charged.

VIP and Commissions

The protocol supports VIP and commissions. For details on these two, please refer to the relevant VIP document.

To claim VIP return fees and commissions, you can directly call the claimUserTradingFee method in the FeeCollector contract.

// FeeCollector.sol
function claimUserTradingFee() external;

Last updated