Websocket Class - websocket_client

Classes:

DemexWebsocket(uri, ping_interval, ping_timeout)

DemexWebsocket is a high-level async implementation off the official Tradehub Demex websocket and provides all functionalities described in the documentation.

class tradehub.websocket_client.DemexWebsocket(uri: str, ping_interval: Optional[int] = 10, ping_timeout: Optional[int] = 30)[source]

Bases: object

DemexWebsocket is a high-level async implementation off the official Tradehub Demex websocket and provides all functionalities described in the documentation.

Methods:

connect(on_receive_message_callback[, …])

Connect to websocket server.

disconnect()

Safely close the websocket connection.

get_account_trades(message_id, swth_address)

Request up to 100 account trades.

get_candlesticks(message_id, market, …)

Requests candlesticks for market with granularity.

get_closed_positions(message_id, swth_address)

Request closed positions.

get_leverages(message_id, swth_address[, market])

Request leverages.

get_market_stats(message_id[, market])

Request market stats.

get_open_orders(message_id, swth_address[, …])

Request open orders.

get_open_positions(message_id, swth_address)

Request open positions.

get_order_history(message_id, swth_address)

Request up to 200 order histories.

get_recent_trades(message_id, market)

Request up to 100 recent trades for a market.

open()

Check if the connection is open.

send(data)

Send data to websocket server.

subscribe(message_id, channels)

Subscribe to one or many channels.

subscribe_account_trades(message_id, …[, …])

Subscribe to account trades.

subscribe_balances(message_id, swth_address)

Subscribe to wallet specific balance channel.

subscribe_books(message_id, market)

Subscribe to book channel.

subscribe_candlesticks(message_id, market, …)

Subscribe to candlesticks channel.

subscribe_leverages(message_id, swth_address)

Subscribe to wallet specific leverages channel.

subscribe_market_stats(message_id)

Subscribe to market stats.

subscribe_orders(message_id, swth_address[, …])

Subscribe to orders channel.

subscribe_positions(message_id, swth_address)

Subscribe to positions channel.

subscribe_recent_trades(message_id, market)

Subscribe to recent trades.

unsubscribe(message_id, channels)

Unsubscribe to one or many channels.

async connect(on_receive_message_callback: Callable, on_connect_callback: Optional[Callable] = None, on_error_callback: Optional[Callable] = None)[source]

Connect to websocket server.

Warning

Callbacks need to be NON-BLOCKING! Otherwise the PING-PONG coroutine is blocked and the server will close the connection. You will not receive any notification about this.

Parameters
  • on_receive_message_callback – async callback which is called with the received message as dict.

  • on_connect_callback – async callback which is called if websocket is connected.

  • on_error_callback – async callback which is called if websocket has an error.

Returns

None

async disconnect()[source]

Safely close the websocket connection.

Returns

async get_account_trades(message_id: str, swth_address: str, market: Optional[str] = None, page: Optional[int] = None)[source]

Request up to 100 account trades.

Example:

ws_client.get_account_trades('account_trades', 'swth1vaavrkrm7usqg9hcwhqh2hev9m3nryw7aera8p')

The expected return result for this function is as follows:

{
    "id": "account_trades",
    "result": [
        {
            "base_precision": 8,
            "quote_precision": 6,
            "fee_precision": 6,
            "order_id": "C7D7DDDCFDC68DF2D078CBD8630B657148893AC24CF8DB8F2E23293C6EDC90AD",
            "market": "wbtc1_usdc1",
            "side": "sell",
            "quantity": "0.0001",
            "price": "48745.12",
            "fee_amount": "0.004875",
            "fee_denom": "usdc1",
            "address": "swth1vaavrkrm7usqg9hcwhqh2hev9m3nryw7aera8p",
            "block_height": "7561537",
            "block_created_at": "2021-02-16T08:31:13.225303Z",
            "id": 289733
        },
        ...
    ]
}

Note

The market identifier is optional and acts as a filter.

Parameters
  • message_id – Identifier that will be included in the websocket message response to allow the subscriber to identify which channel the notification is originated from.

  • swth_address – Tradehub wallet address starting with ‘swth1’ for mainnet and ‘tswth1’ for testnet.

  • market – Tradehub market identifier, e.g. ‘swth_eth1’.

  • page – Used for pagination.

Returns

None

async get_candlesticks(message_id: str, market: str, granularity: int, from_epoch: int, to_epoch: int)[source]

Requests candlesticks for market with granularity.

Example:

ws_client.get_candlesticks('recent_trades', "swth_eth1")

The subscription and channel messages are expected as follow:

{
    'id': 'candlesticks.swth_eth1.1',
    'sequence_number': 57,
    'result': [
        {
            'id': 0,
            'market':'swth_eth1',
            'time': '2021-02-17T10:59:00Z',
            'resolution': 1,
            'open': '0.000018',
            'close': '0.000018',
            'high': '0.000018',
            'low': '0.000018',
            'volume': '5555',
            'quote_volume': '0.09999'
        }
    ]
}

Note

Only candles with non empty volume will be returned. Expect almost none or just a few candles with a low granularity.

Parameters
  • message_id – Identifier that will be included in the websocket message response to allow the subscriber to identify which channel the notification is originated from.

  • market – Tradehub market identifier, e.g. ‘swth_eth1’

  • granularity – Define the candlesticks granularity. Allowed values: 1, 5, 15, 30, 60, 360, 1440.

  • from_epoch – Starting from epoch seconds.

  • to_epoch – Ending to epoch seconds.

Returns

None

async get_closed_positions(message_id: str, swth_address: str, market: Optional[str] = None)[source]

Request closed positions.

Note

The market identifier is optional and acts as a filter.

Warning

The request method has not been tested yet.

Parameters
  • message_id – Identifier that will be included in the websocket message response to allow the subscriber to identify which channel the notification is originated from.

  • swth_address – Tradehub wallet address starting with ‘swth1’ for mainnet and ‘tswth1’ for testnet.

  • market – Tradehub market identifier, e.g. ‘swth_eth1’.

Returns

None

async get_leverages(message_id: str, swth_address: str, market: Optional[str] = None)[source]

Request leverages.

Note

The market identifier is optional and acts as a filter.

Warning

The request method has not been tested yet.

Parameters
  • message_id – Identifier that will be included in the websocket message response to allow the subscriber to identify which channel the notification is originated from.

  • swth_address – Tradehub wallet address starting with ‘swth1’ for mainnet and ‘tswth1’ for testnet.

  • market – Tradehub market identifier, e.g. ‘swth_eth1’.

Returns

None

async get_market_stats(message_id: str, market: Optional[str] = None)[source]

Request market stats.

Example:

ws_client.get_market_stats('market_stats')

The expected return result for this function is as follows:

{
    "id": "market_stats",
    "result": {
        "eth1_usdc1": {
            "day_high": "1818.51",
            "day_low": "1751.81",
            "day_open": "1760.07",
            "day_close": "1788.19",
            "day_volume": "36.503",
            "day_quote_volume": "65153.50224",
            "index_price": "0",
            "mark_price": "0",
            "last_price": "1788.19",
            "market": "eth1_usdc1",
            "market_type": "spot",
            "open_interest": "0"
        },
        ...
    }
}

Warning

Parameter ‘market’ has no effect. Maybe not intended as parameter. Request will result in all market stats.

Parameters
  • message_id – Identifier that will be included in the websocket message response to allow the subscriber to identify which channel the notification is originated from.

  • market – Tradehub market identifier, e.g. ‘swth_eth1’

Returns

None

async get_open_orders(message_id: str, swth_address: str, market: Optional[str] = None)[source]

Request open orders.

Example:

ws_client.get_open_orders('open_orders', "swth1p5hjhag5glkpqaj0y0vn3au7x0vz33k0gxuejk")

The expected return result for this function is as follows:

{
    "id": "open_orders",
    "result": [
        {
            "order_id": "A7C488A6AE25249E90523FCD603236342025340E3DCAE6A6312133905C41794C",
            "block_height": 7564973,
            "triggered_block_height": 0,
            "address": "swth1p5hjhag5glkpqaj0y0vn3au7x0vz33k0gxuejk",
            "market": "swth_eth1",
            "side": "sell",
            "price": "0.0000181",
            "quantity": "58806",
            "available": "58806",
            "filled": "0",
            "order_status": "open",
            "order_type": "limit",
            "initiator": "amm",
            "time_in_force": "gtc",
            "stop_price": "0",
            "trigger_type": "",
            "allocated_margin_denom": "swth",
            "allocated_margin_amount": "0",
            "is_liquidation": false,
            "is_post_only": false,
            "is_reduce_only": false,
            "type": "",
            "block_created_at": "2021-02-16T10:30:27.079962Z",
            "username": "",
            "id": "2316597"
        },
        ...
    ]
}

Note

The market identifier is optional and acts as a filter.

Parameters
  • message_id – Identifier that will be included in the websocket message response to allow the subscriber to identify which channel the notification is originated from.

  • swth_address – Tradehub wallet address starting with ‘swth1’ for mainnet and ‘tswth1’ for testnet.

  • market – Tradehub market identifier, e.g. ‘swth_eth1’

Returns

None

async get_open_positions(message_id: str, swth_address: str, market: Optional[str] = None)[source]

Request open positions.

Note

The market identifier is optional and acts as a filter.

Warning

The request method has not been tested yet.

Parameters
  • message_id – Identifier that will be included in the websocket message response to allow the subscriber to identify which channel the notification is originated from.

  • swth_address – Tradehub wallet address starting with ‘swth1’ for mainnet and ‘tswth1’ for testnet.

  • market – Tradehub market identifier, e.g. ‘swth_eth1’.

Returns

None

async get_order_history(message_id: str, swth_address: str, market: Optional[str] = None)[source]

Request up to 200 order histories.

Example:

ws_client.get_order_history('order_history', "swth1vaavrkrm7usqg9hcwhqh2hev9m3nryw7aera8p")

The expected return result for this function is as follows:

{
    "id": "order_history",
    "result": [
        {
            "order_id": "C7D7DDDCFDC68DF2D078CBD8630B657148893AC24CF8DB8F2E23293C6EDC90AD",
            "block_height": 7561537,
            "triggered_block_height": 0,
            "address": "swth1vaavrkrm7usqg9hcwhqh2hev9m3nryw7aera8p",
            "market": "wbtc1_usdc1",
            "side": "sell",
            "price": "0",
            "quantity": "0.0011",
            "available": "0",
            "filled": "0.0011",
            "order_status": "filled",
            "order_type": "market",
            "initiator": "user",
            "time_in_force": "fok",
            "stop_price": "0",
            "trigger_type": "",
            "allocated_margin_denom": "wbtc1",
            "allocated_margin_amount": "0",
            "is_liquidation": false,
            "is_post_only": false,
            "is_reduce_only": false,
            "type": "",
            "block_created_at": "2021-02-16T08:31:13.225303Z",
            "username": "",
            "id": "2315998"
        },
        ...
    ]
}

Note

The market identifier is optional and acts as a filter.

Parameters
  • message_id – Identifier that will be included in the websocket message response to allow the subscriber to identify which channel the notification is originated from.

  • swth_address – Tradehub wallet address starting with ‘swth1’ for mainnet and ‘tswth1’ for testnet.

  • market – Tradehub market identifier, e.g. ‘swth_eth1’

Returns

None

async get_recent_trades(message_id: str, market: str)[source]

Request up to 100 recent trades for a market.

Example:

ws_client.get_recent_trades('recent_trades', "swth_eth1")

The expected return result for this function is as follows:

{
    "id": "recent_trades",
    "sequence_number": 3,
    "result": [
        {
            "id": "0",
            "block_created_at": "2021-02-16T10:21:31.346041707Z",
            "taker_id": "3F71918F83D84639F505464335FD355105EE63E622CBB819AAFBBAC97368CC7A",
            "taker_address": "swth1ysezxr46dhd4dzjsswqte35wfm0ml5dxx97aqt",
            "taker_fee_amount": "3.2475",
            "taker_fee_denom": "swth",
            "taker_side": "buy",
            "maker_id": "343590CF4F54FEB1E2429F60B77CD3BED701A040418AEB914BB41D561E24E7DE",
            "maker_address": "swth1a5v8pyhkzjjmyw03mh9zqfakwyu0t5wkv0tf66",
            "maker_fee_amount": "-0.6495",
            "maker_fee_denom": "swth",
            "maker_side": "sell",
            "market": "swth_eth1",
            "price": "0.0000182",
            "quantity": "1299",
            "liquidation": "",
            "taker_username": "",
            "maker_username": "",
            "block_height": "7564715"
        },
        ...
    ]
}

Warning

The field ‘id’ is sometimes ‘0’. This endpoint/channel does not seem to work correct.

Parameters
  • message_id – Identifier that will be included in the websocket message response to allow the subscriber to identify which channel the notification is originated from.

  • market – Tradehub market identifier, e.g. ‘swth_eth1’

Returns

None

open()bool[source]

Check if the connection is open.

Returns

Bool

async send(data: dict)[source]

Send data to websocket server. Provided data will be translated to json.

Parameters

data – data as dictionary.

Returns

async subscribe(message_id: str, channels: List[str])[source]

Subscribe to one or many channels.

Parameters
  • message_id – Identifier that will be included in the websocket message response to allow the subscriber to identify which channel the notification is originated from.

  • channels – List with channels to join.

Returns

None

async subscribe_account_trades(message_id: str, swth_address: str, market: Optional[str] = None)[source]

Subscribe to account trades.

Example:

ws_client.subscribe_account_trades('account', 'swth...abcd', 'eth1_usdc1')
# or for all markets
ws_client.subscribe_account_trades('account', "swth...abcd')

The initial channel message is expected as:

{
    'id': 'account',
    'result': ['account_trades_by_market.eth1_usdc1.swth1...abcd']
}
# or for all markets
{
    'id': 'account',
    'result': ['account_trades.swth1...abcd']
}

The channel update messages are expected as:

{
    'channel': 'recent_trades.eth1_usdc1',
    'sequence_number': 812,
    'result': [
        {
            'id': '0',
            'block_created_at': '2021-02-11T20:49:07.095418551Z',
            'taker_id': '5FF349410F9CF59BED36D412D1223424835342274BC0E504ED0A17EE4B5B0856',
            'taker_address': 'swth1...taker',
            'taker_fee_amount': '0.00002',
            'taker_fee_denom': 'eth1',
            'taker_side': 'buy',
            'maker_id': '8334A9C97CAEFAF84774AAADB0D5666E7764BA023DF145C8AF90BB6A6862EA2E',
            'maker_address': 'swth1...maker',
            'maker_fee_amount': '-0.00001',
            'maker_fee_denom': 'eth1',
            'maker_side': 'sell',
            'market': 'eth1_usdc1',
            'price': '1797.1',
            'quantity': '0.02',
            'liquidation': '',
            'taker_username': '',
            'maker_username': '',
            'block_height': '7376096'
        },
        ...
    ]
}

Note

The market identifier is optional and acts as a filter.

Warning

The field ‘id’ is ‘0’ all the time. This endpoint/channel does not seem to work correct.

Parameters
  • message_id – Identifier that will be included in the websocket message response to allow the subscriber to identify which channel the notification is originated from.

  • swth_address – Tradehub wallet address starting with ‘swth1’ for mainnet and ‘tswth1’ for testnet.

  • market – Tradehub market identifier, e.g. ‘swth_eth1’

Returns

None

async subscribe_balances(message_id: str, swth_address: str)[source]

Subscribe to wallet specific balance channel.

Example:

ws_client.subscribe_balances('balance', "swth1...abcd')

The initial channel message is expected as:

{
    'id': 'balance',
    'result': ['balances.swth1...abcd']
}

The subscription and channel messages are expected as follow:

{
    'channel': 'balances.swth1vaavrkrm7usqg9hcwhqh2hev9m3nryw7aera8p',
    'result': {
        'eth1': {
            'available': '0.83941506825',
            'order': '0',
            'position': '0',
            'denom': 'eth1'
        },
        ...
    }
}
Parameters
  • message_id – Identifier that will be included in the websocket message response to allow the subscriber to identify which channel the notification is originated from.

  • swth_address – Tradehub wallet address starting with ‘swth1’ for mainnet and ‘tswth1’ for testnet.

Returns

None

async subscribe_books(message_id: str, market: str)[source]

Subscribe to book channel.

Example:

ws_client.subscribe_books('orderbook', "swth_eth1')

The initial channel message is expected as:

{
    'id':'orderbook',
    'result': ['books.eth1_usdc1', ...]
}

The initial subscription message is expected as:

{
    'channel': 'books.eth1_usdc1',
    'sequence_number': 924,
    'result': [
        {
            'market': 'eth1_usdc1',
            'price': '1797.1',
            'quantity': '0.02',
            'side': 'sell',
            'type': 'new'
        },
        ...
        {
            'market': 'eth1_usdc1',
            'price': '1790.1',
            'quantity': '0.02',
            'side': 'buy',
            'type': 'new'
        }
        ...
    ]
}

The channel update messages are expected as:

{
    'channel': 'books.eth1_usdc1',
    'sequence_number': 924,
    'result': [
        {
            'market': 'eth1_usdc1',
            'price': '1797.1',
            'quantity': '0',
            'side': 'sell',
            'type': 'delete'
        },
        ...
        {
            'market':'eth1_usdc1',
            'price': '1800.18',
            'quantity': '-0.43',
            'side': 'sell',
            'type': 'update'
        },
        ...
        {
            'market': 'eth1_usdc1',
            'price': '1114.48',
            'quantity': '182.716',
            'side': 'buy',
            'type': 'new'
        }
    ]
}

Note

The initial message is a snapshot of the current orderbook. The following messages are delta messages to the snapshot. Each message has a ‘sequence_number’.

Updates can contain update types: ‘new’, ‘update’ or ‘delete’. The quantity in a ‘update’ message can be negative indicating a reduction, while positive value means an increment.

All updates need to be processed in the provided order to maintain an consistent orderbook.

Warning

The initial snapshot is a partial orderbook with a total of 100 entries! Expect receiving updates for orders outside the local managed orderbook. Ignore or reconnect to maintain the local orderbook.

Parameters
  • message_id – Identifier that will be included in the websocket message response to allow the subscriber to identify which channel the notification is originated from.

  • market – Tradehub market identifier, e.g. ‘swth_eth1’

Returns

None

async subscribe_candlesticks(message_id: str, market: str, granularity: int)[source]

Subscribe to candlesticks channel.

Example:

ws_client.subscribe_candlesticks('candle', "swth_eth1', 1)

The initial channel message is expected as:

{
    'id': 'candle',
    'result': ['candlesticks.swth_eth1.1']
}

The subscription and channel messages are expected as follow:

{
    'channel': 'candlesticks.swth_eth1.1',
    'sequence_number': 57,
    'result': {
        'id': 0,
        'market':'swth_eth1',
        'time': '2021-02-17T10:59:00Z',
        'resolution': 1,
        'open': '0.000018',
        'close': '0.000018',
        'high': '0.000018',
        'low': '0.000018',
        'volume': '5555',
        'quote_volume': '0.09999'
    }
}
Parameters
  • message_id – Identifier that will be included in the websocket message response to allow the subscriber to identify which channel the notification is originated from.

  • market – Tradehub market identifier, e.g. ‘swth_eth1’

  • granularity – Define the candlesticks granularity. Allowed values: 1, 5, 15, 30, 60, 360, 1440.

Returns

None

async subscribe_leverages(message_id: str, swth_address: str)[source]

Subscribe to wallet specific leverages channel.

Warning

This channel has not been tested yet.

Parameters
  • message_id – Identifier that will be included in the websocket message response to allow the subscriber to identify which channel the notification is originated from.

  • swth_address – Tradehub wallet address starting with ‘swth1’ for mainnet and ‘tswth1’ for testnet.

Returns

None

async subscribe_market_stats(message_id: str)[source]

Subscribe to market stats.

Example:

ws_client.subscribe_market_stats('market_stats')

The initial channel message is expected as:

{
    'id':'market_stats',
    'result': ['market_stats']
}

The subscription and channel messages are expected as follow:

{
    'channel': 'market_stats',
    'sequence_number': 484,
    'result': {
        'cel1_usdc1': {
            'day_high': '5.97',
            'day_low': '5.72',
            'day_open': '5.86',
            'day_close': '5.74',
            'day_volume': '414.4',
            'day_quote_volume': '2429.009',
            'index_price': '0',
            'mark_price': '0',
            'last_price': '5.74',
            'market': 'cel1_usdc1',
            'market_type': 'spot',
            'open_interest': '0'
        }
        ...
    }
}
Parameters

message_id – Identifier that will be included in the websocket message response to allow the subscriber to identify which channel the notification is originated from.

Returns

None

async subscribe_orders(message_id: str, swth_address: str, market: Optional[str] = None)[source]

Subscribe to orders channel.

Note

The market identifier is optional and acts as a filter.

Example:

ws_client.subscribe_orders('orders', "swth1...abcd')

The initial channel message is expected as:

{
    'id':'orders',
    'result': ['orders.swth1...abcd']
}

The channel update messages are expected as:

{
    'channel': 'orders.swth1...abcd',
    'result': [
        {
            'order_id': '7CBBF51B75CF2E046726BB...56757D6D502B01F4BB62178DCF',
            'block_height': 7375724,
            'triggered_block_height': 0,
            'address': 'swth1...abcd',
            'market': 'eth1_wbtc1',
            'side': 'sell',
            'price': '0',
            'quantity': '0.08',
            'available': '0.08',
            'filled': '0',
            'order_status': 'pending',
            'order_type': 'market',
            'initiator': 'user',
            'time_in_force': 'fok',
            'stop_price': '0',
            'trigger_type': '',
            'allocated_margin_denom': 'eth1',
            'allocated_margin_amount': '0',
            'is_liquidation': False,
            'is_post_only': False,
            'is_reduce_only': False,
            'type': 'new',
            'block_created_at': '2021-02-11T20:36:02.244175356Z',
            'username': '',
            'id': ''
        }
        ...
    ]
}
Parameters
  • message_id – Identifier that will be included in the websocket message response to allow the subscriber to identify which channel the notification is originated from.

  • swth_address – Tradehub wallet address starting with ‘swth1’ for mainnet and ‘tswth1’ for testnet.

  • market – Tradehub market identifier, e.g. ‘swth_eth1’

Returns

None

async subscribe_positions(message_id: str, swth_address: str, market: Optional[str] = None)[source]

Subscribe to positions channel.

Note

The market identifier is optional and acts as a filter.

Warning

This channel is not tested yet.

Parameters
  • message_id – Identifier that will be included in the websocket message response to allow the subscriber to identify which channel the notification is originated from.

  • swth_address – Tradehub wallet address starting with ‘swth1’ for mainnet and ‘tswth1’ for testnet.

  • market – Tradehub market identifier, e.g. ‘swth_eth1’

Returns

None

async subscribe_recent_trades(message_id: str, market: str)[source]

Subscribe to recent trades.

Example:

ws_client.subscribe_recent_trades('trades', "swth_eth1')

The initial channel message is expected as:

{
    'id': 'trades',
    'result': ['recent_trades.swth_eth1']
}

The channel update messages are expected as:

{
    'channel': 'recent_trades.eth1_usdc1',
    'sequence_number': 812,
    'result': [
        {
            'id': '0',
            'block_created_at': '2021-02-11T20:49:07.095418551Z',
            'taker_id': '5FF349410F9CF59BED36D412D1223424835342274BC0E504ED0A17EE4B5B0856',
            'taker_address': 'swth1vaavrkrm7usqg9hcwhqh2hev9m3nryw7aera8p',
            'taker_fee_amount': '0.00002',
            'taker_fee_denom': 'eth1',
            'taker_side': 'buy',
            'maker_id': '8334A9C97CAEFAF84774AAADB0D5666E7764BA023DF145C8AF90BB6A6862EA2E',
            'maker_address': 'swth1wmcj8gmz4tszy5v8c0d9lxnmguqcdkw22275w5',
            'maker_fee_amount': '-0.00001',
            'maker_fee_denom': 'eth1',
            'maker_side': 'sell',
            'market': 'eth1_usdc1',
            'price': '1797.1',
            'quantity': '0.02',
            'liquidation': '',
            'taker_username': '',
            'maker_username': '',
            'block_height': '7376096'
        },
        ...
    ]
}

Warning

The field ‘id’ is sometimes ‘0’. This endpoint/channel does not seem to work correct.

Parameters
  • message_id – Identifier that will be included in the websocket message response to allow the subscriber to identify which channel the notification is originated from.

  • market – Tradehub market identifier, e.g. ‘swth_eth1’

Returns

None

async unsubscribe(message_id: str, channels: List[str])[source]

Unsubscribe to one or many channels.

Parameters
  • message_id – Identifier that will be included in the websocket message response to allow the subscriber to identify which channel the notification is originated from.

  • channels – List with channels to leave.

Returns

None