[ad] CVD + MFI

Jogartt · study · 163 行 · 点赞 14 · TradingView 原页

本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。

Pine Script

// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
//@version=6
indicator("[ad] CVD + MFI", shorttitle = "CVD + MFI", format = format.volume, max_lines_count = 3, max_polylines_count = 100)
 
// TradingView's built-in "Cumulative volume delta" and "Money flow index" in one pane and one indicator slot.
// Both calculations are the original open-source built-ins, unchanged.
//
// A Pine script has a single price scale, so the CVD candles own it. The MFI is drawn as a line fitted to the
// visible CVD range, which is how two auto-scaled studies overlap when merged into one pane: the visible MFI
// range (line and levels) is matched to the visible CVD range (candles and zero line). The status line and
// the Data Window always show the real MFI value.
 
import TradingView/ta/12
 
const string CVD_GROUP = "Cumulative volume delta"
const string MFI_GROUP = "Money flow index"
const string STYLE_GROUP = "MFI style"
const int MAX_POLYLINE_POINTS = 10000
 
// ————— Inputs: CVD (same as the built-in)
 
const string DATA_AGGREGATION_TOOLTIP = "Defines how lower timeframe data is aggregated for the delta calculation. \"1 tick\" computes the delta on tick data and is available only on expert plans."
const string LOWER_TIMEFRAME_TOOLTIP = "The indicator scans lower timeframe data to approximate up and down volume used in the delta calculation. By default, the timeframe is chosen automatically. These inputs override this with a custom timeframe." + " \n\nHigher timeframes provide more historical data, but the data will be less precise."
 
string anchorInput = input.timeframe("1D", "Anchor period", group = CVD_GROUP)
string dataAggregationInput = input.string("Time", "Data aggregation", options = ["Time", "1 tick"], tooltip = DATA_AGGREGATION_TOOLTIP, group = CVD_GROUP)
bool useTicks = dataAggregationInput == "1 tick"
bool useCustomTimeframeInput = input.bool(false, "Use custom timeframe", tooltip = LOWER_TIMEFRAME_TOOLTIP, active = not useTicks, group = CVD_GROUP)
string lowerTimeframeInput = input.timeframe("1", "Timeframe", active = useCustomTimeframeInput and not useTicks, group = CVD_GROUP)
 
// ————— Inputs: MFI (length as in the built-in; levels are inputs because they are drawn as lines)
 
int lengthInput = input.int(14, "Length", minval = 1, maxval = 2000, group = MFI_GROUP)
float overboughtInput = input.float(80.0, "Overbought", group = MFI_GROUP)
float middleInput = input.float(50.0, "Middle band", group = MFI_GROUP)
float oversoldInput = input.float(20.0, "Oversold", group = MFI_GROUP)
 
color mfiColorInput = input.color(#7E57C2, "MFI line", inline = "line", group = STYLE_GROUP)
int mfiWidthInput = input.int(1, "", minval = 1, maxval = 4, inline = "line", tooltip = "Line color and width.", group = STYLE_GROUP)
bool showLevelsInput = input.bool(true, "Levels", inline = "levels", group = STYLE_GROUP)
color levelsColorInput = input.color(#787B86, "", inline = "levels", group = STYLE_GROUP)
bool showBackgroundInput = input.bool(true, "Background", inline = "background", group = STYLE_GROUP)
color backgroundColorInput = input.color(color.new(#7E57C2, 90), "", inline = "background", group = STYLE_GROUP)
 
// ————— Cumulative volume delta (TradingView built-in)
 
var string lowerTimeframe = switch
    useTicks                => "1T"
    useCustomTimeframeInput => lowerTimeframeInput
    timeframe.isseconds     => "1S"
    timeframe.isintraday    => "1"
    timeframe.isdaily       => "5"
    => "60"
 
[openVolume, maxVolume, minVolume, lastVolume] = ta.requestVolumeDelta(lowerTimeframe, anchorInput)
 
color cvdColor = lastVolume >= openVolume ? #089981 : #F23645
hline(0, "Zero")
plotcandle(openVolume, maxVolume, minVolume, lastVolume, "CVD", color = cvdColor, bordercolor = cvdColor, wickcolor = cvdColor)
 
var float cumVol = 0.
cumVol += nz(volume)
bool deltaIsNa = na(openVolume) and na(maxVolume) and na(minVolume) and na(lastVolume)
if barstate.islast
    if cumVol == 0
        runtime.error("The data vendor doesn't provide volume data for this symbol.")
    if str.endswith(lowerTimeframe, "T") and deltaIsNa
        runtime.error("Not enough tick depth for the current anchor period. The available tick depth ends before reaching the start of the anchor period (" + anchorInput + "). Please shorten the 'Anchor period' input or switch the calculation base from '1 Tick' to 'Time' or higher custom timeframe.")
 
// ————— Money flow index (TradingView built-in)
 
float mf = ta.mfi(hlc3, lengthInput)
// Real value for the status line and the Data Window. The visible line is drawn below, fitted to the CVD scale.
plot(mf, "MFI", color = mfiColorInput, display = display.status_line + display.data_window, format = format.price, precision = 2)
 
// ————— MFI line fitted to the visible CVD range
 
int viewLeft = chart.left_visible_bar_time
int viewRight = chart.right_visible_bar_time
int viewSpan = viewRight - viewLeft
// Keep extra bars on both sides so the line does not end at the screen edge while the chart is being dragged.
int bufferTime = math.max(viewSpan * 2, 500 * timeframe.in_seconds() * 1000)
bool isVisible = time >= viewLeft and time <= viewRight
bool isBuffered = time >= viewLeft - bufferTime and time <= viewRight + bufferTime
 
var float cvdHigh = na
var float cvdLow = na
var float mfiHigh = na
var float mfiLow = na
var array<int> mfiTimes = array.new<int>()
var array<float> mfiValues = array.new<float>()
 
if isVisible
    if not na(maxVolume) and not na(minVolume)
        cvdHigh := math.max(nz(cvdHigh, maxVolume), maxVolume)
        cvdLow := math.min(nz(cvdLow, minVolume), minVolume)
    if not na(mf)
        mfiHigh := math.max(nz(mfiHigh, mf), mf)
        mfiLow := math.min(nz(mfiLow, mf), mf)
 
if isBuffered and not na(mf)
    if mfiTimes.size() > 0 and mfiTimes.last() == time
        mfiValues.set(mfiValues.size() - 1, mf)
    else
        mfiTimes.push(time)
        mfiValues.push(mf)
 
// Linear map between the two auto-scale ranges.
type ScaleFit
    float mfiLow
    float mfiHigh
    float cvdLow
    float cvdHigh
 
method toCvdScale(ScaleFit this, float value) =>
    this.cvdLow + (value - this.mfiLow) / (this.mfiHigh - this.mfiLow) * (this.cvdHigh - this.cvdLow)
 
setLevel(line levelLine, float y, color levelColor) =>
    levelLine.set_xy1(viewLeft, y)
    levelLine.set_xy2(viewRight > viewLeft ? viewRight : viewLeft + timeframe.in_seconds() * 1000, y)
    levelLine.set_color(levelColor)
 
var array<polyline> mfiPolylines = array.new<polyline>()
var line overboughtLine = line.new(na, na, na, na, xloc.bar_time, extend.both, style = line.style_dashed)
var line middleLine = line.new(na, na, na, na, xloc.bar_time, extend.both, style = line.style_dashed)
var line oversoldLine = line.new(na, na, na, na, xloc.bar_time, extend.both, style = line.style_dashed)
var linefill background = linefill.new(overboughtLine, oversoldLine, na)
 
if barstate.islast
    for oldPolyline in mfiPolylines
        oldPolyline.delete()
    mfiPolylines.clear()
 
    bool canDraw = not na(cvdHigh) and not na(mfiHigh)
    // TradingView auto-scales a study to its visible plot values plus its horizontal levels. The same two
    // ranges are matched here: MFI line with its levels on one side, CVD candles with the zero line on the
    // other. Everything drawn stays inside the CVD range, so the CVD scale itself is not changed.
    bool fitLevels = showLevelsInput or showBackgroundInput
    float mfiFitHigh = fitLevels ? math.max(mfiHigh, overboughtInput, middleInput, oversoldInput) : mfiHigh
    float mfiFitLow = fitLevels ? math.min(mfiLow, overboughtInput, middleInput, oversoldInput) : mfiLow
    // A flat MFI without levels has no range of its own; fall back to the full 0-100 range.
    bool hasMfiRange = mfiFitHigh > mfiFitLow
    ScaleFit fit = ScaleFit.new(hasMfiRange ? mfiFitLow : 0.0, hasMfiRange ? mfiFitHigh : 100.0, math.min(cvdLow, 0), math.max(cvdHigh, 0))
 
    color levelsColor = showLevelsInput ? levelsColorInput : na
    color middleColor = showLevelsInput ? color.new(levelsColorInput, 50 + color.t(levelsColorInput) / 2) : na
    setLevel(overboughtLine, canDraw ? fit.toCvdScale(overboughtInput) : na, levelsColor)
    setLevel(middleLine, canDraw ? fit.toCvdScale(middleInput) : na, middleColor)
    setLevel(oversoldLine, canDraw ? fit.toCvdScale(oversoldInput) : na, levelsColor)
    background.set_color(showBackgroundInput and canDraw ? backgroundColorInput : na)
 
    if canDraw
        array<chart.point> points = array.new<chart.point>()
        int lastIndex = mfiValues.size() - 1
        for [i, value] in mfiValues
            points.push(chart.point.from_time(mfiTimes.get(i), fit.toCvdScale(value)))
            if points.size() == MAX_POLYLINE_POINTS or i == lastIndex
                if points.size() > 1
                    mfiPolylines.push(polyline.new(points, xloc = xloc.bar_time, line_color = mfiColorInput, line_width = mfiWidthInput))
                // The next chunk starts at the last point so the line stays continuous.
                chart.point joint = points.last()
                points := array.new<chart.point>()
                points.push(joint)

← 返回列表