Transcript for:
Introduction to Algo Trading by Rivas

hello everybody good evening so my name is Rivas I'm going to prepare some videos on AlgoTrading today is the first video it's introduction to AlgoTrading so the topics going to cover today's what is AlgoTrading prerequisites for AlgoTrading the programming languages available for AlgoTrading from brokers like Java C C++ maybe PHP Python and which brokers provide our APS for algo trading like Zerodha, Fires, LS Blue costs involved in algo trading so there are some extra costs involved in algo trading other than trading charges like brokerage and STTs from government how to subscribe to Zerodha trading APIs just for explanation purpose I am going to show you how we can subscribe to trading APIs of Zerodha and types of APS what are the types of APS the brokers provides like trading APS that means order APS, data APS and basic design of algo system how to design algo basically and installing Python and zero the Python SDK so in this video we are going to write sample program in Python and going forward in next videos we are going to use python for our development and algorithm and the broker i'm going to use zerodha and sample program in python code to log in flow with zero the apis so i'll explain when it comes then risk involved in algorithm okay let's see what is all good reading algorithm is nothing but a program trades on behalf of a human with a predefined set of rules It's just a piece of code in whichever language you write Java, Python, C, whatever. So when you start the program it interacts with the broker APIs and whenever you get the signal as per your code it places orders and whenever the time comes for exit it squares up the trades. So the program is trading on behalf of you. That is nothing but AlgoTrade. So what we need here, we need APS from broker to interact with the backend system to place modify or cancel orders. Broker also provide the default interface like if you in case of Zerodha they provide kai.zerodha.com or they provide their Android API to trade manually. So but if you want to trade automatically from your program. So you need to bypass their interface and you have directly interact with a backend system using APIs to place modify or cancel orders. And the algo system you're going to build can be semi automated or fully automated based on your own requirements. Like if you just want to generate signals and you don't want to place the orders automatically so what you can do you can implement you just keep fetching the data, write logic for signal generation and show the signals on your web page where you provide some buttons to place orders. So upon clicking buttons the orders can be placed or modified so in a semi-automated way but if you want fully automated then you need to write everything on your phone. I'm the prerequisite. For algo trading, as I explained already, we need APIs from broker to interact with back-end system to place orders. You should have some little bit of coding background. So for programmers or software engineers it might be easy to start getting into algo trading but for non-coding background people it's a bit tough but possible because nowadays there are some programming languages like python which are very easy to learn and start your algorithmic implementation using python language. You need to spend few weeks on learning python so don't worry in my videos one by one I'm going to explain the code as well so that before watching my video you can prepare with some Python basics so that it's easy for you understand. But in this video... You just need to observe how the code is being written. A little knowledge on different building blocks of Algo system that interacts with each other. So what are the components involved whenever you are implementing your Algo system? And uninterrupted internet connectivity. If you are running your Algo on your local machine, you should make sure that you always have internet connectivity because your Algo keeps... Checking the status of orders and positions placed into broker system. Or else if you are using cloud to run your algo then you don't need to worry about internet connectivity as the connectivity is always there. And last but not least much you should know about trading. At least basics like few indicators, moving averages, bowling a bench and some stuff. At least a little knowledge about trading you should have. before entering into Alcatraz. And then coming to programming languages required. So there are brokers providing these days like APIs, sorry, SDKs for Java, Node.js, PHP, Python. So which programming languages to choose, it's up to you. There's, you can choose any programming, whichever you're comfortable in. In terms of speed, I mean, which is best one? Generally, C++, C hash has higher speed compared to Java than comes to other languages, node.js, PHP, Python. But it doesn't matter which programming language you choose because we, retailers, are not going to have a high frequency trading. So only those having high frequency trading systems require, may require C++ or C hash because they need to place the orders within not even microsecond, even less than that, sorry, in microseconds. So, VDLs are okay with placing orders in milliseconds. Since Python language is easier and it's more popular these days, there are so many tutorials available, so I suggest if you are not from programming background, start learning Python to build your own algo. Next, which brokers provide APS for algo trading? In India we have many brokers who provide APS for algo trading. The first and robust APS provider was Jiroda, next Fires as per me. And the other brokers are Allizeblue, Stocks, Interactive Brokers, 5Pesa and many more. So whichever broker you are trading with, you can try using their APS. And for for learning purpose you can use Jirada broker for implementing your system that's the best way I can say because their APS is very good and they have easy to use I can say yeah then choosing broker is in dependent on robustness of the APS and back so when you finalize your algo and you want to trade with some broker so It's own decision which broker to go with. So when you try different brokers while implementing your algo, you will come to know which broker is providing robust APIs. Like anytime you place orders, you should have some availability 99.9%. Some cases when broker has issues, your orders fail. In some cases, the broker may go down for continuous. you know maybe five to ten minutes sometimes even for half an hour so that's way the robustness of broker comes into picture another important factor is brokerage of course we trade with discount brokers whether it's manually or even with algo to reduce our charges and last there are some broker charges for APIs and some brokers give you a base for free Next, what are the costs involved in Algotrade? So cloud cost, if you deploy your algo on cloud, so you need to consider this extra cost like if you are running some simple program, it may cost you around 15,000 to 20,000 per annum but if you are building a big software and running many accounts and more processing about what you need. speed, fast internet connectivity etc then you may need to pay more like maybe it can go up to 1 lakh per annum the cloud cost. So if you are trying from your home PC if you are running your algo on your home laptop PC. Then you need to pay internet charges. So you need to consider these internet charges or costs involved in Alcatrading. And broker APAs. As I said, there are some broker charges for APAs. In case of 0DAO, they charge 2000 rupees per month for trading APAs. And other brokers like Fires provide APAs at free of cost. And there are other APAs like historical data. you to get candlestick whether it's intraday or day week month candles data they charge for again zero charges for two thousand rupees per month extra so if you are subscribing to trading your place and historical.aps in jirada then you will be paying four thousand rupees per month so that is the cost of algo trading if you are trading with the jirada If you cannot code, another cost involved is if you are not a developer and you are not comfortable coding or you want to hire some programmer, maybe from freelancing sites and making you work, then you need to bear this cost and to develop your algo from a developer. But this won't be a one time cost, please remember, because as you keep improving your strategy, you need to alter your code and some changes from broker or exchanges then you may require to modify your code from time to time so each time you request your developer to change something so it's going to be cost for you so this is again a cost involved in algorithm but if you are doing everything on your own then you don't need to pay for this and at last trading costs are separate I mean just like you do manual trading brokerage charges, STD, GST CB, transaction charges etc anyways they are already there, it's applicable for both if you do manually or through algo and next we go to I am going to show you sample how to subscribe to zero dot trading api, so many of you already know and using the api but just for people who don't know about how to subscribe to zero the ips we need to go to this site developersky.trade.login and create a new app there I'll show you some example going through that site let me open developer you can just go here since I am already having account if you don't have account here you need to sign up so this is not same as 0.client ID you need to separately sign up for the developer account and just logging into developer account there is some app already created in my account so if you want to create a new app click on create new app so this they charge two thousand rupees per month so they are automatically depended from your trading account For that you need to connect your trading account. When you click create button they will ask for your zerodha client account and you need to authorize that and they will debit 2000 rupees per month from the linked account. Let's see you give some many name. Let's sample python algo something. Any name is fine. So give your client ID whatever. 1, 2, 3, 4, whatever. Then there is a redirect URL. So what is this redirect URL? When you are implementing your algo, right, you will be running some server. So you provide some redirect URL. I mean, you expose some API to external system. Why this is needed? In algo trading, the first step before placing orders or whatever you want to do with your trading account, first you need to be authenticated with your client account right so first you need to log into your broker account get the access token so if you just normally log into kite.jirada.com you sign in with your credentials and you enter pin and that sign in will take you to the jirada kite page right but if you want to get access token in your application in your algo application then you have a mechanism to get the access token from broker to your algorithm. So, anyhow I will explain all those points. but just remember we need to give some redirect URL so in this case our redirect URL will be for example since I'm running the program and local machine so you can just give some say this is my redirect URL I'm going to a so in my algorithm my algorithm is running on this port and my local machine and this is the API I'm going to expose for as a redirect URL so when the login flow completes the Jiroda redirects to this URL and this will ultimately request your algo so that will actually request I mean Jiroda calls your redirect URL with access token after successful login so once you get the access token then you are done with the login flow I'll explain those part for just remember that redirect URL is mandatory postback URL you don't need now we'll use it later just ignore and description some description whatever you want okay when you click on create the app will be created and you'll be given a API key and a secret right so in this case since I'm already having some Africa I'm not going to create otherwise they'll charge for me let me go to my apps inside recreated so this is one already existing app So this is my Attaquant main application. This is RedactUR. This is my server where I'm running here and cloud. And some app and this client here is here. Here you have the API key. OK. And if you click on this show API secret button, they will show the API secret. So in your algo trading, if you want to interact with the broker API and your account, first you need API key and API secret button. Right. you have to copy these two things and configure in your algo application so I will explain that in next part so this is how you subscribe to Jiruda APIs you can give any name for the app name it's up to you next come to the PPT okay this is a screenshot I just shown you there to subscribe to Jiruda APIs going next slide okay what are the types of APIs provided by the MZeroTab sorry any broker so here your algo program is running and there is a broker back-end system and there are different types of APIs you need to use to interact with broker back-end system first most is login API in order to place any other API's in order to call any other API's first you need to log into broker system from your algo program so that is Those are called login APIs. Login API is mostly based on redirect URLs. Login URL and some redirect URL. And then instrument APIs. So what are these instrument APIs? Each broker has their own set of instrument codes. Let's say in case of Zerodha, when you are placing order for SBI. So SBIN is a symbol name, but there's underlying instrument code for it. So for placing order for SBI you need to know the underlying instrument code then only you can place the order. In case of 5S you don't need an instrument code you can just directly use SBIN some colon EQ if it is cache base you just prepare the symbol and you use it. So what whatever you need to instrument APIs let's say you need to know the available option symbols, strike prices, our future symbols etc. So all those details are there in when you call instrument APIs you will get all those details. It's a big list. You don't have to call every time whenever your algo starts in the morning. Just fetch all the instruments via this API and store it in your system and you can use those instrument details later while you're placing orders or modifying a cancel line. or even you're fetching historical order. Then comes to order APIs. To place the trades you need order APIs. Order APIs of types like placing a new order, modifying order, cancelling the order and changing any other parameters of order like you have a limit order it's not at field you want to change the order to market so you just change some field to market and fire an API so it will change the existing limit order to market order. then some codes API so codes API is nothing but you want to get the current market price of any symbol that infi you just pass the instrument code of infi To this API you will get the current market price. Current market price not only contains current market price but it also contains the day high, day low and day open, yesterday close and volume traded so far etc. So the code APIs contains this. And next comes to historical data APIs. If you need historical data APIs then you need to subscribe separately for that. And these historical data APIs. Generally start from 1 minute candles, 3 minutes, 5, 10, 15, 30 minutes, 1 hour, so day, 1 week, 1 month. So you can call any timeframe APS based on your requirement and if broker provides. And in some cases you may need to read, get positions, get funds from your broker account into your algo. So there's other APS for providing those details as well. and next come to what are the basic design of algo system there are different components in when you are building is some algo so what are the things involved in it right so first most thing is you need to log into broker right so log into broker and get the access token of your account of your broker client Once you get the access token, you can use that access token to place the orders or fetch the instrument or whatever, get position, get funds, whatever the APS you want to call are possible only after the successful login and you're getting the access token. So once you log into from URL Go, then you need to fetch all the instrument data so that you'll be going to use for the entire data day while interacting with the broker system, placing, modifying orders. Then initialize ticker service if using web sockets. So what is the ticker service? There are two ways to get the current market price. As I told you there is the APS, get quotes. If you call the get quote API and passing some symbols you will get the current market price details of all those symbols. So that is a HTTP based but if you want to if you want a faster mechanism like if you want to read the ticks within milliseconds then you need to go with web socket based. WebSocket is like one layer before the HTTP layer that is TCP. There will be a connection established between your algo and broker. The connection is always live and the server, I mean the broker server keeps pushing the ticks onto your algo. So it is very fast, you will keep getting the ticks of so many symbols within milliseconds. So if you want to if you have some building some breakout strategy and you want to be as fast as you can as whenever the tick crosses your level, I really recommend going for websocket. But if a strategy is not that time sensitive and if you are say placing the order after closing let's three minute candle or five minute candle in that case you don't need to worry you can just use the get code API which is slower compared to websocket. If that satisfy your requirement then you can go with that as well. No issues. Then after fetching instruments and utilizing ticket services then you start your strategy. So you need to write some code in your strategy. So what are the signal when you want to place orders. Let's say if you are trading a moving average on 10 minutes time frame. let's say EMA 21 crossover EMA 30 and you want to place order so that kind of logic you need to write you in a strategy and after strategy there will be some order manager running in your account in your algo so that order manager picks a signal from your strategy and once the conditions meet it will place the orders okay once place the orders place orders means so you're calling the place order API of brook so after placing the order what we need we generally places a lot of right and target order if applicable. Some people may not have any target then you may need to square up your position at the end of the day if it is intraday right so then after placing the orders what else you do you keep tracking the status of all orders and alter if needed Like you, if you are trailing SL, so there is a SL order place, from time to time, let's say every five minutes, you want to check the current market price and the market is moving in your direction, your trade, I mean. Then you modify the SL order with a new trigger price and call the corresponding AP. So the order will be altered. Then when you come to closure of market closing, then you need to scale up your trades. So how do you square up if you already having target data you just modify to market data to close this trade. If you don't have target order for the trade you just place a new target order to exit the position and don't forget to cancel existing orders. SL order or any unfilled orders and then log out from broker so this is the basic design of algo system of course in if you go internal data there are so many things internally but this is at a high level you are all going to be you need to you are going to take care of and here now you're going to Write some sample program. So for my entire all videos I am going to use Python programming language based on some requests in my Twitter account because many people are comfortable with Python. I already implemented some Node.js end-to-end application fully automated one but due to many people not from developer bank and it's tough to use I decided Python is much easier than Node.js so we will start building the algorithm from scratch in Python so what are the requirements first of all to implement your algo in Python so first she is like you install the Python software so here I'm choosing Windows operating system if you're another operating system Linux or Mac so there also the similar things work but the installation of Python and the dependencies may be different another operating system but in my tutorials you I'm using Windows operating system, I am on Windows 10. Make sure Python folder is set after installation. So what does it mean? It is by default set. In case if it is not set, then you need to check your environment variables. open cromon prompt and just type Python to see the version of python install on your machine along with Python the package manager pip will also get installed so what is this pip using pip actually you can install the dependent modules which we are going to use in your program for various purposes like you want to create a HTTP server you want to create rest API and you want to use 0.kyte SDK API so there is again some other module you need to install that 0.kyte module using pip command so let me just go to my command prompt here I'm just cancelling let's say you open it how do you open command prompt you just go to someone cmd so you just type Python minus V which version so it's saying Python so Python is installed and I'm able to get the Python running So this is the version I installed on my machine, python3.8.1 If you want to install on your machine, just go to this link Go to python org downloads, there is a latest download python available, 3.8.1, just download the python and install it on your machine. So after installing python you just need to open the command prompt, like I just did, just type python minus capital V so it will show you the Python version installed and Python is done then now we do next okay so we're going to create a sample project for algo I already created one here okay let me I just call it is this all go trade Python this is the folder I am going to implement my algorithm okay here how I organize this So there is a src folder, source code I am going to write in it. So the source code is going to be in python files. So.py extension means, so that is a python file, python code written in that. And there is another folder I created just for maintaining the configuration. Here in configuration I am going to use json files to give some fixed configuration like the server port on which you want to run your algo and some user details like client ID API key, API secret and some details okay and you can use any editor for writing your code so in this case I'm using some sublime so this project is already here right so the same thing whatever I shown you here this project I just open that folder in my IDE editor Here there is a server.json, here I am just maintaining some configuration at system level on which port my system should run. So this is 080 port. And enable SSL, SSL port, these things I am not going to use now, so just leave it for now. Just going to use only this port. And users, there is a user.json file, so here I am just going to configure my client id, what is the client id, my json is 0 the. I am going to demonstrate only about Jirada for now. So this is my client ID of Jirada and API key. and API secret of my application so what are the app you created here on zerodha so these are the API key and API secret I am going to configure in this file which will be used when my Python code runs right and there is a redirector this is a redirector I am going to configure zerodha right let's see so what will happen so just for demonstration purpose I am going to use this right So what is the redirect URL I am exposing on my machine. So I have to make sure. I am just going to update my existing app with this redirect URL for demonstration purpose. I am just updating and saving the details. I have saved my app. Now coming to the code. So this is the src folder. So our code starts at this main file. main.py Right. Before going to the code, I would like to explain few things related to environment, how to make your program is working. So if you go to here, if you go here, installing 0.python SDK, right? Open your command prompt and we need to install a module called flask. So why we need Flask? We are going to start a web server on the port we configured, that is 8080. And we need to expose some APIs so that the broker can call your algorithm API after successful login. In a redirection mechanism way. so it will send back the redactor URL provided by you to the browser and the browser calls your API after successful login and then only you will get the access token once you get the access token then you can do anything with your broker account another thing after flash we need to install the Jiroda kite connect SDK so that is provide this link you can go to this link Jiroda I'm just opening that so this is the zero github they have project in github zero that is go here just follow the instruction what they did after you install the Python after you install flash then install this pip install and just go open your command prompt and you know you can just run like this since I already installed on my machine I can even write no issues you can just run it So it will since it's already there it went so fast it's saying already installed but in your case it will say time finished installing. So it fetched from internet and installed the kite connect SDK module. Okay and There are some tools needed by the they are recommending you to run this command as well some setup tools in order to do But it's not going to work the straightforward even after you install this so when you run this command and you will get some error so the error may be like There are some errors like Microsoft Visual C++ 14.0 is required. So if you are on Windows 10 and you are using Python 3.8.5, you will get this error if Microsoft Visual C++ build tools are not installed. So what we do is to do that first you need to go to this link, Visual Studio, go here. and there is a build tools right build tools for visual studio 2019 go ahead and download this one when you click on download you get some binary like this already installed I'm just showing going to show you so we have build tools some some machine number and then this is just double click on it since I already installed so anyways let me check so it's already installed before you get started is something continue this continue so what will it will prompt you for installing the build tools this wedding yeah there multiple things see there's so many things right so install this one this one you don't need all these things you should enterprises to the professionals rhythm we don't do anything just only select we just to do build tools 2019 and just click on install I already installed that's why it's already showing is under install tab and this is going to take you know one it will download some around 1.2 GB data from internet for installation and then it will it may take around 4 GB of your system space for installation so it will take a good amount of time I'm not going to do that part already install it so maybe depends on your system speed it may take 15 to 30 minutes for installation so once the Visual Studio installation done I mean you should have built tools For C++ done, then you need to restart your computer. So restart your computer and then again open the command prompt. Do this pip install upgrade-cite connect. This run this command again. So this time you will get successful. Without build tools this command will get failed. After that then run this command as well. pip install minus u pip setup. So once you are done with this then you are ready with Jirada SDK. for Python right next so this is sample program in Python to code login flow with zero there is a source code I just read it I am I have a screenshot here and then how the sample app looks when you open the Algo and the browser. So how do we log into Prokera? I'm going to explain those things. I'm also sharing my sample project at github.com This is a project here you can go there and download the project and modify accordingly. So this is just sample I mean today we are going to have only you know login mechanism so as we keep progressing and implement developing in Algo we will keep updating the code by one week by week let me go back to so they did it here once we are done right so you install the SDK right connect I know the set of tools and so we are done so what what we already since I already opened this one so whatever the project you folder key where are the folder you created are you downloaded this go to that folder and go to the src folder So I am going to show you how what is the code I have written here. So first we need to run what we need to run here. This is the main py right. So you can either run python space you know main dot py or you can just simply do py py and then the main dot simply this is the main program we are going to start. This is main dot py is nothing but our algo program. So what is the main dot contents of the main dot py. Here what I'm getting is instead of hard coding the port number and some user details here, what I did is I'm maintaining in a separate files in config here. So this is a server config, right? Get server config, this is a function. So first basically before understanding the code you should You should be aware of basic syntax in Python. If you're not aware of, just please learn the basics of Python. It may not take that much time. For developers it won't take even one or two days, but non-developers it may take one or two weeks to be comfortable with. So just go through some tutorials on Python from beginner tutorials and learn some basic programming stuff in Python. So how do we just import? There are some modules. Let's say we install a flex module. This is a third-party library. and we are going to use some functionalities of flask module and from Jiroda we will use some other there's another here in this file I'm going to use the kite connect we install using pip this is a kite connect module we are going to use some functionalities from here so to connect to our broker interact with the broker I'm going to start a server using flask and this is the code I only written here this is nothing but from zerodha there is a zerodha.py file here so I'm calling some function login zerodha get kind right and here from config there's a config I'm importing all here so there's a config.py so when this means from config import me basically what are the code written in this config.py file I'm just importing here right so there are two functions I have written here this definition Get server, this import JSON so I need to I mean I want to use some JSON utilities that's why I did import JSON this is JSON is system by default it will comes with Python so I don't need to explicitly install this module right I have written two things here definition get server config so what did exactly this nothing but this just returns the data I have stored in this config server.json file right this completed as port enable is a little board similarly there is a user.json To access this data from config.py I have written function get server config and another thing get user config. So when I, this function, whenever called, so this will actually, what it does, it just with open, so the file name dot dot, so one go back and then config folder, server dot JSON, I am opening this file in read mode and declaring this reading as an object, a server. So this object I have, and I am loading this object using JSON dot load, so I will get the JSON data from this file. So that is nothing but the send data. So JSON server data, this will return JSON server data, whichever is there inside this server.json file. Similarly, when we call getUserConfig function, so I'm reading this user.json file and reading more and just returning the data from this user. So if I go to main py, here I imported those functions using this line. What I'm doing is server, get server config, this function I called from here, right, this function. Now I got server config, this is the data. I'm just printing whether I'm getting the proper data. as expected on it. Similarly I am calling the get user config right from this file config dot py this is giving me the user config. So what happens till now let me just enter py dot my. I'm shorting my server. So what happens see there's a print here server config port 8080 So this is the data I wrote in the server.json file. Similarly, user config, this is the data I wrote in user.json. So we are able to read the data from config.json file successfully. We are going to use this data in our application. Now I need some port. I don't want to hard code it. I am reading from server config. Server config is nothing but an object. So this is an object, python object. So inside that we have multiple fields. like port enable currently I'm just going to use only this port not other fields you can ignore other fields for now so main.py and just make server config data of this field port so the value of this port field is 8080 here so I'll be getting the 8080 value in this variable port next I am going to use flask to create HTTP server right also we'll create rest apis I am going to do some configuration so debug mode true so that whatever things happening you will get some prints here if there anything wrong you'll get error and if everything is going successfully you'll get log something like this okay no prints and then see when you start how do you start your server app here I declared these two things and here at the end I am actually starting app.run. So how do you want to run your application? That is you want to run your application on localhost. This is a home IP address and the port number that is nothing but 8080 that we read from server.json. So this actually starts HTTP server on your local machine with the port 8080 right. So and once your server is started so it has to serve some some requests right. So what are those requests? What should happen? What is the home request? What does mean this slash? Slash means it's a home. So what does it mean when you open say yeah you when you use a browser called localhost localhost is nothing your own machine then I am writing colon 8080 port so you are trying to access some server that is nothing but your algo right from your browser when I click enter so what will happen this will basically yeah So load some page here right, so welcome to algo trading in python login. How this text got under here? So I will explain. So this is nothing but you are not given anything. This is nothing but you gave some slash. Without slash or with slash is same. So this slash is nothing but this is your home page. So for serving this home page what I am doing here. This is the app route I am configuring using method get. Whenever the browser requests your server with the home page as slash, so what I am going to do, I am going to return some HTML text. Thus HTML text will display this part. So this will render like this. So where that HTML is present. Instead of writing the entire index.html here itself, what I am doing is I am modularizing and maintaining it in a separate file for clear understanding. So render template, this flask actually have another utility, it will just render the template file of your HTML file and it will return to the browser, ok, from wherever you are calling. So here I gave index.html, from where this index.html reside. You need to create a template file here. So Flask understands this folder and in this folder wherever you mention the path of the file is nothing but index.html. So this index.html, I have written some code here. Some default HTML code, this is some style CSS code for coloring and buttons. And there is some script what should happen when you click on the button. This is JavaScript code. And here comes the HTML body part. This is welcome to all go trading in Python. This is nothing but you shown here. And so. So the class name style and center etc. So these are the CSS styles used from here and then comes to a button here I have a button. Okay, this button class button and then so what should happen when you click on the button on click log into broker. So this when you click on this button, this will call the JavaScript function here log into broker. So here what I'm doing is I'm just changing inside this log into broker and just window location. Hey, sir, but now I'm just changing the URL here in the browser. So So, when you what is that URL basically is nothing but I am just calling this I'll go server another AP right so where we are now we are on a home page now right when you click on this we are requesting another page that I have written within the client code so when you click that does browser changes the URL this one does nothing but localhost code and zero slash apis broker login zero the so for this this is a rest API I'm going to I will implement in our algo so what is the purpose of this okay so when you landed on that particular request we'll do some stuff for now this is the index.html this is whatever the code written here is being rendered here So this is being transferred from main.py file. Whenever the browser calls your home page slash we are just returning that index.html file content to the browser and the browser rendered here. Now when you click login.broker so as it will. So we are going to call this. Write in this URL browser, call this way, this is what is it, this is nothing but your own algo and on this port and this API. So what will happen when this, when the request received on this route, okay. So here I have written the code, if this route in this app using method get request, I have written some function here, you can write any function, let's say login broker. So this function will be called whenever browser request on this route. So here what I'm doing login to zirada. While calling this function I'm passing the request.orgs. So in this case we don't get any orgs because we don't have any arguments. Question mark there are no any query parameters here. But when the broker calls the same redirect url, sends back to the browser after successful login, the broker actually appends the query parameter. access token, request token, some set of parameters, okay, which we need after successful login. But in this case, anyhow, we just passing the request.arguments that came as part of query parameters. I'm calling the login zerodha. Where is this login zerodha? So there is a file I have written zerodha.py here. In that file I have written the functions login zerodha and get kite. Okay now I'm going to login zerodha.py file. Here we call login zerodha right. So what are the things we are going to use? The kite connect SDK we are going to use. That we install using pip install. So using this command we install only right. pip install upgrade kite connect. So only after you install successful installation you will be able to use this kite connect module so there are some functions within the kite connect module this kite connect maybe is class so what I am doing is easy so here we need one thing earlier we need server.json right so what are the details but here we need the API key apsecret right so from where you get we already have those details inside this user.json file. What I'm doing is I'm just doing a from config import get user config. So this I imported here and just calling that. So this will give you me the user config which are there in user.json right, API key secret and any other parameter. So here I am just declaring some global variable here to set to use it later. So I will explain later. But what the function will do? This kite connect. Okay. So we need to pass apk key to the kite connect. So we have the user config object and in that apk field is there. This apk is nothing but this is the field. Okay. This is the field. So when you call user config of apk you will be getting this value. Right. and that value I am going to set to this api underscore key and passing to kite connect class or function whatever it is. So when I do this, this will return me the kite object. Now since we have, we came from the browser right, how we came here? From browser when you click the button, when you click this login button, so what is happening underlying right? So how we came here right? I will explain, when you click that button. First we landed here the browser call this API because we have written this in index.html right on click what should happen when you are here login.jerodha call when you have login.jerodha we don't have any arguments here right request token so when jerodha calls us this is called but in the current case we don't reach here when I click the first time from the app So, I will go into this case because we don't have any arguments, no arguments in the arguments object. There is no request token that means I understand that okay this click happened from the other. browser when user clicked on sign into broker button so I will come here so what I am doing is I need to tell the browser okay I need to redirect the browser to the broker login URL from where the user can sign in his credential and can come and go with your login flow when user clicks on button we came here via this login.jrodha and now here we are here okay not here this case comes later I'll tell you when this case comes but currently we are in else case what I am going to do is I am getting the login URL from kite object so this login URL see when I click that this login URL is printed here if you see that see login URL print this is the login URL given by me given by broker to the I'll go right so this is basically this is a login URL what the Jiroda gave us they appended our API key because we passed the same API key and this API key is valid in case of the API key is not valid you will get some error instead of the redirection URL right so these are the things so what are these are the arguments passed okay the arguments API key argument and some version 3 anyhow whatever when you get this right this is the URL given by Jiroda to the algo so now what I am doing is I'm just sending the response back what I am sending here code 302 so what does 302 means in a request when the user click on submit button and when I reach here I am responding the browser with 302 HTTP status code and the URL so what does the 302 is nothing but I am instructing the browser just redirect to the link I am giving you. So this link I am responding back to the browser with the status code 302. So what happened internally when I click that button, I will show you again. We are at the local host, right? Local host, 8080 port, this is our home, age of our algo, right? Let's see if I can... So when I click here, right, we went there and the server, I mean the algo server gave us this related URL with http 302 status code and the browser understood and browser directly went there whatever given by whatever the URL we passed to the browser, that is nothing but this one we got from broker and we just pass to the browser with the status code 302 so the browser is understood and it it replaced the browser url event here so now when you go here the account is different so i'm changing now you just log in into your zero the account enter and it will ask some right okay all right so now this will redirect to your what happened underlying okay see I'll tell you what is what happened now after successful login what the broker did the broker actually instructed the browser to go on to the redirector they gave the redirect URL so this is the redirected URL given by broker to the browser So, what is the Redirect URL configured in the app? This is the Redirect URL, right? We are configuring the app where you auto-contact. Yeah, this is the one we configured. But after successful login, what the broker does, they append the query parameters like action login, status success, and request token, right? They're responding with these parameters, right? Now, when they're instructed the browser to go here, right? To the browser again. calls our server algoserver on this route with these parameters this time earlier when user click on submit button there were no parameters right but this time we will get again this with the extra parameters now the same request again come in the main py so this is the route right browser requested and we call login 0 that went here this time what will happen We have request token inside the argument. What does request token? Nothing but this one. So this is also being passed now. Now that means this request came from the broker and browser passed the request on to us for a successful login flow. Now after getting the request token from here, what we are going to do is we need to generate the session. Ultimately we need access token finally, not request token. I just printed the request token here. If you see, the request token came here and access token also printed here. So what I am going to do is using this kite object that we created from the kite module, kite connect module, kite generate session, I am going to generate session using the request token given by Zerodha. And here you need to pass the APAC CRUD. In the first step we are passing the API key right when you get the redirect URL from the broker for while logging we are passing the API key and that will redirect to the broker login page after you enter your credentials and all then the broker redirects to the browser with the request token and the browser calls our algo server API and again we landed here but this time we are going to insert this if condition because we have the request token system now using that request token and the User config, APS secret, this field we have configured here right. So using this value we are actually generating the session. So after generating the session we will get the access token. So if you inside the session you have the access token. Just get the access token like this. I am just printing the access token here. We may not use it because we can directly use the kite object for doing any activity like placing, modifying, cancelling, whatever the orders. Now comes here, kite set access token. So after getting the access token you just need to call this. So for the kite object we are getting this. So what we are doing exactly here, there is a kite object, we are setting the access token. This access token actually refers to a particular account, worker account, right? This we got only after the successful login flow. So that means you have authenticated your algo through this login flow mechanism. to get this access token onto your algo server so once you have the access token I'm just heading to kite object and this you we are going to use this kite object X across your application once you get so the login flow is complete what I am just returning here after successful I'm just returning some HTML text this actually login successful and I'm returning access token so this is just for and that is what he printed here okay this is what written by the algo server now The thing is successful right? Now success will be. We got the access because of the logs. You see the access token and you know. So, I am just trying printing some holdings right. So, this is if you go to main.py, so just to show you something. So, after access token what things you can access. Now, today we are not going to do any order placing and all that will be in other session, but just for demonstration, but I am going to tell you I have also written some routes here your algo server. If you call this positions here, so from the browser, so the request come here in this function. So here get kite so we already have the kite object created when we have login flow so this kite initially null, none so once after successful login we said that and with access token also there's a proper object right with a proper session. Now if I call this kite get kite okay like this get kite is nothing but I'm getting from 0 to and I just calling get kite at position so it will give the position. I'm just returning this thing JSON format the position similarly holdings this is a holding so what does it mean this is a router this algo is created okay you created this APS rest APS in this algo so what does it mean if I just do localhost since the session is already created right the server is running in the background if I call this positions right right enter So this will actually land here. So there is some issue here, I don't know, but maybe this is getting stuck. I'll do press enter so that it's going forward. It may not happen on your machine. Okay, see what happened. So these are the positions. How I got the positions from my broker account? These are the positions, right? How I got these positions? Simple. So when you... type this post slash position this is your algo this is the positions route so we landed here positions this is a corresponding function we are going to execute this code so here I am just getting the kite because the kite is already available as part of a login session with the proper set now and get from the kite object I'm just calling a positions function it will return me from the server from broker server you will get the fetch the position and giving giving to my algo I am just giving back to the browser for similarly I can I have already another route I already here holdings right if I click on holdings I'll get the holdings see there's some liquid piece holdings price quantity etc so this is when you call this from holding so that will launch here this holding this route we call this is how we are done with the sample program I'm just repeating what exactly so you how do you how do you want your server this you need to start server your py.min.py right So here what exactly we are going to do is just reading the details, server config, user config details from the config.json files instead of hard coding here. And the port number we want, which port you want to start your HTTP server. For starting HTTP server we are using flags module which we installed through pip. Here that's how we are using some functionalities of flags using this flags. So there are so many other features also but here in this demo we need flags, render template and request. This request basically to read the arguments here. Okay, this request.org whenever you... redirected from the broker to browser and browser calls your API then you get arguments and the request okay so this model is one you are using so when you just need to start your HTTP server and localhost and with this port and these are the routes I configured here so based on when you just launch your app this will be this code will be executed where inside the browser when you click on the browser button API broker login this API is going to be called here this code will be executed and this call will from two places that is when you click the sign up button first time or you are redirected from the broker and the browser calls this button with the query parameter quest token and then these are the pages just for demonstration purpose just added positions and holding and we are getting from the kind of position displaying and returning back to the browser so this is how the login is made so i'm just going to explain the same thing what is the login flow here in the terms of Sequence diagram. So if you want to see here right, so this code I am going to put here, so you can just download from here and you can refer and go to the parallel directory and call as I mentioned in the video. Now going to the next sequence diagram login flow. So whatever the things we did in the code, I am just going to explain. So this is a browser and this is algo server, your algo server, this is a browser, Chrome browser as you, and this is a broker backend. So send sign in request to the broker request. That is nothing but we are clicking on the sign in button, sign in to broker. Now what the algo server did? Our algo server did, redirect URL to login to broker. We actually, so okay I missed something here, I just want to, we basically what we, okay we didn't even interact with it. Yeah, we actually interacted with the server and we get the redirect URL from the broker to login and we just redirect the URL to the browser. So what does the browser do? So just redirect onto the URL. So now when browser redirects onto the web, this is nothing but the kai.jirotha.com that page and with the API key. So when you log into your broker, when you landed onto broker page, so broker will ask you credentials like username, password, then pin. After successful authentication, the broker sends back browsers. This is send back browser authentication. Once you enter client-ready password, pin, etc. on successful login, this broker redirects to the web. Send the browser back the redirected URL you configured there. We have configured some redirected URL in the browser right. So along with that URL, actually the browser sends a refresh token. Sorry, there's a mistake here. I had written access token but you let me just change it now itself so that it won't be confused. So the broker basically respond back to okay. Request token. so sorry okay it is going here so now we got request again from the broker to the browser and browser browser what it will this is nothing but our algos our URL right that rewrite your nothing but our browser get to do a request on that so we have a request again once we have request again we internally on algo we are calling kite dot you know setting the gate session we are calling and when you are bypassing the IP secret and this request again Then you will get the access token. Once you are getting the access token that means you are successfully logged in and your session is ready. After that you can use any APIs like order APIs, get instruments or you get position, get holdings or whatever APIs you want to do you can do. So for demonstration purpose we just did get positions and get holdings for today's tutorial. now that's it we are done with the sample program how to do a little successful how to make how to authenticate your app for your broker ID sorry you have your broker login I hope that helps you if you have any questions you can ask me the comments you can even follow me on Twitter I have two double zero three zero six two anyhow since I have some other My regular work, I am generally busy so I may not answer all the queries but I try to keep answering the questions in the next videos by collecting all the questions. So now, everything is fine, you are doing all good, trading is good, you feel this is very good, without any manual intervention you can do trading if you are able to write the code and strategies and all. What are the risks involved apart from the strategy and all? So if you have a small bug even, you know, if you have some coding mistake you did, so there can be a big loss happen, right? So when you are implementing, right, you need to test it thoroughly with small quantities, right? Minimum, let's say, one, two quantities on your database. Because while development, it may happen, you have, your algo is firing so many orders. Instead of one order, let's say there's 20 orders went to the broker. So that may, you may lose big money in that case, right? So while implementing, you do test with a smaller. Quantities Only when your algo is ready, I mean bug free, I mean stable, then only you put your real money with actual trading capital. The brokers may have issues, right? If your algo is trading, you are logged into broker, you place some orders after some time, let's say in the afternoon, broker went down and you know, so you have open positions and your algo can't do anything. Even of course, you manually also you can't do anything until the broker comes up, right? So those are kind of issues already there, even manual trading or algo trading. And the broker goes down after your position and can't exit until broker is there. And you, let's say if you are running your algo from your home PC, so you may have internet connected. You place orders and your algo has to take some action. But due to your lost internet connection, your power has gone, no power, so laptop is not running. So you have open position in your browser. So your algo can't do anything, there are other risks involved here. So you have to manually somehow enter into your broker terminal and close your position in that case. But if you're running from, I'll go from the cloud, right? So then you may not have these issues, power issues or internet issues. and in action there are some issues like you'll say you placed your order and after your original order place you place a sell order and target orders but after some time due to sudden spikes of falls what happened right the NSE exchange cancel your order it happens in case of option trading when the price goes out of execution range right so your SL order got cancelled your algo should be intelligent enough to detect that okay your SL order got cancelled take some action whether you square up the position if you don't if your algo doesn't take any action In that risky scenario, you may end up in big loss if your position is open. When the position is created by the broker, end of the deal. And another issue, broker may cancel all your orders if something reset on this side. So this may also happen. It happened few times in the past in Zerodha, but nowadays there are APS robots and they are working fine. But don't think that, okay, this may not come in future, but just be prepared for all kinds of issues and your algo should be able to handle all those. You need to code everything in the algo because you can't monitor your algo every second. So even though your algo is fully automated, what I want to say, you need to monitor it as well. every 15 other teammates because its real money is involved in right. So, that is how you understand right that is. So, that is how algorithmic is a good I mean some point out, but they also risk involved the extra cost involved as explained in the previous you know PPT's and all. So, ok with today I am going to end this session. In next session I will try to explain order will in the. If you are using order apis, you need to be in live right, so I need to prepare next video during live market hours, it's not possible for me after market hour, so I will try to get some time and write some code in python for order placing and all. So once I am ready with those order placing apis, I will prepare another video and probably next week I may be ready with another video thanks for watching, if you have any questions please ask in comments or better to ask in twitter but I may not answer all of them, as I told you I will just collect all the questions and try to answer in the next video thank you all, good luck, see you bye bye