### Install 5paisa SDK Source: https://context7.com/openapi-5p/py5paisa/llms.txt Use pip to install the library. ```sh pip install py5paisa ``` -------------------------------- ### Set up local development environment Source: https://github.com/openapi-5p/py5paisa/blob/master/CONTRIBUTING.rst Commands to create a virtual environment and install the package in development mode. ```shell $ mkvirtualenv py5paisa $ cd py5paisa/ $ python setup.py develop ``` -------------------------------- ### Start Streaming Data via Web Socket Source: https://github.com/openapi-5p/py5paisa/blob/master/docs/usage/websocket.md Initiates the data streaming process after setting up subscriptions. Pass the dictionary obtained from subscription requests. ```python client.Streming_data(dict1) # Note : Pass Dictionary in Parameter Field ``` -------------------------------- ### Get Market Status Source: https://github.com/openapi-5p/py5paisa/blob/master/README.md Fetches the current market status. ```python print(client.get_market_status()) ``` -------------------------------- ### Fetch Market Feed Data Source: https://github.com/openapi-5p/py5paisa/blob/master/docs/usage/mf.md Use this method to fetch live market data for specified instruments. Ensure the symbol format matches the example, including expiry, strike price, and option type for options contracts. ```python # 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_) ``` -------------------------------- ### Fetch Full Market Snapshot Source: https://github.com/openapi-5p/py5paisa/blob/master/README.md Get a snapshot of the full market data for a list of instruments. Each instrument can be specified by 'ScripCode' or 'ScripData'. ```python a=[{"Exchange":"N","ExchangeType":"C","ScripCode":"2885"}, {"Exchange":"N","ExchangeType":"C","ScripData":"ITC_EQ"}, ] print(client.fetch_market_snapshot(a)) ``` -------------------------------- ### Fetch Trade Information Source: https://context7.com/openapi-5p/py5paisa/llms.txt Gets detailed execution information for a specific order. ```python req_list = [ { "Exch": "N", "ExchType": "C", "ScripCode": 20374, "ExchOrderID": "1000000015310807" } ] response = client.fetch_trade_info(req_list) print(response) ``` -------------------------------- ### Fetch User Holdings Source: https://github.com/openapi-5p/py5paisa/blob/master/docs/usage/info.md Call this method to retrieve the user's current holdings. No specific setup is required beyond initializing the client. ```python # Fetches holdings client.holdings() ``` -------------------------------- ### Retrieve Order Book Source: https://context7.com/openapi-5p/py5paisa/llms.txt Get a list of all orders placed during the session. ```python order_book = client.order_book() print(order_book) # Returns: [{'ExchOrderID': '1100000017861430', 'Status': 'Executed', 'ScripCode': 1660, ...}, ...] ``` -------------------------------- ### Get Option Chain Data Source: https://github.com/openapi-5p/py5paisa/blob/master/README.md Retrieve the option chain for a given exchange and symbol. First, get the expiry timestamp using `get_expiry`, then pass it to `get_option_chain`. ```python client.get_expiry("N","NIFTY") # Returns list of all active expiries # client.get_option_chain("N","NIFTY",) client.get_option_chain("N","NIFTY",1647507600000) ``` -------------------------------- ### Retrieve Trade Book Source: https://context7.com/openapi-5p/py5paisa/llms.txt Get details of all executed trades. ```python tradebook = client.get_tradebook() print(tradebook) ``` -------------------------------- ### Get Option Chain Data Source: https://context7.com/openapi-5p/py5paisa/llms.txt Retrieves option chain data for a specific symbol and expiry. ```python # Get all active expiries for a symbol expiries = client.get_expiry("N", "NIFTY") print(expiries) # Returns: {'Expiry': [1647507600000, 1648112400000, ...]} # Get option chain for specific expiry (timestamp in milliseconds) option_chain = client.get_option_chain("N", "NIFTY", 1647507600000) print(option_chain) # Returns: {'Options': [{'StrikePrice': 17000, 'CE': {...}, 'PE': {...}}, ...]} ``` -------------------------------- ### Retrieve Account Holdings Source: https://context7.com/openapi-5p/py5paisa/llms.txt Get a list of current holdings including quantity and average price. ```python holdings = client.holdings() print(holdings) # Returns list of dicts with holding details: # [{'ScripCode': 1660, 'ScripName': 'ITC', 'Quantity': 100, 'AvgRate': 450.50, ...}, ...] ``` -------------------------------- ### Initialize Strategy Module with Python Source: https://context7.com/openapi-5p/py5paisa/llms.txt Set up the strategy module for automated multi-leg option strategies. Initialization can be done using a request token or TOTP and PIN. ```python from py5paisa.strategy import strategies cred = { "APP_NAME": "YOUR_APP_NAME", "APP_SOURCE": "YOUR_APP_SOURCE", "USER_ID": "YOUR_USER_ID", "PASSWORD": "YOUR_PASSWORD", "USER_KEY": "YOUR_USER_KEY", "ENCRYPTION_KEY": "YOUR_ENCRYPTION_KEY" } # Initialize with request token strategy = strategies(cred=cred, request_token="your_request_token") # Or with TOTP strategy = strategies( client_code="your_client_code", totp="123456", pin="1234", cred=cred ) ``` -------------------------------- ### Clone the repository Source: https://github.com/openapi-5p/py5paisa/blob/master/CONTRIBUTING.rst Initial step to obtain a local copy of the project. ```shell $ git clone git@github.com:your_name_here/py5paisa.git ``` -------------------------------- ### GET /fetch_order_status Source: https://context7.com/openapi-5p/py5paisa/llms.txt Retrieves the current status of specific orders. ```APIDOC ## GET /fetch_order_status ### Description Fetches the current status of orders based on a list of exchange order IDs. ### Method GET ### Parameters #### Request Body - **req_list** (array) - Required - List of objects containing Exch and RemoteOrderID. ### Response #### Success Response (200) - **OrdStatusResLst** (array) - List of order status objects including ExchOrderID and Status. ``` -------------------------------- ### Configure API Keys and Authenticate Source: https://github.com/openapi-5p/py5paisa/blob/master/README.md Configure your API credentials and authenticate using OAuth. Ensure your credentials are correct and obtain an access token within 30 seconds of receiving the response token. ```python 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" } #This function will automatically take care of generating and sending access token for all your API's client = FivePaisaClient(cred=cred) # OAUTH Approach # First get a token by logging in to -> https://dev-openapi.5paisa.com/WebVendorLogin/VLogin/Index?VendorKey=&ResponseURL= # VendorKey is UesrKey for individuals user # for e.g. you can use ResponseURL as https://www.5paisa.com/technology/developer-apis # Pass the token received in the response url after successful login to get an access token (this also sets the token for all the APIs you use)- # Please note that you need to copy the request token from URL and paste in this code and start the code within 30s. client.get_oauth_session('Your Response Token') After successful authentication, you should get a `Logged in!!` message in console #Function to fetch access token after successful login print(client.get_access_token()) #Login with Access Token client.set_access_token('accessToken','clientCode') ``` -------------------------------- ### Get Market Status Source: https://context7.com/openapi-5p/py5paisa/llms.txt Checks the current operational status of the exchange. ```python status = client.get_market_status() print(status) # Returns: [{'Exchange': 'NSE', 'Status': 'Open', ...}] ``` -------------------------------- ### Deploy the project Source: https://github.com/openapi-5p/py5paisa/blob/master/CONTRIBUTING.rst Commands for maintainers to bump the version and push tags for deployment. ```shell $ bump2version patch # possible: major / minor / patch $ git push $ git push --tags ``` -------------------------------- ### Import Strategy Package Source: https://github.com/openapi-5p/py5paisa/blob/master/README.md Initializes the strategy module for use. ```python #Import strategy package from py5paisa.strategy import * ``` -------------------------------- ### GET /historical_data Source: https://context7.com/openapi-5p/py5paisa/llms.txt Retrieves historical OHLCV candlestick data for technical analysis. ```APIDOC ## GET /historical_data ### Description Fetches historical candlestick data for a specific scrip over a defined time range. ### Method GET ### Parameters #### Query Parameters - **Exchange** (string) - Required - Exchange code - **ExchangeType** (string) - Required - Exchange type - **ScripCode** (integer) - Required - Scrip code - **TimeFrame** (string) - Required - '1m', '5m', '10m', '15m', '30m', '60m', '1d' - **FromDate** (string) - Required - Start date (YYYY-MM-DD) - **ToDate** (string) - Required - End date (YYYY-MM-DD) ### Response #### Success Response (200) - **df** (dataframe) - Historical OHLCV data including Datetime, Open, High, Low, Close, and Volume. ``` -------------------------------- ### Initialize Strategy Object Source: https://github.com/openapi-5p/py5paisa/blob/master/README.md Configures credentials and authenticates the strategy object using either legacy or token-based approaches. ```python #Create an Object:- 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" } --Old approach strategy=strategies(user="random_email@xyz.com", passw="password", dob="YYYYMMDD",cred=cred) --New Approach strategy=strategies(cred=cred,request_token="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1bmlxdWVfbmFtZSI6IjUwMDUyNzcwIiwicm9sZSI6ImdpUUlvYXR5R2NYQUR3eFYwNXVXSGlPVzJRT1dOTGNzIiwibmJmIjoxNjY3ODMwODczLCJleHAiOjE2Njc4MzA5MDMsImlhdCI6MTY2NzgzMDg3M30.iP_FZtFy-nj6QeRd0sEhaKS-jr-wu-pCwtcdYCGPeO4") ``` -------------------------------- ### Place a standard order Source: https://github.com/openapi-5p/py5paisa/blob/master/docs/usage/place.md Initializes an Order object and submits it using the client instance. ```python from py5paisa.order import Order, OrderType, Exchange test_order = Order(order_type='B',exchange='N',exchange_segment='C', scrip_code=1660, quantity=1, price=205,is_intraday=True,atmarket=False) client.place_order(test_order) ``` -------------------------------- ### Configure API Keys for Py5paisa Source: https://github.com/openapi-5p/py5paisa/blob/master/docs/usage/auth.md Store your API credentials in a `keys.conf` file. Ensure this file is in the same directory as your Python script. ```conf [KEYS] APP_NAME=YOUR_APP_NAME_HERE APP_SOURCE=YOUR_APP_SOURCE_HERE USER_ID=YOUR_USER_ID_HERE PASSWORD=YOUR_PASSWORD_HERE USER_KEY=YOUR_USER_KEY_HERE ENCRYPTION_KEY=YOUR_ENCRYPTION_KEY_HERE ``` -------------------------------- ### Get Trade History Source: https://context7.com/openapi-5p/py5paisa/llms.txt Retrieves the complete trade history for a given exchange order ID. ```python response = client.get_trade_history("1100000017861430") print(response) ``` -------------------------------- ### Manage Order Baskets with Python Source: https://context7.com/openapi-5p/py5paisa/llms.txt Use this to create, manage, and execute orders within baskets for batch processing. Ensure the client object is initialized before use. ```python from py5paisa.order import Basket_order # Create new basket response = client.create_basket("My Trading Basket") print(response) # Returns: {'BasketID': 12345, ...} # Get all baskets baskets = client.get_basket() print(baskets) # Rename basket client.rename_basket("Renamed Basket", basket_id=12345) # Clone basket client.clone_basket(basket_id=12345) # Delete baskets delete_list = [{"BasketID": "12345"}, {"BasketID": "12346"}] client.delete_basket(delete_list) # Add order to basket basket_list = [{"BasketID": "12345"}] order = Basket_order( Exchange="N", ExchangeType="C", Price=23000, OrderType="BUY", Qty=1, ScripCode="1660", DelvIntra="I" # 'I' for Intraday, 'D' for Delivery ) client.add_basket_order(order, basket_list) # Get orders in basket orders = client.get_order_in_basket(basket_id=12345) print(orders) # Execute all orders in basket client.execute_basket(basket_id=12345) ``` -------------------------------- ### Run tests and linting Source: https://github.com/openapi-5p/py5paisa/blob/master/CONTRIBUTING.rst Commands to verify code quality and run test suites. ```shell $ flake8 py5paisa tests $ python setup.py test or pytest $ tox ``` -------------------------------- ### Login to Py5paisa Source: https://github.com/openapi-5p/py5paisa/blob/master/docs/usage/auth.md Instantiate the `FivePaisaClient` with your email, password, and date of birth, then call the `login()` method to authenticate. ```python from py5paisa import FivePaisaClient client = FivePaisaClient(email="random_email@xyz.com", passwd="password", dob="YYYYMMDD") client.login() ``` -------------------------------- ### Authenticate with OAuth Source: https://context7.com/openapi-5p/py5paisa/llms.txt Initialize the client and authenticate using a request token obtained from the redirect URL. ```python from py5paisa import FivePaisaClient # Configure API credentials cred = { "APP_NAME": "YOUR_APP_NAME", "APP_SOURCE": "YOUR_APP_SOURCE", "USER_ID": "YOUR_USER_ID", "PASSWORD": "YOUR_PASSWORD", "USER_KEY": "YOUR_USER_KEY", "ENCRYPTION_KEY": "YOUR_ENCRYPTION_KEY" } # Initialize client client = FivePaisaClient(cred=cred) # Get OAuth session using request token from redirect URL # First login at: https://dev-openapi.5paisa.com/WebVendorLogin/VLogin/Index?VendorKey=&ResponseURL= # Copy the request token from the response URL within 30 seconds client.get_oauth_session('your_response_token_here') # Output: Logged in!! # Retrieve access token for external use access_token = client.get_access_token() print(access_token) # Alternative: Login with existing access token client.set_access_token('existing_access_token', 'client_code') ``` -------------------------------- ### Place a Trading Order Source: https://github.com/openapi-5p/py5paisa/blob/master/README.rst Constructs an Order object with specific exchange and trade parameters, then submits it via the client. ```python # This is an indicative order. from py5paisa.order import Order, OrderType, Exchange, ExchangeType ITC_order = Order(order_for=OrderType.PLACE, exchange=Exchange.BSE, exchange_type=ExchangeType.CASH, price=0, order_id=0, order_type="BUY", quantity=10, scrip_code=500875, atmarket=True, remote_order_id="23324", exch_order_id="0", disqty=10, stoploss_price=0, is_stoploss_order=False, ioc_order=False, is_intraday=False, is_vtd=False, vtd="", ahplaced="Y", public_ip="45.112.149.104", order_validity=0, traded_qty=0) print(client.place_order(ITC_order)) ``` -------------------------------- ### Subscribe to Live Market Depth (Depth 20) Source: https://github.com/openapi-5p/py5paisa/blob/master/README.md Use this method to subscribe to real-time market depth data for a specific instrument. The 'instruments' parameter takes a list of instrument tokens. ```python a={ "method":"subscribe", "operation":"20depth", "instruments":["NC2885"] } print(client.socket_20_depth(a)) def on_message(ws, message): print(message) client.receive_data(on_message) ``` -------------------------------- ### Place an Order Source: https://github.com/openapi-5p/py5paisa/blob/master/README.md Place various types of orders including market orders, SL orders, and derivative orders. Use price = 0 for market orders and IsIntraday=True for intraday orders. Refer to the provided documentation link for detailed parameters. ```python # Note: This is an indicative order. from py5paisa.order import Order, OrderType, Exchange #You can pass scripdata either you can pass scripcode also. # please use price = 0 for market Order #use IsIntraday= true for intraday orders #Using Scrip Data :- #Using Scrip Code :- client.place_order(OrderType='B',Exchange='N',ExchangeType='C', ScripCode = 1660, Qty=1, Price=260) #Sample For SL order (for order to be treated as SL order just pass StopLossPrice) client.place_order(OrderType='B',Exchange='N',ExchangeType='C', ScripCode = 1660, Qty=1, Price=350, IsIntraday=False, StopLossPrice=345) #Derivative Order client.place_order(OrderType='B',Exchange='N',ExchangeType='D', ScripCode = 57633, Qty=50, Price=1.5) Please refer below documentation link for paramaters to be passed in cleint.place_order function https://www.5paisa.com/developerapi/order-request-place-order ``` -------------------------------- ### Run a subset of tests Source: https://github.com/openapi-5p/py5paisa/blob/master/CONTRIBUTING.rst Command to execute specific tests using the unittest module. ```shell $ python -m unittest tests.test_py5paisa ``` -------------------------------- ### Place Bulk Orders Source: https://context7.com/openapi-5p/py5paisa/llms.txt Execute multiple orders in a single batch request using a list of order dictionaries. ```python bulk_order = [ { "Exchange": "N", "ExchangeType": "C", "ScripCode": 0, "ScripData": "ITC_EQ", "Price": "440", "OrderType": "Buy", "Qty": 1, "DisQty": "0", "StopLossPrice": "0", "IsIntraday": True, "iOrderValidity": "0", "RemoteOrderID": "50000091_220620" }, { "Exchange": "N", "ExchangeType": "C", "ScripCode": 0, "ScripData": "IDEA_EQ", "Price": "15", "OrderType": "Buy", "Qty": 1, "DisQty": "0", "StopLossPrice": "0", "IsIntraday": True, "iOrderValidity": "0", "RemoteOrderID": "50000091_220620" } ] response = client.place_order_bulk(OrderList=bulk_order) print(response) ``` -------------------------------- ### Fetch Market Snapshot Source: https://context7.com/openapi-5p/py5paisa/llms.txt Retrieves comprehensive market data for multiple instruments. ```python req_list = [ {"Exchange": "N", "ExchangeType": "C", "ScripCode": "2885"}, {"Exchange": "N", "ExchangeType": "C", "ScripData": "ITC_EQ"} ] response = client.fetch_market_snapshot(req_list) print(response) ``` -------------------------------- ### Place Regular Orders Source: https://context7.com/openapi-5p/py5paisa/llms.txt Use these methods to place market, limit, or derivative orders. Set Price to 0 for market orders and specify ExchangeType for derivatives. ```python # Market order for equity (Price=0 for market order) response = client.place_order( OrderType='B', # 'B' for Buy, 'S' for Sell Exchange='N', # 'N' for NSE, 'B' for BSE, 'M' for MCX ExchangeType='C', # 'C' for Cash, 'D' for Derivative, 'U' for Currency ScripCode=1660, # Scrip code from scrip master Qty=1, Price=0, # 0 for market order IsIntraday=False # True for intraday, False for delivery ) print(response) # Output: {'Message': 'Success', 'ExchOrderID': '1100000017861430', ...} # Limit order with stop loss response = client.place_order( OrderType='B', Exchange='N', ExchangeType='C', ScripCode=1660, Qty=1, Price=350, IsIntraday=False, StopLossPrice=345 # Adding SL makes it a stop-loss order ) # Derivative order (F&O) response = client.place_order( OrderType='B', Exchange='N', ExchangeType='D', # 'D' for derivatives ScripCode=57633, # Options/Futures scrip code Qty=50, # Lot size Price=1.5 ) ``` -------------------------------- ### Place Bulk Orders Source: https://github.com/openapi-5p/py5paisa/blob/master/README.md Submit multiple orders simultaneously using the `place_order_bulk` method. Each order in the `OrderList` must specify exchange, type, scrip details, price, order type, quantity, and other relevant parameters. ```python bulk_order=[ { "Exchange":"N", "ExchangeType":"C", "ScripCode":0, "ScripData":"ITC_EQ", "Price": "440", "OrderType": "Buy", "Qty": 1, "DisQty": "0", "StopLossPrice": "0", "IsIntraday": True, "iOrderValidity": "0", "RemoteOrderID":"50000091_220620" },{ "Exchange":"N", "ExchangeType":"C", "ScripCode":0, "ScripData":"IDEA_EQ", "Price": "15", "OrderType": "Buy", "Qty": 1, "DisQty": "0", "StopLossPrice": "0", "IsIntraday": True, "iOrderValidity": "0", "RemoteOrderID":"50000091_220620" } ] client.place_order_bulk(OrderList=bulk_order) ``` -------------------------------- ### Create a development branch Source: https://github.com/openapi-5p/py5paisa/blob/master/CONTRIBUTING.rst Command to create a new branch for implementing changes. ```shell $ git checkout -b name-of-your-bugfix-or-feature ``` -------------------------------- ### POST /place_order Source: https://context7.com/openapi-5p/py5paisa/llms.txt Places a regular buy or sell order for equity or derivatives. ```APIDOC ## POST /place_order ### Description Place buy/sell orders for equity and derivatives with market or limit pricing. ### Parameters #### Request Body - **OrderType** (string) - Required - 'B' for Buy, 'S' for Sell - **Exchange** (string) - Required - 'N' for NSE, 'B' for BSE, 'M' for MCX - **ExchangeType** (string) - Required - 'C' for Cash, 'D' for Derivative, 'U' for Currency - **ScripCode** (integer) - Required - Scrip code from scrip master - **Qty** (integer) - Required - Order quantity - **Price** (float) - Required - Price (0 for market order) - **IsIntraday** (boolean) - Required - True for intraday, False for delivery - **StopLossPrice** (float) - Optional - Adding SL makes it a stop-loss order - **AHPlaced** (string) - Optional - 'Y' for After Hours placement ### Request Example { "OrderType": "B", "Exchange": "N", "ExchangeType": "C", "ScripCode": 1660, "Qty": 1, "Price": 0, "IsIntraday": false } ### Response #### Success Response (200) - **Message** (string) - Success status - **ExchOrderID** (string) - The exchange order ID ``` -------------------------------- ### Place Bracket and Cover Orders Source: https://context7.com/openapi-5p/py5paisa/llms.txt Use these specialized order types to include automatic stop-loss and profit target legs. ```python response = client.bo_order( OrderType='B', # Buy or Sell Exchange='N', ExchangeType='C', # 'D' for F&O ScripCode=1660, Qty=1, LimitPrice=330, # Entry price TargetPrice=345, # Profit target StopLossPrice=320, # Stop loss trigger LimitPriceForSL=319, # SL limit price TrailingSL=1.5 # Trailing stop loss ) print(response) response = client.cover_order( OrderType='B', Exchange='N', ExchangeType='C', ScripCode=1660, Qty=1, LimitPrice=330, StopLossPrice=320, TrailingSL=1.5 ) print(response) ``` -------------------------------- ### Full Market Snapshot Source: https://github.com/openapi-5p/py5paisa/blob/master/README.md Fetches a full market snapshot for a list of instruments. ```APIDOC ## POST /fetch_market_snapshot ### Description Retrieves a full market snapshot for a provided list of instruments. ### Method POST ### Request Body - **OrderList** (array) - Required - List of objects containing Exchange, ExchangeType, and either ScripCode or ScripData ``` -------------------------------- ### Square Off All Orders Source: https://github.com/openapi-5p/py5paisa/blob/master/README.md Initiate a square-off for all open positions. ```python client.squareoff_all() ``` -------------------------------- ### Short Strangle Strategy with Python Source: https://context7.com/openapi-5p/py5paisa/llms.txt Implement a short strangle strategy by selling Out-of-the-Money Call and Put options at different strike prices. Strikes are provided as a list: [put_strike, call_strike]. ```python # Strikes as list: [put_strike, call_strike] strategy.short_strangle( "banknifty", ["35300", "37000"], # [PE strike, CE strike] "50", "20210610", "D" ) ``` -------------------------------- ### Short Straddle Strategy with Python Source: https://context7.com/openapi-5p/py5paisa/llms.txt Implement a short straddle strategy by selling both Call and Put options at the same strike price. Use 'I' for Intraday or 'D' for Delivery order types. ```python # short_straddle(symbol, strike, qty, expiry, order_type, tag) # Order type: 'I' for Intraday, 'D' for Delivery strategy.short_straddle( "banknifty", "37000", "50", "20210610", "I", tag="my_straddle_1" ) ``` -------------------------------- ### Execute Option Strategies Source: https://github.com/openapi-5p/py5paisa/blob/master/README.md Executes various pre-defined multi-leg option strategies at market price. ```python #short_straddle(,,,,) strategy.short_straddle("banknifty",'37000','50','20210610','I',tag='') #Using tag is optional ``` ```python #short_strangle(,,,,) strategy.short_strangle("banknifty",['35300','37000'],'50','20210610','D') ``` ```python #long_straddle(,,,,) strategy.long_straddle("banknifty",'37000','50','20210610','I',tag='') #Using tag is optional ``` ```python #long_strangle(,,,,) strategy.long_strangle("banknifty",['35300','37000'],'50','20210610','D') ``` ```python #iron_condor(,,,,,) strategy.iron_condor("NIFTY",["15000","15200"],["15100","15150"],"75","20210603","I") ``` ```python #iron_fly(,,,,,) strategy.iron_fly("NIFTY",["15000","15200"],"15100","75","20210610","I",tag='') #Using tag is optional ``` ```python #call_calendar(,,,,) strategy.call_calendar("nifty",'15600','75',['20210603','20210610'],'I') ``` ```python #put_calendar(,,,,) strategy.put_calendar("nifty",'15600','75',['20210603','20210610'],'I') ``` ```python #call_ladder(,,,,,) strategy.call_ladder("NIFTY","15100",["15300","15400"],"75","20210610","I") ``` ```python #put_ladder(,,,,,) strategy.put_ladder("NIFTY","15000",["14800","14500"],"75","20210610","I",tag='') #Using tag is optional ``` ```python #ladder(,,,,,) strategy.ladder("sbin",["400","420"],["350","370","450","500"],"1500","20210729","D") ``` -------------------------------- ### Commit and push changes Source: https://github.com/openapi-5p/py5paisa/blob/master/CONTRIBUTING.rst Standard git workflow to stage, commit, and push local changes. ```shell $ git add . $ git commit -m "Your detailed description of your changes." $ git push origin name-of-your-bugfix-or-feature ``` -------------------------------- ### Iron Condor Strategy with Python Source: https://context7.com/openapi-5p/py5paisa/llms.txt Create an Iron Condor strategy for a range-bound market with limited risk and reward. Define buy strikes, sell strikes, quantity, expiry, and order type. ```python # iron_condor(symbol, buy_strikes, sell_strikes, qty, expiry, order_type) strategy.iron_condor( "NIFTY", ["15000", "15200"], # Buy strikes [PE, CE] ["15100", "15150"], # Sell strikes [PE, CE] "75", "20210603", "I" ) ``` -------------------------------- ### Fetch User Positions Source: https://github.com/openapi-5p/py5paisa/blob/master/docs/usage/info.md Call this method to retrieve the user's open positions. The client must be authenticated. ```python # Fetches positions client.positions() ``` -------------------------------- ### Subscribe to Multiple ScripCodes via Web Socket Source: https://github.com/openapi-5p/py5paisa/blob/master/docs/usage/websocket.md Subscribe to real-time data for multiple stock symbols simultaneously. This is efficient for tracking several instruments. ```python req_list=[ { "Exch":"N","ExchType":"C","ScripCode":1660}, { "Exch":"N","ExchType":"D","ScripCode":61211} ] dict1=client.Request_Feed('mf','s',req_list) ``` -------------------------------- ### Execute Ladder Strategies Source: https://context7.com/openapi-5p/py5paisa/llms.txt Methods for creating directional call, put, and generic ladder spreads with multiple legs. ```python # Call Ladder: Buy 1 ATM call, Sell 2 OTM calls strategy.call_ladder( "NIFTY", "15100", # Buy strike ["15300", "15400"], # Sell strikes "75", "20210610", "I" ) # Put Ladder: Buy 1 ATM put, Sell 2 OTM puts strategy.put_ladder( "NIFTY", "15000", # Buy strike ["14800", "14500"], # Sell strikes "75", "20210610", "I", tag="put_ladder_1" ) # Generic Ladder: Multiple buy and sell legs strategy.ladder( "sbin", ["400", "420"], # Buy strikes ["350", "370", "450", "500"], # Sell strikes "1500", "20210729", "D" ) ``` -------------------------------- ### POST /place_order_bulk Source: https://context7.com/openapi-5p/py5paisa/llms.txt Places multiple orders simultaneously for efficient batch processing. ```APIDOC ## POST /place_order_bulk ### Description Place multiple orders simultaneously for efficient batch processing. ### Parameters #### Request Body - **OrderList** (array) - Required - List of order objects containing Exchange, ExchangeType, ScripCode, ScripData, Price, OrderType, Qty, DisQty, StopLossPrice, IsIntraday, iOrderValidity, and RemoteOrderID. ### Request Example { "OrderList": [ { "Exchange": "N", "ExchangeType": "C", "ScripCode": 0, "ScripData": "ITC_EQ", "Price": "440", "OrderType": "Buy", "Qty": 1 } ] } ``` -------------------------------- ### Place a stop-loss order Source: https://github.com/openapi-5p/py5paisa/blob/master/docs/usage/place.md Requires setting is_stoploss_order to True and providing a stoploss_price. Trigger price constraints apply based on whether the order is a Buy or Sell. ```python from py5paisa.order import Order, OrderType test_order = Order(order_type='B',exchange='N',exchange_segment='C', scrip_code=1660, quantity=1, price=208,is_intraday=True,atmarket=False, is_stoploss_order=True, stoploss_price=207.5) ``` -------------------------------- ### Retrieve User Account Information Source: https://github.com/openapi-5p/py5paisa/blob/master/README.rst Fetches various account details such as holdings, margin, positions, and the order book using the authenticated client. ```python # Fetches holdings client.holdings() # Fetches margin client.margin() # Fetches positions client.positions() # Fetches the order book of the client client.order_book() ``` -------------------------------- ### Live Market Feed Streaming (Websocket) Source: https://github.com/openapi-5p/py5paisa/blob/master/README.md Connect to a websocket to receive live market data feeds for specified scripts. ```APIDOC ## Live Market Feed Streaming API ### Description Connects to a websocket to stream live market data. Requires ScripCode for subscriptions. ### Method Websocket Connection ### Endpoint (Websocket endpoint details not provided in the source text) ### Parameters #### Request Data for Feed Subscription - **Market Feed Type**: 'mf' (Market Feed), 'md' (Market Depth), 'i' (Indices), 'oi' (Open Interest) - **Action**: 's' (Subscribe), 'u' (Unsubscribe) - **Scrip List**: Array of script objects. - **Exch** (string) - Required - Exchange code (e.g., 'N' for NSE). - **ExchType** (string) - Required - Exchange type (e.g., 'C' for Cash). - **ScripCode** (integer) - Required - The unique code for the security. ### Request Example ```python 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) ``` ### Response (Live data is streamed via the websocket connection. Specific response formats are not detailed in the source text.) ``` -------------------------------- ### Fetch User Margin Source: https://github.com/openapi-5p/py5paisa/blob/master/docs/usage/info.md Call this method to retrieve the user's margin details. Ensure the client is properly initialized. ```python # Fetches margin client.margin() ``` -------------------------------- ### Fetch and Query Scrip Data Source: https://context7.com/openapi-5p/py5paisa/llms.txt Retrieve the complete scrip master or query specific instruments using exchange and symbol details. ```python # Fetch entire scrip master (cached after first call) scrips = client.get_scrips() print(scrips.head()) # Returns DataFrame with columns: Exch, ExchType, ScripCode, SymbolRoot, StrikeRate, ScripType, Expiry, etc. # Query scrip data for cash stocks # Parameters: exchange, exchangetype, symbol, strike, type, expiry record = client.query_scrips("N", "C", "ITC", "0", "XX", "") print(record) # Returns matching rows from scrip master # Query for Options record = client.query_scrips("N", "D", "NIFTY", "22300", "CE", "2024-04-25") # Query for Futures (type="XX" for futures, strike="0") record = client.query_scrips("N", "D", "INFY", "0", "XX", "2024-04-25") ``` -------------------------------- ### Iron Fly Strategy with Python Source: https://context7.com/openapi-5p/py5paisa/llms.txt Implement an Iron Butterfly strategy by selling an ATM straddle and buying an OTM strangle to define risk. Specify buy strikes, sell strike, quantity, expiry, and order type. ```python # iron_fly(symbol, buy_strikes, sell_strike, qty, expiry, order_type) strategy.iron_fly( "NIFTY", ["15000", "15200"], # Buy strikes [PE, CE] "15100", # Sell strike (ATM) "75", "20210610", "I", tag="iron_fly_1" ) ``` -------------------------------- ### Place Cover Order Source: https://github.com/openapi-5p/py5paisa/blob/master/README.md Place a cover order with specified quantities, prices, and stop-loss/target levels. For F&O segment, set `ExchType='D'`. ```python client.cover_order(OrderType='B',Exchange='N',ExchangeType='C', ScripCode = 1660, Qty=1, LimitPrice=330,StopLossPrice=320,TrailingSL=1.5) ``` -------------------------------- ### Fetch Market Feed Source: https://github.com/openapi-5p/py5paisa/blob/master/README.md Retrieve live market data for specified scrips. You can provide scrip data or scrip code. Use 'ITC_EQ' for scrip data or '2885' for scrip code. ```python #NOTE : ScripData and ScripCode you can find from new Scripmaster as mentioned above req_list_ = [{"Exch": "N", "ExchType": "C", "ScripData": "ITC_EQ"}] {"Exch": "N", "ExchType": "C", "ScripCode": "2885"}] print(client.fetch_market_feed_scrip(req_list_)) ``` -------------------------------- ### Place Bracket Order Source: https://github.com/openapi-5p/py5paisa/blob/master/README.md Place a bracket order with specified quantities, prices, and stop-loss/target levels. For F&O segment, set `ExchType='D'`. ```python client.bo_order(OrderType='B',Exchange='N',ExchangeType='C', ScripCode = 1660, Qty=1, LimitPrice=330,TargetPrice=345,StopLossPrice=320,LimitPriceForSL=319,TrailingSL=1.5) ``` -------------------------------- ### Place Bracket Order Source: https://github.com/openapi-5p/py5paisa/blob/master/docs/usage/bo.md Use this function to place a new bracket order. For cover orders, set LimitPriceProfitOrder to zero. ```python test_order=bo_co_order(scrip_code=1660,BuySell='B',Qty=1, LimitPriceInitialOrder=204,TriggerPriceInitialOrder=0,LimitPriceProfitOrder=208.0,TriggerPriceForSL=202,RequestType='P',AtMarket=False) client.bo_order(test_order) ``` -------------------------------- ### Subscribe to Single ScripCode via Web Socket Source: https://github.com/openapi-5p/py5paisa/blob/master/docs/usage/websocket.md Use this method to subscribe to real-time data for a single stock symbol. Ensure the 'client' object is initialized. ```python req_list=[ { "Exch":"N","ExchType":"C","ScripCode":1660}, ] dict1=client.Request_Feed('mf','s',req_list) ``` -------------------------------- ### Bracket Order Placement Source: https://github.com/openapi-5p/py5paisa/blob/master/README.md Place Bracket Orders (BO) with specified limit price, target price, and stop-loss price. ```APIDOC ## POST /api/orders/bo (Hypothetical Endpoint) ### Description Places a Bracket Order (BO). ### Method POST ### Endpoint /api/orders/bo ### Parameters #### Request Body - **OrderType** (string) - Required - Type of order ('B' for Buy, 'S' for Sell). - **Exchange** (string) - Required - Exchange code (e.g., 'N' for NSE, 'B' for BSE). - **ExchangeType** (string) - Required - Type of exchange (e.g., 'C' for Cash, 'D' for F&O). - **ScripCode** (integer) - Required - The unique code for the security. - **Qty** (integer) - Required - The quantity of the security. - **LimitPrice** (float) - Required - The limit price for the initial order. - **TargetPrice** (float) - Required - The target profit price. - **StopLossPrice** (float) - Required - The stop-loss price. - **LimitPriceForSL** (float) - Optional - The limit price for the stop-loss order. - **TrailingSL** (float) - Optional - The trailing stop-loss value. ### Request Example ```python client.bo_order(OrderType='B', Exchange='N', ExchangeType='C', ScripCode=1660, Qty=1, LimitPrice=330, TargetPrice=345, StopLossPrice=320, LimitPriceForSL=319, TrailingSL=1.5) ``` ### Response (Success response details not provided in the source text) ``` -------------------------------- ### Fetch User Information Source: https://github.com/openapi-5p/py5paisa/blob/master/README.md Retrieve various user-specific data including holdings, margin, positions, order book, and trade book. ```python # Fetches holdings client.holdings() # Fetches margin client.margin() # Fetches positions client.positions() # Fetches the order book of the client client.order_book() # Fetches Trade book client.get_tradebook() ``` -------------------------------- ### Long Straddle Strategy with Python Source: https://context7.com/openapi-5p/py5paisa/llms.txt Implement a long straddle strategy by buying both Call and Put options at the same strike price. Specify order type as 'I' for Intraday or 'D' for Delivery. ```python strategy.long_straddle( "banknifty", "37000", "50", "20210610", "I", tag="long_straddle_1" ) ``` -------------------------------- ### Square Off All Orders Source: https://github.com/openapi-5p/py5paisa/blob/master/README.md Initiate a square-off for all open positions. ```APIDOC ## POST /api/orders/squareoff/all (Hypothetical Endpoint) ### Description Closes all open positions. ### Method POST ### Endpoint /api/orders/squareoff/all ### Request Example ```python client.squareoff_all() ``` ### Response (Success response details not provided in the source text) ``` -------------------------------- ### Calendar Spreads Strategy with Python Source: https://context7.com/openapi-5p/py5paisa/llms.txt Execute time-based calendar spreads using different expiries. This includes Call Calendar (buy near-term, sell far-term) and Put Calendar strategies. ```python # Call Calendar: Buy near-term, Sell far-term # Expiry list: [buy_expiry, sell_expiry] strategy.call_calendar( "nifty", "15600", "75", ["20210603", "20210610"], "I" ) ``` ```python # Put Calendar strategy.put_calendar( "nifty", "15600", "75", ["20210603", "20210610"], "I" ) ``` -------------------------------- ### Long Strangle Strategy with Python Source: https://context7.com/openapi-5p/py5paisa/llms.txt Implement a long strangle strategy by buying Out-of-the-Money Call and Put options at different strike prices. The strikes should be provided in a list format: [put_strike, call_strike]. ```python strategy.long_strangle( "banknifty", ["35300", "37000"], "50", "20210610", "D" ) ``` -------------------------------- ### Retrieve Trading Positions Source: https://context7.com/openapi-5p/py5paisa/llms.txt Fetch current day or net positions for the account. ```python # Net positions positions = client.positions() print(positions) # Returns: [{'ScripCode': 1660, 'BuyQty': 10, 'SellQty': 0, 'NetQty': 10, ...}, ...] # Day positions only day_positions = client.positions_day() print(day_positions) ``` -------------------------------- ### Generate Financial Reports Source: https://context7.com/openapi-5p/py5paisa/llms.txt Retrieves tax and ledger reports for specified date ranges. ```python report = client.tax_report("2024-01-01", "2024-06-26") print(report) ``` ```python ledger = client.fetch_ledger("2024-01-01", "2024-06-26") print(ledger) ``` -------------------------------- ### Cover Order Placement Source: https://github.com/openapi-5p/py5paisa/blob/master/README.md Place Cover Orders with specified limit price and stop-loss price. ```APIDOC ## POST /api/orders/cover (Hypothetical Endpoint) ### Description Places a Cover Order. ### Method POST ### Endpoint /api/orders/cover ### Parameters #### Request Body - **OrderType** (string) - Required - Type of order ('B' for Buy, 'S' for Sell). - **Exchange** (string) - Required - Exchange code (e.g., 'N' for NSE, 'B' for BSE). - **ExchangeType** (string) - Required - Type of exchange (e.g., 'C' for Cash). - **ScripCode** (integer) - Required - The unique code for the security. - **Qty** (integer) - Required - The quantity of the security. - **LimitPrice** (float) - Required - The limit price for the initial order. - **StopLossPrice** (float) - Required - The stop-loss price. - **TrailingSL** (float) - Optional - The trailing stop-loss value. ### Request Example ```python client.cover_order(OrderType='B', Exchange='N', ExchangeType='C', ScripCode=1660, Qty=1, LimitPrice=330, StopLossPrice=320, TrailingSL=1.5) ``` ### Response (Success response details not provided in the source text) ``` -------------------------------- ### Bulk Order Placement Source: https://github.com/openapi-5p/py5paisa/blob/master/README.md Places multiple orders in a single request. ```APIDOC ## POST /place_order_bulk ### Description Executes a bulk order placement for a list of orders. ### Method POST ### Request Body - **OrderList** (array) - Required - List of order objects containing Exchange, ExchangeType, ScripCode, ScripData, Price, OrderType, Qty, DisQty, StopLossPrice, IsIntraday, iOrderValidity, and RemoteOrderID ```