0

I am tring creating a fyers) serive using flask. That can be used to do different openrations such as placing order or getting quite on demand.

In notebook mode the code is working fine. But with Flask I am ecountering error because it attempts to recreate the object.

Here is the Fyers code:

get_fyers.py

from fyers_api import fyersModel
from fyers_api import accessToken
from urllib import parse
import json


with open('fyers_creds.json', 'r') as openfile:
     creds = json.load(openfile)

client_id = creds['client_id']
secret_key = creds['secret_key']
redirect_uri = creds['redirect_uri']
response_type = creds['response_type']


### Get accessToken_code from file
f = open("authcodeUrl.txt", "r")
url = f.read()
url = parse.unquote(url)
accessToken_code = url.split(sep='&')[2].split(sep='=')[1]


### create a session
session=accessToken.SessionModel(client_id=client_id,secret_key=secret_key,redirect_uri=redirect_uri,response_type='code', grant_type='authorization_code')

def get_authcode():    
    response = session.generate_authcode()
    return response


def get_fyers():
    session.set_token(accessToken_code)
    response = session.generate_token()

    try:
        access_token = response["access_token"]
        fyers = fyersModel.FyersModel(client_id=client_id, token=access_token,log_path="./fyers.logs")
        return fyers
    except:
        return response
    

fyers = get_fyers()

Here is the Flask app code:

fyers_app.py

from flask import Flask, request, jsonify
from get_fyers import get_fyers

try:
    fyers = get_fyers()
    data = {"symbols":"NSE:SBIN-EQ"}
    
    ### Print last price
    print("SBIN-EQ LTP: ", fyers.quotes(data)['d'][0]['v']['lp'])

except:
    print("Error creating fyers object. ", fyers)

app = Flask(__name__)

@app.route('/')
def flask_status():
    return 'Flask server running ok.'

@app.route('/quotes', methods=['GET', 'POST'])
def get_quotes():
    data = request.json
    quotes = fyers.quotes(data)['d'][0]['v']['lp']
    ### Print last price
    return jsonify({"quotes" : quotes})

#@app.route('/renew_fyers')
#def renew_fyers():
#    fyers = get_fyers()
    #return 'renewing fyers object'



    

if __name__ == "__main__":
    app.run(host="0.0.0.0", port='5003', debug=True)
    

Output of the above flask server code:

root@41871270be22:/tradex/intraday# python3 fyers_app.py 
SBIN-EQ LTP:  568.7
 * Serving Flask app 'fyers_app'
 * Debug mode: on
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
 * Running on all addresses (0.0.0.0)
 * Running on http://127.0.0.1:5003
 * Running on http://172.20.0.2:5003
Press CTRL+C to quit
 * Restarting with stat
Error creating fyers object.  {'s': 'error', 'code': -413, 'message': 'Your auth code has expired. Please generate a new auth code'}
 * Debugger is active!
 * Debugger PIN: -----------

As you can see the output is printed once of fyers object is created. It sucessfully gets the ltp of SBIN-EQ. But after that it seems the fyers automatically tries to rerun and recreate the fyers object which doesn't work as we can only use the access code once to create fyers object from session.

In notebook mode the code is working fine or if I run the get_fyers code seperately like this:

fyers_test.py

from get_fyers import get_fyers
from time import sleep

fyers = get_fyers()
while True:
    try:
        data = {"symbols":"NSE:SBIN-EQ"}
        print("SBIN-EQ LTP: ", fyers.quotes(data)['d'][0]['v']['lp'])
        sleep(30)
    except:
        print(fyers)

This works fine and it will keep printing the data for 24 hours (until the session expires)

I want to also recreate the fyers object by calling a api (At time when token expires and craete new one and put it in the file)

Any help on resolving this will be appriciated.

I tried creating the Flask methods to create flask object which doesn't work as expected because you cannot access it outside the function. I am expecting to create a flask application that can run operations on demand.

  • use pyjwt module in python . it will help you if the access token is expired or not. whenever you initiate a fyers object check if access_token is not expired. regenerate one if expired and save it to a file and use it when ever necessary without calling api again and again. – P V Ajay Thota Aug 17 '23 at 23:32

0 Answers0