Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Moving stop to break even after being in profit a set number of ticks

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

    Moving stop to break even after being in profit a set number of ticks

    Hi
    I'm pretty close in the following but at a loss why the strategy is acting as follows

    here is the premise of this strategy

    When I switch from a green bar to a red bar (or vice versa) signifying change in direction and I have 2 bars in a row, the strategy enters an order at the close of the second up or down bar. It does this perfectly.

    Once I am in profit x ticks (based on inputs) I want the SL to move to break even. Unfortunately it does this once but every time price moves ourside of the ticks profit it keeps moving the SL and doesn't keep it at breakeven.

    Here is the code I have. Any help would be appreciated as I'm a newbie to this and can't seem to find why

    Thanks,


    amespace NinjaTrader.NinjaScript.Strategies
    {
    public class RenkoStrategyScalper : Strategy
    {
    private bool GotBar;


    protected override void OnStateChange()
    {
    if (State == State.SetDefaults)
    {
    Description = @"Enter the description for your new custom Strategy here.";
    Name = "RenkoStrategyScalper";
    Calculate = Calculate.OnEachTick;
    EntriesPerDirection = 2;
    EntryHandling = EntryHandling.AllEntries;
    IsExitOnSessionCloseStrategy = true;
    ExitOnSessionCloseSeconds = 30;
    IsFillLimitOnTouch = false;
    MaximumBarsLookBack = MaximumBarsLookBack.TwoHundredFiftySix;
    OrderFillResolution = OrderFillResolution.Standard;
    Slippage = 0;
    StartBehavior = StartBehavior.WaitUntilFlat;
    TimeInForce = TimeInForce.Gtc;
    TraceOrders = false;
    RealtimeErrorHandling = RealtimeErrorHandling.StopCancelClose;
    StopTargetHandling = StopTargetHandling.PerEntryExecution;
    BarsRequiredToTrade = 20;
    // Disable this property for performance gains in Strategy Analyzer optimizations
    // See the Help Guide for additional information
    IsInstantiatedOnEachOptimizationIteration = true;
    Contracts = 1;
    Target1 = 10;
    Stop = 10;
    Target2 = 20;
    Contracts2 = 1;
    Breakeven = 10;
    GotBar = false;
    }
    else if (State == State.Configure)
    {
    SetProfitTarget(@"First", CalculationMode.Ticks, Target1);
    SetStopLoss("", CalculationMode.Ticks, Stop, false);
    }
    }

    protected override void OnBarUpdate()
    {
    if (BarsInProgress != 0)
    return;

    if (CurrentBars[0] < 2)
    return;

    // Set 1
    if ((Close[0] > Open[0])
    && (Close[1] < Open[1]))
    {
    GotBar = true;
    }

    // Set 2
    if ((Close[0] > Open[1])
    && (GotBar == true)
    && (Close[1] > Close[2]))
    {
    GotBar = false;
    BarBrush = Brushes.Lime;
    SetStopLoss("", CalculationMode.Ticks, Stop, false);
    EnterLong(Convert.ToInt32(Contracts2), second);
    EnterLong(Convert.ToInt32(Contracts), First);
    }

    // Set 3
    if ((Close[0] < Open[0])
    && (Close[1] > Open[1]))
    {
    GotBar = true;
    }

    // Set 4
    if ((Close[0] < Open[1])
    && (GotBar == true)
    && (Close[1] < Close[2]))
    {
    GotBar = false;
    BarBrush = Brushes.Red;
    SetStopLoss("", CalculationMode.Ticks, Stop, false);
    EnterShort(Convert.ToInt32(Contracts2), second);
    EnterShort(Convert.ToInt32(Contracts), First);
    }

    // Set 5
    if ((Position.MarketPosition == MarketPosition.Long)
    && (Position.GetUnrealizedProfitLoss(PerformanceUnit. Ticks, Close[0]) == Breakeven))
    {
    BackBrush = Brushes.CornflowerBlue;
    Draw.Dot(this, @"RenkoBarScalper Dot_1", false, 0, Position.AveragePrice, Brushes.White);
    SetStopLoss("", CalculationMode.Price, Position.AveragePrice, false);
    }

    // Set 6
    if ((Position.MarketPosition == MarketPosition.Short)
    && (Position.GetUnrealizedProfitLoss(PerformanceUnit. Ticks, Close[0]) == Breakeven))
    {
    BackBrush = Brushes.CornflowerBlue;
    Draw.Dot(this, @"RenkoBarScalper Dot_1", false, 0, Position.AveragePrice, Brushes.White);
    SetStopLoss("", CalculationMode.Price, Position.AveragePrice, false);
    }

    }

    region Properties
    [NinjaScriptProperty]
    [Range(1, int.MaxValue)]
    [Display(Name="Contracts", Description="Number of Contracts", Order=1, GroupName="Parameters")]
    public int Contracts
    { get; set; }

    [NinjaScriptProperty]
    [Range(1, int.MaxValue)]
    [Display(Name="Target1", Description="Profit Target 1", Order=2, GroupName="Parameters")]
    public int Target1
    { get; set; }

    [NinjaScriptProperty]
    [Range(1, int.MaxValue)]
    [Display(Name="Stop", Description="Stop Loss", Order=3, GroupName="Parameters")]
    public int Stop
    { get; set; }

    [NinjaScriptProperty]
    [Range(1, int.MaxValue)]
    [Display(Name="Target2", Description="Profit Target 2", Order=4, GroupName="Parameters")]
    public int Target2
    { get; set; }

    [NinjaScriptProperty]
    [Range(1, int.MaxValue)]
    [Display(Name="Contracts2", Description="Number of Contracts Position 2", Order=5, GroupName="Parameters")]
    public int Contracts2
    { get; set; }

    [NinjaScriptProperty]
    [Range(1, int.MaxValue)]
    [Display(Name="Breakeven", Description="Move to Breakeven when in profits", Order=6, GroupName="Parameters")]
    public int Breakeven
    { get; set; }
    #endregion

    }
    }



    #2
    Hello nqfundedtrader,

    As a tip, to export a NinjaTrader 8 NinjaScript so this can be shared and imported by the recipient do the following:
    1. Click Tools -> Export -> NinjaScript...
    2. Click the 'add' link -> check the box(es) for the script(s) and reference(s) you want to include
    3. Click the 'Export' button
    4. Enter a unique name for the file in the value for 'File name:'
    5. Choose a save location -> click Save
    6. Click OK to clear the export location message
    By default your exported file will be in the following location:
    • (My) Documents/NinjaTrader 8/bin/Custom/ExportNinjaScript/<export_file_name.zip>
    Below is a link to the help guide on Exporting NinjaScripts.
    http://ninjatrader.com/support/helpG...-us/export.htm

    Then you can attach your export as an attachment to your post or to an email.

    If there are a few specific lines of code you would like focus on, I encourage you to add just those few lines to a code block in a post.


    Below I am providing a link to working example scripts you can learn from that demonstrate a break even in the Strategy Builder.

    As well as an unlocked more complex version.


    Regarding your specific code, debug the script by using Print() and TraceOrders to understand the behavior.


    Print the time of the bar and all values used in the conditions that trigger the action in question.
    Is the condition evaluating as true?
    Print the price you supplying to the order.
    Is this the price you expect?
    Chelsea B.NinjaTrader Customer Service

    Comment


      #3
      Ok I have exported and attached the code as shown.

      Goal of script

      1) Wait until trend shifts and I have a bar in the opposite direction
      2) Once condition above has been met, wait for 2 bars to form in the new direction
      3) Place and order at the close of the 2nd bar in the new direction
      4) Once first target has been hit, move stop loss to break even and leave remaining position as a runner

      Code is attached. Any guidance would be helpful. Thanks

      If you could look at the code I have attached an point me in the right direction that would be helpful. I'm close to abandoning this project because I clearly don't understand what I'm doing

      Thanks,
      Tony
      Attached Files

      Comment


        #4
        Hello nqfundedtrader,

        Start by adding variables for the current trigger price and current stop price as demonstrated in the TrailBuilderExample.
        Optionally add inputs for the TrailFrequency and TrailStopDistance. (The alternative would be using number values instead of inputs)

        In the first condition set, when flat set the current stop price to 0 to reset.

        In the second condition set, also when flat, and when the condition to enter the position is true, set the trigger price to the market price offset with Ticks with the number of ticks ahead where the next trailing action will occur (I use TrailFrequency for this). Set the stop price to the market price offset with the trail stop distance in Ticks.

        In the third condition set, when the position is taken, check if the market price has reached the trigger price. If yes, set the new trigger price and the new stop price.

        In the forth condition set, check if the stop price is not 0, and if so, submit the order using the stop price variable (set to the trailing price).


        You can also contact a professional NinjaScript Consultant who would be eager to create or modify this script at your request or assist you with your script. The NinjaTrader Ecosystem has affiliate contacts who provide educational as well as consulting services. Please let me know if you would like our NinjaTrader Ecosystem team follow up with you with a list of affiliate consultants who would be happy to create this script or any others at your request or provide one on one educational services.
        Chelsea B.NinjaTrader Customer Service

        Comment


          #5
          Hi Chelsea

          would love to have a consultant reach out to me. It would probably be better and I can learn at the same time

          please Let me know how I can work with them

          thanks
          tony

          Comment


            #6
            Hello,

            Thank you for your post.

            You can search our list of NinjaScript consultants through the link below. Simply enter a consultant name or search by using our filter categories. Once you have identified your consultants of choice, please visit each consultant's site for more information or contact them directly to learn more:
            You can locate the contact information for the consultants on their direct websites for any additional questions you may have. Since these consultants are third-party services for NinjaTrader, all pricing and support information will need to be obtained through the consultant.

            The NinjaTrader Ecosystem website is for educational and informational purposes only and should not be considered a solicitation to buy or sell a futures contract or make any other type of investment decision. The companies and services listed on this website are not to be considered a recommendation and it is the reader's responsibility to evaluate any product, service, or company. NinjaTrader Ecosystem, LLC is not responsible for the accuracy or content of any product, service or company linked to on this website.

            Let me know if I may be of further assistance.
            Thomas C.NinjaTrader Customer Service

            Comment

            Latest Posts

            Collapse

            Topics Statistics Last Post
            Started by inanazsocial, Today, 01:15 AM
            0 responses
            2 views
            0 likes
            Last Post inanazsocial  
            Started by trilliantrader, 04-18-2024, 08:16 AM
            5 responses
            22 views
            0 likes
            Last Post trilliantrader  
            Started by Davidtowleii, Today, 12:15 AM
            0 responses
            3 views
            0 likes
            Last Post Davidtowleii  
            Started by guillembm, Yesterday, 11:25 AM
            2 responses
            10 views
            0 likes
            Last Post guillembm  
            Started by junkone, 04-21-2024, 07:17 AM
            9 responses
            71 views
            0 likes
            Last Post jeronymite  
            Working...
            X