diff --git a/.github/workflows/pythonpublish.yml b/.github/workflows/pythonpublish.yml index 5fdb9e42..e9df9e04 100644 --- a/.github/workflows/pythonpublish.yml +++ b/.github/workflows/pythonpublish.yml @@ -15,7 +15,7 @@ jobs: - name: Set up Python uses: actions/setup-python@v1 with: - python-version: '3.8.6' + python-version: '3.10.18' - name: Install dependencies run: | python -m pip install --upgrade pip diff --git a/README.md b/README.md index d5cc5118..f0339d7c 100644 --- a/README.md +++ b/README.md @@ -2,53 +2,115 @@ Python SDK for 5paisa APIs natively written in VB .NET +![PyPI](https://img.shields.io/pypi/v/py5paisa) +![GitHub Workflow Status (branch)](https://img.shields.io/github/workflow/status/5paisa/py5paisa/Publish%20package/master) + ![5paisa logo](./docs/images/5-paisa-img.jpg) #### Documentation -Read the docs hosted [here](https://5paisa.github.io/) +Read the docs hosted [here](https://www.5paisa.com/developerapi/overview) #### Features - Order placement, modification and cancellation - Fetching user info including holdings, positions, margin and order book. +- Fetching live market streaming. +- Placing, modifying and deleting Bracket Order. - Fetching order status and trade information. +- Getting live data streaming using websockets. ### Installation -`pip install pyp5aisa` +`pip install py5paisa` ### Usage #### Configuring API keys -Get your API keys from https://www.5paisa.com/developerapi/apikeys +Get your API keys from [here](https://xstream.5paisa.com/dashboard) -Configure these keys in a file named `keys.conf` in the same directory as your python script exists +Note:- We have deprecated the existing method which involved the use of login credentials. + Kindly go through this updated documentation of using Access token for API Access. -A sample `keys.conf` is given below: +#### Scrip codes reference: +```py +Note : Use these Links for getting scrip codes -```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 -``` +Scrip Master - Downaload ScripMaster [here](https://openapi.5paisa.com/VendorsAPI/Service1.svc/ScripMaster/segment/All) + +[API Documentation](https://xstream.5paisa.com/dev-docs/docFundamentals/scrip-master) + +#Fetch Scrip Codes + +scrips = client.get_scrips() +#Query Script Data Inputs sequence- exchange, exchangetype, symbol, strike, type, expiry -#### Authentication +#Strike to be 0 for cash stocks , Actual Strike for Derivatives +#type to be XX for Cash stocks and Futures, EQ for indices, CE/PE for Options + +#Fetch Scrip Data for Cash +record = client.query_scrips("N","C","ITC","0","XX","") +#Fetch Scrip Data for Options +record = client.query_scrips("N","D","NIFTY","22300","CE","2024-04-25") +#Fetch Scrip Data for Futures +record = client.query_scrips("N","C","INFY","0","XX","") +``` + +#### AUTHENTICATION USING OAUTH ```py 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') -client = FivePaisaClient(email="random_email@xyz.com", passwd="password", dob="YYYYMMDD") -client.login() ``` -After successful authentication, you should get a `Logged in!!` message +#### Market Feed + +```py +#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_)) + +``` +#### Market Status +```py +print(client.get_market_status()) +``` #### Fetching user info @@ -65,55 +127,430 @@ client.positions() # Fetches the order book of the client client.order_book() +# Fetches Trade book +client.get_tradebook() + ``` -Scrip codes reference: +#### Position Conversion + +```py +# Convert positions +# client.position_convertion(,,,,,,) +client.position_convertion("N","C","BPCL_EQ","B",5,"D","I") +``` -BSE: https://www.bseindia.com/ -NSE: https://nse-scrips.herokuapp.com/ #### Placing an order ```py # Note: This is an indicative order. -from py5paisa.order import Order, OrderType, Exchange, ExchangeType +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 -test_order = Order(order_type=OrderType.BUY, scrip_code=11111, quantity=10) +#Using Scrip Data :- -client.place_order(test_order) +#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 +``` +#### Placing offline orders (After Market Orders) + +By default all orders are normal orders, pass `AHPlaced=Y` to place offline orders. + +```py +client.place_order(OrderType='B',Exchange='N',ExchangeType='C', ScripCode = 1660, Qty=1, Price=325, AHPlaced="Y") ``` #### Modifying an order ```py -client.modify_order(exch_order_id="12345678", traded_qty=10, scrip_code=11111) +client.modify_order(ExchOrderID="1100000017861430", Qty=2,Price=261) ``` -#### Canceling an order +#### Cancelling an order ```py -client.cancel_order(exch_order_id="12345678", traded_qty=10, scrip_code=11111) +client.cancel_order(exch_order_id="1100000017795041") +``` +```py +cancel_bulk=[ + { + "ExchOrderID": "" + }, + { + "ExchOrderID": "" + }, +client.cancel_bulk_order(cancel_bulk) ``` -#### Fetching Order Status and Trade Information +#### Order Margin Calculation +- This function can help calculate +- Margin required for single or multileg order +- Margin required considering existing positions( CoverPosition = Y/N) + +```py +Orders2 =[ + + { + "Exch": "N", + "ExchType": "C", + "ScripCode": 2885, + "ScripData": "", + "PlaceModifyCancel": "P", + "OrderType": "B", + "Price": 0, + "Qty": 1, + "IsIntraday": False + }, + { + "Exch": "B", + "ExchType": "C", + "ScripCode": 512070, + "ScripData": "", + "PlaceModifyCancel": "P", + "OrderType": "S", + "Price": 0, + "Qty": 1, + "IsIntraday": True + } + ] +a=client.multi_order_Margin(CoverPositions='Y',Orders=Orders2) + +``` +#### SquareOffAll Orders ```py -from py5paisa.order import OrderForStatus, Exchange, ExchangeType, RequestList +client.squareoff_all() +``` +#### Bracket Order + +For placing Braket order +```py +client.bo_order(OrderType='B',Exchange='N',ExchangeType='C', ScripCode = 1660, Qty=1, LimitPrice=330,TargetPrice=345,StopLossPrice=320,LimitPriceForSL=319,TrailingSL=1.5) + +``` +For placing Cover order +```py +client.cover_order(OrderType='B',Exchange='N',ExchangeType='C', ScripCode = 1660, Qty=1, LimitPrice=330,StopLossPrice=320,TrailingSL=1.5) +``` + +Note:For placing Bracket order in FNO segment pass ExchType='D' + +For Modifying Bracket/Cover Order only for Initial order (entry) +```py + +client.modify_bo_order(ExchOrderID="1100000017861430",LimitPrice=330) +client.modify_cover_order(ExchOrderID="1100000017861430",LimitPrice=330) + +#Note : For cover order just pass LimitPriceProfitOrder equal to Zero. +``` + +For Modifying LimitPriceProfitOrder +```py +client.modify_bo_order(ExchOrderID="1100000017861430",TargetPrice=330) +client.modify_cover_order(ExchOrderID="1100000017861430",TargetPrice=330) +``` +For Modifying TriggerPriceForSL +```py + +client.modify_bo_order(ExchOrderID="1100000017861430",LimitPriceForSL=330) +client.modify_bo_order(ExchOrderID="1100000017861430",LimitPriceForSL=330) + +#Note : You have pass atmarket=true while modifying stoploss price, Pass ExchorderId for the particular leg to modify. +``` +#### Basket Orders + +```py +# Create a new Basket +client.create_basket("") -test_order_status = OrderForStatus(exchange=Exchange.BSE, exchange_type=ExchangeType.CASH, scrip_code=500875, order_id=0) +# Rename existing basket +client.rename_basket("",) -req_list = RequestList() -# Add multiple orders to the RequestList to know status of multiple orders at once. -req_list.add_order(test_order_status) +# Clone existing basket +client.clone_basket() + +# Delete bulk baskets +delete_basket_list=[{"BasketID":""},{"BasketID":""}] +client.delete_basket(delete_basket_list) + + +# Get list of all baskets (Open/Closed) +client.get_basket() + +basket_list= [ + { + "BasketID": "" + }, + { + "BasketID": "" + } + ] +order_to_basket=Basket_order("N","C",23000,"BUY",1,"1660","I") +client.add_basket_order(order_to_basket,basket_list) + +# Get orders in basket +client.get_order_in_basket() + +``` + +#### Fetching Order Status and Trade Information + +```py +from py5paisa.order import Exchange + +req_list= [ + { + "Exch": "N", + "ExchType": "C", + "ScripCode": 20374, + "ExchOrderID": "1000000015310807" + }] # Fetches the trade details client.fetch_trade_info(req_list) +req_list_= [ + + { + "Exch": "N", + "RemoteOrderID": "90980441" + }] # Fetches the order status -client.fetch_order_status(req_list) +client.fetch_order_status(req_list_) + +# Fetch Trade History + +print(client.get_trade_history("PASS EXCHANGE ORDER ID")) + +``` +#### Live Market Feed Streaming - Websocket +#NOTE : Webscoket only works with ScripCode +```py +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) +``` +Note: Use the following abbreviations : + +Market Feed=mf + +Market Depth (upto 5)=md + +Indices (Spot Feed) =i + +Open Interest=oi + +Subscribe= s + +Unsubscribe=u + +#### Live Market Depth Streaming (Depth 20) + +```py +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) + +Note:- Instruments in payload above is a list(array) in format as +``` + +#### Level 5 Market Depth +```py +print(client.fetch_market_depth_by_scrip(Exchange="N",ExchangeType="C",ScripCode="1660")) +print(client.fetch_market_depth_by_scrip(Exchange="N",ExchangeType="C",ScripData="RELIANCE_EQ")) +``` + +#### Full Market Snapshot +```py +a=[{"Exchange":"N","ExchangeType":"C","ScripCode":"2885"}, + {"Exchange":"N","ExchangeType":"C","ScripData":"ITC_EQ"}, + ] +print(client.fetch_market_snapshot(a)) +``` + + +#### Option Chain +```py +client.get_expiry("N","NIFTY") +# Returns list of all active expiries + +# client.get_option_chain("N","NIFTY",) +client.get_option_chain("N","NIFTY",1647507600000) +``` + +#### Historical Data +```py +#historical_data(,,,