Glitch8
 ( 11.20% )
- ago
I was asked on Discord a question about the new WL8 sample Strategy, and I wanted to post the response here so it's recorded in the forum.

>>What is the general buying and selling theories.<<
It's trying to squeeze one percent during the week out of the triple leveraged TQQQ, taking advantage of the volatility of that ETF.

>>Also since it is run on a daily basis but not intraday, Do the signals buy and sell come during the day on a streaming data or is it a signal for the following day ?<<
Because of the way it's coded, it doesn't generate signals like most Strategies, so for now it's a manual effort to trade, but the rules are simple:

- On the first trading day of the week, observe the open price of TQQQ right at the open and enter a limit order to buy 1% below that price.
- After the close, enter a limit order to sell at 1% above the position entry price.
- At any point during the week, after the market closes, If the open position is sitting at a loss of -0.5% or more, make the limit exit price equal to the entry price (for an attempted breakeven result.)
- At the end of the week, if the position is still open, sell it at market close, so it doesn't hold over the weekend.

3
8,814
104 Replies

Reply

Bookmark

Sort
- ago
#1
I don't see that day strategy in the Sample folder. Is it supposed to be there?
0
Glitch8
 ( 11.20% )
- ago
#2
Yes, are you running the latest WL8 build?

0
- ago
#3
Hi Glitch. So since it doesn't produce signals its algorithm is intended for backtesting and by now it should be trade entirely manually. Wright?
0
Glitch8
 ( 11.20% )
- ago
#4
Yes that’s the idea. But I think we can, in a future release, add a new override that can respond to market open and allow a strategy like this to be automated.
1
- ago
#5
I am trying to achieve a similar strategy based on blocks but I think I am missing something, probably the SL placement, I don't know why.
0
- ago
#6
Maybe you can help me to identify what is missing, why I can not get good results as with the original back tested One Percent C-coded strategy, even though it's intended to follow the idea.


0
- ago
#7
I've tried also replacing the SL for a Profit Taking of 0%
0
Glitch8
 ( 11.20% )
- ago
#8
The coded strategy places the order one percent below the open price on Monday, the execution day. This isn’t possible using blocks.

The block strategy places a limit order one percent below the open price of Friday, to be executed on Monday.
1
- ago
#9
Thank you @Glitch for this sample code. It is educational about WL8 functions and thought-provoking.

I believe you may have a typo in your code based on your narrative description of the strategy.

Shouldn't
CODE:
            double target = LastOpenPosition.EntryPrice;             if (LastOpenPosition.ProfitAsOf(idx) > -0.5)


Be
CODE:
            double target = LastOpenPosition.EntryPrice;             if (LastOpenPosition.ProfitPctAsOf(idx) > -0.5)


?
1
Glitch8
 ( 11.20% )
- ago
#10
Yes, good catch, and changing it to what I intended actually bumped the APR up a couple of percent!
0
- ago
#11
I do have a few questions. On day 2 (Tuesday) it places a limit trade either at a profit target or breakeven, depending on profit at that bar. Will it sell on that bar if either limit is reached, or only if the limit is reached on the next bar, Wednesday? A related question is if a Sell.MarketClose order was also added if the Profit pct< 0.5 would it execute on Tuesday or Wednesday?

I suspect this is a basic question and I know the rule is orders are processed on the next bar. I think the answer is Wednesday for both. I'm getting a little confused because I have been looking into the method AssignAutoStopTargetPrices, which it appears you use in the sample code only to set a flag. My understanding is that limits or stops placed inside this method *will* execute on the same bar, both by broker and backtest.

Any thoughts of adding Sell.CloseAtMarket as a method in AssignAutoStopTargetPrices to allow closing position on same bar?

Also, is ProfitPctAsOf calculated at the close or open of the current bar? If the answer is close, it would be too late to place a Close-at-Market trade for the current day.
0
Glitch8
 ( 11.20% )
- ago
#12
I do have a few questions. On day 2 (Tuesday) it places a limit trade either at a profit target or breakeven, depending on profit at that bar. Will it sell on that bar if either limit is reached, or only if the limit is reached on the next bar, Wednesday?<<

Besides the special logic of "peeking ahead" at the open price of Monday, it's a normal strategy. It looks at the profit percent at the end of the day, and places the appropriate order for the following day.

>>A related question is if a Sell.MarketClose order was also added if the Profit pct< 0.5 would it execute on Tuesday or Wednesday?<<

It would execute on the day following whatever day the target was reached.

>>I suspect this is a basic question and I know the rule is orders are processed on the next bar. I think the answer is Wednesday for both. I'm getting a little confused because I have been looking into the method AssignAutoStopTargetPrices, which it appears you use in the sample code only to set a flag. My understanding is that limits or stops placed inside this method *will* execute on the same bar, both by broker and backtest.<<

Yes but this strategy does not employ same-bar exits. The first exit order is calculated after market close of Monday and placed for Tuesday.

>>Any thoughts of adding Sell.CloseAtMarket as a method in AssignAutoStopTargetPrices to allow closing position on same bar?<<

If you want to exit at market close on the same bar you can call PlaceTrade with a Sell of MarketClose right after your PlaceTrade Buy statement. You needn't do it in AssignAutoStop.

>>Also, is ProfitPctAsOf calculated at the close or open of the current bar? If the answer is close, it would be too late to place a Close-at-Market trade for the current day.<<

It's calculated based on the closing price. But the exit order is placed for execution on the following bar.
0
- ago
#13
Thanks for the answers. Getting clearer. One clarification:

QUOTE:
The first exit order is calculated after market close of Monday and placed for Tuesday.

Do you mean the first exit order is calculated after market close on Tuesday and placed for Wednesday?

The logic is that the calculation occurs in

CODE:
         if (HasOpenPosition(bars, PositionType.Long))          { ...... }

which wouldn't be processed until Tuesday when the position executed on Monday is detected, right?

0
Glitch8
 ( 11.20% )
- ago
#14
No, check the position list. The entry trades are filled on Mondays. The system places them after market close on Friday.

The first exit is calculated after the end of day Monday and is placed Tuesday.
0
Glitch8
 ( 11.20% )
- ago
#15
With today's exit at open it notched a 2.15% gain for the week. The rest of the week can be spent relaxing :)
4
- ago
#16
Is there a way to code this to look at either TQQQ or SQQQ to play both long and short volatility. Backtesting holding TQQQ out performs this strategy, but possibly playing both short and long may be able to beat long term holding of TQQQ? It's just hypothetical question right now.
0
Cone8
 ( 7.84% )
- ago
#17
QUOTE:
Backtesting holding TQQQ out performs this strategy
Not if you started any time in the last 5 or 6 years. But sure, triple return from nearly the beginning of a historic bull market, that's tough (impossible?) to beat.
0
- ago
#18
QUOTE:
Because of the way it's coded, it doesn't generate signals like most Strategies

Would you please explain why this strategy doesn't generate signals. It wouldn't generate a signal on Monday either? Does it have something to do with peeking?
0
Glitch8
 ( 11.20% )
- ago
#19
It will not generate a signal because it peeks ahead one bar to look at Monday’s open price. You place a buy limit order one percent below the open price on Monday.
0
Cone8
 ( 7.84% )
- ago
#20
Here's a version that can give you a Signal for all days except Monday.

CODE:
using WealthLab.Backtest; using System; using WealthLab.Core; using WealthLab.Indicators; using System.Collections.Generic; namespace WealthScript1 { public class MyStrategy : UserStrategyBase { //create indicators and other objects here, this is executed prior to the main trading loop public override void Initialize(BarHistory bars) { } //execute the strategy rules here, this is executed once for each bar in the backtest history public override void Execute(BarHistory bars, int idx) {          bool isNextBarStartOfWeek = _lastBarofWeek == idx;          bool isNextBarLastDayOfWeek = bars.TomorrowIsLastTradingDayOfWeek(idx);          if (isNextBarLastDayOfWeek)             _lastBarofWeek = idx + 1;          if (isNextBarStartOfWeek)          SetBackgroundColor(bars, idx + 1, WLColor.Silver.SetAlpha(32));          if (isNextBarStartOfWeek)          {             if (idx >= bars.Count - 1)                return;             mondayOpen = bars.Open[idx + 1];             tradedThisWeek = false;          }          if (HasOpenPosition(bars, PositionType.Long))          {          double target = LastOpenPosition.EntryPrice;          if (LastOpenPosition.ProfitPctAsOf(idx) > -0.5)                target = target * 1.01;             PlaceTrade(bars, TransactionType.Sell, OrderType.Limit, target);             if (isNextBarLastDayOfWeek)             {                PlaceTrade(bars, TransactionType.Sell, OrderType.MarketClose);             }          }          else          {             if (!Double.IsNaN(mondayOpen) && !tradedThisWeek)             {                double mult = 0.99;                PlaceTrade(bars, TransactionType.Buy, OrderType.Limit, mondayOpen * mult);                if (isNextBarLastDayOfWeek)                {                   PlaceTrade(bars, TransactionType.Sell, OrderType.MarketClose);                }             }          } }       //same bar exit public override void AssignAutoStopTargetPrices(Transaction t, double basisPrice, double executionPrice) {          //t.AutoProfitTargetPrice = executionPrice * 1.01;          tradedThisWeek = true; } //declare private variables below private double mondayOpen = Double.NaN;       bool tradedThisWeek = false;       int _lastBarofWeek = -1; } }
0
- ago
#21
This is a good strategy!
0
- ago
#22
QUOTE:
It will not generate a signal because it peeks ahead one bar to look at Monday’s open price.

Yes, makes complete sense for real-world simulation.
0
- ago
#23
QUOTE:
Here's a version that can give you a Signal for all days except Monday.

Thank you for that @Cone
0
Cone8
 ( 7.84% )
- ago
#24
It's Monday and you know what that means!

Consider this your signal for today :)

Edit - If you wanted to Auto-Place the order on Monday, just use this script on 1-minute bars in the Strategy Monitor. It's only job is to place a limit order "Monday today" after the first bar ends at 99% of the opening price.

CODE:
See revision in Post #43
0
- ago
#25
This question is perhaps very basic, but important. I was live monitoring market data and TQQQ opened 33,65 at 09:30, but when looking at Morningstar it says Open=33.14, what open shoould I take in order to be aligned with the backtested strategy? Is it RTH open or Pre-market open?

Thank you in advance.
0
Cone8
 ( 7.84% )
- ago
#26
RTH open.
1
Glitch8
 ( 11.20% )
- ago
#27
And don’t be afraid, like I did today, to exit early. In this market it’s never a bad call to take some profits!
2
- ago
#28
Indeed, also I am trading covered calls
0
- ago
#29
Hi I have a question regarding this strategy > Say if i a buy the TQQQ 1% below the open, and the TQQQ hits 1% on the same day am i selling according to the strategy rules OR am i selling on Tuesday at the open ?

I noticied on the backtesting in WL , that the selling occured the following day. Just want to clarify the sale . Many thanks for your time
0
Cone8
 ( 7.84% )
- ago
#30
The strategy isn't programmed to make a same-bar exit, and it would be unrealistic to do that using only Daily bars.

If you want to trade the way the strategy backtests, then you hold and submit the limit order GTC, regular session, after today's close. If it doesn't hit by the end of the week, then you sell MOC on Friday.
1
- ago
#31
Thank you Cone
1
- ago
#32
How could I alter this code for this a weighted strategy to only submit a limit order for the lower rsi between SQQQ and TQQQ if I made those two their own dataset?
0
Cone8
 ( 7.84% )
- ago
#33
You're not going to like the results, but at least you backtested it and found it to be far worse ;)

Run in Single symbol mode on TQQQ. SQQQ is hard-coded as the secondary symbol.

CODE:
using WealthLab.Backtest; using System; using WealthLab.Core; using WealthLab.Indicators; using System.Collections.Generic; namespace WealthScript6 { public class MyStrategy : UserStrategyBase { //create indicators and other objects here, this is executed prior to the main trading loop public override void Initialize(BarHistory bars) {          // assumes run on TQQQ          _rsiT = RSI.Series(bars.Close, 14);          _sqqq = GetHistory(bars, "SQQQ");          PlotBarHistory(_sqqq, "SQQQ");                    _rsiS = RSI.Series(_sqqq.Close, 14);          _tradeBars = bars; } //execute the strategy rules here, this is executed once for each bar in the backtest history public override void Execute(BarHistory bars, int idx) {          bool isNextBarStartOfWeek = _lastBarofWeek == idx;          bool isNextBarLastDayOfWeek = bars.TomorrowIsLastTradingDayOfWeek(idx);          if (isNextBarLastDayOfWeek)             _lastBarofWeek = idx + 1;          if (isNextBarStartOfWeek)          SetBackgroundColor(bars, idx + 1, WLColor.Silver.SetAlpha(32));          if (isNextBarStartOfWeek)          {             if (idx >= bars.Count - 1)                return;             _tradeBars = _rsiT[idx] < _rsiS[idx] ? bars : _sqqq;             mondayOpen = _tradeBars.Open[idx + 1];             tradedThisWeek = false;          }          Position pos = FindOpenPositionAllSymbols(42);          if (pos != null)          {             double target = pos.EntryPrice;             if (pos.ProfitPctAsOf(idx) > -0.5)                target = target * 1.01;             PlaceTrade(_tradeBars, TransactionType.Sell, OrderType.Limit, target);             if (isNextBarLastDayOfWeek)             {                PlaceTrade(_tradeBars, TransactionType.Sell, OrderType.MarketClose);             }          }          else          {                if (!Double.IsNaN(mondayOpen) && !tradedThisWeek)             {                double mult = 0.99;                PlaceTrade(_tradeBars, TransactionType.Buy, OrderType.Limit, mondayOpen * mult, 42);                if (isNextBarLastDayOfWeek)                {                   PlaceTrade(_tradeBars, TransactionType.Sell, OrderType.MarketClose);                }             }          } }       //same bar exit public override void AssignAutoStopTargetPrices(Transaction t, double basisPrice, double executionPrice) {          //t.AutoProfitTargetPrice = executionPrice * 1.01;          tradedThisWeek = true; } //declare private variables below private double mondayOpen = Double.NaN;       bool tradedThisWeek = false;       int _lastBarofWeek = -1;       RSI _rsiT;       RSI _rsiS;       BarHistory _sqqq;       BarHistory _tradeBars; } }
1
- ago
#34
Thanks cone, was worth a shot to backtest it and rule it out!
0
- ago
#35
Can the method TomorrowIsLastTradingDayOfWeek() be used for real-time trading in addition to backtest? That is, does this function require "peeking" or does it use a source outside the history bars to generate its bool value?
0
Cone8
 ( 7.84% )
- ago
#36
Yes, it can be used. It uses real-world date rules, which isn't "peeking" in the backtesting sense.
0
- ago
#37
Thank you for confirming
0
- ago
#38
Any updates on integrating signals for automation?
0
Cone8
 ( 7.84% )
- ago
#39
@micahwhite02 -
Can you give your question a little context? I not even sure if you're referring to this system specifically. What are you looking for precisely?"
0
- ago
#40
Sorry @Cone, let me rephrase my question.

I saw you wrote code that implements signals for this strategy (forum message #20). I backtested your code and only got one signal. Am I doing something wrong? I gave the backtest a 3 year time frame.
0
Cone8
 ( 7.84% )
- ago
#41
There will never be more than 1 Signal (Alert).

Do you mean that you only got one trade showing in Backtest Results > Positions?
If so, show your Strategy Settings - the answer why is probably there.
1
- ago
#42
Have you guys had luck with the Monday Open code on Message #24? I set it up for Monday, February 27 (yesterday) in the strategy monitor and it did not execute a buy limit signal.

I will say that I just recognized that my backtest settings for the Monday script were set at a Daily refresh rate, but I am not sure if that would affect it's ability to perform on the strategy monitor.
0
Cone8
 ( 7.84% )
- ago
#43
Reviewing it, that script needs a revision. The problem is that it will create a signal only at the end of the first bar of the day.. but then will remove the signal on all following bars. Instead, this script will keep the signal active in an intraday (streaming or polling) chart until price reaches the limit price.

You can test it any day of the week by changing DayOfWeek.Monday to the current DayOfWeek (DayOfWeek.Wednesday today).

CODE:
/* Entry only script for 1% down on Mondays - USE WITH 1-MINUTE INTRADAY BARS */ using WealthLab.Backtest; using System; using WealthLab.Core; namespace WealthScript12 {    public class BuyOnePercentDownFromOpenOnMonday : UserStrategyBase    {       public override void Initialize(BarHistory bars)       {          PlotStopsAndLimits(3);       }       public override void Execute(BarHistory bars, int idx)       {          if (bars.DateTimes[idx].Date != today || bars.DateTimes[idx].DayOfWeek != DayOfWeek.Monday)             return;          // Ensure Filter Pre/Post Market Data is checked!          if (!HasOpenPosition(bars, PositionType.Long))          {             int firstBarToday = idx - bars.IntradayBarNumber(idx);             PlaceTrade(bars, TransactionType.Buy, OrderType.Limit, bars.Open[firstBarToday] * 0.99);          }       }       DateTime today = DateTime.Now.Date;    } }
0
Cone8
 ( 7.84% )
- ago
#45
The idea is to run that on 1-minute bars on Mondays to enter the trade only.
0
Glitch8
 ( 11.20% )
- ago
#46
Ok but then you’re getting in one minute late. It’s better to just trade it manually, quickly observing the open price and making the calculation.
0
Cone8
 ( 7.84% )
- ago
#47
True. There's a tiny risk that TQQQ can open, drop 1% and rise again within the first 1 minute, never to return 1% below the open for the day. If you use this automated strategy, you will miss that trade.

This scenario has happened 4 times since TQQQ was created - 2 of them were the first day of the week. These are those dates -

5/21/2010 (Friday)
9/30/2013 (Monday)
1/27/2020 (Monday)
4/14/2020 (Tuesday)
0
Cone8
 ( 7.84% )
- ago
#48
Two important points -

1. If you use the intraday script, it's set up for Monday only. If there is no entry on Monday, or even if there is, use the regular Daily strategy script for the rest of the week for entry and/or exit signals.

2. Here's how to use the 1-min entry script and get the signal active on the very first bar. First recognize that TQQQ is actively traded, and there is only 1 trade difference between the close of the 0930 pre-market bar and the open of the session. 65% of the time since 2006, these prices are within 1 penny (tested split adjusted prices). And these days, it's unlikely for these prices to be different by more than 2 pennies.

To get the trade going immediately using the close of the last pre market bar, set up TQQQ in a US Market clone that starts at 09:29. The first bar will end at 0930 and the script below will signal the order immediately, but after the first minute it will correct to the actual opening price, if required.

CODE:
/* Entry only script for 1% down on Mondays - USE WITH 1-MINUTE INTRADAY BARS */ /* Assign TQQQ to a market that opens at 09:29 EST */ using WealthLab.Backtest; using System; using WealthLab.Core; namespace WealthScript5 {    public class BuyOnePercentDownFromOpenOnMonday : UserStrategyBase    {       public override void Initialize(BarHistory bars)       {          PlotStopsAndLimits(3);       }       public override void Execute(BarHistory bars, int idx)       {          if (bars.DateTimes[idx].Date != today || bars.DateTimes[idx].DayOfWeek != DayOfWeek.Monday)             return;          // Ensure Filter Pre/Post Market Data is checked!          if (!HasOpenPosition(bars, PositionType.Long))          {             int firstBarToday = idx - bars.IntradayBarNumber(idx);             if (bars.DateTimes[firstBarToday].TimeOfDay == ts0930)             {                // the first bar was the premarket bar ending at 0930.                // if the current bar doesn't equal firstBarToday, add one bar                if (idx > firstBarToday)                   firstBarToday += 1;                             _limit = bars.Close[firstBarToday] * 0.99;             }             else             {                _limit = bars.Open[firstBarToday] * 0.99;             }             PlaceTrade(bars, TransactionType.Buy, OrderType.Limit, _limit);          }       }       DateTime today = DateTime.Now.Date;       TimeSpan ts0930 = new TimeSpan(9, 30, 0);       double _limit = 0;    } }
0
Cone8
 ( 7.84% )
- ago
#49
After testing this today, I realized that the [previous] code was using the Open instead of the Close for the last premarket bar. It's correct now.
0
- ago
#50
Hi,
I'm using the OnePercentAWeek Strategy. Do I need to use a streaming provider? If so, can I you Yahoo Finance? Also, did you mean the Data Manager instead of the Strategy Monitor in your last post? I setup the data manager/historical data to use QData which appears to be free. I have no streaming data setup. So should I expect the results to be realistic?
0
Cone8
 ( 7.84% )
- ago
#51
QUOTE:
Do I need to use a streaming provider?
No. It's very simple to trade, but you do need to determine the opening price for the week as fast as possible. Certainly you can do this in realtime with any broker.

It's off topic, but to trade 1%...
1. Immediately look at TQQQ's opening price for the week. Multiply it by 0.99 and place a GTC limit order at that price.

2. If you are filled, after the session closes...
If your position is losing more than 0.5% at any session close, place a GTC limit order at your entry price. Otherwise, multiply the entry price by 1.01 and place a GTC sell limit order. All orders should be active only for the regular session.

3. If the position is still open at the end of the week, cancel the GTC order and sell your position at "Friday's" close.
2
- ago
#52
Can I setup this strategy to AutoTrade? I believe that answer is yes. Correct me if I'm wrong.
0
Cone8
 ( 7.84% )
- ago
#53
Here's another iteration that takes into account holidays so that the script will signal on any day of the week as long as it's the first session of the week AND "today". That way you can put it in the Strategy Monitor an let it run every day without worry. (Remember, you still need to use the Daily script for signaling each day after the first session.)

CODE:
/* Entry only script for 1% down on the first session of the week - USE WITH 1-MINUTE INTRADAY BARS */ /* Assign TQQQ to a Market that opens at 09:29 EST (Tools > Markets & Symbols) */ using WealthLab.Backtest; using System; using WealthLab.Core; namespace WealthScript1 {    public class BuyOnePercentDownFromOpenOnMonday : UserStrategyBase    {       public override void Initialize(BarHistory bars)       {          PlotStopsAndLimits(3);       }       public override void Execute(BarHistory bars, int idx)       {          if (!TodayIsFirstSessionOfTheWeek(bars, bars.DateTimes[idx]) || bars.DateTimes[idx].Date != DateTime.Now.Date)          {             SetBackgroundColor(bars, idx, WLColor.FromArgb(40, WLColor.Red));             return;          }          // Ensure Filter Pre/Post Market Data is checked!          if (!HasOpenPosition(bars, PositionType.Long))          {             int firstBarToday = idx - bars.IntradayBarNumber(idx);             if (bars.DateTimes[firstBarToday].TimeOfDay == ts0930)      // the first bar was the premarket bar ending at 0930             {                               if (idx > firstBarToday)                {                   _limit = bars.Open[firstBarToday + 1] * 0.99;                }                else                {                   // use the close of the last premarket bar                   _limit = bars.Close[firstBarToday] * 0.99;                }             }             else                                           // the first bar was not a premarket bar                _limit = bars.Open[firstBarToday] * 0.99;                         PlaceTrade(bars, TransactionType.Buy, OrderType.Limit, _limit);          }                }       // pass the current date to check with the bars       public bool TodayIsFirstSessionOfTheWeek(BarHistory bars, DateTime dte)       {          if (!bars.Market.IsTradingDay(dte.Date))             return false;                    DayOfWeek dow = dte.DayOfWeek;          do          {             dte = dte.AddDays(-1);                         if (bars.Market.IsTradingDay(dte.Date))                         return dow < dte.DayOfWeek;                       }          while (dte.Year > 1900);          return false;       }       DateTime today = DateTime.Now.Date;       TimeSpan ts0930 = new TimeSpan(9, 30, 0);       double _limit = 0;       bool _todayIsFirstSessionOfTheWeek;    } }
0
Glitch8
 ( 11.20% )
- ago
#54
Actually you can’t, it relies on looking at the market open so you’ll need to do it manually.

Cone is doing a more automated version but he converted it into an intraday strategy and it’s subjected to potentially missing a signal due to a one minute delay.
0
Cone8
 ( 7.84% )
- ago
#55
The last solution that I posted won't miss, though it's possible the order price during the first minute is off by a penny or two. The solution involves creating a special US Market for TQQQ that opens at 9:29. This way the script can use the last premarket close to estimate the limit order until 0931, at which time it can be corrected if you're not already filled.
0
- ago
#56
How would you create a special US Market for TQQQ within Wealth-Labs?
0
Cone8
 ( 7.84% )
- ago
#57
Here's how, illustrated -
https://wealth-lab.com/Discussion/How-to-Create-a-Special-Market-9415
0
Cone8
 ( 7.84% )
- ago
#59
I updated the "09:30" market time entry script in Post #53. There were some problems with the previous version. For example, if you had loaded too much data, the strategy may enter a trade in a previous week and leave you without a signal for "today". Now, the strategy will trade only if the first day of the week is "today".
0
- ago
#61
Thank you for your contribution. I'm wondering, is there some simple way of using this One Percent per week strategy for live trading?

I've been trying to change the c# code to look at the pre-market for TQQQ at 9:29 which I believe I have to switch from "daily" data to "1-minute" data. I can get the the 1-1-minute data but I'm not getting anywhere.

If there is anyone who can help me a little, I'd appreciate it.
0
Cone8
 ( 7.84% )
- ago
#62
The idea is to Auto-Trade the Strategy in Post #53 with 1-minute TQQQ streaming bars, AND, TQQQ must be assigned to a market that opens at 09:29. This is ONLY for the entry on the first day of the week. After that you use the Daily strategy for signals.

After you follow the instructions linked in Post #57, the first thing to do is to see if the first bar each day in your 1-minute TQQQ chart has a timestamp of 09:30 (the close of the last premarket bar).
1
- ago
#63
Ok. Thank you. I've tried this but how do I switch from 1-minute data to daily data? This may seem like a dumb question but do I treat #53 and the one percent strategy separately or should it be integrated into the one percent strategy?
0
Cone8
 ( 7.84% )
- ago
#64
1. Let's be clear that you don't need 1 minute data at all to test or trade the strategy. The instructions to trade are in the strategy's Description.

2. If you want to automate (Auto-Trade) the entry on the first day of the week, then you need a 1-minute streaming chart with the "entry only" strategy above and an integrated broker. This gets you into the position on the first day of the week only.

3. After that you can just run the Daily strategy at night for the signals the next day. Send those signals to your broker (if you want to, of course).

4. On Friday afternoon, if you're still holding a position, you need to sell it before the close.

Which point isn't clear?
1
- ago
#65
I get it. Thank you very much.
1
- ago
#66
Hi.
Does it make any difference if I run both of these strategies previously stated (Monday Only and Daily) in a Chart or Strategies Monitor?
Thanks,
Mike
0
Cone8
 ( 7.84% )
- ago
#67
No difference.
1
- ago
#68
I was re-reading #64. Is there an easy way to automate steps 3 & 4?
0
- ago
#69
Hi @mas429 Cone's suggestion is to create a daily strategy to complement the one minute strategy he suggested for automating entry. By definition, that would automate the closing of the position, on the next day after you run the daily strategy. Your daily strategy would have to include the position close rules, which would include closing the position on Friday if your strategy does not generate a sell signal (which Glitch's original strategy posting does) before then. You can automate these signals or the actual trade if you connect the strategy to a broker and enable auto-trade.

The idea (of Glitch's strategy goal) is not to hold the position over the weekend, likely to reduce the risk of a large gap down opening on Monday based on what news could emerge while market is closed over the weekend. (Actually, the idea is to sell on the last trading day of week, not just Friday. E.g., last week last trading day was Thursday, and this strategy should have sold on Thursday last week, if not sooner.)

There is a built-in property in Wealth-Lab bars that detects last trading day of the week to help you automate, as in the following:
CODE:
         bool isNextBarLastDayOfWeek = bars.TomorrowIsLastTradingDayOfWeek(idx);


0
- ago
#70
Hi @innertrader. Thank you for response.

QUOTE:

Cone's suggestion is to create a daily strategy to complement the one minute strategy he suggested for automating entry


From my understanding, the daily strategy is the OnePercentAWeek strategy that comes with WL8 which I’ve setup to run after the market closes each day.
I had setup the one minute strategy to run this morning(first trading day of the week)at 9:30 EST in this strategy monitor but I believe the status message stated it was incomplete, so it never bought TQQQ 1% below the open. It should have. I thought I had everything setup correctly with my broker and Auto-Place and everything else but it wouldn’t execute a Buy order. The price of TQQQ should have triggered it.
So I quickly ran it manually which created an open order which I sent to my broker, which was finally executed. Anyway, that’s where I’m at. I hope you understand what I mean. I really want to automate everything.
0
Cone8
 ( 7.84% )
- ago
#71
I use the 1-minute strategy myself (modified for NQ futures). It works. You said, "status message stated it was incomplete" but there isn't an "incomplete" status. What was the status exactly?

In the future, quick grab a screen shot when there's something you don't understand. We can usually explain what happened from an image.

Make sure to check
1. Preferences > Trading > Portfolio Sync
2. Chart is 1-min scale and Streaming (Also can use S. Monitor with Streaming, Streaming Bars, or Polling)
3. Correct Broker Account selected
4. Position Sizing is correct
5. Auto-Place enabled

Save the Workspace to come back to it.

Which script are you using? If it's from a post above, which one?
1
- ago
#72
Thanks @Cone.

I’m using #53. Next time, I’ll grab a screenshot of it. I’ll have to wait until Monday again. I thought that’s what it said. I must be wrong if it’s impossible to get that status message.

I’ll make sure everything is setup correctly. I thought it was.
0
Glitch8
 ( 11.20% )
- ago
#73
Hmm isn’t it possible to simply enter the trade manually right after the market open? It’s a very simple calculation of 1% below the open price.
1
Cone8
 ( 7.84% )
- ago
#74
Nothing's impossible :) but if it said "Incomplete", then it was a broker message that should probably have more info attached. You can double click the order to see the message or check the Log Viewer (Ctrl+L).

@Glitch, sure, but it's easier to automate especially when you can't be there!
0
Glitch8
 ( 11.20% )
- ago
#75
Mmmm with a mobile device you can always "be there" for the one minute it takes to trade this strategy.
0
- ago
#76
I work in a high school. Sometimes I have a signal, sometimes I don’t. That’s why I’m trying for automation.

Thanks for all you guys do.

Mike
2
- ago
#77
So Daily script ran for me. However, today was the last trading day of the week and it did not trigger a MarketClose order, so I am having to hold the position for the weekend.

How can we alter the code so that if there is still a position, and it is the last trading day of the week, it will trigger a market close order?
0
Cone8
 ( 7.84% )
- ago
#78
Holding the weekend and dumping the position on Monday's open turned out to be a lucky break this time.

For total automation with a Friday MOC, you'll need to use the [untested] modification for the v2 script here - https://www.wealth-lab.com/Discussion/One-Percent-a-Week-v2-10024

For more "v2" discussion, please comment there.
0
- ago
#79
I am assuming the Monday entry is a GTC order?

I am seeing trades throughout the backtest results showing other days during the week where the entry was triggered.

0
Glitch8
 ( 11.20% )
- ago
#80
Yes, the entry is made every day until it hits or the week ends. Or to keep it simple you can use a GTC and cancel it at end of day Friday if it hasn't hit.
1
- ago
#81
Thank you Glitch.
0
- ago
#82
Hi I just subscribed to Wealthlab. Curious on this One Percent A Week strategy. When i view the positions (take this week as an example), In the position tab it has an entry price of 48.80, but if you take the open price of Tuesday which was 49.35, then this should infer an entry price of 48.85 (or .99 * 49.35). Shouldn't the entry price in the strategy be 48.85 instead of 48.80 ? I've noticed this inconsistency between my calcs and the position entry prices on a few other entries in the past as well. Thanks
0
Glitch8
 ( 11.20% )
- ago
#83
We have an open of 49.29 so 1% below that is 48.80 which is the correct entry price.

0
Cone8
 ( 7.84% )
- ago
#84
@anthony, you're right that 49.35 was the first full-lot trade that day, but it wasn't the opening price for the primary market, which was 49.29. Only Wealth-Data EOD data give you the primary market opening prices. For more info, check out: https://www.wealth-data.com

And specifically, look for WRONG VALUE FOR THE MOST-USED ORDER TYPE? here:
https://www.wealth-data.com/faq

Here's the TOS - notice how the possibly hundreds of trades on various ECNs don't come close to match the volume of the result of the opening auction on the primary market.


0
- ago
#85
Ok thanks so much guys, i get it now, makes sense.

Thanks so much for the links !

Anhtony
1
- ago
#86
For this week on 2/20/2024, open was 56.55 therefore entry was 55.98, market closed at 56.08 which is not 0.5% of loss in open position so why strategy wants to breakeven tomorrow(2/22/2024).

0
Glitch8
 ( 11.20% )
- ago
#87
According to my backtest the entry price is 56.02 and the current price is 55.38 which is a loss greater than 0.5%.

The Strategy attempts to exit at breakeven if the CURRENT loss is more than 0.5%

0
- ago
#88
Intresting. This is how I interpreted the rules. On entry day we dont place any orders on that day. If market closes down more than 0.5% from entry price. We place breakeven order next morning but if market closes more than entry price we sell 1% above entry.
New twist for me is to breakeven any time trade is losing more than 0.5% on any day after entry
I was trading manually following above but so far so good. One more question is do we reenter a trade after breakeven or we sit out for reamining of the week?
0
Glitch8
 ( 11.20% )
- ago
#89
No re entry, it waits until next week to start the process again.
0
- ago
#90
It seems that if we hold position for more than 3-5 days losses mount, 5 is worst and 4 is second in worst, therefore can I request to implement n day exit in c#code to test this hypothesis. I am not a proegrammer. Thx
0
Cone8
 ( 7.84% )
- ago
#91
Here you go. You can play with the number of days and if you sell at Market or Market on Close (MOC).

CODE:
using WealthLab.Backtest; using System; using WealthLab.Core; using WealthLab.Indicators; using System.Collections.Generic; namespace WealthScript6 {    public class OnePercentV3P : UserStrategyBase    {       public OnePercentV3P()       {          _maxDays = AddParameter("Max Days Hold", ParameterType.Int32, 5, 1, 5);          _useMOC = AddParameter("Use MOC = 1", ParameterType.Int32, 1, 0, 1);       }       public override void Initialize(BarHistory bars)       { }           public override void Execute(BarHistory bars, int idx)       { }              public override void ExecuteSessionOpen(BarHistory bars, int idx, double sessionOpenPrice)       {          bool NextBarIsStartOfWeek = _lastBarofWeek == idx;          bool NextBarIsLastDayOfWeek = bars.TomorrowIsLastTradingDayOfWeek(idx);          if (NextBarIsLastDayOfWeek)             _lastBarofWeek = idx + 1;          if (idx - 1 == _lastBarofWeek)             SetBackgroundColor(bars, idx, WLColor.Silver.SetAlpha(32));                    if (NextBarIsStartOfWeek)          {             mondayOpen = sessionOpenPrice;             tradedThisWeek = false;          }                    if (HasOpenPosition(bars, PositionType.Long))          {             double target = LastOpenPosition.EntryPrice;             if (LastOpenPosition.ProfitPctAsOf(idx) > -0.5)                target = target * 1.01;                       Backtester.CancelationCode = 642;                 if (idx - LastOpenPosition.EntryBar + 1 >= _maxDays.AsInt)             {                ClosePosition(LastOpenPosition, _useMOC.AsInt == 1 ? OrderType.MarketClose : OrderType.Market, 0, "Time-based");             }                             PlaceTrade(bars, TransactionType.Sell, OrderType.Limit, target);                       Backtester.CancelationCode = 642;             if (idx < bars.Count - 1)             {                if (NextBarIsLastDayOfWeek)                   PlaceTrade(bars, TransactionType.Sell, OrderType.MarketClose);             }             else             {                //last bar: if today is the last trading day of the week, signal MOC for the open position                if (bars.TomorrowIsLastTradingDayOfWeek(idx))                   PlaceTrade(bars, TransactionType.Sell, OrderType.MarketClose);             }          }          else          {             if (!Double.IsNaN(mondayOpen) && !tradedThisWeek)             {                double mult = 0.99;                PlaceTrade(bars, TransactionType.Buy, OrderType.Limit, mondayOpen * mult);                if (NextBarIsLastDayOfWeek)                {                   Backtester.CancelationCode = 642;                   PlaceTrade(bars, TransactionType.Sell, OrderType.MarketClose);                }             }          }       } //same bar exit public override void AssignAutoStopTargetPrices(Transaction t, double basisPrice, double executionPrice)       {          //t.AutoProfitTargetPrice = executionPrice * 1.01;          tradedThisWeek = true;       }       //declare private variables below       private double mondayOpen = Double.NaN;       bool tradedThisWeek = false;       int _lastBarofWeek = -1;       Parameter _maxDays;       Parameter _useMOC;    } }
1
- ago
#92
Thanks Cone, since i dont know c# where do i change max number of days to hold and change moc to market order, do I need to restart WL for changes to take effect? or just compile again and run backtest.
0
- ago
#93
Copy/paste, Compile, then drag a slider on the Strategy Settings tab > Strategy Parameters (e.g. Use MOC = 0), then click Run Backtest.
1
- ago
#94
QUOTE:
I use the 1-minute strategy myself (modified for NQ futures). It works


I'm still just learning WL and have been using the sample and published strategies to learn the capabilities of this great tool. The one percent a week strategy has been a good example for that, and I've started trading it live

In Post #71, Cone you mentioned you trade this strategy as well on the NQ, with some modifications. Would you be willing to share your rules? I'd love to backtest them as I work to setup intraday data using IQ feed for futures strategies

Appreciate whatever you'd be willing to share

1
Cone8
 ( 7.84% )
- ago
#95
Disclaimer:
I don't recommend, advise, or support this strategy or its methods.

The 1-minute version for futures requires modifying the Market hours to the U.S. cash market hours and applying the Pre/Post Filter. In the case of NQ/MNQ, the hours are CST, i.e., 0830 to 1500. I use 0829 for the Market's opening time so that the first order is placed immediately at the cash open using the close of the 0830 bar. The order is then corrected for the actual 0830 open at 0831. Also, I set the Market's close time to 1501 for a Friday sell at Close event - you can simply Sell at Market since the futures are still trading.

If you do this, you'll have to remember to disable the Pre/Post Filter if you want to see data outside those hours in other charts/strategies.

If you use IQFeed, then your Market times will be ET, i.e., 0929 to 1601. Otherwise, if your provider supplies the data in CST, (e.g., IB), name your Market "NQ 0830" so that it work with this code.

You can play with the parameters, but the defaults are set for "0.333%" per week. This closely corresponds to the TQQQ (3 x QQQ) entries and exits, but with futures you get the leverage in a different way.

CODE:
/* * Modified 1% strategy for NQ Futures * * Use with 1 minute chart */ using WealthLab.Backtest; using System; using WealthLab.Core; namespace WealthScript2 {    public class BuyOnePercentDownFromOpenOnMondayNQ : UserStrategyBase    {       public BuyOnePercentDownFromOpenOnMondayNQ()       {          AddParameter("Dip %", ParameterType.Double, 0.3333330, 0.333333, 0.999999, 0.1666665);          AddParameter("Loss %", ParameterType.Double, 0.1666665, 0.1666665, 0.999999, 0.1666665);                 }       public override void Initialize(BarHistory bars)       {          _pct = Parameters[0].AsDouble / 100.0;          WriteToDebugLog(_pct);          _lossPct = Parameters[1].AsDouble;          if (!bars.Market.Name.Contains("830")) // "NQ 0830" is modified market for a CME start at 0829          {             _openTime = new TimeSpan(9, 30, 0);             _closeTime = new TimeSpan(16, 0, 0);             }                    // find the beginning of the first week loaded - makes sure there's sufficient data to trade          int bar = bars.Count - 1;          DayOfWeek dowToday = bars.DateTimes[bar].DayOfWeek;          do          {             bar = bar - bars.IntradayBarNumber(bar);             if (bar == 0) break;             if (bars.DateTimes[bar - 1].DayOfWeek >= dowToday)             {                _firstBarThisWeek = bar;             }             bar--;          }          while (bar > 0);                    StartIndex = _firstBarThisWeek;          PlotStopsAndLimits(3);                }              public override void Execute(BarHistory bars, int idx)       {             // must have identified a week's open          if (_firstBarThisWeek == -1   )             return;          DateTime dt = bars.DateTimes[idx];          bool todayIsLastTradingDayOfWeek = dt.DayOfWeek > dt.GetNextTradingDate(bars).DayOfWeek;          // ignore Sunday!          if (bars.DateTimes[idx].DayOfWeek == DayOfWeek.Sunday)             return;                    if (bars.DateTimes[idx].DayOfWeek < bars.DateTimes[idx - 1].DayOfWeek)          {             _firstBarThisWeek = idx; // new week just started             _tradedThisWeek = false;                          if (bars.DateTimes[idx].TimeOfDay == _openTime)             {                _openThisWeek = bars.Close[idx];                _firstBarThisWeek = idx + 1;         // first regular session bar                             }             else             {                               _openThisWeek = bars.Open[idx];                _firstBarThisWeek = idx;             }          }          else          {             _openThisWeek = bars.Open[_firstBarThisWeek];          }          _limit = (1 - _pct) * _openThisWeek;          // draw a line from this week's opening price          if (idx == bars.Count - 1 && _firstBarThisWeek < idx)          {             DrawLine(_firstBarThisWeek, _openThisWeek, idx, _openThisWeek, WLColor.Orange, 2, LineStyle.Dashed);                      }                    if (!HasOpenPosition(bars, PositionType.Long))          {             if (!_tradedThisWeek)             {                if (bars.DateTimes[idx].TimeOfDay < _closeTime)                   PlaceTrade(bars, TransactionType.Buy, OrderType.Limit, _limit);             }          }          else          {                Position pos = LastPosition;             double profitpct = 100 * (bars.Close[idx] / pos.EntryPrice - 1);             // check profit at the end of the day to adjust limit price to break even, if required             if (bars.IsLastBarOfDay(idx))             {                   if (profitpct < -_lossPct)                   _target = pos.EntryPrice;             }             //sell on the open of the last bar of the week             if (todayIsLastTradingDayOfWeek && bars.DateTimes[idx].TimeOfDay >= _closeTime)             {                ClosePosition(pos, OrderType.Market);             }             else             {                // exit at limit only on a subsequent day                if (bars.DateTimes[idx].Date != bars.DateTimes[pos.EntryBar].Date || bars.IsLastBarOfDay(idx))                {                   string msg = "EntryPrice: " + pos.EntryPriceString;                   ClosePosition(pos, OrderType.Limit, _target, msg);                                      if (idx == bars.Count - 1)                      DrawHeaderText(msg, WLColor.Aqua, 14, "Price");                }             }          }       } public override void AssignAutoStopTargetPrices(Transaction t, double basisPrice, double executionPrice) {          _tradedThisWeek = true;          _target = executionPrice * (1 + _pct); }       double _pct = 0.01 / 3.0;       double _lossPct = 0.5 / 3.0; double _limit;       double _target;       int _firstBarThisWeek = -1;       double _openThisWeek = 0;       bool _tradedThisWeek = false;       TimeSpan _closeTime = new TimeSpan(15, 0, 0);             TimeSpan _openTime = new TimeSpan(8, 30, 0);          } }
1
- ago
#96
Thanks very much for sharing this Cone
0
- ago
#97
For what it's worth, I sorted the results based on the day of the week the strategy entered. This is the average results:

Entry on:
Monday --> 1.12%
Tuesday --> 0.74%
Wednesday --> -0.33%
Thursday --> -0.03%
Friday --> 0.11%

Limiting the entries to Mondays and Tuesdays adds ~0.15% to the weekly average, and only eliminates ~14% of the trades. Overall returns are higher with this approach.

1
- ago
#98
@pmerges I found the same thing. It appears to be statistically significant over extended periods. I've never heard before that trading earlier in the week is more profitable.

I actually researched and tested for symbols that do better if you buy them later in the week (Thursday and sell at close Friday). They didn't do nearly as well as buying TQQQ earlier in the week. But you do get more exposure because you are doing two trades a week instead of one. That juices the returns. This presumes your Monday purchase sells by Wednesday. It seems like 80+% of the time it does.
0
- ago
#99
@innertrader - agreed, I don't think there's anything magical about Mondays or Tuesdays. (I'd say 40+ years of working has proven just the opposite :D )

It's *this strategy* that performs best entering the first two days of the week, and I suspect you are correct that it gives the system more opportunity to recover.

It would be interesting to see what happens if you could start the trade any day of the week. I was looking for a function that specifies which day of the week the trade can start but couldn't find that.

@Cone / @Glitch, is there anything like that in the system?

0
Glitch8
 ( 11.20% )
- ago
#100
I’ll see about making a version that lets you specify which day constitutes the start of the week.
2
- ago
#101
Wanted to ask if anyone here has tried trading the 1% a week strategy using call options on the TQQQ or QQQ instead of the shares themselves?

Or is there a way to backtest that approach using options in WL?

I did a manual backtest of this by hand using TOS over 8 weeks using ATM 2 week to expiration calls and the potential seems to be there. The advantage of options is it can limit your left tail risk to the premium paid
0
Glitch8
 ( 11.20% )
- ago
#102
Since we don't have access to historical options data for expired contracts it wouldn't be possible to backtest, but it would be interesting to see some forward results. Would you monitor the prices and then buy the option once TQQQ hits 1% below the open?
0
- ago
#103
Yes the concept is to trade the system exactly the same using the TQQQ chart for buy and sell triggers, but use ATM ~2 weeks to expiration calls instead of shares of the TQQQ

I will manually forward test this for a few weeks then and share my results here
0
Cone8
 ( 7.84% )
- ago
#104
Sound like a good idea. You can get a good idea if it would work by testing with OptionSynthetic. When I get a chance...
1

Reply

Bookmark

Sort