How to determine bitcoin wallet transaction direction (withdraw vs deposit)

How to determine bitcoin wallet transaction direction (withdraw vs deposit)

I'm trying to programmatically process the transactions of my bitcoin wallet and to calculate my wallet balance, I need a solution in python, currently I'm using the blockchain.info, but if you know a better API you are welcome. I don't want to run a bitcoin node locally, I'd like something easy to use, like querying a service online.

My goal is to be able to filter transactions by date, e.g. specifying transactions from January, 1st 2017 until December, 31st, 2017. I don't need the actual balance, that one is easy to get.

To see all my wallet transactions I use the extended public key. In Electrum this can be seen in Wallet > Information > Master Public Key.

I'm able to loop through all the transactions, fetch the timestamp that I need to filter the transactions in my wished time range, but I don't understand how can I determine the direction (money spend aka withdrawn vs money received aka deposit) of a transaction.

Here some python code I wrote you could try (first run pip install blockchain):

import datetime
from blockchain import blockexplorer


def get_btc(amount_satoshi):
    btc_satoshi = 100000000
    return amount_satoshi / btc_satoshi


xpub = 'paste the master public key copied from electrum'
wallet = blockexplorer.get_xpub(xpub)
print(f'Actual balance: {get_btc(wallet.final_balance)}')

balance = 0
transactions = reversed(wallet.transactions)
index = 0
for trx in transactions:
    timestamp = trx.time
    date = datetime.datetime.fromtimestamp(timestamp)
    print(f'{date}')

    if index == 0:
        # The first transaction must be a deposit to initialize a wallet, thus the output is what is coming in (deposit)
        for o in trx.outputs:
            print(f'Initial deposit: {o.address}, {get_btc(o.value)}')
    else:
        for i in trx.inputs:
            print(f'Input: {i.address}, {get_btc(i.value)}')
        for o in trx.outputs:
            print(f'Output: {o.address}, {get_btc(o.value)}')

    index += 1

I thought I could add all my addresses (that I can see in Electrum > Addresses tag) to a hashset called my_addresses, the problem is that I can't find a method to return my addresses... if I can get a list of all my addresses based on my xpub I could determine if the output is one of them it means it's a deposit, if the input is one of them it means it's a withdrawal.

Somebody asked how to retrieve the addresses of a wallet: Find all used addresses using xpub key but the answer is outdated: btc.blockr.io now redirects to coinbase.

If you can't answer with some code, you are welcome to share the logic and I'll code the algorithm myself.

https://ift.tt/2D5xfOp

Comments

Popular posts from this blog

Bitcoin Core errors with database block

Bitfinex & Market Synergy To Offer Institutional Calibre Cryptocurrency Connectivity