fbpx

What Are Units In TradingView? An In-Depth Guide

TradingView is one of the most popular charting platforms with a highly flexible indicator creation language called Pine Script. Pine Script has many features for building robust trading systems and indicators. One key capability is the ability to specify custom units for values.

Understanding how to set and use units appropriately is essential for developing accurate and robust Pine code. In this post, we’ll take an in-depth look at units in TradingView to gain a solid grasp of their functionality.

What Are Units In Tradingview

What are TradingView Units?

TradingView units allow specifying the type of values used in Pine Script variables and returned by functions. They define what the values represent and how they should be interpreted.

Some examples of units you may commonly see in TradingView Pine code:

  • currency – For monetary or currency values like profit, price or stop loss.
  • percent – For percentage values like a win rate or RSI value.
  • barssince – For count values like number of bars since entry.
  • points – For numeric point values like aMoving Average crossover amount.

Units give meaning to numeric values and tell Pine Script how to handle them appropriately in charts, alerts and strategy logic.

Why Units Matter in Pine Script

Specifying proper units for variables in Pine is crucial because:

  • It enables correct math operations. Can’t add points to currency directly.
  • Values are formatted correctly on charts. Currency shown with currency sign.
  • Strategy logic handles values properly. 10 points is not same as 10% in code.
  • Plot colors and visual types adapt based on unit type.
  • Strategy analyzer accounts for unit types properly in backtests.

Without units, Pine has no way to know how to interpret and handle values properly. Bugs, improper plotting and wrong calculations can occur.

Spark Impulse strategy

Access to our Spark Impulse Indicator for Tradingview Platform

Built-In TradingView Unit Types

TradingView Pine Script has a variety of built-in units for all types of values:

Currency Units:

  • currency – Base currency unit, typically USD. -USD – US Dollars. -EUR – Euros -JPY – Japanese Yen -GBP – British Pound -etc.

Numeric Units:

  • percent – Percentage values from 0 to 100.
  • basispoints – Used for interest rates.
  • percentofequity – Percent relative to equity.
  • points – Generic numeric points unit.
  • bars – For bar counts and lengths.

Time Units:

  • day – Number of days.
  • hour – Number of hours.
  • minute – Number of minutes.
  • second – Number of seconds.

Date Units:

  • year – Counts years.
  • month – Counts months.
  • week – Counts weeks.
  • day – Counts days.

Other Special Units:

  • barssince – Counts number of bars since an event.
  • barduration – Measures bar length by time.
  • tickduration – Measures tick length by time.

The built-in units cover most common types of values used in trading strategies and indicators.

Specifying Units in Variable declarations

When declaring a variable in Pine, you specify its unit using the brackets syntax like:

// Long entry stop loss
longStop = 20 [currency]

// Percentage units 
winRate = 55 [percent] 

// Measuring bar count
barsSinceEntry = 10 [barssince]

Declaring the unit at initialization ensures the variable is treated as that type going forward.

Returning Units from Functions

When creating a custom Pine Script function, you can specify the unit it returns using:

// Returns currency value
myfxn() => 
    return 20 [currency]

// Returns percentage 
rsi() =>
    return rsiVal [percent]

Much like variable declarations, this tells Pine the type of data returned so it can be handled properly.

Operating on Different Unit Types

When combining values of different units, Pine Script does some automatic conversion:

  • Currency values are added/subtracted as absolutes.
  • Percent and basispoint values are treated as decimals of 1.
  • Points are assumed to be currency value decimals.

For example:

// Adding currency
profit = 20 [currency]
profit += 10 [currency] // Totals 30

// Percentages  
winRate = 55 [percent] 
winRate += 25 [percent] // Totals 80

// Points treated as currency  
stopLoss = 20 [points]
stopLoss += 50 [points] // Totals 0.70

Pine does its best to convert, but mixing units unpredictably can still cause issues. Explicitly converting units is best practice when operating on different types.

Converting Between Unit Types

You can explicitly convert between units in Pine Script using the to() syntax:

// Convert currency to points
riskAmt = 100 [currency]
riskPts = riskAmt.tofloat() / syminfo.mintick 

// Convert points to percent
atrPts = atr(14)
atrPct = atrPts.tofloat() / close * 100 [percent]

The .tounit() methods allow converting to any built-in or custom unit type as needed. This helps avoid unit mixup bugs.

Creating Custom Units

Beyond built-in units, Pine Script allows defining custom units for proprietary values:

// Define new unit type
newUnit = unit("widgets")

// Declare variable with custom unit
widgets = 56 [widgets]

// Return value using custom unit
getNumWidgets() => 
    int widgets = 10 [widgets]
    return widgets

Custom units help properly type specialized values in indicators and strategies.

Key Benefits of Typed Units

Here are the main advantages of leveraging units in Pine Script:

  • Clarifies intended use of values
  • Enables correct math operations
  • Formats values appropriately on charts
  • Helps strategy analyzer handle values properly
  • Avoids unpredictable type conversion bugs
  • Improves code clarity and readability

In summary, properly typing values with units is a best practice that prevents subtle but serious errors in Pine Script programs. Mastering units ultimately leads to more reliable, robust indicators and strategies.

Conclusion

Understanding the various built-in and custom unit types available in TradingView Pine Script unlocks more powerful scripting capabilities. Specifying units for variables, function returns, and custom types brings structure and minimizes unintended behavior when values are combined and manipulated. While new users may gloss over units at first, they are well worth learning as Pine Script skills grow. Robustly typed values translate to robust Pine code.

Author: Dominic Walsh
blank

I am a highly regarded trader, author & coach with over 16 years of experience trading financial markets. Today I am recognized by many as a forex strategy developer. After starting blogging in 2014, I became one of the world's most widely followed forex trading coaches, with a monthly readership of more than 40,000 traders! Make sure to follow me on social media: Instagram | Facebook | Linkedin | Youtube| Twitter | Pinterest | Medium | Quora | Reddit | Telegram Channel

Leave a Comment

Hey.lt - Nemokamas lankytojų skaitliukas