Search code examples
python-3.xfor-loopcoinbase-apitermux

How to define FOR loop in python


Please I need help here. In the code below, I want the FOR loop to loop through all the accounts with the associated API KEYs and SECRETs listed and send bitcoins from them to the recipient email address one after the other as long as their balance is greater than zero:

    #!/data/data/com.termux/files/usr/bin/python3.8

from coinbase.wallet.client import Client
import json

api_key1 = '<key>'
api_secret1 = '<secret>'
api_key2 = '<key>'
api_secret2 = '<secret>'
api_key3 = '<key>'
api_secret3 = '<secret>'
api_key4 = '<key>'
api_secret4 = '<secret>'
api_key5 = '<key>'
api_secret5 = '<secret>'
client = Client(api_key, api_secret)
accounts = client.get_accounts()['data']
for account in accounts:
    sending_currency = account['currency']
    if float(account['balance']['amount']) > 0:
        #Send to other account
        sending_account = client.get_account(account['id'])
        sending_amount = account['balance']['amount']
        print('sending %s %s from SENDER_EMAIL_ADDRESS' %(sending_amount, sending_currency))
        sending_account.send_money(to = 'RECEPIENT_EMAIL_ADDRESS', amount = sending_amount, currency = sending_currency)

Solution

  • In order to attain what you have described, I would use a list of dictionaries, this will also be iterable and hence usable in the for loop. in order to do this I'd rewrite your code as such :

    #!/data/data/com.termux/files/usr/bin/python3.8
    
    from coinbase.wallet.client import Client
    import json
    credentials = [
    {'api_key':'<key1>', 'api_secret':'<secret1>'},
    {'api_key':'<key2>', 'api_secret':'<secret2>'},
    {'api_key':'<key3>', 'api_secret':'<secret3>'}
    ........
    ]
    while True:
        for credential in credentials:
            client = Client(credential['api_key'], credential['api_secret'])
            accounts = client.get_accounts()['data']
            for account in accounts:
                sending_currency = account['currency']
                if float(account['balance']['amount']) > 0:
                     #Send to other account
                     sending_account = client.get_account(account['id'])
                     sending_amount = account['balance']['amount']
                     print('sending %s %s from SENDER_EMAIL_ADDRESS' %(sending_amount, sending_currency))
                     sending_account.send_money(to = 'RECEPIENT_EMAIL_ADDRESS', amount = sending_amount, currency = sending_currency)
                else:
                    ........