How to use oandapyV20 API: MAKE IT SIMPLE
I find quite a few sample codes are scattered aound on Internet to retrieve prices via oandapyV20 API.
Here below I compile them neatly for the followings:
First of all, download the package:
$ pip install oandapyV20
Import some packages next:
import json
import oandapyV20
from oandapyV20 import API
from oandapyV20.exceptions import V20Error
import configparser
import oandapyV20.endpoints.pricing as pricing
Create config_v20.txt file in the YAML syntax under ./Config. It includes your account_id and api_key, both of which are given after sign-up with OANDA:
[oanda]
account_id = 981-223-99988798-111
api_key = fods348u3091feoiwhfrh2irhfpe-jf382u32hrrehfkhewffkf
#Better NOT to embed API Key in the code, rather read that off a text file (config_v20.txt)
config = configparser.ConfigParser()
config.read('./Config/config_v20.txt')
account_id = config['oanda']['account_id']
api_key = config['oanda']['api_key']
print(account_id + "\n" + api_key)
api = oandapyV20.API(access_token=api_key)
params ={
"instruments": "EUR_USD,EUR_JPY"
}
r = pricing.PricingInfo(accountID=account_id, params=params)
rv = api.request(r)
print(r.response)
instruments = "USD_JPY"
s = pricing.PricingStream(accountID=account_id, params={"instruments":instruments})
try:
n = 0
maxrecs = 5
for R in api.request(s):
print(json.dumps(R, indent=2))
n += 1
if n > maxrecs:
#s.terminate("maxrecs received: {}".format(MAXREC))
s.terminate("maxrecs received")
except V20Error as e:
print("Error: {}".format(e))
import oandapyV20.endpoints.instruments as instruments
#must be in the ISO8601 format
from_date = "2018-11-20T00:00:00.000000Z"
to_date = "2018-11-30T00:00:00.000000Z"
params ={
"granularity": "D",
"from": from_date,
"to": to_date
}
r = instruments.InstrumentsCandles(instrument="USD_JPY",
params=params)
api.request(r)
print(r.response)
#Handy to use list comprehension
#If we don't cast to float from string, pyplot automatically sort y-value!
y_value_list = [float(dict["candles"][i]["mid"]['c']) for i in range(len(dict["candles"]))]
x_value_list = [dict["candles"][i]["time"][0:10] for i in range(len(dict["candles"]))]
import matplotlib.pyplot as plt
plt.title(dict["instrument"] + " in interval of " + dict["granularity"])
plt.plot(x_value_list, y_value_list)
plt.xticks(rotation='vertical')
plt.show