# Order Executors

### OrderExecutorTool ⇐ `WriteAccessHandler`

Functions to execute existing conditional orders from the limit order book. This class requires a private key and executes smart-contract interactions that require gas-payments.

**Kind**: global class\
**Extends**: `WriteAccessHandler`

* [OrderExecutorTool](broken://pages/BSoXgtunbvzHREHtDdtg) ⇐ `WriteAccessHandler`
  * [new OrderExecutorTool(config, signer)](broken://pages/BSoXgtunbvzHREHtDdtg)
  * [.executeOrder(symbol, orderId, executorAddr, nonce, \[submission\])](broken://pages/BSoXgtunbvzHREHtDdtg) ⇒
  * [.executeOrders(symbol, orderIds, executorAddr, nonce, \[submission\])](broken://pages/BSoXgtunbvzHREHtDdtg) ⇒
  * [.getAllOpenOrders(symbol)](broken://pages/BSoXgtunbvzHREHtDdtg) ⇒
  * [.numberOfOpenOrders(symbol)](broken://pages/BSoXgtunbvzHREHtDdtg) ⇒ `number`
  * [.getOrderById(symbol, digest)](broken://pages/BSoXgtunbvzHREHtDdtg) ⇒
  * [.pollLimitOrders(symbol, numElements, \[startAfter\])](broken://pages/BSoXgtunbvzHREHtDdtg) ⇒
  * [.isTradeable(order, indexPrices)](broken://pages/BSoXgtunbvzHREHtDdtg) ⇒
  * [.isTradeableBatch(orders, indexPrice)](broken://pages/BSoXgtunbvzHREHtDdtg) ⇒
  * [.smartContractOrderToOrder(scOrder)](broken://pages/BSoXgtunbvzHREHtDdtg) ⇒
  * [.getTransactionCount(blockTag)](broken://pages/BSoXgtunbvzHREHtDdtg) ⇒

#### new OrderExecutorTool(config, signer)

Constructor.

| Param  | Type                 | Description                                                   |
| ------ | -------------------- | ------------------------------------------------------------- |
| config | `NodeSDKConfig`      | Configuration object, see PerpetualDataHandler.readSDKConfig. |
| signer | `string` \| `Signer` | Private key or ethers Signer of the account                   |

**Example**

```js
import { OrderExecutorTool, PerpetualDataHandler } from '@d8x/perpetuals-sdk';
async function main() {
  console.log(OrderExecutorTool);
  // load configuration for Polygon zkEVM (testnet)
  const config = PerpetualDataHandler.readSDKConfig("cardona");
  // OrderExecutorTool (authentication required, PK is an environment variable with a private key)
  const pk: string = <string>process.env.PK;
  let orderTool = new OrderExecutorTool(config, pk);
  // Create a proxy instance to access the blockchain
  await orderTool.createProxyInstance();
}
main();
```

#### orderExecutorTool.executeOrder(symbol, orderId, executorAddr, nonce, \[submission]) ⇒

Executes an order by symbol and ID. This action interacts with the blockchain and incurs gas costs.

**Kind**: instance method of [`OrderExecutorTool`](broken://pages/BSoXgtunbvzHREHtDdtg)\
**Returns**:

Transaction object.

| Param         | Type                  | Description                                                                                                                   |
| ------------- | --------------------- | ----------------------------------------------------------------------------------------------------------------------------- |
| symbol        | `string`              | Symbol of the form ETH-USD-MATIC.                                                                                             |
| orderId       | `string`              | ID of the order to be executed.                                                                                               |
| executorAddr  | `string`              | optional address of the wallet to be credited for executing the order, if different from the one submitting this transaction. |
| nonce         | `number`              | optional nonce                                                                                                                |
| \[submission] | `PriceFeedSubmission` | optional signed prices obtained via PriceFeeds::fetchLatestFeedPriceInfoForPerpetual                                          |

**Example**

```js
import { OrderExecutorTool, PerpetualDataHandler, Order } from "@d8x/perpetuals-sdk";
async function main() {
  console.log(OrderExecutorTool);
  // Setup (authentication required, PK is an environment variable with a private key)
  const config = PerpetualDataHandler.readSDKConfig("cardona");
  const pk: string = <string>process.env.PK;
  const symbol = "ETH-USD-MATIC";
  let orderTool = new OrderExecutorTool(config, pk);
  await orderTool.createProxyInstance();
  // get some open orders
  const maxOrdersToGet = 5;
  let [orders, ids]: [Order[], string[]] = await orderTool.pollLimitOrders(symbol, maxOrdersToGet);
  console.log(`Got ${ids.length} orders`);
  for (let k = 0; k < ids.length; k++) {
    // check whether order meets conditions
    let doExecute = await orderTool.isTradeable(orders[k]);
    if (doExecute) {
      // execute
      let tx = await orderTool.executeOrder(symbol, ids[k]);
      console.log(`Sent order id ${ids[k]} for execution, tx hash = ${tx.hash}`);
    }
  }
}
main();
```

#### orderExecutorTool.executeOrders(symbol, orderIds, executorAddr, nonce, \[submission]) ⇒

Executes a list of orders of the symbol. This action interacts with the blockchain and incurs gas costs.

**Kind**: instance method of [`OrderExecutorTool`](broken://pages/BSoXgtunbvzHREHtDdtg)\
**Returns**:

Transaction object.

| Param         | Type                  | Description                                                                                                                   |
| ------------- | --------------------- | ----------------------------------------------------------------------------------------------------------------------------- |
| symbol        | `string`              | Symbol of the form ETH-USD-MATIC.                                                                                             |
| orderIds      | `Array.<string>`      | IDs of the orders to be executed.                                                                                             |
| executorAddr  | `string`              | optional address of the wallet to be credited for executing the order, if different from the one submitting this transaction. |
| nonce         | `number`              | optional nonce                                                                                                                |
| \[submission] | `PriceFeedSubmission` | optional signed prices obtained via PriceFeeds::fetchLatestFeedPriceInfoForPerpetual                                          |

**Example**

```js
import { OrderExecutorTool, PerpetualDataHandler, Order } from "@d8x/perpetuals-sdk";
async function main() {
  console.log(OrderExecutorTool);
  // Setup (authentication required, PK is an environment variable with a private key)
  const config = PerpetualDataHandler.readSDKConfig("cardona");
  const pk: string = <string>process.env.PK;
  const symbol = "ETH-USD-MATIC";
  let orderTool = new OrderExecutorTool(config, pk);
  await orderTool.createProxyInstance();
  // get some open orders
  const maxOrdersToGet = 5;
  let [orders, ids]: [Order[], string[]] = await orderTool.pollLimitOrders(symbol, maxOrdersToGet);
  console.log(`Got ${ids.length} orders`);
  // execute
  let tx = await orderTool.executeOrders(symbol, ids);
  console.log(`Sent order ids ${ids.join(", ")} for execution, tx hash = ${tx.hash}`);
}
main();
```

#### orderExecutorTool.getAllOpenOrders(symbol) ⇒

All the orders in the order book for a given symbol that are currently open.

**Kind**: instance method of [`OrderExecutorTool`](broken://pages/BSoXgtunbvzHREHtDdtg)\
**Returns**:

Array with all open orders and their IDs.

| Param  | Type     | Description                       |
| ------ | -------- | --------------------------------- |
| symbol | `string` | Symbol of the form ETH-USD-MATIC. |

**Example**

```js
import { OrderExecutorTool, PerpetualDataHandler } from '@d8x/perpetuals-sdk';
async function main() {
  console.log(OrderExecutorTool);
  // setup (authentication required, PK is an environment variable with a private key)
  const config = PerpetualDataHandler.readSDKConfig("cardona");
  const pk: string = <string>process.env.PK;
  let orderTool = new OrderExecutorTool(config, pk);
  await orderTool.createProxyInstance();
  // get all open orders
  let openOrders = await orderTool.getAllOpenOrders("ETH-USD-MATIC");
  console.log(openOrders);
}
main();
```

#### orderExecutorTool.numberOfOpenOrders(symbol) ⇒ `number`

Total number of limit orders for this symbol, excluding those that have been cancelled/removed.

**Kind**: instance method of [`OrderExecutorTool`](broken://pages/BSoXgtunbvzHREHtDdtg)\
**Returns**: `number` -

Number of open orders.

| Param  | Type     | Description                       |
| ------ | -------- | --------------------------------- |
| symbol | `string` | Symbol of the form ETH-USD-MATIC. |

**Example**

```js
import { OrderExecutorTool, PerpetualDataHandler } from '@d8x/perpetuals-sdk';
async function main() {
  console.log(OrderExecutorTool);
  // setup (authentication required, PK is an environment variable with a private key)
  const config = PerpetualDataHandler.readSDKConfig("cardona");
  const pk: string = <string>process.env.PK;
  let orderTool = new OrderExecutorTool(config, pk);
  await orderTool.createProxyInstance();
  // get all open orders
  let numberOfOrders = await orderTool.numberOfOpenOrders("ETH-USD-MATIC");
  console.log(numberOfOrders);
}
main();
```

#### orderExecutorTool.getOrderById(symbol, digest) ⇒

Get order from the digest (=id)

**Kind**: instance method of [`OrderExecutorTool`](broken://pages/BSoXgtunbvzHREHtDdtg)\
**Returns**:

order or undefined

| Param  | Description                              |
| ------ | ---------------------------------------- |
| symbol | symbol of order book, e.g. ETH-USD-MATIC |
| digest | digest of the order (=order ID)          |

**Example**

```js
import { OrderExecutorTool, PerpetualDataHandler } from '@d8x/perpetuals-sdk';
async function main() {
  console.log(OrderExecutorTool);
  // setup (authentication required, PK is an environment variable with a private key)
  const config = PerpetualDataHandler.readSDKConfig("cardona");
  const pk: string = <string>process.env.PK;
  let orderTool = new OrderExecutorTool(config, pk);
  await orderTool.createProxyInstance();
  // get order by ID
  let myorder = await orderTool.getOrderById("MATIC-USD-MATIC",
      "0x0091a1d878491479afd09448966c1403e9d8753122e25260d3b2b9688d946eae");
  console.log(myorder);
}
main();
```

#### orderExecutorTool.pollLimitOrders(symbol, numElements, \[startAfter]) ⇒

Get a list of active conditional orders in the order book. This a read-only action and does not incur in gas costs.

**Kind**: instance method of [`OrderExecutorTool`](broken://pages/BSoXgtunbvzHREHtDdtg)\
**Returns**:

Array of orders and corresponding order IDs

| Param         | Type     | Description                                                                 |
| ------------- | -------- | --------------------------------------------------------------------------- |
| symbol        | `string` | Symbol of the form ETH-USD-MATIC.                                           |
| numElements   | `number` | Maximum number of orders to poll.                                           |
| \[startAfter] | `string` | Optional order ID from where to start polling. Defaults to the first order. |

**Example**

```js
import { OrderExecutorTool, PerpetualDataHandler } from '@d8x/perpetuals-sdk';
async function main() {
  console.log(OrderExecutorTool);
  // setup (authentication required, PK is an environment variable with a private key)
  const config = PerpetualDataHandler.readSDKConfig("cardona");
  const pk: string = <string>process.env.PK;
  let orderTool = new OrderExecutorTool(config, pk);
  await orderTool.createProxyInstance();
  // get all open orders
  let activeOrders = await orderTool.pollLimitOrders("ETH-USD-MATIC", 2);
  console.log(activeOrders);
}
main();
```

#### orderExecutorTool.isTradeable(order, indexPrices) ⇒

Check if a conditional order can be executed

**Kind**: instance method of [`OrderExecutorTool`](broken://pages/BSoXgtunbvzHREHtDdtg)\
**Returns**:

true if order can be executed for the current state of the perpetuals

| Param       | Description                                                                                                                              |
| ----------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
| order       | order structure                                                                                                                          |
| indexPrices | pair of index prices S2 and S3. S3 set to zero if not required. If undefined the function will fetch the latest prices from the REST API |

**Example**

```js
import { OrderExecutorTool, PerpetualDataHandler } from '@d8x/perpetuals-sdk';
async function main() {
  console.log(OrderExecutorTool);
  // setup (authentication required, PK is an environment variable with a private key)
  const config = PerpetualDataHandler.readSDKConfig("cardona");
  const pk: string = <string>process.env.PK;
  let orderTool = new OrderExecutorTool(config, pk);
  await orderTool.createProxyInstance();
  // check if tradeable
  let openOrders = await orderTool.getAllOpenOrders("MATIC-USD-MATIC");
  let check = await orderTool.isTradeable(openOrders[0][0]);
  console.log(check);
}
main();
```

#### orderExecutorTool.isTradeableBatch(orders, indexPrice) ⇒

Check for a batch of orders on the same perpetual whether they can be traded

**Kind**: instance method of [`OrderExecutorTool`](broken://pages/BSoXgtunbvzHREHtDdtg)\
**Returns**:

array of tradeable boolean

| Param      | Description                                                                                 |
| ---------- | ------------------------------------------------------------------------------------------- |
| orders     | orders belonging to 1 perpetual                                                             |
| indexPrice | S2,S3-index prices for the given perpetual. Will fetch prices from REST API if not defined. |

**Example**

```js
import { OrderExecutorTool, PerpetualDataHandler } from '@d8x/perpetuals-sdk';
async function main() {
  console.log(OrderExecutorTool);
  // setup (authentication required, PK is an environment variable with a private key)
  const config = PerpetualDataHandler.readSDKConfig("cardona");
  const pk: string = <string>process.env.PK;
  let orderTool = new OrderExecutorTool(config, pk);
  await orderTool.createProxyInstance();
  // check if tradeable
  let openOrders = await orderTool.getAllOpenOrders("MATIC-USD-MATIC");
  let check = await orderTool.isTradeableBatch(
      [openOrders[0][0], openOrders[0][1]],
      [openOrders[1][0], openOrders[1][1]]
    );
  console.log(check);
}
main();
```

#### orderExecutorTool.smartContractOrderToOrder(scOrder) ⇒

Wrapper of static method to use after mappings have been loaded into memory.

**Kind**: instance method of [`OrderExecutorTool`](broken://pages/BSoXgtunbvzHREHtDdtg)\
**Returns**:

A user-friendly order struct.

| Param   | Description                                      |
| ------- | ------------------------------------------------ |
| scOrder | Perpetual order as received in the proxy events. |

#### orderExecutorTool.getTransactionCount(blockTag) ⇒

Gets the current transaction count for the connected signer

**Kind**: instance method of [`OrderExecutorTool`](broken://pages/BSoXgtunbvzHREHtDdtg)\
**Returns**:

The nonce for the next transaction

| Param    |
| -------- |
| blockTag |


---

# 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://d8x.gitbook.io/d8x/node-sdk/modules/order-executors.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.
