# Market Contracts

## GammaTradeMarket

This contract represents the market for trading gamma-related financial instruments. It facilitates the execution of trades, auto-hedging, and closing of positions involving gamma exposure.

<figure><img src="https://2254474065-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fc0gVul8aBiXybg5yIkLr%2Fuploads%2FAAeRm0RSOMSo6HvySgQd%2FScreenshot%202024-05-25%20at%202.53.36.png?alt=media&#x26;token=e9e29f36-5a9f-4410-93f0-bd3eba036965" alt="" width="375"><figcaption><p>Squart and short ETH position PnL</p></figcaption></figure>

### executeTrade

This function processes a trader's order and executes perpetual and Squart contract trades on PredyPool. The function is called by the Filler, and the trader's signature is verified using Permit2. The method of token exchange is set by the Filler as `settlementParams`.

Please also refer to [the activity diagram](https://docs.predy.finance/predy-v6/architecture/flowchart#gammatrademarket.executetrade).

#### GammaOrder

GammaOrder is the first argument of `executeTrade` function.

Here is an explanation of the GammaOrder: `info` contains common order information. The `pairId` specifies the pair ID registered in Predy, while the `positionId` designates the vault ID or sets it to 0 to create a new one. The `entryTokenAddress` indicates the address of the quote token. The `quantity` and `quantitySqrt` represent the quantity for perpetual contracts. The `marginAmount` is the amount of margin to be deposited, with negative values indicating a withdrawal. The `baseSqrtPrice` is the base price used to calculate the acceptable price, and the `slippageTolerance` defines the allowable slippage. `leverage` is stored as metadata and is not used. Finally, `modifyInfo` contains hedge trigger information.

```solidity
struct GammaOrder {
    OrderInfo info;
    uint64 pairId;
    uint256 positionId;
    address entryTokenAddress;
    int256 quantity;
    int256 quantitySqrt;
    int256 marginAmount;
    uint256 baseSqrtPrice;
    uint32 slippageTolerance;
    uint8 leverage;
    GammaModifyInfo modifyInfo;
}
```

Here is an explanation of the GammaModifyInfo: If `isEnabled` is true, subsequent updates will be enabled; if false, the following values will be ignored. The `expiration` represents the position's validity period. `maximaDeviation` is the value used to adjust the target delta when performing delta hedging. `lowerLimit` is the lower price limit that triggers an automatic close, and `upperLimit` is the upper price limit. `hedgeInterval` specifies the delta hedging interval in seconds. `sqrtPriceTrigger` indicates the price change threshold that triggers hedging. `minSlippageTolerance` and `maxSlippageTolerance` define the minimum and maximum allowable slippage, respectively. `auctionPeriod` is the duration of the Dutch auction, and `auctionRange` is a parameter for the Dutch auction relative to the price trigger.

```solidity
struct GammaModifyInfo {
    bool isEnabled;
    uint64 expiration;
    int64 maximaDeviation;
    uint256 lowerLimit;
    uint256 upperLimit;
    uint32 hedgeInterval;
    uint32 sqrtPriceTrigger;
    uint32 minSlippageTolerance;
    uint32 maxSlippageTolerance;
    uint16 auctionPeriod;
    uint32 auctionRange;
}
```

### modifyAutoHedgeAndClose

This function processes a trader's modify order to update auto close and auto hedge condition.

### autoHedge

This function automatically hedges the trader's position to manage gamma risk. It adjusts the position to maintain the desired risk profile. There are time triggers and price triggers that activate this function.

### autoClose

This function automatically closes trader positions whose expiration is less than or equal to the current block time. It ensures that expired positions are safely and efficiently closed.

### quoteTrade

This function returns the estimate of an order as a revert message.

### checkAutoHedgeAndClose

This function checks the conditions for auto-hedging and auto-closing.&#x20;

## PerpMarket

This contract represents the perpetual market where continuous trading of perpetual contracts occurs. It facilitates the execution of trades and management of positions without an expiration date, allowing users to hold positions indefinitely.

### executeOrderV3

This function processes a trader's order and executes perpetual contract trades on the PredyPool. It calculates the initial margin based on the specified leverage and ensures the position is in a safe state. The order is validated using the `permitWitnessTransferFrom` function from Permit2 for signature verification. Please also refer to [the activity diagram](https://docs.predy.finance/predy-v6/architecture/flowchart#perpmarket.executeorderv3).

#### PerpOrderV3

PerpOrderV3 is the first argument of `executeOrderV3` function.

The `info` contains common order information. The `pairId` specifies the pair ID registered in Predy. The `entryTokenAddress` indicates the address of the quote token. `quantity` represents the quantity for perpetual contracts. `marginAmount` is the maximum amount of margin to be deposited. `limitPrice` specifies the acceptable price for the trade, while `stopPrice` specifies the stop price that triggers the trade. `leverage` determines the amount of margin relative to the trade quantity, with higher values increasing the liquidation risk. If `reduceOnly` is true, the order can only reduce the position size. If `closePosition` is true, the position will be reduced to zero. `auctionData` contains parameters for the Dutch auction in market orders or stop orders. If both `limitPrice` and `stopPrice` are set to 0, the order is processed as a market order.

```solidity
struct PerpOrderV3 {
    OrderInfo info;
    uint64 pairId;
    address entryTokenAddress;
    string side;
    uint256 quantity;
    uint256 marginAmount;
    uint256 limitPrice;
    uint256 stopPrice;
    uint8 leverage;
    bool reduceOnly;
    bool closePosition;
    bytes auctionData;
}
```

The required initial margin is determined as follows.

```
InitialMargin = (amount of perp) * price / leverage - (position value after trade)
```

### quoteExecuteOrderV3

This function returns the estimate of an order as a revert message. It is designed to always revert.
