DEX · Asterdex

Building a Python Trading Bot with the AsterDEX API

This step-by-step guide shows how to build a simple trading bot in Python that interacts with the AsterDEX exchange via the REST API. We go from environment setup to placing your first order.

Introduction

Trading bots let you automate your strategies, freeing you from the need to watch the market around the clock. Using the API, we can programmatically fetch data and submit trade orders. This tutorial is intended for beginner developers familiar with the basics of Python.

Prerequisites:

  • Python 3.6+ installed
  • A basic understanding of how REST APIs work.
  • API keys generated on the AsterDEX exchange. If you don't have them yet, refer to our API guide.

Step 1: Environment Setup and Installing Libraries

To interact with the API we need the `requests` library for sending HTTP requests. Install it via pip:

pip install requests

Create a file, for example `bot.py`, and import the necessary libraries. We will also need `hmac`, `hashlib` and `time` to create the request signature.

import requests
import hmac
import hashlib
import time

# Your API keys (keep them safe!)
API_KEY = "YOUR_API_KEY"
SECRET_KEY = "YOUR_SECRET_KEY"

# Base API URL
BASE_URL = "https://fapi.asterdex.com"

Important: Never store API keys directly in your code in real projects. Use environment variables or other secure methods.

Step 2: Testing the Connection to the API

Let's make sure we can reach the server by sending a simple GET request to the `/fapi/v1/ping` endpoint.

def check_connection():
    path = "/fapi/v1/ping"
    url = BASE_URL + path

    try:
        response = requests.get(url)
        if response.status_code == 200:
            print("Соединение с API AsterDEX успешно установлено!")
            return True
        else:
            print(f"Ошибка! Статус-код: {response.status_code}, Ответ: {response.text}")
            return False
    except Exception as e:
        print(f"Произошла ошибка при подключении: {e}")
        return False

# Checking the connection
check_connection()

If everything is configured correctly, you will see a success message in the console.

Step 3: Fetching Market Data

Now let's get some real market data. For example, let's request the current order book for the `BTC/USDT` pair.

def get_order_book(symbol="BTCUSDT", limit=5):
    path = "/fapi/v1/depth"
    params = {
        "symbol": symbol,
        "limit": limit
    }
    url = BASE_URL + path

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

        # Best bid and ask prices
        best_bid = data['bids'][0][0]
        best_ask = data['asks'][0][0]

        print(f"--- Стакан для {symbol} ---")
        print(f"Лучшая покупка (Bid): {best_bid}")
        print(f"Лучшая продажа (Ask): {best_ask}")
        print("-----------------------")

        return data

    except Exception as e:
        print(f"Ошибка при получении стакана: {e}")
        return None

# Fetching the order book
get_order_book()

Step 4: Building a Signed Request to Place an Order

This is the most important step. To perform actions on your account (such as placing an order), every request must be signed with your `SECRET_KEY` using the HMAC SHA256 algorithm. This proves to the server that the request was sent by you.

We will build a function that generates the signature and sends a POST request.

def send_signed_request(method, path, params=None):
    if params is None:
        params = {}

    timestamp = int(time.time() * 1000)
    params['timestamp'] = timestamp

    query_string = '&'.join([f"{key}={params[key]}" for key in sorted(params)])

    signature = hmac.new(
        SECRET_KEY.encode('utf-8'),
        query_string.encode('utf-8'),
        hashlib.sha256
    ).hexdigest()

    params['signature'] = signature

    url = BASE_URL + path
    headers = {'X-MBX-APIKEY': API_KEY}

    try:
        if method == 'POST':
            response = requests.post(url, headers=headers, params=params)
        elif method == 'GET':
            response = requests.get(url, headers=headers, params=params)
        else:
            return None

        return response.json()

    except Exception as e:
        print(f"Ошибка при отправке подписанного запроса: {e}")
        return None

# Example: placing a test limit buy order
# IMPORTANT: Use a very small amount for testing!
def place_test_order():
    path = "/fapi/v1/order"

    # Parameters for a limit buy order: 0.001 BTC at $20,000
    # Make sure the price is realistic, otherwise the order will not fill
    params = {
        "symbol": "BTCUSDT",
        "side": "BUY",
        "type": "LIMIT",
        "timeInForce": "GTC", # Good-Til-Canceled
        "quantity": 0.001,
        "price": 20000
    }

    # For live trading add the `test=false` parameter or remove it entirely
    # For testing you can use the /fapi/v1/order/test endpoint
    # response = send_signed_request('POST', path + '/test', params)

    # For a live order:
    # response = send_signed_request('POST', path, params)

    # We commented out the real call so you don't place an order accidentally
    print("Функция для размещения ордера готова. Раскомментируйте вызов для теста.")
    # print(response)


# Calling the function for a test run
place_test_order()

Step 5: Putting It All Together — Simple Bot Logic

Now let's combine all the pieces into a simple loop. The logic is primitive, but it demonstrates the core principle of how a bot works: check the price every 10 seconds and "make a decision".

def simple_bot_logic():
    print("Запуск простого бота...")

    # The target price at which we want to buy
    target_price = 25000.0

    while True:
        try:
            order_book = get_order_book("BTCUSDT")
            if order_book:
                # Take the best ask price — the price we can buy at
                current_price = float(order_book['asks'][0][0])
                print(f"Текущая цена BTC: ${current_price}")

                if current_price < target_price:
                    print(f"Цена (${current_price}) ниже целевой (${target_price}). Время покупать!")
                    # Order placement logic would go here
                    # place_test_order()
                    break # Exiting the loop after the "purchase"
                else:
                    print(f"Цена (${current_price}) выше целевой. Ждем...")

            # Pause for 10 seconds
            time.sleep(10)

        except KeyboardInterrupt:
            print("Бот остановлен вручную.")
            break
        except Exception as e:
            print(f"Произошла ошибка в цикле бота: {e}")
            time.sleep(10)

# Uncomment the following line to start the bot loop
# simple_bot_logic()

Conclusion and Next Steps

Congratulations — you have built the skeleton of a simple trading bot. This is only a starting point. A production bot requires far more sophisticated logic, error handling and risk management.

What's next?

  • Error handling: Add robust handling for all possible API errors and network failures.
  • Advanced logic: Integrate technical indicators (RSI, moving averages) for decision-making.
  • State management: Your bot must keep track of its open orders and current positions.
  • WebSocket: For high-frequency trading, switch to the WebSocket API to receive real-time data without delays.

For the complete list of endpoints and their parameters, see the official AsterDEX API documentation.

---