[fareid] Quick Backtest Framework█ OVERVIEW
This Framework allows Pine Coders to quickly code Study() based signal/strategy and validate its viability before proceed to code with more advance/complex customized rules for entry, exit, trailstop, risk management etc..
This is somewhat an upgraded version of my earlier personal template with different strategy used, cleaner code
and additional features.
█ USE CASES
- You have an idea for trade signal and need a quick way to verify its potential before writing lengthy/complicated code
- You found a study script for trading signal in public library and want to validate it profitability with minimum effort before including it in your trading playbook
█ FEATURES
- Alert: Ready to use alert function based on signals from your custom indicator.
- Visual Backtest: Auto-plot entry, stop-loss and take profit for simple strategy performance analysis
- Backtest Statistic: Provide basic key metrics based on backtest strategy
- BTE External Signal Protocol: Ready to use code that will supply required state to PineCoders Backtesting & Trading Engine if you wish to have more advance and sophisticated backtesting engine
Notes: All of the above features have On/Off toggle
█ Description & How To Use
This Framework consist of 5 Modules but you only need to edit the first 2 Modules:
Module1: Indicator
Module2: Framework Input Protocol
Module3: Alert
Module4: Backtest
Module5: Backtest & Trading Engine
Tips: The source-code includes collapsible block by module for easy navigating
Module1: Indicator:
-----------------------------------------------------------------------------------
Main Module. Place custom indicator input parameter/calculation/indicator plotting here
Sample Strategy: Double MACD Crossover
MACD Signal: 1st MACD Cross above signal line indicate Buy Signal
1st MACD Cross below signal line indicate Sell Signal
MACD Filter: 2nd MACD is above 0 line indicate Uptrend
2nd MACD is below 0 line indicate Downtrend
Module2: Framework Input Protocol:
-----------------------------------------------------------------------------------
Use this module to connect main indicator/signal calculated in Module1 to the rest of the framework's module
4 variables needed to be defined here:
1. Uptrend
2. Dntrend
3. BuySignal
4. SellSignal
i'm not sure how to place a code snippet here to show you example so in the source code i already put a comment in Module2 on which part u need to edit. I hope its pretty simple to use.
Module3: Alert Module Description:
-----------------------------------------------------------------------------------
As long as the variables in Module2 properly defined, the alert module is ready to use without any further modification.
Input:
Enable Alert --> Enable TV's alert and plot signal to chart
Alert Type --> Set to take Buy only, Sell only or Both alert
Module4: Backtest Module Description:
-----------------------------------------------------------------------------------
As long as the variables in Module2 properly defined, the backtest module is ready to use without any further modification.
Input:
Backtest Stat --> Enable Backtest Statistic Label
Backtest Visual --> Enable Backtest visual simulation
Backtest Type --> Set to take Buy only or Sell only or both
SL Type -->
ATR : Set SL in ATR times Multiplier below entry price
Fixed : Set SL in fixed point below entry point (in 'Dollar'). e.g. for Stocks -> 0.5 equals to 50cent while for EURUSD currency -> 0.005 equal to 50 pips
HiLo Bar: Set SL at highest/lowest wick of previous bar plus/minus Fixed point. e.g. EURUSD HiLo=3 and Fixed Point = 0.0005, buy trade will place SL 5 Pips below lowest of previous 3 bar
SL ATR Multi --> Set Lookback Period used for SL's ATR calculation
SL ATR Multi --> Set ATR Multiplier for SL
SL Fixed --> Set Fixed Level for SL
SL Bar --> Set Number of previous bar to check for SL placement
TP RR Ratio --> Set TP based on RR multiplier. e.g. 2 means TP level will be twice further from entry point compared to Entry-SL distance.
Notes: The point is for preliminary testing, so it only supports 1 trade at a time and no Trailing Stop
Module5: Backtest & Trading Engine Description:
-----------------------------------------------------------------------------------
As long as the variables in Module2 properly defined, the Pinecoders BTE module is ready to use without any further modification.
Input:
External Signal Protocol --> Set ESP State to send to "Backtesting & Trading Engine "
Signal With Filter --> Use this to send entry signal that already filtered by this study indicator (without stoploss level)
Signal Without Filter --> Use this to send raw entry signal that are NOT YET FILTERED by this study indicator (without stoploss level)
Signal and Stop With Filter --> Use this to send entry signal WITH StopLoss that already filtered by this study indicator (with stoploss level)
Signal and Stop Without Filter --> Use this to send raw entry signal WITH StopLoss that are NOT YET FILTERED by this study indicator (with stoploss level)
Notes: Backtesting & Trading Engine already have built-in Filter, Entries and Stop Level. e.g. Unselect all their filter state if only want to use custom filter and make sure send Signal with Filter (with or without SL level)
█ DISCLAIMER:
This framework main objective is to create my personal indicator template so that i just have to modify the indicator module for preliminary testing in future.
The sample strategy included are for educational purpose only. Use at your own risk
credit: LucF/PineCoders for a lot of his scripts that i use as a guide to complete this
股票
MavilimW Strategy MTF EMA with HA CandlesThis is a strategy adapted initially for Mavilim moving average indicator, based on WMA MA.
It seems to works amazingly on long term markets, like stocks, some futures, some comodities and so on.
In this strategy, I form initially the candle, using EMA values, so I take the EMA of last 50 closes, open, highs and lows and form the candle
After this I take interally HA and convert the EMA candle to HA.
Then using the moving averages on multiple timeframes, like in this example we have a chart on 4h, but I use 1h and 1d moving averages.
For long condition we have : close is above moving average timeframe1 and oving average timeframe2 and oving average timeframe3
Initially short would be close below ma timeframe1, ma timeframe2 and timeframe3 -> but here I also convert it into a long signal.
So we actually go only long .
And we have 2 different exits : for first long if we have a crossdown of 1h ma with 1 day ma, and for second long if we have a cross up of 1h ma with 1 day ma in this example.
Message me if you have any questions about this strategy.
Heiken Ashi MTF Strategy- IndicatorHello, this is both a strategy and indicator that revolves around Heikin Ashi candles.
In this case we take 3 different time frames, in this example we use daily , weekly and monthly.
The conditions for entry are :
For long : we check that we have a green daily candle, at the same time we check that the weekly and monthly candles are also green.
For short : We check that all candles, daily, weekly and monthly and red.
For exit of long : as soon as 1 of the 3 candles, daily or weekly or monthly converts to red, we exit.
For exit of short : as soon as 1 of the 3 candles converts to green, we exit.
This strategy- indicator can be adapted to any type of market.
Profit MAX MTF HeatMapThis is a powerfull strategy which is made from combining 3 multi timeframes into one for profit max indicator
In this case we have daily, weekly and montly.
Our long conditions are the next ones :
if we have an uptrend on all 3 at the same time, we go long.
If we have a downtrend on all 3 of them at the same time we go short.
For exit, for long, as soon as one of the 3 converts into downtrend we exit the trade.
For exit, for short, as soon as one of the 3 converts into uptrend we exit the trade.
This tool can be used on all types of markets, and can also be changed the time frames.
MACD With Trend Filter: Visual Backtest Module TemplateSample Strategy: MACD Crossover with trend filter options
MA Filter : Price Close Above MA, Search for Buy, Price Close Below MA, Search for Sell
ADX Filter : Take trade only when ADX is above certain treshold
MACD Signal : MACD Cross above signal line while under 0 line indicate Buy Signal
MACD Cross below signal line while above 0 line indicate Sell Signal
-----------------------------
Using Alert Module:
Enable Alert --> Enable TV's alert and plot signal to chart
Alert Type --> Set to take Buy only, Sell only or Both alert
----------------------------
Using Backtest Module:
Enable Backtest --> Enable Backtest simulation
Backtest Type --> Set to take Buy only, Sell only or Both
SL Type -->
ATR : Set SL in ATR times Multiplier below/above entry price
Fixed : Set SL in fixed point below entry point (in 'Dollar'). e.g. for Stocks -> 0.5 equals to 50cent while for EURUSD currency -> 0.005 equal to 50 pips
HiLo Bar : Set SL at highest/lowest wick of previous bar plus/minus Fixed point. e.g. EURUSD HiLo=3 and Fixed Point = 0.0005, buy trade will place SL 5 Pips below lowest of previous 3 bar
SL ATR Period --> Set Lookback Period used for SL's ATR calculation
SL ATR Multi --> Set ATR Multiplier for SL
SL Fixed --> Set Fixed Level for SL (Use when SL Type is either Fixed or HiLo Bar)
SL Bar --> Set Number of previous bar to check for SL placement
TP RR Ratio --> Set TP based on RR multiplier. e.g. 2 means TP level will be twice further from entry point compared to Entry-SL distance.
Notes: The point is for preliminary testing, so it only supports 1 trade at a time and no Trailing Stop
----------------------------
Disclaimer:
This script main objective is to create my personal indicator template so that i just have to modify the indicator module for preliminary testing in future.
Testing Alert Module so i can re-use it as template in future study/indicator
Testing Visual Backtest Module so i can re-use it as template in future study/indicator
i believe using Strategy function is a better approach for this but the entry/exit level seems to be hit n miss (at least for me, still trying to figure what i did wrong)
also, i rather code the strategy in other platform where i can use the more accurate tick data if i want to validate backtest statistics.
My study scripts was built only to test/visualize an idea to see its viability and if it can be used to optimize existing strategy.
credit: ADX code are originally from "ADX and DI" by @BeikabuOyaji although i re-wrote so i can have cleaner read and use RMA instead of SMA
Monthly Options Expiration 2021Monthly options expiration for the year 2021.
Also you can set a flag X no. of days before the expiration date. I use it at as marker to take off existing positions in expiration week or roll to next expiration date or to place new trades.
Happy new year 2021 in advance and all the best traders.
Swing Reversal IndicatorSwing Reversal Indicator was meant to help identify pivot points on the chart which indicate momentum to buy and sell. The indicator uses 3 main questions to help plot the points:
Criteria
Did price take out yesterday's high or low?
Is today's range bigger than yesterday? (Indicates activity in price)
Is the close in the upper/lower portion of the candle? Thus, indicating momentum in that direction
This indicator was built to help me find pivot points for directional options trading however can be used for equities and forex swing trading and other strategies. Used in conjunction with a BB extreme can provide good setups.
Alerts are available for both the long and the short positions and the indicator will repaint as price moves.
The character Plotted can be changed in the settings
The size of the candle area can be changed as well if you want to tighten/loosen the trigger points based on the third question above.
Trendy Bar Trend Color LiteLite version of the original Trendy Bar Trend Color
This will only color the candlestick body of your chart
Can be used with solid, hollow, renko, or any other chart type
Custom coloring for Highs, Lows, and consolidation is removed
Swing/Daytrading strategy with reversal option
Hello, today I bring a swing reversal strategy that work on all financial markets.
It uses timeframes starting from 1h, the bigger the better.
Its very dangerous because it has no stop loss, neither a take profit. Our exit condition is based on the reversal on the entry .
For entry we have 2 types : normal and reversal
Lets say we want to go long , for that we check the last CLOSE of a candle with the previos HIGH. If its higher than that, and at the same time CLOSE is bigger than the moving average, we have a long entry.
For short we have CLOSE with the previous LOW. If its lower than that and at the same time is lower than moving average, we have a short entry.
For moving average we use T3 MA
For reversal what I do, is , I take the short condition and I apply it to long, and for long I apply the short condition.
On many cases I found out it work amazingly.
I forgot to add: it also has a time entry system, so we use the best hours/sessions for entries .
Exit a trade: lets say we enter short, when we find a long condition, we close short and enter into long. Viceversa for long.
If you have any questions, let me know.
Enjoy it :)
Long only strategy VWAP with BB and Golden Cross EMA50/200
This is strategy, mainly designed for stock markets
It makes uses of the EMA 50/ 200 ( Golden cross) and VWAP and Bollinger bands.
It only takes long positions. It can be adapted to all time frames, but preferably to be used with longer timeframes 1h +
The rules for entry are the next ones :
1. EMA50 > EMA 200
2. if current close > vwap session value
3. check if price dipped BB lower band for any of last 10 candles
EXIT RULE
1. price closes above BB upper
STOP LOSS EXIT
1. As configured --- default is set to 1%
Stock Market Strategy : VWAP, MACD, EMA, Breakout, BBHello there,
Today I bring you a stock market strategy, specialized in NASDAQ stocks.
Its a daytrading strategy, that can only do a max of 1 trade per day. In this case it only trades the first 2 opening hours of the market.
The rules are simple :
We follow the trend based on a big EMA, in this case 200, after that, we check for VWAP direction , then, we check histogram from MACD. This is the simple logic of the strategy.
Inside there is another strategy, that not just do the above, but also uses Bollinger bands, and checks for breakout of bottom or top line. Also it uses Average directional Index, for even a bigger criteria .
So for example a long condition it would be : candle is above the ema, and candle is above vwap, and histogram is positive, and candle break the top bb level and ADI < 40 -> long signal . The opposite works for short(ADI > 20).
In this case all this criterias are between the first 2 hours of market. So we enter between the first hour, and exit in the next hour. For this we need to use very short time frames.
Hope you enjoy it.
Let me know if you have any questions
Ichimoku with MACD/ CMF/ TSI This is a strategy made from ichimoku cloud , together with MACD, Chaiking Money FLOW and True Strenght Index.
It can be adapted to any timeframe and any type of financial markets.
The idea behind its very simple,
We combine the long / short strategy from ichimoku, like cross between lines and below/above cloud together with histogram from MACD for positive/negative level. We use the same criteria for TSI and CMF, to check if its above or below 0 level.
Based on that we have a long or a short entry. The exit happens when the next options triggers, like for example we had long signal, we exit when we receive the short signal and viceversa.
It can be adapted with a risk management to apply a tp/sl level.
For any suggestion or details , let me know.
ETF / Stocks / Crypto - DCA Strategy v1Simple "benchmark" strategy for ETFs, Stocks and Crypto! Super-easy to implement for beginners, a DCA (dollar-cost-averaging) strategy means that you buy a fixed amount of an ETF / Stock / Crypto every several months. For instance, to DCA the S&P 500 (SPY), you could purchase $10,000 USD every 12 months, irrespective of the market price. Assuming the macro-economic conditions of the underlying country remain favourable, DCA strategies will result in capital gains over a period of many years, e.g. 10 years. DCA is the safest strategy that beginners can employ to make money in the markets, and all other types of strategies should be "benchmarked" against DCA; if your strategy cannot outperform DCA, then your strategy is useless.
Recommended Chart Settings:
Asset Class: ETF / Stocks / Crypto
Time Frame: H1 (Hourly) / D1 (Daily) / W1 (Weekly) / M1 (Monthly)
Necessary ETF Macro Conditions:
1. Country must have healthy demographics, good ratio of young > old
2. Country population must be increasing
3. Country must be experiencing price-inflation
Necessary Stock Conditions:
1. Growing revenue
2. Growing net income
3. Consistent net margins
4. Higher gross/net profit margin compared to its peers in the industry
5. Growing share holders equity
6. Current ratios > 1
7. Debt to equity ratio (compare to peers)
8. Debt servicing ratio < 30%
9. Wide economic moat
10. Products and services used daily, and will stay relevant for at least 1 decade
Necessary Crypto Conditions:
1. Honest founders
2. Competent technical co-founders
3. Fair or non-existent pre-mine
4. Solid marketing and PR
5. Legitimate use-cases / adoption
Default Robot Settings:
Contribution (USD): $10,000
Frequency (Months): 12
*Robot buys $10,000 worth of ETF, Stock, Crypto, regardless of the market price, every 12 months since its founding time.*
*Equity curve can be seen from the bottom panel*
Risk Warning:
This strategy is low-risk, however it assumes you have a long time horizon of at least 5 to 10 years. The longer your holding-period, the better your returns. The only thing the user has to keep-in-mind are the macro-economic conditions as stated above. If unsure, please stick to ETFs rather than buying individual stocks or cryptocurrencies.
Put Call RatioPlots the CBOE Put Call Ratio and marks up locations of extremities.
Useful as a factor of confluence in identifying extremities in the market.
Magic CandleThis indicator is very simple, but surprisingly effective, and I haven't found any mention of something similar, so here it is. I hope it helps you in your stock trading.
Someone made a comment in a trading room that the 8 am candle of the stock looked odd, so I quickly checked all the other stocks I had on my screen, and for all of them, the 8 am candle was just a little strange. What's more, is that the stock would often respond to the high and low values of that 8 am candle later on in the day. It turned out to be quite an important support and resistance level indicator for stocks which I've used in my trading ever since I discovered it.
After testing it out day after day on multiple stocks, I decided to write this indicator, which not only projects the high and low values of the 8 am candle, but also the previous day's closing price.
If you find that there's another "magic candle" out there for Forex or Crypto, please let me know!
You have the option to set the "magic candle" to another time, if you want to experiment with things.
ETS MA Deviation ExtremesWhile trading, I noticed that emphasis is often placed on how far price has moved from the moving average (whichever a trader prefers). In these cases I also found that Bollinger Bands only sometimes played a factor in determining whether price had moved "too far" from the moving average to potentially result in a sharp move back to the average.
Because I wanted something more objective than a "gut feeling" that price has moved away from the average enough to make it move back, I decided to see what I could do to determine the standard deviation of how price action moved away from the average , in order to determine when it could potentially have a "rubber band effect" to jump back to the "norm". The result of that is the ETS MA Deviation Extremes indicator, and I hope that it will help you in your trading.
The indicator also has bar coloring included, which can be turned off, which gives a good on-chart visual to warn you that the price action might reverse. This has often helped me to be a bit more cautious before just jumping into a trade that might be on the brink of reversing and taking my position out, and it actually turned out to be a good indicator for a reversal trade strategy.
The histogram bars give an indication of how far the price has moved away from the average, and I look for a potential reversal as soon as the histograms move back inside the deviation lines after having been outside it. The bar coloration actually depend on more than one set of deviation lines, but putting all of that on the chart just makes it confusing, so I removed the ones that I felt were not essential to make it clearer.
I hope it helps you in your trading and makes it easier for you to trade successfully!
Trendflex - Another new Ehlers indicatorSource: Stocks and Commodities V38
Hooray! Another new John Ehlers indicator!
John claims this indicator is lag-less and uses the SPY on the Daily as an example.
This indicator is a slight modification of Reflex, which I have posted here
I think it's better for Stocks and ETFs than Reflex since it factors in long trends. It tends to keep you in winning trades for a long time.
I believe this indicator can be used for entries or exits, potentially both.
Entry
1. Entering Long positions at the pivot low points (Stocks and ETFs)
2. Entering Long when the Reflex crosses above the zero lines (Stocks, ETFs, Commodities )
Exit
1. Exiting Long positions at a new pivot high point (Stocks and ETFs)
2. Exiting Long when the Reflex crosses below the zero lines (Stocks, ETFs, Commodities )
In this example, I place a Long order on the SPY every time the Reflex crosses above the zero level and exit when it crosses below or pops my stop loss, set at 1.5 * Daily ATR.
2/3 Wins
+16.05%
Let me know in the comment section if you're able to use this in a strategy.
Reflex - A new Ehlers indicatorSource: Stocks and Commodities V38
Hooray! A new John Ehlers indicator!
John claims this indicator is lag-less and uses the SPY on the Daily as an example.
He states that drawing a line from peak to peak (or trough to trough) will correspond perfectly with the Asset.
I have to say I agree! There is typically one bar of lag or no lag at all!
I believe this indicator can be used for either entries or exits, but not both.
Entry
1. Entering Long positions at the pivot low points (Stocks and ETFs)
2. Entering Long when the Reflex crosses above the zero lines (Stocks, ETFs, Commodities)
Exit
1. Exiting Long positions at a new pivot high point (Stocks and ETFs)
2. Exiting Long when the Reflex crosses below the zero lines (Stocks, ETFs, Commodities)
In this example, I place a Long order on the SPY every time the Reflex crosses above the zero level and exit when it crosses below or pops my stop loss, set at 1.5 * Daily ATR.
4/6 Wins
+10.76%
For me, that's good enough to create a strategy and backtest on several Indices and ETFs, which is what I have a hunch this will work on.
I think there is a lot of promise from a single Indicator!
Let me know in the comment section if you're able to use this in a strategy.
Custom Screener with Alerts [QuantNomad]Some time ago I published an example of simple custom screener in PineScript:
The only thing this screener did is created a dynamic label with screener output.
Recently TradingView announced alerts from the strategy with the possibility to add custom messages to alerts.
So using it I was able to create a bit more advanced screener which sends results as alert messages. With tools like Alertatron, you can easily redirect them to Telegram if you want.
It works for 40 symbols (limitation of the number of security calls).
To create your own screener you need to change only screenerFunc. The logic of this function is very simple, it outputs value you want to display in screener and condition based on which your screener should filter your stocks.
To create alerts for this screener create an alert from strategy and use {{strategy.order.alert_message}} as alert message.
Do you know now how to make this screener better? Let me know.
Disclaimer
Please remember that past performance may not be indicative of future results.
Due to various factors, including changing market conditions, the strategy may no longer perform as good as in historical backtesting.
This post and the script don’t provide any financial advice.
Performance ComparatorThis indicator allows to compare the performance (% change) of a given symbol with the larger market ( AMEX:SPY ) and/or with a custom symbol, which defaults to AMEX:XLK (an ETF tracking technology companies from the S&P 500).
The performance for the current symbol is displayed as a blue histogram, while performance for the AMEX:SPY and the custom symbol are respectively displayed as orange and white lines, making it easy to spot when the symbol outperformed the market.
Features:
Configurable time resolution (default: same as chart)
Comparison using change percentage or its EMA/WMA/SMA (default: EMA)
Configurable moving average length
Optionally hide AMEX:SPY or the custom symbol from the chart
Relative Strength Auto ComparisonRelative Strength Comparison with automatic selection of relevant index
Added support for most european and north american exchanges.
FauxLife EFIModification to Elder's Force Index (EFI)
Ability to change calculation from standard EMA to your choice of SMA, EMA, WMA, or HMA. Very interesting results!
Adjust lookback from standard/suggested 13 candlesticks
Added a color indication to positive or negative force reading
Added background color tint for an easier read on dashboard setups
Suggested pair with my On Balance Volume with Cross to use as a filter & entry/exit setup. Enter or exit trades when the two indicators switch at the same time or within 1-2 candlesticks of each other.
Terminal : Important U.S Indices Change (%) DataHello.
This script is a simple U.S Indices Data Terminal.
You can also set the period to look back manually in the menu.
In this way, an idea can be obtained about Major U.S Indices.
Features
Value changes on a percentage basis (%)
Recently, due to increasing interest, the NQNACE index has been added.
Index descriptions are printed on the information panel.
Sentiment NYSE ARCA and AMEX indices added.
Indices
SP1! : S&P 500 Futures Index
DJI : Dow Jones Industrial Average Index
NDX : Nasdaq 100 Index
RUT : Russell 2000 Index
NYA : NYSE Composite Index
OSX : PHLX Oil Service Sector Index
HGX : PHLX Housing Sector Index
UTY : PHLX Utility Sector Index
SOX : PHLX Semiconductor Sector Index
SPSIBI : S&P Biotechnology Select Industry Index
XNG : NYSE ARCA Natural Gas Index
SPGSCI : S&P Goldman Sachs Commodity Index
XAU : PHLX Gold and Silver Sector Index
SPSIOP : S&P Oil and Gas Exploration and Production Select Industry Index
GDM : NYSE ARCA Gold Miners Index
DRG : NYSE ARCA Pharmaceutical Index
TOB : NYSE ARCA Tobacco Index
DFI : NYSE ARCA Defense Index
NWX : NYSE ARCA Networking Index
XCI : NYSE ARCA Computer Technology
XOI : AMEX Oil Index
XAL : AMEX Airline Index
NQNACE : Nasdaq Yewno North America Cannabis Economy Index