This script needs to take one big trade between 9AM and 11AM, only one big trade on each pair : # Install required libraries (if not already installed)
Uncomment the lines below if you need to install the libraries
!pip install yfinance backtrader pandas_ta ta mplfinance matplotlib tensorflow scikit-learn
Import necessary libraries
import pandas as pd
import numpy as np
import datetime
import pandas_ta as ta
import matplotlib.pyplot as plt
import mplfinance as mpf
import yfinance as yf
import warnings
import pytz
import os
Optional: Set environment variable to disable oneDNN optimizations if desired
os.environ['TF_ENABLE_ONEDNN_OPTS'] = '0'
For Backtesting
import backtrader as bt
For AI Model
from sklearn.preprocessing import MinMaxScaler
from sklearn.model_selection import train_test_split
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM, Dense, Dropout
from tensorflow.keras.callbacks import EarlyStopping
features = ['Close', 'RSI', 'ATR', 'Institutional_Flow', 'BOS_Up', 'BOS_Down',
'CHoCH_Up', 'CHoCH_Down', 'Equal_Highs', 'Equal_Lows', 'Hour']
sequence_length = 60 # Number of time steps for LSTM
Function to fetch data using yfinance
def fetch_data(pair, interval='1m'):
try:
# Fetch data
data = yf.download(tickers=pair, interval=interval, period='5d', progress=False)
if data.empty:
print(f"No data fetched for {pair}")
return None
# Ensure datetime index is timezone-aware in UTC
if data.index.tz is None:
data.index = data.index.tz_localize('UTC') # Set timezone to UTC
else:
data.index = data.index.tz_convert('UTC') # Convert to UTC
data.rename(columns={
'Open': 'Open',
'High': 'High',
'Low': 'Low',
'Close': 'Close',
'Volume': 'Volume'
}, inplace=True)
return data
except Exception as e:
print(f"Error fetching data for {pair}: {e}")
return None
Collect Data
market_data = {}
for pair in currency_pairs:
print(f"Fetching data for {pair}...")
data = fetch_data(pair, interval='1m')
if data is not None:
key = pair.replace('=X', '').replace('/', '_')
market_data[key] = data
ai_models = {}
for key in market_data.keys():
df = market_data[key]
df_prepared = prepare_data(df)
market_data[key] = df_prepared
# Define target variable: Next period return (classification problem)
df_prepared['Target'] = (df_prepared['Close'].shift(-1) > df_prepared['Close']).astype(int)
df_prepared.dropna(inplace=True)
if len(df_prepared) < sequence_length:
print(f"Not enough data for {key} to create sequences.")
continue
# Features for AI model
X = df_prepared[features]
y = df_prepared['Target']
# Scaling
scaler = MinMaxScaler()
X_scaled = scaler.fit_transform(X)
# Create sequences
X_seq, y_seq = [], []
for i in range(sequence_length, len(X_scaled)):
X_seq.append(X_scaled[i-sequence_length:i])
y_seq.append(y.iloc[i])
X_seq, y_seq = np.array(X_seq), np.array(y_seq)
if len(X_seq) == 0:
print(f"Not enough data for {key} after sequence creation.")
continue
# Split data
X_train, X_test, y_train, y_test = train_test_split(X_seq, y_seq, test_size=0.2, shuffle=False)
# Build LSTM model
model = Sequential()
model.add(LSTM(64, return_sequences=True, input_shape=(X_train.shape[1], X_train.shape[2])))
model.add(Dropout(0.2))
model.add(LSTM(32))
model.add(Dropout(0.1))
model.add(Dense(1, activation='sigmoid'))
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
# Early stopping
early_stopping = EarlyStopping(monitor='val_loss', patience=3)
# Train model
history = model.fit(
X_train, y_train,
epochs=5, # Reduced epochs for quick testing
batch_size=32,
validation_data=(X_test, y_test),
callbacks=[early_stopping],
verbose=1
)
# Evaluate model
loss, accuracy = model.evaluate(X_test, y_test)
print(f'{key} Model Accuracy: {accuracy*100:.2f}%')
ai_models[key] = (model, scaler)
Adjusted Kill Zone Definition
def is_within_kill_zone(dt):
# Kill Zone from 9 AM to 11 AM Paris Time
paris_timezone = pytz.timezone('Europe/Paris')
dt_paris = dt.astimezone(paris_timezone)
return dt_paris.time() >= datetime.time(9, 0) and dt_paris.time() < datetime.time(11, 0)
Define the Enhanced ICT Strategy with AI Integration
class EnhancedICTStrategyWithAI(bt.Strategy):
params = dict(
verbose=True, # Enable verbose for debugging
max_risk_per_trade=0.01, # 1% risk per trade
sequence_length=sequence_length,
features=features,
model=None,
scaler=None
)
def __init__(self):
self.trade_journal = []
self.order = None
self.sequence_length = self.params.sequence_length
self.features = self.params.features
# Access data
self.data_open = self.datas[0].open
self.data_high = self.datas[0].high
self.data_low = self.datas[0].low
self.data_close = self.datas[0].close
# Indicators
self.atr = self.datas[0].ATR
self.inst_flow = self.datas[0].Institutional_Flow
self.rsi = self.datas[0].RSI
# AI Model
self.model = self.params.model
self.scaler = self.params.scaler
self.past_data = []
def next(self):
dt = self.datas[0].datetime.datetime(0)
# Check if within Kill Zone
if not is_within_kill_zone(dt):
return
# Collect features for AI prediction
current_features = [
self.data_close[0],
self.rsi[0],
self.atr[0],
self.inst_flow[0],
int(self.datas[0].BOS_Up[0]),
int(self.datas[0].BOS_Down[0]),
int(self.datas[0].CHoCH_Up[0]),
int(self.datas[0].CHoCH_Down[0]),
int(self.datas[0].Equal_Highs[0]),
int(self.datas[0].Equal_Lows[0]),
dt.hour
]
self.past_data.append(current_features)
if len(self.past_data) < self.sequence_length:
return
elif len(self.past_data) > self.sequence_length:
self.past_data.pop(0)
# Prepare AI input
X_ai = np.array(self.past_data)
X_ai_scaled = self.scaler.transform(X_ai)
X_ai_scaled = X_ai_scaled.reshape(1, self.sequence_length, len(self.features))
ai_prediction = self.model.predict(X_ai_scaled)[0][0]
# Adjust AI signal threshold to be less strict
ai_signal = ai_prediction > 0.4 # Reduced threshold to 0.4
# Simplify Entry Conditions
if not self.position:
if is_within_kill_zone(dt):
self.enter_long_position()
elif self.position.size > 0:
# Close position at 11 AM Paris Time
paris_timezone = pytz.timezone('Europe/Paris')
dt_paris = dt.astimezone(paris_timezone)
if dt_paris.time() >= datetime.time(11, 0):
self.close_position()
def enter_long_position(self):
atr = self.atr[-1]
stop_loss_price = self.data_close[0] - 1 * atr
take_profit_price = self.data_close[0] + 1 * atr # Adjusted to 1x ATR for quicker TP
stop_loss_pips = (self.data_close[0] - stop_loss_price) * 10000 # Convert to pips
position_size = self.calculate_position_size(stop_loss_pips)
position_size = max(position_size, 0.01) # Minimum position size
position_size = min(position_size, 10) # Maximum position size
self.order = self.buy(size=position_size)
self.log_trade('BUY', position_size)
# Set Stop Loss and Take Profit
self.sell(exectype=bt.Order.Stop, price=stop_loss_price, size=position_size)
self.sell(exectype=bt.Order.Limit, price=take_profit_price, size=position_size)
print(f"Entering long position at {self.data_close[0]} on {self.datas[0].datetime.datetime(0)}")
def close_position(self):
self.order = self.close()
position_type = 'LONG' if self.position.size > 0 else 'SHORT'
self.log_trade(f'CLOSE {position_type}', abs(self.position.size))
print(f"Closing position at {self.data_close[0]} on {self.datas[0].datetime.datetime(0)}")
def calculate_position_size(self, stop_loss_pips):
# Position size in lots
risk_amount = self.broker.getvalue() * self.params.max_risk_per_trade
pip_value = 10 # For standard lots in major currency pairs
position_size = risk_amount / (stop_loss_pips * pip_value)
return position_size
def log_trade(self, action, position_size):
dt = self.datas[0].datetime.datetime(0)
price = self.data_close[0]
log_entry = {
'Date': dt,
'Action': action,
'Price': price,
'Position Size': position_size
}
self.trade_journal.append(log_entry)
if self.params.verbose:
print(f"{dt} - {action} at {price}, Position Size: {position_size}")
print(f"Trade logged: {log_entry}")
results_dict = {}
for key in market_data.keys():
print(f"Running backtest for {key}...")
df = market_data[key].copy()
df.dropna(inplace=True)
if key not in ai_models:
print(f"Skipping {key} due to insufficient data for AI model.")
continue
# Get AI model and scaler for this currency pair
model, scaler = ai_models[key]
data_feed = CustomPandasData(dataname=df)
cerebro = bt.Cerebro()
cerebro.adddata(data_feed)
cerebro.addstrategy(
EnhancedICTStrategyWithAI,
verbose=True, # Enable verbose mode for diagnostics
model=model,
scaler=scaler,
sequence_length=sequence_length,
features=features
)
cerebro.broker.setcash(100000.0)
cerebro.broker.setcommission(commission=0.0002)
# Run backtest
result = cerebro.run()
final_value = cerebro.broker.getvalue()
print(f"Final Portfolio Value for {key}: {final_value:.2f}")
# Store results and trade journal
trade_journal = result[0].trade_journal
trade_journal_df = pd.DataFrame(trade_journal)
results_dict[key] = {
'Final Portfolio Value': final_value,
'Trade Journal': trade_journal_df,
'Cerebro': cerebro
}
Plot Trades on Price Chart
for key, result in results_dict.items():
df = market_data[key].copy()
trade_journal = result['Trade Journal']
df = df.tail(500)
if trade_journal.empty:
print(f"No trades recorded for {key}.")
continue
if 'Action' not in trade_journal.columns:
print(f"'Action' column not found in trade journal for {key}.")
print(trade_journal)
continue
# Create buy and sell signals
buy_signals = trade_journal[trade_journal['Action'] == 'BUY']
sell_signals = trade_journal[trade_journal['Action'] == 'SELL']
close_signals = trade_journal[trade_journal['Action'].str.startswith('CLOSE')]
# Prepare addplots
apds = []
# Initialize signal columns to NaN
df['Buy_Signal'] = np.nan
df['Sell_Signal'] = np.nan
df['Close_Signal'] = np.nan
if not buy_signals.empty:
buy_dates = pd.to_datetime(buy_signals['Date'])
df.loc[df.index.isin(buy_dates), 'Buy_Signal'] = df['Low'] - (df['High'] - df['Low'])*0.02
if df['Buy_Signal'].notna().any():
apds.append(mpf.make_addplot(df['Buy_Signal'], type='scatter', markersize=50, marker='^', color='g'))
if not sell_signals.empty:
sell_dates = pd.to_datetime(sell_signals['Date'])
df.loc[df.index.isin(sell_dates), 'Sell_Signal'] = df['High'] + (df['High'] - df['Low'])*0.02
if df['Sell_Signal'].notna().any():
apds.append(mpf.make_addplot(df['Sell_Signal'], type='scatter', markersize=50, marker='v', color='r'))
if not close_signals.empty:
close_dates = pd.to_datetime(close_signals['Date'])
df.loc[df.index.isin(close_dates), 'Close_Signal'] = df['Close']
if df['Close_Signal'].notna().any():
apds.append(mpf.make_addplot(df['Close_Signal'], type='scatter', markersize=100, marker='x', color='k'))
# Check if apds is empty
if not apds:
print(f"No trade signals to plot for {key}.")
else:
# Plot price data with signals
mpf.plot(df, type='candle', style='charles', title=f'{key} Price Chart with Trades', addplot=apds)
Save Trade Journals
for key, result in results_dict.items():
trade_journal = result['Trade Journal']
trade_journal.to_csv(f'Trade_Journal_{key}.csv', index=False)
print(f"Trade journal for {key} saved.")
Analyze Trade Journals
for key in results_dict.keys():
trade_journal = results_dict[key]['Trade Journal']
print(f"\nTrade Journal for {key}:")
print(trade_journal)
To ensure that your script takes only one big trade per currency pair between 9 AM and 11 AM (Paris Time), we'll need to adjust your strategy to:
Track whether a trade has already been taken on a given day.
Reset this tracking at the start of each new trading day.
Below, I'll guide you through the necessary modifications to your code to meet your requirements. We'll update the EnhancedICTStrategyWithAI class to implement this functionality.
Step 1: Modify the Strategy to Track Trades Per Day
First, we need to introduce variables to keep track of:
The current trading day.
Whether a trade has been taken today.
Code Changes
Add the following initialization in your __init__ method:
class EnhancedICTStrategyWithAI(bt.Strategy):
# ... existing code ...
def __init__(self):
# ... existing code ...
# Initialize current day and trade tracking
self.current_day = None
self.trade_taken_today = False
Step 2: Reset Trade Tracking at the Start of a New Day
Within the next() method, we need to check if a new day has begun and reset self.trade_taken_today accordingly.
Code Changes
Update the beginning of your next() method:
def next(self):
dt = self.datas[0].datetime.datetime(0)
date = dt.date()
# Reset trade_taken_today at the start of a new day
if self.current_day is None or date != self.current_day:
self.current_day = date
self.trade_taken_today = False
# Check if within Kill Zone
if not is_within_kill_zone(dt):
return
# ... rest of your code ...
Step 3: Adjust Entry Conditions to Allow Only One Trade Per Day
Modify the logic that decides when to enter a trade to ensure that no more than one trade is taken per day.
Code Changes
Update the entry condition in your next() method:
def next(self):
# ... existing code ...
# Simplify Entry Conditions
if not self.position and not self.trade_taken_today:
if is_within_kill_zone(dt):
self.enter_long_position()
self.trade_taken_today = True
elif self.position.size > 0:
# Close position at 11 AM Paris Time
paris_timezone = pytz.timezone('Europe/Paris')
dt_paris = dt.astimezone(paris_timezone)
if dt_paris.time() >= datetime.time(11, 0):
self.close_position()
By adding and not self.trade_taken_today to the condition, we ensure that the strategy will only enter a trade if no trade has been taken yet during the current day.
When we close a position, we don't want to reset self.trade_taken_today, as we aim to take only one trade per day regardless of whether it was closed early.
No Changes Needed
Since self.trade_taken_today remains True after closing a position, no further changes are necessary here.
Final Adjusted Strategy Code
Here is the updated EnhancedICTStrategyWithAI class with all the modifications:
class EnhancedICTStrategyWithAI(bt.Strategy):
params = dict(
verbose=True, # Enable verbose for debugging
max_risk_per_trade=0.01, # 1% risk per trade
sequence_length=sequence_length,
features=features,
model=None,
scaler=None
)
def __init__(self):
self.trade_journal = []
self.order = None
self.sequence_length = self.params.sequence_length
self.features = self.params.features
# Access data
self.data_open = self.datas[0].open
self.data_high = self.datas[0].high
self.data_low = self.datas[0].low
self.data_close = self.datas[0].close
# Indicators
self.atr = self.datas[0].ATR
self.inst_flow = self.datas[0].Institutional_Flow
self.rsi = self.datas[0].RSI
# AI Model
self.model = self.params.model
self.scaler = self.params.scaler
self.past_data = []
# Initialize current day and trade tracking
self.current_day = None
self.trade_taken_today = False
def next(self):
dt = self.datas[0].datetime.datetime(0)
date = dt.date()
# Reset trade_taken_today at the start of a new day
if self.current_day is None or date != self.current_day:
self.current_day = date
self.trade_taken_today = False
# Check if within Kill Zone
if not is_within_kill_zone(dt):
return
# Collect features for AI prediction
current_features = [
self.data_close[0],
self.rsi[0],
self.atr[0],
self.inst_flow[0],
int(self.datas[0].BOS_Up[0]),
int(self.datas[0].BOS_Down[0]),
int(self.datas[0].CHoCH_Up[0]),
int(self.datas[0].CHoCH_Down[0]),
int(self.datas[0].Equal_Highs[0]),
int(self.datas[0].Equal_Lows[0]),
dt.hour
]
self.past_data.append(current_features)
if len(self.past_data) < self.sequence_length:
return
elif len(self.past_data) > self.sequence_length:
self.past_data.pop(0)
# Prepare AI input
X_ai = np.array(self.past_data)
X_ai_scaled = self.scaler.transform(X_ai)
X_ai_scaled = X_ai_scaled.reshape(1, self.sequence_length, len(self.features))
ai_prediction = self.model.predict(X_ai_scaled)[0][0]
# Adjust AI signal threshold to be less strict
ai_signal = ai_prediction > 0.4 # Reduced threshold to 0.4
# Simplify Entry Conditions
if not self.position and not self.trade_taken_today:
if is_within_kill_zone(dt):
self.enter_long_position()
self.trade_taken_today = True
elif self.position.size > 0:
# Close position at 11 AM Paris Time
paris_timezone = pytz.timezone('Europe/Paris')
dt_paris = dt.astimezone(paris_timezone)
if dt_paris.time() >= datetime.time(11, 0):
self.close_position()
def enter_long_position(self):
atr = self.atr[-1]
stop_loss_price = self.data_close[0] - 1 * atr
take_profit_price = self.data_close[0] + 1 * atr # Adjusted to 1x ATR for quicker TP
stop_loss_pips = (self.data_close[0] - stop_loss_price) * 10000 # Convert to pips
position_size = self.calculate_position_size(stop_loss_pips)
position_size = max(position_size, 0.01) # Minimum position size
position_size = min(position_size, 10) # Maximum position size
self.order = self.buy(size=position_size)
self.log_trade('BUY', position_size)
# Set Stop Loss and Take Profit
self.sell(exectype=bt.Order.Stop, price=stop_loss_price, size=position_size)
self.sell(exectype=bt.Order.Limit, price=take_profit_price, size=position_size)
print(f"Entering long position at {self.data_close[0]} on {self.datas[0].datetime.datetime(0)}")
def close_position(self):
self.order = self.close()
position_type = 'LONG' if self.position.size > 0 else 'SHORT'
self.log_trade(f'CLOSE {position_type}', abs(self.position.size))
print(f"Closing position at {self.data_close[0]} on {self.datas[0].datetime.datetime(0)}")
def calculate_position_size(self, stop_loss_pips):
# Position size in lots
risk_amount = self.broker.getvalue() * self.params.max_risk_per_trade
pip_value = 10 # For standard lots in major currency pairs
position_size = risk_amount / (stop_loss_pips * pip_value)
return position_size
def log_trade(self, action, position_size):
dt = self.datas[0].datetime.datetime(0)
price = self.data_close[0]
log_entry = {
'Date': dt,
'Action': action,
'Price': price,
'Position Size': position_size
}
self.trade_journal.append(log_entry)
if self.params.verbose:
print(f"{dt} - {action} at {price}, Position Size: {position_size}")
print(f"Trade logged: {log_entry}")
Explanation
Trade Tracking Variables:
self.current_day keeps track of the date of the last processed data point.
self.trade_taken_today indicates whether a trade has been taken on self.current_day.
Resetting Trade Tracking:
At the start of each new day (when date != self.current_day), we reset self.trade_taken_today to False.
Modified Entry Condition:
Now, the strategy checks not self.trade_taken_today before entering a new position, ensuring only one trade per day.
Testing the Changes
To verify that the strategy now only takes one trade per currency pair between 9 AM and 11 AM, you can:
Run the backtest as you normally would.
Examine the Trade Journal to ensure that only one trade per day is recorded for each pair.
The trade journal entries should have timestamps between 9 AM and 11 AM Paris Time.
There should be at most one 'BUY' action per day.
Additional Considerations
Time Zones: Ensure that your data's timestamps align with the Paris Time Zone, especially if your data is in UTC. The is_within_kill_zone(dt) function should account for time zone conversions, which you've already implemented.
AI Predictions: Currently, the AI prediction (ai_signal) isn't affecting trade entries due to the simplified entry condition. If you wish to include the AI signal in your entry logic, you could modify the entry condition like this:
if not self.position and not self.trade_taken_today and ai_signal:
if is_within_kill_zone(dt):
self.enter_long_position()
self.trade_taken_today = True
Trade Size: The code calculates a position size based on risk management rules. Ensure that these calculations align with your definition of a "big trade".
Conclusion
By making these modifications, your strategy will now comply with the requirement of taking only one big trade between 9 AM and 11 AM per currency pair. The strategy resets the trade tracking at the start of each new trading day, ensuring adherence to your specified trading window.
Feel free to ask if you have any questions or need further assistance with your script!