How to stream live Solana token prices

By RoaringCrypto · Guide · 3 min Read

This guide will demonstrate how to stream live token prices for any token from supported exchanges on the solana chain in javascript. The price information is embedded in swaps so we use the swapSubscribe websocket method to stream the swaps from the blockchain. In this article:

1. Example Code
2. Install Dependencies
3. Run the Code
4. Expected Output

1. Example Javascript code for streaming swaps / token prices

Copy the following code into a file called index.js

// npm install ws
const WebSocket = require('ws');
    
(async function () {
    // Connect
    const ws = new WebSocket('wss://api.solanastreaming.com/', undefined,
        {
            headers: {
                'X-API-KEY': '923aeea0ac3549a80dcd9f881986eaf7'
            }
        }
    );
    ws.on('error', console.error);
    ws.on('open', () => {
        // Start the pair / price stream
        ws.send('{"id":1,"method":"swapSubscribe","params":{"include":{"ammAccount":["DSUvc5qf5LJHHV5e2tD184ixotSnCnwj7i4jJa4Xsrmt"]}}}');
    });
    ws.on('message', (data) => {
        // Continuously read pairs / prices
        const parsed = JSON.parse(data);
        console.log(parsed);
    });
})();

Replace the api key with your own api key obtained for free from the dashboard. The example subscription request sets up a listener for all swaps within the amm pool with account DSUvc5qf5LJHHV5e2tD184ixotSnCnwj7i4jJa4Xsrmt. This is the biggest liquidity pool for the BOOK OF MEME token. Below is the same request but formatted so its easier to read.

{
    "id": 1,
    "method": "swapSubscribe",
    "params": {
        "include": {
            "ammAccount": [
                "DSUvc5qf5LJHHV5e2tD184ixotSnCnwj7i4jJa4Xsrmt"
            ]
        }
    }
}

It states that we are only interested in swaps in that particular ammAccount. Given that it is an array, you can add more ammAccounts and they will all show up in the stream. See more in the swap subscription filter docs.

Warning

You can watch a token price (all the swaps for that token) directly with the baseTokenMint filter instead. However, this will track the token across multiple liquidity pools. If a swap is made in a small liquidity pool, this can drastically affect the token price and not reflect the true market price.

It is best to pick the actual amm account you are interested in and watch that for token price updates. These can be found in the newPair event or can be found in dexscreener as the pairAddress.

Replace the address in baseTokenMint with the mint address of the token you want to track the prices for. Currently it is set to popcat but you can obtain any token address either from the newPairs feed or from the dexscreener solana token list (or anywhere else that shows solana token mint addresses)

2. Install dependancies

In this example we use npm, but you can also use yarn. We will use the ws library to handle the websocket connections. In the root of your project where you saved index.js run the following command:

npm install ws

This will populate a node_modules directory and create package.json and package-lock.json files

3. Run the code

The code is now ready to run. We use the node command to execute the code. Run the following command in the root of your project where you saved index.js. It will instantly connect to the websocket and start streaming price updates.

node index.js

4. Expected Output

Got a 401? Check your api key and try again.

If you have run everything correctly and the token is still trading you should see an output like this:

{
    id: 1,
    result: {
        message: 'listening for priceUpdated on chain...',
        subscription_id: 78
    }
}
{
    subscription_id: 78,
    method: 'swapNotification',
    params: {
        slot: 325817845,
        signature: '45aYbDCFxX1bFMRggSVRRE5xe1Dqaps5hgTK8MPH2Jx1aYaPLRmo5EyZGZLB6VqEktCLqq64Vmb5UUwgE9sBkUcp',
        blockTime: 1741604707,
        swap: {
            ammAccount: 'FRhB8L7Y9Qq41qZXYLtC2nw8An1RJfLLxRF2x9RwLLMo',
            baseTokenMint: '7GCihgDB8fe6KNjn2MYtkzZcRjQy3t9GHdC8uHYmW2hr',
            quoteTokenMint: 'So11111111111111111111111111111111111111112',
            walletAccount: 'fLipggLqMEofWHqiZTBR579Bbu2tT7emw4EWS7Md9QG',
            quotePrice: '0.001353790614',
            usdValue: 0,
            baseAmount: '28808',
            swapType: 'buy',
            quoteTokenLiquidity: '24842519158013'
        }
    }
}
...more like this

The first message is a successful subscription confirmation. You only receive one of these when successfully subscribing.

The second message (which you will then receive lots of) contains all the information relating to the swap that altered the price. You will only receive one of these notifications when a swap takes place on the blockchain. There can be multiple swaps in a single transaction. Detailed information of each field can be found in the documentation.

Note

You should check the blockTime field to ensure you are happy with the notification latency. The blockTime field is the timestamp of when the transaction was included in the blockchain. Compare this value to the current timestamp and you can calculate the notification latency. You can also check the historic latency of our websocket. The graph shows 1.5seconds average but this is a pessimistic value and the real value could be up to 800ms faster. This is due to the fact that solana doesnt record milliseconds in its timestamp so we round down so we calculate the slowest possible time. See more about latency.

With SolanaStreaming, you can start receiving reliable swap updates in seconds. Get started for free and get your free api key.

With the free plan, you can receive up to 1,000 swap events. With the basic plan you can stream an unlimited number of swap events but only for 5 addresses. Upgrade to the Pro plan to be able to receive all swap events.