Skip to Content

General WebSocket Overview

This WebSocket allows you to receive real-time updates on your orders, positions, trades, price alerts and EDIS status over a single connection.

This guide provides instructions on integrating the General WebSocket into any programming language.

USE CASE

Get your order, trade and position updates pushed to your app instead of polling the Order Book, Trade Book or Positions.

Events

Key points

  • Connect to wss://socket.fyers.in/trade/v3 with an authorization header in appId:accessToken format.
  • Subscribe with T set to SUB_ORD, SUB_T set to 1 and the actions you want in SLIST: orders, trades, positions, edis, pricealerts or login. Use SUB_T -1 to unsubscribe.
  • Send a ping message at regular intervals. A pong reply means the connection is alive.
  • Read the top-level key of each message (orders, trades, positions, pricealerts) to know which event it is. The Python SDK subscribes with OnOrders, OnTrades, OnPositions and OnGeneral.
  • Keep a single WebSocket connection instance open at a time.

Connect

Details

To connect to the General WebSocket, the below two input params are mandate. Based on the programming language chosen, respective socket connection libraries can be used. For reference, the sample code for socket connection is written in Python.
Mandatory connection parameters

Pass the websocket endpoint and an authorization header in <appId:accessToken> format.

Websocket endpoint: wss://socket.fyers.in/trade/v3

Header

Format: <appId:accessToken>

Sample header format: 7ABXUX38S-100:eyJ0eXAi**********qiTnzd2lGwS17s

The connection uses parameters and callback functions on_message, on_error, on_close, and on_open, which are required in the Python socket connection library and would change as per the other programming library used. A sample callback function is shared below.

Note

Handle accordingly in your programming language.

Connection response

On success: returns the socket object.

On failure: possible error status code 403.

Error: Handshake status 403 Forbidden

Handshake status 403 Forbidden -+-+- {'date': 'Tue, 19 Dec 2023 04:46:45 GMT', 'content-length': '0', 'connection': 'keep-alive', 'cf-cache-status': 'DYNAMIC', 'set-cookie': '__cf_bm=BOE16LGB7NHpNqW0AJOuFN1rcL3Q9TgnhmtpBfb3.Wk-1702961205-1- AfmECmK9cbVA2XGvkpx+jFuXyRsJET/ZOQYmw3LyZJ68pYLZTgtpbalvNs09ECZZ4GpPiogeYGhhFo+3PCp20nE=; path=/; expires=Tue, 19-Dec-23 05:16:45 GMT; domain=.fyers.in; HttpOnly; Secure', 'server': 'cloudflare', 'cf-ray': '837d00eec8ed17b6-MAA'} -+-+- b''

  • Reason: this error will come when your accessToken is wrong.
  • How to solve: provide the correct accessToken. AccessToken format: <appID:accesstoken>.

Error: Handshake status 404 Not Found

Handshake status 404 Not Found -+-+- {'date': 'Tue, 19 Dec 2023 10:04:35 GMT', 'content-type': 'text/plain; charset=utf-8', 'content-length': '0', 'connection': 'keep-alive', 'cf-cache-status': 'DYNAMIC', 'set-cookie': '__cf_bm=I5oN6zdeKjfGsicqFiXZ57J5SX2IjsFDspaLIEGKPDE-1702980275-1-Ae+ldjrb3WfSuM7yNOzo3ykOIBQ1m+50QqcIqU26A+wqPIHhIEIGSy9kT2OG3OWNI0hwcmh7U+PnJ/aWWhz6fOA=; path=/; expires=Tue, 19-Dec-23 10:34:35 GMT; domain=.fyers.in; HttpOnly; Secure', 'server': 'cloudflare', 'cf-ray': '837ed28169c817ae-MAA'} -+-+- b''

  • Reason: socket connection URL would be wrong.
  • How to solve: provide a valid URL.

Sample callback function: for more reference, see the on_open callback in the Python request sample.

Good to know
  • This is the General WebSocket endpoint for account events. Live market data uses the separate Data Socket.
  • Connecting alone does not deliver any data. Subscribe to the actions you want once the connection is open.
  • The Python SDK sends the access token in the authorization header. With your own client, send <appId:accessToken> in the header.
  • With order_ws.FyersOrderSocket, the callbacks are on_connect, on_close, on_error, on_orders, on_trades, on_positions and on_general. Subscribe inside on_connect, then call keep_running().
  • The SDK starts its ping loop as soon as the connection opens. With your own client, send ping yourself (see Ping method).
  • Create only one WebSocket connection instance at a time, as advised in the WebSocket guidance.

Full reference and samples: General WebSocket - Connect.

Subscribe

Details

Once the connection is established, it is required to subscribe for required actions to get the data. To subscribe for different actions, create a message data, which would be the string format for json node.
Json node params

Convert the json to string and send this message to the socket to subscribe for the action_data mentioned.

message

message = json.dumps({ "T": "SUB_ORD", "SLIST": action_data, "SUB_T": 1 })

T Type: String
value: SUB_ORD (Fixed)

action_data Type: List/Array
Value: orders trades positions edis pricealerts login

Based on the list passed in action_data, web_socket data will be received.

SUB_T Type: Integer
Value: 1 (value 1 is for subscribing and -1 for unsubscribe)

Sample response and socket payload

Once subscribed successfully, for any action triggered, data will be received through the socket. If a callback function is defined, it receives that data. The response is a string in Python and an ArrayBuffer in Node. In another language, convert the payload to a string, then parse it.

Sample response

{'code': 1605, 'message': 'Successfully subscribed', 's': 'ok'}

Type: string

Value

{"orders":{"client_id":"XP0001","exchange":10,"fy_token":"10100000001628","id":"23121800292158","id_fyers":"df013f50-6925-4e2d-ba0f-0becf1229298","instrument":0,"lot_size":1,"offline_flag":false,"oms_flag":"K:1","ord_source":"W","ord_status":20,"ord_type":2,"ordertag":"2:Untagged","org_ord_status":4,"pan":"FYxxxxxx0S","precision":2,"price_multiplier":1,"product_type":"CNC","qty":1,"qty_multiplier":1,"qty_remaining":1,"report_type":"New Ack","segment":10,"status_msg":"New Ack","symbol":"NSE:BECTORFOOD-EQ","symbol_desc":"MRS BECTORS FOOD SPE LTD","symbol_exch":"BECTORFOOD","tick_size":0.05,"time_epoch_oms":1702887690,"time_exch":"NA","time_oms":"18-Dec-2023 13:51:30","tran_side":1,"update_time_epoch_oms":1702887690,"update_time_exch":"01-Jan-1970 05:30:00","validity":"DAY"},"s":"ok"}

Note
  1. The response is a string in Python and an arraybuffer in Node. Check the format you receive from the websocket library for your language.
  2. Convert the data to a string if it is not already a string, then parse that string to JSON. The JSON will contain one of these keys: orders, trades, or positions.
  3. The key identifies the update type. orders is an order update, trades is a trades update, and positions is a positions update.
  4. In the FYERS SDK, the raw socket response is parsed to keep required keys and remove unnecessary keys.

Parsed Data

{
  "s": "ok",
  "orders": {
    "clientId": "XP03754",
    "id": "23121800388066",
    "qty": 1,
    "remainingQuantity": 1,
    "type": 2,
    "fyToken": "10100000002705",
    "exchange": 10,
    "segment": 10,
    "symbol": "NSE:PRAJIND-EQ",
    "instrument": 0,
    "offlineOrder": false,
    "orderDateTime": "18-Dec-2023 16:33:24",
    "orderValidity": "DAY",
    "productType": "CNC",
    "side": 1,
    "status": 4,
    "source": "W",
    "ex_sym": "PRAJIND",
    "description": "PRAJ INDUSTRIES LTD",
    "orderNumStatus": "23121800388066:4"
  }
}
  • All the keys information for orders updates are available there: Link
  • All the keys information for trades updates are available there: Link
  • All the keys information for positions updates are available there: Link

Internal mapping from raw keys to the final parsed data:

{
  "position_mapper": {
    "symbol": "symbol",
    "id": "id",
    "buy_avg": "buyAvg",
    "buy_qty": "buyQty",
    "buy_val": "buyVal",
    "sell_avg": "sellAvg",
    "sell_qty": "sellQty",
    "sell_val": "sellVal",
    "net_avg": "netAvg",
    "net_qty": "netQty",
    "tran_side": "side",
    "qty": "qty",
    "product_type": "productType",
    "pl_realized": "realized_profit",
    "rbirefrate": "rbiRefRate",
    "fy_token": "fyToken",
    "exchange": "exchange",
    "segment": "segment",
    "day_buy_qty": "dayBuyQty",
    "day_sell_qty": "daySellQty",
    "cf_buy_qty": "cfBuyQty",
    "cf_sell_qty": "cfSellQty",
    "qty_multiplier": "qtyMulti_com",
    "pl_total": "pl",
    "cross_curr_flag": "crossCurrency",
    "pl_unrealized": "unrealized_profit"
  },
  "order_mapper": {
    "client_id": "clientId",
    "id": "id",
    "id_parent": "parentId",
    "id_exchange": "exchOrdId",
    "qty": "qty",
    "qty_remaining": "remainingQuantity",
    "qty_filled": "filledQty",
    "price_limit": "limitPrice",
    "price_stop": "stopPrice",
    "tradedPrice": "price_traded",
    "ord_type": "type",
    "fy_token": "fyToken",
    "exchange": "exchange",
    "segment": "segment",
    "symbol": "symbol",
    "instrument": "instrument",
    "oms_msg": "message",
    "offline_flag": "offlineOrder",
    "time_oms": "orderDateTime",
    "validity": "orderValidity",
    "product_type": "productType",
    "tran_side": "side",
    "org_ord_status": "status",
    "ord_source": "source",
    "symbol_exch": "ex_sym",
    "symbol_desc": "description"
  },
  "trade_mapper": {
    "id_fill": "tradeNumber",
    "id": "orderNumber",
    "qty_traded": "tradedQty",
    "price_traded": "tradePrice",
    "traded_val": "tradeValue",
    "product_type": "productType",
    "client_id": "clientId",
    "id_exchange": "exchangeOrderNo",
    "ord_type": "orderType",
    "tran_side": "side",
    "symbol": "symbol",
    "fill_time": "orderDateTime",
    "fy_token": "fyToken",
    "exchange": "exchange",
    "segment": "segment"
  }
}
Good to know
  • Subscribe only after the connection is open. You receive data only for the actions you pass in SLIST, and you can list several actions in one message.
  • A message with code 1605 and s set to ok confirms the subscription.
  • In the Python SDK, subscribe with data_type values OnOrders, OnTrades, OnPositions and OnGeneral. Join several with commas, for example OnOrders,OnTrades. The SDK converts them into SLIST.
  • Price alert, EDIS and login messages are general events and arrive under their own top-level key, for example pricealerts. See General Events.
  • The raw message and the SDK-parsed message use different key names, for example org_ord_status becomes status and tran_side becomes side. Use the key mappers above to translate between them.
  • SUB_T 1 subscribes and -1 unsubscribes. See General Socket - UnSubscribe.

Full reference and samples: General WebSocket - Subscribe.

Unsubscribe

Details

To Unsubscribe for different actions, create a message data, which would be the string format for json node.
Json node params

Convert the json to string and send this message to the socket to unsubscribe for the action_data mentioned.

message

message = json.dumps({ "T": "SUB_ORD", "SLIST": action_data, "SUB_T": -1 })

T Type: String
value: SUB_ORD (Fixed)

action_data Type: List/Array
Value: orders trades positions edis pricealerts login

Based on the list passed in action_data, web_socket data will be received.

SUB_T Type: Integer
Value: -1 (value -1 is for unsubscribing and 1 for subscribe)

Good to know
  • The message is the same as the subscribe message. Only SUB_T changes: -1 unsubscribes and 1 subscribes.
  • Put the actions you want to stop in SLIST, using the same names as when subscribing: orders, trades, positions, edis, pricealerts, login.
  • In the Python SDK, unsubscribe(data_type) takes the same comma-separated names as subscribe and sends this message for you.

Full reference and samples: General WebSocket - Unsubscribe.

Ping

Details

To check whether the websocket connection is alive or not, we have to send a periodically ping message. If we get a pong from websocket, it means it is alive else dead. Find how we are doing in Python Code.
Ping interval

Here there is one while loop with sleep of 10 seconds and we send a ping message to websocket to know that websocket is alive or not.

message

self.__ws_object.send("ping")

ping Type: String
value: ping (Fixed)

sleep Type: Integer
Value: 10 seconds

Good to know
  • The message is the plain text ping, not JSON. A pong reply means the connection is alive. If none comes, treat the connection as dead.
  • The sample loop sends ping and then sleeps for 10 seconds, and keeps going only while the socket is still connected.
  • The Python SDK starts this ping loop in its own thread as soon as the connection opens. If you use your own client, run the loop yourself.
  • Connection, subscribe and unsubscribe each have mandatory fields. See the table below.

Mandatory fields

MethodFieldsReason
WebSocket ConnectionWebSocket Connection URL(Endpoint)To make a connection
WebSocket ConnectionHeadersTo authorize
Subscribe Methodaction_dataTo subscribe for particular actions
Subscribe Method"SUB_T": 1While subscribing to any action
UnSubscribe Method"SUB_T": -1While unsubscribing any action

Full reference and samples: General WebSocket - Ping and Mandatory Fields.

In this section

EndpointMethodDescription
ConnectWSSThis guide explains how to connect to the General WebSocket using the endpoint and an authorization header.
SubscribeWSSThis guide explains how to subscribe to orders, trades, positions, EDIS, price alerts and login updates on the General WebSocket.
UnsubscribeWSSThis guide explains how to stop receiving selected updates on the General WebSocket without closing the connection.
Ping and Mandatory FieldsWSSThis guide explains how to send ping messages to check that the General WebSocket connection is alive.
Order EventsWSSThis WebSocket allows you to receive live updates on the status of your orders, including partial fills and rejections.
Trade EventsWSSThis WebSocket allows you to receive a live update for every trade executed against your orders.
Position EventsWSSThis WebSocket allows you to receive live updates on your positions as your trades execute.
General EventsWSSThis WebSocket allows you to receive price alert, EDIS and login notifications for your account.
Last updated on