Converting Real-Time Forex Data to OHLC Bars Using PHP
Shridhar G Vatharkar

Shridhar G Vatharkar @shridhargv

About: I am passionate about the latest technology used in the financial services landscape. I like to contribute to help fellow developers excel and explore.

Joined:
Oct 14, 2022

Converting Real-Time Forex Data to OHLC Bars Using PHP

Publish Date: Mar 25
0 0

Ever wanted to handle real-time data using WebSockets? WebSockets allow seamless live data streaming, making them perfect for applications like Forex trading.

This guide'll capture real-time Forex data using a WebSocket connection and transform it into minute-by-minute Open, High, Low, and Close (OHLC) bars. These bars provide valuable insights for traders and analysts tracking short-term market trends.

Even if you're new to PHP, don’t worry! We'll take it step by step.
Please take a look at WebSockets Documentation for details on usage and integration.

Let’s dive in.

Setting Up Your Environment

Before we get into the coding, let’s ensure our setup is ready.
Check PHP Installation: Open a terminal and run:

php -version
Enter fullscreen mode Exit fullscreen mode

If PHP isn’t installed, download and install it from the official PHP website.

  • Get a WebSocket API Key: Sign up for a free 14-day WebSocket trial via your TraderMade dashboard.

  • Install Composer (PHP Dependency Manager): Navigate to your project folder and install the WebSocket library:

composer require textalk/websocket
Enter fullscreen mode Exit fullscreen mode

Creating the WebSocket Client in PHP

Step 1: Include Dependencies

First, include Composer's autoload file to manage dependencies efficiently:

require_once("vendor/autoload.php");
Enter fullscreen mode Exit fullscreen mode

Step 2: Establish WebSocket Connection

We need to connect to the WebSocket server. This function handles the connection:

function connectWebSocket() {
    try {
        $client = new WebSocketClient("wss://marketdata.tradermade.com/feedadv");

        $message = $client->receive();
        echo $message;

        $client->text("{\"userKey\":\"api_key\", \"symbol\":\"GBPUSD,EURUSD\"}");

        return $client;
    } catch (WebSocketTimeoutException $e) {
        echo "WebSocket timeout. Reconnecting...\n";
        sleep(5);
        return connectWebSocket();
    }
}
Enter fullscreen mode Exit fullscreen mode

This function:

  • Connects to the WebSocket server.
  • Requests real-time data for specific currency pairs.
  • Implements auto-reconnection in case of timeouts.

Step 3: Receive and Process WebSocket Data

Once connected, we listen for price updates and store them:

$client = connectWebSocket();
$dataArray = [];

while (true) {
    try {
        $message = $client->receive();

        if ($message !== "connected") {
            $decoded_json = json_decode($message, true);

            $bid = $decoded_json['bid'] ?? null;
            $ask = $decoded_json['ask'] ?? null;

            if ($bid !== null && $ask !== null) {
                $mid = ($bid + $ask) / 2;

                echo "{$decoded_json['symbol']} {$decoded_json['ts']} $bid $ask $mid\n";

                $dataArray[] = [
                    'symbol' => $decoded_json['symbol'],
                    'ts' => $decoded_json['ts'],
                    'bid' => $bid,
                    'ask' => $ask,
                    'mid' => $mid
                ];

                file_put_contents('websocket_data.json', json_encode($dataArray, JSON_PRETTY_PRINT));
            }
        }
    } catch (WebSocketTimeoutException $e) {
        echo "Timeout. Reconnecting...\n";
        sleep(5);
        $client = connectWebSocket();
    } catch (Exception $e) {
        echo "Error: " . $e->getMessage();
    }
}
Enter fullscreen mode Exit fullscreen mode

This script:

  • Reads live Forex data.
  • Extracts bid and ask prices.
  • Saves data into websocket_data.json.
  • Handles errors and automatically reconnects if necessary.

Step 4: Load Data from JSON File

Before processing, we ensure our file has valid data:

$jsonFilePath = 'websocket_data.json';
$jsonData = file_get_contents($jsonFilePath);
$forexData = json_decode($jsonData, true);

if (empty($forexData)) {
    echo json_encode(["error" => "No data found in $jsonFilePath"]);
    exit;
}
Enter fullscreen mode Exit fullscreen mode

Step 5: Convert Raw Data to OHLC Bars

Now, let’s transform the tick data into minute-based OHLC bars:

$interval = 60;
$ohlcData = [];

foreach ($forexData as $data) {
    $timestamp = strtotime($data['ts']);
    $roundedTimestamp = floor(($timestamp + (5 * 3600) + (30 * 60)) / $interval) * $interval;

    if (!isset($ohlcData[$roundedTimestamp])) {
        $ohlcData[$roundedTimestamp] = [
            'timestamp' => $roundedTimestamp + (5 * 3600) + (30 * 60),
            'low' => $data['bid'],
            'high' => $data['bid'],
            'open' => $data['bid'],
            'close' => $data['bid']
        ];
    } else {
        $ohlcData[$roundedTimestamp]['low'] = min($ohlcData[$roundedTimestamp]['low'], $data['bid']);
        $ohlcData[$roundedTimestamp]['high'] = max($ohlcData[$roundedTimestamp]['high'], $data['bid']);
        $ohlcData[$roundedTimestamp]['close'] = $data['bid'];
    }
}
Enter fullscreen mode Exit fullscreen mode

This:

  • Rounds timestamps to the nearest minute.
  • Generates OHLC bars for each minute.

Step 6: Save OHLC Data to JSON

Finally, we store the OHLC bars:

$jsonFilePathOutput = 'ohlc_data.json';

if (!file_put_contents($jsonFilePathOutput, json_encode(array_values($ohlcData), JSON_PRETTY_PRINT))) {
    echo json_encode(["error" => "Failed to write OHLC data"]);
    exit;
}

echo json_encode(["success" => "OHLC data saved to $jsonFilePathOutput"]);
Enter fullscreen mode Exit fullscreen mode

Running the Script

To execute, run:

php webSocket_client.php
Enter fullscreen mode Exit fullscreen mode

Your script will now fetch live Forex data and convert it into OHLC bars. 🚀

Sample Outputs

Raw Forex Data:

[
    {"symbol": "GBPUSD", "ts": "1712130980714", "bid": 1.25664, "ask": 1.25668},
    {"symbol": "EURUSD", "ts": "1712130982178", "bid": 1.07712, "ask": 1.07712}
]
Enter fullscreen mode Exit fullscreen mode

OHLC Data Output:

[
    {"timestamp": "1970-01-01 05:30:00", "open": 1.25664, "high": 1.25665, "low": 1.25664, "close": 1.25665}
]
Enter fullscreen mode Exit fullscreen mode

Conclusion
Congratulations! You’ve successfully streamed real-time Forex data and transformed it into OHLC bars. Try tweaking the script and adding new features. Happy coding! 🎉

Comments 0 total

    Add comment