Basic Pine Script Structure
Basic Pine Script Structure
PineScript is Domain-specific language for TradingView platform. It is designed for technical analysis and strategy development. It enables custom indicators, alerts, and automated trading systems. The scripting language is integrated directly with TradingView charts.
The basic structure consists of:
- Version declaration: Specifies the Pine Script version.
- Indicator or strategy definition: Defines the script type.
- Logic implementation: Calculates values based on market data.
- Plotting functions: Visualizes data on the chart.
Comments
Comments help improve code readability and maintainability. Pine Script supports:
- Single-line comments: UsingÂ
//
- Multi-line comments: UsingÂ
/* ... */
Single line comment:
// Single-line comment for brief explanations plot(close, title="Price") // Display closing price
Multi-line comments:/* Multi-line comments for complex logic or detailed algorithm explanations Use sparingly to maintain code readability */
Pine Script Syntax
Pine Script follows a simple yet powerful syntax. Some key elements include:
- Variables: Define constants or store computed values.
- Functions: Perform calculations and return values.
- Conditional Statements: Control logic flow.
- Built-in Functions: Predefined functions for data processing.
Variables
// Case-sensitive language
myVar = close > open // Boolean variable
// Explicit type declaration
float priceDelta = high - low
// Function definition
calculateRSI(int length) =>
ta.rsi(close, length)
// Conditional execution
if (high > high[1])
label.new(bar_index, high, "New High")
Shape Plots
Pine Script provides functions to plot shapes on the chart, such as arrows, circles, or crosses. These shapes help highlight specific conditions.
// Detect bullish crossover
bullishCross = ta.crossover(ta.ema(close, 14), ta.ema(close, 28))
plotshape(series=bullishCross,
title="Buy Signal",
location=location.belowbar,
color=color.green,
style=shape.triangleup,
size=size.small,
text="BUY",
textcolor=color.white)
Example Script
//@version=5
indicator("My Strategy", overlay=true)
// Input parameters
length = input.int(14, "MA Length")
src = input(close, "Source")
// Calculation
ma = ta.sma(src, length)
// Visual output
plot(ma, color=color.blue, linewidth=2)
// Strategy logic
if ta.crossover(close, ma)
strategy.entry("Buy", strategy.long)
if ta.crossunder(close, ma)
strategy.close("Buy")
Disclaimer
This content is for informational and educational purposes only and should not be considered financial or investment advice. Trading stocks, cryptocurrencies, or any financial instruments involves risk, and past performance does not guarantee future results. Always conduct your own research and consult with a licensed financial advisor before making any trading or investment decisions. The author and publisher are not responsible for any financial losses incurred by the use of this information.