Ethereum: Python Binance – How to get the last PRICES traded in futures with websocket?

Ethereum: Trading Latest Futures Prices on Binance WebSocket

For a developer working with Ethereum and Binance APIs, getting real-time price data is essential to building effective trading strategies. In this article, we will walk you through the process of getting the latest futures prices using the Binance WebSocket API.

Prerequisites

  • You have created a Binance account and received an API key.
  • You have installed the required libraries: python-binance and websocket-client.

Step-by-step guide

  • Initialize Binance Socket Manager

import binancesocket as bss

BinanceWS = bss.BinanceSocketManager(binance_info=binance_info)

Replace binance_info with your actual Binance API key and secret.

  • Create a WebSocket Server Connection

conn_key = 'your_api_key_here'

conn_secret = 'your_api_secret_here'

bss.connect(wss='wss://api.binance.com/truehost', key=conn_key, secret=conn_secret)

Replace wss with the URL of your Binance WebSocket server.

  • Subscribe to the Futures Market

symbol = 'BTCUSD'

subscribe = bss.Subscribable(symbol=symbol)

subscribe.subscribe()

This will register you on the Bitcoin USD futures market on the Binance exchange.

  • Get latest prices for trading

last_prices = subscribes.get_all_tickers()

for the ticker in last_prices:

print(f"{ticker.symbol} last price: {ticker.price}")

Please note that we are only interested in futures with tickers ending in _USD (e.g. BTCUSDT, ETHUSDT, etc.). If you want to get all futures, uncomment the following line:

all_tickers = subscribe.get_all_tickers()

for ticker in all_tickers:

print(f"{ticker.symbol} last price: {ticker.price}")

Example Output

BTCUSDT Last Price: 40000.0

ETHUSDT Last Price: 42000.0

...

  • Close Subscription and Disconnect from WebSocket Server

subscribe.close()

bss.disconnect()

Don’t forget to close your subscription when you’re done using it to avoid unnecessary API requests.

By following these steps, you will be able to get the latest prices at which futures are traded on the Binance WebSocket server. Happy trading!

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *