MELONA OB STRATEGY 6TH UPDATE
Похожие материалы по тегам
Сообщите нам, если считаете, что материал размещён без разрешения.
Сообщить о материале
Обращение по товару «melona ob strategy 6th update (by 3dots).pine» отправится на рассмотрение. Укажите контакт для ответа и опишите причину.
О программе
Индикатор TradingView на Pine Script v5, объединяющий множество модулей технического анализа в одном инструменте. Включает осцилляторы (TCCI/Williams %R, RSI, MACD, Stochastic, ADX, CCI), расчёт Supertrend, индикатор Squeeze Momentum на основе Bollinger Bands и Keltner Channels, а также скользящую среднюю с изменением цвета.
Дополнительно реализованы модули обнаружения зон спроса и предложения, рыночной структуры (BOS/CHoCH), волюметрических ордер-блоков, зон давления (Single Candle Order Blocks), полос TMA (Midnight Hunter), набор индикаторов Hull, стандартного отклонения тренда и CMO с условиями оповещений. Поддерживается получение данных с других таймфреймов через request.security().
Индикатор отображает линии, коробки, метки и заливки на графике, позволяет задавать множество пользовательских параметров и настраивать условия оповещений. Все модули включаются и выключаются через соответствующие переключатели.
Настройки программы
| Настройка | Описание |
|---|---|
| n1 | Длина канала TCCI — Длина канала для осциллятора TCCI |
| n2 | Длина усреднения TCCI — Длина усреднения для осциллятора TCCI |
| obLevel1 | Уровень перекупленности 1 — Уровень перекупленности 1 для осциллятора |
| obLevel2 | Уровень перекупленности 2 — Уровень перекупленности 2 для осциллятора |
| osLevel1 | Уровень перепроданности 1 — Уровень перепроданности 1 для осциллятора |
| osLevel2 | Уровень перепроданности 2 — Уровень перепроданности 2 для осциллятора |
| atrPeriod | Период ATR — Период ATR для расчёта Supertrend |
| factor | Множитель Supertrend — Множитель для расчёта Supertrend |
| source | Источник данных — Источник данных для расчётов |
| bbLength | Длина полос Боллинджера — Длина полос Боллинджера |
| bbMult | Множитель полос Боллинджера — Множитель полос Боллинджера |
| kcLength | Длина канала Келтнера — Длина канала Келтнера |
| kcMult | Множитель канала Келтнера — Множитель канала Келтнера |
| useTrueRange | Использовать TrueRange — Использование TrueRange для расчёта канала Келтнера |
| signalLength | Длина сигнальной линии — Длина сигнальной линии для Squeeze Momentum |
| components | Компоненты Squeeze — Отображение компонентов индикатора Squeeze Momentum (полосы BB и KC) |
| lowerThreshold | Нижний порог — Нижний порог для индикатора Squeeze Momentum |
| upperThreshold | Верхний порог — Верхний порог для индикатора Squeeze Momentum |
| alertTrendChange | Оповещение при изменении тренда — Включение оповещения при изменении тренда |
| swr | Показать RSI — Включение индикатора RSI |
| len | Период RSI — Период RSI |
| swm | Показать MACD — Включение индикатора MACD |
| fastLength | Период быстрой EMA (MACD) — Период быстрой EMA для MACD |
| slowLength | Период медленной EMA (MACD) — Период медленной EMA для MACD |
| signalLength2 | Период сигнальной линии MACD — Период сигнальной линии для MACD |
| sws | Показать Stochastic — Включение индикатора Stochastic |
| periodK | Период K (стохастик) — Период K для стохастика |
| periodD | Период D (стохастик) — Период D для стохастика |
| smoothK | Сглаживание K (стохастик) — Сглаживание K для стохастика |
| swx | Показать ADX DI — Включение индикатора ADX DI |
| lenx | Длина DI — Длина DI для ADX |
| lensig | Сглаживание ADX — Сглаживание ADX |
| th | Порог ADX — Пороговое значение для ADX |
| swc | Показать CCI — Включение индикатора CCI |
| length | Период CCI — Период для расчёта CCI |
| scc | Источник CCI — Источник для расчёта CCI |
| maColorUp | Цвет MA (бычий) — Цвет скользящей средней при бычьем тренде |
| maColorDn | Цвет MA (медвежий) — Цвет скользящей средней при медвежьем тренде |
| period | Период стандартного отклонения — Период для расчёта стандартного отклонения тренда |
| stdDevScaler | Масштаб стандартного отклонения — Масштаб стандартного отклонения для тренда |
| structure | Предсказательная структура — Включение предсказательной структуры |
| s_col | Цвет тренда (предсказание) — Цвет тренда в режиме предсказательной структуры |
| showsr | Показать спрос и предложение — Отображение зон спроса и предложения |
| swing_length | Чувствительность свингов — Чувствительность обнаружения свинговых точек |
| box_width | Ширина зоны — Ширина зоны спроса/предложения |
| box_extend_option | Направление продления коробки — Направление продления коробки спроса/предложения |
| res | Таймфрейм спроса/предложения — Таймфрейм для получения данных спроса/предложения |
| demand_color | Цвет зоны спроса — Цвет зоны спроса |
| supply_color | Цвет зоны предложения — Цвет зоны предложения |
| show_swing_ms | Показать свинговую структуру — Отображение свинговой рыночной структуры |
| show_internal_ms | Показать внутреннюю структуру — Отображение внутренней рыночной структуры |
| internal_r_lookback | Длина откатного периода — Длина откатного периода для внутренней структуры |
| swing_r_lookback | Длина откатного периода свинга — Длина откатного периода для свинговой структуры |
| ms_mode | Режим рыночной структуры — Режим рыночной структуры (ручной или динамический) |
| i_ms_up_BOS | Цвет бычьего BOS — Цвет бычьего BOS внутренней структуры |
| i_ms_dn_BOS | Цвет медвежьего BOS — Цвет медвежьего BOS внутренней структуры |
| s_ms_up_BOS | Цвет бычьего BOS структуры — Цвет бычьего BOS структуры |
| s_ms_dn_BOS | Цвет медвежьего BOS структуры — Цвет медвежьего BOS структуры |
| ob_show | Показать ордер-блоки — Отображение последних ордер-блоков |
| ob_num | Количество ордер-блоков — Количество отображаемых последних ордер-блоков |
| ob_metrics_show | Показать метрики ордер-блоков — Отображение метрик внутренней активности для ордер-блоков |
| css_metric_up | Цвет метрики бычьей активности — Цвет метрики внутренней бычьей активности |
| css_metric_dn | Цвет метрики медвежьей активности — Цвет метрики внутренней медвежьей активности |
| ob_swings | Показать Swing ордер-блоки — Отображение Swing ордер-блоков |
| css_swing_up | Цвет Swing ордер-блока (бычий) — Цвет Swing ордер-блока (бычий) |
| css_swing_dn | Цвет Swing ордер-блока (медвежий) — Цвол Swing ордер-блока (медвежий) |
| ob_filter | Фильтрация ордер-блоков — Фильтрация волюметрических ордер-блоков по BOS/CHoCH |
| ob_mitigation | Метод митигации ордер-блоков — Метод митигации для ордер-блоков |
| ob_pos | Позиционирование ордер-блоков — Позиционирование волюметрических ордер-блоков |
| use_grayscale | Градации серого — Использование серого цвета для базовых ордер-блоков |
| use_show_metric | Показать метрики — Отображение объёмных метрик ордер-блоков |
| use_middle_line | Показать среднюю линию — Отображение средней линии ордер-блоков |
| use_overlap | Скрыть перекрытие — Скрытие перекрывающихся ордер-блоков |
| use_overlap_method | Метод перекрытия — Метод обработки перекрытия ордер-блоков |
| ob_bull_css | Цвет бычьего ордер-блока — Цвет бычьего волюметрического ордер-блока |
| ob_bear_css | Цвет медвежьего ордер-блока — Цвет медвежьего волюметрического ордер-блока |
| show_lbl | Показать точку свинга — Отображение точки свинга |
| show_mtb | Показать High/Low/Equilibrium — Отображение High/Low/Equilibrium |
| toplvl | Цвет премиум-зоны — Цвет премиум-зоны для уровней High/Low |
| midlvl | Цвет зоны равновесия — Цвет зоны равновесия для уровней High/Low |
| btmlvl | Цвет зоны скидки — Цвет зоны скидки для уровней High/Low |
| obtxt | Размер метрики — Размер метрики для ордер-блоков |
| showPressure | Показать зоны давления — Отображение одиночных ордер-блоков давления |
| mitigationStyle | Метод митигации — Метод митигации для зон давления |
| showLast | Показать последних ордер-блоков — Количество последних одиночных ордер-блоков давления для отображения |
| volatilityFilter | Фильтр волатильности — Применение фильтра волатильности для зон давления |
| bullishScobColor | Цвет бычьей зоны давления — Цвет бычьей зоны давления |
| bearishScobColor | Цвет медвежьей зоны давления — Цвет медвежьей зоны давления |
| allowOverlap | Разрешить перекрытие — Разрешение перекрытия зон давления |
| showStatusTable | Показать таблицу состояния — Отображение таблицы состояния (на таймфреймах с иерархией) |
| tablePosition | Позиция таблицы — Позиция таблицы состояния |
| tableTextSize | Размер текста таблицы — Размер текста в таблице состояния |
| HalfLength | Половинный период TMA — Половинный период центрированной полосы TMA |
| PriceType | Тип цены — Тип цены для расчёта полос TMA |
| AtrPeriod | Период ATR — Период средней истинной волатильности для расчёта полос TMA |
| AtrMultiplier | Множитель ATR — Множитель средней истинной волатильности для расчёта полос TMA |
| TMAangle | Угол TMA — Угол осторожности центрированной TMA для сигналов |
| tmawidth | Толщина полос TMA — Толщина линий полос TMA |
| i_timeZone | Часовой пояс TMA — Часовой пояс для текстовых оповещений TMA |
| showTF1 | Показать таблицу тренда — Отображение таблицы с трендом и значением индикатора |
Поиск по коду файла
indicator(" MELONA OB STRATEGY 6TH UPDATE (by 3dots)" , overlay = false,max_labels_count = 500)
n1 = input(10, 'Channel Length')
n2 = input(21, 'Average Length')
obLevel1 = input(60, 'Over Bought Level 1')
obLevel2 = input(53, 'Over Bought Level 2')
osLevel1 = input(-60, 'Over Sold Level 1')
osLevel2 = input(-53, 'Over Sold Level 2')
ap = hlc3
esa = ta.ema(ap, n1)
d = ta.ema(math.abs(ap - esa), n1)
ci = (ap - esa) / (0.015 * d)
tci = ta.ema(ci, n2)
wt1 = tci
wt2 = ta.sma(wt1, 4)
plot(0, color=color.new(color.gray, 0))
ob1 = plot(obLevel1, color=color.new(color.maroon, 90))
os1 = plot(osLevel1, color=color.new(color.aqua, 90))
ob2 = plot(obLevel2, color=color.new(color.maroon, 90))
os2 = plot(osLevel2, color=color.new(color.aqua, 90))
p1 = plot(wt1, color=color.new(color.aqua, 0))
p2 = plot(wt2, color=color.new(color.maroon, 0))
plot(ta.cross(wt1, wt2) ? wt2 : na, color=color.new(color.black, 0), style=plot.style_circles, linewidth=3)
plot(ta.cross(wt1, wt2) ? wt2 : na, color=wt2 - wt1 > 0 ? color.maroon : color.aqua, style=plot.style_circles, linewidth=2)
fill(p1,p2,color = wt2 - wt1 > 0 ? color.new(color.red, 50) : color.new(color.aqua, 50))
fill(ob1,ob2,color = color.new(color.maroon, 20))
fill(os1,os2,color = color.new(color.aqua, 20))
atrPeriod = input.int(10, 'ATR Length', minval = 1)
factor = input.float(2.5, 'Factor', minval = 0.01, step = 0.01)
source = input(close, 'Source')
bbLength = input.int(20, 'Bollinger Bands Length', minval = 1)
bbMult = input.float(2, 'Bollinger Bands MultFactor', step = 0.25)
kcLength = input(20, 'Keltner\'s Channel Length')
kcMult = input.float(1.5, 'Keltner\'s Channel MultFactor', step = 0.25)
useTrueRange = input(true, 'Use TrueRange (Keltner\'s Channel)')
signalLength = input(5, 'Signal Length')
tooltip_sqz = 'The Squeeze Indicator measures the relationship between Bollinger Bands and Keltner\'s Channels to help identify consolidations and signal when prices are likely to break out (whether up or down). ' + 'The Squeeze Indicator finds sections of the Bollinger Bands which fall inside the Keltner\'s Channels and in this case the market is said to be in a squeeze (indicator turns off, displayed with grey diamond shapes in this study). ' + 'When the volatility increases, so does the distance between the bands, conversely, when the volatility declines, the distance also decreases and in such cases the squeeze is said to be released (indicator turns on, displayed with triangle up or triangle down shapes)'
components = input.bool(false, 'Components of the Squeeze Indicator', tooltip = tooltip_sqz)
hline(45,linewidth = 1,linestyle = hline.style_solid,color=color.red)
hline(-45,linewidth = 1,linestyle = hline.style_solid,color=color.blue)
lowerThreshold = input(-1.0, title = 'Lower Threshold')
upperThreshold = input(1.0, title = 'Upper Threshold')
targetMultiplier1 = 1
targetMultiplier2 = 2
targetMultiplier3 = 3
stopLossMultiplier = 3
alertTrendChange = input.bool(true, title='Enable Trend Change Alert')
[supertrend, direction] = ta.supertrend(factor, atrPeriod)
upTrend = direction < 0
downTrend = direction > 0
var int previousDirection = na
previousDirection := upTrend ? 1 : -1
atrValue = ta.atr(atrPeriod)
var float entryPrice = na
var float targetLevel1 = na
var float targetLevel2 = na
var float targetLevel3 = na
var float stopLossLevel = na
var int count_up = 0
var int count_down = 0
var bool newLinesDrawn = false
if upTrend
entryPrice := close
targetLevel1 := close + atrValue * targetMultiplier1
targetLevel2 := close + atrValue * targetMultiplier2
targetLevel3 := close + atrValue * targetMultiplier3
stopLossLevel := close - atrValue * stopLossMultiplier
count_up := count_up + 1
count_down := 0
else if downTrend
entryPrice := close
targetLevel1 := close - atrValue * targetMultiplier1
targetLevel2 := close - atrValue * targetMultiplier2
targetLevel3 := close - atrValue * targetMultiplier3
stopLossLevel := close + atrValue * stopLossMultiplier
count_down := count_down + 1
count_up := 0
basis = ta.sma(source, bbLength)
dev = kcMult * ta.stdev(source, bbLength)
bbUpper = basis + dev
bbLower = basis - dev
ma = ta.sma(source, kcLength)
trRange = useTrueRange ? ta.tr : high - low
rangema = ta.sma(trRange, kcLength)
kcUpper = ma + rangema * kcMult
kcLower = ma - rangema * kcMult
sqzOn = bbLower > kcLower and bbUpper < kcUpper
sqzOff = bbLower < kcLower and bbUpper > kcUpper
noSqz = sqzOn == false and sqzOff == false
val = ta.linreg(source - math.avg(math.avg(ta.highest(high, kcLength), ta.lowest(low, kcLength)), ta.sma(source, kcLength)), kcLength, 0)
signal = ta.sma(val, signalLength)
dir = val // - signal
segitigaUp = sqzOff and dir > dir[1] and dir >= upperThreshold
segitigaDown = sqzOff and dir < dir[1] and dir <= lowerThreshold
if sqzOff and not sqzOff[1] // Only trigger alert if the squeeze was previously on
alert('Squeeze Release : '+ syminfo.tickerid + ' | ' + timeframe.period, alert.freq_once_per_bar)
if segitigaDown[2] and not segitigaDown // Only trigger alert if the squeeze was previously on
alert('Weak Trend or Reverse : '+ syminfo.tickerid + ' | ' + timeframe.period, alert.freq_once_per_bar)
if segitigaUp[2] and not segitigaUp // Only trigger alert if the squeeze was previously on
alert('Weak Trend or Reverse : '+ syminfo.tickerid + ' | ' + timeframe.period, alert.freq_once_per_bar)
plot(components ? bbUpper : na, 'BBUpper', color.new(color.blue, 25), show_last = 500,force_overlay=true)
plot(components ? bbLower : na, 'BBLower', color.new(color.blue, 25), show_last = 500,force_overlay=true)
plot(components ? kcUpper : na, 'KCUpper', color.new(color.red, 25), show_last = 500,force_overlay=true)
plot(components ? kcLower : na, 'KCLower', color.new(color.red, 25), show_last = 500,force_overlay=true)
if newLinesDrawn
trendType = upTrend ? "Buy" : "Sell"
stopLossValue = str.tostring(stopLossLevel, '#.###')
entryValue = str.tostring(close, '#.###')
targetValue1 = str.tostring(targetLevel1, '#.###')
targetValue2 = str.tostring(targetLevel2, '#.###')
targetValue3 = str.tostring(targetLevel3, '#.###')
alertMessage = 'Pair : ' + syminfo.tickerid + ' | ' + timeframe.period + '\n' +
'Trend : ' + trendType + '\n' +
'SL : ' + stopLossValue + '\n' +
'Ent : ' + entryValue + '\n' +
'TP1 : ' + targetValue1 + '\n' +
'TP2 : ' + targetValue2 + '\n' +
'TP3 : ' + targetValue3
alert(alertMessage, alert.freq_once_per_bar_close)
newLinesDrawn := false
Distance = 80
swr = input(false, title='RSI')
src = close
len = input.int(14, minval=1, title='Length RSI')
up = ta.rma(math.max(ta.change(src), 0), len)
down = ta.rma(-math.min(ta.change(src), 0), len)
rsi = down == 0 ? 100 : up == 0 ? 0 : 100 - 100 / (1 + up / down)
plot(swr ? rsi + Distance : na, title='RSI', color=color.new(color.purple, 0))
swm = input(false, title='MACD')
source4 = close
fastLength = input.int(12, minval=1)
slowLength = input.int(26, minval=1)
signalLength2 = input.int(9, minval=1)
fastMA = ta.ema(source4, fastLength)
slowMA = ta.ema(source4, slowLength)
macd = fastMA - slowMA
signal2 = ta.ema(macd, signalLength2)
hist = macd - signal2
plot(swm ? hist + Distance : na, color=color.new(color.red, 0), style=plot.style_histogram)
plot(swm ? macd + Distance : na, color=color.new(color.blue, 0))
plot(swm ? signal2 + Distance : na, color=color.new(color.orange, 0))
sws = input(true, title='STOCHASTIC')
periodK = input.int(14, title='K', minval=1)
periodD = input.int(3, title='D', minval=1)
smoothK = input.int(3, title='Smooth', minval=1)
k = ta.sma(ta.stoch(close, high, low, periodK), smoothK)
d2 = ta.sma(k, periodD)
plot(sws ? k + Distance : na, title='%K', color=color.new(color.blue, 0))
plot(sws ? d2 + Distance : na, title='%D', color=color.new(color.orange, 0))
h0 = plot(sws or swr ? 80 + Distance : na)
h1 = plot(sws or swr ? 20 + Distance : na)
fill(h0, h1, color=color.new(color.purple, 75))
swx = input(false, title='ADX DI')
lenx = input.int(14, minval=1, title='DI Length')
lensig = input.int(14, title='ADX Smoothing', minval=1, maxval=50)
th = input(title='threshold', defval=25)
upx = ta.change(high)
downx = -ta.change(low)
plusDM = na(upx) ? na : upx > downx and upx > 0 ? upx : 0
minusDM = na(downx) ? na : downx > upx and downx > 0 ? downx : 0
trur = ta.rma(ta.tr, lenx)
plus = fixnan(100 * ta.rma(plusDM, lenx) / trur)
minus = fixnan(100 * ta.rma(minusDM, lenx) / trur)
sum = plus + minus
adx = 100 * ta.rma(math.abs(plus - minus) / (sum == 0 ? 1 : sum), lensig)
plot(swx ? plus + Distance : na, color=color.new(color.blue, 0), title='+DI')
plot(swx ? minus + Distance : na, color=color.new(color.orange, 0), title='-DI')
plot(swx ? adx + Distance : na, color=color.new(color.red, 0), title='ADX')
plot(swx ? th + Distance : na, color=color.new(color.black, 0), title='th')
swc = input(false, title='Commodity Channel Index')
length = input.int(20, minval=1)
scc = input(close, title='Source')
ma23 = ta.sma(scc, length)
cci = (scc - ma23) / (0.015 * ta.dev(scc, length))
plot(swc ? cci + Distance : na, 'CCI', color=color.new(#996A15, 0))
ma40(source1, length1, MAtype) =>
switch MAtype
"SMA" => ta.sma(source, length)
"EMA" => ta.ema(source, length)
"SMMA (RMA)" => ta.rma(source, length)
"WMA" => ta.wma(source, length)
"VWMA" => ta.vwma(source, length)
color maColorUp = input.color(#2962FF, "MA Bullish")
color maColorDn = input.color(#b42a2a, "MA Bearish")
MA35 = ma40(hl2, 40, "SMA")
color maColor = source >= MA35 ? maColorUp : maColorDn
plot(MA35, "SMA-based MA", color=maColor, force_overlay = true, linewidth = 2)
plot(MA35, "SMA-based MA", color=color.new(maColor, 80), force_overlay = true, linewidth = 7)
t1 = "Determines the number of periods used for the standard deviation calculation. Increasing the value makes the indicator less sensitive to price changes, possibly identifying longer-term trends, while decreasing the value makes the indicator more sensitive, possibly identifying shorter-term trends."
t2 = "Scales the computed standard deviation. Increasing this value may result in larger deviations being needed to confirm trends, potentially filtering out minor price fluctuations and focusing on significant trend changes, while decreasing this value may allow smaller deviations to confirm trends, possibly detecting more frequent changes."
t3 = "Enables or disables the predictive structure setting. Enabling it may emphasize the prediction of market structures, such as potential levels of structure breaks/trend continuation breaks."
t4 = "Activates or deactivates BTC Scalping Mode. When activated, the indicator’s parameters adjust to optimize for shorter time frames and quicker trades, potentially beneficial for scalping strategies in BTC markets."
t5 = "Adjusts the scaling divisor when in BTC Scalping Mode. Modifying this value impacts the volatility and trend sensitivity during scalping. A higher value might result in less sensitivity to price fluctuations, focusing on more substantial trend changes, while a lower value might increase sensitivity, detecting minor trend changes."
period = input.int(20, title="Period for Std Dev", minval = 1, maxval=200, inline="", group="", tooltip=t1)
stdDevScaler = input.int(5, title="Standard Deviation Scaler", minval = 1, maxval=200, inline="", group="", tooltip=t2)
structure = input.bool(false, title="Predictive Structure", inline = "s", group = "", tooltip=t3)
s_col = input.color(color.rgb(70, 40, 204), title="", inline = "s", group = "")
isScalpingModeEnabled = false //input.bool(false, title="BTC Scalping Mode", inline="scalp", group="BTC Scalping", tooltip=t4)
scalpingDivisor = isScalpingModeEnabled==true ? input.int(1, title="", minval = 0, maxval=200, inline="scalp", group="BTC Scalping", tooltip=t5) : 1
bullish_col = structure?s_col :input.color(color.blue, title="Bullish Trend Color", inline = "Trend", group = "Color")
bearish_col = structure?s_col :input.color(color.orange, title="Bearish Trend Color", inline = "Trend", group = "Color")
var float trend = 0
var int trendDirection = 0
trendDirectionFunction(dir) =>
dir - dir[1] > 0 ? 1 : (dir - dir[1] < 0 ? -1 : 0)
trendDirectionChanged(trendDirection) =>
trendDirection != trendDirection[1]
stddev_function(src_, p) =>
if bar_index < p - 1
0.0
else
sum = 0.0
for i = 0 to p - 1
sum := sum + src_[i]
mean = sum / p
sum_diff_sq = 0.0
for i = 0 to p - 1
sum_diff_sq := sum_diff_sq + math.pow(src_[i] - mean, 2)
stdev = isScalpingModeEnabled ? math.sqrt(sum_diff_sq / close * p * scalpingDivisor) : math.sqrt(sum_diff_sq / p * scalpingDivisor)
stdev
scaledStdDev = stdDevScaler * stddev_function(trend, period)
priceDifference = close - trend > 0 ? close - trend : trend - close
rateOfChangeFactor = float(100)
div = structure? float(int(1) / int(100)): 1 / rateOfChangeFactor
reciprocal_factors = (1 / stdDevScaler) * div
trend := priceDifference > scaledStdDev ? math.avg(close, trend):
trendDirection * (trendDirectionChanged(trendDirection) ?
scaledStdDev : reciprocal_factors * scaledStdDev) +
trend
trendDirection := trendDirectionFunction(trend)
color = trendDirection == 1 ? bullish_col : bearish_col
plot(trend, title="Trend", color=trendDirectionChanged(trendDirection) ? na : color,force_overlay = true)
gr_sr = "Supply & Demand"
showsr = input(true, title="Show Supply & Demand", group = gr_sr)
swing_length = input.int(defval=8, title="Sensitivity", group = gr_sr)
box_width = input.float(defval=4, title="Zone Width", group = gr_sr)
box_extend_option = input.string("Right", title="Extend Box", options=["Right", "Both"], group = gr_sr)
res = input.timeframe(title='Time Frame', defval='', group= gr_sr)
s1 = request.security(syminfo.tickerid, res, showsr, gaps=barmerge.gaps_on)
demand_color = input.color(#08998148, title = 'Supply & Demand Color', group = gr_sr ,inline = "1")
supply_color = input.color(#f2364648, title = '', group = gr_sr, inline = "1")
history_of_demand_to_keep = 20
show_zigzag = false
show_price_action_labels = false
avg_volume = ta.sma(volume, 20)
very_weak_multiplier = 0.5
weak_multiplier = 1
strong_multiplier = 1.5
var int[] demandRejections = array.new_int(history_of_demand_to_keep, 0)
var int[] supplyRejections = array.new_int(history_of_demand_to_keep, 0)
var int[] demandCreationBars = array.new_int(history_of_demand_to_keep, na)
var int[] supplyCreationBars = array.new_int(history_of_demand_to_keep, na)
var box[] current_demand_box = array.new_box(history_of_demand_to_keep, na)
var box[] current_supply_box = array.new_box(history_of_demand_to_keep, na)
f_check_demand_rejections() =>
for i = 0 to history_of_demand_to_keep - 1
if not na(array.get(demandCreationBars, i))
if bar_index - array.get(demandCreationBars, i) > 15 and bar_index - array.get(demandCreationBars, i) % 15 == 0
label.new(bar_index, high, "Checking demand rejection", color=color.red)
dBox = array.get(current_demand_box, i)
if (na(dBox))
continue
withinBox = (high >= box.get_bottom(dBox) and high <= box.get_top(dBox)) or (close >= box.get_bottom(dBox) and close <= box.get_top(dBox))
bearishCandlesCount = math.sum(close < open ? 1 : 0, 15)
if withinBox and bearishCandlesCount >= 7
label.new(bar_index, low, "Bearish count > 7", color=color.blue)
array.set(demandRejections, i, array.get(demandRejections, i) + 1)
f_check_supply_rejections() =>
for i = 0 to history_of_demand_to_keep - 1
if not na(array.get(supplyCreationBars, i))
if bar_index - array.get(supplyCreationBars, i) > 15 and bar_index - array.get(supplyCreationBars, i) % 15 == 0
label.new(bar_index, low, "Checking supply rejection", color=color.red)
sBox = array.get(current_supply_box, i)
if (na(sBox))
continue
withinBox = (low <= box.get_top(sBox) and low >= box.get_bottom(sBox)) or (close <= box.get_top(sBox) and close >= box.get_bottom(sBox))
bullishCandlesCount = math.sum(close > open ? 1 : 0, 15)
if withinBox and bullishCandlesCount >= 7
label.new(bar_index, high, "Bullish count > 7", color=color.blue)
array.set(supplyRejections, i, array.get(supplyRejections, i) + 1)
f_array_add_pop(array, new_value_to_add) =>
array.unshift(array, new_value_to_add)
array.pop(array)
f_sh_sl_labels(array, swing_type) =>
var string label_text = na
if swing_type == 1
if array.get(array, 0) >= array.get(array, 1)
label_text := 'HH'
else
label_text := 'LH'
label.new(bar_index - swing_length, array.get(array,0), text = label_text, style=label.style_label_down, textcolor = color.white, color = color.new(color.white, 100), size = size.tiny)
else if swing_type == -1
if array.get(array, 0) >= array.get(array, 1)
label_text := 'HL'
else
label_text := 'LL'
label.new(bar_index - swing_length, array.get(array,0), text = label_text, style=label.style_label_up, textcolor = color.white, color = color.new(color.white, 100), size = size.tiny)
f_check_overlapping(new_poi, box_array, atr) =>
atr_threshold = atr * 2
okay_to_draw = true
for i = 0 to array.size(box_array) - 1
top = box.get_top(array.get(box_array, i))
bottom = box.get_bottom(array.get(box_array, i))
poi = (top + bottom) / 2
upper_boundary = poi + atr_threshold
lower_boundary = poi - atr_threshold
if new_poi >= lower_boundary and new_poi <= upper_boundary
okay_to_draw := false
break
else
okay_to_draw := true
okay_to_draw
f_supply_demand(value_array, bn_array, box_array, label_array, box_type, atr) =>
atr_buffer = atr * (box_width / 15)
box_left = array.get(bn_array, 0)
box_right = bar_index + 20
var float box_top = 0.00
var float box_bottom = 0.00
var float poi = 0.00
if box_type == 1
box_top := array.get(value_array, 0)
box_bottom := box_top - atr_buffer
poi := (box_top + box_bottom) / 2
else if box_type == -1
box_bottom := array.get(value_array, 0)
box_top := box_bottom + atr_buffer
poi := (box_top + box_bottom) / 2
okay_to_draw = f_check_overlapping(poi, box_array, atr)
swing_volume = volume[swing_length]
var string strength_text = ""
highest_volume_last_20 = ta.highest(volume, 20)
volume_percentage = math.round(swing_volume / highest_volume_last_20 * 100)
volume_percentage := math.min(volume_percentage, 100) // Cap the volume percentage to 100
var extend_option = extend.right
if box_extend_option == "Right"
extend_option := extend.right
else if box_extend_option == "Both"
extend_option := extend.both
if box_type == 1 and okay_to_draw and s1
box.delete( array.get(box_array, array.size(box_array) - 5) )
f_array_add_pop(box_array, box.new( left = box_left, top = box_top, right = box_right, bottom = box_bottom, border_color = color.rgb(242,54,69,50), border_width=1,force_overlay = true,
bgcolor = supply_color, extend = extend_option, text = strength_text, text_halign = text.align_center, text_valign = text.align_center, text_color = color.rgb(59, 59, 59), text_size = size.small, xloc = xloc.bar_index))
box.delete( array.get(label_array, array.size(label_array) - 5) )
f_array_add_pop(label_array, box.new( left = box_left, top = poi, right = box_right, bottom = poi, border_color = color.rgb(242,54,69,50), border_width=1, border_style=line.style_dotted,force_overlay = true,
bgcolor = color.new(color.black,100), extend = extend_option, text = 'MAIN OB', text_halign = text.align_center, text_valign = text.align_center, text_color = color.rgb(59, 59, 59), text_size = size.small, xloc = xloc.bar_index))
else if box_type == -1 and okay_to_draw and s1
box.delete( array.get(box_array, array.size(box_array) - 5) )
f_array_add_pop(box_array, box.new( left = box_left, top = box_top, right = box_right, bottom = box_bottom, border_color = color.rgb(0,188,212,50), border_width=1,force_overlay = true,
bgcolor = demand_color, extend = extend_option, text = strength_text, text_halign = text.align_center, text_valign = text.align_center, text_color = color.rgb(59, 59, 59), text_size = size.small, xloc = xloc.bar_index))
box.delete( array.get(label_array, array.size(label_array) - 5) )
f_array_add_pop(label_array, box.new( left = box_left, top = poi, right = box_right, bottom = poi, border_color = color.rgb(0,188,212,50), border_width=1, border_style=line.style_dotted,force_overlay = true,
bgcolor = color.new(color.black,100), extend = extend_option, text = 'MAIN OB', text_halign = text.align_center, text_valign = text.align_center, text_color = color.rgb(59, 59, 59), text_size = size.small, xloc = xloc.bar_index))
f_sd_to_bos(box_array, bos_array, label_array, zone_type) =>
if zone_type == 1
for i = 0 to array.size(box_array) - 1
level_to_break = box.get_top(array.get(box_array,i))
if close >= level_to_break
box.delete(array.get(box_array, i))
box.delete(array.get(label_array, i))
if zone_type == -1
for i = 0 to array.size(box_array) - 1
level_to_break = box.get_bottom(array.get(box_array,i))
if close <= level_to_break
box.delete(array.get(box_array, i))
box.delete(array.get(label_array, i))
f_extend_box_endpoint(box_array) =>
for i = 0 to array.size(box_array) - 1
box.set_right(array.get(box_array, i), bar_index + 30) // Extend only 20 bars
atr567 = ta.atr(50)
swing_high = ta.pivothigh(high, swing_length, swing_length)
swing_low = ta.pivotlow(low, swing_length, swing_length)
var swing_high_values = array.new_float(5,0.00)
var swing_low_values = array.new_float(5,0.00)
var swing_high_bns = array.new_int(5,0)
var swing_low_bns = array.new_int(5,0)
var current_supply_poi = array.new_box(history_of_demand_to_keep, na)
var current_demand_poi = array.new_box(history_of_demand_to_keep, na)
var supply_bos = array.new_box(5, na)
var demand_bos = array.new_box(5, na)
if not na(swing_high)
f_array_add_pop(swing_high_values, swing_high)
f_array_add_pop(swing_high_bns, bar_index[swing_length])
if show_price_action_labels
f_sh_sl_labels(swing_high_values, 1)
f_supply_demand(swing_high_values, swing_high_bns, current_supply_box, current_supply_poi, 1, atr567)
else if not na(swing_low)
f_array_add_pop(swing_low_values, swing_low)
f_array_add_pop(swing_low_bns, bar_index[swing_length])
if show_price_action_labels
f_sh_sl_labels(swing_low_values, -1)
f_supply_demand(swing_low_values, swing_low_bns, current_demand_box, current_demand_poi, -1, atr567)
f_sd_to_bos(current_supply_box, supply_bos, current_supply_poi, 1)
f_sd_to_bos(current_demand_box, demand_bos, current_demand_poi, -1)
f_extend_box_endpoint(current_supply_box)
f_extend_box_endpoint(current_demand_box)
if not na(swing_low)
f_array_add_pop(swing_low_values, swing_low)
f_array_add_pop(swing_low_bns, bar_index[swing_length])
if show_price_action_labels
f_sh_sl_labels(swing_low_values, -1)
f_supply_demand(swing_low_values, swing_low_bns, current_demand_box, current_demand_poi, -1, atr567)
f_check_demand_rejections()
if not na(swing_high)
f_array_add_pop(swing_high_values, swing_high)
f_array_add_pop(swing_high_bns, bar_index[swing_length])
if show_price_action_labels
f_sh_sl_labels(swing_high_values, 1)
f_supply_demand(swing_high_values, swing_high_bns, current_supply_box, current_supply_poi, 1, atr567)
f_check_supply_rejections()
s_BOS = 0
s_CHoCH = 1
i_BOS = 2
i_CHoCH = 3
i_pp_CHoCH = 4
green_candle = 5
red_candle = 6
s_CHoCHP = 7
i_CHoCHP = 8
boolean =
array.from(
false
, false
, false
, false
, false
, false
, false
, false
, false
)
show_swing_ms = input.string ("None" , "Swing " , inline = "1", group = "MARKET STRUCTURE" , options = ["All", "CHoCH", "CHoCH+", "BOS", "None"])
show_internal_ms = input.string ("None" , "Internal " , inline = "2", group = "MARKET STRUCTURE" , options = ["All", "CHoCH", "CHoCH+", "BOS", "None"])
internal_r_lookback = input.int (5 , "" , inline = "2", group = "MARKET STRUCTURE" , minval = 2)
swing_r_lookback = input.int (50 , "" , inline = "1", group = "MARKET STRUCTURE" , minval = 2)
ms_mode = input.string ("Manual" , "Market Structure Mode" , inline = "a", group = "MARKET STRUCTURE" , tooltip = "[Manual] Use selected lenght\n[Dynamic] Use automatic lenght" ,options = ["Manual", "Dynamic"])
i_ms_up_BOS = input.color (#089981 , "" , inline = "2", group = "MARKET STRUCTURE")
i_ms_dn_BOS = input.color (#f23645 , "" , inline = "2", group = "MARKET STRUCTURE")
s_ms_up_BOS = input.color (#089981 , "" , inline = "1", group = "MARKET STRUCTURE")
s_ms_dn_BOS = input.color (#f23645 , "" , inline = "1", group = "MARKET STRUCTURE")
ob_show = input.bool (true , "Show Last " , inline = "1", group = "VOLUMETRIC ORDER BLOCKS" , tooltip = "Display volumetric order blocks on the chart \n\n[Input] Ammount of volumetric order blocks to show")
ob_num = input.int (5 , "" , inline = "1", group = "VOLUMETRIC ORDER BLOCKS" , tooltip = "Orderblocks number", minval = 1, maxval = 10)
ob_metrics_show = input.bool (true , "Internal Buy/Sell Activity" , inline = "2", group = "VOLUMETRIC ORDER BLOCKS" , tooltip = "Display volume metrics that have formed the orderblock")
css_metric_up = input.color (color.new(#047c32, 50) , " " , inline = "2", group = "VOLUMETRIC ORDER BLOCKS")
css_metric_dn = input.color (color.new(#cf041b, 50) , "" , inline = "2", group = "VOLUMETRIC ORDER BLOCKS")
ob_swings = input.bool (false , "Swing Order Blocks" , inline = "a", group = "VOLUMETRIC ORDER BLOCKS" , tooltip = "Display swing volumetric order blocks")
css_swing_up = input.color (color.new(color.gray , 90) , " " , inline = "a", group = "VOLUMETRIC ORDER BLOCKS")
css_swing_dn = input.color (color.new(color.silver, 90) , "" , inline = "a", group = "VOLUMETRIC ORDER BLOCKS")
ob_filter = input.string ("None" , "Filtering " , inline = "d", group = "VOLUMETRIC ORDER BLOCKS" , tooltip = "Filter out volumetric order blocks by BOS/CHoCH/CHoCH+", options = ["None", "BOS", "CHoCH", "CHoCH+"])
ob_mitigation = input.string ("Absolute" , "Mitigation " , inline = "4", group = "VOLUMETRIC ORDER BLOCKS" , tooltip = "Trigger to remove volumetric order blocks", options = ["Absolute", "Middle"])
ob_pos = input.string ("Precise" , "Positioning " , inline = "k", group = "VOLUMETRIC ORDER BLOCKS" , tooltip = "Position of the Order Block\n[Full] Cover the whole candle\n[Middle] Cover half candle\n[Accurate] Adjust to volatility\n[Precise] Same as Accurate but more precise", options = ["Full", "Middle", "Accurate", "Precise"])
use_grayscale = input.bool (true , "Grayscale" , inline = "6", group = "VOLUMETRIC ORDER BLOCKS" , tooltip = "Use gray as basic order blocks color")
use_show_metric = input.bool (true , "Show Metrics" , inline = "7", group = "VOLUMETRIC ORDER BLOCKS" , tooltip = "Show volume associated with the orderblock and his relevance")
use_middle_line = input.bool (false , "Show Middle-Line" , inline = "8", group = "VOLUMETRIC ORDER BLOCKS" , tooltip = "Show mid-line order blocks")
use_overlap = input.bool (true , "Hide Overlap" , inline = "9", group = "VOLUMETRIC ORDER BLOCKS" , tooltip = "Hide overlapping order blocks")
use_overlap_method = input.string ("Previous" , "Overlap Method " , inline = "Z", group = "VOLUMETRIC ORDER BLOCKS" , tooltip = "[Recent] Preserve the most recent volumetric order blocks\n\n[Previous] Preserve the previous volumetric order blocks", options = ["Recent", "Previous"])
ob_bull_css = input.color (color.new(#089981 , 90) , "" , inline = "1", group = "VOLUMETRIC ORDER BLOCKS")
ob_bear_css = input.color (color.new(#f23645 , 90) , "" , inline = "1", group = "VOLUMETRIC ORDER BLOCKS")
show_lbl = input.bool (false , "Show swing point" , inline = "1", group = "High and Low" , tooltip = "Display swing point")
show_mtb = input.bool (false , "Show High/Low/Equilibrium" , inline = "2", group = "High and Low" , tooltip = "Display Strong/Weak High And Low and Equilibrium")
toplvl = input.color (color.red , "Premium Zone " , inline = "3", group = "High and Low")
midlvl = input.color (color.white , "Equilibrium Zone" , inline = "4", group = "High and Low")
btmlvl = input.color (#089981 , "Discount Zone " , inline = "5", group = "High and Low")
t Показано первые 50% кода (символов: 47834)
Открыть по тарифу
Купите тариф с пакетом открытий или войдите, если тариф уже есть. Открытый файл останется в вашем кабинете навсегда.
Разовая покупка файла
На этой странице откроется полный исходный код файла вместо ознакомительного фрагмента.
Зачем нужен email? После подтверждения оплаты файл сохранится в кабинете на этот email. Если аккаунта ещё нет, мы создадим его и пришлём ссылку для задания пароля. Если аккаунт уже есть, покупка добавится в него. Укажите адрес, к которому у вас есть доступ.
Чтобы оформить заказ, введите email и перейдите к оплате.