DZ Strategy ICTThe script presented is a trading strategy called "Breaker Block Strategy with Price Channel". This strategy uses multiple time frames (1 minute, 5 minutes, 15 minutes, 1 hour, and 4 hours) to detect support and resistance areas on the chart.
The strategy uses parameters such as length, deviations, multiplier, Fibonacci level, move lag and volume threshold for each time frame. These parameters are adjustable by the user.
The script then calculates support and resistance levels using the simple moving average (SMA) and standard deviation (STDEV) of closing prices for each time frame.
It also detects "Breaker Blocks" based on price movement from support and resistance levels, as well as trade volume. A Breaker Block occurs when there is a significant breakout of a support or resistance level with high volume.
Buy and sell signals are generated based on the presence of a Breaker Block and price movement from support and resistance levels. When a buy signal is generated, a buy order is placed, and when a sell signal is generated, a sell order is placed.
The script also plots price channels for each time frame, representing resistance and support levels.
Profit limit levels are set for each time range, indicating that the price levels assigned to positions should be closed with a profit. Stop-loss levels are also set to limit losses in the event of canceled price movements.
In summary, this trading strategy uses a combination of Breaker Block detection, support and resistance levels, price channels and profit limit levels to generate buy and sell signals and manage positions on different time ranges.
Portfolio management
Risk Reward Calculator [lovealgotrading]
OVERVIEW:
This Risk Reward Calculator strategy can help you maximize your RR value with help of algorithmic trading.
INDICATOR:
I wanted to setup my trades more easier with this indicator, I didn't want to calculate everytime before orders, with help this indicator we can calculate R:R value, avarage price, stoploss price, take-profit price, order prices, all position cost and more ...
Our strategy is a risk revard calculation indicator that is made easy to use by using visualized lines and panels, and also has algorithmic trading support.
With the help of this indicator, we can quickly and easily calculate our risk reward values and enter the positions.
If we want to ensure that our balance grows regularly while trading in the stock market, we need to manage the risks and rewards otherwise we may fall below our initial balance at the end of the day, even if we seem to be winning.
What is the Risk-Reward value ?
This value is a value that shows how many times the amount of risk we take when entering the position is successful, we will earn.
- For example, you risked $100 while entering the trade, so if your trade stops, you will lose 100 $.
Your Risk-Reward(RR) value is 2 means that if your position is successful, you will have 200 $ in your pocket.
A trader's success is determined by the amount of R he earns monthly or yearly, not how much money he makes.
What is different in this indicator ?
I want to say thank you to © EvoCrypto. His Calculator (weighted) – evo indicator helped me when I was developed my indicator.
I want to explain what I have improved:
1-In this strategy, we can determine the time period in which we want to open our positions.
2-We can open a maximum of 4 positions in the same direction and close our positions at a single level. StopLoss or TakeProfit
3-This indicator, which works in the form of a strategy, shows where our positions have been opened or closed. With the help of this, it helps us to determine our strategy in our future positions more accurately.
4-The most important improvement is that we do not miss our positions with the help of alarms (WEB HOOK). if we want, we receive by quickly connecting all these positions to our robot, the software can enter and exit the position while we are busy.
IMPLEMENTATION DETAILS – SETTINGS:
1 - We can set the start and end dates of the positions we will take.
2- We can set our take profit, stoploss levels.
3- If your trade is stopped, we can determine the amount of the trade that we will lose.
4- We can adjust our entry levels to positions and our position sizes at entry levels.
(Sum of positions weight must be 100%)
5- We can receive our positions even if we are busy with the help of algorithmic trading. For this, we must paste our Jshon codes into the fields specified in the settings panel.
6- Finally, we can change the settings we want and don't want to have in our visual elements.
Let's make a LONG side example together
We have determined our positions to enter stoploss, take profit and long positions. We did not forget to set the start time of our strategy
Our strategy appear on the graph as follows.
Our strategy has calculated the total position size, our R-R value, the distance of the current price to the stop and take profit levels, in short, a lot of things we could look visually.
Notes:
If you're going to connect this bot to an automatic Long or Short direction,
Don’t forget! you need to Webhook URL,
Don’t miss paste this code to your message window {{strategy.order.alert_message}}
ALSO:
If you have any ideas what to add to my work to add more sources or make calculations cooler, feel free to write me.
Lorentzian Classification Strategy Based in the model of Machine learning: Lorentzian Classification by @jdehorty, you will be able to get into trending moves and get interesting entries in the market with this strategy. I also put some new features for better backtesting results!
Backtesting context: 2022-07-19 to 2023-04-14 of US500 1H by PEPPERSTONE. Commissions: 0.03% for each entry, 0.03% for each exit. Risk per trade: 2.5% of the total account
For this strategy, 3 indicators are used:
Machine learning: Lorentzian Classification by @jdehorty
One Ema of 200 periods for identifying the trend
Supertrend indicator as a filter for some exits
Atr stop loss from Gatherio
Trade conditions:
For longs:
Close price is above 200 Ema
Lorentzian Classification indicates a buying signal
This gives us our long signal. Stop loss will be determined by atr stop loss (white point), break even(blue point) by a risk/reward ratio of 1:1 and take profit of 3:1 where half position will be closed. This will be showed as buy.
The other half will be closed when the model indicates a selling signal or Supertrend indicator gives a bearish signal. This will be showed as cl buy.
For shorts:
Close price is under 200 Ema
Lorentzian Classification indicates a selling signal
This gives us our short signal. Stop loss will be determined by atr stop loss (white point), break even(blue point) by a risk/reward ratio of 1:1 and take profit of 3:1 where half position will be closed. This will be showed as sell.
The other half will be closed when the model indicates a buying signal or Supertrend indicator gives a bullish signal. This will be showed as cl sell.
Risk management
To calculate the amount of the position you will use just a small percent of your initial capital for the strategy and you will use the atr stop loss or last swing for this.
Example: You have 1000 usd and you just want to risk 2,5% of your account, there is a buy signal at price of 4,000 usd. The stop loss price from atr stop loss or last swing is 3,900. You calculate the distance in percent between 4,000 and 3,900. In this case, that distance would be of 2.50%. Then, you calculate your position by this way: (initial or current capital * risk per trade of your account) / (stop loss distance).
Using these values on the formula: (1000*2,5%)/(2,5%) = 1000usd. It means, you have to use 1000 usd for risking 2.5% of your account.
We will use this risk management for applying compound interest.
> In settings, with position amount calculator, you can enter the amount in usd of your account and the amount in percentage for risking per trade of the account. You will see this value in green color in the upper left corner that shows the amount in usd to use for risking the specific percentage of your account.
> You can also choose a fixed amount, so you will have to activate fixed amount in risk management for trades and set the fixed amount for backtesting.
Script functions
Inside of settings, you will find some utilities for display atr stop loss, break evens, positions, signals, indicators, a table of some stats from backtesting, etc.
You will find the settings for risk management at the end of the script if you want to change something or trying new values for other assets for backtesting.
If you want to change the initial capital for backtest the strategy, go to properties, and also enter the commisions of your exchange and slippage for more realistic results.
In risk managment you can find an option called "Use leverage ?", activate this if you want to backtest using leverage, which means that in case of not having enough money for risking the % determined by you of your account using your initial capital, you will use leverage for using the enough amount for risking that % of your acount in a buy position. Otherwise, the amount will be limited by your initial/current capital
I also added a function for backtesting if you had added or withdrawn money frequently:
Adding money: You can choose how often you want to add money (Monthly, yearly, daily or weekly). Then a fixed amount of money and activate or deactivate this function
Withdraw money: You can choose if you want to withdraw a fixed amount or a percentage of earnings. Then you can choose a fixed amount of money, the period of time and activate or deactivate this function. Also, the percentage of earnings if you choosed this option.
Some other assets where strategy has worked
BTCUSD 4H, 1D
ETHUSD 4H, 1D
BNBUSD 4H
SPX 1D
BANKNIFTY 4H, 15 min
Some things to consider
USE UNDER YOUR OWN RISK. PAST RESULTS DO NOT REPRESENT THE FUTURE.
DEPENDING OF % ACCOUNT RISK PER TRADE, YOU COULD REQUIRE LEVERAGE FOR OPEN SOME POSITIONS, SO PLEASE, BE CAREFULL AND USE CORRECTLY THE RISK MANAGEMENT
Do not forget to change commissions and other parameters related with back testing results!. If you have problems loading the script reduce max bars back number in general settings
Strategies for trending markets use to have more looses than wins and it takes a long time to get profits, so do not forget to be patient and consistent !
Please, visit the post from @jdehorty called Machine Learning: Lorentzian Classification for a better understanding of his script!
Any support and boosts will be well received. If you have any question, do not doubt to ask!
*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
Breakeven Line DemoPlug the breakeven line code into the bottom of your strategy to get visualization of your breakeven price. Line is green when net position is long, red when net short and invisible when strategy is risk neutral. Most useful for strategies which use pyramiding (successive entries in same direction stacked upon each other) as it can be difficult to track where prices needs to return to to allow closing in profit. Disclaimer: the strategy logic is garbage do not use it. It is only there so you can see how Breakeven Line logic is implemented.
[MT] Strategy Backtest Template| Initial Release | | EN |
An update of my old script, this script is designed so that it can be used as a template for all those traders who want to save time when programming their strategy and backtesting it, having functions already programmed that in normal development would take you more time to program, with this template you can simply add your favorite indicator and thus be able to take advantage of all the functions that this template has.
🔴Stop Loss and 🟢Take Profit:
No need to mention that it is a Stop Loss and a Take Profit, within these functions we find the options of: fixed percentage (%), fixed price ($), ATR, especially for Stop Loss we find the Pivot Points, in addition to this, the price range between the entry and the Stop Loss can be converted into a trailing stop loss, instead, especially for the Take Profit we have an option to choose a 1:X ratio that complements very well with the Pivot Points.
📈Heikin Ashi Based Entries:
Heikin Ashi entries are trades that are calculated based on Heikin Ashi candles but their price is executed to Japanese candles, thus avoiding false results that occur in Heikin candlestick charts, this making in certain cases better results in strategies that are executed with this option compared to Japanese candlesticks.
📊Dashboard:
A more visual and organized way to see the results and necessary data produced by our strategy, among them we can see the dates between which our operations are made regardless if you have activated some time filter, usual data such as Profit, Win Rate, Profit factor are also displayed in this panel, additionally data such as the total number of operations, how many were gains and how many losses, the average profit and loss for each operation and finally the maximum profits and losses followed, which are data that will be very useful to us when we elaborate our strategies.
Feel free to use this template to program your own strategies, if you find errors or want to request a new feature let me know in the comments or through my social networks found in my tradingview profile.
| Update 1.1 | | EN |
➕Additions: '
Time sessions filter and days of the week filter added to the time filter section.
Option to add leverage to the strategy.
5 Moving Averages, RSI, Stochastic RSI, ADX, and Parabolic Sar have been added as indicators for the strategy.
You can choose from the 6 available indicators the way to trade, entry alert or entry filter.
Added the option of ATR for Take Profit.
Ticker information and timeframe are now displayed on the dashboard.
Added display customization and color customization of indicator plots.
Added customization of display and color plots of trades displayed on chart.
📝Changes:
Now when activating the time filter it is optional to add a start or end date and time, being able to only add a start date or only an end date.
Operation plots have been changed from plot() to line creation with line.new().
Indicator plots can now be controlled from the "plots" section.
Acceptable and deniable range of profit, winrate and profit factor can now be chosen from the "plots" section to be displayed on the dashboard.
Aesthetic changes in the section separations within the settings section and within the code itself.
The function that made the indicators give inputs based on heikin ashi candles has been changed, see the code for more information.
⚙️Fixes:
Dashboard label now projects correctly on all timeframes including custom timeframes.
Removed unnecessary lines and variables to take up less code space.
All code in general has been optimized to avoid the use of variables, unnecessary lines and avoid unnecessary calculations, freeing up space to declare more variables and be able to use fewer lines of code.
| Lanzamiento Inicial | | ES |
Una actualización de mi antiguo script, este script está diseñado para que pueda ser usado como una plantilla para todos aquellos traders que quieran ahorrar tiempo al programar su estrategia y hacer un backtesting de ella, teniendo funciones ya programadas que en el desarrollo normal te tomaría más tiempo programar, con esta plantilla puedes simplemente agregar tu indicador favorito y así poder aprovechar todas las funciones que tiene esta plantilla.
🔴Stop Loss y 🟢Take Profit:
No hace falta mencionar que es un Stop Loss y un Take Profit, dentro de estas funciones encontramos las opciones de: porcentaje fijo (%), precio fijo ($), ATR, en especial para Stop Loss encontramos los Pivot Points, adicionalmente a esto, el rango de precio entre la entrada y el Stop Loss se puede convertir en un trailing stop loss, en cambio, especialmente para el Take Profit tenemos una opción para elegir un ratio 1:X que se complementa muy bien con los Pivot Points.
📈Entradas Basadas en Heikin Ashi:
Las entradas Heikin Ashi son operaciones que son calculados en base a las velas Heikin Ashi pero su precio esta ejecutado a velas japonesas, evitando así́ los falsos resultados que se producen en graficas de velas Heikin, esto haciendo que en ciertos casos se obtengan mejores resultados en las estrategias que son ejecutadas con esta opción en comparación con las velas japonesas.
📊Panel de Control:
Una manera más visual y organizada de ver los resultados y datos necesarios producidos por nuestra estrategia, entre ellos podemos ver las fechas entre las que se hacen nuestras operaciones independientemente si se tiene activado algún filtro de tiempo, datos usuales como el Profit, Win Rate, Profit factor también son mostrados en este panel, adicionalmente se agregaron datos como el número total de operaciones, cuantos fueron ganancias y cuantos perdidas, el promedio de ganancias y pérdidas por cada operación y por ultimo las máximas ganancias y pérdidas seguidas, que son datos que nos serán muy útiles al elaborar nuestras estrategias.
Siéntete libre de usar esta plantilla para programar tus propias estrategias, si encuentras errores o quieres solicitar una nueva función házmelo saber en los comentarios o a través de mis redes sociales que se encuentran en mi perfil de tradingview.
| Actualización 1.1 | | ES |
➕Añadidos:
Filtro de sesiones de tiempo y filtro de días de la semana agregados al apartado de filtro de tiempo.
Opción para agregar apalancamiento a la estrategia.
5 Moving Averages, RSI, Stochastic RSI, ADX, y Parabolic Sar se han agregado como indicadores para la estrategia.
Puedes escoger entre los 6 indicadores disponibles la forma de operar, alerta de entrada o filtro de entrada.
Añadido la opción de ATR para Take Profit.
La información del ticker y la temporalidad ahora se muestran en el dashboard.
Añadido personalización de visualización y color de los plots de indicadores.
Añadido personalización de visualización y color de los plots de operaciones mostradas en grafica.
📝Cambios:
Ahora al activar el filtro de tiempo es opcional añadir una fecha y hora de inicio o fin, pudiendo únicamente agregar una fecha de inicio o solamente una fecha de fin.
Los plots de operaciones han cambiados de plot() a creación de líneas con line.new().
Los plots de indicadores ahora se pueden controlar desde el apartado "plots".
Ahora se puede elegir el rango aceptable y negable de profit, winrate y profit factor desde el apartado "plots" para mostrarse en el dashboard.
Cambios estéticos en las separaciones de secciones dentro del apartado de configuraciones y dentro del propio código.
Se ha cambiado la función que hacía que los indicadores dieran entradas en base a velas heikin ashi, mire el código para más información.
⚙️Arreglos:
El dashboard label ahora se proyecta correctamente en todas las temporalidades incluyendo las temporalidades personalizadas.
Se han eliminado líneas y variables innecesarias para ocupar menos espacio en el código.
Se ha optimizado todo el código en general para evitar el uso de variables, líneas innecesarias y evitar los cálculos innecesarios, liberando espacio para declarar más variables y poder utilizar menos líneas de código.
Key Performance IndicatorWe are happy to introduce the Key Performance Indicator by Detlev Matthes. This is an amazing tool to quantify the efficiency of a trading system and identify potential spots of improvement.
Abstract
A key performance indicator with high explanatory value for the quality of trading systems is introduced. Quality is expressed as an indicator and comprises the individual values of qualitative aspects. The work developing the KPI was submitted for the 2017 VTAD Award and won first prize.
Introduction
Imagine that you have a variety of stock trading systems from which to select. During backtesting, each trading system will deliver different results with regard to its indicators (depending on, inter alia, its parameters and the stock used). You will also get different forms of progression for profit development. It requires great experience to select the “best” trading system from this variety of information (provided by several indicators) and significantly varying equity progression forms. In this paper, an indicator will be introduced that expresses the quality of a trading system in just one figure. With such an indicator, you can view the results of one backtest at a glance and also more easily compare a variety of backtesting results with one another.
If you are interested in learning more about the calculations behind this indicator then I have included a link to the english version of his research paper.
Along with this, we now offer indicator development services. If you are interested in learning more then feel free to reach out to get a quote for your project.
**Please note that we have NOT inputted any real strategy into the code and therefore it is not producing any real value. Feel free to change the code as desired to test any strategy!**
drive.google.com
RELATIVE VALUE TRADE MANAGEMENT WEBHOOKThis script it's created to send open-close signals via webhook. It allows you to open a relative value position based in the relative graph. You can set the TP and SL levels and the script will send the signal to your exchange.
Due a pine limitations it is necessary apply the script in the 2 different actives and set the alerts. You can just do the relative analysis and then go to the first asset and set the script. Create your alert and then just go to the other asset and create the alert. It doesn't necessary to change anything in the script because the levels are the same.
It is also possible to do the analysis using the script, deploying the relative graph, but could be annoying sometimes due scales.
Positions will be placed at close always.
THIS IS IMPORTANT: I use Zignaly as a exhange so if you are using Binance or other YOU MUST CHANGE the code. If you know the JSON format that It requires would be easy.
Here is tips in all the important imputs. But let me explain the most important.
The MANDATORY fields are:
Ticker IDs: Here you must write the EXACT ID code for the active. Caps included.
Example : BINANCE:SUSHIUSDTPERP
It is also important select the correct market side. If you want to be long of ANY active you must write that ID in the LONG ID. For short positions is the same.
Time frame: Here you can select the time frame of the graph (not the current active graph, I mean the relative one.) The orders will be send using that time frame. I recommend to do the analysis in other window and then use the script to trigger the order in the time frame that you want.
Money management: In these fields you can select the qty that you will lose if the SL level is reach. Based in a determinated amount of currency or in a % of your capital.
Dates: It is important to select the start date. If the order is already open, we must look for the moment where the activation price was reached. If the order is unopened it is better to select the current date, so the order will be triggered when the entry level is reached.
Ids: If you have current open position you can set here that ID to send the correct order to the exchange.
To set the alert just call the function {{{strategy.order.alert_message}}}
Strategy Multiple Orders + Statistics Template - EducationalHello traders
It's been a while
We're back in a bear market so I have a bit more time to publish new Pine scripts for the TradingView community
Special thanks to @fikira for his Multiple Orders script () and to @carnagecain for allowing me to publish this script we worked together on
I got widely inspired by @fikira's script for that one
This script is for educational purposes only - I wanted to show how we can add multiple TPs/SL + a table with custom statistics
In this Strategy template, users can define multiple take-profit and multiple stop-loss levels.
Basically, we have 4 trades per trend and each trade has its own SL/TP
Statistics
Stats are split per trade direction (Long, Short) and then consolidated
I put custom stats in that table such as:
- Probability of Win
- Probability of Loss
- Avg Profit/Loss per Trade
- APPT: (Probability of Win * Average Gross Profit) - (Probability of Loss * Average Loss)
- Number of times each TP/SL has been hit
I'm catching up with all recent pinescript features as we speak - more educational scripts template to come soon
Best Regards
Dave
Solution Zigma - Fibonacci Impulse'Solution Zigma' is strategy for any securities because this strategy use EMA of Fibonacci Level and Plot Like candle easy for analysis trend impulse. This strategy used DMI(ADX) for filter sideway but not greatest indicator, Please use this strategy with Risk Management.
Swing Stock designed for Monthly/Yearly Trading This is a strategy tester designed around the most important data from FRED - Federal Reserve Economic Data
As input data, we have:
// Personal Consumption Expenditures
// Real Retail and Food Services Sales
// Leading Index for the United States
// All Employees: Total Nonfarm Payrolls
// Real Gross Domestic Product
// Gross Domestic Product
I adapted the long and short entry based on the GDP data, since they are most accurate in prediction compared to the rest.
However, feel free to test with other as well if you want.
For this test I compared previous GDP values, if they were higher than previous that represent a long signals, if they were smaller that represents a reversal=short signal.
From the tests performed we can see that GDP is highly accurate and overall as long as there is patience, profits are going to be make, sometimes even beat the index itself.
If you have any questions, let me know !
MilleMachineHello traders,
I hereby present to you the second stage of my journey to finding a reliable, profitable trading strategy.
The "Millemachine" is based on the "Millebot", my previous published strategy. This means the backbone of the strategy is still the same: a trend following system. Instead of using a fixed TP and SL, a trailing stoploss is now used. To limit the losses when the trend weakens, the trailing stoploss automatically gets smaller, as it is based on the ATR.
A new utility is you can now easily switch between indicators on which the decision making is based. This allows the user to discover which indicators work best for entry, long/short switching and stoploss configuration.
The strategy has been proven to be very profitable in trending markets, but can suffer losses during ranging market. To make the system more robust, the strategy cannot solely rely on a trending system. Other systems must be added.
I believe that a good trading bot must consist of more than 4 different strategies, based on different systems. This is what I am currently working on.
My goal for publishing this strategy is to help other traders build their own. In my journey I found it difficult to find a good strategy that employs a decent risk management, which is truly essential for having good, consistent results. Also, a realistic commission needs to be defined to have a realistic performance prediction. This weighs on the profitability and therefore is often set at 0 by authors of other strategies, which I find misleading.
If you have found this strategy informative or useful, please leave a comment.
Greetings Michael
Trading the Equity Curve Position Sizing Example"Trading the equity curve" as a risk management method is the process of acting on trade signals depending on whether a system’s performance is indicating the strategy is in a profitable or losing phase.
The point of managing equity curve is to minimize risk in trading when the equity curve is in a downtrend. This strategy has two modes to determine the equity curve downtrend: By creating two simple moving averages of a portfolio's equity curve - a short-term and a longer-term one - and acting on their crossings. If the fast SMA is below the slow SMA, equity downtrend is detected (smafastequity < smaslowequity).
The second method is by using the crossings of equity itself with the longer-period SMA (equity < smasloweequity).
When Trading with the Equity Curve" is active, the position size will be reduced by a specified percentage if the equity is "under water" according to a selected rule. If you're a risk seeker, select "Increase size by %" - for some robust systems, it could help overcome their small drawdowns quicker.
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!
Portfolio Performance - Effects of RebalancingFunction:
- Can be used to evaluate the performance of a portfolio containing 2 assets over a set time interval
- Shows the % return of the portfolio over the time interval defined by the user
- Includes a threshold rebalancing algorithm to show the effects that rebalancing has on the portfolio over the long term
- Created to evaluate of the performance of portfolios containing different weightings of stocks and bonds over time assuming that the user would rebalance the portfolio when asset weights crossed a threshold
Instructions:
- To be used with dividends adjustments turned on
- Add this script to a symbol. e.g. AMEX:SPY
- Click the chart to define the entry time and the exit time. i.e. the time interval
- Define the initial investment of the portfolio. Default setting is $100,000
- Define the second asset to be included in the portfolio. e.g. BATS:AGG
- The strategy comes pre-populated with a portfolio that has a weight of 80% asset 1 and 20% asset 2. i.e. 80% AMEX:SPY and 20% BATS:AGG if the symbols mentioned above were chosen
- The 7 lines show the weighted % return of each portfolio over the time period defined by the user
- Each line (except the blue) is the return based on a different rebalancing threshold. The default settings are 1%, 2.5%, 5%, 10%, 15%, 20%, 30%
- The blue line is the % return of a portfolio that was made up of 100% asset 1 over the time interval. i.e. 100% AMEX:SPY
- Asset weights and rebalancing thresholds are adjustable via the settings
- Each plot can be turned on and turned off via a tick box in the settings
Portfolio Performance - 2 AssetsFunction:
- Can be used to evaluate the performance of portfolios containing 2 assets over a set time interval
- Created to evaluate of the performance of portfolios containing different weightings of stocks and bonds over time
- Shows the % return of each portfolio over the time interval defined by the user
- Capable of showing the risk adjusted % return of each portfolio over the time interval defined by the user (setting turned off by default)
Instructions:
- To be used with dividends adjustments turned on
- Add this script to a symbol. e.g. NASDAQ:BND
- Click the chart to define the entry time and the exit time. i.e. the time interval
- Define the second asset to be included in the portfolio. e.g. AMEX:VOO
- The strategy comes pre-populated with 6 portfolios with the most common stock/bond weightings (100% stocks/0% bonds, 80% stocks/20% bonds, 60% stocks/40% bonds, et cetera)
- The 6 lines show the weighted % return of each portfolio over the time period defined by the user
- All asset weights are adjustable via the settings
- Each plot can be turned on and turned off via a tick box in the settings
- There are 6 plots that show the risk adjusted returns of each portfolio (setting turned off by default)