# ITradingInteractionsUtils

*Interface for GNSTradingInteractions facet (inherits types and also contains functions, events, and custom errors)*

## initializeTrading

```solidity
function initializeTrading(uint16 _marketOrdersTimeoutBlocks, address[] _usersByPassTriggerLink) external
```

*Initializes the trading facet*

### Parameters

| Name                        | Type       | Description                                                             |
| --------------------------- | ---------- | ----------------------------------------------------------------------- |
| \_marketOrdersTimeoutBlocks | uint16     | The number of blocks after which a market order is considered timed out |
| \_usersByPassTriggerLink    | address\[] |                                                                         |

## updateMarketOrdersTimeoutBlocks

```solidity
function updateMarketOrdersTimeoutBlocks(uint16 _valueBlocks) external
```

*Updates marketOrdersTimeoutBlocks*

### Parameters

| Name          | Type   | Description                                 |
| ------------- | ------ | ------------------------------------------- |
| \_valueBlocks | uint16 | blocks after which a market order times out |

## updateByPassTriggerLink

```solidity
function updateByPassTriggerLink(address[] _users, bool[] _shouldByPass) external
```

*Updates the users that can bypass the link cost of triggerOrder*

### Parameters

| Name           | Type       | Description                                                      |
| -------------- | ---------- | ---------------------------------------------------------------- |
| \_users        | address\[] | array of addresses that can bypass the link cost of triggerOrder |
| \_shouldByPass | bool\[]    | whether each user should bypass the link cost                    |

## setTradingDelegate

```solidity
function setTradingDelegate(address _delegate) external
```

\_Sets *delegate as the new delegate of caller (can call delegatedAction)*

### Parameters

| Name       | Type    | Description              |
| ---------- | ------- | ------------------------ |
| \_delegate | address | the new delegate address |

## removeTradingDelegate

```solidity
function removeTradingDelegate() external
```

*Removes the delegate of caller (can't call delegatedAction)*

## delegatedTradingAction

```solidity
function delegatedTradingAction(address _trader, bytes _callData) external returns (bytes)
```

\_Caller executes a trading action on behalf of *trader using delegatecall*

### Parameters

| Name       | Type    | Description                                            |
| ---------- | ------- | ------------------------------------------------------ |
| \_trader   | address | the trader address to execute the trading action for   |
| \_callData | bytes   | the data to be executed (open trade/close trade, etc.) |

## openTrade

```solidity
function openTrade(struct ITradingStorage.Trade _trade, uint16 _maxSlippageP, address _referrer) external
```

*Opens a new trade/limit order/stop order*

### Parameters

| Name           | Type                                                                                                        | Description                                                        |
| -------------- | ----------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------ |
| \_trade        | [ITradingStorage.Trade](/developer/technical-reference/contracts/interfaces/types/itradingstorage.md#trade) | the trade to be opened                                             |
| \_maxSlippageP | uint16                                                                                                      | the maximum allowed slippage % when open the trade (1e3 precision) |
| \_referrer     | address                                                                                                     | the address of the referrer (can only be set once for a trader)    |

## openTradeNative

```solidity
function openTradeNative(struct ITradingStorage.Trade _trade, uint16 _maxSlippageP, address _referrer) external payable
```

*Wraps native token and opens a new trade/limit order/stop order*

### Parameters

| Name           | Type                                                                                                        | Description                                                        |
| -------------- | ----------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------ |
| \_trade        | [ITradingStorage.Trade](/developer/technical-reference/contracts/interfaces/types/itradingstorage.md#trade) | the trade to be opened                                             |
| \_maxSlippageP | uint16                                                                                                      | the maximum allowed slippage % when open the trade (1e3 precision) |
| \_referrer     | address                                                                                                     | the address of the referrer (can only be set once for a trader)    |

## updateMaxClosingSlippageP

```solidity
function updateMaxClosingSlippageP(uint32 _index, uint16 _maxSlippageP) external
```

*Updates existing trade's max closing slippage % for caller*

### Parameters

| Name           | Type   | Description                                |
| -------------- | ------ | ------------------------------------------ |
| \_index        | uint32 | index of trade                             |
| \_maxSlippageP | uint16 | new max closing slippage % (1e3 precision) |

## closeTradeMarket

```solidity
function closeTradeMarket(uint32 _index, uint64 _expectedPrice) external
```

*Closes an open trade (market order) for caller*

### Parameters

| Name            | Type   | Description                                                         |
| --------------- | ------ | ------------------------------------------------------------------- |
| \_index         | uint32 | the index of the trade of caller                                    |
| \_expectedPrice | uint64 | expected closing price, used to check max slippage (1e10 precision) |

## updateOpenOrder

```solidity
function updateOpenOrder(uint32 _index, uint64 _triggerPrice, uint64 _tp, uint64 _sl, uint16 _maxSlippageP) external
```

*Updates an existing limit/stop order for caller*

### Parameters

| Name           | Type   | Description                                            |
| -------------- | ------ | ------------------------------------------------------ |
| \_index        | uint32 | index of limit/stop order of caller                    |
| \_triggerPrice | uint64 | new trigger price of limit/stop order (1e10 precision) |
| \_tp           | uint64 | new tp of limit/stop order (1e10 precision)            |
| \_sl           | uint64 | new sl of limit/stop order (1e10 precision)            |
| \_maxSlippageP | uint16 | new max slippage % of limit/stop order (1e3 precision) |

## cancelOpenOrder

```solidity
function cancelOpenOrder(uint32 _index) external
```

*Cancels an open limit/stop order for caller*

### Parameters

| Name    | Type   | Description                         |
| ------- | ------ | ----------------------------------- |
| \_index | uint32 | index of limit/stop order of caller |

## updateTp

```solidity
function updateTp(uint32 _index, uint64 _newTp) external
```

*Updates the tp of an open trade for caller*

### Parameters

| Name    | Type   | Description                           |
| ------- | ------ | ------------------------------------- |
| \_index | uint32 | index of open trade of caller         |
| \_newTp | uint64 | new tp of open trade (1e10 precision) |

## updateSl

```solidity
function updateSl(uint32 _index, uint64 _newSl) external
```

*Updates the sl of an open trade for caller*

### Parameters

| Name    | Type   | Description                           |
| ------- | ------ | ------------------------------------- |
| \_index | uint32 | index of open trade of caller         |
| \_newSl | uint64 | new sl of open trade (1e10 precision) |

## triggerOrder

```solidity
function triggerOrder(uint256 _packed) external
```

*Initiates a new trigger order (for tp/sl/liq/limit/stop orders)*

### Parameters

| Name     | Type    | Description                                                     |
| -------- | ------- | --------------------------------------------------------------- |
| \_packed | uint256 | the packed data of the trigger order (orderType, trader, index) |

## cancelOrderAfterTimeout

```solidity
function cancelOrderAfterTimeout(uint32 _orderIndex) external
```

*Safety function in case oracles don't answer in time, allows caller to cancel a pending order and if relevant claim back any stuck collateral Only allowed for MARKET\_OPEN, MARKET\_CLOSE, UPDATE\_LEVERAGE, MARKET\_PARTIAL\_OPEN, and MARKET\_PARTIAL\_CLOSE orders*

### Parameters

| Name         | Type   | Description                           |
| ------------ | ------ | ------------------------------------- |
| \_orderIndex | uint32 | the id of the pending order to cancel |

## updateLeverage

```solidity
function updateLeverage(uint32 _index, uint24 _newLeverage) external
```

*Update trade leverage*

### Parameters

| Name          | Type   | Description        |
| ------------- | ------ | ------------------ |
| \_index       | uint32 | index of trade     |
| \_newLeverage | uint24 | new leverage (1e3) |

## increasePositionSize

```solidity
function increasePositionSize(uint32 _index, uint120 _collateralDelta, uint24 _leverageDelta, uint64 _expectedPrice, uint16 _maxSlippageP) external
```

*Increase trade position size*

### Parameters

| Name              | Type    | Description                                  |
| ----------------- | ------- | -------------------------------------------- |
| \_index           | uint32  | index of trade                               |
| \_collateralDelta | uint120 | collateral to add (collateral precision)     |
| \_leverageDelta   | uint24  | partial trade leverage (1e3)                 |
| \_expectedPrice   | uint64  | expected price of execution (1e10 precision) |
| \_maxSlippageP    | uint16  | max slippage % (1e3)                         |

## decreasePositionSize

```solidity
function decreasePositionSize(uint32 _index, uint120 _collateralDelta, uint24 _leverageDelta, uint64 _expectedPrice) external
```

*Decrease trade position size*

### Parameters

| Name              | Type    | Description                                                         |
| ----------------- | ------- | ------------------------------------------------------------------- |
| \_index           | uint32  | index of trade                                                      |
| \_collateralDelta | uint120 | collateral to remove (collateral precision)                         |
| \_leverageDelta   | uint24  | leverage to reduce by (1e3)                                         |
| \_expectedPrice   | uint64  | expected closing price, used to check max slippage (1e10 precision) |

## getWrappedNativeToken

```solidity
function getWrappedNativeToken() external view returns (address)
```

*Returns the wrapped native token or address(0) if the current chain, or the wrapped token, is not supported.*

## isWrappedNativeToken

```solidity
function isWrappedNativeToken(address _token) external view returns (bool)
```

*Returns true if the token is the wrapped native token for the current chain, where supported.*

### Parameters

| Name    | Type    | Description   |
| ------- | ------- | ------------- |
| \_token | address | token address |

## getTradingDelegate

```solidity
function getTradingDelegate(address _trader) external view returns (address)
```

*Returns the address a trader delegates his trading actions to*

### Parameters

| Name     | Type    | Description           |
| -------- | ------- | --------------------- |
| \_trader | address | address of the trader |

## getMarketOrdersTimeoutBlocks

```solidity
function getMarketOrdersTimeoutBlocks() external view returns (uint16)
```

*Returns the current marketOrdersTimeoutBlocks value*

## getByPassTriggerLink

```solidity
function getByPassTriggerLink(address _user) external view returns (bool)
```

*Returns whether a user bypasses trigger link costs*

### Parameters

| Name   | Type    | Description         |
| ------ | ------- | ------------------- |
| \_user | address | address of the user |

## MarketOrdersTimeoutBlocksUpdated

```solidity
event MarketOrdersTimeoutBlocksUpdated(uint256 newValueBlocks)
```

*Emitted when marketOrdersTimeoutBlocks is updated*

### Parameters

| Name           | Type    | Description                                |
| -------------- | ------- | ------------------------------------------ |
| newValueBlocks | uint256 | the new value of marketOrdersTimeoutBlocks |

## ByPassTriggerLinkUpdated

```solidity
event ByPassTriggerLinkUpdated(address user, bool bypass)
```

*Emitted when a user is allowed/disallowed to bypass the link cost of triggerOrder*

### Parameters

| Name   | Type    | Description                                               |
| ------ | ------- | --------------------------------------------------------- |
| user   | address | address of the user                                       |
| bypass | bool    | whether the user can bypass the link cost of triggerOrder |

## MarketOrderInitiated

```solidity
event MarketOrderInitiated(struct ITradingStorage.Id orderId, address trader, uint16 pairIndex, bool open)
```

*Emitted when a market order is initiated*

### Parameters

| Name      | Type                      | Description                                                |
| --------- | ------------------------- | ---------------------------------------------------------- |
| orderId   | struct ITradingStorage.Id | price aggregator order id of the pending market order      |
| trader    | address                   | address of the trader                                      |
| pairIndex | uint16                    | index of the trading pair                                  |
| open      | bool                      | whether the market order is for opening or closing a trade |

## OpenOrderPlaced

```solidity
event OpenOrderPlaced(address trader, uint16 pairIndex, uint32 index)
```

*Emitted when a new limit/stop order is placed*

### Parameters

| Name      | Type    | Description                              |
| --------- | ------- | ---------------------------------------- |
| trader    | address | address of the trader                    |
| pairIndex | uint16  | index of the trading pair                |
| index     | uint32  | index of the open limit order for caller |

## OpenLimitUpdated

```solidity
event OpenLimitUpdated(address trader, uint16 pairIndex, uint32 index, uint64 newPrice, uint64 newTp, uint64 newSl, uint64 maxSlippageP)
```

### Parameters

| Name         | Type    | Description                                   |
| ------------ | ------- | --------------------------------------------- |
| trader       | address | address of the trader                         |
| pairIndex    | uint16  | index of the trading pair                     |
| index        | uint32  | index of the open limit/stop order for caller |
| newPrice     | uint64  | new trigger price (1e10 precision)            |
| newTp        | uint64  | new tp (1e10 precision)                       |
| newSl        | uint64  | new sl (1e10 precision)                       |
| maxSlippageP | uint64  | new max slippage % (1e3 precision)            |

## OpenLimitCanceled

```solidity
event OpenLimitCanceled(address trader, uint16 pairIndex, uint32 index)
```

*Emitted when a limit/stop order is canceled (collateral sent back to trader)*

### Parameters

| Name      | Type    | Description                                   |
| --------- | ------- | --------------------------------------------- |
| trader    | address | address of the trader                         |
| pairIndex | uint16  | index of the trading pair                     |
| index     | uint32  | index of the open limit/stop order for caller |

## TriggerOrderInitiated

```solidity
event TriggerOrderInitiated(struct ITradingStorage.Id orderId, address trader, uint16 pairIndex, bool byPassesLinkCost)
```

*Emitted when a trigger order is initiated (tp/sl/liq/limit/stop orders)*

### Parameters

| Name             | Type                      | Description                                            |
| ---------------- | ------------------------- | ------------------------------------------------------ |
| orderId          | struct ITradingStorage.Id | price aggregator order id of the pending trigger order |
| trader           | address                   | address of the trader                                  |
| pairIndex        | uint16                    | index of the trading pair                              |
| byPassesLinkCost | bool                      | whether the caller bypasses the link cost              |

## ChainlinkCallbackTimeout

```solidity
event ChainlinkCallbackTimeout(struct ITradingStorage.Id pendingOrderId, uint256 pairIndex)
```

*Emitted when a pending market order is canceled due to timeout*

### Parameters

| Name           | Type                      | Description               |
| -------------- | ------------------------- | ------------------------- |
| pendingOrderId | struct ITradingStorage.Id | id of the pending order   |
| pairIndex      | uint256                   | index of the trading pair |

## CouldNotCloseTrade

```solidity
event CouldNotCloseTrade(address trader, uint16 pairIndex, uint32 index)
```

*Emitted when a pending market order is canceled due to timeout and new closeTradeMarket() call failed*

### Parameters

| Name      | Type    | Description                        |
| --------- | ------- | ---------------------------------- |
| trader    | address | address of the trader              |
| pairIndex | uint16  | index of the trading pair          |
| index     | uint32  | index of the open trade for caller |

## NativeTokenWrapped

```solidity
event NativeTokenWrapped(address trader, uint256 nativeTokenAmount)
```

*Emitted when a native token is wrapped*

### Parameters

| Name              | Type    | Description                    |
| ----------------- | ------- | ------------------------------ |
| trader            | address | address of the trader          |
| nativeTokenAmount | uint256 | amount of native token wrapped |

## NotWrappedNativeToken

```solidity
error NotWrappedNativeToken()
```

## DelegateNotApproved

```solidity
error DelegateNotApproved()
```

## PriceZero

```solidity
error PriceZero()
```

## AboveExposureLimits

```solidity
error AboveExposureLimits()
```

## CollateralNotActive

```solidity
error CollateralNotActive()
```

## PriceImpactTooHigh

```solidity
error PriceImpactTooHigh()
```

## NoTrade

```solidity
error NoTrade()
```

## NoOrder

```solidity
error NoOrder()
```

## AlreadyBeingMarketClosed

```solidity
error AlreadyBeingMarketClosed()
```

## ConflictingPendingOrder

```solidity
error ConflictingPendingOrder(enum ITradingStorage.PendingOrderType)
```

## WrongLeverage

```solidity
error WrongLeverage()
```

## WrongTp

```solidity
error WrongTp()
```

## WrongSl

```solidity
error WrongSl()
```

## WaitTimeout

```solidity
error WaitTimeout()
```

## PendingTrigger

```solidity
error PendingTrigger()
```

## NoSl

```solidity
error NoSl()
```

## NoTp

```solidity
error NoTp()
```

## NotYourOrder

```solidity
error NotYourOrder()
```

## DelegatedActionNotAllowed

```solidity
error DelegatedActionNotAllowed()
```

## InsufficientCollateral

```solidity
error InsufficientCollateral()
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.gains.trade/developer/technical-reference/contracts/interfaces/libraries/itradinginteractionsutils.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
