Package: alphatrade
Python APIs for SAS Online Alpha Trade Web PlatformMAJOR CHANGES : NEW VERSION 1.0.0API endpoints are changed to match the new ones, bugs expectedRemoved check for enabled exchanges, you can now download or search symbols from MCX as well if it is not enabledTOTP SECRET or TOTP both can be given as argument while creating AlphaTrade object (if it is 6 digits it will conside TOTP else TOTP SECRET)Added new search function to search scrips which will return json for found scrips, you need to process it furtherMore functions to come.Check whether streaming websocket is working or notTheexamplesfolder is removed and examples are renamed and kept in root directory for ease of developmentSTEPS to workClone the repo locally -git clone https://github.com/algo2t/alphatrade.gitCreate a virtualenv -python -m pip install virtualenvand thenpython -m virtualenv venvand activate thevenvenvironment.Install dev-requirement.txt -python -m pip install -r dev-requirements.txt- this is to ensuresetuptools==57.5.0is installed. There is a bug withprotlib, target is to get reed ofprotlibin futureInstall requirement.txt -python -m pip install -r requirement.txtCreate theconfig.pyfile in root of cloned repo withlogin_id,passwordandTOTPSECRET, you can add theaccess_token.txtif you want to use existingaccess_token.Try the examplespython zlogin_example.py,python zexample_sas_login.py,python zhistorical_data.pyandpython zstreaming_data.pyExpecting issues with the streaming data !!! :PNOTE:: This is Unofficial python module, don't ask SAS support team for help, use it AS-ISThe Python APIs for communicating with the SAS Online Alpha Trade Web Platform.Alpha Trade Python library provides an easy to use python wrapper over the HTTPS APIs.The HTTP calls have been converted to methods and JSON responses are wrapped into Python-compatible objects.Websocket connections are handled automatically within the library.This work is completely based on Python SDK / APIs forAliceBlueOnline.Thanks tokrishnavelu.Author:algo2tGithub Repository:alphatradeInstallationThis module is installed via pip:pip install git+https://github.com/algo2t/alphatrade.gitIt can also be installed frompypipip install alphatradeTo force upgrade existing installations:pip uninstall alphatrade
pip --no-cache-dir install --upgrade alphatradePrerequisitesPython 3.xAlso, you need the following modules:protlibwebsocket_clientrequestspandasThe modules can also be installed usingpipExamples - Start Here - ImportantPlease clone this repository and check the examples folder to get started.CheckhereGetting started with APIOverviewThere is only one class in the whole library:AlphaTrade. When theAlphaTradeobject is created an access token from the SAS Online alpha trade server is stored in text fileaccess_token.txtin the same directory. An access token is valid for 24 hours. See the examples folder withconfig.pyfile to see how to store your credentials.
With an access token, you can instantiate an AlphaTrade object again. Ideally you only need to create an access_token once every day.REST DocumentationThe original REST API that this SDK is based on is available online.Alice Blue API REST documentationUsing the APILoggingThe whole library is equipped with python‘sloggingmodule for debugging. If more debug information is needed, enable logging using the following code.importlogginglogging.basicConfig(level=logging.DEBUG)Get an access tokenImport alphatradefromalphatradeimport*Createconfig.pyfileAlways keep credentials in a separate filelogin_id="XXXXX"password="XXXXXXXX"Totp='XXXXXXXXXXXXXXXX'try:access_token=open('access_token.txt','r').read().rstrip()exceptExceptionase:print('Exception occurred ::{}'.format(e))access_token=NoneImport the configimportconfigCreate AlphaTrade ObjectCreateAlphaTradeobject with yourlogin_id,password,TOTP/TOTP_SECRETand/oraccess_token.Useconfigobject to getlogin_id,password,TOTPandaccess_token.fromalphatradeimportAlphaTradeimportconfigimportpyotpTotp=config.Totppin=pyotp.TOTP(Totp).now()totp=f"{int(pin):06d}"iflen(pin)<=5elsepinsas=AlphaTrade(login_id=config.login_id,password=config.password,twofa=totp,access_token=config.access_token)## filename config.pylogin_id="RR24XX"password="SuperSecretPassword!!!"TOTP_SECRET='YOURTOTPSECRETEXTERNALAUTH'try:access_token=open('access_token.txt','r').read().rstrip()exceptExceptionase:print(f'Exception occurred ::{e}')access_token=NonefromalphatradeimportAlphaTradeimportconfigimportpyotpsas=AlphaTrade(login_id=config.login_id,password=config.password,twofa=config.TOTP_SECRET,access_token=config.access_token)You can run commands here to check your connectivityprint(sas.get_balance())# get balance / margin limitsprint(sas.get_profile())# get profileprint(sas.get_daywise_positions())# get daywise positionsprint(sas.get_netwise_positions())# get netwise positionsprint(sas.get_holding_positions())# get holding positionsGet master contractsGetting master contracts allow you to search for instruments by symbol name and place orders.
Master contracts are stored as an OrderedDict by token number and by symbol name. Whenever you get a trade update, order update, or quote update, the library will check if master contracts are loaded. If they are, it will attach the instrument object directly to the update. By default all master contracts of all enabled exchanges in your personal profile will be downloaded. i.e. If your profile contains the following as enabled exchanges['NSE', 'BSE', 'CDS', 'MCX', NFO']all contract notes of all exchanges will be downloaded by default. If you feel it takes too much time to download all exchange, or if you don‘t need all exchanges to be downloaded, you can specify which exchange to download contract notes while creating the AlphaTrade object.sas=AlphaTrade(login_id=config.login_id,password=config.password,twofa=totp,access_token=config.access_token,master_contracts_to_download=['NSE','BSE'])This will reduce a few milliseconds in object creation time of AlphaTrade object.Get tradable instrumentsSymbols can be retrieved in multiple ways. Once you have the master contract loaded for an exchange, you can get an instrument in many ways.Get a single instrument by it‘s name:tatasteel_nse_eq=sas.get_instrument_by_symbol('NSE','TATASTEEL')reliance_nse_eq=sas.get_instrument_by_symbol('NSE','RELIANCE')ongc_bse_eq=sas.get_instrument_by_symbol('BSE','ONGC')india_vix_nse_index=sas.get_instrument_by_symbol('NSE','India VIX')sensex_nse_index=sas.get_instrument_by_symbol('BSE','SENSEX')Get a single instrument by it‘s token number (generally useful only for BSE Equities):ongc_bse_eq=sas.get_instrument_by_token('BSE',500312)reliance_bse_eq=sas.get_instrument_by_token('BSE',500325)acc_nse_eq=sas.get_instrument_by_token('NSE',22)Get FNO instruments easily by mentioning expiry, strike & call or put.bn_fut=sas.get_instrument_for_fno(symbol='BANKNIFTY',expiry_date=datetime.date(2019,6,27),is_fut=True,strike=None,is_call=False)bn_call=sas.get_instrument_for_fno(symbol='BANKNIFTY',expiry_date=datetime.date(2019,6,27),is_fut=False,strike=30000,is_call=True)bn_put=sas.get_instrument_for_fno(symbol='BANKNIFTY',expiry_date=datetime.date(2019,6,27),is_fut=False,strike=30000,is_call=False)Search for symbolsSearch for multiple instruments by matching the name. This works case insensitive and returns all instrument which has the name in its symbol.all_sensex_scrips=sas.search_instruments('BSE','sEnSeX')print(all_sensex_scrips)The above code results multiple symbol which has ‘sensex’ in its symbol.[Instrument(exchange='BSE', token=1, symbol='SENSEX', name='SENSEX', expiry=None, lot_size=None), Instrument(exchange='BSE', token=540154, symbol='IDFSENSEXE B', name='IDFC Mutual Fund', expiry=None, lot_size=None), Instrument(exchange='BSE', token=532985, symbol='KTKSENSEX B', name='KOTAK MAHINDRA MUTUAL FUND', expiry=None, lot_size=None), Instrument(exchange='BSE', token=538683, symbol='NETFSENSEX B', name='NIPPON INDIA ETF SENSEX', expiry=None, lot_size=None), Instrument(exchange='BSE', token=535276, symbol='SBISENSEX B', name='SBI MUTUAL FUND - SBI ETF SENS', expiry=None, lot_size=None)]Search for multiple instruments by matching multiple namesmultiple_underlying=['BANKNIFTY','NIFTY','INFY','BHEL']all_scripts=sas.search_instruments('NFO',multiple_underlying)Instrument objectInstruments are represented by instrument objects. These are named-tuples that are created while getting the master contracts. They are used when placing an order and searching for an instrument. The structure of an instrument tuple is as follows:Instrument=namedtuple('Instrument',['exchange','token','symbol','name','expiry','lot_size'])All instruments have the fields mentioned above. Wherever a field is not applicable for an instrument (for example, equity instruments don‘t have strike prices), that value will beNoneQuote updateOnce you have master contracts loaded, you can easily subscribe to quote updates.Four types of feed data are availableYou can subscribe any one type of quote update for a given scrip. Using theLiveFeedTypeenum, you can specify what type of live feed you need.LiveFeedType.MARKET_DATALiveFeedType.COMPACTLiveFeedType.SNAPQUOTELiveFeedType.FULL_SNAPQUOTEPlease refer to the original documentationherefor more details of different types of quote update.Subscribe to a live feedsas.subscribe(sas.get_instrument_by_symbol('NSE','TATASTEEL'),LiveFeedType.MARKET_DATA)sas.subscribe(sas.get_instrument_by_symbol('BSE','RELIANCE'),LiveFeedType.COMPACT)Subscribe to multiple instruments in a single call. Give an array of instruments to be subscribed.sas.subscribe([sas.get_instrument_by_symbol('NSE','TATASTEEL'),sas.get_instrument_by_symbol('NSE','ACC')],LiveFeedType.MARKET_DATA)Note: There is a limit of 250 scrips that can be subscribed on total. Beyond this point the server may disconnect web-socket connection.Start getting live feed via socketsocket_opened=Falsedefevent_handler_quote_update(message):print(f"quote update{message}")defopen_callback():globalsocket_openedsocket_opened=Truesas.start_websocket(subscribe_callback=event_handler_quote_update,socket_open_callback=open_callback,run_in_background=True)while(socket_opened==False):passsas.subscribe(sas.get_instrument_by_symbol('NSE','ONGC'),LiveFeedType.MARKET_DATA)sleep(10)Unsubscribe to a live feedUnsubscribe to an existing live feedsas.unsubscribe(sas.get_instrument_by_symbol('NSE','TATASTEEL'),LiveFeedType.MARKET_DATA)sas.unsubscribe(sas.get_instrument_by_symbol('BSE','RELIANCE'),LiveFeedType.COMPACT)Unsubscribe to multiple instruments in a single call. Give an array of instruments to be unsubscribed.sas.unsubscribe([sas.get_instrument_by_symbol('NSE','TATASTEEL'),sas.get_instrument_by_symbol('NSE','ACC')],LiveFeedType.MARKET_DATA)Get All Subscribed Symbolssas.get_all_subscriptions()# AllMarket Status messages & Exchange messages.Subscribe to market status messagessas.subscribe_market_status_messages()Getting market status messages.print(sas.get_market_status_messages())Example result ofget_market_status_messages()[{'exchange': 'NSE', 'length_of_market_type': 6, 'market_type': b'NORMAL', 'length_of_status': 31, 'status': b'The Closing Session has closed.'}, {'exchange': 'NFO', 'length_of_market_type': 6, 'market_type': b'NORMAL', 'length_of_status': 45, 'status': b'The Normal market has closed for 22 MAY 2020.'}, {'exchange': 'CDS', 'length_of_market_type': 6, 'market_type': b'NORMAL', 'length_of_status': 45, 'status': b'The Normal market has closed for 22 MAY 2020.'}, {'exchange': 'BSE', 'length_of_market_type': 13, 'market_type': b'OTHER SESSION', 'length_of_status': 0, 'status': b''}]Note: As peralice bluedocumentationall market status messages should be having a timestamp. But in actual the server doesn‘t send timestamp, so the library is unable to get timestamp for now.Subscribe to exchange messagessas.subscribe_exchange_messages()Getting market status messages.print(sas.get_exchange_messages())Example result ofget_exchange_messages()[{'exchange': 'NSE', 'length': 32, 'message': b'DS : Bulk upload can be started.', 'exchange_time_stamp': 1590148595}, {'exchange': 'NFO', 'length': 200, 'message': b'MARKET WIDE LIMIT FOR VEDL IS 183919959. OPEN POSITIONS IN VEDL HAVE REACHED 84 PERCENT OF THE MARKET WIDE LIMIT.                                                                                       ', 'exchange_time_stamp': 1590146132}, {'exchange': 'CDS', 'length': 54, 'message': b'DS : Regular segment Bhav copy broadcast successfully.', 'exchange_time_stamp': 1590148932}, {'exchange': 'MCX', 'length': 7, 'message': b'.......', 'exchange_time_stamp': 1590196159}]Market Status messages & Exchange messages through callbackssocket_opened=Falsedefmarket_status_messages(message):print(f"market status messages{message}")defexchange_messages(message):print(f"exchange messages{message}")defopen_callback():globalsocket_openedsocket_opened=Truesas.start_websocket(market_status_messages_callback=market_status_messages,exchange_messages_callback=exchange_messages,socket_open_callback=open_callback,run_in_background=True)while(socket_opened==False):passsas.subscribe_market_status_messages()sas.subscribe_exchange_messages()sleep(10)Place an orderPlace limit, market, SL, SL-M, AMO, BO, CO ordersprint(sas.get_profile())# TransactionType.Buy, OrderType.Market, ProductType.Deliveryprint("%%%%%%%%%%%%%%%%%%%%%%%%%%%%1%%%%%%%%%%%%%%%%%%%%%%%%%%%%%")print(sas.place_order(transaction_type=TransactionType.Buy,instrument=sas.get_instrument_by_symbol('NSE','INFY'),quantity=1,order_type=OrderType.Market,product_type=ProductType.Delivery,price=0.0,trigger_price=None,stop_loss=None,square_off=None,trailing_sl=None,is_amo=False))# TransactionType.Buy, OrderType.Market, ProductType.Intradayprint("%%%%%%%%%%%%%%%%%%%%%%%%%%%%2%%%%%%%%%%%%%%%%%%%%%%%%%%%%%")print(sas.place_order(transaction_type=TransactionType.Buy,instrument=sas.get_instrument_by_symbol('NSE','INFY'),quantity=1,order_type=OrderType.Market,product_type=ProductType.Intraday,price=0.0,trigger_price=None,stop_loss=None,square_off=None,trailing_sl=None,is_amo=False))# TransactionType.Buy, OrderType.Market, ProductType.CoverOrderprint("%%%%%%%%%%%%%%%%%%%%%%%%%%%%3%%%%%%%%%%%%%%%%%%%%%%%%%%%%%")print(sas.place_order(transaction_type=TransactionType.Buy,instrument=sas.get_instrument_by_symbol('NSE','INFY'),quantity=1,order_type=OrderType.Market,product_type=ProductType.CoverOrder,price=0.0,trigger_price=7.5,# trigger_price Here the trigger_price is taken as stop loss (provide stop loss in actual amount)stop_loss=None,square_off=None,trailing_sl=None,is_amo=False))# TransactionType.Buy, OrderType.Limit, ProductType.BracketOrder# OCO Order can't be of type marketprint("%%%%%%%%%%%%%%%%%%%%%%%%%%%%4%%%%%%%%%%%%%%%%%%%%%%%%%%%%%")print(sas.place_order(transaction_type=TransactionType.Buy,instrument=sas.get_instrument_by_symbol('NSE','INFY'),quantity=1,order_type=OrderType.Limit,product_type=ProductType.BracketOrder,price=8.0,trigger_price=None,stop_loss=6.0,square_off=10.0,trailing_sl=None,is_amo=False))# TransactionType.Buy, OrderType.Limit, ProductType.Intradayprint("%%%%%%%%%%%%%%%%%%%%%%%%%%%%5%%%%%%%%%%%%%%%%%%%%%%%%%%%%%")print(sas.place_order(transaction_type=TransactionType.Buy,instrument=sas.get_instrument_by_symbol('NSE','INFY'),quantity=1,order_type=OrderType.Limit,product_type=ProductType.Intraday,price=8.0,trigger_price=None,stop_loss=None,square_off=None,trailing_sl=None,is_amo=False))# TransactionType.Buy, OrderType.Limit, ProductType.CoverOrderprint("%%%%%%%%%%%%%%%%%%%%%%%%%%%%6%%%%%%%%%%%%%%%%%%%%%%%%%%%%%")print(sas.place_order(transaction_type=TransactionType.Buy,instrument=sas.get_instrument_by_symbol('NSE','INFY'),quantity=1,order_type=OrderType.Limit,product_type=ProductType.CoverOrder,price=7.0,trigger_price=6.5,# trigger_price Here the trigger_price is taken as stop loss (provide stop loss in actual amount)stop_loss=None,square_off=None,trailing_sl=None,is_amo=False))################################ TransactionType.Buy, OrderType.StopLossMarket, ProductType.Deliveryprint("%%%%%%%%%%%%%%%%%%%%%%%%%%%%7%%%%%%%%%%%%%%%%%%%%%%%%%%%%%")print(sas.place_order(transaction_type=TransactionType.Buy,instrument=sas.get_instrument_by_symbol('NSE','INFY'),quantity=1,order_type=OrderType.StopLossMarket,product_type=ProductType.Delivery,price=0.0,trigger_price=8.0,stop_loss=None,square_off=None,trailing_sl=None,is_amo=False))# TransactionType.Buy, OrderType.StopLossMarket, ProductType.Intradayprint("%%%%%%%%%%%%%%%%%%%%%%%%%%%%8%%%%%%%%%%%%%%%%%%%%%%%%%%%%%")print(sas.place_order(transaction_type=TransactionType.Buy,instrument=sas.get_instrument_by_symbol('NSE','INFY'),quantity=1,order_type=OrderType.StopLossMarket,product_type=ProductType.Intraday,price=0.0,trigger_price=8.0,stop_loss=None,square_off=None,trailing_sl=None,is_amo=False))# TransactionType.Buy, OrderType.StopLossMarket, ProductType.CoverOrder# CO order is of type Limit and And Market Only# TransactionType.Buy, OrderType.StopLossMarket, ProductType.BO# BO order is of type Limit and And Market Only#################################### TransactionType.Buy, OrderType.StopLossLimit, ProductType.Deliveryprint("%%%%%%%%%%%%%%%%%%%%%%%%%%%%9%%%%%%%%%%%%%%%%%%%%%%%%%%%%%")print(sas.place_order(transaction_type=TransactionType.Buy,instrument=sas.get_instrument_by_symbol('NSE','INFY'),quantity=1,order_type=OrderType.StopLossMarket,product_type=ProductType.Delivery,price=8.0,trigger_price=8.0,stop_loss=None,square_off=None,trailing_sl=None,is_amo=False))# TransactionType.Buy, OrderType.StopLossLimit, ProductType.Intradayprint("%%%%%%%%%%%%%%%%%%%%%%%%%%%%10%%%%%%%%%%%%%%%%%%%%%%%%%%%%%")print(sas.place_order(transaction_type=TransactionType.Buy,instrument=sas.get_instrument_by_symbol('NSE','INFY'),quantity=1,order_type=OrderType.StopLossLimit,product_type=ProductType.Intraday,price=8.0,trigger_price=8.0,stop_loss=None,square_off=None,trailing_sl=None,is_amo=False))# TransactionType.Buy, OrderType.StopLossLimit, ProductType.CoverOrder# CO order is of type Limit and And Market Only# TransactionType.Buy, OrderType.StopLossLimit, ProductType.BracketOrderprint("%%%%%%%%%%%%%%%%%%%%%%%%%%%%11%%%%%%%%%%%%%%%%%%%%%%%%%%%%%")print(sas.place_order(transaction_type=TransactionType.Buy,instrument=sas.get_instrument_by_symbol('NSE','INFY'),quantity=1,order_type=OrderType.StopLossLimit,product_type=ProductType.BracketOrder,price=8.0,trigger_price=8.0,stop_loss=1.0,square_off=1.0,trailing_sl=20,is_amo=False))Place basket orderBasket order is used to buy or sell group of securities simultaneously.order1={"instrument":sas.get_instrument_by_symbol('NSE','INFY'),"order_type":OrderType.Market,"quantity":1,"transaction_type":TransactionType.Buy,"product_type":ProductType.Delivery}order2={"instrument":sas.get_instrument_by_symbol('NSE','SBIN'),"order_type":OrderType.Limit,"quantity":2,"price":280.0,"transaction_type":TransactionType.Sell,"product_type":ProductType.Intraday}order=[order1,order2]print(sas.place_basket_order(orders))Cancel an ordersas.cancel_order('170713000075481')#Cancel an open orderGetting order history and trade detailsGet order history of a particular orderprint(sas.get_order_history('170713000075481'))Get order history of all orders.print(sas.get_order_history())Get trade bookprint(sas.get_trade_book())Get historical candles dataThis will provide historical data butnot for current day.This returns apandasDataFrameobject which be used withpandas_tato get various indicators values.fromdatetimeimportdatetimeprint(sas.get_historical_candles('MCX','NATURALGAS NOV FUT',datetime(2020,10,19),datetime.now(),interval=30))OutputInstrument(exchange='MCX', token=224365, symbol='NATURALGAS NOV FUT', name='', expiry=datetime.date(2020, 11, 24), lot_size=None)open   high    low  close  volumedate2020-10-19 09:00:00+05:30  238.9  239.2  238.4  239.0     3732020-10-19 09:30:00+05:30  239.0  239.0  238.4  238.6     2102020-10-19 10:00:00+05:30  238.7  238.7  238.1  238.1     2132020-10-19 10:30:00+05:30  238.0  238.4  238.0  238.1     1162020-10-19 11:00:00+05:30  238.1  238.2  238.0  238.0      69...                          ...    ...    ...    ...     ...2020-10-23 21:00:00+05:30  237.5  238.1  237.3  237.6     3312020-10-23 21:30:00+05:30  237.6  238.5  237.6  237.9     7542020-10-23 22:00:00+05:30  237.9  238.1  237.2  237.9     5182020-10-23 22:30:00+05:30  237.9  238.7  237.7  238.1     8972020-10-23 23:00:00+05:30  238.2  238.3  236.3  236.5    1906Better way to get historical data, first get the latest version from githubpython -m pip install git+https://github.com/algo2t/alphatrade.gitfromdatetimeimportdatetimeindia_vix_nse_index=sas.get_instrument_by_symbol('NSE','India VIX')print(sas.get_historical_candles(india_vix_nse_index.exchange,india_vix_nse_index.symbol,datetime(2020,10,19),datetime.now(),interval=30))Get intraday candles dataThis will give candles data forcurrent day only.This returns apandasDataFrameobject which be used withpandas_tato get various indicators values.print(sas.get_intraday_candles('MCX','NATURALGAS NOV FUT',interval=15))Better way to get intraday data, first get the latest version from githubpython -m pip install git+https://github.com/algo2t/alphatrade.gitfromdatetimeimportdatetimenifty_bank_nse_index=sas.get_instrument_by_symbol('NSE','Nifty Bank')print(sas.get_intraday_candles(nifty_bank_nse_index.exchange,nifty_bank_nse_index.symbol,datetime(2020,10,19),datetime.now(),interval=10))Order properties as enumsOrder properties such as TransactionType, OrderType, and others have been safely classified as enums so you don‘t have to write them out as stringsTransactionTypeTransaction types indicate whether you want to buy or sell. Valid transaction types are of the following:TransactionType.Buy- buyTransactionType.Sell- sellOrderTypeOrder type specifies the type of order you want to send. Valid order types include:OrderType.Market- Place the order with a market priceOrderType.Limit- Place the order with a limit price (limit price parameter is mandatory)OrderType.StopLossLimit- Place as a stop loss limit orderOrderType.StopLossMarket- Place as a stop loss market orderProductTypeProduct types indicate the complexity of the order you want to place. Valid product types are:ProductType.Intraday- Intraday order that will get squared off before market closeProductType.Delivery- Delivery order that will be held with you after market closeProductType.CoverOrder- Cover orderProductType.BracketOrder- One cancels other order. Also known as bracket orderWorking with examplesHere, examples directory there are 3 fileszlogin_example.py,zstreaming_data.pyandstop.txtStepsClone the repository to your local machinegit clone https://github.com/algo2t/alphatrade.gitCopy the examples directory to any location where you want to write your codeInstall thealphatrademodule usingpip=>python -m pip install https://github.com/algo2t/alphatrade.gitOpen the examples directory in your favorite editor, in our case it isVSCodiumOpen thezlogin_example.pyfile in the editorNow, createconfig.pyfile as per instructions given below and in the above fileProvide correct login credentials like login_id, password and 16 digit totp code (find below qr code)This is generally set from the homepage of alpha web trading platformhereClick onFORGET PASSWORD?=> SelectReset 2FAradio button.Enter the CLIENT ID (LOGIN_ID), EMAIL ID and PAN NUMBER, click onRESETbutton.Click onBACK TO LOGINand enterCLIENT IDandPASSWORD, click onSECURED SIGN-INSet same answers for 5 questions and click onSUBMITbutton.config.pylogin_id="XXXXX"password="XXXXXXXX"Totp='XXXXXXXXXXXXXXXX'try:access_token=open('access_token.txt','r').read().rstrip()exceptExceptionase:print('Exception occurred ::{}'.format(e))access_token=NoneExample strategy using alpha trade APIHereis an example moving average strategy using alpha trade web API.
This strategy generates a buy signal when 5-EMA > 20-EMA (golden cross) or a sell signal when 5-EMA < 20-EMA (death cross).Example for getting historical and intraday candles dataHereis an example for getting historical data using alpha trade web API.For historical candles datastart_timeandend_timemust be provided in format as shown below.
It can also be provided astimedelta. Check the scriptzhistorical_data.pyin examples.fromdatetimeimportdatetime,timedeltastart_time=datetime(2020,10,19,9,15,0)end_time=datetime(2020,10,21,16,59,0)df=sas.get_historical_candles('MCX','NATURALGAS OCT FUT',start_time,end_time,5)print(df)end_time=start_time+timedelta(days=5)df=sas.get_historical_candles('MCX','NATURALGAS NOV FUT',start_time,end_time,15)print(df)For intraday or today‘s / current day‘s candles data.df=sas.get_intraday_candles('MCX','NATURALGAS OCT FUT')print(df)df=sas.get_intraday_candles('MCX','NATURALGAS NOV FUT',15)print(df)Read this before creating an issueBefore creating an issue in this library, please follow the following steps.Search the problem you are facing is already asked by someone else. There might be some issues already there, either solved/unsolved related to your problem. Go toissuespage, useis:issueas filter and search your problem.If you feel your problem is not asked by anyone or no issues are related to your problem, then create a new issue.Describe your problem in detail while creating the issue. If you don‘t have time to detail/describe the problem you are facing, assume that I also won‘t be having time to respond to your problem.Post a sample code of the problem you are facing. If I copy paste the code directly from issue, I should be able to reproduce the problem you are facing.Before posting the sample code, test your sample code yourself once. Only sample code should be tested, no other addition should be there while you are testing.Have some print() function calls to display the values of some variables related to your problem.Post the results of print() functions also in the issue.Use the insert code feature of github to inset code and print outputs, so that the code is displayed neat.