Backtesting Exit Strategy after "n" days

jpoms13

New member
Hello All!

I am not an active trader, rather, instead I work for a small mortgage company and I actively manage our pipelines interest rate risk. I am looking to improve our hedging ability by incorporating some trading concepts that I've found that supplement my current hedging strategy quite well. I'm looking to dive a little deeper into them though and one of the things I am looking to do is see how the indicators that I've incorporated perform over a fixed timeframe (IE: performance after 5,10,15, 30 days after a trade is triggered.


Can anyone assist with creating an exit strategy that simply closes a trade after n days?

Thanks!
 
Solution
Hello All!

I am not an active trader, rather, instead I work for a small mortgage company and I actively manage our pipelines interest rate risk. I am looking to improve our hedging ability by incorporating some trading concepts that I've found that supplement my current hedging strategy quite well. I'm looking to dive a little deeper into them though and one of the things I am looking to do is see how the indicators that I've incorporated perform over a fixed timeframe (IE: performance after 5,10,15, 30 days after a trade is triggered.


Can anyone assist with creating an exit strategy that simply closes a trade after n days?

Thanks!


asking for a study, without providing any code is asking for a lot.
that means someone has...
Hello All!

I am not an active trader, rather, instead I work for a small mortgage company and I actively manage our pipelines interest rate risk. I am looking to improve our hedging ability by incorporating some trading concepts that I've found that supplement my current hedging strategy quite well. I'm looking to dive a little deeper into them though and one of the things I am looking to do is see how the indicators that I've incorporated perform over a fixed timeframe (IE: performance after 5,10,15, 30 days after a trade is triggered.


Can anyone assist with creating an exit strategy that simply closes a trade after n days?

Thanks!


asking for a study, without providing any code is asking for a lot.
that means someone has to create test code to create signals, to test their new code.

i happen to have a template of 2 averages crossing, that i have used for projects like this, so i used that.

-------------------

can choose how many days that the trade stays active, then sell.

it uses the crossing above of 2 averages for a buy signal.
can choose to use the crossing below signal as a 2nd sell signal.


# change these to use your signals
def buy_signal = xup;
def sell_signal = xdwn;

------------------

this is a strategy, not a study. load it under strategies.

Code:
# str_close_after_x_days_00c

#https://usethinkscript.com/threads/backtesting-exit-strategy-after-n-days.13839/
#Backtesting Exit Strategy after "n" days


def na = Double.NaN;
def bn = BarNumber();
#def lastbar = !isnan(close[0]) and isnan(close[-1]);
#def barCount = HighestAll(If(IsNaN(close), 0, bn));


#=================================
# dates

#input day_bars = no;
def diffday = if GetDay() != GetDay()[1] then 1 else 0;
#def dayend = if GetDay() != GetDay()[-1] then 1 else 0;
#addchartbubble(day_bars and (diffday or dayend), low, (if diffday then "B" else if dayend then "E" else "-"), (if diffday then color.green else if dayend then color.red else color.gray), no);

#=================================
# time

#input start = 0930;
#input end = 1600;
#def daytime = if SecondsFromTime(start) >= 0 and SecondsTillTime(end) > 0 then 1 else 0;
#def daytime2 = (GetTime() >= RegularTradingStart(GetYYYYMMDD()) and GetTime() < RegularTradingEnd(GetYYYYMMDD()));

#-------------------------------------


input close_after_xdays = 10;
input use_cross_below_to_sell = no;


#=================================

# test signals, buy / sell

def price = close;

input ma1_len = 21;
input ma1_type = AverageType.EXPONENTIAL;
def ma1 = MovingAverage(ma1_type, price, ma1_len);

input ma2_len = 44;
input ma2_type = AverageType.EXPONENTIAL;
def ma2 = MovingAverage(ma2_type, price, ma2_len);

def xup = ma1 crosses above ma2;
def xdwn = ma1 crosses below ma2;


input show_lines = yes;

plot z1 = if show_lines then ma1 else na;
z1.SetDefaultColor(GetColor(1));
#z1.setlineweight(1);
z1.HideBubble();

plot z2 = if show_lines then ma2 else na;
z2.SetDefaultColor(GetColor(2));
#z2.setlineweight(1);
z2.HideBubble();



#--------------------------------
#input test1_avgs = no;
#AddChartBubble( test1_avgs, low,
#ma1 + " 1\n" +
#ma2 + " 2\n"
#, Color.YELLOW, no);

#==============================


# change these to use your signals
def buy_signal = xup;
def sell_signal = xdwn;



#====================

#reset cnt on xup
#but dont reset if still in a trade

def cnt;
def trade;  # trade=1 if in a trade
def cancel;

if bn == 1 then {
    cnt = 0;
    trade = 0;
    cancel = 0;

} else if diffday and (cnt[1] + 1) >= close_after_xdays then {
    cnt = 0;
    trade = 0;
    cancel = 1;

} else if use_cross_below_to_sell and trade[1] and sell_signal then {
    cnt = 0;
    trade = 0;
    cancel = 2;

} else if trade[1] and diffday then {
    cnt = cnt[1] + 1;
    trade = trade[1];
    cancel = 0;

} else if buy_signal and trade[1] == 0 then {
    cnt = 1;
    trade = 1;
    cancel = 0;

} else {
    cnt = cnt[1];
    trade = trade[1];
    cancel = 0;
}



AddLabel(1, "use cross " + use_cross_below_to_sell);



# buy
def order_buy = !trade[1] and trade;



#addchartbubble(0, low*0.99,
AddChartBubble(0 and ( order_buy or cancel > 0), low * 0.99,
#trade + "\n" +
#order_buy + "\n" +
cnt[1] + "\n" +
cancel
, (if cancel == 1 then Color.RED else if trade then Color.GREEN else Color.GRAY), no);



# buy
AddOrder(type = OrderType.BUY_TO_OPEN, condition = buy_signal, price = open[-1], tradeSize = 1, tickcolor = Color.green, arrowcolor = Color.green, name = "x" );


# sell
#def order_sell = trade[1] and !trade;
# cancel=1 , red
# cancel=2 , magenta


AddOrder(type = OrderType.SELL_TO_CLOSE, condition = (cancel == 1), price = open[-1], tradeSize = 1, tickcolor = Color.RED, arrowcolor = Color.RED, name = (close_after_xdays + " days") );


AddOrder(type = OrderType.SELL_TO_CLOSE, condition = (cancel == 2), price = open[-1], tradeSize = 1, tickcolor = Color.magenta, arrowcolor = Color.magenata, name = "signal" );
#

set to close a trade after 10 days
1 hour - 30 day chart
red = close after 10 days
purple = cross below sell
0DSq4J1.jpg
 
Last edited:
Solution
Hello All!

I am not an active trader, rather, instead I work for a small mortgage company and I actively manage our pipelines interest rate risk. I am looking to improve our hedging ability by incorporating some trading concepts that I've found that supplement my current hedging strategy quite well. I'm looking to dive a little deeper into them though and one of the things I am looking to do is see how the indicators that I've incorporated perform over a fixed timeframe (IE: performance after 5,10,15, 30 days after a trade is triggered.


Can anyone assist with creating an exit strategy that simply closes a trade after n days?

Thanks!

this is somewhat similar
https://usethinkscript.com/threads/...s-and-elapsed-time-or-number-of-candles.9305/
 

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
338 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