from configparser import ConfigParser except: from ConfigParser import ConfigParser import sys sys.path.append('.') from bitreserve import Bitreserve locale.setlocale(locale.LC_ALL, 'en_US') Config = ConfigParser() Config.read('samples/config.ini') api = Bitreserve() api.auth( Config.get('Settings','username'), Config.get('Settings','password') ) print("Getting user data...") me = api.get_me() print("First name: {}".format(me['firstName'])) print("Last name: {}".format(me['lastName'])) print("\nGetting cards...") cards = api.get_cards() for card in cards: print(card['label'] + ": " + card["available"] + " (" + card["id"] + ")") print("\nGetting USD Card...") usd_card = api.get_card("20c0ccf3-e316-40c1-8a2a-982dd92a96ca") print(usd_card['label']) print("\nGetting contacts...") contacts = api.get_contacts() for contact in contacts:
class Broker(object): """ Represents the broker that handles our portfolio """ def __init__(self, config_file, currencies, base_currency, DEBUG=False): """ Create the Broker object :param String config_file The path to a config file that ConfigParser can read and that has a "Broker" section. """ self.version = 0 config = ConfigParser.ConfigParser() config.read(config_file) self.api = Bitreserve() self.api.auth_pat(config.get('Broker', 'pat')) self.currencies = currencies self.base_currency = base_currency self.DEBUG = DEBUG self.pp = pprint.PrettyPrinter() def get_tickers(self): """ Get the tickers for the currencies in the configuration (paired with the base_currency) :rtype: A dictionary of currency tickers with 3 fields: ask, bid, pair """ tickers = self.api.get_ticker() relevant_pairs = {} for currency in self.currencies: relevant_pairs[currency + self.base_currency] = { 'currency': currency, 'direction': 'direct' } relevant_pairs[self.base_currency + currency] = { 'currency': currency, 'direction': 'reverse', 'direct': currency + self.base_currency } my_tickers = {} for ticker in tickers: if ticker['pair'] in relevant_pairs: if relevant_pairs[ticker['pair']]['direction'] == 'direct': new_ticker = { 'pair': ticker['pair'], 'ask': float(ticker['ask']), 'bid': float(ticker['bid']), } my_tickers[relevant_pairs[ticker['pair']] ['currency']] = new_ticker elif relevant_pairs[ticker['pair']]['direction'] == 'reverse': new_ticker = { 'pair': relevant_pairs[ticker['pair']]['direct'], 'ask': 1.0 / float(ticker['bid']), 'bid': 1.0 / float(ticker['ask']), } my_tickers[relevant_pairs[ticker['pair']] ['currency']] = new_ticker return my_tickers def get_portfolio(self): """ Get all of my assets, from my cards :rtype: A dictionary with the following structure: { 'BTC': { 'amount': 0.0543, # ammont in BTC 'value': 13.88, # value in base_currency 'rate': 255.70500, # conversion rate 'base_currency': 'USD' }, 'TOTAL': { 'value': 13.88, # total value in base_currency 'base_currency': 'USD' } } """ my_portfolio = {} all_of_me = self.api.get_me() if self.DEBUG: print "Broker: Balances I got:" self.pp.pprint(all_of_me['balances']) total_balance = { 'value': float(all_of_me['balances']['total']), 'base_currency': all_of_me['settings']['currency'], } my_portfolio['TOTAL'] = total_balance for currency in all_of_me['balances']['currencies']: if currency not in self.currencies: continue balance = { 'amount': float( all_of_me['balances']['currencies'][currency]['balance']), 'value': float(all_of_me['balances']['currencies'][currency]['amount']), 'rate': float(all_of_me['balances']['currencies'][currency]['rate']), 'base_currency': all_of_me['balances']['currencies'][currency]['currency'], } if balance['base_currency'] != my_portfolio['TOTAL'][ 'base_currency']: print "Broker: Warning: suspicious base_currency in balance for " + currency my_portfolio[currency] = balance return my_portfolio def run_transactions(self, transactions): """ Get a list of transactions and run them on bitreserve. :param List transactions A list of transactions of the form: [{'base_currency': 'USD', 'destination': u'BTC', 'origin': u'USD', 'amount': 0.21}, {'base_currency': 'USD', 'destination': u'BTC', 'origin': u'GBP', 'amount': 0.17}, {'base_currency': 'USD', 'destination': u'BTC', 'origin': u'CNY', 'amount': 0.13}] """ # Get cards addresses my_cards = self.api.get_cards() addresses = {} for card in my_cards: addresses[card['currency']] = card['address']['bitcoin'] # Run through the transacctions and prepare them for trans in transactions: txn_id = self.api.prepare_txn(addresses[trans['origin']], addresses[trans['destination']], trans['amount'], trans['base_currency']) if txn_id: txn_result = self.api.execute_txn( addresses[trans['origin']], txn_id, 'Money Maker automatic transaction') if self.DEBUG: print 'Result:' self.pp.pprint(txn_result) else: print "Broker: Something went wrong with the following transaction:" self.pp.pprint(trans) return
class Broker(object): """ Represents the broker that handles our portfolio """ def __init__( self, config_file, currencies, base_currency, DEBUG=False ): """ Create the Broker object :param String config_file The path to a config file that ConfigParser can read and that has a "Broker" section. """ self.version = 0 config = ConfigParser.ConfigParser() config.read( config_file ) self.api = Bitreserve() self.api.auth_pat( config.get( 'Broker', 'pat' ) ) self.currencies = currencies self.base_currency = base_currency self.DEBUG = DEBUG self.pp = pprint.PrettyPrinter() def get_tickers( self ): """ Get the tickers for the currencies in the configuration (paired with the base_currency) :rtype: A dictionary of currency tickers with 3 fields: ask, bid, pair """ tickers = self.api.get_ticker() relevant_pairs = {} for currency in self.currencies: relevant_pairs[ currency + self.base_currency ] = { 'currency': currency, 'direction': 'direct' } relevant_pairs[ self.base_currency + currency ] = { 'currency': currency, 'direction': 'reverse', 'direct': currency + self.base_currency } my_tickers = {} for ticker in tickers: if ticker[ 'pair' ] in relevant_pairs: if relevant_pairs[ ticker[ 'pair' ] ][ 'direction'] == 'direct': new_ticker = { 'pair': ticker[ 'pair' ], 'ask': float(ticker['ask']), 'bid': float(ticker['bid']), } my_tickers[ relevant_pairs[ ticker[ 'pair' ] ][ 'currency'] ] = new_ticker elif relevant_pairs[ ticker[ 'pair' ] ][ 'direction'] == 'reverse': new_ticker = { 'pair': relevant_pairs[ ticker[ 'pair' ] ][ 'direct' ], 'ask': 1.0 / float(ticker['bid']), 'bid': 1.0 / float(ticker['ask']), } my_tickers[ relevant_pairs[ ticker[ 'pair' ] ][ 'currency'] ] = new_ticker return my_tickers def get_portfolio( self ): """ Get all of my assets, from my cards :rtype: A dictionary with the following structure: { 'BTC': { 'amount': 0.0543, # ammont in BTC 'value': 13.88, # value in base_currency 'rate': 255.70500, # conversion rate 'base_currency': 'USD' }, 'TOTAL': { 'value': 13.88, # total value in base_currency 'base_currency': 'USD' } } """ my_portfolio = {} all_of_me = self.api.get_me() if self.DEBUG: print "Broker: Balances I got:" self.pp.pprint( all_of_me['balances'] ) total_balance = { 'value': float(all_of_me['balances']['total']), 'base_currency': all_of_me['settings']['currency'], } my_portfolio['TOTAL'] = total_balance for currency in all_of_me['balances']['currencies']: if currency not in self.currencies: continue balance = { 'amount': float(all_of_me['balances']['currencies'][currency]['balance']), 'value': float(all_of_me['balances']['currencies'][currency]['amount']), 'rate': float(all_of_me['balances']['currencies'][currency]['rate']), 'base_currency': all_of_me['balances']['currencies'][currency]['currency'], } if balance['base_currency'] != my_portfolio['TOTAL']['base_currency']: print "Broker: Warning: suspicious base_currency in balance for " + currency my_portfolio[currency] = balance return my_portfolio def run_transactions( self, transactions ): """ Get a list of transactions and run them on bitreserve. :param List transactions A list of transactions of the form: [{'base_currency': 'USD', 'destination': u'BTC', 'origin': u'USD', 'amount': 0.21}, {'base_currency': 'USD', 'destination': u'BTC', 'origin': u'GBP', 'amount': 0.17}, {'base_currency': 'USD', 'destination': u'BTC', 'origin': u'CNY', 'amount': 0.13}] """ # Get cards addresses my_cards = self.api.get_cards() addresses = {} for card in my_cards: addresses[card['currency']] = card['address']['bitcoin'] # Run through the transacctions and prepare them for trans in transactions: txn_id = self.api.prepare_txn( addresses[trans['origin']], addresses[trans['destination']], trans['amount'], trans['base_currency'] ) if txn_id: txn_result = self.api.execute_txn( addresses[trans['origin']], txn_id, 'Money Maker automatic transaction' ) if self.DEBUG: print 'Result:' self.pp.pprint( txn_result ) else: print "Broker: Something went wrong with the following transaction:" self.pp.pprint( trans ) return
class MoneyBot(object): def __init__(self, sandbox=False): self.normalize_weights() if DEBUG: print(self.weights) self.auth(sandbox) def normalize_weights(self): total = 0.0 for value in weights.values(): total += value self.weights = {} for key, value in weights.items(): self.weights[key] = value / total def auth(self, sandbox=False): if sandbox: self.api = Bitreserve(host='api-sandbox.bitreserve.org') else: self.api = Bitreserve() pat = auth.get('pat', None) user = auth.get('user', None) password = auth.get('password', None) if pat: self.api.auth_pat(pat) elif user and password: self.api.auth(user, password) def update_card_information(self): me = self.api.get_me() cards = me['cards'] self.cards = {} for card in cards: if Decimal(card['balance'] ) or card['currency'] in self.weights.keys(): self.cards[card['id']] = { 'id': card['id'], 'currency': card['currency'], 'address': card['addresses'][0]['id'], 'balance': Decimal(card['normalized'][0]['balance']), } self.currency = card['normalized'][0]['currency'] total = reduce(lambda total, card: total + card['balance'], self.cards.values(), Decimal('0.0')) if DEBUG: print('total: {}'.format(total)) for card_id, card in self.cards.items(): target = total * Decimal(self.weights[ card['currency']]) # this assumes 1 card per currency if DEBUG: print('target: {}'.format(target)) self.cards[card_id]['difference'] = target - card['balance'] if DEBUG: print(self.cards) def calculate_next_transaction(self): def difference(card_id): return self.cards[card_id]['difference'] potential_sources = list( filter(lambda cid: difference(cid) <= -MINIMUM_TRANSACTION, self.cards.keys())) potential_destinations = list( filter(lambda cid: difference(cid) >= MINIMUM_TRANSACTION, self.cards.keys())) if not (len(potential_sources) and len(potential_destinations)): return None, None, None potential_sources.sort(key=difference, reverse=True) potential_destinations.sort(key=difference, reverse=True) if self.cards[potential_sources[0]] == self.cards[ potential_destinations[0]]: return None, None, None value = min(abs(self.cards[potential_sources[0]]['difference']), abs(self.cards[potential_destinations[0]]['difference'])) value = "{0:.3f}".format(value) return (self.cards[potential_sources[0]], self.cards[potential_destinations[0]], value) def run(self): self.update_card_information() source, destination, amount = self.calculate_next_transaction() if not source: # print('nothing to do') return print('Transfer {} {} from {} to {}.'.format(amount, self.currency, source['address'], destination['address'])) trans = self.api.prepare_txn(source['id'], destination['address'], amount, self.currency) res = self.api.execute_txn(source['id'], trans) print(res['id'])
class MoneyBot(object): def __init__(self, sandbox=False): self.normalize_weights() if DEBUG: print(self.weights) self.auth(sandbox) def normalize_weights(self): total = 0.0 for value in weights.values(): total += value self.weights = {} for key, value in weights.items(): self.weights[key] = value / total def auth(self, sandbox=False): if sandbox: self.api = Bitreserve(host='api-sandbox.bitreserve.org') else: self.api = Bitreserve() pat = auth.get('pat', None) user = auth.get('user', None) password = auth.get('password', None) if pat: self.api.auth_pat(pat) elif user and password: self.api.auth(user, password) def update_card_information(self): me = self.api.get_me() cards = me['cards'] self.cards = {} for card in cards: if Decimal(card['balance']) or card['currency'] in self.weights.keys(): self.cards[card['id']] = { 'id': card['id'], 'currency': card['currency'], 'address': card['addresses'][0]['id'], 'balance': Decimal(card['normalized'][0]['balance']), } self.currency = card['normalized'][0]['currency'] total = reduce(lambda total, card: total + card['balance'], self.cards.values(), Decimal('0.0')) if DEBUG: print('total: {}'.format(total)) for card_id, card in self.cards.items(): target = total * Decimal(self.weights[card['currency']]) # this assumes 1 card per currency if DEBUG: print('target: {}'.format(target)) self.cards[card_id]['difference'] = target - card['balance'] if DEBUG: print(self.cards) def calculate_next_transaction(self): def difference(card_id): return self.cards[card_id]['difference'] potential_sources = list(filter(lambda cid: difference(cid) <= -MINIMUM_TRANSACTION, self.cards.keys())) potential_destinations = list(filter(lambda cid: difference(cid) >= MINIMUM_TRANSACTION, self.cards.keys())) if not (len(potential_sources) and len(potential_destinations)): return None, None, None potential_sources.sort(key=difference, reverse=True) potential_destinations.sort(key=difference, reverse=True) if self.cards[potential_sources[0]] == self.cards[potential_destinations[0]]: return None, None, None return ( self.cards[potential_sources[0]], self.cards[potential_destinations[0]], min(abs(self.cards[potential_sources[0]]['difference']), abs(self.cards[potential_destinations[0]]['difference'])) ) def run(self): self.update_card_information() source, destination, amount = self.calculate_next_transaction() if not source: print('nothing to do') return print('Transfer {} {} from {} to {}.'.format(amount, self.currency, source['address'], destination['address'])) trans = self.api.prepare_txn(source['id'], destination['address'], amount, self.currency) res = self.api.execute_txn(source['id'], trans) print(res['id'])
class MoneyBot(object): def __init__(self, sandbox=False): self.normalize_weights() if DEBUG: print(self.weights) self.auth(sandbox) def normalize_weights(self): total = 0.0 for value in weights.values(): total += value self.weights = {} for key, value in weights.items(): self.weights[key] = value / total def auth(self, sandbox=False): if sandbox: self.api = Bitreserve(host="api-sandbox.bitreserve.org") else: self.api = Bitreserve() pat = auth.get("pat", None) user = auth.get("user", None) password = auth.get("password", None) if pat: self.api.auth_pat(pat) elif user and password: self.api.auth(user, password) def update_card_information(self): me = self.api.get_me() cards = me["cards"] self.cards = {} for card in cards: if Decimal(card["balance"]) or card["currency"] in self.weights.keys(): self.cards[card["id"]] = { "id": card["id"], "currency": card["currency"], "address": card["addresses"][0]["id"], "balance": Decimal(card["normalized"][0]["balance"]), } self.currency = card["normalized"][0]["currency"] total = reduce(lambda total, card: total + card["balance"], self.cards.values(), Decimal("0.0")) if DEBUG: print("total: {}".format(total)) for card_id, card in self.cards.items(): target = total * Decimal(self.weights[card["currency"]]) # this assumes 1 card per currency if DEBUG: print("target: {}".format(target)) self.cards[card_id]["difference"] = target - card["balance"] if DEBUG: print(self.cards) def calculate_next_transaction(self): def difference(card_id): return self.cards[card_id]["difference"] potential_sources = list(filter(lambda cid: difference(cid) <= -MINIMUM_TRANSACTION, self.cards.keys())) potential_destinations = list(filter(lambda cid: difference(cid) >= MINIMUM_TRANSACTION, self.cards.keys())) if not (len(potential_sources) and len(potential_destinations)): return None, None, None potential_sources.sort(key=difference, reverse=True) potential_destinations.sort(key=difference, reverse=True) if self.cards[potential_sources[0]] == self.cards[potential_destinations[0]]: return None, None, None value = min( abs(self.cards[potential_sources[0]]["difference"]), abs(self.cards[potential_destinations[0]]["difference"]), ) value = "{0:.3f}".format(value) return (self.cards[potential_sources[0]], self.cards[potential_destinations[0]], value) def run(self): self.update_card_information() source, destination, amount = self.calculate_next_transaction() if not source: # print('nothing to do') return print("Transfer {} {} from {} to {}.".format(amount, self.currency, source["address"], destination["address"])) trans = self.api.prepare_txn(source["id"], destination["address"], amount, self.currency) res = self.api.execute_txn(source["id"], trans) print(res["id"])