Python for Trading is for three tasks: getting market data, testing strategies in history, and if it makes sense, execute orders automatically through the broker's API. With few libraries (Pandas, CCXT and a backtest tool) you download years of Bitcoin candlesticks in seconds and test an idea with costs included. This guide shows the path with code that works.
In short: Install Python 3, Pandas and CCXT. Use CCXT to download crypto candlesticks without API key crypto brokerages, pandas to calculate indicators and simulate the strategy, and move to BackTrader, VectorBT or Backtesting.py when you need stops, optimization, and reports. For Forex and CFDs, the official MetaTrader5 package reads data and sends orders through the MT5 terminal.
Why is Python so used in trading?
- Mature libraries For data, statistics and graphs.
- Connection with dozens of brokers by the same interface.
- Freedom: Any data, any rule, thousands of batch-tested variations.
- Huge community, with examples and answers to almost every error.
The price of freedom is responsibility: in Python, you yourself ensure that the backtest does not look to the future and that the live robot handles errors and disconnections. For the platform panorama, see What is Algorithmic Trading?.
Want to buy bitcoin?Deposit in reais with PIX and buy BTC and other cryptos in a few minutes.Open accountWhich libraries to use?
| Library | What is it for | Remark |
|---|---|---|
| pandas and NumPy | Candle tables, indicators, returns | Basis of everything |
| ccxt | Data and orders from crypto brokers | More than 100 brokers on the same interface |
| MetaTrader5 | Data and orders via MT5 terminal | Forex, CFDs, Gold |
| backtrader | Event-oriented backtest, also operates live | Commissions, slippage, sizers, analyzers |
| vectorbt | Vectorized and very fast backtest | Tests thousands of parameters at once |
| backtesting.py | Simple backtest with interactive graphics | Stop, target and optimizer ready |
| Matplotlib / Plotly | Graphics | Capital curve, drawdown |
O CCXT repository Informs support for more than 100 brokers, including Binance and BingX, in various languages. The VectorBT It differs by processing many strategies together in arrays, accelerated by NUMBA. The backtrader It has commission modules, slippage and integration with some brokers. The Backtesting.py It's lightweight, uses pandas, NumPy and bokeh and brings an optimizer.
Step 1: Prepare the environment
- Install Python 3By the official website; On Windows, check the option to Add to PATH.
- Create a virtual environmentpython -m venv venv, to isolate the project's libraries.
- Install the librariespip install pandas ccxt matplotlib (and backtrader or vectorbt later).
- Use an editorVS Code or Jupyter Notebook, which shows tables and charts cell by cell.
Step 2: Download Crypto Candles with CCXT
Public market data does not require API key:
import ccxt
import pandas as pd
exchange = ccxt.binance() # dados públicos não exigem chave de API
candles = exchange.fetch_ohlcv("BTC/USDT", timeframe="1d", limit=1000)
df = pd.DataFrame(candles, columns=["timestamp", "open", "high", "low", "close", "volume"])
df["date"] = pd.to_datetime(df["timestamp"], unit="ms")
df = df.set_index("date")
df.to_csv("btcusdt_1d.csv")
print(df.tail())
fetch_ohlcv Returns lists with time (in milliseconds), opening, maximum, minimum, closing and volume. Each broker has a candlestick limit per call; The CCXT MANUAL Describes the pagination to download larger histories and reminds you that the control of the request limit (enableRateLimit) is enabled by default.
Step 3: Calculate indicators with pandas
import pandas as pd
df = pd.read_csv("btcusdt_1d.csv", parse_dates=["date"], index_col="date")
df["sma20"] = df["close"].rolling(20).mean()
df["sma50"] = df["close"].rolling(50).mean()
df["retorno"] = df["close"].pct_change()
df["vol_anual"] = df["retorno"].rolling(30).std() * (365 ** 0.5)
print(df[["close", "sma20", "sma50", "vol_anual"]].tail())
The method rolling Create mobile windows: rolling(20).mean() It is the simple moving average of 20 periods. Annualized volatility uses 365 days because crypto trades every day; in actions, it is used about 252. Understand the averages in moving averages.
Simple and exponential moving averages, which in Pandas come out of rolling().mean() and ewm().mean(). Credit: Alex Kofman, Public Domain, via Wikimedia Commons.
Step 4: The first backtest, with costs
With the columns above, the “bought when the SMA20 is above the SMA50” strategy looks like this:
posicao = (df["sma20"] > df["sma50"]).astype(int).shift(1).fillna(0)
trocas = posicao.diff().abs().fillna(0)
custo = 0.001 # 0,1% por troca: taxa + slippage estimado
ret_estrategia = posicao * df["retorno"].fillna(0) - trocas * custo
curva = (1 + ret_estrategia).cumprod()
drawdown = curva / curva.cummax() - 1
print(f"Retorno: {curva.iloc[-1] - 1:.1%} | Drawdown máximo: {drawdown.min():.1%}")
O shift(1) It guarantees that the decision taken at the end of a day only applies from the next day. Without it, the test “buy” with information that did not yet exist. metrics, traps and the effect of costs are in backtest; Why not optimize too much, in Overfitting in Trading.
Forex and CFDs: the MetaTrader5 package
For those operating on MetaTrader 5, the official package connects Python to the installed terminal. He reads bars and sends orders, according to the MQL5 documentation. installation: pip install MetaTrader5.
import MetaTrader5 as mt5
import pandas as pd
if not mt5.initialize():
raise SystemExit(f"Falha ao conectar ao terminal: {mt5.last_error()}")
barras = mt5.copy_rates_from_pos("EURUSD", mt5.TIMEFRAME_H1, 0, 1000)
mt5.shutdown()
df = pd.DataFrame(barras)
df["time"] = pd.to_datetime(df["time"], unit="s")
print(df[["time", "open", "high", "low", "close"]].tail())
The terminal needs to be open and logged in; The documentation walkthrough is done on Windows. For robots that run within the MT5 itself, see MQL5 Expert Advisor e o MetaTrader 5 Guide.
From backtest to live robot
Search
- Historical data in CSV
- pandas, vectorbt, backtrader
- Mistakes cost only time
Execution
- API keys and 24h connected server
- Error handling, reconnection, logs
- Mistakes cost money
To operate live in crypto, CCXT uses the same methods with API keys (create_order, fetch_balance). Before going to the real account:
- Save the keys in environment variables, never in code;
- Create the key without withdrawal permission and with an IP list;
- Test in a simulation environment when the brokerage offers;
- Have daily loss limit and maximum order size in the code.
All this is detailed in Crypto brokerage API. ready-made logics such as grid and DCA, compared with trend and reversion, are in robot strategies.
To follow the construction of a complete Python algorithm in a single class in Portuguese, the video below is a good complement.
Common mistakes of those who start
- Spindle and dates: Brokers deliver UTC schedules. Convert carefully.
- Missing data: Missing candles distort averages; Check gaps.
- Requisition limits: Respect the Rate Limit or the broker temporarily blocks your IP.
- TAX: Automated crypto operations also enter the investigation; vide Cryptocurrency Income Tax.
Python is the most flexible tool for anyone looking to search and automate. Use this flexibility to test rigorously, not to torture the data until they confess.
Informational content, not investment advice.
Frequently asked questions
Python is for trading?
Yes. Python is the language most used in quantitative research because it has libraries for data (PANDAS), connection with brokers (CCXT, MetaTrader5) and backtest (BackTrader, VectorBT, Backtesting.PY).
What python libraries to use for trading?
To get started: Pandas and NumPy for data, CCXT for crypto brokers, the MetaTrader5 package for Forex and CFDs via MT5, and a backtest library such as BackTrader, VectorBT or Backtesting.py. matplotlib or plotly for graphics.
Do I need to know how to program a lot to use Python in trading?
The basics of Python (variables, functions, lists and dictionaries) and Pandas already allows you to download data and test simple strategies. To operate live, you need to learn error handling, logs and key security.
Python or Pine Script?
Pine Script is faster to test ideas on the TradingView chart. Python gives you complete freedom to search with any data, test thousands of variations, and automate execution by API.
References
This content is informative and is not an investment recommendation. found an error? Write to contato@boletimbitcoin.com.