Home

Published

- 3 min read

Real-Time Forex Trading Bot: Design, Implementation, and Architecture

img of Real-Time Forex Trading Bot: Design, Implementation, and Architecture

Introduction

This report presents the complete implementation, architecture, and functionality of a real-time Forex Trading Bot. The goal was to build a fully modular, object-oriented trading system capable of:

  • Fetching real market data in real time
  • Processing market data through a trading strategy
  • Managing risk and calculating position sizes
  • Simulating trades via a paper broker
  • Displaying market data, positions, and logs through a GUI
  • Coordinating all components via a central controller

The system uses Yahoo Finance for data, a Moving Average Crossover Strategy, a PaperBroker for simulated execution, and a Tkinter GUI with live Matplotlib charts. This project demonstrates the full lifecycle of designing quantitative trading systems using Encapsulation, Inheritance, Polymorphism, Abstraction, and Composition.


Objectives

  • Design an end-to-end algorithmic trading simulation using OOP
  • Fetch and process Forex candle data in real time
  • Implement a trading strategy that opens/closes positions automatically
  • Simulate PnL (profit and loss), trade execution, and position sizing
  • Build a graphical interface showing:
    • Live chart of prices
    • Logs of trades
    • Current open positions

Modules

1. config.py

Stores system-level constants:

  • Trading symbol (EURUSD=X)
  • Candle refresh interval
  • Initial account balance
  • Max allowed position size as a % of equity
  • Strategy parameters (fast MA, slow MA)

Demonstrates encapsulation by centralizing tunable parameters.


2. models.py

Defines data structures for:

  • Candle – Represents OHLCV market data
  • Order – Stores executed order details (side, price, size, timestamp)
  • Position – Tracks open long/short exposure and unrealized PnL

These abstractions hide internal representation and standardize component communication.


3. yahoo_data_provider.py

A real-time market data provider using yfinance:

  • Polls Yahoo Finance every BAR_SECONDS
  • Converts data to Candle objects
  • Emits new candles to subscribed callbacks

4. strategy.py

Defines the strategy base class and the implemented strategy.

StrategyBase (Abstract Base Class)

  • Uses Python’s ABC module
  • Defines required method: on_candle()
  • Provides candle storage through CandleSeries

MovingAverageCrossStrategy

  • Computes SMA (fast) and SMA (slow)
  • Generates buy/sell signals on crossings
  • Tracks last signal to avoid duplicates

5. risk_manager.py

Prevents oversized exposure and adjusts position size with equity changes:

\text{size} = \frac{\text{equity} \times \text{MAX_POSITION_PERCENT}}{\text{price}}

Controls position sizing dynamically.


6. broker.py

Simulated broker executing market orders instantly:

  • Maintains account balance
  • Tracks open positions
  • Updates unrealized PnL
  • Stores trade history
  • Handles long/short flips

7. gui.py

Graphical interface using Tkinter + Matplotlib:

  • Start/Stop buttons
  • Live price chart
  • Real-time logging console
  • Position info display

Architecture Notes

  • GUI polls get_state_callback() only on state change
  • Prevents spamming position updates every second
  • Displays candle closes as a line chart
  • Renders positions and P&L logs

8. Main.py

Central controller (“brain”) of the system:

  • Integrates all modules
  • Handles incoming candle data
  • Coordinates strategy signals
  • Routes orders through the risk manager and broker
  • Updates GUI state in real time

Event Flow inside on_candle():

  1. Strategy receives new candle
  2. Strategy evaluates buy/sell/hold
  3. Broker updates unrealized PnL
  4. Risk Manager determines position size
  5. Broker executes the market order
  6. GUI displays updated prices and PnL

Challenges and Solutions

  1. Real-time Yahoo Finance latency

    • Irregular API caused missing or duplicate candles
    • Fixed using timed loop and retry mechanism
  2. GUI freezing due to blocking operations

    • Data provider moved to background thread
    • GUI now polls state only → Tkinter freezing resolved
  3. Strategy sensitivity

    • Fast MA=1 reacted too strongly
    • Adjusted slow MA to 20
    • Prevents excessive flip-flopping
  4. Thread safety

    • PaperBroker uses threading.Lock
    • Prevents race conditions during order placement

Code Flow & Output

The system successfully fetches, processes, and executes trades while updating the GUI in real time. PnL, trade logs, and position states are displayed continuously.


Conclusion

This project demonstrates the successful design and implementation of a real-time Forex Trading Bot that integrates:

  • Data acquisition
  • Strategy execution
  • Risk management
  • Trade simulation
  • Graphical visualization

The system can be extended further by:

  • Adding multiple strategies (e.g., RSI, Bollinger Bands, ML-based signals)
  • Supporting multiple currency pairs and asset classes
  • Implementing realistic order types (limit, stop, partial fills)
  • Connecting to live brokers for actual trading
  • Enhancing the GUI with performance dashboards and analytics
  • Storing trade history and equity curves in a database

This framework mirrors real-world quantitative trading pipelines and provides a foundation for advanced algorithmic trading systems.


References

Related Posts

There are no related posts yet. 😢