Hard stop and trailing profit target

Bridge001

New member
I am new to this community and I am by no means a experienced coder. I have been working for some time to delping a stratgey that I want use to trade small cap gapping stocks whne on the uptrend each morning. I trade using the 1-min chart. What I need help with is the hard stop and (ideally) a true trailing profit.

Hard Stop
The strategy will set a hard stop but the hard stop updates everytime there is a new buy signal. I have tried everyway I know how to stop the stratgey from generating new buy signals whn there is already an open position but have not had success with that. SO the result is that the hard stop actually then becomes a moving stop going upwards and downwards. Obviously if the hard stop moves down then the strategy fails to stop out at the original stop that was set when a positioned was opened resulting in a more than planed loss.

Trailing Profit
I have a profit target set forth in the strategy but I would like to use a trailing profit instead but I am having no luck getting one that works like what I would expect it to. Because the hard stop also moves upwards is serves sort of as a trailing stop but that isn't the intention. I'm sure my strategy and code will look laughable to most but I am open to and appreciate any input on my questions and also any other general advise or input is certainly welcomed as well. Thanks in advance!



thinkscript code


CSS:
input stockPrice = close;
input averageType = AverageType.WILDERS;
input allowMultiplePositions = No;

def openQuantity = GetQuantity();
def hasOpenPosition = openQuantity > 0;

# Tweakable Parameters based on stock price
def minPctDifference;
def maxSpread;
def minAvgVolume;
def fixedSharesRange;
def currentRange; # Used in Profit Target calculation
def bodyLow = if close < open then close else open;

#       Stocks under $.50
if (stockPrice < .80) {
    minPctDifference = .0005;
    currentRange = Average(high - Low,8);
    maxSpread = 0.03;
    minAvgVolume = 7000;
    fixedSharesRange = 500;
    profitTarget = 0.0; # Not Used
    stopLossPct = 0.0; # Not Used
    atrMultiplier = 0.0;# Not Used

#        Stocks $.50 - $3
} else if (stockPrice >=.80 and stockprice <= 3.0) {
    minPctDifference = .005;
    currentRange = Average(high - low,8);
    maxSpread = 0.03;
    minAvgVolume = 5000;
    fixedSharesRange = 250;
    profitTarget = 0.0; # Not Used
    stopLossPct = 0.0; # Not Used
    atrMultiplier = 0.0; # Not Used

#      Stocks $3 - $5
} else if (stockPrice >=3.0 and stockprice <= 5.0) {
    minPctDifference = .0005;
    currentRange = Average(high - low, 8);
    maxSpread = 0.03;
    minAvgVolume = 7000;
    fixedSharesRange = 100;
    profitTarget = 0.0; # Not Used
    stopLossPct = .00; # Not Used
    atrMultiplier = 0.0; # Not Used

#          Stocks $5 - $9
#        <5             10-25       25-50     >100
# PT  .005/.005      .0005/.005     .05        .05 
# SL  .0005/.0005    .003/.005      .0005      .0005
# MP  .005/.0005     .0005/.0005    .005       .005

} else if (stockPrice >= 5.0 and stockPrice <= 9.0) {
    minPctDifference = .05;
    currentRange = Average(high - low, 6);
    maxSpread = 0.05;
    minAvgVolume = 7000;
    fixedSharesRange = 100;
    profitTarget = 0.0; # Not Used
    stopLossPct = 0.0; # Not Used
    atrMultiplier = 0.0; # Not Used

#          Stocks >$9
#     <5             10-25          25-50       >100 (increase spreads= more trades)
# PT                                            .05/.05
# SL                                            .005/.005
# MP                                            .0005/.05

} else {
    minPctDifference = .0005;
    currentRange = Average(high - low, 8);
    maxSpread = 0.5;
    minAvgVolume = 7000;
    fixedSharesRange = 100;
    profitTarget = 0.0; # Not Used
    stopLossPct = 0.0; # Not Used
    atrMultiplier = 0.0; # Not Used
}

# Parameters changed less frequently
input timeFilterHour = 645;
input lookbackPeriod = 3; # Used in double bottom detection & HardStop
input volumeAvgPeriod = 3;

# Bid, Ask, and Spread
def bid = close(priceType = PriceType.BID);
def ask = close(priceType = PriceType.ASK);
def spread = ask - bid;
def spreadCondition = spread <= maxSpread;

# Double Bottom and Volume Check
def doubleBottom = low >= Lowest(low, lookbackPeriod)[-1] and (low - Lowest(low, lookbackPeriod)[-1]) / Lowest(low, lookbackPeriod)[-1] <= minPctDifference;
def volumeCheck = Average(volume, volumeAvgPeriod) >= minAvgVolume;

# Time Filter
def timeFilter = SecondsFromTime(timeFilterHour) >= 0;

# Buy Signal
def buySignal = (allowMultiplePositions or !hasOpenPosition) and doubleBottom and volumeCheck and timeFilter and spreadCondition;


AddOrder(OrderType.BUY_TO_OPEN, buySignal, ask, fixedSharesRange, Color.GREEN, Color.GREEN);

rec stopLossPrice = if buySignal then Lowest(low, 3) else stopLossPrice[1];

def sellSignal = close < stopLossPrice;

AddOrder(OrderType.SELL_TO_CLOSE, sellSignal, bid, openQuantity, Color.RED, Color.RED);


plot HardStopLoss = stopLossPrice;
HardStopLoss.SetPaintingStrategy(PaintingStrategy.LINE);
HardStopLoss.SetDefaultColor(Color.RED);
HardStopLoss.SetLineWeight(1);
HardStopLoss.SetStyle(Curve.SHORT_DASH);

input arrowDistancePercentage = 0.1;  # You can adjust the percentage value as needed
def currentBarRange = high - low;

plot currentBarBuySignal = if !IsNaN(close) and buySignal and !buySignal[1] then low - arrowDistancePercentage * currentBarRange else Double.NaN;
currentBarBuySignal.SetPaintingStrategy(PaintingStrategy.ARROW_UP);
currentBarBuySignal.AssignValueColor(Color.GREEN);
currentBarBuySignal.SetLineWeight(3);
 
Solution
I am new to this community and I am by no means a experienced coder. I have been working for some time to delping a stratgey that I want use to trade small cap gapping stocks whne on the uptrend each morning. I trade using the 1-min chart. What I need help with is the hard stop and (ideally) a true trailing profit.

Hard Stop
The strategy will set a hard stop but the hard stop updates everytime there is a new buy signal. I have tried everyway I know how to stop the stratgey from generating new buy signals whn there is already an open position but have not had success with that. SO the result is that the hard stop actually then becomes a moving stop going upwards and downwards. Obviously if the hard stop moves down then...
I am new to this community and I am by no means a experienced coder. I have been working for some time to delping a stratgey that I want use to trade small cap gapping stocks whne on the uptrend each morning. I trade using the 1-min chart. What I need help with is the hard stop and (ideally) a true trailing profit.

Hard Stop
The strategy will set a hard stop but the hard stop updates everytime there is a new buy signal. I have tried everyway I know how to stop the stratgey from generating new buy signals whn there is already an open position but have not had success with that. SO the result is that the hard stop actually then becomes a moving stop going upwards and downwards. Obviously if the hard stop moves down then the strategy fails to stop out at the original stop that was set when a positioned was opened resulting in a more than planed loss.

Trailing Profit
I have a profit target set forth in the strategy but I would like to use a trailing profit instead but I am having no luck getting one that works like what I would expect it to. Because the hard stop also moves upwards is serves sort of as a trailing stop but that isn't the intention. I'm sure my strategy and code will look laughable to most but I am open to and appreciate any input on my questions and also any other general advise or input is certainly welcomed as well. Thanks in advance!



thinkscript code


CSS:
input stockPrice = close;
input averageType = AverageType.WILDERS;
input allowMultiplePositions = No;

def openQuantity = GetQuantity();
def hasOpenPosition = openQuantity > 0;

# Tweakable Parameters based on stock price
def minPctDifference;
def maxSpread;
def minAvgVolume;
def fixedSharesRange;
def currentRange; # Used in Profit Target calculation
def bodyLow = if close < open then close else open;

#       Stocks under $.50
if (stockPrice < .80) {
    minPctDifference = .0005;
    currentRange = Average(high - Low,8);
    maxSpread = 0.03;
    minAvgVolume = 7000;
    fixedSharesRange = 500;
    profitTarget = 0.0; # Not Used
    stopLossPct = 0.0; # Not Used
    atrMultiplier = 0.0;# Not Used

#        Stocks $.50 - $3
} else if (stockPrice >=.80 and stockprice <= 3.0) {
    minPctDifference = .005;
    currentRange = Average(high - low,8);
    maxSpread = 0.03;
    minAvgVolume = 5000;
    fixedSharesRange = 250;
    profitTarget = 0.0; # Not Used
    stopLossPct = 0.0; # Not Used
    atrMultiplier = 0.0; # Not Used

#      Stocks $3 - $5
} else if (stockPrice >=3.0 and stockprice <= 5.0) {
    minPctDifference = .0005;
    currentRange = Average(high - low, 8);
    maxSpread = 0.03;
    minAvgVolume = 7000;
    fixedSharesRange = 100;
    profitTarget = 0.0; # Not Used
    stopLossPct = .00; # Not Used
    atrMultiplier = 0.0; # Not Used

#          Stocks $5 - $9
#        <5             10-25       25-50     >100
# PT  .005/.005      .0005/.005     .05        .05 
# SL  .0005/.0005    .003/.005      .0005      .0005
# MP  .005/.0005     .0005/.0005    .005       .005

} else if (stockPrice >= 5.0 and stockPrice <= 9.0) {
    minPctDifference = .05;
    currentRange = Average(high - low, 6);
    maxSpread = 0.05;
    minAvgVolume = 7000;
    fixedSharesRange = 100;
    profitTarget = 0.0; # Not Used
    stopLossPct = 0.0; # Not Used
    atrMultiplier = 0.0; # Not Used

#          Stocks >$9
#     <5             10-25          25-50       >100 (increase spreads= more trades)
# PT                                            .05/.05
# SL                                            .005/.005
# MP                                            .0005/.05

} else {
    minPctDifference = .0005;
    currentRange = Average(high - low, 8);
    maxSpread = 0.5;
    minAvgVolume = 7000;
    fixedSharesRange = 100;
    profitTarget = 0.0; # Not Used
    stopLossPct = 0.0; # Not Used
    atrMultiplier = 0.0; # Not Used
}

# Parameters changed less frequently
input timeFilterHour = 645;
input lookbackPeriod = 3; # Used in double bottom detection & HardStop
input volumeAvgPeriod = 3;

# Bid, Ask, and Spread
def bid = close(priceType = PriceType.BID);
def ask = close(priceType = PriceType.ASK);
def spread = ask - bid;
def spreadCondition = spread <= maxSpread;

# Double Bottom and Volume Check
def doubleBottom = low >= Lowest(low, lookbackPeriod)[-1] and (low - Lowest(low, lookbackPeriod)[-1]) / Lowest(low, lookbackPeriod)[-1] <= minPctDifference;
def volumeCheck = Average(volume, volumeAvgPeriod) >= minAvgVolume;

# Time Filter
def timeFilter = SecondsFromTime(timeFilterHour) >= 0;

# Buy Signal
def buySignal = (allowMultiplePositions or !hasOpenPosition) and doubleBottom and volumeCheck and timeFilter and spreadCondition;


AddOrder(OrderType.BUY_TO_OPEN, buySignal, ask, fixedSharesRange, Color.GREEN, Color.GREEN);

rec stopLossPrice = if buySignal then Lowest(low, 3) else stopLossPrice[1];

def sellSignal = close < stopLossPrice;

AddOrder(OrderType.SELL_TO_CLOSE, sellSignal, bid, openQuantity, Color.RED, Color.RED);


plot HardStopLoss = stopLossPrice;
HardStopLoss.SetPaintingStrategy(PaintingStrategy.LINE);
HardStopLoss.SetDefaultColor(Color.RED);
HardStopLoss.SetLineWeight(1);
HardStopLoss.SetStyle(Curve.SHORT_DASH);

input arrowDistancePercentage = 0.1;  # You can adjust the percentage value as needed
def currentBarRange = high - low;

plot currentBarBuySignal = if !IsNaN(close) and buySignal and !buySignal[1] then low - arrowDistancePercentage * currentBarRange else Double.NaN;
currentBarBuySignal.SetPaintingStrategy(PaintingStrategy.ARROW_UP);
currentBarBuySignal.AssignValueColor(Color.GREEN);
currentBarBuySignal.SetLineWeight(3);


take a look at this as an example of adjusting target and stop levels
https://usethinkscript.com/threads/...-certain-price-is-breached.14635/#post-124118


when things aren't working out, simplify it as much as possible. get it working. then add features back in.
..instead of trying to get this to work with multiple price ranges, just work with price (all prices)
..use close instead of bid, ask
..use terms most people use to avoid confusion. i've never heard trailing profit before. trailing infers , coming from behind, lower than. maybe adjusting target level instead?

try to create a formula that is true during a trade.
then execute a buy when the transition happens from false to true. (repeated buy inputs will be ignored)

long_trade = if a buy signal set it to true. if a sell signal then set to false.
carry out a buy only when previous bar of long_trade is false and current bar is true
 
Solution

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
458 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