Automating your trading strategy can save time, reduce emotional decision-making, and improve execution speed. In this comprehensive guide, you'll learn how to build a functional algorithmic trading bot using Python and connect it to a live market via a broker API. We’ll focus on XTB, a popular broker offering API access, and walk through setting up real-time data streaming, processing candlestick data, and executing trades automatically.
Whether you're new to algorithmic trading or looking to refine your technical implementation, this tutorial provides a solid foundation for creating your own trading bot.
Why Automate Trading?
Algorithmic trading relies on predefined rules—your strategy—to make buy or sell decisions. While you could manually follow these signals, doing so consistently under pressure is challenging. Automation removes human emotion and ensures timely execution.
Python is ideal for this task due to its rich ecosystem: powerful libraries like pandas, numpy, and datetime, combined with accessible broker APIs, make building a trading bot both efficient and scalable.
👉 Discover how automated trading can enhance your strategy execution today.
Getting Started with XTB API Access
To automate trading with XTB, you need API access through their xAPI system. Here's how to get started:
- Open a free demo account at XTB (no deposit required).
- Log into xStation, the trading platform.
- Locate your 8-digit demo account number in the top-right corner.
- Note your demo account password—this will be used for API authentication.
Store your credentials securely in a separate config.py file to avoid exposing sensitive data in your main script:
user_id = 12345678 # Replace with your actual demo account number
pwd = 'your_password_here'Next, download the official xAPIConnector.py wrapper from the XTB Developer Portal. This Python module simplifies communication with the XTB API.
Test Your Connection
Use the following script to verify that your credentials work and you can stream live tick data:
from xAPIConnector import *
import config
user_id = config.user_id
pwd = config.pwd
client = APIClient()
resp = client.execute(loginCommand(user_id, pwd))
ssid = resp['streamSessionId']
sclient = APIStreamClient(ssId=ssid, tickFun=procTickExample)
sclient.subscribePrice('EURUSD')
time.sleep(60)
sclient.unsubscribePrice('EURUSD')
sclient.disconnect()
client.disconnect()If successful, you’ll see real-time tick output like:
TICK: {'command': 'tickPrices', 'data': {'symbol': 'EURUSD', 'ask': 1.09495, 'bid': 1.09487, ...}}This confirms your connection is live and ready for deeper integration.
Introducing XtbTrader.py: The Core Trading Module
The heart of our bot is the XtbTrader class—a reusable Python module designed to manage data streaming, strategy execution, and trade placement.
You can find the full code on GitHub, but let’s break down its structure and functionality.
Initialize the Trader Class
class XtbTrader:
def __init__(self, client, ssid, instrument, interval, lookback, strategy, units, end, csv_results_path):
"""
Arguments:
- client: XTB API client instance
- ssid: Stream session ID
- instrument: Trading pair (e.g., 'EURUSD')
- interval: Candle timeframe ('1min', '5min', etc.)
- lookback: Number of historical candles to fetch
- strategy: Function defining entry/exit logic
- units: Trade size (e.g., 0.1 contract)
- end: Session end time ('YYYY-mm-dd HH:MM')
- csv_results_path: Directory to save logs
"""Ensure you also download valid_xtb_symbols.json from the repository to validate instrument symbols before trading.
Key Methods Explained
history_converter(self, history)
Converts raw JSON price data from the API into a clean pandas.DataFrame. It adjusts for digit precision and computes OHLC (Open, High, Low, Close) values.
df['open'] = df['open'] / (10 ** digits)
df['close'] = df['open'] + df['close'] / (10 ** digits)It also applies your chosen strategy function to generate trading signals.
get_last_n_candles(self)
Fetches historical price data required to initialize indicators (like moving averages). This is essential because most strategies depend on past performance.
data = self.client.commandExecute('getChartRangeRequest', arguments=args)Note: XTB has limits on how much historical data you can retrieve per request.
procCandle(self, msg)
Processes incoming real-time candle updates. This method:
- Aggregates minute-level ticks into higher timeframes (e.g., 5-minute candles).
- Updates the price dataframe.
- Triggers strategy evaluation.
- Executes trades when signals change.
It also checks whether the session end time has been reached and shuts down cleanly.
trade(self)
Monitors position changes and executes orders accordingly:
- Opens a buy if position shifts from 0 or -1 to +1.
- Opens a sell if shifting to -1.
- Closes existing positions when signal returns to 0.
This ensures only one active trade exists at any time.
open_position(self, position_type) & close_order(self)
These handle actual trade execution via tradeTransaction commands. They include safeguards:
- Confirm order acceptance.
- Verify closure before opening new trades.
- Prevent overlapping leveraged positions.
👉 Learn how advanced traders structure their automated systems for consistency.
Putting the Bot Into Action
Let’s test the bot with a simple contrarian strategy—one that bets on short-term reversals.
def contrarian(df, window=1):
df["returns"] = np.log(df['close'] / df['close'].shift(1))
df["position"] = -np.sign(df["returns"].rolling(window).mean())
return dfNow initialize the bot in test_trader.py:
from XtbTrader import XtbTrader
from xAPIConnector import APIClient, loginCommand
import config
if __name__ == '__main__':
client = APIClient()
resp = client.execute(loginCommand(config.user_id, config.pwd))
ssid = resp['streamSessionId']
xt = XtbTrader(
client=client,
ssid=ssid,
instrument='EURUSD',
interval='5min',
lookback=1000,
strategy=contrarian,
units=0.1,
end='2025-12-31 23:59',
csv_results_path='./results/'
)
while True:
if xt.terminate_session:
break
time.sleep(1)
client.disconnect()Run it:
python3 test_trader.pySample output shows live trade execution:
START TRADING AT Wed,10 Jan, 2024, 09:05:02 |instrument: EURUSD| strategy: contrarian | interval: 5min
Sell order number 580885322 ... accepted
Trade profit: -1.6
Cumulative profit: -1.6
...
TRADING SESSION END AT Wed,10 Jan, 2024, 09:51:01
Profit generated during trading session: -0.8All price data and trade logs are saved in CSV files for later analysis.
Frequently Asked Questions
Can I use this bot with real money?
Yes—but proceed with caution. To switch from demo to live trading:
- Update
DEFAULT_XAPI_PORT = 5112andDEFAULT_XAPI_STREAMING_PORT = 5113inxAPIConnector.py. - Use a funded account and real credentials.
- Always backtest thoroughly before going live.
Is algorithmic trading profitable?
Profitability depends on your strategy quality, risk management, and market conditions. Many bots fail due to overfitting or poor execution logic. Start small and iterate.
How do I prevent multiple trades at once?
The XtbTrader class includes built-in safeguards:
- Only one position allowed at a time.
- Orders are confirmed before proceeding.
- Active trades are checked before opening new ones.
Can I run the bot 24/7 on a server?
Absolutely. In future parts of this series, we’ll cover deploying your bot on a cloud server (e.g., AWS, Google Cloud) using tools like screen, systemd, or Docker for uninterrupted operation.
What instruments can I trade?
XTB supports Forex, indices, commodities, and cryptocurrencies. Ensure the symbol matches those listed in valid_xtb_symbols.json. For example:
- EURUSD (Forex)
- US500 (S&P 500 Index)
- XAUUSD (Gold)
Does this work with other brokers?
This implementation is specific to XTB’s xAPI. However, the core concepts apply universally. Brokers like OKX, Interactive Brokers, or Binance offer similar APIs with Python wrappers.
👉 Explore high-performance trading platforms that support API automation.
Final Thoughts
Building your own trading bot gives you full control over strategy logic, execution speed, and risk parameters. In this first part, we’ve laid the groundwork: connecting to XTB’s API, streaming data, applying a strategy, and automating trades.
In upcoming articles, we’ll dive into:
- Strategy optimization and backtesting.
- Deploying bots on remote servers.
- Adding email/SMS alerts.
- Risk management frameworks.
Remember: This is educational content only. Trading involves significant risk. Always test strategies in demo mode and never invest more than you can afford to lose.
Stay tuned for Part II—where we take automation to the next level.