API Documentation

Overview

Now build your custom trading system with our Developer APIs
Use our SDKs for swift integration in the language of your choice.
Get Live market feeds , execute orders in real time, monitor your positions, manage your portfolio and do much more.
Provides more features around trading as well as optimizing these APIs to provide you with a smooth flow of transactions. These APIs are extremely simple to integrate and you can access them FREE of cost. We have ensured maximum security for our APIs

OAUTH Login

Holdings

This function is used to provide athe client’s holdings as of beginning of the day.

REQUEST BODY

Field Name Description Data Type (max length) Sample Value
ClientCode Pass the registered client code of the user. String(10) 12345678

RESPONSE BODY

Field Name Type Description
Exch char Gets the Exchange of the scrip.(N-Nse,B-Bse)
ExchType Char Exchangesegmentofthescrip(C-Cash,D-Derivative,U-Currency)
NseCode Integer NSEScripCode
BseCode Integer BSEScripCode
Symbol String Symbolofthescrip
FullName String Full Name of that Scrip
Quantity Long AvailableBODquantity
CurrentPrice Double Currentpriceoftheshare(symbol)
PoolQty Integer Qty of that scrip in Broker Beneficiary account
DPQty Integer Qty of that Scrip in Client’s DP account
POASigned Char Whether POA is Signed

REQUEST:

  
                      
                      

REQUEST:




curl --location --request POST 'https://Openapi.5paisa.com/VendorsAPI/Service1.svc/V3/Holding' \
--header 'Authorization: bearer {Your Access Token}' \
--header 'Content-Type: application/json' \
--header 'Cookie: NSC_JOh0em50e1pajl5b5jvyafempnkehc3=ffffffffaf103e0f45525d5f4f58455e445a4a423660' \
--data-raw '{
    "head": {
        "key": "{Your Vendor/User Key}"
    },
    "body": {
        "ClientCode": "{Your Client Code}"
    }
}'
/code>

REQUEST:

                      
                        

REQUEST:




client.holdings()

REQUEST:

                      
                        

REQUEST:




client.getHoldings().then((holdings) => {
    console.log(holdings)
}).catch((err) => {
    console.log(err)
});

Margin (Funds)

This API is used to fetch Client’s Margin related details

Request Body

Field Name Description Data Type (max length) Sample Value
ClientCode Pass the registered client code of the user. String(10) 12345678

RESPONSE BODY

Field Name Description Data Type (max length) Sample Value
Status Returns the status of the response. Integer A.-1
B.0
C.1
D.2
Message Returns the message of the reponse. String "Server Unable to process your request"
“Success”
“No records found”
“Invalid input parameters.”
ClientCode Returns client code String 12345678
EquityMargin Array List of Margin Details Array List of Margin Details -
TimeStamp It gives the server time when Margin summary is provided by server DateTime /Date(1538377480067+0530)/

MARGIN DETAILS

Field Name Description Data Type (max length)
ALB Ledger Balance at the beginning of the day Double
Adhoc Adhoc margin provided to customer for the day Double
AvailableMargin Actual Available margin available to the customer for trading Double
GHV Gross Holding Value Double
GHVPer Gross Holding Value Cover % Double
GrossMargin Gross Margin of the customer Double
Mgn4PendOrd Margin blocked for pending orders Double
Mgn4Position Margin blocked for open positions Double
OptionsMtoMLoss Margin blocked for M2M loss in Options position Double
Payments Any funds withdrawn from 5paisa today Double
Receipts Any funds added to the ledger today Double
THV Total Holding Value Double
PDHV Adjusted Holding Value post any applicable Haircut Double

REQUEST:

  
                      
                      

REQUEST:




curl --location --request POST 'https://Openapi.5paisa.com/VendorsAPI/Service1.svc/V3/Margin' \
--header 'Authorization: bearer {Your Access Token}' \
--header 'Content-Type: application/json' \
--header 'Cookie: NSC_JOh0em50e1pajl5b5jvyafempnkehc3=ffffffffaf103e0c45525d5f4f58455e445a4a423660' \
--data-raw '{
    "head": {
        "key": "{Your Vendor/User Key}"
    },
    "body": {
        "ClientCode": "{Your Client Code}"
    }
}'
/code>

REQUEST:

                      
                        

REQUEST:




client.margin()

REQUEST:

                      
                        

REQUEST:




client.getMargin().then((marginDetails) => {
       console.log(marginDetails)
     }).catch((err) => {
       console.log(err)
     });

Positions

This method will provide the client’s Positions.
Positions comprises of all active FNO trades either from on a previous and all current trading days trades.
Request Body
Field Name Description Data Type (max length) Sample Value
ClientCode Pass the registered client code of the user. String(10) 12345678
RESPONSE BODY
Field Name Description Data Type (max length) List Values Sample Value
Message If error code is not 0 then use the message field otherwise it will be empty. String A. "Invalid head parameters."
B. "Invalid Body Parameters."
C. “Success”
D. “Error while processing your request.”
Success
Status If Error code is not 0 then there is an issue while processing client request, In such a case use Message field only. Integer A. -1 = Exception
B. 0 = success
C. 1=No Record Found
D. 2- Invalid Input/ head parameters
0
NetPositionDetail This class contain the all Net Postion details of Client List - -
NET POSITION DETAIL
FieldName Type Description
Exch Char Exchange in which order has been Placed. N- NSE, B-BSE, M-MCX
ExchType Char Exchange segment C-Cash, D-Derivatives, U-Currency
ScripCode Int32 Scrip Code of the particular stock
ScripName String Scrip Name of the scrip.
BuyQty Int32 Number of Shares bought in particular scrip.
BuyAvgRate Double Average buying rate for a particular scrip
BuyValue Double Average buying rate Multiply by bought quantity
SellQty Int32 Number of shares sold in particular scrip.
SellAvgRate Double Average Selling Rate.
SellValue Double Average Selling rate Multiply by sold quantity.
NetQty Int32 Bought Quantity – sold Quantity.
BookedPL Double Profit or Loss booked by client for particular scrip.
LTP Double Last traded Price.
OrderFor Char I-Intraday , D- Delivery.
Multiplier Double Scrip multiplier
BodQty Int32 Bod quantity
MTOM Double MTOM profit and loss.
PreviousClose Double Previous close

REQUEST:

  
                      
                      

REQUEST:



curl --location --request POST 'https://Openapi.5paisa.com/VendorsAPI/Service1.svc/V4/NetPosition' \
--header 'Authorization: bearer abc' \
--header 'Content-Type: application/json' \
--data-raw '{
    "head": {
        "key": ""
    },
    "body": {
        "ClientCode": ""
    }
}'

REQUEST:

                      
                        

REQUEST:




client.positions()

REQUEST:

                      
                        

REQUEST:




client.getPositions().then((positions) => {
    console.log(positions)
}).catch((err) => {
    console.log(err)
});



Position Conversion

Request Body:-

Name Desc Compulsory* DataType
Exch Pass the Exchange. Y String
ExchType Pass the Exchange Type. Y String
ScripCode Pass the Scrip Code of current position Y Integer
ConvertFrom Convert From segment (Intraday/Delivery) Y String
ConvertQty Quantity to be converted Y Integer
ConvertTo Convert From segment (Intraday/Delivery) N String
TradeType Buy/Sell N String
ClientCode Pass the Client Code. N String
AppSource Pass the App Source. N Integer

 

 

Response Body:-

Name Desc
Status 0 for success

In case of non zero code, check following field for error in body
Message Error description incase of non zero status or "Success".
ClientCode Returns the ClientCode.
RMSResponseCode Returns the RMS Response Code.
Status 0 for success
In case of non zero code, refer following field for error description
Message Error description incase of non zero status or "Success".
ScripCode Returns the Scrip Code.

REQUEST:

  
                      
                      

curl --location --request POST 'https://Openapi.5paisa.com/VendorsAPI/Service1.svc/PositionConversion' \
--header 'Authorization: Bearer null' \
--header 'Content-Type: application/json' \
--data-raw '{
    "head": {
        "key": "{Your Vendor/User Key}"
    },
    "body": {
        "ClientCode": "null",
        "Exch":"N",
        "ExchType":"C",
        "ScripCode":"{{Scrip code of current open position}}",
        "TradeType":"{{B/S}}",
        "ConvertQty":"1",
        "ConvertFrom":"I",
        "ConvertTo":"D"
    }
}'

REQUEST:

                      
                        
client.position_convertion("N","C","BPCL_EQ","B",5,"D","I")

REQUEST:

                      
                        
client.position_convertion("N","C","BPCL_EQ","B",5,"D","I")

Customer Login

Response Attributes

Request Body

Header

Field Name Description Data Type (max length) Sample Value
appName App Name provided at the time of registration String APPTRIAL
appVer Developer App Version String 1.0
key UserKey generated at the time of registration String ue73jHVeEzBswG5ss9ugyrAasdasdyKYxg
osName Channel of order String WEB, Android, iOS
requestCode Request Code of the API called String 5PLoginV3
userId User ID generated at the time of registration String asdue73jHVeE
password Password generated at the time of registration String 9ugyrAasdasdy
*Note:- All fields are mandatory (cannot be empty)

Body

Field Name Description Data Type (max length) Sample Value
Email_id Client’s Email id String /EYUDYVGLvfkvufmwN9+Mg==
Password Password Respective ClientCode String +PMtfej7whK6g0HsvdF53Q==
LocalIP Local IP of the login requestor system String 192.168.88.41
PublicIP Public IP of the login requestor system String 192.168.88.41
HDSerialNumber Hard Disk Serial number of the Login requestor system. String  
MACAddress MACAddress of the Login requestor system. String  
MachineID Machine ID of the Login requestor system String BM4653-D-039377.local.indiainfoline.com
VersionNo The version no of the app String Will be 1.7
RequestNo 1 String First request for the day would be 1. Incremental request can be increased.
My2PIN Provide Date of Birth in YYYYMMDD format. E.g 19881226 String YAftqUV3rrXnbuCkD9Z+LA=
ConnectionType 1 String Will be 1
*Note:- All fields are mandatory (cannot be empty)

Response Body

Field Name Description Data Type Sample Value
Success 0= Password change success full. Other 0 will point rejection Int32 A. -1 = Exception
B. 0 = success
C. 1=No Record Found
D. 2- Invalid Input/ head parameters
ServerDt Server Date Date  
LastLogin Last Login Detail String  
TCPBcastLocalIP TCP Broad Cast Local IP Details String 192.168.122.110
TCPBcastPublicIP TCP Broad Cast Public IP Details String  
TCPBCastPort TCP BroadCast Port UInt16 25002
UDPBcastIP UDP Broadcast IP details. String 224.5.6.21
UDPBCastPort UDP Broadcast Port. UInt16 25002
InteractiveLocalIP Interactive LocalIP details. String  
InteractivePublicIP Interactive public P details. String  
InteractivePort InteractivePort details. UInt16 10116
ClientType Client Type Details UInt16 1
Message Message Type String "Invalid head parameters."
"Invalid Body Parameters."
“Success”
“Error while processing your request.”
LastPasswordModify Last Password Modified Details. DateTime /Date(1551422548000+0530)/
LastAccessedTime Last Accessed Details. DateTime /Date(1519693794000+0530)/
CleareDt - Date /Date(1554348600000+0530)/
VersionChanged Application Version Change Details Byte 0
1
IsPLMDefined PLM Defined details Byte 0
1
JWTToken JWT - JSON Web Token   eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1bmlxdWVfbmFtZSI6IjU2NTY1NDAxIiwicm9sZSI6IkNsaWVudCIsIm5iZiI6MTYyMDczNDQ4MiwiZXhwIjoxNjI4NTEwNDgyLCJpYXQiOjE2MjA3MzQ0ODJ9.imlJ6rvaWbY_o9UtcZiBulyeXMJofEiRqxLiYTgWoOc
IsPLM PLM Bind status. Byte 0
1
IsIDBound - Byte 0
1
IsIDBound2 - Byte 0
1
PLMsAllowed PLMs Allowed count Byte 0
1
BulkOrderAllowed Bulk Order facility allowed or not for the customer. Byte 0
1
RunningAuthorization - Byte 0
1
OTPCredentialID - String  
ClientName Client Name String AKASH
EmailId Email ID String DUMMY@GMAIL.COM
PasswordChangeFlag Password Change Flag Integer 0
1
PasswordChangeMessage Password Change Massage String  
ClientCode Client ClientCode String 123456789
AllowNseCash Whether Nse Cash segment is allowed String Y
N
AllowNseDeriv Whether Nse Derivative segment is allowed String Y
N
AllowBseCash Whether Bse Cash segment is allowed String Y
N
AllowMCXComm Whether MCX Comm segment is allowed String Y
N
AllowNSEL Whether NSEL segment is allowed String Y
N
AllowNSECurrency Whether NSE Currency segment is allowed String Y
N
AllowNseMF Whether Nse MF segment is allowed String Y
N
AllowBseMF Whether Bse MF segment is allowed String Y
N
AllowMcxSx Whether McxSx segment is allowed String Y
N
AllowNseComm Whether Nse Comm segment is allowed String Y
N
AllowBseDeriv Whether Bse Derivative segment is allowed String Y
N
IsOnlyMF It specifies wether user is only MF user String Y
N
DemoTrial Is specifies wether user is a trial user String Y
N
POAStatus It will give whether POA is available for that Client Char Y
N

REQUEST:

  
                      
                      

REQUEST:




curl --location --request POST 'https://Openapi.5paisa.com/VendorsAPI/Service1.svc/V4/LoginRequestMobileNewbyEmail' \
--header 'Content-Type: application/json' \
--header 'Cookie: 5paisacookie=qwmwpam1su3s4lvwlwyevrl5; NSC_JOh0em50e1pajl5b5jvyafempnkehc3=ffffffffaf103e0f45525d5f4f58455e445a4a423660' \
--data-raw '{
    "head": {
        "appName": "{Your Appname}",
        "key": "{Your Vendor/User Key}",
        "userId": "{Your User Id}",
        "password": "{Your Password}"
    },
    "body": {
        "Email_id": "{Your Encrypted Login Id}",
        "Password": "{Your Encrypted Login Password}",
        "LocalIP": "192.168.88.41",
        "PublicIP": "192.168.88.41",
        "HDSerailNumber": "",
        "MACAddress": "",
        "MachineID": "BM4653-D-039377.local.indiainfoline.com",
        "VersionNo": "1.7",
        "RequestNo": "1",
        "My2PIN": "{Your Encrypted Login DOB}",
        "ConnectionType": "1"
    }
}'
/code>

REQUEST:

                      
                        

REQUEST:




from py5paisa import FivePaisaClient
cred={
    "APP_NAME":"YOUR APP_NAME",
    "APP_SOURCE":"YOUR APP_SOURCE",
    "USER_ID":"YOUR USER_ID",
    "PASSWORD":"YOUR PASSWORD",
    "USER_KEY":"YOUR USERKEY",
    "ENCRYPTION_KEY":"YOUR ENCRYPTION_KEY"
}

client = FivePaisaClient(email="random_email@xyz.com", passwd="password", dob="YYYYMMDD",cred=cred)
client.login()

REQUEST:

                      
                        

REQUEST:




// Configuration for your app
const conf = {
    "appSource": "",
    "appName": "",
    "userId": "",
    "password": "",
    "userKey": "",
    "encryptionKey": ""
}

const { FivePaisaClient } = require("5paisajs")

var client = new FivePaisaClient(conf)

// This client object can be used to login multiple users.
client.login("random_email@xyz.com", "password", "YYYYMMDD").then((response) => {
    client.init(response).then(() => {
        // Fetch holdings, positions or place orders here.
        // Some things to try out are given below.
    })
}).catch((err) =>{
    // Oh no :/
    console.log(err)
})

Live Quotes

Websocket provides realtime Data of MarketFeeds, MarketDepth, OpenInterest, Indices.

We also provide real-time Order Status (Place, Modify, Cancel, Trigger) updates over websocket. For this you don't need to subscribe to anything.

Connecting to WebSocket :

Websocket URL:- wss://openfeed.5paisa.com/Feeds/api/chat?Value1=<Access_Token(JWT)>|<Client_Code>


Value1 contains JWT Token which we get at the time of Login API(in response body) same as access token.

After Connecting to Websocket It will start giving you order status updates and feeds as per request.

*Note :- At a time only one websocket connection will be connected if trying to connect concurrently older websocket connection will be disconnected.

Response Structure for Order Status updates

Field Name

Description

Data Type (max length)

Sample Value

ReqType

This field shown shows the updated order status.

String

  1. P - Place
  2. M - Modify
  3. C - Cancelled  

ClientCode

Returns Client Code

String

51201912

Exch

Returns Exchange

String

  1. N - NSE
  2. B - BSE

ExchType

Returns Instrument Type

String

  1. C-Cash
  2. D-Derivative

ScripCode

Request traded script code

String

1660

Symbol

Returns traded script symbol

String

ITC

Series

Returns Script Series

String

EQ

BrokerOrderID

Returns Broker Order Id

String

824863636

ExchOrderID

Returns Exchange order id

String

1100000019296811

ExchOrderTime

Returns Exch Order Time

String

2022-10-28 15:05:46

BuySell

Returns Buy or Sell

String

  1. B-Buy
  2. S-Sell

Qty

Returns order quantity

String

5

Price

Returns order price

String

345.2

ReqStatus

Returns Req Status

String

0

Status

Returns Order Status

String

  1. Placed
  2. Modified
  3. Cancelled

OrderRequestorCode

Returns Order Requestor code

String

50052770

AtMarket

Returns AtMarket

String

Y/N

Product

Returns Product Type

String

C/D

WithSL

Returns WithSL flag

String

Y/N

SLTriggerRate

Returns SL trigger rate

String

0

DisclosedQty

Returns  DisclosedQty

String

0

PendingQty

Returns  PendingQty

String

1

TradedQty

Returns  TradedQty

String

0

RemoteOrderId

Returns  RemoteOrderId

String

202205270455305

Subscribing/Unsubscribing to scrips to get live feeds

Refer to below table to map requests:-

Request Method Name
Get Live Quotes MarketFeedV3
Get Market Depth MarketDepthService
Get Open Interest GetScripInfoForFuture
Indices Indices

 

In Request please enter(payload):-

{"Method":"MarketFeedV3","Operation":"Subscribe", "ClientCode":"<<Pass ClientCode>>","MarketFeedData":[ {"Exch":"N","ExchType":"C","ScripCode":15083} ]}

Sample Request:- {"Method":"MarketFeedV3","Operation":"Subscribe", "ClientCode":"ABC123","MarketFeedData":[ {"Exch":"N","ExchType":"C","ScripCode":15083} ]}

Similarly if want to Subscribe multiple scrips we need to put in following Request:-

{"Method":"MarketFeedV3","Operation":"Subscribe", "ClientCode":"<<Pass ClientCode>>","MarketFeedData":[ {"Exch":"N","ExchType":"C","ScripCode":15083}, "Exch":"B","ExchType":"C","ScripCode":999901}, "Exch":"N","ExchType":"C","ScripCode":22} ]}

Sample Request (Multiple Request):- {"Method":"MarketFeedV3","Operation":"Subscribe", "ClientCode":"ABC123","MarketFeedData":[ {"Exch":"N","ExchType":"C","ScripCode":15083}, "Exch":"B","ExchType":"C","ScripCode":999901}, "Exch":"N","ExchType":"C","ScripCode":22} ]}

If user wants to receive feeds again, user has to sign in again and Subscribe to Scrips again that is we need to follow process all over again.

 

Unsubscribing Scrips (To stop getting feeds for particular scrips)

If want to Unsubscribe a particular scrip we need to pass following in Request:- {"Method":"MarketFeedV3","Operation":"Unsubscribe", "ClientCode":"<<Pass ClientCode>>","MarketFeedData":[ {"Exch":"N","ExchType":"C","ScripCode":15083} ]}

In this case we will continue receiving feeds of N,C,999901 and N,C,22 and we will stop receiving live feeds of N,C,15083 as we have unsubscribed this scrip.

Response for Market Feed:- [{"Exch":"N","ExchType":"C","Token":1660,"LastRate":205,"LastQty":13,"TotalQty":6508704, "High":206.5,"Low":203.85,"OpenRate":203.9,"PClose":205.55,"AvgRate":205.39,"Time":23608, "BidQty":21411,"BidRate":205,"OffQty":7401,"OffRate":205.05,"TBidQ":2195269, "TOffQ":2419127,"TickDt":"\/Date(1620716608000)\/"}]

REQUEST:

  
                      
                      

{"Method":"MarketFeedV3","Operation":"Subscribe", "ClientCode":"<<Pass ClientCode>>","MarketFeedData":[ {"Exch":"N","ExchType":"C","ScripCode":15083} ]}

Sample Request:- {"Method":"MarketFeedV3","Operation":"Subscribe", "ClientCode":"ABC123","MarketFeedData":[ {"Exch":"N","ExchType":"C","ScripCode":15083} ]}

REQUEST:

                      
                        

req_list=[
            { "Exch":"N","ExchType":"C","ScripCode":1660},
            ]

req_data=client.Request_Feed('mf','s',req_list)
def on_message(ws, message):
    print(message)


client.connect(req_data)

client.receive_data(on_message)

REQUEST:

                      
                        
                      
                    

Order Request (Place Order)

This allows the user to place an order in cash, FO, currency, commodity segments, intraday or delivery.
Request Body
Name Desc Compulsory* DataType
Exchange Pass the Exchange.
N - Nse
B - Bse
M - Mcx
Y Char
ExchangeType Pass the Exchange Type.
C - Cash
D - Derivative
U - Currency
Y Char
ScripData/ScripCode
  • Either pass ScripCode or ScripData if you pass ScripData then use below format to pass data for different segments : For Cash : ScripData : ”INFY_EQ” (symbol and series)
  • Future scrips : "NIFTY 30 Sep 2021_20210930"( symbol and expiry in yyyymmdd format)
  • Options scrip : "NIFTY 30 Sep 2021 CE 11000.00_20210930_CE_11000" (symbol,expiry, call/put, strikerate) for currency and commodity same pattern will be followed.
  • In case want to pass Scrip Code, please refer to our scrip master file.
(Refer Full Name field)
Y String
Price Pass the Price.
(Price 0 - At Market Order)
Y Double
Qty Pass the Qty. Y Long
OrderType Pass the Order Type.
Buy Or Sell
Y String
DisQty Pass the DisQty. N Long
StopLossPrice Pass the Stop Loss Price.
(Stop Loss Price 0 - Stop Loss Order)
N Double
IsIntraday Pass the IsIntraday.
(True or False)
Y Boolean
iOrderValidity Pass the iOrderValidity. N Enum
AppSource Pass the App Source of Vendor. Y Long
RemoteOrderID Pass the Remote Order ID for tracking. N String
 
 
Response Body
Field Name Description Data Type
BrokerOrderID BrokerOrderID of order placed . string
ClientCode ClientCode passed in request . String
Exch Exchange passed in request String
ExchOrderID it comes as zero RMS doesnt send Exchange order ID String
ExchType Exchange Type passed in request String
LocalOrderID OrderID passed in request String
Message Error Message String
RMSResponseCode RMSResponseCode Double
ScripInfo Scripdata or scripcode passed in request string
status status of order request Integer
time order placed time string

REQUEST:

  
                      
                      

REQUEST:



curl --location --request POST 'https://openapi.5paisa.com/VendorsAPI/Service1.svc/V1/PlaceOrderRequest' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer {Your Access Token}' \
--header 'Cookie: 5paisacookie=j2usr4wuddgegs14hcjrh3d4; NSC_JOh0em50e1pajl5b5jvyafempnkehc3=ffffffffaf103e0f45525d5f4f58455e445a4a423660' \
--data-raw '{
    "head": {
        "key": "{Your Vendor/User Key}"
    },
    "body": {
    "ClientCode":"{Your Client Code}",	
	"Exchange":"N",
	"ExchangeType" : "C",	
    "Qty": "50",
    "Price": "1800.50",
    "OrderType":"Buy",   
	"ScripData" : "1660",   	
	"UniqueOrderID" : "5000009131120348662",
	"IsIntraday" : false,
    "DisQty": 1,
    "StopLossPrice":0,
    "IsStopLossOrder" : false,
    "OrderID" : 2,   
    "IsIOCOrder":false,
    "IsAHOrder": "N",
    "ValidTillDate":"/Date(1630391628000)/",
    "RemoteOrderID":"{Your custom order tag}",
	"AppSource" : "{your app source}"
    }
}'

REQUEST:

                      
                        

REQUEST:


#Note: This is an indicative order.

from py5paisa.order import Order, OrderType, Exchange

#This is example of a commodity order. You can pass scripdata either you can pass scripcode also.

#Using Scrip Data :-

test_order = Order(order_type='B',exchange='M',exchange_segment='D', scripdata = 'GOLDM 03 Nov 2021_20211103', quantity=1, price=47900,is_intraday=True,IsGTCOrder=False,IsEOSOrder=True)
client.place_order(test_order)

#Using Scrip Code :-
test_order = Order(order_type='B',exchange='N',exchange_segment='C', scrip_code = 1660, quantity=1, price=236.5,is_intraday=True)
client.place_order(test_order)



REQUEST:

                      
                        

REQUEST:




 var options = {
            exchangeSegment: "C",
            atMarket: false,
            isStopLossOrder: false,
            stopLossPrice: 0,
            isVTD: false,
            isIOCOrder: false,
            isIntraday: false,
            ahPlaced: "N",
            IOCOrder: false,
            price: 208
        };
        try {
            client.placeOrder("BUY", "1660", "1", "N", options).then((response) => {
                console.log(response)
            })
        } catch (err) {
console.log(err)
        }



Order Modify

This API is used to modify order in cash ,FO, currency, commodity segments.
Now allowed to modify with fields with only relevant fields.All other fields (except ExchangeOrderID) which modification is not needed can be skipped as per requirement.
Request Body
Field Name Description Compulsory* Data Type
Price Pass Price to modify N Double
Qty Pass quantity N integer
ExchOrderID Pass Exchange Order ID of an order which you want to modify. Y string
DisQty pass Disclosed qty N long
Stoplossprice pass stoploss price N double
AppSource pass Appsource given to vendor. N string
RemoteOrderID Pass ID in order to tag placed orders N string

 

Response Body
Field Name Description Data Type
BrokerOrderID BrokerOrderID of order placed. string
ClientCode ClientCode passed in request. String
Exch Exchange passed in request String
ExchOrderID it comes as zero RMS doesnt send Exchange order ID String
ExchType Exchange Type passed in request String
LocalOrderID OrderID passed in request String
Message Error Message String
RMSResponseCode RMSResponseCode Double
ScripInfo Scripdata or scripcode passed in request string
status status of order request Integer
time order modified time string

REQUEST:

  
                      
                      

curl --location --request POST 'https://Openapi.5paisa.com/VendorsAPI/Service1.svc/V1/ModifyOrderRequest' \
--header 'Authorization: Bearer null' \
--header 'Content-Type: application/json' \
--header 'Cookie: ASP.NET_SessionId=bqr45sqdj5vtexqouwvfmjb2; NSC_JOh0em50e1pajl5b5jvyafempnkehc3=ffffffffaf103e0f45525d5f4f58455e445a4a423660' \
--data-raw '{
    "head": {
        "key": "{Your Vendor/User Key}"
    },
    "body": {
        "Qty":"30",
        "ExchOrderID": "{Exchange Order ID }"
    }
}'

REQUEST:

                      
                        

REQUEST:




test_order = Order(order_type='B', scrip_code=1660, quantity=1, price=205,is_intraday=False,exchange='N',exchange_segment='C',exch_order_id="12345678" )
client.modify_order(test_order)


REQUEST:

                      
                        

REQUEST:




    client.modifyOrder("1100000007628729", "1", "210", "1660", false, "N", "C", true).then((response)=> {
            console.log(response)
        })
    } ).catch((err) => {
        console.log(err)
    });


Order Cancel

This API is used to cancel order in cash, FO, currency, commodity segments
 
Request Body
Field Name Description Data Type
ExchOrderID Pass Exchange Order ID of an order which you want to modify. String

 

Response Body
Field Name Description Data Type
BrokerOrderID BrokerOrderID of order placed . string
ClientCode ClientCode passed in request . String
Exch Exchange passed in request String
ExchOrderID it comes as zero RMS doesnt send Exchange order ID String
ExchType Exchange Type passed in request String
LocalOrderID OrderID passed in request String
Message Error Message String
RMSResponseCode RMSResponseCode Double
ScripInfo Scripdata or scripcode passed in request string
status status of order request Integer
time order modified time string

REQUEST:

  
                      
                      

REQUEST:



curl --location --request POST 'https://Openapi.5paisa.com/VendorsAPI/Service1.svc/V1/CancelOrderRequest' \
--header 'Authorization: Bearer null' \
--header 'Content-Type: application/json' \
--data-raw '{
    "head": {
        "key": "{Your Vendor/User Key}"
    },
    "body": {
        "ExchOrderID":"{Exchange Order ID}"
    }
}'

REQUEST:

                      
                        

REQUEST:




client.cancel_order(exchange='N',exchange_segment='C',exch_order_id='12345678')


REQUEST:

                      
                        

REQUEST:




 client.cancelOrder("1100000007973827", "1", "205", "1660", false, "N", "C", false).then((response) => {
            console.log(response)
        })
    } ).catch((err) => {
        console.log(err)
    });

Cancel Bulk Orders

This API is used to cancel multiple orders at a time.

 

Request Body

Name Desc Required* DataType
ExchOrderIDs List of Exchange Order ID. Y List

 

ExchOrderIDs (List)

Name Desc Required* DataType
ExchOrderID Pass the Exchange Order ID. Y String

 

Body Attributes

Name Desc
ClientCode Returns the ClientCode.
LocalOrderID Returns the Local Order ID.
BrokerOrderID Returns the Broker Order ID.
ExchOrderID Returns the Exchange Order ID.
ExchType Returns the Exchange Type.
Exch Returns the Exchange.
RMSResponseCode Returns the RMS Response Code.
Status 0 for success
In case of non zero code, refer following field for error description
Message Error description incase of non zero status or "Success".
Time Returns the TimeStamp.
ScripCode Returns the Scrip Code.

REQUEST:

  
                      
                      

curl --location --request POST 'https://Openapi.5paisa.com/VendorsAPI/Service1.svc/CancelOrderBulk' \
--header 'Authorization: Bearer null' \
--header 'Content-Type: application/json' \
--data-raw '{
    "head": {
        "key": "{Your Vendor/User Key}"
    },
    "body": {
        "ExchOrderIDs": [
            {
                "ExchOrderID": "{{Exchange Order ID1}}"
            },
            {
                "ExchOrderID": "{{Exchange Order ID2}}"
            }
        ]
    }
}'

REQUEST:

                      
                        

cancel_bulk=[
            {
                "ExchOrderID": "<Exchange Order ID 1>"
            },
            {
                "ExchOrderID": "<Exchange Order ID 2>"
            },
client.cancel_bulk_order(cancel_bulk)

REQUEST:

                      
                        

a=[
            {
                "ExchOrderID": "{{Exchange Order ID1}}"
            },
            {
                "ExchOrderID": "{{Exchange Order ID2}}"
            }
        ]

client.canceBulkOrder(a).then((positions) => {

                            console.log(positions)

                        }).catch((err) => {

                            console.log(err)

                        });

SquareOff All Orders

This API is used to squareoff all the open positions for a specific client.

REQUEST:

  
                      
                      

curl --location --request POST 'https://Openapi.5paisa.com/VendorsAPI/Service1.svc/SquareOffAll' \
--header 'Authorization: bearer {{Access_Token}}' \
--header 'Content-Type: application/json' \
--data-raw '{
    "head": {
        "key": "{Your Vendor/User Key}"
    },
    "body": {
        "ClientCode": "{{Client_Code}}"
    }
}'

REQUEST:

                      
                        

client.squareoff_all()

REQUEST:

                      
                        

client.squareoff_all()

Place Bracket/Cover Order

This API allows to Place/Modify/Cancel a new Cover/Bracket order.
This is by default intraday order.
Request Body
Field Name Description Data Type Sample Value
ClientCode Pass the ClientCode. String  
OrderRequesterCode Pass the OrderRequesterCode. String  
RequestType Pass the RequestType. Char p-place
BuySell Pass the BuySell. String B/S
Qty Pass the Qty. Long  
Exch Pass the Exch. String  
ExchType Pass the ExchType. String  
DisQty Pass the DisQty. Long  
AtMarket Pass the AtMarket. Boolean true/false
ExchOrderId Pass the ExchOrderId. Integer  
LimitPriceInitialOrder Pass the LimitPriceInitialOrder. Double  
TriggerPriceInitialOrder Pass the TriggerPriceInitialOrder. Double  
LimitPriceProfitOrder Pass the LimitPriceProfitOrder. Double  
TriggerPriceForSL Pass the TriggerPriceForSL. Double  
TrailingSL Pass the TrailingSL. Double  
StopLoss Pass the StopLoss. Boolean  
ScripCode Pass the ScripCode. Integer  
OrderFor Pass the OrderFor. String  
UniqueOrderIDNormal Pass the UniqueOrderIDNormal. String 5000009120154900067
UniqueOrderIDSL Pass the UniqueOrderIDSL. String  
UniqueOrderIDLimit Pass the UniqueOrderIDLimit. String  
LocalOrderIDNormal Pass the LocalOrderIDNormal. Long  
LocalOrderIDSL Pass the LocalOrderIDSL. Long  
LocalOrderIDLimit Pass the LocalOrderIDLimit. Long  
PublicIP Pass the PublicIP. String  
AppSource Pass the AppSource. Integer  
LimitPriceForSL Pass the Limit Price for SL leg. Double  
TradedQty Pass the TradedQty. Long  
Response Body
Field Name Description Data Type
LocalOrderIDNormal Returns the LocalOrderIDNormal. Integer
LocalOrderIDSL Returns the LocalOrderIDSL. Integer
BrokerOrderIDNormal Returns the BrokerOrderIDNormal. Integer
BrokerOrderIDSL Returns the BrokerOrderIDSL. Integer
RMSStatus Returns the RMSStatus. Integer
Time Returns the Time. Integer
FirstOrderPrice Returns the FirstOrderPrice. Integer
FirstOrderTriggerPrice Returns the FirstOrderTriggerPrice. Integer
SLOrderPrice Returns the SLOrderPrice. Integer
SLOrderTriggerPrice Returns the SLOrderTriggerPrice. Integer
LocalOrderIDProfit Returns the LocalOrderIDProfit. Integer
BrokerOrderIDProfit Returns the BrokerOrderIDProfit. Integer
ProfitPrice Returns the ProfitPrice. Integer
TrailingSL Returns the TrailingSL. Integer
ClientCode Returns the ClientCode. String
ExchOrderID Returns the ExchOrderID. Integer
ExchType Returns the ExchType. Char
Exch Returns the Exch. Char
RMSResponseCode Returns the RMSResponseCode. Integer
Message Returns the Message. String
AvlbMgn Returns the AvlbMgn. Double
AddReqMgn Returns the AddReqMgn. Double

REQUEST:

  
                      
                      

REQUEST:




curl --location --request POST 'https://Openapi.5paisa.com/VendorsAPI/Service1.svc/SMOOrderRequest' \
--header 'Authorization: bearer {Your Access Token}' \
--header 'Content-Type: application/json' \
--header 'Cookie: NSC_JOh0em50e1pajl5b5jvyafempnkehc3=ffffffffaf103e0c45525d5f4f58455e445a4a423660' \
--data-raw '{
    "head": {
        "key": "{Your Vendor/User Key}"
    },
    "body": {
       "ClientCode": "{Your Client Code}",
       "OrderRequesterCode": "{Your Client Code}",
       "RequestType": "P",
       "BuySell": "B",
       "Qty": "300",
       "Exch": "N",
       "ExchType": "D",
       "DisQty": "0",
       "AtMarket": "false",
       "ExchOrderId": "0",
       "LimitPriceForSL":"960.00",
       "LimitPriceInitialOrder": "965.00",
       "TriggerPriceInitialOrder": "0",
       "LimitPriceProfitOrder": "970.00",
       "TriggerPriceForSL": "5",
       "TrailingSL": "0",
       "StopLoss": "0",
       "ScripCode": "72403",
       "OrderFor": "C",
       "UniqueOrderIDNormal": "5000009120154900067",
       "UniqueOrderIDSL": "0",
       "UniqueOrderIDLimit": "0",
       "LocalOrderIDNormal": "5",
       "LocalOrderIDSL": "0",
       "LocalOrderIDLimit": "0",
       "PublicIP": "",
       "AppSource": "4057",
       "TradedQty": "0"
    }
}'
/code>

REQUEST:

                      
                        

REQUEST:




test_order=bo_co_order(scrip_code=1660,BuySell='B',Qty=1, LimitPriceInitialOrder=205,TriggerPriceInitialOrder=0,LimitPriceProfitOrder=215.0,TriggerPriceForSL=203,LimitPriceForSL=202,ExchType='C',Exch='N',RequestType='P',AtMarket=False)

client.bo_order(test_order)

REQUEST:

                      
                        

REQUEST:




var a={
           
        }
    client.bocoorder(1660,1,205,0,217,'B','N','C','P',200,a).then((Response)=>{
            console.log(Response)
        }).catch((err)=>{
            console.log(err)
        })
// Note : For Cover order par Order_for='c'



Modify Bracket/Cover Order

This API allows to modify values(parameters) of a placed order with open stoploss/profit legs.
Request Body
Field Name Description Data Type Sample Value
ClientCode Pass the ClientCode. String  
OrderRequesterCode Pass the OrderRequesterCode. String  
OrderFor Pass the OrderFor. String M-Modify
Exchange Pass the Exchange. Char  
ExchangeType Pass the ExchangeType. Char  
Price Pass the Price. Double  
OrderID Pass the OrderID. Long  
OrderType Pass the OrderType. Date  
Qty Pass the Qty. Long  
OrderDateTime Pass the OrderDateTime. Date  
ScripCode Pass the ScripCode. Long  
AtMarket Pass the AtMarket. Boolean  
RemoteOrderID Pass the RemoteOrderID. String  
ExchOrderID Pass the ExchOrderID. String  
DisQty Pass the DisQty. Long  
TriggerPriceForSL Pass the TriggerPriceForSL. Double  
IsStopLossOrder Pass the IsStopLossOrder. Boolean  
IOCOrder Pass the IOCOrder. Boolean  
IsIntraday Pass the IsIntraday. Boolean  
ValidTillDate Pass the ValidTillDate. Date  
AHPlaced Pass the AHPlaced. Char  
PublicIP Pass the PublicIP. String  
iOrderValidity Pass the iOrderValidity. OrderValidity  
TrailingSL Pass the TrailingSL. Double  
LegType Pass the LegType. Int32  
TMOPartnerOrderID Pass the TMOPartnerOrderID. Int32  
AppSource Pass the AppSource. Integer  
LimitPriceForSL Pass the Limit Price for SL leg. Double  
TradedQty Pass the TradedQty. Long  
Response Body
Field Name Description Data Type
ClientCode Returns the ClientCode. String
LocalOrderID Returns the LocalOrderID. Integer
BrokerOrderID Returns the BrokerOrderID. Integer
ExchOrderID Returns the ExchOrderID. Integer
ExchType Returns the ExchType. Char
Exch Returns the Exch. Char
RMSResponseCode Returns the RMSResponseCode. Integer
Status Returns the Status. Integer
Message Returns the Message. String
Time Returns the Time. DateTime
ScripCode Returns the ScripCode. Integer
AvlbMgn Returns the AvlbMgn. Double
AddReqMgn Returns the AddReqMgn. Double

REQUEST:

  
                      
                      

REQUEST:




curl --location --request POST 'https://Openapi.5paisa.com/VendorsAPI/Service1.svc/ModifySMOOrder' \
--header 'Authorization: bearer {Your Access Token}' \
--header 'Content-Type: application/json' \
--header 'Cookie: NSC_JOh0em50e1pajl5b5jvyafempnkehc3=ffffffffaf103e0f45525d5f4f58455e445a4a423660' \
--data-raw '{
    "head": {
        "key": "{Your Vendor/User Key}"
    },
    "body": {
        "ClientCode": "{Your Client Code}",
        "OrderFor": "M",
        "Exchange": "B",
        "ExchangeType": "C",
        "Price": "780",
        "OrderID": 0,
        "OrderType": "B",
        "Qty": 1,
        "OrderDateTime": "/Date(1569396922334)/",
        "ScripCode": "532215",
        "AtMarket": false,
        "RemoteOrderID": "5000009120154900067",
        "ExchOrderID": 1606801033587000415,
        "DisQty": "0",
        "TriggerPriceForSL": "2",
        "IsStopLossOrder": false,
        "IOCOrder": true,
        "IsIntraday": false,
        "ISVTD": false,
        "AHPlaced": "N",
        "PublicIP": "0.0.0.0",
        "iOrderValidity": 0,
        "TradedQty": 0,
        "OrderRequesterCode": "{Your Client Code}",
        "AppSource": "0",
        "TrailingSL": "0.02",
        "LegType": "0",
        "TMOPartnerOrderID": "0"
    }
}'
/code>

REQUEST:

                      
                        

REQUEST:




test_order=bo_co_order(scrip_code=1660,BuySell='B',Qty=1, LimitPriceInitialOrder=203,TriggerPriceInitialOrder=0,LimitPriceProfitOrder=208.0,TriggerPriceForSL=202,LimitPriceForSL=201,ExchType='C',Exch='N',RequestType='M',AtMarket=False,ExchOrderId='12345678')

client.bo_order(test_order)

#Note : For cover order just pass LimitPriceProfitOrder equal to Zero.

        

REQUEST:

                      
                        

REQUEST:




var a={
            "ExchOrderId":"1100000008193800",      
       }
    client.bocoorder(1660,1,205,0,217,'B','N','C','M',200,a).then((Response)=>{
            console.log(Response)
        }).catch((err)=>{
            console.log(err)
        })
        
   // Note : We Can not Modify Target And Stoploss legs


Order Book

This API is used to Fetch OrderBook of a particular Client which will contain all the Orders.
Please note you can call Order Book API every 3 seconds, for runtime order updates please use websocket.
Request Body
Field Name Description Data Type (max length) Sample Value
ClientCode Pass the registered client code of the user. String(10) 12345678
Response Body
Field Name Description Data Type (max length) List Values Sample Value
Status Returns the status of the response. Integer A. -1
0
1
2
Message Returns the message of the reponse. String - “Success”
“No record found.”
“Invalid input parameters.”
“Invalid head parameters.”
“Error while processing your request.”
“Invalid Session”
"No Order found for this Client."
OrderBookDetail Order Details of that particular client for the day. Array Of Orders Array Of Orders -
ORDER BOOK DETAIL
Field Name Type Description
RequestType Char Order request type
P- Placed, M- Modified, C- Cancelled, S- Bracket/Cover Order
BrokerOrderId Int32 Order ID set by 5paisa for a particular Order
BrokerOrderTime DateTime Time at which order received by 5paisa
Exch Char Exchange in which order has been Placed. N- NSE, B-BSE, M- MCX
ExchType Char Exchange segment C-Cash, D-Derivatives, U-Currency
ScripCode Int32 Scrip Code of the particular stock
ScripName String Scrip Name of the scrip.
BuySell Char B- Buy
S- Sell
Qty Int32 Order Qunatity
Rate Double Rate at which order has been placed
AtMarket Char Order Placed is limit order or Market Order. Y-At Market, N- Limit Order
WithSL Char Is stop loss order.
SLTriggerRate Double Stop lass rate
SLTriggered Char Is stop loss triggered
ExchOrderID String Order ID given by Exchange to an order.
ExchOrderTime DateTime Time at which order has received by Exchange
OrderStatus String Status of an Order.
AfterHours Char Is Order Placed After Market order.
AHProcess Char Is AH Order is Processed by 5paisa or not
OldorderQty Int32 Order quantity before modified quantity
TradedQty Int32 Number of Quantity which are traded.
PendingQty Int32 Remaining quantity after trade happened
OrderRequesterCode String Id of the user who had placed the order.
DisClosedQty Int32 Quantity which is exposed in Exchange by Client.
TerminalId Int32 Terminal number on which order has been sent.
DelvIntra Char I-Intraday, D-Delivery
OrderValidity Int32 Validity of an order.
Day = 0
GTD = 1
GTC = 2
IOC = 3
EOS = 4
VTD = 5
FOK = 6
OrderValidUpto String Order Validity Date
Reason String Order rejection reason.
SMOSLLimitRate Double SMO Stop Loss Limit Rate
SMOSLTriggerRate Double SMO Stop Loss Trigger Rate
SMOProfitRate Double SMO Profit Rate
SMOTrailingSL Double SMO Trailing Stop Loss
MarketLot Double Shows MarketLot

REQUEST:

  
                      
                      

REQUEST:




curl --location --request POST 'https://Openapi.5paisa.com/VendorsAPI/Service1.svc/V2/OrderBook' \
--header 'Authorization: bearer {Your Access Token}' \
--header 'Content-Type: application/json' \
--header 'Cookie: NSC_JOh0em50e1pajl5b5jvyafempnkehc3=ffffffffaf103e0f45525d5f4f58455e445a4a423660' \
--data-raw '{
    "head": {
        "key": "{Your Vendor/User Key}"
    },
    "body": {
        "ClientCode": "{Your Client Code}"
    }
}'

REQUEST:

                      
                        

REQUEST:




client.order_book()

REQUEST:

                      
                        

REQUEST:




 client.getOrderBook().then((orders) => {
       console.log(orders)
     }).catch((err) => {
       console.log(err)
    });

Trade Book

This API will give list of all trades made with complete Trade related information
Request Body
Field Description DataType Sample Value
ClientCode Pass the ClientCode. String 50000091
Response Body
Field Description DataType
TradeBookDetail List of TradeBookDetailV1 List
Status Pass the Status. Integer
Message Pass the Message. String
TradeBookDetailV1 :
Field Description DataType
Exch Pass the Exch. Char
ExchType Pass the ExchType. Char
ScripCode Pass the ScripCode. Int
ScripName Pass Name of Scrip. String
BuySell Pass Buy/Sell. Char
Qty Pass the Qty. Int
PendingQty Pass the PendingQty. Int
OrgQty Pass the OrgQty. Int
Rate Pass the Rate. Double
ExchOrderID Pass the ExchOrderID. String
ExchangeTradeID Pass the ExchangeTradeID. String
ExchangeTradeTime Pass the ExchangeTradeTime. DateTime
TradeType Pass the TradeType. String
DelvIntra Pass the Delv / Intra. Char
Multiplier Pass the Multiplier. Double

REQUEST:

  
                      
                      

REQUEST:




curl --location --request POST 'https://Openapi.5paisa.com/VendorsAPI/Service1.svc/V1/TradeBook' \
--header 'Authorization: bearer {Your Access Token}' \
--header 'Content-Type: application/json' \
--header 'Cookie: NSC_JOh0em50e1pajl5b5jvyafempnkehc3=ffffffffaf103e0f45525d5f4f58455e445a4a423660' \
--data-raw '{
    "head": {
        "key": "{Your Vendor/User Key}"
    },
    "body": {
        "ClientCode": "{Your Client Code}"
    }
}'

REQUEST:

                      
                        

REQUEST:




client.get_tradebook()


REQUEST:

                      
                        

REQUEST:




client.getTradeBook().then((response) => {
            console.log(response)
        }).catch((err) => {
            console.log(err)
        });

Trade History

Request Body

Name Desc Required* DataType
ClientCode Pass the ClientCode. Y String
ExchOrderID Pass Order ExchOrderID. Y String

 

Response Body

Name Desc
TradeHistoryData List of TradeHistoryData.
Status 0 for success
In case of non zero code, refer following field for error description
Message Error description incase of non zero status or "Success".

 

Trade History List Attributes:-

Name Desc
Exchange Returns the Exchange.
ExchangeType Returns the Exchange Type.
ScripCode Returns the Scrip Code.
Symbol Returns the Symbol.
Product Returns the Product.
TransactionType Returns the Transaction Type.
TradedQty Returns the Traded Qty.
ExchOrderID Returns the Exchange Order ID.
RemoteOrderID Returns the Remote Order ID.
ExchangeTime Returns the Exchange Time.
TradePrice Returns the Trade Price.
TradeID Returns the Trade ID.
OrderType Returns the Order Type.

REQUEST:

  
                      
                      

curl --location --request POST 'https://Openapi.5paisa.com/VendorsAPI/Service1.svc/TradeHistory' \
--header 'Authorization: Bearer null' \
--header 'Content-Type: application/json' \
--data-raw '{
    "head": {
        "key": "{Your Vendor/User Key}"
    },
    "body": {
        "ClientCode": "null",
        "ExchOrderID":"{Exchange Order ID}"
    }
}'

REQUEST:

                      
                        
client.get_trade_history("PASS EXCHANGE ORDER ID")

REQUEST:

                      
                        
                      
                    

Order Status

This allows the user to check order status of their placed orders using the RemoteOrderID used at the time of order placement.
Request Structure
Field Name Description Sample Value
ClientCode Pass your ClientCode  12345678
OrdStatusReqList List Of OrderStatusReqList -
 
Request List
Field Name Description Data Type
Exch Exchange in which order has been placed. (N- NSE, B- BSE , M-MCX) char
RemoteOrderID This will be unique ID for each order. String
 
Response Body
Field Name Description Data Type List of values
Status Returns the status of the response. Integer A. -1 B. 0 C. 1 D. 2
Message Returns the message of the response. String A. “Success” B. “No record found.” C. “Invalid input parameters.” D. “Invalid head parameters.” E. “Error while processing your request.” F. “Invalid Session” G. "No Order found for this Client.
OrdStatusResLst Array Of OrdStatusResLst Trade Details of that particular client Array Of OrdStatusResLst -
 
Response List
FieldName Type Description
Exch Char Exchange in which order has been Placed. N- NSE, B-BSE, M-MCX
ExchType Char Exchange segment C-Cash, D-Derivatives, U-Currency
ScripCode Int32 Scrip Code of the particular stock
Symbol String Symbol of the scrip.
OrderQty Int32 Returns order quantity
OrderRate Double Returns order rate
ExchOrderID Int32 Order ID given by Exchange to an order.
ExchOrderTime DateTime Time at which order has received by Exchange
Status String Returns the status of the response.
TradedQty Int32 Returns Traded Qty of an order.
PendingQty Int32 Returns Pending Qty of an order.

REQUEST:

  
                      
                      

REQUEST:




curl --location --request POST 'https://Openapi.5paisa.com/VendorsAPI/Service1.svc/V1/OrderStatus' \
--header 'Authorization: bearer {Your Token}' \
--header 'Content-Type: application/json' \
--data-raw '{
    "head": {
        "key": "{You Key}"
    },
    "body": {
        "ClientCode": "{Your Client Code}",
        "OrdStatusReqList": [
            {
                "Exch": "{Exchange of your placed order}",
                "RemoteOrderID": "{Tag used at the time of placing order}"
            }
        ]
    }
}'


REQUEST:

                      
                        

REQUEST:




req_list_= [

        {
            "Exch": "N",
            "RemoteOrderID": "90980441"
        }]
# Fetches the order status
client.fetch_order_status(req_list_)


REQUEST:

                      
                        

REQUEST

var a=[{ "Exch":"N", "RemoteOrderID":"1" }] client.getOrderStatus(a).then((Response) => { console.log(Response) }).catch((err) => { console.log(err) });

Trade Information

This API is used to Fetch detailed Trade Information for a set of orders placed.
Request Body
Field Name Description Data Type (max length) List of values Sample Value
ClientCode Pass the registered client code of the user. String(10) - 12345678
TradeInformationList List Of TradeInformationList List Of TradeInformationList - -
TRADE INFORMATION LIST
Field Name Description Data Type (max length) List of values
Exch Exchange in which order has been placed. N- NSE, B- BSE ,M-MCX Char N
B
M
ExchType Exchange segment. C-Cash, D-Derivative, U – Currency Char C
D
U
ScripCode Scrip Code of the requested order. Long -
RemoteOrderID This will be unique ID for each order which was sent at the time of placing the order. String 112313

REQUEST:

  
                      
                      

REQUEST:




curl --location --request POST 'https://Openapi.5paisa.com/VendorsAPI/Service1.svc/TradeInformation' \
--header 'Authorization: bearer {Your Access Token}' \
--header 'Content-Type: application/json' \
--header 'Cookie: 5paisacookie=ym05vvsxopu5pxusz45y1ys3; NSC_JOh0em50e1pajl5b5jvyafempnkehc3=ffffffffaf103e0f45525d5f4f58455e445a4a423660' \
--data-raw '{
    "head": {
        "key": "{Your Vendor/User Key}"
    },
    "body": {
        "ClientCode": "{Your Client Code}",
        "TradeInformationList": [
            {
                "Exch": "N",
                "ExchType": "C",
                "ScripCode": {Order ScripCode},
                "ExchOrderID": {ExchangeOrderID}
            }
        ]
    }
}'

REQUEST:

                      
                        

REQUEST:




req_list= [
        {
            "Exch": "N",
            "ExchType": "C",
            "ScripCode": 20374,
            "ExchOrderID": "1000000015310807"
        }]

# Fetches the trade details
client.fetch_trade_info(req_list)

REQUEST:

                      
                        

REQUEST:




a=[
      {
        "Exch":"N",
        "ExchType":"C",
        "ScripCode":11111,
        "RemoteOrderID":"5712977609111312242"
    }
     ]
client.getTradeInfo(a).then((response) => {
            console.log(response)
        }).catch((err) => {
            console.log(err)
        });


Historical Data

Historical candle data is the backbone for any strategy deployed and this API provides the support by providing archived data for various scrip codes. The API works in an active session and requires clients to login first.
Note:- In case of invalid token error; please check validity of the token using Validate Session API (Available in Other APIs section).
The API with the GET request method is used to fetch the historical candle data which After token validation, the historical data can be fetched for any scrip code using GET method. It provides OHLCV (open, high, low, close and volume) and volume data along with timestamps for scrip codes passed in the request.
Time Frames available:-
  • 1m - 1 minute
  • 5m - 5 minute
  • 10m - 10 minute
  • 15m - 15 minute
  • 30m - 30 minute
  • 60m - 60 minute
  • 1d - 1 day
URL PARAMETERS
Field Name Description Sample Value
Exch Exchange of the scrip
N – NSE
B – BSE
M – MCX (ExchType will be D)
n – NCDEX (only if ExchType is X)
N
B
M
ExchType Exchange segment of the scrip
c – Cash
d – Derivative (Commodity if exchange is M) u – Currency Derivative
x – NCDEX commodity
y – Commodity
c
d
u
x
y
ScripCode Unique number for particular scrip 1660
Interval Interval for candle data.
1m - 1 minute
5m - 5 minute
10m - 10 minute
15m - 15 minute
30m - 30 minute
60m - 60 minute
1d - 1 day
1m
5m
10m
15m
30m
60m
1d
FromDate Date from which candle data needs to be fetched (Format: YYYY-MM-DD) 2021-01-01
EndDate Date to which candle data needs to be fetched (Format: YYYY-MM-DD) 2021-05-30
RESPONSE BODY
Field Name Description Data Type Sample Value
status Status of the response String Cannot be empty
data Contains the data of requested candles   -
candles An array of the OHLC and volume data along with timestamp Array [[ Datetime,Open,High,Low,Close,Volume],[Datetime,Open,High,Low,Close,Volume]]
CANDLES
Field Name Description Data Type Sample Value
Timestamp This is the timestamp of the data in the format of YYYY-MM-DDTHH:MM:SS String 2021-04-01T09:15:00
Open This is the open rate at given time stamp Double 1480.2
High This is the high rate at given time stamp Double 1501.35
Low This is the low rate at given time stamp Double 1420
Close This is the close rate at given time stamp Double 1492.95
Volume This is the volume at given time stamp Integer 39003540

REQUEST:

  
                      
                      

REQUEST:




curl --location --request GET 'https://openapi.5paisa.com/historical/n/c/1594/5m?from=2021-05-24&end=2021-05-27' \
--header 'Ocp-Apim-Subscription-Key: c89dgt8d888a426d9e00db888b433027' \
--header 'x-clientcode: {Your client code}' \
--header 'x-auth-token: {Your Access Token}' \

/code>

REQUEST:

                      
                        

REQUEST:




#historical_data(exchange,exchange type,scrip code,time frame,from data,to date)

df=client.historical_data('N','C',1660,'15m','2021-05-25','2021-06-16')
print(df)

# Note : TimeFrame Should be from this list ['1m','5m','10m','15m','30m','60m','1d']


REQUEST:

                      
                        

REQUEST:




// historicalData(exchange,exchange type,scrip code,time frame,from data,to date)
a=client.historicalData('n', 'c', '1660', '1m','2021-05-31', '2021-06-01')

//Note: Timeframe should be from this list ['1m','5m','10m','15m','30m','60m','1d']


Compact Market Snapshot

This API is used to fetch latest live last traded price (LastRate) along with highest price for the day (High), lowest price for the day (Low), previous close (PClose) and Scrip Code (token).
 
INPUT PARAMETERS
(HEAD PARAMETERS NOT INCLUDED)
Field Name Description Data Type Examples
Count Pass the ClientCode. long 1
MarketFeedData Array of MarketFeedDataListReq List -
ClientLoginType Pass the ClientLoginType. Integer 0
LastRequestTime Pass the LastRequestTime. DateTime /Date(0)/
RefreshRate Pass the RefreshRate. String H
*Note:- All fields are mandatory (cannot be empty)
MARKET FEED DATA LIST REQUEST
Field Name Description Data Type Examples
1 Exch Pass the Exch. String
ExchType Pass the ExchType. String C
Symbol Pass the Symbol. String BHEL
Expiry Pass the Expiry. String  
StrikePrice Pass the StrikePrice. Double 0
OptionType Pass the OptionType. String  
*Note:- All fields are mandatory (cannot be empty)
 
OUTPUT PARAMETERS
(HEAD PARAMETERS NOT INCLUDED)
Field Name Description Data Type
1 Status Returns the status of the response.
Message Returns the message of the response. String
CacheTime Returns the CacheTime of the response. Integer
TimeStamp Returns the TimeStamp of the response. DateTime
Data Trade Details of that particular client Array Of MarketFeedDataListRes
MARKET FEED DATA LIST RESPONSE
Field Name Description Data Type
1 Exch Returns the Exch.
ExchType Returns the ExchType. Char
Token Returns the Scrip Code. Integer
LastRate Returns the LastRate. Double
TotalQty Returns the TotalQty. Integer
High Returns the High. Double
Low Returns the Low. Double
PClose Returns the PClose. Double
AvgRate Returns the AvgRate. Double
Time Returns the Time. Integer
TickDt Returns the TickDt. Date

REQUEST:

  
                      
                      

REQUEST:




curl --location --request POST 'https://Openapi.5paisa.com/VendorsAPI/Service1.svc/MarketFeed' \
--header 'Authorization: bearer {Your Access Token}' \
--header 'Content-Type: application/json' \
--header 'Cookie: NSC_JOh0em50e1pajl5b5jvyafempnkehc3=ffffffffaf103e0f45525d5f4f58455e445a4a423660' \
--data-raw '{
    "head": {
        "key": "{Your Vendor/User Key}"
    },
    "body": {
        "Count": 1,
        "MarketFeedData": [
            {
                "Exch": "N",
                "ExchType": "C",
                "Symbol": "BHEL",
                "Expiry": "",
                "StrikePrice": "0",
                "OptionType": ""
            }
        ],
        "ClientLoginType": 0,
        "LastRequestTime": "/Date(0)/",
        "RefreshRate": "H"
    }
}'
/code>

REQUEST:

                      
                        

REQUEST:




#NOTE : Symbol has to be in the same format as specified in the example below.

req_list_=[{"Exch":"N","ExchType":"D","Symbol":"NIFTY 22 APR 2021 CE 15200.00","Expiry":"20210422","StrikePrice":"15200","OptionType":"CE"},
            {"Exch":"N","ExchType":"D","Symbol":"NIFTY 22 APR 2021 PE 15200.00","Expiry":"20210422","StrikePrice":"15200","OptionType":"PE"}]
            
client.fetch_market_feed(req_list_)


REQUEST:

                      
                        

REQUEST:




a=[
    {
    "Exch":"N",
    "ExchType":"D",
    "Symbol":"NIFTY 27 MAY 2021 CE 14500.00",
    "Expiry":"20210527",
    "StrikePrice":"14500",
    "OptionType":"CE"
}]


client.getMarketFeed(a).then((response) => {
            console.log(response)
        }).catch((err) => {
            console.log(err)
        });


Full Market Snapshot

This API is used to fetch the complete market snapshot of multiple scrips at a time.
This gives complete scrip level information of the particular time requested.
INPUT PARAMETERS
(HEAD PARAMETERS NOT INCLUDED)
Field Name Description Data Type
ClientCode Pass the ClientCode. String
Count Pass the Count. Long
Data List of MarketDepthReqData List
MARKETDEPTHREQDATA:
Field Name Description Data Type
Exch Pass the Exch. String
ExchType Pass the ExchType. String
ScripCode Pass the ScripCode. Integer
OUTPUT PARAMETERS
(HEAD PARAMETERS NOT INCLUDED)
MARKETDEPTHRESDATA:
Field Name Description Data Type
LastTradeTime Pass the LastTradeTime. DateTime
NetChange Pass the NetChange. String
Open Pass the Open. String
High Pass the High. String
Low Pass the Low. String
Close Pass the Close. String
Volume Pass the Volume. String
AverageTradePrice Pass the AverageTradePrice. Double
LastTradedPrice Pass the LastTradedPrice. Double
LastQuantity Pass the LastQuantity. Integer
BuyQuantity Pass the BuyQuantity. Integer
SellQuantity Pass the SellQuantity. Integer
TotalBuyQuantity Pass the TotalBuyQuantity. Integer
TotalSellQuantity Pass the TotalSellQuantity. Integer
OpenInterest Pass the OpenInterest. Integer
Exchange Pass the Exchange. String
ExchangeType Pass the ExchangeType. String
ScripCode Pass the ScripCode. Integer

REQUEST:

  
                      
                      

REQUEST:




curl --location --request POST 'https://Openapi.5paisa.com/VendorsAPI/Service1.svc/MarketDepth' \
--header 'Authorization: bearer {Your Access Token}' \
--header 'Content-Type: application/json' \
--header 'Cookie: 5paisacookie=qwmwpam1su3s4lvwlwyevrl5; NSC_JOh0em50e1pajl5b5jvyafempnkehc3=ffffffffaf103e0f45525d5f4f58455e445a4a423660' \
--data-raw '{
    "head": {
        "key": "{Your Vendor/User Key}"
    },
    "body": {
        "ClientCode": "{Your Client Code}",
        "Count": "1",
        "Data": [
            {
                "Exchange": "N",
                "ExchangeType": "C",
                "ScripCode": "2885"
            },
            {
                "Exchange": "N",
                "ExchangeType": "C",
                "ScripCode": "2885"
            },
            {
                "Exchange": "N",
                "ExchangeType": "D",
                "ScripCode": "542003"
            }
        ]
    }
}'

REQUEST:

                      
                        

REQUEST:




a=[{"Exchange":"N","ExchangeType":"C","ScripCode":"2885"},
   {"Exchange":"N","ExchangeType":"C","ScripCode":"1660"},
   ]
print(client.fetch_market_depth(a))

REQUEST:

                      
                        

REQUEST:



 
a=[{"Exchange":"N","ExchangeType":"D","ScripCode":"51440"},{"Exchange":"N","ExchangeType":"C","ScripCode":"1660"}]
     client.getmarketdepth(a).then((response) => {
                    console.log(response)
                }).catch((err) => {
                    console.log(err)
                });

Full Market Snapshot (By Symbol)

Request Body

Name Desc Required* DataType
ClientCode Pass the ClientCode. Y String
Count Pass the Number of ScripList. Y Long
Data List of MarketDepth Y List

Data Structure:-

Name Desc Required* DataType
Exchange Pass the Exchange.
N - Nse
B - Bse
M - Mcx
Y String
ExchangeType Pass the ExchangeType.
C - Cash
D - Derivatives
U - Currency
Y String
Symbol

Pass the ScripName.

For Example:- NSE,Cash, RELIANCE

NSE,Derivatives, BANKNIFTY 10 Mar 2022 CE 41600.00

*Full Name from the scripmaster file

Y String

 

Response Attributes

Name Desc
LastTradeTime Returns the LastTradeTime.
NetChange Returns the NetChange.
Open Returns the Open.
High Returns the High.
Low Returns the Low.
Close Returns the Close.
Volume Returns the Volume.
AverageTradePrice Returns the Average Trade Price.
LastTradedPrice Returns the Last Traded Price.
LastQuantity Returns the Last Quantity.
BuyQuantity Returns the Buy Quantity.
SellQuantity Returns the Sell Quantity.
TotalBuyQuantity Returns the Total Buy Quantity.
TotalSellQuantity Returns the Total Sell Quantity.
OpenInterest Returns the Open Interest.
Exchange Returns the Exchange.
ExchangeType Returns the Exchange Type.
ScripCode Returns the ScripCode.
UpperCircuitLimit Returns the Upper Circuit Limit.
LowerCircuitLimit Returns the Lower Circuit Limit.
MktLot Returns the MktLot.

 

REQUEST:

  
                      
                      

curl --location --request POST 'https://Openapi.5paisa.com/VendorsAPI/Service1.svc/V1/MarketDepth' \
--header 'Authorization: Bearer null' \
--header 'Content-Type: application/json' \
--data-raw '{
    "head": {
        "key": "{Your Vendor/User Key}"
    },
    "body": {
        "ClientCode": "null",
        "Count": "1",
        "Data": [
            {
                "Exchange": "N",
                "ExchangeType": "C",
                "Symbol": "RELIANCE"
            },
            {
                "Exchange": "N",
                "ExchangeType": "D",
                "Symbol": "BANKNIFTY 31 Mar 2022 CE 35600.00"
            }
        ]
    }
}'

REQUEST:

                      
                        

a=[{"Exchange":"N","ExchangeType":"C","Symbol":"RELIANCE"},
   {"Exchange":"N","ExchangeType":"D","Symbol":"BANKNIFTY 31 Mar 2022 CE 35600.00"},
   ]
print(client.fetch_market_depth_by_symbol(a))

REQUEST:

                      
                        
                      
                    

Market Status

Response Attributes

Head

Name Desc
Status 0 for success

In case of non zero code, refer following field for error description
StatusDescription Error description incase of non zero status or "Success".

 

MarketStatusList

Name Desc
Exch Returns the Exchange.
ExchType Returns the ExchangeType.
ExchDescription Returns the information of Segment.
MarketStatus Returns the Market Status (Open or Close)

REQUEST:

  
                      
                      

REQUEST:




curl --location --request POST 'https://Openapi.5paisa.com/VendorsAPI/Service1.svc/MarketStatus' \
--header 'Authorization: bearer access_token' \
--header 'Content-Type: application/json' \
--data-raw '{
    "head": {
        "key": "<Your Key>"
    },
    "body": {
        "ClientCode": "<Your Client Code>"
    }
}'

REQUEST:

                      
                        


client.get_market_status()


REQUEST:

                      
                        


client.getMarketStatus().then((Response)=>{
    console.log(Response)
}).catch((err)=>{
    console.log(err)
})


Trading IDEAs

This API in response will give trading suggestions and ideas that can we used to take trade algorithmically. This API will only give trades if you have an active Ultra Trader Pack activated.
As shown in the sample response, we get suggestions in two categories.
1. ActionableBuys
2. CurrentTrades
The response will be a list of idea’s that can be taken as per choice. Data points present are sufficient to take real-time trades as and when new Idea is generated and shared.
Request Body
Field Name Description Data Type Validation Sample Value
ClientCode
This the client code of particular client
String
Cannot be empty
Dummy

REQUEST:

  
                      
                      

REQUEST:




curl --location --request POST 'https://Openapi.5paisa.com/VendorsAPI/Service1.svc/TraderIDEAs' \
--header 'Authorization: bearer abc' \
--header 'Content-Type: application/json' \
--header 'Cookie: 5paisacookie=taa4m4za1azcwryekinvf2us; NSC_JOh0em50e1pajl5b5jvyafempnkehc3=ffffffffaf103e0c45525d5f4f58455e445a4a423660' \
--data-raw '{
    "head": {
        "key": "{Your Vendor/User Key}"
    },
    "body": {
        "ClientCode": "{Your Client Code}"
    }
}'


REQUEST:

                      
                        

REQUEST:




#To get actionable buy trades use:-
print(Client.get_buy())


#To get list of current trades use:-
print(Client.get_trade())




REQUEST:

                      
                        

REQUEST:




client.ideas_trade().then((positions) => {
        console.log(positions)
    }).catch((err) => {
        console.log(err)
    });




Encryption