Binance API Examples with Python
The Binance cryptocurrency exchange has been one of the leading platforms for trading cryptocurrencies since its inception. It offers an extensive range of features, including a highly efficient and user-friendly Application Programming Interface (API) that allows developers to interact directly with the platform. This article will explore various examples showcasing how to use Python to interact with Binance's API for different purposes, such as fetching market data, placing trades, and more.
Getting Started: Authentication
Before diving into API calls, it is essential to authenticate your application on Binance. The process involves generating a 'API Key' and an optional secret key. This can be achieved by logging in to your Binance account, navigating to the "API/Algo Trading" section under the "Trade" menu, and clicking on "NEW API KEY".
After creating keys, ensure you store them securely, as they grant full access to your trading account. Never share these keys with third parties or include them in public repositories.
Example 1: Fetching Market Data
Market data is crucial for any cryptocurrency trader, and Binance's API makes it straightforward to retrieve this information. The `get_symbol_ticker` function allows you to fetch the ticker (price change) of a specific market symbol.
```python
import requests
import json
apiKey = "your-api-key"
secretKey = "your-secret-key"
url = 'https://fapi.binance.com/fapi/v1/ticker/price'
symbol = 'BTCUSDT' # Example market symbol
payload = {'symbol': symbol}
signature = f'API_KEY={apiKey}&METHOD=GET&SIGNATURE=' + \
hashlib.sha256((timestamp+'GET'+json.dumps(payload).encode()+secretKey.encode()).encode()).hexdigest()
headers = { 'X-MBLOGIN': apiKey, 'X-MBSIGNATURE': signature }
response = requests.get(url, headers=headers, params=payload)
ticker_data = json.loads(response.text)
print(ticker_data)
```
This code uses the `requests` library to send a GET request to Binance's API endpoint for market ticker data. It calculates an MD5 signature using your secret key and timestamp to authenticate your request.
Example 2: Order Placement
You can also use Binance's API for placing buy or sell orders directly from Python. The `place_order` function allows you to create a new order on the specified market symbol.
```python
import requests
import json
apiKey = "your-api-key"
secretKey = "your-secret-key"
url = 'https://fapi.binance.com/fapi/v1/order'
symbol = 'BTCUSDT' # Example market symbol
side = 'BUY' # Buy or Sell
type_ = 'LIMIT' # Market, Limit
timeInForce = 'GTC' # GoodTillCanceled, ImmediateOrCancle, FillOrKill
quantity = 0.1
price = '10000'
payload = {'symbol': symbol, 'side': side, 'type': type_, 'timeInForce': timeInForce, \
'quantity': quantity, 'price': price}
signature = f'API_KEY={apiKey}&METHOD=POST&SIGNATURE=' + \
hashlib.sha256((timestamp+'POST'+json.dumps(payload).encode()+secretKey.encode()).encode()).hexdigest()
headers = { 'X-MBLOGIN': apiKey, 'X-MBSIGNATURE': signature }
response = requests.post(url, headers=headers, json=payload)
order_info = json.loads(response.text)
print(order_info)
```
This script creates a new buy order for 0.1 Bitcoin using a limit price of $10,000 on the BTC/USDT market symbol. It then prints information about the created order upon successful execution.
Example 3: WebSocket Connection
Binance's API also supports real-time data streaming via WebSockets. This can be useful for live trading or developing notification systems when certain conditions are met. Here is an example of establishing a WebSocket connection to Binance's order book updates for BTC/USDT market symbol.
```python
import websocket, json
apiKey = "your-api-key"
secretKey = "your-secret-key"
url_ws = 'wss://fstream.binance.com/stream?streams=' # WebSocket URL prefix
symbol = 'BTCUSDT' # Example market symbol
message = {'method': 'SUBSCRIBE', 'params': [symbol + '/depth@1000ms'], 'id': 1}
def on_open(ws):
payload = json.dumps(message)
signature = hashlib.sha256((timestamp+'POST'+payload+secretKey).encode()).hexdigest()
auth = f'Signature={signature}' # Binance expects the signature in this format
ws.send(payload + '\n' + auth)
def on_message(ws, message):
print('Message received:', json.loads(message))
def on_close(ws):
pass
def on_error(ws, error):
print(f"Error occurred: {str(error)}")
if __name__ == "__main__":
ws = websocket.WebSocketApp(url_ws + symbol + '/depth',
on_open=on_open, on_message=on_message,
on_close=on_close, on_error=on_error)
ws.run()
```
This script connects to the Binance WebSocket endpoint for the BTC/USDT market symbol's depth updates and prints incoming messages. It utilizes a JSON-formatted message subscribing request and authenticates using your API key and secret.
Conclusion
Binance's API provides developers with powerful tools to interact directly with their platform, offering endless possibilities for integrating trading functionalities into existing systems or creating new applications. This article has only scratched the surface of what's possible; there are countless additional features available within Binance's API ecosystem that can be explored and utilized according to your needs. Always remember to follow best practices when dealing with API keys and sensitive data, ensuring security is paramount in any application developed using Binance's APIs.