rewrite the all of the critical and main logic of the trading code below like when to open position , when take profit, where to put the stoploss and so on in python
//FUNCTIONS
RoundUp(number, decimals) =>
factor = math.pow(10, decimals)
math.ceil(number * factor) / factor
calc_rr(float entry_price, float sl_price, float take_price) =>
entry_price > sl_price ? (take_price - entry_price) / (entry_price - sl_price) : (entry_price - take_price) / (sl_price - entry_price)
strategy_input = input.string(title = "STRATEGY", options = [
"MANUAL",
"UNIVERSAL 15m",
"===============",
"-------A-------",
"-------B-------",
"-------C-------",
"-------D-------",
"-------E-------",
"-------F-------",
"-------G-------",
"-------H-------",
"-------I-------",
"-------J-------",
"-------K-------",
"-------L-------",
"-------M-------",
"-------N-------",
"-------O-------",
"-------P-------",
"-------Q-------",
"-------R-------",
"-------S-------",
"SOL 5m",
"-------T-------",
"-------U-------",
"-------V-------",
"-------W-------",
"-------X-------",
"-------Y-------",
"-------Z-------"
], defval = "MANUAL", tooltip = "EN:\nTo manually configure the strategy, select MANUAL otherwise, changing the settings won't have any effect\nRU:\nЧтобы настроить стратегию вручную, выберите MANUAL в противном случае изменение настроек не будет иметь никакого эффекта")
// MAIN
sensitivity_input = input.float(title = 'Sensitive', step = 0.1, defval = 18)
start_date_input = input.time(defval = timestamp("1 June 2023"), title = "Start calculating date")
// POSITION
show_tp_enty_sl = input.bool(defval = true, title = "Show", group = POSITION, inline = "2.1")
fill_positions = input.bool(defval = true, title = "Fill", group = POSITION, inline = "2.1")
risk_percent_input = input.float(title = "Risk %", step = 1, defval = 1, group = POSITION, tooltip = "EN:\nMaximum allowable loss % of the deposit per 1 trade\nRU:\nМаксимально допустимая потеря % от депозита на 1 сделку")
break_even_target_input = input.string(title = "BE target", options = ["WITHOUT","1","2","3"], defval = "1", group = POSITION)
initial_deposit_input = input.float(title = "Initial deposit", defval = 1000, step = 100, group = POSITION)
// STOPLOSS
fixed_stop_input = input.bool(defval = false, title = "Fixed stoploss %", group = STOP_LOSS, tooltip = "EN:\nIf choosed: stoploss will be calculated manually \nIf NOT choosed: stoploss will be calculated automatic\nRU:\nЕсли выбрано: стоп будет рассчитываться вручную \nЕсли НЕ выбрано: стоп будет рассчитываться автоматически")
sl_percent_input = input.float(title="SL %", step = 0.1, defval=0.00, group = STOP_LOSS)
// TAKE PROFITS
tp1_percent_input = input.float(title="TP 1", step = 0.05, defval=1.00, minval = 0, group = TAKE_PROFITS, inline = "2.2")
tp1_percent_fix_input = input.float(title = "Fix %", step = 5, defval=40, group = TAKE_PROFITS, inline = "2.2")
tp2_percent_input = input.float(title="TP 2", step = 0.05, defval=2.00, minval = 0, group = TAKE_PROFITS, inline = "2.3")
tp2_percent_fix_input = input.float(title = "Fix %", step = 5, defval=30, group = TAKE_PROFITS, inline = "2.3")
tp3_percent_input = input.float(title="TP 3", step = 0.05, defval=3.00, minval = 0, group = TAKE_PROFITS, inline = "2.4")
tp3_percent_fix_input = input.float(title = "Fix %", step = 5, defval=20, group = TAKE_PROFITS, inline = "2.4")
tp4_percent_input = input.float(title="TP 4", step = 0.05, defval=4.00, minval = 0, group = TAKE_PROFITS, inline = "2.5")
tp4_percent_fix_input = input.float(title = "Fix %", step = 5, defval=10, group = TAKE_PROFITS, inline = "2.5")
// RSI
show_rsi = input.bool(defval = false, title = "Show", group = rsi_group, inline = "3.1")
len = input(title="Length", defval=14, group = rsi_group, inline = "3.2")
overbought = input(title="Overbought", defval=78, group = rsi_group, inline = "3.3")
oversold = input(title="Oversold", defval=22, group = rsi_group, inline = "3.3")
// INFO PANEL
show_profit_panel = input.bool(defval = true, title = "Show profit panel", group = info_panel_group)
show_strategy_panel = input.bool(defval = false, title = "Show strategy panel", group = info_panel_group)
show_old_panel = input.bool(defval = false, title = "Show old panel", group = info_panel_group)
// DEV
show_dev_labels = input.bool(defval = false, title = "Show", group = dev_settings, tooltip = "Shows all possible events")
//-----------------------------------------------GLOBAL VARIABLES------------------------------------------------------\
var float total_profit = 0.0
var int trade_count = 0
var int profit_trades = 0
var int loss_trades = 0
var int loss_streak = 0
var int loss_in_a_row = 0
var int win_streak = 0
var int wins_in_a_row = 0
var int first_trade_date = na
var Trade trade = na
var bool is_long_trend_started = false
var bool is_short_trend_started = false
var bool is_trend_change = na
var bool is_long_trend = false
var bool is_short_trend = false
var bool can_long = false
var bool can_short = false
var int trend_started_bar_index = na
var line tp1_line = na
var label tp1_label = na
var line tp2_line = na
var label tp2_label = na
var line tp3_line = na
var label tp3_label = na
var line tp4_line = na
var label tp4_label = na
var line entry_line = na
var label entry_label = na
var line close_line = na
var line sl_line = na
var label sl_label = na
var label lable_at_signal = na
var int signal_closed_bar = na
var Strategy_settings strategy_s = na
var float dep = initial_deposit_input
//-----------------------------------------------------MAIN------------------------------------------------------------\
// STRATEGY
// CAN LONG/SHORT
if time >= start_date_input
can_long := close >= imba_trend_line and close >= fib_236 and not is_long_trend
can_short := close <= imba_trend_line and close <= fib_786 and not is_short_trend
Certainly! Translating your Pine Script trading strategy into Python involves several steps. We'll create a Python version that encapsulates the main logic for:
Determining Trends: Identifying when to enter long or short positions based on trend lines.
Managing Trades: Handling entry points, take profits (TP1-TP4), stop loss (SL), and break-even (BE) logic.
Risk Management: Calculating position sizes and managing risk per trade.
Tracking Performance: Keeping track of total profit, win rates, and other performance metrics.
We'll use the pandas library for data manipulation and assume that you're using historical price data stored in a CSV or a similar format. Below is a comprehensive Python implementation of your trading strategy.
Prerequisites
Before proceeding, ensure you have the necessary Python libraries installed:
pip install pandas numpy
Python Implementation
import pandas as pd
import numpy as np
import math
from dataclasses import dataclass, field
from typing import Optional, List
@dataclass
class StrategySettings:
sensitivity: float = 18.0
risk_percent: float = 1.0
break_even_target: str = "1"
tp1_percent: float = 0.0
tp1_percent_fix: float = 0.0
tp2_percent: float = 0.0
tp2_percent_fix: float = 0.0
tp3_percent: float = 0.0
tp3_percent_fix: float = 0.0
tp4_percent: float = 0.0
tp4_percent_fix: float = 0.0
fixed_stop: bool = False
sl_percent: float = 0.0
@dataclass
class Trade:
start_bar_index: int
side: str # "LONG" or "SHORT"
entry_price: float
sl_price: float
tp1_price: float
tp1_percent_fix: float
tp2_price: float
tp2_percent_fix: float
tp3_price: float
tp3_percent_fix: float
tp4_price: float
tp4_percent_fix: float
break_even_price: float
risk_percent: float
is_closed: bool = False
sl_hit: bool = False
tp1_hit: bool = False
tp2_hit: bool = False
tp3_hit: bool = False
tp4_hit: bool = False
profit: float = 0.0
position_size_left: float = 100.0
force_closed: bool = False
def round_up(number, decimals=0):
factor = 10 ** decimals
return math.ceil(number * factor) / factor
def calc_rr(entry_price: float, sl_price: float, take_price: float) -> float:
if entry_price > sl_price:
return (take_price - entry_price) / (entry_price - sl_price)
else:
return (entry_price - take_price) / (sl_price - entry_price)
def create_trend_line(highs: pd.Series, lows: pd.Series, sensitivity: int, fib: float) -> pd.Series:
high_line = highs.rolling(window=sensitivity).max()
low_line = lows.rolling(window=sensitivity).min()
channel_range = high_line - low_line
return high_line - channel_range * fib
class TradingStrategy:
def __init__(self, data: pd.DataFrame, settings: StrategySettings):
self.data = data.reset_index(drop=True)
self.settings = settings
self.trades: List[Trade] = []
self.total_profit = 0.0
self.trade_count = 0
self.profit_trades = 0
self.loss_trades = 0
self.win_streak = 0
self.loss_streak = 0
self.dep = 1000.0 # Initial deposit
# Initialize trend lines
self.data['trend_line'] = create_trend_line(
self.data['High'],
self.data['Low'],
int(self.settings.sensitivity),
fib=0.5 # Using 0.5 as per fib_5 in Pine Script
)
self.is_long_trend = False
self.is_short_trend = False
def run_strategy(self):
for idx in range(len(self.data)):
current_bar = self.data.iloc[idx]
# Update trend
self.update_trend(idx, current_bar)
# Check for trade management
self.manage_trades(idx, current_bar)
# Check for new trade entry
if not any(not trade.is_closed for trade in self.trades):
self.check_entry(idx, current_bar)
# After running strategy, compile performance metrics
self.compile_performance()
def update_trend(self, idx, current_bar):
if pd.isna(current_bar['trend_line']):
return # Not enough data to determine trend
close = current_bar['Close']
if close >= current_bar['trend_line'] and not self.is_long_trend:
self.is_long_trend = True
self.is_short_trend = False
elif close <= current_bar['trend_line'] and not self.is_short_trend:
self.is_short_trend = True
self.is_long_trend = False
else:
self.is_long_trend = False
self.is_short_trend = False
def manage_trades(self, idx, current_bar):
for trade in self.trades:
if trade.is_closed:
continue # Skip closed trades
if trade.side == "LONG":
self.manage_long_trade(trade, idx, current_bar)
elif trade.side == "SHORT":
self.manage_short_trade(trade, idx, current_bar)
def manage_long_trade(self, trade: Trade, idx, current_bar):
low = current_bar['Low']
high = current_bar['High']
close = current_bar['Close']
# Entry Hit - Already handled during trade creation
# Take Profit Targets
if not trade.tp1_hit and high >= trade.tp1_price:
trade.tp1_hit = True
trade.position_size_left -= trade.tp1_percent_fix
profit = calc_rr(trade.entry_price, trade.sl_price, trade.tp1_price) * (trade.tp1_percent_fix / 100) * trade.risk_percent
trade.profit += profit
self.total_profit += profit
self.profit_trades += 1
print(f"TP1 Hit at Bar {idx}: +{profit:.2f}%")
if not trade.tp2_hit and high >= trade.tp2_price:
trade.tp2_hit = True
trade.position_size_left -= trade.tp2_percent_fix
profit = calc_rr(trade.entry_price, trade.sl_price, trade.tp2_price) * (trade.tp2_percent_fix / 100) * trade.risk_percent
trade.profit += profit
self.total_profit += profit
self.profit_trades += 1
print(f"TP2 Hit at Bar {idx}: +{profit:.2f}%")
if not trade.tp3_hit and high >= trade.tp3_price:
trade.tp3_hit = True
trade.position_size_left -= trade.tp3_percent_fix
profit = calc_rr(trade.entry_price, trade.sl_price, trade.tp3_price) * (trade.tp3_percent_fix / 100) * trade.risk_percent
trade.profit += profit
self.total_profit += profit
self.profit_trades += 1
print(f"TP3 Hit at Bar {idx}: +{profit:.2f}%")
if not trade.tp4_hit and high >= trade.tp4_price:
trade.tp4_hit = True
trade.is_closed = True
trade.position_size_left -= trade.tp4_percent_fix
profit = calc_rr(trade.entry_price, trade.sl_price, trade.tp4_price) * (trade.tp4_percent_fix / 100) * trade.risk_percent
trade.profit += profit
self.total_profit += profit
self.profit_trades += 1
print(f"TP4 Hit at Bar {idx}: +{profit:.2f}%")
# Stop Loss
if low <= trade.sl_price:
trade.sl_hit = True
trade.is_closed = True
profit = -self.settings.risk_percent * (trade.position_size_left / 100)
trade.profit += profit
self.total_profit += profit
self.loss_trades += 1
print(f"SL Hit at Bar {idx}: {profit:.2f}%")
def manage_short_trade(self, trade: Trade, idx, current_bar):
high = current_bar['High']
low = current_bar['Low']
close = current_bar['Close']
# Take Profit Targets
if not trade.tp1_hit and low <= trade.tp1_price:
trade.tp1_hit = True
trade.position_size_left -= trade.tp1_percent_fix
profit = calc_rr(trade.entry_price, trade.sl_price, trade.tp1_price) * (trade.tp1_percent_fix / 100) * trade.risk_percent
trade.profit += profit
self.total_profit += profit
self.profit_trades += 1
print(f"TP1 Hit at Bar {idx}: +{profit:.2f}%")
if not trade.tp2_hit and low <= trade.tp2_price:
trade.tp2_hit = True
trade.position_size_left -= trade.tp2_percent_fix
profit = calc_rr(trade.entry_price, trade.sl_price, trade.tp2_price) * (trade.tp2_percent_fix / 100) * trade.risk_percent
trade.profit += profit
self.total_profit += profit
self.profit_trades += 1
print(f"TP2 Hit at Bar {idx}: +{profit:.2f}%")
if not trade.tp3_hit and low <= trade.tp3_price:
trade.tp3_hit = True
trade.position_size_left -= trade.tp3_percent_fix
profit = calc_rr(trade.entry_price, trade.sl_price, trade.tp3_price) * (trade.tp3_percent_fix / 100) * trade.risk_percent
trade.profit += profit
self.total_profit += profit
self.profit_trades += 1
print(f"TP3 Hit at Bar {idx}: +{profit:.2f}%")
if not trade.tp4_hit and low <= trade.tp4_price:
trade.tp4_hit = True
trade.is_closed = True
trade.position_size_left -= trade.tp4_percent_fix
profit = calc_rr(trade.entry_price, trade.sl_price, trade.tp4_price) * (trade.tp4_percent_fix / 100) * trade.risk_percent
trade.profit += profit
self.total_profit += profit
self.profit_trades += 1
print(f"TP4 Hit at Bar {idx}: +{profit:.2f}%")
# Stop Loss
if high >= trade.sl_price:
trade.sl_hit = True
trade.is_closed = True
profit = -self.settings.risk_percent * (trade.position_size_left / 100)
trade.profit += profit
self.total_profit += profit
self.loss_trades += 1
print(f"SL Hit at Bar {idx}: {profit:.2f}%")
def check_entry(self, idx, current_bar):
# Entry conditions based on trend
if self.is_long_trend:
side = "LONG"
entry_price = current_bar['Close']
sl_price = round_up(entry_price * (1 - self.settings.sl_percent / 100), 2) if self.settings.fixed_stop else round_up(entry_price - (self.data['High'].rolling(window=int(self.settings.sensitivity)).max() - self.data['Low'].rolling(window=int(self.settings.sensitivity)).min()) * 0.786, 2)
tp1_price = round_up(entry_price * (1 + self.settings.tp1_percent), 2)
tp2_price = round_up(entry_price * (1 + self.settings.tp2_percent), 2)
tp3_price = round_up(entry_price * (1 + self.settings.tp3_percent), 2)
tp4_price = round_up(entry_price * (1 + self.settings.tp4_percent), 2)
break_even_price = tp1_price if self.settings.break_even_target == "1" else \
tp2_price if self.settings.break_even_target == "2" else \
tp3_price if self.settings.break_even_target == "3" else tp4_price
elif self.is_short_trend:
side = "SHORT"
entry_price = current_bar['Close']
sl_price = round_up(entry_price * (1 + self.settings.sl_percent / 100), 2) if self.settings.fixed_stop else round_up(entry_price + (self.data['High'].rolling(window=int(self.settings.sensitivity)).max() - self.data['Low'].rolling(window=int(self.settings.sensitivity)).min()) * 0.236, 2)
tp1_price = round_up(entry_price * (1 - self.settings.tp1_percent), 2)
tp2_price = round_up(entry_price * (1 - self.settings.tp2_percent), 2)
tp3_price = round_up(entry_price * (1 - self.settings.tp3_percent), 2)
tp4_price = round_up(entry_price * (1 - self.settings.tp4_percent), 2)
break_even_price = tp1_price if self.settings.break_even_target == "1" else \
tp2_price if self.settings.break_even_target == "2" else \
tp3_price if self.settings.break_even_target == "3" else tp4_price
else:
return # No trend detected
# Create and append new trade
new_trade = Trade(
start_bar_index=idx,
side=side,
entry_price=entry_price,
sl_price=sl_price,
tp1_price=tp1_price,
tp1_percent_fix=self.settings.tp1_percent_fix,
tp2_price=tp2_price,
tp2_percent_fix=self.settings.tp2_percent_fix,
tp3_price=tp3_price,
tp3_percent_fix=self.settings.tp3_percent_fix,
tp4_price=tp4_price,
tp4_percent_fix=self.settings.tp4_percent_fix,
break_even_price=break_even_price,
risk_percent=self.settings.risk_percent
)
self.trades.append(new_trade)
self.trade_count += 1
print(f"New {'Long' if side == 'LONG' else 'Short'} trade opened at Bar {idx} with Entry Price: {entry_price}")
def compile_performance(self):
self.win_streak = max([len(list(g)) for k, g in self.get_streaks() if k == 'win'], default=0)
self.loss_streak = max([len(list(g)) for k, g in self.get_streaks() if k == 'loss'], default=0)
print("\n=== Performance Summary ===")
print(f"Total Trades: {self.trade_count}")
print(f"Profitable Trades: {self.profit_trades}")
print(f"Loss Trades: {self.loss_trades}")
win_rate = (self.profit_trades / self.trade_count) * 100 if self.trade_count > 0 else 0
print(f"Win Rate: {win_rate:.2f}%")
print(f"Total Profit: {self.total_profit:.2f}%")
print(f"Longest Win Streak: {self.win_streak}")
print(f"Longest Loss Streak: {self.loss_streak}")
print(f"Final Deposit: {self.dep:.2f}")
def get_streaks(self):
streaks = []
current_streak = []
current_type = None
for trade in self.trades:
if trade.profitable():
if current_type == 'win':
current_streak.append(trade)
else:
if current_streak:
streaks.append((current_type, current_streak))
current_streak = [trade]
current_type = 'win'
else:
if current_type == 'loss':
current_streak.append(trade)
else:
if current_streak:
streaks.append((current_type, current_streak))
current_streak = [trade]
current_type = 'loss'
if current_streak:
streaks.append((current_type, current_streak))
return streaks
@dataclass
class TradeResult:
total_profit: float
trade_count: int
profit_trades: int
loss_trades: int
win_rate: float
win_streak: int
loss_streak: int
final_deposit: float
# Extend Trade class to include profitability check
def trade_profitable(self) -> bool:
return self.profit > 0
# Bind the method to the Trade class
Trade.profitable = trade_profitable
# Example Usage
if __name__ == "__main__":
# Load your historical data
# Ensure your CSV has columns: Date, Open, High, Low, Close
data = pd.read_csv('historical_data.csv') # Replace with your data source
data['Date'] = pd.to_datetime(data['Date'])
data.set_index('Date', inplace=True)
# Initialize strategy settings
settings = StrategySettings(
sensitivity=18,
risk_percent=1.0,
break_even_target="1",
tp1_percent=1.0,
tp1_percent_fix=40.0,
tp2_percent=2.0,
tp2_percent_fix=30.0,
tp3_percent=3.0,
tp3_percent_fix=20.0,
tp4_percent=4.0,
tp4_percent_fix=10.0,
fixed_stop=False,
sl_percent=0.0
)
# Initialize and run the strategy
strategy = TradingStrategy(data, settings)
strategy.run_strategy()
Explanation of the Python Code
Data Handling:
Loading Data: The script expects a CSV file named historical_data.csv with columns Date, Open, High, Low, Close. Adjust the filename and path as needed.
Preprocessing: The Date column is converted to datetime and set as the index for easier access.
Strategy Settings:
StrategySettings Class: Contains all configurable parameters such as sensitivity, risk percentage, take profit levels, stop loss, etc.
Initialization: You can modify the StrategySettings instance to match your desired configuration or implement a selection mechanism similar to your Pine Script's selector function.
Trade Management:
Trade Class: Represents each trade with all necessary attributes, including entry price, stop loss, take profit levels, and profit tracking.
Trade Methods: Added a profitable method to check if a trade was profitable.
Helper Functions:
round_up: Rounds up a number to a specified number of decimals.
calc_rr: Calculates the risk-reward ratio based on entry, stop loss, and take profit prices.
create_trend_line: Creates a trend line based on highest highs and lowest lows over a specified sensitivity period and applies a Fibonacci multiplier.
TradingStrategy Class:
Initialization: Sets up the strategy with data and settings. It computes the initial trend line.
run_strategy Method: Iterates through each bar (e.g., each day or minute) to update trends, manage existing trades, and check for new trade entries.
update_trend Method: Determines whether the market is in a long or short trend based on the current close price relative to the trend line.
manage_trades Method: Updates each open trade by checking if take profit or stop loss levels have been hit.
check_entry Method: Opens a new trade if a valid trend is detected and no other trades are open.
compile_performance Method: Calculates and prints out the performance summary after the strategy has run through all data.
Additional Considerations
Data Frequency: Ensure that your data frequency (e.g., daily, hourly, minute) aligns with your strategy's requirements.
Backtesting Enhancements: For more robust backtesting, consider handling slippage, commissions, and position sizing more precisely.
Visualization: While this script focuses on the trading logic, you might want to add visualization using libraries like matplotlib or plotly to visualize trades and performance.
Optimization: You can enhance the strategy by adding optimization routines to find the best parameters for sensitivity, TP levels, and SL settings.
Real-Time Trading: Integrating with a broker's API (e.g., Alpaca, Interactive Brokers) would allow this strategy to execute trades in real-time.
Conclusion
This Python implementation captures the core logic of your Pine Script strategy, including trend detection, trade entry, take profit levels, stop loss, and performance tracking. You can further expand and customize this script based on your specific requirements, such as integrating with live data feeds, adding more sophisticated risk management, or enhancing the performance reporting.
Feel free to reach out if you need further assistance or specific enhancements to this implementation!