How to Get Real-time TRON Blockchain Trading Data?

Sunpump, SunSwap, StableSwap and other DEXs

Divyasshree
Coinmonks
Published in
4 min readSep 16, 2024

--

Bitquery supports TRON ecosystem in both historical data as well as with real-time streams (V2 Streaming APIs). With only a sub-second delay, one can access real-time TRON mempool and confirmed data.

Let’s see how to implement real-time data for your TRON project. The developer plan gives limited access to work on your Individual hobby projects and for a large-scale application commercial plan suits you better.

Pre-requisites:

  • GraphQL subscription. Frame a subscription query in Bitquery IDE.
  • Streaming API to use in your application
  • WebSocket: wss://streaming.bitquery.io/eap
  • HTTPS: https://streaming.bitquery.io/eap
  • Create an access token for your application.Use the key for authentication. Check in Postman along with your OAuth token, whether you are able to retrieve data for your key here.

Example Query: Track Real-time TRON Token Price

Check if you’re able to retrieve the data on the IDE.

Let’s execute the same query in both React and Python projects.

React Implementation

Step 1: Create a custom hook for establishing a connection to Bitquery API. Accepting 4 parameters.

Use a setTimeout function to call the websocket to send a request every 1 second.

const useWebSocket = (url, options, query, maxRetries = 5) => {
const [data, setData] = useState(null);
const [error, setError] = useState(null);
const [isConnected, setIsConnected] = useState(false);
const [retryCount, setRetryCount] = useState(0);


useEffect(() => {
const connectWebSocket = () => {
const ws = new ReconnectingWebSocket(url, ["graphql-ws"], options);


ws.onopen = () => {
setIsConnected(true);
setRetryCount(0);
ws.send(JSON.stringify({ type: "connection_init" }));

setTimeout(() => {
ws.send(
JSON.stringify({
type: "start",
id: "1",
payload: { query },
})
);
}, 1000);
};


ws.onmessage = (event) => {
console.log("response ",event.data)
const response = JSON.parse(event.data);
if (response.type === "data") {
setData(response.payload.data);
}
};


ws.onclose = () => {
setIsConnected(false);
if (retryCount < maxRetries) {
setRetryCount(retryCount + 1);
setTimeout(connectWebSocket, 2000);
} else {
setError("Max retry attempts reached. Could not connect to Bitquery.");
}
};


ws.onerror = (event) => {
console.error("WebSocket Error:", event);
setError("WebSocket error occurred. See console for details.");
};


return () => {
ws.close();
};
};


connectWebSocket();
}, [retryCount]);


return { data, error, isConnected };
};

Step 2: Create a component Trondata and add in your subscription query and url with options like so and pass it as parameters to your custom hook

import React from "react";
import useWebSocket from "./useWebSocket";
import './App.css';


const Trondata = () => {
const query = `YOUR SUBSCRIPTION QUERY HERE`;

const url =
"wss://streaming.bitquery.io/eap?token=ory_*** Your OAuth Token Here ***";
const options = {
maxReconnectionDelay: 10000,
minReconnectionDelay: 1000,
reconnectionDelayGrowFactor: 1.3,
connectionTimeout: 5000,
maxRetries: Infinity,
debug: true,
};


const { data, error, isConnected } = useWebSocket(url, options, query);

Step 3: Map your Tron data onto UI and see real-time data published.

return (
<div id="trondata">
<h1>Real Time TRON Token Price</h1>
<p id="status">Status: {isConnected ? <span id="connected">Connected</span> : <span id="disconnected">Disconnected</span>}</p>
{error && <p id="status">Error: <span id="error">{error}</span></p>}
{data ? (
<table>
<thead>
<tr>
<th>Time</th>
<th>Currency</th>
<th>Amount In USD</th>
<th>Price In USD</th>
</tr>
</thead>
<tbody>
{data.Tron.DEXTradeByTokens.map((item, index) => (
<tr key={index}>
<td>{item.Block.Time}</td>
<td>{item.Trade.Currency.Symbol}</td>
<td>{item.Trade.AmountInUSD}</td>
<td>{item.Trade.PriceInUSD}</td>
</tr>
))}
</tbody>
</table>
) : (
<p>Loading data...</p>
)}
</div>
);
};


export default Trondata;

Output

Python Implementation

Step 1: Importing the needed libraries gql Client, pandas and Websockets. Optional modules to display data are table and colorama

Step 2: Setup websocket connection with connect using GraphQL

 async def run_subscription():
transport = WebsocketsTransport(
url="wss://streaming.bitquery.io/eap?token= Your OAuthToken Here",
headers={"Sec-WebSocket-Protocol": "graphql-ws"})


# Establish the connection
await transport.connect()
print("Connected to WebSocket")


try:
while True:
async for result in transport.subscribe(
gql("""Your Query Here""")):
if result.data:
new_data = pd.json_normalize(result.data['Tron']['DEXTradeByTokens'])
new_data = new_data.reindex(columns=expected_columns)


if tron_price.empty:
tron_price = new_data
else:
tron_price = pd.concat([tron_price, new_data], ignore_index=True)
table = tabulate(formatted_rows, headers=colored_headers, tablefmt='pretty', showindex=False)


finally:
await transport.close()

def main():
asyncio.run(run_subscription())

Step 3: Print the result.data on a formatted table to see the real-time data printed onto the console.

Now you’ve implemented real-time data on your TRON project.

Now you’ve implemented real-time data on your TRON project.

Kafka Streams

TRON blockchain data is also provided via kafka streams using the subscription query as reference for data you need.

Self Help

You can also check out our pre-built queries on our TRON explorer or on our documentation. Replace the “query” keyword with “subscription to fetch real-time data to integrate to your current project.

References

Streaming API Demo Link

Bitquery documentation: How to build dApps?

Add-Ons

Using Bitquery, you can build Discord and Telegram Bots where you can do a seamless integration to your applications.

Stuck in a step?

If you get stuck on a query or an implementation, DM on our Telegram channel where Bitquery will assist you with queries and your projects.

Real-time support for your projects

Bitquery also does custom integrations with your existing Cloud infrastructure (AWS, Google Cloud) and data Warehouse products.

You can also contact us on our form for your exact specific needs or send us a mail to sales@bitquery.io.

— -

Written by Sreelekha Srinivasan

--

--