Alice Blue Utilize Free of Cost API to Automate Trades in Python

Get Historical Data OHLCV Alice Blue API in Python


Follow the Instructions from the above Video then go for the Code below to Fetch Historical OHLCV Data.


from pya3 import *
from datetime import datetime,timedelta
import pandas
username=open('username.txt','r').read()
api_key=open('api_key.txt','r').read()
alice=Aliceblue(username,api_key)
alice.get_session_id()['sessionID']
days=10
exchange='NSE'
spot_symbol='TATAMOTORS'
interval='1'
indices=False
from_date=datetime.now()-timedelta(days=days)
to_date=datetime.now()
token=alice.get_instrument_by_symbol(exchange,spot_symbol)
data=alice.get_historical(token,from_date,to_date,interval,indices)
data=pd.DataFrame(data)
print(data)


V2 Alice Blue API Utilize Free of Cost to Automate Trades in Python


Follow the Instructions from the above Video then go for the Code below to create Session ID.


from pya3 import *
username=open('username.txt','r').read()
api_key=open('api_key.txt','r').read()
alice=Aliceblue(username,api_key)
alice.get_session_id()['sessionID']
alice.get_contract_master('INDICES')
alice.get_contract_master('MCX')
alice.get_contract_master('NSE')
alice.get_contract_master('NFO')





Open Alice Blue Trading Account Please Click Here.



CMD pip Installation Type and Enter: pip install alice_blue



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



from alice_blue import *
import csv
access_token=AliceBlue.login_and_get_access_token(username='username',password='password',twoFA='twoFA',api_secret='api_secret')
print(access_token)
with open('access_token.txt','w') as wr1:
    wr=csv.writer(wr1)
    wr.writerow([access_token])
access_token=open('access_token.txt','r').read().strip()   
alice=AliceBlue(username='username',password='password',access_token=access_token, master_contracts_to_download=['NSE', 'BSE'])
tatasteel_nse_eq = alice.get_instrument_by_symbol('NSE', 'TATASTEEL')
print(tatasteel_nse_eq)


Manage Alice Blue Login Credentials as well as API Secret Confidentially with the help of Python inbuilt Module Function DBM(Database Manager).


First create the Database and then go for Read and Write in which 'c' does all the work if database not created it will create them and then with the help of 'r' we will read our credentials and utilize them wherever it is required and now the value dbm while write comes with 'b as byte which won't be true if we pass the same in our required credentials so we will go for decode() function which will decode and erase 'b and now we can utilize as required without any trouble or error and if you don't have trading account please follow above link.


To create database with login credentials and api go for below code with your username,password,twoFA and api_secret:


import dbm
with dbm.open('alicedbm','c') as db:
    db['username']='your_username'
    db['password']='your_password'
    db['twoFA']='your_twoFA'
    db['api_secret']='your_api_secret'


After create of database with login credentials and api go for below code to create access token and same utilize for programmatic/algo trading in python as explained in video so follow them properly for instructions.


from alice_blue import *
import csv
import dbm
db=dbm.open('your_db_stored_path/alicedb','r')
access_token=AliceBlue.login_and_get_access_token(username=db['username'].decode(),password=db['password'].decode(),twoFA=db['twoFA'].decode(),api_secret=db['api_secret'].decode())
print(access_token)
with open('access_token.txt','w') as wr1:
    wr=csv.writer(wr1)
    wr.writerow([access_token])
access_token=open('access_token.txt','r').read().strip()   
alice=AliceBlue(username=db['username'].decode(),password=db['password'].decode(),access_token=access_token, master_contracts_to_download=['NSE', 'BSE'])
tatasteel_nse_eq = alice.get_instrument_by_symbol('NSE', 'TATASTEEL')
print(tatasteel_nse_eq)


Get Strike List's of Trading Symbol for Options Trading in Python for that Follow Below Video then Go for the Code.



import requests
import io
from pprint import pprint
import pandas as pd
instruments=requests.get('https://api.kite.trade/instruments').content
instruments=pd.read_csv(io.StringIO(instruments.decode('utf-8')))
instruments_str_match=instruments[instruments['segment'].str.match('NFO-OPT')]
strike=instruments_str_match[instruments_str_match['tradingsymbol'].str.match('TATAMOTORS')]
strike_price=strike['strike']
print(strike_price)

Search Instruments Fetch Symbol,Expiry and Lot Size for that Follow Below Video then Go for the Code.



from alice_blue import *
import pandas as pd
username=open('username.txt','r').read().strip()
password=open('password.txt','r').read().strip()
access_token=open('access_token.txt','r').read().strip()
alice=AliceBlue(username,password,access_token,['NFO','NSE'])
instruments=alice.search_instruments('NFO','BANKNIFTY')
instruments=pd.DataFrame(instruments)
tradingsymbol=instruments[0:1]['symbol'].to_string(index=False)
print(tradingsymbol)

WebSocket Streaming Data Quote Update Live Feed Alice Blue API in Python.For Instructions Please follow the Video then go for the Code.



from alice_blue import *
import dbm
ldb=dbm.open('alicedb','r')
username=ldb['username'].decode()
password=ldb['password'].decode()
access_token=open('access_token.txt','r').read().strip()
alice=AliceBlue(username,password,access_token,['NSE'])

def event_handler_quote_update(ticks):
    print(ticks)

def open_callback():
    global socket_opened
    socket_opened=True
alice.start_websocket(event_handler_quote_update,open_callback,run_in_background=True)

while True:
    alice.subscribe([alice.get_instrument_by_symbol('NSE','TATAMOTORS'),alice.get_instrument_by_symbol('NSE','M&M')],LiveFeedType.COMPACT)


Live Feed Type:COMPACT


{'exchange': 'NSE', 'token': 3456, 'ltp': 309.1, 'change': 605, 'exchange_time_stamp': 1616474552, 'volume': 20777482, 'instrument': Instrument(exchange='NSE', token=3456, symbol='TATAMOTORS', name='TATA MOTORS LIMITED', expiry=None, lot_size=None)}
{'exchange': 'NSE', 'token': 2031, 'ltp': 855.65, 'change': 260, 'exchange_time_stamp': 1616474552, 'volume': 962042, 'instrument': Instrument(exchange='NSE', token=2031, symbol='M&M', name='MAHINDRA & MAHINDRA LTD', expiry=None, lot_size=None)}

Live Feed Type:MARKET_DATA


{'exchange': 'NSE', 'token': 3456, 'ltp': 308.35, 'ltt': 1616475239, 'ltq': 50, 'volume': 23920094, 'best_bid_price': 308.35, 'best_bid_quantity': 1156, 'best_ask_price': 308.45, 'best_ask_quantity': 1761, 'total_buy_quantity': 2733323, 'total_sell_quantity': 4132156, 'atp': 309.28, 'exchange_time_stamp': 1616475239, 'open': 305.0, 'high': 312.25, 'low': 304.0, 'close': 303.05, 'yearly_high': 357.0, 'yearly_low': 63.5, 'instrument': Instrument(exchange='NSE', token=3456, symbol='TATAMOTORS', name='TATA MOTORS LIMITED', expiry=None, lot_size=None)}
{'exchange': 'NSE', 'token': 2031, 'ltp': 855.5, 'ltt': 1616474611, 'ltq': 31, 'volume': 975101, 'best_bid_price': 855.15, 'best_bid_quantity': 3, 'best_ask_price': 855.5, 'best_ask_quantity': 39, 'total_buy_quantity': 314325, 'total_sell_quantity': 432714, 'atp': 859.44, 'exchange_time_stamp': 1616474612, 'open': 859.95, 'high': 864.8, 'low': 854.2, 'close': 853.05, 'yearly_high': 952.05, 'yearly_low': 245.4, 'instrument': Instrument(exchange='NSE', token=2031, symbol='M&M', name='MAHINDRA & MAHINDRA LTD', expiry=None, lot_size=None)}

Live Feed Type:SNAPQUOTE


{'exchange': 'NSE', 'token': 3456, 'buyers': [1, 3, 12, 20, 27], 'bid_prices': [308.95, 308.85, 308.8, 308.75, 308.7], 'bid_quantities': [637, 3283, 55235, 3905, 10632], 'sellers': [117, 5, 37, 18, 24], 'ask_prices': [309.0, 309.05, 309.1, 309.15, 309.2], 'ask_quantities': [86232, 3267, 18439, 7857, 14022], 'exchange_time_stamp': 1616474657, 'instrument': Instrument(exchange='NSE', token=3456, symbol='TATAMOTORS', name='TATA MOTORS LIMITED', expiry=None, lot_size=None)}
{'exchange': 'NSE', 'token': 2031, 'buyers': [1, 1, 3, 6, 12], 'bid_prices': [855.3, 855.25, 855.2, 855.15, 855.1], 'bid_quantities': [56, 100, 503, 1484, 424], 'sellers': [2, 2, 1, 3, 1], 'ask_prices': [855.5, 855.55, 855.6, 855.7, 855.75], 'ask_quantities': [214, 125, 13, 52, 61], 'exchange_time_stamp': 1616474657, 'instrument': Instrument(exchange='NSE', token=2031, symbol='M&M', name='MAHINDRA & MAHINDRA LTD', expiry=None, lot_size=None)}

Live Feed Type:FULL_SNAPQUOTE


{'exchange': 'NSE', 'token': 3456, 'buyers': [12, 10, 30, 22, 38], 'bid_prices': [309.0, 308.95, 308.9, 308.85, 308.8], 'bid_quantities': [4896, 3214, 17176, 16197, 12222], 'sellers': [1, 5, 13, 24, 28], 'ask_prices': [309.05, 309.1, 309.15, 309.2, 309.25], 'ask_quantities': [106, 11060, 3479, 12496, 17461], 'atp': 309.36, 'open': 305.0, 'high': 312.25, 'low': 304.0, 'close': 303.05, 'total_buy_quantity': 2845073, 'total_sell_quantity': 3890134, 'volume': 21699680, 'instrument': Instrument(exchange='NSE', token=3456, symbol='TATAMOTORS', name='TATA MOTORS LIMITED', expiry=None, lot_size=None)}
{'exchange': 'NSE', 'token': 2031, 'buyers': [2, 1, 2, 4, 3], 'bid_prices': [856.5, 856.3, 856.25, 856.2, 856.1], 'bid_quantities': [1367, 11, 78, 757, 160], 'sellers': [1, 2, 2, 2, 3], 'ask_prices': [856.75, 856.8, 856.85, 856.9, 856.95], 'ask_quantities': [100, 250, 2, 202, 24], 'atp': 859.4, 'open': 859.95, 'high': 864.8, 'low': 854.2, 'close': 853.05, 'total_buy_quantity': 321966, 'total_sell_quantity': 431749, 'volume': 986542, 'instrument': Instrument(exchange='NSE', token=2031, symbol='M&M', name='MAHINDRA & MAHINDRA LTD', expiry=None, lot_size=None)}

Automatically Fetch Weekly Expiry Current Index Option Symbols.



from alice_blue import *
import pandas as pd
username=open('username.txt','r').read()
password=open('password.txt','r').read()
access_token=open('access_token.txt','r').read().strip()
alice=AliceBlue(username,password,access_token,['NFO','NSE'])
exchange='NFO'
optidx_symbol='BANKNIFTY'
expiry_index=0
instruments=pd.DataFrame(alice.search_instruments(exchange,optidx_symbol))
options=instruments[:-3]
expiry_date=sorted(options.expiry.drop_duplicates())[expiry_index]
symbols=options[options['expiry']==expiry_date]
symbols['symbol'].to_csv('tradingsymbol.csv',index=False,header=None)

Get ITM ATM OTM Strike Price:




from alice_blue import *
import pandas as pd
username=open('username.txt','r').read().strip()
password=open('password.txt','r').read().strip()
access_token=open('access_token.txt','r').read().strip()
alice=AliceBlue(username,password,access_token)
exchange='NFO'
optidx_symbol='BANKNIFTY'
expiry_index=0
instruments=pd.DataFrame(alice.search_instruments(exchange,optidx_symbol))
options=instruments[:-3]
expiry_date=sorted(options.expiry.drop_duplicates())[expiry_index]
symbols=options[options['expiry']==expiry_date].reset_index(drop=True)
Strike=[float(symbols['symbol'][x][19:26]) for x in range(len(symbols['symbol']))]
Price=34682.65 
ATM=round(Price/100)*100.0
CALL_ITM=[Strike[x] for x in range(len(Strike)) if Strike[x]<=ATM]
CALL_OTM=[Strike[x] for x in range(len(Strike)) if Strike[x]>ATM]
CALL=pd.DataFrame(CALL_ITM+CALL_OTM,columns=['CALL']).drop_duplicates().reset_index(drop=True)
PUT_ITM=[Strike[x] for x in range(len(Strike)) if Strike[x]>ATM]
PUT_OTM=[Strike[x] for x in range(len(Strike)) if Strike[x]<=ATM]
PUT=pd.DataFrame(PUT_OTM+PUT_ITM,columns=['PUT']).drop_duplicates().reset_index(drop=True)
print(CALL)
print(PUT)

Reading Writing and Processing data via HTML table with pandas:


Write data into an HTML table:



from alice_blue import *
import pandas as pd
username=open('username.txt','r').read().strip()
password=open('password.txt','r').read().strip()
access_token=open('access_token.txt','r').read().strip()
alice=AliceBlue(username,password,access_token)
data=pd.DataFrame(alice.search_instruments('NFO','BANKNIFTY'))[:-3]
data.to_html('instruments.html',index=False)

Read data from an HTML table:



import pandas as pd
data=pd.read_html('instruments.html')
data=data[0].sort_values('expiry')
data=data[data.symbol.str.contains('JUL')]
data=data.sort_values('symbol').reset_index(drop=True)
list_data=[data['symbol'][226+x] for x in reversed(range(20))]
print(list_data)