Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
556 views
in Technique[技术] by (71.8m points)

pine script - How to define a specific range as the length of "sum(x, len)"?

I want to check if a certain condition is met at least once within the first half of my lookback period, and then if it's met again at least once within the second half of the period.

I'm trying to do this with the code below, as I've learned here. But I didn't figure it out how to make len a range.

So my question is: how to make len a range? (below len as lenFirstHalf and lenSecondHalf).

Any help will be highly appreciated!

lookBack = input(title="Lookback", type=input.integer, defval=24, minval=2)
condition = close > open
lenFirstHalf = (<GREATER THAN> (lookBack/2)) and (<LESS THAN OR EQUAL TO> lookback)
lenSecondHalf = (<GREATER THAN OR EQUAL TO> 1) and (<LESS THAN OR EQUAL TO (lookback/2))

// Check if the condition is met in the FIRST half of the lookback period
triggerA = (sum(condition ? 1 : 0, lenFirstHalf)) >= 1 ? true : false
// Check if the condition is met in the SECOND half of the lookback period
triggerB = (sum(condition ? 1 : 0, lenSecondHalf)) >= 1 ? true : false

Evidently, those <GREATER THAN> and <LESS THAN OR EQUAL TO> do not exist, but I have no idea how to attribute such a range to a variable.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I think something like this should work.

lookBack = input(title="Lookback", type=input.integer, defval=24, minval=2)

condition     = close > open

sumLookBack   = sum(condition ? 1 : 0, lookBack)
sumSecondHalf = sum(condition ? 1 : 0, lookBack/2)
sumFirstHalf  = sumLookBack - sumSecondHalf

// Check if the condition is met in the FIRST half of the lookback period
triggerA = sumFirstHalf >= 1 ? true : false
// Check if the condition is met in the SECOND half of the lookback period
triggerB = sumSecondHalf >= 1 ? true : false

The length that you use in sum() is used to calculate the sum from length bars back until the latest bar.
So by first calculating the entire length, and then subtracting the "second" half, you get the "first" half.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...