def stream(count, instruments, nice, timeout=None): accountID, access_token = exampleAuth() request_params = {} if timeout: request_params = {"timeout": timeout} # fetch MAXREC stream records MAXREC = count api = API(access_token=access_token, environment="practice", request_params=request_params) # setup the stream request r = PricingStream(accountID=accountID, params={"instruments": ",".join(instruments)}) n = 0 R_list = list() while True: try: for R in api.request(r): if nice: R = json.dumps(R, indent=2) print('Collecting Data.. Please wait..') R_list.append(R) n += 1 if MAXREC and n >= MAXREC: r.terminate("maxrecs received: {}".format(MAXREC)) except V20Error as e: # catch API related errors that may occur with open("LOG", "a") as LOG: LOG.write("V20Error: {}\n".format(e)) break except ConnectionError as e: with open("LOG", "a") as LOG: LOG.write("Error: {}\n".format(e)) except StreamTerminated as e: with open("LOG", "a") as LOG: LOG.write("Stopping: {}\n".format(e)) break except Exception as e: with open("LOG", "a") as LOG: LOG.write("??? : {}\n".format(e)) break return R_list
def main(clargs): accountID, access_token = exampleAuth() request_params = {} if clargs['--timeout']: request_params = {"timeout": clargs['--timeout']} # fetch MAXREC stream records MAXREC = int(clargs['--count']) api = API(access_token=access_token, environment="practice", request_params=request_params) # setup the stream request r = PricingStream(accountID=accountID, params={"instruments": ",".join(clargs['<instrument>'])}) n = 0 _m = {"PRICE": PriceRecord, "HEARTBEAT": HeartBeat} while True: try: for rv in api.request(r): # create a Pydantic record based on the type rec = _m[rv['type']](**rv) n += 1 if MAXREC and n >= MAXREC: r.terminate("maxrecs received: {}".format(MAXREC)) print(rec.json() if clargs['--nice'] else rec) except V20Error as e: # catch API related errors that may occur logger.error("V20Error: %s", e) break except ConnectionError as e: logger.error("%s", e) except StreamTerminated as e: logger.error("Stopping: %s", e) break except Exception as e: logger.error("%s", e) break
def print_stream_pricing(order_instrument): """ Stream price data for given instrument. Note: Gives a "HEARTBEAT" to maintain an active HTTP connection, i.e if no new pricing info is available. """ maxrec = 100 # not exactly sure what this value means s = PricingStream(accountID=accountID, params={"instruments": order_instrument}) try: n = 0 for R in api.request(s): print(json.dumps(R, indent=2)) n += 1 if n > maxrec: s.terminate("maxrecs received: {}".format(maxrec)) except V20Error as e: print("Error: {}".format(e))
def _run(self): tickMsg = "write tick record ...{}\n" while True: r = PricingStream( accountID=accountID, params={"instruments": ",".join(self.instruments)}) se = None # to save the exception if it occurs with open("prices.txt", "a") as O: n = 0 try: for R in api.request(r): now = datetime.now() sys.stderr.write(tickMsg.format(now)) if self.nice: O.write(json.dumps(R, indent=2) + "\n") else: O.write(json.dumps(R) + "\n") O.flush() gevent.sleep(0) n += 1 if self.maxrec and n >= self.maxrec: r.terminate("maxrecs received: {}".format(n)) except V20Error as e: # catch API related errors that may occur se = e # save for reraise logger.error("V20Error: %s %d", e, n) break except ConnectionError as e: logger.error("ConnectionError: %s %d", e, n) time.sleep(3) except StreamTerminated as e: se = e # save for reraise logger.error("StreamTerminated: %s %d", e, n) break except Exception as e: se = e # save for reraise logger.error("Some exception: %s %d", e, n) break
def fetch(): access_token = Config.get('oanda')['api_key'] account_id = Config.get('oanda')['account_id'] api = API(access_token=access_token, environment="practice") instruments = "DE30_EUR,EUR_USD,EUR_JPY" s = PricingStream(accountID=account_id, params={"instruments": instruments}) try: n = 0 for R in api.request(s): print(json.dumps(R, indent=2)) n += 1 if n > 10: s.terminate("maxrecs received: {}".format(MAXREC)) except V20Error as e: print("Error: {}".format(e))
def run(self): c = 0 r = PricingStream(accountID=account.mt4, params={"instruments": ",".join(self.instruments)}) try: for ticks in api.request(r): self.callback(ticks) c += 1 if self.max_rec and c >= self.max_rec: r.terminate(f"Maximum heartbeats received: {c}") except V20Error as e: # catch API related errors that may occur logger.error(f"V20Error: {e}") except ConnectionError as e: logger.error(f"ConnectionError: {e}") time.sleep(2) except StreamTerminated as e: logger.error(f"StreamTerminated: {e}") except Exception as e: logger.error(f"Some exception: {e}")
def get_current_ask_price(order_instrument): """ Return the current ask price for an instrument at the time the function is called """ maxrec = 10 # Try to get the stream price data 10 times n = 0 s = PricingStream(accountID=accountID, params={"instruments": order_instrument}) try: for R in api.request(s): n += 1 if n > maxrec: s.terminate("maxrecs received: {}".format(maxrec)) if R["type"] == "PRICE": #print(R["asks"][0]["price"]) ask_price = R["asks"][0]["price"] return ask_price else: print(R) except V20Error as e: print("Error: {}".format(e)) # If we fail to get price data return False
request_params=request_params) # setup the stream request r = PricingStream(accountID=accountID, params={"instruments": ",".join(clargs.instruments)}) n = 0 while True: try: for R in api.request(r): if clargs.nice: R = json.dumps(R, indent=2) print(R) n += 1 if MAXREC and n >= MAXREC: r.terminate("maxrecs received: {}".format(MAXREC)) except V20Error as e: # catch API related errors that may occur with open("LOG", "a") as LOG: LOG.write("V20Error: {}\n".format(e)) break except ConnectionError as e: with open("LOG", "a") as LOG: LOG.write("Error: {}\n".format(e)) except StreamTerminated as e: with open("LOG", "a") as LOG: LOG.write("Stopping: {}\n".format(e)) break except Exception as e: with open("LOG", "a") as LOG:
api = API(access_token=auth_token_data['oanda-api-token'], environment="practice", request_params=request_params) r = PricingStream(accountID=auth_token_data['oanda-account-id'], params={"instruments": ",".join(args.instruments)}) price_df = pd.DataFrame(columns=[]) n = 0 while True: try: for time_point in api.request(r): print(time_point) n += 1 if max_records and n >= max_records: r.terminate("maxrecs received: {}".format(max_records)) except V20Error as e: # catch API related errors that may occur with open("LOG", "a") as LOG: print("V20Error: {}\n".format(e)) break except ConnectionError as e: with open("LOG", "a") as LOG: print("Error: {}\n".format(e)) except StreamTerminated as e: with open("LOG", "a") as LOG: print("Stopping: {}\n".format(e)) break except Exception as e: with open("LOG", "a") as LOG:
import json import oandapyV20 from oandapyV20 import API from oandapyV20.exceptions import V20Error from oandapyV20.endpoints.pricing import PricingStream from basic import accountID, access_token, api instruments = 'EUR_USD,EUR_JPY' s = PricingStream(accountID=accountID, params={'instruments': instruments}) MAXREC = 10 try: n = 0 for R in api.request(s): print(json.dumps(R, indent=2)) n += 1 if n > MAXREC: s.terminate('maxrecs received {}'.format(MAXREC)) except V20Error as e: print('Error: {}'.format(e))
fig, ax = plt.subplots(1, 1) info = [] try: n = 0 for R in api.request(s): print(json.dumps(R, indent=2)) if ("bids" in R.keys()): cols = [ 'Datetime', 'bids', 'asks', 'closeoutBid', 'closeoutAsk', 'instrument' ] df = pd.DataFrame(index=[], columns=cols) info.append([ R["time"][:19], R["bids"][0]["price"], R["asks"][0]["price"], R["closeoutBid"], R["closeoutAsk"], R["instrument"] ]) df = pd.DataFrame(info) df.columns = cols df['Datetime'] = pd.to_datetime(df['Datetime']) df = df.set_index('Datetime') print(json.dumps(R["bids"][0]["price"], indent=2)) print(df) n += 1 if n > MAXREC: s.terminate("maxrecs received {}".format(MAXREC)) except V20Error as e: print("Error: {}".format(e))