圖表形態
Fvg Setup Indcator For EducationThis indicator automatically detects Fair Value Gaps (FVG) and highlights strong, trend-aligned zones. It works especially well during Kill Zone sessions, providing a clear visualization of structural price gaps.
Key Features:
• EMA & SMA Filters to confirm trend direction
• ATR-Based Gap Measurement to identify strong FVGs
• Automatic TP & SL Calculations
Best Use Case:
• Ideal for spotting potential opportunities during Kill Zone sessions.
⚠️ Disclaimer:
This script is for educational purposes and should not be considered financial advice. Always conduct proper analysis and risk management when trading.
Stochastic+RSIThis script combines stochastic rsi and rsi with overbought and oversold bands for RSI to better vizualize potential pivot or reversals points.
It also scans for potential divergences and pivots marked by arrows on RSI and try to predict the next movements (not super accurate on price movement prediction but it is what it is)
Order Block Zones with Pin Bar & Engulfing SignalsThis strategy gives buy and sell signals based on a pin bar in the 1-minute timeframe, within supply and demand zones in the 15-minute timeframe.
Pi Cycle Bitcoin High/LowThe theory that a Pi Cycle Top might exist in the Bitcoin price action isn't new, but recently I found someone who had done the math on developing a Pi Cycle Low indicator, also using the crosses of moving averages.
The Pi Cycle Top uses the 2x350 Daily MA and the 111 Daily MA
The Pi Cycle Bottom uses the 0.745x471 Daily MA and the 150 Daily EMA
Note: a Signal of "top" doesn't necessarily mean "THE top" of a Bull Run - in 2013 there were two Top Signals, but in 2017 there was just one. There was one in 2021, however BTC rose again 6 months later to actually top at 69K, before the next Bear Market.
There is as much of a chance of two "bottom" indications occurring in a single bear market, as nearly happened in the Liquidity Crisis in March 2020.
On April 19 2024 (UTC) the Fourth Bitcoin Halving took place, as the 840,000th block was completed. It is currently estimated that the 5th halving will take place on March 26, 2028.
wuyx 59 imbGiải thích:
alertcondition: Hàm này được sử dụng để tạo các điều kiện cảnh báo trên TradingView. Khi điều kiện được đáp ứng, cảnh báo sẽ được kích hoạt.
breakFlyingCandleUp: Điều kiện phá vỡ nến bay tăng, xảy ra khi giá đóng cửa cao hơn high của nến bay trước đó.
breakFlyingCandleDown: Điều kiện phá vỡ nến bay giảm, xảy ra khi giá đóng cửa thấp hơn low của nến bay trước đó.
Cách sử dụng:
Khi bạn thêm các cảnh báo này vào script, bạn có thể thiết lập cảnh báo trên TradingView để nhận thông báo khi các điều kiện này được đáp ứng.
Bạn có thể tùy chỉnh thông báo cảnh báo để phù hợp với nhu cầu của mình.
Ví dụ hoàn chỉnh:
Dưới đây là đoạn mã hoàn chỉnh với các cảnh báo đã được thêm vào:
4th Day Performance After 3 Down DaysThis Pine Script indicator analyzes market performance on the 4th day following 3 consecutive down days. It identifies when the close price is lower than the open for three consecutive days and calculates the price change from the 3rd day's close to the 4th day's close.
Key features include:
Entry and Exit Tracking: The script records the entry price (3rd day's close) and the exit price (4th day's close).
Performance Metrics: The script calculates and displays:
Total Profit/Loss (PnL) over all trades.
Total number of trades.
Count of positive and negative 4th-day outcomes.
Customizable Start Date: The user can set a start date to analyze historical data.
Interactive Table: A table on the chart displays all key metrics for easy reference.
Use Case:
This script is useful for traders and analysts who want to study historical patterns and determine if the 4th day's performance presents opportunities following three consecutive down days. It helps identify potential reversal or continuation patterns in market behavior.
Disclaimer:
This script is for educational and research purposes only and should not be considered financial advice. Past performance does not guarantee future results. Always conduct thorough analysis and consult a professional before trading.
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.
Stochastic ala DayTradingRadioStochastic ala DayTradingRadio.
Created for those who have only pasic TW plan and can't add more than 2 indicators.
It's just plot 4 stoch data on one chart.
The Gold Box StrategySuggestions for Improving Entry and Exit Signals:
1. Filtering Signals with EMA Confluence:
Ensure that buy signals (bullish engulfing) are only triggered when the price is above the 20 EMA.
Ensure that sell signals (bearish engulfing) are only triggered when the price is below the 20 EMA.
This will reduce false signals and ensure trades are taken in the direction of the overall trend.
2. Round Number Levels Filtering:
You can add a condition to only allow entries when the price is near round numbers (e.g., within a certain dollar range from $5 intervals like 1775, 1780, etc.).
3. Session Filtering:
Ensure that trades are only taken during active trading sessions (London or New York) to avoid low-volatility periods where false signals are more likely.
Custom Time Candle LabelsHow It Works:
input.int fields allow you to set the hour and minute for both custom times from the indicator settings.
The script checks whether the current candle matches either of the input times.
Labels are plotted at the high of the candle for both custom times.
The label text dynamically displays the custom time you set.
Customization Options:
You can change the colors, label style, or label position as needed.
Would you like me to add any alerts or further features (e.g., showing labels at the low of the candle?
MOVING MODEMoving Mode indicator calculates and displays on the chart the mode (the most frequent value) of the closing prices of the last N bars (configurable). Unlike traditional moving averages, which can be distorted by extreme values, Moving Mode provides a more accurate representation of price behavior by reflecting the most common values.
This approach is based on the concept of "Moda Móvil" proposed by Pedro L. Asensio, who highlights that traditional moving averages can be misleading due to their sensitivity to extremes. The mode, on the other hand, offers a more realistic and market-adjusted alternative, unaffected by outliers.
I, Pedro L. Asensio, created the Moving Mode and Moda Móvil indicators in 2023
These indicators are free to use ;)
AI indicatorThis script is a trading indicator designed for future trading signals on the TradingView platform. It uses a combination of the Relative Strength Index (RSI) and a Simple Moving Average (SMA) to generate buy and sell signals. Here's a breakdown of its components and logic:
1. Inputs
The script includes configurable inputs to make it adaptable for different market conditions:
RSI Length: Determines the number of periods for calculating RSI. Default is 14.
RSI Overbought Level: Signals when RSI is above this level (default 70), indicating potential overbought conditions.
RSI Oversold Level: Signals when RSI is below this level (default 30), indicating potential oversold conditions.
Moving Average Length: Defines the SMA length used to confirm price trends (default 50).
2. Indicators Used
RSI (Relative Strength Index):
Measures the speed and change of price movements.
A value above 70 typically indicates overbought conditions.
A value below 30 typically indicates oversold conditions.
SMA (Simple Moving Average):
Used to smooth price data and identify trends.
Price above the SMA suggests an uptrend, while price below suggests a downtrend.
3. Buy and Sell Signal Logic
Buy Condition:
The RSI value is below the oversold level (e.g., 30), indicating the market might be undervalued.
The current price is above the SMA, confirming an uptrend.
Sell Condition:
The RSI value is above the overbought level (e.g., 70), indicating the market might be overvalued.
The current price is below the SMA, confirming a downtrend.
These conditions ensure that trades align with market trends, reducing false signals.
4. Visual Features
Buy Signals: Displayed as green labels (plotshape) below the price bars when the buy condition is met.
Sell Signals: Displayed as red labels (plotshape) above the price bars when the sell condition is met.
Moving Average Line: A blue line (plot) added to the chart to visualize the SMA trend.
5. How It Works
When the buy condition is true (RSI < 30 and price > SMA), a green label appears below the corresponding price bar.
When the sell condition is true (RSI > 70 and price < SMA), a red label appears above the corresponding price bar.
The blue SMA line helps to visualize the overall trend and acts as confirmation for signals.
6. Advantages
Combines Momentum and Trend Analysis:
RSI identifies overbought/oversold conditions.
SMA confirms whether the market is trending up or down.
Simple Yet Effective:
Reduces noise by using well-established indicators.
Easy to interpret for beginners and experienced traders alike.
Customizable:
Parameters like RSI length, oversold/overbought levels, and SMA length can be adjusted to fit different assets or timeframes.
7. Limitations
Lagging Indicator: SMA is a lagging indicator, so it may not capture rapid market reversals quickly.
Not Foolproof: No trading indicator can guarantee 100% accuracy. False signals can occur in choppy or sideways markets.
Needs Volume Confirmation: The script does not consider trading volume, which could enhance signal reliability.
8. How to Use It
Copy the script into TradingView's Pine Editor.
Save and add it to your chart.
Adjust the RSI and SMA parameters to suit your preferred asset and timeframe.
Look for buy signals (green labels) in uptrends and sell signals (red labels) in downtrends.
Optimized ICT Buy and Sell SignalsI understand that you're seeing too many signals, which can make the strategy seem cluttered or overly reactive. To **optimize the strategy** and reduce the frequency of buy and sell signals, we can add a few improvements:
### Optimization Approach:
1. **Increase Lookback Periods**: By increasing the lookback periods for **Market Structure**, **Order Blocks**, and **FVGs**, we can make the strategy less sensitive to every little fluctuation and focus more on stronger trend shifts.
2. **Trend Confirmation with EMA**: Use the **EMA 9** as a trend filter. Only generate signals when the price is above the **EMA 9** for bullish signals and below the **EMA 9** for bearish signals.
3. **Limit Signals to Stronger Price Action**: For example, we can reduce the number of signals by requiring price to be closer to significant **order blocks** or **FVGs**, or only trigger signals when there is a **break of structure** (BoS) and confirmation of a trend reversal.
---
### Optimized Code
```pinescript
//@version=5
indicator("Optimized ICT Buy and Sell Signals", overlay=true)
// --- Input Parameters ---
emaLength = input.int(9, title="EMA Length")
fvgLookback = input.int(10, title="Fair Value Gap Lookback Period")
orderBlockLookback = input.int(30, title="Order Block Lookback Period")
minGapSize = input.float(0.5, title="Min Gap Size (FVG)") // Minimum gap size for FVG detection
// --- EMA 9 (for trend direction) ---
ema9 = ta.ema(close, emaLength)
plot(ema9, title="EMA 9", color=color.blue, linewidth=2)
// --- Market Structure (ICT) ---
// Identify Higher Highs (HH) and Higher Lows (HL) for Bullish Market Structure
hhCondition = high > ta.highest(high, orderBlockLookback) // Higher High
hlCondition = low > ta.lowest(low, orderBlockLookback) // Higher Low
isBullishStructure = hhCondition and hlCondition // Bullish Market Structure condition
// Identify Lower Highs (LH) and Lower Lows (LL) for Bearish Market Structure
lhCondition = high < ta.highest(high, orderBlockLookback) // Lower High
llCondition = low < ta.lowest(low, orderBlockLookback) // Lower Low
isBearishStructure = lhCondition and llCondition // Bearish Market Structure condition
// --- Order Blocks (ICT) ---
// Bullish Order Block (consolidation before upmove)
var float bullishOrderBlock = na
if isBullishStructure
bullishOrderBlock := ta.valuewhen(low == ta.lowest(low, orderBlockLookback), low, 0)
// Bearish Order Block (consolidation before downmove)
var float bearishOrderBlock = na
if isBearishStructure
bearishOrderBlock := ta.valuewhen(high == ta.highest(high, orderBlockLookback), high, 0)
// --- Fair Value Gap (FVG) ---
// Bullish Fair Value Gap (FVG): Gap between a down-close followed by an up-close
fvgBullish = (low < high ) and (high - low > minGapSize) // Bullish FVG condition with gap size filter
// Bearish Fair Value Gap (FVG): Gap between an up-close followed by a down-close
fvgBearish = (high > low ) and (high - low > minGapSize) // Bearish FVG condition with gap size filter
// --- Entry Conditions ---
// Buy Condition: Bullish Market Structure and Price touching a Bullish Order Block or FVG, and above EMA
longCondition = isBullishStructure and (close <= bullishOrderBlock or fvgBullish) and close > ema9
// Sell Condition: Bearish Market Structure and Price touching a Bearish Order Block or FVG, and below EMA
shortCondition = isBearishStructure and (close >= bearishOrderBlock or fvgBearish) and close < ema9
// --- Plot Buy and Sell Signals on the Chart ---
plotshape(series=longCondition, location=location.belowbar, color=color.green, style=shape.labelup, title="Buy Signal", text="BUY", size=size.small)
plotshape(series=shortCondition, location=location.abovebar, color=color.red, style=shape.labeldown, title="Sell Signal", text="SELL", size=size.small)
// --- Highlight Order Blocks ---
plot(bullishOrderBlock, color=color.green, linewidth=1, title="Bullish Order Block", style=plot.style_circles)
plot(bearishOrderBlock, color=color.red, linewidth=1, title="Bearish Order Block", style=plot.style_circles)
// --- Highlight Fair Value Gaps (FVG) ---
bgcolor(fvgBullish ? color.new(color.green, 90) : na, title="Bullish FVG", transp=90)
bgcolor(fvgBearish ? color.new(color.red, 90) : na, title="Bearish FVG", transp=90)
// --- Alerts ---
// Alert for Buy Signals
alertcondition(longCondition, title="Long Signal", message="Optimized ICT Buy Signal: Bullish structure, price touching bullish order block or FVG, and above EMA.")
// Alert for Sell Signals
alertcondition(shortCondition, title="Short Signal", message="Optimized ICT Sell Signal: Bearish structure, price touching bearish order block or FVG, and below EMA.")
```
### Key Optimizations:
1. **Increased Lookback Periods**:
- The `orderBlockLookback` has been increased to **30**. This allows for a larger window for identifying **order blocks** and **market structure** changes, reducing sensitivity to small price fluctuations.
- The `fvgLookback` has been increased to **10** to ensure that only larger price gaps are considered.
2. **Min Gap Size for FVG**:
- A new input parameter `minGapSize` has been introduced to **filter out small Fair Value Gaps (FVGs)**. This ensures that only significant gaps trigger buy or sell signals. The default value is **0.5** (you can adjust it as needed).
3. **EMA Filter**:
- Added a trend filter using the **EMA 9**. **Buy signals** are only triggered when the price is **above the EMA 9** (indicating an uptrend), and **sell signals** are only triggered when the price is **below the EMA 9** (indicating a downtrend).
- This helps reduce noise by confirming that signals are aligned with the broader market trend.
### How to Use:
1. **Apply the script** to your chart and observe the reduced number of buy and sell signals.
2. **Buy signals** will appear when:
- The price is in a **bullish market structure**.
- The price is near a **bullish order block** or filling a **bullish FVG**.
- The price is **above the EMA 9** (confirming an uptrend).
3. **Sell signals** will appear when:
- The price is in a **bearish market structure**.
- The price is near a **bearish order block** or filling a **bearish FVG**.
- The price is **below the EMA 9** (confirming a downtrend).
### Further Fine-Tuning:
- **Adjust Lookback Periods**: If you still find the signals too frequent or too few, you can tweak the `orderBlockLookback` or `fvgLookback` values further. Increasing them will give more weight to the larger market structures, reducing noise.
- **Test Different Timeframes**: This optimized version is still suited for lower timeframes like 15-minutes or 5-minutes but will also work on higher timeframes (1-hour, 4-hour, etc.). Test across different timeframes for better results.
- **Min Gap Size**: If you notice that the FVG condition is too restrictive or too lenient, adjust the `minGapSize` parameter.
### Conclusion:
This version of the strategy should give you fewer, more meaningful signals by focusing on larger market movements and confirming the trend direction with the **EMA 9**. If you find that the signals are still too frequent, feel free to further increase the lookback periods or tweak the FVG gap size.
Accurate Buy/Sell Signals PingitIndikator yang Digunakan:
EMA: Untuk menentukan tren.
RSI: Untuk mendeteksi kondisi overbought/oversold.
MACD: Untuk mengonfirmasi momentum.
Sinyal Buy:
EMA jangka pendek (10) memotong ke atas EMA jangka panjang (50).
RSI berada di bawah level oversold (30).
MACD Line berada di atas Signal Line.
Sinyal Sell:
EMA jangka pendek memotong ke bawah EMA jangka panjang.
RSI berada di atas level overbought (70).
MACD Line berada di bawah Signal Line.
Harmonic Pattern with WPR Strategy This strategy uses Harmonic Patterns like Gartley, Bat, Crab and Butterfly along with William Percent Range to enter/exit trade
Works best on XAUUSD (specially on smaller time frames)
Can be used for scalping
Multi straddleA straddle with Bollinger Bands combines an options trading strategy and a technical indicator for better analysis.
The Bollinger Bands overlay the combined premium (call + put prices), providing insights into volatility.
This setup allows traders to monitor breakouts or contractions in the total premium, aiding in decision-making for entry, exit, or risk management.
Large Wick IndicatorThis is a wick indicator which shows you 3X wick more than a body so it gives you idea to trade in the right direction
Gold Trading SignalThis indicator is a trading strategy for Gold (XAU/USD) on TradingView, based on the crossover of two Exponential Moving Averages (EMA) and using Average True Range (ATR) to determine Stop Loss and Take Profit levels.
Key Features of the Indicator:
1. Buy and Sell Signals: The indicator generates buy and sell signals based on the crossover of the 9-period short EMA and the 21-period long EMA.
2. ATR Calculation: The ATR (14) is used to calculate Stop Loss and Take Profit levels, which helps in measuring market volatility.
3. Stop Loss and Take Profit Levels:
Stop Loss for Buy: The low of the previous candle minus ATR.
Stop Loss for Sell: The high of the previous candle plus ATR.
Take Profit for Buy: The closing price plus ATR multiplied by a factor.
Take Profit for Sell: The closing price minus ATR multiplied by a factor.
4. Chart Display: Buy signals are displayed as green arrows below bars, and sell signals are shown as red arrows above bars.
5. Alerts: Alerts are triggered when buy or sell signals are activated.
Strategy Objective:
This strategy is designed to identify entry and exit points using EMA crossovers and ATR, helping traders determine optimal Stop Loss and Take Profit levels.
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