Indicator · Pine Script v4 · Own pane

Polarized Fractal Efficiency

by capissimo

Polarized Fractal Efficiency plots a custom efficiency oscillator in a separate pane.

View on GitHub

GitHub stars114on the repository
Pine versionv4older, still runs
Lines of code190
Settings8inputs
LicenceNone statedfile: MPL-2.0
Last update1 year ago7 Nov 2024

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

190 lines of Pine Script v4 from scripts/117-Polarized-Fractal-Efficiency.pine, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

117-Polarized-Fractal-Efficiency.pine
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © capissimo

//@version=4
study('Polarized Fractal Efficiency', '', false)

// Polarized Fractal Efficiency

// Description:

// Technically, Polarized Fractal Efficiency (PFE) is a measure of market 
// choppiness. It is an indicator derived from fractal geometry, the 
// mathematics that describes chaotic systems.

// This technical indicator was developed by Hans Hannula to determine price 
// efficiency over a user-defined period. This indicator fluctuates between 
// -100 and +100, with 0 as the centerline. Securities with a PFE 
// greater than zero are deemed to be trending up, while a reading of 
// less than zero indicates the trend is down. Polarized Fractal 
// Efficiency's signature characteristic is its use of fractal geometry 
// in determining how efficiently a security's price is moving.

// This script uses a customized version of PFE formula and generates a long  
// entry signal when the Polarized Fractional Efficiency (PFE) value crosses  
// over a signal line, and/or generates a short entry signal when the PFE  
// value crosses under a signal line.

// The Polarized Fractional Efficiency indicator can be used to determine
// price efficiency over a user-defined time period. Assets with a PFE  
// greater than zero are deemed to be trending up, while a reading of less 
// than zero indicates the trend is down. The strengh of the trend is  
// measured by the position of the PFE relative to the zero line. 

// As a general rule, the further the PFE value is away from zero, 
// the stronger and more efficient the given trend is. A PFE value that 
// fluctuates around the zero line could indicate that the supply and 
// demand for the security are in balance and price may trade sideways.

// Optional setup: try out InsideOut with 5 lag

//-------------------- Inputs

ptype  = input('Close',  'Price Type',              options=['Open','High','Low','Close','HL2','OC2','OHL3','HLC3','OHLC4'])
lag    = input(10,       'Indicator Lag |3..n|',    minval=3)
m      = input(5,        'Smoothing Period |1..n|', minval=1)
method = input('Center', 'Signal Method',           options=['Center','InsideOut'])
bound  = input(10.0,     'Bounds |0.0..100.0|',     minval=0.0)
ftype  = input('None',   'Filter Signals by',       options=['Volatility','Volume','Both','None'])

//-------------------- System Variables

var int BUY  =  1
var int SELL = -1
var int HOLD =  0

//-------------------- Series

var bool long   = 0.0
var bool short  = 0.0
var int  signal = HOLD

//-------------------- Custom Functions

pfe(ds, lag, smooth) =>  //-- Polarized Fractal Efficiency (custom version!)
    x   = sqrt(pow(ds - ds[lag], 2) + pow(lag, 2))
    y   = sum(sqrt(pow(ds - ds[lag], 2) + 1), lag-2)
    pct = 100 * x / y
    pct_corr = ds < ds[1] ? -pct : pct
    ema(pct_corr, smooth)

volumeBreak(thres) =>  
    rsivol   = rsi(volume, 14)  
    osc      = hma(rsivol, 10)  
    osc > thres                     

volatilityBreak(volmin, volmax) => atr(volmin) > atr(volmax)

//-------------------- Logic

tbase   = (time - time[1]) / 1000
tcurr   = (timenow - time_close[1]) / 1000
barlife = tcurr / tbase

base =  ptype=='Open'  ? open 
      : ptype=='High'  ? high
      : ptype=='Low'   ? low
      : ptype=='Close' ? close
      : ptype=='OC2'   ? (open+close)/2 
      : ptype=='HL2'   ? hl2 
      : ptype=='OHL3'  ? (open+high+low)/3 
      : ptype=='HLC3'  ? hlc3 
      :                  ohlc4

filter =   ftype=='Volatility' ? volatilityBreak(1, 10) 
         : ftype=='Volume'     ? volumeBreak(49) 
         : ftype=='Both'       ? volatilityBreak(1, 10) and volumeBreak(49)
         :                       true

pfevalue = pfe(base, lag, m)

if method=='Center'
    long  := crossover(pfevalue,  HOLD) 
    short := crossunder(pfevalue, HOLD) 
else
    if method=='InsideOut'
        long  := crossover(pfevalue,   bound) 
        short := crossunder(pfevalue, -bound) 
    else 
        if method=='OutsideIn'
            long  := crossunder(pfevalue, bound) 
            short := crossover(pfevalue, -bound) 

signal := long and filter ? BUY : short and filter ? SELL : nz(signal[1])

changed = change(signal)

startLongTrade  = changed and signal==BUY
startShortTrade = changed and signal==SELL
endLongTrade    = changed and signal==SELL
endShortTrade   = changed and signal==BUY

//-------------------- Visualization

hline(HOLD)
hline(bound)
hline(-bound)
plot(pfevalue)

plotshape(startLongTrade  ? -bound : na, 'Buy',  shape.labelup,   location.absolute, color.blue, size=size.tiny) 
plotshape(startShortTrade ?  bound : na, 'Sell', shape.labeldown, location.absolute, color.red,  size=size.tiny) 
plot(endLongTrade         ? HOLD   : na, 'StopBuy',  color.blue, 1, plot.style_cross)
plot(endShortTrade        ? HOLD   : na, 'StopSell', color.red,  1, plot.style_cross)

//-------------------- Notification

if changed and signal==BUY 
    alert('Buy Alert', alert.freq_once_per_bar)  // alert.freq_once_per_bar_close
if changed and signal==SELL 
    alert('Sell Alert', alert.freq_once_per_bar)
    
alertcondition(startLongTrade,  'Buy Alert',  'Go Long!')
alertcondition(startShortTrade, 'Sell Alert', 'Go Short!')

//-------------------- Backtest

show_info = input(false, '===Information===')
lot_size  = input(0.01,  'Lot Size', options=[0.01,0.1,0.2,0.3,0.5,1,2,3,5,10,20,30,50,100,1000]) 

bidask = open //-- (open+high+low)/3 is a more restrained estimate

var float start_long_trade  = bidask  
var float long_trades       = 0.
var float start_short_trade = bidask  
var float short_trades      = 0.
var int   wins              = 0
var int   trade_count       = 0

if startLongTrade 
    start_long_trade := bidask 
if endLongTrade
    ldiff         = (bidask - start_long_trade)
    wins         := ldiff > 0 ? 1 : 0
    long_trades  := ldiff * lot_size   
    trade_count  := 1
if startShortTrade 
    start_short_trade := bidask
if endShortTrade
    sdiff         = (start_short_trade - bidask)
    wins         := sdiff > 0 ? 1 : 0
    short_trades := sdiff * lot_size 
    trade_count  := 1
    
cumreturn   = cum(long_trades) + cum(short_trades)  //-- cumulative return 
totaltrades = cum(trade_count)
totalwins   = cum(wins)  
totallosses = totaltrades - totalwins == 0 ? 1 : totaltrades - totalwins

//------------------- Information

var label lbl = na

info =  ptype
      + '\nCR='        + tostring(cumreturn,             '#.#') 
      + '\nWinrate: '  + tostring(totalwins/totaltrades, '#.#%')       
      + '\nBar Time: ' + tostring(barlife,               '#.#%')

if show_info and barstate.islast  
    lbl := label.new(bar_index, HOLD, info, xloc.bar_index, yloc.price, 
                     color.new(color.blue, 100), label.style_label_left, color.black, size.small, text.align_left)
    label.delete(lbl[1])

Overview

Polarized Fractal Efficiency compares net price movement over a lag with the path of successive moves, signs the result by recent direction, and smooths it with an exponential moving average. Readings above zero indicate an upward trend and readings below zero a downward trend. It marks a long when the value crosses above a signal line and a short when it crosses below. Users choose the price source, lag, smoothing, Center or InsideOut method, bounds, and optional volume or volatility filters. It does not place trades or define exits.

Details

Published by

capissimo on GitHub

Type

Indicator, Pine Script v4

Draws

Separate pane below the chart

Category

Trend, Oscillators & momentum

Markets

Any symbol

Timeframes

Any timeframe

Risk Notes

No repainting, lookahead or stacked entries were found in its code or README. That says nothing about how well it works: test it first.

Settings

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

SettingTypeDefaultVariable
Price TypestringCloseptype
Indicator Lag |3..n|int10lag
Smoothing Period |1..n|int5m
Signal MethodstringCentermethod
Bounds |0.0..100.0|float10.0bound
Filter Signals bystringNoneftype
===Information===boolfalseshow_info
Lot Sizefloat0.01lot_size
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

Schaff Trend Cycle

by everget
948 stars

This indicator plots the Schaff Trend Cycle in a separate pane. It subtracts a slow exponential moving average from a fast one, applies a stochastic cycle twice, and smooths each result to form a 0–100 oscillator. Line color follows the slope, or the upper and

Indicator v4 Oscillators & momentumTrend
Updated 10 days ago · GPL-3.0 GitHub repository of Schaff Trend Cycle

Beep Boop

by magic8bot
409 stars

This indicator calculates a modified MACD oscillator and signal line alongside a trend EMA filter, plotting the output as a stylized column histogram in a separate pane. Instead of plotting true MACD distance, it quantifies positive and negative histogram mome

Indicator v4 Oscillators & momentumTrend
Updated 3 years ago · MIT GitHub repository of Beep Boop

[RS]Standardized Trend Map

by ricardosantos79
261 stars

Standardized Trend Map calculates series momentum relative to active price range across 40 distinct lookback periods ranging from 2 to 80 bars on an exponential moving average source. Each standardized calculation rounds to an integer values of -1, 0, or 1 to

Indicator v4 TrendOscillators & momentum
Updated 4 years ago · None stated GitHub repository of [RS]Standardized Trend Map

ADX Histogram

by harryguiacorn
219 stars

This indicator calculates and displays the Average Directional Index (ADX) as a column histogram in a separate pane. It evaluates market trend strength by calculating directional movement metrics based on specified smoothing and DI length inputs. When the ADX

Indicator v5 TrendOscillators & momentum
Updated 1 year ago · None stated GitHub repository of ADX Histogram
218 stars

Multi-Timeframe Analysis Suite calculates trend direction and momentum conditions across five user-selected timeframes using moving averages, RSI, and Stochastic oscillators. It evaluates moving average slope and oscillator levels to compute trend alignment, m

Indicator v6 Screeners & dashboardsTrend
Updated 3 months ago · None stated GitHub repository of Multi-Timeframe Analysis Suite

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