Binance Trading Bot Python Code Example
In today's digital age, automated trading bots have become increasingly popular among traders for their ability to execute trades automatically according to a set strategy without human intervention. One of the most popular cryptocurrency exchanges that supports this is Binance. This article will walk you through creating an automated trading bot using Python and the Binance Futures API.
Understanding the Binance Futures API
Binance Futures, launched in April 2019, provides a platform for users to trade futures contracts with leverage. The exchange offers several endpoints for its API that can be used by developers to interact with the exchange's trading system programmatically. One such endpoint is the 'API Public Trade Information' which provides real-time order book and trades data.
The Python requests library will be our primary tool for interfacing with this Binance Futures API, making it easy to fetch live trade data that can be used by our bot.
Setting Up Your Environment
Before we start coding, make sure you have the following:
1. Python: Latest version recommended but Python3 is preferable as API requests are more straightforward in this version.
2. requests library: This is a simple HTTP for python and will be used to make API calls. You can install it via pip by running `pip install requests` in your terminal.
3. Binance Futures Trading Account with API Key: Needed for authenticating our API request.
4. Telegram Bot: For sending notifications when trades are executed or other updates, you can create a bot on the Telegram website and get its token.
5. A Virtual Private Server (VPS): To run your bot continuously without worrying about it being affected by your computer's sleep mode, which is essential for 24/7 trading bots.
Building the Binance Trading Bot with Python
Firstly, create a new python file. Let's name this "Binance_bot.py". Here are the steps involved in creating our bot:
1. Connecting to the API: Use your api key and secret key for authentication.
```python
import requests
from binance.client import Client
api_key = 'your_api_key'
secret_key = 'your_secret_key'
Initializing the Binance Futures client
client = Client(api_key, secret_key)
```
2. Getting the Order Book and Trades: Use the API to get the order book for a specific coin pair.
```python
pair = 'ETHBTC' # This is an example pair
symbol = client.get_symbol_info(pair)['symbol']
Getting the current price of the base asset
lastPrice = float(client.futures_now(symbol))
Fetching order book and trades data
orderbook = client.futures_book(symbol, 10)
trades = client.get_futures_trades(symbol=pair, limit=50)
```
3. Creating a Trading Strategy: You can set your own strategy but for demonstration purposes, let's assume we want to buy whenever the price of ETHBTC increases by 1% from its last trade price and sell when it decreases by 2%.
```python
min_profit = 0.01 # 1% profit required
max_loss = 0.02 # Max loss allowed is 2%
Checking if we should buy or sell based on the price movements
if lastPrice * (1 + min_profit) < orderbook['bids'][0]['price']:
client.futures_order(symbol=pair, side='BUY', type='LIMIT', quantity=1, price=orderbook['bids'][0]['price'])
elif lastPrice * (1 - max_loss) > orderbook['asks'][0]['price']:
client.futures_order(symbol=pair, side='SELL', type='LIMIT', quantity=1, price=orderbook['asks'][0]['price'])
```
4. Sending Notifications: Send notifications via Telegram to track your bot's activities.
```python
import telepot
bot = telepot.Bot('your_bot_token')
Sending a message to the user via telegram
message = f"Binance Trading Bot: {lastPrice}"
bot.sendMessage(chat_id='your_telegram_id', text=message)
```
Running Your Bot Continuously
You can use Python's `while` loop to continuously execute your bot in the background. However, running scripts like this unattended is risky, so ensure you are comfortable with what you are doing and have a solid backup strategy for any losses or unexpected events.
```python
while True:
Execute the rest of the code here
time.sleep(60) # This will refresh your bot every minute
```
Conclusion
This brief guide provided you with an example of a simple trading bot that can be adapted to suit different strategies and coin pairs based on Binance Futures API data. Remember, it is crucial to test your strategy on simulated trades before unleashing it onto the live market due to the high volatility of cryptocurrency markets. Always take necessary precautions and do thorough research before implementing any automated trading system.