Indicator · Pine Script v5 · Own pane

Trading Psychology - Fear & Greed Index by DGT

by f-cksociety

The script calculates a variant of the Fear & Greed Index using rate of return, accumulation distribution money flow weighted by volume, and volatility from VIX.

View on GitHub

Repaints

GitHub stars11on the repository
Pine versionv5runs as is
Lines of code194
Settings6inputs
LicenceMPL-2.0
Last update4 years ago20 Sep 2022

Add It to Your TradingView Chart

  1. 1Copy the scriptPress Copy script above, or the copy button on the code below.
  2. 2Open the Pine EditorOpen a TradingView chart and choose Pine Editor at the bottom of the screen.
  3. 3Paste over the templateCreate a new indicator, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart, then adjust the settings with the gear icon next to its name.

Source Code

194 lines of Pine Script v5 from signal-ext/fg-cycle.pine, published under MPL-2.0. Keep the author's credit and licence lines when you reuse it.

fg-cycle.pine
//@version=5
// ══════════════════════════════════════════════════════════════════════════════════════════════════ //
//# * ══════════════════════════════════════════════════════════════════════════════════════════════
//# *
//# * Study       : Trading Psychology - Fear & Greed Index by DGT
//# * Author      : © dgtrd
//# *
//# * Revision History
//# *  Release    : Jul 21, 2020
//# *  Update     : Apr 09, 2021 : Added ability to display Current Time Frame's Fear and Greed Index
//# *  Update     : Apr 09, 2022 : Added Price Candle display option with Fear & Greed weighted risk levels 
//# *
//# * ══════════════════════════════════════════════════════════════════════════════════════════════
// ══════════════════════════════════════════════════════════════════════════════════════════════════ //

indicator('Trading Psychology - Fear & Greed Index by DGT', 'F&G CYCLE ʙʏ DGT ☼☾', false, max_bars_back=252)

// -Inputs ====================================================================================== //

display = input.string('Fear & Greed Index', 'Display as', options=['Price Candles', 'Fear & Greed Index'])
smoothLength = input.int(5, 'RMA Smoothing Length', minval=1, maxval=13)
faster = input(false, 'Fear & Greed Index : Calculation with Faster Legths')
daily = input(false, 'Display Daily Time Frame Calculated Value')
lagendDesc = input(true, 'Show Color Legend')
hLabel = input(false, 'Hide Statistical Label')


fastLength = faster ? 13 : 21
slowLength = faster ? 89 : 144

// -Calculations ================================================================================ //

pmacd = (close / ta.ema(close, slowLength) - 1) * 100
pmacd_d = request.security(syminfo.tickerid, 'D', pmacd, barmerge.gaps_off, barmerge.lookahead_on)

ror = (close - close[slowLength]) / close[slowLength] * 100
ror_d = request.security(syminfo.tickerid, 'D', ror, barmerge.gaps_off, barmerge.lookahead_on)

accDist = close == high and close == low or high == low ? 0 : (2 * close - low - high) / (high - low)
nzVolume = nz(volume)
moneyFlow = math.sum(accDist * nzVolume, fastLength) / math.sum(nzVolume, fastLength) * 100

accDist_d = request.security(syminfo.tickerid, 'D', accDist, barmerge.gaps_off, barmerge.lookahead_on)
nzVolume_d = request.security(syminfo.tickerid, 'D', nzVolume)
moneyFlow_d = math.sum(accDist_d * nzVolume_d, fastLength) / math.sum(nzVolume_d, fastLength) * 100

vix = request.security('VIX', timeframe.period, -(close / ta.ema(close, slowLength) - 1) * 100, barmerge.gaps_off, barmerge.lookahead_on)
vix_d = request.security('VIX', 'D', -(close / ta.ema(close, slowLength) - 1) * 100, barmerge.gaps_off, barmerge.lookahead_on)

gold = request.security('GOLD', timeframe.period, -(1 - close[fastLength] / close) * 100, barmerge.gaps_off, barmerge.lookahead_on)
gold_d = request.security('GOLD', 'D', -(1 - close[fastLength] / close) * 100, barmerge.gaps_off, barmerge.lookahead_on)

cycle_raw = nzVolume ? math.avg(pmacd, ror, moneyFlow, vix, gold) : math.avg(pmacd, ror, vix, gold)
cycle_raw_d = nzVolume_d ? math.avg(pmacd_d, ror_d, moneyFlow_d, vix_d, gold_d) : math.avg(pmacd_d, ror_d, vix_d, gold_d)

cycle = ta.rma(cycle_raw, smoothLength)
cycle_d = ta.rma(cycle_raw_d, smoothLength)

f_getText(_cycle) =>
    if _cycle > 73
        'Extreame Greed'
    else if _cycle > 33
        'Greed'
    else if _cycle < -25
        'Fear'
    else if _cycle < -41
        'Extreame Fear'
    else
        'Neutral'

f_getColor(_cycle) =>
    if _cycle >= 73
        #006400
    else if _cycle >= 63 and _cycle < 73
        #007439
    else if _cycle >= 52 and _cycle < 63
        #008368
    else if _cycle >= 41 and _cycle < 52
        #009096
    else if _cycle >= 30 and _cycle < 41
        #009bbf
    else if _cycle >= 20 and _cycle < 30
        #00a4df
    else if _cycle >= 10 and _cycle < 20
        #00a4df
    else if _cycle >= 5 and _cycle < 10
        #65a095
    else if _cycle < -5 and _cycle >= -10
        #b7b763
    else if _cycle < -10 and _cycle >= -15
        #fafa6e
    else if _cycle < -15 and _cycle >= -20
        #fecb35
    else if _cycle < -20 and _cycle >= -25
        #ff9800
    else if _cycle < -25 and _cycle >= -31
        #ff7434
    else if _cycle < -31 and _cycle >= -37
        #ff5252
    else if _cycle < -37 and _cycle >= -41
        #c72e29
    else if _cycle < -41
        #910000
    else
        #92928f

f_getColor1(_cycle) =>
    if _cycle >= 73
        #910000
    else if _cycle >= 63 and _cycle  <  73
        #c72e29
    else if _cycle >= 52 and _cycle  <  63
        #ff5252
    else if _cycle >= 41 and _cycle  <  52
        #ff7434
    else if _cycle >= 30 and _cycle  <  41
        #ff9800
    else if _cycle >= 20 and _cycle  <  30
        #fecb35
    else if _cycle >= 10 and _cycle  <  20
        #fafa6e
    else if _cycle >= 5  and _cycle  <  10
        #b7b763
    else if _cycle < -5  and _cycle >= -10
        #65a095
    else if _cycle < -10 and _cycle >= -15
        #00a4df
    else if _cycle < -15 and _cycle >= -20
        #00a4df
    else if _cycle < -20 and _cycle >= -25
        #009bbf
    else if _cycle < -25 and _cycle >= -31
        #009096
    else if _cycle < -31 and _cycle >= -37
        #008368
    else if _cycle < -37 and _cycle >= -41
        #007439
    else if _cycle < -41 
        #006400
    else
        #92928f

// -Plotting ==================================================================================== //

fgColor = daily ? f_getColor(cycle_d) : f_getColor(cycle)
plot(display == 'Fear & Greed Index' ? daily ? cycle_d : cycle : na, 'Psychology of The Market Cycle - Index Display', fgColor, 2)

var label fgiLabel = na
if not hLabel
    fgiLabel := label.new(time + math.round(ta.change(time) * 7), display == 'Price Candles' ? close : daily ? cycle_d : cycle, (daily ? '*Daily' : 'Daily') + ' Time Frame : ' + f_getText(cycle_d) + ' : ' + 
                             str.tostring(math.round(cycle_d, 2)) + '%\n' + (daily ? 'Current' : '*Current') + ' Time Frame (' + timeframe.period + ') : ' + f_getText(cycle) + ' : ' + 
                             str.tostring(math.round(cycle, 2)) + '%', xloc.bar_time, tooltip='Psychology of The Market Cycle by DGT\n\n' + 'Fear & Greed Index :\nDaily Time Frame : ' + f_getText(cycle_d) + ' : ' + 
                             str.tostring(math.round(cycle_d, 2)) + '%\nCurrent Time Frame (' + timeframe.period + ') : ' + f_getText(cycle) + ' : ' + 
                             str.tostring(math.round(cycle, 2)) + '%' + '%\n\nReference Sources : ' + '\n-------------------------------------------------------------------' + 
                             '\n 1 - Price Convergence/Divergence to/from its Moving Average (' + str.tostring(slowLength) + ') :\n     Daily TF ' + str.tostring(math.round(pmacd_d, 2)) + '% / Current TF ' + str.tostring(math.round(pmacd, 2)) + '%' + 
                             '\n 2 - Rate of Return (Momentum/RoC), Length (' + str.tostring(slowLength) + ') :\n     Daily TF ' + str.tostring(math.round(ror_d, 2)) + '% / Current TF ' + str.tostring(math.round(ror, 2)) + '%' + 
                             '\n 3 - Chaikin Money Flow, Length (' + str.tostring(fastLength) + ') :\n     Daily TF ' + str.tostring(math.round(moneyFlow_d, 2)) + '% / Current TF ' + str.tostring(math.round(moneyFlow, 2)) + '% \n      ps: cmf calculated only if volume data is provided' + 
                             '\n 4 - VIX - Volatility (Fear) Index, Length (' + str.tostring(slowLength) + ') :\n     Daily TF ' + str.tostring(math.round(vix_d, 2)) + '% / Current TF ' + str.tostring(math.round(vix, 2)) + '%' + 
                             '\n 5 - Safe Haven Demand - Gold Demand, Length (' + str.tostring(fastLength) + ') :\n     Daily TF ' + str.tostring(math.round(gold_d, 2)) + '% / Current TF ' + str.tostring(math.round(gold, 2)) + '%' + 
                             '\n\nWarren Buffett’s quote, buy when others are fearful, and sell when others are greedy', color=color.new(color.gray, 85), style=label.style_label_left, textcolor=color.gray, textalign=text.align_left)

label.delete(fgiLabel[1])

var o = 0., var h = 0., var l = 0., var c = 0.

if display == 'Price Candles'
    o := open, h := high, l := low, c := close

fgColor := daily ? f_getColor1(cycle_d) : f_getColor1(cycle)

if display == 'Fear & Greed Index'
    fgColor := na

plotcandle(o, h, l, c, 'Psychology of The Market Cycle - Price Display', fgColor, fgColor, bordercolor = fgColor)

var table logo = table.new(position.bottom_right, 1, 1)
table.cell(logo, 0, 0, "☼☾  ", text_size = size.normal, text_color = color.teal)


var table legend = table.new(position.middle_right   , 1, 5)

if lagendDesc
    if display == 'Price Candles'
        table.cell(legend, 0, 0, "Max Opportunity █", text_size = size.small, text_color = #006400, text_halign = text.align_right)
        table.cell(legend, 0, 1, "Opportunity █", text_size = size.small, text_color = #008368, text_halign = text.align_right)
        table.cell(legend, 0, 2, "Neutral █", text_size = size.small, text_color = #92928f, text_halign = text.align_right)
        table.cell(legend, 0, 3, "Risk █", text_size = size.small, text_color = #ff7434, text_halign = text.align_right)
        table.cell(legend, 0, 4, "Max Rsik █", text_size = size.small, text_color = #910000, text_halign = text.align_right)
    else
        table.cell(legend, 0, 0, "Extreame Greed █", text_size = size.small, text_color = #006400, text_halign = text.align_right)
        table.cell(legend, 0, 1, "Greed █", text_size = size.small, text_color = #008368, text_halign = text.align_right)
        table.cell(legend, 0, 2, "Neutral █", text_size = size.small, text_color = #92928f, text_halign = text.align_right)
        table.cell(legend, 0, 3, "Fear █", text_size = size.small, text_color = #ff7434, text_halign = text.align_right)
        table.cell(legend, 0, 4, "Extreame Fear █", text_size = size.small, text_color = #910000, text_halign = text.align_right)

Overview

Trading Psychology - Fear & Greed Index by DGT offers display options for the raw index value or price candles scaled by the index level. Smoothing via RMA, faster or standard calculation lengths, and daily timeframe values are configurable. The indicator renders in a dedicated pane beneath the main price chart with optional color legend and statistical labels.

Details

Published by

f-cksociety on GitHub

Type

Indicator, Pine Script v5

Draws

Separate pane below the chart

Category

Oscillators & momentum, Volatility & bands, Volume

Markets

Any symbol

Timeframes

Any timeframe

Risk Notes

  • Reads higher-timeframe data with lookahead on, so the history can show signals that were not there in real time

Settings

The inputs you can change from the gear icon on the chart. Defaults are the author's.

SettingTypeDefaultVariable
Display asstringFear & Greed Indexdisplay
RMA Smoothing Lengthint5smoothLength
Fear & Greed Index : Calculation with Faster Legthsboolfalsefaster
Display Daily Time Frame Calculated Valueboolfalsedaily
Show Color LegendbooltruelagendDesc
Hide Statistical LabelboolfalsehLabel
Third-party code. ForexR did not write, test or endorse this script, and the summary above was generated automatically from its code and README. Indicators describe the past, and a strategy's backtest can look better than live trading, especially when a script repaints. Check it in the Strategy Tester and on a demo account before you rely on it.

Similar Pine Scripts

114 stars

This indicator standardizes price inputs using z-score normalization before calculating a relative strength index (RSI). It generates trade signals when standardized price components cross over or under the standardized RSI feature. Signals can be filtered by

Indicator v4 Oscillators & momentumVolatility & bands Repaints
Updated 1 year ago · None stated GitHub repository of Preprosessed & Standardized RSI

PPO ATR Bands

by cryptorife
75 stars

PPO ATR Bands plots a percentage price oscillator in a separate pane. It compares a Hull average of typical price with a volume-weighted exponential average of Parabolic SAR, then scales three true-range bands around the slow average into matching oscillator l

Indicator v4 Oscillators & momentumMoving averages
Updated 3 years ago · GPL-3.0 GitHub repository of PPO ATR Bands

This indicator calculates the Relative Strength Index (RSI) alongside a simple moving average to generate directional momentum signals in a separate pane. It supports Break Flip and Break Continuous scanning modes for long and short setups. A wide array of opt

Indicator v5 Oscillators & momentumVolatility & bands
Updated 1 year ago · None stated GitHub repository of Momentum Setup: RSI Direction Confirmation

NFI v6

by koradiyakaushal
12 stars

This Pine v4 study ports early NostalgiaForInfinity V6 conditions onto the price chart. It computes two Bollinger setups, several EMAs and SMAs, RSI, MFI, a percent SMA spread labeled EWO, a 14-period choppiness value, and short and longer volume medians. Fixe

Indicator v4 Moving averagesVolatility & bands
Updated 5 years ago · MIT GitHub repository of NFI v6

ACE Squeeze

by JasonTeixeira
9 stars

ACE Squeeze plots a cycle-based squeeze oscillator in a separate pane. It builds a histogram and an optional cycle phase line from a base cycle length, sensitivity, and price source, then can adjust the reading with volatility, volume delta, relative range exp

Indicator v6 Oscillators & momentumVolatility & bands
Updated 12 days ago · Custom licence GitHub repository of ACE Squeeze

More indicators

Trade Your Charts With a Regulated Broker

Compare brokers that connect to TradingView, with spreads, minimum deposits and leverage side by side.

Compare brokers