sgcWebSockets SignalRCore component

From sgcWebSockets 4.2.2 SignalRCore WebSocket API is supported. ASP.NET Core SignalR is an open-source library that simplifies adding real-time web functionality to app.

 

Features

  • Handles initial handshake between server and client.
  • Supports 3 times of invocations: normal invocations, non-blocking invocations and streaming invocations.

  • Can cancel any stream invocation at any time.

  • Notify server about completion messages with result positive or negative.
  • Publish messages to all channel subscribers.

  • Keep Alive connections.

 

Read more about SignalRCore Client Component.

 sgcWebSockets API Bitmex components

From sgcWebSockets 4.2.0 Bitmex WebSocket API is supported. Bitmex is a cryptocurrency exchange and derivative trading platform.

 

Features

  • By default user is identified by a name, but this can be customized passing more data: email, company, twitter...

  • Events to Authorize if a Channel can be created, if a member is allowed...

  • Every time a new member joins a channel, all members are notified.
  • Publish messages to all channel subscribers.

 

 

If TLS is enabled by sgcWebSockets client, by default certificate server is accepted and not verified. If certificate verification is required, follow next steps:

 

1. Handle OnSSLAfterCreateHandler event on client component and enable verification:

 

procedure TfrmWebSocketClient.WSClientSSLAfterCreateHandler(Sender: TObject; aType: TwsSSLHandler; aSSLHandler: TIdSSLIOHandlerSocketBase);

begin

  TIdSSLIOHandlerSocketOpenSSL(aSSLHandler).SSLOptions.VerifyMode := [sslvrfPeer];

  TIdSSLIOHandlerSocketOpenSSL(aSSLHandler).OnVerifyPeer := OnVerifyPeerEvent

end;

 

2. Create a new method to access server certificate info and accept connection or not

 

function OnVerifyPeerEvent(Certificate: TIdX509; AOk: Boolean; ADepth, AError: Integer): Boolean;

begin

  // if certificate is valid

  AOk := True;

  // if not is valid

  AOk := False;

end;

From sgcWebSockets 4.1.10 AppRTC is supported using TsgcWSPServer_AppRTC component.

This protocol uses code from https://github.com/webrtc/apprtc and sgcWebSocket server as signaling server, so you can run your own server to allow Broadcast Audio and Video.

Online demo use viagenie STUN/TURN server, for production environment, is recommended to use own TURN/STURN servers.

AppRTC Online Demo

 sgcWebSockets API Cex components

From sgcWebSockets 4.1.10 CEX.IO WebSocket API is supported. CEX is a cryptocurrency exchange and former Bitcoin cloud mining provider.

WebSocket API allows getting real-time notifications without sending extra requests, making it a faster way to obtain data from the exchange

Cex component has a property called Cex where you can fill API Keys provided by Cex to get access to your account data.

 

Message encoding

All messages are encoded in JSON format.

Prices are presented as strings to avoid rounding errors at JSON parsing on client side

Compression of WebSocket frames is not supported by server.

Time is presented as integer UNIX timestamp in seconds.

 

Authentication

To get access to CEX.IO WebSocket data, you should be authorized.

 

Log in to CEX.IO account.

Go to https://cex.io/trade/profile#/api page.

Select type of required permissions.

Click "Generate Key" button and save your secret key, as it will become inaccessible after activation.

Activate your key.

 

Connectivity

 

If a connected Socket is inactive for 15 seconds, CEX.IO server will send a PING message.

Only server can be an Initiator of PING request.

Server sends ping only to authenticated user.

The user has to respond with a PONG message. Otherwise, the WebSocket will be DISCONNECTED. This is handled automatically by library.

For authenticated user, in case there is no notification or ping from server within 15 seconds, it would be safer to send a request like 'ticker' or 'get-balance' and receive response, in order to ensure connectivity and authentication.

 

 

Public Channels

These channels don't require to Authenticate before. Responses from server are received by OnCexMessage event. 

 

SubscribeTickers: Ticker feed with only price of transaction made on all pairs (deprecated)

 

{

    "e": "tick",

    "data": {

        "symbol1": "BTC",

        "symbol2": "USD",

        "price": "428.0123"

    }

}

 

SubscribeChart: OHLCV chart feeds with Open, High, Low, Close, Volume numbers (deprecated)

 

{

    'e': 'ohlcv24',

    'pair': 'BTC:USD',

    'data': [

        '418.2936',

        '420.277',

        '412.09',

        '416.9778',

        '201451078368'

    ]

}

 

Subscribe Pair: Market Depth feed (deprecated)

 

{

    'e': 'md_groupped', 

    'data': {

        'pair': 'BTC:USD',

        'id': 11296131,

        'sell': {

            '427.5000': 1000000,

            '480.0000': 263544334,

            ...

        },

        'buy': {

            '385.0000': 3630000,

            '390.0000': 1452458642,

            ... 400+ pairs togather with 'sell' pairs

        }

    }

}

 

Subscribe Pair: Order Book feed (deprecated)

 

{

    'e': 'md', 

    'data': {

        'pair': 'BTC:USD',

        'buy_total': 63221099,

        'sell_total': 112430315118,

        'id': 11296131,

        'sell': [

            [426.45, 10000000],

            [426.5, 66088429300],

            [427, 1000000],

            ... 50 pairs overaall

        ],

        'buy': [

            [423.3, 4130702],

            [423.2701, 10641168],

            [423.2671, 1000000],

            ... 50 pairs overaall

        ]

    }

}

 

Private Channels

To access this channels, first call Authenticate method. Responses from server are received by OnCexMessage event. 

 

GetTicker

 

{

    "e": "ticker",

    "data": {

        "timestamp": "1471427037",

        "low": "290",

        "high": "290",

        "last": "290",

        "volume": "0.02062068",

        "volume30d": "14.38062068",

        "bid": 240,

        "ask": 290,

        "pair": [

            "BTC",

            "USD"

        ]

    },

    "oid": "1471427036908_1_ticker",

    "ok": "ok"

}

 

GetBalance

 

{

    "e": "get-balance",

    "data": {

           "balance": {

            'LTC': '10.00000000', 

            'USD': '1024.00',

            'RUB': '35087.98', 

            'EUR': '217.53', 

            'GHS': '10.00000000',

            'BTC': '9.00000000'

        },

           "obalance": {

              'BTC': '0.12000000',

              'USD': "512.00",

           },

       },

       "time": 1435927928597

    "oid": "1435927928274_2_get-balance",

    "ok": "ok"

}

 

SubscribeOrderBook

 

{

"e": "order-book-subscibe",

"data": {

   "timestamp": 1435927929,

   "bids": [

      [

         241.947,

         155.91626

      ],

      [

         241,

         981.1255

      ],

   ],

   "asks": [

      [

         241.95,

         15.4613

      ],

      [

         241.99,

         17.3303

      ],

   ],

   "pair": "BTC:USD",

   "id": 67809

},

"oid": "1435927928274_5_order-book-subscribe",

"ok": "ok"

}

 

UnSubscribeOrderBook

 

{

"e": "order-book-unsubscribe",

"data": {

   "pair": "BTC:USD"

},

"oid": "1435927928274_4_order-book-unsubscribe",

"ok": "ok"

}

 

 

GetOpenOrders

 

{

"e": "open-orders",

"data": [

   {

      "id": "2477098",

      "time": "1435927928618",

      "type": "buy",

      "price": "241.9477",

      "amount": "0.02000000",

      "pending": "0.02000000"

   },

   {

      "id": "2477101",

      "time": "1435927928634",

      "type": "sell",

      "price": "241.9493",

      "amount": "0.02000000",

      "pending": "0.02000000"

   }

],

"oid": "1435927928274_9_open-orders",

"ok": "ok"

}

 

 

PlaceOrder

 

{

"e": "place-order",

"data": {

   "complete": false,

   "id": "2477098",

   "time": 1435927928618,

   "pending": "0.02000000",

   "amount": "0.02000000",

   "type": "buy",

   "price": "241.9477"

},

"oid": "1435927928274_7_place-order",

"ok": "ok"

}

 

 

CancelReplaceOrder

 

{

"e": "cancel-replace-order",

"data": {

   "complete": false,

   "id": "2689009",

   "time": 1443464955904,

   "pending": "0.04000000",

   "amount": "0.04000000",

   "type": "buy",

   "price": "243.25"

},

"oid": "1443464955209_16_cancel-replace-order",

"ok": "ok"

}

 

GetOrderRequest

 

In CEX.IO system, orders can be present in trade engine or in archive database. There can be time periods (~2 seconds or more), when order is done/canceled, but still not moved to archive database. That means, you cannot see it using calls: archived-orders/open-orders. This call allows to get order information in any case. Responses can have different format depending on orders location.

 

{

"e": "get-order",

"data": {

   "user": "XXX",

   "type": "buy",

   "symbol1": "BTC",

   "symbol2": "USD",

   "amount": "0.02000000",

   "remains": "0.02000000",

   "price": "50.75",

   "time": 1450214742160,

   "tradingFeeStrategy": "fixedFee",

   "tradingFeeBuy": "5",

   "tradingFeeSell": "5",

   "tradingFeeUserVolumeAmount": "nil",

   "a:USD:c": "1.08",

   "a:USD:s": "1.08",

   "a:USD:d": "0.00",

   "status": "a",

   "orderId": "5582060"

},

"oid": "1450214742135_10_get-order",

"ok": "ok"

}

 

CancelOrderRequest

 

{

"e": "cancel-order",

"data": {

   "order_id": "2477098"

   "time": 1443468122895

},

"oid": "1435927928274_12_cancel-order",

"ok": "ok"

}

 

GetArchivedOrders

 

{

"e": "archived-orders",

"data": [

   {

       "type": "buy",

       "symbol1": "BTC",

       "symbol2": "USD",

       "amount": 0,

       "amount2": 5000,

       "remains": 0,

       "time": "2015-04-17T10:46:27.971Z",

       "tradingFeeBuy": "2",

       "tradingFeeSell": "2",

       "ta:USD": "49.00",

       "fa:USD": "0.98",

       "orderId": "2340298",

       "status": "d",

       "a:BTC:cds": "0.18151851",

       "a:USD:cds": "50.00",

       "f:USD:cds": "0.98"

   },

   {

       "type": "buy",

       "symbol1": "BTC",

       "symbol2": "USD",

       "amount": 0,

       "amount2": 10000,

       "remains": 0,

       "time": "2015-04-08T15:46:04.651Z",

       "tradingFeeBuy": "2.99",

       "tradingFeeSell": "2.99",

       "ta:USD": "97.08",

       "fa:USD": "2.91",

       "orderId": "2265315",

       "status": "d",

       "a:BTC:cds": "0.39869578",

       "a:USD:cds": "100.00",

       "f:USD:cds": "2.91"

    }

],

"oid": "1435927928274    15_archived-orders",

"ok": "ok"

}

 

OpenPosition

 

{

    "e": "open-position",

    "oid": "1435927928274_7_open-position",

    "data": {   

        'amount': '1',

        'symbol': 'BTC',

        "pair": [

            "BTC",

            "USD"

        ],

        'leverage': '2',

        'ptype': 'long',

        'anySlippage': 'true',

        'eoprice': '650.3232',

        'stopLossPrice': '600.3232'

    }

}

 

GetPosition

 

{

  "e": "get_position",

  "ok": "ok",

  "data": {

    "user": "ud100036721",

    "pair": "BTC:USD",

    "amount": "1.00000000",

    "symbol": "BTC",

    "msymbol": "USD",

    "omamount": "1528.77",

    "lsymbol": "USD",

    "lamount": "3057.53",

    "slamount": "3380.11",

    "leverage": "3",

    "stopLossPrice": "3380.1031",

    "dfl": "3380.10310000",

    "flPrice": "3057.53333333",

    "otime": 1513002370342,

    "psymbol": "BTC",

    "ptype": "long",

    "ofee": "10",

    "pfee": "10",

    "cfee": "10",

    "tfeeAmount": "152.88",

    "rinterval": "14400000",

    "okind": "Manual",

    "a:BTC:c": "1.00000000",

    "a:BTC:s": "1.00000000",

    "oorder": "89101551",

    "pamount": "1.00000000",

    "lremains": "3057.53",

    "slremains": "3380.11",

    "oprice": "4586.3000",

    "status": "a",

    "id": "125531",

    "a:USD:cds": "4739.18"

  }

}

 

GetOpenPositions

 

{

    'e': 'open_positions',

    "oid": "1435927928256_7_open-positions",

    'ok': 'ok',

    'data': [

        {

            'user': 'ud100036721',

            'id': '104102',

            'otime': 1475602208467,

            'symbol': 'BTC',

            'amount': '1.00000000',

            'leverage': '2',

            'ptype': 'long',

            'psymbol': 'BTC',

            'msymbol': 'USD',

            'lsymbol': 'USD',

            'pair': 'BTC:USD',

            'oprice': '607.5000'

            'stopLossPrice': '520.3232',

            'ofee': '1',

            'pfee': '3',

            'cfee': '4',

            'tfeeAmount': '3.04',

            'pamount': '1.00000000',

            'omamount': '303.75',

            'lamount': '303.75',

            'oorder': '34106774',            

            'rinterval': '14400000',

            'dfl': '520.32320000',

            'slamount': '520.33',

            'slremains': '520.33',

            'lremains': '303.75',

            'flPrice': '303.75000000',

            'a:BTC:c': '1.00000000',

            'a:BTC:s': '1.00000000',

            'a:USD:cds': '610.54',

        },

        ...

    ]

}

 

ClosePosition

 

{   

    'e': 'close_position',

    "oid": "1435927928364_7_close-position",

    'ok': 'ok',

    'data': {

        'id': 104034,

        'ctime': 1475484981063,

        'ptype': 'long',

        'msymbol': 'USD'

        'pair': {

            'symbol1': 'BTC',

            'symbol2': 'USD'

        }

        'price': '607.1700',

        'profit': '-12.48',

    }

}

 

 sgcWebSockets API Huobi components

From sgcWebSockets 4.1.9 Huobi WebSocket API is supported.

Huobi is an international multi-language cryptocurrency exchange.

 

Methods

 SubscribeKLine

   K line data, including the opening price, closing price, highest price, lowest price, volume, turnover, number of transactions, etc. per unit time interval $period Optional values: { 1min, 5min, 15min, 30min, 60min, 4hour ,1day, 1mon, 1week, 1year }

 

{

  "status": "ok",

  "rep": "market.btcusdt.kline.1min",

  "tick": [

    {

      "amount": 1.6206,

      "count":  3,

      "id":     1494465840,

      "open":   9887.00,

      "close":  9885.00,

      "low":    9885.00,

      "high":   9887.00,

      "vol":    16021.632026

    },

    {

      "amount": 2.2124,

      "count":  6,

      "id":     1494465900,

      "open":   9885.00,

      "close":  9880.00,

      "low":    9880.00,

      "high":   9885.00,

      "vol":    21859.023500

    }

  ]

}

 

 

  SubscribeMarketDepth

  Handbook depth, according to different step aggregation, buy one, buy two, buy three, and sell one, sell two, sell three, etc. type Optional value: { step0, step1, step2, step3, step4, step5, percent10 } (combination depth 0-5); when step0, no depth is merged

 

{

  "ch": "market.btcusdt.depth.step0",

  "ts": 1489474082831,

  "tick": {

    "bids": [

    [9999.3900,0.0098], // [price, amount]

    [9992.5947,0.0560],

    // more Market Depth data here

    ]

    "asks": [

    [10010.9800,0.0099]

    [10011.3900,2.0000]

    //more data here

    ]

  }

}

 

 

  SubscribeTradeDetail

  Transaction record, including transaction price, volume, direction of transaction, etc.

 

{

  "ch": "market.btcusdt.trade.detail",

  "ts": 1489474082831,

  "tick": {

        "id": 14650745135,

        "ts": 1533265950234,

        "data": [

            {

                "amount": 0.0099,

                "ts": 1533265950234,

                "id": 146507451359183894799,

                "price": 401.74,

                "direction": "buy"

            },

            // more Trade Detail data here

        ]

    }

  

  ]

  }

}

  

  SubscribeMarketDetail

  Last 24 hours of volume, turnover, opening price, closing price, highest price, lowest price, number of transactions, etc.

 

{

  "rep": "market.btcusdt.detail",

  "status": "ok",

  "id": "id12",

  "tick": {

    "amount": 12224.2922,

    "open":   9790.52,

    "close":  10195.00,

    "high":   10300.00,

    "ts":     1494496390000,

    "id":     1494496390,

    "count":  15195,

    "low":    9657.00,

    "vol":    121906001.754751

  }

}

  

  SubscribeMarketTickers

  Information on the daily K line, the last 24 hours of trading, etc.

 

 sgcWebSockets API Binance components

From sgcWebSockets 4.1.8 BinanceWebSocket API is supported.

Binance is an international multi-language cryptocurrency exchange.

 

Properties

  Streams: contains list of streams.

 

Methods

  AddAggregateTrades

    The Aggregate Trade Streams push trade information that is aggregated for a single taker order.

{

  "e": "aggTrade",  // Event type

  "E": 123456789,   // Event time

  "s": "BNBBTC",    // Symbol

  "a": 12345,       // Aggregate trade ID

  "p": "0.001",     // Price

  "q": "100",       // Quantity

  "f": 100,         // First trade ID

  "l": 105,         // Last trade ID

  "T": 123456785,   // Trade time

  "m": true,        // Is the buyer the market maker?

  "M": true         // Ignore.

}

 

  AddTrades

    The Trade Streams push raw trade information; each trade has a unique buyer and seller.

{

  "e": "trade",     // Event type

  "E": 123456789,   // Event time

  "s": "BNBBTC",    // Symbol

  "t": 12345,       // Trade ID

  "p": "0.001",     // Price

  "q": "100",       // Quantity

  "b": 88,          // Buyer order Id

  "a": 50,          // Seller order Id

  "T": 123456785,   // Trade time

  "m": true,        // Is the buyer the market maker?

  "M": true         // Ignore.

}

 

  AddKline

    The Kline/Candlestick Stream push updates to the current klines/candlestick every second.

{

  "e": "kline",     // Event type

  "E": 123456789,   // Event time

  "s": "BNBBTC",    // Symbol

  "k": {

    "t": 123400000, // Kline start time

    "T": 123460000, // Kline close time

    "s": "BNBBTC",  // Symbol

    "i": "1m",      // Interval

    "f": 100,       // First trade ID

    "L": 200,       // Last trade ID

    "o": "0.0010",  // Open price

    "c": "0.0020",  // Close price

    "h": "0.0025",  // High price

    "l": "0.0015",  // Low price

    "v": "1000",    // Base asset volume

    "n": 100,       // Number of trades

    "x": false,     // Is this kline closed?

    "q": "1.0000",  // Quote asset volume

    "V": "500",     // Taker buy base asset volume

    "Q": "0.500",   // Taker buy quote asset volume

    "B": "123456"   // Ignore

  }

}

 

  AddTicker

    24hr Ticker statistics for a single symbol pushed every second

{

  "e": "24hrTicker",  // Event type

  "E": 123456789,     // Event time

  "s": "BNBBTC",      // Symbol

  "p": "0.0015",      // Price change

  "P": "250.00",      // Price change percent

  "w": "0.0018",      // Weighted average price

  "x": "0.0009",      // Previous day's close price

  "c": "0.0025",      // Current day's close price

  "Q": "10",          // Close trade's quantity

  "b": "0.0024",      // Best bid price

  "B": "10",          // Best bid quantity

  "a": "0.0026",      // Best ask price

  "A": "100",         // Best ask quantity

  "o": "0.0010",      // Open price

  "h": "0.0025",      // High price

  "l": "0.0010",      // Low price

  "v": "10000",       // Total traded base asset volume

  "q": "18",          // Total traded quote asset volume

  "O": 0,             // Statistics open time

  "C": 86400000,      // Statistics close time

  "F": 0,             // First trade ID

  "L": 18150,         // Last trade Id

  "n": 18151          // Total number of trades

}

 

 

  AddAllMarketTickers

    24hr Ticker statistics for all symbols in an array pushed every second

[

  {

    // Same as <symbol>@ticker payload

  }

]

 

  AddPartialBookDepth

    Top <levels> bids and asks, pushed every second. Valid <levels> are 5, 10, or 20.

{

  "lastUpdateId": 160,  // Last update ID

  "bids": [             // Bids to be updated

    [

      "0.0024",         // price level to be updated

      "10",             // quantity

      []                // ignore

    ]

  ],

  "asks": [             // Asks to be updated

    [

      "0.0026",         // price level to be updated

      "100",            // quantity

      []                // ignore

    ]

  ]

}

 

  AddDiffDepth

    Order book price and quantity depth updates used to locally manage an order book pushed every second.

{

  "e": "depthUpdate", // Event type

  "E": 123456789,     // Event time

  "s": "BNBBTC",      // Symbol

  "U": 157,           // First update ID in event

  "u": 160,           // Final update ID in event

  "b": [              // Bids to be updated

    [

      "0.0024",       // price level to be updated

      "10",

      []              // ignore

    ]

  ],

  "a": [              // Asks to be updated

    [

      "0.0026",       // price level to be updated

      "100",          // quantity

      []              // ignore

    ]

  ]

}

 

 sgcWebSockets API Bitstamp components

From sgcWebSockets 4.1.8 BinanceWebSocket API is supported.

Binance is an international multi-language cryptocurrency exchange.

 

Methods

 

SubscribeTicker: get live trades from currency selected (if no currency, by default is BTC/USD). JSON data: 

Streams (JSON)
id Trade unique ID.
amount Trade amount.
price Trade price.
type Trade type (0 - buy; 1 - sell).
timestamp Trade timestamp.
buy_order_id Trade buy order id.
sell_order_id Trade sell order id.

 

SubscribeOrderBook: get order book from currency selected (if no currency, by default is BTC/USD). JSON data: 

Streams (JSON)
bids List of tops 100 bids.
asks List of top 100 asks.
timestamp Order book timestamp.

 

SubscribeFullOrderBook: get full order book from currency selected (if no currency, by default is BTC/USD). JSON data: 

bids List of changed bids since last broadcast.
asks List of asks since last broadcast.

 

SubscribeOrders: get live orders from currency selected (if no currency, by default is BTC/USD). JSON data: 

id Order ID.
amount Order amount.
price Order price.
order_type Order type (0 - buy; 1 - sell).
datetime Order datetime.

 

 

From sgcWebSockets 4.1.7 version, SignalR WebSocket API is supported.

SignalR component uses WebSocket as trasport to connect to a SignalR server, if this transport is not supported, an error will be raised. SignalR client component has a property called SignalR where you can set following data:   

  • Hubs: containins a list of hubs the client is subscribing to.
  • ProtocolVersion:  the version of protocol used by the client, supports protocol versions from 1.2 to 1.5
  • UserAgent: user agent used to connect to SignalR server. 

    

Hubs Messages 

Hubs API makes it possible to invoke server methods from the client and client methods from the server. The protocol used for persistent connection is not rich enough to allow expressing RPC (remote procedure call) semantics. It does not mean however that the protocol used for hub connections is completely different from the protocol used for persistent connections. Rather, the protocol used for hub connections is mostly an extension of the protocol for persistent connections.   

When a client invokes a server method it no longer sends a free-flow string as it was for persistent connections. Instead it sends a JSon string containing all necessary information needed to invoke the method. Here is a sample message a client would send to invoke a server method:   

WriteData('{"H":"chathub","M":"Send","A":["Delphi Client","Test message"],"I":0}');   

The payload has the following properties:

I – invocation identifier – allows to match up responses with requests

H – the name of the hub

M – the name of the method

A – arguments (an array, can be empty if the method does not have any parameters)       

 

Component has the following events:   

 

OnSignalRConnect 

When client connects successfully to server, this event is raised.    

 

OnSignalRDisconnect 

When client is disconnected from server, this event is raised.   

 

OnSignalRError 

When there is any error in websocket connection.   

 

OnSignalRMessage 

The protocol used for persistent connection is quite simple. Messages sent to the server are just raw strings. There isn’t any specific format they have to be in. Messages sent to the client are more structured. The properties you can find in the message are as follows:   C – message id, present for all non-KeepAlive messages M – an array containing actual data.   

{"C":"d-9B7A6976-B,2|C,2","M":["Welcome!"]}   

 

OnSignalRResult 

When a server method is invoked the server returns a confirmation that the invocation has completed by sending the invocation id to the client and – if the method returned a value – the return value, or – if invoking the method failed – the error. Here are sample results of a server method call:   

{"I":"0"}   A server void method whose invocation identifier was "0" completed successfully.   

"{"I":"0", "R":42}   A server method returning a number whose invocation identifier was "0" completed successfully and returned the value 42.   

{"I":"0", "E":"Error occurred"}   

 

OnSignalRKeepAlive 

This event is raised when a KeepAlive message is received from server. 

From sgcWebSockets 4.1.7, Bittrex WebSocket API is supported.

 

The Bittrex Websocket API is implemented using SignalR.

Bittrex component has a property called Bittrex where you can fill API Keys provided by Bittrex to get access to your account data.

 

Authenticate

Verifies a user’s identity to the server and begins receiving account-level notifications.

Needs an ApiKey and ApiSecret, which can be obtained in Bittrex user page.

Updates are received OnBittrexMessage event, where Callback is "OrderDelta" or "BalanceDelta".

JSON Order Response

 

{

    AccountUuid : Guid,

    Nonce       : int,

    Type        : int,

    Order: 

    {

        Uuid              : guid,

        Id                : long,

        OrderUuid         : guid,

        Exchange          : string,

        OrderType         : string,

        Quantity          : decimal,

        QuantityRemaining : decimal,

        Limit             : decimal,

        CommissionPaid    : decimal,

        Price             : decimal,

        PricePerUnit      : decimal,

        Opened            : date,

        Closed            : date,

        IsOpen            : bool,

        CancelInitiated   : bool,

        ImmediateOrCancel : bool,

        IsConditional     : bool,

        Condition         : string,

        ConditionTarget   : decimal,

        Updated           : date

    }

}

 

JSON Balance Response

 

{

    Nonce : int,

    Delta : 

    {

        Uuid          : guid,

        AccountId     : int,

        Currency      : string,

        Balance       : decimal,

        Available     : decimal,

        Pending       : decimal,

        CryptoAddress : string,

        Requested     : bool,

        Updated       : date,

        AutoSell      : bool

    }

}

 

QueryExchangeState

Allows the caller to retrieve the full order book for a specific market. There is only one Parameter called MarketName, e.g. BTC-ETH

Updates are received OnBittrexMessage event, where Callback is "QueryExchangeState"

JSON Response

 

{

    MarketName : string,

    Nonce      : int,

    Buys: 

    [

        {

            Quantity : decimal,

            Rate     : decimal

        }

    ],

    Sells: 

    [

        {

            Quantity : decimal,

            Rate     : decimal

        }

    ],

    Fills: 

    [

        {

            Id        : int,

            TimeStamp : date,

            Quantity  : decimal,

            Price     : decimal,

            Total     : decimal,

            FillType  : string,

            OrderType : string

        }

    ]

}

 

QuerySummaryState

Allows the caller to retrieve the full state for all markets. 

Updates are received OnBittrexMessage event, where Callback is "QuerySummaryState"

JSON Response

 

{

    Nonce     : int,

    Summaries : 

    [

        {

            MarketName     : string,

            High           : decimal,

            Low            : decimal,

            Volume         : decimal,

            Last           : decimal,

            BaseVolume     : decimal,

            TimeStamp      : date,

            Bid            : decimal,

            Ask            : decimal,

            OpenBuyOrders  : int,

            OpenSellOrders : int,

            PrevDay        : decimal,

            Created        : date

        }

    ]

}

 

SubscribeToExchangeDeltas

Allows the caller to receive real-time updates to the state of a single market. There is only one Parameter called MarketName, e.g. BTC-ETH

If user is subscribed to the feed, OnBittrexSubscribed event will be raised.

Updates are received OnBittrexMessage event, where Callback is "MarketDelta"

JSON Response

 

{

    MarketName : string,

    Nonce      : int,

    Buys: 

    [

        {

            Type     : int,

            Rate     : decimal,

            Quantity : decimal

        }

    ],

    Sells: 

    [

        {

            Type     : int,

            Rate     : decimal,

            Quantity : decimal

        }

    ],

    Fills: 

    [

        {

            FillId    : int,

            OrderType : string,

            Rate      : decimal,

            Quantity  : decimal,

            TimeStamp : date

        }

    ]

}

 

SubscribeToSummaryDeltas

Allows the caller to receive real-time updates of the state of all markets. 

If user is subscribed to the feed, OnBittrexSubscribed event will be raised.

Updates are received OnBittrexMessage event, where Callback is "SummaryDelta"

JSON Response

 

{

    Nonce : int,

    Deltas : 

    [

        {

            MarketName     : string,

            High           : decimal,

            Low            : decimal,

            Volume         : decimal,

            Last           : decimal,

            BaseVolume     : decimal,

            TimeStamp      : date,

            Bid            : decimal,

            Ask            : decimal,

            OpenBuyOrders  : int,

            OpenSellOrders : int,

            PrevDay        : decimal,

            Created        : date

        }

    ]

}

 

SubscribeToSummaryLiteDeltas

Allows the caller to receive real-time updates of the state of all markets but only market name, the last price, and the base currency  

If user is subscribed to the feed, OnBittrexSubscribed event will be raised.

Updates are received OnBittrexMessage event, where Callback is "LiteSummaryDelta"

JSON Response

 

{

    Deltas : 

    [

        {

            MarketName : string,

            Last       : decimal,

            BaseVolume : decimal

        }

    ]

}

 

 

From sgcWebSockets 4.1.6 STOMP protocol is supported.

STOMP is the Simple (or Streaming) Text Orientated Messaging Protocol. STOMP provides an interoperable wire format so that STOMP clients can communicate with any STOMP message broker to provide easy and widespread messaging interoperability among many languages, platforms and brokers.

Our STOMP client components supports following STOMP versions: 1.0, 1.1 and 1.2.

 

Use

This is Client Protocol STOMP Component, you need to drop this component in the form and select a TsgcWebSocketClient Component using Client Property.

 

Methods

  Send: The SEND frame sends a message to a destination in the messaging system.

  Subscribe: The SUBSCRIBE frame is used to register to listen to a given destination.

  UnSubscribe: The UNSUBSCRIBE frame is used to remove an existing subscription.

  ACK: ACK is used to acknowledge consumption of a message from a subscription.

  NACK: NACK is the opposite of ACK. It is used to tell the server that the client did not consume the message.

  BeginTransaction: is used to start a transaction. Transactions in this case apply to sending and acknowledging - any messages sent or acknowledged during a transaction will be processed atomically based on the transaction.

  CommitTransaction: is used to commit a transaction in progress.

  AbortTransaction: is used to roll back a transaction in progress.

  Disconnect: use to graceful shutdown connection, where the client is assured that all previous frames have been received by the server.

  

Events

  OnSTOMPConnected: this event is fired after a new connection is established.

    version : The version of the STOMP protocol the session will be using. See Protocol Negotiation for more details.

    STOMP 1.2 servers MAY set the following headers:

    heart-beat : The Heart-beating settings.

    session : A session identifier that uniquely identifies the session.

    server : A field that contains information about the STOMP server. The field MUST contain a server-name field and MAY be followed by optional comment fields delimited by a space character.

 

  OnSTOMPMessage: this event is fired when client receives a message.

  The MESSAGE frame MUST include a destination header indicating the destination the message was sent to. If the message has been sent using STOMP, this destination header SHOULD be identical to the one used in the corresponding SEND frame.

  The MESSAGE frame MUST also contain a message-id header with a unique identifier for that message and a subscription header matching the identifier of the subscription that is receiving the message.

  If the message is received from a subscription that requires explicit acknowledgment (either client or client-individual mode) then the MESSAGE frame MUST also contain an ack header with an arbitrary value. This header will be used to relate the message to a subsequent ACK or NACK frame.

  MESSAGE frames SHOULD include a content-length header and a content-type header if a body is present.

  MESSAGE frames will also include all user defined headers that were present when the message was sent to the destination in addition to the server specific headers that MAY get added to the frame.

 

  OnSTOMPReceipt: this event is fired once a server has successfully processed a client frame that requests a receipt.

  A RECEIPT frame is an acknowledgment that the corresponding client frame has been processed by the server. Since STOMP is stream based, the receipt is also a cumulative acknowledgment that all the previous frames have been received by the server. However, these previous frames may not yet be fully processed. If the client disconnects, previously received frames SHOULD continue to get processed by the server.

 

  OnSTOMPError: this event is fired  if something goes wrong.

  The ERROR frame SHOULD contain a message header with a short description of the error, and the body MAY contain more detailed information (or MAY be empty).

  If the error is related to a specific frame sent from the client, the server SHOULD add additional headers to help identify the original frame that caused the error. For example, if the frame included a receipt header, the ERROR frame SHOULD set the receipt-id header to match the value of the receipt header of the frame which the error is related to.

  ERROR frames SHOULD include a content-length header and a content-type header if a body is present.

  

Properties

 Authentication: disabled by default, if True an UserName and Password are sent to server to try user authentication.

 HeartBeat: Heart-beating can optionally be used to test the healthiness of the underlying TCP connection and to make sure that the remote end is alive and kicking. In order to enable heart-beating, each party has to declare what it can do and what it would like the other party to do. 0 means it cannot send/receive heart-beats, otherwise it is the desired number of milliseconds between heart-beats.

 Options: The name of a virtual host that the client wishes to connect to. It is recommended clients set this to the host name that the socket was established against, or to any name of their choosing. If this header does not match a known virtual host, servers supporting virtual hosting MAY select a default virtual host or reject the connection.

 Versions: Set which STOMP versions are supported.

Configure WebSocket client to connect to a websocket server is very easy, find below some examples which show how configure client, there are basically 2 methods:

 

Decode Server Parameters

ws://echo.websocket.org

Client.Host := 'echo.websocket.org;

Client.Port := 80;

Client.TLS := False;

 

wss://echo.websocket.org

Client.Host := 'echo.websocket.org';

Client.Port := 443;

Client.TLS := True;

 

wss://ws.binaryws.com/websockets/v3?app_id=1089

Client.Host := 'ws.binaryws.com';

Client.Port := 443;

Client.Options.Parameters := '/websockets/v3?app_id=1089';

 

Set URL Property (decodes server parameters automatically)

ws://echo.websocket.org

 

Client.URL := 'ws://echo.websocket.org';

 

wss://echo.websocket.org

Client.URL := 'wss://echo.websocket.org';

 

 

wss://ws.binaryws.com/websockets/v3?app_id=1089

Client.URL := 'wss://ws.binaryws.com/websockets/v3?app_Id=1089/';

 

Once websocket client is configured, just call Client.Active := True to connect to websocket server.