def test_symmetric_very_not_equal(self): db_balance = Balance({'USD': Money('50', 'USD'), 'BTC': Money('0', 'BTC')}) ledger_balance = Balance({ 'USD': Money('-60', 'USD'), 'BTC': Money('100', 'BTC'), }) auditing.balance_equality(db_balance, ledger_balance).should.equal(False)
def get_system_balances(self, exchanges): system_balance = Balance() for e in exchanges: system_balance += e.exchange_account_db_object( self.trading_db).balance total_fiat = sum([ balance.to("USD") for currency, balance in system_balance.iteritems() if currency not in Money.CRYPTO_CURRENCIES ]) return system_balance, total_fiat
def test_complex_asymmetric_equal(self): db_balance = Balance({ 'USD': Money('50', 'USD'), 'CAD': Money('10000', 'CAD'), 'ETH': Money('0', 'ETH'), 'BTC': Money('0', 'BTC'), }) ledger_balance = Balance({ 'USD': Money('50', 'USD'), 'CAD': Money('10000', 'CAD'), }) auditing.balance_equality(db_balance, ledger_balance).should.equal(True)
def get_balance_resp(self, req): raw_balances = self.resp(req) volume_currency_available = None price_currency_available = None for raw_balance in raw_balances: if raw_balance['currency'] == self.volume_currency: volume_currency_available = Money( raw_balance['available'], self.volume_currency, ) elif raw_balance['currency'] == self.currency: price_currency_available = Money( raw_balance['available'], self.currency, ) if volume_currency_available == None or price_currency_available == None: raise exceptions.ExchangeAPIErrorException( self, 'missing expected balances', ) balance = Balance() balance[self.volume_currency] = volume_currency_available balance[self.currency] = price_currency_available return balance
def get_balance_time_series_from_audits(audits): fiat_balances = [] btc_balances = [] for audit in audits: timestamp = int(Delorean(audit.time_created, "UTC").epoch) * 1000 # load the fiat and btc balances from the audit data data = json.loads(audit.data) try: # Old data format from before Jan 28, 2015 raw_fiat = data['exchange_balance']['fiat_available'] raw_btc = data['exchange_balance']['btc_available'] fiat = Money.loads(raw_fiat).to("USD") btc = Money.loads(raw_btc) except KeyError: # New data format from after Jan 28, 2015 try: balance_data = data['balance_data'] except KeyError: continue # convert to Money objects for currency, balance_str in balance_data.iteritems(): balance_data[currency] = Money.loads(balance_str) balance = Balance(balance_data) fiat = balance.fiat().to('USD') btc = balance['BTC'] fiat_datapoint = [ timestamp, str(fiat.amount), ] fiat_balances.append(fiat_datapoint) btc_datapoint = [ timestamp, str(btc.amount), ] btc_balances.append(btc_datapoint) return fiat_balances, btc_balances
def test_add_balance(self): balance2 = Balance({ 'USD': Money("50", "USD"), 'BTC': Money("2", "BTC") }) new_balance = self.balance + balance2 new_balance['USD'].should.equal(Money("150", "USD")) new_balance['BTC'].should.equal(Money("3", "BTC"))
def get_drift_from_audits(audits): drift_by_currency = Balance() for audit in audits: if 'drift' in audit.data: data = json.loads(audit.data) for currency, str_amount in data['drift'].iteritems(): drift_by_currency += Money.loads(str_amount) return drift_by_currency
def get_balance_resp(self, req): response = self.resp(req) try: btc_balance = Money(response['btc_balance'], 'BTC') cad_balance = Money(response['cad_balance'], 'CAD') except KeyError: raise exceptions.ExchangeAPIFailureException(self, response) data = Balance() data['BTC'] = btc_balance data['CAD'] = cad_balance return data
def get_liabilities_series(db, start_time, end_time): liabilities_series = [] current_time = start_time while current_time <= end_time: debts = assets.get_active_liabilities(db, current_time) debt_balance = sum([d.amount for d in debts], Balance()) liabilities_series.append((current_time, debt_balance)) current_time += datetime.timedelta(days=1) return liabilities_series
def get_db_balances(exchanges): db = session.get_a_trading_db_mysql_session() db_balances = {} db_balances['system'] = Balance() try: for exchange in exchanges: exchange_data = exchange.exchange_account_db_object(db) db_balances[exchange.name] = exchange_data.balance db_balances['system']['USD'] += db_balances[exchange.name].fiat().to('USD') db_balances['system']['BTC'] += db_balances[exchange.name]['BTC'] finally: db.close() return db_balances
def get_wire_fees_in_period_by_currency(db, start, end): wire_fee_results = db\ .query(Transaction._fee_currency, func.sum(Transaction._fee))\ .filter(Transaction.time_created >= start)\ .filter(Transaction.time_created < end)\ .filter(Transaction._fee != None)\ .group_by(Transaction._fee_currency)\ .all() wire_fees = Balance() for fee_currency, fee_amount in wire_fee_results: wire_fees[fee_currency] = Money(fee_amount, fee_currency) return wire_fees
def balance_responses(exchanges, balance_requests): """ This function uses environment variables to set a minimum balances for an exchange. Format:{{exchange.name}}_MINIMUM_USD Examples: BITSTAMP_MINIMUM_USD, CAVIRTEX_MINIMUM_BTC """ balances = {} balances['system'] = Balance() for exchange in exchanges: req = balance_requests.pop(0) balances[exchange.name] = exchange.get_balance_resp(req) balances['system']['USD'] += balances[exchange.name].fiat().to('USD') balances['system']['BTC'] += balances[exchange.name]['BTC'] return balances
def get_balance_resp(self, req): response, headers = self.resp(req) balance = Balance() try: for account in response: if account['currency'] == 'BTC': balance['BTC'] = Money(account['available'], 'BTC') elif account['currency'] == self.currency: balance[self.currency] = Money(account['available'], self.currency) except KeyError: raise exceptions.ExchangeAPIErrorException(self, 'malformed response') return balance
class TestBalance(unittest.TestCase): def setUp(self): self.balance = Balance({ 'USD': Money("100", "USD"), 'BTC': Money("1", "BTC") }) def tearDown(self): pass def test_empty(self): balance = Balance() balance['BTC'].should.equal(Money("0", "BTC")) def test_add_balance(self): balance2 = Balance({ 'USD': Money("50", "USD"), 'BTC': Money("2", "BTC") }) new_balance = self.balance + balance2 new_balance['USD'].should.equal(Money("150", "USD")) new_balance['BTC'].should.equal(Money("3", "BTC")) def test_add_money(self): new_balance = self.balance + Money("0.2", "BTC") new_balance['USD'].should.equal(Money("100", "USD")) new_balance['BTC'].should.equal(Money("1.2", "BTC")) def test_negate(self): neg = -self.balance neg['USD'].should.equal(Money("-100", "USD")) neg['BTC'].should.equal(Money("-1", "BTC")) def test_fiat(self): fiat = self.balance.fiat() fiat.should.equal(Money("100", "USD")) def test_add_result_mutability(self): m = Money(2, 'BTC') new_balance = self.balance + m # => USD 100, BTC 3 new_balance['USD'].should.equal(Money("100", "USD")) self.balance['USD'].amount += 10 # USD 110 # Changing self.balance shouldn't affect new_balance new_balance['USD'].should.equal(Money("100", "USD"))
def balance_resp(self, req): response = self.resp(req) try: balances = response['info']['funds'] btc_available = Money(balances['free']['btc'], 'BTC') usd_available = Money(balances['free']['usd'], 'USD') except KeyError: raise exceptions.ExchangeAPIErrorException( self, 'Balance missing expected keys', ) balance = Balance() balance['BTC'] = btc_available balance['USD'] = usd_available return balance
def get_balance_resp(self, req): response = self.resp(req) balance = Balance() try: vol_currency_key = '%s_available' % self.volume_currency.lower() price_currency_key = '%s_available' % self.currency.lower() balance[self.volume_currency] = Money( response[vol_currency_key], self.volume_currency, ) balance[self.currency] = Money(response[price_currency_key], self.currency) except KeyError: raise exceptions.ExchangeAPIErrorException( self, 'Balance missing expected keys', ) return balance
def balance_resp(self, req): raw_balances = self.resp(req) btc_available = None usd_available = None for raw_balance in raw_balances: if raw_balance['type'] == 'exchange': if raw_balance['currency'] == 'btc': btc_available = Money(raw_balance['available'], 'BTC') elif raw_balance['currency'] == 'usd': usd_available = Money(raw_balance['available'], 'USD') if btc_available == None or usd_available == None: raise exceptions.ExchangeAPIErrorException( self, 'missing expected balances', ) balance = Balance() balance['BTC'] = btc_available balance['USD'] = usd_available return balance
def get_balance_resp(self, req): response = self.resp(req) total_balance = Balance() # We only want to load the balances for the pair we trade on this account # (BTC + self.currency). For example we have a small USD balance in our main # EUR Kraken account which we want to ignore. Including it in the balance breaks # some other parts of our system which expect to only find a single fiat # currency. supported_currencies = ['BTC', self.currency] for currency in supported_currencies: kraken_currency = self.convert_to_kraken_currency(currency) balance_amount = Decimal(response[kraken_currency]['balance']) credit_amount = Decimal(response[kraken_currency].get('credit_used', 0)) balance = Money(balance_amount, currency) credit = Money(credit_amount, currency) total_balance += (balance - credit) return total_balance
def get_balance_resp(self, req): response = self.resp(req) raw_balances = response['balances'] btc_available = None usd_available = None for raw_balance in raw_balances: if raw_balance['currency'] == 'XBT': btc_available = Money(raw_balance['availableBalance'], 'BTC') elif raw_balance['currency'] == 'USD': usd_available = Money(raw_balance['availableBalance'], 'USD') if btc_available is None or usd_available is None: raise exceptions.ExchangeAPIErrorException( self, 'missing expected balances', ) balance = Balance() balance['BTC'] = btc_available balance['USD'] = usd_available return balance
def test_trivial(self): db_balance = Balance() ledger_balance = Balance() auditing.balance_equality(db_balance, ledger_balance).should.equal(True)
def test_empty(self): balance = Balance() balance['BTC'].should.equal(Money("0", "BTC"))
def setUp(self): self.balance = Balance({ 'USD': Money("100", "USD"), 'BTC': Money("1", "BTC") })
def test_symmetric_equal(self): db_balance = Balance({'USD': Money('50', 'USD'), 'BTC': Money('0', 'BTC')}) ledger_balance = Balance({'USD': Money('50', 'USD'), 'BTC': Money('0', 'BTC')}) auditing.balance_equality(db_balance, ledger_balance).should.equal(True)