Skip to content

Instantly share code, notes, and snippets.

@krishnavelu
Last active March 25, 2023 17:35
Show Gist options
  • 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

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!

Copy link

ghost commented Mar 9, 2022

Try the example as it is. It works.

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

Copy link

ghost commented Mar 16, 2022

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.

Copy link

ghost commented Mar 18, 2022

It’s the same way you subscribe for equity.

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

Copy link

ghost 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