I realized a hole in the logic of my earlier code trying to do this. My goal is to look when the tighter Donchian channel is in profit, if so, leave the stop there until the slower Donchian channel catches up, then trail with the slower channel.
That means I need a static value of the fast Donchian channel at the first candle that it is in profit (was missing this before). I can then use that value to compare it against the value of the slow channel and use the Max
of those two values for the trailing stop. But I am having a really hard time getting a static value and it seems like it is something simple I'm likely overlooking.
Assigning a variable to DonchianStop[i]
causes that variable to change as the DonchianStop
array changes, so that doesn't work.
Using ValueWhen
to try to get the value of DonchianStop
when the current candle is in profit but the previous one was not seems like it should work, but the variable remains empty so I might not be doing it right.
At this point in this code I am just trying to plot a horizontal line at the DonchianStop
value when it is in profit. I plan on adding the logic to compare that value to DonchianLower
later, but just taking it one step at a time. Can anyone help point me in the direction of figuring out how get this value and plot this horizontal line?
// ==========================================================================================
// === TRADING SYSTEM PARAMETERS ===
// ==========================================================================================
SetOption("InitialEquity", 100000);
SetTradeDelays( 0, 0, 0, 0 ); // 1 - Delays the trades to the next day, 0 - Trades same day via stops
SetOption("AllowPositionShrinking", True);
SetOption("AccountMargin",100); // 100 = Cash account, 75 = Using half available margin
SetOption("MaxOpenPositions", 20);
RoundLotSize = 1; // Disallow fractional share purchasing
// ==========================================================================================
// === RISK MANAGEMENT & POSITION SIZING ===
// ==========================================================================================
// Initial (MAX) stop loss
SetOption("ActivateStopsImmediately", False);
stopLoss = 7; // Change this to a small number to experience the issue with trade entries being ignored
ApplyStop(stopTypeLoss, stopModePercent, stopLoss, ExitAtStop = 1);
// Position size based on risk and max stop loss
PositionRisk = 1;
PosSize = 100 * PositionRisk / stopLoss;
SetPositionSize(PosSize, spsPercentOfEquity);
// ==========================================================================================
// === PLOT CHART & INDICATORS ===
// ==========================================================================================
// Chart
SetChartOptions(0,chartShowArrows|chartShowDates);
_N(Title = StrFormat("{{NAME}} - " + FullName() + " | {{INTERVAL}} {{DATE}}: Open %g, Hi %g, Lo %g, Close %g (%.1f%%) {{VALUES}}", O, H, L, C, SelectedValue( ROC( C, 1 ) ) ));
Plot( C, "Close", ParamColor("Color", colorDefault ), styleNoTitle | ParamStyle("Style") | GetPriceStyle() );
// Donchian Channel
pdsU=4; // High channel lookback
pdsL=5; // Low channel lookback
pdsS=3; // Tight Stop Low channel lookback
DonchianUpper =HHV(H,pdsU);
DonchianLower = LLV(L,pdsL);
DonchianStop = LLV(L,pdsS);
Plot(DonchianUpper,"DU",color = colorBlueGrey,styleDashed);
Plot(DonchianLower,"DL",color = colorBlueGrey, styleDashed);
Plot(DonchianStop,"DS",color = colorBlueGrey, styleDashed);
// ==========================================================================================
// === BUY & SELL LOGIC ===
// ==========================================================================================
Buy=Cross(High, Ref(DonchianUpper, -1));
BuyPrice=Max(Ref(DonchianUpper, -1), Open);
// === TRAILING STOP WITH JUST A SINGLE DONCHIAN CHANNEL ===
// Initialize variables
//Sell=0;
//trailArray = Null;
//trailStop = 0;
//Trailing stop logic
//for( i = 0; i < BarCount; i++ )
//{
// if( trailstop == 0 AND Buy[ i ] )
// {
// trailstop = BuyPrice[i] * (1- stopLoss/100);
// entryBar[i] = True;
// }
// else Buy[i] = 0; // remove excess buy signals
// if( trailstop > 0 AND Low[ i ] < trailstop AND entryBar[i] != True)
// {
// Sell[ i ] = 1;
// SellPrice[ i ] = Min( Open[ i ], trailstop );
// trailstop = 0;
// }
// if( trailstop > 0 )
// {
// trailStop = Max(DonchianLower[i], trailStop);
// trailARRAY[ i ] = trailstop;
// }
//}
// === NEW LOGIC TRYING TO MOVE TRAILING STOP TO LOOSER DONCHIAN LEVEL ===
// Initialize variables
Sell=0;
trailArray = Null;
trailStop = 0;
breakEvenLevel = 0;
breakEvenArray = Null;
buyLevel = 0;
// Trailing stop logic trying to do a tighter stop initially until in profit
for( i = 0; i < BarCount; i++ )
{
if( trailstop == 0 AND Buy[ i ] )
{
trailstop = BuyPrice[i] * (1- stopLoss/100);
entryBar[i] = True;
buyLevel = BuyPrice[i];
}
else Buy[i] = 0; // remove excess buy signals
if( trailstop > 0 AND Low[ i ] < trailstop AND entryBar[i] != True)
{
Sell[ i ] = 1;
SellPrice[ i ] = Min( Open[ i ], trailstop );
trailstop = 0;
Buy[i] = 0;
buyLevel = 0;
breakEvenLevel = 0;
}
if( trailstop > 0 ) // Goal is to first trail stop with max stop loss, then follow the tight DonchianStop level, then once in profit, follow DonchianLower level
{
if(DonchianStop[i] >= buyLevel)
{
breakEvenLevel = 340; // set this value to a price on the chart you can see to test out if the line plots correctly
//breakEvenLevel = ValueWhen(((DonchianStop[i] >= buyLevel[i]) AND (Ref(DonchianStop[i], -1) < Ref(BuyLevel[i], -1))), DonchianStop[i], 0);
//breakEvenLevel = DonchianStop[i]; // this breakeven level moves as the DC channel moves. Need to freeze it in at the moment it is true.
breakEvenArray[i] = breakEvenLevel[i];
}
trailStop = Max(DonchianStop[i], trailStop);
trailArray[ i ] = trailstop;
}
}
Plot(trailArray, "Trailing Stop Level", colorRed, styleThick);
Plot(breakEvenArray, "Break Even Level", colorBlue, styleThick);
// Hide buy and sell signals if in position so that it doesn't plot extra arrows - should not use for backtests
//Buy = ExRem(Buy,Sell);
//Sell = ExRem(Sell,Buy);
// Plot arrows indicating trades
PlotShapes(IIf(Buy, shapeUpTriangle, shapeNone),color = colorLime, 0, L, Offset=-50);
PlotShapes(IIf(Sell, shapeDownTriangle, shapeNone),color = colorRed, 0, H, Offset=-50);
// ==========================================================================================
// === EXPLORATION / SCANNING COLUMNS ===
// ==========================================================================================
Filter = 1;
AddTextColumn(FullName(), "Name");
AddColumn(Buy, "Buy Array");
AddColumn(entryBar, "BarsSince Buy", 1);