This content originally appeared on Level Up Coding - Medium and was authored by Kevin Meneses González

Introduction: The moment you realize MetaTrader is no longer enough
A few months ago, a reader reached out to me — frustrated, exhausted, and very close to giving up.
He had spent days trying to build his first Forex trading robot in MetaTrader.
He downloaded sample scripts, watched countless YouTube videos, copied random MQL5 code… and yet he still had no idea why his robot behaved the way it did.
“The robot executes trades… but I genuinely don’t understand why it’s doing anything.”
And that’s the core problem:
If you don’t understand your robot, the robot isn’t really yours.
That day, instead of trying to fix MQL code, I showed him a modern alternative:
Build the Forex robot from scratch using Python, clean data from the EODHD API, and execute trades via Alpaca or Interactive Brokers.
This approach gives you:
- full transparency
- clean and reliable data
- professional execution
- backtesting you can trust
- easy integration with AI
- automation on a real server
- and the ability to scale and evolve the system over time
Today, I’ll show you how to build this exact system — step by step.
🧭 The structure of this article
To keep everything clear and actionable, we’ll follow this roadmap:
- Data — Get clean, consistent Forex data with EODHD
- Strategy — Build your trading signals in Python
- Backtesting — Validate the strategy before risking money
- Visualization & Metrics — Analyze performance properly
- Execution — Trade live using Alpaca or Interactive Brokers
- Automation — Run the bot 24/7 on a cloud server
- Scaling — Multi-strategy systems and AI-powered enhancements
Let’s get into it.
1️. Getting clean Forex data with EODHD
Everything starts with quality data.
If your data is inconsistent, your robot will be inconsistent too.
Download historical Forex data
import requests
import pandas as pd
API = "YOUR_API_KEY"
symbol = "EURUSD.FOREX"
url = f"https://eodhd.com/api/forex-historical/{symbol}?api_token={API}&fmt=json"
df = pd.DataFrame(requests.get(url).json())
df['date'] = pd.to_datetime(df['date'])
df = df.set_index('date')
df.head()
Get real-time Forex data
url = f"https://eodhd.com/api/real-time/{symbol}?api_token={API}&fmt=json"
real = requests.get(url).json()
print(real)With clean data ready, it’s time to build the brain of the robot.
2️. Creating the strategy logic (SMA example)
We’ll start with a simple moving average crossover strategy.
df["SMA20"] = df["close"].rolling(20).mean()
df["SMA50"] = df["close"].rolling(50).mean()
df["signal"] = 0
df.loc[df["SMA20"] > df["SMA50"], "signal"] = 1
df.loc[df["SMA20"] < df["SMA50"], "signal"] = -1
df["position"] = df["signal"].diff()
Meaning:
- position = 1 → buy signal
- position = -1 → sell signal
You can later upgrade this to:
- RSI
- MACD
- Bollinger Bands
- LSTM models
- sentiment-based signals
- or hybrid systems
Generating signals is great — but without backtesting, it means nothing
3️. Adding backtesting (the essential step most beginners skip)
Let’s evaluate whether the strategy actually works.
Strategy returns
df["returns"] = df["close"].pct_change()
df["strategy_returns"] = df["returns"] * df["signal"].shift(1)
Capital growth
initial_capital = 10000
df["equity"] = initial_capital * (1 + df["strategy_returns"]).cumprod()
Drawdown
df["peak"] = df["equity"].cummax()
df["drawdown"] = (df["equity"] - df["peak"]) / df["peak"]
Sharpe Ratio
sharpe = (df["strategy_returns"].mean() / df["strategy_returns"].std()) * (252**0.5)
Numbers matter — but seeing your equity curve matters even more.
4️. Visualizing your strategy performance
import matplotlib.pyplot as plt
plt.figure(figsize=(12,6))
plt.plot(df["equity"], label="Equity Curve")
plt.title("SMA20/SMA50 Strategy on EURUSD")
plt.xlabel("Date")
plt.ylabel("Equity")
plt.legend()
plt.show()
You can also plot:
- drawdowns
- buy/sell markers
- comparison vs “buy & hold” (not applicable in Forex, but useful for stocks)
5️. Live execution using Alpaca (simple API example)
What is Alpaca?
A modern broker built for algorithmic trading with:
- zero commissions
- paper trading
- simple Python API
- great documentation
Example: Buy EURUSD
import alpaca_trade_api as tradeapi
ALPACA_KEY = "YOUR_KEY"
ALPACA_SECRET = "YOUR_SECRET"
api = tradeapi.REST(ALPACA_KEY, ALPACA_SECRET, base_url="https://paper-api.alpaca.markets")
def buy():
api.submit_order(
symbol="EURUSD",
qty=10000,
side="buy",
type="market",
time_in_force="gtc"
)
def sell():
api.submit_order(
symbol="EURUSD",
qty=10000,
side="sell",
type="market",
time_in_force="gtc"
)
Execute based on the latest signal:
latest = df.iloc[-1]
if latest["position"] == 1:
buy()
elif latest["position"] == -1:
sell()
Want institutional-grade execution? That’s where Interactive Brokers comes in.
6️. Professional execution using Interactive Brokers (IBKR)
IBKR is the gold standard for professional FX trading.
from ib_insync import *
ib = IB()
ib.connect('127.0.0.1', 7497, clientId=1)
contract = Forex('EURUSD')
order = MarketOrder('BUY', 10000)
trade = ib.placeOrder(contract, order)
7️. Running your bot 24/7 on a cloud server (AWS)
If you want your bot to trade nonstop, you need it running in the cloud.
Popular deployment options:
AWS EC2
A full virtual machine you control.
AWS Lambda
Runs your bot at intervals (good for signal-based bots).
Google Cloud Run
Perfect for Dockerized bots.
A quick CRON setup:
*/5 * * * * python robot.py
Once your bot is live, the next step is making it robust.
8️. Scaling your system: multiple strategies, blending & meta-models
Professional traders rarely use one strategy.
Instead, they run dozens in parallel and combine their signals.
You can:
- run SMA, RSI, and MACD strategies together
- mix mean-reversion + momentum systems
- apply different timeframes
- weight strategies by past performance
- create ensemble or “meta-strategies”
This improves:
- stability
- consistency
- lower drawdowns
- better diversification
Transition:
And yes — you can even enhance your robot with AI.
9️. Adding AI: using LLMs (ChatGPT, Claude, etc.) to enhance signals
You can integrate language models to:
- Extract sentiment from Forex news
- Evaluate economic reports
- summarize Fed statements
- Classify events as bullish/bearish
- generate context-aware trading signals
Example using ChatGPT API:
prompt = f"""
Analyze the following news and classify whether it has a positive,
negative, or neutral impact on EURUSD:
{news}
"""response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": prompt}]
)
sentiment = response.choices[0].message["content"]
Combine this with your SMA strategy to create hybrid systems.
FAQ — Frequently Asked Questions
Can I do all this without knowing Python?
You need basic Python skills, but the code provided gets you 90% of the way.
Is this better than MetaTrader?
For building scalable robots: yes.
For manual charting: MetaTrader is still great.
Can I run multiple strategies?
Absolutely — and you should. It increases robustness.
Is this suitable for beginners?
Yes, this article is designed for beginners to intermediate quants.
Can I backtest more professionally?
Yes: use vectorbt, Backtrader, Zipline, Lean, or custom engines.
Can I run it in the cloud?
Yes: EC2, GCP, Azure, Railway, Render, Hugging Face Spaces…
Does this work for stocks or crypto?
The architecture works for any market supported by EODHD.
Get started with EODHD (10% Discount)
If you want to build your robot using clean, reliable, affordable financial data,
you can get 10% off using my link:
👉 https://eodhd.com/pricing-special-10?via=kmg&ref1=Meneses
You get access to:
- Forex
- Stocks
- ETFs
- Intraday data
- Fundamentals
- News
- 70+ exchanges
Perfect for algorithmic trading.
Need help, guidance, or content creation?
If you need help with:
- building your bot,
- Python automation,
- data analysis,
- or if you want technical content created for your company…
Reach out anytime:
📩 kevinmensesgonzalez@gmail.com
Or connect with me on LinkedIn:
🔗 https://www.linkedin.com/in/kevin-meneses-gonzalez/
🧠 Final Thoughts
MetaTrader served an entire generation of traders.
But if you want:
- transparency
- reproducibility
- robust backtesting
- AI integration
- multi-strategy systems
- professional execution
- real automation
Then the modern architecture is clear:
→ EODHD for the data
→ Python for the logic
→ Alpaca or Interactive Brokers for execution
→ AWS/GCP for 24/7 deployment
This is how modern quantitative traders build robots — and now, so can you.
How to Build a Forex Trading Bot in Python Using EODHD API (MetaTrader vs Alpaca vs IBKR) was originally published in Level Up Coding on Medium, where people are continuing the conversation by highlighting and responding to this story.
This content originally appeared on Level Up Coding - Medium and was authored by Kevin Meneses González
Kevin Meneses González | Sciencx (2025-11-21T15:06:27+00:00) How to Build a Forex Trading Bot in Python Using EODHD API (MetaTrader vs Alpaca vs IBKR). Retrieved from https://www.scien.cx/2025/11/21/how-to-build-a-forex-trading-bot-in-python-using-eodhd-api-metatrader-vs-alpaca-vs-ibkr/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.