Skip to main content

dex.blue API wrapper for python

Project description

dex.blue python API wrapper

This is the official Python API wrapper for communicating with the dex.blue API.

For further information head to the API Documentation

Installation

Install via pip

pip install dexblue-api-python

Introduction

dex.blue is a trustless, non-custodial exchange. This means, that every input which moves funds needs to by signed with your private key.

You either have to sign orders directly from your wallet address or use a Delegated Signing Key.

For the most straightforward integration, which does not require you to directly interact with the blockchain, you can just use our webinterface for deposits & withdrawals and register a Delegated Signing Key in the settings ⚙ section.

If you want to handle deposits and withdrawals from your bot, please check out this page of our documentation.

Initializing a connection

Tha connection can be initialized with different parameters.

import dexblue

db = dexblue.WsAPI( # all parameters are optional
    # authenticate either an account...
    account=<ETHEREUM PRIVATE KEY>,
    # ...or a delegate
    delegate=<DEXBLUE DELEGATE KEY>,
    # optional parameters
    endpoint=<DEXBLUE WEBSOCKET ENDPOINT>, # default: wss://api.dex.blue/ws
    web3Provider=<ETHEREUM WEB3 RPC ENDPOINT>, # default: https://mainnet.infura.io/
    network=<ETHEREUM NETWORK>, # default: mainnet
    autoAuth=<AUTHENTICATE WHEN CONNECTION OPENS> # default: True
)

def callback(packet):
    # your logic here

db.on('wsOpen', callback)

It is possible to load a encrypted key to authenticate your connection

key = dexblue.utils.readPrivateKeyFromFile(keyfile, password)

db = dexblue.WsAPI(delegate=key)

Calling a method

This Library provides a wrapper function for every method offered by the dex.blue API, which can be invoked with eg: db.methods.getOrderBookSnapshot(parameters, callback, <callback arguments>...).

For a full list of the available methods and parameters, please refer to the websocket API documentation.

Additionally the library offers some helper functions to deal with all of the hard and annoying stuff like hashing and signing:

  • db.authenticate(privKey) - called automatically, when you pass an account to the constructor
  • db.authenticateDelegate(privKey) - Called automatically, when you pass an delegate to the constructor
  • db.placeOrder(order, callback) - This function abstracts all the stress of contructing and signing orders away from you. Very recommended to use this!
  • db.hashOrder(order) returns hash - This function helps you hashing the order inputs correctly. You then need to sign the order by yourself.

Events

You can subscribe to any server and websocket events using the following functions:

Events:

  • Market Events:
    • book20d5 ... book20d1 Orderbook with a depth of 20 with 5 ... 1 decimal precision (for the rate)
    • book100d5 ... book100d1 Orderbook with a depth of 10 with 5 ... 1 decimal precision (for the rate)
    • bookd5 ... bookd1 Full orderbook with 5 ... 1 decimal precision (for the rate)
    • trades Trades Feed of the market
    • ticker The ticker of the market
  • Other Events:
    • rate subscribe to a ETH to fiat conversion rate e.g. ETHUSD, available are ETH traded against the config.conversion_currencies. (sub with: {markets:["ETHUSD"],events:["rate"]})
    • chainStats subscribe to the servers block height and gas price (sub with: {markets:["ethereum"],events:["chainStats"]})
  • Websocket Events (no need to subscribe, just listen)
    • wsOpen websocket connection is opened
    • message every received message
    • wsError websocket errored
    • wsClose websocket conn is closed

Subscribing to events

db.methods.subscribe({
    "markets" : ["ETHDAI", "MKRETH"],
    "events"  : ["trades", "book20d5"]
})

db.on('trade', print)
db.on('book', print)

Callback

A callback must have at least one paramater which is the received data. The following arguments are passed through from the callback definition.

def callback(packet, parameter1, parameter2, ...):
    print(packet, parameter1, parameter2)

db.on('listed', callback, "parameter1", "parameter2")

The packet parameter is a dict, which has the following structure

{
    "chan": <CHANNEL>, # The channel id is documented in the dex.blue api docs
    <EVENT NAME>: <PARSED PACKET>,
    "packet": <UNPARSED PACKET> # the same packet which the server sent
}

Placing an order

def callback(packet):
    # If you passed an account of delegate to the constructor, you will authenticated automatically
    # All private commands should be sent after we are successfully authenticated
    # If no expiry is passed, a default expiry of one month will be applied

    # This function supports either very abstracted input
    db.placeOrder({
        "market" : "ETHDAI",
        "amount" : -1,        # positive amount implies buy order, negative sell
        "rate"   : 300
    }, print)

    # But also supports all the granular API parameters
    orderIdentifier = int(time.time()) # client-set order identifier
    db.placeOrder({
        "cid"         : orderIdentifier,
        "sellToken"   : "0x0000000000000000000000000000000000000000",  # ETH
        "sellAmount"  : "1000000000000000000",                         # 1 ETH
        "buyToken"    : "0x89d24a6b4ccb1b6faa2625fe562bdd9a23260359",  # DAI
        "buyAmount"   : "300000000000000000000",                       # 300 DAI
        "expiry"      : int(time.time() + 86400 * 2),     # order is valid 2 days (different from the timeInForce parameter)
        "hidden"      : False,
        "postOnly"    : True,     # order is either maker or canceled
        "rebateToken" : "buy",    # we want to receive our rebate in DAI (the token we buy)
        # ... more possibilities are listed here: https://docs.dex.blue/websocket/#placeorder
    }, print)

db.on('auth', callback)

Error handling

def reconnect_cb(packet):
    print('Reconnect in: ' + str(packet["reconnect"]["timeout"]) + 's. Message: ' + packet["reconnect"]["message"])

db.on('reconnect', reconnect_cb) # server sent a reconnect instruction

db.on('error', print) # handle error (probably resulting in a disconnect)

db.on('wsClose', print) # handle disconnect

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

dexblue-api-python-0.1.0b4.tar.gz (15.8 kB view details)

Uploaded Source

Built Distribution

dexblue_api_python-0.1.0b4-py3-none-any.whl (14.1 kB view details)

Uploaded Python 3

File details

Details for the file dexblue-api-python-0.1.0b4.tar.gz.

File metadata

  • Download URL: dexblue-api-python-0.1.0b4.tar.gz
  • Upload date:
  • Size: 15.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.1.1 pkginfo/1.5.0.1 requests/2.23.0 setuptools/45.2.0 requests-toolbelt/0.9.1 tqdm/4.40.2 CPython/3.8.1

File hashes

Hashes for dexblue-api-python-0.1.0b4.tar.gz
Algorithm Hash digest
SHA256 16fd647ccd055424eff19654a968b4221ac02fb3bcfd031af8f2c5d5d8b65127
MD5 06065c9589e5e540e84450cf6e9fc175
BLAKE2b-256 48a05edd69a316cc2c18efc956d9615933b55cbad23af84efdb907fdbf41775e

See more details on using hashes here.

File details

Details for the file dexblue_api_python-0.1.0b4-py3-none-any.whl.

File metadata

  • Download URL: dexblue_api_python-0.1.0b4-py3-none-any.whl
  • Upload date:
  • Size: 14.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.1.1 pkginfo/1.5.0.1 requests/2.23.0 setuptools/45.2.0 requests-toolbelt/0.9.1 tqdm/4.40.2 CPython/3.8.1

File hashes

Hashes for dexblue_api_python-0.1.0b4-py3-none-any.whl
Algorithm Hash digest
SHA256 f6d6105802313977d4f31dc7b245156e73d3b7d0569c9328c62337dcaea16a71
MD5 a9d8ff597480a85c08fcbd64695067df
BLAKE2b-256 2e0c8f4d8c0695c45e3edeed2430748ebf5b40ff368d247efc8bc2f4d59665e1

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page