OPEN-SOURCE SCRIPT

Strategy Template - V2

Aktualisiert
This is an educational script created to demonstrate few basic building blocks of a trend based strategy and how to achieve different entry and exit types. My initial intention was to create a comprehensive strategy template which covers all the aspects of strategy. But, ended up creating fully fledged strategy based on trend following.

This is an enhancement on Strategy-Template But this script is comparitively more complex. Hence I decided to create new version instead of updating the existing one.

Lets dive deep.

SIMPLE COMPONENTS OF TREND FOLLOWING STRATEGY

TREND BIAS - This defines the direction of trend. Idea is not to trade against the trend direction. If the bias is bullish, look for long opportunities and if bias is bearish, look for short opportunities. Stay out of the market when the bias is neutral.

Often, trend bias is determined based on longer timeframe conditions. Example - 200 Moving Average, Higher timeframe moving averages, Higher timeframe high-lows etc. can be used for determining the trend bias.

In this script, I am using Weekly donchian channels combined with daily donchian channels to define trend bias.

Long Bias - 40 Day donchian channel sits completely in upper portion of 40 Week dochnial channel.
Short Bias - 40 Day donchian channel sits completely in lower portion of 40 Week donchian channel.

ENTRY CONDITION - Entry signals are generated only in the direction of bias. Hence, when in LongBias, we only get Long signals and when in short bias, we only get short signals.
In our case, when in Long Bias - if price hits 40 day high for the first time, this creates our long entry signal. Similarly when in Short Bias, price hitting 40 day low will create signal for going short. Since we do not take trades opposite to trend, no entry conditions are formed when price hits 40 day high in Short Bias or 40 day low in Long Bias.

EXIT CONDITION - Exit conditions are formed when we get signals of trend failure.
In our case, when in long trade, price hitting 40 day low creates exit signal. Similarly when in short trade price hitting 40 day high creates exit signal for short trade.


DIFFERENT TYPES OF ENTRY AND EXIT
In this script, I have tried to demonstrate different entry and exit types.

Entry types
  • Market - Enter immediately when entry signal is received. That is, in this case when price crossover over high in long bias and crosses under low in short bias
  • Stop - This method includes estimating at what level new highs are made and creating a stop buy order at that level. This way, we do not miss if the break out is stronger. But, susciptible to fail during fakeouts.
  • Limit - This method includes executing a limit order to buy at lower price or sell at higher price. In trend following methods, downside of limit order is when there is genuine breakout, these limit orders may not hit and during trend failures the limit orders are likely to hit and go straight to stop.
  • Stop-Limit - this is same as stop order but will also place a limit condition to avoid buying on overextended breakout or with lots of slippage.


Exit types
  • Market - whether to keep the existing trade running or whether to close it is determined after close of each bar and exit orders are executed manually upon receiving exit signal.
  • Stop - We place stop loss orders beforehand when there is a trade in place. This can help in avoiding big movements against trade within bar. But, this may also stop on false signals or fakeouts.


Take profit
  • Stop - No take profits are configured.
  • Target - 30% of the positions are closed when take profit levels are hit. Take profit levels are defined by risk reward.



USING THE CODE AS TEMPLATE
As mentioned earlier, I intended to create a fully fledged strategy template. But, ended up creating a fully fledged stratgy. However, you can take some part of this code and use it to start your own strategy. Will explain what all things can be adopted without worrying about the strategy implementation within

  • Strategy definition : This can be copied as is and just change the title of strategy. This defines some of the commonly used parameters of strategy which can help with close to realistic backtesting results for your coded strategy and comparison with buy and hold.
  • Generic Strategy Parameters: The parameter which defines controlling alllowed trade direction and trading window are present here. This again can be copied as is and variable inDateRange can be directly used in entry conditions.
  • Generic Methods: f_getMovingAverage and f_secureSecurity are handy and can be used as is. atr method provideded by pine gives you ATR based on RMA. If you want SMA or any other moving average based ATR, you can use the method f_getCustomAtr
  • Trade Statements: This section has all types of trading instructions which includes market/stop/limit/stop-limit type of entries and exits and take profit statements. You can adopt the type of entry you are interested in and change when condition to suit your strategy.
  • Trade conditions and levels: This section is required. But, cannot be copied. All the trade logic goes here which also sets parameters which are used in when of Trade Statements.


Hope this helps.
Versionshinweise
Removed redundant oca_name and oca_type for market orders.
Versionshinweise
Well, I received a review comment stating using if blocks for trades instead of when makes it more readable. While, I personally do not like using if blocks - I agree on the readability part. Hence, converted trade statements to purely if block based from when. Also have kept older when based syntax below in the commented section. Feel free to use whichever appeals more to you.
Versionshinweise
Convert to pine 5
Versionshinweise
Removed margin conditions as they falsely produce margin call even with pyramiding set to 1.
Average True Range (ATR)Donchian Channels (DC)educationalstrategytemplateTrend Analysistrendfollowing

Open-source Skript

Ganz im Sinne von TradingView hat dieser Autor sein/ihr Script als Open-Source veröffentlicht. Auf diese Weise können nun das Script auch andere Trader verstehen und prüfen. Vielen Dank an den Autor! Sie können das Script kostenlos verwenden. Die Nutzung dieses Codes in einer Veröffentlichung wird in unseren Hausregeln reguliert. Sie können es als Favoriten auswählen, um es in einem Chart zu verwenden.

Möchten Sie dieses Skript auf einem Chart verwenden?

Haftungsausschluss