Price Action + Support/Resistance with LabelsEntry Conditions:
Long Entry (BUY): Based on the bullish engulfing pattern and price being above the resistance level.
Short Entry (SELL): For demonstration, the short entry condition is set as price being below the support level and a bullish candle in the previous bar. You can modify this logic for your own use case.
Stop Loss and Take Profit:
Stoploss is plotted at the calculated stop loss level.
Target is plotted at the calculated take profit level.
Labels:
For long trades, labels are added with "BUY", "STOPLOSS", and "TARGET".
For short trades (if enabled), labels are added with "SELL", "STOPLOSS", and "TARGET".
Labels are placed using label.new at specific locations on the chart (above or below bars).
Alert Conditions:
Alerts are created for both long and short entry signals so you can get notified when the entry conditions are met.
How it works:
BUY label will appear below the bar when a long entry condition is met.
SELL label will appear above the bar when a short entry condition is met.
STOPLOSS and TARGET labels will appear at their respective levels when an entry signal is triggered.
The labels will appear on the chart to give you a clear visual cue of the entry, stop loss, and take profit levels.
How to Use:
Copy the script into your Pine Editor on TradingView and apply it to your chart.
Observe the labels that show up on the chart:
"BUY" will appear below the bar when long conditions are met.
"SELL" will appear above the bar when short conditions are met (if using short logic).
"STOPLOSS" will be plotted at the stop loss level.
"TARGET" will be plotted at the take profit level.
Optional Customization:
You can modify the short entry condition based on your preferred method.
You can adjust the length for the support/resistance calculation, the stopLossRR, and other parameters to fine-tune the strategy for Nifty 50 or any other asset.
Let me know if you have any further questions or need additional modifications!
Wyszukaj w skryptach "entry"
Perfect OrderEntry Point
How to Entry
Perfect Order Entry
SMA5,13,21 & EMA75,90,200
Please enjoy your entry
qudranEntry and Exit Logic – BUY, SELL, SHORT, COVER signals.
Filters – Trend confirmation, confirmation candle, one trade at a time.
Recommended Timeframes – M15, M30, or H1 for XAUUSD.
Entry Percent: EssamThis Pine Script code is designed to perform the task of computing and showcasing the profit percentage, profit value, and the duration for which a specific asset is held, all in real-time. The script effectively leverages the built-in resources to provide a seamless and robust experience, as it presents the calculated figures in an easily readable format on the chart, without causing any lag or disruptions to the chart.
MA_Script- Entry Point : base on MA20, MA50, MA100, MA200.
- Exit Point : base on stop loss, MA and trailing stop.
sa-strategy with HTF-TSLEntry- based on HA close above HMA confirmation done with ST and HTF ATR
Exit- based on close below ATR which works as trailing SL
[MV] %B with SMA + Volume Based Colored Bars
Entry Signal when %B Crosses with SMA and this is more meaningful if it supports colored bars.
Black Bar when prices go down and volume is bigger than 150% of its average, that indicates us price action is supported by a strong bearish volume
Blue Bar when prices go up and volume bigger than 150% of its average, that indicates us price action is supported by a strong bullish volume
VBC author @KIVANCfr3762
FX Sniper: T3-CCI Strategy - With 100 IndicatorsEntry signal when moving above -100, sell signal when going below 100
Amazing Crossover SystemEntry Rules
BUY when the 5 EMA crosses above the 10 EMA from underneath and the RSI crosses above the 50.0 mark from the bottom.
SELL when the 5 EMA crosses below the 10 EMA from the top and the RSI crosses below the 50.0 mark from the top.
Make sure that the RSI did cross 50.0 from the top or bottom and not just ranging tightly around the level.
How to setup Alert:
1) Add the Amazing Crossover System to your chart via Indicators
2) Find your currency pair
3) Set the timeframe on the chart to 1 hour
4) Press 'Alt + A' (create alert shortcut)
5) Set the following criteria for the alert:
Condition = 'Amazing Crossover System', Plot, ' BUY Signal'
The rest of the alert can be customized to your preferences
5) Repeat steps 1 - 4, but set the Condition = 'Amazing Crossover System', Plot, ' SELL Signal'
Dual SMA Crossover with Pivot FilterDual SMA Crossover with Pivot Filter
This indicator combines the power of dual Simple Moving Averages (SMAs) with a pivot point filter to generate higher-quality trading signals. By only triggering signals at pivot points during established trends, the indicator helps filter out false signals that often occur with standard SMA crossover strategies.
Key Features
Dual SMA System: Tracks both fast and slow SMAs (default 5 and 20 periods)
Trend Identification: Clear visual representation of bullish and bearish market trends
Pivot Point Filter: Only generates signals at significant market pivot points
Background Color: Easy trend visualization with color-coded chart background
Customizable Parameters:
Adjustable SMA periods (fast and slow)
Configurable pivot lookback period
Signal offset for visual positioning
How It Works
Trend Detection: The indicator identifies trends by comparing the fast and slow SMAs
Signal Generation: Buy signals occur at pivot lows during bullish trends
Signal Filtering: Sell signals trigger at pivot highs during bearish trends
Visual Feedback: Triangular markers indicate entry and exit points
This indicator is ideal for traders who want to avoid the whipsaws commonly associated with moving average strategies while capturing significant trend reversals at optimal entry points.
MTF Moving Averages (only EMA)MTF Moving Averages (only EMA)
This script provides a Multi-Timeframe (MTF) Exponential Moving Average (EMA) indicator for traders to visualize multiple EMAs across different timeframes directly on a single chart.
The indicator dynamically calculates and plots up to four EMAs per timeframe (15-minute, 30-minute, 1-hour, and Daily) with user-defined lengths, offering valuable insight into price trends and potential entry or exit points.
Key Features:
Multiple Timeframe Support: The script allows you to view EMAs from different timeframes simultaneously. This is especially useful for traders who follow trends across different timeframes to make more informed decisions.
Customizable Lengths: For each timeframe, the lengths of the EMAs are fully customizable. You can adjust the length of up to four EMAs per timeframe to suit your strategy.
EMA Calculation: The Exponential Moving Average (EMA) is used, which gives more weight to recent prices and reacts faster to price changes compared to the simple moving average (SMA).
Timeframe Flexibility: The indicator supports the following timeframes:
15-minute: Ideal for short-term traders and scalpers.
30-minute: For intraday trading with a slightly longer perspective.
1-hour: Suitable for swing traders and those who prefer a more medium-term view.
Daily: Great for longer-term trend-following strategies.
Interactive and User-Friendly: You can toggle the visibility of each EMA on each timeframe, allowing you to choose exactly which EMAs you wish to display, depending on your trading strategy.
Color-Coded for Clarity: The script uses distinct colors for each EMA on the chart:
Blue: EMA1
Green: EMA2
Red: EMA3
Purple: EMA4
Line Width Customization: Each plotted EMA line has a customizable width for better visual clarity.
Use Case:
Traders who use multiple timeframes for analysis (e.g., those using the "multi-timeframe analysis" technique) will find this script particularly useful. For example, a trader may look at the 15-minute chart to catch short-term movements, the 30-minute chart for intraday trends, the 1-hour chart for swing positions, and the Daily chart for identifying the overarching market trend. The script enables them to view the EMAs for all these timeframes in one glance without having to manually switch between them.
By observing the relationships between EMAs across multiple timeframes, traders can gain valuable insights into market conditions such as:
Crossovers: When a shorter-term EMA crosses above or below a longer-term EMA, it can signal a potential trend reversal or continuation.
Trend Strength: Multiple EMAs in alignment across different timeframes can indicate strong trend strength.
Support and Resistance: EMAs can act as dynamic support and resistance levels, guiding traders on price action levels to watch for potential price reversals.
Instructions:
Enable/Disable EMAs: Toggle on or off the EMAs for each timeframe (15-min, 30-min, 1-hour, Daily) using the script’s settings.
Adjust EMA Lengths: Change the default lengths for each EMA to match your preferred settings for different timeframes.
Monitor Key Levels: Watch how price interacts with the plotted EMAs to spot potential trading signals based on your strategy.
This indicator is designed to enhance your multi-timeframe analysis and help make more informed, data-driven trading decisions.
Big Candle Identifier with RSI Divergence and Advanced Stops1. Strategy Objective
The main goal of this strategy is to:
Identify significant price momentum (big candles).
Enter trades at opportune moments based on market signals (candlestick patterns and RSI divergence).
Limit initial risk through a fixed stop loss.
Maximize profits by using a trailing stop that activates only after the trade moves a specified distance in the profitable direction.
2. Components of the Strategy
A. Big Candle Identification
The strategy identifies big candles as indicators of strong momentum.
A big candle is defined as:
The body (absolute difference between close and open) of the current candle (body0) is larger than the bodies of the last five candles.
The candle is:
Bullish Big Candle: If close > open.
Bearish Big Candle: If open > close.
Purpose: Big candles signal potential continuation or reversal of trends, serving as the primary entry trigger.
B. RSI Divergence
Relative Strength Index (RSI): A momentum oscillator used to detect overbought/oversold conditions and divergence.
Fast RSI: A 5-period RSI, which is more sensitive to short-term price movements.
Slow RSI: A 14-period RSI, which smoothens fluctuations over a longer timeframe.
Divergence: The difference between the fast and slow RSIs.
Positive divergence (divergence > 0): Bullish momentum.
Negative divergence (divergence < 0): Bearish momentum.
Visualization: The divergence is plotted on the chart, helping traders confirm momentum shifts.
C. Stop Loss
Initial Stop Loss:
When entering a trade, an immediate stop loss of 200 points is applied.
This stop loss ensures the maximum risk is capped at a predefined level.
Implementation:
Long Trades: Stop loss is set below the entry price at low - 200 points.
Short Trades: Stop loss is set above the entry price at high + 200 points.
Purpose:
Prevents significant losses if the price moves against the trade immediately after entry.
D. Trailing Stop
The trailing stop is a dynamic risk management tool that adjusts with price movements to lock in profits. Here’s how it works:
Activation Condition:
The trailing stop only starts trailing when the trade moves 200 ticks (profit) in the right direction:
Long Position: close - entry_price >= 200 ticks.
Short Position: entry_price - close >= 200 ticks.
Trailing Logic:
Once activated, the trailing stop:
For Long Positions: Trails behind the price by 150 ticks (trail_stop = close - 150 ticks).
For Short Positions: Trails above the price by 150 ticks (trail_stop = close + 150 ticks).
Exit Condition:
The trade exits automatically if the price touches the trailing stop level.
Purpose:
Ensures profits are locked in as the trade progresses while still allowing room for price fluctuations.
E. Trade Entry Logic
Long Entry:
Triggered when a bullish big candle is identified.
Stop loss is set at low - 200 points.
Short Entry:
Triggered when a bearish big candle is identified.
Stop loss is set at high + 200 points.
F. Trade Exit Logic
Trailing Stop: Automatically exits the trade if the price touches the trailing stop level.
Fixed Stop Loss: Exits the trade if the price hits the predefined stop loss level.
G. 21 EMA
The strategy includes a 21-period Exponential Moving Average (EMA), which acts as a trend filter.
EMA helps visualize the overall market direction:
Price above EMA: Indicates an uptrend.
Price below EMA: Indicates a downtrend.
H. Visualization
Big Candle Identification:
The open and close prices of big candles are plotted for easy reference.
Trailing Stop:
Plotted on the chart to visualize its progression during the trade.
Green Line: Indicates the trailing stop for long positions.
Red Line: Indicates the trailing stop for short positions.
RSI Divergence:
Positive divergence is shown in green.
Negative divergence is shown in red.
3. Key Parameters
trail_start_ticks: The number of ticks required before the trailing stop activates (default: 200 ticks).
trail_distance_ticks: The distance between the trailing stop and price once the trailing stop starts (default: 150 ticks).
initial_stop_loss_points: The fixed stop loss in points applied at entry (default: 200 points).
tick_size: Automatically calculates the minimum tick size for the trading instrument.
4. Workflow of the Strategy
Step 1: Entry Signal
The strategy identifies a big candle (bullish or bearish).
If conditions are met, a trade is entered with a fixed stop loss.
Step 2: Initial Risk Management
The trade starts with an initial stop loss of 200 points.
Step 3: Trailing Stop Activation
If the trade moves 200 ticks in the profitable direction:
The trailing stop is activated and follows the price at a distance of 150 ticks.
Step 4: Exit the Trade
The trade is exited if:
The price hits the trailing stop.
The price hits the initial stop loss.
5. Advantages of the Strategy
Risk Management:
The fixed stop loss ensures that losses are capped.
The trailing stop locks in profits after the trade becomes profitable.
Momentum-Based Entries:
The strategy uses big candles as entry triggers, which often indicate strong price momentum.
Divergence Confirmation:
RSI divergence helps validate momentum and avoid false signals.
Dynamic Profit Protection:
The trailing stop adjusts dynamically, allowing the trade to capture larger moves while protecting gains.
6. Ideal Market Conditions
This strategy performs best in:
Trending Markets:
Big candles and momentum signals are more effective in capturing directional moves.
High Volatility:
Larger price swings improve the probability of reaching the trailing stop activation level (200 ticks).
CalculatePercentageSlTpLibrary "CalculatePercentageSlTp"
This Library calculate the sl and tp amount in percentage
sl_percentage(entry_price, sl_price)
this function calculates the sl value in percentage
Parameters:
entry_price : indicates the entry level
sl_price : indicates the stop loss level
Returns: stop loss in percentage
tp_percentage(entry_price, tp_price)
this function calculates the tp value in percentage
Parameters:
entry_price : indicates the entry level
tp_price : indicates the take profit level
Returns: take profit in percentage
sl_level(entry_price, sl_percentage)
this function calculates the sl level price
Parameters:
entry_price : indicates the entry level
sl_percentage : indicates the stop loss percentage
Returns: stop loss price in $
tp_level(entry_price, tp_percentage)
this function calculates the tp level price
Parameters:
entry_price : indicates the entry level
tp_percentage : indicates the take profit percentage
Returns: take profit price in $
Order Block Signals//@version=5
indicator("Order Block Signals", overlay=true, max_lines_count=500, max_labels_count=500)
// Inputs
OB_Threshold = input.float(0.001, "OB Threshold (%)", step=0.001) / 100
Lookback = input.int(200, "Lookback Period")
min_diff = input.float(1.0, "Min Candle %", step=0.1)
max_diff = input.float(1.2, "Max Candle %", step=0.1)
tp_percent = input.float(1.3, "Take Profit %", step=0.1) / 100
sl2_percent = input.float(1.3, "Second SL %", step=0.1) / 100
// Order Block Detection
var float highRange = na
var float lowRange = na
highRange := ta.highest(high, Lookback)
lowRange := ta.lowest(low, Lookback)
Buy_OB = low >= lowRange * (1 - OB_Threshold) and low <= lowRange * (1 + OB_Threshold)
Sell_OB = high >= highRange * (1 - OB_Threshold) and high <= highRange * (1 + OB_Threshold)
// Candle Filter
candle_diff = ((high - low) / low) * 100
valid_candle = candle_diff >= min_diff and candle_diff <= max_diff
// Signal Generation
Buy_Signal = Buy_OB and valid_candle
Sell_Signal = Sell_OB and valid_candle
// Remove Excess Signals
var int lastSignal = 0
Buy_Signal := Buy_Signal and lastSignal <= 0
Sell_Signal := Sell_Signal and lastSignal >= 0
if Buy_Signal
lastSignal := 1
else if Sell_Signal
lastSignal := -1
// Price Levels
var float entryPrice = na
var float slPrice = na
var float tpPrice = na
var float sl2Price = na
if Buy_Signal
entryPrice := high
slPrice := low
tpPrice := entryPrice * (1 + tp_percent)
sl2Price := slPrice * (1 - sl2_percent)
else if Sell_Signal
entryPrice := low
slPrice := high
tpPrice := entryPrice * (1 - tp_percent)
sl2Price := slPrice * (1 + sl2_percent)
// Plotting
plot(entryPrice, "Entry", color.new(color.green, 0), 2)
plot(slPrice, "SL", color.new(color.red, 0), 2)
plot(tpPrice, "TP", color.new(color.blue, 0), 2)
plot(sl2Price, "SL2", color.new(color.orange, 0), 2)
// Enhanced Signal Markers
plotshape(Buy_Signal, style=shape.square, location=location.belowbar,
color=color.new(color.green, 0), size=size.tiny, offset=-40)
plotshape(Buy_Signal, style=shape.square, location=location.belowbar,
color=color.new(color.lime, 0), size=size.tiny, offset=-50)
plotshape(Buy_Signal, style=shape.triangleup, location=location.belowbar,
color=color.new(color.white, 0), size=size.small, offset=-45)
plotshape(Sell_Signal, style=shape.square, location=location.abovebar,
color=color.new(color.red, 0), size=size.tiny, offset=40)
plotshape(Sell_Signal, style=shape.square, location=location.abovebar,
color=color.new(color.orange, 0), size=size.tiny, offset=50)
plotshape(Sell_Signal, style=shape.triangledown, location=location.abovebar,
color=color.new(color.white, 0), size=size.small, offset=-45)
// Order Block Zones
bgcolor(Buy_OB ? color.new(color.green, 90) : na)
bgcolor(Sell_OB ? color.new(color.red, 90) : na)
// Dynamic Lines
var line entryLine = na
var line slLine = na
var line tpLine = na
var line sl2Line = na
if Buy_Signal or Sell_Signal
entryLine := line.new(bar_index, entryPrice, bar_index+1, entryPrice,
color=color.green, width=2)
slLine := line.new(bar_index, slPrice, bar_index+1, slPrice,
color=color.red, width=2)
tpLine := line.new(bar_index, tpPrice, bar_index+1, tpPrice,
color=color.blue, width=2)
sl2Line := line.new(bar_index, sl2Price, bar_index+1, sl2Price,
color=color.orange, width=2)
//@version=5
indicator("Order Block Signals - Exclusive & Dynamic", overlay=true, max_lines_count=500)
// Inputs
Lookback = input.int(200, "Lookback Period")
min_diff = input.float(1.0, "Min Candle %", step=0.1)
max_diff = input.float(1.2, "Max Candle %", step=0.1)
tp_percent = input.float(1.3, "Take Profit %", step=0.1) / 100
sl2_percent = input.float(1.3, "Second SL %", step=0.1) / 100
// Order Block Detection
var float highRange = na
var float lowRange = na
highRange := ta.highest(high, Lookback)
lowRange := ta.lowest(low, Lookback)
Buy_OB = low >= lowRange * (1 - OB_Threshold) and low <= lowRange * (1 + OB_Threshold)
Sell_OB = high >= highRange * (1 - OB_Threshold) and high <= highRange * (1 + OB_Threshold)
// Candle Filter
candle_diff = ((high - low) / low) * 100
valid_candle = candle_diff >= min_diff and candle_diff <= max_diff
// Signal Generation with Mutual Exclusivity
var int lastSignal = 0 // -1 = Sell active, 0 = Neutral, 1 = Buy active
var float entryPrice = na
var float slPrice = na
var float tpPrice = na
var float sl2Price = na
Buy_Signal = false
Sell_Signal = false
// Check for new signals
if Buy_OB and valid_candle and lastSignal <= 0
Buy_Signal := true
lastSignal := 1
entryPrice := high
slPrice := low
tpPrice := entryPrice * (1 + tp_percent)
sl2Price := slPrice * (1 - sl2_percent)
else if Sell_OB and valid_candle and lastSignal >= 0
Sell_Signal := true
lastSignal := -1
entryPrice := low
slPrice := high
tpPrice := entryPrice * (1 - tp_percent)
sl2Price := slPrice * (1 + sl2_percent)
// Check for TP/SL hit to reset signals
if lastSignal == 1 and (high >= tpPrice or low <= slPrice)
lastSignal := 0
entryPrice := na
slPrice := na
tpPrice := na
sl2Price := na
else if lastSignal == -1 and (low <= tpPrice or high >= slPrice)
lastSignal := 0
entryPrice := na
slPrice := na
tpPrice := na
sl2Price := na
// Plotting
plot(entryPrice, "Entry", color.new(color.green, 0), 2, linewidth=2)
plot(slPrice, "SL", color.new(color.red, 0), 2, linewidth=2)
plot(tpPrice, "TP", color.new(color.blue, 0), 2, linewidth=2)
plot(sl2Price, "SL2", color.new(color.orange, 0), 2, linewidth=2)
// Signal Markers
plotshape(Buy_Signal, style=shape.triangleup, location=location.belowbar,
color=color.new(color.green, 0), size=size.normal, text="BUY", textcolor=color.white)
plotshape(Sell_Signal, style=shape.triangledown, location=location.abovebar,
color=color.new(color.red, 0), size=size.normal, text="SELL", textcolor=color.white)
// Order Block Zones
bgcolor(Buy_OB ? color.new(color.green, 90) : na, title="Buy OB Zone")
bgcolor(Sell_OB ? color.new(color.red, 90) : na, title="Sell OB Zone")
// Dynamic Lines for TP/SL
var line entryLine = na
var line slLine = na
var line tpLine = na
var line sl2Line = na
if Buy_Signal or Sell_Signal
entryLine := line.new(bar_index, entryPrice, bar_index + 1, entryPrice,
color=color.new(color.green, 0), width=2)
slLine := line.new(bar_index, slPrice, bar_index + 1, slPrice,
color=color.new(color.red, 0), width=2)
tpLine := line.new(bar_index, tpPrice, bar_index + 1, tpPrice,
color=color.new(color.blue, 0), width=2)
sl2Line := line.new(bar_index, sl2Price, bar_index + 1, sl2Price,
color=color.new(color.orange, 0), width=2)
// Clear lines when position is closed
if lastSignal == 0
line.delete(entryLine)
line.delete(slLine)
line.delete(tpLine)
line.delete(sl2Line)
InnovateX//@version=6
strategy("Candle Stop Strategy Backtest", overlay=true)
// --- EMA Variables ---
ema7_length = 7
ema25_length = 25
ema99_length = 99
ema7 = ta.ema(close, ema7_length)
ema25 = ta.ema(close, ema25_length)
ema99 = ta.ema(close, ema99_length)
// --- Support and Resistance Calculation ---
lookback_support_resistance = 50
support_level = ta.lowest(low, lookback_support_resistance)
resistance_level = ta.highest(high, lookback_support_resistance)
// --- Candle Stop Function ---
is_candle_stop(trend) =>
body = math.abs(close - open)
upper_shadow = high - math.max(open, close)
lower_shadow = math.min(open, close) - low
if trend == "up"
lower_shadow >= 1.5 * body and upper_shadow < body and close > open and math.abs(ema7 - close) < body
else if trend == "down"
upper_shadow >= 1.5 * body and lower_shadow < body and close < open and math.abs(ema7 - close) < body
else
false
// --- Trend Determination ---
trend = ema25 > ema99 ? "up" : ema25 < ema99 ? "down" : "neutral"
// --- Breakout Detection ---
var bool breakout_detected = false
if trend == "up" and close > resistance_level
breakout_detected := true
alert("شکست صعودی تشخیص داده شد! منتظر پولبک 🚀", alert.freq_once_per_bar)
else if trend == "down" and close < support_level
breakout_detected := true
alert("شکست نزولی تشخیص داده شد! منتظر پولبک 📉", alert.freq_once_per_bar)
// --- Entry and Exit Conditions ---
var float position = 0.0
var float entry_price = 0.0
var float stop_loss_price = na
var bool take_profit_long = false // Declare take_profit_long
var bool stop_loss_hit_long = false // Declare stop_loss_hit_long
var bool take_profit_short = false // Declare take_profit_short
var bool stop_loss_hit_short = false// Declare stop_loss_hit_short
risk_per_trade_percent = 2.0 // Risk percentage per trade - adjustable in strategy settings
if not breakout_detected
if position == 0 and is_candle_stop(trend)
risk_amount_usd = strategy.initial_capital * (risk_per_trade_percent / 100)
if trend == "up"
stop_loss_price := math.min(low, support_level * 0.99)
if (close - stop_loss_price) != 0
position_size_usd = risk_amount_usd / (close - stop_loss_price)
amount = position_size_usd / close
strategy.entry("Long", strategy.long, qty=amount)
position := amount
entry_price := close
else if trend == "down"
stop_loss_price := math.max(high, resistance_level * 1.01)
if (stop_loss_price - close) != 0
position_size_usd = risk_amount_usd / (stop_loss_price - close)
amount = position_size_usd / close
strategy.entry("Short", strategy.short, qty=amount)
position := amount
entry_price := close
if position > 0
profit_percent_long = (close - entry_price) / entry_price * 100
profit_percent_short = (entry_price - close) / entry_price * 100
loss_percent_long = (entry_price - close) / entry_price * 100
loss_percent_short = (close - entry_price) / entry_price * 100
risk_reward_long = loss_percent_long != 0 ? profit_percent_long / loss_percent_long : profit_percent_long
risk_reward_short = loss_percent_short != 0 ? profit_percent_short / loss_percent_short : profit_percent_short
take_profit_long := profit_percent_long >= 4 and risk_reward_long >= 2 // Assign value to take_profit_long
stop_loss_hit_long := close <= stop_loss_price // Assign value to stop_loss_hit_long
take_profit_short := profit_percent_short >= 4 and risk_reward_short >= 2 // Assign value to take_profit_short
stop_loss_hit_short := close >= stop_loss_price // Assign value to stop_loss_hit_short
if (trend == "up" and (take_profit_long or stop_loss_hit_long)) or (trend == "down" and (take_profit_short or stop_loss_hit_short))
if trend == "up"
strategy.close("Long")
else
strategy.close("Short")
position := 0
entry_price := 0.0
breakout_detected := false
// --- Plotting EMAs and Support/Resistance Levels ---
plot(ema7, color=color.blue, title="EMA7")
plot(ema25, color=color.red, title="EMA25")
plot(ema99, color=color.green, title="EMA99")
plot(resistance_level, color=color.orange, style=plot.style_line, title="Resistance")
plot(support_level, color=color.orange, style=plot.style_line, title="Support")
Commission-aware Trade LabelsCommission-aware Trade Labels
Description:
This library provides an easy way to visualize take-profit and stop-loss levels on your chart, taking into account trading commissions. The library calculates and displays the net profit or loss, along with other useful information such as risk/reward ratio, shares, and position size.
Features:
Configurable take-profit and stop-loss prices or percentages.
Set entry amount or shares.
Calculates and displays the risk/reward ratio.
Shows net profit or loss, considering trading commissions.
Customizable label appearance.
Usage:
Add the script to your chart.
Create an Order object for take-profit and stop-loss with desired configurations.
Call target_label() and stop_label() methods for each order object.
Example:
target_order = Order.new(take_profit_price=27483, stop_loss_price=28000, shares=0.2)
stop_order = Order.new(stop_loss_price=29000, shares=1)
target_order.target_label()
stop_order.stop_label()
This script is a powerful tool for visualizing your trading strategy's performance and helps you make better-informed decisions by considering trading commissions in your profit and loss calculations.
Library "tradelabels"
entry_price(this)
Parameters:
this : Order object
@return entry_price
take_profit_price(this)
Parameters:
this : Order object
@return take_profit_price
stop_loss_price(this)
Parameters:
this : Order object
@return stop_loss_price
is_long(this)
Parameters:
this : Order object
@return entry_price
is_short(this)
Parameters:
this : Order object
@return entry_price
percent_to_target(this, target)
Parameters:
this : Order object
target : Target price
@return percent
risk_reward(this)
Parameters:
this : Order object
@return risk_reward_ratio
shares(this)
Parameters:
this : Order object
@return shares
position_size(this)
Parameters:
this : Order object
@return position_size
commission_cost(this, target_price)
Parameters:
this : Order object
@return commission_cost
target_price
net_result(this, target_price)
Parameters:
this : Order object
target_price : The target price to calculate net result for (either take_profit_price or stop_loss_price)
@return net_result
create_take_profit_label(this, prefix, size, offset_x, bg_color, text_color)
Parameters:
this
prefix
size
offset_x
bg_color
text_color
create_stop_loss_label(this, prefix, size, offset_x, bg_color, text_color)
Parameters:
this
prefix
size
offset_x
bg_color
text_color
create_entry_label(this, prefix, size, offset_x, bg_color, text_color)
Parameters:
this
prefix
size
offset_x
bg_color
text_color
create_line(this, target_price, line_color, offset_x, line_style, line_width, draw_entry_line)
Parameters:
this
target_price
line_color
offset_x
line_style
line_width
draw_entry_line
Order
Order
Fields:
entry_price : Entry price
stop_loss_price : Stop loss price
stop_loss_percent : Stop loss percent, default 2%
take_profit_price : Take profit price
take_profit_percent : Take profit percent, default 6%
entry_amount : Entry amount, default 5000$
shares : Shares
commission : Commission, default 0.04%
Strategy█ OVERVIEW
This library is a Pine Script™ programmer’s tool containing a variety of strategy-related functions to assist in calculations like profit and loss, stop losses and limits. It also includes several useful functions one can use to convert between units in ticks, price, currency or a percentage of the position's size.
█ CONCEPTS
The library contains three types of functions:
1 — Functions beginning with `percent` take either a portion of a price, or the current position's entry price and convert it to the value outlined in the function's documentation.
Example: Converting a percent of the current position entry price to ticks, or calculating a percent profit at a given level for the position.
2 — Functions beginning with `tick` convert a tick value to another form.
These are useful for calculating a price or currency value from a specified number of ticks.
3 — Functions containing `Level` are used to calculate a stop or take profit level using an offset in ticks from the current entry price.
These functions can be used to plot stop or take profit levels on the chart, or as arguments to the `limit` and `stop` parameters in strategy.exit() function calls.
Note that these calculated levels flip automatically with the position's bias.
For example, using `ticksToStopLevel()` will calculate a stop level under the entry price for a long position, and above the entry price for a short position.
There are also two functions to assist in calculating a position size using the entry's stop and a fixed risk expressed as a percentage of the current account's equity. By varying the position size this way, you ensure that entries with different stop levels risk the same proportion of equity.
█ NOTES
Example code using some of the library's functions is included at the end of the library. To see it in action, copy the library's code to a new script in the Pine Editor, and “Add to chart”.
For each trade, the code displays:
• The entry level in orange.
• The stop level in fuchsia.
• The take profit level in green.
The stop and take profit levels automatically flip sides based on whether the current position is long or short.
Labels near the last trade's levels display the percentages used to calculate them, which can be changed in the script's inputs.
We plot markers for entries and exits because strategy code in libraries does not display the usual markers for them.
Look first. Then leap.
█ FUNCTIONS
percentToTicks(percent) Converts a percentage of the average entry price to ticks.
Parameters:
percent : (series int/float) The percentage of `strategy.position_avg_price` to convert to ticks. 50 is 50% of the entry price.
Returns: (float) A value in ticks.
percentToPrice(percent) Converts a percentage of the average entry price to a price.
Parameters:
percent : (series int/float) The percentage of `strategy.position_avg_price` to convert to price. 50 is 50% of the entry price.
Returns: (float) A value in the symbol's quote currency (USD for BTCUSD).
percentToCurrency(price, percent) Converts the percentage of a price to money.
Parameters:
price : (series int/float) The symbol's price.
percent : (series int/float) The percentage of `price` to calculate.
Returns: (float) A value in the symbol's currency.
percentProfit(exitPrice) Calculates the profit (as a percentage of the position's `strategy.position_avg_price` entry price) if the trade is closed at `exitPrice`.
Parameters:
exitPrice : (series int/float) The potential price to close the position.
Returns: (float) Percentage profit for the current position if closed at the `exitPrice`.
priceToTicks(price) Converts a price to ticks.
Parameters:
price : (series int/float) Price to convert to ticks.
Returns: (float) A quantity of ticks.
ticksToPrice(price) Converts ticks to a price offset from the average entry price.
Parameters:
price : (series int/float) Ticks to convert to a price.
Returns: (float) A price level that has a distance from the entry price equal to the specified number of ticks.
ticksToCurrency(ticks) Converts ticks to money.
Parameters:
ticks : (series int/float) Number of ticks.
Returns: (float) Money amount in the symbol's currency.
ticksToStopLevel(ticks) Calculates a stop loss level using a distance in ticks from the current `strategy.position_avg_price` entry price. This value can be plotted on the chart, or used as an argument to the `stop` parameter of a `strategy.exit()` call. NOTE: The stop level automatically flips based on whether the position is long or short.
Parameters:
ticks : (series int/float) The distance in ticks from the entry price to the stop loss level.
Returns: (float) A stop loss level for the current position.
ticksToTpLevel(ticks) Calculates a take profit level using a distance in ticks from the current `strategy.position_avg_price` entry price. This value can be plotted on the chart, or used as an argument to the `limit` parameter of a `strategy.exit()` call. NOTE: The take profit level automatically flips based on whether the position is long or short.
Parameters:
ticks : (series int/float) The distance in ticks from the entry price to the take profit level.
Returns: (float) A take profit level for the current position.
calcPositionSizeByStopLossTicks(stopLossTicks, riskPercent) Calculates the position size needed to implement a given stop loss (in ticks) corresponding to `riskPercent` of equity.
Parameters:
stopLossTicks : (series int) The stop loss (in ticks) that will be used to protect the position.
riskPercent : (series int/float) The maximum risk level as a percent of current equity (`strategy.equity`).
Returns: (int) A quantity of contracts.
calcPositionSizeByStopLossPercent(stopLossPercent, riskPercent, entryPrice) Calculates the position size needed to implement a given stop loss (%) corresponding to `riskPercent` of equity.
Parameters:
stopLossPercent : (series int/float) The stop loss in percent that will be used to protect the position.
riskPercent : (series int/float) The maximum risk level as a percent of current equity (`strategy.equity`).
entryPrice : (series int/float) The entry price of the position.
Returns: (int) A quantity of contracts.
exitPercent(id, lossPercent, profitPercent, qty, qtyPercent, comment, when, alertMessage) A wrapper of the `strategy.exit()` built-in which adds the possibility to specify loss & profit in as a value in percent. NOTE: this function may work incorrectly with pyramiding turned on due to the use of `strategy.position_avg_price` in its calculations of stop loss and take profit offsets.
Parameters:
id : (series string) The order identifier of the `strategy.exit()` call.
lossPercent : (series int/float) Stop loss as a percent of the entry price.
profitPercent : (series int/float) Take profit as a percent of the entry price.
qty : (series int/float) Number of contracts/shares/lots/units to exit a trade with. The default value is `na`.
qtyPercent : (series int/float) The percent of the position's size to exit a trade with. If `qty` is `na`, the default value of `qty_percent` is 100.
comment : (series string) Optional. Additional notes on the order.
when : (series bool) Condition of the order. The order is placed if it is true.
alertMessage : (series string) An optional parameter which replaces the {{strategy.order.alert_message}} placeholder when it is used in the "Create Alert" dialog box's "Message" field.
IU Higher Timeframe MA Cross StrategyIU Higher Timeframe MA Cross Strategy
The IU Higher Timeframe MA Cross Strategy is a versatile trading tool designed to identify trend by utilizing two customizable moving averages (MAs) across different timeframes and types. This strategy includes detailed entry and exit rules with fully configurable inputs, offering flexibility to suit various trading styles.
Key Features:
- Two moving averages (MA1 and MA2) with customizable types, lengths, sources, and timeframes.
- Both long and short trade setups based on MA crossovers.
- Integrated risk management with adjustable stop-loss and take-profit levels based on a user-defined risk-to-reward (RTR) ratio.
- Clear visualization of MAs, entry points, stop-loss, and take-profit zones.
Inputs:
1. Risk-to-Reward Ratio (RTR):
- Defines the take-profit level in relation to the stop-loss distance. Default is 2.
2. MA1 Settings:
- Source: Select the data source for calculating MA1 (e.g., close, open, high, low). Default is close.
- Timeframe: Specify the timeframe for MA1 calculation. Default is 60 (60-minute chart).
- Length: Set the lookback period for MA1 calculation. Default is 20.
- Type: Choose the type of moving average (options: SMA, EMA, SMMA, WMA, VWMA). Default is EMA.
- Smooth: Option to enable or disable smoothing of MA1 to merge gaps. Default is true.
3. MA2 Settings:
- Source: Select the data source for calculating MA2 (e.g., close, open, high, low). Default is close.
- Timeframe: Specify the timeframe for MA2 calculation. Default is 60 (60-minute chart).
- Length: Set the lookback period for MA2 calculation. Default is 50.
- Type: Choose the type of moving average (options: SMA, EMA, SMMA, WMA, VWMA). Default is EMA.
- Smooth: Option to enable or disable smoothing of MA2 to merge gaps. Default is true.
Entry Rules:
- Long Entry:
- Triggered when MA1 crosses above MA2 (crossover).
- Entry is confirmed only when the bar is closed and no existing position is active.
- Short Entry:
- Triggered when MA1 crosses below MA2 (crossunder).
- Entry is confirmed only when the bar is closed and no existing position is active.
Exit Rules:
- Stop-Loss:
- For long positions: Set at the low of the bar preceding the entry.
- For short positions: Set at the high of the bar preceding the entry.
- Take-Profit:
- For long positions: Calculated as (Entry Price - Stop-Loss) * RTR + Entry Price.
- For short positions: Calculated as Entry Price - (Stop-Loss - Entry Price) * RTR.
Visualization:
- Plots MA1 and MA2 on the chart with distinct colors for easy identification.
- Highlights stop-loss and take-profit levels using shaded zones for clear visual representation.
- Displays the entry level for active positions.
This strategy provides a robust framework for traders to identify and act on trend reversals while maintaining strict risk management. The flexibility of its inputs allows for seamless customization to adapt to various market conditions and trading preferences.
SnowdexUtilsLibrary "SnowdexUtils"
the various function that often use when create a strategy trading.
f_backtesting_date(train_start_date, train_end_date, test_date, deploy_date)
Backtesting within a specific window based on deployment and testing dates.
Parameters:
train_start_date (int) : the start date for training the strategy.
train_end_date (int) : the end date for training the strategy.
test_date (bool) : if true, backtests within the period from `train_end_date` to the current time.
deploy_date (bool) : if true, the strategy backtests up to the current time.
Returns: given time falls within the specified window for backtesting.
f_init_ma(ma_type, source, length)
Initializes a moving average based on the specified type.
Parameters:
ma_type (simple string) : the type of moving average (e.g., "RMA", "EMA", "SMA", "WMA").
source (float) : the input series for the moving average calculation.
length (simple int) : the length of the moving average window.
Returns: the calculated moving average value.
f_init_tp(side, entry_price, rr, sl_open_position)
Calculates the target profit based on entry price, risk-reward ratio, and stop loss. The formula is `tp = entry price + (rr * (entry price - stop loss))`.
Parameters:
side (bool) : the trading side (true for long, false for short).
entry_price (float) : the entry price of the position.
rr (float) : the risk-reward ratio.
sl_open_position (float) : the stop loss price for the open position.
Returns: the calculated target profit value.
f_round_up(number, decimals)
Rounds up a number to a specified number of decimals.
Parameters:
number (float)
decimals (int)
Returns: The rounded-up number.
f_get_pip_size()
Calculates the pip size for the current instrument.
Returns: Pip size adjusted for Forex instruments or 1 for others.
f_table_get_position(value)
Maps a string to a table position constant.
Parameters:
value (string) : String representing the desired position (e.g., "Top Right").
Returns: The corresponding position constant or `na` for invalid values.
Position Size CalculatorThe provided Pine Script is a custom indicator titled "Position Size Calculator" designed to assist traders in calculating the appropriate size of a trading position based on predefined risk parameters. This script is intended to be overlaid on a trading chart, as indicated by `overlay=true`, allowing traders to visualize and adjust their risk and position size directly within the context of their trading strategy.
What It Does:
The core functionality of this script revolves around calculating the position size a trader should take based on three input parameters:
**Risk in USD (`Risk`)**: This represents the amount of money the trader is willing to risk on a single trade.
**Entry Price (`EntryPrice`)**: The price at which the trader plans to enter the market.
**Stop Loss (`StopLoss`)**: The price at which the trader plans to exit the market should the trade move against them, effectively limiting their loss.
The script calculates the position size using a function named `calculatePositionSize`, which performs the following steps:
It first calculates the `expectedLoss` by taking 90% (`0.9`) of the input risk. This implies that the script factors in a safety margin, assuming traders are willing to risk up to 90% of their stated risk amount per trade.
It then calculates the position size based on the distance between the Entry Price and the Stop Loss. This calculation adjusts based on whether the Entry Price is higher or lower than the Stop Loss, ensuring that the position size fits the risk profile regardless of trade direction.
The function returns several values: `risk`, `entryPrice`, `stopLoss`, `expectedLoss`, and `size`, which are then plotted on the chart.
How It Does It:
**Expected Loss Calculation**: By reducing the risk by 10% before calculating position size, the script provides a buffer to account for slippage or to ensure the trader does not fully utilize their risk budget on a single trade.
**Position Size Calculation**: The script calculates position size by dividing the adjusted risk (`expectedLoss`) by the price difference between the Entry Price and Stop Loss. This gives a quantitative measure of how many units of the asset can be bought or sold while staying within the risk parameters.
What Traders Can Use It For:
Traders can use this Position Size Calculator for several purposes:
- **Risk Management**: By determining the appropriate position size, traders can ensure that they do not overexpose themselves to market risk on a single trade.
- **Trade Planning**: Before entering a trade, the script allows traders to visualize their risk, entry, and exit points, helping them to make more informed decisions.
- **Consistency**: Using a standardized method for calculating position size helps traders maintain consistency in their trading approach, a key aspect of successful trading strategies.
- **Efficiency**: Automating the calculation of position size saves time and reduces the likelihood of manual calculation errors.
Overall, this Pine Script indicator is a practical tool for traders looking to implement strict risk management rules within their trading strategies, ensuring that each trade is sized appropriately according to their risk tolerance and market conditions.
CNTLibraryLibrary "CNTLibrary"
Custom Functions To Help Code In Pinescript V5
Coded By Christian Nataliano
First Coded In 10/06/2023
Last Edited In 22/06/2023
Huge Shout Out To © ZenAndTheArtOfTrading and his ZenLibrary V5, Some Of The Custom Functions Were Heavily Inspired By Matt's Work & His Pine Script Mastery Course
Another Shout Out To The TradingView's Team Library ta V5
//====================================================================================================================================================
// Custom Indicator Functions
//====================================================================================================================================================
GetKAMA(KAMA_lenght, Fast_KAMA, Slow_KAMA)
Calculates An Adaptive Moving Average Based On Perry J Kaufman's Calculations
Parameters:
KAMA_lenght (int) : Is The KAMA Lenght
Fast_KAMA (int) : Is The KAMA's Fastes Moving Average
Slow_KAMA (int) : Is The KAMA's Slowest Moving Average
Returns: Float Of The KAMA's Current Calculations
GetMovingAverage(Source, Lenght, Type)
Get Custom Moving Averages Values
Parameters:
Source (float) : Of The Moving Average, Defval = close
Lenght (simple int) : Of The Moving Average, Defval = 50
Type (string) : Of The Moving Average, Defval = Exponential Moving Average
Returns: The Moving Average Calculation Based On Its Given Source, Lenght & Calculation Type (Please Call Function On Global Scope)
GetDecimals()
Calculates how many decimals are on the quote price of the current market © ZenAndTheArtOfTrading
Returns: The current decimal places on the market quote price
Truncate(number, decimalPlaces)
Truncates (cuts) excess decimal places © ZenAndTheArtOfTrading
Parameters:
number (float)
decimalPlaces (simple float)
Returns: The given number truncated to the given decimalPlaces
ToWhole(number)
Converts pips into whole numbers © ZenAndTheArtOfTrading
Parameters:
number (float)
Returns: The converted number
ToPips(number)
Converts whole numbers back into pips © ZenAndTheArtOfTrading
Parameters:
number (float)
Returns: The converted number
GetPctChange(value1, value2, lookback)
Gets the percentage change between 2 float values over a given lookback period © ZenAndTheArtOfTrading
Parameters:
value1 (float)
value2 (float)
lookback (int)
BarsAboveMA(lookback, ma)
Counts how many candles are above the MA © ZenAndTheArtOfTrading
Parameters:
lookback (int)
ma (float)
Returns: The bar count of how many recent bars are above the MA
BarsBelowMA(lookback, ma)
Counts how many candles are below the MA © ZenAndTheArtOfTrading
Parameters:
lookback (int)
ma (float)
Returns: The bar count of how many recent bars are below the EMA
BarsCrossedMA(lookback, ma)
Counts how many times the EMA was crossed recently © ZenAndTheArtOfTrading
Parameters:
lookback (int)
ma (float)
Returns: The bar count of how many times price recently crossed the EMA
GetPullbackBarCount(lookback, direction)
Counts how many green & red bars have printed recently (ie. pullback count) © ZenAndTheArtOfTrading
Parameters:
lookback (int)
direction (int)
Returns: The bar count of how many candles have retraced over the given lookback & direction
GetSwingHigh(Lookback, SwingType)
Check If Price Has Made A Recent Swing High
Parameters:
Lookback (int) : Is For The Swing High Lookback Period, Defval = 7
SwingType (int) : Is For The Swing High Type Of Identification, Defval = 1
Returns: A Bool - True If Price Has Made A Recent Swing High
GetSwingLow(Lookback, SwingType)
Check If Price Has Made A Recent Swing Low
Parameters:
Lookback (int) : Is For The Swing Low Lookback Period, Defval = 7
SwingType (int) : Is For The Swing Low Type Of Identification, Defval = 1
Returns: A Bool - True If Price Has Made A Recent Swing Low
//====================================================================================================================================================
// Custom Risk Management Functions
//====================================================================================================================================================
CalculateStopLossLevel(OrderType, Entry, StopLoss)
Calculate StopLoss Level
Parameters:
OrderType (int) : Is To Determine A Long / Short Position, Defval = 1
Entry (float) : Is The Entry Level Of The Order, Defval = na
StopLoss (float) : Is The Custom StopLoss Distance, Defval = 2x ATR Below Close
Returns: Float - The StopLoss Level In Actual Price As A
CalculateStopLossDistance(OrderType, Entry, StopLoss)
Calculate StopLoss Distance In Pips
Parameters:
OrderType (int) : Is To Determine A Long / Short Position, Defval = 1
Entry (float) : Is The Entry Level Of The Order, NEED TO INPUT PARAM
StopLoss (float) : Level Based On Previous Calculation, NEED TO INPUT PARAM
Returns: Float - The StopLoss Value In Pips
CalculateTakeProfitLevel(OrderType, Entry, StopLossDistance, RiskReward)
Calculate TakeProfit Level
Parameters:
OrderType (int) : Is To Determine A Long / Short Position, Defval = 1
Entry (float) : Is The Entry Level Of The Order, Defval = na
StopLossDistance (float)
RiskReward (float)
Returns: Float - The TakeProfit Level In Actual Price
CalculateTakeProfitDistance(OrderType, Entry, TakeProfit)
Get TakeProfit Distance In Pips
Parameters:
OrderType (int) : Is To Determine A Long / Short Position, Defval = 1
Entry (float) : Is The Entry Level Of The Order, NEED TO INPUT PARAM
TakeProfit (float) : Level Based On Previous Calculation, NEED TO INPUT PARAM
Returns: Float - The TakeProfit Value In Pips
CalculateConversionCurrency(AccountCurrency, SymbolCurrency, BaseCurrency)
Get The Conversion Currecny Between Current Account Currency & Current Pair's Quoted Currency (FOR FOREX ONLY)
Parameters:
AccountCurrency (simple string) : Is For The Account Currency Used
SymbolCurrency (simple string) : Is For The Current Symbol Currency (Front Symbol)
BaseCurrency (simple string) : Is For The Current Symbol Base Currency (Back Symbol)
Returns: Tuple Of A Bollean (Convert The Currency ?) And A String (Converted Currency)
CalculateConversionRate(ConvertCurrency, ConversionRate)
Get The Conversion Rate Between Current Account Currency & Current Pair's Quoted Currency (FOR FOREX ONLY)
Parameters:
ConvertCurrency (bool) : Is To Check If The Current Symbol Needs To Be Converted Or Not
ConversionRate (float) : Is The Quoted Price Of The Conversion Currency (Input The request.security Function Here)
Returns: Float Price Of Conversion Rate (If In The Same Currency Than Return Value Will Be 1.0)
LotSize(LotSizeSimple, Balance, Risk, SLDistance, ConversionRate)
Get Current Lot Size
Parameters:
LotSizeSimple (bool) : Is To Toggle Lot Sizing Calculation (Simple Is Good Enough For Stocks & Crypto, Whilst Complex Is For Forex)
Balance (float) : Is For The Current Account Balance To Calculate The Lot Sizing Based Off
Risk (float) : Is For The Current Risk Per Trade To Calculate The Lot Sizing Based Off
SLDistance (float) : Is The Current Position StopLoss Distance From Its Entry Price
ConversionRate (float) : Is The Currency Conversion Rate (Used For Complex Lot Sizing Only)
Returns: Float - Position Size In Units
ToLots(Units)
Converts Units To Lots
Parameters:
Units (float) : Is For How Many Units Need To Be Converted Into Lots (Minimun 1000 Units)
Returns: Float - Position Size In Lots
ToUnits(Lots)
Converts Lots To Units
Parameters:
Lots (float) : Is For How Many Lots Need To Be Converted Into Units (Minimun 0.01 Units)
Returns: Int - Position Size In Units
ToLotsInUnits(Units)
Converts Units To Lots Than Back To Units
Parameters:
Units (float) : Is For How Many Units Need To Be Converted Into Lots (Minimun 1000 Units)
Returns: Float - Position Size In Lots That Were Rounded To Units
ATRTrail(OrderType, SourceType, ATRPeriod, ATRMultiplyer, SwingLookback)
Calculate ATR Trailing Stop
Parameters:
OrderType (int) : Is To Determine A Long / Short Position, Defval = 1
SourceType (int) : Is To Determine Where To Calculate The ATR Trailing From, Defval = close
ATRPeriod (simple int) : Is To Change Its ATR Period, Defval = 20
ATRMultiplyer (float) : Is To Change Its ATR Trailing Distance, Defval = 1
SwingLookback (int) : Is To Change Its Swing HiLo Lookback (Only From Source Type 5), Defval = 7
Returns: Float - Number Of The Current ATR Trailing
DangerZone(WinRate, AvgRRR, Filter)
Calculate Danger Zone Of A Given Strategy
Parameters:
WinRate (float) : Is The Strategy WinRate
AvgRRR (float) : Is The Strategy Avg RRR
Filter (float) : Is The Minimum Profit It Needs To Be Out Of BE Zone, Defval = 3
Returns: Int - Value, 1 If Out Of Danger Zone, 0 If BE, -1 If In Danger Zone
IsQuestionableTrades(TradeTP, TradeSL)
Checks For Questionable Trades (Which Are Trades That Its TP & SL Level Got Hit At The Same Candle)
Parameters:
TradeTP (float) : Is The Trade In Question Take Profit Level
TradeSL (float) : Is The Trade In Question Stop Loss Level
Returns: Bool - True If The Last Trade Was A "Questionable Trade"
//====================================================================================================================================================
// Custom Strategy Functions
//====================================================================================================================================================
OpenLong(EntryID, LotSize, LimitPrice, StopPrice, Comment, CommentValue)
Open A Long Order Based On The Given Params
Parameters:
EntryID (string) : Is The Trade Entry ID, Defval = "Long"
LotSize (float) : Is The Lot Size Of The Trade, Defval = 1
LimitPrice (float) : Is The Limit Order Price To Set The Order At, Defval = Na / Market Order Execution
StopPrice (float) : Is The Stop Order Price To Set The Order At, Defval = Na / Market Order Execution
Comment (string) : Is The Order Comment, Defval = Long Entry Order
CommentValue (string) : Is For Custom Values In The Order Comment, Defval = Na
Returns: Void
OpenShort(EntryID, LotSize, LimitPrice, StopPrice, Comment, CommentValue)
Open A Short Order Based On The Given Params
Parameters:
EntryID (string) : Is The Trade Entry ID, Defval = "Short"
LotSize (float) : Is The Lot Size Of The Trade, Defval = 1
LimitPrice (float) : Is The Limit Order Price To Set The Order At, Defval = Na / Market Order Execution
StopPrice (float) : Is The Stop Order Price To Set The Order At, Defval = Na / Market Order Execution
Comment (string) : Is The Order Comment, Defval = Short Entry Order
CommentValue (string) : Is For Custom Values In The Order Comment, Defval = Na
Returns: Void
TP_SLExit(FromID, TPLevel, SLLevel, PercentageClose, Comment, CommentValue)
Exits Based On Predetermined TP & SL Levels
Parameters:
FromID (string) : Is The Trade ID That The TP & SL Levels Be Palced
TPLevel (float) : Is The Take Profit Level
SLLevel (float) : Is The StopLoss Level
PercentageClose (float) : Is The Amount To Close The Order At (In Percentage) Defval = 100
Comment (string) : Is The Order Comment, Defval = Exit Order
CommentValue (string) : Is For Custom Values In The Order Comment, Defval = Na
Returns: Void
CloseLong(ExitID, PercentageClose, Comment, CommentValue, Instant)
Exits A Long Order Based On A Specified Condition
Parameters:
ExitID (string) : Is The Trade ID That Will Be Closed, Defval = "Long"
PercentageClose (float) : Is The Amount To Close The Order At (In Percentage) Defval = 100
Comment (string) : Is The Order Comment, Defval = Exit Order
CommentValue (string) : Is For Custom Values In The Order Comment, Defval = Na
Instant (bool) : Is For Exit Execution Type, Defval = false
Returns: Void
CloseShort(ExitID, PercentageClose, Comment, CommentValue, Instant)
Exits A Short Order Based On A Specified Condition
Parameters:
ExitID (string) : Is The Trade ID That Will Be Closed, Defval = "Short"
PercentageClose (float) : Is The Amount To Close The Order At (In Percentage) Defval = 100
Comment (string) : Is The Order Comment, Defval = Exit Order
CommentValue (string) : Is For Custom Values In The Order Comment, Defval = Na
Instant (bool) : Is For Exit Execution Type, Defval = false
Returns: Void
BrokerCheck(Broker)
Checks Traded Broker With Current Loaded Chart Broker
Parameters:
Broker (string) : Is The Current Broker That Is Traded
Returns: Bool - True If Current Traded Broker Is Same As Loaded Chart Broker
OpenPC(LicenseID, OrderType, UseLimit, LimitPrice, SymbolPrefix, Symbol, SymbolSuffix, Risk, SL, TP, OrderComment, Spread)
Compiles Given Parameters Into An Alert String Format To Open Trades Using Pine Connector
Parameters:
LicenseID (string) : Is The Users PineConnector LicenseID
OrderType (int) : Is The Desired OrderType To Open
UseLimit (bool) : Is If We Want To Enter The Position At Exactly The Previous Closing Price
LimitPrice (float) : Is The Limit Price Of The Trade (Only For Pending Orders)
SymbolPrefix (string) : Is The Current Symbol Prefix (If Any)
Symbol (string) : Is The Traded Symbol
SymbolSuffix (string) : Is The Current Symbol Suffix (If Any)
Risk (float) : Is The Trade Risk Per Trade / Fixed Lot Sizing
SL (float) : Is The Trade SL In Price / In Pips
TP (float) : Is The Trade TP In Price / In Pips
OrderComment (string) : Is The Executed Trade Comment
Spread (float) : is The Maximum Spread For Execution
Returns: String - Pine Connector Order Syntax Alert Message
ClosePC(LicenseID, OrderType, SymbolPrefix, Symbol, SymbolSuffix)
Compiles Given Parameters Into An Alert String Format To Close Trades Using Pine Connector
Parameters:
LicenseID (string) : Is The Users PineConnector LicenseID
OrderType (int) : Is The Desired OrderType To Close
SymbolPrefix (string) : Is The Current Symbol Prefix (If Any)
Symbol (string) : Is The Traded Symbol
SymbolSuffix (string) : Is The Current Symbol Suffix (If Any)
Returns: String - Pine Connector Order Syntax Alert Message
//====================================================================================================================================================
// Custom Backtesting Calculation Functions
//====================================================================================================================================================
CalculatePNL(EntryPrice, ExitPrice, LotSize, ConversionRate)
Calculates Trade PNL Based On Entry, Eixt & Lot Size
Parameters:
EntryPrice (float) : Is The Trade Entry
ExitPrice (float) : Is The Trade Exit
LotSize (float) : Is The Trade Sizing
ConversionRate (float) : Is The Currency Conversion Rate (Used For Complex Lot Sizing Only)
Returns: Float - The Current Trade PNL
UpdateBalance(PrevBalance, PNL)
Updates The Previous Ginve Balance To The Next PNL
Parameters:
PrevBalance (float) : Is The Previous Balance To Be Updated
PNL (float) : Is The Current Trade PNL To Be Added
Returns: Float - The Current Updated PNL
CalculateSlpComm(PNL, MaxRate)
Calculates Random Slippage & Commisions Fees Based On The Parameters
Parameters:
PNL (float) : Is The Current Trade PNL
MaxRate (float) : Is The Upper Limit (In Percentage) Of The Randomized Fee
Returns: Float - A Percentage Fee Of The Current Trade PNL
UpdateDD(MaxBalance, Balance)
Calculates & Updates The DD Based On Its Given Parameters
Parameters:
MaxBalance (float) : Is The Maximum Balance Ever Recorded
Balance (float) : Is The Current Account Balance
Returns: Float - The Current Strategy DD
CalculateWR(TotalTrades, LongID, ShortID)
Calculate The Total, Long & Short Trades Win Rate
Parameters:
TotalTrades (int) : Are The Current Total Trades That The Strategy Has Taken
LongID (string) : Is The Order ID Of The Long Trades Of The Strategy
ShortID (string) : Is The Order ID Of The Short Trades Of The Strategy
Returns: Tuple Of Long WR%, Short WR%, Total WR%, Total Winning Trades, Total Losing Trades, Total Long Trades & Total Short Trades
CalculateAvgRRR(WinTrades, LossTrades)
Calculates The Overall Strategy Avg Risk Reward Ratio
Parameters:
WinTrades (int) : Are The Strategy Winning Trades
LossTrades (int) : Are The Strategy Losing Trades
Returns: Float - The Average RRR Values
CAGR(StartTime, StartPrice, EndTime, EndPrice)
Calculates The CAGR Over The Given Time Period © TradingView
Parameters:
StartTime (int) : Is The Starting Time Of The Calculation
StartPrice (float) : Is The Starting Price Of The Calculation
EndTime (int) : Is The Ending Time Of The Calculation
EndPrice (float) : Is The Ending Price Of The Calculation
Returns: Float - The CAGR Values
//====================================================================================================================================================
// Custom Plot Functions
//====================================================================================================================================================
EditLabels(LabelID, X1, Y1, Text, Color, TextColor, EditCondition, DeleteCondition)
Edit / Delete Labels
Parameters:
LabelID (label) : Is The ID Of The Selected Label
X1 (int) : Is The X1 Coordinate IN BARINDEX Xloc
Y1 (float) : Is The Y1 Coordinate IN PRICE Yloc
Text (string) : Is The Text Than Wants To Be Written In The Label
Color (color) : Is The Color Value Change Of The Label Text
TextColor (color)
EditCondition (int) : Is The Edit Condition of The Line (Setting Location / Color)
DeleteCondition (bool) : Is The Delete Condition Of The Line If Ture Deletes The Prev Itteration Of The Line
Returns: Void
EditLine(LineID, X1, Y1, X2, Y2, Color, EditCondition, DeleteCondition)
Edit / Delete Lines
Parameters:
LineID (line) : Is The ID Of The Selected Line
X1 (int) : Is The X1 Coordinate IN BARINDEX Xloc
Y1 (float) : Is The Y1 Coordinate IN PRICE Yloc
X2 (int) : Is The X2 Coordinate IN BARINDEX Xloc
Y2 (float) : Is The Y2 Coordinate IN PRICE Yloc
Color (color) : Is The Color Value Change Of The Line
EditCondition (int) : Is The Edit Condition of The Line (Setting Location / Color)
DeleteCondition (bool) : Is The Delete Condition Of The Line If Ture Deletes The Prev Itteration Of The Line
Returns: Void
//====================================================================================================================================================
// Custom Display Functions (Using Tables)
//====================================================================================================================================================
FillTable(TableID, Column, Row, Title, Value, BgColor, TextColor, ToolTip)
Filling The Selected Table With The Inputed Information
Parameters:
TableID (table) : Is The Table ID That Wants To Be Edited
Column (int) : Is The Current Column Of The Table That Wants To Be Edited
Row (int) : Is The Current Row Of The Table That Wants To Be Edited
Title (string) : Is The String Title Of The Current Cell Table
Value (string) : Is The String Value Of The Current Cell Table
BgColor (color) : Is The Selected Color For The Current Table
TextColor (color) : Is The Selected Color For The Current Table
ToolTip (string) : Is The ToolTip Of The Current Cell In The Table
Returns: Void
DisplayBTResults(TableID, BgColor, TextColor, StartingBalance, Balance, DollarReturn, TotalPips, MaxDD)
Filling The Selected Table With The Inputed Information
Parameters:
TableID (table) : Is The Table ID That Wants To Be Edited
BgColor (color) : Is The Selected Color For The Current Table
TextColor (color) : Is The Selected Color For The Current Table
StartingBalance (float) : Is The Account Starting Balance
Balance (float)
DollarReturn (float) : Is The Account Dollar Reture
TotalPips (float) : Is The Total Pips Gained / loss
MaxDD (float) : Is The Maximum Drawdown Over The Backtesting Period
Returns: Void
DisplayBTResultsV2(TableID, BgColor, TextColor, TotalWR, QTCount, LongWR, ShortWR, InitialCapital, CumProfit, CumFee, AvgRRR, MaxDD, CAGR, MeanDD)
Filling The Selected Table With The Inputed Information
Parameters:
TableID (table) : Is The Table ID That Wants To Be Edited
BgColor (color) : Is The Selected Color For The Current Table
TextColor (color) : Is The Selected Color For The Current Table
TotalWR (float) : Is The Strategy Total WR In %
QTCount (int) : Is The Strategy Questionable Trades Count
LongWR (float) : Is The Strategy Total WR In %
ShortWR (float) : Is The Strategy Total WR In %
InitialCapital (float) : Is The Strategy Initial Starting Capital
CumProfit (float) : Is The Strategy Ending Cumulative Profit
CumFee (float) : Is The Strategy Ending Cumulative Fee (Based On Randomized Fee Assumptions)
AvgRRR (float) : Is The Strategy Average Risk Reward Ratio
MaxDD (float) : Is The Strategy Maximum DrawDown In Its Backtesting Period
CAGR (float) : Is The Strategy Compounded Average GRowth In %
MeanDD (float) : Is The Strategy Mean / Average Drawdown In The Backtesting Period
Returns: Void
//====================================================================================================================================================
// Custom Pattern Detection Functions
//====================================================================================================================================================
BullFib(priceLow, priceHigh, fibRatio)
Calculates A Bullish Fibonacci Value (From Swing Low To High) © ZenAndTheArtOfTrading
Parameters:
priceLow (float)
priceHigh (float)
fibRatio (float)
Returns: The Fibonacci Value Of The Given Ratio Between The Two Price Points
BearFib(priceLow, priceHigh, fibRatio)
Calculates A Bearish Fibonacci Value (From Swing High To Low) © ZenAndTheArtOfTrading
Parameters:
priceLow (float)
priceHigh (float)
fibRatio (float)
Returns: The Fibonacci Value Of The Given Ratio Between The Two Price Points
GetBodySize()
Gets The Current Candle Body Size IN POINTS © ZenAndTheArtOfTrading
Returns: The Current Candle Body Size IN POINTS
GetTopWickSize()
Gets The Current Candle Top Wick Size IN POINTS © ZenAndTheArtOfTrading
Returns: The Current Candle Top Wick Size IN POINTS
GetBottomWickSize()
Gets The Current Candle Bottom Wick Size IN POINTS © ZenAndTheArtOfTrading
Returns: The Current Candle Bottom Wick Size IN POINTS
GetBodyPercent()
Gets The Current Candle Body Size As A Percentage Of Its Entire Size Including Its Wicks © ZenAndTheArtOfTrading
Returns: The Current Candle Body Size IN PERCENTAGE
GetTopWickPercent()
Gets The Current Top Wick Size As A Percentage Of Its Entire Body Size
Returns: Float - The Current Candle Top Wick Size IN PERCENTAGE
GetBottomWickPercent()
Gets The Current Bottom Wick Size As A Percentage Of Its Entire Bodu Size
Returns: Float - The Current Candle Bottom Size IN PERCENTAGE
BullishEC(Allowance, RejectionWickSize, EngulfWick, NearSwings, SwingLookBack)
Checks If The Current Bar Is A Bullish Engulfing Candle
Parameters:
Allowance (int) : To Give Flexibility Of Engulfing Pattern Detection In Markets That Have Micro Gaps, Defval = 0
RejectionWickSize (float) : To Filter Out long (Upper And Lower) Wick From The Bullsih Engulfing Pattern, Defval = na
EngulfWick (bool) : To Specify If We Want The Pattern To Also Engulf Its Upper & Lower Previous Wicks, Defval = false
NearSwings (bool) : To Specify If We Want The Pattern To Be Near A Recent Swing Low, Defval = true
SwingLookBack (int) : To Specify How Many Bars Back To Detect A Recent Swing Low, Defval = 10
Returns: Bool - True If The Current Bar Matches The Requirements of a Bullish Engulfing Candle
BearishEC(Allowance, RejectionWickSize, EngulfWick, NearSwings, SwingLookBack)
Checks If The Current Bar Is A Bearish Engulfing Candle
Parameters:
Allowance (int) : To Give Flexibility Of Engulfing Pattern Detection In Markets That Have Micro Gaps, Defval = 0
RejectionWickSize (float) : To Filter Out long (Upper And Lower) Wick From The Bearish Engulfing Pattern, Defval = na
EngulfWick (bool) : To Specify If We Want The Pattern To Also Engulf Its Upper & Lower Previous Wicks, Defval = false
NearSwings (bool) : To Specify If We Want The Pattern To Be Near A Recent Swing High, Defval = true
SwingLookBack (int) : To Specify How Many Bars Back To Detect A Recent Swing High, Defval = 10
Returns: Bool - True If The Current Bar Matches The Requirements of a Bearish Engulfing Candle
Hammer(Fib, ColorMatch, NearSwings, SwingLookBack, ATRFilterCheck, ATRPeriod)
Checks If The Current Bar Is A Hammer Candle
Parameters:
Fib (float) : To Specify Which Fibonacci Ratio To Use When Determining The Hammer Candle, Defval = 0.382 Ratio
ColorMatch (bool) : To Filter Only Bullish Closed Hammer Candle Pattern, Defval = false
NearSwings (bool) : To Specify If We Want The Doji To Be Near A Recent Swing Low, Defval = true
SwingLookBack (int) : To Specify How Many Bars Back To Detect A Recent Swing Low, Defval = 10
ATRFilterCheck (float) : To Filter Smaller Hammer Candles That Might Be Better Classified As A Doji Candle, Defval = 1
ATRPeriod (simple int) : To Change ATR Period Of The ATR Filter, Defval = 20
Returns: Bool - True If The Current Bar Matches The Requirements of a Hammer Candle
Star(Fib, ColorMatch, NearSwings, SwingLookBack, ATRFilterCheck, ATRPeriod)
Checks If The Current Bar Is A Hammer Candle
Parameters:
Fib (float) : To Specify Which Fibonacci Ratio To Use When Determining The Hammer Candle, Defval = 0.382 Ratio
ColorMatch (bool) : To Filter Only Bullish Closed Hammer Candle Pattern, Defval = false
NearSwings (bool) : To Specify If We Want The Doji To Be Near A Recent Swing Low, Defval = true
SwingLookBack (int) : To Specify How Many Bars Back To Detect A Recent Swing Low, Defval = 10
ATRFilterCheck (float) : To Filter Smaller Hammer Candles That Might Be Better Classified As A Doji Candle, Defval = 1
ATRPeriod (simple int) : To Change ATR Period Of The ATR Filter, Defval = 20
Returns: Bool - True If The Current Bar Matches The Requirements of a Hammer Candle
Doji(MaxWickSize, MaxBodySize, DojiType, NearSwings, SwingLookBack)
Checks If The Current Bar Is A Doji Candle
Parameters:
MaxWickSize (float) : To Specify The Maximum Lenght Of Its Upper & Lower Wick, Defval = 2
MaxBodySize (float) : To Specify The Maximum Lenght Of Its Candle Body IN PERCENT, Defval = 0.05
DojiType (int)
NearSwings (bool) : To Specify If We Want The Doji To Be Near A Recent Swing High / Low (Only In Dragonlyf / Gravestone Mode), Defval = true
SwingLookBack (int) : To Specify How Many Bars Back To Detect A Recent Swing High / Low (Only In Dragonlyf / Gravestone Mode), Defval = 10
Returns: Bool - True If The Current Bar Matches The Requirements of a Doji Candle
BullishIB(Allowance, RejectionWickSize, EngulfWick, NearSwings, SwingLookBack)
Checks If The Current Bar Is A Bullish Harami Candle
Parameters:
Allowance (int) : To Give Flexibility Of Harami Pattern Detection In Markets That Have Micro Gaps, Defval = 0
RejectionWickSize (float) : To Filter Out long (Upper And Lower) Wick From The Bullsih Harami Pattern, Defval = na
EngulfWick (bool) : To Specify If We Want The Pattern To Also Engulf Its Upper & Lower Previous Wicks, Defval = false
NearSwings (bool) : To Specify If We Want The Pattern To Be Near A Recent Swing Low, Defval = true
SwingLookBack (int) : To Specify How Many Bars Back To Detect A Recent Swing Low, Defval = 10
Returns: Bool - True If The Current Bar Matches The Requirements of a Bullish Harami Candle
BearishIB(Allowance, RejectionWickSize, EngulfWick, NearSwings, SwingLookBack)
Checks If The Current Bar Is A Bullish Harami Candle
Parameters:
Allowance (int) : To Give Flexibility Of Harami Pattern Detection In Markets That Have Micro Gaps, Defval = 0
RejectionWickSize (float) : To Filter Out long (Upper And Lower) Wick From The Bearish Harami Pattern, Defval = na
EngulfWick (bool) : To Specify If We Want The Pattern To Also Engulf Its Upper & Lower Previous Wicks, Defval = false
NearSwings (bool) : To Specify If We Want The Pattern To Be Near A Recent Swing High, Defval = true
SwingLookBack (int) : To Specify How Many Bars Back To Detect A Recent Swing High, Defval = 10
Returns: Bool - True If The Current Bar Matches The Requirements of a Bearish Harami Candle
//====================================================================================================================================================
// Custom Time Functions
//====================================================================================================================================================
BarInSession(sess, useFilter)
Determines if the current price bar falls inside the specified session © ZenAndTheArtOfTrading
Parameters:
sess (simple string)
useFilter (bool)
Returns: A boolean - true if the current bar falls within the given time session
BarOutSession(sess, useFilter)
Determines if the current price bar falls outside the specified session © ZenAndTheArtOfTrading
Parameters:
sess (simple string)
useFilter (bool)
Returns: A boolean - true if the current bar falls outside the given time session
DateFilter(startTime, endTime)
Determines if this bar's time falls within date filter range © ZenAndTheArtOfTrading
Parameters:
startTime (int)
endTime (int)
Returns: A boolean - true if the current bar falls within the given dates
DayFilter(monday, tuesday, wednesday, thursday, friday, saturday, sunday)
Checks if the current bar's day is in the list of given days to analyze © ZenAndTheArtOfTrading
Parameters:
monday (bool)
tuesday (bool)
wednesday (bool)
thursday (bool)
friday (bool)
saturday (bool)
sunday (bool)
Returns: A boolean - true if the current bar's day is one of the given days
AUSSess()
Checks If The Current Australian Forex Session In Running
Returns: Bool - True If Currently The Australian Session Is Running
ASIASess()
Checks If The Current Asian Forex Session In Running
Returns: Bool - True If Currently The Asian Session Is Running
EURSess()
Checks If The Current European Forex Session In Running
Returns: Bool - True If Currently The European Session Is Running
USSess()
Checks If The Current US Forex Session In Running
Returns: Bool - True If Currently The US Session Is Running
UNIXToDate(Time, ConversionType, TimeZone)
Converts UNIX Time To Datetime
Parameters:
Time (int) : Is The UNIX Time Input
ConversionType (int) : Is The Datetime Output Format, Defval = DD-MM-YYYY
TimeZone (string) : Is To Convert The Outputed Datetime Into The Specified Time Zone, Defval = Exchange Time Zone
Returns: String - String Of Datetime
A股趋势跟踪买卖点策略//@version=6
indicator("A股趋势跟踪买卖点策略", overlay=true)
// ===== 参数设置 =====
// 趋势参数
trendLength = input.int(50, title="趋势周期", minval=20, maxval=100)
atrLength = input.int(14, title="ATR周期", minval=5, maxval=30)
trendFilter = input.float(1.5, title="趋势过滤倍数", minval=1.0, maxval=3.0, step=0.1)
// 相对强度参数
rsPeriod = input.int(30, title="相对强度周期", minval=10, maxval=100)
rsThreshold = input.float(70, title="相对强度阈值", minval=50, maxval=90)
// 成交量参数
volumeMultiplier = input.float(1.5, title="成交量放大阈值", minval=1.0, maxval=3.0, step=0.1)
// 风险管理参数
stopLossMultiplier = input.float(1.0, title="止损ATR倍数", minval=0.5, maxval=2.0, step=0.1)
profitTargetPct = input.float(20.0, title="止盈目标百分比", minval=10.0, maxval=50.0, step=0.5) / 100
// ===== 核心逻辑 =====
// 1. 趋势判断
atr = ta.atr(atrLength)
trendUp = close > ta.sma(close, trendLength) + atr * trendFilter
trendDown = close < ta.sma(close, trendLength) - atr * trendFilter
// 2. 相对强度(RS)计算
marketIndex = request.security("SH000001", timeframe.period, close) // 上证指数
stockReturn = (close - close ) / close
marketReturn = (marketIndex - marketIndex ) / marketIndex
relativeStrength = (stockReturn - marketReturn) * 100
rsValid = relativeStrength >= rsThreshold
// 3. 成交量放大条件
volumeAvg = ta.sma(volume, 50)
volumeSpike = volume > volumeAvg * volumeMultiplier
// 4. 买入条件:趋势向上 + 相对强度强 + 成交量放大
buyCondition = trendUp and rsValid and volumeSpike
// 5. 卖出条件:趋势向下或触发止盈止损
var float entryPrice = na
var bool positionActive = false
if buyCondition and not positionActive
entryPrice := close
positionActive := true
takeProfitLevel = entryPrice * (1 + profitTargetPct)
stopLossLevel = entryPrice * (1 - stopLossMultiplier * atr / entryPrice)
sellCondition = positionActive and (trendDown or close >= takeProfitLevel or close <= stopLossLevel)
// ===== 可视化 =====
// 绘制趋势线
plot(ta.sma(close, trendLength), color=color.blue, title="趋势线")
// 绘制相对强度
hline(rsThreshold, "RS阈值", color=color.orange)
plot(relativeStrength, color=color.purple, title="相对强度")
// 绘制买卖信号
plotshape(series=buyCondition, title="买入信号", location=location.belowbar,
color=color.green, style=shape.labelup, text="买入",
textcolor=color.white, size=size.normal)
plotshape(series=sellCondition, title="卖出信号", location=location.abovebar,
color=color.red, style=shape.labeldown, text="卖出",
textcolor=color.white, size=size.normal)
// ===== 警报 =====
alertcondition(buyCondition, title="买入信号",
message="趋势向上 + 相对强度强 + 成交量放大")
alertcondition(sellCondition, title="卖出信号",
message="趋势向下或触发止盈止损")