Help with Correctly Coding Stop Loss in thinkScript - Positions Not Closing Reliably

Taka

New member
Title: Help with Correctly Coding SL and TP in thinkScript - Positions Not Closing Reliably

Hello everyone,

I'm working on a thinkScript strategy for trading /MNQ futures, and I'm having issues with the stop-loss logic. Sometimes, the stop-loss order does not trigger as expected, leaving positions open when the price hits or crosses the stop-loss level. I suspect the issue might be related to how I'm defining the conditions or the order execution in thinkScript, but I could use some expert eyes to pinpoint the problem and suggest a fix.

Below is the relevant code snippet for position management, including the stop-loss and take-profit logic:

Code:
# Position Management
# Calculate fixed stop loss based on risk percentage
def accountSize = 10000;  # Example account size
def maxRiskPercent = 1;   # 1% risk per trade
def maxRiskDollars = accountSize * (maxRiskPercent / 100);
def contractSize = 1;     # 1 contract for /MNQ
def pointValue = 2;       # $2 per point for /MNQ
def stopLossPoints = Max(1, maxRiskDollars / (contractSize * pointValue)); # SL in points, minimum 1 point
def takeProfitPoints = stopLossPoints * 2; # Example: 2:1 reward-to-risk ratio

def isLong = GetQuantity() > 0;
def isShort = GetQuantity() < 0;

# Entry orders with commissions
AddOrder(OrderType.BUY_AUTO, finalBuySignal, open[-1], 1, Color.GREEN, Color.GREEN);
AddOrder(OrderType.SELL_AUTO, finalSellSignal, open[-1], 1, Color.RED, Color.RED);

# Stop loss and take profit for LONG positions
AddOrder(OrderType.SELL_TO_CLOSE, isLong and low <= EntryPrice() - stopLossPoints, EntryPrice() - stopLossPoints, 1, Color.RED, Color.RED);
AddOrder(OrderType.SELL_TO_CLOSE, isLong and high >= EntryPrice() + takeProfitPoints, EntryPrice() + takeProfitPoints, 1, Color.GREEN, Color.GREEN);


# Stop loss and take profit for SHORT positions
AddOrder(OrderType.BUY_TO_CLOSE, isShort and high >= EntryPrice() + stopLossPoints, EntryPrice() + stopLossPoints, 1, Color.RED, Color.RED);
AddOrder(OrderType.BUY_TO_CLOSE, isShort and low <= EntryPrice() - takeProfitPoints, EntryPrice() - takeProfitPoints, 1, Color.GREEN, Color.GREEN);


The issue occurs intermittently: when the price reaches or exceeds the stop-loss level (e.g., low <= EntryPrice() - stopLossPoints for longs), the SELL_TO_CLOSE or BUY_TO_CLOSE order doesn't always execute, and the position remains open.


Captura de ****alla 2025-06-19 100127.png

Are there best practices for coding stop-losses in thinkScript to avoid missed executions, especially for futures like /MNQ?

Any suggestions for improving the code or debugging this issue would be greatly appreciated. If you need more context (e.g., the full strategy code or how finalBuySignal/finalSellSignal are defined), let me know, and I can provide additional details.

Thanks in advance for your help!
 
@Taka Greetings... I am assuming that you are referring to using a Strategy for testing purposes as they do not perform actual trades...

That being said, Strategies for testing do not always reflect the same performance as live trades because the Strategy only fires Buys and Sells after the candle closes... This point in itself demonstrates how unreliable the actual use of Strategies is if trying to base live trades off of Strategy signals... I have all but given up on utilizing the Strategy feature within TOS for the reasons mentioned...

Also, your image is too small to be of any benefit... It also doesn't display any Buy or Sell orders based on your Strategy...

Before we delve further into this code, please explain what your intentions are for this Strategy code... Is it for proof of concept or are you considering basing live trades off of the signals produce - which I would strongly advised against for the reasons provided...
 
Last edited:

Join useThinkScript to post your question to a community of 21,000+ developers and traders.

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

87k+ Posts
323 Online
Create Post

Similar threads

Similar threads

The Market Trading Game Changer

Join 2,500+ subscribers inside the useThinkScript VIP Membership Club
  • Exclusive indicators
  • Proven strategies & setups
  • Private Discord community
  • ‘Buy The Dip’ signal alerts
  • Exclusive members-only content
  • Add-ons and resources
  • 1 full year of unlimited support

Frequently Asked Questions

What is useThinkScript?

useThinkScript is the #1 community of stock market investors using indicators and other tools to power their trading strategies. Traders of all skill levels use our forums to learn about scripting and indicators, help each other, and discover new ways to gain an edge in the markets.

How do I get started?

We get it. Our forum can be intimidating, if not overwhelming. With thousands of topics, tens of thousands of posts, our community has created an incredibly deep knowledge base for stock traders. No one can ever exhaust every resource provided on our site.

If you are new, or just looking for guidance, here are some helpful links to get you started.

What are the benefits of VIP Membership?
VIP members get exclusive access to these proven and tested premium indicators: Buy the Dip, Advanced Market Moves 2.0, Take Profit, and Volatility Trading Range. In addition, VIP members get access to over 50 VIP-only custom indicators, add-ons, and strategies, private VIP-only forums, private Discord channel to discuss trades and strategies in real-time, customer support, trade alerts, and much more. Learn all about VIP membership here.
How can I access the premium indicators?
To access the premium indicators, which are plug and play ready, sign up for VIP membership here.
Back
Top