> For the complete documentation index, see [llms.txt](https://docs.metalx.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.metalx.com/developers-dex/examples/cancel-dex-order.md). Agents can also search and read this documentation through its [MCP server](https://docs.metalx.com/~gitbook/mcp).

# Cancel DEX Order

{% tabs %}
{% tab title="JS" %}

```javascript
const actions = [
  {
      // Dex Smart Contract
      "account": "dex",
      // Action name
      "name": "cancelorder",
      // Action data
      "data": {
        "account": username,
        "order_id": 23
      },
      authorization
  },
  {
      account: 'dex',
      name: "withdrawall",
      data: {
          account: username,
      },
      authorization
  },
]

const main = async () => {
     await transact(actions)
}

main()
```

{% endtab %}

{% tab title="JS (Submit API)" %}

```javascript
// npm i @proton/js node-fetch@cjs
const { JsonRpc, Api, JsSignatureProvider, Serialize } = require('@proton/js')
const fetch = require('node-fetch');

// For testnet use https://rpc.api.testnet.metalx.com
const ENDPOINTS = ['https://rpc.api.mainnet.metalx.com']

// for testnet use https://dex.api.testnet.metalx.com/dex
const DEX_API_URL = "https://dex.api.mainnet.metalx.com/dex"

// To export private key from your wallet, follow:
// https://help.xprnetwork.org/hc/en-us/articles/4410313687703-How-do-I-backup-my-private-key-in-the-WebAuth-Wallet-
const PRIVATE_KEY = 'PVT_K1_2fdW4UGdbgG59mUaTiMXLy1rFv3afbmSWEZGWFz6zF8dR1VZPb'

// Initialize
const rpc = new JsonRpc(ENDPOINTS)
const signatureProvider = new JsSignatureProvider([PRIVATE_KEY])
const api = new Api({ rpc, signatureProvider })

// Example username, replace with your own
const USERNAME = 'metaltest1'
const authorization = [{ actor: USERNAME, permission: 'active' }]

// Cancel transaction builder
const buildCancelTransaction = orderId => {
  return {
    actions: [
      {
          account: 'dex',
          name: 'cancelorder',
          data: {
            account: USERNAME,
            order_id: orderId
          },
          authorization
      },
      {
          account: 'dex',
          name: 'withdrawall',
          data: {
              account: USERNAME,
          },
          authorization
      },
    ]
  }
}

async function main() {
  // Get order by ordinal ID
  const EXAMPLE_ORDINAL_ORDER_ID = '7fc4fbef0abcc61bebb8fcc0327bf7bb50d9fb77eaa92b876d0985845475a1f3'
  const orderHistoryResponse = await fetch(`${DEX_API_URL}/v1/orders/history?account=${USERNAME}&ordinal_order_ids=${EXAMPLE_ORDINAL_ORDER_ID}`);
  const { data: orders } = await orderHistoryResponse.json()

  // Build transaction (using first order ID for example)
  const transaction = buildCancelTransaction(orders[0].order_id)

  // Sign
  const { serializedTransaction, signatures } = await api.transact(transaction, {
    blocksBehind: 300,
    expireSeconds: 3000,
    broadcast: false
  })
    
  // Submit transaction
  const submitResponse = await fetch(`${DEX_API_URL}/v1/orders/submit`, {
      method: 'POST',
      headers: {
          'Content-Type': 'application/json'
      },
      body: JSON.stringify({
          serialized_tx_hex: Buffer.from(serializedTransaction).toString('hex'),
          signatures: signatures
      }),
  });
  const submitData = await submitResponse.json()
  console.dir(submitData, { depth: null })
}
main()
```

{% endtab %}

{% tab title="Python" %}

```python
args1 = {
        # Trading account
        "account": "user1",
        # ID of order
        "order_id": 1765,
}
args2 = {
        # Trading account
        "account": "user1",
}

permission = {'user1':'active'}

a1 = ['dex', 'cancelorder', args1, permission]
a2 = ['dex', 'withdrawall', args2, permission]

eosapi.push_actions([a1, a2])
```

{% endtab %}

{% tab title="Python (Submit API)" %}

```
# Cancel Order example

import os
import json
import requests
from pyeoskit import eosapi, wallet
#import your account private key here
wallet.import_key('mywallet', 'PVT_K1_2fdW4UGdbgG59mUaTiMXLy1rFv3afbmSWEZGWFz6zF8dR1VZPb')
#For testnet use https://rpc.api.testnet.metalx.com
eosapi.set_node('https://rpc.api.mainnet.metalx.com')

USERNAME = 'otctest'
ORDERID = 000000

# for testnet use "https://dex.api.testnet.metalx.com/dex/v1/orders/submit"
url = "https://dex.api.mainnet.metalx.com/dex/v1/orders/submit"
headers = {"content-type": "application/json", "Accept-Charset": "UTF-8"}
permission = {USERNAME: 'active'}

args1 = {
        # Trading account
        'account': USERNAME,
        # ID of order
        "order_id": ORDERID,
}
args2 = {
        # User account
        'account': USERNAME,
}

a1 = ['dex', 'cancelorder', args1, permission]
a2 = ['dex', 'withdrawall', args2, permission]

info = eosapi.get_info()
final_tx = eosapi.generate_packed_transaction(
    [a1, a2],
    60,
    info['last_irreversible_block_id'],
    info['chain_id']
)

mtx = json.loads(final_tx)
# Print transaction details
print('\nSignature: ', mtx["signatures"], '\nPacked Tx: ',  mtx["packed_trx"])

# Submit transaction
payload = {
    "serialized_tx_hex": mtx["packed_trx"],
    "signatures": mtx["signatures"]
}

r = requests.post(url,  json=payload, headers=headers)
data = r.json()


print(data)
```

{% endtab %}
{% endtabs %}


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

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

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.metalx.com/developers-dex/examples/cancel-dex-order.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

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.
