[SCL] Better Heikin Ashi

SimpleCryptoLife · study · 151 行 · 点赞 1,022 · TradingView 原页

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

Pine Script

//@version=4
study(title="[SCL] Better Heikin Ashi", shorttitle="[SCL] Better Heikin Ashi", overlay=true, linktoseries=true)
 
 
// ============================== ABOUT THIS SCRIPT ==================================
 
// == COPYRIGHT ==
// Script by @SimpleCrpytoLife. This script is open-source.
// > If you use ideas from it, you don't need to ask or give credit to me.
// > If you copy code out of here to adapt for your own script, it must be open-source. You don't need to ask permission, just credit @SimpleCryptoLife. Let me know if you make something cool.
 
// == CREDITS ==
// I looked at a lot of other Heikin Ashi scripts just to see what the comparable functionality is. In the end, all code is my own.
 
// == DESCRIPTION ==
// Heikin Ashi is a different method of calculating candlesticks. It has several advantages:
//      It can help to show the dominant trend in a smoother way than normal candles.
//      Flips in direction can show either trend reversal, or a pause and continuation, which can be a place to join a trend.
// Disadvantages of using Heikin Ashi include:
//      Having to change to a different chart layout
//      Difficulties working directly with Heikin Ashi values, because the values of the Open, Low, High, and Close displayed are different to the "real" prices.
// This indicator solves this problem by bringing trend information from Heikin Ashi candles (whether they're bullish or bearish) onto your normal candle chart. It displays in the main chart pane.
// You can configure the display so that it doesn't conflict with other indicators you already have enabled.
// It also includes a feature to show you how far price would have to travel in order to flip the candle direction.
 
// == USAGE ==
// Works on any market on any timeframe. 
// Heikin Ashi trend flips aren't necessarily entry/exit signals. Use with market structure and support & resistance, as part of your own system.
 
// == SETTINGS ==
// Display Mode: How the Heikin Ashi bull/bear candle information is displayed on the chart:
//      + Bar Colour Classic: Colours the candle bodies red/green
//      + Bar Colour Cool: Colours the candle bodies with an alternate colour scheme
//      + Shapes: Plots little shapes that represent the candle direction, above/below each candle
//      + Flips Only: Plots shpes only when the direction changes
//      + Off: Don't display anything
// Predict Real Close Needed to Flip Colour: Plots the real price at which the candle would need to close in order to change the Heikin Ashi direction.
//      This shows you "how green" or "how red" the current candle is, that is, how far away it is from flipping. 
//      You can use this to decide whether you want to wait for the candle close or take a signal intra-candle.
 
// == ALERTS ==
// .Heikin Ashi Bull Flip: Alerts when the direction changes from bearish to bullish.
// .Heikin Ashi Bear Flip: Alerts when the direction changes from bullish to bearish.
 
// == NO REPAINTING ==
// This indicator does not repaint, meaning, it doesn’t go back and alter any bars in the past.
// However, until a candle closes, the indicator can only use the current price as the "close", and so the drawings, colours and warnings for the current candle 
// will change as the price changes. Once the candle closes, they are fixed.
 
// == DISCLAIMER ==
// You retain full responsibility for your trading at all times. Before trading with actual money, first make sure your risk management is professional-level.
 
 
// ================= INPUTS =================
 
string inputHADisplayMode = input(type=input.string, defval="Bar Colour Classic", title="Display Mode", options=["Bar Colour Classic","Bar Colour Cool","Shapes","Flips Only","Off"])
bool inputShowPredictiveCloses = input(defval=true, type=input.bool, title="Predict Real Close Needed to Flip Colour")
 
 
// ================= CALCULATIONS =================
 
var float HAOpen = 0.0, var float HAClose = 0.0, var float HAHigh = 0.0, var float HALow = 0.0 // OHLC values for HA candles
var bool isHAUp = false, var bool isHADown = false // Is this a red or green HA candle
var bool isHAFlipUp = false, isHAFlipDown = false // Are we flipping red/green?
 
functionHeikinAshi(_open,_close,_high,_low,_HAOpen1,_HAClose1) =>
    // This function calculates the Heikin Ashi values. Coded myself using the formula from Investopedia.
    float _iHAOpen = barstate.isfirst ? (_open + _close) / 2 : (_HAOpen1 + _HAClose1) / 2 // Some formulations on the internet just use HAOpen = open for the first bar.
    float _iHAClose = (_open + _close + _high + _low)/4
    float _iHAHigh = barstate.isfirst ? _high : max(_high,_iHAOpen,_iHAClose) // Not currently used; included for completeness
    float _iHALow = barstate.isfirst ? _low : min(_low,_iHAOpen,_iHAClose) // Not currently used; included for completeness
    bool _iIsHAUp = _iHAClose > _iHAOpen
    bool _iIsHADown = _iHAClose <= _iHAOpen
    [_iHAOpen,_iHAClose,_iHAHigh,_iHALow,_iIsHAUp,_iIsHADown]
 
[r_HAOpen,r_HAClose,r_HAHigh,r_HALow,r_isHAUp,r_isHADown] = functionHeikinAshi(open,close,high,low,HAOpen[1],HAClose[1])
HAOpen := r_HAOpen, HAClose := r_HAClose, isHAUp := r_isHAUp, isHADown := r_isHADown
// HAHigh := r_HAHigh, HALow := r_HALow // We don't actually need these to determine red or green Heikin Ashi.
 
isHAFlipUp := isHAUp and isHADown[1] // The flip variable is only true on the first flipped bar
isHAFlipDown := isHADown and isHAUp[1]
 
 
// === Predicting the Close ===
 
// We want to know what price the real Close would have to be in order to flip the candle to the opposite colour.
// This price changes intra-candle as the High, Low, and Close values change.
//      We calculate it by reverse-engineering the Heikin Ashi Close: HA Close = (open + high + low + close)/4
//      And assuming that it has to be equal to the Heikin Ashi Open, because the Heikin Ashi candle has to close the opposite side of its open in order to change the colour.
// If you assume that the Close is equal to the Low or High as appropriate, you get inaccurate results when the projected close is within the candle.
// But if you use the actual Low and High values when the projected price is outside the candle, the projected close moves rapidly towards price, which doesn't make any sense.
// So we have to iterate and then pick a side in order to make it accurate.
// If the line projected using High and Low is below the Low, then use 2x Close instead of Low.
// If the line projected using High and Low is above the High, then use 2x Close instead of High.
// If the line projected using High and Low is between the current High and Low, use it as-is.
 
functionHAPredictClose(_HAOpen) =>
    // This function predicts the price of the close that would be needed to flip the Heikin Ashi colour of the current bar only
    float _closeInside = (4 * _HAOpen) -open -high -low // Version that works inside candles
    float _closeBelow = (2 * _HAOpen) -((open+high)/2) // Version that works below candles
    float _closeAbove = (2 * _HAOpen) -((open+low)/2) // Version that works above candles
    _close = _closeInside > high ? _closeAbove : _closeInside < low ? _closeBelow : _closeInside // Choose the right formula depending where the projection is
 
float HAPredictiveClose = functionHAPredictClose(HAOpen) 
 
 
// ================= PLOTS =================
 
var color HABarUpColour = inputHADisplayMode == "Bar Colour Classic" ? color.green : inputHADisplayMode == "Bar Colour Cool" ? #00bbbb : na
var color HABarDownColour = inputHADisplayMode == "Bar Colour Classic" ? color.red : inputHADisplayMode == "Bar Colour Cool" ? color.maroon : na
// Colour the candles if that option is set
color HABarColour = inputHADisplayMode != "Bar Colour Classic" and inputHADisplayMode != "Bar Colour Cool" ? na : isHAUp ? HABarUpColour : isHADown ? HABarDownColour : color.yellow 
barcolor(title="Heikin Ashi Bar Colour", color=HABarColour)
 
bool HAShapeUp = isHAUp and inputHADisplayMode == "Shapes", bool HAShapeDown = isHADown and inputHADisplayMode == "Shapes" // Plot little circles if that option is set
plotshape(HAShapeUp, title="Heikin Ashi Bullish Shape", style=shape.circle, location=location.belowbar, color=color.green, size=size.tiny, transp=20)
plotshape(HAShapeDown, title="Heikin Ashi Bearish Shape", style=shape.circle, location=location.abovebar, color=color.red, size=size.tiny, transp=20)
 
bool HAShapeFlipUp = isHAFlipUp and inputHADisplayMode == "Flips Only", bool HAShapeFlipDown = isHAFlipDown and inputHADisplayMode == "Flips Only",
plotshape(HAShapeFlipUp, title="Heikin Ashi Bullish Flip Shape", style=shape.circle, location=location.belowbar, color=color.green, size=size.small, transp=20)
plotshape(HAShapeFlipDown, title="Heikin Ashi Bearish Flip Shape", style=shape.circle, location=location.abovebar, color=color.red, size=size.small, transp=20)
 
 
// Plot line for predictive Heikin Ashi close
functionHLine(_condition,_x1,_y1,_x2,_y2,_color,_style,_width,_extend) =>
    // Draw a horizontal line at the current bar when _condition is true
    if _condition
        line.new(x1=_x1, y1=_y1, x2=_x2, y2=_y2, color=_color, style=_style, width=_width,extend=_extend)
 
color HAPredictiveColour = isHAUp ? color.red : isHADown ? color.green : color.yellow
 
line HAPredictiveCloseLine = functionHLine(inputShowPredictiveCloses,bar_index,HAPredictiveClose,bar_index-1,HAPredictiveClose,HAPredictiveColour,line.style_dotted,1,extend.left)
line.delete(HAPredictiveCloseLine[1]) // Delete previous lines and keep only the one on the current bar
 
 
// ================= ALERTS =================
 
alertcondition(isHAFlipUp, title=".Heikin Ashi Bull Flip", message="REMEMBER to choose Options > On Close to avoid false alerts \n The Heikin Ashi trend flipped to bullish from bearish.")
alertcondition(isHAFlipDown, title=".Heikin Ashi Bear Flip", message="REMEMBER to choose Options > On Close to avoid false alerts \n The Heikin Ashi trend flipped to bearish from bullish.")
 
 
// // === DEBUG ===
// Draw candles using the HA values
// plotcandle(HAOpen, HAHigh, HALow, HAClose, title="DEBUG: Heikin Ashi candles", color = isHAUp ? color.green : isHADown ? color.red : color.yellow, wickcolor = color.white, bordercolor = color.white)
 
 
// ============================== //
//                                //
//   (╯°□°)╯︵ oʎ nsǝp ɐʞɐq      //
//                                //
// ============================== //

← 返回列表