Ranged Volume DCA Strategy - R3c0nTraderUpdate: Republishing this as Public Open-Source script.
Credits:
Thank you "EvoCrypto" for granting me permission to use "Ranged Volume" to create this strategy.
Thank you "junyou0424" for granting me permission to use "DCA Bot with SuperTrend Emulator" which I used for adding bot inputs, calculations, and strategy
What does this do?
This script is mainly used for backtesting a Ranged Volume strategy to see how a 3Commas bot would perform.
I created this script out of necessity and I wanted a way to test a 3Commas DCA bot with a strategy based on “Volume.”
I came across "EvoCrypto’s" "Ranged Volume" study and strategy in TradingView and I liked it. I wanted to configure it so it can be used for DCA bot backtesting. I used parts from "junyou0424’s" "DCA Bot with SuperTrend Emulator" to add the following:
1. The Start Time and End Time
2. Price deviation to open safety orders (%)
3. Target Take Profit (%)
4. Trailing deviation
5. Base Order and Safety Order
6. Safety order volume scale
7. Safety order step scale
8. Max safety orders
In addition to the above, I also added chart indicators for "Take Profit" as well as "Safety Order"
Pre-requisites:
You can use this script without a 3Commas account and see how 3Commas DCA Bot and Ranged Volume strategy would perform vs. a non-DCA strategy. However, I highly recommend signing up for their free account and going through their training. This would give you a base understanding on the settings you will see in this strategy and why you will need to know them.
That said these are the pre-requisites I suggest you have:
1. Base Knowledge of 3Commas DCA bots
2. Base knowledge of settings such as “Max safety trades count”, “safety order volume scale” and “safety order step scale”. If these are alien to you, I suggest you read up on these.
3. Knowledge of setting up a Single-pair 3Commas bot for receiving custom TradingView signal.
4. A paper-bot to test your ideas. (Do not use a real money bot until you have tested it sufficiently with a paper-bot. You alone are responsible for your results!)
5. Add the study I created called "R3c0nTrader’s Ranged Volume Study” which adds a separate chart in its own pane showing the volume spikes. It will also generate the “buy” signals for your bot. NOTE: The study also has the same color scheme as this strategy and having the colors in both the strategy and the study will make things easier to see. If you use EvoCrypto’s Ranged Volume Study instead, just keep in mind that the colors won’t match, and you will have to manually match them.
6. Make your buy signals from your strategy are the same as in your study! To do this, use the same “Volume Range Length” you entered in the STRATEGY and enter that value for the “Volume Range Length” in the STUDY. Also ensure you have the same settings for “Heikin Ashi” (On or Off).
Comparisons of Ranged Volume Strategy vs Ranged Volume DCA Strategy
BTCUSD
Beware of Strategies that claim super high profits. This can easily be done by lowering the initial capital to something unrealistic. If I did that with this strategy and set the initial capital $100 and base order size to $100, I get a net profit of 2,864% which is not realistic.
How to Use
1. On the “Inputs” tab:
a. Set your Start and End Time to backtest against.
b. Set your “Volume Range Length” (number of bars to look back)
c. “Heikin Ashi Colors” – Usually I leave this enabled
d. “Show Bar Colors” – Leave enabled
e. “Show Break-Out” – Leave enabled
f. “Show Range” – Leave enabled
g. Set your other inputs which are those settings you would find in your 3Commas bot that you want to test (e.g., Price deviation to open safety orders, Target Take Profit, Base order, Safety order, etc.).
h. Quick Example for BTCUSD on 2hr chart:
i. Price deviation to open safety orders (%) = 6
ii. Target Take Profit (%) = 14
iii. Trailing deviation = 0
iv. Base order = 100
v. Safety order = 200
vi. Safety order volume scale = 2
vii. Safety order step scale = 1.4
viii. Max safety order = 5
2. On the “Properties” tab, set your initial capital, base currency, etc.
a. Initial capital – Default is 10,000 (Please use realistic values here. The amount here should be able to cover ALL your safety orders if they were triggered. Ideally, you should have funds left over and not use all trade capital.)
b. Base currency – Select your currency
c. Order Size - Not used. Use the “Inputs” tab to change your base order size.
d. Leave “Pyramiding” set to 999. This acts as a ceiling to the “Max safety orders” on the “Inputs” tab. It must always be higher than your “Max safety orders.” For example, if you set your “Max safety orders” to “4” and “Pyramiding” to “4” then it effectively means you have “3” “Max safety orders” and not “4” because it is counting each successive entry including the initial order.
e. “Commission” - Optional
f. “Verify price for limit orders” – Leave at zero. This does not change anything that I can tell.
g. Optional - Enter a value for “Commission”
h. Slippage – Optional. Slippage does not occur in backtesting but does occur in real trading but it can be simulated. Example use case for tracking performance of a real money bot: You enter the start date and time of your bot’s trade into this strategy and you notice some values are a little off due to slippage (average price, take profit, safety orders are not lining up) then you would go back here and increase the slippage until those lines up close enough with your actuals.
i. Margin for long positions – I don’t use this honestly.
j. Margin for short positions – I don’t use this honestly.
k. Recalculate “After order is filled” and “On every tick” – I don’t use this honestly.
3. “Style” tab
a. Ranged Volume Bar Coloring - You must disable bar coloring in any studies you added or this may not work properly
i. Color 0 – Default Yellow; appears when a volume breakout occurs
ii. Color 1 – Default Red; appears when a volume breakdown occurs
iii. Color 2 – Light Blue; appears when Close is higher than the Open
iv. Color 3 – Dark Blue; appears when the Close is lower than the Open
b. Take profit – Default Green; take profit line
c. Safety order – Default Light Blue; safety order line
d. No Safety Orders left – Default Red; when a trade runs out of safety orders, the line turns red and there is no safety orders left underneath to catch any further falling price movements.
e. Avg Position Price – Default Orange; your average position price for any given trade.
f. Take Profit Plot Area – Default Green; creates a highlighted area for your take profit
g. SO Plot Area – Default Light Blue; creates a highlighted area for your safety orders
h. Trades on chart – Show or hide your trades on the chart
i. Signal labels – Show or hide the trade signal labels on the chart
j. Quantity – Show or hide the trade quantity on the chart
Explanation of Chart lines and colors on chart
Educational
Ultimate Strategy Shell [ArtK]This strategy shell script accepts entry/exit signals from an external study indicator.
It is built to cover most common trade execution strategies such as, multiple take profit levels, break even, trailing stop loss, position reverse, laddering and more.
It also aims to provide extended trade statistics such as the actual (win/loss) figures for trades instead of figures for orders as TradingView provides in the Strategy Test Overview.
Features
- 3 Take Profit levels.
- 3 Take Profit target type options (Percentage, Risk Reward Ratio or (IN DEVELOP) Strategy).
- 2 Stop Loss type options (Percentage, Strategy).
- Break Even stoop loss (will move the Stop Loss to the entry price after the 1st or 2nd Take Profit).
- Trailing Stop Loss (will move the Stop Loss after the last Take Profit at specified deviation on every candle).
- Trades Summary Label
Shows the number of wins and losses in a row.
Shows the actual (win/loss) figures for trades instead of figures for orders as TradingView provides in the Strategy Test Overview.
Shows the period from the first trade until the last trade.
Shows how many times each Take Profit level was reached (IN DEVELOP).
(IN DEVELOP) Shows the maximum Stop Loss when using the Stop Loss – Strategy option (helpful when estimating Stop Losses when leveraging).
Plots marks at the bottom of the chart to indicate winning or losing trades (helps to quickly find losing trades for example).
- Entry Filters
-- Date Time, allows placing trades only during the specified period.
-- ADX, filters trades below specified ADX value.
-- Max Stop Loss, can be enabled when the Stop Loss type is set to "Strategy". Used to prevent taking trades which exceed liquidation price.
-- Direction, will filter trades in a certain direction.
Instruction
- The strategy script relies on an external indicator therefore it is required to add the signal indicator first.
- To adapt the signal indicator to be compatible it must have only one plot.
-- The default value of the plot should be 1 when there is no buy/sell signal.
-- When the signal indicator signals BUY the line should plot the value
-- When the signal indicator signals SELL the line should plot the value
-- (I am aiming to support EXIT signals as well as the Stop Loss and Take Profit percentages in the near future)
- The first time you load the script it will show an error "Study Error: Signal source set to default ". This means the signal indicator was not selected.
The signal indicator should be selected in the strategy configuration panel option "Signal Source"
bollinger_Banknifty_CE_PEIt is more suitable for day trading with a 15 min chart. It is more profitable in Banknifty option only. It is based on multiple Bollinger Band and RSI .
The label with Buy+1 and Buy-1 represents more profitable entry positions. The label Buy+1 and Buy-1 stands for entry positions/signals of option "CE" and option "PE" buy at ATM price and backtest results are based on last year's data with one lot .
The Blue dots indicates trailing stop loss of "CE" position and green dots indicates trailing stop loss of "PE" position.
It has an initial capital of 100000 and the size of the lot is 1. The target is 0.8% , stop-loss is 0.35% and trailing stop loss is 0.3% with close candle.
The commission paid is 20 cash per trade and the slippage is 5 ticks per trade. Some of the Indian broker's commission is only 10 cash per trade. Adjust the commission as per your broker.
Trades are conducted based on the intraday time in India set from 9.45 am to 3.0 pm. All positions will get square off at 3.15 pm.
It will execute a maximum of 2 trades per day. All other parameters are suitable for Algo trading with Indian stock brokers.
Banknifty option buy CE & PEIt is more suitable for day trading with a 15 min chart. It is more profitable in option only. It is based on multiple Supertrend, moving average, and .The label with Buy+1 and Buy-1 represents more profitable entry positions. The label Buy+1 and Buy-1 stands for entry positions/signals of option "CE" and option "PE" buy at ATM price and backtest results are based on last year's data with one lot .The Blue dots indicates trailing stop loss of "CE" position and green dots indicates trailing stop loss of "PE" position.It has an initial capital of 100000 and the size of the lot is 1. The target is 0.8% , stop-loss is 0.35% and trailing stop loss is 0.3% with close candle.The commission paid is 20 cash per trade and the slippage is 5 ticks per trade. Some of the Indian broker's commission is only 10 cash per trade. Adjust the commission as per your broker.Trades are conducted based on the intraday time in India set from 9.45 am to 3.0 pm. All positions will get square off at 3.15 pm.It will execute a maximum of 2 trades per day. All other parameters are suitable for Algo trading with Indian stock brokers.
TradeIQ Darvas Box BacktestThis script has been made to backtest the strategy explained in this video link:
www.youtube.com
Publicly available scripts explained in the video were copy pasted and therefore merged into one single script. Open and short entries were made according to the rules of the video.
MA cross strategyI created an sma (10/30) strategy.
The script is under construction and can be changed, since i'm looking for a more profitable strategy.
If you have ideas to make it more profitable, please comment.
It is possible to change everything to your own needs.
MilleMachineHello traders,
I hereby present to you the second stage of my journey to finding a reliable, profitable trading strategy.
The "Millemachine" is based on the "Millebot", my previous published strategy. This means the backbone of the strategy is still the same: a trend following system. Instead of using a fixed TP and SL, a trailing stoploss is now used. To limit the losses when the trend weakens, the trailing stoploss automatically gets smaller, as it is based on the ATR.
A new utility is you can now easily switch between indicators on which the decision making is based. This allows the user to discover which indicators work best for entry, long/short switching and stoploss configuration.
The strategy has been proven to be very profitable in trending markets, but can suffer losses during ranging market. To make the system more robust, the strategy cannot solely rely on a trending system. Other systems must be added.
I believe that a good trading bot must consist of more than 4 different strategies, based on different systems. This is what I am currently working on.
My goal for publishing this strategy is to help other traders build their own. In my journey I found it difficult to find a good strategy that employs a decent risk management, which is truly essential for having good, consistent results. Also, a realistic commission needs to be defined to have a realistic performance prediction. This weighs on the profitability and therefore is often set at 0 by authors of other strategies, which I find misleading.
If you have found this strategy informative or useful, please leave a comment.
Greetings Michael
Follow The Ranging HullThis is a scalping strategy, trying to make quick points based on momentum and trend trading.
Entry Points are when either the range filter or the the following line changes colour. And the Hull is in that same direction.
--The Strategy Only enters on range filter entry point for now.
This Strategy has been tested on the NASDAQ 1 min, And works best with low timeframes.
Set the IsStrategy on the settings to true, to activate the strategy.
Make sure the Dates are correct .
Credits:
Hull Suite by InSilico www.tradingview.com
Range Filter Buy and Sell 5 min www.tradingview.com
Follow Line Indicator by Dreadblitz www.tradingview.com
CoinFlip Indicator + StrategyFlip a coin every Monday.
Heads, go long. Tail, go short. Stoploss at 1 ATR, and Take profit at 1 ATR too. 1:1 risk to reward ratio.
After backtesting 2018, 2019, and 2020 with 28 major currency pairs. We are getting close to a 50% win rate with an 8% standard deviation.
Believe it or not, this simple performs better than lots of the popular indicators out there.
Don't believe me? Test it out yourself!!
Use this as a baseline for your backtest and expose all your other crappy indicators :)
HOW TO USE:
As an indicator:
1. Use a daily chart
2. Green arrow below chart, go long, set a stop-loss at 1 x ATR, and take profit at 1 x ATR
3. Red arrow above chart, go short, set a stop-loss at 1 x ATR, and take profit at 1 x ATR
As an indicator:
1. In setting, set a year to test (default to 2020)
2. Go to the strategy tester and observe the stats
P.s. You can also set the period of the ATR to another value other than 14 periods.
TTP Grid BacktesterThis pine script strategy allows to backtest Grid bots.
This initial version offers the following features:
- Set the top and bottom limits of the grid
- Plots the average position price, realised and unrealised profits
- Set the value to invest
- This script is a strategy so you can check each individual buy/sell, stats and all included with strategies
What does it do:
- Depending where is located the initial close price relative to the grid (above, below, inside) it will buy for as many levels are above the price.
- It will disable a level that recently filled an order (in the way grids bot do)
- When the grid starts it will disable the closest grid level
- It places limit orders in the active levels and many levels can be filled in a single candle
- You can activate recalculate on each order filled, which will allow to fill further needed orders if the price swings up and down crossing multiple times multiple grid levels but I have found that doing this can compromise the accuracy of the price used on those levels (there are minor gaps between the filled price and the original level price)
How to use it:
- When you add this strategy to the chart you will be asked to select the top and bottom limits of the grid
- Notice you can always select the strategy in the chart and drag and drop the limits to adjust the grid
- Once the grid is in place, you can use either lower chart timeframes for higher accuracy of the stats, or higher timeframes if you want to privilege longer periods of testing
How to set the correct "initial capital"
In order to prevent getting wrong stats you need to make sure you are using the correct initial capital. If you put less than what you are actually using your results will be over inflated. If you set an initial capital below what the bot requires, your results will be smaller than they should.
- If you want to use exactly 100% of the capital for the grid use then first select what amount per level you want to use. Set this value in the settings of the indicator (if you are trading BTCUSD pair, how much BTC you want to use per level, 0.01 for example).
- Once you have set this value, then open the TradingView "Data Window" to be able to visualise the calculation of cash required to run the grid that the strategy is giving you. In our example with BTCUSD this value will be given in USD.
- Enter this amount in the "Properties" tab, "Initial Capital". If you enter the exact amount you will be using all for the grid usage.
- The grid first action will be to buy 0.01 for each level that is above the current price in the first candle of the chart. If there are no levels above it won't do any initial investment.
- The rest of the cash will be use to buy levels below if the price goes to the lower range of the grid later
Intention of this script
I built this script to help me understand better how grid bots work.
Understanding the flow of realised vs unrealised profits in a grid can help me understand why sometimes even if you are in red on unrealised profits, you can still compensate with realised profits and many other tricky scenarios with grids.
Sometimes I'm running a grid bot and would like to simulate how much better (or worst) it would have been to run it using different limits.
Future work and ideas
Initially I'm focusing on confirming that the grid behaves correctly and that the stats are as accurate as possible.
That is the first priority.
Once I feel more confident with the accuracy I will consider adding some of the following ideas (not in any particular order):
- Table with stats including: price of each level, times the level filled an order, times it was use for selling/buying, etc. Time it took to become in realised profit. Comparison against profits from buy & hold.
- Trailing TP/SL
- Entry/exit price
- Trading time window: only trade between the specified dates/times
- Alerts
Accurate BUY & SELL 5 mins TF by RRAlways trade using 5 mins Time frame of chart.
For Buy entry always buy 1 point above the candle closing price & SL would be previous candle low or 30 points.
For Sell Entry Always Sell 1 point below the candle opening price & SL would be previous candle high or 30 points.
Do not take trades using 3 mins Time frame, as there is lot of noise. It works best with 5 mins Time frame.
I have adjusted/set according my trading pattern, if needed use the settings options to set accordingly .
Removed range highlighter to keep the chart simple.
Original Version credits to ZacVaughn
Actual Version i just set alerts and change the parameters for Crude OIL 5min Chart.
NO REPAINT.
Wait For Barclose
The strategy example. Close position by timeoutThis is an example how to close open entries by timeout for educational purpose.
multiple orders - strategy - educationalHi,
Here is a 'template', using array's, for multiple orders and different SL/TP levels per trade (This is an example with max 5 open trades)
The 'switch' makes sure that the first available position will be used,
for example, when 'L1' is closed in the past, and a buy condition is triggered, position 'L1' will be filled,
should it be that 'L1', 'L2', 'L3' are already filled, then position 'L4' will be filled, ...
An extra table is added with data of the trades
Be aware, the 'Buy and Hold' resembles the profit when 100% of the available equity has been bought at the time of the very first trade and sold now. On the other hand, the positions work with a % of equity, 20% per trade (5 x 20 = 100%)
You can see that every trade exits on its own terms, without interference of other trades
Important, this technique only works if in the strategy() function:
- close_entries_rule -> set at 'ANY'
- pyramiding is set at max amount of trades or higher (in this case 5 or higher)
Cheers!
Range Filter - B&S Signals - 001 - edited I have not description. Publishing so a freind can use it.
TPS - FX TradeI based my strategy on the Lagging Span 2 line in the Ichimoku Cloud. I actually designed the strategy for the DAX Germany index 3 Minutes period, but you can use it on any instrument you want. I would like to point out some points that you should pay attention to when optimizing the strategy for the instrument you want to use.
Position Take Profit and Stop Loss levels are tick calculations. These values will differ for each instrument. If you are trading in Forex, the values you will write here should be starting from the numbers after the comma in the instrument value. For example, if you want to take profit at "200" points in DAX, you must write "20000" in the Long or Short Take Profit Score field, this applies to the Stop Loss Points, but if you want to take profit or stop loss at 200 points in UKOIL, you must write "200" in the entry part.
Overnight Gap AnalysisThere is a wide range of opinion on holding positions overnight due to gap risk. So, out of curiosity, I coded this analysis as a strategy to see what the result of only holding a position overnight on an asset would be. The results really surprised me. The script backtests 10+ years, and here are the findings:
Holding a position for 1 hour bar overnight on QQQ since January 2010 results in a 545% return. QQQ's entire return holding through the same period is 643%
The max equity drawdown on holding that position overnight is lower then the buy/hold drawdown on the underlying asset.
It doesn't matter if the last bar of the day is green or red, the results are similar.
It doesn't matter if it is a bull or bear market. Filtering the script to only trade when the price is above the 200-day moving average actually reduces its return from 545% to 301%, though it does also reduce drawdown.
I see similar patterns when applying the script to other index ETFs. Applying it to leveraged index ETFs can end up beating buy/hold of the underlying index.
Since this script holds through the 1st bar of the day, this could also speak to a day-opening price pattern
The default inputs are for the script to be applied to 1 hour charts only that have 7 bars on the chart per day. You can apply it to other chart types, but must follow the instructions below for it to work properly.
What the script is doing :
This script is buying the close of the last bar of the day and closing the trade at the close of the next bar. So, all trades are being held for 1 bar. By default, the script is setup for use on a 1hr chart that has 7 bars per day. If you try to apply it to a different timeframe, you will need to adjust the count of the last bar of the day with the script input. I.e. There are 7 bars per day on an hour chart on US Stocks/ETFs, so the input is set to 7 by default.
Other ways this script can be used :
This script can also test the result of holding a position over any 1 bar in the day using that same input. For instance, on an hour chart you can input 6 on the script input, and it will model buying the close of the 6th bar of the day while selling on the close of the next bar. I used this out of curiosity to model what only holding the last bar of the day would result in. On average, you lose money on the last bar every day.
The irony here is that the root cause of this last bar of the day losing may be people selling their positions at the end of day so that they aren't exposed to overnight gap risk.
Disclaimer: This is not financial advice. Open-source scripts I publish in the community are largely meant to spark ideas that can be used as building blocks for part of a more robust trade management strategy. If you would like to implement a version of any script, I would recommend making significant additions/modifications to the strategy & risk management functions. If you don’t know how to program in Pine, then hire a Pine-coder. We can help!
Co-relation and St-deviation Strategy - BNB/USDT 15minThis indicator based on statistical analysis. it uses standard deviation and its co-relation to price action to generate signals. and following indicators has been used to calculate standard deviation and its co-relation values. finally it is capable to identify market changes in bottoms to pic most suitable points.
1. Parabolic SAR (parabolic stop and reverse)
2. Supertrend
3. Relative strength index (RSI)
4. Money flow index (MFI)
5. Balance of Power
6. Chande Momentum Oscillator
7. Center of Gravity (COG)
8. Directional Movement Index (DMI)
9. Stochastic
10. Symmetrically weighted moving average with fixed length
11. True strength index (TSI)
12. Williams %R
13. Accumulation/distribution index
14. Intraday Intensity Index
15. Negative Volume Index
16. Positive Volume Index
17. On Balance Volume
18. Price-Volume Trend
19. True range
20. Volume-weighted average price
21. Williams Accumulation/Distribution
22. Williams Variable Accumulation/Distribution
23. Simple Moving Average
24. Exponential Moving Average
25. CCI (commodity channel index)
26. Chop Zone
27. Ease of Movement
28. Detrended Price Oscillator
29. Advance Decline Line
30. Bull Bear Power
Santanu StrategyThis script use for crypto market, its use ema and supertrend to find the current trend in the market
STR:EMA Oscilator [Azzrael]Strategy based on EMA and EMA Oscilator
(EMA - close) + Std Dev + Factor = detecting oversell/overbuy
Long only!
Pyramiding - sometimes, depends on ...
There're 2 enter strategies in one script:
1 - Classic, buy on entering to OverSell zone (more profitable ~> 70%)
2 - Crazy, buy on entering to OverBuy zone (catching trend and pyramiding, more net profit)
Exit - crossing zero of (EMA - close)
Buy Monday, Exit Tuesday with Stop Loss and Take ProfitStrategy to go long at end of Monday before market closes and exit before Tuesday close, or at stop loss or take profit percentages
This runs strategy on entering by weekday name and also by session time.
Implemented are also Take Profit and Stop Loss to exit position using custom inputs.
Added stoploss and take profit plot lines
Combining Trailing Stop and Stop loss (% of instrument price)Both a trailing stop and a stop loss are necessary tools for every trader, for locking in as much profit in any given trade, while on the other hand minimizing the risks involved in trading.
I started to write this scipt to give an answer to many traders who wanted these two tools combined, but didn't find any way to program this.
TV has some shortcomings in the built-in functions regarding this topic. You can use 'stop' and 'limit', or 'loss' and 'profit' and even functions with trailing stops. But all of these lack the flexibility of the use of percentages.
I used many ideas of the community, and with this scrip I want to give back to the community.
The strategy is just a simple crossing of two Exponential Moving Averages, so do not start trading based solely on this script.
Also keep in mind that no two assets are the same, and adjustments should be made in the configuration for every asset.
This script should be viewed as a template, just take out the chunks of code you need. A savvy programmer can undoubtedly implement a 'take profit' of 50% halfway down the trade.
The features are:
-Everything is easily adjustable through the configuration section
-2 EMA's which form the strategy to go Long or Short
-Trailing stop, which adjust itself every bar according to the configuration
-Stop loss, which uses the entry price of the trade and stays at the same level according to the configuration
-The chart provides a visual reference for the levels of both stops
Happy trading!
Strategy Template - V2This 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.
CRYPTO 3EMA Strategy with Take Profit & Stop Loss based on ATRSimple 3 EMA Strategy with plotted Take Profit and Stop Loss
Entry condition:
- Middle EMA cross above the Slow EMA
- Set take profit and stop loss exit conditions based on ATR Indicator
Exit condition:
- Fast EMA cross below the Middle EMA