Open source bot for trading on Binance. Part 2

In the last article, we put together a simple algorithm that helps to work with the exchange using the averaging strategy
While we are only sketching, we are going to a full-fledged bot by leaps and bounds, I will try to share with you the general logic that can be used to create one of the bot functions, this is a review and collection of statistics from various analytical centers, identifying the most profitable cryptocurrencies in order to avoid failed risks.

1. Receiving data from the cryptocurrency exchange

To get data from the cryptocurrency exchange, you can use the official binance API. To do this, you need to register an account on the exchange and create an API key.

An example of a request to the binance API to get a list of all available cryptocurrencies:

import requests

url="https://api.binance.com/api/v3/ticker/price"

response = requests.get(url)
data = response.json()

cryptocurrencies = [item['symbol'] for item in data]

Cryptocurrency data analysis

To analyze data on cryptocurrencies, you can use various indicators, such as price, trading volume, price changes over a certain period of time, etc. Below is an example of obtaining data on the price of a cryptocurrency:

url="https://api.binance.com/api/v3/ticker/price"

params = {'symbol': 'BTCUSDT'}

response = requests.get(url, params=params)
data = response.json()

price = float(data['price'])

Creating a list of the most profitable and stable cryptocurrency

To create a list of the most profitable and stable cryptocurrency, you can use various algorithms and strategies. For example, you can filter out cryptocurrencies with the largest trading volume, the largest price change in the last week, and so on.

Analysis of mentions of cryptocurrency on the Internet

To analyze mentions of cryptocurrency on the Internet, you can use various tools, such as social networks, forums, etc. There are various APIs and services for monitoring web mentions, such as Google Trends, Brand24, Mention, etc.

An example of using Google Trends to get cryptocurrency popularity data:

from pytrends.request import TrendReq

pytrends = TrendReq()

kw_list = ['Bitcoin']
pytrends.build_payload(kw_list, timeframe="today 5-y")
data = pytrends.interest_over_time()

popularity = data['Bitcoin'].iloc[-1]

To draw cryptocurrency analysis charts, you can use the Python Matplotlib library. Below is an example of a script that draws a graph of cryptocurrency price changes over the past 30 days:

import requests
import matplotlib.pyplot as plt
import pandas as pd
from datetime import datetime, timedelta

# Запрос цен криптовалюты на бирже Binance
symbol="BTCUSDT"
interval="1d"
limit = 30
url="https://api.binance.com/api/v3/klines"
params = {'symbol': symbol, 'interval': interval, 'limit': limit}
response = requests.get(url, params=params)
data = response.json()

# Создание списка дат и цен
dates = []
prices = []
for item in data:
    date = datetime.fromtimestamp(item[0] / 1000)
    price = float(item[4])
    dates.append(date)
    prices.append(price)

# Создание DataFrame из списка дат и цен
df = pd.DataFrame({'date': dates, 'price': prices})
df.set_index('date', inplace=True)

# Создание графика
plt.figure(figsize=(12, 6))
plt.plot(df.index, df.price)
plt.title('Price chart for ' + symbol)
plt.xlabel('Date')
plt.ylabel('Price')
plt.show()

This script gets the last 30 days of cryptocurrency price data using the Binance exchange API, creates a list of dates and prices, creates from the DataFrame list, and draws a graph using Matplotlib. You can change query parameters and chart settings to suit your needs.

risk system

Risk systems, analyzes current orders and market data, compares the conditions for setting a trading strategy and exchange activity, and buys additional coins when the market value of an asset falls

import time
import requests

# Настройки торговой стратегии
symbol="BTCUSDT"
buy_amount = 100   # количество докупаемых монет
buy_threshold = 0.05  # порог падения цены, при котором происходит докупка (5%)
sell_threshold = 0.1  # порог роста цены, при котором происходит продажа (10%)

# Данные для авторизации на бирже
api_key = 'your_api_key'
api_secret="your_api_secret"

# URL для запросов к API биржи
base_url="https://api.binance.com/api/v3"

# Функция для получения баланса по торговой паре
def get_balance(symbol):
    url = base_url + '/account'
    params = {'timestamp': int(time.time() * 1000)}
    headers = {'X-MBX-APIKEY': api_key}
    response = requests.get(url, params=params, headers=headers)
    data = response.json()
    for item in data['balances']:
        if item['asset'] == symbol:
            return float(item['free'])
    return 0.0

# Функция для размещения ордера на покупку
def place_buy_order(symbol, amount):
    url = base_url + '/order'
    params = {'symbol': symbol, 'side': 'BUY', 'type': 'MARKET', 'quantity': amount, 'timestamp': int(time.time() * 1000)}
    headers = {'X-MBX-APIKEY': api_key}
    response = requests.post(url, params=params, headers=headers)
    data = response.json()
    if 'orderId' in data:
        print('Buy order placed. Order ID:', data['orderId'])
    else:
        print('Buy order failed:', data['msg'])

# Функция для размещения ордера на продажу
def place_sell_order(symbol, amount):
    url = base_url + '/order'
    params = {'symbol': symbol, 'side': 'SELL', 'type': 'MARKET', 'quantity': amount, 'timestamp': int(time.time() * 1000)}
    headers = {'X-MBX-APIKEY': api_key}
    response = requests.post(url, params=params, headers=headers)
    data = response.json()
    if 'orderId' in data:
        print('Sell order placed. Order ID:', data['orderId'])
    else:
        print('Sell order failed:', data['msg'])

# Основной цикл программы
while True:
    # Получение текущей цены актива
    url = base_url + '/ticker/price'
    params = {'symbol': symbol}
    response = requests.get(url, params=params)
    data = response.json()
    price = float(data['price'])

    # Получение текущего баланса по активу
    balance = get_balance(symbol)

    # Если цена упала на buy_threshold (5%), размещаем ордер на покупку
    if price < (1 - buy_threshold) * balance / buy_amount:
        place_buy_order(symbol, buy_amount)
        time.sleep(60)  # ждем 1 минуту, чтобы не размещать слишком много ордеров

    # Если цена выросла на sell_threshold (10%), размещаем ордер на продажу
    elif price > (1 + sell_threshold) * balance / buy_amount:
        place_sell_order(symbol, balance)
        time.sleep(60)  # ждем 1 минуту, чтобы не размещать слишком много ордеров

    # Ждем 10 секунд перед следующей итерацией
    time.sleep(10)

In this script, we use the Binance exchange API to get the current price of an asset and the balance for a trading pair, place buy and sell orders, and set price fall and rise thresholds for rebuying and selling. The script works in an endless loop, constantly analyzing the price of an asset and placing buy or sell orders in accordance with the trading strategy settings.

We use the depth of the fall of the delta to determine the fall of the market and the pause of purchases / averaging

import time
import requests

# Настройки торговой стратегии
symbol="BTCUSDT"
buy_amount = 100   # количество докупаемых монет
delta_threshold = 0.05  # порог падения дельты, при котором происходит покупка (5%)
pause_duration = 60  # продолжительность паузы в секундах

# Данные для авторизации на бирже
api_key = 'your_api_key'
api_secret="your_api_secret"

# URL для запросов к API биржи
base_url="https://api.binance.com/api/v3"

# Функция для получения текущей цены актива
def get_price(symbol):
    url = base_url + '/ticker/price'
    params = {'symbol': symbol}
    response = requests.get(url, params=params)
    data = response.json()
    return float(data['price'])

# Функция для получения глубины рынка
def get_depth(symbol):
    url = base_url + '/depth'
    params = {'symbol': symbol}
    response = requests.get(url, params=params)
    data = response.json()
    bids = [(float(item[0]), float(item[1])) for item in data['bids']]
    asks = [(float(item[0]), float(item[1])) for item in data['asks']]
    return bids, asks

# Функция для размещения ордера на покупку
def place_buy_order(symbol, amount):
    url = base_url + '/order'
    params = {'symbol': symbol, 'side': 'BUY', 'type': 'MARKET', 'quantity': amount, 'timestamp': int(time.time() * 1000)}
    headers = {'X-MBX-APIKEY': api_key}
    response = requests.post(url, params=params, headers=headers)
    data = response.json()
    if 'orderId' in data:
        print('Buy order placed. Order ID:', data['orderId'])
    else:
        print('Buy order failed:', data['msg'])

# Основной цикл программы
while True:
    # Получение текущей цены актива и глубины рынка
    price = get_price(symbol)
    bids, asks = get_depth(symbol)

    # Вычисление дельты
    delta = bids[0][0] - price

    # Если дельта упала на delta_threshold (5%), размещаем ордер на покупку
    if delta < -delta_threshold * price:
        place_buy_order(symbol, buy_amount)
        time.sleep(pause_duration)

    # Ждем 10 секунд перед следующей итерацией
    time.sleep(10)

The script works in an infinite loop, constantly calculating the delta and placing a buy order if the delta falls to the given threshold. After placing an order, the script pauses for a given duration to avoid too frequent buying/averaging.

Transaction control so as not to make new transactions if the free balance is lower than – a certain value

import time
import requests

# Настройки торговой стратегии
symbol="BTCUSDT"
quantity = 0.001  # количество монет в одной сделке
min_balance = 100  # минимальный свободный баланс

# Данные для авторизации на бирже
api_key = 'your_api_key'
api_secret="your_api_secret"

# URL для запросов к API биржи
base_url="https://api.binance.com/api/v3"

# Функция для получения свободного баланса
def get_balance(symbol):
    url = base_url + '/account'
    params = {'timestamp': int(time.time() * 1000)}
    headers = {'X-MBX-APIKEY': api_key}
    response = requests.get(url, params=params, headers=headers)
    data = response.json()
    for item in data['balances']:
        if item['asset'] == symbol:
            return float(item['free'])
    return 0.0

# Функция для размещения ордера на покупку
def place_buy_order(symbol, quantity):
    url = base_url + '/order'
    params = {'symbol': symbol, 'side': 'BUY', 'type': 'MARKET', 'quantity': quantity, 'timestamp': int(time.time() * 1000)}
    headers = {'X-MBX-APIKEY': api_key}
    response = requests.post(url, params=params, headers=headers)
    data = response.json()
    if 'orderId' in data:
        print('Buy order placed. Order ID:', data['orderId'])
    else:
        print('Buy order failed:', data['msg'])

# Основной цикл программы
while True:
    # Получение свободного баланса
    balance = get_balance(symbol)

    # Если свободный баланс ниже минимальной суммы, ждем 10 секунд перед следующей итерацией
    if balance < min_balance:
        print('Balance is too low:', balance)
        time.sleep(10)
        continue

    # Размещение ордера на покупку
    place_buy_order(symbol, quantity)

    # Ждем 10 секунд перед следующей итерацией
    time.sleep(10)

If the free balance is below the minimum amount, the script simply waits 10 seconds before the next iteration.

This is another part, I’m still very far from a full build, but soon there will be a full build on github

Similar Posts

Leave a Reply

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