How To Do Algorithmic Trading With Oanda API?

In this post, we will discuss how to do algorithmic trading with Oanda API. Oanda is a well reputed broker that not only offers forex but also other instruments for trading. Quantitative methods are increasing being used in trading now a days. Instead of technical analysis more and more traders are now using quantitative methods in their trading. Did you take a look at my course Quantitative Trading Fundamentals? In this course I give you a general introduction on quantitative trading fundamentals. Now back to the topic of the day. Algorithmic trading has become very popular. There are thousands and thousands of quants that have been employed by Wall Street firms whose sole job is to develop winning algorithmic trading systems. Now you can well imagine their jobs depend on developing good systems. Can you compete with their algorithms with your manual trading methods? You should think about it.

Oanda API

This post is an introduction to algorithmic trading. There are many brokers who provide APIs to traders to develop their own algorithmic trading systems. Interactive Brokers, Oanda, Dukascopy etc these are some popular brokers. Most of the APIs can be programmed with Java, C++ and Python. You should start thinking about learning these programming languages. You can start with python as it is the easiest. We will focus on Python and R in this post. R is much easier to learn than Python. R is a powerful scripting language that has been developed solely for machine learning and statistical analysis. R has got more than 10K packages with it. So you can well imagine how much powerful it is. I will use both python and R in this post. Did you read the post on how to use Regression Splines in binary options trading?

How To Connect With Oanda API Using Python?

We start by using Python programming language. Python is a powerful scripting language. It has got many powerful machine learning and artificial intelligence modules that we can use to build algorithmic trading strategies. MQL4 and MQL5 languages lack this power and versatility of Python. So let’s start. First you need an account with Oanda. Oanda is a well known forex brokeras said above that allows you to use its REST API for algorithmic trading. You don’t need to open a live account, practice account is more than enough for us for building our algorithmic trading system. You can easily open the practice account with your email. Just make sure you download and install FXTrade Oanda platform. FXTrade platform has been developed in Java. So you will find have to install Java on your computer if it is not already installed. Once we have successfully tested the algorithmic trading system and are satisfied with the results, you can open a live account and use your system on the live account. Before you continue watch this recorded webinar on how to achieve 82% winrate with binary options. Below is the python code for connecting with Oanda Practice Account and download the bid/ask price.

#import Oanda REST API
import oandapy
#specify your Oanda account ID
account_id="xxxxxxxxxxxxxx"
#specify oanda API key
oanda_apiKey="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"

#fetch GBPUSD, EURUSD, AURUSD, USDJPY and NZDUSD rates


oanda = oandapy.API(environment="practice", access_token=oanda_apiKey)
response = oanda.get_prices(instruments="GBP_USD")
response
prices = response["prices"]
bid_price = float(prices[0]["bid"])
ask_price = float(prices[0]["ask"])
instrument = prices[0]["instrument"]
time = prices[0]["time"]

print ("[%s] %s bid=%s ask=%s" % (time, instrument, bid_price, ask_price))

Now below is the output! As you can see we have easily downloaded the bid/ask tick data with the time stamp. The first step in algorithmic trading is getting the data in time. Once we have the tick data we can then use the various machine learning algorithms to develop our automated trading system. Tick data is very important when it comes to trading binary options with durations like 1 minute. There are many traders who love to trade this short expiry binary options. In just 30 minutes you can make 30 trades. But you need a system that can win 80-90% of the time, otherwise we will be losing money heavily. The purpose of this blog is to develop such binary options strategies that we can use to trade 1 minute binary options. If you have never traded binary options, you can read this post on how to trade forex binary options? Below is the python code we we print the tick data that we have read. You can easily calculate the spread from this tick data. It is around 2 pips. Knowing the spread is very important. We can use this spread in our algorithmic trading strategy. Watch this video tutorial on how to trade 1 minute binary options.

>>> response
{'prices': [{'ask': 1.24682,
   'bid': 1.24665,
   'instrument': 'GBP_USD',
   'time': '2017-03-21T14:22:33.849858Z'}]}
>>> prices = response["prices"]
>>> bidding_price = float(prices[0]["bid"])
>>> asking_price = float(prices[0]["ask"])
>>> instrument = prices[0]["instrument"]
>>> time = prices[0]["time"]
>>> print ("[%s] %s bid=%s ask=%s" % (time, instrument, bidding_price, asking_price))
[2017-03-21T14:22:33.849858Z] GBP_USD bid=1.24665 ask=1.24682

As you can see we can easily download bid/ask price. We can use this bid/ask data to calculate the spread as said above. Tick data is not evenly spaced. This is very important for you to understand, We can use a Probit Model using this tick data and make predictions. More on that in future posts. Below is a slightly different python code that is more clear than the above code. we use the get method for ask and bid. It is very interesting for you to know how the binary options brokers make money. Forex brokers make money with this spread that they charge for each trade that we open and close. Binary options brokers don’t have the spread with them. Read this post that explains how binary options brokers make money.

#we can also do it like this
prices = response.get("prices")
ask_price = prices[0].get("ask")
bid_price=prices[0].get("bid")
ask_price
bid_price

Below you can see we have printed the ask price and the bid price more clearly. High frequency trading (HFT) entails building predictive models using this tick data. There are many HFT firms that use this tick data to trade. Time is of essence when it comes to HFT trading. Even a delay of a millisecond can be costly. HFT firm that has the fastest servers in the end wins all the trades. Due to this reason most of these HFT firms try to locate their servers close to the exchange servers for which they are ready to pay heavy prices. Learn this Rainbow Binary Options Strategy.

>>> ask_price
1.24682
>>> bid_price
1.24665
>>> 

This was something easy to do. We downloaded the tick data. As said above we can use this tick data to build predictive models.

How To Open A Pending Limit Order?

Now we will try to place a pending limit sell order. The problem that I am facing is that Oanda FXTrade platform disconnects from internet frequently. If this happens too much then we must forget algorithmic trading with Oanda as the platform will disconnect frequently and we won’t be able to execute our algorithmic trading strategy. I think this problem is due to the poor connectivity on my side. I will check and remove it. When it comes to algorithmic trading, you a really fast internet connection as we are dealing with times that are in milliseconds. Watch this video that explains a 30 minute binary options strategy with more than 90% average winrate. Below is the python code for placing a buy limit order.

""" Send  A Limit Order"""
from datetime import datetime, timedelta
# we want the trade to expire after one day
trade_expiry = datetime.now() + timedelta(days=1)
trade_expiry = trade_expiry.isoformat("T") + "Z"

response = oanda.create_order(account_id,
                             instrument="GBP_USD",
                             units=1000,
                             side='buy', 
                             type='limit',
                             price=1.279,
                             expiry=trade_expiry)

response

Below is the code for streaming the data! First we build a class DataStreaming that we can use to build a stream object.

#stream the data from Oanda
class DataStreaming(oandapy.Streamer):
    def __init__(self, count=10, *args, **kwargs):
        super(DataStreaming, self).__init__(*args, **kwargs)
        self.count = count
        self.reccnt = 0

    def on_success(self, data):
        print(data, "\n")
        self.reccnt += 1
        if self.reccnt == self.count:
            self.disconnect()

    def on_error(self, data):
        self.disconnect()
        

account="12345"
stream = DataStreaming(environment="practice", access_token=oanda_apiKey)
stream.rates(account, instruments="EUR_USD,EUR_JPY,US30_USD,DE30_EUR")
print(stream.rates)

#The same procedure can be used for streaming events.

stream = DataStreaming(environment="practice", access_token=oanda_apiKey)
stream
stream.events(ignore_heartbeat=False)

How To Connect R With Oanda API?

As said above, R is a powerful scripting language with the sole purpose of doing data science and statistical analysis. We can also use R to connect with Oanda API. You should consult the Oanda developers site which contains the necessary documentation. So we can also connect R with Oanda API. Below is the sample code!

> #check required packages installed
> Pkg <- c("base","downloader","forecast","httr","jsonlite","lubridate","moments",
+ "PerformanceAnalytics","quantmod","reshape2","RCurl","stats","scales",
+ "tseries","TTR","TSA","xts","zoo")
> inst <- Pkg %in% installed.packages()
> if(length(Pkg[!inst]) > 0) install.packages(Pkg[!inst])
> instpackages <- lapply(Pkg, library, character.only=TRUE)
> #specify the account details 101-004-5348765-001
> AccountType <- "practice"
> AccountID   <- 1234567
> Token       <- "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
> TimeAlign   <- "Asia%2Karachi"
> Granularity <- "H6"
> Start <- "2016-01-01"
> End   <- "2017-03-01"
> #load the ROanda API
> downloader::source_url("http://bit.ly/GitHubROandaAPI",prompt=FALSE,quiet=TRUE)
trying URL 'http://bit.ly/GitHubROandaAPI'
Content type 'text/plain; charset=utf-8' length 35187 bytes (34 KB)
downloaded 34 KB

Now this is just an introduction. In the future posts we will use R or Python to connect with Oanda API and then build predictive models that we can use. You can read this post in which I use R to forward test a binary options trading strategy.