Time Session Filter - MACD exampleTime Session Filter in TradingView Strategy: A Comprehensive Guide
Welcome to this educational TradingView blog where we dive deep into the functionality and utility of the time session filter in trading strategies. It's interesting to note that the time session filter is a commonly overlooked feature in Pine Script, often not integrated into overall trading strategies. Yet, when used wisely, this tool can significantly enhance your trading approach. In essence, the session filter ensures that trades are only made within a specific, user-defined time frame. By incorporating this often-neglected building block, you can make your strategy more adaptable to various market conditions and trading preferences.
What is a Time Session Filter?
A time session filter is designed to:
Select Times of the Day to Trade: The filter allows you to choose specific hours during the day in which trades are allowed to be excecuted.
Toggle Days to Trade: You can decide which days of the week you want to trade, giving you the flexibility to avoid days that are historically not profitable for your strategy.
Close Trade When Session Ends: The filter can automatically close any open trade once the specified time session concludes, reducing the risk associated with holding positions outside your chosen time frame.
The user interface is streamlined, taking minimal space for the input sections, making it convenient to integrate with other indicators in your overall strategy script. In addition the script colors the background of the chart green when the timesession filter is on and makes the background red when the filter doesn't allow any trades. This helps you to visualise the selected timeframes in relation to chart patterns.
Best Practices for Time Selection
From my personal trading experience I share some input settings you can try to play around with:
Stocks: Trading stocks sometimes yield better results if you only trade in the mornings until lunchtime. This is the period when markets are generally more active, and traders are keenly participating.
Cryptocurrencies: For cryptocurrencies, it sometimes makes sense to avoid trading on Fridays, a day when futures contracts often expire. Various other market-moving events also typically occur on Fridays.
Random Selection: Interestingly, sometimes choosing a random selection of times and days can improve the script's performance, adding an element of unpredictability that might outperform more systematic approaches.
Strategy Overview
This strategy script incorporates various elements, including risk position size and MACD indicator, to provide a comprehensive trading strategy. For a detailed explanation of risk position sizing, please refer to this article:
For a complete understanding of the MACD indicator utilized, visit the following explanation:
Additionally, for high time frame trend filters, consult this resource for more info:
Educational Purposes and Risks
Please note that this script is for educational purposes and serves merely as an example of how to incorporate a time session filter into a trading strategy for pinescript. It is a simplified strategy without a fixed stop-loss, which can result in higher exposure to significant losses. The time session filter can be a powerful addition to your trading strategy, providing you with the tools to tailor your approach according to time-specific market conditions. By understanding its functionalities and best practices, you can make more informed trading decisions, but always remember that trading carries inherent risks.
Happy trading!
Pine utilities
Risk to Reward - FIXED SL BacktesterDon't know how to code? No problem! TradingView is an excellent platform for you. ✅ ✅
If you have an indicator that you want to backtest using a risk-to-reward ratio or fixed take profit/stop loss levels, then the Risk to Reward - FIXED SL Backtester script is the perfect solution for you.
introducing Risk to Reward - FIXED SL Backtester Script which will allow you to test any indicator / Signal with RR or Fixed SL system
How does it work ?!
Once you connect the script to your indicator, it will analyze your entry points and perform calculations based on them. It will then open trades for you according to the specified inputs in the script settings.
HOW TO CONNECT IT to your indicator?
simply open your indicator code and add the below line of code to it
plot(Signal ? 100 : 0,"Signal",display = display.data_window)
Replace Signal with the long condition from your own indicator. You can also modify the value 100 to any number you prefer. After that, open the settings.
Once the script is connected to your indicator, you can choose from two options:
Risk To Reward Ratio System
Fixed TP/ SL System
🔸if you select the Risk to Reward System ⤵️
The Risk-to-Reward System requires the calculation of a stop loss. That's why I have included three different types of stop-loss calculations for you to choose from:
ATR Based SL
Pivot Low SL
VWAP Based SL
Your stop loss and take profit levels will be automatically calculated based on the selected stop loss method and your risk-to-reward ratio.
You can also adjust their values to match your desired risk level. The trades will be displayed on the chart.
with the ability to change their values to match your risk.
once this is done, trades will be displayed on the chart
🔸if you select the Fixed system ⤵️
You have 2 inputs, which are FIXED TP & Fixed SL
input the values you want, and trades will be on your chart...
I have also added a Breakeven feature for you.
with this Breakeven feature the trade will not just move SL to Entry ?! NO NO, it will place it above entry by a % you input yourself, so you always win! 🚀
Here is an example
Enjoy, and have fun, if you have any questions do not hesitate to ask
Default Strategy Template© CN_FX-999
Coded By Christian Nataliano
First Coded In 14/06/2023
Last Edited In 22/06/2023
This Is A Default Strategy Template That Can Make Your Strategy Scripts More Organized With The Benefit Of Having The Same Layouts & Not Needing To Copy Over The Common Codes Such As Displaying Backtest Results, Opening & Closing Trades, Pine Connector Capabilities And A Clean User Input Interface. This Is A Blank Strategy Script So Feel Free To Use It As Your Default Template For Your Future Strategies.
Credits To Some Of The Custom Code In The Scripts To © ZenAndTheArtOfTrading, Especially The Table Data Plotting
Monthly Strategy Performance TableWhat Is This?
This script code adds a Monthly Strategy Performance Table to your Pine Script strategy scripts so you can see a month-by-month and year-by-year breakdown of your P&L as a percentage of your account balance.
The table is based on realized equity rather than open equity, so it only updates the metrics when a trade is closed.
That's why some numbers will not match the Strategy Tester metrics (such as max drawdown), as the Strategy Tester bases metrics like max drawdown on open trade equity and not realized equity (closed trades).
The script is still a work-in-progress, so make sure to read the disclaimer below. But I think it's ready to release the code for others to play around with.
How To Use It
The script code includes one of my strategies as an example strategy. You need to replace my strategy code with your own. To do that just copy the source code below into a blank script, delete lines 11 -> 60 and paste your strategy code in there instead of mine. The script should work with most systems, but make sure to read the disclaimer below.
It works best with a significant amount of historical data, so it may not work very effectively on intraday timeframes as there is a severe limitation of available bars on TradingView. I recommend using it on 4HR timeframes and above, as anything less will produce very little usable data. Having a premium TradingView plan will also help boost the number of available bars.
You can hover your mouse over a table cell to get more information in the form of tooltips (such as the Long and Short win rate if you hover over your total return cell).
Credit
The code in this script is based on open-source code originally written by QuantNomad, I've made significant changes and additions to the original script but all credit for the idea and especially the display table code goes to them - I just built on top of it:
Why Did I Make This?
None of this is trading or investment advice, just my personal opinion based on my experience as a trader and systems developer these past 6+ years:
The TradingView Strategy Tester is severely limited in some important ways. And unless you use complex Excel formulas on exported test data, you can't see a granular perspective of your system's historical performance.
There is much more to creating profitable and tradeable systems than developing a strategy with a good win rate and a good return with a reasonable drawdown.
Some additional questions we need to ask ourselves are:
What did the system's worst drawdown look like?
How long did it last?
How often do drawdowns occur, and how quickly are they typically recovered?
How often do we have a break-even or losing month or year?
What is our expected compounded annual growth rate, and how does that growth rate compare to our max drawdown?
And many more questions that are too long to list and take a lifetime of trading experience to answer.
Without answering these kinds of questions, we run the risk of developing systems that look good on paper, but when it comes to live trading, we are uncomfortable or incapable of enduring the system's granular characteristics.
This Monthly Performance Table script code is intended to help bridge some of that gap with the Strategy Tester's limited default performance data.
Disclaimer
I've done my best to ensure the numbers this code outputs are accurate, and according to my testing with my personal strategy scripts it appears to work fine. But there is always a good chance I've missed something, or that this code will not work with your particular system.
The majority of my TradingView systems are extremely simple single-target systems that operate on a closed-candle basis to minimize many of the data reliability issues with the Strategy Tester, so I was unable to do much testing with multiple targets and pyramiding etc.
I've included a Debug option in the script that will display important data and information on a label each time a trade is closed. I recommend using the Debug option to confirm that the numbers you see in the table are accurate and match what your strategy is actually doing.
Always do your own due diligence, verify all claims as best you can, and never take anyone's word for anything.
Take care, and best of luck with your trading :)
Kind regards,
Matt.
PS. If you're interested in learning how this script works, I have a free hour-long video lesson breaking down the source code - just check out the links below this script or in my profile.
Strategy DesignerHello traders.
Thanks to the tool I have published, everyone who knows or does not know coding will be able to create strategies and see the results instantly on the screen. Yes it looks very nice :)
What does this script do?
Thanks to this tool, even if you don't know any coding, you will be able to create your own strategies. You can add and remove indicators.
Entrance
The first thing you need to do is to set a strategy in your mind.
Then you need to adjust the settings of the indicators installed in the system. Please set the indicators first, because later they are forgotten.
The screen for entering the parameters of the indicators will be as follows.
After entering the parameters there is an important part . In this section, we can adjust the strategy settings.
First we choose between which dates we want the strategy to run. We then choose whether we want the strategy results to be displayed in a table or not.
We choose how the Terms should be linked together. For example, if you have a condition that is expected to produce more than one receive signal, select whether these conditions are connected to each other with and or with the connector.
In this way, you can determine whether all or any of the rules in your strategy should apply.
Next, we choose whether our strategy will work in the spot market or in a bidirectional market. Yes, you can design a strategy for both spot and bidirectional trades :)
At the bottom of the above image, we see a screen where we can adjust the stop level and tp level. As a standard, adjustments are made according to the percentage level you enter. However, if you remove the tick next to the percent sign, the previous stop level and the next profit level are determined as much as the value you entered.
At the bottom is the trailing stop. When you open the trailing stop, the trailing stop becomes active in your strategy.
Very important, when the trailing stop and the stop are active at the same time, the trailing stop value is valid.
It's time to design our strategy. Each chapter that begins with an exclamation point is a separate fiction.
If you do not mark the Active button, that condition will not be included in the calculation.
Direction = It is the direction for which the fiction in this region is valid.
We came to the indicator setting screen. Here, there is a screen where we can select two different indicators on the right and left.
We choose the first indicator starting with 1.
Then we choose from the middle region how we want these two indicators to interact.
We choose our second indicator from the place starting with 2.
If you want an indicator to interact with any value, tick the box where it says Value and fill in the value in the blank. When Value is ticked, the second indicator does not work.
*Backtesting System ⚉ OVERVIEW ⚉
One of the best Systems for Backtesting your Strategies.
Incredibly flexible, simple, fast and feature-rich system — will solve most of your queries without much effort.
Many systems for setting StopLoss, TakeProfit, Risk Management and advanced Filters.
All you need to do is plug in your indicator and start Backtesting .
I intentionally left the option to use my System on Full Power before you load your indicator into it.
The system uses the built-in simple and popular moving average crossover signal for this purpose. (EMA 50 & 200).
Also Highly Recommend that you Fully use ALL of the features of this system so that you understand how they work before you ask questions.
Also tried to leave TIPS for each feature everywhere, read Tips, activate them and see how they work.
But before you use this system, I Recommend you to read the following description in Full.
—————— How to connect your indicator in 2 steps:
Adapt your indicator by adding only 2 lines of code and then connect it to this Backtesting System.
Step 1 — Create your connector, For doing so:
• 1 — Find or create in your indicator where are the conditions printing the Long-Buy and Short-Sell signals.
• 2 — Create an additional plot as below
I'm giving an example with a Two moving averages cross.
Please replicate the same methodology for your indicator wether it's a MACD, RSI , Pivots, or whatever indicator with Clear Buy and Sell conditions.
//@version=5
indicator('Moving Average Cross', overlay = true)
MA200 = ta.𝚎𝚖𝚊(close, 200)
MA50 = ta.𝚎𝚖𝚊(close, 50)
// Generate Buy and Sell conditions
buy = ta.crossover (MA200, MA50)
sell = ta.crossunder (MA200, MA50)
plot(MA200, color=color.green)
plot(MA50 , color=color.red )
bgcolor(color = buy ? color.green : sell ? color.red : na, title='SIGNALS')
// ———————————————— SIGNAL FOR SYSTEM ————————————————
Signal = buy ? +1 : sell ? -1 : 0
plot(Signal, title='🔌Connector🔌', display = display.none)
// —————— 🔥 The Backtesting System expects the value to be exactly +1 for the 𝚋𝚞𝚕𝚕𝚒𝚜𝚑 signal, and -1 for the 𝚋𝚎𝚊𝚛𝚒𝚜𝚑 signal
Basically, I identified my Buy & Sell conditions in the code and added this at the bottom of my indicator code
Now you can connect your indicator to the Backtesting System using the Step 2
Step 2 — Connect the connector
• 1 — Add your updated indicator to a TradingView chart and Add the Backtesting System as well to the SAME chart
• 2 — Open the Backtesting System settings and in the External Source field select your 🔌Connector🔌 (which comes from your indicator)
_______________________________
⚉ MAIN SETTINGS ⚉
‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
𝐄𝐱𝐭𝐞𝐫𝐧𝐚𝐥 𝐒𝐨𝐮𝐫𝐜𝐞 — Select your indicator. Add your indicator by following the 2 steps described above and select it in the menu. To familiarize yourself with the system until you select your indicator, you will have an in-built strategy of crossing the two moving EMA's of 50 and 200.
Long Deals — Enable/Disable Long Deals.
Short Deals — Enable/Disable Short Deals.
Wait End Deal — Enable/Disable waiting for a trade to close at Stop Loss/Take Profit. Until the trade closes on the Stop Loss or Take Profit, no new trade will open.
Reverse Deals — To force the opening of a trade in the opposite direction.
ReEntry Deal — Automatically open the same new deal after the deal is closed.
ReOpen Deal — Reopen the trade if the same signal is received. For example, if you are already in the long and a new signal is received in the long, the trade will reopen. * Does not work if Wait End Deal is enabled.
𝐓𝐚𝐤𝐞 𝐏𝐫𝐨𝐟𝐢𝐭:
None — Disables take profit. Useful if you only want to use dynamic stoplosses such as MA, Fast-Trailing, ATR Trail.
FIXED % — Fixed take profit in percent.
FIXED $ — Fixed Take in Money.
ATR — Fixed Take based on ATR.
R:R — Fixed Take based on the size of your stop loss. For example, if your stop is 10% and R:R=1, then the Take would be 10%. R:R=3 Take would be 30%, etc.
HH / LL — Fixed Take based on the previous maximum/minimum (extremum).
𝐒𝐭𝐨𝐩 𝐋𝐨𝐬𝐬:
None — Disables Stop Loss. Useful if you want to work without a stop loss. *Be careful if Wait End Deal is enabled, the trade may not close for a long time until it reaches the Take.
FIXED % — Fixed Stop in percent.
FIXED $ — Fixed Stop in Money.
TRAILING — Dynamic Trailing Stop like on the stock exchanges.
FAST TRAIL — Dynamic Fast Trailing Stop moves immediately in profit and stays in place if the price stands still or the price moves in loss.
ATR — Fixed Stop based on the ATR.
ATR TRAIL — Dynamic Trailing Stop based on the ATR.
LO / HI — A Fixed Stop based on the last Maximum/Minimum extemum. Allows you to place a stop just behind or above the low/high candle.
MA — Dynamic Stop based on selected Moving Average. * You will have 8 types of MA (EMA, SMA, HMA, etc.) to choose from, but you can easily add dozens of other MAs, which makes this type of stop incredibly flexible.
Add % — If true, then with the "𝗦𝘁𝗼𝗽 %" parameter you can add percentages to any of the current SL. Can be especially useful when using Stop - 𝗔𝗧𝗥 or 𝗠𝗔 or 𝗟𝗢/𝗛𝗜. For example with 𝗟𝗢/𝗛𝗜 to put a stop for the last High/Low and add 0.5% additional Stoploss.
Fixed R:R — If the stop loss is Dynamic (Trailing or MA) then if R:R true can also be made Dynamic * Use it carefully, the function is experimental.
_________________________________________
⚉ TAKE PROFIT LEVELS ⚉
‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
A unique method of constructing intermediate Take Profit Levels will allow you to select up to 5 intermediate Take Profit Levels and one intermediate Stop Loss.
Intermediate Take Profit Levels are perfectly calculated into 5 equal parts in the form of levels from the entry point to the final Take Profit target.
All you need to do is to choose the necessary levels for fixing and how much you want to fix at each level as a percentage. For example, TP 3 will always be exactly between the entry point and the Take Profit target. And the value of TP 3 = 50 will close 50% of the amount of the remaining size of the position.
Note: all intermediate SL/TP are closed from the remaining position amount and not from the initial position size, as TV does by default.
SL 0 Position — works in the same way as TP 1-5 but it's Stop. With this parameter you can set the position where the intermediate stop will be set.
Breakeven on TP — When activated, it allows you to put the stop loss at Breakeven after the selected TP is reached. For this function to work as it should - you need to activate an intermediate Take. For example, if TP 3 is activated and Breakeven on TP = 3, then after the price reaches this level, the Stop loss will go to Breakeven.
* This function will not work with Dynamic Stoplosses, because it simply does not make sense.
CoolDown # Bars — When activated, allows you to add a delay before a new trade is opened. A new trade after CoolDown will not be opened until # bars pass and a new signal appears.
_____________________________
⚉ TIME FILTERS ⚉
‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
Powerful time filter code that allows you to filter data based on specific time zones, dates, and session days. This code is ideal for those who need to analyze data from different time zones and weed out irrelevant data.
With Time Filter, you can easily set the starting and ending time zones by which you want to filter the data.
You can also set a start and end date for your data and choose which days of the week to include in the analysis. In addition, you can specify start and end times for a specific session, allowing you to focus your analysis on specific time periods.
_________________________________
⚉ SIGNAL FILTERS ⚉
‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
Signal Filters — allows you to easily customize and optimize your trading strategies based on 10 filters.
Each filter is designed to help you weed out inaccurate signals to minimize your risks.
Let's take a look at their features:
__________________________________
⚉ RISK MANAGEMENT ⚉
‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
Risk management tools that allow you to set the maximum number of losing trades in a row, a limit on the number of trades per day or week and other filters.
Loss Streak — Set Max number of consecutive loss trades.
Win Streak — Max Winning Streak Length.
Row Loss InDay — Max of consecutive days with a loss in a row.
DrawDown % — Max DrawDown (in % of strategy equity).
InDay Loss % — Set Max Intraday Loss.
Daily Trades — Limit the number of MAX trades per day.
Weekly Trades — Limit the number of MAX trades per week.
* 🡅 I would Not Recommend using these functions without understanding how they work.
Order Size — Position Size
• NONE — Use the default position size settings in Tab "Properties".
• EQUITY — The amount of the allowed position as a percentage of the initial capital.
• Use Net Profit — On/Off the use of profit in the following trades. *Only works if the type is EQUITY.
• SIZE — The size of the allowed position in monetary terms.
• Contracts — The size of the allowed position in the contracts. 1 Сontract = Сurrent price.
________________
⚉ NOTES ⚉
‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
It is important to note that I have never worked with Backtesting and the functions associated with them before.
It took me about a month of slow work to build this system.
I want to say Big Thanks:
• The PineScripters🌲 group in Telegram , the guys suggested how to implement some features. Especially @allanster
• Thanks to all those people who share their developments for free on TV and not only.
• I also thank myself for not giving up and finishing the project, and not trying to monetize the system by selling it. * Although I really want the money :)
I tried hard to make it as fast and convenient as possible for everyone who will use my code.
That's why I didn't use any libraries and dozens of heavy functions, and I managed to fit in 8+-functions for the whole code.
Absolutely every block of code I tried to make full-fledged modular, that it was easy to import/edit for myself (you).
I have abused the Ternary Pine operator a little (a lot) so that the code was as compact as possible.
Nevertheless, I tried very hard to keep my code very understandable even for beginners.
At last I managed to write 500 lines of code, making it one of the fastest and most feature-rich systems out there.
I hope everyone enjoys my work.
Put comments and write likes.
Strategy Template + Performance & Returns table + ExtrasA script I've been working on since summer 2022. A template for any strategy so you just have to write or paste the code and go straight into risk management settings
Features:
>Signal only Longs/only Shorts/Both
>Leverage system
>Proper fees calculation (even with leverage on)
>Different Stop Loss systems: Simple percentage, 4 different "move to Break Even" systems and Scaling SL after each TP order (read the disclaimer at the bottom regarding this and the TV % profitable metric)
>2 Take Profit systems: Simple percentages, or Risk/reward ratios based on SL level
>Additional option on TP so last one "rides free" until closure of position or Stoploss is hit (for more than 1 orders)
>Up to 5 TP orders
>Show or hide SL/TP levels on demand
>2 date filters. Manual filter is nothing new, enter two dates/hours and filter will turn on. BUT automatic filter is another thing (thanks to user @bfr_ for his help in codingthis feature)
>AUTOMATIC DATE FILTER. Allows you to split all historical data on the chart in X periods, then choose the range of periods used. Up to 10 but that can be changed, instructions included. Useful for WalkForward simulations, haven't seen a script in TradingView that allows you to do this and test your strategy on "unseen data" automatically
EXTRA SETTINGS
Besides, some additions I like to add to my codes:
>Returns table for monthly and weekly performance. Requires recalculation on every tick. This is a modified version of @QuantNomad's work. May add lower TF options later on
>Volume Based S/R system. Original work from @shtcoinr
>One feature that was made by me, the "portfolio table". Yields info and metrics of your strategy, current position and balance. You're able to turn it off and change its size
Should anyone find an error, or have any idea on how to improve this code, please contact me. Future updates could come, stay tuned
DISCLAIMER:
In order to have accurate StopLoss hit, I had to change the previous system, which was a "close position on candle close" instead at actual stoploss level. It was fixed, but resulted on inflation of the number of trading orders, thus reducing the percent profitable and making it strongly biased and unreal. Keep that in mind, that "real" profitability could be 2x or 3x the metric TradingView says. If your strategy has a really high trading frequency, resulting in 3000+ orders, might be a problem. Try to make use of the automatic/manual date filter as workaround, I have no means of changing this, seems it is not a bug but an intended design of the PineScript Code
X48 - Strategy | BreakOut & Consecutive (11in1) + Alert | V.1.2================== Read This First Before Use This Strategy ==============
*********** Please be aware that this strategy is not a guarantee of success and may lead to losses.
*********** Trading involves risk and you should always do your own research before making any decisions.
================= Thanks Source Script and Explain This Strategy ===================
► Description
Write a detailed and meaningful description that allows users to understand how your script is original, what it does, how it does it and how to use it
This Strategy Are Combine Strategy and Indicators Alert Function For Systematic Trading User.
Strategy List, Thanks For Original Source Script , From Tradingview Build-in Script From fmzquant Github
// Channel BreakOut Strategy : Calculate BreakOut Zone For Buy and Sell.
// Consecutive Bars UP/Down Strategy : The consecutive bars up/down strategy is a trading strategy used to identify potential buy and sell signals in the stock market. This strategy involves looking for a series of bars (or candles) that are either all increasing or all decreasing in price. If the bars are all increasing, it can be a signal to buy, and if the bars are all decreasing, it can be a signal to sell. This strategy can be used on any timeframe, from a daily chart to an intraday chart.
// 15m Range Length SD : Range Of High and Low Candle Price and Lookback For Calculate Buy and Sell.
Indicators Are Simple Source Script (Almost I'm Chating With CHAT-GPT and Convert pinescript V4 to V5 again for complete almost script and combine after)
// SwingHigh and SwingLow Plot For SL (StopLoss by Last Swing).
// Engulfing and 3 Candle Engulfing Plot.
// Stochastic RSI for Plot and Fill Background Paint and Plot TEXT For BULL and BEAR TREND.
// MA TYPE MODE are plot 2 line of MA Type (EMA, SMA, HMA, WMA, VWMA) for Crossover and Crossunder.
// Donchian Fans MODE are Plot Dot Line With Triangle Degree Bull Trend is Green Plot and Bear Trend is Red Plot.
// Ichimoku Cloud Are Plot Cloud A-B For Bull and Bear Trend.
// RSI OB and OS for TEXT PLOT 'OB' , 'OS' you will know after OB and OS, you can combo with other indicators that's make you know what's the similar trend look like?
// MACD for Plot Diamond when MACD > 0 and MACD < 0, you can combo with other indicators that's make you know what's the similar trend look like?
Alert Can Alert Sent When Buy and Sell or TP and SL, you can adjust text to alert sent by your self or use default setting.
========== Let'e Me Explain How To Use This Strategy =============
========== Properties Setting ==========
// Capital : Default : 1,000 USDT For Alot Of People Are Beginner Investor = It's Capital Your Cash For Investment
// Ordersize : Default Are Setting 5% / Order We Call Compounded
========== INPUT Setting ==========
// First Part Use Must Choose Checkbox For Use of Strategy and Choose TP/SL by Swing or % (can choose both)
// In Detail Of Setting Are Not Too Much, Please Read The Header Of Setting Before Change The Value
// For The Indicator In List You Want To Add Just Check ✅ From MODE Setting, It's Show On Your Chart
// You Can Custom TP/SL % You Want
========== ##### No trading strategy is guaranteed to be 100% successful. ###### =========
For Example In My Systematic Trading
Select 1/3 Strategy Setting TP/SL % Match With Timeframe TP Long Are Not Set It's Can 161.8 - 423.6% but Short Position Are Not Than 100% Just Fine From Your Aset
Choose Indicators For Make Sure Trend and Strategy are the same way like Strategy are Long Position but MACD and Sto background is bear. that's mean this time not open position.
Donchian Fans is Simple Support and Ressistant If You Don't Know How To Plot That's, This indicator plot a simple for you ><.
Make Sure With Engulfing and 3 Candle Engulfing If You Don't Know, What's The Engulfing, This Indicator are plot for you too ><.
For a Big Trend You can use Ichimoku Cloud For Check Trend, Candle Upper Than Cloud or Lower Than Cloud for Bull and Bear Trend.
Combined Strategy Trading Bot (RSI ADX 20SMA)Trading Bot V1, This code implements a combined trading strategy that uses several indicators and strategies to make buy and sell decisions in the market. The code is written in Pine Script™, which is a programming language used in the TradingView platform. By BraelonWhitfield.Eth
The strategy uses the Average Directional Movement Index (ADX) and the Pine SuperTrend indicator to identify trends and price movements in the market. The SuperTrend indicator is a popular technical analysis tool that helps to identify the direction of the current trend and provides entry and exit points for trades.
The strategy also uses the Relative Strength Index (RSI) to identify overbought and oversold conditions in the market. The RSI is a momentum indicator that measures the speed and change of price movements in the market.
The first part of the code defines the inputs for the ADX and DI Length, which are used to calculate the ADX and DI values. The dirmov() function is used to calculate the positive and negative directional indicators (plusDM and minusDM) based on the high and low prices. The truerange variable is then calculated using the True Range (TR) formula. Finally, the plus and minus variables are calculated using the smoothed moving average of the plusDM and minusDM values.
The adx() function is then used to calculate the ADX values based on the plus and minus variables. The Pine SuperTrend indicator is defined using the pine_supertrend() function. This function uses the high-low average (hl2) and the Average True Range (ATR) to calculate the upper and lower bands for the indicator. The direction of the current trend is then determined based on whether the current price is above or below the upper or lower bands.
The RSI values are then calculated using the ta.rsi() function, with the inputs for the close price and the RSI period. The overbought and oversold conditions are defined using the OB and OS inputs, which specify the threshold values for the RSI. The upTrend and downTrend variables are defined based on the direction of the Pine SuperTrend indicator.
The next part of the code defines the 20-period Simple Moving Average (SMA) using the ta.sma() function. The os and ob variables are then calculated based on the RSI values and the OB and OS inputs. The strategy.entry() function is used to define the buy and sell orders based on the upTrend and downTrend variables, as well as the Pine SuperTrend indicator, the 20-period SMA, and the os variable.
The final part of the code defines the Channel Breakout Strategy using the ta.highest() and ta.lowest() functions to calculate the upper and lower bounds of the channel. The strategy.entry() function is then used to define the buy and sell orders based on whether the current price is above or below the upper or lower bounds.
In summary, this code implements a combined trading strategy that uses several indicators and strategies to make buy and sell decisions in the market. The strategy is designed to identify trends and price movements in the market, as well as overbought and oversold conditions, to provide entry and exit points for trades. The strategy uses the Pine SuperTrend indicator, the ADX and DI indicators, the RSI, and the 20-period SMA, as well as the Channel Breakout Strategy to make informed trading decisions.
Backtest AdapterThis is a proof-of-concept Backtest Adapter that can be used with my recent publication "Machine Learning: Lorentzian Classification" located here:
This adapter is helpful because it enables interactive backtesting with TradingView's built-in "Strategy Tester" framework without the need to translate the logic from an "indicator" script to a "strategy" script.
To use this, one must have the "Machine Learning: Lorentzian Classification" script and this Backtest Adapter open simultaneously on the same chart. From there, simply change the "Source" setting of the Backtest Adapter to "Lorentzian Classification: Backtest Stream" to transfer the entry/exit signals stream to the Backtest Adapter.
For an example of how to implement your own backtest stream in your indicators, please refer to the "Backtesting" section in the source code of the "Machine Learning: Lorentzian Classification" script, which is shown below for convenience:
smplondonclinic StrategyHello my friend! I'm uploading the code for your strategy. I have included a feature in the settings menu called "Entry Direction" that you can use to isolate only longs, only shorts or have both directions at the same time for the backtesting. I have set the strategy to only open 1 position at a time, it will not open a new position unless the previous position is closed. If you want to remove that just let me know. The green/red triangles that you will see plotting on the chart are the potential entry signals, you can turn them off from the style panel in the settings menu. In the inputs tab besides the strategy settings you also have all the relevant parameters for the three indicators used.
Rocket Grid Algorithm - The Quant ScienceThe Rocket Grid Algorithm is a trading strategy that enables traders to engage in both long and short selling strategies. The script allows traders to backtest their strategies with a date range of their choice, in addition to selecting the desired strategy - either SMA Based Crossunder or SMA Based Crossover.
The script is a combination of trend following and short-term mean reversing strategies. Trend following involves identifying the current market trend and riding it for as long as possible until it changes direction. This type of strategy can be used over a medium- to long-term time horizon, typically several months to a few years.
Short-term mean reversing, on the other hand, involves taking advantage of short-term price movements that deviate from the average price. This type of strategy is usually applied over a much shorter time horizon, such as a few days to a few weeks. By rapidly entering and exiting positions, the strategy seeks to capture small, quick gains in volatile market conditions.
Overall, the script blends the best of both worlds by combining the long-term stability of trend following with the quick gains of short-term mean reversing, allowing traders to potentially benefit from both short-term and long-term market trends.
Traders can configure the start and end dates, months, and years, and choose the length of the data they want to work with. Additionally, they can set the percentage grid and the upper and lower destroyers to manage their trades effectively. The script also calculates the Simple Moving Average of the chosen data length and plots it on the chart.
The trigger for entering a trade is defined as a crossunder or crossover of the close price with the Simple Moving Average. Once the trigger is activated, the script calculates the total percentage of the side and creates a grid range. The grid range is then divided into ten equal parts, with each part representing a unique grid level. The script keeps track of each grid level, and once the close price reaches the grid level, it opens a trade in the specified direction.
The equity management strategy in the script involves a dynamic allocation of equity to each trade. The first order placed uses 10% of the available equity, while each subsequent order uses 1% less of the available equity. This results in the allocation of 9% for the second order, 8% for the third order, and so on, until a maximum of 10 open trades. This approach allows for risk management and can help to limit potential losses.
Overall, the Rocket Grid Algorithm is a flexible and powerful trading strategy that can be customized to meet the specific needs of individual traders. Its user-friendly interface and robust backtesting capabilities make it an excellent tool for traders looking to enhance their trading experience.
DCA Simulator A simple yet powerful Dollar Cost Averaging (DCA) simulator.
You just add the script to your chart, and you'll be able to see:
- Every single entry with its size
- The evolution of you average price in time (blue line)
- The profit and loss areas (where market price < average price the DCA is at loss, and the background is colored in red. At the contrary, where mkt price is > average price, it's profit area and the background is green).
- Max drawdown: the point in price and time where the DCA loss is maximum in the considered time interval. The drawdown amount is specified.
- Profit (or loss) and total cost at the end of the time interval or at the present day: the script shows how much the DCA is netting at a profit or loss, as well as the total cost of the DCA itself.
The parameters are:
- Date start and date end: time interval of the DCA simulation
- DCA period (you can choose between daily, weekly and monthly)
- Week day or month day if you choose those periods
- Single operation size (in base currency)
- Option to choose a DCA LONG or DCA SHORT (for uber bears)
- Option to include an exit strategy that partially closes your position (the % size closed can be chosen as well with the parameter "exit_close_perc") every time the DCA realizes a specific gain (choosable with the parameter "exit_gain_threshold"). If you choose "none" as an exit strategy, the script will assume to never close positions until the end of the period or the present day for simulation purpose.
NB: just ignore the TV strategy tester results, all the data are visible on the chart.
Trading Day and Time SessionThis script provides options for the user to choose:
- Start date and End date
- Trade time during a day (With UTC offset)
- Which days of the week to trade
It return a condition if all the date and time conditions are true. It's very easy to integrate with any script.
Reinforced RSI - The Quant Science This strategy was designed and written with the goal of showing and motivating the community how to integrate our 'Probabilities' module with their own script.
We have recreated one of the simplest strategies used by many traders. The strategy only trades long and uses the overbought and oversold levels on the RSI indicator.
We added stop losses and take profits to offer more dynamism to the strategy. Then the 'Probabilities' module was integrated to create a probabilistic reinforcement on each trade.
Specifically, each trade is executed, only if the past probabilities of making a profitable trade is greater than or equal to 51%. This greatly increased the performance of the strategy by avoiding possible bad trades.
The backtesting was calculated on the NASDAQ:TSLA , on 15 minutes timeframe.
The strategy works on Tesla using the following parameters:
1. Lenght: 13
2. Oversold: 40
3. Overbought: 70
4. Lookback: 50
5. Take profit: 3%
6. Stop loss: 3%
Time period: January 2021 to date.
Our Probabilities Module, used in the strategy example:
Quarterly Returns in Strategies vs Buy & HoldThis is a Quarterly Returns version of Monthly Returns in PineScript Strategies by QuantNomad
This script shows a table of Quarterly/Yearly performance of your strategy.
It also provides an option to compare with Buy & Hold.
The script can easily integrated to your strategy. All you need to do is copy the table part and paste it at the end of your script
Disclaimer
Please remember that past performance may not be indicative of future results.
This post and the script don’t provide any financial advice.
Super 8 - 30M BTCWelcome to Super 8, the ultimate automatic trading script for Pine!
This bad boy is designed to go both long and short, and it's equipped with all the tools you need to maximize your profits. Whether you're looking to take profit, set a trailing stop, or protect yourself with a stop loss, Super 8 has you covered.
But that's not all! Super 8 is also loaded with 8 powerful indicators to help you make informed decisions. We've got the EMA, ADX, SAR, MACD, VOLUME, BOLLINGER BANDS, DONCHIAN, and ATR all working together to give you the best possible trading experience.
And if you want to take it to the next level, Super 8 also has a feature that lets you use stepped entries in normal mode or incremental 1,2,3,... to improve your average price. Plus, if you're using trailing stop, you can activate the Backtest precision to use lower timeframes.
But what's in a name? Super 8 is called that because it's just that... super! It's tailored specifically for the OKX:BTCUSDT.P pair, so you know you're getting the best possible results. it's highly adjustable and can be used with any other pair. So no matter what market you're trading in, Super 8 has got you covered.
So if you want to level up your trading game, give Super 8 a try. You won't be disappointed.
Certain Risks of Live Algorithmic Trading:
Backtesting Cannot Assure Actual Results.
The relevant market might fail or behave unexpectedly.
Your broker may experience failures in its infrastructure, fail to execute your orders in a correct or timely fashion or reject your orders.
The system you use for generating trading orders, communicating those orders to your broker, and receiving queries and trading results from your broker may fail.
Time lag at various point in live trading might cause unexpected behavior.
The systems of third parties in addition to those of the provider from which we obtain various services, your broker, and the applicable securities market may fail or malfunction.
Selected Dates Filter by @zeusbottradingWe are presenting you feature for strategies in Pine Script.
This function/pine script is about NOT opening trades on selected days. Real usage is for bank holidays or volatile days (PPI, CPI, Interest Rates etc.) in United States and United Kingdom from 2020 to 2030 (10 years of dates of bank holidays in mentioned countries above). Strategy is simple - SMA crossover of two lengts 14 and 28 with close source.
In pine script you can see we picked US and GB bank holidays. If you add this into your strategy, your bot will not open trades on those days. You must make it a rule or a condition. We use it as a rule in opening long/short trades.
You can also add some of your prefered dates, here is just example of our idea. If you want to add your preffered days you can find them on any site like forexfactory, myfxbook and so on. But don’t forget to add function “time_tradingday ! = YourChoosedDate” as it is writen lower in the pine script.
Sometimes the date is substituted for a different day, because the day of the holiday is on Saturday or Sunday.
Made with ❤️ for this community.
If you have any questions or suggestions, let us know.
The script is for informational and educational purposes only. Use of the script does not constitutes professional and/or financial advice. You alone the sole responsibility of evaluating the script output and risks associated with the use of the script. In exchange for using the script, you agree not to hold zeusbottrading TradingView user liable for any possible claim for damages arising from any decision you make based on use of the script.
Ultimate Strategy Template (Advanced Edition)Hello traders
This script is an upgraded version of that one below
New features
- Upgraded to Pinescript version 5
- Added the exit SL/TP now in real-time
- Added text fields for the alerts - easier to send the commands to your trading bots
Step 1: Create your connector
Adapt your indicator with only 2 lines of code and then connect it to this strategy template.
For doing so:
1) Find in your indicator where are the conditions printing the long/buy and short/sell signals.
2) Create an additional plot as below
I'm giving an example with a Two moving averages cross.
Please replicate the same methodology for your indicator wether it's a MACD , ZigZag , Pivots , higher-highs, lower-lows or whatever indicator with clear buy and sell conditions.
//@version=5
indicator(title='Moving Average Cross', shorttitle='Moving Average Cross', overlay=true, precision=6, max_labels_count=500, max_lines_count=500)
type_ma1 = input.string(title='MA1 type', defval='SMA', options= )
length_ma1 = input(10, title=' MA1 length')
type_ma2 = input.string(title='MA2 type', defval='SMA', options= )
length_ma2 = input(100, title=' MA2 length')
// MA
f_ma(smoothing, src, length) =>
rma_1 = ta.rma(src, length)
sma_1 = ta.sma(src, length)
ema_1 = ta.ema(src, length)
iff_1 = smoothing == 'EMA' ? ema_1 : src
iff_2 = smoothing == 'SMA' ? sma_1 : iff_1
smoothing == 'RMA' ? rma_1 : iff_2
MA1 = f_ma(type_ma1, close, length_ma1)
MA2 = f_ma(type_ma2, close, length_ma2)
// buy and sell conditions
buy = ta.crossover(MA1, MA2)
sell = ta.crossunder(MA1, MA2)
plot(MA1, color=color.new(color.green, 0), title='Plot MA1', linewidth=3)
plot(MA2, color=color.new(color.red, 0), title='Plot MA2', linewidth=3)
plotshape(buy, title='LONG SIGNAL', style=shape.circle, location=location.belowbar, color=color.new(color.green, 0), size=size.normal)
plotshape(sell, title='SHORT SIGNAL', style=shape.circle, location=location.abovebar, color=color.new(color.red, 0), size=size.normal)
/////////////////////////// SIGNAL FOR STRATEGY /////////////////////////
Signal = buy ? 1 : sell ? -1 : 0
plot(Signal, title='🔌Connector🔌', display = display.data_window)
Basically, I identified my buy, sell conditions in the code and added this at the bottom of my indicator code
Signal = buy ? 1 : sell ? -1 : 0
plot(Signal, title="🔌Connector🔌", transp=100)
Important Notes
🔥 The Strategy Template expects the value to be exactly 1 for the bullish signal, and -1 for the bearish signal
Now you can connect your indicator to the Strategy Template using the method below or that one
Step 2: Connect the connector
1) Add your updated indicator to a TradingView chart
2) Add the Strategy Template as well to the SAME chart
3) Open the Strategy Template settings and in the Data Source field select your 🔌Connector🔌 (which comes from your indicator)
From then, you should start seeing the signals and plenty of other stuff on your chart
🔥 Note that whenever you'll update your indicator values, the strategy statistics and visual on your chart will update in real-time
Settings
- Color Candles: Color the candles based on the trade state ( bullish , bearish , neutral)
- Close positions at market at the end of each session: useful for everything but cryptocurrencies
- Session time ranges: Take the signals from a starting time to an ending time
- Close Direction: Choose to close only the longs, shorts, or both
- Date Filter: Take the signals from a starting date to an ending date
- Set the maximum losing streak length with an input
- Set the maximum winning streak length with an input
- Set the maximum consecutive days with a loss
- Set the maximum drawdown (in % of strategy equity)
- Set the maximum intraday loss in percentage
- Limit the number of trades per day
- Limit the number of trades per week
- Stop-loss: None or Percentage or Trailing Stop Percentage or ATR - I'll add shortly multiple options for the trailing stop loss
- Take-Profit: None or Percentage or ATR - I'll add also a trailing take profit
- Risk-Reward based on ATR multiple for the Stop-Loss and Take-Profit
Special Thanks
Special thanks to @JosKodify as I borrowed a few risk management snippets from his website: kodify.net
Best
Dave
Trading range display with BoxThis script is just for reference to see the trading range.
Do not use this strategy logic, it is just Test strategy.
The trading range is colored depending on whether it is profitable or not.
You can change the color if you want.
When you declare the strategy, put (process_orders_on_close=true,calc_on_every_tick=true, max_boxes_count=500) in your script.
Then it can show you current open trading as well.
If you use switching strategy (e.g longposition to shortposition right away), it may not show you the range properly.
In that case, reduse the test period.
IT IS Repainting Reference.
If you want to see your strategy result visually,
Just copy and paste from line 22 in my script.
Good Luck everyone.
전략 거래 기간 동안을 보여주는 지표입니다.
이 지표에 쓰인 전략은 단순 테스트용 입니다. 절대 사용하지 마세요.
각 거래기간은 수익이냐 아니냐에 따라 색깔이 정해 집니다.
색깔은 여러분이 변경하실 수 있습니다.
전략을 선언부에 process_orders_on_close=true,calc_on_every_tick=true, max_boxes_count=500 을 넣으시면 현재 오픈 거래도 보실 수 있습니다.
스위칭 전략(롱에서 숏으로 바로 전환하는 전략)을 쓰시는 분들은 아마 테스트 기간을 줄이라는 경고를 받으실 수 있습니다.
이 지표는 리페이팅이 될 수 있습니다.
전략 결과를 눈으로 보고 싶으신 분들은 22번째 줄 부터 카피하시면 됩니다.
행운이 있길..
---strategy set---
default_qty_value=10
commission_value=0.04
slippage=2
Tick StrategyTick Strategy:
Questions many pine coders/traders have is, How to enter/exit trade as soon as trade condition is met i.e. do not wait till candle completion to enter/exit the trade. This strategy will help you to understand one of the way to achieve it.
This is an educational strategy to demonstrate, how one can trade based on tick data. This being a strategy based on tick data, it can be tested only on real time candles. This strategy will not take any trades on historical candles and cannot be used for back testing. All the strategy trades taken on real time candles will disappear (repainting) once chart is refreshed and new trades will be entered on real time candles.
The strategy will do nothing during off market hours and will not take any trades.
The strategy has been designed based on rules/inputs below:
1. Count the ticks from start of a candle till end of candle
2. Bifurcate ticks as up-ticks and down-ticks. If tick price is above previous tick price the tick is considered as up-tick and vice versa
3. Count the successive up-ticks and successive down-ticks
Strategy rules:
1. Track candle type (green or red) continuously on each tick (green candle is when latest tick price > previous tick price)
2. Take a long trade if work in progress (WIP) candle is green candle and we get successive up-ticks equal to user input ticks for trade
3. Take a short trade if work in progress (WIP) candle is red candle and we get successive down-ticks equal to user input ticks for trade
4. Exit the trade when we get successive ticks equal to user input ticks in opposite direction
5. Optionally for trade entry, user can decide whether to calculate successive up-ticks/down-ticks from beginning of candle or successive up-ticks/down-ticks anytime during the candle formation
6. Optionally for trade exit/square off, user can decide whether to apply exit rules on the entry candle or only from subsequent candle
Strategy setting:
1. '' – This is just to describe when trades are entered. This parameter is not used for any calculation
2. 'No of successive ticks to enter the trade' – User input to decide, number of successive ticks for trade entry
3. 'Count successive ticks for trade only from start of candle' – check this to count successive ticks only from beginning of a candle
4. 'Exit if succussive ticks in opposite direction' - User input to decide, number of successive ticks in opposite direction for exiting the trade
5. 'Apply exit criteria on entry candle' – check to allow exit of trade on the entry candle, if un-checked, trade will not be exited on the entry candle i.e. opposite direction ticks will be counted from subsequent candle
Information below will be displayed continuously on the chart:
1. Candle no – Candles are counted from start of the trading session. This is current candle being formed on the chart
2. Candle now – This shows either ‘Green’ or ‘Red’ based on type of candle being formed
3. Tick count – This is current tick number being processed. Tick number starts from 1 for each new candle
4. Up-tick count – Number of up-ticks during formation of current candle
5. Down-tick count – Number of down-ticks during formation of current candle
6. Successive up-ticks – Current successive up-tick count
7. Successive down-ticks – Current successive down-tick count
8. Up-tick volume – Volume associated with up-ticks
9. Down-tick volume – Volume associated with down-ticks
10. Up-tick volume % - This is % of volume associated with up-ticks
11. Total volume – Candle volume till now. (Some times you might observe small difference between total volume and the volume shown by volume indicator. The difference could be because of refresh rate of your screen)
12. Candle completion % - This shows current candles completion %. This is candle progress from start of candle till close of candle
Under09_01Parametros de entradas
Activo->btc xbtusd (Bitmex)
Temporalidad->2h
SL-> 0.2
TP->12.2
Angulo->4.2
p->2
longitud->27
//@version=4
//
// ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ //
//Ultima version underground09
strategy(title = " underground09",
shorttitle = "Under09",
overlay = true,
precision = 8,
calc_on_order_fills = true,
calc_on_every_tick = true,
backtest_fill_limits_assumption = 0,
default_qty_type = strategy.fixed,
default_qty_value = 2,
initial_capital = 10000,
pyramiding=5,
currency = currency.USD,
linktoseries = true)
//
// ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ //
var sl = 0.0
var tp = 0.0
var acumaldor_vxp = 0.0
var acomuldor_vol = 0.0
//stop_loss = input(defval=0.2, title="Porcentaje Stop Loss", type=input.float, step=0.2)
stop_loss = input(defval=1.4, title="Porcentaje Stop Loss", type=input.float, step=0.2)
//take_profit = input(defval=4.4, title="Porcentaje Take Profit", type=input.float, step=0.2)
take_profit = input(defval=5.6, title="Porcentaje Take Profit", type=input.float, step=0.2)
//pintar_trade = input(defval=false, title="Pintar trade TP SL")
angulo_permitido = input(defval=26.8, title="Angulo permitido", type=input.float, step=0.2)
backTestSectionFrom = input(title = "═══════════════ From ═══════════════", defval = true, type = input.bool)
FromMonth = input(defval = 1, title = "Month", minval = 1)
FromDay = input(defval = 1, title = "Day", minval = 1)
FromYear = input(defval = 2019, title = "Year", minval = 2014)
backTestSectionTo = input(title = "════════════════ To ════════════════", defval = true, type = input.bool)
ToMonth = input(defval = 31, title = "Month", minval = 1)
ToDay = input(defval = 12, title = "Day", minval = 1)
ToYear = input(defval = 9999, title = "Year", minval = 2014)
Config = input(title = "══════════════ Config ══════════════", defval = true, type = input.bool)
//p = input(6)
p = input(4)
//length = input(30)
length = input(26)
//
backTestPeriod() => (time > timestamp(FromYear, FromMonth, FromDay, 00, 00)) and (time < timestamp(ToYear, ToMonth, ToDay, 23, 59))
//
//
// ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ //
x1 = bar_index
x2 = sqrt(x1)
y = high
//
S11 = sum(x2,length) - sqrt(sum(x1,length)) / length
S12 = sum(x1*x2,length) - (sum(x1,length) * sum(x2,length)) / length
S22 = sum(sqrt(x2),length) - sqrt(sum(x2,length)) / length
Sy1 = sum (y*x1,length) - (sum(y,length) * sum(x1,length)) / length
Sy2 = sum (y*x2,length) - (sum(y,length) * sum(x2,length)) / length
//
max1 = sma(x1,length)
max2 = sma(x2,length)
may = sma(y,length)
b2 = ((Sy1 * S22) - (Sy2*S12))/(S22*S11 - sqrt(S12))
b3 = ((Sy2 * S11) - (Sy1 * S12))/(S22 * S11 - sqrt(S12))
b1 = may - b2*max1 - b3*max2
qr = b1 + b2*x1 + b3*x2
//
yl = low
//
Sy1l = sum(yl*x1,length) - (sum(yl,length) * sum(x1,length)) / length
Sy2l = sum(yl*x2,length) - (sum(yl,length) * sum(x2,length)) / length
//
mayl = sma(yl,length)
b2l = ((Sy1l * S22) - (Sy2l*S12))/(S22*S11 - sqrt(S12))
b3l = ((Sy2l * S11) - (Sy1l * S12))/(S22 * S11 - sqrt(S12))
b1l = mayl - b2l*max1 - b3l*max2
qrl = b1l + b2l*x1 + b3l*x2
//
period = round(p/2)+1
hh = qr
ll = qrl
countH = 0
countL = 0
buy=0
sell=0
//
for i = 1 to period-1
if qr ll
countL:=countL+1
for i = period+1 to p+1
if qr ll
countL:=countL+1
if countH==p
pivotH = high
buy := 1
if countL==p
pivotL = low
sell := 1
//
Angulo(_serie) =>
atan( _serie - _serie ) * 180 / acos(-1)
//calcular elvwap
vxp = volume*hlc3
//:= signo de acumulador
acumaldor_vxp := acumaldor_vxp + vxp
acomuldor_vol := acomuldor_vol + volume
vwap2 = acumaldor_vxp / acomuldor_vol
pendiente = Angulo(vwap2)
//
plotshape(buy == 1 , text='⬆️', style=shape.arrowup, location=location.belowbar, color=#32CD32, textcolor=color.white, offset=0, transp=0,size=size.auto)
if buy == 1
alert("Posible long",alert.freq_all )
plotshape(sell == 1 , text='⬇️', style=shape.arrowdown, location=location.abovebar, color=#FF0000, textcolor=color.white, offset=0, transp=0,size=size.auto)
if sell == 1
alert("Posible short",alert.freq_all )
//
//if (backTestPeriod())
//strategy.entry("long", true, 1, when = buy == 1)
// strategy.entry("short", false, 1, when = sell == 1)
if buy == 1 and pendiente > angulo_permitido
//if buy == 1
cantidad = round(strategy.equity / close )
strategy.entry("long", true, cantidad, comment = "Compra")
sl := close * ( 1 - (stop_loss/100))
tp := close * ( 1 + (take_profit/100))
if sell == 1 and pendiente > angulo_permitido
//if sell == 1
cantidad = round(strategy.equity / close )
strategy.entry("short", false, cantidad, comment = "Venta")
sl := close * ( 1 + (stop_loss/100))
tp := close * ( 1 - (take_profit/100))
//Validaciones
comprado = strategy.position_size > 0 //true si es positivo
vendido = strategy.position_size < 0 //true si es negativo
if comprado
//Salir sl
if close >= tp
//plotshape(close >= tp, style=shape.xcross)
strategy.close("long", comment="TP")
//Salir tp
if close <= sl
strategy.close("long", comment="SL")
if vendido
//Salir sl
if close <= tp
strategy.close("short", comment="TP")
//Salir tp
if close >= sl
strategy.close("short", comment="SL")
//sl tp
plot( sl , color =color.red, style=plot.style_cross)
plot( tp , color= color.green , style=plot.style_circles)
//color
//bgcolor (comprado ? color.green: na)
//bgcolor (vendido ? color.red: na)
//if pintar_trade
//bgcolor (close >= tp ? color.green : na, transp=80)
//bgcolor (close >= sl ? color.red : na, transp=80)
VIPThis indicator is using the modified "SSS".
This strategy uses combined indicators to create LONG entry points, the strategy was first found by saudALThaidy.
How to use: Open your asset and pick a timeframe between 5min and 2hours (recommended: 30min, 45min), the strategy will give entry points itself, you can monitor and take profit manually(recommended), or you can use the exit setup.
exit setup:
Take Profit : close the trade and take profit after the specified percentage from the entry point gets hit.
Use Stop Percentage : if false, trade will be closed if it gets below MA line, if true it will use the next set up.
StopLose Percentage : specify a percentage to close the trade if the asset price goes below it.
Important Notes:
As saudALThaidy states that the strategy must be used with -heiken ashi- candles for the best result.
for best use of the strategy, use (Take Profit = 1,Use Stop Percentage=false) to get every trade, and take profit manually when ever you see the best.
For any notes on the strategy to be edited, or for another strategies ideas please comment.