Page 1 of 1

Buying if percentage of yesterdays range is hit...

Posted: Tue Aug 23, 2022 7:49 am
by elastic
Hi,

I have a simple thesis here -

-calculate the previous days range : High minus the close
-if todays bar exceeds a certain percentage of that range then open long during the day at that point
-Stop loss is to be 50% of that range from entry
-Exit/take profit is first profitable daily open after entry

Here is my strategy, but I'm just a touch off somewhere, was wondering if someone more experienced may know why its not calculating as per my thesis?

Thank you for any help and advice, it's much appreciated.

Code: Select all

  // This source code is subject to the terms of the Mozilla Public License 2.0 at    https://mozilla.org/MPL/2.0/
    // © elasticc

    //@version=5
    strategy("LStrat1",
     initial_capital=4000, 
     default_qty_type=strategy.percent_of_equity, 
     default_qty_value=100,
     overlay=true, 
     use_bar_magnifier=true)

    // Get Inputs

    i_percentRange  = input.int(title="Percentage of Previous Days Range", defval=100)  // This changes the percentage amount of yesterdays range for a buy trigger, default should be 100%
    i_stopPercent   = input.float(title="Stop Loss Percentage", defval=0.5) // Change stop loss percentage of previous days range, default 50%
    i_startTime     = input.time(title="Start Filter", defval=timestamp("01 Jan 1995 13:30 +0000"))
    i_endTime       = input.time(title="End Filter", defval=timestamp("1 Jan 2099 19:30 +0000"))

    // Date Filter

    f_dateFilter    = time >= i_startTime and time <= i_endTime

    // Calculate Data

    Range      = high - close
    percentofRange  = (i_percentRange / 100) * Range[1]

    // Buy Conditions

    var float buyPrice = 0
    buyCondition    = close > percentofRange[1] and strategy.position_size == 0 and f_dateFilter

    // Stop loss Condition, sell condition

    stopPrice       = strategy.position_size > 0 ? buyPrice - (buyPrice * i_stopPercent) : na
    stopDistance    = strategy.position_size > 0 ? buyPrice - i_stopPercent : na
    stopCondition   = strategy.position_size > 0 and stopDistance > i_stopPercent

    sellCondition   = // exit at first profitable daily opening after entry, not sure how to say this?

    // enter Trade

    if buyCondition
    strategy.entry(id="Long", direction=strategy.long)

    
    // Exit trade

    if stopCondition
    strategy.close(id="Long", comment="Stop Loss")
    
    // Plot

    plot(Range, color=color.blue, title="Range")
    plot(percentofRange, color=color.purple, title="Percentage Of Range")
    plot(buyPrice, color=color.green, style=plot.style_linebr)
    plot(stopPrice, color=color.red, style=plot.style_linebr)