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!
Cerca negli script per "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.
Short vs Long MA Crossover Alerts• This indicator spot potential reversal of the market while identifying Accumulation/Distribution zones.
• It is compatible with any instrument and timeframe; parameters should be adapted at will. Each levels can act like support and resistance.
• The blue dots appear when the oscillator is piercing the +200 overbought level of the -200 oversold level.
• Matrix series technical indicators are mathematical calculations applied to stock market data to provide insights and signals for investors. These
indicators analyze historical price and volume data to identify patterns, trends, and potential trading opportunities. They are based on the principle
that past price behavior can help predict future price movements.
• Matrix series indicators utilize various mathematical formulas and statistical techniques to generate signals. They can be broadly categorized into
trend-following indicators, oscillators, and volatility indicators.
• Trend-following indicators, such as moving averages, assess the direction and strength of a stock's trend. They help investors identify if a stock is in
an uptrend, downtrend, or sideways consolidation phase.
• Oscillators, such as the relative strength index (RSI) or stochastic oscillator, measure the momentum and overbought/oversold conditions of a stock.
These indicators indicate whether a stock is overbought (potentially due for a downward correction) or oversold (possibly poised for an upward
bounce).
• Volatility indicators, such as Bollinger Bands or Average True Range (ATR), measure the volatility or price range of a stock. They provide insights into
potential breakouts or trend reversals based on changes in volatility levels.
• Overall, matrix series technical indicators assist investors in making informed decisions by providing visual representations or numerical values that can help identify potential entry or exit points in the stock market.
Market Sessions with Volume Profile - By LeviathanLondon Breakout Strategy Basics
The London breakout strategy aims to capitalize on the increased volatility that occurs when the London session opens. This strategy focuses on breakouts from the Asia session range, typically from 08:00 GMT (London open) to around 12:00 GMT. The idea is to catch the early momentum of the London session as price breaks out of the consolidation range established during the Asia session.
1. Identify Breakout Levels:
The Asia and London sessions are already drawn on the chart.
Focus on the high and low of the Asia session (19:00 GMT - 08:00 GMT) as key breakout levels for the London session.
Asia session high = Resistance.
Asia session low = Support.
2. Wait for Breakout: Watch for price to break either above the Asia session high or below the Asia session low.
A breakout above the Asia high signals a potential long trade, while a breakout below the Asia low signals a potential short trade.
3. RSI & MACD Confirmation:
RSI (Relative Strength Index):
For long trades, ensure RSI > 50 (indicating bullish momentum).
For short trades, ensure RSI < 50 (indicating bearish momentum).
MACD (Moving Average Convergence Divergence):
Look for a bullish crossover (MACD line above the signal line) for long trades.
Look for a bearish crossover (MACD line below the signal line) for short trades.
Confirm the MACD histogram:
Rising histogram indicates bullish momentum.
Falling histogram indicates bearish momentum.
4. Volume Confirmation:
Ensure there’s a volume spike when the breakout happens. A breakout without volume or with weak volume could indicate a fakeout.
Volume should be at least 20% higher than the average during the breakout to confirm a strong move.
5. Timeframe Strategy:
15-Minute Chart:
Use the last 3 candles to identify the overall trend.
If the last 3 candles are mostly bullish, the trend is up.
If the last 3 candles are mostly bearish, the trend is down.
5-Minute Chart:
Use this timeframe to monitor the trade after entering and confirm the breakout.
1-Minute Chart:
Use the 1-minute chart for entry precision:
For long trades, enter when a 1-minute candle closes above the breakout level, confirming volume and momentum.
For short trades, enter when a 1-minute candle closes below the breakout level, confirming volume and momentum.
6. Watch for Fakeouts:
If price breaks out but quickly reverses, it’s likely a fakeout.
Stay cautious if there’s no volume spike or if RSI and MACD don’t confirm the breakout. A fakeout is usually marked by low volume or no momentum confirmation from RSI/MACD.
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.