I have been working on a script that will take TP at 42 ticks then close 9 contracts leaving 1 contract left and move stop loss to break even. I feel like I’m close! But it’s not working when I test. Heres the code if anyone has any ideas on what I’m doing wrong
//@version=5
strategy("Close 9 Contracts at 42 Ticks & Move Stop to Break Even", overlay=true)
// Inputs for customization
tick_size = input.float(0.25, title="Tick Size") // Set tick size for the instrument
close_contracts = input.int(9, title="Contracts to Close at Target")
total_contracts = input.int(10, title="Total Contracts in Position")
partial_target_ticks = input.float(42, title="Partial Target (ticks)")
initial_stop_loss_ticks = input.float(20, title="Initial Stop-Loss (ticks)")
// Calculations
entry_price = strategy.position_avg_price
partial_target = entry_price + (partial_target_ticks * tick_size) * (strategy.position_size > 0 ? 1 : -1)
break_even_price = entry_price
initial_stop_loss = entry_price - (initial_stop_loss_ticks * tick_size) * (strategy.position_size > 0 ? 1 : -1)
// Variables for tracking state
var bool partial_closed = false
// Partial exit and break-even logic
if strategy.position_size > 0
// Close partial contracts at target
if not partial_closed and strategy.position_size == total_contracts and close >= partial_target
strategy.exit("Partial Close", from_entry="Buy", qty=close_contracts, limit=partial_target)
partial_closed := true // Mark as partially closed
// Move stop-loss to break-even for remaining position after partial close
if partial_closed and strategy.position_size == total_contracts - close_contracts
strategy.exit("Break Even Stop", from_entry="Buy", stop=break_even_price)
// Reset state if no position is open
if strategy.position_size == 0
partial_closed := false
// Plot visualizations
plot(entry_price, title="Entry Price", color=color.blue, style=plot.style_circles)
plot(partial_target, title="Partial Target", color=color.green, style=plot.style_line)
plot(initial_stop_loss, title="Initial Stop Loss", color=color.red, style=plot.style_line)