myntapi 0.0.7
This PIP package used for Algo traders
Requires Python: >=3.6

## Mynt PIP package

- [login](#md-login)
- [logout](#md-logout)
- [Oauth_login](#md-oauth_login)
- [Oauth_login_using_code](#md-oauth_login_using_code)
- [set_session](#md-set_session)

Symbols
- [searchscrip](#md-searchscrip)
- [get_security_info](#md-get_security_info)
- [get_quotes](#md-get_quotes)
- [get_time_price_series](#md-get_time_price_series)
- [get_daily_price_series](#md-get_daily_price_series)
- [get_option_chain](#md-get_optionchain)

Orders and Trades
- [place_order](#md-place_order)
- [modify_order](#md-modify_order)
- [cancel_order](#md-cancel_order)
- [exit_order](#md-exit_order)
- [product_convertion](#md-prd_convert)
- [get_orderbook](#md-get_orderbook)
- [get_tradebook](#md-get_tradebook)
- [get_singleorderhistory](#md-get_singleorderhistory)
- [place_basket](#md-place_basket)
- [close_all_position](#md-close_all_position)

Holdings and Limits
- [get_holdings](#md-get_holdings)
- [get_positions](#md-get_positions)
- [get_limits](#md-get_limits)

Calculators
- [span_calculator](#md-span_calculator)
- [get_option_greek](#md-get_option_greek)

Websocket mt
- [start_websocket](#md-start_websocket)
- [subscribe](#md-subscribe)
- [unsubscribe](#md-unsubscribe)

Example
- [getting started](#md-example-basic)
- [Market Functions](#md-example-market)
- [Orders and Trade](#md-example-orders)

#### <a name="md-login"></a> login(userid, password, twoFA, vendor_code, api_secret, imei)

**⚠️ DEPRECATED - This login method will be disabled**

The old login flow (`login()`) has limitations:
- Sessions expire after a few days and stop working
- This authentication method will be **disabled** in the future

**Please use [OAuth login](#md-oauth_login) instead** for reliable, long-term authentication.

connect to the broker, only once this function has returned successfully can any other operations be performed

Example: 
```
#credentials
user    = <uid>
pwd     = <password>
factor2 = <2nd factor>
vc      = <vendor code>
app_key = <secret key>
imei    = <imei>


from myntapi import app
import logging


mt=app()

logging.basicConfig(level=logging.DEBUG)
ret = mt.login(userid=uid, password=pwd, twoFA=factor2, vendor_code=vc, api_secret=app_key, imei=imei)
```
Request Details :

|Json Fields|Possible value|Description|
| --- | --- | ---|
|apkversion*||Application version.|
|uid*||User Id of the login user|
|pwd*||user entered password.|
|factor2*||DOB or PAN as entered by the user. (DOB should be in DD-MM-YYYY)|
|vc*||Vendor code provided by zebu team, along with go.mynt.in|
|api_secret*||you will get from go.mynt.in API key (app key)|
|imei*||Send mac if users logs in for desktop, imei is from mobile|
|addldivinf||Optional field, Value must be in below format:|iOS - iosInfo.utsname.machine - iosInfo.systemVersion|Android - androidInfo.model - androidInfo.version|examples:|iOS - iPhone 8.0 - 9.0|Android - Moto G - 9 PKQ1.181203.01|
|ipaddr||Optional field|
|source|API||


Response Details :


|Json Fields|Possible value|Description|
| --- | --- | ---|
|stat|Ok or Not_Ok|Login Success Or failure status|
|susertoken||It will be present only on login success. This data to be sent in subsequent requests in jKey field and web socket connection while connecting. |
|lastaccesstime||It will be present only on login success.|
|spasswordreset|Y |If Y Mandatory password reset to be enforced. Otherwise the field will be absent.|
|exarr||Json array of strings with enabled exchange names|
|uname||User name|
|prarr||Json array of Product Obj with enabled products, as defined below.|
|actid||Account id|
|email||Email Id|
|brkname||Broker id|
|emsg||This will be present only if Login fails.|(Redirect to force change password if message is “Invalid Input : Password Expired” or “Invalid Input : Change Password”)|


Sample Success Response :
{
    "request_time": "20:18:47 19-05-2020",
    "stat": "Ok",
    "susertoken": "3b97f4c67762259a9ded6dbd7bfafe2787e662b3870422ddd343a59895f423a0",
    "lastaccesstime": "1589899727"
}

Sample Failure Response :
{
    "request_time": "20:32:14 19-05-2020",
    "stat": "Not_Ok",
    "emsg": "Invalid Input : Wrong Password"
}

#### <a name="md-logout"></a> logout()
Terminate the session

Example: 
```
ret = mt.logout()
```

Request Details :

|Json Fields|Possible value|Description|
| --- | --- | ---|
|uid*||User Id of the login user|

Response Details :
Response data will be in json format with below fields.
|Json Fields|Possible value|Description|
| --- | --- | ---|
|stat|Ok or Not_Ok|Logout Success Or failure status|
|request_time||It will be present only on successful logout.|
|emsg||This will be present only if Logout fails.|

Sample Success Response :
{
   "stat":"Ok",
   "request_time":"10:43:41 28-05-2020"
}

Sample Failure Response :
{
   "stat":"Not_Ok",
   "emsg":"Server Timeout :  "
}

#### <a name="md-oauth_login"></a> Oauth_login(client_id, client_secret)
Initiates the complete OAuth 2.0 login flow with automatic callback handling.

This method:
1. Displays your system's public IP address
2. Creates a localhost callback URL (`http://localhost:8189/callback`)
3. Shows the OAuth authorization URL you need to visit
4. Starts a local HTTP server to receive the OAuth callback
5. Waits for you to complete authorization in your browser
6. Automatically exchanges the authorization code for an access token
7. Sets up your session for subsequent API calls
8. Updates the API endpoint to the OAuth endpoint

Example: 
```
from myntapi import app_oauth

# Initialize the OAuth API client
mt = app_oauth()

# OAuth credentials (obtain from go.mynt.in)
client_id = 'your_client_id'
client_secret = 'your_client_secret'

# Perform OAuth login
result = mt.Oauth_login(client_id=client_id, client_secret=client_secret)

if result:
    print("Login successful!")
    # Now you can use all API methods
    positions = mt.get_positions()
    holdings = mt.get_holdings()
```

Request Details :

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| `client_id` | `string` | Yes | Your OAuth client ID from go.mynt.in |
| `client_secret` | `string` | Yes | Your OAuth client secret from go.mynt.in |

Response Details :

Response data will be in json format with below fields.

| Json Fields | Possible value | Description |
| --- | --- | --- |
| stat | Ok or Not_Ok | Login Success Or failure status |
| susertoken | | It will be present only on login success. This data to be sent in subsequent requests in jKey field and web socket connection while connecting. |
| uid | | User ID |
| lastaccesstime | | It will be present only on login success. |
| emsg | | This will be present only if Login fails. |

Sample Success Response :
{
    "request_time": "20:18:47 19-05-2020",
    "stat": "Ok",
    "susertoken": "3b97f4c67762259a9ded6dbd7bfafe2787e662b3870422ddd343a59895f423a0",
    "lastaccesstime": "1589899727",
    "uid": "ZP00XXX"
}

Console Output :

When you call `Oauth_login()`, you'll see:

```
======================================================================
OAuth LOGIN - STEP BY STEP INSTRUCTIONS
======================================================================

📋 INFORMATION:
   • Your Public IP: 203.0.113.42
   • Callback URL: http://localhost:8189/callback
   (Note: Make sure this callback URL is registered in your OAuth app settings)

----------------------------------------------------------------------
🔐 STEP 1: AUTHORIZE THE APPLICATION
----------------------------------------------------------------------

👉 Copy and open this URL in your web browser:

   https://go.mynt.in/OAuthlogin/authorize/oauth?client_id=ZP00XXX_U

   After opening, you will be asked to login and authorize the application.

----------------------------------------------------------------------
⏳ STEP 2: WAITING FOR AUTHORIZATION
----------------------------------------------------------------------

   The system is now waiting for you to complete the authorization...
   Once you authorize in the browser, you will be redirected back automatically.
   You can press Ctrl+C at any time to cancel.

✅ Callback server is ready and waiting...

✅ AUTHORIZATION CODE RECEIVED
======================================================================

🔄 Processing authorization and generating access token...

======================================================================
🎉 LOGIN SUCCESSFUL!
======================================================================

✅ Your session has been established successfully!
   • User ID: ZP00XXX
   • Session Token: 3b97f4c67762259a9ded6dbd7bfafe2787e662b3870422ddd343a59895f423a0...
   • API Endpoint: https://go.mynt.in/NorenWClientAPI/

   You can now use the API to place orders, check positions, etc.
```

Important Notes:

1. **Callback URL Registration**: The callback URL `http://localhost:8189/callback` must be registered in your OAuth application settings on go.mynt.in
2. **Timeout**: The function waits up to 5 minutes for the OAuth callback
3. **Ctrl+C Support**: You can cancel the process at any time using Ctrl+C
4. **Automatic Endpoint Update**: After successful login, the API endpoint automatically changes to `https://go.mynt.in/NorenWClientAPI/`

#### <a name="md-oauth_login_using_code"></a> Oauth_login_using_code(client_id, client_secret, code)
Login using an existing authorization code without setting up a callback server.

This method allows you to login if you already have an authorization code from a previous OAuth flow or from handling the callback yourself.

Example: 
```
from myntapi import app_oauth

mt = app_oauth()

# If you already have an authorization code
code = "f199319d-a5df-444d-b962-27d2886cf252"
result = mt.Oauth_login_using_code(
    client_id='ZP00XXX_U',
    client_secret='your_client_secret',
    code=code
)

if result:
    print("Login successful!")
```

Request Details :

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| `client_id` | `string` | Yes | Your OAuth client ID |
| `client_secret` | `string` | Yes | Your OAuth client secret |
| `code` | `string` | Yes | The authorization code from OAuth callback |

Response Details :

Response data will be in json format with below fields.

| Json Fields | Possible value | Description |
| --- | --- | --- |
| stat | Ok or Not_Ok | Login Success Or failure status |
| susertoken | | It will be present only on login success. This data to be sent in subsequent requests in jKey field and web socket connection while connecting. |
| uid | | User ID |
| lastaccesstime | | It will be present only on login success. |
| emsg | | This will be present only if Login fails. |

Sample Success Response :
{
    "request_time": "20:18:47 19-05-2020",
    "stat": "Ok",
    "susertoken": "3b97f4c67762259a9ded6dbd7bfafe2787e662b3870422ddd343a59895f423a0",
    "lastaccesstime": "1589899727",
    "uid": "ZP00XXX"
}

Use Cases:

- You're handling the OAuth callback in your own web application
- You've stored an authorization code from a previous session
- You want to login programmatically without browser interaction

#### <a name="md-set_session"></a> set_session(userid, password, usertoken)
Manually set the session credentials and user token.

This method allows you to bypass the login flow if you already have a valid session token (usertoken).

Example:
```python
from myntapi import app_oauth

mt = app_oauth()

# Manually set the session
userid = 'your_userid'
password = 'your_password'
usertoken = 'your_valid_usertoken'

mt.set_session(userid=userid, password=password, usertoken=usertoken)

# Now you can use the API
positions = mt.get_positions()
```

Request Details :

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| `userid` | `string` | Yes | Your user ID |
| `password` | `string` | Yes | Your password |
| `usertoken` | `string` | Yes | A valid session token |

Response Details :

Returns `True` on success.

#### <a name="md-place_order"></a> place_order(buy_or_sell, product_type,exchange, tradingsymbol, quantity, discloseqty, price_type, price=0.0, trigger_price=None, retention='DAY', amo='NO', remarks=None)
place an order to oms

Example: 

```
ret = mt.place_order(buy_or_sell='S', product_type='C',
                        exchange='NSE', tradingsymbol='TCS-EQ', 
                        quantity=1, discloseqty=0,price_type='SL-LMT', price=2000.00, trigger_price=1990.50,
                        retention='DAY', remarks='Algo traders')
```
Request Details :

|Json Fields|Possible value|Description|
| --- | --- | ---|
|uid*||Logged in User Id|
|actid*||Login users account ID|
|exch*|NSE  / NFO / BSE / MCX|Exchange (Select from ‘exarr’ Array provided in User Details response)|
|tsym*||Unique id of contract on which order to be placed. (use url encoding to avoid special char error for symbols like M&M)|
|qty*||Order Quantity |
|prc*||Order Price|
|trgprc||Only to be sent in case of SL / SL-M order.|
|dscqty||Disclosed quantity (Max 10% for NSE, and 50% for MCX)|
|prd*|C / M / H|Product name (Select from ‘prarr’ Array provided in User Details response, and if same is allowed for selected, exchange. Show product display name, for user to select, and send corresponding prd in mt call)|
|trantype*|B / S|B -> BUY, S -> SELL|
|prctyp*|LMT / MKT / SL-LMT / SL-MKT / DS / 2L / 3L|Price type|
|ret*|DAY / EOS / IOC |Retention type (Show options as per allowed exchanges) |
|remarks||Any tag by user to mark order.|
|ordersource|MOB / WEB / TT |Used to generate exchange info fields.|
|bpprc||Book Profit Price applicable only if product is selected as B (Bracket order ) |
|blprc||Book loss Price applicable only if product is selected as H and B (High Leverage and Bracket order ) |
|trailprc||Trailing Price applicable only if product is selected as H and B (High Leverage and Bracket order ) |
|amo||Yes , If not sent, of Not “Yes”, will be treated as Regular order. |
|tsym2||Trading symbol of second leg, mandatory for price type 2L and 3L (use url encoding to avoid special char error for symbols like M&M)|
|trantype2||Transaction type of second leg, mandatory for price type 2L and 3L|
|qty2||Quantity for second leg, mandatory for price type 2L and 3L|
|prc2||Price for second leg, mandatory for price type 2L and 3L|
|tsym3||Trading symbol of third leg, mandatory for price type 3L (use url encoding to avoid special char error for symbols like M&M)|
|trantype3||Transaction type of third leg, mandatory for price type 3L|
|qty3||Quantity for third leg, mandatory for price type 3L|
|prc3||Price for third leg, mandatory for price type 3L|


Response Details :

Response data will be in json format with below fields.

|Json Fields|Possible value|Description|
| --- | --- | ---|
|stat|Ok or Not_Ok|Place order success or failure indication.|
|request_time||Response received time.|
|norenordno||It will be present only on successful Order placement to OMS.|
|emsg||This will be present only if Order placement fails|

Sample Success Response:
{
    "request_time": "10:48:03 20-05-2020",
    "stat": "Ok",
    "norenordno": "20052000000017"
}

Sample Error Response :
{
    "stat": "Not_Ok",
    "request_time": "20:40:01 19-05-2020",
    "emsg": "Error Occurred : 2 \"invalid input\""
}

#### <a name="md-modify_order"></a> modify_order(orderno, exchange, tradingsymbol, newquantity,newprice_type, newprice, newtrigger_price, amo):
modify the quantity pricetype or price of an order

Example: 

```
orderno = ret['norenordno'] #from placeorder return value
ret = mt.modify_order(exchange='NSE', tradingsymbol='CANBK-EQ', orderno=orderno,
                                   newquantity=2, newprice_type='MKT', newprice=0.00)
## sl modification
ret = mt.modify_order(exchange='NSE', tradingsymbol='CANBK-EQ', orderno=orderno,
                                   newquantity=2, newprice_type='SL-LMT', newprice=201.00, newtrigger_price=200.00)
```

Request Details :

|Json Fields|Possible value|Description|
| --- | --- | ---|
|exch*||Exchange|
|norenordno*||Noren order number, which needs to be modified|
|prctyp|LMT / MKT / SL-MKT / SL-LMT|This can be modified.|
|prc||Modified / New price|
|qty||Modified / New Quantity|Quantity to Fill / Order Qty - This is the total qty to be filled for the order. Its Open Qty/Pending Qty plus Filled Shares (cumulative for the order) for the order. * Please do not send only the pending qty in this field|
|tsym*||Unique id of contract on which order was placed. Can't be modified, must be the same as that of original order. (use url encoding to avoid special char error for symbols like M&M)|
|ret|DAY / IOC / EOS|New Retention type of the order |
||||
|trgprc||New trigger price in case of SL-MKT or SL-LMT|
|uid*||User id of the logged in user.|
|bpprc||Book Profit Price applicable only if product is selected as B (Bracket order ) |
|blprc||Book loss Price applicable only if product is selected as H and B (High Leverage and Bracket order ) |
|trailprc||Trailing Price applicable only if product is selected as H and B (High Leverage and Bracket order ) |

Response Details :

Response data will be in json format with below fields.

|Json Fields|Possible value|Description|
| --- | --- | ---|
|stat|Ok or Not_Ok|Modify order success or failure indication.|
|result||Noren Order number of the order modified.|
|request_time||Response received time.|
|emsg||This will be present only if Order modification fails|

Sample Success Response :
{
     "request_time":"14:14:08 26-05-2020",
     "stat":"Ok",
     "result":"20052600000103"
}

Sample Failure Response :
{
   "request_time":"16:03:29 28-05-2020",
   "stat":"Not_Ok",
   "emsg":"Rejected : ORA:Order not found"
}

#### <a name="md-cancel_order"></a> cancel_order(orderno)
cancel an order

Example:

```
orderno = ret['norenordno'] #from placeorder return value
ret = mt.cancel_order(orderno=orderno)
```

Request Details :

|Json Fields|Possible value|Description|
| --- | --- | ---|
|norenordno*||Noren order number, which needs to be modified|
|uid*||User id of the logged in user.|

Response Details :

Response data will be in json format with below fields.

|Json Fields|Possible value|Description|
| --- | --- | ---|
|stat|Ok or Not_Ok|Cancel order success or failure indication.|
|result||Noren Order number of the canceled order.|
|request_time||Response received time.|
|emsg||This will be present only if Order cancelation fails|

Sample Success Response :
{
   "request_time":"14:14:10 26-05-2020",
   "stat":"Ok",
   "result":"20052600000103"
}

Sample Failure Response :
{
   "request_time":"16:01:48 28-05-2020",
   "stat":"Not_Ok",
   "emsg":"Rejected : ORA:Order not found to Cancel"
}


#### <a name="md-exit_order"></a> exit_order(orderno)
exits a cover or bracket order

Request Details :

|Json Fields|Possible value|Description|
| --- | --- | ---|
|norenordno*||Noren order number, which needs to be modified|
|prd*|H / B |Allowed for only H and B products (Cover order and bracket order)|
|uid*||User id of the logged in user.|

Response Details :

Response data will be in json format with below fields.

|Json Fields|Possible value|Description|
| --- | --- | ---|
|stat|Ok or Not_Ok|Cancel order success or failure indication.|
|dmsg||Display message, (will be present only in case of success).|
|request_time||Response received time.|
|emsg||This will be present only if Order cancelation fails|


#### <a name="md-prd_convert"></a> position_product_conversion(exchange, tradingsymbol, quantity, new_product_type, previous_product_type, buy_or_sell, day_or_cf)

Convert a product of a position 

Example:

```
ret = mt.get_positions()
#converts the first position from existing product to intraday
p = ret[0]
ret = mt.position_product_conversion(p['exch'], p['tsym'], p['netqty'], 'I', p['prd'], 'S', 'DAY')
```

Request Details :

|Json Fields|Possible value|Description|
| --- | --- | ---|
|exch*||Exchange|
|tsym*||Unique id of contract on which order was placed. Can’t be modified, must be the same as that of original order. (use url encoding to avoid special char error for symbols like M&M)|
|qty*||Quantity to be converted.|
|uid*||User id of the logged in user.|
|actid*||Account id|
|prd*||Product to which the user wants to convert position. |
|prevprd*||Original product of the position.|
|trantype*||Transaction type|
|postype*|Day / CF|Converting Day or Carry forward position|
|ordersource|MOB |For Logging|

Response Details :

Response data will be in json format with below fields.

|Json Fields|Possible value|Description|
| --- | --- | ---|
|stat|Ok or Not_Ok|Position conversion success or failure indication.|
|emsg||This will be present only if Position conversion fails.|

Sample Success Response :
{
   "request_time":"10:52:12 02-06-2020",
   "stat":"Ok"
}

Sample Failure Response :
{
   "stat":"Not_Ok",
   "emsg":"Invalid Input :  Invalid Position Type"
}

#### <a name="md-get_orderbook"></a>  Order Book
List of Orders placed for the account

Example :
```
ret = mt.get_order_book()
print(ret)
```
Request Details :

|Json Fields|Possible value|Description|
| --- | --- | ---|
|uid*||Logged in User Id|
|prd|H / M / ...|Product name|

Response Details :

Response data will be in json Array of objects with below fields in case of success.

|Json Fields|Possible value|Description|
| --- | --- | ---|
|stat|Ok or Not_Ok|Order book success or failure indication.|
|exch||Exchange Segment|
|tsym||Trading symbol / contract on which order is placed.|
|norenordno||Noren Order Number|
|prc||Order Price|
|qty||Order Quantity|
|prd||Display product alias name, using prarr returned in user details.|
|status|||
|trantype|B / S|Transaction type of the order|
|prctyp|LMT / MKT|Price type|
|fillshares||Total Traded Quantity of this order|
|avgprc||Average trade price of total traded quantity |
|rejreason||If order is rejected, reason in text form|
|exchordid||Exchange Order Number|
|cancelqty||Canceled quantity for order which is in status cancelled.|
|remarks||Any message Entered during order entry.|
|dscqty||Order disclosed quantity.|
|trgprc||Order trigger price|
|ret|DAY / IOC / EOS|Order validity|
|uid|||
|actid|||
|bpprc||Book Profit Price applicable only if product is selected as B (Bracket order ) |
|blprc||Book loss Price applicable only if product is selected as H and B (High Leverage and Bracket order ) |
|trailprc||Trailing Price applicable only if product is selected as H and B (High Leverage and Bracket order ) |
|amo||Yes / No|
|pp||Price precision|
|ti||Tick size|
|ls||Lot size|
|token||Contract Token|
|norentm|||
|ordenttm|||
|exch_tm|||
|snoordt||0 for profit leg and 1 for stoploss leg|
|snonum||This field will be present for product H and B; and only if it is profit/sl order.|

Response data will be in json format with below fields in case of failure:

|Json Fields|Possible value|Description|
| --- | --- | ---|
|stat|Not_Ok|Order book failure indication.|
|request_time||Response received time.|
|emsg||Error message|

Sample Success Output :
Success response :
[
      {
        "stat": "Ok",
        "exch": "NSE",
        "tsym": "ACC-EQ",
        "norenordno": "20062500000001223",
        "prc": "127230",
        "qty": "100",
        "prd": "C",
        "status": "Open",
        "trantype": "B",
        "prctyp": "LMT",
        "fillshares": "0",
        "avgprc": "0",
        "exchordid": "250620000000343421",
        "uid": "VIDYA",
        "actid": "CLIENT1",
        "ret": "DAY",
        "amo": "Yes"
      },
      {
        "stat": "Ok",
        "exch": "NSE",
        "tsym": "ABB-EQ",
        "norenordno": "20062500000002543",
        "prc": "127830",
        "qty": "50",
        "prd": "C",
        "status": "REJECT",
        "trantype": "B",
        "prctyp": "LMT",
        "fillshares": "0",
        "avgprc": "0",
        "rejreason": "Insufficient funds",
        "uid": "VIDYA",
        "actid": "CLIENT1",
        "ret": "DAY",
        "amo": "No"
      }
]

Sample Failure Response :
{
   "stat":"Not_Ok",
   "emsg":"Session Expired : Invalid Session Key"
}

#### <a name="md-get_tradebook"></a>  Trade Book 
List of Trades of the account

Example:
```
ret = mt.get_trade_book()
print(ret)
```

Request Details :

|Json Fields|Possible value|Description|
| --- | --- | ---|
|uid*||Logged in User Id|
|actid*||Account Id of logged in user|

Response Details :

Response data will be in json Array of objects with below fields in case of success.

|Json Fields|Possible value|Description|
| --- | --- | ---|
|stat|Ok or Not_Ok|Order book success or failure indication.|
|exch||Exchange Segment|
|tsym||Trading symbol / contract on which order is placed.|
|norenordno||Noren Order Number|
|qty||Order Quantity|
|prd||Display product alias name, using prarr returned in user details.|
|trantype|B / S|Transaction type of the order|
|prctyp|LMT / MKT|Price type|
|fillshares||Total Traded Quantity of this order|
|avgprc||Average trade price of total traded quantity |
|exchordid||Exchange Order Number|
|remarks||Any message Entered during order entry.|
|ret|DAY / IOC / EOS|Order validity|
|uid|||
|actid|||
|pp||Price precision|
|ti||Tick size|
|ls||Lot size|
|cstFrm||Custom Firm|
|fltm||Fill Time|
|flid||Fill ID|
|flqty||Fill Qty|
|flprc||Fill Price|
|ordersource||Order Source|
|token||Token|

Response data will be in json format with below fields in case of failure:

|Json Fields|Possible value|Description|
| --- | --- | ---|
|stat|Not_Ok|Order book failure indication.|
|request_time||Response received time.|
|emsg||Error message|

Sample Success Output :

[
   {
       "stat": "Ok",
       "norenordno": "20121300065715",
       "uid": "ZPXXXX",
       "actid": "ZPXXXX",
       "exch": "NSE",
       "prctyp": "LMT",
       "ret": "DAY",
       "prd": "M",
       "flid": "102",
       "fltm": "01-01-1980 00:00:00",
       "trantype": "S",
       "tsym": "ACCELYA-EQ",
       "qty": "180",
       "token": "7053",
       "fillshares": "180",
       "flqty": "180",
       "pp": "2",
       "ls": "1",
       "ti": "0.05",
       "prc": "800.00",
       "flprc": "800.00",
       "norentm": "19:59:32 13-12-2020",
       "exch_tm": "00:00:00 01-01-1980",
       "remarks": "Algo traders",
       "exchordid": "6857"
   },
   {
       "stat": "Ok",
       "norenordno": "20121300065716",
       "uid": "ZPXXXX",
       "actid": "ZPXXXX",
       "exch": "NSE",
       "prctyp": "LMT",
       "ret": "DAY",
       "prd": "M",
       "flid": "101",
       "fltm": "01-01-1980 00:00:00",
       "trantype": "B",
       "tsym": "ACCELYA-EQ",
       "qty": "180",
       "token": "7053",
       "fillshares": "180",
       "flqty": "180",
       "pp": "2",
       "ls": "1",
       "ti": "0.05",
       "prc": "800.00",
       "flprc": "800.00",
       "norentm": "19:59:32 13-12-2020",
       "exch_tm": "00:00:00 01-01-1980",
       "remarks": "Algo traders",
       "exchordid": "6858"
   }
]

#### <a name="md-get_singleorderhistory"></a>  single order history(orderno)
history an order

```
orderno = ret['norenordno'] #from placeorder return value
ret = mt.single_order_history(orderno=orderno)
```
Request Details :

|Json Fields|Possible value|Description|
| --- | --- | ---|
|uid*||Logged in User Id|
|norenordno*||Noren Order Number|


Response Details :

Response data will be in json Array of objects with below fields in case of success.

|Json Fields|Possible value|Description|
| --- | --- | ---|
|stat|Ok or Not_Ok|Order book success or failure indication.|
|exch||Exchange Segment|
|tsym||Trading symbol / contract on which order is placed.|
|norenordno||Noren Order Number|
|prc||Order Price|
|qty||Order Quantity|
|prd||Display product alias name, using prarr returned in user details.|
|status|||
|rpt|| (fill/complete etc)|
|trantype|B / S|Transaction type of the order|
|prctyp|LMT / MKT|Price type|
|fillshares||Total Traded Quantity of this order|
|avgprc||Average trade price of total traded quantity |
|rejreason||If order is rejected, reason in text form|
|exchordid||Exchange Order Number|
|cancelqty||Canceled quantity for order which is in status cancelled.|
|remarks||Any message Entered during order entry.|
|dscqty||Order disclosed quantity.|
|trgprc||Order trigger price|
|ret|DAY / IOC / EOS|Order validity|
|uid|||
|actid|||
|bpprc||Book Profit Price applicable only if product is selected as B (Bracket order ) |
|blprc||Book loss Price applicable only if product is selected as H and B (High Leverage and Bracket order ) |
|trailprc||Trailing Price applicable only if product is selected as H and B (High Leverage and Bracket order ) |
|amo||Yes / No|
|pp||Price precision|
|ti||Tick size|
|ls||Lot size|
|token||Contract Token|
|norentm|||
|ordenttm|||
|exch_tm|||

Response data will be in json format with below fields in case of failure:

|Json Fields|Possible value|Description|
| --- | --- | ---|
|stat|Not_Ok|Order book failure indication.|
|request_time||Response received time.|
|emsg||Error message|

Sample Success Output :

[
   {
       "stat": "Ok",
       "norenordno": "20121300065716",
       "uid": "DEMO1",
       "actid": "DEMO1",
       "exch": "NSE",
       "tsym": "ACCELYA-EQ",
       "qty": "180",
       "trantype": "B",
       "prctyp": "LMT",
       "ret": "DAY",
       "token": "7053",
       "pp": "2",
       "ls": "1",
       "ti": "0.05",
       "prc": "800.00",
       "avgprc": "800.00",
       "dscqty": "0",
       "prd": "M",
       "status": "COMPLETE",
       "rpt": "Fill",
       "fillshares": "180",
       "norentm": "19:59:32 13-12-2020",
       "exch_tm": "00:00:00 01-01-1980",
       "remarks": "Algo traders",
       "exchordid": "6858"
   },
   {
       "stat": "Ok",
       "norenordno": "20121300065716",
       "uid": "DEMO1",
       "actid": "DEMO1",
       "exch": "NSE",
       "tsym": "ACCELYA-EQ",
       "qty": "180",
       "trantype": "B",
       "prctyp": "LMT",
       "ret": "DAY",
       "token": "7053",
       "pp": "2",
       "ls": "1",
       "ti": "0.05",
       "prc": "800.00",
       "dscqty": "0",
       "prd": "M",
       "status": "OPEN",
       "rpt": "New",
       "norentm": "19:59:32 13-12-2020",
       "exch_tm": "00:00:00 01-01-1980",
       "remarks": "Algo traders",
       "exchordid": "6858"
   },
   {
       "stat": "Ok",
       "norenordno": "20121300065716",
       "uid": "DEMO1",
       "actid": "DEMO1",
       "exch": "NSE",
       "tsym": "ACCELYA-EQ",
       "qty": "180",
       "trantype": "B",
       "prctyp": "LMT",
       "ret": "DAY",
       "token": "7053",
       "pp": "2",
       "ls": "1",
       "ti": "0.05",
       "prc": "800.00",
       "dscqty": "0",
       "prd": "M",
       "status": "PENDING",
       "rpt": "PendingNew",
       "norentm": "19:59:32 13-12-2020",
       "remarks": "Algo traders"
   },
   {
       "stat": "Ok",
       "norenordno": "20121300065716",
       "uid": "DEMO1",
       "actid": "DEMO1",
       "exch": "NSE",
       "tsym": "ACCELYA-EQ",
       "qty": "180",
       "trantype": "B",
       "prctyp": "LMT",
       "ret": "DAY",
       "token": "7053",
       "pp": "2",
       "ls": "1",
       "ti": "0.05",
       "prc": "800.00",
       "prd": "M",
       "status": "PENDING",
       "rpt": "NewAck",
       "norentm": "19:59:32 13-12-2020",
       "remarks": "Algo traders"
   }
]


#### <a name="md-place_basket"></a>  place_basket(order)

Order multiple scripts

```
order=[{'buy_or_sell': 'B', 'product_type': 'I', 'exchange': 'NSE', 'tradingsymbol': 'TCS-EQ', 'quantity': '1', 'discloseqty': '0', 'price_type': 'MKT', 'price': '0'},{'buy_or_sell': 'S', 'product_type': 'I', 'exchange': 'NSE', 'tradingsymbol': 'IDEA-EQ', 'quantity': '6', 'discloseqty': '0', 'price_type': 'MKT', 'price': '0'},{'buy_or_sell': 'B', 'product_type': 'I', 'exchange': 'NSE', 'tradingsymbol': 'SBIN-EQ', 'quantity': '5', 'discloseqty': '0', 'price_type': 'MKT', 'price': '0'}]


ret = mt.place_basket(order)


Response Details :
Response data will be in array format with below fields in case of Success:
[{'buy_or_sell': 'S', 'product_type': 'I', 'exchange': 'NSE', 'tradingsymbol': 'TCS-EQ', 'quantity': '1', 'discloseqty': '0', 'price_type': 'MKT', 'price': '0', 'request_time': '18:51:40 10-01-2024', 'stat': 'Ok', 'norenordno': '24011000052942'},{'buy_or_sell': 'S', 'product_type': 'I', 'exchange': 'NSE', 'tradingsymbol': 'IDEA-EQ', 'quantity': '1', 'discloseqty': '0', 'price_type': 'MKT', 'price': '0', 'request_time': '18:51:40 10-01-2024', 'stat': 'Ok', 'norenordno': '24011000052943'},{'buy_or_sell': 'S', 'product_type': 'I', 'exchange': 'NSE', 'tradingsymbol': 'SBIN-EQ', 'quantity': '1', 'discloseqty': '0', 'price_type': 'MKT', 'price': '0', 'request_time': '18:51:40 10-01-2024', 'stat': 'Ok', 'norenordno': '24011000052944'}]
```
#### <a name="md-close_all_position"></a>  close_all_position()

Close all positions

```
For close all position
ret = mt.close_all_position()

For close partially position
ore=[{
    "tradingsymbol":"TCS-EQ",
    "order_type":"MIS",
    "quantity" : "1"
    },
    {
    "tradingsymbol":"IDEA-EQ",
    "order_type":"MIS",
    "quantity" : "2"
    }]
ret = mt.close_all_position(ore)

Response data will be in array format with below fields in case of Success:
[{'buy_or_sell': 'S', 'product_type': 'I', 'exchange': 'NSE', 'tradingsymbol': 'TCS-EQ', 'quantity': '1', 'discloseqty': '0', 'price_type': 'MKT', 'price': '0', 'request_time': '18:51:40 10-01-2024', 'stat': 'Ok', 'norenordno': '24011000052942'},{'error': 'quantity is greater than position', 'tradingsymbol': 'IDEA-EQ', 'order_type': 'MIS'}]

```


#### <a name="md-get_holdings"></a> get_holdings(product_type)
retrieves the holdings as a list

Example:
```
ret = mt.get_holdings()
```
Request Details :

|Json Fields|Possible value|Description|
| --- | --- | ---|
|uid*||Logged in User Id|
|actid*||Account id of the logged in user.|
|prd*||Product name|

Response Details :
Response data will be in json format with below fields in case of Success:

|Json Fields|Possible value|Description|
| --- | --- | ---|
|stat|Ok or Not_Ok|Holding request success or failure indication.|
|exch_tsym||Array of objects exch_tsym objects as defined below.|
|holdqty||Holding quantity|
|dpqty||DP Holding quantity|
|npoadqty||Non Poa display quantity|
|colqty||Collateral quantity|
|benqty||Beneficiary quantity|
|unplgdqty||Unpledged quantity|
|brkcolqty||Broker Collateral|
|btstqty||BTST quantity|
|btstcolqty||BTST Collateral quantity|
|usedqty||Holding used today|
|upldprc||Average price uploaded along with holdings|
Notes:
Valuation : btstqty + holdqty + brkcolqty + unplgdqty + benqty + Max(npoadqty, dpqty) - usedqty
Salable: btstqty + holdqty + unplgdqty + benqty + dpqty - usedqty


Exch_tsym object:
|Json Fields of object in values Array|Possible value|Description|
| --- | --- | ---|
|exch|NSE, BSE, NFO ...|Exchange |
|tsym||Trading symbol of the scrip (contract)|
|token||Token of the scrip (contract)|
|pp||Price precision|
|ti||Tick size|
|ls||Lot size|

Response data will be in json format with below fields in case of failure:

|Json Fields|Possible value|Description|
| --- | --- | ---|
|stat|Not_Ok|Position book request failure indication.|
|request_time||Response received time.|
|emsg||Error message|

Sample Success Response :
[   
      {
            "stat":"Ok", 
            "exch_tsym":[
                                      {
                                            "exch":"NSE",
                                            "token":"13",
                     "tsym":"ABB-EQ"
   }
         ],
            "holdqty":"2000000",
            "colqty":"200",
            "btstqty":"0",
            "btstcolqty":"0",
            "usedqty":"0",
            "upldprc" : "1800.00"
      },
      {
"stat":"Ok",
"exch_tsym":[
   {
          "exch":"NSE",
          "token":"22",
          "tsym":"ACC-EQ"
   }
         ],
"holdqty":"2000000",
"colqty":"200",
"btstqty":"0",
"btstcolqty":"0",
"usedqty":"0",
               "upldprc" : "1400.00"
        }
]

Sample Failure Response :
{
   "stat":"Not_Ok",
   "emsg":"Invalid Input : Missing uid or actid or prd."
}

#### <a name="md-get_positions"></a> get_positions()

retrieves the overnight and day positions as a list

Example: 
```
ret = mt.get_positions()
mtm = 0
pnl = 0
for i in ret:
    mtm += float(i['urmtom'])
    pnl += float(i['rpnl'])
    day_m2m = mtm + pnl
print(f'{day_m2m} is your Daily MTM')
```

Request Details :

|Json Fields|Possible value|Description|
| --- | --- | ---|
|uid*||Logged in User Id|
|actid*||Account id of the logged in user.|

Response Details :

Response data will be in json format with Array of Objects with below fields in case of success.

|Json Fields|Possible value|Description|
| --- | --- | ---|
|stat|Ok or Not_Ok|Position book success or failure indication.|
|exch||Exchange segment|
|tsym||Trading symbol / contract.|
|token||Contract token|
|uid||User Id|
|actid||Account Id|
|prd||Product name to be shown.|
|netqty||Net Position quantity|
|netavgprc||Net position average price|
|daybuyqty||Day Buy Quantity|
|daysellqty||Day Sell Quantity|
|daybuyavgprc||Day Buy average price|
|daysellavgprc||Day sell average price|
|daybuyamt||Day Buy Amount|
|daysellamt||Day Sell Amount|
|cfbuyqty||Carry Forward Buy Quantity|
|cforgavgprc||Original Avg Price|
|cfsellqty||Carry Forward Sell Quantity|
|cfbuyavgprc||Carry Forward Buy average price|
|cfsellavgprc||Carry Forward Sell average price|
|cfbuyamt||Carry Forward Buy Amount|
|cfsellamt||Carry Forward Sell Amount|
|lp||LTP|
|rpnl||RealizedPNL|
|urmtom||UnrealizedMTOM. (Can be recalculated in LTP update: = netqty * (lp from web socket - netavgprc) * prcftr)||
|bep||Break even price|
|openbuyqty|||
|opensellqty|||
|openbuyamt|||
|opensellamt|||
|openbuyavgprc|||
|opensellavgprc|||
|mult|||
|pp|||
|prcftr||gn*pn/(gd*pd). |
|ti||Tick size|
|ls||Lot size|
|request_time||This will be present only in a failure response.|

Response data will be in json format with below fields in case of failure:

|Json Fields|Possible value|Description|
| --- | --- | ---|
|stat|Not_Ok|Position book request failure indication.|
|request_time||Response received time.|
|emsg||Error message|


Sample Success Response :
[
     {
"stat":"Ok",
"uid":"POORNA",
"actid":"POORNA",
"exch":"NSE",
"tsym":"ACC-EQ",
"prarr":"C",
"pp":"2",
"ls":"1",
"ti":"5.00",
"mult":"1",
"prcftr":"1.000000",
"daybuyqty":"2",
"daysellqty":"2",
"daybuyamt":"2610.00",
"daybuyavgprc":"1305.00",
"daysellamt":"2610.00",
"daysellavgprc":"1305.00",
"cfbuyqty":"0",
"cfsellqty":"0",
"cfbuyamt":"0.00",
"cfbuyavgprc":"0.00",
"cfsellamt":"0.00",
"cfsellavgprc":"0.00",
"openbuyqty":"0",
"opensellqty":"23",
"openbuyamt":"0.00",
"openbuyavgprc":"0.00",
"opensellamt":"30015.00",
"opensellavgprc":"1305.00",
"netqty":"0",
"netavgprc":"0.00",
"lp":"0.00"