SMC & ICT & IndicatorsSMC & ICT & Indicators
**Smart Money Concepts (SMC)** and **Inner Circle Trader (ICT)** are two methodologies used in financial analysis, particularly in forex trading. An overview of how these concepts can be used with indicators and scalping strategies:
### Smart Money Concepts (SMC)
- **Smart Money Concept**: Study how big questions (such as financial institutions) move in the market. This includes demand and supply zones, blocks (demand blocks), comprehensive zones, and price gaps (imbalances).
- **Trend Detection**: Helps understand market trends by analyzing market structure (such as structure breakout - BOS and character change - CHoCH).
### Inner Circle Trader (ICT)
- **ICT Methodology**: Developed by Michael Huddleston, it focuses on understanding how the market moves based on market liquidity and national contribution.
- **Analysis Tools**: Include Order Blocks, Fair Value Gaps (FVG), and comprehensive zones.
### Indicators
- **Technical Indicators**: Indicators such as RSI, MACD, and EMA can be combined with SMC and ICT concepts to enhance the analysis.
- **Plant Chart**: Uses market trends using advanced analysis tools.
###Scalping Hit
- **Scalping**: is a strategy that aims to achieve small targets to achieve quick goals.
- **Using SMC and ICT in scalping**: These concepts can be used as optimal entry and exit points on national market movements.
###Practical Applications
- **Identifying key market areas**: such as demand blocks and comprehensive areas.
- **Understanding the scum**: using advanced analysis tools.
- **Predicting market movements**: through concepts such as BOS and CHoCH.
Indicatori di ampiezza
All-In Overview [JKR] V2Fair Value Gap
50er SMA
200er SMA
Daily High
Daily Low
Prev. Daily High
Prev. Daily Low
Opening Price
All-In [JKR]Fair Value Gap
50er SMA
200er SMA
Daily High
Daily Low
Prev. Daily High
Prev. Daily Low
Opening Price
Fearless Indicator//@version=5
indicator('Fearless Indicator', shorttitle='Fearless Indicator', overlay=true)
// Hard-coded parameters
length = 2 // ATR Period
mult = 3.0 // ATR Multiplier
useClose = true // Use Close Price for Extremums
showLabels = true // Show Buy/Sell Labels
highlightState = true // Highlight State
awaitBarConfirmation = true // Await Bar Confirmation
atr = mult * ta.atr(length)
longStop = (useClose ? ta.highest(close, length) : ta.highest(length)) - atr
longStopPrev = nz(longStop , longStop)
longStop := close > longStopPrev ? math.max(longStop, longStopPrev) : longStop
shortStop = (useClose ? ta.lowest(close, length) : ta.lowest(length)) + atr
shortStopPrev = nz(shortStop , shortStop)
shortStop := close < shortStopPrev ? math.min(shortStop, shortStopPrev) : shortStop
var int dir = 1
dir := close > shortStopPrev ? 1 : close < longStopPrev ? -1 : dir
var color longColor = color.green
var color shortColor = color.red
var color longFillColor = color.new(color.green, 90)
var color shortFillColor = color.new(color.red, 90)
var color textColor = color.new(color.white, 0)
longStopPlot = plot(dir == 1 ? longStop : na, title='Long Stop', style=plot.style_linebr, linewidth=2, color=color.new(longColor, 0))
buySignal = dir == 1 and dir == -1
plotshape(buySignal ? longStop : na, title='Long Stop Start', location=location.absolute, style=shape.circle, size=size.tiny, color=color.new(longColor, 0))
plotshape(buySignal and showLabels ? longStop : na, title='Buy Label', text='Trap', location=location.absolute, style=shape.labelup, size=size.tiny, color=color.new(longColor, 0), textcolor=textColor)
shortStopPlot = plot(dir == 1 ? na : shortStop, title='Short Stop', style=plot.style_linebr, linewidth=2, color=color.new(shortColor, 0))
sellSignal = dir == -1 and dir == 1
plotshape(sellSignal ? shortStop : na, title='Short Stop Start', location=location.absolute, style=shape.circle, size=size.tiny, color=color.new(shortColor, 0))
plotshape(sellSignal and showLabels ? shortStop : na, title='Sell Label', text='Greed', location=location.absolute, style=shape.labeldown, size=size.tiny, color=color.new(shortColor, 0), textcolor=textColor)
midPricePlot = plot(ohlc4, title='', style=plot.style_circles, linewidth=0, display=display.none, editable=false)
longStateFillColor = highlightState ? dir == 1 ? longFillColor : na : na
shortStateFillColor = highlightState ? dir == -1 ? shortFillColor : na : na
fill(midPricePlot, longStopPlot, title='Long State Filling', color=longStateFillColor)
fill(midPricePlot, shortStopPlot, title='Short State Filling', color=shortStateFillColor)
await = awaitBarConfirmation ? barstate.isconfirmed : true
alertcondition(dir != dir and await, title='Alert: CE Direction Change', message='Fearless has changed direction!')
alertcondition(buySignal and await, title='Alert: CE Buy', message='Fearless Buy!')
alertcondition(sellSignal and await, title='Alert: CE Sell', message='Fearless Sell!')
// MACD Settings
= ta.macd(close, 12, 26, 9) // Renamed MACD to Fearless
// Fearless signals
bullishFearlessSignal = ta.crossover(fearlessLine, signalLine)
bearishFearlessSignal = ta.crossunder(fearlessLine, signalLine)
// Check if timeframe is weekly
isWeekly = timeframe.isweekly
// Plot Fearless signals as dots only on weekly timeframe
plotshape(isWeekly and bullishFearlessSignal ? low - 10 : na, title='Bullish Fearless Signal (Weekly)', location=location.absolute, size=size.small, color=color.green)
plotshape(isWeekly and bearishFearlessSignal ? high + 10 : na, title='Bearish Fearless Signal (Weekly)', location=location.absolute, size=size.small, color=color.red)
// 20 Fearless Feature (Standard Line)
fearless20 = ta.ema(close, 20) // Renamed EMA to Fearless
plot(fearless20, title="20 Fearless", color=color.blue, linewidth=2)
CVD OscillatorCVD Delta Oscillator
A momentum oscillator that measures buying and selling pressure through volume analysis, based on the principle that volume precedes price (cause and effect).
How It Works
Volume Analysis
Measures the force of buying and selling by analyzing how volume interacts with price movement within each bar
When price closes higher in a bar's range with strong volume, this indicates stronger buying pressure
When price closes lower in a bar's range with strong volume, this indicates stronger selling pressure
Momentum Measurement
Uses two EMAs (fast and slow) to smooth the volume delta
The difference between these EMAs creates an oscillator that shows:
Rising values = Buying pressure increasing
Falling values = Selling pressure increasing
Zero line crossovers = Potential shift in control between buyers and sellers
Signal Generation
Divergences
Bullish: Price falls to new lows while buying pressure increases (potential reversal up)
Bearish: Price rises to new highs while selling pressure increases (potential reversal down)
Zero-Line Crossovers
Bullish: Buying pressure overtakes selling pressure
Bearish: Selling pressure overtakes buying pressure
Practical Application
Reading the Indicator
Green columns above zero = Net buying pressure
Red columns below zero = Net selling pressure
Larger columns = Stronger pressure
Divergences and crossovers = Potential turning points
Trading Context
Helps identify when price movement has strong or weak volume support
Shows potential exhaustion points through divergences
Confirms trend changes through zero-line crossovers
Customization
Adjustable EMA periods for different trading styles
Toggle-able visual signals
Automatic alerts for all signals
All-In Overview [JKR]Fair Value Gap
50er SMA
200er SMA
Daily High
Daily Low
Prev. Daily High
Prev. Daily Low
Opening Price
Moving Average Crossover StrategyMoving Average Crossover Strategy
This strategy involves using two moving averages (MAs) with different timeframes to identify potential entry and exit points.
How it works:
Choose your moving averages:
Short-term MA: A faster-moving MA, such as a 9-period Exponential Moving Average (EMA)
Long-term MA: A slower-moving MA, such as a 21-period EMA
Identify the trend:
Bullish trend: When the short-term MA crosses above the long-term MA.
Bearish trend: When the short-term MA crosses below the long-term MA.
Enter the trade:
Buy signal: When the short-term MA crosses above the long-term MA, it's a potential buy signal.
Sell signal: When the short-term MA crosses below the long-term MA, it's a potential sell signal.
Set stop-loss and take-profit orders:
Stop-loss: Place your stop-loss order below a recent swing low (for buy trades) or above a recent swing high (for sell trades).
Take-profit: Set your take-profit order at a predetermined price target or based on a specific profit goal.
Additional Tips:
Timeframe: Use a 1-hour or 4-hour timeframe for better trend identification.
Risk management: Always use a stop-loss order to limit potential losses.
Fundamental analysis: Consider economic news and geopolitical events that may impact gold prices.
Backtesting: Test your strategy on historical data to evaluate its performance.
Practice: Practice your strategy on a demo account before risking real money.
Remember:
No strategy is foolproof. Intraday trading involves significant risk, and it's crucial to manage your risk effectively.
Continuous learning: Stay updated on market trends, economic indicators, and technical analysis techniques.
Emotional control: Avoid impulsive decisions based on fear or greed. Stick to your trading plan.
By combining technical analysis with fundamental knowledge and disciplined risk management, you can increase your chances of success in intraday XAUUSD trading
JOVA Multi-Market Adaptive Trading StrategyMulti-Market Adaptive Trading Strategy
This revised version should work correctly in Pine Script and generate trades based on the defined conditions. To use this strategy:
Copy the code into the TradingView Pine Editor.
Apply it to your chosen chart (forex, crypto, or futures).
Adjust the input parameters as needed.
Use TradingView's Strategy Tester to backtest and optimize the strategy.
Monitor the performance using the summary label and TradingView's built-in performance metrics.
Нуряй *****************
//@version=5
indicator("RICH SHORT LONG IND", overlay=true)
// Параметры скользящих средних
shortSMA_length = input(14, title="Short SMA Length")
longSMA_length = input(28, title="Long SMA Length")
// Вычисление скользящих средних
shortSMA = ta.sma(close, shortSMA_length)
longSMA = ta.sma(close, longSMA_length)
// Условия для сигналов
longCondition = ta.crossover(shortSMA, longSMA)
shortCondition = ta.crossunder(shortSMA, longSMA)
// Отображение сигналов на графике
plotshape(longCondition, style=shape.labelup, location=location.belowbar, color=color.green, size=size.small, title="Buy Signal", text="BUY")
plotshape(shortCondition, style=shape.labeldown, location=location.abovebar, color=color.red, size=size.small, title="Sell Signal", text="SELL")
// Отображение скользящих средних на графике
plot(shortSMA, color=color.green, title="Short SMA")
plot(longSMA, color=color.red, title="Long SMA")
*****************************
//@version=5
indicator('RICH SM', overlay = true, max_labels_count = 500, max_lines_count = 500, max_boxes_count = 500)
//---------------------------------------------------------------------------------------------------------------------}
//CONSTANTS & STRINGS & INPUTS
//---------------------------------------------------------------------------------------------------------------------{
BULLISH_LEG = 1
BEARISH_LEG = 0
BULLISH = +1
BEARISH = -1
GREEN = #089981
RED = #F23645
BLUE = #2157f3
GRAY = #878b94
MONO_BULLISH = #b2b5be
MONO_BEARISH = #5d606b
HISTORICAL = 'Historical'
PRESENT = 'Present'
COLORED = 'Colored'
MONOCHROME = 'Monochrome'
ALL = 'All'
BOS = 'BOS'
CHOCH = 'CHoCH'
TINY = size.tiny
SMALL = size.small
NORMAL = size.normal
ATR = 'Atr'
RANGE = 'Cumulative Mean Range'
CLOSE = 'Close'
HIGHLOW = 'High/Low'
SOLID = '⎯⎯⎯'
DASHED = '----'
DOTTED = '····'
SMART_GROUP = 'Smart Money Concepts'
INTERNAL_GROUP = 'Real Time Internal Structure'
SWING_GROUP = 'Real Time Swing Structure'
BLOCKS_GROUP = 'Order Blocks'
EQUAL_GROUP = 'EQH/EQL'
GAPS_GROUP = 'Fair Value Gaps'
LEVELS_GROUP = 'Highs & Lows MTF'
ZONES_GROUP = 'Premium & Discount Zones'
modeTooltip = 'Allows to display historical Structure or only the recent ones'
styleTooltip = 'Indicator color theme'
showTrendTooltip = 'Display additional candles with a color reflecting the current trend detected by structure'
showInternalsTooltip = 'Display internal market structure'
internalFilterConfluenceTooltip = 'Filter non significant internal structure breakouts'
showStructureTooltip = 'Display swing market Structure'
showSwingsTooltip = 'Display swing point as labels on the chart'
showHighLowSwingsTooltip = 'Highlight most recent strong and weak high/low points on the chart'
showInternalOrderBlocksTooltip = 'Display internal order blocks on the chart Number of internal order blocks to display on the chart'
showSwingOrderBlocksTooltip = 'Display swing order blocks on the chart Number of internal swing blocks to display on the chart'
orderBlockFilterTooltip = 'Method used to filter out volatile order blocks It is recommended to use the cumulative mean range method when a low amount of data is available'
orderBlockMitigationTooltip = 'Select what values to use for order block mitigation'
showEqualHighsLowsTooltip = 'Display equal highs and equal lows on the chart'
equalHighsLowsLengthTooltip = 'Number of bars used to confirm equal highs and equal lows'
equalHighsLowsThresholdTooltip = 'Sensitivity threshold in a range (0, 1) used for the detection of equal highs & lows Lower values will return fewer but more pertinent results'
showFairValueGapsTooltip = 'Display fair values gaps on the chart'
fairValueGapsThresholdTooltip = 'Filter out non significant fair value gaps'
fairValueGapsTimeframeTooltip = 'Fair value gaps timeframe'
fairValueGapsExtendTooltip = 'Determine how many bars to extend the Fair Value Gap boxes on chart'
showPremiumDiscountZonesTooltip = 'Display premium, discount, and equilibrium zones on chart'
modeInput = input.string( HISTORICAL, 'Mode', group = SMART_GROUP, tooltip = modeTooltip, options = )
styleInput = input.string( COLORED, 'Style', group = SMART_GROUP, tooltip = styleTooltip,options = )
showTrendInput = input( false, 'Color Candles', group = SMART_GROUP, tooltip = showTrendTooltip)
showInternalsInput = input( true, 'Show Internal Structure', group = INTERNAL_GROUP, tooltip = showInternalsTooltip)
showInternalBullInput = input.string( ALL, 'Bullish Structure', group = INTERNAL_GROUP, inline = 'ibull', options = )
internalBullColorInput = input( GREEN, '', group = INTERNAL_GROUP, inline = 'ibull')
showInternalBearInput = input.string( ALL, 'Bearish Structure' , group = INTERNAL_GROUP, inline = 'ibear', options = )
internalBearColorInput = input( RED, '', group = INTERNAL_GROUP, inline = 'ibear')
internalFilterConfluenceInput = input( false, 'Confluence Filter', group = INTERNAL_GROUP, tooltip = internalFilterConfluenceTooltip)
internalStructureSize = input.string( TINY, 'Internal Label Size', group = INTERNAL_GROUP, options = )
showStructureInput = input( true, 'Show Swing Structure', group = SWING_GROUP, tooltip = showStructureTooltip)
showSwingBullInput = input.string( ALL, 'Bullish Structure', group = SWING_GROUP, inline = 'bull', options = )
swingBullColorInput = input( GREEN, '', group = SWING_GROUP, inline = 'bull')
showSwingBearInput = input.string( ALL, 'Bearish Structure', group = SWING_GROUP, inline = 'bear', options = )
swingBearColorInput = input( RED, '', group = SWING_GROUP, inline = 'bear')
swingStructureSize = input.string( SMALL, 'Swing Label Size', group = SWING_GROUP, options = )
showSwingsInput = input( false, 'Show Swings Points', group = SWING_GROUP, tooltip = showSwingsTooltip,inline = 'swings')
swingsLengthInput = input.int( 50, '', group = SWING_GROUP, minval = 10, inline = 'swings')
showHighLowSwingsInput = input( true, 'Show Strong/Weak High/Low',group = SWING_GROUP, tooltip = showHighLowSwingsTooltip)
showInternalOrderBlocksInput = input( true, 'Internal Order Blocks' , group = BLOCKS_GROUP, tooltip = showInternalOrderBlocksTooltip, inline = 'iob')
internalOrderBlocksSizeInput = input.int( 5, '', group = BLOCKS_GROUP, minval = 1, maxval = 20, inline = 'iob')
showSwingOrderBlocksInput = input( false, 'Swing Order Blocks', group = BLOCKS_GROUP, tooltip = showSwingOrderBlocksTooltip, inline = 'ob')
swingOrderBlocksSizeInput = input.int( 5, '', group = BLOCKS_GROUP, minval = 1, maxval = 20, inline = 'ob')
orderBlockFilterInput = input.string( 'Atr', 'Order Block Filter', group = BLOCKS_GROUP, tooltip = orderBlockFilterTooltip, options = )
orderBlockMitigationInput = input.string( HIGHLOW, 'Order Block Mitigation', group = BLOCKS_GROUP, tooltip = orderBlockMitigationTooltip, options = )
internalBullishOrderBlockColor = input.color(color.new(#3179f5, 80), 'Internal Bullish OB', group = BLOCKS_GROUP)
internalBearishOrderBlockColor = input.color(color.new(#f77c80, 80), 'Internal Bearish OB', group = BLOCKS_GROUP)
swingBullishOrderBlockColor = input.color(color.new(#1848cc, 80), 'Bullish OB', group = BLOCKS_GROUP)
swingBearishOrderBlockColor = input.color(color.new(#b22833, 80), 'Bearish OB', group = BLOCKS_GROUP)
showEqualHighsLowsInput = input( true, 'Equal High/Low', group = EQUAL_GROUP, tooltip = showEqualHighsLowsTooltip)
equalHighsLowsLengthInput = input.int( 3, 'Bars Confirmation', group = EQUAL_GROUP, tooltip = equalHighsLowsLengthTooltip, minval = 1)
equalHighsLowsThresholdInput = input.float( 0.1, 'Threshold', group = EQUAL_GROUP, tooltip = equalHighsLowsThresholdTooltip, minval = 0, maxval = 0.5, step = 0.1)
equalHighsLowsSizeInput = input.string( TINY, 'Label Size', group = EQUAL_GROUP, options = )
showFairValueGapsInput = input( false, 'Fair Value Gaps', group = GAPS_GROUP, tooltip = showFairValueGapsTooltip)
fairValueGapsThresholdInput = input( true, 'Auto Threshold', group = GAPS_GROUP, tooltip = fairValueGapsThresholdTooltip)
fairValueGapsTimeframeInput = input.timeframe('', 'Timeframe', group = GAPS_GROUP, tooltip = fairValueGapsTimeframeTooltip)
fairValueGapsBullColorInput = input.color(color.new(#00ff68, 70), 'Bullish FVG' , group = GAPS_GROUP)
fairValueGapsBearColorInput = input.color(color.new(#ff0008, 70), 'Bearish FVG' , group = GAPS_GROUP)
fairValueGapsExtendInput = input.int( 1, 'Extend FVG', group = GAPS_GROUP, tooltip = fairValueGapsExtendTooltip, minval = 0)
showDailyLevelsInput = input( false, 'Daily', group = LEVELS_GROUP, inline = 'daily')
dailyLevelsStyleInput = input.string( SOLID, '', group = LEVELS_GROUP, inline = 'daily', options = )
dailyLevelsColorInput = input( BLUE, '', group = LEVELS_GROUP, inline = 'daily')
showWeeklyLevelsInput = input( false, 'Weekly', group = LEVELS_GROUP, inline = 'weekly')
weeklyLevelsStyleInput = input.string( SOLID, '', group = LEVELS_GROUP, inline = 'weekly', options = )
weeklyLevelsColorInput = input( BLUE, '', group = LEVELS_GROUP, inline = 'weekly')
showMonthlyLevelsInput = input( false, 'Monthly', group = LEVELS_GROUP, inline = 'monthly')
monthlyLevelsStyleInput = input.string( SOLID, '', group = LEVELS_GROUP, inline = 'monthly', options = )
monthlyLevelsColorInput = input( BLUE, '', group = LEVELS_GROUP, inline = 'monthly')
showPremiumDiscountZonesInput = input( false, 'Premium/Discount Zones', group = ZONES_GROUP , tooltip = showPremiumDiscountZonesTooltip)
premiumZoneColorInput = input.color( RED, 'Premium Zone', group = ZONES_GROUP)
equilibriumZoneColorInput = input.color( GRAY, 'Equilibrium Zone', group = ZONES_GROUP)
discountZoneColorInput = input.color( GREEN, 'Discount Zone', group = ZONES_GROUP)
//---------------------------------------------------------------------------------------------------------------------}
//DATA STRUCTURES & VARIABLES
//---------------------------------------------------------------------------------------------------------------------{
// @type UDT representing alerts as bool fields
// @field internalBullishBOS internal structure custom alert
// @field internalBearishBOS internal structure custom alert
// @field internalBullishCHoCH internal structure custom alert
// @field internalBearishCHoCH internal structure custom alert
// @field swingBullishBOS swing structure custom alert
// @field swingBearishBOS swing structure custom alert
// @field swingBullishCHoCH swing structure custom alert
// @field swingBearishCHoCH swing structure custom alert
// @field internalBullishOrderBlock internal order block custom alert
// @field internalBearishOrderBlock internal order block custom alert
// @field swingBullishOrderBlock swing order block custom alert
// @field swingBearishOrderBlock swing order block custom alert
// @field equalHighs equal high low custom alert
// @field equalLows equal high low custom alert
// @field bullishFairValueGap fair value gap custom alert
// @field bearishFairValueGap fair value gap custom alert
type alerts
bool internalBullishBOS = false
bool internalBearishBOS = false
bool internalBullishCHoCH = false
bool internalBearishCHoCH = false
bool swingBullishBOS = false
bool swingBearishBOS = false
bool swingBullishCHoCH = false
bool swingBearishCHoCH = false
bool internalBullishOrderBlock = false
bool internalBearishOrderBlock = false
bool swingBullishOrderBlock = false
bool swingBearishOrderBlock = false
bool equalHighs = false
bool equalLows = false
bool bullishFairValueGap = false
bool bearishFairValueGap = false
// @type UDT representing last swing extremes (top & bottom)
// @field top last top swing price
// @field bottom last bottom swing price
// @field barTime last swing bar time
// @field barIndex last swing bar index
// @field lastTopTime last top swing time
// @field lastBottomTime last bottom swing time
type trailingExtremes
float top
float bottom
int barTime
int barIndex
int lastTopTime
int lastBottomTime
// @type UDT representing Fair Value Gaps
// @field top top price
// @field bottom bottom price
// @field bias bias (BULLISH or BEARISH)
// @field topBox top box
// @field bottomBox bottom box
type fairValueGap
float top
float bottom
int bias
box topBox
box bottomBox
// @type UDT representing trend bias
// @field bias BULLISH or BEARISH
type trend
int bias
// @type UDT representing Equal Highs Lows display
// @field l_ine displayed line
// @field l_abel displayed label
type equalDisplay
line l_ine = na
label l_abel = na
// @type UDT representing a pivot point (swing point)
// @field currentLevel current price level
// @field lastLevel last price level
// @field crossed true if price level is crossed
// @field barTime bar time
// @field barIndex bar index
type pivot
float currentLevel
float lastLevel
bool crossed
int barTime = time
int barIndex = bar_index
// @type UDT representing an order block
// @field barHigh bar high
// @field barLow bar low
// @field barTime bar time
// @field bias BULLISH or BEARISH
type orderBlock
float barHigh
float barLow
int barTime
int bias
// @variable current swing pivot high
var pivot swingHigh = pivot.new(na,na,false)
// @variable current swing pivot low
var pivot swingLow = pivot.new(na,na,false)
// @variable current internal pivot high
var pivot internalHigh = pivot.new(na,na,false)
// @variable current internal pivot low
var pivot internalLow = pivot.new(na,na,false)
// @variable current equal high pivot
var pivot equalHigh = pivot.new(na,na,false)
// @variable current equal low pivot
var pivot equalLow = pivot.new(na,na,false)
// @variable swing trend bias
var trend swingTrend = trend.new(0)
// @variable internal trend bias
var trend internalTrend = trend.new(0)
// @variable equal high display
var equalDisplay equalHighDisplay = equalDisplay.new()
// @variable equal low display
var equalDisplay equalLowDisplay = equalDisplay.new()
// @variable storage for fairValueGap UDTs
var array fairValueGaps = array.new()
// @variable storage for parsed highs
var array parsedHighs = array.new()
// @variable storage for parsed lows
var array parsedLows = array.new()
// @variable storage for raw highs
var array highs = array.new()
// @variable storage for raw lows
var array lows = array.new()
// @variable storage for bar time values
var array times = array.new()
// @variable last trailing swing high and low
var trailingExtremes trailing = trailingExtremes.new()
// @variable storage for orderBlock UDTs (swing order blocks)
var array swingOrderBlocks = array.new()
// @variable storage for orderBlock UDTs (internal order blocks)
var array internalOrderBlocks = array.new()
// @variable storage for swing order blocks boxes
var array swingOrderBlocksBoxes = array.new()
// @variable storage for internal order blocks boxes
var array internalOrderBlocksBoxes = array.new()
// @variable color for swing bullish structures
var swingBullishColor = styleInput == MONOCHROME ? MONO_BULLISH : swingBullColorInput
// @variable color for swing bearish structures
var swingBearishColor = styleInput == MONOCHROME ? MONO_BEARISH : swingBearColorInput
// @variable color for bullish fair value gaps
var fairValueGapBullishColor = styleInput == MONOCHROME ? color.new(MONO_BULLISH,70) : fairValueGapsBullColorInput
// @variable color for bearish fair value gaps
var fairValueGapBearishColor = styleInput == MONOCHROME ? color.new(MONO_BEARISH,70) : fairValueGapsBearColorInput
// @variable color for premium zone
var premiumZoneColor = styleInput == MONOCHROME ? MONO_BEARISH : premiumZoneColorInput
// @variable color for discount zone
var discountZoneColor = styleInput == MONOCHROME ? MONO_BULLISH : discountZoneColorInput
// @variable bar index on current script iteration
varip int currentBarIndex = bar_index
// @variable bar index on last script iteration
varip int lastBarIndex = bar_index
// @variable alerts in current bar
alerts currentAlerts = alerts.new()
// @variable time at start of chart
var initialTime = time
// we create the needed boxes for displaying order blocks at the first execution
if barstate.isfirst
if showSwingOrderBlocksInput
for index = 1 to swingOrderBlocksSizeInput
swingOrderBlocksBoxes.push(box.new(na,na,na,na,xloc = xloc.bar_time,extend = extend.right))
if showInternalOrderBlocksInput
for index = 1 to internalOrderBlocksSizeInput
internalOrderBlocksBoxes.push(box.new(na,na,na,na,xloc = xloc.bar_time,extend = extend.right))
// @variable source to use in bearish order blocks mitigation
bearishOrderBlockMitigationSource = orderBlockMitigationInput == CLOSE ? close : high
// @variable source to use in bullish order blocks mitigation
bullishOrderBlockMitigationSource = orderBlockMitigationInput == CLOSE ? close : low
// @variable default volatility measure
atrMeasure = ta.atr(200)
// @variable parsed volatility measure by user settings
volatilityMeasure = orderBlockFilterInput == ATR ? atrMeasure : ta.cum(ta.tr)/bar_index
// @variable true if current bar is a high volatility bar
highVolatilityBar = (high - low) >= (2 * volatilityMeasure)
// @variable parsed high
parsedHigh = highVolatilityBar ? low : high
// @variable parsed low
parsedLow = highVolatilityBar ? high : low
// we store current values into the arrays at each bar
parsedHighs.push(parsedHigh)
parsedLows.push(parsedLow)
highs.push(high)
lows.push(low)
times.push(time)
//---------------------------------------------------------------------------------------------------------------------}
//USER-DEFINED FUNCTIONS
//---------------------------------------------------------------------------------------------------------------------{
// @function Get the value of the current leg, it can be 0 (bearish) or 1 (bullish)
// @returns int
leg(int size) =>
var leg = 0
newLegHigh = high > ta.highest( size)
newLegLow = low < ta.lowest( size)
if newLegHigh
leg := BEARISH_LEG
else if newLegLow
leg := BULLISH_LEG
leg
// @function Identify whether the current value is the start of a new leg (swing)
// @param leg (int) Current leg value
// @returns bool
startOfNewLeg(int leg) => ta.change(leg) != 0
// @function Identify whether the current level is the start of a new bearish leg (swing)
// @param leg (int) Current leg value
// @returns bool
startOfBearishLeg(int leg) => ta.change(leg) == -1
// @function Identify whether the current level is the start of a new bullish leg (swing)
// @param leg (int) Current leg value
// @returns bool
startOfBullishLeg(int leg) => ta.change(leg) == +1
// @function create a new label
// @param labelTime bar time coordinate
// @param labelPrice price coordinate
// @param tag text to display
// @param labelColor text color
// @param labelStyle label style
// @returns label ID
drawLabel(int labelTime, float labelPrice, string tag, color labelColor, string labelStyle) =>
var label l_abel = na
if modeInput == PRESENT
l_abel.delete()
l_abel := label.new(chart.point.new(labelTime,na,labelPrice),tag,xloc.bar_time,color=color(na),textcolor=labelColor,style = labelStyle,size = size.small)
// @function create a new line and label representing an EQH or EQL
// @param p_ivot starting pivot
// @param level price level of current pivot
// @param size how many bars ago was the current pivot detected
// @param equalHigh true for EQH, false for EQL
// @returns label ID
drawEqualHighLow(pivot p_ivot, float level, int size, bool equalHigh) =>
equalDisplay e_qualDisplay = equalHigh ? equalHighDisplay : equalLowDisplay
string tag = 'EQL'
color equalColor = swingBullishColor
string labelStyle = label.style_label_up
if equalHigh
tag := 'EQH'
equalColor := swingBearishColor
labelStyle := label.style_label_down
if modeInput == PRESENT
line.delete( e_qualDisplay.l_ine)
label.delete( e_qualDisplay.l_abel)
e_qualDisplay.l_ine := line.new(chart.point.new(p_ivot.barTime,na,p_ivot.currentLevel), chart.point.new(time ,na,level), xloc = xloc.bar_time, color = equalColor, style = line.style_dotted)
labelPosition = math.round(0.5*(p_ivot.barIndex + bar_index - size))
e_qualDisplay.l_abel := label.new(chart.point.new(na,labelPosition,level), tag, xloc.bar_index, color = color(na), textcolor = equalColor, style = labelStyle, size = equalHighsLowsSizeInput)
// @function store current structure and trailing swing points, and also display swing points and equal highs/lows
// @param size (int) structure size
// @param equalHighLow (bool) true for displaying current highs/lows
// @param internal (bool) true for getting internal structures
// @returns label ID
getCurrentStructure(int size,bool equalHighLow = false, bool internal = false) =>
currentLeg = leg(size)
newPivot = startOfNewLeg(currentLeg)
pivotLow = startOfBullishLeg(currentLeg)
pivotHigh = startOfBearishLeg(currentLeg)
if newPivot
if pivotLow
pivot p_ivot = equalHighLow ? equalLow : internal ? internalLow : swingLow
if equalHighLow and math.abs(p_ivot.currentLevel - low ) < equalHighsLowsThresholdInput * atrMeasure
drawEqualHighLow(p_ivot, low , size, false)
p_ivot.lastLevel := p_ivot.currentLevel
p_ivot.currentLevel := low
p_ivot.crossed := false
p_ivot.barTime := time
p_ivot.barIndex := bar_index
if not equalHighLow and not internal
trailing.bottom := p_ivot.currentLevel
trailing.barTime := p_ivot.barTime
trailing.barIndex := p_ivot.barIndex
trailing.lastBottomTime := p_ivot.barTime
if showSwingsInput and not internal and not equalHighLow
drawLabel(time , p_ivot.currentLevel, p_ivot.currentLevel < p_ivot.lastLevel ? 'LL' : 'HL', swingBullishColor, label.style_label_up)
else
pivot p_ivot = equalHighLow ? equalHigh : internal ? internalHigh : swingHigh
if equalHighLow and math.abs(p_ivot.currentLevel - high ) < equalHighsLowsThresholdInput * atrMeasure
drawEqualHighLow(p_ivot,high ,size,true)
p_ivot.lastLevel := p_ivot.currentLevel
p_ivot.currentLevel := high
p_ivot.crossed := false
p_ivot.barTime := time
p_ivot.barIndex := bar_index
if not equalHighLow and not internal
trailing.top := p_ivot.currentLevel
trailing.barTime := p_ivot.barTime
trailing.barIndex := p_ivot.barIndex
trailing.lastTopTime := p_ivot.barTime
if showSwingsInput and not internal and not equalHighLow
drawLabel(time , p_ivot.currentLevel, p_ivot.currentLevel > p_ivot.lastLevel ? 'HH' : 'LH', swingBearishColor, label.style_label_down)
// @function draw line and label representing a structure
// @param p_ivot base pivot point
// @param tag test to display
// @param structureColor base color
// @param lineStyle line style
// @param labelStyle label style
// @param labelSize text size
// @returns label ID
drawStructure(pivot p_ivot, string tag, color structureColor, string lineStyle, string labelStyle, string labelSize) =>
var line l_ine = line.new(na,na,na,na,xloc = xloc.bar_time)
var label l_abel = label.new(na,na)
if modeInput == PRESENT
l_ine.delete()
l_abel.delete()
l_ine := line.new(chart.point.new(p_ivot.barTime,na,p_ivot.currentLevel), chart.point.new(time,na,p_ivot.currentLevel), xloc.bar_time, color=structureColor, style=lineStyle)
l_abel := label.new(chart.point.new(na,math.round(0.5*(p_ivot.barIndex+bar_index)),p_ivot.currentLevel), tag, xloc.bar_index, color=color(na), textcolor=structureColor, style=labelStyle, size = labelSize)
// @function delete order blocks
// @param internal true for internal order blocks
// @returns orderBlock ID
deleteOrderBlocks(bool internal = false) =>
array orderBlocks = internal ? internalOrderBlocks : swingOrderBlocks
for in orderBlocks
bool crossedOderBlock = false
if bearishOrderBlockMitigationSource > eachOrderBlock.barHigh and eachOrderBlock.bias == BEARISH
crossedOderBlock := true
if internal
currentAlerts.internalBearishOrderBlock := true
else
currentAlerts.swingBearishOrderBlock := true
else if bullishOrderBlockMitigationSource < eachOrderBlock.barLow and eachOrderBlock.bias == BULLISH
crossedOderBlock := true
if internal
currentAlerts.internalBullishOrderBlock := true
else
currentAlerts.swingBullishOrderBlock := true
if crossedOderBlock
orderBlocks.remove(index)
// @function fetch and store order blocks
// @param p_ivot base pivot point
// @param internal true for internal order blocks
// @param bias BULLISH or BEARISH
// @returns void
storeOrdeBlock(pivot p_ivot,bool internal = false,int bias) =>
if (not internal and showSwingOrderBlocksInput) or (internal and showInternalOrderBlocksInput)
array a_rray = na
int parsedIndex = na
if bias == BEARISH
a_rray := parsedHighs.slice(p_ivot.barIndex,bar_index)
parsedIndex := p_ivot.barIndex + a_rray.indexof(a_rray.max())
else
a_rray := parsedLows.slice(p_ivot.barIndex,bar_index)
parsedIndex := p_ivot.barIndex + a_rray.indexof(a_rray.min())
orderBlock o_rderBlock = orderBlock.new(parsedHighs.get(parsedIndex), parsedLows.get(parsedIndex), times.get(parsedIndex),bias)
array orderBlocks = internal ? internalOrderBlocks : swingOrderBlocks
if orderBlocks.size() >= 100
orderBlocks.pop()
orderBlocks.unshift(o_rderBlock)
// @function draw order blocks as boxes
// @param internal true for internal order blocks
// @returns void
drawOrderBlocks(bool internal = false) =>
array orderBlocks = internal ? internalOrderBlocks : swingOrderBlocks
orderBlocksSize = orderBlocks.size()
if orderBlocksSize > 0
maxOrderBlocks = internal ? internalOrderBlocksSizeInput : swingOrderBlocksSizeInput
array parsedOrdeBlocks = orderBlocks.slice(0, math.min(maxOrderBlocks,orderBlocksSize))
array b_oxes = internal ? internalOrderBlocksBoxes : swingOrderBlocksBoxes
for in parsedOrdeBlocks
orderBlockColor = styleInput == MONOCHROME ? (eachOrderBlock.bias == BEARISH ? color.new(MONO_BEARISH,80) : color.new(MONO_BULLISH,80)) : internal ? (eachOrderBlock.bias == BEARISH ? internalBearishOrderBlockColor : internalBullishOrderBlockColor) : (eachOrderBlock.bias == BEARISH ? swingBearishOrderBlockColor : swingBullishOrderBlockColor)
box b_ox = b_oxes.get(index)
b_ox.set_top_left_point( chart.point.new(eachOrderBlock.barTime,na,eachOrderBlock.barHigh))
b_ox.set_bottom_right_point(chart.point.new(last_bar_time,na,eachOrderBlock.barLow))
b_ox.set_border_color( internal ? na : orderBlockColor)
b_ox.set_bgcolor( orderBlockColor)
// @function detect and draw structures, also detect and store order blocks
// @param internal true for internal structures or order blocks
// @returns void
displayStructure(bool internal = false) =>
var bullishBar = true
var bearishBar = true
if internalFilterConfluenceInput
bullishBar := high - math.max(close, open) > math.min(close, open - low)
bearishBar := high - math.max(close, open) < math.min(close, open - low)
pivot p_ivot = internal ? internalHigh : swingHigh
trend t_rend = internal ? internalTrend : swingTrend
lineStyle = internal ? line.style_dashed : line.style_solid
labelSize = internal ? internalStructureSize : swingStructureSize
extraCondition = internal ? internalHigh.currentLevel != swingHigh.currentLevel and bullishBar : true
bullishColor = styleInput == MONOCHROME ? MONO_BULLISH : internal ? internalBullColorInput : swingBullColorInput
if ta.crossover(close,p_ivot.currentLevel) and not p_ivot.crossed and extraCondition
string tag = t_rend.bias == BEARISH ? CHOCH : BOS
if internal
currentAlerts.internalBullishCHoCH := tag == CHOCH
currentAlerts.internalBullishBOS := tag == BOS
else
currentAlerts.swingBullishCHoCH := tag == CHOCH
currentAlerts.swingBullishBOS := tag == BOS
p_ivot.crossed := true
t_rend.bias := BULLISH
displayCondition = internal ? showInternalsInput and (showInternalBullInput == ALL or (showInternalBullInput == BOS and tag != CHOCH) or (showInternalBullInput == CHOCH and tag == CHOCH)) : showStructureInput and (showSwingBullInput == ALL or (showSwingBullInput == BOS and tag != CHOCH) or (showSwingBullInput == CHOCH and tag == CHOCH))
if displayCondition
drawStructure(p_ivot,tag,bullishColor,lineStyle,label.style_label_down,labelSize)
if (internal and showInternalOrderBlocksInput) or (not internal and showSwingOrderBlocksInput)
storeOrdeBlock(p_ivot,internal,BULLISH)
p_ivot := internal ? internalLow : swingLow
extraCondition := internal ? internalLow.currentLevel != swingLow.currentLevel and bearishBar : true
bearishColor = styleInput == MONOCHROME ? MONO_BEARISH : internal ? internalBearColorInput : swingBearColorInput
if ta.crossunder(close,p_ivot.currentLevel) and not p_ivot.crossed and extraCondition
string tag = t_rend.bias == BULLISH ? CHOCH : BOS
if internal
currentAlerts.internalBearishCHoCH := tag == CHOCH
currentAlerts.internalBearishBOS := tag == BOS
else
currentAlerts.swingBearishCHoCH := tag == CHOCH
currentAlerts.swingBearishBOS := tag == BOS
p_ivot.crossed := true
t_rend.bias := BEARISH
displayCondition = internal ? showInternalsInput and (showInternalBearInput == ALL or (showInternalBearInput == BOS and tag != CHOCH) or (showInternalBearInput == CHOCH and tag == CHOCH)) : showStructureInput and (showSwingBearInput == ALL or (showSwingBearInput == BOS and tag != CHOCH) or (showSwingBearInput == CHOCH and tag == CHOCH))
if displayCondition
drawStructure(p_ivot,tag,bearishColor,lineStyle,label.style_label_up,labelSize)
if (internal and showInternalOrderBlocksInput) or (not internal and showSwingOrderBlocksInput)
storeOrdeBlock(p_ivot,internal,BEARISH)
// @function draw one fair value gap box (each fair value gap has two boxes)
// @param leftTime left time coordinate
// @param rightTime right time coordinate
// @param topPrice top price level
// @param bottomPrice bottom price level
// @param boxColor box color
// @returns box ID
fairValueGapBox(leftTime,rightTime,topPrice,bottomPrice,boxColor) => box.new(chart.point.new(leftTime,na,topPrice),chart.point.new(rightTime + fairValueGapsExtendInput * (time-time ),na,bottomPrice), xloc=xloc.bar_time, border_color = boxColor, bgcolor = boxColor)
// @function delete fair value gaps
// @returns fairValueGap ID
deleteFairValueGaps() =>
for in fairValueGaps
if (low < eachFairValueGap.bottom and eachFairValueGap.bias == BULLISH) or (high > eachFairValueGap.top and eachFairValueGap.bias == BEARISH)
eachFairValueGap.topBox.delete()
eachFairValueGap.bottomBox.delete()
fairValueGaps.remove(index)
// @function draw fair value gaps
// @returns fairValueGap ID
drawFairValueGaps() =>
= request.security(syminfo.tickerid, fairValueGapsTimeframeInput, [close , open , time , high , low , time , high , low ],lookahead = barmerge.lookahead_on)
barDeltaPercent = (lastClose - lastOpen) / (lastOpen * 100)
newTimeframe = timeframe.change(fairValueGapsTimeframeInput)
threshold = fairValueGapsThresholdInput ? ta.cum(math.abs(newTimeframe ? barDeltaPercent : 0)) / bar_index * 2 : 0
bullishFairValueGap = currentLow > last2High and lastClose > last2High and barDeltaPercent > threshold and newTimeframe
bearishFairValueGap = currentHigh < last2Low and lastClose < last2Low and -barDeltaPercent > threshold and newTimeframe
if bullishFairValueGap
currentAlerts.bullishFairValueGap := true
fairValueGaps.unshift(fairValueGap.new(currentLow,last2High,BULLISH,fairValueGapBox(lastTime,currentTime,currentLow,math.avg(currentLow,last2High),fairValueGapBullishColor),fairValueGapBox(lastTime,currentTime,math.avg(currentLow,last2High),last2High,fairValueGapBullishColor)))
if bearishFairValueGap
currentAlerts.bearishFairValueGap := true
fairValueGaps.unshift(fairValueGap.new(currentHigh,last2Low,BEARISH,fairValueGapBox(lastTime,currentTime,currentHigh,math.avg(currentHigh,last2Low),fairValueGapBearishColor),fairValueGapBox(lastTime,currentTime,math.avg(currentHigh,last2Low),last2Low,fairValueGapBearishColor)))
// @function get line style from string
// @param style line style
// @returns string
getStyle(string style) =>
switch style
SOLID => line.style_solid
DASHED => line.style_dashed
DOTTED => line.style_dotted
// @function draw MultiTimeFrame levels
// @param timeframe base timeframe
// @param sameTimeframe true if chart timeframe is same as base timeframe
// @param style line style
// @param levelColor line and text color
// @returns void
drawLevels(string timeframe, bool sameTimeframe, string style, color levelColor) =>
= request.security(syminfo.tickerid, timeframe, [high , low , time , time],lookahead = barmerge.lookahead_on)
float parsedTop = sameTimeframe ? high : topLevel
float parsedBottom = sameTimeframe ? low : bottomLevel
int parsedLeftTime = sameTimeframe ? time : leftTime
int parsedRightTime = sameTimeframe ? time : rightTime
int parsedTopTime = time
int parsedBottomTime = time
if not sameTimeframe
int leftIndex = times.binary_search_rightmost(parsedLeftTime)
int rightIndex = times.binary_search_rightmost(parsedRightTime)
array timeArray = times.slice(leftIndex,rightIndex)
array topArray = highs.slice(leftIndex,rightIndex)
array bottomArray = lows.slice(leftIndex,rightIndex)
parsedTopTime := timeArray.size() > 0 ? timeArray.get(topArray.indexof(topArray.max())) : initialTime
parsedBottomTime := timeArray.size() > 0 ? timeArray.get(bottomArray.indexof(bottomArray.min())) : initialTime
var line topLine = line.new(na, na, na, na, xloc = xloc.bar_time, color = levelColor, style = getStyle(style))
var line bottomLine = line.new(na, na, na, na, xloc = xloc.bar_time, color = levelColor, style = getStyle(style))
var label topLabel = label.new(na, na, xloc = xloc.bar_time, text = str.format('P{0}H',timeframe), color=color(na), textcolor = levelColor, size = size.small, style = label.style_label_left)
var label bottomLabel = label.new(na, na, xloc = xloc.bar_time, text = str.format('P{0}L',timeframe), color=color(na), textcolor = levelColor, size = size.small, style = label.style_label_left)
topLine.set_first_point( chart.point.new(parsedTopTime,na,parsedTop))
topLine.set_second_point( chart.point.new(last_bar_time + 20 * (time-time ),na,parsedTop))
topLabel.set_point( chart.point.new(last_bar_time + 20 * (time-time ),na,parsedTop))
bottomLine.set_first_point( chart.point.new(parsedBottomTime,na,parsedBottom))
bottomLine.set_second_point(chart.point.new(last_bar_time + 20 * (time-time ),na,parsedBottom))
bottomLabel.set_point( chart.point.new(last_bar_time + 20 * (time-time ),na,parsedBottom))
// @function true if chart timeframe is higher than provided timeframe
// @param timeframe timeframe to check
// @returns bool
higherTimeframe(string timeframe) => timeframe.in_seconds() > timeframe.in_seconds(timeframe)
// @function update trailing swing points
// @returns int
updateTrailingExtremes() =>
trailing.top := math.max(high,trailing.top)
trailing.lastTopTime := trailing.top == high ? time : trailing.lastTopTime
trailing.bottom := math.min(low,trailing.bottom)
trailing.lastBottomTime := trailing.bottom == low ? time : trailing.lastBottomTime
// @function draw trailing swing points
// @returns void
drawHighLowSwings() =>
var line topLine = line.new(na, na, na, na, color = swingBearishColor, xloc = xloc.bar_time)
var line bottomLine = line.new(na, na, na, na, color = swingBullishColor, xloc = xloc.bar_time)
var label topLabel = label.new(na, na, color=color(na), textcolor = swingBearishColor, xloc = xloc.bar_time, style = label.style_label_down, size = size.tiny)
var label bottomLabel = label.new(na, na, color=color(na), textcolor = swingBullishColor, xloc = xloc.bar_time, style = label.style_label_up, size = size.tiny)
rightTimeBar = last_bar_time + 20 * (time - time )
topLine.set_first_point( chart.point.new(trailing.lastTopTime, na, trailing.top))
topLine.set_second_point( chart.point.new(rightTimeBar, na, trailing.top))
topLabel.set_point( chart.point.new(rightTimeBar, na, trailing.top))
topLabel.set_text( swingTrend.bias == BEARISH ? 'Strong High' : 'Weak High')
bottomLine.set_first_point( chart.point.new(trailing.lastBottomTime, na, trailing.bottom))
bottomLine.set_second_point(chart.point.new(rightTimeBar, na, trailing.bottom))
bottomLabel.set_point( chart.point.new(rightTimeBar, na, trailing.bottom))
bottomLabel.set_text( swingTrend.bias == BULLISH ? 'Strong Low' : 'Weak Low')
// @function draw a zone with a label and a box
// @param labelLevel price level for label
// @param labelIndex bar index for label
// @param top top price level for box
// @param bottom bottom price level for box
// @param tag text to display
// @param zoneColor base color
// @param style label style
// @returns void
drawZone(float labelLevel, int labelIndex, float top, float bottom, string tag, color zoneColor, string style) =>
var label l_abel = label.new(na,na,text = tag, color=color(na),textcolor = zoneColor, style = style, size = size.small)
var box b_ox = box.new(na,na,na,na,bgcolor = color.new(zoneColor,80),border_color = color(na), xloc = xloc.bar_time)
b_ox.set_top_left_point( chart.point.new(trailing.barTime,na,top))
b_ox.set_bottom_right_point(chart.point.new(last_bar_time,na,bottom))
l_abel.set_point( chart.point.new(na,labelIndex,labelLevel))
// @function draw premium/discount zones
// @returns void
drawPremiumDiscountZones() =>
drawZone(trailing.top, math.round(0.5*(trailing.barIndex + last_bar_index)), trailing.top, 0.95*trailing.top + 0.05*trailing.bottom, 'Premium', premiumZoneColor, label.style_label_down)
equilibriumLevel = math.avg(trailing.top, trailing.bottom)
drawZone(equilibriumLevel, last_bar_index, 0.525*trailing.top + 0.475*trailing.bottom, 0.525*trailing.bottom + 0.475*trailing.top, 'Equilibrium', equilibriumZoneColorInput, label.style_label_left)
drawZone(trailing.bottom, math.round(0.5*(trailing.barIndex + last_bar_index)), 0.95*trailing.bottom + 0.05*trailing.top, trailing.bottom, 'Discount', discountZoneColor, label.style_label_up)
//---------------------------------------------------------------------------------------------------------------------}
//MUTABLE VARIABLES & EXECUTION
//---------------------------------------------------------------------------------------------------------------------{
parsedOpen = showTrendInput ? open : na
candleColor = internalTrend.bias == BULLISH ? swingBullishColor : swingBearishColor
plotcandle(parsedOpen,high,low,close,color = candleColor, wickcolor = candleColor, bordercolor = candleColor)
if showHighLowSwingsInput or showPremiumDiscountZonesInput
updateTrailingExtremes()
if showHighLowSwingsInput
drawHighLowSwings()
if showPremiumDiscountZonesInput
drawPremiumDiscountZones()
if showFairValueGapsInput
deleteFairValueGaps()
getCurrentStructure(swingsLengthInput,false)
getCurrentStructure(5,false,true)
if showEqualHighsLowsInput
getCurrentStructure(equalHighsLowsLengthInput,true)
if showInternalsInput or showInternalOrderBlocksInput or showTrendInput
displayStructure(true)
if showStructureInput or showSwingOrderBlocksInput or showHighLowSwingsInput
displayStructure()
if showInternalOrderBlocksInput
deleteOrderBlocks(true)
if showSwingOrderBlocksInput
deleteOrderBlocks()
if showFairValueGapsInput
drawFairValueGaps()
if barstate.islastconfirmedhistory or barstate.islast
if showInternalOrderBlocksInput
drawOrderBlocks(true)
if showSwingOrderBlocksInput
drawOrderBlocks()
lastBarIndex := currentBarIndex
currentBarIndex := bar_index
newBar = currentBarIndex != lastBarIndex
if barstate.islastconfirmedhistory or (barstate.isrealtime and newBar)
if showDailyLevelsInput and not higherTimeframe('D')
drawLevels('D',timeframe.isdaily,dailyLevelsStyleInput,dailyLevelsColorInput)
if showWeeklyLevelsInput and not higherTimeframe('W')
drawLevels('W',timeframe.isweekly,weeklyLevelsStyleInput,weeklyLevelsColorInput)
if showMonthlyLevelsInput and not higherTimeframe('M')
drawLevels('M',timeframe.ismonthly,monthlyLevelsStyleInput,monthlyLevelsColorInput)
//---------------------------------------------------------------------------------------------------------------------}
//ALERTS
//---------------------------------------------------------------------------------------------------------------------{
alertcondition(currentAlerts.internalBullishBOS, 'Internal Bullish BOS', 'Internal Bullish BOS formed')
alertcondition(currentAlerts.internalBullishCHoCH, 'Internal Bullish CHoCH', 'Internal Bullish CHoCH formed')
alertcondition(currentAlerts.internalBearishBOS, 'Internal Bearish BOS', 'Internal Bearish BOS formed')
alertcondition(currentAlerts.internalBearishCHoCH, 'Internal Bearish CHoCH', 'Internal Bearish CHoCH formed')
alertcondition(currentAlerts.swingBullishBOS, 'Bullish BOS', 'Internal Bullish BOS formed')
alertcondition(currentAlerts.swingBullishCHoCH, 'Bullish CHoCH', 'Internal Bullish CHoCH formed')
alertcondition(currentAlerts.swingBearishBOS, 'Bearish BOS', 'Bearish BOS formed')
alertcondition(currentAlerts.swingBearishCHoCH, 'Bearish CHoCH', 'Bearish CHoCH formed')
alertcondition(currentAlerts.internalBullishOrderBlock, 'Bullish Internal OB Breakout', 'Price broke bullish internal OB')
alertcondition(currentAlerts.internalBearishOrderBlock, 'Bearish Internal OB Breakout', 'Price broke bearish internal OB')
alertcondition(currentAlerts.swingBullishOrderBlock, 'Bullish Swing OB Breakout', 'Price broke bullish swing OB')
alertcondition(currentAlerts.swingBearishOrderBlock, 'Bearish Swing OB Breakout', 'Price broke bearish swing OB')
alertcondition(currentAlerts.equalHighs, 'Equal Highs', 'Equal highs detected')
alertcondition(currentAlerts.equalLows, 'Equal Lows', 'Equal lows detected')
alertcondition(currentAlerts.bullishFairValueGap, 'Bullish FVG', 'Bullish FVG formed')
alertcondition(currentAlerts.bearishFairValueGap, 'Bearish FVG', 'Bearish FVG formed')
//---------------------------------------------------------------------------------------------------------------------}
Stundenkerzen Breakout AlarmJedes mal, wenn der Stundenchart unter- oder überschritten wird, löst der Indikator einen Alarm aus.
NY SESSION CDLScript para Mostrar la Hora de Pre-Sesión de Nueva York (7:00 - 9:30 AM EST)
Este script destaca el rango de tiempo previo al inicio de la sesión de Nueva York, desde las 7:00 AM hasta las 9:30 AM (hora estándar del Este - EST). Es ideal para traders que desean visualizar el período previo a la apertura oficial del mercado, ayudando a identificar posibles zonas de consolidación, soportes, resistencias o movimientos importantes que puedan influir en la acción del precio en la sesión regular. El gráfico se ajusta automáticamente a este rango de tiempo, proporcionando una herramienta visual clara para tomar decisiones informadas en el trading.
Day's Band Lines [Prabha]It show the upper and lower band for the crossing candle.
Buying above the upperband and selling below the lowerband gives you the high profit.
нурРод
//@version=5
indicator("RICH SHORT LONG IND", overlay=true)
// Параметры скользящих средних
shortSMA_length = input(14, title="Short SMA Length")
longSMA_length = input(28, title="Long SMA Length")
// Вычисление скользящих средних
shortSMA = ta.sma(close, shortSMA_length)
longSMA = ta.sma(close, longSMA_length)
// Условия для сигналов
longCondition = ta.crossover(shortSMA, longSMA)
shortCondition = ta.crossunder(shortSMA, longSMA)
// Отображение сигналов на графике
plotshape(longCondition, style=shape.labelup, location=location.belowbar, color=color.green, size=size.small, title="Buy Signal", text="BUY")
plotshape(shortCondition, style=shape.labeldown, location=location.abovebar, color=color.red, size=size.small, title="Sell Signal", text="SELL")
// Отображение скользящих средних на графике
plot(shortSMA, color=color.green, title="Short SMA")
plot(longSMA, color=color.red, title="Long SMA")
MktCumTickThis script is a market sentiment indicator that calculates the cumulative TICK (Trade Imbalance Sentiment) for four major markets: NYSE (New York Stock Exchange), NASDAQ (National Association of Securities Dealers Automated Quotations), Dow Jones, and AMEX (American Stock Exchange).
Here's a breakdown of the script:
1. Market data requests: The script requests data for the four markets, including:
- TICK (Trade Imbalance Sentiment) data
- HLC3 (High, Low, Close) data
- ADVN (Advancing issues), DECL (Declining issues), and UNCH (Unchanged issues) data
2. Cumulative TICK calculation: The script calculates the cumulative TICK for each market by dividing the TICK data by the maximum TICK value for each market.
3. Plotting: The script plots the cumulative TICK values for each market as separate lines on the chart.
4. Background color: The script changes the background color of the chart based on the cumulative TICK values. If all four markets have decreasing cumulative TICK values, the background color turns red. If all four markets have increasing cumulative TICK values, the background color turns green.
The purpose of this indicator is to provide a visual representation of market sentiment across multiple markets. By analyzing the cumulative TICK values, traders can gain insights into market trends and make more informed trading decisions.
Some possible uses of this indicator include:
- Identifying market trends and sentiment
- Confirming trade entries and exits
- Monitoring market conditions and adjusting trading strategies accordingly
Sigma ScoreFunction and Purpose
The Sigma Score indicator is a tool for analyzing volatility and identifying unusual price movements of a financial instrument over a specified timeframe. It calculates the "Sigma Score," which measures how far the current price change deviates from its historical average in terms of standard deviations. This helps identify potential extremes and unusual market conditions.
Features
Timeframe Control
Users can select the desired timeframe for analysis (e.g., minutes, hours, days). This makes the indicator adaptable to various trading styles:
Supported timeframes: Minutes (M1, M5, M10, M15), Hours (H1, H4, H12), Days (D), Weeks (W), Months (M).
Sigma Score Calculation
The indicator computes the logarithmic return between consecutive price values.
It calculates a simple moving average (SMA) and the standard deviation (StDev) of these returns.
The Sigma Score is derived as the difference between the current return and the average, divided by the standard deviation.
Visual Representation
Sigma Score Plot: The Sigma Score is displayed as a line.
Horizontal Threshold Lines:
A middle line (0) for reference.
Upper and lower threshold lines (default: 2.0 and -2.0) for highlighting extremes.
Background Highlighting:
Green for values above the upper threshold (positive deviations).
Red for values below the lower threshold (negative deviations).
Custom Settings
Timeframe
Select the timeframe for analysis using a dropdown menu (default: D for daily).
Thresholds
Upper Threshold: Default = 2.0 (positive extreme area).
Lower Threshold: Default = -2.0 (negative extreme area).
Both values can be adjusted to modify the indicator's sensitivity.
Use Cases
Identifying Extremes: Values above or below the thresholds can signal unusual market conditions, such as overbought or oversold areas.
Analyzing Market Anomalies: The Sigma Score quantifies how unusual a price movement is based on historical data.
Visual Aid: Threshold lines and background highlighting simplify the interpretation of boundary conditions.
Notes and Limitations
Timeframe Dependency: Results may vary depending on the selected timeframe. Shorter timeframes highlight short-term movements, while longer timeframes capture broader trends.
Volatility Sensitivity: The indicator is sensitive to changes in market volatility. Sudden price swings may produce extreme Sigma values.
Summary
The Sigma Score indicator is a powerful tool for traders and analysts to quickly identify unusual market conditions and make informed decisions. Its flexibility in adjusting timeframes and thresholds makes it a versatile addition to any trading strategy.
Dynamic RSI with Overbought/Oversold LinesDynamic RSI with Overbought/Oversold Lines
This indicator enhances the traditional RSI (Relative Strength Index) by dynamically adjusting the overbought and oversold levels based on the highest and lowest RSI values over a user-defined period. The indicator plots these levels as horizontal lines, allowing traders to visually identify when the market is "overbought" or "oversold."
Features:
Dynamic Overbought/Oversold Levels: Automatically adjusts the overbought and oversold levels based on the highest and lowest RSI values within the defined period, ensuring more accurate signals tailored to the current market conditions.
Customizable RSI Period: Choose your preferred RSI period to suit your trading strategy.
Signal Alerts: Visual signals are displayed when the RSI crosses into the overbought or oversold zone, indicating potential reversal points.
Background Color Alerts: The background changes color when the RSI exceeds overbought or oversold levels, making it easier to spot these important zones at a glance.
Clean and Simple: A minimalist design focusing on the key elements, making it suitable for all traders.
How to Use:
Overbought Zone: When the RSI moves above the overbought line (red), it may indicate that the asset is overbought, signaling a potential price reversal or pullback.
Oversold Zone: When the RSI moves below the oversold line (green), it may indicate that the asset is oversold, signaling a potential price bounce or reversal.
This dynamic RSI indicator is perfect for those looking to capture market extremes and improve their trading decisions. It's especially useful for timeframes like 30-minute and 1-hour charts, where market conditions tend to shift more rapidly.
Volume Index (0-100)Volume Index (0-100) Indicator
The Volume Index (0-100) indicator is a powerful tool designed to help traders understand current volume levels in relation to past activity over a specified period. By normalizing volume data to a scale from 0 to 100, this indicator makes it easy to compare today's volume against recent history and gauge the strength of market movements.
Key Features:
Normalized Volume Index: The indicator indexes volume between 0 and 100, allowing traders to easily determine if the current volume is unusually high or low compared to recent trends.
Colored Visualization: The line graph is colored green for positive volume (increasing activity) and red for negative volume (decreasing activity). This helps traders quickly grasp the market sentiment and volume direction.
User-Defined Lookback Period: Traders can customize the lookback period to best fit their trading strategy, providing flexibility for different market conditions.
How Traders Can Use It:
Identifying Volume Extremes: The Volume Index helps identify periods of unusually high or low volume. Values approaching 100 indicate high volume, while values close to 0 indicate low volume.
Confirmation Tool: During price movements, high volume (near 100) can act as a confirmation signal for the strength of the trend. For instance, a high volume during an uptrend may indicate strong buying interest.
Divergence Analysis: Traders can look for divergences between volume and price. For example, if the price is consolidating while the Volume Index remains high, it could signal an impending breakout.
Volume Alerts: The indicator includes an alert feature when the Volume Index exceeds 80, helping traders stay informed about potential shifts in market volatility.
Support, Resistance, MA, and ADXSummary
This comprehensive script provides traders with a tool that highlights critical levels of support and resistance, detects significant price breakouts with volume confirmation, identifies potential reversals with wick analysis, and plots a moving average that changes color based on trend strength as indicated by the ADX. It is useful for spotting entry and exit points, confirming breakouts, and identifying trend direction and strength.
Edwin K Stochastic Candle ColorsThe Stochastic Candle Colors indicator highlights price action using candle colors based on signals from the stochastic oscillator. Here's how to use it:
1. Indicator Purpose
This indicator overlays on your price chart and changes candle colors based on stochastic oscillator signals:
Green candles: Indicate a bullish signal when the %K line crosses above the %D line in an oversold area (below 20).
Red candles: Indicate a bearish signal when the %K line crosses below the %D line in an overbought area (above 80).
2. How to Use the Inputs
K (periodK): The lookback period for calculating the %K line of the stochastic oscillator. A smaller value makes the indicator more sensitive to price changes.
D (periodD): The period for smoothing the %K line to get the %D line. A larger value creates smoother signals but may result in delays.
Smooth (smoothK): The additional smoothing applied to the %K line before calculating the %D line. This helps reduce noise.
3. How to Interpret the Candle Colors
Green Candle:
Occurs when the %K line crosses above the %D line in the oversold zone (below 20).
Signals a potential bullish reversal.
Red Candle:
Occurs when the %K line crosses below the %D line in the overbought zone (above 80).
Signals a potential bearish reversal.
No Color:
No crossover occurs, or the crossover doesn't happen in overbought/oversold zones.
4. Application in Trading
Entry Points:
Buy when you see a green candle and confirm with other indicators or chart patterns.
Sell when you see a red candle and confirm with additional signals.
Trend Context:
Combine this indicator with trend-following tools like moving averages or support/resistance levels to improve accuracy.
Stop Loss/Take Profit:
Use nearby swing highs/lows for stop-loss placement.
Set profit targets based on risk-reward ratios or key levels.
5. Customization
Adjust the input parameters (K, D, and Smooth) to align the indicator's sensitivity with your trading style:
Short-term traders might prefer lower values for quicker signals.
Long-term traders might opt for higher values for smoother, more reliable signals.
6. Limitations
Signals in isolation might not be reliable. Always use this indicator in conjunction with other tools.
Avoid using during low volatility or sideways markets as stochastic oscillators can produce false signals.
MACD, ADX & RSI -> for altcoins# MACD + ADX + RSI Combined Indicator
## Overview
This advanced technical analysis tool combines three powerful indicators (MACD, ADX, and RSI) into a single view, providing a comprehensive analysis of trend, momentum, and divergence signals. The indicator is designed to help traders identify potential trading opportunities by analyzing multiple aspects of price action simultaneously.
## Components
### 1. MACD (Moving Average Convergence Divergence)
- **Purpose**: Identifies trend direction and momentum
- **Components**:
- Fast EMA (default: 12 periods)
- Slow EMA (default: 26 periods)
- Signal Line (default: 9 periods)
- Histogram showing the difference between MACD and Signal line
- **Visual**:
- Blue line: MACD line
- Orange line: Signal line
- Green/Red histogram: MACD histogram
- **Interpretation**:
- Histogram color changes indicate potential trend shifts
- Crossovers between MACD and Signal lines suggest entry/exit points
### 2. ADX (Average Directional Index)
- **Purpose**: Measures trend strength and direction
- **Components**:
- ADX line (default threshold: 20)
- DI+ (Positive Directional Indicator)
- DI- (Negative Directional Indicator)
- **Visual**:
- Navy blue line: ADX
- Green line: DI+
- Red line: DI-
- **Interpretation**:
- ADX > 20 indicates a strong trend
- DI+ crossing above DI- suggests bullish momentum
- DI- crossing above DI+ suggests bearish momentum
### 3. RSI (Relative Strength Index)
- **Purpose**: Identifies overbought/oversold conditions and divergences
- **Components**:
- RSI line (default: 14 periods)
- Divergence detection
- **Visual**:
- Purple line: RSI
- Horizontal lines at 70 (overbought) and 30 (oversold)
- Divergence labels ("Bull" and "Bear")
- **Interpretation**:
- RSI > 70: Potentially overbought
- RSI < 30: Potentially oversold
- Bullish/Bearish divergences indicate potential trend reversals
## Alert System
The indicator includes several automated alerts:
1. **MACD Alerts**:
- Rising to falling histogram transitions
- Falling to rising histogram transitions
2. **RSI Divergence Alerts**:
- Bullish divergence formations
- Bearish divergence formations
3. **ADX Trend Alerts**:
- Strong trend development (ADX crossing threshold)
- DI+ crossing above DI- (bullish)
- DI- crossing above DI+ (bearish)
## Settings Customization
All components can be fine-tuned through the settings panel:
### MACD Settings
- Fast Length
- Slow Length
- Signal Smoothing
- Source
- MA Type options (SMA/EMA)
### ADX Settings
- Length
- Threshold level
### RSI Settings
- RSI Length
- Source
- Divergence calculation toggle
## Usage Guidelines
### Entry Signals
Strong entry signals typically occur when multiple components align:
1. MACD histogram color change
2. ADX showing strong trend (>20)
3. RSI showing divergence or leaving oversold/overbought zones
### Exit Signals
Consider exits when:
1. MACD crosses signal line in opposite direction
2. ADX shows weakening trend
3. RSI reaches extreme levels with divergence
### Risk Management
- Use the indicator as part of a complete trading strategy
- Combine with price action and support/resistance levels
- Consider multiple timeframe analysis for confirmation
- Don't rely solely on any single component
## Technical Notes
- Built for TradingView using Pine Script v5
- Compatible with all timeframes
- Optimized for real-time calculation
- Includes proper error handling and NA value management
- Memory-efficient calculations for smooth performance
## Installation
1. Copy the provided Pine Script code
2. Open TradingView Chart
3. Create New Indicator -> Pine Editor
4. Paste the code and click "Add to Chart"
5. Adjust settings as needed through the indicator settings panel
## Version Information
- Version: 2.0
- Last Updated: November 2024
- Platform: TradingView
- Language: Pine Script v5
US/JP Factor/Sector Performance RankingThis indicator is designed to help you easily understand the strengths and weaknesses of different factors and sectors in the U.S. stock market. It looks at various ETFs, ranks their performance over a specific period (20 days by default), and shows the results visually.
= How the Ranking Works
The best-performing rank is shown as -1, with lower ranks as -2, -3, -4, and so on. This setup makes it easy to see rank order in TradingView’s default view.
If you turn on the “Inverse” setting, ranks will be shown as positive numbers in order (e.g., 1, 2, 3…). In this case, it’s recommended to reverse the TradingView scale for better understanding.
= How the Indicator Reacts to Market Conditions
- Normal Market Conditions
Certain factors or sectors often stay at the top rank. For example, during the rallies at the start of 2024 and in May, the Momentum factor performed well, showing a risk-on market environment.
On the other hand, sectors at the bottom rank also tend to stay in specific positions.
- Market Tops
Capital flows within sectors slow down, and top ranks begin to change frequently. This may suggest a market turning point.
- Bear Markets or High Volatility
Rankings become more chaotic in these conditions. These large changes can help you understand market sentiment and the level of volatility.
= Way of using the Indicator
You can use this indicator in the following ways:
- To apply sector rotation strategies.
- To build positions after volatile markets calm down.
- To take long positions on strong elements (higher ranks) and short positions on weaker ones (lower ranks).
= Things to Keep in Mind
It’s a Lagging Indicator
This indicator calculates rankings using the past 20 days of data. It doesn’t provide signals for the future but is a tool for analyzing past performance. To predict the market, you should combine this with other tools or leading indicators.
However, since trends in capital flows often continue, this indicator can help you spot those trends.
= Customization
This indicator is set up for U.S. and Japanese stock markets. However, you can customize it for other markets by changing the ticker and label description in the script.
==Japanese Description==
このインジケーターは、米国株市場におけるファクターやセクターの強弱を直感的に把握するために設計されています。
各ETFを参照し、特定期間(デフォルトでは20日間)のパフォーマンスを順位付けし、それを視覚的に表示します。
= インジケーターの特徴
- ランク付けの仕様
ランク1位は-1で表され、順位が下がるごとに-2、-3、-4…と減少します。この仕様により、TradingViewの標準状態でランクの高低を直感的に把握できるようにしました。
さらに、Inverse設定をONにすると、1位から順に正の値(例: 1, 2, 3…)で表示されるようになります。この場合、TradingViewのスケールを反転させることを推奨します。
= 市況とインジケーターの動き
- 平常時の市況
特定のファクターやセクターがランク1位を維持することが多いです。
例えば、2024年の年初や同年5月の上昇相場では、Momentumファクターが効果を発揮し、リスクオンの市場環境であったことを示しています。
一方、最下位に位置するセクターも特定の順位を維持する傾向があります。
- 天井圏の市況
セクター内の資金流入や流出が停滞し、上位ランクの変動が起こり始めます。これが市場の転換点を示唆する場合があります。
- 下落相場や荒れた市況
ランク順位が大きく乱れることが特徴です。この変動の大きさは、市況の雰囲気やボラティリティの高さを感じ取る材料として活用できます。
= 活用方法
このインジケーターは以下のような投資戦略に役立てることができます:
- セクターローテーションを活用した投資戦略
- 荒れた相場が落ち着いたタイミングでのポジション構築
- 強い要素(ランク上位)のロング、弱い要素(ランク下位)のショート
= 注意点
- 遅行指標であること
本インジケーターは、過去20日間のデータを基にランクを算出します。そのため、先行的なシグナルを提供するものではなく、過去のパフォーマンスに基づいた分析ツールです。市場を先回りするには、別途先行指標や分析を組み合わせる必要があります。
ただし、特定のファクターやセクターへの資金流入・流出が継続する傾向があるため、これを見極める手助けにはなります。
= カスタマイズについて
このインジケーターは米国・日本株市場に特化しています。ただし、他国のファクターやセクターのETFや指数が利用可能であれば、スクリプト内のtickerとlabel descriptionを変更することでカスタマイズが可能です。
Buying and Selling PressureThis indicator estimates and visualizes the buying and selling pressure within each bar by distributing the volume based on where the closing price falls within the bar's range. It calculates cumulative buying and selling volumes over the last 10 bars and plots these values, allowing traders to assess market sentiment and potential shifts in momentum.
This indicator provides valuable insights into market dynamics by estimating buying and selling pressures over a set period. By visualizing these pressures, you can enhance your understanding of market sentiment and improve decision-making processes. It's most effective when used alongside other forms of analysis, such as price action, support and resistance levels, and additional technical indicators.
Note: Always thoroughly test any new indicator or trading strategy before applying it to live trading. Understanding how it behaves under different market conditions ensures it aligns with your trading objectives and risk management practices.
Divides company with IndexOverview:
This indicator simplifies the comparison of a stock's performance against a specified index, such as the Nifty 50. By calculating and plotting the ratio between the two, it provides a clear visual representation of relative strength.
Key Features:
-Direct Comparison: Easily compare any stock against a selected index.
-Customizable Index: Choose from a dropdown menu or input a custom index symbol.
-Visual Clarity: Maximizing the chart provides a clear view of the relative performance.
-SMA Overlay: Add a Simple Moving Average (SMA) to identify trends and potential entry/exit
points.
-Customizable Appearance: Adjust background color, text color, and label size for personalized
visualization.
How to Use:
Add the Indicator: Add the indicator to your chart.
Select the Index: Choose the desired index from the dropdown menu or input a custom symbol.
Analyze the Ratio:
-A rising ratio indicates the stock is outperforming the index.
-A falling ratio suggests underperformance.
-The SMA can help identify potential trends and momentum.
Customize the Appearance: Adjust the background color, text color, and label size to suit your preferences.
Benefits:
-Improved Decision Making: Gain insights into a stock's relative strength.
-Faster Analysis: Quickly compare multiple stocks against a benchmark index.
-Enhanced Visualization: Customize the chart for better understanding.
-By leveraging this indicator, you can make informed trading decisions and gain a deeper
understanding of market dynamics.