GithubHelp home page GithubHelp logo

kotak-neo-api's Introduction

Kotak Neo Python SDK Development

  • API version: 1.0.1
  • Package version: 1.2.0

Requirements.

Python 2.7+ and 3.0+

Installation & Usage

pip install

If the python package is hosted on a repository, you can install directly using:

pip install "git+https://github.com/Kotak-Neo/kotak-neo-api.git#egg=neo_api_client"

If you are updating your package please use below command to install

pip install --force-reinstall "git+https://github.com/Kotak-Neo/kotak-neo-api"

(you may need to run pip with root permission: sudo pip install -e ")

Then import the package:

import neo_api_client

Setuptools

Install via [Setuptools]

python setup.py install --user

(or sudo python setup.py install to install the package for all users)

Then import the package:

import neo_api_client

Getting Started

Please follow the installation procedure and then refer to the sample code below for various API requests:

from neo_api_client import NeoAPI
def on_message(message):
    print(message)
    
def on_error(error_message):
    print(error_message)

def on_close(message):
    print(message)
    
def on_open(message):
    print(message)
    
#on_message, on_open, on_close and on_error is a call back function we will provide the response for the subscribe method.
# access_token is an optional one. If you have barrier token then pass and consumer_key and consumer_secret will be optional.
# environment by default uat you can pass prod to connect to live server
client = NeoAPI(consumer_key="", consumer_secret="", environment='uat',
                access_token=None, neo_fin_key=None)

# Initiate login by passing any of the combinations mobilenumber & password (or) pan & password (or) userid & password
# Also this will generate the OTP to complete 2FA
client.login(mobilenumber="+919999999999", password="XXXX")

# Complete login and generate session token
client.session_2fa(OTP="")

# Setup Callbacks for websocket events (Optional)
client.on_message = on_message  # called when message is received from websocket
client.on_error = on_error  # called when any error or exception occurs in code or websocket
client.on_close = on_close  # called when websocket connection is closed
client.on_open = on_open  # called when websocket successfully connects

# Once 2FA has you can place the order by using below function
client.place_order(exchange_segment='', product='', price='', order_type='', quantity=12, validity='', trading_symbol='',
                    transaction_type='', amo="NO", disclosed_quantity="0", market_protection="0", pf="N",
                    trigger_price="0", tag=None)
						
# Modify an order
client.modify_order(order_id = "", price = 0, quantity = 1, disclosed_quantity = 0, trigger_price = 0, validity = "GFD")

# Cancel an order
client.cancel_order(order_id = "")

# This is delay type. if order id along with isVerify as True will be passed then check the status of the given order id and then proceed to further
client.cancel_order(order_id = "", isVerify=True)

# Get Order Book
client.order_report()

# Get Order History
client.order_history(order_id = "")

# Get Trade Book
client.trade_report()

# Get Detailed Trade Report for specific order id. 
client.trade_report(order_id = "")

# Get Positions
client.positions()

# Get Portfolio Holdings
client.holdings()

# Get Limits
client.limits(segment="", exchange="", product="")

# Get Margin required for Equity orders. 
client.margin_required(exchange_segment = "", price = "", order_type= "", product = "",   quantity = "", instrument_token = "",  transaction_type = "")

# Get Scrip Master CSV file
client.scrip_master()

# Get Scrip Master CSV file for specific Exchange Segment. 
client.scrip_master(exchange_segment = "")

# Search for the Scrip details from Scrip master file
# exchange_segment is mandatory option to pass and remaining parameters are optional
client.search_scrip(exchange_segment="cde_fo", symbol="", expiry="", option_type="",
                    strike_price="")

# Get Quote details. 
instrument_tokens = [{"instrument_token": "", "exchange_segment": ""},
    {"instrument_token": "", "exchange_segment": ""},
    {"instrument_token": "", "exchange_segment": ""},
    {"instrument_token": "", "exchange_segment": ""}]

# quote_type can be market_depth, ohlc, ltp, 52w, circuit_limits, scrip_details
# By Default quote_type is set as None that means you will get the complete data.
# Quotes api can be accessed without completing login by passing session_token, sid and server_id 
client.quotes(instrument_tokens = instrument_tokens, quote_type="", isIndex=False, 
              session_token="", sid="",server_id="")

# Subscribe method will get you the live feed details of the given tokens.
# By Default isIndex is set as False and you want to get the live feed to index scrips set the isIndex flag as True 
# By Default isDepth is set as False and you want to get the depth information set the isDepth flag as True
client.subscribe(instrument_tokens = instrument_tokens, isIndex=False, isDepth=False)

# Un_Subscribes the given tokens. First the tokens will be checked weather that is subscribed. If not Subscribed we will send you the error message else we will unsubscribe the give tokens
client.un_subscribe(instrument_tokens=instrument_tokens, isIndex=False, isDepth=False)

#Order Feed 
client.subscribe_to_orderfeed()
#Terminate user's Session
client.logout()

Documentation for API Endpoints

Class Method Description
LoginAPI neo_api_client.SessionINIT Initialise Session
LoginAPI neo_api_client.NeoAPI Login NeoAPI
LoginAPI neo_api_client.2FA Session 2FA
Place Order neo_api_client.placeorder Place Order
Modify Order neo_api_client.modifyorder Modify Order
Cancel Order neo_api_client.cancelorder Cancel Order
Order Report neo_api_client.orderreport Order Report
Trade Report neo_api_client.tradereport Trade Report
Positions neo_api_client.positions Positions
Holdings neo_api_client.holdings Holdings
Limits neo_api_client.limits Limits
Margin Required neo_api_client.margin_required Margin Required
Scrip Master neo_api_client.scrip_master Scrip Master
Search Scrip neo_api_client.scrip_search Scrip Search
Quotes neo_api_client.quotes Quotes
Subscribe neo_api_client.subscribe Subscribe

kotak-neo-api's People

Contributors

bheemaray-hb avatar kotak-neo avatar mayank408 avatar nbharadvajdatamatics avatar shashwat001 avatar subanrafique avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

kotak-neo-api's Issues

Login Issue

Am not able to login am getting the below error .. not sure what am doing wrong

{"data": {"access_token": "eyJ4NXQiOiJNbUprWWpVMlpETmpNelpqTURBM05UZ3pObUUxTm1NNU1qTXpNR1kyWm1OaFpHUTFNakE1TmciLCJraWQiOiJaalJqTUdRek9URmhPV1EwTm1WallXWTNZemRtWkdOa1pUUmpaVEUxTlRnMFkyWTBZVEUyTlRCaVlURTRNak5tWkRVeE5qZ3pPVGM0TWpGbFkyWXpOUV9SUzI1NiIsImFsZyI6IlJTMjU2In0.eyJzdWIiOiJjbGllbnQ4NzcyIiwiYXV0IjoiQVBQTElDQVRJT04iLCJhdWQiOiJUM0RxVGs0YUdYYXF4SWNPZmhhV1ZyZGYzcmdhIiwibmJmIjoxNjkxNDk0OTU5LCJhenAiOiJUM0RxVGs0YUdYYXF4SWNPZmhhV1ZyZGYzcmdhIiwic2NvcGUiOiJkZWZhdWx0IiwiaXNzIjoiaHR0cHM6XC9cL25hcGkua290YWtzZWN1cml0aWVzLmNvbTo0NDNcL29hdXRoMlwvdG9rZW4iLCJleHAiOjE2OTE0OTg1NTksImlhdCI6MTY5MTQ5NDk1OSwianRpIjoiMWQ2ZmQ4MDEtMGNmOS00Zjk1LTk0MjItMTFlNWZmNDgzOTU0In0.Ker72KTYZAGIeDl-pHCbwGBA0Z3HPHAaLXYiDkOROroXTGXhyb58uA21wgX1l-1ZeWeuNN8CLXHaBIBwBowVaSy_HSOu2UG0NzvG2cSG5emy7MxSc2FzIZwwzmh4o36G08MFHf-ty7bcUGdJEBwqULatVjk2-7OezpvmU7e2UWAbGF0_PnnyB0yVjgS8UuZKc6paJ94YvRYQC--0g_u-7N7pIe18GRZm5BMzYhXkWwNCG9ktHrn1BfFzlIQUqeOdYpZ2gf78BkDW5Am84fvWrogoElyjEkaK19w24r-TceVVqQ0qcaXepalh3yr8UPdL4jo-TjYRcINuKZyZqTb6Kw", "scope": "default", "token_type": "Bearer", "expires_in": 3600}}
ERROR msg (0)
Reason: ChunkedEncodingError
("Connection broken: InvalidChunkLength(got length b'', 0 bytes read)", InvalidChunkLength(got length b'', 0 bytes read))

Traceback (most recent call last):
File "/home/ec2-user/.local/lib/python3.9/site-packages/urllib3/response.py", line 761, in _update_chunk_length
self.chunk_left = int(line, 16)
ValueError: invalid literal for int() with base 16: b''

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/home/ec2-user/.local/lib/python3.9/site-packages/urllib3/response.py", line 444, in _error_catcher
yield
File "/home/ec2-user/.local/lib/python3.9/site-packages/urllib3/response.py", line 828, in read_chunked
self._update_chunk_length()
File "/home/ec2-user/.local/lib/python3.9/site-packages/urllib3/response.py", line 765, in _update_chunk_length
raise InvalidChunkLength(self, line)
urllib3.exceptions.InvalidChunkLength: InvalidChunkLength(got length b'', 0 bytes read)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/usr/lib/python3.9/site-packages/requests/models.py", line 753, in generate
for chunk in self.raw.stream(chunk_size, decode_content=True):
File "/home/ec2-user/.local/lib/python3.9/site-packages/urllib3/response.py", line 624, in stream
for line in self.read_chunked(amt, decode_content=decode_content):
File "/home/ec2-user/.local/lib/python3.9/site-packages/urllib3/response.py", line 857, in read_chunked
self._original_response.close()
File "/usr/lib64/python3.9/contextlib.py", line 137, in exit
self.gen.throw(typ, value, traceback)
File "/home/ec2-user/.local/lib/python3.9/site-packages/urllib3/response.py", line 461, in _error_catcher
raise ProtocolError("Connection broken: %r" % e, e)
urllib3.exceptions.ProtocolError: ("Connection broken: InvalidChunkLength(got length b'', 0 bytes read)", InvalidChunkLength(got length b'', 0 bytes read))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/home/ec2-user/.local/lib/python3.9/site-packages/neo_api_client/rest.py", line 59, in request
response = requests.post(url=url, headers=headers, data=request_body)
File "/usr/lib/python3.9/site-packages/requests/api.py", line 119, in post
return request('post', url, data=data, json=json, **kwargs)
File "/usr/lib/python3.9/site-packages/requests/api.py", line 61, in request
return session.request(method=method, url=url, **kwargs)
File "/usr/lib/python3.9/site-packages/requests/sessions.py", line 544, in request
resp = self.send(prep, **send_kwargs)
File "/usr/lib/python3.9/site-packages/requests/sessions.py", line 699, in send
r.content
File "/usr/lib/python3.9/site-packages/requests/models.py", line 831, in content
self._content = b''.join(self.iter_content(CONTENT_CHUNK_SIZE)) or b''
File "/usr/lib/python3.9/site-packages/requests/models.py", line 756, in generate
raise ChunkedEncodingError(e)
requests.exceptions.ChunkedEncodingError: ("Connection broken: InvalidChunkLength(got length b'', 0 bytes read)", InvalidChunkLength(got length b'', 0 bytes read))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/home/ec2-user/kotak.py", line 15, in
client.login(mobilenumber="+My mobile number", password="MyPassword$")
File "/home/ec2-user/.local/lib/python3.9/site-packages/neo_api_client/neo_api.py", line 117, in login
view_token = neo_api_client.LoginAPI(self.api_client).generate_view_token(password=password, mobilenumber=mobilenumber,
File "/home/ec2-user/.local/lib/python3.9/site-packages/neo_api_client/api/login_api.py", line 62, in generate_view_token
generate_view_token = self.rest_client.request(
File "/home/ec2-user/.local/lib/python3.9/site-packages/neo_api_client/rest.py", line 77, in request
raise ApiException(status=0, reason=msg)
ERROR msg (0)
Reason: ChunkedEncodingError
("Connection broken: InvalidChunkLength(got length b'', 0 bytes read)", InvalidChunkLength(got length b'', 0 bytes read))

neo_api_client.exceptions.ApiException: <exception str() failed>

Quotes api does not work

image

This pops up after 5 min whenever I try to run Quotes API. I have turned the firewall off.

image

This never happened in Kotak Securities API. Kindly help.
Also, how can I find the wToken, all I can find is the pTradeSymbol.

Need clarity on few points

After all day trade, I want to run API to close/square off all open positions at 3:15 pm. This is just in case if there is an error and positions doesn't get close. In this scenario:

  1. Do I need to use client.positions() or there is alternate way. I don't want to use 'client' as it authenticates again. Instead I would like to use access_token, token, hsServerId, and server key to call positions API.
  2. In positions API, which parameter or key tells me that a position is open?
  3. When I call place order API, I need to check status of API. Can you tell me all possible values of 'ordSt' in order status API success response? My code broke because ordSt returned some values that are not documented and hence I didn't consider in code.

Thanks

scrip master expiry date

please help on the format of expiry date in scrip master file. i am not able to figure out in which format is the expiry date

Modify Order : getting bad request

client.modify_order(order_id='230718001217031', order_type='SL', price=0.25, quantity=40, disclosed_quantity=0, trigger_price=0.25, validity="DAY")

In above code tried validity as 'GFD" also tried sending prices as int,String

quote api returns empty

I am trying to get LTP for BANKNIFTY2381745000PE
inst_tokens = [{"instrument_token": '39040', "exchange_segment": 'nse_fo'}] self.api.quotes(instrument_tokens=inst_tokens, quote_type='ltp', isIndex=True)

This returns {}.
I have this problem only for FO not for CM

How to avoid OTP by using mpin

Hi support

How can I avoid OTP validation every time I run the application, can we avoid this by some method with mpin , I tried all kind of login mechanism but it comes to OTP validation ..

if there is a way can you please guide on the login process without the OTP but using the mpin you did respond to me in my earlier login issues about using the mpin but not able to figure out the same

Any help in this regard would be of great help

Update python-dotenv version

If python-dotenv is not being used, please update it to version 1.0.0. It will help developers to use the updated dependency.

Login not working

self.api = NeoAPI(
            consumer_key=consumer_key,
            consumer_secret=consumer_secret,
            environment='prod',
            on_message=on_message,
            on_error=on_error,
            on_close=None,
            on_open=None,
        )
self.api.login(
            mobilenumber=mobile_number,
            password=password,
        )

I am using the prod credentials from developer portal and neo web portal's password but
I get TypeError: can only concatenate str (not "NoneType") to str from login_api.py:58
I debugged and found that LoginAPI.session_init returns 401

Modify order not working

Below is the response from orders

[{'brkClnt': '08081', 'ordValDt': 'NA', 'exUsrInfo': 'NA', 'mfdBy': 'ATYPR0648C', 'vendorCode': '', 'rmk': '--', 'odCrt': 'NA', 'ordSrc': 'ADMINCPPAPI_TRADEAPI', 'sipInd': 'NA', 'prc': '1405.00', 'prcTp': 'L', 'cnlQty': 0, 'uSec': '960991', 'classification': '0', 'mktPro': '0.00', 'ordEntTm': '14-Aug-2023 14:27:12', 'reqId': '1', 'algSeqNo': 'NA', 'qty': 150, 'unFldSz': 150, 'mktProPct': '--', 'algCat': 'NA', 'exOrdId': '1100000030916215', 'dscQty': 0, 'actId': '9YM74', 'expDt': 'NA', 'trgPrc': '0.00', 'tok': '5258', 'symOrdId': 'NA', 'fldQty': 0, 'ordDtTm': '14-Aug-2023 14:44:40', 'avgPrc': '0.00', 'locId': '111111111111100', 'algId': 'NA', 'stat': 'Ok', 'prod': 'MIS', 'exSeg': 'nse_cm', 'GuiOrdId': '1692003432-914891-ATYPR0648C-ADMINAPI', 'usrId': 'ATYPR0648C', 'rptTp': 'NA', 'exCfmTm': '14-Aug-2023 14:27:12', 'hsUpTm': '2023/08/14 14:44:40', 'ordGenTp': 'NA', 'vldt': 'DAY', 'tckSz': '0.05', 'ordSt': 'open', 'trnsTp': 'S', 'refLmtPrc': 0.0, 'coPct': 0.0, 'nOrdNo': '230814001127432', 'ordAutSt': 'NA', 'rejRsn': 'RMS:Margin Exceeds,Cash Available:1537430.61,Additional margin required:321.49 for entity account-9YM74 across exchange across segment across product ', 'boeSec': 1692004480, 'expDtSsb': '--', 'dscQtyPct': '0', 'stkPrc': '0.00', 'sym': 'INDUSINDBK', 'trdSym': 'INDUSINDBK-EQ', 'multiplier': '1', 'precision': '2', 'noMktProFlg': '0.00', 'genNum': '1', 'series': 'EQ', 'prcNum': '1', 'genDen': '1', 'brdLtQty': '1', 'mktProFlg': '0.00', 'defMktProV': '0.00', 'lotSz': '1', 'minQty': 0, 'optTp': 'XX', 'prcDen': '1'}] โ€‹
I am trying to modify an existing order of SELL at 1405 to 1406, I get a 200 success response but the order isn't modified to the new price of 1406.

Screenshot 2023-08-14 at 2 49 37 PM

websocket response issues

Thanks for updating web socket documentation however it is still not complete. Can you please clarify the response structure for futures and options as well ?

Currently you have specified for Index, Stocks and Depth
Can you please specify same for futures and options as well ?

Another issue: Many times we are getting response which does not have ltt and ltp.
e.g.
{'ftm0': '09/01/1970 13:18:36', 'dtm1': '09/10/1971 01:35:43', 'fdtm': '08/08/2023 15:30:00', 'v': '221422800', 'ltq': '50', 'tbq': '209550', 'tsq': '509000', 'bp': '82.10', 'bq': '1450', 'bs': '200', 'to': '17623040652.00', 'name': 'sf', 'tk': '47876', 'e': 'nse_fo'}

Also, If I don't want depth details only ltt and ltp is required, is there any way to request on these ( not receive depth)

Error during order placement: {'stat': 'Not_Ok', 'stCode': 5202, 'errMsg': 'Error: Invalid Request'}

I am getting this error while placing an order. I am able to login and get the scrip name but having issue while placing order.
Here is the line of code
client.place_order(exchange_segment="nse_fo", product="NRML", price="", order_type="MKT", quantity="15",
validity="DAY",
trading_symbol="BANKNIFTY2391345000PE",
transaction_type="B", amo="NO", disclosed_quantity="", market_protection="0", pf="N",
trigger_price="", tag="Try")
This is the response
Out[34]: {'stat': 'Not_Ok', 'stCode': 5202, 'errMsg': 'Error: Invalid Request'}

getting error while logging

I am gettig below error
Traceback (most recent call last): File "/Users/sapansoni/Desktop/my_codes/kotak/utils/KotakApi.py", line 13, in <module> client.login(mobilenumber=Mobile, password=Pass) File "/Users/sapansoni/Desktop/my_codes/kotak/venv_kotak1/lib/python3.9/site-packages/neo_api_client/neo_api.py", line 120, in login gen_otp = neo_api_client.LoginAPI(self.api_client).generate_otp() File "/Users/sapansoni/Desktop/my_codes/kotak/venv_kotak1/lib/python3.9/site-packages/neo_api_client/api/login_api.py", line 86, in generate_otp userId = self.api_client.configuration.extract_userid(self.api_client.configuration.view_token) File "/Users/sapansoni/Desktop/my_codes/kotak/venv_kotak1/lib/python3.9/site-packages/neo_api_client/neo_utility.py", line 47, in extract_userid raise ApiValueError( neo_api_client.exceptions.ApiValueError: View Token hasn't been Generated Kindly Call the Login Function and Try to Generate OTP

I am running below code which is producing error

`from neo_api_client import NeoAPI
from cred import *
def on_message(message):
print(message)

def on_error(error_message):
print(error_message)

client = NeoAPI(consumer_key=consumer_key, consumer_secret=consumer_secret,environment='prod', on_message=on_message, on_error=on_error, on_close=None, on_open=None)
client.login(mobilenumber=Mobile, password=Pass)

otp = input("Enter OTP: ")

client.session_2fa(OTP=otp)

`

Keep getting error "ERROR in HSWebscoket socket is already closed." while calling Quotes API

I keep getting errors on Quotes API call. I started getting this error from 3rd Aug, 2023 onwards.

ERROR in HSWebscoket socket is already closed.
[OnError]: Function is running HSWebsocket
ERROR in HSWebscoket Connection is already closed.
[OnError]: Function is running HSWebsocket
ERROR in HSWebscoket 'NoneType' object has no attribute 'sock'
[OnError]: Function is running HSWebsocket
[OnClose]: Function is running HSWebsocket None

What could be the reason?

Live MTM

Hello,

Can you guide how to get live MTM or how to derive realized and unrealized MTM from positions data.

TIA

websocket response details

Could you please add response documentation in Docs for Web-socket ? currently response documentation is provided for quotes and it is very helpful but for websocket response has some wired fields and reference details would be very helpful.
e.g. PFB today's response for 3 instruments.

  • what is 'ftm0' and 'dtm1', why the dates are from 1970/1971 ?
  • what is field 'name' for ?
  • what is field 'to'
  • Can we get open interest as a part of websocket data feed ?
[
  {
    'ftm0': '05/01/1970 08:12:33',
    'dtm1': '02/10/1971 06:21:02',
    'ltt': '03/08/2023 15:20:12',
    'v': '8528520',
    'ltp': '56.00',
    'ltq': '200',
    'tbq': '115120',
    'tsq': '72760',
    'bp': '55.90',
    'sp': '56.00',
    'bq': '1120',
    'bs': '400',
    'cng': '19.05',
    'nc': '51.56',
    'to': '658145888.40',
    'name': 'sf',
    'tk': '42149',
    'e': 'nse_fo'
  },
  {
    'ftm0': '05/01/1970 11:02:39',
    'dtm1': '02/10/1971 06:21:02',
    'ltt': '03/08/2023 15:20:12',
    'v': '11975720',
    'ltp': '42.70',
    'tbq': '205440',
    'tsq': '100040',
    'bp': '42.65',
    'sp': '42.75',
    'bq': '240',
    'bs': '40',
    'cng': '10.70',
    'nc': '33.44',
    'to': '749440557.60',
    'name': 'sf',
    'tk': '42146',
    'e': 'nse_fo'
  },
  {
    'ftm0': '06/01/1970 18:49:04',
    'dtm1': '02/10/1971 06:21:03',
    'v': '15006520',
    'ltq': '40',
    'tbq': '389480',
    'tsq': '29000',
    'bp': '172.40',
    'sp': '172.55',
    'to': '2172193770.00',
    'name': 'sf',
    'tk': '42187',
    'e': 'nse_fo'
  }
]

how to get market data?

Hi want to get the market data such as ohlc for 5,15 min time frame for previous n no of days so that I can do technical analysis on same

is there a way to fetch these information ?

NIFTY 50 Index quote

print('Subscribing to NIFTY Index token')
nifty_token = 26000
n_inst_token = [{"instrument_token": str(nifty_token), "exchange_segment": "Index"}]
client.subscribe(instrument_tokens=n_inst_token, isIndex=True)

This is not working. Can you check what is wrong. Equity and FNO works fine.

Error in scrip_master() API

Hello Team,

I am getting the below error while calling the script_master() API.

Error :

Reason: ChunkedEncodingError
("Connection broken: InvalidChunkLength(got length b'', 0 bytes read)", InvalidChunkLength(got length b'', 0 bytes read))

{'error': ApiException('(0)\nReason: ChunkedEncodingError\n("Connection broken: InvalidChunkLength(got length b\'\', 0 bytes read)", InvalidChunkLength(got length b\'\', 0 bytes read))\n')}

gen_otp = neo_api_client.LoginAPI(self.api_client).generate_otp()

Getting error when i run this code

client.login(mobilenumber="+91myphobenumber", password="mypassword")
client.session_2fa(OTP="1040")

ApiValueError                             Traceback (most recent call last)
Cell In[4], line 1
----> 1 client.login(mobilenumber="+91myphobenumber", password="mypassword")
      2 client.session_2fa(OTP="1040")

File C:\NSE\Python Script\NEO\kotak-neo-api-main\neo_api_client\neo_api.py:120, in NeoAPI.login(self, password, mobilenumber, userid, pan, mpin)
    117 view_token = neo_api_client.LoginAPI(self.api_client).generate_view_token(password=password, mobilenumber=mobilenumber,
    118                                                                           userid=userid, pan=pan, mpin=mpin)
    119 if "error" not in view_token:
--> 120     gen_otp = neo_api_client.LoginAPI(self.api_client).generate_otp()
    121     print(gen_otp)
    122 else:

File C:\NSE\Python Script\NEO\kotak-neo-api-main\neo_api_client\api\login_api.py:86, in LoginAPI.generate_otp(self)
     84 def generate_otp(self):
     85     header_params = {'Authorization': "Bearer " + self.api_client.configuration.bearer_token}
---> 86     userId = self.api_client.configuration.extract_userid(self.api_client.configuration.view_token)
     87     body_params = {
     88         "userId": userId,
     89         "sendEmail": True,
     90         "isWhitelisted": True
     91     }
     92     URL = self.api_client.configuration.get_url_details("generate_otp")

File C:\NSE\Python Script\NEO\kotak-neo-api-main\neo_api_client\neo_utility.py:47, in NeoUtility.extract_userid(self, view_token)
     45 def extract_userid(self, view_token):
     46     if not view_token:
---> 47         raise ApiValueError(
     48             "View Token hasn't been Generated Kindly Call the Login Function and Try to Generate OTP")
     49     decode_jwt = jwt.decode(view_token, options={"verify_signature": False})
     50     userid = decode_jwt.get("sub")

ApiValueError: View Token hasn't been Generated Kindly Call the Login Function and Try to Generate OTP

Unable to login using NeoAPI

Please help resolve this basic issue of logging in.

I have set the values for these variables access_token, consumer_key and consumer_secret from the napi.kotaksecutiriessite.

When this method is called client = NeoAPI(access_token=accessToken, consumer_key=consumerKey, consumer_secret=consumerSecret, environment='UAT',
on_message=on_message,
on_error=on_error)
try:
# Login using password
client.login(mobilenumber=mobileNumber, password=tradingPassword)
print('Client', client)
except Exception as e:
print("Exception when calling SessionApi->login: %s\n" % e)

Below ERROR is reported
Exception when calling SessionApi->login: View Token hasn't been Generated Kindly Call the Login Function and Try to Generate OTP

If the same method is called without access_key
Below ERROR is reported
{"data": "{"data": {"Code": 401, "Message": "Error occurred to initialise the session"}}"}
Exception when calling SessionApi->login: can only concatenate str (not "NoneType") to str

'Tag' field in Order/Trade Report

Order report or trade report doesn't have the 'tag' field. Please advise how can we retrieve the order by 'tag' used while placing the order.

please check cant check postion, cant check limits, cant pull script master

was able to login but cant do anything, cant check postion, cant check limits, cant pull script master
i get below error in all attempt
//
ERROR msg (0)
Reason: ChunkedEncodingError
("Connection broken: InvalidChunkLength(got length b'', 0 bytes read)", InvalidChunkLength(got length b'', 0 bytes read))

{'Error': neo_api_client.exceptions.ApiException('(0)\nReason: ChunkedEncodingError\n("Connection broken: InvalidChunkLength(got length b'', 0 bytes read)", InvalidChunkLength(got length b'', 0 bytes read))\n')}
//

Avg price and current price in positions api

Do you have any plans to bring average price of the order and the current price of the scrip in positions like it was previously. I used to calculate the unrealised PnL using the two price values. Is there any way to calculate PnL now? Also what is cfBuyAmt and cfSellAmt

Highly unreliable and unstable SDK

Raised this issue previously too but no response.

API stops performing tasks such as get limit, place order etc. after 1 hour of login.

I doubt this is suitable for production usage.

Unable to login , using the sample script from readme.md. Error - {"data": "{\"data\": {\"Code\": 401, \"Message\": \"Error occurred to initialise the session\"}}"}

Tried with both prod and uat as env

{"data": "{\"data\": {\"Code\": 401, \"Message\": \"Error occurred to initialise the session\"}}"} Traceback (most recent call last): File "/home/vandan/tradeauto/kotak/trade.py", line 16, in <module> client.login(mobilenumber="+919087777398", password="Taktak24$") File "/home/vandan/tradeauto/env/lib/python3.10/site-packages/neo_api_client/neo_api.py", line 117, in login view_token = neo_api_client.LoginAPI(self.api_client).generate_view_token(password=password, mobilenumber=mobilenumber, File "/home/vandan/tradeauto/env/lib/python3.10/site-packages/neo_api_client/api/login_api.py", line 58, in generate_view_token header_params = {'Authorization': "Bearer " + self.api_client.configuration.bearer_token} TypeError: can only concatenate str (not "NoneType") to str

`from neo_api_client import NeoAPI

def on_message(message):
print(message)

def on_error(error_message):
print(error_message)

client = NeoAPI(consumer_key=consumer_key_here, consumer_secret=consumer_secret_here,
environment='prod', on_message=on_message, on_error=on_error, on_close=None, on_open=None)

client.login(mobilenumber="+91########3", password="*******")`

AMO Order is not allowed to be cancelled

I placed some AMO orders yesterday via API and when I tried to cancel those today I got this error. Note that I was able to cancel orders which were placed today, problem is with AMO orders only.

Error:
{'data': {'error': [{'code': '91400', 'message': 'Request not allowed. Cancel, Modify and OrderHistory will only be available if order was placed via API'}]}}

expiry date in script master

Hello, can you please confirm which column from scrip master is to be used as expiry date ?
e.g. if I look at script master file: https://lapi.kotaksecurities.com/wso2-scripmaster/v1/prod/2023-08-04/transformed/nse_fo.csv
There is column "lExpiryDate " however if seems to be in EPOCH format, however if I convert from epoch to date time, day and month is correct but year is 2013.
e.g. for pTrdSymbol = NIFTY2381017850CE, lExpiryDate is 1376145000. This converted to normal date is Saturday, August 10, 2013 8:00:00 PM GMT+05:30

If check if there is an issue with epoch date from your side or this date is in any different format ?

Clarification reg. id and password

Can you please clarify which 'userid/password' you are talking about here. The regular user id and password for accessing the website or that for the Devportal.

Initiate login by passing any of the combinations mobilenumber & password (or) pan & password (or) userid & password

Also this will generate the OTP to complete 2FA

client.login(mobilenumber="+919999999999", password="XXXX")

Quotes api returns empty {}

Quotes api takes little over 2 minutes to run. And returns {}
Running python 3.11.4

This is the code

inst_tokens = [{"instrument_token": "11536", "exchange_segment": "nse_cm"},
               {"instrument_token": "1594", "exchange_segment": "nse_cm"},
               {"instrument_token": "11915", "exchange_segment": "nse_cm"},
               {"instrument_token": "13245", "exchange_segment": "nse_cm"}]
client.quotes(instrument_tokens=inst_tokens, quote_type='', isIndex=False)

Session expiring every in 60 minutes

API stops returning data after 60 minutes of login. Kindly suggest how to maintain the session for full day.
Hope you understand that we cannot continue to login every hour.

Login on every API call?

Hi.
Your docs suggest to use 'client' object before calling any method (place oder, modify, cancel, etc.)

Does this mean that I need to login again and again every single time? If yes, why did you opt this approach?

If I don't use your github code and rely only on API documentation, then I can create session one time and run x number of methods.

Like in your API documentation, can you allow making calls by passing token, sid, server? Or can you add API doc for quotes in postman?

Historical Data

Hi !!

Are there any plan/ timelines you have to provide the Historical data especially for the Options chain / strike price peremiums ..

Shekar

Sandbox environment

Hi, I was trying to access the sandbox environment, I generated the consumer key and secret from the portal but whenever I try to log in, i am left with message, can you help me understand what I am doing wrong

Thanks

consumer_key = 'xxx'
consumer_secret = 'xxx'

from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
import pickle
import os.path
import re
import neo_api_client
from neo_api_client import NeoAPI
import time 

def on_message(message):
    print(message)
    
def on_error(error_message):
    print(error_message)

client = NeoAPI(consumer_key=consumer_key, consumer_secret=consumer_secret, 
        environment='prod', on_message=on_message, on_error=on_error, on_close=None, on_open=None)

after running the above code I got a response like this

{"data": {"access_token": "xxx", "scope": "default", "token_type": "Bearer", "expires_in": 72000}}

The error happens when I try to log in

client.login(mobilenumber="xxx", password="xxx")

Error - Traceback (most recent call last):

File "/var/folders/4x/s72xvc9d2hs6s8jq6vv26d040000gn/T/ipykernel_84175/4286315428.py", line 1, in <cell line: 1>
client.login(mobilenumber="xxx", password="xxx")

File "/opt/homebrew/lib/python3.10/site-packages/neo_api_client/neo_api.py", line 120, in login
gen_otp = neo_api_client.LoginAPI(self.api_client).generate_otp()

File "/opt/homebrew/lib/python3.10/site-packages/neo_api_client/api/login_api.py", line 86, in generate_otp
userId = self.api_client.configuration.extract_userid(self.api_client.configuration.view_token)

File "/opt/homebrew/lib/python3.10/site-packages/neo_api_client/neo_utility.py", line 47, in extract_userid
raise ApiValueError(

ApiValueError: View Token hasn't been Generated Kindly Call the Login Function and Try to Generate OTP

OTP is not generating

Received below response upon OTP request

{"data": {"access_token": "eyJ4NXQiOiJTm1NNU1qTXpNR1kyWm1OaFpHUTFNakE1TmciLCJraWQiOiJaalJqTUdRek9URmhPV1EwTm1WallXWTNZemRtWkdOa1pUUmpaVEUxTlRnMFkyWTBZVEUyTlRCaVlURTRNak5tWkRVeE5qZ3pPVGM0TWpGbFkyWXpOUV9SUzI1NiIsImFsZyI6IlJTMjU2In0.eyJzdWIiOiJjbGllbnQxNTY1IiwiYXV0IjoiQVBQTElDQVRJT04iLCJhdWQiOiJpcnEzT2NvYzJLXzBmbWZoNGNfS00xZUFTS01hIiwibmJmIjoxNjg5NzUzOTEyLCJhenAiOiJpcnEzT2NvYzJLXzBmbWZoNGNfS00xZUFTS01hIiwic2NvcGUiOiJkZWZhdWx0IiwiaXNzIjoiaHR0cHM6XC9cL25hcGkua290YWtzZWN1cml0aWVzLmNvbTo0NDNcL29hdXRoMlwvdG9rZW4iLCJleHAiOjE2ODk3NTc1MTIsImlhdCI6MTY4OTc1MzkxMiwianRpIjoiNmExNTMyNjItNGM1MC00ZThkLWJhZDktNmE5N2NmMWM4NmM3In0.FUwZanYdwzgBYw54SGyvmVIpl8BlpcDwrl_TvDF0T6CAqQlQniMbnHTNkzPlr7PdZHaS7fKkQIeDIrWgVI48J4_U4Hf2Y4QGDwl7tfjygbNRqgRrD71CR9WIOaTlfi6LBydYRJWlJWMIVMBCl69lo9foAzyTmNgd0y6AdVdhvGmKihJly1yJyJm1KwOFmVOJ1kEa-5bBw9UEdqNh8SvytWjBr8ikV2743ZB82x90ZNmAePHhXFtcYEydRGK5uZPl4Hsj4tsRLN9PyoaL5UGjI01jr2fhdYRfk5BwPPjrp0bduxMLXU9YlS9abc7JhF2OS5OFoYZktRlnqJIqePqabA", "scope": "default", "token_type": "Bearer", "expires_in": 3600}}
{'error': [{'code': '10522', 'message': 'Issues while generating OTP! Try to login again.'}]}

how to get profile information

Why there is no function to fetch profile information.
API is incomplete without profile info function.
If its already there please make it visible, getting very hard time finding it.

Moving Average

Does kotak neo provide movingnaverage data with API like fyer and other brokers. If "yes" please give method to get moving average data.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.