F

Forex Journal Team

June 13, 20262 min read

Build a Python Trading Bot: Complete Step-by-Step Tutorial

pythontrading-botautomationprogrammingtechnology

Building a Python Trading Bot

Python is the perfect language for trading bots — extensive library support, easy to learn, and powerful for data analysis.

What This Bot Does

  • Connects to a broker via API
  • Fetches real-time price data
  • Calculates technical indicators (RSI, MACD, EMAs)
  • Executes trades based on rules
  • Manages risk (stop loss, take profit)
  • Logs every trade

Prerequisites

pip install ccxt pandas numpy ta
  • ccxt — cryptocurrency exchange API (works for crypto)
  • For forex, use MetaTrader5 Python package or broker-specific API

Basic Bot Structure

import ccxt
import pandas as pd
import numpy as np
from ta.momentum import RSIIndicator

class TradingBot:
    def __init__(self, exchange, symbol, params):
        self.exchange = exchange
        self.symbol = symbol
        self.rsi_period = params.get('rsi_period', 14)
        self.rsi_oversold = params.get('rsi_oversold', 30)
        self.rsi_overbought = params.get('rsi_overbought', 70)
        self.positi 0.01)
        
    def fetch_data(self, limit=100):
        ohlcv = self.exchange.fetch_ohlcv(self.symbol, '5m', limit=limit)
        df = pd.DataFrame(ohlcv, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume'])
        df['rsi'] = RSIIndicator(df['close'], window=self.rsi_period).rsi()
        return df
    
    def check_signals(self, df):
        latest_rsi = df['rsi'].iloc[-1]
        if latest_rsi < self.rsi_oversold:
            return 'buy'
        elif latest_rsi > self.rsi_overbought:
            return 'sell'
        return None
    
    def place_order(self, signal):
        side = 'buy' if signal == 'buy' else 'sell'
        order = self.exchange.create_market_order(
            self.symbol, side, self.position_size
        )
        return order
    
    def run(self):
        df = self.fetch_data()
        signal = self.check_signals(df)
        if signal:
            order = self.place_order(signal)
            print(f"Order placed: {order}")
            self.log_trade(signal, df['close'].iloc[-1])

Risk Management

Every bot needs non-negotiable safety rules:

def check_risk_limits(self):
    # Max daily loss: 2%
    if self.daily_pnl < -self.account_balance * 0.02:
        return False
    # Max open positions: 3
    if len(self.open_positions) >= 3:
        return False
    # Min time between trades: 5 minutes
    if time.time() - self.last_trade_time < 300:
        return False
    return True

Testing Your Bot

  1. Run on historical data first (backtest)
  2. Then use a paper trading account
  3. Start with tiny size on a live account
  4. Monitor daily for the first month
  5. A trading journal is essential for bot performance tracking
F

Written by Forex Journal Team

Track every trade. Master your edge.

Forex Journal helps you log, analyze, and improve your trading across forex, indices, crypto, and futures — all 100% free.

Start your free journal