PINE LIBRARY
Обновлено

CoreMACDHTF [CHE]

89
Library "CoreMACDHTF"

calc_macd_htf(src, preset_str, smooth_len)
  Parameters:
    src (float)
    preset_str (simple string)
    smooth_len (int)

is_hist_rising(src, preset_str, smooth_len)
  Parameters:
    src (float)
    preset_str (simple string)
    smooth_len (int)

hist_rising_01(src, preset_str, smooth_len)
  Parameters:
    src (float)
    preset_str (simple string)
    smooth_len (int)

CoreMACDHTF [CHE] — Hardcoded HTF MACD Presets with Smoothed Histogram Regime Flags

Summary

CoreMACDHTF provides a reusable MACD engine that approximates higher-timeframe behavior by selecting hardcoded EMA lengths based on the current chart timeframe, then optionally smoothing the resulting histogram with a stateful filter. It is published as a Pine v6 library but intentionally includes a minimal demo plot so you can validate behavior directly on a chart. The primary exported outputs are MACD, signal, a smoothed histogram, and the resolved lengths plus a timeframe tag. In addition, it exposes a histogram rising condition so importing scripts can reuse the same regime logic instead of re-implementing it.

Motivation: Why this design?

Classic MACD settings are often tuned to one timeframe. When you apply the same parameters to very different chart intervals, the histogram can become either too noisy or too sluggish. This script addresses that by using a fixed mapping from the chart timeframe into a precomputed set of EMA lengths, aiming for more consistent “tempo” across intervals. A second problem is histogram micro-chop around turning points; the included smoother reduces short-run flips so regime-style conditions can be more stable for alerts and filters.

What’s different vs. standard approaches?

Reference baseline: a standard MACD using fixed fast, slow, and signal lengths on the current chart timeframe.
Architecture differences:

Automatic timeframe bucketing that selects a hardcoded length set for the chosen preset.
Two preset families: one labeled A with lengths three, ten, sixteen; one labeled B with lengths twelve, twenty-six, nine.
A custom, stateful histogram smoother intended to damp noisy transitions.
Library exports that return both signals and metadata, plus a dedicated “histogram rising” boolean.
Practical effect:

The MACD lengths change when the chart timeframe changes, so the oscillator’s responsiveness is not constant across intervals by design.
The rising-flag logic is based on the smoothed histogram, which typically reduces single-bar flip noise compared to using the raw histogram directly.

How it works (technical)

1. The script reads the chart timeframe and converts it into milliseconds using built-in timeframe helpers.
2. It assigns the timeframe into a bucket label, such as an intraday bucket or a daily-and-above bucket, using fixed thresholds.
3. It resolves a hardcoded fast, slow, and signal length triplet based on:

The selected preset family.
The bucket label.
In some cases, the current minute multiplier for finer mapping.
4. It computes fast and slow EMAs on the selected source and subtracts them to obtain MACD, then computes an EMA of MACD for the signal line.
5. The histogram is derived from the difference between MACD and signal, then passed through a custom smoother.
6. The smoother uses persistent internal state to carry forward its intermediate values from bar to bar. This is intentional and means the smoothing output depends on contiguous bar history.
7. The histogram rising flag compares the current smoothed histogram to its prior value. On the first comparable bar it defaults to “rising” to avoid a missing prior reference.
8. Exports:

A function that returns MACD, signal, smoothed histogram, the resolved lengths, and a text tag.
A function that returns the boolean rising state.
A function that returns a numeric one-or-zero series for direct plotting or downstream numeric logic.

HTF note: this is not a true higher-timeframe request. It does not fetch higher-timeframe candles. It approximates HTF feel by selecting different lengths on the current timeframe.

Parameter Guide

Source — Input price series used for EMA calculations — Default close — Trade-offs/Tips
Preset — Selects the hardcoded mapping family — Default preset A — Preset A is more reactive than preset B in typical use

Table Position — Anchor for an information table — Default top right — Present but not wired in the provided code (Unknown/Optional)
Table Size — Text size for the information table — Default normal — Present but not wired in the provided code (Unknown/Optional)
Dark Mode — Theme toggle for the table — Default enabled — Present but not wired in the provided code (Unknown/Optional)
Show Table — Visibility toggle for the table — Default enabled — Present but not wired in the provided code (Unknown/Optional)

Zero dead-band (epsilon) — Intended neutral band around zero for regime classification — Default zero — Present but not used in the provided code (Unknown/Optional)
Acceptance bars (n) — Intended debounce count for regime confirmation — Default three — Present but not used in the provided code (Unknown/Optional)

Smoothing length — Length controlling the histogram smoother’s responsiveness — Default nine — Smaller values react faster but can reintroduce flip noise

Reading & Interpretation

Smoothed histogram: use it as the momentum core. A positive value implies MACD is above signal, a negative value implies the opposite.
Histogram rising flag:

True means the smoothed histogram increased compared to the prior bar.
False means it did not increase compared to the prior bar.
Demo plot:

The included plot outputs one when rising is true and zero otherwise. It is a diagnostic-style signal line, not a scaled oscillator display.

Practical Workflows & Combinations

Trend following:

Use rising as a momentum confirmation filter after structural direction is established by higher highs and higher lows, or lower highs and lower lows.
Combine with a simple trend filter such as a higher-timeframe moving average from your main script (Unknown/Optional).
Exits and risk management:

If you use rising to stay in trends, consider exiting or reducing exposure when rising turns false for multiple consecutive bars rather than reacting to a single flip.
If you build alerts, evaluate on closed bars to avoid intra-bar flicker in live candles.
Multi-asset and multi-timeframe:

Because the mapping is hardcoded, validate on each asset class you trade. Volatility regimes differ and the perceived “equivalence” across timeframes is not guaranteed.
For consistent behavior, keep the smoothing length aligned across assets and adjust only when flip frequency becomes problematic.

Behavior, Constraints & Performance

Repaint and confirmation:

There is no forward-looking indexing. The logic uses current and prior values only.
Live-bar values can change until the bar closes, so rising can flicker intra-bar if you evaluate it in real time.
security and HTF:

No higher-timeframe candle requests are used. Length mapping is internal and deterministic per chart timeframe.
Resources:

No loops and no arrays in the core calculation path.
The smoother maintains persistent state, which is lightweight but means results depend on uninterrupted history.
Known limits:

Length mappings are fixed. If your chart timeframe is unusual, the bucket choice may not represent what you expect.
Several table and regime-related inputs are declared but not used in the provided code (Unknown/Optional).
The smoother is stateful; resetting chart history or changing symbol can alter early bars until state settles.

Sensible Defaults & Quick Tuning

Starting point:

Preset A
Smoothing length nine
Source close

Tuning recipes:

Too many flips: increase smoothing length and evaluate rising only on closed bars.
Too sluggish: reduce smoothing length, but expect more short-run reversals.
Different timeframe feel after switching intervals: keep preset fixed and adjust smoothing length first before changing preset.
Want a clean plot signal: use the exported numeric rising series and apply your own display rules in the importing script.

What this indicator is—and isn’t

This is a momentum and regime utility layer built around a MACD-style backbone with hardcoded timeframe-dependent parameters and an optional smoother. It is not a complete trading system, not a risk model, and not predictive. Use it in context with market structure, execution rules, and risk controls.

Disclaimer

The content provided, including all code and materials, is strictly for educational and informational purposes only. It is not intended as, and should not be interpreted as, financial advice, a recommendation to buy or sell any financial instrument, or an offer of any financial product or service. All strategies, tools, and examples discussed are provided for illustrative purposes to demonstrate coding techniques and the functionality of Pine Script within a trading context.

Any results from strategies or tools provided are hypothetical, and past performance is not indicative of future results. Trading and investing involve high risk, including the potential loss of principal, and may not be suitable for all individuals. Before making any trading decisions, please consult with a qualified financial professional to understand the risks involved.

By using this script, you acknowledge and agree that any trading decisions are made solely at your discretion and risk.

Do not use this indicator on Heikin-Ashi, Renko, Kagi, Point-and-Figure, or Range charts, as these chart types can produce unrealistic results for signal markers and alerts.

Best regards and happy trading

Chervolino
Информация о релизе
v2

Отказ от ответственности

Информация и публикации не предназначены для предоставления и не являются финансовыми, инвестиционными, торговыми или другими видами советов или рекомендаций, предоставленных или одобренных TradingView. Подробнее читайте в Условиях использования.