4. Streaming Data

This section is about real-time or streaming data.

In [1]:
import fxcmpy
import pandas as pd
import datetime as dt
con = fxcmpy.fxcmpy(config_file='fxcm.cfg')

4.1. Basic Approach

Streaming the current market data is straightfoward, one just need to subscribe to the instrument of interest.

In [2]:
con.subscribe_market_data('EUR/USD')

A list with the subscribed instruments is returned by the con.get_subscribed_symbols() method.

In [3]:
con.get_subscribed_symbols()
Out[3]:
['EUR/USD']

One can also check the subscription for a specified instruments.

In [4]:
con.is_subscribed('EUR/USD')
Out[4]:
True

After the subscription, fxcm.py collects the data in a pandas DataFrame. The con.get_prices() method returns that DataFrame object.

In [5]:
con.get_prices('EUR/USD')
Out[5]:
Bid Ask High Low
2018-01-09 13:43:58.637 1.19199 1.19222 1.19769 1.19144
2018-01-09 13:43:59.144 1.19198 1.19222 1.19769 1.19144
2018-01-09 13:44:00.080 1.19200 1.19223 1.19769 1.19144
2018-01-09 13:44:04.466 1.19200 1.19224 1.19769 1.19144
2018-01-09 13:44:05.965 1.19200 1.19222 1.19769 1.19144

You can also fetch only the last available quotes via con.get_last_price().

In [6]:
con.get_last_price('EUR/USD')
Out[6]:
Bid     1.19200
Ask     1.19223
High    1.19769
Low     1.19144
Name: 2018-01-09 13:44:09.837000, dtype: float64

To stop the stream and delete (!) the dataframe, use con.unsubscribe_market_data().

In [7]:
con.unsubscribe_market_data('EUR/USD')
In [8]:
con.get_prices('EUR/USD')
Out[8]:
Bid Ask High Low

4.2. Callback Functions

One can add a list object with callback functions to the subscription, as in the example below.

The function print_data() simply prints selected quotes as soon as they are retrieved.

In [9]:
def print_data(data, dataframe):
    print('%3d | %s | %s, %s, %s, %s, %s'
          % (len(dataframe), data['Symbol'],
             pd.to_datetime(int(data['Updated']), unit='ms'),
             data['Rates'][0], data['Rates'][1], data['Rates'][2],
             data['Rates'][3]))
In [10]:
con.subscribe_market_data('EUR/USD', (print_data,))
  1 | new values received for EUR/USD | 2018-01-09 13:44:22.201000, 1.1921, 1.19234, 1.19769, 1.19144
  2 | new values received for EUR/USD | 2018-01-09 13:44:22.745000, 1.19214, 1.19237, 1.19769, 1.19144
  3 | new values received for EUR/USD | 2018-01-09 13:44:23.195000, 1.19214, 1.19237, 1.19769, 1.19144
  4 | new values received for EUR/USD | 2018-01-09 13:44:23.753000, 1.19214, 1.19237, 1.19769, 1.19144
In [11]:
con.unsubscribe_market_data('EUR/USD')