Developing an Automated Trading System with Python

DISCLAIMER! Forex trading carries a heavy amount of risk. Any and everything outlined in this code is for educational purposes only. I am not responsible for any of your losses or any hardships you may face as a result of using this code. Again, this is meant to be used ONLY for educational purposes.

This code is licensed under the GNU Public License. Read More.

The idea for writing this post came from the overwhelming amount of people on r/Forex who were interested in automating their Forex trading strategies. I hope to keep this post short, simple, and informative so please bear with me.

If you do not have at least an intermediate understanding of Python I suggest you read up on it. There are numerous resources that will get you started, I recommend

Be sure to setup a demo account with Oanda and generate an api key

Okay let’s get to it!

First things first, I recommend using an IDE that allows you to run your python code or use Linux/OSX so you can test with terminal. Personally, I use the Spyder IDE that comes in the Anaconda package. You can download that here.

You will need to install two main python libraries: oandapyV20 & requests.

This will be our final file structure:


The first file we will focus on is

# Let's create a new class called userVals.class userVals():# In this class we will create our universal variables that we will # need for our strategy and for using the Oanda API.
____________________________________________________________________# Next let's place some variables in the userVals class.
class userVals():
SMAbig = 50
SMAsmall = 25
count = 55
key ="..."
accountID = "..."
params = {
"count": count,
"granularity": "H4"

In this file we created our variables to be used within the rest of this strategy. I am going to be using a 2 simple moving average cross over strategy, so for my SMAbig I used 50 periods of data, and my SMAsmall I used 25 periods of data. the count variable is the amount of data that you return from the Oanda API. The larger the number, the slower the system will run. Place your api key in the “key” variable. Place your account ID in the “accountID” variable. You can also define the type of candle data you want to use. I am using the 4 hour chart, so under params, I placed “H4”. A list of data you can get from Oanda can be found here.

Alright now we are onto our next file,

# file # # Let's import the packages we will needimport requests as r
from __init__ import userVals
from oandapyV20 import API
import oandapyV20.endpoints.instruments as instruments
# Next, we create a class called user1, this will hold the variables # for our API callsclass user1():
client = API(access_token=userVals.key)
o = instruments.InstrumentsCandles(instrument=userVals.pair,
class candleLogic:
def OHLC(self, data):
# Call imported user1 class
candles = user1.o.response.get("candles")
candleData = candles[data].get("mid")
# OHLC variables to return in array
o = candleData.get("o")
h = candleData.get("h")
l = candleData.get("l")
c = candleData.get("c")
return float(o), float(h), float(l), float(c)
# Define clean function routes for returning proper data
def Open(self, data):
return self.OHLC(data)[0]
# Next we create functions to call our OHLC data based on the candle # we want to return.def High(self, data):
return self.OHLC(data)[1]
def Low(self, data):
return self.OHLC(data)[2]
def Close(self, data):
return self.OHLC(data)[3]
# Finally, this getData function will return the data we want in a -# clean array so we can manipulate it with our strategy. If you want # to return a list of the High or Low data simply create another -- # function and change self.Close(x) to self.High(x) etc.def getData(self):
numList = []
for x in range(0, userVals.count):
return numList

Now on to our next file,

# In this file we will place all of our strategy logic such as ---- # indicators. This strategy is relatively simple so theirs not a --- # whole lot to place here.# create a class called strategyLogic
class strategyLogic():
# create a function for our Simple Moving Average.
def SMA(self, prices, length, period):
return sum(prices[(length-period):length]) / period
# for the previous candle's Simple Moving Average.
def SMAprev(self, prices, length, period):
return sum(prices[(length-period-1):length-1]) / period

Now our final file,

# First let's import the packages we need
from strategy import strategyLogic
from candles import candleLogic
from __init__ import userVals
# Oanda Packages
from oandapyV20 import API
import oandapyV20
from oandapyV20.contrib.requests import MarketOrderRequest
from oandapyV20.contrib.requests import TakeProfitDetails
from oandapyV20.contrib.requests import StopLossDetails
import oandapyV20.endpoints.orders as orders
import oandapyV20.endpoints.accounts as accounts

I recommend Looking at the rest of the code on Github here since Medium’s formatting is pretty terrible. The final file is where we declare our conditionals and decide whether or not the bot should trade.

Full Github Repo: Here

Going forward, there is a lot you can do once you have your initial candle data. Everything from that point is just a matter of performing simple math equations to decide whether or not your bot should trade. Some things that could be easily implemented is Fibonacci retracements, RSI, Heiken Ashi. The possibilities are endless.

Coding, trading, creating