Stochastic Z-Score Oscillator Strategy [TradeDots]The "Stochastic Z-Score Oscillator Strategy" represents an enhanced approach to the original "Buy Sell Strategy With Z-Score" trading strategy. Our upgraded Stochastic model incorporates an additional Stochastic Oscillator layer on top of the Z-Score statistical metrics, which bolsters the affirmation of potential price reversals.
We also revised our exit strategy to when the Z-Score revert to a level of zero. This amendment gives a much smaller drawdown, resulting in a better win-rate compared to the original version.
HOW DOES IT WORK
The strategy operates by calculating the Z-Score of the closing price for each candlestick. This allows us to evaluate how significantly the current price deviates from its typical volatility level.
The strategy first takes the scope of a rolling window, adjusted to the user's preference. This window is used to compute both the standard deviation and mean value. With these values, the strategic model finalizes the Z-Score. This determination is accomplished by subtracting the mean from the closing price and dividing the resulting value by the standard deviation.
Following this, the Stochastic Oscillator is utilized to affirm the Z-Score overbought and oversold indicators. This indicator operates within a 0 to 100 range, so a base adjustment to match the Z-Score scale is required. Post Stochastic Oscillator calculation, we recalibrate the figure to lie within the -4 to 4 range.
Finally, we compute the average of both the Stochastic Oscillator and Z-Score, signaling overpriced or underpriced conditions when the set threshold of positive or negative is breached.
APPLICATION
Firstly, it is better to identify a stable trading pair for this technique, such as two stocks with considerable correlation. This is to ensure conformance with the statistical model's assumption of a normal Gaussian distribution model. The ideal performance is theoretically situated within a sideways market devoid of skewness.
Following pair selection, the user should refine the span of the rolling window. A broader window smoothens the mean, more accurately capturing long-term market trends, while potentially enhancing volatility. This refinement results in fewer, yet precise trading signals.
Finally, the user must settle on an optimal Z-Score threshold, which essentially dictates the timing for buy/sell actions when the Z-Score exceeds with thresholds. A positive threshold signifies the price veering away from its mean, triggering a sell signal. Conversely, a negative threshold denotes the price falling below its mean, illustrating an underpriced condition that prompts a buy signal.
Within a normal distribution, a Z-Score of 1 records about 68% of occurrences centered at the mean, while a Z-Score of 2 captures approximately 95% of occurrences.
The 'cool down period' is essentially the number of bars that await before the next signal generation. This feature is employed to dodge the occurrence of multiple signals in a short period.
DEFAULT SETUP
The following is the default setup on EURAUD 1h timeframe
Rolling Window: 80
Z-Score Threshold: 2.8
Signal Cool Down Period: 5
Stochastic Length: 14
Stochastic Smooth Period: 7
Commission: 0.01%
Initial Capital: $10,000
Equity per Trade: 40%
FURTHER IMPLICATION
The Stochastic Oscillator imparts minimal impact on the current strategy. As such, it may be beneficial to adjust the weightings between the Z-Score and Stochastic Oscillator values or the scale of Stochastic Oscillator to test different performance outcomes.
Alternative momentum indicators such as Keltner Channels or RSI could also serve as robust confirmations of overbought and oversold signals when used for verification.
RISK DISCLAIMER
Trading entails substantial risk, and most day traders incur losses. All content, tools, scripts, articles, and education provided by TradeDots serve purely informational and educational purposes. Past performances are not definitive predictors of future results.
Statistics
Price Based Z-Trend - Strategy [presentTrading]█ Introduction and How it is Different
Z-score: a statistical measurement of a score's relationship to the mean in a group of scores.
Simple but effective approach.
The "Price Based Z-Trend - Strategy " leverages the Z-score, a statistical measure that gauges the deviation of a price from its moving average, normalized against its standard deviation. This strategy stands out due to its simplicity and effectiveness, particularly in markets where price movements often revert to a mean. Unlike more complex systems that might rely on a multitude of indicators, the Z-Trend strategy focuses on clear, statistically significant price movements, making it ideal for traders who prefer a streamlined, data-driven approach.
BTCUSD 6h LS Performance
█ Strategy, How It Works: Detailed Explanation
🔶 Calculation of the Z-score
"Z-score is a statistical measurement that describes a value's relationship to the mean of a group of values. Z-score is measured in terms of standard deviations from the mean. If a Z-score is 0, it indicates that the data point's score is identical to the mean score. A Z-score of 1.0 would indicate a value that is one standard deviation from the mean. Z-scores may be positive or negative, with a positive value indicating the score is above the mean and a negative score indicating it is below the mean."
The Z-score is central to this strategy. It is calculated by taking the difference between the current price and the Exponential Moving Average (EMA) of the price over a user-defined length, then dividing this by the standard deviation of the price over the same length:
z = (x - μ) /σ
Local
🔶 Trading Signals
Trading signals are generated based on the Z-score crossing predefined thresholds:
- Long Entry: When the Z-score crosses above the positive threshold.
- Long Exit: When the Z-score falls below the negative threshold.
- Short Entry: When the Z-score falls below the negative threshold.
- Short Exit: When the Z-score rises above the positive threshold.
█ Trade Direction
The strategy allows users to select their preferred trading direction through an input option.
█ Usage
To use this strategy effectively, traders should first configure the Z-score thresholds according to their risk tolerance and market volatility. It's also crucial to adjust the length for the EMA and standard deviation calculations based on historical performance and the expected "noise" in price data.
The strategy is designed to be flexible, allowing traders to refine settings to better capture profitable opportunities in specific market conditions.
█ Default Settings
- Trade Direction: Both
- Standard Deviation Length: 100
- Average Length: 100
- Threshold for Z-score: 1.0
- Bar Color Indicator: Enabled
These settings offer a balanced starting point but can be customized to suit various trading styles and market environments. The strategy's parameters are designed to be adjusted as traders gain experience and refine their approach based on ongoing market analysis.
Z-score is a must-learn approach for every algorithmic trader.
Buy Sell Strategy With Z-Score [TradeDots]The "Buy Sell Strategy With Z-Score" is a trading strategy that harnesses Z-Score statistical metrics to identify potential pricing reversals, for opportunistic buying and selling opportunities.
HOW DOES IT WORK
The strategy operates by calculating the Z-Score of the closing price for each candlestick. This allows us to evaluate how significantly the current price deviates from its typical volatility level.
The strategy first takes the scope of a rolling window, adjusted to the user's preference. This window is used to compute both the standard deviation and mean value. With these values, the strategic model finalizes the Z-Score. This determination is accomplished by subtracting the mean from the closing price and dividing the resulting value by the standard deviation.
This approach provides an estimation of the price's departure from its traditional trajectory, thereby identifying market conditions conducive to an asset being overpriced or underpriced.
APPLICATION
Firstly, it is better to identify a stable trading pair for this technique, such as two stocks with considerable correlation. This is to ensure conformance with the statistical model's assumption of a normal Gaussian distribution model. The ideal performance is theoretically situated within a sideways market devoid of skewness.
Following pair selection, the user should refine the span of the rolling window. A broader window smoothens the mean, more accurately capturing long-term market trends, while potentially enhancing volatility. This refinement results in fewer, yet precise trading signals.
Finally, the user must settle on an optimal Z-Score threshold, which essentially dictates the timing for buy/sell actions when the Z-Score exceeds with thresholds. A positive threshold signifies the price veering away from its mean, triggering a sell signal. Conversely, a negative threshold denotes the price falling below its mean, illustrating an underpriced condition that prompts a buy signal.
Within a normal distribution, a Z-Score of 1 records about 68% of occurrences centered at the mean, while a Z-Score of 2 captures approximately 95% of occurrences.
The 'cool down period' is essentially the number of bars that await before the next signal generation. This feature is employed to dodge the occurrence of multiple signals in a short period.
DEFAULT SETUP
The following is the default setup on EURUSD 1h timeframe
Rolling Window: 80
Z-Score Threshold: 2.8
Signal Cool Down Period: 5
Commission: 0.03%
Initial Capital: $10,000
Equity per Trade: 30%
RISK DISCLAIMER
Trading entails substantial risk, and most day traders incur losses. All content, tools, scripts, articles, and education provided by TradeDots serve purely informational and educational purposes. Past performances are not definitive predictors of future results.
FreedX Grid Backtest█ FreedX Grid Backtest is an open-source tool that offers accurate GRID calculations for GRID trading strategies. This advanced tool allows users to backtest GRID trading parameters with precision, accurately reflecting exchange functionalities. We are committed to enhancing trading strategies through precise backtesting solutions and address the issue of unreliable backtesting practices observed on GRID trading strategies. FreedX Grid Backtest is designed for optimal calculation speed and plotting efficiency, ensuring users to achieve fastest calculations during their analysis.
█ GRID TRADING STRATEGY SETTINGS
The core of the FreedX Grid Backtest tool lies in its ability to simulate grid trading strategies. Grid trading involves placing orders at regular intervals within a predefined price range, creating a grid of orders that capitalize on market volatility.
Features:
⚙️ Backtest Range:
→ Purpose: Allows users to specify the backtesting range of GRID strategy. Closes all positions at the end of this range.
→ How to Use: Drag the dates to fit the desired backtesting range.
⚙️ Investment & Compounding:
→ Purpose: Allows users to specify the total investment amount and select between fixed and compound investment strategies. Compounding adjusts trade quantities based on performance, enhancing the grid strategy's adaptability to market changes.
→ How to Use: Set the desired investment amount and choose between "Fixed" or "Compound" for the investment method.
⚙️ Leverage & Grid Levels:
→ Purpose: Leverage amplifies the investment amount, increasing potential returns (and risks). Users can define the number of grid levels, which determines how the investment is distributed across the grid.
→ How to Use: Input the desired leverage and number of grids. The tool automatically calculates the distribution of funds across each grid level.
⚙️ Distribution Type & Mode:
→ Purpose: Users can select the distribution type (Arithmetic or Geometric) to set how grid levels are determined. The mode (Neutral, Long, Short) dictates the direction of trades within the grid.
→ How to Use: Choose the distribution type and mode based on the desired trading strategy and market outlook.
⚙️ Enable LONG/SHORT Grids exclusively:
█ MANUAL LEVELS AND STOP TRIGGERS
Beyond automated settings, the tool offers manual adjustments for traders seeking finer control over their grid strategies.
Features:
⚙️ Manual Level Adjustment:
→ Purpose: Enables traders to manually set the top, reference, and bottom levels of the grid, offering precision control over the trading range.
→ How to Use: Activate manual levels and adjust the top, reference, and bottom levels as needed to define the grid's scope.
⚙️ Stop Triggers:
→ Purpose: Provides an option to set upper and lower price limits, acting as stop triggers to close or terminate trades. This feature safeguards investments against significant market movements outside the anticipated range.
→ How to Use: Enable stop triggers and specify the upper and lower limits. The tool will automatically manage positions based on these parameters.
---
This guide gives you a quick and clear overview of the FreedX Grid Backtest tool, explaining how you can use this cutting-edge tool to improve your trading strategies.
Aroon and ASH strategy - ETHERIUM [IkkeOmar]Intro:
This post introduces a Pine Script strategy, as an example if anyone needs a push to get started. This example is a strategy on ETH, obviously it isn't a good strategy, and I wouldn't share my own good strategies because of alpha decay. This strategy combines two technical indicators: Aroon and Absolute Strength Histogram (ASH).
Overview:
The strategy employs the Aroon indicator alongside the Absolute Strength Histogram (ASH) to determine market trends and potential trade setups. Aroon helps identify the strength and direction of a trend, while ASH provides insights into the strength of momentum. By combining these indicators, the strategy aims to capture profitable trading opportunities in Ethereum markets. Normally when developing strats using indicators, you want to find some good indicators, but you NEED to understand their strengths and weaknesses, other indicators can be incorporated to minimize the downs of another indicator. Try to look for synergy in your indicators!
Indicator settings:
Aroon Indicator:
- Two sets of parameters are used for the Aroon indicator:
- For Long Positions: Aroon periods are set to 56 (upper) and 20 (lower).
- For Short Positions: Aroon periods are set to 17 (upper) and 55 (lower).
Absolute Strength Histogram (ASH):
ASH is calculated with a length of 9 bars using the closing price as the data source.
Trading Conditions:
The strategy incorporates specific conditions to initiate and exit trades:
Start Date:
Traders can specify the start date for backtesting purposes.
Trade Direction:
Traders can select the desired trade direction: Long, Short, or Both.
Entry and Exit Conditions:
1. Long Position Entry: A long position is initiated when the Aroon indicator crosses over (crossover) the lower Aroon threshold, indicating a potential uptrend.
2. Long Position Exit: A long position is closed when the Aroon indicator crosses under (crossunder) the lower Aroon threshold.
3. Short Position Entry: A short position is initiated when the Aroon indicator crosses under (crossunder) the upper Aroon threshold, signaling a potential downtrend.
4. Short Position Exit: A short position is closed when the Aroon indicator crosses over (crossover) the upper Aroon threshold.
Disclaimer:
THIS ISN'T AN OPTIMAL STRATEGY AT ALL! It was just an old project from when I started learning pine script!
The backtest doesn't promise the same results in the future, always do both in-sample and out-of-sample testing when backtesting a strategy. And make sure you forward test it as well before implementing it!
Bitcoin Leverage Sentiment - Strategy [presentTrading]█ Introduction and How it is Different
The "Bitcoin Leverage Sentiment - Strategy " represents a novel approach in the realm of cryptocurrency trading by focusing on sentiment analysis through leveraged positions in Bitcoin. Unlike traditional strategies that primarily rely on price action or technical indicators, this strategy leverages the power of Z-Score analysis to gauge market sentiment by examining the ratio of leveraged long to short positions. By assessing how far the current sentiment deviates from the historical norm, it provides a unique lens to spot potential reversals or continuation in market trends, making it an innovative tool for traders who wish to incorporate market psychology into their trading arsenal.
BTC 4h L/S Performance
local
█ Strategy, How It Works: Detailed Explanation
🔶 Data Collection and Ratio Calculation
Firstly, the strategy acquires data on leveraged long (**`priceLongs`**) and short positions (**`priceShorts`**) for Bitcoin. The primary metric of interest is the ratio of long positions relative to the total of both long and short positions:
BTC Ratio=priceLongs / (priceLongs+priceShorts)
This ratio reflects the prevailing market sentiment, where values closer to 1 indicate a bullish sentiment (dominance of long positions), and values closer to 0 suggest bearish sentiment (prevalence of short positions).
🔶 Z-Score Calculation
The Z-Score is then calculated to standardize the BTC Ratio, allowing for comparison across different time periods. The Z-Score formula is:
Z = (X - μ) / σ
Where:
- X is the current BTC Ratio.
- μ is the mean of the BTC Ratio over a specified period (**`zScoreCalculationPeriod`**).
- σ is the standard deviation of the BTC Ratio over the same period.
The Z-Score helps quantify how far the current sentiment deviates from the historical norm, with high positive values indicating extreme bullish sentiment and high negative values signaling extreme bearish sentiment.
🔶 Signal Generation: Trading signals are derived from the Z-Score as follows:
Long Entry Signal: Occurs when the BTC Ratio Z-Score crosses above the thresholdLongEntry, suggesting bullish sentiment.
- Condition for Long Entry = BTC Ratio Z-Score > thresholdLongEntry
Long Exit/Short Entry Signal: Triggered when the BTC Ratio Z-Score drops below thresholdLongExit for exiting longs or below thresholdShortEntry for entering shorts, indicating a shift to bearish sentiment.
- Condition for Long Exit/Short Entry = BTC Ratio Z-Score < thresholdLongExit or BTC Ratio Z-Score < thresholdShortEntry
Short Exit Signal: Happens when the BTC Ratio Z-Score exceeds the thresholdShortExit, hinting at reducing bearish sentiment and a potential switch to bullish conditions.
- Condition for Short Exit = BTC Ratio Z-Score > thresholdShortExit
🔶Implementation and Visualization: The strategy applies these conditions for trade management, aligning with the selected trade direction. It visualizes the BTC Ratio Z-Score with horizontal lines at entry and exit thresholds, illustrating the current sentiment against historical norms.
█ Trade Direction
The strategy offers flexibility in trade direction, allowing users to choose between long, short, or both, depending on their market outlook and risk tolerance. This adaptability ensures that traders can align the strategy with their individual trading style and market conditions.
█ Usage
To employ this strategy effectively:
1. Customization: Begin by setting the trade direction and adjusting the Z-Score calculation period and entry/exit thresholds to match your trading preferences.
2. Observation: Monitor the Z-Score and its moving average for potential trading signals. Look for crossover events relative to the predefined thresholds to identify entry and exit points.
3. Confirmation: Consider using additional analysis or indicators for signal confirmation, ensuring a comprehensive approach to decision-making.
█ Default Settings
- Trade Direction: Determines if the strategy engages in long, short, or both types of trades, impacting its adaptability to market conditions.
- Timeframe Input: Influences signal frequency and sensitivity, affecting the strategy's responsiveness to market dynamics.
- Z-Score Calculation Period: Affects the strategy’s sensitivity to market changes, with longer periods smoothing data and shorter periods increasing responsiveness.
- Entry and Exit Thresholds: Set the Z-Score levels for initiating or exiting trades, balancing between capturing opportunities and minimizing false signals.
- Impact of Default Settings: Provides a balanced approach to leverage sentiment trading, with adjustments needed to optimize performance across various market conditions.
Octopus Nest Strategy Hello Fellas,
Hereby, I come up with a popular strategy from YouTube called Octopus Nest Strategy. It is a no repaint, lower timeframe scalping strategy utilizing PSAR, EMA and TTM Squeeze.
The strategy considers these market factors:
PSAR -> Trend
EMA -> Trend
TTM Squeeze -> Momentum and Volatility by incorporating Bollinger Bands and Keltner Channels
Note: As you can see there is a potential improvement by incorporating volume.
What's Different Compared To The Original Strategy?
I added an option which allows users to use the Adaptive PSAR of @loxx, which will hopefully improve results sometimes.
Signals
Enter Long -> source above EMA 100, source crosses above PSAR and TTM Squeeze crosses above 0
Enter Short -> source below EMA 100, source crosses below PSAR and TTM Squeeze crosses below 0
Exit Long and Exit Short are triggered from the risk management. Thus, it will just exit on SL or TP.
Risk Management
"High Low Stop Loss" and "Automatic High Low Take Profit" are used here.
High Low Stop Loss: Utilizes the last high for short and the last low for long to calculate the stop loss level. The last high or low gets multiplied by the user-defined multiplicator and if no recent high or low was found it uses the backup multiplier.
Automatic High Low Take Profit: Utilizes the current stop loss level of "High Low Stop Loss" and gets calculated by the user-defined risk ratio.
Now, follows the bunch of knowledge for the more inexperienced readers.
PSAR: Parabolic Stop And Reverse; Developed by J. Welles Wilders and a classic trend reversal indicator.
The indicator works most effectively in trending markets where large price moves allow traders to capture significant gains. When a security’s price is range-bound, the indicator will constantly be reversing, resulting in multiple low-profit or losing trades.
TTM Squeeze: TTM Squeeze is a volatility and momentum indicator introduced by John Carter of Trade the Markets (now Simpler Trading), which capitalizes on the tendency for price to break out strongly after consolidating in a tight trading range.
The volatility component of the TTM Squeeze indicator measures price compression using Bollinger Bands and Keltner Channels. If the Bollinger Bands are completely enclosed within the Keltner Channels, that indicates a period of very low volatility. This state is known as the squeeze. When the Bollinger Bands expand and move back outside of the Keltner Channel, the squeeze is said to have “fired”: volatility increases and prices are likely to break out of that tight trading range in one direction or the other. The on/off state of the squeeze is shown with small dots on the zero line of the indicator: red dots indicate the squeeze is on, and green dots indicate the squeeze is off.
EMA: Exponential Moving Average; Like a simple moving average, but with exponential weighting of the input data.
Don't forget to check out the settings and keep it up.
Best regards,
simwai
---
Credits to:
@loxx
@Bjorgum
@Greeny
Hulk Grid Algorithm V2 - The Quant ScienceIt's the latest proprietary grid algorithm developed by our team. This software represents a clearer and more comprehensive modernization of the deprecated Hulk Grid Algorithm. In this new release, we have optimized the source code architecture and investment logic, which we will describe in detail below.
Overview
Hulk Grid Algorithm V2 is designed to optimize returns in sideways market conditions. In this scenario, the algorithm divides purchases with long orders at each level of the grid. Unlike a typical grid algorithm, this version applies an anti-martingale model to mitigate volatility and optimize the average entry price. Starting from the lower level, the purchase quantity is increased at each new subsequent level until reaching the upper level. The initial quantity of the first order is fixed at 0.50% of the initial capital. With each new order, the initial quantity is multiplied by a value equal to the current grid level (where 1 is the lower level and 10 is the upper level).
Example: Let's say we have an initial capital of $10,000. The initial capital for the first order would be $50 * 1 = $50, for the second order $50 * 2 = $100, for the third order $50 * 3 = $150, and so on until reaching the upper level.
All previously opened orders are closed using a percentage-based stop-loss and take-profit, calculated based on the extremes of the grid.
Set Up
As mentioned earlier, the user's goal is to analyze this strategy in markets with a lack of trend, also known as sideways markets. After identifying a price range within which the asset tends to move, the user can choose to create the grid by placing the starting price at the center of the range. This way, they can consider trading the asset, if the backtesting generates a return greater than the Buy & Hold return.
Grid Configuration
To create the grid, it's sufficient to choose the starting price during the launch phase. This level will be the center of the grid from which the upper and lower levels will be calculated. The grid levels are computed using an arithmetic method, adding and subtracting a configurable fixed amount from the user interface (Grid Step $).
Example: Let's imagine choosing 1000 as the starting price and 50 as the Grid Step ($). The upper levels will be 1000, 1050, 1100, 1150, 1200. The lower levels will be 950, 900, 850, 800, and 750.
Markets
This software can be used in all markets: stocks, indices, commodities, cryptocurrencies, ETFs, Forex, etc.
Application
With this backtesting software, is possible to analyze the strategy and search for markets where it can generate better performance than Buy & Hold returns. There are no alerts or automatic investment mechanisms, and currently, the strategy can only be executed manually.
Design
Is possible to modify the grid style and customize colors by accessing the Properties section of the user interface.
Pairs strategyHello, Tradingview community,
I am been playing with this idea that nowadays trading instruments are interconnected and when one goes too far "out of order" it should return to the mean.
So, here's a relatively simple idea.
This is a LONG-ONLY strategy.
Buy when your traded instrument's last bar closes down, and the comparing instrument closes up.
Sell when close is higher than the previous bar's high.
Best results I found with medium timeframes: 45min, 120min, 180min.
Also, feel free to test non-typical timeframes such as 59min, 119min, 179min, etc.
My reasoning for medium timeframes would be, that they are big enough to avoid "market noise"
of smaller timeframes + commissions & slippage is less negligible, and small enough to avoid exposure of higher timeframes, although, I haven't tested D timeframe and above.
The best results, I found were with instruments that aren't directly correlated. I mostly tested equities and equity futures, so for equity indexes, equity index futures, or large-cap stocks, NASDAQ:SMH , NASDAQ:NVDA , EURUSD, and Crude Oil would be a good candidate for comparing symbols.
When testing either futures or stocks, please adjust the commission for each asset, for stocks I use % equity, so it compounds over time, whereas, for futures, I use 1 contract all the time.
Here's NASDAQ:MSFT on 119min chart
Here's AMEX:SPY on 59min chart using NASDAQ:NVDA as comparison
Here's CME_MINI:ES1! on 179min chart using NYMEX:CL1! as comparison
To change comparison symbol just insert your symbol between the brackets on both fields down here.
SymbolClose = request.security("YOUR SYMBOL HERE", timeframe.period, close)
SymbolOpen = request.security("YOUR SYMBOL HERE", timeframe.period, open)
Since I am still relatively new to testing, hence, I am publishing this idea, so you can point out some crucial things I may have missed.
Thanks,
Enjoy the strategy!
Session Breakout Scalper Trading BotHi Traders !
Introduction:
I have recently been exploring the world of automated algorithmic trading (as I prefer more objective trading strategies over subjective technical analysis (TA)) and would like to share one of my automation compatible (PineConnecter compatible) scripts “Session Breakout Scalper”.
The strategy is really simple and is based on time conditional breakouts although has more ”relatively” advanced optional features such as the regime indicators (Regime Filters) that attempt to filter out noise by adding more confluence states and the ATR multiple SL that takes into account volatility to mitigate the down side risk of the trade.
What is Algorthmic Trading:
Firstly what is algorithmic trading? Algorithmic trading also known as algo-trading, is a method of using computer programs (in this case pine script) to execute trades based on predetermined rules and instructions (this trading strategy). It's like having a robot trader who follows a strict set of commands to buy and sell assets automatically, without any human intervention.
Important Note:
For Algorithmic trading the strategy will require you having an essential TV subscription at the minimum (so that you can set alerts) plus a PineConnecter subscription (scroll down to the .”How does the strategy send signals” headings to read more)
The Strategy Explained:
Is the Time input true ? (this can be changed by toggling times under the “TRADE MEDIAN TIMES” group for user inputs).
Given the above is true the strategy waits x bars after the session and then calculates the highest high (HH) to lowest low (LL) range. For this box to form, the user defined amount of bars must print after the session. The box is symmetrical meaning the HH and LL are calculated over a lookback that is equal to the sum of user defined bars before and after the session (+ 1).
The Strategy then simultaneously defines the HH as the buy level (green line) and the LL as the sell level (red line). note the strategy will set stop orders at these levels respectively.
Enter a buy if price action crosses above the HH, and then cancel the sell order type (The opposite is true for a stop order).
If the momentum based regime filters are true the strategy will check for the regime / regimes to be true, if the regime if false the strategy will exit the current trade, as the regime filter has predicted a slowing / reversal of momentum.
The image below shows the strategy executing these trading rules ( Regime filters, "Trades on chart", "Signal & Label" and "Quantity" have been omitted. "Strategy label plots" has been switched to true)
Other Strategy Rules:
If a new session (time session which is user defined) is true (blue vertical line) and the strategy is currently still in a trade it will exit that trade immediately.
It is possible to also set a range of percentage gain per day that the strategy will try to acquire, if at any point the strategy’s profit is within the percentage range then the position / trade will be exited immediately (This can be changed in the “PERCENT DAY GAIN” group for user inputs)
Stops and Targets:
The strategy has either static (fixed) or variable SL options. TP however is only static. The “STRAT TP & TP” group of user inputs is responsible for the SL and TP values (quoted in pips). Note once the ATR stop is set to true the SL values in the above group no longer have any affect on the SL as expected.
What are the Regime Filters:
The Larry Williams Large Trade Index (LWLTI): The Larry Williams Large Trade Index (LWTI) is a momentum-based technical indicator developed by iconic trader Larry Williams. It identifies potential entries and exits for trades by gauging market sentiment, particularly the buying and selling pressure from large market players. Here's a breakdown of the LWTI:
LWLTI components and their interpretation:
Oscillator: It oscillates between 0 and 100, with 50 acting as the neutral line.
Sentiment Meter: Values above 75 suggest a bearish market dominated by large selling, while readings below 25 indicate a bullish market with strong buying from large players.
Trend Confirmation: Crossing above 75 during an uptrend and below 25 during a downtrend confirms the trend's continuation.
The Andean Oscillator (AO) : The Andean Oscillator is a trend and momentum based indicator designed to measure the degree of variations within individual uptrends and downtrends in the prices.
Regime Filter States:
In trading, a regime filter is a tool used to identify the current state or "regime" of the market.
These Regime filters are integrated within the trading strategy to attempt to lower risk (equity volatility and/or draw down). The regime filters have different states for each market order type (buy and sell). When the regime filters are set to true, if these regime states fail to be true the trade is exited immediately.
For Buy Trades:
LWLTI positive momentum state: Quotient of the lagged trailing difference and the ATR > 50
AO positive momentum state: Bull line > Bear line (signal line is omitted)
For Sell Trades:
LWLTI negative momentum stat: Quotient of the lagged trailing difference and the ATR < 50
AO negative momentum state: Bull line < Bear line (signal line is omitted)
How does the Strategy Send Signals:
The strategy triggers a TV alert (you will neet to set a alert first), TV then sends a HTTP request to the automation software (PineConnecter) which receives the request and then communicates to an MT4/5 EA to automate the trading strategy.
For the strategy to send signals you must have the following
At least a TV essential subscription
This Script added to your chart
A PineConnecter account, which is paid and not free. This will provide you with the expert advisor that executes trades based on these strategies signals.
For more detailed information on the automation process I would recommend you read the PineConnecter documentation and FAQ page.
Dashboard:
This Dashboard (top right by defualt) lists some simple trading statistics and also shows when a trade is live.
Important Notice:
- USE THIS STRATEGY AT YOUR OWN RISK AND ALWAYS DO YOUR OWN RESEARCH & MANUAL BACKTESTING !
- THE STRATEGY WILL NOT EXHIBIT THE BACKTEST PERFORMANCE SEEN BELOW IN ALL MARKETS !
COSTAR Strategy [SS]A little late posting this but here it is, as promised!
This is the companion to the COSTAR indicator.
What it does:
It creates a co-integration paired relationship with a separate, cointegrated ticker. It then plots out the expected range based on the value of the cointegrated pair. When the current ticker is below the value of its co-integrated partner, it becomes a "Buy" and should be longed. When it becomes overvalued in comparison, it becomes a "Sell" and should be shorted.
The example above is with BA and USO, which have a strong inverse relationship.
How it works:
I made the strategy version a bit more intuitive. Instead of you selecting the parameters for your model, it will autoselect the ideal parameters based on your desired co-integrated pair. You simply enter the ticker you want to compare against, and it will sort through the values at various lags to find significance and stationarity. It will then create a model and plot the model out for you on your chart, as you can see above.
The premise of the strategy:
The premise of the strategy is as stated before. You long when the ticker is undervalued in comparison to its co-integrated pair, and short when it is overvalued. The conditions for entry are simply a co-integrated pair being over the expected range (short) or below the expected range (long).
The condition to exit is a "re-integration", or a crossover of the expected value of the ticker (the centreline).
What if it can't find a relationship?
In some instances, the indicator will not be able to determine a co-integrated relationship, owning to a lack of stationarity between the data. When this happens, you will get the following error:
The indicator provides you with prompts, such as switching the timeframe or trying an alternative ticker. In the case displayed above, if we simply switch to the 1 hour timeframe, we have a viable model with great backtest results:
You can toggle in the settings menu the various parameters, such as timeframe, fills and displays.
And that is the strategy in a nutshell, be sure to check out its partner indicator, COSTAR, for more information on the premise of using co-integrated models for trading. And let me know your questions below!
Safe trades everyone!
Stx Monthly Trades ProfitMonthly profit displays profits in a grid and allows you to know the gain related to the investment during each month.
The profit could be computed in terms of gain/trade_cost or as percentage of equity update.
Settings:
- Profit: Monthly profit percentage or percentage of equity
- Table position
This strategy is intended only as a container for the code and for testing the script of the profit table.
Setting of strategy allows to select the test case for this snippet (percentage grid).
Money management: not relevant as strategy is a test case.
This script stand out as take in account the gain of each trade in relation to the capital invested in each trade. For example consider the following scenario:
Capital of 1000$ and we invest a fixed amount of 1000$ (I know is too risky but is a good example), we gain 10% every month.
After 10 months our capital is of 2000$ and our strategy is perfect as we have the same performance every month.
Instead, evaluating the percentage of equity we have 10% the first month, 9.9% the second (1200$/1100$ - 1) and 5.26% the tenth month. So seems that strategy degrade with times but this is not true.
For this reason, to evaluate my strategy I prefer to see the montly return of investment.
WARNING: The strategy provided with this script is only a test case and allows to see the behavior with different "trades" management, for these reason commision are set to zero.
At the moment only the provided test cases are handled:
test 1 - single entry and single exit;
test 2 - single entry and multiple exits;
test 3 - single entry and switch position;
Strategy Gaussian Anomaly DerivativeConcept behind this Strategy :
Considering a normal "buy/sell" situation, an asset would be bought in average at the median price following a Gaussian like concept. A higher or lower average trend would significate that the current perceived value is respectively higher or lower than the current median price, which mean that the buyers are evaluating the price underpriced or overpriced.
This behaviour would be even more relevent depending on its derivative evolution.
Therefore, this Strategy setup is based on this Gaussian like concept anomaly of average close positionning compare to high-low average derivative, such as the derivative of the following ploted basic signal : 1-(high+low)/(2*close).
This Strategy can actually be used like a trend change and continuation strength indicator aswell.
In the Setup Signal part :
You can define the filtering of the basis signal "1-(high+low)/(2*close)" on EMA or SMA as you wish.
You can define the corresponding period and the threathold as a mutiply of the average 1/3 of all time value of the basis signal.
You can define the SMA filtering period of the Derivative signal and the corresponding threathold on the same mutiply of the average 1/3 of all time value of the derivative.
In the Setup Strategy part :
You can set up your strategy assesment based on Long and/or Short. You can also define the considered period.
The most successful tuned strategies I did were based on the derivative indicator with periods on the basis signal and the derivative under 30, can be 1 to 3 of te derivative and 7 to 21 for the basis signal. The threathold depends on the asset volatility aswell, 1 is usually the most efficient but 0 to 10 can be relevent depending on the situation I met. You can find an example of tuning for this strategy based on Kering's case hereafter.
I hoping that you will enjoy using this Strategy, don't hesitate to comment, to question, to correct or complete it ! I would be very curious about similar famous approaches that would have already been made.
Thank to you !
CC Trend strategy 2- Downtrend ShortTrend Strategy #2
Indicators:
1. EMA(s)
2. Fibonacci retracement with a mutable lookback period
Strategy:
1. Short Only
2. No preset Stop Loss/Take Profit
3. 0.01% commission
4. When in a profit and a closure above the 200ema, the position takes a profit.
5. The position is stopped When a closure over the (0.764) Fibonacci ratio occurs.
* NO IMMEDIATE RE-ENTRIES EVER!*
How to use it and what makes it unique:
This strategy will enter often and stop quickly. The goal with this strategy is to take losses often but catch the big move to the downside when it occurs through the Silvercross/Fibonacci combination. This is a unique strategy because it uses a programmed Fibonacci ratio that can be used within the strategy and on any program. You can manipulate the stats by changing the lookback period of the Fibonacci retracement and looking at different assets/timeframes.
This description tells the indicators combined to create a new strategy, with commissions and take profit/stop loss conditions included, and the process of strategy execution with a description of how to use it. If you have any questions feel free to PM me and boost if you found it helpful. Thank you, pineUSERS!
CHEATCODE1
Risk to Reward - FIXED SL BacktesterDon't know how to code? No problem! TradingView is an excellent platform for you. ✅ ✅
If you have an indicator that you want to backtest using a risk-to-reward ratio or fixed take profit/stop loss levels, then the Risk to Reward - FIXED SL Backtester script is the perfect solution for you.
introducing Risk to Reward - FIXED SL Backtester Script which will allow you to test any indicator / Signal with RR or Fixed SL system
How does it work ?!
Once you connect the script to your indicator, it will analyze your entry points and perform calculations based on them. It will then open trades for you according to the specified inputs in the script settings.
HOW TO CONNECT IT to your indicator?
simply open your indicator code and add the below line of code to it
plot(Signal ? 100 : 0,"Signal",display = display.data_window)
Replace Signal with the long condition from your own indicator. You can also modify the value 100 to any number you prefer. After that, open the settings.
Once the script is connected to your indicator, you can choose from two options:
Risk To Reward Ratio System
Fixed TP/ SL System
🔸if you select the Risk to Reward System ⤵️
The Risk-to-Reward System requires the calculation of a stop loss. That's why I have included three different types of stop-loss calculations for you to choose from:
ATR Based SL
Pivot Low SL
VWAP Based SL
Your stop loss and take profit levels will be automatically calculated based on the selected stop loss method and your risk-to-reward ratio.
You can also adjust their values to match your desired risk level. The trades will be displayed on the chart.
with the ability to change their values to match your risk.
once this is done, trades will be displayed on the chart
🔸if you select the Fixed system ⤵️
You have 2 inputs, which are FIXED TP & Fixed SL
input the values you want, and trades will be on your chart...
I have also added a Breakeven feature for you.
with this Breakeven feature the trade will not just move SL to Entry ?! NO NO, it will place it above entry by a % you input yourself, so you always win! 🚀
Here is an example
Enjoy, and have fun, if you have any questions do not hesitate to ask
Buy&Sell Bullish Engulfing - The Quant Science🇺🇸
GENERAL OVERVIEW
Buy&Sell Bullish Engulfing - The Quant Science It is a Buy&Sell strategy based on the 'Bullish Engulfing' candlestick pattern. The main goal of the strategy is to achieve a consistent and sustainable return over time, with a manageable level of risk.
Bullish Engulfing
The template was developed at the top of the Indicator provided by TradingView called 'Engulfing - Bullish'.
ENTRY AND EXIT CRITERIA
Entry: A single long order is opened when the candlestick pattern is formed, and the percentage size of the order (%) is fixed by the trader through the user interface.
Exit: The long trade is closed on a percentage equity take profit-stop loss.
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
🇮🇹
PANORAMICA GENERALE
Buy&Sell Bullish Engulfing - The Quant Science è una strategia Buy&Sell basata sul candlestick pattern 'Bullish Engulfing'. L'obiettivo principale della strategia è ottenere un ritorno costante e sostenibile nel tempo, con un livello gestibile di rischio.
Bullish Engulfing
Il template è stato sviluppato al top dell' Indicatore fornito da Trading View chiamato 'Engulfing - Bullish'.
CRITERI DI ENTRATA E USCITA
Entrata: viene aperto un singolo ordine long quando si forma il candlestick pattern, la size percentuale dell'ordine (%) viene selezionato tramite l'interfaccia utente dal trader.
Uscita: la chiusura della posizione avviene unicamente tramite un take profit-stop loss percentuale calcolato sul capitale.
Default Strategy Template© CN_FX-999
Coded By Christian Nataliano
First Coded In 14/06/2023
Last Edited In 22/06/2023
This Is A Default Strategy Template That Can Make Your Strategy Scripts More Organized With The Benefit Of Having The Same Layouts & Not Needing To Copy Over The Common Codes Such As Displaying Backtest Results, Opening & Closing Trades, Pine Connector Capabilities And A Clean User Input Interface. This Is A Blank Strategy Script So Feel Free To Use It As Your Default Template For Your Future Strategies.
Credits To Some Of The Custom Code In The Scripts To © ZenAndTheArtOfTrading, Especially The Table Data Plotting
The Z-score The Z-score, also known as the standard score, is a statistical measurement that describes a value's relationship to the mean of a group of values. It's measured in terms of standard deviations from the mean. If a Z-score is 0, it indicates that the data point's score is identical to the mean score. Z-scores may be positive or negative, with a positive value indicating the score is above the mean and a negative score indicating it is below the mean.
The concept of Z-score was introduced by statistician Carl Friedrich Gauss as part of his "method of the least squares," which was an important step in the development of the normal distribution and Z-score tables. It's a key concept in statistics and is used in various statistical tests.
In financial analysis, Z-scores are used to determine whether a data point is usual or unusual. You can think of it as a measure of how many standard deviations an element is from the mean. For instance, a Z-score of 1.0 would denote a value that is one standard deviation from the mean. Z-scores are also used to predict probabilities, with Z-scores having a distribution that is expected to be normal.
In trading, a Z-score is used to determine how often a trading system may produce a string of winners or losers. It can help a trader to understand whether the losses or profits they see are something that the system would most likely produce, or if it's a once in a blue moon situation. This helps traders make decisions about when to start or stop a system.
I just wanted to play a bit with the Z-score I guess.
Feel free to share your findings if you discover additional applications for this strategy or identify timeframes where it appears to perform more optimally.
How it works:
This strategy is based on a statistical concept called Z-score, which measures the number of standard deviations a data point is from the mean. In other words, it helps determine how unusual or usual a data point is.
In the context of this strategy, Z-score is applied to a 10-period EMA (Exponential Moving Average) of Heikin-Ashi candlestick close prices. The Z-score is calculated over a look-back period of 25 bars.
The EMA of the Z-score is then calculated over a 20-bar period, and the upper and lower thresholds (bounds for buy and sell signals) are defined using the 90th and 10th percentiles of this EMA score.
Long positions are taken when the Z-score crosses above the lower threshold or crosses above the mid-line (50th percentile). An additional long entry is made when the Z-score crosses above the highest value the EMA has been in the past 100 periods.
Short positions are initiated when the EMA crosses below the upper threshold, lower threshold or the highest value the EMA has been in the past 100 periods.
Positions are closed when opposing entry conditions are met, for example, a long position is closed when the short entry condition is true, and vice versa.
Set your desired start date for the strategy. This can be modified in the timestamp("YYYY MM DD") function at the top of the script.
Monthly Strategy Performance TableWhat Is This?
This script code adds a Monthly Strategy Performance Table to your Pine Script strategy scripts so you can see a month-by-month and year-by-year breakdown of your P&L as a percentage of your account balance.
The table is based on realized equity rather than open equity, so it only updates the metrics when a trade is closed.
That's why some numbers will not match the Strategy Tester metrics (such as max drawdown), as the Strategy Tester bases metrics like max drawdown on open trade equity and not realized equity (closed trades).
The script is still a work-in-progress, so make sure to read the disclaimer below. But I think it's ready to release the code for others to play around with.
How To Use It
The script code includes one of my strategies as an example strategy. You need to replace my strategy code with your own. To do that just copy the source code below into a blank script, delete lines 11 -> 60 and paste your strategy code in there instead of mine. The script should work with most systems, but make sure to read the disclaimer below.
It works best with a significant amount of historical data, so it may not work very effectively on intraday timeframes as there is a severe limitation of available bars on TradingView. I recommend using it on 4HR timeframes and above, as anything less will produce very little usable data. Having a premium TradingView plan will also help boost the number of available bars.
You can hover your mouse over a table cell to get more information in the form of tooltips (such as the Long and Short win rate if you hover over your total return cell).
Credit
The code in this script is based on open-source code originally written by QuantNomad, I've made significant changes and additions to the original script but all credit for the idea and especially the display table code goes to them - I just built on top of it:
Why Did I Make This?
None of this is trading or investment advice, just my personal opinion based on my experience as a trader and systems developer these past 6+ years:
The TradingView Strategy Tester is severely limited in some important ways. And unless you use complex Excel formulas on exported test data, you can't see a granular perspective of your system's historical performance.
There is much more to creating profitable and tradeable systems than developing a strategy with a good win rate and a good return with a reasonable drawdown.
Some additional questions we need to ask ourselves are:
What did the system's worst drawdown look like?
How long did it last?
How often do drawdowns occur, and how quickly are they typically recovered?
How often do we have a break-even or losing month or year?
What is our expected compounded annual growth rate, and how does that growth rate compare to our max drawdown?
And many more questions that are too long to list and take a lifetime of trading experience to answer.
Without answering these kinds of questions, we run the risk of developing systems that look good on paper, but when it comes to live trading, we are uncomfortable or incapable of enduring the system's granular characteristics.
This Monthly Performance Table script code is intended to help bridge some of that gap with the Strategy Tester's limited default performance data.
Disclaimer
I've done my best to ensure the numbers this code outputs are accurate, and according to my testing with my personal strategy scripts it appears to work fine. But there is always a good chance I've missed something, or that this code will not work with your particular system.
The majority of my TradingView systems are extremely simple single-target systems that operate on a closed-candle basis to minimize many of the data reliability issues with the Strategy Tester, so I was unable to do much testing with multiple targets and pyramiding etc.
I've included a Debug option in the script that will display important data and information on a label each time a trade is closed. I recommend using the Debug option to confirm that the numbers you see in the table are accurate and match what your strategy is actually doing.
Always do your own due diligence, verify all claims as best you can, and never take anyone's word for anything.
Take care, and best of luck with your trading :)
Kind regards,
Matt.
PS. If you're interested in learning how this script works, I have a free hour-long video lesson breaking down the source code - just check out the links below this script or in my profile.
Initial Balance Panel Strategy for BitcoinInitial Balance Strategy
Initial Balance Strategy uses a source code of "Initial Balance Monitoring Panel" that build from "Initial Balance Markets Time Zones - Overall Highest and Lowest".
Initial Balance is based on the highest and lowest price action within the first 60 minutes of trading. Reading online this can depict which way the market can trend for the session. More information about Initial Balance Panel you can read at the end of the article.
Strategy idea
The main idea is to catch the trend move when most of the 16 Crypto pairs break the Low or High levels together. I found good results when 15 of 16 pairs is break that levels and after we manage the trade within some trail stop indicator, I choose Volatility Stop for this strategy.
Additional Strategy idea
The second one idea that was not made is to catch the pullback after fully green/red zones in Initial Balance Panel become white. That mean the main trend can be finished and we can try to catch good pullback in opposite direction.
Binance Crypto pairs
The strategy use the 16 default Crypto currencies pairs from the Binance. As additional variations of the strategy can be changing the currencies pairs and their number.
List of default pairs:
BINANCE:BTCUSDT, BINANCE:ETHUSDT, BINANCE:EOSUSDT, BINANCE:LTCUSDT, BINANCE:XRPUSDT, BINANCE:DASHUSDT, BINANCE:IOTAUSDT, BINANCE:NEOUSDT, BINANCE:QTUMUSDT, BINANCE:XMRUSDT, BINANCE:ZECUSDT, BINANCE:ETCUSDT, BINANCE:ADAUSDT, BINANCE:XTZUSDT, BINANCE:LINKUSDT, BINANCE:DOTUSDT
Summary
The strategy works very well for a buy trades with settings 15 crypto pairs of 16 that follow the trend with breaking the long initial balance level.
Initial Balance Monitoring Panel
Allows you to have an instant view of 16 Crypto pairs within a monitoring panel, monitoring Initial Balance (Asia, London, New York Stock Exchanges).
The code can easily be changed to suit the crypto pairs you are trading.
The setup of my chart would also include this indicator and the "Initial Balance Markets Time Zones - Overall Highest and Lowest" (with all IBs enabled) as shown above.
Initial Balance is based on the highest and lowest price action within the first 60 minutes of trading. Reading online this can depict which way the market can trend for the session.
The indicator has been coded for Crypto (so other symbols may not work as expected).
Though Initial Balance is based off the first 60 minutes of the trading markets opening, but Crypto is 24/7, this indicator looks at how Asia, London and New York Stock Exchanges opening trading can affect Crypto price action.
Source: Initial Balance Monitoring Panel
Grid Spot Trading Algorithm V2 - The Quant ScienceGrid Spot Trading Algorithm V2 is the last grid trading algorithm made by our developer team.
Grid Spot Trading Algorithm V2 is a fixed 10-level grid trading algorithm. The grid is divided into an accumulation area (red) and a selling area (green).
In the accumulation area, the algorithm will place new buy orders, selling the long positions on the top of the grid.
BUYING AND SELLING LOGIC
The algorithm places up to 5 limit orders on the accumulation section of the grid, each time the price cross through the middle grid. Each single order uses 20% of the equity.
Positions are closed at the top of the grid by default, with the algorithm closing all orders at the first sell level. The exit level can be adjusted using the user interface, from the first level up to the fifth level above.
CONFIGURING THE ALGORITHM
1) Add it to the chart: Add the script to the current chart that you want to analyze.
2) Select the top of the grid: Confirm a price level with the mouse on which to fix the top of the grid.
3) Select the bottom of the grid: Confirm a price level with the mouse on which to fix the bottom of the grid.
4) Wait for the automatic creation of the grid.
USING THE ALGORITHM
Once the grid configuration process is completed, the algorithm will generate automatic backtesting.
You can add a stop loss that destroys the grid by setting the destruction price and activating the feature from the user interface. When the stop loss is activated, you can view it on the chart.
Strategy DesignerHello traders.
Thanks to the tool I have published, everyone who knows or does not know coding will be able to create strategies and see the results instantly on the screen. Yes it looks very nice :)
What does this script do?
Thanks to this tool, even if you don't know any coding, you will be able to create your own strategies. You can add and remove indicators.
Entrance
The first thing you need to do is to set a strategy in your mind.
Then you need to adjust the settings of the indicators installed in the system. Please set the indicators first, because later they are forgotten.
The screen for entering the parameters of the indicators will be as follows.
After entering the parameters there is an important part . In this section, we can adjust the strategy settings.
First we choose between which dates we want the strategy to run. We then choose whether we want the strategy results to be displayed in a table or not.
We choose how the Terms should be linked together. For example, if you have a condition that is expected to produce more than one receive signal, select whether these conditions are connected to each other with and or with the connector.
In this way, you can determine whether all or any of the rules in your strategy should apply.
Next, we choose whether our strategy will work in the spot market or in a bidirectional market. Yes, you can design a strategy for both spot and bidirectional trades :)
At the bottom of the above image, we see a screen where we can adjust the stop level and tp level. As a standard, adjustments are made according to the percentage level you enter. However, if you remove the tick next to the percent sign, the previous stop level and the next profit level are determined as much as the value you entered.
At the bottom is the trailing stop. When you open the trailing stop, the trailing stop becomes active in your strategy.
Very important, when the trailing stop and the stop are active at the same time, the trailing stop value is valid.
It's time to design our strategy. Each chapter that begins with an exclamation point is a separate fiction.
If you do not mark the Active button, that condition will not be included in the calculation.
Direction = It is the direction for which the fiction in this region is valid.
We came to the indicator setting screen. Here, there is a screen where we can select two different indicators on the right and left.
We choose the first indicator starting with 1.
Then we choose from the middle region how we want these two indicators to interact.
We choose our second indicator from the place starting with 2.
If you want an indicator to interact with any value, tick the box where it says Value and fill in the value in the blank. When Value is ticked, the second indicator does not work.
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!