Download OpenAPI specification:Download
This is the REST API documentation for the MTS application. You can learn more about API by visiting multitradesoftech.com/. Please contact in this number +91 8980983000 to obtain API & Secret Key. To test the authorization filters for this sample, you can utilize provided API_key and secret_key.
This API is documented and designed to facilitate algorithmic trading activities. It incorporates standard REST API principles to enable seamless communication between trading applications and the underlying platform. The structure of the API is based on the Multitrade sample provided by our team. Additionally, it has been extended to showcase the capabilities of the API tool and leverage MTS documentation. In addition to adhering to standard REST API syntax, the API also utilizes a few vendor extensions to enhance its functionality.
The API follows the REST API format and is specifically designed to support algorithmic trading activities. It provides comprehensive documentation on endpoints, request/response formats, and authentication mechanisms, making it easy for developers to integrate with trading applications.
Language | Version | Required Libraries/Packages |
---|---|---|
Python | v3.10.12 | requests (v2.31.0), json, websockets (v12.0), asyncio (v3.4.3), nest_asyncio (v1.6.0), ssl |
Node.js | v20.11.1 | request (v2.88.2), websockets (v8.16.0) |
Status_Code | Description | Example Response |
---|---|---|
401 | Invalid AccessToken | {"status": "unsuccessful", "data": {"error": "Invalid AccessToken"}} |
410 | Application Not Active | {"status": "unsuccessful", "data": {"error": "Application Not Active"}} |
404 | Application Not Found | {"status": "unsuccessful", "data": {"error": "Application Not Found"}} |
500 | Api Server Not Connected | {"status": "unsuccessful", "data": {"error": "Api Server Not Connected"}} |
409 | Invalid API version 3 needed | {"status": "unsuccessful", "data": {"error": "Invalid API version 3 needed"}} |
405 | Invalid Method | {"status": "unsuccessful", "data": {"error": "Invalid Method"}} |
404 | Wrong Request please check path | {"status": "unsuccessful", "data": {"error": "Wrong Request please check path"}} |
429 | Msg rate limit exceeded | {"status": "unsuccessful", "data": {"error_text": "Message rate limit has exceeded by it's limit"}} |
MTS API offers combination of two forms of authentication:
The API consumer sends login credentials (secretKey & appKey) to the Interactive API server. After validation, if successful, the user receives a request token in the login response.
Api-Version required | string Default: 3 It is necessary to keep API Version as 3 for this version of API. |
api_key | string The API App key, It will look like ".KAoiU$GCfrrNDN4H|qq<<XtG" |
api_secrets | string secretKey to validate, it will look like "ZOYWyg6U5DfJ@D<NR!%3z<PR" |
import requests url = "https://wss1.mtsp.co.in:15207/connect/login" payload = { "api_key": "API_KEY", "api_secrets": "API_SECRET" } headers = { "Content-Type": "application/x-www-form-urlencoded", "Api-Version": "3" } response = requests.post(url, data=payload, headers=headers) data = response.json() print(data)
{- "status": "successful",
- "data": {
- "request_token": "o%sZ|iPUWe7xfUQgBXKX"
}
}
This call invalidates the session token and destroys the API session. The user should go through the login flow again to obtain a fresh session token for further activities. Any attempts to access API endpoints with the invalidated token will result in authentication errors. Once the new token is acquired, the user can resume activities within the application securely.
Api-Version required | string Default: 3 It is necessary to keep API Version as 3 for this version of API. |
import requests url = "https://wss1.mtsp.co.in:15207/connect/login" payload = { "api_key": "API_KEY", "api_secrets": "API_SECRET" } headers = { "Content-Type": "application/x-www-form-urlencoded", "Api-Version": "3" } response = requests.delete(url, data=payload, headers=headers) data = response.json() print(data)
{- "status": "successful",
- "data": {
- "data": "successfullyloggedout"
}
}
You need to log in every day, every time you start the application, the session token lasts for 24 hours or until logout. Upon launching, users authenticate their sessions. The session token allows access to features securely for 24 hours or until logout. Exceeding this time or logging out invalidates the token, requiring a new login for continued access. This process ensures ongoing session security and a smooth user experience.
Api-Version required | string Default: 3 It is necessary to keep API Version as 3 for this version of API. |
import requests url = "https://wss1.mtsp.co.in:15207/session/token" headers = { "Api-Version": "3", "Authorization": "API_KEY:REQUEST_TOKEN" } response = requests.get(url, headers=headers) data = response.json() print(data)
{- "status": "successful",
- "data": {
- "user_type": "3",
- "email": "info@multitradesoftech.com",
- "user_name": "MTS_User",
- "user_shortname": "User",
- "broker": "",
- "exchanges": "",
- "products": [
- "CNC",
- "NRML"
], - "avatar_url": "",
- "user_id": "DAPI1",
- "api_key": "",
- "access_token": "o%sZ|iPUWe7xfUQgBXKX",
- "order-types": [
- "MARKET",
- "LIMIT",
- "SL",
- "SL-M"
], - "login_time": "2024-02-0313:15:21"
}
}
The purpose of this request is to retrieve user profile data from the server from which users can access their profile stored by the broker, which remains retrievable at any given moment.
Api-Version required | string Default: 3 It is necessary to keep API Version as 3 for this version of API. |
import requests url = "https://wss1.mtsp.co.in:15207/user/profile" headers = { "Api-Version": "3", "Authorization": "API_KEY:REQUEST_TOKEN" } response = requests.get(url, headers=headers) data = response.json() print(data)
{- "status": "successful",
- "data": {
- "user_id": "DAPI1",
- "user_type": "3",
- "email": "info@multitradesoftech.com",
- "user_name": "MTS_User",
- "user_shortname": "User",
- "broker": "",
- "exchanges": [
- "BSECM",
- "BSECOM",
- "BSEFO",
- "BSEFX",
- "BSEINX",
- "CQG",
- "DGCX",
- "IB",
- "MAXXTRADER",
- "MCX",
- "MCX1",
- "NCDEX",
- "NSECD",
- "NSECM",
- "NSECOM",
- "NSEFO",
- "NSEIFSC",
- "NSESLBM",
- "XT"
], - "products": [
- "CNC",
- "NRML"
], - "order-types": [
- "MARKET",
- "LIMIT",
- "SL",
- "SL-M"
], - "avatar_url": ""
}
}
The User Margin endpoint provides detailed information regarding funds, cash, and margin status for the user across both equity and commodity segments.
Upon a successful request, the server responds with a JSON object containing various fields, including "status" and "data". The "data" field further encapsulates detailed information related to the user's margin status.
Api-Version required | string Default: 3 It is necessary to keep API Version as 3 for this version of API. |
import requests url = "https://wss1.mtsp.co.in:15207/user/margins" headers = { "Api-Version": "3", "Authorization": "API_KEY:REQUEST_TOKEN" } response = requests.get(url, headers=headers) data = response.json() print(data)
{- "status": "successful",
- "data": {
- "CM": {
- "enabled": "true",
- "net": "186819082.50",
- "available": {
- "adhoc_margin": "0.00",
- "cash": "436819082",
- "collateral": "0.00",
- "intraday_payin": "0"
}, - "utilized": {
- "debits": "249999999.5",
- "exposure": "0.00",
- "m2m_realised": "0",
- "m2m_unrealised": "0.00",
- "option_premium": "0",
- "payout": "0.00",
- "span": "0.00",
- "holding_sales": "0.00",
- "turnover": "0.00"
}
}, - "DEPOSIT": {
- "enabled": "true",
- "net": "186819082.50",
- "available": {
- "adhoc_margin": "0.00",
- "cash": "545235633",
- "collateral": "0.00",
- "intraday_payin": "0"
}, - "utilized": {
- "debits": "358416550.5",
- "exposure": "0.00",
- "m2m_realised": "0",
- "m2m_unrealised": "0.00",
- "option_premium": "0",
- "payout": "0.00",
- "span": "0.00",
- "holding_sales": "0.00",
- "turnover": "0.00"
}
}, - "FO": {
- "enabled": "true",
- "net": "386819082.50",
- "available": {
- "adhoc_margin": "0.00",
- "cash": "948579472",
- "collateral": "0.00",
- "intraday_payin": "0"
}, - "utilized": {
- "debits": "561760389.5",
- "exposure": "0.00",
- "m2m_realised": "0",
- "m2m_unrealised": "0.00",
- "option_premium": "0",
- "payout": "0.00",
- "span": "0.00",
- "holding_sales": "0.00",
- "turnover": "0.00"
}
}, - "MCX": {
- "enabled": "true",
- "net": "385819082.50",
- "available": {
- "adhoc_margin": "0.00",
- "cash": "873027432.00",
- "collateral": "0.00",
- "intraday_payin": "0"
}, - "utilized": {
- "debits": "487208349.5",
- "exposure": "0.00",
- "m2m_realised": "0",
- "m2m_unrealised": "0.00",
- "option_premium": "0",
- "payout": "0.00",
- "span": "0.00",
- "holding_sales": "0.00",
- "turnover": "0.00"
}
}
}
}
The order APIs facilitate placing orders of various types and retrieving daily order information. Within the MTS interactive API calls, users can initiate orders on exchanges and execute orders with stop-loss protection.
Api-Version required | string Default: 3 It is necessary to keep API Version as 3 for this version of API. |
tradingsecurity | string Unique Security_ID of the script, example "3045" |
exchange | string BSECM, BSECOM, BSEFO,BSEINX, BSEFX, CQG, MCX, NSECD, NSECM, NSEFO, NSEIFSC, NSESLBM, DGCX, IB, MAXXTRADER, NCDEX, NSECOM |
transaction_type | string BUY/ SELL |
order_type | string MARKET, LIMIT, SL, SL-M |
quantity | string Example: 10 |
validity | string DAY, IOC, GTT, GTC, OPG, FOK, GTX, GTD, EOS, FAK, ATO, ATC |
price | string Example: 830.00 |
product | string CNC, NRML |
tag | string An optional tag to apply to an order to identify it (alphanumeric, max 20 chars) |
trigger_price | string The price at which an order should be triggered (SL, SL-M) |
disclosed_quantity | string Quantity to disclose publicly (for equity trades) |
userid | string ClientID = The user id of the user, provided by Multitrade |
import requests url = "https://wss1.mtsp.co.in:15207/orders/regular" payload = { "tradingsecurity": "3045", "exchange": "NSECM", "transaction_type": "BUY", "order_type": "LIMIT", "quantity": "10", "validity": "DAY", "price": "830", "product": "CNC" } headers = { "Content-Type": "application/x-www-form-urlencoded", "Api-Version": "3", "Authorization": "API_KEY:REQUEST_TOKEN" } response = requests.post(url, data=payload, headers=headers) data = response.json() print(data)
{- "status": "successful",
- "data": {
- "orderid": "128439"
}
}
The Orders Regular SLBM APIs enable users to place and manage orders within the Stock Lending and Borrowing Market (SLBM).
Api-Version required | string Default: 3 It is necessary to keep API Version as 3 for this version of API. |
tradingsecurity | string Unique Security_ID of the script, example "150013" |
exchange | string NSESLBM |
transaction_type | string BUY/ SELL |
order_type | string MARKET, LIMIT |
quantity | string Example: 10 |
validity | string DAY, IOC |
price | string Example: 800.00 |
product | string CNC, NRML |
open_close | string BUY => Borrow/Recall, SELL=>Lend/Repay |
userid | string ClientID = The user id of the user, provided by Multitrade |
import requests url = "https://wss1.mtsp.co.in:15207/orders/regular" payload = { "tradingsecurity": "150013", "exchange": "NSESLBM", "transaction_type": "SELL", "order_type": "LIMIT", "quantity": "8", "validity": "DAY", "price": "800", "product": "NRML", "open_close":"Lend", "userid":"DAPI1" } headers = { "Content-Type": "application/x-www-form-urlencoded", "Api-Version": "3", "Authorization": "API_KEY:REQUEST_TOKEN" } response = requests.post(url, data=payload, headers=headers) data = response.json() print(data)
{- "status": "successful",
- "data": {
- "orderid": "17801"
}
}
This will provide order status of all the placed trades.
Api-Version required | string Default: 3 It is necessary to keep API Version as 3 for this version of API. |
import requests url = "https://wss1.mtsp.co.in:15207/orders" headers = { "Api-Version": "3", "Authorization": "API_KEY:REQUEST_TOKEN" } response = requests.get(url, headers=headers) data = response.json() print(data)
{- "status": "successful",
- "data": [
- {
- "order_id": "2918",
- "parent_order_id": "2918",
- "exchange_order_id": "O30452918",
- "placed_by": "DAPI1",
- "tradingsymbol": "SBIN",
- "exchange": "NSECM",
- "instrument_token": "3045",
- "transaction_type": "Sell",
- "order_type": "MARKET",
- "status": "Execute",
- "product": "CNC",
- "validity": "DAY",
- "price": "830.000000",
- "userid": "DAPI1",
- "quantity": "10",
- "trigger_price": "829.0000",
- "average_price": "747.700000",
- "pending_quantity": "0",
- "filled_quantity": "10",
- "disclosed_quantity": "0",
- "market_protection": "0.00",
- "order_timestamp": "23/03/202415:01:11",
- "exchange_timestamp": "23/03/202420:31:11",
- "status_message": "",
- "tag": "ReferenceTag"
}, - {
- "order_id": "2919",
- "parent_order_id": "2919",
- "exchange_order_id": "O30452919",
- "placed_by": "DAPI1",
- "tradingsymbol": "SBIN",
- "exchange": "NSECM",
- "instrument_token": "3045",
- "transaction_type": "Sell",
- "order_type": "MARKET",
- "status": "Execute",
- "product": "CNC",
- "validity": "DAY",
- "price": "830.000000",
- "userid": "DAPI1",
- "quantity": "10",
- "trigger_price": "0.000000",
- "average_price": "747.400000",
- "pending_quantity": "0",
- "filled_quantity": "10",
- "disclosed_quantity": "0",
- "market_protection": "0.00",
- "order_timestamp": "23/03/202415:01:19",
- "exchange_timestamp": "23/03/202420:31:19",
- "status_message": "",
- "tag": "MTS"
}, - {
- "order_id": "2920",
- "parent_order_id": "2920",
- "exchange_order_id": "O30452920",
- "placed_by": "DAPI1",
- "tradingsymbol": "SBIN",
- "exchange": "NSECM",
- "instrument_token": "3045",
- "transaction_type": "Sell",
- "order_type": "MARKET",
- "status": "Execute",
- "product": "NRML",
- "validity": "DAY",
- "price": "830.000000",
- "userid": "DAPI1",
- "quantity": "10",
- "trigger_price": "829.000000",
- "average_price": "748.050000",
- "pending_quantity": "0",
- "filled_quantity": "10",
- "disclosed_quantity": "0",
- "market_protection": "0.00",
- "order_timestamp": "23/03/202415:02:24",
- "exchange_timestamp": "23/03/202420:32:24",
- "status_message": "",
- "tag": "ReferenceTag"
}
]
}
This will provide order status of the placed trade with the help of OrderID.
Api-Version required | string Default: 3 It is necessary to keep API Version as 3 for this version of API. |
import requests url = "https://wss1.mtsp.co.in:15207/orders/2920" headers = { "Api-Version": "3", "Authorization": "API_KEY:REQUEST_TOKEN" } response = requests.get(url, headers=headers) data = response.json() print(data)
{- "status": "Successful",
- "data": [
- {
- "order_id": "2920",
- "parent_order_id": "2920",
- "exchange_order_id": "O30452920",
- "placed_by": "DAPI1",
- "status": "Execute",
- "tradingsymbol": "SBIN",
- "exchange": "NSECM",
- "instrument_token": "3045",
- "transaction_type": "Sell",
- "order_type": "MARKET",
- "product": "NRML",
- "validity": "DAY",
- "price": "829.000000",
- "userid": "DAPI1",
- "quantity": "10",
- "trigger_price": "0.000000",
- "average_price": "0.00",
- "pending_quantity": "0",
- "filled_quantity": "10",
- "disclosed_quantity": "0",
- "market_protection": "0.00",
- "order_timestamp": "23/03/202415:02:24",
- "exchange_timestamp": "23/03/202420:32:24",
- "status_message": "",
- "tag": "ReferenceTag"
}
]
}
This will provide order status of the placed trade with the help of Tag and OrderID.
Api-Version required | string Default: 3 It is necessary to keep API Version as 3 for this version of API. |
import requests url = "https://wss1.mtsp.co.in:15207/orders/ReferenceTag/2920" headers = { "Api-Version": "3", "Authorization": "API_KEY:REQUEST_TOKEN" } response = requests.get(url, headers=headers) data = response.json() print(data)
{- "status": "Successful",
- "data": [
- {
- "order_id": "2920",
- "parent_order_id": "2920",
- "exchange_order_id": "O30452920",
- "placed_by": "DAPI1",
- "status": "Execute",
- "tradingsymbol": "SBIN",
- "exchange": "NSECM",
- "instrument_token": "3045",
- "transaction_type": "Sell",
- "order_type": "MARKET",
- "product": "NRML",
- "validity": "DAY",
- "price": "829.000000",
- "userid": "DAPI1",
- "quantity": "10",
- "trigger_price": "0.000000",
- "average_price": "0.00",
- "pending_quantity": "0",
- "filled_quantity": "10",
- "disclosed_quantity": "0",
- "market_protection": "0.00",
- "order_timestamp": "23/03/202415:02:24",
- "exchange_timestamp": "23/03/202420:32:24",
- "status_message": "",
- "tag": "ReferenceTag"
}
]
}
It facility to modify your open orders by allowing you to change the limit order to market or vice versa, change the Price or Quantity of the limit open order, change the disclosed quantity, or stop-loss of any open stop-loss order.
Api-Version required | string Default: 3 It is necessary to keep API Version as 3 for this version of API. |
order_type | string MARKET, LIMIT, SL, SL-M |
quantity | string Order Quantity is the number of Sell or Buy orders |
price | string This is a price that a buyer wishes to purchase a security at, hence the price is delineated by the buyer. |
validity | string DAY, IOC, GTT, GTC, OPG, FOK, GTX, GTD, EOS, FAK, ATO, ATC |
trigger_price | string The price at which an order should be triggered (SL, SL-M) |
disclosed_quantity | string Quantity to disclose publicly (for equity trades) |
userid | string The user id of the user, provided by Multitrade |
import requests url = "https://wss1.mtsp.co.in:15207/orders/regular/128439" payload = { "order_type": "MARKET", "quantity": "5", "validity": "DAY", "price": "830" } headers = { "Content-Type": "application/x-www-form-urlencoded", "Api-Version": "3", "Authorization": "API_KEY:REQUEST_TOKEN" } response = requests.put(url, data=payload, headers=headers) data = response.json() print(data)
{- "status": "successful",
- "data": {
- "orderid": "128439"
}
}
This endpoint is used to update a regular order by its ID. it sends a PUT request to update the price of a regular order.
Api-Version required | string Default: 3 It is necessary to keep API Version as 3 for this version of API. |
order_type | string MARKET, LIMIT, SL, SL-M |
import requests url = "https://wss1.mtsp.co.in:15207/orders/regular/128439" payload='order_type = MARKET' headers = { 'Api-Version': '3', 'Authorization': 'API_KEY:REQUEST_TOKEN' } response = requests.request("PUT", url, headers=headers, data=payload) print(response.text)
{- "status": "successful",
- "data": {
- "orderid": "128439"
}
}
This API can be called to cancel any open order of the user by providing the correct appOrderID matching with the chosen open order to cancel.
Api-Version required | string Default: 3 It is necessary to keep API Version as 3 for this version of API. |
import requests url = "https://wss1.mtsp.co.in:15207/orders/regular/128439" payload={} headers = { 'Api-Version': '3', 'Authorization': 'API_KEY:REQUEST_TOKEN' } response = requests.request("DELETE", url, headers=headers, data=payload) print(response.text)
{- "status": "successful",
- "data": {
- "order_id": "194719"
}
}
When any order gets executed, a new trade event is generated by the server. Clients can listen to these events by registering to receive them.
Api-Version required | string Default: 3 It is necessary to keep API Version as 3 for this version of API. |
import requests url = "https://wss1.mtsp.co.in:15207/trades" payload={} headers = { 'Api-Version': '3', 'Authorization': 'API_KEY:REQUEST_TOKEN' } response = requests.request("GET", url, headers=headers, data=payload) print(response.text)
{- "status": "successful",
- "data": [
- {
- "trade_id": "1740",
- "order_id": "22",
- "exchange": "NSECM",
- "tradingsymbol": "SBIN",
- "instrument_token": "3045",
- "product": "CNC",
- "average_price": "747.70000000000005",
- "quantity": "10",
- "tag": "ReferenceTag",
- "placed_by": "DAPI1",
- "userid": "DAPI1",
- "transaction_type": "SELL",
- "exchange_order_id": "O30452918",
- "fill_timestamp": "23/03/202420:31:11",
- "order_timestamp": "15:01:11",
- "exchange_timestamp": "23/03/202420:31:11"
}, - {
- "trade_id": "1741",
- "order_id": "23",
- "exchange": "NSECM",
- "tradingsymbol": "SBIN",
- "instrument_token": "3045",
- "product": "CNC",
- "average_price": "747.39999999999998",
- "quantity": "10",
- "tag": "ReferenceTag",
- "placed_by": "DAPI1",
- "userid": "DAPI1",
- "transaction_type": "SELL",
- "exchange_order_id": "O30452919",
- "fill_timestamp": "23/03/202420:31:19",
- "order_timestamp": "15:01:19",
- "exchange_timestamp": "23/03/202420:31:19"
}, - {
- "trade_id": "1742",
- "order_id": "24",
- "exchange": "NSECM",
- "tradingsymbol": "SBIN",
- "instrument_token": "3045",
- "product": "NRML",
- "average_price": "748.04999999999995",
- "quantity": "10",
- "tag": "ReferenceTag",
- "placed_by": "DAPI1",
- "userid": "DAPI1",
- "transaction_type": "SELL",
- "exchange_order_id": "O30452920",
- "fill_timestamp": "23/03/202420:32:24",
- "order_timestamp": "15:02:24",
- "exchange_timestamp": "23/03/202420:32:24"
}
]
}
When any order gets executed, a new trade event is generated by the server. It can be retrieved particularly if OrderID is known.
Api-Version required | string Default: 3 It is necessary to keep API Version as 3 for this version of API. |
import requests url = "https://wss1.mtsp.co.in:15207/trades/2920" payload={} headers = { 'Api-Version': '3', 'Authorization': 'API_KEY:REQUEST_TOKEN' } response = requests.request("GET", url, headers=headers, data=payload) print(response.text)
{- "status": "successful",
- "data": [
- {
- "trade_id": "1742",
- "order_id": "24",
- "exchange_order_id": "O30452920",
- "tradingsymbol": "SBIN",
- "exchange": "NSECM",
- "instrument_token": "3045",
- "product": "NRML",
- "average_price": "748.04999999999995",
- "quantity": "10",
- "placed_by": "DAPI1",
- "userid": "DAPI1",
- "transaction_type": "Sell",
- "tag": "ReferenceTag",
- "fill_timestamp": "23/03/202420:32:24",
- "exchange_timestamp": "23/03/202420:32:24"
}
]
}
When any order gets executed, a new trade event is generated by the server. It can be retrieved selectively if OrderID and reference tag is known.
Api-Version required | string Default: 3 It is necessary to keep API Version as 3 for this version of API. |
import requests url = "https://wss1.mtsp.co.in:15207/trades/ReferenceTag/2920" payload={} headers = { 'Api-Version': '3', 'Authorization': 'API_KEY:REQUEST_TOKEN' } response = requests.request("GET", url, headers=headers, data=payload) print(response.text)
{- "status": "Successful",
- "data": [
- {
- "trade_id": "1742",
- "order_id": "24",
- "exchange_order_id": "O30452920",
- "tradingsymbol": "SBIN",
- "exchange": "NSECM",
- "instrument_token": "3045",
- "product": "NRML",
- "average_price": "748.04999999999995",
- "quantity": "10",
- "placed_by": "DAPI1",
- "userid": "DAPI1",
- "transaction_type": "Sell",
- "tag": "ReferenceTag",
- "fill_timestamp": "23/03/202420:32:24",
- "exchange_timestamp": "23/03/202420:32:24"
}
]
}
The Instruments API provides a single, easy-to-use CSV list of tradable assets from different exchanges and segments.
Retrieving the full instrument list: Unlike other API calls that return JSON, the instruments API returns a gzipped CSV dump of instruments across all exchanges, which can be imported into a database. The dump is generated once every day, and thus the last_price field is not real-time.
Response Structure:
security_id | security_id. | symbol | security_description | previous_close | expiry_date | strike_price | tick_size | quantity | option_type | instrument_type | exchange | face value |
---|---|---|---|---|---|---|---|---|---|---|---|---|
2000259 | 2000259 | TRENT | TRENT24FEB3640PE | 128.75 | 29FEB2024 | 3640.00 | 0.05 | 400.00 | PE | OPTSTK | BSEFO | 1.00 |
2000259 | 2000259 | TRENT | TRENT24FEB3620CE | 132.50 | 29FEB2024 | 3620.00 | 0.05 | 300.00 | CE | OPTSTK | BSEFO | 1.00 |
2000260 | 2000259 | INFY | INFY24FEB2000CE | 45.80 | 29FEB2024 | 2000.00 | 0.05 | 500.00 | CE | OPTSTK | NSEFO | 5.00 |
2000260 | 2000259 | INFY | INFY24FEB2100PE | 50.00 | 29FEB2024 | 2100.00 | 0.05 | 700.00 | PE | OPTSTK | NSEFO | 5.00 |
2000261 | 2000259 | RELIANCE | REL24FEB2500PE | 73.20 | 29FEB2024 | 2500.00 | 0.05 | 200.00 | PE | OPTSTK | NSEFO | 10.00 |
Note:
The CSV file is very large, so this is only a snippet of the CSV response file.
Api-Version required | string Default: 3 It is necessary to keep API Version as 3 for this version of API. |
import requests import csv url = "https://wss1.mtsp.co.in:15207/instruments" headers = { 'Api-Version': '3', 'Authorization': 'API_KEY:REQUEST_TOKEN' 'Content-Type':'application/x-www-form-urlencoded' } response = requests.get( url, headers=headers,verify=False) if response.status_code ==200: content =response.content.decode('utf-8') csv_data = [line.split(',')for line in content.split('\n')if line.strip()] with open ('response_data.csv','w',newline='')as csvfile: writer = csv.writer(csvfile) writer.writerows(csv_data) print("Data has been written to response_data.csv successfully.") else: print(f"Error:{reasponse.status_code}")
With this Endpoint user can get required ExpiryDate of the contract directly with the help of symbol and exchange.
Api-Version required | string Default: 3 It is necessary to keep API Version as 3 for this version of API. |
symbol | string Symbol of instrument , example "NIFTY" |
exchange | string Exchange of instrument , example "NSEFO" |
import requests url = "https://wss1.mtsp.co.in:15207/expirydate" payload = { "symbol":"NIFTY", "exchange":"NSEFO" } headers = { "Api-Version": "3", "Content-Type": "application/x-www-form-urlencoded", "Authorization": "API_KEY:REQUEST_TOKEN" } response = requests.get(url, data=payload, headers=headers) data = response.json() print(data)
{- "status": "successful",
- "data": {
- "exchange": "NSEFO",
- "symbol": "NIFTY",
- "expiry": "06JUN2024,09MAY2024,16MAY2024,23MAY2024,24DEC2025,24JUN2027,25JUL2024,25JUN2026"
}
}
With this endpoint, users can directly obtain the InstrumentID of the required index, this is also known as SecurityID and tradingsecurity of the instrument.
Api-Version required | string Default: 3 It is necessary to keep API Version as 3 for this version of API. |
symbol | string Symbol of instrument , example "NIFTY" |
exchange | string Exchange of instrument , example "NSECM" |
instrument_type | string Instrument_type of instrument, example "INDEX" |
import requests url = "https://wss1.mtsp.co.in:15207/instrumentid" payload = { "symbol": "NIFTY", "exchange": "NSECM", "instrument_type": "INDEX", } headers = { "Api-Version": "3", "Authorization": "API_KEY:REQUEST_TOKEN" } response = requests.get(url, data=payload, headers=headers) data = response.json() print(data)
{- "status": "successful",
- "data": {
- "exchange": "NSECM",
- "symbol": "Nifty 50",
- "expiry_date": "",
- "strike_price": "21000.00",
- "instrument_type": "INDEX",
- "instrument_id": "Nifty 50 "
}
}
With this endpoint, users can directly obtain the InstrumentID of the required Euquity, this is also known as SecurityID and tradingsecurity of the instrument.
Api-Version required | string Default: 3 It is necessary to keep API Version as 3 for this version of API. |
symbol | string Symbol of instrument, example "TCS" |
expiry_date | string ExpiryDate of instrument , Note- For NSECM, expiry_date should be "EQ" and For BSECM, expiry_date should be "A" |
exchange | string Exchange of instrument, example "NSECM" |
instrument_type | string Instrument_type of instrument , example "EQUITY/EQ" |
import requests url = "https://wss1.mtsp.co.in:15207/instrumentid" payload = { "symbol": "TCS", "expiry_date": "EQ", "exchange": "NSECM", "instrument_type": "EQUITY", } headers = { "Api-Version": "3", "Authorization": "API_KEY:REQUEST_TOKEN" } response = requests.get(url, data=payload, headers=headers) data = response.json() print(data)
{- "status": "successful",
- "data": {
- "exchange": "NSECM",
- "symbol": "TCS",
- "expiry_date": "EQ",
- "instrument_type": "EQUITY",
- "instrument_id": "11536"
}
}
With this endpoint, users can directly obtain the InstrumentID of the required Option, this is also known as SecurityID and tradingsecurity of the instrument.
Api-Version required | string Default: 3 It is necessary to keep API Version as 3 for this version of API. |
symbol | string Symbol of instrument , example "NIFTY" |
expiry_date | string ExpiryDate of instrument, example "16MAY2024" |
strike_price | string Strike_price of instrument , example "21000" |
option_type | string Option_type of instrument, example "CE/PE" |
exchange | string Exchange of instrument, example "NSEFO" |
instrument_type | string instrument_type of instrument, example "OPT/OPTION" |
import requests url = "https://wss1.mtsp.co.in:15207/instrumentid" payload = { "symbol": "NIFTY", "expiry_date": "16MAY2024", "strike_price": "21000", "option_type": "PE", "exchange": "NSEFO", "instrument_type": "OPT", } headers = { "Api-Version": "3", "Authorization": "API_KEY:REQUEST_TOKEN" } response = requests.get(url, data=payload, headers=headers) data = response.json() print(data)
{- "status": "successful",
- "data": {
- "symbol": "NIFTY",
- "expiry_date": "16MAY2024",
- "strike_price": "21000",
- "option_type": "PE",
- "exchange": "NSEFO",
- "instrument_type": "OPT"
}
}
With this endpoint, users can directly obtain the InstrumentID of the required Future, this is also known as SecurityID and tradingsecurity of the instrument.
Api-Version required | string Default: 3 It is necessary to keep API Version as 3 for this version of API. |
symbol | string Symbol of instrument, example "NIFTY" |
expiry_date | string ExpiryDate of instrument, example "25JUL2024" |
exchange | string exchange of instrumen, example "NSEFO" |
instrument_type | string instrument_type of instrument, example "FUT/FUTIDX" |
import requests url = "https://wss1.mtsp.co.in:15207/instrumentid" payload = { "symbol": "NIFTY", "expiry_date": "25JUL2024", "exchange": "NSEFO", "instrument_type": "FUT", } headers = { "Api-Version": "3", "Authorization": "API_KEY:REQUEST_TOKEN" } response = requests.get(url, data=payload, headers=headers) data = response.json() print(data)
{- "status": "successful",
- "data": {
- "exchange": "NSEFO",
- "symbol": "NIFTY",
- "expiry_date": "25JUL2024",
- "instrument_type": "FUTIDX",
- "instrument_id": "35007"
}
}
This API provides a list of ongoing auctions, including details like auction number, the security being auctioned, its last traded price, and the quantity available. The auctions list will only display stocks held in your demat account.
Api-Version required | string Default: 3 It is necessary to keep API Version as 3 for this version of API. |
tradingsecurity | string Unique Security_ID of the script, example "220" |
exchange | string NSECM |
transaction_type | string SELL |
order_type | string AUCTION |
quantity | string Example: 10 |
validity | string DAY |
price | string Example: 830.00 |
product | string CNC, NRML |
userid | string ClientID = The user id of the user, provided by Multitrade |
tag | string An optional tag to apply to an order to identify it (alphanumeric, max 20 chars) |
auction_number | string The auction_number of the symbol. |
import requests url = "https://wss1.mtsp.co.in:15207/auctionorder" payload = { "tradingsecurity": "220", "exchange": "NSECM", "transaction_type": "SELL", "order_type": "AUCTION", "quantity": "10", "validity": "DAY", "price": "830", "product": "CNC", "userid":"DAPI1", "tag":"ReferenceTag", "auction_number":"2044" } headers = { "Content-Type": "application/x-www-form-urlencoded", "Api-Version": "3", "Authorization": "API_KEY:REQUEST_TOKEN" } response = requests.post(url, data=payload, headers=headers) data = response.json() print(data)
{- "status": "successful",
- "data": {
- "orderid": "1378"
}
}
The Auction Orders API gives a daily gzipped CSV file of auction orders from exchanges.
Response Structure:
SecurityID | Symbol | AuctionNo | AuctinStatus | InitiatorType | TotalBuyQty | BuyAmount | TotalSellQty | SellAmount | AuctionQty | AuctionPrice | SettlementPeriod | DateTime |
---|---|---|---|---|---|---|---|---|---|---|---|---|
4668 | BANKBARODA | 15 | OPEN_SOLICITOR_PERIOD | 0 | 1 | 0.00 | 4 | 265.00 | 0 | 0.00 | 1 | 15:47:03 |
383 | BEL | 16 | OPEN_SOLICITOR_PERIOD | 0 | 1 | 0.00 | 3 | 228.00 | 0 | 0.00 | 1 | 08:52:33 |
21113 | BFINVEST | 17 | OPEN_SOLICITOR_PERIOD | 0 | 1 | 0.00 | 2 | 591.00 | 0 | 0.00 | 1 | 08:54:18 |
4749 | CONCOR | 30 | OPEN_SOLICITOR_PERIOD | 0 | 1 | 0.00 | 1 | 1049.00 | 0 | 0.00 | 1 | 15:46:45 |
422 | BHARATFORG | 19 | OPEN_SOLICITOR_PERIOD | 0 | 1 | 0.00 | 1500 | 1433.85 | 0 | 0.00 | 1 | 08:53:52 |
Note:
The CSV file is very large, so this is only a snippet of the CSV response file.
Api-Version required | string Default: 3 It is necessary to keep API Version as 3 for this version of API. |
import requests url = "https://wss1.mtsp.co.in:15207/auctions" headers = { 'Api-Version': '3', } response = requests.request("GET", url, headers=headers) print(response.text)
Python
import asyncio
import websockets
async def connect_to_server():
async with websockets.connect('wss://wss1.mtsp.co.in:15207') as websocket:
sc = "{\"Message\":\"Login\",\"API_KEY\":\".KAoiU$GCfrrNDN4H|qq<<XtG\",\"REQUEST_TOKEN\":\"9uGleQ4keI9zL!3oZ.9d\"}"
await websocket.send(sc)
while True:
response = await websocket.recv()
print( response )
return
asyncio.run(connect_to_server())
Node.js
const WebSocket = require('ws');
async function connectToServer() {
const ws = new WebSocket('wss://wss1.mtsp.co.in:15207');
ws.on('open', function open() {
const sc = "{\"Message\":\"Login\",\"API_KEY\":\".KAoiU$GCfrrNDN4H|qq<<XtG\",\"REQUEST_TOKEN\":\"9uGleQ4keI9zL!3oZ.9d\"}";
ws.send(sc);
});
ws.on('message', function incoming(data) {
console.log(data);
});
}
connectToServer();
Response 1 -
When the websocket connection is established and the user is Successfuly logged in, a "success" response will be received. The connection will then remain open, awaiting further updates from the server, such as when a new order is placed.
{"Message":"LoginResponse","Status":"success"}
Response 1 -
When an order is placed via API or through ATINS (outside of the websocket), this will provide the following response:
{
"Message": "Order",
"status": "Successful",
"data": {
"order_id": "23",
"parent_order_id": "6746",
"exchange_order_id": "",
"placed_by": "DAPI1",
"tradingsymbol": "RELIANCE",
"exchange": "NSECM",
"instrument_token": "2885",
"transaction_type": "Buy",
"order_type": "MARKET",
"status": "Unknown",
"product": "CNC",
"validity": "DAY",
"price": "0.00",
"userid": "DAPI1",
"quantity": "100",
"trigger_price": "0.00",
"pending_quantity": "100",
"filled_quantity": "0",
"disclosed_quantity": "0",
"order_timestamp": "02\/03\/2024 18:58:09",
"exchange_timestamp": "01\/01\/1970 05:30:00",
"status_message": "",
"tag": "HELLOMOTO2"
}
}
Order structure:
Response 2 -
When an trade happens in a order placed via API or through ATINS, this will provide the following Trade response:
{
"Message": "Trade",
"status": "Successful",
"data": {
"trade_id": "12440",
"order_id": "6746",
"exchange_trade_id": "T28856746975208",
"exchange_order_id": "O28856746",
"Exchange": "NSECM",
"tradingsymbol": "RELIANCE",
"instrument_token": "2885",
"tag": "HELLOMOTO2",
"product": "CNC",
"average_price": "2939.50",
"price": "2939.50",
"quantity": "100",
"pending_quantity": "0",
"transaction_type": "BUY",
"fill_timestamp": "2024-03-03 00:28:09",
"order_timestamp": "00:28:09",
"exchange_timestamp": "2024-03-03 00:28:09"
}
}
Trade Response structure:
EXC | string Represents the exchange where the security is traded (e.g., "NSEFO"). |
SECID | string Represents the security identifier (e.g., "2885" ). |
FROM | string Represents the start date or time for the data query (e.g., "1719804600" ) . |
TO | string Represents the end date or time for the data query (e.g., "1719914400" ) . |
RESOLUTION | string For getting data in intervals of X Minutes send this as X . For getting data in intervals of X Days send this as XD . For getting data in intervals of X Weeks send this as XW .For getting data in intervals of X Months send this as XM ( e.g., X,XD,XW,XM ). |
import requests url = "https://wss1.mtsp.co.in:15208/ticks?EXC=NSECM&SECID=2885&FROM=1719998100&TO=1720020600&RESOLUTION=15" response = requests.request("GET", url) print(response.text)
{- "Response": "Success",
- "FROM": "1719809100",
- "TO": "1719914400",
- "data": [
- {
- "0": [
- "1719809100",
- "2897.00",
- "2898.95",
- "2895.00",
- "2895.55",
- "715000",
- "65000"
], - "1": [
- "1719810000",
- "2896.30",
- "2898.80",
- "2893.55",
- "2896.35",
- "970000",
- "65000"
], - "2": [
- "1719810900",
- "2896.00",
- "2898.95",
- "2893.55",
- "2896.30",
- "971000",
- "65000"
], - "3": [
- "1719811800",
- "2895.80",
- "2898.95",
- "2893.55",
- "2896.00",
- "969000",
- "63000"
], - "4": [
- "1719812700",
- "2894.20",
- "2898.95",
- "2893.55",
- "2895.35",
- "971000",
- "65000"
]
}
]
}
The WebSocket API is the most efficient (speed, latency, resource consumption, and bandwidth) way to receive quotes for instruments across all exchanges during live market hours. A quote consists of fields such as open, high, low, close, last traded price, 5 levels of bid/offer market depth data etc
Establishing WebSocket connection
To achieve the equivalent WebSocket connection in Python, you can use the websockets library. Here's how you can do it:
Python
import asyncio
import websockets
async def connect_to_server():
async with websockets.connect('wss://wss1.mtsp.co.in:15208') as websocket:
response = await websocket.recv()
if "HandShake" in response:
print("WebSocket connection successful!")
else:
print("WebSocket connection failed")
asyncio.run(connect_to_server())
Node.js
const WebSocket = require('ws');
async function connectToServer() {
const websocket = new WebSocket('wss://wss1.mtsp.co.in:15208');
websocket.on('message', function(message) {
if (message.includes('HandShake')) {
console.log('WebSocket connection successful!');
} else {
console.log('WebSocket connection failed');
}
websocket.close();
});
}
connectToServer();
It awaits a message (response) from the server using websocket.recv(). If the received message contains the substring "HandShake", it prints "WebSocket connection successful!" indicating that the handshake process was successful. If the message does not contain "HandShake", it prints "WebSocket connection failed".
The script establishes a WebSocket connection to a server, sends a "Broadcast" message upon receiving a handshake, and processes and prints the received broadcast messages containing market data.
Request Structure -
{"Message": "Broadcast",
"EXC": "NSECM",
"SECID": "3045"}
Python
import asyncio
import websockets
async def connect_to_server():
async with websockets.connect('wss://wss1.mtsp.co.in:15208') as websocket:
response = await websocket.recv()
if "HandShake" in response:
sc = "{\"Message\":\"Broadcast\",\"EXC\":\"NSECM\",\"SECID\":\"3045\"}"
await websocket.send(sc)
response = await websocket.recv()
if "\"Broadcast\"" in response:
print(response)
else:
print("WebSocket connection failed")
asyncio.run(connect_to_server())
Node.js
const WebSocket = require('ws');
async function connect() {
const ws = new WebSocket('wss://wss1.mtsp.co.in:15208');
ws.on('open', () => ws.send('{"Message":"Broadcast","EXC":"NSECM","SECID":"3045"}'));
ws.on('message', data => {
if (data instanceof Buffer) {
// Convert binary buffer to string
data = data.toString('utf-8');
}
console.log(data.includes('"Broadcast"') ? data : 'WebSocket connection failed');
});
}
connect();
Upon receiving a response to this broadcast message, it checks if the response contains "Broadcast". If so, it prints the entire response. The broadcast response itself is a JSON object containing various fields related to market data. Broadcast response comes in json format, which can further be pursed according to the need and requirement.
JSON Output -
{
"Message": "Broadcast",
"EXC": "NSECM",
"SECID": "3045",
"BT": "1709113203",
"B": [
{
"P": "743.45",
"Q": "91",
"C": "4"
},
{
"P": "743.40",
"Q": "2453",
"C": "8"
},
{
"P": "743.35",
"Q": "26",
"C": "3"
},
{
"P": "743.30",
"Q": "2327",
"C": "16"
},
{
"P": "743.25",
"Q": "316",
"C": "8"
}
],
"A": [
{
"P": "743.50",
"Q": "11",
"C": "1"
},
{
"P": "743.55",
"Q": "267",
"C": "4"
},
{
"P": "743.65",
"Q": "1500",
"C": "1"
},
{
"P": "743.70",
"Q": "11",
"C": "1"
},
{
"P": "743.75",
"Q": "2530",
"C": "7"
}
],
"TQT": "10120104",
"LTP": "743.50",
"LTQ": "12",
"LTT": "1709113203",
"VWAP": "748.39",
"TBQTY": "609120",
"TSQTY": "1216842",
"O": "749.85",
"H": "756.75",
"L": "741.00",
"C": "749.85",
"OI": "0",
"LL": "501.55",
"LH": "777.50",
"TV": "75737.85"
}
The broadcast response itself is a JSON object containing various fields related to market data. Here's a breakdown of the structure:
Parsing Live VWAP value (From Broadcast)
This is the sample code for getting live VWAP out of broadcast message. Similarly we can all other like the Volume Last trded price (LTP), Last Traded Quantity (LTQ), Close price(C), and more. It's all about finding the right names for these values in the JSON data and adjusting the script accordingly. With a bit of tweaking, you can easily fetch and keep an eye on various live market statistics that matter to you.
Python
import asyncio
import websockets
async def connect_to_server():
async with websockets.connect('wss://wss1.mtsp.co.in:15208') as websocket:
response = await websocket.recv()
if "HandShake" in response:
sc = "{\"Message\":\"Broadcast\",\"EXC\":\"NSECM\",\"SECID\":\"3045\"}"
await websocket.send(sc)
OldVWAP = -1
while True:
response = await websocket.recv()
if "\"Broadcast\"" in response:
response_string = response
responses = response_string.strip().split("\n\n")
for res in responses:
data = json.loads(res)
if "LTP" in data:
if (OldVWAP != data["VWAP"] ):
OldVWAP = data["VWAP"]
print("VWAP:", data["VWAP"])
asyncio.run(connect_to_server())
Node.js
const WebSocket = require('ws');
async function connectToServer() {
const ws = new WebSocket('wss://wss1.mtsp.co.in:15208');
ws.on('open', async () => {
const sc = '{"Message":"Broadcast","EXC":"NSECM","SECID":"3045"}';
await ws.send(sc);
});
let oldVWAP = -1;
ws.on('message', data => {
const response = data.toString();
if (response.includes('"VWAP"')) {
const responses = response.trim().split("\n\n");
for (const res of responses) {
try {
const jsonData = JSON.parse(res);
if (jsonData["VWAP"] && oldVWAP !== jsonData["VWAP"]) {
oldVWAP = jsonData["VWAP"];
console.log("VWAP:", jsonData["VWAP"]);
}
} catch (error) {
console.error('Error parsing JSON:', error);
}
}
}
});
}
connectToServer().catch(console.error);
Output:
VWAP: 766.44
VWAP: 766.45
VWAP: 766.46
VWAP: 766.47
VWAP: 766.48
VWAP: 766.51
VWAP: 766.52
VWAP: 766.53
VWAP: 766.54
VWAP: 766.62
VWAP: 766.76
.
.
.
and so on
VWAP is crucial in stock trading, showing the average price weighted by volume. Traders rely on it to gauge fair value, decide on trades, and minimize market impact. It's especially handy for intraday analysis and algorithmic trading, offering a key reference point for efficient market navigation.
It is the Last Traded Price at which a security was traded on an exchange. It provides a real-time snapshot of a security's valuation, guiding investment decisions and trading strategies based on current market sentiment.
Request Structure -
{ "Message": "LTP",
"EXC": "NSEFO",
"SECID": "35020" }
Python
import asyncio
import websockets
async def connect_to_server():
async with websockets.connect('wss://wss1.mtsp.co.in:15208') as websocket:
response = await websocket.recv()
if "HandShake" in response:
sc = "{\"Message\":\"LTP\",\"EXC\":\"NSEFO\",\"SECID\":\"35020\"}"
await websocket.send(sc)
while True:
response = await websocket.recv()
if "\"LTP\"" in response:
print(response)
else:
print("WebSocket connection failed")
asyncio.run(connect_to_server())
Node.js
const WebSocket = require('ws');
async function connect() {
const ws = new WebSocket('wss://wss1.mtsp.co.in:15208');
ws.on('open', () => ws.send('{"Message":"LTP","EXC":"NSEFO","SECID":"35020"}'));
ws.on('message', data => {
if (data instanceof Buffer) {
// Convert binary buffer to string
data = data.toString('utf-8');
}
console.log(data.includes('"LTP"') ? data : 'WebSocket connection failed');
});
}
connect();
JSON Output -
{
"Message": "LTP",
"EXC": "NSEFO",
"SECID": "35020",
"LTP": "20915.00"
}
LTP Response structure:
OHLCL stands for Open, High, Low, Close. It's a set of data points commonly used in financial markets to summarize the trading activity of a security over a given period. This data is essential for technical analysis, charting, and understanding market trends.
Request Structure -
{"Message": "OHLCL",
"EXC": "NSEFO",
"SECID": "35707"}
Python
import asyncio
import websockets
async def connect_to_server():
async with websockets.connect('wss://wss1.mtsp.co.in:15208') as websocket:
response = await websocket.recv()
if "HandShake" in response:
sc = "{\"Message\":\"OHLCL\",\"EXC\":\"NSEFO\",\"SECID\":\"35707\"}"
await websocket.send(sc)
while True:
response = await websocket.recv()
if "\"OHLCL\"" in response:
print(response)
else:
print("WebSocket connection failed")
asyncio.run(connect_to_server())
Node.js
const WebSocket = require('ws');
async function connect() {
const ws = new WebSocket('wss://wss1.mtsp.co.in:15208');
ws.on('open', () => ws.send('{"Message":"OHLCL","EXC":"NSEFO","SECID":"35707"}'));
ws.on('message', data => {
if (data instanceof Buffer) {
// Convert binary buffer to string
data = data.toString('utf-8');
}
console.log(data.includes('"OHLCL"') ? data : 'WebSocket connection failed');
});
}
connect();
JSON Output -
{
"Message": "OHLCL",
"EXC": "NSEFO",
"SECID": "35707",
"O": "11015.00",
"H": "11099.25",
"L": "11013.10",
"C": "10985.00",
"LTP": "11092.05"
}
OHLCL response structure:
The provided data includes essential information for tracking securities in financial markets. It covers details such as the exchange where the security is traded, its unique identifier, and recent trading activity. Other important data points encompass the total quantity and value traded, along with prices at the open, high, low, and close of trading sessions. Additionally, it includes timestamps for the last trade and broadcast, as well as open interest and volume-weighted average price. These details are vital for investors and traders to monitor market movements and make informed decisions.
Request Structure -
{ "Message": "Watch",
"EXC": "NSEFO",
"SECID": "71441" }
Python
import asyncio
import websockets
async def connect_to_server():
async with websockets.connect('wss://wss1.mtsp.co.in:15208') as websocket:
response = await websocket.recv()
if "HandShake" in response:
sc = "{\"Message\":\"Watch\",\"EXC\":\"NSEFO\",\"SECID\":\"71441\"}"
await websocket.send(sc)
while True:
response = await websocket.recv()
if "\"Watch\"" in response:
print(response)
else:
print("WebSocket connection failed")
asyncio.run(connect_to_server())
Node.js
const WebSocket = require('ws');
async function connect() {
const ws = new WebSocket('wss://wss1.mtsp.co.in:15208');
ws.on('open', () => ws.send('{"Message":"Watch","EXC":"NSEFO","SECID":"71441"}'));
ws.on('message', data => {
if (data instanceof Buffer) {
// Convert binary buffer to string
data = data.toString('utf-8');
}
console.log(data.includes('"Watch"') ? data : 'WebSocket connection failed');
});
}
connect();
JSON Output -
{
"Message": "Watch",
"EXC": "NSEFO",
"SECID": "71441",
"LTP": "22287.55",
"LTQ": "50",
"BP": "22285.05",
"BQ": "50",
"SP": "22287.05",
"SQ": "250",
"TQT": "1495350",
"TV": "332965.69659000001",
"BT": "1708663448",
"LLT": "1708663447",
"VWAP": "22266.74",
"OI": "11420900",
"O": "22285.10",
"H": "22344.45",
"L": "22235.10",
"C": "22243.25"
}
Watch response structure:
This script establishes a WebSocket connection to a server, sends an "Auction" message upon receiving a handshake, and processes and prints the received auction messages containing auction data.
Request Structure -
{ "Message": "Auction",
"EXC": "NSECM",
"SECID": "10397" }
Python
import asyncio
import websockets
async def connect_to_server():
async with websockets.connect('wss://wss1.mtsp.co.in:15208') as websocket:
response = await websocket.recv()
if "HandShake" in response:
sc = "{\"Message\":\"Auction\",\"EXC\":\"NSECM\",\"SECID\":\"10397\"}"
await websocket.send(sc)
response = await websocket.recv()
if "\"Auction\"" in response:
print(response)
else:
print("WebSocket connection failed")
asyncio.run(connect_to_server())
Node.js
const WebSocket = require('ws');
async function connect() {
const ws = new WebSocket('wss://wss1.mtsp.co.in:15208');
ws.on('open', () => ws.send('{"Message":"Auction","EXC":"NSECM","SECID":"10397"}'));
ws.on('message', data => {
if (data instanceof Buffer) {
// Convert binary buffer to string
data = data.toString('utf-8');
}
console.log(data.includes('"Auction"') ? data : 'WebSocket connection failed');
});
}
connect();
JSON Output -
{
"Message": "Auction",
"EXC": "NSECM",
"SECID": "10397",
"BT": "1709113203",
"B": [
{
"P": "0.00",
"Q": "151",
"C": "0"
},
{
"P": "0.00",
"Q": "0",
"C": "0"
},
{
"P": "0.00",
"Q": "0",
"C": "0"
},
{
"P": "0.00",
"Q": "0",
"C": "0"
},
{
"P": "0.00",
"Q": "0",
"C": "0"
}
],
"A": [
{
"P": "89.00",
"Q": "151",
"C": "0"
},
{
"P": "90.90",
"Q": "150",
"C": "0"
},
{
"P": "91.00",
"Q": "151",
"C": "0"
},
{
"P": "91.50",
"Q": "50",
"C": "0"
},
{
"P": "91.86",
"Q": "151",
"C": "0"
}
],
"TQT": "0",
"LTP": "0.00",
"LTQ": "0",
"LTT": "0",
"VWAP": "0.00",
"TBQTY": "0",
"TSQTY": "653",
"O": "0.00",
"H": "0.00",
"L": "0.00",
"C": "0.00",
"OI": "0",
"LL": "0.00",
"LH": "0.00",
"TV": "0.00"
"DPR": "60.82-91.23"
}
The Auction response itself is a JSON object containing various fields related to market data. Here's a breakdown of the structure: