def getOandaPriceHeavyThread(q1): i = getOandaInstru(list_pairs) info = PricingInfo(accountID=accountID, params={"instruments": i}) time_t1 = timer() r = api.request(info) # time_t2_temp = r["time"] time_t2 = timer() latency = (time_t2 - time_t1) * 1000 if latency > 0: print("Oanda's Async Latency: ", str(round(latency, 2)), "ms") prices = r["prices"] global quotes_oanda quotes_oanda = [] for j in prices: symbol_raw = j['instrument'] symbol = symbol_raw[:3] + symbol_raw[4:] quote_time = j['time'] qt = parser.parse(quote_time) qt_ok = qt.replace(tzinfo=timezone.utc).timestamp() ask = j['asks'][0]['price'] bid = j['bids'][0]['price'] info = 'time=' + str(qt_ok) + ' symbol=' + symbol + ' ask=' + str( ask) + ' bid=' + str(bid) info_list = dict(i.split('=') for i in info.split()) quotes_oanda.append(info_list) q1.put(quotes_oanda)
def __init__(self, nari_code): a = nari.getOandaSymbolList(nari_code) self.__api = API(access_token=ac.access_token, environment=oc.OANDA_ENV.PRACTICE) params = {"instruments": ','.join(a)} self.__pinfo = PricingInfo(ac.account_ID, params) self.code = nari.getSymbolList(nari_code)
def oanda(): account_id = "" access_token = "" api = API(access_token=access_token, environment="live") params = {"instruments": "USD_JPY"} pricing_info = PricingInfo(accountID=account_id, params=params) oal_ask = 0 oal_ask_pre = 0 oal_bid = 0 oal_bid_pre = 0 try: while True: api.request(pricing_info) response = pricing_info.response oal_ask_pre = oal_ask oal_ask = response['prices'][0]['asks'] oal_bid_pre = oal_bid oal_bid = response['prices'][0]['bids'] if oal_ask != oal_ask_pre: print("oandaask:" + str(oal_ask) + " oandabid:" + str(oal_bid)) except V20Error as e: print("Error: {}".format(e))
def get_realtime_ticker(self, callback): params = { 'instruments': set.product_code } r = PricingInfo(accountID=self.account_id, params=params) try: res = self.client.request(r) except V20Error as e:
def getOandaPrice(): i = getOandaInstru(list_pairs) info = PricingInfo(accountID=accountID, params={"instruments": i}) r = api.request(info) # time = r["time"] prices = r["prices"] price_list = [] for j in prices: symbol_raw = j['instrument'] symbol = symbol_raw[:3] + symbol_raw[4:] quote_time = j['time'] qt = parser.parse(quote_time) qt_ok = qt.replace(tzinfo=timezone.utc).timestamp() ask = j['asks'][0]['price'] bid = j['bids'][0]['price'] info = 'time=' + str(qt_ok) + ' symbol=' + symbol + ' ask=' + str(ask) + ' bid=' + str(bid) info_list = dict(i.split('=') for i in info.split()) price_list.append(info_list) return price_list
def currentTick(self, currency): params = {'instruments': currency} req = PricingInfo(accountID=self.account_id, params=params) try: res = self.client.request(req) tick = Tick(None, None, None, None, None) tick.parse(res) tick.volume = self.currentVolume(currency) except V20Error as e: logger.error('in currentPrice() ... {e}', e) return None
def test_accounts(self): token = open('../Account/Token.txt', 'r').read() accId = open('../Account/Account.txt', 'r').read() oanda = oandapyV20.API(environment="practice", access_token=token) r = AccountList() oanda.request(r) accsInfo = r.response.get('accounts') self.assertTrue(len(accsInfo) > 0) p = PricingInfo(accId, "instruments=EUR_USD") oanda.request(p) print p.response self.assertTrue(len(p.response.get('prices')) > 0)
def test_accounts(self): conf = Config.Config() token = conf.token accId = conf.account_id oanda = oandapyV20.API(environment="practice", access_token=token) r = AccountList() oanda.request(r) accsInfo = r.response.get('accounts') self.assertTrue(len(accsInfo) > 0) p = PricingInfo(accId, "instruments=EUR_USD") oanda.request(p) print(p.response) self.assertTrue(len(p.response.get('prices')) > 0)
def get_ticker(self, product_code) -> Ticker: params = {'instruments': product_code} req = PricingInfo(accountID=self.account_id, params=params) try: resp = self.client.request(req) except V20Error as e: logger.error(f'action=get_ticker error={e}') raise timestamp = datetime.timestamp(dateutil.parser.parse(resp['time'])) price = resp['prices'][0] instrument = price['instrument'] bid = float(price['bids'][0]['price']) ask = float(price['asks'][0]['price']) volume = self.get_candle_volume() return Ticker(instrument, timestamp, bid, ask, volume)
def spreadcheck(self, pairs_checked): for i in pairs_checked: info = PricingInfo(accountID=accountID, params={"instruments": i}) value = api.request(info) bid = float(value['prices'][0]['bids'][0]['price']) ask = float(value['prices'][0]['asks'][0]['price']) decim = str(bid)[::-1].find('.') if decim < 4: spread = (ask - bid) * (10 ** (3 - 1)) if decim >= 4: spread = (ask - bid) * (10 ** (5 - 1)) if spread > spread_limit: print("Spread Limit Exceeded !") return False return True
def orderlaunch(self, args): pair_targeted, direction = args info = PricingInfo(accountID=accountID, params={"instruments": pair_targeted}) mkt_order = None if direction is 0: return False elif direction is 1: mkt_order = MarketOrderRequest( instrument=pair_targeted, units=1000) elif direction is -1: mkt_order = MarketOrderRequest( instrument=pair_targeted, units=-1000) # create the OrderCreate request r = orders.OrderCreate(accountID, data=mkt_order.data) try: # create the OrderCreate request rv = api.request(r) except oandapyV20.exceptions.V20Error as err: print(r.status_code, err) return False else: # print(json.dumps(rv, indent=2)) try: key = 'orderFillTransaction' if key in rv: print('#', pair_targeted, ': Order opening -> SUCCESS') except oandapyV20.exceptions.V20Error as err: print(r.status_code, err) return False else: return True
def get_ticker(self, product_code) -> Ticker: params = {"instruments": product_code} req = PricingInfo(accountID=self.account_id, params=params) try: resp = self.client.request(req) except V20Error as e: logger.error(f"action=get_ticker error={e}") raise timestamp = datetime.timestamp(dateutil.parser.parse(resp["time"])) price = resp["prices"][0] instrument = price["instrument"] bid = float(price["bids"][0]["price"]) ask = float(price["asks"][0]["price"]) volume = self.get_candle_volume() return Ticker( product_code=instrument, timestamp=timestamp, bid=bid, ask=ask, volume=volume, )
def spreadcheck(pair_checked): try: info = PricingInfo(accountID=accountID, params={"instruments": pair_checked}) value = api.request(info) spread = 0 bid = float(value['prices'][0]['bids'][0]['price']) ask = float(value['prices'][0]['asks'][0]['price']) decim = str(bid)[::-1].find('.') if decim < 4: spread = (ask - bid) * (10**(3 - 1)) if decim >= 4: spread = (ask - bid) * (10**(5 - 1)) if spread > spread_limit: print("Spread Limit Exceeded !") return False except V20Error as e: print("V20Error: {}".format(e)) return False else: return True
from google.cloud import datastore from datetime import datetime accountID = "101-011-6029361-001" access_token = "8153764443276ed6230c2d8a95dac609-e9e68019e7c1c51e6f99a755007914f7" api = API(access_token=access_token, environment="practice") # get current data from oanda # example: getdata.py DE30_EUR,EUR_USD,EUR_JPY #instruments = "DE30_EUR,EUR_USD,EUR_JPY" instruments = '' if len(sys.argv) < 2: print('Require 1 argv: a list of instrument separated with comma') print('Example: python getdata.py DE30_EUR,EUR_USD,EUR_JPY') else: instruments = sys.argv[1] r = PricingInfo(accountID=accountID, params={"instruments": instruments}) rv = api.request(r) print(rv['time']) client = datastore.Client() for i in rv['prices']: if i['type'] == 'PRICE': key = client.key(i['instrument']) entity = datastore.Entity(key=key) entity['time'] = datetime.strptime(i['time'][:19], "%Y-%m-%dT%H:%M:%S") entity['closeoutBid'] = i['closeoutBid'] client.put(entity) print('Put entity')
# リアルタイムで為替レート値を取得する。 # # author たっきん # # 事前準備 : # oandapyV20のインストール (pip install oandapyV20) # ============================================================================== import time import json from oandapyV20 import API from oandapyV20.endpoints.pricing import PricingInfo from oandapyV20.exceptions import V20Error from fx import oanda_common as oc from fx import your_account as ya api = API(access_token=ya.access_token, environment=oc.OandaEnv.PRACTICE) params = {"instruments": "USD_JPY,EUR_JPY,EUR_USD"} pi = PricingInfo(ya.account_number, params) try: while True: rsp = api.request(pi) print("■リストの取得") print(json.dumps(rsp, indent=2)) time.sleep(1) except V20Error as e: print("Error: {}".format(e))
def orderlaunch(args): pair_targeted, direction = args info = PricingInfo(accountID=accountID, params={"instruments": pair_targeted}) mkt_order = None if direction is 0: return False elif direction is 1: raw_current_price = api.request(info) bid_current = float(raw_current_price['prices'][0]['bids'][0]['price']) decim = str(bid_current)[::-1].find('.') if decim < 4: decim = 3 if decim >= 4: decim = 5 stop_loss = round(bid_current - bid_current * sl_tp_prc, decim) take_profit = round(bid_current + bid_current * sl_tp_prc, decim) if float(count_spe_trades(pair_targeted)) < 0: close(pair_targeted) mkt_order = MarketOrderRequest( instrument=pair_targeted, units=trade_size, takeProfitOnFill=TakeProfitDetails(price=take_profit).data, stopLossOnFill=StopLossDetails(price=stop_loss).data) elif direction is -1: raw_current_price = api.request(info) ask_current = float(raw_current_price['prices'][0]['asks'][0]['price']) decim = str(ask_current)[::-1].find('.') if decim < 4: decim = 3 if decim >= 4: decim = 5 stop_loss = round(ask_current + ask_current * sl_tp_prc, decim) take_profit = round(ask_current - ask_current * sl_tp_prc, decim) if float(count_spe_trades(pair_targeted)) > 0: close(pair_targeted) mkt_order = MarketOrderRequest( instrument=pair_targeted, units=(trade_size * -1), takeProfitOnFill=TakeProfitDetails(price=take_profit).data, stopLossOnFill=StopLossDetails(price=stop_loss).data) # create the OrderCreate request r = orders.OrderCreate(accountID, data=mkt_order.data) try: # send the OrderCreate request rv = api.request(r) print(json.dumps(rv, indent=2)) except V20Error as err: print(r.status_code, err) return False else: try: if Trailing is True: key = 'orderFillTransaction' if key in rv: trade_id = rv['orderFillTransaction']['tradeOpened'][ 'tradeID'] bid_current = float(rv['orderFillTransaction']['fullPrice'] ['bids'][0]['price']) decim = str(bid_current)[::-1].find('.') trail_point_ok = 0 if decim < 4: trail_point_ok = trail_point * (1 / (10**(3 - 1))) if decim >= 4: trail_point_ok = trail_point * (1 / (10**(5 - 1))) ordr = TrailingStopLossOrderRequest( tradeID=trade_id, distance=trail_point_ok) r = orders.OrderCreate(accountID, data=ordr.data) rva = api.request(r) print(json.dumps(rva, indent=2)) except V20Error as err: print(r.status_code, err) return False else: return True
from os import path import matplotlib.pyplot as plt import oandapyV20 import oandapyV20.endpoints.orders as orders import oandapyV20.endpoints.positions as positions from oandapyV20.contrib.requests import MarketOrderRequest from oandapyV20.contrib.requests import TakeProfitDetails, StopLossDetails from oandapyV20.endpoints.accounts import AccountDetails from oandapyV20.endpoints.pricing import PricingInfo from Conf.Config import Config config = Config() oanda = oandapyV20.API(environment=config.env, access_token=config.token) pReq = PricingInfo(config.account_id, 'instruments=' + config.insName) asks = list() bids = list() long_time = datetime.now() short_time = datetime.now() if config.write_back_log: f_back_log = open( path.relpath(config.back_log_path + '/' + config.insName + '_' + datetime.datetime.now().strftime("%Y%m%d-%H%M%S")) + '.log', 'a') time = 0 times = list() last_ask = 0 last_bid = 0