marketcalls / openalgo

Open Source Algo Trading Platform for Everyone
https://docs.openalgo.in
GNU General Public License v3.0
85 stars 33 forks source link

getting login error _kotak neo #43

Closed sk0024 closed 6 days ago

sk0024 commented 2 weeks ago

open algo error getting login error ; please look and advise account broker Kotak neo screenshot attached for your ref

thanks u sanjay

marketcalls commented 2 weeks ago

Please note that if you experience three failed login attempts via the Kotak API, your account will be automatically locked. However, Kotak has implemented a system where your account will be automatically unlocked after 24 hours. But still the Web Login will be still functional API lockout will not affect the Kotak Web Login.

We understand that this can be inconvenient and appreciate your patience. Please make sure to verify your credentials before attempting to log in to avoid triggering the lockout.

If you have any further questions or need assistance, feel free to reach out.

sk0024 commented 2 weeks ago

keyError

yes . getting key error after generate new Api key also . anyways will try after 24hrs if key locked by system

sk0024 commented 2 weeks ago

open algo key error_11 July open algo key error_11 July_1

getting error again Internal Server Error pls solve

sk0024 commented 2 weeks ago

getting Internal Server Error pls advise KeyError: 'data' 127.0.0.1 - - [11/Jul/2024 10:04:10] "POST /kotak/loginflow HTTP/1.1" 500 -

yadu12342q commented 2 weeks ago

same issue did someone get the solution for this

marketcalls commented 2 weeks ago

can you try replacing your brlogin.py with this code https://github.com/marketcalls/openalgo/blob/restxapi/blueprints/brlogin.py which fixes the data error and will be able to troubleshoot the issue properly

also do a pip install -r requirements.txt

ensure that the installation files are upto date Let me know what is the output you are getting in VS Code that will be helpful in triangulate the problem

sk0024 commented 2 weeks ago

getting unauthorized error

marketcalls commented 2 weeks ago

can you share the logs from VS Code?

yadu12342q commented 2 weeks ago

getting this error

{'code': '900901', 'message': 'Invalid Credentials', 'description': 'Access failure for API: /login/1.0, version: 1.0 status: (900901) - Invalid Credentials. Make sure you have provided the correct security credentials'} 127.0.0.1 - - [13/Jul/2024 18:24:49] "POST /kotak/loginflow HTTP/1.1" 200 - 127.0.0.1 - - [13/Jul/2024 18:24:49] "GET /static/favicon/apple-touch-icon.png HTTP/1.1" 304 - 127.0.0.1 - - [13/Jul/2024 18:24:49] "GET /static/images/thumbs-up.png HTTP/1.1" 304 -

sk0024 commented 1 week ago

Invalid Credentials

sk0024 commented 1 week ago

![Uploading kotak error _openalgo.jpg…]()

marketcalls commented 1 week ago

My trading account with Kotak will be ready in 1-2 days. Will find a solution for those who are facing login issues with Kotak in a day or two. For time being the data key error exception is fixed in 1.0.0.2 release

hemangshah36 commented 1 week ago

My trading account with Kotak will be ready in 1-2 days. Will find a solution for those who are facing login issues with Kotak in a day or two. For time being the data key error exception is fixed in 1.0.0.2 release

@marketcalls

Can you please explain what do you mean by data key error exception fixed in 1.0.0.2? Can you use it to check?

I have updated file as you suggested: https://github.com/marketcalls/openalgo/blob/restxapi/blueprints/brlogin.py

However, still getting error.

Console logs are as under:

127.0.0.1 - - [18/Jul/2024 02:27:10] "GET / HTTP/1.1" 200 - 127.0.0.1 - - [18/Jul/2024 02:27:10] "GET /static/favicon/logo.png HTTP/1.1" 200 - 127.0.0.1 - - [18/Jul/2024 02:27:10] "GET /static/images/brokers/angel.png HTTP/1.1" 200 - 127.0.0.1 - - [18/Jul/2024 02:27:10] "GET /static/images/brokers/5paisa.png HTTP/1.1" 200 - 127.0.0.1 - - [18/Jul/2024 02:27:10] "GET /static/images/brokers/dhan.png HTTP/1.1" 200 - 127.0.0.1 - - [18/Jul/2024 02:27:10] "GET /static/images/brokers/aliceblue.png HTTP/1.1" 200 - 127.0.0.1 - - [18/Jul/2024 02:27:10] "GET /static/images/brokers/fyers.png HTTP/1.1" 200 - 127.0.0.1 - - [18/Jul/2024 02:27:10] "GET /static/images/brokers/icici.png HTTP/1.1" 200 - 127.0.0.1 - - [18/Jul/2024 02:27:10] "GET /static/images/brokers/zerodha.png HTTP/1.1" 200 - 127.0.0.1 - - [18/Jul/2024 02:27:10] "GET /static/images/thumbs-up.png HTTP/1.1" 200 - 127.0.0.1 - - [18/Jul/2024 02:27:10] "GET /static/images/brokers/kotak.png HTTP/1.1" 200 - 127.0.0.1 - - [18/Jul/2024 02:27:10] "GET /static/images/brokers/upstox.png HTTP/1.1" 200 - 127.0.0.1 - - [18/Jul/2024 02:27:10] "GET /static/favicon/apple-touch-icon.png HTTP/1.1" 200 - 127.0.0.1 - - [18/Jul/2024 02:27:10] "GET /static/favicon/favicon-32x32.png HTTP/1.1" 200 - 127.0.0.1 - - [18/Jul/2024 02:27:12] "GET /auth/login HTTP/1.1" 200 - 127.0.0.1 - - [18/Jul/2024 02:27:12] "GET /static/favicon/apple-touch-icon.png HTTP/1.1" 304 - 127.0.0.1 - - [18/Jul/2024 02:27:12] "GET /favicon.ico HTTP/1.1" 404 - login success 127.0.0.1 - - [18/Jul/2024 02:27:21] "POST /auth/login HTTP/1.1" 200 - 127.0.0.1 - - [18/Jul/2024 02:27:21] "GET /auth/broker HTTP/1.1" 200 - 127.0.0.1 - - [18/Jul/2024 02:27:21] "GET /static/favicon/apple-touch-icon.png HTTP/1.1" 304 - 127.0.0.1 - - [18/Jul/2024 02:27:21] "GET /static/images/brokers/5paisa.png HTTP/1.1" 304 - 127.0.0.1 - - [18/Jul/2024 02:27:21] "GET /static/images/brokers/aliceblue.png HTTP/1.1" 304 - 127.0.0.1 - - [18/Jul/2024 02:27:21] "GET /static/images/brokers/dhan.png HTTP/1.1" 304 - 127.0.0.1 - - [18/Jul/2024 02:27:22] "GET /static/images/brokers/angel.png HTTP/1.1" 304 - 127.0.0.1 - - [18/Jul/2024 02:27:22] "GET /static/images/brokers/fyers.png HTTP/1.1" 304 - 127.0.0.1 - - [18/Jul/2024 02:27:22] "GET /static/images/brokers/icici.png HTTP/1.1" 304 - 127.0.0.1 - - [18/Jul/2024 02:27:22] "GET /static/images/brokers/kotak.png HTTP/1.1" 304 - 127.0.0.1 - - [18/Jul/2024 02:27:22] "GET /static/images/brokers/upstox.png HTTP/1.1" 304 - 127.0.0.1 - - [18/Jul/2024 02:27:22] "GET /static/images/brokers/zerodha.png HTTP/1.1" 304 - 127.0.0.1 - - [18/Jul/2024 02:27:22] "GET /static/images/thumbs-up.png HTTP/1.1" 304 - Broker is kotak The Broker is kotak 127.0.0.1 - - [18/Jul/2024 02:27:25] "GET /kotak/callback HTTP/1.1" 200 - 127.0.0.1 - - [18/Jul/2024 02:27:25] "GET /static/favicon/apple-touch-icon.png HTTP/1.1" 304 - 127.0.0.1 - - [18/Jul/2024 02:27:25] "GET /static/images/thumbs-up.png HTTP/1.1" 304 - [2024-07-18 02:27:39,459] ERROR in app: Exception on /kotak/loginflow [POST] Traceback (most recent call last): File "C:\Users\Administrator\AppData\Local\Programs\Python\Python312\Lib\site-packages\flask\app.py", line 1473, in wsgi_app response = self.full_dispatch_request() ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Administrator\AppData\Local\Programs\Python\Python312\Lib\site-packages\flask\app.py", line 882, in full_dispatch_request rv = self.handle_user_exception(e) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Administrator\AppData\Local\Programs\Python\Python312\Lib\site-packages\flask\app.py", line 880, in full_dispatch_request rv = self.dispatch_request() ^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Administrator\AppData\Local\Programs\Python\Python312\Lib\site-packages\flask\app.py", line 865, in dispatch_request return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args) # type: ignore[no-any-return] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Administrator\AppData\Local\Programs\Python\Python312\Lib\site-packages\flask_limiter\extension.py", line 1303, in __inner return cast(R, flask.current_app.ensure_sync(obj)(*a, **k)) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Administrator\AppData\Local\Programs\Python\Python312\Lib\site-packages\flask_limiter\extension.py", line 1303, in __inner return cast(R, flask.current_app.ensure_sync(obj)(*a, **k)) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Administrator\openalgo\blueprints\brlogin.py", line 139, in broker_loginflow conn.request("POST", "/login/1.0/login/v2/validate", payload, headers) File "C:\Users\Administrator\AppData\Local\Programs\Python\Python312\Lib\http\client.py", line 1336, in request self._send_request(method, url, body, headers, encode_chunked) File "C:\Users\Administrator\AppData\Local\Programs\Python\Python312\Lib\http\client.py", line 1382, in _send_request self.endheaders(body, encode_chunked=encode_chunked) File "C:\Users\Administrator\AppData\Local\Programs\Python\Python312\Lib\http\client.py", line 1331, in endheaders self._send_output(message_body, encode_chunked=encode_chunked) File "C:\Users\Administrator\AppData\Local\Programs\Python\Python312\Lib\http\client.py", line 1091, in _send_output self.send(msg) File "C:\Users\Administrator\AppData\Local\Programs\Python\Python312\Lib\http\client.py", line 1035, in send self.connect() File "C:\Users\Administrator\AppData\Local\Programs\Python\Python312\Lib\http\client.py", line 1477, in connect self.sock = self._context.wrap_socket(self.sock, ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Administrator\AppData\Local\Programs\Python\Python312\Lib\ssl.py", line 455, in wrap_socket return self.sslsocket_class._create( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Administrator\AppData\Local\Programs\Python\Python312\Lib\ssl.py", line 1042, in _create self.do_handshake() File "C:\Users\Administrator\AppData\Local\Programs\Python\Python312\Lib\ssl.py", line 1320, in do_handshake self._sslobj.do_handshake() ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1000) 127.0.0.1 - - [18/Jul/2024 02:27:39] "POST /kotak/loginflow HTTP/1.1" 500 -

marketcalls commented 1 week ago

The error log shows an ssl.SSLCertVerificationError, indicating that there is a failure in SSL certificate verification when attempting to connect to an external service. This error is common when the local environment does not have the necessary root certificates installed.

To resolve this issue, you can try the following steps:

Install Root Certificates Ensure that your Python installation has the required root certificates.

macOS: If you're using macOS, you can run the Install Certificates.command script provided by the Python installer. It is typically located in the Applications/Python 3.x/ directory.

Windows: On Windows, you might need to install the certifi package, which provides Mozilla's CA Bundle:

pip install --upgrade certifi

The inconsistency in SSL certificate verification across different machines, even with certifi installed, can be due to several factors. Here's a breakdown of the potential reasons and solutions:

Potential Reasons System-Level Root Certificates:

Some systems might have outdated or missing root certificates, causing SSL verification to fail even if the certifi package is installed.

Python Version Differences:

Different versions of Python might handle SSL verification differently. Ensure all machines are using the same Python version. Environment Configuration:

Differences in environment configuration, such as proxy settings or environment variables, can affect SSL verification.

Network Differences:

Some networks might have additional SSL inspection or restrictions that could interfere with SSL verification.

Solutions Ensure Root Certificates are Up-to-Date:

On systems where SSL verification fails, update the root certificates. macOS: Run the Install Certificates.command script found in the Python installation directory. Windows: Ensure that the system's root certificates are up-to-date. You can also manually update the certificates by using the certifi package.

marketcalls commented 1 week ago

If you are trying with 3.12 or higher versions of python. Consider trying using 3.10 or 3.11 versions. As previously similar error got encountered got fixed. While migrating to Python 3.11 might provide a temporary workaround

A better approach is to ensure SSL handling is robust and compatible with the latest standards. This includes: Updating root certificates. Explicitly configuring SSL contexts to use certifi. Ensuring that all dependencies are up-to-date.

Something like


import http.client
import ssl
import certifi  

@brlogin_bp.route('/<broker>/loginflow', methods=['POST','GET'])
@limiter.limit(LOGIN_RATE_LIMIT_MIN)
@limiter.limit(LOGIN_RATE_LIMIT_HOUR)
def broker_loginflow(broker):
    if broker == 'kotak':
        mobilenumber = request.form.get('mobilenumber')
        password = request.form.get('password')

        # Create an SSL context using certifi
        context = ssl.create_default_context(cafile=certifi.where())

        conn = http.client.HTTPSConnection("gw-napi.kotaksecurities.com", context=context)
        payload = json.dumps({
            "mobileNumber": mobilenumber,
            "password": password
        })
        api_secret = get_broker_api_secret()
        headers = {
            'accept': '*/*',
            'Content-Type': 'application/json',
            'Authorization': f'Bearer {api_secret}'
        }
        conn.request("POST", "/login/1.0/login/v2/validate", payload, headers)
        res = conn.getresponse()
        data = res.read().decode("utf-8")
        data_dict = json.loads(data)

        token = data_dict['data']['token']
        sid = data_dict['data']['sid']
        decode_jwt = jwt.decode(token, options={"verify_signature": False})
        userid = decode_jwt.get("sub")

        para = {
            "token": token,
            "sid": sid,
            "userid": userid
        }
        getKotakOTP(userid, api_secret)
        return render_template('kotakotp.html', para=para)
hemangshah36 commented 1 week ago

@

The error log shows an ssl.SSLCertVerificationError, indicating that there is a failure in SSL certificate verification when attempting to connect to an external service. This error is common when the local environment does not have the necessary root certificates installed.

To resolve this issue, you can try the following steps:

Install Root Certificates Ensure that your Python installation has the required root certificates.

macOS: If you're using macOS, you can run the Install Certificates.command script provided by the Python installer. It is typically located in the Applications/Python 3.x/ directory.

Windows: On Windows, you might need to install the certifi package, which provides Mozilla's CA Bundle:

pip install --upgrade certifi

The inconsistency in SSL certificate verification across different machines, even with certifi installed, can be due to several factors. Here's a breakdown of the potential reasons and solutions:

Potential Reasons System-Level Root Certificates:

Some systems might have outdated or missing root certificates, causing SSL verification to fail even if the certifi package is installed.

Python Version Differences:

Different versions of Python might handle SSL verification differently. Ensure all machines are using the same Python version. Environment Configuration:

Differences in environment configuration, such as proxy settings or environment variables, can affect SSL verification.

Network Differences:

Some networks might have additional SSL inspection or restrictions that could interfere with SSL verification.

Solutions Ensure Root Certificates are Up-to-Date:

On systems where SSL verification fails, update the root certificates. macOS: Run the Install Certificates.command script found in the Python installation directory. Windows: Ensure that the system's root certificates are up-to-date. You can also manually update the certificates by using the certifi package.

pip install --upgrade certifi itself is giving some errors.

pip install --upgrade certifi Requirement already satisfied: certifi in c:\program files\python310\lib\site-packages (2024.7.4) WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:997)'))': /simple/certifi/ WARNING: Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:997)'))': /simple/certifi/ WARNING: Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:997)'))': /simple/certifi/ WARNING: Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:997)'))': /simple/certifi/ WARNING: Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:997)'))': /simple/certifi/ Could not fetch URL https://pypi.org/simple/certifi/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): Max retries exceeded with url: /simple/certifi/ (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:997)'))) - skipping

hemangshah36 commented 1 week ago

If you are trying with 3.12 or higher versions of python. Consider trying using 3.10 or 3.11 versions. As previously similar error got encountered got fixed. While migrating to Python 3.11 might provide a temporary workaround

A better approach is to ensure SSL handling is robust and compatible with the latest standards. This includes: Updating root certificates. Explicitly configuring SSL contexts to use certifi. Ensuring that all dependencies are up-to-date.

Something like


import http.client
import ssl
import certifi  

@brlogin_bp.route('/<broker>/loginflow', methods=['POST','GET'])
@limiter.limit(LOGIN_RATE_LIMIT_MIN)
@limiter.limit(LOGIN_RATE_LIMIT_HOUR)
def broker_loginflow(broker):
    if broker == 'kotak':
        mobilenumber = request.form.get('mobilenumber')
        password = request.form.get('password')

        # Create an SSL context using certifi
        context = ssl.create_default_context(cafile=certifi.where())

        conn = http.client.HTTPSConnection("gw-napi.kotaksecurities.com", context=context)
        payload = json.dumps({
            "mobileNumber": mobilenumber,
            "password": password
        })
        api_secret = get_broker_api_secret()
        headers = {
            'accept': '*/*',
            'Content-Type': 'application/json',
            'Authorization': f'Bearer {api_secret}'
        }
        conn.request("POST", "/login/1.0/login/v2/validate", payload, headers)
        res = conn.getresponse()
        data = res.read().decode("utf-8")
        data_dict = json.loads(data)

        token = data_dict['data']['token']
        sid = data_dict['data']['sid']
        decode_jwt = jwt.decode(token, options={"verify_signature": False})
        userid = decode_jwt.get("sub")

        para = {
            "token": token,
            "sid": sid,
            "userid": userid
        }
        getKotakOTP(userid, api_secret)
        return render_template('kotakotp.html', para=para)

Unfortunately, not working.

marketcalls commented 1 week ago

@sk0024 : Try this procedure. If this works for you let me know

Kotak NEO API - OpenAlgo Integration Procedure https://www.youtube.com/watch?v=uw2PQOEBiV8

@hemangshah36 And for SSL Certificate Issue : Iam looking into it. Will issue a fix shortly after testing in 3.12 python version.

yadu12342q commented 1 week ago

Thanks sir @marketcalls working now

hemangshah36 commented 1 week ago

@yadu12342q Can you please clarify what you have modified and how it got working.

@marketcalls - I updated brlogin.py as under.

Now, I started getting OTP from Kotak.

However, after entering correct OTP and submitting, it again directs to Broker Authentication Page.

Terminal message: The Broker is kotak Authentication error: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1006) 127.0.0.1 - - [19/Jul/2024 01:28:32] "POST /kotak/callback HTTP/1.1" 200 - 127.0.0.1 - - [19/Jul/2024 01:28:32] "GET /static/favicon/apple-touch-icon.png HTTP/1.1" 304 - 127.0.0.1 - - [19/Jul/2024 01:28:32] "GET /static/images/thumbs-up.png HTTP/1.1" 304 -

The brlogin.py is as under:

`from flask import Blueprint, request, redirect, url_for, render_template, session, jsonify, make_response from flask import current_app as app from limiter import limiter # Import the limiter instance from utils.config import get_broker_api_key, get_broker_api_secret, get_login_rate_limit_min, get_login_rate_limit_hour from utils.auth_utils import handle_auth_success, handle_auth_failure import http.client import json import jwt import ssl import certifi

BROKER_API_KEY = get_broker_api_key() LOGIN_RATE_LIMIT_MIN = get_login_rate_limit_min() LOGIN_RATE_LIMIT_HOUR = get_login_rate_limit_hour()

brlogin_bp = Blueprint('brlogin', name, url_prefix='/')

@brlogin_bp.errorhandler(429) def ratelimit_handler(e): return jsonify(error="Rate limit exceeded"), 429

@brlogin_bp.route('//callback', methods=['POST','GET']) @limiter.limit(LOGIN_RATE_LIMIT_MIN) @limiter.limit(LOGIN_RATE_LIMIT_HOUR) def broker_callback(broker,para=None): print(f'Broker is {broker}') if session.get('logged_in'):

Store broker in session and g

    session['broker'] = broker
    return redirect(url_for('dashboard_bp.dashboard'))

broker_auth_functions = app.broker_auth_functions
auth_function = broker_auth_functions.get(f'{broker}_auth')

if not auth_function:
    return jsonify(error="Broker authentication function not found."), 404

if broker == 'fivepaisa':
    if request.method == 'GET':
        if 'user' not in session:
            return redirect(url_for('auth.login'))
        return render_template('5paisa.html')

    elif request.method == 'POST':
        clientcode = request.form.get('clientid')
        broker_pin = request.form.get('pin')
        totp_code = request.form.get('totp')

        auth_token, error_message = auth_function(clientcode, broker_pin, totp_code)
        forward_url = '5paisa.html'

elif broker == 'angel':
    if request.method == 'GET':
        if 'user' not in session:
            return redirect(url_for('auth.login'))
        return render_template('angel.html')

    elif request.method == 'POST':
        clientcode = request.form.get('clientid')
        broker_pin = request.form.get('pin')
        totp_code = request.form.get('totp')
        auth_token, error_message = auth_function(clientcode, broker_pin, totp_code)
        forward_url = 'angel.html'
elif broker=='fyers':
    code = request.args.get('auth_code')
    print(f'The code is {code}')
    auth_token, error_message = auth_function(code)
    forward_url = 'broker.html'

elif broker=='icici':
    full_url = request.full_path
    print(f'Full URL: {full_url}') 
    code = request.args.get('apisession')
    print(f'The code is {code}')
    auth_token, error_message = auth_function(code)
    forward_url = 'broker.html'

elif broker=='dhan':
    code = 'dhan'
    print(f'The code is {code}')
    auth_token, error_message = auth_function(code)
    forward_url = 'broker.html'

elif broker=='kotak':
    print(f"The Broker is {broker}")
    if request.method == 'GET':
        if 'user' not in session:
            return redirect(url_for('auth.login'))
        return render_template('kotak.html')

    elif request.method == 'POST':
        otp = request.form.get('otp')
        token = request.form.get('token')
        sid = request.form.get('sid')
        userid = request.form.get('userid')
        api_secret = get_broker_api_secret()

        auth_token, error_message = auth_function(otp,token,sid,userid,api_secret)

        forward_url = 'kotak.html'

else:
    code = request.args.get('code') or request.args.get('request_token')
    print(f'The code is {code}')
    auth_token, error_message = auth_function(code)
    forward_url = 'broker.html'

if auth_token:
    # Store broker in session
    session['broker'] = broker
    print(f'Connected broker: {broker}')
    if broker == 'zerodha':
        #token = request.args.get('request_token')
        auth_token = f'{BROKER_API_KEY}:{auth_token}'
    if broker == 'dhan':
        #token = request.args.get('request_token')
        auth_token = f'{auth_token}'
    return handle_auth_success(auth_token, session['user'],broker)
else:
    return handle_auth_failure(error_message, forward_url=forward_url)

import http.client import ssl import certifi

@brlogin_bp.route('//loginflow', methods=['POST','GET']) @limiter.limit(LOGIN_RATE_LIMIT_MIN) @limiter.limit(LOGIN_RATE_LIMIT_HOUR) def broker_loginflow(broker): if broker == 'kotak': mobilenumber = request.form.get('mobilenumber') password = request.form.get('password')

    # Create an SSL context using certifi
    context = ssl.create_default_context(cafile=certifi.where())

    conn = http.client.HTTPSConnection("gw-napi.kotaksecurities.com", context=context)
    payload = json.dumps({
        "mobileNumber": mobilenumber,
        "password": password
    })
    api_secret = get_broker_api_secret()
    headers = {
        'accept': '*/*',
        'Content-Type': 'application/json',
        'Authorization': f'Bearer {api_secret}'
    }
    conn.request("POST", "/login/1.0/login/v2/validate", payload, headers)
    res = conn.getresponse()
    data = res.read().decode("utf-8")
    data_dict = json.loads(data)

    token = data_dict['data']['token']
    sid = data_dict['data']['sid']
    decode_jwt = jwt.decode(token, options={"verify_signature": False})
    userid = decode_jwt.get("sub")

    para = {
        "token": token,
        "sid": sid,
        "userid": userid
    }
    getKotakOTP(userid, api_secret)
    return render_template('kotakotp.html', para=para)

def getKotakOTP(userid,token):

Create an SSL context using certifi

context = ssl.create_default_context(cafile=certifi.where())
conn = http.client.HTTPSConnection("gw-napi.kotaksecurities.com", context=context)
payload = json.dumps({
"userId": userid,
"sendEmail": True,
"isWhitelisted": True
})
headers = {
'accept': '*/*',
'Content-Type': 'application/json',
'Authorization': f'Bearer {token}'
}
conn.request("POST", "/login/1.0/login/otp/generate", payload, headers)
res = conn.getresponse()
data = res.read()

return 'success'`
sk0024 commented 1 week ago

PS C:\Users\Admin\Desktop\Testalgo> git clone https://github.com/marketcalls/openalgo Cloning into 'openalgo'... remote: Enumerating objects: 2395, done. remote: Counting objects: 100% (413/413), done. remote: Compressing objects: 100% (127/127), done. remote: Total 2395 (delta 319), reused 326 (delta 280), pack-reused 1982 Receiving objects: 100% (2395/2395), 3.36 MiB | 617.00 KiB/s, done. Resolving deltas: 100% (1443/1443), done. PS C:\Users\Admin\Desktop\Testalgo> cd openalgo PS C:\Users\Admin\Desktop\Testalgo\openalgo> pip install -r requirements.txt Requirement already satisfied: bcrypt==4.1.3 in c:\users\admin\appdata\local\packages\pythonsoftwarefoundation.python.3.10_qbz5n2kfra8p0\localcache\local-packages\python310\site-packages (from -r requirements.txt (line 1)) (4.1.3) Requirement already satisfied: bidict==0.23.1 in c:\users\admin\appdata\local\packages\pythonsoftwarefoundation.python.3.10_qbz5n2kfra8p0\localcache\local-packages\python310\site-packages (from -r requirements.txt (line 2)) (0.23.1) Requirement already satisfied: blinker==1.8.2 in c:\users\admin\appdata\local\packages\pythonsoftwarefoundation.python.3.10_qbz5n2kfra8p0\localcache\local-packages\python310\site-packages (from -r requirements.txt (line 3)) (1.8.2) Requirement already satisfied: cachetools==5.3.3 in c:\users\admin\appdata\local\packages\pythonsoftwarefoundation.python.3.10_qbz5n2kfra8p0\localcache\local-packages\python310\site-packages (from -r requirements.txt (line 4)) (5.3.3) Requirement already satisfied: certifi==2024.7.4 in c:\users\admin\appdata\local\packages\pythonsoftwarefoundation.python.3.10_qbz5n2kfra8p0\localcache\local-packages\python310\site-packages (from -r requirements.txt (line 5)) (2024.7.4) Requirement already satisfied: charset-normalizer==3.3.2 in c:\users\admin\appdata\local\packages\pythonsoftwarefoundation.python.3.10_qbz5n2kfra8p0\localcache\local-packages\python310\site-packages (from -r requirements.txt (line 6)) (3.3.2) Requirement already satisfied: click==8.1.7 in c:\users\admin\appdata\local\packages\pythonsoftwarefoundation.python.3.10_qbz5n2kfra8p0\localcache\local-packages\python310\site-packages (from -r requirements.txt (line 7)) (8.1.7) Requirement already satisfied: Deprecated==1.2.14 in c:\users\admin\appdata\local\packages\pythonsoftwarefoundation.python.3.10_qbz5n2kfra8p0\localcache\local-packages\python310\site-packages (from -r requirements.txt (line 8)) (1.2.14) Requirement already satisfied: Flask==3.0.3 in c:\users\admin\appdata\local\packages\pythonsoftwarefoundation.python.3.10_qbz5n2kfra8p0\localcache\local-packages\python310\site-packages (from -r requirements.txt (line 9)) (3.0.3) Requirement already satisfied: Flask-Bcrypt==1.0.1 in c:\users\admin\appdata\local\packages\pythonsoftwarefoundation.python.3.10_qbz5n2kfra8p0\localcache\local-packages\python310\site-packages (from -r requirements.txt (line 10)) (1.0.1) Requirement already satisfied: Flask-Limiter==3.7.0 in c:\users\admin\appdata\local\packages\pythonsoftwarefoundation.python.3.10_qbz5n2kfra8p0\localcache\local-packages\python310\site-packages (from -r requirements.txt (line 11)) (3.7.0) Requirement already satisfied: Flask-SocketIO==5.3.6 in c:\users\admin\appdata\local\packages\pythonsoftwarefoundation.python.3.10_qbz5n2kfra8p0\localcache\local-packages\python310\site-packages (from -r requirements.txt (line 12)) (5.3.6) Requirement already satisfied: Flask-SQLAlchemy==3.1.1 in c:\users\admin\appdata\local\packages\pythonsoftwarefoundation.python.3.10_qbz5n2kfra8p0\localcache\local-packages\python310\site-packages (from -r requirements.txt (line 13)) (3.1.1) Requirement already satisfied: h11==0.14.0 in c:\users\admin\appdata\local\packages\pythonsoftwarefoundation.python.3.10_qbz5n2kfra8p0\localcache\local-packages\python310\site-packages (from -r requirements.txt (line 14)) (0.14.0) Requirement already satisfied: idna==3.7 in c:\users\admin\appdata\local\packages\pythonsoftwarefoundation.python.3.10_qbz5n2kfra8p0\localcache\local-packages\python310\site-packages (from -r requirements.txt (line 15)) (3.7) Requirement already satisfied: importlib_resources==6.4.0 in c:\users\admin\appdata\local\packages\pythonsoftwarefoundation.python.3.10_qbz5n2kfra8p0\localcache\local-packages\python310\site-packages (from -r requirements.txt (line 16)) (6.4.0) Requirement already satisfied: itsdangerous==2.2.0 in c:\users\admin\appdata\local\packages\pythonsoftwarefoundation.python.3.10_qbz5n2kfra8p0\localcache\local-packages\python310\site-packages (from -r requirements.txt (line 17)) (2.2.0) Requirement already satisfied: Jinja2==3.1.4 in c:\users\admin\appdata\local\packages\pythonsoftwarefoundation.python.3.10_qbz5n2kfra8p0\localcache\local-packages\python310\site-packages (from -r requirements.txt (line 18)) (3.1.4) Requirement already satisfied: limits==3.13.0 in c:\users\admin\appdata\local\packages\pythonsoftwarefoundation.python.3.10_qbz5n2kfra8p0\localcache\local-packages\python310\site-packages (from -r requirements.txt (line 19)) (3.13.0) Requirement already satisfied: markdown-it-py==3.0.0 in c:\users\admin\appdata\local\packages\pythonsoftwarefoundation.python.3.10_qbz5n2kfra8p0\localcache\local-packages\python310\site-packages (from -r requirements.txt (line 20)) (3.0.0) Requirement already satisfied: MarkupSafe==2.1.5 in c:\users\admin\appdata\local\packages\pythonsoftwarefoundation.python.3.10_qbz5n2kfra8p0\localcache\local-packages\python310\site-packages (from -r requirements.txt (line 21)) (2.1.5) Requirement already satisfied: mdurl==0.1.2 in c:\users\admin\appdata\local\packages\pythonsoftwarefoundation.python.3.10_qbz5n2kfra8p0\localcache\local-packages\python310\site-packages (from -r requirements.txt (line 22)) (0.1.2) Requirement already satisfied: numpy==1.26.1 in c:\users\admin\appdata\local\packages\pythonsoftwarefoundation.python.3.10_qbz5n2kfra8p0\localcache\local-packages\python310\site-packages (from -r requirements.txt (line 23)) (1.26.1) Requirement already satisfied: openalgo==1.0.2 in c:\users\admin\appdata\local\packages\pythonsoftwarefoundation.python.3.10_qbz5n2kfra8p0\localcache\local-packages\python310\site-packages (from -r requirements.txt (line 24)) (1.0.2) Requirement already satisfied: ordered-set==4.1.0 in c:\users\admin\appdata\local\packages\pythonsoftwarefoundation.python.3.10_qbz5n2kfra8p0\localcache\local-packages\python310\site-packages (from -r requirements.txt (line 25)) (4.1.0) Requirement already satisfied: packaging==24.1 in c:\users\admin\appdata\local\packages\pythonsoftwarefoundation.python.3.10_qbz5n2kfra8p0\localcache\local-packages\python310\site-packages (from -r requirements.txt (line 26)) (24.1) Requirement already satisfied: pandas==2.2.2 in c:\users\admin\appdata\local\packages\pythonsoftwarefoundation.python.3.10_qbz5n2kfra8p0\localcache\local-packages\python310\site-packages (from -r requirements.txt (line 27)) (2.2.2) Requirement already satisfied: Pygments==2.18.0 in c:\users\admin\appdata\local\packages\pythonsoftwarefoundation.python.3.10_qbz5n2kfra8p0\localcache\local-packages\python310\site-packages (from -r requirements.txt (line 28)) (2.18.0) Requirement already satisfied: PyJWT==2.8.0 in c:\users\admin\appdata\local\packages\pythonsoftwarefoundation.python.3.10_qbz5n2kfra8p0\localcache\local-packages\python310\site-packages (from -r requirements.txt (line 29)) (2.8.0) Requirement already satisfied: pyngrok==7.1.6 in c:\users\admin\appdata\local\packages\pythonsoftwarefoundation.python.3.10_qbz5n2kfra8p0\localcache\local-packages\python310\site-packages (from -r requirements.txt (line 30)) (7.1.6) Requirement already satisfied: pyotp==2.9.0 in c:\users\admin\appdata\local\packages\pythonsoftwarefoundation.python.3.10_qbz5n2kfra8p0\localcache\local-packages\python310\site-packages (from -r requirements.txt (line 31)) (2.9.0) Requirement already satisfied: python-dateutil==2.9.0.post0 in c:\users\admin\appdata\local\packages\pythonsoftwarefoundation.python.3.10_qbz5n2kfra8p0\localcache\local-packages\python310\site-packages (from -r requirements.txt (line 32)) (2.9.0.post0) Requirement already satisfied: python-dotenv==1.0.1 in c:\users\admin\appdata\local\packages\pythonsoftwarefoundation.python.3.10_qbz5n2kfra8p0\localcache\local-packages\python310\site-packages (from -r requirements.txt (line 33)) (1.0.1) Requirement already satisfied: python-engineio==4.9.1 in c:\users\admin\appdata\local\packages\pythonsoftwarefoundation.python.3.10_qbz5n2kfra8p0\localcache\local-packages\python310\site-packages (from -r requirements.txt (line 34)) (4.9.1) Requirement already satisfied: python-socketio==5.11.3 in c:\users\admin\appdata\local\packages\pythonsoftwarefoundation.python.3.10_qbz5n2kfra8p0\localcache\local-packages\python310\site-packages (from -r requirements.txt (line 35)) (5.11.3) Requirement already satisfied: pytz==2024.1 in c:\users\admin\appdata\local\packages\pythonsoftwarefoundation.python.3.10_qbz5n2kfra8p0\localcache\local-packages\python310\site-packages (from -r requirements.txt (line 36)) (2024.1) Requirement already satisfied: PyYAML==6.0.1 in c:\users\admin\appdata\local\packages\pythonsoftwarefoundation.python.3.10_qbz5n2kfra8p0\localcache\local-packages\python310\site-packages (from -r requirements.txt (line 37)) (6.0.1) Requirement already satisfied: requests==2.32.3 in c:\users\admin\appdata\local\packages\pythonsoftwarefoundation.python.3.10_qbz5n2kfra8p0\localcache\local-packages\python310\site-packages (from -r requirements.txt (line 38)) (2.32.3) Requirement already satisfied: rich==13.7.1 in c:\users\admin\appdata\local\packages\pythonsoftwarefoundation.python.3.10_qbz5n2kfra8p0\localcache\local-packages\python310\site-packages (from -r requirements.txt (line 39)) (13.7.1) Requirement already satisfied: setuptools==70.3.0 in c:\users\admin\appdata\local\packages\pythonsoftwarefoundation.python.3.10_qbz5n2kfra8p0\localcache\local-packages\python310\site-packages (from -r requirements.txt (line 40)) (70.3.0) Requirement already satisfied: simple-websocket==1.0.0 in c:\users\admin\appdata\local\packages\pythonsoftwarefoundation.python.3.10_qbz5n2kfra8p0\localcache\local-packages\python310\site-packages (from -r requirements.txt (line 41)) (1.0.0) Requirement already satisfied: six==1.16.0 in c:\users\admin\appdata\local\packages\pythonsoftwarefoundation.python.3.10_qbz5n2kfra8p0\localcache\local-packages\python310\site-packages (from -r requirements.txt (line 42)) (1.16.0) Requirement already satisfied: SQLAlchemy==2.0.31 in c:\users\admin\appdata\local\packages\pythonsoftwarefoundation.python.3.10_qbz5n2kfra8p0\localcache\local-packages\python310\site-packages (from -r requirements.txt (line 43)) (2.0.31) Requirement already satisfied: typing_extensions==4.12.2 in c:\users\admin\appdata\local\packages\pythonsoftwarefoundation.python.3.10_qbz5n2kfra8p0\localcache\local-packages\python310\site-packages (from -r requirements.txt (line 44)) (4.12.2) Requirement already satisfied: tzdata==2024.1 in c:\users\admin\appdata\local\packages\pythonsoftwarefoundation.python.3.10_qbz5n2kfra8p0\localcache\local-packages\python310\site-packages (from -r requirements.txt (line 45)) (2024.1) Requirement already satisfied: urllib3==2.2.2 in c:\users\admin\appdata\local\packages\pythonsoftwarefoundation.python.3.10_qbz5n2kfra8p0\localcache\local-packages\python310\site-packages (from -r requirements.txt (line 46)) (2.2.2) Requirement already satisfied: Werkzeug==3.0.3 in c:\users\admin\appdata\local\packages\pythonsoftwarefoundation.python.3.10_qbz5n2kfra8p0\localcache\local-packages\python310\site-packages (from -r requirements.txt (line 47)) (3.0.3) Requirement already satisfied: wheel==0.43.0 in c:\users\admin\appdata\local\packages\pythonsoftwarefoundation.python.3.10_qbz5n2kfra8p0\localcache\local-packages\python310\site-packages (from -r requirements.txt (line 48)) (0.43.0) Requirement already satisfied: wrapt==1.16.0 in c:\users\admin\appdata\local\packages\pythonsoftwarefoundation.python.3.10_qbz5n2kfra8p0\localcache\local-packages\python310\site-packages (from -r requirements.txt (line 49)) (1.16.0) Requirement already satisfied: wsproto==1.2.0 in c:\users\admin\appdata\local\packages\pythonsoftwarefoundation.python.3.10_qbz5n2kfRequirement already satisfied: zipp==3.19.2 in c:\users\admin\appdata\local\packages\pythonsoftwarefoundation.python.3.10_qbz5n2kfra8p0\localcache\local-packages\python310\site-packages (from -r requirements.txt (line 51)) (3.19.2) Requirement already satisfied: colorama in c:\users\admin\appdata\local\packages\pythonsoftwarefoundation.python.3.10_qbz5n2kfra8p0\localcache\local-packages\python310\site-packages (from click==8.1.7->-r requirements.txt (line 7)) (0.4.6) Requirement already satisfied: greenlet!=0.4.17 in c:\users\admin\appdata\local\packages\pythonsoftwarefoundation.python.3.10_qbz5n2kfra8p0\localcache\local-packages\python310\site-packages (from SQLAlchemy==2.0.31->-r requirements.txt (line 43)) (3.0.3)

[notice] A new release of pip is available: 23.0.1 -> 24.1.2 [notice] To update, run: C:\Users\Admin\AppData\Local\Microsoft\WindowsApps\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\python.exe -m pip install --upgrade pip PS C:\Users\Admin\Desktop\Testalgo\openalgo> python app.py Initializing Auth DB Initializing User DB Initializing Master Contract DB Initializing API Log DB

sk0024 commented 1 week ago

please advise ........earlier used python 3.12 latest but currently installed python 3.10 and getting same error

marketcalls commented 1 week ago

@sk0024 : Try this procedure. If this works for you let me know

Kotak NEO API - OpenAlgo Integration Procedure https://www.youtube.com/watch?v=uw2PQOEBiV8

Already we sorted similar issue in our discord community. Avoid sharing the same API credentials in multiple algo applications.

marketcalls commented 1 week ago

@hemangshah36 your issue is different from @sk0024 and @yadu12342q I will issue a fix shortly.

marketcalls commented 1 week ago

@sk0024 and @yadu12342q : Iam glad that both of your login issues got resolved and @hemangshah36 : Iam marking this SSL Verification issue as a Bug. Will try to issue a fix which very few issuers who are having certificate mismatch are getting this error. Will try for a workaround.

hemangshah36 commented 1 week ago

@marketcalls Thanks for prompt updates. However, I am wondering how only few people are facing issue and it's working for for others. Is this related to my OS? I'm using AWS windows server instance.

On Fri, 19 Jul 2024 at 9:24 pm, @.***> wrote:

@sk0024 and @yadu12342q : Iam glad that both of your login issues got resolved and @hemangshah36 : Iam marking this SSL Verification issue as a Bug. Will try to issue a fix which very few issuers who are having certificate mismatch are getting this error. Will try for a workaround.

— Reply to this email directly, view it on GitHub, or unsubscribe. You are receiving this because you were mentioned.Message ID: @.***>

hemangshah36 commented 1 week ago

@marketcalls

FINAL UPDATE:

I was earlier trying on newly AWS Windows Server 2022 instance and getting SSL related errors.

I decided to install on my laptop having Windows 10 OS. I installed everything (Python latest version python-3.12.4-amd64) and without doing any tweak, Kotak started working.

Then, I decided to again check on my AWS Windows Server 2022.

**I have run following 2 commands using Command Prompt with Admin Access.

Update Certificates Using Certutil:

Run the following command to update the root certificates:

certutil -generateSSTFromWU roots.sst

Once the roots.sst file is generated, run the following command to install the certificates:

certutil -addstore -f root roots.sst**

And it started working.

Finally, to re-check, I have uninstalled everything and rebooted server. Install everything from stretch (Python latest version python-3.12.4-amd64). And it went well. Kotak working successfully without any further tweaks.

Those who are getting ssl related errors on Windows OS are advised to check above Windows Command Prompt actions once.

@marketcalls - It's up to you how to handle this thread further. Thanking you a lot once again and wish you best in your future developments.

marketcalls commented 1 week ago

@hemangshah36

Thank you for the detailed update and for sharing the solution that worked for you.

Your methodical approach and the steps you shared will undoubtedly help others facing similar issues. I recommend any user experiencing SSL errors on Windows OS to try these Command Prompt actions as you suggested.

I’ll keep this thread open for a while longer to see if anyone else has feedback or similar experiences. Your contribution is greatly appreciated, and we wish you continued success with your developments.

Thank you once again for your detailed feedback.