# Advanced Order Types

## Overview

The Order system provides functionality for creating and managing various types of orders in a decentralized trading platform. It supports limit orders, stop-loss orders, and take-profit orders, each with its own specific parameters and behavior.

#### Order Types:

1. Limit Order
2. Stop-Loss Order
3. Take-Profit Order
4. Cancel Order

### Using Order Types

For standard users, these order types can be placed on the [Perennial ](https://app.perennial.finance/trade)web app.&#x20;

For developers, anyone can create, sign and publish these orders. The easiest way to do so through the Typescript [Perennial SDK](https://github.com/equilibria-xyz/perennial-v2-sdk-ts/).&#x20;

### Execution System via Keepers

Perennial V2 employs an Order Keeper system to ensure efficient and timely execution of orders. Order Keepers are external agents that monitor the market and execute orders when they become eligible, playing a crucial role in maintaining a responsive trading environment.

Perennial has open sourced an example Keeper system which could be optimized significantly. Please feel free to take and modify this system: [Github](https://github.com/equilibria-xyz/perennial-v2-keepers?tab=readme-ov-file)

### Order Types & Arguments

#### Base Arguments (BuildTriggerOrderBaseArgs)

All order types share these common arguments:

```typescript
export type BuildTriggerOrderBaseArgs = {
  address: Address
  marketAddress: Address
  side: PositionSide
  delta: bigint
  maxFee?: bigint
  interfaceFee?: InterfaceFee
  referralFee?: InterfaceFee
}
```

#### 1. Limit Order

```typescript
export type BuildLimitOrderTxArgs = {
  limitPrice: bigint
  triggerComparison: TriggerComparison {
    lte = 'lte',
    gte = 'gte',
  }
} & BuildTriggerOrderBaseArgs
```

A limit order allows traders to specify a price at which they want to buy or sell an asset. The order will only be executed if the market price reaches or surpasses the specified limit price.

#### 2. Stop-Loss Order

```typescript
export type BuildStopLossTxArgs = {
  stopLossPrice: bigint
} & BuildTriggerOrderBaseArgs
```

A stop-loss order is designed to limit an investor's loss on a position. It's triggered when the market price reaches a specified stop price, helping to minimize potential losses.

#### 3. Take-Profit Order

```typescript
export type BuildTakeProfitTxArgs = {
  takeProfitPrice: bigint
} & BuildTriggerOrderBaseArgs
```

A take-profit order is used to lock in profits by automatically closing a position when the market price reaches a specified target price.

### Additional Data Structures

#### CancelOrderDetails

```typescript
export type CancelOrderDetails = { 
  market: Address
  nonce: bigint 
} | OpenOrder
```

### Using the SDK

Perennial has released a Typescript package on NPM to help developers interact with the protocol

```typescript
const marketOracles = await sdk.markets.read.marketOracles()
const marketSnapshots = await sdk.markets.read.marketSnapshots({...})
const ethMarketSnapshot = marketSnapshots.market[SupportedMarket.eth]
const ethUserMarketSnapshot = marketSnapshots.user[SupportedMarket.eth]

sdk.markets.write.placeOrder({
  marketAddress: ethMarketSnapshot.market,
  address: getAddress(<User address>),
  // As with `modifyPosition`, marketSnapshots and marketOracles are optional but recommended.
  marketSnapshots,
  marketOracles,
  orderType, // See `OrderTypes` enum for options
  side, // Position side
  limitPrice,
  stopLossPrice,
  takeProfitPrice,
  collateralDelta,
  delta, // Position size delta
  cancelOrderDetails, // Optional list of existing orders to cancel
  triggerComparison, // Comparator used for order execution. See `TriggerComparison` enum for options
  limitOrderFees,
  stopLossFees,
  takeProfitFees
})
```

### Important Notes

* All order-related functions require the user's address, chain ID, and a public client for interaction with the blockchain.
* The system uses BigInt values for prices and amounts to ensure precision in financial calculations.
* Interface fees and referral fees can be optionally specified for orders.
* The system interacts with a MultiInvoker contract to execute order-related actions on the blockchain.
* Stop-loss and take-profit orders require a negative delta, as they are used to close positions.

This order system provides a flexible and comprehensive set of tools for managing various types of orders in a decentralized trading environment, allowing traders to implement complex strategies and manage their risk effectively.


---

# 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.perennial.finance/protocol/markets/advanced-order-types.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.
