Skip to content

Execution Module - Websocket

Section Description
EndPoint Connection EndPoint details
Broker Accounts Management Manage Broker accounts on Quantsapp
Order Management Manage Orders on Broker accounts

Base Endpoint

wss://wsoc-options.quantsapp.com

Query Params

Name Value
ws_msg_type api_client_login
api_jwt jwt_token 1
portal api
sub_portal api
version 1.0.0
country in
uid mac_address of connected network 2
ref_id unique random alphanumeric string of len 16
Sample WS Url
Bash
wss://wsoc-options.quantsapp.com?
    ws_msg_type=api_client_login
    &api_jwt=eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE3NDk4GRhdGVzIn19.iQl2J84Me-u9hp7PFQ9LyBPqVDYaJitZU%3D%3D
    &portal=api
    &sub_portal=api
    &version=1.0.0
    &country=in
    &uid=15%3AA6%3AD8%3ACC%3A31%3A11
    &ref_id=vsU5oDc9aRfAfbZi

Websocket Connection Response

Name Description Allowed Values
status
str
Status code -1 | 0 | 1
msg
str
Message Success | Failure Message
ws_msg_type
str
Login token to be used for further Authentication qapp_api_gateway_options_etoken_authorized
session_data
dict
Session Data Only on success
session_data.api_key
str
API Key Only on success
session_data.user_id
str
User ID Only on success
session_data.etoken
str
Etoken (Used to connect Real-time Broker Order Updates) Only on success
session_data.market_timings
dict
Market Timings Only on success
session_data.market_timings.nse-fo
dict
Market Timings Only on success
session_data.market_timings.nse-fo.open
str
Market Open Timings ISO8601 format Datetime
session_data.market_timings.nse-fo.close
str
Market Close Timings ISO8601 format Datetime
session_data.market_timings.nse-fo.is_open_today
bool
Market Opened or Not Only on success

Sample Response

JSON
{
    "status": "1",
    "msg": "success",
    "ws_msg_type": "qapp_api_gateway_options_etoken_authorized",
    "session_data": {
        "market_timings": {
            "nse-fo": {
                "open": "2025-06-11T09:15:00+05:30",
                "close": "2025-06-11T15:30:00+05:30",
                "is_open_today": True
            }
        },
        "etoken": "sKA2c9UN...TNfrcuRZ",  //(1)!              
        "api_key": "u8IoXQbzTPy5192_zSSI9g",
        "user_id": "612571",
    }
}
  1. Used to connect Real-Time Broker Websocket to receive instant order updates

On Failure Websocket will be closed with any of the below Error Codes

Error Code Error Description Actions to be done
4000 Invalid Session Relogin and try with new jwt_token
4001 User Already disconnected Retry again
4002 Query Params Missing Please make sure all required query params are passed
4003 Invalid Data Value of Query params are invalid
4004 Account Not Exists Create a new account
4005 Account Locked Please contact [email protected]
4006 Force disconnect due to max active connections reached Retry again with the disconnected conn to make it active again
4007 Force disconnect due to ideal state for sometime Retry again
4008 UID Mismatch Retry again
4009 Force Disconnect due to other device login Some other device use the secret key, Retry again to make this connection active
4500 Server Error Retry again after sometime

Additional payload to be added on all requests

Name Description Allowed Values
custom_key
str
Custom Reference ID which will return on response for your references str
platform
str
Platform api
sub_platform
str
Sub Platform live
app
str
Options App o
country
str
Country from where the request is sent Small case 2-digit Country code
version
str
Version of API 1.0.0
Sample addition payload
JSON
{
    "custom_key": "add_broker",
    "platform": "api",
    "sub_platform": "live",
    "app": "o",
    "country": "in",
    "version": "1.0.0",
}

Broker Accounts Management

Section Description
List Mapped Broker List Mapped Broker accounts to Quantsapp
Add Broker Add Broker account to Quantsapp Account
Delete Broker Delete Broker account from Quantsapp Account

List Mapped Brokers

Payload

Name Description Default Allowed Values
acton
str
Action to process request required broker_login
mode
str
Mode to get data required get_accounts_with_token_expiry
revalidate
bool
On true will Revalidate all mapped broker accounts token if expiried false bool
Sample Payload
JSON
{
    "action": "broker_login",
    "mode": "get_accounts_with_token_expiry",
    "revalidate": false,

    # Additional Payload //(1)!
}
  1. Additional Payload
    JSON
    {
        "custom_key": "list_mapped_brokers",
        "platform": "api",
        "sub_platform": "live",
        "app": "o",
        "country": "in",
        "version": "1.0.0",
    }
    

Response

Sample Response

JSON
{
    "status": "1",
    "msg": "No accounts available" | "success",
    "custom_key": "access_expiry_config",

    # Only available if accounts are mapped
    "data": [
        {
           "broker": "fivepaisa",
            "client_id": "51372260",
            "role": "executor",
            "name": "NAME",
            "validity": "02-May-25 23:59:59",
            "valid": true,
            "margin": {
                "dt": "02-May-25 02:18:50",
                "NSE-FO": "1534.53"
            }
        },
    ],
    "version": "9",
    "next_margin_dt_utc": "02-May-25 02:33:50",
}

Sample Response

JSON
{
    "status": "0",
    "msg": "Failed",
}

Add Broker

Payload

Name Description Default Allowed Values
acton
str
Action to process request required broker_login
mode
str
Mode to add Broker required add_account
broker
str
Broker to be added required Broker
delete_previous_users
bool
Whether to delete previous added users required bool
update_owner
bool
Whether to update current user as owner required bool
login_type
str
Login Mode required totp
credentials
dict
Broker Login Credentials to Login required Broker Credentials
Sample Payload
JSON
{
    "action": "broker_login",
    "mode": "add_account",
    "broker": "dhan",
    "delete_previous_users": false,
    "update_owner": false,
    "login_type": "totp",
    "credentials": {
        "access_token": "YOUR_DHAN_ACCESS_TOKEN_HERE"
    },

    # Additional Payload //(1)!
}
  1. Additional Payload
    JSON
    {
        "custom_key": "add_broker",
        "platform": "api",
        "sub_platform": "live",
        "app": "o",
        "country": "in",
        "version": "1.0.0",
    }
    
JSON
{
    "action": "broker_login",
    "mode": "add_account",
    "broker": "choice",
    "delete_previous_users": false,
    "update_owner": false,
    "login_type": "totp",
    "credentials": {
        "mobile": "YOUR_MOBILE_NUMBER_HERE",
        "client_access_token": "YOUR_CHOICE_CLIENT_ACCESS_TOKEN_HERE"
    },

    # Additional Payload //(1)!
}
  1. Additional Payload
    JSON
    {
        "custom_key": "add_broker",
        "platform": "api",
        "sub_platform": "live",
        "app": "o",
        "country": "in",
        "version": "1.0.0",
    }
    

Response

Sample Response

JSON
{
    "status": "1",
    "msg": "success",
    "custom_key": "add_broker",
}

Sample Response

JSON
{
    "status": "0",
    "msg": "Failed",
}

Delete Broker

Payload

Name Description Default Allowed Values
acton
str
Action to process request required broker_login
mode
str
Mode to delete Broker required delete_account
broker
str
Broker to be deleted required Broker
client_id
str
Client ID of Broker Account required str
Sample Payload
JSON
{
    "action": "broker_login",
    "mode": "delete_account",
    "broker": "dhan",
    "client_id": "51372260",

    # Additional Payload //(1)!
}
  1. Additional Payload
    JSON
    {
        "custom_key": "delete_broker",
        "platform": "api",
        "sub_platform": "live",
        "app": "o",
        "country": "in",
        "version": "1.0.0",
    }
    

Response

Sample Response

JSON
{
    "status": "1",
    "msg": "success",
    "custom_key": "delete_broker",
}

Sample Response

JSON
{
    "status": "0",
    "msg": "Failed",
}

Order Management

Section Description
Get OrderBook Get OrderBook data
Place Order Placing order on Broker Accounts
Modify Order Modify order on Broker Accounts
Cancel Order Cancel orders on multiple Broker accounts
Cancel All Order Cancel all orders on specific Broker account
Get Positions Get Positions on specific Broker accounts wise
Get Positions Combined Get Positions on all Broker accounts combined
Get Broker Websocket Status Get the connection status of Broker Websocket
Broker Websocket Reconnect Reconnect to Broker Websocket

Get Order Book

Payload

Name Description Default Allowed Values
acton
str
Action to process request required broker_orders
mode
str
Mode to get orderbook required get_order_status
sub_mode
str
SubMode to get orderbook required account
broker_clientid*
list[str]
Broker accounts to get Orderbook data required list[BrokerClient]
has_pagination
bool
To get all data without pagination set this value to false (recommended) required bool

* broker_clientid - only one broker_client allowed right now

Sample Payload
JSON
{
    "action": "broker_orders",
    "mode": "get_order_status",
    "sub_mode": "account",
    "broker_clientid": [
        "dhan,51372260",
    ],
    "has_pagination": false,
    "pagination_key": "Any",  //(1)!

    # Additional Payload, //(2)!
}
  1. Only send if has_pagination is set to true and the same key available on previous get orderbook api response. Send the exact value from the previous api response

  2. Additional Payload

    JSON
    {
        "custom_key": "get_orderbook",
        "platform": "api",
        "sub_platform": "live",
        "app": "o",
        "country": "in",
        "version": "1.0.0",
    }
    

Response

Sample Response

Gzip Compressed Response
{
    "status": "1",
    "msg": "success",
    "gzip": true,
    "orders": "H4sIAPONSWgC/02Qu27EIBBFf2VFvbvCPG13aSKl2FRpoihCNiYRWvwIDIUV5d/D2MlqqWDunTPDffsmfZyvLhobvJuAtAcyJpjt9Xh5qBhnjHNyPJDezHFw0Q9o4FwwJmVNNed1hfIXrEXQslyX6K0rj+rMsC+vJrkQsK1Hp58SxDz+jXp+enx5bSt5unTricnWtoVLKRq3eQbWBWEk+NED2fDzkC3chCmOYdvA5OQsztVCyUZx1WgtheBFK8q+uSprN+IGT9BBTkhZ3DT46XP/KYJMXoYO3B1P0/0Ui7sLo1J7WctaaEUbhBsLEaU9GPPhQ3Doxd6S7WL+M6Jn+vP+C9F3KnODAQAA",
    "pagination_key": Any,  //(1)!
}
  1. Only present if has_pagination on payload is set to true and more records than certain limit on DB. This can be resent on next payload to get the remaining items

If gzip is true, then decode the orders data with below logic

orders decompress logic
Python
import json, gzip, base64

def decompress_gzip_json_data(orders_data: str) -> list | dict:
    return json.loads(gzip.decompress(base64.b64decode(orders_data)))
JavaScript
// For Node.js environments
const pako = require('pako');  // npm install pako

/**
* Decompresses Base64-encoded, gzipped JSON data.
*
* @param {string} orders_data - The Base64-encoded, gzipped string.
* @returns {Array | Object} The decompressed JSON data.
* @throws {Error} If decompression or JSON parsing fails.
*/
function decompressGzipJsonData(orders_data) {
try {
    // 1. Base64 decode the string
    const decoded = Buffer.from(orders_data, 'base64');

    // 2. Gzip decompress the decoded buffer
    // pako.inflate returns a Uint8Array, which we convert to a Buffer for consistency
    const decompressed = Buffer.from(pako.inflate(decoded));

    // 3. Parse the decompressed data as JSON
    const jsonData = JSON.parse(decompressed.toString('utf8'));

    return jsonData;
} catch (error) {
    console.error("Error decompressing or parsing data:", error);
    throw error; // Re-throw the error for the caller to handle
}
}

// --- Example Usage (Node.js) ---
const compressed_data = "H4sIAPONSWgC/02Qu27EIBBFf2VFvbvCPG13aSKl2FRpoihCNiYRWvwIDIUV5d/D2MlqqWDunTPDffsmfZyvLhobvJuAtAcyJpjt9Xh5qBhnjHNyPJDezHFw0Q9o4FwwJmVNNed1hfIXrEXQslyX6K0rj+rMsC+vJrkQsK1Hp58SxDz+jXp+enx5bSt5unTricnWtoVLKRq3eQbWBWEk+NED2fDzkC3chCmOYdvA5OQsztVCyUZx1WgtheBFK8q+uSprN+IGT9BBTkhZ3DT46XP/KYJMXoYO3B1P0/0Ui7sLo1J7WctaaEUbhBsLEaU9GPPhQ3Doxd6S7WL+M6Jn+vP+C9F3KnODAQAA";

try {
  const decompressedResult = decompressGzipJsonData(python_compressed_data);
  console.log("Decompressed Data:", decompressedResult);
} catch (e) {
   // Handle error
}
Decompressed 'orders' data
[
    {
        "broker_client": "mstock,MA1232233",
        "b_orderid": "33422558073381",
        "qty": 75,
        "price": 1.2,
        "buy_sell": "b",
        "instrument": "NIFTY:15-May-25:c:25500",
        "order_type": "limit",
        "product_type": "nrml",
        "q_usec": 1746596369775443,
        "userid": 622594,
        "order_status": "pending",
        "b_usec_update": 1746596370000000,
        "e_orderid": 1600000075847609,
        "o_ctr": 1,
        "qty_filled": 0,
        "stop_price": 0.0
    }
]

Sample Response

JSON
{
    "status": "0",
    "msg": "Failed",
}

Place Order

Payload

Name Description Default Allowed Values
acton
str
Action to process request required broker_orders
mode
str
Mode to get orderbook required place_order
page_id
str
Reference ID from where it is placed required Sent any string
ui_orderid
str
Unique Reference ID for each order required APIKEY_MICRO-TIMESTAMP
order
dict
Order data to place required dict
order.accounts
dict
Broker Accounts to place order required OrderPlacementBrokerAccounts
order.exchange
str
Exchange to place order required Exchange
order.product
str
Product Type to place order required ProductType
order.order_type
str
Order Type to place order required OrderType
order.validity
str
Order Validity to place order required Validity
order.settings
dict
Settings for the Order to be placed required OrderPlacementSetting
order.legs
list[dict]
Settings for the Order to be placed required list[OrderPlacementLeg]
Sample Payload
JSON
{
    "action": "broker_orders",
    "mode": "place_order",
    "order": {
        "accounts": {
            "mstock,MA6215631": 1
        },
        "exchange": "NSE-FO",
        "product": "nrml",
        "order_type": "limit",
        "validity": "day",
        "legs": [
            {
                "qty": 75,
                "price": 1.1,
                "symbol": "NIFTY",
                "segment": "o",
                "opt_type": "c",
                "expiry": "31-Jul-25",
                "strike": 25500,
                "buy_sell": "b"
            },
            {
                "qty": 75,
                "price": 1.1,
                "symbol": "NIFTY",
                "segment": "o",
                "opt_type": "p",
                "expiry": "31-Jul-25",
                "strike": 23500,
                "buy_sell": "s"
            },
        ],
        "settings": {
            "margin_benefit": True,
        }
    },
    "page_id": "api_v1.0.0",
    "ui_orderid": "u8IoXQbzTPy5192_zSSI9g_1749681323891",

    # Additional Payload //(1)!
}
  1. Additional Payload
    JSON
    {
        "custom_key": "place_order",
        "platform": "api",
        "sub_platform": "live",
        "app": "o",
        "country": "in",
        "version": "1.0.0",
    }
    

Response

Sample Response

    {
        "status": "1",
        "msg": "success",
        "has_failed": true,  //(1)!
        "q_ref_id": 8,
        "q_usec": 1747905016476938,  //(2)!
        "orders": {
            "choice,X123354": {
                "placed": {
                    "NIFTY:31-Jul-25:c:25500": [
                            {
                            "b_orderid": "ATQOU00005F5", //(3)!
                            "qty": 75,
                            "buy_sell": "b",  //(4)!
                            "price": 0.05
                        }
                    ]
                },
                "failed": {
                    "NIFTY:26-Jun-25:p:23500": [
                        {
                            "qty": 75,
                            "buy_sell": "b",
                            "price": 0.01
                        }
                    ]
                }
            }
        }
    }
  1. If true then some or all leg orders got failed, the detailed info available on orders key with BrokerClient wise
  2. Order placed time in Micro seconds (µsec)
  3. Present only if order successfully placed
  4. Indicated Buy or Sell BuySell

Sample Response

JSON
{
    "status": "0",
    "msg": "Failed",
}

Modify Order

Payload

Name Description Default Allowed Values
acton
str
Action to process request required broker_orders
mode
str
Mode to modify order required modify_order
broker_client
str
Broker Account required BrokerClient
b_orderid
str
Broker OrderID required str
e_orderid
str
Exchange OrderID required str
order
dict
Order data to Modify required dict
order.qty
int
Order Quantity to Modify required int
order.price
int|float
Order Price to Modify required int | float
order.stop_price
int|float
Order Stop Loss Price to Modify NA int | float
Sample Payload
JSON
{
    "action": "broker_orders",
    "mode": "modify_order",
    "broker_client": "mstock,MA6215631",
    "b_orderid": "ATQOU00005F5",
    "e_orderid": "1500000155868129",
    "order": {
        "qty": 75,
        "price": 1.1,
        "stop_price": 0.1, //(1)!
    }

    # Additional Payload //(2)!
}
  1. Only for Stop Loss Limit order
  2. Additional Payload
    JSON
    {
        "custom_key": "modify_order",
        "platform": "api",
        "sub_platform": "live",
        "app": "o",
        "country": "in",
        "version": "1.0.0",
    }
    

Response

Sample Response

    {
        "status": "1",
        "msg": "Modified",
    }

Sample Response

JSON
{
    "status": "0",
    "msg": "Failed",
}

Cancel Order

Payload

Name Description Default Allowed Values
acton
str
Action to process request required broker_orders
mode
str
Mode to Cancel Specific orders required cancel_orders
order
dict
Order data to Modify required OrderCancelData
Sample Payload
{
    "action": "broker_orders",
    "mode": "cancel_orders",
    "order": {
        "choice,X123354": [
            {
                "b_orderid": "ATQOU00001K5",
                "e_orderid": "1200000164137820",
            },
            {
                "b_orderid": "ATQOU00001K1",
                "e_orderid": "1200000164137821",
            },
        ],
        "dhan,423354": [
            {
                "b_orderid": "ATQOU00001K2",
                "e_orderid": "1200000164137829",
            },
        ],
    }

    # Additional Payload //(1)!
}
  1. Additional Payload
    JSON
    {
        "custom_key": "cancel_orders",
        "platform": "api",
        "sub_platform": "live",
        "app": "o",
        "country": "in",
        "version": "1.0.0",
    }
    

Response

Sample Response

    {
        "status": "1",
        "msg": "success",
        "has_failed": false,  //(1)!
        "q_ref_id_c": 15
    }
  1. If true then some or all orders cancellation got failed

Sample Response

JSON
{
    "status": "0",
    "msg": "Failed",
}

Cancel All Orders

Payload

Name Description Default Allowed Values
acton
str
Action to process request required broker_orders
mode
str
Mode to get orderbook required cancel_orders
broker_client
str
Broker Account required BrokerClient
cancel_all
bool
Cancel All orders related to specific Broker Account required true
Sample Payload
{
    "action": "broker_orders",
    "mode": "cancel_orders",
    "cancel_all": true,
    "broker_client": "choice,X123354"

    # Additional Payload //(1)!
}
  1. Additional Payload
    JSON
    {
        "custom_key": "cancel_all_orders",
        "platform": "api",
        "sub_platform": "live",
        "app": "o",
        "country": "in",
        "version": "1.0.0",
    }
    

Response

Sample Response

    {
        "status": "1",
        "msg": "success",
        "has_failed": false,  //(1)!
        "q_ref_id_c": 15
    }
  1. If true then some or all orders cancellation got failed

Sample Response

JSON
{
    "status": "0",
    "msg": "Failed",
}

Get Positions

Payload

Name Description Default Allowed Values
acton
str
Action to process request required broker_orders
mode
str
Mode to get Positions Account Wise required get_positions_account_wise
broker_clientids
list[str]
Broker accounts to get Positions Account wise data required list[BrokerClient]
Sample Payload
JSON
{
    "action": "broker_orders",
    "mode": "get_positions_account_wise",
    "broker_clientids": [
        "dhan,51372260",
    ],

    # Additional Payload //(1)!
}
  1. Additional Payload
    JSON
    {
        "custom_key": "get_positions_account_wise",
        "platform": "api",
        "sub_platform": "live",
        "app": "o",
        "country": "in",
        "version": "1.0.0",
    }
    

Response

Sample Response

Gzip Compressed Response
{
    "status": "1",
    "msg": "success",
    "gzip": true,
    "positions":  "H4sIAJhISmgC/03KwQrCIByA8VcZnrfhFLfmAww61KlLRIg5ocCZub+BjL17OoI6fj++BY13aUvW0I6QFiNeXBb0sDP4MGkLqdFxP5zOvGHVQcaKMK44YT3GqCyQ888xKBAQnc6r9ZPJfgtRvCAm6tg3QbylCfnqab3prI35v7b+bbu2JpmdUOBT0/W6fgAlzkEYrgAAAA=="
}

If gzip is true, then decode the positions data with below logic

orders decompress logic
Python
import json, gzip, base64

def decompress_gzip_json_data(positions_data: str) -> list | dict:
    return json.loads(gzip.decompress(base64.b64decode(positions_data)))
JavaScript
// For Node.js environments
const pako = require('pako');  // npm install pako

/**
* Decompresses Base64-encoded, gzipped JSON data.
*
* @param {string} positions_data - The Base64-encoded, gzipped string.
* @returns {Array | Object} The decompressed JSON data.
* @throws {Error} If decompression or JSON parsing fails.
*/
function decompressGzipJsonData(positions_data) {
try {
    // 1. Base64 decode the string
    const decoded = Buffer.from(positions_data, 'base64');

    // 2. Gzip decompress the decoded buffer
    // pako.inflate returns a Uint8Array, which we convert to a Buffer for consistency
    const decompressed = Buffer.from(pako.inflate(decoded));

    // 3. Parse the decompressed data as JSON
    const jsonData = JSON.parse(decompressed.toString('utf8'));

    return jsonData;
} catch (error) {
    console.error("Error decompressing or parsing data:", error);
    throw error; // Re-throw the error for the caller to handle
}
}

// --- Example Usage (Node.js) ---
const compressed_data = "H4sIABvKIWgC/4uuVsrMKy4pKs1NzStRslJQ8vN0C4m0MjTV9U2s1DUytUq2MjI1MjBQ0lFQKijKTylNLokvqSxIBSnNK8rNAYknlVbGF5ZUAoXMTaHckviyxJxSkCpTC0M9I5BwcWpODrIyMB9JnblBbSwAX3B17I4AAAA=";

try {
  const decompressedResult = decompressGzipJsonData(python_compressed_data);
  console.log("Decompressed Data:", decompressedResult);
} catch (e) {
   // Handle error
}
Decompressed 'positions' data
{
    "dhan,51372260": [
        {
            "instrument": "NIFTY:15-May-25:c:25900",
            "product_type": "nrml",
            "buy_qty": 75,
            "buy_t_value": 93.75,
            "sell_qty": 75,
            "sell_t_value": 86.25,
            "p_ctr": 3,
        },
    ]
}

Sample Response

JSON
{
    "status": "0",
    "msg": "Failed",
}

Get Positions Combined

Payload

Name Type Description Default Allowed Values
acton
str
Action to process request required broker_orders
mode
str
Mode to get Positions Combined required get_positions
broker_clientids*
list[str]
Broker accounts to get Positions Combined data required list[BrokerClient]

* broker_clientids - only one broker_client allowed right now

Sample Payload
JSON
{
    "action": "broker_orders",
    "mode": "get_positions",
    "broker_clientids": [
        "dhan,51372260",
    ],

    # Additional Payload //(1)!
}
  1. Additional Payload
    JSON
    {
        "custom_key": "get_positions_combined",
        "platform": "api",
        "sub_platform": "live",
        "app": "o",
        "country": "in",
        "version": "1.0.0",
    }
    

Response

Sample Response

Gzip Compressed Response
{
    "status": "1",
    "msg": "success",
    "gzip": true,
    "positions":  "H4sIABvKIWgC/4uuVsrMKy4pKs1NzStRslJQ8vN0C4m0MjTV9U2s1DUytUq2MjI1MjBQ0lFQKijKTylNLokvqSxIBSnNK8rNAYknlVbGF5ZUAoXMTaHckviyxJxSkCpTC0M9I5BwcWpODrIyMB9JnblBbSwAX3B17I4AAAA="
}

If gzip is true, then decode the positions data with below logic

orders decompress logic
Python
import json, gzip, base64

def decompress_gzip_json_data(positions_data: str) -> list | dict:
    return json.loads(gzip.decompress(base64.b64decode(positions_data)))
JavaScript
// For Node.js environments
const pako = require('pako');  // npm install pako

/**
* Decompresses Base64-encoded, gzipped JSON data.
*
* @param {string} positions_data - The Base64-encoded, gzipped string.
* @returns {Array | Object} The decompressed JSON data.
* @throws {Error} If decompression or JSON parsing fails.
*/
function decompressGzipJsonData(positions_data) {
try {
    // 1. Base64 decode the string
    const decoded = Buffer.from(positions_data, 'base64');

    // 2. Gzip decompress the decoded buffer
    // pako.inflate returns a Uint8Array, which we convert to a Buffer for consistency
    const decompressed = Buffer.from(pako.inflate(decoded));

    // 3. Parse the decompressed data as JSON
    const jsonData = JSON.parse(decompressed.toString('utf8'));

    return jsonData;
} catch (error) {
    console.error("Error decompressing or parsing data:", error);
    throw error; // Re-throw the error for the caller to handle
}
}

// --- Example Usage (Node.js) ---
const compressed_data = "H4sIABvKIWgC/4uuVsrMKy4pKs1NzStRslJQ8vN0C4m0MjTV9U2s1DUytUq2MjI1MjBQ0lFQKijKTylNLokvqSxIBSnNK8rNAYknlVbGF5ZUAoXMTaHckviyxJxSkCpTC0M9I5BwcWpODrIyMB9JnblBbSwAX3B17I4AAAA=";

try {
  const decompressedResult = decompressGzipJsonData(python_compressed_data);
  console.log("Decompressed Data:", decompressedResult);
} catch (e) {
   // Handle error
}
Decompressed 'positions' data
[
    {
        "instrument": "NIFTY:15-May-25:c:25200",
        "product_type": "nrml",
        "buy_qty": 75,
        "buy_t_value": 581.25,
        "sell_qty": 75,
        "sell_t_value": 570
    }
]

Sample Response

JSON
{
    "status": "0",
    "msg": "Failed",
}

Get Broker Websocket Status

Payload

Name Description Default Allowed Values
acton
str
Action to process request required broker_orders
mode
str
Mode to get Broker Websocket Status required get_broker_ws_conn_status
broker_client
str
Broker account to get Websocket Connection Status required list[BrokerClient]
Sample Payload
JSON
{
    "action": "broker_orders",
    "mode": "get_broker_ws_conn_status",
    "broker_client": "dhan,51372260"

    # Additional Payload //(1)!
}
  1. Additional Payload
    JSON
    {
        "custom_key": "get_broker_websocket_status",
        "platform": "api",
        "sub_platform": "live",
        "app": "o",
        "country": "in",
        "version": "1.0.0",
    }
    

Response

Sample Response

{
    "status": "1",
    "msg": "Connected",
    "ts_ping": 1747129266,
    "ts_msg": 1747126860,
    "ts_conn": 1747126860
}

Sample Response

JSON
{
    "status": "0",
    "msg": "Failed"
}

Broker Websocket Reconnect

Payload

Name Description Default Allowed Values
acton
str
Action to process request required broker_orders
mode
str
Mode to Reconnect Broker Websocket required broker_ws_connect
broker_client
str
Broker account to reconnect Websocket Connection required list[BrokerClient]
Sample Payload
JSON
{
    "action": "broker_orders",
    "mode": "broker_ws_connect",
    "broker_client": "dhan,51372260"

    # Additional Payload //(1)!
}
  1. Additional Payload
    JSON
    {
        "custom_key": "broker_websocket_reconnect",
        "platform": "api",
        "sub_platform": "live",
        "app": "o",
        "country": "in",
        "version": "1.0.0",
    }
    

Response

Sample Response

{
    "status": "1",
    "msg": "Connected",
}

Sample Response

JSON
{
    "status": "0",
    "msg": "Failed"
}

  1. JWT Token received from Login Process 

  2. MAC Address Retrieval Code
    Python
    import uuid
    
    def get_mac_address() -> str:
        """Retreive the mac address of the connected network interface"""
    
        # Get the hardware address as a 48-bit positive integer
        mac_num = uuid.getnode()
    
        # 1. Convert the number to hex
        # 2. Pad it to 12 chars
        # 3. Convert it to a series of two char strings
        # 4. Join them with colons
        # 5. convert to uppercase
        return ':'.join(f"{b:02x}" for b in mac_num.to_bytes(6)).upper()
    
    print(get_mac_address)
    # 15:A2:C8:DD:31:11
    
    JavaScript
    const os = require('os');
    
    /**
    * Retrieves the MAC address of a connected non-internal network interface.
    * Prioritizes non-internal (e.g., Ethernet, Wi-Fi) interfaces with a MAC address.
    *
    * @returns {string | null} The MAC address in 'XX:XX:XX:XX:XX:XX' format, or null if not found.
    */
    function getMacAddress() {
        const interfaces = os.networkInterfaces();
        let macAddress = null;
    
        // Iterate over all network interfaces
        for (const interfaceName in interfaces) {
            const networkInterface = interfaces[interfaceName];
    
            for (const iface of networkInterface) {
                // Filter out internal (loopback) interfaces and ensure it has a MAC address
                if (!iface.internal && iface.mac && iface.mac !== '00:00:00:00:00:00') {
                    macAddress = iface.mac.toUpperCase();
                    // Found a valid MAC address, you might want to return the first one found
                    // or continue iterating if you have a specific interface in mind.
                    // For simplicity, we return the first valid one here.
                    return macAddress;
                }
            }
        }
    
        return macAddress; // Return null if no suitable MAC address was found
    }
    
    // --- Usage Example ---
    const mac = getMacAddress();
    
    if (mac) {
        console.log(`MAC Address: ${mac}`);
    } else {
        console.log("No MAC address found for a non-internal interface.");
    }
    
    // MAC Address: 15:A2:C8:DD:31:11