The Wayward Trading Bot... The Wait Is OVER!! (Full Code)

Kurze Zusammenfassung

In diesem Video lernst du, wie man einen Mean Reversion Scalping Trading-Bot programmieren kann. Der Bot wartet darauf, dass der Preis von einem Durchschnitt abweicht, bevor er eine Wette auf eine Rückkehr platziert. Der Autor führt eine Backtest-Analyse durch und testet die Strategie live, um die Funktionsweise zu demonstrieren.

  • Erstellung eines Mean Reversion Scalping Bots
  • Verwendung von Bollinger Bands und RSI zur Identifikation von Handelsmöglichkeiten

Einführung

Der Autor erklärt, dass jeder mit einem Computer und Internetverbindung in der Lage ist, einen Trading-Bot zu erstellen, selbst ohne Programmierkenntnisse. Der Bot basiert auf der Mean Reversion-Strategie, die darauf abzielt, von Preisschwankungen um den Durchschnitt zu profitieren.

Strategie Backtest

Im Backtest zeigt der Autor die Ergebnisse des Bots auf dem USD/JPY-Währungspaar an. Er erwähnt, dass die Ergebnisse mit einem anfänglichen Kapital von 1.000 Dollar bis fast 2 Millionen Dollar ansteigen können, jedoch betont er, dass dies in der realen Welt nicht erwartet werden sollte. Der Backtest gibt jedoch Einblicke in die Performance wie Drawdowns und Gewinnverhältnisse.

Die Strategie im Trading Bot

Der Autor beschreibt das zugrunde liegende Konzept der Strategie. Er verwendet Bollinger Bands zur Messung von Preisschwankungen und fügt einen RSI-Indikator hinzu, um Momentum zu bewerten. Die wichtigsten Eingaben sind der Abstand zur Mitte der Bollinger Bands und die RSI-Grenzen.

Start des Codierens

Der Autor beginnt mit dem Codieren des Bots in der MetaTrader-Entwicklungsumgebung. Er erstellt einen neuen Ordner und fügt eine Vorlage für den Bot hinzu, die er dann anpasst, indem er die Grundfunktionen entfernt und die Struktur für das Trading-Auftragsmanagement einrichtet.

1. Visualisierung der Einstellungen

In diesem Abschnitt erstellt der Autor eine Benutzeroberfläche, in der Benutzer ihre Eingaben für Handelsparameter wie Zeitrahmen, Magic Number und Farben für die Benutzeroberfläche festlegen können. Diese Benutzeranpassungen erleichtern das Arbeiten mit dem Bot.

2. Visualisierung der Einstellungen

Der Autor zeigt, wie man die Indikatoren für Bollinger Bands und RSI visualisiert und ermöglicht es dem Benutzer, die Parameter für diese Indikatoren festzulegen, was zur Flexibilität der Handelsstrategie beiträgt.

Geldmanagement-Einstellungen

Hier wird das Geldmanagement des Bots behandelt. Der Autor erklärt verschiedene Methoden zur Festlegung der Handelsgröße, wie feste Lots oder Prozentsätze des Kontos, und bietet dem Benutzer die Möglichkeit, ihre Risiko-Toleranz zu definieren.

Ausführung des Trading Bots (Visualmodus)

Der Autor demonstriert die Funktionsweise des Bots im Visualmodus. Er erklärt, wie der Bot aktiv Handelsaufträge in den Markt eingibt und optimiert, während er die Preisbewegung verfolgt.

Was wir im 2. Teil bauen werden (Finaler Teil)

Abschließend beschreibt der Autor, welche Verbesserungen und zusätzlichen Funktionen im nächsten Teil des Tutorials implementiert werden. Er spricht über die Einführung von Konfluenz-Analysen und die Gestaltung des Bots, um die Benutzererfahrung zu verbessern.

Fasse jedes YouTube-Video in Sekunden zusammen

Hol dir Zusammenfassungen wie diese für jedes Video, in deiner Sprache, mit der kostenlosen Summ-App.

Laden im App Store
Jetzt bei Google Play

Transkript

Vollständiges Transkript von „The Wayward Trading Bot... The Wait Is OVER!! (Full Code)“. Klicke auf einen Zeitstempel, um das Video an dieser Stelle zu öffnen. Du brauchst ein anderes Video? Nutze den YouTube-Transkript-Generator.

0:00 If you have a computer, an internet connection, and a couple of hours, then by the end of this video you will have built this trading bot line by line all by yourself, even if you have never coded before. It's a mean reversion scalping bot. It waits for the price to stretch far away from an average and then bets on it to snap back. We'll honestly talk about where it works and where it is struggles at the end, but let me show you a very quick test and then we'll build the whole thing a step by step and we'll test everything as we go along. So, here we are in the strategy tester. I'm going to run it on USD/JPY starting from the beginning of this year until today. I'm going to run it on every tick. I know, real ticks, every ticks, Obama ticks, Trump ticks. I mean, all of these are just data provided by your broker. I have flash news. None of them is accurate. I have

0:45 made another video where I compared every tick versus real tick versus the live results. You can go check it out. I'm going to run it on every tick because I just want to see how the strategy is doing. Let's do it on 1,000 deposit and let's run. Now, one of the things you will see is that there are no running drawdowns and that is because of a tight stop loss that we put in place. And the second thing is that you're going to see a lot of periods quite long which are completely flat. Now, it's a back test at the end of the day, so take it with a grain of salt. Take it with a full kilogram of salt. Well, on to the back test results, we started with a balance of 1,000 and we're ending up somewhere close to 2 million. Now, this is not going to happen in the real world, but it does give me the confidence, especially looking at the drawdown numbers, looking at the win percentages, and looking at the risk to reward ratio of almost two to one that

1:31 this is something that I would like to apply in a demo account for a longer period of time to see how it works in the real market. And that's what the back test are for. They're good for visual test because you can see that the codes that you have written, they are actually working properly in a visual environment. And they're good at giving you a bit of an indication of how and what to expect when you apply them in the real world. Now, the real world will have slippages, will have execution delays, will have tons of other things including broker manipulations, which is going to cause the results to change. But, are you going to become a millionaire starting from a thousand dollars in six months? No. But, is this EA worth trying? At least in my books it is. So, if you're still interested, get your

2:17 laptop, make a cup of coffee, and let's start with the strategy itself. The idea is very simple. When the price is stretches too far away from an average, it tends to come back. And we're going to measure too far with Bollinger Bands, which tend to widen when the price is volatile and tend to shrink when the price is stable. Now, you can use other oscillators as well, but we're going to build a strategy on Bollinger Bands. And when the price is going to poke outside those bands, that's when we're going to call it is a stretch. But, a stretch market can remain stretch for a very long time. And to buy it just because the price looks low is like catching a falling knife. And that is why we're going to add a second check, RSI for exhaust momentum. And even then, we don't buy immediately. If we are expecting the price to bounce back up, we're going to put a stop order above the current price. So, we only catch the

3:02 trade on a bounce. If the price continues to keep dropping, we don't catch that falling knife. We only enter once the reversal has started. And we target the middle band, which is the average. But, we're also going to have an aggressive trailing stop, so we move our stop loss into profit territory as soon as we can. Our stop loss is going to be very tight, and this is why even if we catch three or four positive trades, that will be more than enough to compensate for the times when we actually have a stop loss hit. So, that's the entire idea. Now, if you're still interested, get your laptop, make a cup of coffee, and with no more shenanigans, let's start building this thing. So, let's go back to MetaTrader, and we're going to click on the development environment, and here we are in MetaEditor. So, first thing's first, I'm going to create a new folder, and let's call it the Wayward EA.

3:51 Now, within this folder, while selecting it, I'm going to click new. And let's give it the name Wave Rider EA with panel. Next, next, next. And here we are in the opening template. I'm going to clean it up. So, we're left with initialization function and all the codes written here are going to be run on the initialization of the EA. Then we have the deinitialization, which is the reverse. So, all the codes here are going to be run when you stop the EA. And on tick function and all here are going to be run on every tick. Meaning every time a new price data arrives into MetaTrader. Okay, so let's start at the top. And the first thing we're going to do is we're going to include a trade.mqh file, which if you look here in the include folder, in the trade folder, you

4:38 have this file trade.mqh, which comes with all these pre-written codes that MetaEditor has already written so that we don't have to write them. And these can be used to do all of the trading operations like buying, selling, getting position information, modifying TPs and stop losses, getting information on orders. So, for all the trade operations, we're going to use the class CTrade. And I'm going to assign it to a variable by the name of trade. Then CPositionInfo class, which can be used to get information on the current open positions in the market. So, I'm assigning it to a variable by the name PositionInfo. And all the order information class, I'm assigning it to OrderInfo. Then in order to create a drop-down menu for the user to select the start hour and the end hour, I'm going to create an enum. And

5:25 the members within that is going to be inactive equals zero, one equals to 100 hours, 200 hours, 300 hours, all the way to 2300 hours. And then we create an input group, which are going to be the magic number for the EA, what's the time frame, a higher time frame because we're going to need higher time frame for confluence, a start hour input, end hour input, and the gradient color because we're going to put a gradient on chart, the blue color that you saw in the beginning. So, these are the values that the user can define, and this is why these are input variables. Now, if I compile, it compiles properly, and one thing you notice here the enum hour is this enum that we have created up here. So, this is going to become a drop down because we're assigning this variable type to

6:11 these two variables so that these two variables are going to look up their information from this variable type. Now, if I go back to MetaTrader, and here after compilation is our EA. So, if I pull it down here and we go to the inputs, now you're going to see that we have the magic number, we have the time frame that the user can select, we have the higher time frame, which the user can select. And now our end hour and beginning hour is based on the enum that we have created here. And same goes for the end hour because we're assigning the same enum to the end hour as well. The color of the gradient now the user can select because it is variable type color, which comes predefined with MQL. And then as we talked about the strategy is going to be built around Bollinger Bands and RSI, so

6:57 we need certain indicator parameters from the user as well. So, once again, input variables so the user can provide these values, which are the Bollinger Bands, Bollinger Band Deviation, RSI period, RSI filter, and filter basically means from the middle point 50 on RSI how much above and how much below. So, 30 means 80 and 20. So, 50 + 30 and 50 - 30. And then what's the applied price for RSI and Bollinger? If I compile and go back, now we have the indicators parameters here as well, which the user can provide. Then let's create a section for our global variables, and these are the variables which are going to be available throughout the EA. And here I'm creating a handle for Bollinger Band, a handle

7:43 for RSI, and a handle for ATR. I'm already creating the ATR. We're going to create the indicator parameters for ATR separately. Then in order to copy the values from these handles into variables, we're going to need an indicator buffer, an array variable, which is what these two brackets are, which means that the same variable indicator buffer can store more than one value at a time. It's going to do indexing, 0 1 2 3 4, and you can ask for whatever value by providing the index number. Then in order to assign these values, we're going to create a Bollinger lower, a Bollinger main line, a Bollinger upper, an RSI value, and an ATR value. Then we're going to need some helper functions, and the first one is is it a new bar? And the way we're going to do it is we're going to set a previous time into a static date time variable as zero. Then we're going to

8:30 get the current time as iTime, which is what is the time on the current candle on our time frame. And then if the previous time is not equal to current time, that means a new candle has formed, in which case we're going to return true. But before returning true, we're going to say that the previous time is equals to current time, so that the next time on the same candle, if the tick arrives here, the previous time that we have updated is going to be equal to current time, unless there is a new bar. And then in that case, we're going to return false. And another helper function that I'm going to create is is it a back test or visual, which is we're going to have a lot of stuff on the chart like a beautiful gradient, a panel, some lines and indicators. But we don't want to see them when we're not running a visual test. This is where

9:16 we're going to use return, which is if it is MQL tester and it's not visual mode, so it is a back test run without the visual mode, or if it is an optimization run. In those cases, return true. And if it returns true, then we know that we're not supposed to put all the chart objects and gradients and panels, so that it runs faster. And now we go back to our initializations. As soon as the EA starts, set the magic number, right trade, and hit dot. It's going to give you all of the possibilities that you can use. And we're using the set expert magic number. And we're setting the magic number of the EA to our input magic number. And then I don't like to see grid on my charts. So I am saying on the current chart, which is zero, chart show grid

10:02 equals false. Don't show the grid. And then we're going to initialize the three handles that we have created up here. So first the Bollinger by calling the iBands, providing it the current symbol, the time frame that the user has selected, Bollinger period, standard deviation, and the applied price. All of these variables come from here. And then RSI by calling the iRSI, providing it the parameters that RSI needs. And then also the ATR, which is underscore symbol, time frame, and we're going for a thousand ATR to a smooth in the ATR. We don't want the ATR to fluctuate too much. So I'm using a large enough number. You can use even 10,000, but 1,000 is probably enough. And then we come back here. And now we're going to create the trade management section,

10:48 which is the ATR multiplier, which is when we're going to be placing a trade. We want the candle on which we are placing the trade to be large enough. We don't want the small candles where we're placing the orders. So there's the ATR multiplier. So minimum candle size in ATR thousand terms. Then the stop loss based on ATR. So initially stop loss times the ATR. So if you say one, then the stop loss is going to be one ATR. If you say two, the stop loss is going to be two ATR. If you going to say three, then ATR is going to be three ATRs away from wherever the order is. And then the trailing of the ATR. Like we said, when our trade is triggered, and if it's in profit by a certain margin, then we want to start trailing by a distance which we are again linking to ATR so that it is stands across different time frames and different currency pairs. So we're not

11:34 providing a hard coded number. We're providing a trailing based on ATR. So 0.2 means 20% of the ATR. Then order distance. So when we are going to place the buy order, like we said in our strategy, once the price goes outside of the Bollinger band, we don't want to immediately buy. We want to place a buy stop above so that price moves back into us. So this is from the current price, how much distance do we want? That again is based on ATR because across different currency pairs, you're going to have different candle sizes, different fluctuations, volatilities. So linking it to ATR smooths all of that out. And then the max of spread, you can link that to ATR as well, but I'm happy

12:20 with max of spread being 10 points. So not above one pip. Now while we are on max of spread, let's also include a slippage and I'm going to set the maximum slippage to 10 as well. And let's set the slippage by using the trade.set deviation in points, which is the slippage, and providing it our input slippage variable, which the user can define up here. Now we have our variables. If I compile now and go back here, now we can see that in our input settings tab, we have the trade management criteria as well that the user can define. And because now we have all the variables that we need so far, we can start working on the on tick function. And I'm going to start by saying that the the trade signal is

13:07 zero, meaning there is no trade signal in the beginning. I'm going to get the value of the ask and the bid by using symbol info double method, providing the symbol and asking for the ask and bid, and it stored it into these two variables that I'm creating locally. These are the global variables because they are defined at the global level, so they're are to every function whether on init, whether on deinit, whether on tick or any other function that we're going to create. But, these we are creating locally, so they're only going to be created when the on tick is run, and then at the end they're going to be destroyed. Then, we're going to use the copy buffer method to copy the value from the Bollinger Band handle that we have initialized here and paste the value into indicator buffer variable that we have created here. And what we

13:54 are storing in this is the buffer number, which is zero, which is the main line. Then, the starting position, zero means current candle, and how many values do we want? Starting from the current candle, how many values? So, only one, just the current candle. Store that value into indicator buffer, and then we can assign the value from indicator buffer index zero, so the very first index that we have just stored the value in, into a variable Bollinger main, which we created at the global variable level. Then, same for the Bollinger upper, where we're getting the value of the indicator buffer number one instead of zero, so this is the main line. This is the upper, and this is the lower. And then, copying that into indicator buffer, and then from indicator buffer assign it to the

14:40 variable Bollinger upper. Then, in the exactly the same fashion, we get the value for the lower Bollinger Band as well, which is the value number two. Then, we use the copy buffer method on RSI handle, put the value into indicator buffer, only one value starting from the current candle for the main line, and assign it to our RSI variable. And then, also the ATR values, so from ATR handle copy the value into indicator buffer for the main ATR line is starting at the current candle, only get one line, put it into indicator buffer, so it's going to be at index zero, so we can assign it to the ATR. So, now we've gotten all of our indicator values that we're going to need. Then, after that we're going to create three more variables, which is the candle high, the candle low, and the candle size.

15:27 Candle high through the IHigh function for the time frame that the user has specified, and getting the value for the current candle. And then, the same way ILow, so get the lowest value for the current candle, for the current symbol, on the time frame that the user has specified. And then, obviously, the candle size is going to be candle high minus candle low. So, now we have the information on the candles as well. And here comes our trading criteria, which is if the candle size is bigger than the ATR value times ATR multiplier, which, going back to what we have defined here, ATR multiplier, which is the minimum candle size. That's what we are checking here, that the ATR value times the ATR multiplier, that width. If the candle is bigger than that, then check if the bid is a smaller

16:16 than the Bollinger lower. Meaning, the price is outside of the Bollinger band on the lower side. And the RSI is less than 50 minus the RSI filter, which we had defined as 30, so my 50 minus 30 equals 20. So, the bid is below the Bollinger band lower, and the RSI is below 20. So, both of our conditions are met, we're going to set the trade signal, which we have created here, is started as zero, as minus one. And minus one will mean buy signal. And if the ask has gone above the Bollinger upper, it's outside the upper Bollinger band, and the RSI is greater than 50 plus 30, meaning it's gone above 80 as well, so we're in

17:01 extreme on RSI, outside of the Bollinger band, so the trading signal becomes a one. So, it's a sell signal. Okay, so now let's do a quick check. I'm going to comment, and the comment is going to be signal, trade signal, which is is to come from here, and the RSI value we're going to get from RSI and then bid double to to string, again converting it to text, the bid value. And if I compile it now, I have zero warning, zero errors. And if I run it, then the first thing I'm seeing is that my Bollinger Bands, my RSI, and my ATR values are properly being pasted on the chart. And here is our signal. So, whenever that signal was generated, this was printed. If I run it, the RSI

17:46 values are changing, the bid value is changing, and the signal is also getting printed. So, we have a visual confirmation that our code so far are okay, and I'm going to delete this comment, and we can start looking at actually building an order. So, in order to build an order, we need money management section as well. So, I'm going to come back up to the top, and here I'm going to create one more enum, where there are going to be four different possibilities, either to use fixed lots as zero percentage of balance, and that will equal to value one, percentage of equity equals to value two, and percentage of free margin. So, once we have created this enum lot type, we come back down, and now we can create a money management section as well, which is the first thing is going to be using that variable

18:32 type. We're going to assign it to a variable lot type. All of these are input variables, so user can provide the value. And as a default from those four values, I'm going to provide percentage of balance as a default. And if I compile, and we go back to MetaTrader, now we're going to see this money management, and percentage of balance is our default option. But because of that enum, the user has the ability to choose whatever he wants. But if he chooses fixed lots, then in that case he needs to provide what the value of that fixed lots is. And if he chooses any other method, which is percentage of balance, percentage of equity, or percentage of free margin, then in that case he needs to to the risk percentage. And I'm going to call this as lot size defined by risk percentage or fixed lots. Compile again,

19:18 and now this should change to lot size defined by percentage of balance. Good so far? So, we can return to MetaEditor. And I will go down to the bottom where we have the helper functions. And now we're going to start calculating the lot size. Create a function by the name calc lots, and we're going to send to it the stop loss distance because the calculation here is going to be based on what's the distance between when the trade is taken versus the stop loss. How big is the stop loss? And that is going to determine what the lot size should be in order to have 2% risk, 3% risk, 4% risk. Now, we're going to start with a variable lots, and I'm going to assign to it the minimum lot that the broker allows. And that is just to safeguard that we don't have a zero lot size. Then

20:04 let's get these three values because that's what we're going to use as percentage when we are going to be doing the percentage of balance, percentage of equity, percentage of free margin. We're going to need these values. I'm creating these three variables and assigning to them the account balance, the account equity, and account free margin. Then I create a variable by the name risk and start it as zero. And then we're going to switch through the lot type variable. This variable up here, which can have four different values. So, we're going to switch through those four different value. And if it is case zero, which is the fixed lots, then we assign the fixed lots that the user has defined to the lots variable and just return that because we don't need to do anything else. It's fixed lots. But in case of one, which is the percentage of account balance, then the

20:49 risk is equal to account balance times whatever risk the user has defined divided by 100 to convert it into a percentage and break. Break basically means that if you have already found case one to be true, you don't need to go to case two and case three. Just break here. But if it is not case zero and not case two, then go to case two. And then the risk is going to be equals to equity times the risk percentage and break. But if none of these are true, then go next, which is it's going to be the value three. In which case, it's the free margin times the risk percentage and break. Then I'm going to get the value for the tick size from the broker. What's the value of one tick? And then what's the lot steps? So, 0.1 to 0.2 to 0.3 is 0.01 lot step. And then

21:36 we can create a variable, which is money per lot step. So, one lot of step equals this much dollars value by using the formula dividing the stop loss distance by tick size and multiplying it with tick value times the lot step. That's just a general formula. You can use chat GPT to understand it more if you want. And then the lots become the math floor of because you want to round it down by dividing the risk divide by the money lot per step times the lot step. This is how we're going to get the lot size for these three cases. In case zero, we already had the fixed lot and we had exited the function. So, none of this will be run in that case. Once we've got the lot, then just to check that our lot sizes are okay, we're going to get the minimum volume

22:22 from the broker, maximum volume from the broker, and the volume limit from the broker. And we're going to do these three validations that if the volume limit is not equal to zero, so broker has a volume limit, then between that volume limit and lot size, whichever one is smaller, math minimum. Whichever one is a smaller, that becomes the lot size. Then similarly, if there is a max volume at the broker, I don't know, 100 lots, then whatever calculation we have gotten here, if it turns out to be 150 above the maximum volume allowed by the broker, then choose the minimum between the lots that we have calculated and the max volume allowed by the broker. And then for the minimum as well, if our lot size turns out to be

23:08 less than what the broker allows as the minimum volume, then choose the math max, meaning the higher of the two values between the lot size and the minimum volume. Then we normalize it to two decimal places and we return the value of the lots. So that's our calculation of lot size function as a helper function that we're going to need and use. And now we can actually send the order. I'm not going to create it in on tick. I'm going to create a separate function and let's call them trade-related functions. And the first one I'm going to create is a send order function and we're going to send to it the trade signal that we're going to get from here, ask and bid value, which also we got on in the on tick. And the Bollinger mean because that's

23:53 what we're going to use as a TP. So the first thing we're going to do is we're going to create two variables. One is entry equals to zero and a stop loss initialize as zero. Then the stop loss distance is equal to ATR value times the SL ATR that the user has defined up here in terms of ATR 1000, how big the stop loss needs to be. So we need to convert that as ATR value, whatever is the ATR value on the chart, times whatever the user has specified, one time ATR, two times ATR, three times ATR. Then use the calculate lot size, the function we have just written, sending to it the stop loss distance that we got here to calculate the lot size. So we have the entry, we have the stop loss, we have the stop loss distance and the lot size. Then if trade signal is less than zero, so it's a buy signal, then

24:40 entry becomes ask plus the ATR value times the order distance because we're sending a buy order, which is going to be placed a certain amount above the current price and that is the order distance that the user defines in terms of ATR value. So, 0.2 of ATR, meaning 20% of the ATR, 0.3, meaning 30% of the ATR, and so on and so forth. Then the stop loss is going to become entry wherever we are entering minus the stop loss distance, which is coming from here. And then as a check of a spread, if ask minus bid is smaller than max spread converted into points, then in that case send the buy stop, sending the lot size entry on current symbol, the

25:26 stop loss that we have calculated. Bollinger middle line as the TP, and then comment whatever you want to put. If there's a sell signal, then in that case entry is going to be bid minus the ATR distance, because the price is here and we want to put the stop order below it. The stop loss becomes entry plus SL distance, because stop loss goes above for the sell trades. And then using the same max spread check, we send the sell order, sending the lot size entry symbol, Bollinger main as our TP, the stop loss that we calculated here. And that is our send order function. If I compile, I don't have any errors, but now we're going to we're going to need to write something to trail the stop loss, but

26:12 also if the price keeps dropping, we need to trail our stop order with it at that distance as well. So, that's what we're going to write next, but we're going to be needing two more functions before we do that. So, we go down to the helper functions, and here I'm going to write the first one, which is is it trading time, which goes back to these two values, the start hour and the end hour. So, we only want to trade in between these two times, and that's what we're going to do here. So, we're going to create an MQL datetime variable by the name time. The MQL datetime variable is very useful because you can use, for example, time and then hit dot, then this variable will be able to give you the breakdown by day, hour, minute, month, second, and the year. So, we create that variable and then we store

26:58 the current time into that variable time. And once we have that, now we can create an hour now variable and store in that the time. hour. So, if it is 16:15 in the afternoon, then time. hour is going to return the 16. And then we can check that if the hour now is less than the SH input, then in that case we're outside of the trading range. So, in that case close all of the orders, a function that we will write, and return false. It's not trading time. And if the hour now is bigger than the end time and the end hour input is not zero, then in that case also close all of the orders and return false. So, we're checking both possibilities. Is smaller than this? Close all orders. Bigger than this? Close all orders.

27:45 But if it is neither this nor that, then in that case return true that we are in the trading time. And then because we're calling the close all orders, we're going to write a function for the closing of all orders, which is loop through all of the orders, select by index, get the ticket, and if the order symbol is our symbol and the order magic number is our magic number, then we know that it is a trade by this particular trading bot on the current chart symbol. In that case, just delete that order by using the trade.order.delete and sending the ticket value. That's outside of the trading time this happens. But within the trading time, once we have sent the order, we also need to monitor those orders so that if the price continues to go to go down, we

28:31 trail the order. And once the trade is active and in profit, then we want to trail the stop loss. So, we're going to come back up here at trade related functions, and here I'm going to create another function, which is order and position modifier function. We're going to start by creating a few variables as doubles, meaning they can have decimal values. Current stop loss, new stop loss, current order price, and entry. And an integer variable, so it can only store 1 2 3 4 5, not decimals, as order positions total as zero. What we're going to send to this function is the ask price and the bid price from the on tick because we got those values there. And then we create another variable, trailing distance, and that is going to be ATR value times the trailing of the stop loss ATR. Then

29:17 a minimum stop loss distance is whatever is the broker's stop level requirement. Some brokers do not allow either the stop orders or the stop losses to be placed very close to the price. So, let's get that value from the broker if there is any. And then if the trailing distance that we have calculated is a smaller than what the broker allows, then in that case, we make it whatever the broker allows. Then we again set the order distance to ATR value times the order distance ATR. And the stop loss distance is equals to ATR times the SL ATR. And now we're going to loop through all of the current open positions. Select them by index, and then we're going to check that if the [snorts] position which has been selected here, if the symbol of that

30:03 position is the symbol currently on the chart, and the magic number of the position is equal to our magic number, then in that case, it is our trade on the current chart. So, we get the ticket number by using positioninfo.ticket and the open price of the current position. And because it is an open position, so we increase the number of order positions total by one. Plus plus means equals to plus one. And then we check if it is a buy type position, then we get the current stop loss of the position, and the new stop loss becomes bid minus the trailing distance that we have calculated and verified against the broker minimum. And if then the new stop loss is bigger than the current stop loss, so it has moved

30:48 favorably in our direction, and the new stop loss is bigger than the open price, so it has come into the profitable territory, then in that case we modify the position by sending the ticket number, the new stop loss, and whatever was the take profit of the position anyway. So, we don't change the take profit. And if it is a sell, then it's just the reverse. We get the current stop loss, and the new stop loss is ask plus the trailing distance. And now if the new stop loss is a smaller than, so it's below the current stop loss, meaning it has moved positively for our sell trade, and the new stop loss is less than the price open, so it has come into a profit territory as well, then again we modify the stop loss for our open position as well. Then we

31:33 close the bracket for this if statement, and then close the bracket for the for loop as well. So, this is our trailing of the stop loss months activated. And now we're going to loop through all the orders total selected by index, and then check if it if the symbol equals our symbol and the magic number of that order equals our magic number, then it is our trade on the on the current symbol, then get the ticket value and also increase the order positions total by one. And then we say if it's a buy stop, then the current order price is whatever is the price that the order is sitting on. And then entry is ask plus the order distance. If the distance was supposed to be two pips, but now the price has moved, so it's three pips. So, we want to move it back again to two

32:20 pips as well. So, entry becomes ask plus that. And now if the entry is less than our current order price, because the price is falling below, then in that case new stop loss is entry minus the stop loss distance, which is the original ATR value, then we modify the order sending it the new entry price. Now the stop order is going to trail with the price going down, keeping the same distance. And the new stop loss, and whatever was the take profit before. And then the same for the seller stop, which is if the price keeps rising, we want to also trail our stop order up to keep the same distance from the price. So we do exactly the same thing, but just in reverse. And then we close the if bracket, and then we close

33:06 this for bracket as well. And then at the bottom, we return the value of the total number of orders and positions. So that's our order position modify function. If I compile, I don't have any errors. So we can go back to our on tick, and now below the signal generation, we get the value of the order positions total by running the order position modify function. It's doing two things at the same time, two birds with one stone. When we're going to run this function, it's going to modify the positions if it needs to be modified, but also it's going to return the number of total orders and positions, which we're going to store here. And then we can say that if the order positions total is zero, so there is no order placed and there is no

33:53 open trade, and this trading signal is not equal to zero, so there is a buy signal or a sell signal, and it is within the trading time, that the function we created, then in that case, just send the order, which is with the trade signal, buy or sell, sending it the ask, bid, and the Bollinger mean to this function, which is actually going to send the buy stop and the sell stop. So if I compile now, and let's put a block here and here, because this is where we want the codes to stop, and I run it. The the visual test has to stop here because now we are at a sell stop. So, I'm going to make it

34:38 slow and run. And this is our stop order, which is placed at a smaller value. And as the price continues to rise, our stop order continues to rise with it. But if the price comes down, then the order is going to be taken. We have our TP on the main Bollinger line. But if the price moves in a favorable direction and we enter into the profit territory, then the stop loss is trailed and it's going to continue to trail at a distance that we have defined until either this TP is hit or the trailing stop is taken. So, this is for the sell trade. Now, let's go back and remove this this block from the sell stop and we only have the buy stop now.

35:24 And if we run it, we're going to stop when there is a buy stop. And if I play, then we have the buy stop here. There was a TP below, but the TP is now being trailed at a distance that we wanted to trail. Here is our TP at the Bollinger mean. And normally, your trailing stop loss, once it's in profit and trailing, is going to be taken. So, this is the entire strategy. And now what we are going to do is we're going to build confluences. So, we're going to look at higher time frames and things like those to make it a little bit more watertight. And then we're going to build panels and beautify the year.

Share

Weitere Video-Zusammenfassungen