Trend Following High Frequency Algorithmic Trading System

In this post we are going to design and develop a trend following high frequency algorithmic trading system. Did you read the previous post on GBPUSD opening with a huge gap on Monday? Currency markets are dynamic highly non linear systems. News plays a major role in the currency market especially if there is a negative news over the weekend it will get reflected on Monday. Do you remember the British Pound Flash Crash? A rogue algorithm is being blamed for this flash crash. You should watch this documentary on algorithmic and quantitative trading. Today more than 80% of the trades that are being placed on Wall Street are by algorithms

High Frequency Trading also known as HFT means trading on a timeframe shorter than the daily timeframe. HFT trading is very popular with many firms at Wall Street. HFT trading strategies mostly depend on speed. In this post we will also try to build a simple trend followign HFT algorithmic trading system. This is a simple trend following system. It first connects with Oanda API using python and downloads the tick data after every 15 seconds. We will use a 5 period moving average and a 20 period moving average to average the tick data. Did you download the Camarilla Pivot Point Indicator? Camarilla pivot points indicator gives you the support and resistance levels where price can take a turn. This is a good indicator for day trading.Don’t know what are these Camarilla Pivot Points? Watch this video tutorial on what are Camarilla Pivot Points.

In this post we are not going to use Camarilla pivot points . We will be using simple moving averages 5 and 20 as said above. 5 period moving average means we will find the rolling mean based on the last 75 seconds . 20 period moving average means we will find the rolling mean based on the last 300 seconds. If the 5 period moving average is above the 20 period moving average we have an uptrend. When this happens we will enter into a buy trade. In the same manner when the 5 period moving average is below the 20 period moving average we will enter into a short trade. In nutshell this is a simple trend following strategy. Candlestick patterns are important trend continuation and trend reversal signals. Did you read the post on a EURGBP double inside day trade that make $10K? In subsequent posts we will build more complicated algorithmic trading strategies using machine learning algorithms.

Oanda FXTrade Platform

Did you read the post on how to make 600 pips with a 10 pip stop loss? In this post I show you how reading the charts correctly on weekly and daily charts can give you very good trades using the concept of support and resistance. We will try to build an algorithmic trading system based on this manual trading strategy. In this post I will be taking help from a few books on Python. You should have Anaconda installed on your computer. I will be using Rodeo as IDE. You should have a good concept of Python object oriented programming if you want to understand the code below. Object oriented programming also known as OOP allows you to write code only once and then reuse it again and again. This is what we want to do. First build a simple algorithmic trading system. Then use the classes defined in that algorithmic trading system to build more sophisticated algorithmic trading system.

You should a practice account with Oanda. You don’t need to open a live account. Opening a practice account with Oanda is easy. You can register with your email. That’s all. You should download the FXTrade practice account and install it on your computer. Oanda FXTrade platform requires Java to be installed on your computer. If you don’t have Java installed do that before you install FXTrade platform. Once you have the practice account opened, you should generate your account Oanda API key. Save Oanda API key in a text file as you will be using it to connect with Oanda FXTrade platform for algorithmic trading. Read this post on FXCM brokerage reporting $225 million loss on Swiss National Bank surprise decision to unpeg Swiss Franc CHF from the Euro.

""" Trend Following Algorithmic 
    High Frequency Trading System

"""


#import libraries
import oandapy
from datetime import datetime
import pandas as pd

#specift the account ID and Oanda API Key
account_ID="XXXXXXXXXXXXXXXXXXX"
#specify oanda API key
oanda_apiKey="XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"


#define the HFT System Class

class HFTSystem(oandapy.Streamer):
    def __init__(self, *args, **kwargs):
        oandapy.Streamer.__init__(self, *args, **kwargs)
        self.oanda = oandapy.API(kwargs["environment"], kwargs["access_token"])

        self.instrument = None
        self.account_id = None
        self.qty = 0
        self.resample_interval = '15s'
        self.mean_period_short = 5
        self.mean_period_long = 20
        self.buy_threshold = 1.0
        self.sell_threshold = 1.0
        self.prices = pd.DataFrame()
        self.beta = 0
        self.is_position_opened = False
        self.opening_price = 0
        self.executed_price = 0
        self.unrealized_pnl = 0
        self.realized_pnl = 0
        self.position = 0
        self.dt_format = "%Y-%m-%dT%H:%M:%S.%fZ"

#Define HFT System class method
def begin(self, **parameters):
    self.instrument = parameters["instruments"]
    self.account_id = parameters["accountId"]
    self.qty = parameters["qty"]
    self.resample_interval = parameters["resample_interval"]
    self.mean_period_short = parameters["mean_period_short"]
    self.mean_period_long = parameters["mean_period_long"]
    self.buy_threshold = parameters["buy_threshold"]
    self.sell_threshold = parameters["sell_threshold"]
    self.start(**parameters) # Start streaming prices


#handling the events
def on_success(self, data):
    time, symbol, bid, ask = self.parse_tick_data(data["tick"])
    self.tick_event(time, symbol, bid, ask)
    
#tracking the position
def print_status(self):
    print ("[%s] %s pos=%s beta=%s RPnL=%s UPnL=%s" % (
    datetime.now().time()),
    self.instrument,
    self.position,
    round(self.beta, 5),
    self.realized_pnl,
    self.unrealized_pnl)

#implementing the trend following system
def tick_event(self, time, symbol, bid, ask):
    midprice = (ask+bid)/2.
    self.prices.loc[time, symbol] = midprice
    resampled_prices = self.prices.resample(self.resample_interval,how='last',
        fill_method="ffill")
    mean_short = resampled_prices.tail(self.mean_period_short).mean()[0]
    mean_long = resampled_prices.tail(self.mean_period_long).mean()[0]
    self.beta = mean_short / mean_long
    self.perform_trade_logic(self.beta)
    self.calculate_unrealized_pnl(bid, ask)
    self.print_status

#Generate Buy/Sell signals
def perform_trade_logic(self, beta):
    if beta > self.buy_threshold:
        if not self.is_position_opened \
                or self.position < 0:
            self.check_and_send_order(True)
    elif beta < self.sell_threshold: if not self.is_position_opened \ or self.position > 0:
            self.check_and_send_order(False)


#start trading
if __name__ == "__main__":
    key = oanda_apiKey
    account_id = account_ID
    algoSystem = HFTSystem(environment="practice", access_token=key)
    algoSystem.begin(accountId=account_id,
                instruments="EUR_USD",
                qty=1000,
                resample_interval="15s",
                mean_period_short=5,
                mean_period_long=20,
                buy_threshold=1.,
                sell_threshold=1.)

Above is the code for this High Frequency Trading Trend Following Algorithmic Trading Strategy.In the future posts we will try to improve upon this basic trend following strategy. Right now this is a very simple trend following strategy. We can try different machine learning algorithms to improve upon this strategy. In the above code first we define the HFTSystem class. Then we define a few methods like on event success, tracking the trading position, tick event, check for buy/sell trade condition and finally we have the begin trading method. With this begin method, the system will continue monitoring the market and when the conditions for a buy/sell trade is met, it will open a buy/sell trade accordingly. Did you read the post on how to use kernel ridge regression in price prediction? In this post I used kernel ridge regression to predict gold prices. Kernel ridge regression is better than linear regression.

Algorithmic trading is the future of trading. If you are a manual trader, you should start learning algorithmic trading. Before you learn algorithmic trading, you should become familiar with the concepts of quantitative trading. You can start with my basic course Time Series Analysis for Traders. In this course, I take you from the very start and take you step by step how to use time series analysis in your trading. Financial time series are very different from the other time series. Financial time series is highly unpredictable. Modelling financial time series with linear models like Autoregressive and Autoregressive Integrated Moving Average don’t give good predictions when we try to use them on financial time series like the stock market and the currency market.

After this course on time series analysis for traders, you can also take this course Python Machine Learning for Traders. In this course I take you a step above time series analysis and show you how to use machine learning in your trading using logistic regression, support vector machines and neural networks. It is essential that you firsr msOnce you have mastered machine learning, you are ready to take the next step and start building your own algorithmic trading systems with this Algorithmic Trading with Python course. Learning algorithmic trading can open the doors for you in other areas as well like game development and android app development. So don’t hesitate. Take the plunge and start learning algorithmic trading.

Published
Categorized as Forex Tagged