Jay Rocco is the Founder and Editor of FullStack Alpha. He has tested 200+ AI stock tools since 2022 and run 15+ AI trading platforms on live accounts with his own money. He reviews the software. He does not tell you what stocks to buy.
This pine script tutorial gets you from a blank TradingView editor to a working moving-average indicator in five lines of Pine Script v6, then adds a crossover marker and an alert you can switch on. Every code block below compiled without errors on TradingView’s Pine compiler in October 2026. You need a browser and a free TradingView account, not a computer science degree. Your first goal is a calculation you understand, not another mysterious green arrow.
Key takeaways
Pine turns trading rules into visible calculations on a price display. Start with an average, inspect its output, and add detail only after the basic behavior makes sense.
- Pine v6 is the target syntax for every example in this pine script tutorial; v5 code such as
sma()without theta.prefix fails to compile. - Five lines build the first indicator:
//@version=6,indicator(),input.int(),ta.sma()andplot(). - A 20-bar simple moving average moves by (new close minus dropped close) divided by 20 on each bar, which you can check by hand.
alertcondition()works in indicators only, andbarstate.isconfirmedstops a signal from firing before the bar closes.- The User Manual explains behavior that a compiler cannot judge, so keep it open while you work.
What is Pine Script, and what will this pine script tutorial build?

Pine is TradingView’s chart-focused programming language for custom indicators and strategies. This beginner lesson builds a moving average: a rolling average of closing prices displayed over price action, meaning the market’s actual price movement. The official first-steps primer recommends working with existing tools before reading and writing your own.
An indicator displays calculations. It doesn’t establish that a trade has favorable risk-reward, meaning potential gain relative to potential loss. If you want the wider picture of what bots can and cannot do with these signals, start at AI Stock Trading Bots.
Primer: top reasons to learn Pine
Save precious time: replace repeated visual checks with a defined calculation.
Be more efficient: expose settings instead of editing the same expression repeatedly.
Improve your edge: make an assumption testable. An average can describe direction; it cannot prove that the next move will continue.
Understanding scripts: language fundamentals and concepts
Pine scripts contain a declaration and instructions. Variables name values; functions perform jobs. The script structure documentation explains how these pieces fit together.
Because Pine runs within the platform, beginners avoid installing packages or arranging a separate price feed. The trade-off is less freedom than a general-purpose programming environment.
How do you write your first indicator step by step?

Open the Pine Editor from a desktop chart, create a blank indicator, replace the template, and select Add to chart. Keep the example small enough that you can explain every line before changing it.
Pine Editor: first script and code example
Start this pine script tutorial with the Pine code below. The sample length is an editable teaching choice, not a recommended trading setting.
//@version=6
indicator("Alpha average", overlay=true)
length = input.int(20, "Length", minval=1)
average = ta.sma(close, length)
plot(average, "Average", color=#1F5E43, linewidth=2)
The version annotation selects v6. The declaration names the tool; overlay=true places it over price rather than in a separate pane. The reference manual documents these parameters.
Save the script under a recognizable name. Open its settings, change the length, and check whether the average becomes smoother as the window grows. If nothing appears, check the Editor message area before adding more instructions.
Variables, Type, and functions: understanding each line
length = ... defines a variable containing the selected window. average holds a series, meaning values that develop across successive candles. close supplies closing-price data.
These building blocks are used throughout beginner examples:
| Building block | What it does | Example | Common mistake |
|---|---|---|---|
indicator() | Declares the tool | overlay=true | Expecting simulated orders |
plot() | Displays values | plot(average) | Putting it inside a local conditional |
ta.sma() | Calculates an average | ta.sma(close, length) | Using an invalid length |
input.int() | Adds integer settings | minval=1 | Allowing unusable values |
alertcondition() | Exposes an alert condition | ta.crossover(fast, slow) | Assuming an alert is already running |
Check the math by hand: a worked moving-average example
Never trust a line you cannot reproduce with a calculator. A 20-bar simple moving average is the sum of the last 20 closes divided by 20.
Say the last 20 closes add up to $4,000. The average is $4,000 / 20 = $200.00. On the next bar, the oldest close of $195 drops out and a new close of $205 comes in. The new sum is $4,000 − $195 + $205 = $4,010, so the average is $200.50.
The shortcut: the average moves by (new close − dropped close) / 20 = ($205 − $195) / 20 = $0.50. Hover the line in TradingView’s Data Window on two consecutive bars and confirm the same step. If your number and the chart disagree, you are reading a different source price or a different length.
Execution model, series, and the Pine runtime environment
Pine processes historical candles sequentially. On an open candle, an indicator can recalculate as updates arrive, so unfinished results can change. The official manual explains this execution model.
A series is like a running notebook: each completed bar contributes another entry. History references retrieve prior entries. The Pine runtime handles the repeated execution, so beginners usually need built-in functions rather than explicit loops. This is the section of any pine script tutorial that beginners skip, and it explains most of the surprises later.
How do you add a crossover signal and an alert in this pine script tutorial?
Once the single average makes sense, add a second one and mark the crossings. This is step two of the pine script tutorial, and it compiled cleanly in Pine v6.
//@version=6
indicator("Alpha crossover", overlay=true)
fastLength = input.int(10, "Fast length", minval=1)
slowLength = input.int(30, "Slow length", minval=2)
fast = ta.sma(close, fastLength)
slow = ta.sma(close, slowLength)
crossUp = ta.crossover(fast, slow) and barstate.isconfirmed
crossDown = ta.crossunder(fast, slow) and barstate.isconfirmed
plot(fast, "Fast", color=#5FA777)
plot(slow, "Slow", color=#1F5E43, linewidth=2)
plotshape(crossUp, "Cross up", shape.triangleup, location.belowbar, color=#1F5E43)
plotshape(crossDown, "Cross down", shape.triangledown, location.abovebar, color=#A63D40)
alertcondition(crossUp, "Fast crossed above slow", "Fast SMA crossed above slow SMA on {{ticker}}")
What the new lines do:
ta.crossover(fast, slow)is true on the bar where the fast average moves from below to above the slow one.ta.crossunderis the mirror image.and barstate.isconfirmedwaits for the bar to close. Per the bar states docs, it is always true on historical bars and becomes true on a realtime bar’s closing update, so your live markers match your history.plotshape()draws a triangle instead of a line, so the signal is easy to audit by eye.alertcondition()registers an alert you then create yourself from the chart’s Create Alert dialog. TradingView’s alerts page says it works in indicators only; the neweralert()function works in both indicators and strategies and allows dynamic messages.
Decision rule: keep barstate.isconfirmed on any signal you will act on. Drop it only for a visual you watch intrabar and never automate.
Who should learn Pine: day traders, swing traders, scalpers, or long-term investors?
Pine fits day traders and swing traders who want repeatable visual checks. A long-term position investor can also track trend conditions, while a scalper must account for changing prices, alert delays, and fills that may differ from a displayed marker.
For a swing trader, a clean setup might combine an average with support and resistance, meaning areas where price previously found buyers or sellers. For a day trader, session VWAP can provide context. Neither replaces position sizing or a stop loss.
Sourced facts for beginners
Three structural components: a version annotation, declaration, and body organize a typical Pine program. Structure
12, 26, and 9: the official MACD exercise uses these lengths to explain exponential averages and a signal calculation. First steps
2 Boolean states in v6: Boolean values are true or false; Boolean
nais no longer supported. Migration documentation
These are documented mechanics, not win-rate statistics.
How much does Pine cost, and how long does learning take?
You can begin writing with a free account, although platform allowances and some market feeds depend on your plan. Check the platform overview and free chart comparison before paying for extras.
A simple average is a reasonable evening project, not a fixed learning deadline. Independent debugging takes practice. Keep your first learning milestone concrete: explain the calculation without reading someone else’s comments.
Top 5 Pine features beginners use first
The most useful early features reduce typing and make results easier to inspect. These capabilities appear throughout the official introduction and reference material.
- Adjustable inputs: change a window without rewriting the calculation.
- Technical-analysis functions: calculate averages and momentum using built-ins.
- Plots: turn calculated values into visible output.
- Alert conditions: expose rules for separately configured notifications.
- Readable source: inspect open-source scripts before trusting their behavior.
For notification selection beyond this lesson, read the stock alert apps comparison.
How does Pine compare to other programming tools?
Choose Pine for chart-native calculations with minimal setup. Choose Python for research involving external datasets, custom analytics, or portfolio-level work; that flexibility brings more installation and data-management work.
Conversion from other platforms and alternatives
ThinkScript suits thinkorswim users. EasyLanguage suits TradeStation workflows. NinjaScript suits NinjaTrader users comfortable with C#. Python suits broader programming and research.
Conversion means translating behavior, not replacing a few names. Session definitions, historical inputs, and order assumptions can differ.
Built-in studies are the simplest alternative when your desired calculation already exists. For a different charting workflow, compare TrendSpider versus TradingView. If you want to test a rule without writing any code at all, our list of no-code backtesting websites covers the options.
”study” versus “strategy”: can Pine create automated bots?
Older scripts may declare study(); modern examples declare indicator(). A strategy declaration supports simulated orders, but a simulation does not automatically send trades to a broker. When your indicator is ready to become a backtest, our Pine Script strategy guide shows the conversion line by line.
Alerts can connect to outside automation, which adds separate failure points. Keep this lesson visual, and read what to know before automating trades before connecting real funds. Our breakdown of TradingView automated trading covers the bridges that carry an alert to a broker.
Drawbacks: Pine has platform resource limits and restricted access to outside services. It also cannot make a historical result account for every live trading condition.
What are the most common Pine beginner errors?
The common failures are mismatched syntax, invalid inputs, and confusing unfinished values with confirmed results. A script that compiles can still describe the wrong rule. Expect to hit at least one of these while working through this pine script tutorial.
Two compile errors every beginner hits
We ran both of these broken snippets through TradingView’s compiler so you know what the failure looks like.
Error 1: old v5-era names. Writing average = sma(close, 20) under //@version=6 fails with a “Could not find” error pointing at sma. The fix is the namespaced built-in: ta.sma(close, 20).
Error 2: numbers used as conditions. Writing color c = volume ? color.green : color.red fails with a “Cannot call … An argument of … type was used but a … is expected” error, because v6 no longer turns an int or float into a bool for you. The fix is an explicit comparison: volume > 0 ? color.green : color.red. The v6 migration guide lists this change first among the ones that affect v5 scripts.
Troubleshooting Pine code: debug and test
Read the first editor error before fixing later messages. Check spelling, brackets, indentation, and whether a function belongs to the selected version.
When the code compiles but the numbers look wrong, print them. Functions in the log.* namespace, such as log.info(), write messages to the Pine Logs pane, per the debugging docs. One log line per bar showing close, fast and slow will find most logic bugs faster than staring at the chart.
Compare your average with the platform’s built-in average using matching settings. Then inspect another symbol and interval. If values disagree, check the source price and session before blaming the platform.
For MACD, compare all outputs: the MACD curve, signal curve, and histogram. The official next-steps material points readers toward deeper documentation.
Watch live behavior too. A crossing may appear during a bar and disappear before the close. Confirmation reduces this particular risk, but does not fix every repainting problem. TradingView’s repainting page notes that even MACD and RSI fluctuate on an unconfirmed realtime bar until it closes.
Release notes: what changed between v4, v5, and v6?
The v4-to-v5 transition introduced namespace changes such as sma() becoming ta.sma(), and study() becoming indicator(). In v6, numbers no longer implicitly become Boolean conditions; write an explicit comparison instead.
The v6 migration notes also cover removal of transp, lazy evaluation of and and or conditions, and dynamic request.*() calls. Check release notes before combining examples from different generations.
Respect copyright notices and TradingView, Inc. licensing terms rather than treating all public material as reusable source.
Where do you go from here with a Pine mastery course?
Continue with the official MACD exercise after you understand the average. A useful course should teach you to read unfamiliar calculations, diagnose errors, and describe limitations, rather than memorize a profitable-looking screenshot.
What is this course, and what comes next?
This pine script tutorial is an introductory lesson, not a paid Pine Script Mastery Course or a claim of certification. For further study, follow the official learning sequence .
If you search for a pine script tutorial PDF, W3Schools lesson, or YouTube walkthrough, inspect its opening version annotation. A saved PDF can age; a confident presenter can still teach old syntax.
Community searches on Stack Overflow, Telegram, or Reddit may surface useful troubleshooting, but verify answers against the manual. There is no need to add unfamiliar calculations just because a stranger posted impressive results.
A one-week plan after this pine script tutorial
- Day 1: build the five-line average and check two bars by hand.
- Day 2: add the crossover script and confirm the markers only print on closed bars.
- Days 3 to 4: add
log.info()lines and compare your values with the built-in SMA. - Days 5 to 7: convert it to a strategy and read the trade list for look-ahead bias before you read the profit number.
Our Take
Your next step is to paste the first example into the editor and explain every calculation before adding alerts. Keep the original saved so you can reverse a bad edit. A good pine script tutorial should leave you able to read code, not just copy it.
Paper trade it first. Getting stopped out is expensive enough without discovering that your rule meant something different from what you intended. Our paper trading app comparison shows which simulators fill honestly. For the next learning stage, read how to backtest without fooling yourself.
Related: if thinkorswim is your charting home instead of TradingView, start with our thinkorswim review on AI Stock Picker App.
References
This article uses documentation-based desk research and compiler checks of the code shown, not claimed trading performance. The linked manuals are living documents; no publication years have been invented.
- Release Notes
- First Steps
- To Pine Version 6
- Pine Script Docs
- Script Structure
- Welcome
- tradingview
- Next Steps
- Bar States
- Alerts
- Debugging
- Repainting
Looking for more tools beyond this lesson? Compare categories and prices in the FullStack Alpha directory before adding another subscription.
Affiliate disclosure: FullStack Alpha may earn a commission from qualifying purchases through affiliate links.
By Jay Rocco, Founder and Editor, FullStack Alpha.
Stay alpha.
Frequently Asked Questions
Is pine Script easy to learn?
Pine is approachable for simple averages and visual rules because the platform supplies market information and the display. The harder part is understanding changing values and historical assumptions. Begin with a short example, edit a setting, and explain the change. The official [primer ](https://www.tradingview.com/pine-script-docs/primer/first-steps/) follows that practical sequence.
What coding language does Pine Script use?
Pine is its own programming language, created for the platform’s indicators and strategies. It is not Python or JavaScript, even though some expressions may look familiar. Follow its own syntax and execution rules. The [reference manual ](https://www.tradingview.com/pine-script-reference/v6/) is the right place to verify parameters and return types.
Can ChatGPT write a pine Script?
ChatGPT can draft source and explain compiler messages, but its output can contain invented functions, outdated syntax, or faulty logic. Ask for a small v6 example with stated assumptions. Compile it, compare outputs with known calculations, and check unfamiliar calls against the [official reference ](https://www.tradingview.com/pine-script-reference/v6/) before relying on it.
What is the difference between pine Script and Python?
Pine is built for calculations inside a charting platform. Python is a general-purpose option used for tasks such as external research, file handling, and machine learning. Pine reduces setup for visual studies; Python offers wider control with more responsibility for inputs and infrastructure. The [Pine introduction ](https://www.tradingview.com/pine-script-docs/welcome/) explains its intended scope.
Can I publish my indicator and make money?
Publishing scripts and earning money are separate questions. Publication can share your work, while paid access introduces vendor rules, moderation, support, and licensing duties. Keep early experiments private until their behavior is clear. Review the publishing information linked through the [manual ](https://tradingview.com/pine-script-docs/) before offering access or making performance claims.
How should I test before trading?
Compare calculations with a known equivalent, inspect closed candles, and observe changing live values without placing orders. Record mismatches instead of adjusting settings until the picture looks attractive. If you later build strategies, include trading costs and realistic fill assumptions. The [manual ](https://tradingview.com/pine-script-docs/) explains the platform mechanics behind those checks.
Jay Rocco is the Founder and Editor of FullStack Alpha. He has tested 200+ AI stock tools since 2022 and run 15+ AI trading platforms on live accounts with his own money. He reviews the software. He does not tell you what stocks to buy.