Package: cryptowatch-sdk
Cryptowatch Python SDKThe Cryptowatch Python library provides a convenient access to theCryptowatch APIfrom applications written in the Python language.It includes the following features:Auto-serialization of API responses into Python objectsWebsocket client with transparent handling of protobuf messagesAPI credentials automatically read from your~/.cw/credentials.ymlconfig fileCustom exceptions for API-specific issues (e.g.: Requests Allowance)Smart back-off retries in case of API connectivity lossInstallationpip install cryptowatch-sdkNote:Thecryptowatchlibraryisnotrelated withCryptowatch. If you installed it by mistake runpip uninstall cryptowatchto remove it.The correct library name iscryptowatch-sdk.ExampleShowing all Kraken markets that already gained at least 5% over the current weekly candle.importcryptowatchascwfromdatetimeimportdatetime,timedelta# Get all Kraken marketskraken=cw.markets.list("kraken")# For each Kraken market...formarketinkraken.markets:# Forge current market ticker, like KRAKEN:BTCUSDticker="{}:{}".format(market.exchange,market.pair).upper()# Request weekly candles for that marketcandles=cw.markets.get(ticker,ohlc=True,periods=["1w"])# Each candle is a list of [close_timestamp, open, high, low, close, volume, volume_quote]# Get close_timestamp, open and close from the most recent weekly candleclose_ts,wkly_open,wkly_close=(candles.of_1w[-1][0],candles.of_1w[-1][1],candles.of_1w[-1][4],)# Compute market performance, skip if open was 0ifwkly_open==0:continueperf=(wkly_open-wkly_close)*100/wkly_open# If the market performance was 5% or more, print itifperf>=5:open_ts=datetime.utcfromtimestamp(close_ts)-timedelta(days=7)print("{}gained{:.2f}% since{}".format(ticker,perf,open_ts))Requirementspython v3.7+requests v0.8.8+marshmallow v3.2.2+pyyaml v5.1.2+websocket-client v0.56+protobuf v3.11.3+API CrendentialUsing a credential file will allow you to authenticate your requests and grant you the API access of your Cryptowatch account.Your account Credits will be consumed for the REST and WebSocket API. Specific Credit cost details can be found on thePricing page.Setup your credential fileGenerate an Cryptowatch API key fromyour accountCreate your credential file on your machine by running in order:2.1mkdir $HOME/.cw2.2echo "apikey: 123" > $HOME/.cw/credentials.yml(where123is your 20 digitspublic key)Verify withcat $HOME/.cw/credentials.ymlthat you see something like below (123being your public key):apikey: 123The SDK will read your public key as soon asimport cryptowatchis ran in your script.UsageREST APIimportcryptowatchascw# Set your API Key, it is by default read from  your ~/.cw/credentials.yml filecw.api_key="123"# Assetscw.assets.list()cw.assets.get("BTC")# Exchangescw.exchanges.list()cw.exchanges.get("KRAKEN")# Instrumentscw.instruments.list()cw.instruments.get("BTCUSD")# Marketscw.markets.list()# Returns list of all markets on all exchangescw.markets.list("BINANCE")# Returns all markets on Binance# Returns market summary (last, high, low, change, volume)cw.markets.get("KRAKEN:BTCUSD")# Return market candlestick info (open, high, low, close, volume) on some timeframescw.markets.get("KRAKEN:BTCUSD",ohlc=True,periods=["4h","1h","1d"])# Returns market last tradescw.markets.get("KRAKEN:BTCUSD",trades=True)# Return market current orderbookcw.markets.get("KRAKEN:BTCUSD",orderbook=True)# Return market current orderbook liquiditycw.markets.get("KRAKEN:BTCUSD",liquidity=True)You can access the raw HTTP response received via the_http_responseattribute which is arequests.Responseobject:importcryptowatchascwbitcoin=cw.assets.get('btc')print(bitcoin._http_response)Websocketimportcryptowatchascw# Set your API Keycw.api_key="123"# Subscribe to resources (https://docs.cryptowat.ch/websocket-api/data-subscriptions#resources)cw.stream.subscriptions=["markets:*:trades"]# What to do on each trade updatedefhandle_trades_update(trade_update):"""trade_update follows Cryptowatch protocol buffer format:https://github.com/cryptowatch/proto/blob/master/public/markets/market.proto"""market_msg=">>> Market#{}Exchange#{}Pair#{}:{}New Trades".format(trade_update.marketUpdate.market.marketId,trade_update.marketUpdate.market.exchangeId,trade_update.marketUpdate.market.currencyPairId,len(trade_update.marketUpdate.tradesUpdate.trades),)print(market_msg)fortradeintrade_update.marketUpdate.tradesUpdate.trades:trade_msg="\tID:{}TIMESTAMP:{}TIMESTAMPNANO:{}PRICE:{}AMOUNT:{}".format(trade.externalId,trade.timestamp,trade.timestampNano,trade.priceStr,trade.amountStr,)print(trade_msg)cw.stream.on_trades_update=handle_trades_update# Start receivingcw.stream.connect()# Call disconnect to close the stream connection# cw.stream.disconnect()Seethis scriptfor more streaming example.Converting protobuf messages to JSONIf you need to convert the protobuf message to JSON, you can do so withMessageToJson. See the example below:fromgoogle.protobuf.json_formatimportMessageToJsonimportcryptowatchascw# Set your API Keycw.api_key="123"# Subscribe to resources (https://docs.cryptowat.ch/websocket-api/data-subscriptions#resources)cw.stream.subscriptions=["markets:*:trades"]# What to do on each trade updatedefhandle_trades_update(trade_update):"""trade_update follows Cryptowatch protocol buffer format:https://github.com/cryptowatch/proto/blob/master/public/markets/market.proto"""MessageToJson(trade_update)cw.stream.on_trades_update=handle_trades_update# Start receivingcw.stream.connect()LoggingLogging can be enabled through Python'sloggingmodule:importlogginglogging.basicConfig()logging.getLogger("cryptowatch").setLevel(logging.DEBUG)CLIThe library exposes a simple utility, namedcryptowatch, to return last market prices.By default it returns Kraken's BTCUSD market> cryptowatch
7425.0Add another Kraken market to return this market last price> cryptowatch btceur
6758.1You can also specify your own exchange> cryptowatch binance:ethbtc
0.020359When the market doesn't exist a return code of1will be set (0otherwise):> cryptowatch binance:nosuchmarketusd
> echo $?
1TestingUnit tests are under thetestsfolder and usepytest, run them all with:make testIntegration tests sending real HTTP requests to the Cryptowatch API can be run with:make test-http-realDevelopmentTesting and developement dependencies are in therequirements.txtfile, install them with:pip install -r requirements.txtThe code base use theBlacklinter, run it with:make lintLicenseBSD-2-Clause