> 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).

# 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 dynamically by asking a question.

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

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

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
