Python Forex bot: automate your trading in 5 simple steps
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
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
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
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
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
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
BlackBull Markets
- Best for: ECN trading with tight spreads
- Minimum deposit: $200
- Regulation: FMA (New Zealand)
- Special feature: Raw spreads from 0.0 pips
AvaTrade
- Best for: Beginners with copy trading
- Minimum deposit: $100
- Regulation: Central Bank of Ireland, ASIC
- Special feature: AvaSocial copy trading platform
OANDA
- Best for: API trading and reliability
- Minimum deposit: $0
- Regulation: FCA, CFTC, ASIC
- Special feature: Powerful REST API for developers
eToro
- Best for: Social/copy trading
- Minimum deposit: $50
- Regulation: CySEC, FCA, ASIC
- Special feature: Copy pro traders automatically
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
- Always start with a demo account
- Never risk more than 1-2% per trade
- Use stop-loss orders on every trade
- Test strategies with at least 3 years of data
- 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