KuCoin Trading Bot in Python

This guide shows how to build a KuCoin trading bot in Python with LumiBot, for both AI agent trading and algorithmic trading. LumiBot connects to KuCoin through CCXT, the open source library that talks to more than 100 crypto exchanges. You will create a KuCoin 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

KuCoin at a glance

CCXT exchange id

kucoin

Markets

Spot, Margin, Perpetual swaps, Dated futures

Testnet (sandbox)

No

Credentials

API key, API passphrase (CCXT calls it password), API secret

Live data streams

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

CCXT request spacing

about 7.5 ms between requests

Official site

https://www.kucoin.com

API docs

https://docs.kucoin.com

What is KuCoin?

KuCoin is a large crypto exchange. It offers spot trading, margin trading and futures, along with trading bots, copy trading and Earn products.

Sign up for KuCoin

  1. Sign up on the KuCoin site with your email or phone number, enter the code KuCoin sends you, and set a password.

  2. Finish identity verification (KYC). KuCoin says new users must do this before using its products.

  3. Set up Google 2FA and a trading password under Account Security. KuCoin asks for both, plus an email code, when you create an API key.

Open a KuCoin account

Create a KuCoin API key

  1. Log in at www.kucoin.com, click your avatar and choose API Management, then Create API.

  2. In the window that opens, choose API Trading (not Link Third-Party Applications).

  3. Enter an API name and an API passphrase. Write the passphrase down: LumiBot needs it, and KuCoin cannot recover it.

  4. Pick the permissions (see below) and add the IP address of your bot to the whitelist.

  5. Pass the security check with your trading password, email code and Google code, then confirm.

  6. Save the API key, secret and passphrase right away. If you lose any of them you must make a new key.

Which permissions to turn on: Turn on General (read-only: balances, statements and orders) and Spot (place and cancel spot orders). Add Futures only if your bot trades futures. Leave Withdrawal and Transfer off: Transfer lets the API move money without email or Google checks, and a bot never needs to move money out of your account.

Warning

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

Connect KuCoin to LumiBot

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

TRADING_BROKER=kucoin
KUCOIN_API_KEY=your_apiKey
KUCOIN_API_PASSPHRASE=your_password
KUCOIN_API_SECRET=your_secret

LumiBot reads exactly the fields CCXT needs for KuCoin (apiKey, password, 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 KuCoin:

import os

KUCOIN_CONFIG = {
    "exchange_id": "kucoin",
    "apiKey": os.environ.get("KUCOIN_API_KEY"),
    "password": os.environ.get("KUCOIN_API_PASSPHRASE"),
    "secret": os.environ.get("KUCOIN_API_SECRET"),
    "sandbox": False,  # live connection
}

from lumibot.brokers import Ccxt

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

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

Testing on KuCoin

KuCoin has no sandbox in CCXT (no test URL listed), so test with a very small amount. Leave KUCOIN_SANDBOX unset, and in a code config set "sandbox": False.

Algorithmic trading example: a simple KuCoin bot

This bot buys about 50 USDT of BTC on KuCoin 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. KuCoin 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 KucoinBuyOnce(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 = KucoinBuyOnce(quote_asset=Asset("USDT", asset_type=Asset.AssetType.CRYPTO))
    strategy.run_live()

Agentic trading example: an AI agent that trades on KuCoin

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 KuCoin 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 KucoinAITrader(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 KuCoin. "
                "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": "KuCoin", "quote": "USDT", "date": self.get_datetime().isoformat()},
        )


if __name__ == "__main__":
    # LumiBot reads TRADING_BROKER and the keys from your .env file.
    strategy = KucoinAITrader(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 KuCoin

Market

Listed by CCXT

Spot

Yes

Margin

Yes

Perpetual swaps

Yes

Dated futures

Yes

Options

No

CCXT lists these order features for KuCoin: stop orders, stop-loss orders, take-profit 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 KuCoin

KuCoin 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. KuCoin 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 KucoinOpenOneLong(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 = KucoinOpenOneLong(quote_asset=Asset("USDT", asset_type=Asset.AssetType.CRYPTO))
    strategy.run_live()

Fees and partner IDs on KuCoin

You pay KuCoin’s normal trading fees. CCXT, the library underneath, normally tags KuCoin 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.

KuCoin tips

  • KuCoin keys need three values: the API key, the secret and the passphrase you chose. Set KUCOIN_API_KEY, KUCOIN_API_SECRET and KUCOIN_API_PASSPHRASE.

  • Add an IP whitelist. KuCoin says keys with spot, margin or futures trading turned on but no IP address will be deleted or lose their trade permissions after 30 days of inactivity.

  • Sub-accounts can be created from the Sub-Account tab with Spot, Margin or Futures trading permissions. A sub-account per bot keeps bot funds and trades apart from manual trading.

  • Spot symbols look like BTC/USDT. CCXT also has a separate kucoinfutures id for KuCoin futures, which has its own setup.

Frequently asked questions

Can I build a KuCoin trading bot in Python?

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

Does KuCoin have a testnet?

No testnet is set up for KuCoin in LumiBot. Start with a small amount, and in a code config set "sandbox": False.

Which API permissions does a KuCoin bot need?

Turn on General (read-only: balances, statements and orders) and Spot (place and cancel spot orders). Add Futures only if your bot trades futures. Leave Withdrawal and Transfer off: Transfer lets the API move money without email or Google checks, and a bot never needs to move money out of your account.

Can an AI agent trade on KuCoin 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 KuCoin 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 KuCoin 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