Building an AI-Powered Forex Trading Bot with Python

·

Introduction

Imagine creating a real-time forex trading bot that reacts instantly to market movements. This guide walks you through building a live, AI-powered trading system designed for active traders. Using minute-level price updates streamed via TraderMade’s WebSocket API, the bot processes data in real time, calculates technical indicators, feeds signals into a trained machine learning model, and executes trades through a broker—all in one seamless loop.

Key features:


Step 1: Fetching Forex Price Data

Historical vs. Live Data

To train the AI model and operate live, you need:

  1. Historical intraday data (for model training)
  2. Live streaming data (for real-time execution)

TraderMade provides both through:

Code Example: Fetching Historical Data

import requests
import pandas as pd

api_key = 'YOUR_API_KEY'
url = 'https://marketdata.tradermade.com/api/v1/timeseries'
params = {
    'currency': 'GBPCAD',
    'interval': 'minute',
    'api_key': api_key
}
response = requests.get(url, params=params).json()
df = pd.DataFrame(response['quotes'])

Live Data via WebSocket

import websocket

def on_message(ws, message):
    print(json.loads(message))

ws = websocket.WebSocketApp("wss://marketdata.tradermade.com/feedadv", on_message=on_message)
ws.run_forever()

Step 2: Calculating Technical Indicators

Indicators convert raw price data into actionable signals:

Code Example: Indicator Calculation

import ta

def calculate_indicators(df):
    df['rsi'] = ta.momentum.RSIIndicator(close=df['close'], window=14).rsi()
    df['sma_20'] = ta.trend.SMAIndicator(close=df['close'], window=20).sma_indicator()
    return df.dropna()

Step 3: Labeling Data for AI Training

Labeling Logic:

lookahead = 15  # 15-minute window
df['future_return'] = (df['close'].shift(-lookahead) - df['close']) / df['close']
df['signal'] = df['future_return'].apply(lambda x: 1 if x > 0.0002 else (-1 if x < -0.0002 else 0))

Step 4: Training the AI Model

Why Random Forest?

Code Example: Model Training

from sklearn.ensemble import RandomForestClassifier

model = RandomForestClassifier(n_estimators=100, class_weight='balanced')
model.fit(X_train, y_train)

Evaluation Metrics:


Step 5: Live Trade Execution

Key Execution Steps:

  1. Receive live prices via WebSocket
  2. Update indicators in real time
  3. Predict signals using the trained model
  4. Place trades via OANDA’s API with stop-loss/take-profit

Code Example: Placing a Trade

def place_order(units, sl_price, tp_price):
    order_data = {
        "order": {
            "units": str(units),
            "stopLossOnFill": {"price": str(sl_price)},
            "takeProfitOnFill": {"price": str(tp_price)}
        }
    }
    requests.post(OANDA_URL, headers=headers, json=order_data)

Step 6: Risk Management

def execute_trade(signal, current_price):
    if get_open_positions():
        print("Trade already active. Skipping.")
        return
    sl, tp = calculate_sl_tp(current_price, signal)
    place_order(1000 if signal == 1 else -1000, sl, tp)

Conclusion

This bot combines real-time data, AI-driven signals, and automated execution for active forex trading. Future enhancements could include:

👉 Explore advanced trading strategies to further refine your system.


FAQs

Q: How much historical data is needed for training?
A: At least 3–6 months of minute-level data for robust signal detection.

Q: Can this bot trade other instruments?
A: Yes! Adjust the currency pair in the API calls (e.g., EURUSD).

Q: What’s the minimum latency for live execution?
A: Sub-100ms with WebSocket streaming and optimized code.