def GET_ACCOUNT_SUMMARY(): try: req = account.AccountSummary(accountID=ACCOUNT_ID) summary = api.request(req) except Exception as e: print("Got %s error %s, retrying" % (type(e).__name__, e)) time.sleep(10) req = account.AccountSummary(accountID=ACCOUNT_ID) summary = api.request(req) return summary
def get_account_info(api: API): """ Get information about your account """ r = accounts.AccountSummary(accountID) return api.request(r)
def test__get_account_summary(self, accID, status_code, fail=None, **kwargs): """get the summary of specified account.""" tid = "_v3_account_by_accountID_summary" resp, data = fetchTestData(responses, tid) if not accID: # hack to use the global accountID accID = accountID r = accounts.AccountSummary(accountID=accID) text = fail if not fail: text = json.dumps(resp) kwargs['mock'].register_uri('GET', "{}/{}".format(api.api_url, r), text=text, status_code=status_code) if fail: # The test should raise an exception with code == fail oErr = None with self.assertRaises(V20Error) as oErr: result = api.request(r) self.assertTrue(fail in "{}".format(oErr.exception)) else: result = api.request(r) self.assertTrue(result["account"]["id"] == accountID and result["account"]["currency"] == account_cur)
def balance(self): r = accounts.AccountSummary(self.accountID) self.client.request(r) balance = float(r.response['account']['balance']) balance_available = balance - float( r.response['account']['positionValue']) return balance_available, balance
def oanda_balance(self): request = accounts.AccountSummary (self.oanda_account_id) #, params=params) rv = self.oanda.request(request) rv = rv['account']['marginAvailable'] # this accounts for open positions whereas 'balance' is total (nav) result = {} result['Available'] = float(rv) result['Total'] = float(rv) return result
def summary(self): req = accounts.AccountSummary(accountID=self.account_id) try: res = self.client.request(req) except V20Error as e: logger.error('in balance() ... {e}', e) return None return res
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 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 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 account_summary_request(accountID: str = account) -> Union[pd.DataFrame, bool]: """Request Oanda account summary. Parameters ---------- accountID : str, optional Oanda account ID, by default cfg.OANDA_ACCOUNT Returns ------- Union[pd.DataFrame, bool] Account summary data or False """ if accountID == "REPLACE_ME": print("Error: Oanda account credentials are required.") return False try: request = accounts.AccountSummary(accountID=accountID) response = client.request(request) df_summary = pd.DataFrame( [ {"Type": "Balance", "Value": response["account"]["balance"]}, {"Type": "NAV", "Value": response["account"]["NAV"]}, { "Type": "Unrealized P/L", "Value": response["account"]["unrealizedPL"], }, {"Type": "Total P/L", "Value": response["account"]["pl"]}, { "Type": "Open Trade Count", "Value": response["account"]["openTradeCount"], }, { "Type": "Margin Available", "Value": response["account"]["marginAvailable"], }, {"Type": "Margin Used", "Value": response["account"]["marginUsed"]}, { "Type": "Margin Closeout", "Value": response["account"]["marginCloseoutNAV"], }, { "Type": "Margin Closeout Percent", "Value": response["account"]["marginCloseoutPercent"], }, { "Type": "Margin Closeout Position Value", "Value": response["account"]["marginCloseoutPositionValue"], }, ] ) return df_summary except V20Error as e: d_error = json.loads(e.msg) print(d_error["errorMessage"], "\n") return False
def get_balance(self) -> Balance: req = accounts.AccountSummary(self.account_id) try: resp = self.client.request(req) except V20Error as e: logger.error(f"action=get_balance error={e}") raise available = float(resp["account"]["balance"]) currency = resp["account"]["currency"] return Balance(available=available, currency=currency)
def get_info(self): try: r = v20accounts.AccountSummary(self.account_id) resp = RUNNING_ENV.api.request(r) except V20Error as err: logging.error(r.status_code, err) else: logging.info(json.dumps(resp['account'], indent=2)) self.account_info = resp['account'] return self.account_info
def get_balance(self) -> Balance: req = accounts.AccountSummary(accountID=self.account_id) try: resp = self.client.request(req) except V20Error as e: logger.error(f'action=get_balance error={e}') raise available = float(resp['account']['balance']) currency = resp['account']['currency'] return Balance(currency, available)
def get_balance(self): r = accounts.AccountSummary(accountID=self.account_id) try: res = self.client.request(r) except V20Error as e: logger.error(f'get_balance_error:{e}') raise balance = float(res['account']['balance']) currency = res['account']['currency'] return Balance(currency, balance)
def GetMarginLevel(): ret = 0 try: req = accounts.AccountSummary(accountID=account_id) res = api.request(req) marginAvailable = float(res["account"]["marginAvailable"]) marginUsed = float(res["account"]["marginUsed"]) ret = 50 * marginUsed / marginAvailable except Exception as e: print(e) return ret
def get_acct_balance(account_ID: str) -> float: """ Retrieve account balance. Args: accountID (String): account ID Returns: Float: current account balance """ resp = client.request(accounts.AccountSummary(account_ID)) return float(resp["account"]["balance"])
def getBalance(self): try: req = accounts.AccountSummary(accountID=self.account_id) response = self.oanda.request(req) balance = int(float(response["account"]["balance"])) return balance except: raise
def get_account_info(self): try: account = accounts.AccountSummary(self.oanda_account_id) response = self.api.request(account) print('get_account_inforesponse', json.dumps(response, indent=2)) except requests.exceptions.ConnectionError as e_HTTP: print(response.text) print(e_HTTP) except Exception as e: print(e) raise OandaApiError(e)
def get_account_summary(accountID, other_args: List[str]): parser = argparse.ArgumentParser( add_help=False, prog="summary", description="Print some information about your account.", ) ns_parser = parse_known_args_and_warn(parser, other_args) if not ns_parser: return try: request = accounts.AccountSummary(accountID=accountID) response = client.request(request) df_summary = pd.DataFrame( [ {"Type": "Balance", "Value": response["account"]["balance"]}, {"Type": "NAV", "Value": response["account"]["NAV"]}, { "Type": "Unrealized P/L", "Value": response["account"]["unrealizedPL"], }, {"Type": "Total P/L", "Value": response["account"]["pl"]}, { "Type": "Open Trade Count", "Value": response["account"]["openTradeCount"], }, { "Type": "Margin Available", "Value": response["account"]["marginAvailable"], }, {"Type": "Margin Used", "Value": response["account"]["marginUsed"]}, { "Type": "Margin Closeout", "Value": response["account"]["marginCloseoutNAV"], }, { "Type": "Margin Closeout Percent", "Value": response["account"]["marginCloseoutPercent"], }, { "Type": "Margin Closeout Position Value", "Value": response["account"]["marginCloseoutPositionValue"], }, ] ) print(df_summary.to_string(index=False, header=False)) print("") except V20Error as e: d_error = eval(e.msg) print(d_error["errorMessage"], "\n")
def get_account_info(): i = 0 while i <= 10: try: accountSummary = accounts.AccountSummary(accountID=ACCOUNT_ID) summary = oanda.request(accountSummary) return summary['account'] except oandapyV20.exceptions.V20Error as err: if err.code == 429: continue else: print("It f****d bro")
class Account: conn = Connection.getInstance() accountID = conn.config['ACCOUNT_ID'] r = accounts.AccountSummary(accountID) data = conn.API.request(r)['account'] def __init__(self): self.id = self.data['id'] self.balance = self.data['balance'] self.nav = self.data['NAV'] self.margin = self.data['marginAvailable'] self.positions = self.data['openPositionCount']
def get_balance(trade_account): try: oanda = oandapyV20.API(environment=trade_account["env"], access_token=trade_account["accessToken"]) req = accounts.AccountSummary(accountID=trade_account["accountId"]) response = oanda.request(req) balance = int(float(response["account"]["balance"])) return balance except: raise
def updateAccountInfo(self): # get information about oanda account r = accounts.AccountSummary(accountID=self.accountID) try: data = self.client.request(r) self.balance = data['account']['balance'] self.trade_count = data['account']['openTradeCount'] self.last_transaction_ID = data['account']['lastTransactionID'] except V20Error as e: logger.error("V20Error: %s", e)
def get_account_info(): result = None while result is None: r = accounts.AccountSummary(account_id) try: client.request(r) except oandapyV20.exceptions.V20Error as e: log.warning(e) if r.response is not None: result = r.response.get("account", None) if result is not None: result['unrealizedPL'] = float(result['unrealizedPL']) result['pl'] = float(result['pl']) return result
def oanda_collateral(): api = API(access_token=token) r = accounts.AccountSummary(accountID) while True: try: rv = api.request(r) pprint(rv) balance = rv['account']['balance'] spendable_collateral = float(rv['account']['withdrawalLimit']) pprint('現在の口座残高は{}円です。'.format(round(int(float(balance))))) pprint("新規注文に利用可能な証拠金の額は{}円です".format( round(int(spendable_collateral)))) return int(spendable_collateral) except V20Error as e: pprint("OANDAのAPIでの口座残高取得に失敗しました : " + str(e)) break
def account_summary(self): import time import oandapyV20.endpoints.accounts as accounts t = time.gmtime() date_time = f"{t[0]}/{t[1]}/{t[2]} - {t[3]}:{t[4]}:{t[5]}" r_a = accounts.AccountSummary(accountID=self.accountID) self.client.request(r_a) a_i = r_a.response self.account_info = {"Date & Time": date_time, "Balance": a_i['account']['balance'], "Unrealized P/L": a_i['account']['unrealizedPL'], "Financing": a_i['account']['financing'], "Margin Used": a_i['account']['marginCallPercent'], "Open Positions": a_i['account']['openPositionCount']} self.account_info_for_db = [el for el in self.account_info.values()]
def calculate_maximum_unit(account_id, account_token, unit, debug=False): if debug: account_id, client = use_our_token() else: client = account_token try: r1 = accounts.AccountSummary(account_id) client.request(r1) base_currency = unit[:3] home_currency = r1.response['account']['currency'] base_home = f"{base_currency}_{home_currency}" margin_ratio = float(r1.response['account']['marginRate'][:4]) margin_avaliable = float(r1.response['account']['marginAvailable']) if base_currency != 'USD': r2 = pricing.PricingInfo(accountID=account_id, params={"instruments": base_home}) client.request(r2) current_price = float(r2.response['prices'][0]['asks'][0]['price']) else: current_price = 1 maximum_unit = (margin_avaliable * pow(margin_ratio, -1)) / current_price return int(maximum_unit) except V20Error as ex: error_msg = ex.msg.split('"errorMessage":')[1].split(',')[0].replace( '}', '') print(f"Error : {error_msg}") return error_msg
def thread_func(async_handle): try: 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 # result = r.response['account']['currency'] result = 'JKblah' # get the price using an http request to iextrading.com # url = "https://api.iextrading.com/1.0/stock/%s/batch?types=quote" % symbol # data = urllib2.urlopen(url).read() # if sys.version_info[0] > 2: # data = data.decode() # # # the returned data is in json format # result = json.loads(data)["quote"].get("latestPrice", "#NoLatestPrice") except Exception, e: result = e
def position_sizer(self): client = self.api r = accounts.AccountSummary(self.accountID) client.request(r) balance = r.response['account']['balance'] PnL = r.response['account']['unrealizedPL'] estBalance = float(balance) + float(PnL) size = posSize(estBalance, self.perRisk, self.pipRisk, self.recentClose) units = size * 1000 units = round(units) return units
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)