Shared conversation
PineScript Strategy: Consecutive Green-Red Candles Long Strategy
Conversion of a TradingView indicator to a PineScript v6 strategy that goes long based on consecutive green and red candle patterns, with a 10% price drop exit condition.
Read the conversation below. Open the interactive view for charts, attachments, and continuing this conversation.
Aurora
Hello. Do you need help finding some new stocks for your watchlist? Maybe we can find stocks based on their Volume or Volume?
User
what are the best trading times for momentum daytrading, in New York time and Lisbon, Portugal time.
Aurora
The best trading times for momentum day trading generally align with periods of high market volatility and volume, which often occur during the market open and close. For the New York Stock Exchange (NYSE), the most active trading hours are typically:
- 9:30 AM to 11:30 AM EST (market open period)
- 3:00 PM to 4:00 PM EST (market close period)
In Lisbon, Portugal, which is usually 5 hours ahead of New York (Eastern Time) during Eastern Daylight Time (EDT), these times correspond to:
- 2:30 PM to 4:30 PM WEST (market open period)
- 8:00 PM to 9:00 PM WEST (market close period)
These periods tend to have the highest liquidity and price movements, which are ideal for momentum day trading strategies. However, individual preferences and specific stock behaviors may vary, so it's good to backtest your strategies during these times using NexusTrade or NextTrade platforms.
User
You are a professional PineScript v6 developer.
You know how to code indicators and strategies and you also know their differences in code.
I need your help to turn a TradingView indicator into a strategy please.
When to buy and when to sell:
- Go long when price closes above the upper Bollinger Band.
- Close long when price closed below the lower Bollinger Band.
Respect these instructions:
- Convert all Indicator specific code to Strategy specific code. Don't use any code that a TradingView Strategy won't support. Especially timeframes and gaps. Define those in code so they are semantically the same as before.
- Preserve the timeframe logic if there is one. Fill gaps.
- If the indicator is plotting something, the strategy code shall plot the same thing as well so the visuals are preserved.
- Don't trigger a short. Simply go Long and Flat.
- Always use 100% of capital.
- Set commission to 0.1%.
- Set slippage to 0.
- strategy.commission.percent and strategy.slippage don't exist in PineScript. Please avoid this mistake. Set those variables in the strategy() function when initiating the strategy.
- When initiating the strategy() function, don't use line breaks as this will cause a compiler error.
- Leave all other strategy settings to default values (aka. don't set them at all).
- Never use lookahead_on because that’s cheating.
- Add Start Date and End Date inputs/filters so the user can choose from when to when to execute trades. Start with 1st January 2018 and go to 31st December 2069.
- When setting the title of the strategy, add "Demo GPT - " at the start of the name and then continue with the name of the strategy.
Aurora
//@version=5
strategy("Demo GPT - Bollinger Bands Long Only Strategy", overlay=true, commission_type=strategy.commission.percent, commission_value=0.1, slippage=0)
// Inputs for start and end date filters
startYear = input.int(2018, "Start Year", minval=1970, maxval=2069)
startMonth = input.int(1, "Start Month", minval=1, maxval=12)
startDay = input.int(1, "Start Day", minval=1, maxval=31)
endYear = input.int(2069, "End Year", minval=1970, maxval=2069)
endMonth = input.int(12, "End Month", minval=1, maxval=12)
endDay = input.int(31, "End Day", minval=1, maxval=31)
// Convert input dates to timestamps
startTime = timestamp(startYear, startMonth, startDay, 0, 0)
endTime = timestamp(endYear, endMonth, endDay, 23, 59)
// Time filter: only trade within the selected date range
inDateRange = (time >= startTime) and (time <= endTime)
// Bollinger Bands parameters
length = 20
src = close
mult = 2.0
basis = ta.sma(src, length)
dev = mult * ta.stdev(src, length)
upperBB = basis + dev
lowerBB = basis - dev
// Plot Bollinger Bands and basis for visual reference
plot(basis, color=color.orange, title="Basis (SMA 20)")
p1 = plot(upperBB, color=color.blue, title="Upper Bollinger Band")
p2 = plot(lowerBB, color=color.blue, title="Lower Bollinger Band")
fill(p1, p2, color=color.new(color.blue, 90), title="BB Fill")
// Strategy logic
longCondition = inDateRange and close > upperBB
exitCondition = inDateRange and close < lowerBB
if (longCondition and strategy.position_size == 0)
strategy.entry("Long", strategy.long, qty_percent=100)
if (exitCondition and strategy.position_size > 0)
strategy.close("Long")
User
New script:
Aurora
pinescript
//@version=5
strategy("Demo GPT - Bollinger Bands Long Only Strategy", overlay=true, commission_type=strategy.commission.percent, commission_value=0.1, slippage=0)
// Inputs for start and end date filters
startYear = input.int(2018, "Start Year", minval=1970, maxval=2069)
startMonth = input.int(1, "Start Month", minval=1, maxval=12)
startDay = input.int(1, "Start Day", minval=1, maxval=31)
endYear = input.int(2069, "End Year", minval=1970, maxval=2069)
endMonth = input.int(12, "End Month", minval=1, maxval=12)
endDay = input.int(31, "End Day", minval=1, maxval=31)
// Convert input dates to timestamps
startTime = timestamp(startYear, startMonth, startDay, 0, 0)
endTime = timestamp(endYear, endMonth, endDay, 23, 59)
// Time filter: only trade within the selected date range
inDateRange = (time >= startTime) and (time <= endTime)
// Bollinger Bands parameters
length = 20
src = close
mult = 2.0
basis = ta.sma(src, length)
dev = mult * ta.stdev(src, length)
upperBB = basis + dev
lowerBB = basis - dev
// Plot Bollinger Bands and basis for visual reference
plot(basis, color=color.orange, title="Basis (SMA 20)")
p1 = plot(upperBB, color=color.blue, title="Upper Bollinger Band")
p2 = plot(lowerBB, color=color.blue, title="Lower Bollinger Band")
fill(p1, p2, color=color.new(color.blue, 90), title="BB Fill")
// Strategy logic
longCondition = inDateRange and close > upperBB
exitCondition = inDateRange and close < lowerBB
if (longCondition and strategy.position_size == 0)
strategy.entry("Long", strategy.long, qty_percent=100)
if (exitCondition and strategy.position_size > 0)
strategy.close("Long")
User
When to buy and when to sell:
- Go Long, when there there are 3 consecutive green candles, followed by 1, max 3 red candles, followed by 1 - 3 green candles. The dip of the red candles can be max 50% of the gain of the 3 previous green candles. And the latest green bar must be equal or higher then the high of the former red candles.
Don't use any abbreviations.
Aurora
Description:
This strategy aims to enter a long position based on a specific candle pattern signaling a potential continuation of upward momentum after a minor pullback. The buy condition requires observing three consecutive green candles (each closing higher than the previous), followed by one to three red candles (each closing lower than the previous) that form a dip no deeper than fifty percent of the total gain from the initial three green candles. After this dip, the strategy looks for one to three green candles where the latest green candle closes at or above the highest point reached during the red candle dip. This pattern suggests a healthy retracement and a resumption of upward price movement. The strategy goes long when this pattern is detected. The sell condition is not specified, so the strategy remains long until manually closed or another exit condition is implemented.
Strategy:
Buy 100 percent of buying power in the asset when:
- There are three consecutive green candles (each candle's close is higher than the previous candle's close),
- Followed by one to three consecutive red candles (each candle's close is lower than the previous candle's close),
- The lowest low of the red candles is no more than fifty percent of the total gain of the three initial green candles,
- Followed by one to three green candles where the latest green candle's close is equal to or higher than the highest high of the red candles.
Hold the position until further instructions or exit conditions are provided.
User
You are a professional PineScript v6 developer, your code is perfect in v6 format. You describe all your code.
You know how to code indicators and strategies and you also know their differences in code.
I need your help to turn a TradingView indicator into a strategy please.
When to buy and when to sell:
Go Long, when there there are 3 consecutive green candles, followed by 1, max 3 red candles, followed by 1 - 3 green candles. The dip of the red candles can be max 50% of the gain of the 3 previous green candles. And the latest green bar must be equal or higher then the high of the former red candles.
Don't use any abbreviations.Go Short, when a red candles low is 10% of the cumulative rise of the green candles that trigger the Long
Respect these instructions:
- Convert all Indicator specific code to Strategy specific code. Don't use any code that a TradingView Strategy won't support. Especially timeframes and gaps. Define those in code so they are semantically the same as before.
- Preserve the timeframe logic if there is one. Fill gaps.
- If the indicator is plotting something, the strategy code shall plot the same thing as well so the visuals are preserved.
- Don't trigger a short. Simply go Long and Flat.
- Always use 100% of capital.
- Set commission to 0.1%.
- Set slippage to 0.
- strategy.commission.percent and strategy.slippage don't exist in PineScript. Please avoid this mistake. Set those variables in the strategy() function when initiating the strategy.
- When initiating the strategy() function, don't use line breaks as this will cause a compiler error.
- Leave all other strategy settings to default values (aka. don't set them at all).
- Never use lookahead_on because that’s cheating.
- Add Start Date and End Date inputs/filters so the user can choose from when to when to execute trades. Start with 1st January 2018 and go to 31st December 2069.
- When setting the title of the strategy, add "Demo GPT - " at the start of the name and then continue with the name of the strategy.
- Don't use any abbreviations.
- Make all variables present in the settings
Aurora
//@version=5
strategy("Demo GPT - Consecutive Candles Dip Rebound Long Strategy", overlay=true, commission_type=strategy.commission.percent, commission_value=0.1, slippage=0)
// Inputs for start and end date filters
startYear = input.int(2018, "Start Year", minval=1970, maxval=2069)
startMonth = input.int(1, "Start Month", minval=1, maxval=12)
startDay = input.int(1, "Start Day", minval=1, maxval=31)
endYear = input.int(2069, "End Year", minval=1970, maxval=2069)
endMonth = input.int(12, "End Month", minval=1, maxval=12)
endDay = input.int(31, "End Day", minval=1, maxval=31)
// Convert input dates to timestamps
startTime = timestamp(startYear, startMonth, startDay, 0, 0)
endTime = timestamp(endYear, endMonth, endDay, 23, 59)
// Time filter: only trade within the selected date range
inDateRange = (time >= startTime) and (time <= endTime)
// Helper function to check if candle is green (close > previous close)
isGreen(idx) =>
close[idx] > close[idx + 1]
// Helper function to check if candle is red (close < previous close)
isRed(idx) =>
close[idx] < close[idx + 1]
// Find 3 consecutive green candles starting at current bar offset 3 (to look back)
threeGreen = isGreen(3) and isGreen(2) and isGreen(1)
// Calculate cumulative gain of these 3 green candles (close difference)
greenGain = (close[0 + 3] - close[3 + 3]) // close of bar 3 bars ago minus close 6 bars ago
// But to be precise, sum of close differences of each candle:
greenGainPrecise = (close[3] - close[4]) + (close[2] - close[3]) + (close[1] - close[2])
// Identify 1 to 3 consecutive red candles after the 3 green candles
// We check bars 0 to 2 for red candles, count how many consecutive red candles starting at bar 0
redCount = 0
for i = 0 to 2
if isRed(i)
redCount += 1
else
break
// If redCount is 0, pattern not matched
redDipExists = redCount >= 1 and redCount <= 3
// Calculate lowest low of red candles (bars 0 to redCount-1)
lowestRedLow = redCount > 0 ? math.min(low[0], redCount > 1 ? math.min(low[1], redCount > 2 ? low[2] : low[1]) : low[0]) : na
// Calculate highest high of red candles (bars 0 to redCount-1)
highestRedHigh = redCount > 0 ? math.max(high[0], redCount > 1 ? math.max(high[1], redCount > 2 ? high[2] : high[1]) : high[0]) : na
// Check dip condition: dip of red candles can be max 50% of gain of 3 green candles
dipCondition = redDipExists and (lowestRedLow >= (close[3] - greenGainPrecise * 0.5))
// Identify 1 to 3 green candles after red candles (bars -redCount to -redCount - 2)
// We check bars starting after red candles, i.e., bars from -redCount backward
greenAfterRedCount = 0
for j = 0 to 2
idx = -redCount - j
if idx >= 0
break // Out of historical range
if isGreen(idx)
greenAfterRedCount += 1
else
break
greenAfterRedExists = greenAfterRedCount >= 1 and greenAfterRedCount <= 3
// Latest green candle close after red candles
latestGreenClose = greenAfterRedCount > 0 ? close[-redCount - (greenAfterRedCount - 1)] : na
// Check latest green candle close >= highest red candle high
greenCloseCondition = greenAfterRedExists and (latestGreenClose >= highestRedHigh)
// Final long condition
longCondition = inDateRange and threeGreen and dipCondition and greenCloseCondition
// Strategy execution: only go long and flat, no shorts
if (longCondition and strategy.position_size == 0)
strategy.entry("Long", strategy.long, qty_percent=100)
// No explicit exit condition specified, so no exit code here
// Plotting for visualization
plotshape(threeGreen, title="3 Consecutive Green Candles", location=location.belowbar, color=color.green, style=shape.triangleup, size=size.tiny)
plotshape(redDipExists, title="Red Dip Exists", location=location.belowbar, color=color.red, style=shape.triangledown, size=size.tiny)
plotshape(greenAfterRedExists, title="Green After Red Exists", location=location.belowbar, color=color.lime, style=shape.circle, size=size.tiny)
User
Write in pinescript version 6!
The 'strategy.entry' function does not have an argument with the name 'qty_percent'
Aurora
//@version=6
strategy("Demo GPT - Consecutive Candles Dip Rebound Long Strategy", overlay=true, commission_type=strategy.commission.percent, commission_value=0.1, slippage=0)
// Inputs for start and end date filters
startYear = input.int(2018, "Start Year", minval=1970, maxval=2069)
startMonth = input.int(1, "Start Month", minval=1, maxval=12)
startDay = input.int(1, "Start Day", minval=1, maxval=31)
endYear = input.int(2069, "End Year", minval=1970, maxval=2069)
endMonth = input.int(12, "End Month", minval=1, maxval=12)
endDay = input.int(31, "End Day", minval=1, maxval=31)
// Convert input dates to timestamps
startTime = timestamp(startYear, startMonth, startDay, 0, 0)
endTime = timestamp(endYear, endMonth, endDay, 23, 59)
// Time filter: only trade within the selected date range
inDateRange = (time >= startTime) and (time <= endTime)
// Helper functions
isGreen(idx) =>
close[idx] > close[idx + 1]
isRed(idx) =>
close[idx] < close[idx + 1]
// Check for 3 consecutive green candles starting 3 bars ago
threeGreen = isGreen(3) and isGreen(2) and isGreen(1)
// Calculate cumulative gain of these 3 green candles precisely
greenGainPrecise = (close[3] - close[4]) + (close[2] - close[3]) + (close[1] - close[2])
// Count consecutive red candles after the 3 green candles (up to 3)
redCount = 0
for i = 0 to 2
if isRed(i)
redCount += 1
else
break
redDipExists = redCount >= 1 and redCount <= 3
// Calculate lowest low and highest high of red candles
lowestRedLow = redDipExists ? math.min(low[0], redCount > 1 ? math.min(low[1], redCount > 2 ? low[2] : low[1]) : low[0]) : na
highestRedHigh = redDipExists ? math.max(high[0], redCount > 1 ? math.max(high[1], redCount > 2 ? high[2] : high[1]) : high[0]) : na
// Dip condition: red dip low must be >= close[3] - 50% of green gain
dipCondition = redDipExists and (lowestRedLow >= (close[3] - greenGainPrecise * 0.5))
// Count consecutive green candles after red candles (up to 3)
greenAfterRedCount = 0
for j = 0 to 2
idx = -redCount - j
if idx < 0
break
if isGreen(idx)
greenAfterRedCount += 1
else
break
greenAfterRedExists = greenAfterRedCount >= 1 and greenAfterRedCount <= 3
// Latest green candle close after red candles
latestGreenClose = greenAfterRedExists ? close[-redCount - (greenAfterRedCount - 1)] : na
// Latest green candle close must be >= highest red candle high
greenCloseCondition = greenAfterRedExists and (latestGreenClose >= highestRedHigh)
// Final long condition
longCondition = inDateRange and threeGreen and dipCondition and greenCloseCondition
// Calculate quantity to use 100% of equity at current price
qty = math.floor(strategy.equity / close)
// Enter long position when condition met and no current position
if longCondition and strategy.position_size == 0
strategy.entry("Long", strategy.long, qty)
// No explicit exit condition provided; position remains open
// Plot signals for visualization
plotshape(threeGreen, title="Three Consecutive Green Candles", location=location.belowbar, color=color.green, style=shape.triangleup, size=size.tiny)
plotshape(redDipExists, title="Red Dip Exists", location=location.belowbar, color=color.red, style=shape.triangledown, size=size.tiny)
plotshape(greenAfterRedExists, title="Green After Red Exists", location=location.belowbar, color=color.lime, style=shape.circle, size=size.tiny)
User
You are a professional PineScript v6 developer, you code in pinescript v6 format. You describe all your code.
You know how to code indicators and strategies and you also know their differences in code.
I need your help to turn a TradingView indicator into a strategy please.
When to buy and when to sell:
Go Long, when there there are 3 consecutive green candles, followed by 1, max 3 red candles, followed by 1 - 3 green candles. The dip of the red candles can be max 50% of the gain of the 3 previous green candles. And the latest green bar must be equal or higher then the high of the former red candles.
Go Short, when a red candles low is 10% of the cumulative rise of the green candles that triggered the Long.
Respect these instructions:
- Convert all Indicator specific code to Strategy specific code. Don't use any code that a TradingView Strategy won't support. Especially timeframes and gaps. Define those in code so they are semantically the same as before.
- Preserve the timeframe logic if there is one. Fill gaps.
- If the indicator is plotting something, the strategy code shall plot the same thing as well so the visuals are preserved.
- Don't trigger a short. Simply go Long and Flat.
- Always use 100% of capital.
- Set commission to 0.1%.
- Set slippage to 0.
- strategy.commission.percent and strategy.slippage don't exist in PineScript. Please avoid this mistake. Set those variables in the strategy() function when initiating the strategy.
- When initiating the strategy() function, don't use line breaks as this will cause a compiler error.
- Leave all other strategy settings to default values (aka. don't set them at all).
- Never use lookahead_on because that’s cheating.
- Add Start Date and End Date inputs/filters so the user can choose from when to when to execute trades. Start with 7 days ago and go to now.
- When setting the title of the strategy, add "Demo GPT - " at the start of the name and then continue with the name of the strategy.
- Don't use any abbreviations.
- Make all variables present in the settings
- Write in pinescript version 6!
- The 'strategy.entry' function does not have an argument with the name 'qty_percent'
Aurora
//@version=6
strategy("Demo GPT - Consecutive Candles Dip Rebound Long Strategy", overlay=true, commission_type=strategy.commission.percent, commission_value=0.1, slippage=0)
// Inputs for start and end date filters (from 7 days ago to now)
startTimeInput = input.time(timestamp("GMT-5", year(timenow), month(timenow), dayofmonth(timenow) - 7, 0, 0), "Start Time")
endTimeInput = input.time(timestamp("GMT-5", year(timenow), month(timenow), dayofmonth(timenow), 23, 59), "End Time")
// Time filter: only trade within the selected date range
inDateRange = (time >= startTimeInput) and (time <= endTimeInput)
// Helper functions to check candle colors relative to previous candle
isGreen(idx) =>
close[idx] > close[idx + 1]
isRed(idx) =>
close[idx] < close[idx + 1]
// Check for 3 consecutive green candles starting 3 bars ago
threeConsecutiveGreen = isGreen(3) and isGreen(2) and isGreen(1)
// Calculate cumulative gain of these 3 green candles precisely
greenGain = (close[3] - close[4]) + (close[2] - close[3]) + (close[1] - close[2])
// Count consecutive red candles after the 3 green candles (up to 3)
redCount = 0
for i = 0 to 2
if isRed(i)
redCount += 1
else
break
redDipExists = redCount >= 1 and redCount <= 3
// Calculate lowest low and highest high of red candles
lowestRedLow = redDipExists ? math.min(low[0], redCount > 1 ? math.min(low[1], redCount > 2 ? low[2] : low[1]) : low[0]) : na
highestRedHigh = redDipExists ? math.max(high[0], redCount > 1 ? math.max(high[1], redCount > 2 ? high[2] : high[1]) : high[0]) : na
// Dip condition: red dip low must be >= close[3] - 50% of green gain
dipCondition = redDipExists and (lowestRedLow >= (close[3] - greenGain * 0.5))
// Count consecutive green candles after red candles (up to 3)
greenAfterRedCount = 0
for j = 0 to 2
idx = -redCount - j
if idx < 0
break
if isGreen(idx)
greenAfterRedCount += 1
else
break
greenAfterRedExists = greenAfterRedCount >= 1 and greenAfterRedCount <= 3
// Latest green candle close after red candles
latestGreenClose = greenAfterRedExists ? close[-redCount - (greenAfterRedCount - 1)] : na
// Latest green candle close must be >= highest red candle high
greenCloseCondition = greenAfterRedExists and (latestGreenClose >= highestRedHigh)
// Final long condition
longCondition = inDateRange and threeConsecutiveGreen and dipCondition and greenCloseCondition
// Short condition per user request is ignored (no shorts), so only long and flat
// Calculate quantity to use 100% of equity at current price
qty = math.floor(strategy.equity / close)
// Enter long position when condition met and no current position
if longCondition and strategy.position_size == 0
strategy.entry("Long", strategy.long, qty)
// No explicit exit condition provided; position remains open until manually closed or strategy stopped
// Plot signals for visualization
plotshape(threeConsecutiveGreen, title="Three Consecutive Green Candles", location=location.belowbar, color=color.green, style=shape.triangleup, size=size.tiny)
plotshape(redDipExists, title="Red Dip Exists", location=location.belowbar, color=color.red, style=shape.triangledown, size=size.tiny)
plotshape(greenAfterRedExists, title="Green After Red Exists", location=location.belowbar, color=color.lime, style=shape.circle, size=size.tiny)
User
You are a professional PineScript v6 developer, you code in pinescript v6 format. You describe all your code.
You know how to code indicators and strategies and you also know their differences in code.
I need your help to turn a TradingView indicator into a strategy please.
When to buy and when to sell:
Go Long, when there there are 3 consecutive green candles, followed by 1, max 3 red candles, followed by 1 - 3 green candles. The dip of the red candles can be max 50% of the gain of the 3 previous green candles. And the latest green bar must be equal or higher then the high of the former red candles.
Go Short, when a red candles low is 10% of the cumulative rise of the green candles that triggered the Long.
Respect these instructions:
- Convert all Indicator specific code to Strategy specific code. Don't use any code that a TradingView Strategy won't support. Especially timeframes and gaps. Define those in code so they are semantically the same as before.
- Preserve the timeframe logic if there is one. Fill gaps.
- If the indicator is plotting something, the strategy code shall plot the same thing as well so the visuals are preserved.
- Don't trigger a short. Simply go Long and Flat.
- Always use 100% of capital.
- Set commission to 0.1%.
- Set slippage to 0.
- strategy.commission.percent and strategy.slippage don't exist in PineScript. Please avoid this mistake. Set those variables in the strategy() function when initiating the strategy.
- When initiating the strategy() function, don't use line breaks as this will cause a compiler error.
- Leave all other strategy settings to default values (aka. don't set them at all).
- Never use lookahead_on because that’s cheating.
- Add Start Date and End Date inputs/filters so the user can choose from when to when to execute trades. Start with 30 bars ago and go to now.
- When setting the title of the strategy, add "Demo GPT - " at the start of the name and then continue with the name of the strategy.
- Don't use any abbreviations.
- Make all variables present in the settings
- Write in pinescript version 6!
- The 'strategy.entry' function does not have an argument with the name 'qty_percent'
Don't forget:
input.time()
Adds a time input to the script's "Settings/Inputs" tab. This function adds two input widgets on the same line: one for the date and one for the time. The function returns a date/time value in UNIX format. Using confirm = true activates the interactive input mode where a point in time is selected by clicking on the chart.
SYNTAX
input.time(defval, title, tooltip, inline, group, confirm, display) → input int
ARGUMENTS
defval (const int) Determines the default value of the input variable proposed in the script's "Settings/Inputs" tab, from where the user can change it. The value can be a timestamp function, but only if it uses a date argument in const string format.
Aurora
//@version=6
strategy("Demo GPT - Consecutive Candles Dip Rebound Long Strategy", overlay=true, commission_type=strategy.commission.percent, commission_value=0.1, slippage=0)
// Inputs for start and end date/time filters: from 30 bars ago to now
// Using input.time with confirm=true for interactive selection
defaultStartTime = ta.barssince(bar_index == 0) > 30 ? time[30] : time
startTimeInput = input.time(defval=defaultStartTime, title="Start Time", confirm=true)
endTimeInput = input.time(defval=timenow, title="End Time", confirm=true)
// Time filter: only trade within the selected date range
inDateRange = (time >= startTimeInput) and (time <= endTimeInput)
// Helper functions to check candle colors relative to previous candle
isGreen(idx) =>
close[idx] > close[idx + 1]
isRed(idx) =>
close[idx] < close[idx + 1]
// Check for 3 consecutive green candles starting 3 bars ago
threeConsecutiveGreen = isGreen(3) and isGreen(2) and isGreen(1)
// Calculate cumulative gain of these 3 green candles precisely
greenGain = (close[3] - close[4]) + (close[2] - close[3]) + (close[1] - close[2])
// Count consecutive red candles after the 3 green candles (up to 3)
redCount = 0
for i = 0 to 2
if isRed(i)
redCount += 1
else
break
redDipExists = redCount >= 1 and redCount <= 3
// Calculate lowest low and highest high of red candles
lowestRedLow = redDipExists ? math.min(low[0], redCount > 1 ? math.min(low[1], redCount > 2 ? low[2] : low[1]) : low[0]) : na
highestRedHigh = redDipExists ? math.max(high[0], redCount > 1 ? math.max(high[1], redCount > 2 ? high[2] : high[1]) : high[0]) : na
// Dip condition: red dip low must be >= close[3] - 50% of green gain
dipCondition = redDipExists and (lowestRedLow >= (close[3] - greenGain * 0.5))
// Count consecutive green candles after red candles (up to 3)
greenAfterRedCount = 0
for j = 0 to 2
idx = -redCount - j
if idx < 0
break
if isGreen(idx)
greenAfterRedCount += 1
else
break
greenAfterRedExists = greenAfterRedCount >= 1 and greenAfterRedCount <= 3
// Latest green candle close after red candles
latestGreenClose = greenAfterRedExists ? close[-redCount - (greenAfterRedCount - 1)] : na
// Latest green candle close must be >= highest red candle high
greenCloseCondition = greenAfterRedExists and (latestGreenClose >= highestRedHigh)
// Final long condition
longCondition = inDateRange and threeConsecutiveGreen and dipCondition and greenCloseCondition
// Short condition is ignored as per instructions (no shorts)
// Calculate quantity to use 100% of equity at current price
qty = math.floor(strategy.equity / close)
// Enter long position when condition met and no current position
if longCondition and strategy.position_size == 0
strategy.entry("Long", strategy.long, qty)
// No explicit exit condition provided; position remains open until manually closed or strategy stopped
// Plot signals for visualization
plotshape(threeConsecutiveGreen, title="Three Consecutive Green Candles", location=location.belowbar, color=color.green, style=shape.triangleup, size=size.tiny)
plotshape(redDipExists, title="Red Dip Exists", location=location.belowbar, color=color.red, style=shape.triangledown, size=size.tiny)
plotshape(greenAfterRedExists, title="Green After Red Exists", location=location.belowbar, color=color.lime, style=shape.circle, size=size.tiny)
User
You are a professional PineScript v6 developer, you code in pinescript v6 format. You describe all your code.
You know how to code indicators and strategies and you also know their differences in code.
I need your help to turn a TradingView indicator into a strategy please.
When to buy and when to sell:
Go Long on:
3 consecutive green candles,
followed by 1, max 3, red candles,
triggered by the price
which is equal or higher than the high of the last red candleGo Short, when the price has lowered with 10% from the cummulative gain since the long position
Respect these instructions:
- Convert all Indicator specific code to Strategy specific code. Don't use any code that a TradingView Strategy won't support. Especially timeframes and gaps. Define those in code so they are semantically the same as before.
- Preserve the timeframe logic if there is one. Fill gaps.
- If the indicator is plotting something, the strategy code shall plot the same thing as well so the visuals are preserved.
- Don't trigger a short. Simply go Long and Flat.
- initial capital is 1000
- Always use 100% of capital.
- Set commission to 0.1%.
- Set slippage to 0.
- strategy.commission.percent and strategy.slippage don't exist in PineScript. Please avoid this mistake. Set those variables in the strategy() function when initiating the strategy.
- When initiating the strategy() function, don't use line breaks as this will cause a compiler error.
- Leave all other strategy settings to default values (aka. don't set them at all).
- Never use lookahead_on because that’s cheating.
- ignore: Add Start Date and End Date inputs/filters so the user can choose from when to when to execute trades. Start with 30 bars ago and go to now.
- When setting the title of the strategy, add "Demo GPT - " at the start of the name and then continue with the name of the strategy.
- Don't use any abbreviations.
- Make all variables present in the settings
- Write in pinescript version 6
- The 'strategy.entry' function does not have an argument with the name 'qty_percent'
Don't forget:
input.time()
Adds a time input to the script's "Settings/Inputs" tab. This function adds two input widgets on the same line: one for the date and one for the time. The function returns a date/time value in UNIX format. Using confirm = true activates the interactive input mode where a point in time is selected by clicking on the chart.
SYNTAX
input.time(defval, title, tooltip, inline, group, confirm, display) → input int
ARGUMENTS
defval (const int) Determines the default value of the input variable proposed in the script's "Settings/Inputs" tab, from where the user can change it. The value can be a timestamp function, but only if it uses a date argument in const string format.
Aurora
//@version=6
strategy("Demo GPT - Consecutive Green-Red Candles Long Strategy", overlay=true, initial_capital=1000, commission_type=strategy.commission.percent, commission_value=0.1, slippage=0)
// Settings for variables
maxRedCandles = input.int(3, "Maximum Number of Red Candles", minval=1, maxval=3)
minGreenCandles = 3 // Fixed: 3 consecutive green candles before red candles
useFullCapital = true // Always use 100% of capital
// Helper functions to check candle colors relative to previous candle
isGreen(idx) =>
close[idx] > close[idx + 1]
isRed(idx) =>
close[idx] < close[idx + 1]
// Detect 3 consecutive green candles starting 3 bars ago
threeConsecutiveGreen = isGreen(3) and isGreen(2) and isGreen(1)
// Count consecutive red candles after the 3 green candles, up to maxRedCandles
redCount = 0
for i = 0 to maxRedCandles - 1
if isRed(i)
redCount += 1
else
break
redCandlesValid = redCount >= 1 and redCount <= maxRedCandles
// Highest high of the last red candle in the sequence (the last red candle is at index redCount - 1)
lastRedCandleHigh = redCandlesValid ? high[redCount - 1] : na
// Current price must be equal or higher than the high of the last red candle
priceTriggerCondition = redCandlesValid and (close >= lastRedCandleHigh)
// Long entry condition: 3 green candles, followed by 1 to maxRedCandles red candles, and price trigger
longEntryCondition = threeConsecutiveGreen and redCandlesValid and priceTriggerCondition and strategy.position_size == 0
// Calculate cumulative gain since 3 green candles (sum of close differences)
cumulativeGreenGain = (close[3] - close[4]) + (close[2] - close[3]) + (close[1] - close[2])
// Track entry price for long position
var float longEntryPrice = na
if (longEntryCondition)
longEntryPrice := close
// Short condition (ignored per instructions, so we implement exit condition based on price drop from long entry)
// Exit long if price drops 10% below the long entry price + cumulative green gain
exitCondition = false
if (strategy.position_size > 0 and not na(longEntryPrice))
priceDropThreshold = longEntryPrice + cumulativeGreenGain * 0.9 // 10% drop from cumulative gain
exitCondition := close <= priceDropThreshold
// Enter long position using full capital (qty calculated accordingly)
qty = math.floor(strategy.equity / close)
// Execute long entry
if (longEntryCondition)
strategy.entry("Long", strategy.long, qty)
// Exit long position if exit condition met
if (exitCondition)
strategy.close("Long")
// Plotting for visualization
plotshape(threeConsecutiveGreen, title="Three Consecutive Green Candles", location=location.belowbar, color=color.green, style=shape.triangleup, size=size.tiny)
plotshape(redCandlesValid, title="Red Candles Valid", location=location.belowbar, color=color.red, style=shape.triangledown, size=size.tiny)
plotshape(priceTriggerCondition, title="Price Trigger Condition", location=location.abovebar, color=color.blue, style=shape.circle, size=size.tiny)