Top Related Projects
A JavaScript / TypeScript / Python / C# / PHP cryptocurrency trading API with support for more than 100 bitcoin/altcoin exchanges
Binance Exchange API python implementation for automated trading
A bitcoin trading bot written in node - https://gekko.wizb.it/
Free, open source crypto trading bot
Github.com/CryptoSignal - Trading & Technical Analysis Bot - 4,100+ stars, 1,100+ forks
Quick Overview
The Binance Connector for Python is an official Python library provided by Binance, a leading cryptocurrency exchange platform. It allows developers to easily interact with the Binance API, enabling them to build applications and automate trading strategies on the Binance platform.
Pros
- Official Library: As an official library from Binance, it provides reliable and up-to-date integration with the Binance API.
- Comprehensive Documentation: The project has detailed documentation, including examples and usage guides, making it easy for developers to get started.
- Asynchronous Support: The library supports asynchronous programming, allowing for efficient and non-blocking API interactions.
- Actively Maintained: The project is actively maintained by the Binance team, ensuring regular updates and bug fixes.
Cons
- Limited to Binance: The library is specifically designed for the Binance platform, limiting its usefulness for developers who need to interact with other cryptocurrency exchanges.
- Dependency on Binance API: The library's functionality is entirely dependent on the Binance API, which means any changes or issues with the API can impact the library's functionality.
- Learning Curve: While the documentation is comprehensive, developers new to the Binance ecosystem may still face a learning curve when integrating the library into their projects.
- Limited Customization: The library provides a relatively fixed set of functionality, which may limit the ability to customize or extend its capabilities.
Code Examples
Here are a few code examples demonstrating the usage of the Binance Connector for Python:
from binance.client import Client
# Initialize the Binance client
client = Client()
# Get the current price of Bitcoin
ticker = client.get_ticker(symbol='BTCUSDT')
print(f"Current Bitcoin price: {ticker['lastPrice']} USDT")
This code initializes the Binance client and retrieves the current price of Bitcoin (BTC/USDT).
from binance.client import Client
# Initialize the Binance client
client = Client()
# Place a market buy order for 0.1 BTC
order = client.order_market_buy(symbol='BTCUSDT', quantity=0.1)
print(f"Order placed: {order}")
This code places a market buy order for 0.1 BTC on the Binance platform.
from binance.client import Client
from binance.enums import *
# Initialize the Binance client
client = Client()
# Place a limit sell order for 0.05 BTC at $50,000
order = client.order_limit_sell(
symbol='BTCUSDT',
quantity=0.05,
price='50000'
)
print(f"Order placed: {order}")
This code places a limit sell order for 0.05 BTC at a price of $50,000 on the Binance platform.
Getting Started
To get started with the Binance Connector for Python, follow these steps:
- Install the library using pip:
pip install python-binance
- Import the necessary modules and initialize the Binance client:
from binance.client import Client
client = Client(api_key='YOUR_API_KEY', api_secret='YOUR_API_SECRET')
-
Explore the available methods and functionality provided by the library. The official documentation covers a wide range of use cases, including:
- Retrieving market data (prices, order books, trades, etc.)
- Placing and managing orders (market, limit, stop-loss, etc.)
- Monitoring account balances and transaction history
- Accessing user-specific data and settings
-
Refer to the documentation for detailed examples and usage guides to integrate the Binance Connector into your Python projects.
Competitor Comparisons
A JavaScript / TypeScript / Python / C# / PHP cryptocurrency trading API with support for more than 100 bitcoin/altcoin exchanges
Pros of ccxt
- Supports multiple exchanges, not limited to Binance
- More comprehensive documentation and community support
- Offers a unified API across different exchanges
Cons of ccxt
- May have slightly higher latency due to abstraction layer
- Requires more setup and configuration for specific exchanges
- Potentially larger codebase and memory footprint
Code Comparison
ccxt:
import ccxt
exchange = ccxt.binance()
ticker = exchange.fetch_ticker('BTC/USDT')
print(ticker['last'])
binance-connector-python:
from binance.spot import Spot
client = Spot()
ticker = client.ticker_price("BTCUSDT")
print(ticker['price'])
Summary
ccxt offers a versatile solution for interacting with multiple cryptocurrency exchanges, including Binance, through a unified API. It provides extensive documentation and community support, making it easier for developers to work with various exchanges. However, this versatility comes at the cost of slightly higher latency and a larger codebase.
binance-connector-python, on the other hand, is specifically designed for Binance and may offer lower latency and a more streamlined setup process for Binance-specific operations. It has a smaller codebase but is limited to Binance exchange functionality.
The choice between the two depends on whether you need multi-exchange support or are focusing solely on Binance integration.
Binance Exchange API python implementation for automated trading
Pros of python-binance
- More comprehensive API coverage, including futures and margin trading
- Extensive documentation and examples
- Active community support and frequent updates
Cons of python-binance
- Not officially maintained by Binance
- May have slightly higher latency due to additional abstraction layers
Code Comparison
python-binance:
from binance.client import Client
client = Client(api_key, api_secret)
prices = client.get_all_tickers()
binance-connector-python:
from binance.spot import Spot
client = Spot(api_key=api_key, api_secret=api_secret)
prices = client.ticker_price()
Summary
python-binance offers a more feature-rich and well-documented solution, making it ideal for developers who need comprehensive API coverage and community support. However, binance-connector-python, being officially maintained by Binance, may provide more direct and potentially faster access to the API.
The code comparison shows that both libraries offer similar ease of use, with python-binance using a slightly different naming convention for methods. Ultimately, the choice between the two depends on specific project requirements and personal preferences.
A bitcoin trading bot written in node - https://gekko.wizb.it/
Pros of Gekko
- More comprehensive trading platform with backtesting and paper trading capabilities
- Supports multiple exchanges beyond Binance
- Includes a web interface for easier management and visualization
Cons of Gekko
- Less frequently updated and maintained compared to Binance Connector Python
- May have compatibility issues with newer exchange APIs
- Potentially steeper learning curve for beginners
Code Comparison
Gekko (Trading strategy example):
method.update = function(candle) {
if(this.trend.direction == 'up')
this.advice('long');
else if(this.trend.direction == 'down')
this.advice('short');
}
Binance Connector Python (API request example):
from binance.spot import Spot
client = Spot()
print(client.klines("BTCUSDT", "1h"))
Summary
Gekko is a more feature-rich trading platform suitable for advanced users who require backtesting and multi-exchange support. Binance Connector Python, on the other hand, is a focused, well-maintained library specifically for interacting with the Binance API. It's more suitable for developers building custom trading solutions or integrating Binance functionality into existing projects.
Free, open source crypto trading bot
Pros of freqtrade
- Comprehensive trading bot framework with built-in strategies and backtesting capabilities
- Supports multiple exchanges and cryptocurrencies
- Active community and extensive documentation
Cons of freqtrade
- Steeper learning curve due to its complexity and feature-rich nature
- May be overkill for simple trading tasks or API interactions
Code Comparison
freqtrade:
from freqtrade.strategy.interface import IStrategy
class CustomStrategy(IStrategy):
def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
dataframe['rsi'] = ta.RSI(dataframe)
return dataframe
binance-connector-python:
from binance.spot import Spot
client = Spot()
print(client.time())
print(client.klines("BTCUSDT", "1d"))
freqtrade offers a more comprehensive framework for building trading strategies, while binance-connector-python provides a simpler, direct interface to Binance API endpoints. freqtrade is better suited for developing complete trading bots with advanced features, whereas binance-connector-python is ideal for basic API interactions and custom implementations.
Github.com/CryptoSignal - Trading & Technical Analysis Bot - 4,100+ stars, 1,100+ forks
Pros of Crypto-Signal
- Provides a complete trading bot solution with signal generation and analysis
- Supports multiple exchanges beyond just Binance
- Includes backtesting capabilities for strategy evaluation
Cons of Crypto-Signal
- More complex setup and configuration compared to Binance Connector
- May require more resources to run due to its comprehensive features
- Less frequently updated than Binance Connector
Code Comparison
Crypto-Signal (strategy implementation):
class RelativeStrengthIndex(IndicatorUtils):
def analyze(self, historical_data, period_count=14,
signal=['rsi'], hot_thresh=None, cold_thresh=None):
dataframe = self.convert_to_dataframe(historical_data)
rsi_values = abstract.RSI(dataframe, period_count)
rsi_result_data = []
for rsi_value in rsi_values:
is_hot = rsi_value < hot_thresh if hot_thresh else None
is_cold = rsi_value > cold_thresh if cold_thresh else None
rsi_result_data.append((rsi_value, is_hot, is_cold))
return rsi_result_data
Binance Connector (API interaction):
from binance.spot import Spot
client = Spot()
print(client.time())
print(client.klines("BTCUSDT", "1d"))
print(client.depth("BTCUSDT"))
print(client.trades("BTCUSDT"))
print(client.avg_price("BTCUSDT"))
The code comparison shows that Crypto-Signal focuses on implementing trading strategies and indicators, while Binance Connector provides a straightforward interface for interacting with the Binance API.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
Binance Public API Connector Python
This is a lightweight library that works as a connector to Binance public API
- Supported APIs:
/api/*
/sapi/*
- Spot Websocket Market Stream
- Spot User Data Stream
- Spot WebSocket API
- Inclusion of test cases and examples
- Customizable base URL, request timeout and HTTP proxy
- Response metadata can be displayed
Installation
pip install binance-connector
Documentation
https://binance-connector.readthedocs.io
RESTful APIs
Usage examples:
from binance.spot import Spot
client = Spot()
# Get server timestamp
print(client.time())
# Get klines of BTCUSDT at 1m interval
print(client.klines("BTCUSDT", "1m"))
# Get last 10 klines of BNBUSDT at 1h interval
print(client.klines("BNBUSDT", "1h", limit=10))
# API key/secret are required for user data endpoints
client = Spot(api_key='<api_key>', api_secret='<api_secret>')
# Get account and balance information
print(client.account())
# Post a new order
params = {
'symbol': 'BTCUSDT',
'side': 'SELL',
'type': 'LIMIT',
'timeInForce': 'GTC',
'quantity': 0.002,
'price': 9500
}
response = client.new_order(**params)
print(response)
Please find examples
folder to check for more endpoints.
- In order to set your API and Secret Key for use of the examples, create a file
examples/config.ini
with your keys. - Eg:
# examples/config.ini [keys] api_key=abc123456 api_secret=cba654321
Authentication
Binance supports HMAC, RSA and ED25519 API authentication.
# HMAC: pass API key and secret
client = Client(api_key, api_secret)
print(client.account())
# RSA Keys
client = Client(api_key=api_key, private_key=private_key)
print(client.account())
# ED25519 Keys
api_key = ""
private_key = "./private_key.pem"
private_key_pass = "<password_if_applicable>"
with open(private_key, 'rb') as f:
private_key = f.read()
spot_client = Client(api_key=api_key, private_key=private_key, private_key_pass=private_key_pass)
# Encrypted RSA Key
client = Client(api_key=api_key, private_key=private_key, private_key_pass='password')
print(client.account())
Please find examples/spot/wallet/account_snapshot.py
for more details on ED25519.
Please find examples/spot/trade/get_account.py
for more details on RSA.
Testnet
Spot Testnet is available, it can be used to test /api/*
endpoints.
/sapi/*
endpoints are not available.- No UI.
- Steps to setup testnet API key. https://dev.binance.vision/t/99
To use testnet:
from binance.spot import Spot as Client
client = Client(base_url='https://testnet.binance.vision')
print(client.time())
Base URL
If base_url
is not provided, it defaults to api.binance.com
.
It's recommended to pass in the base_url
parameter, even in production as Binance provides alternative URLs
in case of performance issues:
https://api1.binance.com
https://api2.binance.com
https://api3.binance.com
Optional parameters
PEP8 suggests lowercase with words separated by underscores, but for this connector, the methods' optional parameters should follow their exact naming as in the API documentation.
# Recognised parameter name
response = client.cancel_oco_order('BTCUSDT', orderListId=1)
# Unrecognised parameter name
response = client.cancel_oco_order('BTCUSDT', order_list_id=1)
RecvWindow parameter
Additional parameter recvWindow
is available for endpoints requiring signature.
It defaults to 5000
(milliseconds) and can be any value lower than 60000
(milliseconds).
Anything beyond the limit will result in an error response from Binance server.
from binance.spot import Spot as Client
client = Client(api_key, api_secret)
response = client.get_order('BTCUSDT', orderId=11, recvWindow=10000)
Timeout
timeout
is available to be assigned with the number of seconds you find most appropriate to wait for a server response.
Please remember the value as it won't be shown in error message no bytes have been received on the underlying socket for timeout seconds.
By default, timeout
is None. Hence, requests do not time out.
from binance.spot import Spot as Client
client= Client(timeout=1)
Proxy
Proxy is supported.
from binance.spot import Spot as Client
proxies = { 'https': 'http://1.2.3.4:8080' }
client= Client(proxies=proxies)
Response Metadata
The Binance API server provides weight usages in the headers of each response.
You can display them by initializing the client with show_limit_usage=True
:
from binance.spot import Spot as Client
client = Client(show_limit_usage=True)
print(client.time())
returns:
{'data': {'serverTime': 1587990847650}, 'limit_usage': {'x-mbx-used-weight': '31', 'x-mbx-used-weight-1m': '31'}}
You can also display full response metadata to help in debugging:
client = Client(show_header=True)
print(client.time())
returns:
{'data': {'serverTime': 1587990847650}, 'header': {'Context-Type': 'application/json;charset=utf-8', ...}}
If ClientError
is received, it'll display full response meta information.
Display logs
Setting the log level to DEBUG
will log the request URL, payload and response text.
Error
There are 2 types of error returned from the library:
binance.error.ClientError
- This is thrown when server returns
4XX
, it's an issue from client side. - It has 5 properties:
status_code
- HTTP status codeerror_code
- Server's error code, e.g.-1102
error_message
- Server's error message, e.g.Unknown order sent.
header
- Full response header.error_data
* - Additional detailed data which supplements theerror_message
.- *Only applicable on select endpoints, eg.
cancelReplace
- *Only applicable on select endpoints, eg.
- This is thrown when server returns
binance.error.ServerError
- This is thrown when server returns
5XX
, it's an issue from server side.
- This is thrown when server returns
Websocket
Connector v3
WebSocket can be established through either of the following types of connections:
- WebSocket API (
https://github.com/binance/binance-spot-api-docs/blob/master/web-socket-api.md
) - WebSocket Stream (
https://github.com/binance/binance-spot-api-docs/blob/master/web-socket-streams.md
)
# WebSocket API Client
from binance.websocket.spot.websocket_api import SpotWebsocketAPIClient
def message_handler(_, message):
logging.info(message)
my_client = SpotWebsocketAPIClient(on_message=message_handler)
my_client.ticker(symbol="BNBBUSD", type="FULL")
time.sleep(5)
logging.info("closing ws connection")
my_client.stop()
# WebSocket Stream Client
from binance.websocket.spot.websocket_stream import SpotWebsocketStreamClient
def message_handler(_, message):
logging.info(message)
my_client = SpotWebsocketStreamClient(on_message=message_handler)
# Subscribe to a single symbol stream
my_client.agg_trade(symbol="bnbusdt")
time.sleep(5)
logging.info("closing ws connection")
my_client.stop()
Proxy
Proxy is supported for both WebSocket API and WebSocket Stream.
To use it, pass in the proxies
parameter when initializing the client.
The format of the proxies
parameter is the same as the one used in the Spot RESTful API.
It consists on a dictionary with the following format, where the key is the type of the proxy and the value is the proxy URL:
For websockets, the proxy type is http
.
proxies = { 'http': 'http://1.2.3.4:8080' }
You can also use authentication for the proxy by adding the username
and password
parameters to the proxy URL:
proxies = { 'http': 'http://username:password@host:port' }
# WebSocket API Client
from binance.websocket.spot.websocket_api import SpotWebsocketAPIClient
def message_handler(_, message):
logging.info(message)
proxies = { 'http': 'http://1.2.3.4:8080' }
my_client = SpotWebsocketAPIClient(on_message=message_handler, proxies=proxies, timeout=10)
my_client.ticker(symbol="BNBBUSD", type="FULL")
time.sleep(5)
logging.info("closing ws connection")
my_client.stop()
# WebSocket Stream Client
from binance.websocket.spot.websocket_stream import SpotWebsocketStreamClient
def message_handler(_, message):
logging.info(message)
proxies = { 'http': 'http://1.2.3.4:8080' }
my_client = SpotWebsocketStreamClient(on_message=message_handler, proxies=proxies, timeout=10)
# Subscribe to a single symbol stream
my_client.agg_trade(symbol="bnbusdt")
time.sleep(5)
logging.info("closing ws connection")
my_client.stop()
Request Id
Client can assign a request id to each request. The request id will be returned in the response message. Not mandatory in the library, it generates a uuid format string if not provided.
# id provided by client
my_client.ping_connectivity(id="my_request_id")
# library will generate a random uuid string
my_client.ping_connectivity()
Combined Streams
- If you set
is_combined
toTrue
,"/stream/"
will be appended to thebaseURL
to allow for Combining streams. is_combined
defaults toFalse
and"/ws/"
(raw streams) will be appended to thebaseURL
.
More websocket examples are available in the examples
folder.
Example file "examples/websocket_api/app_demo.py" demonstrates how Websocket API and Websocket Stream can be used together.
Connector v1 and v2
from binance.websocket.spot.websocket_client import SpotWebsocketClient as WebsocketClient
def message_handler(message):
print(message)
ws_client = WebsocketClient()
ws_client.start()
ws_client.mini_ticker(
symbol='bnbusdt',
id=1,
callback=message_handler,
)
# Combine selected streams
ws_client.instant_subscribe(
stream=['bnbusdt@bookTicker', 'ethusdt@bookTicker'],
callback=message_handler,
)
ws_client.stop()
Heartbeat
Once connected, the websocket server sends a ping frame every 3 minutes and requires a response pong frame back within a 10 minutes period. This package handles the pong responses automatically.
Testnet
from binance.websocket.spot.websocket_client import SpotWebsocketClient as WebsocketClient
ws_client = WebsocketClient(stream_url='wss://stream.testnet.binance.vision')
Test Case
# In case packages are not installed yet
pip install -r requirements/requirements-test.txt
python -m pytest tests/
Limitation
Futures and Vanilla Options APIs are not supported:
/fapi/*
/dapi/*
/vapi/*
- Associated Websocket Market and User Data Streams
Contributing
Contributions are welcome.
If you've found a bug within this project, please open an issue to discuss what you would like to change.
If it's an issue with the API, please open a topic at Binance Developer Community
Top Related Projects
A JavaScript / TypeScript / Python / C# / PHP cryptocurrency trading API with support for more than 100 bitcoin/altcoin exchanges
Binance Exchange API python implementation for automated trading
A bitcoin trading bot written in node - https://gekko.wizb.it/
Free, open source crypto trading bot
Github.com/CryptoSignal - Trading & Technical Analysis Bot - 4,100+ stars, 1,100+ forks
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot