How can I code TOS to only trade the first leg of a trend?

B

billgt

New member
VIP
I have a strategy that takes a trade when a MACd, Stoch, and RSI are at certain levels. It takes profit when either an ATR move is hit or the indicators say the trend is over. The problem occurs when the ATR target is hit in the middle of an up trend. The signals are still saying that we can trade and so as soon as we exit another trade is entered. I don't want to trade again until the signals say there is no trade to take and then go back to saying there is again. Effectively what this will do is only trade the first leg of a trend if we reach a profit target and then wait for the trend to end or take a break before we look to trade again in either direction.

If I was going to write this code in TradingView or C# or any other language I would do the following. I will simplify it to just use MACD for now and assume some of the logic for the signals is already in another part of the code not shown here. I think it should be clear.

What I can't figure out how to do is to have a flag (LongPossible) that will prevent long entries from happening once we have entered and exited the current trend using an ATR move until it ends when MACD no longer signals we are trending. I am sure there is a way to do it but I can't find a concept of a persistent variable like in TradingView or other languages and I can't seem to come up with a statement for long entry that will work.

I feel sure someone has run into an issue like this in the past and can give me a snippet of code that made something like this work??

Thanks!

Bill

Code:
var LongPossible = true
var longEntry = false

if MACDSignalUp and LongPossible
{
    longEntry = true
    longPossible = false
    longTarget = close + ATR()
    //Enter long trade
}

if longTarget
{
    //ExitLongTrade
}

if (MACDSignalDown)
{
   LongPossible = true
}
 
B

billgt

New member
VIP
I figured this out myself. Thanks to anyone who took a look. Here is the snippet of code I used for anyone who needs something like this in the future. The main trick was figuring out how to set the logic of the flag a bar before and then referencing the previous value of that flag when making the final long entry decision.

Thanks!

Code:
def longEntryLogic = if greenBar[1] and high >= longEntryPrice and greenBar then yes else no;

def longPossible = if greenBar and !greenBar[1] then yes else if longEntryLogic then no else longPossible[1];

def longEntry = longEntryLogic and longPossible[1];
 

Similar threads

Top