Great question! backtrader itself is a backtesting framework — it does not directly connect to live exchanges or trade live out-of-the-box. However, it can be integrated with live data feeds and brokers if you connect it properly.
Using backtrader with MEXC Exchange
- MEXC is a cryptocurrency exchange.
- To use live or historical data from MEXC inside
backtrader, you need to:
- Obtain market data (historical candles or live ticks) from MEXC’s API.
- Feed this data into
backtrader in a format it understands (e.g., OHLCV candles).
- For live trading, create or use a broker interface to send orders to MEXC.
Step 1: Get Historical Market Data from MEXC
MEXC provides REST APIs to get historical kline/candlestick data.
You can write a script to pull historical candle data, then convert it into a CSV or feed it directly into backtrader.
Example snippet using requests to get historical data:
import requests
import pandas as pd
import datetime
import backtrader as bt
def fetch_mexc_klines(symbol="BTC_USDT", interval="1m", limit=1000):
"""
Fetch historical candlesticks from MEXC
interval: 1m,5m,15m,30m,1h,1d etc.
limit: number of data points
"""
url = f"https://contract.mexc.com/api/v1/contract/kline"
params = {
"symbol": symbol,
"interval": interval,
"limit": limit
}
resp = requests.get(url, params=params)
data = resp.json()
if data['success'] is False:
raise Exception(f"API Request failed: {data}")
klines = data['data']
# Convert to DataFrame
df = pd.DataFrame(klines, columns=["open_time", "open", "high", "low", "close", "volume"])
# open_time is in ms, convert it to datetime
df['datetime'] = pd.to_datetime(df['open_time'], unit='ms')
df.set_index('datetime', inplace=True)
df = df[['open','high','low','close','volume']].astype(float)
return df
# Example usage:
df = fetch_mexc_klines()
print(df.head())
You can then save df as a CSV or feed directly into backtrader.
Step 2: Feed Data into backtrader
backtrader can use pandas DataFrames via PandasData feed class.
Add your MEXC data like:
class MEXCPandasData(bt.feeds.PandasData):
# Override default data headers for compatibility
params = (
('datetime', None),
('open', 'open'),
('high', 'high'),
('low', 'low'),
('close', 'close'),
('volume', 'volume'),
('openinterest', -1),
)
# Then add data to cerebro:
cerebro = bt.Cerebro()
mexc_data = MEXCPandasData(dataname=df)
cerebro.adddata(mexc_data)
Step 3: Live Trading and Broker Integration
- Currently,
backtrader has built-in brokers for IB, Oanda, Interactive Brokers, and some crypto brokers, but NOT MEXC directly.
- You would need to build a custom broker and live data feed adapter for MEXC using their API to handle order execution, order status updates, balances, etc.
- This requires advanced programming to:
- Manage authentication.
- Handle order REST API or WebSocket.
- Synchronize
backtrader’s order system with MEXC’s.
- Manage real-time data feed (WebSocket recommended for real-time ticks/candles).
If you want to go down this path, I can help you with a minimal adapter template!
Summary
| Usage | Possible? | How to Implement |
|---|
| Historical Backtest | Yes | Fetch historical klines from MEXC REST API, then feed into backtrader as pandas DataFrame or CSV feed |
| Live Trading | Possible, not out of box | Write custom broker and data feed adapter to connect to MEXC live REST and WebSocket APIs |
Bonus: Minimal data fetch + backtesting example
import backtrader as bt
import pandas as pd
import requests
def fetch_mexc_data():
url = "https://contract.mexc.com/api/v1/contract/kline"
params = {
"symbol": "BTC_USDT",
"interval": "1h",
"limit": 500
}
r = requests.get(url, params=params)
data = r.json()['data']
df = pd.DataFrame(data, columns=['open_time','open','high','low','close','volume'])
df['datetime'] = pd.to_datetime(df['open_time'], unit='ms')
df.set_index('datetime', inplace=True)
df = df[['open','high','low','close','volume']].astype(float)
return df
class MEXCPandasData(bt.feeds.PandasData):
lines = ('volume',)
params = (('datetime', None),
('open', 'open'),
('high', 'high'),
('low', 'low'),
('close', 'close'),
('volume', 'volume'),
('openinterest', -1))
class SmaCrossStrategy(bt.Strategy):
# Simple SMA crossover strategy as before
def __init__(self):
self.sma_fast = bt.indicators.SimpleMovingAverage(self.datas[0], period=10)
self.sma_slow = bt.indicators.SimpleMovingAverage(self.datas[0], period=30)
self.order = None
def next(self):
if self.order:
return # pending order
if not self.position:
if self.sma_fast[0] > self.sma_slow[0]:
self.order = self.buy()
else:
if self.sma_fast[0] < self.sma_slow[0]:
self.order = self.sell()
if __name__ == '__main__':
df = fetch_mexc_data()
cerebro = bt.Cerebro()
data = MEXCPandasData(dataname=df)
cerebro.adddata(data)
cerebro.addstrategy(SmaCrossStrategy)
cerebro.broker.setcash(10000)
print('Starting Portfolio Value: %.2f' % cerebro.broker.getvalue())
cerebro.run()
print('Final Portfolio Value: %.2f' % cerebro.broker.getvalue())
cerebro.plot()
If you want, I can help you write code for a custom live broker or WebSocket data feed for MEXC! Just ask.