The first step to creating a trading strategy for USDJPY on Oanda using python is to import the necessary libraries.
These libraries include Numpy, Pandas, and Oanda’s API.
#Import necessary libraries
import oandapyV20
import oandapyV20.endpoints.instruments as instruments
import pandas as pd
import numpy as np
Next, you need to download the historical price data for the USDJPY pair from Oanda. This data can then be used to create the technical indicators to form the basis of the trading strategy.
# Set up your Oanda environment
oanda = oandapyV20.API(environment="practice",
access_token="YOUR_ACCESS_TOKEN")
accountID = "YOUR_ACCOUNT_ID"
Specifically, you will need to create a Relative Strength Index (RSI) and a Bollinger Band indicator. The RSI is typically used to measure the momentum of a currency pair. It is calculated by taking the average of the gains of the closing prices over the past 14 trading days, and dividing it by the average of the losses of the closing prices over the past 14 trading days. A value of 70 or higher usually indicates that the currency pair is overbought, while a value of 30 or lower usually indicates that the currency pair is oversold. The Bollinger Band indicator is calculated by taking the moving average of the closing prices over the past 20 trading days, and then adding and subtracting two standard deviations from the moving average. The upper band indicates the overbought region, while the lower band indicates the oversold region.
# Get USDJPY price data
params = {"count": 500,
"granularity": "M1"}
response = instruments.InstrumentsCandles(instrument="USD_JPY", params=params)
oanda.request(response)
Implement trading logic:
Enter a long position when RSI is below 30 and price is below the lower Bollinger Band.
Enter a short position when RSI is above 70 and price is above the upper Bollinger Band.
# Calculate RSI
df = response.response["candles"]
df = pd.DataFrame(df)
df['time'] = pd.to_datetime(df['time'])
df = df.set_index('time')
df['returns'] = np.log(df['closeAsk'] / df['closeAsk'].shift(1))
df['delta'] = df['returns'].diff()
# Calculate RSI
# RS = Average gain of up periods during the specified time frame /
# Average loss of down periods during the specified time frame
df['avg_gain'] = 0.00
df['avg_loss'] = 0.00
periods = 14
for i in range(periods, len(df)):
df.loc[df.index[i], 'avg_gain'] = ((df['delta'][i-periods+1:i+1][df['delta'] > 0].sum())/periods)
df.loc[df.index[i], 'avg_loss'] = ((abs(df['delta'][i-periods+1:i+1][df['delta'] < 0].sum()))/periods)
df['RS'] = df['avg_gain']/df['avg_loss']
df['RSI'] = 100 - (100/(1+df['RS']))
# Calculate Bollinger Bands
# Calculate rolling mean and standard deviation
df['sma'] = df['closeAsk'].rolling(window=20).mean()
df['std'] = df['closeAsk'].rolling(window=20).std()
# Calculate upper and lower bands
df['upper_band'] = df['sma'] + (df['std'] * 2)
df['lower_band'] = df['sma'] - (df['std'] * 2)
# Trading Strategy
# If RSI is less than 30 and price is below lower band, buy
# If RSI is greater than 70 and price is above upper band, sell
# Initialize empty buy and sell lists
buy_list = []
sell_list = []
for i in range(len(df)):
# If RSI is less than 30 and price is below lower band
if df['RSI'][i] < 30 and df['closeAsk'][i] < df['lower_band'][i]:
buy_list.append(df.index[i])
# If RSI is greater than 70 and price is above upper band
elif df['RSI'][i] > 70 and df['closeAsk'][i] > df['upper_band'][i]:
sell_list.append(df.index[i])
Show Buy/Sell signals.
# Print buy and sell signals
print("Buy signals: ", buy_list)
print("Sell signals: ", sell_list)
You can improve this strategy by adding your net position from buying and selling of the Forex pair. I.e. Exit a long position when RSI is above 70 and price is above the upper Bollinger Band and exit a short position when RSI is below 30 and price is below the lower Bollinger Band.
Alternatively, you can experiment with different values of RSI to achieve your desired result.
Disclaimer: This article is purely for reference and education. Do not use this as investment advice. Backtest the strategy with your desired financial instrument before executing with live account.