
Writing scripts on TradingView is a game-changer for traders and analysts. With its PineScript language, you can create custom indicators, strategies, and even automated trading systems.
TradingView offers a vast library of scripts, but creating your own can be a powerful way to express your trading ideas and visualize complex market data. PineScript is a powerful language that's relatively easy to learn.
To get started, you'll need to understand the basics of PineScript syntax and data structures, including arrays, variables, and functions. This will allow you to create custom indicators and strategies that can be used in your TradingView charts.
TradingView's PineScript editor is a great tool for writing and testing scripts, with features like syntax highlighting, auto-completion, and a built-in debugger.
Broaden your view: Adding Volume on Tradingview Chart in Pinescript
Script Basics
In Trading View, you need to follow a specific format when writing a script. This format is similar to writing an English essay, where you need to adhere to certain rules to convey your message clearly.
First, you need to set variables, such as input(9), to define parameters for your script.
When calculating processes, you need to use the "ta." prefix before built-in functions, like ta.rsi(close, rsi_Length), to specify the data source and calculation length.
Newbie Learning MACD Trading

In Trading View, you need to set up variables for each indicator parameter, like MACD's parameters are 12, 26, and 9, so you can change them later if needed.
You can calculate a 10-day average line using volume by writing ta.sma(volume, 10), and even calculate a 10-day RSI average value by writing ta.sma(rsi value, 10).
The original creator of the MACD strategy calculated MACD by subtracting the slow EMA from the fast EMA, which is ta.ema(close, fastLength) - ta.ema(close, slowLength).
The aMACD is calculated by taking the EMA of the MACD with a length of MACDLength, which is ta.ema(MACD, MACDLength).
In Trading View, you can write "升穿" or "跌穿" using ta.crossover() and ta.crossunder(), where the first value crosses over or under the second value.
You need to have strategy.entry() in your Trading View script to tell Trading View when to enter a trade.
The strategy.entry() function has three parts: the name of the entry, whether it's a long or short entry, and a comment.
In Trading View, you can plot a line on the chart by using the plot() function, which requires the value to plot, the title, color, line width, and line style.
You can use the // symbol to add comments to your script, which won't affect the strategy.
For another approach, see: Chatgpt Trading Strategy Tradingview
Indicators and Strategies
Indicators and Strategies are the building blocks of TradingView scripts. An indicator script is declared with the `indicator` function, which requires a `title` parameter, and optional parameters such as `overlay` to specify whether the indicator should be displayed on the chart or in a separate window.
Indicators are reusable code blocks that can be applied to charts to analyze and visualize data. They can be used to identify trends, patterns, and other market phenomena. For example, the `ta.stoch` function can be used to calculate the stochastic oscillator, a popular indicator used to gauge market momentum.
A strategy script, on the other hand, is declared with the `strategy` function, which also requires a `title` parameter. Strategies are used to automate trading decisions based on specific conditions and rules. They can be used to enter and exit trades, manage risk, and optimize performance.
Here's a summary of the key differences between indicators and strategies:
In Pine Script, indicators and strategies are written using a unique syntax and set of functions. For example, the `indicator` function requires a `title` parameter, while the `strategy` function also requires a `title` parameter, but can also include optional parameters such as `overlay`. By understanding the differences between indicators and strategies, you can create more effective and efficient TradingView scripts that meet your trading needs.
Conditions

When creating conditions in TradingView scripts, you have multiple options to choose from. The first option is to use the switch statement, which is ideal for conditions with multiple criteria.
The switch statement allows you to define multiple conditions and assign a result to a variable. For example, you can use it to determine the RSI status, as shown in the example: when RSI > 80, the variable rsi_status will be set to "Very Overbought".
You can also use the switch statement to determine the alert condition, such as creating a multiple criteria alert, which can be triggered by multiple conditions.
In TradingView scripts, you can also use the if-else statement to create conditions. However, if you have a large number of conditions, the switch statement is more concise and easier to read.
Here is a summary of the conditions you can use in TradingView scripts:
The switch statement is also useful when you need to frequently modify or add new conditions to your script. This is because the switch statement allows you to easily add or remove conditions without affecting the rest of the script.
Expand your knowledge: Add Volume on Tradingview
Built-in Functions and Variables

In tradingview scripts, you'll often use built-in functions and variables to create and manage your trading strategies. One of the most important functions is strategy.entry, which is used to establish a new position in the market.
To use strategy.entry, you'll need to specify the order ID, direction (either long or short), and quantity. You can also set a limit price and stop price to control your risk. For example, when the short-term moving average (short_ma) crosses above the long-term moving average (long_ma), you can use strategy.entry to buy the asset.
Here's a quick reference guide to the main built-in functions and variables:
These functions and variables are the building blocks of your tradingview scripts, and mastering them will help you create effective and efficient trading strategies.
Property
In Pine Script, you need to declare the property of your script to tell TradingView what the purpose of your code is. This is crucial because without it, the Pine Editor will throw an error and won't be able to execute your code.

You have two main options: declaring your script as a "指標 Indicator" or a "策略 Strategy". If you declare it as a "指標 Indicator", it means your code is used to calculate and display technical indicators on the chart, but it doesn't involve any trading decisions.
If you declare it as a "策略 Strategy", it means your code includes the conditions for buying and selling, as well as the position size, and it can also be used for backtesting.
Here are the key differences between the two:
內建函數
==============================
In Pine Editor, you can use built-in functions to create and manage your trading strategies. One of the most important functions is `strategy.entry`, which is used to establish a new position in the market.
`strategy.entry` is used to create a new position, and it has several parameters that you can customize. For example, you can specify the order ID, direction (long or short), quantity, limit price, stop price, and comment.
Related reading: Tradingview Create Strategy

Here are the key parameters of `strategy.entry`:
- `id`: the order ID, which is used to identify the trade
- `direction`: the direction of the trade, either `strategy.long` for long or `strategy.short` for short
- `qty`: the quantity of the trade
- `limit`: the limit price, which is the price at which the trade will be executed
- `stop`: the stop price, which is the price at which the trade will be closed
- `comment`: a comment to describe the trade
For example, you can use `strategy.entry` to create a new long position with an order ID of "Long Entry" and a quantity of 1:
```pine
strategy.entry("Long Entry", strategy.long, 1)
```
Another important function is `strategy.order`, which is used to modify an existing position. `strategy.order` has similar parameters to `strategy.entry`, but it also allows you to specify the direction of the trade based on the current position.
Here are the key parameters of `strategy.order`:
- `id`: the order ID, which is used to identify the trade
- `direction`: the direction of the trade, either `strategy.long` for long or `strategy.short` for short
- `qty`: the quantity of the trade
- `limit`: the limit price, which is the price at which the trade will be executed
- `stop`: the stop price, which is the price at which the trade will be closed
- `comment`: a comment to describe the trade
For example, you can use `strategy.order` to modify an existing long position with an order ID of "Long Order" and a quantity of 1:
For your interest: Tradingview Long Position Tool

```pine
strategy.order("Long Order", strategy.long, 1)
```
In addition to `strategy.entry` and `strategy.order`, there are two other important functions: `strategy.exit` and `strategy.close`. `strategy.exit` is used to close a position based on a specific condition, while `strategy.close` is used to close a position completely.
Here are the key parameters of `strategy.exit`:
- `id`: the order ID, which is used to identify the trade
- `from_entry`: the entry ID, which is used to identify the trade to be closed
- `qty`: the quantity of the trade to be closed
- `limit`: the limit price, which is the price at which the trade will be executed
- `stop`: the stop price, which is the price at which the trade will be closed
- `trail_points`: the number of points to trail the stop price
- `trail_offset`: the offset of the trail price
For example, you can use `strategy.exit` to close a long position with an order ID of "Long Entry" and a quantity of 1:
```pine
strategy.exit("Long Entry", from_entry = "Long Entry", qty = 1)
You might enjoy: How to Test Your Strategy on Tradingview

```
`strategy.close` is used to close a position completely, and it has only one parameter: `id`, which is the order ID of the trade to be closed.
For example, you can use `strategy.close` to close a long position with an order ID of "Long Entry":
```pine
strategy.close("Long Entry")
```
In summary, `strategy.entry` is used to create a new position, `strategy.order` is used to modify an existing position, `strategy.exit` is used to close a position based on a specific condition, and `strategy.close` is used to close a position completely.
A unique perspective: Order Book Tradingview
Technical Analysis
Technical analysis is a crucial aspect of trading, and TradingView provides a range of tools and scripts to help you analyze markets. With TradingView, you can create custom indicators and strategies using Pine Script, a powerful programming language.
To start, you'll want to familiarize yourself with some of the most common technical indicators, such as Moving Averages (MA) and Relative Strength Index (RSI). These indicators can be used to identify trends, predict price movements, and make informed trading decisions. You can also create your own custom indicators using Pine Script, such as the Bollinger Bands, which are calculated as 20-day moving averages plus or minus two standard deviations.

Here are some common types of Moving Averages you can use in TradingView:
- SMA (Simple Moving Average)
- EMA (Exponential Moving Average)
- WMA (Weighted Moving Average)
- HMA (Hull Moving Average)
You can also use other types of averages, such as RMA (Relative Moving Average) and ALMA (Arnaud Legoux Moving Average), to create more complex trading strategies.
K棒時間
K棒時間 is a crucial concept in Technical Analysis. It refers to the time of day when the market is most volatile, with the highest trading volume and most significant price movements.
During this period, the K棒時間 is typically between 10:30 and 11:30 in the morning, and 14:30 and 15:30 in the afternoon. This is when the market is most active, with many traders and investors making their moves.
The K棒時間 is characterized by a high level of trading volume, with an average daily trading volume of 100 million shares. This is significantly higher than the average daily trading volume of 50 million shares during other times of the day.
As a result, the K棒時間 is a great time to trade if you're looking to make a quick profit.
Take a look at this: Anchored Volume Profile Tradingview
Technical Analysis

Technical analysis is a crucial aspect of trading, and it's essential to understand the various types of moving averages. Moving averages are a type of technical indicator that helps smooth out price fluctuations and identify trends.
A simple average, also known as a Simple Moving Average (SMA), is a basic type of moving average that calculates the average price of a security over a specific period. For example, a 20-day SMA would calculate the average price of a security over the past 20 days.
Exponential Moving Averages (EMAs) are another type of moving average that gives more weight to recent prices. This makes EMAs more responsive to price changes than SMAs. For instance, the article mentions that the EMA formula is used in the ZerolagMACDLine calculation.
Weighted Moving Averages (WMAs) are similar to EMAs but use a different weighting scheme. Hull Moving Averages (HMAs) are a type of WMA that uses a specific weighting scheme to calculate the average price.

Here are some common types of moving averages:
Understanding these types of moving averages is essential for technical analysis, and it can help you make informed trading decisions. By using these indicators, you can identify trends and make predictions about future price movements.
Drawing/Marking Functions
In TradingView scripts, drawing and marking functions are essential for visualizing important information on the chart. The `plot` function is used to draw data lines, and it can be customized with various parameters such as title, color, linewidth, style, trackprice, histbase, and offset.
To use the `plot` function, you need to specify the series (the data to be plotted) and can optionally specify other parameters. For example, you can set the title of the plot, specify the color of the line, and adjust the linewidth.
Here are some examples of using the `plot` function:
* To plot a simple moving average (SMA) line, you can use the following code:

+ `ta.sma` to get the 5-day SMA value
+ `plot` function to plot the SMA line, with the title "SMA" and orange color
* To plot the closing price, you can use the following code:
+ `plot` function to plot the closing price line, with the title "Close Price" and blue color, and displaying the current closing price on the right price axis
The `label.new` function is used to add labels to the chart, which can help visualize important information. You can specify the x and y coordinates of the label, as well as the text to be displayed.
Here are some examples of using the `label.new` function:
* To label a point when RSI > 70, you can use the following code:
+ `ta.rsi` to get the 14-day RSI value
+ `label.new` function to add a label to the chart, with the text "Overbought" and red background color
* To label the golden cross and death cross, you can use the following code:
For your interest: Tradingview Chart Analysis

+ `ta.sma` to get the 10-day and 30-day moving averages
+ `label.new` function to add labels to the chart, with the text "Golden Cross" and "Death Cross" and green and red background colors respectively
In addition to these functions, you can also use trend lines to visualize the chart. You can create a trend line, remove it, set the line color, and adjust the line size and style.
A unique perspective: Tradingview Chart Layout Ideas
Functions and Operators
In TradingView scripts, you can use various functions to create interactive charts and indicators. The `plot` function is used to draw lines and curves on the chart, while the `label.new` function is used to add labels and annotations.
You can use the `plot` function to draw various types of lines and curves, including simple moving averages, close price lines, and MACD histograms. For example, you can use `plot` to draw a 5-day simple moving average, or to draw a close price line with a blue color.
A different take: Thinkorswim Moving Average Crossover Script

The `label.new` function can be used to add labels and annotations to specific points on the chart. You can use it to add labels to specific bars, or to add annotations to specific price levels. For example, you can use `label.new` to add a label to a bar when the RSI is above 70, or to add a label to a bar when there is a golden cross.
Here are some common parameters used in `plot` and `label.new` functions:
Functions
Functions are the building blocks of any programming language, and Pine is no exception. The `plot` function is used to create data lines on a chart, allowing you to draw attention to specific data points or trends.
The `plot` function requires a `series` parameter, which is the data to be plotted. Other parameters, such as `title`, `color`, and `linewidth`, are optional and can be left out if you want to use the default values.

Here are some key parameters for the `plot` function:
- `series`: The data to be plotted.
- `title`: The title of the plot.
- `color`: The color of the line.
- `linewidth`: The thickness of the line.
- `style`: The style of the plot, such as a histogram.
- `trackprice`: Whether to display the current price on the price axis.
- `histbase`: The base value for a histogram plot.
- `offset`: The number of bars to offset the plot.
For example, you can use the `plot` function to create a simple moving average (SMA) line by using the `ta.sma` function to get the 5-day SMA value and then plotting it with the `plot` function.
Here are some examples of using the `plot` function:
- Plotting a simple moving average (SMA) line.
- Plotting the closing price with the current price displayed on the right side of the chart.
- Plotting a MACD histogram.
The `label.new` function is used to add labels to a chart, which can help to visualize important information and identify key points. The `label.new` function requires an `x` and `y` parameter, which specify the position of the label.

Here are some key parameters for the `label.new` function:
- `x`: The horizontal position of the label, typically using the `bar_index` variable.
- `y`: The vertical position of the label, typically using a price value such as `high`, `low`, or `close`.
- `text`: The text to be displayed on the label.
- `color`: The color of the label background, border, and arrow.
- `style`: The style of the label, such as a downward-pointing arrow.
- `textcolor`: The color of the label text.
- `size`: The size of the label.
For example, you can use the `label.new` function to add a label to a chart when the RSI is greater than 70, displaying the text "Overbought".
Here are some examples of using the `label.new` function:
- Adding a label to a chart when the RSI is greater than 70.
- Adding labels to a chart for golden and death crosses.
- Adding labels to a chart for buy and sell signals.
迴圈執行模型範例
Pine Script's unique execution model is based on a loop that runs through each historical data point on the TradingView chart, one by one.
The script runs in accordance with the time unit set on the chart, whether it's seconds, minutes, hours, days, months, or years. This means you don't need to write a loop to fetch each historical data point.
For example, if you want to use the closing price of a stock, you can simply write "close" in your script and Pine Script will automatically run a loop to fetch the closing price for each day within the chart's range.
The script runs until it has processed the last data point, making it a convenient and efficient way to work with historical data.
Recommended read: How to Write Script in Tradingview
Trade and Market

In the world of TradingView, scripts play a crucial role in automating tasks and enhancing the trading experience. TradingView scripts can be used to create custom indicators, alerts, and even automate trading strategies.
One of the key benefits of using TradingView scripts is that they can be easily shared and downloaded by other users, allowing for a community-driven approach to trading. This has led to the creation of a vast library of scripts that can be used for a variety of purposes.
TradingView scripts can be written in a variety of programming languages, including PineScript, which is the native language of TradingView. PineScript is a powerful and flexible language that allows users to create complex trading strategies and indicators.
Suggestion: Pinescript Tradingview
Trade
When trading, it's essential to understand the different types of trades you can make. A Daytrade strategy is one where you only trade once a day, which can help reduce trading costs and emotional stress.

A simple way to implement this in Pine Script is to use a variable to track whether you've already traded that day. For example, you can use a variable called "traded" and set it to false at the beginning of each day. Then, when you enter a trade, you set "traded" to true. This way, you won't enter another trade until the next day.
Here's an example of how this can be implemented in Pine Script:
```python
strategy("用zero lag MACD每日只交易一次例子", margin_long=100, margin_short=100, initial_capital =1000,default_qty_type = strategy.percent_of_equity,default_qty_value = 100)
if buyCond and not traded and noposition
```
This code checks if the buy condition is met, if the "traded" variable is false, and if there are no open positions. If all these conditions are met, it enters a trade.
To make this strategy even more effective, you can also use other indicators, such as the MACD (Moving Average Convergence Divergence) indicator. This can help you identify trends and make more informed trading decisions.
Here are some key things to keep in mind when implementing a Daytrade strategy:
- Use a variable to track whether you've already traded that day
- Set the variable to false at the beginning of each day
- Enter a trade only when the buy condition is met and the variable is false
- Use other indicators, such as the MACD, to help you make more informed trading decisions
By following these steps, you can create a Daytrade strategy that helps you reduce trading costs and emotional stress while making more informed trading decisions.
Write Methods for Managing Investor Positions

Writing methods for managing investor positions is a crucial aspect of trading. The article highlights a few key strategies used by the Turtles, a group of traders trained by Richard Dennis.
One of the most famous trading methods is the "breakout" strategy, where traders buy into a stock when it breaks above a certain level and hold onto it until it falls below a certain level. This strategy is often used in combination with a "no-stop-loss" rule, where traders don't set a stop-loss order to limit their losses.
However, the Turtles also modified this strategy to include position sizing, where they adjusted their position size based on market volatility. They used a formula to calculate the optimal position size, which took into account the stock's price volatility and the trader's risk tolerance.
The formula used by the Turtles is: annvol = 100*math.sqrt(365)*stdev/close, which converts the stock's price volatility into an annualized volatility. They then used this value to calculate the optimal position size, which is a percentage of the trader's initial capital.
Curious to learn more? Check out: How to Set Trailing Stop Loss in Tradingview

The article also mentions that the Turtles used a " Renko chart" strategy, which involves creating a chart with bricks that represent a certain amount of price movement. The bricks are colored based on whether the price is rising or falling, and traders use this chart to identify trends and make trading decisions.
To create a Renko chart, traders can use a formula to calculate the Renko value, which represents the number of bricks that have been formed. The formula is: renkoValue=ticker.renko(syminfo.tickerid,'ATR',renkoLength), where 'ATR' is the average true range and 'renkoLength' is the number of bricks that make up the chart.
By using these strategies, traders can manage their positions more effectively and reduce their risk exposure.
Related reading: Express Scripts Prior Authorization Fax Number
Alerts and Labels
Alerts are a crucial part of TradingView scripts, allowing you to set conditions that trigger notifications when certain events occur.
You can create and configure alerts in multiple ways, including setting multiple criteria alerts, turning alerts in strategy, and receiving alerts from other indicators.

To customize your alerts, you can also use condition with standard placeholders, plot placeholders, and plot in alert condition, which enables you to add more context to your notifications.
Here are some examples of alert types:
Labels are another important feature in TradingView scripts, allowing you to add text and other visual elements to your charts.
You can move label functions, update time and price coordinates, and modify time coordinate styles to customize your labels.
Alert Conditions
Alert conditions are a crucial part of creating effective alerts and labels. You can create and configure alerts to suit your needs.
There are multiple ways to program alerts, including using multiple criteria. This allows you to set up complex alert systems that take into account various factors. For example, you can set up alerts that trigger when a certain condition is met, such as a stock price reaching a certain level.
Alerts can be triggered in real-time or historically, depending on your needs. This means you can set up alerts that notify you when something happens in real-time, or when it happens in the past.
Suggestion: Remove Alert Tradingview

Alerts can also be triggered by other indicators, allowing you to set up complex alert systems that take into account multiple data points.
You can customize the appearance of your alerts by using colored backgrounds, bars, characters, shapes, and text. This makes it easier to visualize the data and make quick decisions.
Here are some examples of alert customization options:
- Coloured background alerts
- Coloured bar alerts
- Plotted character alerts
- Plotted shapes alerts
- Text & shapes alerts
You can also use plot alert texts, arrows, and trigger levels to further customize your alerts. Additionally, you can highlight real-time alerts for quick identification.
Labels
Labels are a crucial part of alerts and labels, and there are several ways to work with them.
You can move label functions, update time coordinates, update price coordinates, update time & price, modify time coordinate style, and set label anchoring.
There are three main categories of label functions: label location functions, label text functions, and label appearance functions.
Label location functions include getting label price, getting label time, and seeing if label uses bars or times.
You can also work with label text by setting label text, getting label text, setting text alignment, setting text colour, setting font family, and setting tooltip text.
Label appearance functions include setting label colour, setting label size, changing label style, and overviewing label styles.
Advanced Topics

In Advanced Topics, we'll dive deeper into the world of TradingView scripts.
You can use the PineScript language to create custom indicators, which can be used to analyze and visualize market data.
PineScript is a powerful language that allows you to create custom indicators and strategies, and it's free to use for TradingView users.
The PineScript editor provides a range of tools and features to help you write and test your scripts, including syntax highlighting and debugging tools.
One of the key features of PineScript is its ability to create custom indicators that can be used to analyze and visualize market data, such as moving averages and RSI.
You can also use PineScript to create strategies that can be used to generate buy and sell signals, based on specific market conditions.
The TradingView API provides a range of functions that can be used to interact with the platform, including functions for retrieving market data and executing trades.
With the TradingView API, you can create custom scripts that can be used to automate tasks, such as sending notifications or executing trades based on specific market conditions.
Additional reading: Tradingview Api Python
Error Handling

As you start writing your TradingView scripts, you may encounter various errors that can be frustrating to deal with. One of the most common issues is the "Bad session spec" error, which means you need to revisit your session specification.
To avoid this, make sure you have the correct session spec set up. I've seen this error happen when users forget to include essential parameters in their session spec.
Some errors are related to the code structure itself. For example, if you try to call an output function without using either indicator() or strategy(), you'll get an error message. This is because TradingView requires you to specify whether your code is an indicator or a strategy.
Here are some common errors you might encounter, along with some tips on how to fix them:
If you're getting errors related to the code syntax, you might see messages like "Variable already declared" or "Syntax error at input". These errors can be tricky to fix, but they usually indicate that there's a problem with the way you've structured your code.

In some cases, you might get an error message saying "Couldn't find function". This happens when TradingView can't find the function you're trying to call. Make sure you've spelled the function name correctly and that it's been properly defined.
One final error to watch out for is "Can't use strategy functions in indicator". This error occurs when you try to use a strategy function within an indicator, which isn't allowed in TradingView. If you need to use a strategy function, consider creating a separate strategy instead.
Editor and Settings
In the Editor and Settings section, you'll find the Script settings, which include essential details about your script. The script name is a required field, and you can also specify a short script name for easier identification.
You can choose between a filename and display name for your script, which is a useful feature if you have multiple scripts with the same name but different purposes.
Script settings also cover the price scale format, plotted values precision, and the precision of overlay scripts.
Version

The first step in writing a script is to declare the version of Pine Script you're using. This is crucial because Pine Script has had several updates, with the latest being version 6, and each new version brings changes and improvements.
Pine Script version 6 is the default version used by most built-in indicators and strategies on TradingView, so it's essential to declare this version at the beginning of your script. If you don't declare the version, you'll get an error message.
To declare the version, simply add a line of code that says "version = 6". This tells the Pine editor which version of Pine Script to use for the rest of the script.
Create in Editor
When creating a strategy script in the Pine Editor, you have two main options: modifying a default script or converting a indicator script. The former is a great way to get started, as you can modify a pre-existing script to suit your needs.

To modify a default script, you can choose from the built-in scripts available in TradingView. For example, you can select the "MovingAvg2Line Cross" script and modify it to suit your trading strategy.
To do this, you'll need to open the Pine Editor and locate the script you want to modify. You can do this by clicking on the "Untitled script" button and then selecting "Create new" from the dropdown menu. From there, you can search for the script you want to modify and click on it to open it in the editor.
Once you've opened the script, you can begin modifying it to suit your needs. For example, you can change the input parameters to suit your trading strategy.
Here are some key settings to keep in mind when modifying a script:
These settings can be adjusted to suit your needs, and can help you customize the script to fit your trading strategy.
Learning Essentials

To write a TradingView script, you need to understand the basic format. It's like writing an English essay, where you need to follow a specific structure to convey your message.
The first step is to set variables. For example, you can use `rsi_Length=input(9)` to set the length of the RSI indicator.
You need to calculate the process of the indicator. Some indicators, like RSI, have built-in functions, while others, like Zero Lag MACD, require you to calculate them manually.
To calculate an indicator, you need to add "ta." at the beginning, followed by the indicator name and the data source. For example, `ta.rsi(close, rsi_Length)` calculates the RSI of the close price with a length of 9.
You also need to give a name to the indicator for easier reference. For example, `rs=ta.rsi(close,rsi_Length)` assigns the calculated RSI to the variable "rs".
The next step is to define the entry and exit conditions. You can use `if` statements to define these conditions. For example, `if (ta.crossover(delta, 0))` checks if the delta crosses over 0.
To enter a trade, you can use `strategy.entry("名稱", strategy.long)` or `strategy.entry("名稱", strategy.short)`. To close a trade, you can use `strategy.close("名稱")`.
When writing a script, you need to pay attention to the syntax and formatting. Common mistakes include incorrect use of quotes, missing or extra spaces, and incorrect naming conventions.
A unique perspective: What Brokers Can I Trade through on Tradingview
Writing Scripts

Writing scripts for TradingView can be a bit overwhelming, especially when you're just starting out. But don't worry, I'm here to help break it down for you.
First, you need to understand the basic structure of a script, which includes four main parts: declaration, defining indicators, conditions, and trading. Think of it like writing a recipe - you need to declare your ingredients, define your cooking method, set the conditions for serving, and finally, execute the trade.
To write a script, you'll need to use a programming language like Pine Script. It's not as hard as it sounds, and with practice, you'll be a pro in no time. One of the most important things to remember is that a script can be broken down into smaller parts, each with its own specific function. For example, you can use the `request.security` function to retrieve data from a different timeframe or symbol.

Here's a simple example of how to use `request.security` to retrieve a 5-minute MACD signal line:
```html
signal5min=request.security(syminfo.tickerid,”5″,signalLine)
```
This line of code tells TradingView to retrieve the 5-minute MACD signal line for the current symbol. You can use this function to create complex scripts that take into account multiple timeframes and symbols.
How to Write
Writing a script is like writing a story, but instead of using words, you use a programming language. To write a script in Pine Script, you need to understand its structure, which consists of four parts: declaration, defining indicators, conditions, and trading.
The declaration part is like introducing the main character of your story. You need to declare the strategy you want to create. You can do this by using the `strategy()` function, which takes several parameters, such as the name of the strategy, the margin, and the initial capital.
To define indicators, you need to use functions like `ta.ema()` or `ta.macd()`. These functions will help you calculate the values of your indicators, such as the Exponential Moving Average (EMA) or the Moving Average Convergence Divergence (MACD). For example, you can use `ta.ema(close, 10)` to calculate the 10-day EMA.

Conditions are like the plot twists in your story. You need to define the conditions under which you want to buy or sell. You can use functions like `ta.crossover()` to check if the fast line of the MACD has crossed above the slow line. For example, you can use `ta.crossover(ZerolagMACDLine, ZerolagSignalLine)` to check if the fast line has crossed above the slow line.
Trading is like the climax of your story. You need to define the actions you want to take when the conditions are met. You can use functions like `strategy.close()` to close a position when a condition is met. For example, you can use `strategy.close("SHORT")` to close a short position.
Here's a summary of the four parts of a Pine Script:
- Declaration: `strategy()` function to declare the strategy
- Defining indicators: `ta.ema()`, `ta.macd()`, etc. to calculate indicator values
- Conditions: `ta.crossover()`, `ta.change()`, etc. to check conditions
- Trading: `strategy.close()`, `strategy.entry()`, etc. to define trading actions
By following these four parts, you can create a script that will help you make informed trading decisions.
Writing with Multiple Timeframes
Writing with Multiple Timeframes is a popular technique in Trading View, and it's actually quite easy to do. You can use the request.security function to access data from different timeframes.

To use request.security, you need to fill in three parts: the symbol, the timeframe, and the data. The symbol is the current ticker ID, which you can get by using syminfo.tickerid. The timeframe is the time interval you want to access, such as 5 minutes, 1 hour, or daily.
For example, if you want to access the MACD line from the 5-minute chart, you can use request.security(syminfo.tickerid",5",macdLine). This will give you the MACD line from the 5-minute chart.
You can also use request.security to access data from different symbols. For instance, if you want to access the data from a different stock, you need to open the chart of that stock and then use the symbol ID in the request.security function.
The request.security function is very powerful, and it's not just limited to accessing different timeframes or symbols. You can also use it to access different data, such as the highest high or the lowest low.
Many traders like to use multiple timeframes in their strategy, such as combining the 5-minute chart with the 1-minute chart. To do this, you can use the request.security function to access the data from the different timeframes.
For instance, if you want to access the highest high from the previous trading day, you can use the following code: dailyhigh=request.security(syminfo.tickerid",D",high[1]). This will give you the highest high from the previous trading day.
You might enjoy: Tradingview Symbol Search Add

You can also use the request.security function to access the MACD line from different timeframes. For example, you can use the following code to access the MACD line from the 5-minute chart and the 1-hour chart: signal5min=request.security(syminfo.tickerid",5",signalLine), macdhourly=request.security(syminfo.tickerid",60",macdLine).
Remember, the request.security function is very flexible, and you can use it to access a wide range of data. With a little practice, you can write powerful scripts that access data from multiple timeframes and symbols.
Example Strategies
In tradingview scripts, you can create and customize your own strategies using the strategy function. This function is similar to the indicator function, but with a different title that's required.
You can declare a strategy script by announcing its properties as a strategy, which then needs to use the strategy function. For example, the strategy function can be used to declare a strategy called "My Strategy" that will overlay its chart on the existing chart window.

Here are some example strategies you can use in tradingview scripts:
市場先生 總結
Market Mr. shares his experience of not having a programming background but still being able to run backtests with the help of software like TradingView.
Market Mr. has no programming background, but he was able to learn and run backtests on his own.
TradingView is a user-friendly software that allows users to run backtests without needing to write code, and it comes with many pre-built indicators and strategies to choose from.
Users can start running backtests by simply selecting a strategy and letting the software do the work.
With TradingView, users can also create their own custom strategies using the Pine Script editor, which is a great way to learn and improve their skills.
Here are some key benefits of using TradingView for backtesting:
Market Mr. encourages users to try out TradingView and start running their own backtests, even if they have no programming background.
Example Strategies

If you're looking for inspiration for your trading strategies, let's take a look at some examples that might interest you.
The ATR Channel Breakout strategy is a great way to identify potential trading opportunities. It involves using the Average True Range (ATR) indicator to determine the volatility of a stock or asset, and then looking for breakouts from the ATR channel.
The Bollinger Breakout strategy is another popular approach that uses the Bollinger Bands indicator to identify overbought or oversold conditions.
The Donchian Trend strategy is a trend-following approach that uses the highest high and lowest low of a given period to determine the direction of the trend.
The SMA Crossover strategy is a simple yet effective approach that involves using two Simple Moving Averages (SMAs) to determine the direction of the trend.
Here are some example strategies listed out for you:
- ATR Channel Breakout
- Bollinger Breakout
- Donchian Trend
- Donchian Trend Time Exit
- Dual Moving Average
- Triple Moving Average
- SMA Crossover
- SMA Weekly Crossover
- Trend With Pattern Entry
- SMA Crossover Pyramiding
- Donchian Channel Breakout
- Double Donchian Channel Breakout
- Unilateral Pairs Trading
- VIX Reversal
- Order limit
These are just a few examples of the many strategies that you can use in your trading. Remember to always backtest and refine your strategies before putting them into practice.
Featured Images: pexels.com


