11_14_TheFXCMTradingPlatform(str_DateTimeIndex

Retrieving Data


FXCM provides access to historical market price data sets, such as tick data, in a pre-packaged
variant. This means that one can retrieve, for instance, compressed files from FXCM servers that
contain tick data for the EUR/USD exchange rate for week 26 of 2018, as described in the following
subsection. The retrieval of historical candles data from the API is explained in the subsequent
subsection.

Retrieving Tick Data
For a number of currency pairs, FXCM provides historical tick data. The fxcmpy package makes
retrieval of such tick data and working with it convenient. First, some imports:

import time
import numpy as np
import pandas as pd
import datetime as dt
from pylab import mpl, plt

plt.style.use('seaborn')
mpl.rcParams['font.family']='serif'
%matplotlib inline

from fxcmpy import fxcmpy_tick_data_reader as tdr

Second, a look at the available symbols (currency pairs) for which tick data is available:

print(tdr.get_available_symbols())

The following code retrieves one week’s worth of tick data for a single symbol. The resulting pandas DataFrame object has more than 1.5 million data rows:

#This retrieves the data file, unpacks it, and stores the raw data in a DataFrame object (as an
#attribute to the resulting object).

start = dt.datetime(2018,6, 25)
stop = dt.datetime(2018, 6, 30)

td = tdr('EURUSD', start, stop)

扫描二维码关注公众号,回复: 8894686 查看本文章

#The td.get_raw_data() method returns the DataFrame object with the raw data; i.e., with the
#index values still being
str objects.

td.get_raw_data().info()

td.get_raw_data().head()

#The td.get_data() method returns a DataFrame object for which the index has been
#transformed to a
DatetimeIndex.
td.get_data().info()

td.get_data().head()

Since the tick data is stored in a DataFrame object, it is straightforward to pick a subset of the data and to implement typical financial analytics tasks on it. Figure shows a plot of the mid prices derived for the subset and a simple moving average (SMA):

#Picks a subset of the complete data set.
sub = td.get_data(start='2018-06-29 12:00:00',
                  end = '2018-06-29 12:15:00')
sub.head()

#Calculates the mid prices from the bid and ask prices.
sub['Mid'] = sub.mean(axis=1)
sub.head()

#Derives SMA values over intervals of 1,000 ticks.
sub['SMA']  = sub['Mid'].rolling(1000).mean()
sub[996:1005]

sub[['Mid','SMA']].plot(figsize=(10,6), lw=0.75, title='Historical mid tick prices for EUR/USD and SMA')

Retrieving Candles Data

FXCM also provides access to historical candles data (beyond the API) — i.e., to data for certain homogeneous( 同种类的) time均质时间 intervals (“bars”) with open, high, low, and close values for both bid and ask prices.

First, a look at the available symbols for which candles data is provided:

from fxcmpy import fxcmpy_candles_data_reader as cdr

print(cdr.get_available_symbols())

#Second, the data retrieval itself. It is similar to the tick data retrieval. The only difference is that a period value — i.e., the bar length — needs to be specified (e.g., m1 for one minute, H1 for one hour,or D1 for one day):

start = dt.datetime(2018,5,1)
stop = dt.datetime(2018,6,30)
period = 'H1'

candles = cdr('EURUSD', start, stop, period)

data = candles.get_data()
data.head()

data.info()

#Open, high, low, close values for the bid prices.
data[data.columns[:4]].tail()

#Open, high, low, close values for the ask prices.
data[data.columns[4:]].tail()

#Calculates the mid close prices from the bid and ask close prices.
data['MidClose'] = data[['BidClose', 'AskClose']].mean(axis=1)
data.head()

#Calculates two SMAs(simple moving average), one for a shorter time interval, one for a longer one.
data['SMA1'] = data['MidClose'].rolling(30).mean()
data['SMA2'] = data['MidClose'].rolling(100).mean()

data[28:100]

data[['MidClose', 'SMA1', 'SMA2']].plot(figsize=(10,6), 
                                                                  title='Historical hourly mid close prices for EUR/USD and two SMAs'
                                                                 )

Working with the API

While the previous sections demonstrate retrieving prepackaged historical tick data and candles data from FXCM servers, this section shows how to retrieve historical data via the API. For this, a connection object to the FXCM API is needed. Therefore, first the import of the fxcmpy package, the connection to the API (based on the unique API token), and a look at the available instruments:

https://www.fxcm.com/uk/forex-trading-demo/

Login: D291084431

Password: 9398

Click "LAUNCH WEB PLATFORM"

Password: 9398

on the top right, click your account then click "Token Management"

Password: 9398

Next:

Click Copy button: 5f20afae941cd6bc981f3f850c991885b3dae125

Then create a fxcm.cfg file

###############################################

import fxcmpy
fxcmpy.__version__

                  #Connects to the demo server. #This connects to the API; adjust the path/filename.
api = fxcmpy.fxcmpy(config_file = 'fxcm.cfg')

instruments = api.get_instruments()
print(instruments)

Retrieving Historical Data

Once connected, data retrieval for specific time intervals is accomplished via a single method call. When using the get_candles() method, the parameter period can be one of m1, m5, m15, m30, H1, H2, H3, H4, H6, H8, D1, W1, or M1. The following code gives a few examples. Figure shows one minute bar ask close prices for the EUR/USD instrument (currency pair):

#Retrieves the 10 most recent end-of-day prices.
candles = api.get_candles('USD/JPY', period='D1', number=10)
candles[candles.columns[:4]]

candles[candles.columns[4:]]

#Retrieves end-of-day prices for a whole year.
start = dt.datetime(2017,1,1)
end = dt.datetime(2018,1,1)
candles = api.get_candles('EUR/GBP', period='D1',
                          start=start, stop=end)
candles.info()

candles.head()

#Retrieves the most recent one-minute bar prices available.
candles = api.get_candles('EUR/GBP', period='m1', number=250)
candles.head()

candles['askclose'].plot(figsize=(10,6), title='Historical ask close prices for EUR/USD (minute bars)')

Retrieving Streaming Data

While historical data is important to, for example, backtest algorithmic trading strategies, continuous access to real-time or streaming data (during trading hours) is required to deploy and automate algorithmic trading strategies. The FXCM API allows for the subscription to real-time data streams for all instruments. The fxcmpy wrapper package supports this functionality, among others, in that it allows users to provide user-defined functions (so-called callback functions) to process the realtime data stream.

The following code presents a simple callback function — it only prints out selected elements of the data set retrieved — and uses it to process data retrieved in real time after subscribing to the desired instrument (here, EUR/USD):

#The callback function that prints out certain elements of the retrieved data set.
def output(data, dataframe):
    print('%3d | %s | %s | %6.5f, %6.5' % (len(dataframe), 
                                           data['Symbol'], 
                                           pd.to_datetime(int(data['Updated']),
                                                          unit='ms'),
                                           data['Rates'][0], data['Rates'][1]
                                    )
         )

#The subscription to a specific real-time data stream; data is processed asynchronously as long as
#there is no “unsubscribe” event.
api.subscribe_market_data('EUR/USD', (output,))

#During the subscription, the .get_last_price() method returns the last available data set
api.get_last_price('EUR/USD')

#This unsubscribes from the real-time data stream.
api.unsubscribe_market_data('EUR/USD')

CALLBACK FUNCTIONS Callback functions are a flexible means to process real-time streaming data based on a Python function or even multiple such functions. They can be used for simple tasks, such as the printing of incoming data, or complex tasks, such as generating trading signals based on online trading algorithms

Placing Orders

The FXCM API allows the placement and management of all types of orders that are also available via the trading application of FXCM (such as entry orders or trailing stop loss orders). However, the following code illustrates basic market buy and sell orders only since they are in general sufficient to at least get started with algorithmic trading. It first verifies that there are no open positions, then opens different positions (via the create_market_buy_order() method):

#Shows the open positions for the connected (default) account.
api.get_open_positions()

#################################################

#################################################

#Opens a position of 100,000 in the EUR/USD currency pair
order = api.create_market_buy_order('EUR/USD', 10)

#Shows the open positions for selected elements only.

          #Ticket     Amount       Symbol      Gross P/L    S/B  
sel = ['tradeId', 'amountK', 'currency', 'grossPL', 'isBuy']

api.get_open_positions()[sel]                                    #isBuy==True: B

#Opens another position of 50,000 in the EUR/GBP currency pair.
order = api.create_market_buy_order('EUR/GBP',5)

api.get_open_positions()[sel]

While the create_market_buy_order() function opens or increases positions, the create_market_sell_order() function allows one to close or decrease positions. There are also more general methods that allow the closing out of positions, as the following code illustrates:

#This reduces the position in the EUR/USD currency pair.
order = api.create_market_sell_order('EUR/USD',3)

#This increases the position in the EUR/GBP currency pair.
order = api.create_market_buy_order('EUR/GBP',5)

#For EUR/GBP there are now two open long positions; contrary to the EUR/USD position, they are not netted净额结算。.
api.get_open_positions()[sel]

#The close_all_for_symbol() method closes all positions for the specified symbol.
api.close_all_for_symbol('EUR/GBP')

api.get_open_positions()[sel]

#The close_all() method closes all open positions.
api.close_all()

api.get_open_positions()

Account Information

Beyond, for example, open positions, the FXCM API allows retrieval of more general account information as well. For example, one can look up the default account (if there are multiple accounts) or get an overview of the equity and margin situation或概述股本和保证金情况:

#Shows the default accountId value.
api.get_default_account()

#Shows for all accounts the financial situation and some parameters.
api.get_accounts().T

发布了53 篇原创文章 · 获赞 38 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/Linli522362242/article/details/102816913
str
今日推荐