Build a Forex trading bot with Python: step-by-step guide

Building a Forex trading bot with Python: a step-by-step guide

Discover how to create your own Forex trading bot using Python, even as a beginner. This comprehensive guide walks you through setting up your trading environment, connecting to broker APIs, implementing trading strategies, and reveals the top 5 brokers for automated trading.

Python Forex bot: automate your trading in 5 simple steps

Building a Forex trading bot with Python

This guide will walk you through creating a simple yet effective Forex trading bot using Python that can connect to real FX brokers. We’ll cover everything from setting up your environment to executing automated trades, plus we’ll reveal the top 5 FX and CFD brokers for beginners.

 

Step 1: Setting up your trading bot environment

Setting up your trading bot environment

What you’ll need

  • Python 3.7+
  • Basic Python knowledge
  • A demo account with an FX broker

Install required libraries

pip install pandas numpy matplotlib ccxt ta backtrader oandapyV20

 

Step 2: Connecting to a broker API

Step 2: Connecting to a broker API

We’ll use OANDA‘s API for this example as it’s beginner-friendly.

from oandapyV20 import API
import oandapyV20.endpoints.instruments as instruments

# Set up your API connection
accountID = "your-account-id"
access_token = "your-api-token"
api = API(access_token=access_token)

# Get EUR/USD data
params = {"count": 100, "granularity": "H1"}  # 100 hourly candles
r = instruments.InstrumentsCandles(instrument="EUR_USD", params=params)
api.request(r)
print(r.response['candles'][0])  # View first candle

 

Step 3: Building a simple moving average strategy

Step 3 Building a simple moving average strategy

We’ll use:

  • RSI (Relative Strength Index) – Buy when RSI < 30 (oversold), Sell when RSI > 70 (overbought).
  • 50-period SMA – Confirm trend direction.
from ta.momentum import RSIIndicator
from ta.trend import SMAIndicator

df['rsi'] = RSIIndicator(df['close'], window=14).rsi()
df['sma50'] = SMAIndicator(df['close'], window=50).sma_indicator()

# Generate signals
df['signal'] = 0  # 0 = no trade, 1 = buy, -1 = sell
df['signal'] = np.where((df['rsi'] < 30) & (df['close'] > df['sma50']), 1, df['signal'])
df['signal'] = np.where((df['rsi'] > 70) & (df['close'] < df['sma50']), -1, df['signal'])

 

Step 4: Executing trades automatically

Step 4: Executing trades automatically

Here’s how to place trades through OANDA’s API:

from oandapyV20.endpoints.orders import OrderCreate

def place_trade(instrument, units, stop_loss=None, take_profit=None):
    data = {
        "order": {
            "units": str(units),
            "instrument": instrument,
            "timeInForce": "FOK",
            "type": "MARKET",
            "positionFill": "DEFAULT"
        }
    }
    
    if stop_loss:
        data["order"]["stopLossOnFill"] = {"price": str(stop_loss)}
    if take_profit:
        data["order"]["takeProfitOnFill"] = {"price": str(take_profit)}
    
    r = OrderCreate(accountID, data=data)
    api.request(r)
    return r.response

# Example trade execution
if df.iloc[-1]['signal'] == 1:
    current_price = df.iloc[-1]['close']
    place_trade("EUR_USD", 1000, 
               stop_loss=current_price*0.995, 
               take_profit=current_price*1.01)

 

Step 5: Backtesting your strategy

Step 5 Backtesting your strategy

Use Backtrader to test your strategy:

import backtrader as bt

class SmaCross(bt.Strategy):
    params = (('fast', 50), ('slow', 200),)

    def __init__(self):
        sma1 = bt.ind.SMA(period=self.p.fast)
        sma2 = bt.ind.SMA(period=self.p.slow)
        self.crossover = bt.ind.CrossOver(sma1, sma2)

    def next(self):
        if not self.position:
            if self.crossover > 0:
                self.buy()
        elif self.crossover < 0:
            self.close()

# Run backtest
cerebro = bt.Cerebro()
data = bt.feeds.PandasData(dataname=df.set_index('time'))
cerebro.adddata(data)
cerebro.addstrategy(SmaCross)
cerebro.run()
cerebro.plot()

 

Top 5 FX and CFD brokers for automated trading

After testing your bot, you’ll need a reliable broker. Here are the best options:

XTB

  • Best for: Low spreads + MetaTrader 4/5
  • Minimum deposit: $0
  • Regulation: FCA, CySEC, KNF
  • Special feature: Free unlimited demo account

98
Min. deposit
-
Min. Spread
0.5
Bonus
Max. leverage
1:500
Used by
656997+
Trading platforms
Own Platform
MetaTrader 4
MetaTrader 5
Web trader
Deposit methods
Bank Transfer, PayPal, Credit/Debit Cards, Neteller, Skrill
! Trading is a risky activity. Up to 69-80% of traders lose their money
Regulated by
FSC
CNMV
KNF
FCA
CySEC
98
Min. deposit
-
Max. leverage
1:500
Bonus
Used by
656997+
Min. Spread
0.5
Trading platforms
Own Platform
MetaTrader 4
MetaTrader 5
Web trader
Deposit methods
Bank Transfer, PayPal, Credit/Debit Cards, Neteller, Skrill
Regulated by
FSC
CNMV
KNF
FCA
CySEC
Broker type
Forex & CFDs
Open account
! Trading is a risky activity. Up to 69-80% of traders lose their money

 

BlackBull Markets

  • Best for: ECN trading with tight spreads
  • Minimum deposit: $200
  • Regulation: FMA (New Zealand)
  • Special feature: Raw spreads from 0.0 pips

98
Min. deposit
-
Min. Spread
0.0
Bonus
Max. leverage
1:500
Used by
-
Trading platforms
Own Platform
Web Platform
MetaTrader 5
MetaTrader 4
Deposit methods
Bank Transfer, FasaPay, Credit/Debit Cards, Neteller, Skrill
Regulated by
FMA
FSA Seychelles
98
Min. deposit
-
Max. leverage
1:500
Bonus
Used by
-
Min. Spread
0.0
Trading platforms
Own Platform
Web Platform
MetaTrader 5
MetaTrader 4
Deposit methods
Bank Transfer, FasaPay, Credit/Debit Cards, Neteller, Skrill
Regulated by
FMA
FSA Seychelles
Broker type
Forex

 

AvaTrade

  • Best for: Beginners with copy trading
  • Minimum deposit: $100
  • Regulation: Central Bank of Ireland, ASIC
  • Special feature: AvaSocial copy trading platform

97
Min. deposit
50$
Min. Spread
0.1
Bonus
Max. leverage
1:400
Used by
350000+
Trading platforms
Web Platform
ZuluTrade
MetaTrader 5
MetaTrader 4
Deposit methods
Bitcoin, Sofort, UnionPay, Credit/Debit Cards, Neteller, Wire, Skrill
Regulated by
ISA
ADGM
FFA of Japan
FSA of Japan
FSCA of South Africa
Central Bank of Ireland
CySEC
FSC of BVI
ASIC
97
Min. deposit
50$
Max. leverage
1:400
Bonus
Used by
350000+
Min. Spread
0.1
Trading platforms
Web Platform
ZuluTrade
MetaTrader 5
MetaTrader 4
Deposit methods
Bitcoin, Sofort, UnionPay, Credit/Debit Cards, Neteller, Wire, Skrill
Regulated by
ISA
ADGM
FFA of Japan
FSA of Japan
FSCA of South Africa
Central Bank of Ireland
CySEC
FSC of BVI
ASIC

 

OANDA

  • Best for: API trading and reliability
  • Minimum deposit: $0
  • Regulation: FCA, CFTC, ASIC
  • Special feature: Powerful REST API for developers

97
Min. deposit
-
Min. Spread
0.8
Bonus
Max. leverage
1:200
Used by
-
Trading platforms
Own Platform
MetaTrader 5
MetaTrader 4
Web trader
Deposit methods
UnionPay, PayPal, Credit/Debit Cards, Wire
Regulated by
IIROC
MAS
FCA
CFTC
ASIC
97
Min. deposit
-
Max. leverage
1:200
Bonus
Used by
-
Min. Spread
0.8
Trading platforms
Own Platform
MetaTrader 5
MetaTrader 4
Web trader
Deposit methods
UnionPay, PayPal, Credit/Debit Cards, Wire
Regulated by
IIROC
MAS
FCA
CFTC
ASIC

 

eToro

  • Best for: Social/copy trading
  • Minimum deposit: $50
  • Regulation: CySEC, FCA, ASIC
  • Special feature: Copy pro traders automatically

98
Min. deposit
50$
Min. Spread
0.5
Bonus
Max. leverage
1:30
Used by
30000000+
Trading platforms
Own Platform
MetaTrader 4
MetaTrader 5
Web trader
Deposit methods
Trustly, iDEAL, Rapid, Klarna, Wire
! 61% of retail CFD accounts lose money.
Regulated by
FCA
CySEC
ASIC
98
Min. deposit
50$
Max. leverage
1:30
Bonus
Used by
30000000+
Min. Spread
0.5
Trading platforms
Own Platform
MetaTrader 4
MetaTrader 5
Web trader
Deposit methods
Trustly, iDEAL, Rapid, Klarna, Wire
Regulated by
FCA
CySEC
ASIC
Open account
! 61% of retail CFD accounts lose money.

Risk disclaimer: eToro is a multi-asset platform which offers both investing in stocks and cryptoassets, as well as trading CFDs.

CFDs are complex instruments and come with a high risk of losing money rapidly due to leverage. 61% of retail investor accounts lose money when trading CFDs with this provider. You should consider whether you understand how CFDs work, and whether you can afford to take the high risk of losing your money.

This communication is intended for information and educational purposes only and should not be considered investment advice or investment recommendation. Past performance is not an indication of future results.

Copy Trading does not amount to investment advice. The value of your investments may go up or down. Your capital is at risk.

Don’t invest unless you’re prepared to lose all the money you invest. This is a high-risk investment and you should not expect to be protected if something goes wrong. Take 2 mins to learn more.

eToro USA LLC does not offer CFDs and makes no representation and assumes no liability as to the accuracy or completeness of the content of this publication, which has been prepared by our partner utilizing publicly available non-entity specific information about eToro.

 

Risk management tips

  1. Always start with a demo account
  2. Never risk more than 1-2% per trade
  3. Use stop-loss orders on every trade
  4. Test strategies with at least 3 years of data
  5. Monitor your bot daily at first

More about: Forex risk management tools: automatic trading with popular market orders

 

Next steps to improve your bot

  • Add more indicators (RSI, MACD, Bollinger Bands)
  • Implement machine learning for better signals
  • Connect to MetaTrader 5 using the Python API
  • Deploy on a cloud server for 24/5 trading

 

 

Related articles:

 

 

 

How to create your own Forex trading bot using Python - FAQ

Basic Python knowledge helps, but our guide breaks down each step simply. You'll be surprised how quickly you can get started! Learn more in the article's step-by-step coding sections.
We recommend OANDA for beginners due to its excellent API, or XTB for MetaTrader users. Our guide compares the top 5 brokers - use our special buttons to sign up and get the best deal on your preferred platform.
Many brokers like eToro and XTB offer $0 minimum deposits for demo accounts. For live trading, amounts vary (typically $50-$200). See our broker comparison for specific requirements.
While no strategy guarantees profits, automation removes emotional trading. Our guide shows how to properly backtest strategies - the article's risk management section explains key safeguards.
Absolutely! The same Python principles apply. Many featured brokers like AvaTrade and eToro offer crypto trading too. Check our recommended brokers section for crypto-friendly platforms.