@

Binance API Connector Overview - The Official Binance Python Library

Thu Aug 24 2023

Python Binance Connector API

Building a profitable crypto trading bot in Python means knowing how to leverage the latest technology available and how to work with exchange APIs in a direct and efficient manner. In this article we’re going to do an overview on the Binance API using Binance’s newly released Binance Connector Python Library.

There are many python tools out there that simplify the interaction with the Binance API, however the Python Binance Connector is the new, official library released Binance, and contrary to the name, it’s not just a Connector, but it also includes an expansive Client for Spot trading and more. So let’s look at some of the main functions that you’d be using in order to build your own Binance Trading Bot in Python from scratch.

Building a crypto trading bot from scratch can be a time consuming endeavour, so if you’re looking to do away with the complexity normally required, you can use an algorithmic cryptocurrency trading platform such as Aesir and launch your crypto trading bots in minutes.

The first thing you want to do is create an API Key so that you can programmatically perform actions on you binance account.

How to Create a Binance API Key

Getting Started With the Binance API Connector

First make sure you have an IDE and a recent version of Python installed on your machine.

To get started, you’ll need to install the Binance Connector Library.

pip install binance-connector



You can now import the Client from this library in order to use the various functions that will allow you to create and configure your own crypto trading bot using the Binance API.

from binance.client import Client

Using the Binance Testnet with the Binance API Connector

To use the testnet in order to make sure that your trading bot works (without actually placing orders) simply change the base URL in the Client.

client = Client(base_url='https://testnet.binance.vision')

Connect to the Live Binance Account

Using the Python Binance Connector Library, you can easily connect to your alive account to programmatically perform actions.

client = Spot(api_key='KEY', api_secret='SECRET')

Get Kline Data

To get kline data using the Binance Connector API you need to call client.klines, with your specified interval and symbol:

client = Spot()
# 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))
# Get the average price for a symbol
print(client.avg_price("BTCUSDT"))

Get Binance Account Snapshot

Using the Binance connector, it’s also possible to easily return an account snapshot for a specific account type (spot, margin, futures, etc..)

client.account_snapshot(type="spot")


Get Trades for a symbol

## Returns Recent Trades list
client.trades(symbol="BTCUSDT")
## Get Older Historical Trades
client.historical_trades(symbol="BTCUSDT")



Place Order using the Binance API

You can place an order using the new_order() method and adding the relevant params.

from binance.spot import Spot

client = Spot()

# 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)



Let’s go over these params in a bit more detail:

Connecting to a Binance Websocket

Using the Binance Connector to easily stream kline data is also possible:


# 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()



These are just some of the functions that the Binance Connector API allows us to access. In fact the connector is probably the most expansive Binance API library out there! Below you will find a list of all the functions available for the different API endpoints.

We understand that building, testing and deploying your crypto trading bots from scratch can be a time consuming task, so before spending a significant amount of time building your crypto trading bots from scratch why not test your strategy on Aesir first? Our algorithmic crypto trading platform lets you easily create, test, and clone strategies so you will always be one step ahead of the market. Get started here. Be sure to Join Us on Discord too (it’s good stuff).

All available Binance Python Connector Methods

MARKET: ping, time, exchange_info, depth, trades, historical_trades, agg_trades, klines, ui_klines, avg_price, ticker_24hr, ticker_price, book_ticker, rolling_window_ticker

ACCOUNT (including orders and trades): new_order_test, new_order, cancel_order, cancel_open_orders, get_order, cancel_and_replace, get_open_orders, get_orders, new_oco_order, cancel_oco_order, get_oco_order, get_oco_orders, get_oco_open_orders, account, my_trades, get_order_rate_limit

STREAMS: new_listen_key, renew_listen_key, close_listen_key, new_margin_listen_key, renew_margin_listen_key, close_margin_listen_key, new_isolated_margin_listen_key, renew_isolated_margin_listen_key, close_isolated_margin_listen_key

MARGIN: margin_transfer, margin_borrow, margin_repay, margin_asset, margin_pair, margin_all_assets, margin_all_pairs, margin_pair_index, new_margin_order, cancel_margin_order, margin_transfer_history, margin_load_record, margin_repay_record, margin_interest_history, margin_force_liquidation_record, margin_account, margin_order, margin_open_orders, margin_open_orders_cancellation, margin_all_orders, margin_my_trades, margin_max_borrowable, margin_max_transferable, isolated_margin_transfer, isolated_margin_transfer_history, isolated_margin_account, isolated_margin_pair, isolated_margin_all_pairs, toggle_bnbBurn, bnbBurn_status, margin_interest_rate_history, new_margin_oco_order, cancel_margin_oco_order, get_margin_oco_order, get_margin_oco_orders, get_margin_open_oco_orders, cancel_isolated_margin_account, enable_isolated_margin_account, isolated_margin_account_limit, margin_fee, isolated_margin_fee, isolated_margin_tier, margin_order_usage, margin_dust_log, summary_of_margin_account

SAVINGS: savings_flexible_products, savings_flexible_user_left_quota, savings_purchase_flexible_product, savings_flexible_user_redemption_quota, savings_flexible_redeem, savings_flexible_product_position, savings_project_list, savings_purchase_project, savings_project_position, savings_account, savings_purchase_record, savings_redemption_record, savings_interest_history, savings_change_position

Staking: staking_product_list, staking_purchase_product, staking_redeem_product, staking_product_position, staking_history, staking_set_auto_staking, staking_product_quota

WALLET: system_status, coin_info, account_snapshot, disable_fast_withdraw, enable_fast_withdraw, withdraw, deposit_history, withdraw_history, deposit_address, account_status, api_trading_status, dust_log, user_universal_transfer, user_universal_transfer_history, transfer_dust, asset_dividend_record, asset_detail, trade_fee, funding_wallet, user_asset, api_key_permissions, bnb_convertible_assets, convertible_coins, toggle_auto_convertion, cloud_mining_trans_history, convert_transfer, convert_history

MINING: mining_algo_list, mining_coin_list, mining_worker, mining_worker_list, mining_earnings_list, mining_bonus_list, mining_statistics_list, mining_account_list, mining_hashrate_resale_request, mining_hashrate_resale_cancellation, mining_hashrate_resale_list, mining_hashrate_resale_details, mining_account_earning

SUB-ACCOUNT: sub_account_create, sub_account_list, sub_account_assets, sub_account_deposit_address, sub_account_deposit_history, sub_account_status, sub_account_enable_margin, sub_account_margin_account, sub_account_margin_account_summary, sub_account_enable_futures, sub_account_futures_transfer, sub_account_margin_transfer, sub_account_transfer_to_sub, sub_account_transfer_to_master, sub_account_transfer_sub_account_history, sub_account_futures_asset_transfer_history, sub_account_futures_asset_transfer, sub_account_spot_summary, sub_account_universal_transfer, sub_account_universal_transfer_history, sub_account_futures_account, sub_account_futures_account_summary, sub_account_futures_position_risk, sub_account_spot_transfer_history, sub_account_enable_leverage_token, managed_sub_account_deposit, managed_sub_account_assets, managed_sub_account_withdraw, sub_account_update_ip_restriction, sub_account_api_get_ip_restriction, sub_account_api_delete_ip, managed_sub_account_get_snapshot, managed_sub_account_investor_trans_log, managed_sub_account_trading_trans_log, managed_sub_account_deposit_address

FUTURES: futures_transfer, futures_transfer_history, futures_loan_borrow_history, futures_loan_repay_history, futures_loan_wallet, futures_loan_adjust_collateral_history, futures_loan_liquidation_history, futures_loan_interest_history

BLVTs: blvt_info, subscribe_blvt, subscription_record, redeem_blvt, redemption_record, user_limit_info

BSwap: bswap_pools, bswap_liquidity, bswap_liquidity_add, bswap_liquidity_remove, bswap_liquidity_operation_record, bswap_request_quote, bswap_swap, bswap_swap_history, bswap_pool_configure, bswap_add_liquidity_preview, bswap_remove_liquidity_preview, bswap_unclaimed_rewards, bswap_claim_rewards, bswap_claimed_rewards

FIAT: fiat_order_history, fiat_payment_history

C2C: c2c_trade_history

LOANS: loan_history, loan_borrow, loan_borrow_history, loan_ongoing_orders, loan_repay, loan_repay_history, loan_adjust_ltv, loan_adjust_ltv_history, loan_vip_ongoing_orders, loan_vip_repay, loan_vip_repay_history, loan_vip_collateral_account, loan_loanable_data, loan_collateral_data, loan_collateral_rate, loan_customize_margin_call

PAY: pay_history

CONVERT: convert_trade_history

REBATE: rebate_spot_history

NFT: nft_transaction_history, nft_deposit_history, nft_withdraw_history, nft_asset

Gift Card (Binance Code in the API documentation): gift_card_create_code, gift_card_redeem_code, gift_card_verify_code, gift_card_rsa_public_key, gift_card_buy_code, gift_card_token_limit

Portfolio Margin: portfolio_margin_account, portfolio_margin_collateral_rate, portfolio_margin_bankruptcy_loan_amount, portfolio_margin_bankruptcy_loan_repay

@SIR

©DEM Group 2024