Using Python & WebSockets to Generate Live OHLC Forex Data

This tutorial guides you through building a real-time Forex OHLC data generator using Python and WebSockets. Learn how to stream FX prices, convert them to OHLC format, and save the results with clean, efficient code. Accessing real-time market data is essential for modern trading and financial analytics. WebSockets provide an efficient method for live, continuous data streaming. In this tutorial, we’ll walk through how to use Python to connect to a WebSocket stream, collect Forex pricing data, and convert it into OHLC (Open, High, Low, Close) bars. What You'll Need Before we start, ensure you have: Python installed on your machine. Basic understanding of how to use Python. Get Your API Key To stream live Forex data, you’ll need a TraderMade API key. Sign up for a 14-day free trial and find your API key in your account dashboard. Refer to the platform's documentation for helpful examples and guidance. Let’s Get Started We’ll be using the tradermade Python package to access live FX rates. The data will be processed into OHLC format and written to a text file in real-time. Step 1: Install the TraderMade Package Install the required package using pip: pip install tradermade Step 2: Import Required Libraries Begin by importing the modules needed to handle WebSocket streaming, manipulate data structures, and format time. from tradermade import stream import json from datetime import datetime from collections import defaultdict Step 3: Initialize Data Structures Prepare dictionaries and variables for managing OHLC values, tracking intervals, and defining output behaviour. ohlc_data = defaultdict(lambda: defaultdict(lambda: {'open': 0, 'high': 0, 'low': 0, 'close': 0})) previous_interval = None count = 0 interval = 1 format = '%Y-%m-%d %H:%M' output_file = 'ohlc_output.txt' Step 4: Define Utility Functions Now we’ll create three utility functions to handle time rounding, file writing, and updating OHLC values. Each function plays a specific role: round_timestamp(timestamp, interval_minutes) This function rounds any incoming timestamp to the nearest defined time interval. Useful for aligning price data into fixed OHLC intervals. Replaces seconds and microseconds, rounding down to the nearest minute block. save_to_file(data) Appends a string to the output text file. Ensures processed OHLC entries are saved for future use. Opens the file in append mode and writes the data with a space separator. update_ohlc_data(current_interval, currency, mid) Updates the OHLC values for each currency pair during the given interval. If no data exists yet for the interval and currency, it initializes values with the current price. The 'open' is set at the start, and the 'high'/'low' are tracked as data flows in. The 'close' is updated every time new data is received in that interval. def round_timestamp(timestamp, interval_minutes): rounded_minutes = (timestamp.minute // interval_minutes) * interval_minutes rounded_time = timestamp.replace(second=0, microsecond=0, minute=rounded_minutes) return rounded_time def save_to_file(data): with open(output_file, 'a') as f: f.write(data + ' ') def update_ohlc_data(current_interval, currency, mid): if current_interval not in ohlc_data: ohlc_data[current_interval] = defaultdict(lambda: {'open': mid, 'high': mid, 'low': mid, 'close': mid}) elif currency not in ohlc_data[current_interval]: ohlc_data[current_interval][currency] = {'open': mid, 'high': mid, 'low': mid, 'close': mid} else: ohlc_data[current_interval][currency]['high'] = max(ohlc_data[current_interval][currency]['high'], mid) ohlc_data[current_interval][currency]['low'] = min(ohlc_data[current_interval][currency]['low'], mid) ohlc_data[current_interval][currency]['close'] = mid Step 5: Connect to the WebSocket Stream You’re now ready to initiate the WebSocket connection. Use your API key and specify the currency symbols you'd like to stream. stream.set_ws_key("API_KEY") # Replace with your actual API key stream.set_symbols("USDJPY,EURGBP") stream.stream_data(process_data) stream.connect() Step 6: Run Your Script Finally, execute the script to start processing live data and generating OHLC output. python websocket_ohlc.py After running the program, a file named ohlc_output.txt will appear in your working directory. It will contain a growing log of OHLC data points based on your specified interval. Conclusion You’ve just built a working solution for streaming live Forex data and transforming it into OHLC bars using Python and WebSockets. This setup can serve as a foundation for real-time dashboards, trading bots, or analytical tools. Please refer to: The tutorial originally published on our website: Create Real-time OHLC Data with Python WebSo

Apr 30, 2025 - 13:33
 0
Using Python & WebSockets to Generate Live OHLC Forex Data

This tutorial guides you through building a real-time Forex OHLC data generator using Python and WebSockets. Learn how to stream FX prices, convert them to OHLC format, and save the results with clean, efficient code.

Accessing real-time market data is essential for modern trading and financial analytics. WebSockets provide an efficient method for live, continuous data streaming. In this tutorial, we’ll walk through how to use Python to connect to a WebSocket stream, collect Forex pricing data, and convert it into OHLC (Open, High, Low, Close) bars.

What You'll Need

Before we start, ensure you have:

  • Python installed on your machine.
  • Basic understanding of how to use Python.

Get Your API Key

To stream live Forex data, you’ll need a TraderMade API key. Sign up for a 14-day free trial and find your API key in your account dashboard. Refer to the platform's documentation for helpful examples and guidance.

Let’s Get Started

We’ll be using the tradermade Python package to access live FX rates. The data will be processed into OHLC format and written to a text file in real-time.

Step 1: Install the TraderMade Package

Install the required package using pip:

pip install tradermade

Step 2: Import Required Libraries

Begin by importing the modules needed to handle WebSocket streaming, manipulate data structures, and format time.

from tradermade import stream
import json
from datetime import datetime
from collections import defaultdict

Step 3: Initialize Data Structures

Prepare dictionaries and variables for managing OHLC values, tracking intervals, and defining output behaviour.

ohlc_data = defaultdict(lambda: defaultdict(lambda: {'open': 0, 'high': 0, 'low': 0, 'close': 0}))
previous_interval = None
count = 0
interval = 1
format = '%Y-%m-%d %H:%M'
output_file = 'ohlc_output.txt'

Step 4: Define Utility Functions

Now we’ll create three utility functions to handle time rounding, file writing, and updating OHLC values. Each function plays a specific role:

round_timestamp(timestamp, interval_minutes)

This function rounds any incoming timestamp to the nearest defined time interval.

  • Useful for aligning price data into fixed OHLC intervals.
  • Replaces seconds and microseconds, rounding down to the nearest minute block.

save_to_file(data)

Appends a string to the output text file.

  • Ensures processed OHLC entries are saved for future use.
  • Opens the file in append mode and writes the data with a space separator.

update_ohlc_data(current_interval, currency, mid)

Updates the OHLC values for each currency pair during the given interval.

  • If no data exists yet for the interval and currency, it initializes values with the current price.
  • The 'open' is set at the start, and the 'high'/'low' are tracked as data flows in.
  • The 'close' is updated every time new data is received in that interval.
def round_timestamp(timestamp, interval_minutes):
    rounded_minutes = (timestamp.minute // interval_minutes) * interval_minutes
    rounded_time = timestamp.replace(second=0, microsecond=0, minute=rounded_minutes)
    return rounded_time
def save_to_file(data):
    with open(output_file, 'a') as f:
        f.write(data + ' ')
def update_ohlc_data(current_interval, currency, mid):
    if current_interval not in ohlc_data:
        ohlc_data[current_interval] = defaultdict(lambda: {'open': mid, 'high': mid, 'low': mid, 'close': mid})
    elif currency not in ohlc_data[current_interval]:
        ohlc_data[current_interval][currency] = {'open': mid, 'high': mid, 'low': mid, 'close': mid}
    else:
        ohlc_data[current_interval][currency]['high'] = max(ohlc_data[current_interval][currency]['high'], mid)
        ohlc_data[current_interval][currency]['low'] = min(ohlc_data[current_interval][currency]['low'], mid)
        ohlc_data[current_interval][currency]['close'] = mid

Step 5: Connect to the WebSocket Stream

You’re now ready to initiate the WebSocket connection. Use your API key and specify the currency symbols you'd like to stream.

stream.set_ws_key("API_KEY")  # Replace with your actual API key
stream.set_symbols("USDJPY,EURGBP")
stream.stream_data(process_data)
stream.connect()

Step 6: Run Your Script

Finally, execute the script to start processing live data and generating OHLC output.

python websocket_ohlc.py

After running the program, a file named ohlc_output.txt will appear in your working directory. It will contain a growing log of OHLC data points based on your specified interval.

Conclusion

You’ve just built a working solution for streaming live Forex data and transforming it into OHLC bars using Python and WebSockets. This setup can serve as a foundation for real-time dashboards, trading bots, or analytical tools.

Please refer to:
The tutorial originally published on our website: Create Real-time OHLC Data with Python WebSocket

Also, watch the video tutorial: Real-time FX Ticks to OHLC Bars With Python.