async def config_arbitrages(): instruments = oanda.request( accounts.AccountInstruments(accountID))["instruments"] symbols = [instrument['displayName'] for instrument in instruments] print("SYMBOLS:\n{}".format(json.dumps(symbols, indent=2))) list_of_arb_lists = [] for symb in symbols: arb_list = [symb] j = 0 while 1: if j >= 1: if len(arb_list) > 1: final = arb_list[0].split('/')[1] + '/' + str( arb_list[1].split('/')[1]) if final in symbols: arb_list.append(final) break for sym in symbols: if sym in arb_list: continue if arb_list[0].split('/')[0] == sym.split('/')[0]: if arb_list[0] == sym: continue else: arb_list.append(sym) j += 1 break j += 1 if len(arb_list) > 2: if arb_list[2] in symbols: list_of_arb_lists.append(arb_list) print("\nList of Arbitrage Symbols:", list_of_arb_lists) return list_of_arb_lists
def get_currency_info(currency_pair: str, api: API): """ Get the designated currency pair's information (e.g.minimum tradable unit, split rate, and so on) Parameters ---------- currency_pair : str currency pair you want to get information e.g. "USD_JPY" api : API Returns ------- r : JSON information of currency pair you designated """ if type(currency_pair) != str: raise Exception('please set currency pair with String.') params = {"instruments": currency_pair} try: r = accounts.AccountInstruments(accountID=accountID, params=params) except Exception: traceback.print_exc() print( 'exception was throwned when app tries to fetch currency info from API.' ) return api.request(r)
def get_instruments(client, accountID): r = accounts.AccountInstruments(accountID=accountID) rv = client.request(r) data = pd.DataFrame(rv['instruments']) return data
def get_instruments(): client = API(access_token=access_token) r = accounts.AccountInstruments(accountID=account_id) rv = client.request(r) print(json.dumps(rv, indent=2)) for item in rv['instruments']: if 'USD_' in item['name']: print(item['name'])
def get_precision_digits(self, finsec): client = oandapyV20.API(access_token=self.token) r = accounts.AccountInstruments(accountID=self.account_id) rv = client.request(r) for line in rv['instruments']: if line['name'] == finsec: return line['displayPrecision']
def get_tradable_instruments(oanda_api=oanda_api, oanda_account=oanda_account): client = oandapyV20.API(access_token=oanda_api) params = { "instruments": "" } #"EU50_EUR,EUR_USD,US30_USD,FR40_EUR,EUR_CHF,DE30_EUR"} r = accounts.AccountInstruments(oanda_account, params=params) client.request(r) return r.response
def test__get_instruments_data_exception(self): """check for data parameter exception.""" with self.assertRaises(TypeError) as oErr: r = accounts.AccountInstruments(accountID=accountID, data={}) self.assertEqual( "__init__() got an unexpected keyword " "argument 'data'", "{}".format(oErr.exception))
def get_instrument_list(self): ''' Request all eligible assets to trade ''' r = accounts.AccountInstruments(accountID=self.accountID) self.api.request(r) self.instruments = pd.DataFrame( r.response['instruments'])['name'].values
def get_instruments(): """Gets a list of all tradable instruments on the Oanda platform.""" account_instruments = accounts.AccountInstruments(accountID) client.request(account_instruments) account_instruments = account_instruments.response all_instruments = account_instruments["instruments"] instrument_pairs = {i["name"]: i["displayName"] for i in all_instruments} return instrument_pairs
def test__account_instruments(self, mock_req): """get the instruments of specified account.""" tid = "_v3_account_by_accountID_instruments" resp, data, params = fetchTestData(responses, tid) r = accounts.AccountInstruments(accountID=accountID, params=params) mock_req.register_uri('GET', "{}/{}".format(api.api_url, r), text=json.dumps(resp)) result = api.request(r) self.assertTrue(result == resp)
async def scalp(order_mode=False): instruments1 = oanda.request( accounts.AccountInstruments(accountID))["instruments"] symbols = [instrument['name'] for instrument in instruments1] symbols_display = [ instrument['displayName'] for instrument in instruments1 ] scores_by_market = [] i = 0 for market in symbols: scores_by_market.append({'market': market, 'strategy_scores': []}) rsi_h1_score = await RSI_strategy(market, "H1") double_ema_score = await double_ema(market, "H1") MACD_score = await MACD_strategy(market, "H1") ATR_score = await ATR_strategy(market, "H1") points_of_val_score = await points_of_value(market, "H1") print("MARKET: {} \n".format(market)) print("RSI score: {}".format(rsi_h1_score)) print("double EMA score: {}".format(double_ema_score)) print("MACD score: {}".format(MACD_score)) print("ATR score: {}".format(MACD_score)) scores_by_market[i]['strategy_scores'].extend( [rsi_h1_score, double_ema_score, MACD_score, ATR_score]) overallscore = {} buy = 0 sell = 0 count = 0 for strategyscore in scores_by_market[i]['strategy_scores']: try: buy += strategyscore['buy_signal'] sell += strategyscore['sell_signal'] except: if buy > sell: buy += strategyscore['enter_signal'] buy -= strategyscore['exit_signal'] elif sell > buy: sell += strategyscore['enter_signal'] sell -= strategyscore['exit_signal'] count += 1 overallscore['buy_signal'] = buy / count overallscore['sell_signal'] = sell / count scores_by_market[i]['overall_score'] = overallscore if (overallscore['buy_signal'] > 3.5 and overallscore['sell_signal'] < 2.5) or (overallscore['buy_signal'] < 2.5 and overallscore['sell_signal'] > 3.5): print("\nFOUND PROFITABLE TRADE OPPORTUNITY---------------") print("OVERALL SCORE: {}".format(overallscore)) if order_mode: market_order = await asyncio.ensure_future( create_order(scores_by_market[i]['market'], overallscore['buy_signal'], overallscore['sell_signal'])) i += 1 return scores_by_market
def get_instruments(self): """Gets a list of all tradable instruments on the Oanda platform.""" instruments_endpoint = accounts.AccountInstruments(self._account_id) self._api_client.request(instruments_endpoint) instruments = instruments_endpoint.response all_instruments = instruments["instruments"] instrument_pairs = { i["name"]: i["displayName"] for i in all_instruments } return instrument_pairs
def create_instrument_list(): oanda = oandapy.API(environment="practice", access_token=Utility.getAccountToken(), headers={'Accept-Datetime-Format': 'UNIX'}) r = accounts.AccountInstruments(accountID=Utility.getAccountID()) name_list = [] for instru in oanda.request(r)["instruments"]: name = instru["name"] index_underscore = name.find("_") name_front = name[:index_underscore] name_back = name[(index_underscore + 1):] name_list.append(name_front) name_list.append(name_back) name_list = set(name_list[:5]) return name_list
def account_instruments(self, asset, option='digits'): r = accounts.AccountInstruments(ACCOUNT_ID, params={'instruments': asset}) if option == 'digits': try: rv = api.request(r)['instruments'][0]['displayPrecision'] except: rv = min( len( str(self.candle_data(asset, 1, 1).iloc[0].close).split('.')[1]), 5) # rv = api.request(r)['instruments'] #to_find solutions return rv
def fetch_markets(self): sleep_time = 0.2 while True: try: request = accounts.AccountInstruments(accountID=self.account_id) self.oanda.request(request) instruments = request.response["instruments"] result = {} id = 0 for instrument in instruments: id = id + 1 symbol = instrument["name"] base = symbol.split("_")[0] quote = symbol.split("_")[1] baseId = 0 quoteId = 0 precision = {} precision["price"] = instrument["displayPrecision"] limits = None market = None name = instrument["displayName"] type = instrument["type"] result[symbol] = { 'id': id, 'symbol': symbol, 'name': name, 'type': type, 'base': base, 'quote': quote, 'baseId': baseId, 'quoteId': quoteId, 'active': True, 'precision': precision, 'limits': limits, 'info': market } self.markets = result break except Exception as e: time.sleep(sleep_time) sleep_time = sleep_time * 2 if sleep_time > 30: sleep_time = 0.2 return self.markets
def instrument_list(accountID, token): """ Function to retrieve all tradable instruments from Oanda. Returns List with instrument codes ------- """ instr_list = [] client = oandapyV20.API(access_token=token) r = accounts.AccountInstruments(accountID=accountID) rv = client.request(r) # instr_dict = json.dumps(rv, indent=2) for i in range(len(rv['instruments'])): instr_list.append(rv['instruments'][i]['name']) return instr_list
def account_instruments(self, only_currency=True, display=False): def leverage(margin): return str(int(1. / float(margin))) + ":1" def percentage(margin): return str(int(float(margin) * 100)) + "%" endpoint = accounts.AccountInstruments(self.account_id) self.send_request(endpoint) _ins = endpoint.response _table = [] _markets = [] if only_currency: for _in in _ins['instruments']: if _in["type"] == "CURRENCY": _markets.append(_in["name"]) _table.append([ _in["displayName"], _in["name"], percentage(_in["marginRate"]), leverage(_in["marginRate"]), _in["type"] ]) _table = sorted(_table, key=lambda x: x[1]) else: for _in in _ins['instruments']: _table.append([ _in["displayName"], _in["name"], percentage(_in["marginRate"]), leverage(_in["marginRate"]), _in["type"] ]) _table = sorted(_table, key=lambda x: x[1]) if display: print( tabulate(_table, headers=[ 'Display name', 'Name', 'Margin rate', 'Leverage', 'type' ], tablefmt="pipe")) return _markets
def pip_spread(instrument, print_=False): api = API(access_token=access_token, environment="practice") pip = 0 r = accounts.AccountInstruments(accountID=accountID) api.request(r) for i in r.response['instruments']: if i['name'] == instrument: pip = 10**i['pipLocation'] spread = 0 r = pricing.PricingInfo(accountID=accountID, params={'instruments': instrument}) api.request(r) response = r.response spread = float(response['prices'][0]['asks'][0]['price']) - float( response['prices'][0]['bids'][0]['price']) spread = round(spread / pip, 1) if print_: root = instrument.split('_')[1] print('{}{} = 1pips, spread: {}pips, {}{}'.format( pip, root, spread, pip * spread, root)) else: return pip, spread, float(Decimal(str(pip)) * Decimal(str(spread)))
def parse_wiki_forex(): """ Download current list of OANDA Instruments. return: list of tuples to add to PostgreSQL. """ now = datetime.datetime.utcnow() accountID = oanda_cred.acc_id_practice token = oanda_cred.token_practice client = oandapyV20.API(access_token=token) r = accounts.AccountInstruments(accountID=accountID) rv = client.request(r) df = pd.read_json(json.dumps(rv, indent=2)) df = pd.io.json.json_normalize(data=df['instruments']) symbols = [] for i, symbol in df.iterrows(): symbols.append((symbol['name'], 'Forex', symbol['displayName'], 'Forex', 'USD', now, now)) return symbols
def get_instrument_info(): params = {"instruments": "USD_JPY"} r = accounts.AccountInstruments(accountID=account_id, params=params) info = oanda.request(r) return info
def __init__(self): client = API(access_token=config['account']['token']) r = accounts.AccountInstruments( accountID=config['account']['accountID']) self.rv = client.request(r)
def all_inst(): api = API(access_token=access_token, environment="practice") r = accounts.AccountInstruments(accountID=accountID) api.request(r) inst_l = [d['name'] for d in r.response['instruments']] return inst_l
async def scalp(order_mode=False): instruments1 = oanda.request( accounts.AccountInstruments(accountID))["instruments"] symbols = [instrument['name'] for instrument in instruments1] symbols_display = [ instrument['displayName'] for instrument in instruments1 ] scores_by_market = [] i = 0 symbols = ["EUR_USD", "AUD_USD"] for market in symbols: scores_by_market.append({'market': market, 'strategy_scores': []}) rsi_h1_score = await RSI_strategy(market, "H1") double_ema_score = await double_ema(market, "H1") MACD_score = await MACD_strategy(market, "H1") ATR_score = await ATR_strategy(market, "H1") # points_of_val_score = await points_of_value(market, "H1") # client_sentiment_score = await client_sentiment(market) print("\nMARKET: {}".format(market)) overallscore = {} buy = 0 sell = 0 count = 0 ### This section is for LSTM Neural Network that will predict the next price lstm_signal = {'buy_signal': 0.0, 'sell_signal': 0.0} params = {"count": 5000, "granularity": "H1"} candles = oanda.request( instruments.InstrumentsCandles(instrument=market, params=params))['candles'] df = pd.DataFrame( columns=["Date", "Open", "High", "Low", "Close", "Volume"]) df['Date'] = [i['time'] for i in candles[::-1]] df['Open'] = [float(i['mid']['o']) for i in candles[::-1]] df['High'] = [float(i['mid']['h']) for i in candles[::-1]] df['Low'] = [float(i['mid']['l']) for i in candles[::-1]] df['Close'] = [float(i['mid']['c']) for i in candles[::-1]] df['Volume'] = [float(i['volume']) for i in candles[::-1]] last_val, next_val = lstmpredictor.lstm_neural_network(df) print(last_val, next_val) if last_val > next_val: lstm_signal['sell_signal'] += 8 * (last_val / next_val) elif last_val < next_val: lstm_signal['buy_signal'] += 8 * (next_val / last_val) buy += lstm_signal['buy_signal'] sell += lstm_signal['sell_signal'] ### print("\nMARKET: {}".format(market)) print("RSI score: {}".format(rsi_h1_score)) print("double EMA score: {}".format(double_ema_score)) print("MACD score: {}".format(MACD_score)) print("ATR score: {}".format(ATR_score)) print("LSTM score: {}".format(lstm_signal)) # print("Points of Value score: {}".format(points_of_val_score)) # print("Client Sentiment Score: {}".format(client_sentiment_score)) # scores_by_market[i]['strategy_scores'].extend([rsi_h1_score, double_ema_score, MACD_score, ATR_score]) scores_by_market[i]['strategy_scores'].extend([ rsi_h1_score, double_ema_score, MACD_score, ATR_score, lstm_signal ]) ## Apply Randomized Weighted Majority Algo here to optimize the weights of each strategy over time for strategyscore in scores_by_market[i]['strategy_scores']: try: buy += strategyscore['buy_signal'] sell += strategyscore['sell_signal'] except: if buy > sell: buy += strategyscore['enter_signal'] buy -= strategyscore['exit_signal'] elif sell > buy: sell += strategyscore['enter_signal'] sell -= strategyscore['exit_signal'] count += 1 overallscore['buy_signal'] = buy / count overallscore['sell_signal'] = sell / count scores_by_market[i]['overall_score'] = overallscore if (overallscore['buy_signal'] > long_buy and overallscore['sell_signal'] < long_sell): print("\nFOUND LONG PROFITABLE TRADE OPPORTUNITY---------------") buyCurrency( market, 'short', 10000.0) #10 refers to amount of money wanted to invest print("OVERALL SCORE: {}".format(overallscore)) if order_mode: market_order, trailing_stop = await asyncio.ensure_future( create_order(scores_by_market[i]['market'], overallscore['buy_signal'], overallscore['sell_signal'])) order_id = market_order['orderFillTransaction']['orderID'] if first_order: first_order_id = order_id first_order = False # await asyncio.ensure_future(watch_order(order_id)) elif (overallscore['buy_signal'] < short_buy and overallscore['sell_signal'] > short_sell): print("\nFOUND SHORT PROFITABLE TRADE OPPORTUNITY---------------") buyCurrency(market, 'short', 10000.0) print("OVERALL SCORE: {}".format(overallscore)) i += 1 return scores_by_market
# -*- coding: utf-8 -*- """retrieve the tradable instruments for account.""" import json import oandapyV20 import oandapyV20.endpoints.accounts as accounts from exampleauth import exampleAuth accountID, token = exampleAuth() client = oandapyV20.API(access_token=token) r = accounts.AccountInstruments(accountID=accountID) rv = client.request(r) print(json.dumps(rv, indent=2))
import pandas as pd import os from configparser import ConfigParser Path_To_TKNS = os.path.join(os.path.abspath(os.path.join(__file__ ,"../../..")), "connections.cfg") config = ConfigParser() config.read(Path_To_TKNS) accountID = config['Oanda']['accountID'] token = config['Oanda']['token'] client = oandapyV20.API(access_token="e675daec169c0349374fb184e82571b0-5996df09a9104009f55ddcc30971e8dd") r = accounts.AccountInstruments(accountID=accountID) rv = client.request(r) data = pd.json_normalize(pd.DataFrame(rv)['instruments']) needed_columns = ['name', 'type', 'displayName', 'minimumTradeSize','marginRate','financing.longRate','financing.shortRate'] frame[needed_columns].to_csv("Oanda_instruments.csv", index=False) #################################################################################### from collections import defaultdict import pandas as pd import oandapyV20 import oandapyV20.endpoints.accounts as accounts import oandapyV20.endpoints.pricing as pricing
def oanda_getinstruments(self): r = accounts.AccountInstruments(accountID=self.oanda_account_id) rv = self.oanda.request(r) return rv
from oandapyV20 import API from oandapyV20.exceptions import V20Error from oandapyV20.endpoints.pricing import PricingStream import oandapyV20.endpoints.orders as orders import oandapyV20.endpoints.instruments as instruments import oandapyV20.endpoints.accounts as accounts accountID = "101-009-14596339-001" access_token = '02b2ada0401a30b2bad21668ae7e0ec2-545d6baa42608e924a1b59bf1dd4278f' api = API(access_token=access_token, environment="practice") params = {"instruments": "USD_JPY"} instrument = accounts.AccountInstruments(accountID=accountID, params=params) api.request(instrument) account = accounts.AccountSummary(accountID) api.request(account) params = {"count": 5, "granularity": "M5"} candles = instruments.InstrumentsCandles(instrument="USD_JPY", params=params) api.request(candles)
def get_symbol(client, account_id, select): r = accounts.AccountInstruments(accountID=account_id) ins = client.request(r) #return [item['name'] for item in ins['instruments'] if item['name'][:3] == select] return r
client = oandapyV20.API(access_token=access_token) # Get Basic Account Details r = accounts.AccountDetails(accountID) client.request(r) account_details = r.response print("\n raw account details: \n", account_details) # or account_table_format = pd.Series(r.response['account']) print(account_table_format) # Get Account List (for tracking multiple aub accounts) r = accounts.AccountList() all_acc_under_mgt = client.request(r) print("\n All Accounts under management: \n", all_acc_under_mgt) # Get Account Status Summary (are there open trades?... etc) r = accounts.AccountSummary(accountID) client.request(r) account_status_summary = pd.Series(r.response['account']) print("\n Summary of Account Status: \n", account_status_summary) # Instruments that can be traded with the specified account, # minimum Trailing Stop Distance, r = accounts.AccountInstruments(accountID=accountID, params="EUR_USD") client.request(r) account_instruments = pd.DataFrame(r.response['instruments']) print("\n List of tradable Account Instruments: \n", account_instruments)
def request_acc_instruments(self): client = oandapyV20.API(access_token=self.token) r = accounts.AccountInstruments(accountID=self.account_id) return client.request(r)