Unofficial Python Methods for AliceBlue API

Theoretically, Every broker’s API is free. Historical Data is also free. Like it is done here for 5paisa https://www.youtube.com/watch?v=2PXSfi0Rsho (Note - I had taken permission from 5Paisa.).

Now, If a human can see the data of stock from chart, a machine can do the same. An official API can’t. We can only make wrapper or share methods that are allowed by Alice.

But, Alice’s management is very flexible than other brokers. I already asked for permission for adding some extra functions. If We’re given, Krishna will add to the main API.

  • Alice Blue Screeners.
  • Market Watch Addition
  • Alerts
  • Bid Ask Level 20 data
  • Historical Data API

Here is a list of screener URLs -
In case we don’t get approval, Coders are free to PyRequest these URLs

https://ant.aliceblueonline.com/api/v1/screeners/gainerslosers?index=nifty_50
https://ant.aliceblueonline.com/api/v1/screeners/mostactivestocks?index=nifty_50
https://ant.aliceblueonline.com/api/v1/screeners/volume_shockers?index=nifty_50&days=3
https://ant.aliceblueonline.com/api/v1/screeners/upper_circuit_breakers?index=nifty_50
https://ant.aliceblueonline.com/api/v1/screeners/lower_circuit_breakers?index=nifty_50
https://ant.aliceblueonline.com/api/v1/screeners/roi?index=nifty_50&days=3
https://ant.aliceblueonline.com/api/v1/screeners/yearly_high?index=nifty_50
https://ant.aliceblueonline.com/api/v1/screeners/yearly_low?index=nifty_50
https://ant.aliceblueonline.com/api/v1/screeners/near_yearly_high?index=nifty_50
https://ant.aliceblueonline.com/api/v1/screeners/near_yearly_low?index=nifty_50
https://ant.aliceblueonline.com/api/v1/screeners/near_upper_circuit_breakers?index=nifty_50
https://ant.aliceblueonline.com/api/v1/screeners/near_lower_circuit_breakers?index=nifty_50

The payloads will be different for different URL structures though. alicebot.in already has this screener function too. The commands are not updated because if the market is closed, the screeners give blank output as a return.

===========

Here is an URL that allows you to add the tickers into the Market Watch to the main GUI. Their GUI is very buggy.

https://ant.aliceblueonline.com/api/v2/marketwatch
Type: POST
Sample Payload: {“exchange”:“NSE”,“instrument_token”:“26059”,“symbol”:“NIFTY Alpha 50”,“mw_number”:“mw3”}

There are 5 mw’s.

===========

Here is an URL that allows you to set an alert in the system,
Request URL: https://ant.aliceblueonline.com/api/v1/alerts
Type: POST
Sample Payload: {"exchange":"NSE","instrument_token":"26059","wait_time":"60","condition":"lesser_than","user_set_values":[15459.94],"frequency":"recurring","expiry":1598285779,"state_after_expiry":"deleted","user_message":"NIFTY Alpha 50 Lesser than ₹15459.94"}

========================
Here is an URL that allows you to see bid/ask system up to Level20 at ease.
Request URL: Request URL: https://ant.aliceblueonline.com/api/v2/marketdata?exchange=NSE&instrument_token=3045&type=snapquote
Type: GET

=======================
Here is the famous Historical API You are talking about.
Request URL: Request URL: https://ant.aliceblueonline.com/api/v1/charts?exchange=NSE&token=3045&candletype=1&starttime=1596825000&endtime=1598121000&type=historical&data_duration=10
Type: GET

The times are in Epoch. The cute part is You can fetch Historical Info as much far You can see in the chart.

As said earlier, If humans can do it, So can a machine.

=========

But right now, It’s unofficial.

I will keep you guys updated if we get it approved.

3 Likes

Great. We have similar thing with nseindia.

const axios = require('axios').default;
const converter = require('json-2-csv');
const fs = require('fs');
const performance = require('perf_hooks').performance
var sleep = require('sleep')
var urlencode = require('urlencode');
console.time('getallcsv');
console.time("getcsv");
function getcsv(indexname) {
  const index = urlencode(indexname.toUpperCase())
  axios.get('https://www.nseindia.com/api/equity-stockIndices?index=' + index)
    .then(function (response) {
      console.log("name :: ", response.data.name);
      console.log("declines :: ", response.data.advance.declines);
      console.log("advances :: ", response.data.advance.advances);
      console.log("unchanged :: ", response.data.advance.unchanged);
      const test = response.data.name.replace(/ /g, '_');
      const name_of_csv = test.replace('/', '_');
      converter.json2csv(response.data.data, (err, csv) => {
        if (err) {
          throw err;
        }
        // write CSV to a file
        fs.writeFileSync('./csv/' + name_of_csv + '.csv', csv);
      });
    });
}

function get_equity_master() {
  let start_time_b = Date.now();
  axios.get('https://www.nseindia.com/api/equity-master')
    .then(function (response) {
      fs.writeFileSync('./equity_master.json', JSON.stringify(response.data));
      const duration_b = Date.now() - start_time_b;
      console.log("time taken eq master :: ", duration_b, 'ms');
    });
}
// index_names = ['NIFTY BANK','NIFTY PHARMA', 'NIFTY 50', 'NIFTY 100', 'NIFTY 200', 'SECURITIES IN F&O']
// index_names = ["NIFTY 50", "NIFTY NEXT 50", "NIFTY MIDCAP 50", "NIFTY MIDCAP 100", "NIFTY MIDCAP 150",
//   "NIFTY SMALLCAP 50", "NIFTY SMALLCAP 100", "NIFTY SMALLCAP 250", "NIFTY MIDSMALLCAP 400", "NIFTY 100",
//   "NIFTY 200", "NIFTY AUTO", "NIFTY BANK", "NIFTY ENERGY", "NIFTY FINANCIAL SERVICES",
//   "NIFTY FINANCIAL SERVICES 25/50", "NIFTY FMCG", "NIFTY IT", "NIFTY MEDIA", "NIFTY METAL",
//   "NIFTY PHARMA", "NIFTY PSU BANK", "NIFTY REALTY", "NIFTY PRIVATE BANK", "NIFTY COMMODITIES",
//   "NIFTY INDIA CONSUMPTION", "NIFTY CPSE", "NIFTY INFRASTRUCTURE", "NIFTY MNC", "NIFTY GROWTH SECTORS 15",
//   "NIFTY PSE", "NIFTY SERVICES SECTOR", "NIFTY100 LIQUID 15", "NIFTY MIDCAP LIQUID 15",
//   "NIFTY DIVIDEND OPPORTUNITIES 50", "NIFTY50 VALUE 20", "NIFTY100 QUALITY 30", "NIFTY50 EQUAL WEIGHT",

//   "NIFTY100 EQUAL WEIGHT", "NIFTY100 LOW VOLATILITY 30", "NIFTY ALPHA 50", "NIFTY200 QUALITY 30",
//   "NIFTY ALPHA LOW-VOLATILITY 30", "Securities in F&O", "Permitted to Trade"]
// index_names.forEach(getcsv)
get_equity_master()
function getallcsv() {
  var masters = require('../equity_master.json');
  for (item in masters) {
    // console.log(item)
    masters[item].forEach(getcsv);
  }
  console.timeLog("getcsv");
  console.timeEnd("getcsv");
}

getallcsv();
console.timeLog("getallcsv");
console.timeEnd("getallcsv");
// masters['Others'].forEach(getcsv)
  // masters["Broad Market Indices"].forEach(getcsv)
  // masters["Strategy Indices"].forEach(getcsv)
  // masters["Sectoral Indices"].forEach(getcsv)
  // masters["Thematic Indices"].forEach(getcsv)
1 Like

How to place single order in multiple account in single request API(alice blue)?

In a single request, it is never possible. NSE gives unique order ID per trade. You need to iterate the trade signal to all accounts. If all accounts are in alicebot.in, You can connect n number of accounts too in same route.

alicebot.in doing this via aliceblue API only na or alicebot takes all token from all accounts and fire multiple request at once.

1 Like

Weird questions. You are asking aladeen or aladeen,

AliceBlue API also generates token and does the trading using the token.
AliceBlue Web Terminal + Mobile works on same method.

Basic Oauth2.

1 Like

Directly coming to point working on creating fully automated algo trading platform with my own logic.
So asking how to place single order in multiple account.Similar to alicebot.in or squareoff.in

Both are firing on accounts one by one. That’s why I repeatedly ask you to google on how Oauth2 works.

Sorry and thank you so much.
As per this logic if order is not placed within some seconds then so much of slippage will be happen

Always.

NSE doesn’t let you fire 1 trade in 5 accounts in 1 order number. Even with consecutive order number it will have slippage.

1 Like

Hi, trying to fetch historical data from aliceblue with the help of below code to authenticate.
The login with username/password combo is success
but twofa is returning ‘internal server error’:
how to getthrough…

or is there any other way of authentication and then download historical data from aliceblue

import json
import requests

username = ‘xxx’
password = ‘yyy’
twofa = ‘zzz’

s = requests.Session()
s.headers.update({‘User-Agent’: ‘Mozilla/5.0’})
url1 = ‘https://ant.aliceblueonline.com/partials/home.login.html
r1 = s.get(url1)
print(r1)#<Response [200]>

url2 = ‘https://ant.aliceblueonline.com/api/v2/login
data2 = {‘login_id’: username,
‘password’: password,
‘device’: ‘web’}
r2 = s.post(url2, data=data2)
print(r2)#<Response [200]>

val = (json.loads(r2.content.decode()))[‘data’][‘question_ids’]
url3 = ‘https ___ ://ant.aliceblueonline.com/api/v2/checktwofa’
data3 = {‘answers’: [twofa, twofa], ‘login_id’: username, ‘question_ids’: val, ‘device’: ‘web’, ‘count’:2}
r3 = s.post(url3, data=data3)

print(r3) #<Response [500]>
print(r3.text) #{“errors”:{“detail”:“Internal server error”}}

Hi,
While login to aliceblue you need to provide certain questions answer.
In case aliceblue api you have to set all questions answer same.
if face this issue after setting same answer for all questions.My issue got resolved.

yes, answers to all 4 security questions are set same
but still getting 500/400 as response for twofa
(can you run the code at your end?)
(in code above, only in url3, the underscores inserted needs to be removed)

Actually i am not using api directly.
I am using python library alice blue API.

The authentication method is illegal as per the team of AliceBlue. Although You can see I have done something similar for 5paisa https://www.youtube.com/watch?v=2PXSfi0Rsho AliceBlue didn’t give such permission.

So Please don’t discuss that part because at the end, they will cut my head. You can get accesstoken using alicebot.in’s accesstoken function if you want to access the historical data.

Alternatively, You can inspect element the stuff once logged in.

1 Like

Hey @dexter , I get “Request unauthorised” error when I pyrequest the url for level 20 bidask and historical data.

response=requests.get(‘https://ant.aliceblueonline.com/api/v2/marketdata?exchange=NSE&instrument_token=2885&type=snapquote’)
response.json()

{‘status’: ‘error’, ‘message’: ‘Request Unauthorised’, ‘data’: {}}

Fastest Solution:

Generate the access token using the alicebot and just paste it direct.

Reason:

The URLs will be blocked from normal access token generated by an OAuth App.

response=requests.get('https://ant.aliceblueonline.com/api/v2/marketdata?exchange=NSE&instrument_token=3045&type=snapquote')
response.json()

{'status': 'error', 'message': 'Request Unauthorised', 'data': {}}

Hey @dexter , the access_token is generated from alicebot through telegram and I’m able to create an Alice object using that access_token but still getting same error.

I just tried it and got the data correct. Paste me the entire program you are using here. It will help in debug.

#basic credentials
username='....'
password='......'
twoFA='.....'
client_id = 'UNOFFICED'
client_secret = '.......'
redirect_url= 'https://www.unofficed.com/alice/fallback/'

#generated from alicebot through telegram app
access_token='...........'

#pyrequest
import requests
myUrl = 'https://ant.aliceblueonline.com/api/v2/marketdata?exchange=NSE&instrument_token=3045&type=snapquote'
head = {'Authorization': 'acess_token {}'.format(access_token)}
response = requests.get(myUrl, headers=head)
response.text

#output
'{"status":"error","message":"Request Unauthorised","data":{}}' 
#Response '401'

To avoid confusion it’ll be great if you can share the code that worked for you.