def update_account(): if not is_directory_locked(): create_lock_file() if (static.live_trading): client = oandapyV20.API(static.token, environment='live') else: client = oandapyV20.API(static.token, environment='practice') # update short account response = accounts.AccountDetails(static.short_account_id) try: rv = client.request(response) file = open(static.filepath+"account-short.txt","w") file.write(str(rv["account"]["balance"])+","+ str(rv["account"]["openTradeCount"])+","+ str(rv["account"]["marginAvailable"])+","+ str(rv["account"]["marginUsed"])+","+ str(rv["account"]["pl"]) ) file.close() except V20Error as err: print("V20Error occurred: {}".format(err)) # update long account response = accounts.AccountDetails(static.long_account_id) try: rv = client.request(response) file = open(static.filepath+"account-long.txt","w") file.write(str(rv["account"]["balance"])+","+ str(rv["account"]["openTradeCount"])+","+ str(rv["account"]["marginAvailable"])+","+ str(rv["account"]["marginUsed"])+","+ str(rv["account"]["pl"]) ) file.close() print("UPDATE ACCOUNT: Success") except V20Error as err: print("V20Error occurred: {}".format(err)) delete_lock_file() return
def account_balance(): client = oandapyV20.API(access_token=access_token) r = accounts.AccountDetails(accountID) client.request(r) resp = r.response nav = int(resp['account']['NAV']) return nav
def ordersize(self): pip_per_100000 = self.pipconvert() request = accounts.AccountDetails(accountID=self.accountID) accountInfo = self.client.request(request) balance = accountInfo['account']['balance'] if self.params['instrument'].find("JPY") != -1: if self.params['orderType'] == 'long': orderSize = ((float(balance) * self.params['stake']) / ( (abs(self.params['price'] - self.params['stopLoss']) * 100) * pip_per_100000)) * 100000 if self.params['orderType'] == 'short': orderSize = ((float(balance) * (-self.params['stake'])) / ( (abs(self.params['price'] - self.params['stopLoss']) * 100) * pip_per_100000)) * 100000 sizeFix = round(orderSize / 1000) * 1000 return sizeFix else: if self.params['orderType'] == 'long': orderSize = ((float(balance) * self.params['stake']) / ( (abs(self.params['price'] - self.params['stopLoss']) * 10000) * pip_per_100000)) * 100000 if self.params['orderType'] == 'short': orderSize = ((float(balance) * (-self.params['stake'])) / ( (abs(self.params['price'] - self.params['stopLoss']) * 10000) * pip_per_100000)) * 100000 sizeFix = round(orderSize / 1000) * 1000 return sizeFix
def statement_unstructured_info(access_token, account_id): # Returns complete account info as dict client = oandapyV20.API(access_token = ACCESS_TOKEN) account_statement = accounts.AccountDetails(ACCOUNT_ID) client.request(account_statement) info_unstructured = account_statement.response return info_unstructured
def CURRENTLY_OWNED(instrument): req = account.AccountDetails(accountID=ACCOUNT_ID) details = api.request(req)['account'] for position in details['positions']: if position['instrument'] == instrument: return True return False
def get_positions_for_all_instruments(self): ''' Get current positions for all assets Long positions are positive Short positions are negative ''' for symbol in self.instruments: self.position[symbol] = 0.0 r = accounts.AccountDetails(accountID=self.accountID) df = pd.DataFrame(self.api.request(r)) print('Net Positions:') for e_position in df['account']['positions']: self.position[e_position['instrument']] = int( e_position['long']['units']) + int( e_position['short']['units']) if self.position[e_position['instrument']] != 0: print('{}: {}'.format(e_position['instrument'], self.position[e_position['instrument']])) print("--------------------------------------")
def _get_status(self): try: account_details = accounts.AccountDetails(self._account_id) self._api_client.request(account_details) self.connection_status = True except V20Error: self.connection_status = False
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 account_details(self): r = accounts.AccountDetails(ACCOUNT_ID) rv = api.request(r) details = rv.get('account') return details
def fetch_account_details(oanda_api=oanda_api, oanda_account=oanda_account): # Fetch Account Details client = oandapyV20.API(access_token=oanda_api) r = accounts.AccountDetails(oanda_account) client.request(r) return r.response
def get_positions(): """ @return: list of positiions """ r = accounts.AccountDetails(account_id) client = API(access_token=access_token) rv = client.request(r) return rv.get('account').get('positions')
def get_nav(self): try: req_acct = accounts.AccountDetails(self.account_id) self.client.request(req_acct) resp_acct = req_acct.response return float(resp_acct['account']['NAV']) except Exception as err: print('Fail to get Oanda NAV: ' + str(err))
def test__account_details(self, mock_req): """get the details of specified account.""" tid = "_v3_account_by_accountID" resp, data = fetchTestData(responses, tid) r = accounts.AccountDetails(accountID=accountID) mock_req.register_uri('GET', "{}/{}".format(api.api_url, r), text=json.dumps(resp)) result = api.request(r) self.assertTrue(result == resp)
def getBalance(): """ Gets the account balance :return: A float that represents the amount of money in the account """ r = accounts.AccountDetails(accountID) api.request(r) balance = r.response["account"]["balance"] balance = float(balance) return balance
def get_account_info(): """ @return: account details """ r = accounts.AccountDetails(account_id) client = API(access_token=access_token) rv = client.request(r) details = rv.get('account') # return details.get('openTradeCount') return details
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 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 account_summary(self): if not self.connection_status: return [] account_endpoint = accounts.AccountDetails(self._account_id) self._api_client.request(account_endpoint) account_data = account_endpoint.response nav = account_data["account"]["NAV"] balance = account_data["account"]["balance"] currency = account_data["account"]["currency"] summary = AccountSummary(nav=nav, balance=balance, currency=currency) return summary
def _api_get_account(self, account_id: str = None) -> Account: endpoint = accounts.AccountDetails(account_id) # TODO: try catch connection error here self._client.request(endpoint) raw_account = endpoint.response["account"] account_type = AccountType.MARGIN \ if float(raw_account["marginRate"]) > 0 \ else AccountType.CASH self.account = Account(currency=raw_account["currency"], balance=raw_account["balance"], account_type=account_type, margin=float(raw_account["marginRate"]))
def oanda_acc_summary(): """Requests the account details from oanda""" account_details = accounts.AccountDetails(accountID) client.request(account_details) account_data = account_details.response nav = account_data["account"]["NAV"] balance = account_data["account"]["balance"] currency = account_data["account"]["currency"] account_details = [["NAV", nav], ["Balance", balance], ["Currency", currency]] return account_details
def connect(self): try: self.account_id = self.set_obj.get_account_num() self.token = self.set_obj.get_account_token() para = {'timeout': 30} self.client = oandapyV20.API(access_token=self.token, environment='live', request_params=para) #practice, live req_acct = accounts.AccountDetails(self.account_id) self.client.request(req_acct) #get account info print(self.broker_name + self.ccy + ' ' + 'connection succeeded...') except Exception as error: print(self.broker_name + self.ccy + ' ' + 'connection failed: ' + str(error)) time.sleep(5) self.connect()
def lots(self): r = accounts.AccountDetails(uniVar.accountID) client = API(access_token=uniVar.key) rv = client.request(r) self.details = rv.get('account') balance = self.details.get('NAV') size = 0 #different calculations based on trade type if self.enterLong() == True: size = abs( int((float(balance) * float(uniVar.risk)) / (self.currentClose - self.support))) elif self.enterShort() == True: size = abs( int((float(balance) * float(uniVar.risk)) / (self.currentClose - self.resistance))) return size
def __init__(self, init_invest=1000): file = open("access.txt", "r+") self.access_token = '82957cd1a8234cf899f729284c094d27-e31e01c267351992774813f5e64c8b43' #file.readline() self.accountID = "101-004-12401398-001" #file.readline() print(self.accountID) print(self.access_token) file.close() self.init_invest = init_invest #initial balance self.client = oandapyV20.API(access_token=self.access_token) self.r = accounts.AccountDetails( self.accountID) #requests (about out account) params = {"instruments": "EUR_USD", "timeout": "5"} self.pc = pricing.PricingStream(self.accountID, params) #stream of prices self.order_type = 'market' self.tickcounter = 0 #self.init_balance_diff = 0 #self.cur_step = None self.stock_owned = None self.balance = None #== position value self.bid_close = None self.ask_close = None self.bid_close_p1 = None self.ask_close_p1 = None # action space self.action_space = spaces.Discrete(3) # observation space: give estimates in order to sample and build scaler balance_range = np.array((-init_invest * 2, init_invest * 2)) stock_range = np.array((0, init_invest * 2 // 1.5)) #stock owned bid_range = np.array((0, 1.5)) ask_range = np.array((0, 1.5)) ask_p1_range = ask_range bid_p1_range = bid_range self.observation_space = spaces.Box( low=np.array((balance_range[0], stock_range[0], bid_range[0], ask_range[0], ask_p1_range[0], bid_p1_range[0])), high=np.array((balance_range[1], stock_range[1], bid_range[1], ask_range[1], ask_p1_range[1], bid_p1_range[1]))) self._reset()
def get_position_for_instrument(self): r = accounts.AccountDetails(accountID=self.accountID) df = pd.DataFrame(self.api.request(r)) print("--------------------------------------") print('Net Positions:') for e_position in df['account']['positions']: if e_position['instrument'] == self.symbol: self.net_position = int(e_position['long']['units'])+int(e_position['short']['units']) self.unrealizedPL = e_position['unrealizedPL'] print('Net position: {}'.format(self.net_position), "P&L: {}".format(self.unrealizedPL)) print("--------------------------------------")
def inTrade(): """ Gets whether the bot is currently in a trade so it doesnt double order :return: A boolean representing if the bot is in a trade """ r = accounts.AccountDetails(accountID) try: api.request(r) currentPosition = int(r.response["account"]["openPositionCount"]) if currentPosition == 0: # If open position count is 0 the bot is not in a trade return False else: return True except ConnectionError as e: write("\n\nConnection Exception in inTrade()") write(e) return oldTrade except: write("\n\nUnknown Error in inTrade()") return oldTrade
def get_account_value(self): ''' Get current account value, P&L, and margin information ''' r = accounts.AccountDetails(accountID=self.accountID) self.NAV = pd.DataFrame(self.api.request(r))['account']['NAV'] self.unrealizedPL = pd.DataFrame( self.api.request(r))['account']['unrealizedPL'] self.positionValue = pd.DataFrame( self.api.request(r))['account']['positionValue'] self.marginUsed = pd.DataFrame( self.api.request(r))['account']['marginUsed'] self.marginAvailable = pd.DataFrame( self.api.request(r))['account']['marginAvailable'] print('Account Values:') print('NAV: ', self.NAV) print('Unrealized P&L: ', self.unrealizedPL) print('Position Value: ', self.positionValue) print('Margin Used: ', self.marginUsed) print('Marging Available', self.marginAvailable) print("--------------------------------------") '''
def get_user_account_details(account_id, account_token, debug=False): if debug: account_id, client = use_our_token() else: client = account_token try: r = accounts.AccountDetails(account_id) client.request(r) # print(r.response) user_balance = r.response['account']['balance'] print(f'user balance = {user_balance}') return r.response except V20Error as ex: error_msg = ex.msg.split('"errorMessage":')[1].split(',')[0] print(f"Error : {error_msg}") return error_msg
import pandas as pd import oandapyV20 import oandapyV20.endpoints.accounts as accounts import configparser # get account details config = configparser.ConfigParser() config.read('./config/config.ini') accountID = config['oanda']['account_id'] access_token = config['oanda']['api_key'] 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)
def getAccountDetails(self): return self.client.request(accounts.AccountDetails(accountID=self.account_id))
import oandapyV20.endpoints.accounts as accounts import oandapyV20.endpoints.instruments as instruments import oandapyV20.endpoints.trades as trades import oandapyV20.endpoints.orders as orders import configparser import time import os # Global Oanda Account Setup config = configparser.ConfigParser() config.read('C:\\Users\\Khari\\Documents\\Algo\\Resources\\config\\config.ini') accTOKEN = config['oanda']['api_key'] accID = config['oanda']['account_id'] api = API(accTOKEN) client = oandapyV20.API(accTOKEN) a = accounts.AccountDetails(accID) """ So rather than calling the network everytime you want to make a calculation on something. maybe you have it call once at the beginning. So get currencybars will be updated at the start of each iteration. But for other data such as pricing. to make it more organize you will make a funciton called "get_currency_data" which will return the raw ouptut from the network. Then make "parse_data" to sort through that data throughout the logic of the program. Do the samething with your account data. """ #Get Data from oanda. def get_currency_bars(ticker, granularity, numBars=1): """ returns a dataframe object that has the specified currency's Current price,Open,High,Low,Close Values