money management – Helping you Master EasyLanguage https://easylanguagemastery.com Helping you Master EasyLanguage Mon, 20 Nov 2023 10:25:45 +0000 en-US hourly 1 https://wordpress.org/?v=7.0.2 https://easylanguagemastery.com/wp-content/uploads/2019/02/cropped-logo_size_icon_invert.jpg money management – Helping you Master EasyLanguage https://easylanguagemastery.com 32 32 Disabling Trading At Profit Target or Max Stoploss https://easylanguagemastery.com/building-strategies/disabling-trading-profit-target-max-stoploss/?utm_source=rss&utm_medium=rss&utm_campaign=disabling-trading-profit-target-max-stoploss https://easylanguagemastery.com/building-strategies/disabling-trading-profit-target-max-stoploss/#comments Mon, 21 Dec 2020 11:00:52 +0000 http://systemtradersuccess.com/?p=9251

When building trading systems, particularly intraday trading systems, you often run into the special conditions where you might want to stop trading. Those two conditions are:

1) When a particular daily profit target is reached. In this case you have determined that when a particular dollar amount is reached in profit then no more trading should be done for the remainder of the day.

2) When a specific dollar value is reached. In this case, you have determined that after you have lost X amount of money, it’s best to stop trading for the rest of the day.

In both of these cases it’s possible to write code that will disable the opening of new trades when either of these functions is reached. In this article I’m going to use EasyLanguage to create a function that will perform these two tasks of disabling an intraday trading system. The final code will be freely available at the bottom of this article where you can easily apply it to your own intraday strategy.

Tracking Daily P&L

The first thing to code is a mechanism for tracking the daily profit or loss for the current day. It will track the net profit of a trading system, but we want to know the profit or loss just for a single day. So, we’re going to write some code to manually track this. The following code will do just that.

First, we’ll define two variables to hold our profit. The first is the profit or loss accumulated for our strategy through yesterday. The second variable is the accumulated profit or loss for our strategy just for today.

PLB4Today(0),   // P&L total before today
PLToday(0),    // P&L total for today (NetProfit + Open Position Profit – PLB4Today)

Next, we’ll add the following code to determine what our current profit or loss is just for today. We do this by using TradeStaton’s built-in reserved word, NetProfit. But NetProfit gives the value for all closed trades. We don’t want that. We don’t want to include the P&L from trades closed today. Thus, we must subtract the net profit up through yesterday. Hence, our PLB4Today variable comes into play.

PLToday = NetProfit – PLB4Today;

Now we have PLToday holding just the value of the profit or loss from today. But what if we have an open position? Maybe it’s a big loss or maybe a big win. Either way, we should include it. We can easily do this by using TradeStation’s built-in reserved word, OpenPositionProfit.

PLToday = NetProfit – PLB4Today + OpenPositionProfit;

Now PLToday contains the closed profit from today plus any open position profit. The only other task for properly tracking the P&L is to update our PLB4Today variable with today’s P&L at the close of the day. The following line of code handles that.

if ( Date <> Date[1] ) then PLB4Today = NetProfit;

Disabling Trading

Now that we have the means to track today’s profit or loss we can make decisions based upon this information. First, let’s tackle the idea of disabling our trading based upon reaching a profit target level. Initially, we’ll create flag which will act as our indicator when trading should be stopped. Let’s create a Boolean variable called OK_To_Trade.

OK_To_Trade(false)

At this time it’s just a mater of setting this variable based upon our daily P&L. Let’s turn our trading system off if we reach $500 in losses today. In other words, we will not open any new positions after we lost $500 within one day.

if ( PLToday <= -500 ) then OK_To_Trade = False;

Let’s say our trading system did just lose $500 and the code set our OK_To_Trade variable to false, now what? Well, when this variable is set to false we presumably want to close all trades and take no more new trades for the remainder of the day. To accomplish this we write the following code:

if ( OK_To_Trade = False ) Then
Begin
Sell next bar at market;
Buy To Cover next bar at market;
End;
if ( OK_To_Trade = True ) Then
Begin
{ Our trade entry logic goes here}
End;

At this point we have the code that will disable taking new trades if our daily loss limit of $500 is reached. Of course you can create another input variable to hold your daily loss limit. That way you can easily test different values.

Another important aspect to note about this code is our PLToday is computed by including any open position profit. That means your trading system would stop trading if your close P&L plus any open position profit was at $500 or greater. This may or may not be what you intend. For example, maybe you only wish to have closed profit counted. If that’s the case then you don’t want to include the open position profit in your calculation. It’s a small change in the code but, something to keep in mind.

Now let’s turn our attention to disable trading when our profit target is reached. We can do this by creating another condition where we set our trading flag to False. In this case, let’s stop trading when we reach a $600 profit for the day.

if ( PLToday >= 600 ) then OK_To_Trade = False;

Now our OK_To_Trade is set to False when we have a profit of $600 or more. At this point setting our flag to false will result in the same behavior as when we set this flag to false when we reached our stop loss limit. That is, all trades will be closed and no new trades will be taken today.

Again, keep in mind as soon as all closed P&L plus the open position profit reaches $600 the current trade will be closed. This might not be what you want. You may prefer to move your stop or simply allow the trade to unfold naturally. So, keep this in mind.

Creating A Function

Putting this code into a function is a great idea because it makes reusing this code very easy. I’m not going to go through the steps used to convert this to a function, instead I’ll simply explain the inputs and how it can be used.

First, the function is called _CE_Limit_Profits_And_Losses

The function takes four parameters:

  1. Daily profit target in dollars – enter zero to disable
  2. Daily stop loss in dollars – enter zero to disable
  3. Stop limit flag – True indicates stop limit hit
  4. Profit Max Flag – True indicates profit max hit

The first two inputs are rather straight forward. You can disable either of these first two inputs by passing in a zero. For example, if you don’t want to use the daily profit target simply pass in a value of zero.

Both inputs #3 and #4 are set by the function. They are referenced inputs which means information is passed back from the function to the calling strategy.

Input #3 is a Boolean flag which is set to true if the stop limit was hit. Likewise with input #4, this Boolean flag will be set to true if the profit max was hit. Setting these variables allows your calling program to know which of the two conditions was met. This can be helpful in tailoring different behaviors depending if the daily profit target was hit or the daily loss limit was hit.

Below is a simple SMA strategy that buys when price closes above the moving average and sells short when price moves below SMA. The _CE_Limit_Profits_And_Losses function is used to enforce both a daily profit target and daily max stop loss. The DailyLossLimit flag and StopLimitFlag are used to create unique exit messages on the sell and buy-to-cover orders.

TradeFlag = _CE_Limit_Profits_And_Losses( DailyProfitTarget, DailyLossLimit, StopLimitFlag, ProfitMaxFlag );

If ( TradeFlag ) Then
Begin
If ( Close > Average( Close,100 ) ) then buy next bar at market;
If ( Close <= Average( Close, 100 ) ) then sell next bar at market;
End
Else begin
If ( StopLimitFlag ) Then
Begin
Sell(“Loss Limit”) next bar at market;
Buytocover(“Loss Limit “) next bar at market;
End
Else If ( ProfitMaxFlag ) Then
Begin
Sell(“Profit Max”) next bar at market;
Buytocover(“Profit Max “) next bar at market;
End
Else Begin
Sell(“LE”) next bar at market;
Buytocover(“SE”) next bar at market;
End;
End;

Setexitonclose;

]]>
https://easylanguagemastery.com/building-strategies/disabling-trading-profit-target-max-stoploss/feed/ 16
Using EasyLanguage To Limit Trades https://easylanguagemastery.com/building-strategies/using-easylanguage-limit-trades/?utm_source=rss&utm_medium=rss&utm_campaign=using-easylanguage-limit-trades https://easylanguagemastery.com/building-strategies/using-easylanguage-limit-trades/#comments Mon, 19 Sep 2016 10:00:10 +0000 http://systemtradersuccess.com/?p=9682

In this article I’m going to demonstrate an EasyLanguage technique to limit the number of trades your trading system will take within a given period. Most often this is done to limit the number of trades a strategy will open in a single day. For example, you may want your day trading strategy to only take a maximum of 20 trades per day. Once it reaches that number, you wish the strategy to not open any more trades until the next trading day.

The code I’m going to write will be a more flexible method than the built-in TradeStation reserved word, EnteriesToday. This works fine in many cases, but what if you wish to limit the number of trades in the overnight session? EnteriesToday assumes the regular session and will reset the trade counter when the day changes – right in the middle of your trading. What if you wish to limit the number of trades over a given week? Nope, can’t do it with EnteriesToday.

Tracking Each Trade

The solution is rather straightforward. We simply wish to track each new position. This can be done by incrementing a variable every time your strategy opens a trade.

Variable: TradesCounter(0);

How do we know when a trade has opened? One way to do this is to monitor the market position state of your strategy. This is done by checking the status of the TradeStation’s built-in reserved word MPMP will have a value of 0 if your strategy is flat. It will have a value of -1 if your strategy is short, and it will have a value of 1 if your strategy is long. Thus, we simply look for a switch between these states.

If ( MP <> 0 ) and (MP[1] <> MP ) then TradesCounter = TradesCounter+ 1;

In the above code we see the first test is to check that we’re not currently flat. The second test then checks that on the previous bar the market position status is not the same as the current status. Put another way, something changed! Again, the first check assures we have a position, either long or short. The second check is looking for a position changed from the previous bar. If this happens, a new position was taken. When a new position is taken, we increase our counter.

Now we can test our counter to see if we’re at our limit. Let’s say we don’t want more than 15 trades, then we can code something like this…

If TradesCounter < 15 then begin
{ Trade entry logic }
end;

The trading entry logic will only be executed if our counter is below our threshold of 15 trades. Once our counter rises above 15, the trade entry logic will no longer execute. Our trade exit logic will continue to function to handle any open positions.

Resetting The Trade Counter

The next step is to reset our TradesCounter counter to zero. This is done when the particular time horizon has passed. That is, do we wish to limit our trades upon a new day? If this is the case then we can write this line of code:

If date <> date[1] then TradesCounter = 0;

The above line of code will set our counter to zero when the date on the previous bar is different than the current bar. Keep in mind, this code we’re writing is for intra-day trading! Thus, when the previous bar has a different date than the current bar we must have entered a new day.

But what if we want to reset our counter at a different time? For example, if we wish to reset our counter at the close of the U.S. regular session? Or, maybe at 2:00 a.m. Central when the regular session for the Euro currency futures opens? Well, this can be accomplished by entering the appropriate time when to reset the counter.

If ( time = 200 ) then TradesCounter = 0;

In the above line, the counter will be reset at 2:00 a.m. based upon your local machine time. You can create an input called ResetTime which will allow you to easily change the time when the counter is reset. The code is below.

If ( time = ResetTime ) then TradesCounter = 0;

Maybe you wish to limit the number of trades in a given week. How would you code that? Well, we simply look for a a particular day of the week to reset our counter. Clearing-out or zeroing our counter at the start of the U.S. Regular Session on Monday will allow us to track the number of trades throughout the entire week.

We can do this by using TradeStation’s built-in Reserved Word called, DayOfWeek. This returns an integer value zero through six. The meaning of this value is straightforward with zero being Sunday and Friday being five. In our example we want to reset our counter on a Monday morning at 8:30 a.m. Central – the regular session open within the U.S.

If ( DayofWeek(Date) = 1 ) and ( Time = 830 ) then TradesCounter = 0;

Limit Trades Function

With this code you can now limit the number of trades on an intra-day strategy. You can easily take the code snippets contained within this article and add them to your strategy. In the downloads section of this article below, you’ll find a function that I created which can be used in your code. The function is called, _CE_Limit_Trades. An example of calling this function is below.

OKtoTrade = _CE_Limit_Trades( ResetCondition, MaxTrades );

The first parameter is your reset condition. This is the condition on which to reset your trade counter. I provided several ideas within this article. The second parameter is the maximum number of trades you wish your strategy to take.

Here is an example strategy using the Limit Trades Function.

Input:
ResetCondition(date <> date[1]),
MaxTrades(5);
Variables:
OKtoTrade(FALSE);
OKtoTrade = _CE_Limit_Trades( ResetCondition, MaxTrades );
If ( OKtoTrade ) Then Begin
If ( RSI( Close, 3 ) < 10 ) Then buy next bar at open;
If ( RSI( Close, 3 ) > 90 ) Then sellshort next bar at open;
End;
If ( Barssinceentry(0) >= Random(5) + 2 ) then Begin
sell next bar at open;
buytocover next bar at open;
End;

In the example below you can see the ResetCondition is set to reset the counter upon a new date. However, the ResetCondition can be any valid EasyLanguage code which evaluate to true/false. For example you could use the text “date <> date[1]” or “time = 200”.

]]>
https://easylanguagemastery.com/building-strategies/using-easylanguage-limit-trades/feed/ 15