# Creating trade stream for specified token

## 1. Use case

* Displaying **Trade History** of the given token on website
* Fetching all trades of the given token to implement snipper bot, arbitrage bot, copy trade bot
* Live UI price feed, OHLCV candle generation, trade heatmap
* Whale trade alert, pump/dump detector

## 2. Steps

* Connect to endpoint `wss://[chain_name]-api.txdecoder.xyz/ws`
* Send optional parameters to filter only DEX action and the given token
  * **type**: <kbd>DEX</kbd>
  * **token**: token involving the transaction
  * **action**: <kbd>swap / add\_liquidity  / remove\_liquidity</kbd>  (optional) , if no action given, all events returned
  * **min\_value\_usd**: minimum usd value , number, greater than 0

```javascript
{
    "type": "DEX",
    "token" : "0x0E09FaBB73Bd3Ade0a17ECC321fD13a19e81cE82", // - token address involving in the transaction.
    "min_value_usd": 1000 // 1000 USD
}
```

* Wait to receive new data
* Response data in **User Action** format

&#x20;

## 3. Example Code (Javascript)

```javascript
const WebSocket = require('ws')

const main = async () => {
  // Connect through the WebSocket proxy with authentication
  const apiKey = process.env.API_KEY
  const proxyUrl = 'wss://bsc-api.txdecoder.xyz/ws'

  const ws = new WebSocket(proxyUrl, {
    headers: {
      'x-api-key': apiKey,
    },
    rejectUnauthorized: false,
  })

  ws.on('open', () => {
    console.log('Connected to TxDecoder WebSocket server')

    // Send the DEX message after connection is established
    
     const message = { type: 'DEX', token: '0x0E09FaBB73Bd3Ade0a17ECC321fD13a19e81cE82' }
     
     ws.send(JSON.stringify(message))
     console.log('Sent message:', message)
  })

  ws.on('message', (data) => {
    try {
      const message = JSON.parse(data)
      
        for (const txHash in message) {
            const userActions = message[txHash]
            if (!Array.isArray(userActions)) continue
            for (const userAction of userActions) {
                const { tokens, participants, tx_hash: txHash, value_usd: valueUsd } = userAction
                if (!txHash) continue

                // TODO: process trade here
            }
        }
        
    } catch (error) {
      console.log('Received raw data:', data.toString())
    }
  })

  ws.on('error', (error) => {
    console.error('WebSocket error:', error)
  })

  ws.on('close', (code, reason) => {
    console.log(`Connection closed. Code: ${code}, Reason: ${reason}`)
  })

  // Handle graceful shutdown
  process.on('SIGINT', () => {
    console.log('Closing WebSocket connection...')
    ws.close()
    process.exit(0)
  })
}

main().catch(console.error)
```

<br>


---

# 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://txdecoder.gitbook.io/docs/tutorials/creating-trade-stream-for-specified-token.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.
