Skip to content

Commit

Permalink
Using Binance.py to get account information (whittlem#167)
Browse files Browse the repository at this point in the history
  • Loading branch information
edrickrenan authored May 13, 2021
1 parent 85a69bb commit 41194f5
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 96 deletions.
47 changes: 14 additions & 33 deletions models/Binance.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
from models.CoinbasePro import FREQUENCY_EQUIVALENTS, SUPPORTED_GRANULARITY
import sys
import math, re
import numpy as np
import pandas as pd
Expand Down Expand Up @@ -76,39 +75,21 @@ def handle_init_error(self, err: str) -> None:
def getClient(self) -> Client:
return self.client

def getAccounts(self) -> pd.DataFrame:
"""Retrieves your list of accounts"""
accounts = self.client.get_account()

if 'balances' not in accounts:
return pd.DataFrame(columns=[ 'index', 'id', 'currency', 'balance', 'hold', 'available', 'profile_id', 'trading_enabled' ])

df = pd.DataFrame(self.client.get_account()['balances'])
df.columns = [ 'currency', 'available', 'hold' ]
df['index'] = df.index
df['id'] = df.index
df['balance'] = df['available']
df['profile_id'] = ''
df['trading_enabled'] = True

return df[[ 'index', 'id', 'currency', 'balance', 'hold', 'available', 'profile_id', 'trading_enabled' ]]

def getAccount(self, account: int) -> pd.DataFrame:
def getAccount(self):
"""Retrieves a specific account"""
accounts = self.client.get_account()

if 'balances' not in accounts:
return pd.DataFrame(columns=[ 'index', 'id', 'currency', 'balance', 'hold', 'available', 'profile_id', 'trading_enabled' ])

df = pd.DataFrame(self.client.get_account()['balances'])
df.columns = [ 'currency', 'available', 'hold' ]
df['index'] = df.index
df['id'] = df.index
df['balance'] = df['available']
df['profile_id'] = ''
df['trading_enabled'] = True

return df[df['id'] == account][[ 'index', 'id', 'currency', 'balance', 'hold', 'available', 'profile_id', 'trading_enabled' ]]
account = self.client.get_account()
if 'balances' in account:
df = pd.DataFrame(account['balances'])
df = df[(df['free'] != '0.00000000') & (df['free'] != '0.00')]
df['free'] = df['free'].astype(float)
df['locked'] = df['locked'].astype(float)
df['balance'] = df['free'] - df['locked']
df.columns = ['currency', 'available', 'hold', 'balance']
df = df[['currency', 'balance', 'hold', 'available']]
df = df.reset_index(drop=True)
return df
else:
return 0.0

def getFees(self, market: str='') -> pd.DataFrame:
if market != '':
Expand Down
34 changes: 14 additions & 20 deletions models/TradingAccount.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
"""Live or test trading account"""

import sys
import re
import requests

import numpy as np
import pandas as pd
import json, math, re, requests, sys
from datetime import datetime
from binance.client import Client
from models.Binance import AuthAPI as BAuthAPI, PublicAPI as BPublicAPI
from models.CoinbasePro import AuthAPI as CBAuthAPI, PublicAPI as CBPublicAPI

from models.Binance import AuthAPI as BAuthAPI, PublicAPI as BPublicAPI, AuthAPI
from models.CoinbasePro import AuthAPI as CBAuthAPI


class TradingAccount():
def __init__(self, app=None):
Expand Down Expand Up @@ -127,17 +129,9 @@ def getBalance(self, currency=''):

if self.app.getExchange() == 'binance':
if self.mode == 'live':
resp = self.client.get_account()
if 'balances' in resp:
df = pd.DataFrame(resp['balances'])
df = df[(df['free'] != '0.00000000') & (df['free'] != '0.00')]
df['free'] = df['free'].astype(float)
df['locked'] = df['locked'].astype(float)
df['balance'] = df['free'] - df['locked']
df.columns = [ 'currency', 'available', 'hold', 'balance' ]
df = df[[ 'currency', 'balance', 'hold', 'available' ]]
df = df.reset_index(drop=True)

model = AuthAPI(self.app.getAPIKey(), self.app.getAPISecret())
df = model.getAccount()
if isinstance(df, pd.DataFrame):
if currency == '':
# retrieve all balances
return df
Expand All @@ -149,7 +143,7 @@ def getBalance(self, currency=''):
return 0.0
else:
# return balance of specified currency (if positive)
if currency in ['EUR','GBP','USD']:
if currency in ['EUR', 'GBP', 'USD']:
return float(self.app.truncate(float(df[df['currency'] == currency]['available'].values[0]), 2))
else:
return float(self.app.truncate(float(df[df['currency'] == currency]['available'].values[0]), 4))
Expand All @@ -170,8 +164,8 @@ def getBalance(self, currency=''):
else:
self.balance = self.balance.replace('BASE', currency)

if self.balance.currency[self.balance.currency.isin([currency])].empty == True:
self.balance.loc[len(self.balance)] = [currency,0,0,0]
if self.balance.currency[self.balance.currency.isin([currency])].empty:
self.balance.loc[len(self.balance)] = [currency, 0, 0, 0]

# retrieve balance of specified currency
df = self.balance
Expand All @@ -182,7 +176,7 @@ def getBalance(self, currency=''):
return 0.0
else:
# return balance of specified currency (if positive)
if currency in ['EUR','GBP','USD']:
if currency in ['EUR', 'GBP', 'USD']:
return float(self.app.truncate(float(df[df['currency'] == currency]['available'].values[0]), 2))
else:
return float(self.app.truncate(float(df[df['currency'] == currency]['available'].values[0]), 4))
Expand Down
45 changes: 2 additions & 43 deletions tests/test_Model_Binance.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,38 +65,6 @@ def test_config_json_exists_and_valid():
api_secret = config['binance']['api_secret']
api_url = config['binance']['api_url']
AuthAPI(api_key, api_secret, api_url)
pass

def test_getAccounts():
filename = 'config.json'

with open(filename) as config_file:
config = json.load(config_file)

api_key = ''
api_secret = ''
api_url = ''
if 'api_key' in config and 'api_secret' in config and 'api_pass' in config and 'api_url' in config:
api_key = config['api_key']
api_secret = config['api_secret']
api_url = config['api_url']
AuthAPI(api_key, api_secret, api_url)
elif 'api_key' in config['binance'] and 'api_secret' in config['binance'] and 'api_url' in config['binance']:
api_key = config['binance']['api_key']
api_secret = config['binance']['api_secret']
api_url = config['binance']['api_url']
AuthAPI(api_key, api_secret, api_url)

exchange = AuthAPI(api_key, api_secret, api_url)
assert type(exchange) is AuthAPI

df = exchange.getAccounts()
assert type(df) is pandas.core.frame.DataFrame

actual = df.columns.to_list()
expected = [ 'index', 'id', 'currency', 'balance', 'hold', 'available', 'profile_id', 'trading_enabled' ]
assert len(actual) == len(expected)
assert all([a == b for a, b in zip(actual, expected)])

def test_getAccount():
filename = 'config.json'
Expand All @@ -121,20 +89,11 @@ def test_getAccount():
exchange = AuthAPI(api_key, api_secret, api_url)
assert type(exchange) is AuthAPI

df = exchange.getAccounts()

account = df.head(1)['id'].values[0]
assert account >= 0

df = exchange.getAccount(account)
df = exchange.getAccount()
assert type(df) is pandas.core.frame.DataFrame

assert len(df) == 1

df.drop(['index'], axis=1, inplace=True)

actual = df.columns.to_list()
expected = [ 'id', 'currency', 'balance', 'hold', 'available', 'profile_id', 'trading_enabled' ]
expected = ['currency', 'balance', 'hold', 'available']
assert len(actual) == len(expected)
assert all([a == b for a, b in zip(actual, expected)])

Expand Down

0 comments on commit 41194f5

Please sign in to comment.