A Semi-automated Trend Line Trading Strategy
The chart below illustrates user drawn trend lines controlling a semi-automated strategy to execute the desired trades: (1) a sell stop order entry (dotted red TL), (2) a profit target (solid green TL), and (3) a buy stop order as a stop loss (dotted green TL):
A detailed description of the technique, documentation for the code, and configuration recommendations may be found in these sections that follow:
Classically drawn trend lines provide one of the best indicators for identifying a change or break in a trend. For this reason, their use in directing semi-automated trading strategies is becoming more popular.
Various methods have been proposed to trigger orders by using trend lines manually drawn on the chart. For example, the trend line number or its color can be used to identify the desired order type (Buy Limit, Buy Stop, Sell Limit, Sell Stop).
Desirable characteristics of any system used to define trend lines are that it be logical, intuitive and user friendly:
However, using trend line numbers to identify the type of order desired is problematic. The trader must draw the desired trend lines in a particular order, since trend line numbers are assigned sequentially as they are added to a chart. The trader must ensure that no other trend lines exist on the chart, as previously drawn trend lines may have drifted out view of the range of data displayed on the chart. If a mistake is made and a trend line is deleted and then redrawn, the trend line numbers may no longer match the associated order types and the strategy may not behave as expected.
Using color to identify the desired order type is a bit more user friendly and less prone to trading errors. After defining the specific colors that are to represent specific types of orders (Buy Limit, Buy Stop, Sell Limit, Sell Stop, etc.), functions such as the built-in Tradestation function TL_FindColor may be used to locate the trend line number of the first trend line matching one of these colors. Unfortunately, the number of colors that display brightly on a chart are limited, and the darker colors are not easily seen.
Using both the trend line Color and Style (solid, dashed, dotted, etc.) to identify the various order types seems to have some advantages:
Most all trading strategy actions can be reduced to four order types, Buy Limit, Buy Stop, Sell Limit and Sell Stop, as follows:
To make trend line trading more intuitive and user-friendly, both Color and Style can be used to identify similar characteristics of these four order types, such as in the following arrangement:
Trend Line Break Out Entry
One often thinks of a breakout trade as a horizontal moving price channel and horizontal stop orders above and below the channel watiing for a breakout in either direction.
However, a more frequent use of the trend line entry is a break in a significant trend. Of course the word significant is relative, but the point is to find a trend that has been continuing for enough bars that so that once the trend breaks the retracement will be sufficient to generate a profit.
Crude Oil (CLK09)
The above chart shows an upward trend in the Crude Oil futures (CLK09) of approximately 2 dollars. This is not a large move for oil, but a retracement large enough to generate a profit is anticipated when this trend is broken.
A Red Dotted trend line has been drawn below the price trend indicating a Sell Stop order is desired. When this trend line is hit, one contract will be sold short.
Short Position Triggered by Trend Line
Shortly later, in the chart above, the Sell Stop is hit and a short position taken:
Stop loss and profit target trend lines added
As the downward move progresses in the chart below, a Buy Stop (Green Dashed) trend line is added, representing an initial stop loss. A Buy Limit (Green Solid) trend line is added, representing a potential profit target.
Stop loss trend line angeled downwards to follow the trend
In the chart above, the downward trend becomes further established. The Buy Stop (Green Dashed) trend line is angled downwards to create a break even stop loss. It is not known whether this trend line or the profit target will be hit first.
Small retracement hits the Buy Stop trend line, closing out the trade.
As the price action continues, a minor retracement hits the Buy Stop trend line, and the trade is closed out for a small profit of $370.
Copper futures HGK09 was trending downwards and then starts moving sideways.
A potential range trading opportunity is anticipated. A protective stop loss trend line is drawn above and below the new trading range.
Buy and Sell limit order trend lines are added within the trading range, above.
The strategy properties are adjusted to allow multiple trades in a range trading scenario, by setting the Maximum Trades to a large number (99) and setting the MaxLimitReversals to a similar large number (99):
The strategy is turned on and starts trading.
As time progresses, several more range trades occur. Eventually, the price moves higher and triggers the stop loss trend line above the trading range to halt further trading.
Analysis of the strategy performance indicates significant profit from this approach. After subtracting the profit of the first 2 trades ($7,333) which were made on historical bars in setting up the strategy, the net trading profit is $20,000 - $7,333 = $12,666.
The main program is divided into two sections, containing code that must be executed (1) with every tick, and (2) at the end of each bar.
Every Tick Processing Region
This section must be executed with each tick, and accomplishes the following:
Method ProcessPositionChange Components
Determining which order has just executed is more complicated than one would think. When a limit price is hit, there is no guarantee that the limit order will be executed. Similarly, if the stop orders are being forwarded to the Tradestation server, the price hitting the stop price is still not sufficient to determine if the stop order executed because the Order Entry Preferences for stop triggering set by the user are not known by the strategy.
Method OrderExecuted determines which order just executed by comparing the last tick price to the various active order values. The order closest to the last tick price is assumed to be the order that triggered the change in position. This works well for limit and stop orers. Market orders, when the stategy is required to make them, are assume to execute immediately. Therefore the order "that just executed", contained in variable ID_Order, is hard coded when a market order is issed.
There is a well documented problem with loss of syncronization of real postiion with strategy position when stop orders attempt to reverse an existing position.
My monitoring the current MarketPosition and identifying the most recent order that executed, one can determine if a desired reversal of position has actually been accomplished.
There are two solutions to ensuring orders to reverse a position using a stop order are completed successfully.
The first solution is to use code, and this is the purpose of Method StopReversalCompletion. If a reversal of position was intended, then variable Reversal will be true. If the position changes from either short or long to flat position, then the reversal has not been completed. In this case, Method StopReversalCompletion will isuse the appropriate market order to complete the reversal.
The second method is accomplished by setting strategy properties as follows:Format - All Strategies - Automation Tab
If the above strategy formatting settings are used, then Method StopReversalCompletion nevers needs to be called. This second method is the recommended method, and it is assumed the user will use these settings. For this reason, the call to Method StopReversalCompletion has been commented out in the main program.
If the user does NOT wish to use these Format - All Strategies settings, then the call to the method should be uncommented in the main program.
Method SetStrategyLogic is responsible for enforcing the following trading rules:
End Of Bar Processing Region
End of bar processing includes the following tasks:
The method used to calculate the trend line value varies depending upon whether the calculation is being done at the end of a bar or intrabar.
[Buy/Sell] next bar at 'value' [Limit/Stop]
Therefore, the next "tick" after the end of bar will be the next bar.
This method generates all of the orders implied by all active trend lines the user has drawn.
Debugging statements are dispersed throughout the code and generate a log of all orders placed if the user has set the strategy formatting option Debugging = true. This log may be examined using the EasyLanguage Output Bar.
Trend Line Alerts
To prepare for using this trend line strategy system, the trend line Properties default values are set as follows:
The default color is set to a bright color (cyan) and solid line style so it can be easily seen on the chart. The default trend line should not be one of the color - style combinations associated with one of the four order types described above. This is to ensure a trend line drawn for purposes of analyzing the chart is not mistaken for a strategy trade order.
The default color (cyan) trend lines may be used by the user to generate alerts about potential trades without triggering the trade order to be generated. This is useful to alert the user to potential trades where the price action has not developed fully enough for the trade order to be formulated.
The trend line default properties for Alerts are set as follows:
Global message preferences are then configured as follows:
Continuous loud audio alerts allows the trader to step away from the computer while the strategy runs. Visual alert windows will be seen if the computer volume is temporarily turned down, or an audible alert has been manually silenced.
When using trend line trading with strategies, many trend lines will be drawn. For convenience, the Toolbar at the top of the Chart workspace can be customized to include a Draw Trend Line icon (pencil icon in the lower right):
This trend line drawing tool speeds up the process of drawing multiple trend lines. The default color is set to a Color and Style combination other than one of those chosen for the four main order types, to avoid inadvertently triggering orders when a "trial" trend line is being placed.
Once the trend line is in position, the Color and Style of the trend line is changed to that associated with desired order type, as noted in the above table. If the trader prefers a different Color and Style association between the various order types, these can be re-defined in the input variables of the strategy.
If a trader wants only an alert and does not wish to place a trade order then the default (Cyan - Solid Line) trend line is used to trigger the alert. If a trade execution is desired, then the trend line drawn is immediately reformatted to the Color and Style appropriate for the desired order type.
Format Strategy Properties
Several user defined input variables to the TL_Trader strategy determine which orders are possible and therefore generated.
RTOnly (Real-time only): If False, trading may occur on historical and real-time bars. If True, trading only may occur on real-time bars.
SetStrategyPosition: Sets the number of contracts (shares) of any real positions prior to starting the strategy.
TradeSize: Number of contracts (shares) for each trade.
PriceRef: The price used to trigger stop orders. Note, with IOG = true, the most recently traded price is always equal to "close". In contrast, with IOG = false, close will be the actual closing price of the bar and trades will not be triggered until the last tick of the current bar.
TradeDirection: = 0 if trades may occur in either direction, = 1 if only long trades are permitted, and -1 if only short trades are permitted.
MaximumTrades: The maximum number of trades the strategy can make before becoming inactive.
MaxLimitReversals: The number of times a limit order may reverse the current position. If a limit order is being used as a profit target to close a position then set = 0. If a limit order is being used to reverse the current position when hit, then set a value > 0. If range trading back and forth between two limit orders, then set some high value to allow multiple reversals of position.
MaxStopReversals: The number of times a stop order may reverse the current position.
ReCalcSeconds: The number of elapsed seconds before the strategy will check to see if the user has moved or deleted any of the established trend lines. If a trend is moved by the user, this will be the number of seconds that will elapse before the new order price is calculated based on the trend line's new position.
Debug: If true, a log of all orders generated is printed in the EasyLanguage Print Log.
UseKillColor: Once a limit order is "hit", it usually deactivated from further use, depending on the settings of MaximumLimitReversals. Each stop order that is "hit" during the strategy is also deactivated. When a trend line is deactivated, it is set to color = KillColor if UseKillColor = true.
This is to give the user a visual confirmation that the order associated with a trend line has been executed and become inactive. It also reminds the user that if this trend line is moved to a new position, it remains inactive until its color and style has been changed back to one of the combinations that indicates a BuyLimit, SellLimit, BuyStop or SellStop order, and the strategy is refreshed with Ctl-R.
KillColor (default white): A trend line that is deactivated during the running of the strategy is changed to color = KillColor if UseKillColor = True.
Strategy Automation settings
Recommended Automation formatting settings are shown above.
Strategy Properties for All Strategies
Recommended formatting options under Strategy Properties for All Strategies, under the Automation tab, are shown below. The stop order selections are required for the strategy to perform position reversals during real time data.
Strategy Properties for All Strategies
The following procedure is recommended when using this strategy:
Initial posted version: 04/24/09
All Routines Bundled: TL_Trader.zip
Included *.ELD files are compiled for TS 9.1