Binance Trading Bot in Python

This guide shows how to build a Binance trading bot in Python with LumiBot, for both AI agent trading and algorithmic trading. LumiBot connects to Binance through CCXT, the open source library that talks to more than 100 crypto exchanges. You will create a Binance account and API key, connect it, and run two examples: a simple algorithmic trading bot and an agentic trading bot where an AI agent makes the calls.

What BotSpot MCP adds

Use Claude, ChatGPT, Codex, Cursor, VS Code or another MCP-compatible assistant? Connect the free BotSpot MCP for:

  • Skills: build LumiBot strategies.

  • Free data: news, economics and SEC filings.

  • Backtests: run tests and read charts.

  • Cloud hosting: low-cost scheduled bots.

  • Community: share bots and discuss trades.

  • Marketplace: discover and publish strategies.

  • Broker linking: connect accounts through BotSpot.

Connect your AI assistant

Binance at a glance

CCXT exchange id

binance

Markets

Spot, Margin, Perpetual swaps, Dated futures, Options

Testnet (sandbox)

Yes

Credentials

API key, API secret

Live data streams

prices, order book, trades, candles, your orders, your balance, your positions

CCXT request spacing

about 50 ms between requests

Official site

https://www.binance.com

API docs

https://developers.binance.com/en

Fees

https://www.binance.com/en/fee/schedule

What is Binance?

Binance is one of the largest crypto exchanges. It offers spot trading, margin, futures and more, with hundreds of coins to trade.

Sign up for Binance

  1. Create a Binance account on the website or app.

  2. Finish identity verification and turn on two-factor authentication (2FA). Binance requires both before you can make an API key, and also a first deposit of any amount to your Spot Wallet.

  3. For practice, log in to the Binance Spot Test Network at https://testnet.binance.vision and make a separate test API key there. Test funds are not real and test keys only work on the test network.

Open a Binance account

Create a Binance API key

  1. Log in and go to Profile, then API Management (https://www.binance.com/en/usercenter/settings/api-management).

  2. Click Create API.

  3. Pick System-generated (you get an API key and a Secret Key). Self-generated keys use Ed25519 or RSA and need your own key pair.

  4. Enter a label for the key, then confirm with your 2FA device or passkey.

  5. Click Edit restrictions, add your bot’s IP address, and turn on the trading permission (see below).

  6. Copy the API key and Secret Key and store them safely.

Which permissions to turn on: Turn on Enable Reading and Enable Spot & Margin Trading. Leave Enable Withdrawals off. Binance only lets a system-generated key trade if you add an IP address restriction. Without an IP list the key can only read.

Warning

Never turn on withdrawals for a Binance trading bot key. Bind the key to your server’s IP address when Binance lets you, keep the secret out of your code and out of Git, and delete the key if it ever leaks.

Connect Binance to LumiBot

The simplest way: put these lines in a .env file next to your strategy. LumiBot loads the file, sees TRADING_BROKER=binance and connects to Binance for you, so your strategy needs no broker code.

TRADING_BROKER=binance
BINANCE_API_KEY=your_apiKey
BINANCE_API_SECRET=your_secret
BINANCE_SANDBOX=true   # testnet; remove this line for your live account

LumiBot reads exactly the fields CCXT needs for Binance (apiKey, secret). If one is missing, LumiBot stops at start-up and names the variable you still need.

You can also build the broker in code. This is handy when one script talks to more than one exchange, or when you need extra CCXT options. The keys in the config are CCXT’s own credential names for Binance:

import os

BINANCE_CONFIG = {
    "exchange_id": "binance",
    "apiKey": os.environ.get("BINANCE_API_KEY"),
    "secret": os.environ.get("BINANCE_API_SECRET"),
    "sandbox": True,  # testnet first; set False for your live account
}

from lumibot.brokers import Ccxt

broker = Ccxt(BINANCE_CONFIG)
# then: MyStrategy(broker=broker, ...)

Either way, LumiBot turns on CCXT’s built-in rate limiting for you.

Practice on the Binance testnet

Binance runs a Spot Test Network at https://testnet.binance.vision with its own keys and free test funds. It is reset about once a month. Set BINANCE_SANDBOX=true (or "sandbox": True in a code config) to use it.

CCXT sends sandbox requests to: https://testnet.binancefuture.com/dapi/v1, https://testnet.binancefuture.com/dapi/v2. Testnet and live accounts use different keys.

Algorithmic trading example: a simple Binance bot

This bot buys about 50 USDT of BTC on Binance once and then holds it. It is a starting point to check that your keys, balances and orders work. If the exchange’s minimum order is larger, raise the amount. Binance accepts only limit orders through CCXT, so the example places a limit order just above the last price.

from lumibot.entities import Asset
from lumibot.strategies import Strategy


class BinanceBuyOnce(Strategy):
    """Buy a small amount of BTC once, then hold it."""

    def initialize(self):
        self.sleeptime = "1H"
        self.set_market("24/7")  # crypto trades all day, every day

    def on_trading_iteration(self):
        coin = Asset("BTC", asset_type=Asset.AssetType.CRYPTO)
        if self.get_position(coin) is not None:
            return  # already holding BTC
        price = self.get_last_price(coin, quote=self.quote_asset)
        if price:
            quantity = round(50 / price, 6)  # about 50 USDT worth
            # This exchange takes only limit orders through CCXT.
            order = self.create_order(coin, quantity, "buy", limit_price=price * 1.002, quote=self.quote_asset)
            self.submit_order(order)


if __name__ == "__main__":
    # LumiBot reads TRADING_BROKER and the keys from your .env file.
    strategy = BinanceBuyOnce(quote_asset=Asset("USDT", asset_type=Asset.AssetType.CRYPTO))
    strategy.run_live()

Agentic trading example: an AI agent that trades on Binance

Agentic trading means an AI agent reads the market and decides what to do. In this example one LumiBot agent looks at prices and your Binance account, then places the orders itself. There is no Python logic in between: you set the rules in plain English in the prompt, such as what it may trade and how big each order can be. This follows the same pattern as LumiBot’s AI trading team examples.

from lumibot.entities import Asset
from lumibot.strategies import Strategy


class BinanceAITrader(Strategy):
    """One AI agent researches the market and places the trades itself."""

    def initialize(self):
        self.sleeptime = "4H"
        self.set_market("24/7")
        self.agents.create(
            name="trader",
            model="openai/gpt-6-luna",
            reasoning_effort="high",
            allow_trading=True,
            system_prompt=(
                "You manage a small crypto account on Binance. "
                "You may trade BTC and ETH against USDT (asset_type 'crypto', quote_symbol 'USDT'), or hold cash. "
                "Before every order, call account_portfolio, account_positions and "
                "market_last_price for that exact symbol in the same run. "
                "Keep each order under 10% of the account value. "
                "Explain each decision in one short paragraph."
            ),
        )

    def on_trading_iteration(self):
        self.agents["trader"].run(
            task_prompt="Review recent BTC/USDT and ETH/USDT prices and your current holdings, then decide whether to buy, sell or hold.",
            context={"exchange": "Binance", "quote": "USDT", "date": self.get_datetime().isoformat()},
        )


if __name__ == "__main__":
    # LumiBot reads TRADING_BROKER and the keys from your .env file.
    strategy = BinanceAITrader(quote_asset=Asset("USDT", asset_type=Asset.AssetType.CRYPTO))
    strategy.run_live()

The agent needs a model key such as OPENAI_API_KEY in your environment. See the AI agents quickstart for models, tools and memory.

What you can trade on Binance

Market

Listed by CCXT

Spot

Yes

Margin

Yes

Perpetual swaps

Yes

Dated futures

Yes

Options

Yes

CCXT lists these order features for Binance: stop orders, stop-loss orders, take-profit orders, reduce-only orders, editing open orders, canceling orders.

For perpetual contracts, use the full CCXT symbol so the settlement currency is clear, for example BTC/USDT:USDT. See the CCXT guide for contract quantities, position modes and leverage.

Perpetual futures example on Binance

Binance also lists perpetual swaps. This bot opens one small long position in BTC/USDT:USDT worth about 50 USDT and then holds it. LumiBot treats a perpetual as asset_type="crypto_future" and sizes it in contracts, the same model as LumiBot’s Bitunix futures broker. Contract symbols can differ by exchange, so check the symbol in self.broker.api.markets before going live. In hedge mode, add position_side="long" to create_order. Binance accepts only limit orders through CCXT, so the example places a limit order just above the last price.

from lumibot.entities import Asset
from lumibot.strategies import Strategy


class BinanceOpenOneLong(Strategy):
    """Open one small long BTC perpetual position, then hold it."""

    def initialize(self):
        self.sleeptime = "1H"
        self.set_market("24/7")  # crypto trades all day, every day

    def on_trading_iteration(self):
        # The full CCXT symbol keeps the settlement currency clear.
        contract = self.broker.get_asset("BTC/USDT:USDT")
        if self.get_position(contract) is not None:
            return  # already holding the position
        price = self.get_last_price(contract)
        if price:
            # Each contract covers contract.multiplier BTC; size the order to about 50 USDT.
            quantity = round(50 / (price * contract.multiplier), 6)
            # This exchange takes only limit orders through CCXT.
            order = self.create_order(contract, quantity, "buy", limit_price=price * 1.002)
            self.submit_order(order)


if __name__ == "__main__":
    # LumiBot reads TRADING_BROKER and the keys from your .env file.
    strategy = BinanceOpenOneLong(quote_asset=Asset("USDT", asset_type=Asset.AssetType.CRYPTO))
    strategy.run_live()

Fees and partner IDs on Binance

You pay Binance’s normal trading fees. CCXT, the library underneath, normally tags Binance orders with its own partner ID. LumiBot removes that tag. LumiBot may attach its own exchange partner ID instead. That costs you nothing extra. LumiBot never adds an extra builder fee unless one is turned on, and it logs a warning when one is.

Binance tips

  • Always add an IP whitelist. Binance says a key with no IP list keeps only read access, and trading permission without an IP list used to expire after 30 days.

  • A key made before you opened your Futures account cannot get Futures permission. Open Futures first, then create the key, if you plan to trade futures.

  • CCXT uses separate ids for some Binance products: binanceusdm for USDT-margined futures, binancecoinm for coin-margined futures and binanceus for the separate Binance.US exchange. Use binance for spot.

  • The Spot Test Network only has the /api endpoints, not /sapi, so wallet and sub-account calls do not work there.

Frequently asked questions

Can I build a Binance trading bot in Python?

Yes. Install LumiBot (pip install lumibot), set your Binance keys and use the binance CCXT exchange id as shown above.

Does Binance have a testnet?

Yes. Set BINANCE_SANDBOX=true and use keys from the Binance testnet.

Which API permissions does a Binance bot need?

Turn on Enable Reading and Enable Spot & Margin Trading. Leave Enable Withdrawals off. Binance only lets a system-generated key trade if you add an IP address restriction. Without an IP list the key can only read.

Can an AI agent trade on Binance by itself?

Yes. The agentic example above gives one agent permission to trade. You control what it may trade and how much through its prompt.

Can I trade Binance perpetual futures with LumiBot?

CCXT lists perpetual swaps for this exchange. Use the full contract symbol, such as BTC/USDT:USDT.

Is LumiBot free?

Yes. LumiBot is open source on GitHub at https://github.com/Lumiwealth/lumibot. You pay only your exchange’s trading fees and, for AI agents, your model provider.

Run it in the cloud with BotSpot

Do not want to keep a computer running for your Binance bot? BotSpot is the hosted home for LumiBot strategies and AI trading agents: build with AI, backtest, connect a broker, and watch every trade with logs and alerts.

Try BotSpot

Sources