Chris
Chris

Reputation: 3269

Removing Complex Recursion in Thinkscript to Pinescript Conversion

I have the following block of code from a longer Thinkscript file that I'm struggling to convert to Pinescript since, as I understand, Pinescript does not support recursion. What makes this conversion challenging in my view is the interdependence between the variables state, trail, and mclose. Does anyone have suggestions on how to cast this into Pinescript?

def state = {default init, long, short};
def trail;
def mclose;
switch (state[1]) {
case init:
   if (!IsNaN(loss)) {
      switch (firstTrade) { 
      case long:
         state = state.long; 
         mclose = close; 
         trail = close - loss;
      case short:
         state = state.short; 
         mclose = close; 
         trail = close + loss;
   }
} else {
   state = state.init;
   trail = Double.NaN; 
   mclose = Double.NaN;
}
case long:
   if (close > trail[1]) {
      state = state.long;
      mclose = Max(mclose[1], close); 
      trail = Max (trail[1], mclose - loss);
   } else {
      state = state.short; 
      mclose = close;
      trail = mclose + loss; 
   }
case short:
   if (close < trail[1]) {
      state = state.short;
      mclose = Min(mclose[1], close); 
      trail = Min(trail[1], mclose + loss);
   } else {
      state = state.long; 
      mclose = close; 
      trail = mclose - loss;
   } 
}

Upvotes: 0

Views: 76

Answers (1)

Chris
Chris

Reputation: 3269

It turns out in the end that not much was required to get it to work in Pinescript. No need for iteration via a for loop. The := operator is key.

string state  = "init"
float  mclose = na
float  trail  = na

if state[1] == "init"
    if not na(loss)
        if first_trade == "long"
            state  := "long"
            mclose := close
            trail  := close - loss
        else // first_trade = "short"
            state  := "short"
            mclose := close
            trail  := close + loss
    else
        state  := "init"
        trail  := na
        mclose := na
else if state[1] == "long"
    if close > trail[1]
        state  := "long"
        mclose := math.max(mclose[1],close)
        trail  := math.max(trail[1],mclose-loss)
    else
        state  := "short"
        mclose := close
        trail  := mclose + loss
else if state[1] == "short"
    if close < trail[1]
        state  := "short"
        mclose := math.min(mclose[1],close)
        trail  := math.min(trail[1],mclose+loss)
    else
        state  := "long"
        mclose := close
        trail  := mclose - loss

Upvotes: 0

Related Questions