- ago
I'm trying to set a conditional flag called "SPYunderperf" to true in one conditional statement that will remain available and valid in another conditional statement shortly after it, but it keeps resetting to false. I've declared the flag as a bool along with others in the block after the Execute loop (and these other bools all seem to persist without issue) as:

CODE:
private bool SPYunderperf = false;


The first block in which I set the "SPYunderperf " flag to true is here:

CODE:
   //exit TLT trade on EOM          if (bars.Symbol == "TLT")          {             if (isLastTradingDayOfMonth && tltLong)             {                PlaceTrade(bars, TransactionType.Sell, OrderType.MarketClose, 0, "EOM").PositionTag = 2;                tltLong = false;                SPYunderperf = true;                DateTime dt2 = bars.DateTimes[idx];                WriteToDebugLog(dt2 + " SPY underperformance 1 is " + SPYunderperf);             }          }


And the second block (which immediately suceeds the preceding block in the Execute loop) is here:

CODE:
         //SPY SOM trade          if (bars.Symbol == "SPY")          {                      if (isLastTradingDayOfMonth)             {                DateTime dt3 = bars.DateTimes[idx];                   WriteToDebugLog(dt3 + "SPY underperformance 2 is " + SPYunderperf);                if (SPYunderperf)                {                   PlaceTrade(bars, TransactionType.Buy, OrderType.MarketClose, 0, "SPY SOM").PositionTag = 4;                   //SPYunderperf = false;                   spyLong = true;                }             }          }


...but while the first the WriteToDebugLog output shows the flag is correctly setting to true, the second shows that it has reset to false by the time it is executed,

Any pointers as to what I am doing wrong gratefully received. Thx
0
287
Solved
9 Replies

Reply

Bookmark

Sort
Cone8
 ( 6.07% )
- ago
#1
A strategy class instance is created for each symbol in "Backtester.Symbols". Consequently, each has its own copy of private variables.

If you want to share a variable between those instances, declare it static.
CODE:
static bool SPYunderperf= false;
However, since you cannot count on the order that symbols run their Execute(), you should make your static variable assignment in Pre or PostExecute() so that it's available to all symbols on the next Execute() index.

More info in this blog -
https://www.wealth-lab.com/blog/anatomy-of-a-wl7-strategy
0
Best Answer
- ago
#2
Thanks - v helpful. The script currently doesn't use PreExecute() or PostExecute() (it just has an Initialize()). Can I just add one or other of those methods to declare this variable within?
0
Cone8
 ( 6.07% )
- ago
#3
QUOTE:
The script currently doesn't use PreExecute() or PostExecute() (it just has an Initialize()).
These are virtual methods that you override with your implementation.

QUOTE:
Can I just add one or other of those methods to declare this variable within?
No. The scope is local to the class. You can see an example of declaring static variables in the link provided.

You'll have to work a bit to get the BarHistory context to assign the value there too. Give me a minute and I'll look at what you're trying to do again...
0
- ago
#4
Thx
0
Cone8
 ( 6.07% )
- ago
#5
Just an example below trying to follow your logic for Position tagging and what not. You really don't need to do that tagging or keep your own trade of "tltlong" etc. This is known by the context of the BarHistory and Position objects in OpenPositions and GetPositions(), etc. If there's only one long Position per symbol, you can follow the template code without using tags at all.

I moved the TLT exit into PreExecute, because it just make sense there. You're code was using an open position in TLT and the last day of the month to assign true to SPYunderperf anyway. (You're code snippets are kind of a mess.)

CODE:
using WealthLab.Backtest; using System; using WealthLab.Core; using WealthLab.Data; using WealthLab.Indicators; using System.Collections.Generic; namespace WealthScript1 { public class MyStrategy : UserStrategyBase {       // let's put them here to easily see they're at the class level       private static bool SPYunderperf = false;       private static bool isLastTradingDayOfMonth = false;              public override void Initialize(BarHistory bars) {        } public override void Execute(BarHistory bars, int idx) {    if (!HasOpenPosition(bars, PositionType.Long))    {             // entry logic             if (bars.Symbol == "SPY")             {                if (isLastTradingDayOfMonth)                {                   DateTime dt3 = bars.DateTimes[idx];                   WriteToDebugLog(dt3 + "SPY underperformance 2 is " + SPYunderperf);                   if (SPYunderperf)                   {                      PlaceTrade(bars, TransactionType.Buy, OrderType.MarketClose, 0, "SPY SOM").PositionTag = 4;                   }                }             }             else             {                // TLT entry logic here             } } else {                // other exit logic }          }       public override void PreExecute(DateTime dt, List<BarHistory> participants)       {          SPYunderperf = false;          int currentIdx = GetCurrentIndex(participants[0]);          isLastTradingDayOfMonth = participants[0].IsLastTradingDayOfMonth(currentIdx);          if (isLastTradingDayOfMonth)             foreach (Position pos in OpenPositionsAllSymbols)             {                if (pos.Symbol == "TLT")                   {                   SPYunderperf = true;                                      // you can just close this open TLT position it right here                   ClosePosition(pos, OrderType.MarketClose, 0, "EOM");                   break;                }             }       }    } }
0
- ago
#6
Sorry - I should have mentioned earlier that I'm adjusting a script from Glitch and the tltlong etc is his code.

I'm basically trying set an new tag that captures the relative performance of SPY versus TLT up to the fifteenth trading day of the month (Glitch has already done the code for the comparison and I just want to add the flag based on the output).

If SPY outperforms up to the 15th TDM, then there's a long TLT position until the last trading day of the month (Glitch already did this bit) and the new flag will be set to true. What I'm trying add based on this new flag is that if it is true then as the TLT trade exits on the the last trading day of the month then a new SPY position is opened, which is then closed on the fifth trading day of the following month.
0
Cone8
 ( 6.07% )
- ago
#7
Context is everything. I gave you as good as example as I could with those snippets and what I thought you were trying to do. Good luck!
0
- ago
#8
Hell really sorry - I should have DM'd you to explain but I couldn't just post the whole code as it's proprietary to a group I belong to.
0
- ago
#9
Fair enough
0

Reply

Bookmark

Sort