Custom Buy BID StrategyThis Pine Script strategy is designed to identify and capitalize on upward trends in the market using the Average True Range (ATR) as a core component of the analysis. The script provides the following features:
Customizable ATR Calculation: Users can switch between different methods of ATR calculation (traditional or simple moving average).
Adjustable Parameters: The strategy allows for adjustable ATR periods, ATR multipliers, and custom time windows for executing trades.
Buy Signal Alerts: The strategy generates buy signals when the market shifts from a downtrend to an uptrend, based on ATR and price action.
Profit and Stop-Loss Management: Built-in take profit and stop-loss conditions are calculated as a percentage of the entry price, allowing for automatic position management.
Visual Enhancements: The script highlights the uptrend with green lines and optionally colors bars to help visualize market direction.
Flexible Timeframe: Users can configure a specific date range to activate the strategy, offering more control over when trades are executed.
This strategy is ideal for traders looking to automate their buy entries and manage risk with a straightforward trend-following approach. By utilizing customizable settings, it adapts to various market conditions and timeframes.
Moving Averages
Trend Magic with EMA, SMA, and Auto-TradingRelease Notes
Strategy Name: Trend Magic with EMA, SMA, and Auto-Trading
Purpose: This strategy is designed to capture entry and exit points in the market using the Trend Magic indicator and three moving averages (EMA45, SMA90, and SMA180). Specifically, it uses the perfect order of the moving averages and the color changes in Trend Magic to identify trend reversals and potential trading opportunities.
Uniqueness and Usefulness
Uniqueness: The strategy utilizes the Trend Magic indicator, which is based on price and volatility, along with three moving averages to assess the strength of trends. The signals are generated only when the moving averages are in perfect order, and the Trend Magic color changes, ensuring that the entry is made during established trends. This combination provides a higher degree of reliability compared to strategies that rely solely on price action or single indicators.
Usefulness: This strategy is particularly useful for traders looking to capture trends over longer periods. It is effective at reducing noise in the market, only providing signals when the moving averages align and the Trend Magic indicator confirms a trend reversal. It works well in both trending and volatile markets.
Entry Conditions
Long Entry:
Condition: A perfect order (EMA45 > SMA90 > SMA180) is established, and Trend Magic changes color from red to blue.
Signal: A buy signal is generated, indicating the start of an uptrend.
Short Entry:
Condition: A perfect order (EMA45 < SMA90 < SMA180) is established, and Trend Magic changes color from blue to red.
Signal: A sell signal is generated, indicating the start of a downtrend.
Exit Conditions
Exit Strategy:
This strategy automatically enters and exits trades based on signals, but traders are encouraged to manage exits manually according to their own risk management preferences. The strategy includes stop loss and take profit settings based on risk-to-reward ratios for better risk management.
Risk Management
The strategy includes built-in risk management by using the SMA90 level at the time of entry as the stop-loss point and setting the take profit at a 1:1.5 risk-to-reward ratio. The stop-loss level is fixed at the entry point and does not move as the market progresses. Traders are advised to implement additional risk management, such as trailing stops, for added protection.
Account Size: ¥100,000
Commissions and Slippage: Assumes 94 pips for commissions and 1 pip for slippage per trade
Risk per Trade: 10% of account equity (adjust this based on personal risk tolerance)
Configurable Options
Configurable Options:
CCI Period: Set the period for the CCI used to calculate the Trend Magic indicator (default is 21).
ATR Multiplier: Set the multiplier for ATR used in the Trend Magic calculation (default is 1.0).
EMA/SMA Periods: The periods for the three moving averages (default is EMA45, SMA90, and SMA180).
Signal Display Control: An option to toggle the display of buy and sell signals on the chart.
Adequate Sample Size
To ensure the robustness and reliability of this strategy, it is recommended to backtest it with a sufficiently long period of historical data. Testing across different market conditions, including high and low volatility periods, is also advised.
Credits
Acknowledgments:
This strategy is based on the Trend Magic indicator combined with moving averages and draws on contributions from the technical analysis and trading community.
Clean Chart Description
Chart Appearance:
To maintain a clean and simple chart, this strategy includes options to turn off the display of Trend Magic, moving averages, and entry signals. Traders can adjust these display settings as needed to minimize visual clutter and focus on effective trend analysis.
Addressing the House Rule Violations
Omissions and Unrealistic Claims
Clarification:
This strategy does not make any unrealistic or unsupported claims about its performance. All signals are intended for educational purposes only and do not guarantee future results. It is important to note that past performance does not guarantee future outcomes, and proper risk management is crucial.
TPS Short Strategy by Larry ConnersThe TPS Short strategy aims to capitalize on extreme overbought conditions in an ETF by employing a scaling-in approach when certain technical indicators signal potential reversals. The strategy is designed to short the ETF when it is deemed overextended, based on the Relative Strength Index (RSI) and moving averages.
Components:
200-Day Simple Moving Average (SMA):
Purpose: Acts as a long-term trend filter. The ETF must be below its 200-day SMA to be eligible for shorting.
Rationale: The 200-day SMA is widely used to gauge the long-term trend of a security. When the price is below this moving average, it is often considered to be in a downtrend (Tushar S. Chande & Stanley Kroll, "The New Technical Trader: Boost Your Profit by Plugging Into the Latest Indicators").
2-Period RSI:
Purpose: Measures the speed and change of price movements to identify overbought conditions.
Criteria: Short 10% of the position when the 2-period RSI is above 75 for two consecutive days.
Rationale: A high RSI value (above 75) indicates that the ETF may be overbought, which could precede a price reversal (J. Welles Wilder, "New Concepts in Technical Trading Systems").
Scaling-In Mechanism:
Purpose: Gradually increase the short position as the ETF price rises beyond previous entry points.
Scaling Strategy:
20% more when the price is higher than the first entry.
30% more when the price is higher than the second entry.
40% more when the price is higher than the third entry.
Rationale: This incremental approach allows for an increased position size in a worsening trend, potentially increasing profitability if the trend continues to align with the strategy’s premise (Marty Schwartz, "Pit Bull: Lessons from Wall Street's Champion Day Trader").
Exit Conditions:
Criteria: Close all positions when the 2-period RSI drops below 30 or the 10-day SMA crosses above the 30-day SMA.
Rationale: A low RSI value (below 30) suggests that the ETF may be oversold and could be poised for a rebound, while the SMA crossover indicates a potential change in the trend (Martin J. Pring, "Technical Analysis Explained").
Risks and Considerations:
Market Risk:
The strategy assumes that the ETF will continue to decline once shorted. However, markets can be unpredictable, and price movements might not align with the strategy's expectations, especially in a volatile market (Nassim Nicholas Taleb, "The Black Swan: The Impact of the Highly Improbable").
Scaling Risks:
Scaling into a position as the price increases may increase exposure to adverse price movements. This method can amplify losses if the market moves against the position significantly before any reversal occurs.
Liquidity Risk:
Depending on the ETF’s liquidity, executing large trades in increments might affect the price and increase trading costs. It is crucial to ensure that the ETF has sufficient liquidity to handle large trades without significant slippage (James Altucher, "Trade Like a Hedge Fund").
Execution Risk:
The strategy relies on timely execution of trades based on specific conditions. Delays or errors in order execution can impact performance, especially in fast-moving markets.
Technical Indicator Limitations:
Technical indicators like RSI and SMA are based on historical data and may not always predict future price movements accurately. They can sometimes produce false signals, leading to potential losses if used in isolation (John Murphy, "Technical Analysis of the Financial Markets").
Conclusion
The TPS Short strategy utilizes a combination of long-term trend filtering, overbought conditions, and incremental shorting to potentially profit from price reversals. While the strategy has a structured approach and leverages well-known technical indicators, it is essential to be aware of the inherent risks, including market volatility, liquidity issues, and potential limitations of technical indicators. As with any trading strategy, thorough backtesting and risk management are crucial to its successful implementation.
Reflected ema Difference (RED) This script, titled "Reflected EMA Difference (RED)," is based on the logic of evaluating the percentage of convergence and divergence between two moving averages, specifically the Hull Moving Averages (HMA), to make price-related decisions. The Hull Moving Average, created by Alan Hull, is used as the foundation of this strategy, offering a faster and more accurate way to analyze market trends. In this script, the concept is employed to measure and reflect price variations.
Script Functionality Overview:
Hull Moving Averages (HMA): The script utilizes two HMAs, one short-term and one long-term. The main idea is to compute the Delta Difference between these two moving averages, which represents how much they are converging or diverging from each other. This difference is key to identifying potential market trend changes.
Reflected HMA Value: Using the Delta Difference between the HMAs, the value of the short-term HMA is reflected, creating a visual reference point that helps traders see the relationship between price and HMAs on the chart.
Percentage Change Index: The second key parameter is the percentage change index. This determines when a trend is reversing, allowing buy or sell orders to be established based on significant changes in the relationship between the HMAs and the price.
Delta Multiplier: The script comes with a default Delta multiplier of 2 for calculating the difference between HMAs, allowing traders to adjust the sensitivity of the analysis based on the time frame being analyzed.
Trend Reversal Signals: When the price crosses the thresholds defined by the percentage change index, buy or sell signals are triggered, based on the detection of a potential trend reversal.
Visual Cues with Boxes: Boxes are drawn on the chart when the HullMA crosses the reflected HMA value, providing a visual aid to identify critical moments where risk should be evaluated.
Alerts for Receiving Signals:
This script allows you to set up buy and sell alerts via TradingView's alert system. These alerts are triggered when trend changes are detected based on the conditions coded in the script. Traders can receive instant notifications, allowing them to make decisions without needing to constantly monitor the chart.
Additional Considerations:
The percentage change parameter is adjustable and should be configured based on the time frame you are trading on. For longer time frames, it's advisable to use a larger percentage change to avoid false signals.
The use of Hull Moving Averages (HMA) provides a faster and more reactive approach to trend evaluation compared to other moving averages, making it a powerful tool for traders seeking quick reversal signals.
This approach combines the power of Hull Moving Averages with an alert system to improve the trader’s response to trend changes.
Spanish
Este script, titulado "Reflected EMA Difference (RED)", está fundamentado en la lógica de evaluar el porcentaje de acercamiento y distancia entre dos medias móviles, específicamente las medias móviles de Hull (HMA), para tomar decisiones sobre el valor del precio. El creador de la media móvil de Hull, Alan Hull, diseñó este indicador para ofrecer una forma más rápida y precisa de analizar tendencias de mercado, y en este script se utiliza su concepto como base para medir y reflejar las variaciones de precio.
Descripción del funcionamiento:
Medias Móviles de Hull (HMA): Se utilizan dos HMAs, una de corto plazo y otra de largo plazo. La idea principal es calcular la diferencia Delta entre estas dos medias móviles, que representa cuánto se están alejando o acercando entre sí. Esta diferencia es clave para identificar cambios potenciales en la tendencia del mercado.
Valor Reflejado de la HMA: Con la diferencia Delta calculada entre las HMAs, se refleja el valor de la HMA corta, creando un punto de referencia visual que ayuda a los traders a observar la relación entre el precio y las HMAs en el gráfico.
Índice de Cambio de Porcentaje: El segundo parámetro clave del script es el índice de cambio porcentual. Este define el momento en que una tendencia está revirtiendo, permitiendo establecer órdenes de compra o venta en función de un cambio significativo en la relación entre las HMAs y el precio.
Multiplicador Delta: El script tiene un multiplicador predeterminado de 2 para el cálculo de la diferencia Delta, lo que permite ajustar la sensibilidad del análisis según la temporalidad del gráfico.
Señales de Reversión de Tendencia: Cuando el precio cruza los límites definidos por el índice de cambio porcentual, se emiten señales para comprar o vender, basadas en la detección de una posible reversión de tendencia.
Visualización con Cajas: Se dibujan cajas en el gráfico cuando el indicador HullMA cruza el valor reflejado de la HMA, ayudando a identificar visualmente los momentos críticos en los que se debe evaluar el riesgo de las operaciones.
Alertas para Recibir Señales:
Este script permite configurar alertas de compra y venta desde el apartado de alertas de TradingView. Estas alertas se activan cuando se detectan cambios de tendencia en función de las condiciones establecidas en el código. El trader puede recibir notificaciones instantáneas, lo que facilita la toma de decisiones sin necesidad de estar constantemente observando el gráfico.
Consideraciones adicionales:
El porcentaje de cambio es un parámetro ajustable y debe configurarse según la temporalidad que se esté operando. En temporalidades más largas, es recomendable usar un porcentaje de cambio mayor para evitar señales falsas.
La utilización de las medias móviles de Hull (HMA) proporciona un enfoque más rápido y reactivo para evaluar tendencias en comparación con otras medias móviles, lo que lo convierte en una herramienta poderosa para traders que buscan señales rápidas de reversión.
Este enfoque combina la potencia de las medias móviles de Hull con un sistema de alertas que mejora la reactividad a cambios de tendencia.
Varanormal Mac N Cheez Strategy v1Mac N Cheez Strategy (Set a $200 Take profit Manually)
It's super cheesy. Strategy does the following:
Here's a detailed explanation of what the entire script does, including its key components, functionality, and purpose.
1. Strategy Setup and Input Parameters:
Strategy Name: The script is named "NQ Futures $200/day Strategy" and is set as an overlay, meaning all elements (like moving averages and signals) are plotted on the price chart.
Input Parameters:
fastLength: This sets the length of the fast moving average. The user can adjust this value, and it defaults to 9.
slowLength: This sets the length of the slow moving average. The user can adjust this value, and it defaults to 21.
dailyTarget: The daily profit target, which defaults to $200. If set to 0, this disables the daily profit target.
stopLossAmount: The fixed stop-loss amount per trade, defaulting to $100. This value is used to calculate how much you're willing to lose on a single trade.
trailOffset: This value sets the distance for a trailing stop. It helps protect profits by automatically adjusting the stop-loss as the price moves in your favor.
2. Calculating the Moving Averages:
fastMA: The fast moving average is calculated using the ta.sma() function on the close price with a period length of fastLength. The ta.sma() function calculates the simple moving average.
slowMA: The slow moving average is also calculated using ta.sma() but with the slowLength period.
These moving averages are used to determine trend direction and identify entry points.
3. Buy and Sell Signal Conditions:
longCondition: This is the buy condition. It occurs when the fast moving average crosses above the slow moving average. The script uses ta.crossover() to detect this crossover event.
shortCondition: This is the sell condition. It occurs when the fast moving average crosses below the slow moving average. The script uses ta.crossunder() to detect this crossunder event.
4. Executing Buy and Sell Orders:
Buy Orders: When the longCondition is true (i.e., fast MA crosses above slow MA), the script enters a long position using strategy.entry("Buy", strategy.long).
Sell Orders: When the shortCondition is true (i.e., fast MA crosses below slow MA), the script enters a short position using strategy.entry("Sell", strategy.short).
5. Setting Stop Loss and Trailing Stop:
Stop-Loss for Long Positions: The stop-loss is calculated as the entry price minus the stopLossAmount. If the price falls below this level, the trade is exited automatically.
Stop-Loss for Short Positions: The stop-loss is calculated as the entry price plus the stopLossAmount. If the price rises above this level, the short trade is exited.
Trailing Stop: The trail_offset dynamically adjusts the stop-loss as the price moves in favor of the trade, locking in profits while still allowing room for market fluctuations.
6. Conditional Daily Profit Target:
The script includes a daily profit target that automatically closes all trades once the total profit for the day reaches or exceeds the dailyTarget.
Conditional Logic:
If the dailyTarget is greater than 0, the strategy checks whether the strategy.netprofit (total profit for the day) has reached or exceeded the target.
If the strategy.netprofit >= dailyTarget, the script calls strategy.close_all(), closing all open trades for the day and stopping further trading.
If dailyTarget is set to 0, this logic is skipped, and the script continues trading without a daily profit target.
7. Plotting Moving Averages:
plot(fastMA): This plots the fast moving average as a blue line on the price chart.
plot(slowMA): This plots the slow moving average as a red line on the price chart. These help visualize the crossover points and the trend direction on the chart.
8. Plotting Buy and Sell Signals:
plotshape(): The script uses plotshape() to add visual markers when buy or sell conditions are met:
"Long Signal": When a buy condition (longCondition) is met, a green marker is plotted below the price bar with the label "Long".
"Short Signal": When a sell condition (shortCondition) is met, a red marker is plotted above the price bar with the label "Short".
These markers help traders quickly see when buy or sell signals occurred on the chart.
In addition, triangle markers are plotted:
Green Triangle: Indicates where a buy entry occurred.
Red Triangle: Indicates where a sell entry occurred.
Summary of What the Script Does:
Inputs: The script allows the user to adjust moving average lengths, daily profit targets, stop-loss amounts, and trailing stop offsets.
Signals: It generates buy and sell signals based on the crossovers of the fast and slow moving averages.
Order Execution: It executes long positions on buy signals and short positions on sell signals.
Stop-Loss and Trailing Stop: It sets dynamic stop-losses and uses a trailing stop to protect profits.
Daily Profit Target: The strategy stops trading for the day once the net profit reaches the daily target (unless the target is disabled by setting it to 0).
Visual Markers: It plots moving averages and buy/sell signals directly on the main price chart to aid in visual analysis.
This script is designed to trade based on moving average crossovers, with robust risk management features like stop-loss and trailing stops, along with an optional daily profit target to limit daily trading activity. Let me know if you need further clarification or want to adjust any specific part of the script!
Fractal Proximity MA Aligment Scalping StrategyFractal Analysis
Fractals in trading help identify potential reversal points by marking significant price changes. Our strategy calculates a "fractal value" by comparing the current price to recent high and low fractal points. This is done by evaluating the sum of distances from the current closing price to the recent highs and lows. A positive fractal value suggests proximity to recent lows, hinting at upward momentum. Conversely, a negative value indicates closeness to recent highs, signaling potential downward movement.
Moving Averages for Confirmation
We use a series of 20 moving averages ranging from 5 to 100 to confirm trend directions indicated by fractal analysis. An entry signal is considered bullish when shorter-term moving averages are all above a long-term moving average, aligning with a positive fractal value.
Exit Strategy
The strategy employs dynamic stop-loss levels set at various moving averages, allowing for partial exits when the price crosses below specific thresholds. This helps manage the trade by locking in profits gradually. A full exit might be triggered by strong reversal signals suggested by both fractal values and moving average trends.
This open-source strategy is available for the community to test, adapt, and utilize. Your feedback and modifications are welcome as we refine the approach based on collective user experiences.
Combo 2/20 EMA & CCI
This is another part of my research work, where I test a combination of two strategies, receiving a combined signal. In order to understand which indicator combinations work better, which work worse, as filters for trades. This is combo strategies for get a cumulative signal.
First strategy
This indicator plots 2/20 exponential moving average. For the Mov Avg X 2/20 Indicator, the EMA bar will be painted when the Alert criteria is met.
Second strategy
The Commodity Channel Index (CCI) is best used with markets that display cyclical or seasonal characteristics, and is formulated to detect the beginning and ending of the cycles by incorporating a moving average together with a divisor that reflects both possible and actual trading ranges. The final index measures the deviation from normal, which indicates major changes in market trend.
Strategy tester settings:
Initial capital: 1000
Order size: 0.5
Commission: 0.1%
Other as default.
Indicator settings:
EMA Length: 50
CCI Length: 10
Fast MA Length: 15
Slow MA Length: 20
Other as default.
WARNING:
- For purpose educate only
- This script to change bars colors.
Intramarket Difference Index StrategyIntramarket Difference Indicator (IDI) Strategy:
In layman’s terms this strategy compares two indicators across (correlated) markets and exploits their differences.
📍 Import Notes:
This Strategy calculates trade position size independently, this means that the ‘Order size’ input in the ‘Properties’ tab will have no effect on the strategy. Why ? because this allows us to define custom position size algorithms which we can use to improve our risk management and equity growth over time. Here we have the option to have fixed quantity or fixed percentage of equity ATR (Average True Range) based stops in addition to the turtle trading position size algorithm.
‘Pyramiding’ does not work for this strategy’, similar to the order size input togeling this input will have no effect on the strategy as the strategy explicitly defines the maximum order size to be 1.
This strategy is not perfect, and as of writing of this post I have not traded this algo.
Always take your time to backtests and debug the strategy.
🔷 The IDI Strategy:
By default this strategy pulls data from your current TV chart and then compares it to the base market, be default BINANCE:BTCUSD . The strategy pulls SMA and RSI data from either market (we call this the difference data), standardizes the data (solving the different unit problem across markets) such that it is comparable and then differentiates the data, calling the result of this transformation and difference the Intramarket Difference (ID). The formula for the the ID is
ID = market1_diff_data - market2_diff_data (1)
Where
market(i)_diff_data = diff_data / ATR(j)_market(i)^0.5,
where i = {1, 2} and j = the natural numbers excluding 0
Formula (1) interpretation is the following
When ID > 0: this means the current market outperforms the base market
When ID = 0: Markets are at long run equilibrium
When ID < 0: this means the current market underperforms the base market
To form the strategy we define one of two strategy type’s which are Trend and Mean Revesion respectively.
🔸 Trend Case:
Given the ‘‘Strategy Type’’ is equal to TREND we define a threshold for which if the ID crosses over we go long and if the ID crosses under the negative of the threshold we go short.
The motivating idea is that the ID is an indicator of the two symbols being out of sync, and given we know volatility clustering, momentum and mean reversion of anomalies to be a stylised fact of financial data we can construct a trading premise. Let's first talk more about this premise.
For some markets (cryptocurrency markets - synthetic symbols in TV) the stylised fact of momentum is true, this means that higher momentum is followed by higher momentum, and given we know momentum to be a vector quantity (with magnitude and direction) this momentum can be both positive and negative i.e. when the ID crosses above some threshold we make an assumption it will continue in that direction for some time before executing back to its long run equilibrium of 0 which is a reasonable assumption to make if the market are correlated. For example for the BTCUSD - ETHUSD pair, if the ID > +threshold (inputs for MA and RSI based ID thresholds are found under the ‘‘INTRAMARKET DIFFERENCE INDEX’’ group’), ETHUSD outperforms BTCUSD, we assume the momentum to continue so we go long ETHUSD.
In the standard case we would exit the market when the IDI returns to its long run equilibrium of 0 (for the positive case the ID may return to 0 because ETH’s difference data may have decreased or BTC’s difference data may have increased). However in this strategy we will not define this as our exit condition, why ?
This is because we want to ‘‘let our winners run’’, to achieve this we define a trailing Donchian Channel stop loss (along with a fixed ATR based stop as our volatility proxy). If we were too use the 0 exit the strategy may print a buy signal (ID > +threshold in the simple case, market regimes may be used), return to 0 and then print another buy signal, and this process can loop may times, this high trade frequency means we fail capture the entire market move lowering our profit, furthermore on lower time frames this high trade frequencies mean we pay more transaction costs (due to price slippage, commission and big-ask spread) which means less profit.
Note it is possible that after printing a buy the strategy then prints many sell signals before returning to a buy, which again has the same implications. The image below showcases the theory above, by allowing our winner to run we may capture more profit.
Valid trades are denoted by solid green and red arrows respectively and all other valid trades which occur within the original signal are light green and red small arrows, if we were to close our trades when the IDI returns to its equilibrium of 0 our average bars per trade would be very low and we would not capture the general trend.
Note by capturing the sum of many momentum moves we are essentially following the trend hence the trend following strategy type.
Here we also print the IDI (with default strategy settings with the MA difference type), we can see that by letting our winners run we may catch many valid momentum moves, that results in a larger final pnl that if we would otherwise exit based on the equilibrium condition.
Note if you would like to plot the IDI separately copy and paste the following code in a new Pine Script indicator template.
indicator("IDI")
// INTRAMARKET INDEX
var string g_idi = "intramarket diffirence index"
ui_index_1 = input.symbol("BINANCE:BTCUSD", title = "Base market", group = g_idi)
// ui_index_2 = input.symbol("BINANCE:ETHUSD", title = "Quote Market", group = g_idi)
type = input.string("MA", title = "Differrencing Series", options = , group = g_idi)
ui_ma_lkb = input.int(24, title = "lookback of ma and volatility scaling constant", group = g_idi)
ui_rsi_lkb = input.int(14, title = "Lookback of RSI", group = g_idi)
ui_atr_lkb = input.int(300, title = "ATR lookback - Normalising value", group = g_idi)
ui_ma_threshold = input.float(5, title = "Threshold of Upward/Downward Trend (MA)", group = g_idi)
ui_rsi_threshold = input.float(20, title = "Threshold of Upward/Downward Trend (RSI)", group = g_idi)
//>>+----------------------------------------------------------------+}
// CUSTOM FUNCTIONS |
//<<+----------------------------------------------------------------+{
// construct UDT (User defined type) containing the IDI (Intramarket Difference Index) source values
// UDT will hold many variables / functions grouped under the UDT
type functions
float Close // close price
float ma // ma of symbol
float rsi // rsi of the asset
float atr // atr of the asset
// the security data
getUDTdata(symbol, malookback, rsilookback, atrlookback) =>
indexHighTF = barstate.isrealtime ? 1 : 0
= request.security(symbol, timeframe = timeframe.period,
expression = [close , // Instentiate UDT variables
ta.sma(close, malookback) ,
ta.rsi(close, rsilookback) ,
ta.atr(atrlookback) ])
data = functions.new(close_, ma_, rsi_, atr_)
data
// Intramerket Difference Index
idi(type, symbol1, malookback, rsilookback, atrlookback, mathreshold, rsithreshold) =>
threshold = float(na)
index1 = getUDTdata(symbol1, malookback, rsilookback, atrlookback)
index2 = getUDTdata(syminfo.tickerid, malookback, rsilookback, atrlookback)
// declare difference variables for both base and quote symbols, conditional on which difference type is selected
var diffindex1 = 0.0, var diffindex2 = 0.0,
// declare Intramarket Difference Index based on series type, note
// if > 0, index 2 outpreforms index 1, buy index 2 (momentum based) until equalibrium
// if < 0, index 2 underpreforms index 1, sell index 1 (momentum based) until equalibrium
// for idi to be valid both series must be stationary and normalised so both series hae he same scale
intramarket_difference = 0.0
if type == "MA"
threshold := mathreshold
diffindex1 := (index1.Close - index1.ma) / math.pow(index1.atr*malookback, 0.5)
diffindex2 := (index2.Close - index2.ma) / math.pow(index2.atr*malookback, 0.5)
intramarket_difference := diffindex2 - diffindex1
else if type == "RSI"
threshold := rsilookback
diffindex1 := index1.rsi
diffindex2 := index2.rsi
intramarket_difference := diffindex2 - diffindex1
//>>+----------------------------------------------------------------+}
// STRATEGY FUNCTIONS CALLS |
//<<+----------------------------------------------------------------+{
// plot the intramarket difference
= idi(type,
ui_index_1,
ui_ma_lkb,
ui_rsi_lkb,
ui_atr_lkb,
ui_ma_threshold,
ui_rsi_threshold)
//>>+----------------------------------------------------------------+}
plot(intramarket_difference, color = color.orange)
hline(type == "MA" ? ui_ma_threshold : ui_rsi_threshold, color = color.green)
hline(type == "MA" ? -ui_ma_threshold : -ui_rsi_threshold, color = color.red)
🔸 Mean Reversion Case:
We stated prior that mean reversion of anomalies is an standerdies fact of financial data, how can we exploit this ?
We exploit this by normalizing the ID by applying the Ehlers fisher transformation. We now assume our series is approximately normally distributed. To form the strategy we employ the same logic as for e the z score, if the FT normalized ID >< 2.5 or -2.5 respectively we buy or short respectively. We also employ the same exit conditions (fixed ATR stop and trailing Donchian Trailing stop)
🔷 Position Sizing:
If ‘‘Fixed Risk From Initial Balance’’ is toggled true this means we risk a fixed percentage of our initial balance, if false we risk a fixed percentage of our equity (current balance).
Note we also employ a volatility adjusted position sizing formula, the turtle training method which is defined as follows.
Turtle position size = (1/ r * ATR * DV) * C
Where,
r = risk factor coefficient (default is 20)
ATR(j) = risk proxy, over j times steps
DV = Dollar Volatility, where DV = (1/Asset Price) * Capital at Risk
🔷 Risk Management:
Correct money management means we can limit risk and increase reward (theoretically). Here we employ
Max loss and gain per day
Max loss per trade
Max number of consecutive losing trades until trade skip
To read more see the tooltips (info circle).
Note the ATR stop losses and take profits are defined, with the prior being default.
ATR SL and TP defined
🔷 Hurst Regime (Regime Filter):
The Hurst Exponent (H) aims to segment the market into three different states, Trending (H > 0.5), Random Geometric Brownian Motion (H = 0.5) and Mean Reverting / Contrarian (H < 0.5). In my interpretation this can be used as a trend filter that eliminates market noise.
We utilize the trending and mean reverting based states, as extra conditions required for valid trades both strategy types respectively, in the process increasing our trade entry quality.
🔷 Example model Architecture:
Here is an example of one configuration of this strategy, combining all aspect discussed in this post.
PVT Crossover Strategy**Release Notes**
**Strategy Name**: PVT Crossover Strategy
**Purpose**: This strategy aims to capture entry and exit points in the market using the Price-Volume Trend (PVT) and its Exponential Moving Average (EMA). It specifically uses the crossover of PVT with its EMA as signals to identify changes in market trends.
**Uniqueness and Usefulness**
**Uniqueness**: This strategy is unique in its use of the PVT indicator, which combines price changes with trading volume to track trends. The filtering with EMA reduces noise and provides more accurate signals compared to other indicators.
**Usefulness**: This strategy is effective for traders looking to detect trend changes early. The signals based on PVT and its EMA crossover work particularly well in markets where volume fluctuations are significant.
**Entry Conditions**
**Long Entry**:
- **Condition**: A crossover occurs where PVT crosses above its EMA.
- **Signal**: A buy signal is generated, indicating a potential uptrend.
**Short Entry**:
- **Condition**: A crossunder occurs where PVT crosses below its EMA.
- **Signal**: A sell signal is generated, indicating a potential downtrend.
**Exit Conditions**
**Exit Strategy**:
- The strategy does not explicitly program exit conditions beyond the entry signals, but traders are encouraged to close positions manually based on signals or apply their own risk management strategy.
**Risk Management**
This strategy does not include default risk management rules, so traders should implement their own. Consider using trailing stops or fixed stop losses to manage risk.
**Account Size**: ¥100,000
**Commissions and Slippage**: 94 pips per trade for commissions and 1 pip for slippage
**Risk per Trade**: 10% of account equity
**Configurable Options**
**Configurable Options**:
- **EMA Length**: The length of the EMA used to calculate the EMA of PVT (default is 20).
- **Signal Display Control**: The option to turn the display of signals on or off.
**Adequate Sample Size**
To ensure the robustness and reliability of this strategy, it is recommended to backtest it with a sufficiently long period of historical data, especially across different market conditions.
**Credits**
**Acknowledgments**:
This strategy is based on the concept of the PVT indicator and its application in strategy design, drawing on contributions from technical analysis and the trading community.
**Clean Chart Description**
**Chart Appearance**:
This strategy is designed to maintain a clean and simple chart by turning off the plot of PVT, its EMA, and entry signals. This reduces clutter and allows for more effective trend analysis.
**Addressing the House Rule Violations**
**Omissions and Unrealistic Claims**
**Clarification**:
This strategy does not make unrealistic or unsupported claims about its performance, and all signals are for educational purposes only, not guaranteeing future results. It is important to understand that past performance does not guarantee future outcomes.
Scalping with Williams %R, MACD, and SMA (1m)Overview:
This trading strategy is designed for scalping in the 1-minute timeframe. It uses a combination of the Williams %R, MACD, and SMA indicators to generate buy and sell signals. It also includes alert functionalities to notify users when trades are executed or closed.
Indicators Used:
Williams %R : A momentum indicator that measures overbought and oversold conditions. The Williams %R values range from -100 to 0.
Length: 140 bars (i.e., 140-period).
MACD (Moving Average Convergence Divergence) : A trend-following momentum indicator that shows the relationship between two moving averages of a security's price.
Fast Length: 24 bars
Slow Length: 52 bars
MACD Length: 9 bars (signal line)
SMA (Simple Moving Average) : A trend-following indicator that smooths out price data to create a trend-following indicator.
Length: 7 bars
Conditions and Logic:
Timeframe Check :
The strategy is designed specifically for the 1-minute timeframe. If the current chart is not on the 1-minute timeframe, a warning label is displayed on the chart instructing the user to switch to the 1-minute timeframe.
Williams %R Conditions :
Buy Condition: The strategy looks for a crossover of Williams %R from below -94 to above -94. This indicates a potential buying opportunity when the market is moving out of an oversold condition.
Sell Condition: The strategy looks for a crossunder of Williams %R from above -6 to below -6. This indicates a potential selling opportunity when the market is moving out of an overbought condition.
Deactivate Buy: If Williams %R crosses above -40, the buy signal is deactivated, suggesting that the buying condition is no longer valid.
Deactivate Sell: If Williams %R crosses below -60, the sell signal is deactivated, suggesting that the selling condition is no longer valid.
MACD Conditions :
MACD Histogram: Used to identify the momentum and the direction of the trend.
Long Entry: The strategy initiates a buy order if the MACD histogram shows a positive bar after a negative bar while a buy condition is active and Williams %R is above -94.
Long Exit: The strategy exits the buy position if the MACD histogram turns negative and is below the previous histogram bar.
Short Entry: The strategy initiates a sell order if the MACD histogram shows a negative bar after a positive bar while a sell condition is active and Williams %R is below -6.
Short Exit: The strategy exits the sell position if the MACD histogram turns positive and is above the previous histogram bar.
Trend Confirmation (Using SMA) :
Bullish Trend: The strategy considers a bullish trend if the current price is above the 7-bar SMA. A buy signal is only considered if this condition is met.
Bearish Trend: The strategy considers a bearish trend if the current price is below the 7-bar SMA. A sell signal is only considered if this condition is met.
Alerts:
Long Entry Alert: An alert is triggered when a buy order is executed.
Long Exit Alert: An alert is triggered when the buy order is closed.
Short Entry Alert: An alert is triggered when a sell order is executed.
Short Exit Alert: An alert is triggered when the sell order is closed.
Summary:
Buy Signal: Activated when Williams %R crosses above -94 and the price is above the 7-bar SMA. A buy order is placed if the MACD histogram shows a positive bar after a negative bar. The buy order is closed when the MACD histogram turns negative and is below the previous histogram bar.
Sell Signal: Activated when Williams %R crosses below -6 and the price is below the 7-bar SMA. A sell order is placed if the MACD histogram shows a negative bar after a positive bar. The sell order is closed when the MACD histogram turns positive and is above the previous histogram bar.
This strategy combines momentum (Williams %R), trend-following (MACD), and trend confirmation (SMA) to identify trading opportunities in the 1-minute timeframe. It is designed for short-term trading or scalping.
Innocent Heikin Ashi Ethereum StrategyHello there, im back!
If you are familiar with my previous scripts, this one will seem like the future's nostalgia!
Functionality:
As you can see, all candles are randomly colored. This has no deeper meaning, it should remind you to switch to Heikin Ashi. The Strategy works on standard candle stick charts, but should be used with Heikin Ashi to see the actual results. (Regular OHLC calculations are included.)
Same as in my previous scripts we import our PVSRA Data from @TradersReality open source Indicator.
With this data and the help of moving averages, we have got an edge in the market.
Signal Logic:
When a "violently green" candle appears (high buy volume + tick speed) above the 50 EMA indicates a change in trend and sudden higher prices. Depending on OHLC of the candle itself and volume, Take Profit and Stop Loss is calculated. (The price margin is the only adjustable setting). Additionally, to make this script as simple and easily useable as possible, all other adjustable variables have been already set to the best suitable value and the chart was kept plain, except for the actual entries and exits.
Basic Settings and Adjustables:
Main Input 1: TP and SL combined price range. (Double, Triple R:R equally.)
Trade Inputs: All standard trade size and contract settings for testing available.
Special Settings:
Checkbox 1: Calculate Signal in Heikin Ashi chart, including regular candle OHLC („Open, High, Low, Close“)
Checkbox 2/3: Calculate by order fill or every tick.
Checkbox 4: Possible to fill orders on bar close.
Timeframe and practical usage:
Made for the 5 Minute to 1 hour timeframe.
Literally ONLY works on Ethereum and more or less on Bitcoin.
EVERY other asset has absolute 0% profitability.
Have fun and share with your friends!
Thanks for using!
Example Chart:
Rsi Long-Term Strategy [15min]Hello, I would like to present to you The "RSI Long-Term Strategy" for 15min tf
The "RSI Long-Term Strategy " is designed for traders who prefer a combination of momentum and trend-following techniques. The strategy focuses on entering long positions during significant market corrections within an overall uptrend, confirmed by both RSI and volume. The use of long-term SMAs ensures that trades are made in line with the broader market trend. The stop-loss feature provides risk management by limiting losses on trades that do not perform as expected. This strategy is particularly well-suited for longer-term traders who monitor 15-minute charts but look for substantial trend reversals or continuations.
Indicators and Parameters:
Relative Strength Index (RSI):
- The RSI is calculated using a 10-period length. It measures the magnitude of recent price changes to evaluate overbought or oversold conditions. The script defines oversold conditions when the RSI is at or below 30 and overbought conditions when the RSI is at or above 70.
Volume Condition:
-The strategy incorporates a volume condition where the current volume must be greater than 2.5 times the 20-period moving average of volume. This is used to confirm the strength of the price movement.
Simple Moving Averages (SMA):
- The strategy uses two SMAs: SMA1 with a length of 250 periods and SMA2 with a length of 500 periods. These SMAs help identify long-term trends and generate signals based on their crossover.
Strategy Logic:
Entry Logic:
A long position is initiated when all the following conditions are met:
The RSI indicates an oversold condition (RSI ≤ 30).
SMA1 is above SMA2, indicating an uptrend.
The volume condition is satisfied, confirming the strength of the signal.
Exit Logic:
The strategy closes the long position when SMA1 crosses under SMA2, signaling a potential end of the uptrend (a "Death Cross").
Stop-Loss:
A stop-loss is set at 5% below the entry price to manage risk and limit potential losses.
Buy and sell signals are highlighted with circles below or above bars:
Green Circle : Buy signal when RSI is oversold, SMA1 > SMA2, and the volume condition is met.
Red Circle : Sell signal when RSI is overbought, SMA1 < SMA2, and the volume condition is met.
Black Cross: "Death Cross" when SMA1 crosses under SMA2, indicating a potential bearish signal.
to determine the level of stop loss and target point I used a piece of code by RafaelZioni, here is the script from which a piece of code was taken
I hope the strategy will be helpful, as always, best regards and safe trades
;)
Multi-Factor StrategyThis trading strategy combines multiple technical indicators to create a systematic approach for entering and exiting trades. The goal is to capture trends by aligning several key indicators to confirm the direction and strength of a potential trade. Below is a detailed description of how the strategy works:
Indicators Used
MACD (Moving Average Convergence Divergence):
MACD Line: The difference between the 12-period and 26-period Exponential Moving Averages (EMAs).
Signal Line: A 9-period EMA of the MACD line.
Usage: The strategy looks for crossovers between the MACD line and the Signal line as entry signals. A bullish crossover (MACD line crossing above the Signal line) indicates a potential upward movement, while a bearish crossover (MACD line crossing below the Signal line) signals a potential downward movement.
RSI (Relative Strength Index):
Usage: RSI is used to gauge the momentum of the price movement. The strategy uses specific thresholds: below 70 for long positions to avoid overbought conditions and above 30 for short positions to avoid oversold conditions.
ATR (Average True Range):
Usage: ATR measures market volatility and is used to set dynamic stop-loss and take-profit levels. A stop loss is set at 2 times the ATR, and a take profit at 3 times the ATR, ensuring that risk is managed relative to market conditions.
Simple Moving Averages (SMA):
50-day SMA: A short-term trend indicator.
200-day SMA: A long-term trend indicator.
Usage: The strategy uses the relationship between the 50-day and 200-day SMAs to determine the overall market trend. Long positions are taken when the price is above the 50-day SMA and the 50-day SMA is above the 200-day SMA, indicating an uptrend. Conversely, short positions are taken when the price is below the 50-day SMA and the 50-day SMA is below the 200-day SMA, indicating a downtrend.
Entry Conditions
Long Position:
-MACD Crossover: The MACD line crosses above the Signal line.
-RSI Confirmation: RSI is below 70, ensuring the asset is not overbought.
-SMA Confirmation: The price is above the 50-day SMA, and the 50-day SMA is above the 200-day SMA, indicating a strong uptrend.
Short Position:
MACD Crossunder: The MACD line crosses below the Signal line.
RSI Confirmation: RSI is above 30, ensuring the asset is not oversold.
SMA Confirmation: The price is below the 50-day SMA, and the 50-day SMA is below the 200-day SMA, indicating a strong downtrend.
Opposite conditions for shorts
Exit Strategy
Stop Loss: Set at 2 times the ATR from the entry price. This dynamically adjusts to market volatility, allowing for wider stops in volatile markets and tighter stops in calmer markets.
Take Profit: Set at 3 times the ATR from the entry price. This ensures a favorable risk-reward ratio of 1:1.5, aiming for higher rewards on successful trades.
Visualization
SMAs: The 50-day and 200-day SMAs are plotted on the chart to visualize the trend direction.
MACD Crossovers: Bullish and bearish MACD crossovers are highlighted on the chart to identify potential entry points.
Summary
This strategy is designed to align multiple indicators to increase the probability of successful trades by confirming trends and momentum before entering a position. It systematically manages risk with ATR-based stop loss and take profit levels, ensuring that trades are exited based on market conditions rather than arbitrary points. The combination of trend indicators (SMAs) with momentum and volatility indicators (MACD, RSI, ATR) creates a robust approach to trading in various market environments.
Negroni Opening Range StrategyStrategy Summary:
This tool can be used to help identify breakouts from a range during a time-zone of your choosing. It plots a pre-market range, an opening range, it also includes moving average levels that can be used as confluence, as well as plotting previous day SESSION highs and lows.
There are several options on how you wish to close out the trades, all described in more detail below.
Back-testing Inputs:
You define your timezone.
You define how many trades to open on any given day.
You decide to go: long only, short only, or long & short (CAREFUL: "Long & Short" can open trades that effectively closes-out existing ones, for better AND worse!)
You define between which times the strategy will open trades.
You define when it closes any open trades (preventing overnight trades, or leaving trades open into US data times!!).
This hopefully helps make back-testing reflect YOUR trading hours.
NOTE: Renko or Heikin-Ashi charts
For ALL strategies, don’t use Renko or Heikin-Ashi charts unless you know EXACTLY the implications.
Specific to my strategy, using a renko chart can make this 85-90% profitable (I wish it was!!) Although they can be useful, renko charts don’t always capture real wicks, so the renko chart may show your trade up-only but your broker (who is not using renko!!) will have likely stopped you out on a wick somewhere along the line.
NOTE: TradingView ‘Deep backtesting’
For ALL strategies, be cynical of all backtesting (e.g. repainting issues etc) as well as ‘Deep backtesting’ results.
Specific to this strategy, the default settings here SHOULD BE OK, but unfortunately at the time of writing, we can’t see on the chart what exactly ‘deep backtesting’ is calculating. In the past I have noted a number of trades that were not closed at the end of the day, despite my ‘end of day’ trade closing being enabled, so there were big winners and losers that would not have materialized otherwise. As I say, this seems ok at these settings but just always be cynical!!
Opening Range Inputs
You define a pre-market range (example: 08:00 - 09:00).
You define an opening range (example: 09:00 - 09:30).
The strategy will give an update at the close of the opening range to let you know if the opening range has broken out the pre-market range (OR Breakout), or if it has remained inside (OR Inside). The label appears at the end of the opening range NOT at the bar that ‘broke-out’.
This is just a visual cue for you, it has no bearing on what the strategy will do.
The strategy default will trade off the pre-market range, but you can untick this if you prefer to trade off the opening range.
Opening Trades:
Strategy goes long when the bar (CLOSE) crosses-over the ‘pre-market’ high (not the ‘opening range’ high); and the time is within your trading session, and you have not maxed out your number of trades for the day!
Strategy goes short when the bar (CLOSE) crosses-under the ‘pre-market’ low (not the ‘opening range low); and the time is within your trading session, and you have not maxed out your number of trades for the day!
Remember, you can untick this if you prefer to trade off the opening range instead.
NOTES:
Using momentum indicators can help (RSI and MACD): especially to trade range plays in failed breakouts, when momentum shifts… but the strategy won’t do this for you!
Using an anchored vwap at the session open can also provide nice confluence, as well as take-profit levels at the upper/lower of 3x standard deviation.
CLOSING TRADES:
You have 6 take-profit (TP) options:
1) Full TP: uses ATR Multiplier - Full TP at the ATR parameters as defined in inputs.
2) Take Partial profits: ATR Multiplier - Takes partial profits based on parameters as defined in inputs (i.e close 40% of original trade at TP1, close another 40% of original trade at TP2, then the remainder at Full TP as set in option 1.).
3) Full TP: Trailing Stop - Applies a Trailing Stop at the number of points, as defined in inputs.
4) Full TP: MA cross - Takes profit when price crosses ‘Trend MA’ as defined in inputs.
5) Scalp: Points - closes at a set number of points, as defined in inputs.
6) Full TP: PMKT Multiplier - places a SL at opposite pre-market Hi/Low (we go long at a break-out of the pre-market high, 50% would place a SL at the pre-market range mid-point; 100% would place a SL at the pre-market low)'. This takes profit at the input set in option 1).
MACD with 1D Stochastic Confirmation Reversal StrategyOverview
The MACD with 1D Stochastic Confirmation Reversal Strategy utilizes MACD indicator in conjunction with 1 day timeframe Stochastic indicators to obtain the high probability short-term trend reversal signals. The main idea is to wait until MACD line crosses up it’s signal line, at the same time Stochastic indicator on 1D time frame shall show the uptrend (will be discussed in methodology) and not to be in the oversold territory. Strategy works on time frames from 30 min to 4 hours and opens only long trades.
Unique Features
Dynamic stop-loss system: Instead of fixed stop-loss level strategy utilizes average true range (ATR) multiplied by user given number subtracted from the position entry price as a dynamic stop loss level.
Configurable Trading Periods: Users can tailor the strategy to specific market windows, adapting to different market conditions.
Higher time frame confirmation: Strategy utilizes 1D Stochastic to establish the major trend and confirm the local reversals with the higher probability.
Trailing take profit level: After reaching the trailing profit activation level scrip activate the trailing of long trade using EMA. More information in methodology.
Methodology
The strategy opens long trade when the following price met the conditions:
MACD line of MACD indicator shall cross over the signal line of MACD indicator.
1D time frame Stochastic’s K line shall be above the D line.
1D time frame Stochastic’s K line value shall be below 80 (not overbought)
When long trade is executed, strategy set the stop-loss level at the price ATR multiplied by user-given value below the entry price. This level is recalculated on every next candle close, adjusting to the current market volatility.
At the same time strategy set up the trailing stop validation level. When the price crosses the level equals entry price plus ATR multiplied by user-given value script starts to trail the price with EMA. If price closes below EMA long trade is closed. When the trailing starts, script prints the label “Trailing Activated”.
Strategy settings
In the inputs window user can setup the following strategy settings:
ATR Stop Loss (by default = 3.25, value multiplied by ATR to be subtracted from position entry price to setup stop loss)
ATR Trailing Profit Activation Level (by default = 4.25, value multiplied by ATR to be added to position entry price to setup trailing profit activation level)
Trailing EMA Length (by default = 20, period for EMA, when price reached trailing profit activation level EMA will stop out of position if price closes below it)
User can choose the optimal parameters during backtesting on certain price chart, in our example we use default settings.
Justification of Methodology
This strategy leverages 2 time frames analysis to have the high probability reversal setups on lower time frame in the direction of the 1D time frame trend. That’s why it’s recommended to use this strategy on 30 min – 4 hours time frames.
To have an approximation of 1D time frame trend strategy utilizes classical Stochastic indicator. The Stochastic Indicator is a momentum oscillator that compares a security's closing price to its price range over a specific period. It's used to identify overbought and oversold conditions. The indicator ranges from 0 to 100, with readings above 80 indicating overbought conditions and readings below 20 indicating oversold conditions.
It consists of two lines:
%K: The main line, calculated using the formula (CurrentClose−LowestLow)/(HighestHigh−LowestLow)×100 . Highest and lowest price taken for 14 periods.
%D: A smoothed moving average of %K, often used as a signal line.
Strategy logic assumes that on 1D time frame it’s uptrend in %K line is above the %D line. Moreover, we can consider long trade only in %K line is below 80. It means that in overbought state the long trade will not be opened due to higher probability of pullback or even major trend reversal. If these conditions are met we are going to our working (lower) time frame.
On the chosen time frame, we remind you that for correct work of this strategy you shall use 30min – 4h time frames, MACD line shall cross over it’s signal line. The MACD (Moving Average Convergence Divergence) is a popular momentum and trend-following indicator used in technical analysis. It helps traders identify changes in the strength, direction, momentum, and duration of a trend in a stock's price.
The MACD consists of three components:
MACD Line: This is the difference between a short-term Exponential Moving Average (EMA) and a long-term EMA, typically calculated as: MACD Line=12-period EMA−26-period
Signal Line: This is a 9-period EMA of the MACD Line, which helps to identify buy or sell signals. When the MACD Line crosses above the Signal Line, it can be a bullish signal (suggesting a buy); when it crosses below, it can be a bearish signal (suggesting a sell).
Histogram: The histogram shows the difference between the MACD Line and the Signal Line, visually representing the momentum of the trend. Positive histogram values indicate increasing bullish momentum, while negative values indicate increasing bearish momentum.
In our script we are interested in only MACD and signal lines. When MACD line crosses signal line there is a high chance that short-term trend reversed to the upside. We use this strategy on 45 min time frame.
ATR is used to adjust the strategy risk management to the current market volatility. If volatility is low, we don’t need the large stop loss to understand the there is a high probability that we made a mistake opening the trade. User can setup the settings ATR Stop Loss and ATR Trailing Profit Activation Level to realize his own risk to reward preferences, but the unique feature of a strategy is that after reaching trailing profit activation level strategy is trying to follow the trend until it is likely to be finished instead of using fixed risk management settings. It allows sometimes to be involved in the large movements.
Backtest Results
Operating window: Date range of backtests is 2023.01.01 - 2024.08.01. It is chosen to let the strategy to close all opened positions.
Commission and Slippage: Includes a standard Binance commission of 0.1% and accounts for possible slippage over 5 ticks.
Initial capital: 10000 USDT
Percent of capital used in every trade: 30%
Maximum Single Position Loss: -4.79%
Maximum Single Profit: +20.14%
Net Profit: +2361.33 USDT (+44.72%)
Total Trades: 123 (44.72% win rate)
Profit Factor: 1.623
Maximum Accumulated Loss: 695.80 USDT (-5.48%)
Average Profit per Trade: 19.20 USDT (+0.59%)
Average Trade Duration: 30 hours
These results are obtained with realistic parameters representing trading conditions observed at major exchanges such as Binance and with realistic trading portfolio usage parameters.
How to Use
Add the script to favorites for easy access.
Apply to the desired timeframe between 30 min and 4 hours and chart (optimal performance observed on 45 min BTC/USDT).
Configure settings using the dropdown choice list in the built-in menu.
Set up alerts to automate strategy positions through web hook with the text: {{strategy.order.alert_message}}
Disclaimer:
Educational and informational tool reflecting Skyrex commitment to informed trading. Past performance does not guarantee future results. Test strategies in a simulated environment before live implementation
Dual Chain StrategyDual Chain Strategy - Technical Overview
How It Works:
The Dual Chain Strategy is a unique approach to trading that utilizes Exponential Moving Averages (EMAs) across different timeframes, creating two distinct "chains" of trading signals. These chains can work independently or together, capturing both long-term trends and short-term price movements.
Chain 1 (Longer-Term Focus):
Entry Signal: The entry signal for Chain 1 is generated when the closing price crosses above the EMA calculated on a weekly timeframe. This suggests the start of a bullish trend and prompts a long position.
bullishChain1 = enableChain1 and ta.crossover(src1, entryEMA1)
Exit Signal: The exit signal is triggered when the closing price crosses below the EMA on a daily timeframe, indicating a potential bearish reversal.
exitLongChain1 = enableChain1 and ta.crossunder(src1, exitEMA1)
Parameters: Chain 1's EMA length is set to 10 periods by default, with the flexibility for user adjustment to match various trading scenarios.
Chain 2 (Shorter-Term Focus):
Entry Signal: Chain 2 generates an entry signal when the closing price crosses above the EMA on a 12-hour timeframe. This setup is designed to capture quicker, shorter-term movements.
bullishChain2 = enableChain2 and ta.crossover(src2, entryEMA2)
Exit Signal: The exit signal occurs when the closing price falls below the EMA on a 9-hour timeframe, indicating the end of the shorter-term trend.
exitLongChain2 = enableChain2 and ta.crossunder(src2, exitEMA2)
Parameters: Chain 2's EMA length is set to 9 periods by default, and can be customized to better align with specific market conditions or trading strategies.
Key Features:
Dual EMA Chains: The strategy's originality shines through its dual-chain configuration, allowing traders to monitor and react to both long-term and short-term market trends. This approach is particularly powerful as it combines the strengths of trend-following with the agility of momentum trading.
Timeframe Flexibility: Users can modify the timeframes for both chains, ensuring the strategy can be tailored to different market conditions and individual trading styles. This flexibility makes it versatile for various assets and trading environments.
Independent Trade Logic: Each chain operates independently, with its own set of entry and exit rules. This allows for simultaneous or separate execution of trades based on the signals from either or both chains, providing a robust trading system that can handle different market phases.
Backtesting Period: The strategy includes a configurable backtesting period, enabling thorough performance assessment over a historical range. This feature is crucial for understanding how the strategy would have performed under different market conditions.
time_cond = time >= startDate and time <= finishDate
What It Does:
The Dual Chain Strategy offers traders a distinctive trading tool that merges two separate EMA-based systems into one cohesive framework. By integrating both long-term and short-term perspectives, the strategy enhances the ability to adapt to changing market conditions. The originality of this script lies in its innovative dual-chain design, providing traders with a unique edge by allowing them to capitalize on both significant trends and smaller, faster price movements.
Whether you aim to capture extended market trends or take advantage of more immediate price action, the Dual Chain Strategy provides a comprehensive solution with a high degree of customization and strategic depth. Its flexibility and originality make it a valuable tool for traders seeking to refine their approach to market analysis and execution.
How to Use the Dual Chain Strategy
Step 1: Access the Strategy
Add the Script: Start by adding the Dual Chain Strategy to your TradingView chart. You can do this by searching for the script by name or using the link provided.
Select the Asset: Apply the strategy to your preferred trading pair or asset, such as #BTCUSD, to see how it performs.
Step 2: Configure the Settings
Enable/Disable Chains:
The strategy is designed with two independent chains. You can choose to enable or disable each chain depending on your trading style and the market conditions.
enableChain1 = input.bool(true, title='Enable Chain 1')
enableChain2 = input.bool(true, title='Enable Chain 2')
By default, both chains are enabled. If you prefer to focus only on longer-term trends, you might disable Chain 2, or vice versa if you prefer shorter-term trades.
Set EMA Lengths:
Adjust the EMA lengths for each chain to match your trading preferences.
Chain 1: The default EMA length is 10 periods. This chain uses a weekly timeframe for entry signals and a daily timeframe for exits.
len1 = input.int(10, minval=1, title='Length Chain 1 EMA', group="Chain 1")
Chain 2: The default EMA length is 9 periods. This chain uses a 12-hour timeframe for entries and a 9-hour timeframe for exits.
len2 = input.int(9, minval=1, title='Length Chain 2 EMA', group="Chain 2")
Customize Timeframes:
You can customize the timeframes used for entry and exit signals for both chains.
Chain 1:
Entry Timeframe: Weekly
Exit Timeframe: Daily
tf1_entry = input.timeframe("W", title='Chain 1 Entry Timeframe', group="Chain 1")
tf1_exit = input.timeframe("D", title='Chain 1 Exit Timeframe', group="Chain 1")
Chain 2:
Entry Timeframe: 12 Hours
Exit Timeframe: 9 Hours
tf2_entry = input.timeframe("720", title='Chain 2 Entry Timeframe (12H)', group="Chain 2")
tf2_exit = input.timeframe("540", title='Chain 2 Exit Timeframe (9H)', group="Chain 2")
Set the Backtesting Period:
Define the period over which you want to backtest the strategy. This allows you to see how the strategy would have performed historically.
startDate = input.time(timestamp('2015-07-27'), title="StartDate")
finishDate = input.time(timestamp('2026-01-01'), title="FinishDate")
Step 3: Analyze the Signals
Understand the Entry and Exit Signals:
Buy Signals: When the price crosses above the entry EMA, the strategy generates a buy signal.
bullishChain1 = enableChain1 and ta.crossover(src1, entryEMA1)
Sell Signals: When the price crosses below the exit EMA, the strategy generates a sell signal.
bearishChain2 = enableChain2 and ta.crossunder(src2, entryEMA2)
Review the Visual Indicators:
The strategy plots buy and sell signals on the chart with labels for easy identification:
BUY C1/C2 for buy signals from Chain 1 and Chain 2.
SELL C1/C2 for sell signals from Chain 1 and Chain 2.
This visual aid helps you quickly understand when and why trades are being executed.
Step 4: Optimize the Strategy
Backtest Results:
Review the strategy’s performance over the backtesting period. Look at key metrics like net profit, drawdown, and trade statistics to evaluate its effectiveness.
Adjust the EMA lengths, timeframes, and other settings to see how changes affect the strategy’s performance.
Customize for Live Trading:
Once satisfied with the backtest results, you can apply the strategy settings to live trading. Remember to continuously monitor and adjust as needed based on market conditions.
Step 5: Implement Risk Management
Use Realistic Position Sizing:
Keep your risk exposure per trade within a comfortable range, typically between 1-2% of your trading capital.
Set Alerts:
Set up alerts for buy and sell signals, so you don’t miss trading opportunities.
Paper Trade First:
Consider running the strategy in a paper trading account to understand its behavior in real market conditions before committing real capital.
This dual-layered approach offers a distinct advantage: it enables the strategy to adapt to varying market conditions by capturing both broad trends and immediate price action without one chain's activity impacting the other's decision-making process. The independence of these chains in executing transactions adds a level of sophistication and flexibility that is rarely seen in more conventional trading systems, making the Dual Chain Strategy not just unique, but a powerful tool for traders seeking to navigate complex market environments.
Quatro SMA Strategy [4h]Hello, I would like to present to you The "Quatro SMA" strategy
Strategy is based on four simple moving averages of different lengths and monitoring trading volume. The key idea is to identify strong market trends by comparing short-term moving averages with the long-term SMA. The strategy generates buy signals when all short-term SMAs are above the SMA(200) and the volume confirms the strength of the move. Similarly, sell signals are generated when all short-term SMAs are below the SMA(200), and the volume is sufficiently high.
The strategy manages risk by applying a stop loss and three different Take Profit levels (TP1, TP2, TP3), with varying percentages of the position closed at each level.
Each Take Profit level is triggered at a specific percentage gain, with the position being closed gradually depending on the achieved targets. The percentage of the position closed at each TP level is also defined by the user.
Indicators and Parameters:
Simple Moving Averages (SMA):
The script utilizes four simple moving averages with different lengths (4, 16, 32, 200). The first three SMAs (SMA1, SMA2, SMA3) are used to determine the trend direction, while the fourth SMA (with a length of 200) serves as a support/resistance line.
Volume:
The script monitors trading volume and checks if the current volume exceeds 2.5 times the average volume of the last 40 candles. High volume is considered as confirmation of trend strength.
Entry Conditions:
- Long Position: Triggered when SMA1 > SMA2 > SMA3, the closing price is above SMA(200), and the volume condition is met.
- Short Position: Triggered when SMA1 < SMA2 < SMA3, the closing price is below SMA(200), and the volume condition is met.
Exit Conditions:
- Long Position: Closed when SMA1 < SMA2 < SMA3 and the closing price is above SMA(200).
- Short Position: Closed when SMA1 > SMA2 > SMA3 and the closing price is below SMA(200).
to determine the level of stop loss and target point I used a piece of code by RafaelZioni, here is the script from which a piece of code was taken
I hope the strategy will be helpful, as always, best regards and safe trades
;)
Double CCI Confirmed Hull Moving Average Reversal StrategyOverview
The Double CCI Confirmed Hull Moving Average Strategy utilizes hull moving average (HMA) in conjunction with two commodity channel index (CCI) indicators: the slow and fast to increase the probability of entering when the short and mid-term uptrend confirmed. The main idea is to wait until the price breaks the HMA while both CCI are showing that the uptrend has likely been already started. Moreover, strategy uses exponential moving average (EMA) to trail the price when it reaches the specific level. The strategy opens only long trades.
Unique Features
Dynamic stop-loss system: Instead of fixed stop-loss level strategy utilizes average true range (ATR) multiplied by user given number subtracted from the position entry price as a dynamic stop loss level.
Configurable Trading Periods: Users can tailor the strategy to specific market windows, adapting to different market conditions.
Double trade setup confirmation: Strategy utilizes two different period CCI indicators to confirm the breakouts of HMA.
Trailing take profit level: After reaching the trailing profit activation level scrip activate the trailing of long trade using EMA. More information in methodology.
Methodology
The strategy opens long trade when the following price met the conditions:
Short-term period CCI indicator shall be above 0.
Long-term period CCI indicator shall be above 0.
Price shall cross the HMA and candle close above it with the same candle
When long trade is executed, strategy set the stop-loss level at the price ATR multiplied by user-given value below the entry price. This level is recalculated on every next candle close, adjusting to the current market volatility.
At the same time strategy set up the trailing stop validation level. When the price crosses the level equals entry price plus ATR multiplied by user-given value script starts to trail the price with EMA. If price closes below EMA long trade is closed. When the trailing starts, script prints the label “Trailing Activated”.
Strategy settings
In the inputs window user can setup the following strategy settings:
ATR Stop Loss (by default = 1.75)
ATR Trailing Profit Activation Level (by default = 2.25)
CCI Fast Length (by default = 25, used for calculation short term period CCI
CCI Slow Length (by default = 50, used for calculation long term period CCI)
Hull MA Length (by default = 34, period of HMA, which shall be broken to open trade)
Trailing EMA Length (by default = 20)
User can choose the optimal parameters during backtesting on certain price chart.
Justification of Methodology
Before understanding why this particular combination of indicator has been chosen let's briefly explain what is CCI and HMA.
The Commodity Channel Index (CCI) is a momentum-based technical indicator used in trading to measure a security's price relative to its average price over a given period. Developed by Donald Lambert in 1980, the CCI is primarily used to identify cyclical trends in a security, helping traders to spot potential buying or selling opportunities.
The CCI formula is:
CCI = (Typical Price − SMA) / (0.015 × Mean Deviation)
Typical Price (TP): This is calculated as the average of the high, low, and closing prices for the period.
Simple Moving Average (SMA): This is the average of the Typical Prices over a specific number of periods.
Mean Deviation: This is the average of the absolute differences between the Typical Price and the SMA.
The result is a value that typically fluctuates between +100 and -100, though it is not bounded and can go higher or lower depending on the price movement.
The Hull Moving Average (HMA) is a type of moving average that was developed by Alan Hull to improve upon the traditional moving averages by reducing lag while maintaining smoothness. The goal of the HMA is to create an indicator that is both quick to respond to price changes and less prone to whipsaws (false signals).
How the Hull Moving Average is Calculated?
The Hull Moving Average is calculated using the following steps:
Weighted Moving Average (WMA): The HMA starts by calculating the Weighted Moving Average (WMA) of the price data over a period square root of n (sqrt(n))
Speed Adjustment: A WMA is then calculated for half of the period n/2, and this is multiplied by 2 to give more weight to recent prices.
Lag Reduction: The WMA of the full period n is subtracted from the doubled n/2 WMA.
Final Smoothing: To smooth the result and reduce noise, a WMA is calculated for the square root of the period n.
The formula can be represented as:
HMA(n) = WMA(WMA(n/2) × 2 − WMA(n), sqrt(n))
The Weighted Moving Average (WMA) is a type of moving average that gives more weight to recent data points, making it more responsive to recent price changes than a Simple Moving Average (SMA). In a WMA, each data point within the selected period is multiplied by a weight, with the most recent data receiving the highest weight. The sum of these weighted values is then divided by the sum of the weights to produce the WMA.
This strategy leverages HMA of user given period as a critical level which shall be broken to say that probability of trend change to the upside increased. HMA reacts faster than EMA or SMA to the price change, that’s why it increases chances to enter new trade earlier. Long-term period CCI helps to have an approximation of mid-term trend. If it’s above 0 the probability of uptrend increases. Short-period CCI allows to have an approximation of short-term trend reversal from down to uptrend. This approach increases chances to have a long trade setup in the direction of mid-term trend when the short-term trend starts to reverse.
ATR is used to adjust the strategy risk management to the current market volatility. If volatility is low, we don’t need the large stop loss to understand the there is a high probability that we made a mistake opening the trade. User can setup the settings ATR Stop Loss and ATR Trailing Profit Activation Level to realize his own risk to reward preferences, but the unique feature of a strategy is that after reaching trailing profit activation level strategy is trying to follow the trend until it is likely to be finished instead of using fixed risk management settings. It allows sometimes to be involved in the large movements. It’s also important to make a note, that script uses HMA to enter the trade, but for trailing it leverages EMA. It’s used because EMA has no such fast reaction to price move which increases probability not to be stopped out from any significant uptrend move.
Backtest Results
Operating window: Date range of backtests is 2022.07.01 - 2024.08.01. It is chosen to let the strategy to close all opened positions.
Commission and Slippage: Includes a standard Binance commission of 0.1% and accounts for possible slippage over 5 ticks.
Initial capital: 10000 USDT
Percent of capital used in every trade: 100%
Maximum Single Position Loss: -4.67%
Maximum Single Profit: +19.66%
Net Profit: +14897.94 USDT (+148.98%)
Total Trades: 104 (36.54% win rate)
Profit Factor: 2.312
Maximum Accumulated Loss: 1302.66 USDT (-9.58%)
Average Profit per Trade: 143.25 USDT (+0.96%)
Average Trade Duration: 34 hours
These results are obtained with realistic parameters representing trading conditions observed at major exchanges such as Binance and with realistic trading portfolio usage parameters.
How to Use
Add the script to favorites for easy access.
Apply to the desired timeframe and chart (optimal performance observed on 2h BTC/USDT).
Configure settings using the dropdown choice list in the built-in menu.
Set up alerts to automate strategy positions through web hook with the text: {{strategy.order.alert_message}}
Disclaimer:
Educational and informational tool reflecting Skyrex commitment to informed trading. Past performance does not guarantee future results. Test strategies in a simulated environment before live implementation
WODIsMA Strategy 3 MA Crossover & Bull-Bear Trend ConfirmationWODIsMA Strategy is a versatile trading strategy designed to leverage the strength of moving averages and volatility indicators to provide clear trading signals for both long and short positions. This strategy is suitable for traders looking for a systematic approach to trading with adjustable parameters to fit various market conditions and personal trading styles.
Key Features
Customizable Moving Averages:
The strategy allows users to select different types of moving averages (SMA, EMA, SMMA, WMA, VWMA) for short-term, mid-term, long-term, and bull-bear trend identification.
Each moving average can be customized with different lengths, sources (e.g., close, high, low), timeframes, and colors.
Position Management:
Users can specify the percentage of capital to use per trade and the percentage to close per partial exit.
The strategy supports both long and short positions with the ability to enable or disable each direction.
Volatility Filter:
Incorporates a volatility filter to ensure trades are only taken when market volatility is above a user-defined threshold, enhancing the strategy's effectiveness in dynamic market conditions.
Bull-Bear Trend Line:
Option to enable a bull-bear trend line that helps identify the overall market trend. Trades are taken based on the relationship between the long-term moving average and the bull-bear trend line.
Partial Exits and Full Close Logic:
The strategy includes logic for partial exits based on the crossing of mid-term and long-term moving averages.
Ensures that positions are fully closed when adverse conditions are detected, such as the price crossing below the bull-bear trend line.
Stop Loss Management:
Implements user-defined stop loss levels to manage risk effectively. The stop loss is dynamically adjusted based on the entry price and user input.
Detailed Description
Moving Average Calculation: The strategy calculates up to six different moving averages, each with customizable parameters. These moving averages help identify the short-term, mid-term, long-term trends, and overall market direction.
Trading Signals:
Long Signal: A long position is opened when the short-term moving average is above the long-term moving average, and the mid-term moving average crosses above the long-term moving average.
Short Signal: A short position is opened when the short-term moving average is below the long-term moving average, and the mid-term moving average crosses below the long-term moving average.
Volatility Condition: The strategy includes a volatility filter that activates trades only when volatility exceeds a specified threshold, ensuring trades are made in favorable market conditions.
Bull-Bear Trend Confirmation: When enabled, trades are filtered based on the relationship between the long-term moving average and the bull-bear trend line, adding another layer of confirmation.
Stop Loss and Exits:
The strategy manages risk by placing stop loss orders based on user-defined percentages.
Positions are partially or fully closed based on the crossing of moving averages and the relationship with the bull-bear trend line.
Originality and Usefulness
This strategy is original as it combines multiple moving averages and volatility indicators in a structured manner to provide reliable trading signals. Its versatility allows traders to adjust the parameters to match their trading preferences and market conditions. The inclusion of a volatility filter and bull-bear trend line adds significant value by reducing false signals and ensuring trades are taken in the direction of the overall market trend. The detailed descriptions and customizable settings make this strategy accessible and understandable for traders, even those unfamiliar with the underlying Pine Script code.
By providing clear entry, exit, and risk management rules, the WODIsMA Strategy enhances the trader's ability to navigate different market environments, making it a valuable addition to the TradingView community scripts.
AsianRange, KillZones, RSI Bars, and Supertrend Strategy by VKombinacija AsianRange, KillZones, RSI Bars, and Supertrend Strategy
Chandelier Exit Strategy with 200 EMA FilterStrategy Name and Purpose
Chandelier Exit Strategy with 200EMA Filter
This strategy uses the Chandelier Exit indicator in combination with a 200-period Exponential Moving Average (EMA) to generate trend-based trading signals. The main purpose of this strategy is to help traders identify high-probability entry points by leveraging the Chandelier Exit for stop loss levels and the EMA for trend confirmation. This strategy aims to provide clear rules for entries and exits, improving overall trading discipline and performance.
Originality and Usefulness
This script integrates two powerful indicators to create a cohesive and effective trading strategy:
Chandelier Exit : This indicator is based on the Average True Range (ATR) and identifies potential stop loss levels. The Chandelier Exit helps manage risk by setting stop loss levels at a distance from the highest high or lowest low over a specified period, multiplied by the ATR. This ensures that the stop loss adapts to market volatility.
200-period Exponential Moving Average (EMA) : The EMA acts as a trend filter. By ensuring trades are only taken in the direction of the overall trend, the strategy improves the probability of success. For long entries, the close price must be above the 200 EMA, indicating a bullish trend. For short entries, the close price must be below the 200 EMA, indicating a bearish trend.
Combining these indicators adds layers of confirmation and risk management, enhancing the strategy's effectiveness. The Chandelier Exit provides dynamic stop loss levels based on market volatility, while the EMA ensures trades align with the prevailing trend.
Entry Conditions
Long Entry
A buy signal is generated by the Chandelier Exit.
The close price is above the 200 EMA, indicating a strong bullish trend.
Short Entry
A sell signal is generated by the Chandelier Exit.
The close price is below the 200 EMA, indicating a strong bearish trend.
Exit Conditions
For long positions: The position is closed when a sell signal is generated by the Chandelier Exit.
For short positions: The position is closed when a buy signal is generated by the Chandelier Exit.
Risk Management
Account Size: 1,000,00 yen
Commission and Slippage: 17 pips commission and 1 pip slippage per trade
Risk per Trade: 10% of account equity
Stop Loss: For long trades, the stop loss is placed slightly below the candle that generated the buy signal. For short trades, the stop loss is placed slightly above the candle that generated the sell signal. The stop loss levels are dynamically adjusted based on the ATR.
Settings Options
ATR Period: Set the period for calculating the ATR to determine the Chandelier Exit levels.
ATR Multiplier: Set the multiplier for ATR to define the distance of stop loss levels from the highest high or lowest low.
Use Close Price for Extremums: Choose whether to use the close price for calculating the extremums.
EMA Period: Set the period for the EMA to adjust the trend filter sensitivity.
Show Buy/Sell Labels: Choose whether to display buy and sell labels on the chart for visual confirmation.
Highlight State: Choose whether to highlight the bullish or bearish state on the chart.
Sufficient Sample Size
The strategy has been backtested with a sufficient sample size to evaluate its performance accurately. This ensures that the strategy's results are statistically significant and reliable.
Notes
This strategy is based on historical data and does not guarantee future results.
Thoroughly backtest and validate results before using in live trading.
Market volatility and other external factors can affect performance and may not yield expected results.
Acknowledgment
This strategy uses the Chandelier Exit indicator. Special thanks to the original contributors for their work on the Chandelier Exit concept.
Clean Chart Explanation
The script is published with a clean chart to ensure that its output is readily identifiable and easy to understand. No other scripts are included on the chart, and any drawings or images used are specifically to illustrate how the script works.
Moving Average Crossover Swing StrategyMoving Average Crossover Swing Strategy
**Overview:**
The basic concept of this strategy is to generate a signal when a faster/shorter length moving average crosses over (for Longs) or crosses under (for Shorts) a medium/longer length moving average. All of which are customizable. This strategy can work on any timeframe, however the daily is the timeframe used for the default settings and screenshots, as it was designed to be a multi-day swing strategy. Once a signal has been confirmed with a candle close, based on user options, the strategy will enter the trade on the open of the next candle.
The crossover strategy is nothing new to trading, but what can make this strategy unique and helpful, is the addition of further confirmation points, ATR based stop loss and take profit targets, optional early exit criteria, customizable to your needs and style, and just about everything visual can be toggled on/off. This strategy is based on a Trend (MA) indicator and a Momentum (MACD) indicator. While a Volume-based indicator is not shown here, one could consider using their favorite from that category to further compliment the signal idea.
It should be noted that depending on the time frame, direction(s) chosen, the signal options, confirmation options, and exit options selected, that a ticker may not produce more than 100 trades on the back test. Depending on your style and frequency, one could consider adjusting options and/or testing multiple tickers. It should also be noted that this strategy simply tests the underlying stock prices, not options contracts. And of course, testing this strategy against historical data does not assume that the same results will occur in future price action.
Shoutout given to Ripster's Clouds Indicator as pieces of that code were taken and modified to create both the Cloud visualization effects, and the Moving Average Pair Plots that are implemented in this strategy.
BASIC DEFAULTS
All can be changed as normal
Initial capital = 10,000
Order Sizing = 25% of equity (use the "Inputs" tab to modify this)
Pyramiding = 0
Commission = 0.65 USD per order
Price Verification = 1 tick
Slippage = 1 tick
RISK MANAGMENT
You will notice two different percentage options and ATR multipliers. This strategy will adjust position sizing by not exceeding either one of those % values based on the ATR (Average True Range) of the symbol and the multipliers selected, should the stock hit the stop loss price.
For Example, lets assume these values are true:
Account size = $10,000,
Max Risk = 1% of account size
Max Position Size = 25% of the account size
Stock Price = 23.45
ATR = 3.5
ATR Stop Loss Multiplier = 1.4
Then the formulas would be:
ACCT_SIZE * MaxRisk_% = 10000 * .01 = $100 (MaxCashRisk)
-----
MaxCashRisk / (ATR * ATR_SL_MULTIPLIER) = 100 / (3.5 * 1.4) = 20.4 Shares based on Max Cash Risk
-----
(ACCT_SIZE * MaxEquity_%) / STOCK_PRICE = (10000 * .25) / 23.45 = 106.61 Shares based on Max Equity Allocation
The minimum value of each of those options is then used, which in this case would be to purchase 20 shares so as not to exceed the max dollar risk should the stock reach the stop loss target. Likewise, if the ATR were to be much lower, say 0.48 cents, and all else the same, then the strategy would purchase the 106 shares based on Max Equity Allocation because the Max Cash Risk would require 149.25 shares.
MOVING AVERAGE OPTIONS
Select between and change the length & type of up to 5 pairs (10 total) of moving averages
The "Show Cloud-x" option will display a fill color between the "a" and "b" pairs
All moving averages lines can be toggled on/off in the "Style" tab, as well as adjusting their colors.
Visualization features do not affect calculations, meaning you could have all or nothing on the chart and the strategy will still produce results
SIGNAL CHOICES
Choose the fast/shorter length MA and the medium/longer length MA to determine the entry signal
CONFIRMATION OPTIONS
Both of these have customizable values and can be toggled on/off
A candle close over a slower/much longer length moving average
An additional cross-over (cross-under for Shorts) on the MACD indicator using default MACD values. While the MACD indicator is not necessary to have on the chart, it can help to add that for visualization. The calculations will perform whether the indicator is on the chart or not.
EARLY EXIT CRITERIA
Both can be toggled on/off with customizable values
MA Cross Exit will exit the trade early if the select moving averages cross-under (for longs) or cross-over (for shorts), indicating a potential reversal.
Max Bars in Trades will act as a last-resort exit by simply calculating the amount of full bars the trade has been open, and exiting on the opening of the next bar. For example: the default value is 8 bars, so after 8 full bars in the trade, if no other exit has been triggered (Stop Loss, Take Profit, or MA Cross(if enabled)), then the trade will exit at the opening of the 9th bar.
Finally, there is a table displaying the amount of trades taken for each side, and the amount & percent of both early exits. This table can be turned off in the "Style" tab
ADDITIONAL PLOTS
MACD (Moving Average Convergence/Divergence):
- The MACD is an optional confirmation indicator for this strategy.
- Plotting the indicator is not necessary for the strategy to work, but it can be helpful to visually see the status and position of the MACD if this feature is enabled in the strategy
- This helps to identify if there is also momentum behind the entry signal
Strategy SEMA SDI WebhookPurpose of the Code:
The strategy utilizes Exponential Moving Averages (EMA) and Smoothed Directional Indicators (SDI) to generate buy and sell signals. It includes features like leverage, take profit, stop loss, and trailing stops. The strategy is intended for backtesting and automating trades based on the specified indicators and conditions.
Key Components and Functionalities:
1.Strategy Settings:
Overlay: The strategy will overlay on the price chart.
Slippage: Set to 1.
Commission Value: Set to 0.035.
Default Quantity Type: Percent of equity.
Default Quantity Value: 50% of equity.
Initial Capital: Set to 1000 units.
Calculation on Order Fills: Enabled.
Process Orders on Close: Enabled.
2.Date and Time Filters:
Inputs for enabling/disabling start and end dates.
Filters to execute strategy only within specified date range.
3.Leverage and Quantity:
Leverage: Adjustable leverage input (default 3).
USD Percentage: Adjustable percentage of equity to use for trades (default 50%).
Initial Capital: Calculated based on leverage and percentage of equity.
4.Take Profit, Stop Loss, and Trailing Stop:
Inputs for enabling/disabling take profit, stop loss, and trailing stop.
Adjustable parameters for take profit percentage (default 25%), stop loss percentage (default 4.8%), and trailing stop percentage (default 1.9%).
Calculations for take profit, stop loss, trailing price, and maximum profit tracking.
5.EMA Calculations:
Fast and slow EMAs.
Smoothed versions of the fast and slow EMAs.
6.SDI Calculations:
Directional movement calculation for positive and negative directional indicators.
Difference between the positive and negative directional indicators, smoothed.
7.Buy/Sell Conditions:
Long (Buy) Condition: Positive DI is greater than negative DI, and fast EMA is greater than slow EMA.
Short (Sell) Condition: Negative DI is greater than positive DI, and fast EMA is less than slow EMA.
8.Strategy Execution:
If buy conditions are met, close any short positions and enter a long position.
If sell conditions are met, close any long positions and enter a short position.
Exit conditions for long and short positions based on take profit, stop loss, and trailing stop levels.
Close all positions if outside the specified date range.
Usage:
This strategy is used to automate trading based on the specified conditions involving EMAs and SDI. It allows backtesting to evaluate performance based on historical data. The strategy includes risk management through take profit, stop loss, and trailing stops to protect gains and limit losses. Traders can customize the parameters to fit their specific trading preferences and risk tolerance. Differently, it can perform leverage analysis and use it as a template.
By using this strategy, traders can systematically execute trades based on technical indicators, helping to remove emotional bias and improve consistency in trading decisions.
Important Note:
This script is provided for educational and template purposes and does not constitute financial advice. Traders and investors should conduct their research and analysis before making any trading decisions.