Websocket API v2

What Is WebSocket?

WebSocket is a protocol providing full-duplex communications channels over a single TCP connection. The WebSocket protocol was standardized by the IETF as RFC 6455 in 2011, and the WebSocket API in Web IDL is being standardized by the W3C.

Connection

Bitstamp by Robinhood uses its implementation of websocket server for real time data streaming. Server is accessible on the following address: wss://ws.bitstamp.net.

Documentation about websocket protocol can be found on the following link: https://websockets.readthedocs.io/en/stable/.

Once you open a connection via websocket handshake (using HTTP upgrade header), you can subscribe to desired channels.

After this is accomplished, you will start to receive a stream of live events for every channel you are subscribed to.

Subscriptions

Public channels

To subscribe to a channel, JSON message must be sent to the server. It should have a following structure:

JSON
{
    "event": "bts:subscribe",
    "data": {
        "channel": "[channel_name]"
    }
}

Private channels

To subscribe to a channel, JSON message must be sent to the server. It should have a following structure:

JSON
{
    "event": "bts:subscribe",
    "data": {
        "channel": "[channel_name]-[user-id]", "auth": "[token]"
    }
}

Token value and user id are generated via HTTP API. See Websockets token section of HTTP API documentation here.

Unsubscriptions

You can also unsubscribe from the channel if you no longer need its stream. Again, you need to send a message to the server.

Its structure is nearly identical to the subscription JSON:

JSON
{
    "event": "bts:unsubscribe",
    "data": {
        "channel": "[channel_name]"
    }
}

Note: Messages described and defined in this article are the only ones that will be processed by the server. Any other form of message or correct form of message with unexpected content will result in an error response.

Channels

Markets: 1incheur, 1inchusd, aavebtc, aaveeur, aaveusd, adaeur, adausd, algoeur, algousd, ampeur, ampusd, apeeur, apeusd, arbeur, arbusd, astereur, asterusd, audioeur, audiousd, avaxeur, avaxusd, avnteur, avntusd, axseur, axsusd, bateur, batusd, bcheur, bchusd, bioeur, biousd, blureur, blurusd, bnbeur, bnbusd, bomeeur, bomeusd, bonkeur, bonkusd, btceur, btceurc, btceurcv, btcgbp, btcrlusd, btcusd, btcusd-perp, btcusdc, btcusdt, chzeur, chzusd, compeur, compusd, coreumeur, coreumusd, crveur, crvusd, cspreur, csprusd, ctsieur, ctsiusd, ctxeur, ctxusd, cxteur, cxtusd, daiusd, dogeeur, dogeusd, dogeusd-perp, doteur, dotusd, egldeur, egldusd, enaeur, enausd, enjeur, enjusd, enseur, ensusd, etceur, etcusd, eth2eth, ethbtc, etheur, etheurc, etheurcv, ethgbp, ethrlusd, ethusd, ethusd-perp, ethusdc, ethusdt, eurceur, eurcusdc, eurcveur, eurcvusdc, eurcvusdt, eurusd, fartcoineur, fartcoinusd, feteur, fetusd, flokieur, flokiusd, flreur, flrusd, ftmeur, ftmusd, galaeur, galausd, gbpusd, grteur, grtusd, gyenusd, hbareur, hbarusd, hypeeur, hypeusd, icpeur, icpusd, imxeur, imxusd, injeur, injusd, jupeur, jupusd, knceur, kncusd, ldoeur, ldousd, linkeur, linkgbp, linkusd, lmwreur, lmwrusd, lrceur, lrcusd, ltcbtc, ltceur, ltcusd, manaeur, manausd, melaniaeur, melaniausd, meweur, mewusd, mkreur, mkrusd, mogeur, mogusd, moneur, monusd, moodengeur, moodengusd, neareur, nearusd, ondoeur, ondousd, opeur, opusd, pendleeur, pendleusd, pengueur, penguusd, pepeeur, pepeusd, perpeur, perpusd, pnuteur, pnutusd, poleur, polusd, popcateur, popcatusd, pytheur, pythusd, pyusdeur, pyusdusd, rlusdeur, rlusdusd, rlusdusdt, rndreur, rndrusd, sandeur, sandusd, seieur, seiusd, sgdusd, shibeur, shibusd, skleur, sklusd, smteur, smtusd, snxeur, snxusd, soleur, solusd, solusd-perp, solusdc, spkeur, spkusd, storjeur, storjusd, strkeur, strkusd, suieur, suiusd, suiusd-perp, sushieur, sushiusd, syrupeur, syrupusd, taieur, taiusd, toneur, tonusd, traceur, tracusd, trufeur, trufusd, trumpeur, trumpusd, umaeur, umausd, unieur, uniusd, usdceur, usdcusd, usdcusdt, usdteur, usdtusd, vchfeur, vchfusd, veureur, veurusd, virtualeur, virtualusd, wbtcbtc, wecaneur, wecanusd, weneur, wenusd, wifeur, wifusd, wlfieur, wlfiusd, wooeur, woousd, xchngeur, xchngusd, xcneur, xcnusd, xdceur, xdcusd, xlmeur, xlmgbp, xlmusd, xpleur, xplusd, xrpbtc, xrpeur, xrpgbp, xrprlusd, xrpusd, xrpusd-perp, xrpusdc, xrpusdt, xsgdusd, xsgdusdt, yfieur, yfiusd, zetaeur, zetausd, zoraeur, zorausd, zrxeur, zrxusd, zusdusd

Below tables include definitions of all existing channels you can subscribe to. Replacing [channel_name] placeholder in one of JSON messages defined in previous paragraphs will subscribe or unsubscribe you to a channel. You also need to replace the [market] placeholder with one of the markets defined above.

Public channels

Name Event Channel
Live ticker trade live_trades_[market]
Live orders order_created, order_changed or order_deleted live_orders_[market]
Live order book data order_book_[market]
Live detail order book data detail_order_book_[market]
Live full order book data diff_order_book_[market]
Live funding rate funding_rate_saved funding_rate_[market]

Private channels

Name Event Channel
Private My Orders order_created, order_changed, order_deleted, stop_active or stop_inactive private-my_orders_[market]-[userId]
Private My Trades trade private-my_trades_[market]-[userId]
Private My Settlements settlement private-my_settlements-[userId]
Private Live Trades self_trade private-live_trades_[market]-[userId]
Private Liquidations im_breach_warning, im_breach, mm_breach_warning, liquidation_start, liquidation_concluded private-my_liquidations-[userId]

Channel JSON structure

Live ticker - JavaScript example: live_trades_v2.html

Property Description
id Trade unique ID.
id_str Trade unique ID represented in string format.
amount Trade amount.
amount_str Trade amount represented in string format.
price Trade price.
price_str Trade price represented in string format.
type Trade type (0 - buy; 1 - sell).
timestamp Trade timestamp.
microtimestamp Trade microtimestamp.
buy_order_id Trade buy order ID.
sell_order_id Trade sell order ID.

Live order book - JavaScript example: order_book_v2.html

Property Description
bids List of top 100 bids.
asks List of top 100 asks.
timestamp Order book timestamp.
microtimestamp Order book microtimestamp.

Live detail order book

Property Description
bids List of top 100 bids [price, amount, order id].
asks List of top 100 asks [price, amount, order id].
timestamp Order book timestamp.
microtimestamp Order book microtimestamp.

Live full order book - JavaScript example: diff_order_book_v2.html

Property Description
bids List of changed bids since last broadcast.
asks List of changed asks since last broadcast.
timestamp Order book timestamp.
microtimestamp Order book microtimestamp.

Live orders - JavaScript example: live_orders_v2.html

Property Description
id Order ID.
amount Order amount.
amount_at_create Order amount at create represented in string format.
amount_str Order amount represented in string format.
amount_traded Amount traded represented in string format.
price Order price.
price_str Order price represented in string format.
order_type Order type (0 - buy; 1 - sell).
order_subtype Order subtype (0 - limit; 1 - instant; 2 - market; 3 - daily; 4 - IOC; 5 - MOC; 6 - FOK; 7 - CASH SELL; 8 - GTD; 20 - stop loss; 21 - take profit; 22 - stop loss limit; 23 - take profit limit; 24 - trailing stop loss; 25 - trailing take profit; 26 - stop loss limit; 27 - trailing take profit limit).
datetime Order datetime.
microtimestamp Order action timestamp represented in microseconds.
is_liquidation Indicates whether the order was triggered as part of a liquidation event (True / False).

Live funding rate

Property Description
funding_rate Funding rate.
mark_price Mark price.
index_price Index price.
market Market of funding rate.
timestamp Event timestamp.
next_funding_time Next funding time.

Private My Orders

Property Description
id Order ID.
id_str Order ID represented in string format.
client_order_id Client order ID (if used when placing order).
amount Order amount left to be executed.
amount_str Order amount left to be executed represented in string format.
amount_traded Executed order amount represented in string format.
amount_at_create Original order amount represented in string format.
price Order price.
price_str Order price represented in string format.
order_type Order type (0 - buy, 1 - sell).
order_subtype Order subtype (0 - limit; 1 - instant; 2 - market; 3 - daily; 4 - IOC; 5 - MOC; 6 - FOK; 7 - CASH SELL; 8 - GTD; 20 - stop loss; 21 - take profit; 22 - stop loss limit; 23 - take profit limit; 24 - trailing stop loss; 25 - trailing take profit; 26 - stop loss limit; 27 - trailing take profit limit).
datetime Order datetime.
microtimestamp Order action timestamp represented in microseconds.
trade_account_id ID of related trade account (0 for main account, Unique ID for sub accounts).
is_liquidation Indicates whether the order was triggered as part of a liquidation event (True / False)
reduce_only Determines whether the order reduce only, if yes the value is true, otherwise it is omitted.
stop_price Order stop price in string format.
activation_price Order activation price in string format.
trailing_delta Order trailing delta.

Private My Trades

Property Description
id Trade ID.
id_str Trade unique ID represented in string format.
order_id Order ID associated with the trade.
client_order_id Client order ID associated with the trade.
amount Trade amount.
price Trade price.
fee Trade fee.
side Trade side (buy or sell).
microtimestamp Trade timestamp represented in microseconds.
trade_account_id ID of related trade account (0 for main account, Unique ID for sub accounts).
position_id Position ID.
is_liquidation Determines whether the trade is a result of liquidation, if yes the value is 1, otherwise it is omitted.
trade_type Trade type (POSITION_LIQUIDATION, COLLATERAL_LIQUIDATION, ORDERBOOK, POSITION_MARKET_WIDE_CLOSURE, POSITION_ASSIGNMENT, POSITION_ADL).

Private My Settlements

Property Description
id Position ID.
tnx_id Transaction id.
ts Settlement time (in seconds).
price Settlement price.
ccy Currency.
as Amount settled.
ap Amount from price.
atf Amount from trading fees.
alf Amount from liquidation fees.
afu Amount from funding.
asl Amount from socialised loss.
sp Strike price.
typ Settlement type, C for closed, otherwise it is omitted.

Private Live Trades

Note: Private-live_trades channels only broadcast self_trade events. Self-trade events occur when orders from the same client are matched against each other and offset against each other instead of executing as a trade due to self-trading prevention.

Property Description
buy_order_id Buy order id.
sell_order_id Sell order id.
amount Trade amount.
amount_str Trade amount represented in string format.
price Trade price.
price_str Trade price represented in string format.
type Order type (0 - buy; 1 - sell).
timestamp Timestamp represented in seconds.
microtimestamp Timestamp represented in microtimestamp.
sellers_trade_account_id ID of related trade account to sell order (0 for main account, Unique ID for sub accounts).
buyers_trade_account_id ID of related trade account to buy order (0 for main account, Unique ID for sub accounts).

Private Liquidations

Property Description
position_id Position ID.
trade_account_id ID of related trade account (0 for main account, Unique ID for sub accounts).
microtimestamp Timestamp of alert, represented in microseconds.
alert_type Type of alert (im_breach_warning, im_breach, mm_breach_warning, liquidation_start, liquidation_concluded).
margin_mode Margin mode (ISOLATED/CROSS).
initial_margin_ratio Initial margin ratio at the time of alert.
maintenance_margin_ratio Maintenance margin ratio at the time of alert.

Other technical information

1. Heartbeat

If you wish to determine that websocket server is responsive, you should do so by websocket heartbeat. This is a form of control message or "PING / PONG" communication. You can do so by sending the following JSON message to the server:

JSON
{
    "event": "bts:heartbeat"
}

2. Forced reconnection

In case of websocket server you are currently connected to is to go under maintenance, you will receive a warning message asking you to reconnect. Such a message will look like this:

JSON
{
    "event": "bts:request_reconnect",
    "channel": "",
    "data": ""
}

After you receive this request, you will have a few seconds to reconnect. Without doing so, you will automatically be disconnected. If you send reconnection request, you will be placed to a new server. Consequentially, you can continue without any message loss.

3. Maximum connection age

Maximum connection age is 90 days from the time the connection is established. When that period of time elapses, you will be automatically disconnected and will need to re-connect.