def __init__(self, **kwargs): user_token_path = kwargs.get('token', './oanda.conf') self._orders_ids = {} self._api_token, self._account_id = open(user_token_path).read().split( ',') self._client = oandapyV20.API(access_token=self._api_token) self._subscriptions = Subscriptions(BrokerType.OANDA, self._client, self._account_id)
def get_transactions_range(_from): env = yaml.safe_load(open('/seq/seq5/configs/env.yaml', 'r')) accountid = env['accountid_long'] client = oandapyV20.API(access_token=env['client']) params = {"from": _from, "to": _from + 500, 'type': 'ORDER_FILL'} r = trans.TransactionIDRange(accountID=accountid, params=params) client.request(r) return r.response
def transactions_close(ACCESS_TOKEN, ACCOUNT_ID, units_quantity, trade_id): # Close a trade according to its id and quantity of units client = oandapyV20.API(access_token=ACCESS_TOKEN) data = {"units": units_quantity} r = trades.TradeClose(accountID=ACCOUNT_ID, data=data, tradeID=trade_id) client.request(r) print(r.response)
def get_most_recent_transaction(): env = yaml.safe_load(open('/seq/seq5/configs/env.yaml', 'r')) accountid = env['accountid_long'] client = oandapyV20.API(access_token=env['client']) r = trades.OpenTrades(accountID=accountid) client.request(r) _id = int(r.response['lastTransactionID']) return _id
def getAccountDetails(): client = oandapyV20.API(access_token=token) client_request = accounts.AccountSummary(accountID=accountID) rv = client.request(client_request) response = json.dumps(rv) data = json.loads(response) return data['account']['balance']
def get_candles(instrument, granularity, _from, _to, da=daily_alignment): print('Fetching Candles.') client = 'f01b219340f61ffa887944e7673d85a5-6bcb8a840148b5c366e17285c984799e' client = oandapyV20.API(access_token=client) params = { 'from': _from, 'to': _to, 'granularity': granularity, 'price': 'BAM', 'count': 5000, 'alignmentTimezone': 'UTC', 'dailyAlignment': da } # Request Data coll = [] for r in InstrumentsCandlesFactory(instrument=instrument, params=params): client.request(r) coll.append(r.response) # collect Returned Data into list. Cast to floats. bidlow = [] bidhigh = [] bidclose = [] asklow = [] askhigh = [] askclose = [] midlow = [] midhigh = [] midclose = [] timestamp = [] volume = [] for i in range(len(coll)): for j in range(len(coll[i]['candles'])): bidhigh.append(float(coll[i]['candles'][j]['bid']['h'])) bidlow.append(float(coll[i]['candles'][j]['bid']['l'])) bidclose.append(float(coll[i]['candles'][j]['bid']['c'])) askhigh.append(float(coll[i]['candles'][j]['ask']['h'])) asklow.append(float(coll[i]['candles'][j]['ask']['l'])) askclose.append(float(coll[i]['candles'][j]['ask']['c'])) midhigh.append(float(coll[i]['candles'][j]['mid']['h'])) midlow.append(float(coll[i]['candles'][j]['mid']['l'])) midclose.append(float(coll[i]['candles'][j]['mid']['c'])) timestamp.append(coll[i]['candles'][j]['time']) volume.append(float(coll[i]['candles'][j]['volume'])) # Assemble DataFrame. Cast Values. df = pd.DataFrame(pd.to_datetime(timestamp)) df.columns = ['timestamp'] df['bidhigh'] = pd.to_numeric(bidhigh) df['bidlow'] = pd.to_numeric(bidlow) df['bidclose'] = pd.to_numeric(bidclose) df['askhigh'] = pd.to_numeric(askhigh) df['asklow'] = pd.to_numeric(asklow) df['askclose'] = pd.to_numeric(askclose) df['midhigh'] = pd.to_numeric(midhigh) df['midlow'] = pd.to_numeric(midlow) df['midclose'] = pd.to_numeric(midclose) df['spread'] = df.askclose - df.bidclose df['volume'] = pd.to_numeric(volume) return df
def get_data(): accountID = os.environ['oanda_demo_id'] access_token = os.environ['oanda_demo_api'] client = oandapyV20.API(access_token=access_token) granularities = ['S5'] #['S5', 'S10', 'S15', 'S30', 'M1', 'M2', 'M4', 'M5', 'M10', 'M15', 'M30', 'H1', 'H2', 'H3','H4', 'H6', 'H8', 'H12', 'D'] granularities = granularities[::-1] instru = sys.argv[1] columns = ['time', 'volume', 'close', 'high', 'low', 'open', 'complete'] for gran in granularities: i = 0 hit_today = False df = pd.DataFrame(columns=columns) df_next = pd.DataFrame(columns=columns) last_timestamp = '2005-01-01T00:00:00.000000000Z' while not hit_today: params = { 'price': 'M', 'granularity': gran, 'count': 5000, 'from': last_timestamp, 'includeFirst': False, 'alignmentTimezone': 'America/New_York' } r = instruments.InstrumentsCandles(instrument=instru, params=params) client.request(r) resp = r.response i += 1 print(r.status_code, i) data = [] for can in resp['candles']: data.append([ can['time'], can['volume'], can['mid']['c'], can['mid']['h'], can['mid']['l'], can['mid']['o'], can['complete'] ]) df_next = pd.DataFrame(data, columns=columns) df = df.append(df_next, ignore_index=True) last_timestamp = list(df.time)[-1] last_month = list(df.time)[-1][:7] if last_month == '2017-09': hit_today = True save_name = instru + '_' + gran print(save_name, df.shape) df.to_pickle('data/' + save_name)
def get_nav(self): account = {} client = oandapyV20.API(access_token=self.access_token) r = accounts.AccountSummary(self.account_ID) client.request(r) account['nav'] = float(r.response['account']['NAV']) account['balance'] = float(r.response['account']['balance']) account['marginAvailable'] = float(r.response['account']['marginAvailable']) return account # return netvalue, and cash balance
def __init__(self, token, account_id): """ Token of the OANDA app Account id of the user """ self.token = token self.client = oandapyV20.API(access_token=self.token, environment="practice") self.id = account_id
def shows_trade_units_available(ACCESS_TOKEN, ACCOUNT_ID): # Gives the amount of trade units still available for trade client = oandapyV20.API(access_token=ACCESS_TOKEN) account_statement = accounts.AccountDetails(ACCOUNT_ID) client.request(account_statement) units_available = format( float(account_statement.response["account"]["marginAvailable"]) / float(account_statement.response["account"]["marginRate"]), '.0f') return units_available
def get_spread(inst, accountID, access_token): api = oandapyV20.API(access_token=access_token) test = candles(inst, granularity=['M1'], count=[1], From=None, to=None, price=['BA'], nice=True, access_token=access_token) bid = float(test['candles'][0]['bid']['c']) ask = float(test['candles'][0]['ask']['c']) print(bid) print(ask) spread = float(format(ask-bid, '.5f')) return spread
def __init__(self, name, conn): from tools import Utility self.name = name self.conn = conn self.tool = None if name is 'oanda': self.tool = oandapy.API(environment="practice", access_token=Utility.getAccountToken(), headers={'Accept-Datetime-Format': 'UNIX'})
def close_order_manually(accountID, access_token, tradeID): """ Closes order manually using tradeID. """ api = oandapyV20.API(access_token=access_token, environment="practice") request = trades.TradeClose(accountID, tradeID) rv = api.request(request) print(json.dumps(rv, indent=2)) return 0
def __init__(self, name, number): self.name = name self.accountID = f'101-004-11969890-00{number}' self.access_token = '1f4b0414fa0f618fced5a83e01db7ffc-316d266c3a8cdd3ef9e29273bbbd8bef' self.client = oandapyV20.API(access_token=self.access_token, environment="practice") self.open_id = [] file = open(f'{self.name}.txt', 'a+') file.close()
def getAccountInfo(): accountID = config.get('fxpractice', 'active_account') client = oandapyV20.API(access_token=config.get('fxpractice', 'token')) # r = positions.OpenPositions(accountID=config.get('fxpractice','active_account')) r = accounts.AccountSummary(accountID) client.request(r) print r.response return r.response
def connect_to_stream(self): try: client = oandapyV20.API(access_token=self.access_token) params = {'instruments': self.instruments} req = pricing.PricingInfo(accountID=self.account_id, params=params) return req except Exception as e: errmsg = 'Caught exception when connecting to stream\n' + str(e) rq.terminate(errmsg)
def request_data(self, timeframe): self.params['granularity'] = timeframe res = instruments.InstrumentsCandles(instrument=self.instrument, params=self.params) client = oandapyV20.API(access_token=self.access_token, environment=self.environment) client.request(res) return res.response
def test_oanda_fx_history(self): token = open('../Account/Token.txt', 'r').read() oanda = oandapyV20.API(environment="practice", access_token=token) downloader = StockDataDownloader.StockDataDownloader() dateFrom = datetime.utcnow() - timedelta(days=1) dateTo = datetime.utcnow() result = downloader.get_data_from_oanda_fx(oanda, 'EUR_USD', 'S5', dateFrom, dateTo) self.assertTrue(len(result) > 0)
def get_transactions_range(_from, account): client = 'client=oandapyV20.API(access_token=env['client'])' client = oandapyV20.API(access_token=client) params = {"from": _from, "to": _from + 500, 'type': 'ORDER_FILL'} r = trans.TransactionIDRange(accountID=account, params=params) client.request(r) return r.response
def get_orderbook(instrument, time): client = 'client=oandapyV20.API(access_token=env['client'])' client = oandapyV20.API(access_token=client) params = {'time': time, 'Accept-Datetime-Format': 'RFC3339'} r = instruments.InstrumentsOrderBook(instrument=instrument, params=params) a = client.request(r) #print(a)#(r.response) return a
def get_accounts(): client = 'client=oandapyV20.API(access_token=env['client'])' client = oandapyV20.API(access_token=client) r = accounts.AccountList() client.request(r) pprint(r.response['accounts']) accounts_collection = [] for each in r.response['accounts']: accounts_collection.append(each['id']) return accounts_collection
def test_oanda_fx_history(self): conf = Config.Config() token = conf.token oanda = oandapyV20.API(environment="practice", access_token=token) downloader = StockDataDownloader.StockDataDownloader() dateFrom = datetime.utcnow() - timedelta(days=1) dateTo = datetime.utcnow() result = downloader.get_data_from_oanda_fx(oanda, 'EUR_USD', 'S5', dateFrom, dateTo) self.assertTrue(len(result) > 0)
def get_spreads(): client = 'client=oandapyV20.API(access_token=env['client'])' client = oandapyV20.API(access_token=client) params = { "instrument": "EUR_USD", "period": 57600 } r = labs.Spreads(params=params) client.request(r) print(r.response)
def get_open_positions(account): client = 'client=oandapyV20.API(access_token=env['client'])' client = oandapyV20.API(access_token=client) r = positions.OpenPositions(accountID=account) client.request(r) p = r.response instruments = [] for position in p['positions']: instruments.append(position['instrument']) return instruments
def request_instruments(): api_token = os.getenv("OANDA_API_TOKEN") account_id = os.getenv("OANDA_ACCOUNT_ID") client = oandapyV20.API(access_token=api_token) req = AccountInstruments(accountID=account_id) res = client.request(req) with open("instruments.json", 'w') as json_file: json.dump(res, json_file)
def __init__(self): self.dayInterval = 30 # the generation will run this many days self.access_token = open("oanda_api_key.txt", "r").readline()[:-1] self.instrument = "EUR_USD" self.client = oandapyV20.API(access_token=self.access_token) self.date = getRandomDate(self.dayInterval) #gets date for self.marketData = self.getAllMarketData() self.weekExtremes = self.calculateExtremes( self.marketData["dailyData"]) self.fundamentalData = marketData.getFundamentalAnalysisData(self.date)
def account_value(): api = oandapyV20.API(access_token=access_token) r = accounts.AccountDetails(accountID) acc_details = api.request(r) balance = float(acc_details['account']['balance']) margin_available = float(acc_details['account']['marginAvailable']) open_trades = float(acc_details['account']['openTradeCount']) return balance, margin_available, open_trades
def closePosition(trade_id): client_obj = oandapyV20.API(access_token=token) client_request = trades.TradeClose(accountID=accountID, tradeID=trade_id) try: rv = client_obj.request(client_request) except V20Error as err: print("ERROR OCCURED DUE TO : {}".format(err)) else: response = json.dumps(rv, indent=2) return response
def statement_indication(ACCESS_TOKEN, ACCOUNT_ID): e = 0 while e != 1: client = oandapyV20.API(access_token=ACCESS_TOKEN) account_statement = accounts.AccountDetails(ACCOUNT_ID) client.request(account_statement) units_available = format( float(account_statement.response["account"]["marginAvailable"]) / float(account_statement.response["account"]["marginRate"]), '.0f') yield units_available time.sleep(1)
def __init__(self, account=None, try_default=True): # initialize config object config = Config() # if not account given, try default config file or die if account is None: try: conf_filename = config.get_filename() account_summary = config.get_from( file=open(conf_filename, "r")) except IOError: raise IOError( "The default config file does not exist.\nPlease run cbt-config.py." ) # else if account given and not try default, try account config file or die elif account is not None and not try_default: try: conf_filename = config.get_filename(account) account_summary = config.get_from( file=open(conf_filename, "r")) except IOError: raise IOError( "The config file '{}' does not exist.\nPlease run cbt-config.py." .format(conf_filename)) # else, try both else: try: conf_filename = config.get_filename(account) account_summary = config.get_from( file=open(conf_filename, "r")) except IOError: pass try: conf_filename = config.get_filename() account_summary = config.get_from( file=open(conf_filename, "r")) except IOError: raise IOError( "No config file associated with the given account was found.\nPlease run cbt-config.py." ) if account is not None: if not account in account_summary.get("accounts"): raise ValueError( "The config file '{}' is corrupt.\nPlease run cbt-config.py." .format(conf_filename)) # initialize API client # TODO: the token is still visible from self.api, use object properties to hide this information self.api = oandapyV20.API( access_token=account_summary.pop("token"), environment=account_summary.pop("environment"), request_params={"timeout": account_summary.pop("timeout")}) # store the rest of the account attributes self.account_summary = account_summary