FYERS API Utilize Free of Cost to Automate Trades in Python


Open Fyers Trading Account Please Click Here.



CMD pip Installation Type and Enter: pip install fyers_api



Please Follow the Above Video then go for the Code Below for generation of access token and Programmatic Trading:


Generate Token:


from fyers_api import accessToken
app_id = open('app_id.txt','r').read()
app_secret = open('app_secret.txt','r').read()
app_session = accessToken.SessionModel(app_id, app_secret)
response = app_session.auth()
print(response)

Place Order:


from fyers_api import fyersModel
token="Your Token "
is_async = False 
fyers = fyersModel.FyersModel(is_async)
print(fyers.place_orders(
token = token,
data = {
"symbol" : "NSE:TATAMOTORS-EQ",
"qty" : 1,
"type" : 2,
"side" : 1,
"productType" : "INTRADAY",
"limitPrice" : 0,
"stopPrice" : 0,
"disclosedQty" : 0,
"validity" : "DAY",
"offlineOrder" : "False",
"stopLoss" : 0,
"takeProfit" : 0
}
))

Generate access token directly from the web browser:



import sys
import webbrowser
from fyers_api import accessToken


def getToken(app_id, app_secret):
 """
 The variable `generateTokenUrl` will have a url like 
 https://api.fyers.in/api/v1/genrateToken?authorization_code=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqaGdqZzg3NiQ3ODVidjVANjQ3NTZ2NSZnNyM2OTg3Njc5OHhkIjoiWElHVFVYVjBSSSIsImV4cCI6MTU2MTU5NzM5Ny41NjQxNTV9.Agl-UUs63NforrUEdbG7YUlPcbFXu9hLYm4akGuIBkU&appId=Your_app_id"
  1. This function open this url in the browser. 
  2. This will ask you to login and will ask you to approve the app if it is not approved already.
  3. Once that is done, it will redirect to a url (added while app creation) with the access_token. The url will look like
     http://localhost:5000?access_token=gAAAAABc3Sh9QpE5mNx2mSz6vvvT29SAsELqkfbKQKa2977zHw3NdPBhe6jAZCBumHvYUum87j53-AzMEPXMjQw31wkRviZ1TdM5OimgTYWEEorWDmWuHnY=&user_id=FYXXXX
  4. You have to take the access_token from the url and use that token in your going forward.
 """
 appSession = accessToken.SessionModel(app_id,app_secret)

 response = appSession.auth()

 if response["code"] != 200:
  print (response)
  sys.exit()

 auth_code = response["data"]["authorization_code"]

 appSession.set_token(auth_code)

 generateTokenUrl = appSession.generate_token()
 webbrowser.open(generateTokenUrl,new=1)





def main():
 app_id = open('app_id.txt','r').read()
 app_secret = open('app_secret.txt','r').read()
 getToken(app_id, app_secret)

if __name__ == '__main__':
 main()


FYERS API V2:

CMD:pip install fyers-apiv2



Instructions from the above video and code we are able to generate access token from fyers api v1 but to generate access token in api v2 we need to follow different syntax in python but instructions will be the same as stated in the video the most important part is that we need to create an app under api version 2.If you don't have an account please do Open Fyers Trading Account for that Please Click Here.  After Opening Fyers trading account from the link please visit https://myapi.fyers.in/dashboard/  When you click on api version 2 the 2 most important thing is app name and redirect url which you can choose of your choice eg. ABCD as app name and in redirect url it can be your choice as well but it should be perfect and that syntax should be followed in every redirect url in your python code while trading i'm using documentation url fyers represent each and every syntax as well usage that will be https://myapi.fyers.in/docs/ after this maintain a description and go ahead with app permissions and accept the API usage terms and conditions as well as app permissions and go ahead with create app click on them and your fyers app is ready for trading in python and meantime don't worry about the inactive status after when you start with python generating access token the app get in active status.
After the app is created you will get an App id and Secret id copy them and store them in a text file and required folder for later access now if you check with api docs there is a list of codes in generation of access token in which we can skip few steps in which we need a url which gives a auth_code from web browser for that reason please follow the url as such 'https://api.fyers.in/api/v2/generate-authcode?client_id=App_id&redirect_uri=https://myapi.fyers.in/docs/&response_type=code&state=None' now the client id will be yours app id which you received after creation of app and redirect url as of your choice or you can use the redirect url of fyers docs as well.
Now put the auth code you received from web browser in python code and generate the access token and saved them in required text file and folder for later access.If you face any error regarding api access it might be issue due to older installation so please completely wipe them by utilizing pip uninstall in cmd and then go directly installation with pip install fyers-apiv2 and follow the below code as follows.
  
from fyers_api import fyersModel
from fyers_api import accessToken  
client_id='your_app_id'
secret_key='your_secret_id'
redirect_uri='https://myapi.fyers.in/docs/'
session=accessToken.SessionModel(client_id=client_id,
secret_key=secret_key,redirect_uri=redirect_uri, 
response_type='code',grant_type='authorization_code') 
auth_code='you received from web browser'
session.set_token(auth_code)
response = session.generate_token()
access_token = response["access_token"]
print(access_token)  

After generation of access token things will get simpler just add the token and client id in required field and call the model and utilize them for placing orders and accessing the details of postions,trades and data as well for writing strategies and implementing strategy as follows.
  
from fyers_api import fyersModel
client_id='your_app_id'
token='your_token'
fyers = fyersModel.FyersModel(client_id=client_id, token=token,log_path='C:/Users/.../Desktop/current_directory')
print(fyers.funds())


Fetch Full Market Quotes Utilizing Fyers API V2:




from fyers_api import fyersModel
client_id=open('app_id.txt','r').read()
token=open('access_token.txt','r').read().strip()
fyers=fyersModel.FyersModel(client_id=client_id,token=token,log_path='C:/Users/.../Desktop/current_directory')
symbol={'symbols':'MCX:SILVERMIC21NOVFUT'}
last_price=fyers.quotes(symbol)['d'][0]['v']['lp']
print(last_price)


Different Symbols Input Syntax:


Nifty Index:{'symbols':'NSE:NIFTY50-INDEX'}

Banknifty Index:{'symbols':'NSE:BANKNIFTY-INDEX'}

Cash:{'symbols':'NSE:TATAMOTORS-EQ'}

Future:{'symbols':'NSE:TATAMOTORS21OCTFUT'}

Options Monthly:{'symbols':'NSE:BANKNIFTY21OCT41800CE'}

Options Weekly:{'symbols':'NSE:BANKNIFTY21N0341800CE'}

Commodity:{'symbols':'MCX:SILVERMIC21NOVFUT'}


Full Market Quotes OUTPUT:  {'s': 'ok', 'd': [{'n': 'MCX:SILVERMIC21NOVFUT', 's': 'ok', 'v': {'ch': 486.0, 'chp': 0.74, 'lp': 66295.0, 'spread': 10.0, 'ask': 66297.0, 'bid': 66287.0, 'open_price': 65990.0, 'high_price': 66529.0, 'low_price': 65784.0, 'prev_close_price': 65809.0, 'volume': 111252, 'short_name': 'SILVERMIC21NOVFUT', 'exchange': 'MCX', 'description': 'MCX:SILVERMIC21NOVFUT', 'original_name': 'MCX:SILVERMIC21NOVFUT', 'symbol': 'MCX:SILVERMIC21NOVFUT', 'fyToken': '1120211130228225', 'tt': 1635120000, 'cmd': {'t': 1635172620, 'o': 66301.0, 'h': 66314.0, 'l': 66290.0, 'c': 66295.0, 'v': 171, 'tf': '20:7'}}}]}


WebSocket Streaming Market Data Update Live Feed Fyers API V2 in Python:


CMD:pip install fyers-apiv2==2.0.4



from fyers_api.websocket import ws
client_id=open('app_id.txt','r').read()
token=open('access_token.txt','r').read().strip()
access_token = client_id+":"+token
data_type = 'symbolData'
symbol = ['NSE:TATAMOTORS-EQ','NSE:ITC-EQ']
def custom_message(ticks):
    print(ticks.response)

ws.FyersSocket.websocket_data = custom_message
fs = ws.FyersSocket(access_token, data_type,symbol)
fs.subscribe()


Market Data Output:  [{'symbol': 'NSE:TATAMOTORS-EQ', 'timestamp': 1637048645, 'fyCode': 7208, 'fyFlag': 2, 'pktLen': 200, 'ltp': 525.2, 'open_price': 506.9, 'high_price': 525.4, 'low_price': 506.2, 'close_price': 505.45, 'min_open_price': 525.0, 'min_high_price': 525.4, 'min_low_price': 524.9, 'min_close_price': 525.2, 'min_volume': 187123, 'last_traded_qty': 100, 'last_traded_time': 1637048645, 'avg_trade_price': 51817, 'vol_traded_today': 36713417, 'tot_buy_qty': 14406277, 'tot_sell_qty': 3051701, 'market_pic': [{'price': 525.2, 'qty': 530, 'num_orders': 3}, {'price': 525.15, 'qty': 769, 'num_orders': 3}, {'price': 525.1, 'qty': 6221, 'num_orders': 8}, {'price': 525.04, 'qty': 3417, 'num_orders': 7}, {'price': 525.0, 'qty': 16171, 'num_orders': 23}, {'price': 525.4, 'qty': 5839, 'num_orders': 9}, {'price': 525.45, 'qty': 4464, 'num_orders': 42}, {'price': 525.5, 'qty': 37375, 'num_orders': 307}, {'price': 525.54, 'qty': 5665, 'num_orders': 43}, {'price': 525.6, 'qty': 7936, 'num_orders': 58}]}, {'symbol': 'NSE:ITC-EQ', 'timestamp': 1637048645, 'fyCode': 7208, 'fyFlag': 2, 'pktLen': 200, 'ltp': 237.7, 'open_price': 239.05, 'high_price': 239.65, 'low_price': 236.4, 'close_price': 238.1, 'min_open_price': 237.6, 'min_high_price': 237.7, 'min_low_price': 237.55, 'min_close_price': 237.7, 'min_volume': 413701, 'last_traded_qty': 40, 'last_traded_time': 1637048644, 'avg_trade_price': 23788, 'vol_traded_today': 10374568, 'tot_buy_qty': 1744272, 'tot_sell_qty': 5123208, 'market_pic': [{'price': 237.55, 'qty': 2293, 'num_orders': 9}, {'price': 237.5, 'qty': 5781, 'num_orders': 27}, {'price': 237.45, 'qty': 8089, 'num_orders': 26}, {'price': 237.4, 'qty': 19099, 'num_orders': 34}, {'price': 237.35, 'qty': 12722, 'num_orders': 24}, {'price': 237.7, 'qty': 3005, 'num_orders': 10}, {'price': 237.75, 'qty': 4475, 'num_orders': 27}, {'price': 237.8, 'qty': 9279, 'num_orders': 42}, {'price': 237.85, 'qty': 15223, 'num_orders': 32}, {'price': 237.9, 'qty': 29671, 'num_orders': 40}]}]


Order Placement Utilizing Fyers API V2 in Python:




from fyers_api import fyersModel
client_id=open('app_id.txt','r').read()
token=open('access_token.txt','r').read().strip()
fyers=fyersModel.FyersModel(client_id=client_id,token=token,log_path='Desktop/fyers')
order_id={
    'symbol':'NSE:BANKNIFTY21D0935000PE',
    'qty':25,
    'type':2,
    'side':1,
    'productType':'MARGIN',
    'limitPrice':0,
    'stopPrice':0,
    'validity':'DAY',
    'disclosedQty':0,
    'offlineOrder':'False',
    'stopLoss':0,
    'takeProfit':0}
order_id=fyers.place_order(order_id)['id']
orders={'id':order_id}
print(fyers.orderbook(orders))

If you registered under my referral for opening of trading account and after successful registration when you got the Client ID and Password applied for API activation and still it is not active please do visit to my whatsapp which is available in the video description will definitely help to get your API active.