Skip to content

ThinkOrSwim Platform's Semi Trade Automation ‐ Intra Day Trading

gitricko edited this page Dec 12, 2025 · 1 revision

Exits after Inmerelo using 1 min chart on 6EMA

# Scripts run on a 1-minute chart.

input hardstop_price = X.X; # The fixed price for your hard stop-loss

input sell_b4_close = Yes; # Enable the end-of-day exit logic
input emaConfirmationBars = 2; # How many consecutive 1-min bars must close below the EMA
input minB4Close = 2; # How many minutes before close; to sell
input emaLength = 6;           # The length for the EMA stop
input aggregationPeriod = AggregationPeriod.FIVE_MIN; # Explicitly use 5-minute data for the EMA
input closeTime = 1600;        # Market close time (e.g., 4:00 PM ET)

# --- Constants for Time Logic ---
def time_to_market_close_seconds = minB4Close * 60;

# --- 1. Hard Stop-Loss Logic ---
# Condition if the 1-minute close price falls below the fixed hardstop_price, sell immediately.
def stop_loss = close < hardstop_price;

# --- 2. EMA Stop Logic (Calculated on 5-min data) ---
# Calculate the Exponential Moving Average (EMA) using the specified 5-minute aggregation period.
def EMA = ExpAverage(close(period = aggregationPeriod), emaLength);

# New logic for counting consecutive closes below the EMA:
def isBelowEMA = close < EMA;


# Use the 'rec' keyword for recursive variables (equivalent to CompoundValue in this context)
# The logic is: If the current bar is below the EMA, increment the previous count (barsBelowEMA[1]), 
# otherwise, reset the count to 0. The default value is 0.
rec barsBelowEMA = if isBelowEMA then barsBelowEMA[1] + 1 else 0;

# The exit condition now requires the count to equal or exceed the confirmation input.
def ema_stop = barsBelowEMA >= emaConfirmationBars;


# --- 3. End-of-Day Exit Logic ---
# Condition to sell unconditionally if enabled when it is N minute or less before close
# Check if we are within N minute of the market close time (1600)
def secondsToClose = SecondsTillTime(closeTime);
def forced_end_of_day_exit = if sell_b4_close and secondsToClose > 0 and secondsToClose <= time_to_market_close_seconds then 1 else 0;

# --- Combined Trigger ---
# Plot 'trigger' if ANY of these conditions are true:
# (Hard Stop-Loss OR EMA Stop OR Forced End-of-Day Exit)
plot trigger = stop_loss or ema_stop or forced_end_of_day_exit;

# --- Optional Plotting (Coloring) ---
trigger.DefineColor("Stop-Loss Triggered", Color.RED);
trigger.DefineColor("EMA Stop Triggered", Color.ORANGE);
trigger.DefineColor("Forced Close Triggered", Color.LIGHT_GRAY);
trigger.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
trigger.AssignValueColor(
    if stop_loss then trigger.Color("Stop-Loss Triggered")
    else if ema_stop then trigger.Color("EMA Stop Triggered")
    else trigger.Color("Forced Close Triggered")
);

Clone this wiki locally