Stock Trend Analyzerشرح الكود خطوة بخطوة:
الكود يستخدم 3 مؤشرات رئيسية لتحديد اتجاه الأسهم:
1. المتوسطات المتحركة (Moving Averages).
2. مؤشر القوة النسبية (RSI).
3. مؤشر MACD.
1. المتوسطات المتحركة (Short MA & Long MA):
• المتوسط المتحرك هو متوسط سعر السهم على فترة زمنية (مثل 9 أو 21 يومًا).
• يتم حساب متوسطين:
• متوسط قصير الأجل (Short MA): أسرع في التفاعل مع تغييرات الأسعار.
• متوسط طويل الأجل (Long MA): أبطأ ويُظهر الاتجاه العام.
• طريقة تحديد الاتجاه:
• إذا كان المتوسط القصير (Short MA) أعلى من المتوسط الطويل (Long MA): الاتجاه صعودي (Bullish).
• إذا كان المتوسط القصير أقل من الطويل: الاتجاه هبوطي (Bearish).
في الرسم البياني:
• الخط الأزرق يمثل المتوسط القصير.
• الخط الأحمر يمثل المتوسط الطويل.
• الخلفية تتحول إلى:
• أخضر في الاتجاه الصعودي.
• أحمر في الاتجاه الهبوطي.
2. مؤشر القوة النسبية (RSI):
• RSI يقيس زخم حركة السعر ويحدد ما إذا كان السهم في حالة تشبع شراء (Overbought) أو تشبع بيع (Oversold).
• يتم حسابه بناءً على آخر 14 يومًا (افتراضيًا).
• إشارات RSI:
• إذا كان RSI > 70: السهم في حالة تشبع شراء (فرصة لبيع محتمل).
• إذا كان RSI < 30: السهم في حالة تشبع بيع (فرصة لشراء محتمل).
في الرسم البياني:
• تظهر علامة سهم أعلى الشموع (برتقالي) عند تشبع الشراء.
• تظهر علامة سهم أسفل الشموع (بنفسجي) عند تشبع البيع.
3. مؤشر MACD:
• MACD يقيس الفارق بين متوسطين متحركين (سريع وبطيء)، ويوضح قوة وزخم الاتجاه.
• يتم حساب خطين:
• MACD Line: الفرق بين المتوسط السريع والبطيء.
• Signal Line: متوسط خط MACD.
• إشارات MACD:
• إذا كان MACD Line > Signal Line: إشارة صعودية (Bullish).
• إذا كان MACD Line < Signal Line: إشارة هبوطية (Bearish).
في الرسم البياني:
• تظهر علامة أعلى الشموع (حمراء) إذا كان MACD يشير لاتجاه هبوطي.
• تظهر علامة أسفل الشموع (خضراء) إذا كان MACD يشير لاتجاه صعودي.
النتيجة النهائية على الرسم البياني:
1. المتوسطات المتحركة مرسومة كخطين (أزرق وأحمر).
2. الخلفية تتغير (أخضر أو أحمر) حسب الاتجاه.
3. تظهر إشارات RSI وMACD كمؤشرات مرئية (أسهم ورموز) على الرسم البياني.
빌 윌리엄스 인디케이터
Planetary Degrees by GannStiamo realizzando un sogno! Stiamo realizzando un sogno! Stiamo realizzando un sogno! Stiamo realizzando un sogno! Stiamo realizzando un sogno! Stiamo realizzando un sogno! Stiamo realizzando un sogno! Stiamo realizzando un sogno! Stiamo realizzando un sogno! Stiamo realizzando un sogno! Stiamo realizzando un sogno! Stiamo realizzando un sogno! Stiamo realizzando un sogno! Stiamo realizzando un sogno! Stiamo realizzando un sogno! Stiamo realizzando un sogno! Stiamo realizzando un sogno! Stiamo realizzando un sogno! Stiamo realizzando un sogno! Stiamo realizzando un sogno! Stiamo realizzando un sogno! Stiamo realizzando un sogno! Stiamo realizzando un sogno! Stiamo realizzando un sogno! Stiamo realizzando un sogno! Stiamo realizzando un sogno! Stiamo realizzando un sogno! Stiamo realizzando un sogno! Stiamo realizzando un sogno! Stiamo realizzando un sogno! Stiamo realizzando un sogno! Stiamo realizzando un sogno! Stiamo realizzando un sogno! Stiamo realizzando un sogno! Stiamo realizzando un sogno! Stiamo realizzando un sogno! Stiamo realizzando un sogno! Stiamo realizzando un sogno! Stiamo realizzando un sogno! Stiamo realizzando un sogno! Stiamo realizzando un sogno! Stiamo realizzando un sogno! Stiamo realizzando un sogno! Stiamo realizzando un sogno! Stiamo realizzando un sogno! Stiamo realizzando un sogno! Stiamo realizzando un sogno! Stiamo realizzando un sogno! Stiamo realizzando un sogno! Stiamo realizzando un sogno! Stiamo realizzando un sogno! Stiamo realizzando un sogno! Stiamo realizzando un sogno! Stiamo realizzando un sogno! Stiamo realizzando un sogno! Stiamo realizzando un sogno! Stiamo realizzando un sogno! Stiamo realizzando un sogno! Stiamo realizzando un sogno!
Enhanced AC Divergence Strategy with Stochastic DivergenceStrategy Name: AC-Stochastic Divergence Forex Strategy
Description:
The AC-Stochastic Divergence Forex Strategy is a powerful tool designed for traders seeking high-probability entries in forex, indices, and commodities markets. This strategy leverages the combined power of two proven technical indicators: the Accelerator Oscillator (AC) and the Stochastic Oscillator, with divergence analysis as the cornerstone.
Key Features:
Accelerator Oscillator Divergence
Identifies shifts in market momentum by detecting divergences between price and the AC, signaling potential trend reversals.
Stochastic Divergence Confirmation
Filters false signals by confirming divergences between price and the Stochastic Oscillator.
Validates bullish signals when the Stochastic makes a higher low while price makes a lower low.
Validates bearish signals when the Stochastic makes a lower high while price makes a higher high.
Risk Management
Includes built-in trade rules with a 20-pip take-profit and 40-pip stop-loss configuration.
Optimal for intraday and swing trading setups.
Visual Markers for Precision
Clearly marked buy and sell signals with triangle markers on the chart.
Alerts notify traders of potential trade setups, allowing for real-time execution.
Ease of Use
Designed for all experience levels, from beginners to advanced traders.
Fully customizable input settings to suit various trading styles and timeframes.
How to Use:
Timeframes: Works best on lower timeframes (e.g., 15M or 30M) for scalping or higher timeframes (e.g., 4H or Daily) for swing trades.
Market Conditions: Suitable for trending and ranging markets.
Entry Rules:
For Bullish Trades: Look for price making a lower low, AC showing bullish divergence, and Stochastic confirming with a higher low.
For Bearish Trades: Look for price making a higher high, AC showing bearish divergence, and Stochastic confirming with a lower high.
Alerts:
Receive real-time alerts when bullish or bearish divergences are identified, ensuring you never miss an opportunity.
Backtesting & Optimization:
Run backtests to measure the strategy’s performance on your favorite currency pairs, indices, or commodities. Adjust the parameters for the Stochastic Oscillator and divergence detection to optimize results.
MY moving//@version=5
indicator("Candlestick Patterns with Moving Averages & Time Sessions", overlay=true)
// Input lengths for moving averages
length14 = input.int(14, minval=1, title="MA 14 Length")
length21 = input.int(21, minval=1, title="MA 21 Length")
length50 = input.int(50, minval=1, title="MA 50 Length")
length200 = input.int(200, minval=1, title="MA 200 Length")
// Calculate moving averages
ma14 = ta.sma(close, length14)
ma21 = ta.sma(close, length21)
ma50 = ta.sma(close, length50)
ma200 = ta.sma(close, length200)
// Plot moving averages
plot(ma14, color=color.red, linewidth=2, title="MA 14")
plot(ma21, color=color.blue, linewidth=2, title="MA 21")
plot(ma50, color=color.green, linewidth=2, title="MA 50")
plot(ma200, color=color.orange, linewidth=2, title="MA 200")
// Get the current date and time
currentDate = dayofweek == 1 ? "Sun" : dayofweek == 2 ? "Mon" : dayofweek == 3 ? "Tue" :
dayofweek == 4 ? "Wed" : dayofweek == 5 ? "Thu" : dayofweek == 6 ? "Fri" : "Sat"
currentHour = str.tostring(hour)
currentMinute = str.tostring(minute)
// Define the four trading session times
tradingTimes = array.new_int(4)
array.set(tradingTimes, 0, timestamp(year, month, dayofmonth, 9, 0)) // 9 AM
array.set(tradingTimes, 1, timestamp(year, month, dayofmonth, 12, 0)) // 12 PM
array.set(tradingTimes, 2, timestamp(year, month, dayofmonth, 15, 0)) // 3 PM
array.set(tradingTimes, 3, timestamp(year, month, dayofmonth, 18, 0)) // 6 PM
// Determine the current trading session and background color
sessionColor = time >= array.get(tradingTimes, 0) and time < array.get(tradingTimes, 1) ? color.new(color.green, 90) :
time >= array.get(tradingTimes, 1) and time < array.get(tradingTimes, 2) ? color.new(color.blue, 90) :
time >= array.get(tradingTimes, 2) and time < array.get(tradingTimes, 3) ? color.new(color.orange, 90) :
color.new(color.red, 90)
bgcolor(sessionColor)
// Create a dynamic label showing the current day and time
var label dayTimeLabel = na
if na(dayTimeLabel)
Нуряй *****************
//@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')
//---------------------------------------------------------------------------------------------------------------------}
Buy Signal on Close Greater Than Previous All-Time High StrategyBuy Signal on Close Greater Than Previous All-Time High Strategy
WVAD (Optimized Log Scaled)The WVAD (Optimized Log Scaled) indicator is a refined version of the classic Williams' Volume Accumulation/Distribution (WVAD). This version introduces logarithmic scaling for better visualization and usability, especially when dealing with large value ranges. It also includes EMA smoothing to highlight trends and reduce noise, providing traders with a more precise and clear representation of market dynamics.
Key Features:
1.Logarithmic Scaling:
Applies a log-based transformation to the WVAD values, ensuring extreme values are compressed while maintaining the overall structure of the data.
The log scaling allows better readability and interpretation, particularly for volatile or high-volume markets.
2.EMA Smoothing:
Uses an exponential moving average (EMA) to smooth the logarithmic WVAD values.
Helps reduce noise while preserving short-term trends, making it suitable for both trend-following and reversal strategies.
3.Customizable Parameters:
N (Lookback Period): Defines the accumulation period for calculating WVAD.
EMA Smoothing Period: Controls the sensitivity of the EMA applied to the logarithmic WVAD.
Decimal Places: Adjusts the precision of the displayed values for clearer visualization.
Line Colors: Fully customizable colors for both the raw WVAD line and the smoothed EMA.
4.Directional Preservation:
Keeps the positive and negative signs of WVAD to reflect accumulation (buying pressure) or distribution (selling pressure) in the market.
5.Zero Line Reference:
A horizontal zero line is plotted to help traders easily identify bullish (above 0) or bearish (below 0) market conditions.
How to Use:
Identify Trends: The smoothed WVAD line (EMA) can help detect trends or shifts in buying/selling pressure.
Crossovers: Use crossovers of the WVAD with the zero line as potential buy or sell signals.
Divergence: Spot divergences between price and the WVAD for early indications of reversals.
Applications:
Suitable for intraday, swing, or longer-term trading strategies.
Works across various asset classes, including stocks, commodities, and cryptocurrencies.
Trendline MAKThe simple moving average (SMA) is a straightforward technical indicator that is obtained by summing the recent data points in a given set and dividing the total by the number of time periods. Traders use the SMA indicator to generate signals on when to enter or exit a market. An SMA is backward-looking, as it relies on the past price data for a given period. It can be computed for different types of prices, i.e., high, low, open, and close.
In financial markets, analysts and investors use the SMA indicator to determine buy and sell signals for securities. The SMA helps to identify support and resistance prices to obtain signals on where to enter or exit a trade.
When generating the SMA, traders must first calculate this average by adding prices over a given period and dividing the total by the total number of periods. The information is then plotted on a graph.
The formula for Simple Moving Average is written as follows:
SMA = (A1 + A2 + ……….An) / n
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
Williams Fractals by Defender**Uptrend Strategy**
1. **Daily Chart (D1):**
- MA(200) < MA(50) → Confirm uptrend.
- ADX(19) ≥ 25 → Strong trend.
2. **4-Hour Chart (H4):**
- RSI(19) ≤ 38.2 → Oversold within a strong trend.
- Use fractal theory for trendlines.
- Identify reaction zones for buying opportunities.
3. **15-Minute Chart (M15):**
- Use trendlines for precision entries.
**Add-ons:**
- **Hourly Chart (H1):**
- Stochastic RSI (19, 19, 3, 3) ≤ 20 → Oversold condition.
- Align with support zones and M15 trendlines.
---
**Downtrend Strategy**
1. **Daily Chart (D1):**
- MA(200) > MA(50) → Confirm downtrend.
- ADX(19) ≥ 25 → Strong trend.
2. **4-Hour Chart (H4):**
- RSI(19) ≥ 61.8 → Overbought within a strong trend.
- Use fractal theory for trendlines.
- Identify reaction zones for selling opportunities.
3. **15-Minute Chart (M15):**
- Use trendlines for precision entries.
**Add-ons:**
- **Hourly Chart (H1):**
- Stochastic RSI (19, 19, 3, 3) ≥ 80 → Overbought condition.
- Align with resistance zones and M15 trendlines.
MultiLayer Awesome Oscillator Saucer Strategy [Skyrexio]Overview
MultiLayer Awesome Oscillator Saucer Strategy leverages the combination of Awesome Oscillator (AO), Williams Alligator, Williams Fractals and Exponential Moving Average (EMA) to obtain the high probability long setups. Moreover, strategy uses multi trades system, adding funds to long position if it considered that current trend has likely became stronger. Awesome Oscillator is used for creating signals, while Alligator and Fractal are used in conjunction as an approximation of short-term trend to filter them. At the same time EMA (default EMA's period = 100) is used as high probability long-term trend filter to open long trades only if it considers current price action as an uptrend. More information in "Methodology" and "Justification of Methodology" paragraphs. The strategy opens only long trades.
Unique Features
No fixed stop-loss and take profit: Instead of fixed stop-loss level strategy utilizes technical condition obtained by Fractals and Alligator to identify when current uptrend is likely to be over (more information in "Methodology" and "Justification of Methodology" paragraphs)
Configurable Trading Periods: Users can tailor the strategy to specific market windows, adapting to different market conditions.
Multilayer trades opening system: strategy uses only 10% of capital in every trade and open up to 5 trades at the same time if script consider current trend as strong one.
Short and long term trend trade filters: strategy uses EMA as high probability long-term trend filter and Alligator and Fractal combination as a short-term one.
Methodology
The strategy opens long trade when the following price met the conditions:
1. Price closed above EMA (by default, period = 100). Crossover is not obligatory.
2. Combination of Alligator and Williams Fractals shall consider current trend as an upward (all details in "Justification of Methodology" paragraph)
3. Awesome Oscillator shall create the "Saucer" long signal (all details in "Justification of Methodology" paragraph). Buy stop order is placed one tick above the candle's high of last created "Saucer signal".
4. If price reaches the order price, long position is opened with 10% of capital.
5. If currently we have opened position and price creates and hit the order price of another one "Saucer" signal another one long position will be added to the previous with another one 10% of capital. Strategy allows to open up to 5 long trades simultaneously.
6. If combination of Alligator and Williams Fractals shall consider current trend has been changed from up to downtrend, all long trades will be closed, no matter how many trades has been opened.
Script also has additional visuals. If second long trade has been opened simultaneously the Alligator's teeth line is plotted with the green color. Also for every trade in a row from 2 to 5 the label "Buy More" is also plotted just below the teeth line. With every next simultaneously opened trade the green color of the space between teeth and price became less transparent.
Strategy settings
In the inputs window user can setup strategy setting: EMA Length (by default = 100, period of EMA, used for long-term trend filtering EMA calculation). User can choose the optimal parameters during backtesting on certain price chart.
Justification of Methodology
Let's go through all concepts used in this strategy to understand how they works together. Let's start from the easies one, the EMA. Let's briefly explain what is EMA. The Exponential Moving Average (EMA) is a type of moving average that gives more weight to recent prices, making it more responsive to current price changes compared to the Simple Moving Average (SMA). It is commonly used in technical analysis to identify trends and generate buy or sell signals. It can be calculated with the following steps:
1.Calculate the Smoothing Multiplier:
Multiplier = 2 / (n + 1), Where n is the number of periods.
2. EMA Calculation
EMA = (Current Price) × Multiplier + (Previous EMA) × (1 − Multiplier)
In this strategy uses EMA an initial long term trend filter. It allows to open long trades only if price close above EMA (by default 50 period). It increases the probability of taking long trades only in the direction of the trend.
Let's go to the next, short-term trend filter which consists of Alligator and Fractals. Let's briefly explain what do these indicators means. The Williams Alligator, developed by Bill Williams, is a technical indicator designed to spot trends and potential market reversals. It uses three smoothed moving averages, referred to as the jaw, teeth, and lips:
Jaw (Blue Line): The slowest of the three, based on a 13-period smoothed moving average shifted 8 bars ahead.
Teeth (Red Line): The medium-speed line, derived from an 8-period smoothed moving average shifted 5 bars forward.
Lips (Green Line): The fastest line, calculated using a 5-period smoothed moving average shifted 3 bars forward.
When these lines diverge and are properly aligned, the "alligator" is considered "awake," signaling a strong trend. Conversely, when the lines overlap or intertwine, the "alligator" is "asleep," indicating a range-bound or sideways market. This indicator assists traders in identifying when to act on or avoid trades.
The Williams Fractals, another tool introduced by Bill Williams, are used to pinpoint potential reversal points on a price chart. A fractal forms when there are at least five consecutive bars, with the middle bar displaying the highest high (for an up fractal) or the lowest low (for a down fractal), relative to the two bars on either side.
Key Points:
Up Fractal: Occurs when the middle bar has a higher high than the two preceding and two following bars, suggesting a potential downward reversal.
Down Fractal: Happens when the middle bar shows a lower low than the surrounding two bars, hinting at a possible upward reversal.
Traders often combine fractals with other indicators to confirm trends or reversals, improving the accuracy of trading decisions.
How we use their combination in this strategy? Let’s consider an uptrend example. A breakout above an up fractal can be interpreted as a bullish signal, indicating a high likelihood that an uptrend is beginning. Here's the reasoning: an up fractal represents a potential shift in market behavior. When the fractal forms, it reflects a pullback caused by traders selling, creating a temporary high. However, if the price manages to return to that fractal’s high and break through it, it suggests the market has "changed its mind" and a bullish trend is likely emerging.
The moment of the breakout marks the potential transition to an uptrend. It’s crucial to note that this breakout must occur above the Alligator's teeth line. If it happens below, the breakout isn’t valid, and the downtrend may still persist. The same logic applies inversely for down fractals in a downtrend scenario.
So, if last up fractal breakout was higher, than Alligator's teeth and it happened after last down fractal breakdown below teeth, algorithm considered current trend as an uptrend. During this uptrend long trades can be opened if signal was flashed. If during the uptrend price breaks down the down fractal below teeth line, strategy considered that uptrend is finished with the high probability and strategy closes all current long trades. This combination is used as a short term trend filter increasing the probability of opening profitable long trades in addition to EMA filter, described above.
Now let's talk about Awesome Oscillator's "Sauser" signals. Briefly explain what is the Awesome Oscillator. The Awesome Oscillator (AO), created by Bill Williams, is a momentum-based indicator that evaluates market momentum by comparing recent price activity to a broader historical context. It assists traders in identifying potential trend reversals and gauging trend strength.
AO = SMA5(Median Price) − SMA34(Median Price)
where:
Median Price = (High + Low) / 2
SMA5 = 5-period Simple Moving Average of the Median Price
SMA 34 = 34-period Simple Moving Average of the Median Price
Now we know what is AO, but what is the "Saucer" signal? This concept was introduced by Bill Williams, let's briefly explain it and how it's used by this strategy. Initially, this type of signal is a combination of the following AO bars: we need 3 bars in a row, the first one shall be higher than the second, the third bar also shall be higher, than second. All three bars shall be above the zero line of AO. The price bar, which corresponds to third "saucer's" bar is our signal bar. Strategy places buy stop order one tick above the price bar which corresponds to signal bar.
After that we can have the following scenarios.
Price hit the order on the next candle in this case strategy opened long with this price.
Price doesn't hit the order price, the next candle set lower low. If current AO bar is increasing buy stop order changes by the script to the high of this new bar plus one tick. This procedure repeats until price finally hit buy order or current AO bar become decreasing. In the second case buy order cancelled and strategy wait for the next "Saucer" signal.
If long trades has been opened strategy use all the next signals until number of trades doesn't exceed 5. All trades are closed when the trend changes to downtrend according to combination of Alligator and Fractals described above.
Why we use "Saucer" signals? If AO above the zero line there is a high probability that price now is in uptrend if we take into account our two trend filters. When we see the decreasing bars on AO and it's above zero it's likely can be considered as a pullback on the uptrend. When we see the stop of AO decreasing and the first increasing bar has been printed there is a high probability that this local pull back is finished and strategy open long trade in the likely direction of a main trend.
Why strategy use only 10% per signal? Sometimes we can see the false signals which appears on sideways. Not risking that much script use only 10% per signal. If the first long trade has been open and price continue going up and our trend approximation by Alligator and Fractals is uptrend, strategy add another one 10% of capital to every next saucer signal while number of active trades no more than 5. This capital allocation allows to take part in long trades when current uptrend is likely to be strong and use only 10% of capital when there is a high probability of sideways.
Backtest Results
Operating window: Date range of backtests is 2023.01.01 - 2024.11.25. It is chosen to let the strategy to close all opened positions.
Commission and Slippage: Includes a standard Binance commission of 0.1% and accounts for possible slippage over 5 ticks.
Initial capital: 10000 USDT
Percent of capital used in every trade: 10%
Maximum Single Position Loss: -5.10%
Maximum Single Profit: +22.80%
Net Profit: +2838.58 USDT (+28.39%)
Total Trades: 107 (42.99% win rate)
Profit Factor: 3.364
Maximum Accumulated Loss: 373.43 USDT (-2.98%)
Average Profit per Trade: 26.53 USDT (+2.40%)
Average Trade Duration: 78 hours
These results are obtained with realistic parameters representing trading conditions observed at major exchanges such as Binance and with realistic trading portfolio usage parameters.
How to Use
Add the script to favorites for easy access.
Apply to the desired timeframe and chart (optimal performance observed on 3h BTC/USDT).
Configure settings using the dropdown choice list in the built-in menu.
Set up alerts to automate strategy positions through web hook with the text: {{strategy.order.alert_message}}
Disclaimer:
Educational and informational tool reflecting Skyrex commitment to informed trading. Past performance does not guarantee future results. Test strategies in a simulated environment before live implementation
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.
Fractal Trail [UAlgo]The Fractal Trail is designed to identify and utilize Williams fractals as dynamic trailing stops. This tool serves traders by marking key fractal points on the chart and leveraging them to create adaptive stop-loss trails, enhancing risk management and trade decision-making.
Williams fractals are pivotal in identifying potential reversals and critical support/resistance levels. By plotting fractals dynamically and providing configurable options, this indicator allows for personalized adjustments based on the trader's strategy.
This script integrates both visual fractal markers and adjustable trailing stops, offering insights into market trends while catering to a wide variety of trading styles and timeframes.
🔶 Key Features
Williams Fractals Identification: The indicator marks Williams Fractals on the chart, which are significant highs and lows within a specified range. These fractals are crucial for identifying potential reversal points in the market.
Dynamic Trailing Stops: The indicator generates dynamic trailing stops based on the identified fractals. These stops adjust automatically as new fractals are formed, providing a responsive and adaptive approach to risk management.
Fractal Range: Users can specify the number of bars to the left and right for analyzing fractals, allowing for flexibility in identifying significant price points.
Trail Buffer Percentage: A percentage-based safety margin can be added between the fractal price and the trailing stop, providing additional control over risk management.
Trail Invalidation Source: Users can choose whether the trailing stop flips based on candle closing prices or the extreme points (high/low) of the candles.
Alerts and Notifications: The indicator provides alerts for when the price crosses the trailing stops, as well as when new Williams Fractals are confirmed. These alerts can be customized to fit the trader's notification preferences.
🔶 Interpreting the Indicator
Fractal Markers: The triangles above and below the bars indicate Williams Fractals. These markers help traders identify potential reversal points in the market.
Trailing Stops: The dynamic trailing stops are plotted as lines on the chart. These lines adjust based on the latest identified fractals, providing a visual representation of potential support and resistance levels.
Fill Colors: The optional fill colors between the trailing stops and the price action help traders quickly identify the current trend and potential pullback zones.
🔶 Disclaimer
Use with Caution: This indicator is provided for educational and informational purposes only and should not be considered as financial advice. Users should exercise caution and perform their own analysis before making trading decisions based on the indicator's signals.
Not Financial Advice: The information provided by this indicator does not constitute financial advice, and the creator (UAlgo) shall not be held responsible for any trading losses incurred as a result of using this indicator.
Backtesting Recommended: Traders are encouraged to backtest the indicator thoroughly on historical data before using it in live trading to assess its performance and suitability for their trading strategies.
Risk Management: Trading involves inherent risks, and users should implement proper risk management strategies, including but not limited to stop-loss orders and position sizing, to mitigate potential losses.
No Guarantees: The accuracy and reliability of the indicator's signals cannot be guaranteed, as they are based on historical price data and past performance may not be indicative of future results.
Awesome_Accelerator_Zone OscillatorExplanation and Usage Guide for AO_AC_ZONE Oscillator
Indicator Overview
The **AO_AC_ZONE** oscillator is based on the concepts introduced by **Bill Williams** in his book *New Trading Dimensions*. This indicator combines the **Awesome Oscillator (AO)**, **Accelerator Oscillator (AC)**, and a custom **Zone Oscillator**, visualizing them together in a clear, color-coded format.
The Zone Oscillator is derived from the relationship between AO and AC, indicating the market's dominant momentum state (bullish, bearish, or neutral). It also integrates real-time candle coloring to visually align price bars with the Zone's momentum.
---
**Components**
1. **Awesome Oscillator (AO)**:
- AO measures the difference between a 5-period and 34-period Simple Moving Average (SMA) applied to the midpoints of candles.
- It reflects market momentum, where:
- Green bars = increasing momentum
- Red bars = decreasing momentum
2. **Accelerator Oscillator (AC)**:
- AC is calculated as the difference between AO and its 5-period SMA.
- It indicates the acceleration or deceleration of market momentum.
- Fuchsia bars = increasing momentum
- Purple bars = decreasing momentum
3. **Zone Oscillator**:
- The Zone combines AO and AC states:
- **Green Zone**: Both AO and AC are positive (bullish momentum).
- **Red Zone**: Both AO and AC are negative (bearish momentum).
- **Gray Zone**: AO and AC have differing signs (neutral/uncertain momentum).
- Candle colors dynamically match the Zone’s state for enhanced visual clarity.
---
**How to Use the Indicator**
**1. Interpreting the Oscillators**
- **AO**: Use it to detect momentum direction and changes. Pay attention to shifts in bar color:
- **Increasing AO (Aqua)**: Bullish momentum gaining strength.
- **Decreasing AO (Navy)**: Bullish momentum weakening or bearish momentum strengthening.
- **AC**: Provides early signals of momentum shifts.
- If AC changes color ahead of AO, it signals potential trend reversals or accelerations.
**2. Using the Zone Oscillator**
- **Green Zone**:
- Both AO and AC are positive.
- Indicates a strong bullish trend. Look for buying opportunities in line with the trend.
- **Red Zone**:
- Both AO and AC are negative.
- Signals strong bearish momentum. Look for shorting opportunities.
- **Gray Zone**:
- AO and AC are in conflict.
- Represents uncertainty; avoid trading or wait for a clear signal.
---
**Real-Time Application**
**Candle Coloring**
- The indicator modifies candle colors to match the Zone Oscillator's state:
- **Green Candles**: Strong bullish momentum.
- **Red Candles**: Strong bearish momentum.
- **Gray Candles**: Neutral momentum.
**Recommended Strategy (Based on New Trading Dimensions)**:
1. **Identify the Zone**:
- Focus on Green Zones for long entries and Red Zones for short entries.
2. **Look for AO/AC Confirmation**:
- Enter trades in the direction of both AO and AC when they align with the Zone.
- For exits, monitor when AO and AC conflict (Gray Zone).
3. **Use in Combination**:
- Combine this oscillator with fractals or trend indicators to confirm signals.
---
**Benefits**
- Visualizes momentum strength, acceleration, and alignment in one chart.
- Simplifies decision-making by integrating price action with oscillator dynamics.
- Supports faster trade identification and execution by highlighting bullish, bearish, and neutral zones.
---
**Disclaimer**
This indicator is a tool to assist in market analysis. Always incorporate proper risk management and avoid trading during uncertain conditions (Gray Zones). For optimal results, use this oscillator in conjunction with other analysis methods like support/resistance, volume analysis, and trend-following systems.
EMA with Supply and Demand Zones
The EMA with Supply and Demand Strategy is a trend-following trading approach that integrates Exponential Moving Averages (EMA) with supply and demand zones to identify potential entry and exit points. Below is a detailed description of its components and logic:
Key Components of the Strategy
1. EMA (Exponential Moving Average)
The EMA is used as a trend filter:
Bullish Trend: Price is above the EMA.
Bearish Trend: Price is below the EMA.
The EMA ensures that trades align with the overall market trend, reducing counter-trend risks.
2. Supply and Demand Zones
Demand Zone:
Represents areas where the price historically found support (buyers dominated).
Calculated using the lowest low over a specified lookback period.
Used for identifying potential long entry points.
Supply Zone:
Represents areas where the price historically faced resistance (sellers dominated).
Calculated using the highest high over a specified lookback period.
Used for identifying potential short entry points.
3. Trade Conditions
Long Trade:
Triggered when:
The price is above the EMA (bullish trend).
The low of the current candle touches or penetrates the most recent demand zone.
Short Trade:
Triggered when:
The price is below the EMA (bearish trend).
The high of the current candle touches or penetrates the most recent supply zone.
4. Exit Conditions
Long Exit:
Exit the trade when the price closes below the EMA, indicating a potential trend reversal.
Short Exit:
Exit the trade when the price closes above the EMA, signaling a potential upward reversal.
Visual Representation
EMA: A blue line plotted on the chart to show the trend.
Supply Zones: Red horizontal lines representing potential resistance levels.
Demand Zones: Green horizontal lines representing potential support levels.
These zones dynamically adjust to reflect the most recent 3 levels.
How the Strategy Works
Trend Identification:
The EMA determines the direction of the trade:
Look for long trades only in a bullish trend (price above EMA).
Look for short trades only in a bearish trend (price below EMA).
Entry Points:
Wait for price interaction with a supply or demand zone:
If the price touches a demand zone during a bullish trend, initiate a long trade.
If the price touches a supply zone during a bearish trend, initiate a short trade.
Risk Management:
The strategy exits trades if the price moves against the trend (crosses the EMA).
This ensures minimal exposure during adverse market movements.
Benefits of the Strategy
Trend Alignment:
Reduces counter-trend trades, improving the win rate.
Clear Entry and Exit Rules:
Combines price action (zones) with a reliable trend filter (EMA).
Dynamic Levels:
The supply and demand zones adapt to changing market conditions.
Customization Options
EMA Length:
Adjust to suit different timeframes or market conditions (e.g., 20 for faster trends, 50 for slower trends).
Lookback Period:
Fine-tune to capture broader or narrower supply and demand zones.
Risk/Reward Preferences:
Pair the strategy with stop-loss and take-profit levels for enhanced control.
This strategy is ideal for traders looking for a structured approach to identify high-probability trades while aligning with the prevailing trend. Backtest and optimize parameters based on your trading style and the specific asset you're tradin
Z-ScoreThe z-score (also known as the standard score) measures how many standard deviations a data point is from the mean of a dataset. It helps determine whether a data point is typical or unusual compared to the dataset.
The formula for the z-score is:
z = \frac{x - \mu}{\sigma}
Where:
• x = the value being evaluated
• \mu = the mean of the dataset
• \sigma = the standard deviation of the dataset
Interpretation:
• A positive z-score indicates the data point is above the mean.
• A negative z-score indicates the data point is below the mean.
• A z-score of 0 means the data point is exactly at the mean.
2 bars BarsInputs:
The script allows you to specify the values for each state (HH, HL, LL, LH) for two bars.
Labels as Bars:
Instead of line.new, this script uses label.new to simulate a pseudo-bar chart.
Bars are visually represented as labels, with distinct positions and colors.
Offset Logic:
The offset ensures that each category has its labels (bars) placed at the correct horizontal distance.
Custom Categories:
The categories array ("HH", "HL", "LL", "LH") links to their respective values.
Dynamic TestingInput Parameters
`lookbackPeriod` : Number of candles to check for determining the highest high (resistance) and lowest low (support) levels.
`atrPeriod` : The period for calculating the Average True Range (ATR), a measure of market volatility.
`atrMultiplierSL` : Multiplier to calculate the stop-loss distance relative to the ATR.
`atrMultiplierTP1` and `atrMultiplierTP2` : Multipliers to calculate two take-profit levels relative to ATR.
`rewardToRisk` : The ratio between reward (profit) and risk (stop loss) for trade management.
---
Core Calculations
ATR (Average True Range)
atr = ta.atr(atrPeriod)
ATR is computed using the specified period to gauge price volatility.
Volume SMA
volumeSMA = ta.sma(volume, atrPeriod)
The script calculates the simple moving average of volume over the same period as ATR. This is used as a threshold for validating high-volume scenarios.
---
Support and Resistance Levels
`support` : Lowest price over the last `lookbackPeriod` candles.
`resistance` : Highest price over the same period.
`supportBuffer` and `resistanceBuffer` : These are "buffered" zones around support and resistance, calculated using half of the ATR to prevent false breakouts.
---
Entry Scenarios
Bullish Entry (`isBullishEntry`)
The close is above the buffered support level.
The low of the current candle touches or breaks below the support level.
The trading volume is greater than the `volumeSMA`.
Bearish Entry (`isBearishEntry`)
The close is below the buffered resistance level.
The high of the current candle touches or exceeds the resistance level.
The trading volume is greater than the `volumeSMA`.
---
Box Visualization
Bullish and Bearish Boxes
Bullish Box (`bullishBox`):
- A green, semi-transparent rectangle around the support level to highlight the bullish entry zone.
- Dynamically updates based on recent price action.
Bearish Box (`bearishBox`):
- A red, semi-transparent rectangle around the resistance level to highlight the bearish entry zone.
- Adjusts similarly as price evolves.
---
Stop Loss and Take Profit Calculations
Bullish Trades
Stop Loss (`bullishSL`): Calculated as support - atrMultiplierSL * ATR .
Take Profit 1 (`bullishTP1`): support + rewardToRisk * atrMultiplierTP1 * ATR .
Take Profit 2 (`bullishTP2`): support + rewardToRisk * atrMultiplierTP2 * ATR .
Bearish Trades
Stop Loss (`bearishSL`): resistance + atrMultiplierSL * ATR .
Take Profit 1 (`bearishTP1`): resistance - rewardToRisk * atrMultiplierTP1 * ATR .
Take Profit 2 (`bearishTP2`): resistance - rewardToRisk * atrMultiplierTP2 * ATR .
---
Visualization for Key Levels
Bullish Scenario
Green lines represent `bullishTP1` and `bullishTP2` for profit targets.
A red line indicates the `bullishSL` .
Labels like "TP1," "TP2," and "SL" dynamically appear at respective levels to make the targets and risk visually clear.
Bearish Scenario
Red lines represent `bearishTP1` and `bearishTP2` .
A green line marks the `bearishSL` .
Similar dynamic labeling for `TP1` , `TP2` , and `SL` at corresponding bearish levels.
---
Dynamic Updates
Both the entry boxes and key level visualizations (lines and labels) adjust dynamically based on real-time price and volume data.
---
Purpose
Identify high-probability bullish and bearish trade setups.
Define clear entry zones (using boxes) and exit levels (TP1, TP2, SL).
Incorporate volatility (via ATR) and volume into decision-making.
---
Technical Summary
Dynamically visualize support/resistance levels.
Set risk-managed trades using ATR-based stop-loss and profit levels.
Automate visual trade zones for enhanced chart clarity.
---
Awesome Oscillator with DivergenceSimple Awesome Oscillator with Divergences
This TradingView script combines the classic Awesome Oscillator (AO) with divergence detection. It plots AO as a histogram, highlighting changes in momentum. Divergences are identified based on pivot highs and lows, signaling potential trend reversals:
- Bullish Divergence: Price makes lower lows, AO makes higher lows.
- Bearish Divergence: Price makes higher highs, AO makes lower highs.
Visual signals (arrows) and alerts ensure clear identification, making it ideal for traders focusing on momentum and trend reversals.
Williams Fractals for ExtremesThis script, written in Pine Script (version 5), implements an indicator for the automatic detection and visualization of fractal extremes on the price chart. The core algorithm is based on Bill Williams' fractal theory and identifies local highs and lows, which are often used to determine potential reversal points and support/resistance levels in the market.
### Key Features:
#### Fractal Detection:
- The indicator identifies a fractal high if the middle candle in a sequence of five candles (two on the left and two on the right) has the highest value.
- A fractal low is identified if the middle candle in the same type of five-candle sequence has the lowest value.
#### Extreme Visualization:
- Fractal highs are displayed as red dots on the chart, signaling potential local peaks.
- Fractal lows are shown as green dots, indicating local troughs.
### Usage:
- The indicator is designed for use across all timeframes and can be applied to both cryptocurrency and traditional financial markets.
- Highlighted points allow traders to quickly spot key levels, aiding in identifying potential zones for trade entry or exit.
### Application in Trading:
#### Identifying Key Levels:
- Fractal highs and lows can serve as resistance and support levels. A breakout beyond a fractal in either direction may signal a continuation of movement in that direction.
#### Finding Reversal Points:
- Fractal extremes indicate potential market reversals, making them useful in counter-trend trading strategies.
#### Adaptability to Market Conditions:
- The indicator updates dynamically with the appearance of new candles, providing traders with real-time fractal extreme levels.
### Settings and Parameters:
- In its current version, the script does not include customizable settings as it implements the standard concept of Williams' fractals.