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/v3with an authorization header inappId:accessTokenformat. - Subscribe with
Tset toSUB_ORD,SUB_Tset to1and the actions you want inSLIST:orders,trades,positions,edis,pricealertsorlogin. UseSUB_T-1to unsubscribe. - Send a
pingmessage at regular intervals. Apongreply 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 withOnOrders,OnTrades,OnPositionsandOnGeneral. - Keep a single WebSocket connection instance open at a time.
Connect
Details
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.
Handle accordingly in your programming language.
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
accessTokenis 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.
- 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
authorizationheader. With your own client, send<appId:accessToken>in the header. - With
order_ws.FyersOrderSocket, the callbacks areon_connect,on_close,on_error,on_orders,on_trades,on_positionsandon_general. Subscribe insideon_connect, then callkeep_running(). - The SDK starts its ping loop as soon as the connection opens. With your own client, send
pingyourself (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
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)
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"}
- The response is a string in Python and an
arraybufferin Node. Check the format you receive from the websocket library for your language. - 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, orpositions. - The key identifies the update type.
ordersis an order update,tradesis a trades update, andpositionsis a positions update. - 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"
}
}- 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
code1605andsset tookconfirms the subscription. - In the Python SDK, subscribe with
data_typevaluesOnOrders,OnTrades,OnPositionsandOnGeneral. Join several with commas, for exampleOnOrders,OnTrades. The SDK converts them intoSLIST. - 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_statusbecomesstatusandtran_sidebecomesside. Use the key mappers above to translate between them. SUB_T1subscribes and-1unsubscribes. See General Socket - UnSubscribe.
Full reference and samples: General WebSocket - Subscribe.
Unsubscribe
Details
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)
- The message is the same as the subscribe message. Only
SUB_Tchanges:-1unsubscribes and1subscribes. - 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 assubscribeand sends this message for you.
Full reference and samples: General WebSocket - Unsubscribe.
Ping
Details
ping message. If we get a pong from websocket, it means it is alive else dead. Find how we are doing in Python Code.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
- The message is the plain text
ping, not JSON. Apongreply means the connection is alive. If none comes, treat the connection as dead. - The sample loop sends
pingand 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
| Method | Fields | Reason |
|---|---|---|
| WebSocket Connection | WebSocket Connection URL(Endpoint) | To make a connection |
| WebSocket Connection | Headers | To authorize |
| Subscribe Method | action_data | To subscribe for particular actions |
| Subscribe Method | "SUB_T": 1 | While subscribing to any action |
| UnSubscribe Method | "SUB_T": -1 | While unsubscribing any action |
Full reference and samples: General WebSocket - Ping and Mandatory Fields.
In this section
| Endpoint | Method | Description |
|---|---|---|
| Connect | WSS | This guide explains how to connect to the General WebSocket using the endpoint and an authorization header. |
| Subscribe | WSS | This guide explains how to subscribe to orders, trades, positions, EDIS, price alerts and login updates on the General WebSocket. |
| Unsubscribe | WSS | This guide explains how to stop receiving selected updates on the General WebSocket without closing the connection. |
| Ping and Mandatory Fields | WSS | This guide explains how to send ping messages to check that the General WebSocket connection is alive. |
| Order Events | WSS | This WebSocket allows you to receive live updates on the status of your orders, including partial fills and rejections. |
| Trade Events | WSS | This WebSocket allows you to receive a live update for every trade executed against your orders. |
| Position Events | WSS | This WebSocket allows you to receive live updates on your positions as your trades execute. |
| General Events | WSS | This WebSocket allows you to receive price alert, EDIS and login notifications for your account. |