How I built my trading bot - Detailed Code Walkthrough C# .NET Core

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
everybody back again and this time we've got the video that all six have you been waiting for me to announce in today's video we're going to look that's my trading bot I'm gonna walk through the code exactly where the code goes what it's gonna be doing and sort through some of the ideas and the approach that I took and why I did what I did so let's dive straight in okay so let's just get straight into it then what we've got here is my initial setup and the way I've decided to approach this is about making a number of classes each class will have its own full task and it's all responsibility so you can see here from the comments those are my classes those are my helper classes there I'm going to reference three minutes so to get started I wanted to make sure that I could track things in a database because I decided if I was to run this without keeping my own log and I was a wholly dependent on logs from somewhere else that may not give me all the information I need in order to make decisions on whether things are working the way they're supposed to work or not so we've got myself a trade about context which just talks to all hosted sequel server and you can see the models here which I've created which get utilized by my helper classes I mentioned a second ago so the very first thing that happens is we're at a console.writeline first initialized class is what I've called the cache manager second we've got the top me top movers after that the stock agent and finally the old stock agent so the job at the cache manager I decided was this is where I can reference to try and find out exactly how much money we've got any given time so this is really get used to decide what the available funds are to be distributed across those five stocks that we're going to invest in and I've wrote a couple of methods such as check status that basically just means that if I'm running this for the first time and we've got how many I've got how many cash we just generates ourselves $1,000 you just put the comments of initial you can see they would put that out as well available balance becomes the total sum of the cash transactions which are just people thousand dollars the only other available method that we references develop balance and as you can see there I reference in my database the cash transactions we sum up the value so that value field will consist of both positive and negative entries so you know that if you have a thousand dollars in a cell in Excel for example and then move down and you put minus 50 if you do some of that so you know you gotta get 950 and likewise if in the cell below you add 100 you'll use somewhere again you'll have a thousand 50 so that's what's going to happen I'm just going to keep injecting audit style entries so that I can call a son any pointing and go and do that so moving on we've got the top movers so the top movers and helper classes where I have my URL to hit the Yahoo endpoint that we talked about the previous video and basically use that endpoint to then go and hit the page bring back the raw HTML and as I described in the previous video I then go and split that out to go and get the actual relevant bit in the middle if you munchin whole web page inside the middle of that web page is the only bit of information that I'm interested in so I need to chop off the start chop off the end and what I'm left in the middle is the bit that I'm actually interested in and that's what we're doing here so you can see here we use the native web clients and then I pop you late the entire and HTML return value into that string this data value so then what I do is I split that into a array now what that'll do is it will give me a which has then got two parts to it the first half is the first half of golf that I don't care about and the second half is the bit that I'm interested in with the rest that a remainder of golf that I don't care as well and that's where the second line comes in which does the same operation again but asks it's simply split on this closing square bracket now that is as you can tell it's going to be an array closure and I know that that's the bit that we interested in so I split on that take the first half of it which is the bit we want and then I append back onto it again closing square bracket that I just removed from there what I'm able to do is populate my actual list that I'm interested in call it results are at least a 10 is quite results and then we use this Jason convert class which would be serialize it so these serialization is the is basically taking what is a serialized object into a string and then taking it into a full object again but I'm turning mine into a generic list after class car top mover routes objects top mover odd roots objects is literally a definition of what that information looks like based on how Yahoo have defined it it's not my definition if you are huge definition the results is then I've then have this object available to me resource which is a list of top movers and I can take from there then the movers that I'm interested in is going to be a new list and I'm gonna take and add to it and the top five entries from Yahoo because I've seen yeah here entry there's gonna be more than five I then just log it we've earned like a message top 5 movies discovered it's got to this point we're not blowing up we know we've got the five movers and then we've got a simple for loop we're gonna iterate over those five items and we're just going to prints out onto the console what those movers are this for those people are unfamiliar with with them string that former is you take a string and you can then escape the string with a opening and closing with the curly brace and inside that the string you can just basically put in an index of the following parameters that you include so there's my string you can see there I'm saying insert and so the first parameter that's index 0 the second item index 1 the third item index 2 now this is quite nice because what you actually do if I wants to put that out twice I can then go on a pen that again and just go like that and I don't have to rerun sit I'll call this number three you can just pick it back up again the way you want it to and as you can see there and then just gonna prints out so I use obviously our index that's going to be tracking it from the follow referencing the move is ray and taking the symbol which is just going to be the symbol of the stock so Apple would be a APL for example the move is the regular market change percentage and then we run a method that just runs commit to DB so that's gonna do rather than just blanketly commits in the database I go and check if the last entry that I entered into the database much is what we just did and it's really just a case of making sure I don't over populated database with information that doesn't necessarily be that to be there and that's what this does it effectively says go get the last entry and if the last entry is knocked off and the last entry symbol one much is the the symbol in the first part of the array and rinse repeat rinse repeat two three four five and no is the same so you can see they're not committed a bit the database is the same before otherwise there has been a change in which case we'll just take our top 5 stocks class create new item and add that to their database here context add new top 5 movies start context save changes and just to commit it to the database and then just add to put it on a message to our console that says new moves after the database and that's what that does okay moving on so next we got some our stock agents so the stock agent really is just my helper method to go and dive into the database and pull back information that we know about a stock or pull information from the web and then commit that to my database again so it has two approaches get what we already know I'll go and get new information and committed so what we know a couple of methods available in here so we've got get from API get latest prize purchase max stock purchase new move this purchase stuck with you know premises going in and sell the old stocks set on stock stock agent yeah this is quite a bit involved in this in this particular class rather than looped through this class I think what we'll do is we will come back to this when you see them being used to think if I've just run through this might be a bit overwhelming finally the last helper method is the own stock agent so if we're going to the old stock agent this basically is the purpose analyzing all of our stock transactions and creating entries in our in a nice referenceable table that is a state at the given time it's been built so what that means is if I was to not call this class and keep trading then this would this piece of paper if you like if you think of it like that is gonna be out of date but I can I can call a method inside here to refresh that anytime and that's what this does so this class here this this method sorry called build portfolio from transactions so we've one of there is we go to our database the on stock table remove everything committed to the database so that we don't have any stocks and then for every transaction that we currently have we'll check if we already have a reference to it and if we don't we create it and if we do we just increase it by the difference save the changes that we go along in case we see all these transactions for all these different stocks it comes out to zero I don't need to know about zero so we just deletes the zero on stock so that we don't have anything in database it okay that summarizes my helper methods let's crack on and get straight into the actual functionality first thing I'm going to do is make sure we've got a reference to all of our live current stocks and then we go dive straight in and say sell anything there's no longer relevant to us sell old stocks method because I'm pulls back our top five movers and angles and checks if anything this you know portfolio that's no longer in the stocks we've run a sell stock method on that stock itself the sell stock method fires as follows we record a stock transaction class symbol itself it's quantities multiplied by a negative one so I know that it's a sell rather than a game and my value is the stocked up value total value is the absolute constant term stocked up value and a pro comments as sold as part of the old stocks committed to the database and then do a another entry to database which will record the cash transaction so that stock transaction and the cash transactions are completely separate do that so that I don't have to look at counting of stock prices and stock quantities when I just want to know how much middle of balance I've got when it comes to checking what we can spend so there we go that just runs through cash transaction total value the comment sale that goes through and it's a database same database changes market see the console next up is we go and purchase any new movers the parameter itself is how much money we got spent so that runs from our cash manager so let's have a look about that method this method runs in and we've already told it how much we've got so I want to clean rom that bid thousand dollars so you say twenty percent of the balance we want to divide it by five so we can split that equal amounts across the five stocks so we just got vailable balance peoples itself divided by five I'll get the latest moves from the database a couple of comments purchase as many shares as we come per mover by bit by the available balance and get the current price for each stock record if I want to log everything to be know exactly where we're gonna go wrong we can see it five of these lines vast ball one through bar five and astrally the exact same method and just basically hitting our API to go and find the latest price for that given symbol so let's have a quick look at one of these you can see here we're using the Alpha Vantage API and there's the Alphonsus data TSD this is the way there there comes back switch got a timestamp and open up high and low and a close and all I'm gonna do is gonna get the latest one of those for each given symbol so we got a list of them all no monthly prices and we will know the method to get from API so this is the bit that she goes and pulls for the information from our vantage so what we do is we prepare a place holder object to receive the information first and if we wrap this up in a try-catch now the reason why I did this is because if we try to make too many calls in a given minute the whole thing blows up because that's a restriction by alpha Vantage because I'm cheap and I'm not paying for an account and running on their free account so this is just a bit of a hacky method in order to you not have to keep a track of how we have done it in that one minute and rather just to try it and if the itami know then I'll wait a minute you can see here I go on gravel populate in some of the prices string dot formats this is the URI that we hits which is their API URI and we're going to go in there and we're going to push in time series daily is the function the symbol is the reference that we're going to passion us that's the bit it's gonna change and it's just got an API key and this is the bit that I'm adding extra which is a two type CSV because the information in CSV Pharma is easy for me to pass based on what they problem I discussed in last video gets pushed in URI from CSV so we going to do that get that information back down as a CSV past that they want to sue the Jason deserialize string method into this type of object multi prices becomes the this the content from this URL so this will trigger if we've done souvenir requests in which case I will write to the to the console kaboom it needs to pay 60 seconds tell the whole things to go to sleep for 60 seconds this is 60 seconds times 1000 milliseconds because the the sleep threat the sleep method takes a value of milliseconds not seconds and then we just log again where we trying and you can see here we actually just running the self so this is consuming itself so that this whole thing all over again up here and it's going to return back to itself and return back of the crisis okay so at this point we wrap we've then got a list of the monthly prices for this particular symbol I don't want to do is create a new type of stock price this symbol which we've just asked for the value in the very first entry the top entry of the CSB so the top entry of the generic list that we created the official time stub which is taken from their day two rather than what time I think it is go and get the last entry that we had and just check if it's the same if it is the same do that log otherwise let's add it to our database and I'm also going to pass it back to myself so I can I've got access to ever need it and that takes place five times over to populate the latest prices for each of those five now that method will get used again in the future I'm not going to go over it again next book think that happens five times over again I wonder why purchase Marc's stock so inside here we're going to say this is my available balance this is the symbol that we're interested in so pitched my stock goes through and this is because it simulated there's no API calls here once you just go into creates a reference to the max that can purchase which is based on the amount that I've got to spend and they're going to divide that by the value of the stock value so again if the available balance was 200 and the stock value was 100 then I know that I'm currently by two so it's very possible that we can't buy any because the stock price is going to be greater than our available balance that we have we've got to buy in this stock in which case this has just wrapped up in an if statements make sure that we come by at least one and if we can we've run the purchase stock method so we're going to pass in the concert we're gonna buy the stock price item the objects itself and I've just got a notable override parameters are here in case I don't how to be custom comments so all we're gonna do create a new stock transaction populates it with the contents that's relevant to this particular stock add it to the database and just like we seen with the selling of the stock really create a cash transaction value as well it goes through and it seems all to the database we've run through all this and we've run a one final Save Changes the idea there was just we're just holding back on the database rights that we're just doing lots of different Lister rights which can let them all played up in our database context and commit them all in one single transaction so upon finishing buying the removers we don't least need to repopulate our portfolio which were only got over not gonna do that again and I'm just going to tell myself the new move is purchase complete and we've got a remaining balance so again we're running my cash manager you see where these methods are gonna come in hardly no can't we the available balance so if we had a thousand dollars which I spent nine hundred that would report the mental balance is now 100 rinse repeats every one minutes so originally I tried to have a rather over complicated over complex over engineered whatever going to call it and check to see if we were inside the time of the NYC trading hours that I just thought you know what let's leave it true we'll always loop and I know that we cannot buy or sell a stock from the stock market if it's not open so we'll let them do the the check rather than so we go to sleep for 60 seconds we've got a console.writeline an empty line and I'm gonna just write down the fact that we are going to sleep and I'm also telling myself what time it is that when I look at the the console if he's if he says he went to sleep a given time and it's been longer than plus one minute I know it's crushed as simple as that we call because to sleep sixty seconds we wake up let's tell myself I'm waking up and then we do the fetch movers so fetch movers we've already seen that goes on checks to see if there's any change in top five movers and celery leftover stocks the same thing we did very first booted the BOP rebuild our portfolio prior to doing it just in case it's out of sync and we try sell socks we don't have that's what that's what that's prevents it and then we're gonna purchase their movies so these are the these really is the same thing we started off of doing we've just then pushed into a loop really we could have put the loop at the start like it was run through upon completing all this we're just gonna write a little message to ourselves and say new rumors pagers complete the remaining balance is this and breathe so hopefully that wasn't too quick and try and Serbia's details that possibly can without taking up 45 minutes to an hour long video which no doubt it could have been if it had gone through in absolute detail so what's next well it's been no secret that's simulated trading as you can see there so I'm running on the bait on the principle that I have money imaginary money mathematically I come by so many stocks at a given site for a certain price and it would record all those I'm gonna sell them where we record the price that I sell them up but I can do a comparison at the end to see how much money I'm left over with I mean you're gonna be all I will be down rarely but I might even balance out but it is a real so there are a couple of factors which I'm aware of which could influence any discrepancy such as a transaction fees or even just delays in the actual Commission so as you can see how much the assuming bit at the given time have I've checked that price it's not changed even even by a millisecond which as we know in the stock market that kind of happened which why there's a lot of investment in tech to make things as fast as possible to get that prize from the decide to pull the trigger so the next plan is I've actually got this application further developed than what you've seen today it's actually plugged into the alpaca API a backer API is a stock trading API only there's no front end to sort a use apart from a nice little dashboard so summarize your your mood and your API calls and as he stands at the moment we're running against that and we're running against what's called a paper account so the paper accounts um is a pretend money again what it's actually running against the real markets so I'm subjected to the real Christ populations I'm subjected to the real delays in my calls and the actual time in between and when I say I want to sell it at a certain price and whatever as when he actually hits the API and actually commits of both bills itself yeah well letting that run for a couple of days to collect some data and another video together so stay tuned for that one otherwise I hope this was informative enough and if you'd like to see anything in particularly even more I'm aware that I'm not gonna need pretty any background details about how programming works but hopefully that's that's a story that you don't need to hear hope that was a benefit and you enjoyed the video as much as I did making this up looking forward to seeing where this progresses to next time looking forward to see what happens with the alpaca API a little bit of an inside scoop it isn't as wonderful as this one let's put it that way once we'll see what happens so if you enjoyed this video please do let me know hit the like button I wouldn't very much appreciate if you subscribe to the channel and you share with anyone else that you think may have interest in this type of thing if you like to see anything in particular that isn't going to be coming up with the alpaca API that what I mentioned please do let me know and I'll see what I can do otherwise look after yourself stay safe thank you very much it's the next time bye bye
Info
Channel: Code and Create
Views: 14,438
Rating: undefined out of 5
Keywords: code and create, trading bot, day trading, c#, .netcore
Id: LPQFUME0GGA
Channel Id: undefined
Length: 20min 35sec (1235 seconds)
Published: Thu Jun 04 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.