Help with Backtest Strategy Code - "STC order with Stop/Exit trade in "X" number of days"

C4rnif3X

New member
6yHWI0G.png


Hello, so i'm at a complete standstill right now. I'm writting a seperate strategy (still a newbie with TS), and I want to be able to set a STC order with a Stop/Exit in "X" number of days upon Entry Price. Instead of including all the other code from the other strat, I wrote a simple example to make things easier.

I've tried all I could think of, and embarrassingly enough the code is probably really simple haha. I've looked everywhere I could online to no avail.

The only thing i've got to work/something to happen is by turning the "Count_Days" highlighted off code, on - and the "Day_Stop" number would actually count the bars and sell out within a semi-right time frame.

The "Count_Days" code below that one does nothing when combined with the Day Stop.

Any help would be appreciated greatly! Thanks.
 
@C4rnif3X Your code, as written, is attempting to use "state" to track candles/bars not days... As such it will only count days if you use the script on a chart using the Day timeframe... Beyond that, I haven't tested the overall logic for accuracy...

All that said, I consider @XeoNoX as our resident counter guru... Perhaps he will chime in with a feasible solution...
 
@C4rnif3X Your code, as written, is attempting to use "state" to track candles/bars not days... As such it will only count days if you use the script on a chart using the Day timeframe... Beyond that, I haven't tested the overall logic for accuracy...

All that said, I consider @XeoNoX as our resident counter guru... Perhaps he will chime in with a feasible solution...
Ya that makes sense as to why it's not working. If you're referring to the "==" command, it's my temporary bypass to my problem at the moment. I don't know enough yet to get what I need working.

I will only be using my backtest on a Daily, so I don't need a GetSeconds or Intraday shenanegans. I definitely sense I need to have some reference to GetDay or aggregation or something, I just don't know enough lol. So hopefully there is a solution!
 
not sure what your trying to do but i think its something like this

Code:
def sell_signal = if count_days>2 then sell else sell_signal[1];

also next time its helpful if you post the code to accompany the screenshot.
 
not sure what your trying to do but i think its something like this

Code:
def sell_signal = if count_days>2 then sell else sell_signal[1];

also next time its helpful if you post the code to accompany the screenshot.
Hey, thanks for responding. Here is the entire code. It's just a template strat so I can get the STC "exit trade" in "X" amount of days order working, then I can figure out how to get it working in my real strategy. I'm trying to keep it as simple as possible so I don't take up to much of anyone's time.

The "Count_Days" command works in label form and counts everybar on the current daily time frame, it just doesn't work when I try to pair it with "Count_Days >= Day_Stop." I must be missing some crucial reference to more information, but i'm still new so I don't know what I don't know lol.

Code:
#BASIC DATA
#--------------

input Price = close;
input Length = 20;
input Quantity = 1;
input Profit_Target = 50;
input Day_Stop = 10;
def Entry_Price = EntryPrice();

#MA DATA
#-----------

plot SMA = Average(Price, Length);

#ORDER DATA
#--------------

def Count_Days = if Price then Count_Days[1] + 1 else 0;

def Buy_Signal = Price crosses above SMA;
def Sell_Signal = Count_Days >= Day_Stop or Price > Entry_Price + Profit_Target;

#BUY CONDITIONS
#--------------

def Entry_1 = Buy_Signal;

#SELL CONDITIONS
#---------------

def Exit_1 = Sell_Signal;

#BUY
#----

AddOrder(OrderType.BUY_TO_OPEN, Entry_1, close, Quantity, name = "BUY");

#SELL
#----

AddOrder(OrderType.SELL_TO_CLOSE, Exit_1, close, Quantity, name = "SELL");
 

in standard English language.... what is this supposed to do?
def Sell_Signal = Count_Days >= Day_Stop or Price > Entry_Price + Profit_Target;
So what i'm trying to accomplish is just with a Sell To Close order in general that can be applied to any other strategy.

" def Sell_Signal = Count_Days >= Day_Stop or Price > Entry_Price + Profit_Target; "

The goal here is to say - I want to make "X" amount of points, or just close the position in "X" amount of days if the price target isn't met - no matter what.

"Price > Entry_Price + Profit_Target
" - works as intended, meaning as soon as my profit target is met - it closes the position with backtesting.

It's the - "Or in X amount of days" I can't figure out how to do.

Is there just a simple way to do this? Thanks for taking the time to help!
 
@C4rnif3X Try using this to count.

Code:
def Count_Days = if Buy_Signal then 0 else Count_Days[1] +1;
Hmm, that seems to be doing something. Still not exiting correctly for some reason. The backtesting report still isn't exiting within the givin time frame. It's odd because the logic you posted makes sense, if upon entry it starts the count.

I think there's more commands needed to make this happen, i'm thinking within the time and date logic - which I have no idea how to do.
 
@C4rnif3X It's exiting on the 10th bar after entry for me. Can you post a ss of what's wrong?
We both probably have the same code layout now, so I won't post it again for the moment. All I did was change the Count_Days to what you posted.

As seen, I have 1 /es fut's contract with a 50 point target, and a 20 day stop.

Some days post the exit correctly like the two smaller red boxes, others like the big red box are a Month+

I tried changing around the aggregation and after hour settings in the platform to see if that would do anything but nadda.

Upon looking at it, I think I know what's happening? We have the Count_Days command to start/be TRUE above the SMA. I think it's stopping the count below the SMA.


vQiqyXP.png
 
So what i'm trying to accomplish is just with a Sell To Close order in general that can be applied to any other strategy.

" def Sell_Signal = Count_Days >= Day_Stop or Price > Entry_Price + Profit_Target; "

The goal here is to say - I want to make "X" amount of points, or just close the position in "X" amount of days if the price target isn't met - no matter what.

"Price > Entry_Price + Profit_Target" - works as intended, meaning as soon as my profit target is met - it closes the position with backtesting.

It's the - "Or in X amount of days" I can't figure out how to do.

Is there just a simple way to do this? Thanks for taking the time to help!
It's the - "Or in X amount of days" I can't figure out how to do.

Code:
#set to day aggregation so that each bar represents 1 day.
def var = entry_price > 0;  #fact this is greater than 0 means you have a open position assuming youre not net short
def barUpCount = CompoundValue(1, if var then barUpCount[1] + 1 else 0, 0); #countdays
def takeprofit = if barUpCount >3 then close_position else takeprofit[1]; #take profit after 3 days
 
It's the - "Or in X amount of days" I can't figure out how to do.

Code:
#set to day aggregation so that each bar represents 1 day.
def var = entry_price > 0;  #fact this is greater than 0 means you have a open position assuming youre not net short
def barUpCount = CompoundValue(1, if var then barUpCount[1] + 1 else 0, 0); #countdays
def takeprofit = if barUpCount >3 then close_position else takeprofit[1]; #take profit after 3 days
Thank you!

Ok so I re-wrote your code in my script to make it easy to read for me. I'll post the code picture and the current code.

The "Day_Stop" value still isn't doing anything in this current state. In fact it's not exiting the position at all. Do I have everything correctly laid out?

qyKmPyo.png


Code:
#BASIC DATA
#----------
input Price = close;
input Length = 20;
input Quantity = 1;
input Profit_Target = 50;
input Day_Stop = 10;
def var = EntryPrice() > 0;

#MA DATA
#-------
plot SMA = Average(Price, Length);

#ORDER DATA
#--------
def Bar_Up_Count = CompoundValue(1, if var then Bar_Up_Count[1] + 1 else 0, 0);

def Buy_Signal = Price crosses above SMA;
def Sell_Signal = if Bar_Up_Count >= Day_Stop then Price > EntryPrice() + Profit_Target else Sell_Signal[1];

#BUY CONDITIONS
#--------------
def Entry_1 = Buy_Signal;

#SELL CONDITIONS
#---------------
def Exit_1 = Sell_Signal;

#BUY
#----

AddOrder(OrderType.BUY_TO_OPEN, Entry_1, close, Quantity, name = "BUY");

#SELL
#----
AddOrder(OrderType.SELL_TO_CLOSE, Exit_1, close, Quantity, name = "SELL");
 
def Sell_Signal = if Bar_Up_Count >= Day_Stop then Price > EntryPrice() + Profit_Target else Sell_Signal[1];

that means
Price > EntryPrice() is equaling to 1 or 0 depending if true or not.
so this is what you are telling sell signal
if days is greater than 10 then add 1 or 0 to the profit target price HOWEVER if its less than 10 days then continue scanning this scan.

i imagine you possibly want something along the lines of:
def Sell_Signal = if Bar_Up_Count >= Day_Stop or ( EntryPrice() + Profit_Target) then SELL_TO_CLOSE else Sell_Signal[1];
 
def Sell_Signal = if Bar_Up_Count >= Day_Stop then Price > EntryPrice() + Profit_Target else Sell_Signal[1];

that means
Price > EntryPrice() is equaling to 1 or 0 depending if true or not.
so this is what you are telling sell signal
if days is greater than 10 then add 1 or 0 to the profit target price HOWEVER if its less than 10 days then continue scanning this scan.

i imagine you possibly want something along the lines of:
def Sell_Signal = if Bar_Up_Count >= Day_Stop or ( EntryPrice() + Profit_Target) then SELL_TO_CLOSE else Sell_Signal[1];
Ahh gotcha, so i'm just adding numbers to the profit target. Makes sense why the current code is currently not selling out at all.

I replaced the code with that suggestion.

Stupid question but :

For - " def Sell_Signal = if Bar_Up_Count >= Day_Stop or ( EntryPrice() + Profit_Target) then SELL_TO_CLOSE else Sell_Signal[1]; "

What function am I replacing "Sell_To_Close" with, Price? My price reference just means close so i'm not sure on that. I tried it and it's still not working.
 
@C4rnif3X Alright, the problem is with the strategy settings. I'm assuming your settings are set to 1 entry order in the same direction. If you look at the ss you posted, you should see that the buy signal got triggered multiple times after the entry in the center box. Each of those cross reset the counter. Try increasing the maximum order entries in the settings and you should see what I'm talking about.
 
@C4rnif3X Alright, the problem is with the strategy settings. I'm assuming your settings are set to 1 entry order in the same direction. If you look at the ss you posted, you should see that the buy signal got triggered multiple times after the entry in the center box. Each of those cross reset the counter. Try increasing the maximum order entries in the settings and you should see what I'm talking about.
Ya I posted about that last night, it was resetting the count every time it crossed. At the end of the day this is just a template strategy - and i'm trying to find just a universal way to do it count and sell out in X days. Instead of "Count on trigger to SMA cross." I just use the SMA cross for this template cause it's the easiest trigger to test for entry.

So far nothing has worked for the selling part, but I do know you can do it cause I saw a video of somebodies strat where they did it. Or course it's a "paid" strategy so they won't share the code lol.
 

Join useThinkScript to post your question to a community of 21,000+ developers and traders.

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

87k+ Posts
469 Online
Create Post

Similar threads

Similar threads

The Market Trading Game Changer

Join 2,500+ subscribers inside the useThinkScript VIP Membership Club
  • Exclusive indicators
  • Proven strategies & setups
  • Private Discord community
  • ‘Buy The Dip’ signal alerts
  • Exclusive members-only content
  • Add-ons and resources
  • 1 full year of unlimited support

Frequently Asked Questions

What is useThinkScript?

useThinkScript is the #1 community of stock market investors using indicators and other tools to power their trading strategies. Traders of all skill levels use our forums to learn about scripting and indicators, help each other, and discover new ways to gain an edge in the markets.

How do I get started?

We get it. Our forum can be intimidating, if not overwhelming. With thousands of topics, tens of thousands of posts, our community has created an incredibly deep knowledge base for stock traders. No one can ever exhaust every resource provided on our site.

If you are new, or just looking for guidance, here are some helpful links to get you started.

What are the benefits of VIP Membership?
VIP members get exclusive access to these proven and tested premium indicators: Buy the Dip, Advanced Market Moves 2.0, Take Profit, and Volatility Trading Range. In addition, VIP members get access to over 50 VIP-only custom indicators, add-ons, and strategies, private VIP-only forums, private Discord channel to discuss trades and strategies in real-time, customer support, trade alerts, and much more. Learn all about VIP membership here.
How can I access the premium indicators?
To access the premium indicators, which are plug and play ready, sign up for VIP membership here.
Back
Top