NAV Navbar
Node.js

Authentication

HTTP Request

POST https://api.b2bx.exchange/api/v1/b2trade/auth

Request params

Parameter Type
email string, required
password string, required

Request example:

const request = require('request');
request.post({
    'url': "https://api.b2bx.exchange/api/v1/b2trade/auth",
    'form': {
        'email': "your email",
        'password': "your password"
    }
}, (error, response, body) => {
    let data = JSON.parse(body).data;
    /**
     * User ID
     * @type {integer}
     */
    let userId = data.user_id;

    /**
     * Session token
     * @type {string}
     */
    let sessionToken = data.session_token;

    /**
     * Websocket auth token
     * @type {string}
     */
    let authToken = data.token;
});

Response data array

Parameter Type
id int
email string
country_code int
settings array
status int
logged_at string
created_at string
updated_at string
nickname int
photo string
token string
user_id int
session_token string

WebSocket API

wss://wss.b2bx.exchange/WSGateway/?session_token=sessionToken

Message Frame

When sending a request in the frame to the software using JavaScript, a call looks like:

var frame = { "m":0, "i":0, "n":"function name", "o":"" };
var requestPayload = { "Parameter1":"Value", "Parameter2":0 };
frame.o = json.Stringify(requestPayload);
WS.Send(json.Stringify(frame));

When receiving a frame from the software, use the frame to determine the context, and then unwrap the content:

var frame = json.Parse(wsMessage);
if (frame.m == 1) //message of type reply 
{ //This is a Reply
  if (frame.n == "WebAuthenticateUser") { 
    var LoginReply = json.Parse(frame.o); 
    if (LoginReply.Authenticated) {
      var user = LoginReply.User; 
    }
  } 
}
Parameter Type Description
m message type int The type of the message:
0 request
1 reply
2 subscribe to event
3 event
4 unsubscribe from event
5 error
i sequence number long integer The sequence number identifies an individual request, or requestand-response pair, to your application.
A non-zero sequence number is required, but the numbering scheme you use is up to you. No arbitrary sequence numbering scheme is enforced.
Best practices: A client-generated API call (of message types 0, 2, and 4) should:
Carry an even sequence number.
Begin at the start of each user session.
Be unique within each user session.
Begin with 2 (2, 4, 6, 8).
Message types 1 (reply), 3 (event), and 5 (error) are generated by the server. These messages echo the sequence number of the message to which they respond.
n function name string The function name is the name of the function that you are calling or that the server responds to. The server echoes your call.
o payload json Payload is a JSON-formatted string containing the data being sent with the message. Payload may consist of request parameters (string-value pairs) or response parameters.

WebAuthenticateUser

WebAuthenticateUser authenticates a user (logs in a user) for the current websocket session. You must call WebAuthenticateUser in order to use the calls in this document shown as "Authentication required."

Request

Parameter Type Description
SessionToken string token returned by REST API b2trade/auth method.

Request example:

wss.send(JSON.stringify({
  "m": 0,
  "i": 0,
  "n": 'WebAuthenticateUser',
  "o": '{"SessionToken":"' +  authToken + '"}'
}));

Response

Parameter Type Description
Authenticated boolean Response for an successful/unsuccessful authentication
SessionToken string SessionToken uniquely identifies the session on the OMS. By returning the SessionToken in the response, the user can log in again if the session is interrupted without going through two-factor authentication.
UserId integer Returns the user ID of the authenticated user

Unsuccessful response:

{ 
  "Authenticated": false 
}

A successful response returns the following (with UserId and SessionToken simulated):

{
  "Authenticated": true,
  "SessionToken":"7d0ccf3a-ae63-44f5-a409-2301d80228bc",
  "UserId": 1
}

GetUserAccounts

Authentication required
Returns a list of account IDs for a given user.

Request

Request

wss.send(JSON.stringify({
    "m": 0,
    "i": 0,
    "n": 'GetUserAccounts',
    "o": '{"OMSId":1, "UserId":' +  userId + '}'
}));
Parameter Type Description
OMSId integer 1
UserId integer The ID of the user whose accounts you want to return.

Response

The response returns list of comma-separated account IDs.

[ 0, // a list of account IDs ]

GetInstruments

Retrieves an array of instrument objects describing all instruments available on a trading venue to the user. An instrument is a pair of exchanged products (or fractions of them) such as US dollars and ounces of gold.

Request

wss.send(JSON.stringify({
    "m": 0,
    "i": 0,
    "n": 'GetInstruments',
    "o": '{"OMSId":1}'
}));

Request

Parameter Type Description
OMSId integer 1

Response

Parameter Type Description
OMSId integer 1
InstrumentId long integer The ID of the instrument.
Symbol string Trading symbol of the instrument
Product1 integer The first product comprising the instrument. For example, USD in a USD/ BitCoin instrument.
Product1Symbol string The symbol for Product 1 on the trading venue. For example, USD.
Product2 integer The second product comprising the instrument. For example, BitCoin in a USD/BitCoin instrument.
Product2Symbol string The symbol for Product 2 on the trading venue. For example, BTC.
InstrumentType string The type of the instrument. All instrument types currently are standard, an exchange of one product for another (or unknown, an error condition), but this may expand to new types in the future.
Unknown
Standard
VenueInstrumentId long integer If the instrument trades on another trading venue to which the user has access, this value is the instrument ID on that other venue. See VenueId.
VenueId integer The ID of the trading venue on which the instrument trades, if not this venue. See VenueInstrumentId.
SortIndex integer The numerical position in which to sort the returned list of instruments on a visual display
SessionStatus string Is the market for this instrument currently open and operational? Returns one of:
Unknown
Running
Paused Stopped Starting
PreviousSessionStatus string What was the previous session status for this instrument? One of:
Unknown
Running
Paused
Stopped
Starting
SessionStatusDateTime string The time and date at which the session status was reported, in ISO 8601 format.
SelfTradePrevention boolean An account trading with itself still incurs fees. If this instrument prevents an account from trading the instrument with itself, the value returns true; otherwise defaults to false.
QuantityIncrement integer The number of decimal places for the smallest quantity of the instrument that can trade (analogous to smallest lot size). For example, the smallest increment of a US Dollar that can trade i s 0.01 (one cent, or 2 decimal places). Current maximum is 8 decimal places. The default is 0.

GetProducts

Returns an array of products available on the trading venue. A product is an asset that is tradable or paid out.

Request

wss.send(JSON.stringify({
    "m": 0,
    "i": 0,
    "n": 'GetProducts',
    "o": '{"OMSId":1}'
}));

Request

Parameter Type Description
OMSId integer 1

Response

The response returns an array of objects, one object for each product available on the Order Management System

Parameter Type Description
OMSId integer 1
ProductId long integer The ID of the product.
Product string Nickname" or shortened name of the product. For example, NZD (New Zealand Dollar).
ProductType string The nature of the product. One of: 0 Unknown (an error condition)
1 NationalCurrency
2 CryptoCurrency
3 Contract
DecimalPlaces integer The number of decimal places in which the product is divided. For example, US Dollars are divided into 100 units, or 2 decimal places. Other products may be different. Burundi Francs use 0 decimal places and the Rial Omani uses 3.
TickSize integer Minimum tradable quantity of the product. See also GetInstrument, where this value is called QuantityIncrement.
For example, with a US Dollar, the minimal tradable quantity is $0.01.
NoFees Boolean Shows whether trading the product incurs fees.
The default is false; that is, if NoFees is false, fees will be incurred.
If NoFees is true, no fees are incurred

SendOrder

Authentication required

Creates an order.

Request

wss.send(JSON.stringify({
    "m": 0,
    "i": 0,
    "n": 'SendOrder',
    "o": '{
        "AccountId": 5,
        "ClientOrderId": 99,
        "Quantity": 1,
        "DisplayQuantity": 0,
        "UseDisplayQuantity": true,
        "LimitPrice": 95,
        "OrderIdOCO": 0,
        "OrderType": 2,
        "PegPriceType": 1,
        "InstrumentId": 1,
        "TrailingAmount": 1.0,
        "LimitOffset": 2.0,
        "Side": 0,
        "StopPrice": 96,
        "TimeInForce": 1,
        "OMSId": 1
      }'
}));

Request

Parameter Type Description
OMSId integer 1
AccountId integer The ID of the account placing the order.
ClientOrderId long integer A user-assigned ID for the order (like a purchase-order number assigned by a company). This ID is useful for recognizing future states related to this order. ClientOrderId defaults to 0.
Quantity real The quantity of the instrument being ordered.
DisplayQuantity real The quantity available to buy or sell that is publicly displayed to the market. To display a DisplayQuantity value, an order must be a Limit order with a reserve.
UseDisplayQuantity Boolean If you enter a Limit order with a reserve, you must set UseDisplayQuantity to true.
LimitPrice real The price at which to execute the order, if the order is a Limit order.
OrderIdOCO integer One Cancels the Other — If this order is order A, OrderIdOCO refers to the order ID of an order B (which is not the order being created by this call). If order B executes, then order A created by this call is canceled. You can also set up order B to watch order A in the same way, but that may require an update to order B to make it watch this one, which could have implications for priority in the order book.
OrderType integer The type of this order, as expressed in integer format. You’ll need Market order.
1 Market
2 Limit
3 StopMarket
4 StopLimit
5 TrailingStopMarket
6 TrailingStopLimit
PegPriceType integer When entering a stop/trailing order, set PegPriceType to an integer that corresponds to the type of price that pegs the stop: 1 Last
2 Bid
3 Ask
4 Midpoint
InstrumentId long integer The ID of the instrument being traded in the order
TrailingAmount real The offset by which to trail the market in one of the trailing order types. Set this to the current price of the market to ensure that the trailing offset is the amount intended in a fast-moving market.
LimitOffset real The amount by which a trailing limit order is offset from the activation price.
Side integer The side of the trade represented by this order. One of: 0 Buy
1 Sell
2 Short (reserved for future use)
3 Unknown (error condition)
StopPrice integer The price at which to execute the order, if the order is a Stop order (either buy or sell).
TimeInForce integer The period during which the order is executable.
1 GTC good til canceled
3 IOC immediate or cancelled
4 FOK fill or kill — fill the order immediately, or cancel it immediately

Response

Parameter Type Description
status string If the order is accepted by the system, it returns 0.
0 Accepted
1 Rejected
errormsg string Any error message the server returns.
OrderId long integer The ID assigned to the order by the server. This allows you to track the order.

GetOpenOrders

Returns an array of 0 or more orders that have not yet been filled (open orders) for a single account for a given user on a specific Order Management System. The call returns an empty array if a user has no open orders.

Request

wss.send(JSON.stringify({
    "m": 0,
    "i": 0,
    "n": 'GetOpenOrders',
    "o": '{
        "OMSId": 1,
        "AccountId": 4,
      }'
}));

Request

Parameter Type Description
OMSId integer The ID of the Order Management System to which the user belongs. A user will belong only to one OMS.
AccountId integer The ID of the authenticated user’s account.

Response

Response. This example response for GetOpenOrders returns an array containing both a buy-side and a sell-side order. The call returns an empty array if there are no open orders for the account.

[
    { 
        "Side": "Buy",
        "OrderId": 1,
        "Price": 100,
        "Quantity": 1,
        "DisplayQuantity": 1,
        "Instrument": 1,
        "Account": 4,
        "OrderType": "Limit",
        "ClientOrderId": 0,
        "OrderState": "Working",
        "ReceiveTime": 1501354241987,
        "ReceiveTimeTicks": 636369510419870950,
        "OrigQuantity": 1,
        "QuantityExecuted": 0,
        "AvgPrice": 0,
        "CounterPartyId": 0,
        "ChangeReason": "NewInputAccepted",
        "OrigOrderId": 1,
        "OrigClOrdId": 0,
        "EnteredBy": 1,
        "IsQuote": false,
        "InsideAsk": 9223372036.854775807,
        "InsideAskSize": 0,
        "InsideBid": 100,
        "InsideBidSize": 1,
        "LastTradePrice": 0,
        "RejectReason": "",
        "IsLockedIn": false,
        "OMSId": 1 
    },
    {
        "Side": "Sell",
        "OrderId": 2,
        "Price": 150,
        "Quantity": 1,
        "DisplayQuantity": 1,
        "Instrument": 1,
        "Account": 4,
        "OrderType": "Limit",
        "ClientOrderId": 0,
        "OrderState": "Working",
        "ReceiveTime": 1501354246718,
        "ReceiveTimeTicks": 636369510467182396,
        "OrigQuantity": 1,
        "QuantityExecuted": 0,
        "AvgPrice": 0,
        "CounterPartyId": 0,
        "ChangeReason": "NewInputAccepted",
        "OrigOrderId": 2,
        "OrigClOrdId": 0,
        "EnteredBy": 1,
        "IsQuote": false,
        "InsideAsk": 150,
        "InsideAskSize": 1,
        "InsideBid": 100,
        "InsideBidSize": 1,
        "LastTradePrice": 0,
        "RejectReason": "",
        "IsLockedIn": false,
        "OMSId": 1
    }
]
Parameter Type Description
OMSId integer ID of the Order Management System on which the order was placed.
Side string The open order can be Buy or Sell.
0 Buy
1 Sell
2 Short (reserved for future use)
3 Unknown (error condition)
OrderId long integer The ID of the open order. The OrderID is unique in each Order Management System
Price real The price at which the buy or sell has been ordered.
Quantity real The quantity to be bought or sold.
DisplayQuantity real The quantity available to buy or sell that is publicly displayed to the market. To display a DisplayQuantity value, an order must be a Limit order with a reserve.
Instrument integer ID of the instrument being traded. See GetInstruments.
Account integer The ID of the account that placed the order.
OrderType string There are currently seven types of order.
ClientOrderId long integer A user-assigned ID for the order (like a purchase-order number assigned by a company). ClientOrderId defaults to 0.
OrderState string The current condition of the order. There are five order states:
Working
Rejected
Canceled
Expired
FullyExecuted
ReceiveTime long integer The time at which the system received the order, in POSIX format and UTC time zone.
ReceiveTimeTicks long integer The time stamp of the received order in Microsoft Tick format, and UTC time zone.
OrigQuantity integer Original quantity of the order. The quantity of the actual execution may be lower than this number, but OrigQuantity shows the quantity in the order as placed.
QuantityExecuted integer The number of units executed in this trade.
AvgPrice real Not currently used.
CounterPartyId long integer Shows 0
ChangeReason string The reason that an order has been changed. Values:
1 NewInputAccepted
2 NewInputRejected
3 OtherRejected
4 Expired
5 Trade
6 SystemCanceled_NoMoreMarket
7 SystemCanceled_BelowMinimum
8 NoChange
100 UserModified
OrigOrderId long ID of the original order. This number is also appended to CancelReplaceOrder. See CancelReplaceOrder.
EnteredBy integer User ID of the person who entered the order.
IsQuote Boolean True if the open order is a quote; false if not.
InsideAsk/InsideBid real Best price available at time of entry (for ask or bid, respectively).
InsideAskSize/InsideBidSize real Quantity available at the best inside ask (or bid) price.
LastTradePrice real Last trade price for this product before this order was entered.
RejectReason string If this order was rejected, RejectReason holds the reason for the rejection.
IsLockedIn Boolean True if both parties to a block trade agree that one party will report the trade for both. Otherwise false.

GetOrderStatus

Returns an array of 0 or more orders that have not yet been filled (open orders) for a single account for a given user on a specific Order Management System. The call returns an empty array if a user has no open orders.

Request

wss.send(JSON.stringify({
    "m": 0,
    "i": 0,
    "n": 'GetOrderStatus',
    "o": '{
        "OMSId": 0,
        "AccountId": 0,
        "OrderId": 0,
      }'
}));

Request

Parameter Type Description
OMSId integer The ID of the Order Management System on which the order was placed.
AccountId integer The ID of the account under which the order was placed.
OrderId integer The ID of the order whose status will be returned.

Response

Response. The response returns a single order object.

{ 
    "Side": { 
        "Options": [
            "Buy",
            "Sell",
            "Short",
            "Unknown"
        ] 
    },
    "OrderId": 0,
    "Price": 0,
    "Quantity": 0,
    "DisplayQuantity": 0,
    "Instrument": 0,
    "Account": 0,
    "OrderType": {
        "Options": [
            "Unknown",
            "Market",
            "Limit",
            "StopMarket",
            "StopLimit",
            "TrailingStopMarket",
            "TrailingStopLimit",
            "BlockTrade"
        ] 
    },
    "ClientOrderId": 0,
    "OrderState": {
        "Options": [
            "Unknown",
            "Working",
            "Rejected",
            "Canceled",
            "Expired",
            "FullyExecuted"
        ] 
    },
    "ReceiveTime": 0,
    "ReceiveTimeTicks": 0,
    "OrigQuantity": 0,
    "QuantityExecuted": 0,
    "AvgPrice": 0,
    "CounterPartyId": 0,
    "ChangeReason": {
       "Options": [
            "Unknown",
            "NewInputAccepted",
            "NewInputRejected",
            "OtherRejected",
            "Expired",
            "Trade",
            "SystemCanceled_NoMoreMarket",
            "SystemCanceled_BelowMinimum",
            "NoChange",
            "UserModified"
        ] 
    },
    "OrigOrderId": 0,
    "OrigClOrdId": 0,
    "EnteredBy": 0,
    "IsQuote": false,
    "InsideAsk": 0,
    "InsideAskSize": 0,
    "InsideBid": 0,
    "InsideBidSize": 0,
    "LastTradePrice": 0,
    "RejectReason": "",
    "IsLockedIn": false,
    "OMSId": 0,
}
Parameter Type Description
OMSId integer ID of the Order Management System on which the order was placed.
Side string The open order can be Buy or Sell.
0 Buy
1 Sell
2 Short (reserved for future use)
3 Unknown (error condition)
OrderId long integer The ID of the order. The response echoes the order ID from the request.
Price real The price at which the order was placed.
Quantity real The quantity of the instrument being ordered.
DisplayQuantity real The quantity available to buy or sell that is publicly displayed to the market. To display a DisplayQuantity value, an order must be a Limit order with a reserve.
Instrument integer The ID of the instrument traded in the order.
Account integer The ID of the account that placed the order.
OrderType string One of:
Unknown
Market
Limit
StopMarket
StopLimit
TrailingStopMarket
TrailingStopLimit
BlockTrade
ClientOrderId long integer A user-assigned ID for the order (like a purchase-order number assigned by a company). ClientOrderId defaults to 0.
OrderState string The current condition of the order. There are five order states:
0 Unknown
2 Working
3 Rejected
4 Canceled
5 Expired
6 FullyExecuted
ReceiveTime long integer The time at which the system received the order, in POSIX format and UTC time zone.
ReceiveTimeTicks long integer The time stamp of the received order in Microsoft Tick format, and UTC time zone.
OrigQuantity real Original quantity of the order. The quantity of the actual execution may be lower than this number, but OrigQuantity shows the quantity in the order as placed.
QuantityExecuted real The quantity executed in this order. May be different from the amount ordered (Quantity).
AvgPrice real Not currently used.
CounterPartyId long integer Shows 0
ChangeReason string The reason that the order may have been changed from the original. One of:
0 Unknown
1 NewInputAccepted
2 NewInputRejected
3 OtherRejected
4 Expired
5 Trade
6 SystemCanceled_NoMoreMarket
7 SystemCanceled_BelowMinimum
8 NoChange
9 UserModified
OrigOrderId integer The ID of the original order, if it has been changed.
OrigClOrId long integer If the order has been changed, shows the original client order ID, a value that the client can create (much like a purchase order). The default value is 0.
EnteredBy integer The ID of the user who originally entered the order.
IsQuote Boolean Returns true if the order is a quote, else returns false. Default is false.
InsideAsk real Ask price among market makers.
InsideAskSize real Ask quantity among market makers.
InsideBid real Bid price among market makers.
InsideBidSize real Bid quantity among market makers.
LastTradePrice real The price at which the instrument traded immediately before this trade.
RejectReason string If the trade was rejected, this string holds the reason.
IsLockedIn Boolean True if both parties to a block trade agree that one party will report the trade for both. Otherwise false.

CancelOrder

Cancels an open order that has been placed but has not yet been executed. Only a trading venue operator can cancel orders for another user or account.

Request. The OMS ID and the Order ID precisely identify the order you wish to cancel. The Order ID is unique across an OMS.
If you specify the OMS ID and the Account ID, you must also specify at least the Client Order ID. The OMS is unable to identify the order using only the OMS ID and the Client Order ID, as the Client Order ID may not be unique.

wss.send(JSON.stringify({
    "m": 0,
    "i": 0,
    "n": 'CancelOrder',
    "o": '{
        "OMSId": 0,
        "AccountId": 0, // conditionally optional
        "ClientOrderId": 0, // conditionally optional
        "OrderId": 0, // conditionally optional
      }'
}));

Request

Parameter Type Description
OMSId integer 1
AccountId integer The ID of the account placing the order.
ClientOrderId long integer A user-assigned ID for the order (like a purchase-order number assigned by a company). This ID is useful for recognizing future states related to this order. ClientOrderId defaults to 0.
OrderId long integer The order to be cancelled. Conditionally optional.

Response

The response to CancelOrder veri es that the call was received, not that the order has been canceled successfully. Individual event updates to the user show order cancellation.

{
  "result": true,
  "errormsg": "", 
  "errorcode": 0, 
  "detail": "",
}
Parameter Type Description
result boolean Returns true if the call to cancel the order has been successfully received, otherwise returns false.
errormsg string A successful receipt of the unsubscribe request returns null; the errormsg parameter for an unsuccessful request returns one of the following messages:
Not Authorized (errorcode 20)
Invalid Request (errorcode 100)
Operation Failed (errorcode 101)
Server Error (errorcode 102)
Resource Not Found (errorcode 104)
errorcode integer A successful receipt of the unsubscribe request returns 0. An unsuccessful receipt returns one of the errorcodes shown in the errormsg list.
detail string Message text that the system may send. Usually null

SubscribeLevel1

Retrieves the latest Level 1 Ticker information and then subscribes the user to ongoing Level 1 market data event updates for one specific instrument. The SubscribeLevel1 call responds with the Level 1 response shown below. The OMS then periodically sends Leve1UpdateEvent information when best bid/best offer issues in the same format as this response, until you send the UnsubscribeLevel1 call.

You can identify the instrument with its ID or with its market symbol (string).

wss.send(JSON.stringify({
    "m": 0,
    "i": 0,
    "n": 'SubscribeLevel1',
    "o": '{"OMSId": 1, "InstrumentId": 0 }'
}));

or

wss.send(JSON.stringify({
    "m": 0,
    "i": 0,
    "n": 'SubscribeLevel1',
    "o": '{"OMSId": 1, "Symbol": "BTCUSD"}'
}));

Request

Parameter Type Description
OMSId integer 1
OInstrumentId integer The ID of the instrument you’re tracking. Conditionally optional.
Symbol string The symbol of the instrument you’re tracking. Conditionally optional.

Response

The SubscribeLevel1 response and Level1UpdateEvent both provide the same information.

Parameter Type Description
OMSId integer 1
InstrumentId integer The ID of the instrument being tracked.
BestBid real The current best bid for the instrument.
BestOffer real The current best offer for the instrument.
LastTradedPx real The last-traded price for the instrument.
LastTradedQty real The last-traded quantity for the instrument.
LastTradeTime long integer The time of the last trade in POSIX format X 1000 (milliseconds since 1 January 1970).
SessionOpen real Opening price. In markets with openings and closings, this is the opening price for the current session; in 24-hour markets, it is the price as of UTC Midnight.
SessionHigh real Highest price during the trading day, either during a true session (with opening and closing prices) or UTC midnight to UTC midnight.
SessionLow real Lowest price during the trading day, either during a true session (with opening and closing prices) or UTC midnight to UTC midnight.
SessionClose real The closing price. In markets with openings and closings,this is the closing price for the current session; in 24-hour markets, it is the price as of UTC Midnight.
Volume real The unit volume of the instrument traded, either during a true session (with openings and closings) or in 24-hour markets, the period from UTC Midnight to UTC Midnight.
CurrentDayVolume real The unit volume of the instrument traded either during a true session (with openings and closings) or in 24-hour markets, the period from UTC Midnight to UTC Midnight.
CurrentDayNumTrades integer The number of trades during the current day, either during a true session (with openings and closings) or in 24-hour markets, the period from UTC Midnight to UTC Midnight.
CurrentDayPxChange real Current day price change, either during a true trading session or UTC Midnight to UTC midnight.
Rolling24HrVolume real Unit volume of the instrument during the past 24 hours, regardless of time zone. Recalculates continuously.
Rolling24HrNumTrades integer Number of trades during the past 24 hours, regardless of time zone. Recalculates continuously.
Rolling24HrPxChange real Price change during the past 24 hours, regardless of time zone. Recalculates continuously
TimeStamp long integer The time this information was provided, in POSIX format X 1000 (milliseconds since 1 January 1970).

UnsubscribeLevel1

Unsubscribes the user from a Level 1 Market Data Feed subscription.

Request

wss.send(JSON.stringify({
    "m": 0,
    "i": 0,
    "n": 'UnsubscribeLevel1',
    "o": '{"OMSId": 1, "InstrumentId": 1 }'
}));

Request

Parameter Type Description
OMSId integer 1
InstrumentId long integer The ID of the instrument being tracked by the Level 1 market data feed.

Response

Parameter Type Description
result boolean A successful receipt of the unsubscribe request returns true; and unsuccessful receipt (an error condition) returns false.
errormsg string A successful receipt of the unsubscribe request returns null; the errormsg parameter for an unsuccessful request returns one of the following messages:
Not Authorized (errorcode 20)
Invalid Request (errorcode 100)
Operation Failed (errorcode 101)
Server Error (errorcode 102)
Resource Not Found (errorcode 104)
errorcode integer A successful receipt of the unsubscribe request returns 0. An unsuccessful receipt returns one of the errorcodes shown in the errormsg list.
detail string Message text that the system may send. Usually null

SubscribeLevel2

Retrieves the latest Level 2 Ticker information and then subscribes the user to Level 2 market data event updates for one specific instrument. Level 2 allows the user to specify the level of market depth information on either side of the bid and ask. The SubscribeLevel2 call responds with the Level 2 response shown below. The OMS then periodically sends Level2UpdateEvent information in the same format as this response until you send the UnsubscribeLevel2 call.

You can identify the instrument either by ID or by market symbol.

wss.send(JSON.stringify({
    "m": 0,
    "i": 0,
    "n": 'SubscribeLevel2',
    "o": '{"OMSId": 1, "InstrumentId": 0, "Depth":10 }'
}));

or

wss.send(JSON.stringify({
    "m": 0,
    "i": 0,
    "n": 'SubscribeLevel2',
    "o": '{"OMSId": 1, "Symbol": "BTCUSD", "Depth":10}'
}));

Response Example

[
  UpdateId,
  NumAccounts,
  TimeStamp,
  UpdateType,
  LastTradePx,
  NumOrders,
  Price,
  InstrumentId,
  Quantity,
  Side
]

Request

Parameter Type Description
OMSId integer 1
InstrumentId integer The ID of the instrument you’re tracking. Conditionally optional.
Symbol string The symbol of the instrument you’re tracking. Conditionally optional.
Depth integer The depth of the order book. The example request returns 10 price levels on each side of the market.

Response

The response is a single object (for one specific instrument). The Level2UpdateEvent contains the same data, but is sent by the OMS when trades occur.

Parameter Type Description
UpdateId long integer Incrementing l2 update for this subscription
NumAccounts integer Number of accounts with orders at this px level
TimeStamp long integer UTC Millis
UpdateType int 0 = new price level, 1 = update to existing level, 2 = delete level
LastTradePx decimal The price at which the instrument was last traded.
NumOrders integer Number of orders at this px level
Price decimal The price at which the instrument traded.
InstrumentId integer The ID of the instrument
Quantity decimal Quantity available at a given Bid or Ask price (see Price above).
Side integer int 0 = Bid, 1 = Ask

UnsubscribeLevel2

Unsubscribes the user from a Level 2 Market Data Feed subscription.

Request

wss.send(JSON.stringify({
    "m": 0,
    "i": 0,
    "n": 'UnsubscribeLevel2',
    "o": '{"OMSId": 1, "InstrumentId": 1}'
}));

Request

Parameter Type Description
OMSId integer 1
InstrumentId integer The ID of the instrument being tracked by the Level 2 market data feed.

Response

The response is a single object (for one specific instrument). The Level2UpdateEvent contains the same data, but is sent by the OMS when trades occur.

Parameter Type Description
result boolean A successful receipt of the unsubscribe request returns true; and unsuccessful receipt (an error condition) returns false.
errormsg string A successful receipt of the unsubscribe request returns null;
the errormsg parameter for an unsuccessful request returns one of the following messages:
Not Authorized (errorcode 20)
Invalid Request (errorcode 100)
Operation Failed (errorcode 101)
Server Error (errorcode 102)
Resource Not Found (errorcode 104)
errorcode integer A successful receipt of the unsubscribe request returns 0. An unsuccessful receipt returns one of the errorcodes shown in the errormsg list.
detail string Message text that the system may send. Usually null

SubscribeTrades

Subscribes an authenticated user to the Trades Market Data Feed for a specific instrument. Each trade has two sides: Buy and Sell.
SubscribeTrades returns the response documented here for your immediate information, then periodically sends the OrderTradeEvent documented in SubscribeAccountEvents.

Request

wss.send(JSON.stringify({
    "m": 0,
    "i": 0,
    "n": 'SubscribeTrades',
    "o": '{"OMSId": 1, "InstrumentId": 1, "IncludeLastCount": 100}'
}));

Request

Parameter Type Description
OMSId integer 1
InstrumentId long integer The ID of the instrument whose trades will be reported.
IncludeLastCount integer Specifies the number of previous trades to retrieve in the immediate snapshot. Default is 100.

Response example.

[
  25346,
  1,
  0.22350592,
  0.11591156,
  830092795,
  830092796,
  1531738027321,
  1,
  1,
  1,
  0
]

[
  TradeId,
  InstrumentId,
  Quantity,
  Price,
  Order1,
  Order2,
  TradeTime,
  Direction,
  TakerSide,
  IsBlockTrade,
  ClientOrderId,
]

Response

Parameter Type Description
TradeID long integer The ID of this trade.
InstrumentId int The ID of the instrument (OMSInstrumentId)
Quantity decimal The quantity of the instrument traded.
Price decimal The price at which the instrument traded.
Order1 long integer The ID of one of the orders that resulted in the trade.
Order2 long integer The ID of the other order that resulted in the trade.
TradeTime long integer The time at which the trade took place. UTC time.
Direction int Effect of the trade on the instrument’s market price. One of: 1 Up
2 Down
TakerSide integer Which side of the trade took liquidity? One of:
0 Buy
1 Sell
The maker side of the trade provides liquidity by placing the order on the book (this can be a buy or a sell order). The other side takes the liquidity. It, too, can be buy-side or sell-side.
IsBlockTrade Boolean Was this a privately negotiated trade that was reported to the OMS? A private trade returns true; otherwise false. Default is false.
ClientOrderId long integer defaults to 0 unless it is a trade of the currently logged in session

UnsubscribeTrades

Unsubscribes a user from the Trades Market Data Feed.

Request

wss.send(JSON.stringify({
    "m": 0,
    "i": 0,
    "n": 'UnsubscribeTrades',
    "o": '{"OMSId": 1, "InstrumentId": 1}'
}));

Request

Parameter Type Description
OMSId integer 1
InstrumentId long integer The ID of the instrument being tracked by the trades market data feed.

Response

Parameter Type Description
result boolean A successful receipt of the unsubscribe request returns true; and unsuccessful receipt (an error condition) returns false.
errormsg string A successful receipt of the unsubscribe request returns null;
the errormsg parameter for an unsuccessful request returns one of the following messages:
Not Authorized (errorcode 20)
Invalid Request (errorcode 100)
Operation Failed (errorcode 101)
Server Error (errorcode 102)
Resource Not Found (errorcode 104)
errorcode integer A successful receipt of the unsubscribe request returns 0. An unsuccessful receipt returns one of the errorcodes shown in the errormsg list.
detail string Message text that the system may send. Usually null

GetTradesHistory

Retrieves a list of trades for the specified account, order ID, user, instrument, or starting and ending time stamp. The returned list begins at start index i, where i is an integer identifying a specific trade in reverse order; that is, the most recent trade has an index of 0. "Depth" is the count of trades to report backwards from StartIndex.

GetTradeHistory

Caution: You must coordinate StartIndex, Depth, StartTimeStamp, and EndTimeStamp to retrieve the historical information you need. As the diagram shows, it is possible to specify values (for example, EndTimeStamp and Depth) that can exclude information you may want (the red areas).

The owner of the trading venue determines how long to retain order history before archiving.

Note: In this call, "Depth" refers not to the depth of the order book, but to the count of trades to report.

All values in the call other than OMSId are optional.

wss.send(JSON.stringify({
    "m": 0,
    "i": 0,
    "n": 'GetTradesHistory',
    "o": '{
        "OMSId": 0,
        "AccountId": 0, 
        "InstrumentId": 0, 
        "TradeId": 0, 
        "OrderId": 0,
        "UserId": 0, 
        "StartTimestamp": 0,
        "EndTimestamp": 0,
        "Depth": 0,
        "StartIndex": 0,
        "ExecutionId": 0
      }'
}));

Request

Parameter Type Description
OMSId integer The ID of the Order Management System on which the trades took place. If no other values are specified, returns the trades associated with the default account for the logged-in user on this Order Management System.
AccountId integer The account ID that made the trades. The logged-in user must be associated with this account, although other users also can be associated with the account. If no account ID is supplied, the system assumes the default account for the logged-in user.
InstrumentId long integer The ID of the instrument whose history is reported. If no instrument ID is included, the system returns trades for all instruments associated with the account and OMS.
TradeId integer The ID of a specific trade. If specified, the call can return multiple states for a single trade.
OrderId integer The ID of the order resulting in the trade. If specified, the call returns all trades associated with the order.
UserId integer The ID of the logged-in user. If not specified, the call returns trades associated with the users belonging to the default account for the logged-in user of this OMS.
StartTimeStamp long integer The historical date and time at which to begin the trade report, in POSIX format and UTC time zone. If not specified, reverts to the start date of this account on the trading venue. See "Time– and Date-Stamp Formats" on page 8.
EndTimeStamp long integer Date at which to end the trade report, in POSIX format and UTC time zone. If not specified, uses the current time. See ""Time– and Date-Stamp Formats" on page 8.
Depth integer In this case, the count of trades to return, counting from the StartIndex. If not specified, returns all trades between BeginTimeStamp and EndTimeStamp, beginning at StartIndex.
StartIndex integer The starting index into the history of trades, from 0 (the most recent trade) and moving backwards in time. If not specified, defaults to 0.
ExecutionId integer The ID of the individual buy or sell execution. If not specified, returns all.

Response

The response returns an array, one element for each trade.

[
    {
        {
           "TradeTimeMS": 0,
           "Fee": 0,
           "FeeProductId": 0,
           "OrderOriginator": 0,
           "OMSId": 0,
           "ExecutionId": 0,
           "TradeId": 0,
           "OrderId": 0,
           "AccountId": 0,
           "SubAccountId": 0,
           "ClientOrderId": 0,
           "InstrumentId": 0,
           "Sides":{
                "Options": [
                    "Buy",
                    "Sell",
                    "Short",
                    "Unknown"
                ]
            },
            "Quantity": 0,
            "RemainingQuantity": 0,
            "Price": 0,
            "Value": 0,
            "TradeTime": 0,
            "CounterParty": "",
            "OrderTradeRevision": 0,
            "Direction": {
               "Options": [
                   "NoChange",
                   "UpTick",
                   "DownTick"
                ] 
            },
            "IsBlockTrade": false,
        }
    }
]
Parameter Type Description
TradeTimeMS long integer The time at which the trade took place, reported in Microsoft ticks format and UTC time zone. See "Time– and Date-Stamp Formats" on page 8.
Fee real The fee that applied to this trade, if any.
FeeProductId integer The ID of the product in which the fee is denominated.
OrderOriginator integer The ID of the user who entered the order on your side of the trade.
OMSId integer The ID of the Order Management System on which the trade took place.
ExecutionId integer The ID of your sell or buy side portion of the execution, individually.
TradeId integer The ID of the overall trade.
OrderId integer The ID of the order that resulted in the trade.
AccountId integer The ID of the account under which the trade was executed.
SubAccountId integer Not currently used.
ClientOrderId long integer A user-assigned ID for the order (like a purchase-order number assigned by a company). ClientOrderId defaults to 0.
InstrumentId long integer The ID of the instrument being traded.
Side string One of:
0 Buy
1 Sell
2 Short (reserved for future use) 3 Unknown (error condition)
Quantity real The quantity of the instrument being traded.
RemainingQuantity real Any quantity remaining in the order after this trade.