RSI50此策略的逻辑是:
1.将RSI周期调整为750.
2.增加一条ma均线,这条ma线是将rsi线进行sma计算 ,并且设置sma周期为15
3.ma均线上穿rsi=50 线,做多
ma均线下穿rsi= 50 线,做空
ma均线上穿rsi=52线,平多
ma均线下穿rsi=48线,平空
此策略暂时适用于btcusdt 15min
The logic of this strategy is as follows:
1. Set the RSI period to 750.
2. Add a moving average (MA) line, which is the simple moving average (SMA) of the RSI line, with a SMA period of 15.
3.Enter a long position when the MA line crosses above the RSI = 50 line.
Enter a short position when the MA line crosses below the RSI = 50 line.
Close the long position when the MA line crosses above the RSI = 52 line.
Close the short position when the MA line crosses below the RSI = 48 line.
this strategy is applied to BTCUSDT on the 15-minute chart.
Скользящие средние
Color based on 20 Day SMA and mvwapColors price based on where it is compared to 20 day SMA and mvwap.
SMA is anchored to the daily timeframe so that it remains constant even in lower timeframes
SUPRA BERSERKER CAPITAL CA & NFLEste indicador combina herramientas técnicas avanzadas para identificar tendencias clave, niveles dinámicos de soporte y resistencia, así como oportunidades de trading basadas en acción del precio. Diseñado para traders que buscan precisión en su análisis, incluye las siguientes características:
1. Medias Móviles Exponenciales (EMAs):
Dos EMAs ajustables (100 y 200 períodos) para identificar la dirección principal de la tendencia.
Configuraciones personalizables de color y fuente para adaptarse a tus necesidades.
2. VWMA (Media Ponderada por Volumen):
Una VWMA de 250 períodos que actúa como indicador principal para determinar la dirección general del mercado, ponderando el volumen de cada vela para una visión más precisa.
Opciones de desplazamiento y ajustes de color para una mejor visualización en el gráfico.
3. Filtro Gaussiano y GMA (Gaussian Moving Average):
Un filtro Gaussiano avanzado que suaviza los datos de precios para destacar la tendencia predominante.
La media móvil Gaussiana cambia de color según la relación entre el precio de cierre y su valor, proporcionando una guía visual clara de la dirección del mercado.
Incluye límites superiores e inferiores basados en el ATR para identificar zonas de alta volatilidad.
Beneficios clave para la estrategia:
Identificación de Soportes Técnicos: Utiliza la combinación de EMAs y VWMA para detectar áreas de interés crítico donde podrían darse rebotes o rupturas.
Confirmación de Volumen y Dirección: La VWMA junto con el filtro Gaussiano validan la fortaleza de una tendencia y ayudan a identificar si el volumen está alineado con el movimiento.
Análisis Visual Intuitivo: Cambios de color en el filtro Gaussiano y límites de volatilidad facilitan decisiones rápidas y fundamentadas.
Este indicador es ideal para estrategias intradiarias o de swing trading en índices como el US30 o el S&P 500, alineado con nuestra filosofía de análisis técnico en Berserker Capital. ¡Optimízalo según tu estilo y comparte tus resultados con la comunidad!
EMA Crossover Signal CROSSMARKET9+21 EMA crossover signal. Needs refinement but effective for scalps.
QQE Strategy with Risk ManagementThis Pine Script is designed to transform Kıvanç Özbilgiç’s QQE indicator into a complete trading strategy. The script uses the QQE indicator to generate buy and sell signals, while integrating robust risk management mechanisms.
Key Features of the Strategy:
1. QQE Indicator-Based Signals:
• Buy (Long): Triggered when the fast QQE line (QQEF) crosses above the slow QQE line (QQES).
• Sell (Short): Triggered when the fast QQE line (QQEF) crosses below the slow QQE line (QQES).
2. Risk Management:
• ATR-Based Stop-Loss and Take-Profit: Dynamically calculated levels to limit losses and maximize profits.
• Trailing Stop: Adjusts stop-loss levels as the position moves into profit, ensuring gains are protected.
• Position Sizing: Automatically calculates position size based on a percentage of account equity.
3. Additions:
• The script enhances the indicator by introducing position entry/exit logic, risk management tools, and ATR-based calculations, making it a comprehensive trading strategy.
This strategy provides a robust framework for leveraging the QQE indicator in automated trading, ensuring effective trend detection and risk control.
EMA: f(x) - f'(x) - f''(x)Computes EMA for the given input period.
Also computes, the first and the second order derivative of that EMA.
ema,atr and with Bollinger Bands (Indicator)1. Indicator Overview
The indicator:
Displays EMA and Bollinger Bands on the chart.
Tracks price behavior during a user-defined trading session.
Generates long/short signals based on crossover conditions of EMA or Bollinger Bands.
Provides alerts for potential entries and exits.
Visualizes tracked open and close prices to help traders interpret market conditions.
2. Key Features
Inputs
session_start and session_end: Define the active trading session using timestamps.
E.g., 17:00:00 (5:00 PM) for session start and 15:40:00 (3:40 PM) for session end.
atr_length: The lookback period for the Average True Range (ATR), used for price movement scaling.
bb_length and bb_mult: Control the Bollinger Bands' calculation, allowing customization of sensitivity.
EMA Calculation
A 21-period EMA is calculated using:
pinescript
Copy code
ema21 = ta.ema(close, 21)
Purpose: Acts as a dynamic support/resistance level. Price crossing above or below the EMA indicates potential trend changes.
Bollinger Bands
Purpose: Measure volatility and identify overbought/oversold conditions.
Formula:
Basis: Simple Moving Average (SMA) of closing prices.
Upper Band: Basis + (Standard Deviation × Multiplier).
Lower Band: Basis - (Standard Deviation × Multiplier).
Code snippet:
pinescript
Copy code
bb_basis = ta.sma(close, bb_length)
bb_dev = bb_mult * ta.stdev(close, bb_length)
bb_upper = bb_basis + bb_dev
bb_lower = bb_basis - bb_dev
Session Tracking
The in_session variable ensures trading signals are only generated within the defined session:
pinescript
Copy code
in_session = time >= session_start and time <= session_end
3. Entry Conditions
EMA Crossover
Long Signal: When the price crosses above the EMA during the session:
pinescript
Copy code
ema_long_entry_condition = ta.crossover(close, ema21) and in_session and barstate.isconfirmed
Short Signal: When the price crosses below the EMA during the session:
pinescript
Copy code
ema_short_entry_condition = ta.crossunder(close, ema21) and in_session and barstate.isconfirmed
Bollinger Bands Crossover
Long Signal: When the price crosses above the upper Bollinger Band:
pinescript
Copy code
bb_long_entry_condition = ta.crossover(close, bb_upper) and in_session and barstate.isconfirmed
Short Signal: When the price crosses below the lower Bollinger Band:
pinescript
Copy code
bb_short_entry_condition = ta.crossunder(close, bb_lower) and in_session and barstate.isconfirmed
4. Tracked Prices
The script keeps track of key open/close prices using the following logic:
If a long signal is detected and the close is above the open, it tracks the open price.
If the close is below the open, it tracks the close price.
Tracked values are scaled using *4 (custom scaling logic).
These tracked prices are plotted for visual feedback:
pinescript
Copy code
plot(tracked_open, color=color.red, title="Tracked Open Price", linewidth=2)
plot(tracked_close, color=color.green, title="Tracked Close Price", linewidth=2)
5. Exit Conditions
Long Exit: When the price drops below the tracked open and close price:
pinescript
Copy code
exit_long_condition = (close < open) and (tracked_close < tracked_open) and barstate.isconfirmed
Short Exit: When the price rises above the tracked open and close price:
pinescript
Copy code
exit_short_condition = (close > open) and (tracked_close > tracked_open) and barstate.isconfirmed
6. Visualization
Plots:
21 EMA, Bollinger Bands (Basis, Upper, Lower).
Tracked open/close prices for additional context.
Background Colors:
Green for long signals, red for short signals (e.g., ema_long_entry_condition triggers a green background).
7. Alerts
The script defines alerts to notify the user about key events:
Entry Alerts:
pinescript
Copy code
alertcondition(ema_long_entry_condition, title="EMA Long Entry", message="EMA Long Entry")
alertcondition(bb_long_entry_condition, title="BB Long Entry", message="BB Long Entry")
Exit Alerts:
pinescript
Copy code
alertcondition(exit_long_condition, title="Exit Long", message="Exit Long")
8. Purpose
Trend Following: EMA crossovers help identify trend changes.
Volatility Breakouts: Bollinger Band crossovers highlight overbought/oversold regions.
Custom Sessions: Trading activity is restricted to specific time periods for precision.
Trend Follow DailyHello,
here's a simple trend following system using D timeframe.
we buy at the close when:
market is been raising for 2 days in a row, current close is higher than previous close, current low is higher than previous low, current close is higher than previous close and the current close is above 21-period simple moving average.
we sell at the close when:
current close is higher than previous day's high.
Strategy works best on stock indices due to the long-term upward drift.
Commission is set to $2.5 per side and slippage is set to 1 tick.
You can adjust commission for your instrument, as well play around with the moving average period.
Moving average is there to simply avoid periods when market is the selloff state.
“MACD + EMA9 + Stop/TP (5 candles) - 3H” (Risk Multiplier = 3,5)Resumo:
Esta estratégia combina um sinal de MACD (cruzamento de DIF e DEA) com o cruzamento do preço pela EMA de 9 períodos. Além disso, utiliza Stop Loss baseado no menor ou maior preço dos últimos 5 candles (lookback) e um Take Profit de 3,5 vezes o risco calculado. Foi otimizada e obteve bons resultados no time frame de 3 horas, apresentando uma taxa de retorno superior a 2,19 em backtests.
Lógica de Entrada
1. Compra (Buy)
• Ocorre quando:
• O close cruza a EMA9 de baixo para cima (crossover).
• O MACD (DIF) cruza a linha de sinal (DEA) de baixo para cima (crossover).
• Ao detectar esse sinal de compra, a estratégia abre uma posição comprada (long) e fecha qualquer posição vendida anterior.
2. Venda (Sell)
• Ocorre quando:
• O close cruza a EMA9 de cima para baixo (crossunder).
• O MACD (DIF) cruza a linha de sinal (DEA) de cima para baixo (crossunder).
• Ao detectar esse sinal de venda, a estratégia abre uma posição vendida (short) e fecha qualquer posição comprada anterior.
Stop Loss e Take Profit
• Stop Loss:
• Compra (long): Stop fica abaixo do menor preço (low) dos últimos 5 candles.
• Venda (short): Stop fica acima do maior preço (high) dos últimos 5 candles.
• Take Profit:
• Utiliza um Fator de Risco de 3,5 vezes a distância do preço de entrada até o stop.
• Exemplo (compra):
• Risco = (Preço de Entrada) – (Stop Loss)
• TP = (Preço de Entrada) + (3,5 × Risco)
Parâmetros Principais
• Gráfico: 3 horas (3H)
• EMA9: Período de 9
• MACD: Padrão (12, 26, 9)
• Stop Loss (lookback): Maior ou menor preço dos últimos 5 candles
• Fator de TP (Risk Multiplier): 3,5 × risco
Observações
• Os resultados (taxa de retorno superior a 2,19) foram observados no histórico, com backtest no time frame de 3H.
• Sempre teste em conta demo ou com testes adicionais antes de usar em conta real, pois condições de mercado podem variar.
• Os parâmetros (EMA, MACD, lookback de 5 candles e fator de risco 3,5) podem ser ajustados de acordo com a volatilidade do ativo e o perfil de risco do trader.
Importante: Nenhum setup garante resultados futuros. Essa descrição serve como referência técnica, e cada investidor/trader deve avaliar a estratégia em conjunto com outras análises e com um gerenciamento de risco adequado.
Combined Indicator with Signals, MACD, RSI, and EMA200Este indicador combina múltiples herramientas técnicas en un solo script, proporcionando un enfoque integral para la toma de decisiones en trading. A continuación, se analiza cada componente y su funcionalidad, así como las fortalezas y áreas de mejora.
Componentes principales
Medias Móviles (MA7, MA20, EMA200):
MA7 y MA20: Son medias móviles simples (SMA) que identifican señales a corto plazo basadas en sus cruces. Estos cruces (hacia arriba o hacia abajo) son fundamentales para las señales de compra o venta.
EMA200: Actúa como un filtro de tendencia general. Aunque su presencia es visualmente informativa, no afecta directamente las señales en este script.
Estas medias móviles son útiles para identificar tendencias a corto y largo plazo.
MACD (Moving Average Convergence Divergence):
Calculado usando las longitudes de entrada (12, 26, y 9 por defecto).
Se trazan dos líneas: la línea MACD (verde) y la línea de señal (naranja). Los cruces entre estas líneas determinan la fuerza de las señales de compra o venta.
Su enfoque está en medir el momento del mercado, especialmente en combinación con los cruces de medias móviles.
RSI (Relative Strength Index):
Calculado con un período estándar de 14.
Se utiliza para identificar condiciones de sobrecompra (>70) y sobreventa (<30).
Además de ser trazado como una línea, el fondo del gráfico se sombrea con colores rojo o verde dependiendo de si el RSI está en zonas extremas, lo que facilita la interpretación visual.
Señales de Compra y Venta:
Una señal de compra ocurre cuando:
La MA7 cruza hacia arriba la MA20.
La línea MACD cruza hacia arriba la línea de señal.
El RSI está en una zona de sobreventa (<30).
Una señal de venta ocurre cuando:
La MA7 cruza hacia abajo la MA20.
La línea MACD cruza hacia abajo la línea de señal.
El RSI está en una zona de sobrecompra (>70).
Las señales se representan con triángulos verdes (compra) y rojos (venta), claramente visibles en el gráfico.
Super Investor Club SMA RSI Trailing Stop for SPXOptimized for SPX, credit goes to Sean Seah Weiming
Key Features
Inputs:
smaLength: Length of the SMA (200 by default).
rsiLength: Length of the RSI calculation (14 by default).
rsiThreshold: RSI value below which entries are considered (40 by default).
trailStopPercent: Trailing stop loss percentage (5% by default).
waitingPeriod: The number of days to wait after an exit before entering again (10 days by default).
200 SMA and RSI Calculation:
Calculates the 200-period SMA of the closing price.
Computes the RSI using the given rsiLength.
Conditions for Entry:
A "buy" signal is triggered when:
The closing price is above the 200 SMA.
The RSI is below the defined threshold.
The waiting period since the last exit has elapsed.
Trailing Stop Loss:
When in a long position, the trailing stop price is adjusted based on the highest price since entry and the specified percentage.
Exit Conditions:
A sell signal is triggered when:
The price falls below the trailing stop price.
The price falls below the 200 SMA.
Visualization:
The 200 SMA is plotted on the chart.
"BUY" and "SELL" signals are marked with green and red labels, respectively.
Moving Average Exponential050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505050505
EMA Crossover Signal CROSSMARKET9+21 EMA crossover signal. Needs refinement but effective for scalps.
Working - Liquididity Weighted Moving AverageI took the Indicator created by AlgoAlpha and essentially just turned it into a strategy. The Buy signal comes when the Fast Length crosses above the Slow Length and the Sell signal when they cross back.
I am looking for feedback from active traders on this strategy. So far, I have found that it is pretty reliable when trading Dogecoin using the 3 Hour interval. It's not reliable at all outside of this time interval. It is hit or miss when changing to other coins.
I am wondering if anyone has an idea of another indicator that will make the strategy more reliable. I am not keen on the Drawdown or Percent Profitable, but when I change the time duration on backtesting, as long as I am using Dogecoin on the 3 hour interval, the strategy appears to work.
SMA+BB+PSAR+GOLDEN AND DEATH CROSSSMA 5-8-13-21-34-55-89-144-233-377-610
BB 20-2
PSAR Parabolik SAR, alış satış analizini güçlendiren bir indikatördür. Bu gösterge temelde durdurma ve tersine çevirme sinyalleri için kullanılır. Teknik yatırımcılar trendleri ve geri dönüşleri tespit etmek için bu indikatörden faydalanır.
GOLDEN AND DEATH CROSS 50X200 KESİŞİMİ YADA NE İSTERSENİZ
Multi 7EMA With MJDescription: The Multi EMA Intraday Setup is a comprehensive indicator designed for intraday trading, combining multiple Exponential Moving Averages (EMAs) to identify market trends and support swift decision-making. By plotting EMAs of varying periods (5, 13, 21, 34, 50, 100, and 200), this setup gives traders a clear view of market momentum and potential entry or exit points. The indicator automatically adjusts to intraday price movements, providing valuable insights into trend strength and direction.
Features:
Multiple EMAs: The setup includes EMAs of various lengths (5, 13, 21, 34, 50, 100, and 200) for a broad analysis of short to long-term trends.
Trend Confirmation: The background color dynamically shifts to green (bullish) or red (bearish) based on the relative positioning of the EMAs.
Customizable Settings: Adjust the lengths of each EMA to tailor the indicator to your specific trading needs.
Intraday Focus: Optimized for intraday trading, the EMAs respond quickly to price changes and market shifts.
Visual Clarity: EMAs are displayed in distinct colors, making it easy to differentiate them on the chart.
How to Use:
Trend Identification: When the EMAs are aligned in a bullish order (shorter EMAs above longer EMAs), the background turns green, indicating a potential uptrend. A bearish alignment (shorter EMAs below longer EMAs) results in a red background, indicating a downtrend.
Bullish Confirmation: Look for the EMA5 to be above EMA13, EMA13 above EMA21, and so on. The stronger the alignment, the stronger the bullish signal.
Bearish Confirmation: Conversely, when all EMAs are aligned downward (EMA5 below EMA13, EMA13 below EMA21, etc.), it suggests a bearish trend.
Entry/Exit Signals: Use the alignment and crossovers of the EMAs to identify potential entry or exit points. The EMAs can help you decide when to enter or exit based on the market's trend direction.
EMA 50 200 BandThis indicator displays the Exponential Moving Averages (EMA) with periods of 50 and 200 and visually highlights the areas between the two lines. The color coding helps to quickly identify trends:
Green: EMA 50 is above EMA 200 (bullish signal).
Red: EMA 50 is below EMA 200 (bearish signal).
This tool is especially useful for trend analysis and can act as a filter for buy and sell signals. It is suitable for day trading or swing trading across various timeframes.
Color Bars based on 20SMA and mVWAPPrice is colored green when above 20SMA and mvwap and red below them
зохламарапролдлорпавапролдждлорипмасвчапролдждлорпавывапролдждлорпасвчвапролдждлорпмсчячспролдлорпавапролдзжхздлорпавапролджздлорпа
RSI ve EMA Tabanlı Alım-Satım StratejisiBu strateji, kısa vadeli ticaret yaparken güçlü trendleri takip etmeye ve riskleri en aza indirgemeye odaklanır. Strateji, aşağıdaki göstergelere dayanarak alım ve satım sinyalleri üretir:
Alım Sinyali:
EMA 50 değeri, EMA 200'ün üzerinde olmalı, yani trend yukarı yönlü olmalı.
MACD göstergesi sıfırın altında olmalı ve önceki değeri aşarak yükselmiş olmalı. Bu, güçlenen bir düşüş trendinden çıkıp yükselişe geçişi işaret eder.
Satım Sinyali:
RSI 14 göstergesi 70 seviyesini yukarıdan aşağıya kırarsa, aşırı alım durumunun sona erdiği ve fiyatın geri çekilebileceği sinyali verilir.
Stop Loss:
Eğer EMA 50 değeri, EMA 200'ün altına düşerse, strateji mevcut pozisyonu kapatarak zararı sınırlamayı hedefler.
Bu strateji, trend takibi yapan ve risk yönetimine önem veren yatırımcılar için tasarlanmıştır. Hem alım hem de satım koşulları, piyasa koşullarını dinamik bir şekilde analiz eder ve sadece trend yönündeki hareketlere odaklanır. RSI, MACD ve EMA göstergeleriyle desteklenen alım-satım sinyalleri, güçlü ve güvenilir bir ticaret stratejisi oluşturur.
Ekstra Notlar:
Strateji, trend yönünde işlem yaparak daha sağlam pozisyonlar almanızı sağlar.
Stop loss seviyeleri, güçlü trend dönüşleri durumunda korunmaya yardımcı olur.
Bu strateji özellikle yükseliş trendleri sırasında alım yapmayı tercih eder ve aşırı alım koşullarında satışı gerçekleştirir.
Volume Breakout_BreakdownHow It Works:
Buy Signals:
Triggered when:
Price is above the 9 and 20 EMAs (15-minute timeframe) and the 9 EMA (1-hour timeframe).
Price opens above the VWAP.
Volume exceeds 1.5x the 5-period average.
Price forms a bullish candlestick breakout (close > previous high).
Sell Signals:
Triggered when:
Price is below the 9 and 20 EMAs (15-minute timeframe) and the 9 EMA (1-hour timeframe).
Price opens below the VWAP.
Volume exceeds 1.5x the 5-period average.
Price forms a bearish candlestick breakdown (close < previous low).
ema 59 Giải thích mã:
Thêm biến buyLabel và sellLabel:
buyLabel và sellLabel được sử dụng để xác định khi nào label Buy hoặc Sell xuất hiện trên biểu đồ.
Cảnh báo khi label Buy xuất hiện:
Sử dụng alertcondition với điều kiện outsideBarCrossAbove để thông báo khi label Buy xuất hiện.
Cảnh báo khi label Sell xuất hiện:
Sử dụng alertcondition với điều kiện outsideBarCrossBelow để thông báo khi label Sell xuất hiện.
Thông báo chi tiết:
Thông báo sẽ hiển thị giá tại thời điểm label xuất hiện.
Ví dụ thông báo:
Khi label Buy xuất hiện: "Label Buy xuất hiện tại giá: 1.1050".
Khi label Sell xuất hiện: "Label Sell xuất hiện tại giá: 1.1000".
Lưu ý:
Đảm bảo rằng bạn đã bật cảnh báo trong TradingView để nhận thông báo khi label xuất hiện.
Kiểm tra kỹ lưỡng chiến lược trên dữ liệu lịch sử trước khi sử dụng trong giao dịch thực tế.
Nếu bạn muốn thông báo chi tiết hơn (ví dụ: thêm thông tin về số lượng hợp đồng hoặc vị thế), bạn có thể sử dụng alert trong strategy thay vì alertcondition. Tuy nhiên, alert chỉ hoạt động với strategy, không hoạt động với indicator.
image.png
PNG 11.25KB
Lỗi "Void expression cannot be assigned to a variable" xảy ra khi bạn cố gắng gán một biểu thức không trả về giá trị (void) vào một biến. Trong Pine Script, hàm plotshape không trả về giá trị nào, vì vậy bạn không thể gán nó vào một biến như buyLabel hoặc sellLabel.
Nguyên nhân:
Bạn đang cố gắng gán kết quả của plotshape vào biến buyLabel và sellLabel, nhưng plotshape không trả về giá trị.
Cách sửa lỗi:
Bạn không cần gán plotshape vào biến. Thay vào đó, bạn có thể sử dụng trực tiếp điều kiện outsideBarCrossAbove và outsideBarCrossBelow để tạo cảnh báo.
Dưới đây là đoạn mã đã được sửa:
pinescript
Copy
//@version=5
strategy(title="Outside Bar EMA Crossover Strategy with EMA Shift", shorttitle="Outside Bar EMA Cross", overlay=true)
// Input for EMA lengths
lenEMA1 = input.int(5, title="EMA 5 Length")
lenEMA2 = input.int(9, title="EMA 9 Length")
// Input for EMA 9 shift
emaShift = input.int(1, title="EMA 9 Shift", minval=0)
// Calculate EMAs
ema1 = ta.ema(close, lenEMA1)
ema2 = ta.ema(close, lenEMA2)
// Apply shift to EMA 9
ema2Shifted = na(ema2 ) ? na : ema2 // Dịch chuyển EMA 9 bằng cách sử dụng offset
// Plot EMAs
plot(ema1, title="EMA 5", color=color.blue, linewidth=2)
plot(ema2Shifted, title="EMA 9 Shifted", color=color.red, linewidth=2)
// Outside Bar condition
outsideBar() => high > high and low < low
// Cross above EMA 5 and EMA 9 (shifted)
crossAboveEMA = close > ema1 and close > ema2Shifted
// Cross below EMA 5 and EMA 9 (shifted)
crossBelowEMA = close < ema1 and close < ema2Shifted
// Outside Bar cross above EMA 5 and EMA 9 (shifted)
outsideBarCrossAbove = outsideBar() and crossAboveEMA
// Outside Bar cross below EMA 5 and EMA 9 (shifted)
outsideBarCrossBelow = outsideBar() and crossBelowEMA
// Plot shapes for visual signals
plotshape(series=outsideBarCrossAbove, title="Outside Bar Cross Above", location=location.belowbar, color=color.green, style=shape.labelup, text="Buy", textcolor=color.white)
plotshape(series=outsideBarCrossBelow, title="Outside Bar Cross Below", location=location.abovebar, color=color.red, style=shape.labeldown, text="Sell", textcolor=color.white)
// Calculate Outside Bar height
outsideBarHeight = high - low // Chiều cao của nến Outside Bar
// Calculate TP and SL levels
tpRatio = 0.5 // TP = 50% chiều cao nến Outside Bar
slRatio = 1.0 // SL = 100% chiều cao nến Outside Bar
tpLevelLong = close + outsideBarHeight * tpRatio // TP cho lệnh mua
slLevelLong = close - outsideBarHeight * slRatio // SL cho lệnh mua
tpLevelShort = close - outsideBarHeight * tpRatio // TP cho lệnh bán
slLevelShort = close + outsideBarHeight * slRatio // SL cho lệnh bán
// Strategy logic
if (outsideBarCrossAbove)
strategy.entry("Buy", strategy.long)
strategy.exit("Take Profit/Stop Loss", "Buy", stop=slLevelLong, limit=tpLevelLong) // Thêm TP và SL
if (outsideBarCrossBelow)
strategy.entry("Sell", strategy.short)
strategy.exit("Take Profit/Stop Loss", "Sell", stop=slLevelShort, limit=tpLevelShort) // Thêm TP và SL
// Logic: Nếu lệnh Buy bị Stop Loss => Vào lệnh Sell
if (strategy.position_size > 0 and close <= slLevelLong)
strategy.close("Buy")
strategy.entry("Sell After Buy SL", strategy.short)
// Logic: Nếu lệnh Sell bị Stop Loss => Vào lệnh Buy
if (strategy.position_size < 0 and close >= slLevelShort)
strategy.close("Sell")
strategy.entry("Buy After Sell SL", strategy.long)
// Cảnh báo khi label Buy xuất hiện
alertcondition(condition=outsideBarCrossAbove, title="Label Buy Xuất Hiện", message="Label Buy xuất hiện tại giá: {{close}}")
// Cảnh báo khi label Sell xuất hiện
alertcondition(condition=outsideBarCrossBelow, title="Label Sell Xuất Hiện", message="Label Sell xuất hiện tại giá: {{close}}")
Giải thích sửa lỗi:
Loại bỏ gán plotshape vào biến:
Bạn không cần gán plotshape vào biến buyLabel hoặc sellLabel. Thay vào đó, bạn có thể sử dụng trực tiếp điều kiện outsideBarCrossAbove và outsideBarCrossBelow để tạo cảnh báo.
Sử dụng alertcondition:
alertcondition được sử dụng để tạo cảnh báo khi điều kiện outsideBarCrossAbove hoặc outsideBarCrossBelow được đáp ứng.
Kết quả:
Khi label Buy xuất hiện, cảnh báo "Label Buy xuất hiện tại giá: X" sẽ được kích hoạt.
Khi label Sell xuất hiện, cảnh báo "Label Sell xuất hiện tại giá: X" sẽ được kích hoạt.
Lưu ý:
Đảm bảo rằng bạn đã bật cảnh báo trong TradingView để nhận thông báo khi label xuất hiện.
Kiểm tra kỹ lưỡng chiến lược trên dữ liệu lịch sử trước khi sử dụng trong giao dịch thực tế.
New chat
Adaptive Moving Averagewhat is the purpose of the indicator?
When short-length moving averages are used as trailing stops, they cause exiting the trade too early. Keeping the length value too high will result in exiting the transaction too late and losing most of the profits earned. I aimed to prevent this problem with this indicator.
what is "Adaptive Moving Average"?
it is a moving average that can change its length on each candle depending on the selected source.
what it does?
The indicator first finds the average lengths of the existing candles and defines different distances accordingly. When the moving average drawn by the indicator enters the area defined as "far" by the indicator, the indicator reduces the length of the moving average, preventing it from moving too far from the price, and continues to do so at different rates until the moving average gets close enough to the price. If the moving average gets close enough to the price, it starts to increase the length of the average and thus the adaptation continues.
how it does it?
Since the change of each trading pair is different in percentage terms, I chose to base the average height of the candles instead of using constant percentage values to define the concept of "far". While doing this, I used a weighted moving average so that the system could quickly adapt to the latest changes (you can see it on line 17). After calculating what percentage of the moving average this value is, I caused the length of the moving average to change in each bar depending on the multiples of this percentage value that the price moved away from the average (look at line 20, 21 and 22). Finally, I created a new moving average using this new length value I obtained.
how to use it?
Although the indicator chooses its own length, we have some inputs to customize it. First of all, we can choose which source we will use the moving average on. The "source" input allows us to use it with other indicators.
"max length" and "min length" determine the maximum and minimum value that the length of the moving average can take.
Apart from this, there are options for you to add a standard moving average to the chart so that you can compare the adaptive moving average, and bollinger band channels that you can use to create different strategies.
This indicator was developed due to the need for a more sophisticated trailing stop, but once you understand how it works, it is completely up to you to combine it with other indicators and create different strategies.