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:
- Real-time data processing for instant market reactions
- AI-driven decision-making using technical indicators
- Automated execution with built-in risk management
Step 1: Fetching Forex Price Data
Historical vs. Live Data
To train the AI model and operate live, you need:
- Historical intraday data (for model training)
- Live streaming data (for real-time execution)
TraderMade provides both through:
- REST API for historical minute-level OHLC data
- WebSocket API for live tick data
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:
- RSI (14-period): Momentum
- SMA (20/50): Trend direction
- Bollinger Bands: Volatility
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:
- Buy (1): Price increase > 0.02% in 15 minutes
- Sell (-1): Price decrease > 0.02%
- Hold (0): Price within threshold
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?
- Handles non-linear patterns
- Reduces overfitting
- Provides feature importance rankings
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:
- Accuracy: 56.2%
- Balanced precision/recall across all classes
Step 5: Live Trade Execution
Key Execution Steps:
- Receive live prices via WebSocket
- Update indicators in real time
- Predict signals using the trained model
- 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
- Stop-loss: 10 pips
- Take-profit: 15 pips
- Position checks: Prevent overlapping trades
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:
- Reinforcement learning
- Multi-pair correlation analysis
- Volatility-based position sizing
👉 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.