分类
coding

How to use Python ccxt library Binance API

Here's how to use the API to automatically trade on the world-famous Bitcoin Binance exchange.

API application

Launch the Binance app and enter your API into Search.

Select the API Management item in the Functions category.

Choose Create API.

Enter the appropriate key label and select the Next button.

Fit the puzzle for security.

Then proceed with phone text verification and email verification.

Upon completion, you will get an API Key and Secret Key.

I checked Enable Futures for futures trading and Permits Universal Transfer for deposits and withdrawals between spot and futures trading.

Install ccxt library

Next, let's install ccxt, a Python library, to easily use the Binance API.

We assume that you know how to use Python and proceed.

Instructions and installation instructions can be found at the following site:

CCXT – CryptoCurrency eXchange Trading Library

You can install it with the following command.

pip install ccxt

Ready to use Binance API

First, import the ccxt library.

import ccxt

This is the code to create a Binance instance using the API Key value requested earlier. The defaultType of the options part is spot, and futures trading is possible by entering future.

binance_access_key = "xxxxxxxxx"
binance_secret_key = "yyyyyyyyy"

binance = ccxt.binance(config={
    'apiKey': binance_access_key, 
    'secret': binance_secret_key,
    'enableRateLimit': True,
    'options': {
        'defaultType': 'future'
    }
})

Current price inquiry

You can simply search as follows.

binance.fetch_ticker('BTC/USDT')

Balance inquiry

First, let's look at the code that retrieves the USDT balance of a futures trade. Enter future in the type of params. Enter spot to view the spot transaction balance.

balance = binance.fetch_balance(params={"type": "future"})
print(balance['USDT']['free'])

Let's also write some code to get the volume of coins held in a spot transaction.

balance_info = binance.fetch_balance(params={"type": "spot"})
for balance in balance_info['info']['balances']:
    if market['id'].find(balance['asset']) > -1:
        print(abs(float(balance['free'])))

The following code gets the volume of a coin that entered a short position in futures trading. Please note the difference with the code of spot trading.

balance_info = binance.fetch_balance(params={"type": "future"})
for position in balance_info['info']['positions']:
    if position['symbol'] == market['id']:
        print(abs(float(position['positionAmt'])))

Entering and Clearing Futures Trading

Below is the code for entering a short position. Both market and limit trades are possible.

symbol='BTC/USDT'

# market sell order
sell_order = binance.create_market_sell_order(symbol=symbol, amount=0.1)

# limit sell order
btc = binance.fetch_ticker(symbol)
sell_order = binance.create_limit_sell_order(symbol=symbol, amount=0.1, price=btc['last'])

And here is the short position cleanup code. Similarly, market and limit trades can be made.

symbol='BTC/USDT'

# market buy order
buy_order = binance.create_market_buy_order(symbol=symbol, amount=0.1)

# limit buy order
btc = binance.fetch_ticker(symbol)
buy_order = binance.create_limit_buy_order(symbol=symbol, amount=0.1, price=btc['last'])

Entering and closing a long position can be done in the opposite way, and spot trading can also be carried out using the same method.

Wire transfer between spot and futures

To transfer cash from spot to futures account, you simply query the cash account balance and transfer the value directly to your futures account. There are no fees for transfers from accounts within the Binance Exchange.

balance_spot = binance.fetch_balance(params={"type": "spot"})
balance_spot_free = balance_spot['USDT']['free']
if balance_spot_free > 0:
    transfer = binance.transfer('USDT', balance_spot_free, 'spot', 'future')

The opposite is also true.

balance_future = binance.fetch_balance(params={"type": "future"})
balance_future_free = balance_future ['USDT']['free']
if balance_future_free > 0:
    transfer = binance.transfer('USDT', balance_future_free, 'future', 'spot')

Leverage setting

For futures trading, you can set leverage. Here's the code: Just change the number in the leverage part.

markets = binance.load_markets()
market = binance.market('BTC/USDT')
resp = binance.fapiPrivate_post_leverage({
    'symbol': market['id'],
    'leverage': 2
})

View transaction data

You can query 1000 BTC daily transaction data by writing the following code:

candles = binance.fetch_ohlcv(
    symbol='BTC/USDT', 
    timeframe='1d', 
    since=None,
    limit=1000)

Leave a Reply

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

This posting is part of Coupang Partners' activities, and a certain amount of commission is provided accordingly.
en_USEnglish