Heikin Ashi with WMA/EMA, Target, Stoploss, and Trailing Stop 22If you continue to experience the "Undeclared identifier 'label'" error, an alternative approach is to use the plotshape function instead of label.new. The plotshape function can place markers (such as "Buy" and "Sell") on the chart without directly using label, and it’s widely supported in Pine Script.
Indicators and strategies
UT 3 3 strategythis is for test Ut bot 3 and 3
this have tp and sl persent and show use martingle for manage losses
in table show maximum sequent loss and date that happened
Dynamic Trading Strategy with Key Levels, Entry/Exit Managementjust a strategy tester i dont have any copy right of this indicator
MTF+MA V2 MTF+MA Indicator by ridvansozen1
The MTF+MA Indicator is a multi-timeframe moving average strategy developed by TradingView user ridvansozen1. This tool is designed to assist cryptocurrency traders in identifying potential long and short trading opportunities by analyzing market trends across multiple timeframes.
Key Features:
Multi-Timeframe Analysis: Utilizes fast and slow exponential moving averages (EMAs) on user-defined long, mid, and short-term timeframes to assess market direction.
Signal Generation: Generates long signals when all selected timeframes indicate a positive trend and short signals when all indicate a negative trend.
Customizable Parameters: Allows users to adjust source data, EMA lengths, and timeframes to tailor the strategy to specific trading preferences.
Date Range Filtering: Includes settings to define specific date ranges for signal generation, enabling focused backtesting and analysis.
How to Use:
Configure Moving Averages: Set your preferred lengths for the fast and slow EMAs.
Select Timeframes: Choose the long, mid, and short-term timeframes that align with your trading strategy.
Set Date Range: Define the date range during which the strategy should generate signals.
Interpret Signals: Monitor the indicator plots—green, blue, and red lines representing the EMA differences across timeframes. A long position is suggested when all three lines are above zero, and a short position is suggested when all are below zero.
Disclaimer: This indicator is intended for educational purposes and should not be considered financial advice. Users are encouraged to conduct thorough backtesting and apply proper risk management before utilizing this strategy in live trading.
Cruce de Medias TotalEs una mejora de la estrategia Cruce de Medias Avanzado permitiendo añadir una tercera media móvil y también permitiendo operar en corto.
Al ser una estrategia se puede ir afinando el rendimiento y personalizando no sólo los períodos de las 3 medias móviles sino activando o desactivando la posibilidad de operar con tres medias o sólo con dos, y también activando o desactivando la opción de operar en corto.
En resumen, es una estrategia de cruce de medias, tienes 7 tipos de medías móviles a elegir, y la posibilidad de operar en corto activando pestaña y también la opción de incluir una tercera media móvil. Por defecto sólo aparece la rentabilidad de operaciones largas (de compras) y cruce de 2 medias móviles.
Cruce de Medias AvanzadoLa estrategia es muy simple, es cruce de medias móviles, por defecto la rápida es 50 y la lenta 200 pero se pueden personalizar, es una estrategia a largo plazo que ha demostrado ser muy rentable en cualquiera de sus medias con índices en gráficos diarios.
Se pueden elegir distintos tipos de medias móviles existentes y ajustar la rentabilidad de cada una y ajustar sus medias móviles a para aumentar la rentabilidad.
Aquí tienes una descripción de las medias móviles añadidas al script y sus características:
Simple SMA (Media Móvil Simple):
Calcula el promedio simple de los precios de cierre durante un período específico.
Es la más básica y fácil de interpretar, pero puede ser lenta para reaccionar a los cambios bruscos en el precio.
Exponencial EMA (Media Móvil Exponencial):
Da más peso a los precios recientes, lo que la hace más sensible a los cambios de precio.
Responde más rápidamente a las fluctuaciones del mercado en comparación con la SMA, lo que ayuda a detectar cambios de tendencia más temprano.
Ponderada WMA (Media Móvil Ponderada):
Asigna más peso a los datos más recientes de forma lineal.
Proporciona un balance entre la sensibilidad de la EMA y la suavidad de la SMA, siendo útil para seguir tendencias a corto plazo.
Volumen Ponderada VWMA (Media Móvil Ponderada por Volumen):
Pondera los precios según el volumen de negociación, dándole más importancia a los precios con mayor volumen.
Es útil para analizar si los movimientos de precio están respaldados por un volumen alto, lo que indica mayor relevancia.
Hull HMA (Media Móvil de Hull):
Diseñada para minimizar el retraso y aumentar la sensibilidad al mismo tiempo.
Combina el suavizado y la rápida respuesta al precio, lo que la hace adecuada para traders que necesitan detectar cambios de tendencia rápidamente.
Media Suavizada RMA (Media Móvil Suavizada):
Es similar a la EMA pero con un suavizado diferente, proporcionando un promedio que filtra de forma más efectiva el ruido de precios.
Suele usarse para análisis de tendencias a medio plazo.
Media de Arnaud Legoux ALMA (Media Móvil ALMA):
Utiliza un algoritmo especial de suavizado con control de sesgo para reducir el ruido y mejorar la detección de tendencias.
Permite ajustar los parámetros de sesgo y suavizado para adaptarse a diferentes necesidades de trading.
Es conocida por su capacidad de mantener una respuesta rápida al precio al tiempo que suprime el ruido.
Estas medias móviles ofrecen diferentes enfoques para seguir y analizar las tendencias en los precios. Dependiendo de tu estrategia de trading, puedes elegir la media móvil que mejor se adapte a tus necesidades: desde una respuesta rápida con la HMA o EMA, hasta un enfoque más estable y menos reactivo con la SMA o RMA.
Prame Weekly RSI and EMA Strategy Prame Weekly RSI and EMA Strategy
weekly RSI 14 is above 55
EMA 9 weeks of weekly RSI 14 is more than EMA 21 weeks of weekly RSI 14
price EMA 9 weeks is more than price EMA 21 weeks
EMA Cross + RSI Pullback Strategy with 1H ConfirmationThis strategy combines an ema9 and ema21 cross on the 15min timeframe with a short retest of the RSI 50-line (or close to the RSI 50-line) on the candle before the cross, on the cross, or one or two candles after the cross.
The script uses higher time frame confirmation on the 1 hour. It gives only a buy signal on the 15 minute if on the 1 hour the ema21 is above the ema 50. It gives only a sell signal on the 15 minute if on the 1 hour the ema21 is below the ema50.
It is still in the testing phase. So please backtest this strategy before putting money in the game. I combine my trading with the ATR stoploss finder set on 0.8 (instead of 1.5 default) and aim for RR 1:2 or better.
Please feel free to comment (nicely and polite) ;)
ameer hamza indicator//@version=5
strategy("Simplified EMA + RSI Strategy", overlay=true)
// Input settings
emaShort = input.int(10, title="Short EMA Length", minval=1)
emaLong = input.int(30, title="Long EMA Length", minval=1)
rsiLength = input.int(14, title="RSI Length")
rsiOverbought = input.int(70, title="RSI Overbought Level", minval=50, maxval=100)
rsiOversold = input.int(30, title="RSI Oversold Level", minval=0, maxval=50)
stopLossPct = input.float(1.0, title="Stop Loss Percentage") / 100
takeProfitPct = input.float(2.0, title="Take Profit Percentage") / 100
// Indicators
emaShortLine = ta.ema(close, emaShort)
emaLongLine = ta.ema(close, emaLong)
rsi = ta.rsi(close, rsiLength)
// Plot EMA lines
plot(emaShortLine, color=color.blue, title="Short EMA")
plot(emaLongLine, color=color.red, title="Long EMA")
hline(rsiOverbought, "RSI Overbought", color=color.orange)
hline(rsiOversold, "RSI Oversold", color=color.green)
// Buy and Sell Conditions
longCondition = crossover(emaShortLine, emaLongLine) and rsi < rsiOverbought
shortCondition = crossunder(emaShortLine, emaLongLine) and rsi > rsiOversold
// Debugging
if (longCondition)
label.new(bar_index, high, "Long Entry", color=color.green, textcolor=color.white)
if (shortCondition)
label.new(bar_index, low, "Short Entry", color=color.red, textcolor=color.white)
// Entry Signals
if (longCondition)
strategy.entry("Long", strategy.long)
if (shortCondition)
strategy.entry("Short", strategy.short)
// Stop Loss and Take Profit
longStopLoss = strategy.position_avg_price * (1 - stopLossPct)
longTakeProfit = strategy.position_avg_price * (1 + takeProfitPct)
shortStopLoss = strategy.position_avg_price * (1 + stopLossPct)
shortTakeProfit = strategy.position_avg_price * (1 - takeProfitPct)
if (strategy.position_size > 0)
strategy.exit("Exit Long", stop=longStopLoss, limit=longTakeProfit)
if (strategy.position_size < 0)
strategy.exit("Exit Short", stop=shortStopLoss, limit=shortTakeProfit)
Average Monthly Closing Direction StrategyEstrategia que diseñé, que combina patrones históricos y filtros técnicos para mejorar las probabilidades de éxito en trading. La idea es simple: he identificado ciertos días específicos del mes que, según los datos históricos, tienen tendencia a cerrar en positivo (suben) o en negativo (bajan).
Minkiu Bollinger Band Strategy Convert all Indicator specific code to Strategy specific code. Don't use any code that a TradingView Strategy won't support. Especially timeframes and gaps. Define those in code so they are semantically the same as before.
Ichimoku + RSI + MACD Strategy1. Relative Strength Index (RSI)
Overview:
The Relative Strength Index (RSI) is a momentum oscillator that measures the speed and change of price movements. It ranges from 0 to 100 and is typically used to identify overbought or oversold conditions in a market.
How to Use with Ichimoku:
Long Entry: Look for RSI to be above 30 (indicating it is not oversold) when the price is above the Ichimoku Cloud.
Short Entry: Look for RSI to be below 70 (indicating it is not overbought) when the price is below the Ichimoku Cloud.
2. Moving Average Convergence Divergence (MACD)
Overview:
The MACD is a trend-following momentum indicator that shows the relationship between two moving averages of a security’s price. It consists of the MACD line, signal line, and histogram.
How to Use with Ichimoku:
Long Entry: Enter a long position when the MACD line crosses above the signal line while the price is above the Ichimoku Cloud.
Short Entry: Enter a short position when the MACD line crosses below the signal line while the price is below the Ichimoku Cloud.
Combined Strategy Example
Here’s a brief outline of how to structure a trading strategy using Ichimoku, RSI, and MACD:
Long Entry Conditions:
Price is above the Ichimoku Cloud.
RSI is above 30.
MACD line crosses above the signal line.
Short Entry Conditions:
Price is below the Ichimoku Cloud.
RSI is below 70.
MACD line crosses below the signal line.
Exit Conditions:
Exit long when MACD line crosses below the signal line.
Exit short when MACD line crosses above the signal line.
Zig Zag + Aroon StrategyBelow is a trading strategy that combines the Zig Zag indicator and the Aroon indicator. This combination can help identify trends and potential reversal points.
Zig Zag and Aroon Strategy Overview
Zig Zag Indicator:
The Zig Zag indicator helps to identify significant price movements and eliminates smaller fluctuations. It is useful for spotting trends and reversals.
Aroon Indicator:
The Aroon indicator consists of two lines: Aroon Up and Aroon Down. It measures the time since the highest high and the lowest low over a specified period, indicating the strength of a trend.
Strategy Conditions
Long Entry Conditions:
Aroon Up crosses above Aroon Down (indicating a bullish trend).
The Zig Zag indicator shows an upward movement (indicating a potential continuation).
Short Entry Conditions:
Aroon Down crosses above Aroon Up (indicating a bearish trend).
The Zig Zag indicator shows a downward movement (indicating a potential continuation).
Exit Conditions:
Exit long when Aroon Down crosses above Aroon Up.
Exit short when Aroon Up crosses above Aroon Down.
SLYY BTC Strategy – Dynamische Trend- und Volatilitätsbasierte Die SLYY BTC Strategy ist eine speziell entwickelte Strategie für den BTC-Handel, die durch eine Kombination von gleitenden Durchschnitten und einem ATR-basierten Filter besonders stabile Ein- und Ausstiege ermöglicht. Der Algorithmus nutzt den 111er und 350er gleitenden Durchschnitt, um grundlegende Marktrichtungen zu erkennen und Entry-Trigger zu setzen. Zusätzlich stellt der ATR-Indikator (Average True Range) sicher, dass Trades nur bei optimaler Marktvolatilität ausgeführt werden, wodurch unnötige Risiken minimiert werden.
Funktionen der Strategie:
• Dynamischer Stop-Loss: Der Stop-Loss passt sich automatisch an die aktuelle Volatilität an und wird auf Basis eines variablen ATR-Multiplikators gesetzt, sodass er in volatilen Phasen breiter und in stabilen Phasen enger ist.
• Flexibler Trade-Einstieg: Die Strategie erkennt Long- und Short-Signale basierend auf den gleitenden Durchschnitten und eröffnet Positionen nur, wenn der ATR unter einem definierten Schwellenwert liegt.
• Zuverlässiges Risikomanagement: Die Stop-Loss-Abstände basieren auf einem fixen prozentualen Offset, der in den Strategieeinstellungen angepasst werden kann, um den persönlichen Risikopräferenzen zu entsprechen.
Einsatzgebiet:
Diese Strategie ist für Trader geeignet, die BTC auf mittleren Zeitrahmen handeln und ein risikokontrolliertes System mit dynamischem Volatilitätsmanagement bevorzugen. Die Slice PTC Strategy bietet eine klare, algorithmische Lösung für den Handel in Trendphasen und stabilisiert die Performance durch eine intelligente Volatilitätssteuerung.
Enhanced 1-Hour Strategy for Maximized ReturnsEnhanced 1-Hour Strategy for Maximized Returns
Overview
This is a trend-following and volatility-based breakout strategy designed for trading on the one-hour timeframe. It combines moving average crossovers, RSI for momentum, and Bollinger Bands as a volatility filter to confirm entries and exits. With a focus on maximizing returns, this strategy is tuned to work with leveraged trading and dynamically allocates position sizes based on available equity.
How the Strategy Works
Trend Detection: The strategy uses two moving averages—a short-term and a long-term—to detect trends.
A crossover of the short moving average above the long moving average indicates a potential upward trend.
Conversely, a crossover of the short moving average below the long moving average suggests a downward trend.
Momentum Confirmation with RSI: To avoid entering trades in low-momentum conditions, the strategy employs the Relative Strength Index (RSI).
A long (buy) trade is considered only when RSI is above a set threshold, indicating upward momentum.
A short (sell) trade is considered only when RSI is below a set threshold, indicating downward momentum.
Volatility Filter with Bollinger Bands: Bollinger Bands act as a filter to ensure the strategy enters trades only during periods of higher volatility.
For a long trade, the price must be above the lower Bollinger Band.
For a short trade, the price must be below the upper Bollinger Band.
ATR-Based Stop-Loss and Take-Profit: The strategy uses the Average True Range (ATR) to set stop-loss and take-profit levels dynamically based on market volatility.
The stop-loss level is set at a certain multiplier of the ATR below (for long trades) or above (for short trades) the entry price.
The take-profit level is set at a larger ATR multiplier, allowing the strategy to capture larger movements.
Position Sizing with Leverage: The position size is calculated as a percentage of equity, leveraging it to maximize returns as the account balance grows.
Key Variables and Adjustable Parameters
Here are the adjustable inputs in the strategy, allowing traders to tailor it to their preferences:
Moving Averages:
Short MA Length (shortMaLength): Length of the short-term moving average (default: 14).
Long MA Length (longMaLength): Length of the long-term moving average (default: 50).
These lengths can be adjusted to make the moving average crossovers more or less sensitive.
RSI Settings:
RSI Length (rsiLength): Length of the RSI calculation (default: 14).
RSI Upper Threshold (rsiUpperThreshold): Minimum RSI value required for long trades (default: 60).
RSI Lower Threshold (rsiLowerThreshold): Maximum RSI value allowed for short trades (default: 40).
Adjusting these thresholds can help control the momentum conditions required for trades.
ATR Multipliers for Stop-Loss and Take-Profit:
ATR Stop-Loss Multiplier (atrMultiplierStopLoss): Multiplier for the ATR to set the stop-loss level (default: 1.5).
ATR Take-Profit Multiplier (atrMultiplierTakeProfit): Multiplier for the ATR to set the take-profit level (default: 3.0).
Tuning these multipliers can help in balancing risk and reward, depending on market volatility.
Bollinger Bands Settings:
Deviation (dev): The standard deviation multiplier for Bollinger Bands (default: 2).
Bollinger Bands provide a volatility filter, and this multiplier affects the width of the bands.
Position Sizing and Leverage:
Leverage (leverage): The leverage applied to the position (default: 10).
Allocation Percent (allocationPercent): The percentage of equity allocated to each trade (default: 0.1 or 10%).
Adjusting these settings can increase or decrease the position size relative to your equity, helping control risk exposure.
EJL FMEAX with Trend Change Detection & Fibonacci This is a sophisticated trading indicator designed to help traders identify key trend reversals and price levels. The indicator combines the power of Fibonacci retracement levels with advanced trend change detection algorithms to provide actionable insights into market trends.
Trend Change Detection: Automatically identifies shifts in market momentum, highlighting potential trend reversals for better timing of entries and exits.
Fibonacci Support & Resistance: Uses Fibonacci levels to mark critical price zones where the market is likely to retrace or find support/resistance, enhancing decision-making for both trend-following and reversal strategies.
This tool is ideal for traders looking to capitalize on market fluctuations by pinpointing precise entry and exit points based on trend shifts and Fibonacci key levels.
Double Bottom Breakout Strategy with Partial Take ProfitsThis strategy is a Double Bottom Breakout Strategy with Partial Take Profits designed to identify breakout opportunities on BTC using the 15-minute, 30-minute, and 1-hour time frames. It leverages the double bottom pattern to trigger entries and uses a multi-target exit strategy to manage trades.
Key features of this strategy include:
Identification of the double bottom pattern using price action and lows.
Calculation of a neckline level, which acts as a breakout trigger.
Multiple take profit targets (target1, target2, target3) based on the neckline and the low of the first bottom.
Stop loss set based on a retracement level, ensuring risk management is in place.
This strategy is ideal for BTC traders looking to take advantage of short-term reversals and breakouts with a structured approach to managing both entry and exit points.
USE: BTC 15MIN/30MIN/1H
----------------------------------------------
该策略是一种具有部分获利的双底突破策略,旨在利用15分钟、30分钟和1小时的时间框架识别BTC上的突破机会。它利用双底模式来触发进入,并使用多目标退出策略来管理交易。
该战略的主要特征包括:
使用价格走势和低点识别双底模式。
计算领口水平,作为突破触发器。
基于领口和第一个底部的低点的多个止盈目标(目标1、目标2、目标3)。
根据回撤水平设置停止损失,确保风险管理到位。
对于希望利用短期逆转和突破的BTC交易员来说,该策略非常理想,并采用结构化的方法来管理进入点和退出点。
Strategy without indicators v11. General Script Strategy
The objective of this strategy is to open buy or sell orders every new hour based on:
Whether the previous candle closed high (buy) or low (sell).
The presence of tops and bottoms to avoid opening orders at times of possible reversals.
The strategy also allows the user to set a date range (start date and end date) to calculate profit, loss, percentage of gain and percentage of loss only in that period.
2. Initial Settings and Parameters
Start Date and End Date: The start_date and end_date variables define the date range to account for profits and losses. These dates can be adjusted by the user to view results in specific periods.
3. Conditions for Order Entry
At each time change, the script checks the conditions for buying or selling, using the following variables and logic:
Detection of Bullish or Bearish Candle:
bullish_candle: True if the previous candle closed high.
bearish_candle: True if the previous candle closed lower.
Analysis of Tops and Bottoms:
To avoid opening orders close to tops and bottoms, the script uses the function find_top_and_bottom(period), which analyzes the last 500 candles and identifies the highest value (top) and the lowest value (bottom).
The variables current_top and current_bottom store these values.
next_top and next_bottom indicate whether the current candle is close to a top (prevents buying) or a bottom (prevents selling).
4. Opening Orders (Buy and Sell)
At each time change, the script checks the conditions to open buy or sell orders:
Condition for Sell:
The sell order is opened if the previous candle was bullish (bullish_candle) and is not close to a top (not next_top).
If there is an open buy order, it is closed before the new sell order.
Buy Condition:
The buy order is opened if the previous candle was bearish (bearish_candle) and is not near a bottom (not_near_bottom).
If there is an open sell order, it is closed before the new buy order.
5. Calculating Profit and Loss
The profit and loss calculation is only done within the configured date range (start_date and end_date):
Profit and Loss:
total_profit and total_loss accumulate the profit and loss values of all operations during the defined period.
percentage_gain and percentage_loss calculate the percentage of gain and loss in relation to the initial capital.
6. Displaying Results on the Chart
The script displays on the chart, next to the candles, the information on Total Profit, Total Loss, % Gain and % Loss:
Strategy Summary
Setting the Date Range: Allows you to set the period for calculating profit and loss.
Previous Candlestick Analysis: Decide whether to buy or sell based on the previous candlestick.
Preventing Entries at Tops and Bottoms: Avoids buying at tops and selling at bottoms to reduce false signals.
Result Calculation: Accumulates profits, losses and percentages within the configured date range.
Results Display on Chart: Displays the configured statistics directly on the chart, next to the candlesticks.
1. Estratégia Geral do Script
O objetivo dessa estratégia é abrir ordens de compra ou venda a cada nova hora com base em:
Se a vela anterior fechou em alta (compra) ou em baixa (venda).
A presença de topos e fundos para evitar abrir ordens em momentos de possíveis reversões.
A estratégia também permite que o usuário configure um intervalo de datas (data inicial e data final) para calcular o lucro, perda, percentual de ganho e percentual de perda apenas nesse período.
2. Configurações e Parâmetros Iniciais
Data Inicial e Data Final: As variáveis data_inicial e data_final definem o intervalo de datas para contabilizar os lucros e perdas. Essas datas podem ser ajustadas pelo usuário para visualizar resultados em períodos específicos.
3. Condições para Entrada de Ordens
A cada mudança de hora, o script verifica as condições de compra ou venda, usando as seguintes variáveis e lógicas:
Detecção de Vela de Alta ou Baixa:
vela_de_alta: Verdadeiro se a vela anterior fechou em alta.
vela_de_baixa: Verdadeiro se a vela anterior fechou em baixa.
Análise de Topos e Fundos:
Para evitar abrir ordens próximas de topos e fundos, o script utiliza a função find_top_and_bottom(periodo), que analisa as últimas 500 velas e identifica o valor mais alto (topo) e o valor mais baixo (fundo).
As variáveis topo_atual e fundo_atual armazenam esses valores.
topo_proximo e fundo_proximo indicam se a vela atual está perto de um topo (evita compra) ou de um fundo (evita venda).
4. Abertura de Ordens (Compra e Venda)
A cada mudança de hora, o script verifica as condições para abrir ordens de compra ou venda:
Condição para Venda:
A ordem de venda é aberta se a vela anterior foi de alta (vela_de_alta) e não está perto de um topo (not topo_proximo).
Se houver uma ordem de compra aberta, ela é fechada antes da nova ordem de venda.
Condição para Compra:
A ordem de compra é aberta se a vela anterior foi de baixa (vela_de_baixa) e não está perto de um fundo (not fundo_proximo).
Se houver uma ordem de venda aberta, ela é fechada antes da nova ordem de compra.
5. Cálculo de Lucros e Perdas
O cálculo de lucro e perda só é feito dentro do intervalo de datas configurado (data_inicial e data_final):
Lucro e Perda:
lucro_total e perca_total acumulam os valores de lucro e perda de todas as operações durante o período definido.
percentual_ganho e percentual_perca calculam o percentual de ganho e perda em relação ao capital inicial.
6. Exibição dos Resultados no Gráfico
O script exibe no gráfico, próximo das velas, as informações de Lucro Total, Perda Total, % de Ganho e % de Perda:
Resumo da Estratégia
Configuração de Intervalo de Datas: Permite configurar o período para cálculo do lucro e da perda.
Análise de Vela Anterior: Decide se a ordem é de compra ou venda com base na vela anterior.
Prevenção de Entradas em Topos e Fundos: Evita compras em topos e vendas em fundos para reduzir sinais falsos.
Cálculo de Resultados: Acumula lucros, perdas e percentuais dentro do período de datas configurado.
Exibição dos Resultados no Gráfico: Exibe as estatísticas configuradas diretamente no gráfico, próximo das velas.
Long-Term Pivot and Golden Crossover Strategy//@version=5
strategy("Long-Term Pivot and Golden Crossover Strategy", overlay=true)
// Input for moving averages
shortTerm = input.int(100, title="Short-term SMA Period") // 100-period SMA
longTerm = input.int(200, title="Long-term SMA Period") // 200-period SMA
// Calculate moving averages
sma100 = ta.sma(close, shortTerm)
sma200 = ta.sma(close, longTerm)
// Golden crossover: when short-term SMA crosses above long-term SMA
goldenCrossover = ta.crossover(sma100, sma200)
// Calculate daily pivot points (traditional formula)
pivot = (high + low + close) / 3
support1 = pivot - (high - low)
resistance1 = pivot + (high - low)
support2 = pivot - 2 * (high - low)
resistance2 = pivot + 2 * (high - low)
// Plot SMAs and pivot points on the chart
plot(sma100, color=color.blue, title="100-period SMA", linewidth=2)
plot(sma200, color=color.red, title="200-period SMA", linewidth=2)
plot(pivot, color=color.purple, title="Pivot Point", linewidth=2)
plot(support1, color=color.green, title="Support 1", linewidth=1)
plot(resistance1, color=color.green, title="Resistance 1", linewidth=1)
plot(support2, color=color.green, title="Support 2", linewidth=1)
plot(resistance2, color=color.green, title="Resistance 2", linewidth=1)
// Entry Condition: Golden crossover with price above the pivot point
longCondition = goldenCrossover and close > pivot
// Exit Condition: You can use a stop-loss and take-profit, or a bearish crossover
stopLossPercent = input.float(3, title="Stop Loss (%)") / 100 // Wider stop loss for long-term trades
takeProfitPercent = input.float(10, title="Take Profit (%)") / 100 // Higher take profit for long-term trades
// Calculate stop-loss and take-profit prices
longStopLoss = close * (1 - stopLossPercent)
longTakeProfit = close * (1 + takeProfitPercent)
// Execute strategy
if (longCondition)
strategy.entry("Long", strategy.long, stop=longStopLoss, limit=longTakeProfit)
// Optional: Exit strategy based on a bearish crossover
exitCondition = ta.crossunder(sma100, sma200)
if (exitCondition)
strategy.close("Long")
// Strategy exit with custom stop loss and take profit
strategy.exit("Take Profit/Stop Loss", from_entry="Long", stop=longStopLoss, limit=longTakeProfit)
52-Week Low Buy-High Sell StrategyThis strategy can be used to test how much profit you would make on a script if you invest at 52 Week Low and Sell at 52 week high previous to the 52 week low.