Skip to content

Instantly share code, notes, and snippets.

@krishnavelu
Last active March 25, 2023 17:35
Show Gist options
  • Star 15 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save krishnavelu/e0df312ccf5f022edb1823461ff4230e to your computer and use it in GitHub Desktop.
Save krishnavelu/e0df312ccf5f022edb1823461ff4230e to your computer and use it in GitHub Desktop.
Simple Moving average strategy using alice_blue library
import logging
import datetime
import statistics
from time import sleep
from alice_blue import *
# Config
username = 'username'
password = 'password'
app_id = 'app_id'
api_secret = 'api_secret'
twoFA = '1993'
EMA_CROSS_SCRIP = 'INFY'
logging.basicConfig(level=logging.DEBUG) # Optional for getting debug messages.
# Config
ltp = 0
alice = None
def event_handler_quote_update(message):
global ltp
ltp = message['ltp']
def buy_signal(ins_scrip):
global alice
alice.place_order(transaction_type = TransactionType.Buy,
instrument = ins_scrip,
quantity = 1,
order_type = OrderType.Market,
product_type = ProductType.Intraday)
def sell_signal(ins_scrip):
global alice
alice.place_order(transaction_type = TransactionType.Sell,
instrument = ins_scrip,
quantity = 1,
order_type = OrderType.Market,
product_type = ProductType.Intraday)
def main():
global alice
global username
global password
global twoFA
global app_id
global api_secret
global EMA_CROSS_SCRIP
minute_close = []
session_id = AliceBlue.login_and_get_sessionID( username = username,
password = password,
twoFA = twoFA,
app_id = app_id,
api_secret = api_secret)
alice = AliceBlue(username = "username", session_id = session_id, master_contracts_to_download=['NSE'])
print(alice.get_balance()) # get balance / margin limits
print(alice.get_profile()) # get profile
print(alice.get_daywise_positions()) # get daywise positions
print(alice.get_netwise_positions()) # get netwise positions
print(alice.get_holding_positions()) # get holding positions
ins_scrip = alice.get_instrument_by_symbol('NSE', EMA_CROSS_SCRIP)
alice.start_websocket(subscribe_callback=event_handler_quote_update)
alice.subscribe(ins_scrip, LiveFeedType.TICK_DATA)
current_signal = ''
while True:
if(datetime.datetime.now().second == 0):
minute_close.append(ltp)
if(len(minute_close) > 20):
sma_5 = statistics.mean(minute_close[-5:])
sma_20 = statistics.mean(minute_close[-20:])
if(current_signal != 'buy'):
if(sma_5 > sma_20):
buy_signal(ins_scrip)
current_signal = 'buy'
if(current_signal != 'sell'):
if(sma_5 < sma_20):
sell_signal(ins_scrip)
current_signal = 'sell'
sleep(1) # sleep for 1 seconds
sleep(0.2) # sleep for 200ms
if(__name__ == '__main__'):
main()
@krishnavelu
Copy link
Author

You get live data. You can get high low of whatever time you want.

@Gautam99-ai
Copy link

As I am new to this, Can you write the API to get the High and Low Price of a Particular Candle of 15 Mins chart.

Like if market opens at 9:15, I want to have an API to get the High and Low price from 9:30 to 9:45 AM.

@Gautam99-ai
Copy link

I mean i am looking for historical data for a time frame for a script using API.

@krishnavelu
Copy link
Author

Learn python.

@ccmoradia
Copy link

What would be the code line for getting LTP printef for two instruments at the same time.

@aatishgupta
Copy link

aatishgupta commented Oct 12, 2020

Hi Krishna,
Everything is working fine for me.
Very good support team thanks for that.
Is it possible to get historical data ?
if possible then how and through which API or anyway to get historical data.
This is just required to backtest my strategy.

@krishnavelu
Copy link
Author

There is no historical data available in alice

@ShujaathKhan
Copy link

ShujaathKhan commented Oct 20, 2020

Hi @krishnavelu,
Instead of searching single instrument can't I get whole stock universe of NSE
for ex: NIFTY 500
Appreciate your response

@aatishgupta
Copy link

Hi Krishna,
if you know about https://www.squareoff.in/ website.
Which allow to place order by login to aliceblue via squareoff website.
So which API we have to use for that so other people can place order from my website without using client secret of mine.

@krishnavelu
Copy link
Author

There is nothing like that available.

@akashrajcashrayz
Copy link

{'exchange': 'NSE', 'token': 26000, 'ltp': 11678.4, 'ltt': 1603945137, 'ltq': 0, 'volume': 0, 'best_bid_price': 0.0, 'best_bid_quantity': 0, 'best_ask_price': 0.0, 'best_ask_quantity': 0, 'total_buy_quantity': 0, 'total_sell_quantity': 0, 'atp': 0.0, 'exchange_time_stamp': 1603945137, 'open': 11633.3, 'high': 11681.7, 'low': 11609.2, 'close': 11729.6, 'yearly_high': 12430.5, 'yearly_low': 7511.1, 'instrument': Instrument(exchange='NSE', token=26000, symbol='Nifty 50', name='Nifty 50', expiry=None, lot_size=None)}

getting this data quanity 0 bid price,ask price 0

@krishnavelu
Copy link
Author

try market hours.

@onevilas
Copy link

onevilas commented Nov 5, 2020

alice.start_websocket(subscribe_callback=event_handler_quote_update,
socket_open_callback=open_callback,
run_in_background=True)
I am not getting open_callback. socket_opened is always False. Any idea on this? Using PyCharm and python 3.8

@krishnavelu
Copy link
Author

krishnavelu commented Nov 8, 2020

Try the example as it is. It works.

@tradermangesh
Copy link

Hi
I want to get Open Interest of say one strike price nifty... it gives following after calling LiveFeedType.MARKET_DATA

{'exchange': 'NFO', 'token': 43838, 'ltp': 60.0, 'ltt': 1617789599, 'ltq': 75, 'volume': 70077975, 'best_bid_price': 59.3, 'best_bid_quantity': 150, 'best_ask_price': 60.0, 'best_ask_quantity': 75, 'total_buy_quantity': 222375, 'total_sell_quantity': 261450, 'atp': 69.91, 'exchange_time_stamp': 1617789600, 'open': 159.9, 'high': 194.05, 'low': 42.4, 'close': 160.45, 'yearly_high': 194.05, 'yearly_low': 0.0, 'instrument': Instrument(exchange='NFO', token=43838, symbol='NIFTY 08 APR21 14800.0 PE', name='', expiry=datetime.date(2021, 4, 8), lot_size='75')}

THERE IS NO OPEN INTEREST IN THIS.... How to get it ?

@krishnavelu
Copy link
Author

OI is not available.

@anuragit15
Copy link

Hi Sir,
Can you please explain why do I have to add a sleep() in order to get quotes after subscribing to any instrument? If I do not add a sleep() subscribing does not send quotes via the websocket?

@krishnavelu
Copy link
Author

That's just an example. If you don't add sleep in that example, it will exit the python script. After exit nothing will happen.

@sanktbn
Copy link

sanktbn commented Feb 21, 2022

quote update {'exchange': 'NSE', 'token': 26000, 'ltp': 17124.9, 'ltt': 1645418890, 'ltq': 0, 'volume': 0, 'best_bid_price': 0.0, 'best_bid_quantity': 0, 'best_ask_price': 0.0, 'best_ask_quantity': 0, 'total_buy_quantity': 0, 'total_sell_quantity': 0, 'atp': 0.0, 'exchange_time_stamp': 1645418890, 'open': 17192.25, 'high': 17231.3, 'low': 17070.7, 'close': 17276.3, 'yearly_high': 18604.45, 'yearly_low': 14151.4, 'instrument': Instrument(exchange='NSE', token=26000, symbol='Nifty 50', name='Nifty 50', expiry=None, lot_size=None)}

Hi I am getting this feed now. How is close greater than high? Could you pls explain based on what time frame is this OHLC information is provided in the feed? THANKS!

@Venkyykarthz
Copy link

Try the example as it is. It works.

How do I close a web socket?
I want better understanding of the concept

@Venkyykarthz
Copy link

Hi @krishnavelu sir.
How can I get the live market data of options?
I want live value of call options for every second , I tried subscribing but I am stuck.

@krishnavelu
Copy link
Author

It’s the same way you subscribe for equity.

@Venkyykarthz
Copy link

It’s the same way you subscribe for equity.

Can you give an example?
I seem to be getting stuck

@Venkyykarthz
Copy link

Venkyykarthz commented Mar 18, 2022

ss1

@krishnavelu
How do I deal with this error??

@krishnavelu
Copy link
Author

Don’t try to reopen connection multiple time. Retry mechanism is already implemented for WS disconnection.

@rajeshrapally
Copy link

@krishnavelu this is the old code, can you please update to latest version,
also is there any possibility to add stoploss and target prices ?

@aabhi922
Copy link

This code is giving below error

File "C:/Users/aabhi/PycharmProjects/pythonProject/nse.py", line 87, in main
socket_open_callback=open_callback
File "C:\Users\aabhi\PycharmProjects\pythonProject\venv\lib\site-packages\alice_blue\alice_blue.py", line 533, in start_websocket
self.__websocket = websocket.WebSocketApp(self.__urls['ws'],
AttributeError: module 'websocket' has no attribute 'WebSocketApp'

@shampavman
Copy link

Does this documentation still hold good?
the run_in_background option seems to be omitted from the API itself..
abObj.start_websocket(subscribe_callback=touchlineupdates,order_update_callback=ordUpdates,run_in_background=True, TypeError: AliceBlue.start_websocket() got an unexpected keyword argument 'run_in_background'

Could you please confirm

@krishnavelu
Copy link
Author

All,
Updated SMA strategy as per new 2.0 version.

@vpkartha
Copy link

You are still showing the old code. That is not workign now. Why this muchu lethargy in uploading a workign version.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment