Bybit Trading Bot in Python¶
This guide shows how to build a Bybit trading bot in Python with LumiBot, for both AI agent trading and algorithmic trading. LumiBot connects to Bybit through CCXT, the open source library that talks to more than 100 crypto exchanges. You will create a Bybit 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.
Bybit at a glance¶
CCXT exchange id |
|
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 20 ms between requests |
Official site |
|
API docs |
|
Fees |
What is Bybit?¶
Bybit is a large crypto exchange for spot trading, perpetual and dated futures, and options. It has one of the most complete APIs in CCXT and is a CCXT certified exchange.
Sign up for Bybit¶
Create a Bybit account on the website and finish identity verification.
Wait if needed: Bybit may block API key creation for the first 48 hours after you register.
For practice, create a separate account on the Bybit testnet at https://testnet.bybit.com. Bybit also has a demo trading mode with its own keys; that is a different system from the testnet.
Create a Bybit API key¶
Open API Management on the Bybit website (https://www.bybit.com/app/user/api-management). Keys cannot be made in the app.
Click Create New Key and pick System-generated API Keys.
Choose API Transaction and give the key a name.
Set the permissions (see below) and add your bot’s IP address.
Enter your two-factor code, then copy the key and secret and store them safely.
Which permissions to turn on: Choose Read-Write. Turn on the trade permissions for what you trade: spot trading, or contract orders and positions for perpetuals. Leave withdrawals off. Freqtrade’s docs list Read-Write, Contract Orders and Contract Positions for futures bots.
Warning
Never turn on withdrawals for a Bybit trading bot key. Bind the key to your server’s IP address when Bybit lets you, keep the secret out of your code and out of Git, and delete the key if it ever leaks.
Connect Bybit to LumiBot¶
The simplest way: put these lines in a .env file next to your strategy. LumiBot loads the file, sees TRADING_BROKER=bybit and connects to Bybit for you, so your strategy needs no broker code.
TRADING_BROKER=bybit
BYBIT_API_KEY=your_apiKey
BYBIT_API_SECRET=your_secret
BYBIT_SANDBOX=true # testnet; remove this line for your live account
LumiBot reads exactly the fields CCXT needs for Bybit (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 Bybit:
import os
BYBIT_CONFIG = {
"exchange_id": "bybit",
"apiKey": os.environ.get("BYBIT_API_KEY"),
"secret": os.environ.get("BYBIT_API_SECRET"),
"sandbox": True, # testnet first; set False for your live account
}
from lumibot.brokers import Ccxt
broker = Ccxt(BYBIT_CONFIG)
# then: MyStrategy(broker=broker, ...)
Either way, LumiBot turns on CCXT’s built-in rate limiting for you.
Practice on the Bybit testnet¶
Bybit’s testnet lives at https://testnet.bybit.com and its API at https://api-testnet.bybit.com. Set BYBIT_SANDBOX=true (or "sandbox": True in a code config) to use it. Bybit’s demo trading mode is a different system with its own keys; the sandbox setting points at the testnet, not demo trading.
CCXT sends sandbox requests to: https://api-testnet.bybit.com. Testnet and live accounts use different keys.
Algorithmic trading example: a simple Bybit bot¶
This bot buys about 50 USDT of BTC on Bybit 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. Bybit 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 BybitBuyOnce(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 = BybitBuyOnce(quote_asset=Asset("USDT", asset_type=Asset.AssetType.CRYPTO))
strategy.run_live()
Agentic trading example: an AI agent that trades on Bybit¶
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 Bybit 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 BybitAITrader(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 Bybit. "
"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": "Bybit", "quote": "USDT", "date": self.get_datetime().isoformat()},
)
if __name__ == "__main__":
# LumiBot reads TRADING_BROKER and the keys from your .env file.
strategy = BybitAITrader(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 Bybit¶
Market |
Listed by CCXT |
|---|---|
Spot |
Yes |
Margin |
Yes |
Perpetual swaps |
Yes |
Dated futures |
Yes |
Options |
Yes |
CCXT lists these order features for Bybit: 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 Bybit¶
Bybit 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. Bybit 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 BybitOpenOneLong(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 = BybitOpenOneLong(quote_asset=Asset("USDT", asset_type=Asset.AssetType.CRYPTO))
strategy.run_live()
Fees and partner IDs on Bybit¶
You pay Bybit’s normal trading fees. CCXT, the library underneath, normally tags Bybit 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.
Backtesting with Bybit data¶
bybit is a documented CCXT backtesting exchange id in LumiBot. Set the data source to ccxt:
export BACKTESTING_DATA_SOURCE=ccxt
Then pass exchange_id="bybit" to CcxtBacktesting, as in lumibot/example_strategies/ccxt_backtesting_example.py. bybit itself is not a valid BACKTESTING_DATA_SOURCE value.
Backtests use historical candles through the CCXT data path. Live trading results can differ from a backtest.
Bybit tips¶
Bybit’s Unified Trading Account keeps spot and derivatives in one wallet. Traders who connect bots often say to make sure it is turned on before you create keys.
CCXT has a separate exchange id,
bybiteu, for Bybit’s EU site. It uses the api.bybit.eu API. Use the id that matches the site where you opened your account.Run one bot per sub-account. Freqtrade warns that manual trades on the same account can confuse a bot.
Frequently asked questions¶
Can I build a Bybit trading bot in Python?
Yes. Install LumiBot (pip install lumibot), set your Bybit keys and use the bybit CCXT exchange id as shown above.
Does Bybit have a testnet?
Yes. Set BYBIT_SANDBOX=true and use keys from the Bybit testnet.
Which API permissions does a Bybit bot need?
Choose Read-Write. Turn on the trade permissions for what you trade: spot trading, or contract orders and positions for perpetuals. Leave withdrawals off. Freqtrade’s docs list Read-Write, Contract Orders and Contract Positions for futures bots.
Can an AI agent trade on Bybit 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 Bybit 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 Bybit 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.
Sources¶
Bybit Help Center: How to create your API key (read 2026-10-23)
Bybit V5 API integration guide (read 2026-10-23)
Bybit Learn: how to create and set up a Bybit API key (read 2026-10-23)
Freqtrade exchange notes: Bybit (read 2026-10-23)
Practitioner video: automating TradingView alerts to Bybit (API key and Unified Trading steps) (read 2026-10-23)
Exchange id, URLs, markets, credentials and stream support: CCXT 4.5.91 metadata, generated 2026-11-01