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!
Educational
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
CryptOli 3 MAs long/short Backtest// this is an educational Script - basicly its very simple - you can see how minimal changes impact results, thats why i posted it
// Credits to Quantnomad to publish tons of free educational script
// this Script is based on Quantnomads Ultimate MA Indicator
// HA - Option for calcultion based on HA-Candles (very famous recently)
// Source Input - Option (Candletype for calculation, close, ohlc4 ect.) --- there are huge differences --- try it by your own
BLANK Strategy + TSL + Backtestrange- I often see ppl struggeling do the first own strategy
- this is an example, for a smooth start
- EDIT it to your needs ( DELET my EXAMPELS and add your INPUTS/CONDITIONS)
- i added also a Backtestrange, so you can test your Strategy in different marketphases
- also added a trailing-stop-loss
[Tutorial][RS]Working with ordersa small tutorial to explain how to work with orders, comments in the script.
How To Set Backtest Date RangeExample how to select and set date range window to be backtested. Normally when you change chart period it changes the number of days being backtested which means as you increas the chart period (for example from 5min to 15min) you also increase the number of days traded, so you can not compare apples to apples for which period would yield best returns for your strategy. Now you can. Incorporate this code replacing buy and sell with your strategy, then simply input the From and To dates in Format -> Inputs, and then change the chart period to view updated results.
NOTE: There is a limit in backtesting to 2000 orders, so please be aware of this when setting your date ranges. If you set your range too high, you may be exceeding this limit on some periods and not on others, so this would yield incorrect comparison of returns per period. If you see in your backtesting results that you are nearing this limit for one of your periods you are testing, then reduce the date range to a smaller number of days.
Enjoy!
(Thanks to @Gesundheit "Adeel" for pointing me in the right direction on this!)