hootnot / oanda-api-v20

OANDA REST-V20 API wrapper. Easy access to OANDA's REST v20 API with oandapyV20 package. Checkout the Jupyter notebooks!
MIT License
398 stars 107 forks source link

oanda-api-v20/oandapyV20/endpoints/pricing.py - STREAM example does not work. #168

Closed biomechman closed 3 years ago

biomechman commented 3 years ago

Would someone be able to provide a sample code with PriceStream() working on Python for the v20? (found the example)

Website (https://oanda-api-v20.readthedocs.io/en/latest/endpoints/pricing/pricingstream.html) and in this GitHub should probably be updated.

Cheers

import oandapyV20  
from oandapyV20 import API  
import oandapyV20.endpoints.pricing as pricing  
accountID = "..."  
api = API(access_token="...")  
params = {"instruments": "EUR_USD,EUR_JPY"}  
r = pricing.PricingStream(accountID=accountID, params=params)  
rv = api.request(r)  
maxrecs = 100  
for ticks in r:
    print(json.dumps(R, indent=4),",")
    if maxrecs == 0:
       r.terminate("maxrecs records received")
oeyvindds commented 3 years ago

Try this one:

import os import argparse import json from oandapyV20 import API from oandapyV20.endpoints.pricing import PricingStream

class Streaming: """Script for streaming of rates Example use: streaming.py --inst EUR_USD --inst EUR_JPY Can be one or more instruments Will keep going until stopped or error occurs """

# Get credentials from .env
access_token = os.getenv("TOKEN")
accountID = os.getenv("ACCOUNT_ID")

# Parser for tickers
parser = argparse.ArgumentParser(prog="streaming")
parser.add_argument("function", type=str, action="store", nargs=1)
parser.add_argument("-i", "--instruments", type=str, action="append")
args = parser.parse_args()

# Generate for the api-calls
api = API(
    access_token=access_token, environment=os.getenv("OandaEnv"), request_params={}
)

r = PricingStream(
    accountID=accountID, params={"instruments": ",".join(args.instruments)}
)

# Continious streaming of rates
while True:
    try:
        for R in api.request(r):
            R = json.dumps(R)
            print(R)

    except Exception as e:
        print("Error occured: {}\n".format(e))
        break

Should work flawless with Python 3.7