Strategy vault / Trend following
Last N Candle Reverse Logic Strategy
The main idea of this strategy is to determine long or short based on the color of the last N candles. If the last N candles are green, go long; if the last N candles are red, go short. The unique part is the…

Overview
The main idea of this strategy is to determine long or short based on the color of the last N candles. If the last N candles are green, go long; if the last N candles are red, go short. The unique part is the addition of an "inverse logic" parameter that can reverse the original logic. When the "inverse logic" parameter is true, the last N green candles will go short, and the last N red candles will go long.
Strategy Principle
This strategy mainly relies on the following important parameters:
- numCandlesToCheck: Used to specify the number of candles to check
- numCandlesToExit: Specifies the number of candles after opening position that needs to exit
- inverseLogic: The inverse logic parameter. When true, the original long and short logic is reversed
The key logic is to traverse the last numCandlesToCheck candles through a for loop, and count the consecutive green and red candles in real time. If consecutive red candles ≥numCandlesToCheck, mark lastNCandlesRed as true. If consecutive green candles ≥numCandlesToCheck, mark lastNCandlesGreen as true.
When lastNCandlesGreen is true, go long if inverseLogic is false, otherwise go short. On the contrary, when lastNCandlesRed is true, go short if inverseLogic is false, otherwise go long.
No matter long or short, the barsSinceEntry counter will be reset to 0 after opening position. When barsSinceEntry is greater than or equal to numCandlesToExit, the current position will be closed.
Advantage Analysis
This is an interesting strategy that uses candle color to make decisions, with an "inverse logic" parameter that can flexibly adjust the long and short logic. The main advantages are:
- The idea is novel and can form reverse investment against market common logic
- The code is clear and concise, easy to understand and modify
- Can find the optimal parameter combination by adjusting parameters
- No matter the market condition, this strategy can continue to run and generate signals
Risk Analysis
There are also some risks to note for this strategy:
- Candle color cannot fully represent market condition, risk of tracking incorrect signal exists
- Unable to determine optimal value for numCandlesToCheck
- Unable to determine optimal value for numCandlesToExit
- Improper inverse logic parameter may amplify losses
- Unable to effectively control single stop loss
To address these risks, the following measures can be adopted for control and optimization:
- Increase other filters to avoid incorrect signals, e.g. determine trend on higher timeframe
- Traverse different parameter values to find optimal parameter combination
- Add stop loss mechanism to control single loss
- Verify effectiveness of inverse logic parameter
Optimization Directions
The main optimization directions for this strategy are:
- Increase orderbook condition to avoid being trapped
- Optimize the values of numCandlesToCheck and numCandlesToExit
- Add trend indicator on higher timeframe to filter false signal
- Add stop loss and take profit
- Backtest on different products to verify effectiveness
- Compare return between original and inverted logic
Conclusion
The overall idea of this strategy is clear and easy to understand, generating trading signals simply based on candle color determination. Adjusting parameters can form rich combination variations for optimization targeting different market environments and products. Also need to pay attention to some potential risks and take necessary measures to control them. By continuously enriching strategy content, this strategy can become a valuable one to keep optimizing for long term trading.
Parameters
| Name | Default | What it controls |
|---|---|---|
| v_input_1 | 5 | Number of Candles to Check |
| v_input_2 | 2 | Number of Candles To Exit |
| v_input_3 | 10000 | Investment Value |
| v_input_4 | false | inverseLogic |
Source Pine Script
/*backtest
start: 2022-12-25 00:00:00
end: 2023-12-25 00:00:00
period: 1d
basePeriod: 1h
exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}]
*/
//@version=4
strategy("Last Number of Candles", overlay=true)
// Define the condition for a green candle
isGreenCandle(candle) =>
close[candle] > open[candle]
// Define the condition for a red candle
isRedCandle(candle) =>
close[candle] < open[candle]
// Input to specify the number of candles to check
numCandlesToCheck = input(5, title="Number of Candles to Check")
numCandlesToExit = input(2, title="Number of Candles To Exit") // Corrected the input title
// Initialize variables to count consecutive green and red candles
var int consecutiveGreenCandles = 0
var int consecutiveRedCandles = 0
// Initialize barsSinceEntry outside the loop
var int barsSinceEntry = 0
// Loop through the last "numCandlesToCheck" candles
for i = 0 to numCandlesToCheck - 1
if isGreenCandle(i)
consecutiveGreenCandles := consecutiveGreenCandles + 1
consecutiveRedCandles := 0 // Reset the count for consecutive red candles
else if isRedCandle(i)
consecutiveRedCandles := consecutiveRedCandles + 1
consecutiveGreenCandles := 0 // Reset the count for consecutive green candles
// Check if the last "numCandlesToCheck" candles are green or red
lastNCandlesGreen = consecutiveGreenCandles >= numCandlesToCheck
lastNCandlesRed = consecutiveRedCandles >= numCandlesToCheck
// Calculate the quantity based on the investment value and current asset price
investmentValue = input(10000, title="Investment Value")
var assetPrice = close
var quantity = investmentValue / assetPrice
inverseLogic = input(false, title="inverseLogic")
// Entry condition: Open a buy order if the last "numCandlesToCheck" candles are green
if lastNCandlesGreen
if inverseLogic
strategy.entry("Short", strategy.long, qty = quantity)
else
strategy.entry("Buy", strategy.long, qty = quantity)// Reset barsSinceEntry when entering a trade
barsSinceEntry := 0
// Entry condition: Open a short order if the last "numCandlesToCheck" candles are red
if lastNCandlesRed
if inverseLogic
strategy.entry("Buy", strategy.long, qty = quantity)
else
strategy.entry("Short", strategy.short, qty = quantity)
// Reset barsSinceEntry when entering a trade
barsSinceEntry := 0
// Increment barsSinceEntry
barsSinceEntry := barsSinceEntry + 1
// Exit condition: Close the position after 2 bars
if barsSinceEntry >= numCandlesToExit
strategy.close("Buy")
strategy.close("Short")
Published by ChaoZhang on the FMZ strategy square · last modified 2023-12-26. Collected in the Quant Trading Vault. Unvalidated research: re-test with your own data and costs before trusting it.
Build this with AgenKit
A spec is not a trading system. Paste this into your coding agent and AgenKit runs a specialist team — architecture, test-first build, risk gates, review — with paper trading on by default.
/agenkit build a production-grade trading bot with a backtest engine, risk controls and paper trading by default from strategies/Last-N-Candle-Reverse-Logic-Strategy.md- npx agenkit install engineering-kit in your project
- Paste the command into your agent and approve each phase
- Get tests, backtest, risk controls and a paper-trading switch
Understand it first
Before you run this, read the lesson behind the idea and how to backtest it honestly. Specs like this one are the survivors of an unknown number of trials; deflate their results accordingly.
Related specs
- 200 EMA VWAP MFI Trend Following StrategyPine Script · Trend following · 1d
- 4 EMA Trend StrategyPine Script · Trend following · 1d
- ADX MA and EMA Long Only Trend Tracking StrategyPine Script · Trend following · 1d
- ATR Dynamic Profit Target and Stop Loss StrategyPine Script · Trend following · 1d
- ATR Dynamic Trend Following and EMA Crossover Trading StrategyPine Script · Trend following · 1d
- ATR and Moving Average Crossover Hybrid StrategyPine Script · Trend following · 1h