Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

time based conditions #761

bafnarahul2 started this conversation in General
Oct 4, 2022 · 3 comments · 3 replies
Discussion options

How do i put time based conditions such as no trade after a particular period or all the positions to be closed 10 minutes before call.

You must be logged in to vote

Replies: 3 comments 3 replies

Comment options

Examine Strategy.data.index[-1] which would be a pd.Timestamp for datetime indexes.

You must be logged in to vote
0 replies
Comment options

I'm trying to implement a condition where a trade is entered only between 8-10am, but the trade stats still show an entry at 14:00:00. Not sure what I'm doing wrong here? Any input much appreciated!

class MACDStrategy(Strategy):
 def init(self):
 self.macd_hist = self.I(MACD, self.data.df) #indicator function to compute first
 self.atr = self.I(ATR, self.data.df)
 def next(self):
 high = self.data.High[-1]
 low = self.data.Low[-1]
 # buy the asset
 hour = self.data.index.hour
 if (6 < self.macd_hist[-1] > self.macd_hist[-2] and
 8 <= hour[-1] <= 10):
 if not self.position:
 sl = low - self.atr * 1.5 # tp = price + self.atr * 2
 self.buy(limit=high, stop=high, sl = sl) #buy if high exceeds prior high
 # Else sell/close the asset
 for trade in self.trades:
 if self.macd_hist[-1] < self.macd_hist[-2]:
 if self.position:
 self.position.close()
#get historical data
df = pd.read_csv('MESH31HJan.csv', index_col='Date', parse_dates=True)
#Backtesting
bt = Backtest(df, MACDStrategy, cash=5_000, commission=0, exclusive_orders=True)
stats = bt.run()

Screen Shot 2023年02月17日 at 10 37 28 AM

You must be logged in to vote
3 replies
Comment options

You're buying with stop-limit. Can you confirm 14:00 bar is not the soonest the stop is reached?

Comment options

Yes, you're absolutely correct!

How can I avoid this situation if I just want to place trades within the specified hours?

Comment options

Placed orders are GTC. Therefore you just have to make sure you cancel the order when you no longer want it filled. You can e.g. close the orders if they haven't been filled by the next bar's completion:

def next(self):
 for order in self.orders:
 if not order.is_contingent:
 order.cancel()
 ... # Rest of code
Comment options

Hi, posting here because I have a similar issue:

Coded the following custom indicator: It return 1 if within the timeframe, 0 if not within:
(i have tried with changing the astype types --> no bueno

` def window(data):
 window = pd.Series(
 (data.index.time >= pd.to_datetime('14:29').time()) & (data.index.time <= pd.to_datetime('16:30').time()),
 index=data.index).astype(int)
 return np.array(window)`

It prints on the graph everything seems ok there. Values are correct. Nonetheless, it seems from time to time that the algo gets a trade before or after. and I will burst a nut if I don't find out why:

self.window = self.I(window, self.data, overlay=False)

Here 9pm purchase UTC, with a window value to 0

Screenshot 2024年01月20日 at 19 56 52

I use it to close positon - which seems to work BTW, cause when it opens outside of the window, it close the position at the next bar:

 if self.position:
 if self.position.is_long:
 if (
 self.position.pl_pct <= max_day_loss
 or self.data.Close < self.ll[hh_ll_Offset]
 or self.window == 0.0
 ):
 self.position.close()

But for the purchase, it does not seem to operate within the specified 1 value: (the other operatorsm pm_v and self.pm_gap works and have a similar dynamic:


` elif (self.window == 1.0) and (self.pm_gap < -pm_gap_val or self.pm_gap > pm_gap_val) and (pm_v_max > self.pm_v > pm_v_low):
 # Going Up:
 if crossover(self.data.High, self.pm_h) and (self.pd_h > self.pm_h):
 if (self.pm_h + (atr_mult * self.atr)) > self.pd_h:
 pass
 elif self.buy(
 stop=self.pm_h + (atr_mult * self.atr),
 sl=price * (1 - 0.01),
 ):
 pass `

Screenshot 2024年01月20日 at 19 47 35

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

AltStyle によって変換されたページ (->オリジナル) /