How to Get Trading Data via the Binance API?

How to Get Trading Data via the Binance API?

Intermediate
Aktualizováno Dec 16, 2025
5m

Key Takeaways

  • Binance provides both public market trades and private account trades data.

  • Public trade data files are available daily or monthly for comprehensive historical market information.

  • REST API endpoints allow fetching recent and historical trade data, with account trades requiring authentication.

  • WebSocket streams deliver real-time updates for public market trades and users’ account trades.

Introduction

Binance provides several ways to access trade history, including public market trades and individual account trades. Trade data can be retrieved through APIs or real-time streams, offering both recent and historical information. This article explains the basic methods to obtain Binance trade history in a clear and straightforward manner.

What Is a Trade?

A trade on Binance refers to individual buy or sell orders that have been matched and executed on the exchange. Each trade represents a single transaction between a buyer and a seller.

Aggregated trade format (aggTrade) is a combined record of multiple trades that happened at the same price and within a very short time frame. Instead of showing every single trade separately, aggTrade groups these trades together to provide a summarized view, which can reduce data volume and make it easier to analyze market activity.

The key difference is that a trade reflects each executed transaction, while an aggTrade combines multiple trades at the same price into one aggregated record. It’s also important to understand that an order is simply a request to buy or sell a certain amount at a specified price, and a trade occurs only when that order is matched and executed with a counterparty.

Public Trades Data

Historical trades

Binance Data Collection lets you easily download public market data from Binance for all trading pairs. 

The data is organized into daily and monthly files to help users track market activity over time. Daily files are updated and available the day after trading happens, while monthly files are compiled and released on the first Monday of each month. 

Both the daily and monthly directories include files for trades and aggTrades, with each file containing all the trades that occurred during that specific day or month. 

This way, traders can quickly access accurate and up-to-date information to analyze price movements, trading volumes, and more.

The API is another effective method to retrieve historical trade data. The /api/v3/trades endpoint offers the most recent trades for a specific symbol, making it useful for analyzing current market activity.

To access older trades, the historicalTrades endpoint can be used. This endpoint includes a fromId parameter that allows the retrieval of trades starting from a particular trade ID.

For filtering trades by date rather than trade ID, the /api/v3/aggTrades endpoint is suitable. It supports startTime and endTime parameters to specify the time range. The response also includes firstTradeId and lastTradeId, which can be used with the historicalTrades endpoint to obtain detailed trade data.

Code Snippet
import logging

from binance_sdk_spot.spot import Spot


logging.basicConfig(level=logging.INFO)

client = Spot()


def agg_trades():
    try:
        agg_trades_response = client.rest_api.agg_trades(
            symbol="BNBUSDT",
            start_time=1760950800000, # October 20, 2025 9:00:00 AM
        )

        data = agg_trades_response.data()
        first_trade_id = data[0].f

        historical_trades_response = client.rest_api.historical_trades(
            symbol="BNBUSDT",
            from_id=first_trade_id,
            limit=100,
        )

        logging.info(f"Historical trades: {historical_trades_response.data()}")
    except Exception as e:
        logging.error(f"agg_trades() error: {e}")


if __name__ == "__main__":
    agg_trades()

Real time events

The Binance WebSocket API provides real-time updates of trades for a specific symbol through the trade stream, delivering immediate notifications whenever a new trade is executed. This stream continuously pushes live trade data, including price, quantity, and trade ID, enabling instant market activity monitoring. 

For aggregated real-time data, the aggTrade stream can be used, which groups trades occurring at the same price within a short time frame. 

While WebSocket streams do not support querying historical data by trade ID or time range, combining real-time streams with REST endpoints allows comprehensive trade analysis by linking live updates with past trade records.

Code Snippet
import asyncio
import logging

from binance_sdk_spot.spot import (Spot)

logging.basicConfig(level=logging.INFO)

client = Spot()


async def trade():
    connection = None
    try:
        connection = await client.websocket_streams.create_connection()

        stream = await connection.trade(
            symbol="bnbusdt",
        )
        stream.on("message", lambda data: print(f"{data}"))

        while True:
            await asyncio.sleep(1)
    except Exception as e:
        logging.error(f"trade() error: {e}")
    finally:
        if connection:
            await connection.close_connection(close_session=True)


if __name__ == "__main__":
    asyncio.run(trade())

My Trades Data

Historical trades

The /api/v3/myTrades endpoint enables retrieval of a user’s trade history with flexible filtering options. Depending on the parameters provided, the query can be tailored to return trades within specific time frames, starting from certain trade IDs, or related to particular orders.
The following parameter combinations are supported:

  • symbol

  • symbol + orderId

  • symbol + startTime

  • symbol + endTime

  • symbol + fromId

  • symbol + startTime + endTime

  • symbol + orderId + fromId

If fromId is specified, trades with IDs greater than or equal to that value will be returned; otherwise, the most recent trades are retrieved. 

The time range between startTime and endTime cannot exceed 24 hours. These options allow historical trades to be queried based on dates or order IDs, providing flexibility depending on the user’s needs.

Real time events

The Binance user data stream via WebSocket provides real-time updates on personal trade executions and order status. By connecting with a valid listen key, immediate notifications are received for fills, partial fills, and order changes, delivering detailed, account-specific trade information to support efficient portfolio tracking and automated trading.

Code Snippet
import asyncio
import logging

from binance_sdk_spot.spot import Spot, SPOT_WS_API_PROD_URL, ConfigurationWebSocketAPI


logging.basicConfig(level=logging.INFO)

configuration_ws_api = ConfigurationWebSocketAPI(
    api_key="apiKey",
    private_key="/path/to/private.key",
    stream_url=SPOT_WS_API_PROD_URL,
)

client = Spot(config_ws_api=configuration_ws_api)


async def user_data():
    connection = None
    try:
        connection = await client.websocket_api.create_connection()

        await connection.session_logon()
        res = await connection.user_data_stream_subscribe()
        response = res.response

        data = response.data()
        logging.info(f"user_data_stream_subscribe() response: {data}")

        res.stream.on("message", handle_message)

        while True:
            await asyncio.sleep(1)
    except Exception as e:
        logging.error(f"user_data() error: {e}")
    finally:
        if connection:
            await connection.close_connection(close_session=True)

def handle_message(data):
    execution_report = data.actual_instance
    if str(type(execution_report)) == "<class 'binance_sdk_spot.websocket_api.models.execution_report.ExecutionReport'>":
        print(f"OrderId: {execution_report.i} has been filled with tradeId: {execution_report.t}")

if __name__ == "__main__":
    asyncio.run(user_data())

Closing Thoughts

Access to detailed trade history is essential for traders aiming to review their past activity and make well-informed decisions. Flexible options for retrieving trade data - whether by date range, order ID, or other criteria - allow users to tailor their queries to fit their individual needs. 

By offering versatile tools to explore both recent and historical trades, Binance enables users to gain deeper insights into their trading behavior and market trends. 

Combined with a comprehensive suite of market data resources, this empowers traders to approach the market with greater transparency and confidence.

Further Reading

Disclaimer: This article is for educational purposes only. This content is presented to you on an “as is” basis for general information and educational purposes only, without representation or warranty of any kind. It should not be construed as financial, legal or other professional advice, nor is it intended to recommend the purchase of any specific product or service. You should seek your own advice from appropriate professional advisors. Products mentioned in this article may not be available in your region. Where the article is contributed by a third party contributor, please note that those views expressed belong to the third party contributor, and do not necessarily reflect those of Binance Academy. Please read our full disclaimer here for further details. Digital asset prices can be volatile. The value of your investment may go down or up and you may not get back the amount invested. You are solely responsible for your investment decisions and Binance Academy is not liable for any losses you may incur. This material should not be construed as financial, legal or other professional advice. For more information, see our Terms of Use and Risk Warning.