Curated List of Bitcoin Python Libraries

Let’s explore some python libraries in active development for the bitcoin market. This blog post provides a list of some interesting python packages which can be used for getting cryptocurrency pricing, interacting with crypto exchanges and wallets, crypto trading bot and market data feeders.

Cryptocurrency Pricing

Following packages can be used for getting cryptocurrency pricing in real-time.

BitcoinAverage

It is one of the longest running Cryptocurrency API providers. The API can be used to get real-time price, volume and historical price data for following currencies as per its website:  Bitcoin (BTC), Bitcoin Cash (BCH), Litecoin (LTC), Ethereum (ETH), Ripple (XRP), Monero (XMR), Dash (DASH) and many more. 

Install with:

pip install bitcoinaverage

Minimal example from documentation:

# HTTP example
from bitcoinaverage import RestfulClient

if __name__ == '__main__':
    public_key = 'your_public_key'

    restful_client = RestfulClient(public_key)

    ticker_global_per_symbol = restful_client.ticker_global_per_symbol('BTCUSD')
    print('Global Ticker for BTCUSD:')
    print(ticker_global_per_symbol)

More details: bitcoinaverage 路 PyPI

Cryptocompare

To get any latest crypto currency price and conversion to other currencies, cryptocompare can be used. Supports both WebSockets and Rest API.

Install with:

pip install cryptocompsdk

Minimal example from documentation:

import cryptocompsdk

from cryptocompsdk import CryptoCompare
API_KEY = 'my-api-key'
cc = CryptoCompare(API_KEY)

data = cc.history.get(from_symbol='BTC', to_symbol='USD', exchange='Kraken')
df = data.to_df()

More details: cryptocompsdk – PyPI

Forex Python

Mostly for bitcoin. Bitcoin pricing, currency conversion and foreign exchange rates. You can get bitcoin price for all currencies and  get historical prices.

Install with:

pip install forex-python

Minimal example from documentation:

>>> from forex_python.converter import CurrencyRates
>>> c = CurrencyRates()
>>> c.get_rates('USD')   # you can directly call get_rates('USD')
{u'IDR': 13625.0, u'BGN': 1.7433, u'ILS': 3.8794, u'GBP': 0.68641, u'DKK': 6.6289, u'CAD': 1.3106, u'JPY': 110.36, u'HUF': 282.36, u'RON': 4.0162, u'MYR': 4.081, u'SEK': 8.3419, u'SGD': 1.3815, u'HKD': 7.7673, u'AUD': 1.3833, u'CHF': 0.99144, u'KRW': 1187.3, u'CNY': 6.5475, u'TRY': 2.9839, u'HRK': 6.6731, u'NZD': 1.4777, u'THB': 35.73, u'EUR': 0.89135, u'NOK': 8.3212, u'RUB': 66.774, u'INR': 67.473, u'MXN': 18.41, u'CZK': 24.089, u'BRL': 3.5473, u'PLN': 3.94, u'PHP': 46.775, u'ZAR': 15.747}

More details: forex-python 路 PyPI

Interacting with Crypto Exchanges

To interact with crypto exchanges for buying and selling cryptocurrencies and digital assets. Though there are multiple exchanges available, only widely used are covered here with good support for python.

Python Binance

It provides interfaces to interact with binance exchange to buy or sell cryptocurrencies like Bitcoin, Ethereum, Binance coin, Dogecoin etc. You can also design your own trading bot using the python binance wrapper. 

Install with:

pip install python-binance

Minimal example from documentation:

from binance import Client, ThreadedWebsocketManager, ThreadedDepthCacheManager
client = Client(api_key, api_secret)

# get market depth
depth = client.get_order_book(symbol='BNBBTC')

# place a test market buy order, to place an actual order use the create_order function
order = client.create_test_order(
    symbol='BNBBTC',
    side=Client.SIDE_BUY,
    type=Client.ORDER_TYPE_MARKET,
    quantity=100)

# get all symbol prices
prices = client.get_all_tickers()

# withdraw 100 ETH
# check docs for assumptions around withdrawals
from binance.exceptions import BinanceAPIException
try:
    result = client.withdraw(
        asset='ETH',
        address='<eth_address>',
        amount=100)
except BinanceAPIException as e:
    print(e)
else:
    print("Success")

# fetch list of withdrawals
withdraws = client.get_withdraw_history()

# fetch list of ETH withdrawals
eth_withdraws = client.get_withdraw_history(coin='ETH')

# get a deposit address for BTC
address = client.get_deposit_address(coin='BTC')

# get historical kline data from any date range

# fetch 1 minute klines for the last day up until now
klines = client.get_historical_klines("BNBBTC", Client.KLINE_INTERVAL_1MINUTE, "1 day ago UTC")

# fetch 30 minute klines for the last month of 2017
klines = client.get_historical_klines("ETHBTC", Client.KLINE_INTERVAL_30MINUTE, "1 Dec, 2017", "1 Jan, 2018")

# fetch weekly klines since it listed
klines = client.get_historical_klines("NEOBTC", Client.KLINE_INTERVAL_1WEEK, "1 Jan, 2017")

# socket manager using threads
twm = ThreadedWebsocketManager()
twm.start()

# depth cache manager using threads
dcm = ThreadedDepthCacheManager()
dcm.start()

def handle_socket_message(msg):
    print(f"message type: {msg['e']}")
    print(msg)

def handle_dcm_message(depth_cache):
    print(f"symbol {depth_cache.symbol}")
    print("top 5 bids")
    print(depth_cache.get_bids()[:5])
    print("top 5 asks")
    print(depth_cache.get_asks()[:5])
    print("last update time {}".format(depth_cache.update_time))

twm.start_kline_socket(callback=handle_socket_message, symbol='BNBBTC')

dcm.start_depth_cache(callback=handle_dcm_message, symbol='ETHBTC')

# replace with a current options symbol
options_symbol = 'BTC-210430-36000-C'
dcm.start_options_depth_cache(callback=handle_dcm_message, symbol=options_symbol)

# join the threaded managers to the main thread
twm.join()
dcm.join()

More details : python-binance 路 PyPI

Bitfinex

Bitfinex supports both cryptocurrency (Bitcoin, Litecoin. Ethereum)  and fiat currencies. To interact with bitfinex using the python bitfinex library.

Install with:

pip install bitfinex-v2

Minimal example from documentation:

from bitfinex import WssClient, ClientV2, ClientV1

def my_handler(message):
  # Here you can do stuff with the messages
  print(message)

my_client = WssClient()
my_client.subscribe_to_ticker(
    symbol="BTCUSD",
    callback=my_handler
)
my_client.start()

More details:

CoinBase

Another widely used crypto exchange for trading cryptocurrencies mostly for Bitcoin and Ethereum.

Install with:

pip install pycoinbase

Minimal example from documentation:

from coinbase.wallet.client import Client
client = Client(api_key, api_secret)

# Get supported native currencies
client.get_currencies()

# Get exchange rates
client.get_exchange_rates()

# Buy price
client.get_buy_price(currency_pair = 'BTC-USD')

# Sell price
client.get_sell_price(currency_pair = 'BTC-USD')

# Spot price
client.get_spot_price(currency_pair = 'BTC-USD')

# Current server time
client.get_time()

More details:

Open source Algorithmic Crypto Trading

If you are looking for an open source algorithmic trading bot then below libraries are widely used to design bots.

CCXT

Stands for CryptoCurrency eXchange Trading Library. This library has an advantage that it can connect to multiple crypto exchanges worldwide for trading and bot design. Widely used by coders, tech savvy traders and data scientists. Apart from python it also supports javascript and PHP.

Install with:

pip install ccxt

Minimal example from documentation:

import ccxt

hitbtc   = ccxt.hitbtc({'verbose': True})
bitmex   = ccxt.bitmex()
huobipro = ccxt.huobipro()
exmo     = ccxt.exmo({
    'apiKey': 'YOUR_PUBLIC_API_KEY',
    'secret': 'YOUR_SECRET_PRIVATE_KEY',
})
kraken = ccxt.kraken({
    'apiKey': 'YOUR_PUBLIC_API_KEY',
    'secret': 'YOUR_SECRET_PRIVATE_KEY',
})

exchange_id = 'binance'
exchange_class = getattr(ccxt, exchange_id)
exchange = exchange_class({
    'apiKey': 'YOUR_API_KEY',
    'secret': 'YOUR_SECRET',
})

hitbtc_markets = hitbtc.load_markets()

print(hitbtc.id, hitbtc_markets)
print(bitmex.id, bitmex.load_markets())
print(huobipro.id, huobipro.load_markets())

print(hitbtc.fetch_order_book(hitbtc.symbols[0]))
print(bitmex.fetch_ticker('BTC/USD'))
print(huobipro.fetch_trades('LTC/USDT'))

print(exmo.fetch_balance())

# sell one 喔 for market price and receive $ right now
print(exmo.id, exmo.create_market_sell_order('BTC/USD', 1))

# limit buy BTC/EUR, you pay 鈧2500 and receive 喔1  when the order is closed
print(exmo.id, exmo.create_limit_buy_order('BTC/EUR', 1, 2500.00))

# pass/redefine custom exchange-specific order params: type, amount, price, flags, etc...
kraken.create_market_buy_order('BTC/USD', 1, {'trading_agreement': 'agree'})

More details: ccxt

Freqtrade

It is an open source algorithmic trading software written in python for cryptocurrency trading. It needs special configuration for each exchange that it needs to connect to. Currently Binance, Bittrex, FTX and Kraken exchanges are supported. It鈥檚 better to know some python coding before doing trading with this library.

More details: Freqtrade

Crypto Wallets

Crypto wallets are used to store cryptocurrencies so that you can use them for trading. The cryptocurrency exchanges like Binance, Coinbase, Bitfinex have an online crypto wallet support which is part of the exchange, for which you can use the above python libraries mentioned here. However, there are software crypto wallets for which there is python support available. Here are some widely used software wallet python packages:

Electrum

It is one of the most well known software wallets and is one of the oldest known wallets since 2011. Being open source anyone can audit the source code. Even though not beginner friendly, it has good security features like 2FA, multi signature support. 

To interact with electrum, one can install electrum which is written in python or use merchant wallet API’s.

Install with:

pip install merchant-wallet

Minimal example on how to accept Bitcoin on your own website—taken from the documentation (see link below):

from merchant_wallet.backends.btc import BitcoinBackend
      
      
btc = BitcoinBackend('master_public_key_gotten_from_an_offline_wallet')
    
btc.generate_new_address(index=0) #index=0 will give the first address displayed on your electrum wallet, increase index to get more addresses as displayed on your wallet
      
btc.confirm_address_payment(address="1Ge6rDuyCdYVGhXZjcK4251q67GXMKx6xK", total_crypto_amount=0.01, confirmation_number=3      ) #Confirm payment on the address with the specified confirmation and amount it will return a tuple of transaction status and value of transaction
      
#Returned values
#Unconfirmed payment -> (UNCONFIRMED_ADDRESS_BALANCE, transaction_hash)
#Confirmed payment -> (CONFIRMED_ADDRESS_BALANCE, sent_value)
#Underpaid payment -> (UNDERPAID_ADDRESS_BALANCE, remaining value)
#No transaction -> (NO_HASH_ADDRESS_BALANCE, None )
btc.confirm_address_payment(address="1Ge6rDuyCdYVGhXZjcK4251q67GXMKx6xK", total_crypto_amount=0.01, confirmation_number=5000, tx_hash='hash_returned_when_transaction_was_unconfirmed')

More details: spesmilo/electrum: Electrum Bitcoin Wallet and merchant-wallet 0.1.1

Block.io

A newly added wallet as a service for Bitcoin, Dogecoin and Litecoin. It also supports multi signatures for more security. Block.io does not charge any fees, but you need to pay network fees (e.g. Bitcoin).

Install with:

pip install block-io

Minimal example from documentation:

from block_io import BlockIo

block_io = BlockIo('API KEY', 'SECRET PIN', API_VERSION)

# print the account balance
print block_io.get_balance()

# print all addresses on this account
print block_io.get_my_addresses()

More details: block-io 路 PyPI

Market data feed handlers

There are some crypto data feed handlers to provide cryptocurrency spot prices and derivatives. One important python library supporting such data feeds is cryptofeed.

Cryptofeed

This handles multi cryptocurrency and multiple exchanges. The data feed can be used to store in a database (e.g. Redis, MongoDB) as cryptofeed provides callback API support to directly write to these databases. It supports historical and real time data and much more. It has both REST and Websocket feeds. 

Install with:

pip install cryptofeed

Minimal example from documentation:

from cryptofeed import FeedHandler
# not all imports shown for clarity

fh = FeedHandler()

# ticker, trade, and book are user defined functions that
# will be called when ticker, trade and book updates are received
ticker_cb = {TICKER: TickerCallback(ticker)}
trade_cb = {TRADES: TradeCallback(trade)}
gemini_cb = {TRADES: TradeCallback(trade), L2_BOOK: BookCallback(book)}


fh.add_feed(Coinbase(symbols=['BTC-USD'], channels=[TICKER], callbacks=ticker_cb))
fh.add_feed(Bitfinex(symbols=['BTC-USD'], channels=[TICKER], callbacks=ticker_cb))
fh.add_feed(Poloniex(symbols=['BTC-USDT'], channels=[TRADES], callbacks=trade_cb))
fh.add_feed(Gemini(symbols=['BTC-USD', 'ETH-USD'], channels=[TRADES, L2_BOOK], callbacks=gemini_cb))

fh.run()

More details: cryptofeed 路 PyPI

Conclusion

In this blog we have seen some important python libraries that are up to date and also are updated whenever there is change in the API’s of exchanges or wallet interfaces. As there are many exchanges and wallets it is not possible to cover each and every python package. Happy exploring!