Transcript for:
Building a Crypto Trading Bot in Python

hey I hope you're doing well now have you ever wanted to run your own fully customizable training but that works with crypto but wait a second by works with crypto I don't just mean that it trades crypto I also mean that it is successful because it harnesses rather than fights against the main feature of crypto and that's volatility you know crypto is definitely the most volatile asset out there so we might as well make the most of it right well that is why today I want to take you on a journey to create exactly this kind of training bot in Python easily it will run on a crypto exchange and even manage multiple coins at the same time if you feel like it and all this for free now if you're curious to know what this sweet little Power house can achieve take a look at these results let's start easy with ethereum and it's 764 per profits in just a few years but more importantly a very healthy Equity curve as you can see and a stunning win rate of 85% and all this for a maximum draw down of only 16% all in all actually gave a very attractive sharp ratio of 1 .3 now let's crack it up with Bitcoin which boasts a staggering 1 141% profits and also a beautiful robust Equity curve it maintains also a very appealing win rate of 86% and listen to this a maximum draw down of only 7% and a sharp ratio of 1.4 sounds almost too good to be true right well that's great if you're skeptical cuz today I'm providing you with every tool you need to make your own mind we will also dive deeper in results analysis later and explore other coins but always keep in mind that past performances are never a guarantee of future results I can never emphasize this enough now just a technicality the codes that will be using are in Python but you don't need a extensive knowledge to run everything I'll be as pedagogical as possible and as you will see I've developed everything such that it is very easy to change parameters or setups and test them and then run what one prefers but now if you do want to learn about python or you might or you need a refresher about your knowledge we do have a comprehensive python for finance free course available on this channel you'll find it in this article from our website robot traders. linked it in the description down below the link is here and in there you'll find all the chapter videos but also a written format of the course I've also linked in this article all the resources for this trading board so here are the links to our GitHub of the Python codes will be looking into shortly and I've also coded the strategy of this trading bot in pinescript so if that's more your thing you can find it here and here's the V the link to the video that explains it now let me also add that all of this is absolutely free and open source this is really the philosophy of this channel okay now let's get practical I've only shown you some fancy results so far but I want to emphasize that the real point of this video goes beyond that it's really about empowering you with all the tools you'll need to effectively manage a trading bot like this now maybe you don't really know and you're not used to trading Bots and you're wondering what does the endgame look like well let me show you so here I am on my bitg Futures Trading account that's indeed the crypto exchange I've developed the trading bot to work on so what I'm going to do now is simply run the trading bot and what you'll see in a few seconds is that you're going to have a bunch of trigger orders popping up here and also updating on the chart here and obviously all these trigger orders these orders depend on the rules of the Str strategy so these are my entry conditions my exit conditions my stop losses Etc that will trigger or not depending on how the price moves and you can see as well what I can do I'm going to run it once again and what you'll see in a few seconds is that it is going to delete all these orders and going to be placing some new ones so obviously what's oh and there we go you can see them here coming up so obviously I'm for the show I'm I'm launching the training bot live by myself but the whole point of this video is also to get it to run automatically on the server and now we are choosing a AWS server the reason for this is that it gives a free instance for one year but to achieve all of this in other words to ensure that by the end of this video you're not only capable of handling this bot but also are comfortable with it operating by itself we need to go through a few key steps and of course this has to begin with a proper understanding of this volatility Master strategy the bot uses then as you know any strategy is defined by trading strategy is defined by a set of parameters and rules and before using that strategy with real money it is crucial to back test the strategy in other words evaluate your choices of parameters and rules on pass data now I have said and it is clear that past performances never guarantee future results but on the other hand if you test and you find out that your strategy doesn't work well with past on past data on historical data then your strategy probably needs to go to the rubbish so you need to check for that also keep in mind that it is through careful back testing on various market conditions that you can identify robust parameters for your strategy so that are all the reasons why we'll take some time to thoroughly analyze some back test results of this strategy and also go through the P the python code that does these bacce so you can do your own testing do your own modifications and possibly create your your own strategies with all of that and then finally we'll be able to go through all the steps to install and automate this live training bot on the add AWS server and I will also explain how the live trading bot code works so again you can Implement your own setup but also use it as a template to build other trading Bots if you feel like it okay enough chitty chatting let's get down to business and review this awesome strategy trading view will be perfect to get a nice clear picture so first let's discuss building blocks and rules so really this strategy is a mean reversion strategy and I've tailored it to work on a 1H hour time frame so the first building block is really this short-term price average that you see here in white and from there what we do is that we compute some key levels so we simply displace this price average to create those envelopes here and the concept the idea with this mean reversion strategy is as you can see the price here goes peace follows peacefully his life but every now and then you have a anomaly a volatility Spike that you see here and what happens with these spikes is that in general they get corrected quickly so the price goes has this bump but then goes back to the price average quite fast let me zoom in a bit no strategy is perfect not all Corrections go so fast Etc but that's but it works quite well and that's the spirit of the strategy so as you can see here what happens is that what we say simp is that when the price hits one of these bands here we enter a trade so now you understand what we saw just before these orders that that were placed on the crypto exchange or those trigger orders that we saw and that we saw on the chart well some of these correspond to exactly these levels that you see here technically speaking I chose them to be trigger orders and not limit orders because limit orders are a bit of a pain in these case because they block your funds so when you want to put multiple exits for the same position the same entry you have issues in other words you can't really put a takeprofit and a stop loss at the same time because one has taken all the capital and the other one won't execute so trigger orders are the way to overcome this anyways so those trigger orders correspond exactly to these levels here so what we see here is indeed that the price hit the this price level so we enter a trade we actually carried on the week the wick I'm I'm not sure you see care properly the Weck of the candle goes down to this one so we also we again we enter another trade in other words we grow our position and it actually stopped around here and we didn't hit the third band so we that's it for the entries and what happens is a few candles after the price goes back to the price average and that's our exit and we exit all this this POS this complete position or these trads at that level here when the price hits the average and now in terms of how do we deal with the capital how does the bot deal with the capital because we have to decide how what the position size when we enter each of these trades and that's quite simple it takes the number the total Capital available given to trade this crypto so here we are doing using ethereum as our example so given that capital we divide it by the number of envelopes in other words we enter with 33% of our portfolio for ethereum on this trade and another 33% on this trade and if we had hit the last ban then that means we would have entered with all our portfolio on this candle but here we didn't we only did two and sometimes it might be just one so we engage only 3% of the trade in that case that's really a way also to mitigate the risk by spreading the our entries on several bands and the number of bands is something you can customize and choose yourself so that's that what I want to also emphasize is that this strategy here I've singled out one trade but this strategy what it really loves is ranging markets where the price really closely follows its average and every now and then and sometimes quite regularly it hits it has a it suddenly does a lot of Trades and you can there'll be periods with nothing happening maybe one trade then periods with a lot of trade anyway let's have a look at this a bit more in detail I just want to show you a few extra trades you can see I there's a lot of very nice trades happening here but what's interesting is maybe this second one here because you see the first position the first let me show it the first entry is here and then we have another entry and then the third entry is here but and the exit is at the Point here so what happened the anomaly was quite strong so it did change quite a lot the price average so we only exited at this point here I think I haven't mentioned this so far but maybe you saw it already the bottom bands are green that's because we bet we do a we we enter a long because we're betting that the price is going to correct going back up and I think we we do have an example here the upper bands are red just to show that when the price hits those upper bands we enter short because we're betting that after the price hits these bands it's going to correct back down towards the average that we see here anyway parenthesis close what I want to mention is that this first trade actually was a loser the first this first entry let's have a little um let me do a little price range so we can see so you can see this first one we lost almost 5% but the cool thing is we have also those other entries so this other one here this one would have given us a plus 2.5 something okay 2.6 um% and that last one here would have given us a 6% profits so overall this total position here this total trade would have been profitable but I mean sometimes you might also have the three because there's a big pump you might have also the three entries that end up being a bad trade and that does hurt your profits but you so anyways I think you see the nice the clear picture here it likes a lot when you have these little bumps and that's really how the bot the bot works and really manages to catch profits okay cool we're done with general concepts and rules so now let's talk parameters and then we can finish with risk management actually let me toggle this on so we see all the parameters of the strategy so these are indeed what you'll see again in the python T back testing code and the live trading bot code so first things first the price average so this white line what is it computed on well we're using the close we're averaging over the close of the candles but technically speaking you could choose something else if you felt like it now as I've mentioned it's really a short-term price average so that's why you see a five here in this example and in terms of the type the type of average this is a Donan channel midline in this example that's why it does look a bit Jagged sometimes and but if you wanted something more smooth or you're used to something else you could very easily test and choose some other like this smooth simple moving average beg your pardon exponential Etc and if you ever even felt like adding your own favorite average in the code is very easy you can do that there's no problem now in terms of the envelopes how do we get these levels very easy we displace this price average by a given percentage so the first envelope here is a displacement with respect to 7% in other words to get from here to this upper band we displace by + 7% and to get to the lower band from here we displace by minus 7% easy so the next envelope or the next set of bands is now a displacement of 11% and you've understood the last one is 14% great then we get to the risk management parameters so we have a good old stop-loss very important 0.4 here means 40% and remember this with respect to what well with respect to the average opening price so 40% with respect to the average opening price because that's what's important for margin requirements okay then price jump percentage this is 30% as well this is quite a special risk management rule that we'll get back into in a bit so now at this point you might be wondering well what do I do with envelopes how many should I consider in this example there's three but maybe I should go for four five whatever it's a bit hard to give you a general rule and well guideline Etc this depends on you your feeling and you have to test for everything but the general idea is that for more robust coins that are less volatile that have a more inertia so when a correction is generally very quickly converted corrected and goes back to the average in other words for Bitcoin ethereum the really big top cryptos of the market you don't need too much envelopes and that's why also we have this very nice kind of smooth curve by the way recently trading view reduced the earliest date you could fetch you could Bank test on on a 1 hour time frame down to back to 22 before it was 21 recently so that's why I'm a bit sad there's not a lot of Trades to give you a nice U meaningful curve but we'll get to to back this with much more data in the when we get to the python code anyways so for that's how you get those smooth curves is because you've spread across several envelopes and for a the those the main market caps you don't need too many envelopes so now let's look at something a bit more volatile and we can go for example for AER and what I do with AER is that I add an envelope because it's more volatile has more jumps the corrections can take sometime longer to correct I tend to go for an extra add an extra envelope and spread them more so let's just remember I want to show you this is about 99% profits a maximum draw down of minus 10 and if we now so an a curve that looks quite Jagged but still very nicely smooth and now what we'll do is is that we will simply add an envelope so I'll just go to add a o. 177% so now what you should see is that we did lose a bit of profits which is really marginal but we did decrease the draw down by 3% so 3% when it was 10% is quite a big change and you can see I don't know if we actually see that but it should be a bit more smooth so that's that's that's how you generally can change the the number of envelopes the if I had to give you a big I'm having a hard time if I had to give you a general guideline the more volatility your coin has that you you want to trade the strategy on you spread more the envelopes and add more so you really spread your Capital across several levels Etc okay so I've mentioned the strategy really shines in ranging markets but that's also means it makes this strategy a really good hedging tool because you can couple it with your more standard trending Trend strategies which them these tend to underperform during ranging markets but now no strategy is perfect and this one is certainly not an exception and it does come with some risks so let's discuss them now also understand the strategies limitation and look at what could potentially cause trigger some big losses if not handled properly so what this strategy really doesn't like is sudden strong pumps and therefore also sudden strong dumps so in other words very violent very sudden strong trends that that trigger so in general for this strategy I would really avoid trading coins that react violently to news and things like that and here we have a case with xrp so you might remember mid last year 2023 we there was a judge that ruled that Ripple didn't violate us Securities Law which was a great news in its ongoing case with the SEC and as a result of that of that news the pump really reacted very favorably for that so in 1 two three four five candle or something like that we the pump price almost pumped by 70 75% which is a huge pump right but what happens with this strategy with the in in when these pumps happen that you don't really have a correction right it's not like this those nice little bumps that the strategy loves what happen what happens is that you have this average price before the pump and then after the pump the now the new average price is way different from that much higher in the case of a pump so what happens is that you you have this price shoots up but also the price average shoots up and on top of this it takes several candles a lot of candle candles before the candles go back to the price average so if you had entered the trade here and had no risk management tool you would o only close the trade here and what and we saw that's like 50 60 even 70% the the jump and if you had for example used leverage or things like that it's very probable that you could have been liquid at that trade would have been liquidated so that's why first sale fail safe of course a stop loss but that's not e not I mean it is a fail save but it's not great because when you hit the stop loss you do have a big dent that appears in your portfolio because a lot of the value that you engaged in that trade here is a full full since we hit the three envelopes by Def by definition here we lose a big chunk of the capital we would attributed to xrp in the trading but if we of course chose that anyways what I'm trying to say is that we have this big dent in our portfolio because as a result of hitting the the stop loss so you might tell me at this point well you know that's just simply because you didn't put your stop loss tight enough well that's true but the thing is with this strategy you can't put to tight stop- loss because it will work against you elsewhere let's have a look so I've putting 20 % and what you can see now is that we've reduced this kind of Dent it looks like we've reduced it but we've created another one so let's go and have a look what happened at this level here so we see now what happened is that on this trade we now got stopped out at the end of the week so very large Wicks so I think this Weck like let's let's go from the the price average that's like a wick of almost 23% so these are really tend to be um liquidity freak events so some liquidity issues on the crypto exchange Etc so these tend to happen much less for higher market caps coins because there's more volume exchange Etc but they can happen anyways so what you see is that this trade this those three entries so this trade um let's actually have a look this one we would have lost a tiny bit of of money 0.5% something like this but then the next entry this would have given us a plus a profit of 8% and then the last one here would have given us a well 12 11 12% profits so a very profitable trade but because we tighten our stop loss now to 20% we ended up the price ended up hitting that stop loss so we're sto so we're stopped out of our position so we lose the amount of capit we lose some capital on that position so we now created this Dent that we didn't have before so that's an example of why tightening that's the examp typically the cases that prevent you from tightening too much the stop loss so what I've done is that I've added this extra risk management tool so let's put back our stop loss even like to 0.4 but I'm putting the price jump percentage to 10% and let's actually go back to I would like to go back to our previous trade that we were having here so you see now this trade instead of hitting the stop loss up up there and having a huge dent I have a much lower Dent because the I have this what I call the clal rule that exit exited the trade at this point here so this rule is quite simple is basically saying that if I realize that my previous candle closed at a value higher than my average entry price of a given percent so here in this case I chose I'm showing with 10% then you simply close the trade and exit and therefore as you can see it does help a bit with containing those pumps and I'm saying that it triggers at the beginning of no new candle if it sees that the previous candle has moved too much with respect to the the price average Etc reason for that is that the trading bot is always always triggered beg your pardon is always launched at every beginning of a new candle every hour so at the minute zero of every new candle so it does it computation and if it sees that at the previous candle we have the close of the previous candle we have the close all rule that is triggered then we exit the position so there we go now with any risk management tool there's always a drawback and typically with this one is that if it's too tight or it's there sometimes it might close a position that would actually correct nicely so this is a bit of a tricky parameter and that's why I've made it optional in other words in the back testing codes and the bot code can simply remove it and not use it if you don't want to typically for top market cap cryptos that have a lot of inertia I simply don't use that parameter it's really there if in case you want to go for more erratic coins or it makes you feel more comfortable Etc you can just use it and anyway that's also the reason why back testing is very important like this you can judge for yourself if you like a rule like a parameter Etc let me not forget that there is one last rule to this strategy and that's that if there's any close or condition that is triggered or a stop loss the strategy and therefore the trading bot is trading bot is not allowed to trade before the price hits back closes back over the average so I this point here this is to avoid repeated trades being stopped out or being closed all out because here you see technically speaking without this rule because we close our trade here on that candle where we do have our price that hits our band and even goes beyond so technically speaking we would we would enter again the trades here but most likely we would get stopped out again or closed all out again and that would really hurt our profits even more so you see that's why I have the rule that until there is the rule in the strategy until the price closes above or or across let's say the candle at this level here we can't trade anymore so that's why there's no more trades after that during all this period but then you can see here then the the tra strategy started trading again and actually made a little winning nice little winning trade here okay great I hope you have a fair understanding of the strategy now if you have any questions comments or even later about the codes and the bot installation Etc please feel free to let me know Down Below in the comments or even join our community Discord and ask us there now before we carry on I want to make a important disclaimer this is really a pedagogical video you can use what I present as is or as templates to create build upon and create your own things that's really your decision but now nothing nothing in none of this content should ever be interpreted in any way as Financial advice you know trading with trading Bots or training manually has its fair share of risks and the biggest of all is indeed of losing your Capital so just keep in mind that you are the sole responsible for what you do with your money not me not the crypto exchange you anyway now it's time to look into some python backst because like this we'll be able to access more data further in the past but also we'll be able to conduct a much deeper analysis of the back test results I think with this code it'll be much easier for you to change and test your own configurations do some modifications or even potentially create your own strategies with it so let's fetch this code so I'll go back to the article of all the links and that's the link to the GitHub repository I have called this code crypto strategy lab maybe that's not too extravagant okay so in the readme file you have all the the steps to install get this code so we will do that quickly together I do want to show you because some of you might not be used to all of that and let me show you briefly what's in the code I also want to mention if you can give me a little star if you use this code that's that would be greatly appreciated it's good it helps with visibility okay so in the code we will have we will get to see some of these files of course but I just want to point out what's in strategies and what you see here is envelope. pi so that's the code to back this this strategy that we we're going to backest together the one we've been talking about but I did add a simple SMA dopy here so that's really it's a template basically because the envelope. pi code might be a bit complicated we will review it briefly together but if you're wanting to create your own strategies maybe using this simple SMA as a template would be easier and of course in the future I do plan to release more strategies and more training bots so I'll simply be adding them here in this repository okay so I said we would do the installation together so what the first thing we need to do is clone this um this repository of the code so I'm just going to copy this and then I've created here a little codes um for this example folder in my documents so I'm just going to now what I want to do is open a terminal this always takes ages to happen I don't know why open in terminal so here I'm showing in Windows but if you're a Linux user I'm sure you know about all of this and Mac will be pretty similar so you know what I'm simply going to put this guy on the side do a contrl v to paste and here the repository is being closed so basically let me show you you can see that now you have the folder with everything here so we have all the code on in in our folder but we still need to install the python packages you needed to run the code so I'm simply going to actually go this CD command is just to go in the correct file so in the folder beg your PM I'm now in code and i i t I always recommend this we're going to be installing a virtual environment basically because we don't want to mess up the packages versions maybe you have you have older versions for some other codes or newer versions Etc so we're just going to install the versions that work for this code in this python in Virtual environment so that we don't mess up anything with some other of your codes anyway not sure that was clear but anyways let's do it so I'm just copy pasting everything one after the other and I think did this go I think it needs a bit more time okay now I'm going into myv inv and now what I'm actually going to do is this pip install minus r requirements so pip install pip is the python package manager so that's what's installing everything that is in requirements so let me actually paste it oh I forgot to put a copy so copy then I'll come back to here and do a little paste and there we go and let me this will take some time there's a few packages to to install but let me just use this opportunity to show you what's in the requirements so you you know what we are installing so pandas very important for all the data managing ccxt this code uses C cxd to download all the historical data and the live trading bot code will also use ccxt to place all the orders and manage the API of bitet Etc ta for technical analysis and that computes our moving averages all all our indicators mat lot lib because in the backst code we want to do some nice charts this you'll see is to lightweight chances to do a very nice candle plot with our entry and exit positions and this IPI candle is for us to be able to run the code nicely in a Jupiter notebook the python packages have finished installing so what we can do is go back to our code here and I'll right click on the code folder go show more options and then do open with code so I'm opening the code with this idal VSS code so if you don't know too much about this and you need help installing it and the basics and also installing python we do that in the chapter zero of our python for finance free course great we're making good progress now that it's all set up the first thing we need to do is download the historical data for uh on the coins for our back list so this is done using this data engine. alnb which meaning a Jupiter notebook and there we we go and you can see let me run this it actually uses this data manager class this is a class that I've created that you have here and that basically handles all the downloading and loading Etc of the OHL CV data and you can see so far only only two exchange are supported bitg and binance but you can add some more if you want I don't want to go into the details of this code I don't think it's particularly helpful you can always ask me if you're interested so let's go back to our data engine so you see yeah I'm choosing the exchange to be binance I tend to work more with binance simply because it's an older exchange and therefore you can access the data on coins up to much earlier in the past so time frame one hour you can see I'm giving the list of of pairs that I'm interested in to download the data on to do my bank testing so in this example I'm just doing BTC and eth note that this B btcusd column USD means that this is the Futures Market this would be the BTC SL USD would be the spot Market market so that's that you can see that here is what I was saying I'm declaring a instance so data of the class data manager I'm feeding the name of the The Exchange that I'm choosing and here this is a little path that you can give if you want to store your database elsewhere in your computer you can give another another path here but if you don't let me run this and if you do if you don't change anything you can see that within the code there's this data folder that was created and in there we will have the all the data um that we're downloading and you can see that we just got our CSV there is in the form of CSV files and his standard OHL CV data so date open high low close volume okay so we didn't what downloaded the data is indeed this little Loop and you can see that I'm using the method data. download the pay I'm giving the time frame and you can also give here a starting an ending date if you don't give any starting and you just remove this like that it'll download all the range available on that exchange but for this example I mean it takes quite a while to download all the data depending on the time frame Etc so just for this example I just went for a tinier a very recent date so we don't have to download too much but you can see it fetched the things I just want to mention the the way the API works is that you can only download the data in batches so if you cover a long range you'll have to download different batches one after the other so it can take a lot of time and you'll have the prints going on like this and sometimes if your earliest date is too early with respect to the the listing of the coin you'll just have you'll see a little empty because the batch is empty anyways moving on I mean basically this you've downloaded the data it is on the database you can we can switch to the maest code but there's a few other little things important I want to say so when you want to load the data so it's downlo load in on the database then you want to load it in your back test you use this data. load where you have to give the name of the pair the time frame and again you can choose for a start and ending date this is particularly important because if you want to back test on different periods then you select the dates here in the loading of the data then one last thing you might not be too familiar with how you have to spell the pairs Etc so if you ever have a doubt you can just use this little function that I created here that just looks for all the pairs available on the exchange with these characters here so if I run this we'll get all the pairs that involve ethereum and since ethereum can also is also often considered in trading some pairs as a quot currency you do have quite a lot and somewhere in there you will have I think you'll have well I don't think I'll even find it but you will have for example you have ethereum um usdc usdc so that's ethereum f backed by usdc I mean traded with a currency being usdc one last thing I want to mention before we move to really the back test something very important when let me just simply run this when you trade on when you're trading there's a minimal position size requirement so you can't engage a trade with a too small amount and that amount depends on the coin so this here is just a little thing to show for you to get what is this minimum price according to the current what is this minimum amount beg your pardon according to the current price so you see for example these days when I'm running the code if you're trading BTC the minim BTC with usdt the minimal size that you can use to enter trade is around 60 usdt so it's quite a big value so you have to keep that in mind because when the bot will be running and you might spreading your Capital across several coins and you know for each coin you're also dividing the total capital of that coin by the number of envelopes then that could possibly end up giving you a position size that is smaller than this note that this however it is the counted after the leverage so say for example you wanted to enter a trade with 40 usdt but then you apply a leverage of two that makes a total size of 80 usgt so it would pass this condition so this is not included these tests are not included in the back test code but in the live trading bot code you will get an error in the log saying I couldn't enter the trade the position size is below the requirements now time to run and analyze and back this properly I did download more historical data for us to do that so now we're looking into this run envelope script so first things first we import the packages we need so you can see we're notably importing the data manager but also the backst analysis Library so this is what I've coded and you can see in in utilities here we won't go into the details of this this is just a a big class that does all the computation of all the metrics and the kpis and does also the plotting to all all all the good stuff to analyze the Backus properly this is really based on what we we wrote in the python for finance free course okay so carrying on the next one is to actually import the strategy so the rules the of the the strategy we want to back this and therefore inside all this rules all of that so you can see I'm importing Envelope as Strat and envelope you can find it in strategies so this is imported I'm instantiating my data manager here and then next cell let me actually run it straight away and what we're doing is fixing the parameters the choices of the backst so we're going to be going for as our first test we'll use BTC in terms of data you see I'm loading it and now you can see I've picked a starting date and so you know there's always a debate here on how far back you should go in the the the past of course you need enough trades to judge your strategy your back test properly but sometimes some people say that going too far in the past is maybe not such a good thing because you're going to markets that are not as relevant as what is happening today day so you could question how was the volatility you know far in the past is it relevant to to the strategy now Etc so I don't know this is really it depends on taste it's up to you by the way I'd be curious to know how what you think about this what is your opinion and how you handle these your your your backst history Etc your choices so let me know in the comments down below anyways for now what I thought was that going at the beginning so beginning of 2021 beginning of the 2021 ball run could be a good mid Middle Ground so we'll be using that now okay moving on now we we we are setting the real the back test the strategy the strategy parameters so you can see we have our average type you see for BTC here we'll be going for SMA average period will'll go for a period of of six then using envelopes I these are the exact same parameters I think that we saw in when we were discussing the strategy on Trading you just by the way note if you remove one the the the code adapts it'll understand that you're just wanting to use two envelopes if you start adding more and they'll understand that here you're going for four envelopes Etc so no problem there very easy stop loss still going for this um stop loss of 40% with respect to the average opening price remember that and not going for the price jump percentage so we're not considering this closer rule for this back test now in terms a few things I want to say about testing maybe the first one I want to mention is there is a mode to just select the Longs or just select the shorts if you want to test you know just one or the other separately so that's the way you would do it if you just don't put anything it'll be using both that's the default value now here position size so this is really for back for back testing purposes so here if you go for position size percentage and with 100% this is really how we've seen on trading View and how the trading bot will work the live trading bot will work is basically saying that for every trade that they wants to enter they can access 100% of the amount of money you've attributed to that coin so if it's 100% then be divided by the number of envelopes so three envelopes 33% at the first hit 33% if there's another hit and the last 33% the last hit okay so that's what will be doing but I just want to mention for testing purposes and optimizations often you you don't want to bias by putting more importance in your latest trade with respect to your B the the trades at the beginning of the practice period the reason if you're going the why I'm saying that is if you go for this percentage here well if your trade your your your strategy has been successful has made some profits the size of your trades at the end of the back test will be much bigger bigger than the ones at the beginning so if you want don't want to have this and really have everything judged on on equal grounds you just select a fixed size amount that you use for each trade entries again this is the total trade entry so it'll be divided by the number of envelopes so here it means that the fixed amount on a trade would be 1,000 usdt from the beginning of the backst Until the End let's go back to this so we're sticking to this 100% here and I think have I run this I already forgot I'm talking too much but let's carry on so once we've defined that dictionary our symbol our data you can see what we're doing is that we're instantiating a strategy object where here remember Strat is envelope so we're doing envelope. strategy and we are setting this strategy parameters and the O lcv data that we've loaded then once this is done we can actually run the run back this me method in the strategy so you see here we're giving an initial balance a leverage that we've set to one and here you can see there's two different fees so the open fee rate and the close fee rate is different this is to mimic how the trade live trading bot Works has been designed to work for the entries I've I thought it would be a good idea to do trigger limit orders and therefore um save a bit of money by using being doing like this will be using will be on on the maker fees so I think with bitg I think with level VIP level zero is 0.02 so that's that for the open fee rate now for the exits now for the exits so here there in terms of exits I wanted to be sure that the exits when they when once they're triggered so whether it's the price touching the average or a stop loss that the the order is the position is exited immediately all of it Etc so for that the the trading bot places trigger Market orders and because of because that's Market orders we're paying the taker fee so this 0.06 in this case Okay so I've run this already so basically you haven't seen it happening there's nothing that was printed but this the back test was run so it actually took 1.1 seconds so it was super fast the back test was run now we want to see start seeing some result so we're running the next cell you can see that what I'm doing is that I'm running on our strategy that has whether we did the back test we're running this prce analysis class and with that done we can the first thing we should look into I think is some the all the important metrics so we're doing results. print metrics just by the way if you want to save like this in a txt file you can just instead of doing that you just run it like this and give in here a path so just path the path to the folder when you where you want to save everything so very simple okay so we're doing that I've run it we can and I think we can look into what we're seeing here so you can see there's quite a lot quite a lot of important information I'm battling a bit with okay there we go so first thing first recalling the period on which the back test is done our initial balance and our final balance you can see here we got a performance with a leverage of one of 130% the hodling performance is slightly less so hling remember or by the way performance if you hear what I'm saying is return on investment or Roi okay so hling performance a bit less hling means holding so holding on the asset so buying with your initial balance all of the asset at the the beginning of the period and just never trading with it so that's the hling so we can see that we average of one we do a tiny bit better than hodling okay terms of Trades we're around 5960 this is maybe a bit short in the number of Trades i' like to see in the back test but anyways let's carry on with that time in position almost 1% that makes a lot of sense remember this is not a trending strategy we don't stay long at all and we don't want to stay long in positions at all what we're training is Corrections anomalies so what we really like with this strategy is like a pump not a pump a a sudden volatility spike a wick or something like this we enter the trade there's a sharp correction it touches again the price touches quickly the average we exit we make profits that's very good so this doesn't take long it takes we I think we've seen several example it takes a few candles anyways let me keep Focus now we're judging a health section so we can see win rate win rate of 86% this is a huge win rate is very good but this is a mean reversion strategy we want a very high win rate that's how this strategy is going to make profits so 86 very good okay now a bit of technicalities you can see here that I'm showing two maximum draw Downs is basically the portfolio balance with respect to which it's computed is not at the same time so let me explain and hopefully I'll be as clear as possible this is the so the maximum draw down is always computed whatever here with respect to the latest alltime High that's the definition of the maximum draw down but here it is computed with respect to the balance at every time a trade is closed so that's a bit like you could say a bit more of a physical maximum draw down while the other one takes into account the unrealized pnl because this is the maximum draw down computed at every time we compute the value of of the total portfolio how much it's worth and the thing is what we did let me open again I did I open this envelope. Pi so that's the strategy we'll look into this briefly a bit later but what I want to show you right here is that this comes from the python for final free course so rather to speed up the code to rather than taking a snapshot of a portfolio at every time frame so like here we're doing every hour we we could it could make sense to just do it once a day to speed up the code to also not have variables with so much information into it if you're like optimizing maybe you're running a a sort of um a random search on top of this code so this will be executing this code like a th000 10,000 100,000 times and you don't want that to SP to take a day so this is one way to that will speed the thing up but that just means that also as you see here so this is this is really the the time so it will compute the equity of the portfolio so the equity curve so the the plot that we'll see in a second every 6 hours it updates it every 6 hours so so if you have open a position but not closed it and the position has increased in value or lost in value this will capture it okay so I think it'll be a bit more clear when we look at the draw down plots in a second but what I want to say is that seeing this a a maximum drw down at trade close or here of just this little amount I think I would be comfortable in cranking up the leverage okay now I'm really going to sound like an old uncle but whatever I must maybe I should rename this channel Uncle Louie instead anyways more seriously you know they're saying with great power comes great responsibilities and leverage definitely Falls in into that category so if you ever decide to crank up the leverage on some coins in the live trading bot you really need to know what you're doing and you definitely need to set your stop loss properly to avoid any liquidations now with this I need to discuss also margin modes at least for those of you who are not too used to Futures Trading I won't get overly overly technical but I do want to give you the big picture first let me actually show you directly in the live trading B code where this choice of margin mode can be made I'm jumping a bit ahead we will look into this script into detail when we installing this whole live trading B code on the AWS server and doing the automation but just to make things a bit more practical you see here in the par param dictionary parameters dictionary of the live trading bot that you indeed have the margin mode here which I've put set to isolated as default but you could also go for the other option which is cross and you can also see in the same way that's here you can set the leverage so what will happen so this you'll will will'll see you'll put a strip per coin if you want to do several coin you make the choice of the coin for that given script here so when the server runs this script it will the choices that you've made here for that coin will be directly set automatically set directly here on your future training account on that coin so it will come here and set things here okay so here we have cross and we have isolated as a default so let's talk about cross marging mode first so this is really the riskiest mode possible and it is really for people who know really really really really well what they're doing and with that have a lot of experience with Futures Trading and derivatives in general and management cuz what happens with cross is that liquidation will happen at the level of your total portfolio so you can lose your whole trading money like that so if you're trading with a lot of money it can hurt a lot so what happens here let me say is that if you have like several positions you have put money in several position your the bot or you're trading and you have several positions open at the same time time so your Capital has been spread across several position maybe you have some Capital left as well anyway what happens in Cross is that the margin is shared across the whole portfolio meaning in this case of several positions if you have a position that drops a lot by many percentage by a big percentage but your other positions are in the green they're pumping or you have a lot of capital left on the side that is's not engaged in the position then things would be fine but if it turns out that several of your positions go red and drop a lot and you you go and these put your your your bring your account below the total margin requirement I said liquidation you lost your money okay so now the reason indeed why I've put isolated as the default this is because it is what I really would recommend to anybody who's not really well attuned with risk management and Futures derivatives Trading is because now a liquidation will occur at the level of a trade so if you spread you have several position all of that and one position drops by quite a bit of an amount well you'll lose the money in that trade so you'll lose your initial margin so what you've invested in that trade and you will also pay some some liquidation fees but you know your the rest of the account won't be affected you'll just lose the money on that given trade and also the other because of this because it happens at the level of a trade you can very easily set your stop loss such that you don't you avoid hitting your liquidation let me let's just take an example here so I'm I'm trading in isolated mode I'm hypothetically I'm trading manually and I'm doing trending Trend Trend strategies and I see that there's a trend here and I think it's a great Trend it's going to carry on upwards so I bet on a long I enter along here turns out it was a bad call there is a reversal it goes the other the other way and it turns out that my liquidation my liquidation price was here so as the price hits there it goes down to here at this point my trade gets liquidated I lose the money on that trade but the thing is there is a rule of thumb which liquidation price is approximatively one over the leverage in the case of isolated so if your Leverage is one you would get your position liquidated if it drops by more or 100% and more if you have a leverage of two then you would get liquidated the liquidation price will be when your position drops 1 over two that would be half meaning if your position drops by more than 50% 50% or more you get that trade is liquidated now if it's a leverage or three it'll be 1/3 and therefore if the your position drops by more than 33% or 33% or more I'm really struggling here the then that position is liquidated in other words if you like you're controlling you have your stop loss well you could just say in our example here well I'll just put my stop loss before so that I never actually get to being liquidated on that trade paying that extra liquidation fees all of that I mean you'll be stopped out it will hurt but at least you don't get to the liquid level on that trade one last important point with regards to all of this before we get back to our back test results if you're in isolated mode the market conditions do force you to never go beyond a leverage of three simply because we saw that it because of liquidity events or or news or things like that we do have some big Wicks on some candles and we've seen that more than 20 25% is that can happen and therefore if you did go for a leverage of four or even more at least with four you would have your liquidation level in isolated mode as at 25% and you would therefore put even your stop loss a bit before but you would get stopped out regularly because of this so it doesn't make any sense to go beyond three in isolated mode with this trading strategy okay so let's crank up this leverage by one and see how it affects our results especially whether it blows up our risk or not it doesn't seem so these numbers I think around doubled so I think we could we could try through that leverage of three and and see what happens remember though if we're going for a leverage of three as we just discussed the .4 this 40% wouldn't make sense so I'm going to put 0.3 and now we can run this and see what happens okay we get a a maximum draw down at close TRS minus four that's still very good and and Ade Equity here minus 7% okay so with these let's carry on analysis by the way we're noting that indeed now the performance has really shot up we're more than one 1,000% um profits and we're doing now much better than hodling like by this amount okay anyway let's carry on what we were I think we haven't we were at this point so profit Factor not surprisingly is is very high 35 same for the romad return over Maximum draw down 150 and the let's let let me put that in the middle okay what was I saying sharp ratio very good I think is very good .4 generally above one that starts being a good a good strategy okay and you have the other ratios here if you know them here they are I'm not going to go into details what I want to what I do want to say is that if we're in here there's some metrics some kpis that are that you're used to to but are not included here please let me know I'm really willing to complement and improve this code so yeah don't hesitate let me know okay let's go go to the trades very nice to see that a average net T pnl per trade is of 10% around almost 10% average trades per day not surprising this strategy is not a strategy that trades several times per day as we saw there's some periods where there's quite a lot of Trades that follow each other but also some long here is with no trades or maybe one every now and then so we have a small number here that makes sense this also makes a lot of sense we we saw that this strategy is um really a fast getting get out it's not a stren trending strategy whatever so our average average Trad duration around four candles for 4.5 so 4.5 hours four to five candles makes a lot of sense best trade on that date and nice to see that is a plus 14% worst trade on that date here and that's a minus 10% okay a lot of winning trades not surprising with respect to losing trades given the win rate nice to see that the average net p&l um of winning trades around 11.5% and which is in absolute value much larger than this number in absolute value so it's nice to see that that to have that ratio here um another thing that makes a lot of sense and that really is a signature of this strategy as we see average winning trades duration four candles four hours makes sense we saw that what makes a a good trade a winning trade is generally a sharp anomaly followed by a sharp correction so that takes just a few candles on the other hand losing trades what makes losing trades is when these there was no sharp correction but rather that the price pumped or dumped and that means that it takes a few more L for the price and the average to converge together again and as we see this on average in this strategy is around for this back test B your pardon around seven seven candles okay Max win streak Max lose streak match more for the winning makes sense although I'm doubting a bit the relevance of these numbers in general because we don't have so many trades to judge on um another important thing that to to see here is just to show you all the open and close reasons so this is basically telling you that the open long one was hit only 33 times then how many times did it managed to go up to long two another four times without going to Long three but how many times did it overall manage the price went and hit all three to the end only six times makes sense that the the closest closest envelopes were hit much more than all the other ones okay same for exit reasons so we close reasons we only have exits had a stop loss been triggered we would see the number uh in here had we considered the Clos all condition and it would and it were hit we would also see the number of times here also okay and and finishing we do see quite a lot of money spent on trading fees here to 266 usdt okay more important information to analyze a trading strategy if you need this tra info in strategy is a is a pandis data frame with all the information hopefully that you would need per on each trade so open time close time the reasons the price open close margin initial margin net pnl and a lot more information just to to mention if you want to save that because you you really want to dig into that check trades and because you don't understand some or whatever just to check things and you want to save this as a CSV file if you use you simply use this method that I've I've coded save trades info and you give a path in there and it'll save that as a CSV file in that in that folder there okay same at the same level same thing for the equity record so that's what I was mentioning before so this snapshot of how much your portfolio is worth at each time you do this update here so in here you see so you see it here and you see the strategy oh what I'm sorry but I meant to save same thing there's a method to save that if you if you want that okay so next thing oh yes I wanted to mention in here I'm not just using the storing the price is all beg your pardon the equity I'm also storing the price because I want to be able to do this nice plot here so as price so the price of the asset what is put here is the close value okay so from this now we move to some nice plots you can see that there's a method plot Equity a method called plot draw down for that plot here and um just to mention if you actually do that and you give a path it will save that that that um PL at the path that you've given it okay so what do we see in this Equity curve plot well that to me this is very appealing it's a very healthy slowly cranking Equity curve you can see that market is going up and down some perers with less volatility some with more volatility more volatility whatever and this but the strategy is slowly Pro regularly taking profit on top of on on that and you have this very nice cranking up Equity curve which to me is very appealing now the draw down plot so this is quite peculiar and is quite peculiar to this to this type of strategy you see some spikes here so why do we have some spikes well remember that this so This Equity draw down is really the draw down is is is the draw down that we that corresponds to this one here this maximum draw down at Equity update so what happens is that you know you upd you're updating every six hours but maybe every one hours generally if it's the more granular the more spikes you'll see and even and way in more depth but the reason is that this is because of the unrealized p&l let me show you the method that does this Updates this Equity record so you understand to compute the unrealized pnl what you say is that if you have some position open you mimic the fact that you sell them to know how much your portfolio is virtually worth at the time that you want so at every time te so that's what you call unrealized pnl so you can see in this update Equity record record there is a computation of the unrealized p&l so what I want to mention with this strategy this unrealized pnl can be often in red but that doesn't mean you're going to lose the money simply let's take a um the example of a short because I'm always putting my hands up rather than down anyways so you enter we see you enter on a wick you enter on a yeah on a wick on a you hit the three bands for example and we saw that the correction as much I would love them to be as fast as possible Sometimes some candles close um further up from that before correcting and sometimes never and that's really a losing Trad but what I want to say is that across these several candles where before the correction happens you the candles close above so if you've entered the short that's actually going against you in terms of Trades so that will Pro give you a negative unreal pnl and typically you see when you have a big spike like this it's quite possible that actually this one there's a few candles that closed against you but then there was the correction and you and that ended up not losing money or maybe a bit or whatever and that's why you have a spike that comes back to zero that's maybe even a trade that had this effect but close at break even or even maybe make profits if whatever on the other hand you do have some rectangles here or things like that that is typically well it did that was a losing trade it closed and it closed with giving you a draw down and that's that okay so keep that in mind um that's a bit a peculiarity of that strategy and next plot that we should look into that this method plot monthly performance with year given as all again you can give a path to save all those plots this is giving the performance across a year but of each month in that year and you can see um BDC is great this this backness looks great there's a lot of months in green it's not always the case especially with assets with um coins with more volatility Etc we'll see a few more later quickly but you can see so 2021 actually across this is the cumulative performance across 2021 that was a very good year in that back this almost 400% with some months in really in in in in red in green B you see some months with zeros here well that's basically months where most likely there was just simply no trades okay can see a month and R in March here okay and we finished the the year the Year here okay so I think this is quite important if you want to have a detail analysis but let's leave it to that for now last plot here that I suggest this plot Candlestick that I've created that I've coded so this uses just to have a plot just like in trading View and I think the trading view is actually based on this or the other way around whatever so you get to see your your your your your positions here nicely okay that was a very thorough backest analysis it was important for me to show you all these details so you can see what the code gives you but also how one can analyze these results now I want to quickly show you not in details like this but quickly of a few other coins we saw the BTC big market cap not so many trades maybe look into a a couple more just more volatile less high on the market cap coins so you get a feeling for those as well let's look into cardano so Ada so we have it here I'll just uncomment this see I've picked here DCM five average period added an envelope you see the parameter here parameters here so let's do a runner and see what that gives us and we have an error what is that error your long way was liquidated on that date okay done that on purpose to show you what happened is that the stop- loss percentage the default was 40% and I didn't change that and we were still using the leverage of three because we were checking into Bitcoin so what would make sense to avoid liquidation as we saw 30 that would be at leverage 3 33% so I'm putting 0.3 so now again I'm doing this but this is really to show you what to not do because now we are avoiding liquidation but what is going to happen is that um oh this is what I want to click we are we have hit a stop loss and with a such a leverage a stop loss like this is going to hurt a lot I'd rather warn you we're going to have a horrible draw down curve and the equity curve here you see minus around even more minus 80% or whatever so of course that's you never want to do do that and I wanted to show you this on the other hand it does show that it took the whole whole period to for that strategy to the strategy to recover from this but it did recover it does show you that the strategy does recover quite well from drops in general I mean this is a huge drop so I took years to do but okay so Takeo message it's much if you're in isolated mode at least it's much better to go easy on The Leverage so that you can afford a looser stop loss because with coins like that trade that those more volatile coins Etc as we see as we saw but I mean it could also happen BTC we never know what the future brings but you do have some WIS that go a lot so so there you go so I'm putting back a four here and I think we'll put back a two here and see if this brings things down to a reasonable um in the backest a reason able Max trade grow Max draw down here and we can see minus 8 and minus 10 I think that's quite cool so just to quickly say performance we are really starting to see big numbers so you see in terms of trade we have much more here 200 so much here bigger performance more than 2, 200% profits High win rate that's really one we want to see I think I don't want to go through all of them but just maybe point out a few things this I wanted to show you this this is more the signature of this kind of mean reversion strategies in general the losing trades hurt much more than the winning ones you see that in terms absolute value so you see plus almost 8% for the best trade in this case but the worst trade was minus 20% so that's why I was insisting on the fact that one thing that is very important is to have a high win rate because every time you'll lose it will hurt your your your your portfolio so you want to win a lot to overcome this and same kind of thing I think Bitcoin was a bit of a um Outsider in certain sense out outlier that's may be the the the the name the the anyways so what I'm trying to say is that this is another characteristic that you see more in mean reversion strategies or at least this type of volatility strategy is that the average winning trade is and the losing ones in absolute values tend to be more more similar and in Trend strategies on the other hand you do not want to see that generally these have a smaller win rate sometimes it goes down to 40% and that's okay but what you want to see is that the average winning p&l is much much much much higher the number than the losing one in absolute value okay great so I think I think that will be cool you see we have more trades so indeed we have more periods you more draw Downs here we have still those spikes I was mentioning and More close trades draw down those steps okay still a very nice um Equity growing Equity curve um I think we could quickly see we there's quite a lot of green again but some months in red I think in general you know one should be prepared with trading and trading mods and all of this to have some months in red otherwise there's no point I mean you know these will happen no matter how hard you you work on on your strategy anyways so I think that's that maybe we can have a look at a ax which is even more volatile so you see here I've added an envelope to kind of mitigate for this and they're quite close aax here SMA 5 for envelopes but I've spread them even more and I think okay we'll keep leverage of two and let's see how how this goes um let me do that we're seeing a huge number okay but you can see that the maximum draw down are getting quite high and especially this Equity because of this um unrealized p&l thing so okay that's that but huge number huge performance but still risk a bit more still getting quite a a good sharp ratio all of this I think let's have a look at the equity curve quite interest you see what I was saying this is really like this um unreal anal p&l we have something quite reasonable but there's one occurrence where this thing that I what what I've discussed before happens anyway nice very nice Equity curve although it's less maybe a bit less smooth we have a huge win here huge win here whatever let's see at the the plots think we have some red okay anyways last things that I want to say with respect to this is that I really think with the the game with this with this strategy is to spread your risk across spread your capital in general what I think would make sense and this is not Financial advice really this is what I I think would make sense with the strategy is really to spread the capital across several coins because this these were nice back test I the parameters were doing well all of this for this for this periods and all of that so there's a lot of green but you will have some months in red um and some for some coins there'll be a month in red here and for another coin it'll be in green whatever so if you're trading your spreading your Capital across multiple coins you will have sort of you will have hedging going on where bad performance on a coin might might be mitigated by better performance on another coin but also you know it is quite possible that a stop loss on a given coin will be hit at some point I mean you can't that's how it is so you might have a dent on that coin on that Port part of your portfolio on that coin Etc but the point is if this is a small part of the capital and and your total capital is across several coins well this drop will be compensated by the the gains on other coins so I think the strategy doesn't really doesn't make sense to go all in on the coin really that would be stupid is several coins small capitals on spread across several coins I think that's the way to go again not Financial advice I think that's how how that's how this strategy what it calls for in my opinion okay I think we've done more than enough back test analysis for today let me just conclude with one important caveat is be very careful with overfitting if you ever get into trying to optimize parameters and all of this just always keep in mind that um just getting the best parameters as the parameters that give you the best results best performance um across a very large historical period is a bad thing um because most likely those parameters will not be able to adapt to the unknown future markets really the best parameters actually are robust parameters that you get from testing various market conditions and finding parameters that do okay across all of these so they won't NE they probably won't be brilliant in any of these but overall they do okay they do good across um different market conditions and therefore the your strategy with these parameters is much more likely to adapt to the own unknown Feature Future than something overly tuned to past data okay time to go very quickly over envelope. piy I'm just going to fly through I I I think I just want to give you the main structure a couple specific points those of you who might want to come and do some modifications Etc which I really encourage you you to do so first things first when the the class is instantiated when you create an instance of that class I should say what is done first notably you see this populate indicators and set trade mode so to make this code as fast as possible we want to do as much computations as possible before we run you see run back test we have this run back test Loop which goes through all the data row by row so you want to do as little as possible in this Loop and as more much as possible before and beforehand what we can do is indeed compute all our indicators so you see in here I'm Computing all the averages I me depending on the choice this data average will be the one of your choice and I'm comput using the TA Library as you can see here import ta can use whatever libraries you want whatever something important here is the shift one so Shifting the computation the time by one by one candle this is very important to avoid any look ahead bias now moving on same second thing here is after the average is computed I'm Computing my bands as you can see for the self um for the band lows sorry I'm doing is the average times 1 minus E where e is will be yeah these values that we have here on the other hand I've done a little modification with respect to what I had presented in my previous video on the pin script strategy version of this instead of doing times 1 plus e I'm doing div divided by 1 minus why am I doing that let me show you I've prepared this on trading view so what was before with this 1 plus e would mean that going from here up to here was plus 7% and going from here to here would have been well displacing by minus 7% what I've done is that I've created with this correction a tiny bias by favoring a tiny bit the Longs and so therefore pushing away a bit the shorts and now it means if you set a 7% it means that going from here to here will be minus 7% from here to here minus 7% why did I do that why didn't want I want to favor a tiny bit more the Longs is simply because top cryptos have shown to be assets that on average have grown across time so I'm I wanted to favor a bit more the Longs making them maybe a bit more probable to be successful so there we go that's this little correction I will update the pin script code according to this modification and the other one that I'll show you later anyways so I think the other thing I wanted to show you set trade mode those are some defaults whatever but you see populate long signals so that's the other thing you can do before running the back test and again this this this philosophy of how the code Works actually is is describe much more properly I think in general terms in the python for finance free course anyways let's carry on just saying populate signal so you have the Longs and the shorts here is populating again a big pandas data frame that will will be scanning through during the back test Loop you see here I'm putting the conditions and basically what will happen with this is that once the condition if the condition to enter a trade is verified we put a true and if it's not it's a false and the same thing if it's time to close I beg your par the close is here while the long is here but so when it's time to close the close row will be a true and Etc so what I was saying I think this run back test in general in general I don't think you would have to touch it if you modify it what is quite important to see is that in in that's the back the loop across all the data and in here by the way you see this update Equity record that I mentioned before that F that function but basically whether to ENT enter a trade or not is all done in evaluate orders so that is this evaluate orders function will be very specific to the strategy and that can does get a bit technical with this with this strategy so I'm not going to go do this in details at all you can let me know if you have questions but basically you see here that you're testing if a a long has been opened is it time to exit it so I'm checking all the condition the price the the the Clos all the stop loss the liquidation and if it's just not simply time to close it normally when it hits our price average so you see here for the Longs for the shorts and after closing possibly that's the closing part and here's the opening part there's one there's two things I I want to and I want to say is that I'm it when when you're back testing it's very hard to know if you have a candle for example that went that hit a band but also hit the average you don't know what happened first so I'm simply not I'm saying that you cannot enter a trade on the same candle if a position was closed to avoid and missing messing up this the live but which since it's going to be placing real orders if a Band hits the top um the top band and then it hits the exit the bot will I mean you will have made that trade no problem but at the level of back testing is you can't know you can't know with the O lcv data what do what does what was what was hit first sorry I'm struggling so I don't want to create any bias with respect to this so I just decided that the rule was that if you've closed a position on that candle you cannot open a new one so that's why we have this this um condition here so okay I'm not going to go into details into this the other thing I just want to mention is the other change I made with respect to the pin script code is for the Clos all condition I was at that time comparing how much the the next candle was closed with respect to the previous one or at least when the co when you're running the bot at the opening of the new candle you're checking where the previous candle closed way above the one even before meaning the price is pumping so I'm closing I'm doing this close all I didn't think this would make a lot of sense depending on the color of the candle so I'm simply doing this computation with respect to the average open price just like the stop- loss I think that makes more sense okay okay okay when is this guy going to finally stop babbling so much and show us how to run this live trading bot well now time to get practical the first thing we need to do is to create a instance on AWS a server instance and then install the live trading Bo code there so let's go we're going for AWS servers because so service provided by Amazon I think you'll find them just by searching a AWS Amazon anyway so we're doing that because they provide this free server instance for one year but you could follow all these steps that we're doing on any other servers really okay not sure what landing page you'll get to so what we'll simply say and is is that we'll search ec2 in the search bar then we can just click on ec2 and that's how we access all the server instance by the way I do remember there is I think a $1 onetime fee you have to pay to create an account on AWS okay so then when once we get here we just click on launch instance then we'll have to give it a name so I'm just going to go test envelope and there we go then we have to select the type so we want a Ubuntu Server so we're going to click here then everything is fine then quite importantly you see here this is the instance type so basically the power that that has this that virtual server has and the more power the more expensive but so this this is the t2 micro is the one that would be free for the first year when you create your account and then I think it's about $10 to $15 per month after that first year so we'll just click on that guy and then next step that's important that's the we have to create this SSH key which is the key that will allow us to connect from our computer to the server instance once it's created so we'll just to create a new key pair here give it a name I'll just go for test and test and test and then we stick to RSA PM very good create that key you can see that it got downloaded here so now it is standard practice to put these SSH keys in the SSH folder which will be in your on windows at least in this Windows C users users Louie and then here you have a SSH and you can just add your key here so paste it here and if you don't have a SSH I think it is should be but if you don't have it you can create it great so this is done we've done the that we've done the creation of the key we've put it where we wanted and basically all of this we can leave it as it is and then do launch instance so this will take a bit of time but at some point there we go we have our instance that has been launched here perfect now we can connect to that instance and install the live trading bot there so it will then run automatically 247 yep no respite for trading Bots we can then go to our instances to find it and we can see here test envelope so I'll simply right click on that then click on connect then in here importantly we go to SSH client and you can see here that we have this this command here that we need to use to connect to the instance so we'll simply copy this and then what we must do is go back to that the folder where we put our SSH key and what we can do is directly in the s in the the path bar the search bar here no the path bar can just type CMD and then press enter what this is what this done is simply it opened a opened a terminal exactly in our SSH folder here so now we can just paste so I'm doing control V and we when that's it and that will'll use our SSH key to connect to this server in so do we want to continue yes of course we do and now there we go so what has happened here is that now we're connected to that server instance on a Amazon server we're no longer the terminal is no longer on the computer as you can see we are in this Ubuntu at whatever this IP address I guess of the server instance so great so now we can start installing the code here so let's go back to that article and now we'll go to this live trading BX GitHub repository our GitHub repository and again you have all the Cod is in here and we have I've just compiled here the steps to follow so the first thing is is to clone the git repository on the server instance in other words download download the the code there so I'm just so I've just copied this here and then we can just come here and do a control control shift V so be careful on Ubuntu and and Linux terminals in generally it's not the standal control V or apple V it'll be control shift V so that's what I did to paste what I just um did so anyways we're pressing enter so basically you can see that we have now downloaded the code on the server instance a command to see what's on at that in that folder you can see that in in our server instance now we have this live trading Bots folder in there so that's great so we're staying there the second thing we need to do is do this command here bash live install so this let me just copy it now I've kind of regrouped in one file here in this sh let me show you all the configuration and the installation of the Python packages everything so you see this this pseudo update is just to update the server this is now to install properly our python packages and in there then what happens is also what is happening here is that we're also installing a virtual environment to run the code just what like we did on the on our computer to run the the back test code and you can see here this once this virtual environment is installed we're going to be installing a series of python packages in this requirements. T day which contains all the package necessary to run the live trading bot code so I'm just going to show you this as well so you know what is being installed exactly so in this requirement. Tak you basic txt beg your pardon just three packages pandas RTA library to to compute the indicators and again the API management and the the of the code is also done using ccxt so that's why we're using ccxt so I think I've already copied this what we can simply do is now go back to the terminal again control shift V paste that that that command and the everything is going to be get installed by itself at some point it does actually take a few minutes to install this at some point you'll probably get this thing saying after this operation this amount of additional whatever is asking you whether it's okay with you installing this those python packages so you just can put I believe yes and that will work and that will carry on doing the installation while the installation finishes let me put on my sales rep hat for on for a second well whatever it's the only one I could find right now anyways if you're new to this channel I'm Louie and at robot Traders our goal is really to democratize algorithmic trading and related topics if you feel like supporting us really the best way is by using our registration links so you'll have all that in the description down below for example with our registration link to create an account on bitet you'll get some welcome gifts but probably more importantly a 10% 10% discounts on your trading fees which can make a big difference especially in the long run so what will happen with this link is that not if you use this link is that not all your trading fees will go to bidget will get a part back in the form of commission so thank you very much if you do do this and now let's get back to business so now with the installation finished let's go and have a look at the script where we can configure the strategy parameters and the coins we would like to trade so we're back into the terminal so we want to go into the live trading B code so I'll do CD that's the command to go into CD live trading Bots I only typed a few letters and then I pressed on tab so that the auto completion did the rest so you see now I am in live trading Bots by the way to go backwards it is CD space dot dot so if I do that I'm back into the the home of the server and just by the way I can go back to my previous commands by using the arrow so Arrow up I went twice back and I got back to this CD live training B so I'm pressing enter we are now in live trading Bots I do LS we see this everything that we saw on the GitHub we want to go into CD code so there we go in there we want to go into strategies this run envelope. sh will be will be using that for the automation a bit later so I said CD strategies there we go and in here we have only strategies for now but I do plan on adding some more so we have envelope CD envelope and in there what do we have finally we have the run.py which is exactly the script that will that will be executed every hour to trade the way we wanted to trade so let's say as an example here will'll be setting up for two coins to be traded simultaneously so what I'm going to do is copy this to leave it fresh as a template and create new scripts per coin that I I want the trading bot to to to be trading with so for that we do a CP space I need to give the source file run.py and now the name of the new file I want to give so let's say that we'll be considering BTC so I'm just going to call it run. BTC so runor BTC dop there we go and actually let's say in this example we'll just be running two coins at the same time and the other one we could say would be Ada so there we go so now if we do LS you can see that I've indeed created the other two um pies so so let's have a look in them and actually configure things so for this we do Nano and then the name of the file let's do BTC first I open open this and what do we have here that is really the script that will be run every hour that executes everything all the rules all of this we'll have a look at it a bit in details later but as you can see first things here are the strategy parameters so exactly what we've been talking about a lot so far is exactly the same like as in the strategy um python back test code but you can see there's one new parameter which is very important this balance fraction so this is the fraction of how much of the total portfolio you want to attribute per coin so each time it enters a trade it just accesses to that small fraction depending on the fraction that you give so we said oh we said that it was going to be BTC so I better put BTC in this symbol here so I'm doing BTC okay great 1 hour isolated balance fraction let's say we would give 60% for BTC so that will be 0.6 I can just put 0.6 great let's I'm not going to change anything for this example I'll just do contrl s to save and then contrl X to get out okay we need to do the same thing for Ada so I do run Nano run a in here first things first I need to give here that I'm going to be trading cardano so a okay and now balance fraction well let's say I'm going to give the rest of what I've given in the portfolio we'll do all this of how the putting money placing the bitg account um setting it up Etc just now but so anyway so I'm putting 0.4 here and actually speaking of this what's important the next step is that we need to allow those scripts this trading Bo to be to be allowed to place the orders on our bitg account and to access the balance and do everything to basically place the orders so for that we need to create an API key and this is what we're going to do now I just want to show you that the API keys we're going to put them in this secret. Json that you have here and you might have several keys in there so I'm just I've configured you see that one is going to be called envelop so I'm just fetching this key name here anyways so I'm just going control s and then control X to exit and now we want to go complement to add the API key to that secret do Json so I'm going back once twice and I think the secret key is not in code is directly here as we can see there is secret. Json so I'm doing Nano Nano secret. Json and there you go you can see that I've have this envelope here so now I need to fetch the API key secret password Etc actually rather than jumping directly into bidg to create those API keys since I've initiated it let's quickly go through the rest of the run.py um file so you know what's how how it works what's being executed might be interesting if if you feel like you want to use this for other projects or something like that might be easier to have a look at it on the GitHub repository rather than in the terminal so we'll do this here first thing I really want to stress is that I'm not sure I was clear enough with this but once the parameters here have been set to whatever one wants on the script there's nothing else that needs to be done the script the rest is automatic and it will do what is said to what is coded to do according to these choices maybe the the one thing you you could change is that if You' changed the name of the the key the API keys in the secret. Json the key name you would come and change this here but that's it okay so let's let me just mentioned that all the placing orders fetching balance all these actions that need to be done on the trading account this is done with C ccxt but what I've done to make my life easier is that I've created a sort of wrapper around ccxt that deals with all these orders let me just give you one quick example so you understand why for example to create an order place an order on on ccxt is the method create order then depending on the parameters that you give it will be a trigger limit order a limit order a market order whatever so what I wanted to do to avoid having to write all of that again and again in the python code I've created some functions that take this into account directly so there you go if you have questions you can let me know so let's go back to the run.py okay so one thing that I need to mention I needed to create a Tracker file per per script so per coin that is being run because you remember the strategy has the rule if a stop- loss was triggered or a closer was triggered then the strategy is not allowed to trade before the price merges back to the the price and the price average touch again so I needed a track of f to track that so that's here and the the path that I gave is going to be in the strategy envelope and it be adjacent file in there next to the run. P okay trigger price Delta that I'm defining here you you let me just show you for when we're doing an entry we're placing an entry is a trigger limit order so as such there is a trigger price and there is a execution price so a price so you see here we in the case of a long set we're doing so the price that we're giving the execution price is indeed the price of the band so band low band low for long so given it'll be a loop across this the the envelopes basically at giving the band low and the trigger price is going to be one plus this trigger price Delta times that execution price here so we for the Longs with is saying that the trigger price will be slightly above the actual band and the band will be the execution price okay let me go back so to here so we're taking it step by step next section here is the authentification so to allow fetching the API keys to allow this script to place the orders and Etc next part here functions to deal with the tracker file here we're doing is the cancelling of the order so you have to keep in mind that the script is run at every candle so we want to update our orders so we need to cancel the ones before and put new ones with the new values of the indicators because the price average changes at every candle for example so we're canceling the orders here and not surprisingly the next step is to compute the values of our indicators and that piece of code is really looks exactly like what we did in the python back disk code Next Step here checking whether a stop loss was triggered good Next Step here this is a funny one here but it's probably very unlikely to happen but if it does we have to take into account this this possibility you might have a candle that hits a upper band and a bottom band at on I mean on the same candle right and depending on the Hedge mode what this would do is that you could have technically a long and a short position open on the same C on the same coin with this strategy we don't want this possibility to carry on let's say so if it does happen well this part will cancel and it'll basically cancel the first order the first position that was open so I'll keep the last position that was hit on the same candle okay so there we go checking whether a position is open this is important because if a position is open we need to update the the stop loss to the average opening price given the percentage we need to update the values of the exits um Etc and depending how many bans were hit we're not going to place the same number of orders after that there we go so for example if we have three envelopes and two bands were hit where we well we're only going to after after doing this at the end of the code Place one last entry because there's one last ban that could be hit okay so checking whether a position was open or not here doing the check whether there was a closer that was triggered and finally here this is the checking whether if there's a closer that position that was open and the stop loss was open has the price merged back to price and price average touched and if yes carry on with the script basically but if not the script stops there there we go so um stops there until the next candle is until until the there's enough runs to get to the point where the price has touched the merg the the average okay next section here we're setting the margin mode and the the the the margin mode and The Leverage so this is really relevant only the first time this script is executed and and then it won't have to update anything because things will be according to the to the parameters that have been set at the begin set at the beginning okay so now we get to if a position is open we need to do these updates of price so you can see here so I mean there'll be a section for the for the Longs section for the shorts if there's a long or I mean only update given whether it's a long or a short I mean accordingly not sure that was clear but anyways so you see in the updates what is doing is updating the exit price and as you can see it is a trigger Market order I mentioned that I wanted this strategy for the exit I decided that the I wanted Market orders to be sure that they were executed immediately and fully Etc so that's why it's a market order so exit updating the ex exit but also updating the stop- loss if several position were open we we updating the stop loss should always be the average opening price times the times the percentage that you know that we discussed already okay let me carry on here we're now getting to the last part where it's actually placing orders so to place orders we need to know the balance and we do the balance in this section and you can indeed see here that we have Bal this balance fraction parameter that times then the leverage and finally times the the total Capital that was attributed to the account so there we go now here well so here depending on whether how many envelopes were already hit or not there's a little Loop that will take into account how many are left to put so if no position was open it'll put all the envelopes all the orders according to the envelopes so anyways you can see here the entry so I think this is the case for the Longs so there's a place trigger limit order as we discussed this before but we also every time we place an order we also also placing an order for the exit so you have the exit here we're also placing a stop- loss um so you have the the we're also placing a order for the stop loss so we have it here and that was the Longs you have the same for the shorts and I think we've done everything okay time to create those API Keys actually what we're going to do as well is rather than creating them on the main account we'll create a sub account so that all the the scripts whatever will be trading on that sa account I think it's much safer and cleaner to separate trading activities like this okay so from my main bitg account I'm just going on the top right here and you see rather than going to API Keys directly we're going to sub accounts once we're there we are just going to create a new one so we click on create account here and what we're doing is a virtual sub account so we're not creating a new email address Etc we're just sticking to a sub account of the main account there we go so that's that we need to give it a name so I'm just going to say test envelope okay notes we don't care and we see that we can create an API directly at the same time so let's toggle this we want a system generateed API key and here we have to give a note so this I mean we don't really care so I'm just doing test envelope again now this is the first thing that we'll have to paste in on the on on the server so I'm just going to do I love peanut butter there we go and we have to give the permiss of what we're allowing through that API key so oh I do want to mention so this is the first thing that will be copy pasting and then there'll be the API secret and API key these this this is all this API Keys is all sensitive information that you need to keep absolutely confidential because if someone gets access to this it will be it will give grant them access to the trading activities on your account so you don't want to do that so keep that very confidential obviously I'm doing this live but then I will be deleting that that API key okay so the next step here is per permissions so what are we creating this API key for well we creating it for to trade Futures to allow the live trading bot the scripts to trade Futures so we want to toggle this on and we want to toggle this on and that's it so I'm doing we're doing create we one could bind an IP address I'm not going to do that so create and then you have to go through through some security whatever so let me do that and get back so now we have the test envelope here that appeared and we also have the API here we have a one so I'm just going to click on the one and there we go we have the API key here but we can't see the secret key so for this we have to click on details and we have to fill in the pass phas so I like what I wrote as I I love peanut butter and also do the email check so I'll see you in a second okay so let's copy this API key and actually come in our terminal you remember where we had to put things uh properly password this is corresponds to this I love peanut better actually so let let's just just write that here so API key is what we just copied so I'm doing a contrl V and we have to do the same for the secret so I'm just going to come back here copy the secret and paste it here and do a contrl s contrl x and that's it we've done that I think we're forgetting one last important very important thing for the bot to work is that we do need to put some funds on this sub account so let's do that so we'll go up here on our wallet and click on transfer and in here what we want to do is a main sa account transfer so we'll click on this okay spot of the main account but we want to get to not the spot but the usdm futures of test envelope so I think I'll put 500 usdt this will be more than enough to to avoid any position siiz restrictions and this is done okay so to change accounts oh sorry what I wanted to show you is that you just simply come here and click on this wheel and then you can select the the the tra the other sub account great this no okay so trade we might as well go on Futures and we'll see that this is where the orders will be priced by the bot but what I wanted to show you is that when we come here and it's updated we should see that this is indeed account assets 500 usdt great let me not forget to mention that to Mark the release of this new video bigget is running a special campaign with us so if you use our bigget registration links you can get these awesome bonuses I'll let you pause the video if you want to read about the conditions this is of course on top of those 10% trading fees discounts on trading fees that I mentioned before so anyways once again thank you very much if you do use the our registration links it really supports Us in creating all this free content okay okay okay time to run some scripts first I think we'll do it by hand to see that everything goes smoothly and then we'll set up the Chrome tab for the automation so rather than having to run all the Run do pies of each coin one after the other what I did is to create a bash file that will execute everything so let's go there and configure it so CD code LS and this is indeed that the run envelope. so let's do a nano run envelope. and as you see first line it fetches it's the source so is fet saying that we'll use the python from the the virtual environment that we that we um that we installed and then you can see then we have Python 3 executing the run.py giving the right path Etc so we did in this example we so let me actually do a contrl k then a control U and the reason for that is that we created two we we said in the example we were doing two coins so BTC and here the other one was Ada so that was that's it so crl srl X and now what we want to do is run that bash that bash file to see to see these things finally executing so I'm going and this by the way this bash file is also what the Chron tab is going to run every hour so the Chown Tab and and is exec executes itself from the root of the home folder here so we're going to mimic this so we have to do bash and then live trading Bots and we have to get to this this um to this bash file so code and then the name was run envelope so now if we run this we should see things appearing here which are the prints that we get from the from the from the script and you we start seeing all the orders being placed all of that I think you can see them Happening Here on the side as well so first execution it was BTC but now I finished placing all the orders so now it's doing the Ada so everything is happening okay so if we get to here what do we so we do see on our BTC we do see some of these orders being placed great but what I want to show you is that in open orders we have in trigger orders we have 36 of them does it make sense yes absolutely so in both these cases we considered three envelopes so three for Longs three for shorts so so that's a total of six per coin and for each entry we always set an exit so that's another six and we always set a stop loss for again each entries so that's another six so that's 18 per coin we're doing two coins we have 36 very nice so you can see I mean we won't go through everything but you can see the the type you see Trigger Price Market order so those are exits you indeed see for that's a close short close short but here we have a open short which is indeed so you see here trigger order at market price and and market price here Market order okay so that was the exits but I was saying that on the open open short that's a trigger order we have the trigger price here but we also have an execution price because it's a trigger limit order so that's great actually let's do another fun little check by hand together let's pretend that a position has been opened and we see when we update execute the script again what happens to these orders so okay so first things first let's me mimic this so I'll just open a a market long on BTC great there we go and as you can see we have the position open around 134 usdt okay all good so we're now back to our orders and what we should do is if let's pretend that this position was open as the result of two bands being hit so technically speaking what would have happened is that two of those open Trigger orders would have been executed so let me cancel this first open long here and this other open long here great so now we can come back to here and simply what we'll do is run the script the the bat the bash script again okay so this amount of time that it takes here is actually the amount of time to download the O lcv data to compute the the indicators as you can see first things first indeed we may make that we had three envelopes we may make that two were hit and you can see that once the when it canceled the orders it did count that there is only one Longs remaining to place so great we have a one here okay for this the usdt position size and you can see that because there's only one left it's not going to put any shorts only longs and you can see that there's only um well a limited amount of orders that were placed and for Ada we didn't touch anything so I just deleted the 18 orders and put back new 18 orders so now the question question is we have 23 trigger orders does this make sense well as I said a 18 and we didn't change anything so 18 now we in we we we're only placing one long there's one long left to place so that's a entry exit and and stop loss three 18 + three that's 21 great but there is a position opened so for this position we need to update the exits so the exit and the stop- loss so that's a 2 21 + 2 gets to 23 great okay let me not forget to cancel all these orders so that we when we do the automation everything works great and I'll just do a flash close here and there we go guys final steps of this journey we now configure the Chrome tab so that this bash file is executed every hour of every day without us having to do anything so for this back to the terminal and we indeed at the route we to be there at the root of the folder the home so we'll just type Chrome tab minus E now if it's the first time that you execute this command it will ask you what um editor you want to open the Chrome tab with and if you select will you press one and enter I think it will select Nano so I've already done that so anyway so let's carry on let me just paste the command that we have to write otherwise I'm going to get it wrong and I will explain it to you so first things first this so this is all explain exp in how it works but we'll do it together so basically you can see that this is indeed the command that we were executing as by hand in the terminal so bash blah blah blah run envelope. essay great so it is this command that will be executed with a regular frequency so then this what we're doing here is to say now in this log which we're putting in the path here and calling it envelope. log print in there save in there all the prints that the scripts all these scripts that are being run will print okay so that but we have these little symbols here this is just to say that don't only print in this log only the prints of the scripts but also if any errors uh happen to be printed you also print the errors great now the most important part is setting the frequency here so let's let me just explain you see here the first the first entry you need to give is the minutes so we exec we want this to be executed at every beginning of the hour so at every beginning of every new candle on a 1H hour time frame and therefore it's the zeroth minute of every hour so that's why we're putting a zero then stars mean every so the first stars is every age so every hour then next star is every day of the month so and then next star here every month and last every day of the week and there we go so for this to activate we need to control save and also exit and that's done the contab is configured the way we want it to be configured by the way let me just mention that if you want it to to stop it you can just come here and just do contrl s and then contrl X and now you've paused that command from the CR tab let me put it back there we go contrl srl crl srl X Perfect by the way we didn't see any orders being placed in the background that's normal it's not the beginning of the hour right now but I can't resist not showing it to you happening so what we'll do is quickly change the crown tab such that it executes every minute of the hour so we'll get to see this happening together so back to the terminal CR minus E let's come down to here let's put a star the Stars here contr srl x for it to activate and then let's see at some point things will let's go to trigger orders let's see them happening and in a few seconds they'll arrive or let me get back to you when it does oh there we go so it is happening they're being triggered we will get end up getting our our 80 our 36 orders once the downloaded the D has been downloaded Al also for the next one and there we go great oh yes by the way very importantly don't forget to if you do this ever do this test don't forget to come back to the Chrome tab afterward words and put back the zero here you definitely don't want to run the the script every minute they won't do what what it is made for and it happens I I've done it many time to forget this and I'm also canceling those orders we made it you survived the journey congratulations if you have any questions or comments you let me know in the comments down below or join our community discords but guys you know they're saying in the crypto community don't trust verify so verify check those CES to check that they work properly according to you do your back testing properly do your testing properly um be mindful with how you deal with your money and how you handle risk um and always keep in mind that past performances don't never guarantee future results okay Uncle Louie go away I just want to say generally this is the moment where I just put say that there's a super cool video on the right or on the left or whatever but honestly I think you've seen my face for more than enough for quite a while right now this channel is about trading boss we have loads of video videos about this I would really appreciate a like and a subscription if you haven't done that already and also don't forget the bitg get registration link if you want to create an account and I think that's enough now go get some fresh air I hope to see you soon happy trading and take care