Login Page - Create Account

Support Board


Date/Time: Sun, 28 Apr 2024 05:43:22 +0000



[User Discussion] - Offering To The Community: Brett's Multi-Function Trailing Stop

View Count: 8984

[2015-10-14 20:28:26]
bjohnson777 (Brett Johnson) - Posts: 284
I've been wanting a MA based trailing stop including trend line and time based exits for a very long time. But first...

A short public service announcement: With the Dow 1000 point crash at the end of August, I decided it was time to take profits on the long term investments. My stuff was easy, but with my elderly mother suffering from Parkinson's, it was very difficult. My health problems didn't make it any easier. Her CFP decided to invest more for himself than her (discovered this was typical of LPL). The hardest to get information were on the variable annuities (which I tend to strongly dislike). They were high cost (3.1% on one) and poor performing. They were also "poison pill" type investment strategies with absurd contracts and penalties (the few contracts I could find). In short, I've spent (wasted) the past 1.5 months sorting and digging through hundreds of pages of statements, getting power of attorney, and hiring a lawyer to clean up an investment mess that was supposed to be simple by mom's instructions. FINRA won't get involved because there weren't any real losses... better not be over 12 years... but the "investments" grossly underperformed the S&P 500 "SPY" ETF and a SMA200 crossover trading strategy for comparison. Moral of the story: now is a very good time to check long term investments for you and your family members.

Now back to the regularly scheduled post...

I've tested this program with my trading style and have it debugged. I normally do longer day trades to swing trades. It may or may not work well with other trading styles. If you run into a problem, I will need detailed steps to reproduce the issue on my end. Please take good notes.

Since I'm not done programming all of the tools I want yet, I do not have a live trading account to test it against. In theory, real time simulation trades should be almost equivalent to live trades, but there might be a quirk or two that needs ironing out. Please take good notes again. I plan to have a live trading account in a month or two... barring any more disasters.

From the help file:
----------

Trading: Brett Johnson's Multi-Function Trailing Stop. Copyright 2016 under GNU GPL v1. If you use this code in your own program, share it like I have. This program provides a trailing stop based on a moving average. This helps prevent premature exits caused by 'bar whiskers' and some stop running. There is also:

A traditional trailing stop further away for safety.
An exit trend line useful for catching channel break outs.
A price target feature.
An exit based on the time of day (such as market closing).
An exit based on the end of the trading week (avoiding weekend gaps).

Note For Lawyers: The goal of this trading program is to keep losses small and let winners run. While this code has been written as solid as possible with many extra safeties in the code, every possible scenario cannot be accounted for. It will also not protect from bad trades 100% of the time. It will not make a bad trading plan into a good one. It is not a magic black box with unlimited profits. There will be money lost. Hopefully losses will be limited and the gains will be far more. There is no warranty expressed nor implied. This trading program is open sourced. If you have questions about programming competency or how it works, source code can be easily checked. There is also extensive documentation in the 'Display Study Documentation' button on how things work and the quirks of the program.

By using this program, you first agree to test it out in simulation mode. While the conceptual operation is quite simple, some of the actions will be unexpected. I wrote this program and some of the actions caught me off guard. When there is real money on the line, always test first.

Functionality and Observations

Sierra Chart must be up and running and connected to the trade service to manage trades. A connection loss to the trade server will mean that the watched orders will go unmanaged and may go horribly wrong. Always use the Safety Trailing Stop option as it will leave a protection Stop at the trade server that does not depend on Sierra Chart connectivity. Note that since the Safety Trailing Stop is on the trade server, it will execute much faster than Sierra Chart triggering an exit order. The Safety Trailing Stop is a traditional Trailing Stop managed by Sierra Chart (not this program) and will be triggered by any price action hitting it. Sierra Chart manages its Trailing Stop by periodically moving a fixed Stop on the trade server.

Make sure there is at least enough data for the 'Price MA Smoothing Period' before trading.

This program is for managing a single order after it has been opened. Multiple trades going in will be treated as an overall single trade. This may not have the desired effect you were expecting.

On the chart, up arrows are used for long positions and down arrows are used for short positions. A green arrow shows an order entry. A red arrow shows an order exit.

The Message Log is used to record entry, exit, and notable changes. If there is an error, the Message Log will pop up with a description of the problem.

The Settings window has a bunch of Flag values at the top. The Flags are set from Sierra Chart's current internal settings. Changing them in the Settings window will do nothing. The point of the Flags is to report Sierra Chart settings in one convenient location and show if trade management will be enabled or not. Set 'MA Trailing Stop Offset' to 0.0 (disabled) to check Flag values before trading. Some values may not change until the Settings window is closed and then reopened.

This program will wait in standby mode for an order to appear. After that, it will start managing it. Check the Flags in the Settings window to make sure detected trade values are correct. When the order closes for any reason, this program will go back into standby mode waiting for the next order.

The MA Trailing Stop is based on a distance from the Price MA line instead of price bars. If the bar price crosses the Price MA line, nothing will happen. This is to help keep noise from causing a premature exit. Note that the Price MA's smoothing period should not be set too high or it will cause significant lag during a high volume jump that will exit the trade late. At the same time, a less noisy price line will allow for tighter stops. If the Price MA line crosses the MA Trailing Stop line, then the MA Trailing Stop will be triggered. The same will happen if the Price MA line crosses the Exit Trend Line. All orders will be flattened and pending orders will be canceled. This leaves a clean chart for the next trade.

The MA Trailing Stop Leading Edge line is used to show where the Price MA line would have to cross to move the MA Trailing Stop line. If the Price MA line is bouncing between the two lines, then they won't move.

If there is an event that causes a graph reset, a redraw will be issued. The redrawn trailing stop lines will be close but not be exactly as they were before due to all the live data not being saved. The Safety Trailing Stop will jump a little at the end of the redraw because of rounding to the nearest tick and the variables realigning over the next few bars. It also is not possible to reset a Safety Trailing Stop with the same price distance information as before, so it might step backwards.

Warning: Changing the chart time period (like from 1m to 5m) will redraw the Price MA line using different bar data and could trigger an immediate stop out. If you need to see multiple time frames, duplicate your chart window before this program starts and leave this program running in it undisturbed.

Warning: if there are multiple open orders not generated by this program, behavior will be undefined. Early partial exit orders could screw up the Price Target feature. A partial Stop order could screw up the Safety Trailing Stop feature. In this case it would very likely create unwanted positions in an unwanted direction. Use the 'Cancel All Other Orders On Entry' feature to stop this from happening. Note again that this program was designed to manage a single order at a time. Adding additional pending orders after order management has started may cause undefined behavior.

The Safety Trailing Stop is constantly moving and much more complicated to keep track of. This program cannot reliably track it. If you move it on the chart, it will be moved back during a reset. This may not be a desired behavior. If you need to change the Safety Trailing Stop, do it in the Settings window.

The Exit Trend Line position will be saved with the chart. This is the same as if saving regular drawing lines with the chart. If you're not in the habit of saving the chart, turn on autosave: Global Settings >> General Settings >> General2 >> Autosave Chartbooks Time In Minutes. If the saved trade data (symbol, date stamp, volume, trade direction (long/short)) doesn't match the current trade on program re-entry, the Exit Trend Line will reset itself flat at your trade start point. If it does match, the Exit Trend Line will resume its previous function. If it does match and the Price MA line has already crossed the Exit Trend Line on program reload, that will trigger an immediate order exit. Make sure the Exit Trend Line drawing points are not in the empty Fill Space or it may jump to a new position on program re-entry. This could cause a premature or late exit.

This program has a safety order limiter in place. If there are 3 new position entries and exits within 15 seconds, this program will disable itself. This helps prevent massive losses in commissions from multiple automated bad position entries that might never stop until someone manually pulls the plug. Be warned that the entered positions will no longer be managed. The automated entry program should also have a safety similar to this. Some might call this an Order Exit Circuit Breaker to prevent costly race conditions.

Replay Notes. The time exit features will not work in any Back Test or Replay Mode. This program uses sc.CurrentSystemDateTime to set the time exit variables. The sc.CurrentSystemDateTime variable always returns current time and not Replay time. There is no clean way to get around this limitation. When you are finished with Replay testing, double check the Settings window to make sure this program is set up for your normal operations. It is recommended to run Replays and Back Tests in a separate chart window to avoid conflicts with your normal trade settings.

The rest of the program functionality is described in the Input Descriptions blocks.

-----
Minor update 2022-07-10. Minor update to compile with SC 2411. No function change.
Regular compiles moved to "Brett Johnson's Standard Tool Kit" DLL.
Offering To The Community: Brett Johnson's Standard Tool Kit
Date Time Of Last Edit: 2022-07-10 07:42:52
Attachment Deleted.
Attachment Deleted.
attachmentTrading_BrettJohnsonsMultiFunctionTrailingStop.cpp - Attached On 2022-07-10 07:42:44 UTC - Size: 124.27 KB - 130 views
[2015-10-15 01:06:18]
Joe Hobart - Posts: 89
thanks for sharing this code sir. do you have a tip on how to get it to fire in Replay mode? it works fine in real time sim, i wanted to feed it some specific scenarios, but the orders don't show up.
[2015-10-15 08:03:33]
ehlaban - Posts: 50
Thank you for sharing, appreciated!
[2015-10-15 16:27:34]
bjohnson777 (Brett Johnson) - Posts: 284
@Joe Hobart: I wish I did. The SC buy/sell functions only work during normal/straight operations. I had to include some preventative error management code (such for replays, redraws, recalcs, etc) to make sure the program didn't improperly handle and miss an exit condition or prematurely fire. Not screwing that up was my primary goal. There's also the issue that this program handles sells/exits only. There would have to be another program generating buy/entry points.

Since this is my first order management program, I haven't done much with Replay yet. All my tests have been in a separate normal-time chart window. As I'm shifting gears back to coding, I'll keep an eye out to see if there's an easy fix.

If anyone has a good code example, please link me and I'll try to get to it this weekend. I'll dig for the replay docs probably tomorrow. I've got some more CFP clean up eating the rest of my time today.
[2015-10-15 16:42:17]
Joe Hobart - Posts: 89
I am really appreciative of the effort here.

I do think that figuring out how to get it to work in replay is a key piece of it. There is no way i would let this thing loose in an actual market without 100s of tests. Hopefully someone can help us get over this hurdle.
[2015-10-17 21:34:02]
bjohnson777 (Brett Johnson) - Posts: 284
I've gone through the documentation, and I think I've made all the necessary changes to the source code without compromising safety.

I've also programmed another buy in testing program. It will watch for no orders then enter one based on a pair of MA line positions. It will go into standby mode until the order disappears.

In theory control should bounce back and forth between the 2 programs.

I've tried running them in Replay mode, but something isn't right. I'll get hundreds of exits in the message log when there shouldn't be any. I can see the graph and know when there should be an exit. The trailing stop program has never done this in regular real time sim mode.

I'm running SC under WINE. That may be an issue. The replay runs extremely slow and seems overloaded. Sometimes the replay system will crash and I have to fully restart SC.

Can you (or someone else) run some tests with this setup? I use a plain chart with the 2 programs. The testing buy in program is also attached.

NOBODY download these versions for anything other than testing. The version in the first post is stable and current. These are for testing only and may have problems that need to be worked out.

==========
Edit: found the problem, removing old files.
Date Time Of Last Edit: 2015-10-19 21:26:14
Attachment Deleted.
Attachment Deleted.
[2015-10-19 21:29:19]
bjohnson777 (Brett Johnson) - Posts: 284
Found the problem. The buy in program was executing a new trade so fast that the trailing stop program didn't have even one iteration to finish the exit code. I fixed it with a simple flag.

I have a replay running right now. Everything is performing as expected.

-----
Minor update 2018-09-18. Minor documentation update.
Regular compiles moved to "Brett Johnson's Standard Tool Kit" DLL.
Offering To The Community: Brett Johnson's Standard Tool Kit
Date Time Of Last Edit: 2018-10-02 20:07:13
attachmentTradeTesting_ConstantEntryForAnExitManagementProgram.cpp - Attached On 2018-10-02 20:06:57 UTC - Size: 12.81 KB - 563 views
attachmentTradeTesting_ConstantEntryForAnExitManagementProgram_64.dll - Attached On 2018-10-02 20:07:05 UTC - Size: 844.5 KB - 564 views
[2015-10-19 23:24:54]
Joe Hobart - Posts: 89
awesome, nice research! can you post the .cpp files? i prefer to compile any code im going to run on my trading rig :)
[2015-10-20 00:17:19]
bjohnson777 (Brett Johnson) - Posts: 284
Understandable. Source attached for both.

I've been going over and checking the source for the trailing stop program this afternoon. I don't think the small changes have negatively affected it. This version should be stable.

-----
Edit: Get the latest Trade Testing in an above post.
Date Time Of Last Edit: 2016-02-07 03:18:32
[2015-10-20 05:34:04]
User44052 - Posts: 34
Thanks Brett. This is great!
[2015-10-21 08:48:04]
User47643 - Posts: 13
Thanks, Brett. I need some help getting this study to work.

I'm on SC Package 3 with AMP/TTNet. I'm using the Trading_BrettsMultiFunctionTrailingStop_0.92.cpp from post #9. The first three flags are YES. I'm in simulation mode. Price MA Smoothing Period is 10. MA Trailing Stop is 6. "Did you read the instructions" is still NO.

If I force "Did you read the instructions" to YES in the code, the MA line shows up, but open positions are still not detected.

How can I troubleshoot this?
[2015-10-21 15:48:40]
User47643 - Posts: 13
I got the study to work. Because the "Did you read the instructions" didn't accept my input earlier, I assumed that input got set automatically. I've learned that I have to set it manually after I get everything configured. I also had to change the Scale from "Automatic" to "Same As Region".

It seems to be working fine now. I need to practice with it some more.

I normally use a TradeDOM adjacent to but separate from a chart for trading. I notice that I can adjust the Target from the TradeDOM and this study will follow the change. Therefore, this question: If I change the code to where "Chart Trade Mode On" is no longer required, will I lose any functionality by using a TradeDOM instead of using a chart for trading? (This would put the right-click context menu back to the way I like it.)

Thanks!
[2015-10-21 17:49:34]
bjohnson777 (Brett Johnson) - Posts: 284
User47643

The "Did you read the instructions?" settings is actually enable/disable. Since this trade program is a bit different from most, I use it as a reminder to check the documentation page so users don't get a surprise. When the program is disabled, nothing gets updated or executed. It is fully disabled.

For "Same As Region", I just added code to make that permanent. I'm not sure why SC sometimes doesn't line up the graphs with the bars, but you found the necessary fix. I'll release a minor revision update probably in a few days.

"Chart Trade Mode On" is required by SC for some features. I know the Safety Trailing Stop, which is a normal Trailing Stop from SC's view, needs it to update properly. Always enable the Safety Trailing Stop for safety reasons in case connectivity is lost to the trade server. I usually move the Safety Trailing Stop far enough away that a bar whisker / stop run won't immediately hit it. If connectivity is lost, the trade server will have a plain Stop at the last known position to prevent a catastrophe in case the market turns against you. Ideally the Safety Trailing Stop will never be needed and will never be hit, but Murphy's Law tends to dominate and say otherwise.

I think "Chart Trade Mode On" was used by something else, but I can't remember off hand. SC documentation is vast and I can't find it in a quick search.

The chart and TradeDOM following each other is an internal function of SC. Actually, it's probably the chart and TradeDOM following the symbol's internals, peeking under the hood. My program should be following this also, as you have already noted. I have some extra code to make sure it does to avoid any "surprises". If you ever see an update that doesn't track, please take good notes on how to reproduce it as I'll need to fix that.

Enjoy
[2015-10-21 23:04:00]
User47643 - Posts: 13
As an experiment, I disabled the code that requires "Chart Trade Mode On". As far as I can tell, the Safety Trailing Stop is working and updating fine without Chart Trade Mode.

I searched for "Chart Trade Mode" on the two main pages of documentation for Automated Trading and didn't find any mention of it.

As you're updating the code, I wonder if there could be an option something along the lines of "Clear Drawings on Position Close", where "No" would be the current behavior and "Yes" would clear all the SubGraph Drawings and the Exit Trend Line when the managed position is closed. Currently, I use the Chart Option to "Reload and Recalculate" to accomplish this.

This is indeed a fine piece of work! Thank you very much!
Date Time Of Last Edit: 2015-10-21 23:05:25
[2015-10-22 01:11:50]
bjohnson777 (Brett Johnson) - Posts: 284
This is where I found that "Chart Trade Mode" needed to be on for SC managed trailing stops:
http://www.sierrachart.com/index.php?page=doc/doc_OrderTypes.html#ManagementOfTrailingStopOrders

I'm real hesitant to remove the code from my official release given this information.

I think chart clearing code like you mentioned shouldn't be too hard to do in the post trade reset code. I'll have a look at it tomorrow.
[2015-10-22 01:19:32]
bjohnson777 (Brett Johnson) - Posts: 284
Looking over that doc page again, I think since you have the Trade DOM open, it is managing the trailing stop. If it was just a chart without the Trade DOM, "Chart Trade Mode" would have to be on.
[2015-10-22 16:11:06]
bjohnson777 (Brett Johnson) - Posts: 284
Changes made along with a couple minor tweaks from earlier in the week. Let me know if your graph clears after trade exit (mine did fine during testing).

Current version is now 0.93 and stable.

-----
Edit: Get the latest version in the first post.
Date Time Of Last Edit: 2016-02-07 03:19:28
[2015-10-27 15:33:11]
User126996 - Posts: 30
Just at a glance it appears that it won't replay outside of trading hours bc the "HandleTimeExitSetup" is set against sc.CurrentSystemDateTime. Therefore, if your system time is outside the hours of trading it cancels all orders. I would recommend the following code to fix this. I apologize that I can't implement this. I have a few appointments today to get to. But I at least wanted to share immediately to help solve the issue. Thanks for sharing this! If you are rusty with programming it sure doesn't show.


// Establishes adjustable inputs for time ext in SC Defaults
if (sc.SetDefaults){
sc.Input[33].Name = "Start Hour";
sc.Input[33].SetInt(0);
sc.Input[33].SetIntLimits(0, 23);

sc.Input[34].Name = "Start Minute";
sc.Input[34].SetInt(0);
sc.Input[34].SetIntLimits(0, 59);

sc.Input[35].Name = "End Hour";
sc.Input[35].SetInt(14);
sc.Input[35].SetIntLimits(0, 23);

sc.Input[36].Name = "End Minute";
sc.Input[36].SetInt(0);
sc.Input[36].SetIntLimits(0, 59);

return; }

/***************************************************************************
Start - Calculating Time Exit Strategy
***************************************************************************/
int StartTime, EndTime, InputDate;
SCDateTime StartDateTime, EndDateTime, InputDateTime1, InputDateTime2;

InputDate = sc.BaseDateTimeIn[sc.Index].GetDate();
InputDateTime1 = sc.BaseDateTimeIn[sc.Index];
InputDateTime2 = sc.BaseDateTimeIn[sc.Index - 1];

StartTime = HMS_TIME(sc.Input[33].GetInt(), sc.Input[34].GetInt(), 0);
StartDateTime = COMBINE_DATE_TIME(InputDate, StartTime);
EndTime = HMS_TIME(sc.Input[35].GetInt(), sc.Input[36].GetInt(), 0);
EndDateTime = COMBINE_DATE_TIME(InputDate, EndTime);

/***************************************************************************
Stop - Calculating Exit Strategy
***************************************************************************/

/***************************************************************************
Start - Execution of Time Exit Strategy
***************************************************************************/

int& inTradeTime = sc.GetPersistentInt(0);
int& outTradeTime = sc.GetPersistentInt(1);

if (InputDateTime1 > StartDateTime && InputDateTime1 < EndDateTime ) {

inTradeTime = 1; }

else { inTradeTime = 0; }


if (InputDateTime2 < EndDateTime && InputDateTime1 >= EndDateTime && PositionStatus != 0) {

outTradeTime = 1;
sc.FlattenAndCancelAllOrders();
return; }

else { outTradeTime = 0; }



I hope this helps. I just glanced through the programming.
[2015-10-29 19:42:46]
bjohnson777 (Brett Johnson) - Posts: 284
User126996: I understand about the delays. I keep getting hit with multiple things that "have to be fixed right now". With my health problems, I'm having trouble keeping up. I really need to be focused on programming right now.

Your proposed code would kinda work OK for replay, but it wouldn't work so well during live trades.

I ran into this problem and that's why I had to scrap my initial code and change over to sc.CurrentSystemDateTime.

The issue is using bars for current time. On a heavily traded 1min chart, this isn't too much of an issue, but a 2min chart or higher will show these problems.

2min Stock Market Example: Let's say you want to exit at 15:59 and stocks close at 16:00. On a 2min chart, odd numbers will never come up. The exit code wouldn't be triggered until 16:00 and then it would be too late. For a 2min example, it isn't too hard to just roll back the exit time to 15:58. But what about a 5min chart? or a 1h chart? That's when the code really starts to break.

Expanding the example a little more, what if trading totally falls off at 15:50? No bars means no tracked time ticks means nothing happens.

During the mid-day lull, some of the better traded stocks and ETF's might go several minutes without a trade. If someone set a time exit in the middle of that, nothing would happen.

That's my reasoning for turning on sc.UpdateAlways and checking the system clock when exit times are activated. This method is highly reliable during live trades.

During a replay, the bar time exit code would probably work OK for a 1min chart. For anything higher, there's the possibility that the person would want to exit sometime in the middle of a bar. The larger the bar time, the larger the time error would be. This would give skewed results and bad numbers in the replay reports. If someone tried to build a trading plan off that, there's a high possibility things could go wrong, and I'd get blamed.

I created the time exit features mainly as a safety catch. If I get distracted, get hit by an important phone call, something pulls me away, or I just have to go lie down for a little while, the safety catch will have my back in case I miss my exit time.

Thanks for the interest. :-)
[2016-02-07 03:21:12]
bjohnson777 (Brett Johnson) - Posts: 284
Minor update 2016-02-06. No major function changes. Fixed the SCT_OSC_PENDINGCHILD split.
Regular compiles moved to "Brett Johnson's Standard Tool Kit" DLL.
[2016-10-15 06:21:58]
bjohnson777 (Brett Johnson) - Posts: 284
Today's DLL was compiled with the M$VC++ change over.
You may need to update your SC version.
Keep your previous DLL version until you've tested the new compile.
Most changes were made to shut up useless M$VC++ warnings when compiling.
There are a few compile warnings left about "argument" that can be ignored.
No real functionality changes have been made.

Note my trailing stop was renamed for consistency. You'll need to re-add it if you're using it.
[2016-11-16 20:03:07]
bjohnson777 (Brett Johnson) - Posts: 284
New version uploaded. There are significant internal changes.

Total rewrite of Exit Trend Line to a class so it can be saved with the chart. Previous functionality still the same. So long as the chartbook is saved before an exit, the Exit Trend Line will be recreated. Enabling autosave is recommended.

Heavy modification of Price Target functions. Previous functionality is still the same, but now it's easier to use.

Added "Average Bar Height" to make apparent vertical price differences easier to set between different symbols. In short, this averages the height of the past 200 bars (user configurable) to turn it into a "unit". Most trailing stops will be X units behind the price movement, no matter what symbol is loaded or the time frame.

Cleaned up the code and made it easier to read.

*** You must fix your settings with this new version. *** The "Average Bar Height" setting was added to the Settings window and this throws off all the other settings below it.

Also re-read the documentation to get more details on what I've added and changed.
[2016-11-18 00:29:48]
User553714 - Posts: 184
Hi,

Could you please upload the latest cpp; thanks for sharing this! Regards
[2016-11-18 05:48:21]
bjohnson777 (Brett Johnson) - Posts: 284
Anytime I make a change, I'll upload new files to the first post and add a message to the thread of this notification. Hit the "Follow" button and the message board will automatically notify you. Last change was on 11/16 (this week).

I'll update my consolidation DLL probably this weekend with this version. I usually wait a few days on the DLL if I've made major changes to make sure someone doesn't find a bug.

Enjoy
[2016-11-22 22:34:24]
bjohnson777 (Brett Johnson) - Posts: 284
In doing overnight trade tests, sometimes I've run into an odd intermittent bug that will exit the position when the chart is recalculated. It's been hard to trace down, but I think I've fixed it.

I also changed the default setting for "Price Input Bias" to "No". This only works well on low volatility symbols. For regular volatility, "HLC Avg" seems to work well. For high volatility, choose "Last" to get non-averaged data. As always, give the settings a test with your preferred trading style.

To post a message in this thread, you need to log in with your Sierra Chart account:

Login

Login Page - Create Account