FYERS API Utilize Free of Cost to Automate Trades in Python

Candlestick Chart in Python:


Follow Instructions from the Above Video then go for the Code Input.


import pandas as pd
from fyers_api import fyersModel
from datetime import datetime,timedelta
import mplfinance as mpf
import warnings
warnings.simplefilter('ignore')
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/VIKASH/Desktop/fyers/tutorial')
days=1
symbol='NSE:TATAMOTORS-EQ'
interval='5'
now=datetime.now()
from_date=now-timedelta(days=days)
from_date=datetime.strftime(from_date,'%Y-%m-%d')
to_date=datetime.strftime(now,'%Y-%m-%d')
data={'symbol':symbol,
      'resolution':interval,
      'date_format':'1',
      'range_from':from_date,
      'range_to':to_date,
      'cont_flag':'1'
      }
df=pd.DataFrame(fyers.history(data=data)['candles'],columns=['date','open','high','low','close','volume'])
df['date']=pd.to_datetime(df['date'],unit='s')
df['date']=df['date'].dt.tz_localize('UTC').dt.tz_convert('Asia/Kolkata')
df['date']=df['date'].dt.tz_localize(None)
df=df.set_index(df['date'])
mpf.plot(df,type='candle',style='yahoo',mav=5,volume=True,title='CandleStick Chart',show_nontrading=False)
mpf.show()

Fyers API Historical Data Convert TimeStamp to DateTime:


Follow Instructions from the Above Video then go for the Code Input.


import pandas as pd
from fyers_api import fyersModel
from datetime import datetime,timedelta
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/VIKASH/Desktop/fyers/tutorial')
days=1
symbol='NSE:TATAMOTORS-EQ'
interval='1'
now=datetime.now()
from_date=now-timedelta(days=days)
from_date=datetime.strftime(from_date,'%Y-%m-%d')
to_date=datetime.strftime(now,'%Y-%m-%d')
data={'symbol':symbol,
      'resolution':interval,
      'date_format':'1',
      'range_from':from_date,
      'range_to':to_date,
      'cont_flag':'1'
      }
df=pd.DataFrame(fyers.history(data=data)['candles'],columns=['date','open','high','low','close','volume'])
df['date']=pd.to_datetime(df['date'],unit='s')
df['date']=df['date'].dt.tz_localize('UTC').dt.tz_convert('Asia/Kolkata')
df['date']=df['date'].dt.tz_localize(None)
df=df.set_index(df['date'])
print(df)

Fetch Current SENSEX & BANKEX Expiry Symbols Convert TimeStamp to DateTime:


Follow Instructions from the Above Video then go for the Code Input.


import pandas as pd
import requests
import io
import csv
spotname=['BANKEX','SENSEX']
weekly_expiry_index=[0,0]
response=requests.get('https://public.fyers.in/sym_details/BSE_FO.csv')
instruments=pd.read_csv(io.StringIO(response.text),header=None)
instruments.to_csv('BSE_FO.csv',index=False,header=None)
wr=csv.writer(open('FO.csv','w'))
for x in range(len(spotname)):
    instruments=pd.read_csv('BSE_FO.csv',header=None)
    instruments=instruments[instruments[13]==spotname[x]]
    instruments[8]=pd.to_datetime(instruments[8],unit='s')
    instruments[8]=instruments[8].dt.strftime('%Y-%m-%d')
    wei=instruments.sort_values(by=8).head(1)[8].iloc[weekly_expiry_index[x]]
    instruments=instruments[instruments[8]==wei]
    print(spotname[x],wei)
    instruments.to_csv('FO.csv',mode='a',index=False,header=None)

Fetch Historical Data OHLCV From Fyers API:


Follow the Instructions from Above Video then go for the Code Input.


import pandas as pd
from fyers_api import fyersModel
from datetime import datetime,timedelta
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/VIKASH/Desktop/fyers/tutorial')
days=1
symbol='NSE:FINNIFTY-INDEX'
interval='1'
now=datetime.now()
from_date=now-timedelta(days=days)
from_date=datetime.strftime(from_date,'%Y-%m-%d')
to_date=datetime.strftime(now,'%Y-%m-%d')
def historical_data(symbol,interval,from_date,to_date):
    data={'symbol':symbol,
          'resolution':interval,
          'date_format':'1',
          'range_from':from_date,
          'range_to':to_date,
          'cont_flag':'1'
          }
    response=pd.DataFrame(fyers.history(data=data)['candles'],columns=['D','O','H','L','C','V'])
    return response
hist=historical_data(symbol,interval,from_date,to_date)
print(hist)



https://youtube.com/shorts/PvC5DMrx6nY?feature=share

How to Place Market Bracket Order in Option Utilizing Fyers API:


Follow the Above Video then go for the Code Input Everything Follows the Same from the Below Code of Placing StopLoss Limit Orders Just for Few Changes Follow the Code After Print Statement Such as StopLoss and TakeProfit


stopLoss=2
takeProfit=10
order_id={
    'symbol':symbol_ce,
    'qty':15,
    'type':2,
    'side':1,
    'productType':'BO',
    'limitPrice':0,
    'stopPrice':0,
    'validity':'DAY',
    'disclosedQty':0,
    'offlineOrder':'False',
    'stopLoss':stopLoss,
    'takeProfit':takeProfit}
order_id=fyers.place_order(order_id)
print(order_id)



How to Place Stop Loss Limit Order in Fyers API:



from fyers_api import fyersModel
import pandas as pd
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/current_directory')
spotsymbol='NSE:NIFTYBANK-INDEX'
index_symbol='BANKNIFTY'
ATMCE=100
ATMPE=200
symbol={'symbols':spotsymbol}
last_price=fyers.quotes(symbol)['d'][0]['v']['lp']
strike=100.0*round(last_price/100)
print(strike)
##instruments=pd.read_csv('inst.csv',header=None)
instruments=pd.read_csv('https://public.fyers.in/sym_details/NSE_FO.csv',header=None)
thirteen=instruments[instruments[13]=='{}'.format(index_symbol)]
fifteen_ce=thirteen[thirteen[15]==strike+ATMCE]
fifteen_ce=fifteen_ce.reset_index(drop=True)
symbol_ce=fifteen_ce[9].iloc[0]
fifteen_pe=thirteen[thirteen[15]==strike+ATMPE]
fifteen_pe=fifteen_pe.reset_index(drop=True)
symbol_pe=fifteen_pe[9].iloc[1]
print(symbol_ce,symbol_pe)
symbol={'symbols':symbol_ce}
last_price=fyers.quotes(symbol)['d'][0]['v']['lp']
price=last_price+5
order_id={
    'symbol':symbol_ce,
    'qty':25,
    'type':4,
    'side':-1,
    'productType':'INTRADAY',
    'limitPrice':last_price,
    'stopPrice':price,
    'validity':'DAY',
    'disclosedQty':0,
    'offlineOrder':'False',
    'stopLoss':0,
    'takeProfit':0}
order_id=fyers.place_order(order_id)
print(order_id)


How to Place Hedge Orders in Fyers API:


Open Fyers Trading Account Please Click Here.



CMD pip Installation Type and Enter: pip install fyers_apiv2




from fyers_api import fyersModel
import pandas as pd
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')
spotsymbol='NSE:NIFTYBANK-INDEX'
index_symbol='BANKNIFTY'
ATMCE=100
ATMPE=200
symbol={'symbols':spotsymbol}
last_price=fyers.quotes(symbol)['d'][0]['v']['lp']
strike=100.0*round(last_price/100)
instruments=pd.read_csv('inst.csv',header=None)
##instruments=pd.read_csv('https://public.fyers.in/sym_details/NSE_FO.csv',header=None)
thirteen=instruments[instruments[13]==index_symbol]
fifteen_ce=thirteen[thirteen[15]==strike+ATMCE]
fifteen_ce=fifteen_ce.reset_index(drop=True)
symbol_ce=fifteen_ce[9].iloc[0]
fifteen_pe=thirteen[thirteen[15]==strike+ATMPE]
fifteen_pe=fifteen_pe.reset_index(drop=True)
symbol_pe=fifteen_pe[9].iloc[1]
print(symbol_ce,symbol_pe)
order_id={
    'symbol':symbol_ce,
    'qty':your_quantity,
    'type':2,
    'side':1,
    'productType':'INTRADAY',
    'limitPrice':0,
    'stopPrice':0,
    'validity':'DAY',
    'disclosedQty':0,
    'offlineOrder':'False',
    'stopLoss':0,
    'takeProfit':0}
order_id=fyers.place_order(order_id)
print(order_id)


WebSocket Streaming Market Data Fyers API V2 in Python:


Open Fyers Trading Account Please Click Here.



CMD pip Installation Type and Enter: pip install fyers_apiv2




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:NIFTYBANK-INDEX','NSE:NIFTY50-INDEX']
def custom_message(ticks):
    print(ticks[0]['symbol'][4:],ticks[0]['timestamp'],ticks[0]['ltp'])

fs = ws.FyersSocket(access_token,run_background=False,log_path='your_folder_path')
fs.websocket_data = custom_message
fs.subscribe(symbol,data_type)



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))

Fetch Weekly Expiry Current Index Option Strike Price Symbol Utilizing Fyers API V2:




import pandas as pd
import csv
wr=csv.writer(open('symbol.csv','w'))
index_symbol='BANKNIFTY'
instruments=pd.read_csv('https://public.fyers.in/sym_details/NSE_FO.csv',header=None)
ism=instruments[instruments[13]=='{}'.format(index_symbol)]
index_value=ism.index[0]
tradingsymbol=ism[1][index_value]
tradingsymbol=tradingsymbol[:-9]
symbol=ism[ism[1].str.match('{}'.format(tradingsymbol))].reset_index(drop=True)[9]
for x in range(len(symbol)):
    with open('symbol.csv','a') as csvfile:
        wr=csv.writer(csvfile)
        wr.writerow([symbol[x][0:3],symbol[x][4:]])

Output:


NSE,BANKNIFTY2230330900CE

NSE,BANKNIFTY2230330900PE

NSE,BANKNIFTY2230339300CE

NSE,BANKNIFTY2230339300PE


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.