2 Moving Averages | Trend FollowingThe trading system is a trend-following strategy based on two moving averages (MA) and Parabolic SAR (PSAR) indicators.
How it works:
The strategy uses two moving averages: a fast MA and a slow MA.
It checks for a bullish trend when the fast MA is above the slow MA and the current price is above the fast MA.
It checks for a bearish trend when the fast MA is below the slow MA and the current price is below the fast MA.
The Parabolic SAR (PSAR) indicator is used for additional trend confirmation.
Long and short positions can be turned on or off based on user input.
The strategy incorporates risk management with stop-loss orders based on the Average True Range (ATR).
Users can filter the backtest date range and display various indicators.
The strategy is designed to work with the date range filter, risk management, and user-defined positions.
Features:
Trend-following strategy.
Two customizable moving averages.
Parabolic SAR for trend confirmation.
User-defined risk management with stop-loss based on ATR.
Backtest date range filter.
Flexibility to enable or disable long and short positions.
This trading system provides a comprehensive approach to trend-following and risk management, making it suitable for traders looking to capture trends with controlled risk.
Portfolio management
Renko StrategyRENKO STRATEGY
CAUTION : This strategy must be applied to a candlestick chart (not a Renko chart).
INTRODUCTION :
The Traditional Renko chart has been reproduced and is plotted according to the evolution of the price. It will enable us to receive buy or sell signals and follow major trends. This is a medium/long term strategy and depends a lot on the box size chosen in the parameters. There's also a money management method allowing us to reinvest part of the profits or reduce the size of orders in the event of substantial losses.
RENKO CHART :
Renko chart construction methodology :
The user must first choose the box size. The minimum is 0.00001 and there is no maximum. The default is 10. The user must then choose the source that will define the data on which the calculations will be based (high, low, open, close). By default, close is selected. The first candle on the chart is used to draw the first box with its high and low.
Each time the price changes by the amount of the box size relative to the high or low of the last box, a new box is added above or below the previous one. If price variations are less than the box size, the same box is added next to the previous one. If price variations are N (integer number) times greater than box size, N boxes are added above or below the previous one. Each box added above the previous one is a green box, while each box added below the previous one is a red box.
Conditions for drawing a green box above the previous one :
(source - high_of_the_last_box) / box_size > 1
Condition for drawing a red box below the previous one :
(low_of_the_last_box - source) / box_size > 1
If neither condition is triggered, the same box is drawn next to the previous one.
Example :
The last candle has drawn a box with low 12 and high 14. The box size is therefore 2. The strategy will look at the value of the close each time a candle ends. The current candle closes with a close equal to 15.5. As the variation from the previous high is only 1.5 (which is less than the box size), the same box is added next to the previous one. The next candle closes at 16.2. The price variation is therefore 2.2 compared with the previous high. We can now add a new green box just above the previous one, with a low of 14 and a high of 16. The same process applies if the candle's close is at least one box size below the low of the last box. In this case, a new red box is placed below the previous one.
PARAMETERS :
Source : Allows you to specify which data will be taken into account by the strategy when performing calculations. The default is close.
Box size : Size of Renko graph boxes. This is a very important parameter to choose carefully, as it has a strong impact on the strategy's performance. Defaults to 10.
Fixed Ratio : This is the amount of gain or loss at which the order quantity is changed. The default is 400, meaning that for each $400 gain or loss, the order size is increased or decreased by a user-selected amount.
Increasing Order Amount : This is the amount to be added to or subtracted from orders when the fixed ratio is reached. The default is $200, which means that for every $400 gain, $200 is reinvested in the strategy. On the other hand, for every $400 loss, the order size is reduced by $200.
Initial capital : $1000
Fees : Interactive Broker fees apply to this strategy. They are set at 0.18% of the trade value.
Slippage : 3 ticks or $0.03 per trade. Corresponds to the latency time between the moment the signal is received and the moment the order is executed by the broker.
Important : A bot has been used to test all possible box sizes to find out which one generates the highest return on BITSTAMP:LTCUSD while limiting the drawdown. This strategy is the most optimal with a box size equal to 5.08 in 8h timeframe.
BUY AND SHORT SIGNALS :
As the aim of this strategy is to follow major trends based on price movements, we need to be on the right side of price fluctuation. We trade every box reversal, i.e. we are LONG when the boxes are green indicating an uptrend and SHORT when they are red indicating a downtrend.
RISK MANAGEMENT :
This strategy can incur losses. The size of the box is decisive, as it is used to plot the RENKO chart and thus trigger buy or sell signals. It's also what allows us to manage risk. For every trade, we risk a maximum amount equal to 2 times the size of the box, i.e. :(5.08*2*nb_contract)/trade_value.
MONEY MANAGEMENT :
The fixed ratio method has been used to manage our gains and losses. For each gain of an amount equal to the value of the fixed ratio, we increase the order size by a value defined by the user in the "Increasing order amount" parameter. Similarly, each time we lose an amount equal to the value of the fixed ratio, we decrease the order size by the same user-defined value. This strategy not only increases our performance, but also our drawdown.
Enjoy the strategy and don't forget to take the trade :)
Bonsai BX (Backtester)In today's trading landscape, traders need precision and deep analytical tools to navigate the sea of strategies. The Bonsai Backtester is one such tool, meticulously designed to evaluate multiple trading strategies in an integrated manner.
═════════════════════════════════════════════════════════════════════════
🌳 Bonsai BX 🌳 Universal Strategy Testing
📘 Overview
A product of collaboration with the Bonsai community, this backtester is both a reflection of collective insights and a means to provide traders with data-driven insights on TradingView.
📌 Current Backtest
• Dataset: BTCUSD daily candles from Coinbase, starting from March 2015.
• Source Signals: The Bonsai indicator signals are employed for both long and short entries. These are directly visible on the publication chart.
• Trading Assumptions:
• Initial Capital: $1,000
• Maximum Position Size: 10% of equity per trade
• Stop Loss: 10% per position
• Commission: 0.1%
• Slippage: 100 ticks (1.00)
🛠 Key Features
The Bonsai BX is equipped with a range of features aimed at providing traders with a more comprehensive analysis environment:
Features on Chart
• External Indicator Adaptability: Easily incorporate signals from both built-in and custom TradingView indicators.
• Snapshot Table: Delivers on-the-spot insights into crucial strategy performance metrics, including equity, open profit, position size, and entry price. While these details are available in TradingView's 'Performance Summary' panel, we've integrated them directly onto the chart for a more streamlined and accessible viewing experience.
• Trade Labels: Visualize profit metrics for individual trades directly on the chart, allowing for a more immediate grasp of trade outcomes.
• Long & Short Behaviors: Modify long behaviors to either open new long positions while closing short ones, or simply to close short positions. Conversely, for short behaviors, opt to either initiate new short positions while closing any active long ones or simply close long positions.
• Multiple Signals Integration: The tool can currently handle up to three different external signals for long and short trades.
• Condition-based Initiation: Define whether longs and shorts are triggered when 'All Conditions Met' or just 'Any Single Condition Met'. This flexibility allows for a more nuanced trading approach. For example, if you're using a trade signal alongside the RSI, you can specify that a long position should only open when the trade signal is active and the RSI is below 30 at the same time. This lets you combine multiple signals or conditions for more precise trade initiation.
• TP & SL Customization:
• Single TP: Set a specific Take Profit percentage.
• SL: Define a Stop Loss percentage and choose between a standard or trailing stop.
• Trail From: Specify the starting point of the trailing stop, be it the breakeven point or a certain percentage.
• Interface Theme: Users can select between light and dark themes for their interface.
Performance and Trailing
🎛 Using Bonsai BX
1. Add it to your TradingView chart.
2. Adjust script parameters and settings. Integrate external indicator signals as needed.
3. Activate the backtester to refine trading strategies.
Backtester Settings Menu
🪝 Webhook (Beta)
The Webhook functionality, now in beta, augments the Bonsai BX utility. This feature offers a more intuitive method for users to direct webhooks to trading bots, exchanges, and brokers. It simplifies the process by eliminating the need to adjust JSON structures or other payload formats, making alert automation more accessible.
📜 Feedback & Community
The feedback from the Bonsai community has been instrumental in the tool's development and will continue to shape its evolution. As part of our commitment to adaptive, smart trading, this script will continually be updated to meet the ever-changing requirements of traders.
❗️ Disclaimer
Backtesting tools, including the Bonsai BX , simulate trading strategies based on historical data. The following key points should be kept in mind:
1. Past Performance is Not Predictive: While backtesting can offer insights, it's essential to understand that past performance does not guarantee or predict future results. Historical data might not account for future market changes or unforeseen events.
2. External Influences: Market outcomes can be significantly influenced by various external factors like geopolitical events, economic announcements, and sudden shifts in market sentiment. Such factors are often not considered in backtesting simulations.
3. Market Dynamics: Elements like market volatility, liquidity constraints, and slippage can drastically alter expected outcomes. These dynamics might not always be accurately represented in backtest simulations.
4. Limitations of Simulated Trades: Backtesting operates under the assumption that historical trends and patterns will replicate. However, market conditions evolve, and what worked in the past might not necessarily be viable in the future.
5. Informed Decisions: Always base your trading decisions on a mix of comprehensive research, current market analysis, and risk assessment. Relying solely on backtested results can lead to misconstrued perceptions and potential pitfalls.
Trading involves risks, and it's crucial to be fully informed and cautious before making any investment decisions. Always consider seeking advice from financial experts or professionals when in doubt.
Risk Management and Positionsize - MACD exampleMastering Risk Management
Risk management is the cornerstone of successful trading, and it's often the difference between turning a profit and suffering a loss. In light of its importance, I share a risk management tool which you can use for your trading strategies. The script not only assists in position sizing but also comes with built-in technical features that help in market timing. Let's delve into the nitty-gritty details.
Input Parameter: MarginFactor
One of the key features of the script is the MarginFactor input parameter. This element lets you control the portion of your equity used for placing each trade. A MarginFactor of -0.5 means 50% of your total equity will be deployed in placing the position size. Although Tradingview has a built-in option to adjust position sizing in a same way, I personally prefer to have the logic in my pinecode script. The main reason is userexperience in managing and testing different settings for different charts, timeframes and instruments (with the same strategy).
Stoploss and MarginFactor
If your strategy has a 4% stop-loss, you can choose to use only 50% of your equity by setting the MarginFactor to -0.5. In this case, you are effectively risking only 2% of your total capital per trade, which aligns well with the widely-accepted rule of thumb suggesting a 1-2% risk per trade. Similar if your stoploss is only 1% you can choose to change the MarginFactor to 1, resulting in a positionsize of 200% of your equity. The total risk would be again 2% per trade if your stoploss is set to 1%.
Max Drawdown and MarginFactor
Your MarginFactor setting can also be aligned with the maximum drawdown of your strategy, seen during a backtested period of 2-3 years. For example, if the max drawdown is 15%, you could calibrate your MarginFactor accordingly to limit your risk exposure.
Option to Toggle Number of Contracts
The script offers the option to toggle between using a percentage of equity for position sizing or specifying a fixed number of contracts. Utilizing a percentage of equity might yield unrealistic backtest results, especially over longer periods. This occurs because as the capital grows, the absolute position size also increases, potentially inflating the accumulated returns generated by the backtester. On the other hand, setting a fixed number of contracts as your position size offers a more stable and realistic ROI over the backtested period, as it removes the compounding effect on position sizes.
Key Features Strategy
MACD High Time Frame Entry and Exit Logic
The strategy employs a high time frame MACD (Moving Average Convergence Divergence) to make entry and exit decisions. You can easily adjust the timeframe settings and MACD settings in the inputsection to trade on lower timeframes. For more information on the HTF MACD with dynamic smoothing see:
Moving Average High Time Frame Filter
To reduce market 'noise', the strategy incorporates a high time frame moving average filter. This ensures that the trades are aligned with the dominant market trend (trading the trend). In the inputsection traders can easily switch between different type of moving averages. For more information about this HTF filter see:
Dynamic Smoothing
The script includes a feature for dynamic smoothing. The script contains The timeframeToMinutes(tf) function to convert any given time frame into its equivalent in minutes. For example, a daily (D) time frame is converted into 1440 minutes, a weekly (W) into 10,080 minutes, and so forth. Next the smoothing factor is calculated by dividing the minutes of the higher time frame by those of the current time frame. Finally, the script applies a Simple Moving Average (SMA) over the MACD, SIGNAL, and HIST values, MA filter using the dynamically calculated smoothing factor.
User Convenience: One of the major benefits is that traders don't need to manually adjust the smoothing factor when switching between different time frames. The script does this dynamically.
Visual Consistency: Dynamic smoothing helps traders to more accurately visualize and interpret HTF indicators when trading on lower time frames.
Time Frame Restriction: It's crucial to note that the operational time frame should always be lower than the time frame selected in the input sections for dynamic smoothing to function as intended.
By incorporating this dynamic smoothing logic, the script offers traders a nuanced yet straightforward way to adapt High Time Frame indicators for lower time frame trading, enhancing both adaptability and user experience.
Limitations: Exit Strategy
It's crucial to note that the script comes with a simplified exit strategy, devoid of features like a stop-loss, trailing stop-loss or multiple take profits. This means that while the script focuses on entries and risk management, it might result in higher losses if market conditions unexpectedly turn unfavorable.
Conclusion
Effective risk management is pivotal for trading success, and this TradingView script is designed to give you a better idea how to implement positions sizing with your preferred strategy. However, it's essential to note that this tool should not be considered financial advice. Always perform your due diligence and consult with financial advisors before making any trading decisions.
Feel free to use this risk management tool as building block in your trading scripts, Happy Trading!
Broadview Algorithmic StudioWelcome! This is the writeup for the Broadview Algorithmic Studio.
There are many unique features in this script.
- Broadview Underpriced & Overpriced
- Broadview Blackout Bollinger Bands
- Trailing Take Profit Suite
- Algorithmic Weights
- VSA Score
- Pip Change Log
- Activation Panel
- Weight Scanner
There are 116 primary inputs that allow users to algorithmically output unique DCA signal-sets. There are 85 inputs that allow users to control individual lengths, levels, thresholds, and multiplicative weights of the script. You will not find any other script with this many inputs, properly strung together for you to produce unlimited strategies for any market. The entire premise for the Broadview Algorithmic Studio is for users to be able to have extensive-cutting-edge features that allow them to produce more strategies, having control over every element that outputs a signal set. The number of unique strategies you can output with this script is VAST, and each continues to follow a safe DCA methodology.
This script is ready for use with 3Commas, interactive brokers, and other means of automation. It provides detailed information on Base Orders and Safety Orders, giving the number, cumulative spending, position average, and remaining balance for each SO in the series. Using this script we will explore the depths of strategic volume scaling, and the algorithms we use to determine spending.
Let me first start by saying the number of safe DCA-friendly signal-sets this script can output is absolutely staggering.
Let's limit the scope just to the Broadview Underpriced & Overpriced and Broadview Dominance indicators.
Each band of the Dominance Suite can be controlled individually with unique lengths, levels, and weights. This means the Dominance Suite can establish Bearish or Bullish dominance, in any market condition, and give it a unique overloading weight. The Broadview Underpriced & Overpriced indicator finally gives us the ability to establish these "market conditions" first with cycles. Of all the cycles this indicator establishes, the two primary are Underpriced & Overpriced. We determine this using a composite Overbought & Oversold with an Exponential Moving Average. So the script can now know, what cycle it is in, who is dominant during that cycle, and exactly how much weight in volume scaling the order should have.
Brand new is the ability for indicators of this level to be able to talk together in a single script. The Broadview Underpriced & Overpriced indicator and the Broadview Dominance indicator can inform one another across multiple vectors, create a unique market snapshot, and give that snapshot a unique weight every bar. The unique weight is compiled in the volume scaling math, thus giving us an automated-strategic-safe and quite efficient volume scaling for every order. In our coming updates we will explore this synergy to its very deepest layers. These indicators can be laced together in many ways, called vectors.
Only in the Algorithmic Studio do we explore these depths and yield those findings, features, and inputs to the user.
Let me take a quick break to explain another area-of-opportunity for our research and development.
The VSA Score is something we've tried before, but until the creation of the Broadview Blackout Bollinger Bands Auto Indicator it was not possible. The concept we want to explore is "Positional Honing". Over time we want users and the script itself to be able to understand the difference between a script-config that produces a high number of Hits, from a configuration that produces a high number of "Misses". The Volume Scaling Accuracy Score uses the BBB Auto Indicator as a heavily reliable, non-repainting, method of determining what the very-best signals for increased volume-scaling are.
Increased volume scaling is denoted by the near-white highlighter line running vertically. This line will either fall inside the BBB Auto Indicator bands (which are hidden), or, they will fall below and outside the BBB Auto bands. If increased spending happens inside the bands it's a "Miss". If increased spending happens below and outside the bands, it's a Hit. Oftentimes misses are actually pretty good spots for extra spending, which helps lower your position average, but Hits are always better. The Hits that the BBB Auto Indicator provides are extremely good.
Let's talk about the Trailing Take Profit Suite. This suite allows us to set a trailing take profit which is a feature that lets one maximize their profits. If the trailing take profit is engaged, then when the regular take profit is hit, it will trigger, denoted in red vertical lines, and the trailing take profit will look for a specified rate of change before it actually takes profit. This usually helps traders in those times when their regular take profit was set too low, allowing them to maximize their profits with a Trailing Take Profit.
For the moment, let's think about our scores. In the dashboard you'll notice a score beginning the Pip Change Log, the VSA Score, and the Activation Panel.
These scores use a new kind of logistic correlation formula where 4 digits are given to activation, rather than 1. This is to allow room for a future concept in AI we call "Deadzones" or you can think of it as impedance. This is not a bias in logistic regression. It's an entirely different concept. A neuron, which a perceptron attempts to mimic, has a bias.. but it also has a sort of electrical resistance. This is because a neuron is individually-alive entity. So a perceptron, as it were, would need to have both a bias and a natural resistance, or deadzone.
It is a lot of fun to watch the scores and how they react during playback. They tend to smooth trends but are also quite quick to correct to accuracy. In the future we will add the deadzones and biases to the scores. This should help both users and the script produce better signal sets. The Pip Change Log is an indicator that measures Rate of Change in Pips. This is one that I am particularly excited to study, as I am a huge fan of ROC. The Activation Panel shows these scores for 4 primary indicators: On Balance Volume, Relative Strength Index, Average Directional Index, and Average True Range.
Having the Pip Change Log, VSA Score, and Activation Panel up on the dashboard with their logistic correlation scores allows traders to study markets and setups quite intimately. The weight scanner at the bottom allows users to track the cumulative applied multiplicative weights during playback. The massive number of inputs, connected vectors of indicators, input-weights, lengths, levels, and thresholds sets up all the algorithmic infrastructure for powerusers to explore every idea and strategy output they could imagine. Also with the connected vector infrastructure we can deepen our indicators in a way where, "How they talk to each other.", comes first in every development conversation.
The Algorithmic Studio is for the Power-user.
These are not basic equations coming together to determine spending. This is a massive multi-layered-perceptron with everything from Trailing-Take-Profits to strategic-automatic algorithmic downscaling. The Broadview Algorithmic Studio gives a home to the poweruser who wants access to everything in a trading and investing AI, right up until the backpropagation. The Broadview Algorithmic Studio, gives users the ability to sit in the chair of the would-be AI.
Thank you.
DCA EMA Simple Bot [Starbots]
This is a simple idea of DCA trading on EMA crosses. Strategy is not repainting.
The difference between this and any other strategy is, that this script allows you to preset DCA buy triggers at desired levels and customize each DCA order size independently. Alerts are working, this strategy is easily used for automatic trading.
I mainly trade on Cryptohopper, Pionex, 3commas. This was created for community, alerts are working and non-repainting. Should work on any other as well.
Trading Condition:
It's buying when Fast EMA crosses up Slow EMA. Set your paramters.
It's selling if EMA's crosses back, signaling a sell. Optional.
DCA:
You can enter DCA on 20 custom levels or layers. It buys DCA when price hits the plotted blue line on the chart that's set by input % triggers. (buy 1st DCA at 2% drop, buy 2nd DCA at 5% drop,...)
Set your Inital Capital and Pyramiding in Properties tab, Initial Order Size and DCA Order Size (lot1,lot2,lot3,..), Order Type are changed in strategy inputs.
-By default you can see that we buy when EMA's cross up and signal a buy for 10% of equity, if market is dropping you will then place a first DCA order ( 20% equity) at 2% drop (lower) from initial order. If market keeps dropping you have more DCA levels where you can buy and average down your holding position. For selling you can use Take profit and Stop Loss targets that averages down multiple open positions, it will sell it once it reaches your desirable Take Profit and close a deal. You can also close your trade if EMA signals a sell.
Pyramiding - number of orders you can open at a time
Your first buy order is pyramiding 1. To allow it to buy 1 DCA or merge one time, set pyramding to 2.
Want to DCA 10 times? Set pyramiding at 11. (+1 always)
More features:
- Profit Calendar
- Show Balance label before every new trade
- DCA table - visualize how much of your investment is used in trades. If a background of the table is green you are okay, if the background color is red - you are using more money for orders than you actually have.
Buy Orders << Strategy Equity/Capital
- Show / Hide DCA lines - if your chart processing is getting slow you should hide some DCA levels to speed it up
- Backtesting Range - for testing the strategy in different time windows
- Alerts
When all trades are closed on your chart, winning rate of the strategy is 100% actually.
Win rate is shown differently as it's actually closing and opening every trade individually by default in TradingView system. We merge positions together and average it down into one big position to later sell for a profit (DCA).
You use this Trading Algorithm at your own risk. Do not trade before testing or invest something you cannot afford to lose on markets.
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.
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!
[pAulseperformance] PSStrategyX█ OVERVIEW
This script reduces the amount of time it takes to turn your indicator into a live trading bot.
It will convert your signals into alerts that will be sent to your exchange for trading.
The script features a broker connector to automate alert syntax and connect with third-party exchanges to live trade strategies with minimal setup.
It also includes an enhanced version of the built-in backtester with customizable options to speed up backtesting, trade-by-trade statistics, and a chart strategy summary to help traders make informed decisions.
The PSStrategyX trading tool is designed to provide traders with a range of benefits, including:
Increased confidence in their strategies.
Better understanding of the accuracy of indicator signals.
Simplified automated trading through third-party broker connections.
Reduced time to develop strategies by focusing on signal development only. No need to work with complicated strategy testing code and 3rd party automation.
█ FEATURES
Broker Connector
— Supports Autoview (More Connectors added in the future)
— Connects and auto trades with most exchanges
— No need for Webhooks (AutoView)
— Can forward test live strategies on Testnets before using real money.
Built in Backtester loaded with options to speed up backtesting
— Standard strategy features including stop loss, take profit, and various filters reduce the time and complexity involved in building a working strategy.
Trade By Trade Statistics
— Gain insight on every trade with additional trade-by-trade statistics.
Strategy Summary
— Get instant feedback on your chart of your strategies performance. Visual cues and feedback give you hints on where to look and what to improve.
Strategy Tester Enhancements
— Take the max trades allowed in the strategy tester without errors.
— Take the largest or smallest trade allowed without errors.
█ WHY?
The PSStrategyX tool was developed to solve a common problem faced by traders who use Pine Script on TradingView: the inability to integrate Pine Script with exchanges through TradingView.
Without this integration, traders need to go through several extra steps to live trade their Pine Script strategies on a real exchange with real money. This includes finding a broker, learning the new syntax for the broker, and placing that syntax correctly in the strategy.
These steps can be time-consuming and add complexity to the codebase.
The PSStrategyX tool simplifies this process by automatically configuring the correct alert syntax to connect to third-party exchanges, allowing traders to live trade their strategies with minimal setup. This saves traders time and effort, allowing them to focus on signal development rather than complicated strategy testing code and 3rd party automation.
Additionally, the tool was developed to address the time-consuming task of converting any one of the thousands of great free indicators on TradingView to strategies through hours of coding.
Overall, I built the PSStrategyX to streamline the auto trading process and make auto trading more accessible to traders of all levels.
█ HOW TO USE THIS?
Using the PSStrategyX trading tool is a straightforward process that requires a few key steps:
1 — Generate trading signals: You need a signal generator that can provide buy and sell signals for your preferred trading instrument(s).
You can use TradingView's indicators or create your own custom indicators using TradingView's Pine programming language.
2 — Connect trading signals to PSStrategyX: You will use 2 scripts on your chart. One generates buy/sell/exit signals, and the other is the PSStrategyX script executing those signals as trades.
To set this up you will need to make sure that your signal generator is an indicator, NOT a strategy.
Make sure the signals are being plotted buy = 1; sell = -1; exit = 0; signals in one plot. Exits are optional.
Example plot(buy ? 1 : sell ? -1 : exit ? 0 : na)
You will choose the plot with buy/sell/exit signals inside the PSStrategyX tool to execute trades. If you need help, check out the docs for more details.
3 — Set up the broker connector (optional): If you want to take live trades with this tool, you will need to set up a third party connecter. Once set up, everything is automated. See more details in the "authors instructions." at the bottom of this post.
4 — Set up an exchange account (optional): If you want to trade on an exchange, you will need to set up an account with the exchange you plan to use.
The Broker Connector supports a range of popular exchanges, including Binance, Bitfinex, Kraken, Oanda and more.
Once you have generated your trading signals, set up the Broker connecter (optional) and set up an exchange account (optional), you can start using the PSStrategyX trading tool to execute trades automatically based on your trading signals.
█ LIMITATIONS
Here are some important limitations to keep in mind when using the PSStrategyX trading tool:
General:
— Once the alert is sent, there is no way to monitor positions on any exchange. The order will be processed by the broker connector and sent to the exchange.
While this usually works fine, it's important to check the log for errors.
Sometimes the broker connector may fail to process the order, or the exchange may not process it for various reasons.
— The tool sends TP/SL orders with the entry order when possible to protect your order in case of errors or if you lose a connection.
However, not all exchanges accept TP/SL orders, and sometimes your entry order will be left unprotected.
FIFO:
— This tool DOES NOT support the First In First Out (FIFO) method for closing positions.
— Instead, it uses the ANY method. There currently is no way to make this variable.
█ FAQ
What does PSStrategyX do exactly?
PSStrategyX is a strategy enhancing, backtester, forwardtester, automation and simulation tool. It's NOT a signal generator, and does not produce buy/sell signals by itself. You provide buy/sell signals, and PSStrategyX will put those signals on steroids...basically.
PSStrategyX helps you figure out what indicators actually work. Without wasting time learning how to code.
Why did you choose AutoView for this tool?
AutoView offered the best integration I could find. They allow you to connect to test exchanges for free, which is great for practicing without using real money. They also work without using webhooks, which means you can live trade without paying for Tradingview pro. Additionally, AutoView supports many different exchanges. I don't work for AutoView, but if you sign up through my referral link and purchase a paid version, I earn a commission.
Why doesn't Tradingview automatically connect Pine Script to exchanges?
This is a great question, but unfortunately I don't have the answer. It would definitely be helpful if Tradingview provided this feature, but it might also put some brokers out of business.
How do I get access?
DON'T ask for access in the comments.
DO review the "Authors Instructions" on this page for details.
Wunder OI botWunder OI bot
1. Wunder OI bot is based on the search for divergences on the Open Interest indicator. The strategy determines the divergence between the price and the Open Interest for a given period.
2. 50 EMA is used as an additional filter. If a divergence is found for a specified number of bars ago and the price is above or below, a trade will be opened.
3. A function for calculating risk on the portfolio (your deposit) has been added to the Wunder OI bot script. When this option is enabled, you get a calculation of the entry amount in dollars relative to your Stop Loss. In the settings, you can select the risk percentage on your portfolio. The loss will be calculated from the amount that will be displayed on the chart.
For example, if your deposit is $1000 and you set the risk to 1%, with a Stop Loss of 5%, the entry volume will be $200. The loss at SL will be $10. 10$, which is your 1% risk or 1% of the deposit.
*Important!** The risk per trade must be less than the Stop Loss value. If the risk is greater than SL, then you should use leverage.
The amount of funds entering the trade is calculated in dollars. This option was created if you want to send the dollar amount from Tradingview to the exchange. However, putting your volume in dollars you get the incorrect net profit and drawdown indication in the backtest results, as TradingView calculates the backtest volume in contracts.
To display the correct net profit and drawdown values in Tradingview Backtest results, use the ”Volume in contract” option.
*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
TENKAN SCALPER STRATEGYTENKAN SCALP is a fully automatic trading system.
It is a continuation of our previous ichimoku release. This time however we throw out the rule book and use ICHIMOKU in a very different way.
It applies non traditional money management tactics.
While most trading strategies rely on a stop loss and a take profit target to manage risk. This strategy uses either no stop loss at all or a time based stop loss.
You might ask yourself the question why would you keep a trade open if it goes against you? Here are a phew reasons why the script does what it does.
Forex Markets consolidate most of the time. If you wait long enough your Take Profit will get hit anyways most of the time
You don't have to risk everything per trade. I keep my orders small so to keep some powder to get into some more trades
All the extra trades you take while one trade is in drawdown limit the drawdown as they provide cashflow
On lower timeframes the markets are so chaotic that a stop loss is very likely to get hit by a wick
About backtest below
This backtest uses a spread of 2 pips for entries and a default position size of 100% of equity. This is only possible on exchanges where spread is low and you have 10:1 leverage or more. It does not represent results obtainable without leverage. Do take into account that there are a lot of forex exchanges that provide this leverage, however a 2 pip spread is not always guaranteed and only applies to major pairs.
This backtest does not use the TIME BASED STOPS functionality.
Always start with small position sizing and see how the strategy performs before adding risk.
Explanation of variables:
Chikou(lagging span): pink line, this is price plotted 26 bars ago. People ignore the power of this it is crucial to see how chikou behaves towards past price action as seen in the chart below where we got an entry at red arrow because chikou bounced from past fractal bottom.
Kijun-Sen(base line): Black line or color coded line. This is the equilibrium of last 26 candles. To me this is the most important line in the system as it attracts price.
Kijun = (Highest high of 26 periods + Lowest low of 26 periods) ÷ 2
Tenkan-Sen(conversion line): Blue line. This is the equilibrium of last 9 candles. In a strong uptrend price stays above this line.
Tenkan = (Highest high of 9 periods + Lowest low of 9 periods) ÷ 2
Senkou A (Leading span A)= Pink cloud line, this is the average of the 2 components projected 26 bars in the future.
Senkou A = (Tenkan + Kijun) ÷ 2
Senkou B (Leading span B) = Green cloud line, this is the 52 day equilibrium projected 26 bars in the future.
Senkou B = (Highest high of prior 52 periods + Lowest low of prior 52 periods) ÷ 2
projection: Script uses same function for variable calculation and substracts a number on each next bar as to make a projection of where the variable will be in future bars if price stayed the same. This works as ICHIMOKU calculations use the middle point of a past set of data. The shorter that amount of bars will be in line with the data that it will be restricted to in future if price stayed the same.
Detection of Market Environment
To enter trades the script uses a lot of ICHIMOKU concepts. Contrary to how most people trade ICHIMOKU this script takes an environment that ICHIMOKU identifies as trending upwards and shorts in that environment. The same will be applied to a downtrend where it will open LONGS.
List of CRITERIA for a trend:
Grapling Hook: this is a component based on the chikou span (closing price displaced 26 bars into the past). The script will use an ATR based range to define a possible future projection to the CHIKOU line. For a market to be bullish there should be no price action happening within this area. Market is free to move upwards. Vice versa for bearish .
Kumo Cloud: script will check if price is above the cloud for bullish trend and below cloud for bearish trend .
Chikou above Kijun: script will check if the chikou line is above the KIJUN line of 26 bars ago. This is further confirmation that price is trending high enough compared to it's past data. Vice versa for downtrend.
Kijun projection: script will check if past Kijun is lower than future projected Kijun. This to ensure we get an equilibrium in our favour in the future. Vice versa for downtrend
Tenkan projection: script will check if future Tenkan-sen will be higher than Kijun-sen for an uptrend. Vice versa for downtrend.
Cloud projection: script will check if in 9 bars the Senkou Span A will be higher than Senkou Span B for an uptrend. Vice versa for downtrend.
Example:
This script does not visualise the prediction lines like I show in the example. I show them here to clarify how the script works.
Usage
Backtests are not indicative of future results, although a trader may want to use a strategy script to have a deeper understanding of how their strategy responds to varying market conditions, or as a tool for identifying possible flaws for a strategy that may be indicative of good or bad performance in the future.
Strategy Settings:
Minimum Body Size (atr): this is the minimum ATR a signal bar needs to be for entry. This is useful because our TP is based on previous bar.
Lot size per trade: this setting does not impact backtest. It is used to for the signals to let tradingconnect.com know your position size.
Direction: do you want to trade longs or shorts. I personally use both a long bot and a short bot at the same time.
Positions Allowed: the amount of positions the script will keep open as a maximum. You do not want to open too many positions, this is for risk management.
Close all positions at drawdown: if total open positions loss gets to this % target it will close all positions.
MetaTrader Prefix: when the script sends a signal it will put this text right before the symbol name from syminfo.ticker
MetaTrader Suffix: when the script sends a signal it will put this text right after the symbol name from syminfo.ticker
Charts below are some examples on how the script handles orders on default settings:
without time based SL
with time based SL
how it handles pyramiding
www.tradingview.com
Tradingconnector.com:
For full automation of the forex market the script uses this connector to execute trade on MT4. The alerts the script sends using the alerts() function call are structured in a way tradingconnector will recognise and send directly to MT4. You can find documentation about this tool on their own website.
Personal recommendation is to start with a minimum lot size and track performance, if you are comfortable scale the size up. You can do that by increasing the lot size setting in the script and making a new alert. Make sure to delete the old one.
How to access
You can see the Author's Instructions below to visit our telegram to get more information on how to get access.
basilGrid GridBot Live [basilChart]This strategy is a full implementation of Live Grid Trading.
Prominent features of this live grid trading strategy are:
- Logarithmic Chart Support: This strategy can support Log Scale on graph. Meaning that grid lines won't have irregular gaps in between the lines if you would like to view the chart Log Scaled. Every line will be aligned correctly even if you use Log Scale or not.
- Precise Buy & Sell: Script will execute precise Buy and Sell orders.
- Dynamic Grid Level Count: From 2 grid levels to n amount of grid levels are supported. There is no limitation on grid level count, however there may be irregularities because of limitations when higher grid levels are used. You can pick any number starting from 2.
- Average Price: Traders can monitor average price of positions.
- Alerts: When order is filled trader can receive notification. Create new alert > Select basilGrid Live > Order fills only()
Characteristics of this script:
- Able to fill more than one order in one single candle.
- Levels will keep being updated with every trade.
- There will be always one grid level ignored and it will be the level which made the last order filling possible. This is normal behavior of grid trading system.
- You can both use Log Scale and Normal Scale with this script. No issue will be on grid levels.
Using the script:
- Add this script to the chart from indicators tab
- Set starting date for the live grid bot either by dragging and dropping the vertical line or by the date-time picker from indicator Inputs tab.
- Set highest and lowest limit for the script. These will be the boundary limits. Highest and lowest price for the script to work on. Lines will populate between these two values
- Set grid level count. Number of levels of the grid.
- Set amount to spend on per level. This quantity of order will be placed on each level when needed.
After setting the above settings, there is one last thing to do in order to get precise results. It is setting the Initial Capital.
- We can set this setting from 'Properties' tab. Named 'Initial Capital'. After setting the boundaries all we need to is to navigate to TradingView's own 'Data Window', and get the value there. Then paste it on the strategy's own related setting area.
In this example we used pair BTCUSDT 1D timeframe, our settings are:
Inputs Tab:
- Grid Count: 19
- High Limit: 65 500
- Low Limit: 15 000
- Quantity per level: 0.1
- Toggle Log Scale: Checked (because I always use Log Scale on charts, if Log Scale is turned on for the chart, this needs to be checked)
- Terminate Grid At The Upmost Level: Not checked
- Show Grid Levels: Checked
- Show Average Position Price: Checked
Properties Tab:
- Initial Capital: 22 628
- Slippage: 5
- Commission: 0.1% (this is the broker commission value)
This script's purpose is to make it easier to get the idea of grid trading, experiencing it in live session.
Broadview Economic StudioThank you for taking the time to read this description. We'll be taking a look at the Broadview Economic Studio. This has been a work-in-progress for years and is a very powerful tool for planning trades with complex volume scaling strategies. We will be talking about many indicators and types of indicators used in the public domain, but it is NOT recommended to reverse engineer our scripts as there is quite a bit of logic in the code that works to make each common approach entirely unique. So although you may understand quite a bit about oscillators, the way they work with the rest of the logic within the script may change the way you know them to work from elsewhere.
In the chart snapshot above you'll see a mild configuration where I only had to tweak a few settings. Commissions are set to 0.1%, starting capital is set to $10,000, and slippage is off. In my tests orders came through less than a penny off. Generally speaking, there are really only two situations in which you should be concerned about slippage. The first is if you trade really low timeframe charts like the 1 second. This tool, while it works for any timeframe, is programmed on the 45 minute timeframe and works best there. The other situation in which you should be prepared for slippage is if you're using extremely high volume trades in the hundreds of thousands or millions depending on the market cap and liquidity of the asset you're studying. Large orders like that have to be split up among several deals and that can cause slippage.
There are 31 primary inputs for users to tweak. Each input is grouped within a module called a Suite. Each suite has a focus like filtering signals or strategically allocating volume according to your strategy. Everything starts with the Origin Suite. The Origin Suite is a group of inputs that generates Tops & Bottoms from price action. It uses math like Rate of Change, where one can specify a required rate of change before an Origin signal can be made, and users can specify how much lower in price a bar must be compared to previous bars. So with the Origin Suite, users can control how often they want to see originating signals and under what conditions they can appear.
We used to use WVF and CVI to produce top and bottom signals, but our Origin Suite works much better for systematically generating profitable configurations.
The triangles you see on the chart represent markers, potential signals, or Prop Signals as they're referred to within the script. The blue arrows represent trades where Prop Signals were allowed to pass as true long signals. There are two ways to ignore Prop Signals. You can filter the markers entirely, or you can reduce their volume scaling to the minimum which is usually $10 for most exchanges. We're first going to be talking about some of the primary DCA inputs before we talk about the technology we use to filter and overload signals.
Here are some important features found within the script:
Base Orders
Safety Orders
Take Profits
Change-Based Volume Scaling
Ignoring Low or Medium Changes
Overloading
Filtering
Alert Messages w/ Volume Scaling
Let's walk through each of these features in more depth.
The Base Order is the initial Long position within a series. It comes in first and is followed by all of its Safety Orders. The Base Order is set to $25 within the script by default. Keeping the base order low allows one to reserve more of their capital for Safety Orders that are lower within a dip, and thus, lower the user's Position Average. The primary feature of this script is to help users plan their volume scaling strategically, and this is where we start. It's this kind of due diligence and effort in protecting trades that makes this script unique.
So we start with a low Base Order. Then, we follow with a lot of Safety Orders. Typically in DCA this is done in consistent time intervals and in consistent amounts. So in regular DCA one may invest the same amount bi-weekly on pay day. They use the financial instrument as a sort of savings and average their position over their consistent investments. This is not where the bleeding edge of DCA is today though. In modern Doller Cost Averaging, I would expect to see signals and volume scaling based on logic.. as opposed to being consistent intervals.
This sets up the explanation of the primary means of volume scaling within the script. Mathematically, we start with the net balance. This is your specified starting balance plus any wins or losses. Users specify what % of their Available Balance they would like to start with when volume scaling. This percent of capital is then multiplied by a Safety Order Multiplier. The safety order multiplier is made up of a number specified by the user, multiplied by the number of the Safety Order you're on. So user's can control this equation/algorithm and scale their investments as the number of Safety Orders increases and drops in price become more opportune.
The Take Profit within the script lets users specify their desired ROI from a series. So if a user sets a 60% take profit, the script will set a price from the position average that when reached will give the user a 60% ROI for the series including its Base Order and all its Safety Orders.
Before moving on, let's talk about the amazing internal reporting found in the script. When you zoom in on the blue arrows, you can see each trade is accompanied by some extremely helpful information. This is just another feature that makes this script unique, it is the feature that gives us accurate reporting and ultimately allows us to connect with TradingView's Strategy Tester in a way that provides instant backtests with good merit. With this reporting not only can users get reports and information on trades made on different assets with different configurations, but user's can perform a deep dive on each configuration and know exactly what was going on for each trade. The first number is the number of the safety order the script is on. Remember, this is used in the primary volume scaling math. The second number is the amount the script spent on the current trade. The third number denotes the cumulative spending for the series. The final number displays the script's available balance at that time. With these numbers, the TradingView Strategy Tester, and the List of Trades feature, users can practice as much due diligence as they need during their studies.
Let's move on to talking about my favorite suite within the script, the Volume Scaling Suite. Here there are two primary means of controlling volume scaling. Although, in the near future there will be more.
In this suite you'll find Change-Based Volume Scaling and Position Average Volume Scaling. Position Average Volume Scaling is quite easy to explain. This feature only allows signals to pass if they are lower in price than your base order. In this way, users can apply most of their capital to trades that lower their position average. Simply having the money in the market can boost profits, but having a lower Position Average is the entire reason we DCA. Change-Based Volume Scaling is quite a bit more complex.
In theory, one could argue that every moment is a great moment to buy. It's just that some moments are more opportune than others. So it's not about perfect signals as much as it's about proper volume scaling.
Change-Based Volume Scaling allows us to set rules that dictate how much volume scaling is used based on the asset's current delta, or Rate of Change.
Using CBVS, one can downscale capital applied to signals with a low ROC, or simply ignore them. So if a signal comes in and the price hasn't changed very much then you can automatically use less volume for the trade. One can do the same thing for medium changes, and the user can specify what quantifies as a low or medium change. Users can give extra volume to signals with a greater rate of change, or overload signals with a high rate of change! So the CBVS feature gives users the ability to allocate volume based on logic rooted in the asset's rate of change. If a signal has dropped a lot in price, then generally, it is deserving of more capital and that's what makes this feature unique and so powerful.
There are two kinds of Overloading found in the script. There's overloading from CBVS, and then overloading from the 4 signal filtering suites. There's an important difference to note before we move on. Overloading performed by CBVS is based on ignored signals. So if you ignore low or medium change signals, and you have CBVS Overloading on, the script will allocate more capital to High Change signals. When signals are ignored, they are downscaled to $10. Whereas with the filtering suites, if a signal is filtered the Prop Signal triangle marker is removed entirely. The overloading in that scenario is simply applied to signals that aren't filtered. The reason it's done this way is because allowing ignored signals to still come in, with the lowest volume scaling possible, keeps the Safety Order count rising which works in the volume scaling math. This math is intrinsic to getting capital deep within dips and crashes.
So in future versions we may allow ignored signals to be filtered out entirely but for the time being, simply scaling them down to the lowest possible amount is what produces the best and most consistent configurations.
Let's talk about filtering signals, and the overloading provided within each filtering suite.
Here you can see our Overbought & Oversold Heatmap V3. This is a unique indicator that takes 15 common oscillators and visualizes them in a way that clearly denotes confluence. Looking at this indicator makes it easer to read cycles and trends. It is quite common for investors to base their entire scripts on one or more of the oscillators found within the OBOS Heatmap V3. So the OBOS Heatmap V3 is an awesome way to ensure your signals follow an oversold trend! The orange represents an oscillator being oversold, while the yellow represents it being overbought. Generally, when an asset is oversold it is a better time to buy. One can filter signals based on this information and use the Heatmap's unique ability to quantify confluences. In this script users can set a sensitivity and that sets the number of oscillators that must be in agreement before a signal is allowed to pass.
Here are the oscillators found within the OBOS Heatmap:
*Please keep in mind that although some of these oscillators may have big names, the code and math in the script may work differently than you're used to. This is because the code and math is changed quite a bit, and the overall intended functionality of the OBOS Heatmap has a larger scope than any one indicator. It's also important to note that the lengths for these oscillators are set low and are meant to classify the individual signal as either overbought or oversold, and not the entire period. So while the OBOS Heatmap is awesome for trends and cycles, it's ultimately meant to classify individual price bars as either overbought or oversold according to a consensus.*
Relative Strength Index
Money Flow Index
Commodity Channel Index
Aroon Oscillator
Relative Volatility Index
Fast Stochastic Detrended Price Oscillator
Fast Stochastic Elders Force Index
Fast Stochastic Relative Strength Index
Fast Stochastic Relative Vigor Index
Fast Stochastic Klinger Oscillator
Fast Stochastic Awesome Oscillator
Fast Stochastic Ultimate Oscillator
Fast Stochastic Chande Momentum Oscillator
Fast Stochastic On Balance Volume Oscillator
Fast Stochastic Moving Average Convergence/Divergence
Each band of the Overbought & Oversold Heatmap represents an oscillator. When it's orange it's said to be oversold. When it's yellow it's said to be overbought. The indicator turns purple during trends and reversals where it is neither overbought nor oversold. It can differentiate between uptrends and downtrends with differing colors of purple, but the OBOS Heatmap is not used for trends or cycles in this script. It is used to quantify oversold confluence.
Let's talk about the Dominance Suite.
First note in the top portion of the screenshot above, you will see various colors in the script. It replaces the price line with something we call Price Flow bars. So when you add the script it's best to make the stock price line invisible in TV settings. The Price Flow Bars use a preset EMA to color price action as being in either a downward momentum or upward momentum. The triangular signals represent dark teal for the initial long marker within a series, dark green for long orders and long signals that convert into safety orders, and light green for safety orders. This is more logic that makes this script really unique. The dark green initial long marker signals are rarely seen. You can find them at the beginning of a new series of signals and they work to establish when a new series of signals should begin. The dark green signals actually denote a long base order opportunity, but if a series has already started then these signals are converted into Safety Orders. The Safety Orders then come in light green, and red for Prop Shorts. Prop Shorts work with Initial Longs to establish the start of a new series. More on that math I cannot tell.
In the bottom half of the screenshot is the Dominance Suite itself. It's another one of the four filtering suites found in the script. It is made up of 7 oscillators that work to classify a price bar as being controlled by either the bears or the bulls. If a price bar is controlled by the bears it is said to be a better investment. The Dominance Suite works by applying a moving average to the balance of power. This is the way TradingView has intended the balance of power to be used, and works quite nicely in classifying individual price bars as either bearish or bullish. It's not an overall trend indicator as much as it states whether a bar is mostly controlled by the bears or the bulls.
Here are the oscillators found within the Dominance Suite:
SMA of BOP
EMA of BOP
HMA of BOP
WMA of BOP
VWMA of BOP
TEMA of BOP
LSMA of BOP
Within the script, there is an input for a negative threshold. When each of these 7 oscillators is in confluence and below this set threshold, the Prop Long will be allowed to pass as a real trade.
Keep in mind that each filtering suite also has the option to overload signals.
So not only can you filter signals based on these suites but you can also apply additional volume scaling to signals that don't get filtered.
Here we have the True Oscillator. The True Oscillator is a brand new oscillator. It's similar to things like the RSI or DPO, but technically speaking it considers many more factors into its average than other oscillators. It considers balance of power, sentiment, volume, momentum, gravity, and places special-strategic weighting on price data based on whether it's opening, closing, high, or low. If you stack the True Oscillator up with the RSI you'll notice right away they look similar, but each movement is quite different. Overall the movements are more balanced, the individual bars are more consistent with price data, and the swings are more clearly pronounced while simultaneously having a better register of strength in momentum. We use this indicator to filter and overload signals, to trade according to momentum, and to provide a 16th independent oscillator that can check the OBOS Heatmap without having to be confluent.
The final filtering suite is based on Net Volume. It classifies signals as oversold when there is a significant negative trend in net volume. If Net Volume is under 0, and trends downward for either 3, 4, or 5 bars in a row then it will mark a signal as oversold and allow it to pass. Then, if overloading for this suite is turned on it will allocate more volume to signals it does not filter out.
There is a lot that can be said about this strategy. The primary takeaway though is that it's not just one strategy. It's a tool for everyone, to help them plan their approach to different assets in different market climates. This tool can help you study current market conditions. It can allow you to plan a strategic approach to market segments, and see how your strategy would fare if new market data performed similarly. It's not just one strategy, but more of a strategy printer.
The Origin Suite allows users to plan the positioning of their signals. The Overbought & Oversold Suite allows users to filter their signals based on whether or not they are oversold. The Dominance Suite allows users to filter signals based on whether the market is being controlled by the bears or the bulls. The True Oscillator gives users the ability to filter signals based on a deep and powerful momentum oscillator. The Net Volume Suite lets users filter signals based on volume trends. When signals are filtered, signals that pass, can be overloaded with additional volume scaling. Features like Change-Based Volume Scaling and Position Average Volume Scaling give users plenty of inputs to create complex volume scaling strategies. Common-sense DCA inputs allow users to scale into markets the way pros do.
The Broadview Economic Studio is a powerful tool for planning trades with complex volume scaling strategies.
Users can plan their approach to different kinds of markets. They can link the script with their bot or broker like 3Commas, and the script will automatically send the correct volume scaling through to the bot.
Thank you for your time, and for reading the description of the Broadview Economic Studio.
bc Grid Backtest v1.4This strategy is a full implementation of Grid Trading backtest.
Prominent features of this backtesting strategy are:
- Logarithmic Chart Support: This strategy can support Log Scale on graph. Meaning that grid lines won't have irregular gaps in between the lines if you would like to view the chart Log Scaled. Every line will be aligned correctly even if you use Log Scale or not.
- Precise Buy & Sell: Script will execute precise Buy and Sell orders.
- Dynamic Grid Level Count: From 2 grid levels to n amount of grid levels are supported. There is no limitation on grid level count. You can pick any number starting from 2.
- Customized Backtesting Results Table: A table which includes data for those who want to know has been added at top right. It can be disabled.
Characteristics of this script:
- Able to fill more than one order in one single candle.
- Levels will keep being updated with every trade.
- There will be always one grid level ignored and it will be the level which made the last order filling possible. This is normal behavior of grid trading system.
- You can both use Log Scale and Normal Scale with this script. No issue will be on grid levels.
Using the script:
- Add this script to the chart from indicators tab
- Set starting and ending date for the grid backtesting bot either by dragging and dropping the vertical lines or by the date-time picker from indicator Inputs tab.
- Set highest and lowest limit for the script. These will be the boundary limits. Highest and lowest price for the script to work on. Lines will populate between these two values
- Set grid level count. Number of levels of the grid.
- Set amount to spend on per level. This quantity of order will be placed on each level when needed.
After setting the above settings, there is one last thing to do in order to get precise results. It is setting the Initial Capital.
- We can set this setting from 'Properties' tab. Named 'Initial Capital'. After setting the boundaries all we need to is to navigate to TradingView's own 'Data Window', and get the value there. Then paste it on the strategy's own related setting area.
In this example we used pair BTCUSDT 4h timeframe, our settings are:
Inputs Tab:
- Grid Count: 13
- High Limit: 72 000
- Low Limit: 17 000
- Logarithmic Grids: Checked (because I always use Log Scale on charts, if Log Scale is turned on, this needs to be checked)
- Quantity per level: 0.1
- Show Table: Checked
- Show Grid Levels: Checked
- Show Average Position Price: Checked
Properties Tab:
- Initial Capital: 24 902
- Slippage: 5
- Commission: 0.1% (this is the broker commission value)
This script's purpose is to make simulating possible outcomes between two dates. Therefore making it easier to get the idea of grid trading, finding the best settings for your risk management and for your portfolio.
Alex trading stragedyOverview
This script, named "ALEX TRADING STRATEGY", is a technical trading strategy designed for new investing groups. It uses a combination of various technical indicators to identify potential buying and selling opportunities in the market. The script includes the Relative Strength Index (RSI), Simple Moving Averages (SMA), Exponential Moving Averages (EMA), and Higher High Lower Low (HHLL) strategies to create a complete trading solution.
The user can change the position from long to short in the Input Settings. The script uses bar colors to indicate the current trading position. The script also has exit strategies to help manage the open trades. The user can also set the period for the various indicators used in the strategy.
The script provides various technical indicators and entry/exit signals to make the trading decision easier for the user. It also includes pivot lines, resistance and support levels to help the user make a more informed decision.
This Pine script implements a multi-indicator trading strategy that combines several technical analysis techniques for making trading decisions. The script uses the Relative Strength Index (RSI) to determine overbought and oversold conditions in the market and plots the RSI values on the chart. The RSI values above 70 are considered overbought and plotted as red upward triangles, while the RSI values below 30 are considered oversold and plotted as green downward triangles.
The script also calculates Simple Moving Averages (SMAs) with the user-defined period and plots them along with the Exponential Moving Averages (EMAs) of 20, 50, and 100 periods. Based on the crossover of the close price and the moving averages, the script enters long or short trades. The script sets the trade exit conditions as the low or high crossing the lower or upper band, respectively.
In addition to the moving average crossover, the script uses the highest high and lowest low over a user-defined period to determine long and short entries. The script plots the long and short conditions on the chart as green upward and red downward triangles, respectively. The script allows the user to switch between long and short trades by changing the input settings.
Finally, the script changes the bar colors based on the trade direction, with green bars indicating a long trade, red bars indicating a short trade, and blue bars indicating no trade. Overall, this Pine script provides a comprehensive trading strategy that combines several technical analysis techniques to make informed trading decisions.
HOW TO USE
Input Settings: In the Input Settings section, you can change the long to short position. You can also change the period value (default is 10) used to calculate the Simple Moving Average (SMA) for the Keltner channel.
Indicators: The script uses RSI (Relative Strength Index) with 14 periods as well as multiple EMAs (Exponential Moving Averages) with periods 20, 50, and 100 to help in making trading decisions.
Entry Signals: The script uses two main entry signals: (1) Keltner Channel and (2) HHLL (High-Low). When the closing price crosses above the upper band of the Keltner channel, the script generates a long signal, and when the closing price crosses below the lower band of the Keltner channel, the script generates a short signal. The HHLL strategy generates a long signal when the current high crosses above the highest high of the last "nPeriod" bars, and generates a short signal when the current low crosses below the lowest low of the last "nPeriod" bars.
Exit Signals: The script uses two exit signals: (1) Stop Loss based on Keltner channel and (2) Profit Target based on Keltner channel. The script exits the long position when the closing price crosses below the lower band of the Keltner channel, and the script exits the short position when the closing price crosses above the upper band of the Keltner channel.
To use this script, you will need to have access to a trading platform that supports PineScript, such as TradingView, and attach the script to a chart. The script will then automatically generate entry and exit signals based on the rules described above. It's important to note that this script is just a tool and not a guarantee of profit. As with any trading strategy, it's important to thoroughly test and understand the script before using it for live trading.
Kioseff Trading - AI-Powered Strategy Optimizer Introducing the Kioseff Trading AI-Powered Strategy Optimizer
Optimize and build your trading strategy with ease, no matter your experience level. The Kioseff Trading AI-Powered Strategy Optimizer allows traders to efficiently test and refine strategies with thousands of different profit targets and stop loss settings. Integrated with TradingView's backtester, this tool simplifies strategy optimization, strategy testing, and alert setting, enabling you to enhance your strategy with AI-driven insights.
Key Features:
Comprehensive Testing : Simultaneously test thousands of profit targets and stop losses to fine-tune your strategy.
Dual Strategy Optimization : Adjust and optimize both long and short strategies for balanced performance.
AI Integration : Elevate your strategy with heuristic-based adaptive learning, turning it into a smart, AI-assisted system.
Detailed Analysis : View critical metrics like profit factor, win rate, max drawdown, and equity curve, presented in a strategy script format.
Customizable Alerts : Set alerts for the best version of your strategy.
Flexible Risk Management : Optimize various stop loss types, including profit targets, limit orders, OCO orders, trailing stops, and fixed stops.
Targeted Goals : Choose optimization goals like highest win rate, maximum net profit, or most efficient profit.
Indicator Compatibility : Integrate any strategy/indicator, whether it’s your creation, a favorite author’s, or any public TradingView indicator.
Accessible Design : Navigate a user-friendly interface suitable for traders of all skill levels. No code required.
Precision Lock-In : “Lock” your optimal profit target or stop loss to drill down into precision testing of other variables.
How it works
It's important to remember that merely having the AI-Powered Strategy Optimizer on your chart doesn't automatically provide you with the best strategy. You need to follow the AI's guidance through an iterative process to discover the optimal settings for your strategy.
The Trading Strategy Optimizer is a versatile tool tailored for both non-coding traders and seasoned algorithmic trading professionals. Let's start with no-code-required instructions on how to use the optimizer.
Instructions: How To Optimize Your Strategy Without Code
1. Build your strategy in the settings
The image above shows explanations for each key setting.
Note: This example uses the RSI indicator to initiate a long trade whenever it dips below the 30 mark.
Ensure that the indicator you wish to optimize is already applied to your chart . This enables the Trading Strategy Optimizer to interact with the indicator and finetune profit targets and stop losses effectively.
Because the indicator is plotted on the chart I can access the indicator with the Trading Strategy Optimizer and optimize profit targets and stop losses for it.
2. Leverage AI Recommendations
Optimization Prompt: After you load your strategy, the tool advises you on new TP and SL levels that could be more profitable.
When your strategy is set, the tool gives you tips for where to set your profit goal (TP) and your stop loss to help you optimize your strategy. It'll tell you if there's a better range for these settings based on past results.
Follow Suggestions: Keep updating your TP and SL according to the tool's suggestions until it says "Best Found".
Final Result: The last image shows the best settings found by the indicator.
(Optional Step 3)
3. Lock the profit target or stop loss to further fine tune your strategy
Continue following the AI’s suggestion until “Best Found” is displayed.
Note: you can select lock either your stop loss or profit target for fine tuning. For this demonstration we will lock our profit target.
Code-Required Instructions (Optional)
You can backtest more code-intensive strategies, such as harmonic patterns, traditional chart patterns, candlestick patterns, Elliot wave, etc., by coding the entry condition in your own script and loading it into the Trading Strategy Optimizer. Let's dial in on how to achieve this!
1. You must create an integer variable in your script with an initial value of "0".
2. Define your entry condition in the code. Once complete, assign the value "1" to the variable you created if the entry condition is fulfilled.
3. Plot your variable.
4. Select the plotted variable in the settings for the Trading Strategy Optimizer
The image above shows a coded entry condition for the linear regression channel (which can be any indicator). When price crosses under and closes below the lower line our variable "strategyEntryVariable" is assigned the value "1".
The Trading Strategy Optimizer will treat this change in value from "0" to "1" as an entry signal and enter long/short up to 1000 times at the price where the entry condition was fulfilled.
5. Test Your Strategy
The image above shows the completion of the process! Keep applying the steps we described. Stick with the AI's recommendations until you see “Best Found” show up.
By following these instructions, you can build, test, and optimize almost any trading indicator or strategy!
So, just note that the Trading Strategy Optimizer considers a change in value of a plotted variable from "0" to "1" as an entry signal! So long as you follow this rule you should be able to test and optimize any conceivable, Pine Script compatible strategy!
AI Mode
AI Mode incorporates Heuristic-Based Adaptive Learning to fine-tune trading strategies in a continuous manner. This feature consists of two main components:
Heuristic-Based Decision Making: The algorithm evaluates multiple versions of your strategy using specific metrics such as Profit and Loss (PNL), Win Rate, and Most Efficient Profit. These metrics act as heuristics to assist the algorithm in identifying suitable profit targets and stop losses for trade execution.
Online Learning: The algorithm updates the performance evaluations of each strategy based on incoming market data. This enables the system to adapt to current market conditions.
Incorporating both heuristic-based decision-making and online learning, this feature aims to provide a framework for trading strategy optimization.
Settings
AI Mode Aggressiveness:
Description: The "AI Mode Aggressiveness" setting allows you to fine-tune the AI's trading behavior. This setting ranges from "Low" To "High, with higher aggressiveness indicating a more assertive trading approach.
Functionality: This feature filters trading strategies based on a proprietary evaluation method. A higher setting narrows down the strategies that the AI will consider, leaning towards more aggressive trading. Conversely, a lower setting allows for a more conservative approach by broadening the pool of potential strategies.
Adaptive Learning Aggressiveness:
Description: When Adaptive Learning is enabled, the "Adaptive Learning Aggressiveness" setting controls how dynamically the AI adapts to market conditions using selected performance metrics.
Functionality: This setting impacts the AI's responsiveness to shifts in strategy performance. By adjusting this setting, you can control how quickly the AI moves away from strategies that may have been historically successful but are currently underperforming, towards strategies that are showing current promise.
Additional Settings
Optimization
Trading system optimization is immensely advantageous when executed with prudence.
Technical-oriented, mechanical trading systems work when a valid correlation is methodical to the extent that an objective, precisely-defined ruleset can consistently exploit it. If no such correlation exists, or a technical-oriented system is erroneously designed to exploit an illusory correlation (absent predictive utility), the trading system will fail.
Evaluate results practically and test parameters rigorously after discovery. Simply mining the best-performing parameters and immediately trading them is unlikely a winning strategy. Put as much effort into testing strong-performing parameters and building an accompanying system as you would any other trading strategy. Automated optimization involves curve fitting - it's the responsibility of the trader to validate a replicable sequence or correlation and the trading system that exploits it.
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.
LuxAlgo - Backtester (S&O)The S&O Backtester is an innovative strategy script that encompasses features + optimization methods from our Signals & Overlays™ toolkit and combines them into one easy-to-use script for backtesting the most detailed trading strategies possible.
Our Signals & Overlays™ toolkit is notorious for its signal optimization methods such as the 'Optimal Sensitivity' displayed in its dashboard which provides optimization backtesting of the Sensitivity parameter for the Confirmation & Contrarian Signals.
This strategy script allows even more detailed & precise backtests than anything available previously in the Signals & Overlays™ toolkit; including External Source inputs allowing users to use any indicator including our other paid toolkits for take profit & stop loss customization to develop strategies, along with 10+ pre-built filters directly Signals & Overlays™' features.
🔶 Features
Full Sensitivity optimization within the dashboard to find the Best Win rates or Best Profits.
Counter Trade Mode to reverse signals in undesirable market conditions (may introduce higher drawdowns)
Built-in filters for Confirmation Signals w/ Indicator Overlays from Signals & Overlays™.
Built-in Confirmation exit points are available within the settings & on by default.
External Source Input to filter signals or set custom Take Profits & Stop Losses.
Optimization Matrix dashboard option showing all possible permutations of Sensitivity.
Option to Maximize for Winrate or Best Profit.
🔶 Settings
Sensitivity signal optimizations for the Confirmation Signals algorithm
Buy & Sell conditions filters with Indicator Overlays & External Source
Take Profit exit signals option
External Source for Take Profit & Stop Loss
Sensitivity ranges
Backtest window default at 2,000 bars
External source
Dashboard locations
🔶 Usage
Backtests are not necessarily indicative of future results, although a trader may want to use a strategy script to have a deeper understanding of how their strategy responds to varying market conditions, or to use as a tool for identifying possible flaws in a strategy that could potentially be indicative of good or bad performance in the future.
A strategy script can also be useful in terms of it's ability to generate more complete & configurable alerts, giving users the option to integrate with external processes.
In the chart below we are using default settings and built-in optimization parameters to generate the highest win rate.
Results like the above will vary & finding a strategy with a high win rate does not necessarily mean it will persist into the future, however, some indications of a well-optimized strategy are:
A high number of closed trades (100+) with a consistently green equity curve
An equity curve that outperforms buy & hold
A low % max drawdown compared to the Net Profit %.
Profit factor around 1.5 or above
In the chart below we are using the Trend Catcher feature from Signals & Overlays™ as a filter for standard Confirmation Signals + exits on a higher timeframe.
By filtering bullish signals only when the Trend Catcher is bullish, as well as bearish signals for when the Trend Catcher is bearish, we have a highly profitable strategy created directly from our flagship features.
While the Signals & Overlays features being used as built-in filters can generate interesting backtests, the provided External Sources can allow for even more creativity when creating strategies. This feature allows you to use many indicators from TradingView as filters or to trigger take-profit/stop-loss events, even if they aren't from LuxAlgo.
The chart below shows the HyperWave Oscillator from our Oscillator Matrix™ being used for take-profit exit conditions, exiting a long position on a profit when crossing 80, and exiting a short position when crossing 20.
🔶 Counter Trade Mode
Our thesis has always firmly remained to use Confirmation Signals within Signals & Overlays™ as a supportive tool to find trends & use as extra confirmation within strategies.
We included the counter-trade mode as a logical way to use the Confirmation signals as direct entries for longs & shorts within more contrarian trading strategies. Many traders can relate to using a trend-following indicator and having the market not respect its conditions for entries.
This mode directly benefits a trader who is aware that market conditions are generally not-so-perfect trends all the time. Acknowledging this, allows the user to use this to their advantage by introducing countertrend following conditions as direct entries, which tend to perform very well in ranging markets.
The big downfall of using counter-trade mode is the potential for very large max-drawdowns during trending market conditions. We suggest for making a strategy to consider introducing stop-loss conditions that can efficiently minimize max-drawdowns during the process of backtesting your creations.
Sensitivity Optimization
Within the Signals & Overlays™ toolkit, we allow users to adjust the Confirmation Signals with a Sensitivity parameter.
We believe the Sensitivity paramter is the most realistic way to generate the most actionable Confirmation Signals that can navigate various market conditions, and the Confirmation Signals algorithm was designed specifically with this in mind.
This script takes this parameter and backtests it internally to generate the most profitable value to display on the dashboard located in the top right of the chart, as well as an optimization table if users enable it to visualize it's backtesting.
In the image below, we can see the optimization table showing permutations of settings within the user-selected Sensitivity range.
The suggested best setting is given at the current time for the backtesting window that's customizable within the indicator. Optimized settings for technical indicators are not indicative of future results and the best settings are highly likely / guaranteed to change over time.
Optimizing signal settings has become a popular activity amongst technical analysts, however, the real-time beneficial applications of optimizing settings are limited & best described as complicated (even with forward testing).
🔶 Strategy Properties (Important)
We strongly recommend all users to ensure they adjust the Properties within the script settings to be in line with their accounts & trading platforms of choice to ensure results from strategies built are realistic.
🔶 How to access
You can see the Author's Instructions below to learn how to get access on our website.
Adulari ATSAdulari's Automated Trading Strategy combines more then 10+ innovative indicators and is carefully designed to provide honest and accurate backtesting results. We created and optimized this strategy to provide realistic results, not insane backtesting results that are very inconsistent and unrealistic. It is made for swing trading on the 15m timeframe. It is recommended to use the BYBIT:BTCUSDT pair.
This strategy has been thoroughly backtested throughout 2 years in order to provide optimal results.
ATS was designed to provide live results close to those of backtesting. It has been ensured this strategy is not overfitted.
Our strategy works in any market & allows users to:
Automate their trades using our alert system and integrations.
View realistic backtesting results.
Filter trades in irregular price action using our trend filters.
And many new features that can be found in the changelog below.
Our strategy detect the direction of trends for any asset & on any timeframe allowing traders to increase their confidence in positions and follow trends.
This strategy is built to be very profitable when used for long time periods. Compounding will make profits very solid.
We give our users the possibility to adjust the settings of the strategy to market price variations, as well as the option to make them less sensitive to irregular price movements so that it only trades predictable price action.
Save time by automating everything!
The strategy's settings play an important role towards profitable trades, however, the constant adjustment of these is not necessary since no overfitting is in play.
We made our strategy as flexible as possible in order to allow it to adjust to internal market dynamics, thus completely removing the need for traders to adjust any settings. We offer multiple setting profiles that are optimized for a certain market, with lower or higher risk.
If you are using this script you acknowledge past performance is not necessarily indicative of future results and there are many more factors that go into a profitable trade.
[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.