Start investing in Bitcoin with Pix, in a few minutesSponsoredOpen free account
Python for Trading: libraries, data and first steps
Trading

Python for Trading: libraries, data and first steps

Python for Trading: Which libraries to use (Pandas, CCXT, BackTrader, VectorBT, MetaTrader5), how to download crypto candles and do the first backtest.

Photo: Unsplash

By Boletim Bitcoin newsroom

. 6 min reading.

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 account

Which libraries to use?

LibraryWhat is it forRemark
pandas and NumPyCandle tables, indicators, returnsBasis of everything
ccxtData and orders from crypto brokersMore than 100 brokers on the same interface
MetaTrader5Data and orders via MT5 terminalForex, CFDs, Gold
backtraderEvent-oriented backtest, also operates liveCommissions, slippage, sizers, analyzers
vectorbtVectorized and very fast backtestTests thousands of parameters at once
backtesting.pySimple backtest with interactive graphicsStop, target and optimizer ready
Matplotlib / PlotlyGraphicsCapital 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

  1. Install Python 3By the official website; On Windows, check the option to Add to PATH.
  2. Create a virtual environmentpython -m venv venv, to isolate the project's libraries.
  3. Install the librariespip install pandas ccxt matplotlib (and backtrader or vectorbt later).
  4. 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.

Price chart with a simple moving average and an overlapping exponential moving average 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.

Tip: Always compare with "buy and hold" the same asset in the same period. A strategy that yields less than simply keeping Bitcoin, with more work and more tax, needs another argument, like much smaller drawdown.

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

Warning: The most expensive errors are not syntax, but of method: use the closing of the candlestick to enter the same candlestick, ignore rates, test only in a bull market, optimize until the curve is perfect and put the API key with the right to serve inside the code.
  • 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

  1. pandas: Series.rolling
  2. CCXT (GitHub)
  3. Manual CCXT
  4. MQL5: Integration with Python (MetaTrader5 package)
  5. backtrader
  6. VectorBT
  7. Backtesting.py
  • Python
  • Algorithmic Trading
  • pandas
  • ccxt
  • backtrader
  • vectorbt
  • MetaTrader5

This content is informative and is not an investment recommendation. found an error? Write to contato@boletimbitcoin.com.

Read also

Start in crypto today

Open your free account, deposit with PIX and access Spot, Futures, Copy Trading and Trading Robots in one app.

  • Easy deposits
  • Copy trading
  • Grid and DCA bots
  • All-in-one app
Advertising. Crypto involves risk, invest responsibly.
Create free account