乐闻世界logo
搜索文章和话题

How to get historical daily close price in PineScript

1个答案

1

In Pine Script, you can retrieve historical data, including historical daily closing prices, using built-in functions. Below are the specific steps and example code demonstrating how to obtain and use historical daily closing prices:

Step 1: Define the Timeframe You Want to Use

First, ensure your script is set to the correct timeframe. If you want to obtain daily data, your script should operate on the daily timeframe. You can specify the timeframe by setting the timeframe parameter in the study or strategy function of Pine Script.

pine
//@version=5 indicator("My Script", overlay=true, timeframe=""

Step 2: Use the request.security Function to Retrieve Historical Data

You can use the request.security function to fetch data from other timeframes. Even if your main script is on a lower timeframe, you can still access daily closing prices.

pine
daily_close = request.security(syminfo.tickerid, "D", close)

This line retrieves the daily closing price of the current symbol.

Example: Calculating the Average Closing Price of the Past Five Days

Below is an example Pine Script that calculates the average closing price over the past five days and plots it on the chart.

pine
//@version=5 indicator("Past 5 Days Average Close", overlay=true) // Retrieve the daily closing prices of the past five trading days day1 = request.security(syminfo.tickerid, "D", close[1]) day2 = request.security(syminfo.tickerid, "D", close[2]) day3 = request.security(syminfo.tickerid, "D", close[3]) day4 = request.security(syminfo.tickerid, "D", close[4]) day5 = request.security(syminfo.tickerid, "D", close[5]) // Calculate the average avg_close = (day1 + day2 + day3 + day4 + day5) / 5 // Plot the average closing price plot(avg_close, title="5-Day Average Close", color=color.blue)

This script first uses the request.security function to obtain the closing prices of the past five trading days, then calculates the average of these values, and plots the average on the chart. This method is particularly useful for analyzing trends or developing trading strategies.

2024年6月29日 12:07 回复

你的答案